diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-1x1x5.dat b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-1x1x5.dat new file mode 100644 index 0000000000000000000000000000000000000000..3d3f27f88eef4e02451d18204cdcfd51f96f6d15 Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-1x1x5.dat differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-1x1x7.dat b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-1x1x7.dat new file mode 100644 index 0000000000000000000000000000000000000000..0bd683096f18eadceb7168f811c75bf072baecfe Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-1x1x7.dat differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-1x3x5.dat b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-1x3x5.dat new file mode 100644 index 0000000000000000000000000000000000000000..25269ff9ea4f6dd3f8a9ca0c8ad27d399e4248f5 Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-1x3x5.dat differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-11x1x10.dat b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-11x1x10.dat new file mode 100644 index 0000000000000000000000000000000000000000..9850de37cf86af622b759625c15e6b1a9477ce47 Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-11x1x10.dat differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-15x10x22.dat b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-15x10x22.dat new file mode 100644 index 0000000000000000000000000000000000000000..98c09c2dff6e1ef605e25ed1d00afe94597abddc Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-15x10x22.dat differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x1x1.dat b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x1x1.dat new file mode 100644 index 0000000000000000000000000000000000000000..959098d2a9cdd6140758843e059d4ca529b14279 Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x1x1.dat differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x1x5.dat b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x1x5.dat new file mode 100644 index 0000000000000000000000000000000000000000..49c0ec1d18d9f08111fe2d2a269ed407da71b158 Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x1x5.dat differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x1x7.dat b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x1x7.dat new file mode 100644 index 0000000000000000000000000000000000000000..bb936b8789920ce18281fa754a5c048b31e59ba8 Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x1x7.dat differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x3x5.dat b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x3x5.dat new file mode 100644 index 0000000000000000000000000000000000000000..cb3e9e4876249f42924a43232b74f05b91123815 Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x3x5.dat differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/invalid_pointer.sav b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/invalid_pointer.sav new file mode 100644 index 0000000000000000000000000000000000000000..d53893c6c734e6c7771e08042c16874623dc6f0e Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/invalid_pointer.sav differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/null_pointer.sav b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/null_pointer.sav new file mode 100644 index 0000000000000000000000000000000000000000..8cee5ebecc3bef248ed37c438e0731160b31a310 Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/null_pointer.sav differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_byte.sav b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_byte.sav new file mode 100644 index 0000000000000000000000000000000000000000..e4027b3cf302b8610b87d9ef8b0aac39d5a40ef9 Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_byte.sav differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_byte_descr.sav b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_byte_descr.sav new file mode 100644 index 0000000000000000000000000000000000000000..182e29bc57dc05154388553a71876820025bca8d Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_byte_descr.sav differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_complex32.sav b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_complex32.sav new file mode 100644 index 0000000000000000000000000000000000000000..593e8c6208ab0bf3aa869de89e213b8aa9f8c071 Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_complex32.sav differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_complex64.sav b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_complex64.sav new file mode 100644 index 0000000000000000000000000000000000000000..edb19d388afbaff44e5f0883978e6a74e9755613 Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_complex64.sav differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_float32.sav b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_float32.sav new file mode 100644 index 0000000000000000000000000000000000000000..be9e3877ea845da76d9466c14d70c4cce882368c Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_float32.sav differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_float64.sav b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_float64.sav new file mode 100644 index 0000000000000000000000000000000000000000..9680b2878c6008a27c8fc9ae6966903ff936cc4a Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_float64.sav differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_heap_pointer.sav b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_heap_pointer.sav new file mode 100644 index 0000000000000000000000000000000000000000..d02b1756ac043a4ba6119acb28ef34c40359a4dd Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_heap_pointer.sav differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_int16.sav b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_int16.sav new file mode 100644 index 0000000000000000000000000000000000000000..603525694cc307d47412717c4c2f85ddc960897b Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_int16.sav differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_int32.sav b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_int32.sav new file mode 100644 index 0000000000000000000000000000000000000000..40210b889402c0f27562296ab39ce1a714f0d0ef Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_int32.sav differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_int64.sav b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_int64.sav new file mode 100644 index 0000000000000000000000000000000000000000..c91cd0a561e011a2f18c86119e45392fbc0be825 Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_int64.sav differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_string.sav b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_string.sav new file mode 100644 index 0000000000000000000000000000000000000000..ee6e69fe8461edfa580f682761118c8afe2add3a Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_string.sav differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_uint16.sav b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_uint16.sav new file mode 100644 index 0000000000000000000000000000000000000000..759c2e64fa034c6ddbdbe6181efae1e699a0c314 Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_uint16.sav differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_uint32.sav b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_uint32.sav new file mode 100644 index 0000000000000000000000000000000000000000..74dec7b8933418d30d17c83d617443a73ceef0c6 Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_uint32.sav differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_uint64.sav b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_uint64.sav new file mode 100644 index 0000000000000000000000000000000000000000..fc9da5796eab6ce9fb59488b836ba2f567de7b25 Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/scalar_uint64.sav differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_arrays.sav b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_arrays.sav new file mode 100644 index 0000000000000000000000000000000000000000..40c9cd330e0c731968d71dbbfeae9bd8c4a745a2 Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_arrays.sav differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_arrays_byte_idl80.sav b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_arrays_byte_idl80.sav new file mode 100644 index 0000000000000000000000000000000000000000..f1aa416f8e661893be282a490005536953d4b7af Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_arrays_byte_idl80.sav differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_arrays_replicated.sav b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_arrays_replicated.sav new file mode 100644 index 0000000000000000000000000000000000000000..6f01fbfd109e76c94b6e6e9bfd9eb388f39d99ee Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_arrays_replicated.sav differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_arrays_replicated_3d.sav b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_arrays_replicated_3d.sav new file mode 100644 index 0000000000000000000000000000000000000000..bac9b207488eb9712ec27fb3567155f0dd773f34 Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_arrays_replicated_3d.sav differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_inherit.sav b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_inherit.sav new file mode 100644 index 0000000000000000000000000000000000000000..8babd56306f09fa612f731ce593ae13c75f84f4c Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_inherit.sav differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointer_arrays.sav b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointer_arrays.sav new file mode 100644 index 0000000000000000000000000000000000000000..a3c678162911426702a9a6e932761385a01f247e Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointer_arrays.sav differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointer_arrays_replicated.sav b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointer_arrays_replicated.sav new file mode 100644 index 0000000000000000000000000000000000000000..38b812261125e6aabef8618955b234f6c7b04955 Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointer_arrays_replicated.sav differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointer_arrays_replicated_3d.sav b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointer_arrays_replicated_3d.sav new file mode 100644 index 0000000000000000000000000000000000000000..db1c256c85a707f0a0d78c28241b78d1eddcab1e Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointer_arrays_replicated_3d.sav differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointers.sav b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointers.sav new file mode 100644 index 0000000000000000000000000000000000000000..acbb058a307090f6c9e2d8402c7badf6bb48144c Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointers.sav differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointers_replicated.sav b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointers_replicated.sav new file mode 100644 index 0000000000000000000000000000000000000000..d16f4655cc20318db2b0d629cd5ed6d7be01b518 Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointers_replicated.sav differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointers_replicated_3d.sav b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointers_replicated_3d.sav new file mode 100644 index 0000000000000000000000000000000000000000..732dd2cbfa9c7fd029bb59b4cfcb630cc1077f54 Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointers_replicated_3d.sav differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_scalars.sav b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_scalars.sav new file mode 100644 index 0000000000000000000000000000000000000000..69d7eaf4ecf8747c21d07e14edcf65b4e394974c Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_scalars.sav differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_scalars_replicated.sav b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_scalars_replicated.sav new file mode 100644 index 0000000000000000000000000000000000000000..2222391ae5b93ba34c1fdb982c02eb97d9658b58 Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_scalars_replicated.sav differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_scalars_replicated_3d.sav b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_scalars_replicated_3d.sav new file mode 100644 index 0000000000000000000000000000000000000000..a35f1acfb4cb93ecb637310bbfa7fc1a2151d483 Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/struct_scalars_replicated_3d.sav differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/various_compressed.sav b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/various_compressed.sav new file mode 100644 index 0000000000000000000000000000000000000000..dcdb0b0d433939d6a240c86e5060214cd8875732 Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/io/tests/data/various_compressed.sav differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/__init__.pxd b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/__init__.pxd new file mode 100644 index 0000000000000000000000000000000000000000..c7c49f9ad8f4c90ee93725fdcdbe73c2e7f5aacd --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/__init__.pxd @@ -0,0 +1 @@ +from scipy.linalg cimport cython_blas, cython_lapack diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9381d7a02c15a3234f38ee4bdee5d12d11d4afd1 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/__init__.py @@ -0,0 +1,236 @@ +""" +==================================== +Linear algebra (:mod:`scipy.linalg`) +==================================== + +.. currentmodule:: scipy.linalg + +.. toctree:: + :hidden: + + linalg.blas + linalg.cython_blas + linalg.cython_lapack + linalg.interpolative + linalg.lapack + +Linear algebra functions. + +.. eventually, we should replace the numpy.linalg HTML link with just `numpy.linalg` + +.. seealso:: + + `numpy.linalg `__ + for more linear algebra functions. Note that + although `scipy.linalg` imports most of them, identically named + functions from `scipy.linalg` may offer more or slightly differing + functionality. + + +Basics +====== + +.. autosummary:: + :toctree: generated/ + + inv - Find the inverse of a square matrix + solve - Solve a linear system of equations + solve_banded - Solve a banded linear system + solveh_banded - Solve a Hermitian or symmetric banded system + solve_circulant - Solve a circulant system + solve_triangular - Solve a triangular matrix + solve_toeplitz - Solve a toeplitz matrix + matmul_toeplitz - Multiply a Toeplitz matrix with an array. + det - Find the determinant of a square matrix + norm - Matrix and vector norm + lstsq - Solve a linear least-squares problem + pinv - Pseudo-inverse (Moore-Penrose) using lstsq + pinvh - Pseudo-inverse of hermitian matrix + kron - Kronecker product of two arrays + khatri_rao - Khatri-Rao product of two arrays + orthogonal_procrustes - Solve an orthogonal Procrustes problem + matrix_balance - Balance matrix entries with a similarity transformation + subspace_angles - Compute the subspace angles between two matrices + bandwidth - Return the lower and upper bandwidth of an array + issymmetric - Check if a square 2D array is symmetric + ishermitian - Check if a square 2D array is Hermitian + LinAlgError + LinAlgWarning + +Eigenvalue Problems +=================== + +.. autosummary:: + :toctree: generated/ + + eig - Find the eigenvalues and eigenvectors of a square matrix + eigvals - Find just the eigenvalues of a square matrix + eigh - Find the e-vals and e-vectors of a Hermitian or symmetric matrix + eigvalsh - Find just the eigenvalues of a Hermitian or symmetric matrix + eig_banded - Find the eigenvalues and eigenvectors of a banded matrix + eigvals_banded - Find just the eigenvalues of a banded matrix + eigh_tridiagonal - Find the eigenvalues and eigenvectors of a tridiagonal matrix + eigvalsh_tridiagonal - Find just the eigenvalues of a tridiagonal matrix + +Decompositions +============== + +.. autosummary:: + :toctree: generated/ + + lu - LU decomposition of a matrix + lu_factor - LU decomposition returning unordered matrix and pivots + lu_solve - Solve Ax=b using back substitution with output of lu_factor + svd - Singular value decomposition of a matrix + svdvals - Singular values of a matrix + diagsvd - Construct matrix of singular values from output of svd + orth - Construct orthonormal basis for the range of A using svd + null_space - Construct orthonormal basis for the null space of A using svd + ldl - LDL.T decomposition of a Hermitian or a symmetric matrix. + cholesky - Cholesky decomposition of a matrix + cholesky_banded - Cholesky decomp. of a sym. or Hermitian banded matrix + cho_factor - Cholesky decomposition for use in solving a linear system + cho_solve - Solve previously factored linear system + cho_solve_banded - Solve previously factored banded linear system + polar - Compute the polar decomposition. + qr - QR decomposition of a matrix + qr_multiply - QR decomposition and multiplication by Q + qr_update - Rank k QR update + qr_delete - QR downdate on row or column deletion + qr_insert - QR update on row or column insertion + rq - RQ decomposition of a matrix + qz - QZ decomposition of a pair of matrices + ordqz - QZ decomposition of a pair of matrices with reordering + schur - Schur decomposition of a matrix + rsf2csf - Real to complex Schur form + hessenberg - Hessenberg form of a matrix + cdf2rdf - Complex diagonal form to real diagonal block form + cossin - Cosine sine decomposition of a unitary or orthogonal matrix + +.. seealso:: + + `scipy.linalg.interpolative` -- Interpolative matrix decompositions + + +Matrix Functions +================ + +.. autosummary:: + :toctree: generated/ + + expm - Matrix exponential + logm - Matrix logarithm + cosm - Matrix cosine + sinm - Matrix sine + tanm - Matrix tangent + coshm - Matrix hyperbolic cosine + sinhm - Matrix hyperbolic sine + tanhm - Matrix hyperbolic tangent + signm - Matrix sign + sqrtm - Matrix square root + funm - Evaluating an arbitrary matrix function + expm_frechet - Frechet derivative of the matrix exponential + expm_cond - Relative condition number of expm in the Frobenius norm + fractional_matrix_power - Fractional matrix power + + +Matrix Equation Solvers +======================= + +.. autosummary:: + :toctree: generated/ + + solve_sylvester - Solve the Sylvester matrix equation + solve_continuous_are - Solve the continuous-time algebraic Riccati equation + solve_discrete_are - Solve the discrete-time algebraic Riccati equation + solve_continuous_lyapunov - Solve the continuous-time Lyapunov equation + solve_discrete_lyapunov - Solve the discrete-time Lyapunov equation + + +Sketches and Random Projections +=============================== + +.. autosummary:: + :toctree: generated/ + + clarkson_woodruff_transform - Applies the Clarkson Woodruff Sketch (a.k.a CountMin Sketch) + +Special Matrices +================ + +.. autosummary:: + :toctree: generated/ + + block_diag - Construct a block diagonal matrix from submatrices + circulant - Circulant matrix + companion - Companion matrix + convolution_matrix - Convolution matrix + dft - Discrete Fourier transform matrix + fiedler - Fiedler matrix + fiedler_companion - Fiedler companion matrix + hadamard - Hadamard matrix of order 2**n + hankel - Hankel matrix + helmert - Helmert matrix + hilbert - Hilbert matrix + invhilbert - Inverse Hilbert matrix + leslie - Leslie matrix + pascal - Pascal matrix + invpascal - Inverse Pascal matrix + toeplitz - Toeplitz matrix + +Low-level routines +================== + +.. autosummary:: + :toctree: generated/ + + get_blas_funcs + get_lapack_funcs + find_best_blas_type + +.. seealso:: + + `scipy.linalg.blas` -- Low-level BLAS functions + + `scipy.linalg.lapack` -- Low-level LAPACK functions + + `scipy.linalg.cython_blas` -- Low-level BLAS functions for Cython + + `scipy.linalg.cython_lapack` -- Low-level LAPACK functions for Cython + +""" # noqa: E501 + +from ._misc import * +from ._cythonized_array_utils import * +from ._basic import * +from ._decomp import * +from ._decomp_lu import * +from ._decomp_ldl import * +from ._decomp_cholesky import * +from ._decomp_qr import * +from ._decomp_qz import * +from ._decomp_svd import * +from ._decomp_schur import * +from ._decomp_polar import * +from ._matfuncs import * +from .blas import * +from .lapack import * +from ._special_matrices import * +from ._solvers import * +from ._procrustes import * +from ._decomp_update import * +from ._sketches import * +from ._decomp_cossin import * + +# Deprecated namespaces, to be removed in v2.0.0 +from . import ( + decomp, decomp_cholesky, decomp_lu, decomp_qr, decomp_svd, decomp_schur, + basic, misc, special_matrices, matfuncs, +) + +__all__ = [s for s in dir() if not s.startswith('_')] + + +from scipy._lib._testutils import PytestTester +test = PytestTester(__name__) +del PytestTester diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_basic.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..70841fa80976c62ed7d894d824fdfbbcb4673273 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_basic.py @@ -0,0 +1,2119 @@ +# +# Author: Pearu Peterson, March 2002 +# +# w/ additions by Travis Oliphant, March 2002 +# and Jake Vanderplas, August 2012 + +import warnings +from warnings import warn +from itertools import product +import numpy as np +from numpy import atleast_1d, atleast_2d +from .lapack import get_lapack_funcs, _compute_lwork +from ._misc import LinAlgError, _datacopied, LinAlgWarning +from ._decomp import _asarray_validated +from . import _decomp, _decomp_svd +from ._solve_toeplitz import levinson +from ._cythonized_array_utils import (find_det_from_lu, bandwidth, issymmetric, + ishermitian) + +__all__ = ['solve', 'solve_triangular', 'solveh_banded', 'solve_banded', + 'solve_toeplitz', 'solve_circulant', 'inv', 'det', 'lstsq', + 'pinv', 'pinvh', 'matrix_balance', 'matmul_toeplitz'] + + +# The numpy facilities for type-casting checks are too slow for small sized +# arrays and eat away the time budget for the checkups. Here we set a +# precomputed dict container of the numpy.can_cast() table. + +# It can be used to determine quickly what a dtype can be cast to LAPACK +# compatible types, i.e., 'float32, float64, complex64, complex128'. +# Then it can be checked via "casting_dict[arr.dtype.char]" +lapack_cast_dict = {x: ''.join([y for y in 'fdFD' if np.can_cast(x, y)]) + for x in np.typecodes['All']} + + +# Linear equations +def _solve_check(n, info, lamch=None, rcond=None): + """ Check arguments during the different steps of the solution phase """ + if info < 0: + raise ValueError(f'LAPACK reported an illegal value in {-info}-th argument.') + elif 0 < info: + raise LinAlgError('Matrix is singular.') + + if lamch is None: + return + E = lamch('E') + if rcond < E: + warn(f'Ill-conditioned matrix (rcond={rcond:.6g}): ' + 'result may not be accurate.', + LinAlgWarning, stacklevel=3) + + +def _find_matrix_structure(a): + n = a.shape[0] + n_below, n_above = bandwidth(a) + + if n_below == n_above == 0: + kind = 'diagonal' + elif n_above == 0: + kind = 'lower triangular' + elif n_below == 0: + kind = 'upper triangular' + elif n_above <= 1 and n_below <= 1 and n > 3: + kind = 'tridiagonal' + elif np.issubdtype(a.dtype, np.complexfloating) and ishermitian(a): + kind = 'hermitian' + elif issymmetric(a): + kind = 'symmetric' + else: + kind = 'general' + + return kind, n_below, n_above + + +def solve(a, b, lower=False, overwrite_a=False, + overwrite_b=False, check_finite=True, assume_a=None, + transposed=False): + """ + Solves the linear equation set ``a @ x == b`` for the unknown ``x`` + for square `a` matrix. + + If the data matrix is known to be a particular type then supplying the + corresponding string to ``assume_a`` key chooses the dedicated solver. + The available options are + + =================== ================================ + diagonal 'diagonal' + tridiagonal 'tridiagonal' + banded 'banded' + upper triangular 'upper triangular' + lower triangular 'lower triangular' + symmetric 'symmetric' (or 'sym') + hermitian 'hermitian' (or 'her') + positive definite 'positive definite' (or 'pos') + general 'general' (or 'gen') + =================== ================================ + + Parameters + ---------- + a : (N, N) array_like + Square input data + b : (N, NRHS) array_like + Input data for the right hand side. + lower : bool, default: False + Ignored unless ``assume_a`` is one of ``'sym'``, ``'her'``, or ``'pos'``. + If True, the calculation uses only the data in the lower triangle of `a`; + entries above the diagonal are ignored. If False (default), the + calculation uses only the data in the upper triangle of `a`; entries + below the diagonal are ignored. + overwrite_a : bool, default: False + Allow overwriting data in `a` (may enhance performance). + overwrite_b : bool, default: False + Allow overwriting data in `b` (may enhance performance). + check_finite : bool, default: True + Whether to check that the input matrices contain only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + assume_a : str, optional + Valid entries are described above. + If omitted or ``None``, checks are performed to identify structure so the + appropriate solver can be called. + transposed : bool, default: False + If True, solve ``a.T @ x == b``. Raises `NotImplementedError` + for complex `a`. + + Returns + ------- + x : (N, NRHS) ndarray + The solution array. + + Raises + ------ + ValueError + If size mismatches detected or input a is not square. + LinAlgError + If the matrix is singular. + LinAlgWarning + If an ill-conditioned input a is detected. + NotImplementedError + If transposed is True and input a is a complex matrix. + + Notes + ----- + If the input b matrix is a 1-D array with N elements, when supplied + together with an NxN input a, it is assumed as a valid column vector + despite the apparent size mismatch. This is compatible with the + numpy.dot() behavior and the returned result is still 1-D array. + + The general, symmetric, Hermitian and positive definite solutions are + obtained via calling ?GESV, ?SYSV, ?HESV, and ?POSV routines of + LAPACK respectively. + + The datatype of the arrays define which solver is called regardless + of the values. In other words, even when the complex array entries have + precisely zero imaginary parts, the complex solver will be called based + on the data type of the array. + + Examples + -------- + Given `a` and `b`, solve for `x`: + + >>> import numpy as np + >>> a = np.array([[3, 2, 0], [1, -1, 0], [0, 5, 1]]) + >>> b = np.array([2, 4, -1]) + >>> from scipy import linalg + >>> x = linalg.solve(a, b) + >>> x + array([ 2., -2., 9.]) + >>> np.dot(a, x) == b + array([ True, True, True], dtype=bool) + + """ + # Flags for 1-D or N-D right-hand side + b_is_1D = False + + # check finite after determining structure + a1 = atleast_2d(_asarray_validated(a, check_finite=False)) + b1 = atleast_1d(_asarray_validated(b, check_finite=False)) + a1, b1 = _ensure_dtype_cdsz(a1, b1) + n = a1.shape[0] + + overwrite_a = overwrite_a or _datacopied(a1, a) + overwrite_b = overwrite_b or _datacopied(b1, b) + + if a1.shape[0] != a1.shape[1]: + raise ValueError('Input a needs to be a square matrix.') + + if n != b1.shape[0]: + # Last chance to catch 1x1 scalar a and 1-D b arrays + if not (n == 1 and b1.size != 0): + raise ValueError('Input b has to have same number of rows as ' + 'input a') + + # accommodate empty arrays + if b1.size == 0: + dt = solve(np.eye(2, dtype=a1.dtype), np.ones(2, dtype=b1.dtype)).dtype + return np.empty_like(b1, dtype=dt) + + # regularize 1-D b arrays to 2D + if b1.ndim == 1: + if n == 1: + b1 = b1[None, :] + else: + b1 = b1[:, None] + b_is_1D = True + + if assume_a not in {None, 'diagonal', 'tridiagonal', 'banded', 'lower triangular', + 'upper triangular', 'symmetric', 'hermitian', + 'positive definite', 'general', 'sym', 'her', 'pos', 'gen'}: + raise ValueError(f'{assume_a} is not a recognized matrix structure') + + # for a real matrix, describe it as "symmetric", not "hermitian" + # (lapack doesn't know what to do with real hermitian matrices) + if assume_a in {'hermitian', 'her'} and not np.iscomplexobj(a1): + assume_a = 'symmetric' + + n_below, n_above = None, None + if assume_a is None: + assume_a, n_below, n_above = _find_matrix_structure(a1) + + # Get the correct lamch function. + # The LAMCH functions only exists for S and D + # So for complex values we have to convert to real/double. + if a1.dtype.char in 'fF': # single precision + lamch = get_lapack_funcs('lamch', dtype='f') + else: + lamch = get_lapack_funcs('lamch', dtype='d') + + # Currently we do not have the other forms of the norm calculators + # lansy, lanpo, lanhe. + # However, in any case they only reduce computations slightly... + if assume_a == 'diagonal': + _matrix_norm = _matrix_norm_diagonal + elif assume_a == 'tridiagonal': + _matrix_norm = _matrix_norm_tridiagonal + elif assume_a in {'lower triangular', 'upper triangular'}: + _matrix_norm = _matrix_norm_triangular(assume_a) + else: + _matrix_norm = _matrix_norm_general + + # Since the I-norm and 1-norm are the same for symmetric matrices + # we can collect them all in this one call + # Note however, that when issuing 'gen' and form!='none', then + # the I-norm should be used + if transposed: + trans = 1 + norm = 'I' + if np.iscomplexobj(a1): + raise NotImplementedError('scipy.linalg.solve can currently ' + 'not solve a^T x = b or a^H x = b ' + 'for complex matrices.') + else: + trans = 0 + norm = '1' + + anorm = _matrix_norm(norm, a1, check_finite) + + info, rcond = 0, np.inf + + # Generalized case 'gesv' + if assume_a in {'general', 'gen'}: + gecon, getrf, getrs = get_lapack_funcs(('gecon', 'getrf', 'getrs'), + (a1, b1)) + lu, ipvt, info = getrf(a1, overwrite_a=overwrite_a) + _solve_check(n, info) + x, info = getrs(lu, ipvt, b1, + trans=trans, overwrite_b=overwrite_b) + _solve_check(n, info) + rcond, info = gecon(lu, anorm, norm=norm) + # Hermitian case 'hesv' + elif assume_a in {'hermitian', 'her'}: + hecon, hesv, hesv_lw = get_lapack_funcs(('hecon', 'hesv', + 'hesv_lwork'), (a1, b1)) + lwork = _compute_lwork(hesv_lw, n, lower) + lu, ipvt, x, info = hesv(a1, b1, lwork=lwork, + lower=lower, + overwrite_a=overwrite_a, + overwrite_b=overwrite_b) + _solve_check(n, info) + rcond, info = hecon(lu, ipvt, anorm) + # Symmetric case 'sysv' + elif assume_a in {'symmetric', 'sym'}: + sycon, sysv, sysv_lw = get_lapack_funcs(('sycon', 'sysv', + 'sysv_lwork'), (a1, b1)) + lwork = _compute_lwork(sysv_lw, n, lower) + lu, ipvt, x, info = sysv(a1, b1, lwork=lwork, + lower=lower, + overwrite_a=overwrite_a, + overwrite_b=overwrite_b) + _solve_check(n, info) + rcond, info = sycon(lu, ipvt, anorm) + # Diagonal case + elif assume_a == 'diagonal': + diag_a = np.diag(a1) + x = (b1.T / diag_a).T + abs_diag_a = np.abs(diag_a) + rcond = abs_diag_a.min() / abs_diag_a.max() + # Tri-diagonal case + elif assume_a == 'tridiagonal': + a1 = a1.T if transposed else a1 + dl, d, du = np.diag(a1, -1), np.diag(a1, 0), np.diag(a1, 1) + _gttrf, _gttrs, _gtcon = get_lapack_funcs(('gttrf', 'gttrs', 'gtcon'), (a1, b1)) + dl, d, du, du2, ipiv, info = _gttrf(dl, d, du) + _solve_check(n, info) + x, info = _gttrs(dl, d, du, du2, ipiv, b1, overwrite_b=overwrite_b) + _solve_check(n, info) + rcond, info = _gtcon(dl, d, du, du2, ipiv, anorm) + # Banded case + elif assume_a == 'banded': + a1, n_below, n_above = ((a1.T, n_above, n_below) if transposed + else (a1, n_below, n_above)) + n_below, n_above = bandwidth(a1) if n_below is None else (n_below, n_above) + ab = _to_banded(n_below, n_above, a1) + gbsv, = get_lapack_funcs(('gbsv',), (a1, b1)) + # Next two lines copied from `solve_banded` + a2 = np.zeros((2*n_below + n_above + 1, ab.shape[1]), dtype=gbsv.dtype) + a2[n_below:, :] = ab + _, _, x, info = gbsv(n_below, n_above, a2, b1, + overwrite_ab=True, overwrite_b=overwrite_b) + _solve_check(n, info) + # TODO: wrap gbcon and use to get rcond + # Triangular case + elif assume_a in {'lower triangular', 'upper triangular'}: + lower = assume_a == 'lower triangular' + x, info = _solve_triangular(a1, b1, lower=lower, overwrite_b=overwrite_b, + trans=transposed) + _solve_check(n, info) + _trcon = get_lapack_funcs(('trcon'), (a1, b1)) + rcond, info = _trcon(a1, uplo='L' if lower else 'U') + # Positive definite case 'posv' + else: + pocon, posv = get_lapack_funcs(('pocon', 'posv'), + (a1, b1)) + lu, x, info = posv(a1, b1, lower=lower, + overwrite_a=overwrite_a, + overwrite_b=overwrite_b) + _solve_check(n, info) + rcond, info = pocon(lu, anorm) + + _solve_check(n, info, lamch, rcond) + + if b_is_1D: + x = x.ravel() + + return x + + +def _matrix_norm_diagonal(_, a, check_finite): + # Equivalent of dlange for diagonal matrix, assuming + # norm is either 'I' or '1' (really just not the Frobenius norm) + d = np.diag(a) + d = np.asarray_chkfinite(d) if check_finite else d + return np.abs(d).max() + + +def _matrix_norm_tridiagonal(norm, a, check_finite): + # Equivalent of dlange for tridiagonal matrix, assuming + # norm is either 'I' or '1' + if norm == 'I': + a = a.T + # Context to avoid warning before error in cases like -inf + inf + with np.errstate(invalid='ignore'): + d = np.abs(np.diag(a)) + d[1:] += np.abs(np.diag(a, 1)) + d[:-1] += np.abs(np.diag(a, -1)) + d = np.asarray_chkfinite(d) if check_finite else d + return d.max() + + +def _matrix_norm_triangular(structure): + def fun(norm, a, check_finite): + a = np.asarray_chkfinite(a) if check_finite else a + lantr = get_lapack_funcs('lantr', (a,)) + return lantr(norm, a, 'L' if structure == 'lower triangular' else 'U' ) + return fun + + +def _matrix_norm_general(norm, a, check_finite): + a = np.asarray_chkfinite(a) if check_finite else a + lange = get_lapack_funcs('lange', (a,)) + return lange(norm, a) + + +def _to_banded(n_below, n_above, a): + n = a.shape[0] + rows = n_above + n_below + 1 + ab = np.zeros((rows, n), dtype=a.dtype) + ab[n_above] = np.diag(a) + for i in range(1, n_above + 1): + ab[n_above - i, i:] = np.diag(a, i) + for i in range(1, n_below + 1): + ab[n_above + i, :-i] = np.diag(a, -i) + return ab + + +def _ensure_dtype_cdsz(*arrays): + # Ensure that the dtype of arrays is one of the standard types + # compatible with LAPACK functions (single or double precision + # real or complex). + dtype = np.result_type(*arrays) + if not np.issubdtype(dtype, np.inexact): + return (array.astype(np.float64) for array in arrays) + complex = np.issubdtype(dtype, np.complexfloating) + if np.finfo(dtype).bits <= 32: + dtype = np.complex64 if complex else np.float32 + elif np.finfo(dtype).bits >= 64: + dtype = np.complex128 if complex else np.float64 + return (array.astype(dtype, copy=False) for array in arrays) + + +def solve_triangular(a, b, trans=0, lower=False, unit_diagonal=False, + overwrite_b=False, check_finite=True): + """ + Solve the equation ``a x = b`` for `x`, assuming a is a triangular matrix. + + Parameters + ---------- + a : (M, M) array_like + A triangular matrix + b : (M,) or (M, N) array_like + Right-hand side matrix in ``a x = b`` + lower : bool, optional + Use only data contained in the lower triangle of `a`. + Default is to use upper triangle. + trans : {0, 1, 2, 'N', 'T', 'C'}, optional + Type of system to solve: + + ======== ========= + trans system + ======== ========= + 0 or 'N' a x = b + 1 or 'T' a^T x = b + 2 or 'C' a^H x = b + ======== ========= + unit_diagonal : bool, optional + If True, diagonal elements of `a` are assumed to be 1 and + will not be referenced. + overwrite_b : bool, optional + Allow overwriting data in `b` (may enhance performance) + check_finite : bool, optional + Whether to check that the input matrices contain only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + + Returns + ------- + x : (M,) or (M, N) ndarray + Solution to the system ``a x = b``. Shape of return matches `b`. + + Raises + ------ + LinAlgError + If `a` is singular + + Notes + ----- + .. versionadded:: 0.9.0 + + Examples + -------- + Solve the lower triangular system a x = b, where:: + + [3 0 0 0] [4] + a = [2 1 0 0] b = [2] + [1 0 1 0] [4] + [1 1 1 1] [2] + + >>> import numpy as np + >>> from scipy.linalg import solve_triangular + >>> a = np.array([[3, 0, 0, 0], [2, 1, 0, 0], [1, 0, 1, 0], [1, 1, 1, 1]]) + >>> b = np.array([4, 2, 4, 2]) + >>> x = solve_triangular(a, b, lower=True) + >>> x + array([ 1.33333333, -0.66666667, 2.66666667, -1.33333333]) + >>> a.dot(x) # Check the result + array([ 4., 2., 4., 2.]) + + """ + + a1 = _asarray_validated(a, check_finite=check_finite) + b1 = _asarray_validated(b, check_finite=check_finite) + + if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]: + raise ValueError('expected square matrix') + + if a1.shape[0] != b1.shape[0]: + raise ValueError(f'shapes of a {a1.shape} and b {b1.shape} are incompatible') + + # accommodate empty arrays + if b1.size == 0: + dt_nonempty = solve_triangular( + np.eye(2, dtype=a1.dtype), np.ones(2, dtype=b1.dtype) + ).dtype + return np.empty_like(b1, dtype=dt_nonempty) + + overwrite_b = overwrite_b or _datacopied(b1, b) + + x, _ = _solve_triangular(a1, b1, trans, lower, unit_diagonal, overwrite_b) + return x + + +# solve_triangular without the input validation +def _solve_triangular(a1, b1, trans=0, lower=False, unit_diagonal=False, + overwrite_b=False): + + trans = {'N': 0, 'T': 1, 'C': 2}.get(trans, trans) + trtrs, = get_lapack_funcs(('trtrs',), (a1, b1)) + if a1.flags.f_contiguous or trans == 2: + x, info = trtrs(a1, b1, overwrite_b=overwrite_b, lower=lower, + trans=trans, unitdiag=unit_diagonal) + else: + # transposed system is solved since trtrs expects Fortran ordering + x, info = trtrs(a1.T, b1, overwrite_b=overwrite_b, lower=not lower, + trans=not trans, unitdiag=unit_diagonal) + + if info == 0: + return x, info + if info > 0: + raise LinAlgError("singular matrix: resolution failed at diagonal %d" % + (info-1)) + raise ValueError('illegal value in %dth argument of internal trtrs' % + (-info)) + + +def solve_banded(l_and_u, ab, b, overwrite_ab=False, overwrite_b=False, + check_finite=True): + """ + Solve the equation a x = b for x, assuming a is banded matrix. + + The matrix a is stored in `ab` using the matrix diagonal ordered form:: + + ab[u + i - j, j] == a[i,j] + + Example of `ab` (shape of a is (6,6), `u` =1, `l` =2):: + + * a01 a12 a23 a34 a45 + a00 a11 a22 a33 a44 a55 + a10 a21 a32 a43 a54 * + a20 a31 a42 a53 * * + + Parameters + ---------- + (l, u) : (integer, integer) + Number of non-zero lower and upper diagonals + ab : (`l` + `u` + 1, M) array_like + Banded matrix + b : (M,) or (M, K) array_like + Right-hand side + overwrite_ab : bool, optional + Discard data in `ab` (may enhance performance) + overwrite_b : bool, optional + Discard data in `b` (may enhance performance) + check_finite : bool, optional + Whether to check that the input matrices contain only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + + Returns + ------- + x : (M,) or (M, K) ndarray + The solution to the system a x = b. Returned shape depends on the + shape of `b`. + + Examples + -------- + Solve the banded system a x = b, where:: + + [5 2 -1 0 0] [0] + [1 4 2 -1 0] [1] + a = [0 1 3 2 -1] b = [2] + [0 0 1 2 2] [2] + [0 0 0 1 1] [3] + + There is one nonzero diagonal below the main diagonal (l = 1), and + two above (u = 2). The diagonal banded form of the matrix is:: + + [* * -1 -1 -1] + ab = [* 2 2 2 2] + [5 4 3 2 1] + [1 1 1 1 *] + + >>> import numpy as np + >>> from scipy.linalg import solve_banded + >>> ab = np.array([[0, 0, -1, -1, -1], + ... [0, 2, 2, 2, 2], + ... [5, 4, 3, 2, 1], + ... [1, 1, 1, 1, 0]]) + >>> b = np.array([0, 1, 2, 2, 3]) + >>> x = solve_banded((1, 2), ab, b) + >>> x + array([-2.37288136, 3.93220339, -4. , 4.3559322 , -1.3559322 ]) + + """ + + a1 = _asarray_validated(ab, check_finite=check_finite, as_inexact=True) + b1 = _asarray_validated(b, check_finite=check_finite, as_inexact=True) + + # Validate shapes. + if a1.shape[-1] != b1.shape[0]: + raise ValueError("shapes of ab and b are not compatible.") + + (nlower, nupper) = l_and_u + if nlower + nupper + 1 != a1.shape[0]: + raise ValueError("invalid values for the number of lower and upper " + "diagonals: l+u+1 (%d) does not equal ab.shape[0] " + "(%d)" % (nlower + nupper + 1, ab.shape[0])) + + # accommodate empty arrays + if b1.size == 0: + dt = solve(np.eye(1, dtype=a1.dtype), np.ones(1, dtype=b1.dtype)).dtype + return np.empty_like(b1, dtype=dt) + + overwrite_b = overwrite_b or _datacopied(b1, b) + if a1.shape[-1] == 1: + b2 = np.array(b1, copy=(not overwrite_b)) + # a1.shape[-1] == 1 -> original matrix is 1x1. Typically, the user + # will pass u = l = 0 and `a1` will be 1x1. However, the rest of the + # function works with unnecessary rows in `a1` as long as + # `a1[u + i - j, j] == a[i,j]`. In the 1x1 case, we want i = j = 0, + # so the diagonal is in row `u` of `a1`. See gh-8906. + b2 /= a1[nupper, 0] + return b2 + if nlower == nupper == 1: + overwrite_ab = overwrite_ab or _datacopied(a1, ab) + gtsv, = get_lapack_funcs(('gtsv',), (a1, b1)) + du = a1[0, 1:] + d = a1[1, :] + dl = a1[2, :-1] + du2, d, du, x, info = gtsv(dl, d, du, b1, overwrite_ab, overwrite_ab, + overwrite_ab, overwrite_b) + else: + gbsv, = get_lapack_funcs(('gbsv',), (a1, b1)) + a2 = np.zeros((2*nlower + nupper + 1, a1.shape[1]), dtype=gbsv.dtype) + a2[nlower:, :] = a1 + lu, piv, x, info = gbsv(nlower, nupper, a2, b1, overwrite_ab=True, + overwrite_b=overwrite_b) + if info == 0: + return x + if info > 0: + raise LinAlgError("singular matrix") + raise ValueError('illegal value in %d-th argument of internal ' + 'gbsv/gtsv' % -info) + + +def solveh_banded(ab, b, overwrite_ab=False, overwrite_b=False, lower=False, + check_finite=True): + """ + Solve equation a x = b. a is Hermitian positive-definite banded matrix. + + Uses Thomas' Algorithm, which is more efficient than standard LU + factorization, but should only be used for Hermitian positive-definite + matrices. + + The matrix ``a`` is stored in `ab` either in lower diagonal or upper + diagonal ordered form: + + ab[u + i - j, j] == a[i,j] (if upper form; i <= j) + ab[ i - j, j] == a[i,j] (if lower form; i >= j) + + Example of `ab` (shape of ``a`` is (6, 6), number of upper diagonals, + ``u`` =2):: + + upper form: + * * a02 a13 a24 a35 + * a01 a12 a23 a34 a45 + a00 a11 a22 a33 a44 a55 + + lower form: + a00 a11 a22 a33 a44 a55 + a10 a21 a32 a43 a54 * + a20 a31 a42 a53 * * + + Cells marked with * are not used. + + Parameters + ---------- + ab : (``u`` + 1, M) array_like + Banded matrix + b : (M,) or (M, K) array_like + Right-hand side + overwrite_ab : bool, optional + Discard data in `ab` (may enhance performance) + overwrite_b : bool, optional + Discard data in `b` (may enhance performance) + lower : bool, optional + Is the matrix in the lower form. (Default is upper form) + check_finite : bool, optional + Whether to check that the input matrices contain only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + + Returns + ------- + x : (M,) or (M, K) ndarray + The solution to the system ``a x = b``. Shape of return matches shape + of `b`. + + Notes + ----- + In the case of a non-positive definite matrix ``a``, the solver + `solve_banded` may be used. + + Examples + -------- + Solve the banded system ``A x = b``, where:: + + [ 4 2 -1 0 0 0] [1] + [ 2 5 2 -1 0 0] [2] + A = [-1 2 6 2 -1 0] b = [2] + [ 0 -1 2 7 2 -1] [3] + [ 0 0 -1 2 8 2] [3] + [ 0 0 0 -1 2 9] [3] + + >>> import numpy as np + >>> from scipy.linalg import solveh_banded + + ``ab`` contains the main diagonal and the nonzero diagonals below the + main diagonal. That is, we use the lower form: + + >>> ab = np.array([[ 4, 5, 6, 7, 8, 9], + ... [ 2, 2, 2, 2, 2, 0], + ... [-1, -1, -1, -1, 0, 0]]) + >>> b = np.array([1, 2, 2, 3, 3, 3]) + >>> x = solveh_banded(ab, b, lower=True) + >>> x + array([ 0.03431373, 0.45938375, 0.05602241, 0.47759104, 0.17577031, + 0.34733894]) + + + Solve the Hermitian banded system ``H x = b``, where:: + + [ 8 2-1j 0 0 ] [ 1 ] + H = [2+1j 5 1j 0 ] b = [1+1j] + [ 0 -1j 9 -2-1j] [1-2j] + [ 0 0 -2+1j 6 ] [ 0 ] + + In this example, we put the upper diagonals in the array ``hb``: + + >>> hb = np.array([[0, 2-1j, 1j, -2-1j], + ... [8, 5, 9, 6 ]]) + >>> b = np.array([1, 1+1j, 1-2j, 0]) + >>> x = solveh_banded(hb, b) + >>> x + array([ 0.07318536-0.02939412j, 0.11877624+0.17696461j, + 0.10077984-0.23035393j, -0.00479904-0.09358128j]) + + """ + a1 = _asarray_validated(ab, check_finite=check_finite) + b1 = _asarray_validated(b, check_finite=check_finite) + + # Validate shapes. + if a1.shape[-1] != b1.shape[0]: + raise ValueError("shapes of ab and b are not compatible.") + + # accommodate empty arrays + if b1.size == 0: + dt = solve(np.eye(1, dtype=a1.dtype), np.ones(1, dtype=b1.dtype)).dtype + return np.empty_like(b1, dtype=dt) + + overwrite_b = overwrite_b or _datacopied(b1, b) + overwrite_ab = overwrite_ab or _datacopied(a1, ab) + + if a1.shape[0] == 2: + ptsv, = get_lapack_funcs(('ptsv',), (a1, b1)) + if lower: + d = a1[0, :].real + e = a1[1, :-1] + else: + d = a1[1, :].real + e = a1[0, 1:].conj() + d, du, x, info = ptsv(d, e, b1, overwrite_ab, overwrite_ab, + overwrite_b) + else: + pbsv, = get_lapack_funcs(('pbsv',), (a1, b1)) + c, x, info = pbsv(a1, b1, lower=lower, overwrite_ab=overwrite_ab, + overwrite_b=overwrite_b) + if info > 0: + raise LinAlgError("%dth leading minor not positive definite" % info) + if info < 0: + raise ValueError('illegal value in %dth argument of internal ' + 'pbsv' % -info) + return x + + +def solve_toeplitz(c_or_cr, b, check_finite=True): + r"""Solve a Toeplitz system using Levinson Recursion + + The Toeplitz matrix has constant diagonals, with c as its first column + and r as its first row. If r is not given, ``r == conjugate(c)`` is + assumed. + + .. warning:: + + Beginning in SciPy 1.17, multidimensional input will be treated as a batch, + not ``ravel``\ ed. To preserve the existing behavior, ``ravel`` arguments + before passing them to `solve_toeplitz`. + + Parameters + ---------- + c_or_cr : array_like or tuple of (array_like, array_like) + The vector ``c``, or a tuple of arrays (``c``, ``r``). If not + supplied, ``r = conjugate(c)`` is assumed; in this case, if c[0] is + real, the Toeplitz matrix is Hermitian. r[0] is ignored; the first row + of the Toeplitz matrix is ``[c[0], r[1:]]``. + b : (M,) or (M, K) array_like + Right-hand side in ``T x = b``. + check_finite : bool, optional + Whether to check that the input matrices contain only finite numbers. + Disabling may give a performance gain, but may result in problems + (result entirely NaNs) if the inputs do contain infinities or NaNs. + + Returns + ------- + x : (M,) or (M, K) ndarray + The solution to the system ``T x = b``. Shape of return matches shape + of `b`. + + See Also + -------- + toeplitz : Toeplitz matrix + + Notes + ----- + The solution is computed using Levinson-Durbin recursion, which is faster + than generic least-squares methods, but can be less numerically stable. + + Examples + -------- + Solve the Toeplitz system T x = b, where:: + + [ 1 -1 -2 -3] [1] + T = [ 3 1 -1 -2] b = [2] + [ 6 3 1 -1] [2] + [10 6 3 1] [5] + + To specify the Toeplitz matrix, only the first column and the first + row are needed. + + >>> import numpy as np + >>> c = np.array([1, 3, 6, 10]) # First column of T + >>> r = np.array([1, -1, -2, -3]) # First row of T + >>> b = np.array([1, 2, 2, 5]) + + >>> from scipy.linalg import solve_toeplitz, toeplitz + >>> x = solve_toeplitz((c, r), b) + >>> x + array([ 1.66666667, -1. , -2.66666667, 2.33333333]) + + Check the result by creating the full Toeplitz matrix and + multiplying it by `x`. We should get `b`. + + >>> T = toeplitz(c, r) + >>> T.dot(x) + array([ 1., 2., 2., 5.]) + + """ + # If numerical stability of this algorithm is a problem, a future + # developer might consider implementing other O(N^2) Toeplitz solvers, + # such as GKO (https://www.jstor.org/stable/2153371) or Bareiss. + + r, c, b, dtype, b_shape = _validate_args_for_toeplitz_ops( + c_or_cr, b, check_finite, keep_b_shape=True) + + # accommodate empty arrays + if b.size == 0: + return np.empty_like(b) + + # Form a 1-D array of values to be used in the matrix, containing a + # reversed copy of r[1:], followed by c. + vals = np.concatenate((r[-1:0:-1], c)) + if b is None: + raise ValueError('illegal value, `b` is a required argument') + + if b.ndim == 1: + x, _ = levinson(vals, np.ascontiguousarray(b)) + else: + x = np.column_stack([levinson(vals, np.ascontiguousarray(b[:, i]))[0] + for i in range(b.shape[1])]) + x = x.reshape(*b_shape) + + return x + + +def _get_axis_len(aname, a, axis): + ax = axis + if ax < 0: + ax += a.ndim + if 0 <= ax < a.ndim: + return a.shape[ax] + raise ValueError(f"'{aname}axis' entry is out of bounds") + + +def solve_circulant(c, b, singular='raise', tol=None, + caxis=-1, baxis=0, outaxis=0): + """Solve C x = b for x, where C is a circulant matrix. + + `C` is the circulant matrix associated with the vector `c`. + + The system is solved by doing division in Fourier space. The + calculation is:: + + x = ifft(fft(b) / fft(c)) + + where `fft` and `ifft` are the fast Fourier transform and its inverse, + respectively. For a large vector `c`, this is *much* faster than + solving the system with the full circulant matrix. + + Parameters + ---------- + c : array_like + The coefficients of the circulant matrix. + b : array_like + Right-hand side matrix in ``a x = b``. + singular : str, optional + This argument controls how a near singular circulant matrix is + handled. If `singular` is "raise" and the circulant matrix is + near singular, a `LinAlgError` is raised. If `singular` is + "lstsq", the least squares solution is returned. Default is "raise". + tol : float, optional + If any eigenvalue of the circulant matrix has an absolute value + that is less than or equal to `tol`, the matrix is considered to be + near singular. If not given, `tol` is set to:: + + tol = abs_eigs.max() * abs_eigs.size * np.finfo(np.float64).eps + + where `abs_eigs` is the array of absolute values of the eigenvalues + of the circulant matrix. + caxis : int + When `c` has dimension greater than 1, it is viewed as a collection + of circulant vectors. In this case, `caxis` is the axis of `c` that + holds the vectors of circulant coefficients. + baxis : int + When `b` has dimension greater than 1, it is viewed as a collection + of vectors. In this case, `baxis` is the axis of `b` that holds the + right-hand side vectors. + outaxis : int + When `c` or `b` are multidimensional, the value returned by + `solve_circulant` is multidimensional. In this case, `outaxis` is + the axis of the result that holds the solution vectors. + + Returns + ------- + x : ndarray + Solution to the system ``C x = b``. + + Raises + ------ + LinAlgError + If the circulant matrix associated with `c` is near singular. + + See Also + -------- + circulant : circulant matrix + + Notes + ----- + For a 1-D vector `c` with length `m`, and an array `b` + with shape ``(m, ...)``, + + solve_circulant(c, b) + + returns the same result as + + solve(circulant(c), b) + + where `solve` and `circulant` are from `scipy.linalg`. + + .. versionadded:: 0.16.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import solve_circulant, solve, circulant, lstsq + + >>> c = np.array([2, 2, 4]) + >>> b = np.array([1, 2, 3]) + >>> solve_circulant(c, b) + array([ 0.75, -0.25, 0.25]) + + Compare that result to solving the system with `scipy.linalg.solve`: + + >>> solve(circulant(c), b) + array([ 0.75, -0.25, 0.25]) + + A singular example: + + >>> c = np.array([1, 1, 0, 0]) + >>> b = np.array([1, 2, 3, 4]) + + Calling ``solve_circulant(c, b)`` will raise a `LinAlgError`. For the + least square solution, use the option ``singular='lstsq'``: + + >>> solve_circulant(c, b, singular='lstsq') + array([ 0.25, 1.25, 2.25, 1.25]) + + Compare to `scipy.linalg.lstsq`: + + >>> x, resid, rnk, s = lstsq(circulant(c), b) + >>> x + array([ 0.25, 1.25, 2.25, 1.25]) + + A broadcasting example: + + Suppose we have the vectors of two circulant matrices stored in an array + with shape (2, 5), and three `b` vectors stored in an array with shape + (3, 5). For example, + + >>> c = np.array([[1.5, 2, 3, 0, 0], [1, 1, 4, 3, 2]]) + >>> b = np.arange(15).reshape(-1, 5) + + We want to solve all combinations of circulant matrices and `b` vectors, + with the result stored in an array with shape (2, 3, 5). When we + disregard the axes of `c` and `b` that hold the vectors of coefficients, + the shapes of the collections are (2,) and (3,), respectively, which are + not compatible for broadcasting. To have a broadcast result with shape + (2, 3), we add a trivial dimension to `c`: ``c[:, np.newaxis, :]`` has + shape (2, 1, 5). The last dimension holds the coefficients of the + circulant matrices, so when we call `solve_circulant`, we can use the + default ``caxis=-1``. The coefficients of the `b` vectors are in the last + dimension of the array `b`, so we use ``baxis=-1``. If we use the + default `outaxis`, the result will have shape (5, 2, 3), so we'll use + ``outaxis=-1`` to put the solution vectors in the last dimension. + + >>> x = solve_circulant(c[:, np.newaxis, :], b, baxis=-1, outaxis=-1) + >>> x.shape + (2, 3, 5) + >>> np.set_printoptions(precision=3) # For compact output of numbers. + >>> x + array([[[-0.118, 0.22 , 1.277, -0.142, 0.302], + [ 0.651, 0.989, 2.046, 0.627, 1.072], + [ 1.42 , 1.758, 2.816, 1.396, 1.841]], + [[ 0.401, 0.304, 0.694, -0.867, 0.377], + [ 0.856, 0.758, 1.149, -0.412, 0.831], + [ 1.31 , 1.213, 1.603, 0.042, 1.286]]]) + + Check by solving one pair of `c` and `b` vectors (cf. ``x[1, 1, :]``): + + >>> solve_circulant(c[1], b[1, :]) + array([ 0.856, 0.758, 1.149, -0.412, 0.831]) + + """ + c = np.atleast_1d(c) + nc = _get_axis_len("c", c, caxis) + b = np.atleast_1d(b) + nb = _get_axis_len("b", b, baxis) + if nc != nb: + raise ValueError(f'Shapes of c {c.shape} and b {b.shape} are incompatible') + + # accommodate empty arrays + if b.size == 0: + dt = solve_circulant(np.arange(3, dtype=c.dtype), + np.ones(3, dtype=b.dtype)).dtype + return np.empty_like(b, dtype=dt) + + fc = np.fft.fft(np.moveaxis(c, caxis, -1), axis=-1) + abs_fc = np.abs(fc) + if tol is None: + # This is the same tolerance as used in np.linalg.matrix_rank. + tol = abs_fc.max(axis=-1) * nc * np.finfo(np.float64).eps + if tol.shape != (): + tol.shape = tol.shape + (1,) + else: + tol = np.atleast_1d(tol) + + near_zeros = abs_fc <= tol + is_near_singular = np.any(near_zeros) + if is_near_singular: + if singular == 'raise': + raise LinAlgError("near singular circulant matrix.") + else: + # Replace the small values with 1 to avoid errors in the + # division fb/fc below. + fc[near_zeros] = 1 + + fb = np.fft.fft(np.moveaxis(b, baxis, -1), axis=-1) + + q = fb / fc + + if is_near_singular: + # `near_zeros` is a boolean array, same shape as `c`, that is + # True where `fc` is (near) zero. `q` is the broadcasted result + # of fb / fc, so to set the values of `q` to 0 where `fc` is near + # zero, we use a mask that is the broadcast result of an array + # of True values shaped like `b` with `near_zeros`. + mask = np.ones_like(b, dtype=bool) & near_zeros + q[mask] = 0 + + x = np.fft.ifft(q, axis=-1) + if not (np.iscomplexobj(c) or np.iscomplexobj(b)): + x = x.real + if outaxis != -1: + x = np.moveaxis(x, -1, outaxis) + return x + + +# matrix inversion +def inv(a, overwrite_a=False, check_finite=True): + """ + Compute the inverse of a matrix. + + Parameters + ---------- + a : array_like + Square matrix to be inverted. + overwrite_a : bool, optional + Discard data in `a` (may improve performance). Default is False. + check_finite : bool, optional + Whether to check that the input matrix contains only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + + Returns + ------- + ainv : ndarray + Inverse of the matrix `a`. + + Raises + ------ + LinAlgError + If `a` is singular. + ValueError + If `a` is not square, or not 2D. + + Examples + -------- + >>> import numpy as np + >>> from scipy import linalg + >>> a = np.array([[1., 2.], [3., 4.]]) + >>> linalg.inv(a) + array([[-2. , 1. ], + [ 1.5, -0.5]]) + >>> np.dot(a, linalg.inv(a)) + array([[ 1., 0.], + [ 0., 1.]]) + + """ + a1 = _asarray_validated(a, check_finite=check_finite) + if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]: + raise ValueError('expected square matrix') + + # accommodate empty square matrices + if a1.size == 0: + dt = inv(np.eye(2, dtype=a1.dtype)).dtype + return np.empty_like(a1, dtype=dt) + + overwrite_a = overwrite_a or _datacopied(a1, a) + getrf, getri, getri_lwork = get_lapack_funcs(('getrf', 'getri', + 'getri_lwork'), + (a1,)) + lu, piv, info = getrf(a1, overwrite_a=overwrite_a) + if info == 0: + lwork = _compute_lwork(getri_lwork, a1.shape[0]) + + # XXX: the following line fixes curious SEGFAULT when + # benchmarking 500x500 matrix inverse. This seems to + # be a bug in LAPACK ?getri routine because if lwork is + # minimal (when using lwork[0] instead of lwork[1]) then + # all tests pass. Further investigation is required if + # more such SEGFAULTs occur. + lwork = int(1.01 * lwork) + inv_a, info = getri(lu, piv, lwork=lwork, overwrite_lu=1) + if info > 0: + raise LinAlgError("singular matrix") + if info < 0: + raise ValueError('illegal value in %d-th argument of internal ' + 'getrf|getri' % -info) + return inv_a + + +# Determinant + +def det(a, overwrite_a=False, check_finite=True): + """ + Compute the determinant of a matrix + + The determinant is a scalar that is a function of the associated square + matrix coefficients. The determinant value is zero for singular matrices. + + Parameters + ---------- + a : (..., M, M) array_like + Input array to compute determinants for. + overwrite_a : bool, optional + Allow overwriting data in a (may enhance performance). + check_finite : bool, optional + Whether to check that the input matrix contains only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + + Returns + ------- + det : (...) float or complex + Determinant of `a`. For stacked arrays, a scalar is returned for each + (m, m) slice in the last two dimensions of the input. For example, an + input of shape (p, q, m, m) will produce a result of shape (p, q). If + all dimensions are 1 a scalar is returned regardless of ndim. + + Notes + ----- + The determinant is computed by performing an LU factorization of the + input with LAPACK routine 'getrf', and then calculating the product of + diagonal entries of the U factor. + + Even if the input array is single precision (float32 or complex64), the + result will be returned in double precision (float64 or complex128) to + prevent overflows. + + Examples + -------- + >>> import numpy as np + >>> from scipy import linalg + >>> a = np.array([[1,2,3], [4,5,6], [7,8,9]]) # A singular matrix + >>> linalg.det(a) + 0.0 + >>> b = np.array([[0,2,3], [4,5,6], [7,8,9]]) + >>> linalg.det(b) + 3.0 + >>> # An array with the shape (3, 2, 2, 2) + >>> c = np.array([[[[1., 2.], [3., 4.]], + ... [[5., 6.], [7., 8.]]], + ... [[[9., 10.], [11., 12.]], + ... [[13., 14.], [15., 16.]]], + ... [[[17., 18.], [19., 20.]], + ... [[21., 22.], [23., 24.]]]]) + >>> linalg.det(c) # The resulting shape is (3, 2) + array([[-2., -2.], + [-2., -2.], + [-2., -2.]]) + >>> linalg.det(c[0, 0]) # Confirm the (0, 0) slice, [[1, 2], [3, 4]] + -2.0 + """ + # The goal is to end up with a writable contiguous array to pass to Cython + + # First we check and make arrays. + a1 = np.asarray_chkfinite(a) if check_finite else np.asarray(a) + if a1.ndim < 2: + raise ValueError('The input array must be at least two-dimensional.') + if a1.shape[-1] != a1.shape[-2]: + raise ValueError('Last 2 dimensions of the array must be square' + f' but received shape {a1.shape}.') + + # Also check if dtype is LAPACK compatible + if a1.dtype.char not in 'fdFD': + dtype_char = lapack_cast_dict[a1.dtype.char] + if not dtype_char: # No casting possible + raise TypeError(f'The dtype "{a1.dtype.name}" cannot be cast ' + 'to float(32, 64) or complex(64, 128).') + + a1 = a1.astype(dtype_char[0]) # makes a copy, free to scratch + overwrite_a = True + + # Empty array has determinant 1 because math. + if min(*a1.shape) == 0: + dtyp = np.float64 if a1.dtype.char not in 'FD' else np.complex128 + if a1.ndim == 2: + return dtyp(1.0) + else: + return np.ones(shape=a1.shape[:-2], dtype=dtyp) + + # Scalar case + if a1.shape[-2:] == (1, 1): + a1 = a1[..., 0, 0] + if a1.ndim == 0: + a1 = a1[()] + # Convert float32 to float64, and complex64 to complex128. + if a1.dtype.char in 'dD': + return a1 + return a1.astype('d') if a1.dtype.char == 'f' else a1.astype('D') + + # Then check overwrite permission + if not _datacopied(a1, a): # "a" still alive through "a1" + if not overwrite_a: + # Data belongs to "a" so make a copy + a1 = a1.copy(order='C') + # else: Do nothing we'll use "a" if possible + # else: a1 has its own data thus free to scratch + + # Then layout checks, might happen that overwrite is allowed but original + # array was read-only or non-C-contiguous. + if not (a1.flags['C_CONTIGUOUS'] and a1.flags['WRITEABLE']): + a1 = a1.copy(order='C') + + if a1.ndim == 2: + det = find_det_from_lu(a1) + # Convert float, complex to NumPy scalars + return (np.float64(det) if np.isrealobj(det) else np.complex128(det)) + + # loop over the stacked array, and avoid overflows for single precision + # Cf. np.linalg.det(np.diag([1e+38, 1e+38]).astype(np.float32)) + dtype_char = a1.dtype.char + if dtype_char in 'fF': + dtype_char = 'd' if dtype_char.islower() else 'D' + + det = np.empty(a1.shape[:-2], dtype=dtype_char) + for ind in product(*[range(x) for x in a1.shape[:-2]]): + det[ind] = find_det_from_lu(a1[ind]) + return det + + +# Linear Least Squares +def lstsq(a, b, cond=None, overwrite_a=False, overwrite_b=False, + check_finite=True, lapack_driver=None): + """ + Compute least-squares solution to equation Ax = b. + + Compute a vector x such that the 2-norm ``|b - A x|`` is minimized. + + Parameters + ---------- + a : (M, N) array_like + Left-hand side array + b : (M,) or (M, K) array_like + Right hand side array + cond : float, optional + Cutoff for 'small' singular values; used to determine effective + rank of a. Singular values smaller than + ``cond * largest_singular_value`` are considered zero. + overwrite_a : bool, optional + Discard data in `a` (may enhance performance). Default is False. + overwrite_b : bool, optional + Discard data in `b` (may enhance performance). Default is False. + check_finite : bool, optional + Whether to check that the input matrices contain only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + lapack_driver : str, optional + Which LAPACK driver is used to solve the least-squares problem. + Options are ``'gelsd'``, ``'gelsy'``, ``'gelss'``. Default + (``'gelsd'``) is a good choice. However, ``'gelsy'`` can be slightly + faster on many problems. ``'gelss'`` was used historically. It is + generally slow but uses less memory. + + .. versionadded:: 0.17.0 + + Returns + ------- + x : (N,) or (N, K) ndarray + Least-squares solution. + residues : (K,) ndarray or float + Square of the 2-norm for each column in ``b - a x``, if ``M > N`` and + ``rank(A) == n`` (returns a scalar if ``b`` is 1-D). Otherwise a + (0,)-shaped array is returned. + rank : int + Effective rank of `a`. + s : (min(M, N),) ndarray or None + Singular values of `a`. The condition number of ``a`` is + ``s[0] / s[-1]``. + + Raises + ------ + LinAlgError + If computation does not converge. + + ValueError + When parameters are not compatible. + + See Also + -------- + scipy.optimize.nnls : linear least squares with non-negativity constraint + + Notes + ----- + When ``'gelsy'`` is used as a driver, `residues` is set to a (0,)-shaped + array and `s` is always ``None``. + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import lstsq + >>> import matplotlib.pyplot as plt + + Suppose we have the following data: + + >>> x = np.array([1, 2.5, 3.5, 4, 5, 7, 8.5]) + >>> y = np.array([0.3, 1.1, 1.5, 2.0, 3.2, 6.6, 8.6]) + + We want to fit a quadratic polynomial of the form ``y = a + b*x**2`` + to this data. We first form the "design matrix" M, with a constant + column of 1s and a column containing ``x**2``: + + >>> M = x[:, np.newaxis]**[0, 2] + >>> M + array([[ 1. , 1. ], + [ 1. , 6.25], + [ 1. , 12.25], + [ 1. , 16. ], + [ 1. , 25. ], + [ 1. , 49. ], + [ 1. , 72.25]]) + + We want to find the least-squares solution to ``M.dot(p) = y``, + where ``p`` is a vector with length 2 that holds the parameters + ``a`` and ``b``. + + >>> p, res, rnk, s = lstsq(M, y) + >>> p + array([ 0.20925829, 0.12013861]) + + Plot the data and the fitted curve. + + >>> plt.plot(x, y, 'o', label='data') + >>> xx = np.linspace(0, 9, 101) + >>> yy = p[0] + p[1]*xx**2 + >>> plt.plot(xx, yy, label='least squares fit, $y = a + bx^2$') + >>> plt.xlabel('x') + >>> plt.ylabel('y') + >>> plt.legend(framealpha=1, shadow=True) + >>> plt.grid(alpha=0.25) + >>> plt.show() + + """ + a1 = _asarray_validated(a, check_finite=check_finite) + b1 = _asarray_validated(b, check_finite=check_finite) + if len(a1.shape) != 2: + raise ValueError('Input array a should be 2D') + m, n = a1.shape + if len(b1.shape) == 2: + nrhs = b1.shape[1] + else: + nrhs = 1 + if m != b1.shape[0]: + raise ValueError('Shape mismatch: a and b should have the same number' + f' of rows ({m} != {b1.shape[0]}).') + if m == 0 or n == 0: # Zero-sized problem, confuses LAPACK + x = np.zeros((n,) + b1.shape[1:], dtype=np.common_type(a1, b1)) + if n == 0: + residues = np.linalg.norm(b1, axis=0)**2 + else: + residues = np.empty((0,)) + return x, residues, 0, np.empty((0,)) + + driver = lapack_driver + if driver is None: + driver = lstsq.default_lapack_driver + if driver not in ('gelsd', 'gelsy', 'gelss'): + raise ValueError(f'LAPACK driver "{driver}" is not found') + + lapack_func, lapack_lwork = get_lapack_funcs((driver, + f'{driver}_lwork'), + (a1, b1)) + real_data = True if (lapack_func.dtype.kind == 'f') else False + + if m < n: + # need to extend b matrix as it will be filled with + # a larger solution matrix + if len(b1.shape) == 2: + b2 = np.zeros((n, nrhs), dtype=lapack_func.dtype) + b2[:m, :] = b1 + else: + b2 = np.zeros(n, dtype=lapack_func.dtype) + b2[:m] = b1 + b1 = b2 + + overwrite_a = overwrite_a or _datacopied(a1, a) + overwrite_b = overwrite_b or _datacopied(b1, b) + + if cond is None: + cond = np.finfo(lapack_func.dtype).eps + + if driver in ('gelss', 'gelsd'): + if driver == 'gelss': + lwork = _compute_lwork(lapack_lwork, m, n, nrhs, cond) + v, x, s, rank, work, info = lapack_func(a1, b1, cond, lwork, + overwrite_a=overwrite_a, + overwrite_b=overwrite_b) + + elif driver == 'gelsd': + if real_data: + lwork, iwork = _compute_lwork(lapack_lwork, m, n, nrhs, cond) + x, s, rank, info = lapack_func(a1, b1, lwork, + iwork, cond, False, False) + else: # complex data + lwork, rwork, iwork = _compute_lwork(lapack_lwork, m, n, + nrhs, cond) + x, s, rank, info = lapack_func(a1, b1, lwork, rwork, iwork, + cond, False, False) + if info > 0: + raise LinAlgError("SVD did not converge in Linear Least Squares") + if info < 0: + raise ValueError('illegal value in %d-th argument of internal %s' + % (-info, lapack_driver)) + resids = np.asarray([], dtype=x.dtype) + if m > n: + x1 = x[:n] + if rank == n: + resids = np.sum(np.abs(x[n:])**2, axis=0) + x = x1 + return x, resids, rank, s + + elif driver == 'gelsy': + lwork = _compute_lwork(lapack_lwork, m, n, nrhs, cond) + jptv = np.zeros((a1.shape[1], 1), dtype=np.int32) + v, x, j, rank, info = lapack_func(a1, b1, jptv, cond, + lwork, False, False) + if info < 0: + raise ValueError("illegal value in %d-th argument of internal " + "gelsy" % -info) + if m > n: + x1 = x[:n] + x = x1 + return x, np.array([], x.dtype), rank, None + + +lstsq.default_lapack_driver = 'gelsd' + + +def pinv(a, *, atol=None, rtol=None, return_rank=False, check_finite=True): + """ + Compute the (Moore-Penrose) pseudo-inverse of a matrix. + + Calculate a generalized inverse of a matrix using its + singular-value decomposition ``U @ S @ V`` in the economy mode and picking + up only the columns/rows that are associated with significant singular + values. + + If ``s`` is the maximum singular value of ``a``, then the + significance cut-off value is determined by ``atol + rtol * s``. Any + singular value below this value is assumed insignificant. + + Parameters + ---------- + a : (M, N) array_like + Matrix to be pseudo-inverted. + atol : float, optional + Absolute threshold term, default value is 0. + + .. versionadded:: 1.7.0 + + rtol : float, optional + Relative threshold term, default value is ``max(M, N) * eps`` where + ``eps`` is the machine precision value of the datatype of ``a``. + + .. versionadded:: 1.7.0 + + return_rank : bool, optional + If True, return the effective rank of the matrix. + check_finite : bool, optional + Whether to check that the input matrix contains only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + + Returns + ------- + B : (N, M) ndarray + The pseudo-inverse of matrix `a`. + rank : int + The effective rank of the matrix. Returned if `return_rank` is True. + + Raises + ------ + LinAlgError + If SVD computation does not converge. + + See Also + -------- + pinvh : Moore-Penrose pseudoinverse of a hermitian matrix. + + Notes + ----- + If ``A`` is invertible then the Moore-Penrose pseudoinverse is exactly + the inverse of ``A`` [1]_. If ``A`` is not invertible then the + Moore-Penrose pseudoinverse computes the ``x`` solution to ``Ax = b`` such + that ``||Ax - b||`` is minimized [1]_. + + References + ---------- + .. [1] Penrose, R. (1956). On best approximate solutions of linear matrix + equations. Mathematical Proceedings of the Cambridge Philosophical + Society, 52(1), 17-19. doi:10.1017/S0305004100030929 + + Examples + -------- + + Given an ``m x n`` matrix ``A`` and an ``n x m`` matrix ``B`` the four + Moore-Penrose conditions are: + + 1. ``ABA = A`` (``B`` is a generalized inverse of ``A``), + 2. ``BAB = B`` (``A`` is a generalized inverse of ``B``), + 3. ``(AB)* = AB`` (``AB`` is hermitian), + 4. ``(BA)* = BA`` (``BA`` is hermitian) [1]_. + + Here, ``A*`` denotes the conjugate transpose. The Moore-Penrose + pseudoinverse is a unique ``B`` that satisfies all four of these + conditions and exists for any ``A``. Note that, unlike the standard + matrix inverse, ``A`` does not have to be a square matrix or have + linearly independent columns/rows. + + As an example, we can calculate the Moore-Penrose pseudoinverse of a + random non-square matrix and verify it satisfies the four conditions. + + >>> import numpy as np + >>> from scipy import linalg + >>> rng = np.random.default_rng() + >>> A = rng.standard_normal((9, 6)) + >>> B = linalg.pinv(A) + >>> np.allclose(A @ B @ A, A) # Condition 1 + True + >>> np.allclose(B @ A @ B, B) # Condition 2 + True + >>> np.allclose((A @ B).conj().T, A @ B) # Condition 3 + True + >>> np.allclose((B @ A).conj().T, B @ A) # Condition 4 + True + + """ + a = _asarray_validated(a, check_finite=check_finite) + u, s, vh = _decomp_svd.svd(a, full_matrices=False, check_finite=False) + t = u.dtype.char.lower() + maxS = np.max(s, initial=0.) + + atol = 0. if atol is None else atol + rtol = max(a.shape) * np.finfo(t).eps if (rtol is None) else rtol + + if (atol < 0.) or (rtol < 0.): + raise ValueError("atol and rtol values must be positive.") + + val = atol + maxS * rtol + rank = np.sum(s > val) + + u = u[:, :rank] + u /= s[:rank] + B = (u @ vh[:rank]).conj().T + + if return_rank: + return B, rank + else: + return B + + +def pinvh(a, atol=None, rtol=None, lower=True, return_rank=False, + check_finite=True): + """ + Compute the (Moore-Penrose) pseudo-inverse of a Hermitian matrix. + + Calculate a generalized inverse of a complex Hermitian/real symmetric + matrix using its eigenvalue decomposition and including all eigenvalues + with 'large' absolute value. + + Parameters + ---------- + a : (N, N) array_like + Real symmetric or complex hermetian matrix to be pseudo-inverted + + atol : float, optional + Absolute threshold term, default value is 0. + + .. versionadded:: 1.7.0 + + rtol : float, optional + Relative threshold term, default value is ``N * eps`` where + ``eps`` is the machine precision value of the datatype of ``a``. + + .. versionadded:: 1.7.0 + + lower : bool, optional + Whether the pertinent array data is taken from the lower or upper + triangle of `a`. (Default: lower) + return_rank : bool, optional + If True, return the effective rank of the matrix. + check_finite : bool, optional + Whether to check that the input matrix contains only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + + Returns + ------- + B : (N, N) ndarray + The pseudo-inverse of matrix `a`. + rank : int + The effective rank of the matrix. Returned if `return_rank` is True. + + Raises + ------ + LinAlgError + If eigenvalue algorithm does not converge. + + See Also + -------- + pinv : Moore-Penrose pseudoinverse of a matrix. + + Examples + -------- + + For a more detailed example see `pinv`. + + >>> import numpy as np + >>> from scipy.linalg import pinvh + >>> rng = np.random.default_rng() + >>> a = rng.standard_normal((9, 6)) + >>> a = np.dot(a, a.T) + >>> B = pinvh(a) + >>> np.allclose(a, a @ B @ a) + True + >>> np.allclose(B, B @ a @ B) + True + + """ + a = _asarray_validated(a, check_finite=check_finite) + s, u = _decomp.eigh(a, lower=lower, check_finite=False, driver='ev') + t = u.dtype.char.lower() + maxS = np.max(np.abs(s), initial=0.) + + atol = 0. if atol is None else atol + rtol = max(a.shape) * np.finfo(t).eps if (rtol is None) else rtol + + if (atol < 0.) or (rtol < 0.): + raise ValueError("atol and rtol values must be positive.") + + val = atol + maxS * rtol + above_cutoff = (abs(s) > val) + + psigma_diag = 1.0 / s[above_cutoff] + u = u[:, above_cutoff] + + B = (u * psigma_diag) @ u.conj().T + + if return_rank: + return B, len(psigma_diag) + else: + return B + + +def matrix_balance(A, permute=True, scale=True, separate=False, + overwrite_a=False): + """ + Compute a diagonal similarity transformation for row/column balancing. + + The balancing tries to equalize the row and column 1-norms by applying + a similarity transformation such that the magnitude variation of the + matrix entries is reflected to the scaling matrices. + + Moreover, if enabled, the matrix is first permuted to isolate the upper + triangular parts of the matrix and, again if scaling is also enabled, + only the remaining subblocks are subjected to scaling. + + The balanced matrix satisfies the following equality + + .. math:: + + B = T^{-1} A T + + The scaling coefficients are approximated to the nearest power of 2 + to avoid round-off errors. + + Parameters + ---------- + A : (n, n) array_like + Square data matrix for the balancing. + permute : bool, optional + The selector to define whether permutation of A is also performed + prior to scaling. + scale : bool, optional + The selector to turn on and off the scaling. If False, the matrix + will not be scaled. + separate : bool, optional + This switches from returning a full matrix of the transformation + to a tuple of two separate 1-D permutation and scaling arrays. + overwrite_a : bool, optional + This is passed to xGEBAL directly. Essentially, overwrites the result + to the data. It might increase the space efficiency. See LAPACK manual + for details. This is False by default. + + Returns + ------- + B : (n, n) ndarray + Balanced matrix + T : (n, n) ndarray + A possibly permuted diagonal matrix whose nonzero entries are + integer powers of 2 to avoid numerical truncation errors. + scale, perm : (n,) ndarray + If ``separate`` keyword is set to True then instead of the array + ``T`` above, the scaling and the permutation vectors are given + separately as a tuple without allocating the full array ``T``. + + Notes + ----- + This algorithm is particularly useful for eigenvalue and matrix + decompositions and in many cases it is already called by various + LAPACK routines. + + The algorithm is based on the well-known technique of [1]_ and has + been modified to account for special cases. See [2]_ for details + which have been implemented since LAPACK v3.5.0. Before this version + there are corner cases where balancing can actually worsen the + conditioning. See [3]_ for such examples. + + The code is a wrapper around LAPACK's xGEBAL routine family for matrix + balancing. + + .. versionadded:: 0.19.0 + + References + ---------- + .. [1] B.N. Parlett and C. Reinsch, "Balancing a Matrix for + Calculation of Eigenvalues and Eigenvectors", Numerische Mathematik, + Vol.13(4), 1969, :doi:`10.1007/BF02165404` + .. [2] R. James, J. Langou, B.R. Lowery, "On matrix balancing and + eigenvector computation", 2014, :arxiv:`1401.5766` + .. [3] D.S. Watkins. A case where balancing is harmful. + Electron. Trans. Numer. Anal, Vol.23, 2006. + + Examples + -------- + >>> import numpy as np + >>> from scipy import linalg + >>> x = np.array([[1,2,0], [9,1,0.01], [1,2,10*np.pi]]) + + >>> y, permscale = linalg.matrix_balance(x) + >>> np.abs(x).sum(axis=0) / np.abs(x).sum(axis=1) + array([ 3.66666667, 0.4995005 , 0.91312162]) + + >>> np.abs(y).sum(axis=0) / np.abs(y).sum(axis=1) + array([ 1.2 , 1.27041742, 0.92658316]) # may vary + + >>> permscale # only powers of 2 (0.5 == 2^(-1)) + array([[ 0.5, 0. , 0. ], # may vary + [ 0. , 1. , 0. ], + [ 0. , 0. , 1. ]]) + + """ + + A = np.atleast_2d(_asarray_validated(A, check_finite=True)) + + if not np.equal(*A.shape): + raise ValueError('The data matrix for balancing should be square.') + + # accommodate empty arrays + if A.size == 0: + b_n, t_n = matrix_balance(np.eye(2, dtype=A.dtype)) + B = np.empty_like(A, dtype=b_n.dtype) + if separate: + scaling = np.ones_like(A, shape=len(A)) + perm = np.arange(len(A)) + return B, (scaling, perm) + return B, np.empty_like(A, dtype=t_n.dtype) + + gebal = get_lapack_funcs(('gebal'), (A,)) + B, lo, hi, ps, info = gebal(A, scale=scale, permute=permute, + overwrite_a=overwrite_a) + + if info < 0: + raise ValueError('xGEBAL exited with the internal error ' + f'"illegal value in argument number {-info}.". See ' + 'LAPACK documentation for the xGEBAL error codes.') + + # Separate the permutations from the scalings and then convert to int + scaling = np.ones_like(ps, dtype=float) + scaling[lo:hi+1] = ps[lo:hi+1] + + # gebal uses 1-indexing + ps = ps.astype(int, copy=False) - 1 + n = A.shape[0] + perm = np.arange(n) + + # LAPACK permutes with the ordering n --> hi, then 0--> lo + if hi < n: + for ind, x in enumerate(ps[hi+1:][::-1], 1): + if n-ind == x: + continue + perm[[x, n-ind]] = perm[[n-ind, x]] + + if lo > 0: + for ind, x in enumerate(ps[:lo]): + if ind == x: + continue + perm[[x, ind]] = perm[[ind, x]] + + if separate: + return B, (scaling, perm) + + # get the inverse permutation + iperm = np.empty_like(perm) + iperm[perm] = np.arange(n) + + return B, np.diag(scaling)[iperm, :] + + +def _validate_args_for_toeplitz_ops(c_or_cr, b, check_finite, keep_b_shape, + enforce_square=True): + """Validate arguments and format inputs for toeplitz functions + + Parameters + ---------- + c_or_cr : array_like or tuple of (array_like, array_like) + The vector ``c``, or a tuple of arrays (``c``, ``r``). Whatever the + actual shape of ``c``, it will be converted to a 1-D array. If not + supplied, ``r = conjugate(c)`` is assumed; in this case, if c[0] is + real, the Toeplitz matrix is Hermitian. r[0] is ignored; the first row + of the Toeplitz matrix is ``[c[0], r[1:]]``. Whatever the actual shape + of ``r``, it will be converted to a 1-D array. + b : (M,) or (M, K) array_like + Right-hand side in ``T x = b``. + check_finite : bool + Whether to check that the input matrices contain only finite numbers. + Disabling may give a performance gain, but may result in problems + (result entirely NaNs) if the inputs do contain infinities or NaNs. + keep_b_shape : bool + Whether to convert a (M,) dimensional b into a (M, 1) dimensional + matrix. + enforce_square : bool, optional + If True (default), this verifies that the Toeplitz matrix is square. + + Returns + ------- + r : array + 1d array corresponding to the first row of the Toeplitz matrix. + c: array + 1d array corresponding to the first column of the Toeplitz matrix. + b: array + (M,), (M, 1) or (M, K) dimensional array, post validation, + corresponding to ``b``. + dtype: numpy datatype + ``dtype`` stores the datatype of ``r``, ``c`` and ``b``. If any of + ``r``, ``c`` or ``b`` are complex, ``dtype`` is ``np.complex128``, + otherwise, it is ``np.float``. + b_shape: tuple + Shape of ``b`` after passing it through ``_asarray_validated``. + + """ + + if isinstance(c_or_cr, tuple): + c, r = c_or_cr + c = _asarray_validated(c, check_finite=check_finite) + r = _asarray_validated(r, check_finite=check_finite) + else: + c = _asarray_validated(c_or_cr, check_finite=check_finite) + r = c.conjugate() + + if c.ndim > 1 or r.ndim > 1: + msg = ("Beginning in SciPy 1.17, multidimensional input will be treated as a " + "batch, not `ravel`ed. To preserve the existing behavior and silence " + "this warning, `ravel` arguments before passing them to " + "`toeplitz`, `matmul_toeplitz`, and `solve_toeplitz`.") + warnings.warn(msg, FutureWarning, stacklevel=2) + c = c.ravel() + r = r.ravel() + + if b is None: + raise ValueError('`b` must be an array, not None.') + + b = _asarray_validated(b, check_finite=check_finite) + b_shape = b.shape + + is_not_square = r.shape[0] != c.shape[0] + if (enforce_square and is_not_square) or b.shape[0] != r.shape[0]: + raise ValueError('Incompatible dimensions.') + + is_cmplx = np.iscomplexobj(r) or np.iscomplexobj(c) or np.iscomplexobj(b) + dtype = np.complex128 if is_cmplx else np.float64 + r, c, b = (np.asarray(i, dtype=dtype) for i in (r, c, b)) + + if b.ndim == 1 and not keep_b_shape: + b = b.reshape(-1, 1) + elif b.ndim != 1: + b = b.reshape(b.shape[0], -1 if b.size > 0 else 0) + + return r, c, b, dtype, b_shape + + +def matmul_toeplitz(c_or_cr, x, check_finite=False, workers=None): + r"""Efficient Toeplitz Matrix-Matrix Multiplication using FFT + + This function returns the matrix multiplication between a Toeplitz + matrix and a dense matrix. + + The Toeplitz matrix has constant diagonals, with c as its first column + and r as its first row. If r is not given, ``r == conjugate(c)`` is + assumed. + + .. warning:: + + Beginning in SciPy 1.17, multidimensional input will be treated as a batch, + not ``ravel``\ ed. To preserve the existing behavior, ``ravel`` arguments + before passing them to `matmul_toeplitz`. + + Parameters + ---------- + c_or_cr : array_like or tuple of (array_like, array_like) + The vector ``c``, or a tuple of arrays (``c``, ``r``). If not + supplied, ``r = conjugate(c)`` is assumed; in this case, if c[0] is + real, the Toeplitz matrix is Hermitian. r[0] is ignored; the first row + of the Toeplitz matrix is ``[c[0], r[1:]]``. + x : (M,) or (M, K) array_like + Matrix with which to multiply. + check_finite : bool, optional + Whether to check that the input matrices contain only finite numbers. + Disabling may give a performance gain, but may result in problems + (result entirely NaNs) if the inputs do contain infinities or NaNs. + workers : int, optional + To pass to scipy.fft.fft and ifft. Maximum number of workers to use + for parallel computation. If negative, the value wraps around from + ``os.cpu_count()``. See scipy.fft.fft for more details. + + Returns + ------- + T @ x : (M,) or (M, K) ndarray + The result of the matrix multiplication ``T @ x``. Shape of return + matches shape of `x`. + + See Also + -------- + toeplitz : Toeplitz matrix + solve_toeplitz : Solve a Toeplitz system using Levinson Recursion + + Notes + ----- + The Toeplitz matrix is embedded in a circulant matrix and the FFT is used + to efficiently calculate the matrix-matrix product. + + Because the computation is based on the FFT, integer inputs will + result in floating point outputs. This is unlike NumPy's `matmul`, + which preserves the data type of the input. + + This is partly based on the implementation that can be found in [1]_, + licensed under the MIT license. More information about the method can be + found in reference [2]_. References [3]_ and [4]_ have more reference + implementations in Python. + + .. versionadded:: 1.6.0 + + References + ---------- + .. [1] Jacob R Gardner, Geoff Pleiss, David Bindel, Kilian + Q Weinberger, Andrew Gordon Wilson, "GPyTorch: Blackbox Matrix-Matrix + Gaussian Process Inference with GPU Acceleration" with contributions + from Max Balandat and Ruihan Wu. Available online: + https://github.com/cornellius-gp/gpytorch + + .. [2] J. Demmel, P. Koev, and X. Li, "A Brief Survey of Direct Linear + Solvers". In Z. Bai, J. Demmel, J. Dongarra, A. Ruhe, and H. van der + Vorst, editors. Templates for the Solution of Algebraic Eigenvalue + Problems: A Practical Guide. SIAM, Philadelphia, 2000. Available at: + http://www.netlib.org/utk/people/JackDongarra/etemplates/node384.html + + .. [3] R. Scheibler, E. Bezzam, I. Dokmanic, Pyroomacoustics: A Python + package for audio room simulations and array processing algorithms, + Proc. IEEE ICASSP, Calgary, CA, 2018. + https://github.com/LCAV/pyroomacoustics/blob/pypi-release/ + pyroomacoustics/adaptive/util.py + + .. [4] Marano S, Edwards B, Ferrari G and Fah D (2017), "Fitting + Earthquake Spectra: Colored Noise and Incomplete Data", Bulletin of + the Seismological Society of America., January, 2017. Vol. 107(1), + pp. 276-291. + + Examples + -------- + Multiply the Toeplitz matrix T with matrix x:: + + [ 1 -1 -2 -3] [1 10] + T = [ 3 1 -1 -2] x = [2 11] + [ 6 3 1 -1] [2 11] + [10 6 3 1] [5 19] + + To specify the Toeplitz matrix, only the first column and the first + row are needed. + + >>> import numpy as np + >>> c = np.array([1, 3, 6, 10]) # First column of T + >>> r = np.array([1, -1, -2, -3]) # First row of T + >>> x = np.array([[1, 10], [2, 11], [2, 11], [5, 19]]) + + >>> from scipy.linalg import toeplitz, matmul_toeplitz + >>> matmul_toeplitz((c, r), x) + array([[-20., -80.], + [ -7., -8.], + [ 9., 85.], + [ 33., 218.]]) + + Check the result by creating the full Toeplitz matrix and + multiplying it by ``x``. + + >>> toeplitz(c, r) @ x + array([[-20, -80], + [ -7, -8], + [ 9, 85], + [ 33, 218]]) + + The full matrix is never formed explicitly, so this routine + is suitable for very large Toeplitz matrices. + + >>> n = 1000000 + >>> matmul_toeplitz([1] + [0]*(n-1), np.ones(n)) + array([1., 1., 1., ..., 1., 1., 1.], shape=(1000000,)) + + """ + + from ..fft import fft, ifft, rfft, irfft + + r, c, x, dtype, x_shape = _validate_args_for_toeplitz_ops( + c_or_cr, x, check_finite, keep_b_shape=False, enforce_square=False) + n, m = x.shape + + T_nrows = len(c) + T_ncols = len(r) + p = T_nrows + T_ncols - 1 # equivalent to len(embedded_col) + return_shape = (T_nrows,) if len(x_shape) == 1 else (T_nrows, m) + + # accommodate empty arrays + if x.size == 0: + return np.empty_like(x, shape=return_shape) + + embedded_col = np.concatenate((c, r[-1:0:-1])) + + if np.iscomplexobj(embedded_col) or np.iscomplexobj(x): + fft_mat = fft(embedded_col, axis=0, workers=workers).reshape(-1, 1) + fft_x = fft(x, n=p, axis=0, workers=workers) + + mat_times_x = ifft(fft_mat*fft_x, axis=0, + workers=workers)[:T_nrows, :] + else: + # Real inputs; using rfft is faster + fft_mat = rfft(embedded_col, axis=0, workers=workers).reshape(-1, 1) + fft_x = rfft(x, n=p, axis=0, workers=workers) + + mat_times_x = irfft(fft_mat*fft_x, axis=0, + workers=workers, n=p)[:T_nrows, :] + + return mat_times_x.reshape(*return_shape) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_blas_subroutines.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_blas_subroutines.h new file mode 100644 index 0000000000000000000000000000000000000000..a175ca15f4adbed6d5c576e9e5ee1117abbd31ec --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_blas_subroutines.h @@ -0,0 +1,164 @@ +/* +This file was generated by _generate_pyx.py. +Do not edit this file directly. +*/ + +#include "npy_cblas.h" +#include "fortran_defs.h" + +#ifdef __cplusplus +extern "C" { +#endif + +void BLAS_FUNC(caxpy)(int *n, npy_complex64 *ca, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy); +void BLAS_FUNC(ccopy)(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy); +void F_FUNC(cdotcwrp,CDOTCWRP)(npy_complex64 *out, int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy); +void F_FUNC(cdotuwrp,CDOTUWRP)(npy_complex64 *out, int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy); +void BLAS_FUNC(cgbmv)(char *trans, int *m, int *n, int *kl, int *ku, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy); +void BLAS_FUNC(cgemm)(char *transa, char *transb, int *m, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *beta, npy_complex64 *c, int *ldc); +void BLAS_FUNC(cgemv)(char *trans, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy); +void BLAS_FUNC(cgerc)(int *m, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, npy_complex64 *a, int *lda); +void BLAS_FUNC(cgeru)(int *m, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, npy_complex64 *a, int *lda); +void BLAS_FUNC(chbmv)(char *uplo, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy); +void BLAS_FUNC(chemm)(char *side, char *uplo, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *beta, npy_complex64 *c, int *ldc); +void BLAS_FUNC(chemv)(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy); +void BLAS_FUNC(cher)(char *uplo, int *n, float *alpha, npy_complex64 *x, int *incx, npy_complex64 *a, int *lda); +void BLAS_FUNC(cher2)(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, npy_complex64 *a, int *lda); +void BLAS_FUNC(cher2k)(char *uplo, char *trans, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, float *beta, npy_complex64 *c, int *ldc); +void BLAS_FUNC(cherk)(char *uplo, char *trans, int *n, int *k, float *alpha, npy_complex64 *a, int *lda, float *beta, npy_complex64 *c, int *ldc); +void BLAS_FUNC(chpmv)(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *ap, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy); +void BLAS_FUNC(chpr)(char *uplo, int *n, float *alpha, npy_complex64 *x, int *incx, npy_complex64 *ap); +void BLAS_FUNC(chpr2)(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, npy_complex64 *ap); +void BLAS_FUNC(crotg)(npy_complex64 *ca, npy_complex64 *cb, float *c, npy_complex64 *s); +void BLAS_FUNC(cscal)(int *n, npy_complex64 *ca, npy_complex64 *cx, int *incx); +void BLAS_FUNC(csrot)(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy, float *c, float *s); +void BLAS_FUNC(csscal)(int *n, float *sa, npy_complex64 *cx, int *incx); +void BLAS_FUNC(cswap)(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy); +void BLAS_FUNC(csymm)(char *side, char *uplo, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *beta, npy_complex64 *c, int *ldc); +void BLAS_FUNC(csyr2k)(char *uplo, char *trans, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *beta, npy_complex64 *c, int *ldc); +void BLAS_FUNC(csyrk)(char *uplo, char *trans, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *beta, npy_complex64 *c, int *ldc); +void BLAS_FUNC(ctbmv)(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx); +void BLAS_FUNC(ctbsv)(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx); +void BLAS_FUNC(ctpmv)(char *uplo, char *trans, char *diag, int *n, npy_complex64 *ap, npy_complex64 *x, int *incx); +void BLAS_FUNC(ctpsv)(char *uplo, char *trans, char *diag, int *n, npy_complex64 *ap, npy_complex64 *x, int *incx); +void BLAS_FUNC(ctrmm)(char *side, char *uplo, char *transa, char *diag, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb); +void BLAS_FUNC(ctrmv)(char *uplo, char *trans, char *diag, int *n, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx); +void BLAS_FUNC(ctrsm)(char *side, char *uplo, char *transa, char *diag, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb); +void BLAS_FUNC(ctrsv)(char *uplo, char *trans, char *diag, int *n, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx); +double BLAS_FUNC(dasum)(int *n, double *dx, int *incx); +void BLAS_FUNC(daxpy)(int *n, double *da, double *dx, int *incx, double *dy, int *incy); +double BLAS_FUNC(dcabs1)(npy_complex128 *z); +void BLAS_FUNC(dcopy)(int *n, double *dx, int *incx, double *dy, int *incy); +double BLAS_FUNC(ddot)(int *n, double *dx, int *incx, double *dy, int *incy); +void BLAS_FUNC(dgbmv)(char *trans, int *m, int *n, int *kl, int *ku, double *alpha, double *a, int *lda, double *x, int *incx, double *beta, double *y, int *incy); +void BLAS_FUNC(dgemm)(char *transa, char *transb, int *m, int *n, int *k, double *alpha, double *a, int *lda, double *b, int *ldb, double *beta, double *c, int *ldc); +void BLAS_FUNC(dgemv)(char *trans, int *m, int *n, double *alpha, double *a, int *lda, double *x, int *incx, double *beta, double *y, int *incy); +void BLAS_FUNC(dger)(int *m, int *n, double *alpha, double *x, int *incx, double *y, int *incy, double *a, int *lda); +double BLAS_FUNC(dnrm2)(int *n, double *x, int *incx); +void BLAS_FUNC(drot)(int *n, double *dx, int *incx, double *dy, int *incy, double *c, double *s); +void BLAS_FUNC(drotg)(double *da, double *db, double *c, double *s); +void BLAS_FUNC(drotm)(int *n, double *dx, int *incx, double *dy, int *incy, double *dparam); +void BLAS_FUNC(drotmg)(double *dd1, double *dd2, double *dx1, double *dy1, double *dparam); +void BLAS_FUNC(dsbmv)(char *uplo, int *n, int *k, double *alpha, double *a, int *lda, double *x, int *incx, double *beta, double *y, int *incy); +void BLAS_FUNC(dscal)(int *n, double *da, double *dx, int *incx); +double BLAS_FUNC(dsdot)(int *n, float *sx, int *incx, float *sy, int *incy); +void BLAS_FUNC(dspmv)(char *uplo, int *n, double *alpha, double *ap, double *x, int *incx, double *beta, double *y, int *incy); +void BLAS_FUNC(dspr)(char *uplo, int *n, double *alpha, double *x, int *incx, double *ap); +void BLAS_FUNC(dspr2)(char *uplo, int *n, double *alpha, double *x, int *incx, double *y, int *incy, double *ap); +void BLAS_FUNC(dswap)(int *n, double *dx, int *incx, double *dy, int *incy); +void BLAS_FUNC(dsymm)(char *side, char *uplo, int *m, int *n, double *alpha, double *a, int *lda, double *b, int *ldb, double *beta, double *c, int *ldc); +void BLAS_FUNC(dsymv)(char *uplo, int *n, double *alpha, double *a, int *lda, double *x, int *incx, double *beta, double *y, int *incy); +void BLAS_FUNC(dsyr)(char *uplo, int *n, double *alpha, double *x, int *incx, double *a, int *lda); +void BLAS_FUNC(dsyr2)(char *uplo, int *n, double *alpha, double *x, int *incx, double *y, int *incy, double *a, int *lda); +void BLAS_FUNC(dsyr2k)(char *uplo, char *trans, int *n, int *k, double *alpha, double *a, int *lda, double *b, int *ldb, double *beta, double *c, int *ldc); +void BLAS_FUNC(dsyrk)(char *uplo, char *trans, int *n, int *k, double *alpha, double *a, int *lda, double *beta, double *c, int *ldc); +void BLAS_FUNC(dtbmv)(char *uplo, char *trans, char *diag, int *n, int *k, double *a, int *lda, double *x, int *incx); +void BLAS_FUNC(dtbsv)(char *uplo, char *trans, char *diag, int *n, int *k, double *a, int *lda, double *x, int *incx); +void BLAS_FUNC(dtpmv)(char *uplo, char *trans, char *diag, int *n, double *ap, double *x, int *incx); +void BLAS_FUNC(dtpsv)(char *uplo, char *trans, char *diag, int *n, double *ap, double *x, int *incx); +void BLAS_FUNC(dtrmm)(char *side, char *uplo, char *transa, char *diag, int *m, int *n, double *alpha, double *a, int *lda, double *b, int *ldb); +void BLAS_FUNC(dtrmv)(char *uplo, char *trans, char *diag, int *n, double *a, int *lda, double *x, int *incx); +void BLAS_FUNC(dtrsm)(char *side, char *uplo, char *transa, char *diag, int *m, int *n, double *alpha, double *a, int *lda, double *b, int *ldb); +void BLAS_FUNC(dtrsv)(char *uplo, char *trans, char *diag, int *n, double *a, int *lda, double *x, int *incx); +double BLAS_FUNC(dzasum)(int *n, npy_complex128 *zx, int *incx); +double BLAS_FUNC(dznrm2)(int *n, npy_complex128 *x, int *incx); +int BLAS_FUNC(icamax)(int *n, npy_complex64 *cx, int *incx); +int BLAS_FUNC(idamax)(int *n, double *dx, int *incx); +int BLAS_FUNC(isamax)(int *n, float *sx, int *incx); +int BLAS_FUNC(izamax)(int *n, npy_complex128 *zx, int *incx); +int BLAS_FUNC(lsame)(char *ca, char *cb); +float BLAS_FUNC(sasum)(int *n, float *sx, int *incx); +void BLAS_FUNC(saxpy)(int *n, float *sa, float *sx, int *incx, float *sy, int *incy); +float BLAS_FUNC(scasum)(int *n, npy_complex64 *cx, int *incx); +float BLAS_FUNC(scnrm2)(int *n, npy_complex64 *x, int *incx); +void BLAS_FUNC(scopy)(int *n, float *sx, int *incx, float *sy, int *incy); +float BLAS_FUNC(sdot)(int *n, float *sx, int *incx, float *sy, int *incy); +float BLAS_FUNC(sdsdot)(int *n, float *sb, float *sx, int *incx, float *sy, int *incy); +void BLAS_FUNC(sgbmv)(char *trans, int *m, int *n, int *kl, int *ku, float *alpha, float *a, int *lda, float *x, int *incx, float *beta, float *y, int *incy); +void BLAS_FUNC(sgemm)(char *transa, char *transb, int *m, int *n, int *k, float *alpha, float *a, int *lda, float *b, int *ldb, float *beta, float *c, int *ldc); +void BLAS_FUNC(sgemv)(char *trans, int *m, int *n, float *alpha, float *a, int *lda, float *x, int *incx, float *beta, float *y, int *incy); +void BLAS_FUNC(sger)(int *m, int *n, float *alpha, float *x, int *incx, float *y, int *incy, float *a, int *lda); +float BLAS_FUNC(snrm2)(int *n, float *x, int *incx); +void BLAS_FUNC(srot)(int *n, float *sx, int *incx, float *sy, int *incy, float *c, float *s); +void BLAS_FUNC(srotg)(float *sa, float *sb, float *c, float *s); +void BLAS_FUNC(srotm)(int *n, float *sx, int *incx, float *sy, int *incy, float *sparam); +void BLAS_FUNC(srotmg)(float *sd1, float *sd2, float *sx1, float *sy1, float *sparam); +void BLAS_FUNC(ssbmv)(char *uplo, int *n, int *k, float *alpha, float *a, int *lda, float *x, int *incx, float *beta, float *y, int *incy); +void BLAS_FUNC(sscal)(int *n, float *sa, float *sx, int *incx); +void BLAS_FUNC(sspmv)(char *uplo, int *n, float *alpha, float *ap, float *x, int *incx, float *beta, float *y, int *incy); +void BLAS_FUNC(sspr)(char *uplo, int *n, float *alpha, float *x, int *incx, float *ap); +void BLAS_FUNC(sspr2)(char *uplo, int *n, float *alpha, float *x, int *incx, float *y, int *incy, float *ap); +void BLAS_FUNC(sswap)(int *n, float *sx, int *incx, float *sy, int *incy); +void BLAS_FUNC(ssymm)(char *side, char *uplo, int *m, int *n, float *alpha, float *a, int *lda, float *b, int *ldb, float *beta, float *c, int *ldc); +void BLAS_FUNC(ssymv)(char *uplo, int *n, float *alpha, float *a, int *lda, float *x, int *incx, float *beta, float *y, int *incy); +void BLAS_FUNC(ssyr)(char *uplo, int *n, float *alpha, float *x, int *incx, float *a, int *lda); +void BLAS_FUNC(ssyr2)(char *uplo, int *n, float *alpha, float *x, int *incx, float *y, int *incy, float *a, int *lda); +void BLAS_FUNC(ssyr2k)(char *uplo, char *trans, int *n, int *k, float *alpha, float *a, int *lda, float *b, int *ldb, float *beta, float *c, int *ldc); +void BLAS_FUNC(ssyrk)(char *uplo, char *trans, int *n, int *k, float *alpha, float *a, int *lda, float *beta, float *c, int *ldc); +void BLAS_FUNC(stbmv)(char *uplo, char *trans, char *diag, int *n, int *k, float *a, int *lda, float *x, int *incx); +void BLAS_FUNC(stbsv)(char *uplo, char *trans, char *diag, int *n, int *k, float *a, int *lda, float *x, int *incx); +void BLAS_FUNC(stpmv)(char *uplo, char *trans, char *diag, int *n, float *ap, float *x, int *incx); +void BLAS_FUNC(stpsv)(char *uplo, char *trans, char *diag, int *n, float *ap, float *x, int *incx); +void BLAS_FUNC(strmm)(char *side, char *uplo, char *transa, char *diag, int *m, int *n, float *alpha, float *a, int *lda, float *b, int *ldb); +void BLAS_FUNC(strmv)(char *uplo, char *trans, char *diag, int *n, float *a, int *lda, float *x, int *incx); +void BLAS_FUNC(strsm)(char *side, char *uplo, char *transa, char *diag, int *m, int *n, float *alpha, float *a, int *lda, float *b, int *ldb); +void BLAS_FUNC(strsv)(char *uplo, char *trans, char *diag, int *n, float *a, int *lda, float *x, int *incx); +void BLAS_FUNC(zaxpy)(int *n, npy_complex128 *za, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy); +void BLAS_FUNC(zcopy)(int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy); +void F_FUNC(zdotcwrp,ZDOTCWRP)(npy_complex128 *out, int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy); +void F_FUNC(zdotuwrp,ZDOTUWRP)(npy_complex128 *out, int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy); +void BLAS_FUNC(zdrot)(int *n, npy_complex128 *cx, int *incx, npy_complex128 *cy, int *incy, double *c, double *s); +void BLAS_FUNC(zdscal)(int *n, double *da, npy_complex128 *zx, int *incx); +void BLAS_FUNC(zgbmv)(char *trans, int *m, int *n, int *kl, int *ku, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy); +void BLAS_FUNC(zgemm)(char *transa, char *transb, int *m, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *beta, npy_complex128 *c, int *ldc); +void BLAS_FUNC(zgemv)(char *trans, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy); +void BLAS_FUNC(zgerc)(int *m, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, npy_complex128 *a, int *lda); +void BLAS_FUNC(zgeru)(int *m, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, npy_complex128 *a, int *lda); +void BLAS_FUNC(zhbmv)(char *uplo, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy); +void BLAS_FUNC(zhemm)(char *side, char *uplo, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *beta, npy_complex128 *c, int *ldc); +void BLAS_FUNC(zhemv)(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy); +void BLAS_FUNC(zher)(char *uplo, int *n, double *alpha, npy_complex128 *x, int *incx, npy_complex128 *a, int *lda); +void BLAS_FUNC(zher2)(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, npy_complex128 *a, int *lda); +void BLAS_FUNC(zher2k)(char *uplo, char *trans, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, double *beta, npy_complex128 *c, int *ldc); +void BLAS_FUNC(zherk)(char *uplo, char *trans, int *n, int *k, double *alpha, npy_complex128 *a, int *lda, double *beta, npy_complex128 *c, int *ldc); +void BLAS_FUNC(zhpmv)(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *ap, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy); +void BLAS_FUNC(zhpr)(char *uplo, int *n, double *alpha, npy_complex128 *x, int *incx, npy_complex128 *ap); +void BLAS_FUNC(zhpr2)(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, npy_complex128 *ap); +void BLAS_FUNC(zrotg)(npy_complex128 *ca, npy_complex128 *cb, double *c, npy_complex128 *s); +void BLAS_FUNC(zscal)(int *n, npy_complex128 *za, npy_complex128 *zx, int *incx); +void BLAS_FUNC(zswap)(int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy); +void BLAS_FUNC(zsymm)(char *side, char *uplo, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *beta, npy_complex128 *c, int *ldc); +void BLAS_FUNC(zsyr2k)(char *uplo, char *trans, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *beta, npy_complex128 *c, int *ldc); +void BLAS_FUNC(zsyrk)(char *uplo, char *trans, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *beta, npy_complex128 *c, int *ldc); +void BLAS_FUNC(ztbmv)(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx); +void BLAS_FUNC(ztbsv)(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx); +void BLAS_FUNC(ztpmv)(char *uplo, char *trans, char *diag, int *n, npy_complex128 *ap, npy_complex128 *x, int *incx); +void BLAS_FUNC(ztpsv)(char *uplo, char *trans, char *diag, int *n, npy_complex128 *ap, npy_complex128 *x, int *incx); +void BLAS_FUNC(ztrmm)(char *side, char *uplo, char *transa, char *diag, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb); +void BLAS_FUNC(ztrmv)(char *uplo, char *trans, char *diag, int *n, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx); +void BLAS_FUNC(ztrsm)(char *side, char *uplo, char *transa, char *diag, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb); +void BLAS_FUNC(ztrsv)(char *uplo, char *trans, char *diag, int *n, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx); + +#ifdef __cplusplus +} +#endif diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_cythonized_array_utils.pxd b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_cythonized_array_utils.pxd new file mode 100644 index 0000000000000000000000000000000000000000..ccec61c078e57ba7b6a310ec57189fcf236c972d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_cythonized_array_utils.pxd @@ -0,0 +1,40 @@ +cimport numpy as cnp + +ctypedef fused lapack_t: + float + double + (float complex) + (double complex) + +ctypedef fused lapack_cz_t: + (float complex) + (double complex) + +ctypedef fused lapack_sd_t: + float + double + +ctypedef fused np_numeric_t: + cnp.int8_t + cnp.int16_t + cnp.int32_t + cnp.int64_t + cnp.uint8_t + cnp.uint16_t + cnp.uint32_t + cnp.uint64_t + cnp.float32_t + cnp.float64_t + cnp.longdouble_t + cnp.complex64_t + cnp.complex128_t + +ctypedef fused np_complex_numeric_t: + cnp.complex64_t + cnp.complex128_t + + +cdef void swap_c_and_f_layout(lapack_t *a, lapack_t *b, int r, int c) noexcept nogil +cdef (int, int) band_check_internal_c(np_numeric_t[:, ::1]A) noexcept nogil +cdef bint is_sym_her_real_c_internal(np_numeric_t[:, ::1]A) noexcept nogil +cdef bint is_sym_her_complex_c_internal(np_complex_numeric_t[:, ::1]A) noexcept nogil diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_cythonized_array_utils.pyi b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_cythonized_array_utils.pyi new file mode 100644 index 0000000000000000000000000000000000000000..5633cb61ecf3a90eba901120f64fa6cc6634fa5a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_cythonized_array_utils.pyi @@ -0,0 +1,16 @@ +from numpy.typing import NDArray +from typing import Any + +def bandwidth(a: NDArray[Any]) -> tuple[int, int]: ... + +def issymmetric( + a: NDArray[Any], + atol: None | float = ..., + rtol: None | float = ..., +) -> bool: ... + +def ishermitian( + a: NDArray[Any], + atol: None | float = ..., + rtol: None | float = ..., +) -> bool: ... diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_decomp.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_decomp.py new file mode 100644 index 0000000000000000000000000000000000000000..c520d6b04b6bf0a22c4fcad62d98a17faea7c9fd --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_decomp.py @@ -0,0 +1,1632 @@ +# +# Author: Pearu Peterson, March 2002 +# +# additions by Travis Oliphant, March 2002 +# additions by Eric Jones, June 2002 +# additions by Johannes Loehnert, June 2006 +# additions by Bart Vandereycken, June 2006 +# additions by Andrew D Straw, May 2007 +# additions by Tiziano Zito, November 2008 +# +# April 2010: Functions for LU, QR, SVD, Schur, and Cholesky decompositions +# were moved to their own files. Still in this file are functions for +# eigenstuff and for the Hessenberg form. + +__all__ = ['eig', 'eigvals', 'eigh', 'eigvalsh', + 'eig_banded', 'eigvals_banded', + 'eigh_tridiagonal', 'eigvalsh_tridiagonal', 'hessenberg', 'cdf2rdf'] + +import numpy as np +from numpy import (array, isfinite, inexact, nonzero, iscomplexobj, + flatnonzero, conj, asarray, argsort, empty, + iscomplex, zeros, einsum, eye, inf) +# Local imports +from scipy._lib._util import _asarray_validated +from ._misc import LinAlgError, _datacopied, norm +from .lapack import get_lapack_funcs, _compute_lwork + + +_I = np.array(1j, dtype='F') + + +def _make_complex_eigvecs(w, vin, dtype): + """ + Produce complex-valued eigenvectors from LAPACK DGGEV real-valued output + """ + # - see LAPACK man page DGGEV at ALPHAI + v = np.array(vin, dtype=dtype) + m = (w.imag > 0) + m[:-1] |= (w.imag[1:] < 0) # workaround for LAPACK bug, cf. ticket #709 + for i in flatnonzero(m): + v.imag[:, i] = vin[:, i+1] + conj(v[:, i], v[:, i+1]) + return v + + +def _make_eigvals(alpha, beta, homogeneous_eigvals): + if homogeneous_eigvals: + if beta is None: + return np.vstack((alpha, np.ones_like(alpha))) + else: + return np.vstack((alpha, beta)) + else: + if beta is None: + return alpha + else: + w = np.empty_like(alpha) + alpha_zero = (alpha == 0) + beta_zero = (beta == 0) + beta_nonzero = ~beta_zero + w[beta_nonzero] = alpha[beta_nonzero]/beta[beta_nonzero] + # Use np.inf for complex values too since + # 1/np.inf = 0, i.e., it correctly behaves as projective + # infinity. + w[~alpha_zero & beta_zero] = np.inf + if np.all(alpha.imag == 0): + w[alpha_zero & beta_zero] = np.nan + else: + w[alpha_zero & beta_zero] = complex(np.nan, np.nan) + return w + + +def _geneig(a1, b1, left, right, overwrite_a, overwrite_b, + homogeneous_eigvals): + ggev, = get_lapack_funcs(('ggev',), (a1, b1)) + cvl, cvr = left, right + res = ggev(a1, b1, lwork=-1) + lwork = res[-2][0].real.astype(np.int_) + if ggev.typecode in 'cz': + alpha, beta, vl, vr, work, info = ggev(a1, b1, cvl, cvr, lwork, + overwrite_a, overwrite_b) + w = _make_eigvals(alpha, beta, homogeneous_eigvals) + else: + alphar, alphai, beta, vl, vr, work, info = ggev(a1, b1, cvl, cvr, + lwork, overwrite_a, + overwrite_b) + alpha = alphar + _I * alphai + w = _make_eigvals(alpha, beta, homogeneous_eigvals) + _check_info(info, 'generalized eig algorithm (ggev)') + + only_real = np.all(w.imag == 0.0) + if not (ggev.typecode in 'cz' or only_real): + t = w.dtype.char + if left: + vl = _make_complex_eigvecs(w, vl, t) + if right: + vr = _make_complex_eigvecs(w, vr, t) + + # the eigenvectors returned by the lapack function are NOT normalized + for i in range(vr.shape[0]): + if right: + vr[:, i] /= norm(vr[:, i]) + if left: + vl[:, i] /= norm(vl[:, i]) + + if not (left or right): + return w + if left: + if right: + return w, vl, vr + return w, vl + return w, vr + + +def eig(a, b=None, left=False, right=True, overwrite_a=False, + overwrite_b=False, check_finite=True, homogeneous_eigvals=False): + """ + Solve an ordinary or generalized eigenvalue problem of a square matrix. + + Find eigenvalues w and right or left eigenvectors of a general matrix:: + + a vr[:,i] = w[i] b vr[:,i] + a.H vl[:,i] = w[i].conj() b.H vl[:,i] + + where ``.H`` is the Hermitian conjugation. + + Parameters + ---------- + a : (M, M) array_like + A complex or real matrix whose eigenvalues and eigenvectors + will be computed. + b : (M, M) array_like, optional + Right-hand side matrix in a generalized eigenvalue problem. + Default is None, identity matrix is assumed. + left : bool, optional + Whether to calculate and return left eigenvectors. Default is False. + right : bool, optional + Whether to calculate and return right eigenvectors. Default is True. + overwrite_a : bool, optional + Whether to overwrite `a`; may improve performance. Default is False. + overwrite_b : bool, optional + Whether to overwrite `b`; may improve performance. Default is False. + check_finite : bool, optional + Whether to check that the input matrices contain only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + homogeneous_eigvals : bool, optional + If True, return the eigenvalues in homogeneous coordinates. + In this case ``w`` is a (2, M) array so that:: + + w[1,i] a vr[:,i] = w[0,i] b vr[:,i] + + Default is False. + + Returns + ------- + w : (M,) or (2, M) double or complex ndarray + The eigenvalues, each repeated according to its + multiplicity. The shape is (M,) unless + ``homogeneous_eigvals=True``. + vl : (M, M) double or complex ndarray + The left eigenvector corresponding to the eigenvalue + ``w[i]`` is the column ``vl[:,i]``. Only returned if ``left=True``. + The left eigenvector is not normalized. + vr : (M, M) double or complex ndarray + The normalized right eigenvector corresponding to the eigenvalue + ``w[i]`` is the column ``vr[:,i]``. Only returned if ``right=True``. + + Raises + ------ + LinAlgError + If eigenvalue computation does not converge. + + See Also + -------- + eigvals : eigenvalues of general arrays + eigh : Eigenvalues and right eigenvectors for symmetric/Hermitian arrays. + eig_banded : eigenvalues and right eigenvectors for symmetric/Hermitian + band matrices + eigh_tridiagonal : eigenvalues and right eiegenvectors for + symmetric/Hermitian tridiagonal matrices + + Examples + -------- + >>> import numpy as np + >>> from scipy import linalg + >>> a = np.array([[0., -1.], [1., 0.]]) + >>> linalg.eigvals(a) + array([0.+1.j, 0.-1.j]) + + >>> b = np.array([[0., 1.], [1., 1.]]) + >>> linalg.eigvals(a, b) + array([ 1.+0.j, -1.+0.j]) + + >>> a = np.array([[3., 0., 0.], [0., 8., 0.], [0., 0., 7.]]) + >>> linalg.eigvals(a, homogeneous_eigvals=True) + array([[3.+0.j, 8.+0.j, 7.+0.j], + [1.+0.j, 1.+0.j, 1.+0.j]]) + + >>> a = np.array([[0., -1.], [1., 0.]]) + >>> linalg.eigvals(a) == linalg.eig(a)[0] + array([ True, True]) + >>> linalg.eig(a, left=True, right=False)[1] # normalized left eigenvector + array([[-0.70710678+0.j , -0.70710678-0.j ], + [-0. +0.70710678j, -0. -0.70710678j]]) + >>> linalg.eig(a, left=False, right=True)[1] # normalized right eigenvector + array([[0.70710678+0.j , 0.70710678-0.j ], + [0. -0.70710678j, 0. +0.70710678j]]) + + + + """ + a1 = _asarray_validated(a, check_finite=check_finite) + if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]: + raise ValueError('expected square matrix') + + # accommodate square empty matrices + if a1.size == 0: + w_n, vr_n = eig(np.eye(2, dtype=a1.dtype)) + w = np.empty_like(a1, shape=(0,), dtype=w_n.dtype) + w = _make_eigvals(w, None, homogeneous_eigvals) + vl = np.empty_like(a1, shape=(0, 0), dtype=vr_n.dtype) + vr = np.empty_like(a1, shape=(0, 0), dtype=vr_n.dtype) + if not (left or right): + return w + if left: + if right: + return w, vl, vr + return w, vl + return w, vr + + overwrite_a = overwrite_a or (_datacopied(a1, a)) + if b is not None: + b1 = _asarray_validated(b, check_finite=check_finite) + overwrite_b = overwrite_b or _datacopied(b1, b) + if len(b1.shape) != 2 or b1.shape[0] != b1.shape[1]: + raise ValueError('expected square matrix') + if b1.shape != a1.shape: + raise ValueError('a and b must have the same shape') + return _geneig(a1, b1, left, right, overwrite_a, overwrite_b, + homogeneous_eigvals) + + geev, geev_lwork = get_lapack_funcs(('geev', 'geev_lwork'), (a1,)) + compute_vl, compute_vr = left, right + + lwork = _compute_lwork(geev_lwork, a1.shape[0], + compute_vl=compute_vl, + compute_vr=compute_vr) + + if geev.typecode in 'cz': + w, vl, vr, info = geev(a1, lwork=lwork, + compute_vl=compute_vl, + compute_vr=compute_vr, + overwrite_a=overwrite_a) + w = _make_eigvals(w, None, homogeneous_eigvals) + else: + wr, wi, vl, vr, info = geev(a1, lwork=lwork, + compute_vl=compute_vl, + compute_vr=compute_vr, + overwrite_a=overwrite_a) + w = wr + _I * wi + w = _make_eigvals(w, None, homogeneous_eigvals) + + _check_info(info, 'eig algorithm (geev)', + positive='did not converge (only eigenvalues ' + 'with order >= %d have converged)') + + only_real = np.all(w.imag == 0.0) + if not (geev.typecode in 'cz' or only_real): + t = w.dtype.char + if left: + vl = _make_complex_eigvecs(w, vl, t) + if right: + vr = _make_complex_eigvecs(w, vr, t) + if not (left or right): + return w + if left: + if right: + return w, vl, vr + return w, vl + return w, vr + + +def eigh(a, b=None, *, lower=True, eigvals_only=False, overwrite_a=False, + overwrite_b=False, type=1, check_finite=True, subset_by_index=None, + subset_by_value=None, driver=None): + """ + Solve a standard or generalized eigenvalue problem for a complex + Hermitian or real symmetric matrix. + + Find eigenvalues array ``w`` and optionally eigenvectors array ``v`` of + array ``a``, where ``b`` is positive definite such that for every + eigenvalue λ (i-th entry of w) and its eigenvector ``vi`` (i-th column of + ``v``) satisfies:: + + a @ vi = λ * b @ vi + vi.conj().T @ a @ vi = λ + vi.conj().T @ b @ vi = 1 + + In the standard problem, ``b`` is assumed to be the identity matrix. + + Parameters + ---------- + a : (M, M) array_like + A complex Hermitian or real symmetric matrix whose eigenvalues and + eigenvectors will be computed. + b : (M, M) array_like, optional + A complex Hermitian or real symmetric definite positive matrix in. + If omitted, identity matrix is assumed. + lower : bool, optional + Whether the pertinent array data is taken from the lower or upper + triangle of ``a`` and, if applicable, ``b``. (Default: lower) + eigvals_only : bool, optional + Whether to calculate only eigenvalues and no eigenvectors. + (Default: both are calculated) + subset_by_index : iterable, optional + If provided, this two-element iterable defines the start and the end + indices of the desired eigenvalues (ascending order and 0-indexed). + To return only the second smallest to fifth smallest eigenvalues, + ``[1, 4]`` is used. ``[n-3, n-1]`` returns the largest three. Only + available with "evr", "evx", and "gvx" drivers. The entries are + directly converted to integers via ``int()``. + subset_by_value : iterable, optional + If provided, this two-element iterable defines the half-open interval + ``(a, b]`` that, if any, only the eigenvalues between these values + are returned. Only available with "evr", "evx", and "gvx" drivers. Use + ``np.inf`` for the unconstrained ends. + driver : str, optional + Defines which LAPACK driver should be used. Valid options are "ev", + "evd", "evr", "evx" for standard problems and "gv", "gvd", "gvx" for + generalized (where b is not None) problems. See the Notes section. + The default for standard problems is "evr". For generalized problems, + "gvd" is used for full set, and "gvx" for subset requested cases. + type : int, optional + For the generalized problems, this keyword specifies the problem type + to be solved for ``w`` and ``v`` (only takes 1, 2, 3 as possible + inputs):: + + 1 => a @ v = w @ b @ v + 2 => a @ b @ v = w @ v + 3 => b @ a @ v = w @ v + + This keyword is ignored for standard problems. + overwrite_a : bool, optional + Whether to overwrite data in ``a`` (may improve performance). Default + is False. + overwrite_b : bool, optional + Whether to overwrite data in ``b`` (may improve performance). Default + is False. + check_finite : bool, optional + Whether to check that the input matrices contain only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + + Returns + ------- + w : (N,) ndarray + The N (N<=M) selected eigenvalues, in ascending order, each + repeated according to its multiplicity. + v : (M, N) ndarray + The normalized eigenvector corresponding to the eigenvalue ``w[i]`` is + the column ``v[:,i]``. Only returned if ``eigvals_only=False``. + + Raises + ------ + LinAlgError + If eigenvalue computation does not converge, an error occurred, or + b matrix is not definite positive. Note that if input matrices are + not symmetric or Hermitian, no error will be reported but results will + be wrong. + + See Also + -------- + eigvalsh : eigenvalues of symmetric or Hermitian arrays + eig : eigenvalues and right eigenvectors for non-symmetric arrays + eigh_tridiagonal : eigenvalues and right eiegenvectors for + symmetric/Hermitian tridiagonal matrices + + Notes + ----- + This function does not check the input array for being Hermitian/symmetric + in order to allow for representing arrays with only their upper/lower + triangular parts. Also, note that even though not taken into account, + finiteness check applies to the whole array and unaffected by "lower" + keyword. + + This function uses LAPACK drivers for computations in all possible keyword + combinations, prefixed with ``sy`` if arrays are real and ``he`` if + complex, e.g., a float array with "evr" driver is solved via + "syevr", complex arrays with "gvx" driver problem is solved via "hegvx" + etc. + + As a brief summary, the slowest and the most robust driver is the + classical ``ev`` which uses symmetric QR. ``evr`` is seen as + the optimal choice for the most general cases. However, there are certain + occasions that ``evd`` computes faster at the expense of more + memory usage. ``evx``, while still being faster than ``ev``, + often performs worse than the rest except when very few eigenvalues are + requested for large arrays though there is still no performance guarantee. + + Note that the underlying LAPACK algorithms are different depending on whether + `eigvals_only` is True or False --- thus the eigenvalues may differ + depending on whether eigenvectors are requested or not. The difference is + generally of the order of machine epsilon times the largest eigenvalue, + so is likely only visible for zero or nearly zero eigenvalues. + + For the generalized problem, normalization with respect to the given + type argument:: + + type 1 and 3 : v.conj().T @ a @ v = w + type 2 : inv(v).conj().T @ a @ inv(v) = w + + type 1 or 2 : v.conj().T @ b @ v = I + type 3 : v.conj().T @ inv(b) @ v = I + + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import eigh + >>> A = np.array([[6, 3, 1, 5], [3, 0, 5, 1], [1, 5, 6, 2], [5, 1, 2, 2]]) + >>> w, v = eigh(A) + >>> np.allclose(A @ v - v @ np.diag(w), np.zeros((4, 4))) + True + + Request only the eigenvalues + + >>> w = eigh(A, eigvals_only=True) + + Request eigenvalues that are less than 10. + + >>> A = np.array([[34, -4, -10, -7, 2], + ... [-4, 7, 2, 12, 0], + ... [-10, 2, 44, 2, -19], + ... [-7, 12, 2, 79, -34], + ... [2, 0, -19, -34, 29]]) + >>> eigh(A, eigvals_only=True, subset_by_value=[-np.inf, 10]) + array([6.69199443e-07, 9.11938152e+00]) + + Request the second smallest eigenvalue and its eigenvector + + >>> w, v = eigh(A, subset_by_index=[1, 1]) + >>> w + array([9.11938152]) + >>> v.shape # only a single column is returned + (5, 1) + + """ + # set lower + uplo = 'L' if lower else 'U' + # Set job for Fortran routines + _job = 'N' if eigvals_only else 'V' + + drv_str = [None, "ev", "evd", "evr", "evx", "gv", "gvd", "gvx"] + if driver not in drv_str: + raise ValueError('"{}" is unknown. Possible values are "None", "{}".' + ''.format(driver, '", "'.join(drv_str[1:]))) + + a1 = _asarray_validated(a, check_finite=check_finite) + if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]: + raise ValueError('expected square "a" matrix') + + # accommodate square empty matrices + if a1.size == 0: + w_n, v_n = eigh(np.eye(2, dtype=a1.dtype)) + + w = np.empty_like(a1, shape=(0,), dtype=w_n.dtype) + v = np.empty_like(a1, shape=(0, 0), dtype=v_n.dtype) + if eigvals_only: + return w + else: + return w, v + + overwrite_a = overwrite_a or (_datacopied(a1, a)) + cplx = True if iscomplexobj(a1) else False + n = a1.shape[0] + drv_args = {'overwrite_a': overwrite_a} + + if b is not None: + b1 = _asarray_validated(b, check_finite=check_finite) + overwrite_b = overwrite_b or _datacopied(b1, b) + if len(b1.shape) != 2 or b1.shape[0] != b1.shape[1]: + raise ValueError('expected square "b" matrix') + + if b1.shape != a1.shape: + raise ValueError(f"wrong b dimensions {b1.shape}, should be {a1.shape}") + + if type not in [1, 2, 3]: + raise ValueError('"type" keyword only accepts 1, 2, and 3.') + + cplx = True if iscomplexobj(b1) else (cplx or False) + drv_args.update({'overwrite_b': overwrite_b, 'itype': type}) + + subset = (subset_by_index is not None) or (subset_by_value is not None) + + # Both subsets can't be given + if subset_by_index and subset_by_value: + raise ValueError('Either index or value subset can be requested.') + + # Check indices if given + if subset_by_index: + lo, hi = (int(x) for x in subset_by_index) + if not (0 <= lo <= hi < n): + raise ValueError('Requested eigenvalue indices are not valid. ' + f'Valid range is [0, {n-1}] and start <= end, but ' + f'start={lo}, end={hi} is given') + # fortran is 1-indexed + drv_args.update({'range': 'I', 'il': lo + 1, 'iu': hi + 1}) + + if subset_by_value: + lo, hi = subset_by_value + if not (-inf <= lo < hi <= inf): + raise ValueError('Requested eigenvalue bounds are not valid. ' + 'Valid range is (-inf, inf) and low < high, but ' + f'low={lo}, high={hi} is given') + + drv_args.update({'range': 'V', 'vl': lo, 'vu': hi}) + + # fix prefix for lapack routines + pfx = 'he' if cplx else 'sy' + + # decide on the driver if not given + # first early exit on incompatible choice + if driver: + if b is None and (driver in ["gv", "gvd", "gvx"]): + raise ValueError(f'{driver} requires input b array to be supplied ' + 'for generalized eigenvalue problems.') + if (b is not None) and (driver in ['ev', 'evd', 'evr', 'evx']): + raise ValueError(f'"{driver}" does not accept input b array ' + 'for standard eigenvalue problems.') + if subset and (driver in ["ev", "evd", "gv", "gvd"]): + raise ValueError(f'"{driver}" cannot compute subsets of eigenvalues') + + # Default driver is evr and gvd + else: + driver = "evr" if b is None else ("gvx" if subset else "gvd") + + lwork_spec = { + 'syevd': ['lwork', 'liwork'], + 'syevr': ['lwork', 'liwork'], + 'heevd': ['lwork', 'liwork', 'lrwork'], + 'heevr': ['lwork', 'lrwork', 'liwork'], + } + + if b is None: # Standard problem + drv, drvlw = get_lapack_funcs((pfx + driver, pfx+driver+'_lwork'), + [a1]) + clw_args = {'n': n, 'lower': lower} + if driver == 'evd': + clw_args.update({'compute_v': 0 if _job == "N" else 1}) + + lw = _compute_lwork(drvlw, **clw_args) + # Multiple lwork vars + if isinstance(lw, tuple): + lwork_args = dict(zip(lwork_spec[pfx+driver], lw)) + else: + lwork_args = {'lwork': lw} + + drv_args.update({'lower': lower, 'compute_v': 0 if _job == "N" else 1}) + w, v, *other_args, info = drv(a=a1, **drv_args, **lwork_args) + + else: # Generalized problem + # 'gvd' doesn't have lwork query + if driver == "gvd": + drv = get_lapack_funcs(pfx + "gvd", [a1, b1]) + lwork_args = {} + else: + drv, drvlw = get_lapack_funcs((pfx + driver, pfx+driver+'_lwork'), + [a1, b1]) + # generalized drivers use uplo instead of lower + lw = _compute_lwork(drvlw, n, uplo=uplo) + lwork_args = {'lwork': lw} + + drv_args.update({'uplo': uplo, 'jobz': _job}) + + w, v, *other_args, info = drv(a=a1, b=b1, **drv_args, **lwork_args) + + # m is always the first extra argument + w = w[:other_args[0]] if subset else w + v = v[:, :other_args[0]] if (subset and not eigvals_only) else v + + # Check if we had a successful exit + if info == 0: + if eigvals_only: + return w + else: + return w, v + else: + if info < -1: + raise LinAlgError(f'Illegal value in argument {-info} of internal ' + f'{drv.typecode + pfx + driver}') + elif info > n: + raise LinAlgError(f'The leading minor of order {info-n} of B is not ' + 'positive definite. The factorization of B ' + 'could not be completed and no eigenvalues ' + 'or eigenvectors were computed.') + else: + drv_err = {'ev': 'The algorithm failed to converge; {} ' + 'off-diagonal elements of an intermediate ' + 'tridiagonal form did not converge to zero.', + 'evx': '{} eigenvectors failed to converge.', + 'evd': 'The algorithm failed to compute an eigenvalue ' + 'while working on the submatrix lying in rows ' + 'and columns {0}/{1} through mod({0},{1}).', + 'evr': 'Internal Error.' + } + if driver in ['ev', 'gv']: + msg = drv_err['ev'].format(info) + elif driver in ['evx', 'gvx']: + msg = drv_err['evx'].format(info) + elif driver in ['evd', 'gvd']: + if eigvals_only: + msg = drv_err['ev'].format(info) + else: + msg = drv_err['evd'].format(info, n+1) + else: + msg = drv_err['evr'] + + raise LinAlgError(msg) + + +_conv_dict = {0: 0, 1: 1, 2: 2, + 'all': 0, 'value': 1, 'index': 2, + 'a': 0, 'v': 1, 'i': 2} + + +def _check_select(select, select_range, max_ev, max_len): + """Check that select is valid, convert to Fortran style.""" + if isinstance(select, str): + select = select.lower() + try: + select = _conv_dict[select] + except KeyError as e: + raise ValueError('invalid argument for select') from e + vl, vu = 0., 1. + il = iu = 1 + if select != 0: # (non-all) + sr = asarray(select_range) + if sr.ndim != 1 or sr.size != 2 or sr[1] < sr[0]: + raise ValueError('select_range must be a 2-element array-like ' + 'in nondecreasing order') + if select == 1: # (value) + vl, vu = sr + if max_ev == 0: + max_ev = max_len + else: # 2 (index) + if sr.dtype.char.lower() not in 'hilqp': + raise ValueError( + f'when using select="i", select_range must ' + f'contain integers, got dtype {sr.dtype} ({sr.dtype.char})' + ) + # translate Python (0 ... N-1) into Fortran (1 ... N) with + 1 + il, iu = sr + 1 + if min(il, iu) < 1 or max(il, iu) > max_len: + raise ValueError('select_range out of bounds') + max_ev = iu - il + 1 + return select, vl, vu, il, iu, max_ev + + +def eig_banded(a_band, lower=False, eigvals_only=False, overwrite_a_band=False, + select='a', select_range=None, max_ev=0, check_finite=True): + """ + Solve real symmetric or complex Hermitian band matrix eigenvalue problem. + + Find eigenvalues w and optionally right eigenvectors v of a:: + + a v[:,i] = w[i] v[:,i] + v.H v = identity + + The matrix a is stored in a_band either in lower diagonal or upper + diagonal ordered form: + + a_band[u + i - j, j] == a[i,j] (if upper form; i <= j) + a_band[ i - j, j] == a[i,j] (if lower form; i >= j) + + where u is the number of bands above the diagonal. + + Example of a_band (shape of a is (6,6), u=2):: + + upper form: + * * a02 a13 a24 a35 + * a01 a12 a23 a34 a45 + a00 a11 a22 a33 a44 a55 + + lower form: + a00 a11 a22 a33 a44 a55 + a10 a21 a32 a43 a54 * + a20 a31 a42 a53 * * + + Cells marked with * are not used. + + Parameters + ---------- + a_band : (u+1, M) array_like + The bands of the M by M matrix a. + lower : bool, optional + Is the matrix in the lower form. (Default is upper form) + eigvals_only : bool, optional + Compute only the eigenvalues and no eigenvectors. + (Default: calculate also eigenvectors) + overwrite_a_band : bool, optional + Discard data in a_band (may enhance performance) + select : {'a', 'v', 'i'}, optional + Which eigenvalues to calculate + + ====== ======================================== + select calculated + ====== ======================================== + 'a' All eigenvalues + 'v' Eigenvalues in the interval (min, max] + 'i' Eigenvalues with indices min <= i <= max + ====== ======================================== + select_range : (min, max), optional + Range of selected eigenvalues + max_ev : int, optional + For select=='v', maximum number of eigenvalues expected. + For other values of select, has no meaning. + + In doubt, leave this parameter untouched. + + check_finite : bool, optional + Whether to check that the input matrix contains only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + + Returns + ------- + w : (M,) ndarray + The eigenvalues, in ascending order, each repeated according to its + multiplicity. + v : (M, M) float or complex ndarray + The normalized eigenvector corresponding to the eigenvalue w[i] is + the column v[:,i]. Only returned if ``eigvals_only=False``. + + Raises + ------ + LinAlgError + If eigenvalue computation does not converge. + + See Also + -------- + eigvals_banded : eigenvalues for symmetric/Hermitian band matrices + eig : eigenvalues and right eigenvectors of general arrays. + eigh : eigenvalues and right eigenvectors for symmetric/Hermitian arrays + eigh_tridiagonal : eigenvalues and right eigenvectors for + symmetric/Hermitian tridiagonal matrices + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import eig_banded + >>> A = np.array([[1, 5, 2, 0], [5, 2, 5, 2], [2, 5, 3, 5], [0, 2, 5, 4]]) + >>> Ab = np.array([[1, 2, 3, 4], [5, 5, 5, 0], [2, 2, 0, 0]]) + >>> w, v = eig_banded(Ab, lower=True) + >>> np.allclose(A @ v - v @ np.diag(w), np.zeros((4, 4))) + True + >>> w = eig_banded(Ab, lower=True, eigvals_only=True) + >>> w + array([-4.26200532, -2.22987175, 3.95222349, 12.53965359]) + + Request only the eigenvalues between ``[-3, 4]`` + + >>> w, v = eig_banded(Ab, lower=True, select='v', select_range=[-3, 4]) + >>> w + array([-2.22987175, 3.95222349]) + + """ + if eigvals_only or overwrite_a_band: + a1 = _asarray_validated(a_band, check_finite=check_finite) + overwrite_a_band = overwrite_a_band or (_datacopied(a1, a_band)) + else: + a1 = array(a_band) + if issubclass(a1.dtype.type, inexact) and not isfinite(a1).all(): + raise ValueError("array must not contain infs or NaNs") + overwrite_a_band = 1 + + if len(a1.shape) != 2: + raise ValueError('expected a 2-D array') + + # accommodate square empty matrices + if a1.size == 0: + w_n, v_n = eig_banded(np.array([[0, 0], [1, 1]], dtype=a1.dtype)) + + w = np.empty_like(a1, shape=(0,), dtype=w_n.dtype) + v = np.empty_like(a1, shape=(0, 0), dtype=v_n.dtype) + if eigvals_only: + return w + else: + return w, v + + select, vl, vu, il, iu, max_ev = _check_select( + select, select_range, max_ev, a1.shape[1]) + + del select_range + if select == 0: + if a1.dtype.char in 'GFD': + # FIXME: implement this somewhen, for now go with builtin values + # FIXME: calc optimal lwork by calling ?hbevd(lwork=-1) + # or by using calc_lwork.f ??? + # lwork = calc_lwork.hbevd(bevd.typecode, a1.shape[0], lower) + internal_name = 'hbevd' + else: # a1.dtype.char in 'fd': + # FIXME: implement this somewhen, for now go with builtin values + # see above + # lwork = calc_lwork.sbevd(bevd.typecode, a1.shape[0], lower) + internal_name = 'sbevd' + bevd, = get_lapack_funcs((internal_name,), (a1,)) + w, v, info = bevd(a1, compute_v=not eigvals_only, + lower=lower, overwrite_ab=overwrite_a_band) + else: # select in [1, 2] + if eigvals_only: + max_ev = 1 + # calculate optimal abstol for dsbevx (see manpage) + if a1.dtype.char in 'fF': # single precision + lamch, = get_lapack_funcs(('lamch',), (array(0, dtype='f'),)) + else: + lamch, = get_lapack_funcs(('lamch',), (array(0, dtype='d'),)) + abstol = 2 * lamch('s') + if a1.dtype.char in 'GFD': + internal_name = 'hbevx' + else: # a1.dtype.char in 'gfd' + internal_name = 'sbevx' + bevx, = get_lapack_funcs((internal_name,), (a1,)) + w, v, m, ifail, info = bevx( + a1, vl, vu, il, iu, compute_v=not eigvals_only, mmax=max_ev, + range=select, lower=lower, overwrite_ab=overwrite_a_band, + abstol=abstol) + # crop off w and v + w = w[:m] + if not eigvals_only: + v = v[:, :m] + _check_info(info, internal_name) + + if eigvals_only: + return w + return w, v + + +def eigvals(a, b=None, overwrite_a=False, check_finite=True, + homogeneous_eigvals=False): + """ + Compute eigenvalues from an ordinary or generalized eigenvalue problem. + + Find eigenvalues of a general matrix:: + + a vr[:,i] = w[i] b vr[:,i] + + Parameters + ---------- + a : (M, M) array_like + A complex or real matrix whose eigenvalues and eigenvectors + will be computed. + b : (M, M) array_like, optional + Right-hand side matrix in a generalized eigenvalue problem. + If omitted, identity matrix is assumed. + overwrite_a : bool, optional + Whether to overwrite data in a (may improve performance) + check_finite : bool, optional + Whether to check that the input matrices contain only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities + or NaNs. + homogeneous_eigvals : bool, optional + If True, return the eigenvalues in homogeneous coordinates. + In this case ``w`` is a (2, M) array so that:: + + w[1,i] a vr[:,i] = w[0,i] b vr[:,i] + + Default is False. + + Returns + ------- + w : (M,) or (2, M) double or complex ndarray + The eigenvalues, each repeated according to its multiplicity + but not in any specific order. The shape is (M,) unless + ``homogeneous_eigvals=True``. + + Raises + ------ + LinAlgError + If eigenvalue computation does not converge + + See Also + -------- + eig : eigenvalues and right eigenvectors of general arrays. + eigvalsh : eigenvalues of symmetric or Hermitian arrays + eigvals_banded : eigenvalues for symmetric/Hermitian band matrices + eigvalsh_tridiagonal : eigenvalues of symmetric/Hermitian tridiagonal + matrices + + Examples + -------- + >>> import numpy as np + >>> from scipy import linalg + >>> a = np.array([[0., -1.], [1., 0.]]) + >>> linalg.eigvals(a) + array([0.+1.j, 0.-1.j]) + + >>> b = np.array([[0., 1.], [1., 1.]]) + >>> linalg.eigvals(a, b) + array([ 1.+0.j, -1.+0.j]) + + >>> a = np.array([[3., 0., 0.], [0., 8., 0.], [0., 0., 7.]]) + >>> linalg.eigvals(a, homogeneous_eigvals=True) + array([[3.+0.j, 8.+0.j, 7.+0.j], + [1.+0.j, 1.+0.j, 1.+0.j]]) + + """ + return eig(a, b=b, left=0, right=0, overwrite_a=overwrite_a, + check_finite=check_finite, + homogeneous_eigvals=homogeneous_eigvals) + + +def eigvalsh(a, b=None, *, lower=True, overwrite_a=False, + overwrite_b=False, type=1, check_finite=True, subset_by_index=None, + subset_by_value=None, driver=None): + """ + Solves a standard or generalized eigenvalue problem for a complex + Hermitian or real symmetric matrix. + + Find eigenvalues array ``w`` of array ``a``, where ``b`` is positive + definite such that for every eigenvalue λ (i-th entry of w) and its + eigenvector vi (i-th column of v) satisfies:: + + a @ vi = λ * b @ vi + vi.conj().T @ a @ vi = λ + vi.conj().T @ b @ vi = 1 + + In the standard problem, b is assumed to be the identity matrix. + + Parameters + ---------- + a : (M, M) array_like + A complex Hermitian or real symmetric matrix whose eigenvalues will + be computed. + b : (M, M) array_like, optional + A complex Hermitian or real symmetric definite positive matrix in. + If omitted, identity matrix is assumed. + lower : bool, optional + Whether the pertinent array data is taken from the lower or upper + triangle of ``a`` and, if applicable, ``b``. (Default: lower) + overwrite_a : bool, optional + Whether to overwrite data in ``a`` (may improve performance). Default + is False. + overwrite_b : bool, optional + Whether to overwrite data in ``b`` (may improve performance). Default + is False. + type : int, optional + For the generalized problems, this keyword specifies the problem type + to be solved for ``w`` and ``v`` (only takes 1, 2, 3 as possible + inputs):: + + 1 => a @ v = w @ b @ v + 2 => a @ b @ v = w @ v + 3 => b @ a @ v = w @ v + + This keyword is ignored for standard problems. + check_finite : bool, optional + Whether to check that the input matrices contain only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + subset_by_index : iterable, optional + If provided, this two-element iterable defines the start and the end + indices of the desired eigenvalues (ascending order and 0-indexed). + To return only the second smallest to fifth smallest eigenvalues, + ``[1, 4]`` is used. ``[n-3, n-1]`` returns the largest three. Only + available with "evr", "evx", and "gvx" drivers. The entries are + directly converted to integers via ``int()``. + subset_by_value : iterable, optional + If provided, this two-element iterable defines the half-open interval + ``(a, b]`` that, if any, only the eigenvalues between these values + are returned. Only available with "evr", "evx", and "gvx" drivers. Use + ``np.inf`` for the unconstrained ends. + driver : str, optional + Defines which LAPACK driver should be used. Valid options are "ev", + "evd", "evr", "evx" for standard problems and "gv", "gvd", "gvx" for + generalized (where b is not None) problems. See the Notes section of + `scipy.linalg.eigh`. + + Returns + ------- + w : (N,) ndarray + The N (N<=M) selected eigenvalues, in ascending order, each + repeated according to its multiplicity. + + Raises + ------ + LinAlgError + If eigenvalue computation does not converge, an error occurred, or + b matrix is not definite positive. Note that if input matrices are + not symmetric or Hermitian, no error will be reported but results will + be wrong. + + See Also + -------- + eigh : eigenvalues and right eigenvectors for symmetric/Hermitian arrays + eigvals : eigenvalues of general arrays + eigvals_banded : eigenvalues for symmetric/Hermitian band matrices + eigvalsh_tridiagonal : eigenvalues of symmetric/Hermitian tridiagonal + matrices + + Notes + ----- + This function does not check the input array for being Hermitian/symmetric + in order to allow for representing arrays with only their upper/lower + triangular parts. + + This function serves as a one-liner shorthand for `scipy.linalg.eigh` with + the option ``eigvals_only=True`` to get the eigenvalues and not the + eigenvectors. Here it is kept as a legacy convenience. It might be + beneficial to use the main function to have full control and to be a bit + more pythonic. + + Examples + -------- + For more examples see `scipy.linalg.eigh`. + + >>> import numpy as np + >>> from scipy.linalg import eigvalsh + >>> A = np.array([[6, 3, 1, 5], [3, 0, 5, 1], [1, 5, 6, 2], [5, 1, 2, 2]]) + >>> w = eigvalsh(A) + >>> w + array([-3.74637491, -0.76263923, 6.08502336, 12.42399079]) + + """ + return eigh(a, b=b, lower=lower, eigvals_only=True, overwrite_a=overwrite_a, + overwrite_b=overwrite_b, type=type, check_finite=check_finite, + subset_by_index=subset_by_index, subset_by_value=subset_by_value, + driver=driver) + + +def eigvals_banded(a_band, lower=False, overwrite_a_band=False, + select='a', select_range=None, check_finite=True): + """ + Solve real symmetric or complex Hermitian band matrix eigenvalue problem. + + Find eigenvalues w of a:: + + a v[:,i] = w[i] v[:,i] + v.H v = identity + + The matrix a is stored in a_band either in lower diagonal or upper + diagonal ordered form: + + a_band[u + i - j, j] == a[i,j] (if upper form; i <= j) + a_band[ i - j, j] == a[i,j] (if lower form; i >= j) + + where u is the number of bands above the diagonal. + + Example of a_band (shape of a is (6,6), u=2):: + + upper form: + * * a02 a13 a24 a35 + * a01 a12 a23 a34 a45 + a00 a11 a22 a33 a44 a55 + + lower form: + a00 a11 a22 a33 a44 a55 + a10 a21 a32 a43 a54 * + a20 a31 a42 a53 * * + + Cells marked with * are not used. + + Parameters + ---------- + a_band : (u+1, M) array_like + The bands of the M by M matrix a. + lower : bool, optional + Is the matrix in the lower form. (Default is upper form) + overwrite_a_band : bool, optional + Discard data in a_band (may enhance performance) + select : {'a', 'v', 'i'}, optional + Which eigenvalues to calculate + + ====== ======================================== + select calculated + ====== ======================================== + 'a' All eigenvalues + 'v' Eigenvalues in the interval (min, max] + 'i' Eigenvalues with indices min <= i <= max + ====== ======================================== + select_range : (min, max), optional + Range of selected eigenvalues + check_finite : bool, optional + Whether to check that the input matrix contains only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + + Returns + ------- + w : (M,) ndarray + The eigenvalues, in ascending order, each repeated according to its + multiplicity. + + Raises + ------ + LinAlgError + If eigenvalue computation does not converge. + + See Also + -------- + eig_banded : eigenvalues and right eigenvectors for symmetric/Hermitian + band matrices + eigvalsh_tridiagonal : eigenvalues of symmetric/Hermitian tridiagonal + matrices + eigvals : eigenvalues of general arrays + eigh : eigenvalues and right eigenvectors for symmetric/Hermitian arrays + eig : eigenvalues and right eigenvectors for non-symmetric arrays + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import eigvals_banded + >>> A = np.array([[1, 5, 2, 0], [5, 2, 5, 2], [2, 5, 3, 5], [0, 2, 5, 4]]) + >>> Ab = np.array([[1, 2, 3, 4], [5, 5, 5, 0], [2, 2, 0, 0]]) + >>> w = eigvals_banded(Ab, lower=True) + >>> w + array([-4.26200532, -2.22987175, 3.95222349, 12.53965359]) + """ + return eig_banded(a_band, lower=lower, eigvals_only=1, + overwrite_a_band=overwrite_a_band, select=select, + select_range=select_range, check_finite=check_finite) + + +def eigvalsh_tridiagonal(d, e, select='a', select_range=None, + check_finite=True, tol=0., lapack_driver='auto'): + """ + Solve eigenvalue problem for a real symmetric tridiagonal matrix. + + Find eigenvalues `w` of ``a``:: + + a v[:,i] = w[i] v[:,i] + v.H v = identity + + For a real symmetric matrix ``a`` with diagonal elements `d` and + off-diagonal elements `e`. + + Parameters + ---------- + d : ndarray, shape (ndim,) + The diagonal elements of the array. + e : ndarray, shape (ndim-1,) + The off-diagonal elements of the array. + select : {'a', 'v', 'i'}, optional + Which eigenvalues to calculate + + ====== ======================================== + select calculated + ====== ======================================== + 'a' All eigenvalues + 'v' Eigenvalues in the interval (min, max] + 'i' Eigenvalues with indices min <= i <= max + ====== ======================================== + select_range : (min, max), optional + Range of selected eigenvalues + check_finite : bool, optional + Whether to check that the input matrix contains only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + tol : float + The absolute tolerance to which each eigenvalue is required + (only used when ``lapack_driver='stebz'``). + An eigenvalue (or cluster) is considered to have converged if it + lies in an interval of this width. If <= 0. (default), + the value ``eps*|a|`` is used where eps is the machine precision, + and ``|a|`` is the 1-norm of the matrix ``a``. + lapack_driver : str + LAPACK function to use, can be 'auto', 'stemr', 'stebz', 'sterf', + or 'stev'. When 'auto' (default), it will use 'stemr' if ``select='a'`` + and 'stebz' otherwise. 'sterf' and 'stev' can only be used when + ``select='a'``. + + Returns + ------- + w : (M,) ndarray + The eigenvalues, in ascending order, each repeated according to its + multiplicity. + + Raises + ------ + LinAlgError + If eigenvalue computation does not converge. + + See Also + -------- + eigh_tridiagonal : eigenvalues and right eiegenvectors for + symmetric/Hermitian tridiagonal matrices + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import eigvalsh_tridiagonal, eigvalsh + >>> d = 3*np.ones(4) + >>> e = -1*np.ones(3) + >>> w = eigvalsh_tridiagonal(d, e) + >>> A = np.diag(d) + np.diag(e, k=1) + np.diag(e, k=-1) + >>> w2 = eigvalsh(A) # Verify with other eigenvalue routines + >>> np.allclose(w - w2, np.zeros(4)) + True + """ + return eigh_tridiagonal( + d, e, eigvals_only=True, select=select, select_range=select_range, + check_finite=check_finite, tol=tol, lapack_driver=lapack_driver) + + +def eigh_tridiagonal(d, e, eigvals_only=False, select='a', select_range=None, + check_finite=True, tol=0., lapack_driver='auto'): + """ + Solve eigenvalue problem for a real symmetric tridiagonal matrix. + + Find eigenvalues `w` and optionally right eigenvectors `v` of ``a``:: + + a v[:,i] = w[i] v[:,i] + v.H v = identity + + For a real symmetric matrix ``a`` with diagonal elements `d` and + off-diagonal elements `e`. + + Parameters + ---------- + d : ndarray, shape (ndim,) + The diagonal elements of the array. + e : ndarray, shape (ndim-1,) + The off-diagonal elements of the array. + eigvals_only : bool, optional + Compute only the eigenvalues and no eigenvectors. + (Default: calculate also eigenvectors) + select : {'a', 'v', 'i'}, optional + Which eigenvalues to calculate + + ====== ======================================== + select calculated + ====== ======================================== + 'a' All eigenvalues + 'v' Eigenvalues in the interval (min, max] + 'i' Eigenvalues with indices min <= i <= max + ====== ======================================== + select_range : (min, max), optional + Range of selected eigenvalues + check_finite : bool, optional + Whether to check that the input matrix contains only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + tol : float + The absolute tolerance to which each eigenvalue is required + (only used when 'stebz' is the `lapack_driver`). + An eigenvalue (or cluster) is considered to have converged if it + lies in an interval of this width. If <= 0. (default), + the value ``eps*|a|`` is used where eps is the machine precision, + and ``|a|`` is the 1-norm of the matrix ``a``. + lapack_driver : str + LAPACK function to use, can be 'auto', 'stemr', 'stebz', 'sterf', + or 'stev'. When 'auto' (default), it will use 'stemr' if ``select='a'`` + and 'stebz' otherwise. When 'stebz' is used to find the eigenvalues and + ``eigvals_only=False``, then a second LAPACK call (to ``?STEIN``) is + used to find the corresponding eigenvectors. 'sterf' can only be + used when ``eigvals_only=True`` and ``select='a'``. 'stev' can only + be used when ``select='a'``. + + Returns + ------- + w : (M,) ndarray + The eigenvalues, in ascending order, each repeated according to its + multiplicity. + v : (M, M) ndarray + The normalized eigenvector corresponding to the eigenvalue ``w[i]`` is + the column ``v[:,i]``. Only returned if ``eigvals_only=False``. + + Raises + ------ + LinAlgError + If eigenvalue computation does not converge. + + See Also + -------- + eigvalsh_tridiagonal : eigenvalues of symmetric/Hermitian tridiagonal + matrices + eig : eigenvalues and right eigenvectors for non-symmetric arrays + eigh : eigenvalues and right eigenvectors for symmetric/Hermitian arrays + eig_banded : eigenvalues and right eigenvectors for symmetric/Hermitian + band matrices + + Notes + ----- + This function makes use of LAPACK ``S/DSTEMR`` routines. + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import eigh_tridiagonal + >>> d = 3*np.ones(4) + >>> e = -1*np.ones(3) + >>> w, v = eigh_tridiagonal(d, e) + >>> A = np.diag(d) + np.diag(e, k=1) + np.diag(e, k=-1) + >>> np.allclose(A @ v - v @ np.diag(w), np.zeros((4, 4))) + True + """ + d = _asarray_validated(d, check_finite=check_finite) + e = _asarray_validated(e, check_finite=check_finite) + for check in (d, e): + if check.ndim != 1: + raise ValueError('expected a 1-D array') + if check.dtype.char in 'GFD': # complex + raise TypeError('Only real arrays currently supported') + if d.size != e.size + 1: + raise ValueError(f'd ({d.size}) must have one more element than e ({e.size})') + select, vl, vu, il, iu, _ = _check_select( + select, select_range, 0, d.size) + if not isinstance(lapack_driver, str): + raise TypeError('lapack_driver must be str') + drivers = ('auto', 'stemr', 'sterf', 'stebz', 'stev') + if lapack_driver not in drivers: + raise ValueError(f'lapack_driver must be one of {drivers}, ' + f'got {lapack_driver}') + if lapack_driver == 'auto': + lapack_driver = 'stemr' if select == 0 else 'stebz' + + # Quick exit for 1x1 case + if len(d) == 1: + if select == 1 and (not (vl < d[0] <= vu)): # request by value + w = array([]) + v = empty([1, 0], dtype=d.dtype) + else: # all and request by index + w = array([d[0]], dtype=d.dtype) + v = array([[1.]], dtype=d.dtype) + + if eigvals_only: + return w + else: + return w, v + + func, = get_lapack_funcs((lapack_driver,), (d, e)) + compute_v = not eigvals_only + if lapack_driver == 'sterf': + if select != 0: + raise ValueError('sterf can only be used when select == "a"') + if not eigvals_only: + raise ValueError('sterf can only be used when eigvals_only is ' + 'True') + w, info = func(d, e) + m = len(w) + elif lapack_driver == 'stev': + if select != 0: + raise ValueError('stev can only be used when select == "a"') + w, v, info = func(d, e, compute_v=compute_v) + m = len(w) + elif lapack_driver == 'stebz': + tol = float(tol) + internal_name = 'stebz' + stebz, = get_lapack_funcs((internal_name,), (d, e)) + # If getting eigenvectors, needs to be block-ordered (B) instead of + # matrix-ordered (E), and we will reorder later + order = 'E' if eigvals_only else 'B' + m, w, iblock, isplit, info = stebz(d, e, select, vl, vu, il, iu, tol, + order) + else: # 'stemr' + # ?STEMR annoyingly requires size N instead of N-1 + e_ = empty(e.size+1, e.dtype) + e_[:-1] = e + stemr_lwork, = get_lapack_funcs(('stemr_lwork',), (d, e)) + lwork, liwork, info = stemr_lwork(d, e_, select, vl, vu, il, iu, + compute_v=compute_v) + _check_info(info, 'stemr_lwork') + m, w, v, info = func(d, e_, select, vl, vu, il, iu, + compute_v=compute_v, lwork=lwork, liwork=liwork) + _check_info(info, lapack_driver + ' (eigh_tridiagonal)') + w = w[:m] + if eigvals_only: + return w + else: + # Do we still need to compute the eigenvalues? + if lapack_driver == 'stebz': + func, = get_lapack_funcs(('stein',), (d, e)) + v, info = func(d, e, w, iblock, isplit) + _check_info(info, 'stein (eigh_tridiagonal)', + positive='%d eigenvectors failed to converge') + # Convert block-order to matrix-order + order = argsort(w) + w, v = w[order], v[:, order] + else: + v = v[:, :m] + return w, v + + +def _check_info(info, driver, positive='did not converge (LAPACK info=%d)'): + """Check info return value.""" + if info < 0: + raise ValueError('illegal value in argument %d of internal %s' + % (-info, driver)) + if info > 0 and positive: + raise LinAlgError(("%s " + positive) % (driver, info,)) + + +def hessenberg(a, calc_q=False, overwrite_a=False, check_finite=True): + """ + Compute Hessenberg form of a matrix. + + The Hessenberg decomposition is:: + + A = Q H Q^H + + where `Q` is unitary/orthogonal and `H` has only zero elements below + the first sub-diagonal. + + Parameters + ---------- + a : (M, M) array_like + Matrix to bring into Hessenberg form. + calc_q : bool, optional + Whether to compute the transformation matrix. Default is False. + overwrite_a : bool, optional + Whether to overwrite `a`; may improve performance. + Default is False. + check_finite : bool, optional + Whether to check that the input matrix contains only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + + Returns + ------- + H : (M, M) ndarray + Hessenberg form of `a`. + Q : (M, M) ndarray + Unitary/orthogonal similarity transformation matrix ``A = Q H Q^H``. + Only returned if ``calc_q=True``. + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import hessenberg + >>> A = np.array([[2, 5, 8, 7], [5, 2, 2, 8], [7, 5, 6, 6], [5, 4, 4, 8]]) + >>> H, Q = hessenberg(A, calc_q=True) + >>> H + array([[ 2. , -11.65843866, 1.42005301, 0.25349066], + [ -9.94987437, 14.53535354, -5.31022304, 2.43081618], + [ 0. , -1.83299243, 0.38969961, -0.51527034], + [ 0. , 0. , -3.83189513, 1.07494686]]) + >>> np.allclose(Q @ H @ Q.conj().T - A, np.zeros((4, 4))) + True + """ + a1 = _asarray_validated(a, check_finite=check_finite) + if len(a1.shape) != 2 or (a1.shape[0] != a1.shape[1]): + raise ValueError('expected square matrix') + overwrite_a = overwrite_a or (_datacopied(a1, a)) + + if a1.size == 0: + h3 = hessenberg(np.eye(3, dtype=a1.dtype)) + h = np.empty(a1.shape, dtype=h3.dtype) + if not calc_q: + return h + else: + h3, q3 = hessenberg(np.eye(3, dtype=a1.dtype), calc_q=True) + q = np.empty(a1.shape, dtype=q3.dtype) + h = np.empty(a1.shape, dtype=h3.dtype) + return h, q + + # if 2x2 or smaller: already in Hessenberg + if a1.shape[0] <= 2: + if calc_q: + return a1, eye(a1.shape[0]) + return a1 + + gehrd, gebal, gehrd_lwork = get_lapack_funcs(('gehrd', 'gebal', + 'gehrd_lwork'), (a1,)) + ba, lo, hi, pivscale, info = gebal(a1, permute=0, overwrite_a=overwrite_a) + _check_info(info, 'gebal (hessenberg)', positive=False) + n = len(a1) + + lwork = _compute_lwork(gehrd_lwork, ba.shape[0], lo=lo, hi=hi) + + hq, tau, info = gehrd(ba, lo=lo, hi=hi, lwork=lwork, overwrite_a=1) + _check_info(info, 'gehrd (hessenberg)', positive=False) + h = np.triu(hq, -1) + if not calc_q: + return h + + # use orghr/unghr to compute q + orghr, orghr_lwork = get_lapack_funcs(('orghr', 'orghr_lwork'), (a1,)) + lwork = _compute_lwork(orghr_lwork, n, lo=lo, hi=hi) + + q, info = orghr(a=hq, tau=tau, lo=lo, hi=hi, lwork=lwork, overwrite_a=1) + _check_info(info, 'orghr (hessenberg)', positive=False) + return h, q + + +def cdf2rdf(w, v): + """ + Converts complex eigenvalues ``w`` and eigenvectors ``v`` to real + eigenvalues in a block diagonal form ``wr`` and the associated real + eigenvectors ``vr``, such that:: + + vr @ wr = X @ vr + + continues to hold, where ``X`` is the original array for which ``w`` and + ``v`` are the eigenvalues and eigenvectors. + + .. versionadded:: 1.1.0 + + Parameters + ---------- + w : (..., M) array_like + Complex or real eigenvalues, an array or stack of arrays + + Conjugate pairs must not be interleaved, else the wrong result + will be produced. So ``[1+1j, 1, 1-1j]`` will give a correct result, + but ``[1+1j, 2+1j, 1-1j, 2-1j]`` will not. + + v : (..., M, M) array_like + Complex or real eigenvectors, a square array or stack of square arrays. + + Returns + ------- + wr : (..., M, M) ndarray + Real diagonal block form of eigenvalues + vr : (..., M, M) ndarray + Real eigenvectors associated with ``wr`` + + See Also + -------- + eig : Eigenvalues and right eigenvectors for non-symmetric arrays + rsf2csf : Convert real Schur form to complex Schur form + + Notes + ----- + ``w``, ``v`` must be the eigenstructure for some *real* matrix ``X``. + For example, obtained by ``w, v = scipy.linalg.eig(X)`` or + ``w, v = numpy.linalg.eig(X)`` in which case ``X`` can also represent + stacked arrays. + + .. versionadded:: 1.1.0 + + Examples + -------- + >>> import numpy as np + >>> X = np.array([[1, 2, 3], [0, 4, 5], [0, -5, 4]]) + >>> X + array([[ 1, 2, 3], + [ 0, 4, 5], + [ 0, -5, 4]]) + + >>> from scipy import linalg + >>> w, v = linalg.eig(X) + >>> w + array([ 1.+0.j, 4.+5.j, 4.-5.j]) + >>> v + array([[ 1.00000+0.j , -0.01906-0.40016j, -0.01906+0.40016j], + [ 0.00000+0.j , 0.00000-0.64788j, 0.00000+0.64788j], + [ 0.00000+0.j , 0.64788+0.j , 0.64788-0.j ]]) + + >>> wr, vr = linalg.cdf2rdf(w, v) + >>> wr + array([[ 1., 0., 0.], + [ 0., 4., 5.], + [ 0., -5., 4.]]) + >>> vr + array([[ 1. , 0.40016, -0.01906], + [ 0. , 0.64788, 0. ], + [ 0. , 0. , 0.64788]]) + + >>> vr @ wr + array([[ 1. , 1.69593, 1.9246 ], + [ 0. , 2.59153, 3.23942], + [ 0. , -3.23942, 2.59153]]) + >>> X @ vr + array([[ 1. , 1.69593, 1.9246 ], + [ 0. , 2.59153, 3.23942], + [ 0. , -3.23942, 2.59153]]) + """ + w, v = _asarray_validated(w), _asarray_validated(v) + + # check dimensions + if w.ndim < 1: + raise ValueError('expected w to be at least 1D') + if v.ndim < 2: + raise ValueError('expected v to be at least 2D') + if v.ndim != w.ndim + 1: + raise ValueError('expected eigenvectors array to have exactly one ' + 'dimension more than eigenvalues array') + + # check shapes + n = w.shape[-1] + M = w.shape[:-1] + if v.shape[-2] != v.shape[-1]: + raise ValueError('expected v to be a square matrix or stacked square ' + 'matrices: v.shape[-2] = v.shape[-1]') + if v.shape[-1] != n: + raise ValueError('expected the same number of eigenvalues as ' + 'eigenvectors') + + # get indices for each first pair of complex eigenvalues + complex_mask = iscomplex(w) + n_complex = complex_mask.sum(axis=-1) + + # check if all complex eigenvalues have conjugate pairs + if not (n_complex % 2 == 0).all(): + raise ValueError('expected complex-conjugate pairs of eigenvalues') + + # find complex indices + idx = nonzero(complex_mask) + idx_stack = idx[:-1] + idx_elem = idx[-1] + + # filter them to conjugate indices, assuming pairs are not interleaved + j = idx_elem[0::2] + k = idx_elem[1::2] + stack_ind = () + for i in idx_stack: + # should never happen, assuming nonzero orders by the last axis + assert (i[0::2] == i[1::2]).all(), \ + "Conjugate pair spanned different arrays!" + stack_ind += (i[0::2],) + + # all eigenvalues to diagonal form + wr = zeros(M + (n, n), dtype=w.real.dtype) + di = range(n) + wr[..., di, di] = w.real + + # complex eigenvalues to real block diagonal form + wr[stack_ind + (j, k)] = w[stack_ind + (j,)].imag + wr[stack_ind + (k, j)] = w[stack_ind + (k,)].imag + + # compute real eigenvectors associated with real block diagonal eigenvalues + u = zeros(M + (n, n), dtype=np.cdouble) + u[..., di, di] = 1.0 + u[stack_ind + (j, j)] = 0.5j + u[stack_ind + (j, k)] = 0.5 + u[stack_ind + (k, j)] = -0.5j + u[stack_ind + (k, k)] = 0.5 + + # multiply matrices v and u (equivalent to v @ u) + vr = einsum('...ij,...jk->...ik', v, u).real + + return wr, vr diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_decomp_cholesky.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_decomp_cholesky.py new file mode 100644 index 0000000000000000000000000000000000000000..c35b6a4920dea6bb638fe54a1fa719ebc74fb773 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_decomp_cholesky.py @@ -0,0 +1,398 @@ +"""Cholesky decomposition functions.""" + +import numpy as np +from numpy import asarray_chkfinite, asarray, atleast_2d, empty_like + +# Local imports +from ._misc import LinAlgError, _datacopied +from .lapack import get_lapack_funcs + +__all__ = ['cholesky', 'cho_factor', 'cho_solve', 'cholesky_banded', + 'cho_solve_banded'] + + +def _cholesky(a, lower=False, overwrite_a=False, clean=True, + check_finite=True): + """Common code for cholesky() and cho_factor().""" + + a1 = asarray_chkfinite(a) if check_finite else asarray(a) + a1 = atleast_2d(a1) + + # Dimension check + if a1.ndim != 2: + raise ValueError(f'Input array needs to be 2D but received a {a1.ndim}d-array.') + # Squareness check + if a1.shape[0] != a1.shape[1]: + raise ValueError('Input array is expected to be square but has ' + f'the shape: {a1.shape}.') + + # Quick return for square empty array + if a1.size == 0: + dt = cholesky(np.eye(1, dtype=a1.dtype)).dtype + return empty_like(a1, dtype=dt), lower + + overwrite_a = overwrite_a or _datacopied(a1, a) + potrf, = get_lapack_funcs(('potrf',), (a1,)) + c, info = potrf(a1, lower=lower, overwrite_a=overwrite_a, clean=clean) + if info > 0: + raise LinAlgError("%d-th leading minor of the array is not positive " + "definite" % info) + if info < 0: + raise ValueError(f'LAPACK reported an illegal value in {-info}-th argument' + 'on entry to "POTRF".') + return c, lower + + +def cholesky(a, lower=False, overwrite_a=False, check_finite=True): + """ + Compute the Cholesky decomposition of a matrix. + + Returns the Cholesky decomposition, :math:`A = L L^*` or + :math:`A = U^* U` of a Hermitian positive-definite matrix A. + + Parameters + ---------- + a : (M, M) array_like + Matrix to be decomposed + lower : bool, optional + Whether to compute the upper- or lower-triangular Cholesky + factorization. During decomposition, only the selected half of the + matrix is referenced. Default is upper-triangular. + overwrite_a : bool, optional + Whether to overwrite data in `a` (may improve performance). + check_finite : bool, optional + Whether to check that the entire input matrix contains only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + + Returns + ------- + c : (M, M) ndarray + Upper- or lower-triangular Cholesky factor of `a`. + + Raises + ------ + LinAlgError : if decomposition fails. + + Notes + ----- + During the finiteness check (if selected), the entire matrix `a` is + checked. During decomposition, `a` is assumed to be symmetric or Hermitian + (as applicable), and only the half selected by option `lower` is referenced. + Consequently, if `a` is asymmetric/non-Hermitian, `cholesky` may still + succeed if the symmetric/Hermitian matrix represented by the selected half + is positive definite, yet it may fail if an element in the other half is + non-finite. + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import cholesky + >>> a = np.array([[1,-2j],[2j,5]]) + >>> L = cholesky(a, lower=True) + >>> L + array([[ 1.+0.j, 0.+0.j], + [ 0.+2.j, 1.+0.j]]) + >>> L @ L.T.conj() + array([[ 1.+0.j, 0.-2.j], + [ 0.+2.j, 5.+0.j]]) + + """ + c, lower = _cholesky(a, lower=lower, overwrite_a=overwrite_a, clean=True, + check_finite=check_finite) + return c + + +def cho_factor(a, lower=False, overwrite_a=False, check_finite=True): + """ + Compute the Cholesky decomposition of a matrix, to use in cho_solve + + Returns a matrix containing the Cholesky decomposition, + ``A = L L*`` or ``A = U* U`` of a Hermitian positive-definite matrix `a`. + The return value can be directly used as the first parameter to cho_solve. + + .. warning:: + The returned matrix also contains random data in the entries not + used by the Cholesky decomposition. If you need to zero these + entries, use the function `cholesky` instead. + + Parameters + ---------- + a : (M, M) array_like + Matrix to be decomposed + lower : bool, optional + Whether to compute the upper or lower triangular Cholesky factorization. + During decomposition, only the selected half of the matrix is referenced. + (Default: upper-triangular) + overwrite_a : bool, optional + Whether to overwrite data in a (may improve performance) + check_finite : bool, optional + Whether to check that the entire input matrix contains only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + + Returns + ------- + c : (M, M) ndarray + Matrix whose upper or lower triangle contains the Cholesky factor + of `a`. Other parts of the matrix contain random data. + lower : bool + Flag indicating whether the factor is in the lower or upper triangle + + Raises + ------ + LinAlgError + Raised if decomposition fails. + + See Also + -------- + cho_solve : Solve a linear set equations using the Cholesky factorization + of a matrix. + + Notes + ----- + During the finiteness check (if selected), the entire matrix `a` is + checked. During decomposition, `a` is assumed to be symmetric or Hermitian + (as applicable), and only the half selected by option `lower` is referenced. + Consequently, if `a` is asymmetric/non-Hermitian, `cholesky` may still + succeed if the symmetric/Hermitian matrix represented by the selected half + is positive definite, yet it may fail if an element in the other half is + non-finite. + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import cho_factor + >>> A = np.array([[9, 3, 1, 5], [3, 7, 5, 1], [1, 5, 9, 2], [5, 1, 2, 6]]) + >>> c, low = cho_factor(A) + >>> c + array([[3. , 1. , 0.33333333, 1.66666667], + [3. , 2.44948974, 1.90515869, -0.27216553], + [1. , 5. , 2.29330749, 0.8559528 ], + [5. , 1. , 2. , 1.55418563]]) + >>> np.allclose(np.triu(c).T @ np. triu(c) - A, np.zeros((4, 4))) + True + + """ + c, lower = _cholesky(a, lower=lower, overwrite_a=overwrite_a, clean=False, + check_finite=check_finite) + return c, lower + + +def cho_solve(c_and_lower, b, overwrite_b=False, check_finite=True): + """Solve the linear equations A x = b, given the Cholesky factorization of A. + + Parameters + ---------- + (c, lower) : tuple, (array, bool) + Cholesky factorization of a, as given by cho_factor + b : array + Right-hand side + overwrite_b : bool, optional + Whether to overwrite data in b (may improve performance) + check_finite : bool, optional + Whether to check that the input matrices contain only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + + Returns + ------- + x : array + The solution to the system A x = b + + See Also + -------- + cho_factor : Cholesky factorization of a matrix + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import cho_factor, cho_solve + >>> A = np.array([[9, 3, 1, 5], [3, 7, 5, 1], [1, 5, 9, 2], [5, 1, 2, 6]]) + >>> c, low = cho_factor(A) + >>> x = cho_solve((c, low), [1, 1, 1, 1]) + >>> np.allclose(A @ x - [1, 1, 1, 1], np.zeros(4)) + True + + """ + (c, lower) = c_and_lower + if check_finite: + b1 = asarray_chkfinite(b) + c = asarray_chkfinite(c) + else: + b1 = asarray(b) + c = asarray(c) + + if c.ndim != 2 or c.shape[0] != c.shape[1]: + raise ValueError("The factored matrix c is not square.") + if c.shape[1] != b1.shape[0]: + raise ValueError(f"incompatible dimensions ({c.shape} and {b1.shape})") + + # accommodate empty arrays + if b1.size == 0: + dt = cho_solve((np.eye(2, dtype=b1.dtype), True), + np.ones(2, dtype=c.dtype)).dtype + return empty_like(b1, dtype=dt) + + overwrite_b = overwrite_b or _datacopied(b1, b) + + potrs, = get_lapack_funcs(('potrs',), (c, b1)) + x, info = potrs(c, b1, lower=lower, overwrite_b=overwrite_b) + if info != 0: + raise ValueError('illegal value in %dth argument of internal potrs' + % -info) + return x + + +def cholesky_banded(ab, overwrite_ab=False, lower=False, check_finite=True): + """ + Cholesky decompose a banded Hermitian positive-definite matrix + + The matrix a is stored in ab either in lower-diagonal or upper- + diagonal ordered form:: + + ab[u + i - j, j] == a[i,j] (if upper form; i <= j) + ab[ i - j, j] == a[i,j] (if lower form; i >= j) + + Example of ab (shape of a is (6,6), u=2):: + + upper form: + * * a02 a13 a24 a35 + * a01 a12 a23 a34 a45 + a00 a11 a22 a33 a44 a55 + + lower form: + a00 a11 a22 a33 a44 a55 + a10 a21 a32 a43 a54 * + a20 a31 a42 a53 * * + + Parameters + ---------- + ab : (u + 1, M) array_like + Banded matrix + overwrite_ab : bool, optional + Discard data in ab (may enhance performance) + lower : bool, optional + Is the matrix in the lower form. (Default is upper form) + check_finite : bool, optional + Whether to check that the input matrix contains only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + + Returns + ------- + c : (u + 1, M) ndarray + Cholesky factorization of a, in the same banded format as ab + + See Also + -------- + cho_solve_banded : + Solve a linear set equations, given the Cholesky factorization + of a banded Hermitian. + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import cholesky_banded + >>> from numpy import allclose, zeros, diag + >>> Ab = np.array([[0, 0, 1j, 2, 3j], [0, -1, -2, 3, 4], [9, 8, 7, 6, 9]]) + >>> A = np.diag(Ab[0,2:], k=2) + np.diag(Ab[1,1:], k=1) + >>> A = A + A.conj().T + np.diag(Ab[2, :]) + >>> c = cholesky_banded(Ab) + >>> C = np.diag(c[0, 2:], k=2) + np.diag(c[1, 1:], k=1) + np.diag(c[2, :]) + >>> np.allclose(C.conj().T @ C - A, np.zeros((5, 5))) + True + + """ + if check_finite: + ab = asarray_chkfinite(ab) + else: + ab = asarray(ab) + + # accommodate square empty matrices + if ab.size == 0: + dt = cholesky_banded(np.array([[0, 0], [1, 1]], dtype=ab.dtype)).dtype + return empty_like(ab, dtype=dt) + + pbtrf, = get_lapack_funcs(('pbtrf',), (ab,)) + c, info = pbtrf(ab, lower=lower, overwrite_ab=overwrite_ab) + if info > 0: + raise LinAlgError("%d-th leading minor not positive definite" % info) + if info < 0: + raise ValueError('illegal value in %d-th argument of internal pbtrf' + % -info) + return c + + +def cho_solve_banded(cb_and_lower, b, overwrite_b=False, check_finite=True): + """ + Solve the linear equations ``A x = b``, given the Cholesky factorization of + the banded Hermitian ``A``. + + Parameters + ---------- + (cb, lower) : tuple, (ndarray, bool) + `cb` is the Cholesky factorization of A, as given by cholesky_banded. + `lower` must be the same value that was given to cholesky_banded. + b : array_like + Right-hand side + overwrite_b : bool, optional + If True, the function will overwrite the values in `b`. + check_finite : bool, optional + Whether to check that the input matrices contain only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + + Returns + ------- + x : array + The solution to the system A x = b + + See Also + -------- + cholesky_banded : Cholesky factorization of a banded matrix + + Notes + ----- + + .. versionadded:: 0.8.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import cholesky_banded, cho_solve_banded + >>> Ab = np.array([[0, 0, 1j, 2, 3j], [0, -1, -2, 3, 4], [9, 8, 7, 6, 9]]) + >>> A = np.diag(Ab[0,2:], k=2) + np.diag(Ab[1,1:], k=1) + >>> A = A + A.conj().T + np.diag(Ab[2, :]) + >>> c = cholesky_banded(Ab) + >>> x = cho_solve_banded((c, False), np.ones(5)) + >>> np.allclose(A @ x - np.ones(5), np.zeros(5)) + True + + """ + (cb, lower) = cb_and_lower + if check_finite: + cb = asarray_chkfinite(cb) + b = asarray_chkfinite(b) + else: + cb = asarray(cb) + b = asarray(b) + + # Validate shapes. + if cb.shape[-1] != b.shape[0]: + raise ValueError("shapes of cb and b are not compatible.") + + # accommodate empty arrays + if b.size == 0: + m = cholesky_banded(np.array([[0, 0], [1, 1]], dtype=cb.dtype)) + dt = cho_solve_banded((m, True), np.ones(2, dtype=b.dtype)).dtype + return empty_like(b, dtype=dt) + + pbtrs, = get_lapack_funcs(('pbtrs',), (cb, b)) + x, info = pbtrs(cb, b, lower=lower, overwrite_b=overwrite_b) + if info > 0: + raise LinAlgError("%dth leading minor not positive definite" % info) + if info < 0: + raise ValueError('illegal value in %dth argument of internal pbtrs' + % -info) + return x diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_decomp_cossin.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_decomp_cossin.py new file mode 100644 index 0000000000000000000000000000000000000000..e10c04fe5ebc196e1b84724b25f0fc20a5e46857 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_decomp_cossin.py @@ -0,0 +1,221 @@ +from collections.abc import Iterable +import numpy as np + +from scipy._lib._util import _asarray_validated +from scipy.linalg import block_diag, LinAlgError +from .lapack import _compute_lwork, get_lapack_funcs + +__all__ = ['cossin'] + + +def cossin(X, p=None, q=None, separate=False, + swap_sign=False, compute_u=True, compute_vh=True): + """ + Compute the cosine-sine (CS) decomposition of an orthogonal/unitary matrix. + + X is an ``(m, m)`` orthogonal/unitary matrix, partitioned as the following + where upper left block has the shape of ``(p, q)``:: + + ┌ ┐ + │ I 0 0 │ 0 0 0 │ + ┌ ┐ ┌ ┐│ 0 C 0 │ 0 -S 0 │┌ ┐* + │ X11 │ X12 │ │ U1 │ ││ 0 0 0 │ 0 0 -I ││ V1 │ │ + │ ────┼──── │ = │────┼────││─────────┼─────────││────┼────│ + │ X21 │ X22 │ │ │ U2 ││ 0 0 0 │ I 0 0 ││ │ V2 │ + └ ┘ └ ┘│ 0 S 0 │ 0 C 0 │└ ┘ + │ 0 0 I │ 0 0 0 │ + └ ┘ + + ``U1``, ``U2``, ``V1``, ``V2`` are square orthogonal/unitary matrices of + dimensions ``(p,p)``, ``(m-p,m-p)``, ``(q,q)``, and ``(m-q,m-q)`` + respectively, and ``C`` and ``S`` are ``(r, r)`` nonnegative diagonal + matrices satisfying ``C^2 + S^2 = I`` where ``r = min(p, m-p, q, m-q)``. + + Moreover, the rank of the identity matrices are ``min(p, q) - r``, + ``min(p, m - q) - r``, ``min(m - p, q) - r``, and ``min(m - p, m - q) - r`` + respectively. + + X can be supplied either by itself and block specifications p, q or its + subblocks in an iterable from which the shapes would be derived. See the + examples below. + + Parameters + ---------- + X : array_like, iterable + complex unitary or real orthogonal matrix to be decomposed, or iterable + of subblocks ``X11``, ``X12``, ``X21``, ``X22``, when ``p``, ``q`` are + omitted. + p : int, optional + Number of rows of the upper left block ``X11``, used only when X is + given as an array. + q : int, optional + Number of columns of the upper left block ``X11``, used only when X is + given as an array. + separate : bool, optional + if ``True``, the low level components are returned instead of the + matrix factors, i.e. ``(u1,u2)``, ``theta``, ``(v1h,v2h)`` instead of + ``u``, ``cs``, ``vh``. + swap_sign : bool, optional + if ``True``, the ``-S``, ``-I`` block will be the bottom left, + otherwise (by default) they will be in the upper right block. + compute_u : bool, optional + if ``False``, ``u`` won't be computed and an empty array is returned. + compute_vh : bool, optional + if ``False``, ``vh`` won't be computed and an empty array is returned. + + Returns + ------- + u : ndarray + When ``compute_u=True``, contains the block diagonal orthogonal/unitary + matrix consisting of the blocks ``U1`` (``p`` x ``p``) and ``U2`` + (``m-p`` x ``m-p``) orthogonal/unitary matrices. If ``separate=True``, + this contains the tuple of ``(U1, U2)``. + cs : ndarray + The cosine-sine factor with the structure described above. + If ``separate=True``, this contains the ``theta`` array containing the + angles in radians. + vh : ndarray + When ``compute_vh=True`, contains the block diagonal orthogonal/unitary + matrix consisting of the blocks ``V1H`` (``q`` x ``q``) and ``V2H`` + (``m-q`` x ``m-q``) orthogonal/unitary matrices. If ``separate=True``, + this contains the tuple of ``(V1H, V2H)``. + + References + ---------- + .. [1] Brian D. Sutton. Computing the complete CS decomposition. Numer. + Algorithms, 50(1):33-65, 2009. + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import cossin + >>> from scipy.stats import unitary_group + >>> x = unitary_group.rvs(4) + >>> u, cs, vdh = cossin(x, p=2, q=2) + >>> np.allclose(x, u @ cs @ vdh) + True + + Same can be entered via subblocks without the need of ``p`` and ``q``. Also + let's skip the computation of ``u`` + + >>> ue, cs, vdh = cossin((x[:2, :2], x[:2, 2:], x[2:, :2], x[2:, 2:]), + ... compute_u=False) + >>> print(ue) + [] + >>> np.allclose(x, u @ cs @ vdh) + True + + """ + + if p or q: + p = 1 if p is None else int(p) + q = 1 if q is None else int(q) + X = _asarray_validated(X, check_finite=True) + if not np.equal(*X.shape): + raise ValueError("Cosine Sine decomposition only supports square" + f" matrices, got {X.shape}") + m = X.shape[0] + if p >= m or p <= 0: + raise ValueError(f"invalid p={p}, 0= m or q <= 0: + raise ValueError(f"invalid q={q}, 0 0: + raise LinAlgError(f"{method_name} did not converge: {info}") + + if separate: + return (u1, u2), theta, (v1h, v2h) + + U = block_diag(u1, u2) + VDH = block_diag(v1h, v2h) + + # Construct the middle factor CS + c = np.diag(np.cos(theta)) + s = np.diag(np.sin(theta)) + r = min(p, q, m - p, m - q) + n11 = min(p, q) - r + n12 = min(p, m - q) - r + n21 = min(m - p, q) - r + n22 = min(m - p, m - q) - r + Id = np.eye(np.max([n11, n12, n21, n22, r]), dtype=theta.dtype) + CS = np.zeros((m, m), dtype=theta.dtype) + + CS[:n11, :n11] = Id[:n11, :n11] + + xs = n11 + r + xe = n11 + r + n12 + ys = n11 + n21 + n22 + 2 * r + ye = n11 + n21 + n22 + 2 * r + n12 + CS[xs: xe, ys:ye] = Id[:n12, :n12] if swap_sign else -Id[:n12, :n12] + + xs = p + n22 + r + xe = p + n22 + r + + n21 + ys = n11 + r + ye = n11 + r + n21 + CS[xs:xe, ys:ye] = -Id[:n21, :n21] if swap_sign else Id[:n21, :n21] + + CS[p:p + n22, q:q + n22] = Id[:n22, :n22] + CS[n11:n11 + r, n11:n11 + r] = c + CS[p + n22:p + n22 + r, n11 + r + n21 + n22:2 * r + n11 + n21 + n22] = c + + xs = n11 + xe = n11 + r + ys = n11 + n21 + n22 + r + ye = n11 + n21 + n22 + 2 * r + CS[xs:xe, ys:ye] = s if swap_sign else -s + + CS[p + n22:p + n22 + r, n11:n11 + r] = -s if swap_sign else s + + return U, CS, VDH diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_decomp_ldl.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_decomp_ldl.py new file mode 100644 index 0000000000000000000000000000000000000000..336df1d5fb416f635c91afe3cc2cfb3c340239fc --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_decomp_ldl.py @@ -0,0 +1,353 @@ +from warnings import warn + +import numpy as np +from numpy import (atleast_2d, arange, zeros_like, imag, diag, + iscomplexobj, tril, triu, argsort, empty_like) +from scipy._lib._util import ComplexWarning +from ._decomp import _asarray_validated +from .lapack import get_lapack_funcs, _compute_lwork + +__all__ = ['ldl'] + + +def ldl(A, lower=True, hermitian=True, overwrite_a=False, check_finite=True): + """ Computes the LDLt or Bunch-Kaufman factorization of a symmetric/ + hermitian matrix. + + This function returns a block diagonal matrix D consisting blocks of size + at most 2x2 and also a possibly permuted unit lower triangular matrix + ``L`` such that the factorization ``A = L D L^H`` or ``A = L D L^T`` + holds. If `lower` is False then (again possibly permuted) upper + triangular matrices are returned as outer factors. + + The permutation array can be used to triangularize the outer factors + simply by a row shuffle, i.e., ``lu[perm, :]`` is an upper/lower + triangular matrix. This is also equivalent to multiplication with a + permutation matrix ``P.dot(lu)``, where ``P`` is a column-permuted + identity matrix ``I[:, perm]``. + + Depending on the value of the boolean `lower`, only upper or lower + triangular part of the input array is referenced. Hence, a triangular + matrix on entry would give the same result as if the full matrix is + supplied. + + Parameters + ---------- + A : array_like + Square input array + lower : bool, optional + This switches between the lower and upper triangular outer factors of + the factorization. Lower triangular (``lower=True``) is the default. + hermitian : bool, optional + For complex-valued arrays, this defines whether ``A = A.conj().T`` or + ``A = A.T`` is assumed. For real-valued arrays, this switch has no + effect. + overwrite_a : bool, optional + Allow overwriting data in `A` (may enhance performance). The default + is False. + check_finite : bool, optional + Whether to check that the input matrices contain only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + + Returns + ------- + lu : ndarray + The (possibly) permuted upper/lower triangular outer factor of the + factorization. + d : ndarray + The block diagonal multiplier of the factorization. + perm : ndarray + The row-permutation index array that brings lu into triangular form. + + Raises + ------ + ValueError + If input array is not square. + ComplexWarning + If a complex-valued array with nonzero imaginary parts on the + diagonal is given and hermitian is set to True. + + See Also + -------- + cholesky, lu + + Notes + ----- + This function uses ``?SYTRF`` routines for symmetric matrices and + ``?HETRF`` routines for Hermitian matrices from LAPACK. See [1]_ for + the algorithm details. + + Depending on the `lower` keyword value, only lower or upper triangular + part of the input array is referenced. Moreover, this keyword also defines + the structure of the outer factors of the factorization. + + .. versionadded:: 1.1.0 + + References + ---------- + .. [1] J.R. Bunch, L. Kaufman, Some stable methods for calculating + inertia and solving symmetric linear systems, Math. Comput. Vol.31, + 1977. :doi:`10.2307/2005787` + + Examples + -------- + Given an upper triangular array ``a`` that represents the full symmetric + array with its entries, obtain ``l``, 'd' and the permutation vector `perm`: + + >>> import numpy as np + >>> from scipy.linalg import ldl + >>> a = np.array([[2, -1, 3], [0, 2, 0], [0, 0, 1]]) + >>> lu, d, perm = ldl(a, lower=0) # Use the upper part + >>> lu + array([[ 0. , 0. , 1. ], + [ 0. , 1. , -0.5], + [ 1. , 1. , 1.5]]) + >>> d + array([[-5. , 0. , 0. ], + [ 0. , 1.5, 0. ], + [ 0. , 0. , 2. ]]) + >>> perm + array([2, 1, 0]) + >>> lu[perm, :] + array([[ 1. , 1. , 1.5], + [ 0. , 1. , -0.5], + [ 0. , 0. , 1. ]]) + >>> lu.dot(d).dot(lu.T) + array([[ 2., -1., 3.], + [-1., 2., 0.], + [ 3., 0., 1.]]) + + """ + a = atleast_2d(_asarray_validated(A, check_finite=check_finite)) + if a.shape[0] != a.shape[1]: + raise ValueError('The input array "a" should be square.') + # Return empty arrays for empty square input + if a.size == 0: + return empty_like(a), empty_like(a), np.array([], dtype=int) + + n = a.shape[0] + r_or_c = complex if iscomplexobj(a) else float + + # Get the LAPACK routine + if r_or_c is complex and hermitian: + s, sl = 'hetrf', 'hetrf_lwork' + if np.any(imag(diag(a))): + warn('scipy.linalg.ldl():\nThe imaginary parts of the diagonal' + 'are ignored. Use "hermitian=False" for factorization of' + 'complex symmetric arrays.', ComplexWarning, stacklevel=2) + else: + s, sl = 'sytrf', 'sytrf_lwork' + + solver, solver_lwork = get_lapack_funcs((s, sl), (a,)) + lwork = _compute_lwork(solver_lwork, n, lower=lower) + ldu, piv, info = solver(a, lwork=lwork, lower=lower, + overwrite_a=overwrite_a) + if info < 0: + raise ValueError(f'{s.upper()} exited with the internal error "illegal value ' + f'in argument number {-info}". See LAPACK documentation ' + 'for the error codes.') + + swap_arr, pivot_arr = _ldl_sanitize_ipiv(piv, lower=lower) + d, lu = _ldl_get_d_and_l(ldu, pivot_arr, lower=lower, hermitian=hermitian) + lu, perm = _ldl_construct_tri_factor(lu, swap_arr, pivot_arr, lower=lower) + + return lu, d, perm + + +def _ldl_sanitize_ipiv(a, lower=True): + """ + This helper function takes the rather strangely encoded permutation array + returned by the LAPACK routines ?(HE/SY)TRF and converts it into + regularized permutation and diagonal pivot size format. + + Since FORTRAN uses 1-indexing and LAPACK uses different start points for + upper and lower formats there are certain offsets in the indices used + below. + + Let's assume a result where the matrix is 6x6 and there are two 2x2 + and two 1x1 blocks reported by the routine. To ease the coding efforts, + we still populate a 6-sized array and fill zeros as the following :: + + pivots = [2, 0, 2, 0, 1, 1] + + This denotes a diagonal matrix of the form :: + + [x x ] + [x x ] + [ x x ] + [ x x ] + [ x ] + [ x] + + In other words, we write 2 when the 2x2 block is first encountered and + automatically write 0 to the next entry and skip the next spin of the + loop. Thus, a separate counter or array appends to keep track of block + sizes are avoided. If needed, zeros can be filtered out later without + losing the block structure. + + Parameters + ---------- + a : ndarray + The permutation array ipiv returned by LAPACK + lower : bool, optional + The switch to select whether upper or lower triangle is chosen in + the LAPACK call. + + Returns + ------- + swap_ : ndarray + The array that defines the row/column swap operations. For example, + if row two is swapped with row four, the result is [0, 3, 2, 3]. + pivots : ndarray + The array that defines the block diagonal structure as given above. + + """ + n = a.size + swap_ = arange(n) + pivots = zeros_like(swap_, dtype=int) + skip_2x2 = False + + # Some upper/lower dependent offset values + # range (s)tart, r(e)nd, r(i)ncrement + x, y, rs, re, ri = (1, 0, 0, n, 1) if lower else (-1, -1, n-1, -1, -1) + + for ind in range(rs, re, ri): + # If previous spin belonged already to a 2x2 block + if skip_2x2: + skip_2x2 = False + continue + + cur_val = a[ind] + # do we have a 1x1 block or not? + if cur_val > 0: + if cur_val != ind+1: + # Index value != array value --> permutation required + swap_[ind] = swap_[cur_val-1] + pivots[ind] = 1 + # Not. + elif cur_val < 0 and cur_val == a[ind+x]: + # first neg entry of 2x2 block identifier + if -cur_val != ind+2: + # Index value != array value --> permutation required + swap_[ind+x] = swap_[-cur_val-1] + pivots[ind+y] = 2 + skip_2x2 = True + else: # Doesn't make sense, give up + raise ValueError('While parsing the permutation array ' + 'in "scipy.linalg.ldl", invalid entries ' + 'found. The array syntax is invalid.') + return swap_, pivots + + +def _ldl_get_d_and_l(ldu, pivs, lower=True, hermitian=True): + """ + Helper function to extract the diagonal and triangular matrices for + LDL.T factorization. + + Parameters + ---------- + ldu : ndarray + The compact output returned by the LAPACK routing + pivs : ndarray + The sanitized array of {0, 1, 2} denoting the sizes of the pivots. For + every 2 there is a succeeding 0. + lower : bool, optional + If set to False, upper triangular part is considered. + hermitian : bool, optional + If set to False a symmetric complex array is assumed. + + Returns + ------- + d : ndarray + The block diagonal matrix. + lu : ndarray + The upper/lower triangular matrix + """ + is_c = iscomplexobj(ldu) + d = diag(diag(ldu)) + n = d.shape[0] + blk_i = 0 # block index + + # row/column offsets for selecting sub-, super-diagonal + x, y = (1, 0) if lower else (0, 1) + + lu = tril(ldu, -1) if lower else triu(ldu, 1) + diag_inds = arange(n) + lu[diag_inds, diag_inds] = 1 + + for blk in pivs[pivs != 0]: + # increment the block index and check for 2s + # if 2 then copy the off diagonals depending on uplo + inc = blk_i + blk + + if blk == 2: + d[blk_i+x, blk_i+y] = ldu[blk_i+x, blk_i+y] + # If Hermitian matrix is factorized, the cross-offdiagonal element + # should be conjugated. + if is_c and hermitian: + d[blk_i+y, blk_i+x] = ldu[blk_i+x, blk_i+y].conj() + else: + d[blk_i+y, blk_i+x] = ldu[blk_i+x, blk_i+y] + + lu[blk_i+x, blk_i+y] = 0. + blk_i = inc + + return d, lu + + +def _ldl_construct_tri_factor(lu, swap_vec, pivs, lower=True): + """ + Helper function to construct explicit outer factors of LDL factorization. + + If lower is True the permuted factors are multiplied as L(1)*L(2)*...*L(k). + Otherwise, the permuted factors are multiplied as L(k)*...*L(2)*L(1). See + LAPACK documentation for more details. + + Parameters + ---------- + lu : ndarray + The triangular array that is extracted from LAPACK routine call with + ones on the diagonals. + swap_vec : ndarray + The array that defines the row swapping indices. If the kth entry is m + then rows k,m are swapped. Notice that the mth entry is not necessarily + k to avoid undoing the swapping. + pivs : ndarray + The array that defines the block diagonal structure returned by + _ldl_sanitize_ipiv(). + lower : bool, optional + The boolean to switch between lower and upper triangular structure. + + Returns + ------- + lu : ndarray + The square outer factor which satisfies the L * D * L.T = A + perm : ndarray + The permutation vector that brings the lu to the triangular form + + Notes + ----- + Note that the original argument "lu" is overwritten. + + """ + n = lu.shape[0] + perm = arange(n) + # Setup the reading order of the permutation matrix for upper/lower + rs, re, ri = (n-1, -1, -1) if lower else (0, n, 1) + + for ind in range(rs, re, ri): + s_ind = swap_vec[ind] + if s_ind != ind: + # Column start and end positions + col_s = ind if lower else 0 + col_e = n if lower else ind+1 + + # If we stumble upon a 2x2 block include both cols in the perm. + if pivs[ind] == (0 if lower else 2): + col_s += -1 if lower else 0 + col_e += 0 if lower else 1 + lu[[s_ind, ind], col_s:col_e] = lu[[ind, s_ind], col_s:col_e] + perm[[s_ind, ind]] = perm[[ind, s_ind]] + + return lu, argsort(perm) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_decomp_lu.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_decomp_lu.py new file mode 100644 index 0000000000000000000000000000000000000000..06562a4a490a4328c08d4de45a5463427e33562b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_decomp_lu.py @@ -0,0 +1,389 @@ +"""LU decomposition functions.""" + +from warnings import warn + +from numpy import asarray, asarray_chkfinite +import numpy as np +from itertools import product + +# Local imports +from ._misc import _datacopied, LinAlgWarning +from .lapack import get_lapack_funcs +from ._decomp_lu_cython import lu_dispatcher + +lapack_cast_dict = {x: ''.join([y for y in 'fdFD' if np.can_cast(x, y)]) + for x in np.typecodes['All']} + +__all__ = ['lu', 'lu_solve', 'lu_factor'] + + +def lu_factor(a, overwrite_a=False, check_finite=True): + """ + Compute pivoted LU decomposition of a matrix. + + The decomposition is:: + + A = P L U + + where P is a permutation matrix, L lower triangular with unit + diagonal elements, and U upper triangular. + + Parameters + ---------- + a : (M, N) array_like + Matrix to decompose + overwrite_a : bool, optional + Whether to overwrite data in A (may increase performance) + check_finite : bool, optional + Whether to check that the input matrix contains only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + + Returns + ------- + lu : (M, N) ndarray + Matrix containing U in its upper triangle, and L in its lower triangle. + The unit diagonal elements of L are not stored. + piv : (K,) ndarray + Pivot indices representing the permutation matrix P: + row i of matrix was interchanged with row piv[i]. + Of shape ``(K,)``, with ``K = min(M, N)``. + + See Also + -------- + lu : gives lu factorization in more user-friendly format + lu_solve : solve an equation system using the LU factorization of a matrix + + Notes + ----- + This is a wrapper to the ``*GETRF`` routines from LAPACK. Unlike + :func:`lu`, it outputs the L and U factors into a single array + and returns pivot indices instead of a permutation matrix. + + While the underlying ``*GETRF`` routines return 1-based pivot indices, the + ``piv`` array returned by ``lu_factor`` contains 0-based indices. + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import lu_factor + >>> A = np.array([[2, 5, 8, 7], [5, 2, 2, 8], [7, 5, 6, 6], [5, 4, 4, 8]]) + >>> lu, piv = lu_factor(A) + >>> piv + array([2, 2, 3, 3], dtype=int32) + + Convert LAPACK's ``piv`` array to NumPy index and test the permutation + + >>> def pivot_to_permutation(piv): + ... perm = np.arange(len(piv)) + ... for i in range(len(piv)): + ... perm[i], perm[piv[i]] = perm[piv[i]], perm[i] + ... return perm + ... + >>> p_inv = pivot_to_permutation(piv) + >>> p_inv + array([2, 0, 3, 1]) + >>> L, U = np.tril(lu, k=-1) + np.eye(4), np.triu(lu) + >>> np.allclose(A[p_inv] - L @ U, np.zeros((4, 4))) + True + + The P matrix in P L U is defined by the inverse permutation and + can be recovered using argsort: + + >>> p = np.argsort(p_inv) + >>> p + array([1, 3, 0, 2]) + >>> np.allclose(A - L[p] @ U, np.zeros((4, 4))) + True + + or alternatively: + + >>> P = np.eye(4)[p] + >>> np.allclose(A - P @ L @ U, np.zeros((4, 4))) + True + """ + if check_finite: + a1 = asarray_chkfinite(a) + else: + a1 = asarray(a) + + # accommodate empty arrays + if a1.size == 0: + lu = np.empty_like(a1) + piv = np.arange(0, dtype=np.int32) + return lu, piv + + overwrite_a = overwrite_a or (_datacopied(a1, a)) + + getrf, = get_lapack_funcs(('getrf',), (a1,)) + lu, piv, info = getrf(a1, overwrite_a=overwrite_a) + if info < 0: + raise ValueError('illegal value in %dth argument of ' + 'internal getrf (lu_factor)' % -info) + if info > 0: + warn("Diagonal number %d is exactly zero. Singular matrix." % info, + LinAlgWarning, stacklevel=2) + return lu, piv + + +def lu_solve(lu_and_piv, b, trans=0, overwrite_b=False, check_finite=True): + """Solve an equation system, a x = b, given the LU factorization of a + + Parameters + ---------- + (lu, piv) + Factorization of the coefficient matrix a, as given by lu_factor. + In particular piv are 0-indexed pivot indices. + b : array + Right-hand side + trans : {0, 1, 2}, optional + Type of system to solve: + + ===== ========= + trans system + ===== ========= + 0 a x = b + 1 a^T x = b + 2 a^H x = b + ===== ========= + overwrite_b : bool, optional + Whether to overwrite data in b (may increase performance) + check_finite : bool, optional + Whether to check that the input matrices contain only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + + Returns + ------- + x : array + Solution to the system + + See Also + -------- + lu_factor : LU factorize a matrix + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import lu_factor, lu_solve + >>> A = np.array([[2, 5, 8, 7], [5, 2, 2, 8], [7, 5, 6, 6], [5, 4, 4, 8]]) + >>> b = np.array([1, 1, 1, 1]) + >>> lu, piv = lu_factor(A) + >>> x = lu_solve((lu, piv), b) + >>> np.allclose(A @ x - b, np.zeros((4,))) + True + + """ + (lu, piv) = lu_and_piv + if check_finite: + b1 = asarray_chkfinite(b) + else: + b1 = asarray(b) + + overwrite_b = overwrite_b or _datacopied(b1, b) + + if lu.shape[0] != b1.shape[0]: + raise ValueError(f"Shapes of lu {lu.shape} and b {b1.shape} are incompatible") + + # accommodate empty arrays + if b1.size == 0: + m = lu_solve((np.eye(2, dtype=lu.dtype), [0, 1]), np.ones(2, dtype=b.dtype)) + return np.empty_like(b1, dtype=m.dtype) + + getrs, = get_lapack_funcs(('getrs',), (lu, b1)) + x, info = getrs(lu, piv, b1, trans=trans, overwrite_b=overwrite_b) + if info == 0: + return x + raise ValueError('illegal value in %dth argument of internal gesv|posv' + % -info) + + +def lu(a, permute_l=False, overwrite_a=False, check_finite=True, + p_indices=False): + """ + Compute LU decomposition of a matrix with partial pivoting. + + The decomposition satisfies:: + + A = P @ L @ U + + where ``P`` is a permutation matrix, ``L`` lower triangular with unit + diagonal elements, and ``U`` upper triangular. If `permute_l` is set to + ``True`` then ``L`` is returned already permuted and hence satisfying + ``A = L @ U``. + + Parameters + ---------- + a : (M, N) array_like + Array to decompose + permute_l : bool, optional + Perform the multiplication P*L (Default: do not permute) + overwrite_a : bool, optional + Whether to overwrite data in a (may improve performance) + check_finite : bool, optional + Whether to check that the input matrix contains only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + p_indices : bool, optional + If ``True`` the permutation information is returned as row indices. + The default is ``False`` for backwards-compatibility reasons. + + Returns + ------- + **(If `permute_l` is ``False``)** + + p : (..., M, M) ndarray + Permutation arrays or vectors depending on `p_indices` + l : (..., M, K) ndarray + Lower triangular or trapezoidal array with unit diagonal. + ``K = min(M, N)`` + u : (..., K, N) ndarray + Upper triangular or trapezoidal array + + **(If `permute_l` is ``True``)** + + pl : (..., M, K) ndarray + Permuted L matrix. + ``K = min(M, N)`` + u : (..., K, N) ndarray + Upper triangular or trapezoidal array + + Notes + ----- + Permutation matrices are costly since they are nothing but row reorder of + ``L`` and hence indices are strongly recommended to be used instead if the + permutation is required. The relation in the 2D case then becomes simply + ``A = L[P, :] @ U``. In higher dimensions, it is better to use `permute_l` + to avoid complicated indexing tricks. + + In 2D case, if one has the indices however, for some reason, the + permutation matrix is still needed then it can be constructed by + ``np.eye(M)[P, :]``. + + Examples + -------- + + >>> import numpy as np + >>> from scipy.linalg import lu + >>> A = np.array([[2, 5, 8, 7], [5, 2, 2, 8], [7, 5, 6, 6], [5, 4, 4, 8]]) + >>> p, l, u = lu(A) + >>> np.allclose(A, p @ l @ u) + True + >>> p # Permutation matrix + array([[0., 1., 0., 0.], # Row index 1 + [0., 0., 0., 1.], # Row index 3 + [1., 0., 0., 0.], # Row index 0 + [0., 0., 1., 0.]]) # Row index 2 + >>> p, _, _ = lu(A, p_indices=True) + >>> p + array([1, 3, 0, 2], dtype=int32) # as given by row indices above + >>> np.allclose(A, l[p, :] @ u) + True + + We can also use nd-arrays, for example, a demonstration with 4D array: + + >>> rng = np.random.default_rng() + >>> A = rng.uniform(low=-4, high=4, size=[3, 2, 4, 8]) + >>> p, l, u = lu(A) + >>> p.shape, l.shape, u.shape + ((3, 2, 4, 4), (3, 2, 4, 4), (3, 2, 4, 8)) + >>> np.allclose(A, p @ l @ u) + True + >>> PL, U = lu(A, permute_l=True) + >>> np.allclose(A, PL @ U) + True + + """ + a1 = np.asarray_chkfinite(a) if check_finite else np.asarray(a) + if a1.ndim < 2: + raise ValueError('The input array must be at least two-dimensional.') + + # Also check if dtype is LAPACK compatible + if a1.dtype.char not in 'fdFD': + dtype_char = lapack_cast_dict[a1.dtype.char] + if not dtype_char: # No casting possible + raise TypeError(f'The dtype {a1.dtype} cannot be cast ' + 'to float(32, 64) or complex(64, 128).') + + a1 = a1.astype(dtype_char[0]) # makes a copy, free to scratch + overwrite_a = True + + *nd, m, n = a1.shape + k = min(m, n) + real_dchar = 'f' if a1.dtype.char in 'fF' else 'd' + + # Empty input + if min(*a1.shape) == 0: + if permute_l: + PL = np.empty(shape=[*nd, m, k], dtype=a1.dtype) + U = np.empty(shape=[*nd, k, n], dtype=a1.dtype) + return PL, U + else: + P = (np.empty([*nd, 0], dtype=np.int32) if p_indices else + np.empty([*nd, 0, 0], dtype=real_dchar)) + L = np.empty(shape=[*nd, m, k], dtype=a1.dtype) + U = np.empty(shape=[*nd, k, n], dtype=a1.dtype) + return P, L, U + + # Scalar case + if a1.shape[-2:] == (1, 1): + if permute_l: + return np.ones_like(a1), (a1 if overwrite_a else a1.copy()) + else: + P = (np.zeros(shape=[*nd, m], dtype=int) if p_indices + else np.ones_like(a1)) + return P, np.ones_like(a1), (a1 if overwrite_a else a1.copy()) + + # Then check overwrite permission + if not _datacopied(a1, a): # "a" still alive through "a1" + if not overwrite_a: + # Data belongs to "a" so make a copy + a1 = a1.copy(order='C') + # else: Do nothing we'll use "a" if possible + # else: a1 has its own data thus free to scratch + + # Then layout checks, might happen that overwrite is allowed but original + # array was read-only or non-contiguous. + + if not (a1.flags['C_CONTIGUOUS'] and a1.flags['WRITEABLE']): + a1 = a1.copy(order='C') + + if not nd: # 2D array + + p = np.empty(m, dtype=np.int32) + u = np.zeros([k, k], dtype=a1.dtype) + lu_dispatcher(a1, u, p, permute_l) + P, L, U = (p, a1, u) if m > n else (p, u, a1) + + else: # Stacked array + + # Prepare the contiguous data holders + P = np.empty([*nd, m], dtype=np.int32) # perm vecs + + if m > n: # Tall arrays, U will be created + U = np.zeros([*nd, k, k], dtype=a1.dtype) + for ind in product(*[range(x) for x in a1.shape[:-2]]): + lu_dispatcher(a1[ind], U[ind], P[ind], permute_l) + L = a1 + + else: # Fat arrays, L will be created + L = np.zeros([*nd, k, k], dtype=a1.dtype) + for ind in product(*[range(x) for x in a1.shape[:-2]]): + lu_dispatcher(a1[ind], L[ind], P[ind], permute_l) + U = a1 + + # Convert permutation vecs to permutation arrays + # permute_l=False needed to enter here to avoid wasted efforts + if (not p_indices) and (not permute_l): + if nd: + Pa = np.zeros([*nd, m, m], dtype=real_dchar) + # An unreadable index hack - One-hot encoding for perm matrices + nd_ix = np.ix_(*([np.arange(x) for x in nd]+[np.arange(m)])) + Pa[(*nd_ix, P)] = 1 + P = Pa + else: # 2D case + Pa = np.zeros([m, m], dtype=real_dchar) + Pa[np.arange(m), P] = 1 + P = Pa + + return (L, U) if permute_l else (P, L, U) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_decomp_lu_cython.pyi b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_decomp_lu_cython.pyi new file mode 100644 index 0000000000000000000000000000000000000000..0a175b1de32806102318cf69f7c5b4c3deddb03c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_decomp_lu_cython.pyi @@ -0,0 +1,6 @@ +from numpy.typing import NDArray +from typing import Any + +def lu_decompose(a: NDArray[Any], lu: NDArray[Any], perm: NDArray[Any], permute_l: bool) -> None: ... # noqa: E501 + +def lu_dispatcher(a: NDArray[Any], lu: NDArray[Any], perm: NDArray[Any], permute_l: bool) -> None: ... # noqa: E501 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_decomp_polar.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_decomp_polar.py new file mode 100644 index 0000000000000000000000000000000000000000..2fc3652899bed607ab1dd5e3f1663345010e93c1 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_decomp_polar.py @@ -0,0 +1,111 @@ +import numpy as np +from scipy.linalg import svd + + +__all__ = ['polar'] + + +def polar(a, side="right"): + """ + Compute the polar decomposition. + + Returns the factors of the polar decomposition [1]_ `u` and `p` such + that ``a = up`` (if `side` is "right") or ``a = pu`` (if `side` is + "left"), where `p` is positive semidefinite. Depending on the shape + of `a`, either the rows or columns of `u` are orthonormal. When `a` + is a square array, `u` is a square unitary array. When `a` is not + square, the "canonical polar decomposition" [2]_ is computed. + + Parameters + ---------- + a : (m, n) array_like + The array to be factored. + side : {'left', 'right'}, optional + Determines whether a right or left polar decomposition is computed. + If `side` is "right", then ``a = up``. If `side` is "left", then + ``a = pu``. The default is "right". + + Returns + ------- + u : (m, n) ndarray + If `a` is square, then `u` is unitary. If m > n, then the columns + of `a` are orthonormal, and if m < n, then the rows of `u` are + orthonormal. + p : ndarray + `p` is Hermitian positive semidefinite. If `a` is nonsingular, `p` + is positive definite. The shape of `p` is (n, n) or (m, m), depending + on whether `side` is "right" or "left", respectively. + + References + ---------- + .. [1] R. A. Horn and C. R. Johnson, "Matrix Analysis", Cambridge + University Press, 1985. + .. [2] N. J. Higham, "Functions of Matrices: Theory and Computation", + SIAM, 2008. + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import polar + >>> a = np.array([[1, -1], [2, 4]]) + >>> u, p = polar(a) + >>> u + array([[ 0.85749293, -0.51449576], + [ 0.51449576, 0.85749293]]) + >>> p + array([[ 1.88648444, 1.2004901 ], + [ 1.2004901 , 3.94446746]]) + + A non-square example, with m < n: + + >>> b = np.array([[0.5, 1, 2], [1.5, 3, 4]]) + >>> u, p = polar(b) + >>> u + array([[-0.21196618, -0.42393237, 0.88054056], + [ 0.39378971, 0.78757942, 0.4739708 ]]) + >>> p + array([[ 0.48470147, 0.96940295, 1.15122648], + [ 0.96940295, 1.9388059 , 2.30245295], + [ 1.15122648, 2.30245295, 3.65696431]]) + >>> u.dot(p) # Verify the decomposition. + array([[ 0.5, 1. , 2. ], + [ 1.5, 3. , 4. ]]) + >>> u.dot(u.T) # The rows of u are orthonormal. + array([[ 1.00000000e+00, -2.07353665e-17], + [ -2.07353665e-17, 1.00000000e+00]]) + + Another non-square example, with m > n: + + >>> c = b.T + >>> u, p = polar(c) + >>> u + array([[-0.21196618, 0.39378971], + [-0.42393237, 0.78757942], + [ 0.88054056, 0.4739708 ]]) + >>> p + array([[ 1.23116567, 1.93241587], + [ 1.93241587, 4.84930602]]) + >>> u.dot(p) # Verify the decomposition. + array([[ 0.5, 1.5], + [ 1. , 3. ], + [ 2. , 4. ]]) + >>> u.T.dot(u) # The columns of u are orthonormal. + array([[ 1.00000000e+00, -1.26363763e-16], + [ -1.26363763e-16, 1.00000000e+00]]) + + """ + if side not in ['right', 'left']: + raise ValueError("`side` must be either 'right' or 'left'") + a = np.asarray(a) + if a.ndim != 2: + raise ValueError("`a` must be a 2-D array.") + + w, s, vh = svd(a, full_matrices=False) + u = w.dot(vh) + if side == 'right': + # a = up + p = (vh.T.conj() * s).dot(vh) + else: + # a = pu + p = (w * s).dot(w.T.conj()) + return u, p diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_decomp_qr.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_decomp_qr.py new file mode 100644 index 0000000000000000000000000000000000000000..a41ad90770e3d53c741d85e6f46d4040bf203e7a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_decomp_qr.py @@ -0,0 +1,490 @@ +"""QR decomposition functions.""" +import numpy as np + +# Local imports +from .lapack import get_lapack_funcs +from ._misc import _datacopied + +__all__ = ['qr', 'qr_multiply', 'rq'] + + +def safecall(f, name, *args, **kwargs): + """Call a LAPACK routine, determining lwork automatically and handling + error return values""" + lwork = kwargs.get("lwork", None) + if lwork in (None, -1): + kwargs['lwork'] = -1 + ret = f(*args, **kwargs) + kwargs['lwork'] = ret[-2][0].real.astype(np.int_) + ret = f(*args, **kwargs) + if ret[-1] < 0: + raise ValueError("illegal value in %dth argument of internal %s" + % (-ret[-1], name)) + return ret[:-2] + + +def qr(a, overwrite_a=False, lwork=None, mode='full', pivoting=False, + check_finite=True): + """ + Compute QR decomposition of a matrix. + + Calculate the decomposition ``A = Q R`` where Q is unitary/orthogonal + and R upper triangular. + + Parameters + ---------- + a : (M, N) array_like + Matrix to be decomposed + overwrite_a : bool, optional + Whether data in `a` is overwritten (may improve performance if + `overwrite_a` is set to True by reusing the existing input data + structure rather than creating a new one.) + lwork : int, optional + Work array size, lwork >= a.shape[1]. If None or -1, an optimal size + is computed. + mode : {'full', 'r', 'economic', 'raw'}, optional + Determines what information is to be returned: either both Q and R + ('full', default), only R ('r') or both Q and R but computed in + economy-size ('economic', see Notes). The final option 'raw' + (added in SciPy 0.11) makes the function return two matrices + (Q, TAU) in the internal format used by LAPACK. + pivoting : bool, optional + Whether or not factorization should include pivoting for rank-revealing + qr decomposition. If pivoting, compute the decomposition + ``A[:, P] = Q @ R`` as above, but where P is chosen such that the + diagonal of R is non-increasing. Equivalently, albeit less efficiently, + an explicit P matrix may be formed explicitly by permuting the rows or columns + (depending on the side of the equation on which it is to be used) of + an identity matrix. See Examples. + check_finite : bool, optional + Whether to check that the input matrix contains only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + + Returns + ------- + Q : float or complex ndarray + Of shape (M, M), or (M, K) for ``mode='economic'``. Not returned + if ``mode='r'``. Replaced by tuple ``(Q, TAU)`` if ``mode='raw'``. + R : float or complex ndarray + Of shape (M, N), or (K, N) for ``mode in ['economic', 'raw']``. + ``K = min(M, N)``. + P : int ndarray + Of shape (N,) for ``pivoting=True``. Not returned if + ``pivoting=False``. + + Raises + ------ + LinAlgError + Raised if decomposition fails + + Notes + ----- + This is an interface to the LAPACK routines dgeqrf, zgeqrf, + dorgqr, zungqr, dgeqp3, and zgeqp3. + + If ``mode=economic``, the shapes of Q and R are (M, K) and (K, N) instead + of (M,M) and (M,N), with ``K=min(M,N)``. + + Examples + -------- + >>> import numpy as np + >>> from scipy import linalg + >>> rng = np.random.default_rng() + >>> a = rng.standard_normal((9, 6)) + + >>> q, r = linalg.qr(a) + >>> np.allclose(a, np.dot(q, r)) + True + >>> q.shape, r.shape + ((9, 9), (9, 6)) + + >>> r2 = linalg.qr(a, mode='r') + >>> np.allclose(r, r2) + True + + >>> q3, r3 = linalg.qr(a, mode='economic') + >>> q3.shape, r3.shape + ((9, 6), (6, 6)) + + >>> q4, r4, p4 = linalg.qr(a, pivoting=True) + >>> d = np.abs(np.diag(r4)) + >>> np.all(d[1:] <= d[:-1]) + True + >>> np.allclose(a[:, p4], np.dot(q4, r4)) + True + >>> P = np.eye(p4.size)[p4] + >>> np.allclose(a, np.dot(q4, r4) @ P) + True + >>> np.allclose(a @ P.T, np.dot(q4, r4)) + True + >>> q4.shape, r4.shape, p4.shape + ((9, 9), (9, 6), (6,)) + + >>> q5, r5, p5 = linalg.qr(a, mode='economic', pivoting=True) + >>> q5.shape, r5.shape, p5.shape + ((9, 6), (6, 6), (6,)) + >>> P = np.eye(6)[:, p5] + >>> np.allclose(a @ P, np.dot(q5, r5)) + True + + """ + # 'qr' was the old default, equivalent to 'full'. Neither 'full' nor + # 'qr' are used below. + # 'raw' is used internally by qr_multiply + if mode not in ['full', 'qr', 'r', 'economic', 'raw']: + raise ValueError("Mode argument should be one of ['full', 'r', " + "'economic', 'raw']") + + if check_finite: + a1 = np.asarray_chkfinite(a) + else: + a1 = np.asarray(a) + if len(a1.shape) != 2: + raise ValueError("expected a 2-D array") + + M, N = a1.shape + + # accommodate empty arrays + if a1.size == 0: + K = min(M, N) + + if mode not in ['economic', 'raw']: + Q = np.empty_like(a1, shape=(M, M)) + Q[...] = np.identity(M) + R = np.empty_like(a1) + else: + Q = np.empty_like(a1, shape=(M, K)) + R = np.empty_like(a1, shape=(K, N)) + + if pivoting: + Rj = R, np.arange(N, dtype=np.int32) + else: + Rj = R, + + if mode == 'r': + return Rj + elif mode == 'raw': + qr = np.empty_like(a1, shape=(M, N)) + tau = np.zeros_like(a1, shape=(K,)) + return ((qr, tau),) + Rj + return (Q,) + Rj + + overwrite_a = overwrite_a or (_datacopied(a1, a)) + + if pivoting: + geqp3, = get_lapack_funcs(('geqp3',), (a1,)) + qr, jpvt, tau = safecall(geqp3, "geqp3", a1, overwrite_a=overwrite_a) + jpvt -= 1 # geqp3 returns a 1-based index array, so subtract 1 + else: + geqrf, = get_lapack_funcs(('geqrf',), (a1,)) + qr, tau = safecall(geqrf, "geqrf", a1, lwork=lwork, + overwrite_a=overwrite_a) + + if mode not in ['economic', 'raw'] or M < N: + R = np.triu(qr) + else: + R = np.triu(qr[:N, :]) + + if pivoting: + Rj = R, jpvt + else: + Rj = R, + + if mode == 'r': + return Rj + elif mode == 'raw': + return ((qr, tau),) + Rj + + gor_un_gqr, = get_lapack_funcs(('orgqr',), (qr,)) + + if M < N: + Q, = safecall(gor_un_gqr, "gorgqr/gungqr", qr[:, :M], tau, + lwork=lwork, overwrite_a=1) + elif mode == 'economic': + Q, = safecall(gor_un_gqr, "gorgqr/gungqr", qr, tau, lwork=lwork, + overwrite_a=1) + else: + t = qr.dtype.char + qqr = np.empty((M, M), dtype=t) + qqr[:, :N] = qr + Q, = safecall(gor_un_gqr, "gorgqr/gungqr", qqr, tau, lwork=lwork, + overwrite_a=1) + + return (Q,) + Rj + + +def qr_multiply(a, c, mode='right', pivoting=False, conjugate=False, + overwrite_a=False, overwrite_c=False): + """ + Calculate the QR decomposition and multiply Q with a matrix. + + Calculate the decomposition ``A = Q R`` where Q is unitary/orthogonal + and R upper triangular. Multiply Q with a vector or a matrix c. + + Parameters + ---------- + a : (M, N), array_like + Input array + c : array_like + Input array to be multiplied by ``q``. + mode : {'left', 'right'}, optional + ``Q @ c`` is returned if mode is 'left', ``c @ Q`` is returned if + mode is 'right'. + The shape of c must be appropriate for the matrix multiplications, + if mode is 'left', ``min(a.shape) == c.shape[0]``, + if mode is 'right', ``a.shape[0] == c.shape[1]``. + pivoting : bool, optional + Whether or not factorization should include pivoting for rank-revealing + qr decomposition, see the documentation of qr. + conjugate : bool, optional + Whether Q should be complex-conjugated. This might be faster + than explicit conjugation. + overwrite_a : bool, optional + Whether data in a is overwritten (may improve performance) + overwrite_c : bool, optional + Whether data in c is overwritten (may improve performance). + If this is used, c must be big enough to keep the result, + i.e. ``c.shape[0]`` = ``a.shape[0]`` if mode is 'left'. + + Returns + ------- + CQ : ndarray + The product of ``Q`` and ``c``. + R : (K, N), ndarray + R array of the resulting QR factorization where ``K = min(M, N)``. + P : (N,) ndarray + Integer pivot array. Only returned when ``pivoting=True``. + + Raises + ------ + LinAlgError + Raised if QR decomposition fails. + + Notes + ----- + This is an interface to the LAPACK routines ``?GEQRF``, ``?ORMQR``, + ``?UNMQR``, and ``?GEQP3``. + + .. versionadded:: 0.11.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import qr_multiply, qr + >>> A = np.array([[1, 3, 3], [2, 3, 2], [2, 3, 3], [1, 3, 2]]) + >>> qc, r1, piv1 = qr_multiply(A, 2*np.eye(4), pivoting=1) + >>> qc + array([[-1., 1., -1.], + [-1., -1., 1.], + [-1., -1., -1.], + [-1., 1., 1.]]) + >>> r1 + array([[-6., -3., -5. ], + [ 0., -1., -1.11022302e-16], + [ 0., 0., -1. ]]) + >>> piv1 + array([1, 0, 2], dtype=int32) + >>> q2, r2, piv2 = qr(A, mode='economic', pivoting=1) + >>> np.allclose(2*q2 - qc, np.zeros((4, 3))) + True + + """ + if mode not in ['left', 'right']: + raise ValueError("Mode argument can only be 'left' or 'right' but " + f"not '{mode}'") + c = np.asarray_chkfinite(c) + if c.ndim < 2: + onedim = True + c = np.atleast_2d(c) + if mode == "left": + c = c.T + else: + onedim = False + + a = np.atleast_2d(np.asarray(a)) # chkfinite done in qr + M, N = a.shape + + if mode == 'left': + if c.shape[0] != min(M, N + overwrite_c*(M-N)): + raise ValueError('Array shapes are not compatible for Q @ c' + f' operation: {a.shape} vs {c.shape}') + else: + if M != c.shape[1]: + raise ValueError('Array shapes are not compatible for c @ Q' + f' operation: {c.shape} vs {a.shape}') + + raw = qr(a, overwrite_a, None, "raw", pivoting) + Q, tau = raw[0] + + # accommodate empty arrays + if c.size == 0: + return (np.empty_like(c),) + raw[1:] + + gor_un_mqr, = get_lapack_funcs(('ormqr',), (Q,)) + if gor_un_mqr.typecode in ('s', 'd'): + trans = "T" + else: + trans = "C" + + Q = Q[:, :min(M, N)] + if M > N and mode == "left" and not overwrite_c: + if conjugate: + cc = np.zeros((c.shape[1], M), dtype=c.dtype, order="F") + cc[:, :N] = c.T + else: + cc = np.zeros((M, c.shape[1]), dtype=c.dtype, order="F") + cc[:N, :] = c + trans = "N" + if conjugate: + lr = "R" + else: + lr = "L" + overwrite_c = True + elif c.flags["C_CONTIGUOUS"] and trans == "T" or conjugate: + cc = c.T + if mode == "left": + lr = "R" + else: + lr = "L" + else: + trans = "N" + cc = c + if mode == "left": + lr = "L" + else: + lr = "R" + cQ, = safecall(gor_un_mqr, "gormqr/gunmqr", lr, trans, Q, tau, cc, + overwrite_c=overwrite_c) + if trans != "N": + cQ = cQ.T + if mode == "right": + cQ = cQ[:, :min(M, N)] + if onedim: + cQ = cQ.ravel() + + return (cQ,) + raw[1:] + + +def rq(a, overwrite_a=False, lwork=None, mode='full', check_finite=True): + """ + Compute RQ decomposition of a matrix. + + Calculate the decomposition ``A = R Q`` where Q is unitary/orthogonal + and R upper triangular. + + Parameters + ---------- + a : (M, N) array_like + Matrix to be decomposed + overwrite_a : bool, optional + Whether data in a is overwritten (may improve performance) + lwork : int, optional + Work array size, lwork >= a.shape[1]. If None or -1, an optimal size + is computed. + mode : {'full', 'r', 'economic'}, optional + Determines what information is to be returned: either both Q and R + ('full', default), only R ('r') or both Q and R but computed in + economy-size ('economic', see Notes). + check_finite : bool, optional + Whether to check that the input matrix contains only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + + Returns + ------- + R : float or complex ndarray + Of shape (M, N) or (M, K) for ``mode='economic'``. ``K = min(M, N)``. + Q : float or complex ndarray + Of shape (N, N) or (K, N) for ``mode='economic'``. Not returned + if ``mode='r'``. + + Raises + ------ + LinAlgError + If decomposition fails. + + Notes + ----- + This is an interface to the LAPACK routines sgerqf, dgerqf, cgerqf, zgerqf, + sorgrq, dorgrq, cungrq and zungrq. + + If ``mode=economic``, the shapes of Q and R are (K, N) and (M, K) instead + of (N,N) and (M,N), with ``K=min(M,N)``. + + Examples + -------- + >>> import numpy as np + >>> from scipy import linalg + >>> rng = np.random.default_rng() + >>> a = rng.standard_normal((6, 9)) + >>> r, q = linalg.rq(a) + >>> np.allclose(a, r @ q) + True + >>> r.shape, q.shape + ((6, 9), (9, 9)) + >>> r2 = linalg.rq(a, mode='r') + >>> np.allclose(r, r2) + True + >>> r3, q3 = linalg.rq(a, mode='economic') + >>> r3.shape, q3.shape + ((6, 6), (6, 9)) + + """ + if mode not in ['full', 'r', 'economic']: + raise ValueError( + "Mode argument should be one of ['full', 'r', 'economic']") + + if check_finite: + a1 = np.asarray_chkfinite(a) + else: + a1 = np.asarray(a) + if len(a1.shape) != 2: + raise ValueError('expected matrix') + + M, N = a1.shape + + # accommodate empty arrays + if a1.size == 0: + K = min(M, N) + + if not mode == 'economic': + R = np.empty_like(a1) + Q = np.empty_like(a1, shape=(N, N)) + Q[...] = np.identity(N) + else: + R = np.empty_like(a1, shape=(M, K)) + Q = np.empty_like(a1, shape=(K, N)) + + if mode == 'r': + return R + return R, Q + + overwrite_a = overwrite_a or (_datacopied(a1, a)) + + gerqf, = get_lapack_funcs(('gerqf',), (a1,)) + rq, tau = safecall(gerqf, 'gerqf', a1, lwork=lwork, + overwrite_a=overwrite_a) + if not mode == 'economic' or N < M: + R = np.triu(rq, N-M) + else: + R = np.triu(rq[-M:, -M:]) + + if mode == 'r': + return R + + gor_un_grq, = get_lapack_funcs(('orgrq',), (rq,)) + + if N < M: + Q, = safecall(gor_un_grq, "gorgrq/gungrq", rq[-N:], tau, lwork=lwork, + overwrite_a=1) + elif mode == 'economic': + Q, = safecall(gor_un_grq, "gorgrq/gungrq", rq, tau, lwork=lwork, + overwrite_a=1) + else: + rq1 = np.empty((N, N), dtype=rq.dtype) + rq1[-M:] = rq + Q, = safecall(gor_un_grq, "gorgrq/gungrq", rq1, tau, lwork=lwork, + overwrite_a=1) + + return R, Q diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_decomp_qz.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_decomp_qz.py new file mode 100644 index 0000000000000000000000000000000000000000..39361f172df7f1985c7ed0fbc4d919b5c4545725 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_decomp_qz.py @@ -0,0 +1,449 @@ +import warnings + +import numpy as np +from numpy import asarray_chkfinite +from ._misc import LinAlgError, _datacopied, LinAlgWarning +from .lapack import get_lapack_funcs + + +__all__ = ['qz', 'ordqz'] + +_double_precision = ['i', 'l', 'd'] + + +def _select_function(sort): + if callable(sort): + # assume the user knows what they're doing + sfunction = sort + elif sort == 'lhp': + sfunction = _lhp + elif sort == 'rhp': + sfunction = _rhp + elif sort == 'iuc': + sfunction = _iuc + elif sort == 'ouc': + sfunction = _ouc + else: + raise ValueError("sort parameter must be None, a callable, or " + "one of ('lhp','rhp','iuc','ouc')") + + return sfunction + + +def _lhp(x, y): + out = np.empty_like(x, dtype=bool) + nonzero = (y != 0) + # handles (x, y) = (0, 0) too + out[~nonzero] = False + out[nonzero] = (np.real(x[nonzero]/y[nonzero]) < 0.0) + return out + + +def _rhp(x, y): + out = np.empty_like(x, dtype=bool) + nonzero = (y != 0) + # handles (x, y) = (0, 0) too + out[~nonzero] = False + out[nonzero] = (np.real(x[nonzero]/y[nonzero]) > 0.0) + return out + + +def _iuc(x, y): + out = np.empty_like(x, dtype=bool) + nonzero = (y != 0) + # handles (x, y) = (0, 0) too + out[~nonzero] = False + out[nonzero] = (abs(x[nonzero]/y[nonzero]) < 1.0) + return out + + +def _ouc(x, y): + out = np.empty_like(x, dtype=bool) + xzero = (x == 0) + yzero = (y == 0) + out[xzero & yzero] = False + out[~xzero & yzero] = True + out[~yzero] = (abs(x[~yzero]/y[~yzero]) > 1.0) + return out + + +def _qz(A, B, output='real', lwork=None, sort=None, overwrite_a=False, + overwrite_b=False, check_finite=True): + if sort is not None: + # Disabled due to segfaults on win32, see ticket 1717. + raise ValueError("The 'sort' input of qz() has to be None and will be " + "removed in a future release. Use ordqz instead.") + + if output not in ['real', 'complex', 'r', 'c']: + raise ValueError("argument must be 'real', or 'complex'") + + if check_finite: + a1 = asarray_chkfinite(A) + b1 = asarray_chkfinite(B) + else: + a1 = np.asarray(A) + b1 = np.asarray(B) + + a_m, a_n = a1.shape + b_m, b_n = b1.shape + if not (a_m == a_n == b_m == b_n): + raise ValueError("Array dimensions must be square and agree") + + typa = a1.dtype.char + if output in ['complex', 'c'] and typa not in ['F', 'D']: + if typa in _double_precision: + a1 = a1.astype('D') + typa = 'D' + else: + a1 = a1.astype('F') + typa = 'F' + typb = b1.dtype.char + if output in ['complex', 'c'] and typb not in ['F', 'D']: + if typb in _double_precision: + b1 = b1.astype('D') + typb = 'D' + else: + b1 = b1.astype('F') + typb = 'F' + + overwrite_a = overwrite_a or (_datacopied(a1, A)) + overwrite_b = overwrite_b or (_datacopied(b1, B)) + + gges, = get_lapack_funcs(('gges',), (a1, b1)) + + if lwork is None or lwork == -1: + # get optimal work array size + result = gges(lambda x: None, a1, b1, lwork=-1) + lwork = result[-2][0].real.astype(int) + + def sfunction(x): + return None + result = gges(sfunction, a1, b1, lwork=lwork, overwrite_a=overwrite_a, + overwrite_b=overwrite_b, sort_t=0) + + info = result[-1] + if info < 0: + raise ValueError(f"Illegal value in argument {-info} of gges") + elif info > 0 and info <= a_n: + warnings.warn("The QZ iteration failed. (a,b) are not in Schur " + "form, but ALPHAR(j), ALPHAI(j), and BETA(j) should be " + f"correct for J={info-1},...,N", LinAlgWarning, + stacklevel=3) + elif info == a_n+1: + raise LinAlgError("Something other than QZ iteration failed") + elif info == a_n+2: + raise LinAlgError("After reordering, roundoff changed values of some " + "complex eigenvalues so that leading eigenvalues " + "in the Generalized Schur form no longer satisfy " + "sort=True. This could also be due to scaling.") + elif info == a_n+3: + raise LinAlgError("Reordering failed in tgsen") + + return result, gges.typecode + + +def qz(A, B, output='real', lwork=None, sort=None, overwrite_a=False, + overwrite_b=False, check_finite=True): + """ + QZ decomposition for generalized eigenvalues of a pair of matrices. + + The QZ, or generalized Schur, decomposition for a pair of n-by-n + matrices (A,B) is:: + + (A,B) = (Q @ AA @ Z*, Q @ BB @ Z*) + + where AA, BB is in generalized Schur form if BB is upper-triangular + with non-negative diagonal and AA is upper-triangular, or for real QZ + decomposition (``output='real'``) block upper triangular with 1x1 + and 2x2 blocks. In this case, the 1x1 blocks correspond to real + generalized eigenvalues and 2x2 blocks are 'standardized' by making + the corresponding elements of BB have the form:: + + [ a 0 ] + [ 0 b ] + + and the pair of corresponding 2x2 blocks in AA and BB will have a complex + conjugate pair of generalized eigenvalues. If (``output='complex'``) or + A and B are complex matrices, Z' denotes the conjugate-transpose of Z. + Q and Z are unitary matrices. + + Parameters + ---------- + A : (N, N) array_like + 2-D array to decompose + B : (N, N) array_like + 2-D array to decompose + output : {'real', 'complex'}, optional + Construct the real or complex QZ decomposition for real matrices. + Default is 'real'. + lwork : int, optional + Work array size. If None or -1, it is automatically computed. + sort : {None, callable, 'lhp', 'rhp', 'iuc', 'ouc'}, optional + NOTE: THIS INPUT IS DISABLED FOR NOW. Use ordqz instead. + + Specifies whether the upper eigenvalues should be sorted. A callable + may be passed that, given a eigenvalue, returns a boolean denoting + whether the eigenvalue should be sorted to the top-left (True). For + real matrix pairs, the sort function takes three real arguments + (alphar, alphai, beta). The eigenvalue + ``x = (alphar + alphai*1j)/beta``. For complex matrix pairs or + output='complex', the sort function takes two complex arguments + (alpha, beta). The eigenvalue ``x = (alpha/beta)``. Alternatively, + string parameters may be used: + + - 'lhp' Left-hand plane (x.real < 0.0) + - 'rhp' Right-hand plane (x.real > 0.0) + - 'iuc' Inside the unit circle (x*x.conjugate() < 1.0) + - 'ouc' Outside the unit circle (x*x.conjugate() > 1.0) + + Defaults to None (no sorting). + overwrite_a : bool, optional + Whether to overwrite data in a (may improve performance) + overwrite_b : bool, optional + Whether to overwrite data in b (may improve performance) + check_finite : bool, optional + If true checks the elements of `A` and `B` are finite numbers. If + false does no checking and passes matrix through to + underlying algorithm. + + Returns + ------- + AA : (N, N) ndarray + Generalized Schur form of A. + BB : (N, N) ndarray + Generalized Schur form of B. + Q : (N, N) ndarray + The left Schur vectors. + Z : (N, N) ndarray + The right Schur vectors. + + See Also + -------- + ordqz + + Notes + ----- + Q is transposed versus the equivalent function in Matlab. + + .. versionadded:: 0.11.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import qz + + >>> A = np.array([[1, 2, -1], [5, 5, 5], [2, 4, -8]]) + >>> B = np.array([[1, 1, -3], [3, 1, -1], [5, 6, -2]]) + + Compute the decomposition. The QZ decomposition is not unique, so + depending on the underlying library that is used, there may be + differences in the signs of coefficients in the following output. + + >>> AA, BB, Q, Z = qz(A, B) + >>> AA + array([[-1.36949157, -4.05459025, 7.44389431], + [ 0. , 7.65653432, 5.13476017], + [ 0. , -0.65978437, 2.4186015 ]]) # may vary + >>> BB + array([[ 1.71890633, -1.64723705, -0.72696385], + [ 0. , 8.6965692 , -0. ], + [ 0. , 0. , 2.27446233]]) # may vary + >>> Q + array([[-0.37048362, 0.1903278 , 0.90912992], + [-0.90073232, 0.16534124, -0.40167593], + [ 0.22676676, 0.96769706, -0.11017818]]) # may vary + >>> Z + array([[-0.67660785, 0.63528924, -0.37230283], + [ 0.70243299, 0.70853819, -0.06753907], + [ 0.22088393, -0.30721526, -0.92565062]]) # may vary + + Verify the QZ decomposition. With real output, we only need the + transpose of ``Z`` in the following expressions. + + >>> Q @ AA @ Z.T # Should be A + array([[ 1., 2., -1.], + [ 5., 5., 5.], + [ 2., 4., -8.]]) + >>> Q @ BB @ Z.T # Should be B + array([[ 1., 1., -3.], + [ 3., 1., -1.], + [ 5., 6., -2.]]) + + Repeat the decomposition, but with ``output='complex'``. + + >>> AA, BB, Q, Z = qz(A, B, output='complex') + + For conciseness in the output, we use ``np.set_printoptions()`` to set + the output precision of NumPy arrays to 3 and display tiny values as 0. + + >>> np.set_printoptions(precision=3, suppress=True) + >>> AA + array([[-1.369+0.j , 2.248+4.237j, 4.861-5.022j], + [ 0. +0.j , 7.037+2.922j, 0.794+4.932j], + [ 0. +0.j , 0. +0.j , 2.655-1.103j]]) # may vary + >>> BB + array([[ 1.719+0.j , -1.115+1.j , -0.763-0.646j], + [ 0. +0.j , 7.24 +0.j , -3.144+3.322j], + [ 0. +0.j , 0. +0.j , 2.732+0.j ]]) # may vary + >>> Q + array([[ 0.326+0.175j, -0.273-0.029j, -0.886-0.052j], + [ 0.794+0.426j, -0.093+0.134j, 0.402-0.02j ], + [-0.2 -0.107j, -0.816+0.482j, 0.151-0.167j]]) # may vary + >>> Z + array([[ 0.596+0.32j , -0.31 +0.414j, 0.393-0.347j], + [-0.619-0.332j, -0.479+0.314j, 0.154-0.393j], + [-0.195-0.104j, 0.576+0.27j , 0.715+0.187j]]) # may vary + + With complex arrays, we must use ``Z.conj().T`` in the following + expressions to verify the decomposition. + + >>> Q @ AA @ Z.conj().T # Should be A + array([[ 1.-0.j, 2.-0.j, -1.-0.j], + [ 5.+0.j, 5.+0.j, 5.-0.j], + [ 2.+0.j, 4.+0.j, -8.+0.j]]) + >>> Q @ BB @ Z.conj().T # Should be B + array([[ 1.+0.j, 1.+0.j, -3.+0.j], + [ 3.-0.j, 1.-0.j, -1.+0.j], + [ 5.+0.j, 6.+0.j, -2.+0.j]]) + + """ + # output for real + # AA, BB, sdim, alphar, alphai, beta, vsl, vsr, work, info + # output for complex + # AA, BB, sdim, alpha, beta, vsl, vsr, work, info + result, _ = _qz(A, B, output=output, lwork=lwork, sort=sort, + overwrite_a=overwrite_a, overwrite_b=overwrite_b, + check_finite=check_finite) + return result[0], result[1], result[-4], result[-3] + + +def ordqz(A, B, sort='lhp', output='real', overwrite_a=False, + overwrite_b=False, check_finite=True): + """QZ decomposition for a pair of matrices with reordering. + + Parameters + ---------- + A : (N, N) array_like + 2-D array to decompose + B : (N, N) array_like + 2-D array to decompose + sort : {callable, 'lhp', 'rhp', 'iuc', 'ouc'}, optional + Specifies whether the upper eigenvalues should be sorted. A + callable may be passed that, given an ordered pair ``(alpha, + beta)`` representing the eigenvalue ``x = (alpha/beta)``, + returns a boolean denoting whether the eigenvalue should be + sorted to the top-left (True). For the real matrix pairs + ``beta`` is real while ``alpha`` can be complex, and for + complex matrix pairs both ``alpha`` and ``beta`` can be + complex. The callable must be able to accept a NumPy + array. Alternatively, string parameters may be used: + + - 'lhp' Left-hand plane (x.real < 0.0) + - 'rhp' Right-hand plane (x.real > 0.0) + - 'iuc' Inside the unit circle (x*x.conjugate() < 1.0) + - 'ouc' Outside the unit circle (x*x.conjugate() > 1.0) + + With the predefined sorting functions, an infinite eigenvalue + (i.e., ``alpha != 0`` and ``beta = 0``) is considered to lie in + neither the left-hand nor the right-hand plane, but it is + considered to lie outside the unit circle. For the eigenvalue + ``(alpha, beta) = (0, 0)``, the predefined sorting functions + all return `False`. + output : str {'real','complex'}, optional + Construct the real or complex QZ decomposition for real matrices. + Default is 'real'. + overwrite_a : bool, optional + If True, the contents of A are overwritten. + overwrite_b : bool, optional + If True, the contents of B are overwritten. + check_finite : bool, optional + If true checks the elements of `A` and `B` are finite numbers. If + false does no checking and passes matrix through to + underlying algorithm. + + Returns + ------- + AA : (N, N) ndarray + Generalized Schur form of A. + BB : (N, N) ndarray + Generalized Schur form of B. + alpha : (N,) ndarray + alpha = alphar + alphai * 1j. See notes. + beta : (N,) ndarray + See notes. + Q : (N, N) ndarray + The left Schur vectors. + Z : (N, N) ndarray + The right Schur vectors. + + See Also + -------- + qz + + Notes + ----- + On exit, ``(ALPHAR(j) + ALPHAI(j)*i)/BETA(j), j=1,...,N``, will be the + generalized eigenvalues. ``ALPHAR(j) + ALPHAI(j)*i`` and + ``BETA(j),j=1,...,N`` are the diagonals of the complex Schur form (S,T) + that would result if the 2-by-2 diagonal blocks of the real generalized + Schur form of (A,B) were further reduced to triangular form using complex + unitary transformations. If ALPHAI(j) is zero, then the jth eigenvalue is + real; if positive, then the ``j``\\ th and ``(j+1)``\\ st eigenvalues are a + complex conjugate pair, with ``ALPHAI(j+1)`` negative. + + .. versionadded:: 0.17.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import ordqz + >>> A = np.array([[2, 5, 8, 7], [5, 2, 2, 8], [7, 5, 6, 6], [5, 4, 4, 8]]) + >>> B = np.array([[0, 6, 0, 0], [5, 0, 2, 1], [5, 2, 6, 6], [4, 7, 7, 7]]) + >>> AA, BB, alpha, beta, Q, Z = ordqz(A, B, sort='lhp') + + Since we have sorted for left half plane eigenvalues, negatives come first + + >>> (alpha/beta).real < 0 + array([ True, True, False, False], dtype=bool) + + """ + (AA, BB, _, *ab, Q, Z, _, _), typ = _qz(A, B, output=output, sort=None, + overwrite_a=overwrite_a, + overwrite_b=overwrite_b, + check_finite=check_finite) + + if typ == 's': + alpha, beta = ab[0] + ab[1]*np.complex64(1j), ab[2] + elif typ == 'd': + alpha, beta = ab[0] + ab[1]*1.j, ab[2] + else: + alpha, beta = ab + + sfunction = _select_function(sort) + select = sfunction(alpha, beta) + + tgsen = get_lapack_funcs('tgsen', (AA, BB)) + # the real case needs 4n + 16 lwork + lwork = 4*AA.shape[0] + 16 if typ in 'sd' else 1 + AAA, BBB, *ab, QQ, ZZ, _, _, _, _, info = tgsen(select, AA, BB, Q, Z, + ijob=0, + lwork=lwork, liwork=1) + + # Once more for tgsen output + if typ == 's': + alpha, beta = ab[0] + ab[1]*np.complex64(1j), ab[2] + elif typ == 'd': + alpha, beta = ab[0] + ab[1]*1.j, ab[2] + else: + alpha, beta = ab + + if info < 0: + raise ValueError(f"Illegal value in argument {-info} of tgsen") + elif info == 1: + raise ValueError("Reordering of (A, B) failed because the transformed" + " matrix pair (A, B) would be too far from " + "generalized Schur form; the problem is very " + "ill-conditioned. (A, B) may have been partially " + "reordered.") + + return AAA, BBB, alpha, beta, QQ, ZZ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_decomp_schur.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_decomp_schur.py new file mode 100644 index 0000000000000000000000000000000000000000..8609a175e16d663938386c6b45d190cd0e5dafd8 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_decomp_schur.py @@ -0,0 +1,334 @@ +"""Schur decomposition functions.""" +import numpy as np +from numpy import asarray_chkfinite, single, asarray, array +from numpy.linalg import norm + + +# Local imports. +from ._misc import LinAlgError, _datacopied +from .lapack import get_lapack_funcs +from ._decomp import eigvals + +__all__ = ['schur', 'rsf2csf'] + +_double_precision = ['i', 'l', 'd'] + + +def schur(a, output='real', lwork=None, overwrite_a=False, sort=None, + check_finite=True): + """ + Compute Schur decomposition of a matrix. + + The Schur decomposition is:: + + A = Z T Z^H + + where Z is unitary and T is either upper-triangular, or for real + Schur decomposition (output='real'), quasi-upper triangular. In + the quasi-triangular form, 2x2 blocks describing complex-valued + eigenvalue pairs may extrude from the diagonal. + + Parameters + ---------- + a : (M, M) array_like + Matrix to decompose + output : {'real', 'complex'}, optional + When the dtype of `a` is real, this specifies whether to compute + the real or complex Schur decomposition. + When the dtype of `a` is complex, this argument is ignored, and the + complex Schur decomposition is computed. + lwork : int, optional + Work array size. If None or -1, it is automatically computed. + overwrite_a : bool, optional + Whether to overwrite data in a (may improve performance). + sort : {None, callable, 'lhp', 'rhp', 'iuc', 'ouc'}, optional + Specifies whether the upper eigenvalues should be sorted. A callable + may be passed that, given an eigenvalue, returns a boolean denoting + whether the eigenvalue should be sorted to the top-left (True). + + - If ``output='complex'`` OR the dtype of `a` is complex, the callable + should have one argument: the eigenvalue expressed as a complex number. + - If ``output='real'`` AND the dtype of `a` is real, the callable should have + two arguments: the real and imaginary parts of the eigenvalue, respectively. + + Alternatively, string parameters may be used:: + + 'lhp' Left-hand plane (real(eigenvalue) < 0.0) + 'rhp' Right-hand plane (real(eigenvalue) >= 0.0) + 'iuc' Inside the unit circle (abs(eigenvalue) <= 1.0) + 'ouc' Outside the unit circle (abs(eigenvalue) > 1.0) + + Defaults to None (no sorting). + check_finite : bool, optional + Whether to check that the input matrix contains only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + + Returns + ------- + T : (M, M) ndarray + Schur form of A. It is real-valued for the real Schur decomposition. + Z : (M, M) ndarray + An unitary Schur transformation matrix for A. + It is real-valued for the real Schur decomposition. + sdim : int + If and only if sorting was requested, a third return value will + contain the number of eigenvalues satisfying the sort condition. + Note that complex conjugate pairs for which the condition is true + for either eigenvalue count as 2. + + Raises + ------ + LinAlgError + Error raised under three conditions: + + 1. The algorithm failed due to a failure of the QR algorithm to + compute all eigenvalues. + 2. If eigenvalue sorting was requested, the eigenvalues could not be + reordered due to a failure to separate eigenvalues, usually because + of poor conditioning. + 3. If eigenvalue sorting was requested, roundoff errors caused the + leading eigenvalues to no longer satisfy the sorting condition. + + See Also + -------- + rsf2csf : Convert real Schur form to complex Schur form + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import schur, eigvals + >>> A = np.array([[0, 2, 2], [0, 1, 2], [1, 0, 1]]) + >>> T, Z = schur(A) + >>> T + array([[ 2.65896708, 1.42440458, -1.92933439], + [ 0. , -0.32948354, -0.49063704], + [ 0. , 1.31178921, -0.32948354]]) + >>> Z + array([[0.72711591, -0.60156188, 0.33079564], + [0.52839428, 0.79801892, 0.28976765], + [0.43829436, 0.03590414, -0.89811411]]) + + >>> T2, Z2 = schur(A, output='complex') + >>> T2 + array([[ 2.65896708, -1.22839825+1.32378589j, 0.42590089+1.51937378j], # may vary + [ 0. , -0.32948354+0.80225456j, -0.59877807+0.56192146j], + [ 0. , 0. , -0.32948354-0.80225456j]]) + >>> eigvals(T2) + array([2.65896708, -0.32948354+0.80225456j, -0.32948354-0.80225456j]) # may vary + + A custom eigenvalue-sorting condition that sorts by positive imaginary part + is satisfied by only one eigenvalue. + + >>> _, _, sdim = schur(A, output='complex', sort=lambda x: x.imag > 1e-15) + >>> sdim + 1 + + When ``output='real'`` and the array `a` is real, the `sort` callable must accept + the real and imaginary parts as separate arguments. Note that now the complex + eigenvalues ``-0.32948354+0.80225456j`` and ``-0.32948354-0.80225456j`` will be + treated as a complex conjugate pair, and according to the `sdim` documentation, + complex conjugate pairs for which the condition is True for *either* eigenvalue + increase `sdim` by *two*. + + >>> _, _, sdim = schur(A, output='real', sort=lambda x, y: y > 1e-15) + >>> sdim + 2 + + """ + if output not in ['real', 'complex', 'r', 'c']: + raise ValueError("argument must be 'real', or 'complex'") + if check_finite: + a1 = asarray_chkfinite(a) + else: + a1 = asarray(a) + if np.issubdtype(a1.dtype, np.integer): + a1 = asarray(a, dtype=np.dtype("long")) + if len(a1.shape) != 2 or (a1.shape[0] != a1.shape[1]): + raise ValueError('expected square matrix') + + typ = a1.dtype.char + if output in ['complex', 'c'] and typ not in ['F', 'D']: + if typ in _double_precision: + a1 = a1.astype('D') + else: + a1 = a1.astype('F') + + # accommodate empty matrix + if a1.size == 0: + t0, z0 = schur(np.eye(2, dtype=a1.dtype)) + if sort is None: + return (np.empty_like(a1, dtype=t0.dtype), + np.empty_like(a1, dtype=z0.dtype)) + else: + return (np.empty_like(a1, dtype=t0.dtype), + np.empty_like(a1, dtype=z0.dtype), 0) + + overwrite_a = overwrite_a or (_datacopied(a1, a)) + gees, = get_lapack_funcs(('gees',), (a1,)) + if lwork is None or lwork == -1: + # get optimal work array + result = gees(lambda x: None, a1, lwork=-1) + lwork = result[-2][0].real.astype(np.int_) + + if sort is None: + sort_t = 0 + def sfunction(x, y=None): + return None + else: + sort_t = 1 + if callable(sort): + sfunction = sort + elif sort == 'lhp': + def sfunction(x, y=None): + return x.real < 0.0 + elif sort == 'rhp': + def sfunction(x, y=None): + return x.real >= 0.0 + elif sort == 'iuc': + def sfunction(x, y=None): + z = x if y is None else x + y*1j + return abs(z) <= 1.0 + elif sort == 'ouc': + def sfunction(x, y=None): + z = x if y is None else x + y*1j + return abs(z) > 1.0 + else: + raise ValueError("'sort' parameter must either be 'None', or a " + "callable, or one of ('lhp','rhp','iuc','ouc')") + + result = gees(sfunction, a1, lwork=lwork, overwrite_a=overwrite_a, + sort_t=sort_t) + + info = result[-1] + if info < 0: + raise ValueError(f'illegal value in {-info}-th argument of internal gees') + elif info == a1.shape[0] + 1: + raise LinAlgError('Eigenvalues could not be separated for reordering.') + elif info == a1.shape[0] + 2: + raise LinAlgError('Leading eigenvalues do not satisfy sort condition.') + elif info > 0: + raise LinAlgError("Schur form not found. Possibly ill-conditioned.") + + if sort is None: + return result[0], result[-3] + else: + return result[0], result[-3], result[1] + + +eps = np.finfo(float).eps +feps = np.finfo(single).eps + +_array_kind = {'b': 0, 'h': 0, 'B': 0, 'i': 0, 'l': 0, + 'f': 0, 'd': 0, 'F': 1, 'D': 1} +_array_precision = {'i': 1, 'l': 1, 'f': 0, 'd': 1, 'F': 0, 'D': 1} +_array_type = [['f', 'd'], ['F', 'D']] + + +def _commonType(*arrays): + kind = 0 + precision = 0 + for a in arrays: + t = a.dtype.char + kind = max(kind, _array_kind[t]) + precision = max(precision, _array_precision[t]) + return _array_type[kind][precision] + + +def _castCopy(type, *arrays): + cast_arrays = () + for a in arrays: + if a.dtype.char == type: + cast_arrays = cast_arrays + (a.copy(),) + else: + cast_arrays = cast_arrays + (a.astype(type),) + if len(cast_arrays) == 1: + return cast_arrays[0] + else: + return cast_arrays + + +def rsf2csf(T, Z, check_finite=True): + """ + Convert real Schur form to complex Schur form. + + Convert a quasi-diagonal real-valued Schur form to the upper-triangular + complex-valued Schur form. + + Parameters + ---------- + T : (M, M) array_like + Real Schur form of the original array + Z : (M, M) array_like + Schur transformation matrix + check_finite : bool, optional + Whether to check that the input arrays contain only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + + Returns + ------- + T : (M, M) ndarray + Complex Schur form of the original array + Z : (M, M) ndarray + Schur transformation matrix corresponding to the complex form + + See Also + -------- + schur : Schur decomposition of an array + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import schur, rsf2csf + >>> A = np.array([[0, 2, 2], [0, 1, 2], [1, 0, 1]]) + >>> T, Z = schur(A) + >>> T + array([[ 2.65896708, 1.42440458, -1.92933439], + [ 0. , -0.32948354, -0.49063704], + [ 0. , 1.31178921, -0.32948354]]) + >>> Z + array([[0.72711591, -0.60156188, 0.33079564], + [0.52839428, 0.79801892, 0.28976765], + [0.43829436, 0.03590414, -0.89811411]]) + >>> T2 , Z2 = rsf2csf(T, Z) + >>> T2 + array([[2.65896708+0.j, -1.64592781+0.743164187j, -1.21516887+1.00660462j], + [0.+0.j , -0.32948354+8.02254558e-01j, -0.82115218-2.77555756e-17j], + [0.+0.j , 0.+0.j, -0.32948354-0.802254558j]]) + >>> Z2 + array([[0.72711591+0.j, 0.28220393-0.31385693j, 0.51319638-0.17258824j], + [0.52839428+0.j, 0.24720268+0.41635578j, -0.68079517-0.15118243j], + [0.43829436+0.j, -0.76618703+0.01873251j, -0.03063006+0.46857912j]]) + + """ + if check_finite: + Z, T = map(asarray_chkfinite, (Z, T)) + else: + Z, T = map(asarray, (Z, T)) + + for ind, X in enumerate([Z, T]): + if X.ndim != 2 or X.shape[0] != X.shape[1]: + raise ValueError(f"Input '{'ZT'[ind]}' must be square.") + + if T.shape[0] != Z.shape[0]: + message = f"Input array shapes must match: Z: {Z.shape} vs. T: {T.shape}" + raise ValueError(message) + N = T.shape[0] + t = _commonType(Z, T, array([3.0], 'F')) + Z, T = _castCopy(t, Z, T) + + for m in range(N-1, 0, -1): + if abs(T[m, m-1]) > eps*(abs(T[m-1, m-1]) + abs(T[m, m])): + mu = eigvals(T[m-1:m+1, m-1:m+1]) - T[m, m] + r = norm([mu[0], T[m, m-1]]) + c = mu[0] / r + s = T[m, m-1] / r + G = array([[c.conj(), s], [-s, c]], dtype=t) + + T[m-1:m+1, m-1:] = G.dot(T[m-1:m+1, m-1:]) + T[:m+1, m-1:m+1] = T[:m+1, m-1:m+1].dot(G.conj().T) + Z[:, m-1:m+1] = Z[:, m-1:m+1].dot(G.conj().T) + + T[m, m-1] = 0.0 + return T, Z diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_decomp_svd.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_decomp_svd.py new file mode 100644 index 0000000000000000000000000000000000000000..98425f6c11e727d582102dce72baeb9cbdb6c40b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_decomp_svd.py @@ -0,0 +1,534 @@ +"""SVD decomposition functions.""" +import numpy as np +from numpy import zeros, r_, diag, dot, arccos, arcsin, where, clip + +# Local imports. +from ._misc import LinAlgError, _datacopied +from .lapack import get_lapack_funcs, _compute_lwork +from ._decomp import _asarray_validated + +__all__ = ['svd', 'svdvals', 'diagsvd', 'orth', 'subspace_angles', 'null_space'] + + +def svd(a, full_matrices=True, compute_uv=True, overwrite_a=False, + check_finite=True, lapack_driver='gesdd'): + """ + Singular Value Decomposition. + + Factorizes the matrix `a` into two unitary matrices ``U`` and ``Vh``, and + a 1-D array ``s`` of singular values (real, non-negative) such that + ``a == U @ S @ Vh``, where ``S`` is a suitably shaped matrix of zeros with + main diagonal ``s``. + + Parameters + ---------- + a : (M, N) array_like + Matrix to decompose. + full_matrices : bool, optional + If True (default), `U` and `Vh` are of shape ``(M, M)``, ``(N, N)``. + If False, the shapes are ``(M, K)`` and ``(K, N)``, where + ``K = min(M, N)``. + compute_uv : bool, optional + Whether to compute also ``U`` and ``Vh`` in addition to ``s``. + Default is True. + overwrite_a : bool, optional + Whether to overwrite `a`; may improve performance. + Default is False. + check_finite : bool, optional + Whether to check that the input matrix contains only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + lapack_driver : {'gesdd', 'gesvd'}, optional + Whether to use the more efficient divide-and-conquer approach + (``'gesdd'``) or general rectangular approach (``'gesvd'``) + to compute the SVD. MATLAB and Octave use the ``'gesvd'`` approach. + Default is ``'gesdd'``. + + Returns + ------- + U : ndarray + Unitary matrix having left singular vectors as columns. + Of shape ``(M, M)`` or ``(M, K)``, depending on `full_matrices`. + s : ndarray + The singular values, sorted in non-increasing order. + Of shape (K,), with ``K = min(M, N)``. + Vh : ndarray + Unitary matrix having right singular vectors as rows. + Of shape ``(N, N)`` or ``(K, N)`` depending on `full_matrices`. + + For ``compute_uv=False``, only ``s`` is returned. + + Raises + ------ + LinAlgError + If SVD computation does not converge. + + See Also + -------- + svdvals : Compute singular values of a matrix. + diagsvd : Construct the Sigma matrix, given the vector s. + + Examples + -------- + >>> import numpy as np + >>> from scipy import linalg + >>> rng = np.random.default_rng() + >>> m, n = 9, 6 + >>> a = rng.standard_normal((m, n)) + 1.j*rng.standard_normal((m, n)) + >>> U, s, Vh = linalg.svd(a) + >>> U.shape, s.shape, Vh.shape + ((9, 9), (6,), (6, 6)) + + Reconstruct the original matrix from the decomposition: + + >>> sigma = np.zeros((m, n)) + >>> for i in range(min(m, n)): + ... sigma[i, i] = s[i] + >>> a1 = np.dot(U, np.dot(sigma, Vh)) + >>> np.allclose(a, a1) + True + + Alternatively, use ``full_matrices=False`` (notice that the shape of + ``U`` is then ``(m, n)`` instead of ``(m, m)``): + + >>> U, s, Vh = linalg.svd(a, full_matrices=False) + >>> U.shape, s.shape, Vh.shape + ((9, 6), (6,), (6, 6)) + >>> S = np.diag(s) + >>> np.allclose(a, np.dot(U, np.dot(S, Vh))) + True + + >>> s2 = linalg.svd(a, compute_uv=False) + >>> np.allclose(s, s2) + True + + """ + a1 = _asarray_validated(a, check_finite=check_finite) + if len(a1.shape) != 2: + raise ValueError('expected matrix') + m, n = a1.shape + + # accommodate empty matrix + if a1.size == 0: + u0, s0, v0 = svd(np.eye(2, dtype=a1.dtype)) + + s = np.empty_like(a1, shape=(0,), dtype=s0.dtype) + if full_matrices: + u = np.empty_like(a1, shape=(m, m), dtype=u0.dtype) + u[...] = np.identity(m) + v = np.empty_like(a1, shape=(n, n), dtype=v0.dtype) + v[...] = np.identity(n) + else: + u = np.empty_like(a1, shape=(m, 0), dtype=u0.dtype) + v = np.empty_like(a1, shape=(0, n), dtype=v0.dtype) + if compute_uv: + return u, s, v + else: + return s + + overwrite_a = overwrite_a or (_datacopied(a1, a)) + + if not isinstance(lapack_driver, str): + raise TypeError('lapack_driver must be a string') + if lapack_driver not in ('gesdd', 'gesvd'): + message = f'lapack_driver must be "gesdd" or "gesvd", not "{lapack_driver}"' + raise ValueError(message) + + if compute_uv: + # XXX: revisit int32 when ILP64 lapack becomes a thing + max_mn, min_mn = (m, n) if m > n else (n, m) + if full_matrices: + if max_mn*max_mn > np.iinfo(np.int32).max: + raise ValueError(f"Indexing a matrix size {max_mn} x {max_mn} " + "would incur integer overflow in LAPACK. " + "Try using numpy.linalg.svd instead.") + else: + sz = max(m * min_mn, n * min_mn) + if max(m * min_mn, n * min_mn) > np.iinfo(np.int32).max: + raise ValueError(f"Indexing a matrix of {sz} elements would " + "incur an in integer overflow in LAPACK. " + "Try using numpy.linalg.svd instead.") + + funcs = (lapack_driver, lapack_driver + '_lwork') + # XXX: As of 1.14.1 it isn't possible to build SciPy with ILP64, + # so the following line always yields a LP64 (32-bit pointer size) variant + gesXd, gesXd_lwork = get_lapack_funcs(funcs, (a1,), ilp64="preferred") + + # compute optimal lwork + lwork = _compute_lwork(gesXd_lwork, a1.shape[0], a1.shape[1], + compute_uv=compute_uv, full_matrices=full_matrices) + + # perform decomposition + u, s, v, info = gesXd(a1, compute_uv=compute_uv, lwork=lwork, + full_matrices=full_matrices, overwrite_a=overwrite_a) + + if info > 0: + raise LinAlgError("SVD did not converge") + if info < 0: + raise ValueError('illegal value in %dth argument of internal gesdd' + % -info) + if compute_uv: + return u, s, v + else: + return s + + +def svdvals(a, overwrite_a=False, check_finite=True): + """ + Compute singular values of a matrix. + + Parameters + ---------- + a : (M, N) array_like + Matrix to decompose. + overwrite_a : bool, optional + Whether to overwrite `a`; may improve performance. + Default is False. + check_finite : bool, optional + Whether to check that the input matrix contains only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + + Returns + ------- + s : (min(M, N),) ndarray + The singular values, sorted in decreasing order. + + Raises + ------ + LinAlgError + If SVD computation does not converge. + + See Also + -------- + svd : Compute the full singular value decomposition of a matrix. + diagsvd : Construct the Sigma matrix, given the vector s. + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import svdvals + >>> m = np.array([[1.0, 0.0], + ... [2.0, 3.0], + ... [1.0, 1.0], + ... [0.0, 2.0], + ... [1.0, 0.0]]) + >>> svdvals(m) + array([ 4.28091555, 1.63516424]) + + We can verify the maximum singular value of `m` by computing the maximum + length of `m.dot(u)` over all the unit vectors `u` in the (x,y) plane. + We approximate "all" the unit vectors with a large sample. Because + of linearity, we only need the unit vectors with angles in [0, pi]. + + >>> t = np.linspace(0, np.pi, 2000) + >>> u = np.array([np.cos(t), np.sin(t)]) + >>> np.linalg.norm(m.dot(u), axis=0).max() + 4.2809152422538475 + + `p` is a projection matrix with rank 1. With exact arithmetic, + its singular values would be [1, 0, 0, 0]. + + >>> v = np.array([0.1, 0.3, 0.9, 0.3]) + >>> p = np.outer(v, v) + >>> svdvals(p) + array([ 1.00000000e+00, 2.02021698e-17, 1.56692500e-17, + 8.15115104e-34]) + + The singular values of an orthogonal matrix are all 1. Here, we + create a random orthogonal matrix by using the `rvs()` method of + `scipy.stats.ortho_group`. + + >>> from scipy.stats import ortho_group + >>> orth = ortho_group.rvs(4) + >>> svdvals(orth) + array([ 1., 1., 1., 1.]) + + """ + return svd(a, compute_uv=0, overwrite_a=overwrite_a, + check_finite=check_finite) + + +def diagsvd(s, M, N): + """ + Construct the sigma matrix in SVD from singular values and size M, N. + + Parameters + ---------- + s : (M,) or (N,) array_like + Singular values + M : int + Size of the matrix whose singular values are `s`. + N : int + Size of the matrix whose singular values are `s`. + + Returns + ------- + S : (M, N) ndarray + The S-matrix in the singular value decomposition + + See Also + -------- + svd : Singular value decomposition of a matrix + svdvals : Compute singular values of a matrix. + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import diagsvd + >>> vals = np.array([1, 2, 3]) # The array representing the computed svd + >>> diagsvd(vals, 3, 4) + array([[1, 0, 0, 0], + [0, 2, 0, 0], + [0, 0, 3, 0]]) + >>> diagsvd(vals, 4, 3) + array([[1, 0, 0], + [0, 2, 0], + [0, 0, 3], + [0, 0, 0]]) + + """ + part = diag(s) + typ = part.dtype.char + MorN = len(s) + if MorN == M: + return np.hstack((part, zeros((M, N - M), dtype=typ))) + elif MorN == N: + return r_[part, zeros((M - N, N), dtype=typ)] + else: + raise ValueError("Length of s must be M or N.") + + +# Orthonormal decomposition + +def orth(A, rcond=None): + """ + Construct an orthonormal basis for the range of A using SVD + + Parameters + ---------- + A : (M, N) array_like + Input array + rcond : float, optional + Relative condition number. Singular values ``s`` smaller than + ``rcond * max(s)`` are considered zero. + Default: floating point eps * max(M,N). + + Returns + ------- + Q : (M, K) ndarray + Orthonormal basis for the range of A. + K = effective rank of A, as determined by rcond + + See Also + -------- + svd : Singular value decomposition of a matrix + null_space : Matrix null space + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import orth + >>> A = np.array([[2, 0, 0], [0, 5, 0]]) # rank 2 array + >>> orth(A) + array([[0., 1.], + [1., 0.]]) + >>> orth(A.T) + array([[0., 1.], + [1., 0.], + [0., 0.]]) + + """ + u, s, vh = svd(A, full_matrices=False) + M, N = u.shape[0], vh.shape[1] + if rcond is None: + rcond = np.finfo(s.dtype).eps * max(M, N) + tol = np.amax(s, initial=0.) * rcond + num = np.sum(s > tol, dtype=int) + Q = u[:, :num] + return Q + + +def null_space(A, rcond=None, *, overwrite_a=False, check_finite=True, + lapack_driver='gesdd'): + """ + Construct an orthonormal basis for the null space of A using SVD + + Parameters + ---------- + A : (M, N) array_like + Input array + rcond : float, optional + Relative condition number. Singular values ``s`` smaller than + ``rcond * max(s)`` are considered zero. + Default: floating point eps * max(M,N). + overwrite_a : bool, optional + Whether to overwrite `a`; may improve performance. + Default is False. + check_finite : bool, optional + Whether to check that the input matrix contains only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + lapack_driver : {'gesdd', 'gesvd'}, optional + Whether to use the more efficient divide-and-conquer approach + (``'gesdd'``) or general rectangular approach (``'gesvd'``) + to compute the SVD. MATLAB and Octave use the ``'gesvd'`` approach. + Default is ``'gesdd'``. + + Returns + ------- + Z : (N, K) ndarray + Orthonormal basis for the null space of A. + K = dimension of effective null space, as determined by rcond + + See Also + -------- + svd : Singular value decomposition of a matrix + orth : Matrix range + + Examples + -------- + 1-D null space: + + >>> import numpy as np + >>> from scipy.linalg import null_space + >>> A = np.array([[1, 1], [1, 1]]) + >>> ns = null_space(A) + >>> ns * np.copysign(1, ns[0,0]) # Remove the sign ambiguity of the vector + array([[ 0.70710678], + [-0.70710678]]) + + 2-D null space: + + >>> from numpy.random import default_rng + >>> rng = default_rng() + >>> B = rng.random((3, 5)) + >>> Z = null_space(B) + >>> Z.shape + (5, 2) + >>> np.allclose(B.dot(Z), 0) + True + + The basis vectors are orthonormal (up to rounding error): + + >>> Z.T.dot(Z) + array([[ 1.00000000e+00, 6.92087741e-17], + [ 6.92087741e-17, 1.00000000e+00]]) + + """ + u, s, vh = svd(A, full_matrices=True, overwrite_a=overwrite_a, + check_finite=check_finite, lapack_driver=lapack_driver) + M, N = u.shape[0], vh.shape[1] + if rcond is None: + rcond = np.finfo(s.dtype).eps * max(M, N) + tol = np.amax(s, initial=0.) * rcond + num = np.sum(s > tol, dtype=int) + Q = vh[num:,:].T.conj() + return Q + + +def subspace_angles(A, B): + r""" + Compute the subspace angles between two matrices. + + Parameters + ---------- + A : (M, N) array_like + The first input array. + B : (M, K) array_like + The second input array. + + Returns + ------- + angles : ndarray, shape (min(N, K),) + The subspace angles between the column spaces of `A` and `B` in + descending order. + + See Also + -------- + orth + svd + + Notes + ----- + This computes the subspace angles according to the formula + provided in [1]_. For equivalence with MATLAB and Octave behavior, + use ``angles[0]``. + + .. versionadded:: 1.0 + + References + ---------- + .. [1] Knyazev A, Argentati M (2002) Principal Angles between Subspaces + in an A-Based Scalar Product: Algorithms and Perturbation + Estimates. SIAM J. Sci. Comput. 23:2008-2040. + + Examples + -------- + An Hadamard matrix, which has orthogonal columns, so we expect that + the suspace angle to be :math:`\frac{\pi}{2}`: + + >>> import numpy as np + >>> from scipy.linalg import hadamard, subspace_angles + >>> rng = np.random.default_rng() + >>> H = hadamard(4) + >>> print(H) + [[ 1 1 1 1] + [ 1 -1 1 -1] + [ 1 1 -1 -1] + [ 1 -1 -1 1]] + >>> np.rad2deg(subspace_angles(H[:, :2], H[:, 2:])) + array([ 90., 90.]) + + And the subspace angle of a matrix to itself should be zero: + + >>> subspace_angles(H[:, :2], H[:, :2]) <= 2 * np.finfo(float).eps + array([ True, True], dtype=bool) + + The angles between non-orthogonal subspaces are in between these extremes: + + >>> x = rng.standard_normal((4, 3)) + >>> np.rad2deg(subspace_angles(x[:, :2], x[:, [2]])) + array([ 55.832]) # random + """ + # Steps here omit the U and V calculation steps from the paper + + # 1. Compute orthonormal bases of column-spaces + A = _asarray_validated(A, check_finite=True) + if len(A.shape) != 2: + raise ValueError(f'expected 2D array, got shape {A.shape}') + QA = orth(A) + del A + + B = _asarray_validated(B, check_finite=True) + if len(B.shape) != 2: + raise ValueError(f'expected 2D array, got shape {B.shape}') + if len(B) != len(QA): + raise ValueError('A and B must have the same number of rows, got ' + f'{QA.shape[0]} and {B.shape[0]}') + QB = orth(B) + del B + + # 2. Compute SVD for cosine + QA_H_QB = dot(QA.T.conj(), QB) + sigma = svdvals(QA_H_QB) + + # 3. Compute matrix B + if QA.shape[1] >= QB.shape[1]: + B = QB - dot(QA, QA_H_QB) + else: + B = QA - dot(QB, QA_H_QB.T.conj()) + del QA, QB, QA_H_QB + + # 4. Compute SVD for sine + mask = sigma ** 2 >= 0.5 + if mask.any(): + mu_arcsin = arcsin(clip(svdvals(B, overwrite_a=True), -1., 1.)) + else: + mu_arcsin = 0. + + # 5. Compute the principal angles + # with reverse ordering of sigma because smallest sigma belongs to largest + # angle theta + theta = where(mask, mu_arcsin, arccos(clip(sigma[::-1], -1., 1.))) + return theta diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_expm_frechet.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_expm_frechet.py new file mode 100644 index 0000000000000000000000000000000000000000..56ddbc45c3bc47f6beb122e2acadd274ebd9be95 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_expm_frechet.py @@ -0,0 +1,413 @@ +"""Frechet derivative of the matrix exponential.""" +import numpy as np +import scipy.linalg + +__all__ = ['expm_frechet', 'expm_cond'] + + +def expm_frechet(A, E, method=None, compute_expm=True, check_finite=True): + """ + Frechet derivative of the matrix exponential of A in the direction E. + + Parameters + ---------- + A : (N, N) array_like + Matrix of which to take the matrix exponential. + E : (N, N) array_like + Matrix direction in which to take the Frechet derivative. + method : str, optional + Choice of algorithm. Should be one of + + - `SPS` (default) + - `blockEnlarge` + + compute_expm : bool, optional + Whether to compute also `expm_A` in addition to `expm_frechet_AE`. + Default is True. + check_finite : bool, optional + Whether to check that the input matrix contains only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + + Returns + ------- + expm_A : ndarray + Matrix exponential of A. + expm_frechet_AE : ndarray + Frechet derivative of the matrix exponential of A in the direction E. + For ``compute_expm = False``, only `expm_frechet_AE` is returned. + + See Also + -------- + expm : Compute the exponential of a matrix. + + Notes + ----- + This section describes the available implementations that can be selected + by the `method` parameter. The default method is *SPS*. + + Method *blockEnlarge* is a naive algorithm. + + Method *SPS* is Scaling-Pade-Squaring [1]_. + It is a sophisticated implementation which should take + only about 3/8 as much time as the naive implementation. + The asymptotics are the same. + + .. versionadded:: 0.13.0 + + References + ---------- + .. [1] Awad H. Al-Mohy and Nicholas J. Higham (2009) + Computing the Frechet Derivative of the Matrix Exponential, + with an application to Condition Number Estimation. + SIAM Journal On Matrix Analysis and Applications., + 30 (4). pp. 1639-1657. ISSN 1095-7162 + + Examples + -------- + >>> import numpy as np + >>> from scipy import linalg + >>> rng = np.random.default_rng() + + >>> A = rng.standard_normal((3, 3)) + >>> E = rng.standard_normal((3, 3)) + >>> expm_A, expm_frechet_AE = linalg.expm_frechet(A, E) + >>> expm_A.shape, expm_frechet_AE.shape + ((3, 3), (3, 3)) + + Create a 6x6 matrix containing [[A, E], [0, A]]: + + >>> M = np.zeros((6, 6)) + >>> M[:3, :3] = A + >>> M[:3, 3:] = E + >>> M[3:, 3:] = A + + >>> expm_M = linalg.expm(M) + >>> np.allclose(expm_A, expm_M[:3, :3]) + True + >>> np.allclose(expm_frechet_AE, expm_M[:3, 3:]) + True + + """ + if check_finite: + A = np.asarray_chkfinite(A) + E = np.asarray_chkfinite(E) + else: + A = np.asarray(A) + E = np.asarray(E) + if A.ndim != 2 or A.shape[0] != A.shape[1]: + raise ValueError('expected A to be a square matrix') + if E.ndim != 2 or E.shape[0] != E.shape[1]: + raise ValueError('expected E to be a square matrix') + if A.shape != E.shape: + raise ValueError('expected A and E to be the same shape') + if method is None: + method = 'SPS' + if method == 'SPS': + expm_A, expm_frechet_AE = expm_frechet_algo_64(A, E) + elif method == 'blockEnlarge': + expm_A, expm_frechet_AE = expm_frechet_block_enlarge(A, E) + else: + raise ValueError(f'Unknown implementation {method}') + if compute_expm: + return expm_A, expm_frechet_AE + else: + return expm_frechet_AE + + +def expm_frechet_block_enlarge(A, E): + """ + This is a helper function, mostly for testing and profiling. + Return expm(A), frechet(A, E) + """ + n = A.shape[0] + M = np.vstack([ + np.hstack([A, E]), + np.hstack([np.zeros_like(A), A])]) + expm_M = scipy.linalg.expm(M) + return expm_M[:n, :n], expm_M[:n, n:] + + +""" +Maximal values ell_m of ||2**-s A|| such that the backward error bound +does not exceed 2**-53. +""" +ell_table_61 = ( + None, + # 1 + 2.11e-8, + 3.56e-4, + 1.08e-2, + 6.49e-2, + 2.00e-1, + 4.37e-1, + 7.83e-1, + 1.23e0, + 1.78e0, + 2.42e0, + # 11 + 3.13e0, + 3.90e0, + 4.74e0, + 5.63e0, + 6.56e0, + 7.52e0, + 8.53e0, + 9.56e0, + 1.06e1, + 1.17e1, + ) + + +# The b vectors and U and V are copypasted +# from scipy.sparse.linalg.matfuncs.py. +# M, Lu, Lv follow (6.11), (6.12), (6.13), (3.3) + +def _diff_pade3(A, E, ident): + b = (120., 60., 12., 1.) + A2 = A.dot(A) + M2 = np.dot(A, E) + np.dot(E, A) + U = A.dot(b[3]*A2 + b[1]*ident) + V = b[2]*A2 + b[0]*ident + Lu = A.dot(b[3]*M2) + E.dot(b[3]*A2 + b[1]*ident) + Lv = b[2]*M2 + return U, V, Lu, Lv + + +def _diff_pade5(A, E, ident): + b = (30240., 15120., 3360., 420., 30., 1.) + A2 = A.dot(A) + M2 = np.dot(A, E) + np.dot(E, A) + A4 = np.dot(A2, A2) + M4 = np.dot(A2, M2) + np.dot(M2, A2) + U = A.dot(b[5]*A4 + b[3]*A2 + b[1]*ident) + V = b[4]*A4 + b[2]*A2 + b[0]*ident + Lu = (A.dot(b[5]*M4 + b[3]*M2) + + E.dot(b[5]*A4 + b[3]*A2 + b[1]*ident)) + Lv = b[4]*M4 + b[2]*M2 + return U, V, Lu, Lv + + +def _diff_pade7(A, E, ident): + b = (17297280., 8648640., 1995840., 277200., 25200., 1512., 56., 1.) + A2 = A.dot(A) + M2 = np.dot(A, E) + np.dot(E, A) + A4 = np.dot(A2, A2) + M4 = np.dot(A2, M2) + np.dot(M2, A2) + A6 = np.dot(A2, A4) + M6 = np.dot(A4, M2) + np.dot(M4, A2) + U = A.dot(b[7]*A6 + b[5]*A4 + b[3]*A2 + b[1]*ident) + V = b[6]*A6 + b[4]*A4 + b[2]*A2 + b[0]*ident + Lu = (A.dot(b[7]*M6 + b[5]*M4 + b[3]*M2) + + E.dot(b[7]*A6 + b[5]*A4 + b[3]*A2 + b[1]*ident)) + Lv = b[6]*M6 + b[4]*M4 + b[2]*M2 + return U, V, Lu, Lv + + +def _diff_pade9(A, E, ident): + b = (17643225600., 8821612800., 2075673600., 302702400., 30270240., + 2162160., 110880., 3960., 90., 1.) + A2 = A.dot(A) + M2 = np.dot(A, E) + np.dot(E, A) + A4 = np.dot(A2, A2) + M4 = np.dot(A2, M2) + np.dot(M2, A2) + A6 = np.dot(A2, A4) + M6 = np.dot(A4, M2) + np.dot(M4, A2) + A8 = np.dot(A4, A4) + M8 = np.dot(A4, M4) + np.dot(M4, A4) + U = A.dot(b[9]*A8 + b[7]*A6 + b[5]*A4 + b[3]*A2 + b[1]*ident) + V = b[8]*A8 + b[6]*A6 + b[4]*A4 + b[2]*A2 + b[0]*ident + Lu = (A.dot(b[9]*M8 + b[7]*M6 + b[5]*M4 + b[3]*M2) + + E.dot(b[9]*A8 + b[7]*A6 + b[5]*A4 + b[3]*A2 + b[1]*ident)) + Lv = b[8]*M8 + b[6]*M6 + b[4]*M4 + b[2]*M2 + return U, V, Lu, Lv + + +def expm_frechet_algo_64(A, E): + n = A.shape[0] + s = None + ident = np.identity(n) + A_norm_1 = scipy.linalg.norm(A, 1) + m_pade_pairs = ( + (3, _diff_pade3), + (5, _diff_pade5), + (7, _diff_pade7), + (9, _diff_pade9)) + for m, pade in m_pade_pairs: + if A_norm_1 <= ell_table_61[m]: + U, V, Lu, Lv = pade(A, E, ident) + s = 0 + break + if s is None: + # scaling + s = max(0, int(np.ceil(np.log2(A_norm_1 / ell_table_61[13])))) + A = A * 2.0**-s + E = E * 2.0**-s + # pade order 13 + A2 = np.dot(A, A) + M2 = np.dot(A, E) + np.dot(E, A) + A4 = np.dot(A2, A2) + M4 = np.dot(A2, M2) + np.dot(M2, A2) + A6 = np.dot(A2, A4) + M6 = np.dot(A4, M2) + np.dot(M4, A2) + b = (64764752532480000., 32382376266240000., 7771770303897600., + 1187353796428800., 129060195264000., 10559470521600., + 670442572800., 33522128640., 1323241920., 40840800., 960960., + 16380., 182., 1.) + W1 = b[13]*A6 + b[11]*A4 + b[9]*A2 + W2 = b[7]*A6 + b[5]*A4 + b[3]*A2 + b[1]*ident + Z1 = b[12]*A6 + b[10]*A4 + b[8]*A2 + Z2 = b[6]*A6 + b[4]*A4 + b[2]*A2 + b[0]*ident + W = np.dot(A6, W1) + W2 + U = np.dot(A, W) + V = np.dot(A6, Z1) + Z2 + Lw1 = b[13]*M6 + b[11]*M4 + b[9]*M2 + Lw2 = b[7]*M6 + b[5]*M4 + b[3]*M2 + Lz1 = b[12]*M6 + b[10]*M4 + b[8]*M2 + Lz2 = b[6]*M6 + b[4]*M4 + b[2]*M2 + Lw = np.dot(A6, Lw1) + np.dot(M6, W1) + Lw2 + Lu = np.dot(A, Lw) + np.dot(E, W) + Lv = np.dot(A6, Lz1) + np.dot(M6, Z1) + Lz2 + # factor once and solve twice + lu_piv = scipy.linalg.lu_factor(-U + V) + R = scipy.linalg.lu_solve(lu_piv, U + V) + L = scipy.linalg.lu_solve(lu_piv, Lu + Lv + np.dot((Lu - Lv), R)) + # squaring + for k in range(s): + L = np.dot(R, L) + np.dot(L, R) + R = np.dot(R, R) + return R, L + + +def vec(M): + """ + Stack columns of M to construct a single vector. + + This is somewhat standard notation in linear algebra. + + Parameters + ---------- + M : 2-D array_like + Input matrix + + Returns + ------- + v : 1-D ndarray + Output vector + + """ + return M.T.ravel() + + +def expm_frechet_kronform(A, method=None, check_finite=True): + """ + Construct the Kronecker form of the Frechet derivative of expm. + + Parameters + ---------- + A : array_like with shape (N, N) + Matrix to be expm'd. + method : str, optional + Extra keyword to be passed to expm_frechet. + check_finite : bool, optional + Whether to check that the input matrix contains only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + + Returns + ------- + K : 2-D ndarray with shape (N*N, N*N) + Kronecker form of the Frechet derivative of the matrix exponential. + + Notes + ----- + This function is used to help compute the condition number + of the matrix exponential. + + See Also + -------- + expm : Compute a matrix exponential. + expm_frechet : Compute the Frechet derivative of the matrix exponential. + expm_cond : Compute the relative condition number of the matrix exponential + in the Frobenius norm. + + """ + if check_finite: + A = np.asarray_chkfinite(A) + else: + A = np.asarray(A) + if len(A.shape) != 2 or A.shape[0] != A.shape[1]: + raise ValueError('expected a square matrix') + + n = A.shape[0] + ident = np.identity(n) + cols = [] + for i in range(n): + for j in range(n): + E = np.outer(ident[i], ident[j]) + F = expm_frechet(A, E, + method=method, compute_expm=False, check_finite=False) + cols.append(vec(F)) + return np.vstack(cols).T + + +def expm_cond(A, check_finite=True): + """ + Relative condition number of the matrix exponential in the Frobenius norm. + + Parameters + ---------- + A : 2-D array_like + Square input matrix with shape (N, N). + check_finite : bool, optional + Whether to check that the input matrix contains only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + + Returns + ------- + kappa : float + The relative condition number of the matrix exponential + in the Frobenius norm + + See Also + -------- + expm : Compute the exponential of a matrix. + expm_frechet : Compute the Frechet derivative of the matrix exponential. + + Notes + ----- + A faster estimate for the condition number in the 1-norm + has been published but is not yet implemented in SciPy. + + .. versionadded:: 0.14.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import expm_cond + >>> A = np.array([[-0.3, 0.2, 0.6], [0.6, 0.3, -0.1], [-0.7, 1.2, 0.9]]) + >>> k = expm_cond(A) + >>> k + 1.7787805864469866 + + """ + if check_finite: + A = np.asarray_chkfinite(A) + else: + A = np.asarray(A) + if len(A.shape) != 2 or A.shape[0] != A.shape[1]: + raise ValueError('expected a square matrix') + + X = scipy.linalg.expm(A) + K = expm_frechet_kronform(A, check_finite=False) + + # The following norm choices are deliberate. + # The norms of A and X are Frobenius norms, + # and the norm of K is the induced 2-norm. + A_norm = scipy.linalg.norm(A, 'fro') + X_norm = scipy.linalg.norm(X, 'fro') + K_norm = scipy.linalg.norm(K, 2) + + kappa = (K_norm * A_norm) / X_norm + return kappa diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_lapack_subroutines.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_lapack_subroutines.h new file mode 100644 index 0000000000000000000000000000000000000000..676658205e41bcde69e3899e8e065c90738af246 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_lapack_subroutines.h @@ -0,0 +1,1521 @@ +/* +This file was generated by _generate_pyx.py. +Do not edit this file directly. +*/ + +#include "npy_cblas.h" +#include "fortran_defs.h" + +typedef int (*_cselect1)(npy_complex64*); +typedef int (*_cselect2)(npy_complex64*, npy_complex64*); +typedef int (*_dselect2)(double*, double*); +typedef int (*_dselect3)(double*, double*, double*); +typedef int (*_sselect2)(float*, float*); +typedef int (*_sselect3)(float*, float*, float*); +typedef int (*_zselect1)(npy_complex128*); +typedef int (*_zselect2)(npy_complex128*, npy_complex128*); + +#ifdef __cplusplus +extern "C" { +#endif + +void BLAS_FUNC(cbbcsd)(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, float *theta, float *phi, npy_complex64 *u1, int *ldu1, npy_complex64 *u2, int *ldu2, npy_complex64 *v1t, int *ldv1t, npy_complex64 *v2t, int *ldv2t, float *b11d, float *b11e, float *b12d, float *b12e, float *b21d, float *b21e, float *b22d, float *b22e, float *rwork, int *lrwork, int *info); +void BLAS_FUNC(cbdsqr)(char *uplo, int *n, int *ncvt, int *nru, int *ncc, float *d, float *e, npy_complex64 *vt, int *ldvt, npy_complex64 *u, int *ldu, npy_complex64 *c, int *ldc, float *rwork, int *info); +void BLAS_FUNC(cgbbrd)(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, npy_complex64 *ab, int *ldab, float *d, float *e, npy_complex64 *q, int *ldq, npy_complex64 *pt, int *ldpt, npy_complex64 *c, int *ldc, npy_complex64 *work, float *rwork, int *info); +void BLAS_FUNC(cgbcon)(char *norm, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, int *ipiv, float *anorm, float *rcond, npy_complex64 *work, float *rwork, int *info); +void BLAS_FUNC(cgbequ)(int *m, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, float *r, float *c, float *rowcnd, float *colcnd, float *amax, int *info); +void BLAS_FUNC(cgbequb)(int *m, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, float *r, float *c, float *rowcnd, float *colcnd, float *amax, int *info); +void BLAS_FUNC(cgbrfs)(char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *afb, int *ldafb, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info); +void BLAS_FUNC(cgbsv)(int *n, int *kl, int *ku, int *nrhs, npy_complex64 *ab, int *ldab, int *ipiv, npy_complex64 *b, int *ldb, int *info); +void BLAS_FUNC(cgbsvx)(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *afb, int *ldafb, int *ipiv, char *equed, float *r, float *c, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info); +void BLAS_FUNC(cgbtf2)(int *m, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, int *ipiv, int *info); +void BLAS_FUNC(cgbtrf)(int *m, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, int *ipiv, int *info); +void BLAS_FUNC(cgbtrs)(char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex64 *ab, int *ldab, int *ipiv, npy_complex64 *b, int *ldb, int *info); +void BLAS_FUNC(cgebak)(char *job, char *side, int *n, int *ilo, int *ihi, float *scale, int *m, npy_complex64 *v, int *ldv, int *info); +void BLAS_FUNC(cgebal)(char *job, int *n, npy_complex64 *a, int *lda, int *ilo, int *ihi, float *scale, int *info); +void BLAS_FUNC(cgebd2)(int *m, int *n, npy_complex64 *a, int *lda, float *d, float *e, npy_complex64 *tauq, npy_complex64 *taup, npy_complex64 *work, int *info); +void BLAS_FUNC(cgebrd)(int *m, int *n, npy_complex64 *a, int *lda, float *d, float *e, npy_complex64 *tauq, npy_complex64 *taup, npy_complex64 *work, int *lwork, int *info); +void BLAS_FUNC(cgecon)(char *norm, int *n, npy_complex64 *a, int *lda, float *anorm, float *rcond, npy_complex64 *work, float *rwork, int *info); +void BLAS_FUNC(cgeequ)(int *m, int *n, npy_complex64 *a, int *lda, float *r, float *c, float *rowcnd, float *colcnd, float *amax, int *info); +void BLAS_FUNC(cgeequb)(int *m, int *n, npy_complex64 *a, int *lda, float *r, float *c, float *rowcnd, float *colcnd, float *amax, int *info); +void BLAS_FUNC(cgees)(char *jobvs, char *sort, _cselect1 *select, int *n, npy_complex64 *a, int *lda, int *sdim, npy_complex64 *w, npy_complex64 *vs, int *ldvs, npy_complex64 *work, int *lwork, float *rwork, int *bwork, int *info); +void BLAS_FUNC(cgeesx)(char *jobvs, char *sort, _cselect1 *select, char *sense, int *n, npy_complex64 *a, int *lda, int *sdim, npy_complex64 *w, npy_complex64 *vs, int *ldvs, float *rconde, float *rcondv, npy_complex64 *work, int *lwork, float *rwork, int *bwork, int *info); +void BLAS_FUNC(cgeev)(char *jobvl, char *jobvr, int *n, npy_complex64 *a, int *lda, npy_complex64 *w, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, npy_complex64 *work, int *lwork, float *rwork, int *info); +void BLAS_FUNC(cgeevx)(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, npy_complex64 *a, int *lda, npy_complex64 *w, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, int *ilo, int *ihi, float *scale, float *abnrm, float *rconde, float *rcondv, npy_complex64 *work, int *lwork, float *rwork, int *info); +void BLAS_FUNC(cgehd2)(int *n, int *ilo, int *ihi, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info); +void BLAS_FUNC(cgehrd)(int *n, int *ilo, int *ihi, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info); +void BLAS_FUNC(cgelq2)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info); +void BLAS_FUNC(cgelqf)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info); +void BLAS_FUNC(cgels)(char *trans, int *m, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *work, int *lwork, int *info); +void BLAS_FUNC(cgelsd)(int *m, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, float *s, float *rcond, int *rank, npy_complex64 *work, int *lwork, float *rwork, int *iwork, int *info); +void BLAS_FUNC(cgelss)(int *m, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, float *s, float *rcond, int *rank, npy_complex64 *work, int *lwork, float *rwork, int *info); +void BLAS_FUNC(cgelsy)(int *m, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *jpvt, float *rcond, int *rank, npy_complex64 *work, int *lwork, float *rwork, int *info); +void BLAS_FUNC(cgemqrt)(char *side, char *trans, int *m, int *n, int *k, int *nb, npy_complex64 *v, int *ldv, npy_complex64 *t, int *ldt, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info); +void BLAS_FUNC(cgeql2)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info); +void BLAS_FUNC(cgeqlf)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info); +void BLAS_FUNC(cgeqp3)(int *m, int *n, npy_complex64 *a, int *lda, int *jpvt, npy_complex64 *tau, npy_complex64 *work, int *lwork, float *rwork, int *info); +void BLAS_FUNC(cgeqr2)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info); +void BLAS_FUNC(cgeqr2p)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info); +void BLAS_FUNC(cgeqrf)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info); +void BLAS_FUNC(cgeqrfp)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info); +void BLAS_FUNC(cgeqrt)(int *m, int *n, int *nb, npy_complex64 *a, int *lda, npy_complex64 *t, int *ldt, npy_complex64 *work, int *info); +void BLAS_FUNC(cgeqrt2)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *t, int *ldt, int *info); +void BLAS_FUNC(cgeqrt3)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *t, int *ldt, int *info); +void BLAS_FUNC(cgerfs)(char *trans, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info); +void BLAS_FUNC(cgerq2)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info); +void BLAS_FUNC(cgerqf)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info); +void BLAS_FUNC(cgesc2)(int *n, npy_complex64 *a, int *lda, npy_complex64 *rhs, int *ipiv, int *jpiv, float *scale); +void BLAS_FUNC(cgesdd)(char *jobz, int *m, int *n, npy_complex64 *a, int *lda, float *s, npy_complex64 *u, int *ldu, npy_complex64 *vt, int *ldvt, npy_complex64 *work, int *lwork, float *rwork, int *iwork, int *info); +void BLAS_FUNC(cgesv)(int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, int *info); +void BLAS_FUNC(cgesvd)(char *jobu, char *jobvt, int *m, int *n, npy_complex64 *a, int *lda, float *s, npy_complex64 *u, int *ldu, npy_complex64 *vt, int *ldvt, npy_complex64 *work, int *lwork, float *rwork, int *info); +void BLAS_FUNC(cgesvx)(char *fact, char *trans, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, char *equed, float *r, float *c, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info); +void BLAS_FUNC(cgetc2)(int *n, npy_complex64 *a, int *lda, int *ipiv, int *jpiv, int *info); +void BLAS_FUNC(cgetf2)(int *m, int *n, npy_complex64 *a, int *lda, int *ipiv, int *info); +void BLAS_FUNC(cgetrf)(int *m, int *n, npy_complex64 *a, int *lda, int *ipiv, int *info); +void BLAS_FUNC(cgetri)(int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *lwork, int *info); +void BLAS_FUNC(cgetrs)(char *trans, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, int *info); +void BLAS_FUNC(cggbak)(char *job, char *side, int *n, int *ilo, int *ihi, float *lscale, float *rscale, int *m, npy_complex64 *v, int *ldv, int *info); +void BLAS_FUNC(cggbal)(char *job, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *ilo, int *ihi, float *lscale, float *rscale, float *work, int *info); +void BLAS_FUNC(cgges)(char *jobvsl, char *jobvsr, char *sort, _cselect2 *selctg, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *sdim, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *vsl, int *ldvsl, npy_complex64 *vsr, int *ldvsr, npy_complex64 *work, int *lwork, float *rwork, int *bwork, int *info); +void BLAS_FUNC(cggesx)(char *jobvsl, char *jobvsr, char *sort, _cselect2 *selctg, char *sense, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *sdim, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *vsl, int *ldvsl, npy_complex64 *vsr, int *ldvsr, float *rconde, float *rcondv, npy_complex64 *work, int *lwork, float *rwork, int *iwork, int *liwork, int *bwork, int *info); +void BLAS_FUNC(cggev)(char *jobvl, char *jobvr, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, npy_complex64 *work, int *lwork, float *rwork, int *info); +void BLAS_FUNC(cggevx)(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, int *ilo, int *ihi, float *lscale, float *rscale, float *abnrm, float *bbnrm, float *rconde, float *rcondv, npy_complex64 *work, int *lwork, float *rwork, int *iwork, int *bwork, int *info); +void BLAS_FUNC(cggglm)(int *n, int *m, int *p, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *d, npy_complex64 *x, npy_complex64 *y, npy_complex64 *work, int *lwork, int *info); +void BLAS_FUNC(cgghrd)(char *compq, char *compz, int *n, int *ilo, int *ihi, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *q, int *ldq, npy_complex64 *z, int *ldz, int *info); +void BLAS_FUNC(cgglse)(int *m, int *n, int *p, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *c, npy_complex64 *d, npy_complex64 *x, npy_complex64 *work, int *lwork, int *info); +void BLAS_FUNC(cggqrf)(int *n, int *m, int *p, npy_complex64 *a, int *lda, npy_complex64 *taua, npy_complex64 *b, int *ldb, npy_complex64 *taub, npy_complex64 *work, int *lwork, int *info); +void BLAS_FUNC(cggrqf)(int *m, int *p, int *n, npy_complex64 *a, int *lda, npy_complex64 *taua, npy_complex64 *b, int *ldb, npy_complex64 *taub, npy_complex64 *work, int *lwork, int *info); +void BLAS_FUNC(cgtcon)(char *norm, int *n, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *du2, int *ipiv, float *anorm, float *rcond, npy_complex64 *work, int *info); +void BLAS_FUNC(cgtrfs)(char *trans, int *n, int *nrhs, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *dlf, npy_complex64 *df, npy_complex64 *duf, npy_complex64 *du2, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info); +void BLAS_FUNC(cgtsv)(int *n, int *nrhs, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *b, int *ldb, int *info); +void BLAS_FUNC(cgtsvx)(char *fact, char *trans, int *n, int *nrhs, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *dlf, npy_complex64 *df, npy_complex64 *duf, npy_complex64 *du2, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info); +void BLAS_FUNC(cgttrf)(int *n, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *du2, int *ipiv, int *info); +void BLAS_FUNC(cgttrs)(char *trans, int *n, int *nrhs, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *du2, int *ipiv, npy_complex64 *b, int *ldb, int *info); +void BLAS_FUNC(cgtts2)(int *itrans, int *n, int *nrhs, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *du2, int *ipiv, npy_complex64 *b, int *ldb); +void BLAS_FUNC(chbev)(char *jobz, char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, float *rwork, int *info); +void BLAS_FUNC(chbevd)(char *jobz, char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, float *rwork, int *lrwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(chbevx)(char *jobz, char *range, char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, npy_complex64 *q, int *ldq, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, float *rwork, int *iwork, int *ifail, int *info); +void BLAS_FUNC(chbgst)(char *vect, char *uplo, int *n, int *ka, int *kb, npy_complex64 *ab, int *ldab, npy_complex64 *bb, int *ldbb, npy_complex64 *x, int *ldx, npy_complex64 *work, float *rwork, int *info); +void BLAS_FUNC(chbgv)(char *jobz, char *uplo, int *n, int *ka, int *kb, npy_complex64 *ab, int *ldab, npy_complex64 *bb, int *ldbb, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, float *rwork, int *info); +void BLAS_FUNC(chbgvd)(char *jobz, char *uplo, int *n, int *ka, int *kb, npy_complex64 *ab, int *ldab, npy_complex64 *bb, int *ldbb, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, float *rwork, int *lrwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(chbgvx)(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, npy_complex64 *ab, int *ldab, npy_complex64 *bb, int *ldbb, npy_complex64 *q, int *ldq, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, float *rwork, int *iwork, int *ifail, int *info); +void BLAS_FUNC(chbtrd)(char *vect, char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, float *d, float *e, npy_complex64 *q, int *ldq, npy_complex64 *work, int *info); +void BLAS_FUNC(checon)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, float *anorm, float *rcond, npy_complex64 *work, int *info); +void BLAS_FUNC(cheequb)(char *uplo, int *n, npy_complex64 *a, int *lda, float *s, float *scond, float *amax, npy_complex64 *work, int *info); +void BLAS_FUNC(cheev)(char *jobz, char *uplo, int *n, npy_complex64 *a, int *lda, float *w, npy_complex64 *work, int *lwork, float *rwork, int *info); +void BLAS_FUNC(cheevd)(char *jobz, char *uplo, int *n, npy_complex64 *a, int *lda, float *w, npy_complex64 *work, int *lwork, float *rwork, int *lrwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(cheevr)(char *jobz, char *range, char *uplo, int *n, npy_complex64 *a, int *lda, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, npy_complex64 *z, int *ldz, int *isuppz, npy_complex64 *work, int *lwork, float *rwork, int *lrwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(cheevx)(char *jobz, char *range, char *uplo, int *n, npy_complex64 *a, int *lda, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, float *rwork, int *iwork, int *ifail, int *info); +void BLAS_FUNC(chegs2)(int *itype, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *info); +void BLAS_FUNC(chegst)(int *itype, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *info); +void BLAS_FUNC(chegv)(int *itype, char *jobz, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, float *w, npy_complex64 *work, int *lwork, float *rwork, int *info); +void BLAS_FUNC(chegvd)(int *itype, char *jobz, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, float *w, npy_complex64 *work, int *lwork, float *rwork, int *lrwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(chegvx)(int *itype, char *jobz, char *range, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, float *rwork, int *iwork, int *ifail, int *info); +void BLAS_FUNC(cherfs)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info); +void BLAS_FUNC(chesv)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *work, int *lwork, int *info); +void BLAS_FUNC(chesvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, int *lwork, float *rwork, int *info); +void BLAS_FUNC(cheswapr)(char *uplo, int *n, npy_complex64 *a, int *lda, int *i1, int *i2); +void BLAS_FUNC(chetd2)(char *uplo, int *n, npy_complex64 *a, int *lda, float *d, float *e, npy_complex64 *tau, int *info); +void BLAS_FUNC(chetf2)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, int *info); +void BLAS_FUNC(chetrd)(char *uplo, int *n, npy_complex64 *a, int *lda, float *d, float *e, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info); +void BLAS_FUNC(chetrf)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *lwork, int *info); +void BLAS_FUNC(chetri)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *info); +void BLAS_FUNC(chetri2)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *lwork, int *info); +void BLAS_FUNC(chetri2x)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *nb, int *info); +void BLAS_FUNC(chetrs)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, int *info); +void BLAS_FUNC(chetrs2)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *work, int *info); +void BLAS_FUNC(chfrk)(char *transr, char *uplo, char *trans, int *n, int *k, float *alpha, npy_complex64 *a, int *lda, float *beta, npy_complex64 *c); +void BLAS_FUNC(chgeqz)(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, npy_complex64 *h, int *ldh, npy_complex64 *t, int *ldt, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *q, int *ldq, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, float *rwork, int *info); +char BLAS_FUNC(chla_transtype)(int *trans); +void BLAS_FUNC(chpcon)(char *uplo, int *n, npy_complex64 *ap, int *ipiv, float *anorm, float *rcond, npy_complex64 *work, int *info); +void BLAS_FUNC(chpev)(char *jobz, char *uplo, int *n, npy_complex64 *ap, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, float *rwork, int *info); +void BLAS_FUNC(chpevd)(char *jobz, char *uplo, int *n, npy_complex64 *ap, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, float *rwork, int *lrwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(chpevx)(char *jobz, char *range, char *uplo, int *n, npy_complex64 *ap, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, float *rwork, int *iwork, int *ifail, int *info); +void BLAS_FUNC(chpgst)(int *itype, char *uplo, int *n, npy_complex64 *ap, npy_complex64 *bp, int *info); +void BLAS_FUNC(chpgv)(int *itype, char *jobz, char *uplo, int *n, npy_complex64 *ap, npy_complex64 *bp, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, float *rwork, int *info); +void BLAS_FUNC(chpgvd)(int *itype, char *jobz, char *uplo, int *n, npy_complex64 *ap, npy_complex64 *bp, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, float *rwork, int *lrwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(chpgvx)(int *itype, char *jobz, char *range, char *uplo, int *n, npy_complex64 *ap, npy_complex64 *bp, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, float *rwork, int *iwork, int *ifail, int *info); +void BLAS_FUNC(chprfs)(char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info); +void BLAS_FUNC(chpsv)(char *uplo, int *n, int *nrhs, npy_complex64 *ap, int *ipiv, npy_complex64 *b, int *ldb, int *info); +void BLAS_FUNC(chpsvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info); +void BLAS_FUNC(chptrd)(char *uplo, int *n, npy_complex64 *ap, float *d, float *e, npy_complex64 *tau, int *info); +void BLAS_FUNC(chptrf)(char *uplo, int *n, npy_complex64 *ap, int *ipiv, int *info); +void BLAS_FUNC(chptri)(char *uplo, int *n, npy_complex64 *ap, int *ipiv, npy_complex64 *work, int *info); +void BLAS_FUNC(chptrs)(char *uplo, int *n, int *nrhs, npy_complex64 *ap, int *ipiv, npy_complex64 *b, int *ldb, int *info); +void BLAS_FUNC(chsein)(char *side, char *eigsrc, char *initv, int *select, int *n, npy_complex64 *h, int *ldh, npy_complex64 *w, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, int *mm, int *m, npy_complex64 *work, float *rwork, int *ifaill, int *ifailr, int *info); +void BLAS_FUNC(chseqr)(char *job, char *compz, int *n, int *ilo, int *ihi, npy_complex64 *h, int *ldh, npy_complex64 *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, int *info); +void BLAS_FUNC(clabrd)(int *m, int *n, int *nb, npy_complex64 *a, int *lda, float *d, float *e, npy_complex64 *tauq, npy_complex64 *taup, npy_complex64 *x, int *ldx, npy_complex64 *y, int *ldy); +void BLAS_FUNC(clacgv)(int *n, npy_complex64 *x, int *incx); +void BLAS_FUNC(clacn2)(int *n, npy_complex64 *v, npy_complex64 *x, float *est, int *kase, int *isave); +void BLAS_FUNC(clacon)(int *n, npy_complex64 *v, npy_complex64 *x, float *est, int *kase); +void BLAS_FUNC(clacp2)(char *uplo, int *m, int *n, float *a, int *lda, npy_complex64 *b, int *ldb); +void BLAS_FUNC(clacpy)(char *uplo, int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb); +void BLAS_FUNC(clacrm)(int *m, int *n, npy_complex64 *a, int *lda, float *b, int *ldb, npy_complex64 *c, int *ldc, float *rwork); +void BLAS_FUNC(clacrt)(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy, npy_complex64 *c, npy_complex64 *s); +void F_FUNC(cladivwrp,CLADIVWRP)(npy_complex64 *out, npy_complex64 *x, npy_complex64 *y); +void BLAS_FUNC(claed0)(int *qsiz, int *n, float *d, float *e, npy_complex64 *q, int *ldq, npy_complex64 *qstore, int *ldqs, float *rwork, int *iwork, int *info); +void BLAS_FUNC(claed7)(int *n, int *cutpnt, int *qsiz, int *tlvls, int *curlvl, int *curpbm, float *d, npy_complex64 *q, int *ldq, float *rho, int *indxq, float *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, float *givnum, npy_complex64 *work, float *rwork, int *iwork, int *info); +void BLAS_FUNC(claed8)(int *k, int *n, int *qsiz, npy_complex64 *q, int *ldq, float *d, float *rho, int *cutpnt, float *z, float *dlamda, npy_complex64 *q2, int *ldq2, float *w, int *indxp, int *indx, int *indxq, int *perm, int *givptr, int *givcol, float *givnum, int *info); +void BLAS_FUNC(claein)(int *rightv, int *noinit, int *n, npy_complex64 *h, int *ldh, npy_complex64 *w, npy_complex64 *v, npy_complex64 *b, int *ldb, float *rwork, float *eps3, float *smlnum, int *info); +void BLAS_FUNC(claesy)(npy_complex64 *a, npy_complex64 *b, npy_complex64 *c, npy_complex64 *rt1, npy_complex64 *rt2, npy_complex64 *evscal, npy_complex64 *cs1, npy_complex64 *sn1); +void BLAS_FUNC(claev2)(npy_complex64 *a, npy_complex64 *b, npy_complex64 *c, float *rt1, float *rt2, float *cs1, npy_complex64 *sn1); +void BLAS_FUNC(clag2z)(int *m, int *n, npy_complex64 *sa, int *ldsa, npy_complex128 *a, int *lda, int *info); +void BLAS_FUNC(clags2)(int *upper, float *a1, npy_complex64 *a2, float *a3, float *b1, npy_complex64 *b2, float *b3, float *csu, npy_complex64 *snu, float *csv, npy_complex64 *snv, float *csq, npy_complex64 *snq); +void BLAS_FUNC(clagtm)(char *trans, int *n, int *nrhs, float *alpha, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *x, int *ldx, float *beta, npy_complex64 *b, int *ldb); +void BLAS_FUNC(clahef)(char *uplo, int *n, int *nb, int *kb, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *w, int *ldw, int *info); +void BLAS_FUNC(clahqr)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, npy_complex64 *h, int *ldh, npy_complex64 *w, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, int *info); +void BLAS_FUNC(clahr2)(int *n, int *k, int *nb, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *t, int *ldt, npy_complex64 *y, int *ldy); +void BLAS_FUNC(claic1)(int *job, int *j, npy_complex64 *x, float *sest, npy_complex64 *w, npy_complex64 *gamma, float *sestpr, npy_complex64 *s, npy_complex64 *c); +void BLAS_FUNC(clals0)(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, npy_complex64 *b, int *ldb, npy_complex64 *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, float *givnum, int *ldgnum, float *poles, float *difl, float *difr, float *z, int *k, float *c, float *s, float *rwork, int *info); +void BLAS_FUNC(clalsa)(int *icompq, int *smlsiz, int *n, int *nrhs, npy_complex64 *b, int *ldb, npy_complex64 *bx, int *ldbx, float *u, int *ldu, float *vt, int *k, float *difl, float *difr, float *z, float *poles, int *givptr, int *givcol, int *ldgcol, int *perm, float *givnum, float *c, float *s, float *rwork, int *iwork, int *info); +void BLAS_FUNC(clalsd)(char *uplo, int *smlsiz, int *n, int *nrhs, float *d, float *e, npy_complex64 *b, int *ldb, float *rcond, int *rank, npy_complex64 *work, float *rwork, int *iwork, int *info); +float BLAS_FUNC(clangb)(char *norm, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, float *work); +float BLAS_FUNC(clange)(char *norm, int *m, int *n, npy_complex64 *a, int *lda, float *work); +float BLAS_FUNC(clangt)(char *norm, int *n, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du); +float BLAS_FUNC(clanhb)(char *norm, char *uplo, int *n, int *k, npy_complex64 *ab, int *ldab, float *work); +float BLAS_FUNC(clanhe)(char *norm, char *uplo, int *n, npy_complex64 *a, int *lda, float *work); +float BLAS_FUNC(clanhf)(char *norm, char *transr, char *uplo, int *n, npy_complex64 *a, float *work); +float BLAS_FUNC(clanhp)(char *norm, char *uplo, int *n, npy_complex64 *ap, float *work); +float BLAS_FUNC(clanhs)(char *norm, int *n, npy_complex64 *a, int *lda, float *work); +float BLAS_FUNC(clanht)(char *norm, int *n, float *d, npy_complex64 *e); +float BLAS_FUNC(clansb)(char *norm, char *uplo, int *n, int *k, npy_complex64 *ab, int *ldab, float *work); +float BLAS_FUNC(clansp)(char *norm, char *uplo, int *n, npy_complex64 *ap, float *work); +float BLAS_FUNC(clansy)(char *norm, char *uplo, int *n, npy_complex64 *a, int *lda, float *work); +float BLAS_FUNC(clantb)(char *norm, char *uplo, char *diag, int *n, int *k, npy_complex64 *ab, int *ldab, float *work); +float BLAS_FUNC(clantp)(char *norm, char *uplo, char *diag, int *n, npy_complex64 *ap, float *work); +float BLAS_FUNC(clantr)(char *norm, char *uplo, char *diag, int *m, int *n, npy_complex64 *a, int *lda, float *work); +void BLAS_FUNC(clapll)(int *n, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, float *ssmin); +void BLAS_FUNC(clapmr)(int *forwrd, int *m, int *n, npy_complex64 *x, int *ldx, int *k); +void BLAS_FUNC(clapmt)(int *forwrd, int *m, int *n, npy_complex64 *x, int *ldx, int *k); +void BLAS_FUNC(claqgb)(int *m, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, float *r, float *c, float *rowcnd, float *colcnd, float *amax, char *equed); +void BLAS_FUNC(claqge)(int *m, int *n, npy_complex64 *a, int *lda, float *r, float *c, float *rowcnd, float *colcnd, float *amax, char *equed); +void BLAS_FUNC(claqhb)(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, float *s, float *scond, float *amax, char *equed); +void BLAS_FUNC(claqhe)(char *uplo, int *n, npy_complex64 *a, int *lda, float *s, float *scond, float *amax, char *equed); +void BLAS_FUNC(claqhp)(char *uplo, int *n, npy_complex64 *ap, float *s, float *scond, float *amax, char *equed); +void BLAS_FUNC(claqp2)(int *m, int *n, int *offset, npy_complex64 *a, int *lda, int *jpvt, npy_complex64 *tau, float *vn1, float *vn2, npy_complex64 *work); +void BLAS_FUNC(claqps)(int *m, int *n, int *offset, int *nb, int *kb, npy_complex64 *a, int *lda, int *jpvt, npy_complex64 *tau, float *vn1, float *vn2, npy_complex64 *auxv, npy_complex64 *f, int *ldf); +void BLAS_FUNC(claqr0)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, npy_complex64 *h, int *ldh, npy_complex64 *w, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, int *info); +void BLAS_FUNC(claqr1)(int *n, npy_complex64 *h, int *ldh, npy_complex64 *s1, npy_complex64 *s2, npy_complex64 *v); +void BLAS_FUNC(claqr2)(int *wantt, int *wantz, int *n, int *ktop, int *kbot, int *nw, npy_complex64 *h, int *ldh, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, int *ns, int *nd, npy_complex64 *sh, npy_complex64 *v, int *ldv, int *nh, npy_complex64 *t, int *ldt, int *nv, npy_complex64 *wv, int *ldwv, npy_complex64 *work, int *lwork); +void BLAS_FUNC(claqr3)(int *wantt, int *wantz, int *n, int *ktop, int *kbot, int *nw, npy_complex64 *h, int *ldh, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, int *ns, int *nd, npy_complex64 *sh, npy_complex64 *v, int *ldv, int *nh, npy_complex64 *t, int *ldt, int *nv, npy_complex64 *wv, int *ldwv, npy_complex64 *work, int *lwork); +void BLAS_FUNC(claqr4)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, npy_complex64 *h, int *ldh, npy_complex64 *w, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, int *info); +void BLAS_FUNC(claqr5)(int *wantt, int *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, npy_complex64 *s, npy_complex64 *h, int *ldh, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, npy_complex64 *v, int *ldv, npy_complex64 *u, int *ldu, int *nv, npy_complex64 *wv, int *ldwv, int *nh, npy_complex64 *wh, int *ldwh); +void BLAS_FUNC(claqsb)(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, float *s, float *scond, float *amax, char *equed); +void BLAS_FUNC(claqsp)(char *uplo, int *n, npy_complex64 *ap, float *s, float *scond, float *amax, char *equed); +void BLAS_FUNC(claqsy)(char *uplo, int *n, npy_complex64 *a, int *lda, float *s, float *scond, float *amax, char *equed); +void BLAS_FUNC(clar1v)(int *n, int *b1, int *bn, float *lambda_, float *d, float *l, float *ld, float *lld, float *pivmin, float *gaptol, npy_complex64 *z, int *wantnc, int *negcnt, float *ztz, float *mingma, int *r, int *isuppz, float *nrminv, float *resid, float *rqcorr, float *work); +void BLAS_FUNC(clar2v)(int *n, npy_complex64 *x, npy_complex64 *y, npy_complex64 *z, int *incx, float *c, npy_complex64 *s, int *incc); +void BLAS_FUNC(clarcm)(int *m, int *n, float *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *c, int *ldc, float *rwork); +void BLAS_FUNC(clarf)(char *side, int *m, int *n, npy_complex64 *v, int *incv, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work); +void BLAS_FUNC(clarfb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, npy_complex64 *v, int *ldv, npy_complex64 *t, int *ldt, npy_complex64 *c, int *ldc, npy_complex64 *work, int *ldwork); +void BLAS_FUNC(clarfg)(int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *tau); +void BLAS_FUNC(clarfgp)(int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *tau); +void BLAS_FUNC(clarft)(char *direct, char *storev, int *n, int *k, npy_complex64 *v, int *ldv, npy_complex64 *tau, npy_complex64 *t, int *ldt); +void BLAS_FUNC(clarfx)(char *side, int *m, int *n, npy_complex64 *v, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work); +void BLAS_FUNC(clargv)(int *n, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, float *c, int *incc); +void BLAS_FUNC(clarnv)(int *idist, int *iseed, int *n, npy_complex64 *x); +void BLAS_FUNC(clarrv)(int *n, float *vl, float *vu, float *d, float *l, float *pivmin, int *isplit, int *m, int *dol, int *dou, float *minrgp, float *rtol1, float *rtol2, float *w, float *werr, float *wgap, int *iblock, int *indexw, float *gers, npy_complex64 *z, int *ldz, int *isuppz, float *work, int *iwork, int *info); +void BLAS_FUNC(clartg)(npy_complex64 *f, npy_complex64 *g, float *cs, npy_complex64 *sn, npy_complex64 *r); +void BLAS_FUNC(clartv)(int *n, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, float *c, npy_complex64 *s, int *incc); +void BLAS_FUNC(clarz)(char *side, int *m, int *n, int *l, npy_complex64 *v, int *incv, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work); +void BLAS_FUNC(clarzb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, npy_complex64 *v, int *ldv, npy_complex64 *t, int *ldt, npy_complex64 *c, int *ldc, npy_complex64 *work, int *ldwork); +void BLAS_FUNC(clarzt)(char *direct, char *storev, int *n, int *k, npy_complex64 *v, int *ldv, npy_complex64 *tau, npy_complex64 *t, int *ldt); +void BLAS_FUNC(clascl)(char *type_bn, int *kl, int *ku, float *cfrom, float *cto, int *m, int *n, npy_complex64 *a, int *lda, int *info); +void BLAS_FUNC(claset)(char *uplo, int *m, int *n, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *a, int *lda); +void BLAS_FUNC(clasr)(char *side, char *pivot, char *direct, int *m, int *n, float *c, float *s, npy_complex64 *a, int *lda); +void BLAS_FUNC(classq)(int *n, npy_complex64 *x, int *incx, float *scale, float *sumsq); +void BLAS_FUNC(claswp)(int *n, npy_complex64 *a, int *lda, int *k1, int *k2, int *ipiv, int *incx); +void BLAS_FUNC(clasyf)(char *uplo, int *n, int *nb, int *kb, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *w, int *ldw, int *info); +void BLAS_FUNC(clatbs)(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, npy_complex64 *ab, int *ldab, npy_complex64 *x, float *scale, float *cnorm, int *info); +void BLAS_FUNC(clatdf)(int *ijob, int *n, npy_complex64 *z, int *ldz, npy_complex64 *rhs, float *rdsum, float *rdscal, int *ipiv, int *jpiv); +void BLAS_FUNC(clatps)(char *uplo, char *trans, char *diag, char *normin, int *n, npy_complex64 *ap, npy_complex64 *x, float *scale, float *cnorm, int *info); +void BLAS_FUNC(clatrd)(char *uplo, int *n, int *nb, npy_complex64 *a, int *lda, float *e, npy_complex64 *tau, npy_complex64 *w, int *ldw); +void BLAS_FUNC(clatrs)(char *uplo, char *trans, char *diag, char *normin, int *n, npy_complex64 *a, int *lda, npy_complex64 *x, float *scale, float *cnorm, int *info); +void BLAS_FUNC(clatrz)(int *m, int *n, int *l, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work); +void BLAS_FUNC(clauu2)(char *uplo, int *n, npy_complex64 *a, int *lda, int *info); +void BLAS_FUNC(clauum)(char *uplo, int *n, npy_complex64 *a, int *lda, int *info); +void BLAS_FUNC(cpbcon)(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, float *anorm, float *rcond, npy_complex64 *work, float *rwork, int *info); +void BLAS_FUNC(cpbequ)(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, float *s, float *scond, float *amax, int *info); +void BLAS_FUNC(cpbrfs)(char *uplo, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *afb, int *ldafb, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info); +void BLAS_FUNC(cpbstf)(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, int *info); +void BLAS_FUNC(cpbsv)(char *uplo, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *b, int *ldb, int *info); +void BLAS_FUNC(cpbsvx)(char *fact, char *uplo, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *afb, int *ldafb, char *equed, float *s, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info); +void BLAS_FUNC(cpbtf2)(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, int *info); +void BLAS_FUNC(cpbtrf)(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, int *info); +void BLAS_FUNC(cpbtrs)(char *uplo, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *b, int *ldb, int *info); +void BLAS_FUNC(cpftrf)(char *transr, char *uplo, int *n, npy_complex64 *a, int *info); +void BLAS_FUNC(cpftri)(char *transr, char *uplo, int *n, npy_complex64 *a, int *info); +void BLAS_FUNC(cpftrs)(char *transr, char *uplo, int *n, int *nrhs, npy_complex64 *a, npy_complex64 *b, int *ldb, int *info); +void BLAS_FUNC(cpocon)(char *uplo, int *n, npy_complex64 *a, int *lda, float *anorm, float *rcond, npy_complex64 *work, float *rwork, int *info); +void BLAS_FUNC(cpoequ)(int *n, npy_complex64 *a, int *lda, float *s, float *scond, float *amax, int *info); +void BLAS_FUNC(cpoequb)(int *n, npy_complex64 *a, int *lda, float *s, float *scond, float *amax, int *info); +void BLAS_FUNC(cporfs)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info); +void BLAS_FUNC(cposv)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *info); +void BLAS_FUNC(cposvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, char *equed, float *s, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info); +void BLAS_FUNC(cpotf2)(char *uplo, int *n, npy_complex64 *a, int *lda, int *info); +void BLAS_FUNC(cpotrf)(char *uplo, int *n, npy_complex64 *a, int *lda, int *info); +void BLAS_FUNC(cpotri)(char *uplo, int *n, npy_complex64 *a, int *lda, int *info); +void BLAS_FUNC(cpotrs)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *info); +void BLAS_FUNC(cppcon)(char *uplo, int *n, npy_complex64 *ap, float *anorm, float *rcond, npy_complex64 *work, float *rwork, int *info); +void BLAS_FUNC(cppequ)(char *uplo, int *n, npy_complex64 *ap, float *s, float *scond, float *amax, int *info); +void BLAS_FUNC(cpprfs)(char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info); +void BLAS_FUNC(cppsv)(char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *b, int *ldb, int *info); +void BLAS_FUNC(cppsvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, char *equed, float *s, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info); +void BLAS_FUNC(cpptrf)(char *uplo, int *n, npy_complex64 *ap, int *info); +void BLAS_FUNC(cpptri)(char *uplo, int *n, npy_complex64 *ap, int *info); +void BLAS_FUNC(cpptrs)(char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *b, int *ldb, int *info); +void BLAS_FUNC(cpstf2)(char *uplo, int *n, npy_complex64 *a, int *lda, int *piv, int *rank, float *tol, float *work, int *info); +void BLAS_FUNC(cpstrf)(char *uplo, int *n, npy_complex64 *a, int *lda, int *piv, int *rank, float *tol, float *work, int *info); +void BLAS_FUNC(cptcon)(int *n, float *d, npy_complex64 *e, float *anorm, float *rcond, float *rwork, int *info); +void BLAS_FUNC(cpteqr)(char *compz, int *n, float *d, float *e, npy_complex64 *z, int *ldz, float *work, int *info); +void BLAS_FUNC(cptrfs)(char *uplo, int *n, int *nrhs, float *d, npy_complex64 *e, float *df, npy_complex64 *ef, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info); +void BLAS_FUNC(cptsv)(int *n, int *nrhs, float *d, npy_complex64 *e, npy_complex64 *b, int *ldb, int *info); +void BLAS_FUNC(cptsvx)(char *fact, int *n, int *nrhs, float *d, npy_complex64 *e, float *df, npy_complex64 *ef, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info); +void BLAS_FUNC(cpttrf)(int *n, float *d, npy_complex64 *e, int *info); +void BLAS_FUNC(cpttrs)(char *uplo, int *n, int *nrhs, float *d, npy_complex64 *e, npy_complex64 *b, int *ldb, int *info); +void BLAS_FUNC(cptts2)(int *iuplo, int *n, int *nrhs, float *d, npy_complex64 *e, npy_complex64 *b, int *ldb); +void BLAS_FUNC(crot)(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy, float *c, npy_complex64 *s); +void BLAS_FUNC(cspcon)(char *uplo, int *n, npy_complex64 *ap, int *ipiv, float *anorm, float *rcond, npy_complex64 *work, int *info); +void BLAS_FUNC(cspmv)(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *ap, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy); +void BLAS_FUNC(cspr)(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *ap); +void BLAS_FUNC(csprfs)(char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info); +void BLAS_FUNC(cspsv)(char *uplo, int *n, int *nrhs, npy_complex64 *ap, int *ipiv, npy_complex64 *b, int *ldb, int *info); +void BLAS_FUNC(cspsvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info); +void BLAS_FUNC(csptrf)(char *uplo, int *n, npy_complex64 *ap, int *ipiv, int *info); +void BLAS_FUNC(csptri)(char *uplo, int *n, npy_complex64 *ap, int *ipiv, npy_complex64 *work, int *info); +void BLAS_FUNC(csptrs)(char *uplo, int *n, int *nrhs, npy_complex64 *ap, int *ipiv, npy_complex64 *b, int *ldb, int *info); +void BLAS_FUNC(csrscl)(int *n, float *sa, npy_complex64 *sx, int *incx); +void BLAS_FUNC(cstedc)(char *compz, int *n, float *d, float *e, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, float *rwork, int *lrwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(cstegr)(char *jobz, char *range, int *n, float *d, float *e, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, npy_complex64 *z, int *ldz, int *isuppz, float *work, int *lwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(cstein)(int *n, float *d, float *e, int *m, float *w, int *iblock, int *isplit, npy_complex64 *z, int *ldz, float *work, int *iwork, int *ifail, int *info); +void BLAS_FUNC(cstemr)(char *jobz, char *range, int *n, float *d, float *e, float *vl, float *vu, int *il, int *iu, int *m, float *w, npy_complex64 *z, int *ldz, int *nzc, int *isuppz, int *tryrac, float *work, int *lwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(csteqr)(char *compz, int *n, float *d, float *e, npy_complex64 *z, int *ldz, float *work, int *info); +void BLAS_FUNC(csycon)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, float *anorm, float *rcond, npy_complex64 *work, int *info); +void BLAS_FUNC(csyconv)(char *uplo, char *way, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *info); +void BLAS_FUNC(csyequb)(char *uplo, int *n, npy_complex64 *a, int *lda, float *s, float *scond, float *amax, npy_complex64 *work, int *info); +void BLAS_FUNC(csymv)(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy); +void BLAS_FUNC(csyr)(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *a, int *lda); +void BLAS_FUNC(csyrfs)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info); +void BLAS_FUNC(csysv)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *work, int *lwork, int *info); +void BLAS_FUNC(csysvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, int *lwork, float *rwork, int *info); +void BLAS_FUNC(csyswapr)(char *uplo, int *n, npy_complex64 *a, int *lda, int *i1, int *i2); +void BLAS_FUNC(csytf2)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, int *info); +void BLAS_FUNC(csytrf)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *lwork, int *info); +void BLAS_FUNC(csytri)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *info); +void BLAS_FUNC(csytri2)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *lwork, int *info); +void BLAS_FUNC(csytri2x)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *nb, int *info); +void BLAS_FUNC(csytrs)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, int *info); +void BLAS_FUNC(csytrs2)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *work, int *info); +void BLAS_FUNC(ctbcon)(char *norm, char *uplo, char *diag, int *n, int *kd, npy_complex64 *ab, int *ldab, float *rcond, npy_complex64 *work, float *rwork, int *info); +void BLAS_FUNC(ctbrfs)(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info); +void BLAS_FUNC(ctbtrs)(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *b, int *ldb, int *info); +void BLAS_FUNC(ctfsm)(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, npy_complex64 *b, int *ldb); +void BLAS_FUNC(ctftri)(char *transr, char *uplo, char *diag, int *n, npy_complex64 *a, int *info); +void BLAS_FUNC(ctfttp)(char *transr, char *uplo, int *n, npy_complex64 *arf, npy_complex64 *ap, int *info); +void BLAS_FUNC(ctfttr)(char *transr, char *uplo, int *n, npy_complex64 *arf, npy_complex64 *a, int *lda, int *info); +void BLAS_FUNC(ctgevc)(char *side, char *howmny, int *select, int *n, npy_complex64 *s, int *lds, npy_complex64 *p, int *ldp, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, int *mm, int *m, npy_complex64 *work, float *rwork, int *info); +void BLAS_FUNC(ctgex2)(int *wantq, int *wantz, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *q, int *ldq, npy_complex64 *z, int *ldz, int *j1, int *info); +void BLAS_FUNC(ctgexc)(int *wantq, int *wantz, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *q, int *ldq, npy_complex64 *z, int *ldz, int *ifst, int *ilst, int *info); +void BLAS_FUNC(ctgsen)(int *ijob, int *wantq, int *wantz, int *select, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *q, int *ldq, npy_complex64 *z, int *ldz, int *m, float *pl, float *pr, float *dif, npy_complex64 *work, int *lwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(ctgsja)(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, float *tola, float *tolb, float *alpha, float *beta, npy_complex64 *u, int *ldu, npy_complex64 *v, int *ldv, npy_complex64 *q, int *ldq, npy_complex64 *work, int *ncycle, int *info); +void BLAS_FUNC(ctgsna)(char *job, char *howmny, int *select, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, float *s, float *dif, int *mm, int *m, npy_complex64 *work, int *lwork, int *iwork, int *info); +void BLAS_FUNC(ctgsy2)(char *trans, int *ijob, int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *c, int *ldc, npy_complex64 *d, int *ldd, npy_complex64 *e, int *lde, npy_complex64 *f, int *ldf, float *scale, float *rdsum, float *rdscal, int *info); +void BLAS_FUNC(ctgsyl)(char *trans, int *ijob, int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *c, int *ldc, npy_complex64 *d, int *ldd, npy_complex64 *e, int *lde, npy_complex64 *f, int *ldf, float *scale, float *dif, npy_complex64 *work, int *lwork, int *iwork, int *info); +void BLAS_FUNC(ctpcon)(char *norm, char *uplo, char *diag, int *n, npy_complex64 *ap, float *rcond, npy_complex64 *work, float *rwork, int *info); +void BLAS_FUNC(ctpmqrt)(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, npy_complex64 *v, int *ldv, npy_complex64 *t, int *ldt, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *work, int *info); +void BLAS_FUNC(ctpqrt)(int *m, int *n, int *l, int *nb, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *t, int *ldt, npy_complex64 *work, int *info); +void BLAS_FUNC(ctpqrt2)(int *m, int *n, int *l, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *t, int *ldt, int *info); +void BLAS_FUNC(ctprfb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, npy_complex64 *v, int *ldv, npy_complex64 *t, int *ldt, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *work, int *ldwork); +void BLAS_FUNC(ctprfs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info); +void BLAS_FUNC(ctptri)(char *uplo, char *diag, int *n, npy_complex64 *ap, int *info); +void BLAS_FUNC(ctptrs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *b, int *ldb, int *info); +void BLAS_FUNC(ctpttf)(char *transr, char *uplo, int *n, npy_complex64 *ap, npy_complex64 *arf, int *info); +void BLAS_FUNC(ctpttr)(char *uplo, int *n, npy_complex64 *ap, npy_complex64 *a, int *lda, int *info); +void BLAS_FUNC(ctrcon)(char *norm, char *uplo, char *diag, int *n, npy_complex64 *a, int *lda, float *rcond, npy_complex64 *work, float *rwork, int *info); +void BLAS_FUNC(ctrevc)(char *side, char *howmny, int *select, int *n, npy_complex64 *t, int *ldt, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, int *mm, int *m, npy_complex64 *work, float *rwork, int *info); +void BLAS_FUNC(ctrexc)(char *compq, int *n, npy_complex64 *t, int *ldt, npy_complex64 *q, int *ldq, int *ifst, int *ilst, int *info); +void BLAS_FUNC(ctrrfs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info); +void BLAS_FUNC(ctrsen)(char *job, char *compq, int *select, int *n, npy_complex64 *t, int *ldt, npy_complex64 *q, int *ldq, npy_complex64 *w, int *m, float *s, float *sep, npy_complex64 *work, int *lwork, int *info); +void BLAS_FUNC(ctrsna)(char *job, char *howmny, int *select, int *n, npy_complex64 *t, int *ldt, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, float *s, float *sep, int *mm, int *m, npy_complex64 *work, int *ldwork, float *rwork, int *info); +void BLAS_FUNC(ctrsyl)(char *trana, char *tranb, int *isgn, int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *c, int *ldc, float *scale, int *info); +void BLAS_FUNC(ctrti2)(char *uplo, char *diag, int *n, npy_complex64 *a, int *lda, int *info); +void BLAS_FUNC(ctrtri)(char *uplo, char *diag, int *n, npy_complex64 *a, int *lda, int *info); +void BLAS_FUNC(ctrtrs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *info); +void BLAS_FUNC(ctrttf)(char *transr, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *arf, int *info); +void BLAS_FUNC(ctrttp)(char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *ap, int *info); +void BLAS_FUNC(ctzrzf)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info); +void BLAS_FUNC(cunbdb)(char *trans, char *signs, int *m, int *p, int *q, npy_complex64 *x11, int *ldx11, npy_complex64 *x12, int *ldx12, npy_complex64 *x21, int *ldx21, npy_complex64 *x22, int *ldx22, float *theta, float *phi, npy_complex64 *taup1, npy_complex64 *taup2, npy_complex64 *tauq1, npy_complex64 *tauq2, npy_complex64 *work, int *lwork, int *info); +void BLAS_FUNC(cuncsd)(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, npy_complex64 *x11, int *ldx11, npy_complex64 *x12, int *ldx12, npy_complex64 *x21, int *ldx21, npy_complex64 *x22, int *ldx22, float *theta, npy_complex64 *u1, int *ldu1, npy_complex64 *u2, int *ldu2, npy_complex64 *v1t, int *ldv1t, npy_complex64 *v2t, int *ldv2t, npy_complex64 *work, int *lwork, float *rwork, int *lrwork, int *iwork, int *info); +void BLAS_FUNC(cung2l)(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info); +void BLAS_FUNC(cung2r)(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info); +void BLAS_FUNC(cungbr)(char *vect, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info); +void BLAS_FUNC(cunghr)(int *n, int *ilo, int *ihi, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info); +void BLAS_FUNC(cungl2)(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info); +void BLAS_FUNC(cunglq)(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info); +void BLAS_FUNC(cungql)(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info); +void BLAS_FUNC(cungqr)(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info); +void BLAS_FUNC(cungr2)(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info); +void BLAS_FUNC(cungrq)(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info); +void BLAS_FUNC(cungtr)(char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info); +void BLAS_FUNC(cunm2l)(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info); +void BLAS_FUNC(cunm2r)(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info); +void BLAS_FUNC(cunmbr)(char *vect, char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info); +void BLAS_FUNC(cunmhr)(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info); +void BLAS_FUNC(cunml2)(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info); +void BLAS_FUNC(cunmlq)(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info); +void BLAS_FUNC(cunmql)(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info); +void BLAS_FUNC(cunmqr)(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info); +void BLAS_FUNC(cunmr2)(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info); +void BLAS_FUNC(cunmr3)(char *side, char *trans, int *m, int *n, int *k, int *l, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info); +void BLAS_FUNC(cunmrq)(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info); +void BLAS_FUNC(cunmrz)(char *side, char *trans, int *m, int *n, int *k, int *l, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info); +void BLAS_FUNC(cunmtr)(char *side, char *uplo, char *trans, int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info); +void BLAS_FUNC(cupgtr)(char *uplo, int *n, npy_complex64 *ap, npy_complex64 *tau, npy_complex64 *q, int *ldq, npy_complex64 *work, int *info); +void BLAS_FUNC(cupmtr)(char *side, char *uplo, char *trans, int *m, int *n, npy_complex64 *ap, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info); +void BLAS_FUNC(dbbcsd)(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, double *theta, double *phi, double *u1, int *ldu1, double *u2, int *ldu2, double *v1t, int *ldv1t, double *v2t, int *ldv2t, double *b11d, double *b11e, double *b12d, double *b12e, double *b21d, double *b21e, double *b22d, double *b22e, double *work, int *lwork, int *info); +void BLAS_FUNC(dbdsdc)(char *uplo, char *compq, int *n, double *d, double *e, double *u, int *ldu, double *vt, int *ldvt, double *q, int *iq, double *work, int *iwork, int *info); +void BLAS_FUNC(dbdsqr)(char *uplo, int *n, int *ncvt, int *nru, int *ncc, double *d, double *e, double *vt, int *ldvt, double *u, int *ldu, double *c, int *ldc, double *work, int *info); +void BLAS_FUNC(ddisna)(char *job, int *m, int *n, double *d, double *sep, int *info); +void BLAS_FUNC(dgbbrd)(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, double *ab, int *ldab, double *d, double *e, double *q, int *ldq, double *pt, int *ldpt, double *c, int *ldc, double *work, int *info); +void BLAS_FUNC(dgbcon)(char *norm, int *n, int *kl, int *ku, double *ab, int *ldab, int *ipiv, double *anorm, double *rcond, double *work, int *iwork, int *info); +void BLAS_FUNC(dgbequ)(int *m, int *n, int *kl, int *ku, double *ab, int *ldab, double *r, double *c, double *rowcnd, double *colcnd, double *amax, int *info); +void BLAS_FUNC(dgbequb)(int *m, int *n, int *kl, int *ku, double *ab, int *ldab, double *r, double *c, double *rowcnd, double *colcnd, double *amax, int *info); +void BLAS_FUNC(dgbrfs)(char *trans, int *n, int *kl, int *ku, int *nrhs, double *ab, int *ldab, double *afb, int *ldafb, int *ipiv, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info); +void BLAS_FUNC(dgbsv)(int *n, int *kl, int *ku, int *nrhs, double *ab, int *ldab, int *ipiv, double *b, int *ldb, int *info); +void BLAS_FUNC(dgbsvx)(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, double *ab, int *ldab, double *afb, int *ldafb, int *ipiv, char *equed, double *r, double *c, double *b, int *ldb, double *x, int *ldx, double *rcond, double *ferr, double *berr, double *work, int *iwork, int *info); +void BLAS_FUNC(dgbtf2)(int *m, int *n, int *kl, int *ku, double *ab, int *ldab, int *ipiv, int *info); +void BLAS_FUNC(dgbtrf)(int *m, int *n, int *kl, int *ku, double *ab, int *ldab, int *ipiv, int *info); +void BLAS_FUNC(dgbtrs)(char *trans, int *n, int *kl, int *ku, int *nrhs, double *ab, int *ldab, int *ipiv, double *b, int *ldb, int *info); +void BLAS_FUNC(dgebak)(char *job, char *side, int *n, int *ilo, int *ihi, double *scale, int *m, double *v, int *ldv, int *info); +void BLAS_FUNC(dgebal)(char *job, int *n, double *a, int *lda, int *ilo, int *ihi, double *scale, int *info); +void BLAS_FUNC(dgebd2)(int *m, int *n, double *a, int *lda, double *d, double *e, double *tauq, double *taup, double *work, int *info); +void BLAS_FUNC(dgebrd)(int *m, int *n, double *a, int *lda, double *d, double *e, double *tauq, double *taup, double *work, int *lwork, int *info); +void BLAS_FUNC(dgecon)(char *norm, int *n, double *a, int *lda, double *anorm, double *rcond, double *work, int *iwork, int *info); +void BLAS_FUNC(dgeequ)(int *m, int *n, double *a, int *lda, double *r, double *c, double *rowcnd, double *colcnd, double *amax, int *info); +void BLAS_FUNC(dgeequb)(int *m, int *n, double *a, int *lda, double *r, double *c, double *rowcnd, double *colcnd, double *amax, int *info); +void BLAS_FUNC(dgees)(char *jobvs, char *sort, _dselect2 *select, int *n, double *a, int *lda, int *sdim, double *wr, double *wi, double *vs, int *ldvs, double *work, int *lwork, int *bwork, int *info); +void BLAS_FUNC(dgeesx)(char *jobvs, char *sort, _dselect2 *select, char *sense, int *n, double *a, int *lda, int *sdim, double *wr, double *wi, double *vs, int *ldvs, double *rconde, double *rcondv, double *work, int *lwork, int *iwork, int *liwork, int *bwork, int *info); +void BLAS_FUNC(dgeev)(char *jobvl, char *jobvr, int *n, double *a, int *lda, double *wr, double *wi, double *vl, int *ldvl, double *vr, int *ldvr, double *work, int *lwork, int *info); +void BLAS_FUNC(dgeevx)(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, double *a, int *lda, double *wr, double *wi, double *vl, int *ldvl, double *vr, int *ldvr, int *ilo, int *ihi, double *scale, double *abnrm, double *rconde, double *rcondv, double *work, int *lwork, int *iwork, int *info); +void BLAS_FUNC(dgehd2)(int *n, int *ilo, int *ihi, double *a, int *lda, double *tau, double *work, int *info); +void BLAS_FUNC(dgehrd)(int *n, int *ilo, int *ihi, double *a, int *lda, double *tau, double *work, int *lwork, int *info); +void BLAS_FUNC(dgejsv)(char *joba, char *jobu, char *jobv, char *jobr, char *jobt, char *jobp, int *m, int *n, double *a, int *lda, double *sva, double *u, int *ldu, double *v, int *ldv, double *work, int *lwork, int *iwork, int *info); +void BLAS_FUNC(dgelq2)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *info); +void BLAS_FUNC(dgelqf)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *lwork, int *info); +void BLAS_FUNC(dgels)(char *trans, int *m, int *n, int *nrhs, double *a, int *lda, double *b, int *ldb, double *work, int *lwork, int *info); +void BLAS_FUNC(dgelsd)(int *m, int *n, int *nrhs, double *a, int *lda, double *b, int *ldb, double *s, double *rcond, int *rank, double *work, int *lwork, int *iwork, int *info); +void BLAS_FUNC(dgelss)(int *m, int *n, int *nrhs, double *a, int *lda, double *b, int *ldb, double *s, double *rcond, int *rank, double *work, int *lwork, int *info); +void BLAS_FUNC(dgelsy)(int *m, int *n, int *nrhs, double *a, int *lda, double *b, int *ldb, int *jpvt, double *rcond, int *rank, double *work, int *lwork, int *info); +void BLAS_FUNC(dgemqrt)(char *side, char *trans, int *m, int *n, int *k, int *nb, double *v, int *ldv, double *t, int *ldt, double *c, int *ldc, double *work, int *info); +void BLAS_FUNC(dgeql2)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *info); +void BLAS_FUNC(dgeqlf)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *lwork, int *info); +void BLAS_FUNC(dgeqp3)(int *m, int *n, double *a, int *lda, int *jpvt, double *tau, double *work, int *lwork, int *info); +void BLAS_FUNC(dgeqr2)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *info); +void BLAS_FUNC(dgeqr2p)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *info); +void BLAS_FUNC(dgeqrf)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *lwork, int *info); +void BLAS_FUNC(dgeqrfp)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *lwork, int *info); +void BLAS_FUNC(dgeqrt)(int *m, int *n, int *nb, double *a, int *lda, double *t, int *ldt, double *work, int *info); +void BLAS_FUNC(dgeqrt2)(int *m, int *n, double *a, int *lda, double *t, int *ldt, int *info); +void BLAS_FUNC(dgeqrt3)(int *m, int *n, double *a, int *lda, double *t, int *ldt, int *info); +void BLAS_FUNC(dgerfs)(char *trans, int *n, int *nrhs, double *a, int *lda, double *af, int *ldaf, int *ipiv, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info); +void BLAS_FUNC(dgerq2)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *info); +void BLAS_FUNC(dgerqf)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *lwork, int *info); +void BLAS_FUNC(dgesc2)(int *n, double *a, int *lda, double *rhs, int *ipiv, int *jpiv, double *scale); +void BLAS_FUNC(dgesdd)(char *jobz, int *m, int *n, double *a, int *lda, double *s, double *u, int *ldu, double *vt, int *ldvt, double *work, int *lwork, int *iwork, int *info); +void BLAS_FUNC(dgesv)(int *n, int *nrhs, double *a, int *lda, int *ipiv, double *b, int *ldb, int *info); +void BLAS_FUNC(dgesvd)(char *jobu, char *jobvt, int *m, int *n, double *a, int *lda, double *s, double *u, int *ldu, double *vt, int *ldvt, double *work, int *lwork, int *info); +void BLAS_FUNC(dgesvj)(char *joba, char *jobu, char *jobv, int *m, int *n, double *a, int *lda, double *sva, int *mv, double *v, int *ldv, double *work, int *lwork, int *info); +void BLAS_FUNC(dgesvx)(char *fact, char *trans, int *n, int *nrhs, double *a, int *lda, double *af, int *ldaf, int *ipiv, char *equed, double *r, double *c, double *b, int *ldb, double *x, int *ldx, double *rcond, double *ferr, double *berr, double *work, int *iwork, int *info); +void BLAS_FUNC(dgetc2)(int *n, double *a, int *lda, int *ipiv, int *jpiv, int *info); +void BLAS_FUNC(dgetf2)(int *m, int *n, double *a, int *lda, int *ipiv, int *info); +void BLAS_FUNC(dgetrf)(int *m, int *n, double *a, int *lda, int *ipiv, int *info); +void BLAS_FUNC(dgetri)(int *n, double *a, int *lda, int *ipiv, double *work, int *lwork, int *info); +void BLAS_FUNC(dgetrs)(char *trans, int *n, int *nrhs, double *a, int *lda, int *ipiv, double *b, int *ldb, int *info); +void BLAS_FUNC(dggbak)(char *job, char *side, int *n, int *ilo, int *ihi, double *lscale, double *rscale, int *m, double *v, int *ldv, int *info); +void BLAS_FUNC(dggbal)(char *job, int *n, double *a, int *lda, double *b, int *ldb, int *ilo, int *ihi, double *lscale, double *rscale, double *work, int *info); +void BLAS_FUNC(dgges)(char *jobvsl, char *jobvsr, char *sort, _dselect3 *selctg, int *n, double *a, int *lda, double *b, int *ldb, int *sdim, double *alphar, double *alphai, double *beta, double *vsl, int *ldvsl, double *vsr, int *ldvsr, double *work, int *lwork, int *bwork, int *info); +void BLAS_FUNC(dggesx)(char *jobvsl, char *jobvsr, char *sort, _dselect3 *selctg, char *sense, int *n, double *a, int *lda, double *b, int *ldb, int *sdim, double *alphar, double *alphai, double *beta, double *vsl, int *ldvsl, double *vsr, int *ldvsr, double *rconde, double *rcondv, double *work, int *lwork, int *iwork, int *liwork, int *bwork, int *info); +void BLAS_FUNC(dggev)(char *jobvl, char *jobvr, int *n, double *a, int *lda, double *b, int *ldb, double *alphar, double *alphai, double *beta, double *vl, int *ldvl, double *vr, int *ldvr, double *work, int *lwork, int *info); +void BLAS_FUNC(dggevx)(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, double *a, int *lda, double *b, int *ldb, double *alphar, double *alphai, double *beta, double *vl, int *ldvl, double *vr, int *ldvr, int *ilo, int *ihi, double *lscale, double *rscale, double *abnrm, double *bbnrm, double *rconde, double *rcondv, double *work, int *lwork, int *iwork, int *bwork, int *info); +void BLAS_FUNC(dggglm)(int *n, int *m, int *p, double *a, int *lda, double *b, int *ldb, double *d, double *x, double *y, double *work, int *lwork, int *info); +void BLAS_FUNC(dgghrd)(char *compq, char *compz, int *n, int *ilo, int *ihi, double *a, int *lda, double *b, int *ldb, double *q, int *ldq, double *z, int *ldz, int *info); +void BLAS_FUNC(dgglse)(int *m, int *n, int *p, double *a, int *lda, double *b, int *ldb, double *c, double *d, double *x, double *work, int *lwork, int *info); +void BLAS_FUNC(dggqrf)(int *n, int *m, int *p, double *a, int *lda, double *taua, double *b, int *ldb, double *taub, double *work, int *lwork, int *info); +void BLAS_FUNC(dggrqf)(int *m, int *p, int *n, double *a, int *lda, double *taua, double *b, int *ldb, double *taub, double *work, int *lwork, int *info); +void BLAS_FUNC(dgsvj0)(char *jobv, int *m, int *n, double *a, int *lda, double *d, double *sva, int *mv, double *v, int *ldv, double *eps, double *sfmin, double *tol, int *nsweep, double *work, int *lwork, int *info); +void BLAS_FUNC(dgsvj1)(char *jobv, int *m, int *n, int *n1, double *a, int *lda, double *d, double *sva, int *mv, double *v, int *ldv, double *eps, double *sfmin, double *tol, int *nsweep, double *work, int *lwork, int *info); +void BLAS_FUNC(dgtcon)(char *norm, int *n, double *dl, double *d, double *du, double *du2, int *ipiv, double *anorm, double *rcond, double *work, int *iwork, int *info); +void BLAS_FUNC(dgtrfs)(char *trans, int *n, int *nrhs, double *dl, double *d, double *du, double *dlf, double *df, double *duf, double *du2, int *ipiv, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info); +void BLAS_FUNC(dgtsv)(int *n, int *nrhs, double *dl, double *d, double *du, double *b, int *ldb, int *info); +void BLAS_FUNC(dgtsvx)(char *fact, char *trans, int *n, int *nrhs, double *dl, double *d, double *du, double *dlf, double *df, double *duf, double *du2, int *ipiv, double *b, int *ldb, double *x, int *ldx, double *rcond, double *ferr, double *berr, double *work, int *iwork, int *info); +void BLAS_FUNC(dgttrf)(int *n, double *dl, double *d, double *du, double *du2, int *ipiv, int *info); +void BLAS_FUNC(dgttrs)(char *trans, int *n, int *nrhs, double *dl, double *d, double *du, double *du2, int *ipiv, double *b, int *ldb, int *info); +void BLAS_FUNC(dgtts2)(int *itrans, int *n, int *nrhs, double *dl, double *d, double *du, double *du2, int *ipiv, double *b, int *ldb); +void BLAS_FUNC(dhgeqz)(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, double *h, int *ldh, double *t, int *ldt, double *alphar, double *alphai, double *beta, double *q, int *ldq, double *z, int *ldz, double *work, int *lwork, int *info); +void BLAS_FUNC(dhsein)(char *side, char *eigsrc, char *initv, int *select, int *n, double *h, int *ldh, double *wr, double *wi, double *vl, int *ldvl, double *vr, int *ldvr, int *mm, int *m, double *work, int *ifaill, int *ifailr, int *info); +void BLAS_FUNC(dhseqr)(char *job, char *compz, int *n, int *ilo, int *ihi, double *h, int *ldh, double *wr, double *wi, double *z, int *ldz, double *work, int *lwork, int *info); +int BLAS_FUNC(disnan)(double *din); +void BLAS_FUNC(dlabad)(double *small, double *large); +void BLAS_FUNC(dlabrd)(int *m, int *n, int *nb, double *a, int *lda, double *d, double *e, double *tauq, double *taup, double *x, int *ldx, double *y, int *ldy); +void BLAS_FUNC(dlacn2)(int *n, double *v, double *x, int *isgn, double *est, int *kase, int *isave); +void BLAS_FUNC(dlacon)(int *n, double *v, double *x, int *isgn, double *est, int *kase); +void BLAS_FUNC(dlacpy)(char *uplo, int *m, int *n, double *a, int *lda, double *b, int *ldb); +void BLAS_FUNC(dladiv)(double *a, double *b, double *c, double *d, double *p, double *q); +void BLAS_FUNC(dlae2)(double *a, double *b, double *c, double *rt1, double *rt2); +void BLAS_FUNC(dlaebz)(int *ijob, int *nitmax, int *n, int *mmax, int *minp, int *nbmin, double *abstol, double *reltol, double *pivmin, double *d, double *e, double *e2, int *nval, double *ab, double *c, int *mout, int *nab, double *work, int *iwork, int *info); +void BLAS_FUNC(dlaed0)(int *icompq, int *qsiz, int *n, double *d, double *e, double *q, int *ldq, double *qstore, int *ldqs, double *work, int *iwork, int *info); +void BLAS_FUNC(dlaed1)(int *n, double *d, double *q, int *ldq, int *indxq, double *rho, int *cutpnt, double *work, int *iwork, int *info); +void BLAS_FUNC(dlaed2)(int *k, int *n, int *n1, double *d, double *q, int *ldq, int *indxq, double *rho, double *z, double *dlamda, double *w, double *q2, int *indx, int *indxc, int *indxp, int *coltyp, int *info); +void BLAS_FUNC(dlaed3)(int *k, int *n, int *n1, double *d, double *q, int *ldq, double *rho, double *dlamda, double *q2, int *indx, int *ctot, double *w, double *s, int *info); +void BLAS_FUNC(dlaed4)(int *n, int *i, double *d, double *z, double *delta, double *rho, double *dlam, int *info); +void BLAS_FUNC(dlaed5)(int *i, double *d, double *z, double *delta, double *rho, double *dlam); +void BLAS_FUNC(dlaed6)(int *kniter, int *orgati, double *rho, double *d, double *z, double *finit, double *tau, int *info); +void BLAS_FUNC(dlaed7)(int *icompq, int *n, int *qsiz, int *tlvls, int *curlvl, int *curpbm, double *d, double *q, int *ldq, int *indxq, double *rho, int *cutpnt, double *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, double *givnum, double *work, int *iwork, int *info); +void BLAS_FUNC(dlaed8)(int *icompq, int *k, int *n, int *qsiz, double *d, double *q, int *ldq, int *indxq, double *rho, int *cutpnt, double *z, double *dlamda, double *q2, int *ldq2, double *w, int *perm, int *givptr, int *givcol, double *givnum, int *indxp, int *indx, int *info); +void BLAS_FUNC(dlaed9)(int *k, int *kstart, int *kstop, int *n, double *d, double *q, int *ldq, double *rho, double *dlamda, double *w, double *s, int *lds, int *info); +void BLAS_FUNC(dlaeda)(int *n, int *tlvls, int *curlvl, int *curpbm, int *prmptr, int *perm, int *givptr, int *givcol, double *givnum, double *q, int *qptr, double *z, double *ztemp, int *info); +void BLAS_FUNC(dlaein)(int *rightv, int *noinit, int *n, double *h, int *ldh, double *wr, double *wi, double *vr, double *vi, double *b, int *ldb, double *work, double *eps3, double *smlnum, double *bignum, int *info); +void BLAS_FUNC(dlaev2)(double *a, double *b, double *c, double *rt1, double *rt2, double *cs1, double *sn1); +void BLAS_FUNC(dlaexc)(int *wantq, int *n, double *t, int *ldt, double *q, int *ldq, int *j1, int *n1, int *n2, double *work, int *info); +void BLAS_FUNC(dlag2)(double *a, int *lda, double *b, int *ldb, double *safmin, double *scale1, double *scale2, double *wr1, double *wr2, double *wi); +void BLAS_FUNC(dlag2s)(int *m, int *n, double *a, int *lda, float *sa, int *ldsa, int *info); +void BLAS_FUNC(dlags2)(int *upper, double *a1, double *a2, double *a3, double *b1, double *b2, double *b3, double *csu, double *snu, double *csv, double *snv, double *csq, double *snq); +void BLAS_FUNC(dlagtf)(int *n, double *a, double *lambda_, double *b, double *c, double *tol, double *d, int *in_, int *info); +void BLAS_FUNC(dlagtm)(char *trans, int *n, int *nrhs, double *alpha, double *dl, double *d, double *du, double *x, int *ldx, double *beta, double *b, int *ldb); +void BLAS_FUNC(dlagts)(int *job, int *n, double *a, double *b, double *c, double *d, int *in_, double *y, double *tol, int *info); +void BLAS_FUNC(dlagv2)(double *a, int *lda, double *b, int *ldb, double *alphar, double *alphai, double *beta, double *csl, double *snl, double *csr, double *snr); +void BLAS_FUNC(dlahqr)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, double *h, int *ldh, double *wr, double *wi, int *iloz, int *ihiz, double *z, int *ldz, int *info); +void BLAS_FUNC(dlahr2)(int *n, int *k, int *nb, double *a, int *lda, double *tau, double *t, int *ldt, double *y, int *ldy); +void BLAS_FUNC(dlaic1)(int *job, int *j, double *x, double *sest, double *w, double *gamma, double *sestpr, double *s, double *c); +void BLAS_FUNC(dlaln2)(int *ltrans, int *na, int *nw, double *smin, double *ca, double *a, int *lda, double *d1, double *d2, double *b, int *ldb, double *wr, double *wi, double *x, int *ldx, double *scale, double *xnorm, int *info); +void BLAS_FUNC(dlals0)(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, double *b, int *ldb, double *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, double *givnum, int *ldgnum, double *poles, double *difl, double *difr, double *z, int *k, double *c, double *s, double *work, int *info); +void BLAS_FUNC(dlalsa)(int *icompq, int *smlsiz, int *n, int *nrhs, double *b, int *ldb, double *bx, int *ldbx, double *u, int *ldu, double *vt, int *k, double *difl, double *difr, double *z, double *poles, int *givptr, int *givcol, int *ldgcol, int *perm, double *givnum, double *c, double *s, double *work, int *iwork, int *info); +void BLAS_FUNC(dlalsd)(char *uplo, int *smlsiz, int *n, int *nrhs, double *d, double *e, double *b, int *ldb, double *rcond, int *rank, double *work, int *iwork, int *info); +double BLAS_FUNC(dlamch)(char *cmach); +void BLAS_FUNC(dlamrg)(int *n1, int *n2, double *a, int *dtrd1, int *dtrd2, int *index_bn); +int BLAS_FUNC(dlaneg)(int *n, double *d, double *lld, double *sigma, double *pivmin, int *r); +double BLAS_FUNC(dlangb)(char *norm, int *n, int *kl, int *ku, double *ab, int *ldab, double *work); +double BLAS_FUNC(dlange)(char *norm, int *m, int *n, double *a, int *lda, double *work); +double BLAS_FUNC(dlangt)(char *norm, int *n, double *dl, double *d_, double *du); +double BLAS_FUNC(dlanhs)(char *norm, int *n, double *a, int *lda, double *work); +double BLAS_FUNC(dlansb)(char *norm, char *uplo, int *n, int *k, double *ab, int *ldab, double *work); +double BLAS_FUNC(dlansf)(char *norm, char *transr, char *uplo, int *n, double *a, double *work); +double BLAS_FUNC(dlansp)(char *norm, char *uplo, int *n, double *ap, double *work); +double BLAS_FUNC(dlanst)(char *norm, int *n, double *d_, double *e); +double BLAS_FUNC(dlansy)(char *norm, char *uplo, int *n, double *a, int *lda, double *work); +double BLAS_FUNC(dlantb)(char *norm, char *uplo, char *diag, int *n, int *k, double *ab, int *ldab, double *work); +double BLAS_FUNC(dlantp)(char *norm, char *uplo, char *diag, int *n, double *ap, double *work); +double BLAS_FUNC(dlantr)(char *norm, char *uplo, char *diag, int *m, int *n, double *a, int *lda, double *work); +void BLAS_FUNC(dlanv2)(double *a, double *b, double *c, double *d, double *rt1r, double *rt1i, double *rt2r, double *rt2i, double *cs, double *sn); +void BLAS_FUNC(dlapll)(int *n, double *x, int *incx, double *y, int *incy, double *ssmin); +void BLAS_FUNC(dlapmr)(int *forwrd, int *m, int *n, double *x, int *ldx, int *k); +void BLAS_FUNC(dlapmt)(int *forwrd, int *m, int *n, double *x, int *ldx, int *k); +double BLAS_FUNC(dlapy2)(double *x, double *y); +double BLAS_FUNC(dlapy3)(double *x, double *y, double *z); +void BLAS_FUNC(dlaqgb)(int *m, int *n, int *kl, int *ku, double *ab, int *ldab, double *r, double *c, double *rowcnd, double *colcnd, double *amax, char *equed); +void BLAS_FUNC(dlaqge)(int *m, int *n, double *a, int *lda, double *r, double *c, double *rowcnd, double *colcnd, double *amax, char *equed); +void BLAS_FUNC(dlaqp2)(int *m, int *n, int *offset, double *a, int *lda, int *jpvt, double *tau, double *vn1, double *vn2, double *work); +void BLAS_FUNC(dlaqps)(int *m, int *n, int *offset, int *nb, int *kb, double *a, int *lda, int *jpvt, double *tau, double *vn1, double *vn2, double *auxv, double *f, int *ldf); +void BLAS_FUNC(dlaqr0)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, double *h, int *ldh, double *wr, double *wi, int *iloz, int *ihiz, double *z, int *ldz, double *work, int *lwork, int *info); +void BLAS_FUNC(dlaqr1)(int *n, double *h, int *ldh, double *sr1, double *si1, double *sr2, double *si2, double *v); +void BLAS_FUNC(dlaqr2)(int *wantt, int *wantz, int *n, int *ktop, int *kbot, int *nw, double *h, int *ldh, int *iloz, int *ihiz, double *z, int *ldz, int *ns, int *nd, double *sr, double *si, double *v, int *ldv, int *nh, double *t, int *ldt, int *nv, double *wv, int *ldwv, double *work, int *lwork); +void BLAS_FUNC(dlaqr3)(int *wantt, int *wantz, int *n, int *ktop, int *kbot, int *nw, double *h, int *ldh, int *iloz, int *ihiz, double *z, int *ldz, int *ns, int *nd, double *sr, double *si, double *v, int *ldv, int *nh, double *t, int *ldt, int *nv, double *wv, int *ldwv, double *work, int *lwork); +void BLAS_FUNC(dlaqr4)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, double *h, int *ldh, double *wr, double *wi, int *iloz, int *ihiz, double *z, int *ldz, double *work, int *lwork, int *info); +void BLAS_FUNC(dlaqr5)(int *wantt, int *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, double *sr, double *si, double *h, int *ldh, int *iloz, int *ihiz, double *z, int *ldz, double *v, int *ldv, double *u, int *ldu, int *nv, double *wv, int *ldwv, int *nh, double *wh, int *ldwh); +void BLAS_FUNC(dlaqsb)(char *uplo, int *n, int *kd, double *ab, int *ldab, double *s, double *scond, double *amax, char *equed); +void BLAS_FUNC(dlaqsp)(char *uplo, int *n, double *ap, double *s, double *scond, double *amax, char *equed); +void BLAS_FUNC(dlaqsy)(char *uplo, int *n, double *a, int *lda, double *s, double *scond, double *amax, char *equed); +void BLAS_FUNC(dlaqtr)(int *ltran, int *lreal, int *n, double *t, int *ldt, double *b, double *w, double *scale, double *x, double *work, int *info); +void BLAS_FUNC(dlar1v)(int *n, int *b1, int *bn, double *lambda_, double *d, double *l, double *ld, double *lld, double *pivmin, double *gaptol, double *z, int *wantnc, int *negcnt, double *ztz, double *mingma, int *r, int *isuppz, double *nrminv, double *resid, double *rqcorr, double *work); +void BLAS_FUNC(dlar2v)(int *n, double *x, double *y, double *z, int *incx, double *c, double *s, int *incc); +void BLAS_FUNC(dlarf)(char *side, int *m, int *n, double *v, int *incv, double *tau, double *c, int *ldc, double *work); +void BLAS_FUNC(dlarfb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, double *v, int *ldv, double *t, int *ldt, double *c, int *ldc, double *work, int *ldwork); +void BLAS_FUNC(dlarfg)(int *n, double *alpha, double *x, int *incx, double *tau); +void BLAS_FUNC(dlarfgp)(int *n, double *alpha, double *x, int *incx, double *tau); +void BLAS_FUNC(dlarft)(char *direct, char *storev, int *n, int *k, double *v, int *ldv, double *tau, double *t, int *ldt); +void BLAS_FUNC(dlarfx)(char *side, int *m, int *n, double *v, double *tau, double *c, int *ldc, double *work); +void BLAS_FUNC(dlargv)(int *n, double *x, int *incx, double *y, int *incy, double *c, int *incc); +void BLAS_FUNC(dlarnv)(int *idist, int *iseed, int *n, double *x); +void BLAS_FUNC(dlarra)(int *n, double *d, double *e, double *e2, double *spltol, double *tnrm, int *nsplit, int *isplit, int *info); +void BLAS_FUNC(dlarrb)(int *n, double *d, double *lld, int *ifirst, int *ilast, double *rtol1, double *rtol2, int *offset, double *w, double *wgap, double *werr, double *work, int *iwork, double *pivmin, double *spdiam, int *twist, int *info); +void BLAS_FUNC(dlarrc)(char *jobt, int *n, double *vl, double *vu, double *d, double *e, double *pivmin, int *eigcnt, int *lcnt, int *rcnt, int *info); +void BLAS_FUNC(dlarrd)(char *range, char *order, int *n, double *vl, double *vu, int *il, int *iu, double *gers, double *reltol, double *d, double *e, double *e2, double *pivmin, int *nsplit, int *isplit, int *m, double *w, double *werr, double *wl, double *wu, int *iblock, int *indexw, double *work, int *iwork, int *info); +void BLAS_FUNC(dlarre)(char *range, int *n, double *vl, double *vu, int *il, int *iu, double *d, double *e, double *e2, double *rtol1, double *rtol2, double *spltol, int *nsplit, int *isplit, int *m, double *w, double *werr, double *wgap, int *iblock, int *indexw, double *gers, double *pivmin, double *work, int *iwork, int *info); +void BLAS_FUNC(dlarrf)(int *n, double *d, double *l, double *ld, int *clstrt, int *clend, double *w, double *wgap, double *werr, double *spdiam, double *clgapl, double *clgapr, double *pivmin, double *sigma, double *dplus, double *lplus, double *work, int *info); +void BLAS_FUNC(dlarrj)(int *n, double *d, double *e2, int *ifirst, int *ilast, double *rtol, int *offset, double *w, double *werr, double *work, int *iwork, double *pivmin, double *spdiam, int *info); +void BLAS_FUNC(dlarrk)(int *n, int *iw, double *gl, double *gu, double *d, double *e2, double *pivmin, double *reltol, double *w, double *werr, int *info); +void BLAS_FUNC(dlarrr)(int *n, double *d, double *e, int *info); +void BLAS_FUNC(dlarrv)(int *n, double *vl, double *vu, double *d, double *l, double *pivmin, int *isplit, int *m, int *dol, int *dou, double *minrgp, double *rtol1, double *rtol2, double *w, double *werr, double *wgap, int *iblock, int *indexw, double *gers, double *z, int *ldz, int *isuppz, double *work, int *iwork, int *info); +void BLAS_FUNC(dlartg)(double *f, double *g, double *cs, double *sn, double *r); +void BLAS_FUNC(dlartgp)(double *f, double *g, double *cs, double *sn, double *r); +void BLAS_FUNC(dlartgs)(double *x, double *y, double *sigma, double *cs, double *sn); +void BLAS_FUNC(dlartv)(int *n, double *x, int *incx, double *y, int *incy, double *c, double *s, int *incc); +void BLAS_FUNC(dlaruv)(int *iseed, int *n, double *x); +void BLAS_FUNC(dlarz)(char *side, int *m, int *n, int *l, double *v, int *incv, double *tau, double *c, int *ldc, double *work); +void BLAS_FUNC(dlarzb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, double *v, int *ldv, double *t, int *ldt, double *c, int *ldc, double *work, int *ldwork); +void BLAS_FUNC(dlarzt)(char *direct, char *storev, int *n, int *k, double *v, int *ldv, double *tau, double *t, int *ldt); +void BLAS_FUNC(dlas2)(double *f, double *g, double *h, double *ssmin, double *ssmax); +void BLAS_FUNC(dlascl)(char *type_bn, int *kl, int *ku, double *cfrom, double *cto, int *m, int *n, double *a, int *lda, int *info); +void BLAS_FUNC(dlasd0)(int *n, int *sqre, double *d, double *e, double *u, int *ldu, double *vt, int *ldvt, int *smlsiz, int *iwork, double *work, int *info); +void BLAS_FUNC(dlasd1)(int *nl, int *nr, int *sqre, double *d, double *alpha, double *beta, double *u, int *ldu, double *vt, int *ldvt, int *idxq, int *iwork, double *work, int *info); +void BLAS_FUNC(dlasd2)(int *nl, int *nr, int *sqre, int *k, double *d, double *z, double *alpha, double *beta, double *u, int *ldu, double *vt, int *ldvt, double *dsigma, double *u2, int *ldu2, double *vt2, int *ldvt2, int *idxp, int *idx, int *idxc, int *idxq, int *coltyp, int *info); +void BLAS_FUNC(dlasd3)(int *nl, int *nr, int *sqre, int *k, double *d, double *q, int *ldq, double *dsigma, double *u, int *ldu, double *u2, int *ldu2, double *vt, int *ldvt, double *vt2, int *ldvt2, int *idxc, int *ctot, double *z, int *info); +void BLAS_FUNC(dlasd4)(int *n, int *i, double *d, double *z, double *delta, double *rho, double *sigma, double *work, int *info); +void BLAS_FUNC(dlasd5)(int *i, double *d, double *z, double *delta, double *rho, double *dsigma, double *work); +void BLAS_FUNC(dlasd6)(int *icompq, int *nl, int *nr, int *sqre, double *d, double *vf, double *vl, double *alpha, double *beta, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, double *givnum, int *ldgnum, double *poles, double *difl, double *difr, double *z, int *k, double *c, double *s, double *work, int *iwork, int *info); +void BLAS_FUNC(dlasd7)(int *icompq, int *nl, int *nr, int *sqre, int *k, double *d, double *z, double *zw, double *vf, double *vfw, double *vl, double *vlw, double *alpha, double *beta, double *dsigma, int *idx, int *idxp, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, double *givnum, int *ldgnum, double *c, double *s, int *info); +void BLAS_FUNC(dlasd8)(int *icompq, int *k, double *d, double *z, double *vf, double *vl, double *difl, double *difr, int *lddifr, double *dsigma, double *work, int *info); +void BLAS_FUNC(dlasda)(int *icompq, int *smlsiz, int *n, int *sqre, double *d, double *e, double *u, int *ldu, double *vt, int *k, double *difl, double *difr, double *z, double *poles, int *givptr, int *givcol, int *ldgcol, int *perm, double *givnum, double *c, double *s, double *work, int *iwork, int *info); +void BLAS_FUNC(dlasdq)(char *uplo, int *sqre, int *n, int *ncvt, int *nru, int *ncc, double *d, double *e, double *vt, int *ldvt, double *u, int *ldu, double *c, int *ldc, double *work, int *info); +void BLAS_FUNC(dlasdt)(int *n, int *lvl, int *nd, int *inode, int *ndiml, int *ndimr, int *msub); +void BLAS_FUNC(dlaset)(char *uplo, int *m, int *n, double *alpha, double *beta, double *a, int *lda); +void BLAS_FUNC(dlasq1)(int *n, double *d, double *e, double *work, int *info); +void BLAS_FUNC(dlasq2)(int *n, double *z, int *info); +void BLAS_FUNC(dlasq3)(int *i0, int *n0, double *z, int *pp, double *dmin, double *sigma, double *desig, double *qmax, int *nfail, int *iter, int *ndiv, int *ieee, int *ttype, double *dmin1, double *dmin2, double *dn, double *dn1, double *dn2, double *g, double *tau); +void BLAS_FUNC(dlasq4)(int *i0, int *n0, double *z, int *pp, int *n0in, double *dmin, double *dmin1, double *dmin2, double *dn, double *dn1, double *dn2, double *tau, int *ttype, double *g); +void BLAS_FUNC(dlasq6)(int *i0, int *n0, double *z, int *pp, double *dmin, double *dmin1, double *dmin2, double *dn, double *dnm1, double *dnm2); +void BLAS_FUNC(dlasr)(char *side, char *pivot, char *direct, int *m, int *n, double *c, double *s, double *a, int *lda); +void BLAS_FUNC(dlasrt)(char *id, int *n, double *d, int *info); +void BLAS_FUNC(dlassq)(int *n, double *x, int *incx, double *scale, double *sumsq); +void BLAS_FUNC(dlasv2)(double *f, double *g, double *h, double *ssmin, double *ssmax, double *snr, double *csr, double *snl, double *csl); +void BLAS_FUNC(dlaswp)(int *n, double *a, int *lda, int *k1, int *k2, int *ipiv, int *incx); +void BLAS_FUNC(dlasy2)(int *ltranl, int *ltranr, int *isgn, int *n1, int *n2, double *tl, int *ldtl, double *tr, int *ldtr, double *b, int *ldb, double *scale, double *x, int *ldx, double *xnorm, int *info); +void BLAS_FUNC(dlasyf)(char *uplo, int *n, int *nb, int *kb, double *a, int *lda, int *ipiv, double *w, int *ldw, int *info); +void BLAS_FUNC(dlat2s)(char *uplo, int *n, double *a, int *lda, float *sa, int *ldsa, int *info); +void BLAS_FUNC(dlatbs)(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, double *ab, int *ldab, double *x, double *scale, double *cnorm, int *info); +void BLAS_FUNC(dlatdf)(int *ijob, int *n, double *z, int *ldz, double *rhs, double *rdsum, double *rdscal, int *ipiv, int *jpiv); +void BLAS_FUNC(dlatps)(char *uplo, char *trans, char *diag, char *normin, int *n, double *ap, double *x, double *scale, double *cnorm, int *info); +void BLAS_FUNC(dlatrd)(char *uplo, int *n, int *nb, double *a, int *lda, double *e, double *tau, double *w, int *ldw); +void BLAS_FUNC(dlatrs)(char *uplo, char *trans, char *diag, char *normin, int *n, double *a, int *lda, double *x, double *scale, double *cnorm, int *info); +void BLAS_FUNC(dlatrz)(int *m, int *n, int *l, double *a, int *lda, double *tau, double *work); +void BLAS_FUNC(dlauu2)(char *uplo, int *n, double *a, int *lda, int *info); +void BLAS_FUNC(dlauum)(char *uplo, int *n, double *a, int *lda, int *info); +void BLAS_FUNC(dopgtr)(char *uplo, int *n, double *ap, double *tau, double *q, int *ldq, double *work, int *info); +void BLAS_FUNC(dopmtr)(char *side, char *uplo, char *trans, int *m, int *n, double *ap, double *tau, double *c, int *ldc, double *work, int *info); +void BLAS_FUNC(dorbdb)(char *trans, char *signs, int *m, int *p, int *q, double *x11, int *ldx11, double *x12, int *ldx12, double *x21, int *ldx21, double *x22, int *ldx22, double *theta, double *phi, double *taup1, double *taup2, double *tauq1, double *tauq2, double *work, int *lwork, int *info); +void BLAS_FUNC(dorcsd)(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, double *x11, int *ldx11, double *x12, int *ldx12, double *x21, int *ldx21, double *x22, int *ldx22, double *theta, double *u1, int *ldu1, double *u2, int *ldu2, double *v1t, int *ldv1t, double *v2t, int *ldv2t, double *work, int *lwork, int *iwork, int *info); +void BLAS_FUNC(dorg2l)(int *m, int *n, int *k, double *a, int *lda, double *tau, double *work, int *info); +void BLAS_FUNC(dorg2r)(int *m, int *n, int *k, double *a, int *lda, double *tau, double *work, int *info); +void BLAS_FUNC(dorgbr)(char *vect, int *m, int *n, int *k, double *a, int *lda, double *tau, double *work, int *lwork, int *info); +void BLAS_FUNC(dorghr)(int *n, int *ilo, int *ihi, double *a, int *lda, double *tau, double *work, int *lwork, int *info); +void BLAS_FUNC(dorgl2)(int *m, int *n, int *k, double *a, int *lda, double *tau, double *work, int *info); +void BLAS_FUNC(dorglq)(int *m, int *n, int *k, double *a, int *lda, double *tau, double *work, int *lwork, int *info); +void BLAS_FUNC(dorgql)(int *m, int *n, int *k, double *a, int *lda, double *tau, double *work, int *lwork, int *info); +void BLAS_FUNC(dorgqr)(int *m, int *n, int *k, double *a, int *lda, double *tau, double *work, int *lwork, int *info); +void BLAS_FUNC(dorgr2)(int *m, int *n, int *k, double *a, int *lda, double *tau, double *work, int *info); +void BLAS_FUNC(dorgrq)(int *m, int *n, int *k, double *a, int *lda, double *tau, double *work, int *lwork, int *info); +void BLAS_FUNC(dorgtr)(char *uplo, int *n, double *a, int *lda, double *tau, double *work, int *lwork, int *info); +void BLAS_FUNC(dorm2l)(char *side, char *trans, int *m, int *n, int *k, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *info); +void BLAS_FUNC(dorm2r)(char *side, char *trans, int *m, int *n, int *k, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *info); +void BLAS_FUNC(dormbr)(char *vect, char *side, char *trans, int *m, int *n, int *k, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *lwork, int *info); +void BLAS_FUNC(dormhr)(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *lwork, int *info); +void BLAS_FUNC(dorml2)(char *side, char *trans, int *m, int *n, int *k, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *info); +void BLAS_FUNC(dormlq)(char *side, char *trans, int *m, int *n, int *k, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *lwork, int *info); +void BLAS_FUNC(dormql)(char *side, char *trans, int *m, int *n, int *k, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *lwork, int *info); +void BLAS_FUNC(dormqr)(char *side, char *trans, int *m, int *n, int *k, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *lwork, int *info); +void BLAS_FUNC(dormr2)(char *side, char *trans, int *m, int *n, int *k, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *info); +void BLAS_FUNC(dormr3)(char *side, char *trans, int *m, int *n, int *k, int *l, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *info); +void BLAS_FUNC(dormrq)(char *side, char *trans, int *m, int *n, int *k, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *lwork, int *info); +void BLAS_FUNC(dormrz)(char *side, char *trans, int *m, int *n, int *k, int *l, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *lwork, int *info); +void BLAS_FUNC(dormtr)(char *side, char *uplo, char *trans, int *m, int *n, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *lwork, int *info); +void BLAS_FUNC(dpbcon)(char *uplo, int *n, int *kd, double *ab, int *ldab, double *anorm, double *rcond, double *work, int *iwork, int *info); +void BLAS_FUNC(dpbequ)(char *uplo, int *n, int *kd, double *ab, int *ldab, double *s, double *scond, double *amax, int *info); +void BLAS_FUNC(dpbrfs)(char *uplo, int *n, int *kd, int *nrhs, double *ab, int *ldab, double *afb, int *ldafb, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info); +void BLAS_FUNC(dpbstf)(char *uplo, int *n, int *kd, double *ab, int *ldab, int *info); +void BLAS_FUNC(dpbsv)(char *uplo, int *n, int *kd, int *nrhs, double *ab, int *ldab, double *b, int *ldb, int *info); +void BLAS_FUNC(dpbsvx)(char *fact, char *uplo, int *n, int *kd, int *nrhs, double *ab, int *ldab, double *afb, int *ldafb, char *equed, double *s, double *b, int *ldb, double *x, int *ldx, double *rcond, double *ferr, double *berr, double *work, int *iwork, int *info); +void BLAS_FUNC(dpbtf2)(char *uplo, int *n, int *kd, double *ab, int *ldab, int *info); +void BLAS_FUNC(dpbtrf)(char *uplo, int *n, int *kd, double *ab, int *ldab, int *info); +void BLAS_FUNC(dpbtrs)(char *uplo, int *n, int *kd, int *nrhs, double *ab, int *ldab, double *b, int *ldb, int *info); +void BLAS_FUNC(dpftrf)(char *transr, char *uplo, int *n, double *a, int *info); +void BLAS_FUNC(dpftri)(char *transr, char *uplo, int *n, double *a, int *info); +void BLAS_FUNC(dpftrs)(char *transr, char *uplo, int *n, int *nrhs, double *a, double *b, int *ldb, int *info); +void BLAS_FUNC(dpocon)(char *uplo, int *n, double *a, int *lda, double *anorm, double *rcond, double *work, int *iwork, int *info); +void BLAS_FUNC(dpoequ)(int *n, double *a, int *lda, double *s, double *scond, double *amax, int *info); +void BLAS_FUNC(dpoequb)(int *n, double *a, int *lda, double *s, double *scond, double *amax, int *info); +void BLAS_FUNC(dporfs)(char *uplo, int *n, int *nrhs, double *a, int *lda, double *af, int *ldaf, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info); +void BLAS_FUNC(dposv)(char *uplo, int *n, int *nrhs, double *a, int *lda, double *b, int *ldb, int *info); +void BLAS_FUNC(dposvx)(char *fact, char *uplo, int *n, int *nrhs, double *a, int *lda, double *af, int *ldaf, char *equed, double *s, double *b, int *ldb, double *x, int *ldx, double *rcond, double *ferr, double *berr, double *work, int *iwork, int *info); +void BLAS_FUNC(dpotf2)(char *uplo, int *n, double *a, int *lda, int *info); +void BLAS_FUNC(dpotrf)(char *uplo, int *n, double *a, int *lda, int *info); +void BLAS_FUNC(dpotri)(char *uplo, int *n, double *a, int *lda, int *info); +void BLAS_FUNC(dpotrs)(char *uplo, int *n, int *nrhs, double *a, int *lda, double *b, int *ldb, int *info); +void BLAS_FUNC(dppcon)(char *uplo, int *n, double *ap, double *anorm, double *rcond, double *work, int *iwork, int *info); +void BLAS_FUNC(dppequ)(char *uplo, int *n, double *ap, double *s, double *scond, double *amax, int *info); +void BLAS_FUNC(dpprfs)(char *uplo, int *n, int *nrhs, double *ap, double *afp, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info); +void BLAS_FUNC(dppsv)(char *uplo, int *n, int *nrhs, double *ap, double *b, int *ldb, int *info); +void BLAS_FUNC(dppsvx)(char *fact, char *uplo, int *n, int *nrhs, double *ap, double *afp, char *equed, double *s, double *b, int *ldb, double *x, int *ldx, double *rcond, double *ferr, double *berr, double *work, int *iwork, int *info); +void BLAS_FUNC(dpptrf)(char *uplo, int *n, double *ap, int *info); +void BLAS_FUNC(dpptri)(char *uplo, int *n, double *ap, int *info); +void BLAS_FUNC(dpptrs)(char *uplo, int *n, int *nrhs, double *ap, double *b, int *ldb, int *info); +void BLAS_FUNC(dpstf2)(char *uplo, int *n, double *a, int *lda, int *piv, int *rank, double *tol, double *work, int *info); +void BLAS_FUNC(dpstrf)(char *uplo, int *n, double *a, int *lda, int *piv, int *rank, double *tol, double *work, int *info); +void BLAS_FUNC(dptcon)(int *n, double *d, double *e, double *anorm, double *rcond, double *work, int *info); +void BLAS_FUNC(dpteqr)(char *compz, int *n, double *d, double *e, double *z, int *ldz, double *work, int *info); +void BLAS_FUNC(dptrfs)(int *n, int *nrhs, double *d, double *e, double *df, double *ef, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *info); +void BLAS_FUNC(dptsv)(int *n, int *nrhs, double *d, double *e, double *b, int *ldb, int *info); +void BLAS_FUNC(dptsvx)(char *fact, int *n, int *nrhs, double *d, double *e, double *df, double *ef, double *b, int *ldb, double *x, int *ldx, double *rcond, double *ferr, double *berr, double *work, int *info); +void BLAS_FUNC(dpttrf)(int *n, double *d, double *e, int *info); +void BLAS_FUNC(dpttrs)(int *n, int *nrhs, double *d, double *e, double *b, int *ldb, int *info); +void BLAS_FUNC(dptts2)(int *n, int *nrhs, double *d, double *e, double *b, int *ldb); +void BLAS_FUNC(drscl)(int *n, double *sa, double *sx, int *incx); +void BLAS_FUNC(dsbev)(char *jobz, char *uplo, int *n, int *kd, double *ab, int *ldab, double *w, double *z, int *ldz, double *work, int *info); +void BLAS_FUNC(dsbevd)(char *jobz, char *uplo, int *n, int *kd, double *ab, int *ldab, double *w, double *z, int *ldz, double *work, int *lwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(dsbevx)(char *jobz, char *range, char *uplo, int *n, int *kd, double *ab, int *ldab, double *q, int *ldq, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, double *z, int *ldz, double *work, int *iwork, int *ifail, int *info); +void BLAS_FUNC(dsbgst)(char *vect, char *uplo, int *n, int *ka, int *kb, double *ab, int *ldab, double *bb, int *ldbb, double *x, int *ldx, double *work, int *info); +void BLAS_FUNC(dsbgv)(char *jobz, char *uplo, int *n, int *ka, int *kb, double *ab, int *ldab, double *bb, int *ldbb, double *w, double *z, int *ldz, double *work, int *info); +void BLAS_FUNC(dsbgvd)(char *jobz, char *uplo, int *n, int *ka, int *kb, double *ab, int *ldab, double *bb, int *ldbb, double *w, double *z, int *ldz, double *work, int *lwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(dsbgvx)(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, double *ab, int *ldab, double *bb, int *ldbb, double *q, int *ldq, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, double *z, int *ldz, double *work, int *iwork, int *ifail, int *info); +void BLAS_FUNC(dsbtrd)(char *vect, char *uplo, int *n, int *kd, double *ab, int *ldab, double *d, double *e, double *q, int *ldq, double *work, int *info); +void BLAS_FUNC(dsfrk)(char *transr, char *uplo, char *trans, int *n, int *k, double *alpha, double *a, int *lda, double *beta, double *c); +void BLAS_FUNC(dsgesv)(int *n, int *nrhs, double *a, int *lda, int *ipiv, double *b, int *ldb, double *x, int *ldx, double *work, float *swork, int *iter, int *info); +void BLAS_FUNC(dspcon)(char *uplo, int *n, double *ap, int *ipiv, double *anorm, double *rcond, double *work, int *iwork, int *info); +void BLAS_FUNC(dspev)(char *jobz, char *uplo, int *n, double *ap, double *w, double *z, int *ldz, double *work, int *info); +void BLAS_FUNC(dspevd)(char *jobz, char *uplo, int *n, double *ap, double *w, double *z, int *ldz, double *work, int *lwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(dspevx)(char *jobz, char *range, char *uplo, int *n, double *ap, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, double *z, int *ldz, double *work, int *iwork, int *ifail, int *info); +void BLAS_FUNC(dspgst)(int *itype, char *uplo, int *n, double *ap, double *bp, int *info); +void BLAS_FUNC(dspgv)(int *itype, char *jobz, char *uplo, int *n, double *ap, double *bp, double *w, double *z, int *ldz, double *work, int *info); +void BLAS_FUNC(dspgvd)(int *itype, char *jobz, char *uplo, int *n, double *ap, double *bp, double *w, double *z, int *ldz, double *work, int *lwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(dspgvx)(int *itype, char *jobz, char *range, char *uplo, int *n, double *ap, double *bp, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, double *z, int *ldz, double *work, int *iwork, int *ifail, int *info); +void BLAS_FUNC(dsposv)(char *uplo, int *n, int *nrhs, double *a, int *lda, double *b, int *ldb, double *x, int *ldx, double *work, float *swork, int *iter, int *info); +void BLAS_FUNC(dsprfs)(char *uplo, int *n, int *nrhs, double *ap, double *afp, int *ipiv, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info); +void BLAS_FUNC(dspsv)(char *uplo, int *n, int *nrhs, double *ap, int *ipiv, double *b, int *ldb, int *info); +void BLAS_FUNC(dspsvx)(char *fact, char *uplo, int *n, int *nrhs, double *ap, double *afp, int *ipiv, double *b, int *ldb, double *x, int *ldx, double *rcond, double *ferr, double *berr, double *work, int *iwork, int *info); +void BLAS_FUNC(dsptrd)(char *uplo, int *n, double *ap, double *d, double *e, double *tau, int *info); +void BLAS_FUNC(dsptrf)(char *uplo, int *n, double *ap, int *ipiv, int *info); +void BLAS_FUNC(dsptri)(char *uplo, int *n, double *ap, int *ipiv, double *work, int *info); +void BLAS_FUNC(dsptrs)(char *uplo, int *n, int *nrhs, double *ap, int *ipiv, double *b, int *ldb, int *info); +void BLAS_FUNC(dstebz)(char *range, char *order, int *n, double *vl, double *vu, int *il, int *iu, double *abstol, double *d, double *e, int *m, int *nsplit, double *w, int *iblock, int *isplit, double *work, int *iwork, int *info); +void BLAS_FUNC(dstedc)(char *compz, int *n, double *d, double *e, double *z, int *ldz, double *work, int *lwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(dstegr)(char *jobz, char *range, int *n, double *d, double *e, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, double *z, int *ldz, int *isuppz, double *work, int *lwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(dstein)(int *n, double *d, double *e, int *m, double *w, int *iblock, int *isplit, double *z, int *ldz, double *work, int *iwork, int *ifail, int *info); +void BLAS_FUNC(dstemr)(char *jobz, char *range, int *n, double *d, double *e, double *vl, double *vu, int *il, int *iu, int *m, double *w, double *z, int *ldz, int *nzc, int *isuppz, int *tryrac, double *work, int *lwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(dsteqr)(char *compz, int *n, double *d, double *e, double *z, int *ldz, double *work, int *info); +void BLAS_FUNC(dsterf)(int *n, double *d, double *e, int *info); +void BLAS_FUNC(dstev)(char *jobz, int *n, double *d, double *e, double *z, int *ldz, double *work, int *info); +void BLAS_FUNC(dstevd)(char *jobz, int *n, double *d, double *e, double *z, int *ldz, double *work, int *lwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(dstevr)(char *jobz, char *range, int *n, double *d, double *e, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, double *z, int *ldz, int *isuppz, double *work, int *lwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(dstevx)(char *jobz, char *range, int *n, double *d, double *e, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, double *z, int *ldz, double *work, int *iwork, int *ifail, int *info); +void BLAS_FUNC(dsycon)(char *uplo, int *n, double *a, int *lda, int *ipiv, double *anorm, double *rcond, double *work, int *iwork, int *info); +void BLAS_FUNC(dsyconv)(char *uplo, char *way, int *n, double *a, int *lda, int *ipiv, double *work, int *info); +void BLAS_FUNC(dsyequb)(char *uplo, int *n, double *a, int *lda, double *s, double *scond, double *amax, double *work, int *info); +void BLAS_FUNC(dsyev)(char *jobz, char *uplo, int *n, double *a, int *lda, double *w, double *work, int *lwork, int *info); +void BLAS_FUNC(dsyevd)(char *jobz, char *uplo, int *n, double *a, int *lda, double *w, double *work, int *lwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(dsyevr)(char *jobz, char *range, char *uplo, int *n, double *a, int *lda, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, double *z, int *ldz, int *isuppz, double *work, int *lwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(dsyevx)(char *jobz, char *range, char *uplo, int *n, double *a, int *lda, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, double *z, int *ldz, double *work, int *lwork, int *iwork, int *ifail, int *info); +void BLAS_FUNC(dsygs2)(int *itype, char *uplo, int *n, double *a, int *lda, double *b, int *ldb, int *info); +void BLAS_FUNC(dsygst)(int *itype, char *uplo, int *n, double *a, int *lda, double *b, int *ldb, int *info); +void BLAS_FUNC(dsygv)(int *itype, char *jobz, char *uplo, int *n, double *a, int *lda, double *b, int *ldb, double *w, double *work, int *lwork, int *info); +void BLAS_FUNC(dsygvd)(int *itype, char *jobz, char *uplo, int *n, double *a, int *lda, double *b, int *ldb, double *w, double *work, int *lwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(dsygvx)(int *itype, char *jobz, char *range, char *uplo, int *n, double *a, int *lda, double *b, int *ldb, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, double *z, int *ldz, double *work, int *lwork, int *iwork, int *ifail, int *info); +void BLAS_FUNC(dsyrfs)(char *uplo, int *n, int *nrhs, double *a, int *lda, double *af, int *ldaf, int *ipiv, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info); +void BLAS_FUNC(dsysv)(char *uplo, int *n, int *nrhs, double *a, int *lda, int *ipiv, double *b, int *ldb, double *work, int *lwork, int *info); +void BLAS_FUNC(dsysvx)(char *fact, char *uplo, int *n, int *nrhs, double *a, int *lda, double *af, int *ldaf, int *ipiv, double *b, int *ldb, double *x, int *ldx, double *rcond, double *ferr, double *berr, double *work, int *lwork, int *iwork, int *info); +void BLAS_FUNC(dsyswapr)(char *uplo, int *n, double *a, int *lda, int *i1, int *i2); +void BLAS_FUNC(dsytd2)(char *uplo, int *n, double *a, int *lda, double *d, double *e, double *tau, int *info); +void BLAS_FUNC(dsytf2)(char *uplo, int *n, double *a, int *lda, int *ipiv, int *info); +void BLAS_FUNC(dsytrd)(char *uplo, int *n, double *a, int *lda, double *d, double *e, double *tau, double *work, int *lwork, int *info); +void BLAS_FUNC(dsytrf)(char *uplo, int *n, double *a, int *lda, int *ipiv, double *work, int *lwork, int *info); +void BLAS_FUNC(dsytri)(char *uplo, int *n, double *a, int *lda, int *ipiv, double *work, int *info); +void BLAS_FUNC(dsytri2)(char *uplo, int *n, double *a, int *lda, int *ipiv, double *work, int *lwork, int *info); +void BLAS_FUNC(dsytri2x)(char *uplo, int *n, double *a, int *lda, int *ipiv, double *work, int *nb, int *info); +void BLAS_FUNC(dsytrs)(char *uplo, int *n, int *nrhs, double *a, int *lda, int *ipiv, double *b, int *ldb, int *info); +void BLAS_FUNC(dsytrs2)(char *uplo, int *n, int *nrhs, double *a, int *lda, int *ipiv, double *b, int *ldb, double *work, int *info); +void BLAS_FUNC(dtbcon)(char *norm, char *uplo, char *diag, int *n, int *kd, double *ab, int *ldab, double *rcond, double *work, int *iwork, int *info); +void BLAS_FUNC(dtbrfs)(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, double *ab, int *ldab, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info); +void BLAS_FUNC(dtbtrs)(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, double *ab, int *ldab, double *b, int *ldb, int *info); +void BLAS_FUNC(dtfsm)(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, double *alpha, double *a, double *b, int *ldb); +void BLAS_FUNC(dtftri)(char *transr, char *uplo, char *diag, int *n, double *a, int *info); +void BLAS_FUNC(dtfttp)(char *transr, char *uplo, int *n, double *arf, double *ap, int *info); +void BLAS_FUNC(dtfttr)(char *transr, char *uplo, int *n, double *arf, double *a, int *lda, int *info); +void BLAS_FUNC(dtgevc)(char *side, char *howmny, int *select, int *n, double *s, int *lds, double *p, int *ldp, double *vl, int *ldvl, double *vr, int *ldvr, int *mm, int *m, double *work, int *info); +void BLAS_FUNC(dtgex2)(int *wantq, int *wantz, int *n, double *a, int *lda, double *b, int *ldb, double *q, int *ldq, double *z, int *ldz, int *j1, int *n1, int *n2, double *work, int *lwork, int *info); +void BLAS_FUNC(dtgexc)(int *wantq, int *wantz, int *n, double *a, int *lda, double *b, int *ldb, double *q, int *ldq, double *z, int *ldz, int *ifst, int *ilst, double *work, int *lwork, int *info); +void BLAS_FUNC(dtgsen)(int *ijob, int *wantq, int *wantz, int *select, int *n, double *a, int *lda, double *b, int *ldb, double *alphar, double *alphai, double *beta, double *q, int *ldq, double *z, int *ldz, int *m, double *pl, double *pr, double *dif, double *work, int *lwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(dtgsja)(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, double *a, int *lda, double *b, int *ldb, double *tola, double *tolb, double *alpha, double *beta, double *u, int *ldu, double *v, int *ldv, double *q, int *ldq, double *work, int *ncycle, int *info); +void BLAS_FUNC(dtgsna)(char *job, char *howmny, int *select, int *n, double *a, int *lda, double *b, int *ldb, double *vl, int *ldvl, double *vr, int *ldvr, double *s, double *dif, int *mm, int *m, double *work, int *lwork, int *iwork, int *info); +void BLAS_FUNC(dtgsy2)(char *trans, int *ijob, int *m, int *n, double *a, int *lda, double *b, int *ldb, double *c, int *ldc, double *d, int *ldd, double *e, int *lde, double *f, int *ldf, double *scale, double *rdsum, double *rdscal, int *iwork, int *pq, int *info); +void BLAS_FUNC(dtgsyl)(char *trans, int *ijob, int *m, int *n, double *a, int *lda, double *b, int *ldb, double *c, int *ldc, double *d, int *ldd, double *e, int *lde, double *f, int *ldf, double *scale, double *dif, double *work, int *lwork, int *iwork, int *info); +void BLAS_FUNC(dtpcon)(char *norm, char *uplo, char *diag, int *n, double *ap, double *rcond, double *work, int *iwork, int *info); +void BLAS_FUNC(dtpmqrt)(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, double *v, int *ldv, double *t, int *ldt, double *a, int *lda, double *b, int *ldb, double *work, int *info); +void BLAS_FUNC(dtpqrt)(int *m, int *n, int *l, int *nb, double *a, int *lda, double *b, int *ldb, double *t, int *ldt, double *work, int *info); +void BLAS_FUNC(dtpqrt2)(int *m, int *n, int *l, double *a, int *lda, double *b, int *ldb, double *t, int *ldt, int *info); +void BLAS_FUNC(dtprfb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, double *v, int *ldv, double *t, int *ldt, double *a, int *lda, double *b, int *ldb, double *work, int *ldwork); +void BLAS_FUNC(dtprfs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, double *ap, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info); +void BLAS_FUNC(dtptri)(char *uplo, char *diag, int *n, double *ap, int *info); +void BLAS_FUNC(dtptrs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, double *ap, double *b, int *ldb, int *info); +void BLAS_FUNC(dtpttf)(char *transr, char *uplo, int *n, double *ap, double *arf, int *info); +void BLAS_FUNC(dtpttr)(char *uplo, int *n, double *ap, double *a, int *lda, int *info); +void BLAS_FUNC(dtrcon)(char *norm, char *uplo, char *diag, int *n, double *a, int *lda, double *rcond, double *work, int *iwork, int *info); +void BLAS_FUNC(dtrevc)(char *side, char *howmny, int *select, int *n, double *t, int *ldt, double *vl, int *ldvl, double *vr, int *ldvr, int *mm, int *m, double *work, int *info); +void BLAS_FUNC(dtrexc)(char *compq, int *n, double *t, int *ldt, double *q, int *ldq, int *ifst, int *ilst, double *work, int *info); +void BLAS_FUNC(dtrrfs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, double *a, int *lda, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info); +void BLAS_FUNC(dtrsen)(char *job, char *compq, int *select, int *n, double *t, int *ldt, double *q, int *ldq, double *wr, double *wi, int *m, double *s, double *sep, double *work, int *lwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(dtrsna)(char *job, char *howmny, int *select, int *n, double *t, int *ldt, double *vl, int *ldvl, double *vr, int *ldvr, double *s, double *sep, int *mm, int *m, double *work, int *ldwork, int *iwork, int *info); +void BLAS_FUNC(dtrsyl)(char *trana, char *tranb, int *isgn, int *m, int *n, double *a, int *lda, double *b, int *ldb, double *c, int *ldc, double *scale, int *info); +void BLAS_FUNC(dtrti2)(char *uplo, char *diag, int *n, double *a, int *lda, int *info); +void BLAS_FUNC(dtrtri)(char *uplo, char *diag, int *n, double *a, int *lda, int *info); +void BLAS_FUNC(dtrtrs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, double *a, int *lda, double *b, int *ldb, int *info); +void BLAS_FUNC(dtrttf)(char *transr, char *uplo, int *n, double *a, int *lda, double *arf, int *info); +void BLAS_FUNC(dtrttp)(char *uplo, int *n, double *a, int *lda, double *ap, int *info); +void BLAS_FUNC(dtzrzf)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *lwork, int *info); +double BLAS_FUNC(dzsum1)(int *n, npy_complex128 *cx, int *incx); +int BLAS_FUNC(icmax1)(int *n, npy_complex64 *cx, int *incx); +int BLAS_FUNC(ieeeck)(int *ispec, float *zero, float *one); +int BLAS_FUNC(ilaclc)(int *m, int *n, npy_complex64 *a, int *lda); +int BLAS_FUNC(ilaclr)(int *m, int *n, npy_complex64 *a, int *lda); +int BLAS_FUNC(iladiag)(char *diag); +int BLAS_FUNC(iladlc)(int *m, int *n, double *a, int *lda); +int BLAS_FUNC(iladlr)(int *m, int *n, double *a, int *lda); +int BLAS_FUNC(ilaprec)(char *prec); +int BLAS_FUNC(ilaslc)(int *m, int *n, float *a, int *lda); +int BLAS_FUNC(ilaslr)(int *m, int *n, float *a, int *lda); +int BLAS_FUNC(ilatrans)(char *trans); +int BLAS_FUNC(ilauplo)(char *uplo); +void BLAS_FUNC(ilaver)(int *vers_major, int *vers_minor, int *vers_patch); +int BLAS_FUNC(ilazlc)(int *m, int *n, npy_complex128 *a, int *lda); +int BLAS_FUNC(ilazlr)(int *m, int *n, npy_complex128 *a, int *lda); +int BLAS_FUNC(izmax1)(int *n, npy_complex128 *cx, int *incx); +void BLAS_FUNC(sbbcsd)(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, float *theta, float *phi, float *u1, int *ldu1, float *u2, int *ldu2, float *v1t, int *ldv1t, float *v2t, int *ldv2t, float *b11d, float *b11e, float *b12d, float *b12e, float *b21d, float *b21e, float *b22d, float *b22e, float *work, int *lwork, int *info); +void BLAS_FUNC(sbdsdc)(char *uplo, char *compq, int *n, float *d, float *e, float *u, int *ldu, float *vt, int *ldvt, float *q, int *iq, float *work, int *iwork, int *info); +void BLAS_FUNC(sbdsqr)(char *uplo, int *n, int *ncvt, int *nru, int *ncc, float *d, float *e, float *vt, int *ldvt, float *u, int *ldu, float *c, int *ldc, float *work, int *info); +float BLAS_FUNC(scsum1)(int *n, npy_complex64 *cx, int *incx); +void BLAS_FUNC(sdisna)(char *job, int *m, int *n, float *d, float *sep, int *info); +void BLAS_FUNC(sgbbrd)(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, float *ab, int *ldab, float *d, float *e, float *q, int *ldq, float *pt, int *ldpt, float *c, int *ldc, float *work, int *info); +void BLAS_FUNC(sgbcon)(char *norm, int *n, int *kl, int *ku, float *ab, int *ldab, int *ipiv, float *anorm, float *rcond, float *work, int *iwork, int *info); +void BLAS_FUNC(sgbequ)(int *m, int *n, int *kl, int *ku, float *ab, int *ldab, float *r, float *c, float *rowcnd, float *colcnd, float *amax, int *info); +void BLAS_FUNC(sgbequb)(int *m, int *n, int *kl, int *ku, float *ab, int *ldab, float *r, float *c, float *rowcnd, float *colcnd, float *amax, int *info); +void BLAS_FUNC(sgbrfs)(char *trans, int *n, int *kl, int *ku, int *nrhs, float *ab, int *ldab, float *afb, int *ldafb, int *ipiv, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info); +void BLAS_FUNC(sgbsv)(int *n, int *kl, int *ku, int *nrhs, float *ab, int *ldab, int *ipiv, float *b, int *ldb, int *info); +void BLAS_FUNC(sgbsvx)(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, float *ab, int *ldab, float *afb, int *ldafb, int *ipiv, char *equed, float *r, float *c, float *b, int *ldb, float *x, int *ldx, float *rcond, float *ferr, float *berr, float *work, int *iwork, int *info); +void BLAS_FUNC(sgbtf2)(int *m, int *n, int *kl, int *ku, float *ab, int *ldab, int *ipiv, int *info); +void BLAS_FUNC(sgbtrf)(int *m, int *n, int *kl, int *ku, float *ab, int *ldab, int *ipiv, int *info); +void BLAS_FUNC(sgbtrs)(char *trans, int *n, int *kl, int *ku, int *nrhs, float *ab, int *ldab, int *ipiv, float *b, int *ldb, int *info); +void BLAS_FUNC(sgebak)(char *job, char *side, int *n, int *ilo, int *ihi, float *scale, int *m, float *v, int *ldv, int *info); +void BLAS_FUNC(sgebal)(char *job, int *n, float *a, int *lda, int *ilo, int *ihi, float *scale, int *info); +void BLAS_FUNC(sgebd2)(int *m, int *n, float *a, int *lda, float *d, float *e, float *tauq, float *taup, float *work, int *info); +void BLAS_FUNC(sgebrd)(int *m, int *n, float *a, int *lda, float *d, float *e, float *tauq, float *taup, float *work, int *lwork, int *info); +void BLAS_FUNC(sgecon)(char *norm, int *n, float *a, int *lda, float *anorm, float *rcond, float *work, int *iwork, int *info); +void BLAS_FUNC(sgeequ)(int *m, int *n, float *a, int *lda, float *r, float *c, float *rowcnd, float *colcnd, float *amax, int *info); +void BLAS_FUNC(sgeequb)(int *m, int *n, float *a, int *lda, float *r, float *c, float *rowcnd, float *colcnd, float *amax, int *info); +void BLAS_FUNC(sgees)(char *jobvs, char *sort, _sselect2 *select, int *n, float *a, int *lda, int *sdim, float *wr, float *wi, float *vs, int *ldvs, float *work, int *lwork, int *bwork, int *info); +void BLAS_FUNC(sgeesx)(char *jobvs, char *sort, _sselect2 *select, char *sense, int *n, float *a, int *lda, int *sdim, float *wr, float *wi, float *vs, int *ldvs, float *rconde, float *rcondv, float *work, int *lwork, int *iwork, int *liwork, int *bwork, int *info); +void BLAS_FUNC(sgeev)(char *jobvl, char *jobvr, int *n, float *a, int *lda, float *wr, float *wi, float *vl, int *ldvl, float *vr, int *ldvr, float *work, int *lwork, int *info); +void BLAS_FUNC(sgeevx)(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, float *a, int *lda, float *wr, float *wi, float *vl, int *ldvl, float *vr, int *ldvr, int *ilo, int *ihi, float *scale, float *abnrm, float *rconde, float *rcondv, float *work, int *lwork, int *iwork, int *info); +void BLAS_FUNC(sgehd2)(int *n, int *ilo, int *ihi, float *a, int *lda, float *tau, float *work, int *info); +void BLAS_FUNC(sgehrd)(int *n, int *ilo, int *ihi, float *a, int *lda, float *tau, float *work, int *lwork, int *info); +void BLAS_FUNC(sgejsv)(char *joba, char *jobu, char *jobv, char *jobr, char *jobt, char *jobp, int *m, int *n, float *a, int *lda, float *sva, float *u, int *ldu, float *v, int *ldv, float *work, int *lwork, int *iwork, int *info); +void BLAS_FUNC(sgelq2)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *info); +void BLAS_FUNC(sgelqf)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *lwork, int *info); +void BLAS_FUNC(sgels)(char *trans, int *m, int *n, int *nrhs, float *a, int *lda, float *b, int *ldb, float *work, int *lwork, int *info); +void BLAS_FUNC(sgelsd)(int *m, int *n, int *nrhs, float *a, int *lda, float *b, int *ldb, float *s, float *rcond, int *rank, float *work, int *lwork, int *iwork, int *info); +void BLAS_FUNC(sgelss)(int *m, int *n, int *nrhs, float *a, int *lda, float *b, int *ldb, float *s, float *rcond, int *rank, float *work, int *lwork, int *info); +void BLAS_FUNC(sgelsy)(int *m, int *n, int *nrhs, float *a, int *lda, float *b, int *ldb, int *jpvt, float *rcond, int *rank, float *work, int *lwork, int *info); +void BLAS_FUNC(sgemqrt)(char *side, char *trans, int *m, int *n, int *k, int *nb, float *v, int *ldv, float *t, int *ldt, float *c, int *ldc, float *work, int *info); +void BLAS_FUNC(sgeql2)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *info); +void BLAS_FUNC(sgeqlf)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *lwork, int *info); +void BLAS_FUNC(sgeqp3)(int *m, int *n, float *a, int *lda, int *jpvt, float *tau, float *work, int *lwork, int *info); +void BLAS_FUNC(sgeqr2)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *info); +void BLAS_FUNC(sgeqr2p)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *info); +void BLAS_FUNC(sgeqrf)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *lwork, int *info); +void BLAS_FUNC(sgeqrfp)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *lwork, int *info); +void BLAS_FUNC(sgeqrt)(int *m, int *n, int *nb, float *a, int *lda, float *t, int *ldt, float *work, int *info); +void BLAS_FUNC(sgeqrt2)(int *m, int *n, float *a, int *lda, float *t, int *ldt, int *info); +void BLAS_FUNC(sgeqrt3)(int *m, int *n, float *a, int *lda, float *t, int *ldt, int *info); +void BLAS_FUNC(sgerfs)(char *trans, int *n, int *nrhs, float *a, int *lda, float *af, int *ldaf, int *ipiv, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info); +void BLAS_FUNC(sgerq2)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *info); +void BLAS_FUNC(sgerqf)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *lwork, int *info); +void BLAS_FUNC(sgesc2)(int *n, float *a, int *lda, float *rhs, int *ipiv, int *jpiv, float *scale); +void BLAS_FUNC(sgesdd)(char *jobz, int *m, int *n, float *a, int *lda, float *s, float *u, int *ldu, float *vt, int *ldvt, float *work, int *lwork, int *iwork, int *info); +void BLAS_FUNC(sgesv)(int *n, int *nrhs, float *a, int *lda, int *ipiv, float *b, int *ldb, int *info); +void BLAS_FUNC(sgesvd)(char *jobu, char *jobvt, int *m, int *n, float *a, int *lda, float *s, float *u, int *ldu, float *vt, int *ldvt, float *work, int *lwork, int *info); +void BLAS_FUNC(sgesvj)(char *joba, char *jobu, char *jobv, int *m, int *n, float *a, int *lda, float *sva, int *mv, float *v, int *ldv, float *work, int *lwork, int *info); +void BLAS_FUNC(sgesvx)(char *fact, char *trans, int *n, int *nrhs, float *a, int *lda, float *af, int *ldaf, int *ipiv, char *equed, float *r, float *c, float *b, int *ldb, float *x, int *ldx, float *rcond, float *ferr, float *berr, float *work, int *iwork, int *info); +void BLAS_FUNC(sgetc2)(int *n, float *a, int *lda, int *ipiv, int *jpiv, int *info); +void BLAS_FUNC(sgetf2)(int *m, int *n, float *a, int *lda, int *ipiv, int *info); +void BLAS_FUNC(sgetrf)(int *m, int *n, float *a, int *lda, int *ipiv, int *info); +void BLAS_FUNC(sgetri)(int *n, float *a, int *lda, int *ipiv, float *work, int *lwork, int *info); +void BLAS_FUNC(sgetrs)(char *trans, int *n, int *nrhs, float *a, int *lda, int *ipiv, float *b, int *ldb, int *info); +void BLAS_FUNC(sggbak)(char *job, char *side, int *n, int *ilo, int *ihi, float *lscale, float *rscale, int *m, float *v, int *ldv, int *info); +void BLAS_FUNC(sggbal)(char *job, int *n, float *a, int *lda, float *b, int *ldb, int *ilo, int *ihi, float *lscale, float *rscale, float *work, int *info); +void BLAS_FUNC(sgges)(char *jobvsl, char *jobvsr, char *sort, _sselect3 *selctg, int *n, float *a, int *lda, float *b, int *ldb, int *sdim, float *alphar, float *alphai, float *beta, float *vsl, int *ldvsl, float *vsr, int *ldvsr, float *work, int *lwork, int *bwork, int *info); +void BLAS_FUNC(sggesx)(char *jobvsl, char *jobvsr, char *sort, _sselect3 *selctg, char *sense, int *n, float *a, int *lda, float *b, int *ldb, int *sdim, float *alphar, float *alphai, float *beta, float *vsl, int *ldvsl, float *vsr, int *ldvsr, float *rconde, float *rcondv, float *work, int *lwork, int *iwork, int *liwork, int *bwork, int *info); +void BLAS_FUNC(sggev)(char *jobvl, char *jobvr, int *n, float *a, int *lda, float *b, int *ldb, float *alphar, float *alphai, float *beta, float *vl, int *ldvl, float *vr, int *ldvr, float *work, int *lwork, int *info); +void BLAS_FUNC(sggevx)(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, float *a, int *lda, float *b, int *ldb, float *alphar, float *alphai, float *beta, float *vl, int *ldvl, float *vr, int *ldvr, int *ilo, int *ihi, float *lscale, float *rscale, float *abnrm, float *bbnrm, float *rconde, float *rcondv, float *work, int *lwork, int *iwork, int *bwork, int *info); +void BLAS_FUNC(sggglm)(int *n, int *m, int *p, float *a, int *lda, float *b, int *ldb, float *d, float *x, float *y, float *work, int *lwork, int *info); +void BLAS_FUNC(sgghrd)(char *compq, char *compz, int *n, int *ilo, int *ihi, float *a, int *lda, float *b, int *ldb, float *q, int *ldq, float *z, int *ldz, int *info); +void BLAS_FUNC(sgglse)(int *m, int *n, int *p, float *a, int *lda, float *b, int *ldb, float *c, float *d, float *x, float *work, int *lwork, int *info); +void BLAS_FUNC(sggqrf)(int *n, int *m, int *p, float *a, int *lda, float *taua, float *b, int *ldb, float *taub, float *work, int *lwork, int *info); +void BLAS_FUNC(sggrqf)(int *m, int *p, int *n, float *a, int *lda, float *taua, float *b, int *ldb, float *taub, float *work, int *lwork, int *info); +void BLAS_FUNC(sgsvj0)(char *jobv, int *m, int *n, float *a, int *lda, float *d, float *sva, int *mv, float *v, int *ldv, float *eps, float *sfmin, float *tol, int *nsweep, float *work, int *lwork, int *info); +void BLAS_FUNC(sgsvj1)(char *jobv, int *m, int *n, int *n1, float *a, int *lda, float *d, float *sva, int *mv, float *v, int *ldv, float *eps, float *sfmin, float *tol, int *nsweep, float *work, int *lwork, int *info); +void BLAS_FUNC(sgtcon)(char *norm, int *n, float *dl, float *d, float *du, float *du2, int *ipiv, float *anorm, float *rcond, float *work, int *iwork, int *info); +void BLAS_FUNC(sgtrfs)(char *trans, int *n, int *nrhs, float *dl, float *d, float *du, float *dlf, float *df, float *duf, float *du2, int *ipiv, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info); +void BLAS_FUNC(sgtsv)(int *n, int *nrhs, float *dl, float *d, float *du, float *b, int *ldb, int *info); +void BLAS_FUNC(sgtsvx)(char *fact, char *trans, int *n, int *nrhs, float *dl, float *d, float *du, float *dlf, float *df, float *duf, float *du2, int *ipiv, float *b, int *ldb, float *x, int *ldx, float *rcond, float *ferr, float *berr, float *work, int *iwork, int *info); +void BLAS_FUNC(sgttrf)(int *n, float *dl, float *d, float *du, float *du2, int *ipiv, int *info); +void BLAS_FUNC(sgttrs)(char *trans, int *n, int *nrhs, float *dl, float *d, float *du, float *du2, int *ipiv, float *b, int *ldb, int *info); +void BLAS_FUNC(sgtts2)(int *itrans, int *n, int *nrhs, float *dl, float *d, float *du, float *du2, int *ipiv, float *b, int *ldb); +void BLAS_FUNC(shgeqz)(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, float *h, int *ldh, float *t, int *ldt, float *alphar, float *alphai, float *beta, float *q, int *ldq, float *z, int *ldz, float *work, int *lwork, int *info); +void BLAS_FUNC(shsein)(char *side, char *eigsrc, char *initv, int *select, int *n, float *h, int *ldh, float *wr, float *wi, float *vl, int *ldvl, float *vr, int *ldvr, int *mm, int *m, float *work, int *ifaill, int *ifailr, int *info); +void BLAS_FUNC(shseqr)(char *job, char *compz, int *n, int *ilo, int *ihi, float *h, int *ldh, float *wr, float *wi, float *z, int *ldz, float *work, int *lwork, int *info); +void BLAS_FUNC(slabad)(float *small, float *large); +void BLAS_FUNC(slabrd)(int *m, int *n, int *nb, float *a, int *lda, float *d, float *e, float *tauq, float *taup, float *x, int *ldx, float *y, int *ldy); +void BLAS_FUNC(slacn2)(int *n, float *v, float *x, int *isgn, float *est, int *kase, int *isave); +void BLAS_FUNC(slacon)(int *n, float *v, float *x, int *isgn, float *est, int *kase); +void BLAS_FUNC(slacpy)(char *uplo, int *m, int *n, float *a, int *lda, float *b, int *ldb); +void BLAS_FUNC(sladiv)(float *a, float *b, float *c, float *d, float *p, float *q); +void BLAS_FUNC(slae2)(float *a, float *b, float *c, float *rt1, float *rt2); +void BLAS_FUNC(slaebz)(int *ijob, int *nitmax, int *n, int *mmax, int *minp, int *nbmin, float *abstol, float *reltol, float *pivmin, float *d, float *e, float *e2, int *nval, float *ab, float *c, int *mout, int *nab, float *work, int *iwork, int *info); +void BLAS_FUNC(slaed0)(int *icompq, int *qsiz, int *n, float *d, float *e, float *q, int *ldq, float *qstore, int *ldqs, float *work, int *iwork, int *info); +void BLAS_FUNC(slaed1)(int *n, float *d, float *q, int *ldq, int *indxq, float *rho, int *cutpnt, float *work, int *iwork, int *info); +void BLAS_FUNC(slaed2)(int *k, int *n, int *n1, float *d, float *q, int *ldq, int *indxq, float *rho, float *z, float *dlamda, float *w, float *q2, int *indx, int *indxc, int *indxp, int *coltyp, int *info); +void BLAS_FUNC(slaed3)(int *k, int *n, int *n1, float *d, float *q, int *ldq, float *rho, float *dlamda, float *q2, int *indx, int *ctot, float *w, float *s, int *info); +void BLAS_FUNC(slaed4)(int *n, int *i, float *d, float *z, float *delta, float *rho, float *dlam, int *info); +void BLAS_FUNC(slaed5)(int *i, float *d, float *z, float *delta, float *rho, float *dlam); +void BLAS_FUNC(slaed6)(int *kniter, int *orgati, float *rho, float *d, float *z, float *finit, float *tau, int *info); +void BLAS_FUNC(slaed7)(int *icompq, int *n, int *qsiz, int *tlvls, int *curlvl, int *curpbm, float *d, float *q, int *ldq, int *indxq, float *rho, int *cutpnt, float *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, float *givnum, float *work, int *iwork, int *info); +void BLAS_FUNC(slaed8)(int *icompq, int *k, int *n, int *qsiz, float *d, float *q, int *ldq, int *indxq, float *rho, int *cutpnt, float *z, float *dlamda, float *q2, int *ldq2, float *w, int *perm, int *givptr, int *givcol, float *givnum, int *indxp, int *indx, int *info); +void BLAS_FUNC(slaed9)(int *k, int *kstart, int *kstop, int *n, float *d, float *q, int *ldq, float *rho, float *dlamda, float *w, float *s, int *lds, int *info); +void BLAS_FUNC(slaeda)(int *n, int *tlvls, int *curlvl, int *curpbm, int *prmptr, int *perm, int *givptr, int *givcol, float *givnum, float *q, int *qptr, float *z, float *ztemp, int *info); +void BLAS_FUNC(slaein)(int *rightv, int *noinit, int *n, float *h, int *ldh, float *wr, float *wi, float *vr, float *vi, float *b, int *ldb, float *work, float *eps3, float *smlnum, float *bignum, int *info); +void BLAS_FUNC(slaev2)(float *a, float *b, float *c, float *rt1, float *rt2, float *cs1, float *sn1); +void BLAS_FUNC(slaexc)(int *wantq, int *n, float *t, int *ldt, float *q, int *ldq, int *j1, int *n1, int *n2, float *work, int *info); +void BLAS_FUNC(slag2)(float *a, int *lda, float *b, int *ldb, float *safmin, float *scale1, float *scale2, float *wr1, float *wr2, float *wi); +void BLAS_FUNC(slag2d)(int *m, int *n, float *sa, int *ldsa, double *a, int *lda, int *info); +void BLAS_FUNC(slags2)(int *upper, float *a1, float *a2, float *a3, float *b1, float *b2, float *b3, float *csu, float *snu, float *csv, float *snv, float *csq, float *snq); +void BLAS_FUNC(slagtf)(int *n, float *a, float *lambda_, float *b, float *c, float *tol, float *d, int *in_, int *info); +void BLAS_FUNC(slagtm)(char *trans, int *n, int *nrhs, float *alpha, float *dl, float *d, float *du, float *x, int *ldx, float *beta, float *b, int *ldb); +void BLAS_FUNC(slagts)(int *job, int *n, float *a, float *b, float *c, float *d, int *in_, float *y, float *tol, int *info); +void BLAS_FUNC(slagv2)(float *a, int *lda, float *b, int *ldb, float *alphar, float *alphai, float *beta, float *csl, float *snl, float *csr, float *snr); +void BLAS_FUNC(slahqr)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, float *h, int *ldh, float *wr, float *wi, int *iloz, int *ihiz, float *z, int *ldz, int *info); +void BLAS_FUNC(slahr2)(int *n, int *k, int *nb, float *a, int *lda, float *tau, float *t, int *ldt, float *y, int *ldy); +void BLAS_FUNC(slaic1)(int *job, int *j, float *x, float *sest, float *w, float *gamma, float *sestpr, float *s, float *c); +void BLAS_FUNC(slaln2)(int *ltrans, int *na, int *nw, float *smin, float *ca, float *a, int *lda, float *d1, float *d2, float *b, int *ldb, float *wr, float *wi, float *x, int *ldx, float *scale, float *xnorm, int *info); +void BLAS_FUNC(slals0)(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, float *b, int *ldb, float *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, float *givnum, int *ldgnum, float *poles, float *difl, float *difr, float *z, int *k, float *c, float *s, float *work, int *info); +void BLAS_FUNC(slalsa)(int *icompq, int *smlsiz, int *n, int *nrhs, float *b, int *ldb, float *bx, int *ldbx, float *u, int *ldu, float *vt, int *k, float *difl, float *difr, float *z, float *poles, int *givptr, int *givcol, int *ldgcol, int *perm, float *givnum, float *c, float *s, float *work, int *iwork, int *info); +void BLAS_FUNC(slalsd)(char *uplo, int *smlsiz, int *n, int *nrhs, float *d, float *e, float *b, int *ldb, float *rcond, int *rank, float *work, int *iwork, int *info); +float BLAS_FUNC(slamch)(char *cmach); +void BLAS_FUNC(slamrg)(int *n1, int *n2, float *a, int *strd1, int *strd2, int *index_bn); +float BLAS_FUNC(slangb)(char *norm, int *n, int *kl, int *ku, float *ab, int *ldab, float *work); +float BLAS_FUNC(slange)(char *norm, int *m, int *n, float *a, int *lda, float *work); +float BLAS_FUNC(slangt)(char *norm, int *n, float *dl, float *d, float *du); +float BLAS_FUNC(slanhs)(char *norm, int *n, float *a, int *lda, float *work); +float BLAS_FUNC(slansb)(char *norm, char *uplo, int *n, int *k, float *ab, int *ldab, float *work); +float BLAS_FUNC(slansf)(char *norm, char *transr, char *uplo, int *n, float *a, float *work); +float BLAS_FUNC(slansp)(char *norm, char *uplo, int *n, float *ap, float *work); +float BLAS_FUNC(slanst)(char *norm, int *n, float *d, float *e); +float BLAS_FUNC(slansy)(char *norm, char *uplo, int *n, float *a, int *lda, float *work); +float BLAS_FUNC(slantb)(char *norm, char *uplo, char *diag, int *n, int *k, float *ab, int *ldab, float *work); +float BLAS_FUNC(slantp)(char *norm, char *uplo, char *diag, int *n, float *ap, float *work); +float BLAS_FUNC(slantr)(char *norm, char *uplo, char *diag, int *m, int *n, float *a, int *lda, float *work); +void BLAS_FUNC(slanv2)(float *a, float *b, float *c, float *d, float *rt1r, float *rt1i, float *rt2r, float *rt2i, float *cs, float *sn); +void BLAS_FUNC(slapll)(int *n, float *x, int *incx, float *y, int *incy, float *ssmin); +void BLAS_FUNC(slapmr)(int *forwrd, int *m, int *n, float *x, int *ldx, int *k); +void BLAS_FUNC(slapmt)(int *forwrd, int *m, int *n, float *x, int *ldx, int *k); +float BLAS_FUNC(slapy2)(float *x, float *y); +float BLAS_FUNC(slapy3)(float *x, float *y, float *z); +void BLAS_FUNC(slaqgb)(int *m, int *n, int *kl, int *ku, float *ab, int *ldab, float *r, float *c, float *rowcnd, float *colcnd, float *amax, char *equed); +void BLAS_FUNC(slaqge)(int *m, int *n, float *a, int *lda, float *r, float *c, float *rowcnd, float *colcnd, float *amax, char *equed); +void BLAS_FUNC(slaqp2)(int *m, int *n, int *offset, float *a, int *lda, int *jpvt, float *tau, float *vn1, float *vn2, float *work); +void BLAS_FUNC(slaqps)(int *m, int *n, int *offset, int *nb, int *kb, float *a, int *lda, int *jpvt, float *tau, float *vn1, float *vn2, float *auxv, float *f, int *ldf); +void BLAS_FUNC(slaqr0)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, float *h, int *ldh, float *wr, float *wi, int *iloz, int *ihiz, float *z, int *ldz, float *work, int *lwork, int *info); +void BLAS_FUNC(slaqr1)(int *n, float *h, int *ldh, float *sr1, float *si1, float *sr2, float *si2, float *v); +void BLAS_FUNC(slaqr2)(int *wantt, int *wantz, int *n, int *ktop, int *kbot, int *nw, float *h, int *ldh, int *iloz, int *ihiz, float *z, int *ldz, int *ns, int *nd, float *sr, float *si, float *v, int *ldv, int *nh, float *t, int *ldt, int *nv, float *wv, int *ldwv, float *work, int *lwork); +void BLAS_FUNC(slaqr3)(int *wantt, int *wantz, int *n, int *ktop, int *kbot, int *nw, float *h, int *ldh, int *iloz, int *ihiz, float *z, int *ldz, int *ns, int *nd, float *sr, float *si, float *v, int *ldv, int *nh, float *t, int *ldt, int *nv, float *wv, int *ldwv, float *work, int *lwork); +void BLAS_FUNC(slaqr4)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, float *h, int *ldh, float *wr, float *wi, int *iloz, int *ihiz, float *z, int *ldz, float *work, int *lwork, int *info); +void BLAS_FUNC(slaqr5)(int *wantt, int *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, float *sr, float *si, float *h, int *ldh, int *iloz, int *ihiz, float *z, int *ldz, float *v, int *ldv, float *u, int *ldu, int *nv, float *wv, int *ldwv, int *nh, float *wh, int *ldwh); +void BLAS_FUNC(slaqsb)(char *uplo, int *n, int *kd, float *ab, int *ldab, float *s, float *scond, float *amax, char *equed); +void BLAS_FUNC(slaqsp)(char *uplo, int *n, float *ap, float *s, float *scond, float *amax, char *equed); +void BLAS_FUNC(slaqsy)(char *uplo, int *n, float *a, int *lda, float *s, float *scond, float *amax, char *equed); +void BLAS_FUNC(slaqtr)(int *ltran, int *lreal, int *n, float *t, int *ldt, float *b, float *w, float *scale, float *x, float *work, int *info); +void BLAS_FUNC(slar1v)(int *n, int *b1, int *bn, float *lambda_, float *d, float *l, float *ld, float *lld, float *pivmin, float *gaptol, float *z, int *wantnc, int *negcnt, float *ztz, float *mingma, int *r, int *isuppz, float *nrminv, float *resid, float *rqcorr, float *work); +void BLAS_FUNC(slar2v)(int *n, float *x, float *y, float *z, int *incx, float *c, float *s, int *incc); +void BLAS_FUNC(slarf)(char *side, int *m, int *n, float *v, int *incv, float *tau, float *c, int *ldc, float *work); +void BLAS_FUNC(slarfb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, float *v, int *ldv, float *t, int *ldt, float *c, int *ldc, float *work, int *ldwork); +void BLAS_FUNC(slarfg)(int *n, float *alpha, float *x, int *incx, float *tau); +void BLAS_FUNC(slarfgp)(int *n, float *alpha, float *x, int *incx, float *tau); +void BLAS_FUNC(slarft)(char *direct, char *storev, int *n, int *k, float *v, int *ldv, float *tau, float *t, int *ldt); +void BLAS_FUNC(slarfx)(char *side, int *m, int *n, float *v, float *tau, float *c, int *ldc, float *work); +void BLAS_FUNC(slargv)(int *n, float *x, int *incx, float *y, int *incy, float *c, int *incc); +void BLAS_FUNC(slarnv)(int *idist, int *iseed, int *n, float *x); +void BLAS_FUNC(slarra)(int *n, float *d, float *e, float *e2, float *spltol, float *tnrm, int *nsplit, int *isplit, int *info); +void BLAS_FUNC(slarrb)(int *n, float *d, float *lld, int *ifirst, int *ilast, float *rtol1, float *rtol2, int *offset, float *w, float *wgap, float *werr, float *work, int *iwork, float *pivmin, float *spdiam, int *twist, int *info); +void BLAS_FUNC(slarrc)(char *jobt, int *n, float *vl, float *vu, float *d, float *e, float *pivmin, int *eigcnt, int *lcnt, int *rcnt, int *info); +void BLAS_FUNC(slarrd)(char *range, char *order, int *n, float *vl, float *vu, int *il, int *iu, float *gers, float *reltol, float *d, float *e, float *e2, float *pivmin, int *nsplit, int *isplit, int *m, float *w, float *werr, float *wl, float *wu, int *iblock, int *indexw, float *work, int *iwork, int *info); +void BLAS_FUNC(slarre)(char *range, int *n, float *vl, float *vu, int *il, int *iu, float *d, float *e, float *e2, float *rtol1, float *rtol2, float *spltol, int *nsplit, int *isplit, int *m, float *w, float *werr, float *wgap, int *iblock, int *indexw, float *gers, float *pivmin, float *work, int *iwork, int *info); +void BLAS_FUNC(slarrf)(int *n, float *d, float *l, float *ld, int *clstrt, int *clend, float *w, float *wgap, float *werr, float *spdiam, float *clgapl, float *clgapr, float *pivmin, float *sigma, float *dplus, float *lplus, float *work, int *info); +void BLAS_FUNC(slarrj)(int *n, float *d, float *e2, int *ifirst, int *ilast, float *rtol, int *offset, float *w, float *werr, float *work, int *iwork, float *pivmin, float *spdiam, int *info); +void BLAS_FUNC(slarrk)(int *n, int *iw, float *gl, float *gu, float *d, float *e2, float *pivmin, float *reltol, float *w, float *werr, int *info); +void BLAS_FUNC(slarrr)(int *n, float *d, float *e, int *info); +void BLAS_FUNC(slarrv)(int *n, float *vl, float *vu, float *d, float *l, float *pivmin, int *isplit, int *m, int *dol, int *dou, float *minrgp, float *rtol1, float *rtol2, float *w, float *werr, float *wgap, int *iblock, int *indexw, float *gers, float *z, int *ldz, int *isuppz, float *work, int *iwork, int *info); +void BLAS_FUNC(slartg)(float *f, float *g, float *cs, float *sn, float *r); +void BLAS_FUNC(slartgp)(float *f, float *g, float *cs, float *sn, float *r); +void BLAS_FUNC(slartgs)(float *x, float *y, float *sigma, float *cs, float *sn); +void BLAS_FUNC(slartv)(int *n, float *x, int *incx, float *y, int *incy, float *c, float *s, int *incc); +void BLAS_FUNC(slaruv)(int *iseed, int *n, float *x); +void BLAS_FUNC(slarz)(char *side, int *m, int *n, int *l, float *v, int *incv, float *tau, float *c, int *ldc, float *work); +void BLAS_FUNC(slarzb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, float *v, int *ldv, float *t, int *ldt, float *c, int *ldc, float *work, int *ldwork); +void BLAS_FUNC(slarzt)(char *direct, char *storev, int *n, int *k, float *v, int *ldv, float *tau, float *t, int *ldt); +void BLAS_FUNC(slas2)(float *f, float *g, float *h, float *ssmin, float *ssmax); +void BLAS_FUNC(slascl)(char *type_bn, int *kl, int *ku, float *cfrom, float *cto, int *m, int *n, float *a, int *lda, int *info); +void BLAS_FUNC(slasd0)(int *n, int *sqre, float *d, float *e, float *u, int *ldu, float *vt, int *ldvt, int *smlsiz, int *iwork, float *work, int *info); +void BLAS_FUNC(slasd1)(int *nl, int *nr, int *sqre, float *d, float *alpha, float *beta, float *u, int *ldu, float *vt, int *ldvt, int *idxq, int *iwork, float *work, int *info); +void BLAS_FUNC(slasd2)(int *nl, int *nr, int *sqre, int *k, float *d, float *z, float *alpha, float *beta, float *u, int *ldu, float *vt, int *ldvt, float *dsigma, float *u2, int *ldu2, float *vt2, int *ldvt2, int *idxp, int *idx, int *idxc, int *idxq, int *coltyp, int *info); +void BLAS_FUNC(slasd3)(int *nl, int *nr, int *sqre, int *k, float *d, float *q, int *ldq, float *dsigma, float *u, int *ldu, float *u2, int *ldu2, float *vt, int *ldvt, float *vt2, int *ldvt2, int *idxc, int *ctot, float *z, int *info); +void BLAS_FUNC(slasd4)(int *n, int *i, float *d, float *z, float *delta, float *rho, float *sigma, float *work, int *info); +void BLAS_FUNC(slasd5)(int *i, float *d, float *z, float *delta, float *rho, float *dsigma, float *work); +void BLAS_FUNC(slasd6)(int *icompq, int *nl, int *nr, int *sqre, float *d, float *vf, float *vl, float *alpha, float *beta, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, float *givnum, int *ldgnum, float *poles, float *difl, float *difr, float *z, int *k, float *c, float *s, float *work, int *iwork, int *info); +void BLAS_FUNC(slasd7)(int *icompq, int *nl, int *nr, int *sqre, int *k, float *d, float *z, float *zw, float *vf, float *vfw, float *vl, float *vlw, float *alpha, float *beta, float *dsigma, int *idx, int *idxp, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, float *givnum, int *ldgnum, float *c, float *s, int *info); +void BLAS_FUNC(slasd8)(int *icompq, int *k, float *d, float *z, float *vf, float *vl, float *difl, float *difr, int *lddifr, float *dsigma, float *work, int *info); +void BLAS_FUNC(slasda)(int *icompq, int *smlsiz, int *n, int *sqre, float *d, float *e, float *u, int *ldu, float *vt, int *k, float *difl, float *difr, float *z, float *poles, int *givptr, int *givcol, int *ldgcol, int *perm, float *givnum, float *c, float *s, float *work, int *iwork, int *info); +void BLAS_FUNC(slasdq)(char *uplo, int *sqre, int *n, int *ncvt, int *nru, int *ncc, float *d, float *e, float *vt, int *ldvt, float *u, int *ldu, float *c, int *ldc, float *work, int *info); +void BLAS_FUNC(slasdt)(int *n, int *lvl, int *nd, int *inode, int *ndiml, int *ndimr, int *msub); +void BLAS_FUNC(slaset)(char *uplo, int *m, int *n, float *alpha, float *beta, float *a, int *lda); +void BLAS_FUNC(slasq1)(int *n, float *d, float *e, float *work, int *info); +void BLAS_FUNC(slasq2)(int *n, float *z, int *info); +void BLAS_FUNC(slasq3)(int *i0, int *n0, float *z, int *pp, float *dmin, float *sigma, float *desig, float *qmax, int *nfail, int *iter, int *ndiv, int *ieee, int *ttype, float *dmin1, float *dmin2, float *dn, float *dn1, float *dn2, float *g, float *tau); +void BLAS_FUNC(slasq4)(int *i0, int *n0, float *z, int *pp, int *n0in, float *dmin, float *dmin1, float *dmin2, float *dn, float *dn1, float *dn2, float *tau, int *ttype, float *g); +void BLAS_FUNC(slasq6)(int *i0, int *n0, float *z, int *pp, float *dmin, float *dmin1, float *dmin2, float *dn, float *dnm1, float *dnm2); +void BLAS_FUNC(slasr)(char *side, char *pivot, char *direct, int *m, int *n, float *c, float *s, float *a, int *lda); +void BLAS_FUNC(slasrt)(char *id, int *n, float *d, int *info); +void BLAS_FUNC(slassq)(int *n, float *x, int *incx, float *scale, float *sumsq); +void BLAS_FUNC(slasv2)(float *f, float *g, float *h, float *ssmin, float *ssmax, float *snr, float *csr, float *snl, float *csl); +void BLAS_FUNC(slaswp)(int *n, float *a, int *lda, int *k1, int *k2, int *ipiv, int *incx); +void BLAS_FUNC(slasy2)(int *ltranl, int *ltranr, int *isgn, int *n1, int *n2, float *tl, int *ldtl, float *tr, int *ldtr, float *b, int *ldb, float *scale, float *x, int *ldx, float *xnorm, int *info); +void BLAS_FUNC(slasyf)(char *uplo, int *n, int *nb, int *kb, float *a, int *lda, int *ipiv, float *w, int *ldw, int *info); +void BLAS_FUNC(slatbs)(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, float *ab, int *ldab, float *x, float *scale, float *cnorm, int *info); +void BLAS_FUNC(slatdf)(int *ijob, int *n, float *z, int *ldz, float *rhs, float *rdsum, float *rdscal, int *ipiv, int *jpiv); +void BLAS_FUNC(slatps)(char *uplo, char *trans, char *diag, char *normin, int *n, float *ap, float *x, float *scale, float *cnorm, int *info); +void BLAS_FUNC(slatrd)(char *uplo, int *n, int *nb, float *a, int *lda, float *e, float *tau, float *w, int *ldw); +void BLAS_FUNC(slatrs)(char *uplo, char *trans, char *diag, char *normin, int *n, float *a, int *lda, float *x, float *scale, float *cnorm, int *info); +void BLAS_FUNC(slatrz)(int *m, int *n, int *l, float *a, int *lda, float *tau, float *work); +void BLAS_FUNC(slauu2)(char *uplo, int *n, float *a, int *lda, int *info); +void BLAS_FUNC(slauum)(char *uplo, int *n, float *a, int *lda, int *info); +void BLAS_FUNC(sopgtr)(char *uplo, int *n, float *ap, float *tau, float *q, int *ldq, float *work, int *info); +void BLAS_FUNC(sopmtr)(char *side, char *uplo, char *trans, int *m, int *n, float *ap, float *tau, float *c, int *ldc, float *work, int *info); +void BLAS_FUNC(sorbdb)(char *trans, char *signs, int *m, int *p, int *q, float *x11, int *ldx11, float *x12, int *ldx12, float *x21, int *ldx21, float *x22, int *ldx22, float *theta, float *phi, float *taup1, float *taup2, float *tauq1, float *tauq2, float *work, int *lwork, int *info); +void BLAS_FUNC(sorcsd)(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, float *x11, int *ldx11, float *x12, int *ldx12, float *x21, int *ldx21, float *x22, int *ldx22, float *theta, float *u1, int *ldu1, float *u2, int *ldu2, float *v1t, int *ldv1t, float *v2t, int *ldv2t, float *work, int *lwork, int *iwork, int *info); +void BLAS_FUNC(sorg2l)(int *m, int *n, int *k, float *a, int *lda, float *tau, float *work, int *info); +void BLAS_FUNC(sorg2r)(int *m, int *n, int *k, float *a, int *lda, float *tau, float *work, int *info); +void BLAS_FUNC(sorgbr)(char *vect, int *m, int *n, int *k, float *a, int *lda, float *tau, float *work, int *lwork, int *info); +void BLAS_FUNC(sorghr)(int *n, int *ilo, int *ihi, float *a, int *lda, float *tau, float *work, int *lwork, int *info); +void BLAS_FUNC(sorgl2)(int *m, int *n, int *k, float *a, int *lda, float *tau, float *work, int *info); +void BLAS_FUNC(sorglq)(int *m, int *n, int *k, float *a, int *lda, float *tau, float *work, int *lwork, int *info); +void BLAS_FUNC(sorgql)(int *m, int *n, int *k, float *a, int *lda, float *tau, float *work, int *lwork, int *info); +void BLAS_FUNC(sorgqr)(int *m, int *n, int *k, float *a, int *lda, float *tau, float *work, int *lwork, int *info); +void BLAS_FUNC(sorgr2)(int *m, int *n, int *k, float *a, int *lda, float *tau, float *work, int *info); +void BLAS_FUNC(sorgrq)(int *m, int *n, int *k, float *a, int *lda, float *tau, float *work, int *lwork, int *info); +void BLAS_FUNC(sorgtr)(char *uplo, int *n, float *a, int *lda, float *tau, float *work, int *lwork, int *info); +void BLAS_FUNC(sorm2l)(char *side, char *trans, int *m, int *n, int *k, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *info); +void BLAS_FUNC(sorm2r)(char *side, char *trans, int *m, int *n, int *k, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *info); +void BLAS_FUNC(sormbr)(char *vect, char *side, char *trans, int *m, int *n, int *k, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *lwork, int *info); +void BLAS_FUNC(sormhr)(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *lwork, int *info); +void BLAS_FUNC(sorml2)(char *side, char *trans, int *m, int *n, int *k, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *info); +void BLAS_FUNC(sormlq)(char *side, char *trans, int *m, int *n, int *k, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *lwork, int *info); +void BLAS_FUNC(sormql)(char *side, char *trans, int *m, int *n, int *k, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *lwork, int *info); +void BLAS_FUNC(sormqr)(char *side, char *trans, int *m, int *n, int *k, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *lwork, int *info); +void BLAS_FUNC(sormr2)(char *side, char *trans, int *m, int *n, int *k, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *info); +void BLAS_FUNC(sormr3)(char *side, char *trans, int *m, int *n, int *k, int *l, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *info); +void BLAS_FUNC(sormrq)(char *side, char *trans, int *m, int *n, int *k, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *lwork, int *info); +void BLAS_FUNC(sormrz)(char *side, char *trans, int *m, int *n, int *k, int *l, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *lwork, int *info); +void BLAS_FUNC(sormtr)(char *side, char *uplo, char *trans, int *m, int *n, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *lwork, int *info); +void BLAS_FUNC(spbcon)(char *uplo, int *n, int *kd, float *ab, int *ldab, float *anorm, float *rcond, float *work, int *iwork, int *info); +void BLAS_FUNC(spbequ)(char *uplo, int *n, int *kd, float *ab, int *ldab, float *s, float *scond, float *amax, int *info); +void BLAS_FUNC(spbrfs)(char *uplo, int *n, int *kd, int *nrhs, float *ab, int *ldab, float *afb, int *ldafb, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info); +void BLAS_FUNC(spbstf)(char *uplo, int *n, int *kd, float *ab, int *ldab, int *info); +void BLAS_FUNC(spbsv)(char *uplo, int *n, int *kd, int *nrhs, float *ab, int *ldab, float *b, int *ldb, int *info); +void BLAS_FUNC(spbsvx)(char *fact, char *uplo, int *n, int *kd, int *nrhs, float *ab, int *ldab, float *afb, int *ldafb, char *equed, float *s, float *b, int *ldb, float *x, int *ldx, float *rcond, float *ferr, float *berr, float *work, int *iwork, int *info); +void BLAS_FUNC(spbtf2)(char *uplo, int *n, int *kd, float *ab, int *ldab, int *info); +void BLAS_FUNC(spbtrf)(char *uplo, int *n, int *kd, float *ab, int *ldab, int *info); +void BLAS_FUNC(spbtrs)(char *uplo, int *n, int *kd, int *nrhs, float *ab, int *ldab, float *b, int *ldb, int *info); +void BLAS_FUNC(spftrf)(char *transr, char *uplo, int *n, float *a, int *info); +void BLAS_FUNC(spftri)(char *transr, char *uplo, int *n, float *a, int *info); +void BLAS_FUNC(spftrs)(char *transr, char *uplo, int *n, int *nrhs, float *a, float *b, int *ldb, int *info); +void BLAS_FUNC(spocon)(char *uplo, int *n, float *a, int *lda, float *anorm, float *rcond, float *work, int *iwork, int *info); +void BLAS_FUNC(spoequ)(int *n, float *a, int *lda, float *s, float *scond, float *amax, int *info); +void BLAS_FUNC(spoequb)(int *n, float *a, int *lda, float *s, float *scond, float *amax, int *info); +void BLAS_FUNC(sporfs)(char *uplo, int *n, int *nrhs, float *a, int *lda, float *af, int *ldaf, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info); +void BLAS_FUNC(sposv)(char *uplo, int *n, int *nrhs, float *a, int *lda, float *b, int *ldb, int *info); +void BLAS_FUNC(sposvx)(char *fact, char *uplo, int *n, int *nrhs, float *a, int *lda, float *af, int *ldaf, char *equed, float *s, float *b, int *ldb, float *x, int *ldx, float *rcond, float *ferr, float *berr, float *work, int *iwork, int *info); +void BLAS_FUNC(spotf2)(char *uplo, int *n, float *a, int *lda, int *info); +void BLAS_FUNC(spotrf)(char *uplo, int *n, float *a, int *lda, int *info); +void BLAS_FUNC(spotri)(char *uplo, int *n, float *a, int *lda, int *info); +void BLAS_FUNC(spotrs)(char *uplo, int *n, int *nrhs, float *a, int *lda, float *b, int *ldb, int *info); +void BLAS_FUNC(sppcon)(char *uplo, int *n, float *ap, float *anorm, float *rcond, float *work, int *iwork, int *info); +void BLAS_FUNC(sppequ)(char *uplo, int *n, float *ap, float *s, float *scond, float *amax, int *info); +void BLAS_FUNC(spprfs)(char *uplo, int *n, int *nrhs, float *ap, float *afp, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info); +void BLAS_FUNC(sppsv)(char *uplo, int *n, int *nrhs, float *ap, float *b, int *ldb, int *info); +void BLAS_FUNC(sppsvx)(char *fact, char *uplo, int *n, int *nrhs, float *ap, float *afp, char *equed, float *s, float *b, int *ldb, float *x, int *ldx, float *rcond, float *ferr, float *berr, float *work, int *iwork, int *info); +void BLAS_FUNC(spptrf)(char *uplo, int *n, float *ap, int *info); +void BLAS_FUNC(spptri)(char *uplo, int *n, float *ap, int *info); +void BLAS_FUNC(spptrs)(char *uplo, int *n, int *nrhs, float *ap, float *b, int *ldb, int *info); +void BLAS_FUNC(spstf2)(char *uplo, int *n, float *a, int *lda, int *piv, int *rank, float *tol, float *work, int *info); +void BLAS_FUNC(spstrf)(char *uplo, int *n, float *a, int *lda, int *piv, int *rank, float *tol, float *work, int *info); +void BLAS_FUNC(sptcon)(int *n, float *d, float *e, float *anorm, float *rcond, float *work, int *info); +void BLAS_FUNC(spteqr)(char *compz, int *n, float *d, float *e, float *z, int *ldz, float *work, int *info); +void BLAS_FUNC(sptrfs)(int *n, int *nrhs, float *d, float *e, float *df, float *ef, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *info); +void BLAS_FUNC(sptsv)(int *n, int *nrhs, float *d, float *e, float *b, int *ldb, int *info); +void BLAS_FUNC(sptsvx)(char *fact, int *n, int *nrhs, float *d, float *e, float *df, float *ef, float *b, int *ldb, float *x, int *ldx, float *rcond, float *ferr, float *berr, float *work, int *info); +void BLAS_FUNC(spttrf)(int *n, float *d, float *e, int *info); +void BLAS_FUNC(spttrs)(int *n, int *nrhs, float *d, float *e, float *b, int *ldb, int *info); +void BLAS_FUNC(sptts2)(int *n, int *nrhs, float *d, float *e, float *b, int *ldb); +void BLAS_FUNC(srscl)(int *n, float *sa, float *sx, int *incx); +void BLAS_FUNC(ssbev)(char *jobz, char *uplo, int *n, int *kd, float *ab, int *ldab, float *w, float *z, int *ldz, float *work, int *info); +void BLAS_FUNC(ssbevd)(char *jobz, char *uplo, int *n, int *kd, float *ab, int *ldab, float *w, float *z, int *ldz, float *work, int *lwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(ssbevx)(char *jobz, char *range, char *uplo, int *n, int *kd, float *ab, int *ldab, float *q, int *ldq, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, float *z, int *ldz, float *work, int *iwork, int *ifail, int *info); +void BLAS_FUNC(ssbgst)(char *vect, char *uplo, int *n, int *ka, int *kb, float *ab, int *ldab, float *bb, int *ldbb, float *x, int *ldx, float *work, int *info); +void BLAS_FUNC(ssbgv)(char *jobz, char *uplo, int *n, int *ka, int *kb, float *ab, int *ldab, float *bb, int *ldbb, float *w, float *z, int *ldz, float *work, int *info); +void BLAS_FUNC(ssbgvd)(char *jobz, char *uplo, int *n, int *ka, int *kb, float *ab, int *ldab, float *bb, int *ldbb, float *w, float *z, int *ldz, float *work, int *lwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(ssbgvx)(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, float *ab, int *ldab, float *bb, int *ldbb, float *q, int *ldq, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, float *z, int *ldz, float *work, int *iwork, int *ifail, int *info); +void BLAS_FUNC(ssbtrd)(char *vect, char *uplo, int *n, int *kd, float *ab, int *ldab, float *d, float *e, float *q, int *ldq, float *work, int *info); +void BLAS_FUNC(ssfrk)(char *transr, char *uplo, char *trans, int *n, int *k, float *alpha, float *a, int *lda, float *beta, float *c); +void BLAS_FUNC(sspcon)(char *uplo, int *n, float *ap, int *ipiv, float *anorm, float *rcond, float *work, int *iwork, int *info); +void BLAS_FUNC(sspev)(char *jobz, char *uplo, int *n, float *ap, float *w, float *z, int *ldz, float *work, int *info); +void BLAS_FUNC(sspevd)(char *jobz, char *uplo, int *n, float *ap, float *w, float *z, int *ldz, float *work, int *lwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(sspevx)(char *jobz, char *range, char *uplo, int *n, float *ap, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, float *z, int *ldz, float *work, int *iwork, int *ifail, int *info); +void BLAS_FUNC(sspgst)(int *itype, char *uplo, int *n, float *ap, float *bp, int *info); +void BLAS_FUNC(sspgv)(int *itype, char *jobz, char *uplo, int *n, float *ap, float *bp, float *w, float *z, int *ldz, float *work, int *info); +void BLAS_FUNC(sspgvd)(int *itype, char *jobz, char *uplo, int *n, float *ap, float *bp, float *w, float *z, int *ldz, float *work, int *lwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(sspgvx)(int *itype, char *jobz, char *range, char *uplo, int *n, float *ap, float *bp, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, float *z, int *ldz, float *work, int *iwork, int *ifail, int *info); +void BLAS_FUNC(ssprfs)(char *uplo, int *n, int *nrhs, float *ap, float *afp, int *ipiv, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info); +void BLAS_FUNC(sspsv)(char *uplo, int *n, int *nrhs, float *ap, int *ipiv, float *b, int *ldb, int *info); +void BLAS_FUNC(sspsvx)(char *fact, char *uplo, int *n, int *nrhs, float *ap, float *afp, int *ipiv, float *b, int *ldb, float *x, int *ldx, float *rcond, float *ferr, float *berr, float *work, int *iwork, int *info); +void BLAS_FUNC(ssptrd)(char *uplo, int *n, float *ap, float *d, float *e, float *tau, int *info); +void BLAS_FUNC(ssptrf)(char *uplo, int *n, float *ap, int *ipiv, int *info); +void BLAS_FUNC(ssptri)(char *uplo, int *n, float *ap, int *ipiv, float *work, int *info); +void BLAS_FUNC(ssptrs)(char *uplo, int *n, int *nrhs, float *ap, int *ipiv, float *b, int *ldb, int *info); +void BLAS_FUNC(sstebz)(char *range, char *order, int *n, float *vl, float *vu, int *il, int *iu, float *abstol, float *d, float *e, int *m, int *nsplit, float *w, int *iblock, int *isplit, float *work, int *iwork, int *info); +void BLAS_FUNC(sstedc)(char *compz, int *n, float *d, float *e, float *z, int *ldz, float *work, int *lwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(sstegr)(char *jobz, char *range, int *n, float *d, float *e, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, float *z, int *ldz, int *isuppz, float *work, int *lwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(sstein)(int *n, float *d, float *e, int *m, float *w, int *iblock, int *isplit, float *z, int *ldz, float *work, int *iwork, int *ifail, int *info); +void BLAS_FUNC(sstemr)(char *jobz, char *range, int *n, float *d, float *e, float *vl, float *vu, int *il, int *iu, int *m, float *w, float *z, int *ldz, int *nzc, int *isuppz, int *tryrac, float *work, int *lwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(ssteqr)(char *compz, int *n, float *d, float *e, float *z, int *ldz, float *work, int *info); +void BLAS_FUNC(ssterf)(int *n, float *d, float *e, int *info); +void BLAS_FUNC(sstev)(char *jobz, int *n, float *d, float *e, float *z, int *ldz, float *work, int *info); +void BLAS_FUNC(sstevd)(char *jobz, int *n, float *d, float *e, float *z, int *ldz, float *work, int *lwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(sstevr)(char *jobz, char *range, int *n, float *d, float *e, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, float *z, int *ldz, int *isuppz, float *work, int *lwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(sstevx)(char *jobz, char *range, int *n, float *d, float *e, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, float *z, int *ldz, float *work, int *iwork, int *ifail, int *info); +void BLAS_FUNC(ssycon)(char *uplo, int *n, float *a, int *lda, int *ipiv, float *anorm, float *rcond, float *work, int *iwork, int *info); +void BLAS_FUNC(ssyconv)(char *uplo, char *way, int *n, float *a, int *lda, int *ipiv, float *work, int *info); +void BLAS_FUNC(ssyequb)(char *uplo, int *n, float *a, int *lda, float *s, float *scond, float *amax, float *work, int *info); +void BLAS_FUNC(ssyev)(char *jobz, char *uplo, int *n, float *a, int *lda, float *w, float *work, int *lwork, int *info); +void BLAS_FUNC(ssyevd)(char *jobz, char *uplo, int *n, float *a, int *lda, float *w, float *work, int *lwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(ssyevr)(char *jobz, char *range, char *uplo, int *n, float *a, int *lda, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, float *z, int *ldz, int *isuppz, float *work, int *lwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(ssyevx)(char *jobz, char *range, char *uplo, int *n, float *a, int *lda, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, float *z, int *ldz, float *work, int *lwork, int *iwork, int *ifail, int *info); +void BLAS_FUNC(ssygs2)(int *itype, char *uplo, int *n, float *a, int *lda, float *b, int *ldb, int *info); +void BLAS_FUNC(ssygst)(int *itype, char *uplo, int *n, float *a, int *lda, float *b, int *ldb, int *info); +void BLAS_FUNC(ssygv)(int *itype, char *jobz, char *uplo, int *n, float *a, int *lda, float *b, int *ldb, float *w, float *work, int *lwork, int *info); +void BLAS_FUNC(ssygvd)(int *itype, char *jobz, char *uplo, int *n, float *a, int *lda, float *b, int *ldb, float *w, float *work, int *lwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(ssygvx)(int *itype, char *jobz, char *range, char *uplo, int *n, float *a, int *lda, float *b, int *ldb, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, float *z, int *ldz, float *work, int *lwork, int *iwork, int *ifail, int *info); +void BLAS_FUNC(ssyrfs)(char *uplo, int *n, int *nrhs, float *a, int *lda, float *af, int *ldaf, int *ipiv, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info); +void BLAS_FUNC(ssysv)(char *uplo, int *n, int *nrhs, float *a, int *lda, int *ipiv, float *b, int *ldb, float *work, int *lwork, int *info); +void BLAS_FUNC(ssysvx)(char *fact, char *uplo, int *n, int *nrhs, float *a, int *lda, float *af, int *ldaf, int *ipiv, float *b, int *ldb, float *x, int *ldx, float *rcond, float *ferr, float *berr, float *work, int *lwork, int *iwork, int *info); +void BLAS_FUNC(ssyswapr)(char *uplo, int *n, float *a, int *lda, int *i1, int *i2); +void BLAS_FUNC(ssytd2)(char *uplo, int *n, float *a, int *lda, float *d, float *e, float *tau, int *info); +void BLAS_FUNC(ssytf2)(char *uplo, int *n, float *a, int *lda, int *ipiv, int *info); +void BLAS_FUNC(ssytrd)(char *uplo, int *n, float *a, int *lda, float *d, float *e, float *tau, float *work, int *lwork, int *info); +void BLAS_FUNC(ssytrf)(char *uplo, int *n, float *a, int *lda, int *ipiv, float *work, int *lwork, int *info); +void BLAS_FUNC(ssytri)(char *uplo, int *n, float *a, int *lda, int *ipiv, float *work, int *info); +void BLAS_FUNC(ssytri2)(char *uplo, int *n, float *a, int *lda, int *ipiv, float *work, int *lwork, int *info); +void BLAS_FUNC(ssytri2x)(char *uplo, int *n, float *a, int *lda, int *ipiv, float *work, int *nb, int *info); +void BLAS_FUNC(ssytrs)(char *uplo, int *n, int *nrhs, float *a, int *lda, int *ipiv, float *b, int *ldb, int *info); +void BLAS_FUNC(ssytrs2)(char *uplo, int *n, int *nrhs, float *a, int *lda, int *ipiv, float *b, int *ldb, float *work, int *info); +void BLAS_FUNC(stbcon)(char *norm, char *uplo, char *diag, int *n, int *kd, float *ab, int *ldab, float *rcond, float *work, int *iwork, int *info); +void BLAS_FUNC(stbrfs)(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, float *ab, int *ldab, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info); +void BLAS_FUNC(stbtrs)(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, float *ab, int *ldab, float *b, int *ldb, int *info); +void BLAS_FUNC(stfsm)(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, float *alpha, float *a, float *b, int *ldb); +void BLAS_FUNC(stftri)(char *transr, char *uplo, char *diag, int *n, float *a, int *info); +void BLAS_FUNC(stfttp)(char *transr, char *uplo, int *n, float *arf, float *ap, int *info); +void BLAS_FUNC(stfttr)(char *transr, char *uplo, int *n, float *arf, float *a, int *lda, int *info); +void BLAS_FUNC(stgevc)(char *side, char *howmny, int *select, int *n, float *s, int *lds, float *p, int *ldp, float *vl, int *ldvl, float *vr, int *ldvr, int *mm, int *m, float *work, int *info); +void BLAS_FUNC(stgex2)(int *wantq, int *wantz, int *n, float *a, int *lda, float *b, int *ldb, float *q, int *ldq, float *z, int *ldz, int *j1, int *n1, int *n2, float *work, int *lwork, int *info); +void BLAS_FUNC(stgexc)(int *wantq, int *wantz, int *n, float *a, int *lda, float *b, int *ldb, float *q, int *ldq, float *z, int *ldz, int *ifst, int *ilst, float *work, int *lwork, int *info); +void BLAS_FUNC(stgsen)(int *ijob, int *wantq, int *wantz, int *select, int *n, float *a, int *lda, float *b, int *ldb, float *alphar, float *alphai, float *beta, float *q, int *ldq, float *z, int *ldz, int *m, float *pl, float *pr, float *dif, float *work, int *lwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(stgsja)(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, float *a, int *lda, float *b, int *ldb, float *tola, float *tolb, float *alpha, float *beta, float *u, int *ldu, float *v, int *ldv, float *q, int *ldq, float *work, int *ncycle, int *info); +void BLAS_FUNC(stgsna)(char *job, char *howmny, int *select, int *n, float *a, int *lda, float *b, int *ldb, float *vl, int *ldvl, float *vr, int *ldvr, float *s, float *dif, int *mm, int *m, float *work, int *lwork, int *iwork, int *info); +void BLAS_FUNC(stgsy2)(char *trans, int *ijob, int *m, int *n, float *a, int *lda, float *b, int *ldb, float *c, int *ldc, float *d, int *ldd, float *e, int *lde, float *f, int *ldf, float *scale, float *rdsum, float *rdscal, int *iwork, int *pq, int *info); +void BLAS_FUNC(stgsyl)(char *trans, int *ijob, int *m, int *n, float *a, int *lda, float *b, int *ldb, float *c, int *ldc, float *d, int *ldd, float *e, int *lde, float *f, int *ldf, float *scale, float *dif, float *work, int *lwork, int *iwork, int *info); +void BLAS_FUNC(stpcon)(char *norm, char *uplo, char *diag, int *n, float *ap, float *rcond, float *work, int *iwork, int *info); +void BLAS_FUNC(stpmqrt)(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, float *v, int *ldv, float *t, int *ldt, float *a, int *lda, float *b, int *ldb, float *work, int *info); +void BLAS_FUNC(stpqrt)(int *m, int *n, int *l, int *nb, float *a, int *lda, float *b, int *ldb, float *t, int *ldt, float *work, int *info); +void BLAS_FUNC(stpqrt2)(int *m, int *n, int *l, float *a, int *lda, float *b, int *ldb, float *t, int *ldt, int *info); +void BLAS_FUNC(stprfb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, float *v, int *ldv, float *t, int *ldt, float *a, int *lda, float *b, int *ldb, float *work, int *ldwork); +void BLAS_FUNC(stprfs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, float *ap, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info); +void BLAS_FUNC(stptri)(char *uplo, char *diag, int *n, float *ap, int *info); +void BLAS_FUNC(stptrs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, float *ap, float *b, int *ldb, int *info); +void BLAS_FUNC(stpttf)(char *transr, char *uplo, int *n, float *ap, float *arf, int *info); +void BLAS_FUNC(stpttr)(char *uplo, int *n, float *ap, float *a, int *lda, int *info); +void BLAS_FUNC(strcon)(char *norm, char *uplo, char *diag, int *n, float *a, int *lda, float *rcond, float *work, int *iwork, int *info); +void BLAS_FUNC(strevc)(char *side, char *howmny, int *select, int *n, float *t, int *ldt, float *vl, int *ldvl, float *vr, int *ldvr, int *mm, int *m, float *work, int *info); +void BLAS_FUNC(strexc)(char *compq, int *n, float *t, int *ldt, float *q, int *ldq, int *ifst, int *ilst, float *work, int *info); +void BLAS_FUNC(strrfs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, float *a, int *lda, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info); +void BLAS_FUNC(strsen)(char *job, char *compq, int *select, int *n, float *t, int *ldt, float *q, int *ldq, float *wr, float *wi, int *m, float *s, float *sep, float *work, int *lwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(strsna)(char *job, char *howmny, int *select, int *n, float *t, int *ldt, float *vl, int *ldvl, float *vr, int *ldvr, float *s, float *sep, int *mm, int *m, float *work, int *ldwork, int *iwork, int *info); +void BLAS_FUNC(strsyl)(char *trana, char *tranb, int *isgn, int *m, int *n, float *a, int *lda, float *b, int *ldb, float *c, int *ldc, float *scale, int *info); +void BLAS_FUNC(strti2)(char *uplo, char *diag, int *n, float *a, int *lda, int *info); +void BLAS_FUNC(strtri)(char *uplo, char *diag, int *n, float *a, int *lda, int *info); +void BLAS_FUNC(strtrs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, float *a, int *lda, float *b, int *ldb, int *info); +void BLAS_FUNC(strttf)(char *transr, char *uplo, int *n, float *a, int *lda, float *arf, int *info); +void BLAS_FUNC(strttp)(char *uplo, int *n, float *a, int *lda, float *ap, int *info); +void BLAS_FUNC(stzrzf)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *lwork, int *info); +void BLAS_FUNC(xerbla_array)(char *srname_array, int *srname_len, int *info); +void BLAS_FUNC(zbbcsd)(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, double *theta, double *phi, npy_complex128 *u1, int *ldu1, npy_complex128 *u2, int *ldu2, npy_complex128 *v1t, int *ldv1t, npy_complex128 *v2t, int *ldv2t, double *b11d, double *b11e, double *b12d, double *b12e, double *b21d, double *b21e, double *b22d, double *b22e, double *rwork, int *lrwork, int *info); +void BLAS_FUNC(zbdsqr)(char *uplo, int *n, int *ncvt, int *nru, int *ncc, double *d, double *e, npy_complex128 *vt, int *ldvt, npy_complex128 *u, int *ldu, npy_complex128 *c, int *ldc, double *rwork, int *info); +void BLAS_FUNC(zcgesv)(int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, npy_complex128 *work, npy_complex64 *swork, double *rwork, int *iter, int *info); +void BLAS_FUNC(zcposv)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, npy_complex128 *work, npy_complex64 *swork, double *rwork, int *iter, int *info); +void BLAS_FUNC(zdrscl)(int *n, double *sa, npy_complex128 *sx, int *incx); +void BLAS_FUNC(zgbbrd)(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, npy_complex128 *ab, int *ldab, double *d, double *e, npy_complex128 *q, int *ldq, npy_complex128 *pt, int *ldpt, npy_complex128 *c, int *ldc, npy_complex128 *work, double *rwork, int *info); +void BLAS_FUNC(zgbcon)(char *norm, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, int *ipiv, double *anorm, double *rcond, npy_complex128 *work, double *rwork, int *info); +void BLAS_FUNC(zgbequ)(int *m, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, double *r, double *c, double *rowcnd, double *colcnd, double *amax, int *info); +void BLAS_FUNC(zgbequb)(int *m, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, double *r, double *c, double *rowcnd, double *colcnd, double *amax, int *info); +void BLAS_FUNC(zgbrfs)(char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *afb, int *ldafb, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info); +void BLAS_FUNC(zgbsv)(int *n, int *kl, int *ku, int *nrhs, npy_complex128 *ab, int *ldab, int *ipiv, npy_complex128 *b, int *ldb, int *info); +void BLAS_FUNC(zgbsvx)(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *afb, int *ldafb, int *ipiv, char *equed, double *r, double *c, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info); +void BLAS_FUNC(zgbtf2)(int *m, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, int *ipiv, int *info); +void BLAS_FUNC(zgbtrf)(int *m, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, int *ipiv, int *info); +void BLAS_FUNC(zgbtrs)(char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex128 *ab, int *ldab, int *ipiv, npy_complex128 *b, int *ldb, int *info); +void BLAS_FUNC(zgebak)(char *job, char *side, int *n, int *ilo, int *ihi, double *scale, int *m, npy_complex128 *v, int *ldv, int *info); +void BLAS_FUNC(zgebal)(char *job, int *n, npy_complex128 *a, int *lda, int *ilo, int *ihi, double *scale, int *info); +void BLAS_FUNC(zgebd2)(int *m, int *n, npy_complex128 *a, int *lda, double *d, double *e, npy_complex128 *tauq, npy_complex128 *taup, npy_complex128 *work, int *info); +void BLAS_FUNC(zgebrd)(int *m, int *n, npy_complex128 *a, int *lda, double *d, double *e, npy_complex128 *tauq, npy_complex128 *taup, npy_complex128 *work, int *lwork, int *info); +void BLAS_FUNC(zgecon)(char *norm, int *n, npy_complex128 *a, int *lda, double *anorm, double *rcond, npy_complex128 *work, double *rwork, int *info); +void BLAS_FUNC(zgeequ)(int *m, int *n, npy_complex128 *a, int *lda, double *r, double *c, double *rowcnd, double *colcnd, double *amax, int *info); +void BLAS_FUNC(zgeequb)(int *m, int *n, npy_complex128 *a, int *lda, double *r, double *c, double *rowcnd, double *colcnd, double *amax, int *info); +void BLAS_FUNC(zgees)(char *jobvs, char *sort, _zselect1 *select, int *n, npy_complex128 *a, int *lda, int *sdim, npy_complex128 *w, npy_complex128 *vs, int *ldvs, npy_complex128 *work, int *lwork, double *rwork, int *bwork, int *info); +void BLAS_FUNC(zgeesx)(char *jobvs, char *sort, _zselect1 *select, char *sense, int *n, npy_complex128 *a, int *lda, int *sdim, npy_complex128 *w, npy_complex128 *vs, int *ldvs, double *rconde, double *rcondv, npy_complex128 *work, int *lwork, double *rwork, int *bwork, int *info); +void BLAS_FUNC(zgeev)(char *jobvl, char *jobvr, int *n, npy_complex128 *a, int *lda, npy_complex128 *w, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, npy_complex128 *work, int *lwork, double *rwork, int *info); +void BLAS_FUNC(zgeevx)(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, npy_complex128 *a, int *lda, npy_complex128 *w, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, int *ilo, int *ihi, double *scale, double *abnrm, double *rconde, double *rcondv, npy_complex128 *work, int *lwork, double *rwork, int *info); +void BLAS_FUNC(zgehd2)(int *n, int *ilo, int *ihi, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info); +void BLAS_FUNC(zgehrd)(int *n, int *ilo, int *ihi, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info); +void BLAS_FUNC(zgelq2)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info); +void BLAS_FUNC(zgelqf)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info); +void BLAS_FUNC(zgels)(char *trans, int *m, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *work, int *lwork, int *info); +void BLAS_FUNC(zgelsd)(int *m, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, double *s, double *rcond, int *rank, npy_complex128 *work, int *lwork, double *rwork, int *iwork, int *info); +void BLAS_FUNC(zgelss)(int *m, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, double *s, double *rcond, int *rank, npy_complex128 *work, int *lwork, double *rwork, int *info); +void BLAS_FUNC(zgelsy)(int *m, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *jpvt, double *rcond, int *rank, npy_complex128 *work, int *lwork, double *rwork, int *info); +void BLAS_FUNC(zgemqrt)(char *side, char *trans, int *m, int *n, int *k, int *nb, npy_complex128 *v, int *ldv, npy_complex128 *t, int *ldt, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info); +void BLAS_FUNC(zgeql2)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info); +void BLAS_FUNC(zgeqlf)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info); +void BLAS_FUNC(zgeqp3)(int *m, int *n, npy_complex128 *a, int *lda, int *jpvt, npy_complex128 *tau, npy_complex128 *work, int *lwork, double *rwork, int *info); +void BLAS_FUNC(zgeqr2)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info); +void BLAS_FUNC(zgeqr2p)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info); +void BLAS_FUNC(zgeqrf)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info); +void BLAS_FUNC(zgeqrfp)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info); +void BLAS_FUNC(zgeqrt)(int *m, int *n, int *nb, npy_complex128 *a, int *lda, npy_complex128 *t, int *ldt, npy_complex128 *work, int *info); +void BLAS_FUNC(zgeqrt2)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *t, int *ldt, int *info); +void BLAS_FUNC(zgeqrt3)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *t, int *ldt, int *info); +void BLAS_FUNC(zgerfs)(char *trans, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info); +void BLAS_FUNC(zgerq2)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info); +void BLAS_FUNC(zgerqf)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info); +void BLAS_FUNC(zgesc2)(int *n, npy_complex128 *a, int *lda, npy_complex128 *rhs, int *ipiv, int *jpiv, double *scale); +void BLAS_FUNC(zgesdd)(char *jobz, int *m, int *n, npy_complex128 *a, int *lda, double *s, npy_complex128 *u, int *ldu, npy_complex128 *vt, int *ldvt, npy_complex128 *work, int *lwork, double *rwork, int *iwork, int *info); +void BLAS_FUNC(zgesv)(int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, int *info); +void BLAS_FUNC(zgesvd)(char *jobu, char *jobvt, int *m, int *n, npy_complex128 *a, int *lda, double *s, npy_complex128 *u, int *ldu, npy_complex128 *vt, int *ldvt, npy_complex128 *work, int *lwork, double *rwork, int *info); +void BLAS_FUNC(zgesvx)(char *fact, char *trans, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, char *equed, double *r, double *c, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info); +void BLAS_FUNC(zgetc2)(int *n, npy_complex128 *a, int *lda, int *ipiv, int *jpiv, int *info); +void BLAS_FUNC(zgetf2)(int *m, int *n, npy_complex128 *a, int *lda, int *ipiv, int *info); +void BLAS_FUNC(zgetrf)(int *m, int *n, npy_complex128 *a, int *lda, int *ipiv, int *info); +void BLAS_FUNC(zgetri)(int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *lwork, int *info); +void BLAS_FUNC(zgetrs)(char *trans, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, int *info); +void BLAS_FUNC(zggbak)(char *job, char *side, int *n, int *ilo, int *ihi, double *lscale, double *rscale, int *m, npy_complex128 *v, int *ldv, int *info); +void BLAS_FUNC(zggbal)(char *job, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *ilo, int *ihi, double *lscale, double *rscale, double *work, int *info); +void BLAS_FUNC(zgges)(char *jobvsl, char *jobvsr, char *sort, _zselect2 *selctg, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *sdim, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *vsl, int *ldvsl, npy_complex128 *vsr, int *ldvsr, npy_complex128 *work, int *lwork, double *rwork, int *bwork, int *info); +void BLAS_FUNC(zggesx)(char *jobvsl, char *jobvsr, char *sort, _zselect2 *selctg, char *sense, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *sdim, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *vsl, int *ldvsl, npy_complex128 *vsr, int *ldvsr, double *rconde, double *rcondv, npy_complex128 *work, int *lwork, double *rwork, int *iwork, int *liwork, int *bwork, int *info); +void BLAS_FUNC(zggev)(char *jobvl, char *jobvr, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, npy_complex128 *work, int *lwork, double *rwork, int *info); +void BLAS_FUNC(zggevx)(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, int *ilo, int *ihi, double *lscale, double *rscale, double *abnrm, double *bbnrm, double *rconde, double *rcondv, npy_complex128 *work, int *lwork, double *rwork, int *iwork, int *bwork, int *info); +void BLAS_FUNC(zggglm)(int *n, int *m, int *p, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *d, npy_complex128 *x, npy_complex128 *y, npy_complex128 *work, int *lwork, int *info); +void BLAS_FUNC(zgghrd)(char *compq, char *compz, int *n, int *ilo, int *ihi, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *q, int *ldq, npy_complex128 *z, int *ldz, int *info); +void BLAS_FUNC(zgglse)(int *m, int *n, int *p, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *c, npy_complex128 *d, npy_complex128 *x, npy_complex128 *work, int *lwork, int *info); +void BLAS_FUNC(zggqrf)(int *n, int *m, int *p, npy_complex128 *a, int *lda, npy_complex128 *taua, npy_complex128 *b, int *ldb, npy_complex128 *taub, npy_complex128 *work, int *lwork, int *info); +void BLAS_FUNC(zggrqf)(int *m, int *p, int *n, npy_complex128 *a, int *lda, npy_complex128 *taua, npy_complex128 *b, int *ldb, npy_complex128 *taub, npy_complex128 *work, int *lwork, int *info); +void BLAS_FUNC(zgtcon)(char *norm, int *n, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *du2, int *ipiv, double *anorm, double *rcond, npy_complex128 *work, int *info); +void BLAS_FUNC(zgtrfs)(char *trans, int *n, int *nrhs, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *dlf, npy_complex128 *df, npy_complex128 *duf, npy_complex128 *du2, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info); +void BLAS_FUNC(zgtsv)(int *n, int *nrhs, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *b, int *ldb, int *info); +void BLAS_FUNC(zgtsvx)(char *fact, char *trans, int *n, int *nrhs, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *dlf, npy_complex128 *df, npy_complex128 *duf, npy_complex128 *du2, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info); +void BLAS_FUNC(zgttrf)(int *n, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *du2, int *ipiv, int *info); +void BLAS_FUNC(zgttrs)(char *trans, int *n, int *nrhs, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *du2, int *ipiv, npy_complex128 *b, int *ldb, int *info); +void BLAS_FUNC(zgtts2)(int *itrans, int *n, int *nrhs, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *du2, int *ipiv, npy_complex128 *b, int *ldb); +void BLAS_FUNC(zhbev)(char *jobz, char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, double *rwork, int *info); +void BLAS_FUNC(zhbevd)(char *jobz, char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, double *rwork, int *lrwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(zhbevx)(char *jobz, char *range, char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, npy_complex128 *q, int *ldq, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, double *rwork, int *iwork, int *ifail, int *info); +void BLAS_FUNC(zhbgst)(char *vect, char *uplo, int *n, int *ka, int *kb, npy_complex128 *ab, int *ldab, npy_complex128 *bb, int *ldbb, npy_complex128 *x, int *ldx, npy_complex128 *work, double *rwork, int *info); +void BLAS_FUNC(zhbgv)(char *jobz, char *uplo, int *n, int *ka, int *kb, npy_complex128 *ab, int *ldab, npy_complex128 *bb, int *ldbb, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, double *rwork, int *info); +void BLAS_FUNC(zhbgvd)(char *jobz, char *uplo, int *n, int *ka, int *kb, npy_complex128 *ab, int *ldab, npy_complex128 *bb, int *ldbb, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, double *rwork, int *lrwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(zhbgvx)(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, npy_complex128 *ab, int *ldab, npy_complex128 *bb, int *ldbb, npy_complex128 *q, int *ldq, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, double *rwork, int *iwork, int *ifail, int *info); +void BLAS_FUNC(zhbtrd)(char *vect, char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, double *d, double *e, npy_complex128 *q, int *ldq, npy_complex128 *work, int *info); +void BLAS_FUNC(zhecon)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, double *anorm, double *rcond, npy_complex128 *work, int *info); +void BLAS_FUNC(zheequb)(char *uplo, int *n, npy_complex128 *a, int *lda, double *s, double *scond, double *amax, npy_complex128 *work, int *info); +void BLAS_FUNC(zheev)(char *jobz, char *uplo, int *n, npy_complex128 *a, int *lda, double *w, npy_complex128 *work, int *lwork, double *rwork, int *info); +void BLAS_FUNC(zheevd)(char *jobz, char *uplo, int *n, npy_complex128 *a, int *lda, double *w, npy_complex128 *work, int *lwork, double *rwork, int *lrwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(zheevr)(char *jobz, char *range, char *uplo, int *n, npy_complex128 *a, int *lda, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, npy_complex128 *z, int *ldz, int *isuppz, npy_complex128 *work, int *lwork, double *rwork, int *lrwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(zheevx)(char *jobz, char *range, char *uplo, int *n, npy_complex128 *a, int *lda, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, double *rwork, int *iwork, int *ifail, int *info); +void BLAS_FUNC(zhegs2)(int *itype, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *info); +void BLAS_FUNC(zhegst)(int *itype, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *info); +void BLAS_FUNC(zhegv)(int *itype, char *jobz, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, double *w, npy_complex128 *work, int *lwork, double *rwork, int *info); +void BLAS_FUNC(zhegvd)(int *itype, char *jobz, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, double *w, npy_complex128 *work, int *lwork, double *rwork, int *lrwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(zhegvx)(int *itype, char *jobz, char *range, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, double *rwork, int *iwork, int *ifail, int *info); +void BLAS_FUNC(zherfs)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info); +void BLAS_FUNC(zhesv)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *work, int *lwork, int *info); +void BLAS_FUNC(zhesvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, int *lwork, double *rwork, int *info); +void BLAS_FUNC(zheswapr)(char *uplo, int *n, npy_complex128 *a, int *lda, int *i1, int *i2); +void BLAS_FUNC(zhetd2)(char *uplo, int *n, npy_complex128 *a, int *lda, double *d, double *e, npy_complex128 *tau, int *info); +void BLAS_FUNC(zhetf2)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, int *info); +void BLAS_FUNC(zhetrd)(char *uplo, int *n, npy_complex128 *a, int *lda, double *d, double *e, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info); +void BLAS_FUNC(zhetrf)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *lwork, int *info); +void BLAS_FUNC(zhetri)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *info); +void BLAS_FUNC(zhetri2)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *lwork, int *info); +void BLAS_FUNC(zhetri2x)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *nb, int *info); +void BLAS_FUNC(zhetrs)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, int *info); +void BLAS_FUNC(zhetrs2)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *work, int *info); +void BLAS_FUNC(zhfrk)(char *transr, char *uplo, char *trans, int *n, int *k, double *alpha, npy_complex128 *a, int *lda, double *beta, npy_complex128 *c); +void BLAS_FUNC(zhgeqz)(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, npy_complex128 *h, int *ldh, npy_complex128 *t, int *ldt, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *q, int *ldq, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, double *rwork, int *info); +void BLAS_FUNC(zhpcon)(char *uplo, int *n, npy_complex128 *ap, int *ipiv, double *anorm, double *rcond, npy_complex128 *work, int *info); +void BLAS_FUNC(zhpev)(char *jobz, char *uplo, int *n, npy_complex128 *ap, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, double *rwork, int *info); +void BLAS_FUNC(zhpevd)(char *jobz, char *uplo, int *n, npy_complex128 *ap, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, double *rwork, int *lrwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(zhpevx)(char *jobz, char *range, char *uplo, int *n, npy_complex128 *ap, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, double *rwork, int *iwork, int *ifail, int *info); +void BLAS_FUNC(zhpgst)(int *itype, char *uplo, int *n, npy_complex128 *ap, npy_complex128 *bp, int *info); +void BLAS_FUNC(zhpgv)(int *itype, char *jobz, char *uplo, int *n, npy_complex128 *ap, npy_complex128 *bp, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, double *rwork, int *info); +void BLAS_FUNC(zhpgvd)(int *itype, char *jobz, char *uplo, int *n, npy_complex128 *ap, npy_complex128 *bp, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, double *rwork, int *lrwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(zhpgvx)(int *itype, char *jobz, char *range, char *uplo, int *n, npy_complex128 *ap, npy_complex128 *bp, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, double *rwork, int *iwork, int *ifail, int *info); +void BLAS_FUNC(zhprfs)(char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info); +void BLAS_FUNC(zhpsv)(char *uplo, int *n, int *nrhs, npy_complex128 *ap, int *ipiv, npy_complex128 *b, int *ldb, int *info); +void BLAS_FUNC(zhpsvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info); +void BLAS_FUNC(zhptrd)(char *uplo, int *n, npy_complex128 *ap, double *d, double *e, npy_complex128 *tau, int *info); +void BLAS_FUNC(zhptrf)(char *uplo, int *n, npy_complex128 *ap, int *ipiv, int *info); +void BLAS_FUNC(zhptri)(char *uplo, int *n, npy_complex128 *ap, int *ipiv, npy_complex128 *work, int *info); +void BLAS_FUNC(zhptrs)(char *uplo, int *n, int *nrhs, npy_complex128 *ap, int *ipiv, npy_complex128 *b, int *ldb, int *info); +void BLAS_FUNC(zhsein)(char *side, char *eigsrc, char *initv, int *select, int *n, npy_complex128 *h, int *ldh, npy_complex128 *w, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, int *mm, int *m, npy_complex128 *work, double *rwork, int *ifaill, int *ifailr, int *info); +void BLAS_FUNC(zhseqr)(char *job, char *compz, int *n, int *ilo, int *ihi, npy_complex128 *h, int *ldh, npy_complex128 *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, int *info); +void BLAS_FUNC(zlabrd)(int *m, int *n, int *nb, npy_complex128 *a, int *lda, double *d, double *e, npy_complex128 *tauq, npy_complex128 *taup, npy_complex128 *x, int *ldx, npy_complex128 *y, int *ldy); +void BLAS_FUNC(zlacgv)(int *n, npy_complex128 *x, int *incx); +void BLAS_FUNC(zlacn2)(int *n, npy_complex128 *v, npy_complex128 *x, double *est, int *kase, int *isave); +void BLAS_FUNC(zlacon)(int *n, npy_complex128 *v, npy_complex128 *x, double *est, int *kase); +void BLAS_FUNC(zlacp2)(char *uplo, int *m, int *n, double *a, int *lda, npy_complex128 *b, int *ldb); +void BLAS_FUNC(zlacpy)(char *uplo, int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb); +void BLAS_FUNC(zlacrm)(int *m, int *n, npy_complex128 *a, int *lda, double *b, int *ldb, npy_complex128 *c, int *ldc, double *rwork); +void BLAS_FUNC(zlacrt)(int *n, npy_complex128 *cx, int *incx, npy_complex128 *cy, int *incy, npy_complex128 *c, npy_complex128 *s); +void F_FUNC(zladivwrp,ZLADIVWRP)(npy_complex128 *out, npy_complex128 *x, npy_complex128 *y); +void BLAS_FUNC(zlaed0)(int *qsiz, int *n, double *d, double *e, npy_complex128 *q, int *ldq, npy_complex128 *qstore, int *ldqs, double *rwork, int *iwork, int *info); +void BLAS_FUNC(zlaed7)(int *n, int *cutpnt, int *qsiz, int *tlvls, int *curlvl, int *curpbm, double *d, npy_complex128 *q, int *ldq, double *rho, int *indxq, double *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, double *givnum, npy_complex128 *work, double *rwork, int *iwork, int *info); +void BLAS_FUNC(zlaed8)(int *k, int *n, int *qsiz, npy_complex128 *q, int *ldq, double *d, double *rho, int *cutpnt, double *z, double *dlamda, npy_complex128 *q2, int *ldq2, double *w, int *indxp, int *indx, int *indxq, int *perm, int *givptr, int *givcol, double *givnum, int *info); +void BLAS_FUNC(zlaein)(int *rightv, int *noinit, int *n, npy_complex128 *h, int *ldh, npy_complex128 *w, npy_complex128 *v, npy_complex128 *b, int *ldb, double *rwork, double *eps3, double *smlnum, int *info); +void BLAS_FUNC(zlaesy)(npy_complex128 *a, npy_complex128 *b, npy_complex128 *c, npy_complex128 *rt1, npy_complex128 *rt2, npy_complex128 *evscal, npy_complex128 *cs1, npy_complex128 *sn1); +void BLAS_FUNC(zlaev2)(npy_complex128 *a, npy_complex128 *b, npy_complex128 *c, double *rt1, double *rt2, double *cs1, npy_complex128 *sn1); +void BLAS_FUNC(zlag2c)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex64 *sa, int *ldsa, int *info); +void BLAS_FUNC(zlags2)(int *upper, double *a1, npy_complex128 *a2, double *a3, double *b1, npy_complex128 *b2, double *b3, double *csu, npy_complex128 *snu, double *csv, npy_complex128 *snv, double *csq, npy_complex128 *snq); +void BLAS_FUNC(zlagtm)(char *trans, int *n, int *nrhs, double *alpha, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *x, int *ldx, double *beta, npy_complex128 *b, int *ldb); +void BLAS_FUNC(zlahef)(char *uplo, int *n, int *nb, int *kb, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *w, int *ldw, int *info); +void BLAS_FUNC(zlahqr)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, npy_complex128 *h, int *ldh, npy_complex128 *w, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, int *info); +void BLAS_FUNC(zlahr2)(int *n, int *k, int *nb, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *t, int *ldt, npy_complex128 *y, int *ldy); +void BLAS_FUNC(zlaic1)(int *job, int *j, npy_complex128 *x, double *sest, npy_complex128 *w, npy_complex128 *gamma, double *sestpr, npy_complex128 *s, npy_complex128 *c); +void BLAS_FUNC(zlals0)(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, npy_complex128 *b, int *ldb, npy_complex128 *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, double *givnum, int *ldgnum, double *poles, double *difl, double *difr, double *z, int *k, double *c, double *s, double *rwork, int *info); +void BLAS_FUNC(zlalsa)(int *icompq, int *smlsiz, int *n, int *nrhs, npy_complex128 *b, int *ldb, npy_complex128 *bx, int *ldbx, double *u, int *ldu, double *vt, int *k, double *difl, double *difr, double *z, double *poles, int *givptr, int *givcol, int *ldgcol, int *perm, double *givnum, double *c, double *s, double *rwork, int *iwork, int *info); +void BLAS_FUNC(zlalsd)(char *uplo, int *smlsiz, int *n, int *nrhs, double *d, double *e, npy_complex128 *b, int *ldb, double *rcond, int *rank, npy_complex128 *work, double *rwork, int *iwork, int *info); +double BLAS_FUNC(zlangb)(char *norm, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, double *work); +double BLAS_FUNC(zlange)(char *norm, int *m, int *n, npy_complex128 *a, int *lda, double *work); +double BLAS_FUNC(zlangt)(char *norm, int *n, npy_complex128 *dl, npy_complex128 *d_, npy_complex128 *du); +double BLAS_FUNC(zlanhb)(char *norm, char *uplo, int *n, int *k, npy_complex128 *ab, int *ldab, double *work); +double BLAS_FUNC(zlanhe)(char *norm, char *uplo, int *n, npy_complex128 *a, int *lda, double *work); +double BLAS_FUNC(zlanhf)(char *norm, char *transr, char *uplo, int *n, npy_complex128 *a, double *work); +double BLAS_FUNC(zlanhp)(char *norm, char *uplo, int *n, npy_complex128 *ap, double *work); +double BLAS_FUNC(zlanhs)(char *norm, int *n, npy_complex128 *a, int *lda, double *work); +double BLAS_FUNC(zlanht)(char *norm, int *n, double *d_, npy_complex128 *e); +double BLAS_FUNC(zlansb)(char *norm, char *uplo, int *n, int *k, npy_complex128 *ab, int *ldab, double *work); +double BLAS_FUNC(zlansp)(char *norm, char *uplo, int *n, npy_complex128 *ap, double *work); +double BLAS_FUNC(zlansy)(char *norm, char *uplo, int *n, npy_complex128 *a, int *lda, double *work); +double BLAS_FUNC(zlantb)(char *norm, char *uplo, char *diag, int *n, int *k, npy_complex128 *ab, int *ldab, double *work); +double BLAS_FUNC(zlantp)(char *norm, char *uplo, char *diag, int *n, npy_complex128 *ap, double *work); +double BLAS_FUNC(zlantr)(char *norm, char *uplo, char *diag, int *m, int *n, npy_complex128 *a, int *lda, double *work); +void BLAS_FUNC(zlapll)(int *n, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, double *ssmin); +void BLAS_FUNC(zlapmr)(int *forwrd, int *m, int *n, npy_complex128 *x, int *ldx, int *k); +void BLAS_FUNC(zlapmt)(int *forwrd, int *m, int *n, npy_complex128 *x, int *ldx, int *k); +void BLAS_FUNC(zlaqgb)(int *m, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, double *r, double *c, double *rowcnd, double *colcnd, double *amax, char *equed); +void BLAS_FUNC(zlaqge)(int *m, int *n, npy_complex128 *a, int *lda, double *r, double *c, double *rowcnd, double *colcnd, double *amax, char *equed); +void BLAS_FUNC(zlaqhb)(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, double *s, double *scond, double *amax, char *equed); +void BLAS_FUNC(zlaqhe)(char *uplo, int *n, npy_complex128 *a, int *lda, double *s, double *scond, double *amax, char *equed); +void BLAS_FUNC(zlaqhp)(char *uplo, int *n, npy_complex128 *ap, double *s, double *scond, double *amax, char *equed); +void BLAS_FUNC(zlaqp2)(int *m, int *n, int *offset, npy_complex128 *a, int *lda, int *jpvt, npy_complex128 *tau, double *vn1, double *vn2, npy_complex128 *work); +void BLAS_FUNC(zlaqps)(int *m, int *n, int *offset, int *nb, int *kb, npy_complex128 *a, int *lda, int *jpvt, npy_complex128 *tau, double *vn1, double *vn2, npy_complex128 *auxv, npy_complex128 *f, int *ldf); +void BLAS_FUNC(zlaqr0)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, npy_complex128 *h, int *ldh, npy_complex128 *w, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, int *info); +void BLAS_FUNC(zlaqr1)(int *n, npy_complex128 *h, int *ldh, npy_complex128 *s1, npy_complex128 *s2, npy_complex128 *v); +void BLAS_FUNC(zlaqr2)(int *wantt, int *wantz, int *n, int *ktop, int *kbot, int *nw, npy_complex128 *h, int *ldh, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, int *ns, int *nd, npy_complex128 *sh, npy_complex128 *v, int *ldv, int *nh, npy_complex128 *t, int *ldt, int *nv, npy_complex128 *wv, int *ldwv, npy_complex128 *work, int *lwork); +void BLAS_FUNC(zlaqr3)(int *wantt, int *wantz, int *n, int *ktop, int *kbot, int *nw, npy_complex128 *h, int *ldh, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, int *ns, int *nd, npy_complex128 *sh, npy_complex128 *v, int *ldv, int *nh, npy_complex128 *t, int *ldt, int *nv, npy_complex128 *wv, int *ldwv, npy_complex128 *work, int *lwork); +void BLAS_FUNC(zlaqr4)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, npy_complex128 *h, int *ldh, npy_complex128 *w, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, int *info); +void BLAS_FUNC(zlaqr5)(int *wantt, int *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, npy_complex128 *s, npy_complex128 *h, int *ldh, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, npy_complex128 *v, int *ldv, npy_complex128 *u, int *ldu, int *nv, npy_complex128 *wv, int *ldwv, int *nh, npy_complex128 *wh, int *ldwh); +void BLAS_FUNC(zlaqsb)(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, double *s, double *scond, double *amax, char *equed); +void BLAS_FUNC(zlaqsp)(char *uplo, int *n, npy_complex128 *ap, double *s, double *scond, double *amax, char *equed); +void BLAS_FUNC(zlaqsy)(char *uplo, int *n, npy_complex128 *a, int *lda, double *s, double *scond, double *amax, char *equed); +void BLAS_FUNC(zlar1v)(int *n, int *b1, int *bn, double *lambda_, double *d, double *l, double *ld, double *lld, double *pivmin, double *gaptol, npy_complex128 *z, int *wantnc, int *negcnt, double *ztz, double *mingma, int *r, int *isuppz, double *nrminv, double *resid, double *rqcorr, double *work); +void BLAS_FUNC(zlar2v)(int *n, npy_complex128 *x, npy_complex128 *y, npy_complex128 *z, int *incx, double *c, npy_complex128 *s, int *incc); +void BLAS_FUNC(zlarcm)(int *m, int *n, double *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *c, int *ldc, double *rwork); +void BLAS_FUNC(zlarf)(char *side, int *m, int *n, npy_complex128 *v, int *incv, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work); +void BLAS_FUNC(zlarfb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, npy_complex128 *v, int *ldv, npy_complex128 *t, int *ldt, npy_complex128 *c, int *ldc, npy_complex128 *work, int *ldwork); +void BLAS_FUNC(zlarfg)(int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *tau); +void BLAS_FUNC(zlarfgp)(int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *tau); +void BLAS_FUNC(zlarft)(char *direct, char *storev, int *n, int *k, npy_complex128 *v, int *ldv, npy_complex128 *tau, npy_complex128 *t, int *ldt); +void BLAS_FUNC(zlarfx)(char *side, int *m, int *n, npy_complex128 *v, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work); +void BLAS_FUNC(zlargv)(int *n, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, double *c, int *incc); +void BLAS_FUNC(zlarnv)(int *idist, int *iseed, int *n, npy_complex128 *x); +void BLAS_FUNC(zlarrv)(int *n, double *vl, double *vu, double *d, double *l, double *pivmin, int *isplit, int *m, int *dol, int *dou, double *minrgp, double *rtol1, double *rtol2, double *w, double *werr, double *wgap, int *iblock, int *indexw, double *gers, npy_complex128 *z, int *ldz, int *isuppz, double *work, int *iwork, int *info); +void BLAS_FUNC(zlartg)(npy_complex128 *f, npy_complex128 *g, double *cs, npy_complex128 *sn, npy_complex128 *r); +void BLAS_FUNC(zlartv)(int *n, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, double *c, npy_complex128 *s, int *incc); +void BLAS_FUNC(zlarz)(char *side, int *m, int *n, int *l, npy_complex128 *v, int *incv, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work); +void BLAS_FUNC(zlarzb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, npy_complex128 *v, int *ldv, npy_complex128 *t, int *ldt, npy_complex128 *c, int *ldc, npy_complex128 *work, int *ldwork); +void BLAS_FUNC(zlarzt)(char *direct, char *storev, int *n, int *k, npy_complex128 *v, int *ldv, npy_complex128 *tau, npy_complex128 *t, int *ldt); +void BLAS_FUNC(zlascl)(char *type_bn, int *kl, int *ku, double *cfrom, double *cto, int *m, int *n, npy_complex128 *a, int *lda, int *info); +void BLAS_FUNC(zlaset)(char *uplo, int *m, int *n, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *a, int *lda); +void BLAS_FUNC(zlasr)(char *side, char *pivot, char *direct, int *m, int *n, double *c, double *s, npy_complex128 *a, int *lda); +void BLAS_FUNC(zlassq)(int *n, npy_complex128 *x, int *incx, double *scale, double *sumsq); +void BLAS_FUNC(zlaswp)(int *n, npy_complex128 *a, int *lda, int *k1, int *k2, int *ipiv, int *incx); +void BLAS_FUNC(zlasyf)(char *uplo, int *n, int *nb, int *kb, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *w, int *ldw, int *info); +void BLAS_FUNC(zlat2c)(char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex64 *sa, int *ldsa, int *info); +void BLAS_FUNC(zlatbs)(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, npy_complex128 *ab, int *ldab, npy_complex128 *x, double *scale, double *cnorm, int *info); +void BLAS_FUNC(zlatdf)(int *ijob, int *n, npy_complex128 *z, int *ldz, npy_complex128 *rhs, double *rdsum, double *rdscal, int *ipiv, int *jpiv); +void BLAS_FUNC(zlatps)(char *uplo, char *trans, char *diag, char *normin, int *n, npy_complex128 *ap, npy_complex128 *x, double *scale, double *cnorm, int *info); +void BLAS_FUNC(zlatrd)(char *uplo, int *n, int *nb, npy_complex128 *a, int *lda, double *e, npy_complex128 *tau, npy_complex128 *w, int *ldw); +void BLAS_FUNC(zlatrs)(char *uplo, char *trans, char *diag, char *normin, int *n, npy_complex128 *a, int *lda, npy_complex128 *x, double *scale, double *cnorm, int *info); +void BLAS_FUNC(zlatrz)(int *m, int *n, int *l, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work); +void BLAS_FUNC(zlauu2)(char *uplo, int *n, npy_complex128 *a, int *lda, int *info); +void BLAS_FUNC(zlauum)(char *uplo, int *n, npy_complex128 *a, int *lda, int *info); +void BLAS_FUNC(zpbcon)(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, double *anorm, double *rcond, npy_complex128 *work, double *rwork, int *info); +void BLAS_FUNC(zpbequ)(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, double *s, double *scond, double *amax, int *info); +void BLAS_FUNC(zpbrfs)(char *uplo, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *afb, int *ldafb, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info); +void BLAS_FUNC(zpbstf)(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, int *info); +void BLAS_FUNC(zpbsv)(char *uplo, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *b, int *ldb, int *info); +void BLAS_FUNC(zpbsvx)(char *fact, char *uplo, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *afb, int *ldafb, char *equed, double *s, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info); +void BLAS_FUNC(zpbtf2)(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, int *info); +void BLAS_FUNC(zpbtrf)(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, int *info); +void BLAS_FUNC(zpbtrs)(char *uplo, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *b, int *ldb, int *info); +void BLAS_FUNC(zpftrf)(char *transr, char *uplo, int *n, npy_complex128 *a, int *info); +void BLAS_FUNC(zpftri)(char *transr, char *uplo, int *n, npy_complex128 *a, int *info); +void BLAS_FUNC(zpftrs)(char *transr, char *uplo, int *n, int *nrhs, npy_complex128 *a, npy_complex128 *b, int *ldb, int *info); +void BLAS_FUNC(zpocon)(char *uplo, int *n, npy_complex128 *a, int *lda, double *anorm, double *rcond, npy_complex128 *work, double *rwork, int *info); +void BLAS_FUNC(zpoequ)(int *n, npy_complex128 *a, int *lda, double *s, double *scond, double *amax, int *info); +void BLAS_FUNC(zpoequb)(int *n, npy_complex128 *a, int *lda, double *s, double *scond, double *amax, int *info); +void BLAS_FUNC(zporfs)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info); +void BLAS_FUNC(zposv)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *info); +void BLAS_FUNC(zposvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, char *equed, double *s, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info); +void BLAS_FUNC(zpotf2)(char *uplo, int *n, npy_complex128 *a, int *lda, int *info); +void BLAS_FUNC(zpotrf)(char *uplo, int *n, npy_complex128 *a, int *lda, int *info); +void BLAS_FUNC(zpotri)(char *uplo, int *n, npy_complex128 *a, int *lda, int *info); +void BLAS_FUNC(zpotrs)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *info); +void BLAS_FUNC(zppcon)(char *uplo, int *n, npy_complex128 *ap, double *anorm, double *rcond, npy_complex128 *work, double *rwork, int *info); +void BLAS_FUNC(zppequ)(char *uplo, int *n, npy_complex128 *ap, double *s, double *scond, double *amax, int *info); +void BLAS_FUNC(zpprfs)(char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info); +void BLAS_FUNC(zppsv)(char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *b, int *ldb, int *info); +void BLAS_FUNC(zppsvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, char *equed, double *s, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info); +void BLAS_FUNC(zpptrf)(char *uplo, int *n, npy_complex128 *ap, int *info); +void BLAS_FUNC(zpptri)(char *uplo, int *n, npy_complex128 *ap, int *info); +void BLAS_FUNC(zpptrs)(char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *b, int *ldb, int *info); +void BLAS_FUNC(zpstf2)(char *uplo, int *n, npy_complex128 *a, int *lda, int *piv, int *rank, double *tol, double *work, int *info); +void BLAS_FUNC(zpstrf)(char *uplo, int *n, npy_complex128 *a, int *lda, int *piv, int *rank, double *tol, double *work, int *info); +void BLAS_FUNC(zptcon)(int *n, double *d, npy_complex128 *e, double *anorm, double *rcond, double *rwork, int *info); +void BLAS_FUNC(zpteqr)(char *compz, int *n, double *d, double *e, npy_complex128 *z, int *ldz, double *work, int *info); +void BLAS_FUNC(zptrfs)(char *uplo, int *n, int *nrhs, double *d, npy_complex128 *e, double *df, npy_complex128 *ef, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info); +void BLAS_FUNC(zptsv)(int *n, int *nrhs, double *d, npy_complex128 *e, npy_complex128 *b, int *ldb, int *info); +void BLAS_FUNC(zptsvx)(char *fact, int *n, int *nrhs, double *d, npy_complex128 *e, double *df, npy_complex128 *ef, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info); +void BLAS_FUNC(zpttrf)(int *n, double *d, npy_complex128 *e, int *info); +void BLAS_FUNC(zpttrs)(char *uplo, int *n, int *nrhs, double *d, npy_complex128 *e, npy_complex128 *b, int *ldb, int *info); +void BLAS_FUNC(zptts2)(int *iuplo, int *n, int *nrhs, double *d, npy_complex128 *e, npy_complex128 *b, int *ldb); +void BLAS_FUNC(zrot)(int *n, npy_complex128 *cx, int *incx, npy_complex128 *cy, int *incy, double *c, npy_complex128 *s); +void BLAS_FUNC(zspcon)(char *uplo, int *n, npy_complex128 *ap, int *ipiv, double *anorm, double *rcond, npy_complex128 *work, int *info); +void BLAS_FUNC(zspmv)(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *ap, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy); +void BLAS_FUNC(zspr)(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *ap); +void BLAS_FUNC(zsprfs)(char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info); +void BLAS_FUNC(zspsv)(char *uplo, int *n, int *nrhs, npy_complex128 *ap, int *ipiv, npy_complex128 *b, int *ldb, int *info); +void BLAS_FUNC(zspsvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info); +void BLAS_FUNC(zsptrf)(char *uplo, int *n, npy_complex128 *ap, int *ipiv, int *info); +void BLAS_FUNC(zsptri)(char *uplo, int *n, npy_complex128 *ap, int *ipiv, npy_complex128 *work, int *info); +void BLAS_FUNC(zsptrs)(char *uplo, int *n, int *nrhs, npy_complex128 *ap, int *ipiv, npy_complex128 *b, int *ldb, int *info); +void BLAS_FUNC(zstedc)(char *compz, int *n, double *d, double *e, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, double *rwork, int *lrwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(zstegr)(char *jobz, char *range, int *n, double *d, double *e, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, npy_complex128 *z, int *ldz, int *isuppz, double *work, int *lwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(zstein)(int *n, double *d, double *e, int *m, double *w, int *iblock, int *isplit, npy_complex128 *z, int *ldz, double *work, int *iwork, int *ifail, int *info); +void BLAS_FUNC(zstemr)(char *jobz, char *range, int *n, double *d, double *e, double *vl, double *vu, int *il, int *iu, int *m, double *w, npy_complex128 *z, int *ldz, int *nzc, int *isuppz, int *tryrac, double *work, int *lwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(zsteqr)(char *compz, int *n, double *d, double *e, npy_complex128 *z, int *ldz, double *work, int *info); +void BLAS_FUNC(zsycon)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, double *anorm, double *rcond, npy_complex128 *work, int *info); +void BLAS_FUNC(zsyconv)(char *uplo, char *way, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *info); +void BLAS_FUNC(zsyequb)(char *uplo, int *n, npy_complex128 *a, int *lda, double *s, double *scond, double *amax, npy_complex128 *work, int *info); +void BLAS_FUNC(zsymv)(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy); +void BLAS_FUNC(zsyr)(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *a, int *lda); +void BLAS_FUNC(zsyrfs)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info); +void BLAS_FUNC(zsysv)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *work, int *lwork, int *info); +void BLAS_FUNC(zsysvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, int *lwork, double *rwork, int *info); +void BLAS_FUNC(zsyswapr)(char *uplo, int *n, npy_complex128 *a, int *lda, int *i1, int *i2); +void BLAS_FUNC(zsytf2)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, int *info); +void BLAS_FUNC(zsytrf)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *lwork, int *info); +void BLAS_FUNC(zsytri)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *info); +void BLAS_FUNC(zsytri2)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *lwork, int *info); +void BLAS_FUNC(zsytri2x)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *nb, int *info); +void BLAS_FUNC(zsytrs)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, int *info); +void BLAS_FUNC(zsytrs2)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *work, int *info); +void BLAS_FUNC(ztbcon)(char *norm, char *uplo, char *diag, int *n, int *kd, npy_complex128 *ab, int *ldab, double *rcond, npy_complex128 *work, double *rwork, int *info); +void BLAS_FUNC(ztbrfs)(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info); +void BLAS_FUNC(ztbtrs)(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *b, int *ldb, int *info); +void BLAS_FUNC(ztfsm)(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, npy_complex128 *b, int *ldb); +void BLAS_FUNC(ztftri)(char *transr, char *uplo, char *diag, int *n, npy_complex128 *a, int *info); +void BLAS_FUNC(ztfttp)(char *transr, char *uplo, int *n, npy_complex128 *arf, npy_complex128 *ap, int *info); +void BLAS_FUNC(ztfttr)(char *transr, char *uplo, int *n, npy_complex128 *arf, npy_complex128 *a, int *lda, int *info); +void BLAS_FUNC(ztgevc)(char *side, char *howmny, int *select, int *n, npy_complex128 *s, int *lds, npy_complex128 *p, int *ldp, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, int *mm, int *m, npy_complex128 *work, double *rwork, int *info); +void BLAS_FUNC(ztgex2)(int *wantq, int *wantz, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *q, int *ldq, npy_complex128 *z, int *ldz, int *j1, int *info); +void BLAS_FUNC(ztgexc)(int *wantq, int *wantz, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *q, int *ldq, npy_complex128 *z, int *ldz, int *ifst, int *ilst, int *info); +void BLAS_FUNC(ztgsen)(int *ijob, int *wantq, int *wantz, int *select, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *q, int *ldq, npy_complex128 *z, int *ldz, int *m, double *pl, double *pr, double *dif, npy_complex128 *work, int *lwork, int *iwork, int *liwork, int *info); +void BLAS_FUNC(ztgsja)(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, double *tola, double *tolb, double *alpha, double *beta, npy_complex128 *u, int *ldu, npy_complex128 *v, int *ldv, npy_complex128 *q, int *ldq, npy_complex128 *work, int *ncycle, int *info); +void BLAS_FUNC(ztgsna)(char *job, char *howmny, int *select, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, double *s, double *dif, int *mm, int *m, npy_complex128 *work, int *lwork, int *iwork, int *info); +void BLAS_FUNC(ztgsy2)(char *trans, int *ijob, int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *c, int *ldc, npy_complex128 *d, int *ldd, npy_complex128 *e, int *lde, npy_complex128 *f, int *ldf, double *scale, double *rdsum, double *rdscal, int *info); +void BLAS_FUNC(ztgsyl)(char *trans, int *ijob, int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *c, int *ldc, npy_complex128 *d, int *ldd, npy_complex128 *e, int *lde, npy_complex128 *f, int *ldf, double *scale, double *dif, npy_complex128 *work, int *lwork, int *iwork, int *info); +void BLAS_FUNC(ztpcon)(char *norm, char *uplo, char *diag, int *n, npy_complex128 *ap, double *rcond, npy_complex128 *work, double *rwork, int *info); +void BLAS_FUNC(ztpmqrt)(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, npy_complex128 *v, int *ldv, npy_complex128 *t, int *ldt, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *work, int *info); +void BLAS_FUNC(ztpqrt)(int *m, int *n, int *l, int *nb, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *t, int *ldt, npy_complex128 *work, int *info); +void BLAS_FUNC(ztpqrt2)(int *m, int *n, int *l, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *t, int *ldt, int *info); +void BLAS_FUNC(ztprfb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, npy_complex128 *v, int *ldv, npy_complex128 *t, int *ldt, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *work, int *ldwork); +void BLAS_FUNC(ztprfs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info); +void BLAS_FUNC(ztptri)(char *uplo, char *diag, int *n, npy_complex128 *ap, int *info); +void BLAS_FUNC(ztptrs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *b, int *ldb, int *info); +void BLAS_FUNC(ztpttf)(char *transr, char *uplo, int *n, npy_complex128 *ap, npy_complex128 *arf, int *info); +void BLAS_FUNC(ztpttr)(char *uplo, int *n, npy_complex128 *ap, npy_complex128 *a, int *lda, int *info); +void BLAS_FUNC(ztrcon)(char *norm, char *uplo, char *diag, int *n, npy_complex128 *a, int *lda, double *rcond, npy_complex128 *work, double *rwork, int *info); +void BLAS_FUNC(ztrevc)(char *side, char *howmny, int *select, int *n, npy_complex128 *t, int *ldt, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, int *mm, int *m, npy_complex128 *work, double *rwork, int *info); +void BLAS_FUNC(ztrexc)(char *compq, int *n, npy_complex128 *t, int *ldt, npy_complex128 *q, int *ldq, int *ifst, int *ilst, int *info); +void BLAS_FUNC(ztrrfs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info); +void BLAS_FUNC(ztrsen)(char *job, char *compq, int *select, int *n, npy_complex128 *t, int *ldt, npy_complex128 *q, int *ldq, npy_complex128 *w, int *m, double *s, double *sep, npy_complex128 *work, int *lwork, int *info); +void BLAS_FUNC(ztrsna)(char *job, char *howmny, int *select, int *n, npy_complex128 *t, int *ldt, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, double *s, double *sep, int *mm, int *m, npy_complex128 *work, int *ldwork, double *rwork, int *info); +void BLAS_FUNC(ztrsyl)(char *trana, char *tranb, int *isgn, int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *c, int *ldc, double *scale, int *info); +void BLAS_FUNC(ztrti2)(char *uplo, char *diag, int *n, npy_complex128 *a, int *lda, int *info); +void BLAS_FUNC(ztrtri)(char *uplo, char *diag, int *n, npy_complex128 *a, int *lda, int *info); +void BLAS_FUNC(ztrtrs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *info); +void BLAS_FUNC(ztrttf)(char *transr, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *arf, int *info); +void BLAS_FUNC(ztrttp)(char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *ap, int *info); +void BLAS_FUNC(ztzrzf)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info); +void BLAS_FUNC(zunbdb)(char *trans, char *signs, int *m, int *p, int *q, npy_complex128 *x11, int *ldx11, npy_complex128 *x12, int *ldx12, npy_complex128 *x21, int *ldx21, npy_complex128 *x22, int *ldx22, double *theta, double *phi, npy_complex128 *taup1, npy_complex128 *taup2, npy_complex128 *tauq1, npy_complex128 *tauq2, npy_complex128 *work, int *lwork, int *info); +void BLAS_FUNC(zuncsd)(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, npy_complex128 *x11, int *ldx11, npy_complex128 *x12, int *ldx12, npy_complex128 *x21, int *ldx21, npy_complex128 *x22, int *ldx22, double *theta, npy_complex128 *u1, int *ldu1, npy_complex128 *u2, int *ldu2, npy_complex128 *v1t, int *ldv1t, npy_complex128 *v2t, int *ldv2t, npy_complex128 *work, int *lwork, double *rwork, int *lrwork, int *iwork, int *info); +void BLAS_FUNC(zung2l)(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info); +void BLAS_FUNC(zung2r)(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info); +void BLAS_FUNC(zungbr)(char *vect, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info); +void BLAS_FUNC(zunghr)(int *n, int *ilo, int *ihi, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info); +void BLAS_FUNC(zungl2)(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info); +void BLAS_FUNC(zunglq)(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info); +void BLAS_FUNC(zungql)(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info); +void BLAS_FUNC(zungqr)(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info); +void BLAS_FUNC(zungr2)(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info); +void BLAS_FUNC(zungrq)(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info); +void BLAS_FUNC(zungtr)(char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info); +void BLAS_FUNC(zunm2l)(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info); +void BLAS_FUNC(zunm2r)(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info); +void BLAS_FUNC(zunmbr)(char *vect, char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info); +void BLAS_FUNC(zunmhr)(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info); +void BLAS_FUNC(zunml2)(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info); +void BLAS_FUNC(zunmlq)(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info); +void BLAS_FUNC(zunmql)(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info); +void BLAS_FUNC(zunmqr)(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info); +void BLAS_FUNC(zunmr2)(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info); +void BLAS_FUNC(zunmr3)(char *side, char *trans, int *m, int *n, int *k, int *l, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info); +void BLAS_FUNC(zunmrq)(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info); +void BLAS_FUNC(zunmrz)(char *side, char *trans, int *m, int *n, int *k, int *l, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info); +void BLAS_FUNC(zunmtr)(char *side, char *uplo, char *trans, int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info); +void BLAS_FUNC(zupgtr)(char *uplo, int *n, npy_complex128 *ap, npy_complex128 *tau, npy_complex128 *q, int *ldq, npy_complex128 *work, int *info); +void BLAS_FUNC(zupmtr)(char *side, char *uplo, char *trans, int *m, int *n, npy_complex128 *ap, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info); + +#ifdef __cplusplus +} +#endif diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_matfuncs.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_matfuncs.py new file mode 100644 index 0000000000000000000000000000000000000000..3a0ba92af71f3f3188cc73ca441187db9701b052 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_matfuncs.py @@ -0,0 +1,867 @@ +# +# Author: Travis Oliphant, March 2002 +# +import warnings +from itertools import product + +import numpy as np +from numpy import (dot, diag, prod, logical_not, ravel, transpose, + conjugate, absolute, amax, sign, isfinite, triu) + +# Local imports +from scipy.linalg import LinAlgError, bandwidth +from ._misc import norm +from ._basic import solve, inv +from ._decomp_svd import svd +from ._decomp_schur import schur, rsf2csf +from ._expm_frechet import expm_frechet, expm_cond +from ._matfuncs_sqrtm import sqrtm +from ._matfuncs_expm import pick_pade_structure, pade_UV_calc +from ._linalg_pythran import _funm_loops # type: ignore[import-not-found] + +__all__ = ['expm', 'cosm', 'sinm', 'tanm', 'coshm', 'sinhm', 'tanhm', 'logm', + 'funm', 'signm', 'sqrtm', 'fractional_matrix_power', 'expm_frechet', + 'expm_cond', 'khatri_rao'] + +eps = np.finfo('d').eps +feps = np.finfo('f').eps + +_array_precision = {'i': 1, 'l': 1, 'f': 0, 'd': 1, 'F': 0, 'D': 1} + + +############################################################################### +# Utility functions. + + +def _asarray_square(A): + """ + Wraps asarray with the extra requirement that the input be a square matrix. + + The motivation is that the matfuncs module has real functions that have + been lifted to square matrix functions. + + Parameters + ---------- + A : array_like + A square matrix. + + Returns + ------- + out : ndarray + An ndarray copy or view or other representation of A. + + """ + A = np.asarray(A) + if len(A.shape) != 2 or A.shape[0] != A.shape[1]: + raise ValueError('expected square array_like input') + return A + + +def _maybe_real(A, B, tol=None): + """ + Return either B or the real part of B, depending on properties of A and B. + + The motivation is that B has been computed as a complicated function of A, + and B may be perturbed by negligible imaginary components. + If A is real and B is complex with small imaginary components, + then return a real copy of B. The assumption in that case would be that + the imaginary components of B are numerical artifacts. + + Parameters + ---------- + A : ndarray + Input array whose type is to be checked as real vs. complex. + B : ndarray + Array to be returned, possibly without its imaginary part. + tol : float + Absolute tolerance. + + Returns + ------- + out : real or complex array + Either the input array B or only the real part of the input array B. + + """ + # Note that booleans and integers compare as real. + if np.isrealobj(A) and np.iscomplexobj(B): + if tol is None: + tol = {0: feps*1e3, 1: eps*1e6}[_array_precision[B.dtype.char]] + if np.allclose(B.imag, 0.0, atol=tol): + B = B.real + return B + + +############################################################################### +# Matrix functions. + + +def fractional_matrix_power(A, t): + """ + Compute the fractional power of a matrix. + + Proceeds according to the discussion in section (6) of [1]_. + + Parameters + ---------- + A : (N, N) array_like + Matrix whose fractional power to evaluate. + t : float + Fractional power. + + Returns + ------- + X : (N, N) array_like + The fractional power of the matrix. + + References + ---------- + .. [1] Nicholas J. Higham and Lijing lin (2011) + "A Schur-Pade Algorithm for Fractional Powers of a Matrix." + SIAM Journal on Matrix Analysis and Applications, + 32 (3). pp. 1056-1078. ISSN 0895-4798 + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import fractional_matrix_power + >>> a = np.array([[1.0, 3.0], [1.0, 4.0]]) + >>> b = fractional_matrix_power(a, 0.5) + >>> b + array([[ 0.75592895, 1.13389342], + [ 0.37796447, 1.88982237]]) + >>> np.dot(b, b) # Verify square root + array([[ 1., 3.], + [ 1., 4.]]) + + """ + # This fixes some issue with imports; + # this function calls onenormest which is in scipy.sparse. + A = _asarray_square(A) + import scipy.linalg._matfuncs_inv_ssq + return scipy.linalg._matfuncs_inv_ssq._fractional_matrix_power(A, t) + + +def logm(A, disp=True): + """ + Compute matrix logarithm. + + The matrix logarithm is the inverse of + expm: expm(logm(`A`)) == `A` + + Parameters + ---------- + A : (N, N) array_like + Matrix whose logarithm to evaluate + disp : bool, optional + Emit warning if error in the result is estimated large + instead of returning estimated error. (Default: True) + + Returns + ------- + logm : (N, N) ndarray + Matrix logarithm of `A` + errest : float + (if disp == False) + + 1-norm of the estimated error, ||err||_1 / ||A||_1 + + References + ---------- + .. [1] Awad H. Al-Mohy and Nicholas J. Higham (2012) + "Improved Inverse Scaling and Squaring Algorithms + for the Matrix Logarithm." + SIAM Journal on Scientific Computing, 34 (4). C152-C169. + ISSN 1095-7197 + + .. [2] Nicholas J. Higham (2008) + "Functions of Matrices: Theory and Computation" + ISBN 978-0-898716-46-7 + + .. [3] Nicholas J. Higham and Lijing lin (2011) + "A Schur-Pade Algorithm for Fractional Powers of a Matrix." + SIAM Journal on Matrix Analysis and Applications, + 32 (3). pp. 1056-1078. ISSN 0895-4798 + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import logm, expm + >>> a = np.array([[1.0, 3.0], [1.0, 4.0]]) + >>> b = logm(a) + >>> b + array([[-1.02571087, 2.05142174], + [ 0.68380725, 1.02571087]]) + >>> expm(b) # Verify expm(logm(a)) returns a + array([[ 1., 3.], + [ 1., 4.]]) + + """ + A = np.asarray(A) # squareness checked in `_logm` + # Avoid circular import ... this is OK, right? + import scipy.linalg._matfuncs_inv_ssq + F = scipy.linalg._matfuncs_inv_ssq._logm(A) + F = _maybe_real(A, F) + errtol = 1000*eps + # TODO use a better error approximation + with np.errstate(divide='ignore', invalid='ignore'): + errest = norm(expm(F)-A, 1) / np.asarray(norm(A, 1), dtype=A.dtype).real[()] + if disp: + if not isfinite(errest) or errest >= errtol: + message = f"logm result may be inaccurate, approximate err = {errest}" + warnings.warn(message, RuntimeWarning, stacklevel=2) + return F + else: + return F, errest + + +def expm(A): + """Compute the matrix exponential of an array. + + Parameters + ---------- + A : ndarray + Input with last two dimensions are square ``(..., n, n)``. + + Returns + ------- + eA : ndarray + The resulting matrix exponential with the same shape of ``A`` + + Notes + ----- + Implements the algorithm given in [1], which is essentially a Pade + approximation with a variable order that is decided based on the array + data. + + For input with size ``n``, the memory usage is in the worst case in the + order of ``8*(n**2)``. If the input data is not of single and double + precision of real and complex dtypes, it is copied to a new array. + + For cases ``n >= 400``, the exact 1-norm computation cost, breaks even with + 1-norm estimation and from that point on the estimation scheme given in + [2] is used to decide on the approximation order. + + References + ---------- + .. [1] Awad H. Al-Mohy and Nicholas J. Higham, (2009), "A New Scaling + and Squaring Algorithm for the Matrix Exponential", SIAM J. Matrix + Anal. Appl. 31(3):970-989, :doi:`10.1137/09074721X` + + .. [2] Nicholas J. Higham and Francoise Tisseur (2000), "A Block Algorithm + for Matrix 1-Norm Estimation, with an Application to 1-Norm + Pseudospectra." SIAM J. Matrix Anal. Appl. 21(4):1185-1201, + :doi:`10.1137/S0895479899356080` + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import expm, sinm, cosm + + Matrix version of the formula exp(0) = 1: + + >>> expm(np.zeros((3, 2, 2))) + array([[[1., 0.], + [0., 1.]], + + [[1., 0.], + [0., 1.]], + + [[1., 0.], + [0., 1.]]]) + + Euler's identity (exp(i*theta) = cos(theta) + i*sin(theta)) + applied to a matrix: + + >>> a = np.array([[1.0, 2.0], [-1.0, 3.0]]) + >>> expm(1j*a) + array([[ 0.42645930+1.89217551j, -2.13721484-0.97811252j], + [ 1.06860742+0.48905626j, -1.71075555+0.91406299j]]) + >>> cosm(a) + 1j*sinm(a) + array([[ 0.42645930+1.89217551j, -2.13721484-0.97811252j], + [ 1.06860742+0.48905626j, -1.71075555+0.91406299j]]) + + """ + a = np.asarray(A) + if a.size == 1 and a.ndim < 2: + return np.array([[np.exp(a.item())]]) + + if a.ndim < 2: + raise LinAlgError('The input array must be at least two-dimensional') + if a.shape[-1] != a.shape[-2]: + raise LinAlgError('Last 2 dimensions of the array must be square') + + # Empty array + if min(*a.shape) == 0: + dtype = expm(np.eye(2, dtype=a.dtype)).dtype + return np.empty_like(a, dtype=dtype) + + # Scalar case + if a.shape[-2:] == (1, 1): + return np.exp(a) + + if not np.issubdtype(a.dtype, np.inexact): + a = a.astype(np.float64) + elif a.dtype == np.float16: + a = a.astype(np.float32) + + # An explicit formula for 2x2 case exists (formula (2.2) in [1]). However, without + # Kahan's method, numerical instabilities can occur (See gh-19584). Hence removed + # here until we have a more stable implementation. + + n = a.shape[-1] + eA = np.empty(a.shape, dtype=a.dtype) + # working memory to hold intermediate arrays + Am = np.empty((5, n, n), dtype=a.dtype) + + # Main loop to go through the slices of an ndarray and passing to expm + for ind in product(*[range(x) for x in a.shape[:-2]]): + aw = a[ind] + + lu = bandwidth(aw) + if not any(lu): # a is diagonal? + eA[ind] = np.diag(np.exp(np.diag(aw))) + continue + + # Generic/triangular case; copy the slice into scratch and send. + # Am will be mutated by pick_pade_structure + # If s != 0, scaled Am will be returned from pick_pade_structure. + Am[0, :, :] = aw + m, s = pick_pade_structure(Am) + if (m < 0): + raise MemoryError("scipy.linalg.expm could not allocate sufficient" + " memory while trying to compute the Pade " + f"structure (error code {m}).") + info = pade_UV_calc(Am, m) + if info != 0: + if info <= -11: + # We raise it from failed mallocs; negative LAPACK codes > -7 + raise MemoryError("scipy.linalg.expm could not allocate " + "sufficient memory while trying to compute the " + f"exponential (error code {info}).") + else: + # LAPACK wrong argument error or exact singularity. + # Neither should happen. + raise RuntimeError("scipy.linalg.expm got an internal LAPACK " + "error during the exponential computation " + f"(error code {info})") + eAw = Am[0] + + if s != 0: # squaring needed + + if (lu[1] == 0) or (lu[0] == 0): # lower/upper triangular + # This branch implements Code Fragment 2.1 of [1] + + diag_aw = np.diag(aw) + # einsum returns a writable view + np.einsum('ii->i', eAw)[:] = np.exp(diag_aw * 2**(-s)) + # super/sub diagonal + sd = np.diag(aw, k=-1 if lu[1] == 0 else 1) + + for i in range(s-1, -1, -1): + eAw = eAw @ eAw + + # diagonal + np.einsum('ii->i', eAw)[:] = np.exp(diag_aw * 2.**(-i)) + exp_sd = _exp_sinch(diag_aw * (2.**(-i))) * (sd * 2**(-i)) + if lu[1] == 0: # lower + np.einsum('ii->i', eAw[1:, :-1])[:] = exp_sd + else: # upper + np.einsum('ii->i', eAw[:-1, 1:])[:] = exp_sd + + else: # generic + for _ in range(s): + eAw = eAw @ eAw + + # Zero out the entries from np.empty in case of triangular input + if (lu[0] == 0) or (lu[1] == 0): + eA[ind] = np.triu(eAw) if lu[0] == 0 else np.tril(eAw) + else: + eA[ind] = eAw + + return eA + + +def _exp_sinch(x): + # Higham's formula (10.42), might overflow, see GH-11839 + lexp_diff = np.diff(np.exp(x)) + l_diff = np.diff(x) + mask_z = l_diff == 0. + lexp_diff[~mask_z] /= l_diff[~mask_z] + lexp_diff[mask_z] = np.exp(x[:-1][mask_z]) + return lexp_diff + + +def cosm(A): + """ + Compute the matrix cosine. + + This routine uses expm to compute the matrix exponentials. + + Parameters + ---------- + A : (N, N) array_like + Input array + + Returns + ------- + cosm : (N, N) ndarray + Matrix cosine of A + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import expm, sinm, cosm + + Euler's identity (exp(i*theta) = cos(theta) + i*sin(theta)) + applied to a matrix: + + >>> a = np.array([[1.0, 2.0], [-1.0, 3.0]]) + >>> expm(1j*a) + array([[ 0.42645930+1.89217551j, -2.13721484-0.97811252j], + [ 1.06860742+0.48905626j, -1.71075555+0.91406299j]]) + >>> cosm(a) + 1j*sinm(a) + array([[ 0.42645930+1.89217551j, -2.13721484-0.97811252j], + [ 1.06860742+0.48905626j, -1.71075555+0.91406299j]]) + + """ + A = _asarray_square(A) + if np.iscomplexobj(A): + return 0.5*(expm(1j*A) + expm(-1j*A)) + else: + return expm(1j*A).real + + +def sinm(A): + """ + Compute the matrix sine. + + This routine uses expm to compute the matrix exponentials. + + Parameters + ---------- + A : (N, N) array_like + Input array. + + Returns + ------- + sinm : (N, N) ndarray + Matrix sine of `A` + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import expm, sinm, cosm + + Euler's identity (exp(i*theta) = cos(theta) + i*sin(theta)) + applied to a matrix: + + >>> a = np.array([[1.0, 2.0], [-1.0, 3.0]]) + >>> expm(1j*a) + array([[ 0.42645930+1.89217551j, -2.13721484-0.97811252j], + [ 1.06860742+0.48905626j, -1.71075555+0.91406299j]]) + >>> cosm(a) + 1j*sinm(a) + array([[ 0.42645930+1.89217551j, -2.13721484-0.97811252j], + [ 1.06860742+0.48905626j, -1.71075555+0.91406299j]]) + + """ + A = _asarray_square(A) + if np.iscomplexobj(A): + return -0.5j*(expm(1j*A) - expm(-1j*A)) + else: + return expm(1j*A).imag + + +def tanm(A): + """ + Compute the matrix tangent. + + This routine uses expm to compute the matrix exponentials. + + Parameters + ---------- + A : (N, N) array_like + Input array. + + Returns + ------- + tanm : (N, N) ndarray + Matrix tangent of `A` + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import tanm, sinm, cosm + >>> a = np.array([[1.0, 3.0], [1.0, 4.0]]) + >>> t = tanm(a) + >>> t + array([[ -2.00876993, -8.41880636], + [ -2.80626879, -10.42757629]]) + + Verify tanm(a) = sinm(a).dot(inv(cosm(a))) + + >>> s = sinm(a) + >>> c = cosm(a) + >>> s.dot(np.linalg.inv(c)) + array([[ -2.00876993, -8.41880636], + [ -2.80626879, -10.42757629]]) + + """ + A = _asarray_square(A) + return _maybe_real(A, solve(cosm(A), sinm(A))) + + +def coshm(A): + """ + Compute the hyperbolic matrix cosine. + + This routine uses expm to compute the matrix exponentials. + + Parameters + ---------- + A : (N, N) array_like + Input array. + + Returns + ------- + coshm : (N, N) ndarray + Hyperbolic matrix cosine of `A` + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import tanhm, sinhm, coshm + >>> a = np.array([[1.0, 3.0], [1.0, 4.0]]) + >>> c = coshm(a) + >>> c + array([[ 11.24592233, 38.76236492], + [ 12.92078831, 50.00828725]]) + + Verify tanhm(a) = sinhm(a).dot(inv(coshm(a))) + + >>> t = tanhm(a) + >>> s = sinhm(a) + >>> t - s.dot(np.linalg.inv(c)) + array([[ 2.72004641e-15, 4.55191440e-15], + [ 0.00000000e+00, -5.55111512e-16]]) + + """ + A = _asarray_square(A) + return _maybe_real(A, 0.5 * (expm(A) + expm(-A))) + + +def sinhm(A): + """ + Compute the hyperbolic matrix sine. + + This routine uses expm to compute the matrix exponentials. + + Parameters + ---------- + A : (N, N) array_like + Input array. + + Returns + ------- + sinhm : (N, N) ndarray + Hyperbolic matrix sine of `A` + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import tanhm, sinhm, coshm + >>> a = np.array([[1.0, 3.0], [1.0, 4.0]]) + >>> s = sinhm(a) + >>> s + array([[ 10.57300653, 39.28826594], + [ 13.09608865, 49.86127247]]) + + Verify tanhm(a) = sinhm(a).dot(inv(coshm(a))) + + >>> t = tanhm(a) + >>> c = coshm(a) + >>> t - s.dot(np.linalg.inv(c)) + array([[ 2.72004641e-15, 4.55191440e-15], + [ 0.00000000e+00, -5.55111512e-16]]) + + """ + A = _asarray_square(A) + return _maybe_real(A, 0.5 * (expm(A) - expm(-A))) + + +def tanhm(A): + """ + Compute the hyperbolic matrix tangent. + + This routine uses expm to compute the matrix exponentials. + + Parameters + ---------- + A : (N, N) array_like + Input array + + Returns + ------- + tanhm : (N, N) ndarray + Hyperbolic matrix tangent of `A` + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import tanhm, sinhm, coshm + >>> a = np.array([[1.0, 3.0], [1.0, 4.0]]) + >>> t = tanhm(a) + >>> t + array([[ 0.3428582 , 0.51987926], + [ 0.17329309, 0.86273746]]) + + Verify tanhm(a) = sinhm(a).dot(inv(coshm(a))) + + >>> s = sinhm(a) + >>> c = coshm(a) + >>> t - s.dot(np.linalg.inv(c)) + array([[ 2.72004641e-15, 4.55191440e-15], + [ 0.00000000e+00, -5.55111512e-16]]) + + """ + A = _asarray_square(A) + return _maybe_real(A, solve(coshm(A), sinhm(A))) + + +def funm(A, func, disp=True): + """ + Evaluate a matrix function specified by a callable. + + Returns the value of matrix-valued function ``f`` at `A`. The + function ``f`` is an extension of the scalar-valued function `func` + to matrices. + + Parameters + ---------- + A : (N, N) array_like + Matrix at which to evaluate the function + func : callable + Callable object that evaluates a scalar function f. + Must be vectorized (eg. using vectorize). + disp : bool, optional + Print warning if error in the result is estimated large + instead of returning estimated error. (Default: True) + + Returns + ------- + funm : (N, N) ndarray + Value of the matrix function specified by func evaluated at `A` + errest : float + (if disp == False) + + 1-norm of the estimated error, ||err||_1 / ||A||_1 + + Notes + ----- + This function implements the general algorithm based on Schur decomposition + (Algorithm 9.1.1. in [1]_). + + If the input matrix is known to be diagonalizable, then relying on the + eigendecomposition is likely to be faster. For example, if your matrix is + Hermitian, you can do + + >>> from scipy.linalg import eigh + >>> def funm_herm(a, func, check_finite=False): + ... w, v = eigh(a, check_finite=check_finite) + ... ## if you further know that your matrix is positive semidefinite, + ... ## you can optionally guard against precision errors by doing + ... # w = np.maximum(w, 0) + ... w = func(w) + ... return (v * w).dot(v.conj().T) + + References + ---------- + .. [1] Gene H. Golub, Charles F. van Loan, Matrix Computations 4th ed. + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import funm + >>> a = np.array([[1.0, 3.0], [1.0, 4.0]]) + >>> funm(a, lambda x: x*x) + array([[ 4., 15.], + [ 5., 19.]]) + >>> a.dot(a) + array([[ 4., 15.], + [ 5., 19.]]) + + """ + A = _asarray_square(A) + # Perform Shur decomposition (lapack ?gees) + T, Z = schur(A) + T, Z = rsf2csf(T, Z) + n, n = T.shape + F = diag(func(diag(T))) # apply function to diagonal elements + F = F.astype(T.dtype.char) # e.g., when F is real but T is complex + + minden = abs(T[0, 0]) + + # implement Algorithm 11.1.1 from Golub and Van Loan + # "matrix Computations." + F, minden = _funm_loops(F, T, n, minden) + + F = dot(dot(Z, F), transpose(conjugate(Z))) + F = _maybe_real(A, F) + + tol = {0: feps, 1: eps}[_array_precision[F.dtype.char]] + if minden == 0.0: + minden = tol + err = min(1, max(tol, (tol/minden)*norm(triu(T, 1), 1))) + if prod(ravel(logical_not(isfinite(F))), axis=0): + err = np.inf + if disp: + if err > 1000*tol: + print("funm result may be inaccurate, approximate err =", err) + return F + else: + return F, err + + +def signm(A, disp=True): + """ + Matrix sign function. + + Extension of the scalar sign(x) to matrices. + + Parameters + ---------- + A : (N, N) array_like + Matrix at which to evaluate the sign function + disp : bool, optional + Print warning if error in the result is estimated large + instead of returning estimated error. (Default: True) + + Returns + ------- + signm : (N, N) ndarray + Value of the sign function at `A` + errest : float + (if disp == False) + + 1-norm of the estimated error, ||err||_1 / ||A||_1 + + Examples + -------- + >>> from scipy.linalg import signm, eigvals + >>> a = [[1,2,3], [1,2,1], [1,1,1]] + >>> eigvals(a) + array([ 4.12488542+0.j, -0.76155718+0.j, 0.63667176+0.j]) + >>> eigvals(signm(a)) + array([-1.+0.j, 1.+0.j, 1.+0.j]) + + """ + A = _asarray_square(A) + + def rounded_sign(x): + rx = np.real(x) + if rx.dtype.char == 'f': + c = 1e3*feps*amax(x) + else: + c = 1e3*eps*amax(x) + return sign((absolute(rx) > c) * rx) + result, errest = funm(A, rounded_sign, disp=0) + errtol = {0: 1e3*feps, 1: 1e3*eps}[_array_precision[result.dtype.char]] + if errest < errtol: + return result + + # Handle signm of defective matrices: + + # See "E.D.Denman and J.Leyva-Ramos, Appl.Math.Comp., + # 8:237-250,1981" for how to improve the following (currently a + # rather naive) iteration process: + + # a = result # sometimes iteration converges faster but where?? + + # Shifting to avoid zero eigenvalues. How to ensure that shifting does + # not change the spectrum too much? + vals = svd(A, compute_uv=False) + max_sv = np.amax(vals) + # min_nonzero_sv = vals[(vals>max_sv*errtol).tolist().count(1)-1] + # c = 0.5/min_nonzero_sv + c = 0.5/max_sv + S0 = A + c*np.identity(A.shape[0]) + prev_errest = errest + for i in range(100): + iS0 = inv(S0) + S0 = 0.5*(S0 + iS0) + Pp = 0.5*(dot(S0, S0)+S0) + errest = norm(dot(Pp, Pp)-Pp, 1) + if errest < errtol or prev_errest == errest: + break + prev_errest = errest + if disp: + if not isfinite(errest) or errest >= errtol: + print("signm result may be inaccurate, approximate err =", errest) + return S0 + else: + return S0, errest + + +def khatri_rao(a, b): + r""" + Khatri-rao product + + A column-wise Kronecker product of two matrices + + Parameters + ---------- + a : (n, k) array_like + Input array + b : (m, k) array_like + Input array + + Returns + ------- + c: (n*m, k) ndarray + Khatri-rao product of `a` and `b`. + + Notes + ----- + The mathematical definition of the Khatri-Rao product is: + + .. math:: + + (A_{ij} \bigotimes B_{ij})_{ij} + + which is the Kronecker product of every column of A and B, e.g.:: + + c = np.vstack([np.kron(a[:, k], b[:, k]) for k in range(b.shape[1])]).T + + Examples + -------- + >>> import numpy as np + >>> from scipy import linalg + >>> a = np.array([[1, 2, 3], [4, 5, 6]]) + >>> b = np.array([[3, 4, 5], [6, 7, 8], [2, 3, 9]]) + >>> linalg.khatri_rao(a, b) + array([[ 3, 8, 15], + [ 6, 14, 24], + [ 2, 6, 27], + [12, 20, 30], + [24, 35, 48], + [ 8, 15, 54]]) + + """ + a = np.asarray(a) + b = np.asarray(b) + + if not (a.ndim == 2 and b.ndim == 2): + raise ValueError("The both arrays should be 2-dimensional.") + + if not a.shape[1] == b.shape[1]: + raise ValueError("The number of columns for both arrays " + "should be equal.") + + # accommodate empty arrays + if a.size == 0 or b.size == 0: + m = a.shape[0] * b.shape[0] + n = a.shape[1] + return np.empty_like(a, shape=(m, n)) + + # c = np.vstack([np.kron(a[:, k], b[:, k]) for k in range(b.shape[1])]).T + c = a[..., :, np.newaxis, :] * b[..., np.newaxis, :, :] + return c.reshape((-1,) + c.shape[2:]) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_matfuncs_expm.pyi b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_matfuncs_expm.pyi new file mode 100644 index 0000000000000000000000000000000000000000..98ca455c6eb06c1e95e6e11d3db2dc346a295fde --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_matfuncs_expm.pyi @@ -0,0 +1,6 @@ +from numpy.typing import NDArray +from typing import Any + +def pick_pade_structure(a: NDArray[Any]) -> tuple[int, int]: ... + +def pade_UV_calc(Am: NDArray[Any], m: int) -> int: ... diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_matfuncs_inv_ssq.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_matfuncs_inv_ssq.py new file mode 100644 index 0000000000000000000000000000000000000000..1decffae2e521f0a9325b873cc33b095a4e3c166 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_matfuncs_inv_ssq.py @@ -0,0 +1,886 @@ +""" +Matrix functions that use Pade approximation with inverse scaling and squaring. + +""" +import warnings + +import numpy as np + +from scipy.linalg._matfuncs_sqrtm import SqrtmError, _sqrtm_triu +from scipy.linalg._decomp_schur import schur, rsf2csf +from scipy.linalg._matfuncs import funm +from scipy.linalg import svdvals, solve_triangular +from scipy.sparse.linalg._interface import LinearOperator +from scipy.sparse.linalg import onenormest +import scipy.special + + +class LogmRankWarning(UserWarning): + pass + + +class LogmExactlySingularWarning(LogmRankWarning): + pass + + +class LogmNearlySingularWarning(LogmRankWarning): + pass + + +class LogmError(np.linalg.LinAlgError): + pass + + +class FractionalMatrixPowerError(np.linalg.LinAlgError): + pass + + +#TODO renovate or move this class when scipy operators are more mature +class _MatrixM1PowerOperator(LinearOperator): + """ + A representation of the linear operator (A - I)^p. + """ + + def __init__(self, A, p): + if A.ndim != 2 or A.shape[0] != A.shape[1]: + raise ValueError('expected A to be like a square matrix') + if p < 0 or p != int(p): + raise ValueError('expected p to be a non-negative integer') + self._A = A + self._p = p + self.ndim = A.ndim + self.shape = A.shape + + def _matvec(self, x): + for i in range(self._p): + x = self._A.dot(x) - x + return x + + def _rmatvec(self, x): + for i in range(self._p): + x = x.dot(self._A) - x + return x + + def _matmat(self, X): + for i in range(self._p): + X = self._A.dot(X) - X + return X + + def _adjoint(self): + return _MatrixM1PowerOperator(self._A.T, self._p) + + +#TODO renovate or move this function when SciPy operators are more mature +def _onenormest_m1_power(A, p, + t=2, itmax=5, compute_v=False, compute_w=False): + """ + Efficiently estimate the 1-norm of (A - I)^p. + + Parameters + ---------- + A : ndarray + Matrix whose 1-norm of a power is to be computed. + p : int + Non-negative integer power. + t : int, optional + A positive parameter controlling the tradeoff between + accuracy versus time and memory usage. + Larger values take longer and use more memory + but give more accurate output. + itmax : int, optional + Use at most this many iterations. + compute_v : bool, optional + Request a norm-maximizing linear operator input vector if True. + compute_w : bool, optional + Request a norm-maximizing linear operator output vector if True. + + Returns + ------- + est : float + An underestimate of the 1-norm of the sparse matrix. + v : ndarray, optional + The vector such that ||Av||_1 == est*||v||_1. + It can be thought of as an input to the linear operator + that gives an output with particularly large norm. + w : ndarray, optional + The vector Av which has relatively large 1-norm. + It can be thought of as an output of the linear operator + that is relatively large in norm compared to the input. + + """ + return onenormest(_MatrixM1PowerOperator(A, p), + t=t, itmax=itmax, compute_v=compute_v, compute_w=compute_w) + + +def _unwindk(z): + """ + Compute the scalar unwinding number. + + Uses Eq. (5.3) in [1]_, and should be equal to (z - log(exp(z)) / (2 pi i). + Note that this definition differs in sign from the original definition + in equations (5, 6) in [2]_. The sign convention is justified in [3]_. + + Parameters + ---------- + z : complex + A complex number. + + Returns + ------- + unwinding_number : integer + The scalar unwinding number of z. + + References + ---------- + .. [1] Nicholas J. Higham and Lijing lin (2011) + "A Schur-Pade Algorithm for Fractional Powers of a Matrix." + SIAM Journal on Matrix Analysis and Applications, + 32 (3). pp. 1056-1078. ISSN 0895-4798 + + .. [2] Robert M. Corless and David J. Jeffrey, + "The unwinding number." Newsletter ACM SIGSAM Bulletin + Volume 30, Issue 2, June 1996, Pages 28-35. + + .. [3] Russell Bradford and Robert M. Corless and James H. Davenport and + David J. Jeffrey and Stephen M. Watt, + "Reasoning about the elementary functions of complex analysis" + Annals of Mathematics and Artificial Intelligence, + 36: 303-318, 2002. + + """ + return int(np.ceil((z.imag - np.pi) / (2*np.pi))) + + +def _briggs_helper_function(a, k): + """ + Computes r = a^(1 / (2^k)) - 1. + + This is algorithm (2) of [1]_. + The purpose is to avoid a danger of subtractive cancellation. + For more computational efficiency it should probably be cythonized. + + Parameters + ---------- + a : complex + A complex number. + k : integer + A nonnegative integer. + + Returns + ------- + r : complex + The value r = a^(1 / (2^k)) - 1 computed with less cancellation. + + Notes + ----- + The algorithm as formulated in the reference does not handle k=0 or k=1 + correctly, so these are special-cased in this implementation. + This function is intended to not allow `a` to belong to the closed + negative real axis, but this constraint is relaxed. + + References + ---------- + .. [1] Awad H. Al-Mohy (2012) + "A more accurate Briggs method for the logarithm", + Numerical Algorithms, 59 : 393--402. + + """ + if k < 0 or int(k) != k: + raise ValueError('expected a nonnegative integer k') + if k == 0: + return a - 1 + elif k == 1: + return np.sqrt(a) - 1 + else: + k_hat = k + if np.angle(a) >= np.pi / 2: + a = np.sqrt(a) + k_hat = k - 1 + z0 = a - 1 + a = np.sqrt(a) + r = 1 + a + for j in range(1, k_hat): + a = np.sqrt(a) + r = r * (1 + a) + r = z0 / r + return r + + +def _fractional_power_superdiag_entry(l1, l2, t12, p): + """ + Compute a superdiagonal entry of a fractional matrix power. + + This is Eq. (5.6) in [1]_. + + Parameters + ---------- + l1 : complex + A diagonal entry of the matrix. + l2 : complex + A diagonal entry of the matrix. + t12 : complex + A superdiagonal entry of the matrix. + p : float + A fractional power. + + Returns + ------- + f12 : complex + A superdiagonal entry of the fractional matrix power. + + Notes + ----- + Care has been taken to return a real number if possible when + all of the inputs are real numbers. + + References + ---------- + .. [1] Nicholas J. Higham and Lijing lin (2011) + "A Schur-Pade Algorithm for Fractional Powers of a Matrix." + SIAM Journal on Matrix Analysis and Applications, + 32 (3). pp. 1056-1078. ISSN 0895-4798 + + """ + if l1 == l2: + f12 = t12 * p * l1**(p-1) + elif abs(l2 - l1) > abs(l1 + l2) / 2: + f12 = t12 * ((l2**p) - (l1**p)) / (l2 - l1) + else: + # This is Eq. (5.5) in [1]. + z = (l2 - l1) / (l2 + l1) + log_l1 = np.log(l1) + log_l2 = np.log(l2) + arctanh_z = np.arctanh(z) + tmp_a = t12 * np.exp((p/2)*(log_l2 + log_l1)) + tmp_u = _unwindk(log_l2 - log_l1) + if tmp_u: + tmp_b = p * (arctanh_z + np.pi * 1j * tmp_u) + else: + tmp_b = p * arctanh_z + tmp_c = 2 * np.sinh(tmp_b) / (l2 - l1) + f12 = tmp_a * tmp_c + return f12 + + +def _logm_superdiag_entry(l1, l2, t12): + """ + Compute a superdiagonal entry of a matrix logarithm. + + This is like Eq. (11.28) in [1]_, except the determination of whether + l1 and l2 are sufficiently far apart has been modified. + + Parameters + ---------- + l1 : complex + A diagonal entry of the matrix. + l2 : complex + A diagonal entry of the matrix. + t12 : complex + A superdiagonal entry of the matrix. + + Returns + ------- + f12 : complex + A superdiagonal entry of the matrix logarithm. + + Notes + ----- + Care has been taken to return a real number if possible when + all of the inputs are real numbers. + + References + ---------- + .. [1] Nicholas J. Higham (2008) + "Functions of Matrices: Theory and Computation" + ISBN 978-0-898716-46-7 + + """ + if l1 == l2: + f12 = t12 / l1 + elif abs(l2 - l1) > abs(l1 + l2) / 2: + f12 = t12 * (np.log(l2) - np.log(l1)) / (l2 - l1) + else: + z = (l2 - l1) / (l2 + l1) + u = _unwindk(np.log(l2) - np.log(l1)) + if u: + f12 = t12 * 2 * (np.arctanh(z) + np.pi*1j*u) / (l2 - l1) + else: + f12 = t12 * 2 * np.arctanh(z) / (l2 - l1) + return f12 + + +def _inverse_squaring_helper(T0, theta): + """ + A helper function for inverse scaling and squaring for Pade approximation. + + Parameters + ---------- + T0 : (N, N) array_like upper triangular + Matrix involved in inverse scaling and squaring. + theta : indexable + The values theta[1] .. theta[7] must be available. + They represent bounds related to Pade approximation, and they depend + on the matrix function which is being computed. + For example, different values of theta are required for + matrix logarithm than for fractional matrix power. + + Returns + ------- + R : (N, N) array_like upper triangular + Composition of zero or more matrix square roots of T0, minus I. + s : non-negative integer + Number of square roots taken. + m : positive integer + The degree of the Pade approximation. + + Notes + ----- + This subroutine appears as a chunk of lines within + a couple of published algorithms; for example it appears + as lines 4--35 in algorithm (3.1) of [1]_, and + as lines 3--34 in algorithm (4.1) of [2]_. + The instances of 'goto line 38' in algorithm (3.1) of [1]_ + probably mean 'goto line 36' and have been interpreted accordingly. + + References + ---------- + .. [1] Nicholas J. Higham and Lijing Lin (2013) + "An Improved Schur-Pade Algorithm for Fractional Powers + of a Matrix and their Frechet Derivatives." + + .. [2] Awad H. Al-Mohy and Nicholas J. Higham (2012) + "Improved Inverse Scaling and Squaring Algorithms + for the Matrix Logarithm." + SIAM Journal on Scientific Computing, 34 (4). C152-C169. + ISSN 1095-7197 + + """ + if len(T0.shape) != 2 or T0.shape[0] != T0.shape[1]: + raise ValueError('expected an upper triangular square matrix') + n, n = T0.shape + T = T0 + + # Find s0, the smallest s such that the spectral radius + # of a certain diagonal matrix is at most theta[7]. + # Note that because theta[7] < 1, + # this search will not terminate if any diagonal entry of T is zero. + s0 = 0 + tmp_diag = np.diag(T) + if np.count_nonzero(tmp_diag) != n: + raise Exception('Diagonal entries of T must be nonzero') + while np.max(np.absolute(tmp_diag - 1), initial=0.) > theta[7]: + tmp_diag = np.sqrt(tmp_diag) + s0 += 1 + + # Take matrix square roots of T. + for i in range(s0): + T = _sqrtm_triu(T) + + # Flow control in this section is a little odd. + # This is because I am translating algorithm descriptions + # which have GOTOs in the publication. + s = s0 + k = 0 + d2 = _onenormest_m1_power(T, 2) ** (1/2) + d3 = _onenormest_m1_power(T, 3) ** (1/3) + a2 = max(d2, d3) + m = None + for i in (1, 2): + if a2 <= theta[i]: + m = i + break + while m is None: + if s > s0: + d3 = _onenormest_m1_power(T, 3) ** (1/3) + d4 = _onenormest_m1_power(T, 4) ** (1/4) + a3 = max(d3, d4) + if a3 <= theta[7]: + j1 = min(i for i in (3, 4, 5, 6, 7) if a3 <= theta[i]) + if j1 <= 6: + m = j1 + break + elif a3 / 2 <= theta[5] and k < 2: + k += 1 + T = _sqrtm_triu(T) + s += 1 + continue + d5 = _onenormest_m1_power(T, 5) ** (1/5) + a4 = max(d4, d5) + eta = min(a3, a4) + for i in (6, 7): + if eta <= theta[i]: + m = i + break + if m is not None: + break + T = _sqrtm_triu(T) + s += 1 + + # The subtraction of the identity is redundant here, + # because the diagonal will be replaced for improved numerical accuracy, + # but this formulation should help clarify the meaning of R. + R = T - np.identity(n) + + # Replace the diagonal and first superdiagonal of T0^(1/(2^s)) - I + # using formulas that have less subtractive cancellation. + # Skip this step if the principal branch + # does not exist at T0; this happens when a diagonal entry of T0 + # is negative with imaginary part 0. + has_principal_branch = all(x.real > 0 or x.imag != 0 for x in np.diag(T0)) + if has_principal_branch: + for j in range(n): + a = T0[j, j] + r = _briggs_helper_function(a, s) + R[j, j] = r + p = np.exp2(-s) + for j in range(n-1): + l1 = T0[j, j] + l2 = T0[j+1, j+1] + t12 = T0[j, j+1] + f12 = _fractional_power_superdiag_entry(l1, l2, t12, p) + R[j, j+1] = f12 + + # Return the T-I matrix, the number of square roots, and the Pade degree. + if not np.array_equal(R, np.triu(R)): + raise Exception('R is not upper triangular') + return R, s, m + + +def _fractional_power_pade_constant(i, t): + # A helper function for matrix fractional power. + if i < 1: + raise ValueError('expected a positive integer i') + if not (-1 < t < 1): + raise ValueError('expected -1 < t < 1') + if i == 1: + return -t + elif i % 2 == 0: + j = i // 2 + return (-j + t) / (2 * (2*j - 1)) + elif i % 2 == 1: + j = (i - 1) // 2 + return (-j - t) / (2 * (2*j + 1)) + else: + raise Exception(f'unnexpected value of i, i = {i}') + + +def _fractional_power_pade(R, t, m): + """ + Evaluate the Pade approximation of a fractional matrix power. + + Evaluate the degree-m Pade approximation of R + to the fractional matrix power t using the continued fraction + in bottom-up fashion using algorithm (4.1) in [1]_. + + Parameters + ---------- + R : (N, N) array_like + Upper triangular matrix whose fractional power to evaluate. + t : float + Fractional power between -1 and 1 exclusive. + m : positive integer + Degree of Pade approximation. + + Returns + ------- + U : (N, N) array_like + The degree-m Pade approximation of R to the fractional power t. + This matrix will be upper triangular. + + References + ---------- + .. [1] Nicholas J. Higham and Lijing lin (2011) + "A Schur-Pade Algorithm for Fractional Powers of a Matrix." + SIAM Journal on Matrix Analysis and Applications, + 32 (3). pp. 1056-1078. ISSN 0895-4798 + + """ + if m < 1 or int(m) != m: + raise ValueError('expected a positive integer m') + if not (-1 < t < 1): + raise ValueError('expected -1 < t < 1') + R = np.asarray(R) + if len(R.shape) != 2 or R.shape[0] != R.shape[1]: + raise ValueError('expected an upper triangular square matrix') + n, n = R.shape + ident = np.identity(n) + Y = R * _fractional_power_pade_constant(2*m, t) + for j in range(2*m - 1, 0, -1): + rhs = R * _fractional_power_pade_constant(j, t) + Y = solve_triangular(ident + Y, rhs) + U = ident + Y + if not np.array_equal(U, np.triu(U)): + raise Exception('U is not upper triangular') + return U + + +def _remainder_matrix_power_triu(T, t): + """ + Compute a fractional power of an upper triangular matrix. + + The fractional power is restricted to fractions -1 < t < 1. + This uses algorithm (3.1) of [1]_. + The Pade approximation itself uses algorithm (4.1) of [2]_. + + Parameters + ---------- + T : (N, N) array_like + Upper triangular matrix whose fractional power to evaluate. + t : float + Fractional power between -1 and 1 exclusive. + + Returns + ------- + X : (N, N) array_like + The fractional power of the matrix. + + References + ---------- + .. [1] Nicholas J. Higham and Lijing Lin (2013) + "An Improved Schur-Pade Algorithm for Fractional Powers + of a Matrix and their Frechet Derivatives." + + .. [2] Nicholas J. Higham and Lijing lin (2011) + "A Schur-Pade Algorithm for Fractional Powers of a Matrix." + SIAM Journal on Matrix Analysis and Applications, + 32 (3). pp. 1056-1078. ISSN 0895-4798 + + """ + m_to_theta = { + 1: 1.51e-5, + 2: 2.24e-3, + 3: 1.88e-2, + 4: 6.04e-2, + 5: 1.24e-1, + 6: 2.00e-1, + 7: 2.79e-1, + } + n, n = T.shape + T0 = T + T0_diag = np.diag(T0) + if np.array_equal(T0, np.diag(T0_diag)): + U = np.diag(T0_diag ** t) + else: + R, s, m = _inverse_squaring_helper(T0, m_to_theta) + + # Evaluate the Pade approximation. + # Note that this function expects the negative of the matrix + # returned by the inverse squaring helper. + U = _fractional_power_pade(-R, t, m) + + # Undo the inverse scaling and squaring. + # Be less clever about this + # if the principal branch does not exist at T0; + # this happens when a diagonal entry of T0 + # is negative with imaginary part 0. + eivals = np.diag(T0) + has_principal_branch = all(x.real > 0 or x.imag != 0 for x in eivals) + for i in range(s, -1, -1): + if i < s: + U = U.dot(U) + else: + if has_principal_branch: + p = t * np.exp2(-i) + U[np.diag_indices(n)] = T0_diag ** p + for j in range(n-1): + l1 = T0[j, j] + l2 = T0[j+1, j+1] + t12 = T0[j, j+1] + f12 = _fractional_power_superdiag_entry(l1, l2, t12, p) + U[j, j+1] = f12 + if not np.array_equal(U, np.triu(U)): + raise Exception('U is not upper triangular') + return U + + +def _remainder_matrix_power(A, t): + """ + Compute the fractional power of a matrix, for fractions -1 < t < 1. + + This uses algorithm (3.1) of [1]_. + The Pade approximation itself uses algorithm (4.1) of [2]_. + + Parameters + ---------- + A : (N, N) array_like + Matrix whose fractional power to evaluate. + t : float + Fractional power between -1 and 1 exclusive. + + Returns + ------- + X : (N, N) array_like + The fractional power of the matrix. + + References + ---------- + .. [1] Nicholas J. Higham and Lijing Lin (2013) + "An Improved Schur-Pade Algorithm for Fractional Powers + of a Matrix and their Frechet Derivatives." + + .. [2] Nicholas J. Higham and Lijing lin (2011) + "A Schur-Pade Algorithm for Fractional Powers of a Matrix." + SIAM Journal on Matrix Analysis and Applications, + 32 (3). pp. 1056-1078. ISSN 0895-4798 + + """ + # This code block is copied from numpy.matrix_power(). + A = np.asarray(A) + if len(A.shape) != 2 or A.shape[0] != A.shape[1]: + raise ValueError('input must be a square array') + + # Get the number of rows and columns. + n, n = A.shape + + # Triangularize the matrix if necessary, + # attempting to preserve dtype if possible. + if np.array_equal(A, np.triu(A)): + Z = None + T = A + else: + if np.isrealobj(A): + T, Z = schur(A) + if not np.array_equal(T, np.triu(T)): + T, Z = rsf2csf(T, Z) + else: + T, Z = schur(A, output='complex') + + # Zeros on the diagonal of the triangular matrix are forbidden, + # because the inverse scaling and squaring cannot deal with it. + T_diag = np.diag(T) + if np.count_nonzero(T_diag) != n: + raise FractionalMatrixPowerError( + 'cannot use inverse scaling and squaring to find ' + 'the fractional matrix power of a singular matrix') + + # If the triangular matrix is real and has a negative + # entry on the diagonal, then force the matrix to be complex. + if np.isrealobj(T) and np.min(T_diag) < 0: + T = T.astype(complex) + + # Get the fractional power of the triangular matrix, + # and de-triangularize it if necessary. + U = _remainder_matrix_power_triu(T, t) + if Z is not None: + ZH = np.conjugate(Z).T + return Z.dot(U).dot(ZH) + else: + return U + + +def _fractional_matrix_power(A, p): + """ + Compute the fractional power of a matrix. + + See the fractional_matrix_power docstring in matfuncs.py for more info. + + """ + A = np.asarray(A) + if len(A.shape) != 2 or A.shape[0] != A.shape[1]: + raise ValueError('expected a square matrix') + if p == int(p): + return np.linalg.matrix_power(A, int(p)) + # Compute singular values. + s = svdvals(A) + # Inverse scaling and squaring cannot deal with a singular matrix, + # because the process of repeatedly taking square roots + # would not converge to the identity matrix. + if s[-1]: + # Compute the condition number relative to matrix inversion, + # and use this to decide between floor(p) and ceil(p). + k2 = s[0] / s[-1] + p1 = p - np.floor(p) + p2 = p - np.ceil(p) + if p1 * k2 ** (1 - p1) <= -p2 * k2: + a = int(np.floor(p)) + b = p1 + else: + a = int(np.ceil(p)) + b = p2 + try: + R = _remainder_matrix_power(A, b) + Q = np.linalg.matrix_power(A, a) + return Q.dot(R) + except np.linalg.LinAlgError: + pass + # If p is negative then we are going to give up. + # If p is non-negative then we can fall back to generic funm. + if p < 0: + X = np.empty_like(A) + X.fill(np.nan) + return X + else: + p1 = p - np.floor(p) + a = int(np.floor(p)) + b = p1 + R, info = funm(A, lambda x: pow(x, b), disp=False) + Q = np.linalg.matrix_power(A, a) + return Q.dot(R) + + +def _logm_triu(T): + """ + Compute matrix logarithm of an upper triangular matrix. + + The matrix logarithm is the inverse of + expm: expm(logm(`T`)) == `T` + + Parameters + ---------- + T : (N, N) array_like + Upper triangular matrix whose logarithm to evaluate + + Returns + ------- + logm : (N, N) ndarray + Matrix logarithm of `T` + + References + ---------- + .. [1] Awad H. Al-Mohy and Nicholas J. Higham (2012) + "Improved Inverse Scaling and Squaring Algorithms + for the Matrix Logarithm." + SIAM Journal on Scientific Computing, 34 (4). C152-C169. + ISSN 1095-7197 + + .. [2] Nicholas J. Higham (2008) + "Functions of Matrices: Theory and Computation" + ISBN 978-0-898716-46-7 + + .. [3] Nicholas J. Higham and Lijing lin (2011) + "A Schur-Pade Algorithm for Fractional Powers of a Matrix." + SIAM Journal on Matrix Analysis and Applications, + 32 (3). pp. 1056-1078. ISSN 0895-4798 + + """ + T = np.asarray(T) + if len(T.shape) != 2 or T.shape[0] != T.shape[1]: + raise ValueError('expected an upper triangular square matrix') + n, n = T.shape + + # Construct T0 with the appropriate type, + # depending on the dtype and the spectrum of T. + T_diag = np.diag(T) + keep_it_real = np.isrealobj(T) and np.min(T_diag, initial=0.) >= 0 + if keep_it_real: + T0 = T + else: + T0 = T.astype(complex) + + # Define bounds given in Table (2.1). + theta = (None, + 1.59e-5, 2.31e-3, 1.94e-2, 6.21e-2, + 1.28e-1, 2.06e-1, 2.88e-1, 3.67e-1, + 4.39e-1, 5.03e-1, 5.60e-1, 6.09e-1, + 6.52e-1, 6.89e-1, 7.21e-1, 7.49e-1) + + R, s, m = _inverse_squaring_helper(T0, theta) + + # Evaluate U = 2**s r_m(T - I) using the partial fraction expansion (1.1). + # This requires the nodes and weights + # corresponding to degree-m Gauss-Legendre quadrature. + # These quadrature arrays need to be transformed from the [-1, 1] interval + # to the [0, 1] interval. + nodes, weights = scipy.special.p_roots(m) + nodes = nodes.real + if nodes.shape != (m,) or weights.shape != (m,): + raise Exception('internal error') + nodes = 0.5 + 0.5 * nodes + weights = 0.5 * weights + ident = np.identity(n) + U = np.zeros_like(R) + for alpha, beta in zip(weights, nodes): + U += solve_triangular(ident + beta*R, alpha*R) + U *= np.exp2(s) + + # Skip this step if the principal branch + # does not exist at T0; this happens when a diagonal entry of T0 + # is negative with imaginary part 0. + has_principal_branch = all(x.real > 0 or x.imag != 0 for x in np.diag(T0)) + if has_principal_branch: + + # Recompute diagonal entries of U. + U[np.diag_indices(n)] = np.log(np.diag(T0)) + + # Recompute superdiagonal entries of U. + # This indexing of this code should be renovated + # when newer np.diagonal() becomes available. + for i in range(n-1): + l1 = T0[i, i] + l2 = T0[i+1, i+1] + t12 = T0[i, i+1] + U[i, i+1] = _logm_superdiag_entry(l1, l2, t12) + + # Return the logm of the upper triangular matrix. + if not np.array_equal(U, np.triu(U)): + raise Exception('U is not upper triangular') + return U + + +def _logm_force_nonsingular_triangular_matrix(T, inplace=False): + # The input matrix should be upper triangular. + # The eps is ad hoc and is not meant to be machine precision. + tri_eps = 1e-20 + abs_diag = np.absolute(np.diag(T)) + if np.any(abs_diag == 0): + exact_singularity_msg = 'The logm input matrix is exactly singular.' + warnings.warn(exact_singularity_msg, LogmExactlySingularWarning, stacklevel=3) + if not inplace: + T = T.copy() + n = T.shape[0] + for i in range(n): + if not T[i, i]: + T[i, i] = tri_eps + elif np.any(abs_diag < tri_eps): + near_singularity_msg = 'The logm input matrix may be nearly singular.' + warnings.warn(near_singularity_msg, LogmNearlySingularWarning, stacklevel=3) + return T + + +def _logm(A): + """ + Compute the matrix logarithm. + + See the logm docstring in matfuncs.py for more info. + + Notes + ----- + In this function we look at triangular matrices that are similar + to the input matrix. If any diagonal entry of such a triangular matrix + is exactly zero then the original matrix is singular. + The matrix logarithm does not exist for such matrices, + but in such cases we will pretend that the diagonal entries that are zero + are actually slightly positive by an ad-hoc amount, in the interest + of returning something more useful than NaN. This will cause a warning. + + """ + A = np.asarray(A) + if len(A.shape) != 2 or A.shape[0] != A.shape[1]: + raise ValueError('expected a square matrix') + + # If the input matrix dtype is integer then copy to a float dtype matrix. + if issubclass(A.dtype.type, np.integer): + A = np.asarray(A, dtype=float) + + keep_it_real = np.isrealobj(A) + try: + if np.array_equal(A, np.triu(A)): + A = _logm_force_nonsingular_triangular_matrix(A) + if np.min(np.diag(A), initial=0.) < 0: + A = A.astype(complex) + return _logm_triu(A) + else: + if keep_it_real: + T, Z = schur(A) + if not np.array_equal(T, np.triu(T)): + T, Z = rsf2csf(T, Z) + else: + T, Z = schur(A, output='complex') + T = _logm_force_nonsingular_triangular_matrix(T, inplace=True) + U = _logm_triu(T) + ZH = np.conjugate(Z).T + return Z.dot(U).dot(ZH) + except (SqrtmError, LogmError): + X = np.empty_like(A) + X.fill(np.nan) + return X diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_matfuncs_sqrtm.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_matfuncs_sqrtm.py new file mode 100644 index 0000000000000000000000000000000000000000..b7da6ced474ee3db548a24ecc08d7e2627f0d7a4 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_matfuncs_sqrtm.py @@ -0,0 +1,205 @@ +""" +Matrix square root for general matrices and for upper triangular matrices. + +This module exists to avoid cyclic imports. + +""" +__all__ = ['sqrtm'] + +import numpy as np + +from scipy._lib._util import _asarray_validated + +# Local imports +from ._misc import norm +from .lapack import ztrsyl, dtrsyl +from ._decomp_schur import schur, rsf2csf +from ._basic import _ensure_dtype_cdsz + + + +class SqrtmError(np.linalg.LinAlgError): + pass + + +from ._matfuncs_sqrtm_triu import within_block_loop # noqa: E402 + + +def _sqrtm_triu(T, blocksize=64): + """ + Matrix square root of an upper triangular matrix. + + This is a helper function for `sqrtm` and `logm`. + + Parameters + ---------- + T : (N, N) array_like upper triangular + Matrix whose square root to evaluate + blocksize : int, optional + If the blocksize is not degenerate with respect to the + size of the input array, then use a blocked algorithm. (Default: 64) + + Returns + ------- + sqrtm : (N, N) ndarray + Value of the sqrt function at `T` + + References + ---------- + .. [1] Edvin Deadman, Nicholas J. Higham, Rui Ralha (2013) + "Blocked Schur Algorithms for Computing the Matrix Square Root, + Lecture Notes in Computer Science, 7782. pp. 171-182. + + """ + T_diag = np.diag(T) + keep_it_real = np.isrealobj(T) and np.min(T_diag, initial=0.) >= 0 + + # Cast to complex as necessary + ensure double precision + if not keep_it_real: + T = np.asarray(T, dtype=np.complex128, order="C") + T_diag = np.asarray(T_diag, dtype=np.complex128) + else: + T = np.asarray(T, dtype=np.float64, order="C") + T_diag = np.asarray(T_diag, dtype=np.float64) + + R = np.diag(np.sqrt(T_diag)) + + # Compute the number of blocks to use; use at least one block. + n, n = T.shape + nblocks = max(n // blocksize, 1) + + # Compute the smaller of the two sizes of blocks that + # we will actually use, and compute the number of large blocks. + bsmall, nlarge = divmod(n, nblocks) + blarge = bsmall + 1 + nsmall = nblocks - nlarge + if nsmall * bsmall + nlarge * blarge != n: + raise Exception('internal inconsistency') + + # Define the index range covered by each block. + start_stop_pairs = [] + start = 0 + for count, size in ((nsmall, bsmall), (nlarge, blarge)): + for i in range(count): + start_stop_pairs.append((start, start + size)) + start += size + + # Within-block interactions (Cythonized) + try: + within_block_loop(R, T, start_stop_pairs, nblocks) + except RuntimeError as e: + raise SqrtmError(*e.args) from e + + # Between-block interactions (Cython would give no significant speedup) + for j in range(nblocks): + jstart, jstop = start_stop_pairs[j] + for i in range(j-1, -1, -1): + istart, istop = start_stop_pairs[i] + S = T[istart:istop, jstart:jstop] + if j - i > 1: + S = S - R[istart:istop, istop:jstart].dot(R[istop:jstart, + jstart:jstop]) + + # Invoke LAPACK. + # For more details, see the solve_sylvester implementation + # and the fortran dtrsyl and ztrsyl docs. + Rii = R[istart:istop, istart:istop] + Rjj = R[jstart:jstop, jstart:jstop] + if keep_it_real: + x, scale, info = dtrsyl(Rii, Rjj, S) + else: + x, scale, info = ztrsyl(Rii, Rjj, S) + R[istart:istop, jstart:jstop] = x * scale + + # Return the matrix square root. + return R + + +def sqrtm(A, disp=True, blocksize=64): + """ + Matrix square root. + + Parameters + ---------- + A : (N, N) array_like + Matrix whose square root to evaluate + disp : bool, optional + Print warning if error in the result is estimated large + instead of returning estimated error. (Default: True) + blocksize : integer, optional + If the blocksize is not degenerate with respect to the + size of the input array, then use a blocked algorithm. (Default: 64) + + Returns + ------- + sqrtm : (N, N) ndarray + Value of the sqrt function at `A`. The dtype is float or complex. + The precision (data size) is determined based on the precision of + input `A`. + + errest : float + (if disp == False) + + Frobenius norm of the estimated error, ||err||_F / ||A||_F + + References + ---------- + .. [1] Edvin Deadman, Nicholas J. Higham, Rui Ralha (2013) + "Blocked Schur Algorithms for Computing the Matrix Square Root, + Lecture Notes in Computer Science, 7782. pp. 171-182. + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import sqrtm + >>> a = np.array([[1.0, 3.0], [1.0, 4.0]]) + >>> r = sqrtm(a) + >>> r + array([[ 0.75592895, 1.13389342], + [ 0.37796447, 1.88982237]]) + >>> r.dot(r) + array([[ 1., 3.], + [ 1., 4.]]) + + """ + A = _asarray_validated(A, check_finite=True, as_inexact=True) + if len(A.shape) != 2: + raise ValueError("Non-matrix input to matrix function.") + if blocksize < 1: + raise ValueError("The blocksize should be at least 1.") + A, = _ensure_dtype_cdsz(A) + keep_it_real = np.isrealobj(A) + if keep_it_real: + T, Z = schur(A) + d0 = np.diagonal(T) + d1 = np.diagonal(T, -1) + eps = np.finfo(T.dtype).eps + needs_conversion = abs(d1) > eps * (abs(d0[1:]) + abs(d0[:-1])) + if needs_conversion.any(): + T, Z = rsf2csf(T, Z) + else: + T, Z = schur(A, output='complex') + failflag = False + try: + R = _sqrtm_triu(T, blocksize=blocksize) + ZH = np.conjugate(Z).T + X = Z.dot(R).dot(ZH) + dtype = np.result_type(A.dtype, 1j if np.iscomplexobj(X) else 1) + X = X.astype(dtype, copy=False) + except SqrtmError: + failflag = True + X = np.empty_like(A) + X.fill(np.nan) + + if disp: + if failflag: + print("Failed to find a square root.") + return X + else: + try: + arg2 = norm(X.dot(X) - A, 'fro')**2 / norm(A, 'fro') + except ValueError: + # NaNs in matrix + arg2 = np.inf + + return X, arg2 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_misc.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_misc.py new file mode 100644 index 0000000000000000000000000000000000000000..27cd442080c8569417694a8a612fe0a461c1a2ca --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_misc.py @@ -0,0 +1,191 @@ +import numpy as np +from numpy.linalg import LinAlgError +from .blas import get_blas_funcs +from .lapack import get_lapack_funcs + +__all__ = ['LinAlgError', 'LinAlgWarning', 'norm'] + + +class LinAlgWarning(RuntimeWarning): + """ + The warning emitted when a linear algebra related operation is close + to fail conditions of the algorithm or loss of accuracy is expected. + """ + pass + + +def norm(a, ord=None, axis=None, keepdims=False, check_finite=True): + """ + Matrix or vector norm. + + This function is able to return one of eight different matrix norms, + or one of an infinite number of vector norms (described below), depending + on the value of the ``ord`` parameter. For tensors with rank different from + 1 or 2, only `ord=None` is supported. + + Parameters + ---------- + a : array_like + Input array. If `axis` is None, `a` must be 1-D or 2-D, unless `ord` + is None. If both `axis` and `ord` are None, the 2-norm of + ``a.ravel`` will be returned. + ord : {int, inf, -inf, 'fro', 'nuc', None}, optional + Order of the norm (see table under ``Notes``). inf means NumPy's + `inf` object. + axis : {int, 2-tuple of ints, None}, optional + If `axis` is an integer, it specifies the axis of `a` along which to + compute the vector norms. If `axis` is a 2-tuple, it specifies the + axes that hold 2-D matrices, and the matrix norms of these matrices + are computed. If `axis` is None then either a vector norm (when `a` + is 1-D) or a matrix norm (when `a` is 2-D) is returned. + keepdims : bool, optional + If this is set to True, the axes which are normed over are left in the + result as dimensions with size one. With this option the result will + broadcast correctly against the original `a`. + check_finite : bool, optional + Whether to check that the input matrix contains only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + + Returns + ------- + n : float or ndarray + Norm of the matrix or vector(s). + + Notes + ----- + For values of ``ord <= 0``, the result is, strictly speaking, not a + mathematical 'norm', but it may still be useful for various numerical + purposes. + + The following norms can be calculated: + + ===== ============================ ========================== + ord norm for matrices norm for vectors + ===== ============================ ========================== + None Frobenius norm 2-norm + 'fro' Frobenius norm -- + 'nuc' nuclear norm -- + inf max(sum(abs(a), axis=1)) max(abs(a)) + -inf min(sum(abs(a), axis=1)) min(abs(a)) + 0 -- sum(a != 0) + 1 max(sum(abs(a), axis=0)) as below + -1 min(sum(abs(a), axis=0)) as below + 2 2-norm (largest sing. value) as below + -2 smallest singular value as below + other -- sum(abs(a)**ord)**(1./ord) + ===== ============================ ========================== + + The Frobenius norm is given by [1]_: + + :math:`||A||_F = [\\sum_{i,j} abs(a_{i,j})^2]^{1/2}` + + The nuclear norm is the sum of the singular values. + + Both the Frobenius and nuclear norm orders are only defined for + matrices. + + References + ---------- + .. [1] G. H. Golub and C. F. Van Loan, *Matrix Computations*, + Baltimore, MD, Johns Hopkins University Press, 1985, pg. 15 + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import norm + >>> a = np.arange(9) - 4.0 + >>> a + array([-4., -3., -2., -1., 0., 1., 2., 3., 4.]) + >>> b = a.reshape((3, 3)) + >>> b + array([[-4., -3., -2.], + [-1., 0., 1.], + [ 2., 3., 4.]]) + + >>> norm(a) + 7.745966692414834 + >>> norm(b) + 7.745966692414834 + >>> norm(b, 'fro') + 7.745966692414834 + >>> norm(a, np.inf) + 4.0 + >>> norm(b, np.inf) + 9.0 + >>> norm(a, -np.inf) + 0.0 + >>> norm(b, -np.inf) + 2.0 + + >>> norm(a, 1) + 20.0 + >>> norm(b, 1) + 7.0 + >>> norm(a, -1) + -4.6566128774142013e-010 + >>> norm(b, -1) + 6.0 + >>> norm(a, 2) + 7.745966692414834 + >>> norm(b, 2) + 7.3484692283495345 + + >>> norm(a, -2) + 0.0 + >>> norm(b, -2) + 1.8570331885190563e-016 + >>> norm(a, 3) + 5.8480354764257312 + >>> norm(a, -3) + 0.0 + + """ + # Differs from numpy only in non-finite handling and the use of blas. + if check_finite: + a = np.asarray_chkfinite(a) + else: + a = np.asarray(a) + + if a.size and a.dtype.char in 'fdFD' and axis is None and not keepdims: + + if ord in (None, 2) and (a.ndim == 1): + # use blas for fast and stable euclidean norm + nrm2 = get_blas_funcs('nrm2', dtype=a.dtype, ilp64='preferred') + return nrm2(a) + + if a.ndim == 2: + # Use lapack for a couple fast matrix norms. + # For some reason the *lange frobenius norm is slow. + lange_args = None + # Make sure this works if the user uses the axis keywords + # to apply the norm to the transpose. + if ord == 1: + if np.isfortran(a): + lange_args = '1', a + elif np.isfortran(a.T): + lange_args = 'i', a.T + elif ord == np.inf: + if np.isfortran(a): + lange_args = 'i', a + elif np.isfortran(a.T): + lange_args = '1', a.T + if lange_args: + lange = get_lapack_funcs('lange', dtype=a.dtype, ilp64='preferred') + return lange(*lange_args) + + # fall back to numpy in every other case + return np.linalg.norm(a, ord=ord, axis=axis, keepdims=keepdims) + + +def _datacopied(arr, original): + """ + Strict check for `arr` not sharing any data with `original`, + under the assumption that arr = asarray(original) + + """ + if arr is original: + return False + if not isinstance(original, np.ndarray) and hasattr(original, '__array__'): + return False + return arr.base is None diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_procrustes.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_procrustes.py new file mode 100644 index 0000000000000000000000000000000000000000..7d68f0b737ead5d581095ad32a34ae88d153264c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_procrustes.py @@ -0,0 +1,111 @@ +""" +Solve the orthogonal Procrustes problem. + +""" +import numpy as np +from ._decomp_svd import svd + + +__all__ = ['orthogonal_procrustes'] + + +def orthogonal_procrustes(A, B, check_finite=True): + """ + Compute the matrix solution of the orthogonal (or unitary) Procrustes problem. + + Given matrices `A` and `B` of the same shape, find an orthogonal (or unitary in + the case of complex input) matrix `R` that most closely maps `A` to `B` using the + algorithm given in [1]_. + + Parameters + ---------- + A : (M, N) array_like + Matrix to be mapped. + B : (M, N) array_like + Target matrix. + check_finite : bool, optional + Whether to check that the input matrices contain only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + + Returns + ------- + R : (N, N) ndarray + The matrix solution of the orthogonal Procrustes problem. + Minimizes the Frobenius norm of ``(A @ R) - B``, subject to + ``R.conj().T @ R = I``. + scale : float + Sum of the singular values of ``A.conj().T @ B``. + + Raises + ------ + ValueError + If the input array shapes don't match or if check_finite is True and + the arrays contain Inf or NaN. + + Notes + ----- + Note that unlike higher level Procrustes analyses of spatial data, this + function only uses orthogonal transformations like rotations and + reflections, and it does not use scaling or translation. + + .. versionadded:: 0.15.0 + + References + ---------- + .. [1] Peter H. Schonemann, "A generalized solution of the orthogonal + Procrustes problem", Psychometrica -- Vol. 31, No. 1, March, 1966. + :doi:`10.1007/BF02289451` + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import orthogonal_procrustes + >>> A = np.array([[ 2, 0, 1], [-2, 0, 0]]) + + Flip the order of columns and check for the anti-diagonal mapping + + >>> R, sca = orthogonal_procrustes(A, np.fliplr(A)) + >>> R + array([[-5.34384992e-17, 0.00000000e+00, 1.00000000e+00], + [ 0.00000000e+00, 1.00000000e+00, 0.00000000e+00], + [ 1.00000000e+00, 0.00000000e+00, -7.85941422e-17]]) + >>> sca + 9.0 + + As an example of the unitary Procrustes problem, generate a + random complex matrix ``A``, a random unitary matrix ``Q``, + and their product ``B``. + + >>> shape = (4, 4) + >>> rng = np.random.default_rng(589234981235) + >>> A = rng.random(shape) + rng.random(shape)*1j + >>> Q = rng.random(shape) + rng.random(shape)*1j + >>> Q, _ = np.linalg.qr(Q) + >>> B = A @ Q + + `orthogonal_procrustes` recovers the unitary matrix ``Q`` + from ``A`` and ``B``. + + >>> R, _ = orthogonal_procrustes(A, B) + >>> np.allclose(R, Q) + True + + """ + if check_finite: + A = np.asarray_chkfinite(A) + B = np.asarray_chkfinite(B) + else: + A = np.asanyarray(A) + B = np.asanyarray(B) + if A.ndim != 2: + raise ValueError(f'expected ndim to be 2, but observed {A.ndim}') + if A.shape != B.shape: + raise ValueError(f'the shapes of A and B differ ({A.shape} vs {B.shape})') + # Be clever with transposes, with the intention to save memory. + # The conjugate has no effect for real inputs, but gives the correct solution + # for complex inputs. + u, w, vt = svd((B.T @ np.conjugate(A)).T) + R = u @ vt + scale = w.sum() + return R, scale diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_sketches.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_sketches.py new file mode 100644 index 0000000000000000000000000000000000000000..589172827f528799203cb3e93a4a013e07dc5ff8 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_sketches.py @@ -0,0 +1,178 @@ +""" Sketching-based Matrix Computations """ + +# Author: Jordi Montes +# August 28, 2017 + +import numpy as np + +from scipy._lib._util import (check_random_state, rng_integers, + _transition_to_rng) +from scipy.sparse import csc_matrix + +__all__ = ['clarkson_woodruff_transform'] + + +def cwt_matrix(n_rows, n_columns, rng=None): + r""" + Generate a matrix S which represents a Clarkson-Woodruff transform. + + Given the desired size of matrix, the method returns a matrix S of size + (n_rows, n_columns) where each column has all the entries set to 0 + except for one position which has been randomly set to +1 or -1 with + equal probability. + + Parameters + ---------- + n_rows : int + Number of rows of S + n_columns : int + Number of columns of S + rng : `numpy.random.Generator`, optional + Pseudorandom number generator state. When `rng` is None, a new + `numpy.random.Generator` is created using entropy from the + operating system. Types other than `numpy.random.Generator` are + passed to `numpy.random.default_rng` to instantiate a ``Generator``. + + + Returns + ------- + S : (n_rows, n_columns) csc_matrix + The returned matrix has ``n_columns`` nonzero entries. + + Notes + ----- + Given a matrix A, with probability at least 9/10, + .. math:: \|SA\| = (1 \pm \epsilon)\|A\| + Where the error epsilon is related to the size of S. + """ + rng = check_random_state(rng) + rows = rng_integers(rng, 0, n_rows, n_columns) + cols = np.arange(n_columns+1) + signs = rng.choice([1, -1], n_columns) + S = csc_matrix((signs, rows, cols), shape=(n_rows, n_columns)) + return S + + +@_transition_to_rng("seed", position_num=2) +def clarkson_woodruff_transform(input_matrix, sketch_size, rng=None): + r""" + Applies a Clarkson-Woodruff Transform/sketch to the input matrix. + + Given an input_matrix ``A`` of size ``(n, d)``, compute a matrix ``A'`` of + size (sketch_size, d) so that + + .. math:: \|Ax\| \approx \|A'x\| + + with high probability via the Clarkson-Woodruff Transform, otherwise + known as the CountSketch matrix. + + Parameters + ---------- + input_matrix : array_like + Input matrix, of shape ``(n, d)``. + sketch_size : int + Number of rows for the sketch. + rng : `numpy.random.Generator`, optional + Pseudorandom number generator state. When `rng` is None, a new + `numpy.random.Generator` is created using entropy from the + operating system. Types other than `numpy.random.Generator` are + passed to `numpy.random.default_rng` to instantiate a ``Generator``. + + Returns + ------- + A' : array_like + Sketch of the input matrix ``A``, of size ``(sketch_size, d)``. + + Notes + ----- + To make the statement + + .. math:: \|Ax\| \approx \|A'x\| + + precise, observe the following result which is adapted from the + proof of Theorem 14 of [2]_ via Markov's Inequality. If we have + a sketch size ``sketch_size=k`` which is at least + + .. math:: k \geq \frac{2}{\epsilon^2\delta} + + Then for any fixed vector ``x``, + + .. math:: \|Ax\| = (1\pm\epsilon)\|A'x\| + + with probability at least one minus delta. + + This implementation takes advantage of sparsity: computing + a sketch takes time proportional to ``A.nnz``. Data ``A`` which + is in ``scipy.sparse.csc_matrix`` format gives the quickest + computation time for sparse input. + + >>> import numpy as np + >>> from scipy import linalg + >>> from scipy import sparse + >>> rng = np.random.default_rng() + >>> n_rows, n_columns, density, sketch_n_rows = 15000, 100, 0.01, 200 + >>> A = sparse.rand(n_rows, n_columns, density=density, format='csc') + >>> B = sparse.rand(n_rows, n_columns, density=density, format='csr') + >>> C = sparse.rand(n_rows, n_columns, density=density, format='coo') + >>> D = rng.standard_normal((n_rows, n_columns)) + >>> SA = linalg.clarkson_woodruff_transform(A, sketch_n_rows) # fastest + >>> SB = linalg.clarkson_woodruff_transform(B, sketch_n_rows) # fast + >>> SC = linalg.clarkson_woodruff_transform(C, sketch_n_rows) # slower + >>> SD = linalg.clarkson_woodruff_transform(D, sketch_n_rows) # slowest + + That said, this method does perform well on dense inputs, just slower + on a relative scale. + + References + ---------- + .. [1] Kenneth L. Clarkson and David P. Woodruff. Low rank approximation + and regression in input sparsity time. In STOC, 2013. + .. [2] David P. Woodruff. Sketching as a tool for numerical linear algebra. + In Foundations and Trends in Theoretical Computer Science, 2014. + + Examples + -------- + Create a big dense matrix ``A`` for the example: + + >>> import numpy as np + >>> from scipy import linalg + >>> n_rows, n_columns = 15000, 100 + >>> rng = np.random.default_rng() + >>> A = rng.standard_normal((n_rows, n_columns)) + + Apply the transform to create a new matrix with 200 rows: + + >>> sketch_n_rows = 200 + >>> sketch = linalg.clarkson_woodruff_transform(A, sketch_n_rows, seed=rng) + >>> sketch.shape + (200, 100) + + Now with high probability, the true norm is close to the sketched norm + in absolute value. + + >>> linalg.norm(A) + 1224.2812927123198 + >>> linalg.norm(sketch) + 1226.518328407333 + + Similarly, applying our sketch preserves the solution to a linear + regression of :math:`\min \|Ax - b\|`. + + >>> b = rng.standard_normal(n_rows) + >>> x = linalg.lstsq(A, b)[0] + >>> Ab = np.hstack((A, b.reshape(-1, 1))) + >>> SAb = linalg.clarkson_woodruff_transform(Ab, sketch_n_rows, seed=rng) + >>> SA, Sb = SAb[:, :-1], SAb[:, -1] + >>> x_sketched = linalg.lstsq(SA, Sb)[0] + + As with the matrix norm example, ``linalg.norm(A @ x - b)`` is close + to ``linalg.norm(A @ x_sketched - b)`` with high probability. + + >>> linalg.norm(A @ x - b) + 122.83242365433877 + >>> linalg.norm(A @ x_sketched - b) + 166.58473879945151 + + """ + S = cwt_matrix(sketch_size, input_matrix.shape[0], rng=rng) + return S.dot(input_matrix) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_solvers.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_solvers.py new file mode 100644 index 0000000000000000000000000000000000000000..60a6a73e7bf9cce36090137c0e884d3ed22c55a8 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_solvers.py @@ -0,0 +1,857 @@ +"""Matrix equation solver routines""" +# Author: Jeffrey Armstrong +# February 24, 2012 + +# Modified: Chad Fulton +# June 19, 2014 + +# Modified: Ilhan Polat +# September 13, 2016 + +import warnings +import numpy as np +from numpy.linalg import inv, LinAlgError, norm, cond, svd + +from ._basic import solve, solve_triangular, matrix_balance +from .lapack import get_lapack_funcs +from ._decomp_schur import schur +from ._decomp_lu import lu +from ._decomp_qr import qr +from ._decomp_qz import ordqz +from ._decomp import _asarray_validated +from ._special_matrices import block_diag + +__all__ = ['solve_sylvester', + 'solve_continuous_lyapunov', 'solve_discrete_lyapunov', + 'solve_lyapunov', + 'solve_continuous_are', 'solve_discrete_are'] + + +def solve_sylvester(a, b, q): + """ + Computes a solution (X) to the Sylvester equation :math:`AX + XB = Q`. + + Parameters + ---------- + a : (M, M) array_like + Leading matrix of the Sylvester equation + b : (N, N) array_like + Trailing matrix of the Sylvester equation + q : (M, N) array_like + Right-hand side + + Returns + ------- + x : (M, N) ndarray + The solution to the Sylvester equation. + + Raises + ------ + LinAlgError + If solution was not found + + Notes + ----- + Computes a solution to the Sylvester matrix equation via the Bartels- + Stewart algorithm. The A and B matrices first undergo Schur + decompositions. The resulting matrices are used to construct an + alternative Sylvester equation (``RY + YS^T = F``) where the R and S + matrices are in quasi-triangular form (or, when R, S or F are complex, + triangular form). The simplified equation is then solved using + ``*TRSYL`` from LAPACK directly. + + .. versionadded:: 0.11.0 + + Examples + -------- + Given `a`, `b`, and `q` solve for `x`: + + >>> import numpy as np + >>> from scipy import linalg + >>> a = np.array([[-3, -2, 0], [-1, -1, 3], [3, -5, -1]]) + >>> b = np.array([[1]]) + >>> q = np.array([[1],[2],[3]]) + >>> x = linalg.solve_sylvester(a, b, q) + >>> x + array([[ 0.0625], + [-0.5625], + [ 0.6875]]) + >>> np.allclose(a.dot(x) + x.dot(b), q) + True + + """ + # Accommodate empty a + if a.size == 0 or b.size == 0: + tdict = {'s': np.float32, 'd': np.float64, + 'c': np.complex64, 'z': np.complex128} + func, = get_lapack_funcs(('trsyl',), arrays=(a, b, q)) + return np.empty(q.shape, dtype=tdict[func.typecode]) + + # Compute the Schur decomposition form of a + r, u = schur(a, output='real') + + # Compute the Schur decomposition of b + s, v = schur(b.conj().transpose(), output='real') + + # Construct f = u'*q*v + f = np.dot(np.dot(u.conj().transpose(), q), v) + + # Call the Sylvester equation solver + trsyl, = get_lapack_funcs(('trsyl',), (r, s, f)) + if trsyl is None: + raise RuntimeError('LAPACK implementation does not contain a proper ' + 'Sylvester equation solver (TRSYL)') + y, scale, info = trsyl(r, s, f, tranb='C') + + y = scale*y + + if info < 0: + raise LinAlgError("Illegal value encountered in " + "the %d term" % (-info,)) + + return np.dot(np.dot(u, y), v.conj().transpose()) + + +def solve_continuous_lyapunov(a, q): + """ + Solves the continuous Lyapunov equation :math:`AX + XA^H = Q`. + + Uses the Bartels-Stewart algorithm to find :math:`X`. + + Parameters + ---------- + a : array_like + A square matrix + + q : array_like + Right-hand side square matrix + + Returns + ------- + x : ndarray + Solution to the continuous Lyapunov equation + + See Also + -------- + solve_discrete_lyapunov : computes the solution to the discrete-time + Lyapunov equation + solve_sylvester : computes the solution to the Sylvester equation + + Notes + ----- + The continuous Lyapunov equation is a special form of the Sylvester + equation, hence this solver relies on LAPACK routine ?TRSYL. + + .. versionadded:: 0.11.0 + + Examples + -------- + Given `a` and `q` solve for `x`: + + >>> import numpy as np + >>> from scipy import linalg + >>> a = np.array([[-3, -2, 0], [-1, -1, 0], [0, -5, -1]]) + >>> b = np.array([2, 4, -1]) + >>> q = np.eye(3) + >>> x = linalg.solve_continuous_lyapunov(a, q) + >>> x + array([[ -0.75 , 0.875 , -3.75 ], + [ 0.875 , -1.375 , 5.3125], + [ -3.75 , 5.3125, -27.0625]]) + >>> np.allclose(a.dot(x) + x.dot(a.T), q) + True + """ + + a = np.atleast_2d(_asarray_validated(a, check_finite=True)) + q = np.atleast_2d(_asarray_validated(q, check_finite=True)) + + r_or_c = float + + for ind, _ in enumerate((a, q)): + if np.iscomplexobj(_): + r_or_c = complex + + if not np.equal(*_.shape): + raise ValueError(f"Matrix {'aq'[ind]} should be square.") + + # Shape consistency check + if a.shape != q.shape: + raise ValueError("Matrix a and q should have the same shape.") + + # Accommodate empty array + if a.size == 0: + tdict = {'s': np.float32, 'd': np.float64, + 'c': np.complex64, 'z': np.complex128} + func, = get_lapack_funcs(('trsyl',), arrays=(a, q)) + return np.empty(a.shape, dtype=tdict[func.typecode]) + + # Compute the Schur decomposition form of a + r, u = schur(a, output='real') + + # Construct f = u'*q*u + f = u.conj().T.dot(q.dot(u)) + + # Call the Sylvester equation solver + trsyl = get_lapack_funcs('trsyl', (r, f)) + + dtype_string = 'T' if r_or_c is float else 'C' + y, scale, info = trsyl(r, r, f, tranb=dtype_string) + + if info < 0: + raise ValueError('?TRSYL exited with the internal error ' + f'"illegal value in argument number {-info}.". See ' + 'LAPACK documentation for the ?TRSYL error codes.') + elif info == 1: + warnings.warn('Input "a" has an eigenvalue pair whose sum is ' + 'very close to or exactly zero. The solution is ' + 'obtained via perturbing the coefficients.', + RuntimeWarning, stacklevel=2) + y *= scale + + return u.dot(y).dot(u.conj().T) + + +# For backwards compatibility, keep the old name +solve_lyapunov = solve_continuous_lyapunov + + +def _solve_discrete_lyapunov_direct(a, q): + """ + Solves the discrete Lyapunov equation directly. + + This function is called by the `solve_discrete_lyapunov` function with + `method=direct`. It is not supposed to be called directly. + """ + + lhs = np.kron(a, a.conj()) + lhs = np.eye(lhs.shape[0]) - lhs + x = solve(lhs, q.flatten()) + + return np.reshape(x, q.shape) + + +def _solve_discrete_lyapunov_bilinear(a, q): + """ + Solves the discrete Lyapunov equation using a bilinear transformation. + + This function is called by the `solve_discrete_lyapunov` function with + `method=bilinear`. It is not supposed to be called directly. + """ + eye = np.eye(a.shape[0]) + aH = a.conj().transpose() + aHI_inv = inv(aH + eye) + b = np.dot(aH - eye, aHI_inv) + c = 2*np.dot(np.dot(inv(a + eye), q), aHI_inv) + return solve_lyapunov(b.conj().transpose(), -c) + + +def solve_discrete_lyapunov(a, q, method=None): + """ + Solves the discrete Lyapunov equation :math:`AXA^H - X + Q = 0`. + + Parameters + ---------- + a, q : (M, M) array_like + Square matrices corresponding to A and Q in the equation + above respectively. Must have the same shape. + + method : {'direct', 'bilinear'}, optional + Type of solver. + + If not given, chosen to be ``direct`` if ``M`` is less than 10 and + ``bilinear`` otherwise. + + Returns + ------- + x : ndarray + Solution to the discrete Lyapunov equation + + See Also + -------- + solve_continuous_lyapunov : computes the solution to the continuous-time + Lyapunov equation + + Notes + ----- + This section describes the available solvers that can be selected by the + 'method' parameter. The default method is *direct* if ``M`` is less than 10 + and ``bilinear`` otherwise. + + Method *direct* uses a direct analytical solution to the discrete Lyapunov + equation. The algorithm is given in, for example, [1]_. However, it requires + the linear solution of a system with dimension :math:`M^2` so that + performance degrades rapidly for even moderately sized matrices. + + Method *bilinear* uses a bilinear transformation to convert the discrete + Lyapunov equation to a continuous Lyapunov equation :math:`(BX+XB'=-C)` + where :math:`B=(A-I)(A+I)^{-1}` and + :math:`C=2(A' + I)^{-1} Q (A + I)^{-1}`. The continuous equation can be + efficiently solved since it is a special case of a Sylvester equation. + The transformation algorithm is from Popov (1964) as described in [2]_. + + .. versionadded:: 0.11.0 + + References + ---------- + .. [1] "Lyapunov equation", Wikipedia, + https://en.wikipedia.org/wiki/Lyapunov_equation#Discrete_time + .. [2] Gajic, Z., and M.T.J. Qureshi. 2008. + Lyapunov Matrix Equation in System Stability and Control. + Dover Books on Engineering Series. Dover Publications. + + Examples + -------- + Given `a` and `q` solve for `x`: + + >>> import numpy as np + >>> from scipy import linalg + >>> a = np.array([[0.2, 0.5],[0.7, -0.9]]) + >>> q = np.eye(2) + >>> x = linalg.solve_discrete_lyapunov(a, q) + >>> x + array([[ 0.70872893, 1.43518822], + [ 1.43518822, -2.4266315 ]]) + >>> np.allclose(a.dot(x).dot(a.T)-x, -q) + True + + """ + a = np.asarray(a) + q = np.asarray(q) + if method is None: + # Select automatically based on size of matrices + if a.shape[0] >= 10: + method = 'bilinear' + else: + method = 'direct' + + meth = method.lower() + + if meth == 'direct': + x = _solve_discrete_lyapunov_direct(a, q) + elif meth == 'bilinear': + x = _solve_discrete_lyapunov_bilinear(a, q) + else: + raise ValueError(f'Unknown solver {method}') + + return x + + +def solve_continuous_are(a, b, q, r, e=None, s=None, balanced=True): + r""" + Solves the continuous-time algebraic Riccati equation (CARE). + + The CARE is defined as + + .. math:: + + X A + A^H X - X B R^{-1} B^H X + Q = 0 + + The limitations for a solution to exist are : + + * All eigenvalues of :math:`A` on the right half plane, should be + controllable. + + * The associated hamiltonian pencil (See Notes), should have + eigenvalues sufficiently away from the imaginary axis. + + Moreover, if ``e`` or ``s`` is not precisely ``None``, then the + generalized version of CARE + + .. math:: + + E^HXA + A^HXE - (E^HXB + S) R^{-1} (B^HXE + S^H) + Q = 0 + + is solved. When omitted, ``e`` is assumed to be the identity and ``s`` + is assumed to be the zero matrix with sizes compatible with ``a`` and + ``b``, respectively. + + Parameters + ---------- + a : (M, M) array_like + Square matrix + b : (M, N) array_like + Input + q : (M, M) array_like + Input + r : (N, N) array_like + Nonsingular square matrix + e : (M, M) array_like, optional + Nonsingular square matrix + s : (M, N) array_like, optional + Input + balanced : bool, optional + The boolean that indicates whether a balancing step is performed + on the data. The default is set to True. + + Returns + ------- + x : (M, M) ndarray + Solution to the continuous-time algebraic Riccati equation. + + Raises + ------ + LinAlgError + For cases where the stable subspace of the pencil could not be + isolated. See Notes section and the references for details. + + See Also + -------- + solve_discrete_are : Solves the discrete-time algebraic Riccati equation + + Notes + ----- + The equation is solved by forming the extended hamiltonian matrix pencil, + as described in [1]_, :math:`H - \lambda J` given by the block matrices :: + + [ A 0 B ] [ E 0 0 ] + [-Q -A^H -S ] - \lambda * [ 0 E^H 0 ] + [ S^H B^H R ] [ 0 0 0 ] + + and using a QZ decomposition method. + + In this algorithm, the fail conditions are linked to the symmetry + of the product :math:`U_2 U_1^{-1}` and condition number of + :math:`U_1`. Here, :math:`U` is the 2m-by-m matrix that holds the + eigenvectors spanning the stable subspace with 2-m rows and partitioned + into two m-row matrices. See [1]_ and [2]_ for more details. + + In order to improve the QZ decomposition accuracy, the pencil goes + through a balancing step where the sum of absolute values of + :math:`H` and :math:`J` entries (after removing the diagonal entries of + the sum) is balanced following the recipe given in [3]_. + + .. versionadded:: 0.11.0 + + References + ---------- + .. [1] P. van Dooren , "A Generalized Eigenvalue Approach For Solving + Riccati Equations.", SIAM Journal on Scientific and Statistical + Computing, Vol.2(2), :doi:`10.1137/0902010` + + .. [2] A.J. Laub, "A Schur Method for Solving Algebraic Riccati + Equations.", Massachusetts Institute of Technology. Laboratory for + Information and Decision Systems. LIDS-R ; 859. Available online : + http://hdl.handle.net/1721.1/1301 + + .. [3] P. Benner, "Symplectic Balancing of Hamiltonian Matrices", 2001, + SIAM J. Sci. Comput., 2001, Vol.22(5), :doi:`10.1137/S1064827500367993` + + Examples + -------- + Given `a`, `b`, `q`, and `r` solve for `x`: + + >>> import numpy as np + >>> from scipy import linalg + >>> a = np.array([[4, 3], [-4.5, -3.5]]) + >>> b = np.array([[1], [-1]]) + >>> q = np.array([[9, 6], [6, 4.]]) + >>> r = 1 + >>> x = linalg.solve_continuous_are(a, b, q, r) + >>> x + array([[ 21.72792206, 14.48528137], + [ 14.48528137, 9.65685425]]) + >>> np.allclose(a.T.dot(x) + x.dot(a)-x.dot(b).dot(b.T).dot(x), -q) + True + + """ + + # Validate input arguments + a, b, q, r, e, s, m, n, r_or_c, gen_are = _are_validate_args( + a, b, q, r, e, s, 'care') + + H = np.empty((2*m+n, 2*m+n), dtype=r_or_c) + H[:m, :m] = a + H[:m, m:2*m] = 0. + H[:m, 2*m:] = b + H[m:2*m, :m] = -q + H[m:2*m, m:2*m] = -a.conj().T + H[m:2*m, 2*m:] = 0. if s is None else -s + H[2*m:, :m] = 0. if s is None else s.conj().T + H[2*m:, m:2*m] = b.conj().T + H[2*m:, 2*m:] = r + + if gen_are and e is not None: + J = block_diag(e, e.conj().T, np.zeros_like(r, dtype=r_or_c)) + else: + J = block_diag(np.eye(2*m), np.zeros_like(r, dtype=r_or_c)) + + if balanced: + # xGEBAL does not remove the diagonals before scaling. Also + # to avoid destroying the Symplectic structure, we follow Ref.3 + M = np.abs(H) + np.abs(J) + np.fill_diagonal(M, 0.) + _, (sca, _) = matrix_balance(M, separate=1, permute=0) + # do we need to bother? + if not np.allclose(sca, np.ones_like(sca)): + # Now impose diag(D,inv(D)) from Benner where D is + # square root of s_i/s_(n+i) for i=0,.... + sca = np.log2(sca) + # NOTE: Py3 uses "Bankers Rounding: round to the nearest even" !! + s = np.round((sca[m:2*m] - sca[:m])/2) + sca = 2 ** np.r_[s, -s, sca[2*m:]] + # Elementwise multiplication via broadcasting. + elwisescale = sca[:, None] * np.reciprocal(sca) + H *= elwisescale + J *= elwisescale + + # Deflate the pencil to 2m x 2m ala Ref.1, eq.(55) + q, r = qr(H[:, -n:]) + H = q[:, n:].conj().T.dot(H[:, :2*m]) + J = q[:2*m, n:].conj().T.dot(J[:2*m, :2*m]) + + # Decide on which output type is needed for QZ + out_str = 'real' if r_or_c is float else 'complex' + + _, _, _, _, _, u = ordqz(H, J, sort='lhp', overwrite_a=True, + overwrite_b=True, check_finite=False, + output=out_str) + + # Get the relevant parts of the stable subspace basis + if e is not None: + u, _ = qr(np.vstack((e.dot(u[:m, :m]), u[m:, :m]))) + u00 = u[:m, :m] + u10 = u[m:, :m] + + # Solve via back-substituion after checking the condition of u00 + up, ul, uu = lu(u00) + if 1/cond(uu) < np.spacing(1.): + raise LinAlgError('Failed to find a finite solution.') + + # Exploit the triangular structure + x = solve_triangular(ul.conj().T, + solve_triangular(uu.conj().T, + u10.conj().T, + lower=True), + unit_diagonal=True, + ).conj().T.dot(up.conj().T) + if balanced: + x *= sca[:m, None] * sca[:m] + + # Check the deviation from symmetry for lack of success + # See proof of Thm.5 item 3 in [2] + u_sym = u00.conj().T.dot(u10) + n_u_sym = norm(u_sym, 1) + u_sym = u_sym - u_sym.conj().T + sym_threshold = np.max([np.spacing(1000.), 0.1*n_u_sym]) + + if norm(u_sym, 1) > sym_threshold: + raise LinAlgError('The associated Hamiltonian pencil has eigenvalues ' + 'too close to the imaginary axis') + + return (x + x.conj().T)/2 + + +def solve_discrete_are(a, b, q, r, e=None, s=None, balanced=True): + r""" + Solves the discrete-time algebraic Riccati equation (DARE). + + The DARE is defined as + + .. math:: + + A^HXA - X - (A^HXB) (R + B^HXB)^{-1} (B^HXA) + Q = 0 + + The limitations for a solution to exist are : + + * All eigenvalues of :math:`A` outside the unit disc, should be + controllable. + + * The associated symplectic pencil (See Notes), should have + eigenvalues sufficiently away from the unit circle. + + Moreover, if ``e`` and ``s`` are not both precisely ``None``, then the + generalized version of DARE + + .. math:: + + A^HXA - E^HXE - (A^HXB+S) (R+B^HXB)^{-1} (B^HXA+S^H) + Q = 0 + + is solved. When omitted, ``e`` is assumed to be the identity and ``s`` + is assumed to be the zero matrix. + + Parameters + ---------- + a : (M, M) array_like + Square matrix + b : (M, N) array_like + Input + q : (M, M) array_like + Input + r : (N, N) array_like + Square matrix + e : (M, M) array_like, optional + Nonsingular square matrix + s : (M, N) array_like, optional + Input + balanced : bool + The boolean that indicates whether a balancing step is performed + on the data. The default is set to True. + + Returns + ------- + x : (M, M) ndarray + Solution to the discrete algebraic Riccati equation. + + Raises + ------ + LinAlgError + For cases where the stable subspace of the pencil could not be + isolated. See Notes section and the references for details. + + See Also + -------- + solve_continuous_are : Solves the continuous algebraic Riccati equation + + Notes + ----- + The equation is solved by forming the extended symplectic matrix pencil, + as described in [1]_, :math:`H - \lambda J` given by the block matrices :: + + [ A 0 B ] [ E 0 B ] + [ -Q E^H -S ] - \lambda * [ 0 A^H 0 ] + [ S^H 0 R ] [ 0 -B^H 0 ] + + and using a QZ decomposition method. + + In this algorithm, the fail conditions are linked to the symmetry + of the product :math:`U_2 U_1^{-1}` and condition number of + :math:`U_1`. Here, :math:`U` is the 2m-by-m matrix that holds the + eigenvectors spanning the stable subspace with 2-m rows and partitioned + into two m-row matrices. See [1]_ and [2]_ for more details. + + In order to improve the QZ decomposition accuracy, the pencil goes + through a balancing step where the sum of absolute values of + :math:`H` and :math:`J` rows/cols (after removing the diagonal entries) + is balanced following the recipe given in [3]_. If the data has small + numerical noise, balancing may amplify their effects and some clean up + is required. + + .. versionadded:: 0.11.0 + + References + ---------- + .. [1] P. van Dooren , "A Generalized Eigenvalue Approach For Solving + Riccati Equations.", SIAM Journal on Scientific and Statistical + Computing, Vol.2(2), :doi:`10.1137/0902010` + + .. [2] A.J. Laub, "A Schur Method for Solving Algebraic Riccati + Equations.", Massachusetts Institute of Technology. Laboratory for + Information and Decision Systems. LIDS-R ; 859. Available online : + http://hdl.handle.net/1721.1/1301 + + .. [3] P. Benner, "Symplectic Balancing of Hamiltonian Matrices", 2001, + SIAM J. Sci. Comput., 2001, Vol.22(5), :doi:`10.1137/S1064827500367993` + + Examples + -------- + Given `a`, `b`, `q`, and `r` solve for `x`: + + >>> import numpy as np + >>> from scipy import linalg as la + >>> a = np.array([[0, 1], [0, -1]]) + >>> b = np.array([[1, 0], [2, 1]]) + >>> q = np.array([[-4, -4], [-4, 7]]) + >>> r = np.array([[9, 3], [3, 1]]) + >>> x = la.solve_discrete_are(a, b, q, r) + >>> x + array([[-4., -4.], + [-4., 7.]]) + >>> R = la.solve(r + b.T.dot(x).dot(b), b.T.dot(x).dot(a)) + >>> np.allclose(a.T.dot(x).dot(a) - x - a.T.dot(x).dot(b).dot(R), -q) + True + + """ + + # Validate input arguments + a, b, q, r, e, s, m, n, r_or_c, gen_are = _are_validate_args( + a, b, q, r, e, s, 'dare') + + # Form the matrix pencil + H = np.zeros((2*m+n, 2*m+n), dtype=r_or_c) + H[:m, :m] = a + H[:m, 2*m:] = b + H[m:2*m, :m] = -q + H[m:2*m, m:2*m] = np.eye(m) if e is None else e.conj().T + H[m:2*m, 2*m:] = 0. if s is None else -s + H[2*m:, :m] = 0. if s is None else s.conj().T + H[2*m:, 2*m:] = r + + J = np.zeros_like(H, dtype=r_or_c) + J[:m, :m] = np.eye(m) if e is None else e + J[m:2*m, m:2*m] = a.conj().T + J[2*m:, m:2*m] = -b.conj().T + + if balanced: + # xGEBAL does not remove the diagonals before scaling. Also + # to avoid destroying the Symplectic structure, we follow Ref.3 + M = np.abs(H) + np.abs(J) + np.fill_diagonal(M, 0.) + _, (sca, _) = matrix_balance(M, separate=1, permute=0) + # do we need to bother? + if not np.allclose(sca, np.ones_like(sca)): + # Now impose diag(D,inv(D)) from Benner where D is + # square root of s_i/s_(n+i) for i=0,.... + sca = np.log2(sca) + # NOTE: Py3 uses "Bankers Rounding: round to the nearest even" !! + s = np.round((sca[m:2*m] - sca[:m])/2) + sca = 2 ** np.r_[s, -s, sca[2*m:]] + # Elementwise multiplication via broadcasting. + elwisescale = sca[:, None] * np.reciprocal(sca) + H *= elwisescale + J *= elwisescale + + # Deflate the pencil by the R column ala Ref.1 + q_of_qr, _ = qr(H[:, -n:]) + H = q_of_qr[:, n:].conj().T.dot(H[:, :2*m]) + J = q_of_qr[:, n:].conj().T.dot(J[:, :2*m]) + + # Decide on which output type is needed for QZ + out_str = 'real' if r_or_c is float else 'complex' + + _, _, _, _, _, u = ordqz(H, J, sort='iuc', + overwrite_a=True, + overwrite_b=True, + check_finite=False, + output=out_str) + + # Get the relevant parts of the stable subspace basis + if e is not None: + u, _ = qr(np.vstack((e.dot(u[:m, :m]), u[m:, :m]))) + u00 = u[:m, :m] + u10 = u[m:, :m] + + # Solve via back-substituion after checking the condition of u00 + up, ul, uu = lu(u00) + + if 1/cond(uu) < np.spacing(1.): + raise LinAlgError('Failed to find a finite solution.') + + # Exploit the triangular structure + x = solve_triangular(ul.conj().T, + solve_triangular(uu.conj().T, + u10.conj().T, + lower=True), + unit_diagonal=True, + ).conj().T.dot(up.conj().T) + if balanced: + x *= sca[:m, None] * sca[:m] + + # Check the deviation from symmetry for lack of success + # See proof of Thm.5 item 3 in [2] + u_sym = u00.conj().T.dot(u10) + n_u_sym = norm(u_sym, 1) + u_sym = u_sym - u_sym.conj().T + sym_threshold = np.max([np.spacing(1000.), 0.1*n_u_sym]) + + if norm(u_sym, 1) > sym_threshold: + raise LinAlgError('The associated symplectic pencil has eigenvalues ' + 'too close to the unit circle') + + return (x + x.conj().T)/2 + + +def _are_validate_args(a, b, q, r, e, s, eq_type='care'): + """ + A helper function to validate the arguments supplied to the + Riccati equation solvers. Any discrepancy found in the input + matrices leads to a ``ValueError`` exception. + + Essentially, it performs: + + - a check whether the input is free of NaN and Infs + - a pass for the data through ``numpy.atleast_2d()`` + - squareness check of the relevant arrays + - shape consistency check of the arrays + - singularity check of the relevant arrays + - symmetricity check of the relevant matrices + - a check whether the regular or the generalized version is asked. + + This function is used by ``solve_continuous_are`` and + ``solve_discrete_are``. + + Parameters + ---------- + a, b, q, r, e, s : array_like + Input data + eq_type : str + Accepted arguments are 'care' and 'dare'. + + Returns + ------- + a, b, q, r, e, s : ndarray + Regularized input data + m, n : int + shape of the problem + r_or_c : type + Data type of the problem, returns float or complex + gen_or_not : bool + Type of the equation, True for generalized and False for regular ARE. + + """ + + if eq_type.lower() not in ("dare", "care"): + raise ValueError("Equation type unknown. " + "Only 'care' and 'dare' is understood") + + a = np.atleast_2d(_asarray_validated(a, check_finite=True)) + b = np.atleast_2d(_asarray_validated(b, check_finite=True)) + q = np.atleast_2d(_asarray_validated(q, check_finite=True)) + r = np.atleast_2d(_asarray_validated(r, check_finite=True)) + + # Get the correct data types otherwise NumPy complains + # about pushing complex numbers into real arrays. + r_or_c = complex if np.iscomplexobj(b) else float + + for ind, mat in enumerate((a, q, r)): + if np.iscomplexobj(mat): + r_or_c = complex + + if not np.equal(*mat.shape): + raise ValueError(f"Matrix {'aqr'[ind]} should be square.") + + # Shape consistency checks + m, n = b.shape + if m != a.shape[0]: + raise ValueError("Matrix a and b should have the same number of rows.") + if m != q.shape[0]: + raise ValueError("Matrix a and q should have the same shape.") + if n != r.shape[0]: + raise ValueError("Matrix b and r should have the same number of cols.") + + # Check if the data matrices q, r are (sufficiently) hermitian + for ind, mat in enumerate((q, r)): + if norm(mat - mat.conj().T, 1) > np.spacing(norm(mat, 1))*100: + raise ValueError(f"Matrix {'qr'[ind]} should be symmetric/hermitian.") + + # Continuous time ARE should have a nonsingular r matrix. + if eq_type == 'care': + min_sv = svd(r, compute_uv=False)[-1] + if min_sv == 0. or min_sv < np.spacing(1.)*norm(r, 1): + raise ValueError('Matrix r is numerically singular.') + + # Check if the generalized case is required with omitted arguments + # perform late shape checking etc. + generalized_case = e is not None or s is not None + + if generalized_case: + if e is not None: + e = np.atleast_2d(_asarray_validated(e, check_finite=True)) + if not np.equal(*e.shape): + raise ValueError("Matrix e should be square.") + if m != e.shape[0]: + raise ValueError("Matrix a and e should have the same shape.") + # numpy.linalg.cond doesn't check for exact zeros and + # emits a runtime warning. Hence the following manual check. + min_sv = svd(e, compute_uv=False)[-1] + if min_sv == 0. or min_sv < np.spacing(1.) * norm(e, 1): + raise ValueError('Matrix e is numerically singular.') + if np.iscomplexobj(e): + r_or_c = complex + if s is not None: + s = np.atleast_2d(_asarray_validated(s, check_finite=True)) + if s.shape != b.shape: + raise ValueError("Matrix b and s should have the same shape.") + if np.iscomplexobj(s): + r_or_c = complex + + return a, b, q, r, e, s, m, n, r_or_c, generalized_case diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_special_matrices.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_special_matrices.py new file mode 100644 index 0000000000000000000000000000000000000000..7dca572f2d5a12a27ccb468425f03c75e86d5da7 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_special_matrices.py @@ -0,0 +1,1332 @@ +import math +import warnings + +import numpy as np +from numpy.lib.stride_tricks import as_strided + + +__all__ = ['toeplitz', 'circulant', 'hankel', + 'hadamard', 'leslie', 'kron', 'block_diag', 'companion', + 'helmert', 'hilbert', 'invhilbert', 'pascal', 'invpascal', 'dft', + 'fiedler', 'fiedler_companion', 'convolution_matrix'] + + +# ----------------------------------------------------------------------------- +# matrix construction functions +# ----------------------------------------------------------------------------- + + +def toeplitz(c, r=None): + r""" + Construct a Toeplitz matrix. + + The Toeplitz matrix has constant diagonals, with c as its first column + and r as its first row. If r is not given, ``r == conjugate(c)`` is + assumed. + + Parameters + ---------- + c : array_like + First column of the matrix. + r : array_like, optional + First row of the matrix. If None, ``r = conjugate(c)`` is assumed; + in this case, if c[0] is real, the result is a Hermitian matrix. + r[0] is ignored; the first row of the returned matrix is + ``[c[0], r[1:]]``. + + .. warning:: + + Beginning in SciPy 1.17, multidimensional input will be treated as a batch, + not ``ravel``\ ed. To preserve the existing behavior, ``ravel`` arguments + before passing them to `toeplitz`. + + Returns + ------- + A : (len(c), len(r)) ndarray + The Toeplitz matrix. Dtype is the same as ``(c[0] + r[0]).dtype``. + + See Also + -------- + circulant : circulant matrix + hankel : Hankel matrix + solve_toeplitz : Solve a Toeplitz system. + + Notes + ----- + The behavior when `c` or `r` is a scalar, or when `c` is complex and + `r` is None, was changed in version 0.8.0. The behavior in previous + versions was undocumented and is no longer supported. + + Examples + -------- + >>> from scipy.linalg import toeplitz + >>> toeplitz([1,2,3], [1,4,5,6]) + array([[1, 4, 5, 6], + [2, 1, 4, 5], + [3, 2, 1, 4]]) + >>> toeplitz([1.0, 2+3j, 4-1j]) + array([[ 1.+0.j, 2.-3.j, 4.+1.j], + [ 2.+3.j, 1.+0.j, 2.-3.j], + [ 4.-1.j, 2.+3.j, 1.+0.j]]) + + """ + c = np.asarray(c) + if r is None: + r = c.conjugate() + else: + r = np.asarray(r) + + if c.ndim > 1 or r.ndim > 1: + msg = ("Beginning in SciPy 1.17, multidimensional input will be treated as a " + "batch, not `ravel`ed. To preserve the existing behavior and silence " + "this warning, `ravel` arguments before passing them to `toeplitz`.") + warnings.warn(msg, FutureWarning, stacklevel=2) + + c, r = c.ravel(), r.ravel() + # Form a 1-D array containing a reversed c followed by r[1:] that could be + # strided to give us toeplitz matrix. + vals = np.concatenate((c[::-1], r[1:])) + out_shp = len(c), len(r) + n = vals.strides[0] + return as_strided(vals[len(c)-1:], shape=out_shp, strides=(-n, n)).copy() + + +def circulant(c): + """ + Construct a circulant matrix. + + Parameters + ---------- + c : (..., N,) array_like + The first column(s) of the matrix. Multidimensional arrays are treated as a + batch: each slice along the last axis is the first column of an output matrix. + + Returns + ------- + A : (..., N, N) ndarray + A circulant matrix whose first column is given by `c`. For batch input, each + slice of shape ``(N, N)`` along the last two dimensions of the output + corresponds with a slice of shape ``(N,)`` along the last dimension of the + input. + + + See Also + -------- + toeplitz : Toeplitz matrix + hankel : Hankel matrix + solve_circulant : Solve a circulant system. + + Notes + ----- + .. versionadded:: 0.8.0 + + Examples + -------- + >>> from scipy.linalg import circulant + >>> circulant([1, 2, 3]) + array([[1, 3, 2], + [2, 1, 3], + [3, 2, 1]]) + + >>> circulant([[1, 2, 3], [4, 5, 6]]) + array([[[1, 3, 2], + [2, 1, 3], + [3, 2, 1]], + [[4, 6, 5], + [5, 4, 6], + [6, 5, 4]]]) + """ + c = np.atleast_1d(c) + batch_shape, N = c.shape[:-1], c.shape[-1] + # Need to use `prod(batch_shape)` instead of `-1` in case array has zero size + c = c.reshape(math.prod(batch_shape), N) if batch_shape else c + # Form an extended array that could be strided to give circulant version + c_ext = np.concatenate((c[..., ::-1], c[..., :0:-1]), axis=-1).ravel() + L = c.shape[-1] + n = c_ext.strides[-1] + if c.ndim == 1: + A = as_strided(c_ext[L-1:], shape=(L, L), strides=(-n, n)) + else: + m = c.shape[0] + A = as_strided(c_ext[L-1:], shape=(m, L, L), strides=(n*(2*L-1), -n, n)) + return A.reshape(batch_shape + (N, N)).copy() + + +def hankel(c, r=None): + """ + Construct a Hankel matrix. + + The Hankel matrix has constant anti-diagonals, with `c` as its + first column and `r` as its last row. If the first element of `r` + differs from the last element of `c`, the first element of `r` is + replaced by the last element of `c` to ensure that anti-diagonals + remain constant. If `r` is not given, then `r = zeros_like(c)` is + assumed. + + Parameters + ---------- + c : array_like + First column of the matrix. Whatever the actual shape of `c`, it + will be converted to a 1-D array. + r : array_like, optional + Last row of the matrix. If None, ``r = zeros_like(c)`` is assumed. + r[0] is ignored; the last row of the returned matrix is + ``[c[-1], r[1:]]``. Whatever the actual shape of `r`, it will be + converted to a 1-D array. + + Returns + ------- + A : (len(c), len(r)) ndarray + The Hankel matrix. Dtype is the same as ``(c[0] + r[0]).dtype``. + + See Also + -------- + toeplitz : Toeplitz matrix + circulant : circulant matrix + + Examples + -------- + >>> from scipy.linalg import hankel + >>> hankel([1, 17, 99]) + array([[ 1, 17, 99], + [17, 99, 0], + [99, 0, 0]]) + >>> hankel([1,2,3,4], [4,7,7,8,9]) + array([[1, 2, 3, 4, 7], + [2, 3, 4, 7, 7], + [3, 4, 7, 7, 8], + [4, 7, 7, 8, 9]]) + + """ + c = np.asarray(c).ravel() + if r is None: + r = np.zeros_like(c) + else: + r = np.asarray(r).ravel() + # Form a 1-D array of values to be used in the matrix, containing `c` + # followed by r[1:]. + vals = np.concatenate((c, r[1:])) + # Stride on concatenated array to get hankel matrix + out_shp = len(c), len(r) + n = vals.strides[0] + return as_strided(vals, shape=out_shp, strides=(n, n)).copy() + + +def hadamard(n, dtype=int): + """ + Construct an Hadamard matrix. + + Constructs an n-by-n Hadamard matrix, using Sylvester's + construction. `n` must be a power of 2. + + Parameters + ---------- + n : int + The order of the matrix. `n` must be a power of 2. + dtype : dtype, optional + The data type of the array to be constructed. + + Returns + ------- + H : (n, n) ndarray + The Hadamard matrix. + + Notes + ----- + .. versionadded:: 0.8.0 + + Examples + -------- + >>> from scipy.linalg import hadamard + >>> hadamard(2, dtype=complex) + array([[ 1.+0.j, 1.+0.j], + [ 1.+0.j, -1.-0.j]]) + >>> hadamard(4) + array([[ 1, 1, 1, 1], + [ 1, -1, 1, -1], + [ 1, 1, -1, -1], + [ 1, -1, -1, 1]]) + + """ + + # This function is a slightly modified version of the + # function contributed by Ivo in ticket #675. + + if n < 1: + lg2 = 0 + else: + lg2 = int(math.log(n, 2)) + if 2 ** lg2 != n: + raise ValueError("n must be an positive integer, and n must be " + "a power of 2") + + H = np.array([[1]], dtype=dtype) + + # Sylvester's construction + for i in range(0, lg2): + H = np.vstack((np.hstack((H, H)), np.hstack((H, -H)))) + + return H + + +def leslie(f, s): + """ + Create a Leslie matrix. + + Given the length n array of fecundity coefficients `f` and the length + n-1 array of survival coefficients `s`, return the associated Leslie + matrix. + + Parameters + ---------- + f : (..., N,) array_like + The "fecundity" coefficients. + s : (..., N-1,) array_like + The "survival" coefficients. The length of each slice of `s` (along the last + axis) must be one less than the length of `f`, and it must be at least 1. + + Returns + ------- + L : (..., N, N) ndarray + The array is zero except for the first row, + which is `f`, and the first sub-diagonal, which is `s`. + For 1-D input, the data-type of the array will be the data-type of + ``f[0]+s[0]``. + + Notes + ----- + .. versionadded:: 0.8.0 + + The Leslie matrix is used to model discrete-time, age-structured + population growth [1]_ [2]_. In a population with `n` age classes, two sets + of parameters define a Leslie matrix: the `n` "fecundity coefficients", + which give the number of offspring per-capita produced by each age + class, and the `n` - 1 "survival coefficients", which give the + per-capita survival rate of each age class. + + N-dimensional input are treated as a batches of coefficient arrays: each + slice along the last axis of the input arrays is a 1-D coefficient array, + and each slice along the last two dimensions of the output is the + corresponding Leslie matrix. + + References + ---------- + .. [1] P. H. Leslie, On the use of matrices in certain population + mathematics, Biometrika, Vol. 33, No. 3, 183--212 (Nov. 1945) + .. [2] P. H. Leslie, Some further notes on the use of matrices in + population mathematics, Biometrika, Vol. 35, No. 3/4, 213--245 + (Dec. 1948) + + Examples + -------- + >>> from scipy.linalg import leslie + >>> leslie([0.1, 2.0, 1.0, 0.1], [0.2, 0.8, 0.7]) + array([[ 0.1, 2. , 1. , 0.1], + [ 0.2, 0. , 0. , 0. ], + [ 0. , 0.8, 0. , 0. ], + [ 0. , 0. , 0.7, 0. ]]) + + """ + f = np.atleast_1d(f) + s = np.atleast_1d(s) + + if f.shape[-1] != s.shape[-1] + 1: + raise ValueError("Incorrect lengths for f and s. The length of s along " + "the last axis must be one less than the length of f.") + if s.shape[-1] == 0: + raise ValueError("The length of s must be at least 1.") + + n = f.shape[-1] + + if f.ndim > 1 or s.ndim > 1: + from scipy.stats._resampling import _vectorize_statistic + _leslie_nd = _vectorize_statistic(leslie) + return np.moveaxis(_leslie_nd(f, s, axis=-1), [0, 1], [-2, -1]) + + tmp = f[0] + s[0] + a = np.zeros((n, n), dtype=tmp.dtype) + a[0] = f + a[list(range(1, n)), list(range(0, n - 1))] = s + return a + + +def kron(a, b): + """ + Kronecker product. + + .. deprecated:: 1.15.0 + `kron` has been deprecated in favour of `numpy.kron` and will be + removed in SciPy 1.17.0. + + The result is the block matrix:: + + a[0,0]*b a[0,1]*b ... a[0,-1]*b + a[1,0]*b a[1,1]*b ... a[1,-1]*b + ... + a[-1,0]*b a[-1,1]*b ... a[-1,-1]*b + + Parameters + ---------- + a : (M, N) ndarray + Input array + b : (P, Q) ndarray + Input array + + Returns + ------- + A : (M*P, N*Q) ndarray + Kronecker product of `a` and `b`. + + Examples + -------- + >>> from numpy import array + >>> from scipy.linalg import kron + >>> kron(array([[1,2],[3,4]]), array([[1,1,1]])) + array([[1, 1, 1, 2, 2, 2], + [3, 3, 3, 4, 4, 4]]) + + """ + msg = ("`kron` has been deprecated in favour of `numpy.kron` in SciPy" + " 1.15.0 and will be removed in SciPy 1.17.0.") + warnings.warn(msg, DeprecationWarning, stacklevel=2) + # accommodate empty arrays + if a.size == 0 or b.size == 0: + m = a.shape[0] * b.shape[0] + n = a.shape[1] * b.shape[1] + return np.empty_like(a, shape=(m, n)) + + if not a.flags['CONTIGUOUS']: + a = np.reshape(a, a.shape) + if not b.flags['CONTIGUOUS']: + b = np.reshape(b, b.shape) + o = np.outer(a, b) + o = o.reshape(a.shape + b.shape) + return np.concatenate(np.concatenate(o, axis=1), axis=1) + + +def block_diag(*arrs): + """ + Create a block diagonal matrix from provided arrays. + + Given the inputs `A`, `B` and `C`, the output will have these + arrays arranged on the diagonal:: + + [[A, 0, 0], + [0, B, 0], + [0, 0, C]] + + Parameters + ---------- + A, B, C, ... : array_like, up to 2-D + Input arrays. A 1-D array or array_like sequence of length `n` is + treated as a 2-D array with shape ``(1,n)``. + + Returns + ------- + D : ndarray + Array with `A`, `B`, `C`, ... on the diagonal. `D` has the + same dtype as `A`. + + Notes + ----- + If all the input arrays are square, the output is known as a + block diagonal matrix. + + Empty sequences (i.e., array-likes of zero size) will not be ignored. + Noteworthy, both [] and [[]] are treated as matrices with shape ``(1,0)``. + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import block_diag + >>> A = [[1, 0], + ... [0, 1]] + >>> B = [[3, 4, 5], + ... [6, 7, 8]] + >>> C = [[7]] + >>> P = np.zeros((2, 0), dtype='int32') + >>> block_diag(A, B, C) + array([[1, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0], + [0, 0, 3, 4, 5, 0], + [0, 0, 6, 7, 8, 0], + [0, 0, 0, 0, 0, 7]]) + >>> block_diag(A, P, B, C) + array([[1, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 3, 4, 5, 0], + [0, 0, 6, 7, 8, 0], + [0, 0, 0, 0, 0, 7]]) + >>> block_diag(1.0, [2, 3], [[4, 5], [6, 7]]) + array([[ 1., 0., 0., 0., 0.], + [ 0., 2., 3., 0., 0.], + [ 0., 0., 0., 4., 5.], + [ 0., 0., 0., 6., 7.]]) + + """ + if arrs == (): + arrs = ([],) + arrs = [np.atleast_2d(a) for a in arrs] + + bad_args = [k for k in range(len(arrs)) if arrs[k].ndim > 2] + if bad_args: + raise ValueError("arguments in the following positions " + f"have dimension greater than 2: {bad_args}") + + shapes = np.array([a.shape for a in arrs]) + out_dtype = np.result_type(*[arr.dtype for arr in arrs]) + out = np.zeros(np.sum(shapes, axis=0), dtype=out_dtype) + + r, c = 0, 0 + for i, (rr, cc) in enumerate(shapes): + out[r:r + rr, c:c + cc] = arrs[i] + r += rr + c += cc + return out + + +def companion(a): + """ + Create a companion matrix. + + Create the companion matrix [1]_ associated with the polynomial whose + coefficients are given in `a`. + + Parameters + ---------- + a : (..., N) array_like + 1-D array of polynomial coefficients. The length of `a` must be + at least two, and ``a[0]`` must not be zero. + M-dimensional arrays are treated as a batch: each slice along the last + axis is a 1-D array of polynomial coefficients. + + Returns + ------- + c : (..., N-1, N-1) ndarray + For 1-D input, the first row of `c` is ``-a[1:]/a[0]``, and the first + sub-diagonal is all ones. The data-type of the array is the same + as the data-type of ``1.0*a[0]``. + For batch input, each slice of shape ``(N-1, N-1)`` along the last two + dimensions of the output corresponds with a slice of shape ``(N,)`` + along the last dimension of the input. + + Raises + ------ + ValueError + If any of the following are true: a) ``a.shape[-1] < 2``; b) ``a[..., 0] == 0``. + + Notes + ----- + .. versionadded:: 0.8.0 + + References + ---------- + .. [1] R. A. Horn & C. R. Johnson, *Matrix Analysis*. Cambridge, UK: + Cambridge University Press, 1999, pp. 146-7. + + Examples + -------- + >>> from scipy.linalg import companion + >>> companion([1, -10, 31, -30]) + array([[ 10., -31., 30.], + [ 1., 0., 0.], + [ 0., 1., 0.]]) + + """ + a = np.atleast_1d(a) + n = a.shape[-1] + + if n < 2: + raise ValueError("The length of `a` along the last axis must be at least 2.") + + if np.any(a[..., 0] == 0): + raise ValueError("The first coefficient(s) of `a` (i.e. elements " + "of `a[..., 0]`) must not be zero.") + + first_row = -a[..., 1:] / (1.0 * a[..., 0:1]) + c = np.zeros(a.shape[:-1] + (n - 1, n - 1), dtype=first_row.dtype) + c[..., 0, :] = first_row + c[..., np.arange(1, n - 1), np.arange(0, n - 2)] = 1 + return c + + +def helmert(n, full=False): + """ + Create an Helmert matrix of order `n`. + + This has applications in statistics, compositional or simplicial analysis, + and in Aitchison geometry. + + Parameters + ---------- + n : int + The size of the array to create. + full : bool, optional + If True the (n, n) ndarray will be returned. + Otherwise the submatrix that does not include the first + row will be returned. + Default: False. + + Returns + ------- + M : ndarray + The Helmert matrix. + The shape is (n, n) or (n-1, n) depending on the `full` argument. + + Examples + -------- + >>> from scipy.linalg import helmert + >>> helmert(5, full=True) + array([[ 0.4472136 , 0.4472136 , 0.4472136 , 0.4472136 , 0.4472136 ], + [ 0.70710678, -0.70710678, 0. , 0. , 0. ], + [ 0.40824829, 0.40824829, -0.81649658, 0. , 0. ], + [ 0.28867513, 0.28867513, 0.28867513, -0.8660254 , 0. ], + [ 0.2236068 , 0.2236068 , 0.2236068 , 0.2236068 , -0.89442719]]) + + """ + H = np.tril(np.ones((n, n)), -1) - np.diag(np.arange(n)) + d = np.arange(n) * np.arange(1, n+1) + H[0] = 1 + d[0] = n + H_full = H / np.sqrt(d)[:, np.newaxis] + if full: + return H_full + else: + return H_full[1:] + + +def hilbert(n): + """ + Create a Hilbert matrix of order `n`. + + Returns the `n` by `n` array with entries `h[i,j] = 1 / (i + j + 1)`. + + Parameters + ---------- + n : int + The size of the array to create. + + Returns + ------- + h : (n, n) ndarray + The Hilbert matrix. + + See Also + -------- + invhilbert : Compute the inverse of a Hilbert matrix. + + Notes + ----- + .. versionadded:: 0.10.0 + + Examples + -------- + >>> from scipy.linalg import hilbert + >>> hilbert(3) + array([[ 1. , 0.5 , 0.33333333], + [ 0.5 , 0.33333333, 0.25 ], + [ 0.33333333, 0.25 , 0.2 ]]) + + """ + values = 1.0 / (1.0 + np.arange(2 * n - 1)) + h = hankel(values[:n], r=values[n - 1:]) + return h + + +def invhilbert(n, exact=False): + """ + Compute the inverse of the Hilbert matrix of order `n`. + + The entries in the inverse of a Hilbert matrix are integers. When `n` + is greater than 14, some entries in the inverse exceed the upper limit + of 64 bit integers. The `exact` argument provides two options for + dealing with these large integers. + + Parameters + ---------- + n : int + The order of the Hilbert matrix. + exact : bool, optional + If False, the data type of the array that is returned is np.float64, + and the array is an approximation of the inverse. + If True, the array is the exact integer inverse array. To represent + the exact inverse when n > 14, the returned array is an object array + of long integers. For n <= 14, the exact inverse is returned as an + array with data type np.int64. + + Returns + ------- + invh : (n, n) ndarray + The data type of the array is np.float64 if `exact` is False. + If `exact` is True, the data type is either np.int64 (for n <= 14) + or object (for n > 14). In the latter case, the objects in the + array will be long integers. + + See Also + -------- + hilbert : Create a Hilbert matrix. + + Notes + ----- + .. versionadded:: 0.10.0 + + Examples + -------- + >>> from scipy.linalg import invhilbert + >>> invhilbert(4) + array([[ 16., -120., 240., -140.], + [ -120., 1200., -2700., 1680.], + [ 240., -2700., 6480., -4200.], + [ -140., 1680., -4200., 2800.]]) + >>> invhilbert(4, exact=True) + array([[ 16, -120, 240, -140], + [ -120, 1200, -2700, 1680], + [ 240, -2700, 6480, -4200], + [ -140, 1680, -4200, 2800]], dtype=int64) + >>> invhilbert(16)[7,7] + 4.2475099528537506e+19 + >>> invhilbert(16, exact=True)[7,7] + 42475099528537378560 + + """ + from scipy.special import comb + if exact: + if n > 14: + dtype = object + else: + dtype = np.int64 + else: + dtype = np.float64 + invh = np.empty((n, n), dtype=dtype) + for i in range(n): + for j in range(0, i + 1): + s = i + j + invh[i, j] = ((-1) ** s * (s + 1) * + comb(n + i, n - j - 1, exact=exact) * + comb(n + j, n - i - 1, exact=exact) * + comb(s, i, exact=exact) ** 2) + if i != j: + invh[j, i] = invh[i, j] + return invh + + +def pascal(n, kind='symmetric', exact=True): + """ + Returns the n x n Pascal matrix. + + The Pascal matrix is a matrix containing the binomial coefficients as + its elements. + + Parameters + ---------- + n : int + The size of the matrix to create; that is, the result is an n x n + matrix. + kind : str, optional + Must be one of 'symmetric', 'lower', or 'upper'. + Default is 'symmetric'. + exact : bool, optional + If `exact` is True, the result is either an array of type + numpy.uint64 (if n < 35) or an object array of Python long integers. + If `exact` is False, the coefficients in the matrix are computed using + `scipy.special.comb` with ``exact=False``. The result will be a floating + point array, and the values in the array will not be the exact + coefficients, but this version is much faster than ``exact=True``. + + Returns + ------- + p : (n, n) ndarray + The Pascal matrix. + + See Also + -------- + invpascal + + Notes + ----- + See https://en.wikipedia.org/wiki/Pascal_matrix for more information + about Pascal matrices. + + .. versionadded:: 0.11.0 + + Examples + -------- + >>> from scipy.linalg import pascal + >>> pascal(4) + array([[ 1, 1, 1, 1], + [ 1, 2, 3, 4], + [ 1, 3, 6, 10], + [ 1, 4, 10, 20]], dtype=uint64) + >>> pascal(4, kind='lower') + array([[1, 0, 0, 0], + [1, 1, 0, 0], + [1, 2, 1, 0], + [1, 3, 3, 1]], dtype=uint64) + >>> pascal(50)[-1, -1] + 25477612258980856902730428600 + >>> from scipy.special import comb + >>> comb(98, 49, exact=True) + 25477612258980856902730428600 + + """ + + from scipy.special import comb + if kind not in ['symmetric', 'lower', 'upper']: + raise ValueError("kind must be 'symmetric', 'lower', or 'upper'") + + if exact: + if n >= 35: + L_n = np.empty((n, n), dtype=object) + L_n.fill(0) + else: + L_n = np.zeros((n, n), dtype=np.uint64) + for i in range(n): + for j in range(i + 1): + L_n[i, j] = comb(i, j, exact=True) + else: + L_n = comb(*np.ogrid[:n, :n]) + + if kind == 'lower': + p = L_n + elif kind == 'upper': + p = L_n.T + else: + p = np.dot(L_n, L_n.T) + + return p + + +def invpascal(n, kind='symmetric', exact=True): + """ + Returns the inverse of the n x n Pascal matrix. + + The Pascal matrix is a matrix containing the binomial coefficients as + its elements. + + Parameters + ---------- + n : int + The size of the matrix to create; that is, the result is an n x n + matrix. + kind : str, optional + Must be one of 'symmetric', 'lower', or 'upper'. + Default is 'symmetric'. + exact : bool, optional + If `exact` is True, the result is either an array of type + ``numpy.int64`` (if `n` <= 35) or an object array of Python integers. + If `exact` is False, the coefficients in the matrix are computed using + `scipy.special.comb` with `exact=False`. The result will be a floating + point array, and for large `n`, the values in the array will not be the + exact coefficients. + + Returns + ------- + invp : (n, n) ndarray + The inverse of the Pascal matrix. + + See Also + -------- + pascal + + Notes + ----- + + .. versionadded:: 0.16.0 + + References + ---------- + .. [1] "Pascal matrix", https://en.wikipedia.org/wiki/Pascal_matrix + .. [2] Cohen, A. M., "The inverse of a Pascal matrix", Mathematical + Gazette, 59(408), pp. 111-112, 1975. + + Examples + -------- + >>> from scipy.linalg import invpascal, pascal + >>> invp = invpascal(5) + >>> invp + array([[ 5, -10, 10, -5, 1], + [-10, 30, -35, 19, -4], + [ 10, -35, 46, -27, 6], + [ -5, 19, -27, 17, -4], + [ 1, -4, 6, -4, 1]]) + + >>> p = pascal(5) + >>> p.dot(invp) + array([[ 1., 0., 0., 0., 0.], + [ 0., 1., 0., 0., 0.], + [ 0., 0., 1., 0., 0.], + [ 0., 0., 0., 1., 0.], + [ 0., 0., 0., 0., 1.]]) + + An example of the use of `kind` and `exact`: + + >>> invpascal(5, kind='lower', exact=False) + array([[ 1., -0., 0., -0., 0.], + [-1., 1., -0., 0., -0.], + [ 1., -2., 1., -0., 0.], + [-1., 3., -3., 1., -0.], + [ 1., -4., 6., -4., 1.]]) + + """ + from scipy.special import comb + + if kind not in ['symmetric', 'lower', 'upper']: + raise ValueError("'kind' must be 'symmetric', 'lower' or 'upper'.") + + if kind == 'symmetric': + if exact: + if n > 34: + dt = object + else: + dt = np.int64 + else: + dt = np.float64 + invp = np.empty((n, n), dtype=dt) + for i in range(n): + for j in range(0, i + 1): + v = 0 + for k in range(n - i): + v += comb(i + k, k, exact=exact) * comb(i + k, i + k - j, + exact=exact) + invp[i, j] = (-1)**(i - j) * v + if i != j: + invp[j, i] = invp[i, j] + else: + # For the 'lower' and 'upper' cases, we computer the inverse by + # changing the sign of every other diagonal of the pascal matrix. + invp = pascal(n, kind=kind, exact=exact) + if invp.dtype == np.uint64: + # This cast from np.uint64 to int64 OK, because if `kind` is not + # "symmetric", the values in invp are all much less than 2**63. + invp = invp.view(np.int64) + + # The toeplitz matrix has alternating bands of 1 and -1. + invp *= toeplitz((-1)**np.arange(n)).astype(invp.dtype) + + return invp + + +def dft(n, scale=None): + """ + Discrete Fourier transform matrix. + + Create the matrix that computes the discrete Fourier transform of a + sequence [1]_. The nth primitive root of unity used to generate the + matrix is exp(-2*pi*i/n), where i = sqrt(-1). + + Parameters + ---------- + n : int + Size the matrix to create. + scale : str, optional + Must be None, 'sqrtn', or 'n'. + If `scale` is 'sqrtn', the matrix is divided by `sqrt(n)`. + If `scale` is 'n', the matrix is divided by `n`. + If `scale` is None (the default), the matrix is not normalized, and the + return value is simply the Vandermonde matrix of the roots of unity. + + Returns + ------- + m : (n, n) ndarray + The DFT matrix. + + Notes + ----- + When `scale` is None, multiplying a vector by the matrix returned by + `dft` is mathematically equivalent to (but much less efficient than) + the calculation performed by `scipy.fft.fft`. + + .. versionadded:: 0.14.0 + + References + ---------- + .. [1] "DFT matrix", https://en.wikipedia.org/wiki/DFT_matrix + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import dft + >>> np.set_printoptions(precision=2, suppress=True) # for compact output + >>> m = dft(5) + >>> m + array([[ 1. +0.j , 1. +0.j , 1. +0.j , 1. +0.j , 1. +0.j ], + [ 1. +0.j , 0.31-0.95j, -0.81-0.59j, -0.81+0.59j, 0.31+0.95j], + [ 1. +0.j , -0.81-0.59j, 0.31+0.95j, 0.31-0.95j, -0.81+0.59j], + [ 1. +0.j , -0.81+0.59j, 0.31-0.95j, 0.31+0.95j, -0.81-0.59j], + [ 1. +0.j , 0.31+0.95j, -0.81+0.59j, -0.81-0.59j, 0.31-0.95j]]) + >>> x = np.array([1, 2, 3, 0, 3]) + >>> m @ x # Compute the DFT of x + array([ 9. +0.j , 0.12-0.81j, -2.12+3.44j, -2.12-3.44j, 0.12+0.81j]) + + Verify that ``m @ x`` is the same as ``fft(x)``. + + >>> from scipy.fft import fft + >>> fft(x) # Same result as m @ x + array([ 9. +0.j , 0.12-0.81j, -2.12+3.44j, -2.12-3.44j, 0.12+0.81j]) + """ + if scale not in [None, 'sqrtn', 'n']: + raise ValueError("scale must be None, 'sqrtn', or 'n'; " + f"{scale!r} is not valid.") + + omegas = np.exp(-2j * np.pi * np.arange(n) / n).reshape(-1, 1) + m = omegas ** np.arange(n) + if scale == 'sqrtn': + m /= math.sqrt(n) + elif scale == 'n': + m /= n + return m + + +def fiedler(a): + """Returns a symmetric Fiedler matrix + + Given an sequence of numbers `a`, Fiedler matrices have the structure + ``F[i, j] = np.abs(a[i] - a[j])``, and hence zero diagonals and nonnegative + entries. A Fiedler matrix has a dominant positive eigenvalue and other + eigenvalues are negative. Although not valid generally, for certain inputs, + the inverse and the determinant can be derived explicitly as given in [1]_. + + Parameters + ---------- + a : (..., n,) array_like + Coefficient array. N-dimensional arrays are treated as a batch: + each slice along the last axis is a 1-D coefficient array. + + Returns + ------- + F : (..., n, n) ndarray + Fiedler matrix. For batch input, each slice of shape ``(n, n)`` + along the last two dimensions of the output corresponds with a + slice of shape ``(n,)`` along the last dimension of the input. + + See Also + -------- + circulant, toeplitz + + Notes + ----- + + .. versionadded:: 1.3.0 + + References + ---------- + .. [1] J. Todd, "Basic Numerical Mathematics: Vol.2 : Numerical Algebra", + 1977, Birkhauser, :doi:`10.1007/978-3-0348-7286-7` + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import det, inv, fiedler + >>> a = [1, 4, 12, 45, 77] + >>> n = len(a) + >>> A = fiedler(a) + >>> A + array([[ 0, 3, 11, 44, 76], + [ 3, 0, 8, 41, 73], + [11, 8, 0, 33, 65], + [44, 41, 33, 0, 32], + [76, 73, 65, 32, 0]]) + + The explicit formulas for determinant and inverse seem to hold only for + monotonically increasing/decreasing arrays. Note the tridiagonal structure + and the corners. + + >>> Ai = inv(A) + >>> Ai[np.abs(Ai) < 1e-12] = 0. # cleanup the numerical noise for display + >>> Ai + array([[-0.16008772, 0.16666667, 0. , 0. , 0.00657895], + [ 0.16666667, -0.22916667, 0.0625 , 0. , 0. ], + [ 0. , 0.0625 , -0.07765152, 0.01515152, 0. ], + [ 0. , 0. , 0.01515152, -0.03077652, 0.015625 ], + [ 0.00657895, 0. , 0. , 0.015625 , -0.00904605]]) + >>> det(A) + 15409151.999999998 + >>> (-1)**(n-1) * 2**(n-2) * np.diff(a).prod() * (a[-1] - a[0]) + 15409152 + + """ + a = np.atleast_1d(a) + + if a.ndim > 1: + return np.apply_along_axis(fiedler, -1, a) + + if a.size == 0: + return np.array([], dtype=float) + elif a.size == 1: + return np.array([[0.]]) + else: + return np.abs(a[:, None] - a) + + +def fiedler_companion(a): + """ Returns a Fiedler companion matrix + + Given a polynomial coefficient array ``a``, this function forms a + pentadiagonal matrix with a special structure whose eigenvalues coincides + with the roots of ``a``. + + Parameters + ---------- + a : (..., N) array_like + 1-D array of polynomial coefficients in descending order with a nonzero + leading coefficient. For ``N < 2``, an empty array is returned. + N-dimensional arrays are treated as a batch: each slice along the last + axis is a 1-D array of polynomial coefficients. + + Returns + ------- + c : (..., N-1, N-1) ndarray + Resulting companion matrix. For batch input, each slice of shape + ``(N-1, N-1)`` along the last two dimensions of the output corresponds + with a slice of shape ``(N,)`` along the last dimension of the input. + + See Also + -------- + companion + + Notes + ----- + Similar to `companion`, each leading coefficient along the last axis of the + input should be nonzero. + If the leading coefficient is not 1, other coefficients are rescaled before + the array generation. To avoid numerical issues, it is best to provide a + monic polynomial. + + .. versionadded:: 1.3.0 + + References + ---------- + .. [1] M. Fiedler, " A note on companion matrices", Linear Algebra and its + Applications, 2003, :doi:`10.1016/S0024-3795(03)00548-2` + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import fiedler_companion, eigvals + >>> p = np.poly(np.arange(1, 9, 2)) # [1., -16., 86., -176., 105.] + >>> fc = fiedler_companion(p) + >>> fc + array([[ 16., -86., 1., 0.], + [ 1., 0., 0., 0.], + [ 0., 176., 0., -105.], + [ 0., 1., 0., 0.]]) + >>> eigvals(fc) + array([7.+0.j, 5.+0.j, 3.+0.j, 1.+0.j]) + + """ + a = np.atleast_1d(a) + + if a.ndim > 1: + return np.apply_along_axis(fiedler_companion, -1, a) + + if a.size <= 2: + if a.size == 2: + return np.array([[-(a/a[0])[-1]]]) + return np.array([], dtype=a.dtype) + + if a[0] == 0.: + raise ValueError('Leading coefficient is zero.') + + a = a/a[0] + n = a.size - 1 + c = np.zeros((n, n), dtype=a.dtype) + # subdiagonals + c[range(3, n, 2), range(1, n-2, 2)] = 1. + c[range(2, n, 2), range(1, n-1, 2)] = -a[3::2] + # superdiagonals + c[range(0, n-2, 2), range(2, n, 2)] = 1. + c[range(0, n-1, 2), range(1, n, 2)] = -a[2::2] + c[[0, 1], 0] = [-a[1], 1] + + return c + + +def convolution_matrix(a, n, mode='full'): + """ + Construct a convolution matrix. + + Constructs the Toeplitz matrix representing one-dimensional + convolution [1]_. See the notes below for details. + + Parameters + ---------- + a : (..., m) array_like + The 1-D array to convolve. N-dimensional arrays are treated as a + batch: each slice along the last axis is a 1-D array to convolve. + n : int + The number of columns in the resulting matrix. It gives the length + of the input to be convolved with `a`. This is analogous to the + length of `v` in ``numpy.convolve(a, v)``. + mode : str + This is analogous to `mode` in ``numpy.convolve(v, a, mode)``. + It must be one of ('full', 'valid', 'same'). + See below for how `mode` determines the shape of the result. + + Returns + ------- + A : (..., k, n) ndarray + The convolution matrix whose row count `k` depends on `mode`:: + + ======= ========================= + mode k + ======= ========================= + 'full' m + n -1 + 'same' max(m, n) + 'valid' max(m, n) - min(m, n) + 1 + ======= ========================= + + For batch input, each slice of shape ``(k, n)`` along the last two + dimensions of the output corresponds with a slice of shape ``(m,)`` + along the last dimension of the input. + + See Also + -------- + toeplitz : Toeplitz matrix + + Notes + ----- + The code:: + + A = convolution_matrix(a, n, mode) + + creates a Toeplitz matrix `A` such that ``A @ v`` is equivalent to + using ``convolve(a, v, mode)``. The returned array always has `n` + columns. The number of rows depends on the specified `mode`, as + explained above. + + In the default 'full' mode, the entries of `A` are given by:: + + A[i, j] == (a[i-j] if (0 <= (i-j) < m) else 0) + + where ``m = len(a)``. Suppose, for example, the input array is + ``[x, y, z]``. The convolution matrix has the form:: + + [x, 0, 0, ..., 0, 0] + [y, x, 0, ..., 0, 0] + [z, y, x, ..., 0, 0] + ... + [0, 0, 0, ..., x, 0] + [0, 0, 0, ..., y, x] + [0, 0, 0, ..., z, y] + [0, 0, 0, ..., 0, z] + + In 'valid' mode, the entries of `A` are given by:: + + A[i, j] == (a[i-j+m-1] if (0 <= (i-j+m-1) < m) else 0) + + This corresponds to a matrix whose rows are the subset of those from + the 'full' case where all the coefficients in `a` are contained in the + row. For input ``[x, y, z]``, this array looks like:: + + [z, y, x, 0, 0, ..., 0, 0, 0] + [0, z, y, x, 0, ..., 0, 0, 0] + [0, 0, z, y, x, ..., 0, 0, 0] + ... + [0, 0, 0, 0, 0, ..., x, 0, 0] + [0, 0, 0, 0, 0, ..., y, x, 0] + [0, 0, 0, 0, 0, ..., z, y, x] + + In the 'same' mode, the entries of `A` are given by:: + + d = (m - 1) // 2 + A[i, j] == (a[i-j+d] if (0 <= (i-j+d) < m) else 0) + + The typical application of the 'same' mode is when one has a signal of + length `n` (with `n` greater than ``len(a)``), and the desired output + is a filtered signal that is still of length `n`. + + For input ``[x, y, z]``, this array looks like:: + + [y, x, 0, 0, ..., 0, 0, 0] + [z, y, x, 0, ..., 0, 0, 0] + [0, z, y, x, ..., 0, 0, 0] + [0, 0, z, y, ..., 0, 0, 0] + ... + [0, 0, 0, 0, ..., y, x, 0] + [0, 0, 0, 0, ..., z, y, x] + [0, 0, 0, 0, ..., 0, z, y] + + .. versionadded:: 1.5.0 + + References + ---------- + .. [1] "Convolution", https://en.wikipedia.org/wiki/Convolution + + Examples + -------- + >>> import numpy as np + >>> from scipy.linalg import convolution_matrix + >>> A = convolution_matrix([-1, 4, -2], 5, mode='same') + >>> A + array([[ 4, -1, 0, 0, 0], + [-2, 4, -1, 0, 0], + [ 0, -2, 4, -1, 0], + [ 0, 0, -2, 4, -1], + [ 0, 0, 0, -2, 4]]) + + Compare multiplication by `A` with the use of `numpy.convolve`. + + >>> x = np.array([1, 2, 0, -3, 0.5]) + >>> A @ x + array([ 2. , 6. , -1. , -12.5, 8. ]) + + Verify that ``A @ x`` produced the same result as applying the + convolution function. + + >>> np.convolve([-1, 4, -2], x, mode='same') + array([ 2. , 6. , -1. , -12.5, 8. ]) + + For comparison to the case ``mode='same'`` shown above, here are the + matrices produced by ``mode='full'`` and ``mode='valid'`` for the + same coefficients and size. + + >>> convolution_matrix([-1, 4, -2], 5, mode='full') + array([[-1, 0, 0, 0, 0], + [ 4, -1, 0, 0, 0], + [-2, 4, -1, 0, 0], + [ 0, -2, 4, -1, 0], + [ 0, 0, -2, 4, -1], + [ 0, 0, 0, -2, 4], + [ 0, 0, 0, 0, -2]]) + + >>> convolution_matrix([-1, 4, -2], 5, mode='valid') + array([[-2, 4, -1, 0, 0], + [ 0, -2, 4, -1, 0], + [ 0, 0, -2, 4, -1]]) + """ + if n <= 0: + raise ValueError('n must be a positive integer.') + + a = np.asarray(a) + + if a.size == 0: + raise ValueError('len(a) must be at least 1.') + + if mode not in ('full', 'valid', 'same'): + raise ValueError( + "'mode' argument must be one of ('full', 'valid', 'same')") + + if a.ndim > 1: + return np.apply_along_axis(lambda a: convolution_matrix(a, n, mode), -1, a) + + # create zero padded versions of the array + az = np.pad(a, (0, n-1), 'constant') + raz = np.pad(a[::-1], (0, n-1), 'constant') + + if mode == 'same': + trim = min(n, len(a)) - 1 + tb = trim//2 + te = trim - tb + col0 = az[tb:len(az)-te] + row0 = raz[-n-tb:len(raz)-tb] + elif mode == 'valid': + tb = min(n, len(a)) - 1 + te = tb + col0 = az[tb:len(az)-te] + row0 = raz[-n-tb:len(raz)-tb] + else: # 'full' + col0 = az + row0 = raz[-n:] + return toeplitz(col0, row0) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_testutils.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_testutils.py new file mode 100644 index 0000000000000000000000000000000000000000..f6d01d2b6e59b040f39c0b53cc2788bbd3d0888f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/_testutils.py @@ -0,0 +1,65 @@ +import numpy as np + + +class _FakeMatrix: + def __init__(self, data): + self._data = data + self.__array_interface__ = data.__array_interface__ + + +class _FakeMatrix2: + def __init__(self, data): + self._data = data + + def __array__(self, dtype=None, copy=None): + if copy: + return self._data.copy() + return self._data + + +def _get_array(shape, dtype): + """ + Get a test array of given shape and data type. + Returned NxN matrices are posdef, and 2xN are banded-posdef. + + """ + if len(shape) == 2 and shape[0] == 2: + # yield a banded positive definite one + x = np.zeros(shape, dtype=dtype) + x[0, 1:] = -1 + x[1] = 2 + return x + elif len(shape) == 2 and shape[0] == shape[1]: + # always yield a positive definite matrix + x = np.zeros(shape, dtype=dtype) + j = np.arange(shape[0]) + x[j, j] = 2 + x[j[:-1], j[:-1]+1] = -1 + x[j[:-1]+1, j[:-1]] = -1 + return x + else: + np.random.seed(1234) + return np.random.randn(*shape).astype(dtype) + + +def _id(x): + return x + + +def assert_no_overwrite(call, shapes, dtypes=None): + """ + Test that a call does not overwrite its input arguments + """ + + if dtypes is None: + dtypes = [np.float32, np.float64, np.complex64, np.complex128] + + for dtype in dtypes: + for order in ["C", "F"]: + for faker in [_id, _FakeMatrix, _FakeMatrix2]: + orig_inputs = [_get_array(s, dtype) for s in shapes] + inputs = [faker(x.copy(order)) for x in orig_inputs] + call(*inputs) + msg = f"call modified inputs [{dtype!r}, {faker!r}]" + for a, b in zip(inputs, orig_inputs): + np.testing.assert_equal(a, b, err_msg=msg) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/basic.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/basic.py new file mode 100644 index 0000000000000000000000000000000000000000..04ef3645a2ed6a22106ed8ca1acf9e9ac93df5cf --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/basic.py @@ -0,0 +1,23 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.linalg` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'solve', 'solve_triangular', 'solveh_banded', 'solve_banded', + 'solve_toeplitz', 'solve_circulant', 'inv', 'det', 'lstsq', + 'pinv', 'pinvh', 'matrix_balance', 'matmul_toeplitz', + 'get_lapack_funcs', 'LinAlgError', 'LinAlgWarning', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="linalg", module="basic", + private_modules=["_basic"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/blas.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/blas.py new file mode 100644 index 0000000000000000000000000000000000000000..c943460e6bafcd9a382586d5a5155357382ea596 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/blas.py @@ -0,0 +1,484 @@ +""" +Low-level BLAS functions (:mod:`scipy.linalg.blas`) +=================================================== + +This module contains low-level functions from the BLAS library. + +.. versionadded:: 0.12.0 + +.. note:: + + The common ``overwrite_<>`` option in many routines, allows the + input arrays to be overwritten to avoid extra memory allocation. + However this requires the array to satisfy two conditions + which are memory order and the data type to match exactly the + order and the type expected by the routine. + + As an example, if you pass a double precision float array to any + ``S....`` routine which expects single precision arguments, f2py + will create an intermediate array to match the argument types and + overwriting will be performed on that intermediate array. + + Similarly, if a C-contiguous array is passed, f2py will pass a + FORTRAN-contiguous array internally. Please make sure that these + details are satisfied. More information can be found in the f2py + documentation. + +.. warning:: + + These functions do little to no error checking. + It is possible to cause crashes by mis-using them, + so prefer using the higher-level routines in `scipy.linalg`. + +Finding functions +----------------- + +.. autosummary:: + :toctree: generated/ + + get_blas_funcs + find_best_blas_type + +BLAS Level 1 functions +---------------------- + +.. autosummary:: + :toctree: generated/ + + caxpy + ccopy + cdotc + cdotu + crotg + cscal + csrot + csscal + cswap + dasum + daxpy + dcopy + ddot + dnrm2 + drot + drotg + drotm + drotmg + dscal + dswap + dzasum + dznrm2 + icamax + idamax + isamax + izamax + sasum + saxpy + scasum + scnrm2 + scopy + sdot + snrm2 + srot + srotg + srotm + srotmg + sscal + sswap + zaxpy + zcopy + zdotc + zdotu + zdrot + zdscal + zrotg + zscal + zswap + +BLAS Level 2 functions +---------------------- + +.. autosummary:: + :toctree: generated/ + + sgbmv + sgemv + sger + ssbmv + sspr + sspr2 + ssymv + ssyr + ssyr2 + stbmv + stpsv + strmv + strsv + dgbmv + dgemv + dger + dsbmv + dspr + dspr2 + dsymv + dsyr + dsyr2 + dtbmv + dtpsv + dtrmv + dtrsv + cgbmv + cgemv + cgerc + cgeru + chbmv + chemv + cher + cher2 + chpmv + chpr + chpr2 + ctbmv + ctbsv + ctpmv + ctpsv + ctrmv + ctrsv + csyr + zgbmv + zgemv + zgerc + zgeru + zhbmv + zhemv + zher + zher2 + zhpmv + zhpr + zhpr2 + ztbmv + ztbsv + ztpmv + ztrmv + ztrsv + zsyr + +BLAS Level 3 functions +---------------------- + +.. autosummary:: + :toctree: generated/ + + sgemm + ssymm + ssyr2k + ssyrk + strmm + strsm + dgemm + dsymm + dsyr2k + dsyrk + dtrmm + dtrsm + cgemm + chemm + cher2k + cherk + csymm + csyr2k + csyrk + ctrmm + ctrsm + zgemm + zhemm + zher2k + zherk + zsymm + zsyr2k + zsyrk + ztrmm + ztrsm + +""" +# +# Author: Pearu Peterson, March 2002 +# refactoring by Fabian Pedregosa, March 2010 +# + +__all__ = ['get_blas_funcs', 'find_best_blas_type'] + +import numpy as np +import functools + +from scipy.linalg import _fblas +try: + from scipy.linalg import _cblas +except ImportError: + _cblas = None + +try: + from scipy.linalg import _fblas_64 + HAS_ILP64 = True +except ImportError: + HAS_ILP64 = False + _fblas_64 = None + +# Expose all functions (only fblas --- cblas is an implementation detail) +empty_module = None +from scipy.linalg._fblas import * # noqa: E402, F403 +del empty_module + +# all numeric dtypes '?bBhHiIlLqQefdgFDGO' that are safe to be converted to + +# single precision float : '?bBhH!!!!!!ef!!!!!!' +# double precision float : '?bBhHiIlLqQefdg!!!!' +# single precision complex : '?bBhH!!!!!!ef!!F!!!' +# double precision complex : '?bBhHiIlLqQefdgFDG!' + +_type_score = {x: 1 for x in '?bBhHef'} +_type_score.update({x: 2 for x in 'iIlLqQd'}) + +# Handle float128(g) and complex256(G) separately in case non-Windows systems. +# On Windows, the values will be rewritten to the same key with the same value. +_type_score.update({'F': 3, 'D': 4, 'g': 2, 'G': 4}) + +# Final mapping to the actual prefixes and dtypes +_type_conv = {1: ('s', np.dtype('float32')), + 2: ('d', np.dtype('float64')), + 3: ('c', np.dtype('complex64')), + 4: ('z', np.dtype('complex128'))} + +# some convenience alias for complex functions +_blas_alias = {'cnrm2': 'scnrm2', 'znrm2': 'dznrm2', + 'cdot': 'cdotc', 'zdot': 'zdotc', + 'cger': 'cgerc', 'zger': 'zgerc', + 'sdotc': 'sdot', 'sdotu': 'sdot', + 'ddotc': 'ddot', 'ddotu': 'ddot'} + + +def find_best_blas_type(arrays=(), dtype=None): + """Find best-matching BLAS/LAPACK type. + + Arrays are used to determine the optimal prefix of BLAS routines. + + Parameters + ---------- + arrays : sequence of ndarrays, optional + Arrays can be given to determine optimal prefix of BLAS + routines. If not given, double-precision routines will be + used, otherwise the most generic type in arrays will be used. + dtype : str or dtype, optional + Data-type specifier. Not used if `arrays` is non-empty. + + Returns + ------- + prefix : str + BLAS/LAPACK prefix character. + dtype : dtype + Inferred Numpy data type. + prefer_fortran : bool + Whether to prefer Fortran order routines over C order. + + Examples + -------- + >>> import numpy as np + >>> import scipy.linalg.blas as bla + >>> rng = np.random.default_rng() + >>> a = rng.random((10,15)) + >>> b = np.asfortranarray(a) # Change the memory layout order + >>> bla.find_best_blas_type((a,)) + ('d', dtype('float64'), False) + >>> bla.find_best_blas_type((a*1j,)) + ('z', dtype('complex128'), False) + >>> bla.find_best_blas_type((b,)) + ('d', dtype('float64'), True) + + """ + dtype = np.dtype(dtype) + max_score = _type_score.get(dtype.char, 5) + prefer_fortran = False + + if arrays: + # In most cases, single element is passed through, quicker route + if len(arrays) == 1: + max_score = _type_score.get(arrays[0].dtype.char, 5) + prefer_fortran = arrays[0].flags['FORTRAN'] + else: + # use the most generic type in arrays + scores = [_type_score.get(x.dtype.char, 5) for x in arrays] + max_score = max(scores) + ind_max_score = scores.index(max_score) + # safe upcasting for mix of float64 and complex64 --> prefix 'z' + if max_score == 3 and (2 in scores): + max_score = 4 + + if arrays[ind_max_score].flags['FORTRAN']: + # prefer Fortran for leading array with column major order + prefer_fortran = True + + # Get the LAPACK prefix and the corresponding dtype if not fall back + # to 'd' and double precision float. + prefix, dtype = _type_conv.get(max_score, ('d', np.dtype('float64'))) + + return prefix, dtype, prefer_fortran + + +def _get_funcs(names, arrays, dtype, + lib_name, fmodule, cmodule, + fmodule_name, cmodule_name, alias, + ilp64=False): + """ + Return available BLAS/LAPACK functions. + + Used also in lapack.py. See get_blas_funcs for docstring. + """ + + funcs = [] + unpack = False + dtype = np.dtype(dtype) + module1 = (cmodule, cmodule_name) + module2 = (fmodule, fmodule_name) + + if isinstance(names, str): + names = (names,) + unpack = True + + prefix, dtype, prefer_fortran = find_best_blas_type(arrays, dtype) + + if prefer_fortran: + module1, module2 = module2, module1 + + for name in names: + func_name = prefix + name + func_name = alias.get(func_name, func_name) + func = getattr(module1[0], func_name, None) + module_name = module1[1] + if func is None: + func = getattr(module2[0], func_name, None) + module_name = module2[1] + if func is None: + raise ValueError( + f'{lib_name} function {func_name} could not be found') + func.module_name, func.typecode = module_name, prefix + func.dtype = dtype + if not ilp64: + func.int_dtype = np.dtype(np.intc) + else: + func.int_dtype = np.dtype(np.int64) + func.prefix = prefix # Backward compatibility + funcs.append(func) + + if unpack: + return funcs[0] + else: + return funcs + + +def _memoize_get_funcs(func): + """ + Memoized fast path for _get_funcs instances + """ + memo = {} + func.memo = memo + + @functools.wraps(func) + def getter(names, arrays=(), dtype=None, ilp64=False): + key = (names, dtype, ilp64) + for array in arrays: + # cf. find_blas_funcs + key += (array.dtype.char, array.flags.fortran) + + try: + value = memo.get(key) + except TypeError: + # unhashable key etc. + key = None + value = None + + if value is not None: + return value + + value = func(names, arrays, dtype, ilp64) + + if key is not None: + memo[key] = value + + return value + + return getter + + +@_memoize_get_funcs +def get_blas_funcs(names, arrays=(), dtype=None, ilp64=False): + """Return available BLAS function objects from names. + + Arrays are used to determine the optimal prefix of BLAS routines. + + Parameters + ---------- + names : str or sequence of str + Name(s) of BLAS functions without type prefix. + + arrays : sequence of ndarrays, optional + Arrays can be given to determine optimal prefix of BLAS + routines. If not given, double-precision routines will be + used, otherwise the most generic type in arrays will be used. + + dtype : str or dtype, optional + Data-type specifier. Not used if `arrays` is non-empty. + + ilp64 : {True, False, 'preferred'}, optional + Whether to return ILP64 routine variant. + Choosing 'preferred' returns ILP64 routine if available, + and otherwise the 32-bit routine. Default: False + + Returns + ------- + funcs : list + List containing the found function(s). + + + Notes + ----- + This routine automatically chooses between Fortran/C + interfaces. Fortran code is used whenever possible for arrays with + column major order. In all other cases, C code is preferred. + + In BLAS, the naming convention is that all functions start with a + type prefix, which depends on the type of the principal + matrix. These can be one of {'s', 'd', 'c', 'z'} for the NumPy + types {float32, float64, complex64, complex128} respectively. + The code and the dtype are stored in attributes `typecode` and `dtype` + of the returned functions. + + Examples + -------- + >>> import numpy as np + >>> import scipy.linalg as LA + >>> rng = np.random.default_rng() + >>> a = rng.random((3,2)) + >>> x_gemv = LA.get_blas_funcs('gemv', (a,)) + >>> x_gemv.typecode + 'd' + >>> x_gemv = LA.get_blas_funcs('gemv',(a*1j,)) + >>> x_gemv.typecode + 'z' + + """ + if isinstance(ilp64, str): + if ilp64 == 'preferred': + ilp64 = HAS_ILP64 + else: + raise ValueError("Invalid value for 'ilp64'") + + if not ilp64: + return _get_funcs(names, arrays, dtype, + "BLAS", _fblas, _cblas, "fblas", "cblas", + _blas_alias, ilp64=False) + else: + if not HAS_ILP64: + raise RuntimeError("BLAS ILP64 routine requested, but Scipy " + "compiled only with 32-bit BLAS") + return _get_funcs(names, arrays, dtype, + "BLAS", _fblas_64, None, "fblas_64", None, + _blas_alias, ilp64=True) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/cython_blas.pxd b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/cython_blas.pxd new file mode 100644 index 0000000000000000000000000000000000000000..7ed44f6ea8611f926e3ea5fd2670446cdf9b398c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/cython_blas.pxd @@ -0,0 +1,169 @@ +""" +This file was generated by _generate_pyx.py. +Do not edit this file directly. +""" + +# Within scipy, these wrappers can be used via relative or absolute cimport. +# Examples: +# from ..linalg cimport cython_blas +# from scipy.linalg cimport cython_blas +# cimport scipy.linalg.cython_blas as cython_blas +# cimport ..linalg.cython_blas as cython_blas + +# Within SciPy, if BLAS functions are needed in C/C++/Fortran, +# these wrappers should not be used. +# The original libraries should be linked directly. + +ctypedef float s +ctypedef double d +ctypedef float complex c +ctypedef double complex z + +cdef void caxpy(int *n, c *ca, c *cx, int *incx, c *cy, int *incy) noexcept nogil +cdef void ccopy(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil +cdef c cdotc(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil +cdef c cdotu(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil +cdef void cgbmv(char *trans, int *m, int *n, int *kl, int *ku, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil +cdef void cgemm(char *transa, char *transb, int *m, int *n, int *k, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogil +cdef void cgemv(char *trans, int *m, int *n, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil +cdef void cgerc(int *m, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *a, int *lda) noexcept nogil +cdef void cgeru(int *m, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *a, int *lda) noexcept nogil +cdef void chbmv(char *uplo, int *n, int *k, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil +cdef void chemm(char *side, char *uplo, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogil +cdef void chemv(char *uplo, int *n, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil +cdef void cher(char *uplo, int *n, s *alpha, c *x, int *incx, c *a, int *lda) noexcept nogil +cdef void cher2(char *uplo, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *a, int *lda) noexcept nogil +cdef void cher2k(char *uplo, char *trans, int *n, int *k, c *alpha, c *a, int *lda, c *b, int *ldb, s *beta, c *c, int *ldc) noexcept nogil +cdef void cherk(char *uplo, char *trans, int *n, int *k, s *alpha, c *a, int *lda, s *beta, c *c, int *ldc) noexcept nogil +cdef void chpmv(char *uplo, int *n, c *alpha, c *ap, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil +cdef void chpr(char *uplo, int *n, s *alpha, c *x, int *incx, c *ap) noexcept nogil +cdef void chpr2(char *uplo, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *ap) noexcept nogil +cdef void crotg(c *ca, c *cb, s *c, c *s) noexcept nogil +cdef void cscal(int *n, c *ca, c *cx, int *incx) noexcept nogil +cdef void csrot(int *n, c *cx, int *incx, c *cy, int *incy, s *c, s *s) noexcept nogil +cdef void csscal(int *n, s *sa, c *cx, int *incx) noexcept nogil +cdef void cswap(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil +cdef void csymm(char *side, char *uplo, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogil +cdef void csyr2k(char *uplo, char *trans, int *n, int *k, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogil +cdef void csyrk(char *uplo, char *trans, int *n, int *k, c *alpha, c *a, int *lda, c *beta, c *c, int *ldc) noexcept nogil +cdef void ctbmv(char *uplo, char *trans, char *diag, int *n, int *k, c *a, int *lda, c *x, int *incx) noexcept nogil +cdef void ctbsv(char *uplo, char *trans, char *diag, int *n, int *k, c *a, int *lda, c *x, int *incx) noexcept nogil +cdef void ctpmv(char *uplo, char *trans, char *diag, int *n, c *ap, c *x, int *incx) noexcept nogil +cdef void ctpsv(char *uplo, char *trans, char *diag, int *n, c *ap, c *x, int *incx) noexcept nogil +cdef void ctrmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb) noexcept nogil +cdef void ctrmv(char *uplo, char *trans, char *diag, int *n, c *a, int *lda, c *x, int *incx) noexcept nogil +cdef void ctrsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb) noexcept nogil +cdef void ctrsv(char *uplo, char *trans, char *diag, int *n, c *a, int *lda, c *x, int *incx) noexcept nogil +cdef d dasum(int *n, d *dx, int *incx) noexcept nogil +cdef void daxpy(int *n, d *da, d *dx, int *incx, d *dy, int *incy) noexcept nogil +cdef d dcabs1(z *z) noexcept nogil +cdef void dcopy(int *n, d *dx, int *incx, d *dy, int *incy) noexcept nogil +cdef d ddot(int *n, d *dx, int *incx, d *dy, int *incy) noexcept nogil +cdef void dgbmv(char *trans, int *m, int *n, int *kl, int *ku, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil +cdef void dgemm(char *transa, char *transb, int *m, int *n, int *k, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) noexcept nogil +cdef void dgemv(char *trans, int *m, int *n, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil +cdef void dger(int *m, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *a, int *lda) noexcept nogil +cdef d dnrm2(int *n, d *x, int *incx) noexcept nogil +cdef void drot(int *n, d *dx, int *incx, d *dy, int *incy, d *c, d *s) noexcept nogil +cdef void drotg(d *da, d *db, d *c, d *s) noexcept nogil +cdef void drotm(int *n, d *dx, int *incx, d *dy, int *incy, d *dparam) noexcept nogil +cdef void drotmg(d *dd1, d *dd2, d *dx1, d *dy1, d *dparam) noexcept nogil +cdef void dsbmv(char *uplo, int *n, int *k, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil +cdef void dscal(int *n, d *da, d *dx, int *incx) noexcept nogil +cdef d dsdot(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil +cdef void dspmv(char *uplo, int *n, d *alpha, d *ap, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil +cdef void dspr(char *uplo, int *n, d *alpha, d *x, int *incx, d *ap) noexcept nogil +cdef void dspr2(char *uplo, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *ap) noexcept nogil +cdef void dswap(int *n, d *dx, int *incx, d *dy, int *incy) noexcept nogil +cdef void dsymm(char *side, char *uplo, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) noexcept nogil +cdef void dsymv(char *uplo, int *n, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil +cdef void dsyr(char *uplo, int *n, d *alpha, d *x, int *incx, d *a, int *lda) noexcept nogil +cdef void dsyr2(char *uplo, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *a, int *lda) noexcept nogil +cdef void dsyr2k(char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) noexcept nogil +cdef void dsyrk(char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *beta, d *c, int *ldc) noexcept nogil +cdef void dtbmv(char *uplo, char *trans, char *diag, int *n, int *k, d *a, int *lda, d *x, int *incx) noexcept nogil +cdef void dtbsv(char *uplo, char *trans, char *diag, int *n, int *k, d *a, int *lda, d *x, int *incx) noexcept nogil +cdef void dtpmv(char *uplo, char *trans, char *diag, int *n, d *ap, d *x, int *incx) noexcept nogil +cdef void dtpsv(char *uplo, char *trans, char *diag, int *n, d *ap, d *x, int *incx) noexcept nogil +cdef void dtrmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb) noexcept nogil +cdef void dtrmv(char *uplo, char *trans, char *diag, int *n, d *a, int *lda, d *x, int *incx) noexcept nogil +cdef void dtrsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb) noexcept nogil +cdef void dtrsv(char *uplo, char *trans, char *diag, int *n, d *a, int *lda, d *x, int *incx) noexcept nogil +cdef d dzasum(int *n, z *zx, int *incx) noexcept nogil +cdef d dznrm2(int *n, z *x, int *incx) noexcept nogil +cdef int icamax(int *n, c *cx, int *incx) noexcept nogil +cdef int idamax(int *n, d *dx, int *incx) noexcept nogil +cdef int isamax(int *n, s *sx, int *incx) noexcept nogil +cdef int izamax(int *n, z *zx, int *incx) noexcept nogil +cdef bint lsame(char *ca, char *cb) noexcept nogil +cdef s sasum(int *n, s *sx, int *incx) noexcept nogil +cdef void saxpy(int *n, s *sa, s *sx, int *incx, s *sy, int *incy) noexcept nogil +cdef s scasum(int *n, c *cx, int *incx) noexcept nogil +cdef s scnrm2(int *n, c *x, int *incx) noexcept nogil +cdef void scopy(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil +cdef s sdot(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil +cdef s sdsdot(int *n, s *sb, s *sx, int *incx, s *sy, int *incy) noexcept nogil +cdef void sgbmv(char *trans, int *m, int *n, int *kl, int *ku, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil +cdef void sgemm(char *transa, char *transb, int *m, int *n, int *k, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) noexcept nogil +cdef void sgemv(char *trans, int *m, int *n, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil +cdef void sger(int *m, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *a, int *lda) noexcept nogil +cdef s snrm2(int *n, s *x, int *incx) noexcept nogil +cdef void srot(int *n, s *sx, int *incx, s *sy, int *incy, s *c, s *s) noexcept nogil +cdef void srotg(s *sa, s *sb, s *c, s *s) noexcept nogil +cdef void srotm(int *n, s *sx, int *incx, s *sy, int *incy, s *sparam) noexcept nogil +cdef void srotmg(s *sd1, s *sd2, s *sx1, s *sy1, s *sparam) noexcept nogil +cdef void ssbmv(char *uplo, int *n, int *k, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil +cdef void sscal(int *n, s *sa, s *sx, int *incx) noexcept nogil +cdef void sspmv(char *uplo, int *n, s *alpha, s *ap, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil +cdef void sspr(char *uplo, int *n, s *alpha, s *x, int *incx, s *ap) noexcept nogil +cdef void sspr2(char *uplo, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *ap) noexcept nogil +cdef void sswap(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil +cdef void ssymm(char *side, char *uplo, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) noexcept nogil +cdef void ssymv(char *uplo, int *n, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil +cdef void ssyr(char *uplo, int *n, s *alpha, s *x, int *incx, s *a, int *lda) noexcept nogil +cdef void ssyr2(char *uplo, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *a, int *lda) noexcept nogil +cdef void ssyr2k(char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) noexcept nogil +cdef void ssyrk(char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *beta, s *c, int *ldc) noexcept nogil +cdef void stbmv(char *uplo, char *trans, char *diag, int *n, int *k, s *a, int *lda, s *x, int *incx) noexcept nogil +cdef void stbsv(char *uplo, char *trans, char *diag, int *n, int *k, s *a, int *lda, s *x, int *incx) noexcept nogil +cdef void stpmv(char *uplo, char *trans, char *diag, int *n, s *ap, s *x, int *incx) noexcept nogil +cdef void stpsv(char *uplo, char *trans, char *diag, int *n, s *ap, s *x, int *incx) noexcept nogil +cdef void strmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb) noexcept nogil +cdef void strmv(char *uplo, char *trans, char *diag, int *n, s *a, int *lda, s *x, int *incx) noexcept nogil +cdef void strsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb) noexcept nogil +cdef void strsv(char *uplo, char *trans, char *diag, int *n, s *a, int *lda, s *x, int *incx) noexcept nogil +cdef void zaxpy(int *n, z *za, z *zx, int *incx, z *zy, int *incy) noexcept nogil +cdef void zcopy(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil +cdef z zdotc(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil +cdef z zdotu(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil +cdef void zdrot(int *n, z *cx, int *incx, z *cy, int *incy, d *c, d *s) noexcept nogil +cdef void zdscal(int *n, d *da, z *zx, int *incx) noexcept nogil +cdef void zgbmv(char *trans, int *m, int *n, int *kl, int *ku, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil +cdef void zgemm(char *transa, char *transb, int *m, int *n, int *k, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogil +cdef void zgemv(char *trans, int *m, int *n, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil +cdef void zgerc(int *m, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *a, int *lda) noexcept nogil +cdef void zgeru(int *m, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *a, int *lda) noexcept nogil +cdef void zhbmv(char *uplo, int *n, int *k, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil +cdef void zhemm(char *side, char *uplo, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogil +cdef void zhemv(char *uplo, int *n, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil +cdef void zher(char *uplo, int *n, d *alpha, z *x, int *incx, z *a, int *lda) noexcept nogil +cdef void zher2(char *uplo, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *a, int *lda) noexcept nogil +cdef void zher2k(char *uplo, char *trans, int *n, int *k, z *alpha, z *a, int *lda, z *b, int *ldb, d *beta, z *c, int *ldc) noexcept nogil +cdef void zherk(char *uplo, char *trans, int *n, int *k, d *alpha, z *a, int *lda, d *beta, z *c, int *ldc) noexcept nogil +cdef void zhpmv(char *uplo, int *n, z *alpha, z *ap, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil +cdef void zhpr(char *uplo, int *n, d *alpha, z *x, int *incx, z *ap) noexcept nogil +cdef void zhpr2(char *uplo, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *ap) noexcept nogil +cdef void zrotg(z *ca, z *cb, d *c, z *s) noexcept nogil +cdef void zscal(int *n, z *za, z *zx, int *incx) noexcept nogil +cdef void zswap(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil +cdef void zsymm(char *side, char *uplo, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogil +cdef void zsyr2k(char *uplo, char *trans, int *n, int *k, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogil +cdef void zsyrk(char *uplo, char *trans, int *n, int *k, z *alpha, z *a, int *lda, z *beta, z *c, int *ldc) noexcept nogil +cdef void ztbmv(char *uplo, char *trans, char *diag, int *n, int *k, z *a, int *lda, z *x, int *incx) noexcept nogil +cdef void ztbsv(char *uplo, char *trans, char *diag, int *n, int *k, z *a, int *lda, z *x, int *incx) noexcept nogil +cdef void ztpmv(char *uplo, char *trans, char *diag, int *n, z *ap, z *x, int *incx) noexcept nogil +cdef void ztpsv(char *uplo, char *trans, char *diag, int *n, z *ap, z *x, int *incx) noexcept nogil +cdef void ztrmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb) noexcept nogil +cdef void ztrmv(char *uplo, char *trans, char *diag, int *n, z *a, int *lda, z *x, int *incx) noexcept nogil +cdef void ztrsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb) noexcept nogil +cdef void ztrsv(char *uplo, char *trans, char *diag, int *n, z *a, int *lda, z *x, int *incx) noexcept nogil diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/cython_blas.pyx b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/cython_blas.pyx new file mode 100644 index 0000000000000000000000000000000000000000..35286fe11d72226269c0e459d9a3109151f74a4a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/cython_blas.pyx @@ -0,0 +1,1432 @@ +# This file was generated by _generate_pyx.py. +# Do not edit this file directly. +# cython: boundscheck = False +# cython: wraparound = False +# cython: cdivision = True + +""" +BLAS Functions for Cython +========================= + +Usable from Cython via:: + + cimport scipy.linalg.cython_blas + +These wrappers do not check for alignment of arrays. +Alignment should be checked before these wrappers are used. + +If using ``cdotu``, ``cdotc``, ``zdotu``, ``zdotc``, ``sladiv``, or ``dladiv``, +the ``CYTHON_CCOMPLEX`` define must be set to 0 during compilation. For +example, in a ``meson.build`` file when using Meson:: + + py.extension_module('ext_module' + 'ext_module.pyx', + c_args: ['-DCYTHON_CCOMPLEX=0'], + ... + ) + +Raw function pointers (Fortran-style pointer arguments): + +- caxpy +- ccopy +- cdotc +- cdotu +- cgbmv +- cgemm +- cgemv +- cgerc +- cgeru +- chbmv +- chemm +- chemv +- cher +- cher2 +- cher2k +- cherk +- chpmv +- chpr +- chpr2 +- crotg +- cscal +- csrot +- csscal +- cswap +- csymm +- csyr2k +- csyrk +- ctbmv +- ctbsv +- ctpmv +- ctpsv +- ctrmm +- ctrmv +- ctrsm +- ctrsv +- dasum +- daxpy +- dcabs1 +- dcopy +- ddot +- dgbmv +- dgemm +- dgemv +- dger +- dnrm2 +- drot +- drotg +- drotm +- drotmg +- dsbmv +- dscal +- dsdot +- dspmv +- dspr +- dspr2 +- dswap +- dsymm +- dsymv +- dsyr +- dsyr2 +- dsyr2k +- dsyrk +- dtbmv +- dtbsv +- dtpmv +- dtpsv +- dtrmm +- dtrmv +- dtrsm +- dtrsv +- dzasum +- dznrm2 +- icamax +- idamax +- isamax +- izamax +- lsame +- sasum +- saxpy +- scasum +- scnrm2 +- scopy +- sdot +- sdsdot +- sgbmv +- sgemm +- sgemv +- sger +- snrm2 +- srot +- srotg +- srotm +- srotmg +- ssbmv +- sscal +- sspmv +- sspr +- sspr2 +- sswap +- ssymm +- ssymv +- ssyr +- ssyr2 +- ssyr2k +- ssyrk +- stbmv +- stbsv +- stpmv +- stpsv +- strmm +- strmv +- strsm +- strsv +- zaxpy +- zcopy +- zdotc +- zdotu +- zdrot +- zdscal +- zgbmv +- zgemm +- zgemv +- zgerc +- zgeru +- zhbmv +- zhemm +- zhemv +- zher +- zher2 +- zher2k +- zherk +- zhpmv +- zhpr +- zhpr2 +- zrotg +- zscal +- zswap +- zsymm +- zsyr2k +- zsyrk +- ztbmv +- ztbsv +- ztpmv +- ztpsv +- ztrmm +- ztrmv +- ztrsm +- ztrsv + + +""" + +# Within SciPy, these wrappers can be used via relative or absolute cimport. +# Examples: +# from ..linalg cimport cython_blas +# from scipy.linalg cimport cython_blas +# cimport scipy.linalg.cython_blas as cython_blas +# cimport ..linalg.cython_blas as cython_blas + +# Within SciPy, if BLAS functions are needed in C/C++/Fortran, +# these wrappers should not be used. +# The original libraries should be linked directly. + +cdef extern from "fortran_defs.h": + pass + +from numpy cimport npy_complex64, npy_complex128 + + +cdef extern from "_blas_subroutines.h": + void _fortran_caxpy "BLAS_FUNC(caxpy)"(int *n, npy_complex64 *ca, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy) nogil +cdef void caxpy(int *n, c *ca, c *cx, int *incx, c *cy, int *incy) noexcept nogil: + + _fortran_caxpy(n, ca, cx, incx, cy, incy) + + +cdef extern from "_blas_subroutines.h": + void _fortran_ccopy "BLAS_FUNC(ccopy)"(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy) nogil +cdef void ccopy(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil: + + _fortran_ccopy(n, cx, incx, cy, incy) + + +cdef extern from "_blas_subroutines.h": + void _fortran_cdotc "F_FUNC(cdotcwrp,CDOTCWRP)"(npy_complex64 *out, int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy) nogil +cdef c cdotc(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil: + cdef c out + _fortran_cdotc(&out, n, cx, incx, cy, incy) + return out + +cdef extern from "_blas_subroutines.h": + void _fortran_cdotu "F_FUNC(cdotuwrp,CDOTUWRP)"(npy_complex64 *out, int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy) nogil +cdef c cdotu(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil: + cdef c out + _fortran_cdotu(&out, n, cx, incx, cy, incy) + return out + +cdef extern from "_blas_subroutines.h": + void _fortran_cgbmv "BLAS_FUNC(cgbmv)"(char *trans, int *m, int *n, int *kl, int *ku, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy) nogil +cdef void cgbmv(char *trans, int *m, int *n, int *kl, int *ku, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil: + + _fortran_cgbmv(trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy) + + +cdef extern from "_blas_subroutines.h": + void _fortran_cgemm "BLAS_FUNC(cgemm)"(char *transa, char *transb, int *m, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *beta, npy_complex64 *c, int *ldc) nogil +cdef void cgemm(char *transa, char *transb, int *m, int *n, int *k, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogil: + + _fortran_cgemm(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc) + + +cdef extern from "_blas_subroutines.h": + void _fortran_cgemv "BLAS_FUNC(cgemv)"(char *trans, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy) nogil +cdef void cgemv(char *trans, int *m, int *n, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil: + + _fortran_cgemv(trans, m, n, alpha, a, lda, x, incx, beta, y, incy) + + +cdef extern from "_blas_subroutines.h": + void _fortran_cgerc "BLAS_FUNC(cgerc)"(int *m, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, npy_complex64 *a, int *lda) nogil +cdef void cgerc(int *m, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *a, int *lda) noexcept nogil: + + _fortran_cgerc(m, n, alpha, x, incx, y, incy, a, lda) + + +cdef extern from "_blas_subroutines.h": + void _fortran_cgeru "BLAS_FUNC(cgeru)"(int *m, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, npy_complex64 *a, int *lda) nogil +cdef void cgeru(int *m, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *a, int *lda) noexcept nogil: + + _fortran_cgeru(m, n, alpha, x, incx, y, incy, a, lda) + + +cdef extern from "_blas_subroutines.h": + void _fortran_chbmv "BLAS_FUNC(chbmv)"(char *uplo, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy) nogil +cdef void chbmv(char *uplo, int *n, int *k, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil: + + _fortran_chbmv(uplo, n, k, alpha, a, lda, x, incx, beta, y, incy) + + +cdef extern from "_blas_subroutines.h": + void _fortran_chemm "BLAS_FUNC(chemm)"(char *side, char *uplo, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *beta, npy_complex64 *c, int *ldc) nogil +cdef void chemm(char *side, char *uplo, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogil: + + _fortran_chemm(side, uplo, m, n, alpha, a, lda, b, ldb, beta, c, ldc) + + +cdef extern from "_blas_subroutines.h": + void _fortran_chemv "BLAS_FUNC(chemv)"(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy) nogil +cdef void chemv(char *uplo, int *n, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil: + + _fortran_chemv(uplo, n, alpha, a, lda, x, incx, beta, y, incy) + + +cdef extern from "_blas_subroutines.h": + void _fortran_cher "BLAS_FUNC(cher)"(char *uplo, int *n, s *alpha, npy_complex64 *x, int *incx, npy_complex64 *a, int *lda) nogil +cdef void cher(char *uplo, int *n, s *alpha, c *x, int *incx, c *a, int *lda) noexcept nogil: + + _fortran_cher(uplo, n, alpha, x, incx, a, lda) + + +cdef extern from "_blas_subroutines.h": + void _fortran_cher2 "BLAS_FUNC(cher2)"(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, npy_complex64 *a, int *lda) nogil +cdef void cher2(char *uplo, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *a, int *lda) noexcept nogil: + + _fortran_cher2(uplo, n, alpha, x, incx, y, incy, a, lda) + + +cdef extern from "_blas_subroutines.h": + void _fortran_cher2k "BLAS_FUNC(cher2k)"(char *uplo, char *trans, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, s *beta, npy_complex64 *c, int *ldc) nogil +cdef void cher2k(char *uplo, char *trans, int *n, int *k, c *alpha, c *a, int *lda, c *b, int *ldb, s *beta, c *c, int *ldc) noexcept nogil: + + _fortran_cher2k(uplo, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc) + + +cdef extern from "_blas_subroutines.h": + void _fortran_cherk "BLAS_FUNC(cherk)"(char *uplo, char *trans, int *n, int *k, s *alpha, npy_complex64 *a, int *lda, s *beta, npy_complex64 *c, int *ldc) nogil +cdef void cherk(char *uplo, char *trans, int *n, int *k, s *alpha, c *a, int *lda, s *beta, c *c, int *ldc) noexcept nogil: + + _fortran_cherk(uplo, trans, n, k, alpha, a, lda, beta, c, ldc) + + +cdef extern from "_blas_subroutines.h": + void _fortran_chpmv "BLAS_FUNC(chpmv)"(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *ap, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy) nogil +cdef void chpmv(char *uplo, int *n, c *alpha, c *ap, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil: + + _fortran_chpmv(uplo, n, alpha, ap, x, incx, beta, y, incy) + + +cdef extern from "_blas_subroutines.h": + void _fortran_chpr "BLAS_FUNC(chpr)"(char *uplo, int *n, s *alpha, npy_complex64 *x, int *incx, npy_complex64 *ap) nogil +cdef void chpr(char *uplo, int *n, s *alpha, c *x, int *incx, c *ap) noexcept nogil: + + _fortran_chpr(uplo, n, alpha, x, incx, ap) + + +cdef extern from "_blas_subroutines.h": + void _fortran_chpr2 "BLAS_FUNC(chpr2)"(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, npy_complex64 *ap) nogil +cdef void chpr2(char *uplo, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *ap) noexcept nogil: + + _fortran_chpr2(uplo, n, alpha, x, incx, y, incy, ap) + + +cdef extern from "_blas_subroutines.h": + void _fortran_crotg "BLAS_FUNC(crotg)"(npy_complex64 *ca, npy_complex64 *cb, s *c, npy_complex64 *s) nogil +cdef void crotg(c *ca, c *cb, s *c, c *s) noexcept nogil: + + _fortran_crotg(ca, cb, c, s) + + +cdef extern from "_blas_subroutines.h": + void _fortran_cscal "BLAS_FUNC(cscal)"(int *n, npy_complex64 *ca, npy_complex64 *cx, int *incx) nogil +cdef void cscal(int *n, c *ca, c *cx, int *incx) noexcept nogil: + + _fortran_cscal(n, ca, cx, incx) + + +cdef extern from "_blas_subroutines.h": + void _fortran_csrot "BLAS_FUNC(csrot)"(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy, s *c, s *s) nogil +cdef void csrot(int *n, c *cx, int *incx, c *cy, int *incy, s *c, s *s) noexcept nogil: + + _fortran_csrot(n, cx, incx, cy, incy, c, s) + + +cdef extern from "_blas_subroutines.h": + void _fortran_csscal "BLAS_FUNC(csscal)"(int *n, s *sa, npy_complex64 *cx, int *incx) nogil +cdef void csscal(int *n, s *sa, c *cx, int *incx) noexcept nogil: + + _fortran_csscal(n, sa, cx, incx) + + +cdef extern from "_blas_subroutines.h": + void _fortran_cswap "BLAS_FUNC(cswap)"(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy) nogil +cdef void cswap(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil: + + _fortran_cswap(n, cx, incx, cy, incy) + + +cdef extern from "_blas_subroutines.h": + void _fortran_csymm "BLAS_FUNC(csymm)"(char *side, char *uplo, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *beta, npy_complex64 *c, int *ldc) nogil +cdef void csymm(char *side, char *uplo, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogil: + + _fortran_csymm(side, uplo, m, n, alpha, a, lda, b, ldb, beta, c, ldc) + + +cdef extern from "_blas_subroutines.h": + void _fortran_csyr2k "BLAS_FUNC(csyr2k)"(char *uplo, char *trans, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *beta, npy_complex64 *c, int *ldc) nogil +cdef void csyr2k(char *uplo, char *trans, int *n, int *k, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogil: + + _fortran_csyr2k(uplo, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc) + + +cdef extern from "_blas_subroutines.h": + void _fortran_csyrk "BLAS_FUNC(csyrk)"(char *uplo, char *trans, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *beta, npy_complex64 *c, int *ldc) nogil +cdef void csyrk(char *uplo, char *trans, int *n, int *k, c *alpha, c *a, int *lda, c *beta, c *c, int *ldc) noexcept nogil: + + _fortran_csyrk(uplo, trans, n, k, alpha, a, lda, beta, c, ldc) + + +cdef extern from "_blas_subroutines.h": + void _fortran_ctbmv "BLAS_FUNC(ctbmv)"(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx) nogil +cdef void ctbmv(char *uplo, char *trans, char *diag, int *n, int *k, c *a, int *lda, c *x, int *incx) noexcept nogil: + + _fortran_ctbmv(uplo, trans, diag, n, k, a, lda, x, incx) + + +cdef extern from "_blas_subroutines.h": + void _fortran_ctbsv "BLAS_FUNC(ctbsv)"(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx) nogil +cdef void ctbsv(char *uplo, char *trans, char *diag, int *n, int *k, c *a, int *lda, c *x, int *incx) noexcept nogil: + + _fortran_ctbsv(uplo, trans, diag, n, k, a, lda, x, incx) + + +cdef extern from "_blas_subroutines.h": + void _fortran_ctpmv "BLAS_FUNC(ctpmv)"(char *uplo, char *trans, char *diag, int *n, npy_complex64 *ap, npy_complex64 *x, int *incx) nogil +cdef void ctpmv(char *uplo, char *trans, char *diag, int *n, c *ap, c *x, int *incx) noexcept nogil: + + _fortran_ctpmv(uplo, trans, diag, n, ap, x, incx) + + +cdef extern from "_blas_subroutines.h": + void _fortran_ctpsv "BLAS_FUNC(ctpsv)"(char *uplo, char *trans, char *diag, int *n, npy_complex64 *ap, npy_complex64 *x, int *incx) nogil +cdef void ctpsv(char *uplo, char *trans, char *diag, int *n, c *ap, c *x, int *incx) noexcept nogil: + + _fortran_ctpsv(uplo, trans, diag, n, ap, x, incx) + + +cdef extern from "_blas_subroutines.h": + void _fortran_ctrmm "BLAS_FUNC(ctrmm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb) nogil +cdef void ctrmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb) noexcept nogil: + + _fortran_ctrmm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb) + + +cdef extern from "_blas_subroutines.h": + void _fortran_ctrmv "BLAS_FUNC(ctrmv)"(char *uplo, char *trans, char *diag, int *n, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx) nogil +cdef void ctrmv(char *uplo, char *trans, char *diag, int *n, c *a, int *lda, c *x, int *incx) noexcept nogil: + + _fortran_ctrmv(uplo, trans, diag, n, a, lda, x, incx) + + +cdef extern from "_blas_subroutines.h": + void _fortran_ctrsm "BLAS_FUNC(ctrsm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb) nogil +cdef void ctrsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb) noexcept nogil: + + _fortran_ctrsm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb) + + +cdef extern from "_blas_subroutines.h": + void _fortran_ctrsv "BLAS_FUNC(ctrsv)"(char *uplo, char *trans, char *diag, int *n, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx) nogil +cdef void ctrsv(char *uplo, char *trans, char *diag, int *n, c *a, int *lda, c *x, int *incx) noexcept nogil: + + _fortran_ctrsv(uplo, trans, diag, n, a, lda, x, incx) + + +cdef extern from "_blas_subroutines.h": + d _fortran_dasum "BLAS_FUNC(dasum)"(int *n, d *dx, int *incx) nogil +cdef d dasum(int *n, d *dx, int *incx) noexcept nogil: + + return _fortran_dasum(n, dx, incx) + + +cdef extern from "_blas_subroutines.h": + void _fortran_daxpy "BLAS_FUNC(daxpy)"(int *n, d *da, d *dx, int *incx, d *dy, int *incy) nogil +cdef void daxpy(int *n, d *da, d *dx, int *incx, d *dy, int *incy) noexcept nogil: + + _fortran_daxpy(n, da, dx, incx, dy, incy) + + +cdef extern from "_blas_subroutines.h": + d _fortran_dcabs1 "BLAS_FUNC(dcabs1)"(npy_complex128 *z) nogil +cdef d dcabs1(z *z) noexcept nogil: + + return _fortran_dcabs1(z) + + +cdef extern from "_blas_subroutines.h": + void _fortran_dcopy "BLAS_FUNC(dcopy)"(int *n, d *dx, int *incx, d *dy, int *incy) nogil +cdef void dcopy(int *n, d *dx, int *incx, d *dy, int *incy) noexcept nogil: + + _fortran_dcopy(n, dx, incx, dy, incy) + + +cdef extern from "_blas_subroutines.h": + d _fortran_ddot "BLAS_FUNC(ddot)"(int *n, d *dx, int *incx, d *dy, int *incy) nogil +cdef d ddot(int *n, d *dx, int *incx, d *dy, int *incy) noexcept nogil: + + return _fortran_ddot(n, dx, incx, dy, incy) + + +cdef extern from "_blas_subroutines.h": + void _fortran_dgbmv "BLAS_FUNC(dgbmv)"(char *trans, int *m, int *n, int *kl, int *ku, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) nogil +cdef void dgbmv(char *trans, int *m, int *n, int *kl, int *ku, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil: + + _fortran_dgbmv(trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy) + + +cdef extern from "_blas_subroutines.h": + void _fortran_dgemm "BLAS_FUNC(dgemm)"(char *transa, char *transb, int *m, int *n, int *k, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) nogil +cdef void dgemm(char *transa, char *transb, int *m, int *n, int *k, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) noexcept nogil: + + _fortran_dgemm(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc) + + +cdef extern from "_blas_subroutines.h": + void _fortran_dgemv "BLAS_FUNC(dgemv)"(char *trans, int *m, int *n, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) nogil +cdef void dgemv(char *trans, int *m, int *n, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil: + + _fortran_dgemv(trans, m, n, alpha, a, lda, x, incx, beta, y, incy) + + +cdef extern from "_blas_subroutines.h": + void _fortran_dger "BLAS_FUNC(dger)"(int *m, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *a, int *lda) nogil +cdef void dger(int *m, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *a, int *lda) noexcept nogil: + + _fortran_dger(m, n, alpha, x, incx, y, incy, a, lda) + + +cdef extern from "_blas_subroutines.h": + d _fortran_dnrm2 "BLAS_FUNC(dnrm2)"(int *n, d *x, int *incx) nogil +cdef d dnrm2(int *n, d *x, int *incx) noexcept nogil: + + return _fortran_dnrm2(n, x, incx) + + +cdef extern from "_blas_subroutines.h": + void _fortran_drot "BLAS_FUNC(drot)"(int *n, d *dx, int *incx, d *dy, int *incy, d *c, d *s) nogil +cdef void drot(int *n, d *dx, int *incx, d *dy, int *incy, d *c, d *s) noexcept nogil: + + _fortran_drot(n, dx, incx, dy, incy, c, s) + + +cdef extern from "_blas_subroutines.h": + void _fortran_drotg "BLAS_FUNC(drotg)"(d *da, d *db, d *c, d *s) nogil +cdef void drotg(d *da, d *db, d *c, d *s) noexcept nogil: + + _fortran_drotg(da, db, c, s) + + +cdef extern from "_blas_subroutines.h": + void _fortran_drotm "BLAS_FUNC(drotm)"(int *n, d *dx, int *incx, d *dy, int *incy, d *dparam) nogil +cdef void drotm(int *n, d *dx, int *incx, d *dy, int *incy, d *dparam) noexcept nogil: + + _fortran_drotm(n, dx, incx, dy, incy, dparam) + + +cdef extern from "_blas_subroutines.h": + void _fortran_drotmg "BLAS_FUNC(drotmg)"(d *dd1, d *dd2, d *dx1, d *dy1, d *dparam) nogil +cdef void drotmg(d *dd1, d *dd2, d *dx1, d *dy1, d *dparam) noexcept nogil: + + _fortran_drotmg(dd1, dd2, dx1, dy1, dparam) + + +cdef extern from "_blas_subroutines.h": + void _fortran_dsbmv "BLAS_FUNC(dsbmv)"(char *uplo, int *n, int *k, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) nogil +cdef void dsbmv(char *uplo, int *n, int *k, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil: + + _fortran_dsbmv(uplo, n, k, alpha, a, lda, x, incx, beta, y, incy) + + +cdef extern from "_blas_subroutines.h": + void _fortran_dscal "BLAS_FUNC(dscal)"(int *n, d *da, d *dx, int *incx) nogil +cdef void dscal(int *n, d *da, d *dx, int *incx) noexcept nogil: + + _fortran_dscal(n, da, dx, incx) + + +cdef extern from "_blas_subroutines.h": + d _fortran_dsdot "BLAS_FUNC(dsdot)"(int *n, s *sx, int *incx, s *sy, int *incy) nogil +cdef d dsdot(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil: + + return _fortran_dsdot(n, sx, incx, sy, incy) + + +cdef extern from "_blas_subroutines.h": + void _fortran_dspmv "BLAS_FUNC(dspmv)"(char *uplo, int *n, d *alpha, d *ap, d *x, int *incx, d *beta, d *y, int *incy) nogil +cdef void dspmv(char *uplo, int *n, d *alpha, d *ap, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil: + + _fortran_dspmv(uplo, n, alpha, ap, x, incx, beta, y, incy) + + +cdef extern from "_blas_subroutines.h": + void _fortran_dspr "BLAS_FUNC(dspr)"(char *uplo, int *n, d *alpha, d *x, int *incx, d *ap) nogil +cdef void dspr(char *uplo, int *n, d *alpha, d *x, int *incx, d *ap) noexcept nogil: + + _fortran_dspr(uplo, n, alpha, x, incx, ap) + + +cdef extern from "_blas_subroutines.h": + void _fortran_dspr2 "BLAS_FUNC(dspr2)"(char *uplo, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *ap) nogil +cdef void dspr2(char *uplo, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *ap) noexcept nogil: + + _fortran_dspr2(uplo, n, alpha, x, incx, y, incy, ap) + + +cdef extern from "_blas_subroutines.h": + void _fortran_dswap "BLAS_FUNC(dswap)"(int *n, d *dx, int *incx, d *dy, int *incy) nogil +cdef void dswap(int *n, d *dx, int *incx, d *dy, int *incy) noexcept nogil: + + _fortran_dswap(n, dx, incx, dy, incy) + + +cdef extern from "_blas_subroutines.h": + void _fortran_dsymm "BLAS_FUNC(dsymm)"(char *side, char *uplo, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) nogil +cdef void dsymm(char *side, char *uplo, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) noexcept nogil: + + _fortran_dsymm(side, uplo, m, n, alpha, a, lda, b, ldb, beta, c, ldc) + + +cdef extern from "_blas_subroutines.h": + void _fortran_dsymv "BLAS_FUNC(dsymv)"(char *uplo, int *n, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) nogil +cdef void dsymv(char *uplo, int *n, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil: + + _fortran_dsymv(uplo, n, alpha, a, lda, x, incx, beta, y, incy) + + +cdef extern from "_blas_subroutines.h": + void _fortran_dsyr "BLAS_FUNC(dsyr)"(char *uplo, int *n, d *alpha, d *x, int *incx, d *a, int *lda) nogil +cdef void dsyr(char *uplo, int *n, d *alpha, d *x, int *incx, d *a, int *lda) noexcept nogil: + + _fortran_dsyr(uplo, n, alpha, x, incx, a, lda) + + +cdef extern from "_blas_subroutines.h": + void _fortran_dsyr2 "BLAS_FUNC(dsyr2)"(char *uplo, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *a, int *lda) nogil +cdef void dsyr2(char *uplo, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *a, int *lda) noexcept nogil: + + _fortran_dsyr2(uplo, n, alpha, x, incx, y, incy, a, lda) + + +cdef extern from "_blas_subroutines.h": + void _fortran_dsyr2k "BLAS_FUNC(dsyr2k)"(char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) nogil +cdef void dsyr2k(char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) noexcept nogil: + + _fortran_dsyr2k(uplo, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc) + + +cdef extern from "_blas_subroutines.h": + void _fortran_dsyrk "BLAS_FUNC(dsyrk)"(char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *beta, d *c, int *ldc) nogil +cdef void dsyrk(char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *beta, d *c, int *ldc) noexcept nogil: + + _fortran_dsyrk(uplo, trans, n, k, alpha, a, lda, beta, c, ldc) + + +cdef extern from "_blas_subroutines.h": + void _fortran_dtbmv "BLAS_FUNC(dtbmv)"(char *uplo, char *trans, char *diag, int *n, int *k, d *a, int *lda, d *x, int *incx) nogil +cdef void dtbmv(char *uplo, char *trans, char *diag, int *n, int *k, d *a, int *lda, d *x, int *incx) noexcept nogil: + + _fortran_dtbmv(uplo, trans, diag, n, k, a, lda, x, incx) + + +cdef extern from "_blas_subroutines.h": + void _fortran_dtbsv "BLAS_FUNC(dtbsv)"(char *uplo, char *trans, char *diag, int *n, int *k, d *a, int *lda, d *x, int *incx) nogil +cdef void dtbsv(char *uplo, char *trans, char *diag, int *n, int *k, d *a, int *lda, d *x, int *incx) noexcept nogil: + + _fortran_dtbsv(uplo, trans, diag, n, k, a, lda, x, incx) + + +cdef extern from "_blas_subroutines.h": + void _fortran_dtpmv "BLAS_FUNC(dtpmv)"(char *uplo, char *trans, char *diag, int *n, d *ap, d *x, int *incx) nogil +cdef void dtpmv(char *uplo, char *trans, char *diag, int *n, d *ap, d *x, int *incx) noexcept nogil: + + _fortran_dtpmv(uplo, trans, diag, n, ap, x, incx) + + +cdef extern from "_blas_subroutines.h": + void _fortran_dtpsv "BLAS_FUNC(dtpsv)"(char *uplo, char *trans, char *diag, int *n, d *ap, d *x, int *incx) nogil +cdef void dtpsv(char *uplo, char *trans, char *diag, int *n, d *ap, d *x, int *incx) noexcept nogil: + + _fortran_dtpsv(uplo, trans, diag, n, ap, x, incx) + + +cdef extern from "_blas_subroutines.h": + void _fortran_dtrmm "BLAS_FUNC(dtrmm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb) nogil +cdef void dtrmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb) noexcept nogil: + + _fortran_dtrmm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb) + + +cdef extern from "_blas_subroutines.h": + void _fortran_dtrmv "BLAS_FUNC(dtrmv)"(char *uplo, char *trans, char *diag, int *n, d *a, int *lda, d *x, int *incx) nogil +cdef void dtrmv(char *uplo, char *trans, char *diag, int *n, d *a, int *lda, d *x, int *incx) noexcept nogil: + + _fortran_dtrmv(uplo, trans, diag, n, a, lda, x, incx) + + +cdef extern from "_blas_subroutines.h": + void _fortran_dtrsm "BLAS_FUNC(dtrsm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb) nogil +cdef void dtrsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb) noexcept nogil: + + _fortran_dtrsm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb) + + +cdef extern from "_blas_subroutines.h": + void _fortran_dtrsv "BLAS_FUNC(dtrsv)"(char *uplo, char *trans, char *diag, int *n, d *a, int *lda, d *x, int *incx) nogil +cdef void dtrsv(char *uplo, char *trans, char *diag, int *n, d *a, int *lda, d *x, int *incx) noexcept nogil: + + _fortran_dtrsv(uplo, trans, diag, n, a, lda, x, incx) + + +cdef extern from "_blas_subroutines.h": + d _fortran_dzasum "BLAS_FUNC(dzasum)"(int *n, npy_complex128 *zx, int *incx) nogil +cdef d dzasum(int *n, z *zx, int *incx) noexcept nogil: + + return _fortran_dzasum(n, zx, incx) + + +cdef extern from "_blas_subroutines.h": + d _fortran_dznrm2 "BLAS_FUNC(dznrm2)"(int *n, npy_complex128 *x, int *incx) nogil +cdef d dznrm2(int *n, z *x, int *incx) noexcept nogil: + + return _fortran_dznrm2(n, x, incx) + + +cdef extern from "_blas_subroutines.h": + int _fortran_icamax "BLAS_FUNC(icamax)"(int *n, npy_complex64 *cx, int *incx) nogil +cdef int icamax(int *n, c *cx, int *incx) noexcept nogil: + + return _fortran_icamax(n, cx, incx) + + +cdef extern from "_blas_subroutines.h": + int _fortran_idamax "BLAS_FUNC(idamax)"(int *n, d *dx, int *incx) nogil +cdef int idamax(int *n, d *dx, int *incx) noexcept nogil: + + return _fortran_idamax(n, dx, incx) + + +cdef extern from "_blas_subroutines.h": + int _fortran_isamax "BLAS_FUNC(isamax)"(int *n, s *sx, int *incx) nogil +cdef int isamax(int *n, s *sx, int *incx) noexcept nogil: + + return _fortran_isamax(n, sx, incx) + + +cdef extern from "_blas_subroutines.h": + int _fortran_izamax "BLAS_FUNC(izamax)"(int *n, npy_complex128 *zx, int *incx) nogil +cdef int izamax(int *n, z *zx, int *incx) noexcept nogil: + + return _fortran_izamax(n, zx, incx) + + +cdef extern from "_blas_subroutines.h": + bint _fortran_lsame "BLAS_FUNC(lsame)"(char *ca, char *cb) nogil +cdef bint lsame(char *ca, char *cb) noexcept nogil: + + return _fortran_lsame(ca, cb) + + +cdef extern from "_blas_subroutines.h": + s _fortran_sasum "BLAS_FUNC(sasum)"(int *n, s *sx, int *incx) nogil +cdef s sasum(int *n, s *sx, int *incx) noexcept nogil: + + return _fortran_sasum(n, sx, incx) + + +cdef extern from "_blas_subroutines.h": + void _fortran_saxpy "BLAS_FUNC(saxpy)"(int *n, s *sa, s *sx, int *incx, s *sy, int *incy) nogil +cdef void saxpy(int *n, s *sa, s *sx, int *incx, s *sy, int *incy) noexcept nogil: + + _fortran_saxpy(n, sa, sx, incx, sy, incy) + + +cdef extern from "_blas_subroutines.h": + s _fortran_scasum "BLAS_FUNC(scasum)"(int *n, npy_complex64 *cx, int *incx) nogil +cdef s scasum(int *n, c *cx, int *incx) noexcept nogil: + + return _fortran_scasum(n, cx, incx) + + +cdef extern from "_blas_subroutines.h": + s _fortran_scnrm2 "BLAS_FUNC(scnrm2)"(int *n, npy_complex64 *x, int *incx) nogil +cdef s scnrm2(int *n, c *x, int *incx) noexcept nogil: + + return _fortran_scnrm2(n, x, incx) + + +cdef extern from "_blas_subroutines.h": + void _fortran_scopy "BLAS_FUNC(scopy)"(int *n, s *sx, int *incx, s *sy, int *incy) nogil +cdef void scopy(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil: + + _fortran_scopy(n, sx, incx, sy, incy) + + +cdef extern from "_blas_subroutines.h": + s _fortran_sdot "BLAS_FUNC(sdot)"(int *n, s *sx, int *incx, s *sy, int *incy) nogil +cdef s sdot(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil: + + return _fortran_sdot(n, sx, incx, sy, incy) + + +cdef extern from "_blas_subroutines.h": + s _fortran_sdsdot "BLAS_FUNC(sdsdot)"(int *n, s *sb, s *sx, int *incx, s *sy, int *incy) nogil +cdef s sdsdot(int *n, s *sb, s *sx, int *incx, s *sy, int *incy) noexcept nogil: + + return _fortran_sdsdot(n, sb, sx, incx, sy, incy) + + +cdef extern from "_blas_subroutines.h": + void _fortran_sgbmv "BLAS_FUNC(sgbmv)"(char *trans, int *m, int *n, int *kl, int *ku, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) nogil +cdef void sgbmv(char *trans, int *m, int *n, int *kl, int *ku, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil: + + _fortran_sgbmv(trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy) + + +cdef extern from "_blas_subroutines.h": + void _fortran_sgemm "BLAS_FUNC(sgemm)"(char *transa, char *transb, int *m, int *n, int *k, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) nogil +cdef void sgemm(char *transa, char *transb, int *m, int *n, int *k, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) noexcept nogil: + + _fortran_sgemm(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc) + + +cdef extern from "_blas_subroutines.h": + void _fortran_sgemv "BLAS_FUNC(sgemv)"(char *trans, int *m, int *n, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) nogil +cdef void sgemv(char *trans, int *m, int *n, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil: + + _fortran_sgemv(trans, m, n, alpha, a, lda, x, incx, beta, y, incy) + + +cdef extern from "_blas_subroutines.h": + void _fortran_sger "BLAS_FUNC(sger)"(int *m, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *a, int *lda) nogil +cdef void sger(int *m, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *a, int *lda) noexcept nogil: + + _fortran_sger(m, n, alpha, x, incx, y, incy, a, lda) + + +cdef extern from "_blas_subroutines.h": + s _fortran_snrm2 "BLAS_FUNC(snrm2)"(int *n, s *x, int *incx) nogil +cdef s snrm2(int *n, s *x, int *incx) noexcept nogil: + + return _fortran_snrm2(n, x, incx) + + +cdef extern from "_blas_subroutines.h": + void _fortran_srot "BLAS_FUNC(srot)"(int *n, s *sx, int *incx, s *sy, int *incy, s *c, s *s) nogil +cdef void srot(int *n, s *sx, int *incx, s *sy, int *incy, s *c, s *s) noexcept nogil: + + _fortran_srot(n, sx, incx, sy, incy, c, s) + + +cdef extern from "_blas_subroutines.h": + void _fortran_srotg "BLAS_FUNC(srotg)"(s *sa, s *sb, s *c, s *s) nogil +cdef void srotg(s *sa, s *sb, s *c, s *s) noexcept nogil: + + _fortran_srotg(sa, sb, c, s) + + +cdef extern from "_blas_subroutines.h": + void _fortran_srotm "BLAS_FUNC(srotm)"(int *n, s *sx, int *incx, s *sy, int *incy, s *sparam) nogil +cdef void srotm(int *n, s *sx, int *incx, s *sy, int *incy, s *sparam) noexcept nogil: + + _fortran_srotm(n, sx, incx, sy, incy, sparam) + + +cdef extern from "_blas_subroutines.h": + void _fortran_srotmg "BLAS_FUNC(srotmg)"(s *sd1, s *sd2, s *sx1, s *sy1, s *sparam) nogil +cdef void srotmg(s *sd1, s *sd2, s *sx1, s *sy1, s *sparam) noexcept nogil: + + _fortran_srotmg(sd1, sd2, sx1, sy1, sparam) + + +cdef extern from "_blas_subroutines.h": + void _fortran_ssbmv "BLAS_FUNC(ssbmv)"(char *uplo, int *n, int *k, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) nogil +cdef void ssbmv(char *uplo, int *n, int *k, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil: + + _fortran_ssbmv(uplo, n, k, alpha, a, lda, x, incx, beta, y, incy) + + +cdef extern from "_blas_subroutines.h": + void _fortran_sscal "BLAS_FUNC(sscal)"(int *n, s *sa, s *sx, int *incx) nogil +cdef void sscal(int *n, s *sa, s *sx, int *incx) noexcept nogil: + + _fortran_sscal(n, sa, sx, incx) + + +cdef extern from "_blas_subroutines.h": + void _fortran_sspmv "BLAS_FUNC(sspmv)"(char *uplo, int *n, s *alpha, s *ap, s *x, int *incx, s *beta, s *y, int *incy) nogil +cdef void sspmv(char *uplo, int *n, s *alpha, s *ap, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil: + + _fortran_sspmv(uplo, n, alpha, ap, x, incx, beta, y, incy) + + +cdef extern from "_blas_subroutines.h": + void _fortran_sspr "BLAS_FUNC(sspr)"(char *uplo, int *n, s *alpha, s *x, int *incx, s *ap) nogil +cdef void sspr(char *uplo, int *n, s *alpha, s *x, int *incx, s *ap) noexcept nogil: + + _fortran_sspr(uplo, n, alpha, x, incx, ap) + + +cdef extern from "_blas_subroutines.h": + void _fortran_sspr2 "BLAS_FUNC(sspr2)"(char *uplo, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *ap) nogil +cdef void sspr2(char *uplo, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *ap) noexcept nogil: + + _fortran_sspr2(uplo, n, alpha, x, incx, y, incy, ap) + + +cdef extern from "_blas_subroutines.h": + void _fortran_sswap "BLAS_FUNC(sswap)"(int *n, s *sx, int *incx, s *sy, int *incy) nogil +cdef void sswap(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil: + + _fortran_sswap(n, sx, incx, sy, incy) + + +cdef extern from "_blas_subroutines.h": + void _fortran_ssymm "BLAS_FUNC(ssymm)"(char *side, char *uplo, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) nogil +cdef void ssymm(char *side, char *uplo, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) noexcept nogil: + + _fortran_ssymm(side, uplo, m, n, alpha, a, lda, b, ldb, beta, c, ldc) + + +cdef extern from "_blas_subroutines.h": + void _fortran_ssymv "BLAS_FUNC(ssymv)"(char *uplo, int *n, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) nogil +cdef void ssymv(char *uplo, int *n, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil: + + _fortran_ssymv(uplo, n, alpha, a, lda, x, incx, beta, y, incy) + + +cdef extern from "_blas_subroutines.h": + void _fortran_ssyr "BLAS_FUNC(ssyr)"(char *uplo, int *n, s *alpha, s *x, int *incx, s *a, int *lda) nogil +cdef void ssyr(char *uplo, int *n, s *alpha, s *x, int *incx, s *a, int *lda) noexcept nogil: + + _fortran_ssyr(uplo, n, alpha, x, incx, a, lda) + + +cdef extern from "_blas_subroutines.h": + void _fortran_ssyr2 "BLAS_FUNC(ssyr2)"(char *uplo, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *a, int *lda) nogil +cdef void ssyr2(char *uplo, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *a, int *lda) noexcept nogil: + + _fortran_ssyr2(uplo, n, alpha, x, incx, y, incy, a, lda) + + +cdef extern from "_blas_subroutines.h": + void _fortran_ssyr2k "BLAS_FUNC(ssyr2k)"(char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) nogil +cdef void ssyr2k(char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) noexcept nogil: + + _fortran_ssyr2k(uplo, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc) + + +cdef extern from "_blas_subroutines.h": + void _fortran_ssyrk "BLAS_FUNC(ssyrk)"(char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *beta, s *c, int *ldc) nogil +cdef void ssyrk(char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *beta, s *c, int *ldc) noexcept nogil: + + _fortran_ssyrk(uplo, trans, n, k, alpha, a, lda, beta, c, ldc) + + +cdef extern from "_blas_subroutines.h": + void _fortran_stbmv "BLAS_FUNC(stbmv)"(char *uplo, char *trans, char *diag, int *n, int *k, s *a, int *lda, s *x, int *incx) nogil +cdef void stbmv(char *uplo, char *trans, char *diag, int *n, int *k, s *a, int *lda, s *x, int *incx) noexcept nogil: + + _fortran_stbmv(uplo, trans, diag, n, k, a, lda, x, incx) + + +cdef extern from "_blas_subroutines.h": + void _fortran_stbsv "BLAS_FUNC(stbsv)"(char *uplo, char *trans, char *diag, int *n, int *k, s *a, int *lda, s *x, int *incx) nogil +cdef void stbsv(char *uplo, char *trans, char *diag, int *n, int *k, s *a, int *lda, s *x, int *incx) noexcept nogil: + + _fortran_stbsv(uplo, trans, diag, n, k, a, lda, x, incx) + + +cdef extern from "_blas_subroutines.h": + void _fortran_stpmv "BLAS_FUNC(stpmv)"(char *uplo, char *trans, char *diag, int *n, s *ap, s *x, int *incx) nogil +cdef void stpmv(char *uplo, char *trans, char *diag, int *n, s *ap, s *x, int *incx) noexcept nogil: + + _fortran_stpmv(uplo, trans, diag, n, ap, x, incx) + + +cdef extern from "_blas_subroutines.h": + void _fortran_stpsv "BLAS_FUNC(stpsv)"(char *uplo, char *trans, char *diag, int *n, s *ap, s *x, int *incx) nogil +cdef void stpsv(char *uplo, char *trans, char *diag, int *n, s *ap, s *x, int *incx) noexcept nogil: + + _fortran_stpsv(uplo, trans, diag, n, ap, x, incx) + + +cdef extern from "_blas_subroutines.h": + void _fortran_strmm "BLAS_FUNC(strmm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb) nogil +cdef void strmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb) noexcept nogil: + + _fortran_strmm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb) + + +cdef extern from "_blas_subroutines.h": + void _fortran_strmv "BLAS_FUNC(strmv)"(char *uplo, char *trans, char *diag, int *n, s *a, int *lda, s *x, int *incx) nogil +cdef void strmv(char *uplo, char *trans, char *diag, int *n, s *a, int *lda, s *x, int *incx) noexcept nogil: + + _fortran_strmv(uplo, trans, diag, n, a, lda, x, incx) + + +cdef extern from "_blas_subroutines.h": + void _fortran_strsm "BLAS_FUNC(strsm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb) nogil +cdef void strsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb) noexcept nogil: + + _fortran_strsm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb) + + +cdef extern from "_blas_subroutines.h": + void _fortran_strsv "BLAS_FUNC(strsv)"(char *uplo, char *trans, char *diag, int *n, s *a, int *lda, s *x, int *incx) nogil +cdef void strsv(char *uplo, char *trans, char *diag, int *n, s *a, int *lda, s *x, int *incx) noexcept nogil: + + _fortran_strsv(uplo, trans, diag, n, a, lda, x, incx) + + +cdef extern from "_blas_subroutines.h": + void _fortran_zaxpy "BLAS_FUNC(zaxpy)"(int *n, npy_complex128 *za, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy) nogil +cdef void zaxpy(int *n, z *za, z *zx, int *incx, z *zy, int *incy) noexcept nogil: + + _fortran_zaxpy(n, za, zx, incx, zy, incy) + + +cdef extern from "_blas_subroutines.h": + void _fortran_zcopy "BLAS_FUNC(zcopy)"(int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy) nogil +cdef void zcopy(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil: + + _fortran_zcopy(n, zx, incx, zy, incy) + + +cdef extern from "_blas_subroutines.h": + void _fortran_zdotc "F_FUNC(zdotcwrp,ZDOTCWRP)"(npy_complex128 *out, int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy) nogil +cdef z zdotc(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil: + cdef z out + _fortran_zdotc(&out, n, zx, incx, zy, incy) + return out + +cdef extern from "_blas_subroutines.h": + void _fortran_zdotu "F_FUNC(zdotuwrp,ZDOTUWRP)"(npy_complex128 *out, int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy) nogil +cdef z zdotu(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil: + cdef z out + _fortran_zdotu(&out, n, zx, incx, zy, incy) + return out + +cdef extern from "_blas_subroutines.h": + void _fortran_zdrot "BLAS_FUNC(zdrot)"(int *n, npy_complex128 *cx, int *incx, npy_complex128 *cy, int *incy, d *c, d *s) nogil +cdef void zdrot(int *n, z *cx, int *incx, z *cy, int *incy, d *c, d *s) noexcept nogil: + + _fortran_zdrot(n, cx, incx, cy, incy, c, s) + + +cdef extern from "_blas_subroutines.h": + void _fortran_zdscal "BLAS_FUNC(zdscal)"(int *n, d *da, npy_complex128 *zx, int *incx) nogil +cdef void zdscal(int *n, d *da, z *zx, int *incx) noexcept nogil: + + _fortran_zdscal(n, da, zx, incx) + + +cdef extern from "_blas_subroutines.h": + void _fortran_zgbmv "BLAS_FUNC(zgbmv)"(char *trans, int *m, int *n, int *kl, int *ku, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy) nogil +cdef void zgbmv(char *trans, int *m, int *n, int *kl, int *ku, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil: + + _fortran_zgbmv(trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy) + + +cdef extern from "_blas_subroutines.h": + void _fortran_zgemm "BLAS_FUNC(zgemm)"(char *transa, char *transb, int *m, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *beta, npy_complex128 *c, int *ldc) nogil +cdef void zgemm(char *transa, char *transb, int *m, int *n, int *k, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogil: + + _fortran_zgemm(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc) + + +cdef extern from "_blas_subroutines.h": + void _fortran_zgemv "BLAS_FUNC(zgemv)"(char *trans, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy) nogil +cdef void zgemv(char *trans, int *m, int *n, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil: + + _fortran_zgemv(trans, m, n, alpha, a, lda, x, incx, beta, y, incy) + + +cdef extern from "_blas_subroutines.h": + void _fortran_zgerc "BLAS_FUNC(zgerc)"(int *m, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, npy_complex128 *a, int *lda) nogil +cdef void zgerc(int *m, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *a, int *lda) noexcept nogil: + + _fortran_zgerc(m, n, alpha, x, incx, y, incy, a, lda) + + +cdef extern from "_blas_subroutines.h": + void _fortran_zgeru "BLAS_FUNC(zgeru)"(int *m, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, npy_complex128 *a, int *lda) nogil +cdef void zgeru(int *m, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *a, int *lda) noexcept nogil: + + _fortran_zgeru(m, n, alpha, x, incx, y, incy, a, lda) + + +cdef extern from "_blas_subroutines.h": + void _fortran_zhbmv "BLAS_FUNC(zhbmv)"(char *uplo, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy) nogil +cdef void zhbmv(char *uplo, int *n, int *k, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil: + + _fortran_zhbmv(uplo, n, k, alpha, a, lda, x, incx, beta, y, incy) + + +cdef extern from "_blas_subroutines.h": + void _fortran_zhemm "BLAS_FUNC(zhemm)"(char *side, char *uplo, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *beta, npy_complex128 *c, int *ldc) nogil +cdef void zhemm(char *side, char *uplo, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogil: + + _fortran_zhemm(side, uplo, m, n, alpha, a, lda, b, ldb, beta, c, ldc) + + +cdef extern from "_blas_subroutines.h": + void _fortran_zhemv "BLAS_FUNC(zhemv)"(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy) nogil +cdef void zhemv(char *uplo, int *n, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil: + + _fortran_zhemv(uplo, n, alpha, a, lda, x, incx, beta, y, incy) + + +cdef extern from "_blas_subroutines.h": + void _fortran_zher "BLAS_FUNC(zher)"(char *uplo, int *n, d *alpha, npy_complex128 *x, int *incx, npy_complex128 *a, int *lda) nogil +cdef void zher(char *uplo, int *n, d *alpha, z *x, int *incx, z *a, int *lda) noexcept nogil: + + _fortran_zher(uplo, n, alpha, x, incx, a, lda) + + +cdef extern from "_blas_subroutines.h": + void _fortran_zher2 "BLAS_FUNC(zher2)"(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, npy_complex128 *a, int *lda) nogil +cdef void zher2(char *uplo, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *a, int *lda) noexcept nogil: + + _fortran_zher2(uplo, n, alpha, x, incx, y, incy, a, lda) + + +cdef extern from "_blas_subroutines.h": + void _fortran_zher2k "BLAS_FUNC(zher2k)"(char *uplo, char *trans, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, d *beta, npy_complex128 *c, int *ldc) nogil +cdef void zher2k(char *uplo, char *trans, int *n, int *k, z *alpha, z *a, int *lda, z *b, int *ldb, d *beta, z *c, int *ldc) noexcept nogil: + + _fortran_zher2k(uplo, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc) + + +cdef extern from "_blas_subroutines.h": + void _fortran_zherk "BLAS_FUNC(zherk)"(char *uplo, char *trans, int *n, int *k, d *alpha, npy_complex128 *a, int *lda, d *beta, npy_complex128 *c, int *ldc) nogil +cdef void zherk(char *uplo, char *trans, int *n, int *k, d *alpha, z *a, int *lda, d *beta, z *c, int *ldc) noexcept nogil: + + _fortran_zherk(uplo, trans, n, k, alpha, a, lda, beta, c, ldc) + + +cdef extern from "_blas_subroutines.h": + void _fortran_zhpmv "BLAS_FUNC(zhpmv)"(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *ap, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy) nogil +cdef void zhpmv(char *uplo, int *n, z *alpha, z *ap, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil: + + _fortran_zhpmv(uplo, n, alpha, ap, x, incx, beta, y, incy) + + +cdef extern from "_blas_subroutines.h": + void _fortran_zhpr "BLAS_FUNC(zhpr)"(char *uplo, int *n, d *alpha, npy_complex128 *x, int *incx, npy_complex128 *ap) nogil +cdef void zhpr(char *uplo, int *n, d *alpha, z *x, int *incx, z *ap) noexcept nogil: + + _fortran_zhpr(uplo, n, alpha, x, incx, ap) + + +cdef extern from "_blas_subroutines.h": + void _fortran_zhpr2 "BLAS_FUNC(zhpr2)"(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, npy_complex128 *ap) nogil +cdef void zhpr2(char *uplo, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *ap) noexcept nogil: + + _fortran_zhpr2(uplo, n, alpha, x, incx, y, incy, ap) + + +cdef extern from "_blas_subroutines.h": + void _fortran_zrotg "BLAS_FUNC(zrotg)"(npy_complex128 *ca, npy_complex128 *cb, d *c, npy_complex128 *s) nogil +cdef void zrotg(z *ca, z *cb, d *c, z *s) noexcept nogil: + + _fortran_zrotg(ca, cb, c, s) + + +cdef extern from "_blas_subroutines.h": + void _fortran_zscal "BLAS_FUNC(zscal)"(int *n, npy_complex128 *za, npy_complex128 *zx, int *incx) nogil +cdef void zscal(int *n, z *za, z *zx, int *incx) noexcept nogil: + + _fortran_zscal(n, za, zx, incx) + + +cdef extern from "_blas_subroutines.h": + void _fortran_zswap "BLAS_FUNC(zswap)"(int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy) nogil +cdef void zswap(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil: + + _fortran_zswap(n, zx, incx, zy, incy) + + +cdef extern from "_blas_subroutines.h": + void _fortran_zsymm "BLAS_FUNC(zsymm)"(char *side, char *uplo, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *beta, npy_complex128 *c, int *ldc) nogil +cdef void zsymm(char *side, char *uplo, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogil: + + _fortran_zsymm(side, uplo, m, n, alpha, a, lda, b, ldb, beta, c, ldc) + + +cdef extern from "_blas_subroutines.h": + void _fortran_zsyr2k "BLAS_FUNC(zsyr2k)"(char *uplo, char *trans, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *beta, npy_complex128 *c, int *ldc) nogil +cdef void zsyr2k(char *uplo, char *trans, int *n, int *k, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogil: + + _fortran_zsyr2k(uplo, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc) + + +cdef extern from "_blas_subroutines.h": + void _fortran_zsyrk "BLAS_FUNC(zsyrk)"(char *uplo, char *trans, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *beta, npy_complex128 *c, int *ldc) nogil +cdef void zsyrk(char *uplo, char *trans, int *n, int *k, z *alpha, z *a, int *lda, z *beta, z *c, int *ldc) noexcept nogil: + + _fortran_zsyrk(uplo, trans, n, k, alpha, a, lda, beta, c, ldc) + + +cdef extern from "_blas_subroutines.h": + void _fortran_ztbmv "BLAS_FUNC(ztbmv)"(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx) nogil +cdef void ztbmv(char *uplo, char *trans, char *diag, int *n, int *k, z *a, int *lda, z *x, int *incx) noexcept nogil: + + _fortran_ztbmv(uplo, trans, diag, n, k, a, lda, x, incx) + + +cdef extern from "_blas_subroutines.h": + void _fortran_ztbsv "BLAS_FUNC(ztbsv)"(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx) nogil +cdef void ztbsv(char *uplo, char *trans, char *diag, int *n, int *k, z *a, int *lda, z *x, int *incx) noexcept nogil: + + _fortran_ztbsv(uplo, trans, diag, n, k, a, lda, x, incx) + + +cdef extern from "_blas_subroutines.h": + void _fortran_ztpmv "BLAS_FUNC(ztpmv)"(char *uplo, char *trans, char *diag, int *n, npy_complex128 *ap, npy_complex128 *x, int *incx) nogil +cdef void ztpmv(char *uplo, char *trans, char *diag, int *n, z *ap, z *x, int *incx) noexcept nogil: + + _fortran_ztpmv(uplo, trans, diag, n, ap, x, incx) + + +cdef extern from "_blas_subroutines.h": + void _fortran_ztpsv "BLAS_FUNC(ztpsv)"(char *uplo, char *trans, char *diag, int *n, npy_complex128 *ap, npy_complex128 *x, int *incx) nogil +cdef void ztpsv(char *uplo, char *trans, char *diag, int *n, z *ap, z *x, int *incx) noexcept nogil: + + _fortran_ztpsv(uplo, trans, diag, n, ap, x, incx) + + +cdef extern from "_blas_subroutines.h": + void _fortran_ztrmm "BLAS_FUNC(ztrmm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb) nogil +cdef void ztrmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb) noexcept nogil: + + _fortran_ztrmm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb) + + +cdef extern from "_blas_subroutines.h": + void _fortran_ztrmv "BLAS_FUNC(ztrmv)"(char *uplo, char *trans, char *diag, int *n, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx) nogil +cdef void ztrmv(char *uplo, char *trans, char *diag, int *n, z *a, int *lda, z *x, int *incx) noexcept nogil: + + _fortran_ztrmv(uplo, trans, diag, n, a, lda, x, incx) + + +cdef extern from "_blas_subroutines.h": + void _fortran_ztrsm "BLAS_FUNC(ztrsm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb) nogil +cdef void ztrsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb) noexcept nogil: + + _fortran_ztrsm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb) + + +cdef extern from "_blas_subroutines.h": + void _fortran_ztrsv "BLAS_FUNC(ztrsv)"(char *uplo, char *trans, char *diag, int *n, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx) nogil +cdef void ztrsv(char *uplo, char *trans, char *diag, int *n, z *a, int *lda, z *x, int *incx) noexcept nogil: + + _fortran_ztrsv(uplo, trans, diag, n, a, lda, x, incx) + + + +# Python-accessible wrappers for testing: + +cdef inline bint _is_contiguous(double[:,:] a, int axis) noexcept nogil: + return (a.strides[axis] == sizeof(a[0,0]) or a.shape[axis] == 1) + +cpdef float complex _test_cdotc(float complex[:] cx, float complex[:] cy) noexcept nogil: + cdef: + int n = cx.shape[0] + int incx = cx.strides[0] // sizeof(cx[0]) + int incy = cy.strides[0] // sizeof(cy[0]) + return cdotc(&n, &cx[0], &incx, &cy[0], &incy) + +cpdef float complex _test_cdotu(float complex[:] cx, float complex[:] cy) noexcept nogil: + cdef: + int n = cx.shape[0] + int incx = cx.strides[0] // sizeof(cx[0]) + int incy = cy.strides[0] // sizeof(cy[0]) + return cdotu(&n, &cx[0], &incx, &cy[0], &incy) + +cpdef double _test_dasum(double[:] dx) noexcept nogil: + cdef: + int n = dx.shape[0] + int incx = dx.strides[0] // sizeof(dx[0]) + return dasum(&n, &dx[0], &incx) + +cpdef double _test_ddot(double[:] dx, double[:] dy) noexcept nogil: + cdef: + int n = dx.shape[0] + int incx = dx.strides[0] // sizeof(dx[0]) + int incy = dy.strides[0] // sizeof(dy[0]) + return ddot(&n, &dx[0], &incx, &dy[0], &incy) + +cpdef int _test_dgemm(double alpha, double[:,:] a, double[:,:] b, double beta, + double[:,:] c) except -1 nogil: + cdef: + char *transa + char *transb + int m, n, k, lda, ldb, ldc + double *a0=&a[0,0] + double *b0=&b[0,0] + double *c0=&c[0,0] + # In the case that c is C contiguous, swap a and b and + # swap whether or not each of them is transposed. + # This can be done because a.dot(b) = b.T.dot(a.T).T. + if _is_contiguous(c, 1): + if _is_contiguous(a, 1): + transb = 'n' + ldb = (&a[1,0]) - a0 if a.shape[0] > 1 else 1 + elif _is_contiguous(a, 0): + transb = 't' + ldb = (&a[0,1]) - a0 if a.shape[1] > 1 else 1 + else: + with gil: + raise ValueError("Input 'a' is neither C nor Fortran contiguous.") + if _is_contiguous(b, 1): + transa = 'n' + lda = (&b[1,0]) - b0 if b.shape[0] > 1 else 1 + elif _is_contiguous(b, 0): + transa = 't' + lda = (&b[0,1]) - b0 if b.shape[1] > 1 else 1 + else: + with gil: + raise ValueError("Input 'b' is neither C nor Fortran contiguous.") + k = b.shape[0] + if k != a.shape[1]: + with gil: + raise ValueError("Shape mismatch in input arrays.") + m = b.shape[1] + n = a.shape[0] + if n != c.shape[0] or m != c.shape[1]: + with gil: + raise ValueError("Output array does not have the correct shape.") + ldc = (&c[1,0]) - c0 if c.shape[0] > 1 else 1 + dgemm(transa, transb, &m, &n, &k, &alpha, b0, &lda, a0, + &ldb, &beta, c0, &ldc) + elif _is_contiguous(c, 0): + if _is_contiguous(a, 1): + transa = 't' + lda = (&a[1,0]) - a0 if a.shape[0] > 1 else 1 + elif _is_contiguous(a, 0): + transa = 'n' + lda = (&a[0,1]) - a0 if a.shape[1] > 1 else 1 + else: + with gil: + raise ValueError("Input 'a' is neither C nor Fortran contiguous.") + if _is_contiguous(b, 1): + transb = 't' + ldb = (&b[1,0]) - b0 if b.shape[0] > 1 else 1 + elif _is_contiguous(b, 0): + transb = 'n' + ldb = (&b[0,1]) - b0 if b.shape[1] > 1 else 1 + else: + with gil: + raise ValueError("Input 'b' is neither C nor Fortran contiguous.") + m = a.shape[0] + k = a.shape[1] + if k != b.shape[0]: + with gil: + raise ValueError("Shape mismatch in input arrays.") + n = b.shape[1] + if m != c.shape[0] or n != c.shape[1]: + with gil: + raise ValueError("Output array does not have the correct shape.") + ldc = (&c[0,1]) - c0 if c.shape[1] > 1 else 1 + dgemm(transa, transb, &m, &n, &k, &alpha, a0, &lda, b0, + &ldb, &beta, c0, &ldc) + else: + with gil: + raise ValueError("Input 'c' is neither C nor Fortran contiguous.") + return 0 + +cpdef double _test_dnrm2(double[:] x) noexcept nogil: + cdef: + int n = x.shape[0] + int incx = x.strides[0] // sizeof(x[0]) + return dnrm2(&n, &x[0], &incx) + +cpdef double _test_dzasum(double complex[:] zx) noexcept nogil: + cdef: + int n = zx.shape[0] + int incx = zx.strides[0] // sizeof(zx[0]) + return dzasum(&n, &zx[0], &incx) + +cpdef double _test_dznrm2(double complex[:] x) noexcept nogil: + cdef: + int n = x.shape[0] + int incx = x.strides[0] // sizeof(x[0]) + return dznrm2(&n, &x[0], &incx) + +cpdef int _test_icamax(float complex[:] cx) noexcept nogil: + cdef: + int n = cx.shape[0] + int incx = cx.strides[0] // sizeof(cx[0]) + return icamax(&n, &cx[0], &incx) + +cpdef int _test_idamax(double[:] dx) noexcept nogil: + cdef: + int n = dx.shape[0] + int incx = dx.strides[0] // sizeof(dx[0]) + return idamax(&n, &dx[0], &incx) + +cpdef int _test_isamax(float[:] sx) noexcept nogil: + cdef: + int n = sx.shape[0] + int incx = sx.strides[0] // sizeof(sx[0]) + return isamax(&n, &sx[0], &incx) + +cpdef int _test_izamax(double complex[:] zx) noexcept nogil: + cdef: + int n = zx.shape[0] + int incx = zx.strides[0] // sizeof(zx[0]) + return izamax(&n, &zx[0], &incx) + +cpdef float _test_sasum(float[:] sx) noexcept nogil: + cdef: + int n = sx.shape[0] + int incx = sx.strides[0] // sizeof(sx[0]) + return sasum(&n, &sx[0], &incx) + +cpdef float _test_scasum(float complex[:] cx) noexcept nogil: + cdef: + int n = cx.shape[0] + int incx = cx.strides[0] // sizeof(cx[0]) + return scasum(&n, &cx[0], &incx) + +cpdef float _test_scnrm2(float complex[:] x) noexcept nogil: + cdef: + int n = x.shape[0] + int incx = x.strides[0] // sizeof(x[0]) + return scnrm2(&n, &x[0], &incx) + +cpdef float _test_sdot(float[:] sx, float[:] sy) noexcept nogil: + cdef: + int n = sx.shape[0] + int incx = sx.strides[0] // sizeof(sx[0]) + int incy = sy.strides[0] // sizeof(sy[0]) + return sdot(&n, &sx[0], &incx, &sy[0], &incy) + +cpdef float _test_snrm2(float[:] x) noexcept nogil: + cdef: + int n = x.shape[0] + int incx = x.strides[0] // sizeof(x[0]) + return snrm2(&n, &x[0], &incx) + +cpdef double complex _test_zdotc(double complex[:] zx, double complex[:] zy) noexcept nogil: + cdef: + int n = zx.shape[0] + int incx = zx.strides[0] // sizeof(zx[0]) + int incy = zy.strides[0] // sizeof(zy[0]) + return zdotc(&n, &zx[0], &incx, &zy[0], &incy) + +cpdef double complex _test_zdotu(double complex[:] zx, double complex[:] zy) noexcept nogil: + cdef: + int n = zx.shape[0] + int incx = zx.strides[0] // sizeof(zx[0]) + int incy = zy.strides[0] // sizeof(zy[0]) + return zdotu(&n, &zx[0], &incx, &zy[0], &incy) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/cython_lapack.pxd b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/cython_lapack.pxd new file mode 100644 index 0000000000000000000000000000000000000000..7964c52d766cd1b08bda6411960a29dbeb6bfe2d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/cython_lapack.pxd @@ -0,0 +1,1528 @@ +""" +This file was generated by _generate_pyx.py. +Do not edit this file directly. +""" + +# Within SciPy, these wrappers can be used via relative or absolute cimport. +# Examples: +# from ..linalg cimport cython_lapack +# from scipy.linalg cimport cython_lapack +# cimport scipy.linalg.cython_lapack as cython_lapack +# cimport ..linalg.cython_lapack as cython_lapack + +# Within SciPy, if LAPACK functions are needed in C/C++/Fortran, +# these wrappers should not be used. +# The original libraries should be linked directly. + +ctypedef float s +ctypedef double d +ctypedef float complex c +ctypedef double complex z + +# Function pointer type declarations for +# gees and gges families of functions. +ctypedef bint cselect1(c*) +ctypedef bint cselect2(c*, c*) +ctypedef bint dselect2(d*, d*) +ctypedef bint dselect3(d*, d*, d*) +ctypedef bint sselect2(s*, s*) +ctypedef bint sselect3(s*, s*, s*) +ctypedef bint zselect1(z*) +ctypedef bint zselect2(z*, z*) + +cdef void cbbcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, s *theta, s *phi, c *u1, int *ldu1, c *u2, int *ldu2, c *v1t, int *ldv1t, c *v2t, int *ldv2t, s *b11d, s *b11e, s *b12d, s *b12e, s *b21d, s *b21e, s *b22d, s *b22e, s *rwork, int *lrwork, int *info) noexcept nogil +cdef void cbdsqr(char *uplo, int *n, int *ncvt, int *nru, int *ncc, s *d, s *e, c *vt, int *ldvt, c *u, int *ldu, c *c, int *ldc, s *rwork, int *info) noexcept nogil +cdef void cgbbrd(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, c *ab, int *ldab, s *d, s *e, c *q, int *ldq, c *pt, int *ldpt, c *c, int *ldc, c *work, s *rwork, int *info) noexcept nogil +cdef void cgbcon(char *norm, int *n, int *kl, int *ku, c *ab, int *ldab, int *ipiv, s *anorm, s *rcond, c *work, s *rwork, int *info) noexcept nogil +cdef void cgbequ(int *m, int *n, int *kl, int *ku, c *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil +cdef void cgbequb(int *m, int *n, int *kl, int *ku, c *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil +cdef void cgbrfs(char *trans, int *n, int *kl, int *ku, int *nrhs, c *ab, int *ldab, c *afb, int *ldafb, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil +cdef void cgbsv(int *n, int *kl, int *ku, int *nrhs, c *ab, int *ldab, int *ipiv, c *b, int *ldb, int *info) noexcept nogil +cdef void cgbsvx(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, c *ab, int *ldab, c *afb, int *ldafb, int *ipiv, char *equed, s *r, s *c, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil +cdef void cgbtf2(int *m, int *n, int *kl, int *ku, c *ab, int *ldab, int *ipiv, int *info) noexcept nogil +cdef void cgbtrf(int *m, int *n, int *kl, int *ku, c *ab, int *ldab, int *ipiv, int *info) noexcept nogil +cdef void cgbtrs(char *trans, int *n, int *kl, int *ku, int *nrhs, c *ab, int *ldab, int *ipiv, c *b, int *ldb, int *info) noexcept nogil +cdef void cgebak(char *job, char *side, int *n, int *ilo, int *ihi, s *scale, int *m, c *v, int *ldv, int *info) noexcept nogil +cdef void cgebal(char *job, int *n, c *a, int *lda, int *ilo, int *ihi, s *scale, int *info) noexcept nogil +cdef void cgebd2(int *m, int *n, c *a, int *lda, s *d, s *e, c *tauq, c *taup, c *work, int *info) noexcept nogil +cdef void cgebrd(int *m, int *n, c *a, int *lda, s *d, s *e, c *tauq, c *taup, c *work, int *lwork, int *info) noexcept nogil +cdef void cgecon(char *norm, int *n, c *a, int *lda, s *anorm, s *rcond, c *work, s *rwork, int *info) noexcept nogil +cdef void cgeequ(int *m, int *n, c *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil +cdef void cgeequb(int *m, int *n, c *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil +cdef void cgees(char *jobvs, char *sort, cselect1 *select, int *n, c *a, int *lda, int *sdim, c *w, c *vs, int *ldvs, c *work, int *lwork, s *rwork, bint *bwork, int *info) noexcept nogil +cdef void cgeesx(char *jobvs, char *sort, cselect1 *select, char *sense, int *n, c *a, int *lda, int *sdim, c *w, c *vs, int *ldvs, s *rconde, s *rcondv, c *work, int *lwork, s *rwork, bint *bwork, int *info) noexcept nogil +cdef void cgeev(char *jobvl, char *jobvr, int *n, c *a, int *lda, c *w, c *vl, int *ldvl, c *vr, int *ldvr, c *work, int *lwork, s *rwork, int *info) noexcept nogil +cdef void cgeevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, c *a, int *lda, c *w, c *vl, int *ldvl, c *vr, int *ldvr, int *ilo, int *ihi, s *scale, s *abnrm, s *rconde, s *rcondv, c *work, int *lwork, s *rwork, int *info) noexcept nogil +cdef void cgehd2(int *n, int *ilo, int *ihi, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil +cdef void cgehrd(int *n, int *ilo, int *ihi, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil +cdef void cgelq2(int *m, int *n, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil +cdef void cgelqf(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil +cdef void cgels(char *trans, int *m, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, c *work, int *lwork, int *info) noexcept nogil +cdef void cgelsd(int *m, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, s *s, s *rcond, int *rank, c *work, int *lwork, s *rwork, int *iwork, int *info) noexcept nogil +cdef void cgelss(int *m, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, s *s, s *rcond, int *rank, c *work, int *lwork, s *rwork, int *info) noexcept nogil +cdef void cgelsy(int *m, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, int *jpvt, s *rcond, int *rank, c *work, int *lwork, s *rwork, int *info) noexcept nogil +cdef void cgemqrt(char *side, char *trans, int *m, int *n, int *k, int *nb, c *v, int *ldv, c *t, int *ldt, c *c, int *ldc, c *work, int *info) noexcept nogil +cdef void cgeql2(int *m, int *n, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil +cdef void cgeqlf(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil +cdef void cgeqp3(int *m, int *n, c *a, int *lda, int *jpvt, c *tau, c *work, int *lwork, s *rwork, int *info) noexcept nogil +cdef void cgeqr2(int *m, int *n, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil +cdef void cgeqr2p(int *m, int *n, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil +cdef void cgeqrf(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil +cdef void cgeqrfp(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil +cdef void cgeqrt(int *m, int *n, int *nb, c *a, int *lda, c *t, int *ldt, c *work, int *info) noexcept nogil +cdef void cgeqrt2(int *m, int *n, c *a, int *lda, c *t, int *ldt, int *info) noexcept nogil +cdef void cgeqrt3(int *m, int *n, c *a, int *lda, c *t, int *ldt, int *info) noexcept nogil +cdef void cgerfs(char *trans, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil +cdef void cgerq2(int *m, int *n, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil +cdef void cgerqf(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil +cdef void cgesc2(int *n, c *a, int *lda, c *rhs, int *ipiv, int *jpiv, s *scale) noexcept nogil +cdef void cgesdd(char *jobz, int *m, int *n, c *a, int *lda, s *s, c *u, int *ldu, c *vt, int *ldvt, c *work, int *lwork, s *rwork, int *iwork, int *info) noexcept nogil +cdef void cgesv(int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, int *info) noexcept nogil +cdef void cgesvd(char *jobu, char *jobvt, int *m, int *n, c *a, int *lda, s *s, c *u, int *ldu, c *vt, int *ldvt, c *work, int *lwork, s *rwork, int *info) noexcept nogil +cdef void cgesvx(char *fact, char *trans, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, char *equed, s *r, s *c, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil +cdef void cgetc2(int *n, c *a, int *lda, int *ipiv, int *jpiv, int *info) noexcept nogil +cdef void cgetf2(int *m, int *n, c *a, int *lda, int *ipiv, int *info) noexcept nogil +cdef void cgetrf(int *m, int *n, c *a, int *lda, int *ipiv, int *info) noexcept nogil +cdef void cgetri(int *n, c *a, int *lda, int *ipiv, c *work, int *lwork, int *info) noexcept nogil +cdef void cgetrs(char *trans, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, int *info) noexcept nogil +cdef void cggbak(char *job, char *side, int *n, int *ilo, int *ihi, s *lscale, s *rscale, int *m, c *v, int *ldv, int *info) noexcept nogil +cdef void cggbal(char *job, int *n, c *a, int *lda, c *b, int *ldb, int *ilo, int *ihi, s *lscale, s *rscale, s *work, int *info) noexcept nogil +cdef void cgges(char *jobvsl, char *jobvsr, char *sort, cselect2 *selctg, int *n, c *a, int *lda, c *b, int *ldb, int *sdim, c *alpha, c *beta, c *vsl, int *ldvsl, c *vsr, int *ldvsr, c *work, int *lwork, s *rwork, bint *bwork, int *info) noexcept nogil +cdef void cggesx(char *jobvsl, char *jobvsr, char *sort, cselect2 *selctg, char *sense, int *n, c *a, int *lda, c *b, int *ldb, int *sdim, c *alpha, c *beta, c *vsl, int *ldvsl, c *vsr, int *ldvsr, s *rconde, s *rcondv, c *work, int *lwork, s *rwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil +cdef void cggev(char *jobvl, char *jobvr, int *n, c *a, int *lda, c *b, int *ldb, c *alpha, c *beta, c *vl, int *ldvl, c *vr, int *ldvr, c *work, int *lwork, s *rwork, int *info) noexcept nogil +cdef void cggevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, c *a, int *lda, c *b, int *ldb, c *alpha, c *beta, c *vl, int *ldvl, c *vr, int *ldvr, int *ilo, int *ihi, s *lscale, s *rscale, s *abnrm, s *bbnrm, s *rconde, s *rcondv, c *work, int *lwork, s *rwork, int *iwork, bint *bwork, int *info) noexcept nogil +cdef void cggglm(int *n, int *m, int *p, c *a, int *lda, c *b, int *ldb, c *d, c *x, c *y, c *work, int *lwork, int *info) noexcept nogil +cdef void cgghrd(char *compq, char *compz, int *n, int *ilo, int *ihi, c *a, int *lda, c *b, int *ldb, c *q, int *ldq, c *z, int *ldz, int *info) noexcept nogil +cdef void cgglse(int *m, int *n, int *p, c *a, int *lda, c *b, int *ldb, c *c, c *d, c *x, c *work, int *lwork, int *info) noexcept nogil +cdef void cggqrf(int *n, int *m, int *p, c *a, int *lda, c *taua, c *b, int *ldb, c *taub, c *work, int *lwork, int *info) noexcept nogil +cdef void cggrqf(int *m, int *p, int *n, c *a, int *lda, c *taua, c *b, int *ldb, c *taub, c *work, int *lwork, int *info) noexcept nogil +cdef void cgtcon(char *norm, int *n, c *dl, c *d, c *du, c *du2, int *ipiv, s *anorm, s *rcond, c *work, int *info) noexcept nogil +cdef void cgtrfs(char *trans, int *n, int *nrhs, c *dl, c *d, c *du, c *dlf, c *df, c *duf, c *du2, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil +cdef void cgtsv(int *n, int *nrhs, c *dl, c *d, c *du, c *b, int *ldb, int *info) noexcept nogil +cdef void cgtsvx(char *fact, char *trans, int *n, int *nrhs, c *dl, c *d, c *du, c *dlf, c *df, c *duf, c *du2, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil +cdef void cgttrf(int *n, c *dl, c *d, c *du, c *du2, int *ipiv, int *info) noexcept nogil +cdef void cgttrs(char *trans, int *n, int *nrhs, c *dl, c *d, c *du, c *du2, int *ipiv, c *b, int *ldb, int *info) noexcept nogil +cdef void cgtts2(int *itrans, int *n, int *nrhs, c *dl, c *d, c *du, c *du2, int *ipiv, c *b, int *ldb) noexcept nogil +cdef void chbev(char *jobz, char *uplo, int *n, int *kd, c *ab, int *ldab, s *w, c *z, int *ldz, c *work, s *rwork, int *info) noexcept nogil +cdef void chbevd(char *jobz, char *uplo, int *n, int *kd, c *ab, int *ldab, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void chbevx(char *jobz, char *range, char *uplo, int *n, int *kd, c *ab, int *ldab, c *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil +cdef void chbgst(char *vect, char *uplo, int *n, int *ka, int *kb, c *ab, int *ldab, c *bb, int *ldbb, c *x, int *ldx, c *work, s *rwork, int *info) noexcept nogil +cdef void chbgv(char *jobz, char *uplo, int *n, int *ka, int *kb, c *ab, int *ldab, c *bb, int *ldbb, s *w, c *z, int *ldz, c *work, s *rwork, int *info) noexcept nogil +cdef void chbgvd(char *jobz, char *uplo, int *n, int *ka, int *kb, c *ab, int *ldab, c *bb, int *ldbb, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void chbgvx(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, c *ab, int *ldab, c *bb, int *ldbb, c *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil +cdef void chbtrd(char *vect, char *uplo, int *n, int *kd, c *ab, int *ldab, s *d, s *e, c *q, int *ldq, c *work, int *info) noexcept nogil +cdef void checon(char *uplo, int *n, c *a, int *lda, int *ipiv, s *anorm, s *rcond, c *work, int *info) noexcept nogil +cdef void cheequb(char *uplo, int *n, c *a, int *lda, s *s, s *scond, s *amax, c *work, int *info) noexcept nogil +cdef void cheev(char *jobz, char *uplo, int *n, c *a, int *lda, s *w, c *work, int *lwork, s *rwork, int *info) noexcept nogil +cdef void cheevd(char *jobz, char *uplo, int *n, c *a, int *lda, s *w, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void cheevr(char *jobz, char *range, char *uplo, int *n, c *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, int *isuppz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void cheevx(char *jobz, char *range, char *uplo, int *n, c *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil +cdef void chegs2(int *itype, char *uplo, int *n, c *a, int *lda, c *b, int *ldb, int *info) noexcept nogil +cdef void chegst(int *itype, char *uplo, int *n, c *a, int *lda, c *b, int *ldb, int *info) noexcept nogil +cdef void chegv(int *itype, char *jobz, char *uplo, int *n, c *a, int *lda, c *b, int *ldb, s *w, c *work, int *lwork, s *rwork, int *info) noexcept nogil +cdef void chegvd(int *itype, char *jobz, char *uplo, int *n, c *a, int *lda, c *b, int *ldb, s *w, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void chegvx(int *itype, char *jobz, char *range, char *uplo, int *n, c *a, int *lda, c *b, int *ldb, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil +cdef void cherfs(char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil +cdef void chesv(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, c *work, int *lwork, int *info) noexcept nogil +cdef void chesvx(char *fact, char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, int *lwork, s *rwork, int *info) noexcept nogil +cdef void cheswapr(char *uplo, int *n, c *a, int *lda, int *i1, int *i2) noexcept nogil +cdef void chetd2(char *uplo, int *n, c *a, int *lda, s *d, s *e, c *tau, int *info) noexcept nogil +cdef void chetf2(char *uplo, int *n, c *a, int *lda, int *ipiv, int *info) noexcept nogil +cdef void chetrd(char *uplo, int *n, c *a, int *lda, s *d, s *e, c *tau, c *work, int *lwork, int *info) noexcept nogil +cdef void chetrf(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *lwork, int *info) noexcept nogil +cdef void chetri(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *info) noexcept nogil +cdef void chetri2(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *lwork, int *info) noexcept nogil +cdef void chetri2x(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *nb, int *info) noexcept nogil +cdef void chetrs(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, int *info) noexcept nogil +cdef void chetrs2(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, c *work, int *info) noexcept nogil +cdef void chfrk(char *transr, char *uplo, char *trans, int *n, int *k, s *alpha, c *a, int *lda, s *beta, c *c) noexcept nogil +cdef void chgeqz(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, c *h, int *ldh, c *t, int *ldt, c *alpha, c *beta, c *q, int *ldq, c *z, int *ldz, c *work, int *lwork, s *rwork, int *info) noexcept nogil +cdef char chla_transtype(int *trans) noexcept nogil +cdef void chpcon(char *uplo, int *n, c *ap, int *ipiv, s *anorm, s *rcond, c *work, int *info) noexcept nogil +cdef void chpev(char *jobz, char *uplo, int *n, c *ap, s *w, c *z, int *ldz, c *work, s *rwork, int *info) noexcept nogil +cdef void chpevd(char *jobz, char *uplo, int *n, c *ap, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void chpevx(char *jobz, char *range, char *uplo, int *n, c *ap, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil +cdef void chpgst(int *itype, char *uplo, int *n, c *ap, c *bp, int *info) noexcept nogil +cdef void chpgv(int *itype, char *jobz, char *uplo, int *n, c *ap, c *bp, s *w, c *z, int *ldz, c *work, s *rwork, int *info) noexcept nogil +cdef void chpgvd(int *itype, char *jobz, char *uplo, int *n, c *ap, c *bp, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void chpgvx(int *itype, char *jobz, char *range, char *uplo, int *n, c *ap, c *bp, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil +cdef void chprfs(char *uplo, int *n, int *nrhs, c *ap, c *afp, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil +cdef void chpsv(char *uplo, int *n, int *nrhs, c *ap, int *ipiv, c *b, int *ldb, int *info) noexcept nogil +cdef void chpsvx(char *fact, char *uplo, int *n, int *nrhs, c *ap, c *afp, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil +cdef void chptrd(char *uplo, int *n, c *ap, s *d, s *e, c *tau, int *info) noexcept nogil +cdef void chptrf(char *uplo, int *n, c *ap, int *ipiv, int *info) noexcept nogil +cdef void chptri(char *uplo, int *n, c *ap, int *ipiv, c *work, int *info) noexcept nogil +cdef void chptrs(char *uplo, int *n, int *nrhs, c *ap, int *ipiv, c *b, int *ldb, int *info) noexcept nogil +cdef void chsein(char *side, char *eigsrc, char *initv, bint *select, int *n, c *h, int *ldh, c *w, c *vl, int *ldvl, c *vr, int *ldvr, int *mm, int *m, c *work, s *rwork, int *ifaill, int *ifailr, int *info) noexcept nogil +cdef void chseqr(char *job, char *compz, int *n, int *ilo, int *ihi, c *h, int *ldh, c *w, c *z, int *ldz, c *work, int *lwork, int *info) noexcept nogil +cdef void clabrd(int *m, int *n, int *nb, c *a, int *lda, s *d, s *e, c *tauq, c *taup, c *x, int *ldx, c *y, int *ldy) noexcept nogil +cdef void clacgv(int *n, c *x, int *incx) noexcept nogil +cdef void clacn2(int *n, c *v, c *x, s *est, int *kase, int *isave) noexcept nogil +cdef void clacon(int *n, c *v, c *x, s *est, int *kase) noexcept nogil +cdef void clacp2(char *uplo, int *m, int *n, s *a, int *lda, c *b, int *ldb) noexcept nogil +cdef void clacpy(char *uplo, int *m, int *n, c *a, int *lda, c *b, int *ldb) noexcept nogil +cdef void clacrm(int *m, int *n, c *a, int *lda, s *b, int *ldb, c *c, int *ldc, s *rwork) noexcept nogil +cdef void clacrt(int *n, c *cx, int *incx, c *cy, int *incy, c *c, c *s) noexcept nogil +cdef c cladiv(c *x, c *y) noexcept nogil +cdef void claed0(int *qsiz, int *n, s *d, s *e, c *q, int *ldq, c *qstore, int *ldqs, s *rwork, int *iwork, int *info) noexcept nogil +cdef void claed7(int *n, int *cutpnt, int *qsiz, int *tlvls, int *curlvl, int *curpbm, s *d, c *q, int *ldq, s *rho, int *indxq, s *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, s *givnum, c *work, s *rwork, int *iwork, int *info) noexcept nogil +cdef void claed8(int *k, int *n, int *qsiz, c *q, int *ldq, s *d, s *rho, int *cutpnt, s *z, s *dlamda, c *q2, int *ldq2, s *w, int *indxp, int *indx, int *indxq, int *perm, int *givptr, int *givcol, s *givnum, int *info) noexcept nogil +cdef void claein(bint *rightv, bint *noinit, int *n, c *h, int *ldh, c *w, c *v, c *b, int *ldb, s *rwork, s *eps3, s *smlnum, int *info) noexcept nogil +cdef void claesy(c *a, c *b, c *c, c *rt1, c *rt2, c *evscal, c *cs1, c *sn1) noexcept nogil +cdef void claev2(c *a, c *b, c *c, s *rt1, s *rt2, s *cs1, c *sn1) noexcept nogil +cdef void clag2z(int *m, int *n, c *sa, int *ldsa, z *a, int *lda, int *info) noexcept nogil +cdef void clags2(bint *upper, s *a1, c *a2, s *a3, s *b1, c *b2, s *b3, s *csu, c *snu, s *csv, c *snv, s *csq, c *snq) noexcept nogil +cdef void clagtm(char *trans, int *n, int *nrhs, s *alpha, c *dl, c *d, c *du, c *x, int *ldx, s *beta, c *b, int *ldb) noexcept nogil +cdef void clahef(char *uplo, int *n, int *nb, int *kb, c *a, int *lda, int *ipiv, c *w, int *ldw, int *info) noexcept nogil +cdef void clahqr(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, c *h, int *ldh, c *w, int *iloz, int *ihiz, c *z, int *ldz, int *info) noexcept nogil +cdef void clahr2(int *n, int *k, int *nb, c *a, int *lda, c *tau, c *t, int *ldt, c *y, int *ldy) noexcept nogil +cdef void claic1(int *job, int *j, c *x, s *sest, c *w, c *gamma, s *sestpr, c *s, c *c) noexcept nogil +cdef void clals0(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, c *b, int *ldb, c *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, s *givnum, int *ldgnum, s *poles, s *difl, s *difr, s *z, int *k, s *c, s *s, s *rwork, int *info) noexcept nogil +cdef void clalsa(int *icompq, int *smlsiz, int *n, int *nrhs, c *b, int *ldb, c *bx, int *ldbx, s *u, int *ldu, s *vt, int *k, s *difl, s *difr, s *z, s *poles, int *givptr, int *givcol, int *ldgcol, int *perm, s *givnum, s *c, s *s, s *rwork, int *iwork, int *info) noexcept nogil +cdef void clalsd(char *uplo, int *smlsiz, int *n, int *nrhs, s *d, s *e, c *b, int *ldb, s *rcond, int *rank, c *work, s *rwork, int *iwork, int *info) noexcept nogil +cdef s clangb(char *norm, int *n, int *kl, int *ku, c *ab, int *ldab, s *work) noexcept nogil +cdef s clange(char *norm, int *m, int *n, c *a, int *lda, s *work) noexcept nogil +cdef s clangt(char *norm, int *n, c *dl, c *d, c *du) noexcept nogil +cdef s clanhb(char *norm, char *uplo, int *n, int *k, c *ab, int *ldab, s *work) noexcept nogil +cdef s clanhe(char *norm, char *uplo, int *n, c *a, int *lda, s *work) noexcept nogil +cdef s clanhf(char *norm, char *transr, char *uplo, int *n, c *a, s *work) noexcept nogil +cdef s clanhp(char *norm, char *uplo, int *n, c *ap, s *work) noexcept nogil +cdef s clanhs(char *norm, int *n, c *a, int *lda, s *work) noexcept nogil +cdef s clanht(char *norm, int *n, s *d, c *e) noexcept nogil +cdef s clansb(char *norm, char *uplo, int *n, int *k, c *ab, int *ldab, s *work) noexcept nogil +cdef s clansp(char *norm, char *uplo, int *n, c *ap, s *work) noexcept nogil +cdef s clansy(char *norm, char *uplo, int *n, c *a, int *lda, s *work) noexcept nogil +cdef s clantb(char *norm, char *uplo, char *diag, int *n, int *k, c *ab, int *ldab, s *work) noexcept nogil +cdef s clantp(char *norm, char *uplo, char *diag, int *n, c *ap, s *work) noexcept nogil +cdef s clantr(char *norm, char *uplo, char *diag, int *m, int *n, c *a, int *lda, s *work) noexcept nogil +cdef void clapll(int *n, c *x, int *incx, c *y, int *incy, s *ssmin) noexcept nogil +cdef void clapmr(bint *forwrd, int *m, int *n, c *x, int *ldx, int *k) noexcept nogil +cdef void clapmt(bint *forwrd, int *m, int *n, c *x, int *ldx, int *k) noexcept nogil +cdef void claqgb(int *m, int *n, int *kl, int *ku, c *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) noexcept nogil +cdef void claqge(int *m, int *n, c *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) noexcept nogil +cdef void claqhb(char *uplo, int *n, int *kd, c *ab, int *ldab, s *s, s *scond, s *amax, char *equed) noexcept nogil +cdef void claqhe(char *uplo, int *n, c *a, int *lda, s *s, s *scond, s *amax, char *equed) noexcept nogil +cdef void claqhp(char *uplo, int *n, c *ap, s *s, s *scond, s *amax, char *equed) noexcept nogil +cdef void claqp2(int *m, int *n, int *offset, c *a, int *lda, int *jpvt, c *tau, s *vn1, s *vn2, c *work) noexcept nogil +cdef void claqps(int *m, int *n, int *offset, int *nb, int *kb, c *a, int *lda, int *jpvt, c *tau, s *vn1, s *vn2, c *auxv, c *f, int *ldf) noexcept nogil +cdef void claqr0(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, c *h, int *ldh, c *w, int *iloz, int *ihiz, c *z, int *ldz, c *work, int *lwork, int *info) noexcept nogil +cdef void claqr1(int *n, c *h, int *ldh, c *s1, c *s2, c *v) noexcept nogil +cdef void claqr2(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, c *h, int *ldh, int *iloz, int *ihiz, c *z, int *ldz, int *ns, int *nd, c *sh, c *v, int *ldv, int *nh, c *t, int *ldt, int *nv, c *wv, int *ldwv, c *work, int *lwork) noexcept nogil +cdef void claqr3(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, c *h, int *ldh, int *iloz, int *ihiz, c *z, int *ldz, int *ns, int *nd, c *sh, c *v, int *ldv, int *nh, c *t, int *ldt, int *nv, c *wv, int *ldwv, c *work, int *lwork) noexcept nogil +cdef void claqr4(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, c *h, int *ldh, c *w, int *iloz, int *ihiz, c *z, int *ldz, c *work, int *lwork, int *info) noexcept nogil +cdef void claqr5(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, c *s, c *h, int *ldh, int *iloz, int *ihiz, c *z, int *ldz, c *v, int *ldv, c *u, int *ldu, int *nv, c *wv, int *ldwv, int *nh, c *wh, int *ldwh) noexcept nogil +cdef void claqsb(char *uplo, int *n, int *kd, c *ab, int *ldab, s *s, s *scond, s *amax, char *equed) noexcept nogil +cdef void claqsp(char *uplo, int *n, c *ap, s *s, s *scond, s *amax, char *equed) noexcept nogil +cdef void claqsy(char *uplo, int *n, c *a, int *lda, s *s, s *scond, s *amax, char *equed) noexcept nogil +cdef void clar1v(int *n, int *b1, int *bn, s *lambda_, s *d, s *l, s *ld, s *lld, s *pivmin, s *gaptol, c *z, bint *wantnc, int *negcnt, s *ztz, s *mingma, int *r, int *isuppz, s *nrminv, s *resid, s *rqcorr, s *work) noexcept nogil +cdef void clar2v(int *n, c *x, c *y, c *z, int *incx, s *c, c *s, int *incc) noexcept nogil +cdef void clarcm(int *m, int *n, s *a, int *lda, c *b, int *ldb, c *c, int *ldc, s *rwork) noexcept nogil +cdef void clarf(char *side, int *m, int *n, c *v, int *incv, c *tau, c *c, int *ldc, c *work) noexcept nogil +cdef void clarfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, c *v, int *ldv, c *t, int *ldt, c *c, int *ldc, c *work, int *ldwork) noexcept nogil +cdef void clarfg(int *n, c *alpha, c *x, int *incx, c *tau) noexcept nogil +cdef void clarfgp(int *n, c *alpha, c *x, int *incx, c *tau) noexcept nogil +cdef void clarft(char *direct, char *storev, int *n, int *k, c *v, int *ldv, c *tau, c *t, int *ldt) noexcept nogil +cdef void clarfx(char *side, int *m, int *n, c *v, c *tau, c *c, int *ldc, c *work) noexcept nogil +cdef void clargv(int *n, c *x, int *incx, c *y, int *incy, s *c, int *incc) noexcept nogil +cdef void clarnv(int *idist, int *iseed, int *n, c *x) noexcept nogil +cdef void clarrv(int *n, s *vl, s *vu, s *d, s *l, s *pivmin, int *isplit, int *m, int *dol, int *dou, s *minrgp, s *rtol1, s *rtol2, s *w, s *werr, s *wgap, int *iblock, int *indexw, s *gers, c *z, int *ldz, int *isuppz, s *work, int *iwork, int *info) noexcept nogil +cdef void clartg(c *f, c *g, s *cs, c *sn, c *r) noexcept nogil +cdef void clartv(int *n, c *x, int *incx, c *y, int *incy, s *c, c *s, int *incc) noexcept nogil +cdef void clarz(char *side, int *m, int *n, int *l, c *v, int *incv, c *tau, c *c, int *ldc, c *work) noexcept nogil +cdef void clarzb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, c *v, int *ldv, c *t, int *ldt, c *c, int *ldc, c *work, int *ldwork) noexcept nogil +cdef void clarzt(char *direct, char *storev, int *n, int *k, c *v, int *ldv, c *tau, c *t, int *ldt) noexcept nogil +cdef void clascl(char *type_bn, int *kl, int *ku, s *cfrom, s *cto, int *m, int *n, c *a, int *lda, int *info) noexcept nogil +cdef void claset(char *uplo, int *m, int *n, c *alpha, c *beta, c *a, int *lda) noexcept nogil +cdef void clasr(char *side, char *pivot, char *direct, int *m, int *n, s *c, s *s, c *a, int *lda) noexcept nogil +cdef void classq(int *n, c *x, int *incx, s *scale, s *sumsq) noexcept nogil +cdef void claswp(int *n, c *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) noexcept nogil +cdef void clasyf(char *uplo, int *n, int *nb, int *kb, c *a, int *lda, int *ipiv, c *w, int *ldw, int *info) noexcept nogil +cdef void clatbs(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, c *ab, int *ldab, c *x, s *scale, s *cnorm, int *info) noexcept nogil +cdef void clatdf(int *ijob, int *n, c *z, int *ldz, c *rhs, s *rdsum, s *rdscal, int *ipiv, int *jpiv) noexcept nogil +cdef void clatps(char *uplo, char *trans, char *diag, char *normin, int *n, c *ap, c *x, s *scale, s *cnorm, int *info) noexcept nogil +cdef void clatrd(char *uplo, int *n, int *nb, c *a, int *lda, s *e, c *tau, c *w, int *ldw) noexcept nogil +cdef void clatrs(char *uplo, char *trans, char *diag, char *normin, int *n, c *a, int *lda, c *x, s *scale, s *cnorm, int *info) noexcept nogil +cdef void clatrz(int *m, int *n, int *l, c *a, int *lda, c *tau, c *work) noexcept nogil +cdef void clauu2(char *uplo, int *n, c *a, int *lda, int *info) noexcept nogil +cdef void clauum(char *uplo, int *n, c *a, int *lda, int *info) noexcept nogil +cdef void cpbcon(char *uplo, int *n, int *kd, c *ab, int *ldab, s *anorm, s *rcond, c *work, s *rwork, int *info) noexcept nogil +cdef void cpbequ(char *uplo, int *n, int *kd, c *ab, int *ldab, s *s, s *scond, s *amax, int *info) noexcept nogil +cdef void cpbrfs(char *uplo, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *afb, int *ldafb, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil +cdef void cpbstf(char *uplo, int *n, int *kd, c *ab, int *ldab, int *info) noexcept nogil +cdef void cpbsv(char *uplo, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *b, int *ldb, int *info) noexcept nogil +cdef void cpbsvx(char *fact, char *uplo, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *afb, int *ldafb, char *equed, s *s, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil +cdef void cpbtf2(char *uplo, int *n, int *kd, c *ab, int *ldab, int *info) noexcept nogil +cdef void cpbtrf(char *uplo, int *n, int *kd, c *ab, int *ldab, int *info) noexcept nogil +cdef void cpbtrs(char *uplo, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *b, int *ldb, int *info) noexcept nogil +cdef void cpftrf(char *transr, char *uplo, int *n, c *a, int *info) noexcept nogil +cdef void cpftri(char *transr, char *uplo, int *n, c *a, int *info) noexcept nogil +cdef void cpftrs(char *transr, char *uplo, int *n, int *nrhs, c *a, c *b, int *ldb, int *info) noexcept nogil +cdef void cpocon(char *uplo, int *n, c *a, int *lda, s *anorm, s *rcond, c *work, s *rwork, int *info) noexcept nogil +cdef void cpoequ(int *n, c *a, int *lda, s *s, s *scond, s *amax, int *info) noexcept nogil +cdef void cpoequb(int *n, c *a, int *lda, s *s, s *scond, s *amax, int *info) noexcept nogil +cdef void cporfs(char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil +cdef void cposv(char *uplo, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, int *info) noexcept nogil +cdef void cposvx(char *fact, char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, char *equed, s *s, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil +cdef void cpotf2(char *uplo, int *n, c *a, int *lda, int *info) noexcept nogil +cdef void cpotrf(char *uplo, int *n, c *a, int *lda, int *info) noexcept nogil +cdef void cpotri(char *uplo, int *n, c *a, int *lda, int *info) noexcept nogil +cdef void cpotrs(char *uplo, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, int *info) noexcept nogil +cdef void cppcon(char *uplo, int *n, c *ap, s *anorm, s *rcond, c *work, s *rwork, int *info) noexcept nogil +cdef void cppequ(char *uplo, int *n, c *ap, s *s, s *scond, s *amax, int *info) noexcept nogil +cdef void cpprfs(char *uplo, int *n, int *nrhs, c *ap, c *afp, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil +cdef void cppsv(char *uplo, int *n, int *nrhs, c *ap, c *b, int *ldb, int *info) noexcept nogil +cdef void cppsvx(char *fact, char *uplo, int *n, int *nrhs, c *ap, c *afp, char *equed, s *s, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil +cdef void cpptrf(char *uplo, int *n, c *ap, int *info) noexcept nogil +cdef void cpptri(char *uplo, int *n, c *ap, int *info) noexcept nogil +cdef void cpptrs(char *uplo, int *n, int *nrhs, c *ap, c *b, int *ldb, int *info) noexcept nogil +cdef void cpstf2(char *uplo, int *n, c *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) noexcept nogil +cdef void cpstrf(char *uplo, int *n, c *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) noexcept nogil +cdef void cptcon(int *n, s *d, c *e, s *anorm, s *rcond, s *rwork, int *info) noexcept nogil +cdef void cpteqr(char *compz, int *n, s *d, s *e, c *z, int *ldz, s *work, int *info) noexcept nogil +cdef void cptrfs(char *uplo, int *n, int *nrhs, s *d, c *e, s *df, c *ef, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil +cdef void cptsv(int *n, int *nrhs, s *d, c *e, c *b, int *ldb, int *info) noexcept nogil +cdef void cptsvx(char *fact, int *n, int *nrhs, s *d, c *e, s *df, c *ef, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil +cdef void cpttrf(int *n, s *d, c *e, int *info) noexcept nogil +cdef void cpttrs(char *uplo, int *n, int *nrhs, s *d, c *e, c *b, int *ldb, int *info) noexcept nogil +cdef void cptts2(int *iuplo, int *n, int *nrhs, s *d, c *e, c *b, int *ldb) noexcept nogil +cdef void crot(int *n, c *cx, int *incx, c *cy, int *incy, s *c, c *s) noexcept nogil +cdef void cspcon(char *uplo, int *n, c *ap, int *ipiv, s *anorm, s *rcond, c *work, int *info) noexcept nogil +cdef void cspmv(char *uplo, int *n, c *alpha, c *ap, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil +cdef void cspr(char *uplo, int *n, c *alpha, c *x, int *incx, c *ap) noexcept nogil +cdef void csprfs(char *uplo, int *n, int *nrhs, c *ap, c *afp, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil +cdef void cspsv(char *uplo, int *n, int *nrhs, c *ap, int *ipiv, c *b, int *ldb, int *info) noexcept nogil +cdef void cspsvx(char *fact, char *uplo, int *n, int *nrhs, c *ap, c *afp, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil +cdef void csptrf(char *uplo, int *n, c *ap, int *ipiv, int *info) noexcept nogil +cdef void csptri(char *uplo, int *n, c *ap, int *ipiv, c *work, int *info) noexcept nogil +cdef void csptrs(char *uplo, int *n, int *nrhs, c *ap, int *ipiv, c *b, int *ldb, int *info) noexcept nogil +cdef void csrscl(int *n, s *sa, c *sx, int *incx) noexcept nogil +cdef void cstedc(char *compz, int *n, s *d, s *e, c *z, int *ldz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void cstegr(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, int *isuppz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void cstein(int *n, s *d, s *e, int *m, s *w, int *iblock, int *isplit, c *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil +cdef void cstemr(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, int *m, s *w, c *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void csteqr(char *compz, int *n, s *d, s *e, c *z, int *ldz, s *work, int *info) noexcept nogil +cdef void csycon(char *uplo, int *n, c *a, int *lda, int *ipiv, s *anorm, s *rcond, c *work, int *info) noexcept nogil +cdef void csyconv(char *uplo, char *way, int *n, c *a, int *lda, int *ipiv, c *work, int *info) noexcept nogil +cdef void csyequb(char *uplo, int *n, c *a, int *lda, s *s, s *scond, s *amax, c *work, int *info) noexcept nogil +cdef void csymv(char *uplo, int *n, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil +cdef void csyr(char *uplo, int *n, c *alpha, c *x, int *incx, c *a, int *lda) noexcept nogil +cdef void csyrfs(char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil +cdef void csysv(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, c *work, int *lwork, int *info) noexcept nogil +cdef void csysvx(char *fact, char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, int *lwork, s *rwork, int *info) noexcept nogil +cdef void csyswapr(char *uplo, int *n, c *a, int *lda, int *i1, int *i2) noexcept nogil +cdef void csytf2(char *uplo, int *n, c *a, int *lda, int *ipiv, int *info) noexcept nogil +cdef void csytrf(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *lwork, int *info) noexcept nogil +cdef void csytri(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *info) noexcept nogil +cdef void csytri2(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *lwork, int *info) noexcept nogil +cdef void csytri2x(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *nb, int *info) noexcept nogil +cdef void csytrs(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, int *info) noexcept nogil +cdef void csytrs2(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, c *work, int *info) noexcept nogil +cdef void ctbcon(char *norm, char *uplo, char *diag, int *n, int *kd, c *ab, int *ldab, s *rcond, c *work, s *rwork, int *info) noexcept nogil +cdef void ctbrfs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil +cdef void ctbtrs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *b, int *ldb, int *info) noexcept nogil +cdef void ctfsm(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, c *alpha, c *a, c *b, int *ldb) noexcept nogil +cdef void ctftri(char *transr, char *uplo, char *diag, int *n, c *a, int *info) noexcept nogil +cdef void ctfttp(char *transr, char *uplo, int *n, c *arf, c *ap, int *info) noexcept nogil +cdef void ctfttr(char *transr, char *uplo, int *n, c *arf, c *a, int *lda, int *info) noexcept nogil +cdef void ctgevc(char *side, char *howmny, bint *select, int *n, c *s, int *lds, c *p, int *ldp, c *vl, int *ldvl, c *vr, int *ldvr, int *mm, int *m, c *work, s *rwork, int *info) noexcept nogil +cdef void ctgex2(bint *wantq, bint *wantz, int *n, c *a, int *lda, c *b, int *ldb, c *q, int *ldq, c *z, int *ldz, int *j1, int *info) noexcept nogil +cdef void ctgexc(bint *wantq, bint *wantz, int *n, c *a, int *lda, c *b, int *ldb, c *q, int *ldq, c *z, int *ldz, int *ifst, int *ilst, int *info) noexcept nogil +cdef void ctgsen(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, c *a, int *lda, c *b, int *ldb, c *alpha, c *beta, c *q, int *ldq, c *z, int *ldz, int *m, s *pl, s *pr, s *dif, c *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void ctgsja(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, c *a, int *lda, c *b, int *ldb, s *tola, s *tolb, s *alpha, s *beta, c *u, int *ldu, c *v, int *ldv, c *q, int *ldq, c *work, int *ncycle, int *info) noexcept nogil +cdef void ctgsna(char *job, char *howmny, bint *select, int *n, c *a, int *lda, c *b, int *ldb, c *vl, int *ldvl, c *vr, int *ldvr, s *s, s *dif, int *mm, int *m, c *work, int *lwork, int *iwork, int *info) noexcept nogil +cdef void ctgsy2(char *trans, int *ijob, int *m, int *n, c *a, int *lda, c *b, int *ldb, c *c, int *ldc, c *d, int *ldd, c *e, int *lde, c *f, int *ldf, s *scale, s *rdsum, s *rdscal, int *info) noexcept nogil +cdef void ctgsyl(char *trans, int *ijob, int *m, int *n, c *a, int *lda, c *b, int *ldb, c *c, int *ldc, c *d, int *ldd, c *e, int *lde, c *f, int *ldf, s *scale, s *dif, c *work, int *lwork, int *iwork, int *info) noexcept nogil +cdef void ctpcon(char *norm, char *uplo, char *diag, int *n, c *ap, s *rcond, c *work, s *rwork, int *info) noexcept nogil +cdef void ctpmqrt(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, c *v, int *ldv, c *t, int *ldt, c *a, int *lda, c *b, int *ldb, c *work, int *info) noexcept nogil +cdef void ctpqrt(int *m, int *n, int *l, int *nb, c *a, int *lda, c *b, int *ldb, c *t, int *ldt, c *work, int *info) noexcept nogil +cdef void ctpqrt2(int *m, int *n, int *l, c *a, int *lda, c *b, int *ldb, c *t, int *ldt, int *info) noexcept nogil +cdef void ctprfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, c *v, int *ldv, c *t, int *ldt, c *a, int *lda, c *b, int *ldb, c *work, int *ldwork) noexcept nogil +cdef void ctprfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, c *ap, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil +cdef void ctptri(char *uplo, char *diag, int *n, c *ap, int *info) noexcept nogil +cdef void ctptrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, c *ap, c *b, int *ldb, int *info) noexcept nogil +cdef void ctpttf(char *transr, char *uplo, int *n, c *ap, c *arf, int *info) noexcept nogil +cdef void ctpttr(char *uplo, int *n, c *ap, c *a, int *lda, int *info) noexcept nogil +cdef void ctrcon(char *norm, char *uplo, char *diag, int *n, c *a, int *lda, s *rcond, c *work, s *rwork, int *info) noexcept nogil +cdef void ctrevc(char *side, char *howmny, bint *select, int *n, c *t, int *ldt, c *vl, int *ldvl, c *vr, int *ldvr, int *mm, int *m, c *work, s *rwork, int *info) noexcept nogil +cdef void ctrexc(char *compq, int *n, c *t, int *ldt, c *q, int *ldq, int *ifst, int *ilst, int *info) noexcept nogil +cdef void ctrrfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil +cdef void ctrsen(char *job, char *compq, bint *select, int *n, c *t, int *ldt, c *q, int *ldq, c *w, int *m, s *s, s *sep, c *work, int *lwork, int *info) noexcept nogil +cdef void ctrsna(char *job, char *howmny, bint *select, int *n, c *t, int *ldt, c *vl, int *ldvl, c *vr, int *ldvr, s *s, s *sep, int *mm, int *m, c *work, int *ldwork, s *rwork, int *info) noexcept nogil +cdef void ctrsyl(char *trana, char *tranb, int *isgn, int *m, int *n, c *a, int *lda, c *b, int *ldb, c *c, int *ldc, s *scale, int *info) noexcept nogil +cdef void ctrti2(char *uplo, char *diag, int *n, c *a, int *lda, int *info) noexcept nogil +cdef void ctrtri(char *uplo, char *diag, int *n, c *a, int *lda, int *info) noexcept nogil +cdef void ctrtrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, int *info) noexcept nogil +cdef void ctrttf(char *transr, char *uplo, int *n, c *a, int *lda, c *arf, int *info) noexcept nogil +cdef void ctrttp(char *uplo, int *n, c *a, int *lda, c *ap, int *info) noexcept nogil +cdef void ctzrzf(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil +cdef void cunbdb(char *trans, char *signs, int *m, int *p, int *q, c *x11, int *ldx11, c *x12, int *ldx12, c *x21, int *ldx21, c *x22, int *ldx22, s *theta, s *phi, c *taup1, c *taup2, c *tauq1, c *tauq2, c *work, int *lwork, int *info) noexcept nogil +cdef void cuncsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, c *x11, int *ldx11, c *x12, int *ldx12, c *x21, int *ldx21, c *x22, int *ldx22, s *theta, c *u1, int *ldu1, c *u2, int *ldu2, c *v1t, int *ldv1t, c *v2t, int *ldv2t, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *info) noexcept nogil +cdef void cung2l(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil +cdef void cung2r(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil +cdef void cungbr(char *vect, int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil +cdef void cunghr(int *n, int *ilo, int *ihi, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil +cdef void cungl2(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil +cdef void cunglq(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil +cdef void cungql(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil +cdef void cungqr(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil +cdef void cungr2(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil +cdef void cungrq(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil +cdef void cungtr(char *uplo, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil +cdef void cunm2l(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil +cdef void cunm2r(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil +cdef void cunmbr(char *vect, char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil +cdef void cunmhr(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil +cdef void cunml2(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil +cdef void cunmlq(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil +cdef void cunmql(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil +cdef void cunmqr(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil +cdef void cunmr2(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil +cdef void cunmr3(char *side, char *trans, int *m, int *n, int *k, int *l, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil +cdef void cunmrq(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil +cdef void cunmrz(char *side, char *trans, int *m, int *n, int *k, int *l, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil +cdef void cunmtr(char *side, char *uplo, char *trans, int *m, int *n, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil +cdef void cupgtr(char *uplo, int *n, c *ap, c *tau, c *q, int *ldq, c *work, int *info) noexcept nogil +cdef void cupmtr(char *side, char *uplo, char *trans, int *m, int *n, c *ap, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil +cdef void dbbcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, d *theta, d *phi, d *u1, int *ldu1, d *u2, int *ldu2, d *v1t, int *ldv1t, d *v2t, int *ldv2t, d *b11d, d *b11e, d *b12d, d *b12e, d *b21d, d *b21e, d *b22d, d *b22e, d *work, int *lwork, int *info) noexcept nogil +cdef void dbdsdc(char *uplo, char *compq, int *n, d *d, d *e, d *u, int *ldu, d *vt, int *ldvt, d *q, int *iq, d *work, int *iwork, int *info) noexcept nogil +cdef void dbdsqr(char *uplo, int *n, int *ncvt, int *nru, int *ncc, d *d, d *e, d *vt, int *ldvt, d *u, int *ldu, d *c, int *ldc, d *work, int *info) noexcept nogil +cdef void ddisna(char *job, int *m, int *n, d *d, d *sep, int *info) noexcept nogil +cdef void dgbbrd(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, d *ab, int *ldab, d *d, d *e, d *q, int *ldq, d *pt, int *ldpt, d *c, int *ldc, d *work, int *info) noexcept nogil +cdef void dgbcon(char *norm, int *n, int *kl, int *ku, d *ab, int *ldab, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil +cdef void dgbequ(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil +cdef void dgbequb(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil +cdef void dgbrfs(char *trans, int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, d *afb, int *ldafb, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil +cdef void dgbsv(int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, int *ipiv, d *b, int *ldb, int *info) noexcept nogil +cdef void dgbsvx(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, d *afb, int *ldafb, int *ipiv, char *equed, d *r, d *c, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil +cdef void dgbtf2(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, int *ipiv, int *info) noexcept nogil +cdef void dgbtrf(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, int *ipiv, int *info) noexcept nogil +cdef void dgbtrs(char *trans, int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, int *ipiv, d *b, int *ldb, int *info) noexcept nogil +cdef void dgebak(char *job, char *side, int *n, int *ilo, int *ihi, d *scale, int *m, d *v, int *ldv, int *info) noexcept nogil +cdef void dgebal(char *job, int *n, d *a, int *lda, int *ilo, int *ihi, d *scale, int *info) noexcept nogil +cdef void dgebd2(int *m, int *n, d *a, int *lda, d *d, d *e, d *tauq, d *taup, d *work, int *info) noexcept nogil +cdef void dgebrd(int *m, int *n, d *a, int *lda, d *d, d *e, d *tauq, d *taup, d *work, int *lwork, int *info) noexcept nogil +cdef void dgecon(char *norm, int *n, d *a, int *lda, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil +cdef void dgeequ(int *m, int *n, d *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil +cdef void dgeequb(int *m, int *n, d *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil +cdef void dgees(char *jobvs, char *sort, dselect2 *select, int *n, d *a, int *lda, int *sdim, d *wr, d *wi, d *vs, int *ldvs, d *work, int *lwork, bint *bwork, int *info) noexcept nogil +cdef void dgeesx(char *jobvs, char *sort, dselect2 *select, char *sense, int *n, d *a, int *lda, int *sdim, d *wr, d *wi, d *vs, int *ldvs, d *rconde, d *rcondv, d *work, int *lwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil +cdef void dgeev(char *jobvl, char *jobvr, int *n, d *a, int *lda, d *wr, d *wi, d *vl, int *ldvl, d *vr, int *ldvr, d *work, int *lwork, int *info) noexcept nogil +cdef void dgeevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, d *a, int *lda, d *wr, d *wi, d *vl, int *ldvl, d *vr, int *ldvr, int *ilo, int *ihi, d *scale, d *abnrm, d *rconde, d *rcondv, d *work, int *lwork, int *iwork, int *info) noexcept nogil +cdef void dgehd2(int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil +cdef void dgehrd(int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil +cdef void dgejsv(char *joba, char *jobu, char *jobv, char *jobr, char *jobt, char *jobp, int *m, int *n, d *a, int *lda, d *sva, d *u, int *ldu, d *v, int *ldv, d *work, int *lwork, int *iwork, int *info) noexcept nogil +cdef void dgelq2(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil +cdef void dgelqf(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil +cdef void dgels(char *trans, int *m, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *work, int *lwork, int *info) noexcept nogil +cdef void dgelsd(int *m, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *s, d *rcond, int *rank, d *work, int *lwork, int *iwork, int *info) noexcept nogil +cdef void dgelss(int *m, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *s, d *rcond, int *rank, d *work, int *lwork, int *info) noexcept nogil +cdef void dgelsy(int *m, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *jpvt, d *rcond, int *rank, d *work, int *lwork, int *info) noexcept nogil +cdef void dgemqrt(char *side, char *trans, int *m, int *n, int *k, int *nb, d *v, int *ldv, d *t, int *ldt, d *c, int *ldc, d *work, int *info) noexcept nogil +cdef void dgeql2(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil +cdef void dgeqlf(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil +cdef void dgeqp3(int *m, int *n, d *a, int *lda, int *jpvt, d *tau, d *work, int *lwork, int *info) noexcept nogil +cdef void dgeqr2(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil +cdef void dgeqr2p(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil +cdef void dgeqrf(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil +cdef void dgeqrfp(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil +cdef void dgeqrt(int *m, int *n, int *nb, d *a, int *lda, d *t, int *ldt, d *work, int *info) noexcept nogil +cdef void dgeqrt2(int *m, int *n, d *a, int *lda, d *t, int *ldt, int *info) noexcept nogil +cdef void dgeqrt3(int *m, int *n, d *a, int *lda, d *t, int *ldt, int *info) noexcept nogil +cdef void dgerfs(char *trans, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil +cdef void dgerq2(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil +cdef void dgerqf(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil +cdef void dgesc2(int *n, d *a, int *lda, d *rhs, int *ipiv, int *jpiv, d *scale) noexcept nogil +cdef void dgesdd(char *jobz, int *m, int *n, d *a, int *lda, d *s, d *u, int *ldu, d *vt, int *ldvt, d *work, int *lwork, int *iwork, int *info) noexcept nogil +cdef void dgesv(int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, int *info) noexcept nogil +cdef void dgesvd(char *jobu, char *jobvt, int *m, int *n, d *a, int *lda, d *s, d *u, int *ldu, d *vt, int *ldvt, d *work, int *lwork, int *info) noexcept nogil +cdef void dgesvj(char *joba, char *jobu, char *jobv, int *m, int *n, d *a, int *lda, d *sva, int *mv, d *v, int *ldv, d *work, int *lwork, int *info) noexcept nogil +cdef void dgesvx(char *fact, char *trans, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, int *ipiv, char *equed, d *r, d *c, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil +cdef void dgetc2(int *n, d *a, int *lda, int *ipiv, int *jpiv, int *info) noexcept nogil +cdef void dgetf2(int *m, int *n, d *a, int *lda, int *ipiv, int *info) noexcept nogil +cdef void dgetrf(int *m, int *n, d *a, int *lda, int *ipiv, int *info) noexcept nogil +cdef void dgetri(int *n, d *a, int *lda, int *ipiv, d *work, int *lwork, int *info) noexcept nogil +cdef void dgetrs(char *trans, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, int *info) noexcept nogil +cdef void dggbak(char *job, char *side, int *n, int *ilo, int *ihi, d *lscale, d *rscale, int *m, d *v, int *ldv, int *info) noexcept nogil +cdef void dggbal(char *job, int *n, d *a, int *lda, d *b, int *ldb, int *ilo, int *ihi, d *lscale, d *rscale, d *work, int *info) noexcept nogil +cdef void dgges(char *jobvsl, char *jobvsr, char *sort, dselect3 *selctg, int *n, d *a, int *lda, d *b, int *ldb, int *sdim, d *alphar, d *alphai, d *beta, d *vsl, int *ldvsl, d *vsr, int *ldvsr, d *work, int *lwork, bint *bwork, int *info) noexcept nogil +cdef void dggesx(char *jobvsl, char *jobvsr, char *sort, dselect3 *selctg, char *sense, int *n, d *a, int *lda, d *b, int *ldb, int *sdim, d *alphar, d *alphai, d *beta, d *vsl, int *ldvsl, d *vsr, int *ldvsr, d *rconde, d *rcondv, d *work, int *lwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil +cdef void dggev(char *jobvl, char *jobvr, int *n, d *a, int *lda, d *b, int *ldb, d *alphar, d *alphai, d *beta, d *vl, int *ldvl, d *vr, int *ldvr, d *work, int *lwork, int *info) noexcept nogil +cdef void dggevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, d *a, int *lda, d *b, int *ldb, d *alphar, d *alphai, d *beta, d *vl, int *ldvl, d *vr, int *ldvr, int *ilo, int *ihi, d *lscale, d *rscale, d *abnrm, d *bbnrm, d *rconde, d *rcondv, d *work, int *lwork, int *iwork, bint *bwork, int *info) noexcept nogil +cdef void dggglm(int *n, int *m, int *p, d *a, int *lda, d *b, int *ldb, d *d, d *x, d *y, d *work, int *lwork, int *info) noexcept nogil +cdef void dgghrd(char *compq, char *compz, int *n, int *ilo, int *ihi, d *a, int *lda, d *b, int *ldb, d *q, int *ldq, d *z, int *ldz, int *info) noexcept nogil +cdef void dgglse(int *m, int *n, int *p, d *a, int *lda, d *b, int *ldb, d *c, d *d, d *x, d *work, int *lwork, int *info) noexcept nogil +cdef void dggqrf(int *n, int *m, int *p, d *a, int *lda, d *taua, d *b, int *ldb, d *taub, d *work, int *lwork, int *info) noexcept nogil +cdef void dggrqf(int *m, int *p, int *n, d *a, int *lda, d *taua, d *b, int *ldb, d *taub, d *work, int *lwork, int *info) noexcept nogil +cdef void dgsvj0(char *jobv, int *m, int *n, d *a, int *lda, d *d, d *sva, int *mv, d *v, int *ldv, d *eps, d *sfmin, d *tol, int *nsweep, d *work, int *lwork, int *info) noexcept nogil +cdef void dgsvj1(char *jobv, int *m, int *n, int *n1, d *a, int *lda, d *d, d *sva, int *mv, d *v, int *ldv, d *eps, d *sfmin, d *tol, int *nsweep, d *work, int *lwork, int *info) noexcept nogil +cdef void dgtcon(char *norm, int *n, d *dl, d *d, d *du, d *du2, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil +cdef void dgtrfs(char *trans, int *n, int *nrhs, d *dl, d *d, d *du, d *dlf, d *df, d *duf, d *du2, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil +cdef void dgtsv(int *n, int *nrhs, d *dl, d *d, d *du, d *b, int *ldb, int *info) noexcept nogil +cdef void dgtsvx(char *fact, char *trans, int *n, int *nrhs, d *dl, d *d, d *du, d *dlf, d *df, d *duf, d *du2, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil +cdef void dgttrf(int *n, d *dl, d *d, d *du, d *du2, int *ipiv, int *info) noexcept nogil +cdef void dgttrs(char *trans, int *n, int *nrhs, d *dl, d *d, d *du, d *du2, int *ipiv, d *b, int *ldb, int *info) noexcept nogil +cdef void dgtts2(int *itrans, int *n, int *nrhs, d *dl, d *d, d *du, d *du2, int *ipiv, d *b, int *ldb) noexcept nogil +cdef void dhgeqz(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *t, int *ldt, d *alphar, d *alphai, d *beta, d *q, int *ldq, d *z, int *ldz, d *work, int *lwork, int *info) noexcept nogil +cdef void dhsein(char *side, char *eigsrc, char *initv, bint *select, int *n, d *h, int *ldh, d *wr, d *wi, d *vl, int *ldvl, d *vr, int *ldvr, int *mm, int *m, d *work, int *ifaill, int *ifailr, int *info) noexcept nogil +cdef void dhseqr(char *job, char *compz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *wr, d *wi, d *z, int *ldz, d *work, int *lwork, int *info) noexcept nogil +cdef bint disnan(d *din) noexcept nogil +cdef void dlabad(d *small, d *large) noexcept nogil +cdef void dlabrd(int *m, int *n, int *nb, d *a, int *lda, d *d, d *e, d *tauq, d *taup, d *x, int *ldx, d *y, int *ldy) noexcept nogil +cdef void dlacn2(int *n, d *v, d *x, int *isgn, d *est, int *kase, int *isave) noexcept nogil +cdef void dlacon(int *n, d *v, d *x, int *isgn, d *est, int *kase) noexcept nogil +cdef void dlacpy(char *uplo, int *m, int *n, d *a, int *lda, d *b, int *ldb) noexcept nogil +cdef void dladiv(d *a, d *b, d *c, d *d, d *p, d *q) noexcept nogil +cdef void dlae2(d *a, d *b, d *c, d *rt1, d *rt2) noexcept nogil +cdef void dlaebz(int *ijob, int *nitmax, int *n, int *mmax, int *minp, int *nbmin, d *abstol, d *reltol, d *pivmin, d *d, d *e, d *e2, int *nval, d *ab, d *c, int *mout, int *nab, d *work, int *iwork, int *info) noexcept nogil +cdef void dlaed0(int *icompq, int *qsiz, int *n, d *d, d *e, d *q, int *ldq, d *qstore, int *ldqs, d *work, int *iwork, int *info) noexcept nogil +cdef void dlaed1(int *n, d *d, d *q, int *ldq, int *indxq, d *rho, int *cutpnt, d *work, int *iwork, int *info) noexcept nogil +cdef void dlaed2(int *k, int *n, int *n1, d *d, d *q, int *ldq, int *indxq, d *rho, d *z, d *dlamda, d *w, d *q2, int *indx, int *indxc, int *indxp, int *coltyp, int *info) noexcept nogil +cdef void dlaed3(int *k, int *n, int *n1, d *d, d *q, int *ldq, d *rho, d *dlamda, d *q2, int *indx, int *ctot, d *w, d *s, int *info) noexcept nogil +cdef void dlaed4(int *n, int *i, d *d, d *z, d *delta, d *rho, d *dlam, int *info) noexcept nogil +cdef void dlaed5(int *i, d *d, d *z, d *delta, d *rho, d *dlam) noexcept nogil +cdef void dlaed6(int *kniter, bint *orgati, d *rho, d *d, d *z, d *finit, d *tau, int *info) noexcept nogil +cdef void dlaed7(int *icompq, int *n, int *qsiz, int *tlvls, int *curlvl, int *curpbm, d *d, d *q, int *ldq, int *indxq, d *rho, int *cutpnt, d *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, d *givnum, d *work, int *iwork, int *info) noexcept nogil +cdef void dlaed8(int *icompq, int *k, int *n, int *qsiz, d *d, d *q, int *ldq, int *indxq, d *rho, int *cutpnt, d *z, d *dlamda, d *q2, int *ldq2, d *w, int *perm, int *givptr, int *givcol, d *givnum, int *indxp, int *indx, int *info) noexcept nogil +cdef void dlaed9(int *k, int *kstart, int *kstop, int *n, d *d, d *q, int *ldq, d *rho, d *dlamda, d *w, d *s, int *lds, int *info) noexcept nogil +cdef void dlaeda(int *n, int *tlvls, int *curlvl, int *curpbm, int *prmptr, int *perm, int *givptr, int *givcol, d *givnum, d *q, int *qptr, d *z, d *ztemp, int *info) noexcept nogil +cdef void dlaein(bint *rightv, bint *noinit, int *n, d *h, int *ldh, d *wr, d *wi, d *vr, d *vi, d *b, int *ldb, d *work, d *eps3, d *smlnum, d *bignum, int *info) noexcept nogil +cdef void dlaev2(d *a, d *b, d *c, d *rt1, d *rt2, d *cs1, d *sn1) noexcept nogil +cdef void dlaexc(bint *wantq, int *n, d *t, int *ldt, d *q, int *ldq, int *j1, int *n1, int *n2, d *work, int *info) noexcept nogil +cdef void dlag2(d *a, int *lda, d *b, int *ldb, d *safmin, d *scale1, d *scale2, d *wr1, d *wr2, d *wi) noexcept nogil +cdef void dlag2s(int *m, int *n, d *a, int *lda, s *sa, int *ldsa, int *info) noexcept nogil +cdef void dlags2(bint *upper, d *a1, d *a2, d *a3, d *b1, d *b2, d *b3, d *csu, d *snu, d *csv, d *snv, d *csq, d *snq) noexcept nogil +cdef void dlagtf(int *n, d *a, d *lambda_, d *b, d *c, d *tol, d *d, int *in_, int *info) noexcept nogil +cdef void dlagtm(char *trans, int *n, int *nrhs, d *alpha, d *dl, d *d, d *du, d *x, int *ldx, d *beta, d *b, int *ldb) noexcept nogil +cdef void dlagts(int *job, int *n, d *a, d *b, d *c, d *d, int *in_, d *y, d *tol, int *info) noexcept nogil +cdef void dlagv2(d *a, int *lda, d *b, int *ldb, d *alphar, d *alphai, d *beta, d *csl, d *snl, d *csr, d *snr) noexcept nogil +cdef void dlahqr(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *wr, d *wi, int *iloz, int *ihiz, d *z, int *ldz, int *info) noexcept nogil +cdef void dlahr2(int *n, int *k, int *nb, d *a, int *lda, d *tau, d *t, int *ldt, d *y, int *ldy) noexcept nogil +cdef void dlaic1(int *job, int *j, d *x, d *sest, d *w, d *gamma, d *sestpr, d *s, d *c) noexcept nogil +cdef void dlaln2(bint *ltrans, int *na, int *nw, d *smin, d *ca, d *a, int *lda, d *d1, d *d2, d *b, int *ldb, d *wr, d *wi, d *x, int *ldx, d *scale, d *xnorm, int *info) noexcept nogil +cdef void dlals0(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, d *b, int *ldb, d *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, d *givnum, int *ldgnum, d *poles, d *difl, d *difr, d *z, int *k, d *c, d *s, d *work, int *info) noexcept nogil +cdef void dlalsa(int *icompq, int *smlsiz, int *n, int *nrhs, d *b, int *ldb, d *bx, int *ldbx, d *u, int *ldu, d *vt, int *k, d *difl, d *difr, d *z, d *poles, int *givptr, int *givcol, int *ldgcol, int *perm, d *givnum, d *c, d *s, d *work, int *iwork, int *info) noexcept nogil +cdef void dlalsd(char *uplo, int *smlsiz, int *n, int *nrhs, d *d, d *e, d *b, int *ldb, d *rcond, int *rank, d *work, int *iwork, int *info) noexcept nogil +cdef d dlamch(char *cmach) noexcept nogil +cdef void dlamrg(int *n1, int *n2, d *a, int *dtrd1, int *dtrd2, int *index_bn) noexcept nogil +cdef int dlaneg(int *n, d *d, d *lld, d *sigma, d *pivmin, int *r) noexcept nogil +cdef d dlangb(char *norm, int *n, int *kl, int *ku, d *ab, int *ldab, d *work) noexcept nogil +cdef d dlange(char *norm, int *m, int *n, d *a, int *lda, d *work) noexcept nogil +cdef d dlangt(char *norm, int *n, d *dl, d *d_, d *du) noexcept nogil +cdef d dlanhs(char *norm, int *n, d *a, int *lda, d *work) noexcept nogil +cdef d dlansb(char *norm, char *uplo, int *n, int *k, d *ab, int *ldab, d *work) noexcept nogil +cdef d dlansf(char *norm, char *transr, char *uplo, int *n, d *a, d *work) noexcept nogil +cdef d dlansp(char *norm, char *uplo, int *n, d *ap, d *work) noexcept nogil +cdef d dlanst(char *norm, int *n, d *d_, d *e) noexcept nogil +cdef d dlansy(char *norm, char *uplo, int *n, d *a, int *lda, d *work) noexcept nogil +cdef d dlantb(char *norm, char *uplo, char *diag, int *n, int *k, d *ab, int *ldab, d *work) noexcept nogil +cdef d dlantp(char *norm, char *uplo, char *diag, int *n, d *ap, d *work) noexcept nogil +cdef d dlantr(char *norm, char *uplo, char *diag, int *m, int *n, d *a, int *lda, d *work) noexcept nogil +cdef void dlanv2(d *a, d *b, d *c, d *d, d *rt1r, d *rt1i, d *rt2r, d *rt2i, d *cs, d *sn) noexcept nogil +cdef void dlapll(int *n, d *x, int *incx, d *y, int *incy, d *ssmin) noexcept nogil +cdef void dlapmr(bint *forwrd, int *m, int *n, d *x, int *ldx, int *k) noexcept nogil +cdef void dlapmt(bint *forwrd, int *m, int *n, d *x, int *ldx, int *k) noexcept nogil +cdef d dlapy2(d *x, d *y) noexcept nogil +cdef d dlapy3(d *x, d *y, d *z) noexcept nogil +cdef void dlaqgb(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) noexcept nogil +cdef void dlaqge(int *m, int *n, d *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) noexcept nogil +cdef void dlaqp2(int *m, int *n, int *offset, d *a, int *lda, int *jpvt, d *tau, d *vn1, d *vn2, d *work) noexcept nogil +cdef void dlaqps(int *m, int *n, int *offset, int *nb, int *kb, d *a, int *lda, int *jpvt, d *tau, d *vn1, d *vn2, d *auxv, d *f, int *ldf) noexcept nogil +cdef void dlaqr0(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *wr, d *wi, int *iloz, int *ihiz, d *z, int *ldz, d *work, int *lwork, int *info) noexcept nogil +cdef void dlaqr1(int *n, d *h, int *ldh, d *sr1, d *si1, d *sr2, d *si2, d *v) noexcept nogil +cdef void dlaqr2(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, d *h, int *ldh, int *iloz, int *ihiz, d *z, int *ldz, int *ns, int *nd, d *sr, d *si, d *v, int *ldv, int *nh, d *t, int *ldt, int *nv, d *wv, int *ldwv, d *work, int *lwork) noexcept nogil +cdef void dlaqr3(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, d *h, int *ldh, int *iloz, int *ihiz, d *z, int *ldz, int *ns, int *nd, d *sr, d *si, d *v, int *ldv, int *nh, d *t, int *ldt, int *nv, d *wv, int *ldwv, d *work, int *lwork) noexcept nogil +cdef void dlaqr4(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *wr, d *wi, int *iloz, int *ihiz, d *z, int *ldz, d *work, int *lwork, int *info) noexcept nogil +cdef void dlaqr5(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, d *sr, d *si, d *h, int *ldh, int *iloz, int *ihiz, d *z, int *ldz, d *v, int *ldv, d *u, int *ldu, int *nv, d *wv, int *ldwv, int *nh, d *wh, int *ldwh) noexcept nogil +cdef void dlaqsb(char *uplo, int *n, int *kd, d *ab, int *ldab, d *s, d *scond, d *amax, char *equed) noexcept nogil +cdef void dlaqsp(char *uplo, int *n, d *ap, d *s, d *scond, d *amax, char *equed) noexcept nogil +cdef void dlaqsy(char *uplo, int *n, d *a, int *lda, d *s, d *scond, d *amax, char *equed) noexcept nogil +cdef void dlaqtr(bint *ltran, bint *lreal, int *n, d *t, int *ldt, d *b, d *w, d *scale, d *x, d *work, int *info) noexcept nogil +cdef void dlar1v(int *n, int *b1, int *bn, d *lambda_, d *d, d *l, d *ld, d *lld, d *pivmin, d *gaptol, d *z, bint *wantnc, int *negcnt, d *ztz, d *mingma, int *r, int *isuppz, d *nrminv, d *resid, d *rqcorr, d *work) noexcept nogil +cdef void dlar2v(int *n, d *x, d *y, d *z, int *incx, d *c, d *s, int *incc) noexcept nogil +cdef void dlarf(char *side, int *m, int *n, d *v, int *incv, d *tau, d *c, int *ldc, d *work) noexcept nogil +cdef void dlarfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, d *v, int *ldv, d *t, int *ldt, d *c, int *ldc, d *work, int *ldwork) noexcept nogil +cdef void dlarfg(int *n, d *alpha, d *x, int *incx, d *tau) noexcept nogil +cdef void dlarfgp(int *n, d *alpha, d *x, int *incx, d *tau) noexcept nogil +cdef void dlarft(char *direct, char *storev, int *n, int *k, d *v, int *ldv, d *tau, d *t, int *ldt) noexcept nogil +cdef void dlarfx(char *side, int *m, int *n, d *v, d *tau, d *c, int *ldc, d *work) noexcept nogil +cdef void dlargv(int *n, d *x, int *incx, d *y, int *incy, d *c, int *incc) noexcept nogil +cdef void dlarnv(int *idist, int *iseed, int *n, d *x) noexcept nogil +cdef void dlarra(int *n, d *d, d *e, d *e2, d *spltol, d *tnrm, int *nsplit, int *isplit, int *info) noexcept nogil +cdef void dlarrb(int *n, d *d, d *lld, int *ifirst, int *ilast, d *rtol1, d *rtol2, int *offset, d *w, d *wgap, d *werr, d *work, int *iwork, d *pivmin, d *spdiam, int *twist, int *info) noexcept nogil +cdef void dlarrc(char *jobt, int *n, d *vl, d *vu, d *d, d *e, d *pivmin, int *eigcnt, int *lcnt, int *rcnt, int *info) noexcept nogil +cdef void dlarrd(char *range, char *order, int *n, d *vl, d *vu, int *il, int *iu, d *gers, d *reltol, d *d, d *e, d *e2, d *pivmin, int *nsplit, int *isplit, int *m, d *w, d *werr, d *wl, d *wu, int *iblock, int *indexw, d *work, int *iwork, int *info) noexcept nogil +cdef void dlarre(char *range, int *n, d *vl, d *vu, int *il, int *iu, d *d, d *e, d *e2, d *rtol1, d *rtol2, d *spltol, int *nsplit, int *isplit, int *m, d *w, d *werr, d *wgap, int *iblock, int *indexw, d *gers, d *pivmin, d *work, int *iwork, int *info) noexcept nogil +cdef void dlarrf(int *n, d *d, d *l, d *ld, int *clstrt, int *clend, d *w, d *wgap, d *werr, d *spdiam, d *clgapl, d *clgapr, d *pivmin, d *sigma, d *dplus, d *lplus, d *work, int *info) noexcept nogil +cdef void dlarrj(int *n, d *d, d *e2, int *ifirst, int *ilast, d *rtol, int *offset, d *w, d *werr, d *work, int *iwork, d *pivmin, d *spdiam, int *info) noexcept nogil +cdef void dlarrk(int *n, int *iw, d *gl, d *gu, d *d, d *e2, d *pivmin, d *reltol, d *w, d *werr, int *info) noexcept nogil +cdef void dlarrr(int *n, d *d, d *e, int *info) noexcept nogil +cdef void dlarrv(int *n, d *vl, d *vu, d *d, d *l, d *pivmin, int *isplit, int *m, int *dol, int *dou, d *minrgp, d *rtol1, d *rtol2, d *w, d *werr, d *wgap, int *iblock, int *indexw, d *gers, d *z, int *ldz, int *isuppz, d *work, int *iwork, int *info) noexcept nogil +cdef void dlartg(d *f, d *g, d *cs, d *sn, d *r) noexcept nogil +cdef void dlartgp(d *f, d *g, d *cs, d *sn, d *r) noexcept nogil +cdef void dlartgs(d *x, d *y, d *sigma, d *cs, d *sn) noexcept nogil +cdef void dlartv(int *n, d *x, int *incx, d *y, int *incy, d *c, d *s, int *incc) noexcept nogil +cdef void dlaruv(int *iseed, int *n, d *x) noexcept nogil +cdef void dlarz(char *side, int *m, int *n, int *l, d *v, int *incv, d *tau, d *c, int *ldc, d *work) noexcept nogil +cdef void dlarzb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, d *v, int *ldv, d *t, int *ldt, d *c, int *ldc, d *work, int *ldwork) noexcept nogil +cdef void dlarzt(char *direct, char *storev, int *n, int *k, d *v, int *ldv, d *tau, d *t, int *ldt) noexcept nogil +cdef void dlas2(d *f, d *g, d *h, d *ssmin, d *ssmax) noexcept nogil +cdef void dlascl(char *type_bn, int *kl, int *ku, d *cfrom, d *cto, int *m, int *n, d *a, int *lda, int *info) noexcept nogil +cdef void dlasd0(int *n, int *sqre, d *d, d *e, d *u, int *ldu, d *vt, int *ldvt, int *smlsiz, int *iwork, d *work, int *info) noexcept nogil +cdef void dlasd1(int *nl, int *nr, int *sqre, d *d, d *alpha, d *beta, d *u, int *ldu, d *vt, int *ldvt, int *idxq, int *iwork, d *work, int *info) noexcept nogil +cdef void dlasd2(int *nl, int *nr, int *sqre, int *k, d *d, d *z, d *alpha, d *beta, d *u, int *ldu, d *vt, int *ldvt, d *dsigma, d *u2, int *ldu2, d *vt2, int *ldvt2, int *idxp, int *idx, int *idxc, int *idxq, int *coltyp, int *info) noexcept nogil +cdef void dlasd3(int *nl, int *nr, int *sqre, int *k, d *d, d *q, int *ldq, d *dsigma, d *u, int *ldu, d *u2, int *ldu2, d *vt, int *ldvt, d *vt2, int *ldvt2, int *idxc, int *ctot, d *z, int *info) noexcept nogil +cdef void dlasd4(int *n, int *i, d *d, d *z, d *delta, d *rho, d *sigma, d *work, int *info) noexcept nogil +cdef void dlasd5(int *i, d *d, d *z, d *delta, d *rho, d *dsigma, d *work) noexcept nogil +cdef void dlasd6(int *icompq, int *nl, int *nr, int *sqre, d *d, d *vf, d *vl, d *alpha, d *beta, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, d *givnum, int *ldgnum, d *poles, d *difl, d *difr, d *z, int *k, d *c, d *s, d *work, int *iwork, int *info) noexcept nogil +cdef void dlasd7(int *icompq, int *nl, int *nr, int *sqre, int *k, d *d, d *z, d *zw, d *vf, d *vfw, d *vl, d *vlw, d *alpha, d *beta, d *dsigma, int *idx, int *idxp, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, d *givnum, int *ldgnum, d *c, d *s, int *info) noexcept nogil +cdef void dlasd8(int *icompq, int *k, d *d, d *z, d *vf, d *vl, d *difl, d *difr, int *lddifr, d *dsigma, d *work, int *info) noexcept nogil +cdef void dlasda(int *icompq, int *smlsiz, int *n, int *sqre, d *d, d *e, d *u, int *ldu, d *vt, int *k, d *difl, d *difr, d *z, d *poles, int *givptr, int *givcol, int *ldgcol, int *perm, d *givnum, d *c, d *s, d *work, int *iwork, int *info) noexcept nogil +cdef void dlasdq(char *uplo, int *sqre, int *n, int *ncvt, int *nru, int *ncc, d *d, d *e, d *vt, int *ldvt, d *u, int *ldu, d *c, int *ldc, d *work, int *info) noexcept nogil +cdef void dlasdt(int *n, int *lvl, int *nd, int *inode, int *ndiml, int *ndimr, int *msub) noexcept nogil +cdef void dlaset(char *uplo, int *m, int *n, d *alpha, d *beta, d *a, int *lda) noexcept nogil +cdef void dlasq1(int *n, d *d, d *e, d *work, int *info) noexcept nogil +cdef void dlasq2(int *n, d *z, int *info) noexcept nogil +cdef void dlasq3(int *i0, int *n0, d *z, int *pp, d *dmin, d *sigma, d *desig, d *qmax, int *nfail, int *iter, int *ndiv, bint *ieee, int *ttype, d *dmin1, d *dmin2, d *dn, d *dn1, d *dn2, d *g, d *tau) noexcept nogil +cdef void dlasq4(int *i0, int *n0, d *z, int *pp, int *n0in, d *dmin, d *dmin1, d *dmin2, d *dn, d *dn1, d *dn2, d *tau, int *ttype, d *g) noexcept nogil +cdef void dlasq6(int *i0, int *n0, d *z, int *pp, d *dmin, d *dmin1, d *dmin2, d *dn, d *dnm1, d *dnm2) noexcept nogil +cdef void dlasr(char *side, char *pivot, char *direct, int *m, int *n, d *c, d *s, d *a, int *lda) noexcept nogil +cdef void dlasrt(char *id, int *n, d *d, int *info) noexcept nogil +cdef void dlassq(int *n, d *x, int *incx, d *scale, d *sumsq) noexcept nogil +cdef void dlasv2(d *f, d *g, d *h, d *ssmin, d *ssmax, d *snr, d *csr, d *snl, d *csl) noexcept nogil +cdef void dlaswp(int *n, d *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) noexcept nogil +cdef void dlasy2(bint *ltranl, bint *ltranr, int *isgn, int *n1, int *n2, d *tl, int *ldtl, d *tr, int *ldtr, d *b, int *ldb, d *scale, d *x, int *ldx, d *xnorm, int *info) noexcept nogil +cdef void dlasyf(char *uplo, int *n, int *nb, int *kb, d *a, int *lda, int *ipiv, d *w, int *ldw, int *info) noexcept nogil +cdef void dlat2s(char *uplo, int *n, d *a, int *lda, s *sa, int *ldsa, int *info) noexcept nogil +cdef void dlatbs(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, d *ab, int *ldab, d *x, d *scale, d *cnorm, int *info) noexcept nogil +cdef void dlatdf(int *ijob, int *n, d *z, int *ldz, d *rhs, d *rdsum, d *rdscal, int *ipiv, int *jpiv) noexcept nogil +cdef void dlatps(char *uplo, char *trans, char *diag, char *normin, int *n, d *ap, d *x, d *scale, d *cnorm, int *info) noexcept nogil +cdef void dlatrd(char *uplo, int *n, int *nb, d *a, int *lda, d *e, d *tau, d *w, int *ldw) noexcept nogil +cdef void dlatrs(char *uplo, char *trans, char *diag, char *normin, int *n, d *a, int *lda, d *x, d *scale, d *cnorm, int *info) noexcept nogil +cdef void dlatrz(int *m, int *n, int *l, d *a, int *lda, d *tau, d *work) noexcept nogil +cdef void dlauu2(char *uplo, int *n, d *a, int *lda, int *info) noexcept nogil +cdef void dlauum(char *uplo, int *n, d *a, int *lda, int *info) noexcept nogil +cdef void dopgtr(char *uplo, int *n, d *ap, d *tau, d *q, int *ldq, d *work, int *info) noexcept nogil +cdef void dopmtr(char *side, char *uplo, char *trans, int *m, int *n, d *ap, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil +cdef void dorbdb(char *trans, char *signs, int *m, int *p, int *q, d *x11, int *ldx11, d *x12, int *ldx12, d *x21, int *ldx21, d *x22, int *ldx22, d *theta, d *phi, d *taup1, d *taup2, d *tauq1, d *tauq2, d *work, int *lwork, int *info) noexcept nogil +cdef void dorcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, d *x11, int *ldx11, d *x12, int *ldx12, d *x21, int *ldx21, d *x22, int *ldx22, d *theta, d *u1, int *ldu1, d *u2, int *ldu2, d *v1t, int *ldv1t, d *v2t, int *ldv2t, d *work, int *lwork, int *iwork, int *info) noexcept nogil +cdef void dorg2l(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil +cdef void dorg2r(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil +cdef void dorgbr(char *vect, int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil +cdef void dorghr(int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil +cdef void dorgl2(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil +cdef void dorglq(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil +cdef void dorgql(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil +cdef void dorgqr(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil +cdef void dorgr2(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil +cdef void dorgrq(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil +cdef void dorgtr(char *uplo, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil +cdef void dorm2l(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil +cdef void dorm2r(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil +cdef void dormbr(char *vect, char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil +cdef void dormhr(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil +cdef void dorml2(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil +cdef void dormlq(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil +cdef void dormql(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil +cdef void dormqr(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil +cdef void dormr2(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil +cdef void dormr3(char *side, char *trans, int *m, int *n, int *k, int *l, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil +cdef void dormrq(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil +cdef void dormrz(char *side, char *trans, int *m, int *n, int *k, int *l, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil +cdef void dormtr(char *side, char *uplo, char *trans, int *m, int *n, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil +cdef void dpbcon(char *uplo, int *n, int *kd, d *ab, int *ldab, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil +cdef void dpbequ(char *uplo, int *n, int *kd, d *ab, int *ldab, d *s, d *scond, d *amax, int *info) noexcept nogil +cdef void dpbrfs(char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *afb, int *ldafb, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil +cdef void dpbstf(char *uplo, int *n, int *kd, d *ab, int *ldab, int *info) noexcept nogil +cdef void dpbsv(char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, int *info) noexcept nogil +cdef void dpbsvx(char *fact, char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *afb, int *ldafb, char *equed, d *s, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil +cdef void dpbtf2(char *uplo, int *n, int *kd, d *ab, int *ldab, int *info) noexcept nogil +cdef void dpbtrf(char *uplo, int *n, int *kd, d *ab, int *ldab, int *info) noexcept nogil +cdef void dpbtrs(char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, int *info) noexcept nogil +cdef void dpftrf(char *transr, char *uplo, int *n, d *a, int *info) noexcept nogil +cdef void dpftri(char *transr, char *uplo, int *n, d *a, int *info) noexcept nogil +cdef void dpftrs(char *transr, char *uplo, int *n, int *nrhs, d *a, d *b, int *ldb, int *info) noexcept nogil +cdef void dpocon(char *uplo, int *n, d *a, int *lda, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil +cdef void dpoequ(int *n, d *a, int *lda, d *s, d *scond, d *amax, int *info) noexcept nogil +cdef void dpoequb(int *n, d *a, int *lda, d *s, d *scond, d *amax, int *info) noexcept nogil +cdef void dporfs(char *uplo, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil +cdef void dposv(char *uplo, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *info) noexcept nogil +cdef void dposvx(char *fact, char *uplo, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, char *equed, d *s, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil +cdef void dpotf2(char *uplo, int *n, d *a, int *lda, int *info) noexcept nogil +cdef void dpotrf(char *uplo, int *n, d *a, int *lda, int *info) noexcept nogil +cdef void dpotri(char *uplo, int *n, d *a, int *lda, int *info) noexcept nogil +cdef void dpotrs(char *uplo, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *info) noexcept nogil +cdef void dppcon(char *uplo, int *n, d *ap, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil +cdef void dppequ(char *uplo, int *n, d *ap, d *s, d *scond, d *amax, int *info) noexcept nogil +cdef void dpprfs(char *uplo, int *n, int *nrhs, d *ap, d *afp, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil +cdef void dppsv(char *uplo, int *n, int *nrhs, d *ap, d *b, int *ldb, int *info) noexcept nogil +cdef void dppsvx(char *fact, char *uplo, int *n, int *nrhs, d *ap, d *afp, char *equed, d *s, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil +cdef void dpptrf(char *uplo, int *n, d *ap, int *info) noexcept nogil +cdef void dpptri(char *uplo, int *n, d *ap, int *info) noexcept nogil +cdef void dpptrs(char *uplo, int *n, int *nrhs, d *ap, d *b, int *ldb, int *info) noexcept nogil +cdef void dpstf2(char *uplo, int *n, d *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) noexcept nogil +cdef void dpstrf(char *uplo, int *n, d *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) noexcept nogil +cdef void dptcon(int *n, d *d, d *e, d *anorm, d *rcond, d *work, int *info) noexcept nogil +cdef void dpteqr(char *compz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *info) noexcept nogil +cdef void dptrfs(int *n, int *nrhs, d *d, d *e, d *df, d *ef, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *info) noexcept nogil +cdef void dptsv(int *n, int *nrhs, d *d, d *e, d *b, int *ldb, int *info) noexcept nogil +cdef void dptsvx(char *fact, int *n, int *nrhs, d *d, d *e, d *df, d *ef, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *info) noexcept nogil +cdef void dpttrf(int *n, d *d, d *e, int *info) noexcept nogil +cdef void dpttrs(int *n, int *nrhs, d *d, d *e, d *b, int *ldb, int *info) noexcept nogil +cdef void dptts2(int *n, int *nrhs, d *d, d *e, d *b, int *ldb) noexcept nogil +cdef void drscl(int *n, d *sa, d *sx, int *incx) noexcept nogil +cdef void dsbev(char *jobz, char *uplo, int *n, int *kd, d *ab, int *ldab, d *w, d *z, int *ldz, d *work, int *info) noexcept nogil +cdef void dsbevd(char *jobz, char *uplo, int *n, int *kd, d *ab, int *ldab, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void dsbevx(char *jobz, char *range, char *uplo, int *n, int *kd, d *ab, int *ldab, d *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil +cdef void dsbgst(char *vect, char *uplo, int *n, int *ka, int *kb, d *ab, int *ldab, d *bb, int *ldbb, d *x, int *ldx, d *work, int *info) noexcept nogil +cdef void dsbgv(char *jobz, char *uplo, int *n, int *ka, int *kb, d *ab, int *ldab, d *bb, int *ldbb, d *w, d *z, int *ldz, d *work, int *info) noexcept nogil +cdef void dsbgvd(char *jobz, char *uplo, int *n, int *ka, int *kb, d *ab, int *ldab, d *bb, int *ldbb, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void dsbgvx(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, d *ab, int *ldab, d *bb, int *ldbb, d *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil +cdef void dsbtrd(char *vect, char *uplo, int *n, int *kd, d *ab, int *ldab, d *d, d *e, d *q, int *ldq, d *work, int *info) noexcept nogil +cdef void dsfrk(char *transr, char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *beta, d *c) noexcept nogil +cdef void dsgesv(int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *work, s *swork, int *iter, int *info) noexcept nogil +cdef void dspcon(char *uplo, int *n, d *ap, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil +cdef void dspev(char *jobz, char *uplo, int *n, d *ap, d *w, d *z, int *ldz, d *work, int *info) noexcept nogil +cdef void dspevd(char *jobz, char *uplo, int *n, d *ap, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void dspevx(char *jobz, char *range, char *uplo, int *n, d *ap, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil +cdef void dspgst(int *itype, char *uplo, int *n, d *ap, d *bp, int *info) noexcept nogil +cdef void dspgv(int *itype, char *jobz, char *uplo, int *n, d *ap, d *bp, d *w, d *z, int *ldz, d *work, int *info) noexcept nogil +cdef void dspgvd(int *itype, char *jobz, char *uplo, int *n, d *ap, d *bp, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void dspgvx(int *itype, char *jobz, char *range, char *uplo, int *n, d *ap, d *bp, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil +cdef void dsposv(char *uplo, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *x, int *ldx, d *work, s *swork, int *iter, int *info) noexcept nogil +cdef void dsprfs(char *uplo, int *n, int *nrhs, d *ap, d *afp, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil +cdef void dspsv(char *uplo, int *n, int *nrhs, d *ap, int *ipiv, d *b, int *ldb, int *info) noexcept nogil +cdef void dspsvx(char *fact, char *uplo, int *n, int *nrhs, d *ap, d *afp, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil +cdef void dsptrd(char *uplo, int *n, d *ap, d *d, d *e, d *tau, int *info) noexcept nogil +cdef void dsptrf(char *uplo, int *n, d *ap, int *ipiv, int *info) noexcept nogil +cdef void dsptri(char *uplo, int *n, d *ap, int *ipiv, d *work, int *info) noexcept nogil +cdef void dsptrs(char *uplo, int *n, int *nrhs, d *ap, int *ipiv, d *b, int *ldb, int *info) noexcept nogil +cdef void dstebz(char *range, char *order, int *n, d *vl, d *vu, int *il, int *iu, d *abstol, d *d, d *e, int *m, int *nsplit, d *w, int *iblock, int *isplit, d *work, int *iwork, int *info) noexcept nogil +cdef void dstedc(char *compz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void dstegr(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, int *isuppz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void dstein(int *n, d *d, d *e, int *m, d *w, int *iblock, int *isplit, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil +cdef void dstemr(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, int *m, d *w, d *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void dsteqr(char *compz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *info) noexcept nogil +cdef void dsterf(int *n, d *d, d *e, int *info) noexcept nogil +cdef void dstev(char *jobz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *info) noexcept nogil +cdef void dstevd(char *jobz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void dstevr(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, int *isuppz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void dstevx(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil +cdef void dsycon(char *uplo, int *n, d *a, int *lda, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil +cdef void dsyconv(char *uplo, char *way, int *n, d *a, int *lda, int *ipiv, d *work, int *info) noexcept nogil +cdef void dsyequb(char *uplo, int *n, d *a, int *lda, d *s, d *scond, d *amax, d *work, int *info) noexcept nogil +cdef void dsyev(char *jobz, char *uplo, int *n, d *a, int *lda, d *w, d *work, int *lwork, int *info) noexcept nogil +cdef void dsyevd(char *jobz, char *uplo, int *n, d *a, int *lda, d *w, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void dsyevr(char *jobz, char *range, char *uplo, int *n, d *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, int *isuppz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void dsyevx(char *jobz, char *range, char *uplo, int *n, d *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *ifail, int *info) noexcept nogil +cdef void dsygs2(int *itype, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, int *info) noexcept nogil +cdef void dsygst(int *itype, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, int *info) noexcept nogil +cdef void dsygv(int *itype, char *jobz, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, d *w, d *work, int *lwork, int *info) noexcept nogil +cdef void dsygvd(int *itype, char *jobz, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, d *w, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void dsygvx(int *itype, char *jobz, char *range, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *ifail, int *info) noexcept nogil +cdef void dsyrfs(char *uplo, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil +cdef void dsysv(char *uplo, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, d *work, int *lwork, int *info) noexcept nogil +cdef void dsysvx(char *fact, char *uplo, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *lwork, int *iwork, int *info) noexcept nogil +cdef void dsyswapr(char *uplo, int *n, d *a, int *lda, int *i1, int *i2) noexcept nogil +cdef void dsytd2(char *uplo, int *n, d *a, int *lda, d *d, d *e, d *tau, int *info) noexcept nogil +cdef void dsytf2(char *uplo, int *n, d *a, int *lda, int *ipiv, int *info) noexcept nogil +cdef void dsytrd(char *uplo, int *n, d *a, int *lda, d *d, d *e, d *tau, d *work, int *lwork, int *info) noexcept nogil +cdef void dsytrf(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *lwork, int *info) noexcept nogil +cdef void dsytri(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *info) noexcept nogil +cdef void dsytri2(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *lwork, int *info) noexcept nogil +cdef void dsytri2x(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *nb, int *info) noexcept nogil +cdef void dsytrs(char *uplo, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, int *info) noexcept nogil +cdef void dsytrs2(char *uplo, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, d *work, int *info) noexcept nogil +cdef void dtbcon(char *norm, char *uplo, char *diag, int *n, int *kd, d *ab, int *ldab, d *rcond, d *work, int *iwork, int *info) noexcept nogil +cdef void dtbrfs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil +cdef void dtbtrs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, int *info) noexcept nogil +cdef void dtfsm(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, d *alpha, d *a, d *b, int *ldb) noexcept nogil +cdef void dtftri(char *transr, char *uplo, char *diag, int *n, d *a, int *info) noexcept nogil +cdef void dtfttp(char *transr, char *uplo, int *n, d *arf, d *ap, int *info) noexcept nogil +cdef void dtfttr(char *transr, char *uplo, int *n, d *arf, d *a, int *lda, int *info) noexcept nogil +cdef void dtgevc(char *side, char *howmny, bint *select, int *n, d *s, int *lds, d *p, int *ldp, d *vl, int *ldvl, d *vr, int *ldvr, int *mm, int *m, d *work, int *info) noexcept nogil +cdef void dtgex2(bint *wantq, bint *wantz, int *n, d *a, int *lda, d *b, int *ldb, d *q, int *ldq, d *z, int *ldz, int *j1, int *n1, int *n2, d *work, int *lwork, int *info) noexcept nogil +cdef void dtgexc(bint *wantq, bint *wantz, int *n, d *a, int *lda, d *b, int *ldb, d *q, int *ldq, d *z, int *ldz, int *ifst, int *ilst, d *work, int *lwork, int *info) noexcept nogil +cdef void dtgsen(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, d *a, int *lda, d *b, int *ldb, d *alphar, d *alphai, d *beta, d *q, int *ldq, d *z, int *ldz, int *m, d *pl, d *pr, d *dif, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void dtgsja(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, d *a, int *lda, d *b, int *ldb, d *tola, d *tolb, d *alpha, d *beta, d *u, int *ldu, d *v, int *ldv, d *q, int *ldq, d *work, int *ncycle, int *info) noexcept nogil +cdef void dtgsna(char *job, char *howmny, bint *select, int *n, d *a, int *lda, d *b, int *ldb, d *vl, int *ldvl, d *vr, int *ldvr, d *s, d *dif, int *mm, int *m, d *work, int *lwork, int *iwork, int *info) noexcept nogil +cdef void dtgsy2(char *trans, int *ijob, int *m, int *n, d *a, int *lda, d *b, int *ldb, d *c, int *ldc, d *d, int *ldd, d *e, int *lde, d *f, int *ldf, d *scale, d *rdsum, d *rdscal, int *iwork, int *pq, int *info) noexcept nogil +cdef void dtgsyl(char *trans, int *ijob, int *m, int *n, d *a, int *lda, d *b, int *ldb, d *c, int *ldc, d *d, int *ldd, d *e, int *lde, d *f, int *ldf, d *scale, d *dif, d *work, int *lwork, int *iwork, int *info) noexcept nogil +cdef void dtpcon(char *norm, char *uplo, char *diag, int *n, d *ap, d *rcond, d *work, int *iwork, int *info) noexcept nogil +cdef void dtpmqrt(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, d *v, int *ldv, d *t, int *ldt, d *a, int *lda, d *b, int *ldb, d *work, int *info) noexcept nogil +cdef void dtpqrt(int *m, int *n, int *l, int *nb, d *a, int *lda, d *b, int *ldb, d *t, int *ldt, d *work, int *info) noexcept nogil +cdef void dtpqrt2(int *m, int *n, int *l, d *a, int *lda, d *b, int *ldb, d *t, int *ldt, int *info) noexcept nogil +cdef void dtprfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, d *v, int *ldv, d *t, int *ldt, d *a, int *lda, d *b, int *ldb, d *work, int *ldwork) noexcept nogil +cdef void dtprfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *ap, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil +cdef void dtptri(char *uplo, char *diag, int *n, d *ap, int *info) noexcept nogil +cdef void dtptrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *ap, d *b, int *ldb, int *info) noexcept nogil +cdef void dtpttf(char *transr, char *uplo, int *n, d *ap, d *arf, int *info) noexcept nogil +cdef void dtpttr(char *uplo, int *n, d *ap, d *a, int *lda, int *info) noexcept nogil +cdef void dtrcon(char *norm, char *uplo, char *diag, int *n, d *a, int *lda, d *rcond, d *work, int *iwork, int *info) noexcept nogil +cdef void dtrevc(char *side, char *howmny, bint *select, int *n, d *t, int *ldt, d *vl, int *ldvl, d *vr, int *ldvr, int *mm, int *m, d *work, int *info) noexcept nogil +cdef void dtrexc(char *compq, int *n, d *t, int *ldt, d *q, int *ldq, int *ifst, int *ilst, d *work, int *info) noexcept nogil +cdef void dtrrfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil +cdef void dtrsen(char *job, char *compq, bint *select, int *n, d *t, int *ldt, d *q, int *ldq, d *wr, d *wi, int *m, d *s, d *sep, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void dtrsna(char *job, char *howmny, bint *select, int *n, d *t, int *ldt, d *vl, int *ldvl, d *vr, int *ldvr, d *s, d *sep, int *mm, int *m, d *work, int *ldwork, int *iwork, int *info) noexcept nogil +cdef void dtrsyl(char *trana, char *tranb, int *isgn, int *m, int *n, d *a, int *lda, d *b, int *ldb, d *c, int *ldc, d *scale, int *info) noexcept nogil +cdef void dtrti2(char *uplo, char *diag, int *n, d *a, int *lda, int *info) noexcept nogil +cdef void dtrtri(char *uplo, char *diag, int *n, d *a, int *lda, int *info) noexcept nogil +cdef void dtrtrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *info) noexcept nogil +cdef void dtrttf(char *transr, char *uplo, int *n, d *a, int *lda, d *arf, int *info) noexcept nogil +cdef void dtrttp(char *uplo, int *n, d *a, int *lda, d *ap, int *info) noexcept nogil +cdef void dtzrzf(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil +cdef d dzsum1(int *n, z *cx, int *incx) noexcept nogil +cdef int icmax1(int *n, c *cx, int *incx) noexcept nogil +cdef int ieeeck(int *ispec, s *zero, s *one) noexcept nogil +cdef int ilaclc(int *m, int *n, c *a, int *lda) noexcept nogil +cdef int ilaclr(int *m, int *n, c *a, int *lda) noexcept nogil +cdef int iladiag(char *diag) noexcept nogil +cdef int iladlc(int *m, int *n, d *a, int *lda) noexcept nogil +cdef int iladlr(int *m, int *n, d *a, int *lda) noexcept nogil +cdef int ilaprec(char *prec) noexcept nogil +cdef int ilaslc(int *m, int *n, s *a, int *lda) noexcept nogil +cdef int ilaslr(int *m, int *n, s *a, int *lda) noexcept nogil +cdef int ilatrans(char *trans) noexcept nogil +cdef int ilauplo(char *uplo) noexcept nogil +cdef void ilaver(int *vers_major, int *vers_minor, int *vers_patch) noexcept nogil +cdef int ilazlc(int *m, int *n, z *a, int *lda) noexcept nogil +cdef int ilazlr(int *m, int *n, z *a, int *lda) noexcept nogil +cdef int izmax1(int *n, z *cx, int *incx) noexcept nogil +cdef void sbbcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, s *theta, s *phi, s *u1, int *ldu1, s *u2, int *ldu2, s *v1t, int *ldv1t, s *v2t, int *ldv2t, s *b11d, s *b11e, s *b12d, s *b12e, s *b21d, s *b21e, s *b22d, s *b22e, s *work, int *lwork, int *info) noexcept nogil +cdef void sbdsdc(char *uplo, char *compq, int *n, s *d, s *e, s *u, int *ldu, s *vt, int *ldvt, s *q, int *iq, s *work, int *iwork, int *info) noexcept nogil +cdef void sbdsqr(char *uplo, int *n, int *ncvt, int *nru, int *ncc, s *d, s *e, s *vt, int *ldvt, s *u, int *ldu, s *c, int *ldc, s *work, int *info) noexcept nogil +cdef s scsum1(int *n, c *cx, int *incx) noexcept nogil +cdef void sdisna(char *job, int *m, int *n, s *d, s *sep, int *info) noexcept nogil +cdef void sgbbrd(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, s *ab, int *ldab, s *d, s *e, s *q, int *ldq, s *pt, int *ldpt, s *c, int *ldc, s *work, int *info) noexcept nogil +cdef void sgbcon(char *norm, int *n, int *kl, int *ku, s *ab, int *ldab, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil +cdef void sgbequ(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil +cdef void sgbequb(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil +cdef void sgbrfs(char *trans, int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, s *afb, int *ldafb, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil +cdef void sgbsv(int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, int *ipiv, s *b, int *ldb, int *info) noexcept nogil +cdef void sgbsvx(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, s *afb, int *ldafb, int *ipiv, char *equed, s *r, s *c, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil +cdef void sgbtf2(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, int *ipiv, int *info) noexcept nogil +cdef void sgbtrf(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, int *ipiv, int *info) noexcept nogil +cdef void sgbtrs(char *trans, int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, int *ipiv, s *b, int *ldb, int *info) noexcept nogil +cdef void sgebak(char *job, char *side, int *n, int *ilo, int *ihi, s *scale, int *m, s *v, int *ldv, int *info) noexcept nogil +cdef void sgebal(char *job, int *n, s *a, int *lda, int *ilo, int *ihi, s *scale, int *info) noexcept nogil +cdef void sgebd2(int *m, int *n, s *a, int *lda, s *d, s *e, s *tauq, s *taup, s *work, int *info) noexcept nogil +cdef void sgebrd(int *m, int *n, s *a, int *lda, s *d, s *e, s *tauq, s *taup, s *work, int *lwork, int *info) noexcept nogil +cdef void sgecon(char *norm, int *n, s *a, int *lda, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil +cdef void sgeequ(int *m, int *n, s *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil +cdef void sgeequb(int *m, int *n, s *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil +cdef void sgees(char *jobvs, char *sort, sselect2 *select, int *n, s *a, int *lda, int *sdim, s *wr, s *wi, s *vs, int *ldvs, s *work, int *lwork, bint *bwork, int *info) noexcept nogil +cdef void sgeesx(char *jobvs, char *sort, sselect2 *select, char *sense, int *n, s *a, int *lda, int *sdim, s *wr, s *wi, s *vs, int *ldvs, s *rconde, s *rcondv, s *work, int *lwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil +cdef void sgeev(char *jobvl, char *jobvr, int *n, s *a, int *lda, s *wr, s *wi, s *vl, int *ldvl, s *vr, int *ldvr, s *work, int *lwork, int *info) noexcept nogil +cdef void sgeevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, s *a, int *lda, s *wr, s *wi, s *vl, int *ldvl, s *vr, int *ldvr, int *ilo, int *ihi, s *scale, s *abnrm, s *rconde, s *rcondv, s *work, int *lwork, int *iwork, int *info) noexcept nogil +cdef void sgehd2(int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil +cdef void sgehrd(int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil +cdef void sgejsv(char *joba, char *jobu, char *jobv, char *jobr, char *jobt, char *jobp, int *m, int *n, s *a, int *lda, s *sva, s *u, int *ldu, s *v, int *ldv, s *work, int *lwork, int *iwork, int *info) noexcept nogil +cdef void sgelq2(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil +cdef void sgelqf(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil +cdef void sgels(char *trans, int *m, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, s *work, int *lwork, int *info) noexcept nogil +cdef void sgelsd(int *m, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, s *s, s *rcond, int *rank, s *work, int *lwork, int *iwork, int *info) noexcept nogil +cdef void sgelss(int *m, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, s *s, s *rcond, int *rank, s *work, int *lwork, int *info) noexcept nogil +cdef void sgelsy(int *m, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *jpvt, s *rcond, int *rank, s *work, int *lwork, int *info) noexcept nogil +cdef void sgemqrt(char *side, char *trans, int *m, int *n, int *k, int *nb, s *v, int *ldv, s *t, int *ldt, s *c, int *ldc, s *work, int *info) noexcept nogil +cdef void sgeql2(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil +cdef void sgeqlf(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil +cdef void sgeqp3(int *m, int *n, s *a, int *lda, int *jpvt, s *tau, s *work, int *lwork, int *info) noexcept nogil +cdef void sgeqr2(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil +cdef void sgeqr2p(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil +cdef void sgeqrf(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil +cdef void sgeqrfp(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil +cdef void sgeqrt(int *m, int *n, int *nb, s *a, int *lda, s *t, int *ldt, s *work, int *info) noexcept nogil +cdef void sgeqrt2(int *m, int *n, s *a, int *lda, s *t, int *ldt, int *info) noexcept nogil +cdef void sgeqrt3(int *m, int *n, s *a, int *lda, s *t, int *ldt, int *info) noexcept nogil +cdef void sgerfs(char *trans, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil +cdef void sgerq2(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil +cdef void sgerqf(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil +cdef void sgesc2(int *n, s *a, int *lda, s *rhs, int *ipiv, int *jpiv, s *scale) noexcept nogil +cdef void sgesdd(char *jobz, int *m, int *n, s *a, int *lda, s *s, s *u, int *ldu, s *vt, int *ldvt, s *work, int *lwork, int *iwork, int *info) noexcept nogil +cdef void sgesv(int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, int *info) noexcept nogil +cdef void sgesvd(char *jobu, char *jobvt, int *m, int *n, s *a, int *lda, s *s, s *u, int *ldu, s *vt, int *ldvt, s *work, int *lwork, int *info) noexcept nogil +cdef void sgesvj(char *joba, char *jobu, char *jobv, int *m, int *n, s *a, int *lda, s *sva, int *mv, s *v, int *ldv, s *work, int *lwork, int *info) noexcept nogil +cdef void sgesvx(char *fact, char *trans, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, int *ipiv, char *equed, s *r, s *c, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil +cdef void sgetc2(int *n, s *a, int *lda, int *ipiv, int *jpiv, int *info) noexcept nogil +cdef void sgetf2(int *m, int *n, s *a, int *lda, int *ipiv, int *info) noexcept nogil +cdef void sgetrf(int *m, int *n, s *a, int *lda, int *ipiv, int *info) noexcept nogil +cdef void sgetri(int *n, s *a, int *lda, int *ipiv, s *work, int *lwork, int *info) noexcept nogil +cdef void sgetrs(char *trans, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, int *info) noexcept nogil +cdef void sggbak(char *job, char *side, int *n, int *ilo, int *ihi, s *lscale, s *rscale, int *m, s *v, int *ldv, int *info) noexcept nogil +cdef void sggbal(char *job, int *n, s *a, int *lda, s *b, int *ldb, int *ilo, int *ihi, s *lscale, s *rscale, s *work, int *info) noexcept nogil +cdef void sgges(char *jobvsl, char *jobvsr, char *sort, sselect3 *selctg, int *n, s *a, int *lda, s *b, int *ldb, int *sdim, s *alphar, s *alphai, s *beta, s *vsl, int *ldvsl, s *vsr, int *ldvsr, s *work, int *lwork, bint *bwork, int *info) noexcept nogil +cdef void sggesx(char *jobvsl, char *jobvsr, char *sort, sselect3 *selctg, char *sense, int *n, s *a, int *lda, s *b, int *ldb, int *sdim, s *alphar, s *alphai, s *beta, s *vsl, int *ldvsl, s *vsr, int *ldvsr, s *rconde, s *rcondv, s *work, int *lwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil +cdef void sggev(char *jobvl, char *jobvr, int *n, s *a, int *lda, s *b, int *ldb, s *alphar, s *alphai, s *beta, s *vl, int *ldvl, s *vr, int *ldvr, s *work, int *lwork, int *info) noexcept nogil +cdef void sggevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, s *a, int *lda, s *b, int *ldb, s *alphar, s *alphai, s *beta, s *vl, int *ldvl, s *vr, int *ldvr, int *ilo, int *ihi, s *lscale, s *rscale, s *abnrm, s *bbnrm, s *rconde, s *rcondv, s *work, int *lwork, int *iwork, bint *bwork, int *info) noexcept nogil +cdef void sggglm(int *n, int *m, int *p, s *a, int *lda, s *b, int *ldb, s *d, s *x, s *y, s *work, int *lwork, int *info) noexcept nogil +cdef void sgghrd(char *compq, char *compz, int *n, int *ilo, int *ihi, s *a, int *lda, s *b, int *ldb, s *q, int *ldq, s *z, int *ldz, int *info) noexcept nogil +cdef void sgglse(int *m, int *n, int *p, s *a, int *lda, s *b, int *ldb, s *c, s *d, s *x, s *work, int *lwork, int *info) noexcept nogil +cdef void sggqrf(int *n, int *m, int *p, s *a, int *lda, s *taua, s *b, int *ldb, s *taub, s *work, int *lwork, int *info) noexcept nogil +cdef void sggrqf(int *m, int *p, int *n, s *a, int *lda, s *taua, s *b, int *ldb, s *taub, s *work, int *lwork, int *info) noexcept nogil +cdef void sgsvj0(char *jobv, int *m, int *n, s *a, int *lda, s *d, s *sva, int *mv, s *v, int *ldv, s *eps, s *sfmin, s *tol, int *nsweep, s *work, int *lwork, int *info) noexcept nogil +cdef void sgsvj1(char *jobv, int *m, int *n, int *n1, s *a, int *lda, s *d, s *sva, int *mv, s *v, int *ldv, s *eps, s *sfmin, s *tol, int *nsweep, s *work, int *lwork, int *info) noexcept nogil +cdef void sgtcon(char *norm, int *n, s *dl, s *d, s *du, s *du2, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil +cdef void sgtrfs(char *trans, int *n, int *nrhs, s *dl, s *d, s *du, s *dlf, s *df, s *duf, s *du2, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil +cdef void sgtsv(int *n, int *nrhs, s *dl, s *d, s *du, s *b, int *ldb, int *info) noexcept nogil +cdef void sgtsvx(char *fact, char *trans, int *n, int *nrhs, s *dl, s *d, s *du, s *dlf, s *df, s *duf, s *du2, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil +cdef void sgttrf(int *n, s *dl, s *d, s *du, s *du2, int *ipiv, int *info) noexcept nogil +cdef void sgttrs(char *trans, int *n, int *nrhs, s *dl, s *d, s *du, s *du2, int *ipiv, s *b, int *ldb, int *info) noexcept nogil +cdef void sgtts2(int *itrans, int *n, int *nrhs, s *dl, s *d, s *du, s *du2, int *ipiv, s *b, int *ldb) noexcept nogil +cdef void shgeqz(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *t, int *ldt, s *alphar, s *alphai, s *beta, s *q, int *ldq, s *z, int *ldz, s *work, int *lwork, int *info) noexcept nogil +cdef void shsein(char *side, char *eigsrc, char *initv, bint *select, int *n, s *h, int *ldh, s *wr, s *wi, s *vl, int *ldvl, s *vr, int *ldvr, int *mm, int *m, s *work, int *ifaill, int *ifailr, int *info) noexcept nogil +cdef void shseqr(char *job, char *compz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *wr, s *wi, s *z, int *ldz, s *work, int *lwork, int *info) noexcept nogil +cdef void slabad(s *small, s *large) noexcept nogil +cdef void slabrd(int *m, int *n, int *nb, s *a, int *lda, s *d, s *e, s *tauq, s *taup, s *x, int *ldx, s *y, int *ldy) noexcept nogil +cdef void slacn2(int *n, s *v, s *x, int *isgn, s *est, int *kase, int *isave) noexcept nogil +cdef void slacon(int *n, s *v, s *x, int *isgn, s *est, int *kase) noexcept nogil +cdef void slacpy(char *uplo, int *m, int *n, s *a, int *lda, s *b, int *ldb) noexcept nogil +cdef void sladiv(s *a, s *b, s *c, s *d, s *p, s *q) noexcept nogil +cdef void slae2(s *a, s *b, s *c, s *rt1, s *rt2) noexcept nogil +cdef void slaebz(int *ijob, int *nitmax, int *n, int *mmax, int *minp, int *nbmin, s *abstol, s *reltol, s *pivmin, s *d, s *e, s *e2, int *nval, s *ab, s *c, int *mout, int *nab, s *work, int *iwork, int *info) noexcept nogil +cdef void slaed0(int *icompq, int *qsiz, int *n, s *d, s *e, s *q, int *ldq, s *qstore, int *ldqs, s *work, int *iwork, int *info) noexcept nogil +cdef void slaed1(int *n, s *d, s *q, int *ldq, int *indxq, s *rho, int *cutpnt, s *work, int *iwork, int *info) noexcept nogil +cdef void slaed2(int *k, int *n, int *n1, s *d, s *q, int *ldq, int *indxq, s *rho, s *z, s *dlamda, s *w, s *q2, int *indx, int *indxc, int *indxp, int *coltyp, int *info) noexcept nogil +cdef void slaed3(int *k, int *n, int *n1, s *d, s *q, int *ldq, s *rho, s *dlamda, s *q2, int *indx, int *ctot, s *w, s *s, int *info) noexcept nogil +cdef void slaed4(int *n, int *i, s *d, s *z, s *delta, s *rho, s *dlam, int *info) noexcept nogil +cdef void slaed5(int *i, s *d, s *z, s *delta, s *rho, s *dlam) noexcept nogil +cdef void slaed6(int *kniter, bint *orgati, s *rho, s *d, s *z, s *finit, s *tau, int *info) noexcept nogil +cdef void slaed7(int *icompq, int *n, int *qsiz, int *tlvls, int *curlvl, int *curpbm, s *d, s *q, int *ldq, int *indxq, s *rho, int *cutpnt, s *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, s *givnum, s *work, int *iwork, int *info) noexcept nogil +cdef void slaed8(int *icompq, int *k, int *n, int *qsiz, s *d, s *q, int *ldq, int *indxq, s *rho, int *cutpnt, s *z, s *dlamda, s *q2, int *ldq2, s *w, int *perm, int *givptr, int *givcol, s *givnum, int *indxp, int *indx, int *info) noexcept nogil +cdef void slaed9(int *k, int *kstart, int *kstop, int *n, s *d, s *q, int *ldq, s *rho, s *dlamda, s *w, s *s, int *lds, int *info) noexcept nogil +cdef void slaeda(int *n, int *tlvls, int *curlvl, int *curpbm, int *prmptr, int *perm, int *givptr, int *givcol, s *givnum, s *q, int *qptr, s *z, s *ztemp, int *info) noexcept nogil +cdef void slaein(bint *rightv, bint *noinit, int *n, s *h, int *ldh, s *wr, s *wi, s *vr, s *vi, s *b, int *ldb, s *work, s *eps3, s *smlnum, s *bignum, int *info) noexcept nogil +cdef void slaev2(s *a, s *b, s *c, s *rt1, s *rt2, s *cs1, s *sn1) noexcept nogil +cdef void slaexc(bint *wantq, int *n, s *t, int *ldt, s *q, int *ldq, int *j1, int *n1, int *n2, s *work, int *info) noexcept nogil +cdef void slag2(s *a, int *lda, s *b, int *ldb, s *safmin, s *scale1, s *scale2, s *wr1, s *wr2, s *wi) noexcept nogil +cdef void slag2d(int *m, int *n, s *sa, int *ldsa, d *a, int *lda, int *info) noexcept nogil +cdef void slags2(bint *upper, s *a1, s *a2, s *a3, s *b1, s *b2, s *b3, s *csu, s *snu, s *csv, s *snv, s *csq, s *snq) noexcept nogil +cdef void slagtf(int *n, s *a, s *lambda_, s *b, s *c, s *tol, s *d, int *in_, int *info) noexcept nogil +cdef void slagtm(char *trans, int *n, int *nrhs, s *alpha, s *dl, s *d, s *du, s *x, int *ldx, s *beta, s *b, int *ldb) noexcept nogil +cdef void slagts(int *job, int *n, s *a, s *b, s *c, s *d, int *in_, s *y, s *tol, int *info) noexcept nogil +cdef void slagv2(s *a, int *lda, s *b, int *ldb, s *alphar, s *alphai, s *beta, s *csl, s *snl, s *csr, s *snr) noexcept nogil +cdef void slahqr(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *wr, s *wi, int *iloz, int *ihiz, s *z, int *ldz, int *info) noexcept nogil +cdef void slahr2(int *n, int *k, int *nb, s *a, int *lda, s *tau, s *t, int *ldt, s *y, int *ldy) noexcept nogil +cdef void slaic1(int *job, int *j, s *x, s *sest, s *w, s *gamma, s *sestpr, s *s, s *c) noexcept nogil +cdef void slaln2(bint *ltrans, int *na, int *nw, s *smin, s *ca, s *a, int *lda, s *d1, s *d2, s *b, int *ldb, s *wr, s *wi, s *x, int *ldx, s *scale, s *xnorm, int *info) noexcept nogil +cdef void slals0(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, s *b, int *ldb, s *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, s *givnum, int *ldgnum, s *poles, s *difl, s *difr, s *z, int *k, s *c, s *s, s *work, int *info) noexcept nogil +cdef void slalsa(int *icompq, int *smlsiz, int *n, int *nrhs, s *b, int *ldb, s *bx, int *ldbx, s *u, int *ldu, s *vt, int *k, s *difl, s *difr, s *z, s *poles, int *givptr, int *givcol, int *ldgcol, int *perm, s *givnum, s *c, s *s, s *work, int *iwork, int *info) noexcept nogil +cdef void slalsd(char *uplo, int *smlsiz, int *n, int *nrhs, s *d, s *e, s *b, int *ldb, s *rcond, int *rank, s *work, int *iwork, int *info) noexcept nogil +cdef s slamch(char *cmach) noexcept nogil +cdef void slamrg(int *n1, int *n2, s *a, int *strd1, int *strd2, int *index_bn) noexcept nogil +cdef s slangb(char *norm, int *n, int *kl, int *ku, s *ab, int *ldab, s *work) noexcept nogil +cdef s slange(char *norm, int *m, int *n, s *a, int *lda, s *work) noexcept nogil +cdef s slangt(char *norm, int *n, s *dl, s *d, s *du) noexcept nogil +cdef s slanhs(char *norm, int *n, s *a, int *lda, s *work) noexcept nogil +cdef s slansb(char *norm, char *uplo, int *n, int *k, s *ab, int *ldab, s *work) noexcept nogil +cdef s slansf(char *norm, char *transr, char *uplo, int *n, s *a, s *work) noexcept nogil +cdef s slansp(char *norm, char *uplo, int *n, s *ap, s *work) noexcept nogil +cdef s slanst(char *norm, int *n, s *d, s *e) noexcept nogil +cdef s slansy(char *norm, char *uplo, int *n, s *a, int *lda, s *work) noexcept nogil +cdef s slantb(char *norm, char *uplo, char *diag, int *n, int *k, s *ab, int *ldab, s *work) noexcept nogil +cdef s slantp(char *norm, char *uplo, char *diag, int *n, s *ap, s *work) noexcept nogil +cdef s slantr(char *norm, char *uplo, char *diag, int *m, int *n, s *a, int *lda, s *work) noexcept nogil +cdef void slanv2(s *a, s *b, s *c, s *d, s *rt1r, s *rt1i, s *rt2r, s *rt2i, s *cs, s *sn) noexcept nogil +cdef void slapll(int *n, s *x, int *incx, s *y, int *incy, s *ssmin) noexcept nogil +cdef void slapmr(bint *forwrd, int *m, int *n, s *x, int *ldx, int *k) noexcept nogil +cdef void slapmt(bint *forwrd, int *m, int *n, s *x, int *ldx, int *k) noexcept nogil +cdef s slapy2(s *x, s *y) noexcept nogil +cdef s slapy3(s *x, s *y, s *z) noexcept nogil +cdef void slaqgb(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) noexcept nogil +cdef void slaqge(int *m, int *n, s *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) noexcept nogil +cdef void slaqp2(int *m, int *n, int *offset, s *a, int *lda, int *jpvt, s *tau, s *vn1, s *vn2, s *work) noexcept nogil +cdef void slaqps(int *m, int *n, int *offset, int *nb, int *kb, s *a, int *lda, int *jpvt, s *tau, s *vn1, s *vn2, s *auxv, s *f, int *ldf) noexcept nogil +cdef void slaqr0(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *wr, s *wi, int *iloz, int *ihiz, s *z, int *ldz, s *work, int *lwork, int *info) noexcept nogil +cdef void slaqr1(int *n, s *h, int *ldh, s *sr1, s *si1, s *sr2, s *si2, s *v) noexcept nogil +cdef void slaqr2(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, s *h, int *ldh, int *iloz, int *ihiz, s *z, int *ldz, int *ns, int *nd, s *sr, s *si, s *v, int *ldv, int *nh, s *t, int *ldt, int *nv, s *wv, int *ldwv, s *work, int *lwork) noexcept nogil +cdef void slaqr3(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, s *h, int *ldh, int *iloz, int *ihiz, s *z, int *ldz, int *ns, int *nd, s *sr, s *si, s *v, int *ldv, int *nh, s *t, int *ldt, int *nv, s *wv, int *ldwv, s *work, int *lwork) noexcept nogil +cdef void slaqr4(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *wr, s *wi, int *iloz, int *ihiz, s *z, int *ldz, s *work, int *lwork, int *info) noexcept nogil +cdef void slaqr5(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, s *sr, s *si, s *h, int *ldh, int *iloz, int *ihiz, s *z, int *ldz, s *v, int *ldv, s *u, int *ldu, int *nv, s *wv, int *ldwv, int *nh, s *wh, int *ldwh) noexcept nogil +cdef void slaqsb(char *uplo, int *n, int *kd, s *ab, int *ldab, s *s, s *scond, s *amax, char *equed) noexcept nogil +cdef void slaqsp(char *uplo, int *n, s *ap, s *s, s *scond, s *amax, char *equed) noexcept nogil +cdef void slaqsy(char *uplo, int *n, s *a, int *lda, s *s, s *scond, s *amax, char *equed) noexcept nogil +cdef void slaqtr(bint *ltran, bint *lreal, int *n, s *t, int *ldt, s *b, s *w, s *scale, s *x, s *work, int *info) noexcept nogil +cdef void slar1v(int *n, int *b1, int *bn, s *lambda_, s *d, s *l, s *ld, s *lld, s *pivmin, s *gaptol, s *z, bint *wantnc, int *negcnt, s *ztz, s *mingma, int *r, int *isuppz, s *nrminv, s *resid, s *rqcorr, s *work) noexcept nogil +cdef void slar2v(int *n, s *x, s *y, s *z, int *incx, s *c, s *s, int *incc) noexcept nogil +cdef void slarf(char *side, int *m, int *n, s *v, int *incv, s *tau, s *c, int *ldc, s *work) noexcept nogil +cdef void slarfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, s *v, int *ldv, s *t, int *ldt, s *c, int *ldc, s *work, int *ldwork) noexcept nogil +cdef void slarfg(int *n, s *alpha, s *x, int *incx, s *tau) noexcept nogil +cdef void slarfgp(int *n, s *alpha, s *x, int *incx, s *tau) noexcept nogil +cdef void slarft(char *direct, char *storev, int *n, int *k, s *v, int *ldv, s *tau, s *t, int *ldt) noexcept nogil +cdef void slarfx(char *side, int *m, int *n, s *v, s *tau, s *c, int *ldc, s *work) noexcept nogil +cdef void slargv(int *n, s *x, int *incx, s *y, int *incy, s *c, int *incc) noexcept nogil +cdef void slarnv(int *idist, int *iseed, int *n, s *x) noexcept nogil +cdef void slarra(int *n, s *d, s *e, s *e2, s *spltol, s *tnrm, int *nsplit, int *isplit, int *info) noexcept nogil +cdef void slarrb(int *n, s *d, s *lld, int *ifirst, int *ilast, s *rtol1, s *rtol2, int *offset, s *w, s *wgap, s *werr, s *work, int *iwork, s *pivmin, s *spdiam, int *twist, int *info) noexcept nogil +cdef void slarrc(char *jobt, int *n, s *vl, s *vu, s *d, s *e, s *pivmin, int *eigcnt, int *lcnt, int *rcnt, int *info) noexcept nogil +cdef void slarrd(char *range, char *order, int *n, s *vl, s *vu, int *il, int *iu, s *gers, s *reltol, s *d, s *e, s *e2, s *pivmin, int *nsplit, int *isplit, int *m, s *w, s *werr, s *wl, s *wu, int *iblock, int *indexw, s *work, int *iwork, int *info) noexcept nogil +cdef void slarre(char *range, int *n, s *vl, s *vu, int *il, int *iu, s *d, s *e, s *e2, s *rtol1, s *rtol2, s *spltol, int *nsplit, int *isplit, int *m, s *w, s *werr, s *wgap, int *iblock, int *indexw, s *gers, s *pivmin, s *work, int *iwork, int *info) noexcept nogil +cdef void slarrf(int *n, s *d, s *l, s *ld, int *clstrt, int *clend, s *w, s *wgap, s *werr, s *spdiam, s *clgapl, s *clgapr, s *pivmin, s *sigma, s *dplus, s *lplus, s *work, int *info) noexcept nogil +cdef void slarrj(int *n, s *d, s *e2, int *ifirst, int *ilast, s *rtol, int *offset, s *w, s *werr, s *work, int *iwork, s *pivmin, s *spdiam, int *info) noexcept nogil +cdef void slarrk(int *n, int *iw, s *gl, s *gu, s *d, s *e2, s *pivmin, s *reltol, s *w, s *werr, int *info) noexcept nogil +cdef void slarrr(int *n, s *d, s *e, int *info) noexcept nogil +cdef void slarrv(int *n, s *vl, s *vu, s *d, s *l, s *pivmin, int *isplit, int *m, int *dol, int *dou, s *minrgp, s *rtol1, s *rtol2, s *w, s *werr, s *wgap, int *iblock, int *indexw, s *gers, s *z, int *ldz, int *isuppz, s *work, int *iwork, int *info) noexcept nogil +cdef void slartg(s *f, s *g, s *cs, s *sn, s *r) noexcept nogil +cdef void slartgp(s *f, s *g, s *cs, s *sn, s *r) noexcept nogil +cdef void slartgs(s *x, s *y, s *sigma, s *cs, s *sn) noexcept nogil +cdef void slartv(int *n, s *x, int *incx, s *y, int *incy, s *c, s *s, int *incc) noexcept nogil +cdef void slaruv(int *iseed, int *n, s *x) noexcept nogil +cdef void slarz(char *side, int *m, int *n, int *l, s *v, int *incv, s *tau, s *c, int *ldc, s *work) noexcept nogil +cdef void slarzb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, s *v, int *ldv, s *t, int *ldt, s *c, int *ldc, s *work, int *ldwork) noexcept nogil +cdef void slarzt(char *direct, char *storev, int *n, int *k, s *v, int *ldv, s *tau, s *t, int *ldt) noexcept nogil +cdef void slas2(s *f, s *g, s *h, s *ssmin, s *ssmax) noexcept nogil +cdef void slascl(char *type_bn, int *kl, int *ku, s *cfrom, s *cto, int *m, int *n, s *a, int *lda, int *info) noexcept nogil +cdef void slasd0(int *n, int *sqre, s *d, s *e, s *u, int *ldu, s *vt, int *ldvt, int *smlsiz, int *iwork, s *work, int *info) noexcept nogil +cdef void slasd1(int *nl, int *nr, int *sqre, s *d, s *alpha, s *beta, s *u, int *ldu, s *vt, int *ldvt, int *idxq, int *iwork, s *work, int *info) noexcept nogil +cdef void slasd2(int *nl, int *nr, int *sqre, int *k, s *d, s *z, s *alpha, s *beta, s *u, int *ldu, s *vt, int *ldvt, s *dsigma, s *u2, int *ldu2, s *vt2, int *ldvt2, int *idxp, int *idx, int *idxc, int *idxq, int *coltyp, int *info) noexcept nogil +cdef void slasd3(int *nl, int *nr, int *sqre, int *k, s *d, s *q, int *ldq, s *dsigma, s *u, int *ldu, s *u2, int *ldu2, s *vt, int *ldvt, s *vt2, int *ldvt2, int *idxc, int *ctot, s *z, int *info) noexcept nogil +cdef void slasd4(int *n, int *i, s *d, s *z, s *delta, s *rho, s *sigma, s *work, int *info) noexcept nogil +cdef void slasd5(int *i, s *d, s *z, s *delta, s *rho, s *dsigma, s *work) noexcept nogil +cdef void slasd6(int *icompq, int *nl, int *nr, int *sqre, s *d, s *vf, s *vl, s *alpha, s *beta, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, s *givnum, int *ldgnum, s *poles, s *difl, s *difr, s *z, int *k, s *c, s *s, s *work, int *iwork, int *info) noexcept nogil +cdef void slasd7(int *icompq, int *nl, int *nr, int *sqre, int *k, s *d, s *z, s *zw, s *vf, s *vfw, s *vl, s *vlw, s *alpha, s *beta, s *dsigma, int *idx, int *idxp, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, s *givnum, int *ldgnum, s *c, s *s, int *info) noexcept nogil +cdef void slasd8(int *icompq, int *k, s *d, s *z, s *vf, s *vl, s *difl, s *difr, int *lddifr, s *dsigma, s *work, int *info) noexcept nogil +cdef void slasda(int *icompq, int *smlsiz, int *n, int *sqre, s *d, s *e, s *u, int *ldu, s *vt, int *k, s *difl, s *difr, s *z, s *poles, int *givptr, int *givcol, int *ldgcol, int *perm, s *givnum, s *c, s *s, s *work, int *iwork, int *info) noexcept nogil +cdef void slasdq(char *uplo, int *sqre, int *n, int *ncvt, int *nru, int *ncc, s *d, s *e, s *vt, int *ldvt, s *u, int *ldu, s *c, int *ldc, s *work, int *info) noexcept nogil +cdef void slasdt(int *n, int *lvl, int *nd, int *inode, int *ndiml, int *ndimr, int *msub) noexcept nogil +cdef void slaset(char *uplo, int *m, int *n, s *alpha, s *beta, s *a, int *lda) noexcept nogil +cdef void slasq1(int *n, s *d, s *e, s *work, int *info) noexcept nogil +cdef void slasq2(int *n, s *z, int *info) noexcept nogil +cdef void slasq3(int *i0, int *n0, s *z, int *pp, s *dmin, s *sigma, s *desig, s *qmax, int *nfail, int *iter, int *ndiv, bint *ieee, int *ttype, s *dmin1, s *dmin2, s *dn, s *dn1, s *dn2, s *g, s *tau) noexcept nogil +cdef void slasq4(int *i0, int *n0, s *z, int *pp, int *n0in, s *dmin, s *dmin1, s *dmin2, s *dn, s *dn1, s *dn2, s *tau, int *ttype, s *g) noexcept nogil +cdef void slasq6(int *i0, int *n0, s *z, int *pp, s *dmin, s *dmin1, s *dmin2, s *dn, s *dnm1, s *dnm2) noexcept nogil +cdef void slasr(char *side, char *pivot, char *direct, int *m, int *n, s *c, s *s, s *a, int *lda) noexcept nogil +cdef void slasrt(char *id, int *n, s *d, int *info) noexcept nogil +cdef void slassq(int *n, s *x, int *incx, s *scale, s *sumsq) noexcept nogil +cdef void slasv2(s *f, s *g, s *h, s *ssmin, s *ssmax, s *snr, s *csr, s *snl, s *csl) noexcept nogil +cdef void slaswp(int *n, s *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) noexcept nogil +cdef void slasy2(bint *ltranl, bint *ltranr, int *isgn, int *n1, int *n2, s *tl, int *ldtl, s *tr, int *ldtr, s *b, int *ldb, s *scale, s *x, int *ldx, s *xnorm, int *info) noexcept nogil +cdef void slasyf(char *uplo, int *n, int *nb, int *kb, s *a, int *lda, int *ipiv, s *w, int *ldw, int *info) noexcept nogil +cdef void slatbs(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, s *ab, int *ldab, s *x, s *scale, s *cnorm, int *info) noexcept nogil +cdef void slatdf(int *ijob, int *n, s *z, int *ldz, s *rhs, s *rdsum, s *rdscal, int *ipiv, int *jpiv) noexcept nogil +cdef void slatps(char *uplo, char *trans, char *diag, char *normin, int *n, s *ap, s *x, s *scale, s *cnorm, int *info) noexcept nogil +cdef void slatrd(char *uplo, int *n, int *nb, s *a, int *lda, s *e, s *tau, s *w, int *ldw) noexcept nogil +cdef void slatrs(char *uplo, char *trans, char *diag, char *normin, int *n, s *a, int *lda, s *x, s *scale, s *cnorm, int *info) noexcept nogil +cdef void slatrz(int *m, int *n, int *l, s *a, int *lda, s *tau, s *work) noexcept nogil +cdef void slauu2(char *uplo, int *n, s *a, int *lda, int *info) noexcept nogil +cdef void slauum(char *uplo, int *n, s *a, int *lda, int *info) noexcept nogil +cdef void sopgtr(char *uplo, int *n, s *ap, s *tau, s *q, int *ldq, s *work, int *info) noexcept nogil +cdef void sopmtr(char *side, char *uplo, char *trans, int *m, int *n, s *ap, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil +cdef void sorbdb(char *trans, char *signs, int *m, int *p, int *q, s *x11, int *ldx11, s *x12, int *ldx12, s *x21, int *ldx21, s *x22, int *ldx22, s *theta, s *phi, s *taup1, s *taup2, s *tauq1, s *tauq2, s *work, int *lwork, int *info) noexcept nogil +cdef void sorcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, s *x11, int *ldx11, s *x12, int *ldx12, s *x21, int *ldx21, s *x22, int *ldx22, s *theta, s *u1, int *ldu1, s *u2, int *ldu2, s *v1t, int *ldv1t, s *v2t, int *ldv2t, s *work, int *lwork, int *iwork, int *info) noexcept nogil +cdef void sorg2l(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil +cdef void sorg2r(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil +cdef void sorgbr(char *vect, int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil +cdef void sorghr(int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil +cdef void sorgl2(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil +cdef void sorglq(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil +cdef void sorgql(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil +cdef void sorgqr(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil +cdef void sorgr2(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil +cdef void sorgrq(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil +cdef void sorgtr(char *uplo, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil +cdef void sorm2l(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil +cdef void sorm2r(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil +cdef void sormbr(char *vect, char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil +cdef void sormhr(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil +cdef void sorml2(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil +cdef void sormlq(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil +cdef void sormql(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil +cdef void sormqr(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil +cdef void sormr2(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil +cdef void sormr3(char *side, char *trans, int *m, int *n, int *k, int *l, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil +cdef void sormrq(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil +cdef void sormrz(char *side, char *trans, int *m, int *n, int *k, int *l, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil +cdef void sormtr(char *side, char *uplo, char *trans, int *m, int *n, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil +cdef void spbcon(char *uplo, int *n, int *kd, s *ab, int *ldab, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil +cdef void spbequ(char *uplo, int *n, int *kd, s *ab, int *ldab, s *s, s *scond, s *amax, int *info) noexcept nogil +cdef void spbrfs(char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *afb, int *ldafb, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil +cdef void spbstf(char *uplo, int *n, int *kd, s *ab, int *ldab, int *info) noexcept nogil +cdef void spbsv(char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, int *info) noexcept nogil +cdef void spbsvx(char *fact, char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *afb, int *ldafb, char *equed, s *s, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil +cdef void spbtf2(char *uplo, int *n, int *kd, s *ab, int *ldab, int *info) noexcept nogil +cdef void spbtrf(char *uplo, int *n, int *kd, s *ab, int *ldab, int *info) noexcept nogil +cdef void spbtrs(char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, int *info) noexcept nogil +cdef void spftrf(char *transr, char *uplo, int *n, s *a, int *info) noexcept nogil +cdef void spftri(char *transr, char *uplo, int *n, s *a, int *info) noexcept nogil +cdef void spftrs(char *transr, char *uplo, int *n, int *nrhs, s *a, s *b, int *ldb, int *info) noexcept nogil +cdef void spocon(char *uplo, int *n, s *a, int *lda, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil +cdef void spoequ(int *n, s *a, int *lda, s *s, s *scond, s *amax, int *info) noexcept nogil +cdef void spoequb(int *n, s *a, int *lda, s *s, s *scond, s *amax, int *info) noexcept nogil +cdef void sporfs(char *uplo, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil +cdef void sposv(char *uplo, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *info) noexcept nogil +cdef void sposvx(char *fact, char *uplo, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, char *equed, s *s, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil +cdef void spotf2(char *uplo, int *n, s *a, int *lda, int *info) noexcept nogil +cdef void spotrf(char *uplo, int *n, s *a, int *lda, int *info) noexcept nogil +cdef void spotri(char *uplo, int *n, s *a, int *lda, int *info) noexcept nogil +cdef void spotrs(char *uplo, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *info) noexcept nogil +cdef void sppcon(char *uplo, int *n, s *ap, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil +cdef void sppequ(char *uplo, int *n, s *ap, s *s, s *scond, s *amax, int *info) noexcept nogil +cdef void spprfs(char *uplo, int *n, int *nrhs, s *ap, s *afp, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil +cdef void sppsv(char *uplo, int *n, int *nrhs, s *ap, s *b, int *ldb, int *info) noexcept nogil +cdef void sppsvx(char *fact, char *uplo, int *n, int *nrhs, s *ap, s *afp, char *equed, s *s, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil +cdef void spptrf(char *uplo, int *n, s *ap, int *info) noexcept nogil +cdef void spptri(char *uplo, int *n, s *ap, int *info) noexcept nogil +cdef void spptrs(char *uplo, int *n, int *nrhs, s *ap, s *b, int *ldb, int *info) noexcept nogil +cdef void spstf2(char *uplo, int *n, s *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) noexcept nogil +cdef void spstrf(char *uplo, int *n, s *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) noexcept nogil +cdef void sptcon(int *n, s *d, s *e, s *anorm, s *rcond, s *work, int *info) noexcept nogil +cdef void spteqr(char *compz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *info) noexcept nogil +cdef void sptrfs(int *n, int *nrhs, s *d, s *e, s *df, s *ef, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *info) noexcept nogil +cdef void sptsv(int *n, int *nrhs, s *d, s *e, s *b, int *ldb, int *info) noexcept nogil +cdef void sptsvx(char *fact, int *n, int *nrhs, s *d, s *e, s *df, s *ef, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *info) noexcept nogil +cdef void spttrf(int *n, s *d, s *e, int *info) noexcept nogil +cdef void spttrs(int *n, int *nrhs, s *d, s *e, s *b, int *ldb, int *info) noexcept nogil +cdef void sptts2(int *n, int *nrhs, s *d, s *e, s *b, int *ldb) noexcept nogil +cdef void srscl(int *n, s *sa, s *sx, int *incx) noexcept nogil +cdef void ssbev(char *jobz, char *uplo, int *n, int *kd, s *ab, int *ldab, s *w, s *z, int *ldz, s *work, int *info) noexcept nogil +cdef void ssbevd(char *jobz, char *uplo, int *n, int *kd, s *ab, int *ldab, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void ssbevx(char *jobz, char *range, char *uplo, int *n, int *kd, s *ab, int *ldab, s *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil +cdef void ssbgst(char *vect, char *uplo, int *n, int *ka, int *kb, s *ab, int *ldab, s *bb, int *ldbb, s *x, int *ldx, s *work, int *info) noexcept nogil +cdef void ssbgv(char *jobz, char *uplo, int *n, int *ka, int *kb, s *ab, int *ldab, s *bb, int *ldbb, s *w, s *z, int *ldz, s *work, int *info) noexcept nogil +cdef void ssbgvd(char *jobz, char *uplo, int *n, int *ka, int *kb, s *ab, int *ldab, s *bb, int *ldbb, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void ssbgvx(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, s *ab, int *ldab, s *bb, int *ldbb, s *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil +cdef void ssbtrd(char *vect, char *uplo, int *n, int *kd, s *ab, int *ldab, s *d, s *e, s *q, int *ldq, s *work, int *info) noexcept nogil +cdef void ssfrk(char *transr, char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *beta, s *c) noexcept nogil +cdef void sspcon(char *uplo, int *n, s *ap, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil +cdef void sspev(char *jobz, char *uplo, int *n, s *ap, s *w, s *z, int *ldz, s *work, int *info) noexcept nogil +cdef void sspevd(char *jobz, char *uplo, int *n, s *ap, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void sspevx(char *jobz, char *range, char *uplo, int *n, s *ap, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil +cdef void sspgst(int *itype, char *uplo, int *n, s *ap, s *bp, int *info) noexcept nogil +cdef void sspgv(int *itype, char *jobz, char *uplo, int *n, s *ap, s *bp, s *w, s *z, int *ldz, s *work, int *info) noexcept nogil +cdef void sspgvd(int *itype, char *jobz, char *uplo, int *n, s *ap, s *bp, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void sspgvx(int *itype, char *jobz, char *range, char *uplo, int *n, s *ap, s *bp, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil +cdef void ssprfs(char *uplo, int *n, int *nrhs, s *ap, s *afp, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil +cdef void sspsv(char *uplo, int *n, int *nrhs, s *ap, int *ipiv, s *b, int *ldb, int *info) noexcept nogil +cdef void sspsvx(char *fact, char *uplo, int *n, int *nrhs, s *ap, s *afp, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil +cdef void ssptrd(char *uplo, int *n, s *ap, s *d, s *e, s *tau, int *info) noexcept nogil +cdef void ssptrf(char *uplo, int *n, s *ap, int *ipiv, int *info) noexcept nogil +cdef void ssptri(char *uplo, int *n, s *ap, int *ipiv, s *work, int *info) noexcept nogil +cdef void ssptrs(char *uplo, int *n, int *nrhs, s *ap, int *ipiv, s *b, int *ldb, int *info) noexcept nogil +cdef void sstebz(char *range, char *order, int *n, s *vl, s *vu, int *il, int *iu, s *abstol, s *d, s *e, int *m, int *nsplit, s *w, int *iblock, int *isplit, s *work, int *iwork, int *info) noexcept nogil +cdef void sstedc(char *compz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void sstegr(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, int *isuppz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void sstein(int *n, s *d, s *e, int *m, s *w, int *iblock, int *isplit, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil +cdef void sstemr(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, int *m, s *w, s *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void ssteqr(char *compz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *info) noexcept nogil +cdef void ssterf(int *n, s *d, s *e, int *info) noexcept nogil +cdef void sstev(char *jobz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *info) noexcept nogil +cdef void sstevd(char *jobz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void sstevr(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, int *isuppz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void sstevx(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil +cdef void ssycon(char *uplo, int *n, s *a, int *lda, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil +cdef void ssyconv(char *uplo, char *way, int *n, s *a, int *lda, int *ipiv, s *work, int *info) noexcept nogil +cdef void ssyequb(char *uplo, int *n, s *a, int *lda, s *s, s *scond, s *amax, s *work, int *info) noexcept nogil +cdef void ssyev(char *jobz, char *uplo, int *n, s *a, int *lda, s *w, s *work, int *lwork, int *info) noexcept nogil +cdef void ssyevd(char *jobz, char *uplo, int *n, s *a, int *lda, s *w, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void ssyevr(char *jobz, char *range, char *uplo, int *n, s *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, int *isuppz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void ssyevx(char *jobz, char *range, char *uplo, int *n, s *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *ifail, int *info) noexcept nogil +cdef void ssygs2(int *itype, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, int *info) noexcept nogil +cdef void ssygst(int *itype, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, int *info) noexcept nogil +cdef void ssygv(int *itype, char *jobz, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, s *w, s *work, int *lwork, int *info) noexcept nogil +cdef void ssygvd(int *itype, char *jobz, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, s *w, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void ssygvx(int *itype, char *jobz, char *range, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *ifail, int *info) noexcept nogil +cdef void ssyrfs(char *uplo, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil +cdef void ssysv(char *uplo, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, s *work, int *lwork, int *info) noexcept nogil +cdef void ssysvx(char *fact, char *uplo, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *lwork, int *iwork, int *info) noexcept nogil +cdef void ssyswapr(char *uplo, int *n, s *a, int *lda, int *i1, int *i2) noexcept nogil +cdef void ssytd2(char *uplo, int *n, s *a, int *lda, s *d, s *e, s *tau, int *info) noexcept nogil +cdef void ssytf2(char *uplo, int *n, s *a, int *lda, int *ipiv, int *info) noexcept nogil +cdef void ssytrd(char *uplo, int *n, s *a, int *lda, s *d, s *e, s *tau, s *work, int *lwork, int *info) noexcept nogil +cdef void ssytrf(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *lwork, int *info) noexcept nogil +cdef void ssytri(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *info) noexcept nogil +cdef void ssytri2(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *lwork, int *info) noexcept nogil +cdef void ssytri2x(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *nb, int *info) noexcept nogil +cdef void ssytrs(char *uplo, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, int *info) noexcept nogil +cdef void ssytrs2(char *uplo, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, s *work, int *info) noexcept nogil +cdef void stbcon(char *norm, char *uplo, char *diag, int *n, int *kd, s *ab, int *ldab, s *rcond, s *work, int *iwork, int *info) noexcept nogil +cdef void stbrfs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil +cdef void stbtrs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, int *info) noexcept nogil +cdef void stfsm(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, s *alpha, s *a, s *b, int *ldb) noexcept nogil +cdef void stftri(char *transr, char *uplo, char *diag, int *n, s *a, int *info) noexcept nogil +cdef void stfttp(char *transr, char *uplo, int *n, s *arf, s *ap, int *info) noexcept nogil +cdef void stfttr(char *transr, char *uplo, int *n, s *arf, s *a, int *lda, int *info) noexcept nogil +cdef void stgevc(char *side, char *howmny, bint *select, int *n, s *s, int *lds, s *p, int *ldp, s *vl, int *ldvl, s *vr, int *ldvr, int *mm, int *m, s *work, int *info) noexcept nogil +cdef void stgex2(bint *wantq, bint *wantz, int *n, s *a, int *lda, s *b, int *ldb, s *q, int *ldq, s *z, int *ldz, int *j1, int *n1, int *n2, s *work, int *lwork, int *info) noexcept nogil +cdef void stgexc(bint *wantq, bint *wantz, int *n, s *a, int *lda, s *b, int *ldb, s *q, int *ldq, s *z, int *ldz, int *ifst, int *ilst, s *work, int *lwork, int *info) noexcept nogil +cdef void stgsen(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, s *a, int *lda, s *b, int *ldb, s *alphar, s *alphai, s *beta, s *q, int *ldq, s *z, int *ldz, int *m, s *pl, s *pr, s *dif, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void stgsja(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, s *a, int *lda, s *b, int *ldb, s *tola, s *tolb, s *alpha, s *beta, s *u, int *ldu, s *v, int *ldv, s *q, int *ldq, s *work, int *ncycle, int *info) noexcept nogil +cdef void stgsna(char *job, char *howmny, bint *select, int *n, s *a, int *lda, s *b, int *ldb, s *vl, int *ldvl, s *vr, int *ldvr, s *s, s *dif, int *mm, int *m, s *work, int *lwork, int *iwork, int *info) noexcept nogil +cdef void stgsy2(char *trans, int *ijob, int *m, int *n, s *a, int *lda, s *b, int *ldb, s *c, int *ldc, s *d, int *ldd, s *e, int *lde, s *f, int *ldf, s *scale, s *rdsum, s *rdscal, int *iwork, int *pq, int *info) noexcept nogil +cdef void stgsyl(char *trans, int *ijob, int *m, int *n, s *a, int *lda, s *b, int *ldb, s *c, int *ldc, s *d, int *ldd, s *e, int *lde, s *f, int *ldf, s *scale, s *dif, s *work, int *lwork, int *iwork, int *info) noexcept nogil +cdef void stpcon(char *norm, char *uplo, char *diag, int *n, s *ap, s *rcond, s *work, int *iwork, int *info) noexcept nogil +cdef void stpmqrt(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, s *v, int *ldv, s *t, int *ldt, s *a, int *lda, s *b, int *ldb, s *work, int *info) noexcept nogil +cdef void stpqrt(int *m, int *n, int *l, int *nb, s *a, int *lda, s *b, int *ldb, s *t, int *ldt, s *work, int *info) noexcept nogil +cdef void stpqrt2(int *m, int *n, int *l, s *a, int *lda, s *b, int *ldb, s *t, int *ldt, int *info) noexcept nogil +cdef void stprfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, s *v, int *ldv, s *t, int *ldt, s *a, int *lda, s *b, int *ldb, s *work, int *ldwork) noexcept nogil +cdef void stprfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *ap, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil +cdef void stptri(char *uplo, char *diag, int *n, s *ap, int *info) noexcept nogil +cdef void stptrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *ap, s *b, int *ldb, int *info) noexcept nogil +cdef void stpttf(char *transr, char *uplo, int *n, s *ap, s *arf, int *info) noexcept nogil +cdef void stpttr(char *uplo, int *n, s *ap, s *a, int *lda, int *info) noexcept nogil +cdef void strcon(char *norm, char *uplo, char *diag, int *n, s *a, int *lda, s *rcond, s *work, int *iwork, int *info) noexcept nogil +cdef void strevc(char *side, char *howmny, bint *select, int *n, s *t, int *ldt, s *vl, int *ldvl, s *vr, int *ldvr, int *mm, int *m, s *work, int *info) noexcept nogil +cdef void strexc(char *compq, int *n, s *t, int *ldt, s *q, int *ldq, int *ifst, int *ilst, s *work, int *info) noexcept nogil +cdef void strrfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil +cdef void strsen(char *job, char *compq, bint *select, int *n, s *t, int *ldt, s *q, int *ldq, s *wr, s *wi, int *m, s *s, s *sep, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void strsna(char *job, char *howmny, bint *select, int *n, s *t, int *ldt, s *vl, int *ldvl, s *vr, int *ldvr, s *s, s *sep, int *mm, int *m, s *work, int *ldwork, int *iwork, int *info) noexcept nogil +cdef void strsyl(char *trana, char *tranb, int *isgn, int *m, int *n, s *a, int *lda, s *b, int *ldb, s *c, int *ldc, s *scale, int *info) noexcept nogil +cdef void strti2(char *uplo, char *diag, int *n, s *a, int *lda, int *info) noexcept nogil +cdef void strtri(char *uplo, char *diag, int *n, s *a, int *lda, int *info) noexcept nogil +cdef void strtrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *info) noexcept nogil +cdef void strttf(char *transr, char *uplo, int *n, s *a, int *lda, s *arf, int *info) noexcept nogil +cdef void strttp(char *uplo, int *n, s *a, int *lda, s *ap, int *info) noexcept nogil +cdef void stzrzf(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil +cdef void xerbla_array(char *srname_array, int *srname_len, int *info) noexcept nogil +cdef void zbbcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, d *theta, d *phi, z *u1, int *ldu1, z *u2, int *ldu2, z *v1t, int *ldv1t, z *v2t, int *ldv2t, d *b11d, d *b11e, d *b12d, d *b12e, d *b21d, d *b21e, d *b22d, d *b22e, d *rwork, int *lrwork, int *info) noexcept nogil +cdef void zbdsqr(char *uplo, int *n, int *ncvt, int *nru, int *ncc, d *d, d *e, z *vt, int *ldvt, z *u, int *ldu, z *c, int *ldc, d *rwork, int *info) noexcept nogil +cdef void zcgesv(int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, z *x, int *ldx, z *work, c *swork, d *rwork, int *iter, int *info) noexcept nogil +cdef void zcposv(char *uplo, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, z *x, int *ldx, z *work, c *swork, d *rwork, int *iter, int *info) noexcept nogil +cdef void zdrscl(int *n, d *sa, z *sx, int *incx) noexcept nogil +cdef void zgbbrd(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, z *ab, int *ldab, d *d, d *e, z *q, int *ldq, z *pt, int *ldpt, z *c, int *ldc, z *work, d *rwork, int *info) noexcept nogil +cdef void zgbcon(char *norm, int *n, int *kl, int *ku, z *ab, int *ldab, int *ipiv, d *anorm, d *rcond, z *work, d *rwork, int *info) noexcept nogil +cdef void zgbequ(int *m, int *n, int *kl, int *ku, z *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil +cdef void zgbequb(int *m, int *n, int *kl, int *ku, z *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil +cdef void zgbrfs(char *trans, int *n, int *kl, int *ku, int *nrhs, z *ab, int *ldab, z *afb, int *ldafb, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil +cdef void zgbsv(int *n, int *kl, int *ku, int *nrhs, z *ab, int *ldab, int *ipiv, z *b, int *ldb, int *info) noexcept nogil +cdef void zgbsvx(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, z *ab, int *ldab, z *afb, int *ldafb, int *ipiv, char *equed, d *r, d *c, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil +cdef void zgbtf2(int *m, int *n, int *kl, int *ku, z *ab, int *ldab, int *ipiv, int *info) noexcept nogil +cdef void zgbtrf(int *m, int *n, int *kl, int *ku, z *ab, int *ldab, int *ipiv, int *info) noexcept nogil +cdef void zgbtrs(char *trans, int *n, int *kl, int *ku, int *nrhs, z *ab, int *ldab, int *ipiv, z *b, int *ldb, int *info) noexcept nogil +cdef void zgebak(char *job, char *side, int *n, int *ilo, int *ihi, d *scale, int *m, z *v, int *ldv, int *info) noexcept nogil +cdef void zgebal(char *job, int *n, z *a, int *lda, int *ilo, int *ihi, d *scale, int *info) noexcept nogil +cdef void zgebd2(int *m, int *n, z *a, int *lda, d *d, d *e, z *tauq, z *taup, z *work, int *info) noexcept nogil +cdef void zgebrd(int *m, int *n, z *a, int *lda, d *d, d *e, z *tauq, z *taup, z *work, int *lwork, int *info) noexcept nogil +cdef void zgecon(char *norm, int *n, z *a, int *lda, d *anorm, d *rcond, z *work, d *rwork, int *info) noexcept nogil +cdef void zgeequ(int *m, int *n, z *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil +cdef void zgeequb(int *m, int *n, z *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil +cdef void zgees(char *jobvs, char *sort, zselect1 *select, int *n, z *a, int *lda, int *sdim, z *w, z *vs, int *ldvs, z *work, int *lwork, d *rwork, bint *bwork, int *info) noexcept nogil +cdef void zgeesx(char *jobvs, char *sort, zselect1 *select, char *sense, int *n, z *a, int *lda, int *sdim, z *w, z *vs, int *ldvs, d *rconde, d *rcondv, z *work, int *lwork, d *rwork, bint *bwork, int *info) noexcept nogil +cdef void zgeev(char *jobvl, char *jobvr, int *n, z *a, int *lda, z *w, z *vl, int *ldvl, z *vr, int *ldvr, z *work, int *lwork, d *rwork, int *info) noexcept nogil +cdef void zgeevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, z *a, int *lda, z *w, z *vl, int *ldvl, z *vr, int *ldvr, int *ilo, int *ihi, d *scale, d *abnrm, d *rconde, d *rcondv, z *work, int *lwork, d *rwork, int *info) noexcept nogil +cdef void zgehd2(int *n, int *ilo, int *ihi, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil +cdef void zgehrd(int *n, int *ilo, int *ihi, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil +cdef void zgelq2(int *m, int *n, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil +cdef void zgelqf(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil +cdef void zgels(char *trans, int *m, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, z *work, int *lwork, int *info) noexcept nogil +cdef void zgelsd(int *m, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, d *s, d *rcond, int *rank, z *work, int *lwork, d *rwork, int *iwork, int *info) noexcept nogil +cdef void zgelss(int *m, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, d *s, d *rcond, int *rank, z *work, int *lwork, d *rwork, int *info) noexcept nogil +cdef void zgelsy(int *m, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, int *jpvt, d *rcond, int *rank, z *work, int *lwork, d *rwork, int *info) noexcept nogil +cdef void zgemqrt(char *side, char *trans, int *m, int *n, int *k, int *nb, z *v, int *ldv, z *t, int *ldt, z *c, int *ldc, z *work, int *info) noexcept nogil +cdef void zgeql2(int *m, int *n, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil +cdef void zgeqlf(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil +cdef void zgeqp3(int *m, int *n, z *a, int *lda, int *jpvt, z *tau, z *work, int *lwork, d *rwork, int *info) noexcept nogil +cdef void zgeqr2(int *m, int *n, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil +cdef void zgeqr2p(int *m, int *n, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil +cdef void zgeqrf(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil +cdef void zgeqrfp(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil +cdef void zgeqrt(int *m, int *n, int *nb, z *a, int *lda, z *t, int *ldt, z *work, int *info) noexcept nogil +cdef void zgeqrt2(int *m, int *n, z *a, int *lda, z *t, int *ldt, int *info) noexcept nogil +cdef void zgeqrt3(int *m, int *n, z *a, int *lda, z *t, int *ldt, int *info) noexcept nogil +cdef void zgerfs(char *trans, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil +cdef void zgerq2(int *m, int *n, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil +cdef void zgerqf(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil +cdef void zgesc2(int *n, z *a, int *lda, z *rhs, int *ipiv, int *jpiv, d *scale) noexcept nogil +cdef void zgesdd(char *jobz, int *m, int *n, z *a, int *lda, d *s, z *u, int *ldu, z *vt, int *ldvt, z *work, int *lwork, d *rwork, int *iwork, int *info) noexcept nogil +cdef void zgesv(int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, int *info) noexcept nogil +cdef void zgesvd(char *jobu, char *jobvt, int *m, int *n, z *a, int *lda, d *s, z *u, int *ldu, z *vt, int *ldvt, z *work, int *lwork, d *rwork, int *info) noexcept nogil +cdef void zgesvx(char *fact, char *trans, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, char *equed, d *r, d *c, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil +cdef void zgetc2(int *n, z *a, int *lda, int *ipiv, int *jpiv, int *info) noexcept nogil +cdef void zgetf2(int *m, int *n, z *a, int *lda, int *ipiv, int *info) noexcept nogil +cdef void zgetrf(int *m, int *n, z *a, int *lda, int *ipiv, int *info) noexcept nogil +cdef void zgetri(int *n, z *a, int *lda, int *ipiv, z *work, int *lwork, int *info) noexcept nogil +cdef void zgetrs(char *trans, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, int *info) noexcept nogil +cdef void zggbak(char *job, char *side, int *n, int *ilo, int *ihi, d *lscale, d *rscale, int *m, z *v, int *ldv, int *info) noexcept nogil +cdef void zggbal(char *job, int *n, z *a, int *lda, z *b, int *ldb, int *ilo, int *ihi, d *lscale, d *rscale, d *work, int *info) noexcept nogil +cdef void zgges(char *jobvsl, char *jobvsr, char *sort, zselect2 *selctg, int *n, z *a, int *lda, z *b, int *ldb, int *sdim, z *alpha, z *beta, z *vsl, int *ldvsl, z *vsr, int *ldvsr, z *work, int *lwork, d *rwork, bint *bwork, int *info) noexcept nogil +cdef void zggesx(char *jobvsl, char *jobvsr, char *sort, zselect2 *selctg, char *sense, int *n, z *a, int *lda, z *b, int *ldb, int *sdim, z *alpha, z *beta, z *vsl, int *ldvsl, z *vsr, int *ldvsr, d *rconde, d *rcondv, z *work, int *lwork, d *rwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil +cdef void zggev(char *jobvl, char *jobvr, int *n, z *a, int *lda, z *b, int *ldb, z *alpha, z *beta, z *vl, int *ldvl, z *vr, int *ldvr, z *work, int *lwork, d *rwork, int *info) noexcept nogil +cdef void zggevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, z *a, int *lda, z *b, int *ldb, z *alpha, z *beta, z *vl, int *ldvl, z *vr, int *ldvr, int *ilo, int *ihi, d *lscale, d *rscale, d *abnrm, d *bbnrm, d *rconde, d *rcondv, z *work, int *lwork, d *rwork, int *iwork, bint *bwork, int *info) noexcept nogil +cdef void zggglm(int *n, int *m, int *p, z *a, int *lda, z *b, int *ldb, z *d, z *x, z *y, z *work, int *lwork, int *info) noexcept nogil +cdef void zgghrd(char *compq, char *compz, int *n, int *ilo, int *ihi, z *a, int *lda, z *b, int *ldb, z *q, int *ldq, z *z, int *ldz, int *info) noexcept nogil +cdef void zgglse(int *m, int *n, int *p, z *a, int *lda, z *b, int *ldb, z *c, z *d, z *x, z *work, int *lwork, int *info) noexcept nogil +cdef void zggqrf(int *n, int *m, int *p, z *a, int *lda, z *taua, z *b, int *ldb, z *taub, z *work, int *lwork, int *info) noexcept nogil +cdef void zggrqf(int *m, int *p, int *n, z *a, int *lda, z *taua, z *b, int *ldb, z *taub, z *work, int *lwork, int *info) noexcept nogil +cdef void zgtcon(char *norm, int *n, z *dl, z *d, z *du, z *du2, int *ipiv, d *anorm, d *rcond, z *work, int *info) noexcept nogil +cdef void zgtrfs(char *trans, int *n, int *nrhs, z *dl, z *d, z *du, z *dlf, z *df, z *duf, z *du2, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil +cdef void zgtsv(int *n, int *nrhs, z *dl, z *d, z *du, z *b, int *ldb, int *info) noexcept nogil +cdef void zgtsvx(char *fact, char *trans, int *n, int *nrhs, z *dl, z *d, z *du, z *dlf, z *df, z *duf, z *du2, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil +cdef void zgttrf(int *n, z *dl, z *d, z *du, z *du2, int *ipiv, int *info) noexcept nogil +cdef void zgttrs(char *trans, int *n, int *nrhs, z *dl, z *d, z *du, z *du2, int *ipiv, z *b, int *ldb, int *info) noexcept nogil +cdef void zgtts2(int *itrans, int *n, int *nrhs, z *dl, z *d, z *du, z *du2, int *ipiv, z *b, int *ldb) noexcept nogil +cdef void zhbev(char *jobz, char *uplo, int *n, int *kd, z *ab, int *ldab, d *w, z *z, int *ldz, z *work, d *rwork, int *info) noexcept nogil +cdef void zhbevd(char *jobz, char *uplo, int *n, int *kd, z *ab, int *ldab, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void zhbevx(char *jobz, char *range, char *uplo, int *n, int *kd, z *ab, int *ldab, z *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil +cdef void zhbgst(char *vect, char *uplo, int *n, int *ka, int *kb, z *ab, int *ldab, z *bb, int *ldbb, z *x, int *ldx, z *work, d *rwork, int *info) noexcept nogil +cdef void zhbgv(char *jobz, char *uplo, int *n, int *ka, int *kb, z *ab, int *ldab, z *bb, int *ldbb, d *w, z *z, int *ldz, z *work, d *rwork, int *info) noexcept nogil +cdef void zhbgvd(char *jobz, char *uplo, int *n, int *ka, int *kb, z *ab, int *ldab, z *bb, int *ldbb, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void zhbgvx(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, z *ab, int *ldab, z *bb, int *ldbb, z *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil +cdef void zhbtrd(char *vect, char *uplo, int *n, int *kd, z *ab, int *ldab, d *d, d *e, z *q, int *ldq, z *work, int *info) noexcept nogil +cdef void zhecon(char *uplo, int *n, z *a, int *lda, int *ipiv, d *anorm, d *rcond, z *work, int *info) noexcept nogil +cdef void zheequb(char *uplo, int *n, z *a, int *lda, d *s, d *scond, d *amax, z *work, int *info) noexcept nogil +cdef void zheev(char *jobz, char *uplo, int *n, z *a, int *lda, d *w, z *work, int *lwork, d *rwork, int *info) noexcept nogil +cdef void zheevd(char *jobz, char *uplo, int *n, z *a, int *lda, d *w, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void zheevr(char *jobz, char *range, char *uplo, int *n, z *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, int *isuppz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void zheevx(char *jobz, char *range, char *uplo, int *n, z *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil +cdef void zhegs2(int *itype, char *uplo, int *n, z *a, int *lda, z *b, int *ldb, int *info) noexcept nogil +cdef void zhegst(int *itype, char *uplo, int *n, z *a, int *lda, z *b, int *ldb, int *info) noexcept nogil +cdef void zhegv(int *itype, char *jobz, char *uplo, int *n, z *a, int *lda, z *b, int *ldb, d *w, z *work, int *lwork, d *rwork, int *info) noexcept nogil +cdef void zhegvd(int *itype, char *jobz, char *uplo, int *n, z *a, int *lda, z *b, int *ldb, d *w, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void zhegvx(int *itype, char *jobz, char *range, char *uplo, int *n, z *a, int *lda, z *b, int *ldb, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil +cdef void zherfs(char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil +cdef void zhesv(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, z *work, int *lwork, int *info) noexcept nogil +cdef void zhesvx(char *fact, char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, int *lwork, d *rwork, int *info) noexcept nogil +cdef void zheswapr(char *uplo, int *n, z *a, int *lda, int *i1, int *i2) noexcept nogil +cdef void zhetd2(char *uplo, int *n, z *a, int *lda, d *d, d *e, z *tau, int *info) noexcept nogil +cdef void zhetf2(char *uplo, int *n, z *a, int *lda, int *ipiv, int *info) noexcept nogil +cdef void zhetrd(char *uplo, int *n, z *a, int *lda, d *d, d *e, z *tau, z *work, int *lwork, int *info) noexcept nogil +cdef void zhetrf(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *lwork, int *info) noexcept nogil +cdef void zhetri(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *info) noexcept nogil +cdef void zhetri2(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *lwork, int *info) noexcept nogil +cdef void zhetri2x(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *nb, int *info) noexcept nogil +cdef void zhetrs(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, int *info) noexcept nogil +cdef void zhetrs2(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, z *work, int *info) noexcept nogil +cdef void zhfrk(char *transr, char *uplo, char *trans, int *n, int *k, d *alpha, z *a, int *lda, d *beta, z *c) noexcept nogil +cdef void zhgeqz(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, z *h, int *ldh, z *t, int *ldt, z *alpha, z *beta, z *q, int *ldq, z *z, int *ldz, z *work, int *lwork, d *rwork, int *info) noexcept nogil +cdef void zhpcon(char *uplo, int *n, z *ap, int *ipiv, d *anorm, d *rcond, z *work, int *info) noexcept nogil +cdef void zhpev(char *jobz, char *uplo, int *n, z *ap, d *w, z *z, int *ldz, z *work, d *rwork, int *info) noexcept nogil +cdef void zhpevd(char *jobz, char *uplo, int *n, z *ap, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void zhpevx(char *jobz, char *range, char *uplo, int *n, z *ap, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil +cdef void zhpgst(int *itype, char *uplo, int *n, z *ap, z *bp, int *info) noexcept nogil +cdef void zhpgv(int *itype, char *jobz, char *uplo, int *n, z *ap, z *bp, d *w, z *z, int *ldz, z *work, d *rwork, int *info) noexcept nogil +cdef void zhpgvd(int *itype, char *jobz, char *uplo, int *n, z *ap, z *bp, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void zhpgvx(int *itype, char *jobz, char *range, char *uplo, int *n, z *ap, z *bp, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil +cdef void zhprfs(char *uplo, int *n, int *nrhs, z *ap, z *afp, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil +cdef void zhpsv(char *uplo, int *n, int *nrhs, z *ap, int *ipiv, z *b, int *ldb, int *info) noexcept nogil +cdef void zhpsvx(char *fact, char *uplo, int *n, int *nrhs, z *ap, z *afp, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil +cdef void zhptrd(char *uplo, int *n, z *ap, d *d, d *e, z *tau, int *info) noexcept nogil +cdef void zhptrf(char *uplo, int *n, z *ap, int *ipiv, int *info) noexcept nogil +cdef void zhptri(char *uplo, int *n, z *ap, int *ipiv, z *work, int *info) noexcept nogil +cdef void zhptrs(char *uplo, int *n, int *nrhs, z *ap, int *ipiv, z *b, int *ldb, int *info) noexcept nogil +cdef void zhsein(char *side, char *eigsrc, char *initv, bint *select, int *n, z *h, int *ldh, z *w, z *vl, int *ldvl, z *vr, int *ldvr, int *mm, int *m, z *work, d *rwork, int *ifaill, int *ifailr, int *info) noexcept nogil +cdef void zhseqr(char *job, char *compz, int *n, int *ilo, int *ihi, z *h, int *ldh, z *w, z *z, int *ldz, z *work, int *lwork, int *info) noexcept nogil +cdef void zlabrd(int *m, int *n, int *nb, z *a, int *lda, d *d, d *e, z *tauq, z *taup, z *x, int *ldx, z *y, int *ldy) noexcept nogil +cdef void zlacgv(int *n, z *x, int *incx) noexcept nogil +cdef void zlacn2(int *n, z *v, z *x, d *est, int *kase, int *isave) noexcept nogil +cdef void zlacon(int *n, z *v, z *x, d *est, int *kase) noexcept nogil +cdef void zlacp2(char *uplo, int *m, int *n, d *a, int *lda, z *b, int *ldb) noexcept nogil +cdef void zlacpy(char *uplo, int *m, int *n, z *a, int *lda, z *b, int *ldb) noexcept nogil +cdef void zlacrm(int *m, int *n, z *a, int *lda, d *b, int *ldb, z *c, int *ldc, d *rwork) noexcept nogil +cdef void zlacrt(int *n, z *cx, int *incx, z *cy, int *incy, z *c, z *s) noexcept nogil +cdef z zladiv(z *x, z *y) noexcept nogil +cdef void zlaed0(int *qsiz, int *n, d *d, d *e, z *q, int *ldq, z *qstore, int *ldqs, d *rwork, int *iwork, int *info) noexcept nogil +cdef void zlaed7(int *n, int *cutpnt, int *qsiz, int *tlvls, int *curlvl, int *curpbm, d *d, z *q, int *ldq, d *rho, int *indxq, d *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, d *givnum, z *work, d *rwork, int *iwork, int *info) noexcept nogil +cdef void zlaed8(int *k, int *n, int *qsiz, z *q, int *ldq, d *d, d *rho, int *cutpnt, d *z, d *dlamda, z *q2, int *ldq2, d *w, int *indxp, int *indx, int *indxq, int *perm, int *givptr, int *givcol, d *givnum, int *info) noexcept nogil +cdef void zlaein(bint *rightv, bint *noinit, int *n, z *h, int *ldh, z *w, z *v, z *b, int *ldb, d *rwork, d *eps3, d *smlnum, int *info) noexcept nogil +cdef void zlaesy(z *a, z *b, z *c, z *rt1, z *rt2, z *evscal, z *cs1, z *sn1) noexcept nogil +cdef void zlaev2(z *a, z *b, z *c, d *rt1, d *rt2, d *cs1, z *sn1) noexcept nogil +cdef void zlag2c(int *m, int *n, z *a, int *lda, c *sa, int *ldsa, int *info) noexcept nogil +cdef void zlags2(bint *upper, d *a1, z *a2, d *a3, d *b1, z *b2, d *b3, d *csu, z *snu, d *csv, z *snv, d *csq, z *snq) noexcept nogil +cdef void zlagtm(char *trans, int *n, int *nrhs, d *alpha, z *dl, z *d, z *du, z *x, int *ldx, d *beta, z *b, int *ldb) noexcept nogil +cdef void zlahef(char *uplo, int *n, int *nb, int *kb, z *a, int *lda, int *ipiv, z *w, int *ldw, int *info) noexcept nogil +cdef void zlahqr(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, z *h, int *ldh, z *w, int *iloz, int *ihiz, z *z, int *ldz, int *info) noexcept nogil +cdef void zlahr2(int *n, int *k, int *nb, z *a, int *lda, z *tau, z *t, int *ldt, z *y, int *ldy) noexcept nogil +cdef void zlaic1(int *job, int *j, z *x, d *sest, z *w, z *gamma, d *sestpr, z *s, z *c) noexcept nogil +cdef void zlals0(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, z *b, int *ldb, z *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, d *givnum, int *ldgnum, d *poles, d *difl, d *difr, d *z, int *k, d *c, d *s, d *rwork, int *info) noexcept nogil +cdef void zlalsa(int *icompq, int *smlsiz, int *n, int *nrhs, z *b, int *ldb, z *bx, int *ldbx, d *u, int *ldu, d *vt, int *k, d *difl, d *difr, d *z, d *poles, int *givptr, int *givcol, int *ldgcol, int *perm, d *givnum, d *c, d *s, d *rwork, int *iwork, int *info) noexcept nogil +cdef void zlalsd(char *uplo, int *smlsiz, int *n, int *nrhs, d *d, d *e, z *b, int *ldb, d *rcond, int *rank, z *work, d *rwork, int *iwork, int *info) noexcept nogil +cdef d zlangb(char *norm, int *n, int *kl, int *ku, z *ab, int *ldab, d *work) noexcept nogil +cdef d zlange(char *norm, int *m, int *n, z *a, int *lda, d *work) noexcept nogil +cdef d zlangt(char *norm, int *n, z *dl, z *d_, z *du) noexcept nogil +cdef d zlanhb(char *norm, char *uplo, int *n, int *k, z *ab, int *ldab, d *work) noexcept nogil +cdef d zlanhe(char *norm, char *uplo, int *n, z *a, int *lda, d *work) noexcept nogil +cdef d zlanhf(char *norm, char *transr, char *uplo, int *n, z *a, d *work) noexcept nogil +cdef d zlanhp(char *norm, char *uplo, int *n, z *ap, d *work) noexcept nogil +cdef d zlanhs(char *norm, int *n, z *a, int *lda, d *work) noexcept nogil +cdef d zlanht(char *norm, int *n, d *d_, z *e) noexcept nogil +cdef d zlansb(char *norm, char *uplo, int *n, int *k, z *ab, int *ldab, d *work) noexcept nogil +cdef d zlansp(char *norm, char *uplo, int *n, z *ap, d *work) noexcept nogil +cdef d zlansy(char *norm, char *uplo, int *n, z *a, int *lda, d *work) noexcept nogil +cdef d zlantb(char *norm, char *uplo, char *diag, int *n, int *k, z *ab, int *ldab, d *work) noexcept nogil +cdef d zlantp(char *norm, char *uplo, char *diag, int *n, z *ap, d *work) noexcept nogil +cdef d zlantr(char *norm, char *uplo, char *diag, int *m, int *n, z *a, int *lda, d *work) noexcept nogil +cdef void zlapll(int *n, z *x, int *incx, z *y, int *incy, d *ssmin) noexcept nogil +cdef void zlapmr(bint *forwrd, int *m, int *n, z *x, int *ldx, int *k) noexcept nogil +cdef void zlapmt(bint *forwrd, int *m, int *n, z *x, int *ldx, int *k) noexcept nogil +cdef void zlaqgb(int *m, int *n, int *kl, int *ku, z *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) noexcept nogil +cdef void zlaqge(int *m, int *n, z *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) noexcept nogil +cdef void zlaqhb(char *uplo, int *n, int *kd, z *ab, int *ldab, d *s, d *scond, d *amax, char *equed) noexcept nogil +cdef void zlaqhe(char *uplo, int *n, z *a, int *lda, d *s, d *scond, d *amax, char *equed) noexcept nogil +cdef void zlaqhp(char *uplo, int *n, z *ap, d *s, d *scond, d *amax, char *equed) noexcept nogil +cdef void zlaqp2(int *m, int *n, int *offset, z *a, int *lda, int *jpvt, z *tau, d *vn1, d *vn2, z *work) noexcept nogil +cdef void zlaqps(int *m, int *n, int *offset, int *nb, int *kb, z *a, int *lda, int *jpvt, z *tau, d *vn1, d *vn2, z *auxv, z *f, int *ldf) noexcept nogil +cdef void zlaqr0(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, z *h, int *ldh, z *w, int *iloz, int *ihiz, z *z, int *ldz, z *work, int *lwork, int *info) noexcept nogil +cdef void zlaqr1(int *n, z *h, int *ldh, z *s1, z *s2, z *v) noexcept nogil +cdef void zlaqr2(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, z *h, int *ldh, int *iloz, int *ihiz, z *z, int *ldz, int *ns, int *nd, z *sh, z *v, int *ldv, int *nh, z *t, int *ldt, int *nv, z *wv, int *ldwv, z *work, int *lwork) noexcept nogil +cdef void zlaqr3(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, z *h, int *ldh, int *iloz, int *ihiz, z *z, int *ldz, int *ns, int *nd, z *sh, z *v, int *ldv, int *nh, z *t, int *ldt, int *nv, z *wv, int *ldwv, z *work, int *lwork) noexcept nogil +cdef void zlaqr4(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, z *h, int *ldh, z *w, int *iloz, int *ihiz, z *z, int *ldz, z *work, int *lwork, int *info) noexcept nogil +cdef void zlaqr5(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, z *s, z *h, int *ldh, int *iloz, int *ihiz, z *z, int *ldz, z *v, int *ldv, z *u, int *ldu, int *nv, z *wv, int *ldwv, int *nh, z *wh, int *ldwh) noexcept nogil +cdef void zlaqsb(char *uplo, int *n, int *kd, z *ab, int *ldab, d *s, d *scond, d *amax, char *equed) noexcept nogil +cdef void zlaqsp(char *uplo, int *n, z *ap, d *s, d *scond, d *amax, char *equed) noexcept nogil +cdef void zlaqsy(char *uplo, int *n, z *a, int *lda, d *s, d *scond, d *amax, char *equed) noexcept nogil +cdef void zlar1v(int *n, int *b1, int *bn, d *lambda_, d *d, d *l, d *ld, d *lld, d *pivmin, d *gaptol, z *z, bint *wantnc, int *negcnt, d *ztz, d *mingma, int *r, int *isuppz, d *nrminv, d *resid, d *rqcorr, d *work) noexcept nogil +cdef void zlar2v(int *n, z *x, z *y, z *z, int *incx, d *c, z *s, int *incc) noexcept nogil +cdef void zlarcm(int *m, int *n, d *a, int *lda, z *b, int *ldb, z *c, int *ldc, d *rwork) noexcept nogil +cdef void zlarf(char *side, int *m, int *n, z *v, int *incv, z *tau, z *c, int *ldc, z *work) noexcept nogil +cdef void zlarfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, z *v, int *ldv, z *t, int *ldt, z *c, int *ldc, z *work, int *ldwork) noexcept nogil +cdef void zlarfg(int *n, z *alpha, z *x, int *incx, z *tau) noexcept nogil +cdef void zlarfgp(int *n, z *alpha, z *x, int *incx, z *tau) noexcept nogil +cdef void zlarft(char *direct, char *storev, int *n, int *k, z *v, int *ldv, z *tau, z *t, int *ldt) noexcept nogil +cdef void zlarfx(char *side, int *m, int *n, z *v, z *tau, z *c, int *ldc, z *work) noexcept nogil +cdef void zlargv(int *n, z *x, int *incx, z *y, int *incy, d *c, int *incc) noexcept nogil +cdef void zlarnv(int *idist, int *iseed, int *n, z *x) noexcept nogil +cdef void zlarrv(int *n, d *vl, d *vu, d *d, d *l, d *pivmin, int *isplit, int *m, int *dol, int *dou, d *minrgp, d *rtol1, d *rtol2, d *w, d *werr, d *wgap, int *iblock, int *indexw, d *gers, z *z, int *ldz, int *isuppz, d *work, int *iwork, int *info) noexcept nogil +cdef void zlartg(z *f, z *g, d *cs, z *sn, z *r) noexcept nogil +cdef void zlartv(int *n, z *x, int *incx, z *y, int *incy, d *c, z *s, int *incc) noexcept nogil +cdef void zlarz(char *side, int *m, int *n, int *l, z *v, int *incv, z *tau, z *c, int *ldc, z *work) noexcept nogil +cdef void zlarzb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, z *v, int *ldv, z *t, int *ldt, z *c, int *ldc, z *work, int *ldwork) noexcept nogil +cdef void zlarzt(char *direct, char *storev, int *n, int *k, z *v, int *ldv, z *tau, z *t, int *ldt) noexcept nogil +cdef void zlascl(char *type_bn, int *kl, int *ku, d *cfrom, d *cto, int *m, int *n, z *a, int *lda, int *info) noexcept nogil +cdef void zlaset(char *uplo, int *m, int *n, z *alpha, z *beta, z *a, int *lda) noexcept nogil +cdef void zlasr(char *side, char *pivot, char *direct, int *m, int *n, d *c, d *s, z *a, int *lda) noexcept nogil +cdef void zlassq(int *n, z *x, int *incx, d *scale, d *sumsq) noexcept nogil +cdef void zlaswp(int *n, z *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) noexcept nogil +cdef void zlasyf(char *uplo, int *n, int *nb, int *kb, z *a, int *lda, int *ipiv, z *w, int *ldw, int *info) noexcept nogil +cdef void zlat2c(char *uplo, int *n, z *a, int *lda, c *sa, int *ldsa, int *info) noexcept nogil +cdef void zlatbs(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, z *ab, int *ldab, z *x, d *scale, d *cnorm, int *info) noexcept nogil +cdef void zlatdf(int *ijob, int *n, z *z, int *ldz, z *rhs, d *rdsum, d *rdscal, int *ipiv, int *jpiv) noexcept nogil +cdef void zlatps(char *uplo, char *trans, char *diag, char *normin, int *n, z *ap, z *x, d *scale, d *cnorm, int *info) noexcept nogil +cdef void zlatrd(char *uplo, int *n, int *nb, z *a, int *lda, d *e, z *tau, z *w, int *ldw) noexcept nogil +cdef void zlatrs(char *uplo, char *trans, char *diag, char *normin, int *n, z *a, int *lda, z *x, d *scale, d *cnorm, int *info) noexcept nogil +cdef void zlatrz(int *m, int *n, int *l, z *a, int *lda, z *tau, z *work) noexcept nogil +cdef void zlauu2(char *uplo, int *n, z *a, int *lda, int *info) noexcept nogil +cdef void zlauum(char *uplo, int *n, z *a, int *lda, int *info) noexcept nogil +cdef void zpbcon(char *uplo, int *n, int *kd, z *ab, int *ldab, d *anorm, d *rcond, z *work, d *rwork, int *info) noexcept nogil +cdef void zpbequ(char *uplo, int *n, int *kd, z *ab, int *ldab, d *s, d *scond, d *amax, int *info) noexcept nogil +cdef void zpbrfs(char *uplo, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *afb, int *ldafb, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil +cdef void zpbstf(char *uplo, int *n, int *kd, z *ab, int *ldab, int *info) noexcept nogil +cdef void zpbsv(char *uplo, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *b, int *ldb, int *info) noexcept nogil +cdef void zpbsvx(char *fact, char *uplo, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *afb, int *ldafb, char *equed, d *s, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil +cdef void zpbtf2(char *uplo, int *n, int *kd, z *ab, int *ldab, int *info) noexcept nogil +cdef void zpbtrf(char *uplo, int *n, int *kd, z *ab, int *ldab, int *info) noexcept nogil +cdef void zpbtrs(char *uplo, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *b, int *ldb, int *info) noexcept nogil +cdef void zpftrf(char *transr, char *uplo, int *n, z *a, int *info) noexcept nogil +cdef void zpftri(char *transr, char *uplo, int *n, z *a, int *info) noexcept nogil +cdef void zpftrs(char *transr, char *uplo, int *n, int *nrhs, z *a, z *b, int *ldb, int *info) noexcept nogil +cdef void zpocon(char *uplo, int *n, z *a, int *lda, d *anorm, d *rcond, z *work, d *rwork, int *info) noexcept nogil +cdef void zpoequ(int *n, z *a, int *lda, d *s, d *scond, d *amax, int *info) noexcept nogil +cdef void zpoequb(int *n, z *a, int *lda, d *s, d *scond, d *amax, int *info) noexcept nogil +cdef void zporfs(char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil +cdef void zposv(char *uplo, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, int *info) noexcept nogil +cdef void zposvx(char *fact, char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, char *equed, d *s, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil +cdef void zpotf2(char *uplo, int *n, z *a, int *lda, int *info) noexcept nogil +cdef void zpotrf(char *uplo, int *n, z *a, int *lda, int *info) noexcept nogil +cdef void zpotri(char *uplo, int *n, z *a, int *lda, int *info) noexcept nogil +cdef void zpotrs(char *uplo, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, int *info) noexcept nogil +cdef void zppcon(char *uplo, int *n, z *ap, d *anorm, d *rcond, z *work, d *rwork, int *info) noexcept nogil +cdef void zppequ(char *uplo, int *n, z *ap, d *s, d *scond, d *amax, int *info) noexcept nogil +cdef void zpprfs(char *uplo, int *n, int *nrhs, z *ap, z *afp, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil +cdef void zppsv(char *uplo, int *n, int *nrhs, z *ap, z *b, int *ldb, int *info) noexcept nogil +cdef void zppsvx(char *fact, char *uplo, int *n, int *nrhs, z *ap, z *afp, char *equed, d *s, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil +cdef void zpptrf(char *uplo, int *n, z *ap, int *info) noexcept nogil +cdef void zpptri(char *uplo, int *n, z *ap, int *info) noexcept nogil +cdef void zpptrs(char *uplo, int *n, int *nrhs, z *ap, z *b, int *ldb, int *info) noexcept nogil +cdef void zpstf2(char *uplo, int *n, z *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) noexcept nogil +cdef void zpstrf(char *uplo, int *n, z *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) noexcept nogil +cdef void zptcon(int *n, d *d, z *e, d *anorm, d *rcond, d *rwork, int *info) noexcept nogil +cdef void zpteqr(char *compz, int *n, d *d, d *e, z *z, int *ldz, d *work, int *info) noexcept nogil +cdef void zptrfs(char *uplo, int *n, int *nrhs, d *d, z *e, d *df, z *ef, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil +cdef void zptsv(int *n, int *nrhs, d *d, z *e, z *b, int *ldb, int *info) noexcept nogil +cdef void zptsvx(char *fact, int *n, int *nrhs, d *d, z *e, d *df, z *ef, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil +cdef void zpttrf(int *n, d *d, z *e, int *info) noexcept nogil +cdef void zpttrs(char *uplo, int *n, int *nrhs, d *d, z *e, z *b, int *ldb, int *info) noexcept nogil +cdef void zptts2(int *iuplo, int *n, int *nrhs, d *d, z *e, z *b, int *ldb) noexcept nogil +cdef void zrot(int *n, z *cx, int *incx, z *cy, int *incy, d *c, z *s) noexcept nogil +cdef void zspcon(char *uplo, int *n, z *ap, int *ipiv, d *anorm, d *rcond, z *work, int *info) noexcept nogil +cdef void zspmv(char *uplo, int *n, z *alpha, z *ap, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil +cdef void zspr(char *uplo, int *n, z *alpha, z *x, int *incx, z *ap) noexcept nogil +cdef void zsprfs(char *uplo, int *n, int *nrhs, z *ap, z *afp, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil +cdef void zspsv(char *uplo, int *n, int *nrhs, z *ap, int *ipiv, z *b, int *ldb, int *info) noexcept nogil +cdef void zspsvx(char *fact, char *uplo, int *n, int *nrhs, z *ap, z *afp, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil +cdef void zsptrf(char *uplo, int *n, z *ap, int *ipiv, int *info) noexcept nogil +cdef void zsptri(char *uplo, int *n, z *ap, int *ipiv, z *work, int *info) noexcept nogil +cdef void zsptrs(char *uplo, int *n, int *nrhs, z *ap, int *ipiv, z *b, int *ldb, int *info) noexcept nogil +cdef void zstedc(char *compz, int *n, d *d, d *e, z *z, int *ldz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void zstegr(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, int *isuppz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void zstein(int *n, d *d, d *e, int *m, d *w, int *iblock, int *isplit, z *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil +cdef void zstemr(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, int *m, d *w, z *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void zsteqr(char *compz, int *n, d *d, d *e, z *z, int *ldz, d *work, int *info) noexcept nogil +cdef void zsycon(char *uplo, int *n, z *a, int *lda, int *ipiv, d *anorm, d *rcond, z *work, int *info) noexcept nogil +cdef void zsyconv(char *uplo, char *way, int *n, z *a, int *lda, int *ipiv, z *work, int *info) noexcept nogil +cdef void zsyequb(char *uplo, int *n, z *a, int *lda, d *s, d *scond, d *amax, z *work, int *info) noexcept nogil +cdef void zsymv(char *uplo, int *n, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil +cdef void zsyr(char *uplo, int *n, z *alpha, z *x, int *incx, z *a, int *lda) noexcept nogil +cdef void zsyrfs(char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil +cdef void zsysv(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, z *work, int *lwork, int *info) noexcept nogil +cdef void zsysvx(char *fact, char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, int *lwork, d *rwork, int *info) noexcept nogil +cdef void zsyswapr(char *uplo, int *n, z *a, int *lda, int *i1, int *i2) noexcept nogil +cdef void zsytf2(char *uplo, int *n, z *a, int *lda, int *ipiv, int *info) noexcept nogil +cdef void zsytrf(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *lwork, int *info) noexcept nogil +cdef void zsytri(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *info) noexcept nogil +cdef void zsytri2(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *lwork, int *info) noexcept nogil +cdef void zsytri2x(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *nb, int *info) noexcept nogil +cdef void zsytrs(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, int *info) noexcept nogil +cdef void zsytrs2(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, z *work, int *info) noexcept nogil +cdef void ztbcon(char *norm, char *uplo, char *diag, int *n, int *kd, z *ab, int *ldab, d *rcond, z *work, d *rwork, int *info) noexcept nogil +cdef void ztbrfs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil +cdef void ztbtrs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *b, int *ldb, int *info) noexcept nogil +cdef void ztfsm(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, z *alpha, z *a, z *b, int *ldb) noexcept nogil +cdef void ztftri(char *transr, char *uplo, char *diag, int *n, z *a, int *info) noexcept nogil +cdef void ztfttp(char *transr, char *uplo, int *n, z *arf, z *ap, int *info) noexcept nogil +cdef void ztfttr(char *transr, char *uplo, int *n, z *arf, z *a, int *lda, int *info) noexcept nogil +cdef void ztgevc(char *side, char *howmny, bint *select, int *n, z *s, int *lds, z *p, int *ldp, z *vl, int *ldvl, z *vr, int *ldvr, int *mm, int *m, z *work, d *rwork, int *info) noexcept nogil +cdef void ztgex2(bint *wantq, bint *wantz, int *n, z *a, int *lda, z *b, int *ldb, z *q, int *ldq, z *z, int *ldz, int *j1, int *info) noexcept nogil +cdef void ztgexc(bint *wantq, bint *wantz, int *n, z *a, int *lda, z *b, int *ldb, z *q, int *ldq, z *z, int *ldz, int *ifst, int *ilst, int *info) noexcept nogil +cdef void ztgsen(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, z *a, int *lda, z *b, int *ldb, z *alpha, z *beta, z *q, int *ldq, z *z, int *ldz, int *m, d *pl, d *pr, d *dif, z *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil +cdef void ztgsja(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, z *a, int *lda, z *b, int *ldb, d *tola, d *tolb, d *alpha, d *beta, z *u, int *ldu, z *v, int *ldv, z *q, int *ldq, z *work, int *ncycle, int *info) noexcept nogil +cdef void ztgsna(char *job, char *howmny, bint *select, int *n, z *a, int *lda, z *b, int *ldb, z *vl, int *ldvl, z *vr, int *ldvr, d *s, d *dif, int *mm, int *m, z *work, int *lwork, int *iwork, int *info) noexcept nogil +cdef void ztgsy2(char *trans, int *ijob, int *m, int *n, z *a, int *lda, z *b, int *ldb, z *c, int *ldc, z *d, int *ldd, z *e, int *lde, z *f, int *ldf, d *scale, d *rdsum, d *rdscal, int *info) noexcept nogil +cdef void ztgsyl(char *trans, int *ijob, int *m, int *n, z *a, int *lda, z *b, int *ldb, z *c, int *ldc, z *d, int *ldd, z *e, int *lde, z *f, int *ldf, d *scale, d *dif, z *work, int *lwork, int *iwork, int *info) noexcept nogil +cdef void ztpcon(char *norm, char *uplo, char *diag, int *n, z *ap, d *rcond, z *work, d *rwork, int *info) noexcept nogil +cdef void ztpmqrt(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, z *v, int *ldv, z *t, int *ldt, z *a, int *lda, z *b, int *ldb, z *work, int *info) noexcept nogil +cdef void ztpqrt(int *m, int *n, int *l, int *nb, z *a, int *lda, z *b, int *ldb, z *t, int *ldt, z *work, int *info) noexcept nogil +cdef void ztpqrt2(int *m, int *n, int *l, z *a, int *lda, z *b, int *ldb, z *t, int *ldt, int *info) noexcept nogil +cdef void ztprfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, z *v, int *ldv, z *t, int *ldt, z *a, int *lda, z *b, int *ldb, z *work, int *ldwork) noexcept nogil +cdef void ztprfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, z *ap, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil +cdef void ztptri(char *uplo, char *diag, int *n, z *ap, int *info) noexcept nogil +cdef void ztptrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, z *ap, z *b, int *ldb, int *info) noexcept nogil +cdef void ztpttf(char *transr, char *uplo, int *n, z *ap, z *arf, int *info) noexcept nogil +cdef void ztpttr(char *uplo, int *n, z *ap, z *a, int *lda, int *info) noexcept nogil +cdef void ztrcon(char *norm, char *uplo, char *diag, int *n, z *a, int *lda, d *rcond, z *work, d *rwork, int *info) noexcept nogil +cdef void ztrevc(char *side, char *howmny, bint *select, int *n, z *t, int *ldt, z *vl, int *ldvl, z *vr, int *ldvr, int *mm, int *m, z *work, d *rwork, int *info) noexcept nogil +cdef void ztrexc(char *compq, int *n, z *t, int *ldt, z *q, int *ldq, int *ifst, int *ilst, int *info) noexcept nogil +cdef void ztrrfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil +cdef void ztrsen(char *job, char *compq, bint *select, int *n, z *t, int *ldt, z *q, int *ldq, z *w, int *m, d *s, d *sep, z *work, int *lwork, int *info) noexcept nogil +cdef void ztrsna(char *job, char *howmny, bint *select, int *n, z *t, int *ldt, z *vl, int *ldvl, z *vr, int *ldvr, d *s, d *sep, int *mm, int *m, z *work, int *ldwork, d *rwork, int *info) noexcept nogil +cdef void ztrsyl(char *trana, char *tranb, int *isgn, int *m, int *n, z *a, int *lda, z *b, int *ldb, z *c, int *ldc, d *scale, int *info) noexcept nogil +cdef void ztrti2(char *uplo, char *diag, int *n, z *a, int *lda, int *info) noexcept nogil +cdef void ztrtri(char *uplo, char *diag, int *n, z *a, int *lda, int *info) noexcept nogil +cdef void ztrtrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, int *info) noexcept nogil +cdef void ztrttf(char *transr, char *uplo, int *n, z *a, int *lda, z *arf, int *info) noexcept nogil +cdef void ztrttp(char *uplo, int *n, z *a, int *lda, z *ap, int *info) noexcept nogil +cdef void ztzrzf(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil +cdef void zunbdb(char *trans, char *signs, int *m, int *p, int *q, z *x11, int *ldx11, z *x12, int *ldx12, z *x21, int *ldx21, z *x22, int *ldx22, d *theta, d *phi, z *taup1, z *taup2, z *tauq1, z *tauq2, z *work, int *lwork, int *info) noexcept nogil +cdef void zuncsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, z *x11, int *ldx11, z *x12, int *ldx12, z *x21, int *ldx21, z *x22, int *ldx22, d *theta, z *u1, int *ldu1, z *u2, int *ldu2, z *v1t, int *ldv1t, z *v2t, int *ldv2t, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *info) noexcept nogil +cdef void zung2l(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil +cdef void zung2r(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil +cdef void zungbr(char *vect, int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil +cdef void zunghr(int *n, int *ilo, int *ihi, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil +cdef void zungl2(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil +cdef void zunglq(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil +cdef void zungql(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil +cdef void zungqr(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil +cdef void zungr2(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil +cdef void zungrq(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil +cdef void zungtr(char *uplo, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil +cdef void zunm2l(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil +cdef void zunm2r(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil +cdef void zunmbr(char *vect, char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil +cdef void zunmhr(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil +cdef void zunml2(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil +cdef void zunmlq(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil +cdef void zunmql(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil +cdef void zunmqr(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil +cdef void zunmr2(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil +cdef void zunmr3(char *side, char *trans, int *m, int *n, int *k, int *l, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil +cdef void zunmrq(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil +cdef void zunmrz(char *side, char *trans, int *m, int *n, int *k, int *l, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil +cdef void zunmtr(char *side, char *uplo, char *trans, int *m, int *n, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil +cdef void zupgtr(char *uplo, int *n, z *ap, z *tau, z *q, int *ldq, z *work, int *info) noexcept nogil +cdef void zupmtr(char *side, char *uplo, char *trans, int *m, int *n, z *ap, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/cython_lapack.pyx b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/cython_lapack.pyx new file mode 100644 index 0000000000000000000000000000000000000000..7f9cbfbb519603d4107af51ac353e0650720cf8c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/cython_lapack.pyx @@ -0,0 +1,12045 @@ +# This file was generated by _generate_pyx.py. +# Do not edit this file directly. +""" +LAPACK functions for Cython +=========================== + +Usable from Cython via:: + + cimport scipy.linalg.cython_lapack + +This module provides Cython-level wrappers for all primary routines included +in LAPACK 3.4.0 except for ``zcgesv`` since its interface is not consistent +from LAPACK 3.4.0 to 3.6.0. It also provides some of the +fixed-api auxiliary routines. + +These wrappers do not check for alignment of arrays. +Alignment should be checked before these wrappers are used. + +Raw function pointers (Fortran-style pointer arguments): + +- cbbcsd +- cbdsqr +- cgbbrd +- cgbcon +- cgbequ +- cgbequb +- cgbrfs +- cgbsv +- cgbsvx +- cgbtf2 +- cgbtrf +- cgbtrs +- cgebak +- cgebal +- cgebd2 +- cgebrd +- cgecon +- cgeequ +- cgeequb +- cgees +- cgeesx +- cgeev +- cgeevx +- cgehd2 +- cgehrd +- cgelq2 +- cgelqf +- cgels +- cgelsd +- cgelss +- cgelsy +- cgemqrt +- cgeql2 +- cgeqlf +- cgeqp3 +- cgeqr2 +- cgeqr2p +- cgeqrf +- cgeqrfp +- cgeqrt +- cgeqrt2 +- cgeqrt3 +- cgerfs +- cgerq2 +- cgerqf +- cgesc2 +- cgesdd +- cgesv +- cgesvd +- cgesvx +- cgetc2 +- cgetf2 +- cgetrf +- cgetri +- cgetrs +- cggbak +- cggbal +- cgges +- cggesx +- cggev +- cggevx +- cggglm +- cgghrd +- cgglse +- cggqrf +- cggrqf +- cgtcon +- cgtrfs +- cgtsv +- cgtsvx +- cgttrf +- cgttrs +- cgtts2 +- chbev +- chbevd +- chbevx +- chbgst +- chbgv +- chbgvd +- chbgvx +- chbtrd +- checon +- cheequb +- cheev +- cheevd +- cheevr +- cheevx +- chegs2 +- chegst +- chegv +- chegvd +- chegvx +- cherfs +- chesv +- chesvx +- cheswapr +- chetd2 +- chetf2 +- chetrd +- chetrf +- chetri +- chetri2 +- chetri2x +- chetrs +- chetrs2 +- chfrk +- chgeqz +- chla_transtype +- chpcon +- chpev +- chpevd +- chpevx +- chpgst +- chpgv +- chpgvd +- chpgvx +- chprfs +- chpsv +- chpsvx +- chptrd +- chptrf +- chptri +- chptrs +- chsein +- chseqr +- clabrd +- clacgv +- clacn2 +- clacon +- clacp2 +- clacpy +- clacrm +- clacrt +- cladiv +- claed0 +- claed7 +- claed8 +- claein +- claesy +- claev2 +- clag2z +- clags2 +- clagtm +- clahef +- clahqr +- clahr2 +- claic1 +- clals0 +- clalsa +- clalsd +- clangb +- clange +- clangt +- clanhb +- clanhe +- clanhf +- clanhp +- clanhs +- clanht +- clansb +- clansp +- clansy +- clantb +- clantp +- clantr +- clapll +- clapmr +- clapmt +- claqgb +- claqge +- claqhb +- claqhe +- claqhp +- claqp2 +- claqps +- claqr0 +- claqr1 +- claqr2 +- claqr3 +- claqr4 +- claqr5 +- claqsb +- claqsp +- claqsy +- clar1v +- clar2v +- clarcm +- clarf +- clarfb +- clarfg +- clarfgp +- clarft +- clarfx +- clargv +- clarnv +- clarrv +- clartg +- clartv +- clarz +- clarzb +- clarzt +- clascl +- claset +- clasr +- classq +- claswp +- clasyf +- clatbs +- clatdf +- clatps +- clatrd +- clatrs +- clatrz +- clauu2 +- clauum +- cpbcon +- cpbequ +- cpbrfs +- cpbstf +- cpbsv +- cpbsvx +- cpbtf2 +- cpbtrf +- cpbtrs +- cpftrf +- cpftri +- cpftrs +- cpocon +- cpoequ +- cpoequb +- cporfs +- cposv +- cposvx +- cpotf2 +- cpotrf +- cpotri +- cpotrs +- cppcon +- cppequ +- cpprfs +- cppsv +- cppsvx +- cpptrf +- cpptri +- cpptrs +- cpstf2 +- cpstrf +- cptcon +- cpteqr +- cptrfs +- cptsv +- cptsvx +- cpttrf +- cpttrs +- cptts2 +- crot +- cspcon +- cspmv +- cspr +- csprfs +- cspsv +- cspsvx +- csptrf +- csptri +- csptrs +- csrscl +- cstedc +- cstegr +- cstein +- cstemr +- csteqr +- csycon +- csyconv +- csyequb +- csymv +- csyr +- csyrfs +- csysv +- csysvx +- csyswapr +- csytf2 +- csytrf +- csytri +- csytri2 +- csytri2x +- csytrs +- csytrs2 +- ctbcon +- ctbrfs +- ctbtrs +- ctfsm +- ctftri +- ctfttp +- ctfttr +- ctgevc +- ctgex2 +- ctgexc +- ctgsen +- ctgsja +- ctgsna +- ctgsy2 +- ctgsyl +- ctpcon +- ctpmqrt +- ctpqrt +- ctpqrt2 +- ctprfb +- ctprfs +- ctptri +- ctptrs +- ctpttf +- ctpttr +- ctrcon +- ctrevc +- ctrexc +- ctrrfs +- ctrsen +- ctrsna +- ctrsyl +- ctrti2 +- ctrtri +- ctrtrs +- ctrttf +- ctrttp +- ctzrzf +- cunbdb +- cuncsd +- cung2l +- cung2r +- cungbr +- cunghr +- cungl2 +- cunglq +- cungql +- cungqr +- cungr2 +- cungrq +- cungtr +- cunm2l +- cunm2r +- cunmbr +- cunmhr +- cunml2 +- cunmlq +- cunmql +- cunmqr +- cunmr2 +- cunmr3 +- cunmrq +- cunmrz +- cunmtr +- cupgtr +- cupmtr +- dbbcsd +- dbdsdc +- dbdsqr +- ddisna +- dgbbrd +- dgbcon +- dgbequ +- dgbequb +- dgbrfs +- dgbsv +- dgbsvx +- dgbtf2 +- dgbtrf +- dgbtrs +- dgebak +- dgebal +- dgebd2 +- dgebrd +- dgecon +- dgeequ +- dgeequb +- dgees +- dgeesx +- dgeev +- dgeevx +- dgehd2 +- dgehrd +- dgejsv +- dgelq2 +- dgelqf +- dgels +- dgelsd +- dgelss +- dgelsy +- dgemqrt +- dgeql2 +- dgeqlf +- dgeqp3 +- dgeqr2 +- dgeqr2p +- dgeqrf +- dgeqrfp +- dgeqrt +- dgeqrt2 +- dgeqrt3 +- dgerfs +- dgerq2 +- dgerqf +- dgesc2 +- dgesdd +- dgesv +- dgesvd +- dgesvj +- dgesvx +- dgetc2 +- dgetf2 +- dgetrf +- dgetri +- dgetrs +- dggbak +- dggbal +- dgges +- dggesx +- dggev +- dggevx +- dggglm +- dgghrd +- dgglse +- dggqrf +- dggrqf +- dgsvj0 +- dgsvj1 +- dgtcon +- dgtrfs +- dgtsv +- dgtsvx +- dgttrf +- dgttrs +- dgtts2 +- dhgeqz +- dhsein +- dhseqr +- disnan +- dlabad +- dlabrd +- dlacn2 +- dlacon +- dlacpy +- dladiv +- dlae2 +- dlaebz +- dlaed0 +- dlaed1 +- dlaed2 +- dlaed3 +- dlaed4 +- dlaed5 +- dlaed6 +- dlaed7 +- dlaed8 +- dlaed9 +- dlaeda +- dlaein +- dlaev2 +- dlaexc +- dlag2 +- dlag2s +- dlags2 +- dlagtf +- dlagtm +- dlagts +- dlagv2 +- dlahqr +- dlahr2 +- dlaic1 +- dlaln2 +- dlals0 +- dlalsa +- dlalsd +- dlamch +- dlamrg +- dlaneg +- dlangb +- dlange +- dlangt +- dlanhs +- dlansb +- dlansf +- dlansp +- dlanst +- dlansy +- dlantb +- dlantp +- dlantr +- dlanv2 +- dlapll +- dlapmr +- dlapmt +- dlapy2 +- dlapy3 +- dlaqgb +- dlaqge +- dlaqp2 +- dlaqps +- dlaqr0 +- dlaqr1 +- dlaqr2 +- dlaqr3 +- dlaqr4 +- dlaqr5 +- dlaqsb +- dlaqsp +- dlaqsy +- dlaqtr +- dlar1v +- dlar2v +- dlarf +- dlarfb +- dlarfg +- dlarfgp +- dlarft +- dlarfx +- dlargv +- dlarnv +- dlarra +- dlarrb +- dlarrc +- dlarrd +- dlarre +- dlarrf +- dlarrj +- dlarrk +- dlarrr +- dlarrv +- dlartg +- dlartgp +- dlartgs +- dlartv +- dlaruv +- dlarz +- dlarzb +- dlarzt +- dlas2 +- dlascl +- dlasd0 +- dlasd1 +- dlasd2 +- dlasd3 +- dlasd4 +- dlasd5 +- dlasd6 +- dlasd7 +- dlasd8 +- dlasda +- dlasdq +- dlasdt +- dlaset +- dlasq1 +- dlasq2 +- dlasq3 +- dlasq4 +- dlasq6 +- dlasr +- dlasrt +- dlassq +- dlasv2 +- dlaswp +- dlasy2 +- dlasyf +- dlat2s +- dlatbs +- dlatdf +- dlatps +- dlatrd +- dlatrs +- dlatrz +- dlauu2 +- dlauum +- dopgtr +- dopmtr +- dorbdb +- dorcsd +- dorg2l +- dorg2r +- dorgbr +- dorghr +- dorgl2 +- dorglq +- dorgql +- dorgqr +- dorgr2 +- dorgrq +- dorgtr +- dorm2l +- dorm2r +- dormbr +- dormhr +- dorml2 +- dormlq +- dormql +- dormqr +- dormr2 +- dormr3 +- dormrq +- dormrz +- dormtr +- dpbcon +- dpbequ +- dpbrfs +- dpbstf +- dpbsv +- dpbsvx +- dpbtf2 +- dpbtrf +- dpbtrs +- dpftrf +- dpftri +- dpftrs +- dpocon +- dpoequ +- dpoequb +- dporfs +- dposv +- dposvx +- dpotf2 +- dpotrf +- dpotri +- dpotrs +- dppcon +- dppequ +- dpprfs +- dppsv +- dppsvx +- dpptrf +- dpptri +- dpptrs +- dpstf2 +- dpstrf +- dptcon +- dpteqr +- dptrfs +- dptsv +- dptsvx +- dpttrf +- dpttrs +- dptts2 +- drscl +- dsbev +- dsbevd +- dsbevx +- dsbgst +- dsbgv +- dsbgvd +- dsbgvx +- dsbtrd +- dsfrk +- dsgesv +- dspcon +- dspev +- dspevd +- dspevx +- dspgst +- dspgv +- dspgvd +- dspgvx +- dsposv +- dsprfs +- dspsv +- dspsvx +- dsptrd +- dsptrf +- dsptri +- dsptrs +- dstebz +- dstedc +- dstegr +- dstein +- dstemr +- dsteqr +- dsterf +- dstev +- dstevd +- dstevr +- dstevx +- dsycon +- dsyconv +- dsyequb +- dsyev +- dsyevd +- dsyevr +- dsyevx +- dsygs2 +- dsygst +- dsygv +- dsygvd +- dsygvx +- dsyrfs +- dsysv +- dsysvx +- dsyswapr +- dsytd2 +- dsytf2 +- dsytrd +- dsytrf +- dsytri +- dsytri2 +- dsytri2x +- dsytrs +- dsytrs2 +- dtbcon +- dtbrfs +- dtbtrs +- dtfsm +- dtftri +- dtfttp +- dtfttr +- dtgevc +- dtgex2 +- dtgexc +- dtgsen +- dtgsja +- dtgsna +- dtgsy2 +- dtgsyl +- dtpcon +- dtpmqrt +- dtpqrt +- dtpqrt2 +- dtprfb +- dtprfs +- dtptri +- dtptrs +- dtpttf +- dtpttr +- dtrcon +- dtrevc +- dtrexc +- dtrrfs +- dtrsen +- dtrsna +- dtrsyl +- dtrti2 +- dtrtri +- dtrtrs +- dtrttf +- dtrttp +- dtzrzf +- dzsum1 +- icmax1 +- ieeeck +- ilaclc +- ilaclr +- iladiag +- iladlc +- iladlr +- ilaprec +- ilaslc +- ilaslr +- ilatrans +- ilauplo +- ilaver +- ilazlc +- ilazlr +- izmax1 +- sbbcsd +- sbdsdc +- sbdsqr +- scsum1 +- sdisna +- sgbbrd +- sgbcon +- sgbequ +- sgbequb +- sgbrfs +- sgbsv +- sgbsvx +- sgbtf2 +- sgbtrf +- sgbtrs +- sgebak +- sgebal +- sgebd2 +- sgebrd +- sgecon +- sgeequ +- sgeequb +- sgees +- sgeesx +- sgeev +- sgeevx +- sgehd2 +- sgehrd +- sgejsv +- sgelq2 +- sgelqf +- sgels +- sgelsd +- sgelss +- sgelsy +- sgemqrt +- sgeql2 +- sgeqlf +- sgeqp3 +- sgeqr2 +- sgeqr2p +- sgeqrf +- sgeqrfp +- sgeqrt +- sgeqrt2 +- sgeqrt3 +- sgerfs +- sgerq2 +- sgerqf +- sgesc2 +- sgesdd +- sgesv +- sgesvd +- sgesvj +- sgesvx +- sgetc2 +- sgetf2 +- sgetrf +- sgetri +- sgetrs +- sggbak +- sggbal +- sgges +- sggesx +- sggev +- sggevx +- sggglm +- sgghrd +- sgglse +- sggqrf +- sggrqf +- sgsvj0 +- sgsvj1 +- sgtcon +- sgtrfs +- sgtsv +- sgtsvx +- sgttrf +- sgttrs +- sgtts2 +- shgeqz +- shsein +- shseqr +- slabad +- slabrd +- slacn2 +- slacon +- slacpy +- sladiv +- slae2 +- slaebz +- slaed0 +- slaed1 +- slaed2 +- slaed3 +- slaed4 +- slaed5 +- slaed6 +- slaed7 +- slaed8 +- slaed9 +- slaeda +- slaein +- slaev2 +- slaexc +- slag2 +- slag2d +- slags2 +- slagtf +- slagtm +- slagts +- slagv2 +- slahqr +- slahr2 +- slaic1 +- slaln2 +- slals0 +- slalsa +- slalsd +- slamch +- slamrg +- slangb +- slange +- slangt +- slanhs +- slansb +- slansf +- slansp +- slanst +- slansy +- slantb +- slantp +- slantr +- slanv2 +- slapll +- slapmr +- slapmt +- slapy2 +- slapy3 +- slaqgb +- slaqge +- slaqp2 +- slaqps +- slaqr0 +- slaqr1 +- slaqr2 +- slaqr3 +- slaqr4 +- slaqr5 +- slaqsb +- slaqsp +- slaqsy +- slaqtr +- slar1v +- slar2v +- slarf +- slarfb +- slarfg +- slarfgp +- slarft +- slarfx +- slargv +- slarnv +- slarra +- slarrb +- slarrc +- slarrd +- slarre +- slarrf +- slarrj +- slarrk +- slarrr +- slarrv +- slartg +- slartgp +- slartgs +- slartv +- slaruv +- slarz +- slarzb +- slarzt +- slas2 +- slascl +- slasd0 +- slasd1 +- slasd2 +- slasd3 +- slasd4 +- slasd5 +- slasd6 +- slasd7 +- slasd8 +- slasda +- slasdq +- slasdt +- slaset +- slasq1 +- slasq2 +- slasq3 +- slasq4 +- slasq6 +- slasr +- slasrt +- slassq +- slasv2 +- slaswp +- slasy2 +- slasyf +- slatbs +- slatdf +- slatps +- slatrd +- slatrs +- slatrz +- slauu2 +- slauum +- sopgtr +- sopmtr +- sorbdb +- sorcsd +- sorg2l +- sorg2r +- sorgbr +- sorghr +- sorgl2 +- sorglq +- sorgql +- sorgqr +- sorgr2 +- sorgrq +- sorgtr +- sorm2l +- sorm2r +- sormbr +- sormhr +- sorml2 +- sormlq +- sormql +- sormqr +- sormr2 +- sormr3 +- sormrq +- sormrz +- sormtr +- spbcon +- spbequ +- spbrfs +- spbstf +- spbsv +- spbsvx +- spbtf2 +- spbtrf +- spbtrs +- spftrf +- spftri +- spftrs +- spocon +- spoequ +- spoequb +- sporfs +- sposv +- sposvx +- spotf2 +- spotrf +- spotri +- spotrs +- sppcon +- sppequ +- spprfs +- sppsv +- sppsvx +- spptrf +- spptri +- spptrs +- spstf2 +- spstrf +- sptcon +- spteqr +- sptrfs +- sptsv +- sptsvx +- spttrf +- spttrs +- sptts2 +- srscl +- ssbev +- ssbevd +- ssbevx +- ssbgst +- ssbgv +- ssbgvd +- ssbgvx +- ssbtrd +- ssfrk +- sspcon +- sspev +- sspevd +- sspevx +- sspgst +- sspgv +- sspgvd +- sspgvx +- ssprfs +- sspsv +- sspsvx +- ssptrd +- ssptrf +- ssptri +- ssptrs +- sstebz +- sstedc +- sstegr +- sstein +- sstemr +- ssteqr +- ssterf +- sstev +- sstevd +- sstevr +- sstevx +- ssycon +- ssyconv +- ssyequb +- ssyev +- ssyevd +- ssyevr +- ssyevx +- ssygs2 +- ssygst +- ssygv +- ssygvd +- ssygvx +- ssyrfs +- ssysv +- ssysvx +- ssyswapr +- ssytd2 +- ssytf2 +- ssytrd +- ssytrf +- ssytri +- ssytri2 +- ssytri2x +- ssytrs +- ssytrs2 +- stbcon +- stbrfs +- stbtrs +- stfsm +- stftri +- stfttp +- stfttr +- stgevc +- stgex2 +- stgexc +- stgsen +- stgsja +- stgsna +- stgsy2 +- stgsyl +- stpcon +- stpmqrt +- stpqrt +- stpqrt2 +- stprfb +- stprfs +- stptri +- stptrs +- stpttf +- stpttr +- strcon +- strevc +- strexc +- strrfs +- strsen +- strsna +- strsyl +- strti2 +- strtri +- strtrs +- strttf +- strttp +- stzrzf +- xerbla_array +- zbbcsd +- zbdsqr +- zcgesv +- zcposv +- zdrscl +- zgbbrd +- zgbcon +- zgbequ +- zgbequb +- zgbrfs +- zgbsv +- zgbsvx +- zgbtf2 +- zgbtrf +- zgbtrs +- zgebak +- zgebal +- zgebd2 +- zgebrd +- zgecon +- zgeequ +- zgeequb +- zgees +- zgeesx +- zgeev +- zgeevx +- zgehd2 +- zgehrd +- zgelq2 +- zgelqf +- zgels +- zgelsd +- zgelss +- zgelsy +- zgemqrt +- zgeql2 +- zgeqlf +- zgeqp3 +- zgeqr2 +- zgeqr2p +- zgeqrf +- zgeqrfp +- zgeqrt +- zgeqrt2 +- zgeqrt3 +- zgerfs +- zgerq2 +- zgerqf +- zgesc2 +- zgesdd +- zgesv +- zgesvd +- zgesvx +- zgetc2 +- zgetf2 +- zgetrf +- zgetri +- zgetrs +- zggbak +- zggbal +- zgges +- zggesx +- zggev +- zggevx +- zggglm +- zgghrd +- zgglse +- zggqrf +- zggrqf +- zgtcon +- zgtrfs +- zgtsv +- zgtsvx +- zgttrf +- zgttrs +- zgtts2 +- zhbev +- zhbevd +- zhbevx +- zhbgst +- zhbgv +- zhbgvd +- zhbgvx +- zhbtrd +- zhecon +- zheequb +- zheev +- zheevd +- zheevr +- zheevx +- zhegs2 +- zhegst +- zhegv +- zhegvd +- zhegvx +- zherfs +- zhesv +- zhesvx +- zheswapr +- zhetd2 +- zhetf2 +- zhetrd +- zhetrf +- zhetri +- zhetri2 +- zhetri2x +- zhetrs +- zhetrs2 +- zhfrk +- zhgeqz +- zhpcon +- zhpev +- zhpevd +- zhpevx +- zhpgst +- zhpgv +- zhpgvd +- zhpgvx +- zhprfs +- zhpsv +- zhpsvx +- zhptrd +- zhptrf +- zhptri +- zhptrs +- zhsein +- zhseqr +- zlabrd +- zlacgv +- zlacn2 +- zlacon +- zlacp2 +- zlacpy +- zlacrm +- zlacrt +- zladiv +- zlaed0 +- zlaed7 +- zlaed8 +- zlaein +- zlaesy +- zlaev2 +- zlag2c +- zlags2 +- zlagtm +- zlahef +- zlahqr +- zlahr2 +- zlaic1 +- zlals0 +- zlalsa +- zlalsd +- zlangb +- zlange +- zlangt +- zlanhb +- zlanhe +- zlanhf +- zlanhp +- zlanhs +- zlanht +- zlansb +- zlansp +- zlansy +- zlantb +- zlantp +- zlantr +- zlapll +- zlapmr +- zlapmt +- zlaqgb +- zlaqge +- zlaqhb +- zlaqhe +- zlaqhp +- zlaqp2 +- zlaqps +- zlaqr0 +- zlaqr1 +- zlaqr2 +- zlaqr3 +- zlaqr4 +- zlaqr5 +- zlaqsb +- zlaqsp +- zlaqsy +- zlar1v +- zlar2v +- zlarcm +- zlarf +- zlarfb +- zlarfg +- zlarfgp +- zlarft +- zlarfx +- zlargv +- zlarnv +- zlarrv +- zlartg +- zlartv +- zlarz +- zlarzb +- zlarzt +- zlascl +- zlaset +- zlasr +- zlassq +- zlaswp +- zlasyf +- zlat2c +- zlatbs +- zlatdf +- zlatps +- zlatrd +- zlatrs +- zlatrz +- zlauu2 +- zlauum +- zpbcon +- zpbequ +- zpbrfs +- zpbstf +- zpbsv +- zpbsvx +- zpbtf2 +- zpbtrf +- zpbtrs +- zpftrf +- zpftri +- zpftrs +- zpocon +- zpoequ +- zpoequb +- zporfs +- zposv +- zposvx +- zpotf2 +- zpotrf +- zpotri +- zpotrs +- zppcon +- zppequ +- zpprfs +- zppsv +- zppsvx +- zpptrf +- zpptri +- zpptrs +- zpstf2 +- zpstrf +- zptcon +- zpteqr +- zptrfs +- zptsv +- zptsvx +- zpttrf +- zpttrs +- zptts2 +- zrot +- zspcon +- zspmv +- zspr +- zsprfs +- zspsv +- zspsvx +- zsptrf +- zsptri +- zsptrs +- zstedc +- zstegr +- zstein +- zstemr +- zsteqr +- zsycon +- zsyconv +- zsyequb +- zsymv +- zsyr +- zsyrfs +- zsysv +- zsysvx +- zsyswapr +- zsytf2 +- zsytrf +- zsytri +- zsytri2 +- zsytri2x +- zsytrs +- zsytrs2 +- ztbcon +- ztbrfs +- ztbtrs +- ztfsm +- ztftri +- ztfttp +- ztfttr +- ztgevc +- ztgex2 +- ztgexc +- ztgsen +- ztgsja +- ztgsna +- ztgsy2 +- ztgsyl +- ztpcon +- ztpmqrt +- ztpqrt +- ztpqrt2 +- ztprfb +- ztprfs +- ztptri +- ztptrs +- ztpttf +- ztpttr +- ztrcon +- ztrevc +- ztrexc +- ztrrfs +- ztrsen +- ztrsna +- ztrsyl +- ztrti2 +- ztrtri +- ztrtrs +- ztrttf +- ztrttp +- ztzrzf +- zunbdb +- zuncsd +- zung2l +- zung2r +- zungbr +- zunghr +- zungl2 +- zunglq +- zungql +- zungqr +- zungr2 +- zungrq +- zungtr +- zunm2l +- zunm2r +- zunmbr +- zunmhr +- zunml2 +- zunmlq +- zunmql +- zunmqr +- zunmr2 +- zunmr3 +- zunmrq +- zunmrz +- zunmtr +- zupgtr +- zupmtr + + +""" + +# Within SciPy, these wrappers can be used via relative or absolute cimport. +# Examples: +# from ..linalg cimport cython_lapack +# from scipy.linalg cimport cython_lapack +# cimport scipy.linalg.cython_lapack as cython_lapack +# cimport ..linalg.cython_lapack as cython_lapack + +# Within SciPy, if LAPACK functions are needed in C/C++/Fortran, +# these wrappers should not be used. +# The original libraries should be linked directly. + +cdef extern from "fortran_defs.h": + pass + +from numpy cimport npy_complex64, npy_complex128 + +cdef extern from "_lapack_subroutines.h": + # Function pointer type declarations for + # gees and gges families of functions. + ctypedef bint _cselect1(npy_complex64*) + ctypedef bint _cselect2(npy_complex64*, npy_complex64*) + ctypedef bint _dselect2(d*, d*) + ctypedef bint _dselect3(d*, d*, d*) + ctypedef bint _sselect2(s*, s*) + ctypedef bint _sselect3(s*, s*, s*) + ctypedef bint _zselect1(npy_complex128*) + ctypedef bint _zselect2(npy_complex128*, npy_complex128*) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cbbcsd "BLAS_FUNC(cbbcsd)"(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, s *theta, s *phi, npy_complex64 *u1, int *ldu1, npy_complex64 *u2, int *ldu2, npy_complex64 *v1t, int *ldv1t, npy_complex64 *v2t, int *ldv2t, s *b11d, s *b11e, s *b12d, s *b12e, s *b21d, s *b21e, s *b22d, s *b22e, s *rwork, int *lrwork, int *info) nogil +cdef void cbbcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, s *theta, s *phi, c *u1, int *ldu1, c *u2, int *ldu2, c *v1t, int *ldv1t, c *v2t, int *ldv2t, s *b11d, s *b11e, s *b12d, s *b12e, s *b21d, s *b21e, s *b22d, s *b22e, s *rwork, int *lrwork, int *info) noexcept nogil: + + _fortran_cbbcsd(jobu1, jobu2, jobv1t, jobv2t, trans, m, p, q, theta, phi, u1, ldu1, u2, ldu2, v1t, ldv1t, v2t, ldv2t, b11d, b11e, b12d, b12e, b21d, b21e, b22d, b22e, rwork, lrwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cbdsqr "BLAS_FUNC(cbdsqr)"(char *uplo, int *n, int *ncvt, int *nru, int *ncc, s *d, s *e, npy_complex64 *vt, int *ldvt, npy_complex64 *u, int *ldu, npy_complex64 *c, int *ldc, s *rwork, int *info) nogil +cdef void cbdsqr(char *uplo, int *n, int *ncvt, int *nru, int *ncc, s *d, s *e, c *vt, int *ldvt, c *u, int *ldu, c *c, int *ldc, s *rwork, int *info) noexcept nogil: + + _fortran_cbdsqr(uplo, n, ncvt, nru, ncc, d, e, vt, ldvt, u, ldu, c, ldc, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgbbrd "BLAS_FUNC(cgbbrd)"(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, npy_complex64 *ab, int *ldab, s *d, s *e, npy_complex64 *q, int *ldq, npy_complex64 *pt, int *ldpt, npy_complex64 *c, int *ldc, npy_complex64 *work, s *rwork, int *info) nogil +cdef void cgbbrd(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, c *ab, int *ldab, s *d, s *e, c *q, int *ldq, c *pt, int *ldpt, c *c, int *ldc, c *work, s *rwork, int *info) noexcept nogil: + + _fortran_cgbbrd(vect, m, n, ncc, kl, ku, ab, ldab, d, e, q, ldq, pt, ldpt, c, ldc, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgbcon "BLAS_FUNC(cgbcon)"(char *norm, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, int *ipiv, s *anorm, s *rcond, npy_complex64 *work, s *rwork, int *info) nogil +cdef void cgbcon(char *norm, int *n, int *kl, int *ku, c *ab, int *ldab, int *ipiv, s *anorm, s *rcond, c *work, s *rwork, int *info) noexcept nogil: + + _fortran_cgbcon(norm, n, kl, ku, ab, ldab, ipiv, anorm, rcond, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgbequ "BLAS_FUNC(cgbequ)"(int *m, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) nogil +cdef void cgbequ(int *m, int *n, int *kl, int *ku, c *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil: + + _fortran_cgbequ(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgbequb "BLAS_FUNC(cgbequb)"(int *m, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) nogil +cdef void cgbequb(int *m, int *n, int *kl, int *ku, c *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil: + + _fortran_cgbequb(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgbrfs "BLAS_FUNC(cgbrfs)"(char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *afb, int *ldafb, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil +cdef void cgbrfs(char *trans, int *n, int *kl, int *ku, int *nrhs, c *ab, int *ldab, c *afb, int *ldafb, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil: + + _fortran_cgbrfs(trans, n, kl, ku, nrhs, ab, ldab, afb, ldafb, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgbsv "BLAS_FUNC(cgbsv)"(int *n, int *kl, int *ku, int *nrhs, npy_complex64 *ab, int *ldab, int *ipiv, npy_complex64 *b, int *ldb, int *info) nogil +cdef void cgbsv(int *n, int *kl, int *ku, int *nrhs, c *ab, int *ldab, int *ipiv, c *b, int *ldb, int *info) noexcept nogil: + + _fortran_cgbsv(n, kl, ku, nrhs, ab, ldab, ipiv, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgbsvx "BLAS_FUNC(cgbsvx)"(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *afb, int *ldafb, int *ipiv, char *equed, s *r, s *c, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil +cdef void cgbsvx(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, c *ab, int *ldab, c *afb, int *ldafb, int *ipiv, char *equed, s *r, s *c, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil: + + _fortran_cgbsvx(fact, trans, n, kl, ku, nrhs, ab, ldab, afb, ldafb, ipiv, equed, r, c, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgbtf2 "BLAS_FUNC(cgbtf2)"(int *m, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, int *ipiv, int *info) nogil +cdef void cgbtf2(int *m, int *n, int *kl, int *ku, c *ab, int *ldab, int *ipiv, int *info) noexcept nogil: + + _fortran_cgbtf2(m, n, kl, ku, ab, ldab, ipiv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgbtrf "BLAS_FUNC(cgbtrf)"(int *m, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, int *ipiv, int *info) nogil +cdef void cgbtrf(int *m, int *n, int *kl, int *ku, c *ab, int *ldab, int *ipiv, int *info) noexcept nogil: + + _fortran_cgbtrf(m, n, kl, ku, ab, ldab, ipiv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgbtrs "BLAS_FUNC(cgbtrs)"(char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex64 *ab, int *ldab, int *ipiv, npy_complex64 *b, int *ldb, int *info) nogil +cdef void cgbtrs(char *trans, int *n, int *kl, int *ku, int *nrhs, c *ab, int *ldab, int *ipiv, c *b, int *ldb, int *info) noexcept nogil: + + _fortran_cgbtrs(trans, n, kl, ku, nrhs, ab, ldab, ipiv, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgebak "BLAS_FUNC(cgebak)"(char *job, char *side, int *n, int *ilo, int *ihi, s *scale, int *m, npy_complex64 *v, int *ldv, int *info) nogil +cdef void cgebak(char *job, char *side, int *n, int *ilo, int *ihi, s *scale, int *m, c *v, int *ldv, int *info) noexcept nogil: + + _fortran_cgebak(job, side, n, ilo, ihi, scale, m, v, ldv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgebal "BLAS_FUNC(cgebal)"(char *job, int *n, npy_complex64 *a, int *lda, int *ilo, int *ihi, s *scale, int *info) nogil +cdef void cgebal(char *job, int *n, c *a, int *lda, int *ilo, int *ihi, s *scale, int *info) noexcept nogil: + + _fortran_cgebal(job, n, a, lda, ilo, ihi, scale, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgebd2 "BLAS_FUNC(cgebd2)"(int *m, int *n, npy_complex64 *a, int *lda, s *d, s *e, npy_complex64 *tauq, npy_complex64 *taup, npy_complex64 *work, int *info) nogil +cdef void cgebd2(int *m, int *n, c *a, int *lda, s *d, s *e, c *tauq, c *taup, c *work, int *info) noexcept nogil: + + _fortran_cgebd2(m, n, a, lda, d, e, tauq, taup, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgebrd "BLAS_FUNC(cgebrd)"(int *m, int *n, npy_complex64 *a, int *lda, s *d, s *e, npy_complex64 *tauq, npy_complex64 *taup, npy_complex64 *work, int *lwork, int *info) nogil +cdef void cgebrd(int *m, int *n, c *a, int *lda, s *d, s *e, c *tauq, c *taup, c *work, int *lwork, int *info) noexcept nogil: + + _fortran_cgebrd(m, n, a, lda, d, e, tauq, taup, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgecon "BLAS_FUNC(cgecon)"(char *norm, int *n, npy_complex64 *a, int *lda, s *anorm, s *rcond, npy_complex64 *work, s *rwork, int *info) nogil +cdef void cgecon(char *norm, int *n, c *a, int *lda, s *anorm, s *rcond, c *work, s *rwork, int *info) noexcept nogil: + + _fortran_cgecon(norm, n, a, lda, anorm, rcond, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgeequ "BLAS_FUNC(cgeequ)"(int *m, int *n, npy_complex64 *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) nogil +cdef void cgeequ(int *m, int *n, c *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil: + + _fortran_cgeequ(m, n, a, lda, r, c, rowcnd, colcnd, amax, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgeequb "BLAS_FUNC(cgeequb)"(int *m, int *n, npy_complex64 *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) nogil +cdef void cgeequb(int *m, int *n, c *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil: + + _fortran_cgeequb(m, n, a, lda, r, c, rowcnd, colcnd, amax, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgees "BLAS_FUNC(cgees)"(char *jobvs, char *sort, _cselect1 *select, int *n, npy_complex64 *a, int *lda, int *sdim, npy_complex64 *w, npy_complex64 *vs, int *ldvs, npy_complex64 *work, int *lwork, s *rwork, bint *bwork, int *info) nogil +cdef void cgees(char *jobvs, char *sort, cselect1 *select, int *n, c *a, int *lda, int *sdim, c *w, c *vs, int *ldvs, c *work, int *lwork, s *rwork, bint *bwork, int *info) noexcept nogil: + + _fortran_cgees(jobvs, sort, <_cselect1*>select, n, a, lda, sdim, w, vs, ldvs, work, lwork, rwork, bwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgeesx "BLAS_FUNC(cgeesx)"(char *jobvs, char *sort, _cselect1 *select, char *sense, int *n, npy_complex64 *a, int *lda, int *sdim, npy_complex64 *w, npy_complex64 *vs, int *ldvs, s *rconde, s *rcondv, npy_complex64 *work, int *lwork, s *rwork, bint *bwork, int *info) nogil +cdef void cgeesx(char *jobvs, char *sort, cselect1 *select, char *sense, int *n, c *a, int *lda, int *sdim, c *w, c *vs, int *ldvs, s *rconde, s *rcondv, c *work, int *lwork, s *rwork, bint *bwork, int *info) noexcept nogil: + + _fortran_cgeesx(jobvs, sort, <_cselect1*>select, sense, n, a, lda, sdim, w, vs, ldvs, rconde, rcondv, work, lwork, rwork, bwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgeev "BLAS_FUNC(cgeev)"(char *jobvl, char *jobvr, int *n, npy_complex64 *a, int *lda, npy_complex64 *w, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, npy_complex64 *work, int *lwork, s *rwork, int *info) nogil +cdef void cgeev(char *jobvl, char *jobvr, int *n, c *a, int *lda, c *w, c *vl, int *ldvl, c *vr, int *ldvr, c *work, int *lwork, s *rwork, int *info) noexcept nogil: + + _fortran_cgeev(jobvl, jobvr, n, a, lda, w, vl, ldvl, vr, ldvr, work, lwork, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgeevx "BLAS_FUNC(cgeevx)"(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, npy_complex64 *a, int *lda, npy_complex64 *w, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, int *ilo, int *ihi, s *scale, s *abnrm, s *rconde, s *rcondv, npy_complex64 *work, int *lwork, s *rwork, int *info) nogil +cdef void cgeevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, c *a, int *lda, c *w, c *vl, int *ldvl, c *vr, int *ldvr, int *ilo, int *ihi, s *scale, s *abnrm, s *rconde, s *rcondv, c *work, int *lwork, s *rwork, int *info) noexcept nogil: + + _fortran_cgeevx(balanc, jobvl, jobvr, sense, n, a, lda, w, vl, ldvl, vr, ldvr, ilo, ihi, scale, abnrm, rconde, rcondv, work, lwork, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgehd2 "BLAS_FUNC(cgehd2)"(int *n, int *ilo, int *ihi, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info) nogil +cdef void cgehd2(int *n, int *ilo, int *ihi, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil: + + _fortran_cgehd2(n, ilo, ihi, a, lda, tau, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgehrd "BLAS_FUNC(cgehrd)"(int *n, int *ilo, int *ihi, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil +cdef void cgehrd(int *n, int *ilo, int *ihi, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil: + + _fortran_cgehrd(n, ilo, ihi, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgelq2 "BLAS_FUNC(cgelq2)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info) nogil +cdef void cgelq2(int *m, int *n, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil: + + _fortran_cgelq2(m, n, a, lda, tau, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgelqf "BLAS_FUNC(cgelqf)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil +cdef void cgelqf(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil: + + _fortran_cgelqf(m, n, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgels "BLAS_FUNC(cgels)"(char *trans, int *m, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *work, int *lwork, int *info) nogil +cdef void cgels(char *trans, int *m, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, c *work, int *lwork, int *info) noexcept nogil: + + _fortran_cgels(trans, m, n, nrhs, a, lda, b, ldb, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgelsd "BLAS_FUNC(cgelsd)"(int *m, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, s *s, s *rcond, int *rank, npy_complex64 *work, int *lwork, s *rwork, int *iwork, int *info) nogil +cdef void cgelsd(int *m, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, s *s, s *rcond, int *rank, c *work, int *lwork, s *rwork, int *iwork, int *info) noexcept nogil: + + _fortran_cgelsd(m, n, nrhs, a, lda, b, ldb, s, rcond, rank, work, lwork, rwork, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgelss "BLAS_FUNC(cgelss)"(int *m, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, s *s, s *rcond, int *rank, npy_complex64 *work, int *lwork, s *rwork, int *info) nogil +cdef void cgelss(int *m, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, s *s, s *rcond, int *rank, c *work, int *lwork, s *rwork, int *info) noexcept nogil: + + _fortran_cgelss(m, n, nrhs, a, lda, b, ldb, s, rcond, rank, work, lwork, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgelsy "BLAS_FUNC(cgelsy)"(int *m, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *jpvt, s *rcond, int *rank, npy_complex64 *work, int *lwork, s *rwork, int *info) nogil +cdef void cgelsy(int *m, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, int *jpvt, s *rcond, int *rank, c *work, int *lwork, s *rwork, int *info) noexcept nogil: + + _fortran_cgelsy(m, n, nrhs, a, lda, b, ldb, jpvt, rcond, rank, work, lwork, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgemqrt "BLAS_FUNC(cgemqrt)"(char *side, char *trans, int *m, int *n, int *k, int *nb, npy_complex64 *v, int *ldv, npy_complex64 *t, int *ldt, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info) nogil +cdef void cgemqrt(char *side, char *trans, int *m, int *n, int *k, int *nb, c *v, int *ldv, c *t, int *ldt, c *c, int *ldc, c *work, int *info) noexcept nogil: + + _fortran_cgemqrt(side, trans, m, n, k, nb, v, ldv, t, ldt, c, ldc, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgeql2 "BLAS_FUNC(cgeql2)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info) nogil +cdef void cgeql2(int *m, int *n, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil: + + _fortran_cgeql2(m, n, a, lda, tau, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgeqlf "BLAS_FUNC(cgeqlf)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil +cdef void cgeqlf(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil: + + _fortran_cgeqlf(m, n, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgeqp3 "BLAS_FUNC(cgeqp3)"(int *m, int *n, npy_complex64 *a, int *lda, int *jpvt, npy_complex64 *tau, npy_complex64 *work, int *lwork, s *rwork, int *info) nogil +cdef void cgeqp3(int *m, int *n, c *a, int *lda, int *jpvt, c *tau, c *work, int *lwork, s *rwork, int *info) noexcept nogil: + + _fortran_cgeqp3(m, n, a, lda, jpvt, tau, work, lwork, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgeqr2 "BLAS_FUNC(cgeqr2)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info) nogil +cdef void cgeqr2(int *m, int *n, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil: + + _fortran_cgeqr2(m, n, a, lda, tau, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgeqr2p "BLAS_FUNC(cgeqr2p)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info) nogil +cdef void cgeqr2p(int *m, int *n, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil: + + _fortran_cgeqr2p(m, n, a, lda, tau, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgeqrf "BLAS_FUNC(cgeqrf)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil +cdef void cgeqrf(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil: + + _fortran_cgeqrf(m, n, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgeqrfp "BLAS_FUNC(cgeqrfp)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil +cdef void cgeqrfp(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil: + + _fortran_cgeqrfp(m, n, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgeqrt "BLAS_FUNC(cgeqrt)"(int *m, int *n, int *nb, npy_complex64 *a, int *lda, npy_complex64 *t, int *ldt, npy_complex64 *work, int *info) nogil +cdef void cgeqrt(int *m, int *n, int *nb, c *a, int *lda, c *t, int *ldt, c *work, int *info) noexcept nogil: + + _fortran_cgeqrt(m, n, nb, a, lda, t, ldt, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgeqrt2 "BLAS_FUNC(cgeqrt2)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *t, int *ldt, int *info) nogil +cdef void cgeqrt2(int *m, int *n, c *a, int *lda, c *t, int *ldt, int *info) noexcept nogil: + + _fortran_cgeqrt2(m, n, a, lda, t, ldt, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgeqrt3 "BLAS_FUNC(cgeqrt3)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *t, int *ldt, int *info) nogil +cdef void cgeqrt3(int *m, int *n, c *a, int *lda, c *t, int *ldt, int *info) noexcept nogil: + + _fortran_cgeqrt3(m, n, a, lda, t, ldt, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgerfs "BLAS_FUNC(cgerfs)"(char *trans, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil +cdef void cgerfs(char *trans, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil: + + _fortran_cgerfs(trans, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgerq2 "BLAS_FUNC(cgerq2)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info) nogil +cdef void cgerq2(int *m, int *n, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil: + + _fortran_cgerq2(m, n, a, lda, tau, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgerqf "BLAS_FUNC(cgerqf)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil +cdef void cgerqf(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil: + + _fortran_cgerqf(m, n, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgesc2 "BLAS_FUNC(cgesc2)"(int *n, npy_complex64 *a, int *lda, npy_complex64 *rhs, int *ipiv, int *jpiv, s *scale) nogil +cdef void cgesc2(int *n, c *a, int *lda, c *rhs, int *ipiv, int *jpiv, s *scale) noexcept nogil: + + _fortran_cgesc2(n, a, lda, rhs, ipiv, jpiv, scale) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgesdd "BLAS_FUNC(cgesdd)"(char *jobz, int *m, int *n, npy_complex64 *a, int *lda, s *s, npy_complex64 *u, int *ldu, npy_complex64 *vt, int *ldvt, npy_complex64 *work, int *lwork, s *rwork, int *iwork, int *info) nogil +cdef void cgesdd(char *jobz, int *m, int *n, c *a, int *lda, s *s, c *u, int *ldu, c *vt, int *ldvt, c *work, int *lwork, s *rwork, int *iwork, int *info) noexcept nogil: + + _fortran_cgesdd(jobz, m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork, rwork, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgesv "BLAS_FUNC(cgesv)"(int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, int *info) nogil +cdef void cgesv(int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, int *info) noexcept nogil: + + _fortran_cgesv(n, nrhs, a, lda, ipiv, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgesvd "BLAS_FUNC(cgesvd)"(char *jobu, char *jobvt, int *m, int *n, npy_complex64 *a, int *lda, s *s, npy_complex64 *u, int *ldu, npy_complex64 *vt, int *ldvt, npy_complex64 *work, int *lwork, s *rwork, int *info) nogil +cdef void cgesvd(char *jobu, char *jobvt, int *m, int *n, c *a, int *lda, s *s, c *u, int *ldu, c *vt, int *ldvt, c *work, int *lwork, s *rwork, int *info) noexcept nogil: + + _fortran_cgesvd(jobu, jobvt, m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgesvx "BLAS_FUNC(cgesvx)"(char *fact, char *trans, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, char *equed, s *r, s *c, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil +cdef void cgesvx(char *fact, char *trans, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, char *equed, s *r, s *c, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil: + + _fortran_cgesvx(fact, trans, n, nrhs, a, lda, af, ldaf, ipiv, equed, r, c, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgetc2 "BLAS_FUNC(cgetc2)"(int *n, npy_complex64 *a, int *lda, int *ipiv, int *jpiv, int *info) nogil +cdef void cgetc2(int *n, c *a, int *lda, int *ipiv, int *jpiv, int *info) noexcept nogil: + + _fortran_cgetc2(n, a, lda, ipiv, jpiv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgetf2 "BLAS_FUNC(cgetf2)"(int *m, int *n, npy_complex64 *a, int *lda, int *ipiv, int *info) nogil +cdef void cgetf2(int *m, int *n, c *a, int *lda, int *ipiv, int *info) noexcept nogil: + + _fortran_cgetf2(m, n, a, lda, ipiv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgetrf "BLAS_FUNC(cgetrf)"(int *m, int *n, npy_complex64 *a, int *lda, int *ipiv, int *info) nogil +cdef void cgetrf(int *m, int *n, c *a, int *lda, int *ipiv, int *info) noexcept nogil: + + _fortran_cgetrf(m, n, a, lda, ipiv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgetri "BLAS_FUNC(cgetri)"(int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *lwork, int *info) nogil +cdef void cgetri(int *n, c *a, int *lda, int *ipiv, c *work, int *lwork, int *info) noexcept nogil: + + _fortran_cgetri(n, a, lda, ipiv, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgetrs "BLAS_FUNC(cgetrs)"(char *trans, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, int *info) nogil +cdef void cgetrs(char *trans, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, int *info) noexcept nogil: + + _fortran_cgetrs(trans, n, nrhs, a, lda, ipiv, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cggbak "BLAS_FUNC(cggbak)"(char *job, char *side, int *n, int *ilo, int *ihi, s *lscale, s *rscale, int *m, npy_complex64 *v, int *ldv, int *info) nogil +cdef void cggbak(char *job, char *side, int *n, int *ilo, int *ihi, s *lscale, s *rscale, int *m, c *v, int *ldv, int *info) noexcept nogil: + + _fortran_cggbak(job, side, n, ilo, ihi, lscale, rscale, m, v, ldv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cggbal "BLAS_FUNC(cggbal)"(char *job, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *ilo, int *ihi, s *lscale, s *rscale, s *work, int *info) nogil +cdef void cggbal(char *job, int *n, c *a, int *lda, c *b, int *ldb, int *ilo, int *ihi, s *lscale, s *rscale, s *work, int *info) noexcept nogil: + + _fortran_cggbal(job, n, a, lda, b, ldb, ilo, ihi, lscale, rscale, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgges "BLAS_FUNC(cgges)"(char *jobvsl, char *jobvsr, char *sort, _cselect2 *selctg, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *sdim, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *vsl, int *ldvsl, npy_complex64 *vsr, int *ldvsr, npy_complex64 *work, int *lwork, s *rwork, bint *bwork, int *info) nogil +cdef void cgges(char *jobvsl, char *jobvsr, char *sort, cselect2 *selctg, int *n, c *a, int *lda, c *b, int *ldb, int *sdim, c *alpha, c *beta, c *vsl, int *ldvsl, c *vsr, int *ldvsr, c *work, int *lwork, s *rwork, bint *bwork, int *info) noexcept nogil: + + _fortran_cgges(jobvsl, jobvsr, sort, <_cselect2*>selctg, n, a, lda, b, ldb, sdim, alpha, beta, vsl, ldvsl, vsr, ldvsr, work, lwork, rwork, bwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cggesx "BLAS_FUNC(cggesx)"(char *jobvsl, char *jobvsr, char *sort, _cselect2 *selctg, char *sense, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *sdim, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *vsl, int *ldvsl, npy_complex64 *vsr, int *ldvsr, s *rconde, s *rcondv, npy_complex64 *work, int *lwork, s *rwork, int *iwork, int *liwork, bint *bwork, int *info) nogil +cdef void cggesx(char *jobvsl, char *jobvsr, char *sort, cselect2 *selctg, char *sense, int *n, c *a, int *lda, c *b, int *ldb, int *sdim, c *alpha, c *beta, c *vsl, int *ldvsl, c *vsr, int *ldvsr, s *rconde, s *rcondv, c *work, int *lwork, s *rwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil: + + _fortran_cggesx(jobvsl, jobvsr, sort, <_cselect2*>selctg, sense, n, a, lda, b, ldb, sdim, alpha, beta, vsl, ldvsl, vsr, ldvsr, rconde, rcondv, work, lwork, rwork, iwork, liwork, bwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cggev "BLAS_FUNC(cggev)"(char *jobvl, char *jobvr, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, npy_complex64 *work, int *lwork, s *rwork, int *info) nogil +cdef void cggev(char *jobvl, char *jobvr, int *n, c *a, int *lda, c *b, int *ldb, c *alpha, c *beta, c *vl, int *ldvl, c *vr, int *ldvr, c *work, int *lwork, s *rwork, int *info) noexcept nogil: + + _fortran_cggev(jobvl, jobvr, n, a, lda, b, ldb, alpha, beta, vl, ldvl, vr, ldvr, work, lwork, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cggevx "BLAS_FUNC(cggevx)"(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, int *ilo, int *ihi, s *lscale, s *rscale, s *abnrm, s *bbnrm, s *rconde, s *rcondv, npy_complex64 *work, int *lwork, s *rwork, int *iwork, bint *bwork, int *info) nogil +cdef void cggevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, c *a, int *lda, c *b, int *ldb, c *alpha, c *beta, c *vl, int *ldvl, c *vr, int *ldvr, int *ilo, int *ihi, s *lscale, s *rscale, s *abnrm, s *bbnrm, s *rconde, s *rcondv, c *work, int *lwork, s *rwork, int *iwork, bint *bwork, int *info) noexcept nogil: + + _fortran_cggevx(balanc, jobvl, jobvr, sense, n, a, lda, b, ldb, alpha, beta, vl, ldvl, vr, ldvr, ilo, ihi, lscale, rscale, abnrm, bbnrm, rconde, rcondv, work, lwork, rwork, iwork, bwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cggglm "BLAS_FUNC(cggglm)"(int *n, int *m, int *p, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *d, npy_complex64 *x, npy_complex64 *y, npy_complex64 *work, int *lwork, int *info) nogil +cdef void cggglm(int *n, int *m, int *p, c *a, int *lda, c *b, int *ldb, c *d, c *x, c *y, c *work, int *lwork, int *info) noexcept nogil: + + _fortran_cggglm(n, m, p, a, lda, b, ldb, d, x, y, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgghrd "BLAS_FUNC(cgghrd)"(char *compq, char *compz, int *n, int *ilo, int *ihi, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *q, int *ldq, npy_complex64 *z, int *ldz, int *info) nogil +cdef void cgghrd(char *compq, char *compz, int *n, int *ilo, int *ihi, c *a, int *lda, c *b, int *ldb, c *q, int *ldq, c *z, int *ldz, int *info) noexcept nogil: + + _fortran_cgghrd(compq, compz, n, ilo, ihi, a, lda, b, ldb, q, ldq, z, ldz, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgglse "BLAS_FUNC(cgglse)"(int *m, int *n, int *p, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *c, npy_complex64 *d, npy_complex64 *x, npy_complex64 *work, int *lwork, int *info) nogil +cdef void cgglse(int *m, int *n, int *p, c *a, int *lda, c *b, int *ldb, c *c, c *d, c *x, c *work, int *lwork, int *info) noexcept nogil: + + _fortran_cgglse(m, n, p, a, lda, b, ldb, c, d, x, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cggqrf "BLAS_FUNC(cggqrf)"(int *n, int *m, int *p, npy_complex64 *a, int *lda, npy_complex64 *taua, npy_complex64 *b, int *ldb, npy_complex64 *taub, npy_complex64 *work, int *lwork, int *info) nogil +cdef void cggqrf(int *n, int *m, int *p, c *a, int *lda, c *taua, c *b, int *ldb, c *taub, c *work, int *lwork, int *info) noexcept nogil: + + _fortran_cggqrf(n, m, p, a, lda, taua, b, ldb, taub, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cggrqf "BLAS_FUNC(cggrqf)"(int *m, int *p, int *n, npy_complex64 *a, int *lda, npy_complex64 *taua, npy_complex64 *b, int *ldb, npy_complex64 *taub, npy_complex64 *work, int *lwork, int *info) nogil +cdef void cggrqf(int *m, int *p, int *n, c *a, int *lda, c *taua, c *b, int *ldb, c *taub, c *work, int *lwork, int *info) noexcept nogil: + + _fortran_cggrqf(m, p, n, a, lda, taua, b, ldb, taub, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgtcon "BLAS_FUNC(cgtcon)"(char *norm, int *n, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *du2, int *ipiv, s *anorm, s *rcond, npy_complex64 *work, int *info) nogil +cdef void cgtcon(char *norm, int *n, c *dl, c *d, c *du, c *du2, int *ipiv, s *anorm, s *rcond, c *work, int *info) noexcept nogil: + + _fortran_cgtcon(norm, n, dl, d, du, du2, ipiv, anorm, rcond, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgtrfs "BLAS_FUNC(cgtrfs)"(char *trans, int *n, int *nrhs, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *dlf, npy_complex64 *df, npy_complex64 *duf, npy_complex64 *du2, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil +cdef void cgtrfs(char *trans, int *n, int *nrhs, c *dl, c *d, c *du, c *dlf, c *df, c *duf, c *du2, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil: + + _fortran_cgtrfs(trans, n, nrhs, dl, d, du, dlf, df, duf, du2, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgtsv "BLAS_FUNC(cgtsv)"(int *n, int *nrhs, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *b, int *ldb, int *info) nogil +cdef void cgtsv(int *n, int *nrhs, c *dl, c *d, c *du, c *b, int *ldb, int *info) noexcept nogil: + + _fortran_cgtsv(n, nrhs, dl, d, du, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgtsvx "BLAS_FUNC(cgtsvx)"(char *fact, char *trans, int *n, int *nrhs, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *dlf, npy_complex64 *df, npy_complex64 *duf, npy_complex64 *du2, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil +cdef void cgtsvx(char *fact, char *trans, int *n, int *nrhs, c *dl, c *d, c *du, c *dlf, c *df, c *duf, c *du2, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil: + + _fortran_cgtsvx(fact, trans, n, nrhs, dl, d, du, dlf, df, duf, du2, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgttrf "BLAS_FUNC(cgttrf)"(int *n, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *du2, int *ipiv, int *info) nogil +cdef void cgttrf(int *n, c *dl, c *d, c *du, c *du2, int *ipiv, int *info) noexcept nogil: + + _fortran_cgttrf(n, dl, d, du, du2, ipiv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgttrs "BLAS_FUNC(cgttrs)"(char *trans, int *n, int *nrhs, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *du2, int *ipiv, npy_complex64 *b, int *ldb, int *info) nogil +cdef void cgttrs(char *trans, int *n, int *nrhs, c *dl, c *d, c *du, c *du2, int *ipiv, c *b, int *ldb, int *info) noexcept nogil: + + _fortran_cgttrs(trans, n, nrhs, dl, d, du, du2, ipiv, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cgtts2 "BLAS_FUNC(cgtts2)"(int *itrans, int *n, int *nrhs, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *du2, int *ipiv, npy_complex64 *b, int *ldb) nogil +cdef void cgtts2(int *itrans, int *n, int *nrhs, c *dl, c *d, c *du, c *du2, int *ipiv, c *b, int *ldb) noexcept nogil: + + _fortran_cgtts2(itrans, n, nrhs, dl, d, du, du2, ipiv, b, ldb) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chbev "BLAS_FUNC(chbev)"(char *jobz, char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, s *rwork, int *info) nogil +cdef void chbev(char *jobz, char *uplo, int *n, int *kd, c *ab, int *ldab, s *w, c *z, int *ldz, c *work, s *rwork, int *info) noexcept nogil: + + _fortran_chbev(jobz, uplo, n, kd, ab, ldab, w, z, ldz, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chbevd "BLAS_FUNC(chbevd)"(char *jobz, char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil +cdef void chbevd(char *jobz, char *uplo, int *n, int *kd, c *ab, int *ldab, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_chbevd(jobz, uplo, n, kd, ab, ldab, w, z, ldz, work, lwork, rwork, lrwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chbevx "BLAS_FUNC(chbevx)"(char *jobz, char *range, char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, npy_complex64 *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, s *rwork, int *iwork, int *ifail, int *info) nogil +cdef void chbevx(char *jobz, char *range, char *uplo, int *n, int *kd, c *ab, int *ldab, c *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil: + + _fortran_chbevx(jobz, range, uplo, n, kd, ab, ldab, q, ldq, vl, vu, il, iu, abstol, m, w, z, ldz, work, rwork, iwork, ifail, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chbgst "BLAS_FUNC(chbgst)"(char *vect, char *uplo, int *n, int *ka, int *kb, npy_complex64 *ab, int *ldab, npy_complex64 *bb, int *ldbb, npy_complex64 *x, int *ldx, npy_complex64 *work, s *rwork, int *info) nogil +cdef void chbgst(char *vect, char *uplo, int *n, int *ka, int *kb, c *ab, int *ldab, c *bb, int *ldbb, c *x, int *ldx, c *work, s *rwork, int *info) noexcept nogil: + + _fortran_chbgst(vect, uplo, n, ka, kb, ab, ldab, bb, ldbb, x, ldx, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chbgv "BLAS_FUNC(chbgv)"(char *jobz, char *uplo, int *n, int *ka, int *kb, npy_complex64 *ab, int *ldab, npy_complex64 *bb, int *ldbb, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, s *rwork, int *info) nogil +cdef void chbgv(char *jobz, char *uplo, int *n, int *ka, int *kb, c *ab, int *ldab, c *bb, int *ldbb, s *w, c *z, int *ldz, c *work, s *rwork, int *info) noexcept nogil: + + _fortran_chbgv(jobz, uplo, n, ka, kb, ab, ldab, bb, ldbb, w, z, ldz, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chbgvd "BLAS_FUNC(chbgvd)"(char *jobz, char *uplo, int *n, int *ka, int *kb, npy_complex64 *ab, int *ldab, npy_complex64 *bb, int *ldbb, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil +cdef void chbgvd(char *jobz, char *uplo, int *n, int *ka, int *kb, c *ab, int *ldab, c *bb, int *ldbb, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_chbgvd(jobz, uplo, n, ka, kb, ab, ldab, bb, ldbb, w, z, ldz, work, lwork, rwork, lrwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chbgvx "BLAS_FUNC(chbgvx)"(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, npy_complex64 *ab, int *ldab, npy_complex64 *bb, int *ldbb, npy_complex64 *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, s *rwork, int *iwork, int *ifail, int *info) nogil +cdef void chbgvx(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, c *ab, int *ldab, c *bb, int *ldbb, c *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil: + + _fortran_chbgvx(jobz, range, uplo, n, ka, kb, ab, ldab, bb, ldbb, q, ldq, vl, vu, il, iu, abstol, m, w, z, ldz, work, rwork, iwork, ifail, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chbtrd "BLAS_FUNC(chbtrd)"(char *vect, char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, s *d, s *e, npy_complex64 *q, int *ldq, npy_complex64 *work, int *info) nogil +cdef void chbtrd(char *vect, char *uplo, int *n, int *kd, c *ab, int *ldab, s *d, s *e, c *q, int *ldq, c *work, int *info) noexcept nogil: + + _fortran_chbtrd(vect, uplo, n, kd, ab, ldab, d, e, q, ldq, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_checon "BLAS_FUNC(checon)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, s *anorm, s *rcond, npy_complex64 *work, int *info) nogil +cdef void checon(char *uplo, int *n, c *a, int *lda, int *ipiv, s *anorm, s *rcond, c *work, int *info) noexcept nogil: + + _fortran_checon(uplo, n, a, lda, ipiv, anorm, rcond, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cheequb "BLAS_FUNC(cheequb)"(char *uplo, int *n, npy_complex64 *a, int *lda, s *s, s *scond, s *amax, npy_complex64 *work, int *info) nogil +cdef void cheequb(char *uplo, int *n, c *a, int *lda, s *s, s *scond, s *amax, c *work, int *info) noexcept nogil: + + _fortran_cheequb(uplo, n, a, lda, s, scond, amax, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cheev "BLAS_FUNC(cheev)"(char *jobz, char *uplo, int *n, npy_complex64 *a, int *lda, s *w, npy_complex64 *work, int *lwork, s *rwork, int *info) nogil +cdef void cheev(char *jobz, char *uplo, int *n, c *a, int *lda, s *w, c *work, int *lwork, s *rwork, int *info) noexcept nogil: + + _fortran_cheev(jobz, uplo, n, a, lda, w, work, lwork, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cheevd "BLAS_FUNC(cheevd)"(char *jobz, char *uplo, int *n, npy_complex64 *a, int *lda, s *w, npy_complex64 *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil +cdef void cheevd(char *jobz, char *uplo, int *n, c *a, int *lda, s *w, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_cheevd(jobz, uplo, n, a, lda, w, work, lwork, rwork, lrwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cheevr "BLAS_FUNC(cheevr)"(char *jobz, char *range, char *uplo, int *n, npy_complex64 *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, npy_complex64 *z, int *ldz, int *isuppz, npy_complex64 *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil +cdef void cheevr(char *jobz, char *range, char *uplo, int *n, c *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, int *isuppz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_cheevr(jobz, range, uplo, n, a, lda, vl, vu, il, iu, abstol, m, w, z, ldz, isuppz, work, lwork, rwork, lrwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cheevx "BLAS_FUNC(cheevx)"(char *jobz, char *range, char *uplo, int *n, npy_complex64 *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, s *rwork, int *iwork, int *ifail, int *info) nogil +cdef void cheevx(char *jobz, char *range, char *uplo, int *n, c *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil: + + _fortran_cheevx(jobz, range, uplo, n, a, lda, vl, vu, il, iu, abstol, m, w, z, ldz, work, lwork, rwork, iwork, ifail, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chegs2 "BLAS_FUNC(chegs2)"(int *itype, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *info) nogil +cdef void chegs2(int *itype, char *uplo, int *n, c *a, int *lda, c *b, int *ldb, int *info) noexcept nogil: + + _fortran_chegs2(itype, uplo, n, a, lda, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chegst "BLAS_FUNC(chegst)"(int *itype, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *info) nogil +cdef void chegst(int *itype, char *uplo, int *n, c *a, int *lda, c *b, int *ldb, int *info) noexcept nogil: + + _fortran_chegst(itype, uplo, n, a, lda, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chegv "BLAS_FUNC(chegv)"(int *itype, char *jobz, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, s *w, npy_complex64 *work, int *lwork, s *rwork, int *info) nogil +cdef void chegv(int *itype, char *jobz, char *uplo, int *n, c *a, int *lda, c *b, int *ldb, s *w, c *work, int *lwork, s *rwork, int *info) noexcept nogil: + + _fortran_chegv(itype, jobz, uplo, n, a, lda, b, ldb, w, work, lwork, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chegvd "BLAS_FUNC(chegvd)"(int *itype, char *jobz, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, s *w, npy_complex64 *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil +cdef void chegvd(int *itype, char *jobz, char *uplo, int *n, c *a, int *lda, c *b, int *ldb, s *w, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_chegvd(itype, jobz, uplo, n, a, lda, b, ldb, w, work, lwork, rwork, lrwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chegvx "BLAS_FUNC(chegvx)"(int *itype, char *jobz, char *range, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, s *rwork, int *iwork, int *ifail, int *info) nogil +cdef void chegvx(int *itype, char *jobz, char *range, char *uplo, int *n, c *a, int *lda, c *b, int *ldb, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil: + + _fortran_chegvx(itype, jobz, range, uplo, n, a, lda, b, ldb, vl, vu, il, iu, abstol, m, w, z, ldz, work, lwork, rwork, iwork, ifail, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cherfs "BLAS_FUNC(cherfs)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil +cdef void cherfs(char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil: + + _fortran_cherfs(uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chesv "BLAS_FUNC(chesv)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *work, int *lwork, int *info) nogil +cdef void chesv(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, c *work, int *lwork, int *info) noexcept nogil: + + _fortran_chesv(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chesvx "BLAS_FUNC(chesvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, int *lwork, s *rwork, int *info) nogil +cdef void chesvx(char *fact, char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, int *lwork, s *rwork, int *info) noexcept nogil: + + _fortran_chesvx(fact, uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, lwork, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cheswapr "BLAS_FUNC(cheswapr)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *i1, int *i2) nogil +cdef void cheswapr(char *uplo, int *n, c *a, int *lda, int *i1, int *i2) noexcept nogil: + + _fortran_cheswapr(uplo, n, a, lda, i1, i2) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chetd2 "BLAS_FUNC(chetd2)"(char *uplo, int *n, npy_complex64 *a, int *lda, s *d, s *e, npy_complex64 *tau, int *info) nogil +cdef void chetd2(char *uplo, int *n, c *a, int *lda, s *d, s *e, c *tau, int *info) noexcept nogil: + + _fortran_chetd2(uplo, n, a, lda, d, e, tau, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chetf2 "BLAS_FUNC(chetf2)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, int *info) nogil +cdef void chetf2(char *uplo, int *n, c *a, int *lda, int *ipiv, int *info) noexcept nogil: + + _fortran_chetf2(uplo, n, a, lda, ipiv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chetrd "BLAS_FUNC(chetrd)"(char *uplo, int *n, npy_complex64 *a, int *lda, s *d, s *e, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil +cdef void chetrd(char *uplo, int *n, c *a, int *lda, s *d, s *e, c *tau, c *work, int *lwork, int *info) noexcept nogil: + + _fortran_chetrd(uplo, n, a, lda, d, e, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chetrf "BLAS_FUNC(chetrf)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *lwork, int *info) nogil +cdef void chetrf(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *lwork, int *info) noexcept nogil: + + _fortran_chetrf(uplo, n, a, lda, ipiv, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chetri "BLAS_FUNC(chetri)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *info) nogil +cdef void chetri(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *info) noexcept nogil: + + _fortran_chetri(uplo, n, a, lda, ipiv, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chetri2 "BLAS_FUNC(chetri2)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *lwork, int *info) nogil +cdef void chetri2(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *lwork, int *info) noexcept nogil: + + _fortran_chetri2(uplo, n, a, lda, ipiv, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chetri2x "BLAS_FUNC(chetri2x)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *nb, int *info) nogil +cdef void chetri2x(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *nb, int *info) noexcept nogil: + + _fortran_chetri2x(uplo, n, a, lda, ipiv, work, nb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chetrs "BLAS_FUNC(chetrs)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, int *info) nogil +cdef void chetrs(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, int *info) noexcept nogil: + + _fortran_chetrs(uplo, n, nrhs, a, lda, ipiv, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chetrs2 "BLAS_FUNC(chetrs2)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *work, int *info) nogil +cdef void chetrs2(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, c *work, int *info) noexcept nogil: + + _fortran_chetrs2(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chfrk "BLAS_FUNC(chfrk)"(char *transr, char *uplo, char *trans, int *n, int *k, s *alpha, npy_complex64 *a, int *lda, s *beta, npy_complex64 *c) nogil +cdef void chfrk(char *transr, char *uplo, char *trans, int *n, int *k, s *alpha, c *a, int *lda, s *beta, c *c) noexcept nogil: + + _fortran_chfrk(transr, uplo, trans, n, k, alpha, a, lda, beta, c) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chgeqz "BLAS_FUNC(chgeqz)"(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, npy_complex64 *h, int *ldh, npy_complex64 *t, int *ldt, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *q, int *ldq, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, s *rwork, int *info) nogil +cdef void chgeqz(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, c *h, int *ldh, c *t, int *ldt, c *alpha, c *beta, c *q, int *ldq, c *z, int *ldz, c *work, int *lwork, s *rwork, int *info) noexcept nogil: + + _fortran_chgeqz(job, compq, compz, n, ilo, ihi, h, ldh, t, ldt, alpha, beta, q, ldq, z, ldz, work, lwork, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + char _fortran_chla_transtype "BLAS_FUNC(chla_transtype)"(int *trans) nogil +cdef char chla_transtype(int *trans) noexcept nogil: + + return _fortran_chla_transtype(trans) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chpcon "BLAS_FUNC(chpcon)"(char *uplo, int *n, npy_complex64 *ap, int *ipiv, s *anorm, s *rcond, npy_complex64 *work, int *info) nogil +cdef void chpcon(char *uplo, int *n, c *ap, int *ipiv, s *anorm, s *rcond, c *work, int *info) noexcept nogil: + + _fortran_chpcon(uplo, n, ap, ipiv, anorm, rcond, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chpev "BLAS_FUNC(chpev)"(char *jobz, char *uplo, int *n, npy_complex64 *ap, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, s *rwork, int *info) nogil +cdef void chpev(char *jobz, char *uplo, int *n, c *ap, s *w, c *z, int *ldz, c *work, s *rwork, int *info) noexcept nogil: + + _fortran_chpev(jobz, uplo, n, ap, w, z, ldz, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chpevd "BLAS_FUNC(chpevd)"(char *jobz, char *uplo, int *n, npy_complex64 *ap, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil +cdef void chpevd(char *jobz, char *uplo, int *n, c *ap, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_chpevd(jobz, uplo, n, ap, w, z, ldz, work, lwork, rwork, lrwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chpevx "BLAS_FUNC(chpevx)"(char *jobz, char *range, char *uplo, int *n, npy_complex64 *ap, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, s *rwork, int *iwork, int *ifail, int *info) nogil +cdef void chpevx(char *jobz, char *range, char *uplo, int *n, c *ap, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil: + + _fortran_chpevx(jobz, range, uplo, n, ap, vl, vu, il, iu, abstol, m, w, z, ldz, work, rwork, iwork, ifail, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chpgst "BLAS_FUNC(chpgst)"(int *itype, char *uplo, int *n, npy_complex64 *ap, npy_complex64 *bp, int *info) nogil +cdef void chpgst(int *itype, char *uplo, int *n, c *ap, c *bp, int *info) noexcept nogil: + + _fortran_chpgst(itype, uplo, n, ap, bp, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chpgv "BLAS_FUNC(chpgv)"(int *itype, char *jobz, char *uplo, int *n, npy_complex64 *ap, npy_complex64 *bp, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, s *rwork, int *info) nogil +cdef void chpgv(int *itype, char *jobz, char *uplo, int *n, c *ap, c *bp, s *w, c *z, int *ldz, c *work, s *rwork, int *info) noexcept nogil: + + _fortran_chpgv(itype, jobz, uplo, n, ap, bp, w, z, ldz, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chpgvd "BLAS_FUNC(chpgvd)"(int *itype, char *jobz, char *uplo, int *n, npy_complex64 *ap, npy_complex64 *bp, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil +cdef void chpgvd(int *itype, char *jobz, char *uplo, int *n, c *ap, c *bp, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_chpgvd(itype, jobz, uplo, n, ap, bp, w, z, ldz, work, lwork, rwork, lrwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chpgvx "BLAS_FUNC(chpgvx)"(int *itype, char *jobz, char *range, char *uplo, int *n, npy_complex64 *ap, npy_complex64 *bp, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, s *rwork, int *iwork, int *ifail, int *info) nogil +cdef void chpgvx(int *itype, char *jobz, char *range, char *uplo, int *n, c *ap, c *bp, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil: + + _fortran_chpgvx(itype, jobz, range, uplo, n, ap, bp, vl, vu, il, iu, abstol, m, w, z, ldz, work, rwork, iwork, ifail, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chprfs "BLAS_FUNC(chprfs)"(char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil +cdef void chprfs(char *uplo, int *n, int *nrhs, c *ap, c *afp, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil: + + _fortran_chprfs(uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chpsv "BLAS_FUNC(chpsv)"(char *uplo, int *n, int *nrhs, npy_complex64 *ap, int *ipiv, npy_complex64 *b, int *ldb, int *info) nogil +cdef void chpsv(char *uplo, int *n, int *nrhs, c *ap, int *ipiv, c *b, int *ldb, int *info) noexcept nogil: + + _fortran_chpsv(uplo, n, nrhs, ap, ipiv, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chpsvx "BLAS_FUNC(chpsvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil +cdef void chpsvx(char *fact, char *uplo, int *n, int *nrhs, c *ap, c *afp, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil: + + _fortran_chpsvx(fact, uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chptrd "BLAS_FUNC(chptrd)"(char *uplo, int *n, npy_complex64 *ap, s *d, s *e, npy_complex64 *tau, int *info) nogil +cdef void chptrd(char *uplo, int *n, c *ap, s *d, s *e, c *tau, int *info) noexcept nogil: + + _fortran_chptrd(uplo, n, ap, d, e, tau, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chptrf "BLAS_FUNC(chptrf)"(char *uplo, int *n, npy_complex64 *ap, int *ipiv, int *info) nogil +cdef void chptrf(char *uplo, int *n, c *ap, int *ipiv, int *info) noexcept nogil: + + _fortran_chptrf(uplo, n, ap, ipiv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chptri "BLAS_FUNC(chptri)"(char *uplo, int *n, npy_complex64 *ap, int *ipiv, npy_complex64 *work, int *info) nogil +cdef void chptri(char *uplo, int *n, c *ap, int *ipiv, c *work, int *info) noexcept nogil: + + _fortran_chptri(uplo, n, ap, ipiv, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chptrs "BLAS_FUNC(chptrs)"(char *uplo, int *n, int *nrhs, npy_complex64 *ap, int *ipiv, npy_complex64 *b, int *ldb, int *info) nogil +cdef void chptrs(char *uplo, int *n, int *nrhs, c *ap, int *ipiv, c *b, int *ldb, int *info) noexcept nogil: + + _fortran_chptrs(uplo, n, nrhs, ap, ipiv, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chsein "BLAS_FUNC(chsein)"(char *side, char *eigsrc, char *initv, bint *select, int *n, npy_complex64 *h, int *ldh, npy_complex64 *w, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, int *mm, int *m, npy_complex64 *work, s *rwork, int *ifaill, int *ifailr, int *info) nogil +cdef void chsein(char *side, char *eigsrc, char *initv, bint *select, int *n, c *h, int *ldh, c *w, c *vl, int *ldvl, c *vr, int *ldvr, int *mm, int *m, c *work, s *rwork, int *ifaill, int *ifailr, int *info) noexcept nogil: + + _fortran_chsein(side, eigsrc, initv, select, n, h, ldh, w, vl, ldvl, vr, ldvr, mm, m, work, rwork, ifaill, ifailr, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_chseqr "BLAS_FUNC(chseqr)"(char *job, char *compz, int *n, int *ilo, int *ihi, npy_complex64 *h, int *ldh, npy_complex64 *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, int *info) nogil +cdef void chseqr(char *job, char *compz, int *n, int *ilo, int *ihi, c *h, int *ldh, c *w, c *z, int *ldz, c *work, int *lwork, int *info) noexcept nogil: + + _fortran_chseqr(job, compz, n, ilo, ihi, h, ldh, w, z, ldz, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clabrd "BLAS_FUNC(clabrd)"(int *m, int *n, int *nb, npy_complex64 *a, int *lda, s *d, s *e, npy_complex64 *tauq, npy_complex64 *taup, npy_complex64 *x, int *ldx, npy_complex64 *y, int *ldy) nogil +cdef void clabrd(int *m, int *n, int *nb, c *a, int *lda, s *d, s *e, c *tauq, c *taup, c *x, int *ldx, c *y, int *ldy) noexcept nogil: + + _fortran_clabrd(m, n, nb, a, lda, d, e, tauq, taup, x, ldx, y, ldy) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clacgv "BLAS_FUNC(clacgv)"(int *n, npy_complex64 *x, int *incx) nogil +cdef void clacgv(int *n, c *x, int *incx) noexcept nogil: + + _fortran_clacgv(n, x, incx) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clacn2 "BLAS_FUNC(clacn2)"(int *n, npy_complex64 *v, npy_complex64 *x, s *est, int *kase, int *isave) nogil +cdef void clacn2(int *n, c *v, c *x, s *est, int *kase, int *isave) noexcept nogil: + + _fortran_clacn2(n, v, x, est, kase, isave) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clacon "BLAS_FUNC(clacon)"(int *n, npy_complex64 *v, npy_complex64 *x, s *est, int *kase) nogil +cdef void clacon(int *n, c *v, c *x, s *est, int *kase) noexcept nogil: + + _fortran_clacon(n, v, x, est, kase) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clacp2 "BLAS_FUNC(clacp2)"(char *uplo, int *m, int *n, s *a, int *lda, npy_complex64 *b, int *ldb) nogil +cdef void clacp2(char *uplo, int *m, int *n, s *a, int *lda, c *b, int *ldb) noexcept nogil: + + _fortran_clacp2(uplo, m, n, a, lda, b, ldb) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clacpy "BLAS_FUNC(clacpy)"(char *uplo, int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb) nogil +cdef void clacpy(char *uplo, int *m, int *n, c *a, int *lda, c *b, int *ldb) noexcept nogil: + + _fortran_clacpy(uplo, m, n, a, lda, b, ldb) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clacrm "BLAS_FUNC(clacrm)"(int *m, int *n, npy_complex64 *a, int *lda, s *b, int *ldb, npy_complex64 *c, int *ldc, s *rwork) nogil +cdef void clacrm(int *m, int *n, c *a, int *lda, s *b, int *ldb, c *c, int *ldc, s *rwork) noexcept nogil: + + _fortran_clacrm(m, n, a, lda, b, ldb, c, ldc, rwork) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clacrt "BLAS_FUNC(clacrt)"(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy, npy_complex64 *c, npy_complex64 *s) nogil +cdef void clacrt(int *n, c *cx, int *incx, c *cy, int *incy, c *c, c *s) noexcept nogil: + + _fortran_clacrt(n, cx, incx, cy, incy, c, s) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cladiv "F_FUNC(cladivwrp,CLADIVWRP)"(npy_complex64 *out, npy_complex64 *x, npy_complex64 *y) nogil +cdef c cladiv(c *x, c *y) noexcept nogil: + cdef c out + _fortran_cladiv(&out, x, y) + return out + +cdef extern from "_lapack_subroutines.h": + void _fortran_claed0 "BLAS_FUNC(claed0)"(int *qsiz, int *n, s *d, s *e, npy_complex64 *q, int *ldq, npy_complex64 *qstore, int *ldqs, s *rwork, int *iwork, int *info) nogil +cdef void claed0(int *qsiz, int *n, s *d, s *e, c *q, int *ldq, c *qstore, int *ldqs, s *rwork, int *iwork, int *info) noexcept nogil: + + _fortran_claed0(qsiz, n, d, e, q, ldq, qstore, ldqs, rwork, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_claed7 "BLAS_FUNC(claed7)"(int *n, int *cutpnt, int *qsiz, int *tlvls, int *curlvl, int *curpbm, s *d, npy_complex64 *q, int *ldq, s *rho, int *indxq, s *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, s *givnum, npy_complex64 *work, s *rwork, int *iwork, int *info) nogil +cdef void claed7(int *n, int *cutpnt, int *qsiz, int *tlvls, int *curlvl, int *curpbm, s *d, c *q, int *ldq, s *rho, int *indxq, s *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, s *givnum, c *work, s *rwork, int *iwork, int *info) noexcept nogil: + + _fortran_claed7(n, cutpnt, qsiz, tlvls, curlvl, curpbm, d, q, ldq, rho, indxq, qstore, qptr, prmptr, perm, givptr, givcol, givnum, work, rwork, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_claed8 "BLAS_FUNC(claed8)"(int *k, int *n, int *qsiz, npy_complex64 *q, int *ldq, s *d, s *rho, int *cutpnt, s *z, s *dlamda, npy_complex64 *q2, int *ldq2, s *w, int *indxp, int *indx, int *indxq, int *perm, int *givptr, int *givcol, s *givnum, int *info) nogil +cdef void claed8(int *k, int *n, int *qsiz, c *q, int *ldq, s *d, s *rho, int *cutpnt, s *z, s *dlamda, c *q2, int *ldq2, s *w, int *indxp, int *indx, int *indxq, int *perm, int *givptr, int *givcol, s *givnum, int *info) noexcept nogil: + + _fortran_claed8(k, n, qsiz, q, ldq, d, rho, cutpnt, z, dlamda, q2, ldq2, w, indxp, indx, indxq, perm, givptr, givcol, givnum, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_claein "BLAS_FUNC(claein)"(bint *rightv, bint *noinit, int *n, npy_complex64 *h, int *ldh, npy_complex64 *w, npy_complex64 *v, npy_complex64 *b, int *ldb, s *rwork, s *eps3, s *smlnum, int *info) nogil +cdef void claein(bint *rightv, bint *noinit, int *n, c *h, int *ldh, c *w, c *v, c *b, int *ldb, s *rwork, s *eps3, s *smlnum, int *info) noexcept nogil: + + _fortran_claein(rightv, noinit, n, h, ldh, w, v, b, ldb, rwork, eps3, smlnum, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_claesy "BLAS_FUNC(claesy)"(npy_complex64 *a, npy_complex64 *b, npy_complex64 *c, npy_complex64 *rt1, npy_complex64 *rt2, npy_complex64 *evscal, npy_complex64 *cs1, npy_complex64 *sn1) nogil +cdef void claesy(c *a, c *b, c *c, c *rt1, c *rt2, c *evscal, c *cs1, c *sn1) noexcept nogil: + + _fortran_claesy(a, b, c, rt1, rt2, evscal, cs1, sn1) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_claev2 "BLAS_FUNC(claev2)"(npy_complex64 *a, npy_complex64 *b, npy_complex64 *c, s *rt1, s *rt2, s *cs1, npy_complex64 *sn1) nogil +cdef void claev2(c *a, c *b, c *c, s *rt1, s *rt2, s *cs1, c *sn1) noexcept nogil: + + _fortran_claev2(a, b, c, rt1, rt2, cs1, sn1) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clag2z "BLAS_FUNC(clag2z)"(int *m, int *n, npy_complex64 *sa, int *ldsa, npy_complex128 *a, int *lda, int *info) nogil +cdef void clag2z(int *m, int *n, c *sa, int *ldsa, z *a, int *lda, int *info) noexcept nogil: + + _fortran_clag2z(m, n, sa, ldsa, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clags2 "BLAS_FUNC(clags2)"(bint *upper, s *a1, npy_complex64 *a2, s *a3, s *b1, npy_complex64 *b2, s *b3, s *csu, npy_complex64 *snu, s *csv, npy_complex64 *snv, s *csq, npy_complex64 *snq) nogil +cdef void clags2(bint *upper, s *a1, c *a2, s *a3, s *b1, c *b2, s *b3, s *csu, c *snu, s *csv, c *snv, s *csq, c *snq) noexcept nogil: + + _fortran_clags2(upper, a1, a2, a3, b1, b2, b3, csu, snu, csv, snv, csq, snq) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clagtm "BLAS_FUNC(clagtm)"(char *trans, int *n, int *nrhs, s *alpha, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *x, int *ldx, s *beta, npy_complex64 *b, int *ldb) nogil +cdef void clagtm(char *trans, int *n, int *nrhs, s *alpha, c *dl, c *d, c *du, c *x, int *ldx, s *beta, c *b, int *ldb) noexcept nogil: + + _fortran_clagtm(trans, n, nrhs, alpha, dl, d, du, x, ldx, beta, b, ldb) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clahef "BLAS_FUNC(clahef)"(char *uplo, int *n, int *nb, int *kb, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *w, int *ldw, int *info) nogil +cdef void clahef(char *uplo, int *n, int *nb, int *kb, c *a, int *lda, int *ipiv, c *w, int *ldw, int *info) noexcept nogil: + + _fortran_clahef(uplo, n, nb, kb, a, lda, ipiv, w, ldw, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clahqr "BLAS_FUNC(clahqr)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, npy_complex64 *h, int *ldh, npy_complex64 *w, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, int *info) nogil +cdef void clahqr(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, c *h, int *ldh, c *w, int *iloz, int *ihiz, c *z, int *ldz, int *info) noexcept nogil: + + _fortran_clahqr(wantt, wantz, n, ilo, ihi, h, ldh, w, iloz, ihiz, z, ldz, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clahr2 "BLAS_FUNC(clahr2)"(int *n, int *k, int *nb, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *t, int *ldt, npy_complex64 *y, int *ldy) nogil +cdef void clahr2(int *n, int *k, int *nb, c *a, int *lda, c *tau, c *t, int *ldt, c *y, int *ldy) noexcept nogil: + + _fortran_clahr2(n, k, nb, a, lda, tau, t, ldt, y, ldy) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_claic1 "BLAS_FUNC(claic1)"(int *job, int *j, npy_complex64 *x, s *sest, npy_complex64 *w, npy_complex64 *gamma, s *sestpr, npy_complex64 *s, npy_complex64 *c) nogil +cdef void claic1(int *job, int *j, c *x, s *sest, c *w, c *gamma, s *sestpr, c *s, c *c) noexcept nogil: + + _fortran_claic1(job, j, x, sest, w, gamma, sestpr, s, c) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clals0 "BLAS_FUNC(clals0)"(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, npy_complex64 *b, int *ldb, npy_complex64 *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, s *givnum, int *ldgnum, s *poles, s *difl, s *difr, s *z, int *k, s *c, s *s, s *rwork, int *info) nogil +cdef void clals0(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, c *b, int *ldb, c *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, s *givnum, int *ldgnum, s *poles, s *difl, s *difr, s *z, int *k, s *c, s *s, s *rwork, int *info) noexcept nogil: + + _fortran_clals0(icompq, nl, nr, sqre, nrhs, b, ldb, bx, ldbx, perm, givptr, givcol, ldgcol, givnum, ldgnum, poles, difl, difr, z, k, c, s, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clalsa "BLAS_FUNC(clalsa)"(int *icompq, int *smlsiz, int *n, int *nrhs, npy_complex64 *b, int *ldb, npy_complex64 *bx, int *ldbx, s *u, int *ldu, s *vt, int *k, s *difl, s *difr, s *z, s *poles, int *givptr, int *givcol, int *ldgcol, int *perm, s *givnum, s *c, s *s, s *rwork, int *iwork, int *info) nogil +cdef void clalsa(int *icompq, int *smlsiz, int *n, int *nrhs, c *b, int *ldb, c *bx, int *ldbx, s *u, int *ldu, s *vt, int *k, s *difl, s *difr, s *z, s *poles, int *givptr, int *givcol, int *ldgcol, int *perm, s *givnum, s *c, s *s, s *rwork, int *iwork, int *info) noexcept nogil: + + _fortran_clalsa(icompq, smlsiz, n, nrhs, b, ldb, bx, ldbx, u, ldu, vt, k, difl, difr, z, poles, givptr, givcol, ldgcol, perm, givnum, c, s, rwork, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clalsd "BLAS_FUNC(clalsd)"(char *uplo, int *smlsiz, int *n, int *nrhs, s *d, s *e, npy_complex64 *b, int *ldb, s *rcond, int *rank, npy_complex64 *work, s *rwork, int *iwork, int *info) nogil +cdef void clalsd(char *uplo, int *smlsiz, int *n, int *nrhs, s *d, s *e, c *b, int *ldb, s *rcond, int *rank, c *work, s *rwork, int *iwork, int *info) noexcept nogil: + + _fortran_clalsd(uplo, smlsiz, n, nrhs, d, e, b, ldb, rcond, rank, work, rwork, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + s _fortran_clangb "BLAS_FUNC(clangb)"(char *norm, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, s *work) nogil +cdef s clangb(char *norm, int *n, int *kl, int *ku, c *ab, int *ldab, s *work) noexcept nogil: + + return _fortran_clangb(norm, n, kl, ku, ab, ldab, work) + + +cdef extern from "_lapack_subroutines.h": + s _fortran_clange "BLAS_FUNC(clange)"(char *norm, int *m, int *n, npy_complex64 *a, int *lda, s *work) nogil +cdef s clange(char *norm, int *m, int *n, c *a, int *lda, s *work) noexcept nogil: + + return _fortran_clange(norm, m, n, a, lda, work) + + +cdef extern from "_lapack_subroutines.h": + s _fortran_clangt "BLAS_FUNC(clangt)"(char *norm, int *n, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du) nogil +cdef s clangt(char *norm, int *n, c *dl, c *d, c *du) noexcept nogil: + + return _fortran_clangt(norm, n, dl, d, du) + + +cdef extern from "_lapack_subroutines.h": + s _fortran_clanhb "BLAS_FUNC(clanhb)"(char *norm, char *uplo, int *n, int *k, npy_complex64 *ab, int *ldab, s *work) nogil +cdef s clanhb(char *norm, char *uplo, int *n, int *k, c *ab, int *ldab, s *work) noexcept nogil: + + return _fortran_clanhb(norm, uplo, n, k, ab, ldab, work) + + +cdef extern from "_lapack_subroutines.h": + s _fortran_clanhe "BLAS_FUNC(clanhe)"(char *norm, char *uplo, int *n, npy_complex64 *a, int *lda, s *work) nogil +cdef s clanhe(char *norm, char *uplo, int *n, c *a, int *lda, s *work) noexcept nogil: + + return _fortran_clanhe(norm, uplo, n, a, lda, work) + + +cdef extern from "_lapack_subroutines.h": + s _fortran_clanhf "BLAS_FUNC(clanhf)"(char *norm, char *transr, char *uplo, int *n, npy_complex64 *a, s *work) nogil +cdef s clanhf(char *norm, char *transr, char *uplo, int *n, c *a, s *work) noexcept nogil: + + return _fortran_clanhf(norm, transr, uplo, n, a, work) + + +cdef extern from "_lapack_subroutines.h": + s _fortran_clanhp "BLAS_FUNC(clanhp)"(char *norm, char *uplo, int *n, npy_complex64 *ap, s *work) nogil +cdef s clanhp(char *norm, char *uplo, int *n, c *ap, s *work) noexcept nogil: + + return _fortran_clanhp(norm, uplo, n, ap, work) + + +cdef extern from "_lapack_subroutines.h": + s _fortran_clanhs "BLAS_FUNC(clanhs)"(char *norm, int *n, npy_complex64 *a, int *lda, s *work) nogil +cdef s clanhs(char *norm, int *n, c *a, int *lda, s *work) noexcept nogil: + + return _fortran_clanhs(norm, n, a, lda, work) + + +cdef extern from "_lapack_subroutines.h": + s _fortran_clanht "BLAS_FUNC(clanht)"(char *norm, int *n, s *d, npy_complex64 *e) nogil +cdef s clanht(char *norm, int *n, s *d, c *e) noexcept nogil: + + return _fortran_clanht(norm, n, d, e) + + +cdef extern from "_lapack_subroutines.h": + s _fortran_clansb "BLAS_FUNC(clansb)"(char *norm, char *uplo, int *n, int *k, npy_complex64 *ab, int *ldab, s *work) nogil +cdef s clansb(char *norm, char *uplo, int *n, int *k, c *ab, int *ldab, s *work) noexcept nogil: + + return _fortran_clansb(norm, uplo, n, k, ab, ldab, work) + + +cdef extern from "_lapack_subroutines.h": + s _fortran_clansp "BLAS_FUNC(clansp)"(char *norm, char *uplo, int *n, npy_complex64 *ap, s *work) nogil +cdef s clansp(char *norm, char *uplo, int *n, c *ap, s *work) noexcept nogil: + + return _fortran_clansp(norm, uplo, n, ap, work) + + +cdef extern from "_lapack_subroutines.h": + s _fortran_clansy "BLAS_FUNC(clansy)"(char *norm, char *uplo, int *n, npy_complex64 *a, int *lda, s *work) nogil +cdef s clansy(char *norm, char *uplo, int *n, c *a, int *lda, s *work) noexcept nogil: + + return _fortran_clansy(norm, uplo, n, a, lda, work) + + +cdef extern from "_lapack_subroutines.h": + s _fortran_clantb "BLAS_FUNC(clantb)"(char *norm, char *uplo, char *diag, int *n, int *k, npy_complex64 *ab, int *ldab, s *work) nogil +cdef s clantb(char *norm, char *uplo, char *diag, int *n, int *k, c *ab, int *ldab, s *work) noexcept nogil: + + return _fortran_clantb(norm, uplo, diag, n, k, ab, ldab, work) + + +cdef extern from "_lapack_subroutines.h": + s _fortran_clantp "BLAS_FUNC(clantp)"(char *norm, char *uplo, char *diag, int *n, npy_complex64 *ap, s *work) nogil +cdef s clantp(char *norm, char *uplo, char *diag, int *n, c *ap, s *work) noexcept nogil: + + return _fortran_clantp(norm, uplo, diag, n, ap, work) + + +cdef extern from "_lapack_subroutines.h": + s _fortran_clantr "BLAS_FUNC(clantr)"(char *norm, char *uplo, char *diag, int *m, int *n, npy_complex64 *a, int *lda, s *work) nogil +cdef s clantr(char *norm, char *uplo, char *diag, int *m, int *n, c *a, int *lda, s *work) noexcept nogil: + + return _fortran_clantr(norm, uplo, diag, m, n, a, lda, work) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clapll "BLAS_FUNC(clapll)"(int *n, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, s *ssmin) nogil +cdef void clapll(int *n, c *x, int *incx, c *y, int *incy, s *ssmin) noexcept nogil: + + _fortran_clapll(n, x, incx, y, incy, ssmin) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clapmr "BLAS_FUNC(clapmr)"(bint *forwrd, int *m, int *n, npy_complex64 *x, int *ldx, int *k) nogil +cdef void clapmr(bint *forwrd, int *m, int *n, c *x, int *ldx, int *k) noexcept nogil: + + _fortran_clapmr(forwrd, m, n, x, ldx, k) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clapmt "BLAS_FUNC(clapmt)"(bint *forwrd, int *m, int *n, npy_complex64 *x, int *ldx, int *k) nogil +cdef void clapmt(bint *forwrd, int *m, int *n, c *x, int *ldx, int *k) noexcept nogil: + + _fortran_clapmt(forwrd, m, n, x, ldx, k) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_claqgb "BLAS_FUNC(claqgb)"(int *m, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) nogil +cdef void claqgb(int *m, int *n, int *kl, int *ku, c *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) noexcept nogil: + + _fortran_claqgb(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, equed) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_claqge "BLAS_FUNC(claqge)"(int *m, int *n, npy_complex64 *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) nogil +cdef void claqge(int *m, int *n, c *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) noexcept nogil: + + _fortran_claqge(m, n, a, lda, r, c, rowcnd, colcnd, amax, equed) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_claqhb "BLAS_FUNC(claqhb)"(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, s *s, s *scond, s *amax, char *equed) nogil +cdef void claqhb(char *uplo, int *n, int *kd, c *ab, int *ldab, s *s, s *scond, s *amax, char *equed) noexcept nogil: + + _fortran_claqhb(uplo, n, kd, ab, ldab, s, scond, amax, equed) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_claqhe "BLAS_FUNC(claqhe)"(char *uplo, int *n, npy_complex64 *a, int *lda, s *s, s *scond, s *amax, char *equed) nogil +cdef void claqhe(char *uplo, int *n, c *a, int *lda, s *s, s *scond, s *amax, char *equed) noexcept nogil: + + _fortran_claqhe(uplo, n, a, lda, s, scond, amax, equed) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_claqhp "BLAS_FUNC(claqhp)"(char *uplo, int *n, npy_complex64 *ap, s *s, s *scond, s *amax, char *equed) nogil +cdef void claqhp(char *uplo, int *n, c *ap, s *s, s *scond, s *amax, char *equed) noexcept nogil: + + _fortran_claqhp(uplo, n, ap, s, scond, amax, equed) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_claqp2 "BLAS_FUNC(claqp2)"(int *m, int *n, int *offset, npy_complex64 *a, int *lda, int *jpvt, npy_complex64 *tau, s *vn1, s *vn2, npy_complex64 *work) nogil +cdef void claqp2(int *m, int *n, int *offset, c *a, int *lda, int *jpvt, c *tau, s *vn1, s *vn2, c *work) noexcept nogil: + + _fortran_claqp2(m, n, offset, a, lda, jpvt, tau, vn1, vn2, work) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_claqps "BLAS_FUNC(claqps)"(int *m, int *n, int *offset, int *nb, int *kb, npy_complex64 *a, int *lda, int *jpvt, npy_complex64 *tau, s *vn1, s *vn2, npy_complex64 *auxv, npy_complex64 *f, int *ldf) nogil +cdef void claqps(int *m, int *n, int *offset, int *nb, int *kb, c *a, int *lda, int *jpvt, c *tau, s *vn1, s *vn2, c *auxv, c *f, int *ldf) noexcept nogil: + + _fortran_claqps(m, n, offset, nb, kb, a, lda, jpvt, tau, vn1, vn2, auxv, f, ldf) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_claqr0 "BLAS_FUNC(claqr0)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, npy_complex64 *h, int *ldh, npy_complex64 *w, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, int *info) nogil +cdef void claqr0(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, c *h, int *ldh, c *w, int *iloz, int *ihiz, c *z, int *ldz, c *work, int *lwork, int *info) noexcept nogil: + + _fortran_claqr0(wantt, wantz, n, ilo, ihi, h, ldh, w, iloz, ihiz, z, ldz, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_claqr1 "BLAS_FUNC(claqr1)"(int *n, npy_complex64 *h, int *ldh, npy_complex64 *s1, npy_complex64 *s2, npy_complex64 *v) nogil +cdef void claqr1(int *n, c *h, int *ldh, c *s1, c *s2, c *v) noexcept nogil: + + _fortran_claqr1(n, h, ldh, s1, s2, v) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_claqr2 "BLAS_FUNC(claqr2)"(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, npy_complex64 *h, int *ldh, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, int *ns, int *nd, npy_complex64 *sh, npy_complex64 *v, int *ldv, int *nh, npy_complex64 *t, int *ldt, int *nv, npy_complex64 *wv, int *ldwv, npy_complex64 *work, int *lwork) nogil +cdef void claqr2(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, c *h, int *ldh, int *iloz, int *ihiz, c *z, int *ldz, int *ns, int *nd, c *sh, c *v, int *ldv, int *nh, c *t, int *ldt, int *nv, c *wv, int *ldwv, c *work, int *lwork) noexcept nogil: + + _fortran_claqr2(wantt, wantz, n, ktop, kbot, nw, h, ldh, iloz, ihiz, z, ldz, ns, nd, sh, v, ldv, nh, t, ldt, nv, wv, ldwv, work, lwork) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_claqr3 "BLAS_FUNC(claqr3)"(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, npy_complex64 *h, int *ldh, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, int *ns, int *nd, npy_complex64 *sh, npy_complex64 *v, int *ldv, int *nh, npy_complex64 *t, int *ldt, int *nv, npy_complex64 *wv, int *ldwv, npy_complex64 *work, int *lwork) nogil +cdef void claqr3(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, c *h, int *ldh, int *iloz, int *ihiz, c *z, int *ldz, int *ns, int *nd, c *sh, c *v, int *ldv, int *nh, c *t, int *ldt, int *nv, c *wv, int *ldwv, c *work, int *lwork) noexcept nogil: + + _fortran_claqr3(wantt, wantz, n, ktop, kbot, nw, h, ldh, iloz, ihiz, z, ldz, ns, nd, sh, v, ldv, nh, t, ldt, nv, wv, ldwv, work, lwork) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_claqr4 "BLAS_FUNC(claqr4)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, npy_complex64 *h, int *ldh, npy_complex64 *w, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, int *info) nogil +cdef void claqr4(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, c *h, int *ldh, c *w, int *iloz, int *ihiz, c *z, int *ldz, c *work, int *lwork, int *info) noexcept nogil: + + _fortran_claqr4(wantt, wantz, n, ilo, ihi, h, ldh, w, iloz, ihiz, z, ldz, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_claqr5 "BLAS_FUNC(claqr5)"(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, npy_complex64 *s, npy_complex64 *h, int *ldh, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, npy_complex64 *v, int *ldv, npy_complex64 *u, int *ldu, int *nv, npy_complex64 *wv, int *ldwv, int *nh, npy_complex64 *wh, int *ldwh) nogil +cdef void claqr5(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, c *s, c *h, int *ldh, int *iloz, int *ihiz, c *z, int *ldz, c *v, int *ldv, c *u, int *ldu, int *nv, c *wv, int *ldwv, int *nh, c *wh, int *ldwh) noexcept nogil: + + _fortran_claqr5(wantt, wantz, kacc22, n, ktop, kbot, nshfts, s, h, ldh, iloz, ihiz, z, ldz, v, ldv, u, ldu, nv, wv, ldwv, nh, wh, ldwh) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_claqsb "BLAS_FUNC(claqsb)"(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, s *s, s *scond, s *amax, char *equed) nogil +cdef void claqsb(char *uplo, int *n, int *kd, c *ab, int *ldab, s *s, s *scond, s *amax, char *equed) noexcept nogil: + + _fortran_claqsb(uplo, n, kd, ab, ldab, s, scond, amax, equed) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_claqsp "BLAS_FUNC(claqsp)"(char *uplo, int *n, npy_complex64 *ap, s *s, s *scond, s *amax, char *equed) nogil +cdef void claqsp(char *uplo, int *n, c *ap, s *s, s *scond, s *amax, char *equed) noexcept nogil: + + _fortran_claqsp(uplo, n, ap, s, scond, amax, equed) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_claqsy "BLAS_FUNC(claqsy)"(char *uplo, int *n, npy_complex64 *a, int *lda, s *s, s *scond, s *amax, char *equed) nogil +cdef void claqsy(char *uplo, int *n, c *a, int *lda, s *s, s *scond, s *amax, char *equed) noexcept nogil: + + _fortran_claqsy(uplo, n, a, lda, s, scond, amax, equed) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clar1v "BLAS_FUNC(clar1v)"(int *n, int *b1, int *bn, s *lambda_, s *d, s *l, s *ld, s *lld, s *pivmin, s *gaptol, npy_complex64 *z, bint *wantnc, int *negcnt, s *ztz, s *mingma, int *r, int *isuppz, s *nrminv, s *resid, s *rqcorr, s *work) nogil +cdef void clar1v(int *n, int *b1, int *bn, s *lambda_, s *d, s *l, s *ld, s *lld, s *pivmin, s *gaptol, c *z, bint *wantnc, int *negcnt, s *ztz, s *mingma, int *r, int *isuppz, s *nrminv, s *resid, s *rqcorr, s *work) noexcept nogil: + + _fortran_clar1v(n, b1, bn, lambda_, d, l, ld, lld, pivmin, gaptol, z, wantnc, negcnt, ztz, mingma, r, isuppz, nrminv, resid, rqcorr, work) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clar2v "BLAS_FUNC(clar2v)"(int *n, npy_complex64 *x, npy_complex64 *y, npy_complex64 *z, int *incx, s *c, npy_complex64 *s, int *incc) nogil +cdef void clar2v(int *n, c *x, c *y, c *z, int *incx, s *c, c *s, int *incc) noexcept nogil: + + _fortran_clar2v(n, x, y, z, incx, c, s, incc) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clarcm "BLAS_FUNC(clarcm)"(int *m, int *n, s *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *c, int *ldc, s *rwork) nogil +cdef void clarcm(int *m, int *n, s *a, int *lda, c *b, int *ldb, c *c, int *ldc, s *rwork) noexcept nogil: + + _fortran_clarcm(m, n, a, lda, b, ldb, c, ldc, rwork) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clarf "BLAS_FUNC(clarf)"(char *side, int *m, int *n, npy_complex64 *v, int *incv, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work) nogil +cdef void clarf(char *side, int *m, int *n, c *v, int *incv, c *tau, c *c, int *ldc, c *work) noexcept nogil: + + _fortran_clarf(side, m, n, v, incv, tau, c, ldc, work) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clarfb "BLAS_FUNC(clarfb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, npy_complex64 *v, int *ldv, npy_complex64 *t, int *ldt, npy_complex64 *c, int *ldc, npy_complex64 *work, int *ldwork) nogil +cdef void clarfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, c *v, int *ldv, c *t, int *ldt, c *c, int *ldc, c *work, int *ldwork) noexcept nogil: + + _fortran_clarfb(side, trans, direct, storev, m, n, k, v, ldv, t, ldt, c, ldc, work, ldwork) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clarfg "BLAS_FUNC(clarfg)"(int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *tau) nogil +cdef void clarfg(int *n, c *alpha, c *x, int *incx, c *tau) noexcept nogil: + + _fortran_clarfg(n, alpha, x, incx, tau) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clarfgp "BLAS_FUNC(clarfgp)"(int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *tau) nogil +cdef void clarfgp(int *n, c *alpha, c *x, int *incx, c *tau) noexcept nogil: + + _fortran_clarfgp(n, alpha, x, incx, tau) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clarft "BLAS_FUNC(clarft)"(char *direct, char *storev, int *n, int *k, npy_complex64 *v, int *ldv, npy_complex64 *tau, npy_complex64 *t, int *ldt) nogil +cdef void clarft(char *direct, char *storev, int *n, int *k, c *v, int *ldv, c *tau, c *t, int *ldt) noexcept nogil: + + _fortran_clarft(direct, storev, n, k, v, ldv, tau, t, ldt) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clarfx "BLAS_FUNC(clarfx)"(char *side, int *m, int *n, npy_complex64 *v, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work) nogil +cdef void clarfx(char *side, int *m, int *n, c *v, c *tau, c *c, int *ldc, c *work) noexcept nogil: + + _fortran_clarfx(side, m, n, v, tau, c, ldc, work) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clargv "BLAS_FUNC(clargv)"(int *n, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, s *c, int *incc) nogil +cdef void clargv(int *n, c *x, int *incx, c *y, int *incy, s *c, int *incc) noexcept nogil: + + _fortran_clargv(n, x, incx, y, incy, c, incc) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clarnv "BLAS_FUNC(clarnv)"(int *idist, int *iseed, int *n, npy_complex64 *x) nogil +cdef void clarnv(int *idist, int *iseed, int *n, c *x) noexcept nogil: + + _fortran_clarnv(idist, iseed, n, x) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clarrv "BLAS_FUNC(clarrv)"(int *n, s *vl, s *vu, s *d, s *l, s *pivmin, int *isplit, int *m, int *dol, int *dou, s *minrgp, s *rtol1, s *rtol2, s *w, s *werr, s *wgap, int *iblock, int *indexw, s *gers, npy_complex64 *z, int *ldz, int *isuppz, s *work, int *iwork, int *info) nogil +cdef void clarrv(int *n, s *vl, s *vu, s *d, s *l, s *pivmin, int *isplit, int *m, int *dol, int *dou, s *minrgp, s *rtol1, s *rtol2, s *w, s *werr, s *wgap, int *iblock, int *indexw, s *gers, c *z, int *ldz, int *isuppz, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_clarrv(n, vl, vu, d, l, pivmin, isplit, m, dol, dou, minrgp, rtol1, rtol2, w, werr, wgap, iblock, indexw, gers, z, ldz, isuppz, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clartg "BLAS_FUNC(clartg)"(npy_complex64 *f, npy_complex64 *g, s *cs, npy_complex64 *sn, npy_complex64 *r) nogil +cdef void clartg(c *f, c *g, s *cs, c *sn, c *r) noexcept nogil: + + _fortran_clartg(f, g, cs, sn, r) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clartv "BLAS_FUNC(clartv)"(int *n, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, s *c, npy_complex64 *s, int *incc) nogil +cdef void clartv(int *n, c *x, int *incx, c *y, int *incy, s *c, c *s, int *incc) noexcept nogil: + + _fortran_clartv(n, x, incx, y, incy, c, s, incc) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clarz "BLAS_FUNC(clarz)"(char *side, int *m, int *n, int *l, npy_complex64 *v, int *incv, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work) nogil +cdef void clarz(char *side, int *m, int *n, int *l, c *v, int *incv, c *tau, c *c, int *ldc, c *work) noexcept nogil: + + _fortran_clarz(side, m, n, l, v, incv, tau, c, ldc, work) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clarzb "BLAS_FUNC(clarzb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, npy_complex64 *v, int *ldv, npy_complex64 *t, int *ldt, npy_complex64 *c, int *ldc, npy_complex64 *work, int *ldwork) nogil +cdef void clarzb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, c *v, int *ldv, c *t, int *ldt, c *c, int *ldc, c *work, int *ldwork) noexcept nogil: + + _fortran_clarzb(side, trans, direct, storev, m, n, k, l, v, ldv, t, ldt, c, ldc, work, ldwork) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clarzt "BLAS_FUNC(clarzt)"(char *direct, char *storev, int *n, int *k, npy_complex64 *v, int *ldv, npy_complex64 *tau, npy_complex64 *t, int *ldt) nogil +cdef void clarzt(char *direct, char *storev, int *n, int *k, c *v, int *ldv, c *tau, c *t, int *ldt) noexcept nogil: + + _fortran_clarzt(direct, storev, n, k, v, ldv, tau, t, ldt) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clascl "BLAS_FUNC(clascl)"(char *type_bn, int *kl, int *ku, s *cfrom, s *cto, int *m, int *n, npy_complex64 *a, int *lda, int *info) nogil +cdef void clascl(char *type_bn, int *kl, int *ku, s *cfrom, s *cto, int *m, int *n, c *a, int *lda, int *info) noexcept nogil: + + _fortran_clascl(type_bn, kl, ku, cfrom, cto, m, n, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_claset "BLAS_FUNC(claset)"(char *uplo, int *m, int *n, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *a, int *lda) nogil +cdef void claset(char *uplo, int *m, int *n, c *alpha, c *beta, c *a, int *lda) noexcept nogil: + + _fortran_claset(uplo, m, n, alpha, beta, a, lda) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clasr "BLAS_FUNC(clasr)"(char *side, char *pivot, char *direct, int *m, int *n, s *c, s *s, npy_complex64 *a, int *lda) nogil +cdef void clasr(char *side, char *pivot, char *direct, int *m, int *n, s *c, s *s, c *a, int *lda) noexcept nogil: + + _fortran_clasr(side, pivot, direct, m, n, c, s, a, lda) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_classq "BLAS_FUNC(classq)"(int *n, npy_complex64 *x, int *incx, s *scale, s *sumsq) nogil +cdef void classq(int *n, c *x, int *incx, s *scale, s *sumsq) noexcept nogil: + + _fortran_classq(n, x, incx, scale, sumsq) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_claswp "BLAS_FUNC(claswp)"(int *n, npy_complex64 *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) nogil +cdef void claswp(int *n, c *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) noexcept nogil: + + _fortran_claswp(n, a, lda, k1, k2, ipiv, incx) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clasyf "BLAS_FUNC(clasyf)"(char *uplo, int *n, int *nb, int *kb, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *w, int *ldw, int *info) nogil +cdef void clasyf(char *uplo, int *n, int *nb, int *kb, c *a, int *lda, int *ipiv, c *w, int *ldw, int *info) noexcept nogil: + + _fortran_clasyf(uplo, n, nb, kb, a, lda, ipiv, w, ldw, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clatbs "BLAS_FUNC(clatbs)"(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, npy_complex64 *ab, int *ldab, npy_complex64 *x, s *scale, s *cnorm, int *info) nogil +cdef void clatbs(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, c *ab, int *ldab, c *x, s *scale, s *cnorm, int *info) noexcept nogil: + + _fortran_clatbs(uplo, trans, diag, normin, n, kd, ab, ldab, x, scale, cnorm, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clatdf "BLAS_FUNC(clatdf)"(int *ijob, int *n, npy_complex64 *z, int *ldz, npy_complex64 *rhs, s *rdsum, s *rdscal, int *ipiv, int *jpiv) nogil +cdef void clatdf(int *ijob, int *n, c *z, int *ldz, c *rhs, s *rdsum, s *rdscal, int *ipiv, int *jpiv) noexcept nogil: + + _fortran_clatdf(ijob, n, z, ldz, rhs, rdsum, rdscal, ipiv, jpiv) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clatps "BLAS_FUNC(clatps)"(char *uplo, char *trans, char *diag, char *normin, int *n, npy_complex64 *ap, npy_complex64 *x, s *scale, s *cnorm, int *info) nogil +cdef void clatps(char *uplo, char *trans, char *diag, char *normin, int *n, c *ap, c *x, s *scale, s *cnorm, int *info) noexcept nogil: + + _fortran_clatps(uplo, trans, diag, normin, n, ap, x, scale, cnorm, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clatrd "BLAS_FUNC(clatrd)"(char *uplo, int *n, int *nb, npy_complex64 *a, int *lda, s *e, npy_complex64 *tau, npy_complex64 *w, int *ldw) nogil +cdef void clatrd(char *uplo, int *n, int *nb, c *a, int *lda, s *e, c *tau, c *w, int *ldw) noexcept nogil: + + _fortran_clatrd(uplo, n, nb, a, lda, e, tau, w, ldw) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clatrs "BLAS_FUNC(clatrs)"(char *uplo, char *trans, char *diag, char *normin, int *n, npy_complex64 *a, int *lda, npy_complex64 *x, s *scale, s *cnorm, int *info) nogil +cdef void clatrs(char *uplo, char *trans, char *diag, char *normin, int *n, c *a, int *lda, c *x, s *scale, s *cnorm, int *info) noexcept nogil: + + _fortran_clatrs(uplo, trans, diag, normin, n, a, lda, x, scale, cnorm, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clatrz "BLAS_FUNC(clatrz)"(int *m, int *n, int *l, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work) nogil +cdef void clatrz(int *m, int *n, int *l, c *a, int *lda, c *tau, c *work) noexcept nogil: + + _fortran_clatrz(m, n, l, a, lda, tau, work) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clauu2 "BLAS_FUNC(clauu2)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *info) nogil +cdef void clauu2(char *uplo, int *n, c *a, int *lda, int *info) noexcept nogil: + + _fortran_clauu2(uplo, n, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_clauum "BLAS_FUNC(clauum)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *info) nogil +cdef void clauum(char *uplo, int *n, c *a, int *lda, int *info) noexcept nogil: + + _fortran_clauum(uplo, n, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cpbcon "BLAS_FUNC(cpbcon)"(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, s *anorm, s *rcond, npy_complex64 *work, s *rwork, int *info) nogil +cdef void cpbcon(char *uplo, int *n, int *kd, c *ab, int *ldab, s *anorm, s *rcond, c *work, s *rwork, int *info) noexcept nogil: + + _fortran_cpbcon(uplo, n, kd, ab, ldab, anorm, rcond, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cpbequ "BLAS_FUNC(cpbequ)"(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, s *s, s *scond, s *amax, int *info) nogil +cdef void cpbequ(char *uplo, int *n, int *kd, c *ab, int *ldab, s *s, s *scond, s *amax, int *info) noexcept nogil: + + _fortran_cpbequ(uplo, n, kd, ab, ldab, s, scond, amax, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cpbrfs "BLAS_FUNC(cpbrfs)"(char *uplo, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *afb, int *ldafb, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil +cdef void cpbrfs(char *uplo, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *afb, int *ldafb, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil: + + _fortran_cpbrfs(uplo, n, kd, nrhs, ab, ldab, afb, ldafb, b, ldb, x, ldx, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cpbstf "BLAS_FUNC(cpbstf)"(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, int *info) nogil +cdef void cpbstf(char *uplo, int *n, int *kd, c *ab, int *ldab, int *info) noexcept nogil: + + _fortran_cpbstf(uplo, n, kd, ab, ldab, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cpbsv "BLAS_FUNC(cpbsv)"(char *uplo, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *b, int *ldb, int *info) nogil +cdef void cpbsv(char *uplo, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *b, int *ldb, int *info) noexcept nogil: + + _fortran_cpbsv(uplo, n, kd, nrhs, ab, ldab, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cpbsvx "BLAS_FUNC(cpbsvx)"(char *fact, char *uplo, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *afb, int *ldafb, char *equed, s *s, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil +cdef void cpbsvx(char *fact, char *uplo, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *afb, int *ldafb, char *equed, s *s, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil: + + _fortran_cpbsvx(fact, uplo, n, kd, nrhs, ab, ldab, afb, ldafb, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cpbtf2 "BLAS_FUNC(cpbtf2)"(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, int *info) nogil +cdef void cpbtf2(char *uplo, int *n, int *kd, c *ab, int *ldab, int *info) noexcept nogil: + + _fortran_cpbtf2(uplo, n, kd, ab, ldab, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cpbtrf "BLAS_FUNC(cpbtrf)"(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, int *info) nogil +cdef void cpbtrf(char *uplo, int *n, int *kd, c *ab, int *ldab, int *info) noexcept nogil: + + _fortran_cpbtrf(uplo, n, kd, ab, ldab, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cpbtrs "BLAS_FUNC(cpbtrs)"(char *uplo, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *b, int *ldb, int *info) nogil +cdef void cpbtrs(char *uplo, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *b, int *ldb, int *info) noexcept nogil: + + _fortran_cpbtrs(uplo, n, kd, nrhs, ab, ldab, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cpftrf "BLAS_FUNC(cpftrf)"(char *transr, char *uplo, int *n, npy_complex64 *a, int *info) nogil +cdef void cpftrf(char *transr, char *uplo, int *n, c *a, int *info) noexcept nogil: + + _fortran_cpftrf(transr, uplo, n, a, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cpftri "BLAS_FUNC(cpftri)"(char *transr, char *uplo, int *n, npy_complex64 *a, int *info) nogil +cdef void cpftri(char *transr, char *uplo, int *n, c *a, int *info) noexcept nogil: + + _fortran_cpftri(transr, uplo, n, a, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cpftrs "BLAS_FUNC(cpftrs)"(char *transr, char *uplo, int *n, int *nrhs, npy_complex64 *a, npy_complex64 *b, int *ldb, int *info) nogil +cdef void cpftrs(char *transr, char *uplo, int *n, int *nrhs, c *a, c *b, int *ldb, int *info) noexcept nogil: + + _fortran_cpftrs(transr, uplo, n, nrhs, a, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cpocon "BLAS_FUNC(cpocon)"(char *uplo, int *n, npy_complex64 *a, int *lda, s *anorm, s *rcond, npy_complex64 *work, s *rwork, int *info) nogil +cdef void cpocon(char *uplo, int *n, c *a, int *lda, s *anorm, s *rcond, c *work, s *rwork, int *info) noexcept nogil: + + _fortran_cpocon(uplo, n, a, lda, anorm, rcond, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cpoequ "BLAS_FUNC(cpoequ)"(int *n, npy_complex64 *a, int *lda, s *s, s *scond, s *amax, int *info) nogil +cdef void cpoequ(int *n, c *a, int *lda, s *s, s *scond, s *amax, int *info) noexcept nogil: + + _fortran_cpoequ(n, a, lda, s, scond, amax, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cpoequb "BLAS_FUNC(cpoequb)"(int *n, npy_complex64 *a, int *lda, s *s, s *scond, s *amax, int *info) nogil +cdef void cpoequb(int *n, c *a, int *lda, s *s, s *scond, s *amax, int *info) noexcept nogil: + + _fortran_cpoequb(n, a, lda, s, scond, amax, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cporfs "BLAS_FUNC(cporfs)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil +cdef void cporfs(char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil: + + _fortran_cporfs(uplo, n, nrhs, a, lda, af, ldaf, b, ldb, x, ldx, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cposv "BLAS_FUNC(cposv)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *info) nogil +cdef void cposv(char *uplo, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, int *info) noexcept nogil: + + _fortran_cposv(uplo, n, nrhs, a, lda, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cposvx "BLAS_FUNC(cposvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, char *equed, s *s, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil +cdef void cposvx(char *fact, char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, char *equed, s *s, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil: + + _fortran_cposvx(fact, uplo, n, nrhs, a, lda, af, ldaf, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cpotf2 "BLAS_FUNC(cpotf2)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *info) nogil +cdef void cpotf2(char *uplo, int *n, c *a, int *lda, int *info) noexcept nogil: + + _fortran_cpotf2(uplo, n, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cpotrf "BLAS_FUNC(cpotrf)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *info) nogil +cdef void cpotrf(char *uplo, int *n, c *a, int *lda, int *info) noexcept nogil: + + _fortran_cpotrf(uplo, n, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cpotri "BLAS_FUNC(cpotri)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *info) nogil +cdef void cpotri(char *uplo, int *n, c *a, int *lda, int *info) noexcept nogil: + + _fortran_cpotri(uplo, n, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cpotrs "BLAS_FUNC(cpotrs)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *info) nogil +cdef void cpotrs(char *uplo, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, int *info) noexcept nogil: + + _fortran_cpotrs(uplo, n, nrhs, a, lda, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cppcon "BLAS_FUNC(cppcon)"(char *uplo, int *n, npy_complex64 *ap, s *anorm, s *rcond, npy_complex64 *work, s *rwork, int *info) nogil +cdef void cppcon(char *uplo, int *n, c *ap, s *anorm, s *rcond, c *work, s *rwork, int *info) noexcept nogil: + + _fortran_cppcon(uplo, n, ap, anorm, rcond, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cppequ "BLAS_FUNC(cppequ)"(char *uplo, int *n, npy_complex64 *ap, s *s, s *scond, s *amax, int *info) nogil +cdef void cppequ(char *uplo, int *n, c *ap, s *s, s *scond, s *amax, int *info) noexcept nogil: + + _fortran_cppequ(uplo, n, ap, s, scond, amax, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cpprfs "BLAS_FUNC(cpprfs)"(char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil +cdef void cpprfs(char *uplo, int *n, int *nrhs, c *ap, c *afp, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil: + + _fortran_cpprfs(uplo, n, nrhs, ap, afp, b, ldb, x, ldx, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cppsv "BLAS_FUNC(cppsv)"(char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *b, int *ldb, int *info) nogil +cdef void cppsv(char *uplo, int *n, int *nrhs, c *ap, c *b, int *ldb, int *info) noexcept nogil: + + _fortran_cppsv(uplo, n, nrhs, ap, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cppsvx "BLAS_FUNC(cppsvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, char *equed, s *s, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil +cdef void cppsvx(char *fact, char *uplo, int *n, int *nrhs, c *ap, c *afp, char *equed, s *s, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil: + + _fortran_cppsvx(fact, uplo, n, nrhs, ap, afp, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cpptrf "BLAS_FUNC(cpptrf)"(char *uplo, int *n, npy_complex64 *ap, int *info) nogil +cdef void cpptrf(char *uplo, int *n, c *ap, int *info) noexcept nogil: + + _fortran_cpptrf(uplo, n, ap, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cpptri "BLAS_FUNC(cpptri)"(char *uplo, int *n, npy_complex64 *ap, int *info) nogil +cdef void cpptri(char *uplo, int *n, c *ap, int *info) noexcept nogil: + + _fortran_cpptri(uplo, n, ap, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cpptrs "BLAS_FUNC(cpptrs)"(char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *b, int *ldb, int *info) nogil +cdef void cpptrs(char *uplo, int *n, int *nrhs, c *ap, c *b, int *ldb, int *info) noexcept nogil: + + _fortran_cpptrs(uplo, n, nrhs, ap, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cpstf2 "BLAS_FUNC(cpstf2)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) nogil +cdef void cpstf2(char *uplo, int *n, c *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) noexcept nogil: + + _fortran_cpstf2(uplo, n, a, lda, piv, rank, tol, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cpstrf "BLAS_FUNC(cpstrf)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) nogil +cdef void cpstrf(char *uplo, int *n, c *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) noexcept nogil: + + _fortran_cpstrf(uplo, n, a, lda, piv, rank, tol, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cptcon "BLAS_FUNC(cptcon)"(int *n, s *d, npy_complex64 *e, s *anorm, s *rcond, s *rwork, int *info) nogil +cdef void cptcon(int *n, s *d, c *e, s *anorm, s *rcond, s *rwork, int *info) noexcept nogil: + + _fortran_cptcon(n, d, e, anorm, rcond, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cpteqr "BLAS_FUNC(cpteqr)"(char *compz, int *n, s *d, s *e, npy_complex64 *z, int *ldz, s *work, int *info) nogil +cdef void cpteqr(char *compz, int *n, s *d, s *e, c *z, int *ldz, s *work, int *info) noexcept nogil: + + _fortran_cpteqr(compz, n, d, e, z, ldz, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cptrfs "BLAS_FUNC(cptrfs)"(char *uplo, int *n, int *nrhs, s *d, npy_complex64 *e, s *df, npy_complex64 *ef, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil +cdef void cptrfs(char *uplo, int *n, int *nrhs, s *d, c *e, s *df, c *ef, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil: + + _fortran_cptrfs(uplo, n, nrhs, d, e, df, ef, b, ldb, x, ldx, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cptsv "BLAS_FUNC(cptsv)"(int *n, int *nrhs, s *d, npy_complex64 *e, npy_complex64 *b, int *ldb, int *info) nogil +cdef void cptsv(int *n, int *nrhs, s *d, c *e, c *b, int *ldb, int *info) noexcept nogil: + + _fortran_cptsv(n, nrhs, d, e, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cptsvx "BLAS_FUNC(cptsvx)"(char *fact, int *n, int *nrhs, s *d, npy_complex64 *e, s *df, npy_complex64 *ef, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil +cdef void cptsvx(char *fact, int *n, int *nrhs, s *d, c *e, s *df, c *ef, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil: + + _fortran_cptsvx(fact, n, nrhs, d, e, df, ef, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cpttrf "BLAS_FUNC(cpttrf)"(int *n, s *d, npy_complex64 *e, int *info) nogil +cdef void cpttrf(int *n, s *d, c *e, int *info) noexcept nogil: + + _fortran_cpttrf(n, d, e, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cpttrs "BLAS_FUNC(cpttrs)"(char *uplo, int *n, int *nrhs, s *d, npy_complex64 *e, npy_complex64 *b, int *ldb, int *info) nogil +cdef void cpttrs(char *uplo, int *n, int *nrhs, s *d, c *e, c *b, int *ldb, int *info) noexcept nogil: + + _fortran_cpttrs(uplo, n, nrhs, d, e, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cptts2 "BLAS_FUNC(cptts2)"(int *iuplo, int *n, int *nrhs, s *d, npy_complex64 *e, npy_complex64 *b, int *ldb) nogil +cdef void cptts2(int *iuplo, int *n, int *nrhs, s *d, c *e, c *b, int *ldb) noexcept nogil: + + _fortran_cptts2(iuplo, n, nrhs, d, e, b, ldb) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_crot "BLAS_FUNC(crot)"(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy, s *c, npy_complex64 *s) nogil +cdef void crot(int *n, c *cx, int *incx, c *cy, int *incy, s *c, c *s) noexcept nogil: + + _fortran_crot(n, cx, incx, cy, incy, c, s) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cspcon "BLAS_FUNC(cspcon)"(char *uplo, int *n, npy_complex64 *ap, int *ipiv, s *anorm, s *rcond, npy_complex64 *work, int *info) nogil +cdef void cspcon(char *uplo, int *n, c *ap, int *ipiv, s *anorm, s *rcond, c *work, int *info) noexcept nogil: + + _fortran_cspcon(uplo, n, ap, ipiv, anorm, rcond, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cspmv "BLAS_FUNC(cspmv)"(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *ap, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy) nogil +cdef void cspmv(char *uplo, int *n, c *alpha, c *ap, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil: + + _fortran_cspmv(uplo, n, alpha, ap, x, incx, beta, y, incy) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cspr "BLAS_FUNC(cspr)"(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *ap) nogil +cdef void cspr(char *uplo, int *n, c *alpha, c *x, int *incx, c *ap) noexcept nogil: + + _fortran_cspr(uplo, n, alpha, x, incx, ap) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_csprfs "BLAS_FUNC(csprfs)"(char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil +cdef void csprfs(char *uplo, int *n, int *nrhs, c *ap, c *afp, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil: + + _fortran_csprfs(uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cspsv "BLAS_FUNC(cspsv)"(char *uplo, int *n, int *nrhs, npy_complex64 *ap, int *ipiv, npy_complex64 *b, int *ldb, int *info) nogil +cdef void cspsv(char *uplo, int *n, int *nrhs, c *ap, int *ipiv, c *b, int *ldb, int *info) noexcept nogil: + + _fortran_cspsv(uplo, n, nrhs, ap, ipiv, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cspsvx "BLAS_FUNC(cspsvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil +cdef void cspsvx(char *fact, char *uplo, int *n, int *nrhs, c *ap, c *afp, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil: + + _fortran_cspsvx(fact, uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_csptrf "BLAS_FUNC(csptrf)"(char *uplo, int *n, npy_complex64 *ap, int *ipiv, int *info) nogil +cdef void csptrf(char *uplo, int *n, c *ap, int *ipiv, int *info) noexcept nogil: + + _fortran_csptrf(uplo, n, ap, ipiv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_csptri "BLAS_FUNC(csptri)"(char *uplo, int *n, npy_complex64 *ap, int *ipiv, npy_complex64 *work, int *info) nogil +cdef void csptri(char *uplo, int *n, c *ap, int *ipiv, c *work, int *info) noexcept nogil: + + _fortran_csptri(uplo, n, ap, ipiv, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_csptrs "BLAS_FUNC(csptrs)"(char *uplo, int *n, int *nrhs, npy_complex64 *ap, int *ipiv, npy_complex64 *b, int *ldb, int *info) nogil +cdef void csptrs(char *uplo, int *n, int *nrhs, c *ap, int *ipiv, c *b, int *ldb, int *info) noexcept nogil: + + _fortran_csptrs(uplo, n, nrhs, ap, ipiv, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_csrscl "BLAS_FUNC(csrscl)"(int *n, s *sa, npy_complex64 *sx, int *incx) nogil +cdef void csrscl(int *n, s *sa, c *sx, int *incx) noexcept nogil: + + _fortran_csrscl(n, sa, sx, incx) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cstedc "BLAS_FUNC(cstedc)"(char *compz, int *n, s *d, s *e, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil +cdef void cstedc(char *compz, int *n, s *d, s *e, c *z, int *ldz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_cstedc(compz, n, d, e, z, ldz, work, lwork, rwork, lrwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cstegr "BLAS_FUNC(cstegr)"(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, npy_complex64 *z, int *ldz, int *isuppz, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil +cdef void cstegr(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, int *isuppz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_cstegr(jobz, range, n, d, e, vl, vu, il, iu, abstol, m, w, z, ldz, isuppz, work, lwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cstein "BLAS_FUNC(cstein)"(int *n, s *d, s *e, int *m, s *w, int *iblock, int *isplit, npy_complex64 *z, int *ldz, s *work, int *iwork, int *ifail, int *info) nogil +cdef void cstein(int *n, s *d, s *e, int *m, s *w, int *iblock, int *isplit, c *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil: + + _fortran_cstein(n, d, e, m, w, iblock, isplit, z, ldz, work, iwork, ifail, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cstemr "BLAS_FUNC(cstemr)"(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, int *m, s *w, npy_complex64 *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil +cdef void cstemr(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, int *m, s *w, c *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_cstemr(jobz, range, n, d, e, vl, vu, il, iu, m, w, z, ldz, nzc, isuppz, tryrac, work, lwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_csteqr "BLAS_FUNC(csteqr)"(char *compz, int *n, s *d, s *e, npy_complex64 *z, int *ldz, s *work, int *info) nogil +cdef void csteqr(char *compz, int *n, s *d, s *e, c *z, int *ldz, s *work, int *info) noexcept nogil: + + _fortran_csteqr(compz, n, d, e, z, ldz, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_csycon "BLAS_FUNC(csycon)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, s *anorm, s *rcond, npy_complex64 *work, int *info) nogil +cdef void csycon(char *uplo, int *n, c *a, int *lda, int *ipiv, s *anorm, s *rcond, c *work, int *info) noexcept nogil: + + _fortran_csycon(uplo, n, a, lda, ipiv, anorm, rcond, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_csyconv "BLAS_FUNC(csyconv)"(char *uplo, char *way, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *info) nogil +cdef void csyconv(char *uplo, char *way, int *n, c *a, int *lda, int *ipiv, c *work, int *info) noexcept nogil: + + _fortran_csyconv(uplo, way, n, a, lda, ipiv, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_csyequb "BLAS_FUNC(csyequb)"(char *uplo, int *n, npy_complex64 *a, int *lda, s *s, s *scond, s *amax, npy_complex64 *work, int *info) nogil +cdef void csyequb(char *uplo, int *n, c *a, int *lda, s *s, s *scond, s *amax, c *work, int *info) noexcept nogil: + + _fortran_csyequb(uplo, n, a, lda, s, scond, amax, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_csymv "BLAS_FUNC(csymv)"(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy) nogil +cdef void csymv(char *uplo, int *n, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil: + + _fortran_csymv(uplo, n, alpha, a, lda, x, incx, beta, y, incy) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_csyr "BLAS_FUNC(csyr)"(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *a, int *lda) nogil +cdef void csyr(char *uplo, int *n, c *alpha, c *x, int *incx, c *a, int *lda) noexcept nogil: + + _fortran_csyr(uplo, n, alpha, x, incx, a, lda) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_csyrfs "BLAS_FUNC(csyrfs)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil +cdef void csyrfs(char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil: + + _fortran_csyrfs(uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_csysv "BLAS_FUNC(csysv)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *work, int *lwork, int *info) nogil +cdef void csysv(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, c *work, int *lwork, int *info) noexcept nogil: + + _fortran_csysv(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_csysvx "BLAS_FUNC(csysvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, int *lwork, s *rwork, int *info) nogil +cdef void csysvx(char *fact, char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, int *lwork, s *rwork, int *info) noexcept nogil: + + _fortran_csysvx(fact, uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, lwork, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_csyswapr "BLAS_FUNC(csyswapr)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *i1, int *i2) nogil +cdef void csyswapr(char *uplo, int *n, c *a, int *lda, int *i1, int *i2) noexcept nogil: + + _fortran_csyswapr(uplo, n, a, lda, i1, i2) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_csytf2 "BLAS_FUNC(csytf2)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, int *info) nogil +cdef void csytf2(char *uplo, int *n, c *a, int *lda, int *ipiv, int *info) noexcept nogil: + + _fortran_csytf2(uplo, n, a, lda, ipiv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_csytrf "BLAS_FUNC(csytrf)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *lwork, int *info) nogil +cdef void csytrf(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *lwork, int *info) noexcept nogil: + + _fortran_csytrf(uplo, n, a, lda, ipiv, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_csytri "BLAS_FUNC(csytri)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *info) nogil +cdef void csytri(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *info) noexcept nogil: + + _fortran_csytri(uplo, n, a, lda, ipiv, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_csytri2 "BLAS_FUNC(csytri2)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *lwork, int *info) nogil +cdef void csytri2(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *lwork, int *info) noexcept nogil: + + _fortran_csytri2(uplo, n, a, lda, ipiv, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_csytri2x "BLAS_FUNC(csytri2x)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *nb, int *info) nogil +cdef void csytri2x(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *nb, int *info) noexcept nogil: + + _fortran_csytri2x(uplo, n, a, lda, ipiv, work, nb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_csytrs "BLAS_FUNC(csytrs)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, int *info) nogil +cdef void csytrs(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, int *info) noexcept nogil: + + _fortran_csytrs(uplo, n, nrhs, a, lda, ipiv, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_csytrs2 "BLAS_FUNC(csytrs2)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *work, int *info) nogil +cdef void csytrs2(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, c *work, int *info) noexcept nogil: + + _fortran_csytrs2(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ctbcon "BLAS_FUNC(ctbcon)"(char *norm, char *uplo, char *diag, int *n, int *kd, npy_complex64 *ab, int *ldab, s *rcond, npy_complex64 *work, s *rwork, int *info) nogil +cdef void ctbcon(char *norm, char *uplo, char *diag, int *n, int *kd, c *ab, int *ldab, s *rcond, c *work, s *rwork, int *info) noexcept nogil: + + _fortran_ctbcon(norm, uplo, diag, n, kd, ab, ldab, rcond, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ctbrfs "BLAS_FUNC(ctbrfs)"(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil +cdef void ctbrfs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil: + + _fortran_ctbrfs(uplo, trans, diag, n, kd, nrhs, ab, ldab, b, ldb, x, ldx, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ctbtrs "BLAS_FUNC(ctbtrs)"(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *b, int *ldb, int *info) nogil +cdef void ctbtrs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *b, int *ldb, int *info) noexcept nogil: + + _fortran_ctbtrs(uplo, trans, diag, n, kd, nrhs, ab, ldab, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ctfsm "BLAS_FUNC(ctfsm)"(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, npy_complex64 *b, int *ldb) nogil +cdef void ctfsm(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, c *alpha, c *a, c *b, int *ldb) noexcept nogil: + + _fortran_ctfsm(transr, side, uplo, trans, diag, m, n, alpha, a, b, ldb) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ctftri "BLAS_FUNC(ctftri)"(char *transr, char *uplo, char *diag, int *n, npy_complex64 *a, int *info) nogil +cdef void ctftri(char *transr, char *uplo, char *diag, int *n, c *a, int *info) noexcept nogil: + + _fortran_ctftri(transr, uplo, diag, n, a, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ctfttp "BLAS_FUNC(ctfttp)"(char *transr, char *uplo, int *n, npy_complex64 *arf, npy_complex64 *ap, int *info) nogil +cdef void ctfttp(char *transr, char *uplo, int *n, c *arf, c *ap, int *info) noexcept nogil: + + _fortran_ctfttp(transr, uplo, n, arf, ap, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ctfttr "BLAS_FUNC(ctfttr)"(char *transr, char *uplo, int *n, npy_complex64 *arf, npy_complex64 *a, int *lda, int *info) nogil +cdef void ctfttr(char *transr, char *uplo, int *n, c *arf, c *a, int *lda, int *info) noexcept nogil: + + _fortran_ctfttr(transr, uplo, n, arf, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ctgevc "BLAS_FUNC(ctgevc)"(char *side, char *howmny, bint *select, int *n, npy_complex64 *s, int *lds, npy_complex64 *p, int *ldp, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, int *mm, int *m, npy_complex64 *work, s *rwork, int *info) nogil +cdef void ctgevc(char *side, char *howmny, bint *select, int *n, c *s, int *lds, c *p, int *ldp, c *vl, int *ldvl, c *vr, int *ldvr, int *mm, int *m, c *work, s *rwork, int *info) noexcept nogil: + + _fortran_ctgevc(side, howmny, select, n, s, lds, p, ldp, vl, ldvl, vr, ldvr, mm, m, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ctgex2 "BLAS_FUNC(ctgex2)"(bint *wantq, bint *wantz, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *q, int *ldq, npy_complex64 *z, int *ldz, int *j1, int *info) nogil +cdef void ctgex2(bint *wantq, bint *wantz, int *n, c *a, int *lda, c *b, int *ldb, c *q, int *ldq, c *z, int *ldz, int *j1, int *info) noexcept nogil: + + _fortran_ctgex2(wantq, wantz, n, a, lda, b, ldb, q, ldq, z, ldz, j1, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ctgexc "BLAS_FUNC(ctgexc)"(bint *wantq, bint *wantz, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *q, int *ldq, npy_complex64 *z, int *ldz, int *ifst, int *ilst, int *info) nogil +cdef void ctgexc(bint *wantq, bint *wantz, int *n, c *a, int *lda, c *b, int *ldb, c *q, int *ldq, c *z, int *ldz, int *ifst, int *ilst, int *info) noexcept nogil: + + _fortran_ctgexc(wantq, wantz, n, a, lda, b, ldb, q, ldq, z, ldz, ifst, ilst, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ctgsen "BLAS_FUNC(ctgsen)"(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *q, int *ldq, npy_complex64 *z, int *ldz, int *m, s *pl, s *pr, s *dif, npy_complex64 *work, int *lwork, int *iwork, int *liwork, int *info) nogil +cdef void ctgsen(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, c *a, int *lda, c *b, int *ldb, c *alpha, c *beta, c *q, int *ldq, c *z, int *ldz, int *m, s *pl, s *pr, s *dif, c *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_ctgsen(ijob, wantq, wantz, select, n, a, lda, b, ldb, alpha, beta, q, ldq, z, ldz, m, pl, pr, dif, work, lwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ctgsja "BLAS_FUNC(ctgsja)"(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, s *tola, s *tolb, s *alpha, s *beta, npy_complex64 *u, int *ldu, npy_complex64 *v, int *ldv, npy_complex64 *q, int *ldq, npy_complex64 *work, int *ncycle, int *info) nogil +cdef void ctgsja(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, c *a, int *lda, c *b, int *ldb, s *tola, s *tolb, s *alpha, s *beta, c *u, int *ldu, c *v, int *ldv, c *q, int *ldq, c *work, int *ncycle, int *info) noexcept nogil: + + _fortran_ctgsja(jobu, jobv, jobq, m, p, n, k, l, a, lda, b, ldb, tola, tolb, alpha, beta, u, ldu, v, ldv, q, ldq, work, ncycle, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ctgsna "BLAS_FUNC(ctgsna)"(char *job, char *howmny, bint *select, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, s *s, s *dif, int *mm, int *m, npy_complex64 *work, int *lwork, int *iwork, int *info) nogil +cdef void ctgsna(char *job, char *howmny, bint *select, int *n, c *a, int *lda, c *b, int *ldb, c *vl, int *ldvl, c *vr, int *ldvr, s *s, s *dif, int *mm, int *m, c *work, int *lwork, int *iwork, int *info) noexcept nogil: + + _fortran_ctgsna(job, howmny, select, n, a, lda, b, ldb, vl, ldvl, vr, ldvr, s, dif, mm, m, work, lwork, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ctgsy2 "BLAS_FUNC(ctgsy2)"(char *trans, int *ijob, int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *c, int *ldc, npy_complex64 *d, int *ldd, npy_complex64 *e, int *lde, npy_complex64 *f, int *ldf, s *scale, s *rdsum, s *rdscal, int *info) nogil +cdef void ctgsy2(char *trans, int *ijob, int *m, int *n, c *a, int *lda, c *b, int *ldb, c *c, int *ldc, c *d, int *ldd, c *e, int *lde, c *f, int *ldf, s *scale, s *rdsum, s *rdscal, int *info) noexcept nogil: + + _fortran_ctgsy2(trans, ijob, m, n, a, lda, b, ldb, c, ldc, d, ldd, e, lde, f, ldf, scale, rdsum, rdscal, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ctgsyl "BLAS_FUNC(ctgsyl)"(char *trans, int *ijob, int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *c, int *ldc, npy_complex64 *d, int *ldd, npy_complex64 *e, int *lde, npy_complex64 *f, int *ldf, s *scale, s *dif, npy_complex64 *work, int *lwork, int *iwork, int *info) nogil +cdef void ctgsyl(char *trans, int *ijob, int *m, int *n, c *a, int *lda, c *b, int *ldb, c *c, int *ldc, c *d, int *ldd, c *e, int *lde, c *f, int *ldf, s *scale, s *dif, c *work, int *lwork, int *iwork, int *info) noexcept nogil: + + _fortran_ctgsyl(trans, ijob, m, n, a, lda, b, ldb, c, ldc, d, ldd, e, lde, f, ldf, scale, dif, work, lwork, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ctpcon "BLAS_FUNC(ctpcon)"(char *norm, char *uplo, char *diag, int *n, npy_complex64 *ap, s *rcond, npy_complex64 *work, s *rwork, int *info) nogil +cdef void ctpcon(char *norm, char *uplo, char *diag, int *n, c *ap, s *rcond, c *work, s *rwork, int *info) noexcept nogil: + + _fortran_ctpcon(norm, uplo, diag, n, ap, rcond, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ctpmqrt "BLAS_FUNC(ctpmqrt)"(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, npy_complex64 *v, int *ldv, npy_complex64 *t, int *ldt, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *work, int *info) nogil +cdef void ctpmqrt(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, c *v, int *ldv, c *t, int *ldt, c *a, int *lda, c *b, int *ldb, c *work, int *info) noexcept nogil: + + _fortran_ctpmqrt(side, trans, m, n, k, l, nb, v, ldv, t, ldt, a, lda, b, ldb, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ctpqrt "BLAS_FUNC(ctpqrt)"(int *m, int *n, int *l, int *nb, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *t, int *ldt, npy_complex64 *work, int *info) nogil +cdef void ctpqrt(int *m, int *n, int *l, int *nb, c *a, int *lda, c *b, int *ldb, c *t, int *ldt, c *work, int *info) noexcept nogil: + + _fortran_ctpqrt(m, n, l, nb, a, lda, b, ldb, t, ldt, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ctpqrt2 "BLAS_FUNC(ctpqrt2)"(int *m, int *n, int *l, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *t, int *ldt, int *info) nogil +cdef void ctpqrt2(int *m, int *n, int *l, c *a, int *lda, c *b, int *ldb, c *t, int *ldt, int *info) noexcept nogil: + + _fortran_ctpqrt2(m, n, l, a, lda, b, ldb, t, ldt, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ctprfb "BLAS_FUNC(ctprfb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, npy_complex64 *v, int *ldv, npy_complex64 *t, int *ldt, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *work, int *ldwork) nogil +cdef void ctprfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, c *v, int *ldv, c *t, int *ldt, c *a, int *lda, c *b, int *ldb, c *work, int *ldwork) noexcept nogil: + + _fortran_ctprfb(side, trans, direct, storev, m, n, k, l, v, ldv, t, ldt, a, lda, b, ldb, work, ldwork) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ctprfs "BLAS_FUNC(ctprfs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil +cdef void ctprfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, c *ap, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil: + + _fortran_ctprfs(uplo, trans, diag, n, nrhs, ap, b, ldb, x, ldx, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ctptri "BLAS_FUNC(ctptri)"(char *uplo, char *diag, int *n, npy_complex64 *ap, int *info) nogil +cdef void ctptri(char *uplo, char *diag, int *n, c *ap, int *info) noexcept nogil: + + _fortran_ctptri(uplo, diag, n, ap, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ctptrs "BLAS_FUNC(ctptrs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *b, int *ldb, int *info) nogil +cdef void ctptrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, c *ap, c *b, int *ldb, int *info) noexcept nogil: + + _fortran_ctptrs(uplo, trans, diag, n, nrhs, ap, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ctpttf "BLAS_FUNC(ctpttf)"(char *transr, char *uplo, int *n, npy_complex64 *ap, npy_complex64 *arf, int *info) nogil +cdef void ctpttf(char *transr, char *uplo, int *n, c *ap, c *arf, int *info) noexcept nogil: + + _fortran_ctpttf(transr, uplo, n, ap, arf, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ctpttr "BLAS_FUNC(ctpttr)"(char *uplo, int *n, npy_complex64 *ap, npy_complex64 *a, int *lda, int *info) nogil +cdef void ctpttr(char *uplo, int *n, c *ap, c *a, int *lda, int *info) noexcept nogil: + + _fortran_ctpttr(uplo, n, ap, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ctrcon "BLAS_FUNC(ctrcon)"(char *norm, char *uplo, char *diag, int *n, npy_complex64 *a, int *lda, s *rcond, npy_complex64 *work, s *rwork, int *info) nogil +cdef void ctrcon(char *norm, char *uplo, char *diag, int *n, c *a, int *lda, s *rcond, c *work, s *rwork, int *info) noexcept nogil: + + _fortran_ctrcon(norm, uplo, diag, n, a, lda, rcond, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ctrevc "BLAS_FUNC(ctrevc)"(char *side, char *howmny, bint *select, int *n, npy_complex64 *t, int *ldt, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, int *mm, int *m, npy_complex64 *work, s *rwork, int *info) nogil +cdef void ctrevc(char *side, char *howmny, bint *select, int *n, c *t, int *ldt, c *vl, int *ldvl, c *vr, int *ldvr, int *mm, int *m, c *work, s *rwork, int *info) noexcept nogil: + + _fortran_ctrevc(side, howmny, select, n, t, ldt, vl, ldvl, vr, ldvr, mm, m, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ctrexc "BLAS_FUNC(ctrexc)"(char *compq, int *n, npy_complex64 *t, int *ldt, npy_complex64 *q, int *ldq, int *ifst, int *ilst, int *info) nogil +cdef void ctrexc(char *compq, int *n, c *t, int *ldt, c *q, int *ldq, int *ifst, int *ilst, int *info) noexcept nogil: + + _fortran_ctrexc(compq, n, t, ldt, q, ldq, ifst, ilst, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ctrrfs "BLAS_FUNC(ctrrfs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil +cdef void ctrrfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil: + + _fortran_ctrrfs(uplo, trans, diag, n, nrhs, a, lda, b, ldb, x, ldx, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ctrsen "BLAS_FUNC(ctrsen)"(char *job, char *compq, bint *select, int *n, npy_complex64 *t, int *ldt, npy_complex64 *q, int *ldq, npy_complex64 *w, int *m, s *s, s *sep, npy_complex64 *work, int *lwork, int *info) nogil +cdef void ctrsen(char *job, char *compq, bint *select, int *n, c *t, int *ldt, c *q, int *ldq, c *w, int *m, s *s, s *sep, c *work, int *lwork, int *info) noexcept nogil: + + _fortran_ctrsen(job, compq, select, n, t, ldt, q, ldq, w, m, s, sep, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ctrsna "BLAS_FUNC(ctrsna)"(char *job, char *howmny, bint *select, int *n, npy_complex64 *t, int *ldt, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, s *s, s *sep, int *mm, int *m, npy_complex64 *work, int *ldwork, s *rwork, int *info) nogil +cdef void ctrsna(char *job, char *howmny, bint *select, int *n, c *t, int *ldt, c *vl, int *ldvl, c *vr, int *ldvr, s *s, s *sep, int *mm, int *m, c *work, int *ldwork, s *rwork, int *info) noexcept nogil: + + _fortran_ctrsna(job, howmny, select, n, t, ldt, vl, ldvl, vr, ldvr, s, sep, mm, m, work, ldwork, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ctrsyl "BLAS_FUNC(ctrsyl)"(char *trana, char *tranb, int *isgn, int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *c, int *ldc, s *scale, int *info) nogil +cdef void ctrsyl(char *trana, char *tranb, int *isgn, int *m, int *n, c *a, int *lda, c *b, int *ldb, c *c, int *ldc, s *scale, int *info) noexcept nogil: + + _fortran_ctrsyl(trana, tranb, isgn, m, n, a, lda, b, ldb, c, ldc, scale, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ctrti2 "BLAS_FUNC(ctrti2)"(char *uplo, char *diag, int *n, npy_complex64 *a, int *lda, int *info) nogil +cdef void ctrti2(char *uplo, char *diag, int *n, c *a, int *lda, int *info) noexcept nogil: + + _fortran_ctrti2(uplo, diag, n, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ctrtri "BLAS_FUNC(ctrtri)"(char *uplo, char *diag, int *n, npy_complex64 *a, int *lda, int *info) nogil +cdef void ctrtri(char *uplo, char *diag, int *n, c *a, int *lda, int *info) noexcept nogil: + + _fortran_ctrtri(uplo, diag, n, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ctrtrs "BLAS_FUNC(ctrtrs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *info) nogil +cdef void ctrtrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, int *info) noexcept nogil: + + _fortran_ctrtrs(uplo, trans, diag, n, nrhs, a, lda, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ctrttf "BLAS_FUNC(ctrttf)"(char *transr, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *arf, int *info) nogil +cdef void ctrttf(char *transr, char *uplo, int *n, c *a, int *lda, c *arf, int *info) noexcept nogil: + + _fortran_ctrttf(transr, uplo, n, a, lda, arf, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ctrttp "BLAS_FUNC(ctrttp)"(char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *ap, int *info) nogil +cdef void ctrttp(char *uplo, int *n, c *a, int *lda, c *ap, int *info) noexcept nogil: + + _fortran_ctrttp(uplo, n, a, lda, ap, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ctzrzf "BLAS_FUNC(ctzrzf)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil +cdef void ctzrzf(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil: + + _fortran_ctzrzf(m, n, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cunbdb "BLAS_FUNC(cunbdb)"(char *trans, char *signs, int *m, int *p, int *q, npy_complex64 *x11, int *ldx11, npy_complex64 *x12, int *ldx12, npy_complex64 *x21, int *ldx21, npy_complex64 *x22, int *ldx22, s *theta, s *phi, npy_complex64 *taup1, npy_complex64 *taup2, npy_complex64 *tauq1, npy_complex64 *tauq2, npy_complex64 *work, int *lwork, int *info) nogil +cdef void cunbdb(char *trans, char *signs, int *m, int *p, int *q, c *x11, int *ldx11, c *x12, int *ldx12, c *x21, int *ldx21, c *x22, int *ldx22, s *theta, s *phi, c *taup1, c *taup2, c *tauq1, c *tauq2, c *work, int *lwork, int *info) noexcept nogil: + + _fortran_cunbdb(trans, signs, m, p, q, x11, ldx11, x12, ldx12, x21, ldx21, x22, ldx22, theta, phi, taup1, taup2, tauq1, tauq2, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cuncsd "BLAS_FUNC(cuncsd)"(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, npy_complex64 *x11, int *ldx11, npy_complex64 *x12, int *ldx12, npy_complex64 *x21, int *ldx21, npy_complex64 *x22, int *ldx22, s *theta, npy_complex64 *u1, int *ldu1, npy_complex64 *u2, int *ldu2, npy_complex64 *v1t, int *ldv1t, npy_complex64 *v2t, int *ldv2t, npy_complex64 *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *info) nogil +cdef void cuncsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, c *x11, int *ldx11, c *x12, int *ldx12, c *x21, int *ldx21, c *x22, int *ldx22, s *theta, c *u1, int *ldu1, c *u2, int *ldu2, c *v1t, int *ldv1t, c *v2t, int *ldv2t, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *info) noexcept nogil: + + _fortran_cuncsd(jobu1, jobu2, jobv1t, jobv2t, trans, signs, m, p, q, x11, ldx11, x12, ldx12, x21, ldx21, x22, ldx22, theta, u1, ldu1, u2, ldu2, v1t, ldv1t, v2t, ldv2t, work, lwork, rwork, lrwork, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cung2l "BLAS_FUNC(cung2l)"(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info) nogil +cdef void cung2l(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil: + + _fortran_cung2l(m, n, k, a, lda, tau, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cung2r "BLAS_FUNC(cung2r)"(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info) nogil +cdef void cung2r(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil: + + _fortran_cung2r(m, n, k, a, lda, tau, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cungbr "BLAS_FUNC(cungbr)"(char *vect, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil +cdef void cungbr(char *vect, int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil: + + _fortran_cungbr(vect, m, n, k, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cunghr "BLAS_FUNC(cunghr)"(int *n, int *ilo, int *ihi, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil +cdef void cunghr(int *n, int *ilo, int *ihi, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil: + + _fortran_cunghr(n, ilo, ihi, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cungl2 "BLAS_FUNC(cungl2)"(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info) nogil +cdef void cungl2(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil: + + _fortran_cungl2(m, n, k, a, lda, tau, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cunglq "BLAS_FUNC(cunglq)"(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil +cdef void cunglq(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil: + + _fortran_cunglq(m, n, k, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cungql "BLAS_FUNC(cungql)"(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil +cdef void cungql(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil: + + _fortran_cungql(m, n, k, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cungqr "BLAS_FUNC(cungqr)"(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil +cdef void cungqr(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil: + + _fortran_cungqr(m, n, k, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cungr2 "BLAS_FUNC(cungr2)"(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info) nogil +cdef void cungr2(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil: + + _fortran_cungr2(m, n, k, a, lda, tau, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cungrq "BLAS_FUNC(cungrq)"(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil +cdef void cungrq(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil: + + _fortran_cungrq(m, n, k, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cungtr "BLAS_FUNC(cungtr)"(char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil +cdef void cungtr(char *uplo, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil: + + _fortran_cungtr(uplo, n, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cunm2l "BLAS_FUNC(cunm2l)"(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info) nogil +cdef void cunm2l(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil: + + _fortran_cunm2l(side, trans, m, n, k, a, lda, tau, c, ldc, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cunm2r "BLAS_FUNC(cunm2r)"(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info) nogil +cdef void cunm2r(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil: + + _fortran_cunm2r(side, trans, m, n, k, a, lda, tau, c, ldc, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cunmbr "BLAS_FUNC(cunmbr)"(char *vect, char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info) nogil +cdef void cunmbr(char *vect, char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil: + + _fortran_cunmbr(vect, side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cunmhr "BLAS_FUNC(cunmhr)"(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info) nogil +cdef void cunmhr(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil: + + _fortran_cunmhr(side, trans, m, n, ilo, ihi, a, lda, tau, c, ldc, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cunml2 "BLAS_FUNC(cunml2)"(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info) nogil +cdef void cunml2(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil: + + _fortran_cunml2(side, trans, m, n, k, a, lda, tau, c, ldc, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cunmlq "BLAS_FUNC(cunmlq)"(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info) nogil +cdef void cunmlq(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil: + + _fortran_cunmlq(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cunmql "BLAS_FUNC(cunmql)"(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info) nogil +cdef void cunmql(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil: + + _fortran_cunmql(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cunmqr "BLAS_FUNC(cunmqr)"(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info) nogil +cdef void cunmqr(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil: + + _fortran_cunmqr(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cunmr2 "BLAS_FUNC(cunmr2)"(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info) nogil +cdef void cunmr2(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil: + + _fortran_cunmr2(side, trans, m, n, k, a, lda, tau, c, ldc, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cunmr3 "BLAS_FUNC(cunmr3)"(char *side, char *trans, int *m, int *n, int *k, int *l, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info) nogil +cdef void cunmr3(char *side, char *trans, int *m, int *n, int *k, int *l, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil: + + _fortran_cunmr3(side, trans, m, n, k, l, a, lda, tau, c, ldc, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cunmrq "BLAS_FUNC(cunmrq)"(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info) nogil +cdef void cunmrq(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil: + + _fortran_cunmrq(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cunmrz "BLAS_FUNC(cunmrz)"(char *side, char *trans, int *m, int *n, int *k, int *l, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info) nogil +cdef void cunmrz(char *side, char *trans, int *m, int *n, int *k, int *l, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil: + + _fortran_cunmrz(side, trans, m, n, k, l, a, lda, tau, c, ldc, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cunmtr "BLAS_FUNC(cunmtr)"(char *side, char *uplo, char *trans, int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info) nogil +cdef void cunmtr(char *side, char *uplo, char *trans, int *m, int *n, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil: + + _fortran_cunmtr(side, uplo, trans, m, n, a, lda, tau, c, ldc, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cupgtr "BLAS_FUNC(cupgtr)"(char *uplo, int *n, npy_complex64 *ap, npy_complex64 *tau, npy_complex64 *q, int *ldq, npy_complex64 *work, int *info) nogil +cdef void cupgtr(char *uplo, int *n, c *ap, c *tau, c *q, int *ldq, c *work, int *info) noexcept nogil: + + _fortran_cupgtr(uplo, n, ap, tau, q, ldq, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_cupmtr "BLAS_FUNC(cupmtr)"(char *side, char *uplo, char *trans, int *m, int *n, npy_complex64 *ap, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info) nogil +cdef void cupmtr(char *side, char *uplo, char *trans, int *m, int *n, c *ap, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil: + + _fortran_cupmtr(side, uplo, trans, m, n, ap, tau, c, ldc, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dbbcsd "BLAS_FUNC(dbbcsd)"(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, d *theta, d *phi, d *u1, int *ldu1, d *u2, int *ldu2, d *v1t, int *ldv1t, d *v2t, int *ldv2t, d *b11d, d *b11e, d *b12d, d *b12e, d *b21d, d *b21e, d *b22d, d *b22e, d *work, int *lwork, int *info) nogil +cdef void dbbcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, d *theta, d *phi, d *u1, int *ldu1, d *u2, int *ldu2, d *v1t, int *ldv1t, d *v2t, int *ldv2t, d *b11d, d *b11e, d *b12d, d *b12e, d *b21d, d *b21e, d *b22d, d *b22e, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dbbcsd(jobu1, jobu2, jobv1t, jobv2t, trans, m, p, q, theta, phi, u1, ldu1, u2, ldu2, v1t, ldv1t, v2t, ldv2t, b11d, b11e, b12d, b12e, b21d, b21e, b22d, b22e, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dbdsdc "BLAS_FUNC(dbdsdc)"(char *uplo, char *compq, int *n, d *d, d *e, d *u, int *ldu, d *vt, int *ldvt, d *q, int *iq, d *work, int *iwork, int *info) nogil +cdef void dbdsdc(char *uplo, char *compq, int *n, d *d, d *e, d *u, int *ldu, d *vt, int *ldvt, d *q, int *iq, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dbdsdc(uplo, compq, n, d, e, u, ldu, vt, ldvt, q, iq, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dbdsqr "BLAS_FUNC(dbdsqr)"(char *uplo, int *n, int *ncvt, int *nru, int *ncc, d *d, d *e, d *vt, int *ldvt, d *u, int *ldu, d *c, int *ldc, d *work, int *info) nogil +cdef void dbdsqr(char *uplo, int *n, int *ncvt, int *nru, int *ncc, d *d, d *e, d *vt, int *ldvt, d *u, int *ldu, d *c, int *ldc, d *work, int *info) noexcept nogil: + + _fortran_dbdsqr(uplo, n, ncvt, nru, ncc, d, e, vt, ldvt, u, ldu, c, ldc, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ddisna "BLAS_FUNC(ddisna)"(char *job, int *m, int *n, d *d, d *sep, int *info) nogil +cdef void ddisna(char *job, int *m, int *n, d *d, d *sep, int *info) noexcept nogil: + + _fortran_ddisna(job, m, n, d, sep, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgbbrd "BLAS_FUNC(dgbbrd)"(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, d *ab, int *ldab, d *d, d *e, d *q, int *ldq, d *pt, int *ldpt, d *c, int *ldc, d *work, int *info) nogil +cdef void dgbbrd(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, d *ab, int *ldab, d *d, d *e, d *q, int *ldq, d *pt, int *ldpt, d *c, int *ldc, d *work, int *info) noexcept nogil: + + _fortran_dgbbrd(vect, m, n, ncc, kl, ku, ab, ldab, d, e, q, ldq, pt, ldpt, c, ldc, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgbcon "BLAS_FUNC(dgbcon)"(char *norm, int *n, int *kl, int *ku, d *ab, int *ldab, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) nogil +cdef void dgbcon(char *norm, int *n, int *kl, int *ku, d *ab, int *ldab, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dgbcon(norm, n, kl, ku, ab, ldab, ipiv, anorm, rcond, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgbequ "BLAS_FUNC(dgbequ)"(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) nogil +cdef void dgbequ(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil: + + _fortran_dgbequ(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgbequb "BLAS_FUNC(dgbequb)"(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) nogil +cdef void dgbequb(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil: + + _fortran_dgbequb(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgbrfs "BLAS_FUNC(dgbrfs)"(char *trans, int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, d *afb, int *ldafb, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) nogil +cdef void dgbrfs(char *trans, int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, d *afb, int *ldafb, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dgbrfs(trans, n, kl, ku, nrhs, ab, ldab, afb, ldafb, ipiv, b, ldb, x, ldx, ferr, berr, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgbsv "BLAS_FUNC(dgbsv)"(int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, int *ipiv, d *b, int *ldb, int *info) nogil +cdef void dgbsv(int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, int *ipiv, d *b, int *ldb, int *info) noexcept nogil: + + _fortran_dgbsv(n, kl, ku, nrhs, ab, ldab, ipiv, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgbsvx "BLAS_FUNC(dgbsvx)"(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, d *afb, int *ldafb, int *ipiv, char *equed, d *r, d *c, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) nogil +cdef void dgbsvx(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, d *afb, int *ldafb, int *ipiv, char *equed, d *r, d *c, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dgbsvx(fact, trans, n, kl, ku, nrhs, ab, ldab, afb, ldafb, ipiv, equed, r, c, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgbtf2 "BLAS_FUNC(dgbtf2)"(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, int *ipiv, int *info) nogil +cdef void dgbtf2(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, int *ipiv, int *info) noexcept nogil: + + _fortran_dgbtf2(m, n, kl, ku, ab, ldab, ipiv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgbtrf "BLAS_FUNC(dgbtrf)"(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, int *ipiv, int *info) nogil +cdef void dgbtrf(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, int *ipiv, int *info) noexcept nogil: + + _fortran_dgbtrf(m, n, kl, ku, ab, ldab, ipiv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgbtrs "BLAS_FUNC(dgbtrs)"(char *trans, int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, int *ipiv, d *b, int *ldb, int *info) nogil +cdef void dgbtrs(char *trans, int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, int *ipiv, d *b, int *ldb, int *info) noexcept nogil: + + _fortran_dgbtrs(trans, n, kl, ku, nrhs, ab, ldab, ipiv, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgebak "BLAS_FUNC(dgebak)"(char *job, char *side, int *n, int *ilo, int *ihi, d *scale, int *m, d *v, int *ldv, int *info) nogil +cdef void dgebak(char *job, char *side, int *n, int *ilo, int *ihi, d *scale, int *m, d *v, int *ldv, int *info) noexcept nogil: + + _fortran_dgebak(job, side, n, ilo, ihi, scale, m, v, ldv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgebal "BLAS_FUNC(dgebal)"(char *job, int *n, d *a, int *lda, int *ilo, int *ihi, d *scale, int *info) nogil +cdef void dgebal(char *job, int *n, d *a, int *lda, int *ilo, int *ihi, d *scale, int *info) noexcept nogil: + + _fortran_dgebal(job, n, a, lda, ilo, ihi, scale, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgebd2 "BLAS_FUNC(dgebd2)"(int *m, int *n, d *a, int *lda, d *d, d *e, d *tauq, d *taup, d *work, int *info) nogil +cdef void dgebd2(int *m, int *n, d *a, int *lda, d *d, d *e, d *tauq, d *taup, d *work, int *info) noexcept nogil: + + _fortran_dgebd2(m, n, a, lda, d, e, tauq, taup, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgebrd "BLAS_FUNC(dgebrd)"(int *m, int *n, d *a, int *lda, d *d, d *e, d *tauq, d *taup, d *work, int *lwork, int *info) nogil +cdef void dgebrd(int *m, int *n, d *a, int *lda, d *d, d *e, d *tauq, d *taup, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dgebrd(m, n, a, lda, d, e, tauq, taup, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgecon "BLAS_FUNC(dgecon)"(char *norm, int *n, d *a, int *lda, d *anorm, d *rcond, d *work, int *iwork, int *info) nogil +cdef void dgecon(char *norm, int *n, d *a, int *lda, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dgecon(norm, n, a, lda, anorm, rcond, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgeequ "BLAS_FUNC(dgeequ)"(int *m, int *n, d *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) nogil +cdef void dgeequ(int *m, int *n, d *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil: + + _fortran_dgeequ(m, n, a, lda, r, c, rowcnd, colcnd, amax, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgeequb "BLAS_FUNC(dgeequb)"(int *m, int *n, d *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) nogil +cdef void dgeequb(int *m, int *n, d *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil: + + _fortran_dgeequb(m, n, a, lda, r, c, rowcnd, colcnd, amax, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgees "BLAS_FUNC(dgees)"(char *jobvs, char *sort, _dselect2 *select, int *n, d *a, int *lda, int *sdim, d *wr, d *wi, d *vs, int *ldvs, d *work, int *lwork, bint *bwork, int *info) nogil +cdef void dgees(char *jobvs, char *sort, dselect2 *select, int *n, d *a, int *lda, int *sdim, d *wr, d *wi, d *vs, int *ldvs, d *work, int *lwork, bint *bwork, int *info) noexcept nogil: + + _fortran_dgees(jobvs, sort, <_dselect2*>select, n, a, lda, sdim, wr, wi, vs, ldvs, work, lwork, bwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgeesx "BLAS_FUNC(dgeesx)"(char *jobvs, char *sort, _dselect2 *select, char *sense, int *n, d *a, int *lda, int *sdim, d *wr, d *wi, d *vs, int *ldvs, d *rconde, d *rcondv, d *work, int *lwork, int *iwork, int *liwork, bint *bwork, int *info) nogil +cdef void dgeesx(char *jobvs, char *sort, dselect2 *select, char *sense, int *n, d *a, int *lda, int *sdim, d *wr, d *wi, d *vs, int *ldvs, d *rconde, d *rcondv, d *work, int *lwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil: + + _fortran_dgeesx(jobvs, sort, <_dselect2*>select, sense, n, a, lda, sdim, wr, wi, vs, ldvs, rconde, rcondv, work, lwork, iwork, liwork, bwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgeev "BLAS_FUNC(dgeev)"(char *jobvl, char *jobvr, int *n, d *a, int *lda, d *wr, d *wi, d *vl, int *ldvl, d *vr, int *ldvr, d *work, int *lwork, int *info) nogil +cdef void dgeev(char *jobvl, char *jobvr, int *n, d *a, int *lda, d *wr, d *wi, d *vl, int *ldvl, d *vr, int *ldvr, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dgeev(jobvl, jobvr, n, a, lda, wr, wi, vl, ldvl, vr, ldvr, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgeevx "BLAS_FUNC(dgeevx)"(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, d *a, int *lda, d *wr, d *wi, d *vl, int *ldvl, d *vr, int *ldvr, int *ilo, int *ihi, d *scale, d *abnrm, d *rconde, d *rcondv, d *work, int *lwork, int *iwork, int *info) nogil +cdef void dgeevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, d *a, int *lda, d *wr, d *wi, d *vl, int *ldvl, d *vr, int *ldvr, int *ilo, int *ihi, d *scale, d *abnrm, d *rconde, d *rcondv, d *work, int *lwork, int *iwork, int *info) noexcept nogil: + + _fortran_dgeevx(balanc, jobvl, jobvr, sense, n, a, lda, wr, wi, vl, ldvl, vr, ldvr, ilo, ihi, scale, abnrm, rconde, rcondv, work, lwork, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgehd2 "BLAS_FUNC(dgehd2)"(int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *work, int *info) nogil +cdef void dgehd2(int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil: + + _fortran_dgehd2(n, ilo, ihi, a, lda, tau, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgehrd "BLAS_FUNC(dgehrd)"(int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil +cdef void dgehrd(int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dgehrd(n, ilo, ihi, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgejsv "BLAS_FUNC(dgejsv)"(char *joba, char *jobu, char *jobv, char *jobr, char *jobt, char *jobp, int *m, int *n, d *a, int *lda, d *sva, d *u, int *ldu, d *v, int *ldv, d *work, int *lwork, int *iwork, int *info) nogil +cdef void dgejsv(char *joba, char *jobu, char *jobv, char *jobr, char *jobt, char *jobp, int *m, int *n, d *a, int *lda, d *sva, d *u, int *ldu, d *v, int *ldv, d *work, int *lwork, int *iwork, int *info) noexcept nogil: + + _fortran_dgejsv(joba, jobu, jobv, jobr, jobt, jobp, m, n, a, lda, sva, u, ldu, v, ldv, work, lwork, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgelq2 "BLAS_FUNC(dgelq2)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) nogil +cdef void dgelq2(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil: + + _fortran_dgelq2(m, n, a, lda, tau, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgelqf "BLAS_FUNC(dgelqf)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil +cdef void dgelqf(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dgelqf(m, n, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgels "BLAS_FUNC(dgels)"(char *trans, int *m, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *work, int *lwork, int *info) nogil +cdef void dgels(char *trans, int *m, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dgels(trans, m, n, nrhs, a, lda, b, ldb, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgelsd "BLAS_FUNC(dgelsd)"(int *m, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *s, d *rcond, int *rank, d *work, int *lwork, int *iwork, int *info) nogil +cdef void dgelsd(int *m, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *s, d *rcond, int *rank, d *work, int *lwork, int *iwork, int *info) noexcept nogil: + + _fortran_dgelsd(m, n, nrhs, a, lda, b, ldb, s, rcond, rank, work, lwork, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgelss "BLAS_FUNC(dgelss)"(int *m, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *s, d *rcond, int *rank, d *work, int *lwork, int *info) nogil +cdef void dgelss(int *m, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *s, d *rcond, int *rank, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dgelss(m, n, nrhs, a, lda, b, ldb, s, rcond, rank, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgelsy "BLAS_FUNC(dgelsy)"(int *m, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *jpvt, d *rcond, int *rank, d *work, int *lwork, int *info) nogil +cdef void dgelsy(int *m, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *jpvt, d *rcond, int *rank, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dgelsy(m, n, nrhs, a, lda, b, ldb, jpvt, rcond, rank, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgemqrt "BLAS_FUNC(dgemqrt)"(char *side, char *trans, int *m, int *n, int *k, int *nb, d *v, int *ldv, d *t, int *ldt, d *c, int *ldc, d *work, int *info) nogil +cdef void dgemqrt(char *side, char *trans, int *m, int *n, int *k, int *nb, d *v, int *ldv, d *t, int *ldt, d *c, int *ldc, d *work, int *info) noexcept nogil: + + _fortran_dgemqrt(side, trans, m, n, k, nb, v, ldv, t, ldt, c, ldc, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgeql2 "BLAS_FUNC(dgeql2)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) nogil +cdef void dgeql2(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil: + + _fortran_dgeql2(m, n, a, lda, tau, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgeqlf "BLAS_FUNC(dgeqlf)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil +cdef void dgeqlf(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dgeqlf(m, n, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgeqp3 "BLAS_FUNC(dgeqp3)"(int *m, int *n, d *a, int *lda, int *jpvt, d *tau, d *work, int *lwork, int *info) nogil +cdef void dgeqp3(int *m, int *n, d *a, int *lda, int *jpvt, d *tau, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dgeqp3(m, n, a, lda, jpvt, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgeqr2 "BLAS_FUNC(dgeqr2)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) nogil +cdef void dgeqr2(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil: + + _fortran_dgeqr2(m, n, a, lda, tau, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgeqr2p "BLAS_FUNC(dgeqr2p)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) nogil +cdef void dgeqr2p(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil: + + _fortran_dgeqr2p(m, n, a, lda, tau, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgeqrf "BLAS_FUNC(dgeqrf)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil +cdef void dgeqrf(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dgeqrf(m, n, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgeqrfp "BLAS_FUNC(dgeqrfp)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil +cdef void dgeqrfp(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dgeqrfp(m, n, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgeqrt "BLAS_FUNC(dgeqrt)"(int *m, int *n, int *nb, d *a, int *lda, d *t, int *ldt, d *work, int *info) nogil +cdef void dgeqrt(int *m, int *n, int *nb, d *a, int *lda, d *t, int *ldt, d *work, int *info) noexcept nogil: + + _fortran_dgeqrt(m, n, nb, a, lda, t, ldt, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgeqrt2 "BLAS_FUNC(dgeqrt2)"(int *m, int *n, d *a, int *lda, d *t, int *ldt, int *info) nogil +cdef void dgeqrt2(int *m, int *n, d *a, int *lda, d *t, int *ldt, int *info) noexcept nogil: + + _fortran_dgeqrt2(m, n, a, lda, t, ldt, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgeqrt3 "BLAS_FUNC(dgeqrt3)"(int *m, int *n, d *a, int *lda, d *t, int *ldt, int *info) nogil +cdef void dgeqrt3(int *m, int *n, d *a, int *lda, d *t, int *ldt, int *info) noexcept nogil: + + _fortran_dgeqrt3(m, n, a, lda, t, ldt, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgerfs "BLAS_FUNC(dgerfs)"(char *trans, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) nogil +cdef void dgerfs(char *trans, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dgerfs(trans, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, ferr, berr, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgerq2 "BLAS_FUNC(dgerq2)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) nogil +cdef void dgerq2(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil: + + _fortran_dgerq2(m, n, a, lda, tau, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgerqf "BLAS_FUNC(dgerqf)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil +cdef void dgerqf(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dgerqf(m, n, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgesc2 "BLAS_FUNC(dgesc2)"(int *n, d *a, int *lda, d *rhs, int *ipiv, int *jpiv, d *scale) nogil +cdef void dgesc2(int *n, d *a, int *lda, d *rhs, int *ipiv, int *jpiv, d *scale) noexcept nogil: + + _fortran_dgesc2(n, a, lda, rhs, ipiv, jpiv, scale) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgesdd "BLAS_FUNC(dgesdd)"(char *jobz, int *m, int *n, d *a, int *lda, d *s, d *u, int *ldu, d *vt, int *ldvt, d *work, int *lwork, int *iwork, int *info) nogil +cdef void dgesdd(char *jobz, int *m, int *n, d *a, int *lda, d *s, d *u, int *ldu, d *vt, int *ldvt, d *work, int *lwork, int *iwork, int *info) noexcept nogil: + + _fortran_dgesdd(jobz, m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgesv "BLAS_FUNC(dgesv)"(int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, int *info) nogil +cdef void dgesv(int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, int *info) noexcept nogil: + + _fortran_dgesv(n, nrhs, a, lda, ipiv, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgesvd "BLAS_FUNC(dgesvd)"(char *jobu, char *jobvt, int *m, int *n, d *a, int *lda, d *s, d *u, int *ldu, d *vt, int *ldvt, d *work, int *lwork, int *info) nogil +cdef void dgesvd(char *jobu, char *jobvt, int *m, int *n, d *a, int *lda, d *s, d *u, int *ldu, d *vt, int *ldvt, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dgesvd(jobu, jobvt, m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgesvj "BLAS_FUNC(dgesvj)"(char *joba, char *jobu, char *jobv, int *m, int *n, d *a, int *lda, d *sva, int *mv, d *v, int *ldv, d *work, int *lwork, int *info) nogil +cdef void dgesvj(char *joba, char *jobu, char *jobv, int *m, int *n, d *a, int *lda, d *sva, int *mv, d *v, int *ldv, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dgesvj(joba, jobu, jobv, m, n, a, lda, sva, mv, v, ldv, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgesvx "BLAS_FUNC(dgesvx)"(char *fact, char *trans, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, int *ipiv, char *equed, d *r, d *c, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) nogil +cdef void dgesvx(char *fact, char *trans, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, int *ipiv, char *equed, d *r, d *c, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dgesvx(fact, trans, n, nrhs, a, lda, af, ldaf, ipiv, equed, r, c, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgetc2 "BLAS_FUNC(dgetc2)"(int *n, d *a, int *lda, int *ipiv, int *jpiv, int *info) nogil +cdef void dgetc2(int *n, d *a, int *lda, int *ipiv, int *jpiv, int *info) noexcept nogil: + + _fortran_dgetc2(n, a, lda, ipiv, jpiv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgetf2 "BLAS_FUNC(dgetf2)"(int *m, int *n, d *a, int *lda, int *ipiv, int *info) nogil +cdef void dgetf2(int *m, int *n, d *a, int *lda, int *ipiv, int *info) noexcept nogil: + + _fortran_dgetf2(m, n, a, lda, ipiv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgetrf "BLAS_FUNC(dgetrf)"(int *m, int *n, d *a, int *lda, int *ipiv, int *info) nogil +cdef void dgetrf(int *m, int *n, d *a, int *lda, int *ipiv, int *info) noexcept nogil: + + _fortran_dgetrf(m, n, a, lda, ipiv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgetri "BLAS_FUNC(dgetri)"(int *n, d *a, int *lda, int *ipiv, d *work, int *lwork, int *info) nogil +cdef void dgetri(int *n, d *a, int *lda, int *ipiv, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dgetri(n, a, lda, ipiv, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgetrs "BLAS_FUNC(dgetrs)"(char *trans, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, int *info) nogil +cdef void dgetrs(char *trans, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, int *info) noexcept nogil: + + _fortran_dgetrs(trans, n, nrhs, a, lda, ipiv, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dggbak "BLAS_FUNC(dggbak)"(char *job, char *side, int *n, int *ilo, int *ihi, d *lscale, d *rscale, int *m, d *v, int *ldv, int *info) nogil +cdef void dggbak(char *job, char *side, int *n, int *ilo, int *ihi, d *lscale, d *rscale, int *m, d *v, int *ldv, int *info) noexcept nogil: + + _fortran_dggbak(job, side, n, ilo, ihi, lscale, rscale, m, v, ldv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dggbal "BLAS_FUNC(dggbal)"(char *job, int *n, d *a, int *lda, d *b, int *ldb, int *ilo, int *ihi, d *lscale, d *rscale, d *work, int *info) nogil +cdef void dggbal(char *job, int *n, d *a, int *lda, d *b, int *ldb, int *ilo, int *ihi, d *lscale, d *rscale, d *work, int *info) noexcept nogil: + + _fortran_dggbal(job, n, a, lda, b, ldb, ilo, ihi, lscale, rscale, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgges "BLAS_FUNC(dgges)"(char *jobvsl, char *jobvsr, char *sort, _dselect3 *selctg, int *n, d *a, int *lda, d *b, int *ldb, int *sdim, d *alphar, d *alphai, d *beta, d *vsl, int *ldvsl, d *vsr, int *ldvsr, d *work, int *lwork, bint *bwork, int *info) nogil +cdef void dgges(char *jobvsl, char *jobvsr, char *sort, dselect3 *selctg, int *n, d *a, int *lda, d *b, int *ldb, int *sdim, d *alphar, d *alphai, d *beta, d *vsl, int *ldvsl, d *vsr, int *ldvsr, d *work, int *lwork, bint *bwork, int *info) noexcept nogil: + + _fortran_dgges(jobvsl, jobvsr, sort, <_dselect3*>selctg, n, a, lda, b, ldb, sdim, alphar, alphai, beta, vsl, ldvsl, vsr, ldvsr, work, lwork, bwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dggesx "BLAS_FUNC(dggesx)"(char *jobvsl, char *jobvsr, char *sort, _dselect3 *selctg, char *sense, int *n, d *a, int *lda, d *b, int *ldb, int *sdim, d *alphar, d *alphai, d *beta, d *vsl, int *ldvsl, d *vsr, int *ldvsr, d *rconde, d *rcondv, d *work, int *lwork, int *iwork, int *liwork, bint *bwork, int *info) nogil +cdef void dggesx(char *jobvsl, char *jobvsr, char *sort, dselect3 *selctg, char *sense, int *n, d *a, int *lda, d *b, int *ldb, int *sdim, d *alphar, d *alphai, d *beta, d *vsl, int *ldvsl, d *vsr, int *ldvsr, d *rconde, d *rcondv, d *work, int *lwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil: + + _fortran_dggesx(jobvsl, jobvsr, sort, <_dselect3*>selctg, sense, n, a, lda, b, ldb, sdim, alphar, alphai, beta, vsl, ldvsl, vsr, ldvsr, rconde, rcondv, work, lwork, iwork, liwork, bwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dggev "BLAS_FUNC(dggev)"(char *jobvl, char *jobvr, int *n, d *a, int *lda, d *b, int *ldb, d *alphar, d *alphai, d *beta, d *vl, int *ldvl, d *vr, int *ldvr, d *work, int *lwork, int *info) nogil +cdef void dggev(char *jobvl, char *jobvr, int *n, d *a, int *lda, d *b, int *ldb, d *alphar, d *alphai, d *beta, d *vl, int *ldvl, d *vr, int *ldvr, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dggev(jobvl, jobvr, n, a, lda, b, ldb, alphar, alphai, beta, vl, ldvl, vr, ldvr, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dggevx "BLAS_FUNC(dggevx)"(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, d *a, int *lda, d *b, int *ldb, d *alphar, d *alphai, d *beta, d *vl, int *ldvl, d *vr, int *ldvr, int *ilo, int *ihi, d *lscale, d *rscale, d *abnrm, d *bbnrm, d *rconde, d *rcondv, d *work, int *lwork, int *iwork, bint *bwork, int *info) nogil +cdef void dggevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, d *a, int *lda, d *b, int *ldb, d *alphar, d *alphai, d *beta, d *vl, int *ldvl, d *vr, int *ldvr, int *ilo, int *ihi, d *lscale, d *rscale, d *abnrm, d *bbnrm, d *rconde, d *rcondv, d *work, int *lwork, int *iwork, bint *bwork, int *info) noexcept nogil: + + _fortran_dggevx(balanc, jobvl, jobvr, sense, n, a, lda, b, ldb, alphar, alphai, beta, vl, ldvl, vr, ldvr, ilo, ihi, lscale, rscale, abnrm, bbnrm, rconde, rcondv, work, lwork, iwork, bwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dggglm "BLAS_FUNC(dggglm)"(int *n, int *m, int *p, d *a, int *lda, d *b, int *ldb, d *d, d *x, d *y, d *work, int *lwork, int *info) nogil +cdef void dggglm(int *n, int *m, int *p, d *a, int *lda, d *b, int *ldb, d *d, d *x, d *y, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dggglm(n, m, p, a, lda, b, ldb, d, x, y, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgghrd "BLAS_FUNC(dgghrd)"(char *compq, char *compz, int *n, int *ilo, int *ihi, d *a, int *lda, d *b, int *ldb, d *q, int *ldq, d *z, int *ldz, int *info) nogil +cdef void dgghrd(char *compq, char *compz, int *n, int *ilo, int *ihi, d *a, int *lda, d *b, int *ldb, d *q, int *ldq, d *z, int *ldz, int *info) noexcept nogil: + + _fortran_dgghrd(compq, compz, n, ilo, ihi, a, lda, b, ldb, q, ldq, z, ldz, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgglse "BLAS_FUNC(dgglse)"(int *m, int *n, int *p, d *a, int *lda, d *b, int *ldb, d *c, d *d, d *x, d *work, int *lwork, int *info) nogil +cdef void dgglse(int *m, int *n, int *p, d *a, int *lda, d *b, int *ldb, d *c, d *d, d *x, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dgglse(m, n, p, a, lda, b, ldb, c, d, x, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dggqrf "BLAS_FUNC(dggqrf)"(int *n, int *m, int *p, d *a, int *lda, d *taua, d *b, int *ldb, d *taub, d *work, int *lwork, int *info) nogil +cdef void dggqrf(int *n, int *m, int *p, d *a, int *lda, d *taua, d *b, int *ldb, d *taub, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dggqrf(n, m, p, a, lda, taua, b, ldb, taub, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dggrqf "BLAS_FUNC(dggrqf)"(int *m, int *p, int *n, d *a, int *lda, d *taua, d *b, int *ldb, d *taub, d *work, int *lwork, int *info) nogil +cdef void dggrqf(int *m, int *p, int *n, d *a, int *lda, d *taua, d *b, int *ldb, d *taub, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dggrqf(m, p, n, a, lda, taua, b, ldb, taub, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgsvj0 "BLAS_FUNC(dgsvj0)"(char *jobv, int *m, int *n, d *a, int *lda, d *d, d *sva, int *mv, d *v, int *ldv, d *eps, d *sfmin, d *tol, int *nsweep, d *work, int *lwork, int *info) nogil +cdef void dgsvj0(char *jobv, int *m, int *n, d *a, int *lda, d *d, d *sva, int *mv, d *v, int *ldv, d *eps, d *sfmin, d *tol, int *nsweep, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dgsvj0(jobv, m, n, a, lda, d, sva, mv, v, ldv, eps, sfmin, tol, nsweep, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgsvj1 "BLAS_FUNC(dgsvj1)"(char *jobv, int *m, int *n, int *n1, d *a, int *lda, d *d, d *sva, int *mv, d *v, int *ldv, d *eps, d *sfmin, d *tol, int *nsweep, d *work, int *lwork, int *info) nogil +cdef void dgsvj1(char *jobv, int *m, int *n, int *n1, d *a, int *lda, d *d, d *sva, int *mv, d *v, int *ldv, d *eps, d *sfmin, d *tol, int *nsweep, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dgsvj1(jobv, m, n, n1, a, lda, d, sva, mv, v, ldv, eps, sfmin, tol, nsweep, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgtcon "BLAS_FUNC(dgtcon)"(char *norm, int *n, d *dl, d *d, d *du, d *du2, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) nogil +cdef void dgtcon(char *norm, int *n, d *dl, d *d, d *du, d *du2, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dgtcon(norm, n, dl, d, du, du2, ipiv, anorm, rcond, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgtrfs "BLAS_FUNC(dgtrfs)"(char *trans, int *n, int *nrhs, d *dl, d *d, d *du, d *dlf, d *df, d *duf, d *du2, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) nogil +cdef void dgtrfs(char *trans, int *n, int *nrhs, d *dl, d *d, d *du, d *dlf, d *df, d *duf, d *du2, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dgtrfs(trans, n, nrhs, dl, d, du, dlf, df, duf, du2, ipiv, b, ldb, x, ldx, ferr, berr, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgtsv "BLAS_FUNC(dgtsv)"(int *n, int *nrhs, d *dl, d *d, d *du, d *b, int *ldb, int *info) nogil +cdef void dgtsv(int *n, int *nrhs, d *dl, d *d, d *du, d *b, int *ldb, int *info) noexcept nogil: + + _fortran_dgtsv(n, nrhs, dl, d, du, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgtsvx "BLAS_FUNC(dgtsvx)"(char *fact, char *trans, int *n, int *nrhs, d *dl, d *d, d *du, d *dlf, d *df, d *duf, d *du2, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) nogil +cdef void dgtsvx(char *fact, char *trans, int *n, int *nrhs, d *dl, d *d, d *du, d *dlf, d *df, d *duf, d *du2, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dgtsvx(fact, trans, n, nrhs, dl, d, du, dlf, df, duf, du2, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgttrf "BLAS_FUNC(dgttrf)"(int *n, d *dl, d *d, d *du, d *du2, int *ipiv, int *info) nogil +cdef void dgttrf(int *n, d *dl, d *d, d *du, d *du2, int *ipiv, int *info) noexcept nogil: + + _fortran_dgttrf(n, dl, d, du, du2, ipiv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgttrs "BLAS_FUNC(dgttrs)"(char *trans, int *n, int *nrhs, d *dl, d *d, d *du, d *du2, int *ipiv, d *b, int *ldb, int *info) nogil +cdef void dgttrs(char *trans, int *n, int *nrhs, d *dl, d *d, d *du, d *du2, int *ipiv, d *b, int *ldb, int *info) noexcept nogil: + + _fortran_dgttrs(trans, n, nrhs, dl, d, du, du2, ipiv, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dgtts2 "BLAS_FUNC(dgtts2)"(int *itrans, int *n, int *nrhs, d *dl, d *d, d *du, d *du2, int *ipiv, d *b, int *ldb) nogil +cdef void dgtts2(int *itrans, int *n, int *nrhs, d *dl, d *d, d *du, d *du2, int *ipiv, d *b, int *ldb) noexcept nogil: + + _fortran_dgtts2(itrans, n, nrhs, dl, d, du, du2, ipiv, b, ldb) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dhgeqz "BLAS_FUNC(dhgeqz)"(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *t, int *ldt, d *alphar, d *alphai, d *beta, d *q, int *ldq, d *z, int *ldz, d *work, int *lwork, int *info) nogil +cdef void dhgeqz(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *t, int *ldt, d *alphar, d *alphai, d *beta, d *q, int *ldq, d *z, int *ldz, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dhgeqz(job, compq, compz, n, ilo, ihi, h, ldh, t, ldt, alphar, alphai, beta, q, ldq, z, ldz, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dhsein "BLAS_FUNC(dhsein)"(char *side, char *eigsrc, char *initv, bint *select, int *n, d *h, int *ldh, d *wr, d *wi, d *vl, int *ldvl, d *vr, int *ldvr, int *mm, int *m, d *work, int *ifaill, int *ifailr, int *info) nogil +cdef void dhsein(char *side, char *eigsrc, char *initv, bint *select, int *n, d *h, int *ldh, d *wr, d *wi, d *vl, int *ldvl, d *vr, int *ldvr, int *mm, int *m, d *work, int *ifaill, int *ifailr, int *info) noexcept nogil: + + _fortran_dhsein(side, eigsrc, initv, select, n, h, ldh, wr, wi, vl, ldvl, vr, ldvr, mm, m, work, ifaill, ifailr, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dhseqr "BLAS_FUNC(dhseqr)"(char *job, char *compz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *wr, d *wi, d *z, int *ldz, d *work, int *lwork, int *info) nogil +cdef void dhseqr(char *job, char *compz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *wr, d *wi, d *z, int *ldz, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dhseqr(job, compz, n, ilo, ihi, h, ldh, wr, wi, z, ldz, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + bint _fortran_disnan "BLAS_FUNC(disnan)"(d *din) nogil +cdef bint disnan(d *din) noexcept nogil: + + return _fortran_disnan(din) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlabad "BLAS_FUNC(dlabad)"(d *small, d *large) nogil +cdef void dlabad(d *small, d *large) noexcept nogil: + + _fortran_dlabad(small, large) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlabrd "BLAS_FUNC(dlabrd)"(int *m, int *n, int *nb, d *a, int *lda, d *d, d *e, d *tauq, d *taup, d *x, int *ldx, d *y, int *ldy) nogil +cdef void dlabrd(int *m, int *n, int *nb, d *a, int *lda, d *d, d *e, d *tauq, d *taup, d *x, int *ldx, d *y, int *ldy) noexcept nogil: + + _fortran_dlabrd(m, n, nb, a, lda, d, e, tauq, taup, x, ldx, y, ldy) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlacn2 "BLAS_FUNC(dlacn2)"(int *n, d *v, d *x, int *isgn, d *est, int *kase, int *isave) nogil +cdef void dlacn2(int *n, d *v, d *x, int *isgn, d *est, int *kase, int *isave) noexcept nogil: + + _fortran_dlacn2(n, v, x, isgn, est, kase, isave) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlacon "BLAS_FUNC(dlacon)"(int *n, d *v, d *x, int *isgn, d *est, int *kase) nogil +cdef void dlacon(int *n, d *v, d *x, int *isgn, d *est, int *kase) noexcept nogil: + + _fortran_dlacon(n, v, x, isgn, est, kase) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlacpy "BLAS_FUNC(dlacpy)"(char *uplo, int *m, int *n, d *a, int *lda, d *b, int *ldb) nogil +cdef void dlacpy(char *uplo, int *m, int *n, d *a, int *lda, d *b, int *ldb) noexcept nogil: + + _fortran_dlacpy(uplo, m, n, a, lda, b, ldb) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dladiv "BLAS_FUNC(dladiv)"(d *a, d *b, d *c, d *d, d *p, d *q) nogil +cdef void dladiv(d *a, d *b, d *c, d *d, d *p, d *q) noexcept nogil: + + _fortran_dladiv(a, b, c, d, p, q) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlae2 "BLAS_FUNC(dlae2)"(d *a, d *b, d *c, d *rt1, d *rt2) nogil +cdef void dlae2(d *a, d *b, d *c, d *rt1, d *rt2) noexcept nogil: + + _fortran_dlae2(a, b, c, rt1, rt2) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlaebz "BLAS_FUNC(dlaebz)"(int *ijob, int *nitmax, int *n, int *mmax, int *minp, int *nbmin, d *abstol, d *reltol, d *pivmin, d *d, d *e, d *e2, int *nval, d *ab, d *c, int *mout, int *nab, d *work, int *iwork, int *info) nogil +cdef void dlaebz(int *ijob, int *nitmax, int *n, int *mmax, int *minp, int *nbmin, d *abstol, d *reltol, d *pivmin, d *d, d *e, d *e2, int *nval, d *ab, d *c, int *mout, int *nab, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dlaebz(ijob, nitmax, n, mmax, minp, nbmin, abstol, reltol, pivmin, d, e, e2, nval, ab, c, mout, nab, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlaed0 "BLAS_FUNC(dlaed0)"(int *icompq, int *qsiz, int *n, d *d, d *e, d *q, int *ldq, d *qstore, int *ldqs, d *work, int *iwork, int *info) nogil +cdef void dlaed0(int *icompq, int *qsiz, int *n, d *d, d *e, d *q, int *ldq, d *qstore, int *ldqs, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dlaed0(icompq, qsiz, n, d, e, q, ldq, qstore, ldqs, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlaed1 "BLAS_FUNC(dlaed1)"(int *n, d *d, d *q, int *ldq, int *indxq, d *rho, int *cutpnt, d *work, int *iwork, int *info) nogil +cdef void dlaed1(int *n, d *d, d *q, int *ldq, int *indxq, d *rho, int *cutpnt, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dlaed1(n, d, q, ldq, indxq, rho, cutpnt, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlaed2 "BLAS_FUNC(dlaed2)"(int *k, int *n, int *n1, d *d, d *q, int *ldq, int *indxq, d *rho, d *z, d *dlamda, d *w, d *q2, int *indx, int *indxc, int *indxp, int *coltyp, int *info) nogil +cdef void dlaed2(int *k, int *n, int *n1, d *d, d *q, int *ldq, int *indxq, d *rho, d *z, d *dlamda, d *w, d *q2, int *indx, int *indxc, int *indxp, int *coltyp, int *info) noexcept nogil: + + _fortran_dlaed2(k, n, n1, d, q, ldq, indxq, rho, z, dlamda, w, q2, indx, indxc, indxp, coltyp, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlaed3 "BLAS_FUNC(dlaed3)"(int *k, int *n, int *n1, d *d, d *q, int *ldq, d *rho, d *dlamda, d *q2, int *indx, int *ctot, d *w, d *s, int *info) nogil +cdef void dlaed3(int *k, int *n, int *n1, d *d, d *q, int *ldq, d *rho, d *dlamda, d *q2, int *indx, int *ctot, d *w, d *s, int *info) noexcept nogil: + + _fortran_dlaed3(k, n, n1, d, q, ldq, rho, dlamda, q2, indx, ctot, w, s, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlaed4 "BLAS_FUNC(dlaed4)"(int *n, int *i, d *d, d *z, d *delta, d *rho, d *dlam, int *info) nogil +cdef void dlaed4(int *n, int *i, d *d, d *z, d *delta, d *rho, d *dlam, int *info) noexcept nogil: + + _fortran_dlaed4(n, i, d, z, delta, rho, dlam, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlaed5 "BLAS_FUNC(dlaed5)"(int *i, d *d, d *z, d *delta, d *rho, d *dlam) nogil +cdef void dlaed5(int *i, d *d, d *z, d *delta, d *rho, d *dlam) noexcept nogil: + + _fortran_dlaed5(i, d, z, delta, rho, dlam) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlaed6 "BLAS_FUNC(dlaed6)"(int *kniter, bint *orgati, d *rho, d *d, d *z, d *finit, d *tau, int *info) nogil +cdef void dlaed6(int *kniter, bint *orgati, d *rho, d *d, d *z, d *finit, d *tau, int *info) noexcept nogil: + + _fortran_dlaed6(kniter, orgati, rho, d, z, finit, tau, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlaed7 "BLAS_FUNC(dlaed7)"(int *icompq, int *n, int *qsiz, int *tlvls, int *curlvl, int *curpbm, d *d, d *q, int *ldq, int *indxq, d *rho, int *cutpnt, d *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, d *givnum, d *work, int *iwork, int *info) nogil +cdef void dlaed7(int *icompq, int *n, int *qsiz, int *tlvls, int *curlvl, int *curpbm, d *d, d *q, int *ldq, int *indxq, d *rho, int *cutpnt, d *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, d *givnum, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dlaed7(icompq, n, qsiz, tlvls, curlvl, curpbm, d, q, ldq, indxq, rho, cutpnt, qstore, qptr, prmptr, perm, givptr, givcol, givnum, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlaed8 "BLAS_FUNC(dlaed8)"(int *icompq, int *k, int *n, int *qsiz, d *d, d *q, int *ldq, int *indxq, d *rho, int *cutpnt, d *z, d *dlamda, d *q2, int *ldq2, d *w, int *perm, int *givptr, int *givcol, d *givnum, int *indxp, int *indx, int *info) nogil +cdef void dlaed8(int *icompq, int *k, int *n, int *qsiz, d *d, d *q, int *ldq, int *indxq, d *rho, int *cutpnt, d *z, d *dlamda, d *q2, int *ldq2, d *w, int *perm, int *givptr, int *givcol, d *givnum, int *indxp, int *indx, int *info) noexcept nogil: + + _fortran_dlaed8(icompq, k, n, qsiz, d, q, ldq, indxq, rho, cutpnt, z, dlamda, q2, ldq2, w, perm, givptr, givcol, givnum, indxp, indx, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlaed9 "BLAS_FUNC(dlaed9)"(int *k, int *kstart, int *kstop, int *n, d *d, d *q, int *ldq, d *rho, d *dlamda, d *w, d *s, int *lds, int *info) nogil +cdef void dlaed9(int *k, int *kstart, int *kstop, int *n, d *d, d *q, int *ldq, d *rho, d *dlamda, d *w, d *s, int *lds, int *info) noexcept nogil: + + _fortran_dlaed9(k, kstart, kstop, n, d, q, ldq, rho, dlamda, w, s, lds, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlaeda "BLAS_FUNC(dlaeda)"(int *n, int *tlvls, int *curlvl, int *curpbm, int *prmptr, int *perm, int *givptr, int *givcol, d *givnum, d *q, int *qptr, d *z, d *ztemp, int *info) nogil +cdef void dlaeda(int *n, int *tlvls, int *curlvl, int *curpbm, int *prmptr, int *perm, int *givptr, int *givcol, d *givnum, d *q, int *qptr, d *z, d *ztemp, int *info) noexcept nogil: + + _fortran_dlaeda(n, tlvls, curlvl, curpbm, prmptr, perm, givptr, givcol, givnum, q, qptr, z, ztemp, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlaein "BLAS_FUNC(dlaein)"(bint *rightv, bint *noinit, int *n, d *h, int *ldh, d *wr, d *wi, d *vr, d *vi, d *b, int *ldb, d *work, d *eps3, d *smlnum, d *bignum, int *info) nogil +cdef void dlaein(bint *rightv, bint *noinit, int *n, d *h, int *ldh, d *wr, d *wi, d *vr, d *vi, d *b, int *ldb, d *work, d *eps3, d *smlnum, d *bignum, int *info) noexcept nogil: + + _fortran_dlaein(rightv, noinit, n, h, ldh, wr, wi, vr, vi, b, ldb, work, eps3, smlnum, bignum, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlaev2 "BLAS_FUNC(dlaev2)"(d *a, d *b, d *c, d *rt1, d *rt2, d *cs1, d *sn1) nogil +cdef void dlaev2(d *a, d *b, d *c, d *rt1, d *rt2, d *cs1, d *sn1) noexcept nogil: + + _fortran_dlaev2(a, b, c, rt1, rt2, cs1, sn1) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlaexc "BLAS_FUNC(dlaexc)"(bint *wantq, int *n, d *t, int *ldt, d *q, int *ldq, int *j1, int *n1, int *n2, d *work, int *info) nogil +cdef void dlaexc(bint *wantq, int *n, d *t, int *ldt, d *q, int *ldq, int *j1, int *n1, int *n2, d *work, int *info) noexcept nogil: + + _fortran_dlaexc(wantq, n, t, ldt, q, ldq, j1, n1, n2, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlag2 "BLAS_FUNC(dlag2)"(d *a, int *lda, d *b, int *ldb, d *safmin, d *scale1, d *scale2, d *wr1, d *wr2, d *wi) nogil +cdef void dlag2(d *a, int *lda, d *b, int *ldb, d *safmin, d *scale1, d *scale2, d *wr1, d *wr2, d *wi) noexcept nogil: + + _fortran_dlag2(a, lda, b, ldb, safmin, scale1, scale2, wr1, wr2, wi) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlag2s "BLAS_FUNC(dlag2s)"(int *m, int *n, d *a, int *lda, s *sa, int *ldsa, int *info) nogil +cdef void dlag2s(int *m, int *n, d *a, int *lda, s *sa, int *ldsa, int *info) noexcept nogil: + + _fortran_dlag2s(m, n, a, lda, sa, ldsa, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlags2 "BLAS_FUNC(dlags2)"(bint *upper, d *a1, d *a2, d *a3, d *b1, d *b2, d *b3, d *csu, d *snu, d *csv, d *snv, d *csq, d *snq) nogil +cdef void dlags2(bint *upper, d *a1, d *a2, d *a3, d *b1, d *b2, d *b3, d *csu, d *snu, d *csv, d *snv, d *csq, d *snq) noexcept nogil: + + _fortran_dlags2(upper, a1, a2, a3, b1, b2, b3, csu, snu, csv, snv, csq, snq) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlagtf "BLAS_FUNC(dlagtf)"(int *n, d *a, d *lambda_, d *b, d *c, d *tol, d *d, int *in_, int *info) nogil +cdef void dlagtf(int *n, d *a, d *lambda_, d *b, d *c, d *tol, d *d, int *in_, int *info) noexcept nogil: + + _fortran_dlagtf(n, a, lambda_, b, c, tol, d, in_, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlagtm "BLAS_FUNC(dlagtm)"(char *trans, int *n, int *nrhs, d *alpha, d *dl, d *d, d *du, d *x, int *ldx, d *beta, d *b, int *ldb) nogil +cdef void dlagtm(char *trans, int *n, int *nrhs, d *alpha, d *dl, d *d, d *du, d *x, int *ldx, d *beta, d *b, int *ldb) noexcept nogil: + + _fortran_dlagtm(trans, n, nrhs, alpha, dl, d, du, x, ldx, beta, b, ldb) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlagts "BLAS_FUNC(dlagts)"(int *job, int *n, d *a, d *b, d *c, d *d, int *in_, d *y, d *tol, int *info) nogil +cdef void dlagts(int *job, int *n, d *a, d *b, d *c, d *d, int *in_, d *y, d *tol, int *info) noexcept nogil: + + _fortran_dlagts(job, n, a, b, c, d, in_, y, tol, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlagv2 "BLAS_FUNC(dlagv2)"(d *a, int *lda, d *b, int *ldb, d *alphar, d *alphai, d *beta, d *csl, d *snl, d *csr, d *snr) nogil +cdef void dlagv2(d *a, int *lda, d *b, int *ldb, d *alphar, d *alphai, d *beta, d *csl, d *snl, d *csr, d *snr) noexcept nogil: + + _fortran_dlagv2(a, lda, b, ldb, alphar, alphai, beta, csl, snl, csr, snr) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlahqr "BLAS_FUNC(dlahqr)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *wr, d *wi, int *iloz, int *ihiz, d *z, int *ldz, int *info) nogil +cdef void dlahqr(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *wr, d *wi, int *iloz, int *ihiz, d *z, int *ldz, int *info) noexcept nogil: + + _fortran_dlahqr(wantt, wantz, n, ilo, ihi, h, ldh, wr, wi, iloz, ihiz, z, ldz, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlahr2 "BLAS_FUNC(dlahr2)"(int *n, int *k, int *nb, d *a, int *lda, d *tau, d *t, int *ldt, d *y, int *ldy) nogil +cdef void dlahr2(int *n, int *k, int *nb, d *a, int *lda, d *tau, d *t, int *ldt, d *y, int *ldy) noexcept nogil: + + _fortran_dlahr2(n, k, nb, a, lda, tau, t, ldt, y, ldy) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlaic1 "BLAS_FUNC(dlaic1)"(int *job, int *j, d *x, d *sest, d *w, d *gamma, d *sestpr, d *s, d *c) nogil +cdef void dlaic1(int *job, int *j, d *x, d *sest, d *w, d *gamma, d *sestpr, d *s, d *c) noexcept nogil: + + _fortran_dlaic1(job, j, x, sest, w, gamma, sestpr, s, c) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlaln2 "BLAS_FUNC(dlaln2)"(bint *ltrans, int *na, int *nw, d *smin, d *ca, d *a, int *lda, d *d1, d *d2, d *b, int *ldb, d *wr, d *wi, d *x, int *ldx, d *scale, d *xnorm, int *info) nogil +cdef void dlaln2(bint *ltrans, int *na, int *nw, d *smin, d *ca, d *a, int *lda, d *d1, d *d2, d *b, int *ldb, d *wr, d *wi, d *x, int *ldx, d *scale, d *xnorm, int *info) noexcept nogil: + + _fortran_dlaln2(ltrans, na, nw, smin, ca, a, lda, d1, d2, b, ldb, wr, wi, x, ldx, scale, xnorm, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlals0 "BLAS_FUNC(dlals0)"(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, d *b, int *ldb, d *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, d *givnum, int *ldgnum, d *poles, d *difl, d *difr, d *z, int *k, d *c, d *s, d *work, int *info) nogil +cdef void dlals0(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, d *b, int *ldb, d *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, d *givnum, int *ldgnum, d *poles, d *difl, d *difr, d *z, int *k, d *c, d *s, d *work, int *info) noexcept nogil: + + _fortran_dlals0(icompq, nl, nr, sqre, nrhs, b, ldb, bx, ldbx, perm, givptr, givcol, ldgcol, givnum, ldgnum, poles, difl, difr, z, k, c, s, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlalsa "BLAS_FUNC(dlalsa)"(int *icompq, int *smlsiz, int *n, int *nrhs, d *b, int *ldb, d *bx, int *ldbx, d *u, int *ldu, d *vt, int *k, d *difl, d *difr, d *z, d *poles, int *givptr, int *givcol, int *ldgcol, int *perm, d *givnum, d *c, d *s, d *work, int *iwork, int *info) nogil +cdef void dlalsa(int *icompq, int *smlsiz, int *n, int *nrhs, d *b, int *ldb, d *bx, int *ldbx, d *u, int *ldu, d *vt, int *k, d *difl, d *difr, d *z, d *poles, int *givptr, int *givcol, int *ldgcol, int *perm, d *givnum, d *c, d *s, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dlalsa(icompq, smlsiz, n, nrhs, b, ldb, bx, ldbx, u, ldu, vt, k, difl, difr, z, poles, givptr, givcol, ldgcol, perm, givnum, c, s, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlalsd "BLAS_FUNC(dlalsd)"(char *uplo, int *smlsiz, int *n, int *nrhs, d *d, d *e, d *b, int *ldb, d *rcond, int *rank, d *work, int *iwork, int *info) nogil +cdef void dlalsd(char *uplo, int *smlsiz, int *n, int *nrhs, d *d, d *e, d *b, int *ldb, d *rcond, int *rank, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dlalsd(uplo, smlsiz, n, nrhs, d, e, b, ldb, rcond, rank, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + d _fortran_dlamch "BLAS_FUNC(dlamch)"(char *cmach) nogil +cdef d dlamch(char *cmach) noexcept nogil: + + return _fortran_dlamch(cmach) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlamrg "BLAS_FUNC(dlamrg)"(int *n1, int *n2, d *a, int *dtrd1, int *dtrd2, int *index_bn) nogil +cdef void dlamrg(int *n1, int *n2, d *a, int *dtrd1, int *dtrd2, int *index_bn) noexcept nogil: + + _fortran_dlamrg(n1, n2, a, dtrd1, dtrd2, index_bn) + + +cdef extern from "_lapack_subroutines.h": + int _fortran_dlaneg "BLAS_FUNC(dlaneg)"(int *n, d *d, d *lld, d *sigma, d *pivmin, int *r) nogil +cdef int dlaneg(int *n, d *d, d *lld, d *sigma, d *pivmin, int *r) noexcept nogil: + + return _fortran_dlaneg(n, d, lld, sigma, pivmin, r) + + +cdef extern from "_lapack_subroutines.h": + d _fortran_dlangb "BLAS_FUNC(dlangb)"(char *norm, int *n, int *kl, int *ku, d *ab, int *ldab, d *work) nogil +cdef d dlangb(char *norm, int *n, int *kl, int *ku, d *ab, int *ldab, d *work) noexcept nogil: + + return _fortran_dlangb(norm, n, kl, ku, ab, ldab, work) + + +cdef extern from "_lapack_subroutines.h": + d _fortran_dlange "BLAS_FUNC(dlange)"(char *norm, int *m, int *n, d *a, int *lda, d *work) nogil +cdef d dlange(char *norm, int *m, int *n, d *a, int *lda, d *work) noexcept nogil: + + return _fortran_dlange(norm, m, n, a, lda, work) + + +cdef extern from "_lapack_subroutines.h": + d _fortran_dlangt "BLAS_FUNC(dlangt)"(char *norm, int *n, d *dl, d *d_, d *du) nogil +cdef d dlangt(char *norm, int *n, d *dl, d *d_, d *du) noexcept nogil: + + return _fortran_dlangt(norm, n, dl, d_, du) + + +cdef extern from "_lapack_subroutines.h": + d _fortran_dlanhs "BLAS_FUNC(dlanhs)"(char *norm, int *n, d *a, int *lda, d *work) nogil +cdef d dlanhs(char *norm, int *n, d *a, int *lda, d *work) noexcept nogil: + + return _fortran_dlanhs(norm, n, a, lda, work) + + +cdef extern from "_lapack_subroutines.h": + d _fortran_dlansb "BLAS_FUNC(dlansb)"(char *norm, char *uplo, int *n, int *k, d *ab, int *ldab, d *work) nogil +cdef d dlansb(char *norm, char *uplo, int *n, int *k, d *ab, int *ldab, d *work) noexcept nogil: + + return _fortran_dlansb(norm, uplo, n, k, ab, ldab, work) + + +cdef extern from "_lapack_subroutines.h": + d _fortran_dlansf "BLAS_FUNC(dlansf)"(char *norm, char *transr, char *uplo, int *n, d *a, d *work) nogil +cdef d dlansf(char *norm, char *transr, char *uplo, int *n, d *a, d *work) noexcept nogil: + + return _fortran_dlansf(norm, transr, uplo, n, a, work) + + +cdef extern from "_lapack_subroutines.h": + d _fortran_dlansp "BLAS_FUNC(dlansp)"(char *norm, char *uplo, int *n, d *ap, d *work) nogil +cdef d dlansp(char *norm, char *uplo, int *n, d *ap, d *work) noexcept nogil: + + return _fortran_dlansp(norm, uplo, n, ap, work) + + +cdef extern from "_lapack_subroutines.h": + d _fortran_dlanst "BLAS_FUNC(dlanst)"(char *norm, int *n, d *d_, d *e) nogil +cdef d dlanst(char *norm, int *n, d *d_, d *e) noexcept nogil: + + return _fortran_dlanst(norm, n, d_, e) + + +cdef extern from "_lapack_subroutines.h": + d _fortran_dlansy "BLAS_FUNC(dlansy)"(char *norm, char *uplo, int *n, d *a, int *lda, d *work) nogil +cdef d dlansy(char *norm, char *uplo, int *n, d *a, int *lda, d *work) noexcept nogil: + + return _fortran_dlansy(norm, uplo, n, a, lda, work) + + +cdef extern from "_lapack_subroutines.h": + d _fortran_dlantb "BLAS_FUNC(dlantb)"(char *norm, char *uplo, char *diag, int *n, int *k, d *ab, int *ldab, d *work) nogil +cdef d dlantb(char *norm, char *uplo, char *diag, int *n, int *k, d *ab, int *ldab, d *work) noexcept nogil: + + return _fortran_dlantb(norm, uplo, diag, n, k, ab, ldab, work) + + +cdef extern from "_lapack_subroutines.h": + d _fortran_dlantp "BLAS_FUNC(dlantp)"(char *norm, char *uplo, char *diag, int *n, d *ap, d *work) nogil +cdef d dlantp(char *norm, char *uplo, char *diag, int *n, d *ap, d *work) noexcept nogil: + + return _fortran_dlantp(norm, uplo, diag, n, ap, work) + + +cdef extern from "_lapack_subroutines.h": + d _fortran_dlantr "BLAS_FUNC(dlantr)"(char *norm, char *uplo, char *diag, int *m, int *n, d *a, int *lda, d *work) nogil +cdef d dlantr(char *norm, char *uplo, char *diag, int *m, int *n, d *a, int *lda, d *work) noexcept nogil: + + return _fortran_dlantr(norm, uplo, diag, m, n, a, lda, work) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlanv2 "BLAS_FUNC(dlanv2)"(d *a, d *b, d *c, d *d, d *rt1r, d *rt1i, d *rt2r, d *rt2i, d *cs, d *sn) nogil +cdef void dlanv2(d *a, d *b, d *c, d *d, d *rt1r, d *rt1i, d *rt2r, d *rt2i, d *cs, d *sn) noexcept nogil: + + _fortran_dlanv2(a, b, c, d, rt1r, rt1i, rt2r, rt2i, cs, sn) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlapll "BLAS_FUNC(dlapll)"(int *n, d *x, int *incx, d *y, int *incy, d *ssmin) nogil +cdef void dlapll(int *n, d *x, int *incx, d *y, int *incy, d *ssmin) noexcept nogil: + + _fortran_dlapll(n, x, incx, y, incy, ssmin) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlapmr "BLAS_FUNC(dlapmr)"(bint *forwrd, int *m, int *n, d *x, int *ldx, int *k) nogil +cdef void dlapmr(bint *forwrd, int *m, int *n, d *x, int *ldx, int *k) noexcept nogil: + + _fortran_dlapmr(forwrd, m, n, x, ldx, k) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlapmt "BLAS_FUNC(dlapmt)"(bint *forwrd, int *m, int *n, d *x, int *ldx, int *k) nogil +cdef void dlapmt(bint *forwrd, int *m, int *n, d *x, int *ldx, int *k) noexcept nogil: + + _fortran_dlapmt(forwrd, m, n, x, ldx, k) + + +cdef extern from "_lapack_subroutines.h": + d _fortran_dlapy2 "BLAS_FUNC(dlapy2)"(d *x, d *y) nogil +cdef d dlapy2(d *x, d *y) noexcept nogil: + + return _fortran_dlapy2(x, y) + + +cdef extern from "_lapack_subroutines.h": + d _fortran_dlapy3 "BLAS_FUNC(dlapy3)"(d *x, d *y, d *z) nogil +cdef d dlapy3(d *x, d *y, d *z) noexcept nogil: + + return _fortran_dlapy3(x, y, z) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlaqgb "BLAS_FUNC(dlaqgb)"(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) nogil +cdef void dlaqgb(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) noexcept nogil: + + _fortran_dlaqgb(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, equed) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlaqge "BLAS_FUNC(dlaqge)"(int *m, int *n, d *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) nogil +cdef void dlaqge(int *m, int *n, d *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) noexcept nogil: + + _fortran_dlaqge(m, n, a, lda, r, c, rowcnd, colcnd, amax, equed) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlaqp2 "BLAS_FUNC(dlaqp2)"(int *m, int *n, int *offset, d *a, int *lda, int *jpvt, d *tau, d *vn1, d *vn2, d *work) nogil +cdef void dlaqp2(int *m, int *n, int *offset, d *a, int *lda, int *jpvt, d *tau, d *vn1, d *vn2, d *work) noexcept nogil: + + _fortran_dlaqp2(m, n, offset, a, lda, jpvt, tau, vn1, vn2, work) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlaqps "BLAS_FUNC(dlaqps)"(int *m, int *n, int *offset, int *nb, int *kb, d *a, int *lda, int *jpvt, d *tau, d *vn1, d *vn2, d *auxv, d *f, int *ldf) nogil +cdef void dlaqps(int *m, int *n, int *offset, int *nb, int *kb, d *a, int *lda, int *jpvt, d *tau, d *vn1, d *vn2, d *auxv, d *f, int *ldf) noexcept nogil: + + _fortran_dlaqps(m, n, offset, nb, kb, a, lda, jpvt, tau, vn1, vn2, auxv, f, ldf) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlaqr0 "BLAS_FUNC(dlaqr0)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *wr, d *wi, int *iloz, int *ihiz, d *z, int *ldz, d *work, int *lwork, int *info) nogil +cdef void dlaqr0(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *wr, d *wi, int *iloz, int *ihiz, d *z, int *ldz, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dlaqr0(wantt, wantz, n, ilo, ihi, h, ldh, wr, wi, iloz, ihiz, z, ldz, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlaqr1 "BLAS_FUNC(dlaqr1)"(int *n, d *h, int *ldh, d *sr1, d *si1, d *sr2, d *si2, d *v) nogil +cdef void dlaqr1(int *n, d *h, int *ldh, d *sr1, d *si1, d *sr2, d *si2, d *v) noexcept nogil: + + _fortran_dlaqr1(n, h, ldh, sr1, si1, sr2, si2, v) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlaqr2 "BLAS_FUNC(dlaqr2)"(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, d *h, int *ldh, int *iloz, int *ihiz, d *z, int *ldz, int *ns, int *nd, d *sr, d *si, d *v, int *ldv, int *nh, d *t, int *ldt, int *nv, d *wv, int *ldwv, d *work, int *lwork) nogil +cdef void dlaqr2(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, d *h, int *ldh, int *iloz, int *ihiz, d *z, int *ldz, int *ns, int *nd, d *sr, d *si, d *v, int *ldv, int *nh, d *t, int *ldt, int *nv, d *wv, int *ldwv, d *work, int *lwork) noexcept nogil: + + _fortran_dlaqr2(wantt, wantz, n, ktop, kbot, nw, h, ldh, iloz, ihiz, z, ldz, ns, nd, sr, si, v, ldv, nh, t, ldt, nv, wv, ldwv, work, lwork) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlaqr3 "BLAS_FUNC(dlaqr3)"(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, d *h, int *ldh, int *iloz, int *ihiz, d *z, int *ldz, int *ns, int *nd, d *sr, d *si, d *v, int *ldv, int *nh, d *t, int *ldt, int *nv, d *wv, int *ldwv, d *work, int *lwork) nogil +cdef void dlaqr3(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, d *h, int *ldh, int *iloz, int *ihiz, d *z, int *ldz, int *ns, int *nd, d *sr, d *si, d *v, int *ldv, int *nh, d *t, int *ldt, int *nv, d *wv, int *ldwv, d *work, int *lwork) noexcept nogil: + + _fortran_dlaqr3(wantt, wantz, n, ktop, kbot, nw, h, ldh, iloz, ihiz, z, ldz, ns, nd, sr, si, v, ldv, nh, t, ldt, nv, wv, ldwv, work, lwork) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlaqr4 "BLAS_FUNC(dlaqr4)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *wr, d *wi, int *iloz, int *ihiz, d *z, int *ldz, d *work, int *lwork, int *info) nogil +cdef void dlaqr4(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *wr, d *wi, int *iloz, int *ihiz, d *z, int *ldz, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dlaqr4(wantt, wantz, n, ilo, ihi, h, ldh, wr, wi, iloz, ihiz, z, ldz, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlaqr5 "BLAS_FUNC(dlaqr5)"(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, d *sr, d *si, d *h, int *ldh, int *iloz, int *ihiz, d *z, int *ldz, d *v, int *ldv, d *u, int *ldu, int *nv, d *wv, int *ldwv, int *nh, d *wh, int *ldwh) nogil +cdef void dlaqr5(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, d *sr, d *si, d *h, int *ldh, int *iloz, int *ihiz, d *z, int *ldz, d *v, int *ldv, d *u, int *ldu, int *nv, d *wv, int *ldwv, int *nh, d *wh, int *ldwh) noexcept nogil: + + _fortran_dlaqr5(wantt, wantz, kacc22, n, ktop, kbot, nshfts, sr, si, h, ldh, iloz, ihiz, z, ldz, v, ldv, u, ldu, nv, wv, ldwv, nh, wh, ldwh) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlaqsb "BLAS_FUNC(dlaqsb)"(char *uplo, int *n, int *kd, d *ab, int *ldab, d *s, d *scond, d *amax, char *equed) nogil +cdef void dlaqsb(char *uplo, int *n, int *kd, d *ab, int *ldab, d *s, d *scond, d *amax, char *equed) noexcept nogil: + + _fortran_dlaqsb(uplo, n, kd, ab, ldab, s, scond, amax, equed) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlaqsp "BLAS_FUNC(dlaqsp)"(char *uplo, int *n, d *ap, d *s, d *scond, d *amax, char *equed) nogil +cdef void dlaqsp(char *uplo, int *n, d *ap, d *s, d *scond, d *amax, char *equed) noexcept nogil: + + _fortran_dlaqsp(uplo, n, ap, s, scond, amax, equed) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlaqsy "BLAS_FUNC(dlaqsy)"(char *uplo, int *n, d *a, int *lda, d *s, d *scond, d *amax, char *equed) nogil +cdef void dlaqsy(char *uplo, int *n, d *a, int *lda, d *s, d *scond, d *amax, char *equed) noexcept nogil: + + _fortran_dlaqsy(uplo, n, a, lda, s, scond, amax, equed) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlaqtr "BLAS_FUNC(dlaqtr)"(bint *ltran, bint *lreal, int *n, d *t, int *ldt, d *b, d *w, d *scale, d *x, d *work, int *info) nogil +cdef void dlaqtr(bint *ltran, bint *lreal, int *n, d *t, int *ldt, d *b, d *w, d *scale, d *x, d *work, int *info) noexcept nogil: + + _fortran_dlaqtr(ltran, lreal, n, t, ldt, b, w, scale, x, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlar1v "BLAS_FUNC(dlar1v)"(int *n, int *b1, int *bn, d *lambda_, d *d, d *l, d *ld, d *lld, d *pivmin, d *gaptol, d *z, bint *wantnc, int *negcnt, d *ztz, d *mingma, int *r, int *isuppz, d *nrminv, d *resid, d *rqcorr, d *work) nogil +cdef void dlar1v(int *n, int *b1, int *bn, d *lambda_, d *d, d *l, d *ld, d *lld, d *pivmin, d *gaptol, d *z, bint *wantnc, int *negcnt, d *ztz, d *mingma, int *r, int *isuppz, d *nrminv, d *resid, d *rqcorr, d *work) noexcept nogil: + + _fortran_dlar1v(n, b1, bn, lambda_, d, l, ld, lld, pivmin, gaptol, z, wantnc, negcnt, ztz, mingma, r, isuppz, nrminv, resid, rqcorr, work) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlar2v "BLAS_FUNC(dlar2v)"(int *n, d *x, d *y, d *z, int *incx, d *c, d *s, int *incc) nogil +cdef void dlar2v(int *n, d *x, d *y, d *z, int *incx, d *c, d *s, int *incc) noexcept nogil: + + _fortran_dlar2v(n, x, y, z, incx, c, s, incc) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlarf "BLAS_FUNC(dlarf)"(char *side, int *m, int *n, d *v, int *incv, d *tau, d *c, int *ldc, d *work) nogil +cdef void dlarf(char *side, int *m, int *n, d *v, int *incv, d *tau, d *c, int *ldc, d *work) noexcept nogil: + + _fortran_dlarf(side, m, n, v, incv, tau, c, ldc, work) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlarfb "BLAS_FUNC(dlarfb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, d *v, int *ldv, d *t, int *ldt, d *c, int *ldc, d *work, int *ldwork) nogil +cdef void dlarfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, d *v, int *ldv, d *t, int *ldt, d *c, int *ldc, d *work, int *ldwork) noexcept nogil: + + _fortran_dlarfb(side, trans, direct, storev, m, n, k, v, ldv, t, ldt, c, ldc, work, ldwork) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlarfg "BLAS_FUNC(dlarfg)"(int *n, d *alpha, d *x, int *incx, d *tau) nogil +cdef void dlarfg(int *n, d *alpha, d *x, int *incx, d *tau) noexcept nogil: + + _fortran_dlarfg(n, alpha, x, incx, tau) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlarfgp "BLAS_FUNC(dlarfgp)"(int *n, d *alpha, d *x, int *incx, d *tau) nogil +cdef void dlarfgp(int *n, d *alpha, d *x, int *incx, d *tau) noexcept nogil: + + _fortran_dlarfgp(n, alpha, x, incx, tau) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlarft "BLAS_FUNC(dlarft)"(char *direct, char *storev, int *n, int *k, d *v, int *ldv, d *tau, d *t, int *ldt) nogil +cdef void dlarft(char *direct, char *storev, int *n, int *k, d *v, int *ldv, d *tau, d *t, int *ldt) noexcept nogil: + + _fortran_dlarft(direct, storev, n, k, v, ldv, tau, t, ldt) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlarfx "BLAS_FUNC(dlarfx)"(char *side, int *m, int *n, d *v, d *tau, d *c, int *ldc, d *work) nogil +cdef void dlarfx(char *side, int *m, int *n, d *v, d *tau, d *c, int *ldc, d *work) noexcept nogil: + + _fortran_dlarfx(side, m, n, v, tau, c, ldc, work) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlargv "BLAS_FUNC(dlargv)"(int *n, d *x, int *incx, d *y, int *incy, d *c, int *incc) nogil +cdef void dlargv(int *n, d *x, int *incx, d *y, int *incy, d *c, int *incc) noexcept nogil: + + _fortran_dlargv(n, x, incx, y, incy, c, incc) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlarnv "BLAS_FUNC(dlarnv)"(int *idist, int *iseed, int *n, d *x) nogil +cdef void dlarnv(int *idist, int *iseed, int *n, d *x) noexcept nogil: + + _fortran_dlarnv(idist, iseed, n, x) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlarra "BLAS_FUNC(dlarra)"(int *n, d *d, d *e, d *e2, d *spltol, d *tnrm, int *nsplit, int *isplit, int *info) nogil +cdef void dlarra(int *n, d *d, d *e, d *e2, d *spltol, d *tnrm, int *nsplit, int *isplit, int *info) noexcept nogil: + + _fortran_dlarra(n, d, e, e2, spltol, tnrm, nsplit, isplit, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlarrb "BLAS_FUNC(dlarrb)"(int *n, d *d, d *lld, int *ifirst, int *ilast, d *rtol1, d *rtol2, int *offset, d *w, d *wgap, d *werr, d *work, int *iwork, d *pivmin, d *spdiam, int *twist, int *info) nogil +cdef void dlarrb(int *n, d *d, d *lld, int *ifirst, int *ilast, d *rtol1, d *rtol2, int *offset, d *w, d *wgap, d *werr, d *work, int *iwork, d *pivmin, d *spdiam, int *twist, int *info) noexcept nogil: + + _fortran_dlarrb(n, d, lld, ifirst, ilast, rtol1, rtol2, offset, w, wgap, werr, work, iwork, pivmin, spdiam, twist, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlarrc "BLAS_FUNC(dlarrc)"(char *jobt, int *n, d *vl, d *vu, d *d, d *e, d *pivmin, int *eigcnt, int *lcnt, int *rcnt, int *info) nogil +cdef void dlarrc(char *jobt, int *n, d *vl, d *vu, d *d, d *e, d *pivmin, int *eigcnt, int *lcnt, int *rcnt, int *info) noexcept nogil: + + _fortran_dlarrc(jobt, n, vl, vu, d, e, pivmin, eigcnt, lcnt, rcnt, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlarrd "BLAS_FUNC(dlarrd)"(char *range, char *order, int *n, d *vl, d *vu, int *il, int *iu, d *gers, d *reltol, d *d, d *e, d *e2, d *pivmin, int *nsplit, int *isplit, int *m, d *w, d *werr, d *wl, d *wu, int *iblock, int *indexw, d *work, int *iwork, int *info) nogil +cdef void dlarrd(char *range, char *order, int *n, d *vl, d *vu, int *il, int *iu, d *gers, d *reltol, d *d, d *e, d *e2, d *pivmin, int *nsplit, int *isplit, int *m, d *w, d *werr, d *wl, d *wu, int *iblock, int *indexw, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dlarrd(range, order, n, vl, vu, il, iu, gers, reltol, d, e, e2, pivmin, nsplit, isplit, m, w, werr, wl, wu, iblock, indexw, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlarre "BLAS_FUNC(dlarre)"(char *range, int *n, d *vl, d *vu, int *il, int *iu, d *d, d *e, d *e2, d *rtol1, d *rtol2, d *spltol, int *nsplit, int *isplit, int *m, d *w, d *werr, d *wgap, int *iblock, int *indexw, d *gers, d *pivmin, d *work, int *iwork, int *info) nogil +cdef void dlarre(char *range, int *n, d *vl, d *vu, int *il, int *iu, d *d, d *e, d *e2, d *rtol1, d *rtol2, d *spltol, int *nsplit, int *isplit, int *m, d *w, d *werr, d *wgap, int *iblock, int *indexw, d *gers, d *pivmin, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dlarre(range, n, vl, vu, il, iu, d, e, e2, rtol1, rtol2, spltol, nsplit, isplit, m, w, werr, wgap, iblock, indexw, gers, pivmin, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlarrf "BLAS_FUNC(dlarrf)"(int *n, d *d, d *l, d *ld, int *clstrt, int *clend, d *w, d *wgap, d *werr, d *spdiam, d *clgapl, d *clgapr, d *pivmin, d *sigma, d *dplus, d *lplus, d *work, int *info) nogil +cdef void dlarrf(int *n, d *d, d *l, d *ld, int *clstrt, int *clend, d *w, d *wgap, d *werr, d *spdiam, d *clgapl, d *clgapr, d *pivmin, d *sigma, d *dplus, d *lplus, d *work, int *info) noexcept nogil: + + _fortran_dlarrf(n, d, l, ld, clstrt, clend, w, wgap, werr, spdiam, clgapl, clgapr, pivmin, sigma, dplus, lplus, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlarrj "BLAS_FUNC(dlarrj)"(int *n, d *d, d *e2, int *ifirst, int *ilast, d *rtol, int *offset, d *w, d *werr, d *work, int *iwork, d *pivmin, d *spdiam, int *info) nogil +cdef void dlarrj(int *n, d *d, d *e2, int *ifirst, int *ilast, d *rtol, int *offset, d *w, d *werr, d *work, int *iwork, d *pivmin, d *spdiam, int *info) noexcept nogil: + + _fortran_dlarrj(n, d, e2, ifirst, ilast, rtol, offset, w, werr, work, iwork, pivmin, spdiam, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlarrk "BLAS_FUNC(dlarrk)"(int *n, int *iw, d *gl, d *gu, d *d, d *e2, d *pivmin, d *reltol, d *w, d *werr, int *info) nogil +cdef void dlarrk(int *n, int *iw, d *gl, d *gu, d *d, d *e2, d *pivmin, d *reltol, d *w, d *werr, int *info) noexcept nogil: + + _fortran_dlarrk(n, iw, gl, gu, d, e2, pivmin, reltol, w, werr, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlarrr "BLAS_FUNC(dlarrr)"(int *n, d *d, d *e, int *info) nogil +cdef void dlarrr(int *n, d *d, d *e, int *info) noexcept nogil: + + _fortran_dlarrr(n, d, e, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlarrv "BLAS_FUNC(dlarrv)"(int *n, d *vl, d *vu, d *d, d *l, d *pivmin, int *isplit, int *m, int *dol, int *dou, d *minrgp, d *rtol1, d *rtol2, d *w, d *werr, d *wgap, int *iblock, int *indexw, d *gers, d *z, int *ldz, int *isuppz, d *work, int *iwork, int *info) nogil +cdef void dlarrv(int *n, d *vl, d *vu, d *d, d *l, d *pivmin, int *isplit, int *m, int *dol, int *dou, d *minrgp, d *rtol1, d *rtol2, d *w, d *werr, d *wgap, int *iblock, int *indexw, d *gers, d *z, int *ldz, int *isuppz, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dlarrv(n, vl, vu, d, l, pivmin, isplit, m, dol, dou, minrgp, rtol1, rtol2, w, werr, wgap, iblock, indexw, gers, z, ldz, isuppz, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlartg "BLAS_FUNC(dlartg)"(d *f, d *g, d *cs, d *sn, d *r) nogil +cdef void dlartg(d *f, d *g, d *cs, d *sn, d *r) noexcept nogil: + + _fortran_dlartg(f, g, cs, sn, r) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlartgp "BLAS_FUNC(dlartgp)"(d *f, d *g, d *cs, d *sn, d *r) nogil +cdef void dlartgp(d *f, d *g, d *cs, d *sn, d *r) noexcept nogil: + + _fortran_dlartgp(f, g, cs, sn, r) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlartgs "BLAS_FUNC(dlartgs)"(d *x, d *y, d *sigma, d *cs, d *sn) nogil +cdef void dlartgs(d *x, d *y, d *sigma, d *cs, d *sn) noexcept nogil: + + _fortran_dlartgs(x, y, sigma, cs, sn) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlartv "BLAS_FUNC(dlartv)"(int *n, d *x, int *incx, d *y, int *incy, d *c, d *s, int *incc) nogil +cdef void dlartv(int *n, d *x, int *incx, d *y, int *incy, d *c, d *s, int *incc) noexcept nogil: + + _fortran_dlartv(n, x, incx, y, incy, c, s, incc) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlaruv "BLAS_FUNC(dlaruv)"(int *iseed, int *n, d *x) nogil +cdef void dlaruv(int *iseed, int *n, d *x) noexcept nogil: + + _fortran_dlaruv(iseed, n, x) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlarz "BLAS_FUNC(dlarz)"(char *side, int *m, int *n, int *l, d *v, int *incv, d *tau, d *c, int *ldc, d *work) nogil +cdef void dlarz(char *side, int *m, int *n, int *l, d *v, int *incv, d *tau, d *c, int *ldc, d *work) noexcept nogil: + + _fortran_dlarz(side, m, n, l, v, incv, tau, c, ldc, work) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlarzb "BLAS_FUNC(dlarzb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, d *v, int *ldv, d *t, int *ldt, d *c, int *ldc, d *work, int *ldwork) nogil +cdef void dlarzb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, d *v, int *ldv, d *t, int *ldt, d *c, int *ldc, d *work, int *ldwork) noexcept nogil: + + _fortran_dlarzb(side, trans, direct, storev, m, n, k, l, v, ldv, t, ldt, c, ldc, work, ldwork) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlarzt "BLAS_FUNC(dlarzt)"(char *direct, char *storev, int *n, int *k, d *v, int *ldv, d *tau, d *t, int *ldt) nogil +cdef void dlarzt(char *direct, char *storev, int *n, int *k, d *v, int *ldv, d *tau, d *t, int *ldt) noexcept nogil: + + _fortran_dlarzt(direct, storev, n, k, v, ldv, tau, t, ldt) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlas2 "BLAS_FUNC(dlas2)"(d *f, d *g, d *h, d *ssmin, d *ssmax) nogil +cdef void dlas2(d *f, d *g, d *h, d *ssmin, d *ssmax) noexcept nogil: + + _fortran_dlas2(f, g, h, ssmin, ssmax) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlascl "BLAS_FUNC(dlascl)"(char *type_bn, int *kl, int *ku, d *cfrom, d *cto, int *m, int *n, d *a, int *lda, int *info) nogil +cdef void dlascl(char *type_bn, int *kl, int *ku, d *cfrom, d *cto, int *m, int *n, d *a, int *lda, int *info) noexcept nogil: + + _fortran_dlascl(type_bn, kl, ku, cfrom, cto, m, n, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlasd0 "BLAS_FUNC(dlasd0)"(int *n, int *sqre, d *d, d *e, d *u, int *ldu, d *vt, int *ldvt, int *smlsiz, int *iwork, d *work, int *info) nogil +cdef void dlasd0(int *n, int *sqre, d *d, d *e, d *u, int *ldu, d *vt, int *ldvt, int *smlsiz, int *iwork, d *work, int *info) noexcept nogil: + + _fortran_dlasd0(n, sqre, d, e, u, ldu, vt, ldvt, smlsiz, iwork, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlasd1 "BLAS_FUNC(dlasd1)"(int *nl, int *nr, int *sqre, d *d, d *alpha, d *beta, d *u, int *ldu, d *vt, int *ldvt, int *idxq, int *iwork, d *work, int *info) nogil +cdef void dlasd1(int *nl, int *nr, int *sqre, d *d, d *alpha, d *beta, d *u, int *ldu, d *vt, int *ldvt, int *idxq, int *iwork, d *work, int *info) noexcept nogil: + + _fortran_dlasd1(nl, nr, sqre, d, alpha, beta, u, ldu, vt, ldvt, idxq, iwork, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlasd2 "BLAS_FUNC(dlasd2)"(int *nl, int *nr, int *sqre, int *k, d *d, d *z, d *alpha, d *beta, d *u, int *ldu, d *vt, int *ldvt, d *dsigma, d *u2, int *ldu2, d *vt2, int *ldvt2, int *idxp, int *idx, int *idxc, int *idxq, int *coltyp, int *info) nogil +cdef void dlasd2(int *nl, int *nr, int *sqre, int *k, d *d, d *z, d *alpha, d *beta, d *u, int *ldu, d *vt, int *ldvt, d *dsigma, d *u2, int *ldu2, d *vt2, int *ldvt2, int *idxp, int *idx, int *idxc, int *idxq, int *coltyp, int *info) noexcept nogil: + + _fortran_dlasd2(nl, nr, sqre, k, d, z, alpha, beta, u, ldu, vt, ldvt, dsigma, u2, ldu2, vt2, ldvt2, idxp, idx, idxc, idxq, coltyp, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlasd3 "BLAS_FUNC(dlasd3)"(int *nl, int *nr, int *sqre, int *k, d *d, d *q, int *ldq, d *dsigma, d *u, int *ldu, d *u2, int *ldu2, d *vt, int *ldvt, d *vt2, int *ldvt2, int *idxc, int *ctot, d *z, int *info) nogil +cdef void dlasd3(int *nl, int *nr, int *sqre, int *k, d *d, d *q, int *ldq, d *dsigma, d *u, int *ldu, d *u2, int *ldu2, d *vt, int *ldvt, d *vt2, int *ldvt2, int *idxc, int *ctot, d *z, int *info) noexcept nogil: + + _fortran_dlasd3(nl, nr, sqre, k, d, q, ldq, dsigma, u, ldu, u2, ldu2, vt, ldvt, vt2, ldvt2, idxc, ctot, z, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlasd4 "BLAS_FUNC(dlasd4)"(int *n, int *i, d *d, d *z, d *delta, d *rho, d *sigma, d *work, int *info) nogil +cdef void dlasd4(int *n, int *i, d *d, d *z, d *delta, d *rho, d *sigma, d *work, int *info) noexcept nogil: + + _fortran_dlasd4(n, i, d, z, delta, rho, sigma, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlasd5 "BLAS_FUNC(dlasd5)"(int *i, d *d, d *z, d *delta, d *rho, d *dsigma, d *work) nogil +cdef void dlasd5(int *i, d *d, d *z, d *delta, d *rho, d *dsigma, d *work) noexcept nogil: + + _fortran_dlasd5(i, d, z, delta, rho, dsigma, work) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlasd6 "BLAS_FUNC(dlasd6)"(int *icompq, int *nl, int *nr, int *sqre, d *d, d *vf, d *vl, d *alpha, d *beta, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, d *givnum, int *ldgnum, d *poles, d *difl, d *difr, d *z, int *k, d *c, d *s, d *work, int *iwork, int *info) nogil +cdef void dlasd6(int *icompq, int *nl, int *nr, int *sqre, d *d, d *vf, d *vl, d *alpha, d *beta, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, d *givnum, int *ldgnum, d *poles, d *difl, d *difr, d *z, int *k, d *c, d *s, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dlasd6(icompq, nl, nr, sqre, d, vf, vl, alpha, beta, idxq, perm, givptr, givcol, ldgcol, givnum, ldgnum, poles, difl, difr, z, k, c, s, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlasd7 "BLAS_FUNC(dlasd7)"(int *icompq, int *nl, int *nr, int *sqre, int *k, d *d, d *z, d *zw, d *vf, d *vfw, d *vl, d *vlw, d *alpha, d *beta, d *dsigma, int *idx, int *idxp, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, d *givnum, int *ldgnum, d *c, d *s, int *info) nogil +cdef void dlasd7(int *icompq, int *nl, int *nr, int *sqre, int *k, d *d, d *z, d *zw, d *vf, d *vfw, d *vl, d *vlw, d *alpha, d *beta, d *dsigma, int *idx, int *idxp, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, d *givnum, int *ldgnum, d *c, d *s, int *info) noexcept nogil: + + _fortran_dlasd7(icompq, nl, nr, sqre, k, d, z, zw, vf, vfw, vl, vlw, alpha, beta, dsigma, idx, idxp, idxq, perm, givptr, givcol, ldgcol, givnum, ldgnum, c, s, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlasd8 "BLAS_FUNC(dlasd8)"(int *icompq, int *k, d *d, d *z, d *vf, d *vl, d *difl, d *difr, int *lddifr, d *dsigma, d *work, int *info) nogil +cdef void dlasd8(int *icompq, int *k, d *d, d *z, d *vf, d *vl, d *difl, d *difr, int *lddifr, d *dsigma, d *work, int *info) noexcept nogil: + + _fortran_dlasd8(icompq, k, d, z, vf, vl, difl, difr, lddifr, dsigma, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlasda "BLAS_FUNC(dlasda)"(int *icompq, int *smlsiz, int *n, int *sqre, d *d, d *e, d *u, int *ldu, d *vt, int *k, d *difl, d *difr, d *z, d *poles, int *givptr, int *givcol, int *ldgcol, int *perm, d *givnum, d *c, d *s, d *work, int *iwork, int *info) nogil +cdef void dlasda(int *icompq, int *smlsiz, int *n, int *sqre, d *d, d *e, d *u, int *ldu, d *vt, int *k, d *difl, d *difr, d *z, d *poles, int *givptr, int *givcol, int *ldgcol, int *perm, d *givnum, d *c, d *s, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dlasda(icompq, smlsiz, n, sqre, d, e, u, ldu, vt, k, difl, difr, z, poles, givptr, givcol, ldgcol, perm, givnum, c, s, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlasdq "BLAS_FUNC(dlasdq)"(char *uplo, int *sqre, int *n, int *ncvt, int *nru, int *ncc, d *d, d *e, d *vt, int *ldvt, d *u, int *ldu, d *c, int *ldc, d *work, int *info) nogil +cdef void dlasdq(char *uplo, int *sqre, int *n, int *ncvt, int *nru, int *ncc, d *d, d *e, d *vt, int *ldvt, d *u, int *ldu, d *c, int *ldc, d *work, int *info) noexcept nogil: + + _fortran_dlasdq(uplo, sqre, n, ncvt, nru, ncc, d, e, vt, ldvt, u, ldu, c, ldc, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlasdt "BLAS_FUNC(dlasdt)"(int *n, int *lvl, int *nd, int *inode, int *ndiml, int *ndimr, int *msub) nogil +cdef void dlasdt(int *n, int *lvl, int *nd, int *inode, int *ndiml, int *ndimr, int *msub) noexcept nogil: + + _fortran_dlasdt(n, lvl, nd, inode, ndiml, ndimr, msub) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlaset "BLAS_FUNC(dlaset)"(char *uplo, int *m, int *n, d *alpha, d *beta, d *a, int *lda) nogil +cdef void dlaset(char *uplo, int *m, int *n, d *alpha, d *beta, d *a, int *lda) noexcept nogil: + + _fortran_dlaset(uplo, m, n, alpha, beta, a, lda) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlasq1 "BLAS_FUNC(dlasq1)"(int *n, d *d, d *e, d *work, int *info) nogil +cdef void dlasq1(int *n, d *d, d *e, d *work, int *info) noexcept nogil: + + _fortran_dlasq1(n, d, e, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlasq2 "BLAS_FUNC(dlasq2)"(int *n, d *z, int *info) nogil +cdef void dlasq2(int *n, d *z, int *info) noexcept nogil: + + _fortran_dlasq2(n, z, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlasq3 "BLAS_FUNC(dlasq3)"(int *i0, int *n0, d *z, int *pp, d *dmin, d *sigma, d *desig, d *qmax, int *nfail, int *iter, int *ndiv, bint *ieee, int *ttype, d *dmin1, d *dmin2, d *dn, d *dn1, d *dn2, d *g, d *tau) nogil +cdef void dlasq3(int *i0, int *n0, d *z, int *pp, d *dmin, d *sigma, d *desig, d *qmax, int *nfail, int *iter, int *ndiv, bint *ieee, int *ttype, d *dmin1, d *dmin2, d *dn, d *dn1, d *dn2, d *g, d *tau) noexcept nogil: + + _fortran_dlasq3(i0, n0, z, pp, dmin, sigma, desig, qmax, nfail, iter, ndiv, ieee, ttype, dmin1, dmin2, dn, dn1, dn2, g, tau) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlasq4 "BLAS_FUNC(dlasq4)"(int *i0, int *n0, d *z, int *pp, int *n0in, d *dmin, d *dmin1, d *dmin2, d *dn, d *dn1, d *dn2, d *tau, int *ttype, d *g) nogil +cdef void dlasq4(int *i0, int *n0, d *z, int *pp, int *n0in, d *dmin, d *dmin1, d *dmin2, d *dn, d *dn1, d *dn2, d *tau, int *ttype, d *g) noexcept nogil: + + _fortran_dlasq4(i0, n0, z, pp, n0in, dmin, dmin1, dmin2, dn, dn1, dn2, tau, ttype, g) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlasq6 "BLAS_FUNC(dlasq6)"(int *i0, int *n0, d *z, int *pp, d *dmin, d *dmin1, d *dmin2, d *dn, d *dnm1, d *dnm2) nogil +cdef void dlasq6(int *i0, int *n0, d *z, int *pp, d *dmin, d *dmin1, d *dmin2, d *dn, d *dnm1, d *dnm2) noexcept nogil: + + _fortran_dlasq6(i0, n0, z, pp, dmin, dmin1, dmin2, dn, dnm1, dnm2) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlasr "BLAS_FUNC(dlasr)"(char *side, char *pivot, char *direct, int *m, int *n, d *c, d *s, d *a, int *lda) nogil +cdef void dlasr(char *side, char *pivot, char *direct, int *m, int *n, d *c, d *s, d *a, int *lda) noexcept nogil: + + _fortran_dlasr(side, pivot, direct, m, n, c, s, a, lda) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlasrt "BLAS_FUNC(dlasrt)"(char *id, int *n, d *d, int *info) nogil +cdef void dlasrt(char *id, int *n, d *d, int *info) noexcept nogil: + + _fortran_dlasrt(id, n, d, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlassq "BLAS_FUNC(dlassq)"(int *n, d *x, int *incx, d *scale, d *sumsq) nogil +cdef void dlassq(int *n, d *x, int *incx, d *scale, d *sumsq) noexcept nogil: + + _fortran_dlassq(n, x, incx, scale, sumsq) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlasv2 "BLAS_FUNC(dlasv2)"(d *f, d *g, d *h, d *ssmin, d *ssmax, d *snr, d *csr, d *snl, d *csl) nogil +cdef void dlasv2(d *f, d *g, d *h, d *ssmin, d *ssmax, d *snr, d *csr, d *snl, d *csl) noexcept nogil: + + _fortran_dlasv2(f, g, h, ssmin, ssmax, snr, csr, snl, csl) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlaswp "BLAS_FUNC(dlaswp)"(int *n, d *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) nogil +cdef void dlaswp(int *n, d *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) noexcept nogil: + + _fortran_dlaswp(n, a, lda, k1, k2, ipiv, incx) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlasy2 "BLAS_FUNC(dlasy2)"(bint *ltranl, bint *ltranr, int *isgn, int *n1, int *n2, d *tl, int *ldtl, d *tr, int *ldtr, d *b, int *ldb, d *scale, d *x, int *ldx, d *xnorm, int *info) nogil +cdef void dlasy2(bint *ltranl, bint *ltranr, int *isgn, int *n1, int *n2, d *tl, int *ldtl, d *tr, int *ldtr, d *b, int *ldb, d *scale, d *x, int *ldx, d *xnorm, int *info) noexcept nogil: + + _fortran_dlasy2(ltranl, ltranr, isgn, n1, n2, tl, ldtl, tr, ldtr, b, ldb, scale, x, ldx, xnorm, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlasyf "BLAS_FUNC(dlasyf)"(char *uplo, int *n, int *nb, int *kb, d *a, int *lda, int *ipiv, d *w, int *ldw, int *info) nogil +cdef void dlasyf(char *uplo, int *n, int *nb, int *kb, d *a, int *lda, int *ipiv, d *w, int *ldw, int *info) noexcept nogil: + + _fortran_dlasyf(uplo, n, nb, kb, a, lda, ipiv, w, ldw, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlat2s "BLAS_FUNC(dlat2s)"(char *uplo, int *n, d *a, int *lda, s *sa, int *ldsa, int *info) nogil +cdef void dlat2s(char *uplo, int *n, d *a, int *lda, s *sa, int *ldsa, int *info) noexcept nogil: + + _fortran_dlat2s(uplo, n, a, lda, sa, ldsa, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlatbs "BLAS_FUNC(dlatbs)"(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, d *ab, int *ldab, d *x, d *scale, d *cnorm, int *info) nogil +cdef void dlatbs(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, d *ab, int *ldab, d *x, d *scale, d *cnorm, int *info) noexcept nogil: + + _fortran_dlatbs(uplo, trans, diag, normin, n, kd, ab, ldab, x, scale, cnorm, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlatdf "BLAS_FUNC(dlatdf)"(int *ijob, int *n, d *z, int *ldz, d *rhs, d *rdsum, d *rdscal, int *ipiv, int *jpiv) nogil +cdef void dlatdf(int *ijob, int *n, d *z, int *ldz, d *rhs, d *rdsum, d *rdscal, int *ipiv, int *jpiv) noexcept nogil: + + _fortran_dlatdf(ijob, n, z, ldz, rhs, rdsum, rdscal, ipiv, jpiv) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlatps "BLAS_FUNC(dlatps)"(char *uplo, char *trans, char *diag, char *normin, int *n, d *ap, d *x, d *scale, d *cnorm, int *info) nogil +cdef void dlatps(char *uplo, char *trans, char *diag, char *normin, int *n, d *ap, d *x, d *scale, d *cnorm, int *info) noexcept nogil: + + _fortran_dlatps(uplo, trans, diag, normin, n, ap, x, scale, cnorm, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlatrd "BLAS_FUNC(dlatrd)"(char *uplo, int *n, int *nb, d *a, int *lda, d *e, d *tau, d *w, int *ldw) nogil +cdef void dlatrd(char *uplo, int *n, int *nb, d *a, int *lda, d *e, d *tau, d *w, int *ldw) noexcept nogil: + + _fortran_dlatrd(uplo, n, nb, a, lda, e, tau, w, ldw) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlatrs "BLAS_FUNC(dlatrs)"(char *uplo, char *trans, char *diag, char *normin, int *n, d *a, int *lda, d *x, d *scale, d *cnorm, int *info) nogil +cdef void dlatrs(char *uplo, char *trans, char *diag, char *normin, int *n, d *a, int *lda, d *x, d *scale, d *cnorm, int *info) noexcept nogil: + + _fortran_dlatrs(uplo, trans, diag, normin, n, a, lda, x, scale, cnorm, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlatrz "BLAS_FUNC(dlatrz)"(int *m, int *n, int *l, d *a, int *lda, d *tau, d *work) nogil +cdef void dlatrz(int *m, int *n, int *l, d *a, int *lda, d *tau, d *work) noexcept nogil: + + _fortran_dlatrz(m, n, l, a, lda, tau, work) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlauu2 "BLAS_FUNC(dlauu2)"(char *uplo, int *n, d *a, int *lda, int *info) nogil +cdef void dlauu2(char *uplo, int *n, d *a, int *lda, int *info) noexcept nogil: + + _fortran_dlauu2(uplo, n, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dlauum "BLAS_FUNC(dlauum)"(char *uplo, int *n, d *a, int *lda, int *info) nogil +cdef void dlauum(char *uplo, int *n, d *a, int *lda, int *info) noexcept nogil: + + _fortran_dlauum(uplo, n, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dopgtr "BLAS_FUNC(dopgtr)"(char *uplo, int *n, d *ap, d *tau, d *q, int *ldq, d *work, int *info) nogil +cdef void dopgtr(char *uplo, int *n, d *ap, d *tau, d *q, int *ldq, d *work, int *info) noexcept nogil: + + _fortran_dopgtr(uplo, n, ap, tau, q, ldq, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dopmtr "BLAS_FUNC(dopmtr)"(char *side, char *uplo, char *trans, int *m, int *n, d *ap, d *tau, d *c, int *ldc, d *work, int *info) nogil +cdef void dopmtr(char *side, char *uplo, char *trans, int *m, int *n, d *ap, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil: + + _fortran_dopmtr(side, uplo, trans, m, n, ap, tau, c, ldc, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dorbdb "BLAS_FUNC(dorbdb)"(char *trans, char *signs, int *m, int *p, int *q, d *x11, int *ldx11, d *x12, int *ldx12, d *x21, int *ldx21, d *x22, int *ldx22, d *theta, d *phi, d *taup1, d *taup2, d *tauq1, d *tauq2, d *work, int *lwork, int *info) nogil +cdef void dorbdb(char *trans, char *signs, int *m, int *p, int *q, d *x11, int *ldx11, d *x12, int *ldx12, d *x21, int *ldx21, d *x22, int *ldx22, d *theta, d *phi, d *taup1, d *taup2, d *tauq1, d *tauq2, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dorbdb(trans, signs, m, p, q, x11, ldx11, x12, ldx12, x21, ldx21, x22, ldx22, theta, phi, taup1, taup2, tauq1, tauq2, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dorcsd "BLAS_FUNC(dorcsd)"(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, d *x11, int *ldx11, d *x12, int *ldx12, d *x21, int *ldx21, d *x22, int *ldx22, d *theta, d *u1, int *ldu1, d *u2, int *ldu2, d *v1t, int *ldv1t, d *v2t, int *ldv2t, d *work, int *lwork, int *iwork, int *info) nogil +cdef void dorcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, d *x11, int *ldx11, d *x12, int *ldx12, d *x21, int *ldx21, d *x22, int *ldx22, d *theta, d *u1, int *ldu1, d *u2, int *ldu2, d *v1t, int *ldv1t, d *v2t, int *ldv2t, d *work, int *lwork, int *iwork, int *info) noexcept nogil: + + _fortran_dorcsd(jobu1, jobu2, jobv1t, jobv2t, trans, signs, m, p, q, x11, ldx11, x12, ldx12, x21, ldx21, x22, ldx22, theta, u1, ldu1, u2, ldu2, v1t, ldv1t, v2t, ldv2t, work, lwork, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dorg2l "BLAS_FUNC(dorg2l)"(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) nogil +cdef void dorg2l(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil: + + _fortran_dorg2l(m, n, k, a, lda, tau, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dorg2r "BLAS_FUNC(dorg2r)"(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) nogil +cdef void dorg2r(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil: + + _fortran_dorg2r(m, n, k, a, lda, tau, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dorgbr "BLAS_FUNC(dorgbr)"(char *vect, int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil +cdef void dorgbr(char *vect, int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dorgbr(vect, m, n, k, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dorghr "BLAS_FUNC(dorghr)"(int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil +cdef void dorghr(int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dorghr(n, ilo, ihi, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dorgl2 "BLAS_FUNC(dorgl2)"(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) nogil +cdef void dorgl2(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil: + + _fortran_dorgl2(m, n, k, a, lda, tau, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dorglq "BLAS_FUNC(dorglq)"(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil +cdef void dorglq(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dorglq(m, n, k, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dorgql "BLAS_FUNC(dorgql)"(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil +cdef void dorgql(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dorgql(m, n, k, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dorgqr "BLAS_FUNC(dorgqr)"(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil +cdef void dorgqr(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dorgqr(m, n, k, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dorgr2 "BLAS_FUNC(dorgr2)"(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) nogil +cdef void dorgr2(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil: + + _fortran_dorgr2(m, n, k, a, lda, tau, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dorgrq "BLAS_FUNC(dorgrq)"(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil +cdef void dorgrq(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dorgrq(m, n, k, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dorgtr "BLAS_FUNC(dorgtr)"(char *uplo, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil +cdef void dorgtr(char *uplo, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dorgtr(uplo, n, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dorm2l "BLAS_FUNC(dorm2l)"(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) nogil +cdef void dorm2l(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil: + + _fortran_dorm2l(side, trans, m, n, k, a, lda, tau, c, ldc, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dorm2r "BLAS_FUNC(dorm2r)"(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) nogil +cdef void dorm2r(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil: + + _fortran_dorm2r(side, trans, m, n, k, a, lda, tau, c, ldc, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dormbr "BLAS_FUNC(dormbr)"(char *vect, char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) nogil +cdef void dormbr(char *vect, char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dormbr(vect, side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dormhr "BLAS_FUNC(dormhr)"(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) nogil +cdef void dormhr(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dormhr(side, trans, m, n, ilo, ihi, a, lda, tau, c, ldc, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dorml2 "BLAS_FUNC(dorml2)"(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) nogil +cdef void dorml2(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil: + + _fortran_dorml2(side, trans, m, n, k, a, lda, tau, c, ldc, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dormlq "BLAS_FUNC(dormlq)"(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) nogil +cdef void dormlq(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dormlq(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dormql "BLAS_FUNC(dormql)"(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) nogil +cdef void dormql(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dormql(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dormqr "BLAS_FUNC(dormqr)"(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) nogil +cdef void dormqr(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dormqr(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dormr2 "BLAS_FUNC(dormr2)"(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) nogil +cdef void dormr2(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil: + + _fortran_dormr2(side, trans, m, n, k, a, lda, tau, c, ldc, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dormr3 "BLAS_FUNC(dormr3)"(char *side, char *trans, int *m, int *n, int *k, int *l, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) nogil +cdef void dormr3(char *side, char *trans, int *m, int *n, int *k, int *l, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil: + + _fortran_dormr3(side, trans, m, n, k, l, a, lda, tau, c, ldc, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dormrq "BLAS_FUNC(dormrq)"(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) nogil +cdef void dormrq(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dormrq(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dormrz "BLAS_FUNC(dormrz)"(char *side, char *trans, int *m, int *n, int *k, int *l, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) nogil +cdef void dormrz(char *side, char *trans, int *m, int *n, int *k, int *l, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dormrz(side, trans, m, n, k, l, a, lda, tau, c, ldc, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dormtr "BLAS_FUNC(dormtr)"(char *side, char *uplo, char *trans, int *m, int *n, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) nogil +cdef void dormtr(char *side, char *uplo, char *trans, int *m, int *n, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dormtr(side, uplo, trans, m, n, a, lda, tau, c, ldc, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dpbcon "BLAS_FUNC(dpbcon)"(char *uplo, int *n, int *kd, d *ab, int *ldab, d *anorm, d *rcond, d *work, int *iwork, int *info) nogil +cdef void dpbcon(char *uplo, int *n, int *kd, d *ab, int *ldab, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dpbcon(uplo, n, kd, ab, ldab, anorm, rcond, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dpbequ "BLAS_FUNC(dpbequ)"(char *uplo, int *n, int *kd, d *ab, int *ldab, d *s, d *scond, d *amax, int *info) nogil +cdef void dpbequ(char *uplo, int *n, int *kd, d *ab, int *ldab, d *s, d *scond, d *amax, int *info) noexcept nogil: + + _fortran_dpbequ(uplo, n, kd, ab, ldab, s, scond, amax, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dpbrfs "BLAS_FUNC(dpbrfs)"(char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *afb, int *ldafb, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) nogil +cdef void dpbrfs(char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *afb, int *ldafb, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dpbrfs(uplo, n, kd, nrhs, ab, ldab, afb, ldafb, b, ldb, x, ldx, ferr, berr, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dpbstf "BLAS_FUNC(dpbstf)"(char *uplo, int *n, int *kd, d *ab, int *ldab, int *info) nogil +cdef void dpbstf(char *uplo, int *n, int *kd, d *ab, int *ldab, int *info) noexcept nogil: + + _fortran_dpbstf(uplo, n, kd, ab, ldab, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dpbsv "BLAS_FUNC(dpbsv)"(char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, int *info) nogil +cdef void dpbsv(char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, int *info) noexcept nogil: + + _fortran_dpbsv(uplo, n, kd, nrhs, ab, ldab, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dpbsvx "BLAS_FUNC(dpbsvx)"(char *fact, char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *afb, int *ldafb, char *equed, d *s, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) nogil +cdef void dpbsvx(char *fact, char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *afb, int *ldafb, char *equed, d *s, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dpbsvx(fact, uplo, n, kd, nrhs, ab, ldab, afb, ldafb, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dpbtf2 "BLAS_FUNC(dpbtf2)"(char *uplo, int *n, int *kd, d *ab, int *ldab, int *info) nogil +cdef void dpbtf2(char *uplo, int *n, int *kd, d *ab, int *ldab, int *info) noexcept nogil: + + _fortran_dpbtf2(uplo, n, kd, ab, ldab, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dpbtrf "BLAS_FUNC(dpbtrf)"(char *uplo, int *n, int *kd, d *ab, int *ldab, int *info) nogil +cdef void dpbtrf(char *uplo, int *n, int *kd, d *ab, int *ldab, int *info) noexcept nogil: + + _fortran_dpbtrf(uplo, n, kd, ab, ldab, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dpbtrs "BLAS_FUNC(dpbtrs)"(char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, int *info) nogil +cdef void dpbtrs(char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, int *info) noexcept nogil: + + _fortran_dpbtrs(uplo, n, kd, nrhs, ab, ldab, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dpftrf "BLAS_FUNC(dpftrf)"(char *transr, char *uplo, int *n, d *a, int *info) nogil +cdef void dpftrf(char *transr, char *uplo, int *n, d *a, int *info) noexcept nogil: + + _fortran_dpftrf(transr, uplo, n, a, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dpftri "BLAS_FUNC(dpftri)"(char *transr, char *uplo, int *n, d *a, int *info) nogil +cdef void dpftri(char *transr, char *uplo, int *n, d *a, int *info) noexcept nogil: + + _fortran_dpftri(transr, uplo, n, a, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dpftrs "BLAS_FUNC(dpftrs)"(char *transr, char *uplo, int *n, int *nrhs, d *a, d *b, int *ldb, int *info) nogil +cdef void dpftrs(char *transr, char *uplo, int *n, int *nrhs, d *a, d *b, int *ldb, int *info) noexcept nogil: + + _fortran_dpftrs(transr, uplo, n, nrhs, a, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dpocon "BLAS_FUNC(dpocon)"(char *uplo, int *n, d *a, int *lda, d *anorm, d *rcond, d *work, int *iwork, int *info) nogil +cdef void dpocon(char *uplo, int *n, d *a, int *lda, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dpocon(uplo, n, a, lda, anorm, rcond, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dpoequ "BLAS_FUNC(dpoequ)"(int *n, d *a, int *lda, d *s, d *scond, d *amax, int *info) nogil +cdef void dpoequ(int *n, d *a, int *lda, d *s, d *scond, d *amax, int *info) noexcept nogil: + + _fortran_dpoequ(n, a, lda, s, scond, amax, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dpoequb "BLAS_FUNC(dpoequb)"(int *n, d *a, int *lda, d *s, d *scond, d *amax, int *info) nogil +cdef void dpoequb(int *n, d *a, int *lda, d *s, d *scond, d *amax, int *info) noexcept nogil: + + _fortran_dpoequb(n, a, lda, s, scond, amax, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dporfs "BLAS_FUNC(dporfs)"(char *uplo, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) nogil +cdef void dporfs(char *uplo, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dporfs(uplo, n, nrhs, a, lda, af, ldaf, b, ldb, x, ldx, ferr, berr, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dposv "BLAS_FUNC(dposv)"(char *uplo, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *info) nogil +cdef void dposv(char *uplo, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *info) noexcept nogil: + + _fortran_dposv(uplo, n, nrhs, a, lda, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dposvx "BLAS_FUNC(dposvx)"(char *fact, char *uplo, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, char *equed, d *s, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) nogil +cdef void dposvx(char *fact, char *uplo, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, char *equed, d *s, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dposvx(fact, uplo, n, nrhs, a, lda, af, ldaf, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dpotf2 "BLAS_FUNC(dpotf2)"(char *uplo, int *n, d *a, int *lda, int *info) nogil +cdef void dpotf2(char *uplo, int *n, d *a, int *lda, int *info) noexcept nogil: + + _fortran_dpotf2(uplo, n, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dpotrf "BLAS_FUNC(dpotrf)"(char *uplo, int *n, d *a, int *lda, int *info) nogil +cdef void dpotrf(char *uplo, int *n, d *a, int *lda, int *info) noexcept nogil: + + _fortran_dpotrf(uplo, n, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dpotri "BLAS_FUNC(dpotri)"(char *uplo, int *n, d *a, int *lda, int *info) nogil +cdef void dpotri(char *uplo, int *n, d *a, int *lda, int *info) noexcept nogil: + + _fortran_dpotri(uplo, n, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dpotrs "BLAS_FUNC(dpotrs)"(char *uplo, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *info) nogil +cdef void dpotrs(char *uplo, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *info) noexcept nogil: + + _fortran_dpotrs(uplo, n, nrhs, a, lda, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dppcon "BLAS_FUNC(dppcon)"(char *uplo, int *n, d *ap, d *anorm, d *rcond, d *work, int *iwork, int *info) nogil +cdef void dppcon(char *uplo, int *n, d *ap, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dppcon(uplo, n, ap, anorm, rcond, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dppequ "BLAS_FUNC(dppequ)"(char *uplo, int *n, d *ap, d *s, d *scond, d *amax, int *info) nogil +cdef void dppequ(char *uplo, int *n, d *ap, d *s, d *scond, d *amax, int *info) noexcept nogil: + + _fortran_dppequ(uplo, n, ap, s, scond, amax, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dpprfs "BLAS_FUNC(dpprfs)"(char *uplo, int *n, int *nrhs, d *ap, d *afp, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) nogil +cdef void dpprfs(char *uplo, int *n, int *nrhs, d *ap, d *afp, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dpprfs(uplo, n, nrhs, ap, afp, b, ldb, x, ldx, ferr, berr, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dppsv "BLAS_FUNC(dppsv)"(char *uplo, int *n, int *nrhs, d *ap, d *b, int *ldb, int *info) nogil +cdef void dppsv(char *uplo, int *n, int *nrhs, d *ap, d *b, int *ldb, int *info) noexcept nogil: + + _fortran_dppsv(uplo, n, nrhs, ap, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dppsvx "BLAS_FUNC(dppsvx)"(char *fact, char *uplo, int *n, int *nrhs, d *ap, d *afp, char *equed, d *s, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) nogil +cdef void dppsvx(char *fact, char *uplo, int *n, int *nrhs, d *ap, d *afp, char *equed, d *s, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dppsvx(fact, uplo, n, nrhs, ap, afp, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dpptrf "BLAS_FUNC(dpptrf)"(char *uplo, int *n, d *ap, int *info) nogil +cdef void dpptrf(char *uplo, int *n, d *ap, int *info) noexcept nogil: + + _fortran_dpptrf(uplo, n, ap, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dpptri "BLAS_FUNC(dpptri)"(char *uplo, int *n, d *ap, int *info) nogil +cdef void dpptri(char *uplo, int *n, d *ap, int *info) noexcept nogil: + + _fortran_dpptri(uplo, n, ap, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dpptrs "BLAS_FUNC(dpptrs)"(char *uplo, int *n, int *nrhs, d *ap, d *b, int *ldb, int *info) nogil +cdef void dpptrs(char *uplo, int *n, int *nrhs, d *ap, d *b, int *ldb, int *info) noexcept nogil: + + _fortran_dpptrs(uplo, n, nrhs, ap, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dpstf2 "BLAS_FUNC(dpstf2)"(char *uplo, int *n, d *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) nogil +cdef void dpstf2(char *uplo, int *n, d *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) noexcept nogil: + + _fortran_dpstf2(uplo, n, a, lda, piv, rank, tol, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dpstrf "BLAS_FUNC(dpstrf)"(char *uplo, int *n, d *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) nogil +cdef void dpstrf(char *uplo, int *n, d *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) noexcept nogil: + + _fortran_dpstrf(uplo, n, a, lda, piv, rank, tol, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dptcon "BLAS_FUNC(dptcon)"(int *n, d *d, d *e, d *anorm, d *rcond, d *work, int *info) nogil +cdef void dptcon(int *n, d *d, d *e, d *anorm, d *rcond, d *work, int *info) noexcept nogil: + + _fortran_dptcon(n, d, e, anorm, rcond, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dpteqr "BLAS_FUNC(dpteqr)"(char *compz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *info) nogil +cdef void dpteqr(char *compz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *info) noexcept nogil: + + _fortran_dpteqr(compz, n, d, e, z, ldz, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dptrfs "BLAS_FUNC(dptrfs)"(int *n, int *nrhs, d *d, d *e, d *df, d *ef, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *info) nogil +cdef void dptrfs(int *n, int *nrhs, d *d, d *e, d *df, d *ef, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *info) noexcept nogil: + + _fortran_dptrfs(n, nrhs, d, e, df, ef, b, ldb, x, ldx, ferr, berr, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dptsv "BLAS_FUNC(dptsv)"(int *n, int *nrhs, d *d, d *e, d *b, int *ldb, int *info) nogil +cdef void dptsv(int *n, int *nrhs, d *d, d *e, d *b, int *ldb, int *info) noexcept nogil: + + _fortran_dptsv(n, nrhs, d, e, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dptsvx "BLAS_FUNC(dptsvx)"(char *fact, int *n, int *nrhs, d *d, d *e, d *df, d *ef, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *info) nogil +cdef void dptsvx(char *fact, int *n, int *nrhs, d *d, d *e, d *df, d *ef, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *info) noexcept nogil: + + _fortran_dptsvx(fact, n, nrhs, d, e, df, ef, b, ldb, x, ldx, rcond, ferr, berr, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dpttrf "BLAS_FUNC(dpttrf)"(int *n, d *d, d *e, int *info) nogil +cdef void dpttrf(int *n, d *d, d *e, int *info) noexcept nogil: + + _fortran_dpttrf(n, d, e, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dpttrs "BLAS_FUNC(dpttrs)"(int *n, int *nrhs, d *d, d *e, d *b, int *ldb, int *info) nogil +cdef void dpttrs(int *n, int *nrhs, d *d, d *e, d *b, int *ldb, int *info) noexcept nogil: + + _fortran_dpttrs(n, nrhs, d, e, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dptts2 "BLAS_FUNC(dptts2)"(int *n, int *nrhs, d *d, d *e, d *b, int *ldb) nogil +cdef void dptts2(int *n, int *nrhs, d *d, d *e, d *b, int *ldb) noexcept nogil: + + _fortran_dptts2(n, nrhs, d, e, b, ldb) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_drscl "BLAS_FUNC(drscl)"(int *n, d *sa, d *sx, int *incx) nogil +cdef void drscl(int *n, d *sa, d *sx, int *incx) noexcept nogil: + + _fortran_drscl(n, sa, sx, incx) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsbev "BLAS_FUNC(dsbev)"(char *jobz, char *uplo, int *n, int *kd, d *ab, int *ldab, d *w, d *z, int *ldz, d *work, int *info) nogil +cdef void dsbev(char *jobz, char *uplo, int *n, int *kd, d *ab, int *ldab, d *w, d *z, int *ldz, d *work, int *info) noexcept nogil: + + _fortran_dsbev(jobz, uplo, n, kd, ab, ldab, w, z, ldz, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsbevd "BLAS_FUNC(dsbevd)"(char *jobz, char *uplo, int *n, int *kd, d *ab, int *ldab, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil +cdef void dsbevd(char *jobz, char *uplo, int *n, int *kd, d *ab, int *ldab, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_dsbevd(jobz, uplo, n, kd, ab, ldab, w, z, ldz, work, lwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsbevx "BLAS_FUNC(dsbevx)"(char *jobz, char *range, char *uplo, int *n, int *kd, d *ab, int *ldab, d *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) nogil +cdef void dsbevx(char *jobz, char *range, char *uplo, int *n, int *kd, d *ab, int *ldab, d *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil: + + _fortran_dsbevx(jobz, range, uplo, n, kd, ab, ldab, q, ldq, vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, ifail, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsbgst "BLAS_FUNC(dsbgst)"(char *vect, char *uplo, int *n, int *ka, int *kb, d *ab, int *ldab, d *bb, int *ldbb, d *x, int *ldx, d *work, int *info) nogil +cdef void dsbgst(char *vect, char *uplo, int *n, int *ka, int *kb, d *ab, int *ldab, d *bb, int *ldbb, d *x, int *ldx, d *work, int *info) noexcept nogil: + + _fortran_dsbgst(vect, uplo, n, ka, kb, ab, ldab, bb, ldbb, x, ldx, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsbgv "BLAS_FUNC(dsbgv)"(char *jobz, char *uplo, int *n, int *ka, int *kb, d *ab, int *ldab, d *bb, int *ldbb, d *w, d *z, int *ldz, d *work, int *info) nogil +cdef void dsbgv(char *jobz, char *uplo, int *n, int *ka, int *kb, d *ab, int *ldab, d *bb, int *ldbb, d *w, d *z, int *ldz, d *work, int *info) noexcept nogil: + + _fortran_dsbgv(jobz, uplo, n, ka, kb, ab, ldab, bb, ldbb, w, z, ldz, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsbgvd "BLAS_FUNC(dsbgvd)"(char *jobz, char *uplo, int *n, int *ka, int *kb, d *ab, int *ldab, d *bb, int *ldbb, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil +cdef void dsbgvd(char *jobz, char *uplo, int *n, int *ka, int *kb, d *ab, int *ldab, d *bb, int *ldbb, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_dsbgvd(jobz, uplo, n, ka, kb, ab, ldab, bb, ldbb, w, z, ldz, work, lwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsbgvx "BLAS_FUNC(dsbgvx)"(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, d *ab, int *ldab, d *bb, int *ldbb, d *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) nogil +cdef void dsbgvx(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, d *ab, int *ldab, d *bb, int *ldbb, d *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil: + + _fortran_dsbgvx(jobz, range, uplo, n, ka, kb, ab, ldab, bb, ldbb, q, ldq, vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, ifail, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsbtrd "BLAS_FUNC(dsbtrd)"(char *vect, char *uplo, int *n, int *kd, d *ab, int *ldab, d *d, d *e, d *q, int *ldq, d *work, int *info) nogil +cdef void dsbtrd(char *vect, char *uplo, int *n, int *kd, d *ab, int *ldab, d *d, d *e, d *q, int *ldq, d *work, int *info) noexcept nogil: + + _fortran_dsbtrd(vect, uplo, n, kd, ab, ldab, d, e, q, ldq, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsfrk "BLAS_FUNC(dsfrk)"(char *transr, char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *beta, d *c) nogil +cdef void dsfrk(char *transr, char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *beta, d *c) noexcept nogil: + + _fortran_dsfrk(transr, uplo, trans, n, k, alpha, a, lda, beta, c) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsgesv "BLAS_FUNC(dsgesv)"(int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *work, s *swork, int *iter, int *info) nogil +cdef void dsgesv(int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *work, s *swork, int *iter, int *info) noexcept nogil: + + _fortran_dsgesv(n, nrhs, a, lda, ipiv, b, ldb, x, ldx, work, swork, iter, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dspcon "BLAS_FUNC(dspcon)"(char *uplo, int *n, d *ap, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) nogil +cdef void dspcon(char *uplo, int *n, d *ap, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dspcon(uplo, n, ap, ipiv, anorm, rcond, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dspev "BLAS_FUNC(dspev)"(char *jobz, char *uplo, int *n, d *ap, d *w, d *z, int *ldz, d *work, int *info) nogil +cdef void dspev(char *jobz, char *uplo, int *n, d *ap, d *w, d *z, int *ldz, d *work, int *info) noexcept nogil: + + _fortran_dspev(jobz, uplo, n, ap, w, z, ldz, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dspevd "BLAS_FUNC(dspevd)"(char *jobz, char *uplo, int *n, d *ap, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil +cdef void dspevd(char *jobz, char *uplo, int *n, d *ap, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_dspevd(jobz, uplo, n, ap, w, z, ldz, work, lwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dspevx "BLAS_FUNC(dspevx)"(char *jobz, char *range, char *uplo, int *n, d *ap, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) nogil +cdef void dspevx(char *jobz, char *range, char *uplo, int *n, d *ap, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil: + + _fortran_dspevx(jobz, range, uplo, n, ap, vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, ifail, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dspgst "BLAS_FUNC(dspgst)"(int *itype, char *uplo, int *n, d *ap, d *bp, int *info) nogil +cdef void dspgst(int *itype, char *uplo, int *n, d *ap, d *bp, int *info) noexcept nogil: + + _fortran_dspgst(itype, uplo, n, ap, bp, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dspgv "BLAS_FUNC(dspgv)"(int *itype, char *jobz, char *uplo, int *n, d *ap, d *bp, d *w, d *z, int *ldz, d *work, int *info) nogil +cdef void dspgv(int *itype, char *jobz, char *uplo, int *n, d *ap, d *bp, d *w, d *z, int *ldz, d *work, int *info) noexcept nogil: + + _fortran_dspgv(itype, jobz, uplo, n, ap, bp, w, z, ldz, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dspgvd "BLAS_FUNC(dspgvd)"(int *itype, char *jobz, char *uplo, int *n, d *ap, d *bp, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil +cdef void dspgvd(int *itype, char *jobz, char *uplo, int *n, d *ap, d *bp, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_dspgvd(itype, jobz, uplo, n, ap, bp, w, z, ldz, work, lwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dspgvx "BLAS_FUNC(dspgvx)"(int *itype, char *jobz, char *range, char *uplo, int *n, d *ap, d *bp, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) nogil +cdef void dspgvx(int *itype, char *jobz, char *range, char *uplo, int *n, d *ap, d *bp, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil: + + _fortran_dspgvx(itype, jobz, range, uplo, n, ap, bp, vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, ifail, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsposv "BLAS_FUNC(dsposv)"(char *uplo, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *x, int *ldx, d *work, s *swork, int *iter, int *info) nogil +cdef void dsposv(char *uplo, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *x, int *ldx, d *work, s *swork, int *iter, int *info) noexcept nogil: + + _fortran_dsposv(uplo, n, nrhs, a, lda, b, ldb, x, ldx, work, swork, iter, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsprfs "BLAS_FUNC(dsprfs)"(char *uplo, int *n, int *nrhs, d *ap, d *afp, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) nogil +cdef void dsprfs(char *uplo, int *n, int *nrhs, d *ap, d *afp, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dsprfs(uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, ferr, berr, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dspsv "BLAS_FUNC(dspsv)"(char *uplo, int *n, int *nrhs, d *ap, int *ipiv, d *b, int *ldb, int *info) nogil +cdef void dspsv(char *uplo, int *n, int *nrhs, d *ap, int *ipiv, d *b, int *ldb, int *info) noexcept nogil: + + _fortran_dspsv(uplo, n, nrhs, ap, ipiv, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dspsvx "BLAS_FUNC(dspsvx)"(char *fact, char *uplo, int *n, int *nrhs, d *ap, d *afp, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) nogil +cdef void dspsvx(char *fact, char *uplo, int *n, int *nrhs, d *ap, d *afp, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dspsvx(fact, uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsptrd "BLAS_FUNC(dsptrd)"(char *uplo, int *n, d *ap, d *d, d *e, d *tau, int *info) nogil +cdef void dsptrd(char *uplo, int *n, d *ap, d *d, d *e, d *tau, int *info) noexcept nogil: + + _fortran_dsptrd(uplo, n, ap, d, e, tau, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsptrf "BLAS_FUNC(dsptrf)"(char *uplo, int *n, d *ap, int *ipiv, int *info) nogil +cdef void dsptrf(char *uplo, int *n, d *ap, int *ipiv, int *info) noexcept nogil: + + _fortran_dsptrf(uplo, n, ap, ipiv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsptri "BLAS_FUNC(dsptri)"(char *uplo, int *n, d *ap, int *ipiv, d *work, int *info) nogil +cdef void dsptri(char *uplo, int *n, d *ap, int *ipiv, d *work, int *info) noexcept nogil: + + _fortran_dsptri(uplo, n, ap, ipiv, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsptrs "BLAS_FUNC(dsptrs)"(char *uplo, int *n, int *nrhs, d *ap, int *ipiv, d *b, int *ldb, int *info) nogil +cdef void dsptrs(char *uplo, int *n, int *nrhs, d *ap, int *ipiv, d *b, int *ldb, int *info) noexcept nogil: + + _fortran_dsptrs(uplo, n, nrhs, ap, ipiv, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dstebz "BLAS_FUNC(dstebz)"(char *range, char *order, int *n, d *vl, d *vu, int *il, int *iu, d *abstol, d *d, d *e, int *m, int *nsplit, d *w, int *iblock, int *isplit, d *work, int *iwork, int *info) nogil +cdef void dstebz(char *range, char *order, int *n, d *vl, d *vu, int *il, int *iu, d *abstol, d *d, d *e, int *m, int *nsplit, d *w, int *iblock, int *isplit, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dstebz(range, order, n, vl, vu, il, iu, abstol, d, e, m, nsplit, w, iblock, isplit, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dstedc "BLAS_FUNC(dstedc)"(char *compz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil +cdef void dstedc(char *compz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_dstedc(compz, n, d, e, z, ldz, work, lwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dstegr "BLAS_FUNC(dstegr)"(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, int *isuppz, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil +cdef void dstegr(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, int *isuppz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_dstegr(jobz, range, n, d, e, vl, vu, il, iu, abstol, m, w, z, ldz, isuppz, work, lwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dstein "BLAS_FUNC(dstein)"(int *n, d *d, d *e, int *m, d *w, int *iblock, int *isplit, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) nogil +cdef void dstein(int *n, d *d, d *e, int *m, d *w, int *iblock, int *isplit, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil: + + _fortran_dstein(n, d, e, m, w, iblock, isplit, z, ldz, work, iwork, ifail, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dstemr "BLAS_FUNC(dstemr)"(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, int *m, d *w, d *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil +cdef void dstemr(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, int *m, d *w, d *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_dstemr(jobz, range, n, d, e, vl, vu, il, iu, m, w, z, ldz, nzc, isuppz, tryrac, work, lwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsteqr "BLAS_FUNC(dsteqr)"(char *compz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *info) nogil +cdef void dsteqr(char *compz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *info) noexcept nogil: + + _fortran_dsteqr(compz, n, d, e, z, ldz, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsterf "BLAS_FUNC(dsterf)"(int *n, d *d, d *e, int *info) nogil +cdef void dsterf(int *n, d *d, d *e, int *info) noexcept nogil: + + _fortran_dsterf(n, d, e, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dstev "BLAS_FUNC(dstev)"(char *jobz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *info) nogil +cdef void dstev(char *jobz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *info) noexcept nogil: + + _fortran_dstev(jobz, n, d, e, z, ldz, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dstevd "BLAS_FUNC(dstevd)"(char *jobz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil +cdef void dstevd(char *jobz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_dstevd(jobz, n, d, e, z, ldz, work, lwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dstevr "BLAS_FUNC(dstevr)"(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, int *isuppz, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil +cdef void dstevr(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, int *isuppz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_dstevr(jobz, range, n, d, e, vl, vu, il, iu, abstol, m, w, z, ldz, isuppz, work, lwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dstevx "BLAS_FUNC(dstevx)"(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) nogil +cdef void dstevx(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil: + + _fortran_dstevx(jobz, range, n, d, e, vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, ifail, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsycon "BLAS_FUNC(dsycon)"(char *uplo, int *n, d *a, int *lda, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) nogil +cdef void dsycon(char *uplo, int *n, d *a, int *lda, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dsycon(uplo, n, a, lda, ipiv, anorm, rcond, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsyconv "BLAS_FUNC(dsyconv)"(char *uplo, char *way, int *n, d *a, int *lda, int *ipiv, d *work, int *info) nogil +cdef void dsyconv(char *uplo, char *way, int *n, d *a, int *lda, int *ipiv, d *work, int *info) noexcept nogil: + + _fortran_dsyconv(uplo, way, n, a, lda, ipiv, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsyequb "BLAS_FUNC(dsyequb)"(char *uplo, int *n, d *a, int *lda, d *s, d *scond, d *amax, d *work, int *info) nogil +cdef void dsyequb(char *uplo, int *n, d *a, int *lda, d *s, d *scond, d *amax, d *work, int *info) noexcept nogil: + + _fortran_dsyequb(uplo, n, a, lda, s, scond, amax, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsyev "BLAS_FUNC(dsyev)"(char *jobz, char *uplo, int *n, d *a, int *lda, d *w, d *work, int *lwork, int *info) nogil +cdef void dsyev(char *jobz, char *uplo, int *n, d *a, int *lda, d *w, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dsyev(jobz, uplo, n, a, lda, w, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsyevd "BLAS_FUNC(dsyevd)"(char *jobz, char *uplo, int *n, d *a, int *lda, d *w, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil +cdef void dsyevd(char *jobz, char *uplo, int *n, d *a, int *lda, d *w, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_dsyevd(jobz, uplo, n, a, lda, w, work, lwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsyevr "BLAS_FUNC(dsyevr)"(char *jobz, char *range, char *uplo, int *n, d *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, int *isuppz, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil +cdef void dsyevr(char *jobz, char *range, char *uplo, int *n, d *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, int *isuppz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_dsyevr(jobz, range, uplo, n, a, lda, vl, vu, il, iu, abstol, m, w, z, ldz, isuppz, work, lwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsyevx "BLAS_FUNC(dsyevx)"(char *jobz, char *range, char *uplo, int *n, d *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *ifail, int *info) nogil +cdef void dsyevx(char *jobz, char *range, char *uplo, int *n, d *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *ifail, int *info) noexcept nogil: + + _fortran_dsyevx(jobz, range, uplo, n, a, lda, vl, vu, il, iu, abstol, m, w, z, ldz, work, lwork, iwork, ifail, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsygs2 "BLAS_FUNC(dsygs2)"(int *itype, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, int *info) nogil +cdef void dsygs2(int *itype, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, int *info) noexcept nogil: + + _fortran_dsygs2(itype, uplo, n, a, lda, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsygst "BLAS_FUNC(dsygst)"(int *itype, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, int *info) nogil +cdef void dsygst(int *itype, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, int *info) noexcept nogil: + + _fortran_dsygst(itype, uplo, n, a, lda, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsygv "BLAS_FUNC(dsygv)"(int *itype, char *jobz, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, d *w, d *work, int *lwork, int *info) nogil +cdef void dsygv(int *itype, char *jobz, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, d *w, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dsygv(itype, jobz, uplo, n, a, lda, b, ldb, w, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsygvd "BLAS_FUNC(dsygvd)"(int *itype, char *jobz, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, d *w, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil +cdef void dsygvd(int *itype, char *jobz, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, d *w, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_dsygvd(itype, jobz, uplo, n, a, lda, b, ldb, w, work, lwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsygvx "BLAS_FUNC(dsygvx)"(int *itype, char *jobz, char *range, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *ifail, int *info) nogil +cdef void dsygvx(int *itype, char *jobz, char *range, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *ifail, int *info) noexcept nogil: + + _fortran_dsygvx(itype, jobz, range, uplo, n, a, lda, b, ldb, vl, vu, il, iu, abstol, m, w, z, ldz, work, lwork, iwork, ifail, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsyrfs "BLAS_FUNC(dsyrfs)"(char *uplo, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) nogil +cdef void dsyrfs(char *uplo, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dsyrfs(uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, ferr, berr, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsysv "BLAS_FUNC(dsysv)"(char *uplo, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, d *work, int *lwork, int *info) nogil +cdef void dsysv(char *uplo, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dsysv(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsysvx "BLAS_FUNC(dsysvx)"(char *fact, char *uplo, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *lwork, int *iwork, int *info) nogil +cdef void dsysvx(char *fact, char *uplo, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *lwork, int *iwork, int *info) noexcept nogil: + + _fortran_dsysvx(fact, uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, lwork, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsyswapr "BLAS_FUNC(dsyswapr)"(char *uplo, int *n, d *a, int *lda, int *i1, int *i2) nogil +cdef void dsyswapr(char *uplo, int *n, d *a, int *lda, int *i1, int *i2) noexcept nogil: + + _fortran_dsyswapr(uplo, n, a, lda, i1, i2) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsytd2 "BLAS_FUNC(dsytd2)"(char *uplo, int *n, d *a, int *lda, d *d, d *e, d *tau, int *info) nogil +cdef void dsytd2(char *uplo, int *n, d *a, int *lda, d *d, d *e, d *tau, int *info) noexcept nogil: + + _fortran_dsytd2(uplo, n, a, lda, d, e, tau, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsytf2 "BLAS_FUNC(dsytf2)"(char *uplo, int *n, d *a, int *lda, int *ipiv, int *info) nogil +cdef void dsytf2(char *uplo, int *n, d *a, int *lda, int *ipiv, int *info) noexcept nogil: + + _fortran_dsytf2(uplo, n, a, lda, ipiv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsytrd "BLAS_FUNC(dsytrd)"(char *uplo, int *n, d *a, int *lda, d *d, d *e, d *tau, d *work, int *lwork, int *info) nogil +cdef void dsytrd(char *uplo, int *n, d *a, int *lda, d *d, d *e, d *tau, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dsytrd(uplo, n, a, lda, d, e, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsytrf "BLAS_FUNC(dsytrf)"(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *lwork, int *info) nogil +cdef void dsytrf(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dsytrf(uplo, n, a, lda, ipiv, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsytri "BLAS_FUNC(dsytri)"(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *info) nogil +cdef void dsytri(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *info) noexcept nogil: + + _fortran_dsytri(uplo, n, a, lda, ipiv, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsytri2 "BLAS_FUNC(dsytri2)"(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *lwork, int *info) nogil +cdef void dsytri2(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dsytri2(uplo, n, a, lda, ipiv, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsytri2x "BLAS_FUNC(dsytri2x)"(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *nb, int *info) nogil +cdef void dsytri2x(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *nb, int *info) noexcept nogil: + + _fortran_dsytri2x(uplo, n, a, lda, ipiv, work, nb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsytrs "BLAS_FUNC(dsytrs)"(char *uplo, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, int *info) nogil +cdef void dsytrs(char *uplo, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, int *info) noexcept nogil: + + _fortran_dsytrs(uplo, n, nrhs, a, lda, ipiv, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dsytrs2 "BLAS_FUNC(dsytrs2)"(char *uplo, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, d *work, int *info) nogil +cdef void dsytrs2(char *uplo, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, d *work, int *info) noexcept nogil: + + _fortran_dsytrs2(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dtbcon "BLAS_FUNC(dtbcon)"(char *norm, char *uplo, char *diag, int *n, int *kd, d *ab, int *ldab, d *rcond, d *work, int *iwork, int *info) nogil +cdef void dtbcon(char *norm, char *uplo, char *diag, int *n, int *kd, d *ab, int *ldab, d *rcond, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dtbcon(norm, uplo, diag, n, kd, ab, ldab, rcond, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dtbrfs "BLAS_FUNC(dtbrfs)"(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) nogil +cdef void dtbrfs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dtbrfs(uplo, trans, diag, n, kd, nrhs, ab, ldab, b, ldb, x, ldx, ferr, berr, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dtbtrs "BLAS_FUNC(dtbtrs)"(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, int *info) nogil +cdef void dtbtrs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, int *info) noexcept nogil: + + _fortran_dtbtrs(uplo, trans, diag, n, kd, nrhs, ab, ldab, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dtfsm "BLAS_FUNC(dtfsm)"(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, d *alpha, d *a, d *b, int *ldb) nogil +cdef void dtfsm(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, d *alpha, d *a, d *b, int *ldb) noexcept nogil: + + _fortran_dtfsm(transr, side, uplo, trans, diag, m, n, alpha, a, b, ldb) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dtftri "BLAS_FUNC(dtftri)"(char *transr, char *uplo, char *diag, int *n, d *a, int *info) nogil +cdef void dtftri(char *transr, char *uplo, char *diag, int *n, d *a, int *info) noexcept nogil: + + _fortran_dtftri(transr, uplo, diag, n, a, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dtfttp "BLAS_FUNC(dtfttp)"(char *transr, char *uplo, int *n, d *arf, d *ap, int *info) nogil +cdef void dtfttp(char *transr, char *uplo, int *n, d *arf, d *ap, int *info) noexcept nogil: + + _fortran_dtfttp(transr, uplo, n, arf, ap, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dtfttr "BLAS_FUNC(dtfttr)"(char *transr, char *uplo, int *n, d *arf, d *a, int *lda, int *info) nogil +cdef void dtfttr(char *transr, char *uplo, int *n, d *arf, d *a, int *lda, int *info) noexcept nogil: + + _fortran_dtfttr(transr, uplo, n, arf, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dtgevc "BLAS_FUNC(dtgevc)"(char *side, char *howmny, bint *select, int *n, d *s, int *lds, d *p, int *ldp, d *vl, int *ldvl, d *vr, int *ldvr, int *mm, int *m, d *work, int *info) nogil +cdef void dtgevc(char *side, char *howmny, bint *select, int *n, d *s, int *lds, d *p, int *ldp, d *vl, int *ldvl, d *vr, int *ldvr, int *mm, int *m, d *work, int *info) noexcept nogil: + + _fortran_dtgevc(side, howmny, select, n, s, lds, p, ldp, vl, ldvl, vr, ldvr, mm, m, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dtgex2 "BLAS_FUNC(dtgex2)"(bint *wantq, bint *wantz, int *n, d *a, int *lda, d *b, int *ldb, d *q, int *ldq, d *z, int *ldz, int *j1, int *n1, int *n2, d *work, int *lwork, int *info) nogil +cdef void dtgex2(bint *wantq, bint *wantz, int *n, d *a, int *lda, d *b, int *ldb, d *q, int *ldq, d *z, int *ldz, int *j1, int *n1, int *n2, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dtgex2(wantq, wantz, n, a, lda, b, ldb, q, ldq, z, ldz, j1, n1, n2, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dtgexc "BLAS_FUNC(dtgexc)"(bint *wantq, bint *wantz, int *n, d *a, int *lda, d *b, int *ldb, d *q, int *ldq, d *z, int *ldz, int *ifst, int *ilst, d *work, int *lwork, int *info) nogil +cdef void dtgexc(bint *wantq, bint *wantz, int *n, d *a, int *lda, d *b, int *ldb, d *q, int *ldq, d *z, int *ldz, int *ifst, int *ilst, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dtgexc(wantq, wantz, n, a, lda, b, ldb, q, ldq, z, ldz, ifst, ilst, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dtgsen "BLAS_FUNC(dtgsen)"(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, d *a, int *lda, d *b, int *ldb, d *alphar, d *alphai, d *beta, d *q, int *ldq, d *z, int *ldz, int *m, d *pl, d *pr, d *dif, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil +cdef void dtgsen(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, d *a, int *lda, d *b, int *ldb, d *alphar, d *alphai, d *beta, d *q, int *ldq, d *z, int *ldz, int *m, d *pl, d *pr, d *dif, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_dtgsen(ijob, wantq, wantz, select, n, a, lda, b, ldb, alphar, alphai, beta, q, ldq, z, ldz, m, pl, pr, dif, work, lwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dtgsja "BLAS_FUNC(dtgsja)"(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, d *a, int *lda, d *b, int *ldb, d *tola, d *tolb, d *alpha, d *beta, d *u, int *ldu, d *v, int *ldv, d *q, int *ldq, d *work, int *ncycle, int *info) nogil +cdef void dtgsja(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, d *a, int *lda, d *b, int *ldb, d *tola, d *tolb, d *alpha, d *beta, d *u, int *ldu, d *v, int *ldv, d *q, int *ldq, d *work, int *ncycle, int *info) noexcept nogil: + + _fortran_dtgsja(jobu, jobv, jobq, m, p, n, k, l, a, lda, b, ldb, tola, tolb, alpha, beta, u, ldu, v, ldv, q, ldq, work, ncycle, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dtgsna "BLAS_FUNC(dtgsna)"(char *job, char *howmny, bint *select, int *n, d *a, int *lda, d *b, int *ldb, d *vl, int *ldvl, d *vr, int *ldvr, d *s, d *dif, int *mm, int *m, d *work, int *lwork, int *iwork, int *info) nogil +cdef void dtgsna(char *job, char *howmny, bint *select, int *n, d *a, int *lda, d *b, int *ldb, d *vl, int *ldvl, d *vr, int *ldvr, d *s, d *dif, int *mm, int *m, d *work, int *lwork, int *iwork, int *info) noexcept nogil: + + _fortran_dtgsna(job, howmny, select, n, a, lda, b, ldb, vl, ldvl, vr, ldvr, s, dif, mm, m, work, lwork, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dtgsy2 "BLAS_FUNC(dtgsy2)"(char *trans, int *ijob, int *m, int *n, d *a, int *lda, d *b, int *ldb, d *c, int *ldc, d *d, int *ldd, d *e, int *lde, d *f, int *ldf, d *scale, d *rdsum, d *rdscal, int *iwork, int *pq, int *info) nogil +cdef void dtgsy2(char *trans, int *ijob, int *m, int *n, d *a, int *lda, d *b, int *ldb, d *c, int *ldc, d *d, int *ldd, d *e, int *lde, d *f, int *ldf, d *scale, d *rdsum, d *rdscal, int *iwork, int *pq, int *info) noexcept nogil: + + _fortran_dtgsy2(trans, ijob, m, n, a, lda, b, ldb, c, ldc, d, ldd, e, lde, f, ldf, scale, rdsum, rdscal, iwork, pq, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dtgsyl "BLAS_FUNC(dtgsyl)"(char *trans, int *ijob, int *m, int *n, d *a, int *lda, d *b, int *ldb, d *c, int *ldc, d *d, int *ldd, d *e, int *lde, d *f, int *ldf, d *scale, d *dif, d *work, int *lwork, int *iwork, int *info) nogil +cdef void dtgsyl(char *trans, int *ijob, int *m, int *n, d *a, int *lda, d *b, int *ldb, d *c, int *ldc, d *d, int *ldd, d *e, int *lde, d *f, int *ldf, d *scale, d *dif, d *work, int *lwork, int *iwork, int *info) noexcept nogil: + + _fortran_dtgsyl(trans, ijob, m, n, a, lda, b, ldb, c, ldc, d, ldd, e, lde, f, ldf, scale, dif, work, lwork, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dtpcon "BLAS_FUNC(dtpcon)"(char *norm, char *uplo, char *diag, int *n, d *ap, d *rcond, d *work, int *iwork, int *info) nogil +cdef void dtpcon(char *norm, char *uplo, char *diag, int *n, d *ap, d *rcond, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dtpcon(norm, uplo, diag, n, ap, rcond, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dtpmqrt "BLAS_FUNC(dtpmqrt)"(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, d *v, int *ldv, d *t, int *ldt, d *a, int *lda, d *b, int *ldb, d *work, int *info) nogil +cdef void dtpmqrt(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, d *v, int *ldv, d *t, int *ldt, d *a, int *lda, d *b, int *ldb, d *work, int *info) noexcept nogil: + + _fortran_dtpmqrt(side, trans, m, n, k, l, nb, v, ldv, t, ldt, a, lda, b, ldb, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dtpqrt "BLAS_FUNC(dtpqrt)"(int *m, int *n, int *l, int *nb, d *a, int *lda, d *b, int *ldb, d *t, int *ldt, d *work, int *info) nogil +cdef void dtpqrt(int *m, int *n, int *l, int *nb, d *a, int *lda, d *b, int *ldb, d *t, int *ldt, d *work, int *info) noexcept nogil: + + _fortran_dtpqrt(m, n, l, nb, a, lda, b, ldb, t, ldt, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dtpqrt2 "BLAS_FUNC(dtpqrt2)"(int *m, int *n, int *l, d *a, int *lda, d *b, int *ldb, d *t, int *ldt, int *info) nogil +cdef void dtpqrt2(int *m, int *n, int *l, d *a, int *lda, d *b, int *ldb, d *t, int *ldt, int *info) noexcept nogil: + + _fortran_dtpqrt2(m, n, l, a, lda, b, ldb, t, ldt, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dtprfb "BLAS_FUNC(dtprfb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, d *v, int *ldv, d *t, int *ldt, d *a, int *lda, d *b, int *ldb, d *work, int *ldwork) nogil +cdef void dtprfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, d *v, int *ldv, d *t, int *ldt, d *a, int *lda, d *b, int *ldb, d *work, int *ldwork) noexcept nogil: + + _fortran_dtprfb(side, trans, direct, storev, m, n, k, l, v, ldv, t, ldt, a, lda, b, ldb, work, ldwork) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dtprfs "BLAS_FUNC(dtprfs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *ap, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) nogil +cdef void dtprfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *ap, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dtprfs(uplo, trans, diag, n, nrhs, ap, b, ldb, x, ldx, ferr, berr, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dtptri "BLAS_FUNC(dtptri)"(char *uplo, char *diag, int *n, d *ap, int *info) nogil +cdef void dtptri(char *uplo, char *diag, int *n, d *ap, int *info) noexcept nogil: + + _fortran_dtptri(uplo, diag, n, ap, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dtptrs "BLAS_FUNC(dtptrs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *ap, d *b, int *ldb, int *info) nogil +cdef void dtptrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *ap, d *b, int *ldb, int *info) noexcept nogil: + + _fortran_dtptrs(uplo, trans, diag, n, nrhs, ap, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dtpttf "BLAS_FUNC(dtpttf)"(char *transr, char *uplo, int *n, d *ap, d *arf, int *info) nogil +cdef void dtpttf(char *transr, char *uplo, int *n, d *ap, d *arf, int *info) noexcept nogil: + + _fortran_dtpttf(transr, uplo, n, ap, arf, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dtpttr "BLAS_FUNC(dtpttr)"(char *uplo, int *n, d *ap, d *a, int *lda, int *info) nogil +cdef void dtpttr(char *uplo, int *n, d *ap, d *a, int *lda, int *info) noexcept nogil: + + _fortran_dtpttr(uplo, n, ap, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dtrcon "BLAS_FUNC(dtrcon)"(char *norm, char *uplo, char *diag, int *n, d *a, int *lda, d *rcond, d *work, int *iwork, int *info) nogil +cdef void dtrcon(char *norm, char *uplo, char *diag, int *n, d *a, int *lda, d *rcond, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dtrcon(norm, uplo, diag, n, a, lda, rcond, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dtrevc "BLAS_FUNC(dtrevc)"(char *side, char *howmny, bint *select, int *n, d *t, int *ldt, d *vl, int *ldvl, d *vr, int *ldvr, int *mm, int *m, d *work, int *info) nogil +cdef void dtrevc(char *side, char *howmny, bint *select, int *n, d *t, int *ldt, d *vl, int *ldvl, d *vr, int *ldvr, int *mm, int *m, d *work, int *info) noexcept nogil: + + _fortran_dtrevc(side, howmny, select, n, t, ldt, vl, ldvl, vr, ldvr, mm, m, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dtrexc "BLAS_FUNC(dtrexc)"(char *compq, int *n, d *t, int *ldt, d *q, int *ldq, int *ifst, int *ilst, d *work, int *info) nogil +cdef void dtrexc(char *compq, int *n, d *t, int *ldt, d *q, int *ldq, int *ifst, int *ilst, d *work, int *info) noexcept nogil: + + _fortran_dtrexc(compq, n, t, ldt, q, ldq, ifst, ilst, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dtrrfs "BLAS_FUNC(dtrrfs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) nogil +cdef void dtrrfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_dtrrfs(uplo, trans, diag, n, nrhs, a, lda, b, ldb, x, ldx, ferr, berr, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dtrsen "BLAS_FUNC(dtrsen)"(char *job, char *compq, bint *select, int *n, d *t, int *ldt, d *q, int *ldq, d *wr, d *wi, int *m, d *s, d *sep, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil +cdef void dtrsen(char *job, char *compq, bint *select, int *n, d *t, int *ldt, d *q, int *ldq, d *wr, d *wi, int *m, d *s, d *sep, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_dtrsen(job, compq, select, n, t, ldt, q, ldq, wr, wi, m, s, sep, work, lwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dtrsna "BLAS_FUNC(dtrsna)"(char *job, char *howmny, bint *select, int *n, d *t, int *ldt, d *vl, int *ldvl, d *vr, int *ldvr, d *s, d *sep, int *mm, int *m, d *work, int *ldwork, int *iwork, int *info) nogil +cdef void dtrsna(char *job, char *howmny, bint *select, int *n, d *t, int *ldt, d *vl, int *ldvl, d *vr, int *ldvr, d *s, d *sep, int *mm, int *m, d *work, int *ldwork, int *iwork, int *info) noexcept nogil: + + _fortran_dtrsna(job, howmny, select, n, t, ldt, vl, ldvl, vr, ldvr, s, sep, mm, m, work, ldwork, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dtrsyl "BLAS_FUNC(dtrsyl)"(char *trana, char *tranb, int *isgn, int *m, int *n, d *a, int *lda, d *b, int *ldb, d *c, int *ldc, d *scale, int *info) nogil +cdef void dtrsyl(char *trana, char *tranb, int *isgn, int *m, int *n, d *a, int *lda, d *b, int *ldb, d *c, int *ldc, d *scale, int *info) noexcept nogil: + + _fortran_dtrsyl(trana, tranb, isgn, m, n, a, lda, b, ldb, c, ldc, scale, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dtrti2 "BLAS_FUNC(dtrti2)"(char *uplo, char *diag, int *n, d *a, int *lda, int *info) nogil +cdef void dtrti2(char *uplo, char *diag, int *n, d *a, int *lda, int *info) noexcept nogil: + + _fortran_dtrti2(uplo, diag, n, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dtrtri "BLAS_FUNC(dtrtri)"(char *uplo, char *diag, int *n, d *a, int *lda, int *info) nogil +cdef void dtrtri(char *uplo, char *diag, int *n, d *a, int *lda, int *info) noexcept nogil: + + _fortran_dtrtri(uplo, diag, n, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dtrtrs "BLAS_FUNC(dtrtrs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *info) nogil +cdef void dtrtrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *info) noexcept nogil: + + _fortran_dtrtrs(uplo, trans, diag, n, nrhs, a, lda, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dtrttf "BLAS_FUNC(dtrttf)"(char *transr, char *uplo, int *n, d *a, int *lda, d *arf, int *info) nogil +cdef void dtrttf(char *transr, char *uplo, int *n, d *a, int *lda, d *arf, int *info) noexcept nogil: + + _fortran_dtrttf(transr, uplo, n, a, lda, arf, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dtrttp "BLAS_FUNC(dtrttp)"(char *uplo, int *n, d *a, int *lda, d *ap, int *info) nogil +cdef void dtrttp(char *uplo, int *n, d *a, int *lda, d *ap, int *info) noexcept nogil: + + _fortran_dtrttp(uplo, n, a, lda, ap, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_dtzrzf "BLAS_FUNC(dtzrzf)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil +cdef void dtzrzf(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil: + + _fortran_dtzrzf(m, n, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + d _fortran_dzsum1 "BLAS_FUNC(dzsum1)"(int *n, npy_complex128 *cx, int *incx) nogil +cdef d dzsum1(int *n, z *cx, int *incx) noexcept nogil: + + return _fortran_dzsum1(n, cx, incx) + + +cdef extern from "_lapack_subroutines.h": + int _fortran_icmax1 "BLAS_FUNC(icmax1)"(int *n, npy_complex64 *cx, int *incx) nogil +cdef int icmax1(int *n, c *cx, int *incx) noexcept nogil: + + return _fortran_icmax1(n, cx, incx) + + +cdef extern from "_lapack_subroutines.h": + int _fortran_ieeeck "BLAS_FUNC(ieeeck)"(int *ispec, s *zero, s *one) nogil +cdef int ieeeck(int *ispec, s *zero, s *one) noexcept nogil: + + return _fortran_ieeeck(ispec, zero, one) + + +cdef extern from "_lapack_subroutines.h": + int _fortran_ilaclc "BLAS_FUNC(ilaclc)"(int *m, int *n, npy_complex64 *a, int *lda) nogil +cdef int ilaclc(int *m, int *n, c *a, int *lda) noexcept nogil: + + return _fortran_ilaclc(m, n, a, lda) + + +cdef extern from "_lapack_subroutines.h": + int _fortran_ilaclr "BLAS_FUNC(ilaclr)"(int *m, int *n, npy_complex64 *a, int *lda) nogil +cdef int ilaclr(int *m, int *n, c *a, int *lda) noexcept nogil: + + return _fortran_ilaclr(m, n, a, lda) + + +cdef extern from "_lapack_subroutines.h": + int _fortran_iladiag "BLAS_FUNC(iladiag)"(char *diag) nogil +cdef int iladiag(char *diag) noexcept nogil: + + return _fortran_iladiag(diag) + + +cdef extern from "_lapack_subroutines.h": + int _fortran_iladlc "BLAS_FUNC(iladlc)"(int *m, int *n, d *a, int *lda) nogil +cdef int iladlc(int *m, int *n, d *a, int *lda) noexcept nogil: + + return _fortran_iladlc(m, n, a, lda) + + +cdef extern from "_lapack_subroutines.h": + int _fortran_iladlr "BLAS_FUNC(iladlr)"(int *m, int *n, d *a, int *lda) nogil +cdef int iladlr(int *m, int *n, d *a, int *lda) noexcept nogil: + + return _fortran_iladlr(m, n, a, lda) + + +cdef extern from "_lapack_subroutines.h": + int _fortran_ilaprec "BLAS_FUNC(ilaprec)"(char *prec) nogil +cdef int ilaprec(char *prec) noexcept nogil: + + return _fortran_ilaprec(prec) + + +cdef extern from "_lapack_subroutines.h": + int _fortran_ilaslc "BLAS_FUNC(ilaslc)"(int *m, int *n, s *a, int *lda) nogil +cdef int ilaslc(int *m, int *n, s *a, int *lda) noexcept nogil: + + return _fortran_ilaslc(m, n, a, lda) + + +cdef extern from "_lapack_subroutines.h": + int _fortran_ilaslr "BLAS_FUNC(ilaslr)"(int *m, int *n, s *a, int *lda) nogil +cdef int ilaslr(int *m, int *n, s *a, int *lda) noexcept nogil: + + return _fortran_ilaslr(m, n, a, lda) + + +cdef extern from "_lapack_subroutines.h": + int _fortran_ilatrans "BLAS_FUNC(ilatrans)"(char *trans) nogil +cdef int ilatrans(char *trans) noexcept nogil: + + return _fortran_ilatrans(trans) + + +cdef extern from "_lapack_subroutines.h": + int _fortran_ilauplo "BLAS_FUNC(ilauplo)"(char *uplo) nogil +cdef int ilauplo(char *uplo) noexcept nogil: + + return _fortran_ilauplo(uplo) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ilaver "BLAS_FUNC(ilaver)"(int *vers_major, int *vers_minor, int *vers_patch) nogil +cdef void ilaver(int *vers_major, int *vers_minor, int *vers_patch) noexcept nogil: + + _fortran_ilaver(vers_major, vers_minor, vers_patch) + + +cdef extern from "_lapack_subroutines.h": + int _fortran_ilazlc "BLAS_FUNC(ilazlc)"(int *m, int *n, npy_complex128 *a, int *lda) nogil +cdef int ilazlc(int *m, int *n, z *a, int *lda) noexcept nogil: + + return _fortran_ilazlc(m, n, a, lda) + + +cdef extern from "_lapack_subroutines.h": + int _fortran_ilazlr "BLAS_FUNC(ilazlr)"(int *m, int *n, npy_complex128 *a, int *lda) nogil +cdef int ilazlr(int *m, int *n, z *a, int *lda) noexcept nogil: + + return _fortran_ilazlr(m, n, a, lda) + + +cdef extern from "_lapack_subroutines.h": + int _fortran_izmax1 "BLAS_FUNC(izmax1)"(int *n, npy_complex128 *cx, int *incx) nogil +cdef int izmax1(int *n, z *cx, int *incx) noexcept nogil: + + return _fortran_izmax1(n, cx, incx) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sbbcsd "BLAS_FUNC(sbbcsd)"(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, s *theta, s *phi, s *u1, int *ldu1, s *u2, int *ldu2, s *v1t, int *ldv1t, s *v2t, int *ldv2t, s *b11d, s *b11e, s *b12d, s *b12e, s *b21d, s *b21e, s *b22d, s *b22e, s *work, int *lwork, int *info) nogil +cdef void sbbcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, s *theta, s *phi, s *u1, int *ldu1, s *u2, int *ldu2, s *v1t, int *ldv1t, s *v2t, int *ldv2t, s *b11d, s *b11e, s *b12d, s *b12e, s *b21d, s *b21e, s *b22d, s *b22e, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_sbbcsd(jobu1, jobu2, jobv1t, jobv2t, trans, m, p, q, theta, phi, u1, ldu1, u2, ldu2, v1t, ldv1t, v2t, ldv2t, b11d, b11e, b12d, b12e, b21d, b21e, b22d, b22e, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sbdsdc "BLAS_FUNC(sbdsdc)"(char *uplo, char *compq, int *n, s *d, s *e, s *u, int *ldu, s *vt, int *ldvt, s *q, int *iq, s *work, int *iwork, int *info) nogil +cdef void sbdsdc(char *uplo, char *compq, int *n, s *d, s *e, s *u, int *ldu, s *vt, int *ldvt, s *q, int *iq, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_sbdsdc(uplo, compq, n, d, e, u, ldu, vt, ldvt, q, iq, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sbdsqr "BLAS_FUNC(sbdsqr)"(char *uplo, int *n, int *ncvt, int *nru, int *ncc, s *d, s *e, s *vt, int *ldvt, s *u, int *ldu, s *c, int *ldc, s *work, int *info) nogil +cdef void sbdsqr(char *uplo, int *n, int *ncvt, int *nru, int *ncc, s *d, s *e, s *vt, int *ldvt, s *u, int *ldu, s *c, int *ldc, s *work, int *info) noexcept nogil: + + _fortran_sbdsqr(uplo, n, ncvt, nru, ncc, d, e, vt, ldvt, u, ldu, c, ldc, work, info) + + +cdef extern from "_lapack_subroutines.h": + s _fortran_scsum1 "BLAS_FUNC(scsum1)"(int *n, npy_complex64 *cx, int *incx) nogil +cdef s scsum1(int *n, c *cx, int *incx) noexcept nogil: + + return _fortran_scsum1(n, cx, incx) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sdisna "BLAS_FUNC(sdisna)"(char *job, int *m, int *n, s *d, s *sep, int *info) nogil +cdef void sdisna(char *job, int *m, int *n, s *d, s *sep, int *info) noexcept nogil: + + _fortran_sdisna(job, m, n, d, sep, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgbbrd "BLAS_FUNC(sgbbrd)"(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, s *ab, int *ldab, s *d, s *e, s *q, int *ldq, s *pt, int *ldpt, s *c, int *ldc, s *work, int *info) nogil +cdef void sgbbrd(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, s *ab, int *ldab, s *d, s *e, s *q, int *ldq, s *pt, int *ldpt, s *c, int *ldc, s *work, int *info) noexcept nogil: + + _fortran_sgbbrd(vect, m, n, ncc, kl, ku, ab, ldab, d, e, q, ldq, pt, ldpt, c, ldc, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgbcon "BLAS_FUNC(sgbcon)"(char *norm, int *n, int *kl, int *ku, s *ab, int *ldab, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) nogil +cdef void sgbcon(char *norm, int *n, int *kl, int *ku, s *ab, int *ldab, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_sgbcon(norm, n, kl, ku, ab, ldab, ipiv, anorm, rcond, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgbequ "BLAS_FUNC(sgbequ)"(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) nogil +cdef void sgbequ(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil: + + _fortran_sgbequ(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgbequb "BLAS_FUNC(sgbequb)"(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) nogil +cdef void sgbequb(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil: + + _fortran_sgbequb(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgbrfs "BLAS_FUNC(sgbrfs)"(char *trans, int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, s *afb, int *ldafb, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) nogil +cdef void sgbrfs(char *trans, int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, s *afb, int *ldafb, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_sgbrfs(trans, n, kl, ku, nrhs, ab, ldab, afb, ldafb, ipiv, b, ldb, x, ldx, ferr, berr, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgbsv "BLAS_FUNC(sgbsv)"(int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, int *ipiv, s *b, int *ldb, int *info) nogil +cdef void sgbsv(int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, int *ipiv, s *b, int *ldb, int *info) noexcept nogil: + + _fortran_sgbsv(n, kl, ku, nrhs, ab, ldab, ipiv, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgbsvx "BLAS_FUNC(sgbsvx)"(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, s *afb, int *ldafb, int *ipiv, char *equed, s *r, s *c, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) nogil +cdef void sgbsvx(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, s *afb, int *ldafb, int *ipiv, char *equed, s *r, s *c, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_sgbsvx(fact, trans, n, kl, ku, nrhs, ab, ldab, afb, ldafb, ipiv, equed, r, c, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgbtf2 "BLAS_FUNC(sgbtf2)"(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, int *ipiv, int *info) nogil +cdef void sgbtf2(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, int *ipiv, int *info) noexcept nogil: + + _fortran_sgbtf2(m, n, kl, ku, ab, ldab, ipiv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgbtrf "BLAS_FUNC(sgbtrf)"(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, int *ipiv, int *info) nogil +cdef void sgbtrf(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, int *ipiv, int *info) noexcept nogil: + + _fortran_sgbtrf(m, n, kl, ku, ab, ldab, ipiv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgbtrs "BLAS_FUNC(sgbtrs)"(char *trans, int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, int *ipiv, s *b, int *ldb, int *info) nogil +cdef void sgbtrs(char *trans, int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, int *ipiv, s *b, int *ldb, int *info) noexcept nogil: + + _fortran_sgbtrs(trans, n, kl, ku, nrhs, ab, ldab, ipiv, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgebak "BLAS_FUNC(sgebak)"(char *job, char *side, int *n, int *ilo, int *ihi, s *scale, int *m, s *v, int *ldv, int *info) nogil +cdef void sgebak(char *job, char *side, int *n, int *ilo, int *ihi, s *scale, int *m, s *v, int *ldv, int *info) noexcept nogil: + + _fortran_sgebak(job, side, n, ilo, ihi, scale, m, v, ldv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgebal "BLAS_FUNC(sgebal)"(char *job, int *n, s *a, int *lda, int *ilo, int *ihi, s *scale, int *info) nogil +cdef void sgebal(char *job, int *n, s *a, int *lda, int *ilo, int *ihi, s *scale, int *info) noexcept nogil: + + _fortran_sgebal(job, n, a, lda, ilo, ihi, scale, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgebd2 "BLAS_FUNC(sgebd2)"(int *m, int *n, s *a, int *lda, s *d, s *e, s *tauq, s *taup, s *work, int *info) nogil +cdef void sgebd2(int *m, int *n, s *a, int *lda, s *d, s *e, s *tauq, s *taup, s *work, int *info) noexcept nogil: + + _fortran_sgebd2(m, n, a, lda, d, e, tauq, taup, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgebrd "BLAS_FUNC(sgebrd)"(int *m, int *n, s *a, int *lda, s *d, s *e, s *tauq, s *taup, s *work, int *lwork, int *info) nogil +cdef void sgebrd(int *m, int *n, s *a, int *lda, s *d, s *e, s *tauq, s *taup, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_sgebrd(m, n, a, lda, d, e, tauq, taup, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgecon "BLAS_FUNC(sgecon)"(char *norm, int *n, s *a, int *lda, s *anorm, s *rcond, s *work, int *iwork, int *info) nogil +cdef void sgecon(char *norm, int *n, s *a, int *lda, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_sgecon(norm, n, a, lda, anorm, rcond, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgeequ "BLAS_FUNC(sgeequ)"(int *m, int *n, s *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) nogil +cdef void sgeequ(int *m, int *n, s *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil: + + _fortran_sgeequ(m, n, a, lda, r, c, rowcnd, colcnd, amax, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgeequb "BLAS_FUNC(sgeequb)"(int *m, int *n, s *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) nogil +cdef void sgeequb(int *m, int *n, s *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil: + + _fortran_sgeequb(m, n, a, lda, r, c, rowcnd, colcnd, amax, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgees "BLAS_FUNC(sgees)"(char *jobvs, char *sort, _sselect2 *select, int *n, s *a, int *lda, int *sdim, s *wr, s *wi, s *vs, int *ldvs, s *work, int *lwork, bint *bwork, int *info) nogil +cdef void sgees(char *jobvs, char *sort, sselect2 *select, int *n, s *a, int *lda, int *sdim, s *wr, s *wi, s *vs, int *ldvs, s *work, int *lwork, bint *bwork, int *info) noexcept nogil: + + _fortran_sgees(jobvs, sort, <_sselect2*>select, n, a, lda, sdim, wr, wi, vs, ldvs, work, lwork, bwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgeesx "BLAS_FUNC(sgeesx)"(char *jobvs, char *sort, _sselect2 *select, char *sense, int *n, s *a, int *lda, int *sdim, s *wr, s *wi, s *vs, int *ldvs, s *rconde, s *rcondv, s *work, int *lwork, int *iwork, int *liwork, bint *bwork, int *info) nogil +cdef void sgeesx(char *jobvs, char *sort, sselect2 *select, char *sense, int *n, s *a, int *lda, int *sdim, s *wr, s *wi, s *vs, int *ldvs, s *rconde, s *rcondv, s *work, int *lwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil: + + _fortran_sgeesx(jobvs, sort, <_sselect2*>select, sense, n, a, lda, sdim, wr, wi, vs, ldvs, rconde, rcondv, work, lwork, iwork, liwork, bwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgeev "BLAS_FUNC(sgeev)"(char *jobvl, char *jobvr, int *n, s *a, int *lda, s *wr, s *wi, s *vl, int *ldvl, s *vr, int *ldvr, s *work, int *lwork, int *info) nogil +cdef void sgeev(char *jobvl, char *jobvr, int *n, s *a, int *lda, s *wr, s *wi, s *vl, int *ldvl, s *vr, int *ldvr, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_sgeev(jobvl, jobvr, n, a, lda, wr, wi, vl, ldvl, vr, ldvr, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgeevx "BLAS_FUNC(sgeevx)"(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, s *a, int *lda, s *wr, s *wi, s *vl, int *ldvl, s *vr, int *ldvr, int *ilo, int *ihi, s *scale, s *abnrm, s *rconde, s *rcondv, s *work, int *lwork, int *iwork, int *info) nogil +cdef void sgeevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, s *a, int *lda, s *wr, s *wi, s *vl, int *ldvl, s *vr, int *ldvr, int *ilo, int *ihi, s *scale, s *abnrm, s *rconde, s *rcondv, s *work, int *lwork, int *iwork, int *info) noexcept nogil: + + _fortran_sgeevx(balanc, jobvl, jobvr, sense, n, a, lda, wr, wi, vl, ldvl, vr, ldvr, ilo, ihi, scale, abnrm, rconde, rcondv, work, lwork, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgehd2 "BLAS_FUNC(sgehd2)"(int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *work, int *info) nogil +cdef void sgehd2(int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil: + + _fortran_sgehd2(n, ilo, ihi, a, lda, tau, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgehrd "BLAS_FUNC(sgehrd)"(int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil +cdef void sgehrd(int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_sgehrd(n, ilo, ihi, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgejsv "BLAS_FUNC(sgejsv)"(char *joba, char *jobu, char *jobv, char *jobr, char *jobt, char *jobp, int *m, int *n, s *a, int *lda, s *sva, s *u, int *ldu, s *v, int *ldv, s *work, int *lwork, int *iwork, int *info) nogil +cdef void sgejsv(char *joba, char *jobu, char *jobv, char *jobr, char *jobt, char *jobp, int *m, int *n, s *a, int *lda, s *sva, s *u, int *ldu, s *v, int *ldv, s *work, int *lwork, int *iwork, int *info) noexcept nogil: + + _fortran_sgejsv(joba, jobu, jobv, jobr, jobt, jobp, m, n, a, lda, sva, u, ldu, v, ldv, work, lwork, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgelq2 "BLAS_FUNC(sgelq2)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) nogil +cdef void sgelq2(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil: + + _fortran_sgelq2(m, n, a, lda, tau, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgelqf "BLAS_FUNC(sgelqf)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil +cdef void sgelqf(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_sgelqf(m, n, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgels "BLAS_FUNC(sgels)"(char *trans, int *m, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, s *work, int *lwork, int *info) nogil +cdef void sgels(char *trans, int *m, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_sgels(trans, m, n, nrhs, a, lda, b, ldb, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgelsd "BLAS_FUNC(sgelsd)"(int *m, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, s *s, s *rcond, int *rank, s *work, int *lwork, int *iwork, int *info) nogil +cdef void sgelsd(int *m, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, s *s, s *rcond, int *rank, s *work, int *lwork, int *iwork, int *info) noexcept nogil: + + _fortran_sgelsd(m, n, nrhs, a, lda, b, ldb, s, rcond, rank, work, lwork, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgelss "BLAS_FUNC(sgelss)"(int *m, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, s *s, s *rcond, int *rank, s *work, int *lwork, int *info) nogil +cdef void sgelss(int *m, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, s *s, s *rcond, int *rank, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_sgelss(m, n, nrhs, a, lda, b, ldb, s, rcond, rank, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgelsy "BLAS_FUNC(sgelsy)"(int *m, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *jpvt, s *rcond, int *rank, s *work, int *lwork, int *info) nogil +cdef void sgelsy(int *m, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *jpvt, s *rcond, int *rank, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_sgelsy(m, n, nrhs, a, lda, b, ldb, jpvt, rcond, rank, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgemqrt "BLAS_FUNC(sgemqrt)"(char *side, char *trans, int *m, int *n, int *k, int *nb, s *v, int *ldv, s *t, int *ldt, s *c, int *ldc, s *work, int *info) nogil +cdef void sgemqrt(char *side, char *trans, int *m, int *n, int *k, int *nb, s *v, int *ldv, s *t, int *ldt, s *c, int *ldc, s *work, int *info) noexcept nogil: + + _fortran_sgemqrt(side, trans, m, n, k, nb, v, ldv, t, ldt, c, ldc, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgeql2 "BLAS_FUNC(sgeql2)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) nogil +cdef void sgeql2(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil: + + _fortran_sgeql2(m, n, a, lda, tau, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgeqlf "BLAS_FUNC(sgeqlf)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil +cdef void sgeqlf(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_sgeqlf(m, n, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgeqp3 "BLAS_FUNC(sgeqp3)"(int *m, int *n, s *a, int *lda, int *jpvt, s *tau, s *work, int *lwork, int *info) nogil +cdef void sgeqp3(int *m, int *n, s *a, int *lda, int *jpvt, s *tau, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_sgeqp3(m, n, a, lda, jpvt, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgeqr2 "BLAS_FUNC(sgeqr2)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) nogil +cdef void sgeqr2(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil: + + _fortran_sgeqr2(m, n, a, lda, tau, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgeqr2p "BLAS_FUNC(sgeqr2p)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) nogil +cdef void sgeqr2p(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil: + + _fortran_sgeqr2p(m, n, a, lda, tau, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgeqrf "BLAS_FUNC(sgeqrf)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil +cdef void sgeqrf(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_sgeqrf(m, n, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgeqrfp "BLAS_FUNC(sgeqrfp)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil +cdef void sgeqrfp(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_sgeqrfp(m, n, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgeqrt "BLAS_FUNC(sgeqrt)"(int *m, int *n, int *nb, s *a, int *lda, s *t, int *ldt, s *work, int *info) nogil +cdef void sgeqrt(int *m, int *n, int *nb, s *a, int *lda, s *t, int *ldt, s *work, int *info) noexcept nogil: + + _fortran_sgeqrt(m, n, nb, a, lda, t, ldt, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgeqrt2 "BLAS_FUNC(sgeqrt2)"(int *m, int *n, s *a, int *lda, s *t, int *ldt, int *info) nogil +cdef void sgeqrt2(int *m, int *n, s *a, int *lda, s *t, int *ldt, int *info) noexcept nogil: + + _fortran_sgeqrt2(m, n, a, lda, t, ldt, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgeqrt3 "BLAS_FUNC(sgeqrt3)"(int *m, int *n, s *a, int *lda, s *t, int *ldt, int *info) nogil +cdef void sgeqrt3(int *m, int *n, s *a, int *lda, s *t, int *ldt, int *info) noexcept nogil: + + _fortran_sgeqrt3(m, n, a, lda, t, ldt, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgerfs "BLAS_FUNC(sgerfs)"(char *trans, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) nogil +cdef void sgerfs(char *trans, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_sgerfs(trans, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, ferr, berr, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgerq2 "BLAS_FUNC(sgerq2)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) nogil +cdef void sgerq2(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil: + + _fortran_sgerq2(m, n, a, lda, tau, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgerqf "BLAS_FUNC(sgerqf)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil +cdef void sgerqf(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_sgerqf(m, n, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgesc2 "BLAS_FUNC(sgesc2)"(int *n, s *a, int *lda, s *rhs, int *ipiv, int *jpiv, s *scale) nogil +cdef void sgesc2(int *n, s *a, int *lda, s *rhs, int *ipiv, int *jpiv, s *scale) noexcept nogil: + + _fortran_sgesc2(n, a, lda, rhs, ipiv, jpiv, scale) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgesdd "BLAS_FUNC(sgesdd)"(char *jobz, int *m, int *n, s *a, int *lda, s *s, s *u, int *ldu, s *vt, int *ldvt, s *work, int *lwork, int *iwork, int *info) nogil +cdef void sgesdd(char *jobz, int *m, int *n, s *a, int *lda, s *s, s *u, int *ldu, s *vt, int *ldvt, s *work, int *lwork, int *iwork, int *info) noexcept nogil: + + _fortran_sgesdd(jobz, m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgesv "BLAS_FUNC(sgesv)"(int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, int *info) nogil +cdef void sgesv(int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, int *info) noexcept nogil: + + _fortran_sgesv(n, nrhs, a, lda, ipiv, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgesvd "BLAS_FUNC(sgesvd)"(char *jobu, char *jobvt, int *m, int *n, s *a, int *lda, s *s, s *u, int *ldu, s *vt, int *ldvt, s *work, int *lwork, int *info) nogil +cdef void sgesvd(char *jobu, char *jobvt, int *m, int *n, s *a, int *lda, s *s, s *u, int *ldu, s *vt, int *ldvt, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_sgesvd(jobu, jobvt, m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgesvj "BLAS_FUNC(sgesvj)"(char *joba, char *jobu, char *jobv, int *m, int *n, s *a, int *lda, s *sva, int *mv, s *v, int *ldv, s *work, int *lwork, int *info) nogil +cdef void sgesvj(char *joba, char *jobu, char *jobv, int *m, int *n, s *a, int *lda, s *sva, int *mv, s *v, int *ldv, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_sgesvj(joba, jobu, jobv, m, n, a, lda, sva, mv, v, ldv, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgesvx "BLAS_FUNC(sgesvx)"(char *fact, char *trans, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, int *ipiv, char *equed, s *r, s *c, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) nogil +cdef void sgesvx(char *fact, char *trans, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, int *ipiv, char *equed, s *r, s *c, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_sgesvx(fact, trans, n, nrhs, a, lda, af, ldaf, ipiv, equed, r, c, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgetc2 "BLAS_FUNC(sgetc2)"(int *n, s *a, int *lda, int *ipiv, int *jpiv, int *info) nogil +cdef void sgetc2(int *n, s *a, int *lda, int *ipiv, int *jpiv, int *info) noexcept nogil: + + _fortran_sgetc2(n, a, lda, ipiv, jpiv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgetf2 "BLAS_FUNC(sgetf2)"(int *m, int *n, s *a, int *lda, int *ipiv, int *info) nogil +cdef void sgetf2(int *m, int *n, s *a, int *lda, int *ipiv, int *info) noexcept nogil: + + _fortran_sgetf2(m, n, a, lda, ipiv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgetrf "BLAS_FUNC(sgetrf)"(int *m, int *n, s *a, int *lda, int *ipiv, int *info) nogil +cdef void sgetrf(int *m, int *n, s *a, int *lda, int *ipiv, int *info) noexcept nogil: + + _fortran_sgetrf(m, n, a, lda, ipiv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgetri "BLAS_FUNC(sgetri)"(int *n, s *a, int *lda, int *ipiv, s *work, int *lwork, int *info) nogil +cdef void sgetri(int *n, s *a, int *lda, int *ipiv, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_sgetri(n, a, lda, ipiv, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgetrs "BLAS_FUNC(sgetrs)"(char *trans, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, int *info) nogil +cdef void sgetrs(char *trans, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, int *info) noexcept nogil: + + _fortran_sgetrs(trans, n, nrhs, a, lda, ipiv, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sggbak "BLAS_FUNC(sggbak)"(char *job, char *side, int *n, int *ilo, int *ihi, s *lscale, s *rscale, int *m, s *v, int *ldv, int *info) nogil +cdef void sggbak(char *job, char *side, int *n, int *ilo, int *ihi, s *lscale, s *rscale, int *m, s *v, int *ldv, int *info) noexcept nogil: + + _fortran_sggbak(job, side, n, ilo, ihi, lscale, rscale, m, v, ldv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sggbal "BLAS_FUNC(sggbal)"(char *job, int *n, s *a, int *lda, s *b, int *ldb, int *ilo, int *ihi, s *lscale, s *rscale, s *work, int *info) nogil +cdef void sggbal(char *job, int *n, s *a, int *lda, s *b, int *ldb, int *ilo, int *ihi, s *lscale, s *rscale, s *work, int *info) noexcept nogil: + + _fortran_sggbal(job, n, a, lda, b, ldb, ilo, ihi, lscale, rscale, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgges "BLAS_FUNC(sgges)"(char *jobvsl, char *jobvsr, char *sort, _sselect3 *selctg, int *n, s *a, int *lda, s *b, int *ldb, int *sdim, s *alphar, s *alphai, s *beta, s *vsl, int *ldvsl, s *vsr, int *ldvsr, s *work, int *lwork, bint *bwork, int *info) nogil +cdef void sgges(char *jobvsl, char *jobvsr, char *sort, sselect3 *selctg, int *n, s *a, int *lda, s *b, int *ldb, int *sdim, s *alphar, s *alphai, s *beta, s *vsl, int *ldvsl, s *vsr, int *ldvsr, s *work, int *lwork, bint *bwork, int *info) noexcept nogil: + + _fortran_sgges(jobvsl, jobvsr, sort, <_sselect3*>selctg, n, a, lda, b, ldb, sdim, alphar, alphai, beta, vsl, ldvsl, vsr, ldvsr, work, lwork, bwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sggesx "BLAS_FUNC(sggesx)"(char *jobvsl, char *jobvsr, char *sort, _sselect3 *selctg, char *sense, int *n, s *a, int *lda, s *b, int *ldb, int *sdim, s *alphar, s *alphai, s *beta, s *vsl, int *ldvsl, s *vsr, int *ldvsr, s *rconde, s *rcondv, s *work, int *lwork, int *iwork, int *liwork, bint *bwork, int *info) nogil +cdef void sggesx(char *jobvsl, char *jobvsr, char *sort, sselect3 *selctg, char *sense, int *n, s *a, int *lda, s *b, int *ldb, int *sdim, s *alphar, s *alphai, s *beta, s *vsl, int *ldvsl, s *vsr, int *ldvsr, s *rconde, s *rcondv, s *work, int *lwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil: + + _fortran_sggesx(jobvsl, jobvsr, sort, <_sselect3*>selctg, sense, n, a, lda, b, ldb, sdim, alphar, alphai, beta, vsl, ldvsl, vsr, ldvsr, rconde, rcondv, work, lwork, iwork, liwork, bwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sggev "BLAS_FUNC(sggev)"(char *jobvl, char *jobvr, int *n, s *a, int *lda, s *b, int *ldb, s *alphar, s *alphai, s *beta, s *vl, int *ldvl, s *vr, int *ldvr, s *work, int *lwork, int *info) nogil +cdef void sggev(char *jobvl, char *jobvr, int *n, s *a, int *lda, s *b, int *ldb, s *alphar, s *alphai, s *beta, s *vl, int *ldvl, s *vr, int *ldvr, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_sggev(jobvl, jobvr, n, a, lda, b, ldb, alphar, alphai, beta, vl, ldvl, vr, ldvr, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sggevx "BLAS_FUNC(sggevx)"(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, s *a, int *lda, s *b, int *ldb, s *alphar, s *alphai, s *beta, s *vl, int *ldvl, s *vr, int *ldvr, int *ilo, int *ihi, s *lscale, s *rscale, s *abnrm, s *bbnrm, s *rconde, s *rcondv, s *work, int *lwork, int *iwork, bint *bwork, int *info) nogil +cdef void sggevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, s *a, int *lda, s *b, int *ldb, s *alphar, s *alphai, s *beta, s *vl, int *ldvl, s *vr, int *ldvr, int *ilo, int *ihi, s *lscale, s *rscale, s *abnrm, s *bbnrm, s *rconde, s *rcondv, s *work, int *lwork, int *iwork, bint *bwork, int *info) noexcept nogil: + + _fortran_sggevx(balanc, jobvl, jobvr, sense, n, a, lda, b, ldb, alphar, alphai, beta, vl, ldvl, vr, ldvr, ilo, ihi, lscale, rscale, abnrm, bbnrm, rconde, rcondv, work, lwork, iwork, bwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sggglm "BLAS_FUNC(sggglm)"(int *n, int *m, int *p, s *a, int *lda, s *b, int *ldb, s *d, s *x, s *y, s *work, int *lwork, int *info) nogil +cdef void sggglm(int *n, int *m, int *p, s *a, int *lda, s *b, int *ldb, s *d, s *x, s *y, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_sggglm(n, m, p, a, lda, b, ldb, d, x, y, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgghrd "BLAS_FUNC(sgghrd)"(char *compq, char *compz, int *n, int *ilo, int *ihi, s *a, int *lda, s *b, int *ldb, s *q, int *ldq, s *z, int *ldz, int *info) nogil +cdef void sgghrd(char *compq, char *compz, int *n, int *ilo, int *ihi, s *a, int *lda, s *b, int *ldb, s *q, int *ldq, s *z, int *ldz, int *info) noexcept nogil: + + _fortran_sgghrd(compq, compz, n, ilo, ihi, a, lda, b, ldb, q, ldq, z, ldz, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgglse "BLAS_FUNC(sgglse)"(int *m, int *n, int *p, s *a, int *lda, s *b, int *ldb, s *c, s *d, s *x, s *work, int *lwork, int *info) nogil +cdef void sgglse(int *m, int *n, int *p, s *a, int *lda, s *b, int *ldb, s *c, s *d, s *x, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_sgglse(m, n, p, a, lda, b, ldb, c, d, x, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sggqrf "BLAS_FUNC(sggqrf)"(int *n, int *m, int *p, s *a, int *lda, s *taua, s *b, int *ldb, s *taub, s *work, int *lwork, int *info) nogil +cdef void sggqrf(int *n, int *m, int *p, s *a, int *lda, s *taua, s *b, int *ldb, s *taub, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_sggqrf(n, m, p, a, lda, taua, b, ldb, taub, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sggrqf "BLAS_FUNC(sggrqf)"(int *m, int *p, int *n, s *a, int *lda, s *taua, s *b, int *ldb, s *taub, s *work, int *lwork, int *info) nogil +cdef void sggrqf(int *m, int *p, int *n, s *a, int *lda, s *taua, s *b, int *ldb, s *taub, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_sggrqf(m, p, n, a, lda, taua, b, ldb, taub, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgsvj0 "BLAS_FUNC(sgsvj0)"(char *jobv, int *m, int *n, s *a, int *lda, s *d, s *sva, int *mv, s *v, int *ldv, s *eps, s *sfmin, s *tol, int *nsweep, s *work, int *lwork, int *info) nogil +cdef void sgsvj0(char *jobv, int *m, int *n, s *a, int *lda, s *d, s *sva, int *mv, s *v, int *ldv, s *eps, s *sfmin, s *tol, int *nsweep, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_sgsvj0(jobv, m, n, a, lda, d, sva, mv, v, ldv, eps, sfmin, tol, nsweep, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgsvj1 "BLAS_FUNC(sgsvj1)"(char *jobv, int *m, int *n, int *n1, s *a, int *lda, s *d, s *sva, int *mv, s *v, int *ldv, s *eps, s *sfmin, s *tol, int *nsweep, s *work, int *lwork, int *info) nogil +cdef void sgsvj1(char *jobv, int *m, int *n, int *n1, s *a, int *lda, s *d, s *sva, int *mv, s *v, int *ldv, s *eps, s *sfmin, s *tol, int *nsweep, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_sgsvj1(jobv, m, n, n1, a, lda, d, sva, mv, v, ldv, eps, sfmin, tol, nsweep, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgtcon "BLAS_FUNC(sgtcon)"(char *norm, int *n, s *dl, s *d, s *du, s *du2, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) nogil +cdef void sgtcon(char *norm, int *n, s *dl, s *d, s *du, s *du2, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_sgtcon(norm, n, dl, d, du, du2, ipiv, anorm, rcond, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgtrfs "BLAS_FUNC(sgtrfs)"(char *trans, int *n, int *nrhs, s *dl, s *d, s *du, s *dlf, s *df, s *duf, s *du2, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) nogil +cdef void sgtrfs(char *trans, int *n, int *nrhs, s *dl, s *d, s *du, s *dlf, s *df, s *duf, s *du2, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_sgtrfs(trans, n, nrhs, dl, d, du, dlf, df, duf, du2, ipiv, b, ldb, x, ldx, ferr, berr, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgtsv "BLAS_FUNC(sgtsv)"(int *n, int *nrhs, s *dl, s *d, s *du, s *b, int *ldb, int *info) nogil +cdef void sgtsv(int *n, int *nrhs, s *dl, s *d, s *du, s *b, int *ldb, int *info) noexcept nogil: + + _fortran_sgtsv(n, nrhs, dl, d, du, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgtsvx "BLAS_FUNC(sgtsvx)"(char *fact, char *trans, int *n, int *nrhs, s *dl, s *d, s *du, s *dlf, s *df, s *duf, s *du2, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) nogil +cdef void sgtsvx(char *fact, char *trans, int *n, int *nrhs, s *dl, s *d, s *du, s *dlf, s *df, s *duf, s *du2, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_sgtsvx(fact, trans, n, nrhs, dl, d, du, dlf, df, duf, du2, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgttrf "BLAS_FUNC(sgttrf)"(int *n, s *dl, s *d, s *du, s *du2, int *ipiv, int *info) nogil +cdef void sgttrf(int *n, s *dl, s *d, s *du, s *du2, int *ipiv, int *info) noexcept nogil: + + _fortran_sgttrf(n, dl, d, du, du2, ipiv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgttrs "BLAS_FUNC(sgttrs)"(char *trans, int *n, int *nrhs, s *dl, s *d, s *du, s *du2, int *ipiv, s *b, int *ldb, int *info) nogil +cdef void sgttrs(char *trans, int *n, int *nrhs, s *dl, s *d, s *du, s *du2, int *ipiv, s *b, int *ldb, int *info) noexcept nogil: + + _fortran_sgttrs(trans, n, nrhs, dl, d, du, du2, ipiv, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sgtts2 "BLAS_FUNC(sgtts2)"(int *itrans, int *n, int *nrhs, s *dl, s *d, s *du, s *du2, int *ipiv, s *b, int *ldb) nogil +cdef void sgtts2(int *itrans, int *n, int *nrhs, s *dl, s *d, s *du, s *du2, int *ipiv, s *b, int *ldb) noexcept nogil: + + _fortran_sgtts2(itrans, n, nrhs, dl, d, du, du2, ipiv, b, ldb) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_shgeqz "BLAS_FUNC(shgeqz)"(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *t, int *ldt, s *alphar, s *alphai, s *beta, s *q, int *ldq, s *z, int *ldz, s *work, int *lwork, int *info) nogil +cdef void shgeqz(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *t, int *ldt, s *alphar, s *alphai, s *beta, s *q, int *ldq, s *z, int *ldz, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_shgeqz(job, compq, compz, n, ilo, ihi, h, ldh, t, ldt, alphar, alphai, beta, q, ldq, z, ldz, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_shsein "BLAS_FUNC(shsein)"(char *side, char *eigsrc, char *initv, bint *select, int *n, s *h, int *ldh, s *wr, s *wi, s *vl, int *ldvl, s *vr, int *ldvr, int *mm, int *m, s *work, int *ifaill, int *ifailr, int *info) nogil +cdef void shsein(char *side, char *eigsrc, char *initv, bint *select, int *n, s *h, int *ldh, s *wr, s *wi, s *vl, int *ldvl, s *vr, int *ldvr, int *mm, int *m, s *work, int *ifaill, int *ifailr, int *info) noexcept nogil: + + _fortran_shsein(side, eigsrc, initv, select, n, h, ldh, wr, wi, vl, ldvl, vr, ldvr, mm, m, work, ifaill, ifailr, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_shseqr "BLAS_FUNC(shseqr)"(char *job, char *compz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *wr, s *wi, s *z, int *ldz, s *work, int *lwork, int *info) nogil +cdef void shseqr(char *job, char *compz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *wr, s *wi, s *z, int *ldz, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_shseqr(job, compz, n, ilo, ihi, h, ldh, wr, wi, z, ldz, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slabad "BLAS_FUNC(slabad)"(s *small, s *large) nogil +cdef void slabad(s *small, s *large) noexcept nogil: + + _fortran_slabad(small, large) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slabrd "BLAS_FUNC(slabrd)"(int *m, int *n, int *nb, s *a, int *lda, s *d, s *e, s *tauq, s *taup, s *x, int *ldx, s *y, int *ldy) nogil +cdef void slabrd(int *m, int *n, int *nb, s *a, int *lda, s *d, s *e, s *tauq, s *taup, s *x, int *ldx, s *y, int *ldy) noexcept nogil: + + _fortran_slabrd(m, n, nb, a, lda, d, e, tauq, taup, x, ldx, y, ldy) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slacn2 "BLAS_FUNC(slacn2)"(int *n, s *v, s *x, int *isgn, s *est, int *kase, int *isave) nogil +cdef void slacn2(int *n, s *v, s *x, int *isgn, s *est, int *kase, int *isave) noexcept nogil: + + _fortran_slacn2(n, v, x, isgn, est, kase, isave) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slacon "BLAS_FUNC(slacon)"(int *n, s *v, s *x, int *isgn, s *est, int *kase) nogil +cdef void slacon(int *n, s *v, s *x, int *isgn, s *est, int *kase) noexcept nogil: + + _fortran_slacon(n, v, x, isgn, est, kase) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slacpy "BLAS_FUNC(slacpy)"(char *uplo, int *m, int *n, s *a, int *lda, s *b, int *ldb) nogil +cdef void slacpy(char *uplo, int *m, int *n, s *a, int *lda, s *b, int *ldb) noexcept nogil: + + _fortran_slacpy(uplo, m, n, a, lda, b, ldb) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sladiv "BLAS_FUNC(sladiv)"(s *a, s *b, s *c, s *d, s *p, s *q) nogil +cdef void sladiv(s *a, s *b, s *c, s *d, s *p, s *q) noexcept nogil: + + _fortran_sladiv(a, b, c, d, p, q) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slae2 "BLAS_FUNC(slae2)"(s *a, s *b, s *c, s *rt1, s *rt2) nogil +cdef void slae2(s *a, s *b, s *c, s *rt1, s *rt2) noexcept nogil: + + _fortran_slae2(a, b, c, rt1, rt2) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slaebz "BLAS_FUNC(slaebz)"(int *ijob, int *nitmax, int *n, int *mmax, int *minp, int *nbmin, s *abstol, s *reltol, s *pivmin, s *d, s *e, s *e2, int *nval, s *ab, s *c, int *mout, int *nab, s *work, int *iwork, int *info) nogil +cdef void slaebz(int *ijob, int *nitmax, int *n, int *mmax, int *minp, int *nbmin, s *abstol, s *reltol, s *pivmin, s *d, s *e, s *e2, int *nval, s *ab, s *c, int *mout, int *nab, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_slaebz(ijob, nitmax, n, mmax, minp, nbmin, abstol, reltol, pivmin, d, e, e2, nval, ab, c, mout, nab, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slaed0 "BLAS_FUNC(slaed0)"(int *icompq, int *qsiz, int *n, s *d, s *e, s *q, int *ldq, s *qstore, int *ldqs, s *work, int *iwork, int *info) nogil +cdef void slaed0(int *icompq, int *qsiz, int *n, s *d, s *e, s *q, int *ldq, s *qstore, int *ldqs, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_slaed0(icompq, qsiz, n, d, e, q, ldq, qstore, ldqs, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slaed1 "BLAS_FUNC(slaed1)"(int *n, s *d, s *q, int *ldq, int *indxq, s *rho, int *cutpnt, s *work, int *iwork, int *info) nogil +cdef void slaed1(int *n, s *d, s *q, int *ldq, int *indxq, s *rho, int *cutpnt, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_slaed1(n, d, q, ldq, indxq, rho, cutpnt, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slaed2 "BLAS_FUNC(slaed2)"(int *k, int *n, int *n1, s *d, s *q, int *ldq, int *indxq, s *rho, s *z, s *dlamda, s *w, s *q2, int *indx, int *indxc, int *indxp, int *coltyp, int *info) nogil +cdef void slaed2(int *k, int *n, int *n1, s *d, s *q, int *ldq, int *indxq, s *rho, s *z, s *dlamda, s *w, s *q2, int *indx, int *indxc, int *indxp, int *coltyp, int *info) noexcept nogil: + + _fortran_slaed2(k, n, n1, d, q, ldq, indxq, rho, z, dlamda, w, q2, indx, indxc, indxp, coltyp, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slaed3 "BLAS_FUNC(slaed3)"(int *k, int *n, int *n1, s *d, s *q, int *ldq, s *rho, s *dlamda, s *q2, int *indx, int *ctot, s *w, s *s, int *info) nogil +cdef void slaed3(int *k, int *n, int *n1, s *d, s *q, int *ldq, s *rho, s *dlamda, s *q2, int *indx, int *ctot, s *w, s *s, int *info) noexcept nogil: + + _fortran_slaed3(k, n, n1, d, q, ldq, rho, dlamda, q2, indx, ctot, w, s, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slaed4 "BLAS_FUNC(slaed4)"(int *n, int *i, s *d, s *z, s *delta, s *rho, s *dlam, int *info) nogil +cdef void slaed4(int *n, int *i, s *d, s *z, s *delta, s *rho, s *dlam, int *info) noexcept nogil: + + _fortran_slaed4(n, i, d, z, delta, rho, dlam, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slaed5 "BLAS_FUNC(slaed5)"(int *i, s *d, s *z, s *delta, s *rho, s *dlam) nogil +cdef void slaed5(int *i, s *d, s *z, s *delta, s *rho, s *dlam) noexcept nogil: + + _fortran_slaed5(i, d, z, delta, rho, dlam) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slaed6 "BLAS_FUNC(slaed6)"(int *kniter, bint *orgati, s *rho, s *d, s *z, s *finit, s *tau, int *info) nogil +cdef void slaed6(int *kniter, bint *orgati, s *rho, s *d, s *z, s *finit, s *tau, int *info) noexcept nogil: + + _fortran_slaed6(kniter, orgati, rho, d, z, finit, tau, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slaed7 "BLAS_FUNC(slaed7)"(int *icompq, int *n, int *qsiz, int *tlvls, int *curlvl, int *curpbm, s *d, s *q, int *ldq, int *indxq, s *rho, int *cutpnt, s *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, s *givnum, s *work, int *iwork, int *info) nogil +cdef void slaed7(int *icompq, int *n, int *qsiz, int *tlvls, int *curlvl, int *curpbm, s *d, s *q, int *ldq, int *indxq, s *rho, int *cutpnt, s *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, s *givnum, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_slaed7(icompq, n, qsiz, tlvls, curlvl, curpbm, d, q, ldq, indxq, rho, cutpnt, qstore, qptr, prmptr, perm, givptr, givcol, givnum, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slaed8 "BLAS_FUNC(slaed8)"(int *icompq, int *k, int *n, int *qsiz, s *d, s *q, int *ldq, int *indxq, s *rho, int *cutpnt, s *z, s *dlamda, s *q2, int *ldq2, s *w, int *perm, int *givptr, int *givcol, s *givnum, int *indxp, int *indx, int *info) nogil +cdef void slaed8(int *icompq, int *k, int *n, int *qsiz, s *d, s *q, int *ldq, int *indxq, s *rho, int *cutpnt, s *z, s *dlamda, s *q2, int *ldq2, s *w, int *perm, int *givptr, int *givcol, s *givnum, int *indxp, int *indx, int *info) noexcept nogil: + + _fortran_slaed8(icompq, k, n, qsiz, d, q, ldq, indxq, rho, cutpnt, z, dlamda, q2, ldq2, w, perm, givptr, givcol, givnum, indxp, indx, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slaed9 "BLAS_FUNC(slaed9)"(int *k, int *kstart, int *kstop, int *n, s *d, s *q, int *ldq, s *rho, s *dlamda, s *w, s *s, int *lds, int *info) nogil +cdef void slaed9(int *k, int *kstart, int *kstop, int *n, s *d, s *q, int *ldq, s *rho, s *dlamda, s *w, s *s, int *lds, int *info) noexcept nogil: + + _fortran_slaed9(k, kstart, kstop, n, d, q, ldq, rho, dlamda, w, s, lds, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slaeda "BLAS_FUNC(slaeda)"(int *n, int *tlvls, int *curlvl, int *curpbm, int *prmptr, int *perm, int *givptr, int *givcol, s *givnum, s *q, int *qptr, s *z, s *ztemp, int *info) nogil +cdef void slaeda(int *n, int *tlvls, int *curlvl, int *curpbm, int *prmptr, int *perm, int *givptr, int *givcol, s *givnum, s *q, int *qptr, s *z, s *ztemp, int *info) noexcept nogil: + + _fortran_slaeda(n, tlvls, curlvl, curpbm, prmptr, perm, givptr, givcol, givnum, q, qptr, z, ztemp, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slaein "BLAS_FUNC(slaein)"(bint *rightv, bint *noinit, int *n, s *h, int *ldh, s *wr, s *wi, s *vr, s *vi, s *b, int *ldb, s *work, s *eps3, s *smlnum, s *bignum, int *info) nogil +cdef void slaein(bint *rightv, bint *noinit, int *n, s *h, int *ldh, s *wr, s *wi, s *vr, s *vi, s *b, int *ldb, s *work, s *eps3, s *smlnum, s *bignum, int *info) noexcept nogil: + + _fortran_slaein(rightv, noinit, n, h, ldh, wr, wi, vr, vi, b, ldb, work, eps3, smlnum, bignum, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slaev2 "BLAS_FUNC(slaev2)"(s *a, s *b, s *c, s *rt1, s *rt2, s *cs1, s *sn1) nogil +cdef void slaev2(s *a, s *b, s *c, s *rt1, s *rt2, s *cs1, s *sn1) noexcept nogil: + + _fortran_slaev2(a, b, c, rt1, rt2, cs1, sn1) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slaexc "BLAS_FUNC(slaexc)"(bint *wantq, int *n, s *t, int *ldt, s *q, int *ldq, int *j1, int *n1, int *n2, s *work, int *info) nogil +cdef void slaexc(bint *wantq, int *n, s *t, int *ldt, s *q, int *ldq, int *j1, int *n1, int *n2, s *work, int *info) noexcept nogil: + + _fortran_slaexc(wantq, n, t, ldt, q, ldq, j1, n1, n2, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slag2 "BLAS_FUNC(slag2)"(s *a, int *lda, s *b, int *ldb, s *safmin, s *scale1, s *scale2, s *wr1, s *wr2, s *wi) nogil +cdef void slag2(s *a, int *lda, s *b, int *ldb, s *safmin, s *scale1, s *scale2, s *wr1, s *wr2, s *wi) noexcept nogil: + + _fortran_slag2(a, lda, b, ldb, safmin, scale1, scale2, wr1, wr2, wi) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slag2d "BLAS_FUNC(slag2d)"(int *m, int *n, s *sa, int *ldsa, d *a, int *lda, int *info) nogil +cdef void slag2d(int *m, int *n, s *sa, int *ldsa, d *a, int *lda, int *info) noexcept nogil: + + _fortran_slag2d(m, n, sa, ldsa, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slags2 "BLAS_FUNC(slags2)"(bint *upper, s *a1, s *a2, s *a3, s *b1, s *b2, s *b3, s *csu, s *snu, s *csv, s *snv, s *csq, s *snq) nogil +cdef void slags2(bint *upper, s *a1, s *a2, s *a3, s *b1, s *b2, s *b3, s *csu, s *snu, s *csv, s *snv, s *csq, s *snq) noexcept nogil: + + _fortran_slags2(upper, a1, a2, a3, b1, b2, b3, csu, snu, csv, snv, csq, snq) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slagtf "BLAS_FUNC(slagtf)"(int *n, s *a, s *lambda_, s *b, s *c, s *tol, s *d, int *in_, int *info) nogil +cdef void slagtf(int *n, s *a, s *lambda_, s *b, s *c, s *tol, s *d, int *in_, int *info) noexcept nogil: + + _fortran_slagtf(n, a, lambda_, b, c, tol, d, in_, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slagtm "BLAS_FUNC(slagtm)"(char *trans, int *n, int *nrhs, s *alpha, s *dl, s *d, s *du, s *x, int *ldx, s *beta, s *b, int *ldb) nogil +cdef void slagtm(char *trans, int *n, int *nrhs, s *alpha, s *dl, s *d, s *du, s *x, int *ldx, s *beta, s *b, int *ldb) noexcept nogil: + + _fortran_slagtm(trans, n, nrhs, alpha, dl, d, du, x, ldx, beta, b, ldb) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slagts "BLAS_FUNC(slagts)"(int *job, int *n, s *a, s *b, s *c, s *d, int *in_, s *y, s *tol, int *info) nogil +cdef void slagts(int *job, int *n, s *a, s *b, s *c, s *d, int *in_, s *y, s *tol, int *info) noexcept nogil: + + _fortran_slagts(job, n, a, b, c, d, in_, y, tol, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slagv2 "BLAS_FUNC(slagv2)"(s *a, int *lda, s *b, int *ldb, s *alphar, s *alphai, s *beta, s *csl, s *snl, s *csr, s *snr) nogil +cdef void slagv2(s *a, int *lda, s *b, int *ldb, s *alphar, s *alphai, s *beta, s *csl, s *snl, s *csr, s *snr) noexcept nogil: + + _fortran_slagv2(a, lda, b, ldb, alphar, alphai, beta, csl, snl, csr, snr) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slahqr "BLAS_FUNC(slahqr)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *wr, s *wi, int *iloz, int *ihiz, s *z, int *ldz, int *info) nogil +cdef void slahqr(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *wr, s *wi, int *iloz, int *ihiz, s *z, int *ldz, int *info) noexcept nogil: + + _fortran_slahqr(wantt, wantz, n, ilo, ihi, h, ldh, wr, wi, iloz, ihiz, z, ldz, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slahr2 "BLAS_FUNC(slahr2)"(int *n, int *k, int *nb, s *a, int *lda, s *tau, s *t, int *ldt, s *y, int *ldy) nogil +cdef void slahr2(int *n, int *k, int *nb, s *a, int *lda, s *tau, s *t, int *ldt, s *y, int *ldy) noexcept nogil: + + _fortran_slahr2(n, k, nb, a, lda, tau, t, ldt, y, ldy) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slaic1 "BLAS_FUNC(slaic1)"(int *job, int *j, s *x, s *sest, s *w, s *gamma, s *sestpr, s *s, s *c) nogil +cdef void slaic1(int *job, int *j, s *x, s *sest, s *w, s *gamma, s *sestpr, s *s, s *c) noexcept nogil: + + _fortran_slaic1(job, j, x, sest, w, gamma, sestpr, s, c) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slaln2 "BLAS_FUNC(slaln2)"(bint *ltrans, int *na, int *nw, s *smin, s *ca, s *a, int *lda, s *d1, s *d2, s *b, int *ldb, s *wr, s *wi, s *x, int *ldx, s *scale, s *xnorm, int *info) nogil +cdef void slaln2(bint *ltrans, int *na, int *nw, s *smin, s *ca, s *a, int *lda, s *d1, s *d2, s *b, int *ldb, s *wr, s *wi, s *x, int *ldx, s *scale, s *xnorm, int *info) noexcept nogil: + + _fortran_slaln2(ltrans, na, nw, smin, ca, a, lda, d1, d2, b, ldb, wr, wi, x, ldx, scale, xnorm, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slals0 "BLAS_FUNC(slals0)"(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, s *b, int *ldb, s *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, s *givnum, int *ldgnum, s *poles, s *difl, s *difr, s *z, int *k, s *c, s *s, s *work, int *info) nogil +cdef void slals0(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, s *b, int *ldb, s *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, s *givnum, int *ldgnum, s *poles, s *difl, s *difr, s *z, int *k, s *c, s *s, s *work, int *info) noexcept nogil: + + _fortran_slals0(icompq, nl, nr, sqre, nrhs, b, ldb, bx, ldbx, perm, givptr, givcol, ldgcol, givnum, ldgnum, poles, difl, difr, z, k, c, s, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slalsa "BLAS_FUNC(slalsa)"(int *icompq, int *smlsiz, int *n, int *nrhs, s *b, int *ldb, s *bx, int *ldbx, s *u, int *ldu, s *vt, int *k, s *difl, s *difr, s *z, s *poles, int *givptr, int *givcol, int *ldgcol, int *perm, s *givnum, s *c, s *s, s *work, int *iwork, int *info) nogil +cdef void slalsa(int *icompq, int *smlsiz, int *n, int *nrhs, s *b, int *ldb, s *bx, int *ldbx, s *u, int *ldu, s *vt, int *k, s *difl, s *difr, s *z, s *poles, int *givptr, int *givcol, int *ldgcol, int *perm, s *givnum, s *c, s *s, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_slalsa(icompq, smlsiz, n, nrhs, b, ldb, bx, ldbx, u, ldu, vt, k, difl, difr, z, poles, givptr, givcol, ldgcol, perm, givnum, c, s, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slalsd "BLAS_FUNC(slalsd)"(char *uplo, int *smlsiz, int *n, int *nrhs, s *d, s *e, s *b, int *ldb, s *rcond, int *rank, s *work, int *iwork, int *info) nogil +cdef void slalsd(char *uplo, int *smlsiz, int *n, int *nrhs, s *d, s *e, s *b, int *ldb, s *rcond, int *rank, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_slalsd(uplo, smlsiz, n, nrhs, d, e, b, ldb, rcond, rank, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + s _fortran_slamch "BLAS_FUNC(slamch)"(char *cmach) nogil +cdef s slamch(char *cmach) noexcept nogil: + + return _fortran_slamch(cmach) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slamrg "BLAS_FUNC(slamrg)"(int *n1, int *n2, s *a, int *strd1, int *strd2, int *index_bn) nogil +cdef void slamrg(int *n1, int *n2, s *a, int *strd1, int *strd2, int *index_bn) noexcept nogil: + + _fortran_slamrg(n1, n2, a, strd1, strd2, index_bn) + + +cdef extern from "_lapack_subroutines.h": + s _fortran_slangb "BLAS_FUNC(slangb)"(char *norm, int *n, int *kl, int *ku, s *ab, int *ldab, s *work) nogil +cdef s slangb(char *norm, int *n, int *kl, int *ku, s *ab, int *ldab, s *work) noexcept nogil: + + return _fortran_slangb(norm, n, kl, ku, ab, ldab, work) + + +cdef extern from "_lapack_subroutines.h": + s _fortran_slange "BLAS_FUNC(slange)"(char *norm, int *m, int *n, s *a, int *lda, s *work) nogil +cdef s slange(char *norm, int *m, int *n, s *a, int *lda, s *work) noexcept nogil: + + return _fortran_slange(norm, m, n, a, lda, work) + + +cdef extern from "_lapack_subroutines.h": + s _fortran_slangt "BLAS_FUNC(slangt)"(char *norm, int *n, s *dl, s *d, s *du) nogil +cdef s slangt(char *norm, int *n, s *dl, s *d, s *du) noexcept nogil: + + return _fortran_slangt(norm, n, dl, d, du) + + +cdef extern from "_lapack_subroutines.h": + s _fortran_slanhs "BLAS_FUNC(slanhs)"(char *norm, int *n, s *a, int *lda, s *work) nogil +cdef s slanhs(char *norm, int *n, s *a, int *lda, s *work) noexcept nogil: + + return _fortran_slanhs(norm, n, a, lda, work) + + +cdef extern from "_lapack_subroutines.h": + s _fortran_slansb "BLAS_FUNC(slansb)"(char *norm, char *uplo, int *n, int *k, s *ab, int *ldab, s *work) nogil +cdef s slansb(char *norm, char *uplo, int *n, int *k, s *ab, int *ldab, s *work) noexcept nogil: + + return _fortran_slansb(norm, uplo, n, k, ab, ldab, work) + + +cdef extern from "_lapack_subroutines.h": + s _fortran_slansf "BLAS_FUNC(slansf)"(char *norm, char *transr, char *uplo, int *n, s *a, s *work) nogil +cdef s slansf(char *norm, char *transr, char *uplo, int *n, s *a, s *work) noexcept nogil: + + return _fortran_slansf(norm, transr, uplo, n, a, work) + + +cdef extern from "_lapack_subroutines.h": + s _fortran_slansp "BLAS_FUNC(slansp)"(char *norm, char *uplo, int *n, s *ap, s *work) nogil +cdef s slansp(char *norm, char *uplo, int *n, s *ap, s *work) noexcept nogil: + + return _fortran_slansp(norm, uplo, n, ap, work) + + +cdef extern from "_lapack_subroutines.h": + s _fortran_slanst "BLAS_FUNC(slanst)"(char *norm, int *n, s *d, s *e) nogil +cdef s slanst(char *norm, int *n, s *d, s *e) noexcept nogil: + + return _fortran_slanst(norm, n, d, e) + + +cdef extern from "_lapack_subroutines.h": + s _fortran_slansy "BLAS_FUNC(slansy)"(char *norm, char *uplo, int *n, s *a, int *lda, s *work) nogil +cdef s slansy(char *norm, char *uplo, int *n, s *a, int *lda, s *work) noexcept nogil: + + return _fortran_slansy(norm, uplo, n, a, lda, work) + + +cdef extern from "_lapack_subroutines.h": + s _fortran_slantb "BLAS_FUNC(slantb)"(char *norm, char *uplo, char *diag, int *n, int *k, s *ab, int *ldab, s *work) nogil +cdef s slantb(char *norm, char *uplo, char *diag, int *n, int *k, s *ab, int *ldab, s *work) noexcept nogil: + + return _fortran_slantb(norm, uplo, diag, n, k, ab, ldab, work) + + +cdef extern from "_lapack_subroutines.h": + s _fortran_slantp "BLAS_FUNC(slantp)"(char *norm, char *uplo, char *diag, int *n, s *ap, s *work) nogil +cdef s slantp(char *norm, char *uplo, char *diag, int *n, s *ap, s *work) noexcept nogil: + + return _fortran_slantp(norm, uplo, diag, n, ap, work) + + +cdef extern from "_lapack_subroutines.h": + s _fortran_slantr "BLAS_FUNC(slantr)"(char *norm, char *uplo, char *diag, int *m, int *n, s *a, int *lda, s *work) nogil +cdef s slantr(char *norm, char *uplo, char *diag, int *m, int *n, s *a, int *lda, s *work) noexcept nogil: + + return _fortran_slantr(norm, uplo, diag, m, n, a, lda, work) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slanv2 "BLAS_FUNC(slanv2)"(s *a, s *b, s *c, s *d, s *rt1r, s *rt1i, s *rt2r, s *rt2i, s *cs, s *sn) nogil +cdef void slanv2(s *a, s *b, s *c, s *d, s *rt1r, s *rt1i, s *rt2r, s *rt2i, s *cs, s *sn) noexcept nogil: + + _fortran_slanv2(a, b, c, d, rt1r, rt1i, rt2r, rt2i, cs, sn) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slapll "BLAS_FUNC(slapll)"(int *n, s *x, int *incx, s *y, int *incy, s *ssmin) nogil +cdef void slapll(int *n, s *x, int *incx, s *y, int *incy, s *ssmin) noexcept nogil: + + _fortran_slapll(n, x, incx, y, incy, ssmin) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slapmr "BLAS_FUNC(slapmr)"(bint *forwrd, int *m, int *n, s *x, int *ldx, int *k) nogil +cdef void slapmr(bint *forwrd, int *m, int *n, s *x, int *ldx, int *k) noexcept nogil: + + _fortran_slapmr(forwrd, m, n, x, ldx, k) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slapmt "BLAS_FUNC(slapmt)"(bint *forwrd, int *m, int *n, s *x, int *ldx, int *k) nogil +cdef void slapmt(bint *forwrd, int *m, int *n, s *x, int *ldx, int *k) noexcept nogil: + + _fortran_slapmt(forwrd, m, n, x, ldx, k) + + +cdef extern from "_lapack_subroutines.h": + s _fortran_slapy2 "BLAS_FUNC(slapy2)"(s *x, s *y) nogil +cdef s slapy2(s *x, s *y) noexcept nogil: + + return _fortran_slapy2(x, y) + + +cdef extern from "_lapack_subroutines.h": + s _fortran_slapy3 "BLAS_FUNC(slapy3)"(s *x, s *y, s *z) nogil +cdef s slapy3(s *x, s *y, s *z) noexcept nogil: + + return _fortran_slapy3(x, y, z) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slaqgb "BLAS_FUNC(slaqgb)"(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) nogil +cdef void slaqgb(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) noexcept nogil: + + _fortran_slaqgb(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, equed) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slaqge "BLAS_FUNC(slaqge)"(int *m, int *n, s *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) nogil +cdef void slaqge(int *m, int *n, s *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) noexcept nogil: + + _fortran_slaqge(m, n, a, lda, r, c, rowcnd, colcnd, amax, equed) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slaqp2 "BLAS_FUNC(slaqp2)"(int *m, int *n, int *offset, s *a, int *lda, int *jpvt, s *tau, s *vn1, s *vn2, s *work) nogil +cdef void slaqp2(int *m, int *n, int *offset, s *a, int *lda, int *jpvt, s *tau, s *vn1, s *vn2, s *work) noexcept nogil: + + _fortran_slaqp2(m, n, offset, a, lda, jpvt, tau, vn1, vn2, work) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slaqps "BLAS_FUNC(slaqps)"(int *m, int *n, int *offset, int *nb, int *kb, s *a, int *lda, int *jpvt, s *tau, s *vn1, s *vn2, s *auxv, s *f, int *ldf) nogil +cdef void slaqps(int *m, int *n, int *offset, int *nb, int *kb, s *a, int *lda, int *jpvt, s *tau, s *vn1, s *vn2, s *auxv, s *f, int *ldf) noexcept nogil: + + _fortran_slaqps(m, n, offset, nb, kb, a, lda, jpvt, tau, vn1, vn2, auxv, f, ldf) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slaqr0 "BLAS_FUNC(slaqr0)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *wr, s *wi, int *iloz, int *ihiz, s *z, int *ldz, s *work, int *lwork, int *info) nogil +cdef void slaqr0(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *wr, s *wi, int *iloz, int *ihiz, s *z, int *ldz, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_slaqr0(wantt, wantz, n, ilo, ihi, h, ldh, wr, wi, iloz, ihiz, z, ldz, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slaqr1 "BLAS_FUNC(slaqr1)"(int *n, s *h, int *ldh, s *sr1, s *si1, s *sr2, s *si2, s *v) nogil +cdef void slaqr1(int *n, s *h, int *ldh, s *sr1, s *si1, s *sr2, s *si2, s *v) noexcept nogil: + + _fortran_slaqr1(n, h, ldh, sr1, si1, sr2, si2, v) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slaqr2 "BLAS_FUNC(slaqr2)"(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, s *h, int *ldh, int *iloz, int *ihiz, s *z, int *ldz, int *ns, int *nd, s *sr, s *si, s *v, int *ldv, int *nh, s *t, int *ldt, int *nv, s *wv, int *ldwv, s *work, int *lwork) nogil +cdef void slaqr2(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, s *h, int *ldh, int *iloz, int *ihiz, s *z, int *ldz, int *ns, int *nd, s *sr, s *si, s *v, int *ldv, int *nh, s *t, int *ldt, int *nv, s *wv, int *ldwv, s *work, int *lwork) noexcept nogil: + + _fortran_slaqr2(wantt, wantz, n, ktop, kbot, nw, h, ldh, iloz, ihiz, z, ldz, ns, nd, sr, si, v, ldv, nh, t, ldt, nv, wv, ldwv, work, lwork) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slaqr3 "BLAS_FUNC(slaqr3)"(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, s *h, int *ldh, int *iloz, int *ihiz, s *z, int *ldz, int *ns, int *nd, s *sr, s *si, s *v, int *ldv, int *nh, s *t, int *ldt, int *nv, s *wv, int *ldwv, s *work, int *lwork) nogil +cdef void slaqr3(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, s *h, int *ldh, int *iloz, int *ihiz, s *z, int *ldz, int *ns, int *nd, s *sr, s *si, s *v, int *ldv, int *nh, s *t, int *ldt, int *nv, s *wv, int *ldwv, s *work, int *lwork) noexcept nogil: + + _fortran_slaqr3(wantt, wantz, n, ktop, kbot, nw, h, ldh, iloz, ihiz, z, ldz, ns, nd, sr, si, v, ldv, nh, t, ldt, nv, wv, ldwv, work, lwork) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slaqr4 "BLAS_FUNC(slaqr4)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *wr, s *wi, int *iloz, int *ihiz, s *z, int *ldz, s *work, int *lwork, int *info) nogil +cdef void slaqr4(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *wr, s *wi, int *iloz, int *ihiz, s *z, int *ldz, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_slaqr4(wantt, wantz, n, ilo, ihi, h, ldh, wr, wi, iloz, ihiz, z, ldz, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slaqr5 "BLAS_FUNC(slaqr5)"(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, s *sr, s *si, s *h, int *ldh, int *iloz, int *ihiz, s *z, int *ldz, s *v, int *ldv, s *u, int *ldu, int *nv, s *wv, int *ldwv, int *nh, s *wh, int *ldwh) nogil +cdef void slaqr5(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, s *sr, s *si, s *h, int *ldh, int *iloz, int *ihiz, s *z, int *ldz, s *v, int *ldv, s *u, int *ldu, int *nv, s *wv, int *ldwv, int *nh, s *wh, int *ldwh) noexcept nogil: + + _fortran_slaqr5(wantt, wantz, kacc22, n, ktop, kbot, nshfts, sr, si, h, ldh, iloz, ihiz, z, ldz, v, ldv, u, ldu, nv, wv, ldwv, nh, wh, ldwh) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slaqsb "BLAS_FUNC(slaqsb)"(char *uplo, int *n, int *kd, s *ab, int *ldab, s *s, s *scond, s *amax, char *equed) nogil +cdef void slaqsb(char *uplo, int *n, int *kd, s *ab, int *ldab, s *s, s *scond, s *amax, char *equed) noexcept nogil: + + _fortran_slaqsb(uplo, n, kd, ab, ldab, s, scond, amax, equed) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slaqsp "BLAS_FUNC(slaqsp)"(char *uplo, int *n, s *ap, s *s, s *scond, s *amax, char *equed) nogil +cdef void slaqsp(char *uplo, int *n, s *ap, s *s, s *scond, s *amax, char *equed) noexcept nogil: + + _fortran_slaqsp(uplo, n, ap, s, scond, amax, equed) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slaqsy "BLAS_FUNC(slaqsy)"(char *uplo, int *n, s *a, int *lda, s *s, s *scond, s *amax, char *equed) nogil +cdef void slaqsy(char *uplo, int *n, s *a, int *lda, s *s, s *scond, s *amax, char *equed) noexcept nogil: + + _fortran_slaqsy(uplo, n, a, lda, s, scond, amax, equed) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slaqtr "BLAS_FUNC(slaqtr)"(bint *ltran, bint *lreal, int *n, s *t, int *ldt, s *b, s *w, s *scale, s *x, s *work, int *info) nogil +cdef void slaqtr(bint *ltran, bint *lreal, int *n, s *t, int *ldt, s *b, s *w, s *scale, s *x, s *work, int *info) noexcept nogil: + + _fortran_slaqtr(ltran, lreal, n, t, ldt, b, w, scale, x, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slar1v "BLAS_FUNC(slar1v)"(int *n, int *b1, int *bn, s *lambda_, s *d, s *l, s *ld, s *lld, s *pivmin, s *gaptol, s *z, bint *wantnc, int *negcnt, s *ztz, s *mingma, int *r, int *isuppz, s *nrminv, s *resid, s *rqcorr, s *work) nogil +cdef void slar1v(int *n, int *b1, int *bn, s *lambda_, s *d, s *l, s *ld, s *lld, s *pivmin, s *gaptol, s *z, bint *wantnc, int *negcnt, s *ztz, s *mingma, int *r, int *isuppz, s *nrminv, s *resid, s *rqcorr, s *work) noexcept nogil: + + _fortran_slar1v(n, b1, bn, lambda_, d, l, ld, lld, pivmin, gaptol, z, wantnc, negcnt, ztz, mingma, r, isuppz, nrminv, resid, rqcorr, work) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slar2v "BLAS_FUNC(slar2v)"(int *n, s *x, s *y, s *z, int *incx, s *c, s *s, int *incc) nogil +cdef void slar2v(int *n, s *x, s *y, s *z, int *incx, s *c, s *s, int *incc) noexcept nogil: + + _fortran_slar2v(n, x, y, z, incx, c, s, incc) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slarf "BLAS_FUNC(slarf)"(char *side, int *m, int *n, s *v, int *incv, s *tau, s *c, int *ldc, s *work) nogil +cdef void slarf(char *side, int *m, int *n, s *v, int *incv, s *tau, s *c, int *ldc, s *work) noexcept nogil: + + _fortran_slarf(side, m, n, v, incv, tau, c, ldc, work) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slarfb "BLAS_FUNC(slarfb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, s *v, int *ldv, s *t, int *ldt, s *c, int *ldc, s *work, int *ldwork) nogil +cdef void slarfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, s *v, int *ldv, s *t, int *ldt, s *c, int *ldc, s *work, int *ldwork) noexcept nogil: + + _fortran_slarfb(side, trans, direct, storev, m, n, k, v, ldv, t, ldt, c, ldc, work, ldwork) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slarfg "BLAS_FUNC(slarfg)"(int *n, s *alpha, s *x, int *incx, s *tau) nogil +cdef void slarfg(int *n, s *alpha, s *x, int *incx, s *tau) noexcept nogil: + + _fortran_slarfg(n, alpha, x, incx, tau) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slarfgp "BLAS_FUNC(slarfgp)"(int *n, s *alpha, s *x, int *incx, s *tau) nogil +cdef void slarfgp(int *n, s *alpha, s *x, int *incx, s *tau) noexcept nogil: + + _fortran_slarfgp(n, alpha, x, incx, tau) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slarft "BLAS_FUNC(slarft)"(char *direct, char *storev, int *n, int *k, s *v, int *ldv, s *tau, s *t, int *ldt) nogil +cdef void slarft(char *direct, char *storev, int *n, int *k, s *v, int *ldv, s *tau, s *t, int *ldt) noexcept nogil: + + _fortran_slarft(direct, storev, n, k, v, ldv, tau, t, ldt) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slarfx "BLAS_FUNC(slarfx)"(char *side, int *m, int *n, s *v, s *tau, s *c, int *ldc, s *work) nogil +cdef void slarfx(char *side, int *m, int *n, s *v, s *tau, s *c, int *ldc, s *work) noexcept nogil: + + _fortran_slarfx(side, m, n, v, tau, c, ldc, work) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slargv "BLAS_FUNC(slargv)"(int *n, s *x, int *incx, s *y, int *incy, s *c, int *incc) nogil +cdef void slargv(int *n, s *x, int *incx, s *y, int *incy, s *c, int *incc) noexcept nogil: + + _fortran_slargv(n, x, incx, y, incy, c, incc) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slarnv "BLAS_FUNC(slarnv)"(int *idist, int *iseed, int *n, s *x) nogil +cdef void slarnv(int *idist, int *iseed, int *n, s *x) noexcept nogil: + + _fortran_slarnv(idist, iseed, n, x) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slarra "BLAS_FUNC(slarra)"(int *n, s *d, s *e, s *e2, s *spltol, s *tnrm, int *nsplit, int *isplit, int *info) nogil +cdef void slarra(int *n, s *d, s *e, s *e2, s *spltol, s *tnrm, int *nsplit, int *isplit, int *info) noexcept nogil: + + _fortran_slarra(n, d, e, e2, spltol, tnrm, nsplit, isplit, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slarrb "BLAS_FUNC(slarrb)"(int *n, s *d, s *lld, int *ifirst, int *ilast, s *rtol1, s *rtol2, int *offset, s *w, s *wgap, s *werr, s *work, int *iwork, s *pivmin, s *spdiam, int *twist, int *info) nogil +cdef void slarrb(int *n, s *d, s *lld, int *ifirst, int *ilast, s *rtol1, s *rtol2, int *offset, s *w, s *wgap, s *werr, s *work, int *iwork, s *pivmin, s *spdiam, int *twist, int *info) noexcept nogil: + + _fortran_slarrb(n, d, lld, ifirst, ilast, rtol1, rtol2, offset, w, wgap, werr, work, iwork, pivmin, spdiam, twist, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slarrc "BLAS_FUNC(slarrc)"(char *jobt, int *n, s *vl, s *vu, s *d, s *e, s *pivmin, int *eigcnt, int *lcnt, int *rcnt, int *info) nogil +cdef void slarrc(char *jobt, int *n, s *vl, s *vu, s *d, s *e, s *pivmin, int *eigcnt, int *lcnt, int *rcnt, int *info) noexcept nogil: + + _fortran_slarrc(jobt, n, vl, vu, d, e, pivmin, eigcnt, lcnt, rcnt, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slarrd "BLAS_FUNC(slarrd)"(char *range, char *order, int *n, s *vl, s *vu, int *il, int *iu, s *gers, s *reltol, s *d, s *e, s *e2, s *pivmin, int *nsplit, int *isplit, int *m, s *w, s *werr, s *wl, s *wu, int *iblock, int *indexw, s *work, int *iwork, int *info) nogil +cdef void slarrd(char *range, char *order, int *n, s *vl, s *vu, int *il, int *iu, s *gers, s *reltol, s *d, s *e, s *e2, s *pivmin, int *nsplit, int *isplit, int *m, s *w, s *werr, s *wl, s *wu, int *iblock, int *indexw, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_slarrd(range, order, n, vl, vu, il, iu, gers, reltol, d, e, e2, pivmin, nsplit, isplit, m, w, werr, wl, wu, iblock, indexw, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slarre "BLAS_FUNC(slarre)"(char *range, int *n, s *vl, s *vu, int *il, int *iu, s *d, s *e, s *e2, s *rtol1, s *rtol2, s *spltol, int *nsplit, int *isplit, int *m, s *w, s *werr, s *wgap, int *iblock, int *indexw, s *gers, s *pivmin, s *work, int *iwork, int *info) nogil +cdef void slarre(char *range, int *n, s *vl, s *vu, int *il, int *iu, s *d, s *e, s *e2, s *rtol1, s *rtol2, s *spltol, int *nsplit, int *isplit, int *m, s *w, s *werr, s *wgap, int *iblock, int *indexw, s *gers, s *pivmin, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_slarre(range, n, vl, vu, il, iu, d, e, e2, rtol1, rtol2, spltol, nsplit, isplit, m, w, werr, wgap, iblock, indexw, gers, pivmin, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slarrf "BLAS_FUNC(slarrf)"(int *n, s *d, s *l, s *ld, int *clstrt, int *clend, s *w, s *wgap, s *werr, s *spdiam, s *clgapl, s *clgapr, s *pivmin, s *sigma, s *dplus, s *lplus, s *work, int *info) nogil +cdef void slarrf(int *n, s *d, s *l, s *ld, int *clstrt, int *clend, s *w, s *wgap, s *werr, s *spdiam, s *clgapl, s *clgapr, s *pivmin, s *sigma, s *dplus, s *lplus, s *work, int *info) noexcept nogil: + + _fortran_slarrf(n, d, l, ld, clstrt, clend, w, wgap, werr, spdiam, clgapl, clgapr, pivmin, sigma, dplus, lplus, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slarrj "BLAS_FUNC(slarrj)"(int *n, s *d, s *e2, int *ifirst, int *ilast, s *rtol, int *offset, s *w, s *werr, s *work, int *iwork, s *pivmin, s *spdiam, int *info) nogil +cdef void slarrj(int *n, s *d, s *e2, int *ifirst, int *ilast, s *rtol, int *offset, s *w, s *werr, s *work, int *iwork, s *pivmin, s *spdiam, int *info) noexcept nogil: + + _fortran_slarrj(n, d, e2, ifirst, ilast, rtol, offset, w, werr, work, iwork, pivmin, spdiam, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slarrk "BLAS_FUNC(slarrk)"(int *n, int *iw, s *gl, s *gu, s *d, s *e2, s *pivmin, s *reltol, s *w, s *werr, int *info) nogil +cdef void slarrk(int *n, int *iw, s *gl, s *gu, s *d, s *e2, s *pivmin, s *reltol, s *w, s *werr, int *info) noexcept nogil: + + _fortran_slarrk(n, iw, gl, gu, d, e2, pivmin, reltol, w, werr, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slarrr "BLAS_FUNC(slarrr)"(int *n, s *d, s *e, int *info) nogil +cdef void slarrr(int *n, s *d, s *e, int *info) noexcept nogil: + + _fortran_slarrr(n, d, e, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slarrv "BLAS_FUNC(slarrv)"(int *n, s *vl, s *vu, s *d, s *l, s *pivmin, int *isplit, int *m, int *dol, int *dou, s *minrgp, s *rtol1, s *rtol2, s *w, s *werr, s *wgap, int *iblock, int *indexw, s *gers, s *z, int *ldz, int *isuppz, s *work, int *iwork, int *info) nogil +cdef void slarrv(int *n, s *vl, s *vu, s *d, s *l, s *pivmin, int *isplit, int *m, int *dol, int *dou, s *minrgp, s *rtol1, s *rtol2, s *w, s *werr, s *wgap, int *iblock, int *indexw, s *gers, s *z, int *ldz, int *isuppz, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_slarrv(n, vl, vu, d, l, pivmin, isplit, m, dol, dou, minrgp, rtol1, rtol2, w, werr, wgap, iblock, indexw, gers, z, ldz, isuppz, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slartg "BLAS_FUNC(slartg)"(s *f, s *g, s *cs, s *sn, s *r) nogil +cdef void slartg(s *f, s *g, s *cs, s *sn, s *r) noexcept nogil: + + _fortran_slartg(f, g, cs, sn, r) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slartgp "BLAS_FUNC(slartgp)"(s *f, s *g, s *cs, s *sn, s *r) nogil +cdef void slartgp(s *f, s *g, s *cs, s *sn, s *r) noexcept nogil: + + _fortran_slartgp(f, g, cs, sn, r) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slartgs "BLAS_FUNC(slartgs)"(s *x, s *y, s *sigma, s *cs, s *sn) nogil +cdef void slartgs(s *x, s *y, s *sigma, s *cs, s *sn) noexcept nogil: + + _fortran_slartgs(x, y, sigma, cs, sn) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slartv "BLAS_FUNC(slartv)"(int *n, s *x, int *incx, s *y, int *incy, s *c, s *s, int *incc) nogil +cdef void slartv(int *n, s *x, int *incx, s *y, int *incy, s *c, s *s, int *incc) noexcept nogil: + + _fortran_slartv(n, x, incx, y, incy, c, s, incc) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slaruv "BLAS_FUNC(slaruv)"(int *iseed, int *n, s *x) nogil +cdef void slaruv(int *iseed, int *n, s *x) noexcept nogil: + + _fortran_slaruv(iseed, n, x) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slarz "BLAS_FUNC(slarz)"(char *side, int *m, int *n, int *l, s *v, int *incv, s *tau, s *c, int *ldc, s *work) nogil +cdef void slarz(char *side, int *m, int *n, int *l, s *v, int *incv, s *tau, s *c, int *ldc, s *work) noexcept nogil: + + _fortran_slarz(side, m, n, l, v, incv, tau, c, ldc, work) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slarzb "BLAS_FUNC(slarzb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, s *v, int *ldv, s *t, int *ldt, s *c, int *ldc, s *work, int *ldwork) nogil +cdef void slarzb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, s *v, int *ldv, s *t, int *ldt, s *c, int *ldc, s *work, int *ldwork) noexcept nogil: + + _fortran_slarzb(side, trans, direct, storev, m, n, k, l, v, ldv, t, ldt, c, ldc, work, ldwork) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slarzt "BLAS_FUNC(slarzt)"(char *direct, char *storev, int *n, int *k, s *v, int *ldv, s *tau, s *t, int *ldt) nogil +cdef void slarzt(char *direct, char *storev, int *n, int *k, s *v, int *ldv, s *tau, s *t, int *ldt) noexcept nogil: + + _fortran_slarzt(direct, storev, n, k, v, ldv, tau, t, ldt) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slas2 "BLAS_FUNC(slas2)"(s *f, s *g, s *h, s *ssmin, s *ssmax) nogil +cdef void slas2(s *f, s *g, s *h, s *ssmin, s *ssmax) noexcept nogil: + + _fortran_slas2(f, g, h, ssmin, ssmax) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slascl "BLAS_FUNC(slascl)"(char *type_bn, int *kl, int *ku, s *cfrom, s *cto, int *m, int *n, s *a, int *lda, int *info) nogil +cdef void slascl(char *type_bn, int *kl, int *ku, s *cfrom, s *cto, int *m, int *n, s *a, int *lda, int *info) noexcept nogil: + + _fortran_slascl(type_bn, kl, ku, cfrom, cto, m, n, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slasd0 "BLAS_FUNC(slasd0)"(int *n, int *sqre, s *d, s *e, s *u, int *ldu, s *vt, int *ldvt, int *smlsiz, int *iwork, s *work, int *info) nogil +cdef void slasd0(int *n, int *sqre, s *d, s *e, s *u, int *ldu, s *vt, int *ldvt, int *smlsiz, int *iwork, s *work, int *info) noexcept nogil: + + _fortran_slasd0(n, sqre, d, e, u, ldu, vt, ldvt, smlsiz, iwork, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slasd1 "BLAS_FUNC(slasd1)"(int *nl, int *nr, int *sqre, s *d, s *alpha, s *beta, s *u, int *ldu, s *vt, int *ldvt, int *idxq, int *iwork, s *work, int *info) nogil +cdef void slasd1(int *nl, int *nr, int *sqre, s *d, s *alpha, s *beta, s *u, int *ldu, s *vt, int *ldvt, int *idxq, int *iwork, s *work, int *info) noexcept nogil: + + _fortran_slasd1(nl, nr, sqre, d, alpha, beta, u, ldu, vt, ldvt, idxq, iwork, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slasd2 "BLAS_FUNC(slasd2)"(int *nl, int *nr, int *sqre, int *k, s *d, s *z, s *alpha, s *beta, s *u, int *ldu, s *vt, int *ldvt, s *dsigma, s *u2, int *ldu2, s *vt2, int *ldvt2, int *idxp, int *idx, int *idxc, int *idxq, int *coltyp, int *info) nogil +cdef void slasd2(int *nl, int *nr, int *sqre, int *k, s *d, s *z, s *alpha, s *beta, s *u, int *ldu, s *vt, int *ldvt, s *dsigma, s *u2, int *ldu2, s *vt2, int *ldvt2, int *idxp, int *idx, int *idxc, int *idxq, int *coltyp, int *info) noexcept nogil: + + _fortran_slasd2(nl, nr, sqre, k, d, z, alpha, beta, u, ldu, vt, ldvt, dsigma, u2, ldu2, vt2, ldvt2, idxp, idx, idxc, idxq, coltyp, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slasd3 "BLAS_FUNC(slasd3)"(int *nl, int *nr, int *sqre, int *k, s *d, s *q, int *ldq, s *dsigma, s *u, int *ldu, s *u2, int *ldu2, s *vt, int *ldvt, s *vt2, int *ldvt2, int *idxc, int *ctot, s *z, int *info) nogil +cdef void slasd3(int *nl, int *nr, int *sqre, int *k, s *d, s *q, int *ldq, s *dsigma, s *u, int *ldu, s *u2, int *ldu2, s *vt, int *ldvt, s *vt2, int *ldvt2, int *idxc, int *ctot, s *z, int *info) noexcept nogil: + + _fortran_slasd3(nl, nr, sqre, k, d, q, ldq, dsigma, u, ldu, u2, ldu2, vt, ldvt, vt2, ldvt2, idxc, ctot, z, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slasd4 "BLAS_FUNC(slasd4)"(int *n, int *i, s *d, s *z, s *delta, s *rho, s *sigma, s *work, int *info) nogil +cdef void slasd4(int *n, int *i, s *d, s *z, s *delta, s *rho, s *sigma, s *work, int *info) noexcept nogil: + + _fortran_slasd4(n, i, d, z, delta, rho, sigma, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slasd5 "BLAS_FUNC(slasd5)"(int *i, s *d, s *z, s *delta, s *rho, s *dsigma, s *work) nogil +cdef void slasd5(int *i, s *d, s *z, s *delta, s *rho, s *dsigma, s *work) noexcept nogil: + + _fortran_slasd5(i, d, z, delta, rho, dsigma, work) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slasd6 "BLAS_FUNC(slasd6)"(int *icompq, int *nl, int *nr, int *sqre, s *d, s *vf, s *vl, s *alpha, s *beta, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, s *givnum, int *ldgnum, s *poles, s *difl, s *difr, s *z, int *k, s *c, s *s, s *work, int *iwork, int *info) nogil +cdef void slasd6(int *icompq, int *nl, int *nr, int *sqre, s *d, s *vf, s *vl, s *alpha, s *beta, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, s *givnum, int *ldgnum, s *poles, s *difl, s *difr, s *z, int *k, s *c, s *s, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_slasd6(icompq, nl, nr, sqre, d, vf, vl, alpha, beta, idxq, perm, givptr, givcol, ldgcol, givnum, ldgnum, poles, difl, difr, z, k, c, s, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slasd7 "BLAS_FUNC(slasd7)"(int *icompq, int *nl, int *nr, int *sqre, int *k, s *d, s *z, s *zw, s *vf, s *vfw, s *vl, s *vlw, s *alpha, s *beta, s *dsigma, int *idx, int *idxp, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, s *givnum, int *ldgnum, s *c, s *s, int *info) nogil +cdef void slasd7(int *icompq, int *nl, int *nr, int *sqre, int *k, s *d, s *z, s *zw, s *vf, s *vfw, s *vl, s *vlw, s *alpha, s *beta, s *dsigma, int *idx, int *idxp, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, s *givnum, int *ldgnum, s *c, s *s, int *info) noexcept nogil: + + _fortran_slasd7(icompq, nl, nr, sqre, k, d, z, zw, vf, vfw, vl, vlw, alpha, beta, dsigma, idx, idxp, idxq, perm, givptr, givcol, ldgcol, givnum, ldgnum, c, s, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slasd8 "BLAS_FUNC(slasd8)"(int *icompq, int *k, s *d, s *z, s *vf, s *vl, s *difl, s *difr, int *lddifr, s *dsigma, s *work, int *info) nogil +cdef void slasd8(int *icompq, int *k, s *d, s *z, s *vf, s *vl, s *difl, s *difr, int *lddifr, s *dsigma, s *work, int *info) noexcept nogil: + + _fortran_slasd8(icompq, k, d, z, vf, vl, difl, difr, lddifr, dsigma, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slasda "BLAS_FUNC(slasda)"(int *icompq, int *smlsiz, int *n, int *sqre, s *d, s *e, s *u, int *ldu, s *vt, int *k, s *difl, s *difr, s *z, s *poles, int *givptr, int *givcol, int *ldgcol, int *perm, s *givnum, s *c, s *s, s *work, int *iwork, int *info) nogil +cdef void slasda(int *icompq, int *smlsiz, int *n, int *sqre, s *d, s *e, s *u, int *ldu, s *vt, int *k, s *difl, s *difr, s *z, s *poles, int *givptr, int *givcol, int *ldgcol, int *perm, s *givnum, s *c, s *s, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_slasda(icompq, smlsiz, n, sqre, d, e, u, ldu, vt, k, difl, difr, z, poles, givptr, givcol, ldgcol, perm, givnum, c, s, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slasdq "BLAS_FUNC(slasdq)"(char *uplo, int *sqre, int *n, int *ncvt, int *nru, int *ncc, s *d, s *e, s *vt, int *ldvt, s *u, int *ldu, s *c, int *ldc, s *work, int *info) nogil +cdef void slasdq(char *uplo, int *sqre, int *n, int *ncvt, int *nru, int *ncc, s *d, s *e, s *vt, int *ldvt, s *u, int *ldu, s *c, int *ldc, s *work, int *info) noexcept nogil: + + _fortran_slasdq(uplo, sqre, n, ncvt, nru, ncc, d, e, vt, ldvt, u, ldu, c, ldc, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slasdt "BLAS_FUNC(slasdt)"(int *n, int *lvl, int *nd, int *inode, int *ndiml, int *ndimr, int *msub) nogil +cdef void slasdt(int *n, int *lvl, int *nd, int *inode, int *ndiml, int *ndimr, int *msub) noexcept nogil: + + _fortran_slasdt(n, lvl, nd, inode, ndiml, ndimr, msub) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slaset "BLAS_FUNC(slaset)"(char *uplo, int *m, int *n, s *alpha, s *beta, s *a, int *lda) nogil +cdef void slaset(char *uplo, int *m, int *n, s *alpha, s *beta, s *a, int *lda) noexcept nogil: + + _fortran_slaset(uplo, m, n, alpha, beta, a, lda) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slasq1 "BLAS_FUNC(slasq1)"(int *n, s *d, s *e, s *work, int *info) nogil +cdef void slasq1(int *n, s *d, s *e, s *work, int *info) noexcept nogil: + + _fortran_slasq1(n, d, e, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slasq2 "BLAS_FUNC(slasq2)"(int *n, s *z, int *info) nogil +cdef void slasq2(int *n, s *z, int *info) noexcept nogil: + + _fortran_slasq2(n, z, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slasq3 "BLAS_FUNC(slasq3)"(int *i0, int *n0, s *z, int *pp, s *dmin, s *sigma, s *desig, s *qmax, int *nfail, int *iter, int *ndiv, bint *ieee, int *ttype, s *dmin1, s *dmin2, s *dn, s *dn1, s *dn2, s *g, s *tau) nogil +cdef void slasq3(int *i0, int *n0, s *z, int *pp, s *dmin, s *sigma, s *desig, s *qmax, int *nfail, int *iter, int *ndiv, bint *ieee, int *ttype, s *dmin1, s *dmin2, s *dn, s *dn1, s *dn2, s *g, s *tau) noexcept nogil: + + _fortran_slasq3(i0, n0, z, pp, dmin, sigma, desig, qmax, nfail, iter, ndiv, ieee, ttype, dmin1, dmin2, dn, dn1, dn2, g, tau) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slasq4 "BLAS_FUNC(slasq4)"(int *i0, int *n0, s *z, int *pp, int *n0in, s *dmin, s *dmin1, s *dmin2, s *dn, s *dn1, s *dn2, s *tau, int *ttype, s *g) nogil +cdef void slasq4(int *i0, int *n0, s *z, int *pp, int *n0in, s *dmin, s *dmin1, s *dmin2, s *dn, s *dn1, s *dn2, s *tau, int *ttype, s *g) noexcept nogil: + + _fortran_slasq4(i0, n0, z, pp, n0in, dmin, dmin1, dmin2, dn, dn1, dn2, tau, ttype, g) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slasq6 "BLAS_FUNC(slasq6)"(int *i0, int *n0, s *z, int *pp, s *dmin, s *dmin1, s *dmin2, s *dn, s *dnm1, s *dnm2) nogil +cdef void slasq6(int *i0, int *n0, s *z, int *pp, s *dmin, s *dmin1, s *dmin2, s *dn, s *dnm1, s *dnm2) noexcept nogil: + + _fortran_slasq6(i0, n0, z, pp, dmin, dmin1, dmin2, dn, dnm1, dnm2) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slasr "BLAS_FUNC(slasr)"(char *side, char *pivot, char *direct, int *m, int *n, s *c, s *s, s *a, int *lda) nogil +cdef void slasr(char *side, char *pivot, char *direct, int *m, int *n, s *c, s *s, s *a, int *lda) noexcept nogil: + + _fortran_slasr(side, pivot, direct, m, n, c, s, a, lda) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slasrt "BLAS_FUNC(slasrt)"(char *id, int *n, s *d, int *info) nogil +cdef void slasrt(char *id, int *n, s *d, int *info) noexcept nogil: + + _fortran_slasrt(id, n, d, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slassq "BLAS_FUNC(slassq)"(int *n, s *x, int *incx, s *scale, s *sumsq) nogil +cdef void slassq(int *n, s *x, int *incx, s *scale, s *sumsq) noexcept nogil: + + _fortran_slassq(n, x, incx, scale, sumsq) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slasv2 "BLAS_FUNC(slasv2)"(s *f, s *g, s *h, s *ssmin, s *ssmax, s *snr, s *csr, s *snl, s *csl) nogil +cdef void slasv2(s *f, s *g, s *h, s *ssmin, s *ssmax, s *snr, s *csr, s *snl, s *csl) noexcept nogil: + + _fortran_slasv2(f, g, h, ssmin, ssmax, snr, csr, snl, csl) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slaswp "BLAS_FUNC(slaswp)"(int *n, s *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) nogil +cdef void slaswp(int *n, s *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) noexcept nogil: + + _fortran_slaswp(n, a, lda, k1, k2, ipiv, incx) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slasy2 "BLAS_FUNC(slasy2)"(bint *ltranl, bint *ltranr, int *isgn, int *n1, int *n2, s *tl, int *ldtl, s *tr, int *ldtr, s *b, int *ldb, s *scale, s *x, int *ldx, s *xnorm, int *info) nogil +cdef void slasy2(bint *ltranl, bint *ltranr, int *isgn, int *n1, int *n2, s *tl, int *ldtl, s *tr, int *ldtr, s *b, int *ldb, s *scale, s *x, int *ldx, s *xnorm, int *info) noexcept nogil: + + _fortran_slasy2(ltranl, ltranr, isgn, n1, n2, tl, ldtl, tr, ldtr, b, ldb, scale, x, ldx, xnorm, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slasyf "BLAS_FUNC(slasyf)"(char *uplo, int *n, int *nb, int *kb, s *a, int *lda, int *ipiv, s *w, int *ldw, int *info) nogil +cdef void slasyf(char *uplo, int *n, int *nb, int *kb, s *a, int *lda, int *ipiv, s *w, int *ldw, int *info) noexcept nogil: + + _fortran_slasyf(uplo, n, nb, kb, a, lda, ipiv, w, ldw, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slatbs "BLAS_FUNC(slatbs)"(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, s *ab, int *ldab, s *x, s *scale, s *cnorm, int *info) nogil +cdef void slatbs(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, s *ab, int *ldab, s *x, s *scale, s *cnorm, int *info) noexcept nogil: + + _fortran_slatbs(uplo, trans, diag, normin, n, kd, ab, ldab, x, scale, cnorm, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slatdf "BLAS_FUNC(slatdf)"(int *ijob, int *n, s *z, int *ldz, s *rhs, s *rdsum, s *rdscal, int *ipiv, int *jpiv) nogil +cdef void slatdf(int *ijob, int *n, s *z, int *ldz, s *rhs, s *rdsum, s *rdscal, int *ipiv, int *jpiv) noexcept nogil: + + _fortran_slatdf(ijob, n, z, ldz, rhs, rdsum, rdscal, ipiv, jpiv) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slatps "BLAS_FUNC(slatps)"(char *uplo, char *trans, char *diag, char *normin, int *n, s *ap, s *x, s *scale, s *cnorm, int *info) nogil +cdef void slatps(char *uplo, char *trans, char *diag, char *normin, int *n, s *ap, s *x, s *scale, s *cnorm, int *info) noexcept nogil: + + _fortran_slatps(uplo, trans, diag, normin, n, ap, x, scale, cnorm, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slatrd "BLAS_FUNC(slatrd)"(char *uplo, int *n, int *nb, s *a, int *lda, s *e, s *tau, s *w, int *ldw) nogil +cdef void slatrd(char *uplo, int *n, int *nb, s *a, int *lda, s *e, s *tau, s *w, int *ldw) noexcept nogil: + + _fortran_slatrd(uplo, n, nb, a, lda, e, tau, w, ldw) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slatrs "BLAS_FUNC(slatrs)"(char *uplo, char *trans, char *diag, char *normin, int *n, s *a, int *lda, s *x, s *scale, s *cnorm, int *info) nogil +cdef void slatrs(char *uplo, char *trans, char *diag, char *normin, int *n, s *a, int *lda, s *x, s *scale, s *cnorm, int *info) noexcept nogil: + + _fortran_slatrs(uplo, trans, diag, normin, n, a, lda, x, scale, cnorm, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slatrz "BLAS_FUNC(slatrz)"(int *m, int *n, int *l, s *a, int *lda, s *tau, s *work) nogil +cdef void slatrz(int *m, int *n, int *l, s *a, int *lda, s *tau, s *work) noexcept nogil: + + _fortran_slatrz(m, n, l, a, lda, tau, work) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slauu2 "BLAS_FUNC(slauu2)"(char *uplo, int *n, s *a, int *lda, int *info) nogil +cdef void slauu2(char *uplo, int *n, s *a, int *lda, int *info) noexcept nogil: + + _fortran_slauu2(uplo, n, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_slauum "BLAS_FUNC(slauum)"(char *uplo, int *n, s *a, int *lda, int *info) nogil +cdef void slauum(char *uplo, int *n, s *a, int *lda, int *info) noexcept nogil: + + _fortran_slauum(uplo, n, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sopgtr "BLAS_FUNC(sopgtr)"(char *uplo, int *n, s *ap, s *tau, s *q, int *ldq, s *work, int *info) nogil +cdef void sopgtr(char *uplo, int *n, s *ap, s *tau, s *q, int *ldq, s *work, int *info) noexcept nogil: + + _fortran_sopgtr(uplo, n, ap, tau, q, ldq, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sopmtr "BLAS_FUNC(sopmtr)"(char *side, char *uplo, char *trans, int *m, int *n, s *ap, s *tau, s *c, int *ldc, s *work, int *info) nogil +cdef void sopmtr(char *side, char *uplo, char *trans, int *m, int *n, s *ap, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil: + + _fortran_sopmtr(side, uplo, trans, m, n, ap, tau, c, ldc, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sorbdb "BLAS_FUNC(sorbdb)"(char *trans, char *signs, int *m, int *p, int *q, s *x11, int *ldx11, s *x12, int *ldx12, s *x21, int *ldx21, s *x22, int *ldx22, s *theta, s *phi, s *taup1, s *taup2, s *tauq1, s *tauq2, s *work, int *lwork, int *info) nogil +cdef void sorbdb(char *trans, char *signs, int *m, int *p, int *q, s *x11, int *ldx11, s *x12, int *ldx12, s *x21, int *ldx21, s *x22, int *ldx22, s *theta, s *phi, s *taup1, s *taup2, s *tauq1, s *tauq2, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_sorbdb(trans, signs, m, p, q, x11, ldx11, x12, ldx12, x21, ldx21, x22, ldx22, theta, phi, taup1, taup2, tauq1, tauq2, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sorcsd "BLAS_FUNC(sorcsd)"(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, s *x11, int *ldx11, s *x12, int *ldx12, s *x21, int *ldx21, s *x22, int *ldx22, s *theta, s *u1, int *ldu1, s *u2, int *ldu2, s *v1t, int *ldv1t, s *v2t, int *ldv2t, s *work, int *lwork, int *iwork, int *info) nogil +cdef void sorcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, s *x11, int *ldx11, s *x12, int *ldx12, s *x21, int *ldx21, s *x22, int *ldx22, s *theta, s *u1, int *ldu1, s *u2, int *ldu2, s *v1t, int *ldv1t, s *v2t, int *ldv2t, s *work, int *lwork, int *iwork, int *info) noexcept nogil: + + _fortran_sorcsd(jobu1, jobu2, jobv1t, jobv2t, trans, signs, m, p, q, x11, ldx11, x12, ldx12, x21, ldx21, x22, ldx22, theta, u1, ldu1, u2, ldu2, v1t, ldv1t, v2t, ldv2t, work, lwork, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sorg2l "BLAS_FUNC(sorg2l)"(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) nogil +cdef void sorg2l(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil: + + _fortran_sorg2l(m, n, k, a, lda, tau, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sorg2r "BLAS_FUNC(sorg2r)"(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) nogil +cdef void sorg2r(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil: + + _fortran_sorg2r(m, n, k, a, lda, tau, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sorgbr "BLAS_FUNC(sorgbr)"(char *vect, int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil +cdef void sorgbr(char *vect, int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_sorgbr(vect, m, n, k, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sorghr "BLAS_FUNC(sorghr)"(int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil +cdef void sorghr(int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_sorghr(n, ilo, ihi, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sorgl2 "BLAS_FUNC(sorgl2)"(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) nogil +cdef void sorgl2(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil: + + _fortran_sorgl2(m, n, k, a, lda, tau, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sorglq "BLAS_FUNC(sorglq)"(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil +cdef void sorglq(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_sorglq(m, n, k, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sorgql "BLAS_FUNC(sorgql)"(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil +cdef void sorgql(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_sorgql(m, n, k, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sorgqr "BLAS_FUNC(sorgqr)"(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil +cdef void sorgqr(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_sorgqr(m, n, k, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sorgr2 "BLAS_FUNC(sorgr2)"(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) nogil +cdef void sorgr2(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil: + + _fortran_sorgr2(m, n, k, a, lda, tau, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sorgrq "BLAS_FUNC(sorgrq)"(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil +cdef void sorgrq(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_sorgrq(m, n, k, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sorgtr "BLAS_FUNC(sorgtr)"(char *uplo, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil +cdef void sorgtr(char *uplo, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_sorgtr(uplo, n, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sorm2l "BLAS_FUNC(sorm2l)"(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) nogil +cdef void sorm2l(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil: + + _fortran_sorm2l(side, trans, m, n, k, a, lda, tau, c, ldc, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sorm2r "BLAS_FUNC(sorm2r)"(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) nogil +cdef void sorm2r(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil: + + _fortran_sorm2r(side, trans, m, n, k, a, lda, tau, c, ldc, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sormbr "BLAS_FUNC(sormbr)"(char *vect, char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) nogil +cdef void sormbr(char *vect, char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_sormbr(vect, side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sormhr "BLAS_FUNC(sormhr)"(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) nogil +cdef void sormhr(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_sormhr(side, trans, m, n, ilo, ihi, a, lda, tau, c, ldc, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sorml2 "BLAS_FUNC(sorml2)"(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) nogil +cdef void sorml2(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil: + + _fortran_sorml2(side, trans, m, n, k, a, lda, tau, c, ldc, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sormlq "BLAS_FUNC(sormlq)"(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) nogil +cdef void sormlq(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_sormlq(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sormql "BLAS_FUNC(sormql)"(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) nogil +cdef void sormql(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_sormql(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sormqr "BLAS_FUNC(sormqr)"(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) nogil +cdef void sormqr(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_sormqr(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sormr2 "BLAS_FUNC(sormr2)"(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) nogil +cdef void sormr2(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil: + + _fortran_sormr2(side, trans, m, n, k, a, lda, tau, c, ldc, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sormr3 "BLAS_FUNC(sormr3)"(char *side, char *trans, int *m, int *n, int *k, int *l, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) nogil +cdef void sormr3(char *side, char *trans, int *m, int *n, int *k, int *l, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil: + + _fortran_sormr3(side, trans, m, n, k, l, a, lda, tau, c, ldc, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sormrq "BLAS_FUNC(sormrq)"(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) nogil +cdef void sormrq(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_sormrq(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sormrz "BLAS_FUNC(sormrz)"(char *side, char *trans, int *m, int *n, int *k, int *l, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) nogil +cdef void sormrz(char *side, char *trans, int *m, int *n, int *k, int *l, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_sormrz(side, trans, m, n, k, l, a, lda, tau, c, ldc, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sormtr "BLAS_FUNC(sormtr)"(char *side, char *uplo, char *trans, int *m, int *n, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) nogil +cdef void sormtr(char *side, char *uplo, char *trans, int *m, int *n, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_sormtr(side, uplo, trans, m, n, a, lda, tau, c, ldc, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_spbcon "BLAS_FUNC(spbcon)"(char *uplo, int *n, int *kd, s *ab, int *ldab, s *anorm, s *rcond, s *work, int *iwork, int *info) nogil +cdef void spbcon(char *uplo, int *n, int *kd, s *ab, int *ldab, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_spbcon(uplo, n, kd, ab, ldab, anorm, rcond, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_spbequ "BLAS_FUNC(spbequ)"(char *uplo, int *n, int *kd, s *ab, int *ldab, s *s, s *scond, s *amax, int *info) nogil +cdef void spbequ(char *uplo, int *n, int *kd, s *ab, int *ldab, s *s, s *scond, s *amax, int *info) noexcept nogil: + + _fortran_spbequ(uplo, n, kd, ab, ldab, s, scond, amax, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_spbrfs "BLAS_FUNC(spbrfs)"(char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *afb, int *ldafb, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) nogil +cdef void spbrfs(char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *afb, int *ldafb, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_spbrfs(uplo, n, kd, nrhs, ab, ldab, afb, ldafb, b, ldb, x, ldx, ferr, berr, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_spbstf "BLAS_FUNC(spbstf)"(char *uplo, int *n, int *kd, s *ab, int *ldab, int *info) nogil +cdef void spbstf(char *uplo, int *n, int *kd, s *ab, int *ldab, int *info) noexcept nogil: + + _fortran_spbstf(uplo, n, kd, ab, ldab, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_spbsv "BLAS_FUNC(spbsv)"(char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, int *info) nogil +cdef void spbsv(char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, int *info) noexcept nogil: + + _fortran_spbsv(uplo, n, kd, nrhs, ab, ldab, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_spbsvx "BLAS_FUNC(spbsvx)"(char *fact, char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *afb, int *ldafb, char *equed, s *s, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) nogil +cdef void spbsvx(char *fact, char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *afb, int *ldafb, char *equed, s *s, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_spbsvx(fact, uplo, n, kd, nrhs, ab, ldab, afb, ldafb, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_spbtf2 "BLAS_FUNC(spbtf2)"(char *uplo, int *n, int *kd, s *ab, int *ldab, int *info) nogil +cdef void spbtf2(char *uplo, int *n, int *kd, s *ab, int *ldab, int *info) noexcept nogil: + + _fortran_spbtf2(uplo, n, kd, ab, ldab, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_spbtrf "BLAS_FUNC(spbtrf)"(char *uplo, int *n, int *kd, s *ab, int *ldab, int *info) nogil +cdef void spbtrf(char *uplo, int *n, int *kd, s *ab, int *ldab, int *info) noexcept nogil: + + _fortran_spbtrf(uplo, n, kd, ab, ldab, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_spbtrs "BLAS_FUNC(spbtrs)"(char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, int *info) nogil +cdef void spbtrs(char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, int *info) noexcept nogil: + + _fortran_spbtrs(uplo, n, kd, nrhs, ab, ldab, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_spftrf "BLAS_FUNC(spftrf)"(char *transr, char *uplo, int *n, s *a, int *info) nogil +cdef void spftrf(char *transr, char *uplo, int *n, s *a, int *info) noexcept nogil: + + _fortran_spftrf(transr, uplo, n, a, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_spftri "BLAS_FUNC(spftri)"(char *transr, char *uplo, int *n, s *a, int *info) nogil +cdef void spftri(char *transr, char *uplo, int *n, s *a, int *info) noexcept nogil: + + _fortran_spftri(transr, uplo, n, a, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_spftrs "BLAS_FUNC(spftrs)"(char *transr, char *uplo, int *n, int *nrhs, s *a, s *b, int *ldb, int *info) nogil +cdef void spftrs(char *transr, char *uplo, int *n, int *nrhs, s *a, s *b, int *ldb, int *info) noexcept nogil: + + _fortran_spftrs(transr, uplo, n, nrhs, a, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_spocon "BLAS_FUNC(spocon)"(char *uplo, int *n, s *a, int *lda, s *anorm, s *rcond, s *work, int *iwork, int *info) nogil +cdef void spocon(char *uplo, int *n, s *a, int *lda, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_spocon(uplo, n, a, lda, anorm, rcond, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_spoequ "BLAS_FUNC(spoequ)"(int *n, s *a, int *lda, s *s, s *scond, s *amax, int *info) nogil +cdef void spoequ(int *n, s *a, int *lda, s *s, s *scond, s *amax, int *info) noexcept nogil: + + _fortran_spoequ(n, a, lda, s, scond, amax, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_spoequb "BLAS_FUNC(spoequb)"(int *n, s *a, int *lda, s *s, s *scond, s *amax, int *info) nogil +cdef void spoequb(int *n, s *a, int *lda, s *s, s *scond, s *amax, int *info) noexcept nogil: + + _fortran_spoequb(n, a, lda, s, scond, amax, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sporfs "BLAS_FUNC(sporfs)"(char *uplo, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) nogil +cdef void sporfs(char *uplo, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_sporfs(uplo, n, nrhs, a, lda, af, ldaf, b, ldb, x, ldx, ferr, berr, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sposv "BLAS_FUNC(sposv)"(char *uplo, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *info) nogil +cdef void sposv(char *uplo, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *info) noexcept nogil: + + _fortran_sposv(uplo, n, nrhs, a, lda, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sposvx "BLAS_FUNC(sposvx)"(char *fact, char *uplo, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, char *equed, s *s, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) nogil +cdef void sposvx(char *fact, char *uplo, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, char *equed, s *s, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_sposvx(fact, uplo, n, nrhs, a, lda, af, ldaf, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_spotf2 "BLAS_FUNC(spotf2)"(char *uplo, int *n, s *a, int *lda, int *info) nogil +cdef void spotf2(char *uplo, int *n, s *a, int *lda, int *info) noexcept nogil: + + _fortran_spotf2(uplo, n, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_spotrf "BLAS_FUNC(spotrf)"(char *uplo, int *n, s *a, int *lda, int *info) nogil +cdef void spotrf(char *uplo, int *n, s *a, int *lda, int *info) noexcept nogil: + + _fortran_spotrf(uplo, n, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_spotri "BLAS_FUNC(spotri)"(char *uplo, int *n, s *a, int *lda, int *info) nogil +cdef void spotri(char *uplo, int *n, s *a, int *lda, int *info) noexcept nogil: + + _fortran_spotri(uplo, n, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_spotrs "BLAS_FUNC(spotrs)"(char *uplo, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *info) nogil +cdef void spotrs(char *uplo, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *info) noexcept nogil: + + _fortran_spotrs(uplo, n, nrhs, a, lda, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sppcon "BLAS_FUNC(sppcon)"(char *uplo, int *n, s *ap, s *anorm, s *rcond, s *work, int *iwork, int *info) nogil +cdef void sppcon(char *uplo, int *n, s *ap, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_sppcon(uplo, n, ap, anorm, rcond, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sppequ "BLAS_FUNC(sppequ)"(char *uplo, int *n, s *ap, s *s, s *scond, s *amax, int *info) nogil +cdef void sppequ(char *uplo, int *n, s *ap, s *s, s *scond, s *amax, int *info) noexcept nogil: + + _fortran_sppequ(uplo, n, ap, s, scond, amax, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_spprfs "BLAS_FUNC(spprfs)"(char *uplo, int *n, int *nrhs, s *ap, s *afp, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) nogil +cdef void spprfs(char *uplo, int *n, int *nrhs, s *ap, s *afp, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_spprfs(uplo, n, nrhs, ap, afp, b, ldb, x, ldx, ferr, berr, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sppsv "BLAS_FUNC(sppsv)"(char *uplo, int *n, int *nrhs, s *ap, s *b, int *ldb, int *info) nogil +cdef void sppsv(char *uplo, int *n, int *nrhs, s *ap, s *b, int *ldb, int *info) noexcept nogil: + + _fortran_sppsv(uplo, n, nrhs, ap, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sppsvx "BLAS_FUNC(sppsvx)"(char *fact, char *uplo, int *n, int *nrhs, s *ap, s *afp, char *equed, s *s, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) nogil +cdef void sppsvx(char *fact, char *uplo, int *n, int *nrhs, s *ap, s *afp, char *equed, s *s, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_sppsvx(fact, uplo, n, nrhs, ap, afp, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_spptrf "BLAS_FUNC(spptrf)"(char *uplo, int *n, s *ap, int *info) nogil +cdef void spptrf(char *uplo, int *n, s *ap, int *info) noexcept nogil: + + _fortran_spptrf(uplo, n, ap, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_spptri "BLAS_FUNC(spptri)"(char *uplo, int *n, s *ap, int *info) nogil +cdef void spptri(char *uplo, int *n, s *ap, int *info) noexcept nogil: + + _fortran_spptri(uplo, n, ap, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_spptrs "BLAS_FUNC(spptrs)"(char *uplo, int *n, int *nrhs, s *ap, s *b, int *ldb, int *info) nogil +cdef void spptrs(char *uplo, int *n, int *nrhs, s *ap, s *b, int *ldb, int *info) noexcept nogil: + + _fortran_spptrs(uplo, n, nrhs, ap, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_spstf2 "BLAS_FUNC(spstf2)"(char *uplo, int *n, s *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) nogil +cdef void spstf2(char *uplo, int *n, s *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) noexcept nogil: + + _fortran_spstf2(uplo, n, a, lda, piv, rank, tol, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_spstrf "BLAS_FUNC(spstrf)"(char *uplo, int *n, s *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) nogil +cdef void spstrf(char *uplo, int *n, s *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) noexcept nogil: + + _fortran_spstrf(uplo, n, a, lda, piv, rank, tol, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sptcon "BLAS_FUNC(sptcon)"(int *n, s *d, s *e, s *anorm, s *rcond, s *work, int *info) nogil +cdef void sptcon(int *n, s *d, s *e, s *anorm, s *rcond, s *work, int *info) noexcept nogil: + + _fortran_sptcon(n, d, e, anorm, rcond, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_spteqr "BLAS_FUNC(spteqr)"(char *compz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *info) nogil +cdef void spteqr(char *compz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *info) noexcept nogil: + + _fortran_spteqr(compz, n, d, e, z, ldz, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sptrfs "BLAS_FUNC(sptrfs)"(int *n, int *nrhs, s *d, s *e, s *df, s *ef, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *info) nogil +cdef void sptrfs(int *n, int *nrhs, s *d, s *e, s *df, s *ef, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *info) noexcept nogil: + + _fortran_sptrfs(n, nrhs, d, e, df, ef, b, ldb, x, ldx, ferr, berr, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sptsv "BLAS_FUNC(sptsv)"(int *n, int *nrhs, s *d, s *e, s *b, int *ldb, int *info) nogil +cdef void sptsv(int *n, int *nrhs, s *d, s *e, s *b, int *ldb, int *info) noexcept nogil: + + _fortran_sptsv(n, nrhs, d, e, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sptsvx "BLAS_FUNC(sptsvx)"(char *fact, int *n, int *nrhs, s *d, s *e, s *df, s *ef, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *info) nogil +cdef void sptsvx(char *fact, int *n, int *nrhs, s *d, s *e, s *df, s *ef, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *info) noexcept nogil: + + _fortran_sptsvx(fact, n, nrhs, d, e, df, ef, b, ldb, x, ldx, rcond, ferr, berr, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_spttrf "BLAS_FUNC(spttrf)"(int *n, s *d, s *e, int *info) nogil +cdef void spttrf(int *n, s *d, s *e, int *info) noexcept nogil: + + _fortran_spttrf(n, d, e, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_spttrs "BLAS_FUNC(spttrs)"(int *n, int *nrhs, s *d, s *e, s *b, int *ldb, int *info) nogil +cdef void spttrs(int *n, int *nrhs, s *d, s *e, s *b, int *ldb, int *info) noexcept nogil: + + _fortran_spttrs(n, nrhs, d, e, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sptts2 "BLAS_FUNC(sptts2)"(int *n, int *nrhs, s *d, s *e, s *b, int *ldb) nogil +cdef void sptts2(int *n, int *nrhs, s *d, s *e, s *b, int *ldb) noexcept nogil: + + _fortran_sptts2(n, nrhs, d, e, b, ldb) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_srscl "BLAS_FUNC(srscl)"(int *n, s *sa, s *sx, int *incx) nogil +cdef void srscl(int *n, s *sa, s *sx, int *incx) noexcept nogil: + + _fortran_srscl(n, sa, sx, incx) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ssbev "BLAS_FUNC(ssbev)"(char *jobz, char *uplo, int *n, int *kd, s *ab, int *ldab, s *w, s *z, int *ldz, s *work, int *info) nogil +cdef void ssbev(char *jobz, char *uplo, int *n, int *kd, s *ab, int *ldab, s *w, s *z, int *ldz, s *work, int *info) noexcept nogil: + + _fortran_ssbev(jobz, uplo, n, kd, ab, ldab, w, z, ldz, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ssbevd "BLAS_FUNC(ssbevd)"(char *jobz, char *uplo, int *n, int *kd, s *ab, int *ldab, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil +cdef void ssbevd(char *jobz, char *uplo, int *n, int *kd, s *ab, int *ldab, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_ssbevd(jobz, uplo, n, kd, ab, ldab, w, z, ldz, work, lwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ssbevx "BLAS_FUNC(ssbevx)"(char *jobz, char *range, char *uplo, int *n, int *kd, s *ab, int *ldab, s *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) nogil +cdef void ssbevx(char *jobz, char *range, char *uplo, int *n, int *kd, s *ab, int *ldab, s *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil: + + _fortran_ssbevx(jobz, range, uplo, n, kd, ab, ldab, q, ldq, vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, ifail, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ssbgst "BLAS_FUNC(ssbgst)"(char *vect, char *uplo, int *n, int *ka, int *kb, s *ab, int *ldab, s *bb, int *ldbb, s *x, int *ldx, s *work, int *info) nogil +cdef void ssbgst(char *vect, char *uplo, int *n, int *ka, int *kb, s *ab, int *ldab, s *bb, int *ldbb, s *x, int *ldx, s *work, int *info) noexcept nogil: + + _fortran_ssbgst(vect, uplo, n, ka, kb, ab, ldab, bb, ldbb, x, ldx, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ssbgv "BLAS_FUNC(ssbgv)"(char *jobz, char *uplo, int *n, int *ka, int *kb, s *ab, int *ldab, s *bb, int *ldbb, s *w, s *z, int *ldz, s *work, int *info) nogil +cdef void ssbgv(char *jobz, char *uplo, int *n, int *ka, int *kb, s *ab, int *ldab, s *bb, int *ldbb, s *w, s *z, int *ldz, s *work, int *info) noexcept nogil: + + _fortran_ssbgv(jobz, uplo, n, ka, kb, ab, ldab, bb, ldbb, w, z, ldz, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ssbgvd "BLAS_FUNC(ssbgvd)"(char *jobz, char *uplo, int *n, int *ka, int *kb, s *ab, int *ldab, s *bb, int *ldbb, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil +cdef void ssbgvd(char *jobz, char *uplo, int *n, int *ka, int *kb, s *ab, int *ldab, s *bb, int *ldbb, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_ssbgvd(jobz, uplo, n, ka, kb, ab, ldab, bb, ldbb, w, z, ldz, work, lwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ssbgvx "BLAS_FUNC(ssbgvx)"(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, s *ab, int *ldab, s *bb, int *ldbb, s *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) nogil +cdef void ssbgvx(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, s *ab, int *ldab, s *bb, int *ldbb, s *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil: + + _fortran_ssbgvx(jobz, range, uplo, n, ka, kb, ab, ldab, bb, ldbb, q, ldq, vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, ifail, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ssbtrd "BLAS_FUNC(ssbtrd)"(char *vect, char *uplo, int *n, int *kd, s *ab, int *ldab, s *d, s *e, s *q, int *ldq, s *work, int *info) nogil +cdef void ssbtrd(char *vect, char *uplo, int *n, int *kd, s *ab, int *ldab, s *d, s *e, s *q, int *ldq, s *work, int *info) noexcept nogil: + + _fortran_ssbtrd(vect, uplo, n, kd, ab, ldab, d, e, q, ldq, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ssfrk "BLAS_FUNC(ssfrk)"(char *transr, char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *beta, s *c) nogil +cdef void ssfrk(char *transr, char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *beta, s *c) noexcept nogil: + + _fortran_ssfrk(transr, uplo, trans, n, k, alpha, a, lda, beta, c) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sspcon "BLAS_FUNC(sspcon)"(char *uplo, int *n, s *ap, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) nogil +cdef void sspcon(char *uplo, int *n, s *ap, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_sspcon(uplo, n, ap, ipiv, anorm, rcond, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sspev "BLAS_FUNC(sspev)"(char *jobz, char *uplo, int *n, s *ap, s *w, s *z, int *ldz, s *work, int *info) nogil +cdef void sspev(char *jobz, char *uplo, int *n, s *ap, s *w, s *z, int *ldz, s *work, int *info) noexcept nogil: + + _fortran_sspev(jobz, uplo, n, ap, w, z, ldz, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sspevd "BLAS_FUNC(sspevd)"(char *jobz, char *uplo, int *n, s *ap, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil +cdef void sspevd(char *jobz, char *uplo, int *n, s *ap, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_sspevd(jobz, uplo, n, ap, w, z, ldz, work, lwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sspevx "BLAS_FUNC(sspevx)"(char *jobz, char *range, char *uplo, int *n, s *ap, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) nogil +cdef void sspevx(char *jobz, char *range, char *uplo, int *n, s *ap, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil: + + _fortran_sspevx(jobz, range, uplo, n, ap, vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, ifail, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sspgst "BLAS_FUNC(sspgst)"(int *itype, char *uplo, int *n, s *ap, s *bp, int *info) nogil +cdef void sspgst(int *itype, char *uplo, int *n, s *ap, s *bp, int *info) noexcept nogil: + + _fortran_sspgst(itype, uplo, n, ap, bp, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sspgv "BLAS_FUNC(sspgv)"(int *itype, char *jobz, char *uplo, int *n, s *ap, s *bp, s *w, s *z, int *ldz, s *work, int *info) nogil +cdef void sspgv(int *itype, char *jobz, char *uplo, int *n, s *ap, s *bp, s *w, s *z, int *ldz, s *work, int *info) noexcept nogil: + + _fortran_sspgv(itype, jobz, uplo, n, ap, bp, w, z, ldz, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sspgvd "BLAS_FUNC(sspgvd)"(int *itype, char *jobz, char *uplo, int *n, s *ap, s *bp, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil +cdef void sspgvd(int *itype, char *jobz, char *uplo, int *n, s *ap, s *bp, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_sspgvd(itype, jobz, uplo, n, ap, bp, w, z, ldz, work, lwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sspgvx "BLAS_FUNC(sspgvx)"(int *itype, char *jobz, char *range, char *uplo, int *n, s *ap, s *bp, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) nogil +cdef void sspgvx(int *itype, char *jobz, char *range, char *uplo, int *n, s *ap, s *bp, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil: + + _fortran_sspgvx(itype, jobz, range, uplo, n, ap, bp, vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, ifail, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ssprfs "BLAS_FUNC(ssprfs)"(char *uplo, int *n, int *nrhs, s *ap, s *afp, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) nogil +cdef void ssprfs(char *uplo, int *n, int *nrhs, s *ap, s *afp, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_ssprfs(uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, ferr, berr, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sspsv "BLAS_FUNC(sspsv)"(char *uplo, int *n, int *nrhs, s *ap, int *ipiv, s *b, int *ldb, int *info) nogil +cdef void sspsv(char *uplo, int *n, int *nrhs, s *ap, int *ipiv, s *b, int *ldb, int *info) noexcept nogil: + + _fortran_sspsv(uplo, n, nrhs, ap, ipiv, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sspsvx "BLAS_FUNC(sspsvx)"(char *fact, char *uplo, int *n, int *nrhs, s *ap, s *afp, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) nogil +cdef void sspsvx(char *fact, char *uplo, int *n, int *nrhs, s *ap, s *afp, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_sspsvx(fact, uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ssptrd "BLAS_FUNC(ssptrd)"(char *uplo, int *n, s *ap, s *d, s *e, s *tau, int *info) nogil +cdef void ssptrd(char *uplo, int *n, s *ap, s *d, s *e, s *tau, int *info) noexcept nogil: + + _fortran_ssptrd(uplo, n, ap, d, e, tau, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ssptrf "BLAS_FUNC(ssptrf)"(char *uplo, int *n, s *ap, int *ipiv, int *info) nogil +cdef void ssptrf(char *uplo, int *n, s *ap, int *ipiv, int *info) noexcept nogil: + + _fortran_ssptrf(uplo, n, ap, ipiv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ssptri "BLAS_FUNC(ssptri)"(char *uplo, int *n, s *ap, int *ipiv, s *work, int *info) nogil +cdef void ssptri(char *uplo, int *n, s *ap, int *ipiv, s *work, int *info) noexcept nogil: + + _fortran_ssptri(uplo, n, ap, ipiv, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ssptrs "BLAS_FUNC(ssptrs)"(char *uplo, int *n, int *nrhs, s *ap, int *ipiv, s *b, int *ldb, int *info) nogil +cdef void ssptrs(char *uplo, int *n, int *nrhs, s *ap, int *ipiv, s *b, int *ldb, int *info) noexcept nogil: + + _fortran_ssptrs(uplo, n, nrhs, ap, ipiv, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sstebz "BLAS_FUNC(sstebz)"(char *range, char *order, int *n, s *vl, s *vu, int *il, int *iu, s *abstol, s *d, s *e, int *m, int *nsplit, s *w, int *iblock, int *isplit, s *work, int *iwork, int *info) nogil +cdef void sstebz(char *range, char *order, int *n, s *vl, s *vu, int *il, int *iu, s *abstol, s *d, s *e, int *m, int *nsplit, s *w, int *iblock, int *isplit, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_sstebz(range, order, n, vl, vu, il, iu, abstol, d, e, m, nsplit, w, iblock, isplit, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sstedc "BLAS_FUNC(sstedc)"(char *compz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil +cdef void sstedc(char *compz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_sstedc(compz, n, d, e, z, ldz, work, lwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sstegr "BLAS_FUNC(sstegr)"(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, int *isuppz, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil +cdef void sstegr(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, int *isuppz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_sstegr(jobz, range, n, d, e, vl, vu, il, iu, abstol, m, w, z, ldz, isuppz, work, lwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sstein "BLAS_FUNC(sstein)"(int *n, s *d, s *e, int *m, s *w, int *iblock, int *isplit, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) nogil +cdef void sstein(int *n, s *d, s *e, int *m, s *w, int *iblock, int *isplit, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil: + + _fortran_sstein(n, d, e, m, w, iblock, isplit, z, ldz, work, iwork, ifail, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sstemr "BLAS_FUNC(sstemr)"(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, int *m, s *w, s *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil +cdef void sstemr(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, int *m, s *w, s *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_sstemr(jobz, range, n, d, e, vl, vu, il, iu, m, w, z, ldz, nzc, isuppz, tryrac, work, lwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ssteqr "BLAS_FUNC(ssteqr)"(char *compz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *info) nogil +cdef void ssteqr(char *compz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *info) noexcept nogil: + + _fortran_ssteqr(compz, n, d, e, z, ldz, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ssterf "BLAS_FUNC(ssterf)"(int *n, s *d, s *e, int *info) nogil +cdef void ssterf(int *n, s *d, s *e, int *info) noexcept nogil: + + _fortran_ssterf(n, d, e, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sstev "BLAS_FUNC(sstev)"(char *jobz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *info) nogil +cdef void sstev(char *jobz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *info) noexcept nogil: + + _fortran_sstev(jobz, n, d, e, z, ldz, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sstevd "BLAS_FUNC(sstevd)"(char *jobz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil +cdef void sstevd(char *jobz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_sstevd(jobz, n, d, e, z, ldz, work, lwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sstevr "BLAS_FUNC(sstevr)"(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, int *isuppz, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil +cdef void sstevr(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, int *isuppz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_sstevr(jobz, range, n, d, e, vl, vu, il, iu, abstol, m, w, z, ldz, isuppz, work, lwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_sstevx "BLAS_FUNC(sstevx)"(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) nogil +cdef void sstevx(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil: + + _fortran_sstevx(jobz, range, n, d, e, vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, ifail, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ssycon "BLAS_FUNC(ssycon)"(char *uplo, int *n, s *a, int *lda, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) nogil +cdef void ssycon(char *uplo, int *n, s *a, int *lda, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_ssycon(uplo, n, a, lda, ipiv, anorm, rcond, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ssyconv "BLAS_FUNC(ssyconv)"(char *uplo, char *way, int *n, s *a, int *lda, int *ipiv, s *work, int *info) nogil +cdef void ssyconv(char *uplo, char *way, int *n, s *a, int *lda, int *ipiv, s *work, int *info) noexcept nogil: + + _fortran_ssyconv(uplo, way, n, a, lda, ipiv, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ssyequb "BLAS_FUNC(ssyequb)"(char *uplo, int *n, s *a, int *lda, s *s, s *scond, s *amax, s *work, int *info) nogil +cdef void ssyequb(char *uplo, int *n, s *a, int *lda, s *s, s *scond, s *amax, s *work, int *info) noexcept nogil: + + _fortran_ssyequb(uplo, n, a, lda, s, scond, amax, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ssyev "BLAS_FUNC(ssyev)"(char *jobz, char *uplo, int *n, s *a, int *lda, s *w, s *work, int *lwork, int *info) nogil +cdef void ssyev(char *jobz, char *uplo, int *n, s *a, int *lda, s *w, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_ssyev(jobz, uplo, n, a, lda, w, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ssyevd "BLAS_FUNC(ssyevd)"(char *jobz, char *uplo, int *n, s *a, int *lda, s *w, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil +cdef void ssyevd(char *jobz, char *uplo, int *n, s *a, int *lda, s *w, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_ssyevd(jobz, uplo, n, a, lda, w, work, lwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ssyevr "BLAS_FUNC(ssyevr)"(char *jobz, char *range, char *uplo, int *n, s *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, int *isuppz, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil +cdef void ssyevr(char *jobz, char *range, char *uplo, int *n, s *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, int *isuppz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_ssyevr(jobz, range, uplo, n, a, lda, vl, vu, il, iu, abstol, m, w, z, ldz, isuppz, work, lwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ssyevx "BLAS_FUNC(ssyevx)"(char *jobz, char *range, char *uplo, int *n, s *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *ifail, int *info) nogil +cdef void ssyevx(char *jobz, char *range, char *uplo, int *n, s *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *ifail, int *info) noexcept nogil: + + _fortran_ssyevx(jobz, range, uplo, n, a, lda, vl, vu, il, iu, abstol, m, w, z, ldz, work, lwork, iwork, ifail, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ssygs2 "BLAS_FUNC(ssygs2)"(int *itype, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, int *info) nogil +cdef void ssygs2(int *itype, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, int *info) noexcept nogil: + + _fortran_ssygs2(itype, uplo, n, a, lda, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ssygst "BLAS_FUNC(ssygst)"(int *itype, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, int *info) nogil +cdef void ssygst(int *itype, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, int *info) noexcept nogil: + + _fortran_ssygst(itype, uplo, n, a, lda, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ssygv "BLAS_FUNC(ssygv)"(int *itype, char *jobz, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, s *w, s *work, int *lwork, int *info) nogil +cdef void ssygv(int *itype, char *jobz, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, s *w, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_ssygv(itype, jobz, uplo, n, a, lda, b, ldb, w, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ssygvd "BLAS_FUNC(ssygvd)"(int *itype, char *jobz, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, s *w, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil +cdef void ssygvd(int *itype, char *jobz, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, s *w, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_ssygvd(itype, jobz, uplo, n, a, lda, b, ldb, w, work, lwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ssygvx "BLAS_FUNC(ssygvx)"(int *itype, char *jobz, char *range, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *ifail, int *info) nogil +cdef void ssygvx(int *itype, char *jobz, char *range, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *ifail, int *info) noexcept nogil: + + _fortran_ssygvx(itype, jobz, range, uplo, n, a, lda, b, ldb, vl, vu, il, iu, abstol, m, w, z, ldz, work, lwork, iwork, ifail, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ssyrfs "BLAS_FUNC(ssyrfs)"(char *uplo, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) nogil +cdef void ssyrfs(char *uplo, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_ssyrfs(uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, ferr, berr, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ssysv "BLAS_FUNC(ssysv)"(char *uplo, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, s *work, int *lwork, int *info) nogil +cdef void ssysv(char *uplo, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_ssysv(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ssysvx "BLAS_FUNC(ssysvx)"(char *fact, char *uplo, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *lwork, int *iwork, int *info) nogil +cdef void ssysvx(char *fact, char *uplo, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *lwork, int *iwork, int *info) noexcept nogil: + + _fortran_ssysvx(fact, uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, lwork, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ssyswapr "BLAS_FUNC(ssyswapr)"(char *uplo, int *n, s *a, int *lda, int *i1, int *i2) nogil +cdef void ssyswapr(char *uplo, int *n, s *a, int *lda, int *i1, int *i2) noexcept nogil: + + _fortran_ssyswapr(uplo, n, a, lda, i1, i2) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ssytd2 "BLAS_FUNC(ssytd2)"(char *uplo, int *n, s *a, int *lda, s *d, s *e, s *tau, int *info) nogil +cdef void ssytd2(char *uplo, int *n, s *a, int *lda, s *d, s *e, s *tau, int *info) noexcept nogil: + + _fortran_ssytd2(uplo, n, a, lda, d, e, tau, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ssytf2 "BLAS_FUNC(ssytf2)"(char *uplo, int *n, s *a, int *lda, int *ipiv, int *info) nogil +cdef void ssytf2(char *uplo, int *n, s *a, int *lda, int *ipiv, int *info) noexcept nogil: + + _fortran_ssytf2(uplo, n, a, lda, ipiv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ssytrd "BLAS_FUNC(ssytrd)"(char *uplo, int *n, s *a, int *lda, s *d, s *e, s *tau, s *work, int *lwork, int *info) nogil +cdef void ssytrd(char *uplo, int *n, s *a, int *lda, s *d, s *e, s *tau, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_ssytrd(uplo, n, a, lda, d, e, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ssytrf "BLAS_FUNC(ssytrf)"(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *lwork, int *info) nogil +cdef void ssytrf(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_ssytrf(uplo, n, a, lda, ipiv, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ssytri "BLAS_FUNC(ssytri)"(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *info) nogil +cdef void ssytri(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *info) noexcept nogil: + + _fortran_ssytri(uplo, n, a, lda, ipiv, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ssytri2 "BLAS_FUNC(ssytri2)"(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *lwork, int *info) nogil +cdef void ssytri2(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_ssytri2(uplo, n, a, lda, ipiv, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ssytri2x "BLAS_FUNC(ssytri2x)"(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *nb, int *info) nogil +cdef void ssytri2x(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *nb, int *info) noexcept nogil: + + _fortran_ssytri2x(uplo, n, a, lda, ipiv, work, nb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ssytrs "BLAS_FUNC(ssytrs)"(char *uplo, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, int *info) nogil +cdef void ssytrs(char *uplo, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, int *info) noexcept nogil: + + _fortran_ssytrs(uplo, n, nrhs, a, lda, ipiv, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ssytrs2 "BLAS_FUNC(ssytrs2)"(char *uplo, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, s *work, int *info) nogil +cdef void ssytrs2(char *uplo, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, s *work, int *info) noexcept nogil: + + _fortran_ssytrs2(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_stbcon "BLAS_FUNC(stbcon)"(char *norm, char *uplo, char *diag, int *n, int *kd, s *ab, int *ldab, s *rcond, s *work, int *iwork, int *info) nogil +cdef void stbcon(char *norm, char *uplo, char *diag, int *n, int *kd, s *ab, int *ldab, s *rcond, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_stbcon(norm, uplo, diag, n, kd, ab, ldab, rcond, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_stbrfs "BLAS_FUNC(stbrfs)"(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) nogil +cdef void stbrfs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_stbrfs(uplo, trans, diag, n, kd, nrhs, ab, ldab, b, ldb, x, ldx, ferr, berr, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_stbtrs "BLAS_FUNC(stbtrs)"(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, int *info) nogil +cdef void stbtrs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, int *info) noexcept nogil: + + _fortran_stbtrs(uplo, trans, diag, n, kd, nrhs, ab, ldab, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_stfsm "BLAS_FUNC(stfsm)"(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, s *alpha, s *a, s *b, int *ldb) nogil +cdef void stfsm(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, s *alpha, s *a, s *b, int *ldb) noexcept nogil: + + _fortran_stfsm(transr, side, uplo, trans, diag, m, n, alpha, a, b, ldb) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_stftri "BLAS_FUNC(stftri)"(char *transr, char *uplo, char *diag, int *n, s *a, int *info) nogil +cdef void stftri(char *transr, char *uplo, char *diag, int *n, s *a, int *info) noexcept nogil: + + _fortran_stftri(transr, uplo, diag, n, a, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_stfttp "BLAS_FUNC(stfttp)"(char *transr, char *uplo, int *n, s *arf, s *ap, int *info) nogil +cdef void stfttp(char *transr, char *uplo, int *n, s *arf, s *ap, int *info) noexcept nogil: + + _fortran_stfttp(transr, uplo, n, arf, ap, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_stfttr "BLAS_FUNC(stfttr)"(char *transr, char *uplo, int *n, s *arf, s *a, int *lda, int *info) nogil +cdef void stfttr(char *transr, char *uplo, int *n, s *arf, s *a, int *lda, int *info) noexcept nogil: + + _fortran_stfttr(transr, uplo, n, arf, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_stgevc "BLAS_FUNC(stgevc)"(char *side, char *howmny, bint *select, int *n, s *s, int *lds, s *p, int *ldp, s *vl, int *ldvl, s *vr, int *ldvr, int *mm, int *m, s *work, int *info) nogil +cdef void stgevc(char *side, char *howmny, bint *select, int *n, s *s, int *lds, s *p, int *ldp, s *vl, int *ldvl, s *vr, int *ldvr, int *mm, int *m, s *work, int *info) noexcept nogil: + + _fortran_stgevc(side, howmny, select, n, s, lds, p, ldp, vl, ldvl, vr, ldvr, mm, m, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_stgex2 "BLAS_FUNC(stgex2)"(bint *wantq, bint *wantz, int *n, s *a, int *lda, s *b, int *ldb, s *q, int *ldq, s *z, int *ldz, int *j1, int *n1, int *n2, s *work, int *lwork, int *info) nogil +cdef void stgex2(bint *wantq, bint *wantz, int *n, s *a, int *lda, s *b, int *ldb, s *q, int *ldq, s *z, int *ldz, int *j1, int *n1, int *n2, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_stgex2(wantq, wantz, n, a, lda, b, ldb, q, ldq, z, ldz, j1, n1, n2, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_stgexc "BLAS_FUNC(stgexc)"(bint *wantq, bint *wantz, int *n, s *a, int *lda, s *b, int *ldb, s *q, int *ldq, s *z, int *ldz, int *ifst, int *ilst, s *work, int *lwork, int *info) nogil +cdef void stgexc(bint *wantq, bint *wantz, int *n, s *a, int *lda, s *b, int *ldb, s *q, int *ldq, s *z, int *ldz, int *ifst, int *ilst, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_stgexc(wantq, wantz, n, a, lda, b, ldb, q, ldq, z, ldz, ifst, ilst, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_stgsen "BLAS_FUNC(stgsen)"(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, s *a, int *lda, s *b, int *ldb, s *alphar, s *alphai, s *beta, s *q, int *ldq, s *z, int *ldz, int *m, s *pl, s *pr, s *dif, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil +cdef void stgsen(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, s *a, int *lda, s *b, int *ldb, s *alphar, s *alphai, s *beta, s *q, int *ldq, s *z, int *ldz, int *m, s *pl, s *pr, s *dif, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_stgsen(ijob, wantq, wantz, select, n, a, lda, b, ldb, alphar, alphai, beta, q, ldq, z, ldz, m, pl, pr, dif, work, lwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_stgsja "BLAS_FUNC(stgsja)"(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, s *a, int *lda, s *b, int *ldb, s *tola, s *tolb, s *alpha, s *beta, s *u, int *ldu, s *v, int *ldv, s *q, int *ldq, s *work, int *ncycle, int *info) nogil +cdef void stgsja(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, s *a, int *lda, s *b, int *ldb, s *tola, s *tolb, s *alpha, s *beta, s *u, int *ldu, s *v, int *ldv, s *q, int *ldq, s *work, int *ncycle, int *info) noexcept nogil: + + _fortran_stgsja(jobu, jobv, jobq, m, p, n, k, l, a, lda, b, ldb, tola, tolb, alpha, beta, u, ldu, v, ldv, q, ldq, work, ncycle, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_stgsna "BLAS_FUNC(stgsna)"(char *job, char *howmny, bint *select, int *n, s *a, int *lda, s *b, int *ldb, s *vl, int *ldvl, s *vr, int *ldvr, s *s, s *dif, int *mm, int *m, s *work, int *lwork, int *iwork, int *info) nogil +cdef void stgsna(char *job, char *howmny, bint *select, int *n, s *a, int *lda, s *b, int *ldb, s *vl, int *ldvl, s *vr, int *ldvr, s *s, s *dif, int *mm, int *m, s *work, int *lwork, int *iwork, int *info) noexcept nogil: + + _fortran_stgsna(job, howmny, select, n, a, lda, b, ldb, vl, ldvl, vr, ldvr, s, dif, mm, m, work, lwork, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_stgsy2 "BLAS_FUNC(stgsy2)"(char *trans, int *ijob, int *m, int *n, s *a, int *lda, s *b, int *ldb, s *c, int *ldc, s *d, int *ldd, s *e, int *lde, s *f, int *ldf, s *scale, s *rdsum, s *rdscal, int *iwork, int *pq, int *info) nogil +cdef void stgsy2(char *trans, int *ijob, int *m, int *n, s *a, int *lda, s *b, int *ldb, s *c, int *ldc, s *d, int *ldd, s *e, int *lde, s *f, int *ldf, s *scale, s *rdsum, s *rdscal, int *iwork, int *pq, int *info) noexcept nogil: + + _fortran_stgsy2(trans, ijob, m, n, a, lda, b, ldb, c, ldc, d, ldd, e, lde, f, ldf, scale, rdsum, rdscal, iwork, pq, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_stgsyl "BLAS_FUNC(stgsyl)"(char *trans, int *ijob, int *m, int *n, s *a, int *lda, s *b, int *ldb, s *c, int *ldc, s *d, int *ldd, s *e, int *lde, s *f, int *ldf, s *scale, s *dif, s *work, int *lwork, int *iwork, int *info) nogil +cdef void stgsyl(char *trans, int *ijob, int *m, int *n, s *a, int *lda, s *b, int *ldb, s *c, int *ldc, s *d, int *ldd, s *e, int *lde, s *f, int *ldf, s *scale, s *dif, s *work, int *lwork, int *iwork, int *info) noexcept nogil: + + _fortran_stgsyl(trans, ijob, m, n, a, lda, b, ldb, c, ldc, d, ldd, e, lde, f, ldf, scale, dif, work, lwork, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_stpcon "BLAS_FUNC(stpcon)"(char *norm, char *uplo, char *diag, int *n, s *ap, s *rcond, s *work, int *iwork, int *info) nogil +cdef void stpcon(char *norm, char *uplo, char *diag, int *n, s *ap, s *rcond, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_stpcon(norm, uplo, diag, n, ap, rcond, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_stpmqrt "BLAS_FUNC(stpmqrt)"(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, s *v, int *ldv, s *t, int *ldt, s *a, int *lda, s *b, int *ldb, s *work, int *info) nogil +cdef void stpmqrt(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, s *v, int *ldv, s *t, int *ldt, s *a, int *lda, s *b, int *ldb, s *work, int *info) noexcept nogil: + + _fortran_stpmqrt(side, trans, m, n, k, l, nb, v, ldv, t, ldt, a, lda, b, ldb, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_stpqrt "BLAS_FUNC(stpqrt)"(int *m, int *n, int *l, int *nb, s *a, int *lda, s *b, int *ldb, s *t, int *ldt, s *work, int *info) nogil +cdef void stpqrt(int *m, int *n, int *l, int *nb, s *a, int *lda, s *b, int *ldb, s *t, int *ldt, s *work, int *info) noexcept nogil: + + _fortran_stpqrt(m, n, l, nb, a, lda, b, ldb, t, ldt, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_stpqrt2 "BLAS_FUNC(stpqrt2)"(int *m, int *n, int *l, s *a, int *lda, s *b, int *ldb, s *t, int *ldt, int *info) nogil +cdef void stpqrt2(int *m, int *n, int *l, s *a, int *lda, s *b, int *ldb, s *t, int *ldt, int *info) noexcept nogil: + + _fortran_stpqrt2(m, n, l, a, lda, b, ldb, t, ldt, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_stprfb "BLAS_FUNC(stprfb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, s *v, int *ldv, s *t, int *ldt, s *a, int *lda, s *b, int *ldb, s *work, int *ldwork) nogil +cdef void stprfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, s *v, int *ldv, s *t, int *ldt, s *a, int *lda, s *b, int *ldb, s *work, int *ldwork) noexcept nogil: + + _fortran_stprfb(side, trans, direct, storev, m, n, k, l, v, ldv, t, ldt, a, lda, b, ldb, work, ldwork) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_stprfs "BLAS_FUNC(stprfs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *ap, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) nogil +cdef void stprfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *ap, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_stprfs(uplo, trans, diag, n, nrhs, ap, b, ldb, x, ldx, ferr, berr, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_stptri "BLAS_FUNC(stptri)"(char *uplo, char *diag, int *n, s *ap, int *info) nogil +cdef void stptri(char *uplo, char *diag, int *n, s *ap, int *info) noexcept nogil: + + _fortran_stptri(uplo, diag, n, ap, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_stptrs "BLAS_FUNC(stptrs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *ap, s *b, int *ldb, int *info) nogil +cdef void stptrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *ap, s *b, int *ldb, int *info) noexcept nogil: + + _fortran_stptrs(uplo, trans, diag, n, nrhs, ap, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_stpttf "BLAS_FUNC(stpttf)"(char *transr, char *uplo, int *n, s *ap, s *arf, int *info) nogil +cdef void stpttf(char *transr, char *uplo, int *n, s *ap, s *arf, int *info) noexcept nogil: + + _fortran_stpttf(transr, uplo, n, ap, arf, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_stpttr "BLAS_FUNC(stpttr)"(char *uplo, int *n, s *ap, s *a, int *lda, int *info) nogil +cdef void stpttr(char *uplo, int *n, s *ap, s *a, int *lda, int *info) noexcept nogil: + + _fortran_stpttr(uplo, n, ap, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_strcon "BLAS_FUNC(strcon)"(char *norm, char *uplo, char *diag, int *n, s *a, int *lda, s *rcond, s *work, int *iwork, int *info) nogil +cdef void strcon(char *norm, char *uplo, char *diag, int *n, s *a, int *lda, s *rcond, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_strcon(norm, uplo, diag, n, a, lda, rcond, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_strevc "BLAS_FUNC(strevc)"(char *side, char *howmny, bint *select, int *n, s *t, int *ldt, s *vl, int *ldvl, s *vr, int *ldvr, int *mm, int *m, s *work, int *info) nogil +cdef void strevc(char *side, char *howmny, bint *select, int *n, s *t, int *ldt, s *vl, int *ldvl, s *vr, int *ldvr, int *mm, int *m, s *work, int *info) noexcept nogil: + + _fortran_strevc(side, howmny, select, n, t, ldt, vl, ldvl, vr, ldvr, mm, m, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_strexc "BLAS_FUNC(strexc)"(char *compq, int *n, s *t, int *ldt, s *q, int *ldq, int *ifst, int *ilst, s *work, int *info) nogil +cdef void strexc(char *compq, int *n, s *t, int *ldt, s *q, int *ldq, int *ifst, int *ilst, s *work, int *info) noexcept nogil: + + _fortran_strexc(compq, n, t, ldt, q, ldq, ifst, ilst, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_strrfs "BLAS_FUNC(strrfs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) nogil +cdef void strrfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil: + + _fortran_strrfs(uplo, trans, diag, n, nrhs, a, lda, b, ldb, x, ldx, ferr, berr, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_strsen "BLAS_FUNC(strsen)"(char *job, char *compq, bint *select, int *n, s *t, int *ldt, s *q, int *ldq, s *wr, s *wi, int *m, s *s, s *sep, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil +cdef void strsen(char *job, char *compq, bint *select, int *n, s *t, int *ldt, s *q, int *ldq, s *wr, s *wi, int *m, s *s, s *sep, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_strsen(job, compq, select, n, t, ldt, q, ldq, wr, wi, m, s, sep, work, lwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_strsna "BLAS_FUNC(strsna)"(char *job, char *howmny, bint *select, int *n, s *t, int *ldt, s *vl, int *ldvl, s *vr, int *ldvr, s *s, s *sep, int *mm, int *m, s *work, int *ldwork, int *iwork, int *info) nogil +cdef void strsna(char *job, char *howmny, bint *select, int *n, s *t, int *ldt, s *vl, int *ldvl, s *vr, int *ldvr, s *s, s *sep, int *mm, int *m, s *work, int *ldwork, int *iwork, int *info) noexcept nogil: + + _fortran_strsna(job, howmny, select, n, t, ldt, vl, ldvl, vr, ldvr, s, sep, mm, m, work, ldwork, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_strsyl "BLAS_FUNC(strsyl)"(char *trana, char *tranb, int *isgn, int *m, int *n, s *a, int *lda, s *b, int *ldb, s *c, int *ldc, s *scale, int *info) nogil +cdef void strsyl(char *trana, char *tranb, int *isgn, int *m, int *n, s *a, int *lda, s *b, int *ldb, s *c, int *ldc, s *scale, int *info) noexcept nogil: + + _fortran_strsyl(trana, tranb, isgn, m, n, a, lda, b, ldb, c, ldc, scale, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_strti2 "BLAS_FUNC(strti2)"(char *uplo, char *diag, int *n, s *a, int *lda, int *info) nogil +cdef void strti2(char *uplo, char *diag, int *n, s *a, int *lda, int *info) noexcept nogil: + + _fortran_strti2(uplo, diag, n, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_strtri "BLAS_FUNC(strtri)"(char *uplo, char *diag, int *n, s *a, int *lda, int *info) nogil +cdef void strtri(char *uplo, char *diag, int *n, s *a, int *lda, int *info) noexcept nogil: + + _fortran_strtri(uplo, diag, n, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_strtrs "BLAS_FUNC(strtrs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *info) nogil +cdef void strtrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *info) noexcept nogil: + + _fortran_strtrs(uplo, trans, diag, n, nrhs, a, lda, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_strttf "BLAS_FUNC(strttf)"(char *transr, char *uplo, int *n, s *a, int *lda, s *arf, int *info) nogil +cdef void strttf(char *transr, char *uplo, int *n, s *a, int *lda, s *arf, int *info) noexcept nogil: + + _fortran_strttf(transr, uplo, n, a, lda, arf, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_strttp "BLAS_FUNC(strttp)"(char *uplo, int *n, s *a, int *lda, s *ap, int *info) nogil +cdef void strttp(char *uplo, int *n, s *a, int *lda, s *ap, int *info) noexcept nogil: + + _fortran_strttp(uplo, n, a, lda, ap, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_stzrzf "BLAS_FUNC(stzrzf)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil +cdef void stzrzf(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil: + + _fortran_stzrzf(m, n, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_xerbla_array "BLAS_FUNC(xerbla_array)"(char *srname_array, int *srname_len, int *info) nogil +cdef void xerbla_array(char *srname_array, int *srname_len, int *info) noexcept nogil: + + _fortran_xerbla_array(srname_array, srname_len, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zbbcsd "BLAS_FUNC(zbbcsd)"(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, d *theta, d *phi, npy_complex128 *u1, int *ldu1, npy_complex128 *u2, int *ldu2, npy_complex128 *v1t, int *ldv1t, npy_complex128 *v2t, int *ldv2t, d *b11d, d *b11e, d *b12d, d *b12e, d *b21d, d *b21e, d *b22d, d *b22e, d *rwork, int *lrwork, int *info) nogil +cdef void zbbcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, d *theta, d *phi, z *u1, int *ldu1, z *u2, int *ldu2, z *v1t, int *ldv1t, z *v2t, int *ldv2t, d *b11d, d *b11e, d *b12d, d *b12e, d *b21d, d *b21e, d *b22d, d *b22e, d *rwork, int *lrwork, int *info) noexcept nogil: + + _fortran_zbbcsd(jobu1, jobu2, jobv1t, jobv2t, trans, m, p, q, theta, phi, u1, ldu1, u2, ldu2, v1t, ldv1t, v2t, ldv2t, b11d, b11e, b12d, b12e, b21d, b21e, b22d, b22e, rwork, lrwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zbdsqr "BLAS_FUNC(zbdsqr)"(char *uplo, int *n, int *ncvt, int *nru, int *ncc, d *d, d *e, npy_complex128 *vt, int *ldvt, npy_complex128 *u, int *ldu, npy_complex128 *c, int *ldc, d *rwork, int *info) nogil +cdef void zbdsqr(char *uplo, int *n, int *ncvt, int *nru, int *ncc, d *d, d *e, z *vt, int *ldvt, z *u, int *ldu, z *c, int *ldc, d *rwork, int *info) noexcept nogil: + + _fortran_zbdsqr(uplo, n, ncvt, nru, ncc, d, e, vt, ldvt, u, ldu, c, ldc, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zcgesv "BLAS_FUNC(zcgesv)"(int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, npy_complex128 *work, npy_complex64 *swork, d *rwork, int *iter, int *info) nogil +cdef void zcgesv(int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, z *x, int *ldx, z *work, c *swork, d *rwork, int *iter, int *info) noexcept nogil: + + _fortran_zcgesv(n, nrhs, a, lda, ipiv, b, ldb, x, ldx, work, swork, rwork, iter, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zcposv "BLAS_FUNC(zcposv)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, npy_complex128 *work, npy_complex64 *swork, d *rwork, int *iter, int *info) nogil +cdef void zcposv(char *uplo, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, z *x, int *ldx, z *work, c *swork, d *rwork, int *iter, int *info) noexcept nogil: + + _fortran_zcposv(uplo, n, nrhs, a, lda, b, ldb, x, ldx, work, swork, rwork, iter, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zdrscl "BLAS_FUNC(zdrscl)"(int *n, d *sa, npy_complex128 *sx, int *incx) nogil +cdef void zdrscl(int *n, d *sa, z *sx, int *incx) noexcept nogil: + + _fortran_zdrscl(n, sa, sx, incx) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgbbrd "BLAS_FUNC(zgbbrd)"(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, npy_complex128 *ab, int *ldab, d *d, d *e, npy_complex128 *q, int *ldq, npy_complex128 *pt, int *ldpt, npy_complex128 *c, int *ldc, npy_complex128 *work, d *rwork, int *info) nogil +cdef void zgbbrd(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, z *ab, int *ldab, d *d, d *e, z *q, int *ldq, z *pt, int *ldpt, z *c, int *ldc, z *work, d *rwork, int *info) noexcept nogil: + + _fortran_zgbbrd(vect, m, n, ncc, kl, ku, ab, ldab, d, e, q, ldq, pt, ldpt, c, ldc, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgbcon "BLAS_FUNC(zgbcon)"(char *norm, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, int *ipiv, d *anorm, d *rcond, npy_complex128 *work, d *rwork, int *info) nogil +cdef void zgbcon(char *norm, int *n, int *kl, int *ku, z *ab, int *ldab, int *ipiv, d *anorm, d *rcond, z *work, d *rwork, int *info) noexcept nogil: + + _fortran_zgbcon(norm, n, kl, ku, ab, ldab, ipiv, anorm, rcond, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgbequ "BLAS_FUNC(zgbequ)"(int *m, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) nogil +cdef void zgbequ(int *m, int *n, int *kl, int *ku, z *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil: + + _fortran_zgbequ(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgbequb "BLAS_FUNC(zgbequb)"(int *m, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) nogil +cdef void zgbequb(int *m, int *n, int *kl, int *ku, z *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil: + + _fortran_zgbequb(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgbrfs "BLAS_FUNC(zgbrfs)"(char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *afb, int *ldafb, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil +cdef void zgbrfs(char *trans, int *n, int *kl, int *ku, int *nrhs, z *ab, int *ldab, z *afb, int *ldafb, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil: + + _fortran_zgbrfs(trans, n, kl, ku, nrhs, ab, ldab, afb, ldafb, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgbsv "BLAS_FUNC(zgbsv)"(int *n, int *kl, int *ku, int *nrhs, npy_complex128 *ab, int *ldab, int *ipiv, npy_complex128 *b, int *ldb, int *info) nogil +cdef void zgbsv(int *n, int *kl, int *ku, int *nrhs, z *ab, int *ldab, int *ipiv, z *b, int *ldb, int *info) noexcept nogil: + + _fortran_zgbsv(n, kl, ku, nrhs, ab, ldab, ipiv, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgbsvx "BLAS_FUNC(zgbsvx)"(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *afb, int *ldafb, int *ipiv, char *equed, d *r, d *c, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil +cdef void zgbsvx(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, z *ab, int *ldab, z *afb, int *ldafb, int *ipiv, char *equed, d *r, d *c, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil: + + _fortran_zgbsvx(fact, trans, n, kl, ku, nrhs, ab, ldab, afb, ldafb, ipiv, equed, r, c, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgbtf2 "BLAS_FUNC(zgbtf2)"(int *m, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, int *ipiv, int *info) nogil +cdef void zgbtf2(int *m, int *n, int *kl, int *ku, z *ab, int *ldab, int *ipiv, int *info) noexcept nogil: + + _fortran_zgbtf2(m, n, kl, ku, ab, ldab, ipiv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgbtrf "BLAS_FUNC(zgbtrf)"(int *m, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, int *ipiv, int *info) nogil +cdef void zgbtrf(int *m, int *n, int *kl, int *ku, z *ab, int *ldab, int *ipiv, int *info) noexcept nogil: + + _fortran_zgbtrf(m, n, kl, ku, ab, ldab, ipiv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgbtrs "BLAS_FUNC(zgbtrs)"(char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex128 *ab, int *ldab, int *ipiv, npy_complex128 *b, int *ldb, int *info) nogil +cdef void zgbtrs(char *trans, int *n, int *kl, int *ku, int *nrhs, z *ab, int *ldab, int *ipiv, z *b, int *ldb, int *info) noexcept nogil: + + _fortran_zgbtrs(trans, n, kl, ku, nrhs, ab, ldab, ipiv, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgebak "BLAS_FUNC(zgebak)"(char *job, char *side, int *n, int *ilo, int *ihi, d *scale, int *m, npy_complex128 *v, int *ldv, int *info) nogil +cdef void zgebak(char *job, char *side, int *n, int *ilo, int *ihi, d *scale, int *m, z *v, int *ldv, int *info) noexcept nogil: + + _fortran_zgebak(job, side, n, ilo, ihi, scale, m, v, ldv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgebal "BLAS_FUNC(zgebal)"(char *job, int *n, npy_complex128 *a, int *lda, int *ilo, int *ihi, d *scale, int *info) nogil +cdef void zgebal(char *job, int *n, z *a, int *lda, int *ilo, int *ihi, d *scale, int *info) noexcept nogil: + + _fortran_zgebal(job, n, a, lda, ilo, ihi, scale, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgebd2 "BLAS_FUNC(zgebd2)"(int *m, int *n, npy_complex128 *a, int *lda, d *d, d *e, npy_complex128 *tauq, npy_complex128 *taup, npy_complex128 *work, int *info) nogil +cdef void zgebd2(int *m, int *n, z *a, int *lda, d *d, d *e, z *tauq, z *taup, z *work, int *info) noexcept nogil: + + _fortran_zgebd2(m, n, a, lda, d, e, tauq, taup, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgebrd "BLAS_FUNC(zgebrd)"(int *m, int *n, npy_complex128 *a, int *lda, d *d, d *e, npy_complex128 *tauq, npy_complex128 *taup, npy_complex128 *work, int *lwork, int *info) nogil +cdef void zgebrd(int *m, int *n, z *a, int *lda, d *d, d *e, z *tauq, z *taup, z *work, int *lwork, int *info) noexcept nogil: + + _fortran_zgebrd(m, n, a, lda, d, e, tauq, taup, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgecon "BLAS_FUNC(zgecon)"(char *norm, int *n, npy_complex128 *a, int *lda, d *anorm, d *rcond, npy_complex128 *work, d *rwork, int *info) nogil +cdef void zgecon(char *norm, int *n, z *a, int *lda, d *anorm, d *rcond, z *work, d *rwork, int *info) noexcept nogil: + + _fortran_zgecon(norm, n, a, lda, anorm, rcond, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgeequ "BLAS_FUNC(zgeequ)"(int *m, int *n, npy_complex128 *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) nogil +cdef void zgeequ(int *m, int *n, z *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil: + + _fortran_zgeequ(m, n, a, lda, r, c, rowcnd, colcnd, amax, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgeequb "BLAS_FUNC(zgeequb)"(int *m, int *n, npy_complex128 *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) nogil +cdef void zgeequb(int *m, int *n, z *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil: + + _fortran_zgeequb(m, n, a, lda, r, c, rowcnd, colcnd, amax, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgees "BLAS_FUNC(zgees)"(char *jobvs, char *sort, _zselect1 *select, int *n, npy_complex128 *a, int *lda, int *sdim, npy_complex128 *w, npy_complex128 *vs, int *ldvs, npy_complex128 *work, int *lwork, d *rwork, bint *bwork, int *info) nogil +cdef void zgees(char *jobvs, char *sort, zselect1 *select, int *n, z *a, int *lda, int *sdim, z *w, z *vs, int *ldvs, z *work, int *lwork, d *rwork, bint *bwork, int *info) noexcept nogil: + + _fortran_zgees(jobvs, sort, <_zselect1*>select, n, a, lda, sdim, w, vs, ldvs, work, lwork, rwork, bwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgeesx "BLAS_FUNC(zgeesx)"(char *jobvs, char *sort, _zselect1 *select, char *sense, int *n, npy_complex128 *a, int *lda, int *sdim, npy_complex128 *w, npy_complex128 *vs, int *ldvs, d *rconde, d *rcondv, npy_complex128 *work, int *lwork, d *rwork, bint *bwork, int *info) nogil +cdef void zgeesx(char *jobvs, char *sort, zselect1 *select, char *sense, int *n, z *a, int *lda, int *sdim, z *w, z *vs, int *ldvs, d *rconde, d *rcondv, z *work, int *lwork, d *rwork, bint *bwork, int *info) noexcept nogil: + + _fortran_zgeesx(jobvs, sort, <_zselect1*>select, sense, n, a, lda, sdim, w, vs, ldvs, rconde, rcondv, work, lwork, rwork, bwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgeev "BLAS_FUNC(zgeev)"(char *jobvl, char *jobvr, int *n, npy_complex128 *a, int *lda, npy_complex128 *w, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, npy_complex128 *work, int *lwork, d *rwork, int *info) nogil +cdef void zgeev(char *jobvl, char *jobvr, int *n, z *a, int *lda, z *w, z *vl, int *ldvl, z *vr, int *ldvr, z *work, int *lwork, d *rwork, int *info) noexcept nogil: + + _fortran_zgeev(jobvl, jobvr, n, a, lda, w, vl, ldvl, vr, ldvr, work, lwork, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgeevx "BLAS_FUNC(zgeevx)"(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, npy_complex128 *a, int *lda, npy_complex128 *w, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, int *ilo, int *ihi, d *scale, d *abnrm, d *rconde, d *rcondv, npy_complex128 *work, int *lwork, d *rwork, int *info) nogil +cdef void zgeevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, z *a, int *lda, z *w, z *vl, int *ldvl, z *vr, int *ldvr, int *ilo, int *ihi, d *scale, d *abnrm, d *rconde, d *rcondv, z *work, int *lwork, d *rwork, int *info) noexcept nogil: + + _fortran_zgeevx(balanc, jobvl, jobvr, sense, n, a, lda, w, vl, ldvl, vr, ldvr, ilo, ihi, scale, abnrm, rconde, rcondv, work, lwork, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgehd2 "BLAS_FUNC(zgehd2)"(int *n, int *ilo, int *ihi, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info) nogil +cdef void zgehd2(int *n, int *ilo, int *ihi, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil: + + _fortran_zgehd2(n, ilo, ihi, a, lda, tau, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgehrd "BLAS_FUNC(zgehrd)"(int *n, int *ilo, int *ihi, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil +cdef void zgehrd(int *n, int *ilo, int *ihi, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil: + + _fortran_zgehrd(n, ilo, ihi, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgelq2 "BLAS_FUNC(zgelq2)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info) nogil +cdef void zgelq2(int *m, int *n, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil: + + _fortran_zgelq2(m, n, a, lda, tau, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgelqf "BLAS_FUNC(zgelqf)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil +cdef void zgelqf(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil: + + _fortran_zgelqf(m, n, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgels "BLAS_FUNC(zgels)"(char *trans, int *m, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *work, int *lwork, int *info) nogil +cdef void zgels(char *trans, int *m, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, z *work, int *lwork, int *info) noexcept nogil: + + _fortran_zgels(trans, m, n, nrhs, a, lda, b, ldb, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgelsd "BLAS_FUNC(zgelsd)"(int *m, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, d *s, d *rcond, int *rank, npy_complex128 *work, int *lwork, d *rwork, int *iwork, int *info) nogil +cdef void zgelsd(int *m, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, d *s, d *rcond, int *rank, z *work, int *lwork, d *rwork, int *iwork, int *info) noexcept nogil: + + _fortran_zgelsd(m, n, nrhs, a, lda, b, ldb, s, rcond, rank, work, lwork, rwork, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgelss "BLAS_FUNC(zgelss)"(int *m, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, d *s, d *rcond, int *rank, npy_complex128 *work, int *lwork, d *rwork, int *info) nogil +cdef void zgelss(int *m, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, d *s, d *rcond, int *rank, z *work, int *lwork, d *rwork, int *info) noexcept nogil: + + _fortran_zgelss(m, n, nrhs, a, lda, b, ldb, s, rcond, rank, work, lwork, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgelsy "BLAS_FUNC(zgelsy)"(int *m, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *jpvt, d *rcond, int *rank, npy_complex128 *work, int *lwork, d *rwork, int *info) nogil +cdef void zgelsy(int *m, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, int *jpvt, d *rcond, int *rank, z *work, int *lwork, d *rwork, int *info) noexcept nogil: + + _fortran_zgelsy(m, n, nrhs, a, lda, b, ldb, jpvt, rcond, rank, work, lwork, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgemqrt "BLAS_FUNC(zgemqrt)"(char *side, char *trans, int *m, int *n, int *k, int *nb, npy_complex128 *v, int *ldv, npy_complex128 *t, int *ldt, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info) nogil +cdef void zgemqrt(char *side, char *trans, int *m, int *n, int *k, int *nb, z *v, int *ldv, z *t, int *ldt, z *c, int *ldc, z *work, int *info) noexcept nogil: + + _fortran_zgemqrt(side, trans, m, n, k, nb, v, ldv, t, ldt, c, ldc, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgeql2 "BLAS_FUNC(zgeql2)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info) nogil +cdef void zgeql2(int *m, int *n, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil: + + _fortran_zgeql2(m, n, a, lda, tau, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgeqlf "BLAS_FUNC(zgeqlf)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil +cdef void zgeqlf(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil: + + _fortran_zgeqlf(m, n, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgeqp3 "BLAS_FUNC(zgeqp3)"(int *m, int *n, npy_complex128 *a, int *lda, int *jpvt, npy_complex128 *tau, npy_complex128 *work, int *lwork, d *rwork, int *info) nogil +cdef void zgeqp3(int *m, int *n, z *a, int *lda, int *jpvt, z *tau, z *work, int *lwork, d *rwork, int *info) noexcept nogil: + + _fortran_zgeqp3(m, n, a, lda, jpvt, tau, work, lwork, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgeqr2 "BLAS_FUNC(zgeqr2)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info) nogil +cdef void zgeqr2(int *m, int *n, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil: + + _fortran_zgeqr2(m, n, a, lda, tau, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgeqr2p "BLAS_FUNC(zgeqr2p)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info) nogil +cdef void zgeqr2p(int *m, int *n, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil: + + _fortran_zgeqr2p(m, n, a, lda, tau, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgeqrf "BLAS_FUNC(zgeqrf)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil +cdef void zgeqrf(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil: + + _fortran_zgeqrf(m, n, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgeqrfp "BLAS_FUNC(zgeqrfp)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil +cdef void zgeqrfp(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil: + + _fortran_zgeqrfp(m, n, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgeqrt "BLAS_FUNC(zgeqrt)"(int *m, int *n, int *nb, npy_complex128 *a, int *lda, npy_complex128 *t, int *ldt, npy_complex128 *work, int *info) nogil +cdef void zgeqrt(int *m, int *n, int *nb, z *a, int *lda, z *t, int *ldt, z *work, int *info) noexcept nogil: + + _fortran_zgeqrt(m, n, nb, a, lda, t, ldt, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgeqrt2 "BLAS_FUNC(zgeqrt2)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *t, int *ldt, int *info) nogil +cdef void zgeqrt2(int *m, int *n, z *a, int *lda, z *t, int *ldt, int *info) noexcept nogil: + + _fortran_zgeqrt2(m, n, a, lda, t, ldt, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgeqrt3 "BLAS_FUNC(zgeqrt3)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *t, int *ldt, int *info) nogil +cdef void zgeqrt3(int *m, int *n, z *a, int *lda, z *t, int *ldt, int *info) noexcept nogil: + + _fortran_zgeqrt3(m, n, a, lda, t, ldt, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgerfs "BLAS_FUNC(zgerfs)"(char *trans, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil +cdef void zgerfs(char *trans, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil: + + _fortran_zgerfs(trans, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgerq2 "BLAS_FUNC(zgerq2)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info) nogil +cdef void zgerq2(int *m, int *n, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil: + + _fortran_zgerq2(m, n, a, lda, tau, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgerqf "BLAS_FUNC(zgerqf)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil +cdef void zgerqf(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil: + + _fortran_zgerqf(m, n, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgesc2 "BLAS_FUNC(zgesc2)"(int *n, npy_complex128 *a, int *lda, npy_complex128 *rhs, int *ipiv, int *jpiv, d *scale) nogil +cdef void zgesc2(int *n, z *a, int *lda, z *rhs, int *ipiv, int *jpiv, d *scale) noexcept nogil: + + _fortran_zgesc2(n, a, lda, rhs, ipiv, jpiv, scale) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgesdd "BLAS_FUNC(zgesdd)"(char *jobz, int *m, int *n, npy_complex128 *a, int *lda, d *s, npy_complex128 *u, int *ldu, npy_complex128 *vt, int *ldvt, npy_complex128 *work, int *lwork, d *rwork, int *iwork, int *info) nogil +cdef void zgesdd(char *jobz, int *m, int *n, z *a, int *lda, d *s, z *u, int *ldu, z *vt, int *ldvt, z *work, int *lwork, d *rwork, int *iwork, int *info) noexcept nogil: + + _fortran_zgesdd(jobz, m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork, rwork, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgesv "BLAS_FUNC(zgesv)"(int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, int *info) nogil +cdef void zgesv(int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, int *info) noexcept nogil: + + _fortran_zgesv(n, nrhs, a, lda, ipiv, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgesvd "BLAS_FUNC(zgesvd)"(char *jobu, char *jobvt, int *m, int *n, npy_complex128 *a, int *lda, d *s, npy_complex128 *u, int *ldu, npy_complex128 *vt, int *ldvt, npy_complex128 *work, int *lwork, d *rwork, int *info) nogil +cdef void zgesvd(char *jobu, char *jobvt, int *m, int *n, z *a, int *lda, d *s, z *u, int *ldu, z *vt, int *ldvt, z *work, int *lwork, d *rwork, int *info) noexcept nogil: + + _fortran_zgesvd(jobu, jobvt, m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgesvx "BLAS_FUNC(zgesvx)"(char *fact, char *trans, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, char *equed, d *r, d *c, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil +cdef void zgesvx(char *fact, char *trans, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, char *equed, d *r, d *c, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil: + + _fortran_zgesvx(fact, trans, n, nrhs, a, lda, af, ldaf, ipiv, equed, r, c, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgetc2 "BLAS_FUNC(zgetc2)"(int *n, npy_complex128 *a, int *lda, int *ipiv, int *jpiv, int *info) nogil +cdef void zgetc2(int *n, z *a, int *lda, int *ipiv, int *jpiv, int *info) noexcept nogil: + + _fortran_zgetc2(n, a, lda, ipiv, jpiv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgetf2 "BLAS_FUNC(zgetf2)"(int *m, int *n, npy_complex128 *a, int *lda, int *ipiv, int *info) nogil +cdef void zgetf2(int *m, int *n, z *a, int *lda, int *ipiv, int *info) noexcept nogil: + + _fortran_zgetf2(m, n, a, lda, ipiv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgetrf "BLAS_FUNC(zgetrf)"(int *m, int *n, npy_complex128 *a, int *lda, int *ipiv, int *info) nogil +cdef void zgetrf(int *m, int *n, z *a, int *lda, int *ipiv, int *info) noexcept nogil: + + _fortran_zgetrf(m, n, a, lda, ipiv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgetri "BLAS_FUNC(zgetri)"(int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *lwork, int *info) nogil +cdef void zgetri(int *n, z *a, int *lda, int *ipiv, z *work, int *lwork, int *info) noexcept nogil: + + _fortran_zgetri(n, a, lda, ipiv, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgetrs "BLAS_FUNC(zgetrs)"(char *trans, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, int *info) nogil +cdef void zgetrs(char *trans, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, int *info) noexcept nogil: + + _fortran_zgetrs(trans, n, nrhs, a, lda, ipiv, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zggbak "BLAS_FUNC(zggbak)"(char *job, char *side, int *n, int *ilo, int *ihi, d *lscale, d *rscale, int *m, npy_complex128 *v, int *ldv, int *info) nogil +cdef void zggbak(char *job, char *side, int *n, int *ilo, int *ihi, d *lscale, d *rscale, int *m, z *v, int *ldv, int *info) noexcept nogil: + + _fortran_zggbak(job, side, n, ilo, ihi, lscale, rscale, m, v, ldv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zggbal "BLAS_FUNC(zggbal)"(char *job, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *ilo, int *ihi, d *lscale, d *rscale, d *work, int *info) nogil +cdef void zggbal(char *job, int *n, z *a, int *lda, z *b, int *ldb, int *ilo, int *ihi, d *lscale, d *rscale, d *work, int *info) noexcept nogil: + + _fortran_zggbal(job, n, a, lda, b, ldb, ilo, ihi, lscale, rscale, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgges "BLAS_FUNC(zgges)"(char *jobvsl, char *jobvsr, char *sort, _zselect2 *selctg, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *sdim, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *vsl, int *ldvsl, npy_complex128 *vsr, int *ldvsr, npy_complex128 *work, int *lwork, d *rwork, bint *bwork, int *info) nogil +cdef void zgges(char *jobvsl, char *jobvsr, char *sort, zselect2 *selctg, int *n, z *a, int *lda, z *b, int *ldb, int *sdim, z *alpha, z *beta, z *vsl, int *ldvsl, z *vsr, int *ldvsr, z *work, int *lwork, d *rwork, bint *bwork, int *info) noexcept nogil: + + _fortran_zgges(jobvsl, jobvsr, sort, <_zselect2*>selctg, n, a, lda, b, ldb, sdim, alpha, beta, vsl, ldvsl, vsr, ldvsr, work, lwork, rwork, bwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zggesx "BLAS_FUNC(zggesx)"(char *jobvsl, char *jobvsr, char *sort, _zselect2 *selctg, char *sense, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *sdim, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *vsl, int *ldvsl, npy_complex128 *vsr, int *ldvsr, d *rconde, d *rcondv, npy_complex128 *work, int *lwork, d *rwork, int *iwork, int *liwork, bint *bwork, int *info) nogil +cdef void zggesx(char *jobvsl, char *jobvsr, char *sort, zselect2 *selctg, char *sense, int *n, z *a, int *lda, z *b, int *ldb, int *sdim, z *alpha, z *beta, z *vsl, int *ldvsl, z *vsr, int *ldvsr, d *rconde, d *rcondv, z *work, int *lwork, d *rwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil: + + _fortran_zggesx(jobvsl, jobvsr, sort, <_zselect2*>selctg, sense, n, a, lda, b, ldb, sdim, alpha, beta, vsl, ldvsl, vsr, ldvsr, rconde, rcondv, work, lwork, rwork, iwork, liwork, bwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zggev "BLAS_FUNC(zggev)"(char *jobvl, char *jobvr, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, npy_complex128 *work, int *lwork, d *rwork, int *info) nogil +cdef void zggev(char *jobvl, char *jobvr, int *n, z *a, int *lda, z *b, int *ldb, z *alpha, z *beta, z *vl, int *ldvl, z *vr, int *ldvr, z *work, int *lwork, d *rwork, int *info) noexcept nogil: + + _fortran_zggev(jobvl, jobvr, n, a, lda, b, ldb, alpha, beta, vl, ldvl, vr, ldvr, work, lwork, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zggevx "BLAS_FUNC(zggevx)"(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, int *ilo, int *ihi, d *lscale, d *rscale, d *abnrm, d *bbnrm, d *rconde, d *rcondv, npy_complex128 *work, int *lwork, d *rwork, int *iwork, bint *bwork, int *info) nogil +cdef void zggevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, z *a, int *lda, z *b, int *ldb, z *alpha, z *beta, z *vl, int *ldvl, z *vr, int *ldvr, int *ilo, int *ihi, d *lscale, d *rscale, d *abnrm, d *bbnrm, d *rconde, d *rcondv, z *work, int *lwork, d *rwork, int *iwork, bint *bwork, int *info) noexcept nogil: + + _fortran_zggevx(balanc, jobvl, jobvr, sense, n, a, lda, b, ldb, alpha, beta, vl, ldvl, vr, ldvr, ilo, ihi, lscale, rscale, abnrm, bbnrm, rconde, rcondv, work, lwork, rwork, iwork, bwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zggglm "BLAS_FUNC(zggglm)"(int *n, int *m, int *p, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *d, npy_complex128 *x, npy_complex128 *y, npy_complex128 *work, int *lwork, int *info) nogil +cdef void zggglm(int *n, int *m, int *p, z *a, int *lda, z *b, int *ldb, z *d, z *x, z *y, z *work, int *lwork, int *info) noexcept nogil: + + _fortran_zggglm(n, m, p, a, lda, b, ldb, d, x, y, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgghrd "BLAS_FUNC(zgghrd)"(char *compq, char *compz, int *n, int *ilo, int *ihi, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *q, int *ldq, npy_complex128 *z, int *ldz, int *info) nogil +cdef void zgghrd(char *compq, char *compz, int *n, int *ilo, int *ihi, z *a, int *lda, z *b, int *ldb, z *q, int *ldq, z *z, int *ldz, int *info) noexcept nogil: + + _fortran_zgghrd(compq, compz, n, ilo, ihi, a, lda, b, ldb, q, ldq, z, ldz, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgglse "BLAS_FUNC(zgglse)"(int *m, int *n, int *p, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *c, npy_complex128 *d, npy_complex128 *x, npy_complex128 *work, int *lwork, int *info) nogil +cdef void zgglse(int *m, int *n, int *p, z *a, int *lda, z *b, int *ldb, z *c, z *d, z *x, z *work, int *lwork, int *info) noexcept nogil: + + _fortran_zgglse(m, n, p, a, lda, b, ldb, c, d, x, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zggqrf "BLAS_FUNC(zggqrf)"(int *n, int *m, int *p, npy_complex128 *a, int *lda, npy_complex128 *taua, npy_complex128 *b, int *ldb, npy_complex128 *taub, npy_complex128 *work, int *lwork, int *info) nogil +cdef void zggqrf(int *n, int *m, int *p, z *a, int *lda, z *taua, z *b, int *ldb, z *taub, z *work, int *lwork, int *info) noexcept nogil: + + _fortran_zggqrf(n, m, p, a, lda, taua, b, ldb, taub, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zggrqf "BLAS_FUNC(zggrqf)"(int *m, int *p, int *n, npy_complex128 *a, int *lda, npy_complex128 *taua, npy_complex128 *b, int *ldb, npy_complex128 *taub, npy_complex128 *work, int *lwork, int *info) nogil +cdef void zggrqf(int *m, int *p, int *n, z *a, int *lda, z *taua, z *b, int *ldb, z *taub, z *work, int *lwork, int *info) noexcept nogil: + + _fortran_zggrqf(m, p, n, a, lda, taua, b, ldb, taub, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgtcon "BLAS_FUNC(zgtcon)"(char *norm, int *n, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *du2, int *ipiv, d *anorm, d *rcond, npy_complex128 *work, int *info) nogil +cdef void zgtcon(char *norm, int *n, z *dl, z *d, z *du, z *du2, int *ipiv, d *anorm, d *rcond, z *work, int *info) noexcept nogil: + + _fortran_zgtcon(norm, n, dl, d, du, du2, ipiv, anorm, rcond, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgtrfs "BLAS_FUNC(zgtrfs)"(char *trans, int *n, int *nrhs, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *dlf, npy_complex128 *df, npy_complex128 *duf, npy_complex128 *du2, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil +cdef void zgtrfs(char *trans, int *n, int *nrhs, z *dl, z *d, z *du, z *dlf, z *df, z *duf, z *du2, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil: + + _fortran_zgtrfs(trans, n, nrhs, dl, d, du, dlf, df, duf, du2, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgtsv "BLAS_FUNC(zgtsv)"(int *n, int *nrhs, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *b, int *ldb, int *info) nogil +cdef void zgtsv(int *n, int *nrhs, z *dl, z *d, z *du, z *b, int *ldb, int *info) noexcept nogil: + + _fortran_zgtsv(n, nrhs, dl, d, du, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgtsvx "BLAS_FUNC(zgtsvx)"(char *fact, char *trans, int *n, int *nrhs, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *dlf, npy_complex128 *df, npy_complex128 *duf, npy_complex128 *du2, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil +cdef void zgtsvx(char *fact, char *trans, int *n, int *nrhs, z *dl, z *d, z *du, z *dlf, z *df, z *duf, z *du2, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil: + + _fortran_zgtsvx(fact, trans, n, nrhs, dl, d, du, dlf, df, duf, du2, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgttrf "BLAS_FUNC(zgttrf)"(int *n, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *du2, int *ipiv, int *info) nogil +cdef void zgttrf(int *n, z *dl, z *d, z *du, z *du2, int *ipiv, int *info) noexcept nogil: + + _fortran_zgttrf(n, dl, d, du, du2, ipiv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgttrs "BLAS_FUNC(zgttrs)"(char *trans, int *n, int *nrhs, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *du2, int *ipiv, npy_complex128 *b, int *ldb, int *info) nogil +cdef void zgttrs(char *trans, int *n, int *nrhs, z *dl, z *d, z *du, z *du2, int *ipiv, z *b, int *ldb, int *info) noexcept nogil: + + _fortran_zgttrs(trans, n, nrhs, dl, d, du, du2, ipiv, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zgtts2 "BLAS_FUNC(zgtts2)"(int *itrans, int *n, int *nrhs, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *du2, int *ipiv, npy_complex128 *b, int *ldb) nogil +cdef void zgtts2(int *itrans, int *n, int *nrhs, z *dl, z *d, z *du, z *du2, int *ipiv, z *b, int *ldb) noexcept nogil: + + _fortran_zgtts2(itrans, n, nrhs, dl, d, du, du2, ipiv, b, ldb) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhbev "BLAS_FUNC(zhbev)"(char *jobz, char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, d *rwork, int *info) nogil +cdef void zhbev(char *jobz, char *uplo, int *n, int *kd, z *ab, int *ldab, d *w, z *z, int *ldz, z *work, d *rwork, int *info) noexcept nogil: + + _fortran_zhbev(jobz, uplo, n, kd, ab, ldab, w, z, ldz, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhbevd "BLAS_FUNC(zhbevd)"(char *jobz, char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil +cdef void zhbevd(char *jobz, char *uplo, int *n, int *kd, z *ab, int *ldab, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_zhbevd(jobz, uplo, n, kd, ab, ldab, w, z, ldz, work, lwork, rwork, lrwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhbevx "BLAS_FUNC(zhbevx)"(char *jobz, char *range, char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, npy_complex128 *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, d *rwork, int *iwork, int *ifail, int *info) nogil +cdef void zhbevx(char *jobz, char *range, char *uplo, int *n, int *kd, z *ab, int *ldab, z *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil: + + _fortran_zhbevx(jobz, range, uplo, n, kd, ab, ldab, q, ldq, vl, vu, il, iu, abstol, m, w, z, ldz, work, rwork, iwork, ifail, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhbgst "BLAS_FUNC(zhbgst)"(char *vect, char *uplo, int *n, int *ka, int *kb, npy_complex128 *ab, int *ldab, npy_complex128 *bb, int *ldbb, npy_complex128 *x, int *ldx, npy_complex128 *work, d *rwork, int *info) nogil +cdef void zhbgst(char *vect, char *uplo, int *n, int *ka, int *kb, z *ab, int *ldab, z *bb, int *ldbb, z *x, int *ldx, z *work, d *rwork, int *info) noexcept nogil: + + _fortran_zhbgst(vect, uplo, n, ka, kb, ab, ldab, bb, ldbb, x, ldx, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhbgv "BLAS_FUNC(zhbgv)"(char *jobz, char *uplo, int *n, int *ka, int *kb, npy_complex128 *ab, int *ldab, npy_complex128 *bb, int *ldbb, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, d *rwork, int *info) nogil +cdef void zhbgv(char *jobz, char *uplo, int *n, int *ka, int *kb, z *ab, int *ldab, z *bb, int *ldbb, d *w, z *z, int *ldz, z *work, d *rwork, int *info) noexcept nogil: + + _fortran_zhbgv(jobz, uplo, n, ka, kb, ab, ldab, bb, ldbb, w, z, ldz, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhbgvd "BLAS_FUNC(zhbgvd)"(char *jobz, char *uplo, int *n, int *ka, int *kb, npy_complex128 *ab, int *ldab, npy_complex128 *bb, int *ldbb, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil +cdef void zhbgvd(char *jobz, char *uplo, int *n, int *ka, int *kb, z *ab, int *ldab, z *bb, int *ldbb, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_zhbgvd(jobz, uplo, n, ka, kb, ab, ldab, bb, ldbb, w, z, ldz, work, lwork, rwork, lrwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhbgvx "BLAS_FUNC(zhbgvx)"(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, npy_complex128 *ab, int *ldab, npy_complex128 *bb, int *ldbb, npy_complex128 *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, d *rwork, int *iwork, int *ifail, int *info) nogil +cdef void zhbgvx(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, z *ab, int *ldab, z *bb, int *ldbb, z *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil: + + _fortran_zhbgvx(jobz, range, uplo, n, ka, kb, ab, ldab, bb, ldbb, q, ldq, vl, vu, il, iu, abstol, m, w, z, ldz, work, rwork, iwork, ifail, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhbtrd "BLAS_FUNC(zhbtrd)"(char *vect, char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, d *d, d *e, npy_complex128 *q, int *ldq, npy_complex128 *work, int *info) nogil +cdef void zhbtrd(char *vect, char *uplo, int *n, int *kd, z *ab, int *ldab, d *d, d *e, z *q, int *ldq, z *work, int *info) noexcept nogil: + + _fortran_zhbtrd(vect, uplo, n, kd, ab, ldab, d, e, q, ldq, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhecon "BLAS_FUNC(zhecon)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, d *anorm, d *rcond, npy_complex128 *work, int *info) nogil +cdef void zhecon(char *uplo, int *n, z *a, int *lda, int *ipiv, d *anorm, d *rcond, z *work, int *info) noexcept nogil: + + _fortran_zhecon(uplo, n, a, lda, ipiv, anorm, rcond, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zheequb "BLAS_FUNC(zheequb)"(char *uplo, int *n, npy_complex128 *a, int *lda, d *s, d *scond, d *amax, npy_complex128 *work, int *info) nogil +cdef void zheequb(char *uplo, int *n, z *a, int *lda, d *s, d *scond, d *amax, z *work, int *info) noexcept nogil: + + _fortran_zheequb(uplo, n, a, lda, s, scond, amax, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zheev "BLAS_FUNC(zheev)"(char *jobz, char *uplo, int *n, npy_complex128 *a, int *lda, d *w, npy_complex128 *work, int *lwork, d *rwork, int *info) nogil +cdef void zheev(char *jobz, char *uplo, int *n, z *a, int *lda, d *w, z *work, int *lwork, d *rwork, int *info) noexcept nogil: + + _fortran_zheev(jobz, uplo, n, a, lda, w, work, lwork, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zheevd "BLAS_FUNC(zheevd)"(char *jobz, char *uplo, int *n, npy_complex128 *a, int *lda, d *w, npy_complex128 *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil +cdef void zheevd(char *jobz, char *uplo, int *n, z *a, int *lda, d *w, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_zheevd(jobz, uplo, n, a, lda, w, work, lwork, rwork, lrwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zheevr "BLAS_FUNC(zheevr)"(char *jobz, char *range, char *uplo, int *n, npy_complex128 *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, npy_complex128 *z, int *ldz, int *isuppz, npy_complex128 *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil +cdef void zheevr(char *jobz, char *range, char *uplo, int *n, z *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, int *isuppz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_zheevr(jobz, range, uplo, n, a, lda, vl, vu, il, iu, abstol, m, w, z, ldz, isuppz, work, lwork, rwork, lrwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zheevx "BLAS_FUNC(zheevx)"(char *jobz, char *range, char *uplo, int *n, npy_complex128 *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, d *rwork, int *iwork, int *ifail, int *info) nogil +cdef void zheevx(char *jobz, char *range, char *uplo, int *n, z *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil: + + _fortran_zheevx(jobz, range, uplo, n, a, lda, vl, vu, il, iu, abstol, m, w, z, ldz, work, lwork, rwork, iwork, ifail, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhegs2 "BLAS_FUNC(zhegs2)"(int *itype, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *info) nogil +cdef void zhegs2(int *itype, char *uplo, int *n, z *a, int *lda, z *b, int *ldb, int *info) noexcept nogil: + + _fortran_zhegs2(itype, uplo, n, a, lda, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhegst "BLAS_FUNC(zhegst)"(int *itype, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *info) nogil +cdef void zhegst(int *itype, char *uplo, int *n, z *a, int *lda, z *b, int *ldb, int *info) noexcept nogil: + + _fortran_zhegst(itype, uplo, n, a, lda, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhegv "BLAS_FUNC(zhegv)"(int *itype, char *jobz, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, d *w, npy_complex128 *work, int *lwork, d *rwork, int *info) nogil +cdef void zhegv(int *itype, char *jobz, char *uplo, int *n, z *a, int *lda, z *b, int *ldb, d *w, z *work, int *lwork, d *rwork, int *info) noexcept nogil: + + _fortran_zhegv(itype, jobz, uplo, n, a, lda, b, ldb, w, work, lwork, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhegvd "BLAS_FUNC(zhegvd)"(int *itype, char *jobz, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, d *w, npy_complex128 *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil +cdef void zhegvd(int *itype, char *jobz, char *uplo, int *n, z *a, int *lda, z *b, int *ldb, d *w, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_zhegvd(itype, jobz, uplo, n, a, lda, b, ldb, w, work, lwork, rwork, lrwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhegvx "BLAS_FUNC(zhegvx)"(int *itype, char *jobz, char *range, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, d *rwork, int *iwork, int *ifail, int *info) nogil +cdef void zhegvx(int *itype, char *jobz, char *range, char *uplo, int *n, z *a, int *lda, z *b, int *ldb, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil: + + _fortran_zhegvx(itype, jobz, range, uplo, n, a, lda, b, ldb, vl, vu, il, iu, abstol, m, w, z, ldz, work, lwork, rwork, iwork, ifail, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zherfs "BLAS_FUNC(zherfs)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil +cdef void zherfs(char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil: + + _fortran_zherfs(uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhesv "BLAS_FUNC(zhesv)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *work, int *lwork, int *info) nogil +cdef void zhesv(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, z *work, int *lwork, int *info) noexcept nogil: + + _fortran_zhesv(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhesvx "BLAS_FUNC(zhesvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, int *lwork, d *rwork, int *info) nogil +cdef void zhesvx(char *fact, char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, int *lwork, d *rwork, int *info) noexcept nogil: + + _fortran_zhesvx(fact, uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, lwork, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zheswapr "BLAS_FUNC(zheswapr)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *i1, int *i2) nogil +cdef void zheswapr(char *uplo, int *n, z *a, int *lda, int *i1, int *i2) noexcept nogil: + + _fortran_zheswapr(uplo, n, a, lda, i1, i2) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhetd2 "BLAS_FUNC(zhetd2)"(char *uplo, int *n, npy_complex128 *a, int *lda, d *d, d *e, npy_complex128 *tau, int *info) nogil +cdef void zhetd2(char *uplo, int *n, z *a, int *lda, d *d, d *e, z *tau, int *info) noexcept nogil: + + _fortran_zhetd2(uplo, n, a, lda, d, e, tau, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhetf2 "BLAS_FUNC(zhetf2)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, int *info) nogil +cdef void zhetf2(char *uplo, int *n, z *a, int *lda, int *ipiv, int *info) noexcept nogil: + + _fortran_zhetf2(uplo, n, a, lda, ipiv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhetrd "BLAS_FUNC(zhetrd)"(char *uplo, int *n, npy_complex128 *a, int *lda, d *d, d *e, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil +cdef void zhetrd(char *uplo, int *n, z *a, int *lda, d *d, d *e, z *tau, z *work, int *lwork, int *info) noexcept nogil: + + _fortran_zhetrd(uplo, n, a, lda, d, e, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhetrf "BLAS_FUNC(zhetrf)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *lwork, int *info) nogil +cdef void zhetrf(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *lwork, int *info) noexcept nogil: + + _fortran_zhetrf(uplo, n, a, lda, ipiv, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhetri "BLAS_FUNC(zhetri)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *info) nogil +cdef void zhetri(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *info) noexcept nogil: + + _fortran_zhetri(uplo, n, a, lda, ipiv, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhetri2 "BLAS_FUNC(zhetri2)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *lwork, int *info) nogil +cdef void zhetri2(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *lwork, int *info) noexcept nogil: + + _fortran_zhetri2(uplo, n, a, lda, ipiv, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhetri2x "BLAS_FUNC(zhetri2x)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *nb, int *info) nogil +cdef void zhetri2x(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *nb, int *info) noexcept nogil: + + _fortran_zhetri2x(uplo, n, a, lda, ipiv, work, nb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhetrs "BLAS_FUNC(zhetrs)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, int *info) nogil +cdef void zhetrs(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, int *info) noexcept nogil: + + _fortran_zhetrs(uplo, n, nrhs, a, lda, ipiv, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhetrs2 "BLAS_FUNC(zhetrs2)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *work, int *info) nogil +cdef void zhetrs2(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, z *work, int *info) noexcept nogil: + + _fortran_zhetrs2(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhfrk "BLAS_FUNC(zhfrk)"(char *transr, char *uplo, char *trans, int *n, int *k, d *alpha, npy_complex128 *a, int *lda, d *beta, npy_complex128 *c) nogil +cdef void zhfrk(char *transr, char *uplo, char *trans, int *n, int *k, d *alpha, z *a, int *lda, d *beta, z *c) noexcept nogil: + + _fortran_zhfrk(transr, uplo, trans, n, k, alpha, a, lda, beta, c) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhgeqz "BLAS_FUNC(zhgeqz)"(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, npy_complex128 *h, int *ldh, npy_complex128 *t, int *ldt, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *q, int *ldq, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, d *rwork, int *info) nogil +cdef void zhgeqz(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, z *h, int *ldh, z *t, int *ldt, z *alpha, z *beta, z *q, int *ldq, z *z, int *ldz, z *work, int *lwork, d *rwork, int *info) noexcept nogil: + + _fortran_zhgeqz(job, compq, compz, n, ilo, ihi, h, ldh, t, ldt, alpha, beta, q, ldq, z, ldz, work, lwork, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhpcon "BLAS_FUNC(zhpcon)"(char *uplo, int *n, npy_complex128 *ap, int *ipiv, d *anorm, d *rcond, npy_complex128 *work, int *info) nogil +cdef void zhpcon(char *uplo, int *n, z *ap, int *ipiv, d *anorm, d *rcond, z *work, int *info) noexcept nogil: + + _fortran_zhpcon(uplo, n, ap, ipiv, anorm, rcond, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhpev "BLAS_FUNC(zhpev)"(char *jobz, char *uplo, int *n, npy_complex128 *ap, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, d *rwork, int *info) nogil +cdef void zhpev(char *jobz, char *uplo, int *n, z *ap, d *w, z *z, int *ldz, z *work, d *rwork, int *info) noexcept nogil: + + _fortran_zhpev(jobz, uplo, n, ap, w, z, ldz, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhpevd "BLAS_FUNC(zhpevd)"(char *jobz, char *uplo, int *n, npy_complex128 *ap, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil +cdef void zhpevd(char *jobz, char *uplo, int *n, z *ap, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_zhpevd(jobz, uplo, n, ap, w, z, ldz, work, lwork, rwork, lrwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhpevx "BLAS_FUNC(zhpevx)"(char *jobz, char *range, char *uplo, int *n, npy_complex128 *ap, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, d *rwork, int *iwork, int *ifail, int *info) nogil +cdef void zhpevx(char *jobz, char *range, char *uplo, int *n, z *ap, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil: + + _fortran_zhpevx(jobz, range, uplo, n, ap, vl, vu, il, iu, abstol, m, w, z, ldz, work, rwork, iwork, ifail, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhpgst "BLAS_FUNC(zhpgst)"(int *itype, char *uplo, int *n, npy_complex128 *ap, npy_complex128 *bp, int *info) nogil +cdef void zhpgst(int *itype, char *uplo, int *n, z *ap, z *bp, int *info) noexcept nogil: + + _fortran_zhpgst(itype, uplo, n, ap, bp, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhpgv "BLAS_FUNC(zhpgv)"(int *itype, char *jobz, char *uplo, int *n, npy_complex128 *ap, npy_complex128 *bp, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, d *rwork, int *info) nogil +cdef void zhpgv(int *itype, char *jobz, char *uplo, int *n, z *ap, z *bp, d *w, z *z, int *ldz, z *work, d *rwork, int *info) noexcept nogil: + + _fortran_zhpgv(itype, jobz, uplo, n, ap, bp, w, z, ldz, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhpgvd "BLAS_FUNC(zhpgvd)"(int *itype, char *jobz, char *uplo, int *n, npy_complex128 *ap, npy_complex128 *bp, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil +cdef void zhpgvd(int *itype, char *jobz, char *uplo, int *n, z *ap, z *bp, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_zhpgvd(itype, jobz, uplo, n, ap, bp, w, z, ldz, work, lwork, rwork, lrwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhpgvx "BLAS_FUNC(zhpgvx)"(int *itype, char *jobz, char *range, char *uplo, int *n, npy_complex128 *ap, npy_complex128 *bp, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, d *rwork, int *iwork, int *ifail, int *info) nogil +cdef void zhpgvx(int *itype, char *jobz, char *range, char *uplo, int *n, z *ap, z *bp, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil: + + _fortran_zhpgvx(itype, jobz, range, uplo, n, ap, bp, vl, vu, il, iu, abstol, m, w, z, ldz, work, rwork, iwork, ifail, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhprfs "BLAS_FUNC(zhprfs)"(char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil +cdef void zhprfs(char *uplo, int *n, int *nrhs, z *ap, z *afp, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil: + + _fortran_zhprfs(uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhpsv "BLAS_FUNC(zhpsv)"(char *uplo, int *n, int *nrhs, npy_complex128 *ap, int *ipiv, npy_complex128 *b, int *ldb, int *info) nogil +cdef void zhpsv(char *uplo, int *n, int *nrhs, z *ap, int *ipiv, z *b, int *ldb, int *info) noexcept nogil: + + _fortran_zhpsv(uplo, n, nrhs, ap, ipiv, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhpsvx "BLAS_FUNC(zhpsvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil +cdef void zhpsvx(char *fact, char *uplo, int *n, int *nrhs, z *ap, z *afp, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil: + + _fortran_zhpsvx(fact, uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhptrd "BLAS_FUNC(zhptrd)"(char *uplo, int *n, npy_complex128 *ap, d *d, d *e, npy_complex128 *tau, int *info) nogil +cdef void zhptrd(char *uplo, int *n, z *ap, d *d, d *e, z *tau, int *info) noexcept nogil: + + _fortran_zhptrd(uplo, n, ap, d, e, tau, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhptrf "BLAS_FUNC(zhptrf)"(char *uplo, int *n, npy_complex128 *ap, int *ipiv, int *info) nogil +cdef void zhptrf(char *uplo, int *n, z *ap, int *ipiv, int *info) noexcept nogil: + + _fortran_zhptrf(uplo, n, ap, ipiv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhptri "BLAS_FUNC(zhptri)"(char *uplo, int *n, npy_complex128 *ap, int *ipiv, npy_complex128 *work, int *info) nogil +cdef void zhptri(char *uplo, int *n, z *ap, int *ipiv, z *work, int *info) noexcept nogil: + + _fortran_zhptri(uplo, n, ap, ipiv, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhptrs "BLAS_FUNC(zhptrs)"(char *uplo, int *n, int *nrhs, npy_complex128 *ap, int *ipiv, npy_complex128 *b, int *ldb, int *info) nogil +cdef void zhptrs(char *uplo, int *n, int *nrhs, z *ap, int *ipiv, z *b, int *ldb, int *info) noexcept nogil: + + _fortran_zhptrs(uplo, n, nrhs, ap, ipiv, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhsein "BLAS_FUNC(zhsein)"(char *side, char *eigsrc, char *initv, bint *select, int *n, npy_complex128 *h, int *ldh, npy_complex128 *w, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, int *mm, int *m, npy_complex128 *work, d *rwork, int *ifaill, int *ifailr, int *info) nogil +cdef void zhsein(char *side, char *eigsrc, char *initv, bint *select, int *n, z *h, int *ldh, z *w, z *vl, int *ldvl, z *vr, int *ldvr, int *mm, int *m, z *work, d *rwork, int *ifaill, int *ifailr, int *info) noexcept nogil: + + _fortran_zhsein(side, eigsrc, initv, select, n, h, ldh, w, vl, ldvl, vr, ldvr, mm, m, work, rwork, ifaill, ifailr, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zhseqr "BLAS_FUNC(zhseqr)"(char *job, char *compz, int *n, int *ilo, int *ihi, npy_complex128 *h, int *ldh, npy_complex128 *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, int *info) nogil +cdef void zhseqr(char *job, char *compz, int *n, int *ilo, int *ihi, z *h, int *ldh, z *w, z *z, int *ldz, z *work, int *lwork, int *info) noexcept nogil: + + _fortran_zhseqr(job, compz, n, ilo, ihi, h, ldh, w, z, ldz, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlabrd "BLAS_FUNC(zlabrd)"(int *m, int *n, int *nb, npy_complex128 *a, int *lda, d *d, d *e, npy_complex128 *tauq, npy_complex128 *taup, npy_complex128 *x, int *ldx, npy_complex128 *y, int *ldy) nogil +cdef void zlabrd(int *m, int *n, int *nb, z *a, int *lda, d *d, d *e, z *tauq, z *taup, z *x, int *ldx, z *y, int *ldy) noexcept nogil: + + _fortran_zlabrd(m, n, nb, a, lda, d, e, tauq, taup, x, ldx, y, ldy) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlacgv "BLAS_FUNC(zlacgv)"(int *n, npy_complex128 *x, int *incx) nogil +cdef void zlacgv(int *n, z *x, int *incx) noexcept nogil: + + _fortran_zlacgv(n, x, incx) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlacn2 "BLAS_FUNC(zlacn2)"(int *n, npy_complex128 *v, npy_complex128 *x, d *est, int *kase, int *isave) nogil +cdef void zlacn2(int *n, z *v, z *x, d *est, int *kase, int *isave) noexcept nogil: + + _fortran_zlacn2(n, v, x, est, kase, isave) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlacon "BLAS_FUNC(zlacon)"(int *n, npy_complex128 *v, npy_complex128 *x, d *est, int *kase) nogil +cdef void zlacon(int *n, z *v, z *x, d *est, int *kase) noexcept nogil: + + _fortran_zlacon(n, v, x, est, kase) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlacp2 "BLAS_FUNC(zlacp2)"(char *uplo, int *m, int *n, d *a, int *lda, npy_complex128 *b, int *ldb) nogil +cdef void zlacp2(char *uplo, int *m, int *n, d *a, int *lda, z *b, int *ldb) noexcept nogil: + + _fortran_zlacp2(uplo, m, n, a, lda, b, ldb) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlacpy "BLAS_FUNC(zlacpy)"(char *uplo, int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb) nogil +cdef void zlacpy(char *uplo, int *m, int *n, z *a, int *lda, z *b, int *ldb) noexcept nogil: + + _fortran_zlacpy(uplo, m, n, a, lda, b, ldb) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlacrm "BLAS_FUNC(zlacrm)"(int *m, int *n, npy_complex128 *a, int *lda, d *b, int *ldb, npy_complex128 *c, int *ldc, d *rwork) nogil +cdef void zlacrm(int *m, int *n, z *a, int *lda, d *b, int *ldb, z *c, int *ldc, d *rwork) noexcept nogil: + + _fortran_zlacrm(m, n, a, lda, b, ldb, c, ldc, rwork) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlacrt "BLAS_FUNC(zlacrt)"(int *n, npy_complex128 *cx, int *incx, npy_complex128 *cy, int *incy, npy_complex128 *c, npy_complex128 *s) nogil +cdef void zlacrt(int *n, z *cx, int *incx, z *cy, int *incy, z *c, z *s) noexcept nogil: + + _fortran_zlacrt(n, cx, incx, cy, incy, c, s) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zladiv "F_FUNC(zladivwrp,ZLADIVWRP)"(npy_complex128 *out, npy_complex128 *x, npy_complex128 *y) nogil +cdef z zladiv(z *x, z *y) noexcept nogil: + cdef z out + _fortran_zladiv(&out, x, y) + return out + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlaed0 "BLAS_FUNC(zlaed0)"(int *qsiz, int *n, d *d, d *e, npy_complex128 *q, int *ldq, npy_complex128 *qstore, int *ldqs, d *rwork, int *iwork, int *info) nogil +cdef void zlaed0(int *qsiz, int *n, d *d, d *e, z *q, int *ldq, z *qstore, int *ldqs, d *rwork, int *iwork, int *info) noexcept nogil: + + _fortran_zlaed0(qsiz, n, d, e, q, ldq, qstore, ldqs, rwork, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlaed7 "BLAS_FUNC(zlaed7)"(int *n, int *cutpnt, int *qsiz, int *tlvls, int *curlvl, int *curpbm, d *d, npy_complex128 *q, int *ldq, d *rho, int *indxq, d *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, d *givnum, npy_complex128 *work, d *rwork, int *iwork, int *info) nogil +cdef void zlaed7(int *n, int *cutpnt, int *qsiz, int *tlvls, int *curlvl, int *curpbm, d *d, z *q, int *ldq, d *rho, int *indxq, d *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, d *givnum, z *work, d *rwork, int *iwork, int *info) noexcept nogil: + + _fortran_zlaed7(n, cutpnt, qsiz, tlvls, curlvl, curpbm, d, q, ldq, rho, indxq, qstore, qptr, prmptr, perm, givptr, givcol, givnum, work, rwork, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlaed8 "BLAS_FUNC(zlaed8)"(int *k, int *n, int *qsiz, npy_complex128 *q, int *ldq, d *d, d *rho, int *cutpnt, d *z, d *dlamda, npy_complex128 *q2, int *ldq2, d *w, int *indxp, int *indx, int *indxq, int *perm, int *givptr, int *givcol, d *givnum, int *info) nogil +cdef void zlaed8(int *k, int *n, int *qsiz, z *q, int *ldq, d *d, d *rho, int *cutpnt, d *z, d *dlamda, z *q2, int *ldq2, d *w, int *indxp, int *indx, int *indxq, int *perm, int *givptr, int *givcol, d *givnum, int *info) noexcept nogil: + + _fortran_zlaed8(k, n, qsiz, q, ldq, d, rho, cutpnt, z, dlamda, q2, ldq2, w, indxp, indx, indxq, perm, givptr, givcol, givnum, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlaein "BLAS_FUNC(zlaein)"(bint *rightv, bint *noinit, int *n, npy_complex128 *h, int *ldh, npy_complex128 *w, npy_complex128 *v, npy_complex128 *b, int *ldb, d *rwork, d *eps3, d *smlnum, int *info) nogil +cdef void zlaein(bint *rightv, bint *noinit, int *n, z *h, int *ldh, z *w, z *v, z *b, int *ldb, d *rwork, d *eps3, d *smlnum, int *info) noexcept nogil: + + _fortran_zlaein(rightv, noinit, n, h, ldh, w, v, b, ldb, rwork, eps3, smlnum, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlaesy "BLAS_FUNC(zlaesy)"(npy_complex128 *a, npy_complex128 *b, npy_complex128 *c, npy_complex128 *rt1, npy_complex128 *rt2, npy_complex128 *evscal, npy_complex128 *cs1, npy_complex128 *sn1) nogil +cdef void zlaesy(z *a, z *b, z *c, z *rt1, z *rt2, z *evscal, z *cs1, z *sn1) noexcept nogil: + + _fortran_zlaesy(a, b, c, rt1, rt2, evscal, cs1, sn1) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlaev2 "BLAS_FUNC(zlaev2)"(npy_complex128 *a, npy_complex128 *b, npy_complex128 *c, d *rt1, d *rt2, d *cs1, npy_complex128 *sn1) nogil +cdef void zlaev2(z *a, z *b, z *c, d *rt1, d *rt2, d *cs1, z *sn1) noexcept nogil: + + _fortran_zlaev2(a, b, c, rt1, rt2, cs1, sn1) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlag2c "BLAS_FUNC(zlag2c)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex64 *sa, int *ldsa, int *info) nogil +cdef void zlag2c(int *m, int *n, z *a, int *lda, c *sa, int *ldsa, int *info) noexcept nogil: + + _fortran_zlag2c(m, n, a, lda, sa, ldsa, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlags2 "BLAS_FUNC(zlags2)"(bint *upper, d *a1, npy_complex128 *a2, d *a3, d *b1, npy_complex128 *b2, d *b3, d *csu, npy_complex128 *snu, d *csv, npy_complex128 *snv, d *csq, npy_complex128 *snq) nogil +cdef void zlags2(bint *upper, d *a1, z *a2, d *a3, d *b1, z *b2, d *b3, d *csu, z *snu, d *csv, z *snv, d *csq, z *snq) noexcept nogil: + + _fortran_zlags2(upper, a1, a2, a3, b1, b2, b3, csu, snu, csv, snv, csq, snq) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlagtm "BLAS_FUNC(zlagtm)"(char *trans, int *n, int *nrhs, d *alpha, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *x, int *ldx, d *beta, npy_complex128 *b, int *ldb) nogil +cdef void zlagtm(char *trans, int *n, int *nrhs, d *alpha, z *dl, z *d, z *du, z *x, int *ldx, d *beta, z *b, int *ldb) noexcept nogil: + + _fortran_zlagtm(trans, n, nrhs, alpha, dl, d, du, x, ldx, beta, b, ldb) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlahef "BLAS_FUNC(zlahef)"(char *uplo, int *n, int *nb, int *kb, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *w, int *ldw, int *info) nogil +cdef void zlahef(char *uplo, int *n, int *nb, int *kb, z *a, int *lda, int *ipiv, z *w, int *ldw, int *info) noexcept nogil: + + _fortran_zlahef(uplo, n, nb, kb, a, lda, ipiv, w, ldw, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlahqr "BLAS_FUNC(zlahqr)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, npy_complex128 *h, int *ldh, npy_complex128 *w, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, int *info) nogil +cdef void zlahqr(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, z *h, int *ldh, z *w, int *iloz, int *ihiz, z *z, int *ldz, int *info) noexcept nogil: + + _fortran_zlahqr(wantt, wantz, n, ilo, ihi, h, ldh, w, iloz, ihiz, z, ldz, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlahr2 "BLAS_FUNC(zlahr2)"(int *n, int *k, int *nb, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *t, int *ldt, npy_complex128 *y, int *ldy) nogil +cdef void zlahr2(int *n, int *k, int *nb, z *a, int *lda, z *tau, z *t, int *ldt, z *y, int *ldy) noexcept nogil: + + _fortran_zlahr2(n, k, nb, a, lda, tau, t, ldt, y, ldy) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlaic1 "BLAS_FUNC(zlaic1)"(int *job, int *j, npy_complex128 *x, d *sest, npy_complex128 *w, npy_complex128 *gamma, d *sestpr, npy_complex128 *s, npy_complex128 *c) nogil +cdef void zlaic1(int *job, int *j, z *x, d *sest, z *w, z *gamma, d *sestpr, z *s, z *c) noexcept nogil: + + _fortran_zlaic1(job, j, x, sest, w, gamma, sestpr, s, c) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlals0 "BLAS_FUNC(zlals0)"(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, npy_complex128 *b, int *ldb, npy_complex128 *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, d *givnum, int *ldgnum, d *poles, d *difl, d *difr, d *z, int *k, d *c, d *s, d *rwork, int *info) nogil +cdef void zlals0(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, z *b, int *ldb, z *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, d *givnum, int *ldgnum, d *poles, d *difl, d *difr, d *z, int *k, d *c, d *s, d *rwork, int *info) noexcept nogil: + + _fortran_zlals0(icompq, nl, nr, sqre, nrhs, b, ldb, bx, ldbx, perm, givptr, givcol, ldgcol, givnum, ldgnum, poles, difl, difr, z, k, c, s, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlalsa "BLAS_FUNC(zlalsa)"(int *icompq, int *smlsiz, int *n, int *nrhs, npy_complex128 *b, int *ldb, npy_complex128 *bx, int *ldbx, d *u, int *ldu, d *vt, int *k, d *difl, d *difr, d *z, d *poles, int *givptr, int *givcol, int *ldgcol, int *perm, d *givnum, d *c, d *s, d *rwork, int *iwork, int *info) nogil +cdef void zlalsa(int *icompq, int *smlsiz, int *n, int *nrhs, z *b, int *ldb, z *bx, int *ldbx, d *u, int *ldu, d *vt, int *k, d *difl, d *difr, d *z, d *poles, int *givptr, int *givcol, int *ldgcol, int *perm, d *givnum, d *c, d *s, d *rwork, int *iwork, int *info) noexcept nogil: + + _fortran_zlalsa(icompq, smlsiz, n, nrhs, b, ldb, bx, ldbx, u, ldu, vt, k, difl, difr, z, poles, givptr, givcol, ldgcol, perm, givnum, c, s, rwork, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlalsd "BLAS_FUNC(zlalsd)"(char *uplo, int *smlsiz, int *n, int *nrhs, d *d, d *e, npy_complex128 *b, int *ldb, d *rcond, int *rank, npy_complex128 *work, d *rwork, int *iwork, int *info) nogil +cdef void zlalsd(char *uplo, int *smlsiz, int *n, int *nrhs, d *d, d *e, z *b, int *ldb, d *rcond, int *rank, z *work, d *rwork, int *iwork, int *info) noexcept nogil: + + _fortran_zlalsd(uplo, smlsiz, n, nrhs, d, e, b, ldb, rcond, rank, work, rwork, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + d _fortran_zlangb "BLAS_FUNC(zlangb)"(char *norm, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, d *work) nogil +cdef d zlangb(char *norm, int *n, int *kl, int *ku, z *ab, int *ldab, d *work) noexcept nogil: + + return _fortran_zlangb(norm, n, kl, ku, ab, ldab, work) + + +cdef extern from "_lapack_subroutines.h": + d _fortran_zlange "BLAS_FUNC(zlange)"(char *norm, int *m, int *n, npy_complex128 *a, int *lda, d *work) nogil +cdef d zlange(char *norm, int *m, int *n, z *a, int *lda, d *work) noexcept nogil: + + return _fortran_zlange(norm, m, n, a, lda, work) + + +cdef extern from "_lapack_subroutines.h": + d _fortran_zlangt "BLAS_FUNC(zlangt)"(char *norm, int *n, npy_complex128 *dl, npy_complex128 *d_, npy_complex128 *du) nogil +cdef d zlangt(char *norm, int *n, z *dl, z *d_, z *du) noexcept nogil: + + return _fortran_zlangt(norm, n, dl, d_, du) + + +cdef extern from "_lapack_subroutines.h": + d _fortran_zlanhb "BLAS_FUNC(zlanhb)"(char *norm, char *uplo, int *n, int *k, npy_complex128 *ab, int *ldab, d *work) nogil +cdef d zlanhb(char *norm, char *uplo, int *n, int *k, z *ab, int *ldab, d *work) noexcept nogil: + + return _fortran_zlanhb(norm, uplo, n, k, ab, ldab, work) + + +cdef extern from "_lapack_subroutines.h": + d _fortran_zlanhe "BLAS_FUNC(zlanhe)"(char *norm, char *uplo, int *n, npy_complex128 *a, int *lda, d *work) nogil +cdef d zlanhe(char *norm, char *uplo, int *n, z *a, int *lda, d *work) noexcept nogil: + + return _fortran_zlanhe(norm, uplo, n, a, lda, work) + + +cdef extern from "_lapack_subroutines.h": + d _fortran_zlanhf "BLAS_FUNC(zlanhf)"(char *norm, char *transr, char *uplo, int *n, npy_complex128 *a, d *work) nogil +cdef d zlanhf(char *norm, char *transr, char *uplo, int *n, z *a, d *work) noexcept nogil: + + return _fortran_zlanhf(norm, transr, uplo, n, a, work) + + +cdef extern from "_lapack_subroutines.h": + d _fortran_zlanhp "BLAS_FUNC(zlanhp)"(char *norm, char *uplo, int *n, npy_complex128 *ap, d *work) nogil +cdef d zlanhp(char *norm, char *uplo, int *n, z *ap, d *work) noexcept nogil: + + return _fortran_zlanhp(norm, uplo, n, ap, work) + + +cdef extern from "_lapack_subroutines.h": + d _fortran_zlanhs "BLAS_FUNC(zlanhs)"(char *norm, int *n, npy_complex128 *a, int *lda, d *work) nogil +cdef d zlanhs(char *norm, int *n, z *a, int *lda, d *work) noexcept nogil: + + return _fortran_zlanhs(norm, n, a, lda, work) + + +cdef extern from "_lapack_subroutines.h": + d _fortran_zlanht "BLAS_FUNC(zlanht)"(char *norm, int *n, d *d_, npy_complex128 *e) nogil +cdef d zlanht(char *norm, int *n, d *d_, z *e) noexcept nogil: + + return _fortran_zlanht(norm, n, d_, e) + + +cdef extern from "_lapack_subroutines.h": + d _fortran_zlansb "BLAS_FUNC(zlansb)"(char *norm, char *uplo, int *n, int *k, npy_complex128 *ab, int *ldab, d *work) nogil +cdef d zlansb(char *norm, char *uplo, int *n, int *k, z *ab, int *ldab, d *work) noexcept nogil: + + return _fortran_zlansb(norm, uplo, n, k, ab, ldab, work) + + +cdef extern from "_lapack_subroutines.h": + d _fortran_zlansp "BLAS_FUNC(zlansp)"(char *norm, char *uplo, int *n, npy_complex128 *ap, d *work) nogil +cdef d zlansp(char *norm, char *uplo, int *n, z *ap, d *work) noexcept nogil: + + return _fortran_zlansp(norm, uplo, n, ap, work) + + +cdef extern from "_lapack_subroutines.h": + d _fortran_zlansy "BLAS_FUNC(zlansy)"(char *norm, char *uplo, int *n, npy_complex128 *a, int *lda, d *work) nogil +cdef d zlansy(char *norm, char *uplo, int *n, z *a, int *lda, d *work) noexcept nogil: + + return _fortran_zlansy(norm, uplo, n, a, lda, work) + + +cdef extern from "_lapack_subroutines.h": + d _fortran_zlantb "BLAS_FUNC(zlantb)"(char *norm, char *uplo, char *diag, int *n, int *k, npy_complex128 *ab, int *ldab, d *work) nogil +cdef d zlantb(char *norm, char *uplo, char *diag, int *n, int *k, z *ab, int *ldab, d *work) noexcept nogil: + + return _fortran_zlantb(norm, uplo, diag, n, k, ab, ldab, work) + + +cdef extern from "_lapack_subroutines.h": + d _fortran_zlantp "BLAS_FUNC(zlantp)"(char *norm, char *uplo, char *diag, int *n, npy_complex128 *ap, d *work) nogil +cdef d zlantp(char *norm, char *uplo, char *diag, int *n, z *ap, d *work) noexcept nogil: + + return _fortran_zlantp(norm, uplo, diag, n, ap, work) + + +cdef extern from "_lapack_subroutines.h": + d _fortran_zlantr "BLAS_FUNC(zlantr)"(char *norm, char *uplo, char *diag, int *m, int *n, npy_complex128 *a, int *lda, d *work) nogil +cdef d zlantr(char *norm, char *uplo, char *diag, int *m, int *n, z *a, int *lda, d *work) noexcept nogil: + + return _fortran_zlantr(norm, uplo, diag, m, n, a, lda, work) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlapll "BLAS_FUNC(zlapll)"(int *n, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, d *ssmin) nogil +cdef void zlapll(int *n, z *x, int *incx, z *y, int *incy, d *ssmin) noexcept nogil: + + _fortran_zlapll(n, x, incx, y, incy, ssmin) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlapmr "BLAS_FUNC(zlapmr)"(bint *forwrd, int *m, int *n, npy_complex128 *x, int *ldx, int *k) nogil +cdef void zlapmr(bint *forwrd, int *m, int *n, z *x, int *ldx, int *k) noexcept nogil: + + _fortran_zlapmr(forwrd, m, n, x, ldx, k) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlapmt "BLAS_FUNC(zlapmt)"(bint *forwrd, int *m, int *n, npy_complex128 *x, int *ldx, int *k) nogil +cdef void zlapmt(bint *forwrd, int *m, int *n, z *x, int *ldx, int *k) noexcept nogil: + + _fortran_zlapmt(forwrd, m, n, x, ldx, k) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlaqgb "BLAS_FUNC(zlaqgb)"(int *m, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) nogil +cdef void zlaqgb(int *m, int *n, int *kl, int *ku, z *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) noexcept nogil: + + _fortran_zlaqgb(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, equed) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlaqge "BLAS_FUNC(zlaqge)"(int *m, int *n, npy_complex128 *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) nogil +cdef void zlaqge(int *m, int *n, z *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) noexcept nogil: + + _fortran_zlaqge(m, n, a, lda, r, c, rowcnd, colcnd, amax, equed) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlaqhb "BLAS_FUNC(zlaqhb)"(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, d *s, d *scond, d *amax, char *equed) nogil +cdef void zlaqhb(char *uplo, int *n, int *kd, z *ab, int *ldab, d *s, d *scond, d *amax, char *equed) noexcept nogil: + + _fortran_zlaqhb(uplo, n, kd, ab, ldab, s, scond, amax, equed) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlaqhe "BLAS_FUNC(zlaqhe)"(char *uplo, int *n, npy_complex128 *a, int *lda, d *s, d *scond, d *amax, char *equed) nogil +cdef void zlaqhe(char *uplo, int *n, z *a, int *lda, d *s, d *scond, d *amax, char *equed) noexcept nogil: + + _fortran_zlaqhe(uplo, n, a, lda, s, scond, amax, equed) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlaqhp "BLAS_FUNC(zlaqhp)"(char *uplo, int *n, npy_complex128 *ap, d *s, d *scond, d *amax, char *equed) nogil +cdef void zlaqhp(char *uplo, int *n, z *ap, d *s, d *scond, d *amax, char *equed) noexcept nogil: + + _fortran_zlaqhp(uplo, n, ap, s, scond, amax, equed) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlaqp2 "BLAS_FUNC(zlaqp2)"(int *m, int *n, int *offset, npy_complex128 *a, int *lda, int *jpvt, npy_complex128 *tau, d *vn1, d *vn2, npy_complex128 *work) nogil +cdef void zlaqp2(int *m, int *n, int *offset, z *a, int *lda, int *jpvt, z *tau, d *vn1, d *vn2, z *work) noexcept nogil: + + _fortran_zlaqp2(m, n, offset, a, lda, jpvt, tau, vn1, vn2, work) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlaqps "BLAS_FUNC(zlaqps)"(int *m, int *n, int *offset, int *nb, int *kb, npy_complex128 *a, int *lda, int *jpvt, npy_complex128 *tau, d *vn1, d *vn2, npy_complex128 *auxv, npy_complex128 *f, int *ldf) nogil +cdef void zlaqps(int *m, int *n, int *offset, int *nb, int *kb, z *a, int *lda, int *jpvt, z *tau, d *vn1, d *vn2, z *auxv, z *f, int *ldf) noexcept nogil: + + _fortran_zlaqps(m, n, offset, nb, kb, a, lda, jpvt, tau, vn1, vn2, auxv, f, ldf) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlaqr0 "BLAS_FUNC(zlaqr0)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, npy_complex128 *h, int *ldh, npy_complex128 *w, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, int *info) nogil +cdef void zlaqr0(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, z *h, int *ldh, z *w, int *iloz, int *ihiz, z *z, int *ldz, z *work, int *lwork, int *info) noexcept nogil: + + _fortran_zlaqr0(wantt, wantz, n, ilo, ihi, h, ldh, w, iloz, ihiz, z, ldz, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlaqr1 "BLAS_FUNC(zlaqr1)"(int *n, npy_complex128 *h, int *ldh, npy_complex128 *s1, npy_complex128 *s2, npy_complex128 *v) nogil +cdef void zlaqr1(int *n, z *h, int *ldh, z *s1, z *s2, z *v) noexcept nogil: + + _fortran_zlaqr1(n, h, ldh, s1, s2, v) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlaqr2 "BLAS_FUNC(zlaqr2)"(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, npy_complex128 *h, int *ldh, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, int *ns, int *nd, npy_complex128 *sh, npy_complex128 *v, int *ldv, int *nh, npy_complex128 *t, int *ldt, int *nv, npy_complex128 *wv, int *ldwv, npy_complex128 *work, int *lwork) nogil +cdef void zlaqr2(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, z *h, int *ldh, int *iloz, int *ihiz, z *z, int *ldz, int *ns, int *nd, z *sh, z *v, int *ldv, int *nh, z *t, int *ldt, int *nv, z *wv, int *ldwv, z *work, int *lwork) noexcept nogil: + + _fortran_zlaqr2(wantt, wantz, n, ktop, kbot, nw, h, ldh, iloz, ihiz, z, ldz, ns, nd, sh, v, ldv, nh, t, ldt, nv, wv, ldwv, work, lwork) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlaqr3 "BLAS_FUNC(zlaqr3)"(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, npy_complex128 *h, int *ldh, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, int *ns, int *nd, npy_complex128 *sh, npy_complex128 *v, int *ldv, int *nh, npy_complex128 *t, int *ldt, int *nv, npy_complex128 *wv, int *ldwv, npy_complex128 *work, int *lwork) nogil +cdef void zlaqr3(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, z *h, int *ldh, int *iloz, int *ihiz, z *z, int *ldz, int *ns, int *nd, z *sh, z *v, int *ldv, int *nh, z *t, int *ldt, int *nv, z *wv, int *ldwv, z *work, int *lwork) noexcept nogil: + + _fortran_zlaqr3(wantt, wantz, n, ktop, kbot, nw, h, ldh, iloz, ihiz, z, ldz, ns, nd, sh, v, ldv, nh, t, ldt, nv, wv, ldwv, work, lwork) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlaqr4 "BLAS_FUNC(zlaqr4)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, npy_complex128 *h, int *ldh, npy_complex128 *w, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, int *info) nogil +cdef void zlaqr4(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, z *h, int *ldh, z *w, int *iloz, int *ihiz, z *z, int *ldz, z *work, int *lwork, int *info) noexcept nogil: + + _fortran_zlaqr4(wantt, wantz, n, ilo, ihi, h, ldh, w, iloz, ihiz, z, ldz, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlaqr5 "BLAS_FUNC(zlaqr5)"(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, npy_complex128 *s, npy_complex128 *h, int *ldh, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, npy_complex128 *v, int *ldv, npy_complex128 *u, int *ldu, int *nv, npy_complex128 *wv, int *ldwv, int *nh, npy_complex128 *wh, int *ldwh) nogil +cdef void zlaqr5(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, z *s, z *h, int *ldh, int *iloz, int *ihiz, z *z, int *ldz, z *v, int *ldv, z *u, int *ldu, int *nv, z *wv, int *ldwv, int *nh, z *wh, int *ldwh) noexcept nogil: + + _fortran_zlaqr5(wantt, wantz, kacc22, n, ktop, kbot, nshfts, s, h, ldh, iloz, ihiz, z, ldz, v, ldv, u, ldu, nv, wv, ldwv, nh, wh, ldwh) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlaqsb "BLAS_FUNC(zlaqsb)"(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, d *s, d *scond, d *amax, char *equed) nogil +cdef void zlaqsb(char *uplo, int *n, int *kd, z *ab, int *ldab, d *s, d *scond, d *amax, char *equed) noexcept nogil: + + _fortran_zlaqsb(uplo, n, kd, ab, ldab, s, scond, amax, equed) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlaqsp "BLAS_FUNC(zlaqsp)"(char *uplo, int *n, npy_complex128 *ap, d *s, d *scond, d *amax, char *equed) nogil +cdef void zlaqsp(char *uplo, int *n, z *ap, d *s, d *scond, d *amax, char *equed) noexcept nogil: + + _fortran_zlaqsp(uplo, n, ap, s, scond, amax, equed) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlaqsy "BLAS_FUNC(zlaqsy)"(char *uplo, int *n, npy_complex128 *a, int *lda, d *s, d *scond, d *amax, char *equed) nogil +cdef void zlaqsy(char *uplo, int *n, z *a, int *lda, d *s, d *scond, d *amax, char *equed) noexcept nogil: + + _fortran_zlaqsy(uplo, n, a, lda, s, scond, amax, equed) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlar1v "BLAS_FUNC(zlar1v)"(int *n, int *b1, int *bn, d *lambda_, d *d, d *l, d *ld, d *lld, d *pivmin, d *gaptol, npy_complex128 *z, bint *wantnc, int *negcnt, d *ztz, d *mingma, int *r, int *isuppz, d *nrminv, d *resid, d *rqcorr, d *work) nogil +cdef void zlar1v(int *n, int *b1, int *bn, d *lambda_, d *d, d *l, d *ld, d *lld, d *pivmin, d *gaptol, z *z, bint *wantnc, int *negcnt, d *ztz, d *mingma, int *r, int *isuppz, d *nrminv, d *resid, d *rqcorr, d *work) noexcept nogil: + + _fortran_zlar1v(n, b1, bn, lambda_, d, l, ld, lld, pivmin, gaptol, z, wantnc, negcnt, ztz, mingma, r, isuppz, nrminv, resid, rqcorr, work) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlar2v "BLAS_FUNC(zlar2v)"(int *n, npy_complex128 *x, npy_complex128 *y, npy_complex128 *z, int *incx, d *c, npy_complex128 *s, int *incc) nogil +cdef void zlar2v(int *n, z *x, z *y, z *z, int *incx, d *c, z *s, int *incc) noexcept nogil: + + _fortran_zlar2v(n, x, y, z, incx, c, s, incc) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlarcm "BLAS_FUNC(zlarcm)"(int *m, int *n, d *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *c, int *ldc, d *rwork) nogil +cdef void zlarcm(int *m, int *n, d *a, int *lda, z *b, int *ldb, z *c, int *ldc, d *rwork) noexcept nogil: + + _fortran_zlarcm(m, n, a, lda, b, ldb, c, ldc, rwork) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlarf "BLAS_FUNC(zlarf)"(char *side, int *m, int *n, npy_complex128 *v, int *incv, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work) nogil +cdef void zlarf(char *side, int *m, int *n, z *v, int *incv, z *tau, z *c, int *ldc, z *work) noexcept nogil: + + _fortran_zlarf(side, m, n, v, incv, tau, c, ldc, work) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlarfb "BLAS_FUNC(zlarfb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, npy_complex128 *v, int *ldv, npy_complex128 *t, int *ldt, npy_complex128 *c, int *ldc, npy_complex128 *work, int *ldwork) nogil +cdef void zlarfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, z *v, int *ldv, z *t, int *ldt, z *c, int *ldc, z *work, int *ldwork) noexcept nogil: + + _fortran_zlarfb(side, trans, direct, storev, m, n, k, v, ldv, t, ldt, c, ldc, work, ldwork) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlarfg "BLAS_FUNC(zlarfg)"(int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *tau) nogil +cdef void zlarfg(int *n, z *alpha, z *x, int *incx, z *tau) noexcept nogil: + + _fortran_zlarfg(n, alpha, x, incx, tau) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlarfgp "BLAS_FUNC(zlarfgp)"(int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *tau) nogil +cdef void zlarfgp(int *n, z *alpha, z *x, int *incx, z *tau) noexcept nogil: + + _fortran_zlarfgp(n, alpha, x, incx, tau) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlarft "BLAS_FUNC(zlarft)"(char *direct, char *storev, int *n, int *k, npy_complex128 *v, int *ldv, npy_complex128 *tau, npy_complex128 *t, int *ldt) nogil +cdef void zlarft(char *direct, char *storev, int *n, int *k, z *v, int *ldv, z *tau, z *t, int *ldt) noexcept nogil: + + _fortran_zlarft(direct, storev, n, k, v, ldv, tau, t, ldt) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlarfx "BLAS_FUNC(zlarfx)"(char *side, int *m, int *n, npy_complex128 *v, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work) nogil +cdef void zlarfx(char *side, int *m, int *n, z *v, z *tau, z *c, int *ldc, z *work) noexcept nogil: + + _fortran_zlarfx(side, m, n, v, tau, c, ldc, work) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlargv "BLAS_FUNC(zlargv)"(int *n, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, d *c, int *incc) nogil +cdef void zlargv(int *n, z *x, int *incx, z *y, int *incy, d *c, int *incc) noexcept nogil: + + _fortran_zlargv(n, x, incx, y, incy, c, incc) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlarnv "BLAS_FUNC(zlarnv)"(int *idist, int *iseed, int *n, npy_complex128 *x) nogil +cdef void zlarnv(int *idist, int *iseed, int *n, z *x) noexcept nogil: + + _fortran_zlarnv(idist, iseed, n, x) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlarrv "BLAS_FUNC(zlarrv)"(int *n, d *vl, d *vu, d *d, d *l, d *pivmin, int *isplit, int *m, int *dol, int *dou, d *minrgp, d *rtol1, d *rtol2, d *w, d *werr, d *wgap, int *iblock, int *indexw, d *gers, npy_complex128 *z, int *ldz, int *isuppz, d *work, int *iwork, int *info) nogil +cdef void zlarrv(int *n, d *vl, d *vu, d *d, d *l, d *pivmin, int *isplit, int *m, int *dol, int *dou, d *minrgp, d *rtol1, d *rtol2, d *w, d *werr, d *wgap, int *iblock, int *indexw, d *gers, z *z, int *ldz, int *isuppz, d *work, int *iwork, int *info) noexcept nogil: + + _fortran_zlarrv(n, vl, vu, d, l, pivmin, isplit, m, dol, dou, minrgp, rtol1, rtol2, w, werr, wgap, iblock, indexw, gers, z, ldz, isuppz, work, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlartg "BLAS_FUNC(zlartg)"(npy_complex128 *f, npy_complex128 *g, d *cs, npy_complex128 *sn, npy_complex128 *r) nogil +cdef void zlartg(z *f, z *g, d *cs, z *sn, z *r) noexcept nogil: + + _fortran_zlartg(f, g, cs, sn, r) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlartv "BLAS_FUNC(zlartv)"(int *n, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, d *c, npy_complex128 *s, int *incc) nogil +cdef void zlartv(int *n, z *x, int *incx, z *y, int *incy, d *c, z *s, int *incc) noexcept nogil: + + _fortran_zlartv(n, x, incx, y, incy, c, s, incc) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlarz "BLAS_FUNC(zlarz)"(char *side, int *m, int *n, int *l, npy_complex128 *v, int *incv, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work) nogil +cdef void zlarz(char *side, int *m, int *n, int *l, z *v, int *incv, z *tau, z *c, int *ldc, z *work) noexcept nogil: + + _fortran_zlarz(side, m, n, l, v, incv, tau, c, ldc, work) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlarzb "BLAS_FUNC(zlarzb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, npy_complex128 *v, int *ldv, npy_complex128 *t, int *ldt, npy_complex128 *c, int *ldc, npy_complex128 *work, int *ldwork) nogil +cdef void zlarzb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, z *v, int *ldv, z *t, int *ldt, z *c, int *ldc, z *work, int *ldwork) noexcept nogil: + + _fortran_zlarzb(side, trans, direct, storev, m, n, k, l, v, ldv, t, ldt, c, ldc, work, ldwork) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlarzt "BLAS_FUNC(zlarzt)"(char *direct, char *storev, int *n, int *k, npy_complex128 *v, int *ldv, npy_complex128 *tau, npy_complex128 *t, int *ldt) nogil +cdef void zlarzt(char *direct, char *storev, int *n, int *k, z *v, int *ldv, z *tau, z *t, int *ldt) noexcept nogil: + + _fortran_zlarzt(direct, storev, n, k, v, ldv, tau, t, ldt) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlascl "BLAS_FUNC(zlascl)"(char *type_bn, int *kl, int *ku, d *cfrom, d *cto, int *m, int *n, npy_complex128 *a, int *lda, int *info) nogil +cdef void zlascl(char *type_bn, int *kl, int *ku, d *cfrom, d *cto, int *m, int *n, z *a, int *lda, int *info) noexcept nogil: + + _fortran_zlascl(type_bn, kl, ku, cfrom, cto, m, n, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlaset "BLAS_FUNC(zlaset)"(char *uplo, int *m, int *n, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *a, int *lda) nogil +cdef void zlaset(char *uplo, int *m, int *n, z *alpha, z *beta, z *a, int *lda) noexcept nogil: + + _fortran_zlaset(uplo, m, n, alpha, beta, a, lda) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlasr "BLAS_FUNC(zlasr)"(char *side, char *pivot, char *direct, int *m, int *n, d *c, d *s, npy_complex128 *a, int *lda) nogil +cdef void zlasr(char *side, char *pivot, char *direct, int *m, int *n, d *c, d *s, z *a, int *lda) noexcept nogil: + + _fortran_zlasr(side, pivot, direct, m, n, c, s, a, lda) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlassq "BLAS_FUNC(zlassq)"(int *n, npy_complex128 *x, int *incx, d *scale, d *sumsq) nogil +cdef void zlassq(int *n, z *x, int *incx, d *scale, d *sumsq) noexcept nogil: + + _fortran_zlassq(n, x, incx, scale, sumsq) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlaswp "BLAS_FUNC(zlaswp)"(int *n, npy_complex128 *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) nogil +cdef void zlaswp(int *n, z *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) noexcept nogil: + + _fortran_zlaswp(n, a, lda, k1, k2, ipiv, incx) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlasyf "BLAS_FUNC(zlasyf)"(char *uplo, int *n, int *nb, int *kb, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *w, int *ldw, int *info) nogil +cdef void zlasyf(char *uplo, int *n, int *nb, int *kb, z *a, int *lda, int *ipiv, z *w, int *ldw, int *info) noexcept nogil: + + _fortran_zlasyf(uplo, n, nb, kb, a, lda, ipiv, w, ldw, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlat2c "BLAS_FUNC(zlat2c)"(char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex64 *sa, int *ldsa, int *info) nogil +cdef void zlat2c(char *uplo, int *n, z *a, int *lda, c *sa, int *ldsa, int *info) noexcept nogil: + + _fortran_zlat2c(uplo, n, a, lda, sa, ldsa, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlatbs "BLAS_FUNC(zlatbs)"(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, npy_complex128 *ab, int *ldab, npy_complex128 *x, d *scale, d *cnorm, int *info) nogil +cdef void zlatbs(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, z *ab, int *ldab, z *x, d *scale, d *cnorm, int *info) noexcept nogil: + + _fortran_zlatbs(uplo, trans, diag, normin, n, kd, ab, ldab, x, scale, cnorm, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlatdf "BLAS_FUNC(zlatdf)"(int *ijob, int *n, npy_complex128 *z, int *ldz, npy_complex128 *rhs, d *rdsum, d *rdscal, int *ipiv, int *jpiv) nogil +cdef void zlatdf(int *ijob, int *n, z *z, int *ldz, z *rhs, d *rdsum, d *rdscal, int *ipiv, int *jpiv) noexcept nogil: + + _fortran_zlatdf(ijob, n, z, ldz, rhs, rdsum, rdscal, ipiv, jpiv) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlatps "BLAS_FUNC(zlatps)"(char *uplo, char *trans, char *diag, char *normin, int *n, npy_complex128 *ap, npy_complex128 *x, d *scale, d *cnorm, int *info) nogil +cdef void zlatps(char *uplo, char *trans, char *diag, char *normin, int *n, z *ap, z *x, d *scale, d *cnorm, int *info) noexcept nogil: + + _fortran_zlatps(uplo, trans, diag, normin, n, ap, x, scale, cnorm, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlatrd "BLAS_FUNC(zlatrd)"(char *uplo, int *n, int *nb, npy_complex128 *a, int *lda, d *e, npy_complex128 *tau, npy_complex128 *w, int *ldw) nogil +cdef void zlatrd(char *uplo, int *n, int *nb, z *a, int *lda, d *e, z *tau, z *w, int *ldw) noexcept nogil: + + _fortran_zlatrd(uplo, n, nb, a, lda, e, tau, w, ldw) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlatrs "BLAS_FUNC(zlatrs)"(char *uplo, char *trans, char *diag, char *normin, int *n, npy_complex128 *a, int *lda, npy_complex128 *x, d *scale, d *cnorm, int *info) nogil +cdef void zlatrs(char *uplo, char *trans, char *diag, char *normin, int *n, z *a, int *lda, z *x, d *scale, d *cnorm, int *info) noexcept nogil: + + _fortran_zlatrs(uplo, trans, diag, normin, n, a, lda, x, scale, cnorm, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlatrz "BLAS_FUNC(zlatrz)"(int *m, int *n, int *l, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work) nogil +cdef void zlatrz(int *m, int *n, int *l, z *a, int *lda, z *tau, z *work) noexcept nogil: + + _fortran_zlatrz(m, n, l, a, lda, tau, work) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlauu2 "BLAS_FUNC(zlauu2)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *info) nogil +cdef void zlauu2(char *uplo, int *n, z *a, int *lda, int *info) noexcept nogil: + + _fortran_zlauu2(uplo, n, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zlauum "BLAS_FUNC(zlauum)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *info) nogil +cdef void zlauum(char *uplo, int *n, z *a, int *lda, int *info) noexcept nogil: + + _fortran_zlauum(uplo, n, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zpbcon "BLAS_FUNC(zpbcon)"(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, d *anorm, d *rcond, npy_complex128 *work, d *rwork, int *info) nogil +cdef void zpbcon(char *uplo, int *n, int *kd, z *ab, int *ldab, d *anorm, d *rcond, z *work, d *rwork, int *info) noexcept nogil: + + _fortran_zpbcon(uplo, n, kd, ab, ldab, anorm, rcond, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zpbequ "BLAS_FUNC(zpbequ)"(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, d *s, d *scond, d *amax, int *info) nogil +cdef void zpbequ(char *uplo, int *n, int *kd, z *ab, int *ldab, d *s, d *scond, d *amax, int *info) noexcept nogil: + + _fortran_zpbequ(uplo, n, kd, ab, ldab, s, scond, amax, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zpbrfs "BLAS_FUNC(zpbrfs)"(char *uplo, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *afb, int *ldafb, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil +cdef void zpbrfs(char *uplo, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *afb, int *ldafb, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil: + + _fortran_zpbrfs(uplo, n, kd, nrhs, ab, ldab, afb, ldafb, b, ldb, x, ldx, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zpbstf "BLAS_FUNC(zpbstf)"(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, int *info) nogil +cdef void zpbstf(char *uplo, int *n, int *kd, z *ab, int *ldab, int *info) noexcept nogil: + + _fortran_zpbstf(uplo, n, kd, ab, ldab, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zpbsv "BLAS_FUNC(zpbsv)"(char *uplo, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *b, int *ldb, int *info) nogil +cdef void zpbsv(char *uplo, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *b, int *ldb, int *info) noexcept nogil: + + _fortran_zpbsv(uplo, n, kd, nrhs, ab, ldab, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zpbsvx "BLAS_FUNC(zpbsvx)"(char *fact, char *uplo, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *afb, int *ldafb, char *equed, d *s, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil +cdef void zpbsvx(char *fact, char *uplo, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *afb, int *ldafb, char *equed, d *s, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil: + + _fortran_zpbsvx(fact, uplo, n, kd, nrhs, ab, ldab, afb, ldafb, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zpbtf2 "BLAS_FUNC(zpbtf2)"(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, int *info) nogil +cdef void zpbtf2(char *uplo, int *n, int *kd, z *ab, int *ldab, int *info) noexcept nogil: + + _fortran_zpbtf2(uplo, n, kd, ab, ldab, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zpbtrf "BLAS_FUNC(zpbtrf)"(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, int *info) nogil +cdef void zpbtrf(char *uplo, int *n, int *kd, z *ab, int *ldab, int *info) noexcept nogil: + + _fortran_zpbtrf(uplo, n, kd, ab, ldab, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zpbtrs "BLAS_FUNC(zpbtrs)"(char *uplo, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *b, int *ldb, int *info) nogil +cdef void zpbtrs(char *uplo, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *b, int *ldb, int *info) noexcept nogil: + + _fortran_zpbtrs(uplo, n, kd, nrhs, ab, ldab, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zpftrf "BLAS_FUNC(zpftrf)"(char *transr, char *uplo, int *n, npy_complex128 *a, int *info) nogil +cdef void zpftrf(char *transr, char *uplo, int *n, z *a, int *info) noexcept nogil: + + _fortran_zpftrf(transr, uplo, n, a, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zpftri "BLAS_FUNC(zpftri)"(char *transr, char *uplo, int *n, npy_complex128 *a, int *info) nogil +cdef void zpftri(char *transr, char *uplo, int *n, z *a, int *info) noexcept nogil: + + _fortran_zpftri(transr, uplo, n, a, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zpftrs "BLAS_FUNC(zpftrs)"(char *transr, char *uplo, int *n, int *nrhs, npy_complex128 *a, npy_complex128 *b, int *ldb, int *info) nogil +cdef void zpftrs(char *transr, char *uplo, int *n, int *nrhs, z *a, z *b, int *ldb, int *info) noexcept nogil: + + _fortran_zpftrs(transr, uplo, n, nrhs, a, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zpocon "BLAS_FUNC(zpocon)"(char *uplo, int *n, npy_complex128 *a, int *lda, d *anorm, d *rcond, npy_complex128 *work, d *rwork, int *info) nogil +cdef void zpocon(char *uplo, int *n, z *a, int *lda, d *anorm, d *rcond, z *work, d *rwork, int *info) noexcept nogil: + + _fortran_zpocon(uplo, n, a, lda, anorm, rcond, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zpoequ "BLAS_FUNC(zpoequ)"(int *n, npy_complex128 *a, int *lda, d *s, d *scond, d *amax, int *info) nogil +cdef void zpoequ(int *n, z *a, int *lda, d *s, d *scond, d *amax, int *info) noexcept nogil: + + _fortran_zpoequ(n, a, lda, s, scond, amax, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zpoequb "BLAS_FUNC(zpoequb)"(int *n, npy_complex128 *a, int *lda, d *s, d *scond, d *amax, int *info) nogil +cdef void zpoequb(int *n, z *a, int *lda, d *s, d *scond, d *amax, int *info) noexcept nogil: + + _fortran_zpoequb(n, a, lda, s, scond, amax, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zporfs "BLAS_FUNC(zporfs)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil +cdef void zporfs(char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil: + + _fortran_zporfs(uplo, n, nrhs, a, lda, af, ldaf, b, ldb, x, ldx, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zposv "BLAS_FUNC(zposv)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *info) nogil +cdef void zposv(char *uplo, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, int *info) noexcept nogil: + + _fortran_zposv(uplo, n, nrhs, a, lda, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zposvx "BLAS_FUNC(zposvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, char *equed, d *s, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil +cdef void zposvx(char *fact, char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, char *equed, d *s, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil: + + _fortran_zposvx(fact, uplo, n, nrhs, a, lda, af, ldaf, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zpotf2 "BLAS_FUNC(zpotf2)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *info) nogil +cdef void zpotf2(char *uplo, int *n, z *a, int *lda, int *info) noexcept nogil: + + _fortran_zpotf2(uplo, n, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zpotrf "BLAS_FUNC(zpotrf)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *info) nogil +cdef void zpotrf(char *uplo, int *n, z *a, int *lda, int *info) noexcept nogil: + + _fortran_zpotrf(uplo, n, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zpotri "BLAS_FUNC(zpotri)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *info) nogil +cdef void zpotri(char *uplo, int *n, z *a, int *lda, int *info) noexcept nogil: + + _fortran_zpotri(uplo, n, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zpotrs "BLAS_FUNC(zpotrs)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *info) nogil +cdef void zpotrs(char *uplo, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, int *info) noexcept nogil: + + _fortran_zpotrs(uplo, n, nrhs, a, lda, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zppcon "BLAS_FUNC(zppcon)"(char *uplo, int *n, npy_complex128 *ap, d *anorm, d *rcond, npy_complex128 *work, d *rwork, int *info) nogil +cdef void zppcon(char *uplo, int *n, z *ap, d *anorm, d *rcond, z *work, d *rwork, int *info) noexcept nogil: + + _fortran_zppcon(uplo, n, ap, anorm, rcond, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zppequ "BLAS_FUNC(zppequ)"(char *uplo, int *n, npy_complex128 *ap, d *s, d *scond, d *amax, int *info) nogil +cdef void zppequ(char *uplo, int *n, z *ap, d *s, d *scond, d *amax, int *info) noexcept nogil: + + _fortran_zppequ(uplo, n, ap, s, scond, amax, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zpprfs "BLAS_FUNC(zpprfs)"(char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil +cdef void zpprfs(char *uplo, int *n, int *nrhs, z *ap, z *afp, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil: + + _fortran_zpprfs(uplo, n, nrhs, ap, afp, b, ldb, x, ldx, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zppsv "BLAS_FUNC(zppsv)"(char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *b, int *ldb, int *info) nogil +cdef void zppsv(char *uplo, int *n, int *nrhs, z *ap, z *b, int *ldb, int *info) noexcept nogil: + + _fortran_zppsv(uplo, n, nrhs, ap, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zppsvx "BLAS_FUNC(zppsvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, char *equed, d *s, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil +cdef void zppsvx(char *fact, char *uplo, int *n, int *nrhs, z *ap, z *afp, char *equed, d *s, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil: + + _fortran_zppsvx(fact, uplo, n, nrhs, ap, afp, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zpptrf "BLAS_FUNC(zpptrf)"(char *uplo, int *n, npy_complex128 *ap, int *info) nogil +cdef void zpptrf(char *uplo, int *n, z *ap, int *info) noexcept nogil: + + _fortran_zpptrf(uplo, n, ap, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zpptri "BLAS_FUNC(zpptri)"(char *uplo, int *n, npy_complex128 *ap, int *info) nogil +cdef void zpptri(char *uplo, int *n, z *ap, int *info) noexcept nogil: + + _fortran_zpptri(uplo, n, ap, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zpptrs "BLAS_FUNC(zpptrs)"(char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *b, int *ldb, int *info) nogil +cdef void zpptrs(char *uplo, int *n, int *nrhs, z *ap, z *b, int *ldb, int *info) noexcept nogil: + + _fortran_zpptrs(uplo, n, nrhs, ap, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zpstf2 "BLAS_FUNC(zpstf2)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) nogil +cdef void zpstf2(char *uplo, int *n, z *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) noexcept nogil: + + _fortran_zpstf2(uplo, n, a, lda, piv, rank, tol, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zpstrf "BLAS_FUNC(zpstrf)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) nogil +cdef void zpstrf(char *uplo, int *n, z *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) noexcept nogil: + + _fortran_zpstrf(uplo, n, a, lda, piv, rank, tol, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zptcon "BLAS_FUNC(zptcon)"(int *n, d *d, npy_complex128 *e, d *anorm, d *rcond, d *rwork, int *info) nogil +cdef void zptcon(int *n, d *d, z *e, d *anorm, d *rcond, d *rwork, int *info) noexcept nogil: + + _fortran_zptcon(n, d, e, anorm, rcond, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zpteqr "BLAS_FUNC(zpteqr)"(char *compz, int *n, d *d, d *e, npy_complex128 *z, int *ldz, d *work, int *info) nogil +cdef void zpteqr(char *compz, int *n, d *d, d *e, z *z, int *ldz, d *work, int *info) noexcept nogil: + + _fortran_zpteqr(compz, n, d, e, z, ldz, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zptrfs "BLAS_FUNC(zptrfs)"(char *uplo, int *n, int *nrhs, d *d, npy_complex128 *e, d *df, npy_complex128 *ef, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil +cdef void zptrfs(char *uplo, int *n, int *nrhs, d *d, z *e, d *df, z *ef, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil: + + _fortran_zptrfs(uplo, n, nrhs, d, e, df, ef, b, ldb, x, ldx, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zptsv "BLAS_FUNC(zptsv)"(int *n, int *nrhs, d *d, npy_complex128 *e, npy_complex128 *b, int *ldb, int *info) nogil +cdef void zptsv(int *n, int *nrhs, d *d, z *e, z *b, int *ldb, int *info) noexcept nogil: + + _fortran_zptsv(n, nrhs, d, e, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zptsvx "BLAS_FUNC(zptsvx)"(char *fact, int *n, int *nrhs, d *d, npy_complex128 *e, d *df, npy_complex128 *ef, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil +cdef void zptsvx(char *fact, int *n, int *nrhs, d *d, z *e, d *df, z *ef, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil: + + _fortran_zptsvx(fact, n, nrhs, d, e, df, ef, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zpttrf "BLAS_FUNC(zpttrf)"(int *n, d *d, npy_complex128 *e, int *info) nogil +cdef void zpttrf(int *n, d *d, z *e, int *info) noexcept nogil: + + _fortran_zpttrf(n, d, e, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zpttrs "BLAS_FUNC(zpttrs)"(char *uplo, int *n, int *nrhs, d *d, npy_complex128 *e, npy_complex128 *b, int *ldb, int *info) nogil +cdef void zpttrs(char *uplo, int *n, int *nrhs, d *d, z *e, z *b, int *ldb, int *info) noexcept nogil: + + _fortran_zpttrs(uplo, n, nrhs, d, e, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zptts2 "BLAS_FUNC(zptts2)"(int *iuplo, int *n, int *nrhs, d *d, npy_complex128 *e, npy_complex128 *b, int *ldb) nogil +cdef void zptts2(int *iuplo, int *n, int *nrhs, d *d, z *e, z *b, int *ldb) noexcept nogil: + + _fortran_zptts2(iuplo, n, nrhs, d, e, b, ldb) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zrot "BLAS_FUNC(zrot)"(int *n, npy_complex128 *cx, int *incx, npy_complex128 *cy, int *incy, d *c, npy_complex128 *s) nogil +cdef void zrot(int *n, z *cx, int *incx, z *cy, int *incy, d *c, z *s) noexcept nogil: + + _fortran_zrot(n, cx, incx, cy, incy, c, s) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zspcon "BLAS_FUNC(zspcon)"(char *uplo, int *n, npy_complex128 *ap, int *ipiv, d *anorm, d *rcond, npy_complex128 *work, int *info) nogil +cdef void zspcon(char *uplo, int *n, z *ap, int *ipiv, d *anorm, d *rcond, z *work, int *info) noexcept nogil: + + _fortran_zspcon(uplo, n, ap, ipiv, anorm, rcond, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zspmv "BLAS_FUNC(zspmv)"(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *ap, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy) nogil +cdef void zspmv(char *uplo, int *n, z *alpha, z *ap, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil: + + _fortran_zspmv(uplo, n, alpha, ap, x, incx, beta, y, incy) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zspr "BLAS_FUNC(zspr)"(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *ap) nogil +cdef void zspr(char *uplo, int *n, z *alpha, z *x, int *incx, z *ap) noexcept nogil: + + _fortran_zspr(uplo, n, alpha, x, incx, ap) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zsprfs "BLAS_FUNC(zsprfs)"(char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil +cdef void zsprfs(char *uplo, int *n, int *nrhs, z *ap, z *afp, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil: + + _fortran_zsprfs(uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zspsv "BLAS_FUNC(zspsv)"(char *uplo, int *n, int *nrhs, npy_complex128 *ap, int *ipiv, npy_complex128 *b, int *ldb, int *info) nogil +cdef void zspsv(char *uplo, int *n, int *nrhs, z *ap, int *ipiv, z *b, int *ldb, int *info) noexcept nogil: + + _fortran_zspsv(uplo, n, nrhs, ap, ipiv, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zspsvx "BLAS_FUNC(zspsvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil +cdef void zspsvx(char *fact, char *uplo, int *n, int *nrhs, z *ap, z *afp, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil: + + _fortran_zspsvx(fact, uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zsptrf "BLAS_FUNC(zsptrf)"(char *uplo, int *n, npy_complex128 *ap, int *ipiv, int *info) nogil +cdef void zsptrf(char *uplo, int *n, z *ap, int *ipiv, int *info) noexcept nogil: + + _fortran_zsptrf(uplo, n, ap, ipiv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zsptri "BLAS_FUNC(zsptri)"(char *uplo, int *n, npy_complex128 *ap, int *ipiv, npy_complex128 *work, int *info) nogil +cdef void zsptri(char *uplo, int *n, z *ap, int *ipiv, z *work, int *info) noexcept nogil: + + _fortran_zsptri(uplo, n, ap, ipiv, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zsptrs "BLAS_FUNC(zsptrs)"(char *uplo, int *n, int *nrhs, npy_complex128 *ap, int *ipiv, npy_complex128 *b, int *ldb, int *info) nogil +cdef void zsptrs(char *uplo, int *n, int *nrhs, z *ap, int *ipiv, z *b, int *ldb, int *info) noexcept nogil: + + _fortran_zsptrs(uplo, n, nrhs, ap, ipiv, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zstedc "BLAS_FUNC(zstedc)"(char *compz, int *n, d *d, d *e, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil +cdef void zstedc(char *compz, int *n, d *d, d *e, z *z, int *ldz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_zstedc(compz, n, d, e, z, ldz, work, lwork, rwork, lrwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zstegr "BLAS_FUNC(zstegr)"(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, npy_complex128 *z, int *ldz, int *isuppz, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil +cdef void zstegr(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, int *isuppz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_zstegr(jobz, range, n, d, e, vl, vu, il, iu, abstol, m, w, z, ldz, isuppz, work, lwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zstein "BLAS_FUNC(zstein)"(int *n, d *d, d *e, int *m, d *w, int *iblock, int *isplit, npy_complex128 *z, int *ldz, d *work, int *iwork, int *ifail, int *info) nogil +cdef void zstein(int *n, d *d, d *e, int *m, d *w, int *iblock, int *isplit, z *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil: + + _fortran_zstein(n, d, e, m, w, iblock, isplit, z, ldz, work, iwork, ifail, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zstemr "BLAS_FUNC(zstemr)"(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, int *m, d *w, npy_complex128 *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil +cdef void zstemr(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, int *m, d *w, z *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_zstemr(jobz, range, n, d, e, vl, vu, il, iu, m, w, z, ldz, nzc, isuppz, tryrac, work, lwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zsteqr "BLAS_FUNC(zsteqr)"(char *compz, int *n, d *d, d *e, npy_complex128 *z, int *ldz, d *work, int *info) nogil +cdef void zsteqr(char *compz, int *n, d *d, d *e, z *z, int *ldz, d *work, int *info) noexcept nogil: + + _fortran_zsteqr(compz, n, d, e, z, ldz, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zsycon "BLAS_FUNC(zsycon)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, d *anorm, d *rcond, npy_complex128 *work, int *info) nogil +cdef void zsycon(char *uplo, int *n, z *a, int *lda, int *ipiv, d *anorm, d *rcond, z *work, int *info) noexcept nogil: + + _fortran_zsycon(uplo, n, a, lda, ipiv, anorm, rcond, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zsyconv "BLAS_FUNC(zsyconv)"(char *uplo, char *way, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *info) nogil +cdef void zsyconv(char *uplo, char *way, int *n, z *a, int *lda, int *ipiv, z *work, int *info) noexcept nogil: + + _fortran_zsyconv(uplo, way, n, a, lda, ipiv, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zsyequb "BLAS_FUNC(zsyequb)"(char *uplo, int *n, npy_complex128 *a, int *lda, d *s, d *scond, d *amax, npy_complex128 *work, int *info) nogil +cdef void zsyequb(char *uplo, int *n, z *a, int *lda, d *s, d *scond, d *amax, z *work, int *info) noexcept nogil: + + _fortran_zsyequb(uplo, n, a, lda, s, scond, amax, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zsymv "BLAS_FUNC(zsymv)"(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy) nogil +cdef void zsymv(char *uplo, int *n, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil: + + _fortran_zsymv(uplo, n, alpha, a, lda, x, incx, beta, y, incy) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zsyr "BLAS_FUNC(zsyr)"(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *a, int *lda) nogil +cdef void zsyr(char *uplo, int *n, z *alpha, z *x, int *incx, z *a, int *lda) noexcept nogil: + + _fortran_zsyr(uplo, n, alpha, x, incx, a, lda) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zsyrfs "BLAS_FUNC(zsyrfs)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil +cdef void zsyrfs(char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil: + + _fortran_zsyrfs(uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zsysv "BLAS_FUNC(zsysv)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *work, int *lwork, int *info) nogil +cdef void zsysv(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, z *work, int *lwork, int *info) noexcept nogil: + + _fortran_zsysv(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zsysvx "BLAS_FUNC(zsysvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, int *lwork, d *rwork, int *info) nogil +cdef void zsysvx(char *fact, char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, int *lwork, d *rwork, int *info) noexcept nogil: + + _fortran_zsysvx(fact, uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, lwork, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zsyswapr "BLAS_FUNC(zsyswapr)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *i1, int *i2) nogil +cdef void zsyswapr(char *uplo, int *n, z *a, int *lda, int *i1, int *i2) noexcept nogil: + + _fortran_zsyswapr(uplo, n, a, lda, i1, i2) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zsytf2 "BLAS_FUNC(zsytf2)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, int *info) nogil +cdef void zsytf2(char *uplo, int *n, z *a, int *lda, int *ipiv, int *info) noexcept nogil: + + _fortran_zsytf2(uplo, n, a, lda, ipiv, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zsytrf "BLAS_FUNC(zsytrf)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *lwork, int *info) nogil +cdef void zsytrf(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *lwork, int *info) noexcept nogil: + + _fortran_zsytrf(uplo, n, a, lda, ipiv, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zsytri "BLAS_FUNC(zsytri)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *info) nogil +cdef void zsytri(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *info) noexcept nogil: + + _fortran_zsytri(uplo, n, a, lda, ipiv, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zsytri2 "BLAS_FUNC(zsytri2)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *lwork, int *info) nogil +cdef void zsytri2(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *lwork, int *info) noexcept nogil: + + _fortran_zsytri2(uplo, n, a, lda, ipiv, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zsytri2x "BLAS_FUNC(zsytri2x)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *nb, int *info) nogil +cdef void zsytri2x(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *nb, int *info) noexcept nogil: + + _fortran_zsytri2x(uplo, n, a, lda, ipiv, work, nb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zsytrs "BLAS_FUNC(zsytrs)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, int *info) nogil +cdef void zsytrs(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, int *info) noexcept nogil: + + _fortran_zsytrs(uplo, n, nrhs, a, lda, ipiv, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zsytrs2 "BLAS_FUNC(zsytrs2)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *work, int *info) nogil +cdef void zsytrs2(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, z *work, int *info) noexcept nogil: + + _fortran_zsytrs2(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ztbcon "BLAS_FUNC(ztbcon)"(char *norm, char *uplo, char *diag, int *n, int *kd, npy_complex128 *ab, int *ldab, d *rcond, npy_complex128 *work, d *rwork, int *info) nogil +cdef void ztbcon(char *norm, char *uplo, char *diag, int *n, int *kd, z *ab, int *ldab, d *rcond, z *work, d *rwork, int *info) noexcept nogil: + + _fortran_ztbcon(norm, uplo, diag, n, kd, ab, ldab, rcond, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ztbrfs "BLAS_FUNC(ztbrfs)"(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil +cdef void ztbrfs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil: + + _fortran_ztbrfs(uplo, trans, diag, n, kd, nrhs, ab, ldab, b, ldb, x, ldx, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ztbtrs "BLAS_FUNC(ztbtrs)"(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *b, int *ldb, int *info) nogil +cdef void ztbtrs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *b, int *ldb, int *info) noexcept nogil: + + _fortran_ztbtrs(uplo, trans, diag, n, kd, nrhs, ab, ldab, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ztfsm "BLAS_FUNC(ztfsm)"(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, npy_complex128 *b, int *ldb) nogil +cdef void ztfsm(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, z *alpha, z *a, z *b, int *ldb) noexcept nogil: + + _fortran_ztfsm(transr, side, uplo, trans, diag, m, n, alpha, a, b, ldb) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ztftri "BLAS_FUNC(ztftri)"(char *transr, char *uplo, char *diag, int *n, npy_complex128 *a, int *info) nogil +cdef void ztftri(char *transr, char *uplo, char *diag, int *n, z *a, int *info) noexcept nogil: + + _fortran_ztftri(transr, uplo, diag, n, a, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ztfttp "BLAS_FUNC(ztfttp)"(char *transr, char *uplo, int *n, npy_complex128 *arf, npy_complex128 *ap, int *info) nogil +cdef void ztfttp(char *transr, char *uplo, int *n, z *arf, z *ap, int *info) noexcept nogil: + + _fortran_ztfttp(transr, uplo, n, arf, ap, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ztfttr "BLAS_FUNC(ztfttr)"(char *transr, char *uplo, int *n, npy_complex128 *arf, npy_complex128 *a, int *lda, int *info) nogil +cdef void ztfttr(char *transr, char *uplo, int *n, z *arf, z *a, int *lda, int *info) noexcept nogil: + + _fortran_ztfttr(transr, uplo, n, arf, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ztgevc "BLAS_FUNC(ztgevc)"(char *side, char *howmny, bint *select, int *n, npy_complex128 *s, int *lds, npy_complex128 *p, int *ldp, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, int *mm, int *m, npy_complex128 *work, d *rwork, int *info) nogil +cdef void ztgevc(char *side, char *howmny, bint *select, int *n, z *s, int *lds, z *p, int *ldp, z *vl, int *ldvl, z *vr, int *ldvr, int *mm, int *m, z *work, d *rwork, int *info) noexcept nogil: + + _fortran_ztgevc(side, howmny, select, n, s, lds, p, ldp, vl, ldvl, vr, ldvr, mm, m, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ztgex2 "BLAS_FUNC(ztgex2)"(bint *wantq, bint *wantz, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *q, int *ldq, npy_complex128 *z, int *ldz, int *j1, int *info) nogil +cdef void ztgex2(bint *wantq, bint *wantz, int *n, z *a, int *lda, z *b, int *ldb, z *q, int *ldq, z *z, int *ldz, int *j1, int *info) noexcept nogil: + + _fortran_ztgex2(wantq, wantz, n, a, lda, b, ldb, q, ldq, z, ldz, j1, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ztgexc "BLAS_FUNC(ztgexc)"(bint *wantq, bint *wantz, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *q, int *ldq, npy_complex128 *z, int *ldz, int *ifst, int *ilst, int *info) nogil +cdef void ztgexc(bint *wantq, bint *wantz, int *n, z *a, int *lda, z *b, int *ldb, z *q, int *ldq, z *z, int *ldz, int *ifst, int *ilst, int *info) noexcept nogil: + + _fortran_ztgexc(wantq, wantz, n, a, lda, b, ldb, q, ldq, z, ldz, ifst, ilst, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ztgsen "BLAS_FUNC(ztgsen)"(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *q, int *ldq, npy_complex128 *z, int *ldz, int *m, d *pl, d *pr, d *dif, npy_complex128 *work, int *lwork, int *iwork, int *liwork, int *info) nogil +cdef void ztgsen(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, z *a, int *lda, z *b, int *ldb, z *alpha, z *beta, z *q, int *ldq, z *z, int *ldz, int *m, d *pl, d *pr, d *dif, z *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil: + + _fortran_ztgsen(ijob, wantq, wantz, select, n, a, lda, b, ldb, alpha, beta, q, ldq, z, ldz, m, pl, pr, dif, work, lwork, iwork, liwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ztgsja "BLAS_FUNC(ztgsja)"(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, d *tola, d *tolb, d *alpha, d *beta, npy_complex128 *u, int *ldu, npy_complex128 *v, int *ldv, npy_complex128 *q, int *ldq, npy_complex128 *work, int *ncycle, int *info) nogil +cdef void ztgsja(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, z *a, int *lda, z *b, int *ldb, d *tola, d *tolb, d *alpha, d *beta, z *u, int *ldu, z *v, int *ldv, z *q, int *ldq, z *work, int *ncycle, int *info) noexcept nogil: + + _fortran_ztgsja(jobu, jobv, jobq, m, p, n, k, l, a, lda, b, ldb, tola, tolb, alpha, beta, u, ldu, v, ldv, q, ldq, work, ncycle, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ztgsna "BLAS_FUNC(ztgsna)"(char *job, char *howmny, bint *select, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, d *s, d *dif, int *mm, int *m, npy_complex128 *work, int *lwork, int *iwork, int *info) nogil +cdef void ztgsna(char *job, char *howmny, bint *select, int *n, z *a, int *lda, z *b, int *ldb, z *vl, int *ldvl, z *vr, int *ldvr, d *s, d *dif, int *mm, int *m, z *work, int *lwork, int *iwork, int *info) noexcept nogil: + + _fortran_ztgsna(job, howmny, select, n, a, lda, b, ldb, vl, ldvl, vr, ldvr, s, dif, mm, m, work, lwork, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ztgsy2 "BLAS_FUNC(ztgsy2)"(char *trans, int *ijob, int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *c, int *ldc, npy_complex128 *d, int *ldd, npy_complex128 *e, int *lde, npy_complex128 *f, int *ldf, d *scale, d *rdsum, d *rdscal, int *info) nogil +cdef void ztgsy2(char *trans, int *ijob, int *m, int *n, z *a, int *lda, z *b, int *ldb, z *c, int *ldc, z *d, int *ldd, z *e, int *lde, z *f, int *ldf, d *scale, d *rdsum, d *rdscal, int *info) noexcept nogil: + + _fortran_ztgsy2(trans, ijob, m, n, a, lda, b, ldb, c, ldc, d, ldd, e, lde, f, ldf, scale, rdsum, rdscal, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ztgsyl "BLAS_FUNC(ztgsyl)"(char *trans, int *ijob, int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *c, int *ldc, npy_complex128 *d, int *ldd, npy_complex128 *e, int *lde, npy_complex128 *f, int *ldf, d *scale, d *dif, npy_complex128 *work, int *lwork, int *iwork, int *info) nogil +cdef void ztgsyl(char *trans, int *ijob, int *m, int *n, z *a, int *lda, z *b, int *ldb, z *c, int *ldc, z *d, int *ldd, z *e, int *lde, z *f, int *ldf, d *scale, d *dif, z *work, int *lwork, int *iwork, int *info) noexcept nogil: + + _fortran_ztgsyl(trans, ijob, m, n, a, lda, b, ldb, c, ldc, d, ldd, e, lde, f, ldf, scale, dif, work, lwork, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ztpcon "BLAS_FUNC(ztpcon)"(char *norm, char *uplo, char *diag, int *n, npy_complex128 *ap, d *rcond, npy_complex128 *work, d *rwork, int *info) nogil +cdef void ztpcon(char *norm, char *uplo, char *diag, int *n, z *ap, d *rcond, z *work, d *rwork, int *info) noexcept nogil: + + _fortran_ztpcon(norm, uplo, diag, n, ap, rcond, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ztpmqrt "BLAS_FUNC(ztpmqrt)"(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, npy_complex128 *v, int *ldv, npy_complex128 *t, int *ldt, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *work, int *info) nogil +cdef void ztpmqrt(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, z *v, int *ldv, z *t, int *ldt, z *a, int *lda, z *b, int *ldb, z *work, int *info) noexcept nogil: + + _fortran_ztpmqrt(side, trans, m, n, k, l, nb, v, ldv, t, ldt, a, lda, b, ldb, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ztpqrt "BLAS_FUNC(ztpqrt)"(int *m, int *n, int *l, int *nb, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *t, int *ldt, npy_complex128 *work, int *info) nogil +cdef void ztpqrt(int *m, int *n, int *l, int *nb, z *a, int *lda, z *b, int *ldb, z *t, int *ldt, z *work, int *info) noexcept nogil: + + _fortran_ztpqrt(m, n, l, nb, a, lda, b, ldb, t, ldt, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ztpqrt2 "BLAS_FUNC(ztpqrt2)"(int *m, int *n, int *l, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *t, int *ldt, int *info) nogil +cdef void ztpqrt2(int *m, int *n, int *l, z *a, int *lda, z *b, int *ldb, z *t, int *ldt, int *info) noexcept nogil: + + _fortran_ztpqrt2(m, n, l, a, lda, b, ldb, t, ldt, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ztprfb "BLAS_FUNC(ztprfb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, npy_complex128 *v, int *ldv, npy_complex128 *t, int *ldt, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *work, int *ldwork) nogil +cdef void ztprfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, z *v, int *ldv, z *t, int *ldt, z *a, int *lda, z *b, int *ldb, z *work, int *ldwork) noexcept nogil: + + _fortran_ztprfb(side, trans, direct, storev, m, n, k, l, v, ldv, t, ldt, a, lda, b, ldb, work, ldwork) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ztprfs "BLAS_FUNC(ztprfs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil +cdef void ztprfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, z *ap, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil: + + _fortran_ztprfs(uplo, trans, diag, n, nrhs, ap, b, ldb, x, ldx, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ztptri "BLAS_FUNC(ztptri)"(char *uplo, char *diag, int *n, npy_complex128 *ap, int *info) nogil +cdef void ztptri(char *uplo, char *diag, int *n, z *ap, int *info) noexcept nogil: + + _fortran_ztptri(uplo, diag, n, ap, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ztptrs "BLAS_FUNC(ztptrs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *b, int *ldb, int *info) nogil +cdef void ztptrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, z *ap, z *b, int *ldb, int *info) noexcept nogil: + + _fortran_ztptrs(uplo, trans, diag, n, nrhs, ap, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ztpttf "BLAS_FUNC(ztpttf)"(char *transr, char *uplo, int *n, npy_complex128 *ap, npy_complex128 *arf, int *info) nogil +cdef void ztpttf(char *transr, char *uplo, int *n, z *ap, z *arf, int *info) noexcept nogil: + + _fortran_ztpttf(transr, uplo, n, ap, arf, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ztpttr "BLAS_FUNC(ztpttr)"(char *uplo, int *n, npy_complex128 *ap, npy_complex128 *a, int *lda, int *info) nogil +cdef void ztpttr(char *uplo, int *n, z *ap, z *a, int *lda, int *info) noexcept nogil: + + _fortran_ztpttr(uplo, n, ap, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ztrcon "BLAS_FUNC(ztrcon)"(char *norm, char *uplo, char *diag, int *n, npy_complex128 *a, int *lda, d *rcond, npy_complex128 *work, d *rwork, int *info) nogil +cdef void ztrcon(char *norm, char *uplo, char *diag, int *n, z *a, int *lda, d *rcond, z *work, d *rwork, int *info) noexcept nogil: + + _fortran_ztrcon(norm, uplo, diag, n, a, lda, rcond, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ztrevc "BLAS_FUNC(ztrevc)"(char *side, char *howmny, bint *select, int *n, npy_complex128 *t, int *ldt, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, int *mm, int *m, npy_complex128 *work, d *rwork, int *info) nogil +cdef void ztrevc(char *side, char *howmny, bint *select, int *n, z *t, int *ldt, z *vl, int *ldvl, z *vr, int *ldvr, int *mm, int *m, z *work, d *rwork, int *info) noexcept nogil: + + _fortran_ztrevc(side, howmny, select, n, t, ldt, vl, ldvl, vr, ldvr, mm, m, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ztrexc "BLAS_FUNC(ztrexc)"(char *compq, int *n, npy_complex128 *t, int *ldt, npy_complex128 *q, int *ldq, int *ifst, int *ilst, int *info) nogil +cdef void ztrexc(char *compq, int *n, z *t, int *ldt, z *q, int *ldq, int *ifst, int *ilst, int *info) noexcept nogil: + + _fortran_ztrexc(compq, n, t, ldt, q, ldq, ifst, ilst, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ztrrfs "BLAS_FUNC(ztrrfs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil +cdef void ztrrfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil: + + _fortran_ztrrfs(uplo, trans, diag, n, nrhs, a, lda, b, ldb, x, ldx, ferr, berr, work, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ztrsen "BLAS_FUNC(ztrsen)"(char *job, char *compq, bint *select, int *n, npy_complex128 *t, int *ldt, npy_complex128 *q, int *ldq, npy_complex128 *w, int *m, d *s, d *sep, npy_complex128 *work, int *lwork, int *info) nogil +cdef void ztrsen(char *job, char *compq, bint *select, int *n, z *t, int *ldt, z *q, int *ldq, z *w, int *m, d *s, d *sep, z *work, int *lwork, int *info) noexcept nogil: + + _fortran_ztrsen(job, compq, select, n, t, ldt, q, ldq, w, m, s, sep, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ztrsna "BLAS_FUNC(ztrsna)"(char *job, char *howmny, bint *select, int *n, npy_complex128 *t, int *ldt, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, d *s, d *sep, int *mm, int *m, npy_complex128 *work, int *ldwork, d *rwork, int *info) nogil +cdef void ztrsna(char *job, char *howmny, bint *select, int *n, z *t, int *ldt, z *vl, int *ldvl, z *vr, int *ldvr, d *s, d *sep, int *mm, int *m, z *work, int *ldwork, d *rwork, int *info) noexcept nogil: + + _fortran_ztrsna(job, howmny, select, n, t, ldt, vl, ldvl, vr, ldvr, s, sep, mm, m, work, ldwork, rwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ztrsyl "BLAS_FUNC(ztrsyl)"(char *trana, char *tranb, int *isgn, int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *c, int *ldc, d *scale, int *info) nogil +cdef void ztrsyl(char *trana, char *tranb, int *isgn, int *m, int *n, z *a, int *lda, z *b, int *ldb, z *c, int *ldc, d *scale, int *info) noexcept nogil: + + _fortran_ztrsyl(trana, tranb, isgn, m, n, a, lda, b, ldb, c, ldc, scale, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ztrti2 "BLAS_FUNC(ztrti2)"(char *uplo, char *diag, int *n, npy_complex128 *a, int *lda, int *info) nogil +cdef void ztrti2(char *uplo, char *diag, int *n, z *a, int *lda, int *info) noexcept nogil: + + _fortran_ztrti2(uplo, diag, n, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ztrtri "BLAS_FUNC(ztrtri)"(char *uplo, char *diag, int *n, npy_complex128 *a, int *lda, int *info) nogil +cdef void ztrtri(char *uplo, char *diag, int *n, z *a, int *lda, int *info) noexcept nogil: + + _fortran_ztrtri(uplo, diag, n, a, lda, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ztrtrs "BLAS_FUNC(ztrtrs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *info) nogil +cdef void ztrtrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, int *info) noexcept nogil: + + _fortran_ztrtrs(uplo, trans, diag, n, nrhs, a, lda, b, ldb, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ztrttf "BLAS_FUNC(ztrttf)"(char *transr, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *arf, int *info) nogil +cdef void ztrttf(char *transr, char *uplo, int *n, z *a, int *lda, z *arf, int *info) noexcept nogil: + + _fortran_ztrttf(transr, uplo, n, a, lda, arf, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ztrttp "BLAS_FUNC(ztrttp)"(char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *ap, int *info) nogil +cdef void ztrttp(char *uplo, int *n, z *a, int *lda, z *ap, int *info) noexcept nogil: + + _fortran_ztrttp(uplo, n, a, lda, ap, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_ztzrzf "BLAS_FUNC(ztzrzf)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil +cdef void ztzrzf(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil: + + _fortran_ztzrzf(m, n, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zunbdb "BLAS_FUNC(zunbdb)"(char *trans, char *signs, int *m, int *p, int *q, npy_complex128 *x11, int *ldx11, npy_complex128 *x12, int *ldx12, npy_complex128 *x21, int *ldx21, npy_complex128 *x22, int *ldx22, d *theta, d *phi, npy_complex128 *taup1, npy_complex128 *taup2, npy_complex128 *tauq1, npy_complex128 *tauq2, npy_complex128 *work, int *lwork, int *info) nogil +cdef void zunbdb(char *trans, char *signs, int *m, int *p, int *q, z *x11, int *ldx11, z *x12, int *ldx12, z *x21, int *ldx21, z *x22, int *ldx22, d *theta, d *phi, z *taup1, z *taup2, z *tauq1, z *tauq2, z *work, int *lwork, int *info) noexcept nogil: + + _fortran_zunbdb(trans, signs, m, p, q, x11, ldx11, x12, ldx12, x21, ldx21, x22, ldx22, theta, phi, taup1, taup2, tauq1, tauq2, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zuncsd "BLAS_FUNC(zuncsd)"(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, npy_complex128 *x11, int *ldx11, npy_complex128 *x12, int *ldx12, npy_complex128 *x21, int *ldx21, npy_complex128 *x22, int *ldx22, d *theta, npy_complex128 *u1, int *ldu1, npy_complex128 *u2, int *ldu2, npy_complex128 *v1t, int *ldv1t, npy_complex128 *v2t, int *ldv2t, npy_complex128 *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *info) nogil +cdef void zuncsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, z *x11, int *ldx11, z *x12, int *ldx12, z *x21, int *ldx21, z *x22, int *ldx22, d *theta, z *u1, int *ldu1, z *u2, int *ldu2, z *v1t, int *ldv1t, z *v2t, int *ldv2t, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *info) noexcept nogil: + + _fortran_zuncsd(jobu1, jobu2, jobv1t, jobv2t, trans, signs, m, p, q, x11, ldx11, x12, ldx12, x21, ldx21, x22, ldx22, theta, u1, ldu1, u2, ldu2, v1t, ldv1t, v2t, ldv2t, work, lwork, rwork, lrwork, iwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zung2l "BLAS_FUNC(zung2l)"(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info) nogil +cdef void zung2l(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil: + + _fortran_zung2l(m, n, k, a, lda, tau, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zung2r "BLAS_FUNC(zung2r)"(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info) nogil +cdef void zung2r(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil: + + _fortran_zung2r(m, n, k, a, lda, tau, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zungbr "BLAS_FUNC(zungbr)"(char *vect, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil +cdef void zungbr(char *vect, int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil: + + _fortran_zungbr(vect, m, n, k, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zunghr "BLAS_FUNC(zunghr)"(int *n, int *ilo, int *ihi, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil +cdef void zunghr(int *n, int *ilo, int *ihi, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil: + + _fortran_zunghr(n, ilo, ihi, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zungl2 "BLAS_FUNC(zungl2)"(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info) nogil +cdef void zungl2(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil: + + _fortran_zungl2(m, n, k, a, lda, tau, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zunglq "BLAS_FUNC(zunglq)"(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil +cdef void zunglq(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil: + + _fortran_zunglq(m, n, k, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zungql "BLAS_FUNC(zungql)"(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil +cdef void zungql(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil: + + _fortran_zungql(m, n, k, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zungqr "BLAS_FUNC(zungqr)"(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil +cdef void zungqr(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil: + + _fortran_zungqr(m, n, k, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zungr2 "BLAS_FUNC(zungr2)"(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info) nogil +cdef void zungr2(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil: + + _fortran_zungr2(m, n, k, a, lda, tau, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zungrq "BLAS_FUNC(zungrq)"(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil +cdef void zungrq(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil: + + _fortran_zungrq(m, n, k, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zungtr "BLAS_FUNC(zungtr)"(char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil +cdef void zungtr(char *uplo, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil: + + _fortran_zungtr(uplo, n, a, lda, tau, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zunm2l "BLAS_FUNC(zunm2l)"(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info) nogil +cdef void zunm2l(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil: + + _fortran_zunm2l(side, trans, m, n, k, a, lda, tau, c, ldc, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zunm2r "BLAS_FUNC(zunm2r)"(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info) nogil +cdef void zunm2r(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil: + + _fortran_zunm2r(side, trans, m, n, k, a, lda, tau, c, ldc, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zunmbr "BLAS_FUNC(zunmbr)"(char *vect, char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info) nogil +cdef void zunmbr(char *vect, char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil: + + _fortran_zunmbr(vect, side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zunmhr "BLAS_FUNC(zunmhr)"(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info) nogil +cdef void zunmhr(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil: + + _fortran_zunmhr(side, trans, m, n, ilo, ihi, a, lda, tau, c, ldc, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zunml2 "BLAS_FUNC(zunml2)"(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info) nogil +cdef void zunml2(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil: + + _fortran_zunml2(side, trans, m, n, k, a, lda, tau, c, ldc, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zunmlq "BLAS_FUNC(zunmlq)"(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info) nogil +cdef void zunmlq(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil: + + _fortran_zunmlq(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zunmql "BLAS_FUNC(zunmql)"(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info) nogil +cdef void zunmql(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil: + + _fortran_zunmql(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zunmqr "BLAS_FUNC(zunmqr)"(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info) nogil +cdef void zunmqr(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil: + + _fortran_zunmqr(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zunmr2 "BLAS_FUNC(zunmr2)"(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info) nogil +cdef void zunmr2(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil: + + _fortran_zunmr2(side, trans, m, n, k, a, lda, tau, c, ldc, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zunmr3 "BLAS_FUNC(zunmr3)"(char *side, char *trans, int *m, int *n, int *k, int *l, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info) nogil +cdef void zunmr3(char *side, char *trans, int *m, int *n, int *k, int *l, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil: + + _fortran_zunmr3(side, trans, m, n, k, l, a, lda, tau, c, ldc, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zunmrq "BLAS_FUNC(zunmrq)"(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info) nogil +cdef void zunmrq(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil: + + _fortran_zunmrq(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zunmrz "BLAS_FUNC(zunmrz)"(char *side, char *trans, int *m, int *n, int *k, int *l, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info) nogil +cdef void zunmrz(char *side, char *trans, int *m, int *n, int *k, int *l, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil: + + _fortran_zunmrz(side, trans, m, n, k, l, a, lda, tau, c, ldc, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zunmtr "BLAS_FUNC(zunmtr)"(char *side, char *uplo, char *trans, int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info) nogil +cdef void zunmtr(char *side, char *uplo, char *trans, int *m, int *n, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil: + + _fortran_zunmtr(side, uplo, trans, m, n, a, lda, tau, c, ldc, work, lwork, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zupgtr "BLAS_FUNC(zupgtr)"(char *uplo, int *n, npy_complex128 *ap, npy_complex128 *tau, npy_complex128 *q, int *ldq, npy_complex128 *work, int *info) nogil +cdef void zupgtr(char *uplo, int *n, z *ap, z *tau, z *q, int *ldq, z *work, int *info) noexcept nogil: + + _fortran_zupgtr(uplo, n, ap, tau, q, ldq, work, info) + + +cdef extern from "_lapack_subroutines.h": + void _fortran_zupmtr "BLAS_FUNC(zupmtr)"(char *side, char *uplo, char *trans, int *m, int *n, npy_complex128 *ap, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info) nogil +cdef void zupmtr(char *side, char *uplo, char *trans, int *m, int *n, z *ap, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil: + + _fortran_zupmtr(side, uplo, trans, m, n, ap, tau, c, ldc, work, info) + + + +# Python accessible wrappers for testing: + +def _test_dlamch(cmach): + # This conversion is necessary to handle Python 3 strings. + cmach_bytes = bytes(cmach) + # Now that it is a bytes representation, a non-temporary variable + # must be passed as a part of the function call. + cdef char* cmach_char = cmach_bytes + return dlamch(cmach_char) + +def _test_slamch(cmach): + # This conversion is necessary to handle Python 3 strings. + cmach_bytes = bytes(cmach) + # Now that it is a bytes representation, a non-temporary variable + # must be passed as a part of the function call. + cdef char* cmach_char = cmach_bytes + return slamch(cmach_char) + +cpdef double complex _test_zladiv(double complex zx, double complex zy) noexcept nogil: + return zladiv(&zx, &zy) + +cpdef float complex _test_cladiv(float complex cx, float complex cy) noexcept nogil: + return cladiv(&cx, &cy) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/decomp.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/decomp.py new file mode 100644 index 0000000000000000000000000000000000000000..0d82ab157ce3be763f63e453c9a6fee064557c85 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/decomp.py @@ -0,0 +1,23 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.linalg` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'eig', 'eigvals', 'eigh', 'eigvalsh', + 'eig_banded', 'eigvals_banded', + 'eigh_tridiagonal', 'eigvalsh_tridiagonal', 'hessenberg', 'cdf2rdf', + 'LinAlgError', 'norm', 'get_lapack_funcs' +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="linalg", module="decomp", + private_modules=["_decomp"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/decomp_cholesky.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/decomp_cholesky.py new file mode 100644 index 0000000000000000000000000000000000000000..92545a5c6af5fe7a4de13f8746b96696d68b5bd2 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/decomp_cholesky.py @@ -0,0 +1,21 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.linalg` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'cholesky', 'cho_factor', 'cho_solve', 'cholesky_banded', + 'cho_solve_banded', 'LinAlgError', 'get_lapack_funcs' +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="linalg", module="decomp_cholesky", + private_modules=["_decomp_cholesky"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/decomp_lu.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/decomp_lu.py new file mode 100644 index 0000000000000000000000000000000000000000..9d5d9a98a04a689fb735f81299e129dc7f307590 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/decomp_lu.py @@ -0,0 +1,21 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.linalg` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'lu', 'lu_solve', 'lu_factor', + 'LinAlgWarning', 'get_lapack_funcs', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="linalg", module="decomp_lu", + private_modules=["_decomp_lu"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/decomp_qr.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/decomp_qr.py new file mode 100644 index 0000000000000000000000000000000000000000..4ef58729412ce2c83310b7817a143d14b8f28c19 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/decomp_qr.py @@ -0,0 +1,20 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.linalg` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'qr', 'qr_multiply', 'rq', 'get_lapack_funcs' +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="linalg", module="decomp_qr", + private_modules=["_decomp_qr"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/decomp_schur.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/decomp_schur.py new file mode 100644 index 0000000000000000000000000000000000000000..c3c6cc494db9b35dce8e4007c8c30d823b03881f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/decomp_schur.py @@ -0,0 +1,21 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.linalg` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'schur', 'rsf2csf', 'norm', 'LinAlgError', 'get_lapack_funcs', 'eigvals', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="linalg", module="decomp_schur", + private_modules=["_decomp_schur"], all=__all__, + attribute=name) + diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/decomp_svd.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/decomp_svd.py new file mode 100644 index 0000000000000000000000000000000000000000..64d0ce8562f06a3837df050f0ea6b8b15a2b359e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/decomp_svd.py @@ -0,0 +1,21 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.linalg` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'svd', 'svdvals', 'diagsvd', 'orth', 'subspace_angles', 'null_space', + 'LinAlgError', 'get_lapack_funcs' +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="linalg", module="decomp_svd", + private_modules=["_decomp_svd"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/interpolative.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/interpolative.py new file mode 100644 index 0000000000000000000000000000000000000000..38070863aa515266b0b130dbbdbd3d645da4aa0c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/interpolative.py @@ -0,0 +1,989 @@ +# ****************************************************************************** +# Copyright (C) 2013 Kenneth L. Ho +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. Redistributions in binary +# form must reproduce the above copyright notice, this list of conditions and +# the following disclaimer in the documentation and/or other materials +# provided with the distribution. +# +# None of the names of the copyright holders may be used to endorse or +# promote products derived from this software without specific prior written +# permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. +# ****************************************************************************** + +r""" +====================================================================== +Interpolative matrix decomposition (:mod:`scipy.linalg.interpolative`) +====================================================================== + +.. versionadded:: 0.13 + +.. versionchanged:: 1.15.0 + The underlying algorithms have been ported to Python from the original Fortran77 + code. See references below for more details. + +.. currentmodule:: scipy.linalg.interpolative + +An interpolative decomposition (ID) of a matrix :math:`A \in +\mathbb{C}^{m \times n}` of rank :math:`k \leq \min \{ m, n \}` is a +factorization + +.. math:: + A \Pi = + \begin{bmatrix} + A \Pi_{1} & A \Pi_{2} + \end{bmatrix} = + A \Pi_{1} + \begin{bmatrix} + I & T + \end{bmatrix}, + +where :math:`\Pi = [\Pi_{1}, \Pi_{2}]` is a permutation matrix with +:math:`\Pi_{1} \in \{ 0, 1 \}^{n \times k}`, i.e., :math:`A \Pi_{2} = +A \Pi_{1} T`. This can equivalently be written as :math:`A = BP`, +where :math:`B = A \Pi_{1}` and :math:`P = [I, T] \Pi^{\mathsf{T}}` +are the *skeleton* and *interpolation matrices*, respectively. + +If :math:`A` does not have exact rank :math:`k`, then there exists an +approximation in the form of an ID such that :math:`A = BP + E`, where +:math:`\| E \| \sim \sigma_{k + 1}` is on the order of the :math:`(k + +1)`-th largest singular value of :math:`A`. Note that :math:`\sigma_{k ++ 1}` is the best possible error for a rank-:math:`k` approximation +and, in fact, is achieved by the singular value decomposition (SVD) +:math:`A \approx U S V^{*}`, where :math:`U \in \mathbb{C}^{m \times +k}` and :math:`V \in \mathbb{C}^{n \times k}` have orthonormal columns +and :math:`S = \mathop{\mathrm{diag}} (\sigma_{i}) \in \mathbb{C}^{k +\times k}` is diagonal with nonnegative entries. The principal +advantages of using an ID over an SVD are that: + +- it is cheaper to construct; +- it preserves the structure of :math:`A`; and +- it is more efficient to compute with in light of the identity submatrix of :math:`P`. + +Routines +======== + +Main functionality: + +.. autosummary:: + :toctree: generated/ + + interp_decomp + reconstruct_matrix_from_id + reconstruct_interp_matrix + reconstruct_skel_matrix + id_to_svd + svd + estimate_spectral_norm + estimate_spectral_norm_diff + estimate_rank + +Following support functions are deprecated and will be removed in SciPy 1.17.0: + +.. autosummary:: + :toctree: generated/ + + seed + rand + + +References +========== + +This module uses the algorithms found in ID software package [1]_ by Martinsson, +Rokhlin, Shkolnisky, and Tygert, which is a Fortran library for computing IDs using +various algorithms, including the rank-revealing QR approach of [2]_ and the more +recent randomized methods described in [3]_, [4]_, and [5]_. + +We advise the user to consult also the documentation for the `ID package +`_. + +.. [1] P.G. Martinsson, V. Rokhlin, Y. Shkolnisky, M. Tygert. "ID: a + software package for low-rank approximation of matrices via interpolative + decompositions, version 0.2." http://tygert.com/id_doc.4.pdf. + +.. [2] H. Cheng, Z. Gimbutas, P.G. Martinsson, V. Rokhlin. "On the + compression of low rank matrices." *SIAM J. Sci. Comput.* 26 (4): 1389--1404, + 2005. :doi:`10.1137/030602678`. + +.. [3] E. Liberty, F. Woolfe, P.G. Martinsson, V. Rokhlin, M. + Tygert. "Randomized algorithms for the low-rank approximation of matrices." + *Proc. Natl. Acad. Sci. U.S.A.* 104 (51): 20167--20172, 2007. + :doi:`10.1073/pnas.0709640104`. + +.. [4] P.G. Martinsson, V. Rokhlin, M. Tygert. "A randomized + algorithm for the decomposition of matrices." *Appl. Comput. Harmon. Anal.* 30 + (1): 47--68, 2011. :doi:`10.1016/j.acha.2010.02.003`. + +.. [5] F. Woolfe, E. Liberty, V. Rokhlin, M. Tygert. "A fast + randomized algorithm for the approximation of matrices." *Appl. Comput. + Harmon. Anal.* 25 (3): 335--366, 2008. :doi:`10.1016/j.acha.2007.12.002`. + + +Tutorial +======== + +Initializing +------------ + +The first step is to import :mod:`scipy.linalg.interpolative` by issuing the +command: + +>>> import scipy.linalg.interpolative as sli + +Now let's build a matrix. For this, we consider a Hilbert matrix, which is well +know to have low rank: + +>>> from scipy.linalg import hilbert +>>> n = 1000 +>>> A = hilbert(n) + +We can also do this explicitly via: + +>>> import numpy as np +>>> n = 1000 +>>> A = np.empty((n, n), order='F') +>>> for j in range(n): +... for i in range(n): +... A[i,j] = 1. / (i + j + 1) + +Note the use of the flag ``order='F'`` in :func:`numpy.empty`. This +instantiates the matrix in Fortran-contiguous order and is important for +avoiding data copying when passing to the backend. + +We then define multiplication routines for the matrix by regarding it as a +:class:`scipy.sparse.linalg.LinearOperator`: + +>>> from scipy.sparse.linalg import aslinearoperator +>>> L = aslinearoperator(A) + +This automatically sets up methods describing the action of the matrix and its +adjoint on a vector. + +Computing an ID +--------------- + +We have several choices of algorithm to compute an ID. These fall largely +according to two dichotomies: + +1. how the matrix is represented, i.e., via its entries or via its action on a + vector; and +2. whether to approximate it to a fixed relative precision or to a fixed rank. + +We step through each choice in turn below. + +In all cases, the ID is represented by three parameters: + +1. a rank ``k``; +2. an index array ``idx``; and +3. interpolation coefficients ``proj``. + +The ID is specified by the relation +``np.dot(A[:,idx[:k]], proj) == A[:,idx[k:]]``. + +From matrix entries +................... + +We first consider a matrix given in terms of its entries. + +To compute an ID to a fixed precision, type: + +>>> eps = 1e-3 +>>> k, idx, proj = sli.interp_decomp(A, eps) + +where ``eps < 1`` is the desired precision. + +To compute an ID to a fixed rank, use: + +>>> idx, proj = sli.interp_decomp(A, k) + +where ``k >= 1`` is the desired rank. + +Both algorithms use random sampling and are usually faster than the +corresponding older, deterministic algorithms, which can be accessed via the +commands: + +>>> k, idx, proj = sli.interp_decomp(A, eps, rand=False) + +and: + +>>> idx, proj = sli.interp_decomp(A, k, rand=False) + +respectively. + +From matrix action +.................. + +Now consider a matrix given in terms of its action on a vector as a +:class:`scipy.sparse.linalg.LinearOperator`. + +To compute an ID to a fixed precision, type: + +>>> k, idx, proj = sli.interp_decomp(L, eps) + +To compute an ID to a fixed rank, use: + +>>> idx, proj = sli.interp_decomp(L, k) + +These algorithms are randomized. + +Reconstructing an ID +-------------------- + +The ID routines above do not output the skeleton and interpolation matrices +explicitly but instead return the relevant information in a more compact (and +sometimes more useful) form. To build these matrices, write: + +>>> B = sli.reconstruct_skel_matrix(A, k, idx) + +for the skeleton matrix and: + +>>> P = sli.reconstruct_interp_matrix(idx, proj) + +for the interpolation matrix. The ID approximation can then be computed as: + +>>> C = np.dot(B, P) + +This can also be constructed directly using: + +>>> C = sli.reconstruct_matrix_from_id(B, idx, proj) + +without having to first compute ``P``. + +Alternatively, this can be done explicitly as well using: + +>>> B = A[:,idx[:k]] +>>> P = np.hstack([np.eye(k), proj])[:,np.argsort(idx)] +>>> C = np.dot(B, P) + +Computing an SVD +---------------- + +An ID can be converted to an SVD via the command: + +>>> U, S, V = sli.id_to_svd(B, idx, proj) + +The SVD approximation is then: + +>>> approx = U @ np.diag(S) @ V.conj().T + +The SVD can also be computed "fresh" by combining both the ID and conversion +steps into one command. Following the various ID algorithms above, there are +correspondingly various SVD algorithms that one can employ. + +From matrix entries +................... + +We consider first SVD algorithms for a matrix given in terms of its entries. + +To compute an SVD to a fixed precision, type: + +>>> U, S, V = sli.svd(A, eps) + +To compute an SVD to a fixed rank, use: + +>>> U, S, V = sli.svd(A, k) + +Both algorithms use random sampling; for the deterministic versions, issue the +keyword ``rand=False`` as above. + +From matrix action +.................. + +Now consider a matrix given in terms of its action on a vector. + +To compute an SVD to a fixed precision, type: + +>>> U, S, V = sli.svd(L, eps) + +To compute an SVD to a fixed rank, use: + +>>> U, S, V = sli.svd(L, k) + +Utility routines +---------------- + +Several utility routines are also available. + +To estimate the spectral norm of a matrix, use: + +>>> snorm = sli.estimate_spectral_norm(A) + +This algorithm is based on the randomized power method and thus requires only +matrix-vector products. The number of iterations to take can be set using the +keyword ``its`` (default: ``its=20``). The matrix is interpreted as a +:class:`scipy.sparse.linalg.LinearOperator`, but it is also valid to supply it +as a :class:`numpy.ndarray`, in which case it is trivially converted using +:func:`scipy.sparse.linalg.aslinearoperator`. + +The same algorithm can also estimate the spectral norm of the difference of two +matrices ``A1`` and ``A2`` as follows: + +>>> A1, A2 = A**2, A +>>> diff = sli.estimate_spectral_norm_diff(A1, A2) + +This is often useful for checking the accuracy of a matrix approximation. + +Some routines in :mod:`scipy.linalg.interpolative` require estimating the rank +of a matrix as well. This can be done with either: + +>>> k = sli.estimate_rank(A, eps) + +or: + +>>> k = sli.estimate_rank(L, eps) + +depending on the representation. The parameter ``eps`` controls the definition +of the numerical rank. + +Finally, the random number generation required for all randomized routines can +be controlled via providing NumPy pseudo-random generators with a fixed seed. See +:class:`numpy.random.Generator` and :func:`numpy.random.default_rng` for more details. + +Remarks +------- + +The above functions all automatically detect the appropriate interface and work +with both real and complex data types, passing input arguments to the proper +backend routine. + +""" + +import scipy.linalg._decomp_interpolative as _backend +import numpy as np +import warnings + +__all__ = [ + 'estimate_rank', + 'estimate_spectral_norm', + 'estimate_spectral_norm_diff', + 'id_to_svd', + 'interp_decomp', + 'rand', + 'reconstruct_interp_matrix', + 'reconstruct_matrix_from_id', + 'reconstruct_skel_matrix', + 'seed', + 'svd', +] + +_DTYPE_ERROR = ValueError("invalid input dtype (input must be float64 or complex128)") +_TYPE_ERROR = TypeError("invalid input type (must be array or LinearOperator)") + + +def _C_contiguous_copy(A): + """ + Same as np.ascontiguousarray, but ensure a copy + """ + A = np.asarray(A) + if A.flags.c_contiguous: + A = A.copy() + else: + A = np.ascontiguousarray(A) + return A + + +def _is_real(A): + try: + if A.dtype == np.complex128: + return False + elif A.dtype == np.float64: + return True + else: + raise _DTYPE_ERROR + except AttributeError as e: + raise _TYPE_ERROR from e + + +def seed(seed=None): + """ + This function, historically, used to set the seed of the randomization algorithms + used in the `scipy.linalg.interpolative` functions written in Fortran77. + + The library has been ported to Python and now the functions use the native NumPy + generators and this function has no content and returns None. Thus this function + should not be used and will be removed in SciPy version 1.17.0. + """ + warnings.warn("`scipy.linalg.interpolative.seed` is deprecated and will be " + "removed in SciPy 1.17.0.", DeprecationWarning, stacklevel=3) + + +def rand(*shape): + """ + This function, historically, used to generate uniformly distributed random number + for the randomization algorithms used in the `scipy.linalg.interpolative` functions + written in Fortran77. + + The library has been ported to Python and now the functions use the native NumPy + generators. Thus this function should not be used and will be removed in the + SciPy version 1.17.0. + + If pseudo-random numbers are needed, NumPy pseudo-random generators should be used + instead. + + Parameters + ---------- + *shape + Shape of output array + + """ + warnings.warn("`scipy.linalg.interpolative.rand` is deprecated and will be " + "removed in SciPy 1.17.0.", DeprecationWarning, stacklevel=3) + rng = np.random.default_rng() + return rng.uniform(low=0., high=1.0, size=shape) + + +def interp_decomp(A, eps_or_k, rand=True, rng=None): + """ + Compute ID of a matrix. + + An ID of a matrix `A` is a factorization defined by a rank `k`, a column + index array `idx`, and interpolation coefficients `proj` such that:: + + numpy.dot(A[:,idx[:k]], proj) = A[:,idx[k:]] + + The original matrix can then be reconstructed as:: + + numpy.hstack([A[:,idx[:k]], + numpy.dot(A[:,idx[:k]], proj)] + )[:,numpy.argsort(idx)] + + or via the routine :func:`reconstruct_matrix_from_id`. This can + equivalently be written as:: + + numpy.dot(A[:,idx[:k]], + numpy.hstack([numpy.eye(k), proj]) + )[:,np.argsort(idx)] + + in terms of the skeleton and interpolation matrices:: + + B = A[:,idx[:k]] + + and:: + + P = numpy.hstack([numpy.eye(k), proj])[:,np.argsort(idx)] + + respectively. See also :func:`reconstruct_interp_matrix` and + :func:`reconstruct_skel_matrix`. + + The ID can be computed to any relative precision or rank (depending on the + value of `eps_or_k`). If a precision is specified (`eps_or_k < 1`), then + this function has the output signature:: + + k, idx, proj = interp_decomp(A, eps_or_k) + + Otherwise, if a rank is specified (`eps_or_k >= 1`), then the output + signature is:: + + idx, proj = interp_decomp(A, eps_or_k) + + .. This function automatically detects the form of the input parameters + and passes them to the appropriate backend. For details, see + :func:`_backend.iddp_id`, :func:`_backend.iddp_aid`, + :func:`_backend.iddp_rid`, :func:`_backend.iddr_id`, + :func:`_backend.iddr_aid`, :func:`_backend.iddr_rid`, + :func:`_backend.idzp_id`, :func:`_backend.idzp_aid`, + :func:`_backend.idzp_rid`, :func:`_backend.idzr_id`, + :func:`_backend.idzr_aid`, and :func:`_backend.idzr_rid`. + + Parameters + ---------- + A : :class:`numpy.ndarray` or :class:`scipy.sparse.linalg.LinearOperator` with `rmatvec` + Matrix to be factored + eps_or_k : float or int + Relative error (if ``eps_or_k < 1``) or rank (if ``eps_or_k >= 1``) of + approximation. + rand : bool, optional + Whether to use random sampling if `A` is of type :class:`numpy.ndarray` + (randomized algorithms are always used if `A` is of type + :class:`scipy.sparse.linalg.LinearOperator`). + rng : `numpy.random.Generator`, optional + Pseudorandom number generator state. When `rng` is None, a new + `numpy.random.Generator` is created using entropy from the + operating system. Types other than `numpy.random.Generator` are + passed to `numpy.random.default_rng` to instantiate a ``Generator``. + If `rand` is ``False``, the argument is ignored. + + Returns + ------- + k : int + Rank required to achieve specified relative precision if + ``eps_or_k < 1``. + idx : :class:`numpy.ndarray` + Column index array. + proj : :class:`numpy.ndarray` + Interpolation coefficients. + """ # numpy/numpydoc#87 # noqa: E501 + from scipy.sparse.linalg import LinearOperator + rng = np.random.default_rng(rng) + real = _is_real(A) + + if isinstance(A, np.ndarray): + A = _C_contiguous_copy(A) + if eps_or_k < 1: + eps = eps_or_k + if rand: + if real: + k, idx, proj = _backend.iddp_aid(A, eps, rng=rng) + else: + k, idx, proj = _backend.idzp_aid(A, eps, rng=rng) + else: + if real: + k, idx, proj = _backend.iddp_id(A, eps) + else: + k, idx, proj = _backend.idzp_id(A, eps) + return k, idx, proj + else: + k = int(eps_or_k) + if rand: + if real: + idx, proj = _backend.iddr_aid(A, k, rng=rng) + else: + idx, proj = _backend.idzr_aid(A, k, rng=rng) + else: + if real: + idx, proj = _backend.iddr_id(A, k) + else: + idx, proj = _backend.idzr_id(A, k) + return idx, proj + elif isinstance(A, LinearOperator): + + if eps_or_k < 1: + eps = eps_or_k + if real: + k, idx, proj = _backend.iddp_rid(A, eps, rng=rng) + else: + k, idx, proj = _backend.idzp_rid(A, eps, rng=rng) + return k, idx, proj + else: + k = int(eps_or_k) + if real: + idx, proj = _backend.iddr_rid(A, k, rng=rng) + else: + idx, proj = _backend.idzr_rid(A, k, rng=rng) + return idx, proj + else: + raise _TYPE_ERROR + + +def reconstruct_matrix_from_id(B, idx, proj): + """ + Reconstruct matrix from its ID. + + A matrix `A` with skeleton matrix `B` and ID indices and coefficients `idx` + and `proj`, respectively, can be reconstructed as:: + + numpy.hstack([B, numpy.dot(B, proj)])[:,numpy.argsort(idx)] + + See also :func:`reconstruct_interp_matrix` and + :func:`reconstruct_skel_matrix`. + + .. This function automatically detects the matrix data type and calls the + appropriate backend. For details, see :func:`_backend.idd_reconid` and + :func:`_backend.idz_reconid`. + + Parameters + ---------- + B : :class:`numpy.ndarray` + Skeleton matrix. + idx : :class:`numpy.ndarray` + Column index array. + proj : :class:`numpy.ndarray` + Interpolation coefficients. + + Returns + ------- + :class:`numpy.ndarray` + Reconstructed matrix. + """ + if _is_real(B): + return _backend.idd_reconid(B, idx, proj) + else: + return _backend.idz_reconid(B, idx, proj) + + +def reconstruct_interp_matrix(idx, proj): + """ + Reconstruct interpolation matrix from ID. + + The interpolation matrix can be reconstructed from the ID indices and + coefficients `idx` and `proj`, respectively, as:: + + P = numpy.hstack([numpy.eye(proj.shape[0]), proj])[:,numpy.argsort(idx)] + + The original matrix can then be reconstructed from its skeleton matrix ``B`` + via ``A = B @ P`` + + See also :func:`reconstruct_matrix_from_id` and + :func:`reconstruct_skel_matrix`. + + .. This function automatically detects the matrix data type and calls the + appropriate backend. For details, see :func:`_backend.idd_reconint` and + :func:`_backend.idz_reconint`. + + Parameters + ---------- + idx : :class:`numpy.ndarray` + 1D column index array. + proj : :class:`numpy.ndarray` + Interpolation coefficients. + + Returns + ------- + :class:`numpy.ndarray` + Interpolation matrix. + """ + n, krank = len(idx), proj.shape[0] + if _is_real(proj): + p = np.zeros([krank, n], dtype=np.float64) + else: + p = np.zeros([krank, n], dtype=np.complex128) + + for ci in range(krank): + p[ci, idx[ci]] = 1.0 + p[:, idx[krank:]] = proj[:, :] + + return p + + +def reconstruct_skel_matrix(A, k, idx): + """ + Reconstruct skeleton matrix from ID. + + The skeleton matrix can be reconstructed from the original matrix `A` and its + ID rank and indices `k` and `idx`, respectively, as:: + + B = A[:,idx[:k]] + + The original matrix can then be reconstructed via:: + + numpy.hstack([B, numpy.dot(B, proj)])[:,numpy.argsort(idx)] + + See also :func:`reconstruct_matrix_from_id` and + :func:`reconstruct_interp_matrix`. + + .. This function automatically detects the matrix data type and calls the + appropriate backend. For details, see :func:`_backend.idd_copycols` and + :func:`_backend.idz_copycols`. + + Parameters + ---------- + A : :class:`numpy.ndarray` + Original matrix. + k : int + Rank of ID. + idx : :class:`numpy.ndarray` + Column index array. + + Returns + ------- + :class:`numpy.ndarray` + Skeleton matrix. + """ + return A[:, idx[:k]] + + +def id_to_svd(B, idx, proj): + """ + Convert ID to SVD. + + The SVD reconstruction of a matrix with skeleton matrix `B` and ID indices and + coefficients `idx` and `proj`, respectively, is:: + + U, S, V = id_to_svd(B, idx, proj) + A = numpy.dot(U, numpy.dot(numpy.diag(S), V.conj().T)) + + See also :func:`svd`. + + .. This function automatically detects the matrix data type and calls the + appropriate backend. For details, see :func:`_backend.idd_id2svd` and + :func:`_backend.idz_id2svd`. + + Parameters + ---------- + B : :class:`numpy.ndarray` + Skeleton matrix. + idx : :class:`numpy.ndarray` + 1D column index array. + proj : :class:`numpy.ndarray` + Interpolation coefficients. + + Returns + ------- + U : :class:`numpy.ndarray` + Left singular vectors. + S : :class:`numpy.ndarray` + Singular values. + V : :class:`numpy.ndarray` + Right singular vectors. + """ + B = _C_contiguous_copy(B) + if _is_real(B): + U, S, V = _backend.idd_id2svd(B, idx, proj) + else: + U, S, V = _backend.idz_id2svd(B, idx, proj) + + return U, S, V + + +def estimate_spectral_norm(A, its=20, rng=None): + """ + Estimate spectral norm of a matrix by the randomized power method. + + .. This function automatically detects the matrix data type and calls the + appropriate backend. For details, see :func:`_backend.idd_snorm` and + :func:`_backend.idz_snorm`. + + Parameters + ---------- + A : :class:`scipy.sparse.linalg.LinearOperator` + Matrix given as a :class:`scipy.sparse.linalg.LinearOperator` with the + `matvec` and `rmatvec` methods (to apply the matrix and its adjoint). + its : int, optional + Number of power method iterations. + rng : `numpy.random.Generator`, optional + Pseudorandom number generator state. When `rng` is None, a new + `numpy.random.Generator` is created using entropy from the + operating system. Types other than `numpy.random.Generator` are + passed to `numpy.random.default_rng` to instantiate a ``Generator``. + If `rand` is ``False``, the argument is ignored. + + Returns + ------- + float + Spectral norm estimate. + """ + from scipy.sparse.linalg import aslinearoperator + rng = np.random.default_rng(rng) + A = aslinearoperator(A) + + if _is_real(A): + return _backend.idd_snorm(A, its=its, rng=rng) + else: + return _backend.idz_snorm(A, its=its, rng=rng) + + +def estimate_spectral_norm_diff(A, B, its=20, rng=None): + """ + Estimate spectral norm of the difference of two matrices by the randomized + power method. + + .. This function automatically detects the matrix data type and calls the + appropriate backend. For details, see :func:`_backend.idd_diffsnorm` and + :func:`_backend.idz_diffsnorm`. + + Parameters + ---------- + A : :class:`scipy.sparse.linalg.LinearOperator` + First matrix given as a :class:`scipy.sparse.linalg.LinearOperator` with the + `matvec` and `rmatvec` methods (to apply the matrix and its adjoint). + B : :class:`scipy.sparse.linalg.LinearOperator` + Second matrix given as a :class:`scipy.sparse.linalg.LinearOperator` with + the `matvec` and `rmatvec` methods (to apply the matrix and its adjoint). + its : int, optional + Number of power method iterations. + rng : `numpy.random.Generator`, optional + Pseudorandom number generator state. When `rng` is None, a new + `numpy.random.Generator` is created using entropy from the + operating system. Types other than `numpy.random.Generator` are + passed to `numpy.random.default_rng` to instantiate a ``Generator``. + If `rand` is ``False``, the argument is ignored. + + Returns + ------- + float + Spectral norm estimate of matrix difference. + """ + from scipy.sparse.linalg import aslinearoperator + rng = np.random.default_rng(rng) + A = aslinearoperator(A) + B = aslinearoperator(B) + + if _is_real(A): + return _backend.idd_diffsnorm(A, B, its=its, rng=rng) + else: + return _backend.idz_diffsnorm(A, B, its=its, rng=rng) + + +def svd(A, eps_or_k, rand=True, rng=None): + """ + Compute SVD of a matrix via an ID. + + An SVD of a matrix `A` is a factorization:: + + A = U @ np.diag(S) @ V.conj().T + + where `U` and `V` have orthonormal columns and `S` is nonnegative. + + The SVD can be computed to any relative precision or rank (depending on the + value of `eps_or_k`). + + See also :func:`interp_decomp` and :func:`id_to_svd`. + + .. This function automatically detects the form of the input parameters and + passes them to the appropriate backend. For details, see + :func:`_backend.iddp_svd`, :func:`_backend.iddp_asvd`, + :func:`_backend.iddp_rsvd`, :func:`_backend.iddr_svd`, + :func:`_backend.iddr_asvd`, :func:`_backend.iddr_rsvd`, + :func:`_backend.idzp_svd`, :func:`_backend.idzp_asvd`, + :func:`_backend.idzp_rsvd`, :func:`_backend.idzr_svd`, + :func:`_backend.idzr_asvd`, and :func:`_backend.idzr_rsvd`. + + Parameters + ---------- + A : :class:`numpy.ndarray` or :class:`scipy.sparse.linalg.LinearOperator` + Matrix to be factored, given as either a :class:`numpy.ndarray` or a + :class:`scipy.sparse.linalg.LinearOperator` with the `matvec` and + `rmatvec` methods (to apply the matrix and its adjoint). + eps_or_k : float or int + Relative error (if ``eps_or_k < 1``) or rank (if ``eps_or_k >= 1``) of + approximation. + rand : bool, optional + Whether to use random sampling if `A` is of type :class:`numpy.ndarray` + (randomized algorithms are always used if `A` is of type + :class:`scipy.sparse.linalg.LinearOperator`). + rng : `numpy.random.Generator`, optional + Pseudorandom number generator state. When `rng` is None, a new + `numpy.random.Generator` is created using entropy from the + operating system. Types other than `numpy.random.Generator` are + passed to `numpy.random.default_rng` to instantiate a ``Generator``. + If `rand` is ``False``, the argument is ignored. + + Returns + ------- + U : :class:`numpy.ndarray` + 2D array of left singular vectors. + S : :class:`numpy.ndarray` + 1D array of singular values. + V : :class:`numpy.ndarray` + 2D array right singular vectors. + """ + from scipy.sparse.linalg import LinearOperator + rng = np.random.default_rng(rng) + + real = _is_real(A) + + if isinstance(A, np.ndarray): + A = _C_contiguous_copy(A) + if eps_or_k < 1: + eps = eps_or_k + if rand: + if real: + U, S, V = _backend.iddp_asvd(A, eps, rng=rng) + else: + U, S, V = _backend.idzp_asvd(A, eps, rng=rng) + else: + if real: + U, S, V = _backend.iddp_svd(A, eps) + V = V.T.conj() + else: + U, S, V = _backend.idzp_svd(A, eps) + V = V.T.conj() + else: + k = int(eps_or_k) + if k > min(A.shape): + raise ValueError(f"Approximation rank {k} exceeds min(A.shape) = " + f" {min(A.shape)} ") + if rand: + if real: + U, S, V = _backend.iddr_asvd(A, k, rng=rng) + else: + U, S, V = _backend.idzr_asvd(A, k, rng=rng) + else: + if real: + U, S, V = _backend.iddr_svd(A, k) + V = V.T.conj() + else: + U, S, V = _backend.idzr_svd(A, k) + V = V.T.conj() + elif isinstance(A, LinearOperator): + if eps_or_k < 1: + eps = eps_or_k + if real: + U, S, V = _backend.iddp_rsvd(A, eps, rng=rng) + else: + U, S, V = _backend.idzp_rsvd(A, eps, rng=rng) + else: + k = int(eps_or_k) + if real: + U, S, V = _backend.iddr_rsvd(A, k, rng=rng) + else: + U, S, V = _backend.idzr_rsvd(A, k, rng=rng) + else: + raise _TYPE_ERROR + return U, S, V + + +def estimate_rank(A, eps, rng=None): + """ + Estimate matrix rank to a specified relative precision using randomized + methods. + + The matrix `A` can be given as either a :class:`numpy.ndarray` or a + :class:`scipy.sparse.linalg.LinearOperator`, with different algorithms used + for each case. If `A` is of type :class:`numpy.ndarray`, then the output + rank is typically about 8 higher than the actual numerical rank. + + .. This function automatically detects the form of the input parameters and + passes them to the appropriate backend. For details, + see :func:`_backend.idd_estrank`, :func:`_backend.idd_findrank`, + :func:`_backend.idz_estrank`, and :func:`_backend.idz_findrank`. + + Parameters + ---------- + A : :class:`numpy.ndarray` or :class:`scipy.sparse.linalg.LinearOperator` + Matrix whose rank is to be estimated, given as either a + :class:`numpy.ndarray` or a :class:`scipy.sparse.linalg.LinearOperator` + with the `rmatvec` method (to apply the matrix adjoint). + eps : float + Relative error for numerical rank definition. + rng : `numpy.random.Generator`, optional + Pseudorandom number generator state. When `rng` is None, a new + `numpy.random.Generator` is created using entropy from the + operating system. Types other than `numpy.random.Generator` are + passed to `numpy.random.default_rng` to instantiate a ``Generator``. + If `rand` is ``False``, the argument is ignored. + + Returns + ------- + int + Estimated matrix rank. + """ + from scipy.sparse.linalg import LinearOperator + + rng = np.random.default_rng(rng) + real = _is_real(A) + + if isinstance(A, np.ndarray): + A = _C_contiguous_copy(A) + if real: + rank, _ = _backend.idd_estrank(A, eps, rng=rng) + else: + rank, _ = _backend.idz_estrank(A, eps, rng=rng) + if rank == 0: + # special return value for nearly full rank + rank = min(A.shape) + return rank + elif isinstance(A, LinearOperator): + if real: + return _backend.idd_findrank(A, eps, rng=rng)[0] + else: + return _backend.idz_findrank(A, eps, rng=rng)[0] + else: + raise _TYPE_ERROR diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/lapack.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/lapack.py new file mode 100644 index 0000000000000000000000000000000000000000..2d15cf4d72d19f4b7949cd80bc77aa31553841c1 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/lapack.py @@ -0,0 +1,1061 @@ +""" +Low-level LAPACK functions (:mod:`scipy.linalg.lapack`) +======================================================= + +This module contains low-level functions from the LAPACK library. + +.. versionadded:: 0.12.0 + +.. note:: + + The common ``overwrite_<>`` option in many routines, allows the + input arrays to be overwritten to avoid extra memory allocation. + However this requires the array to satisfy two conditions + which are memory order and the data type to match exactly the + order and the type expected by the routine. + + As an example, if you pass a double precision float array to any + ``S....`` routine which expects single precision arguments, f2py + will create an intermediate array to match the argument types and + overwriting will be performed on that intermediate array. + + Similarly, if a C-contiguous array is passed, f2py will pass a + FORTRAN-contiguous array internally. Please make sure that these + details are satisfied. More information can be found in the f2py + documentation. + +.. warning:: + + These functions do little to no error checking. + It is possible to cause crashes by mis-using them, + so prefer using the higher-level routines in `scipy.linalg`. + +Finding functions +----------------- + +.. autosummary:: + :toctree: generated/ + + get_lapack_funcs + +All functions +------------- + +.. autosummary:: + :toctree: generated/ + + sgbsv + dgbsv + cgbsv + zgbsv + + sgbtrf + dgbtrf + cgbtrf + zgbtrf + + sgbtrs + dgbtrs + cgbtrs + zgbtrs + + sgebal + dgebal + cgebal + zgebal + + sgecon + dgecon + cgecon + zgecon + + sgeequ + dgeequ + cgeequ + zgeequ + + sgeequb + dgeequb + cgeequb + zgeequb + + sgees + dgees + cgees + zgees + + sgeev + dgeev + cgeev + zgeev + + sgeev_lwork + dgeev_lwork + cgeev_lwork + zgeev_lwork + + sgehrd + dgehrd + cgehrd + zgehrd + + sgehrd_lwork + dgehrd_lwork + cgehrd_lwork + zgehrd_lwork + + sgejsv + dgejsv + + sgels + dgels + cgels + zgels + + sgels_lwork + dgels_lwork + cgels_lwork + zgels_lwork + + sgelsd + dgelsd + cgelsd + zgelsd + + sgelsd_lwork + dgelsd_lwork + cgelsd_lwork + zgelsd_lwork + + sgelss + dgelss + cgelss + zgelss + + sgelss_lwork + dgelss_lwork + cgelss_lwork + zgelss_lwork + + sgelsy + dgelsy + cgelsy + zgelsy + + sgelsy_lwork + dgelsy_lwork + cgelsy_lwork + zgelsy_lwork + + sgeqp3 + dgeqp3 + cgeqp3 + zgeqp3 + + sgeqrf + dgeqrf + cgeqrf + zgeqrf + + sgeqrf_lwork + dgeqrf_lwork + cgeqrf_lwork + zgeqrf_lwork + + sgeqrfp + dgeqrfp + cgeqrfp + zgeqrfp + + sgeqrfp_lwork + dgeqrfp_lwork + cgeqrfp_lwork + zgeqrfp_lwork + + sgerqf + dgerqf + cgerqf + zgerqf + + sgesdd + dgesdd + cgesdd + zgesdd + + sgesdd_lwork + dgesdd_lwork + cgesdd_lwork + zgesdd_lwork + + sgesv + dgesv + cgesv + zgesv + + sgesvd + dgesvd + cgesvd + zgesvd + + sgesvd_lwork + dgesvd_lwork + cgesvd_lwork + zgesvd_lwork + + sgesvx + dgesvx + cgesvx + zgesvx + + sgetrf + dgetrf + cgetrf + zgetrf + + sgetc2 + dgetc2 + cgetc2 + zgetc2 + + sgetri + dgetri + cgetri + zgetri + + sgetri_lwork + dgetri_lwork + cgetri_lwork + zgetri_lwork + + sgetrs + dgetrs + cgetrs + zgetrs + + sgesc2 + dgesc2 + cgesc2 + zgesc2 + + sgges + dgges + cgges + zgges + + sggev + dggev + cggev + zggev + + sgglse + dgglse + cgglse + zgglse + + sgglse_lwork + dgglse_lwork + cgglse_lwork + zgglse_lwork + + sgtsv + dgtsv + cgtsv + zgtsv + + sgtsvx + dgtsvx + cgtsvx + zgtsvx + + chbevd + zhbevd + + chbevx + zhbevx + + checon + zhecon + + cheequb + zheequb + + cheev + zheev + + cheev_lwork + zheev_lwork + + cheevd + zheevd + + cheevd_lwork + zheevd_lwork + + cheevr + zheevr + + cheevr_lwork + zheevr_lwork + + cheevx + zheevx + + cheevx_lwork + zheevx_lwork + + chegst + zhegst + + chegv + zhegv + + chegv_lwork + zhegv_lwork + + chegvd + zhegvd + + chegvx + zhegvx + + chegvx_lwork + zhegvx_lwork + + chesv + zhesv + + chesv_lwork + zhesv_lwork + + chesvx + zhesvx + + chesvx_lwork + zhesvx_lwork + + chetrd + zhetrd + + chetrd_lwork + zhetrd_lwork + + chetrf + zhetrf + + chetrf_lwork + zhetrf_lwork + + chetrs + zhetrs + + chfrk + zhfrk + + slamch + dlamch + + slange + dlange + clange + zlange + + slantr + dlantr + clantr + zlantr + + slarf + dlarf + clarf + zlarf + + slarfg + dlarfg + clarfg + zlarfg + + slartg + dlartg + clartg + zlartg + + slasd4 + dlasd4 + + slaswp + dlaswp + claswp + zlaswp + + slauum + dlauum + clauum + zlauum + + sorcsd + dorcsd + sorcsd_lwork + dorcsd_lwork + + sorghr + dorghr + sorghr_lwork + dorghr_lwork + + sorgqr + dorgqr + + sorgrq + dorgrq + + sormqr + dormqr + + sormrz + dormrz + + sormrz_lwork + dormrz_lwork + + spbsv + dpbsv + cpbsv + zpbsv + + spbtrf + dpbtrf + cpbtrf + zpbtrf + + spbtrs + dpbtrs + cpbtrs + zpbtrs + + spftrf + dpftrf + cpftrf + zpftrf + + spftri + dpftri + cpftri + zpftri + + spftrs + dpftrs + cpftrs + zpftrs + + spocon + dpocon + cpocon + zpocon + + spstrf + dpstrf + cpstrf + zpstrf + + spstf2 + dpstf2 + cpstf2 + zpstf2 + + sposv + dposv + cposv + zposv + + sposvx + dposvx + cposvx + zposvx + + spotrf + dpotrf + cpotrf + zpotrf + + spotri + dpotri + cpotri + zpotri + + spotrs + dpotrs + cpotrs + zpotrs + + sppcon + dppcon + cppcon + zppcon + + sppsv + dppsv + cppsv + zppsv + + spptrf + dpptrf + cpptrf + zpptrf + + spptri + dpptri + cpptri + zpptri + + spptrs + dpptrs + cpptrs + zpptrs + + sptsv + dptsv + cptsv + zptsv + + sptsvx + dptsvx + cptsvx + zptsvx + + spttrf + dpttrf + cpttrf + zpttrf + + spttrs + dpttrs + cpttrs + zpttrs + + spteqr + dpteqr + cpteqr + zpteqr + + crot + zrot + + ssbev + dsbev + + ssbevd + dsbevd + + ssbevx + dsbevx + + ssfrk + dsfrk + + sstebz + dstebz + + sstein + dstein + + sstemr + dstemr + + sstemr_lwork + dstemr_lwork + + ssterf + dsterf + + sstev + dstev + + ssycon + dsycon + csycon + zsycon + + ssyconv + dsyconv + csyconv + zsyconv + + ssyequb + dsyequb + csyequb + zsyequb + + ssyev + dsyev + + ssyev_lwork + dsyev_lwork + + ssyevd + dsyevd + + ssyevd_lwork + dsyevd_lwork + + ssyevr + dsyevr + + ssyevr_lwork + dsyevr_lwork + + ssyevx + dsyevx + + ssyevx_lwork + dsyevx_lwork + + ssygst + dsygst + + ssygv + dsygv + + ssygv_lwork + dsygv_lwork + + ssygvd + dsygvd + + ssygvx + dsygvx + + ssygvx_lwork + dsygvx_lwork + + ssysv + dsysv + csysv + zsysv + + ssysv_lwork + dsysv_lwork + csysv_lwork + zsysv_lwork + + ssysvx + dsysvx + csysvx + zsysvx + + ssysvx_lwork + dsysvx_lwork + csysvx_lwork + zsysvx_lwork + + ssytf2 + dsytf2 + csytf2 + zsytf2 + + ssytrd + dsytrd + + ssytrd_lwork + dsytrd_lwork + + ssytrf + dsytrf + csytrf + zsytrf + + ssytrf_lwork + dsytrf_lwork + csytrf_lwork + zsytrf_lwork + + ssytrs + dsytrs + csytrs + zsytrs + + stbtrs + dtbtrs + ctbtrs + ztbtrs + + stfsm + dtfsm + ctfsm + ztfsm + + stfttp + dtfttp + ctfttp + ztfttp + + stfttr + dtfttr + ctfttr + ztfttr + + stgexc + dtgexc + ctgexc + ztgexc + + stgsen + dtgsen + ctgsen + ztgsen + + stgsen_lwork + dtgsen_lwork + ctgsen_lwork + ztgsen_lwork + + stgsyl + dtgsyl + + stpttf + dtpttf + ctpttf + ztpttf + + stpttr + dtpttr + ctpttr + ztpttr + + strcon + dtrcon + ctrcon + ztrcon + + strexc + dtrexc + ctrexc + ztrexc + + strsen + dtrsen + ctrsen + ztrsen + + strsen_lwork + dtrsen_lwork + ctrsen_lwork + ztrsen_lwork + + strsyl + dtrsyl + ctrsyl + ztrsyl + + strtri + dtrtri + ctrtri + ztrtri + + strtrs + dtrtrs + ctrtrs + ztrtrs + + strttf + dtrttf + ctrttf + ztrttf + + strttp + dtrttp + ctrttp + ztrttp + + stzrzf + dtzrzf + ctzrzf + ztzrzf + + stzrzf_lwork + dtzrzf_lwork + ctzrzf_lwork + ztzrzf_lwork + + cunghr + zunghr + + cunghr_lwork + zunghr_lwork + + cungqr + zungqr + + cungrq + zungrq + + cunmqr + zunmqr + + sgeqrt + dgeqrt + cgeqrt + zgeqrt + + sgemqrt + dgemqrt + cgemqrt + zgemqrt + + sgttrf + dgttrf + cgttrf + zgttrf + + sgttrs + dgttrs + cgttrs + zgttrs + + sgtcon + dgtcon + cgtcon + zgtcon + + stpqrt + dtpqrt + ctpqrt + ztpqrt + + stpmqrt + dtpmqrt + ctpmqrt + ztpmqrt + + cuncsd + zuncsd + + cuncsd_lwork + zuncsd_lwork + + cunmrz + zunmrz + + cunmrz_lwork + zunmrz_lwork + + ilaver + +""" +# +# Author: Pearu Peterson, March 2002 +# + +import numpy as np +from .blas import _get_funcs, _memoize_get_funcs +from scipy.linalg import _flapack +from re import compile as regex_compile +try: + from scipy.linalg import _clapack +except ImportError: + _clapack = None + +try: + from scipy.linalg import _flapack_64 + HAS_ILP64 = True +except ImportError: + HAS_ILP64 = False + _flapack_64 = None + + +# Expose all functions (only flapack --- clapack is an implementation detail) +empty_module = None +from scipy.linalg._flapack import * # noqa: E402, F403 +del empty_module + +__all__ = ['get_lapack_funcs'] + +# some convenience alias for complex functions +_lapack_alias = { + 'corghr': 'cunghr', 'zorghr': 'zunghr', + 'corghr_lwork': 'cunghr_lwork', 'zorghr_lwork': 'zunghr_lwork', + 'corgqr': 'cungqr', 'zorgqr': 'zungqr', + 'cormqr': 'cunmqr', 'zormqr': 'zunmqr', + 'corgrq': 'cungrq', 'zorgrq': 'zungrq', +} + + +# Place guards against docstring rendering issues with special characters +p1 = regex_compile(r'with bounds (?P.*?)( and (?P.*?) storage){0,1}\n') +p2 = regex_compile(r'Default: (?P.*?)\n') + + +def backtickrepl(m): + if m.group('s'): + return (f"with bounds ``{m.group('b')}`` with ``{m.group('s')}`` storage\n") + else: + return f"with bounds ``{m.group('b')}``\n" + + +for routine in [ssyevr, dsyevr, cheevr, zheevr, + ssyevx, dsyevx, cheevx, zheevx, + ssygvd, dsygvd, chegvd, zhegvd]: + if routine.__doc__: + routine.__doc__ = p1.sub(backtickrepl, routine.__doc__) + routine.__doc__ = p2.sub('Default ``\\1``\n', routine.__doc__) + else: + continue + +del regex_compile, p1, p2, backtickrepl + + +@_memoize_get_funcs +def get_lapack_funcs(names, arrays=(), dtype=None, ilp64=False): + """Return available LAPACK function objects from names. + + Arrays are used to determine the optimal prefix of LAPACK routines. + + Parameters + ---------- + names : str or sequence of str + Name(s) of LAPACK functions without type prefix. + + arrays : sequence of ndarrays, optional + Arrays can be given to determine optimal prefix of LAPACK + routines. If not given, double-precision routines will be + used, otherwise the most generic type in arrays will be used. + + dtype : str or dtype, optional + Data-type specifier. Not used if `arrays` is non-empty. + + ilp64 : {True, False, 'preferred'}, optional + Whether to return ILP64 routine variant. + Choosing 'preferred' returns ILP64 routine if available, and + otherwise the 32-bit routine. Default: False + + Returns + ------- + funcs : list + List containing the found function(s). + + Notes + ----- + This routine automatically chooses between Fortran/C + interfaces. Fortran code is used whenever possible for arrays with + column major order. In all other cases, C code is preferred. + + In LAPACK, the naming convention is that all functions start with a + type prefix, which depends on the type of the principal + matrix. These can be one of {'s', 'd', 'c', 'z'} for the NumPy + types {float32, float64, complex64, complex128} respectively, and + are stored in attribute ``typecode`` of the returned functions. + + Examples + -------- + Suppose we would like to use '?lange' routine which computes the selected + norm of an array. We pass our array in order to get the correct 'lange' + flavor. + + >>> import numpy as np + >>> import scipy.linalg as LA + >>> rng = np.random.default_rng() + + >>> a = rng.random((3,2)) + >>> x_lange = LA.get_lapack_funcs('lange', (a,)) + >>> x_lange.typecode + 'd' + >>> x_lange = LA.get_lapack_funcs('lange',(a*1j,)) + >>> x_lange.typecode + 'z' + + Several LAPACK routines work best when its internal WORK array has + the optimal size (big enough for fast computation and small enough to + avoid waste of memory). This size is determined also by a dedicated query + to the function which is often wrapped as a standalone function and + commonly denoted as ``###_lwork``. Below is an example for ``?sysv`` + + >>> a = rng.random((1000, 1000)) + >>> b = rng.random((1000, 1)) * 1j + >>> # We pick up zsysv and zsysv_lwork due to b array + ... xsysv, xlwork = LA.get_lapack_funcs(('sysv', 'sysv_lwork'), (a, b)) + >>> opt_lwork, _ = xlwork(a.shape[0]) # returns a complex for 'z' prefix + >>> udut, ipiv, x, info = xsysv(a, b, lwork=int(opt_lwork.real)) + + """ + if isinstance(ilp64, str): + if ilp64 == 'preferred': + ilp64 = HAS_ILP64 + else: + raise ValueError("Invalid value for 'ilp64'") + + if not ilp64: + return _get_funcs(names, arrays, dtype, + "LAPACK", _flapack, _clapack, + "flapack", "clapack", _lapack_alias, + ilp64=False) + else: + if not HAS_ILP64: + raise RuntimeError("LAPACK ILP64 routine requested, but Scipy " + "compiled only with 32-bit BLAS") + return _get_funcs(names, arrays, dtype, + "LAPACK", _flapack_64, None, + "flapack_64", None, _lapack_alias, + ilp64=True) + + +_int32_max = np.iinfo(np.int32).max +_int64_max = np.iinfo(np.int64).max + + +def _compute_lwork(routine, *args, **kwargs): + """ + Round floating-point lwork returned by lapack to integer. + + Several LAPACK routines compute optimal values for LWORK, which + they return in a floating-point variable. However, for large + values of LWORK, single-precision floating point is not sufficient + to hold the exact value --- some LAPACK versions (<= 3.5.0 at + least) truncate the returned integer to single precision and in + some cases this can be smaller than the required value. + + Examples + -------- + >>> from scipy.linalg import lapack + >>> n = 5000 + >>> s_r, s_lw = lapack.get_lapack_funcs(('sysvx', 'sysvx_lwork')) + >>> lwork = lapack._compute_lwork(s_lw, n) + >>> lwork + 32000 + + """ + dtype = getattr(routine, 'dtype', None) + int_dtype = getattr(routine, 'int_dtype', None) + ret = routine(*args, **kwargs) + if ret[-1] != 0: + raise ValueError("Internal work array size computation failed: " + "%d" % (ret[-1],)) + + if len(ret) == 2: + return _check_work_float(ret[0].real, dtype, int_dtype) + else: + return tuple(_check_work_float(x.real, dtype, int_dtype) + for x in ret[:-1]) + + +def _check_work_float(value, dtype, int_dtype): + """ + Convert LAPACK-returned work array size float to integer, + carefully for single-precision types. + """ + + if dtype == np.float32 or dtype == np.complex64: + # Single-precision routine -- take next fp value to work + # around possible truncation in LAPACK code + value = np.nextafter(value, np.inf, dtype=np.float32) + + value = int(value) + if int_dtype.itemsize == 4: + if value < 0 or value > _int32_max: + raise ValueError("Too large work array required -- computation " + "cannot be performed with standard 32-bit" + " LAPACK.") + elif int_dtype.itemsize == 8: + if value < 0 or value > _int64_max: + raise ValueError("Too large work array required -- computation" + " cannot be performed with standard 64-bit" + " LAPACK.") + return value diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/matfuncs.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/matfuncs.py new file mode 100644 index 0000000000000000000000000000000000000000..9ec8123b3ad8df096d5791c29bb28cce8271d4ad --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/matfuncs.py @@ -0,0 +1,23 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.linalg` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'expm', 'cosm', 'sinm', 'tanm', 'coshm', 'sinhm', + 'tanhm', 'logm', 'funm', 'signm', 'sqrtm', + 'expm_frechet', 'expm_cond', 'fractional_matrix_power', + 'khatri_rao', 'norm', 'solve', 'inv', 'svd', 'schur', 'rsf2csf' +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="linalg", module="matfuncs", + private_modules=["_matfuncs"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/misc.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/misc.py new file mode 100644 index 0000000000000000000000000000000000000000..1fad087489c6a24c8e33df54b811b6c37a3a46d4 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/misc.py @@ -0,0 +1,21 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.linalg` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'LinAlgError', 'LinAlgWarning', 'norm', 'get_blas_funcs', + 'get_lapack_funcs' +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="linalg", module="misc", + private_modules=["_misc"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/special_matrices.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/special_matrices.py new file mode 100644 index 0000000000000000000000000000000000000000..a881ce765dfa3a3c4c2853c405f8129aafc615b5 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/special_matrices.py @@ -0,0 +1,22 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.linalg` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__ = [ # noqa: F822 + 'toeplitz', 'circulant', 'hankel', + 'hadamard', 'leslie', 'kron', 'block_diag', 'companion', + 'helmert', 'hilbert', 'invhilbert', 'pascal', 'invpascal', 'dft', + 'fiedler', 'fiedler_companion', 'convolution_matrix' +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="linalg", module="special_matrices", + private_modules=["_special_matrices"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/_cython_examples/extending.pyx b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/_cython_examples/extending.pyx new file mode 100644 index 0000000000000000000000000000000000000000..3954d08791cceb3a2b66669fe3c0ec4180089208 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/_cython_examples/extending.pyx @@ -0,0 +1,23 @@ +#!/usr/bin/env python3 +#cython: language_level=3 +#cython: boundscheck=False +#cython: wraparound=False + +cimport scipy.linalg +from scipy.linalg.cython_blas cimport cdotu +from scipy.linalg.cython_lapack cimport dgtsv + +cpdef tridiag(double[:] a, double[:] b, double[:] c, double[:] x): + """ Solve the system A y = x for y where A is the tridiagonal matrix with + subdiagonal 'a', diagonal 'b', and superdiagonal 'c'. """ + cdef int n=b.shape[0], nrhs=1, info + # Solution is written over the values in x. + dgtsv(&n, &nrhs, &a[0], &b[0], &c[0], &x[0], &n, &info) + +cpdef float complex complex_dot(float complex[:] cx, float complex[:] cy): + """ Take dot product of two complex vectors """ + cdef: + int n = cx.shape[0] + int incx = cx.strides[0] // sizeof(cx[0]) + int incy = cy.strides[0] // sizeof(cy[0]) + return cdotu(&n, &cx[0], &incx, &cy[0], &incy) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/_cython_examples/meson.build b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/_cython_examples/meson.build new file mode 100644 index 0000000000000000000000000000000000000000..88f23170ac0bbe382d8470bd22a42a92d9473008 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/_cython_examples/meson.build @@ -0,0 +1,27 @@ +project('random-build-examples', 'c', 'cpp', 'cython') + +fs = import('fs') + +py3 = import('python').find_installation(pure: false) + +cy = meson.get_compiler('cython') + +if not cy.version().version_compare('>=3.0.8') + error('tests requires Cython >= 3.0.8') +endif + +py3.extension_module( + 'extending', + 'extending.pyx', + install: false, + c_args: ['-DCYTHON_CCOMPLEX=0'] # see gh-18975 for why we need this +) + +extending_cpp = fs.copyfile('extending.pyx', 'extending_cpp.pyx') +py3.extension_module( + 'extending_cpp', + extending_cpp, + install: false, + override_options : ['cython_language=cpp'], + cpp_args: ['-DCYTHON_CCOMPLEX=0'] # see gh-18975 for why we need this +) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_basic.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..fe51dcc21824ae122a17376940d43e34ec9ac22c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_basic.py @@ -0,0 +1,2059 @@ +import itertools + +import numpy as np +from numpy import (arange, array, dot, zeros, identity, conjugate, transpose, + float32) +from numpy.random import random + +from numpy.testing import (assert_equal, assert_almost_equal, assert_, + assert_array_almost_equal, assert_allclose, + assert_array_equal, suppress_warnings) +import pytest +from pytest import raises as assert_raises + +from scipy.linalg import (solve, inv, det, lstsq, pinv, pinvh, norm, + solve_banded, solveh_banded, solve_triangular, + solve_circulant, circulant, LinAlgError, block_diag, + matrix_balance, qr, LinAlgWarning) + +from scipy.linalg._testutils import assert_no_overwrite +from scipy._lib._testutils import check_free_memory, IS_MUSL +from scipy.linalg.blas import HAS_ILP64 + +REAL_DTYPES = (np.float32, np.float64, np.longdouble) +COMPLEX_DTYPES = (np.complex64, np.complex128, np.clongdouble) +DTYPES = REAL_DTYPES + COMPLEX_DTYPES + + +def _eps_cast(dtyp): + """Get the epsilon for dtype, possibly downcast to BLAS types.""" + dt = dtyp + if dt == np.longdouble: + dt = np.float64 + elif dt == np.clongdouble: + dt = np.complex128 + return np.finfo(dt).eps + + +class TestSolveBanded: + + def test_real(self): + a = array([[1.0, 20, 0, 0], + [-30, 4, 6, 0], + [2, 1, 20, 2], + [0, -1, 7, 14]]) + ab = array([[0.0, 20, 6, 2], + [1, 4, 20, 14], + [-30, 1, 7, 0], + [2, -1, 0, 0]]) + l, u = 2, 1 + b4 = array([10.0, 0.0, 2.0, 14.0]) + b4by1 = b4.reshape(-1, 1) + b4by2 = array([[2, 1], + [-30, 4], + [2, 3], + [1, 3]]) + b4by4 = array([[1, 0, 0, 0], + [0, 0, 0, 1], + [0, 1, 0, 0], + [0, 1, 0, 0]]) + for b in [b4, b4by1, b4by2, b4by4]: + x = solve_banded((l, u), ab, b) + assert_array_almost_equal(dot(a, x), b) + + def test_complex(self): + a = array([[1.0, 20, 0, 0], + [-30, 4, 6, 0], + [2j, 1, 20, 2j], + [0, -1, 7, 14]]) + ab = array([[0.0, 20, 6, 2j], + [1, 4, 20, 14], + [-30, 1, 7, 0], + [2j, -1, 0, 0]]) + l, u = 2, 1 + b4 = array([10.0, 0.0, 2.0, 14.0j]) + b4by1 = b4.reshape(-1, 1) + b4by2 = array([[2, 1], + [-30, 4], + [2, 3], + [1, 3]]) + b4by4 = array([[1, 0, 0, 0], + [0, 0, 0, 1j], + [0, 1, 0, 0], + [0, 1, 0, 0]]) + for b in [b4, b4by1, b4by2, b4by4]: + x = solve_banded((l, u), ab, b) + assert_array_almost_equal(dot(a, x), b) + + def test_tridiag_real(self): + ab = array([[0.0, 20, 6, 2], + [1, 4, 20, 14], + [-30, 1, 7, 0]]) + a = np.diag(ab[0, 1:], 1) + np.diag(ab[1, :], 0) + np.diag( + ab[2, :-1], -1) + b4 = array([10.0, 0.0, 2.0, 14.0]) + b4by1 = b4.reshape(-1, 1) + b4by2 = array([[2, 1], + [-30, 4], + [2, 3], + [1, 3]]) + b4by4 = array([[1, 0, 0, 0], + [0, 0, 0, 1], + [0, 1, 0, 0], + [0, 1, 0, 0]]) + for b in [b4, b4by1, b4by2, b4by4]: + x = solve_banded((1, 1), ab, b) + assert_array_almost_equal(dot(a, x), b) + + def test_tridiag_complex(self): + ab = array([[0.0, 20, 6, 2j], + [1, 4, 20, 14], + [-30, 1, 7, 0]]) + a = np.diag(ab[0, 1:], 1) + np.diag(ab[1, :], 0) + np.diag( + ab[2, :-1], -1) + b4 = array([10.0, 0.0, 2.0, 14.0j]) + b4by1 = b4.reshape(-1, 1) + b4by2 = array([[2, 1], + [-30, 4], + [2, 3], + [1, 3]]) + b4by4 = array([[1, 0, 0, 0], + [0, 0, 0, 1], + [0, 1, 0, 0], + [0, 1, 0, 0]]) + for b in [b4, b4by1, b4by2, b4by4]: + x = solve_banded((1, 1), ab, b) + assert_array_almost_equal(dot(a, x), b) + + def test_check_finite(self): + a = array([[1.0, 20, 0, 0], + [-30, 4, 6, 0], + [2, 1, 20, 2], + [0, -1, 7, 14]]) + ab = array([[0.0, 20, 6, 2], + [1, 4, 20, 14], + [-30, 1, 7, 0], + [2, -1, 0, 0]]) + l, u = 2, 1 + b4 = array([10.0, 0.0, 2.0, 14.0]) + x = solve_banded((l, u), ab, b4, check_finite=False) + assert_array_almost_equal(dot(a, x), b4) + + def test_bad_shape(self): + ab = array([[0.0, 20, 6, 2], + [1, 4, 20, 14], + [-30, 1, 7, 0], + [2, -1, 0, 0]]) + l, u = 2, 1 + bad = array([1.0, 2.0, 3.0, 4.0]).reshape(-1, 4) + assert_raises(ValueError, solve_banded, (l, u), ab, bad) + assert_raises(ValueError, solve_banded, (l, u), ab, [1.0, 2.0]) + + # Values of (l,u) are not compatible with ab. + assert_raises(ValueError, solve_banded, (1, 1), ab, [1.0, 2.0]) + + def test_1x1(self): + # gh-8906 noted that the case of A@x = b with 1x1 A was handled + # incorrectly; check that this is resolved. Typical case: + # nupper == nlower == 0 + # A = [[2]] + b = array([[1., 2., 3.]]) + ref = array([[0.5, 1.0, 1.5]]) + x = solve_banded((0, 0), [[2]], b) + assert_allclose(x, ref, rtol=1e-15) + + # However, the user *can* represent the same system with garbage rows + # in `ab`. Test the case with `nupper == 1, nlower == 1`. + x = solve_banded((1, 1), [[0], [2], [0]], b) + assert_allclose(x, ref, rtol=1e-15) + assert_equal(x.dtype, np.dtype('f8')) + assert_array_equal(b, [[1.0, 2.0, 3.0]]) + + def test_native_list_arguments(self): + a = [[1.0, 20, 0, 0], + [-30, 4, 6, 0], + [2, 1, 20, 2], + [0, -1, 7, 14]] + ab = [[0.0, 20, 6, 2], + [1, 4, 20, 14], + [-30, 1, 7, 0], + [2, -1, 0, 0]] + l, u = 2, 1 + b = [10.0, 0.0, 2.0, 14.0] + x = solve_banded((l, u), ab, b) + assert_array_almost_equal(dot(a, x), b) + + @pytest.mark.thread_unsafe # due to Cython fused types, see cython#6506 + @pytest.mark.parametrize('dt_ab', [int, float, np.float32, complex, np.complex64]) + @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64]) + def test_empty(self, dt_ab, dt_b): + # ab contains one empty row corresponding to the diagonal + ab = np.array([[]], dtype=dt_ab) + b = np.array([], dtype=dt_b) + x = solve_banded((0, 0), ab, b) + + assert x.shape == (0,) + assert x.dtype == solve(np.eye(1, dtype=dt_ab), np.ones(1, dtype=dt_b)).dtype + + b = np.empty((0, 0), dtype=dt_b) + x = solve_banded((0, 0), ab, b) + + assert x.shape == (0, 0) + assert x.dtype == solve(np.eye(1, dtype=dt_ab), np.ones(1, dtype=dt_b)).dtype + + +class TestSolveHBanded: + + def test_01_upper(self): + # Solve + # [ 4 1 2 0] [1] + # [ 1 4 1 2] X = [4] + # [ 2 1 4 1] [1] + # [ 0 2 1 4] [2] + # with the RHS as a 1D array. + ab = array([[0.0, 0.0, 2.0, 2.0], + [-99, 1.0, 1.0, 1.0], + [4.0, 4.0, 4.0, 4.0]]) + b = array([1.0, 4.0, 1.0, 2.0]) + x = solveh_banded(ab, b) + assert_array_almost_equal(x, [0.0, 1.0, 0.0, 0.0]) + + def test_02_upper(self): + # Solve + # [ 4 1 2 0] [1 6] + # [ 1 4 1 2] X = [4 2] + # [ 2 1 4 1] [1 6] + # [ 0 2 1 4] [2 1] + # + ab = array([[0.0, 0.0, 2.0, 2.0], + [-99, 1.0, 1.0, 1.0], + [4.0, 4.0, 4.0, 4.0]]) + b = array([[1.0, 6.0], + [4.0, 2.0], + [1.0, 6.0], + [2.0, 1.0]]) + x = solveh_banded(ab, b) + expected = array([[0.0, 1.0], + [1.0, 0.0], + [0.0, 1.0], + [0.0, 0.0]]) + assert_array_almost_equal(x, expected) + + def test_03_upper(self): + # Solve + # [ 4 1 2 0] [1] + # [ 1 4 1 2] X = [4] + # [ 2 1 4 1] [1] + # [ 0 2 1 4] [2] + # with the RHS as a 2D array with shape (3,1). + ab = array([[0.0, 0.0, 2.0, 2.0], + [-99, 1.0, 1.0, 1.0], + [4.0, 4.0, 4.0, 4.0]]) + b = array([1.0, 4.0, 1.0, 2.0]).reshape(-1, 1) + x = solveh_banded(ab, b) + assert_array_almost_equal(x, array([0., 1., 0., 0.]).reshape(-1, 1)) + + def test_01_lower(self): + # Solve + # [ 4 1 2 0] [1] + # [ 1 4 1 2] X = [4] + # [ 2 1 4 1] [1] + # [ 0 2 1 4] [2] + # + ab = array([[4.0, 4.0, 4.0, 4.0], + [1.0, 1.0, 1.0, -99], + [2.0, 2.0, 0.0, 0.0]]) + b = array([1.0, 4.0, 1.0, 2.0]) + x = solveh_banded(ab, b, lower=True) + assert_array_almost_equal(x, [0.0, 1.0, 0.0, 0.0]) + + def test_02_lower(self): + # Solve + # [ 4 1 2 0] [1 6] + # [ 1 4 1 2] X = [4 2] + # [ 2 1 4 1] [1 6] + # [ 0 2 1 4] [2 1] + # + ab = array([[4.0, 4.0, 4.0, 4.0], + [1.0, 1.0, 1.0, -99], + [2.0, 2.0, 0.0, 0.0]]) + b = array([[1.0, 6.0], + [4.0, 2.0], + [1.0, 6.0], + [2.0, 1.0]]) + x = solveh_banded(ab, b, lower=True) + expected = array([[0.0, 1.0], + [1.0, 0.0], + [0.0, 1.0], + [0.0, 0.0]]) + assert_array_almost_equal(x, expected) + + def test_01_float32(self): + # Solve + # [ 4 1 2 0] [1] + # [ 1 4 1 2] X = [4] + # [ 2 1 4 1] [1] + # [ 0 2 1 4] [2] + # + ab = array([[0.0, 0.0, 2.0, 2.0], + [-99, 1.0, 1.0, 1.0], + [4.0, 4.0, 4.0, 4.0]], dtype=float32) + b = array([1.0, 4.0, 1.0, 2.0], dtype=float32) + x = solveh_banded(ab, b) + assert_array_almost_equal(x, [0.0, 1.0, 0.0, 0.0]) + + def test_02_float32(self): + # Solve + # [ 4 1 2 0] [1 6] + # [ 1 4 1 2] X = [4 2] + # [ 2 1 4 1] [1 6] + # [ 0 2 1 4] [2 1] + # + ab = array([[0.0, 0.0, 2.0, 2.0], + [-99, 1.0, 1.0, 1.0], + [4.0, 4.0, 4.0, 4.0]], dtype=float32) + b = array([[1.0, 6.0], + [4.0, 2.0], + [1.0, 6.0], + [2.0, 1.0]], dtype=float32) + x = solveh_banded(ab, b) + expected = array([[0.0, 1.0], + [1.0, 0.0], + [0.0, 1.0], + [0.0, 0.0]]) + assert_array_almost_equal(x, expected) + + def test_01_complex(self): + # Solve + # [ 4 -j 2 0] [2-j] + # [ j 4 -j 2] X = [4-j] + # [ 2 j 4 -j] [4+j] + # [ 0 2 j 4] [2+j] + # + ab = array([[0.0, 0.0, 2.0, 2.0], + [-99, -1.0j, -1.0j, -1.0j], + [4.0, 4.0, 4.0, 4.0]]) + b = array([2-1.0j, 4.0-1j, 4+1j, 2+1j]) + x = solveh_banded(ab, b) + assert_array_almost_equal(x, [0.0, 1.0, 1.0, 0.0]) + + def test_02_complex(self): + # Solve + # [ 4 -j 2 0] [2-j 2+4j] + # [ j 4 -j 2] X = [4-j -1-j] + # [ 2 j 4 -j] [4+j 4+2j] + # [ 0 2 j 4] [2+j j] + # + ab = array([[0.0, 0.0, 2.0, 2.0], + [-99, -1.0j, -1.0j, -1.0j], + [4.0, 4.0, 4.0, 4.0]]) + b = array([[2-1j, 2+4j], + [4.0-1j, -1-1j], + [4.0+1j, 4+2j], + [2+1j, 1j]]) + x = solveh_banded(ab, b) + expected = array([[0.0, 1.0j], + [1.0, 0.0], + [1.0, 1.0], + [0.0, 0.0]]) + assert_array_almost_equal(x, expected) + + def test_tridiag_01_upper(self): + # Solve + # [ 4 1 0] [1] + # [ 1 4 1] X = [4] + # [ 0 1 4] [1] + # with the RHS as a 1D array. + ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]]) + b = array([1.0, 4.0, 1.0]) + x = solveh_banded(ab, b) + assert_array_almost_equal(x, [0.0, 1.0, 0.0]) + + def test_tridiag_02_upper(self): + # Solve + # [ 4 1 0] [1 4] + # [ 1 4 1] X = [4 2] + # [ 0 1 4] [1 4] + # + ab = array([[-99, 1.0, 1.0], + [4.0, 4.0, 4.0]]) + b = array([[1.0, 4.0], + [4.0, 2.0], + [1.0, 4.0]]) + x = solveh_banded(ab, b) + expected = array([[0.0, 1.0], + [1.0, 0.0], + [0.0, 1.0]]) + assert_array_almost_equal(x, expected) + + def test_tridiag_03_upper(self): + # Solve + # [ 4 1 0] [1] + # [ 1 4 1] X = [4] + # [ 0 1 4] [1] + # with the RHS as a 2D array with shape (3,1). + ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]]) + b = array([1.0, 4.0, 1.0]).reshape(-1, 1) + x = solveh_banded(ab, b) + assert_array_almost_equal(x, array([0.0, 1.0, 0.0]).reshape(-1, 1)) + + def test_tridiag_01_lower(self): + # Solve + # [ 4 1 0] [1] + # [ 1 4 1] X = [4] + # [ 0 1 4] [1] + # + ab = array([[4.0, 4.0, 4.0], + [1.0, 1.0, -99]]) + b = array([1.0, 4.0, 1.0]) + x = solveh_banded(ab, b, lower=True) + assert_array_almost_equal(x, [0.0, 1.0, 0.0]) + + def test_tridiag_02_lower(self): + # Solve + # [ 4 1 0] [1 4] + # [ 1 4 1] X = [4 2] + # [ 0 1 4] [1 4] + # + ab = array([[4.0, 4.0, 4.0], + [1.0, 1.0, -99]]) + b = array([[1.0, 4.0], + [4.0, 2.0], + [1.0, 4.0]]) + x = solveh_banded(ab, b, lower=True) + expected = array([[0.0, 1.0], + [1.0, 0.0], + [0.0, 1.0]]) + assert_array_almost_equal(x, expected) + + def test_tridiag_01_float32(self): + # Solve + # [ 4 1 0] [1] + # [ 1 4 1] X = [4] + # [ 0 1 4] [1] + # + ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]], dtype=float32) + b = array([1.0, 4.0, 1.0], dtype=float32) + x = solveh_banded(ab, b) + assert_array_almost_equal(x, [0.0, 1.0, 0.0]) + + def test_tridiag_02_float32(self): + # Solve + # [ 4 1 0] [1 4] + # [ 1 4 1] X = [4 2] + # [ 0 1 4] [1 4] + # + ab = array([[-99, 1.0, 1.0], + [4.0, 4.0, 4.0]], dtype=float32) + b = array([[1.0, 4.0], + [4.0, 2.0], + [1.0, 4.0]], dtype=float32) + x = solveh_banded(ab, b) + expected = array([[0.0, 1.0], + [1.0, 0.0], + [0.0, 1.0]]) + assert_array_almost_equal(x, expected) + + def test_tridiag_01_complex(self): + # Solve + # [ 4 -j 0] [ -j] + # [ j 4 -j] X = [4-j] + # [ 0 j 4] [4+j] + # + ab = array([[-99, -1.0j, -1.0j], [4.0, 4.0, 4.0]]) + b = array([-1.0j, 4.0-1j, 4+1j]) + x = solveh_banded(ab, b) + assert_array_almost_equal(x, [0.0, 1.0, 1.0]) + + def test_tridiag_02_complex(self): + # Solve + # [ 4 -j 0] [ -j 4j] + # [ j 4 -j] X = [4-j -1-j] + # [ 0 j 4] [4+j 4 ] + # + ab = array([[-99, -1.0j, -1.0j], + [4.0, 4.0, 4.0]]) + b = array([[-1j, 4.0j], + [4.0-1j, -1.0-1j], + [4.0+1j, 4.0]]) + x = solveh_banded(ab, b) + expected = array([[0.0, 1.0j], + [1.0, 0.0], + [1.0, 1.0]]) + assert_array_almost_equal(x, expected) + + def test_check_finite(self): + # Solve + # [ 4 1 0] [1] + # [ 1 4 1] X = [4] + # [ 0 1 4] [1] + # with the RHS as a 1D array. + ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]]) + b = array([1.0, 4.0, 1.0]) + x = solveh_banded(ab, b, check_finite=False) + assert_array_almost_equal(x, [0.0, 1.0, 0.0]) + + def test_bad_shapes(self): + ab = array([[-99, 1.0, 1.0], + [4.0, 4.0, 4.0]]) + b = array([[1.0, 4.0], + [4.0, 2.0]]) + assert_raises(ValueError, solveh_banded, ab, b) + assert_raises(ValueError, solveh_banded, ab, [1.0, 2.0]) + assert_raises(ValueError, solveh_banded, ab, [1.0]) + + def test_1x1(self): + x = solveh_banded([[1]], [[1, 2, 3]]) + assert_array_equal(x, [[1.0, 2.0, 3.0]]) + assert_equal(x.dtype, np.dtype('f8')) + + def test_native_list_arguments(self): + # Same as test_01_upper, using python's native list. + ab = [[0.0, 0.0, 2.0, 2.0], + [-99, 1.0, 1.0, 1.0], + [4.0, 4.0, 4.0, 4.0]] + b = [1.0, 4.0, 1.0, 2.0] + x = solveh_banded(ab, b) + assert_array_almost_equal(x, [0.0, 1.0, 0.0, 0.0]) + + @pytest.mark.parametrize('dt_ab', [int, float, np.float32, complex, np.complex64]) + @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64]) + def test_empty(self, dt_ab, dt_b): + # ab contains one empty row corresponding to the diagonal + ab = np.array([[]], dtype=dt_ab) + b = np.array([], dtype=dt_b) + x = solveh_banded(ab, b) + + assert x.shape == (0,) + assert x.dtype == solve(np.eye(1, dtype=dt_ab), np.ones(1, dtype=dt_b)).dtype + + b = np.empty((0, 0), dtype=dt_b) + x = solveh_banded(ab, b) + + assert x.shape == (0, 0) + assert x.dtype == solve(np.eye(1, dtype=dt_ab), np.ones(1, dtype=dt_b)).dtype + + +class TestSolve: + def setup_method(self): + np.random.seed(1234) + + @pytest.mark.thread_unsafe + def test_20Feb04_bug(self): + a = [[1, 1], [1.0, 0]] # ok + x0 = solve(a, [1, 0j]) + assert_array_almost_equal(dot(a, x0), [1, 0]) + + # gives failure with clapack.zgesv(..,rowmajor=0) + a = [[1, 1], [1.2, 0]] + b = [1, 0j] + x0 = solve(a, b) + assert_array_almost_equal(dot(a, x0), [1, 0]) + + def test_simple(self): + a = [[1, 20], [-30, 4]] + for b in ([[1, 0], [0, 1]], + [1, 0], + [[2, 1], [-30, 4]] + ): + x = solve(a, b) + assert_array_almost_equal(dot(a, x), b) + + def test_simple_complex(self): + a = array([[5, 2], [2j, 4]], 'D') + for b in ([1j, 0], + [[1j, 1j], [0, 2]], + [1, 0j], + array([1, 0], 'D'), + ): + x = solve(a, b) + assert_array_almost_equal(dot(a, x), b) + + def test_simple_pos(self): + a = [[2, 3], [3, 5]] + for lower in [0, 1]: + for b in ([[1, 0], [0, 1]], + [1, 0] + ): + x = solve(a, b, assume_a='pos', lower=lower) + assert_array_almost_equal(dot(a, x), b) + + def test_simple_pos_complexb(self): + a = [[5, 2], [2, 4]] + for b in ([1j, 0], + [[1j, 1j], [0, 2]], + ): + x = solve(a, b, assume_a='pos') + assert_array_almost_equal(dot(a, x), b) + + def test_simple_sym(self): + a = [[2, 3], [3, -5]] + for lower in [0, 1]: + for b in ([[1, 0], [0, 1]], + [1, 0] + ): + x = solve(a, b, assume_a='sym', lower=lower) + assert_array_almost_equal(dot(a, x), b) + + def test_simple_sym_complexb(self): + a = [[5, 2], [2, -4]] + for b in ([1j, 0], + [[1j, 1j], [0, 2]] + ): + x = solve(a, b, assume_a='sym') + assert_array_almost_equal(dot(a, x), b) + + def test_simple_sym_complex(self): + a = [[5, 2+1j], [2+1j, -4]] + for b in ([1j, 0], + [1, 0], + [[1j, 1j], [0, 2]] + ): + x = solve(a, b, assume_a='sym') + assert_array_almost_equal(dot(a, x), b) + + def test_simple_her_actuallysym(self): + a = [[2, 3], [3, -5]] + for lower in [0, 1]: + for b in ([[1, 0], [0, 1]], + [1, 0], + [1j, 0], + ): + x = solve(a, b, assume_a='her', lower=lower) + assert_array_almost_equal(dot(a, x), b) + + def test_simple_her(self): + a = [[5, 2+1j], [2-1j, -4]] + for b in ([1j, 0], + [1, 0], + [[1j, 1j], [0, 2]] + ): + x = solve(a, b, assume_a='her') + assert_array_almost_equal(dot(a, x), b) + + def test_nils_20Feb04(self): + n = 2 + A = random([n, n])+random([n, n])*1j + X = zeros((n, n), 'D') + Ainv = inv(A) + R = identity(n)+identity(n)*0j + for i in arange(0, n): + r = R[:, i] + X[:, i] = solve(A, r) + assert_array_almost_equal(X, Ainv) + + def test_random(self): + + n = 20 + a = random([n, n]) + for i in range(n): + a[i, i] = 20*(.1+a[i, i]) + for i in range(4): + b = random([n, 3]) + x = solve(a, b) + assert_array_almost_equal(dot(a, x), b) + + def test_random_complex(self): + n = 20 + a = random([n, n]) + 1j * random([n, n]) + for i in range(n): + a[i, i] = 20*(.1+a[i, i]) + for i in range(2): + b = random([n, 3]) + x = solve(a, b) + assert_array_almost_equal(dot(a, x), b) + + def test_random_sym(self): + n = 20 + a = random([n, n]) + for i in range(n): + a[i, i] = abs(20*(.1+a[i, i])) + for j in range(i): + a[i, j] = a[j, i] + for i in range(4): + b = random([n]) + x = solve(a, b, assume_a="pos") + assert_array_almost_equal(dot(a, x), b) + + def test_random_sym_complex(self): + n = 20 + a = random([n, n]) + a = a + 1j*random([n, n]) + for i in range(n): + a[i, i] = abs(20*(.1+a[i, i])) + for j in range(i): + a[i, j] = conjugate(a[j, i]) + b = random([n])+2j*random([n]) + for i in range(2): + x = solve(a, b, assume_a="pos") + assert_array_almost_equal(dot(a, x), b) + + def test_check_finite(self): + a = [[1, 20], [-30, 4]] + for b in ([[1, 0], [0, 1]], [1, 0], + [[2, 1], [-30, 4]]): + x = solve(a, b, check_finite=False) + assert_array_almost_equal(dot(a, x), b) + + def test_scalar_a_and_1D_b(self): + a = 1 + b = [1, 2, 3] + x = solve(a, b) + assert_array_almost_equal(x.ravel(), b) + assert_(x.shape == (3,), 'Scalar_a_1D_b test returned wrong shape') + + def test_simple2(self): + a = np.array([[1.80, 2.88, 2.05, -0.89], + [525.00, -295.00, -95.00, -380.00], + [1.58, -2.69, -2.90, -1.04], + [-1.11, -0.66, -0.59, 0.80]]) + + b = np.array([[9.52, 18.47], + [2435.00, 225.00], + [0.77, -13.28], + [-6.22, -6.21]]) + + x = solve(a, b) + assert_array_almost_equal(x, np.array([[1., -1, 3, -5], + [3, 2, 4, 1]]).T) + + def test_simple_complex2(self): + a = np.array([[-1.34+2.55j, 0.28+3.17j, -6.39-2.20j, 0.72-0.92j], + [-1.70-14.10j, 33.10-1.50j, -1.50+13.40j, 12.90+13.80j], + [-3.29-2.39j, -1.91+4.42j, -0.14-1.35j, 1.72+1.35j], + [2.41+0.39j, -0.56+1.47j, -0.83-0.69j, -1.96+0.67j]]) + + b = np.array([[26.26+51.78j, 31.32-6.70j], + [64.30-86.80j, 158.60-14.20j], + [-5.75+25.31j, -2.15+30.19j], + [1.16+2.57j, -2.56+7.55j]]) + + x = solve(a, b) + assert_array_almost_equal(x, np. array([[1+1.j, -1-2.j], + [2-3.j, 5+1.j], + [-4-5.j, -3+4.j], + [6.j, 2-3.j]])) + + def test_hermitian(self): + # An upper triangular matrix will be used for hermitian matrix a + a = np.array([[-1.84, 0.11-0.11j, -1.78-1.18j, 3.91-1.50j], + [0, -4.63, -1.84+0.03j, 2.21+0.21j], + [0, 0, -8.87, 1.58-0.90j], + [0, 0, 0, -1.36]]) + b = np.array([[2.98-10.18j, 28.68-39.89j], + [-9.58+3.88j, -24.79-8.40j], + [-0.77-16.05j, 4.23-70.02j], + [7.79+5.48j, -35.39+18.01j]]) + res = np.array([[2.+1j, -8+6j], + [3.-2j, 7-2j], + [-1+2j, -1+5j], + [1.-1j, 3-4j]]) + x = solve(a, b, assume_a='her') + assert_array_almost_equal(x, res) + # Also conjugate a and test for lower triangular data + x = solve(a.conj().T, b, assume_a='her', lower=True) + assert_array_almost_equal(x, res) + + def test_pos_and_sym(self): + A = np.arange(1, 10).reshape(3, 3) + x = solve(np.tril(A)/9, np.ones(3), assume_a='pos') + assert_array_almost_equal(x, [9., 1.8, 1.]) + x = solve(np.tril(A)/9, np.ones(3), assume_a='sym') + assert_array_almost_equal(x, [9., 1.8, 1.]) + + def test_singularity(self): + a = np.array([[1, 0, 0, 0, 0, 0, 1, 0, 1], + [1, 1, 1, 0, 0, 0, 1, 0, 1], + [0, 1, 1, 0, 0, 0, 1, 0, 1], + [1, 0, 1, 1, 1, 1, 0, 0, 0], + [1, 0, 1, 1, 1, 1, 0, 0, 0], + [1, 0, 1, 1, 1, 1, 0, 0, 0], + [1, 0, 1, 1, 1, 1, 0, 0, 0], + [1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1]]) + b = np.arange(9)[:, None] + assert_raises(LinAlgError, solve, a, b) + + @pytest.mark.thread_unsafe + @pytest.mark.parametrize('structure', + ('diagonal', 'tridiagonal', 'lower triangular', + 'upper triangular', 'symmetric', 'hermitian', + 'positive definite', 'general', None)) + def test_ill_condition_warning(self, structure): + rng = np.random.default_rng(234859349452) + n = 10 + d = np.logspace(0, 50, n) + A = np.diag(d) + b = rng.random(size=n) + message = "Ill-conditioned matrix..." + with pytest.warns(LinAlgWarning, match=message): + solve(A, b, assume_a=structure) + + def test_multiple_rhs(self): + a = np.eye(2) + b = np.random.rand(2, 3, 4) + x = solve(a, b) + assert_array_almost_equal(x, b) + + def test_transposed_keyword(self): + A = np.arange(9).reshape(3, 3) + 1 + x = solve(np.tril(A)/9, np.ones(3), transposed=True) + assert_array_almost_equal(x, [1.2, 0.2, 1]) + x = solve(np.tril(A)/9, np.ones(3), transposed=False) + assert_array_almost_equal(x, [9, -5.4, -1.2]) + + def test_transposed_notimplemented(self): + a = np.eye(3).astype(complex) + with assert_raises(NotImplementedError): + solve(a, a, transposed=True) + + def test_nonsquare_a(self): + assert_raises(ValueError, solve, [1, 2], 1) + + def test_size_mismatch_with_1D_b(self): + assert_array_almost_equal(solve(np.eye(3), np.ones(3)), np.ones(3)) + assert_raises(ValueError, solve, np.eye(3), np.ones(4)) + + def test_assume_a_keyword(self): + assert_raises(ValueError, solve, 1, 1, assume_a='zxcv') + + @pytest.mark.skip(reason="Failure on OS X (gh-7500), " + "crash on Windows (gh-8064)") + def test_all_type_size_routine_combinations(self): + sizes = [10, 100] + assume_as = ['gen', 'sym', 'pos', 'her'] + dtypes = [np.float32, np.float64, np.complex64, np.complex128] + for size, assume_a, dtype in itertools.product(sizes, assume_as, + dtypes): + is_complex = dtype in (np.complex64, np.complex128) + if assume_a == 'her' and not is_complex: + continue + + err_msg = (f"Failed for size: {size}, assume_a: {assume_a}," + f"dtype: {dtype}") + + a = np.random.randn(size, size).astype(dtype) + b = np.random.randn(size).astype(dtype) + if is_complex: + a = a + (1j*np.random.randn(size, size)).astype(dtype) + + if assume_a == 'sym': # Can still be complex but only symmetric + a = a + a.T + elif assume_a == 'her': # Handle hermitian matrices here instead + a = a + a.T.conj() + elif assume_a == 'pos': + a = a.conj().T.dot(a) + 0.1*np.eye(size) + + tol = 1e-12 if dtype in (np.float64, np.complex128) else 1e-6 + + if assume_a in ['gen', 'sym', 'her']: + # We revert the tolerance from before + # 4b4a6e7c34fa4060533db38f9a819b98fa81476c + if dtype in (np.float32, np.complex64): + tol *= 10 + + x = solve(a, b, assume_a=assume_a) + assert_allclose(a.dot(x), b, + atol=tol * size, + rtol=tol * size, + err_msg=err_msg) + + if assume_a == 'sym' and dtype not in (np.complex64, + np.complex128): + x = solve(a, b, assume_a=assume_a, transposed=True) + assert_allclose(a.dot(x), b, + atol=tol * size, + rtol=tol * size, + err_msg=err_msg) + + @pytest.mark.thread_unsafe + @pytest.mark.parametrize('dt_a', [int, float, np.float32, complex, np.complex64]) + @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64]) + def test_empty(self, dt_a, dt_b): + a = np.empty((0, 0), dtype=dt_a) + b = np.empty(0, dtype=dt_b) + x = solve(a, b) + + assert x.size == 0 + dt_nonempty = solve(np.eye(2, dtype=dt_a), np.ones(2, dtype=dt_b)).dtype + assert x.dtype == dt_nonempty + + def test_empty_rhs(self): + a = np.eye(2) + b = [[], []] + x = solve(a, b) + assert_(x.size == 0, 'Returned array is not empty') + assert_(x.shape == (2, 0), 'Returned empty array shape is wrong') + + @pytest.mark.parametrize('dtype', [np.float64, np.complex128]) + # "pos" and "positive definite" need to be added + @pytest.mark.parametrize('assume_a', ['diagonal', 'tridiagonal', 'banded', + 'lower triangular', 'upper triangular', + 'symmetric', 'hermitian', + 'general', 'sym', 'her', 'gen']) + @pytest.mark.parametrize('nrhs', [(), (5,)]) + @pytest.mark.parametrize('transposed', [True, False]) + @pytest.mark.parametrize('overwrite', [True, False]) + @pytest.mark.parametrize('fortran', [True, False]) + def test_structure_detection(self, dtype, assume_a, nrhs, transposed, + overwrite, fortran): + rng = np.random.default_rng(982345982439826) + n = 5 if not assume_a == 'banded' else 20 + b = rng.random(size=(n,) + nrhs) + A = rng.random(size=(n, n)) + + if np.issubdtype(dtype, np.complexfloating): + b = b + rng.random(size=(n,) + nrhs) * 1j + A = A + rng.random(size=(n, n)) * 1j + + if assume_a == 'diagonal': + A = np.diag(np.diag(A)) + elif assume_a == 'lower triangular': + A = np.tril(A) + elif assume_a == 'upper triangular': + A = np.triu(A) + elif assume_a == 'tridiagonal': + A = (np.diag(np.diag(A)) + + np.diag(np.diag(A, -1), -1) + + np.diag(np.diag(A, 1), 1)) + elif assume_a == 'banded': + A = np.triu(np.tril(A, 2), -1) + elif assume_a in {'symmetric', 'sym'}: + A = A + A.T + elif assume_a in {'hermitian', 'her'}: + A = A + A.conj().T + elif assume_a in {'positive definite', 'pos'}: + A = A + A.T + A += np.diag(A.sum(axis=1)) + + if fortran: + A = np.asfortranarray(A) + + A_copy = A.copy(order='A') + b_copy = b.copy() + + if np.issubdtype(dtype, np.complexfloating) and transposed: + message = "scipy.linalg.solve can currently..." + with pytest.raises(NotImplementedError, match=message): + solve(A, b, overwrite_a=overwrite, overwrite_b=overwrite, + transposed=transposed) + return + + res = solve(A, b, overwrite_a=overwrite, overwrite_b=overwrite, + transposed=transposed, assume_a=assume_a) + + # Check that solution this solution is *correct* + ref = np.linalg.solve(A_copy.T if transposed else A_copy, b_copy) + assert_allclose(res, ref) + + # Check that `solve` correctly identifies the structure and returns + # *exactly* the same solution whether `assume_a` is specified or not + if assume_a != 'banded': # structure detection removed for banded + assert_equal(solve(A_copy, b_copy, transposed=transposed), res) + + # Check that overwrite was respected + if not overwrite: + assert_equal(A, A_copy) + assert_equal(b, b_copy) + + +class TestSolveTriangular: + + def test_simple(self): + """ + solve_triangular on a simple 2x2 matrix. + """ + A = array([[1, 0], [1, 2]]) + b = [1, 1] + sol = solve_triangular(A, b, lower=True) + assert_array_almost_equal(sol, [1, 0]) + + # check that it works also for non-contiguous matrices + sol = solve_triangular(A.T, b, lower=False) + assert_array_almost_equal(sol, [.5, .5]) + + # and that it gives the same result as trans=1 + sol = solve_triangular(A, b, lower=True, trans=1) + assert_array_almost_equal(sol, [.5, .5]) + + b = identity(2) + sol = solve_triangular(A, b, lower=True, trans=1) + assert_array_almost_equal(sol, [[1., -.5], [0, 0.5]]) + + def test_simple_complex(self): + """ + solve_triangular on a simple 2x2 complex matrix + """ + A = array([[1+1j, 0], [1j, 2]]) + b = identity(2) + sol = solve_triangular(A, b, lower=True, trans=1) + assert_array_almost_equal(sol, [[.5-.5j, -.25-.25j], [0, 0.5]]) + + # check other option combinations with complex rhs + b = np.diag([1+1j, 1+2j]) + sol = solve_triangular(A, b, lower=True, trans=0) + assert_array_almost_equal(sol, [[1, 0], [-0.5j, 0.5+1j]]) + + sol = solve_triangular(A, b, lower=True, trans=1) + assert_array_almost_equal(sol, [[1, 0.25-0.75j], [0, 0.5+1j]]) + + sol = solve_triangular(A, b, lower=True, trans=2) + assert_array_almost_equal(sol, [[1j, -0.75-0.25j], [0, 0.5+1j]]) + + sol = solve_triangular(A.T, b, lower=False, trans=0) + assert_array_almost_equal(sol, [[1, 0.25-0.75j], [0, 0.5+1j]]) + + sol = solve_triangular(A.T, b, lower=False, trans=1) + assert_array_almost_equal(sol, [[1, 0], [-0.5j, 0.5+1j]]) + + sol = solve_triangular(A.T, b, lower=False, trans=2) + assert_array_almost_equal(sol, [[1j, 0], [-0.5, 0.5+1j]]) + + def test_check_finite(self): + """ + solve_triangular on a simple 2x2 matrix. + """ + A = array([[1, 0], [1, 2]]) + b = [1, 1] + sol = solve_triangular(A, b, lower=True, check_finite=False) + assert_array_almost_equal(sol, [1, 0]) + + @pytest.mark.parametrize('dt_a', [int, float, np.float32, complex, np.complex64]) + @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64]) + def test_empty(self, dt_a, dt_b): + a = np.empty((0, 0), dtype=dt_a) + b = np.empty(0, dtype=dt_b) + x = solve_triangular(a, b) + + assert x.size == 0 + dt_nonempty = solve_triangular( + np.eye(2, dtype=dt_a), np.ones(2, dtype=dt_b) + ).dtype + assert x.dtype == dt_nonempty + + def test_empty_rhs(self): + a = np.eye(2) + b = [[], []] + x = solve_triangular(a, b) + assert_(x.size == 0, 'Returned array is not empty') + assert_(x.shape == (2, 0), 'Returned empty array shape is wrong') + + +class TestInv: + def setup_method(self): + np.random.seed(1234) + + def test_simple(self): + a = [[1, 2], [3, 4]] + a_inv = inv(a) + assert_array_almost_equal(dot(a, a_inv), np.eye(2)) + a = [[1, 2, 3], [4, 5, 6], [7, 8, 10]] + a_inv = inv(a) + assert_array_almost_equal(dot(a, a_inv), np.eye(3)) + + def test_random(self): + n = 20 + for i in range(4): + a = random([n, n]) + for i in range(n): + a[i, i] = 20*(.1+a[i, i]) + a_inv = inv(a) + assert_array_almost_equal(dot(a, a_inv), + identity(n)) + + def test_simple_complex(self): + a = [[1, 2], [3, 4j]] + a_inv = inv(a) + assert_array_almost_equal(dot(a, a_inv), [[1, 0], [0, 1]]) + + def test_random_complex(self): + n = 20 + for i in range(4): + a = random([n, n])+2j*random([n, n]) + for i in range(n): + a[i, i] = 20*(.1+a[i, i]) + a_inv = inv(a) + assert_array_almost_equal(dot(a, a_inv), + identity(n)) + + def test_check_finite(self): + a = [[1, 2], [3, 4]] + a_inv = inv(a, check_finite=False) + assert_array_almost_equal(dot(a, a_inv), [[1, 0], [0, 1]]) + + @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) + def test_empty(self, dt): + a = np.empty((0, 0), dtype=dt) + a_inv = inv(a) + assert a_inv.size == 0 + assert a_inv.dtype == inv(np.eye(2, dtype=dt)).dtype + + +class TestDet: + def setup_method(self): + self.rng = np.random.default_rng(1680305949878959) + + def test_1x1_all_singleton_dims(self): + a = np.array([[1]]) + deta = det(a) + assert deta.dtype.char == 'd' + assert np.isscalar(deta) + assert deta == 1. + a = np.array([[[[1]]]], dtype='f') + deta = det(a) + assert deta.dtype.char == 'd' + assert deta.shape == (1, 1) + assert_equal(deta, [[1.0]]) + a = np.array([[[1 + 3.j]]], dtype=np.complex64) + deta = det(a) + assert deta.dtype.char == 'D' + assert deta.shape == (1,) + assert_equal(deta, [1.+3.j]) + + def test_1by1_stacked_input_output(self): + a = self.rng.random([4, 5, 1, 1], dtype=np.float32) + deta = det(a) + assert deta.dtype.char == 'd' + assert deta.shape == (4, 5) + assert_allclose(deta, np.squeeze(a)) + + a = self.rng.random([4, 5, 1, 1], dtype=np.float32)*np.complex64(1.j) + deta = det(a) + assert deta.dtype.char == 'D' + assert deta.shape == (4, 5) + assert_allclose(deta, np.squeeze(a)) + + @pytest.mark.parametrize('shape', [[2, 2], [20, 20], [3, 2, 20, 20]]) + def test_simple_det_shapes_real_complex(self, shape): + a = self.rng.uniform(-1., 1., size=shape) + d1, d2 = det(a), np.linalg.det(a) + assert_allclose(d1, d2) + + b = self.rng.uniform(-1., 1., size=shape)*1j + b += self.rng.uniform(-0.5, 0.5, size=shape) + d3, d4 = det(b), np.linalg.det(b) + assert_allclose(d3, d4) + + def test_for_known_det_values(self): + # Hadamard8 + a = np.array([[1, 1, 1, 1, 1, 1, 1, 1], + [1, -1, 1, -1, 1, -1, 1, -1], + [1, 1, -1, -1, 1, 1, -1, -1], + [1, -1, -1, 1, 1, -1, -1, 1], + [1, 1, 1, 1, -1, -1, -1, -1], + [1, -1, 1, -1, -1, 1, -1, 1], + [1, 1, -1, -1, -1, -1, 1, 1], + [1, -1, -1, 1, -1, 1, 1, -1]]) + assert_allclose(det(a), 4096.) + + # consecutive number array always singular + assert_allclose(det(np.arange(25).reshape(5, 5)), 0.) + + # simple anti-diagonal block array + # Upper right has det (-2+1j) and lower right has (-2-1j) + # det(a) = - (-2+1j) (-2-1j) = 5. + a = np.array([[0.+0.j, 0.+0.j, 0.-1.j, 1.-1.j], + [0.+0.j, 0.+0.j, 1.+0.j, 0.-1.j], + [0.+1.j, 1.+1.j, 0.+0.j, 0.+0.j], + [1.+0.j, 0.+1.j, 0.+0.j, 0.+0.j]], dtype=np.complex64) + assert_allclose(det(a), 5.+0.j) + + # Fiedler companion complexified + # >>> a = scipy.linalg.fiedler_companion(np.arange(1, 10)) + a = np.array([[-2., -3., 1., 0., 0., 0., 0., 0.], + [1., 0., 0., 0., 0., 0., 0., 0.], + [0., -4., 0., -5., 1., 0., 0., 0.], + [0., 1., 0., 0., 0., 0., 0., 0.], + [0., 0., 0., -6., 0., -7., 1., 0.], + [0., 0., 0., 1., 0., 0., 0., 0.], + [0., 0., 0., 0., 0., -8., 0., -9.], + [0., 0., 0., 0., 0., 1., 0., 0.]])*1.j + assert_allclose(det(a), 9.) + + # g and G dtypes are handled differently in windows and other platforms + @pytest.mark.parametrize('typ', [x for x in np.typecodes['All'][:20] + if x not in 'gG']) + def test_sample_compatible_dtype_input(self, typ): + n = 4 + a = self.rng.random([n, n]).astype(typ) # value is not important + assert isinstance(det(a), (np.float64 | np.complex128)) + + def test_incompatible_dtype_input(self): + # Double backslashes needed for escaping pytest regex. + msg = 'cannot be cast to float\\(32, 64\\)' + + for c, t in zip('SUO', ['bytes8', 'str32', 'object']): + with assert_raises(TypeError, match=msg): + det(np.array([['a', 'b']]*2, dtype=c)) + with assert_raises(TypeError, match=msg): + det(np.array([[b'a', b'b']]*2, dtype='V')) + with assert_raises(TypeError, match=msg): + det(np.array([[100, 200]]*2, dtype='datetime64[s]')) + with assert_raises(TypeError, match=msg): + det(np.array([[100, 200]]*2, dtype='timedelta64[s]')) + + def test_empty_edge_cases(self): + assert_allclose(det(np.empty([0, 0])), 1.) + assert_allclose(det(np.empty([0, 0, 0])), np.array([])) + assert_allclose(det(np.empty([3, 0, 0])), np.array([1., 1., 1.])) + with assert_raises(ValueError, match='Last 2 dimensions'): + det(np.empty([0, 0, 3])) + with assert_raises(ValueError, match='at least two-dimensional'): + det(np.array([])) + with assert_raises(ValueError, match='Last 2 dimensions'): + det(np.array([[]])) + with assert_raises(ValueError, match='Last 2 dimensions'): + det(np.array([[[]]])) + + @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) + def test_empty_dtype(self, dt): + a = np.empty((0, 0), dtype=dt) + d = det(a) + assert d.shape == () + assert d.dtype == det(np.eye(2, dtype=dt)).dtype + + a = np.empty((3, 0, 0), dtype=dt) + d = det(a) + assert d.shape == (3,) + assert d.dtype == det(np.zeros((3, 1, 1), dtype=dt)).dtype + + def test_overwrite_a(self): + # If all conditions are met then input should be overwritten; + # - dtype is one of 'fdFD' + # - C-contiguous + # - writeable + a = np.arange(9).reshape(3, 3).astype(np.float32) + ac = a.copy() + deta = det(ac, overwrite_a=True) + assert_allclose(deta, 0.) + assert not (a == ac).all() + + def test_readonly_array(self): + a = np.array([[2., 0., 1.], [5., 3., -1.], [1., 1., 1.]]) + a.setflags(write=False) + # overwrite_a will be overridden + assert_allclose(det(a, overwrite_a=True), 10.) + + def test_simple_check_finite(self): + a = [[1, 2], [3, np.inf]] + with assert_raises(ValueError, match='array must not contain'): + det(a) + + +def direct_lstsq(a, b, cmplx=0): + at = transpose(a) + if cmplx: + at = conjugate(at) + a1 = dot(at, a) + b1 = dot(at, b) + return solve(a1, b1) + + +class TestLstsq: + lapack_drivers = ('gelsd', 'gelss', 'gelsy', None) + + def test_simple_exact(self): + for dtype in REAL_DTYPES: + a = np.array([[1, 20], [-30, 4]], dtype=dtype) + for lapack_driver in TestLstsq.lapack_drivers: + for overwrite in (True, False): + for bt in (((1, 0), (0, 1)), (1, 0), + ((2, 1), (-30, 4))): + # Store values in case they are overwritten + # later + a1 = a.copy() + b = np.array(bt, dtype=dtype) + b1 = b.copy() + out = lstsq(a1, b1, + lapack_driver=lapack_driver, + overwrite_a=overwrite, + overwrite_b=overwrite) + x = out[0] + r = out[2] + assert_(r == 2, + f'expected efficient rank 2, got {r}') + assert_allclose(dot(a, x), b, + atol=25 * _eps_cast(a1.dtype), + rtol=25 * _eps_cast(a1.dtype), + err_msg=f"driver: {lapack_driver}") + + def test_simple_overdet(self): + for dtype in REAL_DTYPES: + a = np.array([[1, 2], [4, 5], [3, 4]], dtype=dtype) + b = np.array([1, 2, 3], dtype=dtype) + for lapack_driver in TestLstsq.lapack_drivers: + for overwrite in (True, False): + # Store values in case they are overwritten later + a1 = a.copy() + b1 = b.copy() + out = lstsq(a1, b1, lapack_driver=lapack_driver, + overwrite_a=overwrite, + overwrite_b=overwrite) + x = out[0] + if lapack_driver == 'gelsy': + residuals = np.sum((b - a.dot(x))**2) + else: + residuals = out[1] + r = out[2] + assert_(r == 2, f'expected efficient rank 2, got {r}') + assert_allclose(abs((dot(a, x) - b)**2).sum(axis=0), + residuals, + rtol=25 * _eps_cast(a1.dtype), + atol=25 * _eps_cast(a1.dtype), + err_msg=f"driver: {lapack_driver}") + assert_allclose(x, (-0.428571428571429, 0.85714285714285), + rtol=25 * _eps_cast(a1.dtype), + atol=25 * _eps_cast(a1.dtype), + err_msg=f"driver: {lapack_driver}") + + def test_simple_overdet_complex(self): + for dtype in COMPLEX_DTYPES: + a = np.array([[1+2j, 2], [4, 5], [3, 4]], dtype=dtype) + b = np.array([1, 2+4j, 3], dtype=dtype) + for lapack_driver in TestLstsq.lapack_drivers: + for overwrite in (True, False): + # Store values in case they are overwritten later + a1 = a.copy() + b1 = b.copy() + out = lstsq(a1, b1, lapack_driver=lapack_driver, + overwrite_a=overwrite, + overwrite_b=overwrite) + + x = out[0] + if lapack_driver == 'gelsy': + res = b - a.dot(x) + residuals = np.sum(res * res.conj()) + else: + residuals = out[1] + r = out[2] + assert_(r == 2, f'expected efficient rank 2, got {r}') + assert_allclose(abs((dot(a, x) - b)**2).sum(axis=0), + residuals, + rtol=25 * _eps_cast(a1.dtype), + atol=25 * _eps_cast(a1.dtype), + err_msg=f"driver: {lapack_driver}") + assert_allclose( + x, (-0.4831460674157303 + 0.258426966292135j, + 0.921348314606741 + 0.292134831460674j), + rtol=25 * _eps_cast(a1.dtype), + atol=25 * _eps_cast(a1.dtype), + err_msg=f"driver: {lapack_driver}") + + def test_simple_underdet(self): + for dtype in REAL_DTYPES: + a = np.array([[1, 2, 3], [4, 5, 6]], dtype=dtype) + b = np.array([1, 2], dtype=dtype) + for lapack_driver in TestLstsq.lapack_drivers: + for overwrite in (True, False): + # Store values in case they are overwritten later + a1 = a.copy() + b1 = b.copy() + out = lstsq(a1, b1, lapack_driver=lapack_driver, + overwrite_a=overwrite, + overwrite_b=overwrite) + + x = out[0] + r = out[2] + assert_(r == 2, f'expected efficient rank 2, got {r}') + assert_allclose(x, (-0.055555555555555, 0.111111111111111, + 0.277777777777777), + rtol=25 * _eps_cast(a1.dtype), + atol=25 * _eps_cast(a1.dtype), + err_msg=f"driver: {lapack_driver}") + + @pytest.mark.parametrize("dtype", REAL_DTYPES) + @pytest.mark.parametrize("n", (20, 200)) + @pytest.mark.parametrize("lapack_driver", lapack_drivers) + @pytest.mark.parametrize("overwrite", (True, False)) + def test_random_exact(self, dtype, n, lapack_driver, overwrite): + rng = np.random.RandomState(1234) + + a = np.asarray(rng.random([n, n]), dtype=dtype) + for i in range(n): + a[i, i] = 20 * (0.1 + a[i, i]) + for i in range(4): + b = np.asarray(rng.random([n, 3]), dtype=dtype) + # Store values in case they are overwritten later + a1 = a.copy() + b1 = b.copy() + out = lstsq(a1, b1, + lapack_driver=lapack_driver, + overwrite_a=overwrite, + overwrite_b=overwrite) + x = out[0] + r = out[2] + assert_(r == n, f'expected efficient rank {n}, ' + f'got {r}') + if dtype is np.float32: + assert_allclose( + dot(a, x), b, + rtol=500 * _eps_cast(a1.dtype), + atol=500 * _eps_cast(a1.dtype), + err_msg=f"driver: {lapack_driver}") + else: + assert_allclose( + dot(a, x), b, + rtol=1000 * _eps_cast(a1.dtype), + atol=1000 * _eps_cast(a1.dtype), + err_msg=f"driver: {lapack_driver}") + + @pytest.mark.skipif(IS_MUSL, reason="may segfault on Alpine, see gh-17630") + @pytest.mark.parametrize("dtype", COMPLEX_DTYPES) + @pytest.mark.parametrize("n", (20, 200)) + @pytest.mark.parametrize("lapack_driver", lapack_drivers) + @pytest.mark.parametrize("overwrite", (True, False)) + def test_random_complex_exact(self, dtype, n, lapack_driver, overwrite): + rng = np.random.RandomState(1234) + + a = np.asarray(rng.random([n, n]) + 1j*rng.random([n, n]), + dtype=dtype) + for i in range(n): + a[i, i] = 20 * (0.1 + a[i, i]) + for i in range(2): + b = np.asarray(rng.random([n, 3]), dtype=dtype) + # Store values in case they are overwritten later + a1 = a.copy() + b1 = b.copy() + out = lstsq(a1, b1, lapack_driver=lapack_driver, + overwrite_a=overwrite, + overwrite_b=overwrite) + x = out[0] + r = out[2] + assert_(r == n, f'expected efficient rank {n}, ' + f'got {r}') + if dtype is np.complex64: + assert_allclose( + dot(a, x), b, + rtol=400 * _eps_cast(a1.dtype), + atol=400 * _eps_cast(a1.dtype), + err_msg=f"driver: {lapack_driver}") + else: + assert_allclose( + dot(a, x), b, + rtol=1000 * _eps_cast(a1.dtype), + atol=1000 * _eps_cast(a1.dtype), + err_msg=f"driver: {lapack_driver}") + + def test_random_overdet(self): + rng = np.random.RandomState(1234) + for dtype in REAL_DTYPES: + for (n, m) in ((20, 15), (200, 2)): + for lapack_driver in TestLstsq.lapack_drivers: + for overwrite in (True, False): + a = np.asarray(rng.random([n, m]), dtype=dtype) + for i in range(m): + a[i, i] = 20 * (0.1 + a[i, i]) + for i in range(4): + b = np.asarray(rng.random([n, 3]), dtype=dtype) + # Store values in case they are overwritten later + a1 = a.copy() + b1 = b.copy() + out = lstsq(a1, b1, + lapack_driver=lapack_driver, + overwrite_a=overwrite, + overwrite_b=overwrite) + x = out[0] + r = out[2] + assert_(r == m, f'expected efficient rank {m}, ' + f'got {r}') + assert_allclose( + x, direct_lstsq(a, b, cmplx=0), + rtol=25 * _eps_cast(a1.dtype), + atol=25 * _eps_cast(a1.dtype), + err_msg=f"driver: {lapack_driver}") + + def test_random_complex_overdet(self): + rng = np.random.RandomState(1234) + for dtype in COMPLEX_DTYPES: + for (n, m) in ((20, 15), (200, 2)): + for lapack_driver in TestLstsq.lapack_drivers: + for overwrite in (True, False): + a = np.asarray(rng.random([n, m]) + 1j*rng.random([n, m]), + dtype=dtype) + for i in range(m): + a[i, i] = 20 * (0.1 + a[i, i]) + for i in range(2): + b = np.asarray(rng.random([n, 3]), dtype=dtype) + # Store values in case they are overwritten + # later + a1 = a.copy() + b1 = b.copy() + out = lstsq(a1, b1, + lapack_driver=lapack_driver, + overwrite_a=overwrite, + overwrite_b=overwrite) + x = out[0] + r = out[2] + assert_(r == m, f'expected efficient rank {m}, ' + f'got {r}') + assert_allclose( + x, direct_lstsq(a, b, cmplx=1), + rtol=25 * _eps_cast(a1.dtype), + atol=25 * _eps_cast(a1.dtype), + err_msg=f"driver: {lapack_driver}") + + def test_check_finite(self): + with suppress_warnings() as sup: + # On (some) OSX this tests triggers a warning (gh-7538) + sup.filter(RuntimeWarning, + "internal gelsd driver lwork query error,.*" + "Falling back to 'gelss' driver.") + + at = np.array(((1, 20), (-30, 4))) + for dtype, bt, lapack_driver, overwrite, check_finite in \ + itertools.product(REAL_DTYPES, + (((1, 0), (0, 1)), (1, 0), ((2, 1), (-30, 4))), + TestLstsq.lapack_drivers, + (True, False), + (True, False)): + + a = at.astype(dtype) + b = np.array(bt, dtype=dtype) + # Store values in case they are overwritten + # later + a1 = a.copy() + b1 = b.copy() + out = lstsq(a1, b1, lapack_driver=lapack_driver, + check_finite=check_finite, overwrite_a=overwrite, + overwrite_b=overwrite) + x = out[0] + r = out[2] + assert_(r == 2, f'expected efficient rank 2, got {r}') + assert_allclose(dot(a, x), b, + rtol=25 * _eps_cast(a.dtype), + atol=25 * _eps_cast(a.dtype), + err_msg=f"driver: {lapack_driver}") + + def test_empty(self): + for a_shape, b_shape in (((0, 2), (0,)), + ((0, 4), (0, 2)), + ((4, 0), (4,)), + ((4, 0), (4, 2))): + b = np.ones(b_shape) + x, residues, rank, s = lstsq(np.zeros(a_shape), b) + assert_equal(x, np.zeros((a_shape[1],) + b_shape[1:])) + residues_should_be = (np.empty((0,)) if a_shape[1] + else np.linalg.norm(b, axis=0)**2) + assert_equal(residues, residues_should_be) + assert_(rank == 0, 'expected rank 0') + assert_equal(s, np.empty((0,))) + + @pytest.mark.parametrize('dt_a', [int, float, np.float32, complex, np.complex64]) + @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64]) + def test_empty_dtype(self, dt_a, dt_b): + a = np.empty((0, 0), dtype=dt_a) + b = np.empty(0, dtype=dt_b) + x, residues, rank, s = lstsq(a, b) + + assert x.size == 0 + dt_nonempty = lstsq(np.eye(2, dtype=dt_a), np.ones(2, dtype=dt_b))[0].dtype + assert x.dtype == dt_nonempty + + +class TestPinv: + def setup_method(self): + np.random.seed(1234) + + def test_simple_real(self): + a = array([[1, 2, 3], [4, 5, 6], [7, 8, 10]], dtype=float) + a_pinv = pinv(a) + assert_array_almost_equal(dot(a, a_pinv), np.eye(3)) + + def test_simple_complex(self): + a = (array([[1, 2, 3], [4, 5, 6], [7, 8, 10]], + dtype=float) + 1j * array([[10, 8, 7], [6, 5, 4], [3, 2, 1]], + dtype=float)) + a_pinv = pinv(a) + assert_array_almost_equal(dot(a, a_pinv), np.eye(3)) + + def test_simple_singular(self): + a = array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=float) + a_pinv = pinv(a) + expected = array([[-6.38888889e-01, -1.66666667e-01, 3.05555556e-01], + [-5.55555556e-02, 1.30136518e-16, 5.55555556e-02], + [5.27777778e-01, 1.66666667e-01, -1.94444444e-01]]) + assert_array_almost_equal(a_pinv, expected) + + def test_simple_cols(self): + a = array([[1, 2, 3], [4, 5, 6]], dtype=float) + a_pinv = pinv(a) + expected = array([[-0.94444444, 0.44444444], + [-0.11111111, 0.11111111], + [0.72222222, -0.22222222]]) + assert_array_almost_equal(a_pinv, expected) + + def test_simple_rows(self): + a = array([[1, 2], [3, 4], [5, 6]], dtype=float) + a_pinv = pinv(a) + expected = array([[-1.33333333, -0.33333333, 0.66666667], + [1.08333333, 0.33333333, -0.41666667]]) + assert_array_almost_equal(a_pinv, expected) + + def test_check_finite(self): + a = array([[1, 2, 3], [4, 5, 6.], [7, 8, 10]]) + a_pinv = pinv(a, check_finite=False) + assert_array_almost_equal(dot(a, a_pinv), np.eye(3)) + + def test_native_list_argument(self): + a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + a_pinv = pinv(a) + expected = array([[-6.38888889e-01, -1.66666667e-01, 3.05555556e-01], + [-5.55555556e-02, 1.30136518e-16, 5.55555556e-02], + [5.27777778e-01, 1.66666667e-01, -1.94444444e-01]]) + assert_array_almost_equal(a_pinv, expected) + + def test_atol_rtol(self): + n = 12 + # get a random ortho matrix for shuffling + q, _ = qr(np.random.rand(n, n)) + a_m = np.arange(35.0).reshape(7, 5) + a = a_m.copy() + a[0, 0] = 0.001 + atol = 1e-5 + rtol = 0.05 + # svds of a_m is ~ [116.906, 4.234, tiny, tiny, tiny] + # svds of a is ~ [116.906, 4.234, 4.62959e-04, tiny, tiny] + # Just abs cutoff such that we arrive at a_modified + a_p = pinv(a_m, atol=atol, rtol=0.) + adiff1 = a @ a_p @ a - a + adiff2 = a_m @ a_p @ a_m - a_m + # Now adiff1 should be around atol value while adiff2 should be + # relatively tiny + assert_allclose(np.linalg.norm(adiff1), 5e-4, atol=5.e-4) + assert_allclose(np.linalg.norm(adiff2), 5e-14, atol=5.e-14) + + # Now do the same but remove another sv ~4.234 via rtol + a_p = pinv(a_m, atol=atol, rtol=rtol) + adiff1 = a @ a_p @ a - a + adiff2 = a_m @ a_p @ a_m - a_m + assert_allclose(np.linalg.norm(adiff1), 4.233, rtol=0.01) + assert_allclose(np.linalg.norm(adiff2), 4.233, rtol=0.01) + + @pytest.mark.parametrize('dt', [float, np.float32, complex, np.complex64]) + def test_empty(self, dt): + a = np.empty((0, 0), dtype=dt) + a_pinv = pinv(a) + assert a_pinv.size == 0 + assert a_pinv.dtype == pinv(np.eye(2, dtype=dt)).dtype + + +class TestPinvSymmetric: + + def setup_method(self): + np.random.seed(1234) + + def test_simple_real(self): + a = array([[1, 2, 3], [4, 5, 6], [7, 8, 10]], dtype=float) + a = np.dot(a, a.T) + a_pinv = pinvh(a) + assert_array_almost_equal(np.dot(a, a_pinv), np.eye(3)) + + def test_nonpositive(self): + a = array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=float) + a = np.dot(a, a.T) + u, s, vt = np.linalg.svd(a) + s[0] *= -1 + a = np.dot(u * s, vt) # a is now symmetric non-positive and singular + a_pinv = pinv(a) + a_pinvh = pinvh(a) + assert_array_almost_equal(a_pinv, a_pinvh) + + def test_simple_complex(self): + a = (array([[1, 2, 3], [4, 5, 6], [7, 8, 10]], + dtype=float) + 1j * array([[10, 8, 7], [6, 5, 4], [3, 2, 1]], + dtype=float)) + a = np.dot(a, a.conj().T) + a_pinv = pinvh(a) + assert_array_almost_equal(np.dot(a, a_pinv), np.eye(3)) + + def test_native_list_argument(self): + a = array([[1, 2, 3], [4, 5, 6], [7, 8, 10]], dtype=float) + a = np.dot(a, a.T) + a_pinv = pinvh(a.tolist()) + assert_array_almost_equal(np.dot(a, a_pinv), np.eye(3)) + + def test_zero_eigenvalue(self): + # https://github.com/scipy/scipy/issues/12515 + # the SYEVR eigh driver may give the zero eigenvalue > eps + a = np.array([[1, -1, 0], [-1, 2, -1], [0, -1, 1]]) + p = pinvh(a) + assert_allclose(p @ a @ p, p, atol=1e-15) + assert_allclose(a @ p @ a, a, atol=1e-15) + + def test_atol_rtol(self): + n = 12 + # get a random ortho matrix for shuffling + q, _ = qr(np.random.rand(n, n)) + a = np.diag([4, 3, 2, 1, 0.99e-4, 0.99e-5] + [0.99e-6]*(n-6)) + a = q.T @ a @ q + a_m = np.diag([4, 3, 2, 1, 0.99e-4, 0.] + [0.]*(n-6)) + a_m = q.T @ a_m @ q + atol = 1e-5 + rtol = (4.01e-4 - 4e-5)/4 + # Just abs cutoff such that we arrive at a_modified + a_p = pinvh(a, atol=atol, rtol=0.) + adiff1 = a @ a_p @ a - a + adiff2 = a_m @ a_p @ a_m - a_m + # Now adiff1 should dance around atol value since truncation + # while adiff2 should be relatively tiny + assert_allclose(norm(adiff1), atol, rtol=0.1) + assert_allclose(norm(adiff2), 1e-12, atol=1e-11) + + # Now do the same but through rtol cancelling atol value + a_p = pinvh(a, atol=atol, rtol=rtol) + adiff1 = a @ a_p @ a - a + adiff2 = a_m @ a_p @ a_m - a_m + # adiff1 and adiff2 should be elevated to ~1e-4 due to mismatch + assert_allclose(norm(adiff1), 1e-4, rtol=0.1) + assert_allclose(norm(adiff2), 1e-4, rtol=0.1) + + @pytest.mark.parametrize('dt', [float, np.float32, complex, np.complex64]) + def test_empty(self, dt): + a = np.empty((0, 0), dtype=dt) + a_pinv = pinvh(a) + assert a_pinv.size == 0 + assert a_pinv.dtype == pinv(np.eye(2, dtype=dt)).dtype + + +@pytest.mark.parametrize('scale', (1e-20, 1., 1e20)) +@pytest.mark.parametrize('pinv_', (pinv, pinvh)) +def test_auto_rcond(scale, pinv_): + x = np.array([[1, 0], [0, 1e-10]]) * scale + expected = np.diag(1. / np.diag(x)) + x_inv = pinv_(x) + assert_allclose(x_inv, expected) + + +class TestVectorNorms: + + def test_types(self): + for dtype in np.typecodes['AllFloat']: + x = np.array([1, 2, 3], dtype=dtype) + tol = max(1e-15, np.finfo(dtype).eps.real * 20) + assert_allclose(norm(x), np.sqrt(14), rtol=tol) + assert_allclose(norm(x, 2), np.sqrt(14), rtol=tol) + + for dtype in np.typecodes['Complex']: + x = np.array([1j, 2j, 3j], dtype=dtype) + tol = max(1e-15, np.finfo(dtype).eps.real * 20) + assert_allclose(norm(x), np.sqrt(14), rtol=tol) + assert_allclose(norm(x, 2), np.sqrt(14), rtol=tol) + + def test_overflow(self): + # unlike numpy's norm, this one is + # safer on overflow + a = array([1e20], dtype=float32) + assert_almost_equal(norm(a), a) + + def test_stable(self): + # more stable than numpy's norm + a = array([1e4] + [1]*10000, dtype=float32) + try: + # snrm in double precision; we obtain the same as for float64 + # -- large atol needed due to varying blas implementations + assert_allclose(norm(a) - 1e4, 0.5, atol=1e-2) + except AssertionError: + # snrm implemented in single precision, == np.linalg.norm result + msg = ": Result should equal either 0.0 or 0.5 (depending on " \ + "implementation of snrm2)." + assert_almost_equal(norm(a) - 1e4, 0.0, err_msg=msg) + + def test_zero_norm(self): + assert_equal(norm([1, 0, 3], 0), 2) + assert_equal(norm([1, 2, 3], 0), 3) + + def test_axis_kwd(self): + a = np.array([[[2, 1], [3, 4]]] * 2, 'd') + assert_allclose(norm(a, axis=1), [[3.60555128, 4.12310563]] * 2) + assert_allclose(norm(a, 1, axis=1), [[5.] * 2] * 2) + + def test_keepdims_kwd(self): + a = np.array([[[2, 1], [3, 4]]] * 2, 'd') + b = norm(a, axis=1, keepdims=True) + assert_allclose(b, [[[3.60555128, 4.12310563]]] * 2) + assert_(b.shape == (2, 1, 2)) + assert_allclose(norm(a, 1, axis=2, keepdims=True), [[[3.], [7.]]] * 2) + + @pytest.mark.skipif(not HAS_ILP64, reason="64-bit BLAS required") + def test_large_vector(self): + check_free_memory(free_mb=17000) + x = np.zeros([2**31], dtype=np.float64) + x[-1] = 1 + res = norm(x) + del x + assert_allclose(res, 1.0) + + +class TestMatrixNorms: + + def test_matrix_norms(self): + # Not all of these are matrix norms in the most technical sense. + np.random.seed(1234) + for n, m in (1, 1), (1, 3), (3, 1), (4, 4), (4, 5), (5, 4): + for t in np.float32, np.float64, np.complex64, np.complex128, np.int64: + A = 10 * np.random.randn(n, m).astype(t) + if np.issubdtype(A.dtype, np.complexfloating): + A = (A + 10j * np.random.randn(n, m)).astype(t) + t_high = np.complex128 + else: + t_high = np.float64 + for order in (None, 'fro', 1, -1, 2, -2, np.inf, -np.inf): + actual = norm(A, ord=order) + desired = np.linalg.norm(A, ord=order) + # SciPy may return higher precision matrix norms. + # This is a consequence of using LAPACK. + if not np.allclose(actual, desired): + desired = np.linalg.norm(A.astype(t_high), ord=order) + assert_allclose(actual, desired) + + def test_axis_kwd(self): + a = np.array([[[2, 1], [3, 4]]] * 2, 'd') + b = norm(a, ord=np.inf, axis=(1, 0)) + c = norm(np.swapaxes(a, 0, 1), ord=np.inf, axis=(0, 1)) + d = norm(a, ord=1, axis=(0, 1)) + assert_allclose(b, c) + assert_allclose(c, d) + assert_allclose(b, d) + assert_(b.shape == c.shape == d.shape) + b = norm(a, ord=1, axis=(1, 0)) + c = norm(np.swapaxes(a, 0, 1), ord=1, axis=(0, 1)) + d = norm(a, ord=np.inf, axis=(0, 1)) + assert_allclose(b, c) + assert_allclose(c, d) + assert_allclose(b, d) + assert_(b.shape == c.shape == d.shape) + + def test_keepdims_kwd(self): + a = np.arange(120, dtype='d').reshape(2, 3, 4, 5) + b = norm(a, ord=np.inf, axis=(1, 0), keepdims=True) + c = norm(a, ord=1, axis=(0, 1), keepdims=True) + assert_allclose(b, c) + assert_(b.shape == c.shape) + + def test_empty(self): + a = np.empty((0, 0)) + assert_allclose(norm(a), 0.) + assert_allclose(norm(a, axis=0), np.zeros((0,))) + assert_allclose(norm(a, keepdims=True), np.zeros((1, 1))) + + a = np.empty((0, 3)) + assert_allclose(norm(a), 0.) + assert_allclose(norm(a, axis=0), np.zeros((3,))) + assert_allclose(norm(a, keepdims=True), np.zeros((1, 1))) + + +class TestOverwrite: + def test_solve(self): + assert_no_overwrite(solve, [(3, 3), (3,)]) + + def test_solve_triangular(self): + assert_no_overwrite(solve_triangular, [(3, 3), (3,)]) + + def test_solve_banded(self): + assert_no_overwrite(lambda ab, b: solve_banded((2, 1), ab, b), + [(4, 6), (6,)]) + + def test_solveh_banded(self): + assert_no_overwrite(solveh_banded, [(2, 6), (6,)]) + + def test_inv(self): + assert_no_overwrite(inv, [(3, 3)]) + + def test_det(self): + assert_no_overwrite(det, [(3, 3)]) + + def test_lstsq(self): + assert_no_overwrite(lstsq, [(3, 2), (3,)]) + + def test_pinv(self): + assert_no_overwrite(pinv, [(3, 3)]) + + def test_pinvh(self): + assert_no_overwrite(pinvh, [(3, 3)]) + + +class TestSolveCirculant: + + def test_basic1(self): + c = np.array([1, 2, 3, 5]) + b = np.array([1, -1, 1, 0]) + x = solve_circulant(c, b) + y = solve(circulant(c), b) + assert_allclose(x, y) + + def test_basic2(self): + # b is a 2-d matrix. + c = np.array([1, 2, -3, -5]) + b = np.arange(12).reshape(4, 3) + x = solve_circulant(c, b) + y = solve(circulant(c), b) + assert_allclose(x, y) + + def test_basic3(self): + # b is a 3-d matrix. + c = np.array([1, 2, -3, -5]) + b = np.arange(24).reshape(4, 3, 2) + x = solve_circulant(c, b) + y = solve(circulant(c), b) + assert_allclose(x, y) + + def test_complex(self): + # Complex b and c + c = np.array([1+2j, -3, 4j, 5]) + b = np.arange(8).reshape(4, 2) + 0.5j + x = solve_circulant(c, b) + y = solve(circulant(c), b) + assert_allclose(x, y) + + def test_random_b_and_c(self): + # Random b and c + rng = np.random.RandomState(54321) + c = rng.randn(50) + b = rng.randn(50) + x = solve_circulant(c, b) + y = solve(circulant(c), b) + assert_allclose(x, y) + + def test_singular(self): + # c gives a singular circulant matrix. + c = np.array([1, 1, 0, 0]) + b = np.array([1, 2, 3, 4]) + x = solve_circulant(c, b, singular='lstsq') + y, res, rnk, s = lstsq(circulant(c), b) + assert_allclose(x, y) + assert_raises(LinAlgError, solve_circulant, x, y) + + def test_axis_args(self): + # Test use of caxis, baxis and outaxis. + + # c has shape (2, 1, 4) + c = np.array([[[-1, 2.5, 3, 3.5]], [[1, 6, 6, 6.5]]]) + + # b has shape (3, 4) + b = np.array([[0, 0, 1, 1], [1, 1, 0, 0], [1, -1, 0, 0]]) + + x = solve_circulant(c, b, baxis=1) + assert_equal(x.shape, (4, 2, 3)) + expected = np.empty_like(x) + expected[:, 0, :] = solve(circulant(c[0].ravel()), b.T) + expected[:, 1, :] = solve(circulant(c[1].ravel()), b.T) + assert_allclose(x, expected) + + x = solve_circulant(c, b, baxis=1, outaxis=-1) + assert_equal(x.shape, (2, 3, 4)) + assert_allclose(np.moveaxis(x, -1, 0), expected) + + # np.swapaxes(c, 1, 2) has shape (2, 4, 1); b.T has shape (4, 3). + x = solve_circulant(np.swapaxes(c, 1, 2), b.T, caxis=1) + assert_equal(x.shape, (4, 2, 3)) + assert_allclose(x, expected) + + def test_native_list_arguments(self): + # Same as test_basic1 using python's native list. + c = [1, 2, 3, 5] + b = [1, -1, 1, 0] + x = solve_circulant(c, b) + y = solve(circulant(c), b) + assert_allclose(x, y) + + @pytest.mark.parametrize('dt_c', [int, float, np.float32, complex, np.complex64]) + @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64]) + def test_empty(self, dt_c, dt_b): + c = np.array([], dtype=dt_c) + b = np.array([], dtype=dt_b) + x = solve_circulant(c, b) + assert x.shape == (0,) + assert x.dtype == solve_circulant(np.arange(3, dtype=dt_c), + np.ones(3, dtype=dt_b)).dtype + + b = np.empty((0, 0), dtype=dt_b) + x1 = solve_circulant(c, b) + assert x1.shape == (0, 0) + assert x1.dtype == x.dtype + + +class TestMatrix_Balance: + + def test_string_arg(self): + assert_raises(ValueError, matrix_balance, 'Some string for fail') + + def test_infnan_arg(self): + assert_raises(ValueError, matrix_balance, + np.array([[1, 2], [3, np.inf]])) + assert_raises(ValueError, matrix_balance, + np.array([[1, 2], [3, np.nan]])) + + def test_scaling(self): + _, y = matrix_balance(np.array([[1000, 1], [1000, 0]])) + # Pre/post LAPACK 3.5.0 gives the same result up to an offset + # since in each case col norm is x1000 greater and + # 1000 / 32 ~= 1 * 32 hence balanced with 2 ** 5. + assert_allclose(np.diff(np.log2(np.diag(y))), [5]) + + def test_scaling_order(self): + A = np.array([[1, 0, 1e-4], [1, 1, 1e-2], [1e4, 1e2, 1]]) + x, y = matrix_balance(A) + assert_allclose(solve(y, A).dot(y), x) + + def test_separate(self): + _, (y, z) = matrix_balance(np.array([[1000, 1], [1000, 0]]), + separate=1) + assert_equal(np.diff(np.log2(y)), [5]) + assert_allclose(z, np.arange(2)) + + def test_permutation(self): + A = block_diag(np.ones((2, 2)), np.tril(np.ones((2, 2))), + np.ones((3, 3))) + x, (y, z) = matrix_balance(A, separate=1) + assert_allclose(y, np.ones_like(y)) + assert_allclose(z, np.array([0, 1, 6, 5, 4, 3, 2])) + + def test_perm_and_scaling(self): + # Matrix with its diagonal removed + cases = ( # Case 0 + np.array([[0., 0., 0., 0., 0.000002], + [0., 0., 0., 0., 0.], + [2., 2., 0., 0., 0.], + [2., 2., 0., 0., 0.], + [0., 0., 0.000002, 0., 0.]]), + # Case 1 user reported GH-7258 + np.array([[-0.5, 0., 0., 0.], + [0., -1., 0., 0.], + [1., 0., -0.5, 0.], + [0., 1., 0., -1.]]), + # Case 2 user reported GH-7258 + np.array([[-3., 0., 1., 0.], + [-1., -1., -0., 1.], + [-3., -0., -0., 0.], + [-1., -0., 1., -1.]]) + ) + + for A in cases: + x, y = matrix_balance(A) + x, (s, p) = matrix_balance(A, separate=1) + ip = np.empty_like(p) + ip[p] = np.arange(A.shape[0]) + assert_allclose(y, np.diag(s)[ip, :]) + assert_allclose(solve(y, A).dot(y), x) + + @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) + def test_empty(self, dt): + a = np.empty((0, 0), dtype=dt) + b, t = matrix_balance(a) + + assert b.size == 0 + assert t.size == 0 + + b_n, t_n = matrix_balance(np.eye(2, dtype=dt)) + assert b.dtype == b_n.dtype + assert t.dtype == t_n.dtype + + b, (scale, perm) = matrix_balance(a, separate=True) + assert b.size == 0 + assert scale.size == 0 + assert perm.size == 0 + + b_n, (scale_n, perm_n) = matrix_balance(a, separate=True) + assert b.dtype == b_n.dtype + assert scale.dtype == scale_n.dtype + assert perm.dtype == perm_n.dtype diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_blas.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_blas.py new file mode 100644 index 0000000000000000000000000000000000000000..b6645d0ad5d967ca00a2a5193d51e7ee74b8ad73 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_blas.py @@ -0,0 +1,1127 @@ +# +# Created by: Pearu Peterson, April 2002 +# + +import math +import pytest +import numpy as np +import numpy.random +from numpy.testing import (assert_equal, assert_almost_equal, assert_, + assert_array_almost_equal, assert_allclose) +from pytest import raises as assert_raises + +from numpy import float32, float64, complex64, complex128, arange, triu, \ + tril, zeros, tril_indices, ones, mod, diag, append, eye, \ + nonzero + +import scipy +from scipy.linalg import _fblas as fblas, get_blas_funcs, toeplitz, solve + +try: + from scipy.linalg import _cblas as cblas +except ImportError: + cblas = None + +REAL_DTYPES = [float32, float64] +COMPLEX_DTYPES = [complex64, complex128] +DTYPES = REAL_DTYPES + COMPLEX_DTYPES + + +def test_get_blas_funcs(): + # check that it returns Fortran code for arrays that are + # fortran-ordered + f1, f2, f3 = get_blas_funcs( + ('axpy', 'axpy', 'axpy'), + (np.empty((2, 2), dtype=np.complex64, order='F'), + np.empty((2, 2), dtype=np.complex128, order='C')) + ) + + # get_blas_funcs will choose libraries depending on most generic + # array + assert_equal(f1.typecode, 'z') + assert_equal(f2.typecode, 'z') + if cblas is not None: + assert_equal(f1.module_name, 'cblas') + assert_equal(f2.module_name, 'cblas') + + # check defaults. + f1 = get_blas_funcs('rotg') + assert_equal(f1.typecode, 'd') + + # check also dtype interface + f1 = get_blas_funcs('gemm', dtype=np.complex64) + assert_equal(f1.typecode, 'c') + f1 = get_blas_funcs('gemm', dtype='F') + assert_equal(f1.typecode, 'c') + + # extended precision complex + f1 = get_blas_funcs('gemm', dtype=np.clongdouble) + assert_equal(f1.typecode, 'z') + + # check safe complex upcasting + f1 = get_blas_funcs('axpy', + (np.empty((2, 2), dtype=np.float64), + np.empty((2, 2), dtype=np.complex64)) + ) + assert_equal(f1.typecode, 'z') + + +def test_get_blas_funcs_alias(): + # check alias for get_blas_funcs + f, g = get_blas_funcs(('nrm2', 'dot'), dtype=np.complex64) + assert f.typecode == 'c' + assert g.typecode == 'c' + + f, g, h = get_blas_funcs(('dot', 'dotc', 'dotu'), dtype=np.float64) + assert f is g + assert f is h + + +class TestCBLAS1Simple: + + def test_axpy(self): + for p in 'sd': + f = getattr(cblas, p+'axpy', None) + if f is None: + continue + assert_array_almost_equal(f([1, 2, 3], [2, -1, 3], a=5), + [7, 9, 18]) + for p in 'cz': + f = getattr(cblas, p+'axpy', None) + if f is None: + continue + assert_array_almost_equal(f([1, 2j, 3], [2, -1, 3], a=5), + [7, 10j-1, 18]) + + +class TestFBLAS1Simple: + + def test_axpy(self): + for p in 'sd': + f = getattr(fblas, p+'axpy', None) + if f is None: + continue + assert_array_almost_equal(f([1, 2, 3], [2, -1, 3], a=5), + [7, 9, 18]) + for p in 'cz': + f = getattr(fblas, p+'axpy', None) + if f is None: + continue + assert_array_almost_equal(f([1, 2j, 3], [2, -1, 3], a=5), + [7, 10j-1, 18]) + + def test_copy(self): + for p in 'sd': + f = getattr(fblas, p+'copy', None) + if f is None: + continue + assert_array_almost_equal(f([3, 4, 5], [8]*3), [3, 4, 5]) + for p in 'cz': + f = getattr(fblas, p+'copy', None) + if f is None: + continue + assert_array_almost_equal(f([3, 4j, 5+3j], [8]*3), [3, 4j, 5+3j]) + + def test_asum(self): + for p in 'sd': + f = getattr(fblas, p+'asum', None) + if f is None: + continue + assert_almost_equal(f([3, -4, 5]), 12) + for p in ['sc', 'dz']: + f = getattr(fblas, p+'asum', None) + if f is None: + continue + assert_almost_equal(f([3j, -4, 3-4j]), 14) + + def test_dot(self): + for p in 'sd': + f = getattr(fblas, p+'dot', None) + if f is None: + continue + assert_almost_equal(f([3, -4, 5], [2, 5, 1]), -9) + + def test_complex_dotu(self): + for p in 'cz': + f = getattr(fblas, p+'dotu', None) + if f is None: + continue + assert_almost_equal(f([3j, -4, 3-4j], [2, 3, 1]), -9+2j) + + def test_complex_dotc(self): + for p in 'cz': + f = getattr(fblas, p+'dotc', None) + if f is None: + continue + assert_almost_equal(f([3j, -4, 3-4j], [2, 3j, 1]), 3-14j) + + def test_nrm2(self): + for p in 'sd': + f = getattr(fblas, p+'nrm2', None) + if f is None: + continue + assert_almost_equal(f([3, -4, 5]), math.sqrt(50)) + for p in ['c', 'z', 'sc', 'dz']: + f = getattr(fblas, p+'nrm2', None) + if f is None: + continue + assert_almost_equal(f([3j, -4, 3-4j]), math.sqrt(50)) + + def test_scal(self): + for p in 'sd': + f = getattr(fblas, p+'scal', None) + if f is None: + continue + assert_array_almost_equal(f(2, [3, -4, 5]), [6, -8, 10]) + for p in 'cz': + f = getattr(fblas, p+'scal', None) + if f is None: + continue + assert_array_almost_equal(f(3j, [3j, -4, 3-4j]), [-9, -12j, 12+9j]) + for p in ['cs', 'zd']: + f = getattr(fblas, p+'scal', None) + if f is None: + continue + assert_array_almost_equal(f(3, [3j, -4, 3-4j]), [9j, -12, 9-12j]) + + def test_swap(self): + for p in 'sd': + f = getattr(fblas, p+'swap', None) + if f is None: + continue + x, y = [2, 3, 1], [-2, 3, 7] + x1, y1 = f(x, y) + assert_array_almost_equal(x1, y) + assert_array_almost_equal(y1, x) + for p in 'cz': + f = getattr(fblas, p+'swap', None) + if f is None: + continue + x, y = [2, 3j, 1], [-2, 3, 7-3j] + x1, y1 = f(x, y) + assert_array_almost_equal(x1, y) + assert_array_almost_equal(y1, x) + + def test_amax(self): + for p in 'sd': + f = getattr(fblas, 'i'+p+'amax') + assert_equal(f([-2, 4, 3]), 1) + for p in 'cz': + f = getattr(fblas, 'i'+p+'amax') + assert_equal(f([-5, 4+3j, 6]), 1) + # XXX: need tests for rot,rotm,rotg,rotmg + + +class TestFBLAS2Simple: + + def test_gemv(self): + for p in 'sd': + f = getattr(fblas, p+'gemv', None) + if f is None: + continue + assert_array_almost_equal(f(3, [[3]], [-4]), [-36]) + assert_array_almost_equal(f(3, [[3]], [-4], 3, [5]), [-21]) + for p in 'cz': + f = getattr(fblas, p+'gemv', None) + if f is None: + continue + assert_array_almost_equal(f(3j, [[3-4j]], [-4]), [-48-36j]) + assert_array_almost_equal(f(3j, [[3-4j]], [-4], 3, [5j]), + [-48-21j]) + + # All of these *ger* functions are segfaulting when called from multiple + # threads under free-threaded CPython, see gh-21936. + @pytest.mark.thread_unsafe + def test_ger(self): + + for p in 'sd': + f = getattr(fblas, p+'ger', None) + if f is None: + continue + assert_array_almost_equal(f(1, [1, 2], [3, 4]), [[3, 4], [6, 8]]) + assert_array_almost_equal(f(2, [1, 2, 3], [3, 4]), + [[6, 8], [12, 16], [18, 24]]) + + assert_array_almost_equal(f(1, [1, 2], [3, 4], + a=[[1, 2], [3, 4]]), [[4, 6], [9, 12]]) + + for p in 'cz': + f = getattr(fblas, p+'geru', None) + if f is None: + continue + assert_array_almost_equal(f(1, [1j, 2], [3, 4]), + [[3j, 4j], [6, 8]]) + assert_array_almost_equal(f(-2, [1j, 2j, 3j], [3j, 4j]), + [[6, 8], [12, 16], [18, 24]]) + + for p in 'cz': + for name in ('ger', 'gerc'): + f = getattr(fblas, p+name, None) + if f is None: + continue + assert_array_almost_equal(f(1, [1j, 2], [3, 4]), + [[3j, 4j], [6, 8]]) + assert_array_almost_equal(f(2, [1j, 2j, 3j], [3j, 4j]), + [[6, 8], [12, 16], [18, 24]]) + + def test_syr_her(self): + x = np.arange(1, 5, dtype='d') + resx = np.triu(x[:, np.newaxis] * x) + resx_reverse = np.triu(x[::-1, np.newaxis] * x[::-1]) + + y = np.linspace(0, 8.5, 17, endpoint=False) + + z = np.arange(1, 9, dtype='d').view('D') + resz = np.triu(z[:, np.newaxis] * z) + resz_reverse = np.triu(z[::-1, np.newaxis] * z[::-1]) + rehz = np.triu(z[:, np.newaxis] * z.conj()) + rehz_reverse = np.triu(z[::-1, np.newaxis] * z[::-1].conj()) + + w = np.c_[np.zeros(4), z, np.zeros(4)].ravel() + + for p, rtol in zip('sd', [1e-7, 1e-14]): + f = getattr(fblas, p+'syr', None) + if f is None: + continue + assert_allclose(f(1.0, x), resx, rtol=rtol) + assert_allclose(f(1.0, x, lower=True), resx.T, rtol=rtol) + assert_allclose(f(1.0, y, incx=2, offx=2, n=4), resx, rtol=rtol) + # negative increments imply reversed vectors in blas + assert_allclose(f(1.0, y, incx=-2, offx=2, n=4), + resx_reverse, rtol=rtol) + + a = np.zeros((4, 4), 'f' if p == 's' else 'd', 'F') + b = f(1.0, x, a=a, overwrite_a=True) + assert_allclose(a, resx, rtol=rtol) + + b = f(2.0, x, a=a) + assert_(a is not b) + assert_allclose(b, 3*resx, rtol=rtol) + + assert_raises(Exception, f, 1.0, x, incx=0) + assert_raises(Exception, f, 1.0, x, offx=5) + assert_raises(Exception, f, 1.0, x, offx=-2) + assert_raises(Exception, f, 1.0, x, n=-2) + assert_raises(Exception, f, 1.0, x, n=5) + assert_raises(Exception, f, 1.0, x, lower=2) + assert_raises(Exception, f, 1.0, x, a=np.zeros((2, 2), 'd', 'F')) + + for p, rtol in zip('cz', [1e-7, 1e-14]): + f = getattr(fblas, p+'syr', None) + if f is None: + continue + assert_allclose(f(1.0, z), resz, rtol=rtol) + assert_allclose(f(1.0, z, lower=True), resz.T, rtol=rtol) + assert_allclose(f(1.0, w, incx=3, offx=1, n=4), resz, rtol=rtol) + # negative increments imply reversed vectors in blas + assert_allclose(f(1.0, w, incx=-3, offx=1, n=4), + resz_reverse, rtol=rtol) + + a = np.zeros((4, 4), 'F' if p == 'c' else 'D', 'F') + b = f(1.0, z, a=a, overwrite_a=True) + assert_allclose(a, resz, rtol=rtol) + + b = f(2.0, z, a=a) + assert_(a is not b) + assert_allclose(b, 3*resz, rtol=rtol) + + assert_raises(Exception, f, 1.0, x, incx=0) + assert_raises(Exception, f, 1.0, x, offx=5) + assert_raises(Exception, f, 1.0, x, offx=-2) + assert_raises(Exception, f, 1.0, x, n=-2) + assert_raises(Exception, f, 1.0, x, n=5) + assert_raises(Exception, f, 1.0, x, lower=2) + assert_raises(Exception, f, 1.0, x, a=np.zeros((2, 2), 'd', 'F')) + + for p, rtol in zip('cz', [1e-7, 1e-14]): + f = getattr(fblas, p+'her', None) + if f is None: + continue + assert_allclose(f(1.0, z), rehz, rtol=rtol) + assert_allclose(f(1.0, z, lower=True), rehz.T.conj(), rtol=rtol) + assert_allclose(f(1.0, w, incx=3, offx=1, n=4), rehz, rtol=rtol) + # negative increments imply reversed vectors in blas + assert_allclose(f(1.0, w, incx=-3, offx=1, n=4), + rehz_reverse, rtol=rtol) + + a = np.zeros((4, 4), 'F' if p == 'c' else 'D', 'F') + b = f(1.0, z, a=a, overwrite_a=True) + assert_allclose(a, rehz, rtol=rtol) + + b = f(2.0, z, a=a) + assert_(a is not b) + assert_allclose(b, 3*rehz, rtol=rtol) + + assert_raises(Exception, f, 1.0, x, incx=0) + assert_raises(Exception, f, 1.0, x, offx=5) + assert_raises(Exception, f, 1.0, x, offx=-2) + assert_raises(Exception, f, 1.0, x, n=-2) + assert_raises(Exception, f, 1.0, x, n=5) + assert_raises(Exception, f, 1.0, x, lower=2) + assert_raises(Exception, f, 1.0, x, a=np.zeros((2, 2), 'd', 'F')) + + def test_syr2(self): + x = np.arange(1, 5, dtype='d') + y = np.arange(5, 9, dtype='d') + resxy = np.triu(x[:, np.newaxis] * y + y[:, np.newaxis] * x) + resxy_reverse = np.triu(x[::-1, np.newaxis] * y[::-1] + + y[::-1, np.newaxis] * x[::-1]) + + q = np.linspace(0, 8.5, 17, endpoint=False) + + for p, rtol in zip('sd', [1e-7, 1e-14]): + f = getattr(fblas, p+'syr2', None) + if f is None: + continue + assert_allclose(f(1.0, x, y), resxy, rtol=rtol) + assert_allclose(f(1.0, x, y, n=3), resxy[:3, :3], rtol=rtol) + assert_allclose(f(1.0, x, y, lower=True), resxy.T, rtol=rtol) + + assert_allclose(f(1.0, q, q, incx=2, offx=2, incy=2, offy=10), + resxy, rtol=rtol) + assert_allclose(f(1.0, q, q, incx=2, offx=2, incy=2, offy=10, n=3), + resxy[:3, :3], rtol=rtol) + # negative increments imply reversed vectors in blas + assert_allclose(f(1.0, q, q, incx=-2, offx=2, incy=-2, offy=10), + resxy_reverse, rtol=rtol) + + a = np.zeros((4, 4), 'f' if p == 's' else 'd', 'F') + b = f(1.0, x, y, a=a, overwrite_a=True) + assert_allclose(a, resxy, rtol=rtol) + + b = f(2.0, x, y, a=a) + assert_(a is not b) + assert_allclose(b, 3*resxy, rtol=rtol) + + assert_raises(Exception, f, 1.0, x, y, incx=0) + assert_raises(Exception, f, 1.0, x, y, offx=5) + assert_raises(Exception, f, 1.0, x, y, offx=-2) + assert_raises(Exception, f, 1.0, x, y, incy=0) + assert_raises(Exception, f, 1.0, x, y, offy=5) + assert_raises(Exception, f, 1.0, x, y, offy=-2) + assert_raises(Exception, f, 1.0, x, y, n=-2) + assert_raises(Exception, f, 1.0, x, y, n=5) + assert_raises(Exception, f, 1.0, x, y, lower=2) + assert_raises(Exception, f, 1.0, x, y, + a=np.zeros((2, 2), 'd', 'F')) + + def test_her2(self): + x = np.arange(1, 9, dtype='d').view('D') + y = np.arange(9, 17, dtype='d').view('D') + resxy = x[:, np.newaxis] * y.conj() + y[:, np.newaxis] * x.conj() + resxy = np.triu(resxy) + + resxy_reverse = x[::-1, np.newaxis] * y[::-1].conj() + resxy_reverse += y[::-1, np.newaxis] * x[::-1].conj() + resxy_reverse = np.triu(resxy_reverse) + + u = np.c_[np.zeros(4), x, np.zeros(4)].ravel() + v = np.c_[np.zeros(4), y, np.zeros(4)].ravel() + + for p, rtol in zip('cz', [1e-7, 1e-14]): + f = getattr(fblas, p+'her2', None) + if f is None: + continue + assert_allclose(f(1.0, x, y), resxy, rtol=rtol) + assert_allclose(f(1.0, x, y, n=3), resxy[:3, :3], rtol=rtol) + assert_allclose(f(1.0, x, y, lower=True), resxy.T.conj(), + rtol=rtol) + + assert_allclose(f(1.0, u, v, incx=3, offx=1, incy=3, offy=1), + resxy, rtol=rtol) + assert_allclose(f(1.0, u, v, incx=3, offx=1, incy=3, offy=1, n=3), + resxy[:3, :3], rtol=rtol) + # negative increments imply reversed vectors in blas + assert_allclose(f(1.0, u, v, incx=-3, offx=1, incy=-3, offy=1), + resxy_reverse, rtol=rtol) + + a = np.zeros((4, 4), 'F' if p == 'c' else 'D', 'F') + b = f(1.0, x, y, a=a, overwrite_a=True) + assert_allclose(a, resxy, rtol=rtol) + + b = f(2.0, x, y, a=a) + assert_(a is not b) + assert_allclose(b, 3*resxy, rtol=rtol) + + assert_raises(Exception, f, 1.0, x, y, incx=0) + assert_raises(Exception, f, 1.0, x, y, offx=5) + assert_raises(Exception, f, 1.0, x, y, offx=-2) + assert_raises(Exception, f, 1.0, x, y, incy=0) + assert_raises(Exception, f, 1.0, x, y, offy=5) + assert_raises(Exception, f, 1.0, x, y, offy=-2) + assert_raises(Exception, f, 1.0, x, y, n=-2) + assert_raises(Exception, f, 1.0, x, y, n=5) + assert_raises(Exception, f, 1.0, x, y, lower=2) + assert_raises(Exception, f, 1.0, x, y, + a=np.zeros((2, 2), 'd', 'F')) + + def test_gbmv(self): + rng = np.random.default_rng(1234) + for ind, dtype in enumerate(DTYPES): + n = 7 + m = 5 + kl = 1 + ku = 2 + # fake a banded matrix via toeplitz + A = toeplitz(append(rng.random(kl+1), zeros(m-kl-1)), + append(rng.random(ku+1), zeros(n-ku-1))) + A = A.astype(dtype) + Ab = zeros((kl+ku+1, n), dtype=dtype) + + # Form the banded storage + Ab[2, :5] = A[0, 0] # diag + Ab[1, 1:6] = A[0, 1] # sup1 + Ab[0, 2:7] = A[0, 2] # sup2 + Ab[3, :4] = A[1, 0] # sub1 + + x = rng.random(n).astype(dtype) + y = rng.random(m).astype(dtype) + alpha, beta = dtype(3), dtype(-5) + + func, = get_blas_funcs(('gbmv',), dtype=dtype) + y1 = func(m=m, n=n, ku=ku, kl=kl, alpha=alpha, a=Ab, + x=x, y=y, beta=beta) + y2 = alpha * A.dot(x) + beta * y + assert_array_almost_equal(y1, y2) + + y1 = func(m=m, n=n, ku=ku, kl=kl, alpha=alpha, a=Ab, + x=y, y=x, beta=beta, trans=1) + y2 = alpha * A.T.dot(y) + beta * x + assert_array_almost_equal(y1, y2) + + def test_sbmv_hbmv(self): + rng = np.random.default_rng(1234) + for ind, dtype in enumerate(DTYPES): + n = 6 + k = 2 + A = zeros((n, n), dtype=dtype) + Ab = zeros((k+1, n), dtype=dtype) + + # Form the array and its packed banded storage + A[arange(n), arange(n)] = rng.random(n) + for ind2 in range(1, k+1): + temp = rng.random(n-ind2) + A[arange(n-ind2), arange(ind2, n)] = temp + Ab[-1-ind2, ind2:] = temp + A = A.astype(dtype) + A = A + A.T if ind < 2 else A + A.conj().T + Ab[-1, :] = diag(A) + x = rng.random(n).astype(dtype) + y = rng.random(n).astype(dtype) + alpha, beta = dtype(1.25), dtype(3) + + if ind > 1: + func, = get_blas_funcs(('hbmv',), dtype=dtype) + else: + func, = get_blas_funcs(('sbmv',), dtype=dtype) + y1 = func(k=k, alpha=alpha, a=Ab, x=x, y=y, beta=beta) + y2 = alpha * A.dot(x) + beta * y + assert_array_almost_equal(y1, y2) + + def test_spmv_hpmv(self): + rng = np.random.default_rng(12345698) + for ind, dtype in enumerate(DTYPES+COMPLEX_DTYPES): + n = 3 + A = rng.random((n, n)).astype(dtype) + if ind > 1: + A += rng.random((n, n))*1j + A = A.astype(dtype) + A = A + A.T if ind < 4 else A + A.conj().T + c, r = tril_indices(n) + Ap = A[r, c] + x = rng.random(n).astype(dtype) + y = rng.random(n).astype(dtype) + xlong = arange(2*n).astype(dtype) + ylong = ones(2*n).astype(dtype) + alpha, beta = dtype(1.25), dtype(2) + + if ind > 3: + func, = get_blas_funcs(('hpmv',), dtype=dtype) + else: + func, = get_blas_funcs(('spmv',), dtype=dtype) + y1 = func(n=n, alpha=alpha, ap=Ap, x=x, y=y, beta=beta) + y2 = alpha * A.dot(x) + beta * y + assert_array_almost_equal(y1, y2) + + # Test inc and offsets + y1 = func(n=n-1, alpha=alpha, beta=beta, x=xlong, y=ylong, ap=Ap, + incx=2, incy=2, offx=n, offy=n) + y2 = (alpha * A[:-1, :-1]).dot(xlong[3::2]) + beta * ylong[3::2] + assert_array_almost_equal(y1[3::2], y2) + assert_almost_equal(y1[4], ylong[4]) + + def test_spr_hpr(self): + rng = np.random.default_rng(1234) + for ind, dtype in enumerate(DTYPES+COMPLEX_DTYPES): + n = 3 + A = rng.random((n, n)).astype(dtype) + if ind > 1: + A += rng.random((n, n))*1j + A = A.astype(dtype) + A = A + A.T if ind < 4 else A + A.conj().T + c, r = tril_indices(n) + Ap = A[r, c] + x = rng.random(n).astype(dtype) + alpha = (DTYPES+COMPLEX_DTYPES)[mod(ind, 4)](2.5) + + if ind > 3: + func, = get_blas_funcs(('hpr',), dtype=dtype) + y2 = alpha * x[:, None].dot(x[None, :].conj()) + A + else: + func, = get_blas_funcs(('spr',), dtype=dtype) + y2 = alpha * x[:, None].dot(x[None, :]) + A + + y1 = func(n=n, alpha=alpha, ap=Ap, x=x) + y1f = zeros((3, 3), dtype=dtype) + y1f[r, c] = y1 + y1f[c, r] = y1.conj() if ind > 3 else y1 + assert_array_almost_equal(y1f, y2) + + def test_spr2_hpr2(self): + rng = np.random.default_rng(1234) + for ind, dtype in enumerate(DTYPES): + n = 3 + A = rng.random((n, n)).astype(dtype) + if ind > 1: + A += rng.random((n, n))*1j + A = A.astype(dtype) + A = A + A.T if ind < 2 else A + A.conj().T + c, r = tril_indices(n) + Ap = A[r, c] + x = rng.random(n).astype(dtype) + y = rng.random(n).astype(dtype) + alpha = dtype(2) + + if ind > 1: + func, = get_blas_funcs(('hpr2',), dtype=dtype) + else: + func, = get_blas_funcs(('spr2',), dtype=dtype) + + u = alpha.conj() * x[:, None].dot(y[None, :].conj()) + y2 = A + u + u.conj().T + y1 = func(n=n, alpha=alpha, x=x, y=y, ap=Ap) + y1f = zeros((3, 3), dtype=dtype) + y1f[r, c] = y1 + y1f[[1, 2, 2], [0, 0, 1]] = y1[[1, 3, 4]].conj() + assert_array_almost_equal(y1f, y2) + + def test_tbmv(self): + rng = np.random.default_rng(1234) + for ind, dtype in enumerate(DTYPES): + n = 10 + k = 3 + x = rng.random(n).astype(dtype) + A = zeros((n, n), dtype=dtype) + # Banded upper triangular array + for sup in range(k+1): + A[arange(n-sup), arange(sup, n)] = rng.random(n-sup) + + # Add complex parts for c,z + if ind > 1: + A[nonzero(A)] += 1j * rng.random((k+1)*n-(k*(k+1)//2)).astype(dtype) + + # Form the banded storage + Ab = zeros((k+1, n), dtype=dtype) + for row in range(k+1): + Ab[-row-1, row:] = diag(A, k=row) + func, = get_blas_funcs(('tbmv',), dtype=dtype) + + y1 = func(k=k, a=Ab, x=x) + y2 = A.dot(x) + assert_array_almost_equal(y1, y2) + + y1 = func(k=k, a=Ab, x=x, diag=1) + A[arange(n), arange(n)] = dtype(1) + y2 = A.dot(x) + assert_array_almost_equal(y1, y2) + + y1 = func(k=k, a=Ab, x=x, diag=1, trans=1) + y2 = A.T.dot(x) + assert_array_almost_equal(y1, y2) + + y1 = func(k=k, a=Ab, x=x, diag=1, trans=2) + y2 = A.conj().T.dot(x) + assert_array_almost_equal(y1, y2) + + def test_tbsv(self): + rng = np.random.default_rng(1234) + for ind, dtype in enumerate(DTYPES): + n = 6 + k = 3 + x = rng.random(n).astype(dtype) + A = zeros((n, n), dtype=dtype) + # Banded upper triangular array + for sup in range(k+1): + A[arange(n-sup), arange(sup, n)] = rng.random(n-sup) + + # Add complex parts for c,z + if ind > 1: + A[nonzero(A)] += 1j * rng.random((k+1)*n-(k*(k+1)//2)).astype(dtype) + + # Form the banded storage + Ab = zeros((k+1, n), dtype=dtype) + for row in range(k+1): + Ab[-row-1, row:] = diag(A, k=row) + func, = get_blas_funcs(('tbsv',), dtype=dtype) + + y1 = func(k=k, a=Ab, x=x) + y2 = solve(A, x) + assert_array_almost_equal(y1, y2) + + y1 = func(k=k, a=Ab, x=x, diag=1) + A[arange(n), arange(n)] = dtype(1) + y2 = solve(A, x) + assert_array_almost_equal(y1, y2) + + y1 = func(k=k, a=Ab, x=x, diag=1, trans=1) + y2 = solve(A.T, x) + assert_array_almost_equal(y1, y2) + + y1 = func(k=k, a=Ab, x=x, diag=1, trans=2) + y2 = solve(A.conj().T, x) + assert_array_almost_equal(y1, y2) + + def test_tpmv(self): + rng = np.random.default_rng(1234) + for ind, dtype in enumerate(DTYPES): + n = 10 + x = rng.random(n).astype(dtype) + # Upper triangular array + if ind < 2: + A = triu(rng.random((n, n))) + else: + A = triu(rng.random((n, n)) + rng.random((n, n))*1j) + + # Form the packed storage + c, r = tril_indices(n) + Ap = A[r, c] + func, = get_blas_funcs(('tpmv',), dtype=dtype) + + y1 = func(n=n, ap=Ap, x=x) + y2 = A.dot(x) + assert_array_almost_equal(y1, y2) + + y1 = func(n=n, ap=Ap, x=x, diag=1) + A[arange(n), arange(n)] = dtype(1) + y2 = A.dot(x) + assert_array_almost_equal(y1, y2) + + y1 = func(n=n, ap=Ap, x=x, diag=1, trans=1) + y2 = A.T.dot(x) + assert_array_almost_equal(y1, y2) + + y1 = func(n=n, ap=Ap, x=x, diag=1, trans=2) + y2 = A.conj().T.dot(x) + assert_array_almost_equal(y1, y2) + + def test_tpsv(self): + rng = np.random.default_rng(1234) + for ind, dtype in enumerate(DTYPES): + n = 10 + x = rng.random(n).astype(dtype) + # Upper triangular array + if ind < 2: + A = triu(rng.random((n, n))) + else: + A = triu(rng.random((n, n)) + rng.random((n, n))*1j) + A += eye(n) + # Form the packed storage + c, r = tril_indices(n) + Ap = A[r, c] + func, = get_blas_funcs(('tpsv',), dtype=dtype) + + y1 = func(n=n, ap=Ap, x=x) + y2 = solve(A, x) + assert_array_almost_equal(y1, y2) + + y1 = func(n=n, ap=Ap, x=x, diag=1) + A[arange(n), arange(n)] = dtype(1) + y2 = solve(A, x) + assert_array_almost_equal(y1, y2) + + y1 = func(n=n, ap=Ap, x=x, diag=1, trans=1) + y2 = solve(A.T, x) + assert_array_almost_equal(y1, y2) + + y1 = func(n=n, ap=Ap, x=x, diag=1, trans=2) + y2 = solve(A.conj().T, x) + assert_array_almost_equal(y1, y2) + + def test_trmv(self): + rng = np.random.default_rng(1234) + for ind, dtype in enumerate(DTYPES): + n = 3 + A = (rng.random((n, n))+eye(n)).astype(dtype) + x = rng.random(3).astype(dtype) + func, = get_blas_funcs(('trmv',), dtype=dtype) + + y1 = func(a=A, x=x) + y2 = triu(A).dot(x) + assert_array_almost_equal(y1, y2) + + y1 = func(a=A, x=x, diag=1) + A[arange(n), arange(n)] = dtype(1) + y2 = triu(A).dot(x) + assert_array_almost_equal(y1, y2) + + y1 = func(a=A, x=x, diag=1, trans=1) + y2 = triu(A).T.dot(x) + assert_array_almost_equal(y1, y2) + + y1 = func(a=A, x=x, diag=1, trans=2) + y2 = triu(A).conj().T.dot(x) + assert_array_almost_equal(y1, y2) + + def test_trsv(self): + rng = np.random.default_rng(1234) + for ind, dtype in enumerate(DTYPES): + n = 15 + A = (rng.random((n, n))+eye(n)).astype(dtype) + x = rng.random(n).astype(dtype) + func, = get_blas_funcs(('trsv',), dtype=dtype) + + y1 = func(a=A, x=x) + y2 = solve(triu(A), x) + assert_array_almost_equal(y1, y2) + + y1 = func(a=A, x=x, lower=1) + y2 = solve(tril(A), x) + assert_array_almost_equal(y1, y2) + + y1 = func(a=A, x=x, diag=1) + A[arange(n), arange(n)] = dtype(1) + y2 = solve(triu(A), x) + assert_array_almost_equal(y1, y2) + + y1 = func(a=A, x=x, diag=1, trans=1) + y2 = solve(triu(A).T, x) + assert_array_almost_equal(y1, y2) + + y1 = func(a=A, x=x, diag=1, trans=2) + y2 = solve(triu(A).conj().T, x) + assert_array_almost_equal(y1, y2) + + +class TestFBLAS3Simple: + + def test_gemm(self): + for p in 'sd': + f = getattr(fblas, p+'gemm', None) + if f is None: + continue + assert_array_almost_equal(f(3, [3], [-4]), [[-36]]) + assert_array_almost_equal(f(3, [3], [-4], 3, [5]), [-21]) + for p in 'cz': + f = getattr(fblas, p+'gemm', None) + if f is None: + continue + assert_array_almost_equal(f(3j, [3-4j], [-4]), [[-48-36j]]) + assert_array_almost_equal(f(3j, [3-4j], [-4], 3, [5j]), [-48-21j]) + + +def _get_func(func, ps='sdzc'): + """Just a helper: return a specified BLAS function w/typecode.""" + for p in ps: + f = getattr(fblas, p+func, None) + if f is None: + continue + yield f + + +class TestBLAS3Symm: + + def setup_method(self): + self.a = np.array([[1., 2.], + [0., 1.]]) + self.b = np.array([[1., 0., 3.], + [0., -1., 2.]]) + self.c = np.ones((2, 3)) + self.t = np.array([[2., -1., 8.], + [3., 0., 9.]]) + + def test_symm(self): + for f in _get_func('symm'): + res = f(a=self.a, b=self.b, c=self.c, alpha=1., beta=1.) + assert_array_almost_equal(res, self.t) + + res = f(a=self.a.T, b=self.b, lower=1, c=self.c, alpha=1., beta=1.) + assert_array_almost_equal(res, self.t) + + res = f(a=self.a, b=self.b.T, side=1, c=self.c.T, + alpha=1., beta=1.) + assert_array_almost_equal(res, self.t.T) + + def test_summ_wrong_side(self): + f = getattr(fblas, 'dsymm', None) + if f is not None: + assert_raises(Exception, f, **{'a': self.a, 'b': self.b, + 'alpha': 1, 'side': 1}) + # `side=1` means C <- B*A, hence shapes of A and B are to be + # compatible. Otherwise, f2py exception is raised + + def test_symm_wrong_uplo(self): + """SYMM only considers the upper/lower part of A. Hence setting + wrong value for `lower` (default is lower=0, meaning upper triangle) + gives a wrong result. + """ + f = getattr(fblas, 'dsymm', None) + if f is not None: + res = f(a=self.a, b=self.b, c=self.c, alpha=1., beta=1.) + assert np.allclose(res, self.t) + + res = f(a=self.a, b=self.b, lower=1, c=self.c, alpha=1., beta=1.) + assert not np.allclose(res, self.t) + + +class TestBLAS3Syrk: + def setup_method(self): + self.a = np.array([[1., 0.], + [0., -2.], + [2., 3.]]) + self.t = np.array([[1., 0., 2.], + [0., 4., -6.], + [2., -6., 13.]]) + self.tt = np.array([[5., 6.], + [6., 13.]]) + + def test_syrk(self): + for f in _get_func('syrk'): + c = f(a=self.a, alpha=1.) + assert_array_almost_equal(np.triu(c), np.triu(self.t)) + + c = f(a=self.a, alpha=1., lower=1) + assert_array_almost_equal(np.tril(c), np.tril(self.t)) + + c0 = np.ones(self.t.shape) + c = f(a=self.a, alpha=1., beta=1., c=c0) + assert_array_almost_equal(np.triu(c), np.triu(self.t+c0)) + + c = f(a=self.a, alpha=1., trans=1) + assert_array_almost_equal(np.triu(c), np.triu(self.tt)) + + # prints '0-th dimension must be fixed to 3 but got 5', + # FIXME: suppress? + # FIXME: how to catch the _fblas.error? + def test_syrk_wrong_c(self): + f = getattr(fblas, 'dsyrk', None) + if f is not None: + assert_raises(Exception, f, **{'a': self.a, 'alpha': 1., + 'c': np.ones((5, 8))}) + # if C is supplied, it must have compatible dimensions + + +class TestBLAS3Syr2k: + def setup_method(self): + self.a = np.array([[1., 0.], + [0., -2.], + [2., 3.]]) + self.b = np.array([[0., 1.], + [1., 0.], + [0, 1.]]) + self.t = np.array([[0., -1., 3.], + [-1., 0., 0.], + [3., 0., 6.]]) + self.tt = np.array([[0., 1.], + [1., 6]]) + + def test_syr2k(self): + for f in _get_func('syr2k'): + c = f(a=self.a, b=self.b, alpha=1.) + assert_array_almost_equal(np.triu(c), np.triu(self.t)) + + c = f(a=self.a, b=self.b, alpha=1., lower=1) + assert_array_almost_equal(np.tril(c), np.tril(self.t)) + + c0 = np.ones(self.t.shape) + c = f(a=self.a, b=self.b, alpha=1., beta=1., c=c0) + assert_array_almost_equal(np.triu(c), np.triu(self.t+c0)) + + c = f(a=self.a, b=self.b, alpha=1., trans=1) + assert_array_almost_equal(np.triu(c), np.triu(self.tt)) + + # prints '0-th dimension must be fixed to 3 but got 5', FIXME: suppress? + def test_syr2k_wrong_c(self): + f = getattr(fblas, 'dsyr2k', None) + if f is not None: + assert_raises(Exception, f, **{'a': self.a, + 'b': self.b, + 'alpha': 1., + 'c': np.zeros((15, 8))}) + # if C is supplied, it must have compatible dimensions + + +class TestSyHe: + """Quick and simple tests for (zc)-symm, syrk, syr2k.""" + + def setup_method(self): + self.sigma_y = np.array([[0., -1.j], + [1.j, 0.]]) + + def test_symm_zc(self): + for f in _get_func('symm', 'zc'): + # NB: a is symmetric w/upper diag of ONLY + res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.) + assert_array_almost_equal(np.triu(res), np.diag([1, -1])) + + def test_hemm_zc(self): + for f in _get_func('hemm', 'zc'): + # NB: a is hermitian w/upper diag of ONLY + res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.) + assert_array_almost_equal(np.triu(res), np.diag([1, 1])) + + def test_syrk_zr(self): + for f in _get_func('syrk', 'zc'): + res = f(a=self.sigma_y, alpha=1.) + assert_array_almost_equal(np.triu(res), np.diag([-1, -1])) + + def test_herk_zr(self): + for f in _get_func('herk', 'zc'): + res = f(a=self.sigma_y, alpha=1.) + assert_array_almost_equal(np.triu(res), np.diag([1, 1])) + + def test_syr2k_zr(self): + for f in _get_func('syr2k', 'zc'): + res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.) + assert_array_almost_equal(np.triu(res), 2.*np.diag([-1, -1])) + + def test_her2k_zr(self): + for f in _get_func('her2k', 'zc'): + res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.) + assert_array_almost_equal(np.triu(res), 2.*np.diag([1, 1])) + + +class TestTRMM: + """Quick and simple tests for dtrmm.""" + + def setup_method(self): + self.a = np.array([[1., 2., ], + [-2., 1.]]) + self.b = np.array([[3., 4., -1.], + [5., 6., -2.]]) + + self.a2 = np.array([[1, 1, 2, 3], + [0, 1, 4, 5], + [0, 0, 1, 6], + [0, 0, 0, 1]], order="f") + self.b2 = np.array([[1, 4], [2, 5], [3, 6], [7, 8], [9, 10]], + order="f") + + @pytest.mark.parametrize("dtype_", DTYPES) + def test_side(self, dtype_): + trmm = get_blas_funcs("trmm", dtype=dtype_) + # Provide large A array that works for side=1 but not 0 (see gh-10841) + assert_raises(Exception, trmm, 1.0, self.a2, self.b2) + res = trmm(1.0, self.a2.astype(dtype_), self.b2.astype(dtype_), + side=1) + k = self.b2.shape[1] + assert_allclose(res, self.b2 @ self.a2[:k, :k], rtol=0., + atol=100*np.finfo(dtype_).eps) + + def test_ab(self): + f = getattr(fblas, 'dtrmm', None) + if f is not None: + result = f(1., self.a, self.b) + # default a is upper triangular + expected = np.array([[13., 16., -5.], + [5., 6., -2.]]) + assert_array_almost_equal(result, expected) + + def test_ab_lower(self): + f = getattr(fblas, 'dtrmm', None) + if f is not None: + result = f(1., self.a, self.b, lower=True) + expected = np.array([[3., 4., -1.], + [-1., -2., 0.]]) # now a is lower triangular + assert_array_almost_equal(result, expected) + + def test_b_overwrites(self): + # BLAS dtrmm modifies B argument in-place. + # Here the default is to copy, but this can be overridden + f = getattr(fblas, 'dtrmm', None) + if f is not None: + for overwr in [True, False]: + bcopy = self.b.copy() + result = f(1., self.a, bcopy, overwrite_b=overwr) + # C-contiguous arrays are copied + assert_(bcopy.flags.f_contiguous is False and + np.may_share_memory(bcopy, result) is False) + assert_equal(bcopy, self.b) + + bcopy = np.asfortranarray(self.b.copy()) # or just transpose it + result = f(1., self.a, bcopy, overwrite_b=True) + assert_(bcopy.flags.f_contiguous is True and + np.may_share_memory(bcopy, result) is True) + assert_array_almost_equal(bcopy, result) + + +def test_trsm(): + rng = np.random.default_rng(1234) + for ind, dtype in enumerate(DTYPES): + tol = np.finfo(dtype).eps*1000 + func, = get_blas_funcs(('trsm',), dtype=dtype) + + # Test protection against size mismatches + A = rng.random((4, 5)).astype(dtype) + B = rng.random((4, 4)).astype(dtype) + alpha = dtype(1) + assert_raises(Exception, func, alpha, A, B) + assert_raises(Exception, func, alpha, A.T, B) + + n = 8 + m = 7 + alpha = dtype(-2.5) + if ind < 2: + A = rng.random((m, m)) + eye(m) + else: + A = (rng.random((m, m)) + rng.random((m, m))*1j) + eye(m) + A = A.astype(dtype) + Au = triu(A) + Al = tril(A) + B1 = rng.random((m, n)).astype(dtype) + B2 = rng.random((n, m)).astype(dtype) + + x1 = func(alpha=alpha, a=A, b=B1) + assert_equal(B1.shape, x1.shape) + x2 = solve(Au, alpha*B1) + assert_allclose(x1, x2, atol=tol) + + x1 = func(alpha=alpha, a=A, b=B1, trans_a=1) + x2 = solve(Au.T, alpha*B1) + assert_allclose(x1, x2, atol=tol) + + x1 = func(alpha=alpha, a=A, b=B1, trans_a=2) + x2 = solve(Au.conj().T, alpha*B1) + assert_allclose(x1, x2, atol=tol) + + x1 = func(alpha=alpha, a=A, b=B1, diag=1) + Au[arange(m), arange(m)] = dtype(1) + x2 = solve(Au, alpha*B1) + assert_allclose(x1, x2, atol=tol) + + x1 = func(alpha=alpha, a=A, b=B2, diag=1, side=1) + x2 = solve(Au.conj().T, alpha*B2.conj().T) + assert_allclose(x1, x2.conj().T, atol=tol) + + x1 = func(alpha=alpha, a=A, b=B2, diag=1, side=1, lower=1) + Al[arange(m), arange(m)] = dtype(1) + x2 = solve(Al.conj().T, alpha*B2.conj().T) + assert_allclose(x1, x2.conj().T, atol=tol) + + +@pytest.mark.xfail(run=False, + reason="gh-16930") +def test_gh_169309(): + x = np.repeat(10, 9) + actual = scipy.linalg.blas.dnrm2(x, 5, 3, -1) + expected = math.sqrt(500) + assert_allclose(actual, expected) + + +def test_dnrm2_neg_incx(): + # check that dnrm2(..., incx < 0) raises + # XXX: remove the test after the lowest supported BLAS implements + # negative incx (new in LAPACK 3.10) + x = np.repeat(10, 9) + incx = -1 + with assert_raises(fblas.__fblas_error): + scipy.linalg.blas.dnrm2(x, 5, 3, incx) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_cython_blas.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_cython_blas.py new file mode 100644 index 0000000000000000000000000000000000000000..284e214d38ed331cf0493d1e3bba6e1214939b2c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_cython_blas.py @@ -0,0 +1,118 @@ +import numpy as np +from numpy.testing import (assert_allclose, + assert_equal) +import scipy.linalg.cython_blas as blas + +class TestDGEMM: + + def test_transposes(self): + + a = np.arange(12, dtype='d').reshape((3, 4))[:2,:2] + b = np.arange(1, 13, dtype='d').reshape((4, 3))[:2,:2] + c = np.empty((2, 4))[:2,:2] + + blas._test_dgemm(1., a, b, 0., c) + assert_allclose(c, a.dot(b)) + + blas._test_dgemm(1., a.T, b, 0., c) + assert_allclose(c, a.T.dot(b)) + + blas._test_dgemm(1., a, b.T, 0., c) + assert_allclose(c, a.dot(b.T)) + + blas._test_dgemm(1., a.T, b.T, 0., c) + assert_allclose(c, a.T.dot(b.T)) + + blas._test_dgemm(1., a, b, 0., c.T) + assert_allclose(c, a.dot(b).T) + + blas._test_dgemm(1., a.T, b, 0., c.T) + assert_allclose(c, a.T.dot(b).T) + + blas._test_dgemm(1., a, b.T, 0., c.T) + assert_allclose(c, a.dot(b.T).T) + + blas._test_dgemm(1., a.T, b.T, 0., c.T) + assert_allclose(c, a.T.dot(b.T).T) + + def test_shapes(self): + a = np.arange(6, dtype='d').reshape((3, 2)) + b = np.arange(-6, 2, dtype='d').reshape((2, 4)) + c = np.empty((3, 4)) + + blas._test_dgemm(1., a, b, 0., c) + assert_allclose(c, a.dot(b)) + + blas._test_dgemm(1., b.T, a.T, 0., c.T) + assert_allclose(c, b.T.dot(a.T).T) + +class TestWfuncPointers: + """ Test the function pointers that are expected to fail on + Mac OS X without the additional entry statement in their definitions + in fblas_l1.pyf.src. """ + + def test_complex_args(self): + + cx = np.array([.5 + 1.j, .25 - .375j, 12.5 - 4.j], np.complex64) + cy = np.array([.8 + 2.j, .875 - .625j, -1. + 2.j], np.complex64) + + assert_allclose(blas._test_cdotc(cx, cy), + -17.6468753815+21.3718757629j) + assert_allclose(blas._test_cdotu(cx, cy), + -6.11562538147+30.3156242371j) + + assert_equal(blas._test_icamax(cx), 3) + + assert_allclose(blas._test_scasum(cx), 18.625) + assert_allclose(blas._test_scnrm2(cx), 13.1796483994) + + assert_allclose(blas._test_cdotc(cx[::2], cy[::2]), + -18.1000003815+21.2000007629j) + assert_allclose(blas._test_cdotu(cx[::2], cy[::2]), + -6.10000038147+30.7999992371j) + assert_allclose(blas._test_scasum(cx[::2]), 18.) + assert_allclose(blas._test_scnrm2(cx[::2]), 13.1719398499) + + def test_double_args(self): + + x = np.array([5., -3, -.5], np.float64) + y = np.array([2, 1, .5], np.float64) + + assert_allclose(blas._test_dasum(x), 8.5) + assert_allclose(blas._test_ddot(x, y), 6.75) + assert_allclose(blas._test_dnrm2(x), 5.85234975815) + + assert_allclose(blas._test_dasum(x[::2]), 5.5) + assert_allclose(blas._test_ddot(x[::2], y[::2]), 9.75) + assert_allclose(blas._test_dnrm2(x[::2]), 5.0249376297) + + assert_equal(blas._test_idamax(x), 1) + + def test_float_args(self): + + x = np.array([5., -3, -.5], np.float32) + y = np.array([2, 1, .5], np.float32) + + assert_equal(blas._test_isamax(x), 1) + + assert_allclose(blas._test_sasum(x), 8.5) + assert_allclose(blas._test_sdot(x, y), 6.75) + assert_allclose(blas._test_snrm2(x), 5.85234975815) + + assert_allclose(blas._test_sasum(x[::2]), 5.5) + assert_allclose(blas._test_sdot(x[::2], y[::2]), 9.75) + assert_allclose(blas._test_snrm2(x[::2]), 5.0249376297) + + def test_double_complex_args(self): + + cx = np.array([.5 + 1.j, .25 - .375j, 13. - 4.j], np.complex128) + cy = np.array([.875 + 2.j, .875 - .625j, -1. + 2.j], np.complex128) + + assert_equal(blas._test_izamax(cx), 3) + + assert_allclose(blas._test_zdotc(cx, cy), -18.109375+22.296875j) + assert_allclose(blas._test_zdotu(cx, cy), -6.578125+31.390625j) + + assert_allclose(blas._test_zdotc(cx[::2], cy[::2]), -18.5625+22.125j) + assert_allclose(blas._test_zdotu(cx[::2], cy[::2]), -6.5625+31.875j) + diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_cython_lapack.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_cython_lapack.py new file mode 100644 index 0000000000000000000000000000000000000000..2a4e7b34b62042efdb0ce0f8ee61ce0189320995 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_cython_lapack.py @@ -0,0 +1,22 @@ +from numpy.testing import assert_allclose +from scipy.linalg import cython_lapack as cython_lapack +from scipy.linalg import lapack + + +class TestLamch: + + def test_slamch(self): + for c in [b'e', b's', b'b', b'p', b'n', b'r', b'm', b'u', b'l', b'o']: + assert_allclose(cython_lapack._test_slamch(c), + lapack.slamch(c)) + + def test_dlamch(self): + for c in [b'e', b's', b'b', b'p', b'n', b'r', b'm', b'u', b'l', b'o']: + assert_allclose(cython_lapack._test_dlamch(c), + lapack.dlamch(c)) + + def test_complex_ladiv(self): + cx = .5 + 1.j + cy = .875 + 2.j + assert_allclose(cython_lapack._test_zladiv(cy, cx), 1.95+0.1j) + assert_allclose(cython_lapack._test_cladiv(cy, cx), 1.95+0.1j) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_cythonized_array_utils.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_cythonized_array_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d52c93950b6398c010b8bb8e5312153b3102fdf4 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_cythonized_array_utils.py @@ -0,0 +1,132 @@ +import numpy as np +from scipy.linalg import bandwidth, issymmetric, ishermitian +import pytest +from pytest import raises + + +def test_bandwidth_dtypes(): + n = 5 + for t in np.typecodes['All']: + A = np.zeros([n, n], dtype=t) + if t in 'eUVOMm': + raises(TypeError, bandwidth, A) + elif t == 'G': # No-op test. On win these pass on others fail. + pass + else: + _ = bandwidth(A) + + +def test_bandwidth_non2d_input(): + A = np.array([1, 2, 3]) + raises(ValueError, bandwidth, A) + A = np.array([[[1, 2, 3], [4, 5, 6]]]) + raises(ValueError, bandwidth, A) + + +@pytest.mark.parametrize('T', [x for x in np.typecodes['All'] + if x not in 'eGUVOMm']) +def test_bandwidth_square_inputs(T): + n = 20 + k = 4 + R = np.zeros([n, n], dtype=T, order='F') + # form a banded matrix inplace + R[[x for x in range(n)], [x for x in range(n)]] = 1 + R[[x for x in range(n-k)], [x for x in range(k, n)]] = 1 + R[[x for x in range(1, n)], [x for x in range(n-1)]] = 1 + R[[x for x in range(k, n)], [x for x in range(n-k)]] = 1 + assert bandwidth(R) == (k, k) + A = np.array([ + [1, 1, 0, 0, 0, 0, 0, 0], + [1, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 1, 1], + [0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0], + ]) + assert bandwidth(A) == (2, 2) + + +@pytest.mark.parametrize('T', [x for x in np.typecodes['All'] + if x not in 'eGUVOMm']) +def test_bandwidth_rect_inputs(T): + n, m = 10, 20 + k = 5 + R = np.zeros([n, m], dtype=T, order='F') + # form a banded matrix inplace + R[[x for x in range(n)], [x for x in range(n)]] = 1 + R[[x for x in range(n-k)], [x for x in range(k, n)]] = 1 + R[[x for x in range(1, n)], [x for x in range(n-1)]] = 1 + R[[x for x in range(k, n)], [x for x in range(n-k)]] = 1 + assert bandwidth(R) == (k, k) + + +def test_issymetric_ishermitian_dtypes(): + n = 5 + for t in np.typecodes['All']: + A = np.zeros([n, n], dtype=t) + if t in 'eUVOMm': + raises(TypeError, issymmetric, A) + raises(TypeError, ishermitian, A) + elif t == 'G': # No-op test. On win these pass on others fail. + pass + else: + assert issymmetric(A) + assert ishermitian(A) + + +def test_issymmetric_ishermitian_invalid_input(): + A = np.array([1, 2, 3]) + raises(ValueError, issymmetric, A) + raises(ValueError, ishermitian, A) + A = np.array([[[1, 2, 3], [4, 5, 6]]]) + raises(ValueError, issymmetric, A) + raises(ValueError, ishermitian, A) + A = np.array([[1, 2, 3], [4, 5, 6]]) + raises(ValueError, issymmetric, A) + raises(ValueError, ishermitian, A) + + +def test_issymetric_complex_decimals(): + A = np.arange(1, 10).astype(complex).reshape(3, 3) + A += np.arange(-4, 5).astype(complex).reshape(3, 3)*1j + # make entries decimal + A /= np.pi + A = A + A.T + assert issymmetric(A) + + +def test_ishermitian_complex_decimals(): + A = np.arange(1, 10).astype(complex).reshape(3, 3) + A += np.arange(-4, 5).astype(complex).reshape(3, 3)*1j + # make entries decimal + A /= np.pi + A = A + A.T.conj() + assert ishermitian(A) + + +def test_issymmetric_approximate_results(): + n = 20 + rng = np.random.RandomState(123456789) + x = rng.uniform(high=5., size=[n, n]) + y = x @ x.T # symmetric + p = rng.standard_normal([n, n]) + z = p @ y @ p.T + assert issymmetric(z, atol=1e-10) + assert issymmetric(z, atol=1e-10, rtol=0.) + assert issymmetric(z, atol=0., rtol=1e-12) + assert issymmetric(z, atol=1e-13, rtol=1e-12) + + +def test_ishermitian_approximate_results(): + n = 20 + rng = np.random.RandomState(987654321) + x = rng.uniform(high=5., size=[n, n]) + y = x @ x.T # symmetric + p = rng.standard_normal([n, n]) + rng.standard_normal([n, n])*1j + z = p @ y @ p.conj().T + assert ishermitian(z, atol=1e-10) + assert ishermitian(z, atol=1e-10, rtol=0.) + assert ishermitian(z, atol=0., rtol=1e-12) + assert ishermitian(z, atol=1e-13, rtol=1e-12) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp.py new file mode 100644 index 0000000000000000000000000000000000000000..605496721f8eec7a522fbba0a77ed33d6c1fdeaf --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp.py @@ -0,0 +1,3152 @@ +import itertools +import platform +import sys + +import numpy as np +from numpy.testing import (assert_equal, assert_almost_equal, + assert_array_almost_equal, assert_array_equal, + assert_, assert_allclose) + +import pytest +from pytest import raises as assert_raises + +from scipy.linalg import (eig, eigvals, lu, svd, svdvals, cholesky, qr, + schur, rsf2csf, lu_solve, lu_factor, solve, diagsvd, + hessenberg, rq, eig_banded, eigvals_banded, eigh, + eigvalsh, qr_multiply, qz, orth, ordqz, + subspace_angles, hadamard, eigvalsh_tridiagonal, + eigh_tridiagonal, null_space, cdf2rdf, LinAlgError) + +from scipy.linalg.lapack import (dgbtrf, dgbtrs, zgbtrf, zgbtrs, dsbev, + dsbevd, dsbevx, zhbevd, zhbevx) + +from scipy.linalg._misc import norm +from scipy.linalg._decomp_qz import _select_function +from scipy.stats import ortho_group + +from numpy import (array, diag, full, linalg, argsort, zeros, arange, + float32, complex64, ravel, sqrt, iscomplex, shape, sort, + sign, asarray, isfinite, ndarray, eye,) + +from scipy.linalg._testutils import assert_no_overwrite +from scipy.sparse._sputils import matrix + +from scipy._lib._testutils import check_free_memory +from scipy.linalg.blas import HAS_ILP64 +try: + from scipy.__config__ import CONFIG +except ImportError: + CONFIG = None + +IS_WASM = (sys.platform == "emscripten" or platform.machine() in ["wasm32", "wasm64"]) + + +def _random_hermitian_matrix(n, posdef=False, dtype=float): + "Generate random sym/hermitian array of the given size n" + if dtype in COMPLEX_DTYPES: + A = np.random.rand(n, n) + np.random.rand(n, n)*1.0j + A = (A + A.conj().T)/2 + else: + A = np.random.rand(n, n) + A = (A + A.T)/2 + + if posdef: + A += sqrt(2*n)*np.eye(n) + + return A.astype(dtype) + + +REAL_DTYPES = [np.float32, np.float64] +COMPLEX_DTYPES = [np.complex64, np.complex128] +DTYPES = REAL_DTYPES + COMPLEX_DTYPES + + +# XXX: This function should not be defined here, but somewhere in +# scipy.linalg namespace +def symrand(dim_or_eigv, rng): + """Return a random symmetric (Hermitian) matrix. + + If 'dim_or_eigv' is an integer N, return a NxN matrix, with eigenvalues + uniformly distributed on (-1,1). + + If 'dim_or_eigv' is 1-D real array 'a', return a matrix whose + eigenvalues are 'a'. + """ + if isinstance(dim_or_eigv, int): + dim = dim_or_eigv + d = rng.random(dim)*2 - 1 + elif (isinstance(dim_or_eigv, ndarray) and + len(dim_or_eigv.shape) == 1): + dim = dim_or_eigv.shape[0] + d = dim_or_eigv + else: + raise TypeError("input type not supported.") + + v = ortho_group.rvs(dim) + h = v.T.conj() @ diag(d) @ v + # to avoid roundoff errors, symmetrize the matrix (again) + h = 0.5*(h.T+h) + return h + + +class TestEigVals: + + def test_simple(self): + a = [[1, 2, 3], [1, 2, 3], [2, 5, 6]] + w = eigvals(a) + exact_w = [(9+sqrt(93))/2, 0, (9-sqrt(93))/2] + assert_array_almost_equal(w, exact_w) + + def test_simple_tr(self): + a = array([[1, 2, 3], [1, 2, 3], [2, 5, 6]], 'd').T + a = a.copy() + a = a.T + w = eigvals(a) + exact_w = [(9+sqrt(93))/2, 0, (9-sqrt(93))/2] + assert_array_almost_equal(w, exact_w) + + def test_simple_complex(self): + a = [[1, 2, 3], [1, 2, 3], [2, 5, 6+1j]] + w = eigvals(a) + exact_w = [(9+1j+sqrt(92+6j))/2, + 0, + (9+1j-sqrt(92+6j))/2] + assert_array_almost_equal(w, exact_w) + + def test_finite(self): + a = [[1, 2, 3], [1, 2, 3], [2, 5, 6]] + w = eigvals(a, check_finite=False) + exact_w = [(9+sqrt(93))/2, 0, (9-sqrt(93))/2] + assert_array_almost_equal(w, exact_w) + + @pytest.mark.parametrize('dt', [int, float, float32, complex, complex64]) + def test_empty(self, dt): + a = np.empty((0, 0), dtype=dt) + w = eigvals(a) + assert w.shape == (0,) + assert w.dtype == eigvals(np.eye(2, dtype=dt)).dtype + + w = eigvals(a, homogeneous_eigvals=True) + assert w.shape == (2, 0) + assert w.dtype == eigvals(np.eye(2, dtype=dt)).dtype + + +class TestEig: + + def test_simple(self): + a = array([[1, 2, 3], [1, 2, 3], [2, 5, 6]]) + w, v = eig(a) + exact_w = [(9+sqrt(93))/2, 0, (9-sqrt(93))/2] + v0 = array([1, 1, (1+sqrt(93)/3)/2]) + v1 = array([3., 0, -1]) + v2 = array([1, 1, (1-sqrt(93)/3)/2]) + v0 = v0 / norm(v0) + v1 = v1 / norm(v1) + v2 = v2 / norm(v2) + assert_array_almost_equal(w, exact_w) + assert_array_almost_equal(v0, v[:, 0]*sign(v[0, 0])) + assert_array_almost_equal(v1, v[:, 1]*sign(v[0, 1])) + assert_array_almost_equal(v2, v[:, 2]*sign(v[0, 2])) + for i in range(3): + assert_array_almost_equal(a @ v[:, i], w[i]*v[:, i]) + w, v = eig(a, left=1, right=0) + for i in range(3): + assert_array_almost_equal(a.T @ v[:, i], w[i]*v[:, i]) + + def test_simple_complex_eig(self): + a = array([[1, 2], [-2, 1]]) + w, vl, vr = eig(a, left=1, right=1) + assert_array_almost_equal(w, array([1+2j, 1-2j])) + for i in range(2): + assert_array_almost_equal(a @ vr[:, i], w[i]*vr[:, i]) + for i in range(2): + assert_array_almost_equal(a.conj().T @ vl[:, i], + w[i].conj()*vl[:, i]) + + def test_simple_complex(self): + a = array([[1, 2, 3], [1, 2, 3], [2, 5, 6+1j]]) + w, vl, vr = eig(a, left=1, right=1) + for i in range(3): + assert_array_almost_equal(a @ vr[:, i], w[i]*vr[:, i]) + for i in range(3): + assert_array_almost_equal(a.conj().T @ vl[:, i], + w[i].conj()*vl[:, i]) + + def test_gh_3054(self): + a = [[1]] + b = [[0]] + w, vr = eig(a, b, homogeneous_eigvals=True) + assert_allclose(w[1, 0], 0) + assert_(w[0, 0] != 0) + assert_allclose(vr, 1) + + w, vr = eig(a, b) + assert_equal(w, np.inf) + assert_allclose(vr, 1) + + def _check_gen_eig(self, A, B, atol_homog=1e-13, rtol_homog=1e-13, + atol=1e-13, rtol=1e-13): + if B is not None: + A, B = asarray(A), asarray(B) + B0 = B + else: + A = asarray(A) + B0 = B + B = np.eye(*A.shape) + msg = f"\n{A!r}\n{B!r}" + + # Eigenvalues in homogeneous coordinates + w, vr = eig(A, B0, homogeneous_eigvals=True) + wt = eigvals(A, B0, homogeneous_eigvals=True) + val1 = A @ vr * w[1, :] + val2 = B @ vr * w[0, :] + for i in range(val1.shape[1]): + assert_allclose(val1[:, i], val2[:, i], + rtol=rtol_homog, atol=atol_homog, err_msg=msg) + + if B0 is None: + assert_allclose(w[1, :], 1) + assert_allclose(wt[1, :], 1) + + perm = np.lexsort(w) + permt = np.lexsort(wt) + assert_allclose(w[:, perm], wt[:, permt], atol=1e-7, rtol=1e-7, + err_msg=msg) + + length = np.empty(len(vr)) + + for i in range(len(vr)): + length[i] = norm(vr[:, i]) + + assert_allclose(length, np.ones(length.size), err_msg=msg, + atol=1e-7, rtol=1e-7) + + # Convert homogeneous coordinates + beta_nonzero = (w[1, :] != 0) + wh = w[0, beta_nonzero] / w[1, beta_nonzero] + + # Eigenvalues in standard coordinates + w, vr = eig(A, B0) + wt = eigvals(A, B0) + val1 = A @ vr + val2 = B @ vr * w + res = val1 - val2 + for i in range(res.shape[1]): + if np.all(isfinite(res[:, i])): + assert_allclose(res[:, i], 0, + rtol=rtol, atol=atol, err_msg=msg) + + # try to consistently order eigenvalues, including complex conjugate pairs + w_fin = w[isfinite(w)] + wt_fin = wt[isfinite(wt)] + + # prune noise in the real parts + w_fin = -1j * np.real_if_close(1j*w_fin, tol=1e-10) + wt_fin = -1j * np.real_if_close(1j*wt_fin, tol=1e-10) + + perm = argsort(abs(w_fin) + w_fin.imag) + permt = argsort(abs(wt_fin) + wt_fin.imag) + + assert_allclose(w_fin[perm], wt_fin[permt], + atol=1e-7, rtol=1e-7, err_msg=msg) + + length = np.empty(len(vr)) + for i in range(len(vr)): + length[i] = norm(vr[:, i]) + assert_allclose(length, np.ones(length.size), err_msg=msg) + + # Compare homogeneous and nonhomogeneous versions + assert_allclose(sort(wh), sort(w[np.isfinite(w)])) + + def test_singular(self): + # Example taken from + # https://web.archive.org/web/20040903121217/http://www.cs.umu.se/research/nla/singular_pairs/guptri/matlab.html + A = array([[22, 34, 31, 31, 17], + [45, 45, 42, 19, 29], + [39, 47, 49, 26, 34], + [27, 31, 26, 21, 15], + [38, 44, 44, 24, 30]]) + B = array([[13, 26, 25, 17, 24], + [31, 46, 40, 26, 37], + [26, 40, 19, 25, 25], + [16, 25, 27, 14, 23], + [24, 35, 18, 21, 22]]) + + with np.errstate(all='ignore'): + self._check_gen_eig(A, B, atol_homog=5e-13, atol=5e-13) + + def test_falker(self): + # Test matrices giving some Nan generalized eigenvalues. + M = diag(array([1, 0, 3])) + K = array(([2, -1, -1], [-1, 2, -1], [-1, -1, 2])) + D = array(([1, -1, 0], [-1, 1, 0], [0, 0, 0])) + Z = zeros((3, 3)) + I3 = eye(3) + A = np.block([[I3, Z], [Z, -K]]) + B = np.block([[Z, I3], [M, D]]) + + with np.errstate(all='ignore'): + self._check_gen_eig(A, B) + + def test_bad_geneig(self): + # Ticket #709 (strange return values from DGGEV) + + def matrices(omega): + c1 = -9 + omega**2 + c2 = 2*omega + A = [[1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, c1, 0], + [0, 0, 0, c1]] + B = [[0, 0, 1, 0], + [0, 0, 0, 1], + [1, 0, 0, -c2], + [0, 1, c2, 0]] + return A, B + + # With a buggy LAPACK, this can fail for different omega on different + # machines -- so we need to test several values + with np.errstate(all='ignore'): + for k in range(100): + A, B = matrices(omega=k*5./100) + self._check_gen_eig(A, B) + + def test_make_eigvals(self): + # Step through all paths in _make_eigvals + # Real eigenvalues + rng = np.random.RandomState(1234) + A = symrand(3, rng) + self._check_gen_eig(A, None) + B = symrand(3, rng) + self._check_gen_eig(A, B) + # Complex eigenvalues + A = rng.random((3, 3)) + 1j*rng.random((3, 3)) + self._check_gen_eig(A, None) + B = rng.random((3, 3)) + 1j*rng.random((3, 3)) + self._check_gen_eig(A, B) + + def test_check_finite(self): + a = [[1, 2, 3], [1, 2, 3], [2, 5, 6]] + w, v = eig(a, check_finite=False) + exact_w = [(9+sqrt(93))/2, 0, (9-sqrt(93))/2] + v0 = array([1, 1, (1+sqrt(93)/3)/2]) + v1 = array([3., 0, -1]) + v2 = array([1, 1, (1-sqrt(93)/3)/2]) + v0 = v0 / norm(v0) + v1 = v1 / norm(v1) + v2 = v2 / norm(v2) + assert_array_almost_equal(w, exact_w) + assert_array_almost_equal(v0, v[:, 0]*sign(v[0, 0])) + assert_array_almost_equal(v1, v[:, 1]*sign(v[0, 1])) + assert_array_almost_equal(v2, v[:, 2]*sign(v[0, 2])) + for i in range(3): + assert_array_almost_equal(a @ v[:, i], w[i]*v[:, i]) + + def test_not_square_error(self): + """Check that passing a non-square array raises a ValueError.""" + A = np.arange(6).reshape(3, 2) + assert_raises(ValueError, eig, A) + + def test_shape_mismatch(self): + """Check that passing arrays of with different shapes + raises a ValueError.""" + A = eye(2) + B = np.arange(9.0).reshape(3, 3) + assert_raises(ValueError, eig, A, B) + assert_raises(ValueError, eig, B, A) + + def test_gh_11577(self): + # https://github.com/scipy/scipy/issues/11577 + # `A - lambda B` should have 4 and 8 among the eigenvalues, and this + # was apparently broken on some platforms + A = np.array([[12.0, 28.0, 76.0, 220.0], + [16.0, 32.0, 80.0, 224.0], + [24.0, 40.0, 88.0, 232.0], + [40.0, 56.0, 104.0, 248.0]], dtype='float64') + B = np.array([[2.0, 4.0, 10.0, 28.0], + [3.0, 5.0, 11.0, 29.0], + [5.0, 7.0, 13.0, 31.0], + [9.0, 11.0, 17.0, 35.0]], dtype='float64') + + D, V = eig(A, B) + + # The problem is ill-conditioned, and two other eigenvalues + # depend on ATLAS/OpenBLAS version, compiler version etc + # see gh-11577 for discussion + # + # NB: it is tempting to use `assert_allclose(D[:2], [4, 8])` instead but + # the ordering of eigenvalues also comes out different on different + # systems depending on who knows what. + with np.testing.suppress_warnings() as sup: + # isclose chokes on inf/nan values + sup.filter(RuntimeWarning, "invalid value encountered in multiply") + assert np.isclose(D, 4.0, atol=1e-14).any() + assert np.isclose(D, 8.0, atol=1e-14).any() + + @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) + def test_empty(self, dt): + a = np.empty((0, 0), dtype=dt) + w, vr = eig(a) + + w_n, vr_n = eig(np.eye(2, dtype=dt)) + + assert w.shape == (0,) + assert w.dtype == w_n.dtype #eigvals(np.eye(2, dtype=dt)).dtype + + assert_allclose(vr, np.empty((0, 0))) + assert vr.shape == (0, 0) + assert vr.dtype == vr_n.dtype + + w, vr = eig(a, homogeneous_eigvals=True) + assert w.shape == (2, 0) + assert w.dtype == w_n.dtype + + assert vr.shape == (0, 0) + assert vr.dtype == vr_n.dtype + + + +class TestEigBanded: + def setup_method(self): + self.create_bandmat() + + def create_bandmat(self): + """Create the full matrix `self.fullmat` and + the corresponding band matrix `self.bandmat`.""" + N = 10 + self.KL = 2 # number of subdiagonals (below the diagonal) + self.KU = 2 # number of superdiagonals (above the diagonal) + + # symmetric band matrix + self.sym_mat = (diag(full(N, 1.0)) + + diag(full(N-1, -1.0), -1) + diag(full(N-1, -1.0), 1) + + diag(full(N-2, -2.0), -2) + diag(full(N-2, -2.0), 2)) + + # hermitian band matrix + self.herm_mat = (diag(full(N, -1.0)) + + 1j*diag(full(N-1, 1.0), -1) + - 1j*diag(full(N-1, 1.0), 1) + + diag(full(N-2, -2.0), -2) + + diag(full(N-2, -2.0), 2)) + + # general real band matrix + self.real_mat = (diag(full(N, 1.0)) + + diag(full(N-1, -1.0), -1) + diag(full(N-1, -3.0), 1) + + diag(full(N-2, 2.0), -2) + diag(full(N-2, -2.0), 2)) + + # general complex band matrix + self.comp_mat = (1j*diag(full(N, 1.0)) + + diag(full(N-1, -1.0), -1) + + 1j*diag(full(N-1, -3.0), 1) + + diag(full(N-2, 2.0), -2) + + diag(full(N-2, -2.0), 2)) + + # Eigenvalues and -vectors from linalg.eig + ew, ev = linalg.eig(self.sym_mat) + ew = ew.real + args = argsort(ew) + self.w_sym_lin = ew[args] + self.evec_sym_lin = ev[:, args] + + ew, ev = linalg.eig(self.herm_mat) + ew = ew.real + args = argsort(ew) + self.w_herm_lin = ew[args] + self.evec_herm_lin = ev[:, args] + + # Extract upper bands from symmetric and hermitian band matrices + # (for use in dsbevd, dsbevx, zhbevd, zhbevx + # and their single precision versions) + LDAB = self.KU + 1 + self.bandmat_sym = zeros((LDAB, N), dtype=float) + self.bandmat_herm = zeros((LDAB, N), dtype=complex) + for i in range(LDAB): + self.bandmat_sym[LDAB-i-1, i:N] = diag(self.sym_mat, i) + self.bandmat_herm[LDAB-i-1, i:N] = diag(self.herm_mat, i) + + # Extract bands from general real and complex band matrix + # (for use in dgbtrf, dgbtrs and their single precision versions) + LDAB = 2*self.KL + self.KU + 1 + self.bandmat_real = zeros((LDAB, N), dtype=float) + self.bandmat_real[2*self.KL, :] = diag(self.real_mat) # diagonal + for i in range(self.KL): + # superdiagonals + self.bandmat_real[2*self.KL-1-i, i+1:N] = diag(self.real_mat, i+1) + # subdiagonals + self.bandmat_real[2*self.KL+1+i, 0:N-1-i] = diag(self.real_mat, + -i-1) + + self.bandmat_comp = zeros((LDAB, N), dtype=complex) + self.bandmat_comp[2*self.KL, :] = diag(self.comp_mat) # diagonal + for i in range(self.KL): + # superdiagonals + self.bandmat_comp[2*self.KL-1-i, i+1:N] = diag(self.comp_mat, i+1) + # subdiagonals + self.bandmat_comp[2*self.KL+1+i, 0:N-1-i] = diag(self.comp_mat, + -i-1) + + # absolute value for linear equation system A*x = b + self.b = 1.0*arange(N) + self.bc = self.b * (1 + 1j) + + ##################################################################### + + def test_dsbev(self): + """Compare dsbev eigenvalues and eigenvectors with + the result of linalg.eig.""" + w, evec, info = dsbev(self.bandmat_sym, compute_v=1) + evec_ = evec[:, argsort(w)] + assert_array_almost_equal(sort(w), self.w_sym_lin) + assert_array_almost_equal(abs(evec_), abs(self.evec_sym_lin)) + + def test_dsbevd(self): + """Compare dsbevd eigenvalues and eigenvectors with + the result of linalg.eig.""" + w, evec, info = dsbevd(self.bandmat_sym, compute_v=1) + evec_ = evec[:, argsort(w)] + assert_array_almost_equal(sort(w), self.w_sym_lin) + assert_array_almost_equal(abs(evec_), abs(self.evec_sym_lin)) + + def test_dsbevx(self): + """Compare dsbevx eigenvalues and eigenvectors + with the result of linalg.eig.""" + N, N = shape(self.sym_mat) + # Achtung: Argumente 0.0,0.0,range? + w, evec, num, ifail, info = dsbevx(self.bandmat_sym, 0.0, 0.0, 1, N, + compute_v=1, range=2) + evec_ = evec[:, argsort(w)] + assert_array_almost_equal(sort(w), self.w_sym_lin) + assert_array_almost_equal(abs(evec_), abs(self.evec_sym_lin)) + + def test_zhbevd(self): + """Compare zhbevd eigenvalues and eigenvectors + with the result of linalg.eig.""" + w, evec, info = zhbevd(self.bandmat_herm, compute_v=1) + evec_ = evec[:, argsort(w)] + assert_array_almost_equal(sort(w), self.w_herm_lin) + assert_array_almost_equal(abs(evec_), abs(self.evec_herm_lin)) + + def test_zhbevx(self): + """Compare zhbevx eigenvalues and eigenvectors + with the result of linalg.eig.""" + N, N = shape(self.herm_mat) + # Achtung: Argumente 0.0,0.0,range? + w, evec, num, ifail, info = zhbevx(self.bandmat_herm, 0.0, 0.0, 1, N, + compute_v=1, range=2) + evec_ = evec[:, argsort(w)] + assert_array_almost_equal(sort(w), self.w_herm_lin) + assert_array_almost_equal(abs(evec_), abs(self.evec_herm_lin)) + + def test_eigvals_banded(self): + """Compare eigenvalues of eigvals_banded with those of linalg.eig.""" + w_sym = eigvals_banded(self.bandmat_sym) + w_sym = w_sym.real + assert_array_almost_equal(sort(w_sym), self.w_sym_lin) + + w_herm = eigvals_banded(self.bandmat_herm) + w_herm = w_herm.real + assert_array_almost_equal(sort(w_herm), self.w_herm_lin) + + # extracting eigenvalues with respect to an index range + ind1 = 2 + ind2 = np.longlong(6) + w_sym_ind = eigvals_banded(self.bandmat_sym, + select='i', select_range=(ind1, ind2)) + assert_array_almost_equal(sort(w_sym_ind), + self.w_sym_lin[ind1:ind2+1]) + w_herm_ind = eigvals_banded(self.bandmat_herm, + select='i', select_range=(ind1, ind2)) + assert_array_almost_equal(sort(w_herm_ind), + self.w_herm_lin[ind1:ind2+1]) + + # extracting eigenvalues with respect to a value range + v_lower = self.w_sym_lin[ind1] - 1.0e-5 + v_upper = self.w_sym_lin[ind2] + 1.0e-5 + w_sym_val = eigvals_banded(self.bandmat_sym, + select='v', select_range=(v_lower, v_upper)) + assert_array_almost_equal(sort(w_sym_val), + self.w_sym_lin[ind1:ind2+1]) + + v_lower = self.w_herm_lin[ind1] - 1.0e-5 + v_upper = self.w_herm_lin[ind2] + 1.0e-5 + w_herm_val = eigvals_banded(self.bandmat_herm, + select='v', + select_range=(v_lower, v_upper)) + assert_array_almost_equal(sort(w_herm_val), + self.w_herm_lin[ind1:ind2+1]) + + w_sym = eigvals_banded(self.bandmat_sym, check_finite=False) + w_sym = w_sym.real + assert_array_almost_equal(sort(w_sym), self.w_sym_lin) + + def test_eig_banded(self): + """Compare eigenvalues and eigenvectors of eig_banded + with those of linalg.eig. """ + w_sym, evec_sym = eig_banded(self.bandmat_sym) + evec_sym_ = evec_sym[:, argsort(w_sym.real)] + assert_array_almost_equal(sort(w_sym), self.w_sym_lin) + assert_array_almost_equal(abs(evec_sym_), abs(self.evec_sym_lin)) + + w_herm, evec_herm = eig_banded(self.bandmat_herm) + evec_herm_ = evec_herm[:, argsort(w_herm.real)] + assert_array_almost_equal(sort(w_herm), self.w_herm_lin) + assert_array_almost_equal(abs(evec_herm_), abs(self.evec_herm_lin)) + + # extracting eigenvalues with respect to an index range + ind1 = 2 + ind2 = 6 + w_sym_ind, evec_sym_ind = eig_banded(self.bandmat_sym, + select='i', + select_range=(ind1, ind2)) + assert_array_almost_equal(sort(w_sym_ind), + self.w_sym_lin[ind1:ind2+1]) + assert_array_almost_equal(abs(evec_sym_ind), + abs(self.evec_sym_lin[:, ind1:ind2+1])) + + w_herm_ind, evec_herm_ind = eig_banded(self.bandmat_herm, + select='i', + select_range=(ind1, ind2)) + assert_array_almost_equal(sort(w_herm_ind), + self.w_herm_lin[ind1:ind2+1]) + assert_array_almost_equal(abs(evec_herm_ind), + abs(self.evec_herm_lin[:, ind1:ind2+1])) + + # extracting eigenvalues with respect to a value range + v_lower = self.w_sym_lin[ind1] - 1.0e-5 + v_upper = self.w_sym_lin[ind2] + 1.0e-5 + w_sym_val, evec_sym_val = eig_banded(self.bandmat_sym, + select='v', + select_range=(v_lower, v_upper)) + assert_array_almost_equal(sort(w_sym_val), + self.w_sym_lin[ind1:ind2+1]) + assert_array_almost_equal(abs(evec_sym_val), + abs(self.evec_sym_lin[:, ind1:ind2+1])) + + v_lower = self.w_herm_lin[ind1] - 1.0e-5 + v_upper = self.w_herm_lin[ind2] + 1.0e-5 + w_herm_val, evec_herm_val = eig_banded(self.bandmat_herm, + select='v', + select_range=(v_lower, v_upper)) + assert_array_almost_equal(sort(w_herm_val), + self.w_herm_lin[ind1:ind2+1]) + assert_array_almost_equal(abs(evec_herm_val), + abs(self.evec_herm_lin[:, ind1:ind2+1])) + + w_sym, evec_sym = eig_banded(self.bandmat_sym, check_finite=False) + evec_sym_ = evec_sym[:, argsort(w_sym.real)] + assert_array_almost_equal(sort(w_sym), self.w_sym_lin) + assert_array_almost_equal(abs(evec_sym_), abs(self.evec_sym_lin)) + + def test_dgbtrf(self): + """Compare dgbtrf LU factorisation with the LU factorisation result + of linalg.lu.""" + M, N = shape(self.real_mat) + lu_symm_band, ipiv, info = dgbtrf(self.bandmat_real, self.KL, self.KU) + + # extract matrix u from lu_symm_band + u = diag(lu_symm_band[2*self.KL, :]) + for i in range(self.KL + self.KU): + u += diag(lu_symm_band[2*self.KL-1-i, i+1:N], i+1) + + p_lin, l_lin, u_lin = lu(self.real_mat, permute_l=0) + assert_array_almost_equal(u, u_lin) + + def test_zgbtrf(self): + """Compare zgbtrf LU factorisation with the LU factorisation result + of linalg.lu.""" + M, N = shape(self.comp_mat) + lu_symm_band, ipiv, info = zgbtrf(self.bandmat_comp, self.KL, self.KU) + + # extract matrix u from lu_symm_band + u = diag(lu_symm_band[2*self.KL, :]) + for i in range(self.KL + self.KU): + u += diag(lu_symm_band[2*self.KL-1-i, i+1:N], i+1) + + p_lin, l_lin, u_lin = lu(self.comp_mat, permute_l=0) + assert_array_almost_equal(u, u_lin) + + def test_dgbtrs(self): + """Compare dgbtrs solutions for linear equation system A*x = b + with solutions of linalg.solve.""" + + lu_symm_band, ipiv, info = dgbtrf(self.bandmat_real, self.KL, self.KU) + y, info = dgbtrs(lu_symm_band, self.KL, self.KU, self.b, ipiv) + + y_lin = linalg.solve(self.real_mat, self.b) + assert_array_almost_equal(y, y_lin) + + def test_zgbtrs(self): + """Compare zgbtrs solutions for linear equation system A*x = b + with solutions of linalg.solve.""" + + lu_symm_band, ipiv, info = zgbtrf(self.bandmat_comp, self.KL, self.KU) + y, info = zgbtrs(lu_symm_band, self.KL, self.KU, self.bc, ipiv) + + y_lin = linalg.solve(self.comp_mat, self.bc) + assert_array_almost_equal(y, y_lin) + + @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) + def test_empty(self, dt): + a_band = np.empty((0, 0), dtype=dt) + w, v = eig_banded(a_band) + + w_n, v_n = eig_banded(np.array([[0, 0], [1, 1]], dtype=dt)) + + assert w.shape == (0,) + assert w.dtype == w_n.dtype + + assert v.shape == (0, 0) + assert v.dtype == v_n.dtype + + w = eig_banded(a_band, eigvals_only=True) + assert w.shape == (0,) + assert w.dtype == w_n.dtype + +class TestEigTridiagonal: + def setup_method(self): + self.create_trimat() + + def create_trimat(self): + """Create the full matrix `self.fullmat`, `self.d`, and `self.e`.""" + N = 10 + + # symmetric band matrix + self.d = full(N, 1.0) + self.e = full(N-1, -1.0) + self.full_mat = (diag(self.d) + diag(self.e, -1) + diag(self.e, 1)) + + ew, ev = linalg.eig(self.full_mat) + ew = ew.real + args = argsort(ew) + self.w = ew[args] + self.evec = ev[:, args] + + def test_degenerate(self): + """Test error conditions.""" + # Wrong sizes + assert_raises(ValueError, eigvalsh_tridiagonal, self.d, self.e[:-1]) + # Must be real + assert_raises(TypeError, eigvalsh_tridiagonal, self.d, self.e * 1j) + # Bad driver + assert_raises(TypeError, eigvalsh_tridiagonal, self.d, self.e, + lapack_driver=1.) + assert_raises(ValueError, eigvalsh_tridiagonal, self.d, self.e, + lapack_driver='foo') + # Bad bounds + assert_raises(ValueError, eigvalsh_tridiagonal, self.d, self.e, + select='i', select_range=(0, -1)) + + def test_eigvalsh_tridiagonal(self): + """Compare eigenvalues of eigvalsh_tridiagonal with those of eig.""" + # can't use ?STERF with subselection + for driver in ('sterf', 'stev', 'stebz', 'stemr', 'auto'): + w = eigvalsh_tridiagonal(self.d, self.e, lapack_driver=driver) + assert_array_almost_equal(sort(w), self.w) + + for driver in ('sterf', 'stev'): + assert_raises(ValueError, eigvalsh_tridiagonal, self.d, self.e, + lapack_driver=driver, select='i', + select_range=(0, 1)) + for driver in ('stebz', 'stemr', 'auto'): + # extracting eigenvalues with respect to the full index range + w_ind = eigvalsh_tridiagonal( + self.d, self.e, select='i', select_range=(0, len(self.d)-1), + lapack_driver=driver) + assert_array_almost_equal(sort(w_ind), self.w) + + # extracting eigenvalues with respect to an index range + ind1 = 2 + ind2 = 6 + w_ind = eigvalsh_tridiagonal( + self.d, self.e, select='i', select_range=(ind1, ind2), + lapack_driver=driver) + assert_array_almost_equal(sort(w_ind), self.w[ind1:ind2+1]) + + # extracting eigenvalues with respect to a value range + v_lower = self.w[ind1] - 1.0e-5 + v_upper = self.w[ind2] + 1.0e-5 + w_val = eigvalsh_tridiagonal( + self.d, self.e, select='v', select_range=(v_lower, v_upper), + lapack_driver=driver) + assert_array_almost_equal(sort(w_val), self.w[ind1:ind2+1]) + + def test_eigh_tridiagonal(self): + """Compare eigenvalues and eigenvectors of eigh_tridiagonal + with those of eig. """ + # can't use ?STERF when eigenvectors are requested + assert_raises(ValueError, eigh_tridiagonal, self.d, self.e, + lapack_driver='sterf') + for driver in ('stebz', 'stev', 'stemr', 'auto'): + w, evec = eigh_tridiagonal(self.d, self.e, lapack_driver=driver) + evec_ = evec[:, argsort(w)] + assert_array_almost_equal(sort(w), self.w) + assert_array_almost_equal(abs(evec_), abs(self.evec)) + + assert_raises(ValueError, eigh_tridiagonal, self.d, self.e, + lapack_driver='stev', select='i', select_range=(0, 1)) + for driver in ('stebz', 'stemr', 'auto'): + # extracting eigenvalues with respect to an index range + ind1 = 0 + ind2 = len(self.d)-1 + w, evec = eigh_tridiagonal( + self.d, self.e, select='i', select_range=(ind1, ind2), + lapack_driver=driver) + assert_array_almost_equal(sort(w), self.w) + assert_array_almost_equal(abs(evec), abs(self.evec)) + ind1 = 2 + ind2 = 6 + w, evec = eigh_tridiagonal( + self.d, self.e, select='i', select_range=(ind1, ind2), + lapack_driver=driver) + assert_array_almost_equal(sort(w), self.w[ind1:ind2+1]) + assert_array_almost_equal(abs(evec), + abs(self.evec[:, ind1:ind2+1])) + + # extracting eigenvalues with respect to a value range + v_lower = self.w[ind1] - 1.0e-5 + v_upper = self.w[ind2] + 1.0e-5 + w, evec = eigh_tridiagonal( + self.d, self.e, select='v', select_range=(v_lower, v_upper), + lapack_driver=driver) + assert_array_almost_equal(sort(w), self.w[ind1:ind2+1]) + assert_array_almost_equal(abs(evec), + abs(self.evec[:, ind1:ind2+1])) + + def test_eigh_tridiagonal_1x1(self): + """See gh-20075""" + a = np.array([-2.0]) + b = np.array([]) + x = eigh_tridiagonal(a, b, eigvals_only=True) + assert x.ndim == 1 + assert_allclose(x, a) + x, V = eigh_tridiagonal(a, b, select="i", select_range=(0, 0)) + assert x.ndim == 1 + assert V.ndim == 2 + assert_allclose(x, a) + assert_allclose(V, array([[1.]])) + + x, V = eigh_tridiagonal(a, b, select="v", select_range=(-2, 0)) + assert x.size == 0 + assert x.shape == (0,) + assert V.shape == (1, 0) + + +class TestEigh: + def setup_class(self): + np.random.seed(1234) + + def test_wrong_inputs(self): + # Nonsquare a + assert_raises(ValueError, eigh, np.ones([1, 2])) + # Nonsquare b + assert_raises(ValueError, eigh, np.ones([2, 2]), np.ones([2, 1])) + # Incompatible a, b sizes + assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([2, 2])) + # Wrong type parameter for generalized problem + assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]), + type=4) + # Both value and index subsets requested + assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]), + subset_by_value=[1, 2], subset_by_index=[2, 4]) + # Invalid upper index spec + assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]), + subset_by_index=[0, 4]) + # Invalid lower index + assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]), + subset_by_index=[-2, 2]) + # Invalid index spec #2 + assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]), + subset_by_index=[2, 0]) + # Invalid value spec + assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]), + subset_by_value=[2, 0]) + # Invalid driver name + assert_raises(ValueError, eigh, np.ones([2, 2]), driver='wrong') + # Generalized driver selection without b + assert_raises(ValueError, eigh, np.ones([3, 3]), None, driver='gvx') + # Standard driver with b + assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]), + driver='evr') + # Subset request from invalid driver + assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]), + driver='gvd', subset_by_index=[1, 2]) + assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]), + driver='gvd', subset_by_index=[1, 2]) + + def test_nonpositive_b(self): + assert_raises(LinAlgError, eigh, np.ones([3, 3]), np.ones([3, 3])) + + # index based subsets are done in the legacy test_eigh() + def test_value_subsets(self): + for ind, dt in enumerate(DTYPES): + + a = _random_hermitian_matrix(20, dtype=dt) + w, v = eigh(a, subset_by_value=[-2, 2]) + assert_equal(v.shape[1], len(w)) + assert all((w > -2) & (w < 2)) + + b = _random_hermitian_matrix(20, posdef=True, dtype=dt) + w, v = eigh(a, b, subset_by_value=[-2, 2]) + assert_equal(v.shape[1], len(w)) + assert all((w > -2) & (w < 2)) + + def test_eigh_integer(self): + a = array([[1, 2], [2, 7]]) + b = array([[3, 1], [1, 5]]) + w, z = eigh(a) + w, z = eigh(a, b) + + def test_eigh_of_sparse(self): + # This tests the rejection of inputs that eigh cannot currently handle. + import scipy.sparse + a = scipy.sparse.identity(2).tocsc() + b = np.atleast_2d(a) + assert_raises(ValueError, eigh, a) + assert_raises(ValueError, eigh, b) + + @pytest.mark.parametrize('dtype_', DTYPES) + @pytest.mark.parametrize('driver', ("ev", "evd", "evr", "evx")) + def test_various_drivers_standard(self, driver, dtype_): + a = _random_hermitian_matrix(n=20, dtype=dtype_) + w, v = eigh(a, driver=driver) + assert_allclose(a @ v - (v * w), 0., + atol=1000*np.finfo(dtype_).eps, + rtol=0.) + + @pytest.mark.parametrize('driver', ("ev", "evd", "evr", "evx")) + def test_1x1_lwork(self, driver): + w, v = eigh([[1]], driver=driver) + assert_allclose(w, array([1.]), atol=1e-15) + assert_allclose(v, array([[1.]]), atol=1e-15) + + # complex case now + w, v = eigh([[1j]], driver=driver) + assert_allclose(w, array([0]), atol=1e-15) + assert_allclose(v, array([[1.]]), atol=1e-15) + + @pytest.mark.parametrize('type', (1, 2, 3)) + @pytest.mark.parametrize('driver', ("gv", "gvd", "gvx")) + def test_various_drivers_generalized(self, driver, type): + atol = np.spacing(5000.) + a = _random_hermitian_matrix(20) + b = _random_hermitian_matrix(20, posdef=True) + w, v = eigh(a=a, b=b, driver=driver, type=type) + if type == 1: + assert_allclose(a @ v - w*(b @ v), 0., atol=atol, rtol=0.) + elif type == 2: + assert_allclose(a @ b @ v - v * w, 0., atol=atol, rtol=0.) + else: + assert_allclose(b @ a @ v - v * w, 0., atol=atol, rtol=0.) + + def test_eigvalsh_new_args(self): + a = _random_hermitian_matrix(5) + w = eigvalsh(a, subset_by_index=[1, 2]) + assert_equal(len(w), 2) + + w2 = eigvalsh(a, subset_by_index=[1, 2]) + assert_equal(len(w2), 2) + assert_allclose(w, w2) + + b = np.diag([1, 1.2, 1.3, 1.5, 2]) + w3 = eigvalsh(b, subset_by_value=[1, 1.4]) + assert_equal(len(w3), 2) + assert_allclose(w3, np.array([1.2, 1.3])) + + @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) + def test_empty(self, dt): + a = np.empty((0, 0), dtype=dt) + w, v = eigh(a) + + w_n, v_n = eigh(np.eye(2, dtype=dt)) + + assert w.shape == (0,) + assert w.dtype == w_n.dtype + + assert v.shape == (0, 0) + assert v.dtype == v_n.dtype + + w = eigh(a, eigvals_only=True) + assert_allclose(w, np.empty((0,))) + + assert w.shape == (0,) + assert w.dtype == w_n.dtype + +class TestSVD_GESDD: + lapack_driver = 'gesdd' + + def test_degenerate(self): + assert_raises(TypeError, svd, [[1.]], lapack_driver=1.) + assert_raises(ValueError, svd, [[1.]], lapack_driver='foo') + + def test_simple(self): + a = [[1, 2, 3], [1, 20, 3], [2, 5, 6]] + for full_matrices in (True, False): + u, s, vh = svd(a, full_matrices=full_matrices, + lapack_driver=self.lapack_driver) + assert_array_almost_equal(u.T @ u, eye(3)) + assert_array_almost_equal(vh.T @ vh, eye(3)) + sigma = zeros((u.shape[0], vh.shape[0]), s.dtype.char) + for i in range(len(s)): + sigma[i, i] = s[i] + assert_array_almost_equal(u @ sigma @ vh, a) + + def test_simple_singular(self): + a = [[1, 2, 3], [1, 2, 3], [2, 5, 6]] + for full_matrices in (True, False): + u, s, vh = svd(a, full_matrices=full_matrices, + lapack_driver=self.lapack_driver) + assert_array_almost_equal(u.T @ u, eye(3)) + assert_array_almost_equal(vh.T @ vh, eye(3)) + sigma = zeros((u.shape[0], vh.shape[0]), s.dtype.char) + for i in range(len(s)): + sigma[i, i] = s[i] + assert_array_almost_equal(u @ sigma @ vh, a) + + def test_simple_underdet(self): + a = [[1, 2, 3], [4, 5, 6]] + for full_matrices in (True, False): + u, s, vh = svd(a, full_matrices=full_matrices, + lapack_driver=self.lapack_driver) + assert_array_almost_equal(u.T @ u, eye(u.shape[0])) + sigma = zeros((u.shape[0], vh.shape[0]), s.dtype.char) + for i in range(len(s)): + sigma[i, i] = s[i] + assert_array_almost_equal(u @ sigma @ vh, a) + + def test_simple_overdet(self): + a = [[1, 2], [4, 5], [3, 4]] + for full_matrices in (True, False): + u, s, vh = svd(a, full_matrices=full_matrices, + lapack_driver=self.lapack_driver) + assert_array_almost_equal(u.T @ u, eye(u.shape[1])) + assert_array_almost_equal(vh.T @ vh, eye(2)) + sigma = zeros((u.shape[1], vh.shape[0]), s.dtype.char) + for i in range(len(s)): + sigma[i, i] = s[i] + assert_array_almost_equal(u @ sigma @ vh, a) + + def test_random(self): + rng = np.random.RandomState(1234) + n = 20 + m = 15 + for i in range(3): + for a in [rng.random([n, m]), rng.random([m, n])]: + for full_matrices in (True, False): + u, s, vh = svd(a, full_matrices=full_matrices, + lapack_driver=self.lapack_driver) + assert_array_almost_equal(u.T @ u, eye(u.shape[1])) + assert_array_almost_equal(vh @ vh.T, eye(vh.shape[0])) + sigma = zeros((u.shape[1], vh.shape[0]), s.dtype.char) + for i in range(len(s)): + sigma[i, i] = s[i] + assert_array_almost_equal(u @ sigma @ vh, a) + + def test_simple_complex(self): + a = [[1, 2, 3], [1, 2j, 3], [2, 5, 6]] + for full_matrices in (True, False): + u, s, vh = svd(a, full_matrices=full_matrices, + lapack_driver=self.lapack_driver) + assert_array_almost_equal(u.conj().T @ u, eye(u.shape[1])) + assert_array_almost_equal(vh.conj().T @ vh, eye(vh.shape[0])) + sigma = zeros((u.shape[0], vh.shape[0]), s.dtype.char) + for i in range(len(s)): + sigma[i, i] = s[i] + assert_array_almost_equal(u @ sigma @ vh, a) + + def test_random_complex(self): + rng = np.random.RandomState(1234) + n = 20 + m = 15 + for i in range(3): + for full_matrices in (True, False): + for a in [rng.random([n, m]), rng.random([m, n])]: + a = a + 1j*rng.random(list(a.shape)) + u, s, vh = svd(a, full_matrices=full_matrices, + lapack_driver=self.lapack_driver) + assert_array_almost_equal(u.conj().T @ u, + eye(u.shape[1])) + # This fails when [m,n] + # assert_array_almost_equal(vh.conj().T @ vh, + # eye(len(vh),dtype=vh.dtype.char)) + sigma = zeros((u.shape[1], vh.shape[0]), s.dtype.char) + for i in range(len(s)): + sigma[i, i] = s[i] + assert_array_almost_equal(u @ sigma @ vh, a) + + def test_crash_1580(self): + rng = np.random.RandomState(1234) + sizes = [(13, 23), (30, 50), (60, 100)] + for sz in sizes: + for dt in [np.float32, np.float64, np.complex64, np.complex128]: + a = rng.rand(*sz).astype(dt) + # should not crash + svd(a, lapack_driver=self.lapack_driver) + + def test_check_finite(self): + a = [[1, 2, 3], [1, 20, 3], [2, 5, 6]] + u, s, vh = svd(a, check_finite=False, lapack_driver=self.lapack_driver) + assert_array_almost_equal(u.T @ u, eye(3)) + assert_array_almost_equal(vh.T @ vh, eye(3)) + sigma = zeros((u.shape[0], vh.shape[0]), s.dtype.char) + for i in range(len(s)): + sigma[i, i] = s[i] + assert_array_almost_equal(u @ sigma @ vh, a) + + def test_gh_5039(self): + # This is a smoke test for https://github.com/scipy/scipy/issues/5039 + # + # The following is reported to raise "ValueError: On entry to DGESDD + # parameter number 12 had an illegal value". + # `interp1d([1,2,3,4], [1,2,3,4], kind='cubic')` + # This is reported to only show up on LAPACK 3.0.3. + # + # The matrix below is taken from the call to + # `B = _fitpack._bsplmat(order, xk)` in interpolate._find_smoothest + b = np.array( + [[0.16666667, 0.66666667, 0.16666667, 0., 0., 0.], + [0., 0.16666667, 0.66666667, 0.16666667, 0., 0.], + [0., 0., 0.16666667, 0.66666667, 0.16666667, 0.], + [0., 0., 0., 0.16666667, 0.66666667, 0.16666667]]) + svd(b, lapack_driver=self.lapack_driver) + + @pytest.mark.skipif(not HAS_ILP64, reason="64-bit LAPACK required") + @pytest.mark.slow + def test_large_matrix(self): + check_free_memory(free_mb=17000) + A = np.zeros([1, 2**31], dtype=np.float32) + A[0, -1] = 1 + u, s, vh = svd(A, full_matrices=False) + assert_allclose(s[0], 1.0) + assert_allclose(u[0, 0] * vh[0, -1], 1.0) + + @pytest.mark.parametrize("m", [0, 1, 2]) + @pytest.mark.parametrize("n", [0, 1, 2]) + @pytest.mark.parametrize('dtype', DTYPES) + def test_shape_dtype(self, m, n, dtype): + a = np.zeros((m, n), dtype=dtype) + k = min(m, n) + dchar = a.dtype.char + real_dchar = dchar.lower() if dchar in 'FD' else dchar + + u, s, v = svd(a) + assert_equal(u.shape, (m, m)) + assert_equal(u.dtype, dtype) + assert_equal(s.shape, (k,)) + assert_equal(s.dtype, np.dtype(real_dchar)) + assert_equal(v.shape, (n, n)) + assert_equal(v.dtype, dtype) + + u, s, v = svd(a, full_matrices=False) + assert_equal(u.shape, (m, k)) + assert_equal(u.dtype, dtype) + assert_equal(s.shape, (k,)) + assert_equal(s.dtype, np.dtype(real_dchar)) + assert_equal(v.shape, (k, n)) + assert_equal(v.dtype, dtype) + + s = svd(a, compute_uv=False) + assert_equal(s.shape, (k,)) + assert_equal(s.dtype, np.dtype(real_dchar)) + + @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) + @pytest.mark.parametrize(("m", "n"), [(0, 0), (0, 2), (2, 0)]) + def test_empty(self, dt, m, n): + a0 = np.eye(3, dtype=dt) + u0, s0, v0 = svd(a0) + + a = np.empty((m, n), dtype=dt) + u, s, v = svd(a) + assert_allclose(u, np.identity(m)) + assert_allclose(s, np.empty((0,))) + assert_allclose(v, np.identity(n)) + + assert u.dtype == u0.dtype + assert v.dtype == v0.dtype + assert s.dtype == s0.dtype + + u, s, v = svd(a, full_matrices=False) + assert_allclose(u, np.empty((m, 0))) + assert_allclose(s, np.empty((0,))) + assert_allclose(v, np.empty((0, n))) + + assert u.dtype == u0.dtype + assert v.dtype == v0.dtype + assert s.dtype == s0.dtype + + s = svd(a, compute_uv=False) + assert_allclose(s, np.empty((0,))) + + assert s.dtype == s0.dtype + +class TestSVD_GESVD(TestSVD_GESDD): + lapack_driver = 'gesvd' + + +# Allocating an array of such a size leads to _ArrayMemoryError(s) +# since the maximum memory that can be in 32-bit (WASM) is 4GB +@pytest.mark.skipif(IS_WASM, reason="out of memory in WASM") +@pytest.mark.fail_slow(10) +def test_svd_gesdd_nofegfault(): + # svd(a) with {U,VT}.size > INT_MAX does not segfault + # cf https://github.com/scipy/scipy/issues/14001 + df=np.ones((4799, 53130), dtype=np.float64) + with assert_raises(ValueError): + svd(df) + + +class TestSVDVals: + + @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) + def test_empty(self, dt): + for a in [[]], np.empty((2, 0)), np.ones((0, 3)): + a = np.array(a, dtype=dt) + s = svdvals(a) + assert_equal(s, np.empty(0)) + + s0 = svdvals(np.eye(2, dtype=dt)) + assert s.dtype == s0.dtype + + def test_simple(self): + a = [[1, 2, 3], [1, 2, 3], [2, 5, 6]] + s = svdvals(a) + assert_(len(s) == 3) + assert_(s[0] >= s[1] >= s[2]) + + def test_simple_underdet(self): + a = [[1, 2, 3], [4, 5, 6]] + s = svdvals(a) + assert_(len(s) == 2) + assert_(s[0] >= s[1]) + + def test_simple_overdet(self): + a = [[1, 2], [4, 5], [3, 4]] + s = svdvals(a) + assert_(len(s) == 2) + assert_(s[0] >= s[1]) + + def test_simple_complex(self): + a = [[1, 2, 3], [1, 20, 3j], [2, 5, 6]] + s = svdvals(a) + assert_(len(s) == 3) + assert_(s[0] >= s[1] >= s[2]) + + def test_simple_underdet_complex(self): + a = [[1, 2, 3], [4, 5j, 6]] + s = svdvals(a) + assert_(len(s) == 2) + assert_(s[0] >= s[1]) + + def test_simple_overdet_complex(self): + a = [[1, 2], [4, 5], [3j, 4]] + s = svdvals(a) + assert_(len(s) == 2) + assert_(s[0] >= s[1]) + + def test_check_finite(self): + a = [[1, 2, 3], [1, 2, 3], [2, 5, 6]] + s = svdvals(a, check_finite=False) + assert_(len(s) == 3) + assert_(s[0] >= s[1] >= s[2]) + + @pytest.mark.slow + def test_crash_2609(self): + np.random.seed(1234) + a = np.random.rand(1500, 2800) + # Shouldn't crash: + svdvals(a) + + +class TestDiagSVD: + + def test_simple(self): + assert_array_almost_equal(diagsvd([1, 0, 0], 3, 3), + [[1, 0, 0], [0, 0, 0], [0, 0, 0]]) + + +class TestQR: + def test_simple(self): + a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]] + q, r = qr(a) + assert_array_almost_equal(q.T @ q, eye(3)) + assert_array_almost_equal(q @ r, a) + + def test_simple_left(self): + a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]] + q, r = qr(a) + c = [1, 2, 3] + qc, r2 = qr_multiply(a, c, "left") + assert_array_almost_equal(q @ c, qc) + assert_array_almost_equal(r, r2) + qc, r2 = qr_multiply(a, eye(3), "left") + assert_array_almost_equal(q, qc) + + def test_simple_right(self): + a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]] + q, r = qr(a) + c = [1, 2, 3] + qc, r2 = qr_multiply(a, c) + assert_array_almost_equal(c @ q, qc) + assert_array_almost_equal(r, r2) + qc, r = qr_multiply(a, eye(3)) + assert_array_almost_equal(q, qc) + + def test_simple_pivoting(self): + a = np.asarray([[8, 2, 3], [2, 9, 3], [5, 3, 6]]) + q, r, p = qr(a, pivoting=True) + d = abs(diag(r)) + assert_(np.all(d[1:] <= d[:-1])) + assert_array_almost_equal(q.T @ q, eye(3)) + assert_array_almost_equal(q @ r, a[:, p]) + q2, r2 = qr(a[:, p]) + assert_array_almost_equal(q, q2) + assert_array_almost_equal(r, r2) + + def test_simple_left_pivoting(self): + a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]] + q, r, jpvt = qr(a, pivoting=True) + c = [1, 2, 3] + qc, r, jpvt = qr_multiply(a, c, "left", True) + assert_array_almost_equal(q @ c, qc) + + def test_simple_right_pivoting(self): + a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]] + q, r, jpvt = qr(a, pivoting=True) + c = [1, 2, 3] + qc, r, jpvt = qr_multiply(a, c, pivoting=True) + assert_array_almost_equal(c @ q, qc) + + def test_simple_trap(self): + a = [[8, 2, 3], [2, 9, 3]] + q, r = qr(a) + assert_array_almost_equal(q.T @ q, eye(2)) + assert_array_almost_equal(q @ r, a) + + def test_simple_trap_pivoting(self): + a = np.asarray([[8, 2, 3], [2, 9, 3]]) + q, r, p = qr(a, pivoting=True) + d = abs(diag(r)) + assert_(np.all(d[1:] <= d[:-1])) + assert_array_almost_equal(q.T @ q, eye(2)) + assert_array_almost_equal(q @ r, a[:, p]) + q2, r2 = qr(a[:, p]) + assert_array_almost_equal(q, q2) + assert_array_almost_equal(r, r2) + + def test_simple_tall(self): + # full version + a = [[8, 2], [2, 9], [5, 3]] + q, r = qr(a) + assert_array_almost_equal(q.T @ q, eye(3)) + assert_array_almost_equal(q @ r, a) + + def test_simple_tall_pivoting(self): + # full version pivoting + a = np.asarray([[8, 2], [2, 9], [5, 3]]) + q, r, p = qr(a, pivoting=True) + d = abs(diag(r)) + assert_(np.all(d[1:] <= d[:-1])) + assert_array_almost_equal(q.T @ q, eye(3)) + assert_array_almost_equal(q @ r, a[:, p]) + q2, r2 = qr(a[:, p]) + assert_array_almost_equal(q, q2) + assert_array_almost_equal(r, r2) + + def test_simple_tall_e(self): + # economy version + a = [[8, 2], [2, 9], [5, 3]] + q, r = qr(a, mode='economic') + assert_array_almost_equal(q.T @ q, eye(2)) + assert_array_almost_equal(q @ r, a) + assert_equal(q.shape, (3, 2)) + assert_equal(r.shape, (2, 2)) + + def test_simple_tall_e_pivoting(self): + # economy version pivoting + a = np.asarray([[8, 2], [2, 9], [5, 3]]) + q, r, p = qr(a, pivoting=True, mode='economic') + d = abs(diag(r)) + assert_(np.all(d[1:] <= d[:-1])) + assert_array_almost_equal(q.T @ q, eye(2)) + assert_array_almost_equal(q @ r, a[:, p]) + q2, r2 = qr(a[:, p], mode='economic') + assert_array_almost_equal(q, q2) + assert_array_almost_equal(r, r2) + + def test_simple_tall_left(self): + a = [[8, 2], [2, 9], [5, 3]] + q, r = qr(a, mode="economic") + c = [1, 2] + qc, r2 = qr_multiply(a, c, "left") + assert_array_almost_equal(q @ c, qc) + assert_array_almost_equal(r, r2) + c = array([1, 2, 0]) + qc, r2 = qr_multiply(a, c, "left", overwrite_c=True) + assert_array_almost_equal(q @ c[:2], qc) + qc, r = qr_multiply(a, eye(2), "left") + assert_array_almost_equal(qc, q) + + def test_simple_tall_left_pivoting(self): + a = [[8, 2], [2, 9], [5, 3]] + q, r, jpvt = qr(a, mode="economic", pivoting=True) + c = [1, 2] + qc, r, kpvt = qr_multiply(a, c, "left", True) + assert_array_equal(jpvt, kpvt) + assert_array_almost_equal(q @ c, qc) + qc, r, jpvt = qr_multiply(a, eye(2), "left", True) + assert_array_almost_equal(qc, q) + + def test_simple_tall_right(self): + a = [[8, 2], [2, 9], [5, 3]] + q, r = qr(a, mode="economic") + c = [1, 2, 3] + cq, r2 = qr_multiply(a, c) + assert_array_almost_equal(c @ q, cq) + assert_array_almost_equal(r, r2) + cq, r = qr_multiply(a, eye(3)) + assert_array_almost_equal(cq, q) + + def test_simple_tall_right_pivoting(self): + a = [[8, 2], [2, 9], [5, 3]] + q, r, jpvt = qr(a, pivoting=True, mode="economic") + c = [1, 2, 3] + cq, r, jpvt = qr_multiply(a, c, pivoting=True) + assert_array_almost_equal(c @ q, cq) + cq, r, jpvt = qr_multiply(a, eye(3), pivoting=True) + assert_array_almost_equal(cq, q) + + def test_simple_fat(self): + # full version + a = [[8, 2, 5], [2, 9, 3]] + q, r = qr(a) + assert_array_almost_equal(q.T @ q, eye(2)) + assert_array_almost_equal(q @ r, a) + assert_equal(q.shape, (2, 2)) + assert_equal(r.shape, (2, 3)) + + def test_simple_fat_pivoting(self): + # full version pivoting + a = np.asarray([[8, 2, 5], [2, 9, 3]]) + q, r, p = qr(a, pivoting=True) + d = abs(diag(r)) + assert_(np.all(d[1:] <= d[:-1])) + assert_array_almost_equal(q.T @ q, eye(2)) + assert_array_almost_equal(q @ r, a[:, p]) + assert_equal(q.shape, (2, 2)) + assert_equal(r.shape, (2, 3)) + q2, r2 = qr(a[:, p]) + assert_array_almost_equal(q, q2) + assert_array_almost_equal(r, r2) + + def test_simple_fat_e(self): + # economy version + a = [[8, 2, 3], [2, 9, 5]] + q, r = qr(a, mode='economic') + assert_array_almost_equal(q.T @ q, eye(2)) + assert_array_almost_equal(q @ r, a) + assert_equal(q.shape, (2, 2)) + assert_equal(r.shape, (2, 3)) + + def test_simple_fat_e_pivoting(self): + # economy version pivoting + a = np.asarray([[8, 2, 3], [2, 9, 5]]) + q, r, p = qr(a, pivoting=True, mode='economic') + d = abs(diag(r)) + assert_(np.all(d[1:] <= d[:-1])) + assert_array_almost_equal(q.T @ q, eye(2)) + assert_array_almost_equal(q @ r, a[:, p]) + assert_equal(q.shape, (2, 2)) + assert_equal(r.shape, (2, 3)) + q2, r2 = qr(a[:, p], mode='economic') + assert_array_almost_equal(q, q2) + assert_array_almost_equal(r, r2) + + def test_simple_fat_left(self): + a = [[8, 2, 3], [2, 9, 5]] + q, r = qr(a, mode="economic") + c = [1, 2] + qc, r2 = qr_multiply(a, c, "left") + assert_array_almost_equal(q @ c, qc) + assert_array_almost_equal(r, r2) + qc, r = qr_multiply(a, eye(2), "left") + assert_array_almost_equal(qc, q) + + def test_simple_fat_left_pivoting(self): + a = [[8, 2, 3], [2, 9, 5]] + q, r, jpvt = qr(a, mode="economic", pivoting=True) + c = [1, 2] + qc, r, jpvt = qr_multiply(a, c, "left", True) + assert_array_almost_equal(q @ c, qc) + qc, r, jpvt = qr_multiply(a, eye(2), "left", True) + assert_array_almost_equal(qc, q) + + def test_simple_fat_right(self): + a = [[8, 2, 3], [2, 9, 5]] + q, r = qr(a, mode="economic") + c = [1, 2] + cq, r2 = qr_multiply(a, c) + assert_array_almost_equal(c @ q, cq) + assert_array_almost_equal(r, r2) + cq, r = qr_multiply(a, eye(2)) + assert_array_almost_equal(cq, q) + + def test_simple_fat_right_pivoting(self): + a = [[8, 2, 3], [2, 9, 5]] + q, r, jpvt = qr(a, pivoting=True, mode="economic") + c = [1, 2] + cq, r, jpvt = qr_multiply(a, c, pivoting=True) + assert_array_almost_equal(c @ q, cq) + cq, r, jpvt = qr_multiply(a, eye(2), pivoting=True) + assert_array_almost_equal(cq, q) + + def test_simple_complex(self): + a = [[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]] + q, r = qr(a) + assert_array_almost_equal(q.conj().T @ q, eye(3)) + assert_array_almost_equal(q @ r, a) + + def test_simple_complex_left(self): + a = [[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]] + q, r = qr(a) + c = [1, 2, 3+4j] + qc, r = qr_multiply(a, c, "left") + assert_array_almost_equal(q @ c, qc) + qc, r = qr_multiply(a, eye(3), "left") + assert_array_almost_equal(q, qc) + + def test_simple_complex_right(self): + a = [[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]] + q, r = qr(a) + c = [1, 2, 3+4j] + qc, r = qr_multiply(a, c) + assert_array_almost_equal(c @ q, qc) + qc, r = qr_multiply(a, eye(3)) + assert_array_almost_equal(q, qc) + + def test_simple_tall_complex_left(self): + a = [[8, 2+3j], [2, 9], [5+7j, 3]] + q, r = qr(a, mode="economic") + c = [1, 2+2j] + qc, r2 = qr_multiply(a, c, "left") + assert_array_almost_equal(q @ c, qc) + assert_array_almost_equal(r, r2) + c = array([1, 2, 0]) + qc, r2 = qr_multiply(a, c, "left", overwrite_c=True) + assert_array_almost_equal(q @ c[:2], qc) + qc, r = qr_multiply(a, eye(2), "left") + assert_array_almost_equal(qc, q) + + def test_simple_complex_left_conjugate(self): + a = [[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]] + q, r = qr(a) + c = [1, 2, 3+4j] + qc, r = qr_multiply(a, c, "left", conjugate=True) + assert_array_almost_equal(q.conj() @ c, qc) + + def test_simple_complex_tall_left_conjugate(self): + a = [[3, 3+4j], [5, 2+2j], [3, 2]] + q, r = qr(a, mode='economic') + c = [1, 3+4j] + qc, r = qr_multiply(a, c, "left", conjugate=True) + assert_array_almost_equal(q.conj() @ c, qc) + + def test_simple_complex_right_conjugate(self): + a = [[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]] + q, r = qr(a) + c = np.array([1, 2, 3+4j]) + qc, r = qr_multiply(a, c, conjugate=True) + assert_array_almost_equal(c @ q.conj(), qc) + + def test_simple_complex_pivoting(self): + a = array([[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]]) + q, r, p = qr(a, pivoting=True) + d = abs(diag(r)) + assert_(np.all(d[1:] <= d[:-1])) + assert_array_almost_equal(q.conj().T @ q, eye(3)) + assert_array_almost_equal(q @ r, a[:, p]) + q2, r2 = qr(a[:, p]) + assert_array_almost_equal(q, q2) + assert_array_almost_equal(r, r2) + + def test_simple_complex_left_pivoting(self): + a = array([[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]]) + q, r, jpvt = qr(a, pivoting=True) + c = [1, 2, 3+4j] + qc, r, jpvt = qr_multiply(a, c, "left", True) + assert_array_almost_equal(q @ c, qc) + + def test_simple_complex_right_pivoting(self): + a = array([[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]]) + q, r, jpvt = qr(a, pivoting=True) + c = [1, 2, 3+4j] + qc, r, jpvt = qr_multiply(a, c, pivoting=True) + assert_array_almost_equal(c @ q, qc) + + def test_random(self): + rng = np.random.RandomState(1234) + n = 20 + for k in range(2): + a = rng.random([n, n]) + q, r = qr(a) + assert_array_almost_equal(q.T @ q, eye(n)) + assert_array_almost_equal(q @ r, a) + + def test_random_left(self): + rng = np.random.RandomState(1234) + n = 20 + for k in range(2): + a = rng.random([n, n]) + q, r = qr(a) + c = rng.random([n]) + qc, r = qr_multiply(a, c, "left") + assert_array_almost_equal(q @ c, qc) + qc, r = qr_multiply(a, eye(n), "left") + assert_array_almost_equal(q, qc) + + def test_random_right(self): + rng = np.random.RandomState(1234) + n = 20 + for k in range(2): + a = rng.random([n, n]) + q, r = qr(a) + c = rng.random([n]) + cq, r = qr_multiply(a, c) + assert_array_almost_equal(c @ q, cq) + cq, r = qr_multiply(a, eye(n)) + assert_array_almost_equal(q, cq) + + def test_random_pivoting(self): + rng = np.random.RandomState(1234) + n = 20 + for k in range(2): + a = rng.random([n, n]) + q, r, p = qr(a, pivoting=True) + d = abs(diag(r)) + assert_(np.all(d[1:] <= d[:-1])) + assert_array_almost_equal(q.T @ q, eye(n)) + assert_array_almost_equal(q @ r, a[:, p]) + q2, r2 = qr(a[:, p]) + assert_array_almost_equal(q, q2) + assert_array_almost_equal(r, r2) + + def test_random_tall(self): + rng = np.random.RandomState(1234) + # full version + m = 200 + n = 100 + for k in range(2): + a = rng.random([m, n]) + q, r = qr(a) + assert_array_almost_equal(q.T @ q, eye(m)) + assert_array_almost_equal(q @ r, a) + + def test_random_tall_left(self): + rng = np.random.RandomState(1234) + # full version + m = 200 + n = 100 + for k in range(2): + a = rng.random([m, n]) + q, r = qr(a, mode="economic") + c = rng.random([n]) + qc, r = qr_multiply(a, c, "left") + assert_array_almost_equal(q @ c, qc) + qc, r = qr_multiply(a, eye(n), "left") + assert_array_almost_equal(qc, q) + + def test_random_tall_right(self): + rng = np.random.RandomState(1234) + # full version + m = 200 + n = 100 + for k in range(2): + a = rng.random([m, n]) + q, r = qr(a, mode="economic") + c = rng.random([m]) + cq, r = qr_multiply(a, c) + assert_array_almost_equal(c @ q, cq) + cq, r = qr_multiply(a, eye(m)) + assert_array_almost_equal(cq, q) + + def test_random_tall_pivoting(self): + rng = np.random.RandomState(1234) + # full version pivoting + m = 200 + n = 100 + for k in range(2): + a = rng.random([m, n]) + q, r, p = qr(a, pivoting=True) + d = abs(diag(r)) + assert_(np.all(d[1:] <= d[:-1])) + assert_array_almost_equal(q.T @ q, eye(m)) + assert_array_almost_equal(q @ r, a[:, p]) + q2, r2 = qr(a[:, p]) + assert_array_almost_equal(q, q2) + assert_array_almost_equal(r, r2) + + def test_random_tall_e(self): + rng = np.random.RandomState(1234) + # economy version + m = 200 + n = 100 + for k in range(2): + a = rng.random([m, n]) + q, r = qr(a, mode='economic') + assert_array_almost_equal(q.T @ q, eye(n)) + assert_array_almost_equal(q @ r, a) + assert_equal(q.shape, (m, n)) + assert_equal(r.shape, (n, n)) + + def test_random_tall_e_pivoting(self): + rng = np.random.RandomState(1234) + # economy version pivoting + m = 200 + n = 100 + for k in range(2): + a = rng.random([m, n]) + q, r, p = qr(a, pivoting=True, mode='economic') + d = abs(diag(r)) + assert_(np.all(d[1:] <= d[:-1])) + assert_array_almost_equal(q.T @ q, eye(n)) + assert_array_almost_equal(q @ r, a[:, p]) + assert_equal(q.shape, (m, n)) + assert_equal(r.shape, (n, n)) + q2, r2 = qr(a[:, p], mode='economic') + assert_array_almost_equal(q, q2) + assert_array_almost_equal(r, r2) + + def test_random_trap(self): + rng = np.random.RandomState(1234) + m = 100 + n = 200 + for k in range(2): + a = rng.random([m, n]) + q, r = qr(a) + assert_array_almost_equal(q.T @ q, eye(m)) + assert_array_almost_equal(q @ r, a) + + def test_random_trap_pivoting(self): + rng = np.random.RandomState(1234) + m = 100 + n = 200 + for k in range(2): + a = rng.random([m, n]) + q, r, p = qr(a, pivoting=True) + d = abs(diag(r)) + assert_(np.all(d[1:] <= d[:-1])) + assert_array_almost_equal(q.T @ q, eye(m)) + assert_array_almost_equal(q @ r, a[:, p]) + q2, r2 = qr(a[:, p]) + assert_array_almost_equal(q, q2) + assert_array_almost_equal(r, r2) + + def test_random_complex(self): + rng = np.random.RandomState(1234) + n = 20 + for k in range(2): + a = rng.random([n, n]) + 1j*rng.random([n, n]) + q, r = qr(a) + assert_array_almost_equal(q.conj().T @ q, eye(n)) + assert_array_almost_equal(q @ r, a) + + def test_random_complex_left(self): + rng = np.random.RandomState(1234) + n = 20 + for k in range(2): + a = rng.random([n, n]) + 1j*rng.random([n, n]) + q, r = qr(a) + c = rng.random([n]) + 1j*rng.random([n]) + qc, r = qr_multiply(a, c, "left") + assert_array_almost_equal(q @ c, qc) + qc, r = qr_multiply(a, eye(n), "left") + assert_array_almost_equal(q, qc) + + def test_random_complex_right(self): + rng = np.random.RandomState(1234) + n = 20 + for k in range(2): + a = rng.random([n, n]) + 1j*rng.random([n, n]) + q, r = qr(a) + c = rng.random([n]) + 1j*rng.random([n]) + cq, r = qr_multiply(a, c) + assert_array_almost_equal(c @ q, cq) + cq, r = qr_multiply(a, eye(n)) + assert_array_almost_equal(q, cq) + + def test_random_complex_pivoting(self): + rng = np.random.RandomState(1234) + n = 20 + for k in range(2): + a = rng.random([n, n]) + 1j*rng.random([n, n]) + q, r, p = qr(a, pivoting=True) + d = abs(diag(r)) + assert_(np.all(d[1:] <= d[:-1])) + assert_array_almost_equal(q.conj().T @ q, eye(n)) + assert_array_almost_equal(q @ r, a[:, p]) + q2, r2 = qr(a[:, p]) + assert_array_almost_equal(q, q2) + assert_array_almost_equal(r, r2) + + def test_check_finite(self): + a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]] + q, r = qr(a, check_finite=False) + assert_array_almost_equal(q.T @ q, eye(3)) + assert_array_almost_equal(q @ r, a) + + def test_lwork(self): + a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]] + # Get comparison values + q, r = qr(a, lwork=None) + + # Test against minimum valid lwork + q2, r2 = qr(a, lwork=3) + assert_array_almost_equal(q2, q) + assert_array_almost_equal(r2, r) + + # Test against larger lwork + q3, r3 = qr(a, lwork=10) + assert_array_almost_equal(q3, q) + assert_array_almost_equal(r3, r) + + # Test against explicit lwork=-1 + q4, r4 = qr(a, lwork=-1) + assert_array_almost_equal(q4, q) + assert_array_almost_equal(r4, r) + + # Test against invalid lwork + assert_raises(Exception, qr, (a,), {'lwork': 0}) + assert_raises(Exception, qr, (a,), {'lwork': 2}) + + @pytest.mark.parametrize("m", [0, 1, 2]) + @pytest.mark.parametrize("n", [0, 1, 2]) + @pytest.mark.parametrize("pivoting", [False, True]) + @pytest.mark.parametrize('dtype', DTYPES) + def test_shape_dtype(self, m, n, pivoting, dtype): + k = min(m, n) + + a = np.zeros((m, n), dtype=dtype) + q, r, *other = qr(a, pivoting=pivoting) + assert_equal(q.shape, (m, m)) + assert_equal(q.dtype, dtype) + assert_equal(r.shape, (m, n)) + assert_equal(r.dtype, dtype) + assert len(other) == (1 if pivoting else 0) + if pivoting: + p, = other + assert_equal(p.shape, (n,)) + assert_equal(p.dtype, np.int32) + + r, *other = qr(a, mode='r', pivoting=pivoting) + assert_equal(r.shape, (m, n)) + assert_equal(r.dtype, dtype) + assert len(other) == (1 if pivoting else 0) + if pivoting: + p, = other + assert_equal(p.shape, (n,)) + assert_equal(p.dtype, np.int32) + + q, r, *other = qr(a, mode='economic', pivoting=pivoting) + assert_equal(q.shape, (m, k)) + assert_equal(q.dtype, dtype) + assert_equal(r.shape, (k, n)) + assert_equal(r.dtype, dtype) + assert len(other) == (1 if pivoting else 0) + if pivoting: + p, = other + assert_equal(p.shape, (n,)) + assert_equal(p.dtype, np.int32) + + (raw, tau), r, *other = qr(a, mode='raw', pivoting=pivoting) + assert_equal(raw.shape, (m, n)) + assert_equal(raw.dtype, dtype) + assert_equal(tau.shape, (k,)) + assert_equal(tau.dtype, dtype) + assert_equal(r.shape, (k, n)) + assert_equal(r.dtype, dtype) + assert len(other) == (1 if pivoting else 0) + if pivoting: + p, = other + assert_equal(p.shape, (n,)) + assert_equal(p.dtype, np.int32) + + @pytest.mark.parametrize(("m", "n"), [(0, 0), (0, 2), (2, 0)]) + def test_empty(self, m, n): + k = min(m, n) + + a = np.empty((m, n)) + q, r = qr(a) + assert_allclose(q, np.identity(m)) + assert_allclose(r, np.empty((m, n))) + + q, r, p = qr(a, pivoting=True) + assert_allclose(q, np.identity(m)) + assert_allclose(r, np.empty((m, n))) + assert_allclose(p, np.arange(n)) + + r, = qr(a, mode='r') + assert_allclose(r, np.empty((m, n))) + + q, r = qr(a, mode='economic') + assert_allclose(q, np.empty((m, k))) + assert_allclose(r, np.empty((k, n))) + + (raw, tau), r = qr(a, mode='raw') + assert_allclose(raw, np.empty((m, n))) + assert_allclose(tau, np.empty((k,))) + assert_allclose(r, np.empty((k, n))) + + def test_multiply_empty(self): + a = np.empty((0, 0)) + c = np.empty((0, 0)) + cq, r = qr_multiply(a, c) + assert_allclose(cq, np.empty((0, 0))) + + a = np.empty((0, 2)) + c = np.empty((2, 0)) + cq, r = qr_multiply(a, c) + assert_allclose(cq, np.empty((2, 0))) + + a = np.empty((2, 0)) + c = np.empty((0, 2)) + cq, r = qr_multiply(a, c) + assert_allclose(cq, np.empty((0, 2))) + + +class TestRQ: + def test_simple(self): + a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]] + r, q = rq(a) + assert_array_almost_equal(q @ q.T, eye(3)) + assert_array_almost_equal(r @ q, a) + + def test_r(self): + a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]] + r, q = rq(a) + r2 = rq(a, mode='r') + assert_array_almost_equal(r, r2) + + def test_random(self): + rng = np.random.RandomState(1234) + n = 20 + for k in range(2): + a = rng.random([n, n]) + r, q = rq(a) + assert_array_almost_equal(q @ q.T, eye(n)) + assert_array_almost_equal(r @ q, a) + + def test_simple_trap(self): + a = [[8, 2, 3], [2, 9, 3]] + r, q = rq(a) + assert_array_almost_equal(q.T @ q, eye(3)) + assert_array_almost_equal(r @ q, a) + + def test_simple_tall(self): + a = [[8, 2], [2, 9], [5, 3]] + r, q = rq(a) + assert_array_almost_equal(q.T @ q, eye(2)) + assert_array_almost_equal(r @ q, a) + + def test_simple_fat(self): + a = [[8, 2, 5], [2, 9, 3]] + r, q = rq(a) + assert_array_almost_equal(q @ q.T, eye(3)) + assert_array_almost_equal(r @ q, a) + + def test_simple_complex(self): + a = [[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]] + r, q = rq(a) + assert_array_almost_equal(q @ q.conj().T, eye(3)) + assert_array_almost_equal(r @ q, a) + + def test_random_tall(self): + rng = np.random.RandomState(1234) + m = 200 + n = 100 + for k in range(2): + a = rng.random([m, n]) + r, q = rq(a) + assert_array_almost_equal(q @ q.T, eye(n)) + assert_array_almost_equal(r @ q, a) + + def test_random_trap(self): + rng = np.random.RandomState(1234) + m = 100 + n = 200 + for k in range(2): + a = rng.random([m, n]) + r, q = rq(a) + assert_array_almost_equal(q @ q.T, eye(n)) + assert_array_almost_equal(r @ q, a) + + def test_random_trap_economic(self): + rng = np.random.RandomState(1234) + m = 100 + n = 200 + for k in range(2): + a = rng.random([m, n]) + r, q = rq(a, mode='economic') + assert_array_almost_equal(q @ q.T, eye(m)) + assert_array_almost_equal(r @ q, a) + assert_equal(q.shape, (m, n)) + assert_equal(r.shape, (m, m)) + + def test_random_complex(self): + rng = np.random.RandomState(1234) + n = 20 + for k in range(2): + a = rng.random([n, n]) + 1j*rng.random([n, n]) + r, q = rq(a) + assert_array_almost_equal(q @ q.conj().T, eye(n)) + assert_array_almost_equal(r @ q, a) + + def test_random_complex_economic(self): + rng = np.random.RandomState(1234) + m = 100 + n = 200 + for k in range(2): + a = rng.random([m, n]) + 1j*rng.random([m, n]) + r, q = rq(a, mode='economic') + assert_array_almost_equal(q @ q.conj().T, eye(m)) + assert_array_almost_equal(r @ q, a) + assert_equal(q.shape, (m, n)) + assert_equal(r.shape, (m, m)) + + def test_check_finite(self): + a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]] + r, q = rq(a, check_finite=False) + assert_array_almost_equal(q @ q.T, eye(3)) + assert_array_almost_equal(r @ q, a) + + @pytest.mark.parametrize("m", [0, 1, 2]) + @pytest.mark.parametrize("n", [0, 1, 2]) + @pytest.mark.parametrize('dtype', DTYPES) + def test_shape_dtype(self, m, n, dtype): + k = min(m, n) + + a = np.zeros((m, n), dtype=dtype) + r, q = rq(a) + assert_equal(q.shape, (n, n)) + assert_equal(r.shape, (m, n)) + assert_equal(r.dtype, dtype) + assert_equal(q.dtype, dtype) + + r = rq(a, mode='r') + assert_equal(r.shape, (m, n)) + assert_equal(r.dtype, dtype) + + r, q = rq(a, mode='economic') + assert_equal(r.shape, (m, k)) + assert_equal(r.dtype, dtype) + assert_equal(q.shape, (k, n)) + assert_equal(q.dtype, dtype) + + @pytest.mark.parametrize(("m", "n"), [(0, 0), (0, 2), (2, 0)]) + def test_empty(self, m, n): + k = min(m, n) + + a = np.empty((m, n)) + r, q = rq(a) + assert_allclose(r, np.empty((m, n))) + assert_allclose(q, np.identity(n)) + + r = rq(a, mode='r') + assert_allclose(r, np.empty((m, n))) + + r, q = rq(a, mode='economic') + assert_allclose(r, np.empty((m, k))) + assert_allclose(q, np.empty((k, n))) + + +class TestSchur: + + def check_schur(self, a, t, u, rtol, atol): + # Check that the Schur decomposition is correct. + assert_allclose(u @ t @ u.conj().T, a, rtol=rtol, atol=atol, + err_msg="Schur decomposition does not match 'a'") + # The expected value of u @ u.H - I is all zeros, so test + # with absolute tolerance only. + assert_allclose(u @ u.conj().T - np.eye(len(u)), 0, rtol=0, atol=atol, + err_msg="u is not unitary") + + def test_simple(self): + a = [[8, 12, 3], [2, 9, 3], [10, 3, 6]] + t, z = schur(a) + self.check_schur(a, t, z, rtol=1e-14, atol=5e-15) + tc, zc = schur(a, 'complex') + assert_(np.any(ravel(iscomplex(zc))) and np.any(ravel(iscomplex(tc)))) + self.check_schur(a, tc, zc, rtol=1e-14, atol=5e-15) + tc2, zc2 = rsf2csf(tc, zc) + self.check_schur(a, tc2, zc2, rtol=1e-14, atol=5e-15) + + @pytest.mark.parametrize( + 'sort, expected_diag', + [('lhp', [-np.sqrt(2), -0.5, np.sqrt(2), 0.5]), + ('rhp', [np.sqrt(2), 0.5, -np.sqrt(2), -0.5]), + ('iuc', [-0.5, 0.5, np.sqrt(2), -np.sqrt(2)]), + ('ouc', [np.sqrt(2), -np.sqrt(2), -0.5, 0.5]), + (lambda x: x >= 0.0, [np.sqrt(2), 0.5, -np.sqrt(2), -0.5])] + ) + def test_sort(self, sort, expected_diag): + # The exact eigenvalues of this matrix are + # -sqrt(2), sqrt(2), -1/2, 1/2. + a = [[4., 3., 1., -1.], + [-4.5, -3.5, -1., 1.], + [9., 6., -4., 4.5], + [6., 4., -3., 3.5]] + t, u, sdim = schur(a, sort=sort) + self.check_schur(a, t, u, rtol=1e-14, atol=5e-15) + assert_allclose(np.diag(t), expected_diag, rtol=1e-12) + assert_equal(2, sdim) + + def test_sort_errors(self): + a = [[4., 3., 1., -1.], + [-4.5, -3.5, -1., 1.], + [9., 6., -4., 4.5], + [6., 4., -3., 3.5]] + assert_raises(ValueError, schur, a, sort='unsupported') + assert_raises(ValueError, schur, a, sort=1) + + def test_check_finite(self): + a = [[8, 12, 3], [2, 9, 3], [10, 3, 6]] + t, z = schur(a, check_finite=False) + assert_array_almost_equal(z @ t @ z.conj().T, a) + + @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) + def test_empty(self, dt): + a = np.empty((0, 0), dtype=dt) + t, z = schur(a) + t0, z0 = schur(np.eye(2, dtype=dt)) + assert_allclose(t, np.empty((0, 0))) + assert_allclose(z, np.empty((0, 0))) + assert t.dtype == t0.dtype + assert z.dtype == z0.dtype + + t, z, sdim = schur(a, sort='lhp') + assert_allclose(t, np.empty((0, 0))) + assert_allclose(z, np.empty((0, 0))) + assert_equal(sdim, 0) + assert t.dtype == t0.dtype + assert z.dtype == z0.dtype + + @pytest.mark.parametrize('sort', ['iuc', 'ouc']) + @pytest.mark.parametrize('output', ['real', 'complex']) + @pytest.mark.parametrize('dtype', [np.float32, np.float64, + np.complex64, np.complex128]) + def test_gh_13137_sort_str(self, sort, output, dtype): + # gh-13137 reported that sort values 'iuc' and 'ouc' were not + # correct because the callables assumed that the eigenvalues would + # always be expressed as a single complex number. + # In fact, when `output='real'` and the dtype is real, the + # eigenvalues are passed as separate real and imaginary components + # (yet no error is raised if the callable accepts only one argument). + # + # This tests these sort values by counting the number of eigenvalues + # `schur` reports as being inside/outside the unit circle. + + # Real matrix with eigenvalues 0.1 +- 2j + A = np.asarray([[0.1, -2], [2, 0.1]]) + + # Previously, this would fail for `output='real'` with real dtypes + sdim = schur(A.astype(dtype), sort=sort, output=output)[-1] + assert sdim == 0 if sort == 'iuc' else sdim == 2 + + @pytest.mark.parametrize('output', ['real', 'complex']) + @pytest.mark.parametrize('dtype', [np.float32, np.float64, + np.complex64, np.complex128]) + def test_gh_13137_sort_custom(self, output, dtype): + # This simply tests our understanding of how eigenvalues are + # passed to a sort callable. If `output='real'` and the dtype is real, + # real and imaginary parts are passed as separate real arguments; + # otherwise, they are passed a single complex argument. + # Also, if `output='real'` and the dtype is real, when either + # eigenvalue in a complex conjugate pair satisfies the sort condition, + # `sdim` is incremented by TWO. + + # Real matrix with eigenvalues 0.1 +- 2j + A = np.asarray([[0.1, -2], [2, 0.1]]) + + all_real = output=='real' and dtype in {np.float32, np.float64} + + def sort(x, y=None): + if all_real: + assert not np.iscomplexobj(x) + assert y is not None and np.isreal(y) + z = x + y*1j + else: + assert np.iscomplexobj(x) + assert y is None + z = x + return z.imag > 1e-15 + + # Only one complex eigenvalue satisfies the condition, but when + # `all_real` applies, both eigenvalues in the complex conjugate pair + # are counted. + sdim = schur(A.astype(dtype), sort=sort, output=output)[-1] + assert sdim == 2 if all_real else sdim == 1 + + +class TestHessenberg: + + def test_simple(self): + a = [[-149, -50, -154], + [537, 180, 546], + [-27, -9, -25]] + h1 = [[-149.0000, 42.2037, -156.3165], + [-537.6783, 152.5511, -554.9272], + [0, 0.0728, 2.4489]] + h, q = hessenberg(a, calc_q=1) + assert_array_almost_equal(q.T @ a @ q, h) + assert_array_almost_equal(h, h1, decimal=4) + + def test_simple_complex(self): + a = [[-149, -50, -154], + [537, 180j, 546], + [-27j, -9, -25]] + h, q = hessenberg(a, calc_q=1) + assert_array_almost_equal(q.conj().T @ a @ q, h) + + def test_simple2(self): + a = [[1, 2, 3, 4, 5, 6, 7], + [0, 2, 3, 4, 6, 7, 2], + [0, 2, 2, 3, 0, 3, 2], + [0, 0, 2, 8, 0, 0, 2], + [0, 3, 1, 2, 0, 1, 2], + [0, 1, 2, 3, 0, 1, 0], + [0, 0, 0, 0, 0, 1, 2]] + h, q = hessenberg(a, calc_q=1) + assert_array_almost_equal(q.T @ a @ q, h) + + def test_simple3(self): + a = np.eye(3) + a[-1, 0] = 2 + h, q = hessenberg(a, calc_q=1) + assert_array_almost_equal(q.T @ a @ q, h) + + def test_random(self): + rng = np.random.RandomState(1234) + n = 20 + for k in range(2): + a = rng.random([n, n]) + h, q = hessenberg(a, calc_q=1) + assert_array_almost_equal(q.T @ a @ q, h) + + def test_random_complex(self): + rng = np.random.RandomState(1234) + n = 20 + for k in range(2): + a = rng.random([n, n]) + 1j*rng.random([n, n]) + h, q = hessenberg(a, calc_q=1) + assert_array_almost_equal(q.conj().T @ a @ q, h) + + def test_check_finite(self): + a = [[-149, -50, -154], + [537, 180, 546], + [-27, -9, -25]] + h1 = [[-149.0000, 42.2037, -156.3165], + [-537.6783, 152.5511, -554.9272], + [0, 0.0728, 2.4489]] + h, q = hessenberg(a, calc_q=1, check_finite=False) + assert_array_almost_equal(q.T @ a @ q, h) + assert_array_almost_equal(h, h1, decimal=4) + + def test_2x2(self): + a = [[2, 1], [7, 12]] + + h, q = hessenberg(a, calc_q=1) + assert_array_almost_equal(q, np.eye(2)) + assert_array_almost_equal(h, a) + + b = [[2-7j, 1+2j], [7+3j, 12-2j]] + h2, q2 = hessenberg(b, calc_q=1) + assert_array_almost_equal(q2, np.eye(2)) + assert_array_almost_equal(h2, b) + + @pytest.mark.parametrize('dt', [int, float, float32, complex, complex64]) + def test_empty(self, dt): + a = np.empty((0, 0), dtype=dt) + h = hessenberg(a) + assert h.shape == (0, 0) + assert h.dtype == hessenberg(np.eye(3, dtype=dt)).dtype + + h, q = hessenberg(a, calc_q=True) + h3, q3 = hessenberg(a, calc_q=True) + assert h.shape == (0, 0) + assert h.dtype == h3.dtype + + assert q.shape == (0, 0) + assert q.dtype == q3.dtype + + +blas_provider = blas_version = None +if CONFIG is not None: + blas_provider = CONFIG['Build Dependencies']['blas']['name'] + blas_version = CONFIG['Build Dependencies']['blas']['version'] + + +class TestQZ: + def test_qz_single(self): + rng = np.random.RandomState(12345) + n = 5 + A = rng.random([n, n]).astype(float32) + B = rng.random([n, n]).astype(float32) + AA, BB, Q, Z = qz(A, B) + assert_array_almost_equal(Q @ AA @ Z.T, A, decimal=5) + assert_array_almost_equal(Q @ BB @ Z.T, B, decimal=5) + assert_array_almost_equal(Q @ Q.T, eye(n), decimal=5) + assert_array_almost_equal(Z @ Z.T, eye(n), decimal=5) + assert_(np.all(diag(BB) >= 0)) + + def test_qz_double(self): + rng = np.random.RandomState(12345) + n = 5 + A = rng.random([n, n]) + B = rng.random([n, n]) + AA, BB, Q, Z = qz(A, B) + assert_array_almost_equal(Q @ AA @ Z.T, A) + assert_array_almost_equal(Q @ BB @ Z.T, B) + assert_array_almost_equal(Q @ Q.T, eye(n)) + assert_array_almost_equal(Z @ Z.T, eye(n)) + assert_(np.all(diag(BB) >= 0)) + + def test_qz_complex(self): + rng = np.random.RandomState(12345) + n = 5 + A = rng.random([n, n]) + 1j*rng.random([n, n]) + B = rng.random([n, n]) + 1j*rng.random([n, n]) + AA, BB, Q, Z = qz(A, B) + assert_array_almost_equal(Q @ AA @ Z.conj().T, A) + assert_array_almost_equal(Q @ BB @ Z.conj().T, B) + assert_array_almost_equal(Q @ Q.conj().T, eye(n)) + assert_array_almost_equal(Z @ Z.conj().T, eye(n)) + assert_(np.all(diag(BB) >= 0)) + assert_(np.all(diag(BB).imag == 0)) + + def test_qz_complex64(self): + rng = np.random.RandomState(12345) + n = 5 + A = (rng.random([n, n]) + 1j*rng.random([n, n])).astype(complex64) + B = (rng.random([n, n]) + 1j*rng.random([n, n])).astype(complex64) + AA, BB, Q, Z = qz(A, B) + assert_array_almost_equal(Q @ AA @ Z.conj().T, A, decimal=5) + assert_array_almost_equal(Q @ BB @ Z.conj().T, B, decimal=5) + assert_array_almost_equal(Q @ Q.conj().T, eye(n), decimal=5) + assert_array_almost_equal(Z @ Z.conj().T, eye(n), decimal=5) + assert_(np.all(diag(BB) >= 0)) + assert_(np.all(diag(BB).imag == 0)) + + def test_qz_double_complex(self): + rng = np.random.RandomState(12345) + n = 5 + A = rng.random([n, n]) + B = rng.random([n, n]) + AA, BB, Q, Z = qz(A, B, output='complex') + aa = Q @ AA @ Z.conj().T + assert_array_almost_equal(aa.real, A) + assert_array_almost_equal(aa.imag, 0) + bb = Q @ BB @ Z.conj().T + assert_array_almost_equal(bb.real, B) + assert_array_almost_equal(bb.imag, 0) + assert_array_almost_equal(Q @ Q.conj().T, eye(n)) + assert_array_almost_equal(Z @ Z.conj().T, eye(n)) + assert_(np.all(diag(BB) >= 0)) + + def test_qz_double_sort(self): + # from https://www.nag.com/lapack-ex/node119.html + # NOTE: These matrices may be ill-conditioned and lead to a + # seg fault on certain python versions when compiled with + # sse2 or sse3 older ATLAS/LAPACK binaries for windows + # A = np.array([[3.9, 12.5, -34.5, -0.5], + # [ 4.3, 21.5, -47.5, 7.5], + # [ 4.3, 21.5, -43.5, 3.5], + # [ 4.4, 26.0, -46.0, 6.0 ]]) + + # B = np.array([[ 1.0, 2.0, -3.0, 1.0], + # [1.0, 3.0, -5.0, 4.0], + # [1.0, 3.0, -4.0, 3.0], + # [1.0, 3.0, -4.0, 4.0]]) + A = np.array([[3.9, 12.5, -34.5, 2.5], + [4.3, 21.5, -47.5, 7.5], + [4.3, 1.5, -43.5, 3.5], + [4.4, 6.0, -46.0, 6.0]]) + + B = np.array([[1.0, 1.0, -3.0, 1.0], + [1.0, 3.0, -5.0, 4.4], + [1.0, 2.0, -4.0, 1.0], + [1.2, 3.0, -4.0, 4.0]]) + + assert_raises(ValueError, qz, A, B, sort=lambda ar, ai, beta: ai == 0) + if False: + AA, BB, Q, Z, sdim = qz(A, B, sort=lambda ar, ai, beta: ai == 0) + # assert_(sdim == 2) + assert_(sdim == 4) + assert_array_almost_equal(Q @ AA @ Z.T, A) + assert_array_almost_equal(Q @ BB @ Z.T, B) + + # test absolute values bc the sign is ambiguous and + # might be platform dependent + assert_array_almost_equal(np.abs(AA), np.abs(np.array( + [[35.7864, -80.9061, -12.0629, -9.498], + [0., 2.7638, -2.3505, 7.3256], + [0., 0., 0.6258, -0.0398], + [0., 0., 0., -12.8217]])), 4) + assert_array_almost_equal(np.abs(BB), np.abs(np.array( + [[4.5324, -8.7878, 3.2357, -3.5526], + [0., 1.4314, -2.1894, 0.9709], + [0., 0., 1.3126, -0.3468], + [0., 0., 0., 0.559]])), 4) + assert_array_almost_equal(np.abs(Q), np.abs(np.array( + [[-0.4193, -0.605, -0.1894, -0.6498], + [-0.5495, 0.6987, 0.2654, -0.3734], + [-0.4973, -0.3682, 0.6194, 0.4832], + [-0.5243, 0.1008, -0.7142, 0.4526]])), 4) + assert_array_almost_equal(np.abs(Z), np.abs(np.array( + [[-0.9471, -0.2971, -0.1217, 0.0055], + [-0.0367, 0.1209, 0.0358, 0.9913], + [0.3171, -0.9041, -0.2547, 0.1312], + [0.0346, 0.2824, -0.9587, 0.0014]])), 4) + + # test absolute values bc the sign is ambiguous and might be platform + # dependent + # assert_array_almost_equal(abs(AA), abs(np.array([ + # [3.8009, -69.4505, 50.3135, -43.2884], + # [0.0000, 9.2033, -0.2001, 5.9881], + # [0.0000, 0.0000, 1.4279, 4.4453], + # [0.0000, 0.0000, 0.9019, -1.1962]])), 4) + # assert_array_almost_equal(abs(BB), abs(np.array([ + # [1.9005, -10.2285, 0.8658, -5.2134], + # [0.0000, 2.3008, 0.7915, 0.4262], + # [0.0000, 0.0000, 0.8101, 0.0000], + # [0.0000, 0.0000, 0.0000, -0.2823]])), 4) + # assert_array_almost_equal(abs(Q), abs(np.array([ + # [0.4642, 0.7886, 0.2915, -0.2786], + # [0.5002, -0.5986, 0.5638, -0.2713], + # [0.5002, 0.0154, -0.0107, 0.8657], + # [0.5331, -0.1395, -0.7727, -0.3151]])), 4) + # assert_array_almost_equal(dot(Q,Q.T), eye(4)) + # assert_array_almost_equal(abs(Z), abs(np.array([ + # [0.9961, -0.0014, 0.0887, -0.0026], + # [0.0057, -0.0404, -0.0938, -0.9948], + # [0.0626, 0.7194, -0.6908, 0.0363], + # [0.0626, -0.6934, -0.7114, 0.0956]])), 4) + # assert_array_almost_equal(dot(Z,Z.T), eye(4)) + + # def test_qz_complex_sort(self): + # cA = np.array([ + # [-21.10+22.50*1j, 53.50+-50.50*1j, -34.50+127.50*1j, 7.50+ 0.50*1j], + # [-0.46+ -7.78*1j, -3.50+-37.50*1j, -15.50+ 58.50*1j,-10.50+ -1.50*1j], + # [ 4.30+ -5.50*1j, 39.70+-17.10*1j, -68.50+ 12.50*1j, -7.50+ -3.50*1j], + # [ 5.50+ 4.40*1j, 14.40+ 43.30*1j, -32.50+-46.00*1j,-19.00+-32.50*1j]]) + + # cB = np.array([ + # [1.00+ -5.00*1j, 1.60+ 1.20*1j,-3.00+ 0.00*1j, 0.00+ -1.00*1j], + # [0.80+ -0.60*1j, 3.00+ -5.00*1j,-4.00+ 3.00*1j,-2.40+ -3.20*1j], + # [1.00+ 0.00*1j, 2.40+ 1.80*1j,-4.00+ -5.00*1j, 0.00+ -3.00*1j], + # [0.00+ 1.00*1j,-1.80+ 2.40*1j, 0.00+ -4.00*1j, 4.00+ -5.00*1j]]) + + # AAS,BBS,QS,ZS,sdim = qz(cA,cB,sort='lhp') + + # eigenvalues = diag(AAS)/diag(BBS) + # assert_(np.all(np.real(eigenvalues[:sdim] < 0))) + # assert_(np.all(np.real(eigenvalues[sdim:] > 0))) + + def test_check_finite(self): + rng = np.random.RandomState(12345) + n = 5 + A = rng.random([n, n]) + B = rng.random([n, n]) + AA, BB, Q, Z = qz(A, B, check_finite=False) + assert_array_almost_equal(Q @ AA @ Z.T, A) + assert_array_almost_equal(Q @ BB @ Z.T, B) + assert_array_almost_equal(Q @ Q.T, eye(n)) + assert_array_almost_equal(Z @ Z.T, eye(n)) + assert_(np.all(diag(BB) >= 0)) + + +class TestOrdQZ: + @classmethod + def setup_class(cls): + # https://www.nag.com/lapack-ex/node119.html + A1 = np.array([[-21.10 - 22.50j, 53.5 - 50.5j, -34.5 + 127.5j, + 7.5 + 0.5j], + [-0.46 - 7.78j, -3.5 - 37.5j, -15.5 + 58.5j, + -10.5 - 1.5j], + [4.30 - 5.50j, 39.7 - 17.1j, -68.5 + 12.5j, + -7.5 - 3.5j], + [5.50 + 4.40j, 14.4 + 43.3j, -32.5 - 46.0j, + -19.0 - 32.5j]]) + + B1 = np.array([[1.0 - 5.0j, 1.6 + 1.2j, -3 + 0j, 0.0 - 1.0j], + [0.8 - 0.6j, .0 - 5.0j, -4 + 3j, -2.4 - 3.2j], + [1.0 + 0.0j, 2.4 + 1.8j, -4 - 5j, 0.0 - 3.0j], + [0.0 + 1.0j, -1.8 + 2.4j, 0 - 4j, 4.0 - 5.0j]]) + + # https://www.nag.com/numeric/fl/nagdoc_fl23/xhtml/F08/f08yuf.xml + A2 = np.array([[3.9, 12.5, -34.5, -0.5], + [4.3, 21.5, -47.5, 7.5], + [4.3, 21.5, -43.5, 3.5], + [4.4, 26.0, -46.0, 6.0]]) + + B2 = np.array([[1, 2, -3, 1], + [1, 3, -5, 4], + [1, 3, -4, 3], + [1, 3, -4, 4]]) + + # example with the eigenvalues + # -0.33891648, 1.61217396+0.74013521j, 1.61217396-0.74013521j, + # 0.61244091 + # thus featuring: + # * one complex conjugate eigenvalue pair, + # * one eigenvalue in the lhp + # * 2 eigenvalues in the unit circle + # * 2 non-real eigenvalues + A3 = np.array([[5., 1., 3., 3.], + [4., 4., 2., 7.], + [7., 4., 1., 3.], + [0., 4., 8., 7.]]) + B3 = np.array([[8., 10., 6., 10.], + [7., 7., 2., 9.], + [9., 1., 6., 6.], + [5., 1., 4., 7.]]) + + # example with infinite eigenvalues + A4 = np.eye(2) + B4 = np.diag([0, 1]) + + # example with (alpha, beta) = (0, 0) + A5 = np.diag([1, 0]) + + cls.A = [A1, A2, A3, A4, A5] + cls.B = [B1, B2, B3, B4, A5] + + def qz_decomp(self, sort): + with np.errstate(all='raise'): + ret = [ordqz(Ai, Bi, sort=sort) for Ai, Bi in zip(self.A, self.B)] + return tuple(ret) + + def check(self, A, B, sort, AA, BB, alpha, beta, Q, Z): + Id = np.eye(*A.shape) + # make sure Q and Z are orthogonal + assert_array_almost_equal(Q @ Q.T.conj(), Id) + assert_array_almost_equal(Z @ Z.T.conj(), Id) + # check factorization + assert_array_almost_equal(Q @ AA, A @ Z) + assert_array_almost_equal(Q @ BB, B @ Z) + # check shape of AA and BB + assert_array_equal(np.tril(AA, -2), np.zeros(AA.shape)) + assert_array_equal(np.tril(BB, -1), np.zeros(BB.shape)) + # check eigenvalues + for i in range(A.shape[0]): + # does the current diagonal element belong to a 2-by-2 block + # that was already checked? + if i > 0 and A[i, i - 1] != 0: + continue + # take care of 2-by-2 blocks + if i < AA.shape[0] - 1 and AA[i + 1, i] != 0: + evals, _ = eig(AA[i:i + 2, i:i + 2], BB[i:i + 2, i:i + 2]) + # make sure the pair of complex conjugate eigenvalues + # is ordered consistently (positive imaginary part first) + if evals[0].imag < 0: + evals = evals[[1, 0]] + tmp = alpha[i:i + 2]/beta[i:i + 2] + if tmp[0].imag < 0: + tmp = tmp[[1, 0]] + assert_array_almost_equal(evals, tmp) + else: + if alpha[i] == 0 and beta[i] == 0: + assert_equal(AA[i, i], 0) + assert_equal(BB[i, i], 0) + elif beta[i] == 0: + assert_equal(BB[i, i], 0) + else: + assert_almost_equal(AA[i, i]/BB[i, i], alpha[i]/beta[i]) + sortfun = _select_function(sort) + lastsort = True + for i in range(A.shape[0]): + cursort = sortfun(np.array([alpha[i]]), np.array([beta[i]])) + # once the sorting criterion was not matched all subsequent + # eigenvalues also shouldn't match + if not lastsort: + assert not cursort + lastsort = cursort + + def check_all(self, sort): + ret = self.qz_decomp(sort) + + for reti, Ai, Bi in zip(ret, self.A, self.B): + self.check(Ai, Bi, sort, *reti) + + def test_lhp(self): + self.check_all('lhp') + + def test_rhp(self): + self.check_all('rhp') + + def test_iuc(self): + self.check_all('iuc') + + def test_ouc(self): + self.check_all('ouc') + + def test_ref(self): + # real eigenvalues first (top-left corner) + def sort(x, y): + out = np.empty_like(x, dtype=bool) + nonzero = (y != 0) + out[~nonzero] = False + out[nonzero] = (x[nonzero]/y[nonzero]).imag == 0 + return out + + self.check_all(sort) + + def test_cef(self): + # complex eigenvalues first (top-left corner) + def sort(x, y): + out = np.empty_like(x, dtype=bool) + nonzero = (y != 0) + out[~nonzero] = False + out[nonzero] = (x[nonzero]/y[nonzero]).imag != 0 + return out + + self.check_all(sort) + + def test_diff_input_types(self): + ret = ordqz(self.A[1], self.B[2], sort='lhp') + self.check(self.A[1], self.B[2], 'lhp', *ret) + + ret = ordqz(self.B[2], self.A[1], sort='lhp') + self.check(self.B[2], self.A[1], 'lhp', *ret) + + def test_sort_explicit(self): + # Test order of the eigenvalues in the 2 x 2 case where we can + # explicitly compute the solution + A1 = np.eye(2) + B1 = np.diag([-2, 0.5]) + expected1 = [('lhp', [-0.5, 2]), + ('rhp', [2, -0.5]), + ('iuc', [-0.5, 2]), + ('ouc', [2, -0.5])] + A2 = np.eye(2) + B2 = np.diag([-2 + 1j, 0.5 + 0.5j]) + expected2 = [('lhp', [1/(-2 + 1j), 1/(0.5 + 0.5j)]), + ('rhp', [1/(0.5 + 0.5j), 1/(-2 + 1j)]), + ('iuc', [1/(-2 + 1j), 1/(0.5 + 0.5j)]), + ('ouc', [1/(0.5 + 0.5j), 1/(-2 + 1j)])] + # 'lhp' is ambiguous so don't test it + A3 = np.eye(2) + B3 = np.diag([2, 0]) + expected3 = [('rhp', [0.5, np.inf]), + ('iuc', [0.5, np.inf]), + ('ouc', [np.inf, 0.5])] + # 'rhp' is ambiguous so don't test it + A4 = np.eye(2) + B4 = np.diag([-2, 0]) + expected4 = [('lhp', [-0.5, np.inf]), + ('iuc', [-0.5, np.inf]), + ('ouc', [np.inf, -0.5])] + A5 = np.diag([0, 1]) + B5 = np.diag([0, 0.5]) + # 'lhp' and 'iuc' are ambiguous so don't test them + expected5 = [('rhp', [2, np.nan]), + ('ouc', [2, np.nan])] + + A = [A1, A2, A3, A4, A5] + B = [B1, B2, B3, B4, B5] + expected = [expected1, expected2, expected3, expected4, expected5] + for Ai, Bi, expectedi in zip(A, B, expected): + for sortstr, expected_eigvals in expectedi: + _, _, alpha, beta, _, _ = ordqz(Ai, Bi, sort=sortstr) + azero = (alpha == 0) + bzero = (beta == 0) + x = np.empty_like(alpha) + x[azero & bzero] = np.nan + x[~azero & bzero] = np.inf + x[~bzero] = alpha[~bzero]/beta[~bzero] + assert_allclose(expected_eigvals, x) + + +class TestOrdQZWorkspaceSize: + @pytest.mark.fail_slow(5) + def test_decompose(self): + rng = np.random.RandomState(12345) + N = 202 + # raises error if lwork parameter to dtrsen is too small + for ddtype in [np.float32, np.float64]: + A = rng.random((N, N)).astype(ddtype) + B = rng.random((N, N)).astype(ddtype) + # sort = lambda ar, ai, b: ar**2 + ai**2 < b**2 + _ = ordqz(A, B, sort=lambda alpha, beta: alpha < beta, + output='real') + + for ddtype in [np.complex128, np.complex64]: + A = rng.random((N, N)).astype(ddtype) + B = rng.random((N, N)).astype(ddtype) + _ = ordqz(A, B, sort=lambda alpha, beta: alpha < beta, + output='complex') + + @pytest.mark.slow + def test_decompose_ouc(self): + rng = np.random.RandomState(12345) + N = 202 + # segfaults if lwork parameter to dtrsen is too small + for ddtype in [np.float32, np.float64, np.complex128, np.complex64]: + A = rng.random((N, N)).astype(ddtype) + B = rng.random((N, N)).astype(ddtype) + S, T, alpha, beta, U, V = ordqz(A, B, sort='ouc') + + +class TestDatacopied: + + def test_datacopied(self): + from scipy.linalg._decomp import _datacopied + + M = matrix([[0, 1], [2, 3]]) + A = asarray(M) + L = M.tolist() + M2 = M.copy() + + class Fake1: + def __array__(self, dtype=None, copy=None): + return A + + class Fake2: + __array_interface__ = A.__array_interface__ + + F1 = Fake1() + F2 = Fake2() + + for item, status in [(M, False), (A, False), (L, True), + (M2, False), (F1, False), (F2, False)]: + arr = asarray(item) + assert_equal(_datacopied(arr, item), status, + err_msg=repr(item)) + + +def test_aligned_mem_float(): + """Check linalg works with non-aligned memory (float32)""" + # Allocate 402 bytes of memory (allocated on boundary) + a = arange(402, dtype=np.uint8) + + # Create an array with boundary offset 4 + z = np.frombuffer(a.data, offset=2, count=100, dtype=float32) + z.shape = 10, 10 + + eig(z, overwrite_a=True) + eig(z.T, overwrite_a=True) + + +@pytest.mark.skipif(platform.machine() == 'ppc64le', + reason="crashes on ppc64le") +def test_aligned_mem(): + """Check linalg works with non-aligned memory (float64)""" + # Allocate 804 bytes of memory (allocated on boundary) + a = arange(804, dtype=np.uint8) + + # Create an array with boundary offset 4 + z = np.frombuffer(a.data, offset=4, count=100, dtype=float) + z.shape = 10, 10 + + eig(z, overwrite_a=True) + eig(z.T, overwrite_a=True) + + +def test_aligned_mem_complex(): + """Check that complex objects don't need to be completely aligned""" + # Allocate 1608 bytes of memory (allocated on boundary) + a = zeros(1608, dtype=np.uint8) + + # Create an array with boundary offset 8 + z = np.frombuffer(a.data, offset=8, count=100, dtype=complex) + z.shape = 10, 10 + + eig(z, overwrite_a=True) + # This does not need special handling + eig(z.T, overwrite_a=True) + + +def check_lapack_misaligned(func, args, kwargs): + args = list(args) + for i in range(len(args)): + a = args[:] + if isinstance(a[i], np.ndarray): + # Try misaligning a[i] + aa = np.zeros(a[i].size*a[i].dtype.itemsize+8, dtype=np.uint8) + aa = np.frombuffer(aa.data, offset=4, count=a[i].size, + dtype=a[i].dtype) + aa.shape = a[i].shape + aa[...] = a[i] + a[i] = aa + func(*a, **kwargs) + if len(a[i].shape) > 1: + a[i] = a[i].T + func(*a, **kwargs) + + +@pytest.mark.xfail(run=False, + reason="Ticket #1152, triggers a segfault in rare cases.") +def test_lapack_misaligned(): + M = np.eye(10, dtype=float) + R = np.arange(100) + R.shape = 10, 10 + S = np.arange(20000, dtype=np.uint8) + S = np.frombuffer(S.data, offset=4, count=100, dtype=float) + S.shape = 10, 10 + b = np.ones(10) + LU, piv = lu_factor(S) + for (func, args, kwargs) in [ + (eig, (S,), dict(overwrite_a=True)), # crash + (eigvals, (S,), dict(overwrite_a=True)), # no crash + (lu, (S,), dict(overwrite_a=True)), # no crash + (lu_factor, (S,), dict(overwrite_a=True)), # no crash + (lu_solve, ((LU, piv), b), dict(overwrite_b=True)), + (solve, (S, b), dict(overwrite_a=True, overwrite_b=True)), + (svd, (M,), dict(overwrite_a=True)), # no crash + (svd, (R,), dict(overwrite_a=True)), # no crash + (svd, (S,), dict(overwrite_a=True)), # crash + (svdvals, (S,), dict()), # no crash + (svdvals, (S,), dict(overwrite_a=True)), # crash + (cholesky, (M,), dict(overwrite_a=True)), # no crash + (qr, (S,), dict(overwrite_a=True)), # crash + (rq, (S,), dict(overwrite_a=True)), # crash + (hessenberg, (S,), dict(overwrite_a=True)), # crash + (schur, (S,), dict(overwrite_a=True)), # crash + ]: + check_lapack_misaligned(func, args, kwargs) +# not properly tested +# cholesky, rsf2csf, lu_solve, solve, eig_banded, eigvals_banded, eigh, diagsvd + + +class TestOverwrite: + def test_eig(self): + assert_no_overwrite(eig, [(3, 3)]) + assert_no_overwrite(eig, [(3, 3), (3, 3)]) + + def test_eigh(self): + assert_no_overwrite(eigh, [(3, 3)]) + assert_no_overwrite(eigh, [(3, 3), (3, 3)]) + + def test_eig_banded(self): + assert_no_overwrite(eig_banded, [(3, 2)]) + + def test_eigvals(self): + assert_no_overwrite(eigvals, [(3, 3)]) + + def test_eigvalsh(self): + assert_no_overwrite(eigvalsh, [(3, 3)]) + + def test_eigvals_banded(self): + assert_no_overwrite(eigvals_banded, [(3, 2)]) + + def test_hessenberg(self): + assert_no_overwrite(hessenberg, [(3, 3)]) + + def test_lu_factor(self): + assert_no_overwrite(lu_factor, [(3, 3)]) + + def test_lu_solve(self): + x = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 8]]) + xlu = lu_factor(x) + assert_no_overwrite(lambda b: lu_solve(xlu, b), [(3,)]) + + def test_lu(self): + assert_no_overwrite(lu, [(3, 3)]) + + def test_qr(self): + assert_no_overwrite(qr, [(3, 3)]) + + def test_rq(self): + assert_no_overwrite(rq, [(3, 3)]) + + def test_schur(self): + assert_no_overwrite(schur, [(3, 3)]) + + def test_schur_complex(self): + assert_no_overwrite(lambda a: schur(a, 'complex'), [(3, 3)], + dtypes=[np.float32, np.float64]) + + def test_svd(self): + assert_no_overwrite(svd, [(3, 3)]) + assert_no_overwrite(lambda a: svd(a, lapack_driver='gesvd'), [(3, 3)]) + + def test_svdvals(self): + assert_no_overwrite(svdvals, [(3, 3)]) + + +def _check_orth(n, dtype, skip_big=False): + X = np.ones((n, 2), dtype=float).astype(dtype) + + eps = np.finfo(dtype).eps + tol = 1000 * eps + + Y = orth(X) + assert_equal(Y.shape, (n, 1)) + assert_allclose(Y, Y.mean(), atol=tol) + + Y = orth(X.T) + assert_equal(Y.shape, (2, 1)) + assert_allclose(Y, Y.mean(), atol=tol) + + if n > 5 and not skip_big: + rng = np.random.RandomState(1) + X = rng.rand(n, 5) @ rng.rand(5, n) + X = X + 1e-4 * rng.rand(n, 1) @ rng.rand(1, n) + X = X.astype(dtype) + + Y = orth(X, rcond=1e-3) + assert_equal(Y.shape, (n, 5)) + + Y = orth(X, rcond=1e-6) + assert_equal(Y.shape, (n, 5 + 1)) + + +@pytest.mark.slow +@pytest.mark.skipif(np.dtype(np.intp).itemsize < 8, + reason="test only on 64-bit, else too slow") +def test_orth_memory_efficiency(): + # Pick n so that 16*n bytes is reasonable but 8*n*n bytes is unreasonable. + # Keep in mind that @pytest.mark.slow tests are likely to be running + # under configurations that support 4Gb+ memory for tests related to + # 32 bit overflow. + n = 10*1000*1000 + try: + _check_orth(n, np.float64, skip_big=True) + except MemoryError as e: + raise AssertionError( + 'memory error perhaps caused by orth regression' + ) from e + + +def test_orth(): + dtypes = [np.float32, np.float64, np.complex64, np.complex128] + sizes = [1, 2, 3, 10, 100] + for dt, n in itertools.product(dtypes, sizes): + _check_orth(n, dt) + +@pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) +def test_orth_empty(dt): + a = np.empty((0, 0), dtype=dt) + a0 = np.eye(2, dtype=dt) + + oa = orth(a) + assert oa.dtype == orth(a0).dtype + assert oa.shape == (0, 0) + + +class TestNullSpace: + def test_null_space(self): + rng = np.random.RandomState(1) + + dtypes = [np.float32, np.float64, np.complex64, np.complex128] + sizes = [1, 2, 3, 10, 100] + + for dt, n in itertools.product(dtypes, sizes): + X = np.ones((2, n), dtype=dt) + + eps = np.finfo(dt).eps + tol = 1000 * eps + + Y = null_space(X) + assert_equal(Y.shape, (n, n-1)) + assert_allclose(X @ Y, 0, atol=tol) + + Y = null_space(X.T) + assert_equal(Y.shape, (2, 1)) + assert_allclose(X.T @ Y, 0, atol=tol) + + X = rng.randn(1 + n//2, n) + Y = null_space(X) + assert_equal(Y.shape, (n, n - 1 - n//2)) + assert_allclose(X @ Y, 0, atol=tol) + + if n > 5: + rng = np.random.RandomState(1) + X = rng.rand(n, 5) @ rng.rand(5, n) + X = X + 1e-4 * rng.rand(n, 1) @ rng.rand(1, n) + X = X.astype(dt) + + Y = null_space(X, rcond=1e-3) + assert_equal(Y.shape, (n, n - 5)) + + Y = null_space(X, rcond=1e-6) + assert_equal(Y.shape, (n, n - 6)) + + @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) + def test_null_space_empty(self, dt): + a = np.empty((0, 0), dtype=dt) + a0 = np.eye(2, dtype=dt) + nsa = null_space(a) + + assert nsa.shape == (0, 0) + assert nsa.dtype == null_space(a0).dtype + + @pytest.mark.parametrize("overwrite_a", [True, False]) + @pytest.mark.parametrize("check_finite", [True, False]) + @pytest.mark.parametrize("lapack_driver", ["gesdd", "gesvd"]) + def test_null_space_options(self, overwrite_a, check_finite, lapack_driver): + rng = np.random.default_rng(42887289350573064398746) + n = 10 + X = rng.standard_normal((1 + n//2, n)) + Y = null_space(X.copy(), overwrite_a=overwrite_a, check_finite=check_finite, + lapack_driver=lapack_driver) + assert_allclose(X @ Y, 0, atol=np.finfo(X.dtype).eps*100) + + +def test_subspace_angles(): + H = hadamard(8, float) + A = H[:, :3] + B = H[:, 3:] + assert_allclose(subspace_angles(A, B), [np.pi / 2.] * 3, atol=1e-14) + assert_allclose(subspace_angles(B, A), [np.pi / 2.] * 3, atol=1e-14) + for x in (A, B): + assert_allclose(subspace_angles(x, x), np.zeros(x.shape[1]), + atol=1e-14) + # From MATLAB function "subspace", which effectively only returns the + # last value that we calculate + x = np.array( + [[0.537667139546100, 0.318765239858981, 3.578396939725760, 0.725404224946106], # noqa: E501 + [1.833885014595086, -1.307688296305273, 2.769437029884877, -0.063054873189656], # noqa: E501 + [-2.258846861003648, -0.433592022305684, -1.349886940156521, 0.714742903826096], # noqa: E501 + [0.862173320368121, 0.342624466538650, 3.034923466331855, -0.204966058299775]]) # noqa: E501 + expected = 1.481454682101605 + assert_allclose(subspace_angles(x[:, :2], x[:, 2:])[0], expected, + rtol=1e-12) + assert_allclose(subspace_angles(x[:, 2:], x[:, :2])[0], expected, + rtol=1e-12) + expected = 0.746361174247302 + assert_allclose(subspace_angles(x[:, :2], x[:, [2]]), expected, rtol=1e-12) + assert_allclose(subspace_angles(x[:, [2]], x[:, :2]), expected, rtol=1e-12) + expected = 0.487163718534313 + assert_allclose(subspace_angles(x[:, :3], x[:, [3]]), expected, rtol=1e-12) + assert_allclose(subspace_angles(x[:, [3]], x[:, :3]), expected, rtol=1e-12) + expected = 0.328950515907756 + assert_allclose(subspace_angles(x[:, :2], x[:, 1:]), [expected, 0], + atol=1e-12) + # Degenerate conditions + assert_raises(ValueError, subspace_angles, x[0], x) + assert_raises(ValueError, subspace_angles, x, x[0]) + assert_raises(ValueError, subspace_angles, x[:-1], x) + + # Test branch if mask.any is True: + A = np.array([[1, 0, 0], + [0, 1, 0], + [0, 0, 1], + [0, 0, 0], + [0, 0, 0]]) + B = np.array([[1, 0, 0], + [0, 1, 0], + [0, 0, 0], + [0, 0, 0], + [0, 0, 1]]) + expected = np.array([np.pi/2, 0, 0]) + assert_allclose(subspace_angles(A, B), expected, rtol=1e-12) + + # Complex + # second column in "b" does not affect result, just there so that + # b can have more cols than a, and vice-versa (both conditional code paths) + a = [[1 + 1j], [0]] + b = [[1 - 1j, 0], [0, 1]] + assert_allclose(subspace_angles(a, b), 0., atol=1e-14) + assert_allclose(subspace_angles(b, a), 0., atol=1e-14) + + # Empty + a = np.empty((0, 0)) + b = np.empty((0, 0)) + assert_allclose(subspace_angles(a, b), np.empty((0,))) + a = np.empty((2, 0)) + b = np.empty((2, 0)) + assert_allclose(subspace_angles(a, b), np.empty((0,))) + a = np.empty((0, 2)) + b = np.empty((0, 3)) + assert_allclose(subspace_angles(a, b), np.empty((0,))) + + +class TestCDF2RDF: + + def matmul(self, a, b): + return np.einsum('...ij,...jk->...ik', a, b) + + def assert_eig_valid(self, w, v, x): + assert_array_almost_equal( + self.matmul(v, w), + self.matmul(x, v) + ) + + def test_single_array0x0real(self): + # eig doesn't support 0x0 in old versions of numpy + X = np.empty((0, 0)) + w, v = np.empty(0), np.empty((0, 0)) + wr, vr = cdf2rdf(w, v) + self.assert_eig_valid(wr, vr, X) + + def test_single_array2x2_real(self): + X = np.array([[1, 2], [3, -1]]) + w, v = np.linalg.eig(X) + wr, vr = cdf2rdf(w, v) + self.assert_eig_valid(wr, vr, X) + + def test_single_array2x2_complex(self): + X = np.array([[1, 2], [-2, 1]]) + w, v = np.linalg.eig(X) + wr, vr = cdf2rdf(w, v) + self.assert_eig_valid(wr, vr, X) + + def test_single_array3x3_real(self): + X = np.array([[1, 2, 3], [1, 2, 3], [2, 5, 6]]) + w, v = np.linalg.eig(X) + wr, vr = cdf2rdf(w, v) + self.assert_eig_valid(wr, vr, X) + + def test_single_array3x3_complex(self): + X = np.array([[1, 2, 3], [0, 4, 5], [0, -5, 4]]) + w, v = np.linalg.eig(X) + wr, vr = cdf2rdf(w, v) + self.assert_eig_valid(wr, vr, X) + + def test_random_1d_stacked_arrays(self): + # cannot test M == 0 due to bug in old numpy + for M in range(1, 7): + np.random.seed(999999999) + X = np.random.rand(100, M, M) + w, v = np.linalg.eig(X) + wr, vr = cdf2rdf(w, v) + self.assert_eig_valid(wr, vr, X) + + def test_random_2d_stacked_arrays(self): + # cannot test M == 0 due to bug in old numpy + for M in range(1, 7): + X = np.random.rand(10, 10, M, M) + w, v = np.linalg.eig(X) + wr, vr = cdf2rdf(w, v) + self.assert_eig_valid(wr, vr, X) + + def test_low_dimensionality_error(self): + w, v = np.empty(()), np.array((2,)) + assert_raises(ValueError, cdf2rdf, w, v) + + def test_not_square_error(self): + # Check that passing a non-square array raises a ValueError. + w, v = np.arange(3), np.arange(6).reshape(3, 2) + assert_raises(ValueError, cdf2rdf, w, v) + + def test_swapped_v_w_error(self): + # Check that exchanging places of w and v raises ValueError. + X = np.array([[1, 2, 3], [0, 4, 5], [0, -5, 4]]) + w, v = np.linalg.eig(X) + assert_raises(ValueError, cdf2rdf, v, w) + + def test_non_associated_error(self): + # Check that passing non-associated eigenvectors raises a ValueError. + w, v = np.arange(3), np.arange(16).reshape(4, 4) + assert_raises(ValueError, cdf2rdf, w, v) + + def test_not_conjugate_pairs(self): + # Check that passing non-conjugate pairs raises a ValueError. + X = np.array([[1, 2, 3], [1, 2, 3], [2, 5, 6+1j]]) + w, v = np.linalg.eig(X) + assert_raises(ValueError, cdf2rdf, w, v) + + # different arrays in the stack, so not conjugate + X = np.array([ + [[1, 2, 3], [1, 2, 3], [2, 5, 6+1j]], + [[1, 2, 3], [1, 2, 3], [2, 5, 6-1j]], + ]) + w, v = np.linalg.eig(X) + assert_raises(ValueError, cdf2rdf, w, v) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_cholesky.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_cholesky.py new file mode 100644 index 0000000000000000000000000000000000000000..61bbc7e544f10fc834034fbadd7141f6deb1d423 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_cholesky.py @@ -0,0 +1,268 @@ +import pytest +import numpy as np +from numpy.testing import assert_array_almost_equal +from pytest import raises as assert_raises + +from numpy import array, transpose, dot, conjugate, zeros_like, empty +from numpy.random import random +from scipy.linalg import (cholesky, cholesky_banded, cho_solve_banded, + cho_factor, cho_solve) + +from scipy.linalg._testutils import assert_no_overwrite + + +class TestCholesky: + + def test_simple(self): + a = [[8, 2, 3], [2, 9, 3], [3, 3, 6]] + c = cholesky(a) + assert_array_almost_equal(dot(transpose(c), c), a) + c = transpose(c) + a = dot(c, transpose(c)) + assert_array_almost_equal(cholesky(a, lower=1), c) + + def test_check_finite(self): + a = [[8, 2, 3], [2, 9, 3], [3, 3, 6]] + c = cholesky(a, check_finite=False) + assert_array_almost_equal(dot(transpose(c), c), a) + c = transpose(c) + a = dot(c, transpose(c)) + assert_array_almost_equal(cholesky(a, lower=1, check_finite=False), c) + + def test_simple_complex(self): + m = array([[3+1j, 3+4j, 5], [0, 2+2j, 2+7j], [0, 0, 7+4j]]) + a = dot(transpose(conjugate(m)), m) + c = cholesky(a) + a1 = dot(transpose(conjugate(c)), c) + assert_array_almost_equal(a, a1) + c = transpose(c) + a = dot(c, transpose(conjugate(c))) + assert_array_almost_equal(cholesky(a, lower=1), c) + + def test_random(self): + n = 20 + for k in range(2): + m = random([n, n]) + for i in range(n): + m[i, i] = 20*(.1+m[i, i]) + a = dot(transpose(m), m) + c = cholesky(a) + a1 = dot(transpose(c), c) + assert_array_almost_equal(a, a1) + c = transpose(c) + a = dot(c, transpose(c)) + assert_array_almost_equal(cholesky(a, lower=1), c) + + def test_random_complex(self): + n = 20 + for k in range(2): + m = random([n, n])+1j*random([n, n]) + for i in range(n): + m[i, i] = 20*(.1+abs(m[i, i])) + a = dot(transpose(conjugate(m)), m) + c = cholesky(a) + a1 = dot(transpose(conjugate(c)), c) + assert_array_almost_equal(a, a1) + c = transpose(c) + a = dot(c, transpose(conjugate(c))) + assert_array_almost_equal(cholesky(a, lower=1), c) + + @pytest.mark.xslow + def test_int_overflow(self): + # regression test for + # https://github.com/scipy/scipy/issues/17436 + # the problem was an int overflow in zeroing out + # the unused triangular part + n = 47_000 + x = np.eye(n, dtype=np.float64, order='F') + x[:4, :4] = np.array([[4, -2, 3, -1], + [-2, 4, -3, 1], + [3, -3, 5, 0], + [-1, 1, 0, 5]]) + + cholesky(x, check_finite=False, overwrite_a=True) # should not segfault + + @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) + @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64]) + def test_empty(self, dt, dt_b): + a = empty((0, 0), dtype=dt) + + c = cholesky(a) + assert c.shape == (0, 0) + assert c.dtype == cholesky(np.eye(2, dtype=dt)).dtype + + c_and_lower = (c, True) + b = np.asarray([], dtype=dt_b) + x = cho_solve(c_and_lower, b) + assert x.shape == (0,) + assert x.dtype == cho_solve((np.eye(2, dtype=dt), True), + np.ones(2, dtype=dt_b)).dtype + + b = empty((0, 0), dtype=dt_b) + x = cho_solve(c_and_lower, b) + assert x.shape == (0, 0) + assert x.dtype == cho_solve((np.eye(2, dtype=dt), True), + np.ones(2, dtype=dt_b)).dtype + + a1 = array([]) + a2 = array([[]]) + a3 = [] + a4 = [[]] + for x in ([a1, a2, a3, a4]): + assert_raises(ValueError, cholesky, x) + + +class TestCholeskyBanded: + """Tests for cholesky_banded() and cho_solve_banded.""" + + def test_check_finite(self): + # Symmetric positive definite banded matrix `a` + a = array([[4.0, 1.0, 0.0, 0.0], + [1.0, 4.0, 0.5, 0.0], + [0.0, 0.5, 4.0, 0.2], + [0.0, 0.0, 0.2, 4.0]]) + # Banded storage form of `a`. + ab = array([[-1.0, 1.0, 0.5, 0.2], + [4.0, 4.0, 4.0, 4.0]]) + c = cholesky_banded(ab, lower=False, check_finite=False) + ufac = zeros_like(a) + ufac[list(range(4)), list(range(4))] = c[-1] + ufac[(0, 1, 2), (1, 2, 3)] = c[0, 1:] + assert_array_almost_equal(a, dot(ufac.T, ufac)) + + b = array([0.0, 0.5, 4.2, 4.2]) + x = cho_solve_banded((c, False), b, check_finite=False) + assert_array_almost_equal(x, [0.0, 0.0, 1.0, 1.0]) + + def test_upper_real(self): + # Symmetric positive definite banded matrix `a` + a = array([[4.0, 1.0, 0.0, 0.0], + [1.0, 4.0, 0.5, 0.0], + [0.0, 0.5, 4.0, 0.2], + [0.0, 0.0, 0.2, 4.0]]) + # Banded storage form of `a`. + ab = array([[-1.0, 1.0, 0.5, 0.2], + [4.0, 4.0, 4.0, 4.0]]) + c = cholesky_banded(ab, lower=False) + ufac = zeros_like(a) + ufac[list(range(4)), list(range(4))] = c[-1] + ufac[(0, 1, 2), (1, 2, 3)] = c[0, 1:] + assert_array_almost_equal(a, dot(ufac.T, ufac)) + + b = array([0.0, 0.5, 4.2, 4.2]) + x = cho_solve_banded((c, False), b) + assert_array_almost_equal(x, [0.0, 0.0, 1.0, 1.0]) + + def test_upper_complex(self): + # Hermitian positive definite banded matrix `a` + a = array([[4.0, 1.0, 0.0, 0.0], + [1.0, 4.0, 0.5, 0.0], + [0.0, 0.5, 4.0, -0.2j], + [0.0, 0.0, 0.2j, 4.0]]) + # Banded storage form of `a`. + ab = array([[-1.0, 1.0, 0.5, -0.2j], + [4.0, 4.0, 4.0, 4.0]]) + c = cholesky_banded(ab, lower=False) + ufac = zeros_like(a) + ufac[list(range(4)), list(range(4))] = c[-1] + ufac[(0, 1, 2), (1, 2, 3)] = c[0, 1:] + assert_array_almost_equal(a, dot(ufac.conj().T, ufac)) + + b = array([0.0, 0.5, 4.0-0.2j, 0.2j + 4.0]) + x = cho_solve_banded((c, False), b) + assert_array_almost_equal(x, [0.0, 0.0, 1.0, 1.0]) + + def test_lower_real(self): + # Symmetric positive definite banded matrix `a` + a = array([[4.0, 1.0, 0.0, 0.0], + [1.0, 4.0, 0.5, 0.0], + [0.0, 0.5, 4.0, 0.2], + [0.0, 0.0, 0.2, 4.0]]) + # Banded storage form of `a`. + ab = array([[4.0, 4.0, 4.0, 4.0], + [1.0, 0.5, 0.2, -1.0]]) + c = cholesky_banded(ab, lower=True) + lfac = zeros_like(a) + lfac[list(range(4)), list(range(4))] = c[0] + lfac[(1, 2, 3), (0, 1, 2)] = c[1, :3] + assert_array_almost_equal(a, dot(lfac, lfac.T)) + + b = array([0.0, 0.5, 4.2, 4.2]) + x = cho_solve_banded((c, True), b) + assert_array_almost_equal(x, [0.0, 0.0, 1.0, 1.0]) + + def test_lower_complex(self): + # Hermitian positive definite banded matrix `a` + a = array([[4.0, 1.0, 0.0, 0.0], + [1.0, 4.0, 0.5, 0.0], + [0.0, 0.5, 4.0, -0.2j], + [0.0, 0.0, 0.2j, 4.0]]) + # Banded storage form of `a`. + ab = array([[4.0, 4.0, 4.0, 4.0], + [1.0, 0.5, 0.2j, -1.0]]) + c = cholesky_banded(ab, lower=True) + lfac = zeros_like(a) + lfac[list(range(4)), list(range(4))] = c[0] + lfac[(1, 2, 3), (0, 1, 2)] = c[1, :3] + assert_array_almost_equal(a, dot(lfac, lfac.conj().T)) + + b = array([0.0, 0.5j, 3.8j, 3.8]) + x = cho_solve_banded((c, True), b) + assert_array_almost_equal(x, [0.0, 0.0, 1.0j, 1.0]) + + @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) + @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64]) + def test_empty(self, dt, dt_b): + ab = empty((0, 0), dtype=dt) + + cb = cholesky_banded(ab) + assert cb.shape == (0, 0) + + m = cholesky_banded(np.array([[0, 0], [1, 1]], dtype=dt)) + assert cb.dtype == m.dtype + + cb_and_lower = (cb, True) + b = np.asarray([], dtype=dt_b) + x = cho_solve_banded(cb_and_lower, b) + assert x.shape == (0,) + + dtype_nonempty = cho_solve_banded((m, True), np.ones(2, dtype=dt_b)).dtype + assert x.dtype == dtype_nonempty + + b = empty((0, 0), dtype=dt_b) + x = cho_solve_banded(cb_and_lower, b) + assert x.shape == (0, 0) + assert x.dtype == dtype_nonempty + + +class TestOverwrite: + def test_cholesky(self): + assert_no_overwrite(cholesky, [(3, 3)]) + + def test_cho_factor(self): + assert_no_overwrite(cho_factor, [(3, 3)]) + + def test_cho_solve(self): + x = array([[2, -1, 0], [-1, 2, -1], [0, -1, 2]]) + xcho = cho_factor(x) + assert_no_overwrite(lambda b: cho_solve(xcho, b), [(3,)]) + + def test_cholesky_banded(self): + assert_no_overwrite(cholesky_banded, [(2, 3)]) + + def test_cho_solve_banded(self): + x = array([[0, -1, -1], [2, 2, 2]]) + xcho = cholesky_banded(x) + assert_no_overwrite(lambda b: cho_solve_banded((xcho, False), b), + [(3,)]) + +class TestChoFactor: + @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) + def test_empty(self, dt): + a = np.empty((0, 0), dtype=dt) + x, lower = cho_factor(a) + + assert x.shape == (0, 0) + + xx, lower = cho_factor(np.eye(2, dtype=dt)) + assert x.dtype == xx.dtype diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_cossin.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_cossin.py new file mode 100644 index 0000000000000000000000000000000000000000..df112f0e4cf75d03d2787c24306665b7027967ee --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_cossin.py @@ -0,0 +1,300 @@ +import pytest +import numpy as np +from numpy.random import default_rng +from numpy.testing import assert_allclose + +from scipy import linalg +from scipy.linalg.lapack import _compute_lwork +from scipy.stats import ortho_group, unitary_group +from scipy.linalg import cossin, get_lapack_funcs + +REAL_DTYPES = (np.float32, np.float64) +COMPLEX_DTYPES = (np.complex64, np.complex128) +DTYPES = REAL_DTYPES + COMPLEX_DTYPES + + +@pytest.mark.parametrize('dtype_', DTYPES) +@pytest.mark.parametrize('m, p, q', + [ + (2, 1, 1), + (3, 2, 1), + (3, 1, 2), + (4, 2, 2), + (4, 1, 2), + (40, 12, 20), + (40, 30, 1), + (40, 1, 30), + (100, 50, 1), + (100, 50, 50), + ]) +@pytest.mark.parametrize('swap_sign', [True, False]) +def test_cossin(dtype_, m, p, q, swap_sign): + rng = default_rng(1708093570726217) + if dtype_ in COMPLEX_DTYPES: + x = np.array(unitary_group.rvs(m, random_state=rng), dtype=dtype_) + else: + x = np.array(ortho_group.rvs(m, random_state=rng), dtype=dtype_) + + u, cs, vh = cossin(x, p, q, + swap_sign=swap_sign) + assert_allclose(x, u @ cs @ vh, rtol=0., atol=m*1e3*np.finfo(dtype_).eps) + assert u.dtype == dtype_ + # Test for float32 or float 64 + assert cs.dtype == np.real(u).dtype + assert vh.dtype == dtype_ + + u, cs, vh = cossin([x[:p, :q], x[:p, q:], x[p:, :q], x[p:, q:]], + swap_sign=swap_sign) + assert_allclose(x, u @ cs @ vh, rtol=0., atol=m*1e3*np.finfo(dtype_).eps) + assert u.dtype == dtype_ + assert cs.dtype == np.real(u).dtype + assert vh.dtype == dtype_ + + _, cs2, vh2 = cossin(x, p, q, + compute_u=False, + swap_sign=swap_sign) + assert_allclose(cs, cs2, rtol=0., atol=10*np.finfo(dtype_).eps) + assert_allclose(vh, vh2, rtol=0., atol=10*np.finfo(dtype_).eps) + + u2, cs2, _ = cossin(x, p, q, + compute_vh=False, + swap_sign=swap_sign) + assert_allclose(u, u2, rtol=0., atol=10*np.finfo(dtype_).eps) + assert_allclose(cs, cs2, rtol=0., atol=10*np.finfo(dtype_).eps) + + _, cs2, _ = cossin(x, p, q, + compute_u=False, + compute_vh=False, + swap_sign=swap_sign) + assert_allclose(cs, cs2, rtol=0., atol=10*np.finfo(dtype_).eps) + + +def test_cossin_mixed_types(): + rng = default_rng(1708093736390459) + x = np.array(ortho_group.rvs(4, random_state=rng), dtype=np.float64) + u, cs, vh = cossin([x[:2, :2], + np.array(x[:2, 2:], dtype=np.complex128), + x[2:, :2], + x[2:, 2:]]) + + assert u.dtype == np.complex128 + assert cs.dtype == np.float64 + assert vh.dtype == np.complex128 + assert_allclose(x, u @ cs @ vh, rtol=0., + atol=1e4 * np.finfo(np.complex128).eps) + + +def test_cossin_error_incorrect_subblocks(): + with pytest.raises(ValueError, match="be due to missing p, q arguments."): + cossin(([1, 2], [3, 4, 5], [6, 7], [8, 9, 10])) + + +def test_cossin_error_empty_subblocks(): + with pytest.raises(ValueError, match="x11.*empty"): + cossin(([], [], [], [])) + with pytest.raises(ValueError, match="x12.*empty"): + cossin(([1, 2], [], [6, 7], [8, 9, 10])) + with pytest.raises(ValueError, match="x21.*empty"): + cossin(([1, 2], [3, 4, 5], [], [8, 9, 10])) + with pytest.raises(ValueError, match="x22.*empty"): + cossin(([1, 2], [3, 4, 5], [2], [])) + + +def test_cossin_error_missing_partitioning(): + with pytest.raises(ValueError, match=".*exactly four arrays.* got 2"): + cossin(unitary_group.rvs(2)) + + with pytest.raises(ValueError, match=".*might be due to missing p, q"): + cossin(unitary_group.rvs(4)) + + +def test_cossin_error_non_iterable(): + with pytest.raises(ValueError, match="containing the subblocks of X"): + cossin(12j) + + +def test_cossin_error_non_square(): + with pytest.raises(ValueError, match="only supports square"): + cossin(np.array([[1, 2]]), 1, 1) + + +def test_cossin_error_partitioning(): + x = np.array(ortho_group.rvs(4), dtype=np.float64) + with pytest.raises(ValueError, match="invalid p=0.*0= m) or (q >= m): + pytest.skip("`0 < p < m` and `0 < q < m` must hold") + + # Generate unitary input + rng = np.random.default_rng(329548272348596421) + X = unitary_group.rvs(m, random_state=rng) + np.testing.assert_allclose(X @ X.conj().T, np.eye(m), atol=1e-15) + + # Perform the decomposition + u0, cs0, vh0 = linalg.cossin(X, p=p, q=q, separate=True, swap_sign=swap_sign) + u1, u2 = u0 + v1, v2 = vh0 + v1, v2 = v1.conj().T, v2.conj().T + + # "U1, U2, V1, V2 are square orthogonal/unitary matrices + # of dimensions (p,p), (m-p,m-p), (q,q), and (m-q,m-q) respectively" + np.testing.assert_allclose(u1 @ u1.conj().T, np.eye(p), atol=1e-13) + np.testing.assert_allclose(u2 @ u2.conj().T, np.eye(m-p), atol=1e-13) + np.testing.assert_allclose(v1 @ v1.conj().T, np.eye(q), atol=1e-13) + np.testing.assert_allclose(v2 @ v2.conj().T, np.eye(m-q), atol=1e-13) + + # "and C and S are (r, r) nonnegative diagonal matrices..." + C = np.diag(np.cos(cs0)) + S = np.diag(np.sin(cs0)) + # "...satisfying C^2 + S^2 = I where r = min(p, m-p, q, m-q)." + r = min(p, m-p, q, m-q) + np.testing.assert_allclose(C**2 + S**2, np.eye(r)) + + # "Moreover, the rank of the identity matrices are + # min(p, q) - r, min(p, m - q) - r, min(m - p, q) - r, + # and min(m - p, m - q) - r respectively." + I11 = np.eye(min(p, q) - r) + I12 = np.eye(min(p, m - q) - r) + I21 = np.eye(min(m - p, q) - r) + I22 = np.eye(min(m - p, m - q) - r) + + # From: + # ┌ ┐ + # │ I 0 0 │ 0 0 0 │ + # ┌ ┐ ┌ ┐│ 0 C 0 │ 0 -S 0 │┌ ┐* + # │ X11 │ X12 │ │ U1 │ ││ 0 0 0 │ 0 0 -I ││ V1 │ │ + # │ ────┼──── │ = │────┼────││─────────┼─────────││────┼────│ + # │ X21 │ X22 │ │ │ U2 ││ 0 0 0 │ I 0 0 ││ │ V2 │ + # └ ┘ └ ┘│ 0 S 0 │ 0 C 0 │└ ┘ + # │ 0 0 I │ 0 0 0 │ + # └ ┘ + + # We can see that U and V are block diagonal matrices like so: + U = linalg.block_diag(u1, u2) + V = linalg.block_diag(v1, v2) + + # And the center matrix, which we'll call Q here, must be: + Q11 = np.zeros((u1.shape[1], v1.shape[0])) + IC11 = linalg.block_diag(I11, C) + Q11[:IC11.shape[0], :IC11.shape[1]] = IC11 + + Q12 = np.zeros((u1.shape[1], v2.shape[0])) + SI12 = linalg.block_diag(S, I12) if swap_sign else linalg.block_diag(-S, -I12) + Q12[-SI12.shape[0]:, -SI12.shape[1]:] = SI12 + + Q21 = np.zeros((u2.shape[1], v1.shape[0])) + SI21 = linalg.block_diag(-S, -I21) if swap_sign else linalg.block_diag(S, I21) + Q21[-SI21.shape[0]:, -SI21.shape[1]:] = SI21 + + Q22 = np.zeros((u2.shape[1], v2.shape[0])) + IC22 = linalg.block_diag(I22, C) + Q22[:IC22.shape[0], :IC22.shape[1]] = IC22 + + Q = np.block([[Q11, Q12], [Q21, Q22]]) + + # Confirm that `cossin` decomposes `X` as shown + np.testing.assert_allclose(X, U @ Q @ V.conj().T) + + # And check that `separate=False` agrees + U0, CS0, Vh0 = linalg.cossin(X, p=p, q=q, swap_sign=swap_sign) + np.testing.assert_allclose(U, U0) + np.testing.assert_allclose(Q, CS0) + np.testing.assert_allclose(V, Vh0.conj().T) + + # Confirm that `compute_u`/`compute_vh` don't affect the results + kwargs = dict(p=p, q=q, swap_sign=swap_sign) + + # `compute_u=False` + u, cs, vh = linalg.cossin(X, separate=True, compute_u=False, **kwargs) + assert u[0].shape == (0, 0) # probably not ideal, but this is what it does + assert u[1].shape == (0, 0) + assert_allclose(cs, cs0, rtol=1e-15) + assert_allclose(vh[0], vh0[0], rtol=1e-15) + assert_allclose(vh[1], vh0[1], rtol=1e-15) + + U, CS, Vh = linalg.cossin(X, compute_u=False, **kwargs) + assert U.shape == (0, 0) + assert_allclose(CS, CS0, rtol=1e-15) + assert_allclose(Vh, Vh0, rtol=1e-15) + + # `compute_vh=False` + u, cs, vh = linalg.cossin(X, separate=True, compute_vh=False, **kwargs) + assert_allclose(u[0], u[0], rtol=1e-15) + assert_allclose(u[1], u[1], rtol=1e-15) + assert_allclose(cs, cs0, rtol=1e-15) + assert vh[0].shape == (0, 0) + assert vh[1].shape == (0, 0) + + U, CS, Vh = linalg.cossin(X, compute_vh=False, **kwargs) + assert_allclose(U, U0, rtol=1e-15) + assert_allclose(CS, CS0, rtol=1e-15) + assert Vh.shape == (0, 0) + + # `compute_u=False, compute_vh=False` + u, cs, vh = linalg.cossin(X, separate=True, compute_u=False, + compute_vh=False, **kwargs) + assert u[0].shape == (0, 0) + assert u[1].shape == (0, 0) + assert_allclose(cs, cs0, rtol=1e-15) + assert vh[0].shape == (0, 0) + assert vh[1].shape == (0, 0) + + U, CS, Vh = linalg.cossin(X, compute_u=False, compute_vh=False, **kwargs) + assert U.shape == (0, 0) + assert_allclose(CS, CS0, rtol=1e-15) + assert Vh.shape == (0, 0) + + +def test_indexing_bug_gh19365(): + # Regression test for gh-19365, which reported a bug with `separate=False` + rng = np.random.default_rng(32954827234421) + m = rng.integers(50, high=100) + p = rng.integers(10, 40) # always p < m + q = rng.integers(m - p + 1, m - 1) # always m-p < q < m + X = unitary_group.rvs(m, random_state=rng) # random unitary matrix + U, D, Vt = linalg.cossin(X, p=p, q=q, separate=False) + assert np.allclose(U @ D @ Vt, X) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_ldl.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_ldl.py new file mode 100644 index 0000000000000000000000000000000000000000..2d74a746b4dd7bb6367500b4c893aa9f767de51f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_ldl.py @@ -0,0 +1,137 @@ +from numpy.testing import assert_array_almost_equal, assert_allclose, assert_ +from numpy import (array, eye, zeros, empty_like, empty, tril_indices_from, + tril, triu_indices_from, spacing, float32, float64, + complex64, complex128) +from numpy.random import rand, randint, seed +from scipy.linalg import ldl +from scipy._lib._util import ComplexWarning +import pytest +from pytest import raises as assert_raises, warns + + +@pytest.mark.thread_unsafe +def test_args(): + A = eye(3) + # Nonsquare array + assert_raises(ValueError, ldl, A[:, :2]) + # Complex matrix with imaginary diagonal entries with "hermitian=True" + with warns(ComplexWarning): + ldl(A*1j) + + +def test_empty_array(): + a = empty((0, 0), dtype=complex) + l, d, p = ldl(empty((0, 0))) + assert_array_almost_equal(l, empty_like(a)) + assert_array_almost_equal(d, empty_like(a)) + assert_array_almost_equal(p, array([], dtype=int)) + + +def test_simple(): + a = array([[-0.39-0.71j, 5.14-0.64j, -7.86-2.96j, 3.80+0.92j], + [5.14-0.64j, 8.86+1.81j, -3.52+0.58j, 5.32-1.59j], + [-7.86-2.96j, -3.52+0.58j, -2.83-0.03j, -1.54-2.86j], + [3.80+0.92j, 5.32-1.59j, -1.54-2.86j, -0.56+0.12j]]) + b = array([[5., 10, 1, 18], + [10., 2, 11, 1], + [1., 11, 19, 9], + [18., 1, 9, 0]]) + c = array([[52., 97, 112, 107, 50], + [97., 114, 89, 98, 13], + [112., 89, 64, 33, 6], + [107., 98, 33, 60, 73], + [50., 13, 6, 73, 77]]) + + d = array([[2., 2, -4, 0, 4], + [2., -2, -2, 10, -8], + [-4., -2, 6, -8, -4], + [0., 10, -8, 6, -6], + [4., -8, -4, -6, 10]]) + e = array([[-1.36+0.00j, 0+0j, 0+0j, 0+0j], + [1.58-0.90j, -8.87+0j, 0+0j, 0+0j], + [2.21+0.21j, -1.84+0.03j, -4.63+0j, 0+0j], + [3.91-1.50j, -1.78-1.18j, 0.11-0.11j, -1.84+0.00j]]) + for x in (b, c, d): + l, d, p = ldl(x) + assert_allclose(l.dot(d).dot(l.T), x, atol=spacing(1000.), rtol=0) + + u, d, p = ldl(x, lower=False) + assert_allclose(u.dot(d).dot(u.T), x, atol=spacing(1000.), rtol=0) + + l, d, p = ldl(a, hermitian=False) + assert_allclose(l.dot(d).dot(l.T), a, atol=spacing(1000.), rtol=0) + + u, d, p = ldl(a, lower=False, hermitian=False) + assert_allclose(u.dot(d).dot(u.T), a, atol=spacing(1000.), rtol=0) + + # Use upper part for the computation and use the lower part for comparison + l, d, p = ldl(e.conj().T, lower=0) + assert_allclose(tril(l.dot(d).dot(l.conj().T)-e), zeros((4, 4)), + atol=spacing(1000.), rtol=0) + + +def test_permutations(): + seed(1234) + for _ in range(10): + n = randint(1, 100) + # Random real/complex array + x = rand(n, n) if randint(2) else rand(n, n) + rand(n, n)*1j + x = x + x.conj().T + x += eye(n)*randint(5, 1e6) + l_ind = tril_indices_from(x, k=-1) + u_ind = triu_indices_from(x, k=1) + + # Test whether permutations lead to a triangular array + u, d, p = ldl(x, lower=0) + # lower part should be zero + assert_(not any(u[p, :][l_ind]), f'Spin {_} failed') + + l, d, p = ldl(x, lower=1) + # upper part should be zero + assert_(not any(l[p, :][u_ind]), f'Spin {_} failed') + + +@pytest.mark.parametrize("dtype", [float32, float64]) +@pytest.mark.parametrize("n", [30, 150]) +def test_ldl_type_size_combinations_real(n, dtype): + seed(1234) + msg = (f"Failed for size: {n}, dtype: {dtype}") + + x = rand(n, n).astype(dtype) + x = x + x.T + x += eye(n, dtype=dtype)*dtype(randint(5, 1e6)) + + l, d1, p = ldl(x) + u, d2, p = ldl(x, lower=0) + rtol = 1e-4 if dtype is float32 else 1e-10 + assert_allclose(l.dot(d1).dot(l.T), x, rtol=rtol, err_msg=msg) + assert_allclose(u.dot(d2).dot(u.T), x, rtol=rtol, err_msg=msg) + + +@pytest.mark.parametrize("dtype", [complex64, complex128]) +@pytest.mark.parametrize("n", [30, 150]) +def test_ldl_type_size_combinations_complex(n, dtype): + seed(1234) + msg1 = (f"Her failed for size: {n}, dtype: {dtype}") + msg2 = (f"Sym failed for size: {n}, dtype: {dtype}") + + # Complex hermitian upper/lower + x = (rand(n, n)+1j*rand(n, n)).astype(dtype) + x = x+x.conj().T + x += eye(n, dtype=dtype)*dtype(randint(5, 1e6)) + + l, d1, p = ldl(x) + u, d2, p = ldl(x, lower=0) + rtol = 2e-4 if dtype is complex64 else 1e-10 + assert_allclose(l.dot(d1).dot(l.conj().T), x, rtol=rtol, err_msg=msg1) + assert_allclose(u.dot(d2).dot(u.conj().T), x, rtol=rtol, err_msg=msg1) + + # Complex symmetric upper/lower + x = (rand(n, n)+1j*rand(n, n)).astype(dtype) + x = x+x.T + x += eye(n, dtype=dtype)*dtype(randint(5, 1e6)) + + l, d1, p = ldl(x, hermitian=0) + u, d2, p = ldl(x, lower=0, hermitian=0) + assert_allclose(l.dot(d1).dot(l.T), x, rtol=rtol, err_msg=msg2) + assert_allclose(u.dot(d2).dot(u.T), x, rtol=rtol, err_msg=msg2) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_lu.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_lu.py new file mode 100644 index 0000000000000000000000000000000000000000..da0beccf1f0e66baf4ac4ec80d7ff7129b2df345 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_lu.py @@ -0,0 +1,308 @@ +import pytest +from pytest import raises as assert_raises + +import numpy as np +from scipy.linalg import lu, lu_factor, lu_solve, get_lapack_funcs, solve +from numpy.testing import assert_allclose, assert_array_equal, assert_equal + + +REAL_DTYPES = [np.float32, np.float64] +COMPLEX_DTYPES = [np.complex64, np.complex128] +DTYPES = REAL_DTYPES + COMPLEX_DTYPES + + +class TestLU: + def setup_method(self): + self.rng = np.random.default_rng(1682281250228846) + + def test_old_lu_smoke_tests(self): + "Tests from old fortran based lu test suite" + a = np.array([[1, 2, 3], [1, 2, 3], [2, 5, 6]]) + p, l, u = lu(a) + result_lu = np.array([[2., 5., 6.], [0.5, -0.5, 0.], [0.5, 1., 0.]]) + assert_allclose(p, np.rot90(np.eye(3))) + assert_allclose(l, np.tril(result_lu, k=-1)+np.eye(3)) + assert_allclose(u, np.triu(result_lu)) + + a = np.array([[1, 2, 3], [1, 2, 3], [2, 5j, 6]]) + p, l, u = lu(a) + result_lu = np.array([[2., 5.j, 6.], [0.5, 2-2.5j, 0.], [0.5, 1., 0.]]) + assert_allclose(p, np.rot90(np.eye(3))) + assert_allclose(l, np.tril(result_lu, k=-1)+np.eye(3)) + assert_allclose(u, np.triu(result_lu)) + + b = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + p, l, u = lu(b) + assert_allclose(p, np.array([[0, 1, 0], [0, 0, 1], [1, 0, 0]])) + assert_allclose(l, np.array([[1, 0, 0], [1/7, 1, 0], [4/7, 0.5, 1]])) + assert_allclose(u, np.array([[7, 8, 9], [0, 6/7, 12/7], [0, 0, 0]]), + rtol=0., atol=1e-14) + + cb = np.array([[1.j, 2.j, 3.j], [4j, 5j, 6j], [7j, 8j, 9j]]) + p, l, u = lu(cb) + assert_allclose(p, np.array([[0, 1, 0], [0, 0, 1], [1, 0, 0]])) + assert_allclose(l, np.array([[1, 0, 0], [1/7, 1, 0], [4/7, 0.5, 1]])) + assert_allclose(u, np.array([[7, 8, 9], [0, 6/7, 12/7], [0, 0, 0]])*1j, + rtol=0., atol=1e-14) + + # Rectangular matrices + hrect = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 12, 12]]) + p, l, u = lu(hrect) + assert_allclose(p, np.array([[0, 1, 0], [0, 0, 1], [1, 0, 0]])) + assert_allclose(l, np.array([[1, 0, 0], [1/9, 1, 0], [5/9, 0.5, 1]])) + assert_allclose(u, np.array([[9, 10, 12, 12], [0, 8/9, 15/9, 24/9], + [0, 0, -0.5, 0]]), rtol=0., atol=1e-14) + + chrect = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 12, 12]])*1.j + p, l, u = lu(chrect) + assert_allclose(p, np.array([[0, 1, 0], [0, 0, 1], [1, 0, 0]])) + assert_allclose(l, np.array([[1, 0, 0], [1/9, 1, 0], [5/9, 0.5, 1]])) + assert_allclose(u, np.array([[9, 10, 12, 12], [0, 8/9, 15/9, 24/9], + [0, 0, -0.5, 0]])*1j, rtol=0., atol=1e-14) + + vrect = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 12, 12]]) + p, l, u = lu(vrect) + assert_allclose(p, np.eye(4)[[1, 3, 2, 0], :]) + assert_allclose(l, np.array([[1., 0, 0], [0.1, 1, 0], [0.7, -0.5, 1], + [0.4, 0.25, 0.5]])) + assert_allclose(u, np.array([[10, 12, 12], + [0, 0.8, 1.8], + [0, 0, 1.5]])) + + cvrect = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 12, 12]])*1j + p, l, u = lu(cvrect) + assert_allclose(p, np.eye(4)[[1, 3, 2, 0], :]) + assert_allclose(l, np.array([[1., 0, 0], + [0.1, 1, 0], + [0.7, -0.5, 1], + [0.4, 0.25, 0.5]])) + assert_allclose(u, np.array([[10, 12, 12], + [0, 0.8, 1.8], + [0, 0, 1.5]])*1j) + + @pytest.mark.parametrize('shape', [[2, 2], [2, 4], [4, 2], [20, 20], + [20, 4], [4, 20], [3, 2, 9, 9], + [2, 2, 17, 5], [2, 2, 11, 7]]) + def test_simple_lu_shapes_real_complex(self, shape): + a = self.rng.uniform(-10., 10., size=shape) + p, l, u = lu(a) + assert_allclose(a, p @ l @ u) + pl, u = lu(a, permute_l=True) + assert_allclose(a, pl @ u) + + b = self.rng.uniform(-10., 10., size=shape)*1j + b += self.rng.uniform(-10, 10, size=shape) + pl, u = lu(b, permute_l=True) + assert_allclose(b, pl @ u) + + @pytest.mark.parametrize('shape', [[2, 2], [2, 4], [4, 2], [20, 20], + [20, 4], [4, 20]]) + def test_simple_lu_shapes_real_complex_2d_indices(self, shape): + a = self.rng.uniform(-10., 10., size=shape) + p, l, u = lu(a, p_indices=True) + assert_allclose(a, l[p, :] @ u) + + def test_1by1_input_output(self): + a = self.rng.random([4, 5, 1, 1], dtype=np.float32) + p, l, u = lu(a, p_indices=True) + assert_allclose(p, np.zeros(shape=(4, 5, 1), dtype=int)) + assert_allclose(l, np.ones(shape=(4, 5, 1, 1), dtype=np.float32)) + assert_allclose(u, a) + + a = self.rng.random([4, 5, 1, 1], dtype=np.float32) + p, l, u = lu(a) + assert_allclose(p, np.ones(shape=(4, 5, 1, 1), dtype=np.float32)) + assert_allclose(l, np.ones(shape=(4, 5, 1, 1), dtype=np.float32)) + assert_allclose(u, a) + + pl, u = lu(a, permute_l=True) + assert_allclose(pl, np.ones(shape=(4, 5, 1, 1), dtype=np.float32)) + assert_allclose(u, a) + + a = self.rng.random([4, 5, 1, 1], dtype=np.float32)*np.complex64(1.j) + p, l, u = lu(a) + assert_allclose(p, np.ones(shape=(4, 5, 1, 1), dtype=np.complex64)) + assert_allclose(l, np.ones(shape=(4, 5, 1, 1), dtype=np.complex64)) + assert_allclose(u, a) + + def test_empty_edge_cases(self): + a = np.empty([0, 0]) + p, l, u = lu(a) + assert_allclose(p, np.empty(shape=(0, 0), dtype=np.float64)) + assert_allclose(l, np.empty(shape=(0, 0), dtype=np.float64)) + assert_allclose(u, np.empty(shape=(0, 0), dtype=np.float64)) + + a = np.empty([0, 3], dtype=np.float16) + p, l, u = lu(a) + assert_allclose(p, np.empty(shape=(0, 0), dtype=np.float32)) + assert_allclose(l, np.empty(shape=(0, 0), dtype=np.float32)) + assert_allclose(u, np.empty(shape=(0, 3), dtype=np.float32)) + + a = np.empty([3, 0], dtype=np.complex64) + p, l, u = lu(a) + assert_allclose(p, np.empty(shape=(0, 0), dtype=np.float32)) + assert_allclose(l, np.empty(shape=(3, 0), dtype=np.complex64)) + assert_allclose(u, np.empty(shape=(0, 0), dtype=np.complex64)) + p, l, u = lu(a, p_indices=True) + assert_allclose(p, np.empty(shape=(0,), dtype=int)) + assert_allclose(l, np.empty(shape=(3, 0), dtype=np.complex64)) + assert_allclose(u, np.empty(shape=(0, 0), dtype=np.complex64)) + pl, u = lu(a, permute_l=True) + assert_allclose(pl, np.empty(shape=(3, 0), dtype=np.complex64)) + assert_allclose(u, np.empty(shape=(0, 0), dtype=np.complex64)) + + a = np.empty([3, 0, 0], dtype=np.complex64) + p, l, u = lu(a) + assert_allclose(p, np.empty(shape=(3, 0, 0), dtype=np.float32)) + assert_allclose(l, np.empty(shape=(3, 0, 0), dtype=np.complex64)) + assert_allclose(u, np.empty(shape=(3, 0, 0), dtype=np.complex64)) + + a = np.empty([0, 0, 3]) + p, l, u = lu(a) + assert_allclose(p, np.empty(shape=(0, 0, 0))) + assert_allclose(l, np.empty(shape=(0, 0, 0))) + assert_allclose(u, np.empty(shape=(0, 0, 3))) + + with assert_raises(ValueError, match='at least two-dimensional'): + lu(np.array([])) + + a = np.array([[]]) + p, l, u = lu(a) + assert_allclose(p, np.empty(shape=(0, 0))) + assert_allclose(l, np.empty(shape=(1, 0))) + assert_allclose(u, np.empty(shape=(0, 0))) + + a = np.array([[[]]]) + p, l, u = lu(a) + assert_allclose(p, np.empty(shape=(1, 0, 0))) + assert_allclose(l, np.empty(shape=(1, 1, 0))) + assert_allclose(u, np.empty(shape=(1, 0, 0))) + + +class TestLUFactor: + def setup_method(self): + self.rng = np.random.default_rng(1682281250228846) + + self.a = np.array([[1, 2, 3], [1, 2, 3], [2, 5, 6]]) + self.ca = np.array([[1, 2, 3], [1, 2, 3], [2, 5j, 6]]) + # Those matrices are more robust to detect problems in permutation + # matrices than the ones above + self.b = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + self.cb = np.array([[1j, 2j, 3j], [4j, 5j, 6j], [7j, 8j, 9j]]) + + # Rectangular matrices + self.hrect = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 12, 12]]) + self.chrect = np.array([[1, 2, 3, 4], [5, 6, 7, 8], + [9, 10, 12, 12]]) * 1.j + + self.vrect = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 12, 12]]) + self.cvrect = 1.j * np.array([[1, 2, 3], + [4, 5, 6], + [7, 8, 9], + [10, 12, 12]]) + + # Medium sizes matrices + self.med = self.rng.random((30, 40)) + self.cmed = self.rng.random((30, 40)) + 1.j*self.rng.random((30, 40)) + + def _test_common_lu_factor(self, data): + l_and_u1, piv1 = lu_factor(data) + (getrf,) = get_lapack_funcs(("getrf",), (data,)) + l_and_u2, piv2, _ = getrf(data, overwrite_a=False) + assert_allclose(l_and_u1, l_and_u2) + assert_allclose(piv1, piv2) + + # Simple tests. + # For lu_factor gives a LinAlgWarning because these matrices are singular + def test_hrectangular(self): + self._test_common_lu_factor(self.hrect) + + def test_vrectangular(self): + self._test_common_lu_factor(self.vrect) + + def test_hrectangular_complex(self): + self._test_common_lu_factor(self.chrect) + + def test_vrectangular_complex(self): + self._test_common_lu_factor(self.cvrect) + + # Bigger matrices + def test_medium1(self): + """Check lu decomposition on medium size, rectangular matrix.""" + self._test_common_lu_factor(self.med) + + def test_medium1_complex(self): + """Check lu decomposition on medium size, rectangular matrix.""" + self._test_common_lu_factor(self.cmed) + + def test_check_finite(self): + p, l, u = lu(self.a, check_finite=False) + assert_allclose(p @ l @ u, self.a) + + def test_simple_known(self): + # Ticket #1458 + for order in ['C', 'F']: + A = np.array([[2, 1], [0, 1.]], order=order) + LU, P = lu_factor(A) + assert_allclose(LU, np.array([[2, 1], [0, 1]])) + assert_array_equal(P, np.array([0, 1])) + + @pytest.mark.parametrize("m", [0, 1, 2]) + @pytest.mark.parametrize("n", [0, 1, 2]) + @pytest.mark.parametrize('dtype', DTYPES) + def test_shape_dtype(self, m, n, dtype): + k = min(m, n) + + a = np.eye(m, n, dtype=dtype) + lu, p = lu_factor(a) + assert_equal(lu.shape, (m, n)) + assert_equal(lu.dtype, dtype) + assert_equal(p.shape, (k,)) + assert_equal(p.dtype, np.int32) + + @pytest.mark.parametrize(("m", "n"), [(0, 0), (0, 2), (2, 0)]) + def test_empty(self, m, n): + a = np.zeros((m, n)) + lu, p = lu_factor(a) + assert_allclose(lu, np.empty((m, n))) + assert_allclose(p, np.arange(0)) + + +class TestLUSolve: + def setup_method(self): + self.rng = np.random.default_rng(1682281250228846) + + def test_lu(self): + a0 = self.rng.random((10, 10)) + b = self.rng.random((10,)) + + for order in ['C', 'F']: + a = np.array(a0, order=order) + x1 = solve(a, b) + lu_a = lu_factor(a) + x2 = lu_solve(lu_a, b) + assert_allclose(x1, x2) + + def test_check_finite(self): + a = self.rng.random((10, 10)) + b = self.rng.random((10,)) + x1 = solve(a, b) + lu_a = lu_factor(a, check_finite=False) + x2 = lu_solve(lu_a, b, check_finite=False) + assert_allclose(x1, x2) + + @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) + @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64]) + def test_empty(self, dt, dt_b): + lu_and_piv = (np.empty((0, 0), dtype=dt), np.array([])) + b = np.asarray([], dtype=dt_b) + x = lu_solve(lu_and_piv, b) + assert x.shape == (0,) + + m = lu_solve((np.eye(2, dtype=dt), [0, 1]), np.ones(2, dtype=dt_b)) + assert x.dtype == m.dtype + + b = np.empty((0, 0), dtype=dt_b) + x = lu_solve(lu_and_piv, b) + assert x.shape == (0, 0) + assert x.dtype == m.dtype diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_polar.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_polar.py new file mode 100644 index 0000000000000000000000000000000000000000..607238842b3cc643d9665e40f29e41b15d8951a1 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_polar.py @@ -0,0 +1,110 @@ +import pytest +import numpy as np +from numpy.linalg import norm +from numpy.testing import (assert_, assert_allclose, assert_equal) +from scipy.linalg import polar, eigh + + +diag2 = np.array([[2, 0], [0, 3]]) +a13 = np.array([[1, 2, 2]]) + +precomputed_cases = [ + [[[0]], 'right', [[1]], [[0]]], + [[[0]], 'left', [[1]], [[0]]], + [[[9]], 'right', [[1]], [[9]]], + [[[9]], 'left', [[1]], [[9]]], + [diag2, 'right', np.eye(2), diag2], + [diag2, 'left', np.eye(2), diag2], + [a13, 'right', a13/norm(a13[0]), a13.T.dot(a13)/norm(a13[0])], +] + +verify_cases = [ + [[1, 2], [3, 4]], + [[1, 2, 3]], + [[1], [2], [3]], + [[1, 2, 3], [3, 4, 0]], + [[1, 2], [3, 4], [5, 5]], + [[1, 2], [3, 4+5j]], + [[1, 2, 3j]], + [[1], [2], [3j]], + [[1, 2, 3+2j], [3, 4-1j, -4j]], + [[1, 2], [3-2j, 4+0.5j], [5, 5]], + [[10000, 10, 1], [-1, 2, 3j], [0, 1, 2]], + np.empty((0, 0)), + np.empty((0, 2)), + np.empty((2, 0)), +] + + +def check_precomputed_polar(a, side, expected_u, expected_p): + # Compare the result of the polar decomposition to a + # precomputed result. + u, p = polar(a, side=side) + assert_allclose(u, expected_u, atol=1e-15) + assert_allclose(p, expected_p, atol=1e-15) + + +def verify_polar(a): + # Compute the polar decomposition, and then verify that + # the result has all the expected properties. + product_atol = np.sqrt(np.finfo(float).eps) + + aa = np.asarray(a) + m, n = aa.shape + + u, p = polar(a, side='right') + assert_equal(u.shape, (m, n)) + assert_equal(p.shape, (n, n)) + # a = up + assert_allclose(u.dot(p), a, atol=product_atol) + if m >= n: + assert_allclose(u.conj().T.dot(u), np.eye(n), atol=1e-15) + else: + assert_allclose(u.dot(u.conj().T), np.eye(m), atol=1e-15) + # p is Hermitian positive semidefinite. + assert_allclose(p.conj().T, p) + evals = eigh(p, eigvals_only=True) + nonzero_evals = evals[abs(evals) > 1e-14] + assert_((nonzero_evals >= 0).all()) + + u, p = polar(a, side='left') + assert_equal(u.shape, (m, n)) + assert_equal(p.shape, (m, m)) + # a = pu + assert_allclose(p.dot(u), a, atol=product_atol) + if m >= n: + assert_allclose(u.conj().T.dot(u), np.eye(n), atol=1e-15) + else: + assert_allclose(u.dot(u.conj().T), np.eye(m), atol=1e-15) + # p is Hermitian positive semidefinite. + assert_allclose(p.conj().T, p) + evals = eigh(p, eigvals_only=True) + nonzero_evals = evals[abs(evals) > 1e-14] + assert_((nonzero_evals >= 0).all()) + + +def test_precomputed_cases(): + for a, side, expected_u, expected_p in precomputed_cases: + check_precomputed_polar(a, side, expected_u, expected_p) + + +def test_verify_cases(): + for a in verify_cases: + verify_polar(a) + +@pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) +@pytest.mark.parametrize('shape', [(0, 0), (0, 2), (2, 0)]) +@pytest.mark.parametrize('side', ['left', 'right']) +def test_empty(dt, shape, side): + a = np.empty(shape, dtype=dt) + m, n = shape + p_shape = (m, m) if side == 'left' else (n, n) + + u, p = polar(a, side=side) + u_n, p_n = polar(np.eye(5, dtype=dt)) + + assert_equal(u.dtype, u_n.dtype) + assert_equal(p.dtype, p_n.dtype) + assert u.shape == shape + assert p.shape == p_shape + assert np.all(p == 0) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_update.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_update.py new file mode 100644 index 0000000000000000000000000000000000000000..7553e21d61ceaa774d24c48d9d4bc2e3a8e3cc00 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_update.py @@ -0,0 +1,1701 @@ +import itertools + +import numpy as np +from numpy.testing import assert_, assert_allclose, assert_equal +from pytest import raises as assert_raises +from scipy import linalg +import scipy.linalg._decomp_update as _decomp_update +from scipy.linalg._decomp_update import qr_delete, qr_update, qr_insert + +def assert_unitary(a, rtol=None, atol=None, assert_sqr=True): + if rtol is None: + rtol = 10.0 ** -(np.finfo(a.dtype).precision-2) + if atol is None: + atol = 10*np.finfo(a.dtype).eps + + if assert_sqr: + assert_(a.shape[0] == a.shape[1], 'unitary matrices must be square') + aTa = np.dot(a.T.conj(), a) + assert_allclose(aTa, np.eye(a.shape[1]), rtol=rtol, atol=atol) + +def assert_upper_tri(a, rtol=None, atol=None): + if rtol is None: + rtol = 10.0 ** -(np.finfo(a.dtype).precision-2) + if atol is None: + atol = 2*np.finfo(a.dtype).eps + mask = np.tri(a.shape[0], a.shape[1], -1, np.bool_) + assert_allclose(a[mask], 0.0, rtol=rtol, atol=atol) + +def check_qr(q, r, a, rtol, atol, assert_sqr=True): + assert_unitary(q, rtol, atol, assert_sqr) + assert_upper_tri(r, rtol, atol) + assert_allclose(q.dot(r), a, rtol=rtol, atol=atol) + +def make_strided(arrs): + strides = [(3, 7), (2, 2), (3, 4), (4, 2), (5, 4), (2, 3), (2, 1), (4, 5)] + kmax = len(strides) + k = 0 + ret = [] + for a in arrs: + if a.ndim == 1: + s = strides[k % kmax] + k += 1 + base = np.zeros(s[0]*a.shape[0]+s[1], a.dtype) + view = base[s[1]::s[0]] + view[...] = a + elif a.ndim == 2: + s = strides[k % kmax] + t = strides[(k+1) % kmax] + k += 2 + base = np.zeros((s[0]*a.shape[0]+s[1], t[0]*a.shape[1]+t[1]), + a.dtype) + view = base[s[1]::s[0], t[1]::t[0]] + view[...] = a + else: + raise ValueError('make_strided only works for ndim = 1 or' + ' 2 arrays') + ret.append(view) + return ret + +def negate_strides(arrs): + ret = [] + for a in arrs: + b = np.zeros_like(a) + if b.ndim == 2: + b = b[::-1, ::-1] + elif b.ndim == 1: + b = b[::-1] + else: + raise ValueError('negate_strides only works for ndim = 1 or' + ' 2 arrays') + b[...] = a + ret.append(b) + return ret + +def nonitemsize_strides(arrs): + out = [] + for a in arrs: + a_dtype = a.dtype + b = np.zeros(a.shape, [('a', a_dtype), ('junk', 'S1')]) + c = b.getfield(a_dtype) + c[...] = a + out.append(c) + return out + + +def make_nonnative(arrs): + return [a.astype(a.dtype.newbyteorder()) for a in arrs] + + +class BaseQRdeltas: + def setup_method(self): + self.rtol = 10.0 ** -(np.finfo(self.dtype).precision-2) + self.atol = 10 * np.finfo(self.dtype).eps + + def generate(self, type, mode='full'): + np.random.seed(29382) + shape = {'sqr': (8, 8), 'tall': (12, 7), 'fat': (7, 12), + 'Mx1': (8, 1), '1xN': (1, 8), '1x1': (1, 1)}[type] + a = np.random.random(shape) + if np.iscomplexobj(self.dtype.type(1)): + b = np.random.random(shape) + a = a + 1j * b + a = a.astype(self.dtype) + q, r = linalg.qr(a, mode=mode) + return a, q, r + +class BaseQRdelete(BaseQRdeltas): + def test_sqr_1_row(self): + a, q, r = self.generate('sqr') + for row in range(r.shape[0]): + q1, r1 = qr_delete(q, r, row, overwrite_qr=False) + a1 = np.delete(a, row, 0) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_sqr_p_row(self): + a, q, r = self.generate('sqr') + for ndel in range(2, 6): + for row in range(a.shape[0]-ndel): + q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False) + a1 = np.delete(a, slice(row, row+ndel), 0) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_sqr_1_col(self): + a, q, r = self.generate('sqr') + for col in range(r.shape[1]): + q1, r1 = qr_delete(q, r, col, which='col', overwrite_qr=False) + a1 = np.delete(a, col, 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_sqr_p_col(self): + a, q, r = self.generate('sqr') + for ndel in range(2, 6): + for col in range(r.shape[1]-ndel): + q1, r1 = qr_delete(q, r, col, ndel, which='col', + overwrite_qr=False) + a1 = np.delete(a, slice(col, col+ndel), 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_tall_1_row(self): + a, q, r = self.generate('tall') + for row in range(r.shape[0]): + q1, r1 = qr_delete(q, r, row, overwrite_qr=False) + a1 = np.delete(a, row, 0) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_tall_p_row(self): + a, q, r = self.generate('tall') + for ndel in range(2, 6): + for row in range(a.shape[0]-ndel): + q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False) + a1 = np.delete(a, slice(row, row+ndel), 0) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_tall_1_col(self): + a, q, r = self.generate('tall') + for col in range(r.shape[1]): + q1, r1 = qr_delete(q, r, col, which='col', overwrite_qr=False) + a1 = np.delete(a, col, 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_tall_p_col(self): + a, q, r = self.generate('tall') + for ndel in range(2, 6): + for col in range(r.shape[1]-ndel): + q1, r1 = qr_delete(q, r, col, ndel, which='col', + overwrite_qr=False) + a1 = np.delete(a, slice(col, col+ndel), 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_fat_1_row(self): + a, q, r = self.generate('fat') + for row in range(r.shape[0]): + q1, r1 = qr_delete(q, r, row, overwrite_qr=False) + a1 = np.delete(a, row, 0) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_fat_p_row(self): + a, q, r = self.generate('fat') + for ndel in range(2, 6): + for row in range(a.shape[0]-ndel): + q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False) + a1 = np.delete(a, slice(row, row+ndel), 0) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_fat_1_col(self): + a, q, r = self.generate('fat') + for col in range(r.shape[1]): + q1, r1 = qr_delete(q, r, col, which='col', overwrite_qr=False) + a1 = np.delete(a, col, 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_fat_p_col(self): + a, q, r = self.generate('fat') + for ndel in range(2, 6): + for col in range(r.shape[1]-ndel): + q1, r1 = qr_delete(q, r, col, ndel, which='col', + overwrite_qr=False) + a1 = np.delete(a, slice(col, col+ndel), 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_economic_1_row(self): + # this test always starts and ends with an economic decomp. + a, q, r = self.generate('tall', 'economic') + for row in range(r.shape[0]): + q1, r1 = qr_delete(q, r, row, overwrite_qr=False) + a1 = np.delete(a, row, 0) + check_qr(q1, r1, a1, self.rtol, self.atol, False) + + # for economic row deletes + # eco - prow = eco + # eco - prow = sqr + # eco - prow = fat + def base_economic_p_row_xxx(self, ndel): + a, q, r = self.generate('tall', 'economic') + for row in range(a.shape[0]-ndel): + q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False) + a1 = np.delete(a, slice(row, row+ndel), 0) + check_qr(q1, r1, a1, self.rtol, self.atol, False) + + def test_economic_p_row_economic(self): + # (12, 7) - (3, 7) = (9,7) --> stays economic + self.base_economic_p_row_xxx(3) + + def test_economic_p_row_sqr(self): + # (12, 7) - (5, 7) = (7, 7) --> becomes square + self.base_economic_p_row_xxx(5) + + def test_economic_p_row_fat(self): + # (12, 7) - (7,7) = (5, 7) --> becomes fat + self.base_economic_p_row_xxx(7) + + def test_economic_1_col(self): + a, q, r = self.generate('tall', 'economic') + for col in range(r.shape[1]): + q1, r1 = qr_delete(q, r, col, which='col', overwrite_qr=False) + a1 = np.delete(a, col, 1) + check_qr(q1, r1, a1, self.rtol, self.atol, False) + + def test_economic_p_col(self): + a, q, r = self.generate('tall', 'economic') + for ndel in range(2, 6): + for col in range(r.shape[1]-ndel): + q1, r1 = qr_delete(q, r, col, ndel, which='col', + overwrite_qr=False) + a1 = np.delete(a, slice(col, col+ndel), 1) + check_qr(q1, r1, a1, self.rtol, self.atol, False) + + def test_Mx1_1_row(self): + a, q, r = self.generate('Mx1') + for row in range(r.shape[0]): + q1, r1 = qr_delete(q, r, row, overwrite_qr=False) + a1 = np.delete(a, row, 0) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_Mx1_p_row(self): + a, q, r = self.generate('Mx1') + for ndel in range(2, 6): + for row in range(a.shape[0]-ndel): + q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False) + a1 = np.delete(a, slice(row, row+ndel), 0) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_1xN_1_col(self): + a, q, r = self.generate('1xN') + for col in range(r.shape[1]): + q1, r1 = qr_delete(q, r, col, which='col', overwrite_qr=False) + a1 = np.delete(a, col, 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_1xN_p_col(self): + a, q, r = self.generate('1xN') + for ndel in range(2, 6): + for col in range(r.shape[1]-ndel): + q1, r1 = qr_delete(q, r, col, ndel, which='col', + overwrite_qr=False) + a1 = np.delete(a, slice(col, col+ndel), 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_Mx1_economic_1_row(self): + a, q, r = self.generate('Mx1', 'economic') + for row in range(r.shape[0]): + q1, r1 = qr_delete(q, r, row, overwrite_qr=False) + a1 = np.delete(a, row, 0) + check_qr(q1, r1, a1, self.rtol, self.atol, False) + + def test_Mx1_economic_p_row(self): + a, q, r = self.generate('Mx1', 'economic') + for ndel in range(2, 6): + for row in range(a.shape[0]-ndel): + q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False) + a1 = np.delete(a, slice(row, row+ndel), 0) + check_qr(q1, r1, a1, self.rtol, self.atol, False) + + def test_delete_last_1_row(self): + # full and eco are the same for 1xN + a, q, r = self.generate('1xN') + q1, r1 = qr_delete(q, r, 0, 1, 'row') + assert_equal(q1, np.ndarray(shape=(0, 0), dtype=q.dtype)) + assert_equal(r1, np.ndarray(shape=(0, r.shape[1]), dtype=r.dtype)) + + def test_delete_last_p_row(self): + a, q, r = self.generate('tall', 'full') + q1, r1 = qr_delete(q, r, 0, a.shape[0], 'row') + assert_equal(q1, np.ndarray(shape=(0, 0), dtype=q.dtype)) + assert_equal(r1, np.ndarray(shape=(0, r.shape[1]), dtype=r.dtype)) + + a, q, r = self.generate('tall', 'economic') + q1, r1 = qr_delete(q, r, 0, a.shape[0], 'row') + assert_equal(q1, np.ndarray(shape=(0, 0), dtype=q.dtype)) + assert_equal(r1, np.ndarray(shape=(0, r.shape[1]), dtype=r.dtype)) + + def test_delete_last_1_col(self): + a, q, r = self.generate('Mx1', 'economic') + q1, r1 = qr_delete(q, r, 0, 1, 'col') + assert_equal(q1, np.ndarray(shape=(q.shape[0], 0), dtype=q.dtype)) + assert_equal(r1, np.ndarray(shape=(0, 0), dtype=r.dtype)) + + a, q, r = self.generate('Mx1', 'full') + q1, r1 = qr_delete(q, r, 0, 1, 'col') + assert_unitary(q1) + assert_(q1.dtype == q.dtype) + assert_(q1.shape == q.shape) + assert_equal(r1, np.ndarray(shape=(r.shape[0], 0), dtype=r.dtype)) + + def test_delete_last_p_col(self): + a, q, r = self.generate('tall', 'full') + q1, r1 = qr_delete(q, r, 0, a.shape[1], 'col') + assert_unitary(q1) + assert_(q1.dtype == q.dtype) + assert_(q1.shape == q.shape) + assert_equal(r1, np.ndarray(shape=(r.shape[0], 0), dtype=r.dtype)) + + a, q, r = self.generate('tall', 'economic') + q1, r1 = qr_delete(q, r, 0, a.shape[1], 'col') + assert_equal(q1, np.ndarray(shape=(q.shape[0], 0), dtype=q.dtype)) + assert_equal(r1, np.ndarray(shape=(0, 0), dtype=r.dtype)) + + def test_delete_1x1_row_col(self): + a, q, r = self.generate('1x1') + q1, r1 = qr_delete(q, r, 0, 1, 'row') + assert_equal(q1, np.ndarray(shape=(0, 0), dtype=q.dtype)) + assert_equal(r1, np.ndarray(shape=(0, r.shape[1]), dtype=r.dtype)) + + a, q, r = self.generate('1x1') + q1, r1 = qr_delete(q, r, 0, 1, 'col') + assert_unitary(q1) + assert_(q1.dtype == q.dtype) + assert_(q1.shape == q.shape) + assert_equal(r1, np.ndarray(shape=(r.shape[0], 0), dtype=r.dtype)) + + # all full qr, row deletes and single column deletes should be able to + # handle any non negative strides. (only row and column vector + # operations are used.) p column delete require fortran ordered + # Q and R and will make a copy as necessary. Economic qr row deletes + # require a contiguous q. + + def base_non_simple_strides(self, adjust_strides, ks, p, which, + overwriteable): + if which == 'row': + qind = (slice(p,None), slice(p,None)) + rind = (slice(p,None), slice(None)) + else: + qind = (slice(None), slice(None)) + rind = (slice(None), slice(None,-p)) + + for type, k in itertools.product(['sqr', 'tall', 'fat'], ks): + a, q0, r0, = self.generate(type) + qs, rs = adjust_strides((q0, r0)) + if p == 1: + a1 = np.delete(a, k, 0 if which == 'row' else 1) + else: + s = slice(k,k+p) + if k < 0: + s = slice(k, k + p + + (a.shape[0] if which == 'row' else a.shape[1])) + a1 = np.delete(a, s, 0 if which == 'row' else 1) + + # for each variable, q, r we try with it strided and + # overwrite=False. Then we try with overwrite=True, and make + # sure that q and r are still overwritten. + + q = q0.copy('F') + r = r0.copy('F') + q1, r1 = qr_delete(qs, r, k, p, which, False) + check_qr(q1, r1, a1, self.rtol, self.atol) + q1o, r1o = qr_delete(qs, r, k, p, which, True) + check_qr(q1o, r1o, a1, self.rtol, self.atol) + if overwriteable: + assert_allclose(q1o, qs[qind], rtol=self.rtol, atol=self.atol) + assert_allclose(r1o, r[rind], rtol=self.rtol, atol=self.atol) + + q = q0.copy('F') + r = r0.copy('F') + q2, r2 = qr_delete(q, rs, k, p, which, False) + check_qr(q2, r2, a1, self.rtol, self.atol) + q2o, r2o = qr_delete(q, rs, k, p, which, True) + check_qr(q2o, r2o, a1, self.rtol, self.atol) + if overwriteable: + assert_allclose(q2o, q[qind], rtol=self.rtol, atol=self.atol) + assert_allclose(r2o, rs[rind], rtol=self.rtol, atol=self.atol) + + q = q0.copy('F') + r = r0.copy('F') + # since some of these were consumed above + qs, rs = adjust_strides((q, r)) + q3, r3 = qr_delete(qs, rs, k, p, which, False) + check_qr(q3, r3, a1, self.rtol, self.atol) + q3o, r3o = qr_delete(qs, rs, k, p, which, True) + check_qr(q3o, r3o, a1, self.rtol, self.atol) + if overwriteable: + assert_allclose(q2o, qs[qind], rtol=self.rtol, atol=self.atol) + assert_allclose(r3o, rs[rind], rtol=self.rtol, atol=self.atol) + + def test_non_unit_strides_1_row(self): + self.base_non_simple_strides(make_strided, [0], 1, 'row', True) + + def test_non_unit_strides_p_row(self): + self.base_non_simple_strides(make_strided, [0], 3, 'row', True) + + def test_non_unit_strides_1_col(self): + self.base_non_simple_strides(make_strided, [0], 1, 'col', True) + + def test_non_unit_strides_p_col(self): + self.base_non_simple_strides(make_strided, [0], 3, 'col', False) + + def test_neg_strides_1_row(self): + self.base_non_simple_strides(negate_strides, [0], 1, 'row', False) + + def test_neg_strides_p_row(self): + self.base_non_simple_strides(negate_strides, [0], 3, 'row', False) + + def test_neg_strides_1_col(self): + self.base_non_simple_strides(negate_strides, [0], 1, 'col', False) + + def test_neg_strides_p_col(self): + self.base_non_simple_strides(negate_strides, [0], 3, 'col', False) + + def test_non_itemize_strides_1_row(self): + self.base_non_simple_strides(nonitemsize_strides, [0], 1, 'row', False) + + def test_non_itemize_strides_p_row(self): + self.base_non_simple_strides(nonitemsize_strides, [0], 3, 'row', False) + + def test_non_itemize_strides_1_col(self): + self.base_non_simple_strides(nonitemsize_strides, [0], 1, 'col', False) + + def test_non_itemize_strides_p_col(self): + self.base_non_simple_strides(nonitemsize_strides, [0], 3, 'col', False) + + def test_non_native_byte_order_1_row(self): + self.base_non_simple_strides(make_nonnative, [0], 1, 'row', False) + + def test_non_native_byte_order_p_row(self): + self.base_non_simple_strides(make_nonnative, [0], 3, 'row', False) + + def test_non_native_byte_order_1_col(self): + self.base_non_simple_strides(make_nonnative, [0], 1, 'col', False) + + def test_non_native_byte_order_p_col(self): + self.base_non_simple_strides(make_nonnative, [0], 3, 'col', False) + + def test_neg_k(self): + a, q, r = self.generate('sqr') + for k, p, w in itertools.product([-3, -7], [1, 3], ['row', 'col']): + q1, r1 = qr_delete(q, r, k, p, w, overwrite_qr=False) + if w == 'row': + a1 = np.delete(a, slice(k+a.shape[0], k+p+a.shape[0]), 0) + else: + a1 = np.delete(a, slice(k+a.shape[0], k+p+a.shape[1]), 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def base_overwrite_qr(self, which, p, test_C, test_F, mode='full'): + assert_sqr = True if mode == 'full' else False + if which == 'row': + qind = (slice(p,None), slice(p,None)) + rind = (slice(p,None), slice(None)) + else: + qind = (slice(None), slice(None)) + rind = (slice(None), slice(None,-p)) + a, q0, r0 = self.generate('sqr', mode) + if p == 1: + a1 = np.delete(a, 3, 0 if which == 'row' else 1) + else: + a1 = np.delete(a, slice(3, 3+p), 0 if which == 'row' else 1) + + # don't overwrite + q = q0.copy('F') + r = r0.copy('F') + q1, r1 = qr_delete(q, r, 3, p, which, False) + check_qr(q1, r1, a1, self.rtol, self.atol, assert_sqr) + check_qr(q, r, a, self.rtol, self.atol, assert_sqr) + + if test_F: + q = q0.copy('F') + r = r0.copy('F') + q2, r2 = qr_delete(q, r, 3, p, which, True) + check_qr(q2, r2, a1, self.rtol, self.atol, assert_sqr) + # verify the overwriting + assert_allclose(q2, q[qind], rtol=self.rtol, atol=self.atol) + assert_allclose(r2, r[rind], rtol=self.rtol, atol=self.atol) + + if test_C: + q = q0.copy('C') + r = r0.copy('C') + q3, r3 = qr_delete(q, r, 3, p, which, True) + check_qr(q3, r3, a1, self.rtol, self.atol, assert_sqr) + assert_allclose(q3, q[qind], rtol=self.rtol, atol=self.atol) + assert_allclose(r3, r[rind], rtol=self.rtol, atol=self.atol) + + def test_overwrite_qr_1_row(self): + # any positively strided q and r. + self.base_overwrite_qr('row', 1, True, True) + + def test_overwrite_economic_qr_1_row(self): + # Any contiguous q and positively strided r. + self.base_overwrite_qr('row', 1, True, True, 'economic') + + def test_overwrite_qr_1_col(self): + # any positively strided q and r. + # full and eco share code paths + self.base_overwrite_qr('col', 1, True, True) + + def test_overwrite_qr_p_row(self): + # any positively strided q and r. + self.base_overwrite_qr('row', 3, True, True) + + def test_overwrite_economic_qr_p_row(self): + # any contiguous q and positively strided r + self.base_overwrite_qr('row', 3, True, True, 'economic') + + def test_overwrite_qr_p_col(self): + # only F ordered q and r can be overwritten for cols + # full and eco share code paths + self.base_overwrite_qr('col', 3, False, True) + + def test_bad_which(self): + a, q, r = self.generate('sqr') + assert_raises(ValueError, qr_delete, q, r, 0, which='foo') + + def test_bad_k(self): + a, q, r = self.generate('tall') + assert_raises(ValueError, qr_delete, q, r, q.shape[0], 1) + assert_raises(ValueError, qr_delete, q, r, -q.shape[0]-1, 1) + assert_raises(ValueError, qr_delete, q, r, r.shape[0], 1, 'col') + assert_raises(ValueError, qr_delete, q, r, -r.shape[0]-1, 1, 'col') + + def test_bad_p(self): + a, q, r = self.generate('tall') + # p must be positive + assert_raises(ValueError, qr_delete, q, r, 0, -1) + assert_raises(ValueError, qr_delete, q, r, 0, -1, 'col') + + # and nonzero + assert_raises(ValueError, qr_delete, q, r, 0, 0) + assert_raises(ValueError, qr_delete, q, r, 0, 0, 'col') + + # must have at least k+p rows or cols, depending. + assert_raises(ValueError, qr_delete, q, r, 3, q.shape[0]-2) + assert_raises(ValueError, qr_delete, q, r, 3, r.shape[1]-2, 'col') + + def test_empty_q(self): + a, q, r = self.generate('tall') + # same code path for 'row' and 'col' + assert_raises(ValueError, qr_delete, np.array([]), r, 0, 1) + + def test_empty_r(self): + a, q, r = self.generate('tall') + # same code path for 'row' and 'col' + assert_raises(ValueError, qr_delete, q, np.array([]), 0, 1) + + def test_mismatched_q_and_r(self): + a, q, r = self.generate('tall') + r = r[1:] + assert_raises(ValueError, qr_delete, q, r, 0, 1) + + def test_unsupported_dtypes(self): + dts = ['int8', 'int16', 'int32', 'int64', + 'uint8', 'uint16', 'uint32', 'uint64', + 'float16', 'longdouble', 'clongdouble', + 'bool'] + a, q0, r0 = self.generate('tall') + for dtype in dts: + q = q0.real.astype(dtype) + with np.errstate(invalid="ignore"): + r = r0.real.astype(dtype) + assert_raises(ValueError, qr_delete, q, r0, 0, 1, 'row') + assert_raises(ValueError, qr_delete, q, r0, 0, 2, 'row') + assert_raises(ValueError, qr_delete, q, r0, 0, 1, 'col') + assert_raises(ValueError, qr_delete, q, r0, 0, 2, 'col') + + assert_raises(ValueError, qr_delete, q0, r, 0, 1, 'row') + assert_raises(ValueError, qr_delete, q0, r, 0, 2, 'row') + assert_raises(ValueError, qr_delete, q0, r, 0, 1, 'col') + assert_raises(ValueError, qr_delete, q0, r, 0, 2, 'col') + + def test_check_finite(self): + a0, q0, r0 = self.generate('tall') + + q = q0.copy('F') + q[1,1] = np.nan + assert_raises(ValueError, qr_delete, q, r0, 0, 1, 'row') + assert_raises(ValueError, qr_delete, q, r0, 0, 3, 'row') + assert_raises(ValueError, qr_delete, q, r0, 0, 1, 'col') + assert_raises(ValueError, qr_delete, q, r0, 0, 3, 'col') + + r = r0.copy('F') + r[1,1] = np.nan + assert_raises(ValueError, qr_delete, q0, r, 0, 1, 'row') + assert_raises(ValueError, qr_delete, q0, r, 0, 3, 'row') + assert_raises(ValueError, qr_delete, q0, r, 0, 1, 'col') + assert_raises(ValueError, qr_delete, q0, r, 0, 3, 'col') + + def test_qr_scalar(self): + a, q, r = self.generate('1x1') + assert_raises(ValueError, qr_delete, q[0, 0], r, 0, 1, 'row') + assert_raises(ValueError, qr_delete, q, r[0, 0], 0, 1, 'row') + assert_raises(ValueError, qr_delete, q[0, 0], r, 0, 1, 'col') + assert_raises(ValueError, qr_delete, q, r[0, 0], 0, 1, 'col') + +class TestQRdelete_f(BaseQRdelete): + dtype = np.dtype('f') + +class TestQRdelete_F(BaseQRdelete): + dtype = np.dtype('F') + +class TestQRdelete_d(BaseQRdelete): + dtype = np.dtype('d') + +class TestQRdelete_D(BaseQRdelete): + dtype = np.dtype('D') + +class BaseQRinsert(BaseQRdeltas): + def generate(self, type, mode='full', which='row', p=1): + a, q, r = super().generate(type, mode) + + assert_(p > 0) + rng = np.random.RandomState(1234) + + # super call set the seed... + if which == 'row': + if p == 1: + u = rng.random(a.shape[1]) + else: + u = rng.random((p, a.shape[1])) + elif which == 'col': + if p == 1: + u = rng.random(a.shape[0]) + else: + u = rng.random((a.shape[0], p)) + else: + ValueError('which should be either "row" or "col"') + + if np.iscomplexobj(self.dtype.type(1)): + b = rng.random(u.shape) + u = u + 1j * b + + u = u.astype(self.dtype) + return a, q, r, u + + def test_sqr_1_row(self): + a, q, r, u = self.generate('sqr', which='row') + for row in range(r.shape[0] + 1): + q1, r1 = qr_insert(q, r, u, row) + a1 = np.insert(a, row, u, 0) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_sqr_p_row(self): + # sqr + rows --> fat always + a, q, r, u = self.generate('sqr', which='row', p=3) + for row in range(r.shape[0] + 1): + q1, r1 = qr_insert(q, r, u, row) + a1 = np.insert(a, np.full(3, row, np.intp), u, 0) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_sqr_1_col(self): + a, q, r, u = self.generate('sqr', which='col') + for col in range(r.shape[1] + 1): + q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) + a1 = np.insert(a, col, u, 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_sqr_p_col(self): + # sqr + cols --> fat always + a, q, r, u = self.generate('sqr', which='col', p=3) + for col in range(r.shape[1] + 1): + q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) + a1 = np.insert(a, np.full(3, col, np.intp), u, 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_tall_1_row(self): + a, q, r, u = self.generate('tall', which='row') + for row in range(r.shape[0] + 1): + q1, r1 = qr_insert(q, r, u, row) + a1 = np.insert(a, row, u, 0) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_tall_p_row(self): + # tall + rows --> tall always + a, q, r, u = self.generate('tall', which='row', p=3) + for row in range(r.shape[0] + 1): + q1, r1 = qr_insert(q, r, u, row) + a1 = np.insert(a, np.full(3, row, np.intp), u, 0) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_tall_1_col(self): + a, q, r, u = self.generate('tall', which='col') + for col in range(r.shape[1] + 1): + q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) + a1 = np.insert(a, col, u, 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + # for column adds to tall matrices there are three cases to test + # tall + pcol --> tall + # tall + pcol --> sqr + # tall + pcol --> fat + def base_tall_p_col_xxx(self, p): + a, q, r, u = self.generate('tall', which='col', p=p) + for col in range(r.shape[1] + 1): + q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) + a1 = np.insert(a, np.full(p, col, np.intp), u, 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_tall_p_col_tall(self): + # 12x7 + 12x3 = 12x10 --> stays tall + self.base_tall_p_col_xxx(3) + + def test_tall_p_col_sqr(self): + # 12x7 + 12x5 = 12x12 --> becomes sqr + self.base_tall_p_col_xxx(5) + + def test_tall_p_col_fat(self): + # 12x7 + 12x7 = 12x14 --> becomes fat + self.base_tall_p_col_xxx(7) + + def test_fat_1_row(self): + a, q, r, u = self.generate('fat', which='row') + for row in range(r.shape[0] + 1): + q1, r1 = qr_insert(q, r, u, row) + a1 = np.insert(a, row, u, 0) + check_qr(q1, r1, a1, self.rtol, self.atol) + + # for row adds to fat matrices there are three cases to test + # fat + prow --> fat + # fat + prow --> sqr + # fat + prow --> tall + def base_fat_p_row_xxx(self, p): + a, q, r, u = self.generate('fat', which='row', p=p) + for row in range(r.shape[0] + 1): + q1, r1 = qr_insert(q, r, u, row) + a1 = np.insert(a, np.full(p, row, np.intp), u, 0) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_fat_p_row_fat(self): + # 7x12 + 3x12 = 10x12 --> stays fat + self.base_fat_p_row_xxx(3) + + def test_fat_p_row_sqr(self): + # 7x12 + 5x12 = 12x12 --> becomes sqr + self.base_fat_p_row_xxx(5) + + def test_fat_p_row_tall(self): + # 7x12 + 7x12 = 14x12 --> becomes tall + self.base_fat_p_row_xxx(7) + + def test_fat_1_col(self): + a, q, r, u = self.generate('fat', which='col') + for col in range(r.shape[1] + 1): + q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) + a1 = np.insert(a, col, u, 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_fat_p_col(self): + # fat + cols --> fat always + a, q, r, u = self.generate('fat', which='col', p=3) + for col in range(r.shape[1] + 1): + q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) + a1 = np.insert(a, np.full(3, col, np.intp), u, 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_economic_1_row(self): + a, q, r, u = self.generate('tall', 'economic', 'row') + for row in range(r.shape[0] + 1): + q1, r1 = qr_insert(q, r, u, row, overwrite_qru=False) + a1 = np.insert(a, row, u, 0) + check_qr(q1, r1, a1, self.rtol, self.atol, False) + + def test_economic_p_row(self): + # tall + rows --> tall always + a, q, r, u = self.generate('tall', 'economic', 'row', 3) + for row in range(r.shape[0] + 1): + q1, r1 = qr_insert(q, r, u, row, overwrite_qru=False) + a1 = np.insert(a, np.full(3, row, np.intp), u, 0) + check_qr(q1, r1, a1, self.rtol, self.atol, False) + + def test_economic_1_col(self): + a, q, r, u = self.generate('tall', 'economic', which='col') + for col in range(r.shape[1] + 1): + q1, r1 = qr_insert(q, r, u.copy(), col, 'col', overwrite_qru=False) + a1 = np.insert(a, col, u, 1) + check_qr(q1, r1, a1, self.rtol, self.atol, False) + + def test_economic_1_col_bad_update(self): + # When the column to be added lies in the span of Q, the update is + # not meaningful. This is detected, and a LinAlgError is issued. + q = np.eye(5, 3, dtype=self.dtype) + r = np.eye(3, dtype=self.dtype) + u = np.array([1, 0, 0, 0, 0], self.dtype) + assert_raises(linalg.LinAlgError, qr_insert, q, r, u, 0, 'col') + + # for column adds to economic matrices there are three cases to test + # eco + pcol --> eco + # eco + pcol --> sqr + # eco + pcol --> fat + def base_economic_p_col_xxx(self, p): + a, q, r, u = self.generate('tall', 'economic', which='col', p=p) + for col in range(r.shape[1] + 1): + q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) + a1 = np.insert(a, np.full(p, col, np.intp), u, 1) + check_qr(q1, r1, a1, self.rtol, self.atol, False) + + def test_economic_p_col_eco(self): + # 12x7 + 12x3 = 12x10 --> stays eco + self.base_economic_p_col_xxx(3) + + def test_economic_p_col_sqr(self): + # 12x7 + 12x5 = 12x12 --> becomes sqr + self.base_economic_p_col_xxx(5) + + def test_economic_p_col_fat(self): + # 12x7 + 12x7 = 12x14 --> becomes fat + self.base_economic_p_col_xxx(7) + + def test_Mx1_1_row(self): + a, q, r, u = self.generate('Mx1', which='row') + for row in range(r.shape[0] + 1): + q1, r1 = qr_insert(q, r, u, row) + a1 = np.insert(a, row, u, 0) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_Mx1_p_row(self): + a, q, r, u = self.generate('Mx1', which='row', p=3) + for row in range(r.shape[0] + 1): + q1, r1 = qr_insert(q, r, u, row) + a1 = np.insert(a, np.full(3, row, np.intp), u, 0) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_Mx1_1_col(self): + a, q, r, u = self.generate('Mx1', which='col') + for col in range(r.shape[1] + 1): + q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) + a1 = np.insert(a, col, u, 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_Mx1_p_col(self): + a, q, r, u = self.generate('Mx1', which='col', p=3) + for col in range(r.shape[1] + 1): + q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) + a1 = np.insert(a, np.full(3, col, np.intp), u, 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_Mx1_economic_1_row(self): + a, q, r, u = self.generate('Mx1', 'economic', 'row') + for row in range(r.shape[0] + 1): + q1, r1 = qr_insert(q, r, u, row) + a1 = np.insert(a, row, u, 0) + check_qr(q1, r1, a1, self.rtol, self.atol, False) + + def test_Mx1_economic_p_row(self): + a, q, r, u = self.generate('Mx1', 'economic', 'row', 3) + for row in range(r.shape[0] + 1): + q1, r1 = qr_insert(q, r, u, row) + a1 = np.insert(a, np.full(3, row, np.intp), u, 0) + check_qr(q1, r1, a1, self.rtol, self.atol, False) + + def test_Mx1_economic_1_col(self): + a, q, r, u = self.generate('Mx1', 'economic', 'col') + for col in range(r.shape[1] + 1): + q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) + a1 = np.insert(a, col, u, 1) + check_qr(q1, r1, a1, self.rtol, self.atol, False) + + def test_Mx1_economic_p_col(self): + a, q, r, u = self.generate('Mx1', 'economic', 'col', 3) + for col in range(r.shape[1] + 1): + q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) + a1 = np.insert(a, np.full(3, col, np.intp), u, 1) + check_qr(q1, r1, a1, self.rtol, self.atol, False) + + def test_1xN_1_row(self): + a, q, r, u = self.generate('1xN', which='row') + for row in range(r.shape[0] + 1): + q1, r1 = qr_insert(q, r, u, row) + a1 = np.insert(a, row, u, 0) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_1xN_p_row(self): + a, q, r, u = self.generate('1xN', which='row', p=3) + for row in range(r.shape[0] + 1): + q1, r1 = qr_insert(q, r, u, row) + a1 = np.insert(a, np.full(3, row, np.intp), u, 0) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_1xN_1_col(self): + a, q, r, u = self.generate('1xN', which='col') + for col in range(r.shape[1] + 1): + q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) + a1 = np.insert(a, col, u, 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_1xN_p_col(self): + a, q, r, u = self.generate('1xN', which='col', p=3) + for col in range(r.shape[1] + 1): + q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) + a1 = np.insert(a, np.full(3, col, np.intp), u, 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_1x1_1_row(self): + a, q, r, u = self.generate('1x1', which='row') + for row in range(r.shape[0] + 1): + q1, r1 = qr_insert(q, r, u, row) + a1 = np.insert(a, row, u, 0) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_1x1_p_row(self): + a, q, r, u = self.generate('1x1', which='row', p=3) + for row in range(r.shape[0] + 1): + q1, r1 = qr_insert(q, r, u, row) + a1 = np.insert(a, np.full(3, row, np.intp), u, 0) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_1x1_1_col(self): + a, q, r, u = self.generate('1x1', which='col') + for col in range(r.shape[1] + 1): + q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) + a1 = np.insert(a, col, u, 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_1x1_p_col(self): + a, q, r, u = self.generate('1x1', which='col', p=3) + for col in range(r.shape[1] + 1): + q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False) + a1 = np.insert(a, np.full(3, col, np.intp), u, 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_1x1_1_scalar(self): + a, q, r, u = self.generate('1x1', which='row') + assert_raises(ValueError, qr_insert, q[0, 0], r, u, 0, 'row') + assert_raises(ValueError, qr_insert, q, r[0, 0], u, 0, 'row') + assert_raises(ValueError, qr_insert, q, r, u[0], 0, 'row') + + assert_raises(ValueError, qr_insert, q[0, 0], r, u, 0, 'col') + assert_raises(ValueError, qr_insert, q, r[0, 0], u, 0, 'col') + assert_raises(ValueError, qr_insert, q, r, u[0], 0, 'col') + + def base_non_simple_strides(self, adjust_strides, k, p, which): + for type in ['sqr', 'tall', 'fat']: + a, q0, r0, u0 = self.generate(type, which=which, p=p) + qs, rs, us = adjust_strides((q0, r0, u0)) + if p == 1: + ai = np.insert(a, k, u0, 0 if which == 'row' else 1) + else: + ai = np.insert(a, np.full(p, k, np.intp), + u0 if which == 'row' else u0, + 0 if which == 'row' else 1) + + # for each variable, q, r, u we try with it strided and + # overwrite=False. Then we try with overwrite=True. Nothing + # is checked to see if it can be overwritten, since only + # F ordered Q can be overwritten when adding columns. + + q = q0.copy('F') + r = r0.copy('F') + u = u0.copy('F') + q1, r1 = qr_insert(qs, r, u, k, which, overwrite_qru=False) + check_qr(q1, r1, ai, self.rtol, self.atol) + q1o, r1o = qr_insert(qs, r, u, k, which, overwrite_qru=True) + check_qr(q1o, r1o, ai, self.rtol, self.atol) + + q = q0.copy('F') + r = r0.copy('F') + u = u0.copy('F') + q2, r2 = qr_insert(q, rs, u, k, which, overwrite_qru=False) + check_qr(q2, r2, ai, self.rtol, self.atol) + q2o, r2o = qr_insert(q, rs, u, k, which, overwrite_qru=True) + check_qr(q2o, r2o, ai, self.rtol, self.atol) + + q = q0.copy('F') + r = r0.copy('F') + u = u0.copy('F') + q3, r3 = qr_insert(q, r, us, k, which, overwrite_qru=False) + check_qr(q3, r3, ai, self.rtol, self.atol) + q3o, r3o = qr_insert(q, r, us, k, which, overwrite_qru=True) + check_qr(q3o, r3o, ai, self.rtol, self.atol) + + q = q0.copy('F') + r = r0.copy('F') + u = u0.copy('F') + # since some of these were consumed above + qs, rs, us = adjust_strides((q, r, u)) + q5, r5 = qr_insert(qs, rs, us, k, which, overwrite_qru=False) + check_qr(q5, r5, ai, self.rtol, self.atol) + q5o, r5o = qr_insert(qs, rs, us, k, which, overwrite_qru=True) + check_qr(q5o, r5o, ai, self.rtol, self.atol) + + def test_non_unit_strides_1_row(self): + self.base_non_simple_strides(make_strided, 0, 1, 'row') + + def test_non_unit_strides_p_row(self): + self.base_non_simple_strides(make_strided, 0, 3, 'row') + + def test_non_unit_strides_1_col(self): + self.base_non_simple_strides(make_strided, 0, 1, 'col') + + def test_non_unit_strides_p_col(self): + self.base_non_simple_strides(make_strided, 0, 3, 'col') + + def test_neg_strides_1_row(self): + self.base_non_simple_strides(negate_strides, 0, 1, 'row') + + def test_neg_strides_p_row(self): + self.base_non_simple_strides(negate_strides, 0, 3, 'row') + + def test_neg_strides_1_col(self): + self.base_non_simple_strides(negate_strides, 0, 1, 'col') + + def test_neg_strides_p_col(self): + self.base_non_simple_strides(negate_strides, 0, 3, 'col') + + def test_non_itemsize_strides_1_row(self): + self.base_non_simple_strides(nonitemsize_strides, 0, 1, 'row') + + def test_non_itemsize_strides_p_row(self): + self.base_non_simple_strides(nonitemsize_strides, 0, 3, 'row') + + def test_non_itemsize_strides_1_col(self): + self.base_non_simple_strides(nonitemsize_strides, 0, 1, 'col') + + def test_non_itemsize_strides_p_col(self): + self.base_non_simple_strides(nonitemsize_strides, 0, 3, 'col') + + def test_non_native_byte_order_1_row(self): + self.base_non_simple_strides(make_nonnative, 0, 1, 'row') + + def test_non_native_byte_order_p_row(self): + self.base_non_simple_strides(make_nonnative, 0, 3, 'row') + + def test_non_native_byte_order_1_col(self): + self.base_non_simple_strides(make_nonnative, 0, 1, 'col') + + def test_non_native_byte_order_p_col(self): + self.base_non_simple_strides(make_nonnative, 0, 3, 'col') + + def test_overwrite_qu_rank_1(self): + # when inserting rows, the size of both Q and R change, so only + # column inserts can overwrite q. Only complex column inserts + # with C ordered Q overwrite u. Any contiguous Q is overwritten + # when inserting 1 column + a, q0, r, u, = self.generate('sqr', which='col', p=1) + q = q0.copy('C') + u0 = u.copy() + # don't overwrite + q1, r1 = qr_insert(q, r, u, 0, 'col', overwrite_qru=False) + a1 = np.insert(a, 0, u0, 1) + check_qr(q1, r1, a1, self.rtol, self.atol) + check_qr(q, r, a, self.rtol, self.atol) + + # try overwriting + q2, r2 = qr_insert(q, r, u, 0, 'col', overwrite_qru=True) + check_qr(q2, r2, a1, self.rtol, self.atol) + # verify the overwriting + assert_allclose(q2, q, rtol=self.rtol, atol=self.atol) + assert_allclose(u, u0.conj(), self.rtol, self.atol) + + # now try with a fortran ordered Q + qF = q0.copy('F') + u1 = u0.copy() + q3, r3 = qr_insert(qF, r, u1, 0, 'col', overwrite_qru=False) + check_qr(q3, r3, a1, self.rtol, self.atol) + check_qr(qF, r, a, self.rtol, self.atol) + + # try overwriting + q4, r4 = qr_insert(qF, r, u1, 0, 'col', overwrite_qru=True) + check_qr(q4, r4, a1, self.rtol, self.atol) + assert_allclose(q4, qF, rtol=self.rtol, atol=self.atol) + + def test_overwrite_qu_rank_p(self): + # when inserting rows, the size of both Q and R change, so only + # column inserts can potentially overwrite Q. In practice, only + # F ordered Q are overwritten with a rank p update. + a, q0, r, u, = self.generate('sqr', which='col', p=3) + q = q0.copy('F') + a1 = np.insert(a, np.zeros(3, np.intp), u, 1) + + # don't overwrite + q1, r1 = qr_insert(q, r, u, 0, 'col', overwrite_qru=False) + check_qr(q1, r1, a1, self.rtol, self.atol) + check_qr(q, r, a, self.rtol, self.atol) + + # try overwriting + q2, r2 = qr_insert(q, r, u, 0, 'col', overwrite_qru=True) + check_qr(q2, r2, a1, self.rtol, self.atol) + assert_allclose(q2, q, rtol=self.rtol, atol=self.atol) + + def test_empty_inputs(self): + a, q, r, u = self.generate('sqr', which='row') + assert_raises(ValueError, qr_insert, np.array([]), r, u, 0, 'row') + assert_raises(ValueError, qr_insert, q, np.array([]), u, 0, 'row') + assert_raises(ValueError, qr_insert, q, r, np.array([]), 0, 'row') + assert_raises(ValueError, qr_insert, np.array([]), r, u, 0, 'col') + assert_raises(ValueError, qr_insert, q, np.array([]), u, 0, 'col') + assert_raises(ValueError, qr_insert, q, r, np.array([]), 0, 'col') + + def test_mismatched_shapes(self): + a, q, r, u = self.generate('tall', which='row') + assert_raises(ValueError, qr_insert, q, r[1:], u, 0, 'row') + assert_raises(ValueError, qr_insert, q[:-2], r, u, 0, 'row') + assert_raises(ValueError, qr_insert, q, r, u[1:], 0, 'row') + assert_raises(ValueError, qr_insert, q, r[1:], u, 0, 'col') + assert_raises(ValueError, qr_insert, q[:-2], r, u, 0, 'col') + assert_raises(ValueError, qr_insert, q, r, u[1:], 0, 'col') + + def test_unsupported_dtypes(self): + dts = ['int8', 'int16', 'int32', 'int64', + 'uint8', 'uint16', 'uint32', 'uint64', + 'float16', 'longdouble', 'clongdouble', + 'bool'] + a, q0, r0, u0 = self.generate('sqr', which='row') + for dtype in dts: + q = q0.real.astype(dtype) + with np.errstate(invalid="ignore"): + r = r0.real.astype(dtype) + u = u0.real.astype(dtype) + assert_raises(ValueError, qr_insert, q, r0, u0, 0, 'row') + assert_raises(ValueError, qr_insert, q, r0, u0, 0, 'col') + assert_raises(ValueError, qr_insert, q0, r, u0, 0, 'row') + assert_raises(ValueError, qr_insert, q0, r, u0, 0, 'col') + assert_raises(ValueError, qr_insert, q0, r0, u, 0, 'row') + assert_raises(ValueError, qr_insert, q0, r0, u, 0, 'col') + + def test_check_finite(self): + a0, q0, r0, u0 = self.generate('sqr', which='row', p=3) + + q = q0.copy('F') + q[1,1] = np.nan + assert_raises(ValueError, qr_insert, q, r0, u0[:,0], 0, 'row') + assert_raises(ValueError, qr_insert, q, r0, u0, 0, 'row') + assert_raises(ValueError, qr_insert, q, r0, u0[:,0], 0, 'col') + assert_raises(ValueError, qr_insert, q, r0, u0, 0, 'col') + + r = r0.copy('F') + r[1,1] = np.nan + assert_raises(ValueError, qr_insert, q0, r, u0[:,0], 0, 'row') + assert_raises(ValueError, qr_insert, q0, r, u0, 0, 'row') + assert_raises(ValueError, qr_insert, q0, r, u0[:,0], 0, 'col') + assert_raises(ValueError, qr_insert, q0, r, u0, 0, 'col') + + u = u0.copy('F') + u[0,0] = np.nan + assert_raises(ValueError, qr_insert, q0, r0, u[:,0], 0, 'row') + assert_raises(ValueError, qr_insert, q0, r0, u, 0, 'row') + assert_raises(ValueError, qr_insert, q0, r0, u[:,0], 0, 'col') + assert_raises(ValueError, qr_insert, q0, r0, u, 0, 'col') + +class TestQRinsert_f(BaseQRinsert): + dtype = np.dtype('f') + +class TestQRinsert_F(BaseQRinsert): + dtype = np.dtype('F') + +class TestQRinsert_d(BaseQRinsert): + dtype = np.dtype('d') + +class TestQRinsert_D(BaseQRinsert): + dtype = np.dtype('D') + +class BaseQRupdate(BaseQRdeltas): + def generate(self, type, mode='full', p=1): + a, q, r = super().generate(type, mode) + + # super call set the seed... + if p == 1: + u = np.random.random(q.shape[0]) + v = np.random.random(r.shape[1]) + else: + u = np.random.random((q.shape[0], p)) + v = np.random.random((r.shape[1], p)) + + if np.iscomplexobj(self.dtype.type(1)): + b = np.random.random(u.shape) + u = u + 1j * b + + c = np.random.random(v.shape) + v = v + 1j * c + + u = u.astype(self.dtype) + v = v.astype(self.dtype) + return a, q, r, u, v + + def test_sqr_rank_1(self): + a, q, r, u, v = self.generate('sqr') + q1, r1 = qr_update(q, r, u, v, False) + a1 = a + np.outer(u, v.conj()) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_sqr_rank_p(self): + # test ndim = 2, rank 1 updates here too + for p in [1, 2, 3, 5]: + a, q, r, u, v = self.generate('sqr', p=p) + if p == 1: + u = u.reshape(u.size, 1) + v = v.reshape(v.size, 1) + q1, r1 = qr_update(q, r, u, v, False) + a1 = a + np.dot(u, v.T.conj()) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_tall_rank_1(self): + a, q, r, u, v = self.generate('tall') + q1, r1 = qr_update(q, r, u, v, False) + a1 = a + np.outer(u, v.conj()) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_tall_rank_p(self): + for p in [1, 2, 3, 5]: + a, q, r, u, v = self.generate('tall', p=p) + if p == 1: + u = u.reshape(u.size, 1) + v = v.reshape(v.size, 1) + q1, r1 = qr_update(q, r, u, v, False) + a1 = a + np.dot(u, v.T.conj()) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_fat_rank_1(self): + a, q, r, u, v = self.generate('fat') + q1, r1 = qr_update(q, r, u, v, False) + a1 = a + np.outer(u, v.conj()) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_fat_rank_p(self): + for p in [1, 2, 3, 5]: + a, q, r, u, v = self.generate('fat', p=p) + if p == 1: + u = u.reshape(u.size, 1) + v = v.reshape(v.size, 1) + q1, r1 = qr_update(q, r, u, v, False) + a1 = a + np.dot(u, v.T.conj()) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_economic_rank_1(self): + a, q, r, u, v = self.generate('tall', 'economic') + q1, r1 = qr_update(q, r, u, v, False) + a1 = a + np.outer(u, v.conj()) + check_qr(q1, r1, a1, self.rtol, self.atol, False) + + def test_economic_rank_p(self): + for p in [1, 2, 3, 5]: + a, q, r, u, v = self.generate('tall', 'economic', p) + if p == 1: + u = u.reshape(u.size, 1) + v = v.reshape(v.size, 1) + q1, r1 = qr_update(q, r, u, v, False) + a1 = a + np.dot(u, v.T.conj()) + check_qr(q1, r1, a1, self.rtol, self.atol, False) + + def test_Mx1_rank_1(self): + a, q, r, u, v = self.generate('Mx1') + q1, r1 = qr_update(q, r, u, v, False) + a1 = a + np.outer(u, v.conj()) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_Mx1_rank_p(self): + # when M or N == 1, only a rank 1 update is allowed. This isn't + # fundamental limitation, but the code does not support it. + a, q, r, u, v = self.generate('Mx1', p=1) + u = u.reshape(u.size, 1) + v = v.reshape(v.size, 1) + q1, r1 = qr_update(q, r, u, v, False) + a1 = a + np.dot(u, v.T.conj()) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_Mx1_economic_rank_1(self): + a, q, r, u, v = self.generate('Mx1', 'economic') + q1, r1 = qr_update(q, r, u, v, False) + a1 = a + np.outer(u, v.conj()) + check_qr(q1, r1, a1, self.rtol, self.atol, False) + + def test_Mx1_economic_rank_p(self): + # when M or N == 1, only a rank 1 update is allowed. This isn't + # fundamental limitation, but the code does not support it. + a, q, r, u, v = self.generate('Mx1', 'economic', p=1) + u = u.reshape(u.size, 1) + v = v.reshape(v.size, 1) + q1, r1 = qr_update(q, r, u, v, False) + a1 = a + np.dot(u, v.T.conj()) + check_qr(q1, r1, a1, self.rtol, self.atol, False) + + def test_1xN_rank_1(self): + a, q, r, u, v = self.generate('1xN') + q1, r1 = qr_update(q, r, u, v, False) + a1 = a + np.outer(u, v.conj()) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_1xN_rank_p(self): + # when M or N == 1, only a rank 1 update is allowed. This isn't + # fundamental limitation, but the code does not support it. + a, q, r, u, v = self.generate('1xN', p=1) + u = u.reshape(u.size, 1) + v = v.reshape(v.size, 1) + q1, r1 = qr_update(q, r, u, v, False) + a1 = a + np.dot(u, v.T.conj()) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_1x1_rank_1(self): + a, q, r, u, v = self.generate('1x1') + q1, r1 = qr_update(q, r, u, v, False) + a1 = a + np.outer(u, v.conj()) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_1x1_rank_p(self): + # when M or N == 1, only a rank 1 update is allowed. This isn't + # fundamental limitation, but the code does not support it. + a, q, r, u, v = self.generate('1x1', p=1) + u = u.reshape(u.size, 1) + v = v.reshape(v.size, 1) + q1, r1 = qr_update(q, r, u, v, False) + a1 = a + np.dot(u, v.T.conj()) + check_qr(q1, r1, a1, self.rtol, self.atol) + + def test_1x1_rank_1_scalar(self): + a, q, r, u, v = self.generate('1x1') + assert_raises(ValueError, qr_update, q[0, 0], r, u, v) + assert_raises(ValueError, qr_update, q, r[0, 0], u, v) + assert_raises(ValueError, qr_update, q, r, u[0], v) + assert_raises(ValueError, qr_update, q, r, u, v[0]) + + def base_non_simple_strides(self, adjust_strides, mode, p, overwriteable): + assert_sqr = False if mode == 'economic' else True + for type in ['sqr', 'tall', 'fat']: + a, q0, r0, u0, v0 = self.generate(type, mode, p) + qs, rs, us, vs = adjust_strides((q0, r0, u0, v0)) + if p == 1: + aup = a + np.outer(u0, v0.conj()) + else: + aup = a + np.dot(u0, v0.T.conj()) + + # for each variable, q, r, u, v we try with it strided and + # overwrite=False. Then we try with overwrite=True, and make + # sure that if p == 1, r and v are still overwritten. + # a strided q and u must always be copied. + + q = q0.copy('F') + r = r0.copy('F') + u = u0.copy('F') + v = v0.copy('C') + q1, r1 = qr_update(qs, r, u, v, False) + check_qr(q1, r1, aup, self.rtol, self.atol, assert_sqr) + q1o, r1o = qr_update(qs, r, u, v, True) + check_qr(q1o, r1o, aup, self.rtol, self.atol, assert_sqr) + if overwriteable: + assert_allclose(r1o, r, rtol=self.rtol, atol=self.atol) + assert_allclose(v, v0.conj(), rtol=self.rtol, atol=self.atol) + + q = q0.copy('F') + r = r0.copy('F') + u = u0.copy('F') + v = v0.copy('C') + q2, r2 = qr_update(q, rs, u, v, False) + check_qr(q2, r2, aup, self.rtol, self.atol, assert_sqr) + q2o, r2o = qr_update(q, rs, u, v, True) + check_qr(q2o, r2o, aup, self.rtol, self.atol, assert_sqr) + if overwriteable: + assert_allclose(r2o, rs, rtol=self.rtol, atol=self.atol) + assert_allclose(v, v0.conj(), rtol=self.rtol, atol=self.atol) + + q = q0.copy('F') + r = r0.copy('F') + u = u0.copy('F') + v = v0.copy('C') + q3, r3 = qr_update(q, r, us, v, False) + check_qr(q3, r3, aup, self.rtol, self.atol, assert_sqr) + q3o, r3o = qr_update(q, r, us, v, True) + check_qr(q3o, r3o, aup, self.rtol, self.atol, assert_sqr) + if overwriteable: + assert_allclose(r3o, r, rtol=self.rtol, atol=self.atol) + assert_allclose(v, v0.conj(), rtol=self.rtol, atol=self.atol) + + q = q0.copy('F') + r = r0.copy('F') + u = u0.copy('F') + v = v0.copy('C') + q4, r4 = qr_update(q, r, u, vs, False) + check_qr(q4, r4, aup, self.rtol, self.atol, assert_sqr) + q4o, r4o = qr_update(q, r, u, vs, True) + check_qr(q4o, r4o, aup, self.rtol, self.atol, assert_sqr) + if overwriteable: + assert_allclose(r4o, r, rtol=self.rtol, atol=self.atol) + assert_allclose(vs, v0.conj(), rtol=self.rtol, atol=self.atol) + + q = q0.copy('F') + r = r0.copy('F') + u = u0.copy('F') + v = v0.copy('C') + # since some of these were consumed above + qs, rs, us, vs = adjust_strides((q, r, u, v)) + q5, r5 = qr_update(qs, rs, us, vs, False) + check_qr(q5, r5, aup, self.rtol, self.atol, assert_sqr) + q5o, r5o = qr_update(qs, rs, us, vs, True) + check_qr(q5o, r5o, aup, self.rtol, self.atol, assert_sqr) + if overwriteable: + assert_allclose(r5o, rs, rtol=self.rtol, atol=self.atol) + assert_allclose(vs, v0.conj(), rtol=self.rtol, atol=self.atol) + + def test_non_unit_strides_rank_1(self): + self.base_non_simple_strides(make_strided, 'full', 1, True) + + def test_non_unit_strides_economic_rank_1(self): + self.base_non_simple_strides(make_strided, 'economic', 1, True) + + def test_non_unit_strides_rank_p(self): + self.base_non_simple_strides(make_strided, 'full', 3, False) + + def test_non_unit_strides_economic_rank_p(self): + self.base_non_simple_strides(make_strided, 'economic', 3, False) + + def test_neg_strides_rank_1(self): + self.base_non_simple_strides(negate_strides, 'full', 1, False) + + def test_neg_strides_economic_rank_1(self): + self.base_non_simple_strides(negate_strides, 'economic', 1, False) + + def test_neg_strides_rank_p(self): + self.base_non_simple_strides(negate_strides, 'full', 3, False) + + def test_neg_strides_economic_rank_p(self): + self.base_non_simple_strides(negate_strides, 'economic', 3, False) + + def test_non_itemsize_strides_rank_1(self): + self.base_non_simple_strides(nonitemsize_strides, 'full', 1, False) + + def test_non_itemsize_strides_economic_rank_1(self): + self.base_non_simple_strides(nonitemsize_strides, 'economic', 1, False) + + def test_non_itemsize_strides_rank_p(self): + self.base_non_simple_strides(nonitemsize_strides, 'full', 3, False) + + def test_non_itemsize_strides_economic_rank_p(self): + self.base_non_simple_strides(nonitemsize_strides, 'economic', 3, False) + + def test_non_native_byte_order_rank_1(self): + self.base_non_simple_strides(make_nonnative, 'full', 1, False) + + def test_non_native_byte_order_economic_rank_1(self): + self.base_non_simple_strides(make_nonnative, 'economic', 1, False) + + def test_non_native_byte_order_rank_p(self): + self.base_non_simple_strides(make_nonnative, 'full', 3, False) + + def test_non_native_byte_order_economic_rank_p(self): + self.base_non_simple_strides(make_nonnative, 'economic', 3, False) + + def test_overwrite_qruv_rank_1(self): + # Any positive strided q, r, u, and v can be overwritten for a rank 1 + # update, only checking C and F contiguous. + a, q0, r0, u0, v0 = self.generate('sqr') + a1 = a + np.outer(u0, v0.conj()) + q = q0.copy('F') + r = r0.copy('F') + u = u0.copy('F') + v = v0.copy('F') + + # don't overwrite + q1, r1 = qr_update(q, r, u, v, False) + check_qr(q1, r1, a1, self.rtol, self.atol) + check_qr(q, r, a, self.rtol, self.atol) + + q2, r2 = qr_update(q, r, u, v, True) + check_qr(q2, r2, a1, self.rtol, self.atol) + # verify the overwriting, no good way to check u and v. + assert_allclose(q2, q, rtol=self.rtol, atol=self.atol) + assert_allclose(r2, r, rtol=self.rtol, atol=self.atol) + + q = q0.copy('C') + r = r0.copy('C') + u = u0.copy('C') + v = v0.copy('C') + q3, r3 = qr_update(q, r, u, v, True) + check_qr(q3, r3, a1, self.rtol, self.atol) + assert_allclose(q3, q, rtol=self.rtol, atol=self.atol) + assert_allclose(r3, r, rtol=self.rtol, atol=self.atol) + + def test_overwrite_qruv_rank_1_economic(self): + # updating economic decompositions can overwrite any contiguous r, + # and positively strided r and u. V is only ever read. + # only checking C and F contiguous. + a, q0, r0, u0, v0 = self.generate('tall', 'economic') + a1 = a + np.outer(u0, v0.conj()) + q = q0.copy('F') + r = r0.copy('F') + u = u0.copy('F') + v = v0.copy('F') + + # don't overwrite + q1, r1 = qr_update(q, r, u, v, False) + check_qr(q1, r1, a1, self.rtol, self.atol, False) + check_qr(q, r, a, self.rtol, self.atol, False) + + q2, r2 = qr_update(q, r, u, v, True) + check_qr(q2, r2, a1, self.rtol, self.atol, False) + # verify the overwriting, no good way to check u and v. + assert_allclose(q2, q, rtol=self.rtol, atol=self.atol) + assert_allclose(r2, r, rtol=self.rtol, atol=self.atol) + + q = q0.copy('C') + r = r0.copy('C') + u = u0.copy('C') + v = v0.copy('C') + q3, r3 = qr_update(q, r, u, v, True) + check_qr(q3, r3, a1, self.rtol, self.atol, False) + assert_allclose(q3, q, rtol=self.rtol, atol=self.atol) + assert_allclose(r3, r, rtol=self.rtol, atol=self.atol) + + def test_overwrite_qruv_rank_p(self): + # for rank p updates, q r must be F contiguous, v must be C (v.T --> F) + # and u can be C or F, but is only overwritten if Q is C and complex + a, q0, r0, u0, v0 = self.generate('sqr', p=3) + a1 = a + np.dot(u0, v0.T.conj()) + q = q0.copy('F') + r = r0.copy('F') + u = u0.copy('F') + v = v0.copy('C') + + # don't overwrite + q1, r1 = qr_update(q, r, u, v, False) + check_qr(q1, r1, a1, self.rtol, self.atol) + check_qr(q, r, a, self.rtol, self.atol) + + q2, r2 = qr_update(q, r, u, v, True) + check_qr(q2, r2, a1, self.rtol, self.atol) + # verify the overwriting, no good way to check u and v. + assert_allclose(q2, q, rtol=self.rtol, atol=self.atol) + assert_allclose(r2, r, rtol=self.rtol, atol=self.atol) + + def test_empty_inputs(self): + a, q, r, u, v = self.generate('tall') + assert_raises(ValueError, qr_update, np.array([]), r, u, v) + assert_raises(ValueError, qr_update, q, np.array([]), u, v) + assert_raises(ValueError, qr_update, q, r, np.array([]), v) + assert_raises(ValueError, qr_update, q, r, u, np.array([])) + + def test_mismatched_shapes(self): + a, q, r, u, v = self.generate('tall') + assert_raises(ValueError, qr_update, q, r[1:], u, v) + assert_raises(ValueError, qr_update, q[:-2], r, u, v) + assert_raises(ValueError, qr_update, q, r, u[1:], v) + assert_raises(ValueError, qr_update, q, r, u, v[1:]) + + def test_unsupported_dtypes(self): + dts = ['int8', 'int16', 'int32', 'int64', + 'uint8', 'uint16', 'uint32', 'uint64', + 'float16', 'longdouble', 'clongdouble', + 'bool'] + a, q0, r0, u0, v0 = self.generate('tall') + for dtype in dts: + q = q0.real.astype(dtype) + with np.errstate(invalid="ignore"): + r = r0.real.astype(dtype) + u = u0.real.astype(dtype) + v = v0.real.astype(dtype) + assert_raises(ValueError, qr_update, q, r0, u0, v0) + assert_raises(ValueError, qr_update, q0, r, u0, v0) + assert_raises(ValueError, qr_update, q0, r0, u, v0) + assert_raises(ValueError, qr_update, q0, r0, u0, v) + + def test_integer_input(self): + q = np.arange(16).reshape(4, 4) + r = q.copy() # doesn't matter + u = q[:, 0].copy() + v = r[0, :].copy() + assert_raises(ValueError, qr_update, q, r, u, v) + + def test_check_finite(self): + a0, q0, r0, u0, v0 = self.generate('tall', p=3) + + q = q0.copy('F') + q[1,1] = np.nan + assert_raises(ValueError, qr_update, q, r0, u0[:,0], v0[:,0]) + assert_raises(ValueError, qr_update, q, r0, u0, v0) + + r = r0.copy('F') + r[1,1] = np.nan + assert_raises(ValueError, qr_update, q0, r, u0[:,0], v0[:,0]) + assert_raises(ValueError, qr_update, q0, r, u0, v0) + + u = u0.copy('F') + u[0,0] = np.nan + assert_raises(ValueError, qr_update, q0, r0, u[:,0], v0[:,0]) + assert_raises(ValueError, qr_update, q0, r0, u, v0) + + v = v0.copy('F') + v[0,0] = np.nan + assert_raises(ValueError, qr_update, q0, r0, u[:,0], v[:,0]) + assert_raises(ValueError, qr_update, q0, r0, u, v) + + def test_economic_check_finite(self): + a0, q0, r0, u0, v0 = self.generate('tall', mode='economic', p=3) + + q = q0.copy('F') + q[1,1] = np.nan + assert_raises(ValueError, qr_update, q, r0, u0[:,0], v0[:,0]) + assert_raises(ValueError, qr_update, q, r0, u0, v0) + + r = r0.copy('F') + r[1,1] = np.nan + assert_raises(ValueError, qr_update, q0, r, u0[:,0], v0[:,0]) + assert_raises(ValueError, qr_update, q0, r, u0, v0) + + u = u0.copy('F') + u[0,0] = np.nan + assert_raises(ValueError, qr_update, q0, r0, u[:,0], v0[:,0]) + assert_raises(ValueError, qr_update, q0, r0, u, v0) + + v = v0.copy('F') + v[0,0] = np.nan + assert_raises(ValueError, qr_update, q0, r0, u[:,0], v[:,0]) + assert_raises(ValueError, qr_update, q0, r0, u, v) + + def test_u_exactly_in_span_q(self): + q = np.array([[0, 0], [0, 0], [1, 0], [0, 1]], self.dtype) + r = np.array([[1, 0], [0, 1]], self.dtype) + u = np.array([0, 0, 0, -1], self.dtype) + v = np.array([1, 2], self.dtype) + q1, r1 = qr_update(q, r, u, v) + a1 = np.dot(q, r) + np.outer(u, v.conj()) + check_qr(q1, r1, a1, self.rtol, self.atol, False) + +class TestQRupdate_f(BaseQRupdate): + dtype = np.dtype('f') + +class TestQRupdate_F(BaseQRupdate): + dtype = np.dtype('F') + +class TestQRupdate_d(BaseQRupdate): + dtype = np.dtype('d') + +class TestQRupdate_D(BaseQRupdate): + dtype = np.dtype('D') + +def test_form_qTu(): + # We want to ensure that all of the code paths through this function are + # tested. Most of them should be hit with the rest of test suite, but + # explicit tests make clear precisely what is being tested. + # + # This function expects that Q is either C or F contiguous and square. + # Economic mode decompositions (Q is (M, N), M != N) do not go through this + # function. U may have any positive strides. + # + # Some of these test are duplicates, since contiguous 1d arrays are both C + # and F. + + q_order = ['F', 'C'] + q_shape = [(8, 8), ] + u_order = ['F', 'C', 'A'] # here A means is not F not C + u_shape = [1, 3] + dtype = ['f', 'd', 'F', 'D'] + + for qo, qs, uo, us, d in \ + itertools.product(q_order, q_shape, u_order, u_shape, dtype): + if us == 1: + check_form_qTu(qo, qs, uo, us, 1, d) + check_form_qTu(qo, qs, uo, us, 2, d) + else: + check_form_qTu(qo, qs, uo, us, 2, d) + +def check_form_qTu(q_order, q_shape, u_order, u_shape, u_ndim, dtype): + np.random.seed(47) + if u_shape == 1 and u_ndim == 1: + u_shape = (q_shape[0],) + else: + u_shape = (q_shape[0], u_shape) + dtype = np.dtype(dtype) + + if dtype.char in 'fd': + q = np.random.random(q_shape) + u = np.random.random(u_shape) + elif dtype.char in 'FD': + q = np.random.random(q_shape) + 1j*np.random.random(q_shape) + u = np.random.random(u_shape) + 1j*np.random.random(u_shape) + else: + ValueError("form_qTu doesn't support this dtype") + + q = np.require(q, dtype, q_order) + if u_order != 'A': + u = np.require(u, dtype, u_order) + else: + u, = make_strided((u.astype(dtype),)) + + rtol = 10.0 ** -(np.finfo(dtype).precision-2) + atol = 2*np.finfo(dtype).eps + + expected = np.dot(q.T.conj(), u) + res = _decomp_update._form_qTu(q, u) + assert_allclose(res, expected, rtol=rtol, atol=atol) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_extending.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_extending.py new file mode 100644 index 0000000000000000000000000000000000000000..36e4692cd9717a221cc683a663e8ee23a81aa5b6 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_extending.py @@ -0,0 +1,46 @@ +import os +import platform +import sysconfig + +import numpy as np +import pytest + +from scipy._lib._testutils import IS_EDITABLE, _test_cython_extension, cython +from scipy.linalg.blas import cdotu # type: ignore[attr-defined] +from scipy.linalg.lapack import dgtsv # type: ignore[attr-defined] + + +@pytest.mark.fail_slow(120) +# essential per https://github.com/scipy/scipy/pull/20487#discussion_r1567057247 +@pytest.mark.skipif(IS_EDITABLE, + reason='Editable install cannot find .pxd headers.') +@pytest.mark.skipif((platform.system() == 'Windows' and + sysconfig.get_config_var('Py_GIL_DISABLED')), + reason='gh-22039') +@pytest.mark.skipif(platform.machine() in ["wasm32", "wasm64"], + reason="Can't start subprocess") +@pytest.mark.skipif(cython is None, reason="requires cython") +def test_cython(tmp_path): + srcdir = os.path.dirname(os.path.dirname(__file__)) + extensions, extensions_cpp = _test_cython_extension(tmp_path, srcdir) + # actually test the cython c-extensions + a = np.ones(8) * 3 + b = np.ones(9) + c = np.ones(8) * 4 + x = np.ones(9) + _, _, _, x, _ = dgtsv(a, b, c, x) + a = np.ones(8) * 3 + b = np.ones(9) + c = np.ones(8) * 4 + x_c = np.ones(9) + extensions.tridiag(a, b, c, x_c) + a = np.ones(8) * 3 + b = np.ones(9) + c = np.ones(8) * 4 + x_cpp = np.ones(9) + extensions_cpp.tridiag(a, b, c, x_cpp) + np.testing.assert_array_equal(x, x_cpp) + cx = np.array([1-1j, 2+2j, 3-3j], dtype=np.complex64) + cy = np.array([4+4j, 5-5j, 6+6j], dtype=np.complex64) + np.testing.assert_array_equal(cdotu(cx, cy), extensions.complex_dot(cx, cy)) + np.testing.assert_array_equal(cdotu(cx, cy), extensions_cpp.complex_dot(cx, cy)) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_fblas.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_fblas.py new file mode 100644 index 0000000000000000000000000000000000000000..7c5ada830043af0eecb6d04bf39aef13d29d777c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_fblas.py @@ -0,0 +1,607 @@ +# Test interfaces to fortran blas. +# +# The tests are more of interface than they are of the underlying blas. +# Only very small matrices checked -- N=3 or so. +# +# !! Complex calculations really aren't checked that carefully. +# !! Only real valued complex numbers are used in tests. + +from numpy import float32, float64, complex64, complex128, arange, array, \ + zeros, shape, transpose, newaxis, common_type, conjugate + +from scipy.linalg import _fblas as fblas + +from numpy.testing import assert_array_equal, \ + assert_allclose, assert_array_almost_equal, assert_ + +import pytest + +# decimal accuracy to require between Python and LAPACK/BLAS calculations +accuracy = 5 + +# Since numpy.dot likely uses the same blas, use this routine +# to check. + + +def matrixmultiply(a, b): + if len(b.shape) == 1: + b_is_vector = True + b = b[:, newaxis] + else: + b_is_vector = False + assert_(a.shape[1] == b.shape[0]) + c = zeros((a.shape[0], b.shape[1]), common_type(a, b)) + for i in range(a.shape[0]): + for j in range(b.shape[1]): + s = 0 + for k in range(a.shape[1]): + s += a[i, k] * b[k, j] + c[i, j] = s + if b_is_vector: + c = c.reshape((a.shape[0],)) + return c + +################################################## +# Test blas ?axpy + + +class BaseAxpy: + ''' Mixin class for axpy tests ''' + + def test_default_a(self): + x = arange(3., dtype=self.dtype) + y = arange(3., dtype=x.dtype) + real_y = x*1.+y + y = self.blas_func(x, y) + assert_array_equal(real_y, y) + + def test_simple(self): + x = arange(3., dtype=self.dtype) + y = arange(3., dtype=x.dtype) + real_y = x*3.+y + y = self.blas_func(x, y, a=3.) + assert_array_equal(real_y, y) + + def test_x_stride(self): + x = arange(6., dtype=self.dtype) + y = zeros(3, x.dtype) + y = arange(3., dtype=x.dtype) + real_y = x[::2]*3.+y + y = self.blas_func(x, y, a=3., n=3, incx=2) + assert_array_equal(real_y, y) + + def test_y_stride(self): + x = arange(3., dtype=self.dtype) + y = zeros(6, x.dtype) + real_y = x*3.+y[::2] + y = self.blas_func(x, y, a=3., n=3, incy=2) + assert_array_equal(real_y, y[::2]) + + def test_x_and_y_stride(self): + x = arange(12., dtype=self.dtype) + y = zeros(6, x.dtype) + real_y = x[::4]*3.+y[::2] + y = self.blas_func(x, y, a=3., n=3, incx=4, incy=2) + assert_array_equal(real_y, y[::2]) + + def test_x_bad_size(self): + x = arange(12., dtype=self.dtype) + y = zeros(6, x.dtype) + with pytest.raises(Exception, match='failed for 1st keyword'): + self.blas_func(x, y, n=4, incx=5) + + def test_y_bad_size(self): + x = arange(12., dtype=self.dtype) + y = zeros(6, x.dtype) + with pytest.raises(Exception, match='failed for 1st keyword'): + self.blas_func(x, y, n=3, incy=5) + + +try: + class TestSaxpy(BaseAxpy): + blas_func = fblas.saxpy + dtype = float32 +except AttributeError: + class TestSaxpy: + pass + + +class TestDaxpy(BaseAxpy): + blas_func = fblas.daxpy + dtype = float64 + + +try: + class TestCaxpy(BaseAxpy): + blas_func = fblas.caxpy + dtype = complex64 +except AttributeError: + class TestCaxpy: + pass + + +class TestZaxpy(BaseAxpy): + blas_func = fblas.zaxpy + dtype = complex128 + + +################################################## +# Test blas ?scal + +class BaseScal: + ''' Mixin class for scal testing ''' + + def test_simple(self): + x = arange(3., dtype=self.dtype) + real_x = x*3. + x = self.blas_func(3., x) + assert_array_equal(real_x, x) + + def test_x_stride(self): + x = arange(6., dtype=self.dtype) + real_x = x.copy() + real_x[::2] = x[::2]*array(3., self.dtype) + x = self.blas_func(3., x, n=3, incx=2) + assert_array_equal(real_x, x) + + def test_x_bad_size(self): + x = arange(12., dtype=self.dtype) + with pytest.raises(Exception, match='failed for 1st keyword'): + self.blas_func(2., x, n=4, incx=5) + + +try: + class TestSscal(BaseScal): + blas_func = fblas.sscal + dtype = float32 +except AttributeError: + class TestSscal: + pass + + +class TestDscal(BaseScal): + blas_func = fblas.dscal + dtype = float64 + + +try: + class TestCscal(BaseScal): + blas_func = fblas.cscal + dtype = complex64 +except AttributeError: + class TestCscal: + pass + + +class TestZscal(BaseScal): + blas_func = fblas.zscal + dtype = complex128 + + +################################################## +# Test blas ?copy + +class BaseCopy: + ''' Mixin class for copy testing ''' + + def test_simple(self): + x = arange(3., dtype=self.dtype) + y = zeros(shape(x), x.dtype) + y = self.blas_func(x, y) + assert_array_equal(x, y) + + def test_x_stride(self): + x = arange(6., dtype=self.dtype) + y = zeros(3, x.dtype) + y = self.blas_func(x, y, n=3, incx=2) + assert_array_equal(x[::2], y) + + def test_y_stride(self): + x = arange(3., dtype=self.dtype) + y = zeros(6, x.dtype) + y = self.blas_func(x, y, n=3, incy=2) + assert_array_equal(x, y[::2]) + + def test_x_and_y_stride(self): + x = arange(12., dtype=self.dtype) + y = zeros(6, x.dtype) + y = self.blas_func(x, y, n=3, incx=4, incy=2) + assert_array_equal(x[::4], y[::2]) + + def test_x_bad_size(self): + x = arange(12., dtype=self.dtype) + y = zeros(6, x.dtype) + with pytest.raises(Exception, match='failed for 1st keyword'): + self.blas_func(x, y, n=4, incx=5) + + def test_y_bad_size(self): + x = arange(12., dtype=self.dtype) + y = zeros(6, x.dtype) + with pytest.raises(Exception, match='failed for 1st keyword'): + self.blas_func(x, y, n=3, incy=5) + + # def test_y_bad_type(self): + ## Hmmm. Should this work? What should be the output. + # x = arange(3.,dtype=self.dtype) + # y = zeros(shape(x)) + # self.blas_func(x,y) + # assert_array_equal(x,y) + + +try: + class TestScopy(BaseCopy): + blas_func = fblas.scopy + dtype = float32 +except AttributeError: + class TestScopy: + pass + + +class TestDcopy(BaseCopy): + blas_func = fblas.dcopy + dtype = float64 + + +try: + class TestCcopy(BaseCopy): + blas_func = fblas.ccopy + dtype = complex64 +except AttributeError: + class TestCcopy: + pass + + +class TestZcopy(BaseCopy): + blas_func = fblas.zcopy + dtype = complex128 + + +################################################## +# Test blas ?swap + +class BaseSwap: + ''' Mixin class for swap tests ''' + + def test_simple(self): + x = arange(3., dtype=self.dtype) + y = zeros(shape(x), x.dtype) + desired_x = y.copy() + desired_y = x.copy() + x, y = self.blas_func(x, y) + assert_array_equal(desired_x, x) + assert_array_equal(desired_y, y) + + def test_x_stride(self): + x = arange(6., dtype=self.dtype) + y = zeros(3, x.dtype) + desired_x = y.copy() + desired_y = x.copy()[::2] + x, y = self.blas_func(x, y, n=3, incx=2) + assert_array_equal(desired_x, x[::2]) + assert_array_equal(desired_y, y) + + def test_y_stride(self): + x = arange(3., dtype=self.dtype) + y = zeros(6, x.dtype) + desired_x = y.copy()[::2] + desired_y = x.copy() + x, y = self.blas_func(x, y, n=3, incy=2) + assert_array_equal(desired_x, x) + assert_array_equal(desired_y, y[::2]) + + def test_x_and_y_stride(self): + x = arange(12., dtype=self.dtype) + y = zeros(6, x.dtype) + desired_x = y.copy()[::2] + desired_y = x.copy()[::4] + x, y = self.blas_func(x, y, n=3, incx=4, incy=2) + assert_array_equal(desired_x, x[::4]) + assert_array_equal(desired_y, y[::2]) + + def test_x_bad_size(self): + x = arange(12., dtype=self.dtype) + y = zeros(6, x.dtype) + with pytest.raises(Exception, match='failed for 1st keyword'): + self.blas_func(x, y, n=4, incx=5) + + def test_y_bad_size(self): + x = arange(12., dtype=self.dtype) + y = zeros(6, x.dtype) + with pytest.raises(Exception, match='failed for 1st keyword'): + self.blas_func(x, y, n=3, incy=5) + + +try: + class TestSswap(BaseSwap): + blas_func = fblas.sswap + dtype = float32 +except AttributeError: + class TestSswap: + pass + + +class TestDswap(BaseSwap): + blas_func = fblas.dswap + dtype = float64 + + +try: + class TestCswap(BaseSwap): + blas_func = fblas.cswap + dtype = complex64 +except AttributeError: + class TestCswap: + pass + + +class TestZswap(BaseSwap): + blas_func = fblas.zswap + dtype = complex128 + +################################################## +# Test blas ?gemv +# This will be a mess to test all cases. + + +class BaseGemv: + ''' Mixin class for gemv tests ''' + + def get_data(self, x_stride=1, y_stride=1): + mult = array(1, dtype=self.dtype) + if self.dtype in [complex64, complex128]: + mult = array(1+1j, dtype=self.dtype) + from numpy.random import normal, seed + seed(1234) + alpha = array(1., dtype=self.dtype) * mult + beta = array(1., dtype=self.dtype) * mult + a = normal(0., 1., (3, 3)).astype(self.dtype) * mult + x = arange(shape(a)[0]*x_stride, dtype=self.dtype) * mult + y = arange(shape(a)[1]*y_stride, dtype=self.dtype) * mult + return alpha, beta, a, x, y + + def test_simple(self): + alpha, beta, a, x, y = self.get_data() + desired_y = alpha*matrixmultiply(a, x)+beta*y + y = self.blas_func(alpha, a, x, beta, y) + assert_array_almost_equal(desired_y, y) + + def test_default_beta_y(self): + alpha, beta, a, x, y = self.get_data() + desired_y = matrixmultiply(a, x) + y = self.blas_func(1, a, x) + assert_array_almost_equal(desired_y, y) + + def test_simple_transpose(self): + alpha, beta, a, x, y = self.get_data() + desired_y = alpha*matrixmultiply(transpose(a), x)+beta*y + y = self.blas_func(alpha, a, x, beta, y, trans=1) + assert_array_almost_equal(desired_y, y) + + def test_simple_transpose_conj(self): + alpha, beta, a, x, y = self.get_data() + desired_y = alpha*matrixmultiply(transpose(conjugate(a)), x)+beta*y + y = self.blas_func(alpha, a, x, beta, y, trans=2) + assert_array_almost_equal(desired_y, y) + + def test_x_stride(self): + alpha, beta, a, x, y = self.get_data(x_stride=2) + desired_y = alpha*matrixmultiply(a, x[::2])+beta*y + y = self.blas_func(alpha, a, x, beta, y, incx=2) + assert_array_almost_equal(desired_y, y) + + def test_x_stride_transpose(self): + alpha, beta, a, x, y = self.get_data(x_stride=2) + desired_y = alpha*matrixmultiply(transpose(a), x[::2])+beta*y + y = self.blas_func(alpha, a, x, beta, y, trans=1, incx=2) + assert_array_almost_equal(desired_y, y) + + def test_x_stride_assert(self): + # What is the use of this test? + alpha, beta, a, x, y = self.get_data(x_stride=2) + with pytest.raises(Exception, match='failed for 3rd argument'): + y = self.blas_func(1, a, x, 1, y, trans=0, incx=3) + with pytest.raises(Exception, match='failed for 3rd argument'): + y = self.blas_func(1, a, x, 1, y, trans=1, incx=3) + + def test_y_stride(self): + alpha, beta, a, x, y = self.get_data(y_stride=2) + desired_y = y.copy() + desired_y[::2] = alpha*matrixmultiply(a, x)+beta*y[::2] + y = self.blas_func(alpha, a, x, beta, y, incy=2) + assert_array_almost_equal(desired_y, y) + + def test_y_stride_transpose(self): + alpha, beta, a, x, y = self.get_data(y_stride=2) + desired_y = y.copy() + desired_y[::2] = alpha*matrixmultiply(transpose(a), x)+beta*y[::2] + y = self.blas_func(alpha, a, x, beta, y, trans=1, incy=2) + assert_array_almost_equal(desired_y, y) + + def test_y_stride_assert(self): + # What is the use of this test? + alpha, beta, a, x, y = self.get_data(y_stride=2) + with pytest.raises(Exception, match='failed for 2nd keyword'): + y = self.blas_func(1, a, x, 1, y, trans=0, incy=3) + with pytest.raises(Exception, match='failed for 2nd keyword'): + y = self.blas_func(1, a, x, 1, y, trans=1, incy=3) + + +try: + class TestSgemv(BaseGemv): + blas_func = fblas.sgemv + dtype = float32 + + def test_sgemv_on_osx(self): + from itertools import product + import sys + import numpy as np + + if sys.platform != 'darwin': + return + + def aligned_array(shape, align, dtype, order='C'): + # Make array shape `shape` with aligned at `align` bytes + d = dtype() + # Make array of correct size with `align` extra bytes + N = np.prod(shape) + tmp = np.zeros(N * d.nbytes + align, dtype=np.uint8) + address = tmp.__array_interface__["data"][0] + # Find offset into array giving desired alignment + for offset in range(align): + if (address + offset) % align == 0: + break + tmp = tmp[offset:offset+N*d.nbytes].view(dtype=dtype) + return tmp.reshape(shape, order=order) + + def as_aligned(arr, align, dtype, order='C'): + # Copy `arr` into an aligned array with same shape + aligned = aligned_array(arr.shape, align, dtype, order) + aligned[:] = arr[:] + return aligned + + def assert_dot_close(A, X, desired): + assert_allclose(self.blas_func(1.0, A, X), desired, + rtol=1e-5, atol=1e-7) + + testdata = product((15, 32), (10000,), (200, 89), ('C', 'F')) + for align, m, n, a_order in testdata: + A_d = np.random.rand(m, n) + X_d = np.random.rand(n) + desired = np.dot(A_d, X_d) + # Calculation with aligned single precision + A_f = as_aligned(A_d, align, np.float32, order=a_order) + X_f = as_aligned(X_d, align, np.float32, order=a_order) + assert_dot_close(A_f, X_f, desired) + +except AttributeError: + class TestSgemv: + pass + + +class TestDgemv(BaseGemv): + blas_func = fblas.dgemv + dtype = float64 + + +try: + class TestCgemv(BaseGemv): + blas_func = fblas.cgemv + dtype = complex64 +except AttributeError: + class TestCgemv: + pass + + +class TestZgemv(BaseGemv): + blas_func = fblas.zgemv + dtype = complex128 + + +""" +################################################## +### Test blas ?ger +### This will be a mess to test all cases. + +class BaseGer: + def get_data(self,x_stride=1,y_stride=1): + from numpy.random import normal, seed + seed(1234) + alpha = array(1., dtype = self.dtype) + a = normal(0.,1.,(3,3)).astype(self.dtype) + x = arange(shape(a)[0]*x_stride,dtype=self.dtype) + y = arange(shape(a)[1]*y_stride,dtype=self.dtype) + return alpha,a,x,y + def test_simple(self): + alpha,a,x,y = self.get_data() + # transpose takes care of Fortran vs. C(and Python) memory layout + desired_a = alpha*transpose(x[:,newaxis]*y) + a + self.blas_func(x,y,a) + assert_array_almost_equal(desired_a,a) + def test_x_stride(self): + alpha,a,x,y = self.get_data(x_stride=2) + desired_a = alpha*transpose(x[::2,newaxis]*y) + a + self.blas_func(x,y,a,incx=2) + assert_array_almost_equal(desired_a,a) + def test_x_stride_assert(self): + alpha,a,x,y = self.get_data(x_stride=2) + with pytest.raises(ValueError, match='foo'): + self.blas_func(x,y,a,incx=3) + def test_y_stride(self): + alpha,a,x,y = self.get_data(y_stride=2) + desired_a = alpha*transpose(x[:,newaxis]*y[::2]) + a + self.blas_func(x,y,a,incy=2) + assert_array_almost_equal(desired_a,a) + + def test_y_stride_assert(self): + alpha,a,x,y = self.get_data(y_stride=2) + with pytest.raises(ValueError, match='foo'): + self.blas_func(a,x,y,incy=3) + +class TestSger(BaseGer): + blas_func = fblas.sger + dtype = float32 +class TestDger(BaseGer): + blas_func = fblas.dger + dtype = float64 +""" +################################################## +# Test blas ?gerc +# This will be a mess to test all cases. + +""" +class BaseGerComplex(BaseGer): + def get_data(self,x_stride=1,y_stride=1): + from numpy.random import normal, seed + seed(1234) + alpha = array(1+1j, dtype = self.dtype) + a = normal(0.,1.,(3,3)).astype(self.dtype) + a = a + normal(0.,1.,(3,3)) * array(1j, dtype = self.dtype) + x = normal(0.,1.,shape(a)[0]*x_stride).astype(self.dtype) + x = x + x * array(1j, dtype = self.dtype) + y = normal(0.,1.,shape(a)[1]*y_stride).astype(self.dtype) + y = y + y * array(1j, dtype = self.dtype) + return alpha,a,x,y + def test_simple(self): + alpha,a,x,y = self.get_data() + # transpose takes care of Fortran vs. C(and Python) memory layout + a = a * array(0.,dtype = self.dtype) + #desired_a = alpha*transpose(x[:,newaxis]*self.transform(y)) + a + desired_a = alpha*transpose(x[:,newaxis]*y) + a + #self.blas_func(x,y,a,alpha = alpha) + fblas.cgeru(x,y,a,alpha = alpha) + assert_array_almost_equal(desired_a,a) + + #def test_x_stride(self): + # alpha,a,x,y = self.get_data(x_stride=2) + # desired_a = alpha*transpose(x[::2,newaxis]*self.transform(y)) + a + # self.blas_func(x,y,a,incx=2) + # assert_array_almost_equal(desired_a,a) + #def test_y_stride(self): + # alpha,a,x,y = self.get_data(y_stride=2) + # desired_a = alpha*transpose(x[:,newaxis]*self.transform(y[::2])) + a + # self.blas_func(x,y,a,incy=2) + # assert_array_almost_equal(desired_a,a) + +class TestCgeru(BaseGerComplex): + blas_func = fblas.cgeru + dtype = complex64 + def transform(self,x): + return x +class TestZgeru(BaseGerComplex): + blas_func = fblas.zgeru + dtype = complex128 + def transform(self,x): + return x + +class TestCgerc(BaseGerComplex): + blas_func = fblas.cgerc + dtype = complex64 + def transform(self,x): + return conjugate(x) + +class TestZgerc(BaseGerComplex): + blas_func = fblas.zgerc + dtype = complex128 + def transform(self,x): + return conjugate(x) +""" diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_interpolative.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_interpolative.py new file mode 100644 index 0000000000000000000000000000000000000000..6e1cc5496eafe19ced81ea546e3bad386148ae7b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_interpolative.py @@ -0,0 +1,232 @@ +# ****************************************************************************** +# Copyright (C) 2013 Kenneth L. Ho +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. Redistributions in binary +# form must reproduce the above copyright notice, this list of conditions and +# the following disclaimer in the documentation and/or other materials +# provided with the distribution. +# +# None of the names of the copyright holders may be used to endorse or +# promote products derived from this software without specific prior written +# permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. +# ****************************************************************************** + +import scipy.linalg.interpolative as pymatrixid +import numpy as np +from scipy.linalg import hilbert, svdvals, norm +from scipy.sparse.linalg import aslinearoperator +from scipy.linalg.interpolative import interp_decomp + +from numpy.testing import (assert_, assert_allclose, assert_equal, + assert_array_equal) +import pytest +from pytest import raises as assert_raises + + +@pytest.fixture() +def eps(): + yield 1e-12 + + +@pytest.fixture() +def rng(): + rng = np.random.default_rng(1718313768084012) + yield rng + + +@pytest.fixture(params=[np.float64, np.complex128]) +def A(request): + # construct Hilbert matrix + # set parameters + n = 300 + yield hilbert(n).astype(request.param) + + +@pytest.fixture() +def L(A): + yield aslinearoperator(A) + + +@pytest.fixture() +def rank(A, eps): + S = np.linalg.svd(A, compute_uv=False) + try: + rank = np.nonzero(S < eps)[0][0] + except IndexError: + rank = A.shape[0] + return rank + + +class TestInterpolativeDecomposition: + + @pytest.mark.parametrize( + "rand,lin_op", + [(False, False), (True, False), (True, True)]) + def test_real_id_fixed_precision(self, A, L, eps, rand, lin_op, rng): + # Test ID routines on a Hilbert matrix. + A_or_L = A if not lin_op else L + + k, idx, proj = pymatrixid.interp_decomp(A_or_L, eps, rand=rand, rng=rng) + B = pymatrixid.reconstruct_matrix_from_id(A[:, idx[:k]], idx, proj) + assert_allclose(A, B, rtol=eps, atol=1e-08) + + @pytest.mark.parametrize( + "rand,lin_op", + [(False, False), (True, False), (True, True)]) + def test_real_id_fixed_rank(self, A, L, eps, rank, rand, lin_op, rng): + k = rank + A_or_L = A if not lin_op else L + + idx, proj = pymatrixid.interp_decomp(A_or_L, k, rand=rand, rng=rng) + B = pymatrixid.reconstruct_matrix_from_id(A[:, idx[:k]], idx, proj) + assert_allclose(A, B, rtol=eps, atol=1e-08) + + @pytest.mark.parametrize("rand,lin_op", [(False, False)]) + def test_real_id_skel_and_interp_matrices( + self, A, L, eps, rank, rand, lin_op, rng): + k = rank + A_or_L = A if not lin_op else L + + idx, proj = pymatrixid.interp_decomp(A_or_L, k, rand=rand, rng=rng) + P = pymatrixid.reconstruct_interp_matrix(idx, proj) + B = pymatrixid.reconstruct_skel_matrix(A, k, idx) + assert_allclose(B, A[:, idx[:k]], rtol=eps, atol=1e-08) + assert_allclose(B @ P, A, rtol=eps, atol=1e-08) + + @pytest.mark.parametrize( + "rand,lin_op", + [(False, False), (True, False), (True, True)]) + def test_svd_fixed_precision(self, A, L, eps, rand, lin_op, rng): + A_or_L = A if not lin_op else L + + U, S, V = pymatrixid.svd(A_or_L, eps, rand=rand, rng=rng) + B = U * S @ V.T.conj() + assert_allclose(A, B, rtol=eps, atol=1e-08) + + @pytest.mark.parametrize( + "rand,lin_op", + [(False, False), (True, False), (True, True)]) + def test_svd_fixed_rank(self, A, L, eps, rank, rand, lin_op, rng): + k = rank + A_or_L = A if not lin_op else L + + U, S, V = pymatrixid.svd(A_or_L, k, rand=rand, rng=rng) + B = U * S @ V.T.conj() + assert_allclose(A, B, rtol=eps, atol=1e-08) + + def test_id_to_svd(self, A, eps, rank): + k = rank + + idx, proj = pymatrixid.interp_decomp(A, k, rand=False) + U, S, V = pymatrixid.id_to_svd(A[:, idx[:k]], idx, proj) + B = U * S @ V.T.conj() + assert_allclose(A, B, rtol=eps, atol=1e-08) + + def test_estimate_spectral_norm(self, A, rng): + s = svdvals(A) + norm_2_est = pymatrixid.estimate_spectral_norm(A, rng=rng) + assert_allclose(norm_2_est, s[0], rtol=1e-6, atol=1e-8) + + def test_estimate_spectral_norm_diff(self, A, rng): + B = A.copy() + B[:, 0] *= 1.2 + s = svdvals(A - B) + norm_2_est = pymatrixid.estimate_spectral_norm_diff(A, B, rng=rng) + assert_allclose(norm_2_est, s[0], rtol=1e-6, atol=1e-8) + + def test_rank_estimates_array(self, A, rng): + B = np.array([[1, 1, 0], [0, 0, 1], [0, 0, 1]], dtype=A.dtype) + + for M in [A, B]: + rank_tol = 1e-9 + rank_np = np.linalg.matrix_rank(M, norm(M, 2) * rank_tol) + rank_est = pymatrixid.estimate_rank(M, rank_tol, rng=rng) + assert_(rank_est >= rank_np) + assert_(rank_est <= rank_np + 10) + + def test_rank_estimates_lin_op(self, A, rng): + B = np.array([[1, 1, 0], [0, 0, 1], [0, 0, 1]], dtype=A.dtype) + + for M in [A, B]: + ML = aslinearoperator(M) + rank_tol = 1e-9 + rank_np = np.linalg.matrix_rank(M, norm(M, 2) * rank_tol) + rank_est = pymatrixid.estimate_rank(ML, rank_tol, rng=rng) + assert_(rank_est >= rank_np - 4) + assert_(rank_est <= rank_np + 4) + + def test_badcall(self): + A = hilbert(5).astype(np.float32) + with assert_raises(ValueError): + pymatrixid.interp_decomp(A, 1e-6, rand=False) + + def test_rank_too_large(self): + # svd(array, k) should not segfault + a = np.ones((4, 3)) + with assert_raises(ValueError): + pymatrixid.svd(a, 4) + + def test_full_rank(self): + eps = 1.0e-12 + + # fixed precision + A = np.random.rand(16, 8) + k, idx, proj = pymatrixid.interp_decomp(A, eps) + assert_equal(k, A.shape[1]) + + P = pymatrixid.reconstruct_interp_matrix(idx, proj) + B = pymatrixid.reconstruct_skel_matrix(A, k, idx) + assert_allclose(A, B @ P) + + # fixed rank + idx, proj = pymatrixid.interp_decomp(A, k) + + P = pymatrixid.reconstruct_interp_matrix(idx, proj) + B = pymatrixid.reconstruct_skel_matrix(A, k, idx) + assert_allclose(A, B @ P) + + @pytest.mark.parametrize("dtype", [np.float64, np.complex128]) + @pytest.mark.parametrize("rand", [True, False]) + @pytest.mark.parametrize("eps", [1, 0.1]) + def test_bug_9793(self, dtype, rand, eps): + A = np.array([[-1, -1, -1, 0, 0, 0], + [0, 0, 0, 1, 1, 1], + [1, 0, 0, 1, 0, 0], + [0, 1, 0, 0, 1, 0], + [0, 0, 1, 0, 0, 1]], + dtype=dtype, order="C") + B = A.copy() + interp_decomp(A.T, eps, rand=rand) + assert_array_equal(A, B) + + def test_svd_aslinearoperator_shape_check(self): + # See gh-issue #22451 + rng = np.random.default_rng(1744580941832515) + x = rng.uniform(size=[7, 5]) + xl = aslinearoperator(x) + u, s, v = pymatrixid.svd(xl, 3) + assert_equal(u.shape, (7, 3)) + assert_equal(s.shape, (3,)) + assert_equal(v.shape, (5, 3)) + + x = rng.uniform(size=[4, 9]) + xl = aslinearoperator(x) + u, s, v = pymatrixid.svd(xl, 2) + assert_equal(u.shape, (4, 2)) + assert_equal(s.shape, (2,)) + assert_equal(v.shape, (9, 2)) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_lapack.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_lapack.py new file mode 100644 index 0000000000000000000000000000000000000000..86555d6c19916c8ae1f6a796fb009a6b803b2159 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_lapack.py @@ -0,0 +1,3508 @@ +# +# Created by: Pearu Peterson, September 2002 +# + +from functools import reduce +import random + +from numpy.testing import (assert_equal, assert_array_almost_equal, assert_, + assert_allclose, assert_almost_equal, + assert_array_equal) +import pytest +from pytest import raises as assert_raises + +import numpy as np +from numpy import (eye, ones, zeros, zeros_like, triu, tril, tril_indices, + triu_indices) + +from numpy.random import rand, randint, seed + +from scipy.linalg import (_flapack as flapack, lapack, inv, svd, cholesky, + solve, ldl, norm, block_diag, qr, eigh, qz) + +from scipy.linalg.lapack import _compute_lwork +from scipy.stats import ortho_group, unitary_group + +import scipy.sparse as sps +try: + from scipy.__config__ import CONFIG +except ImportError: + CONFIG = None + +try: + from scipy.linalg import _clapack as clapack +except ImportError: + clapack = None +from scipy.linalg.lapack import get_lapack_funcs +from scipy.linalg.blas import get_blas_funcs + +REAL_DTYPES = [np.float32, np.float64] +COMPLEX_DTYPES = [np.complex64, np.complex128] +DTYPES = REAL_DTYPES + COMPLEX_DTYPES + +blas_provider = blas_version = None +if CONFIG is not None: + blas_provider = CONFIG['Build Dependencies']['blas']['name'] + blas_version = CONFIG['Build Dependencies']['blas']['version'] + + +def generate_random_dtype_array(shape, dtype, rng): + # generates a random matrix of desired data type of shape + if dtype in COMPLEX_DTYPES: + return (rng.rand(*shape) + + rng.rand(*shape)*1.0j).astype(dtype) + return rng.rand(*shape).astype(dtype) + + +def test_lapack_documented(): + """Test that all entries are in the doc.""" + if lapack.__doc__ is None: # just in case there is a python -OO + pytest.skip('lapack.__doc__ is None') + names = set(lapack.__doc__.split()) + ignore_list = { + "absolute_import", + "clapack", + "division", + "find_best_lapack_type", + "flapack", + "print_function", + "HAS_ILP64", + "np", + } + missing = list() + for name in dir(lapack): + if (not name.startswith('_') and name not in ignore_list and + name not in names): + missing.append(name) + assert missing == [], 'Name(s) missing from lapack.__doc__ or ignore_list' + + +class TestFlapackSimple: + + def test_gebal(self): + a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + a1 = [[1, 0, 0, 3e-4], + [4, 0, 0, 2e-3], + [7, 1, 0, 0], + [0, 1, 0, 0]] + for p in 'sdzc': + f = getattr(flapack, p+'gebal', None) + if f is None: + continue + ba, lo, hi, pivscale, info = f(a) + assert_(not info, repr(info)) + assert_array_almost_equal(ba, a) + assert_equal((lo, hi), (0, len(a[0])-1)) + assert_array_almost_equal(pivscale, np.ones(len(a))) + + ba, lo, hi, pivscale, info = f(a1, permute=1, scale=1) + assert_(not info, repr(info)) + # print(a1) + # print(ba, lo, hi, pivscale) + + def test_gehrd(self): + a = [[-149, -50, -154], + [537, 180, 546], + [-27, -9, -25]] + for p in 'd': + f = getattr(flapack, p+'gehrd', None) + if f is None: + continue + ht, tau, info = f(a) + assert_(not info, repr(info)) + + def test_trsyl(self): + a = np.array([[1, 2], [0, 4]]) + b = np.array([[5, 6], [0, 8]]) + c = np.array([[9, 10], [11, 12]]) + trans = 'T' + + # Test single and double implementations, including most + # of the options + for dtype in 'fdFD': + a1, b1, c1 = a.astype(dtype), b.astype(dtype), c.astype(dtype) + trsyl, = get_lapack_funcs(('trsyl',), (a1,)) + if dtype.isupper(): # is complex dtype + a1[0] += 1j + trans = 'C' + + x, scale, info = trsyl(a1, b1, c1) + assert_array_almost_equal(np.dot(a1, x) + np.dot(x, b1), + scale * c1) + + x, scale, info = trsyl(a1, b1, c1, trana=trans, tranb=trans) + assert_array_almost_equal( + np.dot(a1.conjugate().T, x) + np.dot(x, b1.conjugate().T), + scale * c1, decimal=4) + + x, scale, info = trsyl(a1, b1, c1, isgn=-1) + assert_array_almost_equal(np.dot(a1, x) - np.dot(x, b1), + scale * c1, decimal=4) + + def test_lange(self): + a = np.array([ + [-149, -50, -154], + [537, 180, 546], + [-27, -9, -25]]) + + for dtype in 'fdFD': + for norm_str in 'Mm1OoIiFfEe': + a1 = a.astype(dtype) + if dtype.isupper(): + # is complex dtype + a1[0, 0] += 1j + + lange, = get_lapack_funcs(('lange',), (a1,)) + value = lange(norm_str, a1) + + if norm_str in 'FfEe': + if dtype in 'Ff': + decimal = 3 + else: + decimal = 7 + ref = np.sqrt(np.sum(np.square(np.abs(a1)))) + assert_almost_equal(value, ref, decimal) + else: + if norm_str in 'Mm': + ref = np.max(np.abs(a1)) + elif norm_str in '1Oo': + ref = np.max(np.sum(np.abs(a1), axis=0)) + elif norm_str in 'Ii': + ref = np.max(np.sum(np.abs(a1), axis=1)) + + assert_equal(value, ref) + + +class TestLapack: + + def test_flapack(self): + if hasattr(flapack, 'empty_module'): + # flapack module is empty + pass + + def test_clapack(self): + if hasattr(clapack, 'empty_module'): + # clapack module is empty + pass + + +class TestLeastSquaresSolvers: + + def test_gels(self): + seed(1234) + # Test fat/tall matrix argument handling - gh-issue #8329 + for ind, dtype in enumerate(DTYPES): + m = 10 + n = 20 + nrhs = 1 + a1 = rand(m, n).astype(dtype) + b1 = rand(n).astype(dtype) + gls, glslw = get_lapack_funcs(('gels', 'gels_lwork'), dtype=dtype) + + # Request of sizes + lwork = _compute_lwork(glslw, m, n, nrhs) + _, _, info = gls(a1, b1, lwork=lwork) + assert_(info >= 0) + _, _, info = gls(a1, b1, trans='TTCC'[ind], lwork=lwork) + assert_(info >= 0) + + for dtype in REAL_DTYPES: + a1 = np.array([[1.0, 2.0], + [4.0, 5.0], + [7.0, 8.0]], dtype=dtype) + b1 = np.array([16.0, 17.0, 20.0], dtype=dtype) + gels, gels_lwork, geqrf = get_lapack_funcs( + ('gels', 'gels_lwork', 'geqrf'), (a1, b1)) + + m, n = a1.shape + if len(b1.shape) == 2: + nrhs = b1.shape[1] + else: + nrhs = 1 + + # Request of sizes + lwork = _compute_lwork(gels_lwork, m, n, nrhs) + + lqr, x, info = gels(a1, b1, lwork=lwork) + assert_allclose(x[:-1], np.array([-14.333333333333323, + 14.999999999999991], + dtype=dtype), + rtol=25*np.finfo(dtype).eps) + lqr_truth, _, _, _ = geqrf(a1) + assert_array_equal(lqr, lqr_truth) + + for dtype in COMPLEX_DTYPES: + a1 = np.array([[1.0+4.0j, 2.0], + [4.0+0.5j, 5.0-3.0j], + [7.0-2.0j, 8.0+0.7j]], dtype=dtype) + b1 = np.array([16.0, 17.0+2.0j, 20.0-4.0j], dtype=dtype) + gels, gels_lwork, geqrf = get_lapack_funcs( + ('gels', 'gels_lwork', 'geqrf'), (a1, b1)) + + m, n = a1.shape + if len(b1.shape) == 2: + nrhs = b1.shape[1] + else: + nrhs = 1 + + # Request of sizes + lwork = _compute_lwork(gels_lwork, m, n, nrhs) + + lqr, x, info = gels(a1, b1, lwork=lwork) + assert_allclose(x[:-1], + np.array([1.161753632288328-1.901075709391912j, + 1.735882340522193+1.521240901196909j], + dtype=dtype), rtol=25*np.finfo(dtype).eps) + lqr_truth, _, _, _ = geqrf(a1) + assert_array_equal(lqr, lqr_truth) + + def test_gelsd(self): + for dtype in REAL_DTYPES: + a1 = np.array([[1.0, 2.0], + [4.0, 5.0], + [7.0, 8.0]], dtype=dtype) + b1 = np.array([16.0, 17.0, 20.0], dtype=dtype) + gelsd, gelsd_lwork = get_lapack_funcs(('gelsd', 'gelsd_lwork'), + (a1, b1)) + + m, n = a1.shape + if len(b1.shape) == 2: + nrhs = b1.shape[1] + else: + nrhs = 1 + + # Request of sizes + work, iwork, info = gelsd_lwork(m, n, nrhs, -1) + lwork = int(np.real(work)) + iwork_size = iwork + + x, s, rank, info = gelsd(a1, b1, lwork, iwork_size, + -1, False, False) + assert_allclose(x[:-1], np.array([-14.333333333333323, + 14.999999999999991], + dtype=dtype), + rtol=25*np.finfo(dtype).eps) + assert_allclose(s, np.array([12.596017180511966, + 0.583396253199685], dtype=dtype), + rtol=25*np.finfo(dtype).eps) + + for dtype in COMPLEX_DTYPES: + a1 = np.array([[1.0+4.0j, 2.0], + [4.0+0.5j, 5.0-3.0j], + [7.0-2.0j, 8.0+0.7j]], dtype=dtype) + b1 = np.array([16.0, 17.0+2.0j, 20.0-4.0j], dtype=dtype) + gelsd, gelsd_lwork = get_lapack_funcs(('gelsd', 'gelsd_lwork'), + (a1, b1)) + + m, n = a1.shape + if len(b1.shape) == 2: + nrhs = b1.shape[1] + else: + nrhs = 1 + + # Request of sizes + work, rwork, iwork, info = gelsd_lwork(m, n, nrhs, -1) + lwork = int(np.real(work)) + rwork_size = int(rwork) + iwork_size = iwork + + x, s, rank, info = gelsd(a1, b1, lwork, rwork_size, iwork_size, + -1, False, False) + assert_allclose(x[:-1], + np.array([1.161753632288328-1.901075709391912j, + 1.735882340522193+1.521240901196909j], + dtype=dtype), rtol=25*np.finfo(dtype).eps) + assert_allclose(s, + np.array([13.035514762572043, 4.337666985231382], + dtype=dtype), rtol=25*np.finfo(dtype).eps) + + def test_gelss(self): + + for dtype in REAL_DTYPES: + a1 = np.array([[1.0, 2.0], + [4.0, 5.0], + [7.0, 8.0]], dtype=dtype) + b1 = np.array([16.0, 17.0, 20.0], dtype=dtype) + gelss, gelss_lwork = get_lapack_funcs(('gelss', 'gelss_lwork'), + (a1, b1)) + + m, n = a1.shape + if len(b1.shape) == 2: + nrhs = b1.shape[1] + else: + nrhs = 1 + + # Request of sizes + work, info = gelss_lwork(m, n, nrhs, -1) + lwork = int(np.real(work)) + + v, x, s, rank, work, info = gelss(a1, b1, -1, lwork, False, False) + assert_allclose(x[:-1], np.array([-14.333333333333323, + 14.999999999999991], + dtype=dtype), + rtol=25*np.finfo(dtype).eps) + assert_allclose(s, np.array([12.596017180511966, + 0.583396253199685], dtype=dtype), + rtol=25*np.finfo(dtype).eps) + + for dtype in COMPLEX_DTYPES: + a1 = np.array([[1.0+4.0j, 2.0], + [4.0+0.5j, 5.0-3.0j], + [7.0-2.0j, 8.0+0.7j]], dtype=dtype) + b1 = np.array([16.0, 17.0+2.0j, 20.0-4.0j], dtype=dtype) + gelss, gelss_lwork = get_lapack_funcs(('gelss', 'gelss_lwork'), + (a1, b1)) + + m, n = a1.shape + if len(b1.shape) == 2: + nrhs = b1.shape[1] + else: + nrhs = 1 + + # Request of sizes + work, info = gelss_lwork(m, n, nrhs, -1) + lwork = int(np.real(work)) + + v, x, s, rank, work, info = gelss(a1, b1, -1, lwork, False, False) + assert_allclose(x[:-1], + np.array([1.161753632288328-1.901075709391912j, + 1.735882340522193+1.521240901196909j], + dtype=dtype), + rtol=25*np.finfo(dtype).eps) + assert_allclose(s, np.array([13.035514762572043, + 4.337666985231382], dtype=dtype), + rtol=25*np.finfo(dtype).eps) + + def test_gelsy(self): + + for dtype in REAL_DTYPES: + a1 = np.array([[1.0, 2.0], + [4.0, 5.0], + [7.0, 8.0]], dtype=dtype) + b1 = np.array([16.0, 17.0, 20.0], dtype=dtype) + gelsy, gelsy_lwork = get_lapack_funcs(('gelsy', 'gelss_lwork'), + (a1, b1)) + + m, n = a1.shape + if len(b1.shape) == 2: + nrhs = b1.shape[1] + else: + nrhs = 1 + + # Request of sizes + work, info = gelsy_lwork(m, n, nrhs, 10*np.finfo(dtype).eps) + lwork = int(np.real(work)) + + jptv = np.zeros((a1.shape[1], 1), dtype=np.int32) + v, x, j, rank, info = gelsy(a1, b1, jptv, np.finfo(dtype).eps, + lwork, False, False) + assert_allclose(x[:-1], np.array([-14.333333333333323, + 14.999999999999991], + dtype=dtype), + rtol=25*np.finfo(dtype).eps) + + for dtype in COMPLEX_DTYPES: + a1 = np.array([[1.0+4.0j, 2.0], + [4.0+0.5j, 5.0-3.0j], + [7.0-2.0j, 8.0+0.7j]], dtype=dtype) + b1 = np.array([16.0, 17.0+2.0j, 20.0-4.0j], dtype=dtype) + gelsy, gelsy_lwork = get_lapack_funcs(('gelsy', 'gelss_lwork'), + (a1, b1)) + + m, n = a1.shape + if len(b1.shape) == 2: + nrhs = b1.shape[1] + else: + nrhs = 1 + + # Request of sizes + work, info = gelsy_lwork(m, n, nrhs, 10*np.finfo(dtype).eps) + lwork = int(np.real(work)) + + jptv = np.zeros((a1.shape[1], 1), dtype=np.int32) + v, x, j, rank, info = gelsy(a1, b1, jptv, np.finfo(dtype).eps, + lwork, False, False) + assert_allclose(x[:-1], + np.array([1.161753632288328-1.901075709391912j, + 1.735882340522193+1.521240901196909j], + dtype=dtype), + rtol=25*np.finfo(dtype).eps) + + +@pytest.mark.parametrize('dtype', DTYPES) +@pytest.mark.parametrize('shape', [(3, 4), (5, 2), (2**18, 2**18)]) +def test_geqrf_lwork(dtype, shape): + geqrf_lwork = get_lapack_funcs(('geqrf_lwork'), dtype=dtype) + m, n = shape + lwork, info = geqrf_lwork(m=m, n=n) + assert_equal(info, 0) + + +class TestRegression: + + def test_ticket_1645(self): + # Check that RQ routines have correct lwork + for dtype in DTYPES: + a = np.zeros((300, 2), dtype=dtype) + + gerqf, = get_lapack_funcs(['gerqf'], [a]) + assert_raises(Exception, gerqf, a, lwork=2) + rq, tau, work, info = gerqf(a) + + if dtype in REAL_DTYPES: + orgrq, = get_lapack_funcs(['orgrq'], [a]) + assert_raises(Exception, orgrq, rq[-2:], tau, lwork=1) + orgrq(rq[-2:], tau, lwork=2) + elif dtype in COMPLEX_DTYPES: + ungrq, = get_lapack_funcs(['ungrq'], [a]) + assert_raises(Exception, ungrq, rq[-2:], tau, lwork=1) + ungrq(rq[-2:], tau, lwork=2) + + +class TestDpotr: + def test_gh_2691(self): + # 'lower' argument of dportf/dpotri + for lower in [True, False]: + for clean in [True, False]: + np.random.seed(42) + x = np.random.normal(size=(3, 3)) + a = x.dot(x.T) + + dpotrf, dpotri = get_lapack_funcs(("potrf", "potri"), (a, )) + + c, info = dpotrf(a, lower, clean=clean) + dpt = dpotri(c, lower)[0] + + if lower: + assert_allclose(np.tril(dpt), np.tril(inv(a))) + else: + assert_allclose(np.triu(dpt), np.triu(inv(a))) + + +class TestDlasd4: + def test_sing_val_update(self): + + sigmas = np.array([4., 3., 2., 0]) + m_vec = np.array([3.12, 5.7, -4.8, -2.2]) + + M = np.hstack((np.vstack((np.diag(sigmas[0:-1]), + np.zeros((1, len(m_vec) - 1)))), + m_vec[:, np.newaxis])) + SM = svd(M, full_matrices=False, compute_uv=False, overwrite_a=False, + check_finite=False) + + it_len = len(sigmas) + sgm = np.concatenate((sigmas[::-1], [sigmas[0] + it_len*norm(m_vec)])) + mvc = np.concatenate((m_vec[::-1], (0,))) + + lasd4 = get_lapack_funcs('lasd4', (sigmas,)) + + roots = [] + for i in range(0, it_len): + res = lasd4(i, sgm, mvc) + roots.append(res[1]) + + assert_((res[3] <= 0), "LAPACK root finding dlasd4 failed to find \ + the singular value %i" % i) + roots = np.array(roots)[::-1] + + assert_((not np.any(np.isnan(roots)), "There are NaN roots")) + assert_allclose(SM, roots, atol=100*np.finfo(np.float64).eps, + rtol=100*np.finfo(np.float64).eps) + + +class TestTbtrs: + + @pytest.mark.parametrize('dtype', DTYPES) + def test_nag_example_f07vef_f07vsf(self, dtype): + """Test real (f07vef) and complex (f07vsf) examples from NAG + + Examples available from: + * https://www.nag.com/numeric/fl/nagdoc_latest/html/f07/f07vef.html + * https://www.nag.com/numeric/fl/nagdoc_latest/html/f07/f07vsf.html + + """ + if dtype in REAL_DTYPES: + ab = np.array([[-4.16, 4.78, 6.32, 0.16], + [-2.25, 5.86, -4.82, 0]], + dtype=dtype) + b = np.array([[-16.64, -4.16], + [-13.78, -16.59], + [13.10, -4.94], + [-14.14, -9.96]], + dtype=dtype) + x_out = np.array([[4, 1], + [-1, -3], + [3, 2], + [2, -2]], + dtype=dtype) + elif dtype in COMPLEX_DTYPES: + ab = np.array([[-1.94+4.43j, 4.12-4.27j, 0.43-2.66j, 0.44+0.1j], + [-3.39+3.44j, -1.84+5.52j, 1.74 - 0.04j, 0], + [1.62+3.68j, -2.77-1.93j, 0, 0]], + dtype=dtype) + b = np.array([[-8.86 - 3.88j, -24.09 - 5.27j], + [-15.57 - 23.41j, -57.97 + 8.14j], + [-7.63 + 22.78j, 19.09 - 29.51j], + [-14.74 - 2.40j, 19.17 + 21.33j]], + dtype=dtype) + x_out = np.array([[2j, 1 + 5j], + [1 - 3j, -7 - 2j], + [-4.001887 - 4.988417j, 3.026830 + 4.003182j], + [1.996158 - 1.045105j, -6.103357 - 8.986653j]], + dtype=dtype) + else: + raise ValueError(f"Datatype {dtype} not understood.") + + tbtrs = get_lapack_funcs(('tbtrs'), dtype=dtype) + x, info = tbtrs(ab=ab, b=b, uplo='L') + assert_equal(info, 0) + assert_allclose(x, x_out, rtol=0, atol=1e-5) + + @pytest.mark.parametrize('dtype,trans', + [(dtype, trans) + for dtype in DTYPES for trans in ['N', 'T', 'C'] + if not (trans == 'C' and dtype in REAL_DTYPES)]) + @pytest.mark.parametrize('uplo', ['U', 'L']) + @pytest.mark.parametrize('diag', ['N', 'U']) + def test_random_matrices(self, dtype, trans, uplo, diag): + rng = np.random.RandomState(1724) + + # n, nrhs, kd are used to specify A and b. + # A is of shape n x n with kd super/sub-diagonals + # b is of shape n x nrhs matrix + n, nrhs, kd = 4, 3, 2 + tbtrs = get_lapack_funcs('tbtrs', dtype=dtype) + + is_upper = (uplo == 'U') + ku = kd * is_upper + kl = kd - ku + + # Construct the diagonal and kd super/sub diagonals of A with + # the corresponding offsets. + band_offsets = range(ku, -kl - 1, -1) + band_widths = [n - abs(x) for x in band_offsets] + bands = [generate_random_dtype_array((width,), dtype, rng) + for width in band_widths] + + if diag == 'U': # A must be unit triangular + bands[ku] = np.ones(n, dtype=dtype) + + # Construct the diagonal banded matrix A from the bands and offsets. + a = sps.diags(bands, band_offsets, format='dia') + + # Convert A into banded storage form + ab = np.zeros((kd + 1, n), dtype) + for row, k in enumerate(band_offsets): + ab[row, max(k, 0):min(n+k, n)] = a.diagonal(k) + + # The RHS values. + b = generate_random_dtype_array((n, nrhs), dtype, rng) + + x, info = tbtrs(ab=ab, b=b, uplo=uplo, trans=trans, diag=diag) + assert_equal(info, 0) + + if trans == 'N': + assert_allclose(a @ x, b, rtol=5e-5) + elif trans == 'T': + assert_allclose(a.T @ x, b, rtol=5e-5) + elif trans == 'C': + assert_allclose(a.T.conjugate() @ x, b, rtol=5e-5) + else: + raise ValueError('Invalid trans argument') + + @pytest.mark.parametrize('uplo,trans,diag', + [['U', 'N', 'Invalid'], + ['U', 'Invalid', 'N'], + ['Invalid', 'N', 'N']]) + def test_invalid_argument_raises_exception(self, uplo, trans, diag): + """Test if invalid values of uplo, trans and diag raise exceptions""" + # Argument checks occur independently of used datatype. + # This mean we must not parameterize all available datatypes. + tbtrs = get_lapack_funcs('tbtrs', dtype=np.float64) + ab = rand(4, 2) + b = rand(2, 4) + assert_raises(Exception, tbtrs, ab, b, uplo, trans, diag) + + def test_zero_element_in_diagonal(self): + """Test if a matrix with a zero diagonal element is singular + + If the i-th diagonal of A is zero, ?tbtrs should return `i` in `info` + indicating the provided matrix is singular. + + Note that ?tbtrs requires the matrix A to be stored in banded form. + In this form the diagonal corresponds to the last row.""" + ab = np.ones((3, 4), dtype=float) + b = np.ones(4, dtype=float) + tbtrs = get_lapack_funcs('tbtrs', dtype=float) + + ab[-1, 3] = 0 + _, info = tbtrs(ab=ab, b=b, uplo='U') + assert_equal(info, 4) + + @pytest.mark.parametrize('ldab,n,ldb,nrhs', [ + (5, 5, 0, 5), + (5, 5, 3, 5) + ]) + def test_invalid_matrix_shapes(self, ldab, n, ldb, nrhs): + """Test ?tbtrs fails correctly if shapes are invalid.""" + ab = np.ones((ldab, n), dtype=float) + b = np.ones((ldb, nrhs), dtype=float) + tbtrs = get_lapack_funcs('tbtrs', dtype=float) + assert_raises(Exception, tbtrs, ab, b) + + + +@pytest.mark.parametrize('dtype', DTYPES) +@pytest.mark.parametrize('norm', ['I', '1', 'O']) +@pytest.mark.parametrize('uplo', ['U', 'L']) +@pytest.mark.parametrize('diag', ['N', 'U']) +@pytest.mark.parametrize('n', [3, 10]) +def test_trcon(dtype, norm, uplo, diag, n): + # Simple way to get deterministic (unlike `hash`) integer seed based on arguments + random.seed(f"{dtype}{norm}{uplo}{diag}{n}") + rng = np.random.default_rng(random.randint(0, 9999999999999)) + + A = rng.random(size=(n, n)) + rng.random(size=(n, n))*1j + # make the condition numbers more interesting + offset = rng.permuted(np.logspace(0, rng.integers(0, 10), n)) + A += offset + A = A.real if np.issubdtype(dtype, np.floating) else A + A = np.triu(A) if uplo == 'U' else np.tril(A) + if diag == 'U': + A /= np.diag(A)[:, np.newaxis] + A = A.astype(dtype) + + trcon = get_lapack_funcs('trcon', (A,)) + res, _ = trcon(A, norm=norm, uplo=uplo, diag=diag) + + if norm == 'I': + norm_A = np.linalg.norm(A, ord=np.inf) + norm_inv_A = np.linalg.norm(np.linalg.inv(A), ord=np.inf) + ref = 1 / (norm_A * norm_inv_A) + else: + anorm = np.abs(A).sum(axis=0).max() + gecon, getrf = get_lapack_funcs(('gecon', 'getrf'), (A,)) + lu, ipvt, info = getrf(A) + ref, _ = gecon(lu, anorm, norm=norm) + + # This is an estimate of reciprocal condition number; we just need order of + # magnitude. In testing, we observed that much smaller rtol is OK in almost + # all cases... but sometimes it isn't. + rtol = 1 # np.finfo(dtype).eps**0.75 + assert_allclose(res, ref, rtol=rtol) + + +def test_lartg(): + for dtype in 'fdFD': + lartg = get_lapack_funcs('lartg', dtype=dtype) + + f = np.array(3, dtype) + g = np.array(4, dtype) + + if np.iscomplexobj(g): + g *= 1j + + cs, sn, r = lartg(f, g) + + assert_allclose(cs, 3.0/5.0) + assert_allclose(r, 5.0) + + if np.iscomplexobj(g): + assert_allclose(sn, -4.0j/5.0) + assert_(isinstance(r, complex)) + assert_(isinstance(cs, float)) + else: + assert_allclose(sn, 4.0/5.0) + + +def test_rot(): + # srot, drot from blas and crot and zrot from lapack. + + for dtype in 'fdFD': + c = 0.6 + s = 0.8 + + u = np.full(4, 3, dtype) + v = np.full(4, 4, dtype) + atol = 10**-(np.finfo(dtype).precision-1) + + if dtype in 'fd': + rot = get_blas_funcs('rot', dtype=dtype) + f = 4 + else: + rot = get_lapack_funcs('rot', dtype=dtype) + s *= -1j + v *= 1j + f = 4j + + assert_allclose(rot(u, v, c, s), [[5, 5, 5, 5], + [0, 0, 0, 0]], atol=atol) + assert_allclose(rot(u, v, c, s, n=2), [[5, 5, 3, 3], + [0, 0, f, f]], atol=atol) + assert_allclose(rot(u, v, c, s, offx=2, offy=2), + [[3, 3, 5, 5], [f, f, 0, 0]], atol=atol) + assert_allclose(rot(u, v, c, s, incx=2, offy=2, n=2), + [[5, 3, 5, 3], [f, f, 0, 0]], atol=atol) + assert_allclose(rot(u, v, c, s, offx=2, incy=2, n=2), + [[3, 3, 5, 5], [0, f, 0, f]], atol=atol) + assert_allclose(rot(u, v, c, s, offx=2, incx=2, offy=2, incy=2, n=1), + [[3, 3, 5, 3], [f, f, 0, f]], atol=atol) + assert_allclose(rot(u, v, c, s, incx=-2, incy=-2, n=2), + [[5, 3, 5, 3], [0, f, 0, f]], atol=atol) + + a, b = rot(u, v, c, s, overwrite_x=1, overwrite_y=1) + assert_(a is u) + assert_(b is v) + assert_allclose(a, [5, 5, 5, 5], atol=atol) + assert_allclose(b, [0, 0, 0, 0], atol=atol) + + +def test_larfg_larf(): + np.random.seed(1234) + a0 = np.random.random((4, 4)) + a0 = a0.T.dot(a0) + + a0j = np.random.random((4, 4)) + 1j*np.random.random((4, 4)) + a0j = a0j.T.conj().dot(a0j) + + # our test here will be to do one step of reducing a hermetian matrix to + # tridiagonal form using householder transforms. + + for dtype in 'fdFD': + larfg, larf = get_lapack_funcs(['larfg', 'larf'], dtype=dtype) + + if dtype in 'FD': + a = a0j.copy() + else: + a = a0.copy() + + # generate a householder transform to clear a[2:,0] + alpha, x, tau = larfg(a.shape[0]-1, a[1, 0], a[2:, 0]) + + # create expected output + expected = np.zeros_like(a[:, 0]) + expected[0] = a[0, 0] + expected[1] = alpha + + # assemble householder vector + v = np.zeros_like(a[1:, 0]) + v[0] = 1.0 + v[1:] = x + + # apply transform from the left + a[1:, :] = larf(v, tau.conjugate(), a[1:, :], np.zeros(a.shape[1])) + + # apply transform from the right + a[:, 1:] = larf(v, tau, a[:, 1:], np.zeros(a.shape[0]), side='R') + + assert_allclose(a[:, 0], expected, atol=1e-5) + assert_allclose(a[0, :], expected, atol=1e-5) + + +def test_sgesdd_lwork_bug_workaround(): + # Test that SGESDD lwork is sufficiently large for LAPACK. + # + # This checks that _compute_lwork() correctly works around a bug in + # LAPACK versions older than 3.10.1. + + sgesdd_lwork = get_lapack_funcs('gesdd_lwork', dtype=np.float32, + ilp64='preferred') + n = 9537 + lwork = _compute_lwork(sgesdd_lwork, n, n, + compute_uv=True, full_matrices=True) + # If we called the Fortran function SGESDD directly with IWORK=-1, the + # LAPACK bug would result in lwork being 272929856, which was too small. + # (The result was returned in a single precision float, which does not + # have sufficient precision to represent the exact integer value that it + # computed internally.) The work-around implemented in _compute_lwork() + # will convert that to 272929888. If we are using LAPACK 3.10.1 or later + # (such as in OpenBLAS 0.3.21 or later), the work-around will return + # 272929920, because it does not know which version of LAPACK is being + # used, so it always applies the correction to whatever it is given. We + # will accept either 272929888 or 272929920. + # Note that the acceptable values are a LAPACK implementation detail. + # If a future version of LAPACK changes how SGESDD works, and therefore + # changes the required LWORK size, the acceptable values might have to + # be updated. + assert lwork == 272929888 or lwork == 272929920 + + +class TestSytrd: + @pytest.mark.parametrize('dtype', REAL_DTYPES) + def test_sytrd_with_zero_dim_array(self, dtype): + # Assert that a 0x0 matrix raises an error + A = np.zeros((0, 0), dtype=dtype) + sytrd = get_lapack_funcs('sytrd', (A,)) + assert_raises(ValueError, sytrd, A) + + @pytest.mark.parametrize('dtype', REAL_DTYPES) + @pytest.mark.parametrize('n', (1, 3)) + def test_sytrd(self, dtype, n): + A = np.zeros((n, n), dtype=dtype) + + sytrd, sytrd_lwork = \ + get_lapack_funcs(('sytrd', 'sytrd_lwork'), (A,)) + + # some upper triangular array + A[np.triu_indices_from(A)] = \ + np.arange(1, n*(n+1)//2+1, dtype=dtype) + + # query lwork + lwork, info = sytrd_lwork(n) + assert_equal(info, 0) + + # check lower=1 behavior (shouldn't do much since the matrix is + # upper triangular) + data, d, e, tau, info = sytrd(A, lower=1, lwork=lwork) + assert_equal(info, 0) + + assert_allclose(data, A, atol=5*np.finfo(dtype).eps, rtol=1.0) + assert_allclose(d, np.diag(A)) + assert_allclose(e, 0.0) + assert_allclose(tau, 0.0) + + # and now for the proper test (lower=0 is the default) + data, d, e, tau, info = sytrd(A, lwork=lwork) + assert_equal(info, 0) + + # assert Q^T*A*Q = tridiag(e, d, e) + + # build tridiagonal matrix + T = np.zeros_like(A, dtype=dtype) + k = np.arange(A.shape[0]) + T[k, k] = d + k2 = np.arange(A.shape[0]-1) + T[k2+1, k2] = e + T[k2, k2+1] = e + + # build Q + Q = np.eye(n, n, dtype=dtype) + for i in range(n-1): + v = np.zeros(n, dtype=dtype) + v[:i] = data[:i, i+1] + v[i] = 1.0 + H = np.eye(n, n, dtype=dtype) - tau[i] * np.outer(v, v) + Q = np.dot(H, Q) + + # Make matrix fully symmetric + i_lower = np.tril_indices(n, -1) + A[i_lower] = A.T[i_lower] + + QTAQ = np.dot(Q.T, np.dot(A, Q)) + + # disable rtol here since some values in QTAQ and T are very close + # to 0. + assert_allclose(QTAQ, T, atol=5*np.finfo(dtype).eps, rtol=1.0) + + +class TestHetrd: + @pytest.mark.parametrize('complex_dtype', COMPLEX_DTYPES) + def test_hetrd_with_zero_dim_array(self, complex_dtype): + # Assert that a 0x0 matrix raises an error + A = np.zeros((0, 0), dtype=complex_dtype) + hetrd = get_lapack_funcs('hetrd', (A,)) + assert_raises(ValueError, hetrd, A) + + @pytest.mark.parametrize('real_dtype,complex_dtype', + zip(REAL_DTYPES, COMPLEX_DTYPES)) + @pytest.mark.parametrize('n', (1, 3)) + def test_hetrd(self, n, real_dtype, complex_dtype): + A = np.zeros((n, n), dtype=complex_dtype) + hetrd, hetrd_lwork = \ + get_lapack_funcs(('hetrd', 'hetrd_lwork'), (A,)) + + # some upper triangular array + A[np.triu_indices_from(A)] = ( + np.arange(1, n*(n+1)//2+1, dtype=real_dtype) + + 1j * np.arange(1, n*(n+1)//2+1, dtype=real_dtype) + ) + np.fill_diagonal(A, np.real(np.diag(A))) + + # test query lwork + for x in [0, 1]: + _, info = hetrd_lwork(n, lower=x) + assert_equal(info, 0) + # lwork returns complex which segfaults hetrd call (gh-10388) + # use the safe and recommended option + lwork = _compute_lwork(hetrd_lwork, n) + + # check lower=1 behavior (shouldn't do much since the matrix is + # upper triangular) + data, d, e, tau, info = hetrd(A, lower=1, lwork=lwork) + assert_equal(info, 0) + + assert_allclose(data, A, atol=5*np.finfo(real_dtype).eps, rtol=1.0) + + assert_allclose(d, np.real(np.diag(A))) + assert_allclose(e, 0.0) + assert_allclose(tau, 0.0) + + # and now for the proper test (lower=0 is the default) + data, d, e, tau, info = hetrd(A, lwork=lwork) + assert_equal(info, 0) + + # assert Q^T*A*Q = tridiag(e, d, e) + + # build tridiagonal matrix + T = np.zeros_like(A, dtype=real_dtype) + k = np.arange(A.shape[0], dtype=int) + T[k, k] = d + k2 = np.arange(A.shape[0]-1, dtype=int) + T[k2+1, k2] = e + T[k2, k2+1] = e + + # build Q + Q = np.eye(n, n, dtype=complex_dtype) + for i in range(n-1): + v = np.zeros(n, dtype=complex_dtype) + v[:i] = data[:i, i+1] + v[i] = 1.0 + H = np.eye(n, n, dtype=complex_dtype) \ + - tau[i] * np.outer(v, np.conj(v)) + Q = np.dot(H, Q) + + # Make matrix fully Hermitian + i_lower = np.tril_indices(n, -1) + A[i_lower] = np.conj(A.T[i_lower]) + + QHAQ = np.dot(np.conj(Q.T), np.dot(A, Q)) + + # disable rtol here since some values in QTAQ and T are very close + # to 0. + assert_allclose( + QHAQ, T, atol=10*np.finfo(real_dtype).eps, rtol=1.0 + ) + + +def test_gglse(): + # Example data taken from NAG manual + for ind, dtype in enumerate(DTYPES): + # DTYPES = gglse + func, func_lwork = get_lapack_funcs(('gglse', 'gglse_lwork'), + dtype=dtype) + lwork = _compute_lwork(func_lwork, m=6, n=4, p=2) + # For gglse + if ind < 2: + a = np.array([[-0.57, -1.28, -0.39, 0.25], + [-1.93, 1.08, -0.31, -2.14], + [2.30, 0.24, 0.40, -0.35], + [-1.93, 0.64, -0.66, 0.08], + [0.15, 0.30, 0.15, -2.13], + [-0.02, 1.03, -1.43, 0.50]], dtype=dtype) + c = np.array([-1.50, -2.14, 1.23, -0.54, -1.68, 0.82], dtype=dtype) + d = np.array([0., 0.], dtype=dtype) + # For gglse + else: + a = np.array([[0.96-0.81j, -0.03+0.96j, -0.91+2.06j, -0.05+0.41j], + [-0.98+1.98j, -1.20+0.19j, -0.66+0.42j, -0.81+0.56j], + [0.62-0.46j, 1.01+0.02j, 0.63-0.17j, -1.11+0.60j], + [0.37+0.38j, 0.19-0.54j, -0.98-0.36j, 0.22-0.20j], + [0.83+0.51j, 0.20+0.01j, -0.17-0.46j, 1.47+1.59j], + [1.08-0.28j, 0.20-0.12j, -0.07+1.23j, 0.26+0.26j]]) + c = np.array([[-2.54+0.09j], + [1.65-2.26j], + [-2.11-3.96j], + [1.82+3.30j], + [-6.41+3.77j], + [2.07+0.66j]]) + d = np.zeros(2, dtype=dtype) + + b = np.array([[1., 0., -1., 0.], [0., 1., 0., -1.]], dtype=dtype) + + _, _, _, result, _ = func(a, b, c, d, lwork=lwork) + if ind < 2: + expected = np.array([0.48904455, + 0.99754786, + 0.48904455, + 0.99754786]) + else: + expected = np.array([1.08742917-1.96205783j, + -0.74093902+3.72973919j, + 1.08742917-1.96205759j, + -0.74093896+3.72973895j]) + assert_array_almost_equal(result, expected, decimal=4) + + +def test_sycon_hecon(): + seed(1234) + for ind, dtype in enumerate(DTYPES+COMPLEX_DTYPES): + # DTYPES + COMPLEX DTYPES = sycon + hecon + n = 10 + # For sycon + if ind < 4: + func_lwork = get_lapack_funcs('sytrf_lwork', dtype=dtype) + funcon, functrf = get_lapack_funcs(('sycon', 'sytrf'), dtype=dtype) + A = (rand(n, n)).astype(dtype) + # For hecon + else: + func_lwork = get_lapack_funcs('hetrf_lwork', dtype=dtype) + funcon, functrf = get_lapack_funcs(('hecon', 'hetrf'), dtype=dtype) + A = (rand(n, n) + rand(n, n)*1j).astype(dtype) + + # Since sycon only refers to upper/lower part, conj() is safe here. + A = (A + A.conj().T)/2 + 2*np.eye(n, dtype=dtype) + + anorm = norm(A, 1) + lwork = _compute_lwork(func_lwork, n) + ldu, ipiv, _ = functrf(A, lwork=lwork, lower=1) + rcond, _ = funcon(a=ldu, ipiv=ipiv, anorm=anorm, lower=1) + # The error is at most 1-fold + assert_(abs(1/rcond - np.linalg.cond(A, p=1))*rcond < 1) + + +def test_sygst(): + seed(1234) + for ind, dtype in enumerate(REAL_DTYPES): + # DTYPES = sygst + n = 10 + + potrf, sygst, syevd, sygvd = get_lapack_funcs(('potrf', 'sygst', + 'syevd', 'sygvd'), + dtype=dtype) + + A = rand(n, n).astype(dtype) + A = (A + A.T)/2 + # B must be positive definite + B = rand(n, n).astype(dtype) + B = (B + B.T)/2 + 2 * np.eye(n, dtype=dtype) + + # Perform eig (sygvd) + eig_gvd, _, info = sygvd(A, B) + assert_(info == 0) + + # Convert to std problem potrf + b, info = potrf(B) + assert_(info == 0) + a, info = sygst(A, b) + assert_(info == 0) + + eig, _, info = syevd(a) + assert_(info == 0) + assert_allclose(eig, eig_gvd, rtol=1.2e-4) + + +def test_hegst(): + seed(1234) + for ind, dtype in enumerate(COMPLEX_DTYPES): + # DTYPES = hegst + n = 10 + + potrf, hegst, heevd, hegvd = get_lapack_funcs(('potrf', 'hegst', + 'heevd', 'hegvd'), + dtype=dtype) + + A = rand(n, n).astype(dtype) + 1j * rand(n, n).astype(dtype) + A = (A + A.conj().T)/2 + # B must be positive definite + B = rand(n, n).astype(dtype) + 1j * rand(n, n).astype(dtype) + B = (B + B.conj().T)/2 + 2 * np.eye(n, dtype=dtype) + + # Perform eig (hegvd) + eig_gvd, _, info = hegvd(A, B) + assert_(info == 0) + + # Convert to std problem potrf + b, info = potrf(B) + assert_(info == 0) + a, info = hegst(A, b) + assert_(info == 0) + + eig, _, info = heevd(a) + assert_(info == 0) + assert_allclose(eig, eig_gvd, rtol=1e-4) + + +def test_tzrzf(): + """ + This test performs an RZ decomposition in which an m x n upper trapezoidal + array M (m <= n) is factorized as M = [R 0] * Z where R is upper triangular + and Z is unitary. + """ + rng = np.random.RandomState(1234) + m, n = 10, 15 + for ind, dtype in enumerate(DTYPES): + tzrzf, tzrzf_lw = get_lapack_funcs(('tzrzf', 'tzrzf_lwork'), + dtype=dtype) + lwork = _compute_lwork(tzrzf_lw, m, n) + + if ind < 2: + A = triu(rng.rand(m, n).astype(dtype)) + else: + A = triu((rng.rand(m, n) + rng.rand(m, n)*1j).astype(dtype)) + + # assert wrong shape arg, f2py returns generic error + assert_raises(Exception, tzrzf, A.T) + rz, tau, info = tzrzf(A, lwork=lwork) + # Check success + assert_(info == 0) + + # Get Z manually for comparison + R = np.hstack((rz[:, :m], np.zeros((m, n-m), dtype=dtype))) + V = np.hstack((np.eye(m, dtype=dtype), rz[:, m:])) + Id = np.eye(n, dtype=dtype) + ref = [Id-tau[x]*V[[x], :].T.dot(V[[x], :].conj()) for x in range(m)] + Z = reduce(np.dot, ref) + assert_allclose(R.dot(Z) - A, zeros_like(A, dtype=dtype), + atol=10*np.spacing(dtype(1.0).real), rtol=0.) + + +def test_tfsm(): + """ + Test for solving a linear system with the coefficient matrix is a + triangular array stored in Full Packed (RFP) format. + """ + rng = np.random.RandomState(1234) + for ind, dtype in enumerate(DTYPES): + n = 20 + if ind > 1: + A = triu(rng.rand(n, n) + rng.rand(n, n)*1j + eye(n)).astype(dtype) + trans = 'C' + else: + A = triu(rng.rand(n, n) + eye(n)).astype(dtype) + trans = 'T' + + trttf, tfttr, tfsm = get_lapack_funcs(('trttf', 'tfttr', 'tfsm'), + dtype=dtype) + + Afp, _ = trttf(A) + B = rng.rand(n, 2).astype(dtype) + soln = tfsm(-1, Afp, B) + assert_array_almost_equal(soln, solve(-A, B), + decimal=4 if ind % 2 == 0 else 6) + + soln = tfsm(-1, Afp, B, trans=trans) + assert_array_almost_equal(soln, solve(-A.conj().T, B), + decimal=4 if ind % 2 == 0 else 6) + + # Make A, unit diagonal + A[np.arange(n), np.arange(n)] = dtype(1.) + soln = tfsm(-1, Afp, B, trans=trans, diag='U') + assert_array_almost_equal(soln, solve(-A.conj().T, B), + decimal=4 if ind % 2 == 0 else 6) + + # Change side + B2 = rng.rand(3, n).astype(dtype) + soln = tfsm(-1, Afp, B2, trans=trans, diag='U', side='R') + assert_array_almost_equal(soln, solve(-A, B2.T).conj().T, + decimal=4 if ind % 2 == 0 else 6) + + +def test_ormrz_unmrz(): + """ + This test performs a matrix multiplication with an arbitrary m x n matrix C + and a unitary matrix Q without explicitly forming the array. The array data + is encoded in the rectangular part of A which is obtained from ?TZRZF. Q + size is inferred by m, n, side keywords. + """ + rng = np.random.RandomState(1234) + qm, qn, cn = 10, 15, 15 + for ind, dtype in enumerate(DTYPES): + tzrzf, tzrzf_lw = get_lapack_funcs(('tzrzf', 'tzrzf_lwork'), + dtype=dtype) + lwork_rz = _compute_lwork(tzrzf_lw, qm, qn) + + if ind < 2: + A = triu(rng.rand(qm, qn).astype(dtype)) + C = rng.rand(cn, cn).astype(dtype) + orun_mrz, orun_mrz_lw = get_lapack_funcs(('ormrz', 'ormrz_lwork'), + dtype=dtype) + else: + A = triu((rng.rand(qm, qn) + rng.rand(qm, qn)*1j).astype(dtype)) + C = (rng.rand(cn, cn) + rand(cn, cn)*1j).astype(dtype) + orun_mrz, orun_mrz_lw = get_lapack_funcs(('unmrz', 'unmrz_lwork'), + dtype=dtype) + + lwork_mrz = _compute_lwork(orun_mrz_lw, cn, cn) + rz, tau, info = tzrzf(A, lwork=lwork_rz) + + # Get Q manually for comparison + V = np.hstack((np.eye(qm, dtype=dtype), rz[:, qm:])) + Id = np.eye(qn, dtype=dtype) + ref = [Id-tau[x]*V[[x], :].T.dot(V[[x], :].conj()) for x in range(qm)] + Q = reduce(np.dot, ref) + + # Now that we have Q, we can test whether lapack results agree with + # each case of CQ, CQ^H, QC, and QC^H + trans = 'T' if ind < 2 else 'C' + tol = 10*np.spacing(dtype(1.0).real) + + cq, info = orun_mrz(rz, tau, C, lwork=lwork_mrz) + assert_(info == 0) + assert_allclose(cq - Q.dot(C), zeros_like(C), atol=tol, rtol=0.) + + cq, info = orun_mrz(rz, tau, C, trans=trans, lwork=lwork_mrz) + assert_(info == 0) + assert_allclose(cq - Q.conj().T.dot(C), zeros_like(C), atol=tol, + rtol=0.) + + cq, info = orun_mrz(rz, tau, C, side='R', lwork=lwork_mrz) + assert_(info == 0) + assert_allclose(cq - C.dot(Q), zeros_like(C), atol=tol, rtol=0.) + + cq, info = orun_mrz(rz, tau, C, side='R', trans=trans, lwork=lwork_mrz) + assert_(info == 0) + assert_allclose(cq - C.dot(Q.conj().T), zeros_like(C), atol=tol, + rtol=0.) + + +def test_tfttr_trttf(): + """ + Test conversion routines between the Rectangular Full Packed (RFP) format + and Standard Triangular Array (TR) + """ + rng = np.random.RandomState(1234) + for ind, dtype in enumerate(DTYPES): + n = 20 + if ind > 1: + A_full = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype) + transr = 'C' + else: + A_full = (rng.rand(n, n)).astype(dtype) + transr = 'T' + + trttf, tfttr = get_lapack_funcs(('trttf', 'tfttr'), dtype=dtype) + A_tf_U, info = trttf(A_full) + assert_(info == 0) + A_tf_L, info = trttf(A_full, uplo='L') + assert_(info == 0) + A_tf_U_T, info = trttf(A_full, transr=transr, uplo='U') + assert_(info == 0) + A_tf_L_T, info = trttf(A_full, transr=transr, uplo='L') + assert_(info == 0) + + # Create the RFP array manually (n is even!) + A_tf_U_m = zeros((n+1, n//2), dtype=dtype) + A_tf_U_m[:-1, :] = triu(A_full)[:, n//2:] + A_tf_U_m[n//2+1:, :] += triu(A_full)[:n//2, :n//2].conj().T + + A_tf_L_m = zeros((n+1, n//2), dtype=dtype) + A_tf_L_m[1:, :] = tril(A_full)[:, :n//2] + A_tf_L_m[:n//2, :] += tril(A_full)[n//2:, n//2:].conj().T + + assert_array_almost_equal(A_tf_U, A_tf_U_m.reshape(-1, order='F')) + assert_array_almost_equal(A_tf_U_T, + A_tf_U_m.conj().T.reshape(-1, order='F')) + + assert_array_almost_equal(A_tf_L, A_tf_L_m.reshape(-1, order='F')) + assert_array_almost_equal(A_tf_L_T, + A_tf_L_m.conj().T.reshape(-1, order='F')) + + # Get the original array from RFP + A_tr_U, info = tfttr(n, A_tf_U) + assert_(info == 0) + A_tr_L, info = tfttr(n, A_tf_L, uplo='L') + assert_(info == 0) + A_tr_U_T, info = tfttr(n, A_tf_U_T, transr=transr, uplo='U') + assert_(info == 0) + A_tr_L_T, info = tfttr(n, A_tf_L_T, transr=transr, uplo='L') + assert_(info == 0) + + assert_array_almost_equal(A_tr_U, triu(A_full)) + assert_array_almost_equal(A_tr_U_T, triu(A_full)) + assert_array_almost_equal(A_tr_L, tril(A_full)) + assert_array_almost_equal(A_tr_L_T, tril(A_full)) + + +def test_tpttr_trttp(): + """ + Test conversion routines between the Rectangular Full Packed (RFP) format + and Standard Triangular Array (TR) + """ + rng = np.random.RandomState(1234) + for ind, dtype in enumerate(DTYPES): + n = 20 + if ind > 1: + A_full = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype) + else: + A_full = (rng.rand(n, n)).astype(dtype) + + trttp, tpttr = get_lapack_funcs(('trttp', 'tpttr'), dtype=dtype) + A_tp_U, info = trttp(A_full) + assert_(info == 0) + A_tp_L, info = trttp(A_full, uplo='L') + assert_(info == 0) + + # Create the TP array manually + inds = tril_indices(n) + A_tp_U_m = zeros(n*(n+1)//2, dtype=dtype) + A_tp_U_m[:] = (triu(A_full).T)[inds] + + inds = triu_indices(n) + A_tp_L_m = zeros(n*(n+1)//2, dtype=dtype) + A_tp_L_m[:] = (tril(A_full).T)[inds] + + assert_array_almost_equal(A_tp_U, A_tp_U_m) + assert_array_almost_equal(A_tp_L, A_tp_L_m) + + # Get the original array from TP + A_tr_U, info = tpttr(n, A_tp_U) + assert_(info == 0) + A_tr_L, info = tpttr(n, A_tp_L, uplo='L') + assert_(info == 0) + + assert_array_almost_equal(A_tr_U, triu(A_full)) + assert_array_almost_equal(A_tr_L, tril(A_full)) + + +def test_pftrf(): + """ + Test Cholesky factorization of a positive definite Rectangular Full + Packed (RFP) format array + """ + rng = np.random.RandomState(1234) + for ind, dtype in enumerate(DTYPES): + n = 20 + if ind > 1: + A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype) + A = A + A.conj().T + n*eye(n) + else: + A = (rng.rand(n, n)).astype(dtype) + A = A + A.T + n*eye(n) + + pftrf, trttf, tfttr = get_lapack_funcs(('pftrf', 'trttf', 'tfttr'), + dtype=dtype) + + # Get the original array from TP + Afp, info = trttf(A) + Achol_rfp, info = pftrf(n, Afp) + assert_(info == 0) + A_chol_r, _ = tfttr(n, Achol_rfp) + Achol = cholesky(A) + assert_array_almost_equal(A_chol_r, Achol) + + +def test_pftri(): + """ + Test Cholesky factorization of a positive definite Rectangular Full + Packed (RFP) format array to find its inverse + """ + rng = np.random.RandomState(1234) + for ind, dtype in enumerate(DTYPES): + n = 20 + if ind > 1: + A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype) + A = A + A.conj().T + n*eye(n) + else: + A = (rng.rand(n, n)).astype(dtype) + A = A + A.T + n*eye(n) + + pftri, pftrf, trttf, tfttr = get_lapack_funcs(('pftri', + 'pftrf', + 'trttf', + 'tfttr'), + dtype=dtype) + + # Get the original array from TP + Afp, info = trttf(A) + A_chol_rfp, info = pftrf(n, Afp) + A_inv_rfp, info = pftri(n, A_chol_rfp) + assert_(info == 0) + A_inv_r, _ = tfttr(n, A_inv_rfp) + Ainv = inv(A) + assert_array_almost_equal(A_inv_r, triu(Ainv), + decimal=4 if ind % 2 == 0 else 6) + + +def test_pftrs(): + """ + Test Cholesky factorization of a positive definite Rectangular Full + Packed (RFP) format array and solve a linear system + """ + rng = np.random.RandomState(1234) + for ind, dtype in enumerate(DTYPES): + n = 20 + if ind > 1: + A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype) + A = A + A.conj().T + n*eye(n) + else: + A = (rng.rand(n, n)).astype(dtype) + A = A + A.T + n*eye(n) + + B = ones((n, 3), dtype=dtype) + Bf1 = ones((n+2, 3), dtype=dtype) + Bf2 = ones((n-2, 3), dtype=dtype) + pftrs, pftrf, trttf, tfttr = get_lapack_funcs(('pftrs', + 'pftrf', + 'trttf', + 'tfttr'), + dtype=dtype) + + # Get the original array from TP + Afp, info = trttf(A) + A_chol_rfp, info = pftrf(n, Afp) + # larger B arrays shouldn't segfault + soln, info = pftrs(n, A_chol_rfp, Bf1) + assert_(info == 0) + assert_raises(Exception, pftrs, n, A_chol_rfp, Bf2) + soln, info = pftrs(n, A_chol_rfp, B) + assert_(info == 0) + assert_array_almost_equal(solve(A, B), soln, + decimal=4 if ind % 2 == 0 else 6) + + +def test_sfrk_hfrk(): + """ + Test for performing a symmetric rank-k operation for matrix in RFP format. + """ + rng = np.random.RandomState(1234) + for ind, dtype in enumerate(DTYPES): + n = 20 + if ind > 1: + A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype) + A = A + A.conj().T + n*eye(n) + else: + A = (rng.rand(n, n)).astype(dtype) + A = A + A.T + n*eye(n) + + prefix = 's'if ind < 2 else 'h' + trttf, tfttr, shfrk = get_lapack_funcs(('trttf', 'tfttr', f'{prefix}frk'), + dtype=dtype) + + Afp, _ = trttf(A) + C = rng.rand(n, 2).astype(dtype) + Afp_out = shfrk(n, 2, -1, C, 2, Afp) + A_out, _ = tfttr(n, Afp_out) + assert_array_almost_equal(A_out, triu(-C.dot(C.conj().T) + 2*A), + decimal=4 if ind % 2 == 0 else 6) + + +def test_syconv(): + """ + Test for going back and forth between the returned format of he/sytrf to + L and D factors/permutations. + """ + rng = np.random.RandomState(1234) + for ind, dtype in enumerate(DTYPES): + n = 10 + + if ind > 1: + A = (rng.randint(-30, 30, (n, n)) + + rng.randint(-30, 30, (n, n))*1j).astype(dtype) + + A = A + A.conj().T + else: + A = rng.randint(-30, 30, (n, n)).astype(dtype) + A = A + A.T + n*eye(n) + + tol = 100*np.spacing(dtype(1.0).real) + syconv, trf, trf_lwork = get_lapack_funcs(('syconv', 'sytrf', + 'sytrf_lwork'), dtype=dtype) + lw = _compute_lwork(trf_lwork, n, lower=1) + L, D, perm = ldl(A, lower=1, hermitian=False) + lw = _compute_lwork(trf_lwork, n, lower=1) + ldu, ipiv, info = trf(A, lower=1, lwork=lw) + a, e, info = syconv(ldu, ipiv, lower=1) + assert_allclose(tril(a, -1,), tril(L[perm, :], -1), atol=tol, rtol=0.) + + # Test also upper + U, D, perm = ldl(A, lower=0, hermitian=False) + ldu, ipiv, info = trf(A, lower=0) + a, e, info = syconv(ldu, ipiv, lower=0) + assert_allclose(triu(a, 1), triu(U[perm, :], 1), atol=tol, rtol=0.) + + +class TestBlockedQR: + """ + Tests for the blocked QR factorization, namely through geqrt, gemqrt, tpqrt + and tpmqr. + """ + + def test_geqrt_gemqrt(self): + rng = np.random.RandomState(1234) + for ind, dtype in enumerate(DTYPES): + n = 20 + + if ind > 1: + A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype) + else: + A = (rng.rand(n, n)).astype(dtype) + + tol = 100*np.spacing(dtype(1.0).real) + geqrt, gemqrt = get_lapack_funcs(('geqrt', 'gemqrt'), dtype=dtype) + + a, t, info = geqrt(n, A) + assert info == 0 + + # Extract elementary reflectors from lower triangle, adding the + # main diagonal of ones. + v = np.tril(a, -1) + np.eye(n, dtype=dtype) + # Generate the block Householder transform I - VTV^H + Q = np.eye(n, dtype=dtype) - v @ t @ v.T.conj() + R = np.triu(a) + + # Test columns of Q are orthogonal + assert_allclose(Q.T.conj() @ Q, np.eye(n, dtype=dtype), atol=tol, + rtol=0.) + assert_allclose(Q @ R, A, atol=tol, rtol=0.) + + if ind > 1: + C = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype) + transpose = 'C' + else: + C = (rng.rand(n, n)).astype(dtype) + transpose = 'T' + + for side in ('L', 'R'): + for trans in ('N', transpose): + c, info = gemqrt(a, t, C, side=side, trans=trans) + assert info == 0 + + if trans == transpose: + q = Q.T.conj() + else: + q = Q + + if side == 'L': + qC = q @ C + else: + qC = C @ q + + assert_allclose(c, qC, atol=tol, rtol=0.) + + # Test default arguments + if (side, trans) == ('L', 'N'): + c_default, info = gemqrt(a, t, C) + assert info == 0 + assert_equal(c_default, c) + + # Test invalid side/trans + assert_raises(Exception, gemqrt, a, t, C, side='A') + assert_raises(Exception, gemqrt, a, t, C, trans='A') + + def test_tpqrt_tpmqrt(self): + rng = np.random.RandomState(1234) + for ind, dtype in enumerate(DTYPES): + n = 20 + + if ind > 1: + A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype) + B = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype) + else: + A = (rng.rand(n, n)).astype(dtype) + B = (rng.rand(n, n)).astype(dtype) + + tol = 100*np.spacing(dtype(1.0).real) + tpqrt, tpmqrt = get_lapack_funcs(('tpqrt', 'tpmqrt'), dtype=dtype) + + # Test for the range of pentagonal B, from square to upper + # triangular + for l in (0, n // 2, n): + a, b, t, info = tpqrt(l, n, A, B) + assert info == 0 + + # Check that lower triangular part of A has not been modified + assert_equal(np.tril(a, -1), np.tril(A, -1)) + # Check that elements not part of the pentagonal portion of B + # have not been modified. + assert_equal(np.tril(b, l - n - 1), np.tril(B, l - n - 1)) + + # Extract pentagonal portion of B + B_pent, b_pent = np.triu(B, l - n), np.triu(b, l - n) + + # Generate elementary reflectors + v = np.concatenate((np.eye(n, dtype=dtype), b_pent)) + # Generate the block Householder transform I - VTV^H + Q = np.eye(2 * n, dtype=dtype) - v @ t @ v.T.conj() + R = np.concatenate((np.triu(a), np.zeros_like(a))) + + # Test columns of Q are orthogonal + assert_allclose(Q.T.conj() @ Q, np.eye(2 * n, dtype=dtype), + atol=tol, rtol=0.) + assert_allclose(Q @ R, np.concatenate((np.triu(A), B_pent)), + atol=tol, rtol=0.) + + if ind > 1: + C = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype) + D = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype) + transpose = 'C' + else: + C = (rng.rand(n, n)).astype(dtype) + D = (rng.rand(n, n)).astype(dtype) + transpose = 'T' + + for side in ('L', 'R'): + for trans in ('N', transpose): + c, d, info = tpmqrt(l, b, t, C, D, side=side, + trans=trans) + assert info == 0 + + if trans == transpose: + q = Q.T.conj() + else: + q = Q + + if side == 'L': + cd = np.concatenate((c, d), axis=0) + CD = np.concatenate((C, D), axis=0) + qCD = q @ CD + else: + cd = np.concatenate((c, d), axis=1) + CD = np.concatenate((C, D), axis=1) + qCD = CD @ q + + assert_allclose(cd, qCD, atol=tol, rtol=0.) + + if (side, trans) == ('L', 'N'): + c_default, d_default, info = tpmqrt(l, b, t, C, D) + assert info == 0 + assert_equal(c_default, c) + assert_equal(d_default, d) + + # Test invalid side/trans + assert_raises(Exception, tpmqrt, l, b, t, C, D, side='A') + assert_raises(Exception, tpmqrt, l, b, t, C, D, trans='A') + + +def test_pstrf(): + rng = np.random.RandomState(1234) + for ind, dtype in enumerate(DTYPES): + # DTYPES = pstrf + n = 10 + r = 2 + pstrf = get_lapack_funcs('pstrf', dtype=dtype) + + # Create positive semidefinite A + if ind > 1: + A = rng.rand(n, n-r).astype(dtype) + 1j * rng.rand(n, n-r).astype(dtype) + A = A @ A.conj().T + else: + A = rng.rand(n, n-r).astype(dtype) + A = A @ A.T + + c, piv, r_c, info = pstrf(A) + U = triu(c) + U[r_c - n:, r_c - n:] = 0. + + assert_equal(info, 1) + # python-dbg 3.5.2 runs cause trouble with the following assertion. + # assert_equal(r_c, n - r) + single_atol = 1000 * np.finfo(np.float32).eps + double_atol = 1000 * np.finfo(np.float64).eps + atol = single_atol if ind in [0, 2] else double_atol + assert_allclose(A[piv-1][:, piv-1], U.conj().T @ U, rtol=0., atol=atol) + + c, piv, r_c, info = pstrf(A, lower=1) + L = tril(c) + L[r_c - n:, r_c - n:] = 0. + + assert_equal(info, 1) + # assert_equal(r_c, n - r) + single_atol = 1000 * np.finfo(np.float32).eps + double_atol = 1000 * np.finfo(np.float64).eps + atol = single_atol if ind in [0, 2] else double_atol + assert_allclose(A[piv-1][:, piv-1], L @ L.conj().T, rtol=0., atol=atol) + + +def test_pstf2(): + rng = np.random.RandomState(1234) + for ind, dtype in enumerate(DTYPES): + # DTYPES = pstf2 + n = 10 + r = 2 + pstf2 = get_lapack_funcs('pstf2', dtype=dtype) + + # Create positive semidefinite A + if ind > 1: + A = rng.rand(n, n-r).astype(dtype) + 1j * rng.rand(n, n-r).astype(dtype) + A = A @ A.conj().T + else: + A = rng.rand(n, n-r).astype(dtype) + A = A @ A.T + + c, piv, r_c, info = pstf2(A) + U = triu(c) + U[r_c - n:, r_c - n:] = 0. + + assert_equal(info, 1) + # python-dbg 3.5.2 runs cause trouble with the commented assertions. + # assert_equal(r_c, n - r) + single_atol = 1000 * np.finfo(np.float32).eps + double_atol = 1000 * np.finfo(np.float64).eps + atol = single_atol if ind in [0, 2] else double_atol + assert_allclose(A[piv-1][:, piv-1], U.conj().T @ U, rtol=0., atol=atol) + + c, piv, r_c, info = pstf2(A, lower=1) + L = tril(c) + L[r_c - n:, r_c - n:] = 0. + + assert_equal(info, 1) + # assert_equal(r_c, n - r) + single_atol = 1000 * np.finfo(np.float32).eps + double_atol = 1000 * np.finfo(np.float64).eps + atol = single_atol if ind in [0, 2] else double_atol + assert_allclose(A[piv-1][:, piv-1], L @ L.conj().T, rtol=0., atol=atol) + + +def test_geequ(): + desired_real = np.array([[0.6250, 1.0000, 0.0393, -0.4269], + [1.0000, -0.5619, -1.0000, -1.0000], + [0.5874, -1.0000, -0.0596, -0.5341], + [-1.0000, -0.5946, -0.0294, 0.9957]]) + + desired_cplx = np.array([[-0.2816+0.5359*1j, + 0.0812+0.9188*1j, + -0.7439-0.2561*1j], + [-0.3562-0.2954*1j, + 0.9566-0.0434*1j, + -0.0174+0.1555*1j], + [0.8607+0.1393*1j, + -0.2759+0.7241*1j, + -0.1642-0.1365*1j]]) + + for ind, dtype in enumerate(DTYPES): + if ind < 2: + # Use examples from the NAG documentation + A = np.array([[1.80e+10, 2.88e+10, 2.05e+00, -8.90e+09], + [5.25e+00, -2.95e+00, -9.50e-09, -3.80e+00], + [1.58e+00, -2.69e+00, -2.90e-10, -1.04e+00], + [-1.11e+00, -6.60e-01, -5.90e-11, 8.00e-01]]) + A = A.astype(dtype) + else: + A = np.array([[-1.34e+00, 0.28e+10, -6.39e+00], + [-1.70e+00, 3.31e+10, -0.15e+00], + [2.41e-10, -0.56e+00, -0.83e-10]], dtype=dtype) + A += np.array([[2.55e+00, 3.17e+10, -2.20e+00], + [-1.41e+00, -0.15e+10, 1.34e+00], + [0.39e-10, 1.47e+00, -0.69e-10]])*1j + + A = A.astype(dtype) + + geequ = get_lapack_funcs('geequ', dtype=dtype) + r, c, rowcnd, colcnd, amax, info = geequ(A) + + if ind < 2: + assert_allclose(desired_real.astype(dtype), r[:, None]*A*c, + rtol=0, atol=1e-4) + else: + assert_allclose(desired_cplx.astype(dtype), r[:, None]*A*c, + rtol=0, atol=1e-4) + + +def test_syequb(): + desired_log2s = np.array([0, 0, 0, 0, 0, 0, -1, -1, -2, -3]) + + for ind, dtype in enumerate(DTYPES): + A = np.eye(10, dtype=dtype) + alpha = dtype(1. if ind < 2 else 1.j) + d = np.array([alpha * 2.**x for x in range(-5, 5)], dtype=dtype) + A += np.rot90(np.diag(d)) + + syequb = get_lapack_funcs('syequb', dtype=dtype) + s, scond, amax, info = syequb(A) + + assert_equal(np.log2(s).astype(int), desired_log2s) + + +@pytest.mark.skipif(True, + reason="Failing on some OpenBLAS version, see gh-12276") +def test_heequb(): + # zheequb has a bug for versions =< LAPACK 3.9.0 + # See Reference-LAPACK gh-61 and gh-408 + # Hence the zheequb test is customized accordingly to avoid + # work scaling. + A = np.diag([2]*5 + [1002]*5) + np.diag(np.ones(9), k=1)*1j + s, scond, amax, info = lapack.zheequb(A) + assert_equal(info, 0) + assert_allclose(np.log2(s), [0., -1.]*2 + [0.] + [-4]*5) + + A = np.diag(2**np.abs(np.arange(-5, 6)) + 0j) + A[5, 5] = 1024 + A[5, 0] = 16j + s, scond, amax, info = lapack.cheequb(A.astype(np.complex64), lower=1) + assert_equal(info, 0) + assert_allclose(np.log2(s), [-2, -1, -1, 0, 0, -5, 0, -1, -1, -2, -2]) + + +def test_getc2_gesc2(): + rng = np.random.RandomState(42) + n = 10 + desired_real = rng.rand(n) + desired_cplx = rng.rand(n) + rng.rand(n)*1j + + for ind, dtype in enumerate(DTYPES): + if ind < 2: + A = rng.rand(n, n) + A = A.astype(dtype) + b = A @ desired_real + b = b.astype(dtype) + else: + A = rng.rand(n, n) + rng.rand(n, n)*1j + A = A.astype(dtype) + b = A @ desired_cplx + b = b.astype(dtype) + + getc2 = get_lapack_funcs('getc2', dtype=dtype) + gesc2 = get_lapack_funcs('gesc2', dtype=dtype) + lu, ipiv, jpiv, info = getc2(A, overwrite_a=0) + x, scale = gesc2(lu, b, ipiv, jpiv, overwrite_rhs=0) + + if ind < 2: + assert_array_almost_equal(desired_real.astype(dtype), + x/scale, decimal=4) + else: + assert_array_almost_equal(desired_cplx.astype(dtype), + x/scale, decimal=4) + + +@pytest.mark.parametrize('size', [(6, 5), (5, 5)]) +@pytest.mark.parametrize('dtype', REAL_DTYPES) +@pytest.mark.parametrize('joba', range(6)) # 'C', 'E', 'F', 'G', 'A', 'R' +@pytest.mark.parametrize('jobu', range(4)) # 'U', 'F', 'W', 'N' +@pytest.mark.parametrize('jobv', range(4)) # 'V', 'J', 'W', 'N' +@pytest.mark.parametrize('jobr', [0, 1]) +@pytest.mark.parametrize('jobp', [0, 1]) +def test_gejsv_general(size, dtype, joba, jobu, jobv, jobr, jobp, jobt=0): + """Test the lapack routine ?gejsv. + + This function tests that a singular value decomposition can be performed + on the random M-by-N matrix A. The test performs the SVD using ?gejsv + then performs the following checks: + + * ?gejsv exist successfully (info == 0) + * The returned singular values are correct + * `A` can be reconstructed from `u`, `SIGMA`, `v` + * Ensure that u.T @ u is the identity matrix + * Ensure that v.T @ v is the identity matrix + * The reported matrix rank + * The reported number of singular values + * If denormalized floats are required + + Notes + ----- + joba specifies several choices effecting the calculation's accuracy + Although all arguments are tested, the tests only check that the correct + solution is returned - NOT that the prescribed actions are performed + internally. + + jobt is, as of v3.9.0, still experimental and removed to cut down number of + test cases. However keyword itself is tested externally. + """ + rng = np.random.RandomState(42) + + # Define some constants for later use: + m, n = size + atol = 100 * np.finfo(dtype).eps + A = generate_random_dtype_array(size, dtype, rng) + gejsv = get_lapack_funcs('gejsv', dtype=dtype) + + # Set up checks for invalid job? combinations + # if an invalid combination occurs we set the appropriate + # exit status. + lsvec = jobu < 2 # Calculate left singular vectors + rsvec = jobv < 2 # Calculate right singular vectors + l2tran = (jobt == 1) and (m == n) + is_complex = np.iscomplexobj(A) + + invalid_real_jobv = (jobv == 1) and (not lsvec) and (not is_complex) + invalid_cplx_jobu = (jobu == 2) and not (rsvec and l2tran) and is_complex + invalid_cplx_jobv = (jobv == 2) and not (lsvec and l2tran) and is_complex + + # Set the exit status to the expected value. + # Here we only check for invalid combinations, not individual + # parameters. + if invalid_cplx_jobu: + exit_status = -2 + elif invalid_real_jobv or invalid_cplx_jobv: + exit_status = -3 + else: + exit_status = 0 + + if (jobu > 1) and (jobv == 1): + assert_raises(Exception, gejsv, A, joba, jobu, jobv, jobr, jobt, jobp) + else: + sva, u, v, work, iwork, info = gejsv(A, + joba=joba, + jobu=jobu, + jobv=jobv, + jobr=jobr, + jobt=jobt, + jobp=jobp) + + # Check that ?gejsv exited successfully/as expected + assert_equal(info, exit_status) + + # If exit_status is non-zero the combination of jobs is invalid. + # We test this above but no calculations are performed. + if not exit_status: + + # Check the returned singular values + sigma = (work[0] / work[1]) * sva[:n] + assert_allclose(sigma, svd(A, compute_uv=False), atol=atol) + + if jobu == 1: + # If JOBU = 'F', then u contains the M-by-M matrix of + # the left singular vectors, including an ONB of the orthogonal + # complement of the Range(A) + # However, to recalculate A we are concerned about the + # first n singular values and so can ignore the latter. + # TODO: Add a test for ONB? + u = u[:, :n] + + if lsvec and rsvec: + assert_allclose(u @ np.diag(sigma) @ v.conj().T, A, atol=atol) + if lsvec: + assert_allclose(u.conj().T @ u, np.identity(n), atol=atol) + if rsvec: + assert_allclose(v.conj().T @ v, np.identity(n), atol=atol) + + assert_equal(iwork[0], np.linalg.matrix_rank(A)) + assert_equal(iwork[1], np.count_nonzero(sigma)) + # iwork[2] is non-zero if requested accuracy is not warranted for + # the data. This should never occur for these tests. + assert_equal(iwork[2], 0) + + +@pytest.mark.parametrize('dtype', REAL_DTYPES) +def test_gejsv_edge_arguments(dtype): + """Test edge arguments return expected status""" + gejsv = get_lapack_funcs('gejsv', dtype=dtype) + + # scalar A + sva, u, v, work, iwork, info = gejsv(1.) + assert_equal(info, 0) + assert_equal(u.shape, (1, 1)) + assert_equal(v.shape, (1, 1)) + assert_equal(sva, np.array([1.], dtype=dtype)) + + # 1d A + A = np.ones((1,), dtype=dtype) + sva, u, v, work, iwork, info = gejsv(A) + assert_equal(info, 0) + assert_equal(u.shape, (1, 1)) + assert_equal(v.shape, (1, 1)) + assert_equal(sva, np.array([1.], dtype=dtype)) + + # 2d empty A + A = np.ones((1, 0), dtype=dtype) + sva, u, v, work, iwork, info = gejsv(A) + assert_equal(info, 0) + assert_equal(u.shape, (1, 0)) + assert_equal(v.shape, (1, 0)) + assert_equal(sva, np.array([], dtype=dtype)) + + # make sure "overwrite_a" is respected - user reported in gh-13191 + A = np.sin(np.arange(100).reshape(10, 10)).astype(dtype) + A = np.asfortranarray(A + A.T) # make it symmetric and column major + Ac = A.copy('A') + _ = gejsv(A) + assert_allclose(A, Ac) + + +@pytest.mark.parametrize(('kwargs'), + ({'joba': 9}, + {'jobu': 9}, + {'jobv': 9}, + {'jobr': 9}, + {'jobt': 9}, + {'jobp': 9}) + ) +def test_gejsv_invalid_job_arguments(kwargs): + """Test invalid job arguments raise an Exception""" + A = np.ones((2, 2), dtype=float) + gejsv = get_lapack_funcs('gejsv', dtype=float) + assert_raises(Exception, gejsv, A, **kwargs) + + +@pytest.mark.parametrize("A,sva_expect,u_expect,v_expect", + [(np.array([[2.27, -1.54, 1.15, -1.94], + [0.28, -1.67, 0.94, -0.78], + [-0.48, -3.09, 0.99, -0.21], + [1.07, 1.22, 0.79, 0.63], + [-2.35, 2.93, -1.45, 2.30], + [0.62, -7.39, 1.03, -2.57]]), + np.array([9.9966, 3.6831, 1.3569, 0.5000]), + np.array([[0.2774, -0.6003, -0.1277, 0.1323], + [0.2020, -0.0301, 0.2805, 0.7034], + [0.2918, 0.3348, 0.6453, 0.1906], + [-0.0938, -0.3699, 0.6781, -0.5399], + [-0.4213, 0.5266, 0.0413, -0.0575], + [0.7816, 0.3353, -0.1645, -0.3957]]), + np.array([[0.1921, -0.8030, 0.0041, -0.5642], + [-0.8794, -0.3926, -0.0752, 0.2587], + [0.2140, -0.2980, 0.7827, 0.5027], + [-0.3795, 0.3351, 0.6178, -0.6017]]))]) +def test_gejsv_NAG(A, sva_expect, u_expect, v_expect): + """ + This test implements the example found in the NAG manual, f08khf. + An example was not found for the complex case. + """ + # NAG manual provides accuracy up to 4 decimals + atol = 1e-4 + gejsv = get_lapack_funcs('gejsv', dtype=A.dtype) + + sva, u, v, work, iwork, info = gejsv(A) + + assert_allclose(sva_expect, sva, atol=atol) + assert_allclose(u_expect, u, atol=atol) + assert_allclose(v_expect, v, atol=atol) + + +@pytest.mark.parametrize("dtype", DTYPES) +def test_gttrf_gttrs(dtype): + # The test uses ?gttrf and ?gttrs to solve a random system for each dtype, + # tests that the output of ?gttrf define LU matrices, that input + # parameters are unmodified, transposal options function correctly, that + # incompatible matrix shapes raise an error, and singular matrices return + # non zero info. + + rng = np.random.RandomState(42) + n = 10 + atol = 100 * np.finfo(dtype).eps + + # create the matrix in accordance with the data type + du = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng) + d = generate_random_dtype_array((n,), dtype=dtype, rng=rng) + dl = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng) + + diag_cpy = [dl.copy(), d.copy(), du.copy()] + + A = np.diag(d) + np.diag(dl, -1) + np.diag(du, 1) + x = np.random.rand(n) + b = A @ x + + gttrf, gttrs = get_lapack_funcs(('gttrf', 'gttrs'), dtype=dtype) + + _dl, _d, _du, du2, ipiv, info = gttrf(dl, d, du) + # test to assure that the inputs of ?gttrf are unmodified + assert_array_equal(dl, diag_cpy[0]) + assert_array_equal(d, diag_cpy[1]) + assert_array_equal(du, diag_cpy[2]) + + # generate L and U factors from ?gttrf return values + # L/U are lower/upper triangular by construction (initially and at end) + U = np.diag(_d, 0) + np.diag(_du, 1) + np.diag(du2, 2) + L = np.eye(n, dtype=dtype) + + for i, m in enumerate(_dl): + # L is given in a factored form. + # See + # www.hpcavf.uclan.ac.uk/softwaredoc/sgi_scsl_html/sgi_html/ch03.html + piv = ipiv[i] - 1 + # right multiply by permutation matrix + L[:, [i, piv]] = L[:, [piv, i]] + # right multiply by Li, rank-one modification of identity + L[:, i] += L[:, i+1]*m + + # one last permutation + i, piv = -1, ipiv[-1] - 1 + # right multiply by final permutation matrix + L[:, [i, piv]] = L[:, [piv, i]] + + # check that the outputs of ?gttrf define an LU decomposition of A + assert_allclose(A, L @ U, atol=atol) + + b_cpy = b.copy() + x_gttrs, info = gttrs(_dl, _d, _du, du2, ipiv, b) + # test that the inputs of ?gttrs are unmodified + assert_array_equal(b, b_cpy) + # test that the result of ?gttrs matches the expected input + assert_allclose(x, x_gttrs, atol=atol) + + # test that ?gttrf and ?gttrs work with transposal options + if dtype in REAL_DTYPES: + trans = "T" + b_trans = A.T @ x + else: + trans = "C" + b_trans = A.conj().T @ x + + x_gttrs, info = gttrs(_dl, _d, _du, du2, ipiv, b_trans, trans=trans) + assert_allclose(x, x_gttrs, atol=atol) + + # test that ValueError is raised with incompatible matrix shapes + with assert_raises(ValueError): + gttrf(dl[:-1], d, du) + with assert_raises(ValueError): + gttrf(dl, d[:-1], du) + with assert_raises(ValueError): + gttrf(dl, d, du[:-1]) + + # test that matrix of size n=2 raises exception + with assert_raises(ValueError): + gttrf(dl[0], d[:1], du[0]) + + # test that singular (row of all zeroes) matrix fails via info + du[0] = 0 + d[0] = 0 + __dl, __d, __du, _du2, _ipiv, _info = gttrf(dl, d, du) + np.testing.assert_(__d[info - 1] == 0, (f"?gttrf: _d[info-1] is {__d[info - 1]}," + " not the illegal value :0.")) + + +@pytest.mark.parametrize("du, d, dl, du_exp, d_exp, du2_exp, ipiv_exp, b, x", + [(np.array([2.1, -1.0, 1.9, 8.0]), + np.array([3.0, 2.3, -5.0, -.9, 7.1]), + np.array([3.4, 3.6, 7.0, -6.0]), + np.array([2.3, -5, -.9, 7.1]), + np.array([3.4, 3.6, 7, -6, -1.015373]), + np.array([-1, 1.9, 8]), + np.array([2, 3, 4, 5, 5]), + np.array([[2.7, 6.6], + [-0.5, 10.8], + [2.6, -3.2], + [0.6, -11.2], + [2.7, 19.1] + ]), + np.array([[-4, 5], + [7, -4], + [3, -3], + [-4, -2], + [-3, 1]])), + ( + np.array([2 - 1j, 2 + 1j, -1 + 1j, 1 - 1j]), + np.array([-1.3 + 1.3j, -1.3 + 1.3j, + -1.3 + 3.3j, - .3 + 4.3j, + -3.3 + 1.3j]), + np.array([1 - 2j, 1 + 1j, 2 - 3j, 1 + 1j]), + # du exp + np.array([-1.3 + 1.3j, -1.3 + 3.3j, + -0.3 + 4.3j, -3.3 + 1.3j]), + np.array([1 - 2j, 1 + 1j, 2 - 3j, 1 + 1j, + -1.3399 + 0.2875j]), + np.array([2 + 1j, -1 + 1j, 1 - 1j]), + np.array([2, 3, 4, 5, 5]), + np.array([[2.4 - 5j, 2.7 + 6.9j], + [3.4 + 18.2j, - 6.9 - 5.3j], + [-14.7 + 9.7j, - 6 - .6j], + [31.9 - 7.7j, -3.9 + 9.3j], + [-1 + 1.6j, -3 + 12.2j]]), + np.array([[1 + 1j, 2 - 1j], + [3 - 1j, 1 + 2j], + [4 + 5j, -1 + 1j], + [-1 - 2j, 2 + 1j], + [1 - 1j, 2 - 2j]]) + )]) +def test_gttrf_gttrs_NAG_f07cdf_f07cef_f07crf_f07csf(du, d, dl, du_exp, d_exp, + du2_exp, ipiv_exp, b, x): + # test to assure that wrapper is consistent with NAG Library Manual Mark 26 + # example problems: f07cdf and f07cef (real) + # examples: f07crf and f07csf (complex) + # (Links may expire, so search for "NAG Library Manual Mark 26" online) + + gttrf, gttrs = get_lapack_funcs(('gttrf', "gttrs"), (du[0], du[0])) + + _dl, _d, _du, du2, ipiv, info = gttrf(dl, d, du) + assert_allclose(du2, du2_exp) + assert_allclose(_du, du_exp) + assert_allclose(_d, d_exp, atol=1e-4) # NAG examples provide 4 decimals. + assert_allclose(ipiv, ipiv_exp) + + x_gttrs, info = gttrs(_dl, _d, _du, du2, ipiv, b) + + assert_allclose(x_gttrs, x) + + +@pytest.mark.parametrize('dtype', DTYPES) +@pytest.mark.parametrize('norm', ['1', 'I', 'O']) +@pytest.mark.parametrize('n', [3, 10]) +def test_gtcon(dtype, norm, n): + rng = np.random.default_rng(23498324) + + d = rng.random(n) + rng.random(n)*1j + dl = rng.random(n - 1) + rng.random(n - 1)*1j + du = rng.random(n - 1) + rng.random(n - 1)*1j + A = np.diag(d) + np.diag(dl, -1) + np.diag(du, 1) + if np.issubdtype(dtype, np.floating): + A, d, dl, du = A.real, d.real, dl.real, du.real + A, d, dl, du = A.astype(dtype), d.astype(dtype), dl.astype(dtype), du.astype(dtype) + + anorm = np.abs(A).sum(axis=0).max() + + gttrf, gtcon = get_lapack_funcs(('gttrf', 'gtcon'), (A,)) + dl, d, du, du2, ipiv, info = gttrf(dl, d, du) + res, _ = gtcon(dl, d, du, du2, ipiv, anorm, norm=norm) + + gecon, getrf = get_lapack_funcs(('gecon', 'getrf'), (A,)) + lu, ipvt, info = getrf(A) + ref, _ = gecon(lu, anorm, norm=norm) + + rtol = np.finfo(dtype).eps**0.75 + assert_allclose(res, ref, rtol=rtol) + + +@pytest.mark.parametrize('dtype', DTYPES) +@pytest.mark.parametrize('shape', [(3, 7), (7, 3), (2**18, 2**18)]) +def test_geqrfp_lwork(dtype, shape): + geqrfp_lwork = get_lapack_funcs(('geqrfp_lwork'), dtype=dtype) + m, n = shape + lwork, info = geqrfp_lwork(m=m, n=n) + assert_equal(info, 0) + + +@pytest.mark.parametrize("ddtype,dtype", + zip(REAL_DTYPES + REAL_DTYPES, DTYPES)) +def test_pttrf_pttrs(ddtype, dtype): + rng = np.random.RandomState(42) + # set test tolerance appropriate for dtype + atol = 100*np.finfo(dtype).eps + # n is the length diagonal of A + n = 10 + # create diagonals according to size and dtype + + # diagonal d should always be real. + # add 4 to d so it will be dominant for all dtypes + d = generate_random_dtype_array((n,), ddtype, rng) + 4 + # diagonal e may be real or complex. + e = generate_random_dtype_array((n-1,), dtype, rng) + + # assemble diagonals together into matrix + A = np.diag(d) + np.diag(e, -1) + np.diag(np.conj(e), 1) + # store a copy of diagonals to later verify + diag_cpy = [d.copy(), e.copy()] + + pttrf = get_lapack_funcs('pttrf', dtype=dtype) + + _d, _e, info = pttrf(d, e) + # test to assure that the inputs of ?pttrf are unmodified + assert_array_equal(d, diag_cpy[0]) + assert_array_equal(e, diag_cpy[1]) + assert_equal(info, 0, err_msg=f"pttrf: info = {info}, should be 0") + + # test that the factors from pttrf can be recombined to make A + L = np.diag(_e, -1) + np.diag(np.ones(n)) + D = np.diag(_d) + + assert_allclose(A, L@D@L.conjugate().T, atol=atol) + + # generate random solution x + x = generate_random_dtype_array((n,), dtype, rng) + # determine accompanying b to get soln x + b = A@x + + # determine _x from pttrs + pttrs = get_lapack_funcs('pttrs', dtype=dtype) + _x, info = pttrs(_d, _e.conj(), b) + assert_equal(info, 0, err_msg=f"pttrs: info = {info}, should be 0") + + # test that _x from pttrs matches the expected x + assert_allclose(x, _x, atol=atol) + + +@pytest.mark.parametrize("ddtype,dtype", + zip(REAL_DTYPES + REAL_DTYPES, DTYPES)) +def test_pttrf_pttrs_errors_incompatible_shape(ddtype, dtype): + n = 10 + rng = np.random.RandomState(1234) + pttrf = get_lapack_funcs('pttrf', dtype=dtype) + d = generate_random_dtype_array((n,), ddtype, rng) + 2 + e = generate_random_dtype_array((n-1,), dtype, rng) + # test that ValueError is raised with incompatible matrix shapes + assert_raises(ValueError, pttrf, d[:-1], e) + assert_raises(ValueError, pttrf, d, e[:-1]) + + +@pytest.mark.parametrize("ddtype,dtype", + zip(REAL_DTYPES + REAL_DTYPES, DTYPES)) +def test_pttrf_pttrs_errors_singular_nonSPD(ddtype, dtype): + n = 10 + rng = np.random.RandomState(42) + pttrf = get_lapack_funcs('pttrf', dtype=dtype) + d = generate_random_dtype_array((n,), ddtype, rng) + 2 + e = generate_random_dtype_array((n-1,), dtype, rng) + # test that singular (row of all zeroes) matrix fails via info + d[0] = 0 + e[0] = 0 + _d, _e, info = pttrf(d, e) + assert_equal(_d[info - 1], 0, + f"?pttrf: _d[info-1] is {_d[info - 1]}, not the illegal value :0.") + + # test with non-spd matrix + d = generate_random_dtype_array((n,), ddtype, rng) + _d, _e, info = pttrf(d, e) + assert_(info != 0, "?pttrf should fail with non-spd matrix, but didn't") + + +@pytest.mark.parametrize(("d, e, d_expect, e_expect, b, x_expect"), [ + (np.array([4, 10, 29, 25, 5]), + np.array([-2, -6, 15, 8]), + np.array([4, 9, 25, 16, 1]), + np.array([-.5, -.6667, .6, .5]), + np.array([[6, 10], [9, 4], [2, 9], [14, 65], + [7, 23]]), + np.array([[2.5, 2], [2, -1], [1, -3], [-1, 6], + [3, -5]]) + ), ( + np.array([16, 41, 46, 21]), + np.array([16 + 16j, 18 - 9j, 1 - 4j]), + np.array([16, 9, 1, 4]), + np.array([1+1j, 2-1j, 1-4j]), + np.array([[64+16j, -16-32j], [93+62j, 61-66j], + [78-80j, 71-74j], [14-27j, 35+15j]]), + np.array([[2+1j, -3-2j], [1+1j, 1+1j], [1-2j, 1-2j], + [1-1j, 2+1j]]) + )]) +def test_pttrf_pttrs_NAG(d, e, d_expect, e_expect, b, x_expect): + # test to assure that wrapper is consistent with NAG Manual Mark 26 + # example problems: f07jdf and f07jef (real) + # examples: f07jrf and f07csf (complex) + # NAG examples provide 4 decimals. + # (Links expire, so please search for "NAG Library Manual Mark 26" online) + + atol = 1e-4 + pttrf = get_lapack_funcs('pttrf', dtype=e[0]) + _d, _e, info = pttrf(d, e) + assert_allclose(_d, d_expect, atol=atol) + assert_allclose(_e, e_expect, atol=atol) + + pttrs = get_lapack_funcs('pttrs', dtype=e[0]) + _x, info = pttrs(_d, _e.conj(), b) + assert_allclose(_x, x_expect, atol=atol) + + # also test option `lower` + if e.dtype in COMPLEX_DTYPES: + _x, info = pttrs(_d, _e, b, lower=1) + assert_allclose(_x, x_expect, atol=atol) + + +def pteqr_get_d_e_A_z(dtype, realtype, n, compute_z): + # used by ?pteqr tests to build parameters + # returns tuple of (d, e, A, z) + rng = np.random.RandomState(42) + if compute_z == 1: + # build Hermitian A from Q**T * tri * Q = A by creating Q and tri + A_eig = generate_random_dtype_array((n, n), dtype, rng) + A_eig = A_eig + np.diag(np.zeros(n) + 4*n) + A_eig = (A_eig + A_eig.conj().T) / 2 + # obtain right eigenvectors (orthogonal) + vr = eigh(A_eig)[1] + # create tridiagonal matrix + d = generate_random_dtype_array((n,), realtype, rng) + 4 + e = generate_random_dtype_array((n-1,), realtype, rng) + tri = np.diag(d) + np.diag(e, 1) + np.diag(e, -1) + # Build A using these factors that sytrd would: (Q**T * tri * Q = A) + A = vr @ tri @ vr.conj().T + # vr is orthogonal + z = vr + + else: + # d and e are always real per lapack docs. + d = generate_random_dtype_array((n,), realtype, rng) + e = generate_random_dtype_array((n-1,), realtype, rng) + + # make SPD + d = d + 4 + A = np.diag(d) + np.diag(e, 1) + np.diag(e, -1) + z = np.diag(d) + np.diag(e, -1) + np.diag(e, 1) + return (d, e, A, z) + + +@pytest.mark.parametrize("dtype,realtype", + zip(DTYPES, REAL_DTYPES + REAL_DTYPES)) +@pytest.mark.parametrize("compute_z", range(3)) +def test_pteqr(dtype, realtype, compute_z): + ''' + Tests the ?pteqr lapack routine for all dtypes and compute_z parameters. + It generates random SPD matrix diagonals d and e, and then confirms + correct eigenvalues with scipy.linalg.eig. With applicable compute_z=2 it + tests that z can reform A. + ''' + seed(42) + atol = 1000*np.finfo(dtype).eps + pteqr = get_lapack_funcs(('pteqr'), dtype=dtype) + + n = 10 + + d, e, A, z = pteqr_get_d_e_A_z(dtype, realtype, n, compute_z) + + d_pteqr, e_pteqr, z_pteqr, info = pteqr(d=d, e=e, z=z, compute_z=compute_z) + assert_equal(info, 0, f"info = {info}, should be 0.") + + # compare the routine's eigenvalues with scipy.linalg.eig's. + assert_allclose(np.sort(eigh(A)[0]), np.sort(d_pteqr), atol=atol) + + if compute_z: + # verify z_pteqr as orthogonal + assert_allclose(z_pteqr @ np.conj(z_pteqr).T, np.identity(n), + atol=atol) + # verify that z_pteqr recombines to A + assert_allclose(z_pteqr @ np.diag(d_pteqr) @ np.conj(z_pteqr).T, + A, atol=atol) + + +@pytest.mark.parametrize("dtype,realtype", + zip(DTYPES, REAL_DTYPES + REAL_DTYPES)) +@pytest.mark.parametrize("compute_z", range(3)) +def test_pteqr_error_non_spd(dtype, realtype, compute_z): + seed(42) + pteqr = get_lapack_funcs(('pteqr'), dtype=dtype) + + n = 10 + d, e, A, z = pteqr_get_d_e_A_z(dtype, realtype, n, compute_z) + + # test with non-spd matrix + d_pteqr, e_pteqr, z_pteqr, info = pteqr(d - 4, e, z=z, compute_z=compute_z) + assert info > 0 + + +@pytest.mark.parametrize("dtype,realtype", + zip(DTYPES, REAL_DTYPES + REAL_DTYPES)) +@pytest.mark.parametrize("compute_z", range(3)) +def test_pteqr_raise_error_wrong_shape(dtype, realtype, compute_z): + seed(42) + pteqr = get_lapack_funcs(('pteqr'), dtype=dtype) + n = 10 + d, e, A, z = pteqr_get_d_e_A_z(dtype, realtype, n, compute_z) + # test with incorrect/incompatible array sizes + assert_raises(ValueError, pteqr, d[:-1], e, z=z, compute_z=compute_z) + assert_raises(ValueError, pteqr, d, e[:-1], z=z, compute_z=compute_z) + if compute_z: + assert_raises(ValueError, pteqr, d, e, z=z[:-1], compute_z=compute_z) + + +@pytest.mark.parametrize("dtype,realtype", + zip(DTYPES, REAL_DTYPES + REAL_DTYPES)) +@pytest.mark.parametrize("compute_z", range(3)) +def test_pteqr_error_singular(dtype, realtype, compute_z): + seed(42) + pteqr = get_lapack_funcs(('pteqr'), dtype=dtype) + n = 10 + d, e, A, z = pteqr_get_d_e_A_z(dtype, realtype, n, compute_z) + # test with singular matrix + d[0] = 0 + e[0] = 0 + d_pteqr, e_pteqr, z_pteqr, info = pteqr(d, e, z=z, compute_z=compute_z) + assert info > 0 + + +@pytest.mark.parametrize("compute_z,d,e,d_expect,z_expect", + [(2, # "I" + np.array([4.16, 5.25, 1.09, .62]), + np.array([3.17, -.97, .55]), + np.array([8.0023, 1.9926, 1.0014, 0.1237]), + np.array([[0.6326, 0.6245, -0.4191, 0.1847], + [0.7668, -0.4270, 0.4176, -0.2352], + [-0.1082, 0.6071, 0.4594, -0.6393], + [-0.0081, 0.2432, 0.6625, 0.7084]])), + ]) +def test_pteqr_NAG_f08jgf(compute_z, d, e, d_expect, z_expect): + ''' + Implements real (f08jgf) example from NAG Manual Mark 26. + Tests for correct outputs. + ''' + # the NAG manual has 4 decimals accuracy + atol = 1e-4 + pteqr = get_lapack_funcs(('pteqr'), dtype=d.dtype) + + z = np.diag(d) + np.diag(e, 1) + np.diag(e, -1) + _d, _e, _z, info = pteqr(d=d, e=e, z=z, compute_z=compute_z) + assert_allclose(_d, d_expect, atol=atol) + assert_allclose(np.abs(_z), np.abs(z_expect), atol=atol) + + +@pytest.mark.parametrize('dtype', DTYPES) +@pytest.mark.parametrize('matrix_size', [(3, 4), (7, 6), (6, 6)]) +def test_geqrfp(dtype, matrix_size): + # Tests for all dytpes, tall, wide, and square matrices. + # Using the routine with random matrix A, Q and R are obtained and then + # tested such that R is upper triangular and non-negative on the diagonal, + # and Q is an orthogonal matrix. Verifies that A=Q@R. It also + # tests against a matrix that for which the linalg.qr method returns + # negative diagonals, and for error messaging. + + # set test tolerance appropriate for dtype + rng = np.random.RandomState(42) + rtol = 250*np.finfo(dtype).eps + atol = 100*np.finfo(dtype).eps + # get appropriate ?geqrfp for dtype + geqrfp = get_lapack_funcs(('geqrfp'), dtype=dtype) + gqr = get_lapack_funcs(("orgqr"), dtype=dtype) + + m, n = matrix_size + + # create random matrix of dimensions m x n + A = generate_random_dtype_array((m, n), dtype=dtype, rng=rng) + # create qr matrix using geqrfp + qr_A, tau, info = geqrfp(A) + + # obtain r from the upper triangular area + r = np.triu(qr_A) + + # obtain q from the orgqr lapack routine + # based on linalg.qr's extraction strategy of q with orgqr + + if m > n: + # this adds an extra column to the end of qr_A + # let qqr be an empty m x m matrix + qqr = np.zeros((m, m), dtype=dtype) + # set first n columns of qqr to qr_A + qqr[:, :n] = qr_A + # determine q from this qqr + # note that m is a sufficient for lwork based on LAPACK documentation + q = gqr(qqr, tau=tau, lwork=m)[0] + else: + q = gqr(qr_A[:, :m], tau=tau, lwork=m)[0] + + # test that q and r still make A + assert_allclose(q@r, A, rtol=rtol) + # ensure that q is orthogonal (that q @ transposed q is the identity) + assert_allclose(np.eye(q.shape[0]), q@(q.conj().T), rtol=rtol, + atol=atol) + # ensure r is upper tri by comparing original r to r as upper triangular + assert_allclose(r, np.triu(r), rtol=rtol) + # make sure diagonals of r are positive for this random solution + assert_(np.all(np.diag(r) > np.zeros(len(np.diag(r))))) + # ensure that info is zero for this success + assert_(info == 0) + + # test that this routine gives r diagonals that are positive for a + # matrix that returns negatives in the diagonal with scipy.linalg.rq + A_negative = generate_random_dtype_array((n, m), dtype=dtype, rng=rng) * -1 + r_rq_neg, q_rq_neg = qr(A_negative) + rq_A_neg, tau_neg, info_neg = geqrfp(A_negative) + # assert that any of the entries on the diagonal from linalg.qr + # are negative and that all of geqrfp are positive. + assert_(np.any(np.diag(r_rq_neg) < 0) and + np.all(np.diag(r) > 0)) + + +def test_geqrfp_errors_with_empty_array(): + # check that empty array raises good error message + A_empty = np.array([]) + geqrfp = get_lapack_funcs('geqrfp', dtype=A_empty.dtype) + assert_raises(Exception, geqrfp, A_empty) + + +@pytest.mark.parametrize("driver", ['ev', 'evd', 'evr', 'evx']) +@pytest.mark.parametrize("pfx", ['sy', 'he']) +def test_standard_eigh_lworks(pfx, driver): + n = 1200 # Some sufficiently big arbitrary number + dtype = REAL_DTYPES if pfx == 'sy' else COMPLEX_DTYPES + sc_dlw = get_lapack_funcs(pfx+driver+'_lwork', dtype=dtype[0]) + dz_dlw = get_lapack_funcs(pfx+driver+'_lwork', dtype=dtype[1]) + try: + _compute_lwork(sc_dlw, n, lower=1) + _compute_lwork(dz_dlw, n, lower=1) + except Exception as e: + pytest.fail(f"{pfx+driver}_lwork raised unexpected exception: {e}") + + +@pytest.mark.parametrize("driver", ['gv', 'gvx']) +@pytest.mark.parametrize("pfx", ['sy', 'he']) +def test_generalized_eigh_lworks(pfx, driver): + n = 1200 # Some sufficiently big arbitrary number + dtype = REAL_DTYPES if pfx == 'sy' else COMPLEX_DTYPES + sc_dlw = get_lapack_funcs(pfx+driver+'_lwork', dtype=dtype[0]) + dz_dlw = get_lapack_funcs(pfx+driver+'_lwork', dtype=dtype[1]) + # Shouldn't raise any exceptions + try: + _compute_lwork(sc_dlw, n, uplo="L") + _compute_lwork(dz_dlw, n, uplo="L") + except Exception as e: + pytest.fail(f"{pfx+driver}_lwork raised unexpected exception: {e}") + + +@pytest.mark.parametrize("dtype_", DTYPES) +@pytest.mark.parametrize("m", [1, 10, 100, 1000]) +def test_orcsd_uncsd_lwork(dtype_, m): + seed(1234) + p = randint(0, m) + q = m - p + pfx = 'or' if dtype_ in REAL_DTYPES else 'un' + dlw = pfx + 'csd_lwork' + lw = get_lapack_funcs(dlw, dtype=dtype_) + lwval = _compute_lwork(lw, m, p, q) + lwval = lwval if pfx == 'un' else (lwval,) + assert all([x > 0 for x in lwval]) + + +@pytest.mark.parametrize("dtype_", DTYPES) +def test_orcsd_uncsd(dtype_): + m, p, q = 250, 80, 170 + + pfx = 'or' if dtype_ in REAL_DTYPES else 'un' + X = ortho_group.rvs(m) if pfx == 'or' else unitary_group.rvs(m) + + drv, dlw = get_lapack_funcs((pfx + 'csd', pfx + 'csd_lwork'), dtype=dtype_) + lwval = _compute_lwork(dlw, m, p, q) + lwvals = {'lwork': lwval} if pfx == 'or' else dict(zip(['lwork', + 'lrwork'], lwval)) + + cs11, cs12, cs21, cs22, theta, u1, u2, v1t, v2t, info =\ + drv(X[:p, :q], X[:p, q:], X[p:, :q], X[p:, q:], **lwvals) + + assert info == 0 + + U = block_diag(u1, u2) + VH = block_diag(v1t, v2t) + r = min(min(p, q), min(m-p, m-q)) + n11 = min(p, q) - r + n12 = min(p, m-q) - r + n21 = min(m-p, q) - r + n22 = min(m-p, m-q) - r + + S = np.zeros((m, m), dtype=dtype_) + one = dtype_(1.) + for i in range(n11): + S[i, i] = one + for i in range(n22): + S[p+i, q+i] = one + for i in range(n12): + S[i+n11+r, i+n11+r+n21+n22+r] = -one + for i in range(n21): + S[p+n22+r+i, n11+r+i] = one + + for i in range(r): + S[i+n11, i+n11] = np.cos(theta[i]) + S[p+n22+i, i+r+n21+n22] = np.cos(theta[i]) + + S[i+n11, i+n11+n21+n22+r] = -np.sin(theta[i]) + S[p+n22+i, i+n11] = np.sin(theta[i]) + + Xc = U @ S @ VH + assert_allclose(X, Xc, rtol=0., atol=1e4*np.finfo(dtype_).eps) + + +@pytest.mark.parametrize("dtype", DTYPES) +@pytest.mark.parametrize("trans_bool", [False, True]) +@pytest.mark.parametrize("fact", ["F", "N"]) +def test_gtsvx(dtype, trans_bool, fact): + """ + These tests uses ?gtsvx to solve a random Ax=b system for each dtype. + It tests that the outputs define an LU matrix, that inputs are unmodified, + transposal options, incompatible shapes, singular matrices, and + singular factorizations. It parametrizes DTYPES and the 'fact' value along + with the fact related inputs. + """ + rng = np.random.RandomState(42) + # set test tolerance appropriate for dtype + atol = 100 * np.finfo(dtype).eps + # obtain routine + gtsvx, gttrf = get_lapack_funcs(('gtsvx', 'gttrf'), dtype=dtype) + # Generate random tridiagonal matrix A + n = 10 + dl = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng) + d = generate_random_dtype_array((n,), dtype=dtype, rng=rng) + du = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng) + A = np.diag(dl, -1) + np.diag(d) + np.diag(du, 1) + # generate random solution x + x = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng) + # create b from x for equation Ax=b + trans = ("T" if dtype in REAL_DTYPES else "C") if trans_bool else "N" + b = (A.conj().T if trans_bool else A) @ x + + # store a copy of the inputs to check they haven't been modified later + inputs_cpy = [dl.copy(), d.copy(), du.copy(), b.copy()] + + # set these to None if fact = 'N', or the output of gttrf is fact = 'F' + dlf_, df_, duf_, du2f_, ipiv_, info_ = \ + gttrf(dl, d, du) if fact == 'F' else [None]*6 + + gtsvx_out = gtsvx(dl, d, du, b, fact=fact, trans=trans, dlf=dlf_, df=df_, + duf=duf_, du2=du2f_, ipiv=ipiv_) + dlf, df, duf, du2f, ipiv, x_soln, rcond, ferr, berr, info = gtsvx_out + assert_(info == 0, f"?gtsvx info = {info}, should be zero") + + # assure that inputs are unmodified + assert_array_equal(dl, inputs_cpy[0]) + assert_array_equal(d, inputs_cpy[1]) + assert_array_equal(du, inputs_cpy[2]) + assert_array_equal(b, inputs_cpy[3]) + + # test that x_soln matches the expected x + assert_allclose(x, x_soln, atol=atol) + + # assert that the outputs are of correct type or shape + # rcond should be a scalar + assert_(hasattr(rcond, "__len__") is not True, + f"rcond should be scalar but is {rcond}") + # ferr should be length of # of cols in x + assert_(ferr.shape[0] == b.shape[1], (f"ferr.shape is {ferr.shape[0]} but should" + f" be {b.shape[1]}")) + # berr should be length of # of cols in x + assert_(berr.shape[0] == b.shape[1], (f"berr.shape is {berr.shape[0]} but should" + f" be {b.shape[1]}")) + + +@pytest.mark.parametrize("dtype", DTYPES) +@pytest.mark.parametrize("trans_bool", [0, 1]) +@pytest.mark.parametrize("fact", ["F", "N"]) +def test_gtsvx_error_singular(dtype, trans_bool, fact): + rng = np.random.RandomState(42) + # obtain routine + gtsvx, gttrf = get_lapack_funcs(('gtsvx', 'gttrf'), dtype=dtype) + # Generate random tridiagonal matrix A + n = 10 + dl = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng) + d = generate_random_dtype_array((n,), dtype=dtype, rng=rng) + du = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng) + A = np.diag(dl, -1) + np.diag(d) + np.diag(du, 1) + # generate random solution x + x = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng) + # create b from x for equation Ax=b + trans = "T" if dtype in REAL_DTYPES else "C" + b = (A.conj().T if trans_bool else A) @ x + + # set these to None if fact = 'N', or the output of gttrf is fact = 'F' + dlf_, df_, duf_, du2f_, ipiv_, info_ = \ + gttrf(dl, d, du) if fact == 'F' else [None]*6 + + gtsvx_out = gtsvx(dl, d, du, b, fact=fact, trans=trans, dlf=dlf_, df=df_, + duf=duf_, du2=du2f_, ipiv=ipiv_) + dlf, df, duf, du2f, ipiv, x_soln, rcond, ferr, berr, info = gtsvx_out + # test with singular matrix + # no need to test inputs with fact "F" since ?gttrf already does. + if fact == "N": + # Construct a singular example manually + d[-1] = 0 + dl[-1] = 0 + # solve using routine + gtsvx_out = gtsvx(dl, d, du, b) + dlf, df, duf, du2f, ipiv, x_soln, rcond, ferr, berr, info = gtsvx_out + # test for the singular matrix. + assert info > 0, "info should be > 0 for singular matrix" + + elif fact == 'F': + # assuming that a singular factorization is input + df_[-1] = 0 + duf_[-1] = 0 + du2f_[-1] = 0 + + gtsvx_out = gtsvx(dl, d, du, b, fact=fact, dlf=dlf_, df=df_, duf=duf_, + du2=du2f_, ipiv=ipiv_) + dlf, df, duf, du2f, ipiv, x_soln, rcond, ferr, berr, info = gtsvx_out + # info should not be zero and should provide index of illegal value + assert info > 0, "info should be > 0 for singular matrix" + + +@pytest.mark.parametrize("dtype", DTYPES*2) +@pytest.mark.parametrize("trans_bool", [False, True]) +@pytest.mark.parametrize("fact", ["F", "N"]) +def test_gtsvx_error_incompatible_size(dtype, trans_bool, fact): + rng = np.random.RandomState(42) + # obtain routine + gtsvx, gttrf = get_lapack_funcs(('gtsvx', 'gttrf'), dtype=dtype) + # Generate random tridiagonal matrix A + n = 10 + dl = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng) + d = generate_random_dtype_array((n,), dtype=dtype, rng=rng) + du = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng) + A = np.diag(dl, -1) + np.diag(d) + np.diag(du, 1) + # generate random solution x + x = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng) + # create b from x for equation Ax=b + trans = "T" if dtype in REAL_DTYPES else "C" + b = (A.conj().T if trans_bool else A) @ x + + # set these to None if fact = 'N', or the output of gttrf is fact = 'F' + dlf_, df_, duf_, du2f_, ipiv_, info_ = \ + gttrf(dl, d, du) if fact == 'F' else [None]*6 + + if fact == "N": + assert_raises(ValueError, gtsvx, dl[:-1], d, du, b, + fact=fact, trans=trans, dlf=dlf_, df=df_, + duf=duf_, du2=du2f_, ipiv=ipiv_) + assert_raises(ValueError, gtsvx, dl, d[:-1], du, b, + fact=fact, trans=trans, dlf=dlf_, df=df_, + duf=duf_, du2=du2f_, ipiv=ipiv_) + assert_raises(ValueError, gtsvx, dl, d, du[:-1], b, + fact=fact, trans=trans, dlf=dlf_, df=df_, + duf=duf_, du2=du2f_, ipiv=ipiv_) + assert_raises(Exception, gtsvx, dl, d, du, b[:-1], + fact=fact, trans=trans, dlf=dlf_, df=df_, + duf=duf_, du2=du2f_, ipiv=ipiv_) + else: + assert_raises(ValueError, gtsvx, dl, d, du, b, + fact=fact, trans=trans, dlf=dlf_[:-1], df=df_, + duf=duf_, du2=du2f_, ipiv=ipiv_) + assert_raises(ValueError, gtsvx, dl, d, du, b, + fact=fact, trans=trans, dlf=dlf_, df=df_[:-1], + duf=duf_, du2=du2f_, ipiv=ipiv_) + assert_raises(ValueError, gtsvx, dl, d, du, b, + fact=fact, trans=trans, dlf=dlf_, df=df_, + duf=duf_[:-1], du2=du2f_, ipiv=ipiv_) + assert_raises(ValueError, gtsvx, dl, d, du, b, + fact=fact, trans=trans, dlf=dlf_, df=df_, + duf=duf_, du2=du2f_[:-1], ipiv=ipiv_) + + +@pytest.mark.parametrize("du,d,dl,b,x", + [(np.array([2.1, -1.0, 1.9, 8.0]), + np.array([3.0, 2.3, -5.0, -0.9, 7.1]), + np.array([3.4, 3.6, 7.0, -6.0]), + np.array([[2.7, 6.6], [-.5, 10.8], [2.6, -3.2], + [.6, -11.2], [2.7, 19.1]]), + np.array([[-4, 5], [7, -4], [3, -3], [-4, -2], + [-3, 1]])), + (np.array([2 - 1j, 2 + 1j, -1 + 1j, 1 - 1j]), + np.array([-1.3 + 1.3j, -1.3 + 1.3j, -1.3 + 3.3j, + -.3 + 4.3j, -3.3 + 1.3j]), + np.array([1 - 2j, 1 + 1j, 2 - 3j, 1 + 1j]), + np.array([[2.4 - 5j, 2.7 + 6.9j], + [3.4 + 18.2j, -6.9 - 5.3j], + [-14.7 + 9.7j, -6 - .6j], + [31.9 - 7.7j, -3.9 + 9.3j], + [-1 + 1.6j, -3 + 12.2j]]), + np.array([[1 + 1j, 2 - 1j], [3 - 1j, 1 + 2j], + [4 + 5j, -1 + 1j], [-1 - 2j, 2 + 1j], + [1 - 1j, 2 - 2j]]))]) +def test_gtsvx_NAG(du, d, dl, b, x): + # Test to ensure wrapper is consistent with NAG Manual Mark 26 + # example problems: real (f07cbf) and complex (f07cpf) + gtsvx = get_lapack_funcs('gtsvx', dtype=d.dtype) + + gtsvx_out = gtsvx(dl, d, du, b) + dlf, df, duf, du2f, ipiv, x_soln, rcond, ferr, berr, info = gtsvx_out + + assert_array_almost_equal(x, x_soln) + + +@pytest.mark.parametrize("dtype,realtype", zip(DTYPES, REAL_DTYPES + + REAL_DTYPES)) +@pytest.mark.parametrize("fact,df_de_lambda", + [("F", + lambda d, e: get_lapack_funcs('pttrf', + dtype=e.dtype)(d, e)), + ("N", lambda d, e: (None, None, None))]) +def test_ptsvx(dtype, realtype, fact, df_de_lambda): + ''' + This tests the ?ptsvx lapack routine wrapper to solve a random system + Ax = b for all dtypes and input variations. Tests for: unmodified + input parameters, fact options, incompatible matrix shapes raise an error, + and singular matrices return info of illegal value. + ''' + rng = np.random.RandomState(42) + # set test tolerance appropriate for dtype + atol = 100 * np.finfo(dtype).eps + ptsvx = get_lapack_funcs('ptsvx', dtype=dtype) + n = 5 + # create diagonals according to size and dtype + d = generate_random_dtype_array((n,), realtype, rng) + 4 + e = generate_random_dtype_array((n-1,), dtype, rng) + A = np.diag(d) + np.diag(e, -1) + np.diag(np.conj(e), 1) + x_soln = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng) + b = A @ x_soln + + # use lambda to determine what df, ef are + df, ef, info = df_de_lambda(d, e) + + # create copy to later test that they are unmodified + diag_cpy = [d.copy(), e.copy(), b.copy()] + + # solve using routine + df, ef, x, rcond, ferr, berr, info = ptsvx(d, e, b, fact=fact, + df=df, ef=ef) + # d, e, and b should be unmodified + assert_array_equal(d, diag_cpy[0]) + assert_array_equal(e, diag_cpy[1]) + assert_array_equal(b, diag_cpy[2]) + assert_(info == 0, f"info should be 0 but is {info}.") + assert_array_almost_equal(x_soln, x) + + # test that the factors from ptsvx can be recombined to make A + L = np.diag(ef, -1) + np.diag(np.ones(n)) + D = np.diag(df) + assert_allclose(A, L@D@(np.conj(L).T), atol=atol) + + # assert that the outputs are of correct type or shape + # rcond should be a scalar + assert not hasattr(rcond, "__len__"), \ + f"rcond should be scalar but is {rcond}" + # ferr should be length of # of cols in x + assert_(ferr.shape == (2,), (f"ferr.shape is {ferr.shape} but should be " + "({x_soln.shape[1]},)")) + # berr should be length of # of cols in x + assert_(berr.shape == (2,), (f"berr.shape is {berr.shape} but should be " + "({x_soln.shape[1]},)")) + + +@pytest.mark.parametrize("dtype,realtype", zip(DTYPES, REAL_DTYPES + + REAL_DTYPES)) +@pytest.mark.parametrize("fact,df_de_lambda", + [("F", + lambda d, e: get_lapack_funcs('pttrf', + dtype=e.dtype)(d, e)), + ("N", lambda d, e: (None, None, None))]) +def test_ptsvx_error_raise_errors(dtype, realtype, fact, df_de_lambda): + rng = np.random.RandomState(42) + ptsvx = get_lapack_funcs('ptsvx', dtype=dtype) + n = 5 + # create diagonals according to size and dtype + d = generate_random_dtype_array((n,), realtype, rng) + 4 + e = generate_random_dtype_array((n-1,), dtype, rng) + A = np.diag(d) + np.diag(e, -1) + np.diag(np.conj(e), 1) + x_soln = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng) + b = A @ x_soln + + # use lambda to determine what df, ef are + df, ef, info = df_de_lambda(d, e) + + # test with malformatted array sizes + assert_raises(ValueError, ptsvx, d[:-1], e, b, fact=fact, df=df, ef=ef) + assert_raises(ValueError, ptsvx, d, e[:-1], b, fact=fact, df=df, ef=ef) + assert_raises(Exception, ptsvx, d, e, b[:-1], fact=fact, df=df, ef=ef) + + +@pytest.mark.parametrize("dtype,realtype", zip(DTYPES, REAL_DTYPES + + REAL_DTYPES)) +@pytest.mark.parametrize("fact,df_de_lambda", + [("F", + lambda d, e: get_lapack_funcs('pttrf', + dtype=e.dtype)(d, e)), + ("N", lambda d, e: (None, None, None))]) +def test_ptsvx_non_SPD_singular(dtype, realtype, fact, df_de_lambda): + rng = np.random.RandomState(42) + ptsvx = get_lapack_funcs('ptsvx', dtype=dtype) + n = 5 + # create diagonals according to size and dtype + d = generate_random_dtype_array((n,), realtype, rng) + 4 + e = generate_random_dtype_array((n-1,), dtype, rng) + A = np.diag(d) + np.diag(e, -1) + np.diag(np.conj(e), 1) + x_soln = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng) + b = A @ x_soln + + # use lambda to determine what df, ef are + df, ef, info = df_de_lambda(d, e) + + if fact == "N": + d[3] = 0 + # obtain new df, ef + df, ef, info = df_de_lambda(d, e) + # solve using routine + df, ef, x, rcond, ferr, berr, info = ptsvx(d, e, b) + # test for the singular matrix. + assert info > 0 and info <= n + + # non SPD matrix + d = generate_random_dtype_array((n,), realtype, rng) + df, ef, x, rcond, ferr, berr, info = ptsvx(d, e, b) + assert info > 0 and info <= n + else: + # assuming that someone is using a singular factorization + df, ef, info = df_de_lambda(d, e) + df[0] = 0 + ef[0] = 0 + df, ef, x, rcond, ferr, berr, info = ptsvx(d, e, b, fact=fact, + df=df, ef=ef) + assert info > 0 + + +@pytest.mark.parametrize('d,e,b,x', + [(np.array([4, 10, 29, 25, 5]), + np.array([-2, -6, 15, 8]), + np.array([[6, 10], [9, 4], [2, 9], [14, 65], + [7, 23]]), + np.array([[2.5, 2], [2, -1], [1, -3], + [-1, 6], [3, -5]])), + (np.array([16, 41, 46, 21]), + np.array([16 + 16j, 18 - 9j, 1 - 4j]), + np.array([[64 + 16j, -16 - 32j], + [93 + 62j, 61 - 66j], + [78 - 80j, 71 - 74j], + [14 - 27j, 35 + 15j]]), + np.array([[2 + 1j, -3 - 2j], + [1 + 1j, 1 + 1j], + [1 - 2j, 1 - 2j], + [1 - 1j, 2 + 1j]]))]) +def test_ptsvx_NAG(d, e, b, x): + # test to assure that wrapper is consistent with NAG Manual Mark 26 + # example problems: f07jbf, f07jpf + # (Links expire, so please search for "NAG Library Manual Mark 26" online) + + # obtain routine with correct type based on e.dtype + ptsvx = get_lapack_funcs('ptsvx', dtype=e.dtype) + # solve using routine + df, ef, x_ptsvx, rcond, ferr, berr, info = ptsvx(d, e, b) + # determine ptsvx's solution and x are the same. + assert_array_almost_equal(x, x_ptsvx) + + +@pytest.mark.parametrize('lower', [False, True]) +@pytest.mark.parametrize('dtype', DTYPES) +def test_pptrs_pptri_pptrf_ppsv_ppcon(dtype, lower): + rng = np.random.RandomState(1234) + atol = np.finfo(dtype).eps*100 + # Manual conversion to/from packed format is feasible here. + n, nrhs = 10, 4 + a = generate_random_dtype_array([n, n], dtype=dtype, rng=rng) + b = generate_random_dtype_array([n, nrhs], dtype=dtype, rng=rng) + + a = a.conj().T + a + np.eye(n, dtype=dtype) * dtype(5.) + if lower: + inds = ([x for y in range(n) for x in range(y, n)], + [y for y in range(n) for x in range(y, n)]) + else: + inds = ([x for y in range(1, n+1) for x in range(y)], + [y-1 for y in range(1, n+1) for x in range(y)]) + ap = a[inds] + ppsv, pptrf, pptrs, pptri, ppcon = get_lapack_funcs( + ('ppsv', 'pptrf', 'pptrs', 'pptri', 'ppcon'), + dtype=dtype, + ilp64="preferred") + + ul, info = pptrf(n, ap, lower=lower) + assert_equal(info, 0) + aul = cholesky(a, lower=lower)[inds] + assert_allclose(ul, aul, rtol=0, atol=atol) + + uli, info = pptri(n, ul, lower=lower) + assert_equal(info, 0) + auli = inv(a)[inds] + assert_allclose(uli, auli, rtol=0, atol=atol) + + x, info = pptrs(n, ul, b, lower=lower) + assert_equal(info, 0) + bx = solve(a, b) + assert_allclose(x, bx, rtol=0, atol=atol) + + xv, info = ppsv(n, ap, b, lower=lower) + assert_equal(info, 0) + assert_allclose(xv, bx, rtol=0, atol=atol) + + anorm = np.linalg.norm(a, 1) + rcond, info = ppcon(n, ap, anorm=anorm, lower=lower) + assert_equal(info, 0) + assert_(abs(1/rcond - np.linalg.cond(a, p=1))*rcond < 1) + + +@pytest.mark.parametrize('dtype', DTYPES) +def test_gees_trexc(dtype): + rng = np.random.RandomState(1234) + atol = np.finfo(dtype).eps*100 + + n = 10 + a = generate_random_dtype_array([n, n], dtype=dtype, rng=rng) + + gees, trexc = get_lapack_funcs(('gees', 'trexc'), dtype=dtype) + + result = gees(lambda x: None, a, overwrite_a=False) + assert_equal(result[-1], 0) + + t = result[0] + z = result[-3] + + d2 = t[6, 6] + + if dtype in COMPLEX_DTYPES: + assert_allclose(t, np.triu(t), rtol=0, atol=atol) + + assert_allclose(z @ t @ z.conj().T, a, rtol=0, atol=atol) + + result = trexc(t, z, 7, 1) + assert_equal(result[-1], 0) + + t = result[0] + z = result[-2] + + if dtype in COMPLEX_DTYPES: + assert_allclose(t, np.triu(t), rtol=0, atol=atol) + + assert_allclose(z @ t @ z.conj().T, a, rtol=0, atol=atol) + + assert_allclose(t[0, 0], d2, rtol=0, atol=atol) + + +@pytest.mark.parametrize( + "t, expect, ifst, ilst", + [(np.array([[0.80, -0.11, 0.01, 0.03], + [0.00, -0.10, 0.25, 0.35], + [0.00, -0.65, -0.10, 0.20], + [0.00, 0.00, 0.00, -0.10]]), + np.array([[-0.1000, -0.6463, 0.0874, 0.2010], + [0.2514, -0.1000, 0.0927, 0.3505], + [0.0000, 0.0000, 0.8000, -0.0117], + [0.0000, 0.0000, 0.0000, -0.1000]]), + 2, 1), + (np.array([[-6.00 - 7.00j, 0.36 - 0.36j, -0.19 + 0.48j, 0.88 - 0.25j], + [0.00 + 0.00j, -5.00 + 2.00j, -0.03 - 0.72j, -0.23 + 0.13j], + [0.00 + 0.00j, 0.00 + 0.00j, 8.00 - 1.00j, 0.94 + 0.53j], + [0.00 + 0.00j, 0.00 + 0.00j, 0.00 + 0.00j, 3.00 - 4.00j]]), + np.array([[-5.0000 + 2.0000j, -0.1574 + 0.7143j, + 0.1781 - 0.1913j, 0.3950 + 0.3861j], + [0.0000 + 0.0000j, 8.0000 - 1.0000j, + 1.0742 + 0.1447j, 0.2515 - 0.3397j], + [0.0000 + 0.0000j, 0.0000 + 0.0000j, + 3.0000 - 4.0000j, 0.2264 + 0.8962j], + [0.0000 + 0.0000j, 0.0000 + 0.0000j, + 0.0000 + 0.0000j, -6.0000 - 7.0000j]]), + 1, 4)]) +def test_trexc_NAG(t, ifst, ilst, expect): + """ + This test implements the example found in the NAG manual, + f08qfc, f08qtc, f08qgc, f08quc. + """ + # NAG manual provides accuracy up to 4 decimals + atol = 1e-4 + trexc = get_lapack_funcs('trexc', dtype=t.dtype) + + result = trexc(t, t, ifst, ilst, wantq=0) + assert_equal(result[-1], 0) + + t = result[0] + assert_allclose(expect, t, atol=atol) + + +@pytest.mark.parametrize('dtype', DTYPES) +def test_gges_tgexc(dtype): + rng = np.random.RandomState(1234) + atol = np.finfo(dtype).eps*100 + + n = 10 + a = generate_random_dtype_array([n, n], dtype=dtype, rng=rng) + b = generate_random_dtype_array([n, n], dtype=dtype, rng=rng) + + gges, tgexc = get_lapack_funcs(('gges', 'tgexc'), dtype=dtype) + + result = gges(lambda x: None, a, b, overwrite_a=False, overwrite_b=False) + assert_equal(result[-1], 0) + + s = result[0] + t = result[1] + q = result[-4] + z = result[-3] + + d1 = s[0, 0] / t[0, 0] + d2 = s[6, 6] / t[6, 6] + + if dtype in COMPLEX_DTYPES: + assert_allclose(s, np.triu(s), rtol=0, atol=atol) + assert_allclose(t, np.triu(t), rtol=0, atol=atol) + + assert_allclose(q @ s @ z.conj().T, a, rtol=0, atol=atol) + assert_allclose(q @ t @ z.conj().T, b, rtol=0, atol=atol) + + result = tgexc(s, t, q, z, 7, 1) + assert_equal(result[-1], 0) + + s = result[0] + t = result[1] + q = result[2] + z = result[3] + + if dtype in COMPLEX_DTYPES: + assert_allclose(s, np.triu(s), rtol=0, atol=atol) + assert_allclose(t, np.triu(t), rtol=0, atol=atol) + + assert_allclose(q @ s @ z.conj().T, a, rtol=0, atol=atol) + assert_allclose(q @ t @ z.conj().T, b, rtol=0, atol=atol) + + assert_allclose(s[0, 0] / t[0, 0], d2, rtol=0, atol=atol) + assert_allclose(s[1, 1] / t[1, 1], d1, rtol=0, atol=atol) + + +@pytest.mark.parametrize('dtype', DTYPES) +def test_gees_trsen(dtype): + rng = np.random.RandomState(1234) + atol = np.finfo(dtype).eps*100 + + n = 10 + a = generate_random_dtype_array([n, n], dtype=dtype, rng=rng) + + gees, trsen, trsen_lwork = get_lapack_funcs( + ('gees', 'trsen', 'trsen_lwork'), dtype=dtype) + + result = gees(lambda x: None, a, overwrite_a=False) + assert_equal(result[-1], 0) + + t = result[0] + z = result[-3] + + d2 = t[6, 6] + + if dtype in COMPLEX_DTYPES: + assert_allclose(t, np.triu(t), rtol=0, atol=atol) + + assert_allclose(z @ t @ z.conj().T, a, rtol=0, atol=atol) + + select = np.zeros(n) + select[6] = 1 + + lwork = _compute_lwork(trsen_lwork, select, t) + + if dtype in COMPLEX_DTYPES: + result = trsen(select, t, z, lwork=lwork) + else: + result = trsen(select, t, z, lwork=lwork, liwork=lwork[1]) + assert_equal(result[-1], 0) + + t = result[0] + z = result[1] + + if dtype in COMPLEX_DTYPES: + assert_allclose(t, np.triu(t), rtol=0, atol=atol) + + assert_allclose(z @ t @ z.conj().T, a, rtol=0, atol=atol) + + assert_allclose(t[0, 0], d2, rtol=0, atol=atol) + + +@pytest.mark.parametrize( + "t, q, expect, select, expect_s, expect_sep", + [(np.array([[0.7995, -0.1144, 0.0060, 0.0336], + [0.0000, -0.0994, 0.2478, 0.3474], + [0.0000, -0.6483, -0.0994, 0.2026], + [0.0000, 0.0000, 0.0000, -0.1007]]), + np.array([[0.6551, 0.1037, 0.3450, 0.6641], + [0.5236, -0.5807, -0.6141, -0.1068], + [-0.5362, -0.3073, -0.2935, 0.7293], + [0.0956, 0.7467, -0.6463, 0.1249]]), + np.array([[0.3500, 0.4500, -0.1400, -0.1700], + [0.0900, 0.0700, -0.5399, 0.3500], + [-0.4400, -0.3300, -0.0300, 0.1700], + [0.2500, -0.3200, -0.1300, 0.1100]]), + np.array([1, 0, 0, 1]), + 1.75e+00, 3.22e+00), + (np.array([[-6.0004 - 6.9999j, 0.3637 - 0.3656j, + -0.1880 + 0.4787j, 0.8785 - 0.2539j], + [0.0000 + 0.0000j, -5.0000 + 2.0060j, + -0.0307 - 0.7217j, -0.2290 + 0.1313j], + [0.0000 + 0.0000j, 0.0000 + 0.0000j, + 7.9982 - 0.9964j, 0.9357 + 0.5359j], + [0.0000 + 0.0000j, 0.0000 + 0.0000j, + 0.0000 + 0.0000j, 3.0023 - 3.9998j]]), + np.array([[-0.8347 - 0.1364j, -0.0628 + 0.3806j, + 0.2765 - 0.0846j, 0.0633 - 0.2199j], + [0.0664 - 0.2968j, 0.2365 + 0.5240j, + -0.5877 - 0.4208j, 0.0835 + 0.2183j], + [-0.0362 - 0.3215j, 0.3143 - 0.5473j, + 0.0576 - 0.5736j, 0.0057 - 0.4058j], + [0.0086 + 0.2958j, -0.3416 - 0.0757j, + -0.1900 - 0.1600j, 0.8327 - 0.1868j]]), + np.array([[-3.9702 - 5.0406j, -4.1108 + 3.7002j, + -0.3403 + 1.0098j, 1.2899 - 0.8590j], + [0.3397 - 1.5006j, 1.5201 - 0.4301j, + 1.8797 - 5.3804j, 3.3606 + 0.6498j], + [3.3101 - 3.8506j, 2.4996 + 3.4504j, + 0.8802 - 1.0802j, 0.6401 - 1.4800j], + [-1.0999 + 0.8199j, 1.8103 - 1.5905j, + 3.2502 + 1.3297j, 1.5701 - 3.4397j]]), + np.array([1, 0, 0, 1]), + 1.02e+00, 1.82e-01)]) +def test_trsen_NAG(t, q, select, expect, expect_s, expect_sep): + """ + This test implements the example found in the NAG manual, + f08qgc, f08quc. + """ + # NAG manual provides accuracy up to 4 and 2 decimals + atol = 1e-4 + atol2 = 1e-2 + trsen, trsen_lwork = get_lapack_funcs( + ('trsen', 'trsen_lwork'), dtype=t.dtype) + + lwork = _compute_lwork(trsen_lwork, select, t) + + if t.dtype in COMPLEX_DTYPES: + result = trsen(select, t, q, lwork=lwork) + else: + result = trsen(select, t, q, lwork=lwork, liwork=lwork[1]) + assert_equal(result[-1], 0) + + t = result[0] + q = result[1] + if t.dtype in COMPLEX_DTYPES: + s = result[4] + sep = result[5] + else: + s = result[5] + sep = result[6] + + assert_allclose(expect, q @ t @ q.conj().T, atol=atol) + assert_allclose(expect_s, 1 / s, atol=atol2) + assert_allclose(expect_sep, 1 / sep, atol=atol2) + + +@pytest.mark.parametrize('dtype', DTYPES) +def test_gges_tgsen(dtype): + rng = np.random.RandomState(1234) + atol = np.finfo(dtype).eps*100 + + n = 10 + a = generate_random_dtype_array([n, n], dtype=dtype, rng=rng) + b = generate_random_dtype_array([n, n], dtype=dtype, rng=rng) + + gges, tgsen, tgsen_lwork = get_lapack_funcs( + ('gges', 'tgsen', 'tgsen_lwork'), dtype=dtype) + + result = gges(lambda x: None, a, b, overwrite_a=False, overwrite_b=False) + assert_equal(result[-1], 0) + + s = result[0] + t = result[1] + q = result[-4] + z = result[-3] + + d1 = s[0, 0] / t[0, 0] + d2 = s[6, 6] / t[6, 6] + + if dtype in COMPLEX_DTYPES: + assert_allclose(s, np.triu(s), rtol=0, atol=atol) + assert_allclose(t, np.triu(t), rtol=0, atol=atol) + + assert_allclose(q @ s @ z.conj().T, a, rtol=0, atol=atol) + assert_allclose(q @ t @ z.conj().T, b, rtol=0, atol=atol) + + select = np.zeros(n) + select[6] = 1 + + lwork = _compute_lwork(tgsen_lwork, select, s, t) + + # off-by-one error in LAPACK, see gh-issue #13397 + lwork = (lwork[0]+1, lwork[1]) + + result = tgsen(select, s, t, q, z, lwork=lwork) + assert_equal(result[-1], 0) + + s = result[0] + t = result[1] + q = result[-7] + z = result[-6] + + if dtype in COMPLEX_DTYPES: + assert_allclose(s, np.triu(s), rtol=0, atol=atol) + assert_allclose(t, np.triu(t), rtol=0, atol=atol) + + assert_allclose(q @ s @ z.conj().T, a, rtol=0, atol=atol) + assert_allclose(q @ t @ z.conj().T, b, rtol=0, atol=atol) + + assert_allclose(s[0, 0] / t[0, 0], d2, rtol=0, atol=atol) + assert_allclose(s[1, 1] / t[1, 1], d1, rtol=0, atol=atol) + + +@pytest.mark.parametrize( + "a, b, c, d, e, f, rans, lans", + [(np.array([[4.0, 1.0, 1.0, 2.0], + [0.0, 3.0, 4.0, 1.0], + [0.0, 1.0, 3.0, 1.0], + [0.0, 0.0, 0.0, 6.0]]), + np.array([[1.0, 1.0, 1.0, 1.0], + [0.0, 3.0, 4.0, 1.0], + [0.0, 1.0, 3.0, 1.0], + [0.0, 0.0, 0.0, 4.0]]), + np.array([[-4.0, 7.0, 1.0, 12.0], + [-9.0, 2.0, -2.0, -2.0], + [-4.0, 2.0, -2.0, 8.0], + [-7.0, 7.0, -6.0, 19.0]]), + np.array([[2.0, 1.0, 1.0, 3.0], + [0.0, 1.0, 2.0, 1.0], + [0.0, 0.0, 1.0, 1.0], + [0.0, 0.0, 0.0, 2.0]]), + np.array([[1.0, 1.0, 1.0, 2.0], + [0.0, 1.0, 4.0, 1.0], + [0.0, 0.0, 1.0, 1.0], + [0.0, 0.0, 0.0, 1.0]]), + np.array([[-7.0, 5.0, 0.0, 7.0], + [-5.0, 1.0, -8.0, 0.0], + [-1.0, 2.0, -3.0, 5.0], + [-3.0, 2.0, 0.0, 5.0]]), + np.array([[1.0, 1.0, 1.0, 1.0], + [-1.0, 2.0, -1.0, -1.0], + [-1.0, 1.0, 3.0, 1.0], + [-1.0, 1.0, -1.0, 4.0]]), + np.array([[4.0, -1.0, 1.0, -1.0], + [1.0, 3.0, -1.0, 1.0], + [-1.0, 1.0, 2.0, -1.0], + [1.0, -1.0, 1.0, 1.0]]))]) +@pytest.mark.parametrize('dtype', REAL_DTYPES) +def test_tgsyl_NAG(a, b, c, d, e, f, rans, lans, dtype): + atol = 1e-4 + + tgsyl = get_lapack_funcs(('tgsyl'), dtype=dtype) + rout, lout, scale, dif, info = tgsyl(a, b, c, d, e, f) + + assert_equal(info, 0) + assert_allclose(scale, 1.0, rtol=0, atol=np.finfo(dtype).eps*100, + err_msg="SCALE must be 1.0") + assert_allclose(dif, 0.0, rtol=0, atol=np.finfo(dtype).eps*100, + err_msg="DIF must be nearly 0") + assert_allclose(rout, rans, atol=atol, + err_msg="Solution for R is incorrect") + assert_allclose(lout, lans, atol=atol, + err_msg="Solution for L is incorrect") + + +@pytest.mark.parametrize('dtype', REAL_DTYPES) +@pytest.mark.parametrize('trans', ('N', 'T')) +@pytest.mark.parametrize('ijob', [0, 1, 2, 3, 4]) +def test_tgsyl(dtype, trans, ijob): + + atol = 1e-3 if dtype == np.float32 else 1e-10 + rng = np.random.default_rng(1685779866898198) + m, n = 10, 15 + + a, d, *_ = qz(rng.uniform(-10, 10, [m, m]).astype(dtype), + rng.uniform(-10, 10, [m, m]).astype(dtype), + output='real') + + b, e, *_ = qz(rng.uniform(-10, 10, [n, n]).astype(dtype), + rng.uniform(-10, 10, [n, n]).astype(dtype), + output='real') + + c = rng.uniform(-2, 2, [m, n]).astype(dtype) + f = rng.uniform(-2, 2, [m, n]).astype(dtype) + + tgsyl = get_lapack_funcs(('tgsyl'), dtype=dtype) + rout, lout, scale, dif, info = tgsyl(a, b, c, d, e, f, + trans=trans, ijob=ijob) + + assert info == 0, "INFO is non-zero" + assert scale >= 0.0, "SCALE must be non-negative" + if ijob == 0: + assert_allclose(dif, 0.0, rtol=0, atol=np.finfo(dtype).eps*100, + err_msg="DIF must be 0 for ijob =0") + else: + assert dif >= 0.0, "DIF must be non-negative" + + # Only DIF is calculated for ijob = 3/4 + if ijob <= 2: + if trans == 'N': + lhs1 = a @ rout - lout @ b + rhs1 = scale*c + lhs2 = d @ rout - lout @ e + rhs2 = scale*f + elif trans == 'T': + lhs1 = np.transpose(a) @ rout + np.transpose(d) @ lout + rhs1 = scale*c + lhs2 = rout @ np.transpose(b) + lout @ np.transpose(e) + rhs2 = -1.0*scale*f + + assert_allclose(lhs1, rhs1, atol=atol, rtol=0., + err_msg='lhs1 and rhs1 do not match') + assert_allclose(lhs2, rhs2, atol=atol, rtol=0., + err_msg='lhs2 and rhs2 do not match') + + +@pytest.mark.parametrize('mtype', ['sy', 'he']) # matrix type +@pytest.mark.parametrize('dtype', DTYPES) +@pytest.mark.parametrize('lower', (0, 1)) +def test_sy_hetrs(mtype, dtype, lower): + if mtype == 'he' and dtype in REAL_DTYPES: + pytest.skip("hetrs not for real dtypes.") + rng = np.random.default_rng(1723059677121834) + n, nrhs = 20, 5 + if dtype in COMPLEX_DTYPES: + A = (rng.uniform(size=(n, n)) + rng.uniform(size=(n, n))*1j).astype(dtype) + else: + A = rng.uniform(size=(n, n)).astype(dtype) + + A = A + A.T if mtype == 'sy' else A + A.conj().T + b = rng.uniform(size=(n, nrhs)).astype(dtype) + names = f'{mtype}trf', f'{mtype}trf_lwork', f'{mtype}trs' + trf, trf_lwork, trs = get_lapack_funcs(names, dtype=dtype) + lwork = trf_lwork(n, lower=lower) + ldu, ipiv, info = trf(A, lwork=lwork) + assert info == 0 + x, info = trs(a=ldu, ipiv=ipiv, b=b) + assert info == 0 + eps = np.finfo(dtype).eps + assert_allclose(A@x, b, atol=100*n*eps) + + +@pytest.mark.parametrize('norm', list('Mm1OoIiFfEe')) +@pytest.mark.parametrize('uplo, m, n', [('U', 5, 10), ('U', 10, 10), + ('L', 10, 5), ('L', 10, 10)]) +@pytest.mark.parametrize('diag', ['N', 'U']) +@pytest.mark.parametrize('dtype', DTYPES) +def test_lantr(norm, uplo, m, n, diag, dtype): + rng = np.random.default_rng(98426598246982456) + A = rng.random(size=(m, n)).astype(dtype) + lantr, lange = get_lapack_funcs(('lantr', 'lange'), (A,)) + res = lantr(norm, A, uplo=uplo, diag=diag) + + # now modify the matrix according to assumptions made by `lantr` + A = np.triu(A) if uplo == 'U' else np.tril(A) + if diag == 'U': + i = np.arange(min(m, n)) + A[i, i] = 1 + ref = lange(norm, A) + + assert_allclose(res, ref, rtol=2e-6) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_matfuncs.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_matfuncs.py new file mode 100644 index 0000000000000000000000000000000000000000..9e87333c40b64d3f54024779dfb959be7a599178 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_matfuncs.py @@ -0,0 +1,1063 @@ +# +# Created by: Pearu Peterson, March 2002 +# +""" Test functions for linalg.matfuncs module + +""" +import functools + +import numpy as np +from numpy import array, identity, dot, sqrt +from numpy.testing import (assert_array_almost_equal, assert_allclose, assert_, + assert_array_less, assert_array_equal, assert_warns) +import pytest + +import scipy.linalg +from scipy.linalg import (funm, signm, logm, sqrtm, fractional_matrix_power, + expm, expm_frechet, expm_cond, norm, khatri_rao, + cosm, sinm, tanm, coshm, sinhm, tanhm) +from scipy.linalg import _matfuncs_inv_ssq +from scipy.linalg._matfuncs import pick_pade_structure +from scipy.linalg._matfuncs_inv_ssq import LogmExactlySingularWarning +import scipy.linalg._expm_frechet + +from scipy.optimize import minimize + + +def _get_al_mohy_higham_2012_experiment_1(): + """ + Return the test matrix from Experiment (1) of [1]_. + + References + ---------- + .. [1] Awad H. Al-Mohy and Nicholas J. Higham (2012) + "Improved Inverse Scaling and Squaring Algorithms + for the Matrix Logarithm." + SIAM Journal on Scientific Computing, 34 (4). C152-C169. + ISSN 1095-7197 + + """ + A = np.array([ + [3.2346e-1, 3e4, 3e4, 3e4], + [0, 3.0089e-1, 3e4, 3e4], + [0, 0, 3.2210e-1, 3e4], + [0, 0, 0, 3.0744e-1]], dtype=float) + return A + + +class TestSignM: + + def test_nils(self): + a = array([[29.2, -24.2, 69.5, 49.8, 7.], + [-9.2, 5.2, -18., -16.8, -2.], + [-10., 6., -20., -18., -2.], + [-9.6, 9.6, -25.5, -15.4, -2.], + [9.8, -4.8, 18., 18.2, 2.]]) + cr = array([[11.94933333,-2.24533333,15.31733333,21.65333333,-2.24533333], + [-3.84266667,0.49866667,-4.59066667,-7.18666667,0.49866667], + [-4.08,0.56,-4.92,-7.6,0.56], + [-4.03466667,1.04266667,-5.59866667,-7.02666667,1.04266667], + [4.15733333,-0.50133333,4.90933333,7.81333333,-0.50133333]]) + r = signm(a) + assert_array_almost_equal(r,cr) + + def test_defective1(self): + a = array([[0.0,1,0,0],[1,0,1,0],[0,0,0,1],[0,0,1,0]]) + signm(a, disp=False) + #XXX: what would be the correct result? + + def test_defective2(self): + a = array(( + [29.2,-24.2,69.5,49.8,7.0], + [-9.2,5.2,-18.0,-16.8,-2.0], + [-10.0,6.0,-20.0,-18.0,-2.0], + [-9.6,9.6,-25.5,-15.4,-2.0], + [9.8,-4.8,18.0,18.2,2.0])) + signm(a, disp=False) + #XXX: what would be the correct result? + + def test_defective3(self): + a = array([[-2., 25., 0., 0., 0., 0., 0.], + [0., -3., 10., 3., 3., 3., 0.], + [0., 0., 2., 15., 3., 3., 0.], + [0., 0., 0., 0., 15., 3., 0.], + [0., 0., 0., 0., 3., 10., 0.], + [0., 0., 0., 0., 0., -2., 25.], + [0., 0., 0., 0., 0., 0., -3.]]) + signm(a, disp=False) + #XXX: what would be the correct result? + + +class TestLogM: + + def test_nils(self): + a = array([[-2., 25., 0., 0., 0., 0., 0.], + [0., -3., 10., 3., 3., 3., 0.], + [0., 0., 2., 15., 3., 3., 0.], + [0., 0., 0., 0., 15., 3., 0.], + [0., 0., 0., 0., 3., 10., 0.], + [0., 0., 0., 0., 0., -2., 25.], + [0., 0., 0., 0., 0., 0., -3.]]) + m = (identity(7)*3.1+0j)-a + logm(m, disp=False) + #XXX: what would be the correct result? + + def test_al_mohy_higham_2012_experiment_1_logm(self): + # The logm completes the round trip successfully. + # Note that the expm leg of the round trip is badly conditioned. + A = _get_al_mohy_higham_2012_experiment_1() + A_logm, info = logm(A, disp=False) + A_round_trip = expm(A_logm) + assert_allclose(A_round_trip, A, rtol=5e-5, atol=1e-14) + + def test_al_mohy_higham_2012_experiment_1_funm_log(self): + # The raw funm with np.log does not complete the round trip. + # Note that the expm leg of the round trip is badly conditioned. + A = _get_al_mohy_higham_2012_experiment_1() + A_funm_log, info = funm(A, np.log, disp=False) + A_round_trip = expm(A_funm_log) + assert_(not np.allclose(A_round_trip, A, rtol=1e-5, atol=1e-14)) + + def test_round_trip_random_float(self): + np.random.seed(1234) + for n in range(1, 6): + M_unscaled = np.random.randn(n, n) + for scale in np.logspace(-4, 4, 9): + M = M_unscaled * scale + + # Eigenvalues are related to the branch cut. + W = np.linalg.eigvals(M) + err_msg = f'M:{M} eivals:{W}' + + # Check sqrtm round trip because it is used within logm. + M_sqrtm, info = sqrtm(M, disp=False) + M_sqrtm_round_trip = M_sqrtm.dot(M_sqrtm) + assert_allclose(M_sqrtm_round_trip, M) + + # Check logm round trip. + M_logm, info = logm(M, disp=False) + M_logm_round_trip = expm(M_logm) + assert_allclose(M_logm_round_trip, M, err_msg=err_msg) + + def test_round_trip_random_complex(self): + np.random.seed(1234) + for n in range(1, 6): + M_unscaled = np.random.randn(n, n) + 1j * np.random.randn(n, n) + for scale in np.logspace(-4, 4, 9): + M = M_unscaled * scale + M_logm, info = logm(M, disp=False) + M_round_trip = expm(M_logm) + assert_allclose(M_round_trip, M) + + def test_logm_type_preservation_and_conversion(self): + # The logm matrix function should preserve the type of a matrix + # whose eigenvalues are positive with zero imaginary part. + # Test this preservation for variously structured matrices. + complex_dtype_chars = ('F', 'D', 'G') + for matrix_as_list in ( + [[1, 0], [0, 1]], + [[1, 0], [1, 1]], + [[2, 1], [1, 1]], + [[2, 3], [1, 2]]): + + # check that the spectrum has the expected properties + W = scipy.linalg.eigvals(matrix_as_list) + assert_(not any(w.imag or w.real < 0 for w in W)) + + # check float type preservation + A = np.array(matrix_as_list, dtype=float) + A_logm, info = logm(A, disp=False) + assert_(A_logm.dtype.char not in complex_dtype_chars) + + # check complex type preservation + A = np.array(matrix_as_list, dtype=complex) + A_logm, info = logm(A, disp=False) + assert_(A_logm.dtype.char in complex_dtype_chars) + + # check float->complex type conversion for the matrix negation + A = -np.array(matrix_as_list, dtype=float) + A_logm, info = logm(A, disp=False) + assert_(A_logm.dtype.char in complex_dtype_chars) + + def test_complex_spectrum_real_logm(self): + # This matrix has complex eigenvalues and real logm. + # Its output dtype depends on its input dtype. + M = [[1, 1, 2], [2, 1, 1], [1, 2, 1]] + for dt in float, complex: + X = np.array(M, dtype=dt) + w = scipy.linalg.eigvals(X) + assert_(1e-2 < np.absolute(w.imag).sum()) + Y, info = logm(X, disp=False) + assert_(np.issubdtype(Y.dtype, np.inexact)) + assert_allclose(expm(Y), X) + + def test_real_mixed_sign_spectrum(self): + # These matrices have real eigenvalues with mixed signs. + # The output logm dtype is complex, regardless of input dtype. + for M in ( + [[1, 0], [0, -1]], + [[0, 1], [1, 0]]): + for dt in float, complex: + A = np.array(M, dtype=dt) + A_logm, info = logm(A, disp=False) + assert_(np.issubdtype(A_logm.dtype, np.complexfloating)) + + @pytest.mark.thread_unsafe + def test_exactly_singular(self): + A = np.array([[0, 0], [1j, 1j]]) + B = np.asarray([[1, 1], [0, 0]]) + for M in A, A.T, B, B.T: + expected_warning = _matfuncs_inv_ssq.LogmExactlySingularWarning + L, info = assert_warns(expected_warning, logm, M, disp=False) + E = expm(L) + assert_allclose(E, M, atol=1e-14) + + @pytest.mark.thread_unsafe + def test_nearly_singular(self): + M = np.array([[1e-100]]) + expected_warning = _matfuncs_inv_ssq.LogmNearlySingularWarning + L, info = assert_warns(expected_warning, logm, M, disp=False) + E = expm(L) + assert_allclose(E, M, atol=1e-14) + + def test_opposite_sign_complex_eigenvalues(self): + # See gh-6113 + E = [[0, 1], [-1, 0]] + L = [[0, np.pi*0.5], [-np.pi*0.5, 0]] + assert_allclose(expm(L), E, atol=1e-14) + assert_allclose(logm(E), L, atol=1e-14) + E = [[1j, 4], [0, -1j]] + L = [[1j*np.pi*0.5, 2*np.pi], [0, -1j*np.pi*0.5]] + assert_allclose(expm(L), E, atol=1e-14) + assert_allclose(logm(E), L, atol=1e-14) + E = [[1j, 0], [0, -1j]] + L = [[1j*np.pi*0.5, 0], [0, -1j*np.pi*0.5]] + assert_allclose(expm(L), E, atol=1e-14) + assert_allclose(logm(E), L, atol=1e-14) + + def test_readonly(self): + n = 5 + a = np.ones((n, n)) + np.identity(n) + a.flags.writeable = False + logm(a) + + @pytest.mark.xfail(reason="ValueError: attempt to get argmax of an empty sequence") + @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) + def test_empty(self, dt): + a = np.empty((0, 0), dtype=dt) + log_a = logm(a) + a0 = np.eye(2, dtype=dt) + log_a0 = logm(a0) + + assert log_a.shape == (0, 0) + assert log_a.dtype == log_a0.dtype + + @pytest.mark.thread_unsafe + @pytest.mark.parametrize('dtype', [int, float, np.float32, complex, np.complex64]) + def test_no_ZeroDivisionError(self, dtype): + # gh-17136 reported inconsistent behavior in `logm` depending on input dtype: + # sometimes it raised an error, and sometimes it printed a warning message. + # check that this is resolved and that the warning is emitted properly. + with (pytest.warns(RuntimeWarning, match="logm result may be inaccurate"), + pytest.warns(LogmExactlySingularWarning)): + logm(np.zeros((2, 2), dtype=dtype)) + + +class TestSqrtM: + def test_round_trip_random_float(self): + rng = np.random.RandomState(1234) + for n in range(1, 6): + M_unscaled = rng.randn(n, n) + for scale in np.logspace(-4, 4, 9): + M = M_unscaled * scale + M_sqrtm, info = sqrtm(M, disp=False) + M_sqrtm_round_trip = M_sqrtm.dot(M_sqrtm) + assert_allclose(M_sqrtm_round_trip, M) + + def test_round_trip_random_complex(self): + rng = np.random.RandomState(1234) + for n in range(1, 6): + M_unscaled = rng.randn(n, n) + 1j * rng.randn(n, n) + for scale in np.logspace(-4, 4, 9): + M = M_unscaled * scale + M_sqrtm, info = sqrtm(M, disp=False) + M_sqrtm_round_trip = M_sqrtm.dot(M_sqrtm) + assert_allclose(M_sqrtm_round_trip, M) + + def test_bad(self): + # See https://web.archive.org/web/20051220232650/http://www.maths.man.ac.uk/~nareports/narep336.ps.gz + e = 2**-5 + se = sqrt(e) + a = array([[1.0,0,0,1], + [0,e,0,0], + [0,0,e,0], + [0,0,0,1]]) + sa = array([[1,0,0,0.5], + [0,se,0,0], + [0,0,se,0], + [0,0,0,1]]) + n = a.shape[0] + assert_array_almost_equal(dot(sa,sa),a) + # Check default sqrtm. + esa = sqrtm(a, disp=False, blocksize=n)[0] + assert_array_almost_equal(dot(esa,esa),a) + # Check sqrtm with 2x2 blocks. + esa = sqrtm(a, disp=False, blocksize=2)[0] + assert_array_almost_equal(dot(esa,esa),a) + + def test_sqrtm_type_preservation_and_conversion(self): + # The sqrtm matrix function should preserve the type of a matrix + # whose eigenvalues are nonnegative with zero imaginary part. + # Test this preservation for variously structured matrices. + complex_dtype_chars = ('F', 'D', 'G') + for matrix_as_list in ( + [[1, 0], [0, 1]], + [[1, 0], [1, 1]], + [[2, 1], [1, 1]], + [[2, 3], [1, 2]], + [[1, 1], [1, 1]]): + + # check that the spectrum has the expected properties + W = scipy.linalg.eigvals(matrix_as_list) + assert_(not any(w.imag or w.real < 0 for w in W)) + + # check float type preservation + A = np.array(matrix_as_list, dtype=float) + A_sqrtm, info = sqrtm(A, disp=False) + assert_(A_sqrtm.dtype.char not in complex_dtype_chars) + + # check complex type preservation + A = np.array(matrix_as_list, dtype=complex) + A_sqrtm, info = sqrtm(A, disp=False) + assert_(A_sqrtm.dtype.char in complex_dtype_chars) + + # check float->complex type conversion for the matrix negation + A = -np.array(matrix_as_list, dtype=float) + A_sqrtm, info = sqrtm(A, disp=False) + assert_(A_sqrtm.dtype.char in complex_dtype_chars) + + def test_sqrtm_type_conversion_mixed_sign_or_complex_spectrum(self): + complex_dtype_chars = ('F', 'D', 'G') + for matrix_as_list in ( + [[1, 0], [0, -1]], + [[0, 1], [1, 0]], + [[0, 1, 0], [0, 0, 1], [1, 0, 0]]): + + # check that the spectrum has the expected properties + W = scipy.linalg.eigvals(matrix_as_list) + assert_(any(w.imag or w.real < 0 for w in W)) + + # check complex->complex + A = np.array(matrix_as_list, dtype=complex) + A_sqrtm, info = sqrtm(A, disp=False) + assert_(A_sqrtm.dtype.char in complex_dtype_chars) + + # check float->complex + A = np.array(matrix_as_list, dtype=float) + A_sqrtm, info = sqrtm(A, disp=False) + assert_(A_sqrtm.dtype.char in complex_dtype_chars) + + def test_blocksizes(self): + # Make sure I do not goof up the blocksizes when they do not divide n. + np.random.seed(1234) + for n in range(1, 8): + A = np.random.rand(n, n) + 1j*np.random.randn(n, n) + A_sqrtm_default, info = sqrtm(A, disp=False, blocksize=n) + assert_allclose(A, np.linalg.matrix_power(A_sqrtm_default, 2)) + for blocksize in range(1, 10): + A_sqrtm_new, info = sqrtm(A, disp=False, blocksize=blocksize) + assert_allclose(A_sqrtm_default, A_sqrtm_new) + + def test_al_mohy_higham_2012_experiment_1(self): + # Matrix square root of a tricky upper triangular matrix. + A = _get_al_mohy_higham_2012_experiment_1() + A_sqrtm, info = sqrtm(A, disp=False) + A_round_trip = A_sqrtm.dot(A_sqrtm) + assert_allclose(A_round_trip, A, rtol=1e-5) + assert_allclose(np.tril(A_round_trip), np.tril(A)) + + def test_strict_upper_triangular(self): + # This matrix has no square root. + for dt in int, float: + A = np.array([ + [0, 3, 0, 0], + [0, 0, 3, 0], + [0, 0, 0, 3], + [0, 0, 0, 0]], dtype=dt) + A_sqrtm, info = sqrtm(A, disp=False) + assert_(np.isnan(A_sqrtm).all()) + + def test_weird_matrix(self): + # The square root of matrix B exists. + for dt in int, float: + A = np.array([ + [0, 0, 1], + [0, 0, 0], + [0, 1, 0]], dtype=dt) + B = np.array([ + [0, 1, 0], + [0, 0, 0], + [0, 0, 0]], dtype=dt) + assert_array_equal(B, A.dot(A)) + + # But scipy sqrtm is not clever enough to find it. + B_sqrtm, info = sqrtm(B, disp=False) + assert_(np.isnan(B_sqrtm).all()) + + def test_disp(self): + np.random.seed(1234) + + A = np.random.rand(3, 3) + B = sqrtm(A, disp=True) + assert_allclose(B.dot(B), A) + + def test_opposite_sign_complex_eigenvalues(self): + M = [[2j, 4], [0, -2j]] + R = [[1+1j, 2], [0, 1-1j]] + assert_allclose(np.dot(R, R), M, atol=1e-14) + assert_allclose(sqrtm(M), R, atol=1e-14) + + def test_gh4866(self): + M = np.array([[1, 0, 0, 1], + [0, 0, 0, 0], + [0, 0, 0, 0], + [1, 0, 0, 1]]) + R = np.array([[sqrt(0.5), 0, 0, sqrt(0.5)], + [0, 0, 0, 0], + [0, 0, 0, 0], + [sqrt(0.5), 0, 0, sqrt(0.5)]]) + assert_allclose(np.dot(R, R), M, atol=1e-14) + assert_allclose(sqrtm(M), R, atol=1e-14) + + def test_gh5336(self): + M = np.diag([2, 1, 0]) + R = np.diag([sqrt(2), 1, 0]) + assert_allclose(np.dot(R, R), M, atol=1e-14) + assert_allclose(sqrtm(M), R, atol=1e-14) + + def test_gh7839(self): + M = np.zeros((2, 2)) + R = np.zeros((2, 2)) + assert_allclose(np.dot(R, R), M, atol=1e-14) + assert_allclose(sqrtm(M), R, atol=1e-14) + + @pytest.mark.xfail(reason="failing on macOS after gh-20212") + def test_gh17918(self): + M = np.empty((19, 19)) + M.fill(0.94) + np.fill_diagonal(M, 1) + assert np.isrealobj(sqrtm(M)) + + def test_data_size_preservation_uint_in_float_out(self): + M = np.zeros((10, 10), dtype=np.uint8) + assert sqrtm(M).dtype == np.float64 + M = np.zeros((10, 10), dtype=np.uint16) + assert sqrtm(M).dtype == np.float64 + M = np.zeros((10, 10), dtype=np.uint32) + assert sqrtm(M).dtype == np.float64 + M = np.zeros((10, 10), dtype=np.uint64) + assert sqrtm(M).dtype == np.float64 + + def test_data_size_preservation_int_in_float_out(self): + M = np.zeros((10, 10), dtype=np.int8) + assert sqrtm(M).dtype == np.float64 + M = np.zeros((10, 10), dtype=np.int16) + assert sqrtm(M).dtype == np.float64 + M = np.zeros((10, 10), dtype=np.int32) + assert sqrtm(M).dtype == np.float64 + M = np.zeros((10, 10), dtype=np.int64) + assert sqrtm(M).dtype == np.float64 + + def test_data_size_preservation_int_in_comp_out(self): + M = np.array([[2, 4], [0, -2]], dtype=np.int8) + assert sqrtm(M).dtype == np.complex128 + M = np.array([[2, 4], [0, -2]], dtype=np.int16) + assert sqrtm(M).dtype == np.complex128 + M = np.array([[2, 4], [0, -2]], dtype=np.int32) + assert sqrtm(M).dtype == np.complex128 + M = np.array([[2, 4], [0, -2]], dtype=np.int64) + assert sqrtm(M).dtype == np.complex128 + + def test_data_size_preservation_float_in_float_out(self): + M = np.zeros((10, 10), dtype=np.float16) + assert sqrtm(M).dtype == np.float32 + M = np.zeros((10, 10), dtype=np.float32) + assert sqrtm(M).dtype == np.float32 + M = np.zeros((10, 10), dtype=np.float64) + assert sqrtm(M).dtype == np.float64 + if hasattr(np, 'float128'): + M = np.zeros((10, 10), dtype=np.float128) + assert sqrtm(M).dtype == np.float64 + + def test_data_size_preservation_float_in_comp_out(self): + M = np.array([[2, 4], [0, -2]], dtype=np.float16) + assert sqrtm(M).dtype == np.complex64 + M = np.array([[2, 4], [0, -2]], dtype=np.float32) + assert sqrtm(M).dtype == np.complex64 + M = np.array([[2, 4], [0, -2]], dtype=np.float64) + assert sqrtm(M).dtype == np.complex128 + if hasattr(np, 'float128') and hasattr(np, 'complex256'): + M = np.array([[2, 4], [0, -2]], dtype=np.float128) + assert sqrtm(M).dtype == np.complex128 + + def test_data_size_preservation_comp_in_comp_out(self): + M = np.array([[2j, 4], [0, -2j]], dtype=np.complex64) + assert sqrtm(M).dtype == np.complex64 + M = np.array([[2j, 4], [0, -2j]], dtype=np.complex128) + assert sqrtm(M).dtype == np.complex128 + if hasattr(np, 'complex256'): + M = np.array([[2j, 4], [0, -2j]], dtype=np.complex256) + assert sqrtm(M).dtype == np.complex128 + + @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) + def test_empty(self, dt): + a = np.empty((0, 0), dtype=dt) + s = sqrtm(a) + a0 = np.eye(2, dtype=dt) + s0 = sqrtm(a0) + + assert s.shape == (0, 0) + assert s.dtype == s0.dtype + + +class TestFractionalMatrixPower: + def test_round_trip_random_complex(self): + np.random.seed(1234) + for p in range(1, 5): + for n in range(1, 5): + M_unscaled = np.random.randn(n, n) + 1j * np.random.randn(n, n) + for scale in np.logspace(-4, 4, 9): + M = M_unscaled * scale + M_root = fractional_matrix_power(M, 1/p) + M_round_trip = np.linalg.matrix_power(M_root, p) + assert_allclose(M_round_trip, M) + + def test_round_trip_random_float(self): + # This test is more annoying because it can hit the branch cut; + # this happens when the matrix has an eigenvalue + # with no imaginary component and with a real negative component, + # and it means that the principal branch does not exist. + np.random.seed(1234) + for p in range(1, 5): + for n in range(1, 5): + M_unscaled = np.random.randn(n, n) + for scale in np.logspace(-4, 4, 9): + M = M_unscaled * scale + M_root = fractional_matrix_power(M, 1/p) + M_round_trip = np.linalg.matrix_power(M_root, p) + assert_allclose(M_round_trip, M) + + def test_larger_abs_fractional_matrix_powers(self): + np.random.seed(1234) + for n in (2, 3, 5): + for i in range(10): + M = np.random.randn(n, n) + 1j * np.random.randn(n, n) + M_one_fifth = fractional_matrix_power(M, 0.2) + # Test the round trip. + M_round_trip = np.linalg.matrix_power(M_one_fifth, 5) + assert_allclose(M, M_round_trip) + # Test a large abs fractional power. + X = fractional_matrix_power(M, -5.4) + Y = np.linalg.matrix_power(M_one_fifth, -27) + assert_allclose(X, Y) + # Test another large abs fractional power. + X = fractional_matrix_power(M, 3.8) + Y = np.linalg.matrix_power(M_one_fifth, 19) + assert_allclose(X, Y) + + def test_random_matrices_and_powers(self): + # Each independent iteration of this fuzz test picks random parameters. + # It tries to hit some edge cases. + rng = np.random.default_rng(1726500458620605) + nsamples = 20 + for i in range(nsamples): + # Sample a matrix size and a random real power. + n = rng.integers(1, 5) + p = rng.random() + + # Sample a random real or complex matrix. + matrix_scale = np.exp(rng.integers(-4, 5)) + A = rng.random(size=[n, n]) + if [True, False][rng.choice(2)]: + A = A + 1j * rng.random(size=[n, n]) + A = A * matrix_scale + + # Check a couple of analytically equivalent ways + # to compute the fractional matrix power. + # These can be compared because they both use the principal branch. + A_power = fractional_matrix_power(A, p) + A_logm, info = logm(A, disp=False) + A_power_expm_logm = expm(A_logm * p) + assert_allclose(A_power, A_power_expm_logm) + + def test_al_mohy_higham_2012_experiment_1(self): + # Fractional powers of a tricky upper triangular matrix. + A = _get_al_mohy_higham_2012_experiment_1() + + # Test remainder matrix power. + A_funm_sqrt, info = funm(A, np.sqrt, disp=False) + A_sqrtm, info = sqrtm(A, disp=False) + A_rem_power = _matfuncs_inv_ssq._remainder_matrix_power(A, 0.5) + A_power = fractional_matrix_power(A, 0.5) + assert_allclose(A_rem_power, A_power, rtol=1e-11) + assert_allclose(A_sqrtm, A_power) + assert_allclose(A_sqrtm, A_funm_sqrt) + + # Test more fractional powers. + for p in (1/2, 5/3): + A_power = fractional_matrix_power(A, p) + A_round_trip = fractional_matrix_power(A_power, 1/p) + assert_allclose(A_round_trip, A, rtol=1e-2) + assert_allclose(np.tril(A_round_trip, 1), np.tril(A, 1)) + + def test_briggs_helper_function(self): + np.random.seed(1234) + for a in np.random.randn(10) + 1j * np.random.randn(10): + for k in range(5): + x_observed = _matfuncs_inv_ssq._briggs_helper_function(a, k) + x_expected = a ** np.exp2(-k) - 1 + assert_allclose(x_observed, x_expected) + + def test_type_preservation_and_conversion(self): + # The fractional_matrix_power matrix function should preserve + # the type of a matrix whose eigenvalues + # are positive with zero imaginary part. + # Test this preservation for variously structured matrices. + complex_dtype_chars = ('F', 'D', 'G') + for matrix_as_list in ( + [[1, 0], [0, 1]], + [[1, 0], [1, 1]], + [[2, 1], [1, 1]], + [[2, 3], [1, 2]]): + + # check that the spectrum has the expected properties + W = scipy.linalg.eigvals(matrix_as_list) + assert_(not any(w.imag or w.real < 0 for w in W)) + + # Check various positive and negative powers + # with absolute values bigger and smaller than 1. + for p in (-2.4, -0.9, 0.2, 3.3): + + # check float type preservation + A = np.array(matrix_as_list, dtype=float) + A_power = fractional_matrix_power(A, p) + assert_(A_power.dtype.char not in complex_dtype_chars) + + # check complex type preservation + A = np.array(matrix_as_list, dtype=complex) + A_power = fractional_matrix_power(A, p) + assert_(A_power.dtype.char in complex_dtype_chars) + + # check float->complex for the matrix negation + A = -np.array(matrix_as_list, dtype=float) + A_power = fractional_matrix_power(A, p) + assert_(A_power.dtype.char in complex_dtype_chars) + + def test_type_conversion_mixed_sign_or_complex_spectrum(self): + complex_dtype_chars = ('F', 'D', 'G') + for matrix_as_list in ( + [[1, 0], [0, -1]], + [[0, 1], [1, 0]], + [[0, 1, 0], [0, 0, 1], [1, 0, 0]]): + + # check that the spectrum has the expected properties + W = scipy.linalg.eigvals(matrix_as_list) + assert_(any(w.imag or w.real < 0 for w in W)) + + # Check various positive and negative powers + # with absolute values bigger and smaller than 1. + for p in (-2.4, -0.9, 0.2, 3.3): + + # check complex->complex + A = np.array(matrix_as_list, dtype=complex) + A_power = fractional_matrix_power(A, p) + assert_(A_power.dtype.char in complex_dtype_chars) + + # check float->complex + A = np.array(matrix_as_list, dtype=float) + A_power = fractional_matrix_power(A, p) + assert_(A_power.dtype.char in complex_dtype_chars) + + @pytest.mark.xfail(reason='Too unstable across LAPACKs.') + def test_singular(self): + # Negative fractional powers do not work with singular matrices. + for matrix_as_list in ( + [[0, 0], [0, 0]], + [[1, 1], [1, 1]], + [[1, 2], [3, 6]], + [[0, 0, 0], [0, 1, 1], [0, -1, 1]]): + + # Check fractional powers both for float and for complex types. + for newtype in (float, complex): + A = np.array(matrix_as_list, dtype=newtype) + for p in (-0.7, -0.9, -2.4, -1.3): + A_power = fractional_matrix_power(A, p) + assert_(np.isnan(A_power).all()) + for p in (0.2, 1.43): + A_power = fractional_matrix_power(A, p) + A_round_trip = fractional_matrix_power(A_power, 1/p) + assert_allclose(A_round_trip, A) + + def test_opposite_sign_complex_eigenvalues(self): + M = [[2j, 4], [0, -2j]] + R = [[1+1j, 2], [0, 1-1j]] + assert_allclose(np.dot(R, R), M, atol=1e-14) + assert_allclose(fractional_matrix_power(M, 0.5), R, atol=1e-14) + + +class TestExpM: + def test_zero(self): + a = array([[0.,0],[0,0]]) + assert_array_almost_equal(expm(a),[[1,0],[0,1]]) + + def test_single_elt(self): + elt = expm(1) + assert_allclose(elt, np.array([[np.e]])) + + @pytest.mark.parametrize('func', [expm, cosm, sinm, tanm, coshm, sinhm, tanhm]) + @pytest.mark.parametrize('dt',[int, float, np.float32, complex, np.complex64]) + @pytest.mark.parametrize('shape', [(0, 0), (1, 1)]) + def test_small_empty_matrix_input(self, func, dt, shape): + # regression test for gh-11082 / gh-20372 - test behavior of expm + # and related functions for small and zero-sized arrays. + A = np.zeros(shape, dtype=dt) + A0 = np.zeros((10, 10), dtype=dt) + result = func(A) + result0 = func(A0) + assert result.shape == shape + assert result.dtype == result0.dtype + + def test_2x2_input(self): + E = np.e + a = array([[1, 4], [1, 1]]) + aa = (E**4 + 1)/(2*E) + bb = (E**4 - 1)/E + assert_allclose(expm(a), array([[aa, bb], [bb/4, aa]])) + assert expm(a.astype(np.complex64)).dtype.char == 'F' + assert expm(a.astype(np.float32)).dtype.char == 'f' + + def test_nx2x2_input(self): + E = np.e + # These are integer matrices with integer eigenvalues + a = np.array([[[1, 4], [1, 1]], + [[1, 3], [1, -1]], + [[1, 3], [4, 5]], + [[1, 3], [5, 3]], + [[4, 5], [-3, -4]]], order='F') + # Exact results are computed symbolically + a_res = np.array([ + [[(E**4+1)/(2*E), (E**4-1)/E], + [(E**4-1)/4/E, (E**4+1)/(2*E)]], + [[1/(4*E**2)+(3*E**2)/4, (3*E**2)/4-3/(4*E**2)], + [E**2/4-1/(4*E**2), 3/(4*E**2)+E**2/4]], + [[3/(4*E)+E**7/4, -3/(8*E)+(3*E**7)/8], + [-1/(2*E)+E**7/2, 1/(4*E)+(3*E**7)/4]], + [[5/(8*E**2)+(3*E**6)/8, -3/(8*E**2)+(3*E**6)/8], + [-5/(8*E**2)+(5*E**6)/8, 3/(8*E**2)+(5*E**6)/8]], + [[-3/(2*E)+(5*E)/2, -5/(2*E)+(5*E)/2], + [3/(2*E)-(3*E)/2, 5/(2*E)-(3*E)/2]] + ]) + assert_allclose(expm(a), a_res) + + def test_readonly(self): + n = 7 + a = np.ones((n, n)) + a.flags.writeable = False + expm(a) + + @pytest.mark.thread_unsafe + @pytest.mark.fail_slow(5) + def test_gh18086(self): + A = np.zeros((400, 400), dtype=float) + rng = np.random.default_rng(100) + i = rng.integers(0, 399, 500) + j = rng.integers(0, 399, 500) + A[i, j] = rng.random(500) + # Problem appears when m = 9 + Am = np.empty((5, 400, 400), dtype=float) + Am[0] = A.copy() + m, s = pick_pade_structure(Am) + assert m == 9 + # Check that result is accurate + first_res = expm(A) + np.testing.assert_array_almost_equal(logm(first_res), A) + # Check that result is consistent + for i in range(5): + next_res = expm(A) + np.testing.assert_array_almost_equal(first_res, next_res) + + +class TestExpmFrechet: + + def test_expm_frechet(self): + # a test of the basic functionality + M = np.array([ + [1, 2, 3, 4], + [5, 6, 7, 8], + [0, 0, 1, 2], + [0, 0, 5, 6], + ], dtype=float) + A = np.array([ + [1, 2], + [5, 6], + ], dtype=float) + E = np.array([ + [3, 4], + [7, 8], + ], dtype=float) + expected_expm = scipy.linalg.expm(A) + expected_frechet = scipy.linalg.expm(M)[:2, 2:] + for kwargs in ({}, {'method':'SPS'}, {'method':'blockEnlarge'}): + observed_expm, observed_frechet = expm_frechet(A, E, **kwargs) + assert_allclose(expected_expm, observed_expm) + assert_allclose(expected_frechet, observed_frechet) + + def test_small_norm_expm_frechet(self): + # methodically test matrices with a range of norms, for better coverage + M_original = np.array([ + [1, 2, 3, 4], + [5, 6, 7, 8], + [0, 0, 1, 2], + [0, 0, 5, 6], + ], dtype=float) + A_original = np.array([ + [1, 2], + [5, 6], + ], dtype=float) + E_original = np.array([ + [3, 4], + [7, 8], + ], dtype=float) + A_original_norm_1 = scipy.linalg.norm(A_original, 1) + selected_m_list = [1, 3, 5, 7, 9, 11, 13, 15] + m_neighbor_pairs = zip(selected_m_list[:-1], selected_m_list[1:]) + for ma, mb in m_neighbor_pairs: + ell_a = scipy.linalg._expm_frechet.ell_table_61[ma] + ell_b = scipy.linalg._expm_frechet.ell_table_61[mb] + target_norm_1 = 0.5 * (ell_a + ell_b) + scale = target_norm_1 / A_original_norm_1 + M = scale * M_original + A = scale * A_original + E = scale * E_original + expected_expm = scipy.linalg.expm(A) + expected_frechet = scipy.linalg.expm(M)[:2, 2:] + observed_expm, observed_frechet = expm_frechet(A, E) + assert_allclose(expected_expm, observed_expm) + assert_allclose(expected_frechet, observed_frechet) + + def test_fuzz(self): + rng = np.random.default_rng(1726500908359153) + # try a bunch of crazy inputs + rfuncs = ( + np.random.uniform, + np.random.normal, + np.random.standard_cauchy, + np.random.exponential) + ntests = 100 + for i in range(ntests): + rfunc = rfuncs[rng.choice(4)] + target_norm_1 = rng.exponential() + n = rng.integers(2, 16) + A_original = rfunc(size=(n,n)) + E_original = rfunc(size=(n,n)) + A_original_norm_1 = scipy.linalg.norm(A_original, 1) + scale = target_norm_1 / A_original_norm_1 + A = scale * A_original + E = scale * E_original + M = np.vstack([ + np.hstack([A, E]), + np.hstack([np.zeros_like(A), A])]) + expected_expm = scipy.linalg.expm(A) + expected_frechet = scipy.linalg.expm(M)[:n, n:] + observed_expm, observed_frechet = expm_frechet(A, E) + assert_allclose(expected_expm, observed_expm, atol=5e-8) + assert_allclose(expected_frechet, observed_frechet, atol=1e-7) + + def test_problematic_matrix(self): + # this test case uncovered a bug which has since been fixed + A = np.array([ + [1.50591997, 1.93537998], + [0.41203263, 0.23443516], + ], dtype=float) + E = np.array([ + [1.87864034, 2.07055038], + [1.34102727, 0.67341123], + ], dtype=float) + scipy.linalg.norm(A, 1) + sps_expm, sps_frechet = expm_frechet( + A, E, method='SPS') + blockEnlarge_expm, blockEnlarge_frechet = expm_frechet( + A, E, method='blockEnlarge') + assert_allclose(sps_expm, blockEnlarge_expm) + assert_allclose(sps_frechet, blockEnlarge_frechet) + + @pytest.mark.slow + @pytest.mark.skip(reason='this test is deliberately slow') + def test_medium_matrix(self): + # profile this to see the speed difference + n = 1000 + A = np.random.exponential(size=(n, n)) + E = np.random.exponential(size=(n, n)) + sps_expm, sps_frechet = expm_frechet( + A, E, method='SPS') + blockEnlarge_expm, blockEnlarge_frechet = expm_frechet( + A, E, method='blockEnlarge') + assert_allclose(sps_expm, blockEnlarge_expm) + assert_allclose(sps_frechet, blockEnlarge_frechet) + + +def _help_expm_cond_search(A, A_norm, X, X_norm, eps, p): + p = np.reshape(p, A.shape) + p_norm = norm(p) + perturbation = eps * p * (A_norm / p_norm) + X_prime = expm(A + perturbation) + scaled_relative_error = norm(X_prime - X) / (X_norm * eps) + return -scaled_relative_error + + +def _normalized_like(A, B): + return A * (scipy.linalg.norm(B) / scipy.linalg.norm(A)) + + +def _relative_error(f, A, perturbation): + X = f(A) + X_prime = f(A + perturbation) + return norm(X_prime - X) / norm(X) + + +class TestExpmConditionNumber: + def test_expm_cond_smoke(self): + np.random.seed(1234) + for n in range(1, 4): + A = np.random.randn(n, n) + kappa = expm_cond(A) + assert_array_less(0, kappa) + + def test_expm_bad_condition_number(self): + A = np.array([ + [-1.128679820, 9.614183771e4, -4.524855739e9, 2.924969411e14], + [0, -1.201010529, 9.634696872e4, -4.681048289e9], + [0, 0, -1.132893222, 9.532491830e4], + [0, 0, 0, -1.179475332], + ]) + kappa = expm_cond(A) + assert_array_less(1e36, kappa) + + def test_univariate(self): + np.random.seed(12345) + for x in np.linspace(-5, 5, num=11): + A = np.array([[x]]) + assert_allclose(expm_cond(A), abs(x)) + for x in np.logspace(-2, 2, num=11): + A = np.array([[x]]) + assert_allclose(expm_cond(A), abs(x)) + for i in range(10): + A = np.random.randn(1, 1) + assert_allclose(expm_cond(A), np.absolute(A)[0, 0]) + + @pytest.mark.slow + def test_expm_cond_fuzz(self): + rng = np.random.RandomState(12345) + eps = 1e-5 + nsamples = 10 + for i in range(nsamples): + n = rng.randint(2, 5) + A = rng.randn(n, n) + A_norm = scipy.linalg.norm(A) + X = expm(A) + X_norm = scipy.linalg.norm(X) + kappa = expm_cond(A) + + # Look for the small perturbation that gives the greatest + # relative error. + f = functools.partial(_help_expm_cond_search, + A, A_norm, X, X_norm, eps) + guess = np.ones(n*n) + out = minimize(f, guess, method='L-BFGS-B') + xopt = out.x + yopt = f(xopt) + p_best = eps * _normalized_like(np.reshape(xopt, A.shape), A) + p_best_relerr = _relative_error(expm, A, p_best) + assert_allclose(p_best_relerr, -yopt * eps) + + # Check that the identified perturbation indeed gives greater + # relative error than random perturbations with similar norms. + for j in range(5): + p_rand = eps * _normalized_like(rng.randn(*A.shape), A) + assert_allclose(norm(p_best), norm(p_rand)) + p_rand_relerr = _relative_error(expm, A, p_rand) + assert_array_less(p_rand_relerr, p_best_relerr) + + # The greatest relative error should not be much greater than + # eps times the condition number kappa. + # In the limit as eps approaches zero it should never be greater. + assert_array_less(p_best_relerr, (1 + 2*eps) * eps * kappa) + + +class TestKhatriRao: + + def test_basic(self): + a = khatri_rao(array([[1, 2], [3, 4]]), + array([[5, 6], [7, 8]])) + + assert_array_equal(a, array([[5, 12], + [7, 16], + [15, 24], + [21, 32]])) + + b = khatri_rao(np.empty([2, 2]), np.empty([2, 2])) + assert_array_equal(b.shape, (4, 2)) + + def test_number_of_columns_equality(self): + with pytest.raises(ValueError): + a = array([[1, 2, 3], + [4, 5, 6]]) + b = array([[1, 2], + [3, 4]]) + khatri_rao(a, b) + + def test_to_assure_2d_array(self): + with pytest.raises(ValueError): + # both arrays are 1-D + a = array([1, 2, 3]) + b = array([4, 5, 6]) + khatri_rao(a, b) + + with pytest.raises(ValueError): + # first array is 1-D + a = array([1, 2, 3]) + b = array([ + [1, 2, 3], + [4, 5, 6] + ]) + khatri_rao(a, b) + + with pytest.raises(ValueError): + # second array is 1-D + a = array([ + [1, 2, 3], + [7, 8, 9] + ]) + b = array([4, 5, 6]) + khatri_rao(a, b) + + def test_equality_of_two_equations(self): + a = array([[1, 2], [3, 4]]) + b = array([[5, 6], [7, 8]]) + + res1 = khatri_rao(a, b) + res2 = np.vstack([np.kron(a[:, k], b[:, k]) + for k in range(b.shape[1])]).T + + assert_array_equal(res1, res2) + + def test_empty(self): + a = np.empty((0, 2)) + b = np.empty((3, 2)) + res = khatri_rao(a, b) + assert_allclose(res, np.empty((0, 2))) + + a = np.empty((3, 0)) + b = np.empty((5, 0)) + res = khatri_rao(a, b) + assert_allclose(res, np.empty((15, 0))) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_matmul_toeplitz.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_matmul_toeplitz.py new file mode 100644 index 0000000000000000000000000000000000000000..22f8f94fd10a5404d4013adf995bba54f76ff803 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_matmul_toeplitz.py @@ -0,0 +1,136 @@ +"""Test functions for linalg.matmul_toeplitz function +""" + +import numpy as np +from scipy.linalg import toeplitz, matmul_toeplitz + +from pytest import raises as assert_raises +from numpy.testing import assert_allclose + + +class TestMatmulToeplitz: + + def setup_method(self): + self.rng = np.random.RandomState(42) + self.tolerance = 1.5e-13 + + def test_real(self): + cases = [] + + n = 1 + c = self.rng.normal(size=n) + r = self.rng.normal(size=n) + x = self.rng.normal(size=(n, 1)) + cases.append((x, c, r, False)) + + n = 2 + c = self.rng.normal(size=n) + r = self.rng.normal(size=n) + x = self.rng.normal(size=(n, 1)) + cases.append((x, c, r, False)) + + n = 101 + c = self.rng.normal(size=n) + r = self.rng.normal(size=n) + x = self.rng.normal(size=(n, 1)) + cases.append((x, c, r, True)) + + n = 1000 + c = self.rng.normal(size=n) + r = self.rng.normal(size=n) + x = self.rng.normal(size=(n, 1)) + cases.append((x, c, r, False)) + + n = 100 + c = self.rng.normal(size=n) + r = self.rng.normal(size=n) + x = self.rng.normal(size=(n, self.rng.randint(1, 10))) + cases.append((x, c, r, False)) + + n = 100 + c = self.rng.normal(size=(n, 1)) + r = self.rng.normal(size=(n, 1)) + x = self.rng.normal(size=(n, self.rng.randint(1, 10))) + cases.append((x, c, r, True)) + + n = 100 + c = self.rng.normal(size=(n, 1)) + r = None + x = self.rng.normal(size=(n, self.rng.randint(1, 10))) + cases.append((x, c, r, True, -1)) + + n = 100 + c = self.rng.normal(size=(n, 1)) + r = None + x = self.rng.normal(size=n) + cases.append((x, c, r, False)) + + n = 101 + c = self.rng.normal(size=n) + r = self.rng.normal(size=n-27) + x = self.rng.normal(size=(n-27, 1)) + cases.append((x, c, r, True)) + + n = 100 + c = self.rng.normal(size=n) + r = self.rng.normal(size=n//4) + x = self.rng.normal(size=(n//4, self.rng.randint(1, 10))) + cases.append((x, c, r, True)) + + [self.do(*i) for i in cases] + + def test_complex(self): + n = 127 + c = self.rng.normal(size=(n, 1)) + self.rng.normal(size=(n, 1))*1j + r = self.rng.normal(size=(n, 1)) + self.rng.normal(size=(n, 1))*1j + x = self.rng.normal(size=(n, 3)) + self.rng.normal(size=(n, 3))*1j + self.do(x, c, r, False) + + n = 100 + c = self.rng.normal(size=(n, 1)) + self.rng.normal(size=(n, 1))*1j + r = self.rng.normal(size=(n//2, 1)) +\ + self.rng.normal(size=(n//2, 1))*1j + x = self.rng.normal(size=(n//2, 3)) +\ + self.rng.normal(size=(n//2, 3))*1j + self.do(x, c, r, False) + + def test_empty(self): + c = [] + r = [] + x = [] + self.do(x, c, r, False) + + x = np.empty((0, 0)) + self.do(x, c, r, False) + + def test_exceptions(self): + + n = 100 + c = self.rng.normal(size=n) + r = self.rng.normal(size=2*n) + x = self.rng.normal(size=n) + assert_raises(ValueError, matmul_toeplitz, (c, r), x, True) + + n = 100 + c = self.rng.normal(size=n) + r = self.rng.normal(size=n) + x = self.rng.normal(size=n-1) + assert_raises(ValueError, matmul_toeplitz, (c, r), x, True) + + n = 100 + c = self.rng.normal(size=n) + r = self.rng.normal(size=n//2) + x = self.rng.normal(size=n//2-1) + assert_raises(ValueError, matmul_toeplitz, (c, r), x, True) + + # For toeplitz matrices, matmul_toeplitz() should be equivalent to @. + def do(self, x, c, r=None, check_finite=False, workers=None): + c = np.ravel(c) + if r is None: + actual = matmul_toeplitz(c, x, check_finite, workers) + else: + r = np.ravel(r) + actual = matmul_toeplitz((c, r), x, check_finite) + desired = toeplitz(c, r) @ x + assert_allclose(actual, desired, + rtol=self.tolerance, atol=self.tolerance) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_procrustes.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_procrustes.py new file mode 100644 index 0000000000000000000000000000000000000000..4efa433c2cab01a4f77ef1c4f1bde3ab4d5c421b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_procrustes.py @@ -0,0 +1,221 @@ +from itertools import product, permutations + +import numpy as np +import pytest +from numpy.testing import assert_array_less, assert_allclose +from pytest import raises as assert_raises + +from scipy.linalg import inv, eigh, norm, svd +from scipy.linalg import orthogonal_procrustes +from scipy.sparse._sputils import matrix + + +def test_orthogonal_procrustes_ndim_too_large(): + rng = np.random.RandomState(1234) + A = rng.randn(3, 4, 5) + B = rng.randn(3, 4, 5) + assert_raises(ValueError, orthogonal_procrustes, A, B) + + +def test_orthogonal_procrustes_ndim_too_small(): + rng = np.random.RandomState(1234) + A = rng.randn(3) + B = rng.randn(3) + assert_raises(ValueError, orthogonal_procrustes, A, B) + + +def test_orthogonal_procrustes_shape_mismatch(): + rng = np.random.RandomState(1234) + shapes = ((3, 3), (3, 4), (4, 3), (4, 4)) + for a, b in permutations(shapes, 2): + A = rng.randn(*a) + B = rng.randn(*b) + assert_raises(ValueError, orthogonal_procrustes, A, B) + + +def test_orthogonal_procrustes_checkfinite_exception(): + rng = np.random.RandomState(1234) + m, n = 2, 3 + A_good = rng.randn(m, n) + B_good = rng.randn(m, n) + for bad_value in np.inf, -np.inf, np.nan: + A_bad = A_good.copy() + A_bad[1, 2] = bad_value + B_bad = B_good.copy() + B_bad[1, 2] = bad_value + for A, B in ((A_good, B_bad), (A_bad, B_good), (A_bad, B_bad)): + assert_raises(ValueError, orthogonal_procrustes, A, B) + + +def test_orthogonal_procrustes_scale_invariance(): + rng = np.random.RandomState(1234) + m, n = 4, 3 + for i in range(3): + A_orig = rng.randn(m, n) + B_orig = rng.randn(m, n) + R_orig, s = orthogonal_procrustes(A_orig, B_orig) + for A_scale in np.square(rng.randn(3)): + for B_scale in np.square(rng.randn(3)): + R, s = orthogonal_procrustes(A_orig * A_scale, B_orig * B_scale) + assert_allclose(R, R_orig) + + +def test_orthogonal_procrustes_array_conversion(): + rng = np.random.RandomState(1234) + for m, n in ((6, 4), (4, 4), (4, 6)): + A_arr = rng.randn(m, n) + B_arr = rng.randn(m, n) + As = (A_arr, A_arr.tolist(), matrix(A_arr)) + Bs = (B_arr, B_arr.tolist(), matrix(B_arr)) + R_arr, s = orthogonal_procrustes(A_arr, B_arr) + AR_arr = A_arr.dot(R_arr) + for A, B in product(As, Bs): + R, s = orthogonal_procrustes(A, B) + AR = A_arr.dot(R) + assert_allclose(AR, AR_arr) + + +def test_orthogonal_procrustes(): + rng = np.random.RandomState(1234) + for m, n in ((6, 4), (4, 4), (4, 6)): + # Sample a random target matrix. + B = rng.randn(m, n) + # Sample a random orthogonal matrix + # by computing eigh of a sampled symmetric matrix. + X = rng.randn(n, n) + w, V = eigh(X.T + X) + assert_allclose(inv(V), V.T) + # Compute a matrix with a known orthogonal transformation that gives B. + A = np.dot(B, V.T) + # Check that an orthogonal transformation from A to B can be recovered. + R, s = orthogonal_procrustes(A, B) + assert_allclose(inv(R), R.T) + assert_allclose(A.dot(R), B) + # Create a perturbed input matrix. + A_perturbed = A + 1e-2 * rng.randn(m, n) + # Check that the orthogonal procrustes function can find an orthogonal + # transformation that is better than the orthogonal transformation + # computed from the original input matrix. + R_prime, s = orthogonal_procrustes(A_perturbed, B) + assert_allclose(inv(R_prime), R_prime.T) + # Compute the naive and optimal transformations of the perturbed input. + naive_approx = A_perturbed.dot(R) + optim_approx = A_perturbed.dot(R_prime) + # Compute the Frobenius norm errors of the matrix approximations. + naive_approx_error = norm(naive_approx - B, ord='fro') + optim_approx_error = norm(optim_approx - B, ord='fro') + # Check that the orthogonal Procrustes approximation is better. + assert_array_less(optim_approx_error, naive_approx_error) + + +def _centered(A): + mu = A.mean(axis=0) + return A - mu, mu + + +def test_orthogonal_procrustes_exact_example(): + # Check a small application. + # It uses translation, scaling, reflection, and rotation. + # + # | + # a b | + # | + # d c | w + # | + # --------+--- x ----- z --- + # | + # | y + # | + # + A_orig = np.array([[-3, 3], [-2, 3], [-2, 2], [-3, 2]], dtype=float) + B_orig = np.array([[3, 2], [1, 0], [3, -2], [5, 0]], dtype=float) + A, A_mu = _centered(A_orig) + B, B_mu = _centered(B_orig) + R, s = orthogonal_procrustes(A, B) + scale = s / np.square(norm(A)) + B_approx = scale * np.dot(A, R) + B_mu + assert_allclose(B_approx, B_orig, atol=1e-8) + + +def test_orthogonal_procrustes_stretched_example(): + # Try again with a target with a stretched y axis. + A_orig = np.array([[-3, 3], [-2, 3], [-2, 2], [-3, 2]], dtype=float) + B_orig = np.array([[3, 40], [1, 0], [3, -40], [5, 0]], dtype=float) + A, A_mu = _centered(A_orig) + B, B_mu = _centered(B_orig) + R, s = orthogonal_procrustes(A, B) + scale = s / np.square(norm(A)) + B_approx = scale * np.dot(A, R) + B_mu + expected = np.array([[3, 21], [-18, 0], [3, -21], [24, 0]], dtype=float) + assert_allclose(B_approx, expected, atol=1e-8) + # Check disparity symmetry. + expected_disparity = 0.4501246882793018 + AB_disparity = np.square(norm(B_approx - B_orig) / norm(B)) + assert_allclose(AB_disparity, expected_disparity) + R, s = orthogonal_procrustes(B, A) + scale = s / np.square(norm(B)) + A_approx = scale * np.dot(B, R) + A_mu + BA_disparity = np.square(norm(A_approx - A_orig) / norm(A)) + assert_allclose(BA_disparity, expected_disparity) + + +def test_orthogonal_procrustes_skbio_example(): + # This transformation is also exact. + # It uses translation, scaling, and reflection. + # + # | + # | a + # | b + # | c d + # --+--------- + # | + # | w + # | + # | x + # | + # | z y + # | + # + A_orig = np.array([[4, -2], [4, -4], [4, -6], [2, -6]], dtype=float) + B_orig = np.array([[1, 3], [1, 2], [1, 1], [2, 1]], dtype=float) + B_standardized = np.array([ + [-0.13363062, 0.6681531], + [-0.13363062, 0.13363062], + [-0.13363062, -0.40089186], + [0.40089186, -0.40089186]]) + A, A_mu = _centered(A_orig) + B, B_mu = _centered(B_orig) + R, s = orthogonal_procrustes(A, B) + scale = s / np.square(norm(A)) + B_approx = scale * np.dot(A, R) + B_mu + assert_allclose(B_approx, B_orig) + assert_allclose(B / norm(B), B_standardized) + + +def test_empty(): + a = np.empty((0, 0)) + r, s = orthogonal_procrustes(a, a) + assert_allclose(r, np.empty((0, 0))) + + a = np.empty((0, 3)) + r, s = orthogonal_procrustes(a, a) + assert_allclose(r, np.identity(3)) + + +@pytest.mark.parametrize('shape', [(4, 5), (5, 5), (5, 4)]) +def test_unitary(shape): + # gh-12071 added support for unitary matrices; check that it + # works as intended. + m, n = shape + rng = np.random.default_rng(589234981235) + A = rng.random(shape) + rng.random(shape) * 1j + Q = rng.random((n, n)) + rng.random((n, n)) * 1j + Q, _ = np.linalg.qr(Q) + B = A @ Q + R, scale = orthogonal_procrustes(A, B) + assert_allclose(R @ R.conj().T, np.eye(n), atol=1e-14) + assert_allclose(A @ Q, B) + if shape != (4, 5): # solution is unique + assert_allclose(R, Q) + _, s, _ = svd(A.conj().T @ B) + assert_allclose(scale, np.sum(s)) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_sketches.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_sketches.py new file mode 100644 index 0000000000000000000000000000000000000000..7fc5a8540510f57a2b00334b5e190d4ddd474d09 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_sketches.py @@ -0,0 +1,118 @@ +"""Tests for _sketches.py.""" + +import numpy as np +from numpy.testing import assert_, assert_equal +from scipy.linalg import clarkson_woodruff_transform +from scipy.linalg._sketches import cwt_matrix +from scipy.sparse import issparse, rand +from scipy.sparse.linalg import norm + + +class TestClarksonWoodruffTransform: + """ + Testing the Clarkson Woodruff Transform + """ + # set seed for generating test matrices + rng = np.random.default_rng(1179103485) + + # Test matrix parameters + n_rows = 2000 + n_cols = 100 + density = 0.1 + + # Sketch matrix dimensions + n_sketch_rows = 200 + + # Seeds to test with + seeds = [1755490010, 934377150, 1391612830, 1752708722, 2008891431, + 1302443994, 1521083269, 1501189312, 1126232505, 1533465685] + + A_dense = rng.random((n_rows, n_cols)) + A_csc = rand( + n_rows, n_cols, density=density, format='csc', random_state=rng, + ) + A_csr = rand( + n_rows, n_cols, density=density, format='csr', random_state=rng, + ) + A_coo = rand( + n_rows, n_cols, density=density, format='coo', random_state=rng, + ) + + # Collect the test matrices + test_matrices = [ + A_dense, A_csc, A_csr, A_coo, + ] + + # Test vector with norm ~1 + x = rng.random((n_rows, 1)) / np.sqrt(n_rows) + + def test_sketch_dimensions(self): + for A in self.test_matrices: + for seed in self.seeds: + # seed to ensure backwards compatibility post SPEC7 + sketch = clarkson_woodruff_transform( + A, self.n_sketch_rows, seed=seed + ) + assert_(sketch.shape == (self.n_sketch_rows, self.n_cols)) + + def test_seed_returns_identical_transform_matrix(self): + for seed in self.seeds: + S1 = cwt_matrix( + self.n_sketch_rows, self.n_rows, rng=seed + ).toarray() + S2 = cwt_matrix( + self.n_sketch_rows, self.n_rows, rng=seed + ).toarray() + assert_equal(S1, S2) + + def test_seed_returns_identically(self): + for A in self.test_matrices: + for seed in self.seeds: + sketch1 = clarkson_woodruff_transform( + A, self.n_sketch_rows, rng=seed + ) + sketch2 = clarkson_woodruff_transform( + A, self.n_sketch_rows, rng=seed + ) + if issparse(sketch1): + sketch1 = sketch1.toarray() + if issparse(sketch2): + sketch2 = sketch2.toarray() + assert_equal(sketch1, sketch2) + + def test_sketch_preserves_frobenius_norm(self): + # Given the probabilistic nature of the sketches + # we run the test multiple times and check that + # we pass all/almost all the tries. + n_errors = 0 + for A in self.test_matrices: + if issparse(A): + true_norm = norm(A) + else: + true_norm = np.linalg.norm(A) + for seed in self.seeds: + sketch = clarkson_woodruff_transform( + A, self.n_sketch_rows, rng=seed, + ) + if issparse(sketch): + sketch_norm = norm(sketch) + else: + sketch_norm = np.linalg.norm(sketch) + + if np.abs(true_norm - sketch_norm) > 0.1 * true_norm: + n_errors += 1 + assert_(n_errors == 0) + + def test_sketch_preserves_vector_norm(self): + n_errors = 0 + n_sketch_rows = int(np.ceil(2. / (0.01 * 0.5**2))) + true_norm = np.linalg.norm(self.x) + for seed in self.seeds: + sketch = clarkson_woodruff_transform( + self.x, n_sketch_rows, rng=seed, + ) + sketch_norm = np.linalg.norm(sketch) + + if np.abs(true_norm - sketch_norm) > 0.5 * true_norm: + n_errors += 1 + assert_(n_errors == 0) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_solve_toeplitz.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_solve_toeplitz.py new file mode 100644 index 0000000000000000000000000000000000000000..440a73abc8c83bc32887c37c75577b790f3f1be9 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_solve_toeplitz.py @@ -0,0 +1,150 @@ +"""Test functions for linalg._solve_toeplitz module +""" +import numpy as np +from scipy.linalg._solve_toeplitz import levinson +from scipy.linalg import solve, toeplitz, solve_toeplitz, matmul_toeplitz +from numpy.testing import assert_equal, assert_allclose + +import pytest +from pytest import raises as assert_raises + + +def test_solve_equivalence(): + # For toeplitz matrices, solve_toeplitz() should be equivalent to solve(). + random = np.random.RandomState(1234) + for n in (1, 2, 3, 10): + c = random.randn(n) + if random.rand() < 0.5: + c = c + 1j * random.randn(n) + r = random.randn(n) + if random.rand() < 0.5: + r = r + 1j * random.randn(n) + y = random.randn(n) + if random.rand() < 0.5: + y = y + 1j * random.randn(n) + + # Check equivalence when both the column and row are provided. + actual = solve_toeplitz((c,r), y) + desired = solve(toeplitz(c, r=r), y) + assert_allclose(actual, desired) + + # Check equivalence when the column is provided but not the row. + actual = solve_toeplitz(c, b=y) + desired = solve(toeplitz(c), y) + assert_allclose(actual, desired) + + +def test_multiple_rhs(): + random = np.random.RandomState(1234) + c = random.randn(4) + r = random.randn(4) + for offset in [0, 1j]: + for yshape in ((4,), (4, 3), (4, 3, 2)): + y = random.randn(*yshape) + offset + actual = solve_toeplitz((c,r), b=y) + desired = solve(toeplitz(c, r=r), y) + assert_equal(actual.shape, yshape) + assert_equal(desired.shape, yshape) + assert_allclose(actual, desired) + + +def test_native_list_arguments(): + c = [1,2,4,7] + r = [1,3,9,12] + y = [5,1,4,2] + actual = solve_toeplitz((c,r), y) + desired = solve(toeplitz(c, r=r), y) + assert_allclose(actual, desired) + + +def test_zero_diag_error(): + # The Levinson-Durbin implementation fails when the diagonal is zero. + random = np.random.RandomState(1234) + n = 4 + c = random.randn(n) + r = random.randn(n) + y = random.randn(n) + c[0] = 0 + assert_raises(np.linalg.LinAlgError, + solve_toeplitz, (c, r), b=y) + + +def test_wikipedia_counterexample(): + # The Levinson-Durbin implementation also fails in other cases. + # This example is from the talk page of the wikipedia article. + random = np.random.RandomState(1234) + c = [2, 2, 1] + y = random.randn(3) + assert_raises(np.linalg.LinAlgError, solve_toeplitz, c, b=y) + + +def test_reflection_coeffs(): + # check that the partial solutions are given by the reflection + # coefficients + + random = np.random.RandomState(1234) + y_d = random.randn(10) + y_z = random.randn(10) + 1j + reflection_coeffs_d = [1] + reflection_coeffs_z = [1] + for i in range(2, 10): + reflection_coeffs_d.append(solve_toeplitz(y_d[:(i-1)], b=y_d[1:i])[-1]) + reflection_coeffs_z.append(solve_toeplitz(y_z[:(i-1)], b=y_z[1:i])[-1]) + + y_d_concat = np.concatenate((y_d[-2:0:-1], y_d[:-1])) + y_z_concat = np.concatenate((y_z[-2:0:-1].conj(), y_z[:-1])) + _, ref_d = levinson(y_d_concat, b=y_d[1:]) + _, ref_z = levinson(y_z_concat, b=y_z[1:]) + + assert_allclose(reflection_coeffs_d, ref_d[:-1]) + assert_allclose(reflection_coeffs_z, ref_z[:-1]) + + +@pytest.mark.xfail(reason='Instability of Levinson iteration') +def test_unstable(): + # this is a "Gaussian Toeplitz matrix", as mentioned in Example 2 of + # I. Gohbert, T. Kailath and V. Olshevsky "Fast Gaussian Elimination with + # Partial Pivoting for Matrices with Displacement Structure" + # Mathematics of Computation, 64, 212 (1995), pp 1557-1576 + # which can be unstable for levinson recursion. + + # other fast toeplitz solvers such as GKO or Burg should be better. + random = np.random.RandomState(1234) + n = 100 + c = 0.9 ** (np.arange(n)**2) + y = random.randn(n) + + solution1 = solve_toeplitz(c, b=y) + solution2 = solve(toeplitz(c), y) + + assert_allclose(solution1, solution2) + + +@pytest.mark.parametrize('dt_c', [int, float, np.float32, complex, np.complex64]) +@pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64]) +def test_empty(dt_c, dt_b): + c = np.array([], dtype=dt_c) + b = np.array([], dtype=dt_b) + x = solve_toeplitz(c, b) + assert x.shape == (0,) + assert x.dtype == solve_toeplitz(np.array([2, 1], dtype=dt_c), + np.ones(2, dtype=dt_b)).dtype + + b = np.empty((0, 0), dtype=dt_b) + x1 = solve_toeplitz(c, b) + assert x1.shape == (0, 0) + assert x1.dtype == x.dtype + + +@pytest.mark.parametrize('fun', [solve_toeplitz, matmul_toeplitz]) +def test_nd_FutureWarning(fun): + # Test future warnings with n-D `c`/`r` + rng = np.random.default_rng(283592436523456) + c = rng.random((2, 3, 4)) + r = rng.random((2, 3, 4)) + b_or_x = rng.random(24) + message = "Beginning in SciPy 1.17, multidimensional input will be..." + with pytest.warns(FutureWarning, match=message): + fun(c, b_or_x) + with pytest.warns(FutureWarning, match=message): + fun((c, r), b_or_x) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_solvers.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_solvers.py new file mode 100644 index 0000000000000000000000000000000000000000..a4a39c5e86939bddabafaaf87c643c0a4ad570fe --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_solvers.py @@ -0,0 +1,844 @@ +import os +import numpy as np + +from numpy.testing import assert_array_almost_equal, assert_allclose +import pytest +from pytest import raises as assert_raises + +from scipy.linalg import solve_sylvester +from scipy.linalg import solve_continuous_lyapunov, solve_discrete_lyapunov +from scipy.linalg import solve_continuous_are, solve_discrete_are +from scipy.linalg import block_diag, solve, LinAlgError +from scipy.sparse._sputils import matrix + + +# dtypes for testing size-0 case following precedent set in gh-20295 +dtypes = [int, float, np.float32, complex, np.complex64] + + +def _load_data(name): + """ + Load npz data file under data/ + Returns a copy of the data, rather than keeping the npz file open. + """ + filename = os.path.join(os.path.abspath(os.path.dirname(__file__)), + 'data', name) + with np.load(filename) as f: + return dict(f.items()) + + +class TestSolveLyapunov: + + cases = [ + # empty case + (np.empty((0, 0)), + np.empty((0, 0))), + (np.array([[1, 2], [3, 4]]), + np.array([[9, 10], [11, 12]])), + # a, q all complex. + (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]), + np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])), + # a real; q complex. + (np.array([[1.0, 2.0], [3.0, 5.0]]), + np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])), + # a complex; q real. + (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]), + np.array([[2.0, 2.0], [-1.0, 2.0]])), + # An example from Kitagawa, 1977 + (np.array([[3, 9, 5, 1, 4], [1, 2, 3, 8, 4], [4, 6, 6, 6, 3], + [1, 5, 2, 0, 7], [5, 3, 3, 1, 5]]), + np.array([[2, 4, 1, 0, 1], [4, 1, 0, 2, 0], [1, 0, 3, 0, 3], + [0, 2, 0, 1, 0], [1, 0, 3, 0, 4]])), + # Companion matrix example. a complex; q real; a.shape[0] = 11 + (np.array([[0.100+0.j, 0.091+0.j, 0.082+0.j, 0.073+0.j, 0.064+0.j, + 0.055+0.j, 0.046+0.j, 0.037+0.j, 0.028+0.j, 0.019+0.j, + 0.010+0.j], + [1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, + 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, + 0.000+0.j], + [0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, + 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, + 0.000+0.j], + [0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j, + 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, + 0.000+0.j], + [0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j, + 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, + 0.000+0.j], + [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j, + 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, + 0.000+0.j], + [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, + 1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, + 0.000+0.j], + [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, + 0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, + 0.000+0.j], + [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, + 0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j, + 0.000+0.j], + [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, + 0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j, + 0.000+0.j], + [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, + 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j, + 0.000+0.j]]), + np.eye(11)), + # https://github.com/scipy/scipy/issues/4176 + (matrix([[0, 1], [-1/2, -1]]), + (matrix([0, 3]).T @ matrix([0, 3]).T.T)), + # https://github.com/scipy/scipy/issues/4176 + (matrix([[0, 1], [-1/2, -1]]), + (np.array(matrix([0, 3]).T @ matrix([0, 3]).T.T))), + ] + + def test_continuous_squareness_and_shape(self): + nsq = np.ones((3, 2)) + sq = np.eye(3) + assert_raises(ValueError, solve_continuous_lyapunov, nsq, sq) + assert_raises(ValueError, solve_continuous_lyapunov, sq, nsq) + assert_raises(ValueError, solve_continuous_lyapunov, sq, np.eye(2)) + + def check_continuous_case(self, a, q): + x = solve_continuous_lyapunov(a, q) + assert_array_almost_equal( + np.dot(a, x) + np.dot(x, a.conj().transpose()), q) + + def check_discrete_case(self, a, q, method=None): + x = solve_discrete_lyapunov(a, q, method=method) + assert_array_almost_equal( + np.dot(np.dot(a, x), a.conj().transpose()) - x, -1.0*q) + + def test_cases(self): + for case in self.cases: + self.check_continuous_case(case[0], case[1]) + self.check_discrete_case(case[0], case[1]) + self.check_discrete_case(case[0], case[1], method='direct') + self.check_discrete_case(case[0], case[1], method='bilinear') + + @pytest.mark.parametrize("dtype_a", dtypes) + @pytest.mark.parametrize("dtype_q", dtypes) + def test_size_0(self, dtype_a, dtype_q): + rng = np.random.default_rng(234598235) + + a = np.zeros((0, 0), dtype=dtype_a) + q = np.zeros((0, 0), dtype=dtype_q) + res = solve_continuous_lyapunov(a, q) + + a = (rng.random((5, 5))*100).astype(dtype_a) + q = (rng.random((5, 5))*100).astype(dtype_q) + ref = solve_continuous_lyapunov(a, q) + + assert res.shape == (0, 0) + assert res.dtype == ref.dtype + + +class TestSolveContinuousAre: + mat6 = _load_data('carex_6_data.npz') + mat15 = _load_data('carex_15_data.npz') + mat18 = _load_data('carex_18_data.npz') + mat19 = _load_data('carex_19_data.npz') + mat20 = _load_data('carex_20_data.npz') + cases = [ + # Carex examples taken from (with default parameters): + # [1] P.BENNER, A.J. LAUB, V. MEHRMANN: 'A Collection of Benchmark + # Examples for the Numerical Solution of Algebraic Riccati + # Equations II: Continuous-Time Case', Tech. Report SPC 95_23, + # Fak. f. Mathematik, TU Chemnitz-Zwickau (Germany), 1995. + # + # The format of the data is (a, b, q, r, knownfailure), where + # knownfailure is None if the test passes or a string + # indicating the reason for failure. + # + # Test Case 0: carex #1 + (np.diag([1.], 1), + np.array([[0], [1]]), + block_diag(1., 2.), + 1, + None), + # Test Case 1: carex #2 + (np.array([[4, 3], [-4.5, -3.5]]), + np.array([[1], [-1]]), + np.array([[9, 6], [6, 4.]]), + 1, + None), + # Test Case 2: carex #3 + (np.array([[0, 1, 0, 0], + [0, -1.89, 0.39, -5.53], + [0, -0.034, -2.98, 2.43], + [0.034, -0.0011, -0.99, -0.21]]), + np.array([[0, 0], [0.36, -1.6], [-0.95, -0.032], [0.03, 0]]), + np.array([[2.313, 2.727, 0.688, 0.023], + [2.727, 4.271, 1.148, 0.323], + [0.688, 1.148, 0.313, 0.102], + [0.023, 0.323, 0.102, 0.083]]), + np.eye(2), + None), + # Test Case 3: carex #4 + (np.array([[-0.991, 0.529, 0, 0, 0, 0, 0, 0], + [0.522, -1.051, 0.596, 0, 0, 0, 0, 0], + [0, 0.522, -1.118, 0.596, 0, 0, 0, 0], + [0, 0, 0.522, -1.548, 0.718, 0, 0, 0], + [0, 0, 0, 0.922, -1.64, 0.799, 0, 0], + [0, 0, 0, 0, 0.922, -1.721, 0.901, 0], + [0, 0, 0, 0, 0, 0.922, -1.823, 1.021], + [0, 0, 0, 0, 0, 0, 0.922, -1.943]]), + np.array([[3.84, 4.00, 37.60, 3.08, 2.36, 2.88, 3.08, 3.00], + [-2.88, -3.04, -2.80, -2.32, -3.32, -3.82, -4.12, -3.96]] + ).T * 0.001, + np.array([[1.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.1], + [0.0, 1.0, 0.0, 0.0, 0.1, 0.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0, 0.0, 0.5, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0], + [0.5, 0.1, 0.0, 0.0, 0.1, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.5, 0.0, 0.0, 0.1, 0.0, 0.0], + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.1, 0.0], + [0.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.1]]), + np.eye(2), + None), + # Test Case 4: carex #5 + (np.array( + [[-4.019, 5.120, 0., 0., -2.082, 0., 0., 0., 0.870], + [-0.346, 0.986, 0., 0., -2.340, 0., 0., 0., 0.970], + [-7.909, 15.407, -4.069, 0., -6.450, 0., 0., 0., 2.680], + [-21.816, 35.606, -0.339, -3.870, -17.800, 0., 0., 0., 7.390], + [-60.196, 98.188, -7.907, 0.340, -53.008, 0., 0., 0., 20.400], + [0, 0, 0, 0, 94.000, -147.200, 0., 53.200, 0.], + [0, 0, 0, 0, 0, 94.000, -147.200, 0, 0], + [0, 0, 0, 0, 0, 12.800, 0.000, -31.600, 0], + [0, 0, 0, 0, 12.800, 0.000, 0.000, 18.800, -31.600]]), + np.array([[0.010, -0.011, -0.151], + [0.003, -0.021, 0.000], + [0.009, -0.059, 0.000], + [0.024, -0.162, 0.000], + [0.068, -0.445, 0.000], + [0.000, 0.000, 0.000], + [0.000, 0.000, 0.000], + [0.000, 0.000, 0.000], + [0.000, 0.000, 0.000]]), + np.eye(9), + np.eye(3), + None), + # Test Case 5: carex #6 + (mat6['A'], mat6['B'], mat6['Q'], mat6['R'], None), + # Test Case 6: carex #7 + (np.array([[1, 0], [0, -2.]]), + np.array([[1e-6], [0]]), + np.ones((2, 2)), + 1., + 'Bad residual accuracy'), + # Test Case 7: carex #8 + (block_diag(-0.1, -0.02), + np.array([[0.100, 0.000], [0.001, 0.010]]), + np.array([[100, 1000], [1000, 10000]]), + np.ones((2, 2)) + block_diag(1e-6, 0), + None), + # Test Case 8: carex #9 + (np.array([[0, 1e6], [0, 0]]), + np.array([[0], [1.]]), + np.eye(2), + 1., + None), + # Test Case 9: carex #10 + (np.array([[1.0000001, 1], [1., 1.0000001]]), + np.eye(2), + np.eye(2), + np.eye(2), + None), + # Test Case 10: carex #11 + (np.array([[3, 1.], [4, 2]]), + np.array([[1], [1]]), + np.array([[-11, -5], [-5, -2.]]), + 1., + None), + # Test Case 11: carex #12 + (np.array([[7000000., 2000000., -0.], + [2000000., 6000000., -2000000.], + [0., -2000000., 5000000.]]) / 3, + np.eye(3), + np.array([[1., -2., -2.], [-2., 1., -2.], [-2., -2., 1.]]).dot( + np.diag([1e-6, 1, 1e6])).dot( + np.array([[1., -2., -2.], [-2., 1., -2.], [-2., -2., 1.]])) / 9, + np.eye(3) * 1e6, + 'Bad Residual Accuracy'), + # Test Case 12: carex #13 + (np.array([[0, 0.4, 0, 0], + [0, 0, 0.345, 0], + [0, -0.524e6, -0.465e6, 0.262e6], + [0, 0, 0, -1e6]]), + np.array([[0, 0, 0, 1e6]]).T, + np.diag([1, 0, 1, 0]), + 1., + None), + # Test Case 13: carex #14 + (np.array([[-1e-6, 1, 0, 0], + [-1, -1e-6, 0, 0], + [0, 0, 1e-6, 1], + [0, 0, -1, 1e-6]]), + np.ones((4, 1)), + np.ones((4, 4)), + 1., + None), + # Test Case 14: carex #15 + (mat15['A'], mat15['B'], mat15['Q'], mat15['R'], None), + # Test Case 15: carex #16 + (np.eye(64, 64, k=-1) + np.eye(64, 64)*(-2.) + np.rot90( + block_diag(1, np.zeros((62, 62)), 1)) + np.eye(64, 64, k=1), + np.eye(64), + np.eye(64), + np.eye(64), + None), + # Test Case 16: carex #17 + (np.diag(np.ones((20, )), 1), + np.flipud(np.eye(21, 1)), + np.eye(21, 1) * np.eye(21, 1).T, + 1, + 'Bad Residual Accuracy'), + # Test Case 17: carex #18 + (mat18['A'], mat18['B'], mat18['Q'], mat18['R'], None), + # Test Case 18: carex #19 + (mat19['A'], mat19['B'], mat19['Q'], mat19['R'], + 'Bad Residual Accuracy'), + # Test Case 19: carex #20 + (mat20['A'], mat20['B'], mat20['Q'], mat20['R'], + 'Bad Residual Accuracy') + ] + # Makes the minimum precision requirements customized to the test. + # Here numbers represent the number of decimals that agrees with zero + # matrix when the solution x is plugged in to the equation. + # + # res = array([[8e-3,1e-16],[1e-16,1e-20]]) --> min_decimal[k] = 2 + # + # If the test is failing use "None" for that entry. + # + min_decimal = (14, 12, 13, 14, 11, 6, None, 5, 7, 14, 14, + None, 9, 14, 13, 14, None, 12, None, None) + + @pytest.mark.parametrize("j, case", enumerate(cases)) + def test_solve_continuous_are(self, j, case): + """Checks if 0 = XA + A'X - XB(R)^{-1} B'X + Q is true""" + a, b, q, r, knownfailure = case + if knownfailure: + pytest.xfail(reason=knownfailure) + + dec = self.min_decimal[j] + x = solve_continuous_are(a, b, q, r) + res = x @ a + a.conj().T @ x + q + out_fact = x @ b + res -= out_fact @ solve(np.atleast_2d(r), out_fact.conj().T) + assert_array_almost_equal(res, np.zeros_like(res), decimal=dec) + + +class TestSolveDiscreteAre: + cases = [ + # Darex examples taken from (with default parameters): + # [1] P.BENNER, A.J. LAUB, V. MEHRMANN: 'A Collection of Benchmark + # Examples for the Numerical Solution of Algebraic Riccati + # Equations II: Discrete-Time Case', Tech. Report SPC 95_23, + # Fak. f. Mathematik, TU Chemnitz-Zwickau (Germany), 1995. + # [2] T. GUDMUNDSSON, C. KENNEY, A.J. LAUB: 'Scaling of the + # Discrete-Time Algebraic Riccati Equation to Enhance Stability + # of the Schur Solution Method', IEEE Trans.Aut.Cont., vol.37(4) + # + # The format of the data is (a, b, q, r, knownfailure), where + # knownfailure is None if the test passes or a string + # indicating the reason for failure. + # + # TEST CASE 0 : Complex a; real b, q, r + (np.array([[2, 1-2j], [0, -3j]]), + np.array([[0], [1]]), + np.array([[1, 0], [0, 2]]), + np.array([[1]]), + None), + # TEST CASE 1 :Real a, q, r; complex b + (np.array([[2, 1], [0, -1]]), + np.array([[-2j], [1j]]), + np.array([[1, 0], [0, 2]]), + np.array([[1]]), + None), + # TEST CASE 2 : Real a, b; complex q, r + (np.array([[3, 1], [0, -1]]), + np.array([[1, 2], [1, 3]]), + np.array([[1, 1+1j], [1-1j, 2]]), + np.array([[2, -2j], [2j, 3]]), + None), + # TEST CASE 3 : User-reported gh-2251 (Trac #1732) + (np.array([[0.63399379, 0.54906824, 0.76253406], + [0.5404729, 0.53745766, 0.08731853], + [0.27524045, 0.84922129, 0.4681622]]), + np.array([[0.96861695], [0.05532739], [0.78934047]]), + np.eye(3), + np.eye(1), + None), + # TEST CASE 4 : darex #1 + (np.array([[4, 3], [-4.5, -3.5]]), + np.array([[1], [-1]]), + np.array([[9, 6], [6, 4]]), + np.array([[1]]), + None), + # TEST CASE 5 : darex #2 + (np.array([[0.9512, 0], [0, 0.9048]]), + np.array([[4.877, 4.877], [-1.1895, 3.569]]), + np.array([[0.005, 0], [0, 0.02]]), + np.array([[1/3, 0], [0, 3]]), + None), + # TEST CASE 6 : darex #3 + (np.array([[2, -1], [1, 0]]), + np.array([[1], [0]]), + np.array([[0, 0], [0, 1]]), + np.array([[0]]), + None), + # TEST CASE 7 : darex #4 (skipped the gen. Ric. term S) + (np.array([[0, 1], [0, -1]]), + np.array([[1, 0], [2, 1]]), + np.array([[-4, -4], [-4, 7]]) * (1/11), + np.array([[9, 3], [3, 1]]), + None), + # TEST CASE 8 : darex #5 + (np.array([[0, 1], [0, 0]]), + np.array([[0], [1]]), + np.array([[1, 2], [2, 4]]), + np.array([[1]]), + None), + # TEST CASE 9 : darex #6 + (np.array([[0.998, 0.067, 0, 0], + [-.067, 0.998, 0, 0], + [0, 0, 0.998, 0.153], + [0, 0, -.153, 0.998]]), + np.array([[0.0033, 0.0200], + [0.1000, -.0007], + [0.0400, 0.0073], + [-.0028, 0.1000]]), + np.array([[1.87, 0, 0, -0.244], + [0, 0.744, 0.205, 0], + [0, 0.205, 0.589, 0], + [-0.244, 0, 0, 1.048]]), + np.eye(2), + None), + # TEST CASE 10 : darex #7 + (np.array([[0.984750, -.079903, 0.0009054, -.0010765], + [0.041588, 0.998990, -.0358550, 0.0126840], + [-.546620, 0.044916, -.3299100, 0.1931800], + [2.662400, -.100450, -.9245500, -.2632500]]), + np.array([[0.0037112, 0.0007361], + [-.0870510, 9.3411e-6], + [-1.198440, -4.1378e-4], + [-3.192700, 9.2535e-4]]), + np.eye(4)*1e-2, + np.eye(2), + None), + # TEST CASE 11 : darex #8 + (np.array([[-0.6000000, -2.2000000, -3.6000000, -5.4000180], + [1.0000000, 0.6000000, 0.8000000, 3.3999820], + [0.0000000, 1.0000000, 1.8000000, 3.7999820], + [0.0000000, 0.0000000, 0.0000000, -0.9999820]]), + np.array([[1.0, -1.0, -1.0, -1.0], + [0.0, 1.0, -1.0, -1.0], + [0.0, 0.0, 1.0, -1.0], + [0.0, 0.0, 0.0, 1.0]]), + np.array([[2, 1, 3, 6], + [1, 2, 2, 5], + [3, 2, 6, 11], + [6, 5, 11, 22]]), + np.eye(4), + None), + # TEST CASE 12 : darex #9 + (np.array([[95.4070, 1.9643, 0.3597, 0.0673, 0.0190], + [40.8490, 41.3170, 16.0840, 4.4679, 1.1971], + [12.2170, 26.3260, 36.1490, 15.9300, 12.3830], + [4.1118, 12.8580, 27.2090, 21.4420, 40.9760], + [0.1305, 0.5808, 1.8750, 3.6162, 94.2800]]) * 0.01, + np.array([[0.0434, -0.0122], + [2.6606, -1.0453], + [3.7530, -5.5100], + [3.6076, -6.6000], + [0.4617, -0.9148]]) * 0.01, + np.eye(5), + np.eye(2), + None), + # TEST CASE 13 : darex #10 + (np.kron(np.eye(2), np.diag([1, 1], k=1)), + np.kron(np.eye(2), np.array([[0], [0], [1]])), + np.array([[1, 1, 0, 0, 0, 0], + [1, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, -1, 0], + [0, 0, 0, -1, 1, 0], + [0, 0, 0, 0, 0, 0]]), + np.array([[3, 0], [0, 1]]), + None), + # TEST CASE 14 : darex #11 + (0.001 * np.array( + [[870.1, 135.0, 11.59, .5014, -37.22, .3484, 0, 4.242, 7.249], + [76.55, 897.4, 12.72, 0.5504, -40.16, .3743, 0, 4.53, 7.499], + [-127.2, 357.5, 817, 1.455, -102.8, .987, 0, 11.85, 18.72], + [-363.5, 633.9, 74.91, 796.6, -273.5, 2.653, 0, 31.72, 48.82], + [-960, 1645.9, -128.9, -5.597, 71.42, 7.108, 0, 84.52, 125.9], + [-664.4, 112.96, -88.89, -3.854, 84.47, 13.6, 0, 144.3, 101.6], + [-410.2, 693, -54.71, -2.371, 66.49, 12.49, .1063, 99.97, 69.67], + [-179.9, 301.7, -23.93, -1.035, 60.59, 22.16, 0, 213.9, 35.54], + [-345.1, 580.4, -45.96, -1.989, 105.6, 19.86, 0, 219.1, 215.2]]), + np.array([[4.7600, -0.5701, -83.6800], + [0.8790, -4.7730, -2.7300], + [1.4820, -13.1200, 8.8760], + [3.8920, -35.1300, 24.8000], + [10.3400, -92.7500, 66.8000], + [7.2030, -61.5900, 38.3400], + [4.4540, -36.8300, 20.2900], + [1.9710, -15.5400, 6.9370], + [3.7730, -30.2800, 14.6900]]) * 0.001, + np.diag([50, 0, 0, 0, 50, 0, 0, 0, 0]), + np.eye(3), + None), + # TEST CASE 15 : darex #12 - numerically least accurate example + (np.array([[0, 1e6], [0, 0]]), + np.array([[0], [1]]), + np.eye(2), + np.array([[1]]), + None), + # TEST CASE 16 : darex #13 + (np.array([[16, 10, -2], + [10, 13, -8], + [-2, -8, 7]]) * (1/9), + np.eye(3), + 1e6 * np.eye(3), + 1e6 * np.eye(3), + None), + # TEST CASE 17 : darex #14 + (np.array([[1 - 1/1e8, 0, 0, 0], + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, 0]]), + np.array([[1e-08], [0], [0], [0]]), + np.diag([0, 0, 0, 1]), + np.array([[0.25]]), + None), + # TEST CASE 18 : darex #15 + (np.eye(100, k=1), + np.flipud(np.eye(100, 1)), + np.eye(100), + np.array([[1]]), + None) + ] + + # Makes the minimum precision requirements customized to the test. + # Here numbers represent the number of decimals that agrees with zero + # matrix when the solution x is plugged in to the equation. + # + # res = array([[8e-3,1e-16],[1e-16,1e-20]]) --> min_decimal[k] = 2 + # + # If the test is failing use "None" for that entry. + # + min_decimal = (12, 14, 13, 14, 13, 16, 18, 14, 14, 13, + 14, 13, 13, 14, 12, 2, 4, 6, 10) + max_tol = [1.5 * 10**-ind for ind in min_decimal] + # relaxed tolerance in gh-18012 after bump to OpenBLAS + max_tol[11] = 2.5e-13 + + # relaxed tolerance in gh-20335 for linux-aarch64 build on Cirrus + # with OpenBLAS from ubuntu jammy + max_tol[15] = 2.0e-2 + + # relaxed tolerance in gh-20335 for OpenBLAS 3.20 on ubuntu jammy + # bump not needed for OpenBLAS 3.26 + max_tol[16] = 2.0e-4 + + @pytest.mark.parametrize("j, case", enumerate(cases)) + def test_solve_discrete_are(self, j, case): + """Checks if X = A'XA-(A'XB)(R+B'XB)^-1(B'XA)+Q) is true""" + a, b, q, r, knownfailure = case + if knownfailure: + pytest.xfail(reason=knownfailure) + + atol = self.max_tol[j] + + x = solve_discrete_are(a, b, q, r) + bH = b.conj().T + xa, xb = x @ a, x @ b + + res = a.conj().T @ xa - x + q + res -= a.conj().T @ xb @ (solve(r + bH @ xb, bH) @ xa) + + # changed from + # assert_array_almost_equal(res, np.zeros_like(res), decimal=dec) + # in gh-18012 as it's easier to relax a tolerance and allclose is + # preferred + assert_allclose(res, np.zeros_like(res), atol=atol) + + def test_infeasible(self): + # An infeasible example taken from https://arxiv.org/abs/1505.04861v1 + A = np.triu(np.ones((3, 3))) + A[0, 1] = -1 + B = np.array([[1, 1, 0], [0, 0, 1]]).T + Q = np.full_like(A, -2) + np.diag([8, -1, -1.9]) + R = np.diag([-10, 0.1]) + assert_raises(LinAlgError, solve_continuous_are, A, B, Q, R) + + +def test_solve_generalized_continuous_are(): + cases = [ + # Two random examples differ by s term + # in the absence of any literature for demanding examples. + (np.array([[2.769230e-01, 8.234578e-01, 9.502220e-01], + [4.617139e-02, 6.948286e-01, 3.444608e-02], + [9.713178e-02, 3.170995e-01, 4.387444e-01]]), + np.array([[3.815585e-01, 1.868726e-01], + [7.655168e-01, 4.897644e-01], + [7.951999e-01, 4.455862e-01]]), + np.eye(3), + np.eye(2), + np.array([[6.463130e-01, 2.760251e-01, 1.626117e-01], + [7.093648e-01, 6.797027e-01, 1.189977e-01], + [7.546867e-01, 6.550980e-01, 4.983641e-01]]), + np.zeros((3, 2)), + None), + (np.array([[2.769230e-01, 8.234578e-01, 9.502220e-01], + [4.617139e-02, 6.948286e-01, 3.444608e-02], + [9.713178e-02, 3.170995e-01, 4.387444e-01]]), + np.array([[3.815585e-01, 1.868726e-01], + [7.655168e-01, 4.897644e-01], + [7.951999e-01, 4.455862e-01]]), + np.eye(3), + np.eye(2), + np.array([[6.463130e-01, 2.760251e-01, 1.626117e-01], + [7.093648e-01, 6.797027e-01, 1.189977e-01], + [7.546867e-01, 6.550980e-01, 4.983641e-01]]), + np.ones((3, 2)), + None) + ] + + min_decimal = (10, 10) + + def _test_factory(case, dec): + """Checks if X = A'XA-(A'XB)(R+B'XB)^-1(B'XA)+Q) is true""" + a, b, q, r, e, s, knownfailure = case + if knownfailure: + pytest.xfail(reason=knownfailure) + + x = solve_continuous_are(a, b, q, r, e, s) + res = a.conj().T.dot(x.dot(e)) + e.conj().T.dot(x.dot(a)) + q + out_fact = e.conj().T.dot(x).dot(b) + s + res -= out_fact.dot(solve(np.atleast_2d(r), out_fact.conj().T)) + assert_array_almost_equal(res, np.zeros_like(res), decimal=dec) + + for ind, case in enumerate(cases): + _test_factory(case, min_decimal[ind]) + + +def test_solve_generalized_discrete_are(): + mat20170120 = _load_data('gendare_20170120_data.npz') + + cases = [ + # Two random examples differ by s term + # in the absence of any literature for demanding examples. + (np.array([[2.769230e-01, 8.234578e-01, 9.502220e-01], + [4.617139e-02, 6.948286e-01, 3.444608e-02], + [9.713178e-02, 3.170995e-01, 4.387444e-01]]), + np.array([[3.815585e-01, 1.868726e-01], + [7.655168e-01, 4.897644e-01], + [7.951999e-01, 4.455862e-01]]), + np.eye(3), + np.eye(2), + np.array([[6.463130e-01, 2.760251e-01, 1.626117e-01], + [7.093648e-01, 6.797027e-01, 1.189977e-01], + [7.546867e-01, 6.550980e-01, 4.983641e-01]]), + np.zeros((3, 2)), + None), + (np.array([[2.769230e-01, 8.234578e-01, 9.502220e-01], + [4.617139e-02, 6.948286e-01, 3.444608e-02], + [9.713178e-02, 3.170995e-01, 4.387444e-01]]), + np.array([[3.815585e-01, 1.868726e-01], + [7.655168e-01, 4.897644e-01], + [7.951999e-01, 4.455862e-01]]), + np.eye(3), + np.eye(2), + np.array([[6.463130e-01, 2.760251e-01, 1.626117e-01], + [7.093648e-01, 6.797027e-01, 1.189977e-01], + [7.546867e-01, 6.550980e-01, 4.983641e-01]]), + np.ones((3, 2)), + None), + # user-reported (under PR-6616) 20-Jan-2017 + # tests against the case where E is None but S is provided + (mat20170120['A'], + mat20170120['B'], + mat20170120['Q'], + mat20170120['R'], + None, + mat20170120['S'], + None), + ] + + max_atol = (1.5e-11, 1.5e-11, 3.5e-16) + + def _test_factory(case, atol): + """Checks if X = A'XA-(A'XB)(R+B'XB)^-1(B'XA)+Q) is true""" + a, b, q, r, e, s, knownfailure = case + if knownfailure: + pytest.xfail(reason=knownfailure) + + x = solve_discrete_are(a, b, q, r, e, s) + if e is None: + e = np.eye(a.shape[0]) + if s is None: + s = np.zeros_like(b) + res = a.conj().T.dot(x.dot(a)) - e.conj().T.dot(x.dot(e)) + q + res -= (a.conj().T.dot(x.dot(b)) + s).dot( + solve(r+b.conj().T.dot(x.dot(b)), + (b.conj().T.dot(x.dot(a)) + s.conj().T) + ) + ) + # changed from: + # assert_array_almost_equal(res, np.zeros_like(res), decimal=dec) + # in gh-17950 because of a Linux 32 bit fail. + assert_allclose(res, np.zeros_like(res), atol=atol) + + for ind, case in enumerate(cases): + _test_factory(case, max_atol[ind]) + + +def test_are_validate_args(): + + def test_square_shape(): + nsq = np.ones((3, 2)) + sq = np.eye(3) + for x in (solve_continuous_are, solve_discrete_are): + assert_raises(ValueError, x, nsq, 1, 1, 1) + assert_raises(ValueError, x, sq, sq, nsq, 1) + assert_raises(ValueError, x, sq, sq, sq, nsq) + assert_raises(ValueError, x, sq, sq, sq, sq, nsq) + + def test_compatible_sizes(): + nsq = np.ones((3, 2)) + sq = np.eye(4) + for x in (solve_continuous_are, solve_discrete_are): + assert_raises(ValueError, x, sq, nsq, 1, 1) + assert_raises(ValueError, x, sq, sq, sq, sq, sq, nsq) + assert_raises(ValueError, x, sq, sq, np.eye(3), sq) + assert_raises(ValueError, x, sq, sq, sq, np.eye(3)) + assert_raises(ValueError, x, sq, sq, sq, sq, np.eye(3)) + + def test_symmetry(): + nsym = np.arange(9).reshape(3, 3) + sym = np.eye(3) + for x in (solve_continuous_are, solve_discrete_are): + assert_raises(ValueError, x, sym, sym, nsym, sym) + assert_raises(ValueError, x, sym, sym, sym, nsym) + + def test_singularity(): + sing = np.full((3, 3), 1e12) + sing[2, 2] -= 1 + sq = np.eye(3) + for x in (solve_continuous_are, solve_discrete_are): + assert_raises(ValueError, x, sq, sq, sq, sq, sing) + + assert_raises(ValueError, solve_continuous_are, sq, sq, sq, sing) + + def test_finiteness(): + nm = np.full((2, 2), np.nan) + sq = np.eye(2) + for x in (solve_continuous_are, solve_discrete_are): + assert_raises(ValueError, x, nm, sq, sq, sq) + assert_raises(ValueError, x, sq, nm, sq, sq) + assert_raises(ValueError, x, sq, sq, nm, sq) + assert_raises(ValueError, x, sq, sq, sq, nm) + assert_raises(ValueError, x, sq, sq, sq, sq, nm) + assert_raises(ValueError, x, sq, sq, sq, sq, sq, nm) + + +class TestSolveSylvester: + cases = [ + # empty cases + (np.empty((0, 0)), + np.empty((0, 0)), + np.empty((0, 0))), + (np.empty((0, 0)), + np.empty((2, 2)), + np.empty((0, 2))), + (np.empty((2, 2)), + np.empty((0, 0)), + np.empty((2, 0))), + # a, b, c all real. + (np.array([[1, 2], [0, 4]]), + np.array([[5, 6], [0, 8]]), + np.array([[9, 10], [11, 12]])), + # a, b, c all real, 4x4. a and b have non-trivial 2x2 blocks in their + # quasi-triangular form. + (np.array([[1.0, 0, 0, 0], + [0, 1.0, 2.0, 0.0], + [0, 0, 3.0, -4], + [0, 0, 2, 5]]), + np.array([[2.0, 0, 0, 1.0], + [0, 1.0, 0.0, 0.0], + [0, 0, 1.0, -1], + [0, 0, 1, 1]]), + np.array([[1.0, 0, 0, 0], + [0, 1.0, 0, 0], + [0, 0, 1.0, 0], + [0, 0, 0, 1.0]])), + # a, b, c all complex. + (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]), + np.array([[-1.0, 2j], [3.0, 4.0]]), + np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])), + # a and b real; c complex. + (np.array([[1.0, 2.0], [3.0, 5.0]]), + np.array([[-1.0, 0], [3.0, 4.0]]), + np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])), + # a and c complex; b real. + (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]), + np.array([[-1.0, 0], [3.0, 4.0]]), + np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])), + # a complex; b and c real. + (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]), + np.array([[-1.0, 0], [3.0, 4.0]]), + np.array([[2.0, 2.0], [-1.0, 2.0]])), + # not square matrices, real + (np.array([[8, 1, 6], [3, 5, 7], [4, 9, 2]]), + np.array([[2, 3], [4, 5]]), + np.array([[1, 2], [3, 4], [5, 6]])), + # not square matrices, complex + (np.array([[8, 1j, 6+2j], [3, 5, 7], [4, 9, 2]]), + np.array([[2, 3], [4, 5-1j]]), + np.array([[1, 2j], [3, 4j], [5j, 6+7j]])), + ] + + def check_case(self, a, b, c): + x = solve_sylvester(a, b, c) + assert_array_almost_equal(np.dot(a, x) + np.dot(x, b), c) + + def test_cases(self): + for case in self.cases: + self.check_case(case[0], case[1], case[2]) + + def test_trivial(self): + a = np.array([[1.0, 0.0], [0.0, 1.0]]) + b = np.array([[1.0]]) + c = np.array([2.0, 2.0]).reshape(-1, 1) + x = solve_sylvester(a, b, c) + assert_array_almost_equal(x, np.array([1.0, 1.0]).reshape(-1, 1)) + + # Feel free to adjust this to test fewer dtypes or random selections rather than + # the Cartesian product. It doesn't take very long to test all combinations, + # though, so we'll start there and trim it down as we see fit. + @pytest.mark.parametrize("dtype_a", dtypes) + @pytest.mark.parametrize("dtype_b", dtypes) + @pytest.mark.parametrize("dtype_q", dtypes) + @pytest.mark.parametrize("m", [0, 3]) + @pytest.mark.parametrize("n", [0, 3]) + def test_size_0(self, m, n, dtype_a, dtype_b, dtype_q): + if m == n != 0: + pytest.skip('m = n != 0 is not a case that needs to be tested here.') + + rng = np.random.default_rng(598435298262546) + + a = np.zeros((m, m), dtype=dtype_a) + b = np.zeros((n, n), dtype=dtype_b) + q = np.zeros((m, n), dtype=dtype_q) + res = solve_sylvester(a, b, q) + + a = (rng.random((5, 5))*100).astype(dtype_a) + b = (rng.random((6, 6))*100).astype(dtype_b) + q = (rng.random((5, 6))*100).astype(dtype_q) + ref = solve_sylvester(a, b, q) + + assert res.shape == (m, n) + assert res.dtype == ref.dtype diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_special_matrices.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_special_matrices.py new file mode 100644 index 0000000000000000000000000000000000000000..d32e7ed4b4016924c60b3ed6287888a0372e8791 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/linalg/tests/test_special_matrices.py @@ -0,0 +1,640 @@ +import pytest +import numpy as np +from numpy import arange, array, eye, copy, sqrt +from numpy.testing import (assert_equal, assert_array_equal, + assert_array_almost_equal, assert_allclose) +from pytest import raises as assert_raises + +from scipy.fft import fft +from scipy.special import comb +from scipy.linalg import (toeplitz, hankel, circulant, hadamard, leslie, dft, + companion, kron, block_diag, + helmert, hilbert, invhilbert, pascal, invpascal, + fiedler, fiedler_companion, eigvals, + convolution_matrix) +from numpy.linalg import cond + + +class TestToeplitz: + + def test_basic(self): + y = toeplitz([1, 2, 3]) + assert_array_equal(y, [[1, 2, 3], [2, 1, 2], [3, 2, 1]]) + y = toeplitz([1, 2, 3], [1, 4, 5]) + assert_array_equal(y, [[1, 4, 5], [2, 1, 4], [3, 2, 1]]) + + def test_complex_01(self): + data = (1.0 + arange(3.0)) * (1.0 + 1.0j) + x = copy(data) + t = toeplitz(x) + # Calling toeplitz should not change x. + assert_array_equal(x, data) + # According to the docstring, x should be the first column of t. + col0 = t[:, 0] + assert_array_equal(col0, data) + assert_array_equal(t[0, 1:], data[1:].conj()) + + def test_scalar_00(self): + """Scalar arguments still produce a 2D array.""" + t = toeplitz(10) + assert_array_equal(t, [[10]]) + t = toeplitz(10, 20) + assert_array_equal(t, [[10]]) + + def test_scalar_01(self): + c = array([1, 2, 3]) + t = toeplitz(c, 1) + assert_array_equal(t, [[1], [2], [3]]) + + def test_scalar_02(self): + c = array([1, 2, 3]) + t = toeplitz(c, array(1)) + assert_array_equal(t, [[1], [2], [3]]) + + def test_scalar_03(self): + c = array([1, 2, 3]) + t = toeplitz(c, array([1])) + assert_array_equal(t, [[1], [2], [3]]) + + def test_scalar_04(self): + r = array([10, 2, 3]) + t = toeplitz(1, r) + assert_array_equal(t, [[1, 2, 3]]) + + +class TestHankel: + def test_basic(self): + y = hankel([1, 2, 3]) + assert_array_equal(y, [[1, 2, 3], [2, 3, 0], [3, 0, 0]]) + y = hankel([1, 2, 3], [3, 4, 5]) + assert_array_equal(y, [[1, 2, 3], [2, 3, 4], [3, 4, 5]]) + + +class TestCirculant: + def test_basic(self): + y = circulant([1, 2, 3]) + assert_array_equal(y, [[1, 3, 2], [2, 1, 3], [3, 2, 1]]) + + +class TestHadamard: + + def test_basic(self): + + y = hadamard(1) + assert_array_equal(y, [[1]]) + + y = hadamard(2, dtype=float) + assert_array_equal(y, [[1.0, 1.0], [1.0, -1.0]]) + + y = hadamard(4) + assert_array_equal(y, [[1, 1, 1, 1], + [1, -1, 1, -1], + [1, 1, -1, -1], + [1, -1, -1, 1]]) + + assert_raises(ValueError, hadamard, 0) + assert_raises(ValueError, hadamard, 5) + + +class TestLeslie: + + def test_bad_shapes(self): + assert_raises(ValueError, leslie, [[1, 1], [2, 2]], [3, 4, 5]) + assert_raises(ValueError, leslie, [1, 2], [1, 2]) + assert_raises(ValueError, leslie, [1], []) + + def test_basic(self): + a = leslie([1, 2, 3], [0.25, 0.5]) + expected = array([[1.0, 2.0, 3.0], + [0.25, 0.0, 0.0], + [0.0, 0.5, 0.0]]) + assert_array_equal(a, expected) + + +class TestCompanion: + + def test_bad_shapes(self): + assert_raises(ValueError, companion, [0, 4, 5]) + assert_raises(ValueError, companion, [1]) + assert_raises(ValueError, companion, []) + + def test_basic(self): + c = companion([1, 2, 3]) + expected = array([ + [-2.0, -3.0], + [1.0, 0.0]]) + assert_array_equal(c, expected) + + c = companion([2.0, 5.0, -10.0]) + expected = array([ + [-2.5, 5.0], + [1.0, 0.0]]) + assert_array_equal(c, expected) + + c = companion([(1.0, 2.0, 3.0), + (4.0, 5.0, 6.0)]) + expected = array([ + ([-2.00, -3.00], + [+1.00, +0.00]), + ([-1.25, -1.50], + [+1.00, +0.00]) + ]) + assert_array_equal(c, expected) + + +class TestBlockDiag: + def test_basic(self): + x = block_diag(eye(2), [[1, 2], [3, 4], [5, 6]], [[1, 2, 3]]) + assert_array_equal(x, [[1, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0], + [0, 0, 1, 2, 0, 0, 0], + [0, 0, 3, 4, 0, 0, 0], + [0, 0, 5, 6, 0, 0, 0], + [0, 0, 0, 0, 1, 2, 3]]) + + def test_dtype(self): + x = block_diag([[1.5]]) + assert_equal(x.dtype, float) + + x = block_diag([[True]]) + assert_equal(x.dtype, bool) + + def test_mixed_dtypes(self): + actual = block_diag([[1]], [[1j]]) + desired = np.array([[1, 0], [0, 1j]]) + assert_array_equal(actual, desired) + + def test_scalar_and_1d_args(self): + a = block_diag(1) + assert_equal(a.shape, (1, 1)) + assert_array_equal(a, [[1]]) + + a = block_diag([2, 3], 4) + assert_array_equal(a, [[2, 3, 0], [0, 0, 4]]) + + def test_bad_arg(self): + assert_raises(ValueError, block_diag, [[[1]]]) + + def test_no_args(self): + a = block_diag() + assert_equal(a.ndim, 2) + assert_equal(a.nbytes, 0) + + def test_empty_matrix_arg(self): + # regression test for gh-4596: check the shape of the result + # for empty matrix inputs. Empty matrices are no longer ignored + # (gh-4908) it is viewed as a shape (1, 0) matrix. + a = block_diag([[1, 0], [0, 1]], + [], + [[2, 3], [4, 5], [6, 7]]) + assert_array_equal(a, [[1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 0, 0], + [0, 0, 2, 3], + [0, 0, 4, 5], + [0, 0, 6, 7]]) + + def test_zerosized_matrix_arg(self): + # test for gh-4908: check the shape of the result for + # zero-sized matrix inputs, i.e. matrices with shape (0,n) or (n,0). + # note that [[]] takes shape (1,0) + a = block_diag([[1, 0], [0, 1]], + [[]], + [[2, 3], [4, 5], [6, 7]], + np.zeros([0, 2], dtype='int32')) + assert_array_equal(a, [[1, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 2, 3, 0, 0], + [0, 0, 4, 5, 0, 0], + [0, 0, 6, 7, 0, 0]]) + + +class TestKron: + @pytest.mark.thread_unsafe + def test_dep(self): + with pytest.deprecated_call(match="`kron`"): + kron(np.array([[1, 2],[3, 4]]),np.array([[1, 1, 1]])) + + @pytest.mark.filterwarnings('ignore::DeprecationWarning') + def test_basic(self): + + a = kron(array([[1, 2], [3, 4]]), array([[1, 1, 1]])) + assert_array_equal(a, array([[1, 1, 1, 2, 2, 2], + [3, 3, 3, 4, 4, 4]])) + + m1 = array([[1, 2], [3, 4]]) + m2 = array([[10], [11]]) + a = kron(m1, m2) + expected = array([[10, 20], + [11, 22], + [30, 40], + [33, 44]]) + assert_array_equal(a, expected) + + @pytest.mark.filterwarnings('ignore::DeprecationWarning') + def test_empty(self): + m1 = np.empty((0, 2)) + m2 = np.empty((1, 3)) + a = kron(m1, m2) + assert_allclose(a, np.empty((0, 6))) + + +class TestHelmert: + + def test_orthogonality(self): + for n in range(1, 7): + H = helmert(n, full=True) + Id = np.eye(n) + assert_allclose(H.dot(H.T), Id, atol=1e-12) + assert_allclose(H.T.dot(H), Id, atol=1e-12) + + def test_subspace(self): + for n in range(2, 7): + H_full = helmert(n, full=True) + H_partial = helmert(n) + for U in H_full[1:, :].T, H_partial.T: + C = np.eye(n) - np.full((n, n), 1 / n) + assert_allclose(U.dot(U.T), C) + assert_allclose(U.T.dot(U), np.eye(n-1), atol=1e-12) + + +class TestHilbert: + + def test_basic(self): + h3 = array([[1.0, 1/2., 1/3.], + [1/2., 1/3., 1/4.], + [1/3., 1/4., 1/5.]]) + assert_array_almost_equal(hilbert(3), h3) + + assert_array_equal(hilbert(1), [[1.0]]) + + h0 = hilbert(0) + assert_equal(h0.shape, (0, 0)) + + +class TestInvHilbert: + + def test_basic(self): + invh1 = array([[1]]) + assert_array_equal(invhilbert(1, exact=True), invh1) + assert_array_equal(invhilbert(1), invh1) + + invh2 = array([[4, -6], + [-6, 12]]) + assert_array_equal(invhilbert(2, exact=True), invh2) + assert_array_almost_equal(invhilbert(2), invh2) + + invh3 = array([[9, -36, 30], + [-36, 192, -180], + [30, -180, 180]]) + assert_array_equal(invhilbert(3, exact=True), invh3) + assert_array_almost_equal(invhilbert(3), invh3) + + invh4 = array([[16, -120, 240, -140], + [-120, 1200, -2700, 1680], + [240, -2700, 6480, -4200], + [-140, 1680, -4200, 2800]]) + assert_array_equal(invhilbert(4, exact=True), invh4) + assert_array_almost_equal(invhilbert(4), invh4) + + invh5 = array([[25, -300, 1050, -1400, 630], + [-300, 4800, -18900, 26880, -12600], + [1050, -18900, 79380, -117600, 56700], + [-1400, 26880, -117600, 179200, -88200], + [630, -12600, 56700, -88200, 44100]]) + assert_array_equal(invhilbert(5, exact=True), invh5) + assert_array_almost_equal(invhilbert(5), invh5) + + invh17 = array([ + [289, -41616, 1976760, -46124400, 629598060, -5540462928, + 33374693352, -143034400080, 446982500250, -1033026222800, + 1774926873720, -2258997839280, 2099709530100, -1384423866000, + 613101997800, -163493866080, 19835652870], + [-41616, 7990272, -426980160, 10627061760, -151103534400, + 1367702848512, -8410422724704, 36616806420480, -115857864064800, + 270465047424000, -468580694662080, 600545887119360, + -561522320049600, 372133135180800, -165537539406000, + 44316454993920, -5395297580640], + [1976760, -426980160, 24337869120, -630981792000, 9228108708000, + -85267724461920, 532660105897920, -2348052711713280, + 7504429831470000, -17664748409880000, 30818191841236800, + -39732544853164800, 37341234283298400, -24857330514030000, + 11100752642520000, -2982128117299200, 364182586693200], + [-46124400, 10627061760, -630981792000, 16826181120000, + -251209625940000, 2358021022156800, -14914482965141760, + 66409571644416000, -214015221119700000, 507295338950400000, + -890303319857952000, 1153715376477081600, -1089119333262870000, + 727848632044800000, -326170262829600000, 87894302404608000, + -10763618673376800], + [629598060, -151103534400, 9228108708000, + -251209625940000, 3810012660090000, -36210360321495360, + 231343968720664800, -1038687206500944000, 3370739732635275000, + -8037460526495400000, 14178080368737885600, -18454939322943942000, + 17489975175339030000, -11728977435138600000, 5272370630081100000, + -1424711708039692800, 174908803442373000], + [-5540462928, 1367702848512, -85267724461920, 2358021022156800, + -36210360321495360, 347619459086355456, -2239409617216035264, + 10124803292907663360, -33052510749726468000, + 79217210949138662400, -140362995650505067440, + 183420385176741672960, -174433352415381259200, + 117339159519533952000, -52892422160973595200, + 14328529177999196160, -1763080738699119840], + [33374693352, -8410422724704, 532660105897920, + -14914482965141760, 231343968720664800, -2239409617216035264, + 14527452132196331328, -66072377044391477760, + 216799987176909536400, -521925895055522958000, + 928414062734059661760, -1217424500995626443520, + 1161358898976091015200, -783401860847777371200, + 354015418167362952000, -96120549902411274240, + 11851820521255194480], + [-143034400080, 36616806420480, -2348052711713280, + 66409571644416000, -1038687206500944000, 10124803292907663360, + -66072377044391477760, 302045152202932469760, + -995510145200094810000, 2405996923185123840000, + -4294704507885446054400, 5649058909023744614400, + -5403874060541811254400, 3654352703663101440000, + -1655137020003255360000, 450325202737117593600, + -55630994283442749600], + [446982500250, -115857864064800, 7504429831470000, + -214015221119700000, 3370739732635275000, -33052510749726468000, + 216799987176909536400, -995510145200094810000, + 3293967392206196062500, -7988661659013106500000, + 14303908928401362270000, -18866974090684772052000, + 18093328327706957325000, -12263364009096700500000, + 5565847995255512250000, -1517208935002984080000, + 187754605706619279900], + [-1033026222800, 270465047424000, -17664748409880000, + 507295338950400000, -8037460526495400000, 79217210949138662400, + -521925895055522958000, 2405996923185123840000, + -7988661659013106500000, 19434404971634224000000, + -34894474126569249192000, 46141453390504792320000, + -44349976506971935800000, 30121928988527376000000, + -13697025107665828500000, 3740200989399948902400, + -463591619028689580000], + [1774926873720, -468580694662080, + 30818191841236800, -890303319857952000, 14178080368737885600, + -140362995650505067440, 928414062734059661760, + -4294704507885446054400, 14303908928401362270000, + -34894474126569249192000, 62810053427824648545600, + -83243376594051600326400, 80177044485212743068000, + -54558343880470209780000, 24851882355348879230400, + -6797096028813368678400, 843736746632215035600], + [-2258997839280, 600545887119360, -39732544853164800, + 1153715376477081600, -18454939322943942000, 183420385176741672960, + -1217424500995626443520, 5649058909023744614400, + -18866974090684772052000, 46141453390504792320000, + -83243376594051600326400, 110552468520163390156800, + -106681852579497947388000, 72720410752415168870400, + -33177973900974346080000, 9087761081682520473600, + -1129631016152221783200], + [2099709530100, -561522320049600, 37341234283298400, + -1089119333262870000, 17489975175339030000, + -174433352415381259200, 1161358898976091015200, + -5403874060541811254400, 18093328327706957325000, + -44349976506971935800000, 80177044485212743068000, + -106681852579497947388000, 103125790826848015808400, + -70409051543137015800000, 32171029219823375700000, + -8824053728865840192000, 1098252376814660067000], + [-1384423866000, 372133135180800, + -24857330514030000, 727848632044800000, -11728977435138600000, + 117339159519533952000, -783401860847777371200, + 3654352703663101440000, -12263364009096700500000, + 30121928988527376000000, -54558343880470209780000, + 72720410752415168870400, -70409051543137015800000, + 48142941226076592000000, -22027500987368499000000, + 6049545098753157120000, -753830033789944188000], + [613101997800, -165537539406000, + 11100752642520000, -326170262829600000, 5272370630081100000, + -52892422160973595200, 354015418167362952000, + -1655137020003255360000, 5565847995255512250000, + -13697025107665828500000, 24851882355348879230400, + -33177973900974346080000, 32171029219823375700000, + -22027500987368499000000, 10091416708498869000000, + -2774765838662800128000, 346146444087219270000], + [-163493866080, 44316454993920, -2982128117299200, + 87894302404608000, -1424711708039692800, + 14328529177999196160, -96120549902411274240, + 450325202737117593600, -1517208935002984080000, + 3740200989399948902400, -6797096028813368678400, + 9087761081682520473600, -8824053728865840192000, + 6049545098753157120000, -2774765838662800128000, + 763806510427609497600, -95382575704033754400], + [19835652870, -5395297580640, 364182586693200, -10763618673376800, + 174908803442373000, -1763080738699119840, 11851820521255194480, + -55630994283442749600, 187754605706619279900, + -463591619028689580000, 843736746632215035600, + -1129631016152221783200, 1098252376814660067000, + -753830033789944188000, 346146444087219270000, + -95382575704033754400, 11922821963004219300] + ]) + assert_array_equal(invhilbert(17, exact=True), invh17) + assert_allclose(invhilbert(17), invh17.astype(float), rtol=1e-12) + + def test_inverse(self): + for n in range(1, 10): + a = hilbert(n) + b = invhilbert(n) + # The Hilbert matrix is increasingly badly conditioned, + # so take that into account in the test + c = cond(a) + assert_allclose(a.dot(b), eye(n), atol=1e-15*c, rtol=1e-15*c) + + +class TestPascal: + + cases = [ + (1, array([[1]]), array([[1]])), + (2, array([[1, 1], + [1, 2]]), + array([[1, 0], + [1, 1]])), + (3, array([[1, 1, 1], + [1, 2, 3], + [1, 3, 6]]), + array([[1, 0, 0], + [1, 1, 0], + [1, 2, 1]])), + (4, array([[1, 1, 1, 1], + [1, 2, 3, 4], + [1, 3, 6, 10], + [1, 4, 10, 20]]), + array([[1, 0, 0, 0], + [1, 1, 0, 0], + [1, 2, 1, 0], + [1, 3, 3, 1]])), + ] + + def check_case(self, n, sym, low): + assert_array_equal(pascal(n), sym) + assert_array_equal(pascal(n, kind='lower'), low) + assert_array_equal(pascal(n, kind='upper'), low.T) + assert_array_almost_equal(pascal(n, exact=False), sym) + assert_array_almost_equal(pascal(n, exact=False, kind='lower'), low) + assert_array_almost_equal(pascal(n, exact=False, kind='upper'), low.T) + + def test_cases(self): + for n, sym, low in self.cases: + self.check_case(n, sym, low) + + def test_big(self): + p = pascal(50) + assert p[-1, -1] == comb(98, 49, exact=True) + + def test_threshold(self): + # Regression test. An early version of `pascal` returned an + # array of type np.uint64 for n=35, but that data type is too small + # to hold p[-1, -1]. The second assert_equal below would fail + # because p[-1, -1] overflowed. + p = pascal(34) + assert_equal(2*p.item(-1, -2), p.item(-1, -1), err_msg="n = 34") + p = pascal(35) + assert_equal(2.*p.item(-1, -2), 1.*p.item(-1, -1), err_msg="n = 35") + + +def test_invpascal(): + + def check_invpascal(n, kind, exact): + ip = invpascal(n, kind=kind, exact=exact) + p = pascal(n, kind=kind, exact=exact) + # Matrix-multiply ip and p, and check that we get the identity matrix. + # We can't use the simple expression e = ip.dot(p), because when + # n < 35 and exact is True, p.dtype is np.uint64 and ip.dtype is + # np.int64. The product of those dtypes is np.float64, which loses + # precision when n is greater than 18. Instead we'll cast both to + # object arrays, and then multiply. + e = ip.astype(object).dot(p.astype(object)) + assert_array_equal(e, eye(n), err_msg="n=%d kind=%r exact=%r" % + (n, kind, exact)) + + kinds = ['symmetric', 'lower', 'upper'] + + ns = [1, 2, 5, 18] + for n in ns: + for kind in kinds: + for exact in [True, False]: + check_invpascal(n, kind, exact) + + ns = [19, 34, 35, 50] + for n in ns: + for kind in kinds: + check_invpascal(n, kind, True) + + +def test_dft(): + m = dft(2) + expected = array([[1.0, 1.0], [1.0, -1.0]]) + assert_array_almost_equal(m, expected) + m = dft(2, scale='n') + assert_array_almost_equal(m, expected/2.0) + m = dft(2, scale='sqrtn') + assert_array_almost_equal(m, expected/sqrt(2.0)) + + x = array([0, 1, 2, 3, 4, 5, 0, 1]) + m = dft(8) + mx = m.dot(x) + fx = fft(x) + assert_array_almost_equal(mx, fx) + + +def test_fiedler(): + f = fiedler([]) + assert_equal(f.size, 0) + f = fiedler([123.]) + assert_array_equal(f, np.array([[0.]])) + f = fiedler(np.arange(1, 7)) + des = np.array([[0, 1, 2, 3, 4, 5], + [1, 0, 1, 2, 3, 4], + [2, 1, 0, 1, 2, 3], + [3, 2, 1, 0, 1, 2], + [4, 3, 2, 1, 0, 1], + [5, 4, 3, 2, 1, 0]]) + assert_array_equal(f, des) + + +def test_fiedler_companion(): + fc = fiedler_companion([]) + assert_equal(fc.size, 0) + fc = fiedler_companion([1.]) + assert_equal(fc.size, 0) + fc = fiedler_companion([1., 2.]) + assert_array_equal(fc, np.array([[-2.]])) + fc = fiedler_companion([1e-12, 2., 3.]) + assert_array_almost_equal(fc, companion([1e-12, 2., 3.])) + with assert_raises(ValueError): + fiedler_companion([0, 1, 2]) + fc = fiedler_companion([1., -16., 86., -176., 105.]) + assert_array_almost_equal(eigvals(fc), + np.array([7., 5., 3., 1.])) + + +class TestConvolutionMatrix: + """ + Test convolution_matrix vs. numpy.convolve for various parameters. + """ + + def create_vector(self, n, cpx): + """Make a complex or real test vector of length n.""" + x = np.linspace(-2.5, 2.2, n) + if cpx: + x = x + 1j*np.linspace(-1.5, 3.1, n) + return x + + def test_bad_n(self): + # n must be a positive integer + with pytest.raises(ValueError, match='n must be a positive integer'): + convolution_matrix([1, 2, 3], 0) + + def test_empty_first_arg(self): + # first arg must have at least one value + with pytest.raises(ValueError, match=r'len\(a\)'): + convolution_matrix([], 4) + + def test_bad_mode(self): + # mode must be in ('full', 'valid', 'same') + with pytest.raises(ValueError, match='mode.*must be one of'): + convolution_matrix((1, 1), 4, mode='invalid argument') + + @pytest.mark.parametrize('cpx', [False, True]) + @pytest.mark.parametrize('na', [1, 2, 9]) + @pytest.mark.parametrize('nv', [1, 2, 9]) + @pytest.mark.parametrize('mode', [None, 'full', 'valid', 'same']) + def test_against_numpy_convolve(self, cpx, na, nv, mode): + a = self.create_vector(na, cpx) + v = self.create_vector(nv, cpx) + if mode is None: + y1 = np.convolve(v, a) + A = convolution_matrix(a, nv) + else: + y1 = np.convolve(v, a, mode) + A = convolution_matrix(a, nv, mode) + y2 = A @ v + assert_array_almost_equal(y1, y2) + + +@pytest.mark.thread_unsafe +@pytest.mark.fail_slow(5) # `leslie` has an import in the function +@pytest.mark.parametrize('f, args', [(circulant, ()), + (companion, ()), + (convolution_matrix, (5, 'same')), + (fiedler, ()), + (fiedler_companion, ()), + (leslie, (np.arange(9),)), + (toeplitz, (np.arange(9),)), + ]) +def test_batch(f, args): + rng = np.random.default_rng(283592436523456) + batch_shape = (2, 3) + m = 10 + A = rng.random(batch_shape + (m,)) + + if f in {toeplitz}: + message = "Beginning in SciPy 1.17, multidimensional input will be..." + with pytest.warns(FutureWarning, match=message): + f(A, *args) + return + + res = f(A, *args) + ref = np.asarray([f(a, *args) for a in A.reshape(-1, m)]) + ref = ref.reshape(A.shape[:-1] + ref.shape[-2:]) + assert_allclose(res, ref) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/misc/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/misc/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2eb2f71afd54a67b54d7012347e5d1a983fac7be --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/misc/__init__.py @@ -0,0 +1,6 @@ +import warnings +warnings.warn( + "scipy.misc is deprecated and will be removed in 2.0.0", + DeprecationWarning, + stacklevel=2 +) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/misc/common.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/misc/common.py new file mode 100644 index 0000000000000000000000000000000000000000..e85acca3ac49d1cb84792bdf369cffe69a5d8ad8 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/misc/common.py @@ -0,0 +1,6 @@ +import warnings +warnings.warn( + "scipy.misc.common is deprecated and will be removed in 2.0.0", + DeprecationWarning, + stacklevel=2 +) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/misc/doccer.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/misc/doccer.py new file mode 100644 index 0000000000000000000000000000000000000000..74cabc8c2fd14fe6424b8aad828c329ecdaee4b2 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/misc/doccer.py @@ -0,0 +1,6 @@ +import warnings +warnings.warn( + "scipy.misc.doccer is deprecated and will be removed in 2.0.0", + DeprecationWarning, + stacklevel=2 +) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2e9d9f6ff99218088fd9e693aaca00ca8a070040 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/__init__.py @@ -0,0 +1,173 @@ +""" +========================================================= +Multidimensional image processing (:mod:`scipy.ndimage`) +========================================================= + +.. currentmodule:: scipy.ndimage + +This package contains various functions for multidimensional image +processing. + + +Filters +======= + +.. autosummary:: + :toctree: generated/ + + convolve - Multidimensional convolution + convolve1d - 1-D convolution along the given axis + correlate - Multidimensional correlation + correlate1d - 1-D correlation along the given axis + gaussian_filter + gaussian_filter1d + gaussian_gradient_magnitude + gaussian_laplace + generic_filter - Multidimensional filter using a given function + generic_filter1d - 1-D generic filter along the given axis + generic_gradient_magnitude + generic_laplace + laplace - N-D Laplace filter based on approximate second derivatives + maximum_filter + maximum_filter1d + median_filter - Calculates a multidimensional median filter + minimum_filter + minimum_filter1d + percentile_filter - Calculates a multidimensional percentile filter + prewitt + rank_filter - Calculates a multidimensional rank filter + sobel + uniform_filter - Multidimensional uniform filter + uniform_filter1d - 1-D uniform filter along the given axis + +Fourier filters +=============== + +.. autosummary:: + :toctree: generated/ + + fourier_ellipsoid + fourier_gaussian + fourier_shift + fourier_uniform + +Interpolation +============= + +.. autosummary:: + :toctree: generated/ + + affine_transform - Apply an affine transformation + geometric_transform - Apply an arbitrary geometric transform + map_coordinates - Map input array to new coordinates by interpolation + rotate - Rotate an array + shift - Shift an array + spline_filter + spline_filter1d + zoom - Zoom an array + +Measurements +============ + +.. autosummary:: + :toctree: generated/ + + center_of_mass - The center of mass of the values of an array at labels + extrema - Min's and max's of an array at labels, with their positions + find_objects - Find objects in a labeled array + histogram - Histogram of the values of an array, optionally at labels + label - Label features in an array + labeled_comprehension + maximum + maximum_position + mean - Mean of the values of an array at labels + median + minimum + minimum_position + standard_deviation - Standard deviation of an N-D image array + sum_labels - Sum of the values of the array + value_indices - Find indices of each distinct value in given array + variance - Variance of the values of an N-D image array + watershed_ift + +Morphology +========== + +.. autosummary:: + :toctree: generated/ + + binary_closing + binary_dilation + binary_erosion + binary_fill_holes + binary_hit_or_miss + binary_opening + binary_propagation + black_tophat + distance_transform_bf + distance_transform_cdt + distance_transform_edt + generate_binary_structure + grey_closing + grey_dilation + grey_erosion + grey_opening + iterate_structure + morphological_gradient + morphological_laplace + white_tophat + +""" + +# Copyright (C) 2003-2005 Peter J. Verveer +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# 2. Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# 3. The name of the author may not be used to endorse or promote +# products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS +# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE +# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +# bring in the public functionality from private namespaces + +# mypy: ignore-errors + +from ._support_alternative_backends import * + +# adjust __all__ and do not leak implementation details +from . import _support_alternative_backends +__all__ = _support_alternative_backends.__all__ +del _support_alternative_backends, _ndimage_api, _delegators # noqa: F821 + + +# Deprecated namespaces, to be removed in v2.0.0 +from . import filters +from . import fourier +from . import interpolation +from . import measurements +from . import morphology + +from scipy._lib._testutils import PytestTester +test = PytestTester(__name__) +del PytestTester diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/_ctest.cpython-310-x86_64-linux-gnu.so b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/_ctest.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..0d05e123ba1f7f45c1f37795e7ba5cd0257018b4 Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/_ctest.cpython-310-x86_64-linux-gnu.so differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/_cytest.cpython-310-x86_64-linux-gnu.so b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/_cytest.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..7898248eb4d089b5ffa726ff39de4d0ec4637272 Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/_cytest.cpython-310-x86_64-linux-gnu.so differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/_delegators.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/_delegators.py new file mode 100644 index 0000000000000000000000000000000000000000..9647ea6456426c9a62178ff277b0f35017a8310b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/_delegators.py @@ -0,0 +1,297 @@ +"""Delegators for alternative backends in scipy.ndimage. + +The signature of `func_signature` must match the signature of ndimage.func. +The job of a `func_signature` is to know which arguments of `ndimage.func` +are arrays. + +* signatures are generated by + +-------------- +import inspect +from scipy import ndimage + +names = [x for x in dir(ndimage) if not x.startswith('_')] +objs = [getattr(ndimage, name) for name in names] +funcs = [obj for obj in objs if inspect.isroutine(obj)] + +for func in funcs: + sig = inspect.signature(func) + print(f"def {func.__name__}_signature{sig}:\n\tpass\n\n") +--------------- + +* which arguments to delegate on: manually trawled the documentation for + array-like and array arguments + +""" +import numpy as np +from scipy._lib._array_api import array_namespace +from scipy.ndimage._ni_support import _skip_if_dtype, _skip_if_int + + +def affine_transform_signature( + input, matrix, offset=0.0, output_shape=None, output=None, *args, **kwds +): + return array_namespace(input, matrix, _skip_if_dtype(output)) + + +def binary_closing_signature( + input, structure=None, iterations=1, output=None, *args, **kwds +): + return array_namespace(input, structure, _skip_if_dtype(output)) + +binary_opening_signature = binary_closing_signature + + +def binary_dilation_signature( + input, structure=None, iterations=1, mask=None, output=None, *args, **kwds +): + return array_namespace(input, structure, _skip_if_dtype(output), mask) + +binary_erosion_signature = binary_dilation_signature + + +def binary_fill_holes_signature( + input, structure=None, output=None, origin=0, *args, **kwargs +): + return array_namespace(input, structure, _skip_if_dtype(output)) + + +def label_signature(input, structure=None, output=None, origin=0): + return array_namespace(input, structure, _skip_if_dtype(output)) + + +def binary_hit_or_miss_signature( + input, structure1=None, structure2=None, output=None, *args, **kwds +): + return array_namespace(input, structure1, structure2, _skip_if_dtype(output)) + + +def binary_propagation_signature( + input, structure=None, mask=None, output=None, *args, **kwds +): + return array_namespace(input, structure, mask, _skip_if_dtype(output)) + + +def convolve_signature(input, weights, output=None, *args, **kwds): + return array_namespace(input, weights, _skip_if_dtype(output)) + +correlate_signature = convolve_signature + + +def convolve1d_signature(input, weights, axis=-1, output=None, *args, **kwds): + return array_namespace(input, weights, _skip_if_dtype(output)) + +correlate1d_signature = convolve1d_signature + + +def distance_transform_bf_signature( + input, metric='euclidean', sampling=None, return_distances=True, + return_indices=False, distances=None, indices=None +): + return array_namespace(input, distances, indices) + + +def distance_transform_cdt_signature( + input, metric='chessboard', return_distances=True, return_indices=False, + distances=None, indices=None +): + return array_namespace(input, distances, indices) + + +def distance_transform_edt_signature( + input, sampling=None, return_distances=True, return_indices=False, + distances=None, indices=None +): + return array_namespace(input, distances, indices) + + +def find_objects_signature(input, max_label=0): + return array_namespace(input) + + +def fourier_ellipsoid_signature(input, size, n=-1, axis=-1, output=None): + return array_namespace(input, _skip_if_dtype(output)) + +fourier_uniform_signature = fourier_ellipsoid_signature + + +def fourier_gaussian_signature(input, sigma, n=-1, axis=-1, output=None): + return array_namespace(input, _skip_if_dtype(output)) + +def fourier_shift_signature(input, shift, n=-1, axis=-1, output=None): + return array_namespace(input, _skip_if_dtype(output)) + + +def gaussian_filter_signature(input, sigma, order=0, output=None, *args, **kwds): + return array_namespace(input, _skip_if_dtype(output)) + + +def gaussian_filter1d_signature( + input, sigma, axis=-1, order=0, output=None, *args, **kwds +): + return array_namespace(input, _skip_if_dtype(output)) + + +def gaussian_gradient_magnitude_signature(input, sigma, output=None, *args, **kwds): + return array_namespace(input, _skip_if_dtype(output)) + +gaussian_laplace_signature = gaussian_gradient_magnitude_signature + + +def generate_binary_structure_signature(rank, connectivity): + # XXX: no input arrays; always return numpy + return np + + +def generic_filter_signature( + input, function, size=None, footprint=None, output=None, *args, **kwds +): + # XXX: function LowLevelCallable w/backends + return array_namespace(input, footprint, _skip_if_dtype(output)) + + +def generic_filter1d_signature( + input, function, filter_size, axis=-1, output=None, *args, **kwds +): + return array_namespace(input, _skip_if_dtype(output)) + + +def generic_gradient_magnitude_signature( + input, derivative, output=None, *args, **kwds +): + # XXX: function LowLevelCallable w/backends + return array_namespace(input, _skip_if_dtype(output)) + + +def generic_laplace_signature(input, derivative2, output=None, *args, **kwds): + # XXX: function LowLevelCallable w/backends + return array_namespace(input, _skip_if_dtype(output)) + + +def geometric_transform_signature( + input, mapping, output_shape=None, output=None, *args, **kwds +): + return array_namespace(input, _skip_if_dtype(output)) + + +def histogram_signature(input, min, max, bins, labels=None, index=None): + return array_namespace(input, labels) + + +def iterate_structure_signature(structure, iterations, origin=None): + return array_namespace(structure) + + +def labeled_comprehension_signature(input, labels, *args, **kwds): + return array_namespace(input, labels) + + +def laplace_signature(input, output=None, *args, **kwds): + return array_namespace(input, _skip_if_dtype(output)) + + +def map_coordinates_signature(input, coordinates, output=None, *args, **kwds): + return array_namespace(input, coordinates, _skip_if_dtype(output)) + + +def maximum_filter1d_signature(input, size, axis=-1, output=None, *args, **kwds): + return array_namespace(input, _skip_if_dtype(output)) + +minimum_filter1d_signature = maximum_filter1d_signature +uniform_filter1d_signature = maximum_filter1d_signature + + +def maximum_signature(input, labels=None, index=None): + return array_namespace(input, labels, _skip_if_int(index)) + +minimum_signature = maximum_signature +median_signature = maximum_signature +mean_signature = maximum_signature +variance_signature = maximum_signature +standard_deviation_signature = maximum_signature +sum_labels_signature = maximum_signature +sum_signature = maximum_signature # ndimage.sum is sum_labels + +maximum_position_signature = maximum_signature +minimum_position_signature = maximum_signature + +extrema_signature = maximum_signature +center_of_mass_signature = extrema_signature + + +def median_filter_signature( + input, size=None, footprint=None, output=None, *args, **kwds +): + return array_namespace(input, footprint, _skip_if_dtype(output)) + +minimum_filter_signature = median_filter_signature +maximum_filter_signature = median_filter_signature + + +def morphological_gradient_signature( + input, size=None, footprint=None, structure=None, output=None, *args, **kwds +): + return array_namespace(input, footprint, structure, _skip_if_dtype(output)) + +morphological_laplace_signature = morphological_gradient_signature +white_tophat_signature = morphological_gradient_signature +black_tophat_signature = morphological_gradient_signature +grey_closing_signature = morphological_gradient_signature +grey_dilation_signature = morphological_gradient_signature +grey_erosion_signature = morphological_gradient_signature +grey_opening_signature = morphological_gradient_signature + + +def percentile_filter_signature( + input, percentile, size=None, footprint=None, output=None, *args, **kwds +): + return array_namespace(input, footprint, _skip_if_dtype(output)) + + +def prewitt_signature(input, axis=-1, output=None, *args, **kwds): + return array_namespace(input, _skip_if_dtype(output)) + +sobel_signature = prewitt_signature + + +def rank_filter_signature( + input, rank, size=None, footprint=None, output=None, *args, **kwds +): + return array_namespace(input, footprint, _skip_if_dtype(output)) + + +def rotate_signature( + input, angle, axes=(1, 0), reshape=True, output=None , *args, **kwds +): + return array_namespace(input, _skip_if_dtype(output)) + + +def shift_signature(input, shift, output=None, *args, **kwds): + return array_namespace(input, _skip_if_dtype(output)) + + +def spline_filter_signature(input, order=3, output=np.float64, *args, **kwds): + return array_namespace(input, _skip_if_dtype(output)) + + +def spline_filter1d_signature( + input, order=3, axis=-1, output=np.float64, *args, **kwds +): + return array_namespace(input, _skip_if_dtype(output)) + + +def uniform_filter_signature(input, size=3, output=None, *args, **kwds): + return array_namespace(input, _skip_if_dtype(output)) + + +def value_indices_signature(arr, *args, **kwds): + return array_namespace(arr) + + +def watershed_ift_signature(input, markers, structure=None, output=None): + return array_namespace(input, markers, structure, _skip_if_dtype(output)) + + +def zoom_signature(input, zoom, output=None, *args, **kwds): + return array_namespace(input, _skip_if_dtype(output)) + diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/_filters.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/_filters.py new file mode 100644 index 0000000000000000000000000000000000000000..710ea60c03653cc80ac3bd1eefd425b4268a5246 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/_filters.py @@ -0,0 +1,1965 @@ +# Copyright (C) 2003-2005 Peter J. Verveer +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# 2. Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# 3. The name of the author may not be used to endorse or promote +# products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS +# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE +# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +from collections.abc import Iterable +import numbers +import warnings +import numpy as np +import operator + +from scipy._lib._util import normalize_axis_index +from . import _ni_support +from . import _nd_image +from . import _ni_docstrings +from . import _rank_filter_1d + +__all__ = ['correlate1d', 'convolve1d', 'gaussian_filter1d', 'gaussian_filter', + 'prewitt', 'sobel', 'generic_laplace', 'laplace', + 'gaussian_laplace', 'generic_gradient_magnitude', + 'gaussian_gradient_magnitude', 'correlate', 'convolve', + 'uniform_filter1d', 'uniform_filter', 'minimum_filter1d', + 'maximum_filter1d', 'minimum_filter', 'maximum_filter', + 'rank_filter', 'median_filter', 'percentile_filter', + 'generic_filter1d', 'generic_filter'] + + +def _invalid_origin(origin, lenw): + return (origin < -(lenw // 2)) or (origin > (lenw - 1) // 2) + + +def _complex_via_real_components(func, input, weights, output, cval, **kwargs): + """Complex convolution via a linear combination of real convolutions.""" + complex_input = input.dtype.kind == 'c' + complex_weights = weights.dtype.kind == 'c' + if complex_input and complex_weights: + # real component of the output + func(input.real, weights.real, output=output.real, + cval=np.real(cval), **kwargs) + output.real -= func(input.imag, weights.imag, output=None, + cval=np.imag(cval), **kwargs) + # imaginary component of the output + func(input.real, weights.imag, output=output.imag, + cval=np.real(cval), **kwargs) + output.imag += func(input.imag, weights.real, output=None, + cval=np.imag(cval), **kwargs) + elif complex_input: + func(input.real, weights, output=output.real, cval=np.real(cval), + **kwargs) + func(input.imag, weights, output=output.imag, cval=np.imag(cval), + **kwargs) + else: + if np.iscomplexobj(cval): + raise ValueError("Cannot provide a complex-valued cval when the " + "input is real.") + func(input, weights.real, output=output.real, cval=cval, **kwargs) + func(input, weights.imag, output=output.imag, cval=cval, **kwargs) + return output + + +def _expand_origin(ndim_image, axes, origin): + num_axes = len(axes) + origins = _ni_support._normalize_sequence(origin, num_axes) + if num_axes < ndim_image: + # set origin = 0 for any axes not being filtered + origins_temp = [0,] * ndim_image + for o, ax in zip(origins, axes): + origins_temp[ax] = o + origins = origins_temp + return origins + + +def _expand_footprint(ndim_image, axes, footprint, + footprint_name="footprint"): + num_axes = len(axes) + if num_axes < ndim_image: + if footprint.ndim != num_axes: + raise RuntimeError(f"{footprint_name}.ndim ({footprint.ndim}) " + f"must match len(axes) ({num_axes})") + + footprint = np.expand_dims( + footprint, + tuple(ax for ax in range(ndim_image) if ax not in axes) + ) + return footprint + + +def _expand_mode(ndim_image, axes, mode): + num_axes = len(axes) + if not isinstance(mode, str) and isinstance(mode, Iterable): + # set mode = 'constant' for any axes not being filtered + modes = _ni_support._normalize_sequence(mode, num_axes) + modes_temp = ['constant'] * ndim_image + for m, ax in zip(modes, axes): + modes_temp[ax] = m + mode = modes_temp + return mode + + +@_ni_docstrings.docfiller +def correlate1d(input, weights, axis=-1, output=None, mode="reflect", + cval=0.0, origin=0): + """Calculate a 1-D correlation along the given axis. + + The lines of the array along the given axis are correlated with the + given weights. + + Parameters + ---------- + %(input)s + weights : array + 1-D sequence of numbers. + %(axis)s + %(output)s + %(mode_reflect)s + %(cval)s + %(origin)s + + Returns + ------- + result : ndarray + Correlation result. Has the same shape as `input`. + + Examples + -------- + >>> from scipy.ndimage import correlate1d + >>> correlate1d([2, 8, 0, 4, 1, 9, 9, 0], weights=[1, 3]) + array([ 8, 26, 8, 12, 7, 28, 36, 9]) + """ + input = np.asarray(input) + weights = np.asarray(weights) + complex_input = input.dtype.kind == 'c' + complex_weights = weights.dtype.kind == 'c' + if complex_input or complex_weights: + if complex_weights: + weights = weights.conj() + weights = weights.astype(np.complex128, copy=False) + kwargs = dict(axis=axis, mode=mode, origin=origin) + output = _ni_support._get_output(output, input, complex_output=True) + return _complex_via_real_components(correlate1d, input, weights, + output, cval, **kwargs) + + output = _ni_support._get_output(output, input) + weights = np.asarray(weights, dtype=np.float64) + if weights.ndim != 1 or weights.shape[0] < 1: + raise RuntimeError('no filter weights given') + if not weights.flags.contiguous: + weights = weights.copy() + axis = normalize_axis_index(axis, input.ndim) + if _invalid_origin(origin, len(weights)): + raise ValueError('Invalid origin; origin must satisfy ' + '-(len(weights) // 2) <= origin <= ' + '(len(weights)-1) // 2') + mode = _ni_support._extend_mode_to_code(mode) + _nd_image.correlate1d(input, weights, axis, output, mode, cval, + origin) + return output + + +@_ni_docstrings.docfiller +def convolve1d(input, weights, axis=-1, output=None, mode="reflect", + cval=0.0, origin=0): + """Calculate a 1-D convolution along the given axis. + + The lines of the array along the given axis are convolved with the + given weights. + + Parameters + ---------- + %(input)s + weights : ndarray + 1-D sequence of numbers. + %(axis)s + %(output)s + %(mode_reflect)s + %(cval)s + %(origin)s + + Returns + ------- + convolve1d : ndarray + Convolved array with same shape as input + + Examples + -------- + >>> from scipy.ndimage import convolve1d + >>> convolve1d([2, 8, 0, 4, 1, 9, 9, 0], weights=[1, 3]) + array([14, 24, 4, 13, 12, 36, 27, 0]) + """ + weights = np.asarray(weights) + weights = weights[::-1] + origin = -origin + if not weights.shape[0] & 1: + origin -= 1 + if weights.dtype.kind == 'c': + # pre-conjugate here to counteract the conjugation in correlate1d + weights = weights.conj() + return correlate1d(input, weights, axis, output, mode, cval, origin) + + +def _gaussian_kernel1d(sigma, order, radius): + """ + Computes a 1-D Gaussian convolution kernel. + """ + if order < 0: + raise ValueError('order must be non-negative') + exponent_range = np.arange(order + 1) + sigma2 = sigma * sigma + x = np.arange(-radius, radius+1) + phi_x = np.exp(-0.5 / sigma2 * x ** 2) + phi_x = phi_x / phi_x.sum() + + if order == 0: + return phi_x + else: + # f(x) = q(x) * phi(x) = q(x) * exp(p(x)) + # f'(x) = (q'(x) + q(x) * p'(x)) * phi(x) + # p'(x) = -1 / sigma ** 2 + # Implement q'(x) + q(x) * p'(x) as a matrix operator and apply to the + # coefficients of q(x) + q = np.zeros(order + 1) + q[0] = 1 + D = np.diag(exponent_range[1:], 1) # D @ q(x) = q'(x) + P = np.diag(np.ones(order)/-sigma2, -1) # P @ q(x) = q(x) * p'(x) + Q_deriv = D + P + for _ in range(order): + q = Q_deriv.dot(q) + q = (x[:, None] ** exponent_range).dot(q) + return q * phi_x + + +@_ni_docstrings.docfiller +def gaussian_filter1d(input, sigma, axis=-1, order=0, output=None, + mode="reflect", cval=0.0, truncate=4.0, *, radius=None): + """1-D Gaussian filter. + + Parameters + ---------- + %(input)s + sigma : scalar + standard deviation for Gaussian kernel + %(axis)s + order : int, optional + An order of 0 corresponds to convolution with a Gaussian + kernel. A positive order corresponds to convolution with + that derivative of a Gaussian. + %(output)s + %(mode_reflect)s + %(cval)s + truncate : float, optional + Truncate the filter at this many standard deviations. + Default is 4.0. + radius : None or int, optional + Radius of the Gaussian kernel. If specified, the size of + the kernel will be ``2*radius + 1``, and `truncate` is ignored. + Default is None. + + Returns + ------- + gaussian_filter1d : ndarray + + Notes + ----- + The Gaussian kernel will have size ``2*radius + 1`` along each axis. If + `radius` is None, a default ``radius = round(truncate * sigma)`` will be + used. + + Examples + -------- + >>> from scipy.ndimage import gaussian_filter1d + >>> import numpy as np + >>> gaussian_filter1d([1.0, 2.0, 3.0, 4.0, 5.0], 1) + array([ 1.42704095, 2.06782203, 3. , 3.93217797, 4.57295905]) + >>> gaussian_filter1d([1.0, 2.0, 3.0, 4.0, 5.0], 4) + array([ 2.91948343, 2.95023502, 3. , 3.04976498, 3.08051657]) + >>> import matplotlib.pyplot as plt + >>> rng = np.random.default_rng() + >>> x = rng.standard_normal(101).cumsum() + >>> y3 = gaussian_filter1d(x, 3) + >>> y6 = gaussian_filter1d(x, 6) + >>> plt.plot(x, 'k', label='original data') + >>> plt.plot(y3, '--', label='filtered, sigma=3') + >>> plt.plot(y6, ':', label='filtered, sigma=6') + >>> plt.legend() + >>> plt.grid() + >>> plt.show() + + """ + sd = float(sigma) + # make the radius of the filter equal to truncate standard deviations + lw = int(truncate * sd + 0.5) + if radius is not None: + lw = radius + if not isinstance(lw, numbers.Integral) or lw < 0: + raise ValueError('Radius must be a nonnegative integer.') + # Since we are calling correlate, not convolve, revert the kernel + weights = _gaussian_kernel1d(sigma, order, lw)[::-1] + return correlate1d(input, weights, axis, output, mode, cval, 0) + + +@_ni_docstrings.docfiller +def gaussian_filter(input, sigma, order=0, output=None, + mode="reflect", cval=0.0, truncate=4.0, *, radius=None, + axes=None): + """Multidimensional Gaussian filter. + + Parameters + ---------- + %(input)s + sigma : scalar or sequence of scalars + Standard deviation for Gaussian kernel. The standard + deviations of the Gaussian filter are given for each axis as a + sequence, or as a single number, in which case it is equal for + all axes. + order : int or sequence of ints, optional + The order of the filter along each axis is given as a sequence + of integers, or as a single number. An order of 0 corresponds + to convolution with a Gaussian kernel. A positive order + corresponds to convolution with that derivative of a Gaussian. + %(output)s + %(mode_multiple)s + %(cval)s + truncate : float, optional + Truncate the filter at this many standard deviations. + Default is 4.0. + radius : None or int or sequence of ints, optional + Radius of the Gaussian kernel. The radius are given for each axis + as a sequence, or as a single number, in which case it is equal + for all axes. If specified, the size of the kernel along each axis + will be ``2*radius + 1``, and `truncate` is ignored. + Default is None. + axes : tuple of int or None, optional + If None, `input` is filtered along all axes. Otherwise, + `input` is filtered along the specified axes. When `axes` is + specified, any tuples used for `sigma`, `order`, `mode` and/or `radius` + must match the length of `axes`. The ith entry in any of these tuples + corresponds to the ith entry in `axes`. + + Returns + ------- + gaussian_filter : ndarray + Returned array of same shape as `input`. + + Notes + ----- + The multidimensional filter is implemented as a sequence of + 1-D convolution filters. The intermediate arrays are + stored in the same data type as the output. Therefore, for output + types with a limited precision, the results may be imprecise + because intermediate results may be stored with insufficient + precision. + + The Gaussian kernel will have size ``2*radius + 1`` along each axis. If + `radius` is None, the default ``radius = round(truncate * sigma)`` will be + used. + + Examples + -------- + >>> from scipy.ndimage import gaussian_filter + >>> import numpy as np + >>> a = np.arange(50, step=2).reshape((5,5)) + >>> a + array([[ 0, 2, 4, 6, 8], + [10, 12, 14, 16, 18], + [20, 22, 24, 26, 28], + [30, 32, 34, 36, 38], + [40, 42, 44, 46, 48]]) + >>> gaussian_filter(a, sigma=1) + array([[ 4, 6, 8, 9, 11], + [10, 12, 14, 15, 17], + [20, 22, 24, 25, 27], + [29, 31, 33, 34, 36], + [35, 37, 39, 40, 42]]) + + >>> from scipy import datasets + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> plt.gray() # show the filtered result in grayscale + >>> ax1 = fig.add_subplot(121) # left side + >>> ax2 = fig.add_subplot(122) # right side + >>> ascent = datasets.ascent() + >>> result = gaussian_filter(ascent, sigma=5) + >>> ax1.imshow(ascent) + >>> ax2.imshow(result) + >>> plt.show() + """ + input = np.asarray(input) + output = _ni_support._get_output(output, input) + + axes = _ni_support._check_axes(axes, input.ndim) + num_axes = len(axes) + orders = _ni_support._normalize_sequence(order, num_axes) + sigmas = _ni_support._normalize_sequence(sigma, num_axes) + modes = _ni_support._normalize_sequence(mode, num_axes) + radiuses = _ni_support._normalize_sequence(radius, num_axes) + axes = [(axes[ii], sigmas[ii], orders[ii], modes[ii], radiuses[ii]) + for ii in range(num_axes) if sigmas[ii] > 1e-15] + if len(axes) > 0: + for axis, sigma, order, mode, radius in axes: + gaussian_filter1d(input, sigma, axis, order, output, + mode, cval, truncate, radius=radius) + input = output + else: + output[...] = input[...] + return output + + +@_ni_docstrings.docfiller +def prewitt(input, axis=-1, output=None, mode="reflect", cval=0.0): + """Calculate a Prewitt filter. + + Parameters + ---------- + %(input)s + %(axis)s + %(output)s + %(mode_multiple)s + %(cval)s + + Returns + ------- + prewitt : ndarray + Filtered array. Has the same shape as `input`. + + See Also + -------- + sobel: Sobel filter + + Notes + ----- + This function computes the one-dimensional Prewitt filter. + Horizontal edges are emphasised with the horizontal transform (axis=0), + vertical edges with the vertical transform (axis=1), and so on for higher + dimensions. These can be combined to give the magnitude. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import matplotlib.pyplot as plt + >>> import numpy as np + >>> ascent = datasets.ascent() + >>> prewitt_h = ndimage.prewitt(ascent, axis=0) + >>> prewitt_v = ndimage.prewitt(ascent, axis=1) + >>> magnitude = np.sqrt(prewitt_h ** 2 + prewitt_v ** 2) + >>> magnitude *= 255 / np.max(magnitude) # Normalization + >>> fig, axes = plt.subplots(2, 2, figsize = (8, 8)) + >>> plt.gray() + >>> axes[0, 0].imshow(ascent) + >>> axes[0, 1].imshow(prewitt_h) + >>> axes[1, 0].imshow(prewitt_v) + >>> axes[1, 1].imshow(magnitude) + >>> titles = ["original", "horizontal", "vertical", "magnitude"] + >>> for i, ax in enumerate(axes.ravel()): + ... ax.set_title(titles[i]) + ... ax.axis("off") + >>> plt.show() + + """ + input = np.asarray(input) + axis = normalize_axis_index(axis, input.ndim) + output = _ni_support._get_output(output, input) + modes = _ni_support._normalize_sequence(mode, input.ndim) + correlate1d(input, [-1, 0, 1], axis, output, modes[axis], cval, 0) + axes = [ii for ii in range(input.ndim) if ii != axis] + for ii in axes: + correlate1d(output, [1, 1, 1], ii, output, modes[ii], cval, 0,) + return output + + +@_ni_docstrings.docfiller +def sobel(input, axis=-1, output=None, mode="reflect", cval=0.0): + """Calculate a Sobel filter. + + Parameters + ---------- + %(input)s + %(axis)s + %(output)s + %(mode_multiple)s + %(cval)s + + Returns + ------- + sobel : ndarray + Filtered array. Has the same shape as `input`. + + Notes + ----- + This function computes the axis-specific Sobel gradient. + The horizontal edges can be emphasised with the horizontal transform (axis=0), + the vertical edges with the vertical transform (axis=1) and so on for higher + dimensions. These can be combined to give the magnitude. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import matplotlib.pyplot as plt + >>> import numpy as np + >>> ascent = datasets.ascent().astype('int32') + >>> sobel_h = ndimage.sobel(ascent, 0) # horizontal gradient + >>> sobel_v = ndimage.sobel(ascent, 1) # vertical gradient + >>> magnitude = np.sqrt(sobel_h**2 + sobel_v**2) + >>> magnitude *= 255.0 / np.max(magnitude) # normalization + >>> fig, axs = plt.subplots(2, 2, figsize=(8, 8)) + >>> plt.gray() # show the filtered result in grayscale + >>> axs[0, 0].imshow(ascent) + >>> axs[0, 1].imshow(sobel_h) + >>> axs[1, 0].imshow(sobel_v) + >>> axs[1, 1].imshow(magnitude) + >>> titles = ["original", "horizontal", "vertical", "magnitude"] + >>> for i, ax in enumerate(axs.ravel()): + ... ax.set_title(titles[i]) + ... ax.axis("off") + >>> plt.show() + + """ + input = np.asarray(input) + axis = normalize_axis_index(axis, input.ndim) + output = _ni_support._get_output(output, input) + modes = _ni_support._normalize_sequence(mode, input.ndim) + correlate1d(input, [-1, 0, 1], axis, output, modes[axis], cval, 0) + axes = [ii for ii in range(input.ndim) if ii != axis] + for ii in axes: + correlate1d(output, [1, 2, 1], ii, output, modes[ii], cval, 0) + return output + + +@_ni_docstrings.docfiller +def generic_laplace(input, derivative2, output=None, mode="reflect", + cval=0.0, + extra_arguments=(), + extra_keywords=None, + *, axes=None): + """ + N-D Laplace filter using a provided second derivative function. + + Parameters + ---------- + %(input)s + derivative2 : callable + Callable with the following signature:: + + derivative2(input, axis, output, mode, cval, + *extra_arguments, **extra_keywords) + + See `extra_arguments`, `extra_keywords` below. + %(output)s + %(mode_multiple)s + %(cval)s + %(extra_keywords)s + %(extra_arguments)s + axes : tuple of int or None + The axes over which to apply the filter. If a `mode` tuple is + provided, its length must match the number of axes. + + Returns + ------- + generic_laplace : ndarray + Filtered array. Has the same shape as `input`. + + """ + if extra_keywords is None: + extra_keywords = {} + input = np.asarray(input) + output = _ni_support._get_output(output, input) + axes = _ni_support._check_axes(axes, input.ndim) + if len(axes) > 0: + modes = _ni_support._normalize_sequence(mode, len(axes)) + derivative2(input, axes[0], output, modes[0], cval, + *extra_arguments, **extra_keywords) + for ii in range(1, len(axes)): + tmp = derivative2(input, axes[ii], output.dtype, modes[ii], cval, + *extra_arguments, **extra_keywords) + output += tmp + else: + output[...] = input[...] + return output + + +@_ni_docstrings.docfiller +def laplace(input, output=None, mode="reflect", cval=0.0, *, axes=None): + """N-D Laplace filter based on approximate second derivatives. + + Parameters + ---------- + %(input)s + %(output)s + %(mode_multiple)s + %(cval)s + axes : tuple of int or None + The axes over which to apply the filter. If a `mode` tuple is + provided, its length must match the number of axes. + + Returns + ------- + laplace : ndarray + Filtered array. Has the same shape as `input`. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> plt.gray() # show the filtered result in grayscale + >>> ax1 = fig.add_subplot(121) # left side + >>> ax2 = fig.add_subplot(122) # right side + >>> ascent = datasets.ascent() + >>> result = ndimage.laplace(ascent) + >>> ax1.imshow(ascent) + >>> ax2.imshow(result) + >>> plt.show() + """ + def derivative2(input, axis, output, mode, cval): + return correlate1d(input, [1, -2, 1], axis, output, mode, cval, 0) + return generic_laplace(input, derivative2, output, mode, cval, axes=axes) + + +@_ni_docstrings.docfiller +def gaussian_laplace(input, sigma, output=None, mode="reflect", + cval=0.0, *, axes=None, **kwargs): + """Multidimensional Laplace filter using Gaussian second derivatives. + + Parameters + ---------- + %(input)s + sigma : scalar or sequence of scalars + The standard deviations of the Gaussian filter are given for + each axis as a sequence, or as a single number, in which case + it is equal for all axes. + %(output)s + %(mode_multiple)s + %(cval)s + axes : tuple of int or None + The axes over which to apply the filter. If `sigma` or `mode` tuples + are provided, their length must match the number of axes. + Extra keyword arguments will be passed to gaussian_filter(). + + Returns + ------- + gaussian_laplace : ndarray + Filtered array. Has the same shape as `input`. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import matplotlib.pyplot as plt + >>> ascent = datasets.ascent() + + >>> fig = plt.figure() + >>> plt.gray() # show the filtered result in grayscale + >>> ax1 = fig.add_subplot(121) # left side + >>> ax2 = fig.add_subplot(122) # right side + + >>> result = ndimage.gaussian_laplace(ascent, sigma=1) + >>> ax1.imshow(result) + + >>> result = ndimage.gaussian_laplace(ascent, sigma=3) + >>> ax2.imshow(result) + >>> plt.show() + """ + input = np.asarray(input) + + def derivative2(input, axis, output, mode, cval, sigma, **kwargs): + order = [0] * input.ndim + order[axis] = 2 + return gaussian_filter(input, sigma, order, output, mode, cval, + **kwargs) + + axes = _ni_support._check_axes(axes, input.ndim) + num_axes = len(axes) + sigma = _ni_support._normalize_sequence(sigma, num_axes) + if num_axes < input.ndim: + # set sigma = 0 for any axes not being filtered + sigma_temp = [0,] * input.ndim + for s, ax in zip(sigma, axes): + sigma_temp[ax] = s + sigma = sigma_temp + + return generic_laplace(input, derivative2, output, mode, cval, + extra_arguments=(sigma,), + extra_keywords=kwargs, + axes=axes) + + +@_ni_docstrings.docfiller +def generic_gradient_magnitude(input, derivative, output=None, + mode="reflect", cval=0.0, + extra_arguments=(), extra_keywords=None, + *, axes=None): + """Gradient magnitude using a provided gradient function. + + Parameters + ---------- + %(input)s + derivative : callable + Callable with the following signature:: + + derivative(input, axis, output, mode, cval, + *extra_arguments, **extra_keywords) + + See `extra_arguments`, `extra_keywords` below. + `derivative` can assume that `input` and `output` are ndarrays. + Note that the output from `derivative` is modified inplace; + be careful to copy important inputs before returning them. + %(output)s + %(mode_multiple)s + %(cval)s + %(extra_keywords)s + %(extra_arguments)s + axes : tuple of int or None + The axes over which to apply the filter. If a `mode` tuple is + provided, its length must match the number of axes. + + Returns + ------- + generic_gradient_matnitude : ndarray + Filtered array. Has the same shape as `input`. + + """ + if extra_keywords is None: + extra_keywords = {} + input = np.asarray(input) + output = _ni_support._get_output(output, input) + axes = _ni_support._check_axes(axes, input.ndim) + if len(axes) > 0: + modes = _ni_support._normalize_sequence(mode, len(axes)) + derivative(input, axes[0], output, modes[0], cval, + *extra_arguments, **extra_keywords) + np.multiply(output, output, output) + for ii in range(1, len(axes)): + tmp = derivative(input, axes[ii], output.dtype, modes[ii], cval, + *extra_arguments, **extra_keywords) + np.multiply(tmp, tmp, tmp) + output += tmp + # This allows the sqrt to work with a different default casting + np.sqrt(output, output, casting='unsafe') + else: + output[...] = input[...] + return output + + +@_ni_docstrings.docfiller +def gaussian_gradient_magnitude(input, sigma, output=None, + mode="reflect", cval=0.0, *, axes=None, + **kwargs): + """Multidimensional gradient magnitude using Gaussian derivatives. + + Parameters + ---------- + %(input)s + sigma : scalar or sequence of scalars + The standard deviations of the Gaussian filter are given for + each axis as a sequence, or as a single number, in which case + it is equal for all axes. + %(output)s + %(mode_multiple)s + %(cval)s + axes : tuple of int or None + The axes over which to apply the filter. If `sigma` or `mode` tuples + are provided, their length must match the number of axes. + Extra keyword arguments will be passed to gaussian_filter(). + + Returns + ------- + gaussian_gradient_magnitude : ndarray + Filtered array. Has the same shape as `input`. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> plt.gray() # show the filtered result in grayscale + >>> ax1 = fig.add_subplot(121) # left side + >>> ax2 = fig.add_subplot(122) # right side + >>> ascent = datasets.ascent() + >>> result = ndimage.gaussian_gradient_magnitude(ascent, sigma=5) + >>> ax1.imshow(ascent) + >>> ax2.imshow(result) + >>> plt.show() + """ + input = np.asarray(input) + + def derivative(input, axis, output, mode, cval, sigma, **kwargs): + order = [0] * input.ndim + order[axis] = 1 + return gaussian_filter(input, sigma, order, output, mode, + cval, **kwargs) + + return generic_gradient_magnitude(input, derivative, output, mode, + cval, extra_arguments=(sigma,), + extra_keywords=kwargs, axes=axes) + + +def _correlate_or_convolve(input, weights, output, mode, cval, origin, + convolution, axes): + input = np.asarray(input) + weights = np.asarray(weights) + complex_input = input.dtype.kind == 'c' + complex_weights = weights.dtype.kind == 'c' + if complex_input or complex_weights: + if complex_weights and not convolution: + # As for np.correlate, conjugate weights rather than input. + weights = weights.conj() + kwargs = dict( + mode=mode, origin=origin, convolution=convolution, axes=axes + ) + output = _ni_support._get_output(output, input, complex_output=True) + + return _complex_via_real_components(_correlate_or_convolve, input, + weights, output, cval, **kwargs) + + axes = _ni_support._check_axes(axes, input.ndim) + weights = np.asarray(weights, dtype=np.float64) + + # expand weights and origins if num_axes < input.ndim + weights = _expand_footprint(input.ndim, axes, weights, "weights") + origins = _expand_origin(input.ndim, axes, origin) + + wshape = [ii for ii in weights.shape if ii > 0] + if len(wshape) != input.ndim: + raise RuntimeError(f"weights.ndim ({len(wshape)}) must match " + f"len(axes) ({len(axes)})") + if convolution: + weights = weights[tuple([slice(None, None, -1)] * weights.ndim)] + for ii in range(len(origins)): + origins[ii] = -origins[ii] + if not weights.shape[ii] & 1: + origins[ii] -= 1 + for origin, lenw in zip(origins, wshape): + if _invalid_origin(origin, lenw): + raise ValueError('Invalid origin; origin must satisfy ' + '-(weights.shape[k] // 2) <= origin[k] <= ' + '(weights.shape[k]-1) // 2') + + if not weights.flags.contiguous: + weights = weights.copy() + output = _ni_support._get_output(output, input) + temp_needed = np.may_share_memory(input, output) + if temp_needed: + # input and output arrays cannot share memory + temp = output + output = _ni_support._get_output(output.dtype, input) + if not isinstance(mode, str) and isinstance(mode, Iterable): + raise RuntimeError("A sequence of modes is not supported") + mode = _ni_support._extend_mode_to_code(mode) + _nd_image.correlate(input, weights, output, mode, cval, origins) + if temp_needed: + temp[...] = output + output = temp + return output + + +@_ni_docstrings.docfiller +def correlate(input, weights, output=None, mode='reflect', cval=0.0, + origin=0, *, axes=None): + """ + Multidimensional correlation. + + The array is correlated with the given kernel. + + Parameters + ---------- + %(input)s + weights : ndarray + array of weights, same number of dimensions as input + %(output)s + %(mode_reflect)s + %(cval)s + %(origin_multiple)s + axes : tuple of int or None, optional + If None, `input` is filtered along all axes. Otherwise, + `input` is filtered along the specified axes. When `axes` is + specified, any tuples used for `mode` or `origin` must match the length + of `axes`. The ith entry in any of these tuples corresponds to the ith + entry in `axes`. + + Returns + ------- + result : ndarray + The result of correlation of `input` with `weights`. + + See Also + -------- + convolve : Convolve an image with a kernel. + + Examples + -------- + Correlation is the process of moving a filter mask often referred to + as kernel over the image and computing the sum of products at each location. + + >>> from scipy.ndimage import correlate + >>> import numpy as np + >>> input_img = np.arange(25).reshape(5,5) + >>> print(input_img) + [[ 0 1 2 3 4] + [ 5 6 7 8 9] + [10 11 12 13 14] + [15 16 17 18 19] + [20 21 22 23 24]] + + Define a kernel (weights) for correlation. In this example, it is for sum of + center and up, down, left and right next elements. + + >>> weights = [[0, 1, 0], + ... [1, 1, 1], + ... [0, 1, 0]] + + We can calculate a correlation result: + For example, element ``[2,2]`` is ``7 + 11 + 12 + 13 + 17 = 60``. + + >>> correlate(input_img, weights) + array([[ 6, 10, 15, 20, 24], + [ 26, 30, 35, 40, 44], + [ 51, 55, 60, 65, 69], + [ 76, 80, 85, 90, 94], + [ 96, 100, 105, 110, 114]]) + + """ + return _correlate_or_convolve(input, weights, output, mode, cval, + origin, False, axes) + + +@_ni_docstrings.docfiller +def convolve(input, weights, output=None, mode='reflect', cval=0.0, + origin=0, *, axes=None): + """ + Multidimensional convolution. + + The array is convolved with the given kernel. + + Parameters + ---------- + %(input)s + weights : array_like + Array of weights, same number of dimensions as input + %(output)s + %(mode_reflect)s + cval : scalar, optional + Value to fill past edges of input if `mode` is 'constant'. Default + is 0.0 + origin : int or sequence, optional + Controls the placement of the filter on the input array's pixels. + A value of 0 (the default) centers the filter over the pixel, with + positive values shifting the filter to the right, and negative ones + to the left. By passing a sequence of origins with length equal to + the number of dimensions of the input array, different shifts can + be specified along each axis. + axes : tuple of int or None, optional + If None, `input` is filtered along all axes. Otherwise, + `input` is filtered along the specified axes. When `axes` is + specified, any tuples used for `mode` or `origin` must match the length + of `axes`. The ith entry in any of these tuples corresponds to the ith + entry in `axes`. + + Returns + ------- + result : ndarray + The result of convolution of `input` with `weights`. + + See Also + -------- + correlate : Correlate an image with a kernel. + + Notes + ----- + Each value in result is :math:`C_i = \\sum_j{I_{i+k-j} W_j}`, where + W is the `weights` kernel, + j is the N-D spatial index over :math:`W`, + I is the `input` and k is the coordinate of the center of + W, specified by `origin` in the input parameters. + + Examples + -------- + Perhaps the simplest case to understand is ``mode='constant', cval=0.0``, + because in this case borders (i.e., where the `weights` kernel, centered + on any one value, extends beyond an edge of `input`) are treated as zeros. + + >>> import numpy as np + >>> a = np.array([[1, 2, 0, 0], + ... [5, 3, 0, 4], + ... [0, 0, 0, 7], + ... [9, 3, 0, 0]]) + >>> k = np.array([[1,1,1],[1,1,0],[1,0,0]]) + >>> from scipy import ndimage + >>> ndimage.convolve(a, k, mode='constant', cval=0.0) + array([[11, 10, 7, 4], + [10, 3, 11, 11], + [15, 12, 14, 7], + [12, 3, 7, 0]]) + + Setting ``cval=1.0`` is equivalent to padding the outer edge of `input` + with 1.0's (and then extracting only the original region of the result). + + >>> ndimage.convolve(a, k, mode='constant', cval=1.0) + array([[13, 11, 8, 7], + [11, 3, 11, 14], + [16, 12, 14, 10], + [15, 6, 10, 5]]) + + With ``mode='reflect'`` (the default), outer values are reflected at the + edge of `input` to fill in missing values. + + >>> b = np.array([[2, 0, 0], + ... [1, 0, 0], + ... [0, 0, 0]]) + >>> k = np.array([[0,1,0], [0,1,0], [0,1,0]]) + >>> ndimage.convolve(b, k, mode='reflect') + array([[5, 0, 0], + [3, 0, 0], + [1, 0, 0]]) + + This includes diagonally at the corners. + + >>> k = np.array([[1,0,0],[0,1,0],[0,0,1]]) + >>> ndimage.convolve(b, k) + array([[4, 2, 0], + [3, 2, 0], + [1, 1, 0]]) + + With ``mode='nearest'``, the single nearest value in to an edge in + `input` is repeated as many times as needed to match the overlapping + `weights`. + + >>> c = np.array([[2, 0, 1], + ... [1, 0, 0], + ... [0, 0, 0]]) + >>> k = np.array([[0, 1, 0], + ... [0, 1, 0], + ... [0, 1, 0], + ... [0, 1, 0], + ... [0, 1, 0]]) + >>> ndimage.convolve(c, k, mode='nearest') + array([[7, 0, 3], + [5, 0, 2], + [3, 0, 1]]) + + """ + return _correlate_or_convolve(input, weights, output, mode, cval, + origin, True, axes) + + +@_ni_docstrings.docfiller +def uniform_filter1d(input, size, axis=-1, output=None, + mode="reflect", cval=0.0, origin=0): + """Calculate a 1-D uniform filter along the given axis. + + The lines of the array along the given axis are filtered with a + uniform filter of given size. + + Parameters + ---------- + %(input)s + size : int + length of uniform filter + %(axis)s + %(output)s + %(mode_reflect)s + %(cval)s + %(origin)s + + Returns + ------- + result : ndarray + Filtered array. Has same shape as `input`. + + Examples + -------- + >>> from scipy.ndimage import uniform_filter1d + >>> uniform_filter1d([2, 8, 0, 4, 1, 9, 9, 0], size=3) + array([4, 3, 4, 1, 4, 6, 6, 3]) + """ + input = np.asarray(input) + axis = normalize_axis_index(axis, input.ndim) + if size < 1: + raise RuntimeError('incorrect filter size') + complex_output = input.dtype.kind == 'c' + output = _ni_support._get_output(output, input, + complex_output=complex_output) + if (size // 2 + origin < 0) or (size // 2 + origin >= size): + raise ValueError('invalid origin') + mode = _ni_support._extend_mode_to_code(mode) + if not complex_output: + _nd_image.uniform_filter1d(input, size, axis, output, mode, cval, + origin) + else: + _nd_image.uniform_filter1d(input.real, size, axis, output.real, mode, + np.real(cval), origin) + _nd_image.uniform_filter1d(input.imag, size, axis, output.imag, mode, + np.imag(cval), origin) + return output + + +@_ni_docstrings.docfiller +def uniform_filter(input, size=3, output=None, mode="reflect", + cval=0.0, origin=0, *, axes=None): + """Multidimensional uniform filter. + + Parameters + ---------- + %(input)s + size : int or sequence of ints, optional + The sizes of the uniform filter are given for each axis as a + sequence, or as a single number, in which case the size is + equal for all axes. + %(output)s + %(mode_multiple)s + %(cval)s + %(origin_multiple)s + axes : tuple of int or None, optional + If None, `input` is filtered along all axes. Otherwise, + `input` is filtered along the specified axes. When `axes` is + specified, any tuples used for `size`, `origin`, and/or `mode` + must match the length of `axes`. The ith entry in any of these tuples + corresponds to the ith entry in `axes`. + + Returns + ------- + uniform_filter : ndarray + Filtered array. Has the same shape as `input`. + + Notes + ----- + The multidimensional filter is implemented as a sequence of + 1-D uniform filters. The intermediate arrays are stored + in the same data type as the output. Therefore, for output types + with a limited precision, the results may be imprecise because + intermediate results may be stored with insufficient precision. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> plt.gray() # show the filtered result in grayscale + >>> ax1 = fig.add_subplot(121) # left side + >>> ax2 = fig.add_subplot(122) # right side + >>> ascent = datasets.ascent() + >>> result = ndimage.uniform_filter(ascent, size=20) + >>> ax1.imshow(ascent) + >>> ax2.imshow(result) + >>> plt.show() + """ + input = np.asarray(input) + output = _ni_support._get_output(output, input, + complex_output=input.dtype.kind == 'c') + axes = _ni_support._check_axes(axes, input.ndim) + num_axes = len(axes) + sizes = _ni_support._normalize_sequence(size, num_axes) + origins = _ni_support._normalize_sequence(origin, num_axes) + modes = _ni_support._normalize_sequence(mode, num_axes) + axes = [(axes[ii], sizes[ii], origins[ii], modes[ii]) + for ii in range(num_axes) if sizes[ii] > 1] + if len(axes) > 0: + for axis, size, origin, mode in axes: + uniform_filter1d(input, int(size), axis, output, mode, + cval, origin) + input = output + else: + output[...] = input[...] + return output + + +@_ni_docstrings.docfiller +def minimum_filter1d(input, size, axis=-1, output=None, + mode="reflect", cval=0.0, origin=0): + """Calculate a 1-D minimum filter along the given axis. + + The lines of the array along the given axis are filtered with a + minimum filter of given size. + + Parameters + ---------- + %(input)s + size : int + length along which to calculate 1D minimum + %(axis)s + %(output)s + %(mode_reflect)s + %(cval)s + %(origin)s + + Returns + ------- + result : ndarray. + Filtered image. Has the same shape as `input`. + + Notes + ----- + This function implements the MINLIST algorithm [1]_, as described by + Richard Harter [2]_, and has a guaranteed O(n) performance, `n` being + the `input` length, regardless of filter size. + + References + ---------- + .. [1] http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.42.2777 + .. [2] http://www.richardhartersworld.com/cri/2001/slidingmin.html + + + Examples + -------- + >>> from scipy.ndimage import minimum_filter1d + >>> minimum_filter1d([2, 8, 0, 4, 1, 9, 9, 0], size=3) + array([2, 0, 0, 0, 1, 1, 0, 0]) + """ + input = np.asarray(input) + if np.iscomplexobj(input): + raise TypeError('Complex type not supported') + axis = normalize_axis_index(axis, input.ndim) + if size < 1: + raise RuntimeError('incorrect filter size') + output = _ni_support._get_output(output, input) + if (size // 2 + origin < 0) or (size // 2 + origin >= size): + raise ValueError('invalid origin') + mode = _ni_support._extend_mode_to_code(mode) + _nd_image.min_or_max_filter1d(input, size, axis, output, mode, cval, + origin, 1) + return output + + +@_ni_docstrings.docfiller +def maximum_filter1d(input, size, axis=-1, output=None, + mode="reflect", cval=0.0, origin=0): + """Calculate a 1-D maximum filter along the given axis. + + The lines of the array along the given axis are filtered with a + maximum filter of given size. + + Parameters + ---------- + %(input)s + size : int + Length along which to calculate the 1-D maximum. + %(axis)s + %(output)s + %(mode_reflect)s + %(cval)s + %(origin)s + + Returns + ------- + maximum1d : ndarray, None + Maximum-filtered array with same shape as input. + None if `output` is not None + + Notes + ----- + This function implements the MAXLIST algorithm [1]_, as described by + Richard Harter [2]_, and has a guaranteed O(n) performance, `n` being + the `input` length, regardless of filter size. + + References + ---------- + .. [1] http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.42.2777 + .. [2] http://www.richardhartersworld.com/cri/2001/slidingmin.html + + Examples + -------- + >>> from scipy.ndimage import maximum_filter1d + >>> maximum_filter1d([2, 8, 0, 4, 1, 9, 9, 0], size=3) + array([8, 8, 8, 4, 9, 9, 9, 9]) + """ + input = np.asarray(input) + if np.iscomplexobj(input): + raise TypeError('Complex type not supported') + axis = normalize_axis_index(axis, input.ndim) + if size < 1: + raise RuntimeError('incorrect filter size') + output = _ni_support._get_output(output, input) + if (size // 2 + origin < 0) or (size // 2 + origin >= size): + raise ValueError('invalid origin') + mode = _ni_support._extend_mode_to_code(mode) + _nd_image.min_or_max_filter1d(input, size, axis, output, mode, cval, + origin, 0) + return output + + +def _min_or_max_filter(input, size, footprint, structure, output, mode, + cval, origin, minimum, axes=None): + if (size is not None) and (footprint is not None): + warnings.warn("ignoring size because footprint is set", + UserWarning, stacklevel=3) + if structure is None: + if footprint is None: + if size is None: + raise RuntimeError("no footprint provided") + separable = True + else: + footprint = np.asarray(footprint, dtype=bool) + if not footprint.any(): + raise ValueError("All-zero footprint is not supported.") + if footprint.all(): + size = footprint.shape + footprint = None + separable = True + else: + separable = False + else: + structure = np.asarray(structure, dtype=np.float64) + separable = False + if footprint is None: + footprint = np.ones(structure.shape, bool) + else: + footprint = np.asarray(footprint, dtype=bool) + input = np.asarray(input) + if np.iscomplexobj(input): + raise TypeError("Complex type not supported") + output = _ni_support._get_output(output, input) + temp_needed = np.may_share_memory(input, output) + if temp_needed: + # input and output arrays cannot share memory + temp = output + output = _ni_support._get_output(output.dtype, input) + axes = _ni_support._check_axes(axes, input.ndim) + num_axes = len(axes) + if separable: + origins = _ni_support._normalize_sequence(origin, num_axes) + sizes = _ni_support._normalize_sequence(size, num_axes) + modes = _ni_support._normalize_sequence(mode, num_axes) + axes = [(axes[ii], sizes[ii], origins[ii], modes[ii]) + for ii in range(len(axes)) if sizes[ii] > 1] + if minimum: + filter_ = minimum_filter1d + else: + filter_ = maximum_filter1d + if len(axes) > 0: + for axis, size, origin, mode in axes: + filter_(input, int(size), axis, output, mode, cval, origin) + input = output + else: + output[...] = input[...] + else: + # expand origins and footprint if num_axes < input.ndim + footprint = _expand_footprint(input.ndim, axes, footprint) + origins = _expand_origin(input.ndim, axes, origin) + + fshape = [ii for ii in footprint.shape if ii > 0] + if len(fshape) != input.ndim: + raise RuntimeError(f"footprint.ndim ({footprint.ndim}) must match " + f"len(axes) ({len(axes)})") + for origin, lenf in zip(origins, fshape): + if (lenf // 2 + origin < 0) or (lenf // 2 + origin >= lenf): + raise ValueError("invalid origin") + if not footprint.flags.contiguous: + footprint = footprint.copy() + if structure is not None: + if len(structure.shape) != num_axes: + raise RuntimeError("structure array has incorrect shape") + if num_axes != structure.ndim: + structure = np.expand_dims( + structure, + tuple(ax for ax in range(structure.ndim) if ax not in axes) + ) + if not structure.flags.contiguous: + structure = structure.copy() + if not isinstance(mode, str) and isinstance(mode, Iterable): + raise RuntimeError( + "A sequence of modes is not supported for non-separable " + "footprints") + mode = _ni_support._extend_mode_to_code(mode) + _nd_image.min_or_max_filter(input, footprint, structure, output, + mode, cval, origins, minimum) + if temp_needed: + temp[...] = output + output = temp + return output + + +@_ni_docstrings.docfiller +def minimum_filter(input, size=None, footprint=None, output=None, + mode="reflect", cval=0.0, origin=0, *, axes=None): + """Calculate a multidimensional minimum filter. + + Parameters + ---------- + %(input)s + %(size_foot)s + %(output)s + %(mode_multiple)s + %(cval)s + %(origin_multiple)s + axes : tuple of int or None, optional + If None, `input` is filtered along all axes. Otherwise, + `input` is filtered along the specified axes. When `axes` is + specified, any tuples used for `size`, `origin`, and/or `mode` + must match the length of `axes`. The ith entry in any of these tuples + corresponds to the ith entry in `axes`. + + Returns + ------- + minimum_filter : ndarray + Filtered array. Has the same shape as `input`. + + Notes + ----- + A sequence of modes (one per axis) is only supported when the footprint is + separable. Otherwise, a single mode string must be provided. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> plt.gray() # show the filtered result in grayscale + >>> ax1 = fig.add_subplot(121) # left side + >>> ax2 = fig.add_subplot(122) # right side + >>> ascent = datasets.ascent() + >>> result = ndimage.minimum_filter(ascent, size=20) + >>> ax1.imshow(ascent) + >>> ax2.imshow(result) + >>> plt.show() + """ + return _min_or_max_filter(input, size, footprint, None, output, mode, + cval, origin, 1, axes) + + +@_ni_docstrings.docfiller +def maximum_filter(input, size=None, footprint=None, output=None, + mode="reflect", cval=0.0, origin=0, *, axes=None): + """Calculate a multidimensional maximum filter. + + Parameters + ---------- + %(input)s + %(size_foot)s + %(output)s + %(mode_multiple)s + %(cval)s + %(origin_multiple)s + axes : tuple of int or None, optional + If None, `input` is filtered along all axes. Otherwise, + `input` is filtered along the specified axes. When `axes` is + specified, any tuples used for `size`, `origin`, and/or `mode` + must match the length of `axes`. The ith entry in any of these tuples + corresponds to the ith entry in `axes`. + + Returns + ------- + maximum_filter : ndarray + Filtered array. Has the same shape as `input`. + + Notes + ----- + A sequence of modes (one per axis) is only supported when the footprint is + separable. Otherwise, a single mode string must be provided. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> plt.gray() # show the filtered result in grayscale + >>> ax1 = fig.add_subplot(121) # left side + >>> ax2 = fig.add_subplot(122) # right side + >>> ascent = datasets.ascent() + >>> result = ndimage.maximum_filter(ascent, size=20) + >>> ax1.imshow(ascent) + >>> ax2.imshow(result) + >>> plt.show() + """ + return _min_or_max_filter(input, size, footprint, None, output, mode, + cval, origin, 0, axes) + + +@_ni_docstrings.docfiller +def _rank_filter(input, rank, size=None, footprint=None, output=None, + mode="reflect", cval=0.0, origin=0, operation='rank', + axes=None): + if (size is not None) and (footprint is not None): + warnings.warn("ignoring size because footprint is set", + UserWarning, stacklevel=3) + input = np.asarray(input) + if np.iscomplexobj(input): + raise TypeError('Complex type not supported') + axes = _ni_support._check_axes(axes, input.ndim) + num_axes = len(axes) + if footprint is None: + if size is None: + raise RuntimeError("no footprint or filter size provided") + sizes = _ni_support._normalize_sequence(size, num_axes) + footprint = np.ones(sizes, dtype=bool) + else: + footprint = np.asarray(footprint, dtype=bool) + # expand origins, footprint and modes if num_axes < input.ndim + footprint = _expand_footprint(input.ndim, axes, footprint) + origins = _expand_origin(input.ndim, axes, origin) + mode = _expand_mode(input.ndim, axes, mode) + + fshape = [ii for ii in footprint.shape if ii > 0] + if len(fshape) != input.ndim: + raise RuntimeError(f"footprint.ndim ({footprint.ndim}) must match " + f"len(axes) ({len(axes)})") + for origin, lenf in zip(origins, fshape): + if (lenf // 2 + origin < 0) or (lenf // 2 + origin >= lenf): + raise ValueError('invalid origin') + if not footprint.flags.contiguous: + footprint = footprint.copy() + filter_size = np.where(footprint, 1, 0).sum() + if operation == 'median': + rank = filter_size // 2 + elif operation == 'percentile': + percentile = rank + if percentile < 0.0: + percentile += 100.0 + if percentile < 0 or percentile > 100: + raise RuntimeError('invalid percentile') + if percentile == 100.0: + rank = filter_size - 1 + else: + rank = int(float(filter_size) * percentile / 100.0) + if rank < 0: + rank += filter_size + if rank < 0 or rank >= filter_size: + raise RuntimeError('rank not within filter footprint size') + if rank == 0: + return minimum_filter(input, None, footprint, output, mode, cval, + origins, axes=None) + elif rank == filter_size - 1: + return maximum_filter(input, None, footprint, output, mode, cval, + origins, axes=None) + else: + output = _ni_support._get_output(output, input) + temp_needed = np.may_share_memory(input, output) + if temp_needed: + # input and output arrays cannot share memory + temp = output + output = _ni_support._get_output(output.dtype, input) + if not isinstance(mode, str) and isinstance(mode, Iterable): + raise RuntimeError( + "A sequence of modes is not supported by non-separable rank " + "filters") + mode = _ni_support._extend_mode_to_code(mode, is_filter=True) + if input.ndim == 1: + if input.dtype in (np.int64, np.float64, np.float32): + x = input + x_out = output + elif input.dtype == np.float16: + x = input.astype('float32') + x_out = np.empty(x.shape, dtype='float32') + elif np.result_type(input, np.int64) == np.int64: + x = input.astype('int64') + x_out = np.empty(x.shape, dtype='int64') + elif input.dtype.kind in 'biu': + # cast any other boolean, integer or unsigned type to int64 + x = input.astype('int64') + x_out = np.empty(x.shape, dtype='int64') + else: + raise RuntimeError('Unsupported array type') + cval = x.dtype.type(cval) + _rank_filter_1d.rank_filter(x, rank, footprint.size, x_out, mode, cval, + origin) + if input.dtype not in (np.int64, np.float64, np.float32): + np.copyto(output, x_out, casting='unsafe') + else: + _nd_image.rank_filter(input, rank, footprint, output, mode, cval, origins) + if temp_needed: + temp[...] = output + output = temp + return output + + +@_ni_docstrings.docfiller +def rank_filter(input, rank, size=None, footprint=None, output=None, + mode="reflect", cval=0.0, origin=0, *, axes=None): + """Calculate a multidimensional rank filter. + + Parameters + ---------- + %(input)s + rank : int + The rank parameter may be less than zero, i.e., rank = -1 + indicates the largest element. + %(size_foot)s + %(output)s + %(mode_reflect)s + %(cval)s + %(origin_multiple)s + axes : tuple of int or None, optional + If None, `input` is filtered along all axes. Otherwise, + `input` is filtered along the specified axes. When `axes` is + specified, any tuples used for `size`, `origin`, and/or `mode` + must match the length of `axes`. The ith entry in any of these tuples + corresponds to the ith entry in `axes`. + + Returns + ------- + rank_filter : ndarray + Filtered array. Has the same shape as `input`. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> plt.gray() # show the filtered result in grayscale + >>> ax1 = fig.add_subplot(121) # left side + >>> ax2 = fig.add_subplot(122) # right side + >>> ascent = datasets.ascent() + >>> result = ndimage.rank_filter(ascent, rank=42, size=20) + >>> ax1.imshow(ascent) + >>> ax2.imshow(result) + >>> plt.show() + """ + rank = operator.index(rank) + return _rank_filter(input, rank, size, footprint, output, mode, cval, + origin, 'rank', axes=axes) + + +@_ni_docstrings.docfiller +def median_filter(input, size=None, footprint=None, output=None, + mode="reflect", cval=0.0, origin=0, *, axes=None): + """ + Calculate a multidimensional median filter. + + Parameters + ---------- + %(input)s + %(size_foot)s + %(output)s + %(mode_reflect)s + %(cval)s + %(origin_multiple)s + axes : tuple of int or None, optional + If None, `input` is filtered along all axes. Otherwise, + `input` is filtered along the specified axes. When `axes` is + specified, any tuples used for `size`, `origin`, and/or `mode` + must match the length of `axes`. The ith entry in any of these tuples + corresponds to the ith entry in `axes`. + + Returns + ------- + median_filter : ndarray + Filtered array. Has the same shape as `input`. + + See Also + -------- + scipy.signal.medfilt2d + + Notes + ----- + For 2-dimensional images with ``uint8``, ``float32`` or ``float64`` dtypes + the specialised function `scipy.signal.medfilt2d` may be faster. It is + however limited to constant mode with ``cval=0``. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> plt.gray() # show the filtered result in grayscale + >>> ax1 = fig.add_subplot(121) # left side + >>> ax2 = fig.add_subplot(122) # right side + >>> ascent = datasets.ascent() + >>> result = ndimage.median_filter(ascent, size=20) + >>> ax1.imshow(ascent) + >>> ax2.imshow(result) + >>> plt.show() + """ + return _rank_filter(input, 0, size, footprint, output, mode, cval, + origin, 'median', axes=axes) + + +@_ni_docstrings.docfiller +def percentile_filter(input, percentile, size=None, footprint=None, + output=None, mode="reflect", cval=0.0, origin=0, *, + axes=None): + """Calculate a multidimensional percentile filter. + + Parameters + ---------- + %(input)s + percentile : scalar + The percentile parameter may be less than zero, i.e., + percentile = -20 equals percentile = 80 + %(size_foot)s + %(output)s + %(mode_reflect)s + %(cval)s + %(origin_multiple)s + axes : tuple of int or None, optional + If None, `input` is filtered along all axes. Otherwise, + `input` is filtered along the specified axes. When `axes` is + specified, any tuples used for `size`, `origin`, and/or `mode` + must match the length of `axes`. The ith entry in any of these tuples + corresponds to the ith entry in `axes`. + + Returns + ------- + percentile_filter : ndarray + Filtered array. Has the same shape as `input`. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> plt.gray() # show the filtered result in grayscale + >>> ax1 = fig.add_subplot(121) # left side + >>> ax2 = fig.add_subplot(122) # right side + >>> ascent = datasets.ascent() + >>> result = ndimage.percentile_filter(ascent, percentile=20, size=20) + >>> ax1.imshow(ascent) + >>> ax2.imshow(result) + >>> plt.show() + """ + return _rank_filter(input, percentile, size, footprint, output, mode, + cval, origin, 'percentile', axes=axes) + + +@_ni_docstrings.docfiller +def generic_filter1d(input, function, filter_size, axis=-1, + output=None, mode="reflect", cval=0.0, origin=0, + extra_arguments=(), extra_keywords=None): + """Calculate a 1-D filter along the given axis. + + `generic_filter1d` iterates over the lines of the array, calling the + given function at each line. The arguments of the line are the + input line, and the output line. The input and output lines are 1-D + double arrays. The input line is extended appropriately according + to the filter size and origin. The output line must be modified + in-place with the result. + + Parameters + ---------- + %(input)s + function : {callable, scipy.LowLevelCallable} + Function to apply along given axis. + filter_size : scalar + Length of the filter. + %(axis)s + %(output)s + %(mode_reflect)s + %(cval)s + %(origin)s + %(extra_arguments)s + %(extra_keywords)s + + Returns + ------- + generic_filter1d : ndarray + Filtered array. Has the same shape as `input`. + + Notes + ----- + This function also accepts low-level callback functions with one of + the following signatures and wrapped in `scipy.LowLevelCallable`: + + .. code:: c + + int function(double *input_line, npy_intp input_length, + double *output_line, npy_intp output_length, + void *user_data) + int function(double *input_line, intptr_t input_length, + double *output_line, intptr_t output_length, + void *user_data) + + The calling function iterates over the lines of the input and output + arrays, calling the callback function at each line. The current line + is extended according to the border conditions set by the calling + function, and the result is copied into the array that is passed + through ``input_line``. The length of the input line (after extension) + is passed through ``input_length``. The callback function should apply + the filter and store the result in the array passed through + ``output_line``. The length of the output line is passed through + ``output_length``. ``user_data`` is the data pointer provided + to `scipy.LowLevelCallable` as-is. + + The callback function must return an integer error status that is zero + if something went wrong and one otherwise. If an error occurs, you should + normally set the python error status with an informative message + before returning, otherwise a default error message is set by the + calling function. + + In addition, some other low-level function pointer specifications + are accepted, but these are for backward compatibility only and should + not be used in new code. + + """ + if extra_keywords is None: + extra_keywords = {} + input = np.asarray(input) + if np.iscomplexobj(input): + raise TypeError('Complex type not supported') + output = _ni_support._get_output(output, input) + if filter_size < 1: + raise RuntimeError('invalid filter size') + axis = normalize_axis_index(axis, input.ndim) + if (filter_size // 2 + origin < 0) or (filter_size // 2 + origin >= + filter_size): + raise ValueError('invalid origin') + mode = _ni_support._extend_mode_to_code(mode) + _nd_image.generic_filter1d(input, function, filter_size, axis, output, + mode, cval, origin, extra_arguments, + extra_keywords) + return output + + +@_ni_docstrings.docfiller +def generic_filter(input, function, size=None, footprint=None, + output=None, mode="reflect", cval=0.0, origin=0, + extra_arguments=(), extra_keywords=None, *, axes=None): + """Calculate a multidimensional filter using the given function. + + At each element the provided function is called. The input values + within the filter footprint at that element are passed to the function + as a 1-D array of double values. + + Parameters + ---------- + %(input)s + function : {callable, scipy.LowLevelCallable} + Function to apply at each element. + %(size_foot)s + %(output)s + %(mode_reflect)s + %(cval)s + %(origin_multiple)s + %(extra_arguments)s + %(extra_keywords)s + axes : tuple of int or None, optional + If None, `input` is filtered along all axes. Otherwise, + `input` is filtered along the specified axes. When `axes` is + specified, any tuples used for `size` or `origin` must match the length + of `axes`. The ith entry in any of these tuples corresponds to the ith + entry in `axes`. + + Returns + ------- + generic_filter : ndarray + Filtered array. Has the same shape as `input`. + + Notes + ----- + This function also accepts low-level callback functions with one of + the following signatures and wrapped in `scipy.LowLevelCallable`: + + .. code:: c + + int callback(double *buffer, npy_intp filter_size, + double *return_value, void *user_data) + int callback(double *buffer, intptr_t filter_size, + double *return_value, void *user_data) + + The calling function iterates over the elements of the input and + output arrays, calling the callback function at each element. The + elements within the footprint of the filter at the current element are + passed through the ``buffer`` parameter, and the number of elements + within the footprint through ``filter_size``. The calculated value is + returned in ``return_value``. ``user_data`` is the data pointer provided + to `scipy.LowLevelCallable` as-is. + + The callback function must return an integer error status that is zero + if something went wrong and one otherwise. If an error occurs, you should + normally set the python error status with an informative message + before returning, otherwise a default error message is set by the + calling function. + + In addition, some other low-level function pointer specifications + are accepted, but these are for backward compatibility only and should + not be used in new code. + + Examples + -------- + Import the necessary modules and load the example image used for + filtering. + + >>> import numpy as np + >>> from scipy import datasets + >>> from scipy.ndimage import zoom, generic_filter + >>> import matplotlib.pyplot as plt + >>> ascent = zoom(datasets.ascent(), 0.5) + + Compute a maximum filter with kernel size 5 by passing a simple NumPy + aggregation function as argument to `function`. + + >>> maximum_filter_result = generic_filter(ascent, np.amax, [5, 5]) + + While a maximum filter could also directly be obtained using + `maximum_filter`, `generic_filter` allows generic Python function or + `scipy.LowLevelCallable` to be used as a filter. Here, we compute the + range between maximum and minimum value as an example for a kernel size + of 5. + + >>> def custom_filter(image): + ... return np.amax(image) - np.amin(image) + >>> custom_filter_result = generic_filter(ascent, custom_filter, [5, 5]) + + Plot the original and filtered images. + + >>> fig, axes = plt.subplots(3, 1, figsize=(3, 9)) + >>> plt.gray() # show the filtered result in grayscale + >>> top, middle, bottom = axes + >>> for ax in axes: + ... ax.set_axis_off() # remove coordinate system + >>> top.imshow(ascent) + >>> top.set_title("Original image") + >>> middle.imshow(maximum_filter_result) + >>> middle.set_title("Maximum filter, Kernel: 5x5") + >>> bottom.imshow(custom_filter_result) + >>> bottom.set_title("Custom filter, Kernel: 5x5") + >>> fig.tight_layout() + + """ + if (size is not None) and (footprint is not None): + warnings.warn("ignoring size because footprint is set", + UserWarning, stacklevel=2) + if extra_keywords is None: + extra_keywords = {} + input = np.asarray(input) + if np.iscomplexobj(input): + raise TypeError('Complex type not supported') + axes = _ni_support._check_axes(axes, input.ndim) + num_axes = len(axes) + if footprint is None: + if size is None: + raise RuntimeError("no footprint or filter size provided") + sizes = _ni_support._normalize_sequence(size, num_axes) + footprint = np.ones(sizes, dtype=bool) + else: + footprint = np.asarray(footprint, dtype=bool) + + # expand origins, footprint if num_axes < input.ndim + footprint = _expand_footprint(input.ndim, axes, footprint) + origins = _expand_origin(input.ndim, axes, origin) + + fshape = [ii for ii in footprint.shape if ii > 0] + if len(fshape) != input.ndim: + raise RuntimeError(f"footprint.ndim ({footprint.ndim}) " + f"must match len(axes) ({num_axes})") + for origin, lenf in zip(origins, fshape): + if (lenf // 2 + origin < 0) or (lenf // 2 + origin >= lenf): + raise ValueError('invalid origin') + if not footprint.flags.contiguous: + footprint = footprint.copy() + output = _ni_support._get_output(output, input) + + mode = _ni_support._extend_mode_to_code(mode) + _nd_image.generic_filter(input, function, footprint, output, mode, + cval, origins, extra_arguments, extra_keywords) + return output diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/_fourier.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/_fourier.py new file mode 100644 index 0000000000000000000000000000000000000000..bb5ffa6b9287cb740611aefba5f1f322011518cf --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/_fourier.py @@ -0,0 +1,306 @@ +# Copyright (C) 2003-2005 Peter J. Verveer +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# 2. Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# 3. The name of the author may not be used to endorse or promote +# products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS +# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE +# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import numpy as np +from scipy._lib._util import normalize_axis_index +from . import _ni_support +from . import _nd_image + +__all__ = ['fourier_gaussian', 'fourier_uniform', 'fourier_ellipsoid', + 'fourier_shift'] + + +def _get_output_fourier(output, input): + if output is None: + if input.dtype.type in [np.complex64, np.complex128, np.float32]: + output = np.zeros(input.shape, dtype=input.dtype) + else: + output = np.zeros(input.shape, dtype=np.float64) + elif type(output) is type: + if output not in [np.complex64, np.complex128, + np.float32, np.float64]: + raise RuntimeError("output type not supported") + output = np.zeros(input.shape, dtype=output) + elif output.shape != input.shape: + raise RuntimeError("output shape not correct") + return output + + +def _get_output_fourier_complex(output, input): + if output is None: + if input.dtype.type in [np.complex64, np.complex128]: + output = np.zeros(input.shape, dtype=input.dtype) + else: + output = np.zeros(input.shape, dtype=np.complex128) + elif type(output) is type: + if output not in [np.complex64, np.complex128]: + raise RuntimeError("output type not supported") + output = np.zeros(input.shape, dtype=output) + elif output.shape != input.shape: + raise RuntimeError("output shape not correct") + return output + + +def fourier_gaussian(input, sigma, n=-1, axis=-1, output=None): + """ + Multidimensional Gaussian fourier filter. + + The array is multiplied with the fourier transform of a Gaussian + kernel. + + Parameters + ---------- + input : array_like + The input array. + sigma : float or sequence + The sigma of the Gaussian kernel. If a float, `sigma` is the same for + all axes. If a sequence, `sigma` has to contain one value for each + axis. + n : int, optional + If `n` is negative (default), then the input is assumed to be the + result of a complex fft. + If `n` is larger than or equal to zero, the input is assumed to be the + result of a real fft, and `n` gives the length of the array before + transformation along the real transform direction. + axis : int, optional + The axis of the real transform. + output : ndarray, optional + If given, the result of filtering the input is placed in this array. + + Returns + ------- + fourier_gaussian : ndarray + The filtered input. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import numpy.fft + >>> import matplotlib.pyplot as plt + >>> fig, (ax1, ax2) = plt.subplots(1, 2) + >>> plt.gray() # show the filtered result in grayscale + >>> ascent = datasets.ascent() + >>> input_ = numpy.fft.fft2(ascent) + >>> result = ndimage.fourier_gaussian(input_, sigma=4) + >>> result = numpy.fft.ifft2(result) + >>> ax1.imshow(ascent) + >>> ax2.imshow(result.real) # the imaginary part is an artifact + >>> plt.show() + """ + input = np.asarray(input) + output = _get_output_fourier(output, input) + axis = normalize_axis_index(axis, input.ndim) + sigmas = _ni_support._normalize_sequence(sigma, input.ndim) + sigmas = np.asarray(sigmas, dtype=np.float64) + if not sigmas.flags.contiguous: + sigmas = sigmas.copy() + + _nd_image.fourier_filter(input, sigmas, n, axis, output, 0) + return output + + +def fourier_uniform(input, size, n=-1, axis=-1, output=None): + """ + Multidimensional uniform fourier filter. + + The array is multiplied with the Fourier transform of a box of given + size. + + Parameters + ---------- + input : array_like + The input array. + size : float or sequence + The size of the box used for filtering. + If a float, `size` is the same for all axes. If a sequence, `size` has + to contain one value for each axis. + n : int, optional + If `n` is negative (default), then the input is assumed to be the + result of a complex fft. + If `n` is larger than or equal to zero, the input is assumed to be the + result of a real fft, and `n` gives the length of the array before + transformation along the real transform direction. + axis : int, optional + The axis of the real transform. + output : ndarray, optional + If given, the result of filtering the input is placed in this array. + + Returns + ------- + fourier_uniform : ndarray + The filtered input. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import numpy.fft + >>> import matplotlib.pyplot as plt + >>> fig, (ax1, ax2) = plt.subplots(1, 2) + >>> plt.gray() # show the filtered result in grayscale + >>> ascent = datasets.ascent() + >>> input_ = numpy.fft.fft2(ascent) + >>> result = ndimage.fourier_uniform(input_, size=20) + >>> result = numpy.fft.ifft2(result) + >>> ax1.imshow(ascent) + >>> ax2.imshow(result.real) # the imaginary part is an artifact + >>> plt.show() + """ + input = np.asarray(input) + output = _get_output_fourier(output, input) + axis = normalize_axis_index(axis, input.ndim) + sizes = _ni_support._normalize_sequence(size, input.ndim) + sizes = np.asarray(sizes, dtype=np.float64) + if not sizes.flags.contiguous: + sizes = sizes.copy() + _nd_image.fourier_filter(input, sizes, n, axis, output, 1) + return output + + +def fourier_ellipsoid(input, size, n=-1, axis=-1, output=None): + """ + Multidimensional ellipsoid Fourier filter. + + The array is multiplied with the fourier transform of an ellipsoid of + given sizes. + + Parameters + ---------- + input : array_like + The input array. + size : float or sequence + The size of the box used for filtering. + If a float, `size` is the same for all axes. If a sequence, `size` has + to contain one value for each axis. + n : int, optional + If `n` is negative (default), then the input is assumed to be the + result of a complex fft. + If `n` is larger than or equal to zero, the input is assumed to be the + result of a real fft, and `n` gives the length of the array before + transformation along the real transform direction. + axis : int, optional + The axis of the real transform. + output : ndarray, optional + If given, the result of filtering the input is placed in this array. + + Returns + ------- + fourier_ellipsoid : ndarray + The filtered input. + + Notes + ----- + This function is implemented for arrays of rank 1, 2, or 3. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import numpy.fft + >>> import matplotlib.pyplot as plt + >>> fig, (ax1, ax2) = plt.subplots(1, 2) + >>> plt.gray() # show the filtered result in grayscale + >>> ascent = datasets.ascent() + >>> input_ = numpy.fft.fft2(ascent) + >>> result = ndimage.fourier_ellipsoid(input_, size=20) + >>> result = numpy.fft.ifft2(result) + >>> ax1.imshow(ascent) + >>> ax2.imshow(result.real) # the imaginary part is an artifact + >>> plt.show() + """ + input = np.asarray(input) + if input.ndim > 3: + raise NotImplementedError("Only 1d, 2d and 3d inputs are supported") + output = _get_output_fourier(output, input) + if output.size == 0: + # The C code has a bug that can result in a segfault with arrays + # that have size 0 (gh-17270), so check here. + return output + axis = normalize_axis_index(axis, input.ndim) + sizes = _ni_support._normalize_sequence(size, input.ndim) + sizes = np.asarray(sizes, dtype=np.float64) + if not sizes.flags.contiguous: + sizes = sizes.copy() + _nd_image.fourier_filter(input, sizes, n, axis, output, 2) + return output + + +def fourier_shift(input, shift, n=-1, axis=-1, output=None): + """ + Multidimensional Fourier shift filter. + + The array is multiplied with the Fourier transform of a shift operation. + + Parameters + ---------- + input : array_like + The input array. + shift : float or sequence + The size of the box used for filtering. + If a float, `shift` is the same for all axes. If a sequence, `shift` + has to contain one value for each axis. + n : int, optional + If `n` is negative (default), then the input is assumed to be the + result of a complex fft. + If `n` is larger than or equal to zero, the input is assumed to be the + result of a real fft, and `n` gives the length of the array before + transformation along the real transform direction. + axis : int, optional + The axis of the real transform. + output : ndarray, optional + If given, the result of shifting the input is placed in this array. + + Returns + ------- + fourier_shift : ndarray + The shifted input. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import matplotlib.pyplot as plt + >>> import numpy.fft + >>> fig, (ax1, ax2) = plt.subplots(1, 2) + >>> plt.gray() # show the filtered result in grayscale + >>> ascent = datasets.ascent() + >>> input_ = numpy.fft.fft2(ascent) + >>> result = ndimage.fourier_shift(input_, shift=200) + >>> result = numpy.fft.ifft2(result) + >>> ax1.imshow(ascent) + >>> ax2.imshow(result.real) # the imaginary part is an artifact + >>> plt.show() + """ + input = np.asarray(input) + output = _get_output_fourier_complex(output, input) + axis = normalize_axis_index(axis, input.ndim) + shifts = _ni_support._normalize_sequence(shift, input.ndim) + shifts = np.asarray(shifts, dtype=np.float64) + if not shifts.flags.contiguous: + shifts = shifts.copy() + _nd_image.fourier_shift(input, shifts, n, axis, output) + return output diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/_interpolation.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/_interpolation.py new file mode 100644 index 0000000000000000000000000000000000000000..4e4ea94184871fe87f848532b21e2def29bd406b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/_interpolation.py @@ -0,0 +1,1003 @@ +# Copyright (C) 2003-2005 Peter J. Verveer +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# 2. Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# 3. The name of the author may not be used to endorse or promote +# products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS +# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE +# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import itertools +import warnings + +import numpy as np +from scipy._lib._util import normalize_axis_index + +from scipy import special +from . import _ni_support +from . import _nd_image +from ._ni_docstrings import docfiller + + +__all__ = ['spline_filter1d', 'spline_filter', 'geometric_transform', + 'map_coordinates', 'affine_transform', 'shift', 'zoom', 'rotate'] + + +@docfiller +def spline_filter1d(input, order=3, axis=-1, output=np.float64, + mode='mirror'): + """ + Calculate a 1-D spline filter along the given axis. + + The lines of the array along the given axis are filtered by a + spline filter. The order of the spline must be >= 2 and <= 5. + + Parameters + ---------- + %(input)s + order : int, optional + The order of the spline, default is 3. + axis : int, optional + The axis along which the spline filter is applied. Default is the last + axis. + output : ndarray or dtype, optional + The array in which to place the output, or the dtype of the returned + array. Default is ``numpy.float64``. + %(mode_interp_mirror)s + + Returns + ------- + spline_filter1d : ndarray + The filtered input. + + See Also + -------- + spline_filter : Multidimensional spline filter. + + Notes + ----- + All of the interpolation functions in `ndimage` do spline interpolation of + the input image. If using B-splines of `order > 1`, the input image + values have to be converted to B-spline coefficients first, which is + done by applying this 1-D filter sequentially along all + axes of the input. All functions that require B-spline coefficients + will automatically filter their inputs, a behavior controllable with + the `prefilter` keyword argument. For functions that accept a `mode` + parameter, the result will only be correct if it matches the `mode` + used when filtering. + + For complex-valued `input`, this function processes the real and imaginary + components independently. + + .. versionadded:: 1.6.0 + Complex-valued support added. + + Examples + -------- + We can filter an image using 1-D spline along the given axis: + + >>> from scipy.ndimage import spline_filter1d + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> orig_img = np.eye(20) # create an image + >>> orig_img[10, :] = 1.0 + >>> sp_filter_axis_0 = spline_filter1d(orig_img, axis=0) + >>> sp_filter_axis_1 = spline_filter1d(orig_img, axis=1) + >>> f, ax = plt.subplots(1, 3, sharex=True) + >>> for ind, data in enumerate([[orig_img, "original image"], + ... [sp_filter_axis_0, "spline filter (axis=0)"], + ... [sp_filter_axis_1, "spline filter (axis=1)"]]): + ... ax[ind].imshow(data[0], cmap='gray_r') + ... ax[ind].set_title(data[1]) + >>> plt.tight_layout() + >>> plt.show() + + """ + if order < 0 or order > 5: + raise RuntimeError('spline order not supported') + input = np.asarray(input) + complex_output = np.iscomplexobj(input) + output = _ni_support._get_output(output, input, + complex_output=complex_output) + if complex_output: + spline_filter1d(input.real, order, axis, output.real, mode) + spline_filter1d(input.imag, order, axis, output.imag, mode) + return output + if order in [0, 1]: + output[...] = np.array(input) + else: + mode = _ni_support._extend_mode_to_code(mode) + axis = normalize_axis_index(axis, input.ndim) + _nd_image.spline_filter1d(input, order, axis, output, mode) + return output + +@docfiller +def spline_filter(input, order=3, output=np.float64, mode='mirror'): + """ + Multidimensional spline filter. + + Parameters + ---------- + %(input)s + order : int, optional + The order of the spline, default is 3. + output : ndarray or dtype, optional + The array in which to place the output, or the dtype of the returned + array. Default is ``numpy.float64``. + %(mode_interp_mirror)s + + Returns + ------- + spline_filter : ndarray + Filtered array. Has the same shape as `input`. + + See Also + -------- + spline_filter1d : Calculate a 1-D spline filter along the given axis. + + Notes + ----- + The multidimensional filter is implemented as a sequence of + 1-D spline filters. The intermediate arrays are stored + in the same data type as the output. Therefore, for output types + with a limited precision, the results may be imprecise because + intermediate results may be stored with insufficient precision. + + For complex-valued `input`, this function processes the real and imaginary + components independently. + + .. versionadded:: 1.6.0 + Complex-valued support added. + + Examples + -------- + We can filter an image using multidimensional splines: + + >>> from scipy.ndimage import spline_filter + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> orig_img = np.eye(20) # create an image + >>> orig_img[10, :] = 1.0 + >>> sp_filter = spline_filter(orig_img, order=3) + >>> f, ax = plt.subplots(1, 2, sharex=True) + >>> for ind, data in enumerate([[orig_img, "original image"], + ... [sp_filter, "spline filter"]]): + ... ax[ind].imshow(data[0], cmap='gray_r') + ... ax[ind].set_title(data[1]) + >>> plt.tight_layout() + >>> plt.show() + + """ + if order < 2 or order > 5: + raise RuntimeError('spline order not supported') + input = np.asarray(input) + complex_output = np.iscomplexobj(input) + output = _ni_support._get_output(output, input, + complex_output=complex_output) + if complex_output: + spline_filter(input.real, order, output.real, mode) + spline_filter(input.imag, order, output.imag, mode) + return output + if order not in [0, 1] and input.ndim > 0: + for axis in range(input.ndim): + spline_filter1d(input, order, axis, output=output, mode=mode) + input = output + else: + output[...] = input[...] + return output + + +def _prepad_for_spline_filter(input, mode, cval): + if mode in ['nearest', 'grid-constant']: + npad = 12 + if mode == 'grid-constant': + padded = np.pad(input, npad, mode='constant', + constant_values=cval) + elif mode == 'nearest': + padded = np.pad(input, npad, mode='edge') + else: + # other modes have exact boundary conditions implemented so + # no prepadding is needed + npad = 0 + padded = input + return padded, npad + + +@docfiller +def geometric_transform(input, mapping, output_shape=None, + output=None, order=3, + mode='constant', cval=0.0, prefilter=True, + extra_arguments=(), extra_keywords=None): + """ + Apply an arbitrary geometric transform. + + The given mapping function is used to find, for each point in the + output, the corresponding coordinates in the input. The value of the + input at those coordinates is determined by spline interpolation of + the requested order. + + Parameters + ---------- + %(input)s + mapping : {callable, scipy.LowLevelCallable} + A callable object that accepts a tuple of length equal to the output + array rank, and returns the corresponding input coordinates as a tuple + of length equal to the input array rank. + output_shape : tuple of ints, optional + Shape tuple. + %(output)s + order : int, optional + The order of the spline interpolation, default is 3. + The order has to be in the range 0-5. + %(mode_interp_constant)s + %(cval)s + %(prefilter)s + extra_arguments : tuple, optional + Extra arguments passed to `mapping`. + extra_keywords : dict, optional + Extra keywords passed to `mapping`. + + Returns + ------- + output : ndarray + The filtered input. + + See Also + -------- + map_coordinates, affine_transform, spline_filter1d + + + Notes + ----- + This function also accepts low-level callback functions with one + the following signatures and wrapped in `scipy.LowLevelCallable`: + + .. code:: c + + int mapping(npy_intp *output_coordinates, double *input_coordinates, + int output_rank, int input_rank, void *user_data) + int mapping(intptr_t *output_coordinates, double *input_coordinates, + int output_rank, int input_rank, void *user_data) + + The calling function iterates over the elements of the output array, + calling the callback function at each element. The coordinates of the + current output element are passed through ``output_coordinates``. The + callback function must return the coordinates at which the input must + be interpolated in ``input_coordinates``. The rank of the input and + output arrays are given by ``input_rank`` and ``output_rank`` + respectively. ``user_data`` is the data pointer provided + to `scipy.LowLevelCallable` as-is. + + The callback function must return an integer error status that is zero + if something went wrong and one otherwise. If an error occurs, you should + normally set the Python error status with an informative message + before returning, otherwise a default error message is set by the + calling function. + + In addition, some other low-level function pointer specifications + are accepted, but these are for backward compatibility only and should + not be used in new code. + + For complex-valued `input`, this function transforms the real and imaginary + components independently. + + .. versionadded:: 1.6.0 + Complex-valued support added. + + Examples + -------- + >>> import numpy as np + >>> from scipy.ndimage import geometric_transform + >>> a = np.arange(12.).reshape((4, 3)) + >>> def shift_func(output_coords): + ... return (output_coords[0] - 0.5, output_coords[1] - 0.5) + ... + >>> geometric_transform(a, shift_func) + array([[ 0. , 0. , 0. ], + [ 0. , 1.362, 2.738], + [ 0. , 4.812, 6.187], + [ 0. , 8.263, 9.637]]) + + >>> b = [1, 2, 3, 4, 5] + >>> def shift_func(output_coords): + ... return (output_coords[0] - 3,) + ... + >>> geometric_transform(b, shift_func, mode='constant') + array([0, 0, 0, 1, 2]) + >>> geometric_transform(b, shift_func, mode='nearest') + array([1, 1, 1, 1, 2]) + >>> geometric_transform(b, shift_func, mode='reflect') + array([3, 2, 1, 1, 2]) + >>> geometric_transform(b, shift_func, mode='wrap') + array([2, 3, 4, 1, 2]) + + """ + if extra_keywords is None: + extra_keywords = {} + if order < 0 or order > 5: + raise RuntimeError('spline order not supported') + input = np.asarray(input) + if output_shape is None: + output_shape = input.shape + if input.ndim < 1 or len(output_shape) < 1: + raise RuntimeError('input and output rank must be > 0') + complex_output = np.iscomplexobj(input) + output = _ni_support._get_output(output, input, shape=output_shape, + complex_output=complex_output) + if complex_output: + kwargs = dict(order=order, mode=mode, prefilter=prefilter, + output_shape=output_shape, + extra_arguments=extra_arguments, + extra_keywords=extra_keywords) + geometric_transform(input.real, mapping, output=output.real, + cval=np.real(cval), **kwargs) + geometric_transform(input.imag, mapping, output=output.imag, + cval=np.imag(cval), **kwargs) + return output + + if prefilter and order > 1: + padded, npad = _prepad_for_spline_filter(input, mode, cval) + filtered = spline_filter(padded, order, output=np.float64, + mode=mode) + else: + npad = 0 + filtered = input + mode = _ni_support._extend_mode_to_code(mode) + _nd_image.geometric_transform(filtered, mapping, None, None, None, output, + order, mode, cval, npad, extra_arguments, + extra_keywords) + return output + + +@docfiller +def map_coordinates(input, coordinates, output=None, order=3, + mode='constant', cval=0.0, prefilter=True): + """ + Map the input array to new coordinates by interpolation. + + The array of coordinates is used to find, for each point in the output, + the corresponding coordinates in the input. The value of the input at + those coordinates is determined by spline interpolation of the + requested order. + + The shape of the output is derived from that of the coordinate + array by dropping the first axis. The values of the array along + the first axis are the coordinates in the input array at which the + output value is found. + + Parameters + ---------- + %(input)s + coordinates : array_like + The coordinates at which `input` is evaluated. + %(output)s + order : int, optional + The order of the spline interpolation, default is 3. + The order has to be in the range 0-5. + %(mode_interp_constant)s + %(cval)s + %(prefilter)s + + Returns + ------- + map_coordinates : ndarray + The result of transforming the input. The shape of the output is + derived from that of `coordinates` by dropping the first axis. + + See Also + -------- + spline_filter, geometric_transform, scipy.interpolate + + Notes + ----- + For complex-valued `input`, this function maps the real and imaginary + components independently. + + .. versionadded:: 1.6.0 + Complex-valued support added. + + Examples + -------- + >>> from scipy import ndimage + >>> import numpy as np + >>> a = np.arange(12.).reshape((4, 3)) + >>> a + array([[ 0., 1., 2.], + [ 3., 4., 5.], + [ 6., 7., 8.], + [ 9., 10., 11.]]) + >>> ndimage.map_coordinates(a, [[0.5, 2], [0.5, 1]], order=1) + array([ 2., 7.]) + + Above, the interpolated value of a[0.5, 0.5] gives output[0], while + a[2, 1] is output[1]. + + >>> inds = np.array([[0.5, 2], [0.5, 4]]) + >>> ndimage.map_coordinates(a, inds, order=1, cval=-33.3) + array([ 2. , -33.3]) + >>> ndimage.map_coordinates(a, inds, order=1, mode='nearest') + array([ 2., 8.]) + >>> ndimage.map_coordinates(a, inds, order=1, cval=0, output=bool) + array([ True, False], dtype=bool) + + """ + if order < 0 or order > 5: + raise RuntimeError('spline order not supported') + input = np.asarray(input) + coordinates = np.asarray(coordinates) + if np.iscomplexobj(coordinates): + raise TypeError('Complex type not supported') + output_shape = coordinates.shape[1:] + if input.ndim < 1 or len(output_shape) < 1: + raise RuntimeError('input and output rank must be > 0') + if coordinates.shape[0] != input.ndim: + raise RuntimeError('invalid shape for coordinate array') + complex_output = np.iscomplexobj(input) + output = _ni_support._get_output(output, input, shape=output_shape, + complex_output=complex_output) + if complex_output: + kwargs = dict(order=order, mode=mode, prefilter=prefilter) + map_coordinates(input.real, coordinates, output=output.real, + cval=np.real(cval), **kwargs) + map_coordinates(input.imag, coordinates, output=output.imag, + cval=np.imag(cval), **kwargs) + return output + if prefilter and order > 1: + padded, npad = _prepad_for_spline_filter(input, mode, cval) + filtered = spline_filter(padded, order, output=np.float64, mode=mode) + else: + npad = 0 + filtered = input + mode = _ni_support._extend_mode_to_code(mode) + _nd_image.geometric_transform(filtered, None, coordinates, None, None, + output, order, mode, cval, npad, None, None) + return output + + +@docfiller +def affine_transform(input, matrix, offset=0.0, output_shape=None, + output=None, order=3, + mode='constant', cval=0.0, prefilter=True): + """ + Apply an affine transformation. + + Given an output image pixel index vector ``o``, the pixel value + is determined from the input image at position + ``np.dot(matrix, o) + offset``. + + This does 'pull' (or 'backward') resampling, transforming the output space + to the input to locate data. Affine transformations are often described in + the 'push' (or 'forward') direction, transforming input to output. If you + have a matrix for the 'push' transformation, use its inverse + (:func:`numpy.linalg.inv`) in this function. + + Parameters + ---------- + %(input)s + matrix : ndarray + The inverse coordinate transformation matrix, mapping output + coordinates to input coordinates. If ``ndim`` is the number of + dimensions of ``input``, the given matrix must have one of the + following shapes: + + - ``(ndim, ndim)``: the linear transformation matrix for each + output coordinate. + - ``(ndim,)``: assume that the 2-D transformation matrix is + diagonal, with the diagonal specified by the given value. A more + efficient algorithm is then used that exploits the separability + of the problem. + - ``(ndim + 1, ndim + 1)``: assume that the transformation is + specified using homogeneous coordinates [1]_. In this case, any + value passed to ``offset`` is ignored. + - ``(ndim, ndim + 1)``: as above, but the bottom row of a + homogeneous transformation matrix is always ``[0, 0, ..., 1]``, + and may be omitted. + + offset : float or sequence, optional + The offset into the array where the transform is applied. If a float, + `offset` is the same for each axis. If a sequence, `offset` should + contain one value for each axis. + output_shape : tuple of ints, optional + Shape tuple. + %(output)s + order : int, optional + The order of the spline interpolation, default is 3. + The order has to be in the range 0-5. + %(mode_interp_constant)s + %(cval)s + %(prefilter)s + + Returns + ------- + affine_transform : ndarray + The transformed input. + + Notes + ----- + The given matrix and offset are used to find for each point in the + output the corresponding coordinates in the input by an affine + transformation. The value of the input at those coordinates is + determined by spline interpolation of the requested order. Points + outside the boundaries of the input are filled according to the given + mode. + + .. versionchanged:: 0.18.0 + Previously, the exact interpretation of the affine transformation + depended on whether the matrix was supplied as a 1-D or a + 2-D array. If a 1-D array was supplied + to the matrix parameter, the output pixel value at index ``o`` + was determined from the input image at position + ``matrix * (o + offset)``. + + For complex-valued `input`, this function transforms the real and imaginary + components independently. + + .. versionadded:: 1.6.0 + Complex-valued support added. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Homogeneous_coordinates + """ + if order < 0 or order > 5: + raise RuntimeError('spline order not supported') + input = np.asarray(input) + if output_shape is None: + if isinstance(output, np.ndarray): + output_shape = output.shape + else: + output_shape = input.shape + if input.ndim < 1 or len(output_shape) < 1: + raise RuntimeError('input and output rank must be > 0') + complex_output = np.iscomplexobj(input) + output = _ni_support._get_output(output, input, shape=output_shape, + complex_output=complex_output) + if complex_output: + kwargs = dict(offset=offset, output_shape=output_shape, order=order, + mode=mode, prefilter=prefilter) + affine_transform(input.real, matrix, output=output.real, + cval=np.real(cval), **kwargs) + affine_transform(input.imag, matrix, output=output.imag, + cval=np.imag(cval), **kwargs) + return output + if prefilter and order > 1: + padded, npad = _prepad_for_spline_filter(input, mode, cval) + filtered = spline_filter(padded, order, output=np.float64, mode=mode) + else: + npad = 0 + filtered = input + mode = _ni_support._extend_mode_to_code(mode) + matrix = np.asarray(matrix, dtype=np.float64) + if matrix.ndim not in [1, 2] or matrix.shape[0] < 1: + raise RuntimeError('no proper affine matrix provided') + if (matrix.ndim == 2 and matrix.shape[1] == input.ndim + 1 and + (matrix.shape[0] in [input.ndim, input.ndim + 1])): + if matrix.shape[0] == input.ndim + 1: + exptd = [0] * input.ndim + [1] + if not np.all(matrix[input.ndim] == exptd): + msg = (f'Expected homogeneous transformation matrix with ' + f'shape {matrix.shape} for image shape {input.shape}, ' + f'but bottom row was not equal to {exptd}') + raise ValueError(msg) + # assume input is homogeneous coordinate transformation matrix + offset = matrix[:input.ndim, input.ndim] + matrix = matrix[:input.ndim, :input.ndim] + if matrix.shape[0] != input.ndim: + raise RuntimeError('affine matrix has wrong number of rows') + if matrix.ndim == 2 and matrix.shape[1] != output.ndim: + raise RuntimeError('affine matrix has wrong number of columns') + if not matrix.flags.contiguous: + matrix = matrix.copy() + offset = _ni_support._normalize_sequence(offset, input.ndim) + offset = np.asarray(offset, dtype=np.float64) + if offset.ndim != 1 or offset.shape[0] < 1: + raise RuntimeError('no proper offset provided') + if not offset.flags.contiguous: + offset = offset.copy() + if matrix.ndim == 1: + warnings.warn( + "The behavior of affine_transform with a 1-D " + "array supplied for the matrix parameter has changed in " + "SciPy 0.18.0.", + stacklevel=2 + ) + _nd_image.zoom_shift(filtered, matrix, offset/matrix, output, order, + mode, cval, npad, False) + else: + _nd_image.geometric_transform(filtered, None, None, matrix, offset, + output, order, mode, cval, npad, None, + None) + return output + + +@docfiller +def shift(input, shift, output=None, order=3, mode='constant', cval=0.0, + prefilter=True): + """ + Shift an array. + + The array is shifted using spline interpolation of the requested order. + Points outside the boundaries of the input are filled according to the + given mode. + + Parameters + ---------- + %(input)s + shift : float or sequence + The shift along the axes. If a float, `shift` is the same for each + axis. If a sequence, `shift` should contain one value for each axis. + %(output)s + order : int, optional + The order of the spline interpolation, default is 3. + The order has to be in the range 0-5. + %(mode_interp_constant)s + %(cval)s + %(prefilter)s + + Returns + ------- + shift : ndarray + The shifted input. + + See Also + -------- + affine_transform : Affine transformations + + Notes + ----- + For complex-valued `input`, this function shifts the real and imaginary + components independently. + + .. versionadded:: 1.6.0 + Complex-valued support added. + + Examples + -------- + Import the necessary modules and an exemplary image. + + >>> from scipy.ndimage import shift + >>> import matplotlib.pyplot as plt + >>> from scipy import datasets + >>> image = datasets.ascent() + + Shift the image vertically by 20 pixels. + + >>> image_shifted_vertically = shift(image, (20, 0)) + + Shift the image vertically by -200 pixels and horizontally by 100 pixels. + + >>> image_shifted_both_directions = shift(image, (-200, 100)) + + Plot the original and the shifted images. + + >>> fig, axes = plt.subplots(3, 1, figsize=(4, 12)) + >>> plt.gray() # show the filtered result in grayscale + >>> top, middle, bottom = axes + >>> for ax in axes: + ... ax.set_axis_off() # remove coordinate system + >>> top.imshow(image) + >>> top.set_title("Original image") + >>> middle.imshow(image_shifted_vertically) + >>> middle.set_title("Vertically shifted image") + >>> bottom.imshow(image_shifted_both_directions) + >>> bottom.set_title("Image shifted in both directions") + >>> fig.tight_layout() + """ + if order < 0 or order > 5: + raise RuntimeError('spline order not supported') + input = np.asarray(input) + if input.ndim < 1: + raise RuntimeError('input and output rank must be > 0') + complex_output = np.iscomplexobj(input) + output = _ni_support._get_output(output, input, complex_output=complex_output) + if complex_output: + # import under different name to avoid confusion with shift parameter + from scipy.ndimage._interpolation import shift as _shift + + kwargs = dict(order=order, mode=mode, prefilter=prefilter) + _shift(input.real, shift, output=output.real, cval=np.real(cval), **kwargs) + _shift(input.imag, shift, output=output.imag, cval=np.imag(cval), **kwargs) + return output + if prefilter and order > 1: + padded, npad = _prepad_for_spline_filter(input, mode, cval) + filtered = spline_filter(padded, order, output=np.float64, mode=mode) + else: + npad = 0 + filtered = input + mode = _ni_support._extend_mode_to_code(mode) + shift = _ni_support._normalize_sequence(shift, input.ndim) + shift = [-ii for ii in shift] + shift = np.asarray(shift, dtype=np.float64) + if not shift.flags.contiguous: + shift = shift.copy() + _nd_image.zoom_shift(filtered, None, shift, output, order, mode, cval, + npad, False) + return output + + +@docfiller +def zoom(input, zoom, output=None, order=3, mode='constant', cval=0.0, + prefilter=True, *, grid_mode=False): + """ + Zoom an array. + + The array is zoomed using spline interpolation of the requested order. + + Parameters + ---------- + %(input)s + zoom : float or sequence + The zoom factor along the axes. If a float, `zoom` is the same for each + axis. If a sequence, `zoom` should contain one value for each axis. + %(output)s + order : int, optional + The order of the spline interpolation, default is 3. + The order has to be in the range 0-5. + %(mode_interp_constant)s + %(cval)s + %(prefilter)s + grid_mode : bool, optional + If False, the distance from the pixel centers is zoomed. Otherwise, the + distance including the full pixel extent is used. For example, a 1d + signal of length 5 is considered to have length 4 when `grid_mode` is + False, but length 5 when `grid_mode` is True. See the following + visual illustration: + + .. code-block:: text + + | pixel 1 | pixel 2 | pixel 3 | pixel 4 | pixel 5 | + |<-------------------------------------->| + vs. + |<----------------------------------------------->| + + The starting point of the arrow in the diagram above corresponds to + coordinate location 0 in each mode. + + Returns + ------- + zoom : ndarray + The zoomed input. + + Notes + ----- + For complex-valued `input`, this function zooms the real and imaginary + components independently. + + .. versionadded:: 1.6.0 + Complex-valued support added. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import matplotlib.pyplot as plt + + >>> fig = plt.figure() + >>> ax1 = fig.add_subplot(121) # left side + >>> ax2 = fig.add_subplot(122) # right side + >>> ascent = datasets.ascent() + >>> result = ndimage.zoom(ascent, 3.0) + >>> ax1.imshow(ascent, vmin=0, vmax=255) + >>> ax2.imshow(result, vmin=0, vmax=255) + >>> plt.show() + + >>> print(ascent.shape) + (512, 512) + + >>> print(result.shape) + (1536, 1536) + """ + if order < 0 or order > 5: + raise RuntimeError('spline order not supported') + input = np.asarray(input) + if input.ndim < 1: + raise RuntimeError('input and output rank must be > 0') + zoom = _ni_support._normalize_sequence(zoom, input.ndim) + output_shape = tuple( + [int(round(ii * jj)) for ii, jj in zip(input.shape, zoom)]) + complex_output = np.iscomplexobj(input) + output = _ni_support._get_output(output, input, shape=output_shape, + complex_output=complex_output) + if complex_output: + # import under different name to avoid confusion with zoom parameter + from scipy.ndimage._interpolation import zoom as _zoom + + kwargs = dict(order=order, mode=mode, prefilter=prefilter) + _zoom(input.real, zoom, output=output.real, cval=np.real(cval), **kwargs) + _zoom(input.imag, zoom, output=output.imag, cval=np.imag(cval), **kwargs) + return output + if prefilter and order > 1: + padded, npad = _prepad_for_spline_filter(input, mode, cval) + filtered = spline_filter(padded, order, output=np.float64, mode=mode) + else: + npad = 0 + filtered = input + if grid_mode: + # warn about modes that may have surprising behavior + suggest_mode = None + if mode == 'constant': + suggest_mode = 'grid-constant' + elif mode == 'wrap': + suggest_mode = 'grid-wrap' + if suggest_mode is not None: + warnings.warn( + (f"It is recommended to use mode = {suggest_mode} instead of {mode} " + f"when grid_mode is True."), + stacklevel=2 + ) + mode = _ni_support._extend_mode_to_code(mode) + + zoom_div = np.array(output_shape) + zoom_nominator = np.array(input.shape) + if not grid_mode: + zoom_div -= 1 + zoom_nominator -= 1 + + # Zooming to infinite values is unpredictable, so just choose + # zoom factor 1 instead + zoom = np.divide(zoom_nominator, zoom_div, + out=np.ones_like(input.shape, dtype=np.float64), + where=zoom_div != 0) + zoom = np.ascontiguousarray(zoom) + _nd_image.zoom_shift(filtered, zoom, None, output, order, mode, cval, npad, + grid_mode) + return output + + +@docfiller +def rotate(input, angle, axes=(1, 0), reshape=True, output=None, order=3, + mode='constant', cval=0.0, prefilter=True): + """ + Rotate an array. + + The array is rotated in the plane defined by the two axes given by the + `axes` parameter using spline interpolation of the requested order. + + Parameters + ---------- + %(input)s + angle : float + The rotation angle in degrees. + axes : tuple of 2 ints, optional + The two axes that define the plane of rotation. Default is the first + two axes. + reshape : bool, optional + If `reshape` is true, the output shape is adapted so that the input + array is contained completely in the output. Default is True. + %(output)s + order : int, optional + The order of the spline interpolation, default is 3. + The order has to be in the range 0-5. + %(mode_interp_constant)s + %(cval)s + %(prefilter)s + + Returns + ------- + rotate : ndarray + The rotated input. + + Notes + ----- + For complex-valued `input`, this function rotates the real and imaginary + components independently. + + .. versionadded:: 1.6.0 + Complex-valued support added. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure(figsize=(10, 3)) + >>> ax1, ax2, ax3 = fig.subplots(1, 3) + >>> img = datasets.ascent() + >>> img_45 = ndimage.rotate(img, 45, reshape=False) + >>> full_img_45 = ndimage.rotate(img, 45, reshape=True) + >>> ax1.imshow(img, cmap='gray') + >>> ax1.set_axis_off() + >>> ax2.imshow(img_45, cmap='gray') + >>> ax2.set_axis_off() + >>> ax3.imshow(full_img_45, cmap='gray') + >>> ax3.set_axis_off() + >>> fig.set_layout_engine('tight') + >>> plt.show() + >>> print(img.shape) + (512, 512) + >>> print(img_45.shape) + (512, 512) + >>> print(full_img_45.shape) + (724, 724) + + """ + input_arr = np.asarray(input) + ndim = input_arr.ndim + + if ndim < 2: + raise ValueError('input array should be at least 2D') + + axes = list(axes) + + if len(axes) != 2: + raise ValueError('axes should contain exactly two values') + + if not all([float(ax).is_integer() for ax in axes]): + raise ValueError('axes should contain only integer values') + + if axes[0] < 0: + axes[0] += ndim + if axes[1] < 0: + axes[1] += ndim + if axes[0] < 0 or axes[1] < 0 or axes[0] >= ndim or axes[1] >= ndim: + raise ValueError('invalid rotation plane specified') + + axes.sort() + + c, s = special.cosdg(angle), special.sindg(angle) + + rot_matrix = np.array([[c, s], + [-s, c]]) + + img_shape = np.asarray(input_arr.shape) + in_plane_shape = img_shape[axes] + if reshape: + # Compute transformed input bounds + iy, ix = in_plane_shape + out_bounds = rot_matrix @ [[0, 0, iy, iy], + [0, ix, 0, ix]] + # Compute the shape of the transformed input plane + out_plane_shape = (np.ptp(out_bounds, axis=1) + 0.5).astype(int) + else: + out_plane_shape = img_shape[axes] + + out_center = rot_matrix @ ((out_plane_shape - 1) / 2) + in_center = (in_plane_shape - 1) / 2 + offset = in_center - out_center + + output_shape = img_shape + output_shape[axes] = out_plane_shape + output_shape = tuple(output_shape) + + complex_output = np.iscomplexobj(input_arr) + output = _ni_support._get_output(output, input_arr, shape=output_shape, + complex_output=complex_output) + + if ndim <= 2: + affine_transform(input_arr, rot_matrix, offset, output_shape, output, + order, mode, cval, prefilter) + else: + # If ndim > 2, the rotation is applied over all the planes + # parallel to axes + planes_coord = itertools.product( + *[[slice(None)] if ax in axes else range(img_shape[ax]) + for ax in range(ndim)]) + + out_plane_shape = tuple(out_plane_shape) + + for coordinates in planes_coord: + ia = input_arr[coordinates] + oa = output[coordinates] + affine_transform(ia, rot_matrix, offset, out_plane_shape, + oa, order, mode, cval, prefilter) + + return output diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/_measurements.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/_measurements.py new file mode 100644 index 0000000000000000000000000000000000000000..67ec12870ccf1dfe52624da05787b197542a0253 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/_measurements.py @@ -0,0 +1,1687 @@ +# Copyright (C) 2003-2005 Peter J. Verveer +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# 2. Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# 3. The name of the author may not be used to endorse or promote +# products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS +# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE +# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import numpy as np +from . import _ni_support +from . import _ni_label +from . import _nd_image +from . import _morphology + +__all__ = ['label', 'find_objects', 'labeled_comprehension', 'sum', 'mean', + 'variance', 'standard_deviation', 'minimum', 'maximum', 'median', + 'minimum_position', 'maximum_position', 'extrema', 'center_of_mass', + 'histogram', 'watershed_ift', 'sum_labels', 'value_indices'] + + +def label(input, structure=None, output=None): + """ + Label features in an array. + + Parameters + ---------- + input : array_like + An array-like object to be labeled. Any non-zero values in `input` are + counted as features and zero values are considered the background. + structure : array_like, optional + A structuring element that defines feature connections. + `structure` must be centrosymmetric + (see Notes). + If no structuring element is provided, + one is automatically generated with a squared connectivity equal to + one. That is, for a 2-D `input` array, the default structuring element + is:: + + [[0,1,0], + [1,1,1], + [0,1,0]] + + output : (None, data-type, array_like), optional + If `output` is a data type, it specifies the type of the resulting + labeled feature array. + If `output` is an array-like object, then `output` will be updated + with the labeled features from this function. This function can + operate in-place, by passing output=input. + Note that the output must be able to store the largest label, or this + function will raise an Exception. + + Returns + ------- + label : ndarray or int + An integer ndarray where each unique feature in `input` has a unique + label in the returned array. + num_features : int + How many objects were found. + + If `output` is None, this function returns a tuple of + (`labeled_array`, `num_features`). + + If `output` is a ndarray, then it will be updated with values in + `labeled_array` and only `num_features` will be returned by this + function. + + See Also + -------- + find_objects : generate a list of slices for the labeled features (or + objects); useful for finding features' position or + dimensions + + Notes + ----- + A centrosymmetric matrix is a matrix that is symmetric about the center. + See [1]_ for more information. + + The `structure` matrix must be centrosymmetric to ensure + two-way connections. + For instance, if the `structure` matrix is not centrosymmetric + and is defined as:: + + [[0,1,0], + [1,1,0], + [0,0,0]] + + and the `input` is:: + + [[1,2], + [0,3]] + + then the structure matrix would indicate the + entry 2 in the input is connected to 1, + but 1 is not connected to 2. + + References + ---------- + .. [1] James R. Weaver, "Centrosymmetric (cross-symmetric) + matrices, their basic properties, eigenvalues, and + eigenvectors." The American Mathematical Monthly 92.10 + (1985): 711-717. + + Examples + -------- + Create an image with some features, then label it using the default + (cross-shaped) structuring element: + + >>> from scipy.ndimage import label, generate_binary_structure + >>> import numpy as np + >>> a = np.array([[0,0,1,1,0,0], + ... [0,0,0,1,0,0], + ... [1,1,0,0,1,0], + ... [0,0,0,1,0,0]]) + >>> labeled_array, num_features = label(a) + + Each of the 4 features are labeled with a different integer: + + >>> num_features + 4 + >>> labeled_array + array([[0, 0, 1, 1, 0, 0], + [0, 0, 0, 1, 0, 0], + [2, 2, 0, 0, 3, 0], + [0, 0, 0, 4, 0, 0]], dtype=int32) + + Generate a structuring element that will consider features connected even + if they touch diagonally: + + >>> s = generate_binary_structure(2,2) + + or, + + >>> s = [[1,1,1], + ... [1,1,1], + ... [1,1,1]] + + Label the image using the new structuring element: + + >>> labeled_array, num_features = label(a, structure=s) + + Show the 2 labeled features (note that features 1, 3, and 4 from above are + now considered a single feature): + + >>> num_features + 2 + >>> labeled_array + array([[0, 0, 1, 1, 0, 0], + [0, 0, 0, 1, 0, 0], + [2, 2, 0, 0, 1, 0], + [0, 0, 0, 1, 0, 0]], dtype=int32) + + """ + input = np.asarray(input) + if np.iscomplexobj(input): + raise TypeError('Complex type not supported') + if structure is None: + structure = _morphology.generate_binary_structure(input.ndim, 1) + structure = np.asarray(structure, dtype=bool) + if structure.ndim != input.ndim: + raise RuntimeError('structure and input must have equal rank') + for ii in structure.shape: + if ii != 3: + raise ValueError('structure dimensions must be equal to 3') + + # Use 32 bits if it's large enough for this image. + # _ni_label.label() needs two entries for background and + # foreground tracking + need_64bits = input.size >= (2**31 - 2) + + if isinstance(output, np.ndarray): + if output.shape != input.shape: + raise ValueError("output shape not correct") + caller_provided_output = True + else: + caller_provided_output = False + if output is None: + output = np.empty(input.shape, np.intp if need_64bits else np.int32) + else: + output = np.empty(input.shape, output) + + # handle scalars, 0-D arrays + if input.ndim == 0 or input.size == 0: + if input.ndim == 0: + # scalar + maxlabel = 1 if (input != 0) else 0 + output[...] = maxlabel + else: + # 0-D + maxlabel = 0 + if caller_provided_output: + return maxlabel + else: + return output, maxlabel + + try: + max_label = _ni_label._label(input, structure, output) + except _ni_label.NeedMoreBits as e: + # Make another attempt with enough bits, then try to cast to the + # new type. + tmp_output = np.empty(input.shape, np.intp if need_64bits else np.int32) + max_label = _ni_label._label(input, structure, tmp_output) + output[...] = tmp_output[...] + if not np.all(output == tmp_output): + # refuse to return bad results + raise RuntimeError( + "insufficient bit-depth in requested output type" + ) from e + + if caller_provided_output: + # result was written in-place + return max_label + else: + return output, max_label + + +def find_objects(input, max_label=0): + """ + Find objects in a labeled array. + + Parameters + ---------- + input : ndarray of ints + Array containing objects defined by different labels. Labels with + value 0 are ignored. + max_label : int, optional + Maximum label to be searched for in `input`. If max_label is not + given, the positions of all objects are returned. + + Returns + ------- + object_slices : list of tuples + A list of tuples, with each tuple containing N slices (with N the + dimension of the input array). Slices correspond to the minimal + parallelepiped that contains the object. If a number is missing, + None is returned instead of a slice. The label ``l`` corresponds to + the index ``l-1`` in the returned list. + + See Also + -------- + label, center_of_mass + + Notes + ----- + This function is very useful for isolating a volume of interest inside + a 3-D array, that cannot be "seen through". + + Examples + -------- + >>> from scipy import ndimage + >>> import numpy as np + >>> a = np.zeros((6,6), dtype=int) + >>> a[2:4, 2:4] = 1 + >>> a[4, 4] = 1 + >>> a[:2, :3] = 2 + >>> a[0, 5] = 3 + >>> a + array([[2, 2, 2, 0, 0, 3], + [2, 2, 2, 0, 0, 0], + [0, 0, 1, 1, 0, 0], + [0, 0, 1, 1, 0, 0], + [0, 0, 0, 0, 1, 0], + [0, 0, 0, 0, 0, 0]]) + >>> ndimage.find_objects(a) + [(slice(2, 5, None), slice(2, 5, None)), + (slice(0, 2, None), slice(0, 3, None)), + (slice(0, 1, None), slice(5, 6, None))] + >>> ndimage.find_objects(a, max_label=2) + [(slice(2, 5, None), slice(2, 5, None)), (slice(0, 2, None), slice(0, 3, None))] + >>> ndimage.find_objects(a == 1, max_label=2) + [(slice(2, 5, None), slice(2, 5, None)), None] + + >>> loc = ndimage.find_objects(a)[0] + >>> a[loc] + array([[1, 1, 0], + [1, 1, 0], + [0, 0, 1]]) + + """ + input = np.asarray(input) + if np.iscomplexobj(input): + raise TypeError('Complex type not supported') + + if max_label < 1: + max_label = input.max() + + return _nd_image.find_objects(input, max_label) + + +def value_indices(arr, *, ignore_value=None): + """ + Find indices of each distinct value in given array. + + Parameters + ---------- + arr : ndarray of ints + Array containing integer values. + ignore_value : int, optional + This value will be ignored in searching the `arr` array. If not + given, all values found will be included in output. Default + is None. + + Returns + ------- + indices : dictionary + A Python dictionary of array indices for each distinct value. The + dictionary is keyed by the distinct values, the entries are array + index tuples covering all occurrences of the value within the + array. + + This dictionary can occupy significant memory, usually several times + the size of the input array. + + See Also + -------- + label, maximum, median, minimum_position, extrema, sum, mean, variance, + standard_deviation, numpy.where, numpy.unique + + Notes + ----- + For a small array with few distinct values, one might use + `numpy.unique()` to find all possible values, and ``(arr == val)`` to + locate each value within that array. However, for large arrays, + with many distinct values, this can become extremely inefficient, + as locating each value would require a new search through the entire + array. Using this function, there is essentially one search, with + the indices saved for all distinct values. + + This is useful when matching a categorical image (e.g. a segmentation + or classification) to an associated image of other data, allowing + any per-class statistic(s) to then be calculated. Provides a + more flexible alternative to functions like ``scipy.ndimage.mean()`` + and ``scipy.ndimage.variance()``. + + Some other closely related functionality, with different strengths and + weaknesses, can also be found in ``scipy.stats.binned_statistic()`` and + the `scikit-image `_ function + ``skimage.measure.regionprops()``. + + Note for IDL users: this provides functionality equivalent to IDL's + REVERSE_INDICES option (as per the IDL documentation for the + `HISTOGRAM `_ + function). + + .. versionadded:: 1.10.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy import ndimage + >>> a = np.zeros((6, 6), dtype=int) + >>> a[2:4, 2:4] = 1 + >>> a[4, 4] = 1 + >>> a[:2, :3] = 2 + >>> a[0, 5] = 3 + >>> a + array([[2, 2, 2, 0, 0, 3], + [2, 2, 2, 0, 0, 0], + [0, 0, 1, 1, 0, 0], + [0, 0, 1, 1, 0, 0], + [0, 0, 0, 0, 1, 0], + [0, 0, 0, 0, 0, 0]]) + >>> val_indices = ndimage.value_indices(a) + + The dictionary `val_indices` will have an entry for each distinct + value in the input array. + + >>> val_indices.keys() + dict_keys([np.int64(0), np.int64(1), np.int64(2), np.int64(3)]) + + The entry for each value is an index tuple, locating the elements + with that value. + + >>> ndx1 = val_indices[1] + >>> ndx1 + (array([2, 2, 3, 3, 4]), array([2, 3, 2, 3, 4])) + + This can be used to index into the original array, or any other + array with the same shape. + + >>> a[ndx1] + array([1, 1, 1, 1, 1]) + + If the zeros were to be ignored, then the resulting dictionary + would no longer have an entry for zero. + + >>> val_indices = ndimage.value_indices(a, ignore_value=0) + >>> val_indices.keys() + dict_keys([np.int64(1), np.int64(2), np.int64(3)]) + + """ + # Cope with ignore_value being None, without too much extra complexity + # in the C code. If not None, the value is passed in as a numpy array + # with the same dtype as arr. + arr = np.asarray(arr) + ignore_value_arr = np.zeros((1,), dtype=arr.dtype) + ignoreIsNone = (ignore_value is None) + if not ignoreIsNone: + ignore_value_arr[0] = ignore_value_arr.dtype.type(ignore_value) + + val_indices = _nd_image.value_indices(arr, ignoreIsNone, ignore_value_arr) + return val_indices + + +def labeled_comprehension(input, labels, index, func, out_dtype, default, + pass_positions=False): + """ + Roughly equivalent to [func(input[labels == i]) for i in index]. + + Sequentially applies an arbitrary function (that works on array_like input) + to subsets of an N-D image array specified by `labels` and `index`. + The option exists to provide the function with positional parameters as the + second argument. + + Parameters + ---------- + input : array_like + Data from which to select `labels` to process. + labels : array_like or None + Labels to objects in `input`. + If not None, array must be same shape as `input`. + If None, `func` is applied to raveled `input`. + index : int, sequence of ints or None + Subset of `labels` to which to apply `func`. + If a scalar, a single value is returned. + If None, `func` is applied to all non-zero values of `labels`. + func : callable + Python function to apply to `labels` from `input`. + out_dtype : dtype + Dtype to use for `result`. + default : int, float or None + Default return value when a element of `index` does not exist + in `labels`. + pass_positions : bool, optional + If True, pass linear indices to `func` as a second argument. + Default is False. + + Returns + ------- + result : ndarray + Result of applying `func` to each of `labels` to `input` in `index`. + + Examples + -------- + >>> import numpy as np + >>> a = np.array([[1, 2, 0, 0], + ... [5, 3, 0, 4], + ... [0, 0, 0, 7], + ... [9, 3, 0, 0]]) + >>> from scipy import ndimage + >>> lbl, nlbl = ndimage.label(a) + >>> lbls = np.arange(1, nlbl+1) + >>> ndimage.labeled_comprehension(a, lbl, lbls, np.mean, float, 0) + array([ 2.75, 5.5 , 6. ]) + + Falling back to `default`: + + >>> lbls = np.arange(1, nlbl+2) + >>> ndimage.labeled_comprehension(a, lbl, lbls, np.mean, float, -1) + array([ 2.75, 5.5 , 6. , -1. ]) + + Passing positions: + + >>> def fn(val, pos): + ... print("fn says: %s : %s" % (val, pos)) + ... return (val.sum()) if (pos.sum() % 2 == 0) else (-val.sum()) + ... + >>> ndimage.labeled_comprehension(a, lbl, lbls, fn, float, 0, True) + fn says: [1 2 5 3] : [0 1 4 5] + fn says: [4 7] : [ 7 11] + fn says: [9 3] : [12 13] + array([ 11., 11., -12., 0.]) + + """ + + as_scalar = np.isscalar(index) + input = np.asarray(input) + + if pass_positions: + positions = np.arange(input.size).reshape(input.shape) + + if labels is None: + if index is not None: + raise ValueError("index without defined labels") + if not pass_positions: + return func(input.ravel()) + else: + return func(input.ravel(), positions.ravel()) + + labels = np.asarray(labels) + + try: + input, labels = np.broadcast_arrays(input, labels) + except ValueError as e: + raise ValueError("input and labels must have the same shape " + "(excepting dimensions with width 1)") from e + + if index is None: + if not pass_positions: + return func(input[labels > 0]) + else: + return func(input[labels > 0], positions[labels > 0]) + + index = np.atleast_1d(index) + if np.any(index.astype(labels.dtype).astype(index.dtype) != index): + raise ValueError(f"Cannot convert index values from <{index.dtype}> to " + f"<{labels.dtype}> (labels' type) without loss of precision") + + index = index.astype(labels.dtype) + + # optimization: find min/max in index, + # and select those parts of labels, input, and positions + lo = index.min() + hi = index.max() + mask = (labels >= lo) & (labels <= hi) + + # this also ravels the arrays + labels = labels[mask] + input = input[mask] + if pass_positions: + positions = positions[mask] + + # sort everything by labels + label_order = labels.argsort() + labels = labels[label_order] + input = input[label_order] + if pass_positions: + positions = positions[label_order] + + index_order = index.argsort() + sorted_index = index[index_order] + + def do_map(inputs, output): + """labels must be sorted""" + nidx = sorted_index.size + + # Find boundaries for each stretch of constant labels + # This could be faster, but we already paid N log N to sort labels. + lo = np.searchsorted(labels, sorted_index, side='left') + hi = np.searchsorted(labels, sorted_index, side='right') + + for i, l, h in zip(range(nidx), lo, hi): + if l == h: + continue + output[i] = func(*[inp[l:h] for inp in inputs]) + + temp = np.empty(index.shape, out_dtype) + temp[:] = default + if not pass_positions: + do_map([input], temp) + else: + do_map([input, positions], temp) + + output = np.zeros(index.shape, out_dtype) + output[index_order] = temp + if as_scalar: + output = output[0] + + return output + + +def _safely_castable_to_int(dt): + """Test whether the NumPy data type `dt` can be safely cast to an int.""" + int_size = np.dtype(int).itemsize + safe = ((np.issubdtype(dt, np.signedinteger) and dt.itemsize <= int_size) or + (np.issubdtype(dt, np.unsignedinteger) and dt.itemsize < int_size)) + return safe + + +def _stats(input, labels=None, index=None, centered=False): + """Count, sum, and optionally compute (sum - centre)^2 of input by label + + Parameters + ---------- + input : array_like, N-D + The input data to be analyzed. + labels : array_like (N-D), optional + The labels of the data in `input`. This array must be broadcast + compatible with `input`; typically, it is the same shape as `input`. + If `labels` is None, all nonzero values in `input` are treated as + the single labeled group. + index : label or sequence of labels, optional + These are the labels of the groups for which the stats are computed. + If `index` is None, the stats are computed for the single group where + `labels` is greater than 0. + centered : bool, optional + If True, the centered sum of squares for each labeled group is + also returned. Default is False. + + Returns + ------- + counts : int or ndarray of ints + The number of elements in each labeled group. + sums : scalar or ndarray of scalars + The sums of the values in each labeled group. + sums_c : scalar or ndarray of scalars, optional + The sums of mean-centered squares of the values in each labeled group. + This is only returned if `centered` is True. + + """ + def single_group(vals): + if centered: + vals_c = vals - vals.mean() + return vals.size, vals.sum(), (vals_c * vals_c.conjugate()).sum() + else: + return vals.size, vals.sum() + + input = np.asarray(input) + if labels is None: + return single_group(input) + + # ensure input and labels match sizes + input, labels = np.broadcast_arrays(input, labels) + + if index is None: + return single_group(input[labels > 0]) + + if np.isscalar(index): + return single_group(input[labels == index]) + + def _sum_centered(labels): + # `labels` is expected to be an ndarray with the same shape as `input`. + # It must contain the label indices (which are not necessarily the labels + # themselves). + means = sums / counts + centered_input = input - means[labels] + # bincount expects 1-D inputs, so we ravel the arguments. + bc = np.bincount(labels.ravel(), + weights=(centered_input * + centered_input.conjugate()).ravel()) + return bc + + # Remap labels to unique integers if necessary, or if the largest + # label is larger than the number of values. + + if (not _safely_castable_to_int(labels.dtype) or + labels.min() < 0 or labels.max() > labels.size): + # Use np.unique to generate the label indices. `new_labels` will + # be 1-D, but it should be interpreted as the flattened N-D array of + # label indices. + unique_labels, new_labels = np.unique(labels, return_inverse=True) + new_labels = np.reshape(new_labels, (-1,)) # flatten, since it may be >1-D + counts = np.bincount(new_labels) + sums = np.bincount(new_labels, weights=input.ravel()) + if centered: + # Compute the sum of the mean-centered squares. + # We must reshape new_labels to the N-D shape of `input` before + # passing it _sum_centered. + sums_c = _sum_centered(new_labels.reshape(labels.shape)) + idxs = np.searchsorted(unique_labels, index) + # make all of idxs valid + idxs[idxs >= unique_labels.size] = 0 + found = (unique_labels[idxs] == index) + else: + # labels are an integer type allowed by bincount, and there aren't too + # many, so call bincount directly. + counts = np.bincount(labels.ravel()) + sums = np.bincount(labels.ravel(), weights=input.ravel()) + if centered: + sums_c = _sum_centered(labels) + # make sure all index values are valid + idxs = np.asanyarray(index, np.int_).copy() + found = (idxs >= 0) & (idxs < counts.size) + idxs[~found] = 0 + + counts = counts[idxs] + counts[~found] = 0 + sums = sums[idxs] + sums[~found] = 0 + + if not centered: + return (counts, sums) + else: + sums_c = sums_c[idxs] + sums_c[~found] = 0 + return (counts, sums, sums_c) + + +def sum(input, labels=None, index=None): + """ + Calculate the sum of the values of the array. + + Notes + ----- + This is an alias for `ndimage.sum_labels` kept for backwards compatibility + reasons, for new code please prefer `sum_labels`. See the `sum_labels` + docstring for more details. + + """ + return sum_labels(input, labels, index) + + +def sum_labels(input, labels=None, index=None): + """ + Calculate the sum of the values of the array. + + Parameters + ---------- + input : array_like + Values of `input` inside the regions defined by `labels` + are summed together. + labels : array_like of ints, optional + Assign labels to the values of the array. Has to have the same shape as + `input`. + index : array_like, optional + A single label number or a sequence of label numbers of + the objects to be measured. + + Returns + ------- + sum : ndarray or scalar + An array of the sums of values of `input` inside the regions defined + by `labels` with the same shape as `index`. If 'index' is None or scalar, + a scalar is returned. + + See Also + -------- + mean, median + + Examples + -------- + >>> from scipy import ndimage + >>> input = [0,1,2,3] + >>> labels = [1,1,2,2] + >>> ndimage.sum_labels(input, labels, index=[1,2]) + [1.0, 5.0] + >>> ndimage.sum_labels(input, labels, index=1) + 1 + >>> ndimage.sum_labels(input, labels) + 6 + + + """ + count, sum = _stats(input, labels, index) + return sum + + +def mean(input, labels=None, index=None): + """ + Calculate the mean of the values of an array at labels. + + Parameters + ---------- + input : array_like + Array on which to compute the mean of elements over distinct + regions. + labels : array_like, optional + Array of labels of same shape, or broadcastable to the same shape as + `input`. All elements sharing the same label form one region over + which the mean of the elements is computed. + index : int or sequence of ints, optional + Labels of the objects over which the mean is to be computed. + Default is None, in which case the mean for all values where label is + greater than 0 is calculated. + + Returns + ------- + out : list + Sequence of same length as `index`, with the mean of the different + regions labeled by the labels in `index`. + + See Also + -------- + variance, standard_deviation, minimum, maximum, sum, label + + Examples + -------- + >>> from scipy import ndimage + >>> import numpy as np + >>> a = np.arange(25).reshape((5,5)) + >>> labels = np.zeros_like(a) + >>> labels[3:5,3:5] = 1 + >>> index = np.unique(labels) + >>> labels + array([[0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 1, 1], + [0, 0, 0, 1, 1]]) + >>> index + array([0, 1]) + >>> ndimage.mean(a, labels=labels, index=index) + [10.285714285714286, 21.0] + + """ + + count, sum = _stats(input, labels, index) + return sum / np.asanyarray(count).astype(np.float64) + + +def variance(input, labels=None, index=None): + """ + Calculate the variance of the values of an N-D image array, optionally at + specified sub-regions. + + Parameters + ---------- + input : array_like + Nd-image data to process. + labels : array_like, optional + Labels defining sub-regions in `input`. + If not None, must be same shape as `input`. + index : int or sequence of ints, optional + `labels` to include in output. If None (default), all values where + `labels` is non-zero are used. + + Returns + ------- + variance : float or ndarray + Values of variance, for each sub-region if `labels` and `index` are + specified. + + See Also + -------- + label, standard_deviation, maximum, minimum, extrema + + Examples + -------- + >>> import numpy as np + >>> a = np.array([[1, 2, 0, 0], + ... [5, 3, 0, 4], + ... [0, 0, 0, 7], + ... [9, 3, 0, 0]]) + >>> from scipy import ndimage + >>> ndimage.variance(a) + 7.609375 + + Features to process can be specified using `labels` and `index`: + + >>> lbl, nlbl = ndimage.label(a) + >>> ndimage.variance(a, lbl, index=np.arange(1, nlbl+1)) + array([ 2.1875, 2.25 , 9. ]) + + If no index is given, all non-zero `labels` are processed: + + >>> ndimage.variance(a, lbl) + 6.1875 + + """ + count, sum, sum_c_sq = _stats(input, labels, index, centered=True) + return sum_c_sq / np.asanyarray(count).astype(float) + + +def standard_deviation(input, labels=None, index=None): + """ + Calculate the standard deviation of the values of an N-D image array, + optionally at specified sub-regions. + + Parameters + ---------- + input : array_like + N-D image data to process. + labels : array_like, optional + Labels to identify sub-regions in `input`. + If not None, must be same shape as `input`. + index : int or sequence of ints, optional + `labels` to include in output. If None (default), all values where + `labels` is non-zero are used. + + Returns + ------- + standard_deviation : float or ndarray + Values of standard deviation, for each sub-region if `labels` and + `index` are specified. + + See Also + -------- + label, variance, maximum, minimum, extrema + + Examples + -------- + >>> import numpy as np + >>> a = np.array([[1, 2, 0, 0], + ... [5, 3, 0, 4], + ... [0, 0, 0, 7], + ... [9, 3, 0, 0]]) + >>> from scipy import ndimage + >>> ndimage.standard_deviation(a) + 2.7585095613392387 + + Features to process can be specified using `labels` and `index`: + + >>> lbl, nlbl = ndimage.label(a) + >>> ndimage.standard_deviation(a, lbl, index=np.arange(1, nlbl+1)) + array([ 1.479, 1.5 , 3. ]) + + If no index is given, non-zero `labels` are processed: + + >>> ndimage.standard_deviation(a, lbl) + 2.4874685927665499 + + """ + return np.sqrt(variance(input, labels, index)) + + +def _select(input, labels=None, index=None, find_min=False, find_max=False, + find_min_positions=False, find_max_positions=False, + find_median=False): + """Returns min, max, or both, plus their positions (if requested), and + median.""" + + input = np.asanyarray(input) + + find_positions = find_min_positions or find_max_positions + positions = None + if find_positions: + positions = np.arange(input.size).reshape(input.shape) + + def single_group(vals, positions): + result = [] + if find_min: + result += [vals.min()] + if find_min_positions: + result += [positions[vals == vals.min()][0]] + if find_max: + result += [vals.max()] + if find_max_positions: + result += [positions[vals == vals.max()][0]] + if find_median: + result += [np.median(vals)] + return result + + if labels is None: + return single_group(input, positions) + + # ensure input and labels match sizes + input, labels = np.broadcast_arrays(input, labels) + + if index is None: + mask = (labels > 0) + masked_positions = None + if find_positions: + masked_positions = positions[mask] + return single_group(input[mask], masked_positions) + + if np.isscalar(index): + mask = (labels == index) + masked_positions = None + if find_positions: + masked_positions = positions[mask] + return single_group(input[mask], masked_positions) + + index = np.asarray(index) + + # remap labels to unique integers if necessary, or if the largest + # label is larger than the number of values. + if (not _safely_castable_to_int(labels.dtype) or + labels.min() < 0 or labels.max() > labels.size): + # remap labels, and indexes + unique_labels, labels = np.unique(labels, return_inverse=True) + idxs = np.searchsorted(unique_labels, index) + + # make all of idxs valid + idxs[idxs >= unique_labels.size] = 0 + found = (unique_labels[idxs] == index) + else: + # labels are an integer type, and there aren't too many + idxs = np.asanyarray(index, np.int_).copy() + found = (idxs >= 0) & (idxs <= labels.max()) + + idxs[~ found] = labels.max() + 1 + + if find_median: + order = np.lexsort((input.ravel(), labels.ravel())) + else: + order = input.ravel().argsort() + input = input.ravel()[order] + labels = labels.ravel()[order] + if find_positions: + positions = positions.ravel()[order] + + result = [] + if find_min: + mins = np.zeros(labels.max() + 2, input.dtype) + mins[labels[::-1]] = input[::-1] + result += [mins[idxs]] + if find_min_positions: + minpos = np.zeros(labels.max() + 2, int) + minpos[labels[::-1]] = positions[::-1] + result += [minpos[idxs]] + if find_max: + maxs = np.zeros(labels.max() + 2, input.dtype) + maxs[labels] = input + result += [maxs[idxs]] + if find_max_positions: + maxpos = np.zeros(labels.max() + 2, int) + maxpos[labels] = positions + result += [maxpos[idxs]] + if find_median: + locs = np.arange(len(labels)) + lo = np.zeros(labels.max() + 2, np.int_) + lo[labels[::-1]] = locs[::-1] + hi = np.zeros(labels.max() + 2, np.int_) + hi[labels] = locs + lo = lo[idxs] + hi = hi[idxs] + # lo is an index to the lowest value in input for each label, + # hi is an index to the largest value. + # move them to be either the same ((hi - lo) % 2 == 0) or next + # to each other ((hi - lo) % 2 == 1), then average. + step = (hi - lo) // 2 + lo += step + hi -= step + if (np.issubdtype(input.dtype, np.integer) + or np.issubdtype(input.dtype, np.bool_)): + # avoid integer overflow or boolean addition (gh-12836) + result += [(input[lo].astype('d') + input[hi].astype('d')) / 2.0] + else: + result += [(input[lo] + input[hi]) / 2.0] + + return result + + +def minimum(input, labels=None, index=None): + """ + Calculate the minimum of the values of an array over labeled regions. + + Parameters + ---------- + input : array_like + Array_like of values. For each region specified by `labels`, the + minimal values of `input` over the region is computed. + labels : array_like, optional + An array_like of integers marking different regions over which the + minimum value of `input` is to be computed. `labels` must have the + same shape as `input`. If `labels` is not specified, the minimum + over the whole array is returned. + index : array_like, optional + A list of region labels that are taken into account for computing the + minima. If index is None, the minimum over all elements where `labels` + is non-zero is returned. + + Returns + ------- + minimum : float or list of floats + List of minima of `input` over the regions determined by `labels` and + whose index is in `index`. If `index` or `labels` are not specified, a + float is returned: the minimal value of `input` if `labels` is None, + and the minimal value of elements where `labels` is greater than zero + if `index` is None. + + See Also + -------- + label, maximum, median, minimum_position, extrema, sum, mean, variance, + standard_deviation + + Notes + ----- + The function returns a Python list and not a NumPy array, use + `np.array` to convert the list to an array. + + Examples + -------- + >>> from scipy import ndimage + >>> import numpy as np + >>> a = np.array([[1, 2, 0, 0], + ... [5, 3, 0, 4], + ... [0, 0, 0, 7], + ... [9, 3, 0, 0]]) + >>> labels, labels_nb = ndimage.label(a) + >>> labels + array([[1, 1, 0, 0], + [1, 1, 0, 2], + [0, 0, 0, 2], + [3, 3, 0, 0]], dtype=int32) + >>> ndimage.minimum(a, labels=labels, index=np.arange(1, labels_nb + 1)) + [1, 4, 3] + >>> ndimage.minimum(a) + 0 + >>> ndimage.minimum(a, labels=labels) + 1 + + """ + return _select(input, labels, index, find_min=True)[0] + + +def maximum(input, labels=None, index=None): + """ + Calculate the maximum of the values of an array over labeled regions. + + Parameters + ---------- + input : array_like + Array_like of values. For each region specified by `labels`, the + maximal values of `input` over the region is computed. + labels : array_like, optional + An array of integers marking different regions over which the + maximum value of `input` is to be computed. `labels` must have the + same shape as `input`. If `labels` is not specified, the maximum + over the whole array is returned. + index : array_like, optional + A list of region labels that are taken into account for computing the + maxima. If index is None, the maximum over all elements where `labels` + is non-zero is returned. + + Returns + ------- + output : float or list of floats + List of maxima of `input` over the regions determined by `labels` and + whose index is in `index`. If `index` or `labels` are not specified, a + float is returned: the maximal value of `input` if `labels` is None, + and the maximal value of elements where `labels` is greater than zero + if `index` is None. + + See Also + -------- + label, minimum, median, maximum_position, extrema, sum, mean, variance, + standard_deviation + + Notes + ----- + The function returns a Python list and not a NumPy array, use + `np.array` to convert the list to an array. + + Examples + -------- + >>> import numpy as np + >>> a = np.arange(16).reshape((4,4)) + >>> a + array([[ 0, 1, 2, 3], + [ 4, 5, 6, 7], + [ 8, 9, 10, 11], + [12, 13, 14, 15]]) + >>> labels = np.zeros_like(a) + >>> labels[:2,:2] = 1 + >>> labels[2:, 1:3] = 2 + >>> labels + array([[1, 1, 0, 0], + [1, 1, 0, 0], + [0, 2, 2, 0], + [0, 2, 2, 0]]) + >>> from scipy import ndimage + >>> ndimage.maximum(a) + 15 + >>> ndimage.maximum(a, labels=labels, index=[1,2]) + [5, 14] + >>> ndimage.maximum(a, labels=labels) + 14 + + >>> b = np.array([[1, 2, 0, 0], + ... [5, 3, 0, 4], + ... [0, 0, 0, 7], + ... [9, 3, 0, 0]]) + >>> labels, labels_nb = ndimage.label(b) + >>> labels + array([[1, 1, 0, 0], + [1, 1, 0, 2], + [0, 0, 0, 2], + [3, 3, 0, 0]], dtype=int32) + >>> ndimage.maximum(b, labels=labels, index=np.arange(1, labels_nb + 1)) + [5, 7, 9] + + """ + return _select(input, labels, index, find_max=True)[0] + + +def median(input, labels=None, index=None): + """ + Calculate the median of the values of an array over labeled regions. + + Parameters + ---------- + input : array_like + Array_like of values. For each region specified by `labels`, the + median value of `input` over the region is computed. + labels : array_like, optional + An array_like of integers marking different regions over which the + median value of `input` is to be computed. `labels` must have the + same shape as `input`. If `labels` is not specified, the median + over the whole array is returned. + index : array_like, optional + A list of region labels that are taken into account for computing the + medians. If index is None, the median over all elements where `labels` + is non-zero is returned. + + Returns + ------- + median : float or list of floats + List of medians of `input` over the regions determined by `labels` and + whose index is in `index`. If `index` or `labels` are not specified, a + float is returned: the median value of `input` if `labels` is None, + and the median value of elements where `labels` is greater than zero + if `index` is None. + + See Also + -------- + label, minimum, maximum, extrema, sum, mean, variance, standard_deviation + + Notes + ----- + The function returns a Python list and not a NumPy array, use + `np.array` to convert the list to an array. + + Examples + -------- + >>> from scipy import ndimage + >>> import numpy as np + >>> a = np.array([[1, 2, 0, 1], + ... [5, 3, 0, 4], + ... [0, 0, 0, 7], + ... [9, 3, 0, 0]]) + >>> labels, labels_nb = ndimage.label(a) + >>> labels + array([[1, 1, 0, 2], + [1, 1, 0, 2], + [0, 0, 0, 2], + [3, 3, 0, 0]], dtype=int32) + >>> ndimage.median(a, labels=labels, index=np.arange(1, labels_nb + 1)) + [2.5, 4.0, 6.0] + >>> ndimage.median(a) + 1.0 + >>> ndimage.median(a, labels=labels) + 3.0 + + """ + return _select(input, labels, index, find_median=True)[0] + + +def minimum_position(input, labels=None, index=None): + """ + Find the positions of the minimums of the values of an array at labels. + + Parameters + ---------- + input : array_like + Array_like of values. + labels : array_like, optional + An array of integers marking different regions over which the + position of the minimum value of `input` is to be computed. + `labels` must have the same shape as `input`. If `labels` is not + specified, the location of the first minimum over the whole + array is returned. + + The `labels` argument only works when `index` is specified. + index : array_like, optional + A list of region labels that are taken into account for finding the + location of the minima. If `index` is None, the ``first`` minimum + over all elements where `labels` is non-zero is returned. + + The `index` argument only works when `labels` is specified. + + Returns + ------- + output : list of tuples of ints + Tuple of ints or list of tuples of ints that specify the location + of minima of `input` over the regions determined by `labels` and + whose index is in `index`. + + If `index` or `labels` are not specified, a tuple of ints is + returned specifying the location of the first minimal value of `input`. + + See Also + -------- + label, minimum, median, maximum_position, extrema, sum, mean, variance, + standard_deviation + + Examples + -------- + >>> import numpy as np + >>> a = np.array([[10, 20, 30], + ... [40, 80, 100], + ... [1, 100, 200]]) + >>> b = np.array([[1, 2, 0, 1], + ... [5, 3, 0, 4], + ... [0, 0, 0, 7], + ... [9, 3, 0, 0]]) + + >>> from scipy import ndimage + + >>> ndimage.minimum_position(a) + (2, 0) + >>> ndimage.minimum_position(b) + (0, 2) + + Features to process can be specified using `labels` and `index`: + + >>> label, pos = ndimage.label(a) + >>> ndimage.minimum_position(a, label, index=np.arange(1, pos+1)) + [(2, 0)] + + >>> label, pos = ndimage.label(b) + >>> ndimage.minimum_position(b, label, index=np.arange(1, pos+1)) + [(0, 0), (0, 3), (3, 1)] + + """ + dims = np.array(np.asarray(input).shape) + # see np.unravel_index to understand this line. + dim_prod = np.cumprod([1] + list(dims[:0:-1]))[::-1] + + result = _select(input, labels, index, find_min_positions=True)[0] + + if np.isscalar(result): + return tuple((result // dim_prod) % dims) + + return [tuple(v) for v in (result.reshape(-1, 1) // dim_prod) % dims] + + +def maximum_position(input, labels=None, index=None): + """ + Find the positions of the maximums of the values of an array at labels. + + For each region specified by `labels`, the position of the maximum + value of `input` within the region is returned. + + Parameters + ---------- + input : array_like + Array_like of values. + labels : array_like, optional + An array of integers marking different regions over which the + position of the maximum value of `input` is to be computed. + `labels` must have the same shape as `input`. If `labels` is not + specified, the location of the first maximum over the whole + array is returned. + + The `labels` argument only works when `index` is specified. + index : array_like, optional + A list of region labels that are taken into account for finding the + location of the maxima. If `index` is None, the first maximum + over all elements where `labels` is non-zero is returned. + + The `index` argument only works when `labels` is specified. + + Returns + ------- + output : list of tuples of ints + List of tuples of ints that specify the location of maxima of + `input` over the regions determined by `labels` and whose index + is in `index`. + + If `index` or `labels` are not specified, a tuple of ints is + returned specifying the location of the ``first`` maximal value + of `input`. + + See Also + -------- + label, minimum, median, maximum_position, extrema, sum, mean, variance, + standard_deviation + + Examples + -------- + >>> from scipy import ndimage + >>> import numpy as np + >>> a = np.array([[1, 2, 0, 0], + ... [5, 3, 0, 4], + ... [0, 0, 0, 7], + ... [9, 3, 0, 0]]) + >>> ndimage.maximum_position(a) + (3, 0) + + Features to process can be specified using `labels` and `index`: + + >>> lbl = np.array([[0, 1, 2, 3], + ... [0, 1, 2, 3], + ... [0, 1, 2, 3], + ... [0, 1, 2, 3]]) + >>> ndimage.maximum_position(a, lbl, 1) + (1, 1) + + If no index is given, non-zero `labels` are processed: + + >>> ndimage.maximum_position(a, lbl) + (2, 3) + + If there are no maxima, the position of the first element is returned: + + >>> ndimage.maximum_position(a, lbl, 2) + (0, 2) + + """ + dims = np.array(np.asarray(input).shape) + # see np.unravel_index to understand this line. + dim_prod = np.cumprod([1] + list(dims[:0:-1]))[::-1] + + result = _select(input, labels, index, find_max_positions=True)[0] + + if np.isscalar(result): + return tuple((result // dim_prod) % dims) + + return [tuple(v) for v in (result.reshape(-1, 1) // dim_prod) % dims] + + +def extrema(input, labels=None, index=None): + """ + Calculate the minimums and maximums of the values of an array + at labels, along with their positions. + + Parameters + ---------- + input : ndarray + N-D image data to process. + labels : ndarray, optional + Labels of features in input. + If not None, must be same shape as `input`. + index : int or sequence of ints, optional + Labels to include in output. If None (default), all values where + non-zero `labels` are used. + + Returns + ------- + minimums, maximums : int or ndarray + Values of minimums and maximums in each feature. + min_positions, max_positions : tuple or list of tuples + Each tuple gives the N-D coordinates of the corresponding minimum + or maximum. + + See Also + -------- + maximum, minimum, maximum_position, minimum_position, center_of_mass + + Examples + -------- + >>> import numpy as np + >>> a = np.array([[1, 2, 0, 0], + ... [5, 3, 0, 4], + ... [0, 0, 0, 7], + ... [9, 3, 0, 0]]) + >>> from scipy import ndimage + >>> ndimage.extrema(a) + (0, 9, (0, 2), (3, 0)) + + Features to process can be specified using `labels` and `index`: + + >>> lbl, nlbl = ndimage.label(a) + >>> ndimage.extrema(a, lbl, index=np.arange(1, nlbl+1)) + (array([1, 4, 3]), + array([5, 7, 9]), + [(0, 0), (1, 3), (3, 1)], + [(1, 0), (2, 3), (3, 0)]) + + If no index is given, non-zero `labels` are processed: + + >>> ndimage.extrema(a, lbl) + (1, 9, (0, 0), (3, 0)) + + """ + dims = np.array(np.asarray(input).shape) + # see np.unravel_index to understand this line. + dim_prod = np.cumprod([1] + list(dims[:0:-1]))[::-1] + + minimums, min_positions, maximums, max_positions = _select(input, labels, + index, + find_min=True, + find_max=True, + find_min_positions=True, + find_max_positions=True) + + if np.isscalar(minimums): + return (minimums, maximums, tuple((min_positions // dim_prod) % dims), + tuple((max_positions // dim_prod) % dims)) + + min_positions = [ + tuple(v) for v in (min_positions.reshape(-1, 1) // dim_prod) % dims + ] + max_positions = [ + tuple(v) for v in (max_positions.reshape(-1, 1) // dim_prod) % dims + ] + + return minimums, maximums, min_positions, max_positions + + +def center_of_mass(input, labels=None, index=None): + """ + Calculate the center of mass of the values of an array at labels. + + Parameters + ---------- + input : ndarray + Data from which to calculate center-of-mass. The masses can either + be positive or negative. + labels : ndarray, optional + Labels for objects in `input`, as generated by `ndimage.label`. + Only used with `index`. Dimensions must be the same as `input`. + index : int or sequence of ints, optional + Labels for which to calculate centers-of-mass. If not specified, + the combined center of mass of all labels greater than zero + will be calculated. Only used with `labels`. + + Returns + ------- + center_of_mass : tuple, or list of tuples + Coordinates of centers-of-mass. + + Examples + -------- + >>> import numpy as np + >>> a = np.array(([0,0,0,0], + ... [0,1,1,0], + ... [0,1,1,0], + ... [0,1,1,0])) + >>> from scipy import ndimage + >>> ndimage.center_of_mass(a) + (2.0, 1.5) + + Calculation of multiple objects in an image + + >>> b = np.array(([0,1,1,0], + ... [0,1,0,0], + ... [0,0,0,0], + ... [0,0,1,1], + ... [0,0,1,1])) + >>> lbl = ndimage.label(b)[0] + >>> ndimage.center_of_mass(b, lbl, [1,2]) + [(0.33333333333333331, 1.3333333333333333), (3.5, 2.5)] + + Negative masses are also accepted, which can occur for example when + bias is removed from measured data due to random noise. + + >>> c = np.array(([-1,0,0,0], + ... [0,-1,-1,0], + ... [0,1,-1,0], + ... [0,1,1,0])) + >>> ndimage.center_of_mass(c) + (-4.0, 1.0) + + If there are division by zero issues, the function does not raise an + error but rather issues a RuntimeWarning before returning inf and/or NaN. + + >>> d = np.array([-1, 1]) + >>> ndimage.center_of_mass(d) + (inf,) + """ + input = np.asarray(input) + normalizer = sum_labels(input, labels, index) + grids = np.ogrid[[slice(0, i) for i in input.shape]] + + results = [sum_labels(input * grids[dir].astype(float), labels, index) / normalizer + for dir in range(input.ndim)] + + if np.isscalar(results[0]): + return tuple(results) + + return [tuple(v) for v in np.array(results).T] + + +def histogram(input, min, max, bins, labels=None, index=None): + """ + Calculate the histogram of the values of an array, optionally at labels. + + Histogram calculates the frequency of values in an array within bins + determined by `min`, `max`, and `bins`. The `labels` and `index` + keywords can limit the scope of the histogram to specified sub-regions + within the array. + + Parameters + ---------- + input : array_like + Data for which to calculate histogram. + min, max : int + Minimum and maximum values of range of histogram bins. + bins : int + Number of bins. + labels : array_like, optional + Labels for objects in `input`. + If not None, must be same shape as `input`. + index : int or sequence of ints, optional + Label or labels for which to calculate histogram. If None, all values + where label is greater than zero are used + + Returns + ------- + hist : ndarray + Histogram counts. + + Examples + -------- + >>> import numpy as np + >>> a = np.array([[ 0. , 0.2146, 0.5962, 0. ], + ... [ 0. , 0.7778, 0. , 0. ], + ... [ 0. , 0. , 0. , 0. ], + ... [ 0. , 0. , 0.7181, 0.2787], + ... [ 0. , 0. , 0.6573, 0.3094]]) + >>> from scipy import ndimage + >>> ndimage.histogram(a, 0, 1, 10) + array([13, 0, 2, 1, 0, 1, 1, 2, 0, 0]) + + With labels and no indices, non-zero elements are counted: + + >>> lbl, nlbl = ndimage.label(a) + >>> ndimage.histogram(a, 0, 1, 10, lbl) + array([0, 0, 2, 1, 0, 1, 1, 2, 0, 0]) + + Indices can be used to count only certain objects: + + >>> ndimage.histogram(a, 0, 1, 10, lbl, 2) + array([0, 0, 1, 1, 0, 0, 1, 1, 0, 0]) + + """ + _bins = np.linspace(min, max, bins + 1) + + def _hist(vals): + return np.histogram(vals, _bins)[0] + + return labeled_comprehension(input, labels, index, _hist, object, None, + pass_positions=False) + + +def watershed_ift(input, markers, structure=None, output=None): + """ + Apply watershed from markers using image foresting transform algorithm. + + Parameters + ---------- + input : array_like + Input. + markers : array_like + Markers are points within each watershed that form the beginning + of the process. Negative markers are considered background markers + which are processed after the other markers. + structure : structure element, optional + A structuring element defining the connectivity of the object can be + provided. If None, an element is generated with a squared + connectivity equal to one. + output : ndarray, optional + An output array can optionally be provided. The same shape as input. + + Returns + ------- + watershed_ift : ndarray + Output. Same shape as `input`. + + References + ---------- + .. [1] A.X. Falcao, J. Stolfi and R. de Alencar Lotufo, "The image + foresting transform: theory, algorithms, and applications", + Pattern Analysis and Machine Intelligence, vol. 26, pp. 19-29, 2004. + + """ + input = np.asarray(input) + if input.dtype.type not in [np.uint8, np.uint16]: + raise TypeError('only 8 and 16 unsigned inputs are supported') + + if structure is None: + structure = _morphology.generate_binary_structure(input.ndim, 1) + structure = np.asarray(structure, dtype=bool) + if structure.ndim != input.ndim: + raise RuntimeError('structure and input must have equal rank') + for ii in structure.shape: + if ii != 3: + raise RuntimeError('structure dimensions must be equal to 3') + + if not structure.flags.contiguous: + structure = structure.copy() + markers = np.asarray(markers) + if input.shape != markers.shape: + raise RuntimeError('input and markers must have equal shape') + + integral_types = [np.int8, + np.int16, + np.int32, + np.int64, + np.intc, + np.intp] + + if markers.dtype.type not in integral_types: + raise RuntimeError('marker should be of integer type') + + if isinstance(output, np.ndarray): + if output.dtype.type not in integral_types: + raise RuntimeError('output should be of integer type') + else: + output = markers.dtype + + output = _ni_support._get_output(output, input) + _nd_image.watershed_ift(input, markers, structure, output) + return output diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/_morphology.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/_morphology.py new file mode 100644 index 0000000000000000000000000000000000000000..12972c09a7cd5de0ca059814281fb9d210fbd395 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/_morphology.py @@ -0,0 +1,2629 @@ +# Copyright (C) 2003-2005 Peter J. Verveer +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# 2. Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# 3. The name of the author may not be used to endorse or promote +# products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS +# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE +# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import warnings +import operator + +import numpy as np +from . import _ni_support +from . import _nd_image +from . import _filters + +__all__ = ['iterate_structure', 'generate_binary_structure', 'binary_erosion', + 'binary_dilation', 'binary_opening', 'binary_closing', + 'binary_hit_or_miss', 'binary_propagation', 'binary_fill_holes', + 'grey_erosion', 'grey_dilation', 'grey_opening', 'grey_closing', + 'morphological_gradient', 'morphological_laplace', 'white_tophat', + 'black_tophat', 'distance_transform_bf', 'distance_transform_cdt', + 'distance_transform_edt'] + + +def _center_is_true(structure, origin): + structure = np.asarray(structure) + coor = tuple([oo + ss // 2 for ss, oo in zip(structure.shape, + origin)]) + return bool(structure[coor]) + + +def iterate_structure(structure, iterations, origin=None): + """ + Iterate a structure by dilating it with itself. + + Parameters + ---------- + structure : array_like + Structuring element (an array of bools, for example), to be dilated with + itself. + iterations : int + number of dilations performed on the structure with itself + origin : optional + If origin is None, only the iterated structure is returned. If + not, a tuple of the iterated structure and the modified origin is + returned. + + Returns + ------- + iterate_structure : ndarray of bools + A new structuring element obtained by dilating `structure` + (`iterations` - 1) times with itself. + + See Also + -------- + generate_binary_structure + + Examples + -------- + >>> from scipy import ndimage + >>> struct = ndimage.generate_binary_structure(2, 1) + >>> struct.astype(int) + array([[0, 1, 0], + [1, 1, 1], + [0, 1, 0]]) + >>> ndimage.iterate_structure(struct, 2).astype(int) + array([[0, 0, 1, 0, 0], + [0, 1, 1, 1, 0], + [1, 1, 1, 1, 1], + [0, 1, 1, 1, 0], + [0, 0, 1, 0, 0]]) + >>> ndimage.iterate_structure(struct, 3).astype(int) + array([[0, 0, 0, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [1, 1, 1, 1, 1, 1, 1], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 0, 0, 0]]) + + """ + structure = np.asarray(structure) + if iterations < 2: + return structure.copy() + ni = iterations - 1 + shape = [ii + ni * (ii - 1) for ii in structure.shape] + pos = [ni * (structure.shape[ii] // 2) for ii in range(len(shape))] + slc = tuple(slice(pos[ii], pos[ii] + structure.shape[ii], None) + for ii in range(len(shape))) + out = np.zeros(shape, bool) + out[slc] = structure != 0 + out = binary_dilation(out, structure, iterations=ni) + if origin is None: + return out + else: + origin = _ni_support._normalize_sequence(origin, structure.ndim) + origin = [iterations * o for o in origin] + return out, origin + + +def generate_binary_structure(rank, connectivity): + """ + Generate a binary structure for binary morphological operations. + + Parameters + ---------- + rank : int + Number of dimensions of the array to which the structuring element + will be applied, as returned by `np.ndim`. + connectivity : int + `connectivity` determines which elements of the output array belong + to the structure, i.e., are considered as neighbors of the central + element. Elements up to a squared distance of `connectivity` from + the center are considered neighbors. `connectivity` may range from 1 + (no diagonal elements are neighbors) to `rank` (all elements are + neighbors). + + Returns + ------- + output : ndarray of bools + Structuring element which may be used for binary morphological + operations, with `rank` dimensions and all dimensions equal to 3. + + See Also + -------- + iterate_structure, binary_dilation, binary_erosion + + Notes + ----- + `generate_binary_structure` can only create structuring elements with + dimensions equal to 3, i.e., minimal dimensions. For larger structuring + elements, that are useful e.g., for eroding large objects, one may either + use `iterate_structure`, or create directly custom arrays with + numpy functions such as `numpy.ones`. + + Examples + -------- + >>> from scipy import ndimage + >>> import numpy as np + >>> struct = ndimage.generate_binary_structure(2, 1) + >>> struct + array([[False, True, False], + [ True, True, True], + [False, True, False]], dtype=bool) + >>> a = np.zeros((5,5)) + >>> a[2, 2] = 1 + >>> a + array([[ 0., 0., 0., 0., 0.], + [ 0., 0., 0., 0., 0.], + [ 0., 0., 1., 0., 0.], + [ 0., 0., 0., 0., 0.], + [ 0., 0., 0., 0., 0.]]) + >>> b = ndimage.binary_dilation(a, structure=struct).astype(a.dtype) + >>> b + array([[ 0., 0., 0., 0., 0.], + [ 0., 0., 1., 0., 0.], + [ 0., 1., 1., 1., 0.], + [ 0., 0., 1., 0., 0.], + [ 0., 0., 0., 0., 0.]]) + >>> ndimage.binary_dilation(b, structure=struct).astype(a.dtype) + array([[ 0., 0., 1., 0., 0.], + [ 0., 1., 1., 1., 0.], + [ 1., 1., 1., 1., 1.], + [ 0., 1., 1., 1., 0.], + [ 0., 0., 1., 0., 0.]]) + >>> struct = ndimage.generate_binary_structure(2, 2) + >>> struct + array([[ True, True, True], + [ True, True, True], + [ True, True, True]], dtype=bool) + >>> struct = ndimage.generate_binary_structure(3, 1) + >>> struct # no diagonal elements + array([[[False, False, False], + [False, True, False], + [False, False, False]], + [[False, True, False], + [ True, True, True], + [False, True, False]], + [[False, False, False], + [False, True, False], + [False, False, False]]], dtype=bool) + + """ + if connectivity < 1: + connectivity = 1 + if rank < 1: + return np.array(True, dtype=bool) + output = np.fabs(np.indices([3] * rank) - 1) + output = np.add.reduce(output, 0) + return output <= connectivity + + +def _binary_erosion(input, structure, iterations, mask, output, + border_value, origin, invert, brute_force, axes): + try: + iterations = operator.index(iterations) + except TypeError as e: + raise TypeError('iterations parameter should be an integer') from e + + input = np.asarray(input) + ndim = input.ndim + if np.iscomplexobj(input): + raise TypeError('Complex type not supported') + axes = _ni_support._check_axes(axes, input.ndim) + num_axes = len(axes) + if structure is None: + structure = generate_binary_structure(num_axes, 1) + else: + structure = np.asarray(structure, dtype=bool) + if ndim > num_axes: + structure = _filters._expand_footprint(ndim, axes, structure, + footprint_name="structure") + + if structure.ndim != input.ndim: + raise RuntimeError('structure and input must have same dimensionality') + if not structure.flags.contiguous: + structure = structure.copy() + if structure.size < 1: + raise RuntimeError('structure must not be empty') + if mask is not None: + mask = np.asarray(mask) + if mask.shape != input.shape: + raise RuntimeError('mask and input must have equal sizes') + origin = _ni_support._normalize_sequence(origin, num_axes) + origin = _filters._expand_origin(ndim, axes, origin) + cit = _center_is_true(structure, origin) + if isinstance(output, np.ndarray): + if np.iscomplexobj(output): + raise TypeError('Complex output type not supported') + else: + output = bool + output = _ni_support._get_output(output, input) + temp_needed = np.may_share_memory(input, output) + if temp_needed: + # input and output arrays cannot share memory + temp = output + output = _ni_support._get_output(output.dtype, input) + if iterations == 1: + _nd_image.binary_erosion(input, structure, mask, output, + border_value, origin, invert, cit, 0) + elif cit and not brute_force: + changed, coordinate_list = _nd_image.binary_erosion( + input, structure, mask, output, + border_value, origin, invert, cit, 1) + structure = structure[tuple([slice(None, None, -1)] * + structure.ndim)] + for ii in range(len(origin)): + origin[ii] = -origin[ii] + if not structure.shape[ii] & 1: + origin[ii] -= 1 + if mask is not None: + mask = np.asarray(mask, dtype=np.int8) + if not structure.flags.contiguous: + structure = structure.copy() + _nd_image.binary_erosion2(output, structure, mask, iterations - 1, + origin, invert, coordinate_list) + else: + tmp_in = np.empty_like(input, dtype=bool) + tmp_out = output + if iterations >= 1 and not iterations & 1: + tmp_in, tmp_out = tmp_out, tmp_in + changed = _nd_image.binary_erosion( + input, structure, mask, tmp_out, + border_value, origin, invert, cit, 0) + ii = 1 + while ii < iterations or (iterations < 1 and changed): + tmp_in, tmp_out = tmp_out, tmp_in + changed = _nd_image.binary_erosion( + tmp_in, structure, mask, tmp_out, + border_value, origin, invert, cit, 0) + ii += 1 + if temp_needed: + temp[...] = output + output = temp + return output + + +def binary_erosion(input, structure=None, iterations=1, mask=None, output=None, + border_value=0, origin=0, brute_force=False, *, axes=None): + """ + Multidimensional binary erosion with a given structuring element. + + Binary erosion is a mathematical morphology operation used for image + processing. + + Parameters + ---------- + input : array_like + Binary image to be eroded. Non-zero (True) elements form + the subset to be eroded. + structure : array_like, optional + Structuring element used for the erosion. Non-zero elements are + considered True. If no structuring element is provided, an element + is generated with a square connectivity equal to one. + iterations : int, optional + The erosion is repeated `iterations` times (one, by default). + If iterations is less than 1, the erosion is repeated until the + result does not change anymore. + mask : array_like, optional + If a mask is given, only those elements with a True value at + the corresponding mask element are modified at each iteration. + output : ndarray, optional + Array of the same shape as input, into which the output is placed. + By default, a new array is created. + border_value : int (cast to 0 or 1), optional + Value at the border in the output array. + origin : int or tuple of ints, optional + Placement of the filter, by default 0. + brute_force : boolean, optional + Memory condition: if False, only the pixels whose value was changed in + the last iteration are tracked as candidates to be updated (eroded) in + the current iteration; if True all pixels are considered as candidates + for erosion, regardless of what happened in the previous iteration. + False by default. + axes : tuple of int or None + The axes over which to apply the filter. If None, `input` is filtered + along all axes. If an `origin` tuple is provided, its length must match + the number of axes. + + Returns + ------- + binary_erosion : ndarray of bools + Erosion of the input by the structuring element. + + See Also + -------- + grey_erosion, binary_dilation, binary_closing, binary_opening, + generate_binary_structure + + Notes + ----- + Erosion [1]_ is a mathematical morphology operation [2]_ that uses a + structuring element for shrinking the shapes in an image. The binary + erosion of an image by a structuring element is the locus of the points + where a superimposition of the structuring element centered on the point + is entirely contained in the set of non-zero elements of the image. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Erosion_%28morphology%29 + .. [2] https://en.wikipedia.org/wiki/Mathematical_morphology + + Examples + -------- + >>> from scipy import ndimage + >>> import numpy as np + >>> a = np.zeros((7,7), dtype=int) + >>> a[1:6, 2:5] = 1 + >>> a + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> ndimage.binary_erosion(a).astype(a.dtype) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> #Erosion removes objects smaller than the structure + >>> ndimage.binary_erosion(a, structure=np.ones((5,5))).astype(a.dtype) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]]) + + """ + return _binary_erosion(input, structure, iterations, mask, + output, border_value, origin, 0, brute_force, axes) + + +def binary_dilation(input, structure=None, iterations=1, mask=None, + output=None, border_value=0, origin=0, + brute_force=False, *, axes=None): + """ + Multidimensional binary dilation with the given structuring element. + + Parameters + ---------- + input : array_like + Binary array_like to be dilated. Non-zero (True) elements form + the subset to be dilated. + structure : array_like, optional + Structuring element used for the dilation. Non-zero elements are + considered True. If no structuring element is provided an element + is generated with a square connectivity equal to one. + iterations : int, optional + The dilation is repeated `iterations` times (one, by default). + If iterations is less than 1, the dilation is repeated until the + result does not change anymore. Only an integer of iterations is + accepted. + mask : array_like, optional + If a mask is given, only those elements with a True value at + the corresponding mask element are modified at each iteration. + output : ndarray, optional + Array of the same shape as input, into which the output is placed. + By default, a new array is created. + border_value : int (cast to 0 or 1), optional + Value at the border in the output array. + origin : int or tuple of ints, optional + Placement of the filter, by default 0. + brute_force : boolean, optional + Memory condition: if False, only the pixels whose value was changed in + the last iteration are tracked as candidates to be updated (dilated) + in the current iteration; if True all pixels are considered as + candidates for dilation, regardless of what happened in the previous + iteration. False by default. + axes : tuple of int or None + The axes over which to apply the filter. If None, `input` is filtered + along all axes. If an `origin` tuple is provided, its length must match + the number of axes. + + Returns + ------- + binary_dilation : ndarray of bools + Dilation of the input by the structuring element. + + See Also + -------- + grey_dilation, binary_erosion, binary_closing, binary_opening, + generate_binary_structure + + Notes + ----- + Dilation [1]_ is a mathematical morphology operation [2]_ that uses a + structuring element for expanding the shapes in an image. The binary + dilation of an image by a structuring element is the locus of the points + covered by the structuring element, when its center lies within the + non-zero points of the image. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Dilation_%28morphology%29 + .. [2] https://en.wikipedia.org/wiki/Mathematical_morphology + + Examples + -------- + >>> from scipy import ndimage + >>> import numpy as np + >>> a = np.zeros((5, 5)) + >>> a[2, 2] = 1 + >>> a + array([[ 0., 0., 0., 0., 0.], + [ 0., 0., 0., 0., 0.], + [ 0., 0., 1., 0., 0.], + [ 0., 0., 0., 0., 0.], + [ 0., 0., 0., 0., 0.]]) + >>> ndimage.binary_dilation(a) + array([[False, False, False, False, False], + [False, False, True, False, False], + [False, True, True, True, False], + [False, False, True, False, False], + [False, False, False, False, False]], dtype=bool) + >>> ndimage.binary_dilation(a).astype(a.dtype) + array([[ 0., 0., 0., 0., 0.], + [ 0., 0., 1., 0., 0.], + [ 0., 1., 1., 1., 0.], + [ 0., 0., 1., 0., 0.], + [ 0., 0., 0., 0., 0.]]) + >>> # 3x3 structuring element with connectivity 1, used by default + >>> struct1 = ndimage.generate_binary_structure(2, 1) + >>> struct1 + array([[False, True, False], + [ True, True, True], + [False, True, False]], dtype=bool) + >>> # 3x3 structuring element with connectivity 2 + >>> struct2 = ndimage.generate_binary_structure(2, 2) + >>> struct2 + array([[ True, True, True], + [ True, True, True], + [ True, True, True]], dtype=bool) + >>> ndimage.binary_dilation(a, structure=struct1).astype(a.dtype) + array([[ 0., 0., 0., 0., 0.], + [ 0., 0., 1., 0., 0.], + [ 0., 1., 1., 1., 0.], + [ 0., 0., 1., 0., 0.], + [ 0., 0., 0., 0., 0.]]) + >>> ndimage.binary_dilation(a, structure=struct2).astype(a.dtype) + array([[ 0., 0., 0., 0., 0.], + [ 0., 1., 1., 1., 0.], + [ 0., 1., 1., 1., 0.], + [ 0., 1., 1., 1., 0.], + [ 0., 0., 0., 0., 0.]]) + >>> ndimage.binary_dilation(a, structure=struct1,\\ + ... iterations=2).astype(a.dtype) + array([[ 0., 0., 1., 0., 0.], + [ 0., 1., 1., 1., 0.], + [ 1., 1., 1., 1., 1.], + [ 0., 1., 1., 1., 0.], + [ 0., 0., 1., 0., 0.]]) + + """ + input = np.asarray(input) + axes = _ni_support._check_axes(axes, input.ndim) + num_axes = len(axes) + if structure is None: + structure = generate_binary_structure(num_axes, 1) + origin = _ni_support._normalize_sequence(origin, num_axes) + structure = np.asarray(structure) + structure = structure[tuple([slice(None, None, -1)] * + structure.ndim)] + for ii in range(len(origin)): + origin[ii] = -origin[ii] + if not structure.shape[ii] & 1: + origin[ii] -= 1 + + return _binary_erosion(input, structure, iterations, mask, + output, border_value, origin, 1, brute_force, axes) + + +def binary_opening(input, structure=None, iterations=1, output=None, + origin=0, mask=None, border_value=0, brute_force=False, *, + axes=None): + """ + Multidimensional binary opening with the given structuring element. + + The *opening* of an input image by a structuring element is the + *dilation* of the *erosion* of the image by the structuring element. + + Parameters + ---------- + input : array_like + Binary array_like to be opened. Non-zero (True) elements form + the subset to be opened. + structure : array_like, optional + Structuring element used for the opening. Non-zero elements are + considered True. If no structuring element is provided an element + is generated with a square connectivity equal to one (i.e., only + nearest neighbors are connected to the center, diagonally-connected + elements are not considered neighbors). + iterations : int, optional + The erosion step of the opening, then the dilation step are each + repeated `iterations` times (one, by default). If `iterations` is + less than 1, each operation is repeated until the result does + not change anymore. Only an integer of iterations is accepted. + output : ndarray, optional + Array of the same shape as input, into which the output is placed. + By default, a new array is created. + origin : int or tuple of ints, optional + Placement of the filter, by default 0. + mask : array_like, optional + If a mask is given, only those elements with a True value at + the corresponding mask element are modified at each iteration. + + .. versionadded:: 1.1.0 + border_value : int (cast to 0 or 1), optional + Value at the border in the output array. + + .. versionadded:: 1.1.0 + brute_force : boolean, optional + Memory condition: if False, only the pixels whose value was changed in + the last iteration are tracked as candidates to be updated in the + current iteration; if true all pixels are considered as candidates for + update, regardless of what happened in the previous iteration. + False by default. + + .. versionadded:: 1.1.0 + axes : tuple of int or None + The axes over which to apply the filter. If None, `input` is filtered + along all axes. If an `origin` tuple is provided, its length must match + the number of axes. + + Returns + ------- + binary_opening : ndarray of bools + Opening of the input by the structuring element. + + See Also + -------- + grey_opening, binary_closing, binary_erosion, binary_dilation, + generate_binary_structure + + Notes + ----- + *Opening* [1]_ is a mathematical morphology operation [2]_ that + consists in the succession of an erosion and a dilation of the + input with the same structuring element. Opening, therefore, removes + objects smaller than the structuring element. + + Together with *closing* (`binary_closing`), opening can be used for + noise removal. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Opening_%28morphology%29 + .. [2] https://en.wikipedia.org/wiki/Mathematical_morphology + + Examples + -------- + >>> from scipy import ndimage + >>> import numpy as np + >>> a = np.zeros((5,5), dtype=int) + >>> a[1:4, 1:4] = 1; a[4, 4] = 1 + >>> a + array([[0, 0, 0, 0, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 1]]) + >>> # Opening removes small objects + >>> ndimage.binary_opening(a, structure=np.ones((3,3))).astype(int) + array([[0, 0, 0, 0, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 0]]) + >>> # Opening can also smooth corners + >>> ndimage.binary_opening(a).astype(int) + array([[0, 0, 0, 0, 0], + [0, 0, 1, 0, 0], + [0, 1, 1, 1, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 0, 0]]) + >>> # Opening is the dilation of the erosion of the input + >>> ndimage.binary_erosion(a).astype(int) + array([[0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0]]) + >>> ndimage.binary_dilation(ndimage.binary_erosion(a)).astype(int) + array([[0, 0, 0, 0, 0], + [0, 0, 1, 0, 0], + [0, 1, 1, 1, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 0, 0]]) + + """ + input = np.asarray(input) + axes = _ni_support._check_axes(axes, input.ndim) + num_axes = len(axes) + if structure is None: + structure = generate_binary_structure(num_axes, 1) + + tmp = binary_erosion(input, structure, iterations, mask, None, + border_value, origin, brute_force, axes=axes) + return binary_dilation(tmp, structure, iterations, mask, output, + border_value, origin, brute_force, axes=axes) + + +def binary_closing(input, structure=None, iterations=1, output=None, + origin=0, mask=None, border_value=0, brute_force=False, *, + axes=None): + """ + Multidimensional binary closing with the given structuring element. + + The *closing* of an input image by a structuring element is the + *erosion* of the *dilation* of the image by the structuring element. + + Parameters + ---------- + input : array_like + Binary array_like to be closed. Non-zero (True) elements form + the subset to be closed. + structure : array_like, optional + Structuring element used for the closing. Non-zero elements are + considered True. If no structuring element is provided an element + is generated with a square connectivity equal to one (i.e., only + nearest neighbors are connected to the center, diagonally-connected + elements are not considered neighbors). + iterations : int, optional + The dilation step of the closing, then the erosion step are each + repeated `iterations` times (one, by default). If iterations is + less than 1, each operations is repeated until the result does + not change anymore. Only an integer of iterations is accepted. + output : ndarray, optional + Array of the same shape as input, into which the output is placed. + By default, a new array is created. + origin : int or tuple of ints, optional + Placement of the filter, by default 0. + mask : array_like, optional + If a mask is given, only those elements with a True value at + the corresponding mask element are modified at each iteration. + + .. versionadded:: 1.1.0 + border_value : int (cast to 0 or 1), optional + Value at the border in the output array. + + .. versionadded:: 1.1.0 + brute_force : boolean, optional + Memory condition: if False, only the pixels whose value was changed in + the last iteration are tracked as candidates to be updated in the + current iteration; if true al pixels are considered as candidates for + update, regardless of what happened in the previous iteration. + False by default. + + .. versionadded:: 1.1.0 + axes : tuple of int or None + The axes over which to apply the filter. If None, `input` is filtered + along all axes. If an `origin` tuple is provided, its length must match + the number of axes. + + Returns + ------- + binary_closing : ndarray of bools + Closing of the input by the structuring element. + + See Also + -------- + grey_closing, binary_opening, binary_dilation, binary_erosion, + generate_binary_structure + + Notes + ----- + *Closing* [1]_ is a mathematical morphology operation [2]_ that + consists in the succession of a dilation and an erosion of the + input with the same structuring element. Closing therefore fills + holes smaller than the structuring element. + + Together with *opening* (`binary_opening`), closing can be used for + noise removal. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Closing_%28morphology%29 + .. [2] https://en.wikipedia.org/wiki/Mathematical_morphology + + Examples + -------- + >>> from scipy import ndimage + >>> import numpy as np + >>> a = np.zeros((5,5), dtype=int) + >>> a[1:-1, 1:-1] = 1; a[2,2] = 0 + >>> a + array([[0, 0, 0, 0, 0], + [0, 1, 1, 1, 0], + [0, 1, 0, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 0]]) + >>> # Closing removes small holes + >>> ndimage.binary_closing(a).astype(int) + array([[0, 0, 0, 0, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 0]]) + >>> # Closing is the erosion of the dilation of the input + >>> ndimage.binary_dilation(a).astype(int) + array([[0, 1, 1, 1, 0], + [1, 1, 1, 1, 1], + [1, 1, 1, 1, 1], + [1, 1, 1, 1, 1], + [0, 1, 1, 1, 0]]) + >>> ndimage.binary_erosion(ndimage.binary_dilation(a)).astype(int) + array([[0, 0, 0, 0, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 0]]) + + + >>> a = np.zeros((7,7), dtype=int) + >>> a[1:6, 2:5] = 1; a[1:3,3] = 0 + >>> a + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 1, 0, 0], + [0, 0, 1, 0, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> # In addition to removing holes, closing can also + >>> # coarsen boundaries with fine hollows. + >>> ndimage.binary_closing(a).astype(int) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> ndimage.binary_closing(a, structure=np.ones((2,2))).astype(int) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0]]) + + """ + input = np.asarray(input) + axes = _ni_support._check_axes(axes, input.ndim) + num_axes = len(axes) + if structure is None: + structure = generate_binary_structure(num_axes, 1) + + tmp = binary_dilation(input, structure, iterations, mask, None, + border_value, origin, brute_force, axes=axes) + return binary_erosion(tmp, structure, iterations, mask, output, + border_value, origin, brute_force, axes=axes) + + +def binary_hit_or_miss(input, structure1=None, structure2=None, + output=None, origin1=0, origin2=None, *, axes=None): + """ + Multidimensional binary hit-or-miss transform. + + The hit-or-miss transform finds the locations of a given pattern + inside the input image. + + Parameters + ---------- + input : array_like (cast to booleans) + Binary image where a pattern is to be detected. + structure1 : array_like (cast to booleans), optional + Part of the structuring element to be fitted to the foreground + (non-zero elements) of `input`. If no value is provided, a + structure of square connectivity 1 is chosen. + structure2 : array_like (cast to booleans), optional + Second part of the structuring element that has to miss completely + the foreground. If no value is provided, the complementary of + `structure1` is taken. + output : ndarray, optional + Array of the same shape as input, into which the output is placed. + By default, a new array is created. + origin1 : int or tuple of ints, optional + Placement of the first part of the structuring element `structure1`, + by default 0 for a centered structure. + origin2 : int or tuple of ints, optional + Placement of the second part of the structuring element `structure2`, + by default 0 for a centered structure. If a value is provided for + `origin1` and not for `origin2`, then `origin2` is set to `origin1`. + axes : tuple of int or None + The axes over which to apply the filter. If None, `input` is filtered + along all axes. If `origin1` or `origin2` tuples are provided, their + length must match the number of axes. + + Returns + ------- + binary_hit_or_miss : ndarray + Hit-or-miss transform of `input` with the given structuring + element (`structure1`, `structure2`). + + See Also + -------- + binary_erosion + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Hit-or-miss_transform + + Examples + -------- + >>> from scipy import ndimage + >>> import numpy as np + >>> a = np.zeros((7,7), dtype=int) + >>> a[1, 1] = 1; a[2:4, 2:4] = 1; a[4:6, 4:6] = 1 + >>> a + array([[0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 1, 1, 0], + [0, 0, 0, 0, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> structure1 = np.array([[1, 0, 0], [0, 1, 1], [0, 1, 1]]) + >>> structure1 + array([[1, 0, 0], + [0, 1, 1], + [0, 1, 1]]) + >>> # Find the matches of structure1 in the array a + >>> ndimage.binary_hit_or_miss(a, structure1=structure1).astype(int) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> # Change the origin of the filter + >>> # origin1=1 is equivalent to origin1=(1,1) here + >>> ndimage.binary_hit_or_miss(a, structure1=structure1,\\ + ... origin1=1).astype(int) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0], + [0, 0, 0, 0, 0, 0, 0]]) + + """ + input = np.asarray(input) + axes = _ni_support._check_axes(axes, input.ndim) + num_axes = len(axes) + if structure1 is None: + structure1 = generate_binary_structure(num_axes, 1) + else: + structure1 = np.asarray(structure1) + if structure2 is None: + structure2 = np.logical_not(structure1) + origin1 = _ni_support._normalize_sequence(origin1, num_axes) + if origin2 is None: + origin2 = origin1 + else: + origin2 = _ni_support._normalize_sequence(origin2, num_axes) + + tmp1 = _binary_erosion(input, structure1, 1, None, None, 0, origin1, + 0, False, axes) + inplace = isinstance(output, np.ndarray) + result = _binary_erosion(input, structure2, 1, None, output, 0, + origin2, 1, False, axes) + if inplace: + np.logical_not(output, output) + np.logical_and(tmp1, output, output) + else: + np.logical_not(result, result) + return np.logical_and(tmp1, result) + + +def binary_propagation(input, structure=None, mask=None, + output=None, border_value=0, origin=0, *, axes=None): + """ + Multidimensional binary propagation with the given structuring element. + + Parameters + ---------- + input : array_like + Binary image to be propagated inside `mask`. + structure : array_like, optional + Structuring element used in the successive dilations. The output + may depend on the structuring element, especially if `mask` has + several connex components. If no structuring element is + provided, an element is generated with a squared connectivity equal + to one. + mask : array_like, optional + Binary mask defining the region into which `input` is allowed to + propagate. + output : ndarray, optional + Array of the same shape as input, into which the output is placed. + By default, a new array is created. + border_value : int (cast to 0 or 1), optional + Value at the border in the output array. + origin : int or tuple of ints, optional + Placement of the filter, by default 0. + axes : tuple of int or None + The axes over which to apply the filter. If None, `input` is filtered + along all axes. If an `origin` tuple is provided, its length must match + the number of axes. + + Returns + ------- + binary_propagation : ndarray + Binary propagation of `input` inside `mask`. + + Notes + ----- + This function is functionally equivalent to calling binary_dilation + with the number of iterations less than one: iterative dilation until + the result does not change anymore. + + The succession of an erosion and propagation inside the original image + can be used instead of an *opening* for deleting small objects while + keeping the contours of larger objects untouched. + + References + ---------- + .. [1] http://cmm.ensmp.fr/~serra/cours/pdf/en/ch6en.pdf, slide 15. + .. [2] I.T. Young, J.J. Gerbrands, and L.J. van Vliet, "Fundamentals of + image processing", 1998 + ftp://qiftp.tudelft.nl/DIPimage/docs/FIP2.3.pdf + + Examples + -------- + >>> from scipy import ndimage + >>> import numpy as np + >>> input = np.zeros((8, 8), dtype=int) + >>> input[2, 2] = 1 + >>> mask = np.zeros((8, 8), dtype=int) + >>> mask[1:4, 1:4] = mask[4, 4] = mask[6:8, 6:8] = 1 + >>> input + array([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]]) + >>> mask + array([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 1, 1], + [0, 0, 0, 0, 0, 0, 1, 1]]) + >>> ndimage.binary_propagation(input, mask=mask).astype(int) + array([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]]) + >>> ndimage.binary_propagation(input, mask=mask,\\ + ... structure=np.ones((3,3))).astype(int) + array([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]]) + + >>> # Comparison between opening and erosion+propagation + >>> a = np.zeros((6,6), dtype=int) + >>> a[2:5, 2:5] = 1; a[0, 0] = 1; a[5, 5] = 1 + >>> a + array([[1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 1]]) + >>> ndimage.binary_opening(a).astype(int) + array([[0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0], + [0, 0, 1, 1, 1, 0], + [0, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0]]) + >>> b = ndimage.binary_erosion(a) + >>> b.astype(int) + array([[0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0]]) + >>> ndimage.binary_propagation(b, mask=a).astype(int) + array([[0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0]]) + + """ + return binary_dilation(input, structure, -1, mask, output, + border_value, origin, axes=axes) + + +def binary_fill_holes(input, structure=None, output=None, origin=0, *, + axes=None): + """ + Fill the holes in binary objects. + + + Parameters + ---------- + input : array_like + N-D binary array with holes to be filled + structure : array_like, optional + Structuring element used in the computation; large-size elements + make computations faster but may miss holes separated from the + background by thin regions. The default element (with a square + connectivity equal to one) yields the intuitive result where all + holes in the input have been filled. + output : ndarray, optional + Array of the same shape as input, into which the output is placed. + By default, a new array is created. + origin : int, tuple of ints, optional + Position of the structuring element. + axes : tuple of int or None + The axes over which to apply the filter. If None, `input` is filtered + along all axes. If an `origin` tuple is provided, its length must match + the number of axes. + + Returns + ------- + out : ndarray + Transformation of the initial image `input` where holes have been + filled. + + See Also + -------- + binary_dilation, binary_propagation, label + + Notes + ----- + The algorithm used in this function consists in invading the complementary + of the shapes in `input` from the outer boundary of the image, + using binary dilations. Holes are not connected to the boundary and are + therefore not invaded. The result is the complementary subset of the + invaded region. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Mathematical_morphology + + + Examples + -------- + >>> from scipy import ndimage + >>> import numpy as np + >>> a = np.zeros((5, 5), dtype=int) + >>> a[1:4, 1:4] = 1 + >>> a[2,2] = 0 + >>> a + array([[0, 0, 0, 0, 0], + [0, 1, 1, 1, 0], + [0, 1, 0, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 0]]) + >>> ndimage.binary_fill_holes(a).astype(int) + array([[0, 0, 0, 0, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 0]]) + >>> # Too big structuring element + >>> ndimage.binary_fill_holes(a, structure=np.ones((5,5))).astype(int) + array([[0, 0, 0, 0, 0], + [0, 1, 1, 1, 0], + [0, 1, 0, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 0]]) + + """ + input = np.asarray(input) + mask = np.logical_not(input) + tmp = np.zeros(mask.shape, bool) + inplace = isinstance(output, np.ndarray) + if inplace: + binary_dilation(tmp, structure, -1, mask, output, 1, origin, axes=axes) + np.logical_not(output, output) + else: + output = binary_dilation(tmp, structure, -1, mask, None, 1, + origin, axes=axes) + np.logical_not(output, output) + return output + + +def grey_erosion(input, size=None, footprint=None, structure=None, + output=None, mode="reflect", cval=0.0, origin=0, *, + axes=None): + """ + Calculate a greyscale erosion, using either a structuring element, + or a footprint corresponding to a flat structuring element. + + Grayscale erosion is a mathematical morphology operation. For the + simple case of a full and flat structuring element, it can be viewed + as a minimum filter over a sliding window. + + Parameters + ---------- + input : array_like + Array over which the grayscale erosion is to be computed. + size : tuple of ints + Shape of a flat and full structuring element used for the grayscale + erosion. Optional if `footprint` or `structure` is provided. + footprint : array of ints, optional + Positions of non-infinite elements of a flat structuring element + used for the grayscale erosion. Non-zero values give the set of + neighbors of the center over which the minimum is chosen. + structure : array of ints, optional + Structuring element used for the grayscale erosion. `structure` + may be a non-flat structuring element. The `structure` array applies a + subtractive offset for each pixel in the neighborhood. + output : array, optional + An array used for storing the output of the erosion may be provided. + mode : {'reflect','constant','nearest','mirror', 'wrap'}, optional + The `mode` parameter determines how the array borders are + handled, where `cval` is the value when mode is equal to + 'constant'. Default is 'reflect' + cval : scalar, optional + Value to fill past edges of input if `mode` is 'constant'. Default + is 0.0. + origin : scalar, optional + The `origin` parameter controls the placement of the filter. + Default 0 + axes : tuple of int or None + The axes over which to apply the filter. If None, `input` is filtered + along all axes. If an `origin` tuple is provided, its length must match + the number of axes. + + Returns + ------- + output : ndarray + Grayscale erosion of `input`. + + See Also + -------- + binary_erosion, grey_dilation, grey_opening, grey_closing + generate_binary_structure, minimum_filter + + Notes + ----- + The grayscale erosion of an image input by a structuring element s defined + over a domain E is given by: + + (input+s)(x) = min {input(y) - s(x-y), for y in E} + + In particular, for structuring elements defined as + s(y) = 0 for y in E, the grayscale erosion computes the minimum of the + input image inside a sliding window defined by E. + + Grayscale erosion [1]_ is a *mathematical morphology* operation [2]_. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Erosion_%28morphology%29 + .. [2] https://en.wikipedia.org/wiki/Mathematical_morphology + + Examples + -------- + >>> from scipy import ndimage + >>> import numpy as np + >>> a = np.zeros((7,7), dtype=int) + >>> a[1:6, 1:6] = 3 + >>> a[4,4] = 2; a[2,3] = 1 + >>> a + array([[0, 0, 0, 0, 0, 0, 0], + [0, 3, 3, 3, 3, 3, 0], + [0, 3, 3, 1, 3, 3, 0], + [0, 3, 3, 3, 3, 3, 0], + [0, 3, 3, 3, 2, 3, 0], + [0, 3, 3, 3, 3, 3, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> ndimage.grey_erosion(a, size=(3,3)) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 3, 2, 2, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> footprint = ndimage.generate_binary_structure(2, 1) + >>> footprint + array([[False, True, False], + [ True, True, True], + [False, True, False]], dtype=bool) + >>> # Diagonally-connected elements are not considered neighbors + >>> ndimage.grey_erosion(a, footprint=footprint) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 3, 1, 2, 0, 0], + [0, 0, 3, 2, 2, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]]) + + """ + if size is None and footprint is None and structure is None: + raise ValueError("size, footprint, or structure must be specified") + + return _filters._min_or_max_filter(input, size, footprint, structure, + output, mode, cval, origin, 1, + axes=axes) + + +def grey_dilation(input, size=None, footprint=None, structure=None, + output=None, mode="reflect", cval=0.0, origin=0, *, + axes=None): + """ + Calculate a greyscale dilation, using either a structuring element, + or a footprint corresponding to a flat structuring element. + + Grayscale dilation is a mathematical morphology operation. For the + simple case of a full and flat structuring element, it can be viewed + as a maximum filter over a sliding window. + + Parameters + ---------- + input : array_like + Array over which the grayscale dilation is to be computed. + size : tuple of ints + Shape of a flat and full structuring element used for the grayscale + dilation. Optional if `footprint` or `structure` is provided. + footprint : array of ints, optional + Positions of non-infinite elements of a flat structuring element + used for the grayscale dilation. Non-zero values give the set of + neighbors of the center over which the maximum is chosen. + structure : array of ints, optional + Structuring element used for the grayscale dilation. `structure` + may be a non-flat structuring element. The `structure` array applies an + additive offset for each pixel in the neighborhood. + output : array, optional + An array used for storing the output of the dilation may be provided. + mode : {'reflect','constant','nearest','mirror', 'wrap'}, optional + The `mode` parameter determines how the array borders are + handled, where `cval` is the value when mode is equal to + 'constant'. Default is 'reflect' + cval : scalar, optional + Value to fill past edges of input if `mode` is 'constant'. Default + is 0.0. + origin : scalar, optional + The `origin` parameter controls the placement of the filter. + Default 0 + axes : tuple of int or None + The axes over which to apply the filter. If None, `input` is filtered + along all axes. If an `origin` tuple is provided, its length must match + the number of axes. + + Returns + ------- + grey_dilation : ndarray + Grayscale dilation of `input`. + + See Also + -------- + binary_dilation, grey_erosion, grey_closing, grey_opening + generate_binary_structure, maximum_filter + + Notes + ----- + The grayscale dilation of an image input by a structuring element s defined + over a domain E is given by: + + (input+s)(x) = max {input(y) + s(x-y), for y in E} + + In particular, for structuring elements defined as + s(y) = 0 for y in E, the grayscale dilation computes the maximum of the + input image inside a sliding window defined by E. + + Grayscale dilation [1]_ is a *mathematical morphology* operation [2]_. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Dilation_%28morphology%29 + .. [2] https://en.wikipedia.org/wiki/Mathematical_morphology + + Examples + -------- + >>> from scipy import ndimage + >>> import numpy as np + >>> a = np.zeros((7,7), dtype=int) + >>> a[2:5, 2:5] = 1 + >>> a[4,4] = 2; a[2,3] = 3 + >>> a + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 3, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 2, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> ndimage.grey_dilation(a, size=(3,3)) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 1, 3, 3, 3, 1, 0], + [0, 1, 3, 3, 3, 1, 0], + [0, 1, 3, 3, 3, 2, 0], + [0, 1, 1, 2, 2, 2, 0], + [0, 1, 1, 2, 2, 2, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> ndimage.grey_dilation(a, footprint=np.ones((3,3))) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 1, 3, 3, 3, 1, 0], + [0, 1, 3, 3, 3, 1, 0], + [0, 1, 3, 3, 3, 2, 0], + [0, 1, 1, 2, 2, 2, 0], + [0, 1, 1, 2, 2, 2, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> s = ndimage.generate_binary_structure(2,1) + >>> s + array([[False, True, False], + [ True, True, True], + [False, True, False]], dtype=bool) + >>> ndimage.grey_dilation(a, footprint=s) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 3, 1, 0, 0], + [0, 1, 3, 3, 3, 1, 0], + [0, 1, 1, 3, 2, 1, 0], + [0, 1, 1, 2, 2, 2, 0], + [0, 0, 1, 1, 2, 0, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> ndimage.grey_dilation(a, size=(3,3), structure=np.ones((3,3))) + array([[1, 1, 1, 1, 1, 1, 1], + [1, 2, 4, 4, 4, 2, 1], + [1, 2, 4, 4, 4, 2, 1], + [1, 2, 4, 4, 4, 3, 1], + [1, 2, 2, 3, 3, 3, 1], + [1, 2, 2, 3, 3, 3, 1], + [1, 1, 1, 1, 1, 1, 1]]) + + """ + if size is None and footprint is None and structure is None: + raise ValueError("size, footprint, or structure must be specified") + if structure is not None: + structure = np.asarray(structure) + structure = structure[tuple([slice(None, None, -1)] * + structure.ndim)] + if footprint is not None: + footprint = np.asarray(footprint) + footprint = footprint[tuple([slice(None, None, -1)] * + footprint.ndim)] + + input = np.asarray(input) + axes = _ni_support._check_axes(axes, input.ndim) + origin = _ni_support._normalize_sequence(origin, len(axes)) + for ii in range(len(origin)): + origin[ii] = -origin[ii] + if footprint is not None: + sz = footprint.shape[ii] + elif structure is not None: + sz = structure.shape[ii] + elif np.isscalar(size): + sz = size + else: + sz = size[ii] + if not sz & 1: + origin[ii] -= 1 + + return _filters._min_or_max_filter(input, size, footprint, structure, + output, mode, cval, origin, 0, + axes=axes) + + +def grey_opening(input, size=None, footprint=None, structure=None, + output=None, mode="reflect", cval=0.0, origin=0, *, + axes=None): + """ + Multidimensional grayscale opening. + + A grayscale opening consists in the succession of a grayscale erosion, + and a grayscale dilation. + + Parameters + ---------- + input : array_like + Array over which the grayscale opening is to be computed. + size : tuple of ints + Shape of a flat and full structuring element used for the grayscale + opening. Optional if `footprint` or `structure` is provided. + footprint : array of ints, optional + Positions of non-infinite elements of a flat structuring element + used for the grayscale opening. + structure : array of ints, optional + Structuring element used for the grayscale opening. `structure` + may be a non-flat structuring element. The `structure` array applies + offsets to the pixels in a neighborhood (the offset is additive during + dilation and subtractive during erosion). + output : array, optional + An array used for storing the output of the opening may be provided. + mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional + The `mode` parameter determines how the array borders are + handled, where `cval` is the value when mode is equal to + 'constant'. Default is 'reflect' + cval : scalar, optional + Value to fill past edges of input if `mode` is 'constant'. Default + is 0.0. + origin : scalar, optional + The `origin` parameter controls the placement of the filter. + Default 0 + axes : tuple of int or None + The axes over which to apply the filter. If None, `input` is filtered + along all axes. If an `origin` tuple is provided, its length must match + the number of axes. + + Returns + ------- + grey_opening : ndarray + Result of the grayscale opening of `input` with `structure`. + + See Also + -------- + binary_opening, grey_dilation, grey_erosion, grey_closing + generate_binary_structure + + Notes + ----- + The action of a grayscale opening with a flat structuring element amounts + to smoothen high local maxima, whereas binary opening erases small objects. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Mathematical_morphology + + Examples + -------- + >>> from scipy import ndimage + >>> import numpy as np + >>> a = np.arange(36).reshape((6,6)) + >>> a[3, 3] = 50 + >>> a + array([[ 0, 1, 2, 3, 4, 5], + [ 6, 7, 8, 9, 10, 11], + [12, 13, 14, 15, 16, 17], + [18, 19, 20, 50, 22, 23], + [24, 25, 26, 27, 28, 29], + [30, 31, 32, 33, 34, 35]]) + >>> ndimage.grey_opening(a, size=(3,3)) + array([[ 0, 1, 2, 3, 4, 4], + [ 6, 7, 8, 9, 10, 10], + [12, 13, 14, 15, 16, 16], + [18, 19, 20, 22, 22, 22], + [24, 25, 26, 27, 28, 28], + [24, 25, 26, 27, 28, 28]]) + >>> # Note that the local maximum a[3,3] has disappeared + + """ + if (size is not None) and (footprint is not None): + warnings.warn("ignoring size because footprint is set", + UserWarning, stacklevel=2) + tmp = grey_erosion(input, size, footprint, structure, None, mode, + cval, origin, axes=axes) + return grey_dilation(tmp, size, footprint, structure, output, mode, + cval, origin, axes=axes) + + +def grey_closing(input, size=None, footprint=None, structure=None, + output=None, mode="reflect", cval=0.0, origin=0, *, + axes=None): + """ + Multidimensional grayscale closing. + + A grayscale closing consists in the succession of a grayscale dilation, + and a grayscale erosion. + + Parameters + ---------- + input : array_like + Array over which the grayscale closing is to be computed. + size : tuple of ints + Shape of a flat and full structuring element used for the grayscale + closing. Optional if `footprint` or `structure` is provided. + footprint : array of ints, optional + Positions of non-infinite elements of a flat structuring element + used for the grayscale closing. + structure : array of ints, optional + Structuring element used for the grayscale closing. `structure` + may be a non-flat structuring element. The `structure` array applies + offsets to the pixels in a neighborhood (the offset is additive during + dilation and subtractive during erosion) + output : array, optional + An array used for storing the output of the closing may be provided. + mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional + The `mode` parameter determines how the array borders are + handled, where `cval` is the value when mode is equal to + 'constant'. Default is 'reflect' + cval : scalar, optional + Value to fill past edges of input if `mode` is 'constant'. Default + is 0.0. + origin : scalar, optional + The `origin` parameter controls the placement of the filter. + Default 0 + axes : tuple of int or None + The axes over which to apply the filter. If None, `input` is filtered + along all axes. If an `origin` tuple is provided, its length must match + the number of axes. + + Returns + ------- + grey_closing : ndarray + Result of the grayscale closing of `input` with `structure`. + + See Also + -------- + binary_closing, grey_dilation, grey_erosion, grey_opening, + generate_binary_structure + + Notes + ----- + The action of a grayscale closing with a flat structuring element amounts + to smoothen deep local minima, whereas binary closing fills small holes. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Mathematical_morphology + + Examples + -------- + >>> from scipy import ndimage + >>> import numpy as np + >>> a = np.arange(36).reshape((6,6)) + >>> a[3,3] = 0 + >>> a + array([[ 0, 1, 2, 3, 4, 5], + [ 6, 7, 8, 9, 10, 11], + [12, 13, 14, 15, 16, 17], + [18, 19, 20, 0, 22, 23], + [24, 25, 26, 27, 28, 29], + [30, 31, 32, 33, 34, 35]]) + >>> ndimage.grey_closing(a, size=(3,3)) + array([[ 7, 7, 8, 9, 10, 11], + [ 7, 7, 8, 9, 10, 11], + [13, 13, 14, 15, 16, 17], + [19, 19, 20, 20, 22, 23], + [25, 25, 26, 27, 28, 29], + [31, 31, 32, 33, 34, 35]]) + >>> # Note that the local minimum a[3,3] has disappeared + + """ + if (size is not None) and (footprint is not None): + warnings.warn("ignoring size because footprint is set", + UserWarning, stacklevel=2) + tmp = grey_dilation(input, size, footprint, structure, None, mode, + cval, origin, axes=axes) + return grey_erosion(tmp, size, footprint, structure, output, mode, + cval, origin, axes=axes) + + +def morphological_gradient(input, size=None, footprint=None, structure=None, + output=None, mode="reflect", cval=0.0, origin=0, *, + axes=None): + """ + Multidimensional morphological gradient. + + The morphological gradient is calculated as the difference between a + dilation and an erosion of the input with a given structuring element. + + Parameters + ---------- + input : array_like + Array over which to compute the morphlogical gradient. + size : tuple of ints + Shape of a flat and full structuring element used for the mathematical + morphology operations. Optional if `footprint` or `structure` is + provided. A larger `size` yields a more blurred gradient. + footprint : array of ints, optional + Positions of non-infinite elements of a flat structuring element + used for the morphology operations. Larger footprints + give a more blurred morphological gradient. + structure : array of ints, optional + Structuring element used for the morphology operations. `structure` may + be a non-flat structuring element. The `structure` array applies + offsets to the pixels in a neighborhood (the offset is additive during + dilation and subtractive during erosion) + output : array, optional + An array used for storing the output of the morphological gradient + may be provided. + mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional + The `mode` parameter determines how the array borders are + handled, where `cval` is the value when mode is equal to + 'constant'. Default is 'reflect' + cval : scalar, optional + Value to fill past edges of input if `mode` is 'constant'. Default + is 0.0. + origin : scalar, optional + The `origin` parameter controls the placement of the filter. + Default 0 + axes : tuple of int or None + The axes over which to apply the filter. If None, `input` is filtered + along all axes. If an `origin` tuple is provided, its length must match + the number of axes. + + Returns + ------- + morphological_gradient : ndarray + Morphological gradient of `input`. + + See Also + -------- + grey_dilation, grey_erosion, gaussian_gradient_magnitude + + Notes + ----- + For a flat structuring element, the morphological gradient + computed at a given point corresponds to the maximal difference + between elements of the input among the elements covered by the + structuring element centered on the point. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Mathematical_morphology + + Examples + -------- + >>> from scipy import ndimage + >>> import numpy as np + >>> a = np.zeros((7,7), dtype=int) + >>> a[2:5, 2:5] = 1 + >>> ndimage.morphological_gradient(a, size=(3,3)) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 0, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> # The morphological gradient is computed as the difference + >>> # between a dilation and an erosion + >>> ndimage.grey_dilation(a, size=(3,3)) -\\ + ... ndimage.grey_erosion(a, size=(3,3)) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 0, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> a = np.zeros((7,7), dtype=int) + >>> a[2:5, 2:5] = 1 + >>> a[4,4] = 2; a[2,3] = 3 + >>> a + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 3, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 2, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> ndimage.morphological_gradient(a, size=(3,3)) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 1, 3, 3, 3, 1, 0], + [0, 1, 3, 3, 3, 1, 0], + [0, 1, 3, 2, 3, 2, 0], + [0, 1, 1, 2, 2, 2, 0], + [0, 1, 1, 2, 2, 2, 0], + [0, 0, 0, 0, 0, 0, 0]]) + + """ + tmp = grey_dilation(input, size, footprint, structure, None, mode, + cval, origin, axes=axes) + if isinstance(output, np.ndarray): + grey_erosion(input, size, footprint, structure, output, mode, + cval, origin, axes=axes) + return np.subtract(tmp, output, output) + else: + return (tmp - grey_erosion(input, size, footprint, structure, + None, mode, cval, origin, axes=axes)) + + +def morphological_laplace(input, size=None, footprint=None, structure=None, + output=None, mode="reflect", cval=0.0, origin=0, *, + axes=None): + """ + Multidimensional morphological laplace. + + Parameters + ---------- + input : array_like + Input. + size : tuple of ints + Shape of a flat and full structuring element used for the mathematical + morphology operations. Optional if `footprint` or `structure` is + provided. + footprint : array of ints, optional + Positions of non-infinite elements of a flat structuring element + used for the morphology operations. + structure : array of ints, optional + Structuring element used for the morphology operations. `structure` may + be a non-flat structuring element. The `structure` array applies + offsets to the pixels in a neighborhood (the offset is additive during + dilation and subtractive during erosion) + output : ndarray, optional + An output array can optionally be provided. + mode : {'reflect','constant','nearest','mirror', 'wrap'}, optional + The mode parameter determines how the array borders are handled. + For 'constant' mode, values beyond borders are set to be `cval`. + Default is 'reflect'. + cval : scalar, optional + Value to fill past edges of input if mode is 'constant'. + Default is 0.0 + origin : origin, optional + The origin parameter controls the placement of the filter. + axes : tuple of int or None + The axes over which to apply the filter. If None, `input` is filtered + along all axes. If an `origin` tuple is provided, its length must match + the number of axes. + + Returns + ------- + morphological_laplace : ndarray + Output + + """ + tmp1 = grey_dilation(input, size, footprint, structure, None, mode, + cval, origin, axes=axes) + if isinstance(output, np.ndarray): + grey_erosion(input, size, footprint, structure, output, mode, + cval, origin, axes=axes) + np.add(tmp1, output, output) + np.subtract(output, input, output) + return np.subtract(output, input, output) + else: + tmp2 = grey_erosion(input, size, footprint, structure, None, mode, + cval, origin, axes=axes) + np.add(tmp1, tmp2, tmp2) + np.subtract(tmp2, input, tmp2) + np.subtract(tmp2, input, tmp2) + return tmp2 + + +def white_tophat(input, size=None, footprint=None, structure=None, + output=None, mode="reflect", cval=0.0, origin=0, *, + axes=None): + """ + Multidimensional white tophat filter. + + Parameters + ---------- + input : array_like + Input. + size : tuple of ints + Shape of a flat and full structuring element used for the filter. + Optional if `footprint` or `structure` is provided. + footprint : array of ints, optional + Positions of elements of a flat structuring element + used for the white tophat filter. + structure : array of ints, optional + Structuring element used for the filter. `structure` may be a non-flat + structuring element. The `structure` array applies offsets to the + pixels in a neighborhood (the offset is additive during dilation and + subtractive during erosion) + output : array, optional + An array used for storing the output of the filter may be provided. + mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional + The `mode` parameter determines how the array borders are + handled, where `cval` is the value when mode is equal to + 'constant'. Default is 'reflect' + cval : scalar, optional + Value to fill past edges of input if `mode` is 'constant'. + Default is 0.0. + origin : scalar, optional + The `origin` parameter controls the placement of the filter. + Default is 0. + axes : tuple of int or None + The axes over which to apply the filter. If None, `input` is filtered + along all axes. If an `origin` tuple is provided, its length must match + the number of axes. + + Returns + ------- + output : ndarray + Result of the filter of `input` with `structure`. + + See Also + -------- + black_tophat + + Examples + -------- + Subtract gray background from a bright peak. + + >>> from scipy.ndimage import generate_binary_structure, white_tophat + >>> import numpy as np + >>> square = generate_binary_structure(rank=2, connectivity=3) + >>> bright_on_gray = np.array([[2, 3, 3, 3, 2], + ... [3, 4, 5, 4, 3], + ... [3, 5, 9, 5, 3], + ... [3, 4, 5, 4, 3], + ... [2, 3, 3, 3, 2]]) + >>> white_tophat(input=bright_on_gray, structure=square) + array([[0, 0, 0, 0, 0], + [0, 0, 1, 0, 0], + [0, 1, 5, 1, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 0, 0]]) + + """ + input = np.asarray(input) + + if (size is not None) and (footprint is not None): + warnings.warn("ignoring size because footprint is set", + UserWarning, stacklevel=2) + tmp = grey_erosion(input, size, footprint, structure, None, mode, + cval, origin, axes=axes) + tmp = grey_dilation(tmp, size, footprint, structure, output, mode, + cval, origin, axes=axes) + if tmp is None: + tmp = output + + if input.dtype == np.bool_ and tmp.dtype == np.bool_: + np.bitwise_xor(input, tmp, out=tmp) + else: + np.subtract(input, tmp, out=tmp) + return tmp + + +def black_tophat(input, size=None, footprint=None, structure=None, output=None, + mode="reflect", cval=0.0, origin=0, *, axes=None): + """ + Multidimensional black tophat filter. + + Parameters + ---------- + input : array_like + Input. + size : tuple of ints, optional + Shape of a flat and full structuring element used for the filter. + Optional if `footprint` or `structure` is provided. + footprint : array of ints, optional + Positions of non-infinite elements of a flat structuring element + used for the black tophat filter. + structure : array of ints, optional + Structuring element used for the filter. `structure` may be a non-flat + structuring element. The `structure` array applies offsets to the + pixels in a neighborhood (the offset is additive during dilation and + subtractive during erosion) + output : array, optional + An array used for storing the output of the filter may be provided. + mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional + The `mode` parameter determines how the array borders are + handled, where `cval` is the value when mode is equal to + 'constant'. Default is 'reflect' + cval : scalar, optional + Value to fill past edges of input if `mode` is 'constant'. Default + is 0.0. + origin : scalar, optional + The `origin` parameter controls the placement of the filter. + Default 0 + axes : tuple of int or None + The axes over which to apply the filter. If None, `input` is filtered + along all axes. If an `origin` tuple is provided, its length must match + the number of axes. + + Returns + ------- + black_tophat : ndarray + Result of the filter of `input` with `structure`. + + See Also + -------- + white_tophat, grey_opening, grey_closing + + Examples + -------- + Change dark peak to bright peak and subtract background. + + >>> from scipy.ndimage import generate_binary_structure, black_tophat + >>> import numpy as np + >>> square = generate_binary_structure(rank=2, connectivity=3) + >>> dark_on_gray = np.array([[7, 6, 6, 6, 7], + ... [6, 5, 4, 5, 6], + ... [6, 4, 0, 4, 6], + ... [6, 5, 4, 5, 6], + ... [7, 6, 6, 6, 7]]) + >>> black_tophat(input=dark_on_gray, structure=square) + array([[0, 0, 0, 0, 0], + [0, 0, 1, 0, 0], + [0, 1, 5, 1, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 0, 0]]) + + """ + input = np.asarray(input) + + if (size is not None) and (footprint is not None): + warnings.warn("ignoring size because footprint is set", + UserWarning, stacklevel=2) + tmp = grey_dilation(input, size, footprint, structure, None, mode, + cval, origin, axes=axes) + tmp = grey_erosion(tmp, size, footprint, structure, output, mode, + cval, origin, axes=axes) + if tmp is None: + tmp = output + + if input.dtype == np.bool_ and tmp.dtype == np.bool_: + np.bitwise_xor(tmp, input, out=tmp) + else: + np.subtract(tmp, input, out=tmp) + return tmp + + +def distance_transform_bf(input, metric="euclidean", sampling=None, + return_distances=True, return_indices=False, + distances=None, indices=None): + """ + Distance transform function by a brute force algorithm. + + This function calculates the distance transform of the `input`, by + replacing each foreground (non-zero) element, with its + shortest distance to the background (any zero-valued element). + + In addition to the distance transform, the feature transform can + be calculated. In this case the index of the closest background + element to each foreground element is returned in a separate array. + + Parameters + ---------- + input : array_like + Input + metric : {'euclidean', 'taxicab', 'chessboard'}, optional + 'cityblock' and 'manhattan' are also valid, and map to 'taxicab'. + The default is 'euclidean'. + sampling : float, or sequence of float, optional + This parameter is only used when `metric` is 'euclidean'. + Spacing of elements along each dimension. If a sequence, must be of + length equal to the input rank; if a single number, this is used for + all axes. If not specified, a grid spacing of unity is implied. + return_distances : bool, optional + Whether to calculate the distance transform. + Default is True. + return_indices : bool, optional + Whether to calculate the feature transform. + Default is False. + distances : ndarray, optional + An output array to store the calculated distance transform, instead of + returning it. + `return_distances` must be True. + It must be the same shape as `input`, and of type float64 if `metric` + is 'euclidean', uint32 otherwise. + indices : int32 ndarray, optional + An output array to store the calculated feature transform, instead of + returning it. + `return_indicies` must be True. + Its shape must be ``(input.ndim,) + input.shape``. + + Returns + ------- + distances : ndarray, optional + The calculated distance transform. Returned only when + `return_distances` is True and `distances` is not supplied. + It will have the same shape as the input array. + indices : int32 ndarray, optional + The calculated feature transform. It has an input-shaped array for each + dimension of the input. See distance_transform_edt documentation for an + example. + Returned only when `return_indices` is True and `indices` is not + supplied. + + See Also + -------- + distance_transform_cdt : Faster distance transform for taxicab and + chessboard metrics + distance_transform_edt : Faster distance transform for euclidean metric + + Notes + ----- + This function employs a slow brute force algorithm. See also the + function `distance_transform_cdt` for more efficient taxicab [1]_ and + chessboard algorithms [2]_. + + References + ---------- + .. [1] Taxicab distance. Wikipedia, 2023. + https://en.wikipedia.org/wiki/Taxicab_geometry + .. [2] Chessboard distance. Wikipedia, 2023. + https://en.wikipedia.org/wiki/Chebyshev_distance + + Examples + -------- + Import the necessary modules. + + >>> import numpy as np + >>> from scipy.ndimage import distance_transform_bf + >>> import matplotlib.pyplot as plt + >>> from mpl_toolkits.axes_grid1 import ImageGrid + + First, we create a toy binary image. + + >>> def add_circle(center_x, center_y, radius, image, fillvalue=1): + ... # fill circular area with 1 + ... xx, yy = np.mgrid[:image.shape[0], :image.shape[1]] + ... circle = (xx - center_x) ** 2 + (yy - center_y) ** 2 + ... circle_shape = np.sqrt(circle) < radius + ... image[circle_shape] = fillvalue + ... return image + >>> image = np.zeros((100, 100), dtype=np.uint8) + >>> image[35:65, 20:80] = 1 + >>> image = add_circle(28, 65, 10, image) + >>> image = add_circle(37, 30, 10, image) + >>> image = add_circle(70, 45, 20, image) + >>> image = add_circle(45, 80, 10, image) + + Next, we set up the figure. + + >>> fig = plt.figure(figsize=(8, 8)) # set up the figure structure + >>> grid = ImageGrid(fig, 111, nrows_ncols=(2, 2), axes_pad=(0.4, 0.3), + ... label_mode="1", share_all=True, + ... cbar_location="right", cbar_mode="each", + ... cbar_size="7%", cbar_pad="2%") + >>> for ax in grid: + ... ax.axis('off') # remove axes from images + + The top left image is the original binary image. + + >>> binary_image = grid[0].imshow(image, cmap='gray') + >>> cbar_binary_image = grid.cbar_axes[0].colorbar(binary_image) + >>> cbar_binary_image.set_ticks([0, 1]) + >>> grid[0].set_title("Binary image: foreground in white") + + The distance transform calculates the distance between foreground pixels + and the image background according to a distance metric. Available metrics + in `distance_transform_bf` are: ``euclidean`` (default), ``taxicab`` + and ``chessboard``. The top right image contains the distance transform + based on the ``euclidean`` metric. + + >>> distance_transform_euclidean = distance_transform_bf(image) + >>> euclidean_transform = grid[1].imshow(distance_transform_euclidean, + ... cmap='gray') + >>> cbar_euclidean = grid.cbar_axes[1].colorbar(euclidean_transform) + >>> colorbar_ticks = [0, 10, 20] + >>> cbar_euclidean.set_ticks(colorbar_ticks) + >>> grid[1].set_title("Euclidean distance") + + The lower left image contains the distance transform using the ``taxicab`` + metric. + + >>> distance_transform_taxicab = distance_transform_bf(image, + ... metric='taxicab') + >>> taxicab_transformation = grid[2].imshow(distance_transform_taxicab, + ... cmap='gray') + >>> cbar_taxicab = grid.cbar_axes[2].colorbar(taxicab_transformation) + >>> cbar_taxicab.set_ticks(colorbar_ticks) + >>> grid[2].set_title("Taxicab distance") + + Finally, the lower right image contains the distance transform using the + ``chessboard`` metric. + + >>> distance_transform_cb = distance_transform_bf(image, + ... metric='chessboard') + >>> chessboard_transformation = grid[3].imshow(distance_transform_cb, + ... cmap='gray') + >>> cbar_taxicab = grid.cbar_axes[3].colorbar(chessboard_transformation) + >>> cbar_taxicab.set_ticks(colorbar_ticks) + >>> grid[3].set_title("Chessboard distance") + >>> plt.show() + + """ + ft_inplace = isinstance(indices, np.ndarray) + dt_inplace = isinstance(distances, np.ndarray) + _distance_tranform_arg_check( + dt_inplace, ft_inplace, return_distances, return_indices + ) + + tmp1 = np.asarray(input) != 0 + struct = generate_binary_structure(tmp1.ndim, tmp1.ndim) + tmp2 = binary_dilation(tmp1, struct) + tmp2 = np.logical_xor(tmp1, tmp2) + tmp1 = tmp1.astype(np.int8) - tmp2.astype(np.int8) + metric = metric.lower() + if metric == 'euclidean': + metric = 1 + elif metric in ['taxicab', 'cityblock', 'manhattan']: + metric = 2 + elif metric == 'chessboard': + metric = 3 + else: + raise RuntimeError('distance metric not supported') + if sampling is not None: + sampling = _ni_support._normalize_sequence(sampling, tmp1.ndim) + sampling = np.asarray(sampling, dtype=np.float64) + if not sampling.flags.contiguous: + sampling = sampling.copy() + if return_indices: + ft = np.zeros(tmp1.shape, dtype=np.int32) + else: + ft = None + if return_distances: + if distances is None: + if metric == 1: + dt = np.zeros(tmp1.shape, dtype=np.float64) + else: + dt = np.zeros(tmp1.shape, dtype=np.uint32) + else: + if distances.shape != tmp1.shape: + raise RuntimeError('distances array has wrong shape') + if metric == 1: + if distances.dtype.type != np.float64: + raise RuntimeError('distances array must be float64') + else: + if distances.dtype.type != np.uint32: + raise RuntimeError('distances array must be uint32') + dt = distances + else: + dt = None + + _nd_image.distance_transform_bf(tmp1, metric, sampling, dt, ft) + if return_indices: + if isinstance(indices, np.ndarray): + if indices.dtype.type != np.int32: + raise RuntimeError('indices array must be int32') + if indices.shape != (tmp1.ndim,) + tmp1.shape: + raise RuntimeError('indices array has wrong shape') + tmp2 = indices + else: + tmp2 = np.indices(tmp1.shape, dtype=np.int32) + ft = np.ravel(ft) + for ii in range(tmp2.shape[0]): + rtmp = np.ravel(tmp2[ii, ...])[ft] + rtmp.shape = tmp1.shape + tmp2[ii, ...] = rtmp + ft = tmp2 + + # construct and return the result + result = [] + if return_distances and not dt_inplace: + result.append(dt) + if return_indices and not ft_inplace: + result.append(ft) + + if len(result) == 2: + return tuple(result) + elif len(result) == 1: + return result[0] + else: + return None + + +def distance_transform_cdt(input, metric='chessboard', return_distances=True, + return_indices=False, distances=None, indices=None): + """ + Distance transform for chamfer type of transforms. + + This function calculates the distance transform of the `input`, by + replacing each foreground (non-zero) element, with its + shortest distance to the background (any zero-valued element). + + In addition to the distance transform, the feature transform can + be calculated. In this case the index of the closest background + element to each foreground element is returned in a separate array. + + Parameters + ---------- + input : array_like + Input. Values of 0 are treated as background. + metric : {'chessboard', 'taxicab'} or array_like, optional + The `metric` determines the type of chamfering that is done. If the + `metric` is equal to 'taxicab' a structure is generated using + `generate_binary_structure` with a squared distance equal to 1. If + the `metric` is equal to 'chessboard', a `metric` is generated + using `generate_binary_structure` with a squared distance equal to + the dimensionality of the array. These choices correspond to the + common interpretations of the 'taxicab' and the 'chessboard' + distance metrics in two dimensions. + A custom metric may be provided, in the form of a matrix where + each dimension has a length of three. + 'cityblock' and 'manhattan' are also valid, and map to 'taxicab'. + The default is 'chessboard'. + return_distances : bool, optional + Whether to calculate the distance transform. + Default is True. + return_indices : bool, optional + Whether to calculate the feature transform. + Default is False. + distances : int32 ndarray, optional + An output array to store the calculated distance transform, instead of + returning it. + `return_distances` must be True. + It must be the same shape as `input`. + indices : int32 ndarray, optional + An output array to store the calculated feature transform, instead of + returning it. + `return_indicies` must be True. + Its shape must be ``(input.ndim,) + input.shape``. + + Returns + ------- + distances : int32 ndarray, optional + The calculated distance transform. Returned only when + `return_distances` is True, and `distances` is not supplied. + It will have the same shape as the input array. + indices : int32 ndarray, optional + The calculated feature transform. It has an input-shaped array for each + dimension of the input. See distance_transform_edt documentation for an + example. + Returned only when `return_indices` is True, and `indices` is not + supplied. + + See Also + -------- + distance_transform_edt : Fast distance transform for euclidean metric + distance_transform_bf : Distance transform for different metrics using + a slower brute force algorithm + + Examples + -------- + Import the necessary modules. + + >>> import numpy as np + >>> from scipy.ndimage import distance_transform_cdt + >>> import matplotlib.pyplot as plt + >>> from mpl_toolkits.axes_grid1 import ImageGrid + + First, we create a toy binary image. + + >>> def add_circle(center_x, center_y, radius, image, fillvalue=1): + ... # fill circular area with 1 + ... xx, yy = np.mgrid[:image.shape[0], :image.shape[1]] + ... circle = (xx - center_x) ** 2 + (yy - center_y) ** 2 + ... circle_shape = np.sqrt(circle) < radius + ... image[circle_shape] = fillvalue + ... return image + >>> image = np.zeros((100, 100), dtype=np.uint8) + >>> image[35:65, 20:80] = 1 + >>> image = add_circle(28, 65, 10, image) + >>> image = add_circle(37, 30, 10, image) + >>> image = add_circle(70, 45, 20, image) + >>> image = add_circle(45, 80, 10, image) + + Next, we set up the figure. + + >>> fig = plt.figure(figsize=(5, 15)) + >>> grid = ImageGrid(fig, 111, nrows_ncols=(3, 1), axes_pad=(0.5, 0.3), + ... label_mode="1", share_all=True, + ... cbar_location="right", cbar_mode="each", + ... cbar_size="7%", cbar_pad="2%") + >>> for ax in grid: + ... ax.axis('off') + >>> top, middle, bottom = grid + >>> colorbar_ticks = [0, 10, 20] + + The top image contains the original binary image. + + >>> binary_image = top.imshow(image, cmap='gray') + >>> cbar_binary_image = top.cax.colorbar(binary_image) + >>> cbar_binary_image.set_ticks([0, 1]) + >>> top.set_title("Binary image: foreground in white") + + The middle image contains the distance transform using the ``taxicab`` + metric. + + >>> distance_taxicab = distance_transform_cdt(image, metric="taxicab") + >>> taxicab_transform = middle.imshow(distance_taxicab, cmap='gray') + >>> cbar_taxicab = middle.cax.colorbar(taxicab_transform) + >>> cbar_taxicab.set_ticks(colorbar_ticks) + >>> middle.set_title("Taxicab metric") + + The bottom image contains the distance transform using the ``chessboard`` + metric. + + >>> distance_chessboard = distance_transform_cdt(image, + ... metric="chessboard") + >>> chessboard_transform = bottom.imshow(distance_chessboard, cmap='gray') + >>> cbar_chessboard = bottom.cax.colorbar(chessboard_transform) + >>> cbar_chessboard.set_ticks(colorbar_ticks) + >>> bottom.set_title("Chessboard metric") + >>> plt.tight_layout() + >>> plt.show() + + """ + ft_inplace = isinstance(indices, np.ndarray) + dt_inplace = isinstance(distances, np.ndarray) + _distance_tranform_arg_check( + dt_inplace, ft_inplace, return_distances, return_indices + ) + input = np.asarray(input) + if isinstance(metric, str): + if metric in ['taxicab', 'cityblock', 'manhattan']: + rank = input.ndim + metric = generate_binary_structure(rank, 1) + elif metric == 'chessboard': + rank = input.ndim + metric = generate_binary_structure(rank, rank) + else: + raise ValueError('invalid metric provided') + else: + try: + metric = np.asarray(metric) + except Exception as e: + raise ValueError('invalid metric provided') from e + for s in metric.shape: + if s != 3: + raise ValueError('metric sizes must be equal to 3') + + if not metric.flags.contiguous: + metric = metric.copy() + if dt_inplace: + if distances.dtype.type != np.int32: + raise ValueError('distances must be of int32 type') + if distances.shape != input.shape: + raise ValueError('distances has wrong shape') + dt = distances + dt[...] = np.where(input, -1, 0).astype(np.int32) + else: + dt = np.where(input, -1, 0).astype(np.int32) + + rank = dt.ndim + if return_indices: + ft = np.arange(dt.size, dtype=np.int32) + ft.shape = dt.shape + else: + ft = None + + _nd_image.distance_transform_op(metric, dt, ft) + dt = dt[tuple([slice(None, None, -1)] * rank)] + if return_indices: + ft = ft[tuple([slice(None, None, -1)] * rank)] + _nd_image.distance_transform_op(metric, dt, ft) + dt = dt[tuple([slice(None, None, -1)] * rank)] + if return_indices: + ft = ft[tuple([slice(None, None, -1)] * rank)] + ft = np.ravel(ft) + if ft_inplace: + if indices.dtype.type != np.int32: + raise ValueError('indices array must be int32') + if indices.shape != (dt.ndim,) + dt.shape: + raise ValueError('indices array has wrong shape') + tmp = indices + else: + tmp = np.indices(dt.shape, dtype=np.int32) + for ii in range(tmp.shape[0]): + rtmp = np.ravel(tmp[ii, ...])[ft] + rtmp.shape = dt.shape + tmp[ii, ...] = rtmp + ft = tmp + + # construct and return the result + result = [] + if return_distances and not dt_inplace: + result.append(dt) + if return_indices and not ft_inplace: + result.append(ft) + + if len(result) == 2: + return tuple(result) + elif len(result) == 1: + return result[0] + else: + return None + + +def distance_transform_edt(input, sampling=None, return_distances=True, + return_indices=False, distances=None, indices=None): + """ + Exact Euclidean distance transform. + + This function calculates the distance transform of the `input`, by + replacing each foreground (non-zero) element, with its + shortest distance to the background (any zero-valued element). + + In addition to the distance transform, the feature transform can + be calculated. In this case the index of the closest background + element to each foreground element is returned in a separate array. + + Parameters + ---------- + input : array_like + Input data to transform. Can be any type but will be converted + into binary: 1 wherever input equates to True, 0 elsewhere. + sampling : float, or sequence of float, optional + Spacing of elements along each dimension. If a sequence, must be of + length equal to the input rank; if a single number, this is used for + all axes. If not specified, a grid spacing of unity is implied. + return_distances : bool, optional + Whether to calculate the distance transform. + Default is True. + return_indices : bool, optional + Whether to calculate the feature transform. + Default is False. + distances : float64 ndarray, optional + An output array to store the calculated distance transform, instead of + returning it. + `return_distances` must be True. + It must be the same shape as `input`. + indices : int32 ndarray, optional + An output array to store the calculated feature transform, instead of + returning it. + `return_indicies` must be True. + Its shape must be ``(input.ndim,) + input.shape``. + + Returns + ------- + distances : float64 ndarray, optional + The calculated distance transform. Returned only when + `return_distances` is True and `distances` is not supplied. + It will have the same shape as the input array. + indices : int32 ndarray, optional + The calculated feature transform. It has an input-shaped array for each + dimension of the input. See example below. + Returned only when `return_indices` is True and `indices` is not + supplied. + + Notes + ----- + The Euclidean distance transform gives values of the Euclidean + distance:: + + n + y_i = sqrt(sum (x[i]-b[i])**2) + i + + where b[i] is the background point (value 0) with the smallest + Euclidean distance to input points x[i], and n is the + number of dimensions. + + Examples + -------- + >>> from scipy import ndimage + >>> import numpy as np + >>> a = np.array(([0,1,1,1,1], + ... [0,0,1,1,1], + ... [0,1,1,1,1], + ... [0,1,1,1,0], + ... [0,1,1,0,0])) + >>> ndimage.distance_transform_edt(a) + array([[ 0. , 1. , 1.4142, 2.2361, 3. ], + [ 0. , 0. , 1. , 2. , 2. ], + [ 0. , 1. , 1.4142, 1.4142, 1. ], + [ 0. , 1. , 1.4142, 1. , 0. ], + [ 0. , 1. , 1. , 0. , 0. ]]) + + With a sampling of 2 units along x, 1 along y: + + >>> ndimage.distance_transform_edt(a, sampling=[2,1]) + array([[ 0. , 1. , 2. , 2.8284, 3.6056], + [ 0. , 0. , 1. , 2. , 3. ], + [ 0. , 1. , 2. , 2.2361, 2. ], + [ 0. , 1. , 2. , 1. , 0. ], + [ 0. , 1. , 1. , 0. , 0. ]]) + + Asking for indices as well: + + >>> edt, inds = ndimage.distance_transform_edt(a, return_indices=True) + >>> inds + array([[[0, 0, 1, 1, 3], + [1, 1, 1, 1, 3], + [2, 2, 1, 3, 3], + [3, 3, 4, 4, 3], + [4, 4, 4, 4, 4]], + [[0, 0, 1, 1, 4], + [0, 1, 1, 1, 4], + [0, 0, 1, 4, 4], + [0, 0, 3, 3, 4], + [0, 0, 3, 3, 4]]], dtype=int32) + + With arrays provided for inplace outputs: + + >>> indices = np.zeros(((np.ndim(a),) + a.shape), dtype=np.int32) + >>> ndimage.distance_transform_edt(a, return_indices=True, indices=indices) + array([[ 0. , 1. , 1.4142, 2.2361, 3. ], + [ 0. , 0. , 1. , 2. , 2. ], + [ 0. , 1. , 1.4142, 1.4142, 1. ], + [ 0. , 1. , 1.4142, 1. , 0. ], + [ 0. , 1. , 1. , 0. , 0. ]]) + >>> indices + array([[[0, 0, 1, 1, 3], + [1, 1, 1, 1, 3], + [2, 2, 1, 3, 3], + [3, 3, 4, 4, 3], + [4, 4, 4, 4, 4]], + [[0, 0, 1, 1, 4], + [0, 1, 1, 1, 4], + [0, 0, 1, 4, 4], + [0, 0, 3, 3, 4], + [0, 0, 3, 3, 4]]], dtype=int32) + + """ + ft_inplace = isinstance(indices, np.ndarray) + dt_inplace = isinstance(distances, np.ndarray) + _distance_tranform_arg_check( + dt_inplace, ft_inplace, return_distances, return_indices + ) + + # calculate the feature transform + input = np.atleast_1d(np.where(input, 1, 0).astype(np.int8)) + if sampling is not None: + sampling = _ni_support._normalize_sequence(sampling, input.ndim) + sampling = np.asarray(sampling, dtype=np.float64) + if not sampling.flags.contiguous: + sampling = sampling.copy() + + if ft_inplace: + ft = indices + if ft.shape != (input.ndim,) + input.shape: + raise RuntimeError('indices array has wrong shape') + if ft.dtype.type != np.int32: + raise RuntimeError('indices array must be int32') + else: + ft = np.zeros((input.ndim,) + input.shape, dtype=np.int32) + + _nd_image.euclidean_feature_transform(input, sampling, ft) + # if requested, calculate the distance transform + if return_distances: + dt = ft - np.indices(input.shape, dtype=ft.dtype) + dt = dt.astype(np.float64) + if sampling is not None: + for ii in range(len(sampling)): + dt[ii, ...] *= sampling[ii] + np.multiply(dt, dt, dt) + if dt_inplace: + dt = np.add.reduce(dt, axis=0) + if distances.shape != dt.shape: + raise RuntimeError('distances array has wrong shape') + if distances.dtype.type != np.float64: + raise RuntimeError('distances array must be float64') + np.sqrt(dt, distances) + else: + dt = np.add.reduce(dt, axis=0) + dt = np.sqrt(dt) + + # construct and return the result + result = [] + if return_distances and not dt_inplace: + result.append(dt) + if return_indices and not ft_inplace: + result.append(ft) + + if len(result) == 2: + return tuple(result) + elif len(result) == 1: + return result[0] + else: + return None + + +def _distance_tranform_arg_check(distances_out, indices_out, + return_distances, return_indices): + """Raise a RuntimeError if the arguments are invalid""" + error_msgs = [] + if (not return_distances) and (not return_indices): + error_msgs.append( + 'at least one of return_distances/return_indices must be True') + if distances_out and not return_distances: + error_msgs.append( + 'return_distances must be True if distances is supplied' + ) + if indices_out and not return_indices: + error_msgs.append('return_indices must be True if indices is supplied') + if error_msgs: + raise RuntimeError(', '.join(error_msgs)) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/_ndimage_api.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/_ndimage_api.py new file mode 100644 index 0000000000000000000000000000000000000000..1673391726a4070af4814d04be16e29e01d9f29b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/_ndimage_api.py @@ -0,0 +1,16 @@ +"""This is the 'bare' ndimage API. + +This --- private! --- module only collects implementations of public ndimage API +for _support_alternative_backends. +The latter --- also private! --- module adds delegation to CuPy etc and +re-exports decorated names to __init__.py +""" + +from ._filters import * # noqa: F403 +from ._fourier import * # noqa: F403 +from ._interpolation import * # noqa: F403 +from ._measurements import * # noqa: F403 +from ._morphology import * # noqa: F403 + +# '@' due to pytest bug, scipy/scipy#22236 +__all__ = [s for s in dir() if not s.startswith(('_', '@'))] diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/_ni_docstrings.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/_ni_docstrings.py new file mode 100644 index 0000000000000000000000000000000000000000..2c0d977500574b73f168296645fb36d10c1320de --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/_ni_docstrings.py @@ -0,0 +1,210 @@ +"""Docstring components common to several ndimage functions.""" +from typing import Final + +from scipy._lib import doccer + +__all__ = ['docfiller'] + + +_input_doc = ( +"""input : array_like + The input array.""") +_axis_doc = ( +"""axis : int, optional + The axis of `input` along which to calculate. Default is -1.""") +_output_doc = ( +"""output : array or dtype, optional + The array in which to place the output, or the dtype of the + returned array. By default an array of the same dtype as input + will be created.""") +_size_foot_doc = ( +"""size : scalar or tuple, optional + See footprint, below. Ignored if footprint is given. +footprint : array, optional + Either `size` or `footprint` must be defined. `size` gives + the shape that is taken from the input array, at every element + position, to define the input to the filter function. + `footprint` is a boolean array that specifies (implicitly) a + shape, but also which of the elements within this shape will get + passed to the filter function. Thus ``size=(n,m)`` is equivalent + to ``footprint=np.ones((n,m))``. We adjust `size` to the number + of dimensions of the input array, so that, if the input array is + shape (10,10,10), and `size` is 2, then the actual size used is + (2,2,2). When `footprint` is given, `size` is ignored.""") +_mode_reflect_doc = ( +"""mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional + The `mode` parameter determines how the input array is extended + beyond its boundaries. Default is 'reflect'. Behavior for each valid + value is as follows: + + 'reflect' (`d c b a | a b c d | d c b a`) + The input is extended by reflecting about the edge of the last + pixel. This mode is also sometimes referred to as half-sample + symmetric. + + 'constant' (`k k k k | a b c d | k k k k`) + The input is extended by filling all values beyond the edge with + the same constant value, defined by the `cval` parameter. + + 'nearest' (`a a a a | a b c d | d d d d`) + The input is extended by replicating the last pixel. + + 'mirror' (`d c b | a b c d | c b a`) + The input is extended by reflecting about the center of the last + pixel. This mode is also sometimes referred to as whole-sample + symmetric. + + 'wrap' (`a b c d | a b c d | a b c d`) + The input is extended by wrapping around to the opposite edge. + + For consistency with the interpolation functions, the following mode + names can also be used: + + 'grid-mirror' + This is a synonym for 'reflect'. + + 'grid-constant' + This is a synonym for 'constant'. + + 'grid-wrap' + This is a synonym for 'wrap'.""") + +_mode_interp_constant_doc = ( +"""mode : {'reflect', 'grid-mirror', 'constant', 'grid-constant', 'nearest', \ +'mirror', 'grid-wrap', 'wrap'}, optional + The `mode` parameter determines how the input array is extended + beyond its boundaries. Default is 'constant'. Behavior for each valid + value is as follows (see additional plots and details on + :ref:`boundary modes `): + + 'reflect' (`d c b a | a b c d | d c b a`) + The input is extended by reflecting about the edge of the last + pixel. This mode is also sometimes referred to as half-sample + symmetric. + + 'grid-mirror' + This is a synonym for 'reflect'. + + 'constant' (`k k k k | a b c d | k k k k`) + The input is extended by filling all values beyond the edge with + the same constant value, defined by the `cval` parameter. No + interpolation is performed beyond the edges of the input. + + 'grid-constant' (`k k k k | a b c d | k k k k`) + The input is extended by filling all values beyond the edge with + the same constant value, defined by the `cval` parameter. Interpolation + occurs for samples outside the input's extent as well. + + 'nearest' (`a a a a | a b c d | d d d d`) + The input is extended by replicating the last pixel. + + 'mirror' (`d c b | a b c d | c b a`) + The input is extended by reflecting about the center of the last + pixel. This mode is also sometimes referred to as whole-sample + symmetric. + + 'grid-wrap' (`a b c d | a b c d | a b c d`) + The input is extended by wrapping around to the opposite edge. + + 'wrap' (`d b c d | a b c d | b c a b`) + The input is extended by wrapping around to the opposite edge, but in a + way such that the last point and initial point exactly overlap. In this + case it is not well defined which sample will be chosen at the point of + overlap.""") +_mode_interp_mirror_doc = ( + _mode_interp_constant_doc.replace("Default is 'constant'", + "Default is 'mirror'") +) +assert _mode_interp_mirror_doc != _mode_interp_constant_doc, \ + 'Default not replaced' + +_mode_multiple_doc = ( +"""mode : str or sequence, optional + The `mode` parameter determines how the input array is extended + when the filter overlaps a border. By passing a sequence of modes + with length equal to the number of dimensions of the input array, + different modes can be specified along each axis. Default value is + 'reflect'. The valid values and their behavior is as follows: + + 'reflect' (`d c b a | a b c d | d c b a`) + The input is extended by reflecting about the edge of the last + pixel. This mode is also sometimes referred to as half-sample + symmetric. + + 'constant' (`k k k k | a b c d | k k k k`) + The input is extended by filling all values beyond the edge with + the same constant value, defined by the `cval` parameter. + + 'nearest' (`a a a a | a b c d | d d d d`) + The input is extended by replicating the last pixel. + + 'mirror' (`d c b | a b c d | c b a`) + The input is extended by reflecting about the center of the last + pixel. This mode is also sometimes referred to as whole-sample + symmetric. + + 'wrap' (`a b c d | a b c d | a b c d`) + The input is extended by wrapping around to the opposite edge. + + For consistency with the interpolation functions, the following mode + names can also be used: + + 'grid-constant' + This is a synonym for 'constant'. + + 'grid-mirror' + This is a synonym for 'reflect'. + + 'grid-wrap' + This is a synonym for 'wrap'.""") +_cval_doc = ( +"""cval : scalar, optional + Value to fill past edges of input if `mode` is 'constant'. Default + is 0.0.""") +_origin_doc = ( +"""origin : int, optional + Controls the placement of the filter on the input array's pixels. + A value of 0 (the default) centers the filter over the pixel, with + positive values shifting the filter to the left, and negative ones + to the right.""") +_origin_multiple_doc = ( +"""origin : int or sequence, optional + Controls the placement of the filter on the input array's pixels. + A value of 0 (the default) centers the filter over the pixel, with + positive values shifting the filter to the left, and negative ones + to the right. By passing a sequence of origins with length equal to + the number of dimensions of the input array, different shifts can + be specified along each axis.""") +_extra_arguments_doc = ( +"""extra_arguments : sequence, optional + Sequence of extra positional arguments to pass to passed function.""") +_extra_keywords_doc = ( +"""extra_keywords : dict, optional + dict of extra keyword arguments to pass to passed function.""") +_prefilter_doc = ( +"""prefilter : bool, optional + Determines if the input array is prefiltered with `spline_filter` + before interpolation. The default is True, which will create a + temporary `float64` array of filtered values if ``order > 1``. If + setting this to False, the output will be slightly blurred if + ``order > 1``, unless the input is prefiltered, i.e. it is the result + of calling `spline_filter` on the original input.""") + +docdict = { + 'input': _input_doc, + 'axis': _axis_doc, + 'output': _output_doc, + 'size_foot': _size_foot_doc, + 'mode_interp_constant': _mode_interp_constant_doc, + 'mode_interp_mirror': _mode_interp_mirror_doc, + 'mode_reflect': _mode_reflect_doc, + 'mode_multiple': _mode_multiple_doc, + 'cval': _cval_doc, + 'origin': _origin_doc, + 'origin_multiple': _origin_multiple_doc, + 'extra_arguments': _extra_arguments_doc, + 'extra_keywords': _extra_keywords_doc, + 'prefilter': _prefilter_doc + } + +docfiller: Final = doccer.filldoc(docdict) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/_ni_support.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/_ni_support.py new file mode 100644 index 0000000000000000000000000000000000000000..f8d41d00d9edf8d347c4ffc95598210489fed5e9 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/_ni_support.py @@ -0,0 +1,143 @@ +# Copyright (C) 2003-2005 Peter J. Verveer +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# 2. Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# 3. The name of the author may not be used to endorse or promote +# products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS +# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE +# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +from collections.abc import Iterable +import operator +import warnings +import numpy as np + + +def _extend_mode_to_code(mode, is_filter=False): + """Convert an extension mode to the corresponding integer code. + """ + if mode == 'nearest': + return 0 + elif mode == 'wrap': + return 1 + elif mode in ['reflect', 'grid-mirror']: + return 2 + elif mode == 'mirror': + return 3 + elif mode == 'constant': + return 4 + elif mode == 'grid-wrap' and is_filter: + return 1 + elif mode == 'grid-wrap': + return 5 + elif mode == 'grid-constant' and is_filter: + return 4 + elif mode == 'grid-constant': + return 6 + else: + raise RuntimeError('boundary mode not supported') + + +def _normalize_sequence(input, rank): + """If input is a scalar, create a sequence of length equal to the + rank by duplicating the input. If input is a sequence, + check if its length is equal to the length of array. + """ + is_str = isinstance(input, str) + if not is_str and np.iterable(input): + normalized = list(input) + if len(normalized) != rank: + err = "sequence argument must have length equal to input rank" + raise RuntimeError(err) + else: + normalized = [input] * rank + return normalized + + +def _get_output(output, input, shape=None, complex_output=False): + if shape is None: + shape = input.shape + if output is None: + if not complex_output: + output = np.zeros(shape, dtype=input.dtype.name) + else: + complex_type = np.promote_types(input.dtype, np.complex64) + output = np.zeros(shape, dtype=complex_type) + elif isinstance(output, (type, np.dtype)): + # Classes (like `np.float32`) and dtypes are interpreted as dtype + if complex_output and np.dtype(output).kind != 'c': + warnings.warn("promoting specified output dtype to complex", stacklevel=3) + output = np.promote_types(output, np.complex64) + output = np.zeros(shape, dtype=output) + elif isinstance(output, str): + output = np.dtype(output) + if complex_output and output.kind != 'c': + raise RuntimeError("output must have complex dtype") + elif not issubclass(output.type, np.number): + raise RuntimeError("output must have numeric dtype") + output = np.zeros(shape, dtype=output) + else: + # output was supplied as an array + output = np.asarray(output) + if output.shape != shape: + raise RuntimeError("output shape not correct") + elif complex_output and output.dtype.kind != 'c': + raise RuntimeError("output must have complex dtype") + return output + + +def _check_axes(axes, ndim): + if axes is None: + return tuple(range(ndim)) + elif np.isscalar(axes): + axes = (operator.index(axes),) + elif isinstance(axes, Iterable): + for ax in axes: + axes = tuple(operator.index(ax) for ax in axes) + if ax < -ndim or ax > ndim - 1: + raise ValueError(f"specified axis: {ax} is out of range") + axes = tuple(ax % ndim if ax < 0 else ax for ax in axes) + else: + message = "axes must be an integer, iterable of integers, or None" + raise ValueError(message) + if len(tuple(set(axes))) != len(axes): + raise ValueError("axes must be unique") + return axes + +def _skip_if_dtype(arg): + """'array or dtype' polymorphism. + + Return None for np.int8, dtype('float32') or 'f' etc + arg for np.empty(3) etc + """ + if isinstance(arg, str): + return None + if type(arg) is type: + return None if issubclass(arg, np.generic) else arg + else: + return None if isinstance(arg, np.dtype) else arg + + +def _skip_if_int(arg): + return None if (arg is None or isinstance(arg, int)) else arg diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/_rank_filter_1d.cpython-310-x86_64-linux-gnu.so b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/_rank_filter_1d.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..6d998aa648b493336d9871117e687e8f8d5279aa Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/_rank_filter_1d.cpython-310-x86_64-linux-gnu.so differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/_support_alternative_backends.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/_support_alternative_backends.py new file mode 100644 index 0000000000000000000000000000000000000000..fbb913b14c76873202fce8eaabe2d08f778abe94 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/_support_alternative_backends.py @@ -0,0 +1,72 @@ +import functools +from scipy._lib._array_api import ( + is_cupy, is_jax, scipy_namespace_for, SCIPY_ARRAY_API +) + +import numpy as np +from ._ndimage_api import * # noqa: F403 +from . import _ndimage_api +from . import _delegators +__all__ = _ndimage_api.__all__ + + +MODULE_NAME = 'ndimage' + + +def delegate_xp(delegator, module_name): + def inner(func): + @functools.wraps(func) + def wrapper(*args, **kwds): + xp = delegator(*args, **kwds) + + # try delegating to a cupyx/jax namesake + if is_cupy(xp): + # https://github.com/cupy/cupy/issues/8336 + import importlib + cupyx_module = importlib.import_module(f"cupyx.scipy.{module_name}") + cupyx_func = getattr(cupyx_module, func.__name__) + return cupyx_func(*args, **kwds) + elif is_jax(xp) and func.__name__ == "map_coordinates": + spx = scipy_namespace_for(xp) + jax_module = getattr(spx, module_name) + jax_func = getattr(jax_module, func.__name__) + return jax_func(*args, **kwds) + else: + # the original function (does all np.asarray internally) + # XXX: output arrays + result = func(*args, **kwds) + + if isinstance(result, (np.ndarray, np.generic)): + # XXX: np.int32->np.array_0D + return xp.asarray(result) + elif isinstance(result, int): + return result + elif isinstance(result, dict): + # value_indices: result is {np.int64(1): (array(0), array(1))} etc + return { + k.item(): tuple(xp.asarray(vv) for vv in v) + for k,v in result.items() + } + elif result is None: + # inplace operations + return result + else: + # lists/tuples + return type(result)( + xp.asarray(x) if isinstance(x, np.ndarray) else x + for x in result + ) + return wrapper + return inner + +# ### decorate ### +for func_name in _ndimage_api.__all__: + bare_func = getattr(_ndimage_api, func_name) + delegator = getattr(_delegators, func_name + "_signature") + + f = (delegate_xp(delegator, MODULE_NAME)(bare_func) + if SCIPY_ARRAY_API + else bare_func) + + # add the decorated function to the namespace, to be imported in __init__.py + vars()[func_name] = f diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/filters.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/filters.py new file mode 100644 index 0000000000000000000000000000000000000000..e16d9d279a9585b2454c46ee09cf22143de833a6 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/filters.py @@ -0,0 +1,27 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.ndimage` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'correlate1d', 'convolve1d', 'gaussian_filter1d', + 'gaussian_filter', 'prewitt', 'sobel', 'generic_laplace', + 'laplace', 'gaussian_laplace', 'generic_gradient_magnitude', + 'gaussian_gradient_magnitude', 'correlate', 'convolve', + 'uniform_filter1d', 'uniform_filter', 'minimum_filter1d', + 'maximum_filter1d', 'minimum_filter', 'maximum_filter', + 'rank_filter', 'median_filter', 'percentile_filter', + 'generic_filter1d', 'generic_filter' +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package='ndimage', module='filters', + private_modules=['_filters'], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/fourier.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/fourier.py new file mode 100644 index 0000000000000000000000000000000000000000..73c49bd52d9a446ce0fe25d9e15b8de68fbd46fb --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/fourier.py @@ -0,0 +1,21 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.ndimage` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'fourier_gaussian', 'fourier_uniform', + 'fourier_ellipsoid', 'fourier_shift' +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package='ndimage', module='fourier', + private_modules=['_fourier'], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/interpolation.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/interpolation.py new file mode 100644 index 0000000000000000000000000000000000000000..a2739c60c51037487ae8892c407e2f3d7870d5da --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/interpolation.py @@ -0,0 +1,22 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.ndimage` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'spline_filter1d', 'spline_filter', + 'geometric_transform', 'map_coordinates', + 'affine_transform', 'shift', 'zoom', 'rotate', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package='ndimage', module='interpolation', + private_modules=['_interpolation'], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/measurements.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/measurements.py new file mode 100644 index 0000000000000000000000000000000000000000..22f76b01840ffb829205bd1d28a7ad1f9ac5db61 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/measurements.py @@ -0,0 +1,24 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.ndimage` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'label', 'find_objects', 'labeled_comprehension', + 'sum', 'mean', 'variance', 'standard_deviation', + 'minimum', 'maximum', 'median', 'minimum_position', + 'maximum_position', 'extrema', 'center_of_mass', + 'histogram', 'watershed_ift', 'sum_labels' +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package='ndimage', module='measurements', + private_modules=['_measurements'], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/morphology.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/morphology.py new file mode 100644 index 0000000000000000000000000000000000000000..e522e7df3a4b06b7e04ed8c2d0ecaff2a98b951d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/morphology.py @@ -0,0 +1,27 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.ndimage` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'iterate_structure', 'generate_binary_structure', + 'binary_erosion', 'binary_dilation', 'binary_opening', + 'binary_closing', 'binary_hit_or_miss', 'binary_propagation', + 'binary_fill_holes', 'grey_erosion', 'grey_dilation', + 'grey_opening', 'grey_closing', 'morphological_gradient', + 'morphological_laplace', 'white_tophat', 'black_tophat', + 'distance_transform_bf', 'distance_transform_cdt', + 'distance_transform_edt' +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package='ndimage', module='morphology', + private_modules=['_morphology'], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/tests/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8d8fd292b537a84fe48d0c8ae8bee75bab2b3353 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/tests/__init__.py @@ -0,0 +1,12 @@ +import numpy as np + +# list of numarray data types +integer_types: list[str] = [ + "int8", "uint8", "int16", "uint16", + "int32", "uint32", "int64", "uint64"] + +float_types: list[str] = ["float32", "float64"] + +complex_types: list[str] = ["complex64", "complex128"] + +types: list[str] = integer_types + float_types diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/tests/data/label_inputs.txt b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/tests/data/label_inputs.txt new file mode 100644 index 0000000000000000000000000000000000000000..6c3cff3b12cec4ad050b31cc5d5c327f32784447 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/tests/data/label_inputs.txt @@ -0,0 +1,21 @@ +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 0 1 1 1 +1 1 0 0 0 1 1 +1 0 1 0 1 0 1 +0 0 0 1 0 0 0 +1 0 1 0 1 0 1 +1 1 0 0 0 1 1 +1 1 1 0 1 1 1 +1 0 1 1 1 0 1 +0 0 0 1 0 0 0 +1 0 0 1 0 0 1 +1 1 1 1 1 1 1 +1 0 0 1 0 0 1 +0 0 0 1 0 0 0 +1 0 1 1 1 0 1 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/tests/data/label_results.txt b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/tests/data/label_results.txt new file mode 100644 index 0000000000000000000000000000000000000000..c239b0369c9df3e06df9a2fbf048faec2f84941f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/tests/data/label_results.txt @@ -0,0 +1,294 @@ +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +2 2 2 2 2 2 2 +3 3 3 3 3 3 3 +4 4 4 4 4 4 4 +5 5 5 5 5 5 5 +6 6 6 6 6 6 6 +7 7 7 7 7 7 7 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 2 3 4 5 6 7 +8 9 10 11 12 13 14 +15 16 17 18 19 20 21 +22 23 24 25 26 27 28 +29 30 31 32 33 34 35 +36 37 38 39 40 41 42 +43 44 45 46 47 48 49 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 2 3 4 5 6 7 +8 1 2 3 4 5 6 +9 8 1 2 3 4 5 +10 9 8 1 2 3 4 +11 10 9 8 1 2 3 +12 11 10 9 8 1 2 +13 12 11 10 9 8 1 +1 2 3 4 5 6 7 +1 2 3 4 5 6 7 +1 2 3 4 5 6 7 +1 2 3 4 5 6 7 +1 2 3 4 5 6 7 +1 2 3 4 5 6 7 +1 2 3 4 5 6 7 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 2 1 2 1 2 1 +2 1 2 1 2 1 2 +1 2 1 2 1 2 1 +2 1 2 1 2 1 2 +1 2 1 2 1 2 1 +2 1 2 1 2 1 2 +1 2 1 2 1 2 1 +1 2 3 4 5 6 7 +2 3 4 5 6 7 8 +3 4 5 6 7 8 9 +4 5 6 7 8 9 10 +5 6 7 8 9 10 11 +6 7 8 9 10 11 12 +7 8 9 10 11 12 13 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 1 1 1 1 +1 1 1 0 2 2 2 +1 1 0 0 0 2 2 +1 0 3 0 2 0 4 +0 0 0 2 0 0 0 +5 0 2 0 6 0 7 +2 2 0 0 0 7 7 +2 2 2 0 7 7 7 +1 1 1 0 2 2 2 +1 1 0 0 0 2 2 +3 0 1 0 4 0 2 +0 0 0 1 0 0 0 +5 0 6 0 1 0 7 +5 5 0 0 0 1 1 +5 5 5 0 1 1 1 +1 1 1 0 2 2 2 +3 3 0 0 0 4 4 +5 0 6 0 7 0 8 +0 0 0 9 0 0 0 +10 0 11 0 12 0 13 +14 14 0 0 0 15 15 +16 16 16 0 17 17 17 +1 1 1 0 2 3 3 +1 1 0 0 0 3 3 +1 0 4 0 3 0 3 +0 0 0 3 0 0 0 +3 0 3 0 5 0 6 +3 3 0 0 0 6 6 +3 3 7 0 6 6 6 +1 2 3 0 4 5 6 +7 8 0 0 0 9 10 +11 0 12 0 13 0 14 +0 0 0 15 0 0 0 +16 0 17 0 18 0 19 +20 21 0 0 0 22 23 +24 25 26 0 27 28 29 +1 1 1 0 2 2 2 +1 1 0 0 0 2 2 +1 0 3 0 2 0 2 +0 0 0 2 0 0 0 +2 0 2 0 4 0 5 +2 2 0 0 0 5 5 +2 2 2 0 5 5 5 +1 1 1 0 2 2 2 +1 1 0 0 0 2 2 +1 0 3 0 4 0 2 +0 0 0 5 0 0 0 +6 0 7 0 8 0 9 +6 6 0 0 0 9 9 +6 6 6 0 9 9 9 +1 2 3 0 4 5 6 +7 1 0 0 0 4 5 +8 0 1 0 9 0 4 +0 0 0 1 0 0 0 +10 0 11 0 1 0 12 +13 10 0 0 0 1 14 +15 13 10 0 16 17 1 +1 2 3 0 4 5 6 +1 2 0 0 0 5 6 +1 0 7 0 8 0 6 +0 0 0 9 0 0 0 +10 0 11 0 12 0 13 +10 14 0 0 0 15 13 +10 14 16 0 17 15 13 +1 1 1 0 1 1 1 +1 1 0 0 0 1 1 +1 0 1 0 1 0 1 +0 0 0 1 0 0 0 +1 0 1 0 1 0 1 +1 1 0 0 0 1 1 +1 1 1 0 1 1 1 +1 1 2 0 3 3 3 +1 1 0 0 0 3 3 +1 0 1 0 4 0 3 +0 0 0 1 0 0 0 +5 0 6 0 1 0 1 +5 5 0 0 0 1 1 +5 5 5 0 7 1 1 +1 2 1 0 1 3 1 +2 1 0 0 0 1 3 +1 0 1 0 1 0 1 +0 0 0 1 0 0 0 +1 0 1 0 1 0 1 +4 1 0 0 0 1 5 +1 4 1 0 1 5 1 +1 2 3 0 4 5 6 +2 3 0 0 0 6 7 +3 0 8 0 6 0 9 +0 0 0 6 0 0 0 +10 0 6 0 11 0 12 +13 6 0 0 0 12 14 +6 15 16 0 12 14 17 +1 1 1 0 2 2 2 +1 1 0 0 0 2 2 +1 0 1 0 3 0 2 +0 0 0 1 0 0 0 +4 0 5 0 1 0 1 +4 4 0 0 0 1 1 +4 4 4 0 1 1 1 +1 0 2 2 2 0 3 +0 0 0 2 0 0 0 +4 0 0 5 0 0 5 +5 5 5 5 5 5 5 +5 0 0 5 0 0 6 +0 0 0 7 0 0 0 +8 0 7 7 7 0 9 +1 0 2 2 2 0 3 +0 0 0 2 0 0 0 +4 0 0 4 0 0 5 +4 4 4 4 4 4 4 +6 0 0 4 0 0 4 +0 0 0 7 0 0 0 +8 0 7 7 7 0 9 +1 0 2 2 2 0 3 +0 0 0 4 0 0 0 +5 0 0 6 0 0 7 +8 8 8 8 8 8 8 +9 0 0 10 0 0 11 +0 0 0 12 0 0 0 +13 0 14 14 14 0 15 +1 0 2 3 3 0 4 +0 0 0 3 0 0 0 +5 0 0 3 0 0 6 +5 5 3 3 3 6 6 +5 0 0 3 0 0 6 +0 0 0 3 0 0 0 +7 0 3 3 8 0 9 +1 0 2 3 4 0 5 +0 0 0 6 0 0 0 +7 0 0 8 0 0 9 +10 11 12 13 14 15 16 +17 0 0 18 0 0 19 +0 0 0 20 0 0 0 +21 0 22 23 24 0 25 +1 0 2 2 2 0 3 +0 0 0 2 0 0 0 +2 0 0 2 0 0 2 +2 2 2 2 2 2 2 +2 0 0 2 0 0 2 +0 0 0 2 0 0 0 +4 0 2 2 2 0 5 +1 0 2 2 2 0 3 +0 0 0 2 0 0 0 +2 0 0 2 0 0 2 +2 2 2 2 2 2 2 +2 0 0 2 0 0 2 +0 0 0 2 0 0 0 +4 0 2 2 2 0 5 +1 0 2 3 4 0 5 +0 0 0 2 0 0 0 +6 0 0 7 0 0 8 +9 6 10 11 7 12 13 +14 0 0 10 0 0 12 +0 0 0 15 0 0 0 +16 0 17 18 15 0 19 +1 0 2 3 4 0 5 +0 0 0 3 0 0 0 +6 0 0 3 0 0 7 +6 8 9 3 10 11 7 +6 0 0 3 0 0 7 +0 0 0 3 0 0 0 +12 0 13 3 14 0 15 +1 0 2 2 2 0 3 +0 0 0 2 0 0 0 +2 0 0 2 0 0 2 +2 2 2 2 2 2 2 +2 0 0 2 0 0 2 +0 0 0 2 0 0 0 +4 0 2 2 2 0 5 +1 0 2 2 3 0 4 +0 0 0 2 0 0 0 +5 0 0 2 0 0 6 +5 5 2 2 2 6 6 +5 0 0 2 0 0 6 +0 0 0 2 0 0 0 +7 0 8 2 2 0 9 +1 0 2 3 2 0 4 +0 0 0 2 0 0 0 +5 0 0 6 0 0 7 +8 5 6 9 6 7 10 +5 0 0 6 0 0 7 +0 0 0 11 0 0 0 +12 0 11 13 11 0 14 +1 0 2 3 4 0 5 +0 0 0 4 0 0 0 +6 0 0 7 0 0 8 +9 10 7 11 12 8 13 +10 0 0 12 0 0 14 +0 0 0 15 0 0 0 +16 0 15 17 18 0 19 +1 0 2 2 2 0 3 +0 0 0 2 0 0 0 +2 0 0 2 0 0 2 +2 2 2 2 2 2 2 +2 0 0 2 0 0 2 +0 0 0 2 0 0 0 +4 0 2 2 2 0 5 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/tests/data/label_strels.txt b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/tests/data/label_strels.txt new file mode 100644 index 0000000000000000000000000000000000000000..35ae8121364d4fb3292c11f2a72333f456fa9c0a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/tests/data/label_strels.txt @@ -0,0 +1,42 @@ +0 0 1 +1 1 1 +1 0 0 +1 0 0 +1 1 1 +0 0 1 +0 0 0 +1 1 1 +0 0 0 +0 1 1 +0 1 0 +1 1 0 +0 0 0 +0 0 0 +0 0 0 +0 1 1 +1 1 1 +1 1 0 +0 1 0 +1 1 1 +0 1 0 +1 0 0 +0 1 0 +0 0 1 +0 1 0 +0 1 0 +0 1 0 +1 1 1 +1 1 1 +1 1 1 +1 1 0 +0 1 0 +0 1 1 +1 0 1 +0 1 0 +1 0 1 +0 0 1 +0 1 0 +1 0 0 +1 1 0 +1 1 1 +0 1 1 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/tests/test_c_api.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/tests/test_c_api.py new file mode 100644 index 0000000000000000000000000000000000000000..61a5a0f70262ef9f21fe8593a64f155bd583cab1 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/tests/test_c_api.py @@ -0,0 +1,102 @@ +import numpy as np +from scipy._lib._array_api import xp_assert_close + +from scipy import ndimage +from scipy.ndimage import _ctest +from scipy.ndimage import _cytest +from scipy._lib._ccallback import LowLevelCallable + +FILTER1D_FUNCTIONS = [ + lambda filter_size: _ctest.filter1d(filter_size), + lambda filter_size: _cytest.filter1d(filter_size, with_signature=False), + lambda filter_size: LowLevelCallable( + _cytest.filter1d(filter_size, with_signature=True) + ), + lambda filter_size: LowLevelCallable.from_cython( + _cytest, "_filter1d", + _cytest.filter1d_capsule(filter_size), + ), +] + +FILTER2D_FUNCTIONS = [ + lambda weights: _ctest.filter2d(weights), + lambda weights: _cytest.filter2d(weights, with_signature=False), + lambda weights: LowLevelCallable(_cytest.filter2d(weights, with_signature=True)), + lambda weights: LowLevelCallable.from_cython(_cytest, + "_filter2d", + _cytest.filter2d_capsule(weights),), +] + +TRANSFORM_FUNCTIONS = [ + lambda shift: _ctest.transform(shift), + lambda shift: _cytest.transform(shift, with_signature=False), + lambda shift: LowLevelCallable(_cytest.transform(shift, with_signature=True)), + lambda shift: LowLevelCallable.from_cython(_cytest, + "_transform", + _cytest.transform_capsule(shift),), +] + + +def test_generic_filter(): + def filter2d(footprint_elements, weights): + return (weights*footprint_elements).sum() + + def check(j): + func = FILTER2D_FUNCTIONS[j] + + im = np.ones((20, 20)) + im[:10,:10] = 0 + footprint = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) + footprint_size = np.count_nonzero(footprint) + weights = np.ones(footprint_size)/footprint_size + + res = ndimage.generic_filter(im, func(weights), + footprint=footprint) + std = ndimage.generic_filter(im, filter2d, footprint=footprint, + extra_arguments=(weights,)) + xp_assert_close(res, std, err_msg=f"#{j} failed") + + for j, func in enumerate(FILTER2D_FUNCTIONS): + check(j) + + +def test_generic_filter1d(): + def filter1d(input_line, output_line, filter_size): + for i in range(output_line.size): + output_line[i] = 0 + for j in range(filter_size): + output_line[i] += input_line[i+j] + output_line /= filter_size + + def check(j): + func = FILTER1D_FUNCTIONS[j] + + im = np.tile(np.hstack((np.zeros(10), np.ones(10))), (10, 1)) + filter_size = 3 + + res = ndimage.generic_filter1d(im, func(filter_size), + filter_size) + std = ndimage.generic_filter1d(im, filter1d, filter_size, + extra_arguments=(filter_size,)) + xp_assert_close(res, std, err_msg=f"#{j} failed") + + for j, func in enumerate(FILTER1D_FUNCTIONS): + check(j) + + +def test_geometric_transform(): + def transform(output_coordinates, shift): + return output_coordinates[0] - shift, output_coordinates[1] - shift + + def check(j): + func = TRANSFORM_FUNCTIONS[j] + + im = np.arange(12).reshape(4, 3).astype(np.float64) + shift = 0.5 + + res = ndimage.geometric_transform(im, func(shift)) + std = ndimage.geometric_transform(im, transform, extra_arguments=(shift,)) + xp_assert_close(res, std, err_msg=f"#{j} failed") + + for j, func in enumerate(TRANSFORM_FUNCTIONS): + check(j) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/tests/test_datatypes.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/tests/test_datatypes.py new file mode 100644 index 0000000000000000000000000000000000000000..a82de456bb92c96d5b9a599d4b33c987e134fdc8 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/tests/test_datatypes.py @@ -0,0 +1,67 @@ +""" Testing data types for ndimage calls +""" +import numpy as np + +from scipy._lib._array_api import assert_array_almost_equal +import pytest + +from scipy import ndimage + + +def test_map_coordinates_dts(): + # check that ndimage accepts different data types for interpolation + data = np.array([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + shifted_data = np.array([[0, 0, 0, 0], + [0, 4, 1, 3], + [0, 7, 6, 8]]) + idx = np.indices(data.shape) + dts = (np.uint8, np.uint16, np.uint32, np.uint64, + np.int8, np.int16, np.int32, np.int64, + np.intp, np.uintp, np.float32, np.float64) + for order in range(0, 6): + for data_dt in dts: + these_data = data.astype(data_dt) + for coord_dt in dts: + # affine mapping + mat = np.eye(2, dtype=coord_dt) + off = np.zeros((2,), dtype=coord_dt) + out = ndimage.affine_transform(these_data, mat, off) + assert_array_almost_equal(these_data, out) + # map coordinates + coords_m1 = idx.astype(coord_dt) - 1 + coords_p10 = idx.astype(coord_dt) + 10 + out = ndimage.map_coordinates(these_data, coords_m1, order=order) + assert_array_almost_equal(out, shifted_data) + # check constant fill works + out = ndimage.map_coordinates(these_data, coords_p10, order=order) + assert_array_almost_equal(out, np.zeros((3,4))) + # check shift and zoom + out = ndimage.shift(these_data, 1) + assert_array_almost_equal(out, shifted_data) + out = ndimage.zoom(these_data, 1) + assert_array_almost_equal(these_data, out) + + +@pytest.mark.xfail(True, reason="Broken on many platforms") +def test_uint64_max(): + # Test interpolation respects uint64 max. Reported to fail at least on + # win32 (due to the 32 bit visual C compiler using signed int64 when + # converting between uint64 to double) and Debian on s390x. + # Interpolation is always done in double precision floating point, so + # we use the largest uint64 value for which int(float(big)) still fits + # in a uint64. + # This test was last enabled on macOS only, and there it started failing + # on arm64 as well (see gh-19117). + big = 2**64 - 1025 + arr = np.array([big, big, big], dtype=np.uint64) + # Tests geometric transform (map_coordinates, affine_transform) + inds = np.indices(arr.shape) - 0.1 + x = ndimage.map_coordinates(arr, inds) + assert x[1] == int(float(big)) + assert x[2] == int(float(big)) + # Tests zoom / shift + x = ndimage.shift(arr, 0.1) + assert x[1] == int(float(big)) + assert x[2] == int(float(big)) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/tests/test_filters.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/tests/test_filters.py new file mode 100644 index 0000000000000000000000000000000000000000..1d5cb39f566827f41037e34a5a63ce874996c36f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/tests/test_filters.py @@ -0,0 +1,2920 @@ +''' Some tests for filters ''' +import functools +import itertools +import re + +import numpy as np +import pytest +from numpy.testing import suppress_warnings, assert_allclose, assert_array_equal +from hypothesis import strategies as st +from hypothesis import given +import hypothesis.extra.numpy as npst +from pytest import raises as assert_raises +from scipy import ndimage +from scipy._lib._array_api import ( + assert_almost_equal, + assert_array_almost_equal, + xp_assert_close, + xp_assert_equal, +) +from scipy._lib._array_api import is_cupy, is_numpy, is_torch, array_namespace +from scipy.conftest import array_api_compatible +from scipy.ndimage._filters import _gaussian_kernel1d + +from . import types, float_types, complex_types + + +skip_xp_backends = pytest.mark.skip_xp_backends +xfail_xp_backends = pytest.mark.xfail_xp_backends +pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends"), + pytest.mark.usefixtures("xfail_xp_backends"), + skip_xp_backends(cpu_only=True, exceptions=['cupy', 'jax.numpy']),] + + +def sumsq(a, b, xp=None): + xp = array_namespace(a, b) if xp is None else xp + return xp.sqrt(xp.sum((a - b)**2)) + + +def _complex_correlate(xp, array, kernel, real_dtype, convolve=False, + mode="reflect", cval=0, ): + """Utility to perform a reference complex-valued convolutions. + + When convolve==False, correlation is performed instead + """ + array = xp.asarray(array) + kernel = xp.asarray(kernel) + isdtype = array_namespace(array, kernel).isdtype + complex_array = isdtype(array.dtype, 'complex floating') + complex_kernel = isdtype(kernel.dtype, 'complex floating') + if array.ndim == 1: + func = ndimage.convolve1d if convolve else ndimage.correlate1d + else: + func = ndimage.convolve if convolve else ndimage.correlate + if not convolve: + kernel = xp.conj(kernel) + if complex_array and complex_kernel: + # use: real(cval) for array.real component + # imag(cval) for array.imag component + re_cval = cval.real if isinstance(cval, complex) else xp.real(cval) + im_cval = cval.imag if isinstance(cval, complex) else xp.imag(cval) + + output = ( + func(xp.real(array), xp.real(kernel), output=real_dtype, + mode=mode, cval=re_cval) - + func(xp.imag(array), xp.imag(kernel), output=real_dtype, + mode=mode, cval=im_cval) + + 1j * func(xp.imag(array), xp.real(kernel), output=real_dtype, + mode=mode, cval=im_cval) + + 1j * func(xp.real(array), xp.imag(kernel), output=real_dtype, + mode=mode, cval=re_cval) + ) + elif complex_array: + re_cval = xp.real(cval) + re_cval = re_cval.item() if isinstance(re_cval, xp.ndarray) else re_cval + im_cval = xp.imag(cval) + im_cval = im_cval.item() if isinstance(im_cval, xp.ndarray) else im_cval + + output = ( + func(xp.real(array), kernel, output=real_dtype, mode=mode, + cval=re_cval) + + 1j * func(xp.imag(array), kernel, output=real_dtype, mode=mode, + cval=im_cval) + ) + elif complex_kernel: + # real array so cval is real too + output = ( + func(array, xp.real(kernel), output=real_dtype, mode=mode, cval=cval) + + 1j * func(array, xp.imag(kernel), output=real_dtype, mode=mode, + cval=cval) + ) + return output + + +def _cases_axes_tuple_length_mismatch(): + # Generate combinations of filter function, valid kwargs, and + # keyword-value pairs for which the value will become with mismatched + # (invalid) size + filter_func = ndimage.gaussian_filter + kwargs = dict(radius=3, mode='constant', sigma=1.0, order=0) + for key, val in kwargs.items(): + yield filter_func, kwargs, key, val + + filter_funcs = [ndimage.uniform_filter, ndimage.minimum_filter, + ndimage.maximum_filter] + kwargs = dict(size=3, mode='constant', origin=0) + for filter_func in filter_funcs: + for key, val in kwargs.items(): + yield filter_func, kwargs, key, val + + filter_funcs = [ndimage.correlate, ndimage.convolve] + # sequence of mode not supported for correlate or convolve + kwargs = dict(origin=0) + for filter_func in filter_funcs: + for key, val in kwargs.items(): + yield filter_func, kwargs, key, val + + +class TestNdimageFilters: + + def _validate_complex(self, xp, array, kernel, type2, mode='reflect', + cval=0, check_warnings=True): + # utility for validating complex-valued correlations + real_dtype = xp.real(xp.asarray([], dtype=type2)).dtype + expected = _complex_correlate( + xp, array, kernel, real_dtype, convolve=False, mode=mode, cval=cval + ) + + if array.ndim == 1: + correlate = functools.partial(ndimage.correlate1d, axis=-1, + mode=mode, cval=cval) + convolve = functools.partial(ndimage.convolve1d, axis=-1, + mode=mode, cval=cval) + else: + correlate = functools.partial(ndimage.correlate, mode=mode, + cval=cval) + convolve = functools.partial(ndimage.convolve, mode=mode, + cval=cval) + + # test correlate output dtype + output = correlate(array, kernel, output=type2) + assert_array_almost_equal(expected, output) + assert output.dtype.type == type2 + + # test correlate with pre-allocated output + output = xp.zeros_like(array, dtype=type2) + correlate(array, kernel, output=output) + assert_array_almost_equal(expected, output) + + # test convolve output dtype + output = convolve(array, kernel, output=type2) + expected = _complex_correlate( + xp, array, kernel, real_dtype, convolve=True, mode=mode, cval=cval, + ) + assert_array_almost_equal(expected, output) + assert output.dtype.type == type2 + + # convolve with pre-allocated output + convolve(array, kernel, output=output) + assert_array_almost_equal(expected, output) + assert output.dtype.type == type2 + + if check_warnings: + # warns if the output is not a complex dtype + with pytest.warns(UserWarning, + match="promoting specified output dtype to " + "complex"): + correlate(array, kernel, output=real_dtype) + + with pytest.warns(UserWarning, + match="promoting specified output dtype to " + "complex"): + convolve(array, kernel, output=real_dtype) + + # raises if output array is provided, but is not complex-valued + output_real = xp.zeros_like(array, dtype=real_dtype) + with assert_raises(RuntimeError): + correlate(array, kernel, output=output_real) + + with assert_raises(RuntimeError): + convolve(array, kernel, output=output_real) + + def test_correlate01(self, xp): + array = xp.asarray([1, 2]) + weights = xp.asarray([2]) + expected = xp.asarray([2, 4]) + + output = ndimage.correlate(array, weights) + assert_array_almost_equal(output, expected) + + output = ndimage.convolve(array, weights) + assert_array_almost_equal(output, expected) + + output = ndimage.correlate1d(array, weights) + assert_array_almost_equal(output, expected) + + output = ndimage.convolve1d(array, weights) + assert_array_almost_equal(output, expected) + + @xfail_xp_backends('cupy', reason="Differs by a factor of two?") + @skip_xp_backends("jax.numpy", reason="output array is read-only.") + def test_correlate01_overlap(self, xp): + array = xp.reshape(xp.arange(256), (16, 16)) + weights = xp.asarray([2]) + expected = 2 * array + + ndimage.correlate1d(array, weights, output=array) + assert_array_almost_equal(array, expected) + + def test_correlate02(self, xp): + array = xp.asarray([1, 2, 3]) + kernel = xp.asarray([1]) + + output = ndimage.correlate(array, kernel) + assert_array_almost_equal(array, output) + + output = ndimage.convolve(array, kernel) + assert_array_almost_equal(array, output) + + output = ndimage.correlate1d(array, kernel) + assert_array_almost_equal(array, output) + + output = ndimage.convolve1d(array, kernel) + assert_array_almost_equal(array, output) + + def test_correlate03(self, xp): + array = xp.asarray([1]) + weights = xp.asarray([1, 1]) + expected = xp.asarray([2]) + + output = ndimage.correlate(array, weights) + assert_array_almost_equal(output, expected) + + output = ndimage.convolve(array, weights) + assert_array_almost_equal(output, expected) + + output = ndimage.correlate1d(array, weights) + assert_array_almost_equal(output, expected) + + output = ndimage.convolve1d(array, weights) + assert_array_almost_equal(output, expected) + + def test_correlate04(self, xp): + array = xp.asarray([1, 2]) + tcor = xp.asarray([2, 3]) + tcov = xp.asarray([3, 4]) + weights = xp.asarray([1, 1]) + output = ndimage.correlate(array, weights) + assert_array_almost_equal(output, tcor) + output = ndimage.convolve(array, weights) + assert_array_almost_equal(output, tcov) + output = ndimage.correlate1d(array, weights) + assert_array_almost_equal(output, tcor) + output = ndimage.convolve1d(array, weights) + assert_array_almost_equal(output, tcov) + + def test_correlate05(self, xp): + array = xp.asarray([1, 2, 3]) + tcor = xp.asarray([2, 3, 5]) + tcov = xp.asarray([3, 5, 6]) + kernel = xp.asarray([1, 1]) + output = ndimage.correlate(array, kernel) + assert_array_almost_equal(tcor, output) + output = ndimage.convolve(array, kernel) + assert_array_almost_equal(tcov, output) + output = ndimage.correlate1d(array, kernel) + assert_array_almost_equal(tcor, output) + output = ndimage.convolve1d(array, kernel) + assert_array_almost_equal(tcov, output) + + def test_correlate06(self, xp): + array = xp.asarray([1, 2, 3]) + tcor = xp.asarray([9, 14, 17]) + tcov = xp.asarray([7, 10, 15]) + weights = xp.asarray([1, 2, 3]) + output = ndimage.correlate(array, weights) + assert_array_almost_equal(output, tcor) + output = ndimage.convolve(array, weights) + assert_array_almost_equal(output, tcov) + output = ndimage.correlate1d(array, weights) + assert_array_almost_equal(output, tcor) + output = ndimage.convolve1d(array, weights) + assert_array_almost_equal(output, tcov) + + def test_correlate07(self, xp): + array = xp.asarray([1, 2, 3]) + expected = xp.asarray([5, 8, 11]) + weights = xp.asarray([1, 2, 1]) + output = ndimage.correlate(array, weights) + assert_array_almost_equal(output, expected) + output = ndimage.convolve(array, weights) + assert_array_almost_equal(output, expected) + output = ndimage.correlate1d(array, weights) + assert_array_almost_equal(output, expected) + output = ndimage.convolve1d(array, weights) + assert_array_almost_equal(output, expected) + + def test_correlate08(self, xp): + array = xp.asarray([1, 2, 3]) + tcor = xp.asarray([1, 2, 5]) + tcov = xp.asarray([3, 6, 7]) + weights = xp.asarray([1, 2, -1]) + output = ndimage.correlate(array, weights) + assert_array_almost_equal(output, tcor) + output = ndimage.convolve(array, weights) + assert_array_almost_equal(output, tcov) + output = ndimage.correlate1d(array, weights) + assert_array_almost_equal(output, tcor) + output = ndimage.convolve1d(array, weights) + assert_array_almost_equal(output, tcov) + + def test_correlate09(self, xp): + array = xp.asarray([]) + kernel = xp.asarray([1, 1]) + output = ndimage.correlate(array, kernel) + assert_array_almost_equal(array, output) + output = ndimage.convolve(array, kernel) + assert_array_almost_equal(array, output) + output = ndimage.correlate1d(array, kernel) + assert_array_almost_equal(array, output) + output = ndimage.convolve1d(array, kernel) + assert_array_almost_equal(array, output) + + def test_correlate10(self, xp): + array = xp.asarray([[]]) + kernel = xp.asarray([[1, 1]]) + output = ndimage.correlate(array, kernel) + assert_array_almost_equal(array, output) + output = ndimage.convolve(array, kernel) + assert_array_almost_equal(array, output) + + def test_correlate11(self, xp): + array = xp.asarray([[1, 2, 3], + [4, 5, 6]]) + kernel = xp.asarray([[1, 1], + [1, 1]]) + output = ndimage.correlate(array, kernel) + assert_array_almost_equal(xp.asarray([[4, 6, 10], [10, 12, 16]]), output) + output = ndimage.convolve(array, kernel) + assert_array_almost_equal(xp.asarray([[12, 16, 18], [18, 22, 24]]), output) + + def test_correlate12(self, xp): + array = xp.asarray([[1, 2, 3], + [4, 5, 6]]) + kernel = xp.asarray([[1, 0], + [0, 1]]) + output = ndimage.correlate(array, kernel) + assert_array_almost_equal(xp.asarray([[2, 3, 5], [5, 6, 8]]), output) + output = ndimage.convolve(array, kernel) + assert_array_almost_equal(xp.asarray([[6, 8, 9], [9, 11, 12]]), output) + + @xfail_xp_backends(np_only=True, + reason="output=dtype is numpy-specific", + exceptions=['cupy'],) + @pytest.mark.parametrize('dtype_array', types) + @pytest.mark.parametrize('dtype_kernel', types) + def test_correlate13(self, dtype_array, dtype_kernel, xp): + dtype_array = getattr(xp, dtype_array) + dtype_kernel = getattr(xp, dtype_kernel) + + kernel = xp.asarray([[1, 0], + [0, 1]]) + array = xp.asarray([[1, 2, 3], + [4, 5, 6]], dtype=dtype_array) + output = ndimage.correlate(array, kernel, output=dtype_kernel) + assert_array_almost_equal(xp.asarray([[2, 3, 5], [5, 6, 8]]), output) + assert output.dtype.type == dtype_kernel + + output = ndimage.convolve(array, kernel, + output=dtype_kernel) + assert_array_almost_equal(xp.asarray([[6, 8, 9], [9, 11, 12]]), output) + assert output.dtype.type == dtype_kernel + + @xfail_xp_backends(np_only=True, + reason="output=dtype is numpy-specific", + exceptions=['cupy'],) + @pytest.mark.parametrize('dtype_array', types) + @pytest.mark.parametrize('dtype_output', types) + def test_correlate14(self, dtype_array, dtype_output, xp): + dtype_array = getattr(xp, dtype_array) + dtype_output = getattr(xp, dtype_output) + + kernel = xp.asarray([[1, 0], + [0, 1]]) + array = xp.asarray([[1, 2, 3], + [4, 5, 6]], dtype=dtype_array) + output = xp.zeros(array.shape, dtype=dtype_output) + ndimage.correlate(array, kernel, output=output) + assert_array_almost_equal(xp.asarray([[2, 3, 5], [5, 6, 8]]), output) + assert output.dtype.type == dtype_output + + ndimage.convolve(array, kernel, output=output) + assert_array_almost_equal(xp.asarray([[6, 8, 9], [9, 11, 12]]), output) + assert output.dtype.type == dtype_output + + @xfail_xp_backends(np_only=True, + reason="output=dtype is numpy-specific", + exceptions=['cupy'],) + @pytest.mark.parametrize('dtype_array', types) + def test_correlate15(self, dtype_array, xp): + dtype_array = getattr(xp, dtype_array) + + kernel = xp.asarray([[1, 0], + [0, 1]]) + array = xp.asarray([[1, 2, 3], + [4, 5, 6]], dtype=dtype_array) + output = ndimage.correlate(array, kernel, output=xp.float32) + assert_array_almost_equal(xp.asarray([[2, 3, 5], [5, 6, 8]]), output) + assert output.dtype.type == xp.float32 + + output = ndimage.convolve(array, kernel, output=xp.float32) + assert_array_almost_equal(xp.asarray([[6, 8, 9], [9, 11, 12]]), output) + assert output.dtype.type == xp.float32 + + @xfail_xp_backends(np_only=True, + reason="output=dtype is numpy-specific", + exceptions=['cupy'],) + @pytest.mark.parametrize('dtype_array', types) + def test_correlate16(self, dtype_array, xp): + dtype_array = getattr(xp, dtype_array) + + kernel = xp.asarray([[0.5, 0], + [0, 0.5]]) + array = xp.asarray([[1, 2, 3], [4, 5, 6]], dtype=dtype_array) + output = ndimage.correlate(array, kernel, output=xp.float32) + assert_array_almost_equal(xp.asarray([[1, 1.5, 2.5], [2.5, 3, 4]]), output) + assert output.dtype.type == xp.float32 + + output = ndimage.convolve(array, kernel, output=xp.float32) + assert_array_almost_equal(xp.asarray([[3, 4, 4.5], [4.5, 5.5, 6]]), output) + assert output.dtype.type == xp.float32 + + def test_correlate17(self, xp): + array = xp.asarray([1, 2, 3]) + tcor = xp.asarray([3, 5, 6]) + tcov = xp.asarray([2, 3, 5]) + kernel = xp.asarray([1, 1]) + output = ndimage.correlate(array, kernel, origin=-1) + assert_array_almost_equal(tcor, output) + output = ndimage.convolve(array, kernel, origin=-1) + assert_array_almost_equal(tcov, output) + output = ndimage.correlate1d(array, kernel, origin=-1) + assert_array_almost_equal(tcor, output) + output = ndimage.convolve1d(array, kernel, origin=-1) + assert_array_almost_equal(tcov, output) + + @xfail_xp_backends(np_only=True, + reason="output=dtype is numpy-specific", + exceptions=['cupy'],) + @pytest.mark.parametrize('dtype_array', types) + def test_correlate18(self, dtype_array, xp): + dtype_array = getattr(xp, dtype_array) + + kernel = xp.asarray([[1, 0], + [0, 1]]) + array = xp.asarray([[1, 2, 3], + [4, 5, 6]], dtype=dtype_array) + output = ndimage.correlate(array, kernel, + output=xp.float32, + mode='nearest', origin=-1) + assert_array_almost_equal(xp.asarray([[6, 8, 9], [9, 11, 12]]), output) + assert output.dtype.type == xp.float32 + + output = ndimage.convolve(array, kernel, + output=xp.float32, + mode='nearest', origin=-1) + assert_array_almost_equal(xp.asarray([[2, 3, 5], [5, 6, 8]]), output) + assert output.dtype.type == xp.float32 + + def test_correlate_mode_sequence(self, xp): + kernel = xp.ones((2, 2)) + array = xp.ones((3, 3), dtype=xp.float64) + with assert_raises(RuntimeError): + ndimage.correlate(array, kernel, mode=['nearest', 'reflect']) + with assert_raises(RuntimeError): + ndimage.convolve(array, kernel, mode=['nearest', 'reflect']) + + @xfail_xp_backends(np_only=True, + reason="output=dtype is numpy-specific", + exceptions=['cupy'],) + @pytest.mark.parametrize('dtype_array', types) + def test_correlate19(self, dtype_array, xp): + dtype_array = getattr(xp, dtype_array) + + kernel = xp.asarray([[1, 0], + [0, 1]]) + array = xp.asarray([[1, 2, 3], + [4, 5, 6]], dtype=dtype_array) + output = ndimage.correlate(array, kernel, + output=xp.float32, + mode='nearest', origin=[-1, 0]) + assert_array_almost_equal(xp.asarray([[5, 6, 8], [8, 9, 11]]), output) + assert output.dtype.type == xp.float32 + + output = ndimage.convolve(array, kernel, + output=xp.float32, + mode='nearest', origin=[-1, 0]) + assert_array_almost_equal(xp.asarray([[3, 5, 6], [6, 8, 9]]), output) + assert output.dtype.type == xp.float32 + + @xfail_xp_backends(np_only=True, + reason="output=dtype is numpy-specific", + exceptions=['cupy'],) + @pytest.mark.parametrize('dtype_array', types) + @pytest.mark.parametrize('dtype_output', types) + def test_correlate20(self, dtype_array, dtype_output, xp): + dtype_array = getattr(xp, dtype_array) + dtype_output = getattr(xp, dtype_output) + + weights = xp.asarray([1, 2, 1]) + expected = xp.asarray([[5, 10, 15], [7, 14, 21]]) + array = xp.asarray([[1, 2, 3], + [2, 4, 6]], dtype=dtype_array) + output = xp.zeros((2, 3), dtype=dtype_output) + ndimage.correlate1d(array, weights, axis=0, output=output) + assert_array_almost_equal(output, expected) + ndimage.convolve1d(array, weights, axis=0, output=output) + assert_array_almost_equal(output, expected) + + def test_correlate21(self, xp): + array = xp.asarray([[1, 2, 3], + [2, 4, 6]]) + expected = xp.asarray([[5, 10, 15], [7, 14, 21]]) + weights = xp.asarray([1, 2, 1]) + output = ndimage.correlate1d(array, weights, axis=0) + assert_array_almost_equal(output, expected) + output = ndimage.convolve1d(array, weights, axis=0) + assert_array_almost_equal(output, expected) + + @xfail_xp_backends(np_only=True, + reason="output=dtype is numpy-specific", + exceptions=['cupy'],) + @pytest.mark.parametrize('dtype_array', types) + @pytest.mark.parametrize('dtype_output', types) + def test_correlate22(self, dtype_array, dtype_output, xp): + dtype_array = getattr(xp, dtype_array) + dtype_output = getattr(xp, dtype_output) + + weights = xp.asarray([1, 2, 1]) + expected = xp.asarray([[6, 12, 18], [6, 12, 18]]) + array = xp.asarray([[1, 2, 3], + [2, 4, 6]], dtype=dtype_array) + output = xp.zeros((2, 3), dtype=dtype_output) + ndimage.correlate1d(array, weights, axis=0, + mode='wrap', output=output) + assert_array_almost_equal(output, expected) + ndimage.convolve1d(array, weights, axis=0, + mode='wrap', output=output) + assert_array_almost_equal(output, expected) + + @skip_xp_backends("jax.numpy", reason="output array is read-only.") + @pytest.mark.parametrize('dtype_array', types) + @pytest.mark.parametrize('dtype_output', types) + def test_correlate23(self, dtype_array, dtype_output, xp): + dtype_array = getattr(xp, dtype_array) + dtype_output = getattr(xp, dtype_output) + + weights = xp.asarray([1, 2, 1]) + expected = xp.asarray([[5, 10, 15], [7, 14, 21]]) + array = xp.asarray([[1, 2, 3], + [2, 4, 6]], dtype=dtype_array) + output = xp.zeros((2, 3), dtype=dtype_output) + ndimage.correlate1d(array, weights, axis=0, + mode='nearest', output=output) + assert_array_almost_equal(output, expected) + ndimage.convolve1d(array, weights, axis=0, + mode='nearest', output=output) + assert_array_almost_equal(output, expected) + + @skip_xp_backends("jax.numpy", reason="output array is read-only.") + @pytest.mark.parametrize('dtype_array', types) + @pytest.mark.parametrize('dtype_output', types) + def test_correlate24(self, dtype_array, dtype_output, xp): + dtype_array = getattr(xp, dtype_array) + dtype_output = getattr(xp, dtype_output) + + weights = xp.asarray([1, 2, 1]) + tcor = xp.asarray([[7, 14, 21], [8, 16, 24]]) + tcov = xp.asarray([[4, 8, 12], [5, 10, 15]]) + array = xp.asarray([[1, 2, 3], + [2, 4, 6]], dtype=dtype_array) + output = xp.zeros((2, 3), dtype=dtype_output) + ndimage.correlate1d(array, weights, axis=0, + mode='nearest', output=output, origin=-1) + assert_array_almost_equal(output, tcor) + ndimage.convolve1d(array, weights, axis=0, + mode='nearest', output=output, origin=-1) + assert_array_almost_equal(output, tcov) + + @skip_xp_backends("jax.numpy", reason="output array is read-only.") + @pytest.mark.parametrize('dtype_array', types) + @pytest.mark.parametrize('dtype_output', types) + def test_correlate25(self, dtype_array, dtype_output, xp): + dtype_array = getattr(xp, dtype_array) + dtype_output = getattr(xp, dtype_output) + + weights = xp.asarray([1, 2, 1]) + tcor = xp.asarray([[4, 8, 12], [5, 10, 15]]) + tcov = xp.asarray([[7, 14, 21], [8, 16, 24]]) + array = xp.asarray([[1, 2, 3], + [2, 4, 6]], dtype=dtype_array) + output = xp.zeros((2, 3), dtype=dtype_output) + ndimage.correlate1d(array, weights, axis=0, + mode='nearest', output=output, origin=1) + assert_array_almost_equal(output, tcor) + ndimage.convolve1d(array, weights, axis=0, + mode='nearest', output=output, origin=1) + assert_array_almost_equal(output, tcov) + + def test_correlate26(self, xp): + # test fix for gh-11661 (mirror extension of a length 1 signal) + y = ndimage.convolve1d(xp.ones(1), xp.ones(5), mode='mirror') + xp_assert_equal(y, xp.asarray([5.])) + + y = ndimage.correlate1d(xp.ones(1), xp.ones(5), mode='mirror') + xp_assert_equal(y, xp.asarray([5.])) + + @xfail_xp_backends(np_only=True, + reason="output=dtype is numpy-specific", + exceptions=['cupy'],) + @pytest.mark.parametrize('dtype_kernel', complex_types) + @pytest.mark.parametrize('dtype_input', types) + @pytest.mark.parametrize('dtype_output', complex_types) + def test_correlate_complex_kernel(self, dtype_input, dtype_kernel, + dtype_output, xp, num_parallel_threads): + dtype_input = getattr(xp, dtype_input) + dtype_kernel = getattr(xp, dtype_kernel) + dtype_output = getattr(xp, dtype_output) + + kernel = xp.asarray([[1, 0], + [0, 1 + 1j]], dtype=dtype_kernel) + array = xp.asarray([[1, 2, 3], + [4, 5, 6]], dtype=dtype_input) + self._validate_complex(xp, array, kernel, dtype_output, + check_warnings=num_parallel_threads == 1) + + @xfail_xp_backends(np_only=True, + reason="output=dtype is numpy-specific", + exceptions=['cupy'],) + @pytest.mark.parametrize('dtype_kernel', complex_types) + @pytest.mark.parametrize('dtype_input', types) + @pytest.mark.parametrize('dtype_output', complex_types) + @pytest.mark.parametrize('mode', ['grid-constant', 'constant']) + def test_correlate_complex_kernel_cval(self, dtype_input, dtype_kernel, + dtype_output, mode, xp, + num_parallel_threads): + dtype_input = getattr(xp, dtype_input) + dtype_kernel = getattr(xp, dtype_kernel) + dtype_output = getattr(xp, dtype_output) + + if is_cupy(xp) and mode == 'grid-constant': + pytest.xfail('https://github.com/cupy/cupy/issues/8404') + + # test use of non-zero cval with complex inputs + # also verifies that mode 'grid-constant' does not segfault + kernel = xp.asarray([[1, 0], + [0, 1 + 1j]], dtype=dtype_kernel) + array = xp.asarray([[1, 2, 3], + [4, 5, 6]], dtype=dtype_input) + self._validate_complex(xp, array, kernel, dtype_output, mode=mode, + cval=5.0, + check_warnings=num_parallel_threads == 1) + + @xfail_xp_backends('cupy', reason="cupy/cupy#8405") + @pytest.mark.parametrize('dtype_kernel', complex_types) + @pytest.mark.parametrize('dtype_input', types) + @pytest.mark.thread_unsafe + def test_correlate_complex_kernel_invalid_cval(self, dtype_input, + dtype_kernel, xp): + dtype_input = getattr(xp, dtype_input) + dtype_kernel = getattr(xp, dtype_kernel) + + # cannot give complex cval with a real image + kernel = xp.asarray([[1, 0], + [0, 1 + 1j]], dtype=dtype_kernel) + array = xp.asarray([[1, 2, 3], + [4, 5, 6]], dtype=dtype_input) + for func in [ndimage.convolve, ndimage.correlate, ndimage.convolve1d, + ndimage.correlate1d]: + with pytest.raises((ValueError, TypeError)): + func(array, kernel, mode='constant', cval=5.0 + 1.0j, + output=xp.complex64) + + @skip_xp_backends(np_only=True, reason='output=dtype is numpy-specific') + @pytest.mark.parametrize('dtype_kernel', complex_types) + @pytest.mark.parametrize('dtype_input', types) + @pytest.mark.parametrize('dtype_output', complex_types) + def test_correlate1d_complex_kernel(self, dtype_input, dtype_kernel, + dtype_output, xp, num_parallel_threads): + dtype_input = getattr(xp, dtype_input) + dtype_kernel = getattr(xp, dtype_kernel) + dtype_output = getattr(xp, dtype_output) + + kernel = xp.asarray([1, 1 + 1j], dtype=dtype_kernel) + array = xp.asarray([1, 2, 3, 4, 5, 6], dtype=dtype_input) + self._validate_complex(xp, array, kernel, dtype_output, + check_warnings=num_parallel_threads == 1) + + @skip_xp_backends(np_only=True, reason='output=dtype is numpy-specific') + @pytest.mark.parametrize('dtype_kernel', complex_types) + @pytest.mark.parametrize('dtype_input', types) + @pytest.mark.parametrize('dtype_output', complex_types) + def test_correlate1d_complex_kernel_cval(self, dtype_input, dtype_kernel, + dtype_output, xp, + num_parallel_threads): + dtype_input = getattr(xp, dtype_input) + dtype_kernel = getattr(xp, dtype_kernel) + dtype_output = getattr(xp, dtype_output) + + kernel = xp.asarray([1, 1 + 1j], dtype=dtype_kernel) + array = xp.asarray([1, 2, 3, 4, 5, 6], dtype=dtype_input) + self._validate_complex(xp, array, kernel, dtype_output, mode='constant', + cval=5.0, + check_warnings=num_parallel_threads == 1) + + @skip_xp_backends(np_only=True, reason='output=dtype is numpy-specific') + @pytest.mark.parametrize('dtype_kernel', types) + @pytest.mark.parametrize('dtype_input', complex_types) + @pytest.mark.parametrize('dtype_output', complex_types) + def test_correlate_complex_input(self, dtype_input, dtype_kernel, + dtype_output, xp, num_parallel_threads): + dtype_input = getattr(xp, dtype_input) + dtype_kernel = getattr(xp, dtype_kernel) + dtype_output = getattr(xp, dtype_output) + + kernel = xp.asarray([[1, 0], + [0, 1]], dtype=dtype_kernel) + array = xp.asarray([[1, 2j, 3], + [1 + 4j, 5, 6j]], dtype=dtype_input) + self._validate_complex(xp, array, kernel, dtype_output, + check_warnings=num_parallel_threads == 1) + + @skip_xp_backends(np_only=True, reason='output=dtype is numpy-specific') + @pytest.mark.parametrize('dtype_kernel', types) + @pytest.mark.parametrize('dtype_input', complex_types) + @pytest.mark.parametrize('dtype_output', complex_types) + def test_correlate1d_complex_input(self, dtype_input, dtype_kernel, + dtype_output, xp, num_parallel_threads): + dtype_input = getattr(xp, dtype_input) + dtype_kernel = getattr(xp, dtype_kernel) + dtype_output = getattr(xp, dtype_output) + + kernel = xp.asarray([1, 0, 1], dtype=dtype_kernel) + array = xp.asarray([1, 2j, 3, 1 + 4j, 5, 6j], dtype=dtype_input) + self._validate_complex(xp, array, kernel, dtype_output, + check_warnings=num_parallel_threads == 1) + + @xfail_xp_backends('cupy', reason="cupy/cupy#8405") + @skip_xp_backends(np_only=True, + reason='output=dtype is numpy-specific', + exceptions=['cupy']) + @pytest.mark.parametrize('dtype_kernel', types) + @pytest.mark.parametrize('dtype_input', complex_types) + @pytest.mark.parametrize('dtype_output', complex_types) + def test_correlate1d_complex_input_cval(self, dtype_input, dtype_kernel, + dtype_output, xp, + num_parallel_threads): + dtype_input = getattr(xp, dtype_input) + dtype_kernel = getattr(xp, dtype_kernel) + dtype_output = getattr(xp, dtype_output) + + kernel = xp.asarray([1, 0, 1], dtype=dtype_kernel) + array = xp.asarray([1, 2j, 3, 1 + 4j, 5, 6j], dtype=dtype_input) + self._validate_complex(xp, array, kernel, dtype_output, mode='constant', + cval=5 - 3j, + check_warnings=num_parallel_threads == 1) + + @skip_xp_backends(np_only=True, reason='output=dtype is numpy-specific') + @pytest.mark.parametrize('dtype', complex_types) + @pytest.mark.parametrize('dtype_output', complex_types) + def test_correlate_complex_input_and_kernel(self, dtype, dtype_output, xp, + num_parallel_threads): + dtype = getattr(xp, dtype) + dtype_output = getattr(xp, dtype_output) + + kernel = xp.asarray([[1, 0], + [0, 1 + 1j]], dtype=dtype) + array = xp.asarray([[1, 2j, 3], + [1 + 4j, 5, 6j]], dtype=dtype) + self._validate_complex(xp, array, kernel, dtype_output, + check_warnings=num_parallel_threads == 1) + + @xfail_xp_backends('cupy', reason="cupy/cupy#8405") + @skip_xp_backends(np_only=True, + reason="output=dtype is numpy-specific", + exceptions=['cupy'],) + @pytest.mark.parametrize('dtype', complex_types) + @pytest.mark.parametrize('dtype_output', complex_types) + def test_correlate_complex_input_and_kernel_cval(self, dtype, + dtype_output, xp, + num_parallel_threads): + dtype = getattr(xp, dtype) + dtype_output = getattr(xp, dtype_output) + + kernel = xp.asarray([[1, 0], + [0, 1 + 1j]], dtype=dtype) + array = xp.asarray([[1, 2, 3], + [4, 5, 6]], dtype=dtype) + self._validate_complex(xp, array, kernel, dtype_output, mode='constant', + cval=5.0 + 2.0j, + check_warnings=num_parallel_threads == 1) + + @skip_xp_backends(np_only=True, reason="output=dtype is numpy-specific") + @pytest.mark.parametrize('dtype', complex_types) + @pytest.mark.parametrize('dtype_output', complex_types) + @pytest.mark.thread_unsafe + def test_correlate1d_complex_input_and_kernel(self, dtype, dtype_output, xp, + num_parallel_threads): + dtype = getattr(xp, dtype) + dtype_output = getattr(xp, dtype_output) + + kernel = xp.asarray([1, 1 + 1j], dtype=dtype) + array = xp.asarray([1, 2j, 3, 1 + 4j, 5, 6j], dtype=dtype) + self._validate_complex(xp, array, kernel, dtype_output, + check_warnings=num_parallel_threads == 1) + + @pytest.mark.parametrize('dtype', complex_types) + @pytest.mark.parametrize('dtype_output', complex_types) + def test_correlate1d_complex_input_and_kernel_cval(self, dtype, + dtype_output, xp, + num_parallel_threads): + if not (is_numpy(xp) or is_cupy(xp)): + pytest.xfail("output=dtype is numpy-specific") + + dtype = getattr(xp, dtype) + dtype_output = getattr(xp, dtype_output) + + if is_cupy(xp): + pytest.xfail("https://github.com/cupy/cupy/issues/8405") + + kernel = xp.asarray([1, 1 + 1j], dtype=dtype) + array = xp.asarray([1, 2j, 3, 1 + 4j, 5, 6j], dtype=dtype) + self._validate_complex(xp, array, kernel, dtype_output, mode='constant', + cval=5.0 + 2.0j, + check_warnings=num_parallel_threads == 1) + + def test_gauss01(self, xp): + input = xp.asarray([[1, 2, 3], + [2, 4, 6]], dtype=xp.float32) + output = ndimage.gaussian_filter(input, 0) + assert_array_almost_equal(output, input) + + def test_gauss02(self, xp): + input = xp.asarray([[1, 2, 3], + [2, 4, 6]], dtype=xp.float32) + output = ndimage.gaussian_filter(input, 1.0) + assert input.dtype == output.dtype + assert input.shape == output.shape + + def test_gauss03(self, xp): + if is_cupy(xp): + pytest.xfail("https://github.com/cupy/cupy/issues/8403") + + # single precision data + input = xp.arange(100 * 100, dtype=xp.float32) + input = xp.reshape(input, (100, 100)) + output = ndimage.gaussian_filter(input, [1.0, 1.0]) + + assert input.dtype == output.dtype + assert input.shape == output.shape + + # input.sum() is 49995000.0. With single precision floats, we can't + # expect more than 8 digits of accuracy, so use decimal=0 in this test. + o_sum = xp.sum(output, dtype=xp.float64) + i_sum = xp.sum(input, dtype=xp.float64) + assert_almost_equal(o_sum, i_sum, decimal=0) + assert sumsq(input, output) > 1.0 + + def test_gauss04(self, xp): + if not (is_numpy(xp) or is_cupy(xp)): + pytest.xfail("output=dtype is numpy-specific") + + input = xp.arange(100 * 100, dtype=xp.float32) + input = xp.reshape(input, (100, 100)) + otype = xp.float64 + output = ndimage.gaussian_filter(input, [1.0, 1.0], output=otype) + assert output.dtype.type == xp.float64 + assert input.shape == output.shape + assert sumsq(input, output) > 1.0 + + def test_gauss05(self, xp): + if not (is_numpy(xp) or is_cupy(xp)): + pytest.xfail("output=dtype is numpy-specific") + + input = xp.arange(100 * 100, dtype=xp.float32) + input = xp.reshape(input, (100, 100)) + otype = xp.float64 + output = ndimage.gaussian_filter(input, [1.0, 1.0], + order=1, output=otype) + assert output.dtype.type == xp.float64 + assert input.shape == output.shape + assert sumsq(input, output) > 1.0 + + def test_gauss06(self, xp): + if not (is_numpy(xp) or is_cupy(xp)): + pytest.xfail("output=dtype is numpy-specific") + + input = xp.arange(100 * 100, dtype=xp.float32) + input = xp.reshape(input, (100, 100)) + otype = xp.float64 + output1 = ndimage.gaussian_filter(input, [1.0, 1.0], output=otype) + output2 = ndimage.gaussian_filter(input, 1.0, output=otype) + assert_array_almost_equal(output1, output2) + + @skip_xp_backends("jax.numpy", reason="output array is read-only.") + def test_gauss_memory_overlap(self, xp): + input = xp.arange(100 * 100, dtype=xp.float32) + input = xp.reshape(input, (100, 100)) + output1 = ndimage.gaussian_filter(input, 1.0) + ndimage.gaussian_filter(input, 1.0, output=input) + assert_array_almost_equal(output1, input) + + @pytest.mark.parametrize(('filter_func', 'extra_args', 'size0', 'size'), + [(ndimage.gaussian_filter, (), 0, 1.0), + (ndimage.uniform_filter, (), 1, 3), + (ndimage.minimum_filter, (), 1, 3), + (ndimage.maximum_filter, (), 1, 3), + (ndimage.median_filter, (), 1, 3), + (ndimage.rank_filter, (1,), 1, 3), + (ndimage.percentile_filter, (40,), 1, 3)]) + @pytest.mark.parametrize( + 'axes', + tuple(itertools.combinations(range(-3, 3), 1)) + + tuple(itertools.combinations(range(-3, 3), 2)) + + ((0, 1, 2),)) + def test_filter_axes(self, filter_func, extra_args, size0, size, axes, xp): + if is_cupy(xp): + pytest.xfail("https://github.com/cupy/cupy/pull/8339") + + # Note: `size` is called `sigma` in `gaussian_filter` + array = xp.arange(6 * 8 * 12, dtype=xp.float64) + array = xp.reshape(array, (6, 8, 12)) + + if len(set(ax % array.ndim for ax in axes)) != len(axes): + # parametrized cases with duplicate axes raise an error + with pytest.raises(ValueError, match="axes must be unique"): + filter_func(array, *extra_args, size, axes=axes) + return + output = filter_func(array, *extra_args, size, axes=axes) + + # result should be equivalent to sigma=0.0/size=1 on unfiltered axes + axes = xp.asarray(axes) + all_sizes = tuple(size if ax in (axes % array.ndim) else size0 + for ax in range(array.ndim)) + expected = filter_func(array, *extra_args, all_sizes) + xp_assert_close(output, expected) + + @skip_xp_backends("cupy", + reason="these filters do not yet have axes support", + ) + @pytest.mark.parametrize(('filter_func', 'kwargs'), + [(ndimage.laplace, {}), + (ndimage.gaussian_gradient_magnitude, + {"sigma": 1.0}), + (ndimage.gaussian_laplace, {"sigma": 0.5})]) + def test_derivative_filter_axes(self, xp, filter_func, kwargs): + array = xp.arange(6 * 8 * 12, dtype=xp.float64) + array = xp.reshape(array, (6, 8, 12)) + + # duplicate axes raises an error + with pytest.raises(ValueError, match="axes must be unique"): + filter_func(array, axes=(1, 1), **kwargs) + + # compare results to manually looping over the non-filtered axes + output = filter_func(array, axes=(1, 2), **kwargs) + expected = xp.empty_like(output) + expected = [] + for i in range(array.shape[0]): + expected.append(filter_func(array[i, ...], **kwargs)) + expected = xp.stack(expected, axis=0) + xp_assert_close(output, expected) + + output = filter_func(array, axes=(0, -1), **kwargs) + expected = [] + for i in range(array.shape[1]): + expected.append(filter_func(array[:, i, :], **kwargs)) + expected = xp.stack(expected, axis=1) + xp_assert_close(output, expected) + + output = filter_func(array, axes=(1), **kwargs) + expected = [] + for i in range(array.shape[0]): + exp_inner = [] + for j in range(array.shape[2]): + exp_inner.append(filter_func(array[i, :, j], **kwargs)) + expected.append(xp.stack(exp_inner, axis=-1)) + expected = xp.stack(expected, axis=0) + xp_assert_close(output, expected) + + @skip_xp_backends("cupy", + reason="generic_filter does not yet have axes support", + ) + @pytest.mark.parametrize( + 'axes', + tuple(itertools.combinations(range(-3, 3), 1)) + + tuple(itertools.combinations(range(-3, 3), 2)) + + ((0, 1, 2),)) + def test_generic_filter_axes(self, xp, axes): + array = xp.arange(6 * 8 * 12, dtype=xp.float64) + array = xp.reshape(array, (6, 8, 12)) + size = 3 + if len(set(ax % array.ndim for ax in axes)) != len(axes): + # parametrized cases with duplicate axes raise an error + with pytest.raises(ValueError, match="axes must be unique"): + ndimage.generic_filter(array, np.amax, size=size, axes=axes) + return + + # choose np.amax as the function so we can compare to maximum_filter + output = ndimage.generic_filter(array, np.amax, size=size, axes=axes) + expected = ndimage.maximum_filter(array, size=size, axes=axes) + xp_assert_close(output, expected) + + @skip_xp_backends("cupy", + reason="https://github.com/cupy/cupy/pull/8339", + ) + @pytest.mark.parametrize('func', [ndimage.correlate, ndimage.convolve]) + @pytest.mark.parametrize( + 'dtype', [np.float32, np.float64, np.complex64, np.complex128] + ) + @pytest.mark.parametrize( + 'axes', tuple(itertools.combinations(range(-3, 3), 2)) + ) + @pytest.mark.parametrize('origin', [(0, 0), (-1, 1)]) + def test_correlate_convolve_axes(self, xp, func, dtype, axes, origin): + array = xp.asarray(np.arange(6 * 8 * 12, dtype=dtype).reshape(6, 8, 12)) + weights = xp.arange(3 * 5) + weights = xp.reshape(weights, (3, 5)) + axes = tuple(ax % array.ndim for ax in axes) + if len(tuple(set(axes))) != len(axes): + # parametrized cases with duplicate axes raise an error + with pytest.raises(ValueError): + func(array, weights=weights, axes=axes, origin=origin) + return + output = func(array, weights=weights, axes=axes, origin=origin) + + missing_axis = tuple(set(range(3)) - set(axes))[0] + # module 'torch' has no attribute 'expand_dims' so use reshape instead + # weights_3d = xp.expand_dims(weights, axis=missing_axis) + shape_3d = ( + weights.shape[:missing_axis] + (1,) + weights.shape[missing_axis:] + ) + weights_3d = xp.reshape(weights, shape_3d) + origin_3d = [0, 0, 0] + for i, ax in enumerate(axes): + origin_3d[ax] = origin[i] + expected = func(array, weights=weights_3d, origin=origin_3d) + xp_assert_close(output, expected) + + kwargs_gauss = dict(radius=[4, 2, 3], order=[0, 1, 2], + mode=['reflect', 'nearest', 'constant']) + kwargs_other = dict(origin=(-1, 0, 1), + mode=['reflect', 'nearest', 'constant']) + kwargs_rank = dict(origin=(-1, 0, 1)) + + @skip_xp_backends("array_api_strict", + reason="fancy indexing is only available in 2024 version", + ) + @pytest.mark.parametrize("filter_func, size0, size, kwargs", + [(ndimage.gaussian_filter, 0, 1.0, kwargs_gauss), + (ndimage.uniform_filter, 1, 3, kwargs_other), + (ndimage.maximum_filter, 1, 3, kwargs_other), + (ndimage.minimum_filter, 1, 3, kwargs_other), + (ndimage.median_filter, 1, 3, kwargs_rank), + (ndimage.rank_filter, 1, 3, kwargs_rank), + (ndimage.percentile_filter, 1, 3, kwargs_rank)]) + @pytest.mark.parametrize('axes', itertools.combinations(range(-3, 3), 2)) + def test_filter_axes_kwargs(self, filter_func, size0, size, kwargs, axes, xp): + + if is_cupy(xp): + pytest.xfail("https://github.com/cupy/cupy/pull/8339") + + array = xp.arange(6 * 8 * 12, dtype=xp.float64) + array = xp.reshape(array, (6, 8, 12)) + + kwargs = {key: np.array(val) for key, val in kwargs.items()} + axes = np.array(axes) + n_axes = axes.size + + if filter_func == ndimage.rank_filter: + args = (2,) # (rank,) + elif filter_func == ndimage.percentile_filter: + args = (30,) # (percentile,) + else: + args = () + + # form kwargs that specify only the axes in `axes` + reduced_kwargs = {key: val[axes] for key, val in kwargs.items()} + if len(set(axes % array.ndim)) != len(axes): + # parametrized cases with duplicate axes raise an error + with pytest.raises(ValueError, match="axes must be unique"): + filter_func(array, *args, [size]*n_axes, axes=axes, + **reduced_kwargs) + return + + output = filter_func(array, *args, [size]*n_axes, axes=axes, + **reduced_kwargs) + + # result should be equivalent to sigma=0.0/size=1 on unfiltered axes + size_3d = np.full(array.ndim, fill_value=size0) + size_3d[axes] = size + size_3d = [size_3d[i] for i in range(size_3d.shape[0])] + if 'origin' in kwargs: + # origin should be zero on the axis that has size 0 + origin = np.asarray([0, 0, 0]) + origin[axes] = reduced_kwargs['origin'] + origin = xp.asarray(origin) + kwargs['origin'] = origin + expected = filter_func(array, *args, size_3d, **kwargs) + xp_assert_close(output, expected) + + + @pytest.mark.parametrize("filter_func, kwargs", + [(ndimage.convolve, {}), + (ndimage.correlate, {}), + (ndimage.minimum_filter, {}), + (ndimage.maximum_filter, {}), + (ndimage.median_filter, {}), + (ndimage.rank_filter, {"rank": 1}), + (ndimage.percentile_filter, {"percentile": 30})]) + def test_filter_weights_subset_axes_origins(self, filter_func, kwargs, xp): + if is_cupy(xp): + pytest.xfail("https://github.com/cupy/cupy/pull/8339") + + axes = (-2, -1) + origins = (0, 1) + array = xp.arange(6 * 8 * 12, dtype=xp.float64) + array = xp.reshape(array, (6, 8, 12)) + + # weights with ndim matching len(axes) + footprint = np.ones((3, 5), dtype=bool) + footprint[0, 1] = 0 # make non-separable + footprint = xp.asarray(footprint) + + if filter_func in (ndimage.convolve, ndimage.correlate): + kwargs["weights"] = footprint + else: + kwargs["footprint"] = footprint + kwargs["axes"] = axes + + output = filter_func(array, origin=origins, **kwargs) + + output0 = filter_func(array, origin=0, **kwargs) + + # output has origin shift on last axis relative to output0, so + # expect shifted arrays to be equal. + if filter_func == ndimage.convolve: + # shift is in the opposite direction for convolve because it + # flips the weights array and negates the origin values. + xp_assert_equal( + output[:, :, :-origins[1]], output0[:, :, origins[1]:]) + else: + xp_assert_equal( + output[:, :, origins[1]:], output0[:, :, :-origins[1]]) + + + @pytest.mark.parametrize( + 'filter_func, args', + [(ndimage.convolve, (np.ones((3, 3, 3)),)), # args = (weights,) + (ndimage.correlate,(np.ones((3, 3, 3)),)), # args = (weights,) + (ndimage.gaussian_filter, (1.0,)), # args = (sigma,) + (ndimage.uniform_filter, (3,)), # args = (size,) + (ndimage.minimum_filter, (3,)), # args = (size,) + (ndimage.maximum_filter, (3,)), # args = (size,) + (ndimage.median_filter, (3,)), # args = (size,) + (ndimage.rank_filter, (2, 3)), # args = (rank, size) + (ndimage.percentile_filter, (30, 3))]) # args = (percentile, size) + @pytest.mark.parametrize( + 'axes', [(1.5,), (0, 1, 2, 3), (3,), (-4,)] + ) + def test_filter_invalid_axes(self, filter_func, args, axes, xp): + if is_cupy(xp): + pytest.xfail("https://github.com/cupy/cupy/pull/8339") + + array = xp.arange(6 * 8 * 12, dtype=xp.float64) + array = xp.reshape(array, (6, 8, 12)) + args = [ + xp.asarray(arg) if isinstance(arg, np.ndarray) else arg + for arg in args + ] + if any(isinstance(ax, float) for ax in axes): + error_class = TypeError + match = "cannot be interpreted as an integer" + else: + error_class = ValueError + match = "out of range" + with pytest.raises(error_class, match=match): + filter_func(array, *args, axes=axes) + + @pytest.mark.parametrize( + 'filter_func, kwargs', + [(ndimage.convolve, {}), + (ndimage.correlate, {}), + (ndimage.minimum_filter, {}), + (ndimage.maximum_filter, {}), + (ndimage.median_filter, {}), + (ndimage.rank_filter, dict(rank=3)), + (ndimage.percentile_filter, dict(percentile=30))]) + @pytest.mark.parametrize( + 'axes', [(0, ), (1, 2), (0, 1, 2)] + ) + @pytest.mark.parametrize('separable_footprint', [False, True]) + def test_filter_invalid_footprint_ndim(self, filter_func, kwargs, axes, + separable_footprint, xp): + if is_cupy(xp): + pytest.xfail("https://github.com/cupy/cupy/pull/8339") + + array = xp.arange(6 * 8 * 12, dtype=xp.float64) + array = xp.reshape(array, (6, 8, 12)) + # create a footprint with one too many dimensions + footprint = np.ones((3,) * (len(axes) + 1)) + if not separable_footprint: + footprint[(0,) * footprint.ndim] = 0 + footprint = xp.asarray(footprint) + if (filter_func in [ndimage.minimum_filter, ndimage.maximum_filter] + and separable_footprint): + match = "sequence argument must have length equal to input rank" + elif filter_func in [ndimage.convolve, ndimage.correlate]: + match = re.escape(f"weights.ndim ({footprint.ndim}) must match " + f"len(axes) ({len(axes)})") + else: + match = re.escape(f"footprint.ndim ({footprint.ndim}) must match " + f"len(axes) ({len(axes)})") + if filter_func in [ndimage.convolve, ndimage.correlate]: + kwargs["weights"] = footprint + else: + kwargs["footprint"] = footprint + with pytest.raises(RuntimeError, match=match): + filter_func(array, axes=axes, **kwargs) + + @pytest.mark.parametrize('n_mismatch', [1, 3]) + @pytest.mark.parametrize('filter_func, kwargs, key, val', + _cases_axes_tuple_length_mismatch()) + def test_filter_tuple_length_mismatch(self, n_mismatch, filter_func, + kwargs, key, val, xp): + if is_cupy(xp): + pytest.xfail("https://github.com/cupy/cupy/pull/8339") + + # Test for the intended RuntimeError when a kwargs has an invalid size + array = xp.arange(6 * 8 * 12, dtype=xp.float64) + array = xp.reshape(array, (6, 8, 12)) + axes = (0, 1) + kwargs = dict(**kwargs, axes=axes) + kwargs[key] = (val,) * n_mismatch + if filter_func in [ndimage.convolve, ndimage.correlate]: + kwargs["weights"] = xp.ones((5,) * len(axes)) + err_msg = "sequence argument must have length equal to input rank" + with pytest.raises(RuntimeError, match=err_msg): + filter_func(array, **kwargs) + + @pytest.mark.parametrize('dtype', types + complex_types) + def test_prewitt01(self, dtype, xp): + if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"): + pytest.xfail("https://github.com/pytorch/pytorch/issues/58734") + + dtype = getattr(xp, dtype) + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=dtype) + t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 0) + t = ndimage.correlate1d(t, xp.asarray([1.0, 1.0, 1.0]), 1) + output = ndimage.prewitt(array, 0) + assert_array_almost_equal(t, output) + + @skip_xp_backends("jax.numpy", reason="output array is read-only.") + @pytest.mark.parametrize('dtype', types + complex_types) + def test_prewitt02(self, dtype, xp): + if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"): + pytest.xfail("https://github.com/pytorch/pytorch/issues/58734") + + dtype = getattr(xp, dtype) + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=dtype) + t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 0) + t = ndimage.correlate1d(t, xp.asarray([1.0, 1.0, 1.0]), 1) + output = xp.zeros(array.shape, dtype=dtype) + ndimage.prewitt(array, 0, output) + assert_array_almost_equal(t, output) + + @pytest.mark.parametrize('dtype', types + complex_types) + def test_prewitt03(self, dtype, xp): + if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"): + pytest.xfail("https://github.com/pytorch/pytorch/issues/58734") + + dtype = getattr(xp, dtype) + if is_cupy(xp) and dtype in [xp.uint32, xp.uint64]: + pytest.xfail("uint UB? XXX") + if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"): + pytest.xfail("https://github.com/pytorch/pytorch/issues/58734") + + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=dtype) + t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 1) + t = ndimage.correlate1d(t, xp.asarray([1.0, 1.0, 1.0]), 0) + output = ndimage.prewitt(array, 1) + assert_array_almost_equal(t, output) + + @pytest.mark.parametrize('dtype', types + complex_types) + def test_prewitt04(self, dtype, xp): + if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"): + pytest.xfail("https://github.com/pytorch/pytorch/issues/58734") + + dtype = getattr(xp, dtype) + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=dtype) + t = ndimage.prewitt(array, -1) + output = ndimage.prewitt(array, 1) + assert_array_almost_equal(t, output) + + @pytest.mark.parametrize('dtype', types + complex_types) + def test_sobel01(self, dtype, xp): + if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"): + pytest.xfail("https://github.com/pytorch/pytorch/issues/58734") + + dtype = getattr(xp, dtype) + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=dtype) + t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 0) + t = ndimage.correlate1d(t, xp.asarray([1.0, 2.0, 1.0]), 1) + output = ndimage.sobel(array, 0) + assert_array_almost_equal(t, output) + + @skip_xp_backends("jax.numpy", reason="output array is read-only.",) + @pytest.mark.parametrize('dtype', types + complex_types) + def test_sobel02(self, dtype, xp): + if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"): + pytest.xfail("https://github.com/pytorch/pytorch/issues/58734") + + dtype = getattr(xp, dtype) + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=dtype) + t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 0) + t = ndimage.correlate1d(t, xp.asarray([1.0, 2.0, 1.0]), 1) + output = xp.zeros(array.shape, dtype=dtype) + ndimage.sobel(array, 0, output) + assert_array_almost_equal(t, output) + + @pytest.mark.parametrize('dtype', types + complex_types) + def test_sobel03(self, dtype, xp): + if is_cupy(xp) and dtype in ["uint32", "uint64"]: + pytest.xfail("uint UB? XXX") + if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"): + pytest.xfail("https://github.com/pytorch/pytorch/issues/58734") + + dtype = getattr(xp, dtype) + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=dtype) + t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 1) + t = ndimage.correlate1d(t, xp.asarray([1.0, 2.0, 1.0]), 0) + output = xp.zeros(array.shape, dtype=dtype) + output = ndimage.sobel(array, 1) + assert_array_almost_equal(t, output) + + @pytest.mark.parametrize('dtype', types + complex_types) + def test_sobel04(self, dtype, xp): + if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"): + pytest.xfail("https://github.com/pytorch/pytorch/issues/58734") + + dtype = getattr(xp, dtype) + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=dtype) + t = ndimage.sobel(array, -1) + output = ndimage.sobel(array, 1) + assert_array_almost_equal(t, output) + + @pytest.mark.parametrize('dtype', + ["int32", "float32", "float64", + "complex64", "complex128"]) + def test_laplace01(self, dtype, xp): + dtype = getattr(xp, dtype) + + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=dtype) * 100 + tmp1 = ndimage.correlate1d(array, xp.asarray([1, -2, 1]), 0) + tmp2 = ndimage.correlate1d(array, xp.asarray([1, -2, 1]), 1) + output = ndimage.laplace(array) + assert_array_almost_equal(tmp1 + tmp2, output) + + @skip_xp_backends("jax.numpy", reason="output array is read-only",) + @pytest.mark.parametrize('dtype', + ["int32", "float32", "float64", + "complex64", "complex128"]) + def test_laplace02(self, dtype, xp): + dtype = getattr(xp, dtype) + + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=dtype) * 100 + tmp1 = ndimage.correlate1d(array, xp.asarray([1, -2, 1]), 0) + tmp2 = ndimage.correlate1d(array, xp.asarray([1, -2, 1]), 1) + output = xp.zeros(array.shape, dtype=dtype) + ndimage.laplace(array, output=output) + assert_array_almost_equal(tmp1 + tmp2, output) + + @pytest.mark.parametrize('dtype', + ["int32", "float32", "float64", + "complex64", "complex128"]) + def test_gaussian_laplace01(self, dtype, xp): + dtype = getattr(xp, dtype) + + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=dtype) * 100 + tmp1 = ndimage.gaussian_filter(array, 1.0, [2, 0]) + tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 2]) + output = ndimage.gaussian_laplace(array, 1.0) + assert_array_almost_equal(tmp1 + tmp2, output) + + @skip_xp_backends("jax.numpy", reason="output array is read-only") + @pytest.mark.parametrize('dtype', + ["int32", "float32", "float64", + "complex64", "complex128"]) + def test_gaussian_laplace02(self, dtype, xp): + dtype = getattr(xp, dtype) + + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=dtype) * 100 + tmp1 = ndimage.gaussian_filter(array, 1.0, [2, 0]) + tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 2]) + output = xp.zeros(array.shape, dtype=dtype) + ndimage.gaussian_laplace(array, 1.0, output) + assert_array_almost_equal(tmp1 + tmp2, output) + + @skip_xp_backends("jax.numpy", reason="output array is read-only.") + @pytest.mark.parametrize('dtype', types + complex_types) + def test_generic_laplace01(self, dtype, xp): + if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"): + pytest.xfail("https://github.com/pytorch/pytorch/issues/58734") + + def derivative2(input, axis, output, mode, cval, a, b): + sigma = np.asarray([a, b / 2.0]) + order = [0] * input.ndim + order[axis] = 2 + return ndimage.gaussian_filter(input, sigma, order, + output, mode, cval) + + dtype = getattr(xp, dtype) + + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=dtype) + output = xp.zeros(array.shape, dtype=dtype) + tmp = ndimage.generic_laplace(array, derivative2, + extra_arguments=(1.0,), + extra_keywords={'b': 2.0}) + ndimage.gaussian_laplace(array, 1.0, output) + assert_array_almost_equal(tmp, output) + + @skip_xp_backends("jax.numpy", reason="output array is read-only") + @pytest.mark.parametrize('dtype', + ["int32", "float32", "float64", + "complex64", "complex128"]) + def test_gaussian_gradient_magnitude01(self, dtype, xp): + is_int_dtype = dtype == "int32" + dtype = getattr(xp, dtype) + + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=dtype) * 100 + tmp1 = ndimage.gaussian_filter(array, 1.0, [1, 0]) + tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 1]) + output = ndimage.gaussian_gradient_magnitude(array, 1.0) + expected = tmp1 * tmp1 + tmp2 * tmp2 + + astype = array_namespace(expected).astype + expected_float = astype(expected, xp.float64) if is_int_dtype else expected + expected = astype(xp.sqrt(expected_float), dtype) + xp_assert_close(output, expected, rtol=1e-6, atol=1e-6) + + @skip_xp_backends("jax.numpy", reason="output array is read-only") + @pytest.mark.parametrize('dtype', + ["int32", "float32", "float64", + "complex64", "complex128"]) + def test_gaussian_gradient_magnitude02(self, dtype, xp): + is_int_dtype = dtype == 'int32' + dtype = getattr(xp, dtype) + + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=dtype) * 100 + tmp1 = ndimage.gaussian_filter(array, 1.0, [1, 0]) + tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 1]) + output = xp.zeros(array.shape, dtype=dtype) + ndimage.gaussian_gradient_magnitude(array, 1.0, output) + expected = tmp1 * tmp1 + tmp2 * tmp2 + + astype = array_namespace(expected).astype + fl_expected = astype(expected, xp.float64) if is_int_dtype else expected + + expected = astype(xp.sqrt(fl_expected), dtype) + xp_assert_close(output, expected, rtol=1e-6, atol=1e-6) + + def test_generic_gradient_magnitude01(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=xp.float64) + + def derivative(input, axis, output, mode, cval, a, b): + sigma = [a, b / 2.0] + order = [0] * input.ndim + order[axis] = 1 + return ndimage.gaussian_filter(input, sigma, order, output, mode, cval) + + tmp1 = ndimage.gaussian_gradient_magnitude(array, 1.0) + tmp2 = ndimage.generic_gradient_magnitude( + array, derivative, extra_arguments=(1.0,), + extra_keywords={'b': 2.0}) + assert_array_almost_equal(tmp1, tmp2) + + @skip_xp_backends("cupy", + reason="https://github.com/cupy/cupy/pull/8430", + ) + def test_uniform01(self, xp): + array = xp.asarray([2, 4, 6]) + size = 2 + output = ndimage.uniform_filter1d(array, size, origin=-1) + assert_array_almost_equal(xp.asarray([3, 5, 6]), output) + + @skip_xp_backends("cupy", + reason="https://github.com/cupy/cupy/pull/8430", + ) + def test_uniform01_complex(self, xp): + array = xp.asarray([2 + 1j, 4 + 2j, 6 + 3j], dtype=xp.complex128) + size = 2 + output = ndimage.uniform_filter1d(array, size, origin=-1) + assert_array_almost_equal(xp.real(output), xp.asarray([3., 5, 6])) + assert_array_almost_equal(xp.imag(output), xp.asarray([1.5, 2.5, 3])) + + def test_uniform02(self, xp): + array = xp.asarray([1, 2, 3]) + filter_shape = [0] + output = ndimage.uniform_filter(array, filter_shape) + assert_array_almost_equal(array, output) + + def test_uniform03(self, xp): + array = xp.asarray([1, 2, 3]) + filter_shape = [1] + output = ndimage.uniform_filter(array, filter_shape) + assert_array_almost_equal(array, output) + + @skip_xp_backends("cupy", + reason="https://github.com/cupy/cupy/pull/8430", + ) + def test_uniform04(self, xp): + array = xp.asarray([2, 4, 6]) + filter_shape = [2] + output = ndimage.uniform_filter(array, filter_shape) + assert_array_almost_equal(xp.asarray([2, 3, 5]), output) + + def test_uniform05(self, xp): + array = xp.asarray([]) + filter_shape = [1] + output = ndimage.uniform_filter(array, filter_shape) + assert_array_almost_equal(xp.asarray([]), output) + + @skip_xp_backends("cupy", + reason="https://github.com/cupy/cupy/pull/8430", + ) + @pytest.mark.parametrize('dtype_array', types) + @pytest.mark.parametrize('dtype_output', types) + def test_uniform06(self, dtype_array, dtype_output, xp): + if not (is_numpy(xp) or is_cupy(xp)): + pytest.xfail("output=dtype is numpy-specific") + + dtype_array = getattr(xp, dtype_array) + dtype_output = getattr(xp, dtype_output) + + filter_shape = [2, 2] + array = xp.asarray([[4, 8, 12], + [16, 20, 24]], dtype=dtype_array) + output = ndimage.uniform_filter( + array, filter_shape, output=dtype_output) + assert_array_almost_equal(xp.asarray([[4, 6, 10], [10, 12, 16]]), output) + assert output.dtype.type == dtype_output + + @skip_xp_backends("cupy", + reason="https://github.com/cupy/cupy/pull/8430", + ) + @pytest.mark.parametrize('dtype_array', complex_types) + @pytest.mark.parametrize('dtype_output', complex_types) + def test_uniform06_complex(self, dtype_array, dtype_output, xp): + if not (is_numpy(xp) or is_cupy(xp)): + pytest.xfail("output=dtype is numpy-specific") + + dtype_array = getattr(xp, dtype_array) + dtype_output = getattr(xp, dtype_output) + + filter_shape = [2, 2] + array = xp.asarray([[4, 8 + 5j, 12], + [16, 20, 24]], dtype=dtype_array) + output = ndimage.uniform_filter( + array, filter_shape, output=dtype_output) + assert_array_almost_equal(xp.asarray([[4, 6, 10], [10, 12, 16]]), output.real) + assert output.dtype.type == dtype_output + + def test_minimum_filter01(self, xp): + array = xp.asarray([1, 2, 3, 4, 5]) + filter_shape = xp.asarray([2]) + output = ndimage.minimum_filter(array, filter_shape) + assert_array_almost_equal(xp.asarray([1, 1, 2, 3, 4]), output) + + def test_minimum_filter02(self, xp): + array = xp.asarray([1, 2, 3, 4, 5]) + filter_shape = xp.asarray([3]) + output = ndimage.minimum_filter(array, filter_shape) + assert_array_almost_equal(xp.asarray([1, 1, 2, 3, 4]), output) + + def test_minimum_filter03(self, xp): + array = xp.asarray([3, 2, 5, 1, 4]) + filter_shape = xp.asarray([2]) + output = ndimage.minimum_filter(array, filter_shape) + assert_array_almost_equal(xp.asarray([3, 2, 2, 1, 1]), output) + + def test_minimum_filter04(self, xp): + array = xp.asarray([3, 2, 5, 1, 4]) + filter_shape = xp.asarray([3]) + output = ndimage.minimum_filter(array, filter_shape) + assert_array_almost_equal(xp.asarray([2, 2, 1, 1, 1]), output) + + def test_minimum_filter05(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + filter_shape = xp.asarray([2, 3]) + output = ndimage.minimum_filter(array, filter_shape) + assert_array_almost_equal(xp.asarray([[2, 2, 1, 1, 1], + [2, 2, 1, 1, 1], + [5, 3, 3, 1, 1]]), output) + + @skip_xp_backends("jax.numpy", reason="assignment destination is read-only") + def test_minimum_filter05_overlap(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + filter_shape = xp.asarray([2, 3]) + ndimage.minimum_filter(array, filter_shape, output=array) + assert_array_almost_equal(xp.asarray([[2, 2, 1, 1, 1], + [2, 2, 1, 1, 1], + [5, 3, 3, 1, 1]]), array) + + def test_minimum_filter06(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 1, 1], [1, 1, 1]]) + output = ndimage.minimum_filter(array, footprint=footprint) + assert_array_almost_equal(xp.asarray([[2, 2, 1, 1, 1], + [2, 2, 1, 1, 1], + [5, 3, 3, 1, 1]]), output) + # separable footprint should allow mode sequence + output2 = ndimage.minimum_filter(array, footprint=footprint, + mode=['reflect', 'reflect']) + assert_array_almost_equal(output2, output) + + def test_minimum_filter07(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + output = ndimage.minimum_filter(array, footprint=footprint) + assert_array_almost_equal(xp.asarray([[2, 2, 1, 1, 1], + [2, 3, 1, 3, 1], + [5, 5, 3, 3, 1]]), output) + with assert_raises(RuntimeError): + ndimage.minimum_filter(array, footprint=footprint, + mode=['reflect', 'constant']) + + def test_minimum_filter08(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + output = ndimage.minimum_filter(array, footprint=footprint, origin=-1) + assert_array_almost_equal(xp.asarray([[3, 1, 3, 1, 1], + [5, 3, 3, 1, 1], + [3, 3, 1, 1, 1]]), output) + + def test_minimum_filter09(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + output = ndimage.minimum_filter(array, footprint=footprint, + origin=[-1, 0]) + assert_array_almost_equal(xp.asarray([[2, 3, 1, 3, 1], + [5, 5, 3, 3, 1], + [5, 3, 3, 1, 1]]), output) + + def test_maximum_filter01(self, xp): + array = xp.asarray([1, 2, 3, 4, 5]) + filter_shape = xp.asarray([2]) + output = ndimage.maximum_filter(array, filter_shape) + assert_array_almost_equal(xp.asarray([1, 2, 3, 4, 5]), output) + + def test_maximum_filter02(self, xp): + array = xp.asarray([1, 2, 3, 4, 5]) + filter_shape = xp.asarray([3]) + output = ndimage.maximum_filter(array, filter_shape) + assert_array_almost_equal(xp.asarray([2, 3, 4, 5, 5]), output) + + def test_maximum_filter03(self, xp): + array = xp.asarray([3, 2, 5, 1, 4]) + filter_shape = xp.asarray([2]) + output = ndimage.maximum_filter(array, filter_shape) + assert_array_almost_equal(xp.asarray([3, 3, 5, 5, 4]), output) + + def test_maximum_filter04(self, xp): + array = xp.asarray([3, 2, 5, 1, 4]) + filter_shape = xp.asarray([3]) + output = ndimage.maximum_filter(array, filter_shape) + assert_array_almost_equal(xp.asarray([3, 5, 5, 5, 4]), output) + + def test_maximum_filter05(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + filter_shape = xp.asarray([2, 3]) + output = ndimage.maximum_filter(array, filter_shape) + assert_array_almost_equal(xp.asarray([[3, 5, 5, 5, 4], + [7, 9, 9, 9, 5], + [8, 9, 9, 9, 7]]), output) + + def test_maximum_filter06(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 1, 1], [1, 1, 1]]) + output = ndimage.maximum_filter(array, footprint=footprint) + assert_array_almost_equal(xp.asarray([[3, 5, 5, 5, 4], + [7, 9, 9, 9, 5], + [8, 9, 9, 9, 7]]), output) + # separable footprint should allow mode sequence + output2 = ndimage.maximum_filter(array, footprint=footprint, + mode=['reflect', 'reflect']) + assert_array_almost_equal(output2, output) + + def test_maximum_filter07(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + output = ndimage.maximum_filter(array, footprint=footprint) + assert_array_almost_equal(xp.asarray([[3, 5, 5, 5, 4], + [7, 7, 9, 9, 5], + [7, 9, 8, 9, 7]]), output) + # non-separable footprint should not allow mode sequence + with assert_raises(RuntimeError): + ndimage.maximum_filter(array, footprint=footprint, + mode=['reflect', 'reflect']) + + def test_maximum_filter08(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + output = ndimage.maximum_filter(array, footprint=footprint, origin=-1) + assert_array_almost_equal(xp.asarray([[7, 9, 9, 5, 5], + [9, 8, 9, 7, 5], + [8, 8, 7, 7, 7]]), output) + + def test_maximum_filter09(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + output = ndimage.maximum_filter(array, footprint=footprint, + origin=[-1, 0]) + assert_array_almost_equal(xp.asarray([[7, 7, 9, 9, 5], + [7, 9, 8, 9, 7], + [8, 8, 8, 7, 7]]), output) + + @pytest.mark.parametrize( + 'axes', tuple(itertools.combinations(range(-3, 3), 2)) + ) + @pytest.mark.parametrize( + 'filter_func, kwargs', + [(ndimage.minimum_filter, {}), + (ndimage.maximum_filter, {}), + (ndimage.median_filter, {}), + (ndimage.rank_filter, dict(rank=3)), + (ndimage.percentile_filter, dict(percentile=60))] + ) + def test_minmax_nonseparable_axes(self, filter_func, axes, kwargs, xp): + if is_cupy(xp): + pytest.xfail("https://github.com/cupy/cupy/pull/8339") + + array = xp.arange(6 * 8 * 12, dtype=xp.float32) + array = xp.reshape(array, (6, 8, 12)) + # use 2D triangular footprint because it is non-separable + footprint = xp.asarray(np.tri(5)) + axes = np.asarray(axes) + + if len(set(axes % array.ndim)) != len(axes): + # parametrized cases with duplicate axes raise an error + with pytest.raises(ValueError): + filter_func(array, footprint=footprint, axes=axes, **kwargs) + return + output = filter_func(array, footprint=footprint, axes=axes, **kwargs) + + missing_axis = tuple(set(range(3)) - set(axes % array.ndim))[0] + + expand_dims = array_namespace(footprint).expand_dims + footprint_3d = expand_dims(footprint, axis=missing_axis) + expected = filter_func(array, footprint=footprint_3d, **kwargs) + xp_assert_close(output, expected) + + def test_rank01(self, xp): + array = xp.asarray([1, 2, 3, 4, 5]) + output = ndimage.rank_filter(array, 1, size=2) + xp_assert_equal(array, output) + output = ndimage.percentile_filter(array, 100, size=2) + xp_assert_equal(array, output) + output = ndimage.median_filter(array, 2) + xp_assert_equal(array, output) + + def test_rank02(self, xp): + array = xp.asarray([1, 2, 3, 4, 5]) + output = ndimage.rank_filter(array, 1, size=[3]) + xp_assert_equal(array, output) + output = ndimage.percentile_filter(array, 50, size=3) + xp_assert_equal(array, output) + output = ndimage.median_filter(array, (3,)) + xp_assert_equal(array, output) + + def test_rank03(self, xp): + array = xp.asarray([3, 2, 5, 1, 4]) + output = ndimage.rank_filter(array, 1, size=[2]) + xp_assert_equal(xp.asarray([3, 3, 5, 5, 4]), output) + output = ndimage.percentile_filter(array, 100, size=2) + xp_assert_equal(xp.asarray([3, 3, 5, 5, 4]), output) + + def test_rank04(self, xp): + array = xp.asarray([3, 2, 5, 1, 4]) + expected = xp.asarray([3, 3, 2, 4, 4]) + output = ndimage.rank_filter(array, 1, size=3) + xp_assert_equal(expected, output) + output = ndimage.percentile_filter(array, 50, size=3) + xp_assert_equal(expected, output) + output = ndimage.median_filter(array, size=3) + xp_assert_equal(expected, output) + + def test_rank05(self, xp): + array = xp.asarray([3, 2, 5, 1, 4]) + expected = xp.asarray([3, 3, 2, 4, 4]) + output = ndimage.rank_filter(array, -2, size=3) + xp_assert_equal(expected, output) + + def test_rank06(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]]) + expected = [[2, 2, 1, 1, 1], + [3, 3, 2, 1, 1], + [5, 5, 3, 3, 1]] + expected = xp.asarray(expected) + output = ndimage.rank_filter(array, 1, size=[2, 3]) + xp_assert_equal(expected, output) + output = ndimage.percentile_filter(array, 17, size=(2, 3)) + xp_assert_equal(expected, output) + + @skip_xp_backends("jax.numpy", + reason="assignment destination is read-only", + ) + def test_rank06_overlap(self, xp): + if is_cupy(xp): + pytest.xfail("https://github.com/cupy/cupy/issues/8406") + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]]) + + asarray = array_namespace(array).asarray + array_copy = asarray(array, copy=True) + expected = [[2, 2, 1, 1, 1], + [3, 3, 2, 1, 1], + [5, 5, 3, 3, 1]] + expected = xp.asarray(expected) + ndimage.rank_filter(array, 1, size=[2, 3], output=array) + xp_assert_equal(expected, array) + + ndimage.percentile_filter(array_copy, 17, size=(2, 3), + output=array_copy) + xp_assert_equal(expected, array_copy) + + def test_rank07(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]]) + expected = [[3, 5, 5, 5, 4], + [5, 5, 7, 5, 4], + [6, 8, 8, 7, 5]] + expected = xp.asarray(expected) + output = ndimage.rank_filter(array, -2, size=[2, 3]) + xp_assert_equal(expected, output) + + def test_rank08(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]]) + expected = [[3, 3, 2, 4, 4], + [5, 5, 5, 4, 4], + [5, 6, 7, 5, 5]] + expected = xp.asarray(expected) + output = ndimage.percentile_filter(array, 50.0, size=(2, 3)) + xp_assert_equal(expected, output) + output = ndimage.rank_filter(array, 3, size=(2, 3)) + xp_assert_equal(expected, output) + output = ndimage.median_filter(array, size=(2, 3)) + xp_assert_equal(expected, output) + + # non-separable: does not allow mode sequence + with assert_raises(RuntimeError): + ndimage.percentile_filter(array, 50.0, size=(2, 3), + mode=['reflect', 'constant']) + with assert_raises(RuntimeError): + ndimage.rank_filter(array, 3, size=(2, 3), mode=['reflect']*2) + with assert_raises(RuntimeError): + ndimage.median_filter(array, size=(2, 3), mode=['reflect']*2) + + @pytest.mark.parametrize('dtype', types) + def test_rank09(self, dtype, xp): + dtype = getattr(xp, dtype) + expected = [[3, 3, 2, 4, 4], + [3, 5, 2, 5, 1], + [5, 5, 8, 3, 5]] + expected = xp.asarray(expected) + footprint = xp.asarray([[1, 0, 1], [0, 1, 0]]) + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=dtype) + output = ndimage.rank_filter(array, 1, footprint=footprint) + assert_array_almost_equal(expected, output) + output = ndimage.percentile_filter(array, 35, footprint=footprint) + assert_array_almost_equal(expected, output) + + def test_rank10(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + expected = [[2, 2, 1, 1, 1], + [2, 3, 1, 3, 1], + [5, 5, 3, 3, 1]] + expected = xp.asarray(expected) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + output = ndimage.rank_filter(array, 0, footprint=footprint) + xp_assert_equal(expected, output) + output = ndimage.percentile_filter(array, 0.0, footprint=footprint) + xp_assert_equal(expected, output) + + def test_rank11(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + expected = [[3, 5, 5, 5, 4], + [7, 7, 9, 9, 5], + [7, 9, 8, 9, 7]] + expected = xp.asarray(expected) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + output = ndimage.rank_filter(array, -1, footprint=footprint) + xp_assert_equal(expected, output) + output = ndimage.percentile_filter(array, 100.0, footprint=footprint) + xp_assert_equal(expected, output) + + @pytest.mark.parametrize('dtype', types) + def test_rank12(self, dtype, xp): + if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"): + pytest.xfail("https://github.com/pytorch/pytorch/issues/58734") + + dtype = getattr(xp, dtype) + expected = [[3, 3, 2, 4, 4], + [3, 5, 2, 5, 1], + [5, 5, 8, 3, 5]] + expected = xp.asarray(expected, dtype=dtype) + footprint = xp.asarray([[1, 0, 1], [0, 1, 0]]) + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=dtype) + output = ndimage.rank_filter(array, 1, footprint=footprint) + assert_array_almost_equal(expected, output) + output = ndimage.percentile_filter(array, 50.0, + footprint=footprint) + xp_assert_equal(expected, output) + output = ndimage.median_filter(array, footprint=footprint) + xp_assert_equal(expected, output) + + @pytest.mark.parametrize('dtype', types) + def test_rank13(self, dtype, xp): + if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"): + pytest.xfail("https://github.com/pytorch/pytorch/issues/58734") + + dtype = getattr(xp, dtype) + expected = [[5, 2, 5, 1, 1], + [5, 8, 3, 5, 5], + [6, 6, 5, 5, 5]] + expected = xp.asarray(expected, dtype=dtype) + footprint = xp.asarray([[1, 0, 1], [0, 1, 0]]) + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=dtype) + output = ndimage.rank_filter(array, 1, footprint=footprint, + origin=-1) + xp_assert_equal(expected, output) + + @pytest.mark.parametrize('dtype', types) + def test_rank14(self, dtype, xp): + if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"): + pytest.xfail("https://github.com/pytorch/pytorch/issues/58734") + + dtype = getattr(xp, dtype) + expected = [[3, 5, 2, 5, 1], + [5, 5, 8, 3, 5], + [5, 6, 6, 5, 5]] + expected = xp.asarray(expected, dtype=dtype) + footprint = xp.asarray([[1, 0, 1], [0, 1, 0]]) + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=dtype) + output = ndimage.rank_filter(array, 1, footprint=footprint, + origin=[-1, 0]) + xp_assert_equal(expected, output) + + @pytest.mark.parametrize('dtype', types) + def test_rank15(self, dtype, xp): + if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"): + pytest.xfail("https://github.com/pytorch/pytorch/issues/58734") + + dtype = getattr(xp, dtype) + expected = [[2, 3, 1, 4, 1], + [5, 3, 7, 1, 1], + [5, 5, 3, 3, 3]] + expected = xp.asarray(expected, dtype=dtype) + footprint = xp.asarray([[1, 0, 1], [0, 1, 0]]) + array = xp.asarray([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype=dtype) + output = ndimage.rank_filter(array, 0, footprint=footprint, + origin=[-1, 0]) + xp_assert_equal(expected, output) + + def test_rank16(self, xp): + # test that lists are accepted and interpreted as numpy arrays + array = [3, 2, 5, 1, 4] + # expected values are: median(3, 2, 5) = 3, median(2, 5, 1) = 2, etc + expected = np.asarray([3, 3, 2, 4, 4]) + output = ndimage.rank_filter(array, -2, size=3) + xp_assert_equal(expected, output) + + def test_rank17(self, xp): + array = xp.asarray([3, 2, 5, 1, 4]) + if not hasattr(array, 'flags'): + return + array.flags.writeable = False + expected = xp.asarray([3, 3, 2, 4, 4]) + output = ndimage.rank_filter(array, -2, size=3) + xp_assert_equal(expected, output) + + def test_rank18(self, xp): + # module 'array_api_strict' has no attribute 'float16' + tested_dtypes = ['int8', 'int16', 'int32', 'int64', 'float32', 'float64', + 'uint8', 'uint16', 'uint32', 'uint64'] + for dtype_str in tested_dtypes: + dtype = getattr(xp, dtype_str) + x = xp.asarray([3, 2, 5, 1, 4], dtype=dtype) + y = ndimage.rank_filter(x, -2, size=3) + assert y.dtype == x.dtype + + def test_rank19(self, xp): + # module 'array_api_strict' has no attribute 'float16' + tested_dtypes = ['int8', 'int16', 'int32', 'int64', 'float32', 'float64', + 'uint8', 'uint16', 'uint32', 'uint64'] + for dtype_str in tested_dtypes: + dtype = getattr(xp, dtype_str) + x = xp.asarray([[3, 2, 5, 1, 4], [3, 2, 5, 1, 4]], dtype=dtype) + y = ndimage.rank_filter(x, -2, size=3) + assert y.dtype == x.dtype + + @skip_xp_backends(np_only=True, reason="off-by-ones on alt backends") + @pytest.mark.parametrize('dtype', types) + def test_generic_filter1d01(self, dtype, xp): + weights = xp.asarray([1.1, 2.2, 3.3]) + + if is_cupy(xp): + pytest.xfail("CuPy does not support extra_arguments") + + def _filter_func(input, output, fltr, total): + fltr = fltr / total + for ii in range(input.shape[0] - 2): + output[ii] = input[ii] * fltr[0] + output[ii] += input[ii + 1] * fltr[1] + output[ii] += input[ii + 2] * fltr[2] + a = np.arange(12, dtype=dtype).reshape(3, 4) + a = xp.asarray(a) + dtype = getattr(xp, dtype) + + r1 = ndimage.correlate1d(a, weights / xp.sum(weights), 0, origin=-1) + r2 = ndimage.generic_filter1d( + a, _filter_func, 3, axis=0, origin=-1, + extra_arguments=(weights,), + extra_keywords={'total': xp.sum(weights)}) + assert_array_almost_equal(r1, r2) + + @pytest.mark.parametrize('dtype', types) + def test_generic_filter01(self, dtype, xp): + if is_cupy(xp): + pytest.xfail("CuPy does not support extra_arguments") + if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"): + pytest.xfail("https://github.com/pytorch/pytorch/issues/58734") + + dtype_str = dtype + dtype = getattr(xp, dtype_str) + + filter_ = xp.asarray([[1.0, 2.0], [3.0, 4.0]]) + footprint = xp.asarray([[1.0, 0.0], [0.0, 1.0]]) + cf = xp.asarray([1., 4.]) + + def _filter_func(buffer, weights, total=1.0): + weights = np.asarray(cf) / np.asarray(total) + return np.sum(buffer * weights) + + a = np.arange(12, dtype=dtype_str).reshape(3, 4) + a = xp.asarray(a) + r1 = ndimage.correlate(a, filter_ * footprint) + if dtype_str in float_types: + r1 /= 5 + else: + r1 //= 5 + r2 = ndimage.generic_filter( + a, _filter_func, footprint=footprint, extra_arguments=(cf,), + extra_keywords={'total': xp.sum(cf)}) + assert_array_almost_equal(r1, r2) + + # generic_filter doesn't allow mode sequence + with assert_raises(RuntimeError): + r2 = ndimage.generic_filter( + a, _filter_func, mode=['reflect', 'reflect'], + footprint=footprint, extra_arguments=(cf,), + extra_keywords={'total': xp.sum(cf)}) + + @pytest.mark.parametrize( + 'mode, expected_value', + [('nearest', [1, 1, 2]), + ('wrap', [3, 1, 2]), + ('reflect', [1, 1, 2]), + ('mirror', [2, 1, 2]), + ('constant', [0, 1, 2])] + ) + def test_extend01(self, mode, expected_value, xp): + array = xp.asarray([1, 2, 3]) + weights = xp.asarray([1, 0]) + output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0) + expected_value = xp.asarray(expected_value) + xp_assert_equal(output, expected_value) + + @pytest.mark.parametrize( + 'mode, expected_value', + [('nearest', [1, 1, 1]), + ('wrap', [3, 1, 2]), + ('reflect', [3, 3, 2]), + ('mirror', [1, 2, 3]), + ('constant', [0, 0, 0])] + ) + def test_extend02(self, mode, expected_value, xp): + array = xp.asarray([1, 2, 3]) + weights = xp.asarray([1, 0, 0, 0, 0, 0, 0, 0]) + output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0) + expected_value = xp.asarray(expected_value) + xp_assert_equal(output, expected_value) + + @pytest.mark.parametrize( + 'mode, expected_value', + [('nearest', [2, 3, 3]), + ('wrap', [2, 3, 1]), + ('reflect', [2, 3, 3]), + ('mirror', [2, 3, 2]), + ('constant', [2, 3, 0])] + ) + def test_extend03(self, mode, expected_value, xp): + array = xp.asarray([1, 2, 3]) + weights = xp.asarray([0, 0, 1]) + output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0) + expected_value = xp.asarray(expected_value) + xp_assert_equal(output, expected_value) + + @pytest.mark.parametrize( + 'mode, expected_value', + [('nearest', [3, 3, 3]), + ('wrap', [2, 3, 1]), + ('reflect', [2, 1, 1]), + ('mirror', [1, 2, 3]), + ('constant', [0, 0, 0])] + ) + def test_extend04(self, mode, expected_value, xp): + array = xp.asarray([1, 2, 3]) + weights = xp.asarray([0, 0, 0, 0, 0, 0, 0, 0, 1]) + output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0) + expected_value = xp.asarray(expected_value) + xp_assert_equal(output, expected_value) + + @pytest.mark.parametrize( + 'mode, expected_value', + [('nearest', [[1, 1, 2], [1, 1, 2], [4, 4, 5]]), + ('wrap', [[9, 7, 8], [3, 1, 2], [6, 4, 5]]), + ('reflect', [[1, 1, 2], [1, 1, 2], [4, 4, 5]]), + ('mirror', [[5, 4, 5], [2, 1, 2], [5, 4, 5]]), + ('constant', [[0, 0, 0], [0, 1, 2], [0, 4, 5]])] + ) + def test_extend05(self, mode, expected_value, xp): + array = xp.asarray([[1, 2, 3], + [4, 5, 6], + [7, 8, 9]]) + weights = xp.asarray([[1, 0], [0, 0]]) + output = ndimage.correlate(array, weights, mode=mode, cval=0) + expected_value = xp.asarray(expected_value) + xp_assert_equal(output, expected_value) + + @pytest.mark.parametrize( + 'mode, expected_value', + [('nearest', [[5, 6, 6], [8, 9, 9], [8, 9, 9]]), + ('wrap', [[5, 6, 4], [8, 9, 7], [2, 3, 1]]), + ('reflect', [[5, 6, 6], [8, 9, 9], [8, 9, 9]]), + ('mirror', [[5, 6, 5], [8, 9, 8], [5, 6, 5]]), + ('constant', [[5, 6, 0], [8, 9, 0], [0, 0, 0]])] + ) + def test_extend06(self, mode, expected_value, xp): + array = xp.asarray([[1, 2, 3], + [4, 5, 6], + [7, 8, 9]]) + weights = xp.asarray([[0, 0, 0], [0, 0, 0], [0, 0, 1]]) + output = ndimage.correlate(array, weights, mode=mode, cval=0) + expected_value = xp.asarray(expected_value) + xp_assert_equal(output, expected_value) + + @pytest.mark.parametrize( + 'mode, expected_value', + [('nearest', [3, 3, 3]), + ('wrap', [2, 3, 1]), + ('reflect', [2, 1, 1]), + ('mirror', [1, 2, 3]), + ('constant', [0, 0, 0])] + ) + def test_extend07(self, mode, expected_value, xp): + array = xp.asarray([1, 2, 3]) + weights = xp.asarray([0, 0, 0, 0, 0, 0, 0, 0, 1]) + output = ndimage.correlate(array, weights, mode=mode, cval=0) + expected_value = xp.asarray(expected_value) + xp_assert_equal(output, expected_value) + + @pytest.mark.parametrize( + 'mode, expected_value', + [('nearest', [[3], [3], [3]]), + ('wrap', [[2], [3], [1]]), + ('reflect', [[2], [1], [1]]), + ('mirror', [[1], [2], [3]]), + ('constant', [[0], [0], [0]])] + ) + def test_extend08(self, mode, expected_value, xp): + array = xp.asarray([[1], [2], [3]]) + weights = xp.asarray([[0], [0], [0], [0], [0], [0], [0], [0], [1]]) + output = ndimage.correlate(array, weights, mode=mode, cval=0) + expected_value = xp.asarray(expected_value) + xp_assert_equal(output, expected_value) + + @pytest.mark.parametrize( + 'mode, expected_value', + [('nearest', [3, 3, 3]), + ('wrap', [2, 3, 1]), + ('reflect', [2, 1, 1]), + ('mirror', [1, 2, 3]), + ('constant', [0, 0, 0])] + ) + def test_extend09(self, mode, expected_value, xp): + array = xp.asarray([1, 2, 3]) + weights = xp.asarray([0, 0, 0, 0, 0, 0, 0, 0, 1]) + output = ndimage.correlate(array, weights, mode=mode, cval=0) + expected_value = xp.asarray(expected_value) + xp_assert_equal(output, expected_value) + + @pytest.mark.parametrize( + 'mode, expected_value', + [('nearest', [[3], [3], [3]]), + ('wrap', [[2], [3], [1]]), + ('reflect', [[2], [1], [1]]), + ('mirror', [[1], [2], [3]]), + ('constant', [[0], [0], [0]])] + ) + def test_extend10(self, mode, expected_value, xp): + array = xp.asarray([[1], [2], [3]]) + weights = xp.asarray([[0], [0], [0], [0], [0], [0], [0], [0], [1]]) + output = ndimage.correlate(array, weights, mode=mode, cval=0) + expected_value = xp.asarray(expected_value) + xp_assert_equal(output, expected_value) + + +def test_ticket_701(xp): + if is_cupy(xp): + pytest.xfail("CuPy raises a TypeError.") + + # Test generic filter sizes + arr = xp.asarray(np.arange(4).reshape(2, 2)) + def func(x): + return np.min(x) # NB: np.min not xp.min for callables + res = ndimage.generic_filter(arr, func, size=(1, 1)) + # The following raises an error unless ticket 701 is fixed + res2 = ndimage.generic_filter(arr, func, size=1) + xp_assert_equal(res, res2) + + +def test_gh_5430(): + # At least one of these raises an error unless gh-5430 is + # fixed. In py2k an int is implemented using a C long, so + # which one fails depends on your system. In py3k there is only + # one arbitrary precision integer type, so both should fail. + sigma = np.int32(1) + out = ndimage._ni_support._normalize_sequence(sigma, 1) + assert out == [sigma] + sigma = np.int64(1) + out = ndimage._ni_support._normalize_sequence(sigma, 1) + assert out == [sigma] + # This worked before; make sure it still works + sigma = 1 + out = ndimage._ni_support._normalize_sequence(sigma, 1) + assert out == [sigma] + # This worked before; make sure it still works + sigma = [1, 1] + out = ndimage._ni_support._normalize_sequence(sigma, 2) + assert out == sigma + # Also include the OPs original example to make sure we fixed the issue + x = np.random.normal(size=(256, 256)) + perlin = np.zeros_like(x) + for i in 2**np.arange(6): + perlin += ndimage.gaussian_filter(x, i, mode="wrap") * i**2 + # This also fixes gh-4106, show that the OPs example now runs. + x = np.int64(21) + ndimage._ni_support._normalize_sequence(x, 0) + + +def test_gaussian_kernel1d(xp): + if is_cupy(xp): + pytest.skip("This test tests a private scipy utility.") + radius = 10 + sigma = 2 + sigma2 = sigma * sigma + x = np.arange(-radius, radius + 1, dtype=np.float64) + x = xp.asarray(x) + phi_x = xp.exp(-0.5 * x * x / sigma2) + phi_x /= xp.sum(phi_x) + xp_assert_close(phi_x, + xp.asarray(_gaussian_kernel1d(sigma, 0, radius))) + xp_assert_close(-phi_x * x / sigma2, + xp.asarray(_gaussian_kernel1d(sigma, 1, radius))) + xp_assert_close(phi_x * (x * x / sigma2 - 1) / sigma2, + xp.asarray(_gaussian_kernel1d(sigma, 2, radius))) + xp_assert_close(phi_x * (3 - x * x / sigma2) * x / (sigma2 * sigma2), + xp.asarray(_gaussian_kernel1d(sigma, 3, radius))) + + +def test_orders_gauss(xp): + # Check order inputs to Gaussians + arr = xp.zeros((1,)) + xp_assert_equal(ndimage.gaussian_filter(arr, 1, order=0), xp.asarray([0.])) + xp_assert_equal(ndimage.gaussian_filter(arr, 1, order=3), xp.asarray([0.])) + assert_raises(ValueError, ndimage.gaussian_filter, arr, 1, -1) + xp_assert_equal(ndimage.gaussian_filter1d(arr, 1, axis=-1, order=0), + xp.asarray([0.])) + xp_assert_equal(ndimage.gaussian_filter1d(arr, 1, axis=-1, order=3), + xp.asarray([0.])) + assert_raises(ValueError, ndimage.gaussian_filter1d, arr, 1, -1, -1) + + +def test_valid_origins(xp): + """Regression test for #1311.""" + if is_cupy(xp): + pytest.xfail("CuPy raises a TypeError.") + + def func(x): + return xp.mean(x) + data = xp.asarray([1, 2, 3, 4, 5], dtype=xp.float64) + assert_raises(ValueError, ndimage.generic_filter, data, func, size=3, + origin=2) + assert_raises(ValueError, ndimage.generic_filter1d, data, func, + filter_size=3, origin=2) + assert_raises(ValueError, ndimage.percentile_filter, data, 0.2, size=3, + origin=2) + + for filter in [ndimage.uniform_filter, ndimage.minimum_filter, + ndimage.maximum_filter, ndimage.maximum_filter1d, + ndimage.median_filter, ndimage.minimum_filter1d]: + # This should work, since for size == 3, the valid range for origin is + # -1 to 1. + list(filter(data, 3, origin=-1)) + list(filter(data, 3, origin=1)) + # Just check this raises an error instead of silently accepting or + # segfaulting. + assert_raises(ValueError, filter, data, 3, origin=2) + + +def test_bad_convolve_and_correlate_origins(xp): + """Regression test for gh-822.""" + # Before gh-822 was fixed, these would generate seg. faults or + # other crashes on many system. + assert_raises(ValueError, ndimage.correlate1d, + [0, 1, 2, 3, 4, 5], [1, 1, 2, 0], origin=2) + assert_raises(ValueError, ndimage.correlate, + [0, 1, 2, 3, 4, 5], [0, 1, 2], origin=[2]) + assert_raises(ValueError, ndimage.correlate, + xp.ones((3, 5)), xp.ones((2, 2)), origin=[0, 1]) + + assert_raises(ValueError, ndimage.convolve1d, + xp.arange(10), xp.ones(3), origin=-2) + assert_raises(ValueError, ndimage.convolve, + xp.arange(10), xp.ones(3), origin=[-2]) + assert_raises(ValueError, ndimage.convolve, + xp.ones((3, 5)), xp.ones((2, 2)), origin=[0, -2]) + +@skip_xp_backends("cupy", + reason="https://github.com/cupy/cupy/pull/8430", +) +def test_multiple_modes(xp): + # Test that the filters with multiple mode capabilities for different + # dimensions give the same result as applying a single mode. + arr = xp.asarray([[1., 0., 0.], + [1., 1., 0.], + [0., 0., 0.]]) + + mode1 = 'reflect' + mode2 = ['reflect', 'reflect'] + + xp_assert_equal(ndimage.gaussian_filter(arr, 1, mode=mode1), + ndimage.gaussian_filter(arr, 1, mode=mode2)) + xp_assert_equal(ndimage.prewitt(arr, mode=mode1), + ndimage.prewitt(arr, mode=mode2)) + xp_assert_equal(ndimage.sobel(arr, mode=mode1), + ndimage.sobel(arr, mode=mode2)) + xp_assert_equal(ndimage.laplace(arr, mode=mode1), + ndimage.laplace(arr, mode=mode2)) + xp_assert_equal(ndimage.gaussian_laplace(arr, 1, mode=mode1), + ndimage.gaussian_laplace(arr, 1, mode=mode2)) + xp_assert_equal(ndimage.maximum_filter(arr, size=5, mode=mode1), + ndimage.maximum_filter(arr, size=5, mode=mode2)) + xp_assert_equal(ndimage.minimum_filter(arr, size=5, mode=mode1), + ndimage.minimum_filter(arr, size=5, mode=mode2)) + xp_assert_equal(ndimage.gaussian_gradient_magnitude(arr, 1, mode=mode1), + ndimage.gaussian_gradient_magnitude(arr, 1, mode=mode2)) + xp_assert_equal(ndimage.uniform_filter(arr, 5, mode=mode1), + ndimage.uniform_filter(arr, 5, mode=mode2)) + + +@skip_xp_backends("cupy", reason="https://github.com/cupy/cupy/pull/8430") +@skip_xp_backends("jax.numpy", reason="output array is read-only.") +def test_multiple_modes_sequentially(xp): + # Test that the filters with multiple mode capabilities for different + # dimensions give the same result as applying the filters with + # different modes sequentially + arr = xp.asarray([[1., 0., 0.], + [1., 1., 0.], + [0., 0., 0.]]) + + modes = ['reflect', 'wrap'] + + expected = ndimage.gaussian_filter1d(arr, 1, axis=0, mode=modes[0]) + expected = ndimage.gaussian_filter1d(expected, 1, axis=1, mode=modes[1]) + xp_assert_equal(expected, + ndimage.gaussian_filter(arr, 1, mode=modes)) + + expected = ndimage.uniform_filter1d(arr, 5, axis=0, mode=modes[0]) + expected = ndimage.uniform_filter1d(expected, 5, axis=1, mode=modes[1]) + xp_assert_equal(expected, + ndimage.uniform_filter(arr, 5, mode=modes)) + + expected = ndimage.maximum_filter1d(arr, size=5, axis=0, mode=modes[0]) + expected = ndimage.maximum_filter1d(expected, size=5, axis=1, + mode=modes[1]) + xp_assert_equal(expected, + ndimage.maximum_filter(arr, size=5, mode=modes)) + + expected = ndimage.minimum_filter1d(arr, size=5, axis=0, mode=modes[0]) + expected = ndimage.minimum_filter1d(expected, size=5, axis=1, + mode=modes[1]) + xp_assert_equal(expected, + ndimage.minimum_filter(arr, size=5, mode=modes)) + + +def test_multiple_modes_prewitt(xp): + # Test prewitt filter for multiple extrapolation modes + arr = xp.asarray([[1., 0., 0.], + [1., 1., 0.], + [0., 0., 0.]]) + + expected = xp.asarray([[1., -3., 2.], + [1., -2., 1.], + [1., -1., 0.]]) + + modes = ['reflect', 'wrap'] + + xp_assert_equal(expected, + ndimage.prewitt(arr, mode=modes)) + + +def test_multiple_modes_sobel(xp): + # Test sobel filter for multiple extrapolation modes + arr = xp.asarray([[1., 0., 0.], + [1., 1., 0.], + [0., 0., 0.]]) + + expected = xp.asarray([[1., -4., 3.], + [2., -3., 1.], + [1., -1., 0.]]) + + modes = ['reflect', 'wrap'] + + xp_assert_equal(expected, + ndimage.sobel(arr, mode=modes)) + + +def test_multiple_modes_laplace(xp): + # Test laplace filter for multiple extrapolation modes + arr = xp.asarray([[1., 0., 0.], + [1., 1., 0.], + [0., 0., 0.]]) + + expected = xp.asarray([[-2., 2., 1.], + [-2., -3., 2.], + [1., 1., 0.]]) + + modes = ['reflect', 'wrap'] + + xp_assert_equal(expected, + ndimage.laplace(arr, mode=modes)) + + +def test_multiple_modes_gaussian_laplace(xp): + # Test gaussian_laplace filter for multiple extrapolation modes + arr = xp.asarray([[1., 0., 0.], + [1., 1., 0.], + [0., 0., 0.]]) + + expected = xp.asarray([[-0.28438687, 0.01559809, 0.19773499], + [-0.36630503, -0.20069774, 0.07483620], + [0.15849176, 0.18495566, 0.21934094]]) + + modes = ['reflect', 'wrap'] + + assert_almost_equal(expected, + ndimage.gaussian_laplace(arr, 1, mode=modes)) + + +def test_multiple_modes_gaussian_gradient_magnitude(xp): + # Test gaussian_gradient_magnitude filter for multiple + # extrapolation modes + arr = xp.asarray([[1., 0., 0.], + [1., 1., 0.], + [0., 0., 0.]]) + + expected = xp.asarray([[0.04928965, 0.09745625, 0.06405368], + [0.23056905, 0.14025305, 0.04550846], + [0.19894369, 0.14950060, 0.06796850]]) + + modes = ['reflect', 'wrap'] + + calculated = ndimage.gaussian_gradient_magnitude(arr, 1, mode=modes) + + assert_almost_equal(expected, calculated) + +@skip_xp_backends("cupy", + reason="https://github.com/cupy/cupy/pull/8430", +) +def test_multiple_modes_uniform(xp): + # Test uniform filter for multiple extrapolation modes + arr = xp.asarray([[1., 0., 0.], + [1., 1., 0.], + [0., 0., 0.]]) + + expected = xp.asarray([[0.32, 0.40, 0.48], + [0.20, 0.28, 0.32], + [0.28, 0.32, 0.40]]) + + modes = ['reflect', 'wrap'] + + assert_almost_equal(expected, + ndimage.uniform_filter(arr, 5, mode=modes)) + + +def _count_nonzero(arr): + # XXX: a simplified count_nonzero replacement; replace once + # https://github.com/data-apis/array-api/pull/803/ is in + + # this assumes arr.dtype == xp.bool + xp = array_namespace(arr) + return xp.sum(xp.astype(arr, xp.int8)) + + +def test_gaussian_truncate(xp): + # Test that Gaussian filters can be truncated at different widths. + # These tests only check that the result has the expected number + # of nonzero elements. + arr = np.zeros((100, 100), dtype=np.float64) + arr[50, 50] = 1 + arr = xp.asarray(arr) + num_nonzeros_2 = _count_nonzero(ndimage.gaussian_filter(arr, 5, truncate=2) > 0) + assert num_nonzeros_2 == 21**2 + + num_nonzeros_5 = _count_nonzero( + ndimage.gaussian_filter(arr, 5, truncate=5) > 0 + ) + assert num_nonzeros_5 == 51**2 + + nnz_kw = {'as_tuple': True} if is_torch(xp) else {} + + # Test truncate when sigma is a sequence. + f = ndimage.gaussian_filter(arr, [0.5, 2.5], truncate=3.5) + fpos = f > 0 + n0 = _count_nonzero(xp.any(fpos, axis=0)) + assert n0 == 19 + n1 = _count_nonzero(xp.any(fpos, axis=1)) + assert n1 == 5 + + # Test gaussian_filter1d. + x = np.zeros(51) + x[25] = 1 + x = xp.asarray(x) + f = ndimage.gaussian_filter1d(x, sigma=2, truncate=3.5) + n = _count_nonzero(f > 0) + assert n == 15 + + # Test gaussian_laplace + y = ndimage.gaussian_laplace(x, sigma=2, truncate=3.5) + nonzero_indices = xp.nonzero(y != 0, **nnz_kw)[0] + + n = xp.max(nonzero_indices) - xp.min(nonzero_indices) + 1 + assert n == 15 + + # Test gaussian_gradient_magnitude + y = ndimage.gaussian_gradient_magnitude(x, sigma=2, truncate=3.5) + nonzero_indices = xp.nonzero(y != 0, **nnz_kw)[0] + n = xp.max(nonzero_indices) - xp.min(nonzero_indices) + 1 + assert n == 15 + + +def test_gaussian_radius(xp): + if is_cupy(xp): + pytest.xfail("https://github.com/cupy/cupy/issues/8402") + + # Test that Gaussian filters with radius argument produce the same + # results as the filters with corresponding truncate argument. + # radius = int(truncate * sigma + 0.5) + # Test gaussian_filter1d + x = np.zeros(7) + x[3] = 1 + x = xp.asarray(x) + f1 = ndimage.gaussian_filter1d(x, sigma=2, truncate=1.5) + f2 = ndimage.gaussian_filter1d(x, sigma=2, radius=3) + xp_assert_equal(f1, f2) + + # Test gaussian_filter when sigma is a number. + a = np.zeros((9, 9)) + a[4, 4] = 1 + a = xp.asarray(a) + f1 = ndimage.gaussian_filter(a, sigma=0.5, truncate=3.5) + f2 = ndimage.gaussian_filter(a, sigma=0.5, radius=2) + xp_assert_equal(f1, f2) + + # Test gaussian_filter when sigma is a sequence. + a = np.zeros((50, 50)) + a[25, 25] = 1 + a = xp.asarray(a) + f1 = ndimage.gaussian_filter(a, sigma=[0.5, 2.5], truncate=3.5) + f2 = ndimage.gaussian_filter(a, sigma=[0.5, 2.5], radius=[2, 9]) + xp_assert_equal(f1, f2) + + +def test_gaussian_radius_invalid(xp): + if is_cupy(xp): + pytest.xfail("https://github.com/cupy/cupy/issues/8402") + + # radius must be a nonnegative integer + with assert_raises(ValueError): + ndimage.gaussian_filter1d(xp.zeros(8), sigma=1, radius=-1) + with assert_raises(ValueError): + ndimage.gaussian_filter1d(xp.zeros(8), sigma=1, radius=1.1) + + +@skip_xp_backends("jax.numpy", reason="output array is read-only") +class TestThreading: + def check_func_thread(self, n, fun, args, out): + from threading import Thread + thrds = [Thread(target=fun, args=args, kwargs={'output': out[x, ...]}) + for x in range(n)] + [t.start() for t in thrds] + [t.join() for t in thrds] + + def check_func_serial(self, n, fun, args, out): + for i in range(n): + fun(*args, output=out[i, ...]) + + def test_correlate1d(self, xp): + if is_cupy(xp): + pytest.xfail("XXX thread exception; cannot repro outside of pytest") + + d = np.random.randn(5000) + os = np.empty((4, d.size)) + ot = np.empty_like(os) + d = xp.asarray(d) + os = xp.asarray(os) + ot = xp.asarray(ot) + k = xp.arange(5) + self.check_func_serial(4, ndimage.correlate1d, (d, k), os) + self.check_func_thread(4, ndimage.correlate1d, (d, k), ot) + xp_assert_equal(os, ot) + + def test_correlate(self, xp): + if is_cupy(xp): + pytest.xfail("XXX thread exception; cannot repro outside of pytest") + + d = xp.asarray(np.random.randn(500, 500)) + k = xp.asarray(np.random.randn(10, 10)) + os = xp.empty([4] + list(d.shape)) + ot = xp.empty_like(os) + self.check_func_serial(4, ndimage.correlate, (d, k), os) + self.check_func_thread(4, ndimage.correlate, (d, k), ot) + xp_assert_equal(os, ot) + + def test_median_filter(self, xp): + if is_cupy(xp): + pytest.xfail("XXX thread exception; cannot repro outside of pytest") + + d = xp.asarray(np.random.randn(500, 500)) + os = xp.empty([4] + list(d.shape)) + ot = xp.empty_like(os) + self.check_func_serial(4, ndimage.median_filter, (d, 3), os) + self.check_func_thread(4, ndimage.median_filter, (d, 3), ot) + xp_assert_equal(os, ot) + + def test_uniform_filter1d(self, xp): + if is_cupy(xp): + pytest.xfail("XXX thread exception; cannot repro outside of pytest") + + d = np.random.randn(5000) + os = np.empty((4, d.size)) + ot = np.empty_like(os) + d = xp.asarray(d) + os = xp.asarray(os) + ot = xp.asarray(ot) + self.check_func_serial(4, ndimage.uniform_filter1d, (d, 5), os) + self.check_func_thread(4, ndimage.uniform_filter1d, (d, 5), ot) + xp_assert_equal(os, ot) + + def test_minmax_filter(self, xp): + if is_cupy(xp): + pytest.xfail("XXX thread exception; cannot repro outside of pytest") + + d = xp.asarray(np.random.randn(500, 500)) + os = xp.empty([4] + list(d.shape)) + ot = xp.empty_like(os) + self.check_func_serial(4, ndimage.maximum_filter, (d, 3), os) + self.check_func_thread(4, ndimage.maximum_filter, (d, 3), ot) + xp_assert_equal(os, ot) + self.check_func_serial(4, ndimage.minimum_filter, (d, 3), os) + self.check_func_thread(4, ndimage.minimum_filter, (d, 3), ot) + xp_assert_equal(os, ot) + + +def test_minmaximum_filter1d(xp): + # Regression gh-3898 + in_ = xp.arange(10) + out = ndimage.minimum_filter1d(in_, 1) + xp_assert_equal(in_, out) + out = ndimage.maximum_filter1d(in_, 1) + xp_assert_equal(in_, out) + # Test reflect + out = ndimage.minimum_filter1d(in_, 5, mode='reflect') + xp_assert_equal(xp.asarray([0, 0, 0, 1, 2, 3, 4, 5, 6, 7]), out) + out = ndimage.maximum_filter1d(in_, 5, mode='reflect') + xp_assert_equal(xp.asarray([2, 3, 4, 5, 6, 7, 8, 9, 9, 9]), out) + # Test constant + out = ndimage.minimum_filter1d(in_, 5, mode='constant', cval=-1) + xp_assert_equal(xp.asarray([-1, -1, 0, 1, 2, 3, 4, 5, -1, -1]), out) + out = ndimage.maximum_filter1d(in_, 5, mode='constant', cval=10) + xp_assert_equal(xp.asarray([10, 10, 4, 5, 6, 7, 8, 9, 10, 10]), out) + # Test nearest + out = ndimage.minimum_filter1d(in_, 5, mode='nearest') + xp_assert_equal(xp.asarray([0, 0, 0, 1, 2, 3, 4, 5, 6, 7]), out) + out = ndimage.maximum_filter1d(in_, 5, mode='nearest') + xp_assert_equal(xp.asarray([2, 3, 4, 5, 6, 7, 8, 9, 9, 9]), out) + # Test wrap + out = ndimage.minimum_filter1d(in_, 5, mode='wrap') + xp_assert_equal(xp.asarray([0, 0, 0, 1, 2, 3, 4, 5, 0, 0]), out) + out = ndimage.maximum_filter1d(in_, 5, mode='wrap') + xp_assert_equal(xp.asarray([9, 9, 4, 5, 6, 7, 8, 9, 9, 9]), out) + + +def test_uniform_filter1d_roundoff_errors(xp): + if is_cupy(xp): + pytest.xfail("https://github.com/cupy/cupy/issues/8401") + # gh-6930 + in_ = np.repeat([0, 1, 0], [9, 9, 9]) + in_ = xp.asarray(in_) + + for filter_size in range(3, 10): + out = ndimage.uniform_filter1d(in_, filter_size) + xp_assert_equal(xp.sum(out), xp.asarray(10 - filter_size), check_0d=False) + + +def test_footprint_all_zeros(xp): + # regression test for gh-6876: footprint of all zeros segfaults + arr = xp.asarray(np.random.randint(0, 100, (100, 100))) + kernel = xp.asarray(np.zeros((3, 3), dtype=bool)) + with assert_raises(ValueError): + ndimage.maximum_filter(arr, footprint=kernel) + + +def test_gaussian_filter(xp): + if is_cupy(xp): + pytest.xfail("CuPy does not raise") + + if not hasattr(xp, "float16"): + pytest.xfail(f"{xp} does not have float16") + + # Test gaussian filter with xp.float16 + # gh-8207 + data = xp.asarray([1], dtype=xp.float16) + sigma = 1.0 + with assert_raises(RuntimeError): + ndimage.gaussian_filter(data, sigma) + + +def test_rank_filter_noninteger_rank(xp): + if is_cupy(xp): + pytest.xfail("CuPy does not raise") + + # regression test for issue 9388: ValueError for + # non integer rank when performing rank_filter + arr = xp.asarray(np.random.random((10, 20, 30))) + footprint = xp.asarray(np.ones((1, 1, 10), dtype=bool)) + assert_raises(TypeError, ndimage.rank_filter, arr, 0.5, + footprint=footprint) + + +def test_size_footprint_both_set(xp): + # test for input validation, expect user warning when + # size and footprint is set + with suppress_warnings() as sup: + sup.filter(UserWarning, + "ignoring size because footprint is set") + arr = xp.asarray(np.random.random((10, 20, 30))) + footprint = xp.asarray(np.ones((1, 1, 10), dtype=bool)) + ndimage.rank_filter( + arr, 5, size=2, footprint=footprint + ) + + +@skip_xp_backends(np_only=True, reason='byteorder is numpy-specific') +def test_byte_order_median(xp): + """Regression test for #413: median_filter does not handle bytes orders.""" + a = xp.arange(9, dtype='1 makes sense too + (3, + np.array([0.25266576, 0.30958242, 0.27894721, 0.27894721, 0.27894721, 0.30445588, + 0.31442572, 0.30445588, 0.18015438, 0.14831921, 0.18015438, 0.25754605, + 0.32910465, 0.25754605, 0.17736568, 0.17736568, 0.09089549, 0.22183391, + 0.25266576, 0.30958242]), + ), + (15, + np.array([0.27894721, 0.25266576, 0.25266576, 0.25266576, 0.27894721, 0.27894721, + 0.27894721, 0.27894721, 0.25754605, 0.25754605, 0.22183391, 0.22183391, + 0.25266576, 0.25266576, 0.22183391, 0.22183391, 0.25266576, 0.25266576, + 0.25754605, 0.25754605]), + ), +]) +def test_gh_22250(filter_size, exp): + rng = np.random.default_rng(42) + image = np.zeros((20,)) + noisy_image = image + 0.4 * rng.random(image.shape) + result = ndimage.median_filter(noisy_image, size=filter_size, mode='wrap') + assert_allclose(result, exp) + + +def test_gh_22333(): + x = np.array([272, 58, 67, 163, 463, 608, 87, 108, 1378]) + expected = [58, 67, 87, 108, 163, 108, 108, 108, 87] + actual = ndimage.median_filter(x, size=9, mode='constant') + assert_array_equal(actual, expected) + + +@given(x=npst.arrays(dtype=np.float64, + shape=st.integers(min_value=1, max_value=1000)), + size=st.integers(min_value=1, max_value=50), + mode=st.sampled_from(["constant", "mirror", "wrap", "reflect", + "nearest"]), + ) +def test_gh_22586_crash_property(x, size, mode): + # property-based test for median_filter resilience to hard crashing + ndimage.median_filter(x, size=size, mode=mode) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/tests/test_fourier.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/tests/test_fourier.py new file mode 100644 index 0000000000000000000000000000000000000000..be544eaab9ce00b2e9802cf8f9a4819c4f1d2731 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/tests/test_fourier.py @@ -0,0 +1,189 @@ +import math +import numpy as np + +from scipy._lib._array_api import ( + xp_assert_equal, + assert_array_almost_equal, + assert_almost_equal, + is_cupy, +) + +import pytest + +from scipy import ndimage + +from scipy.conftest import array_api_compatible +skip_xp_backends = pytest.mark.skip_xp_backends +pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends"), + skip_xp_backends(cpu_only=True, exceptions=['cupy', 'jax.numpy'],)] + + +@skip_xp_backends('jax.numpy', reason="jax-ml/jax#23827") +class TestNdimageFourier: + + @pytest.mark.parametrize('shape', [(32, 16), (31, 15), (1, 10)]) + @pytest.mark.parametrize('dtype, dec', [("float32", 6), ("float64", 14)]) + def test_fourier_gaussian_real01(self, shape, dtype, dec, xp): + fft = getattr(xp, 'fft') + + a = np.zeros(shape, dtype=dtype) + a[0, 0] = 1.0 + a = xp.asarray(a) + + a = fft.rfft(a, n=shape[0], axis=0) + a = fft.fft(a, n=shape[1], axis=1) + a = ndimage.fourier_gaussian(a, [5.0, 2.5], shape[0], 0) + a = fft.ifft(a, n=shape[1], axis=1) + a = fft.irfft(a, n=shape[0], axis=0) + assert_almost_equal(ndimage.sum(a), xp.asarray(1), decimal=dec, + check_0d=False) + + @pytest.mark.parametrize('shape', [(32, 16), (31, 15)]) + @pytest.mark.parametrize('dtype, dec', [("complex64", 6), ("complex128", 14)]) + def test_fourier_gaussian_complex01(self, shape, dtype, dec, xp): + fft = getattr(xp, 'fft') + + a = np.zeros(shape, dtype=dtype) + a[0, 0] = 1.0 + a = xp.asarray(a) + + a = fft.fft(a, n=shape[0], axis=0) + a = fft.fft(a, n=shape[1], axis=1) + a = ndimage.fourier_gaussian(a, [5.0, 2.5], -1, 0) + a = fft.ifft(a, n=shape[1], axis=1) + a = fft.ifft(a, n=shape[0], axis=0) + assert_almost_equal(ndimage.sum(xp.real(a)), xp.asarray(1.0), decimal=dec, + check_0d=False) + + @pytest.mark.parametrize('shape', [(32, 16), (31, 15), (1, 10)]) + @pytest.mark.parametrize('dtype, dec', [("float32", 6), ("float64", 14)]) + def test_fourier_uniform_real01(self, shape, dtype, dec, xp): + fft = getattr(xp, 'fft') + + a = np.zeros(shape, dtype=dtype) + a[0, 0] = 1.0 + a = xp.asarray(a) + + a = fft.rfft(a, n=shape[0], axis=0) + a = fft.fft(a, n=shape[1], axis=1) + a = ndimage.fourier_uniform(a, [5.0, 2.5], shape[0], 0) + a = fft.ifft(a, n=shape[1], axis=1) + a = fft.irfft(a, n=shape[0], axis=0) + assert_almost_equal(ndimage.sum(a), xp.asarray(1.0), decimal=dec, + check_0d=False) + + @pytest.mark.parametrize('shape', [(32, 16), (31, 15)]) + @pytest.mark.parametrize('dtype, dec', [("complex64", 6), ("complex128", 14)]) + def test_fourier_uniform_complex01(self, shape, dtype, dec, xp): + fft = getattr(xp, 'fft') + + a = np.zeros(shape, dtype=dtype) + a[0, 0] = 1.0 + a = xp.asarray(a) + + a = fft.fft(a, n=shape[0], axis=0) + a = fft.fft(a, n=shape[1], axis=1) + a = ndimage.fourier_uniform(a, [5.0, 2.5], -1, 0) + a = fft.ifft(a, n=shape[1], axis=1) + a = fft.ifft(a, n=shape[0], axis=0) + assert_almost_equal(ndimage.sum(xp.real(a)), xp.asarray(1.0), decimal=dec, + check_0d=False) + + @pytest.mark.parametrize('shape', [(32, 16), (31, 15)]) + @pytest.mark.parametrize('dtype, dec', [("float32", 4), ("float64", 11)]) + def test_fourier_shift_real01(self, shape, dtype, dec, xp): + fft = getattr(xp, 'fft') + + expected = np.arange(shape[0] * shape[1], dtype=dtype).reshape(shape) + expected = xp.asarray(expected) + + a = fft.rfft(expected, n=shape[0], axis=0) + a = fft.fft(a, n=shape[1], axis=1) + a = ndimage.fourier_shift(a, [1, 1], shape[0], 0) + a = fft.ifft(a, n=shape[1], axis=1) + a = fft.irfft(a, n=shape[0], axis=0) + assert_array_almost_equal(a[1:, 1:], expected[:-1, :-1], decimal=dec) + + @pytest.mark.parametrize('shape', [(32, 16), (31, 15)]) + @pytest.mark.parametrize('dtype, dec', [("complex64", 4), ("complex128", 11)]) + def test_fourier_shift_complex01(self, shape, dtype, dec, xp): + fft = getattr(xp, 'fft') + + expected = np.arange(shape[0] * shape[1], dtype=dtype).reshape(shape) + expected = xp.asarray(expected) + + a = fft.fft(expected, n=shape[0], axis=0) + a = fft.fft(a, n=shape[1], axis=1) + a = ndimage.fourier_shift(a, [1, 1], -1, 0) + a = fft.ifft(a, n=shape[1], axis=1) + a = fft.ifft(a, n=shape[0], axis=0) + assert_array_almost_equal(xp.real(a)[1:, 1:], expected[:-1, :-1], decimal=dec) + assert_array_almost_equal(xp.imag(a), xp.zeros(shape), decimal=dec) + + @pytest.mark.parametrize('shape', [(32, 16), (31, 15), (1, 10)]) + @pytest.mark.parametrize('dtype, dec', [("float32", 5), ("float64", 14)]) + def test_fourier_ellipsoid_real01(self, shape, dtype, dec, xp): + fft = getattr(xp, 'fft') + + a = np.zeros(shape, dtype=dtype) + a[0, 0] = 1.0 + a = xp.asarray(a) + + a = fft.rfft(a, n=shape[0], axis=0) + a = fft.fft(a, n=shape[1], axis=1) + a = ndimage.fourier_ellipsoid(a, [5.0, 2.5], shape[0], 0) + a = fft.ifft(a, n=shape[1], axis=1) + a = fft.irfft(a, n=shape[0], axis=0) + assert_almost_equal(ndimage.sum(a), xp.asarray(1.0), decimal=dec, + check_0d=False) + + @pytest.mark.parametrize('shape', [(32, 16), (31, 15)]) + @pytest.mark.parametrize('dtype, dec', [("complex64", 5), ("complex128", 14)]) + def test_fourier_ellipsoid_complex01(self, shape, dtype, dec, xp): + fft = getattr(xp, 'fft') + + a = np.zeros(shape, dtype=dtype) + a[0, 0] = 1.0 + a = xp.asarray(a) + + a = fft.fft(a, n=shape[0], axis=0) + a = fft.fft(a, n=shape[1], axis=1) + a = ndimage.fourier_ellipsoid(a, [5.0, 2.5], -1, 0) + a = fft.ifft(a, n=shape[1], axis=1) + a = fft.ifft(a, n=shape[0], axis=0) + assert_almost_equal(ndimage.sum(xp.real(a)), xp.asarray(1.0), decimal=dec, + check_0d=False) + + def test_fourier_ellipsoid_unimplemented_ndim(self, xp): + # arrays with ndim > 3 raise NotImplementedError + x = xp.ones((4, 6, 8, 10), dtype=xp.complex128) + with pytest.raises(NotImplementedError): + ndimage.fourier_ellipsoid(x, 3) + + def test_fourier_ellipsoid_1d_complex(self, xp): + # expected result of 1d ellipsoid is the same as for fourier_uniform + for shape in [(32, ), (31, )]: + for type_, dec in zip([xp.complex64, xp.complex128], [5, 14]): + x = xp.ones(shape, dtype=type_) + a = ndimage.fourier_ellipsoid(x, 5, -1, 0) + b = ndimage.fourier_uniform(x, 5, -1, 0) + assert_array_almost_equal(a, b, decimal=dec) + + @pytest.mark.parametrize('shape', [(0, ), (0, 10), (10, 0)]) + @pytest.mark.parametrize('dtype', ["float32", "float64", + "complex64", "complex128"]) + @pytest.mark.parametrize('test_func', + [ndimage.fourier_ellipsoid, + ndimage.fourier_gaussian, + ndimage.fourier_uniform]) + def test_fourier_zero_length_dims(self, shape, dtype, test_func, xp): + if is_cupy(xp): + if (test_func.__name__ == "fourier_ellipsoid" and + math.prod(shape) == 0): + pytest.xfail( + "CuPy's fourier_ellipsoid does not accept size==0 arrays" + ) + dtype = getattr(xp, dtype) + a = xp.ones(shape, dtype=dtype) + b = test_func(a, 3) + xp_assert_equal(a, b) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/tests/test_interpolation.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/tests/test_interpolation.py new file mode 100644 index 0000000000000000000000000000000000000000..51e8441e244f46642a07102e297b4d72513514d0 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/tests/test_interpolation.py @@ -0,0 +1,1484 @@ +import sys + +import numpy as np +from numpy.testing import suppress_warnings +from scipy._lib._array_api import ( + xp_assert_equal, xp_assert_close, + assert_array_almost_equal, +) +from scipy._lib._array_api import is_cupy, is_jax, _asarray, array_namespace + +import pytest +from pytest import raises as assert_raises +import scipy.ndimage as ndimage + +from . import types + +from scipy.conftest import array_api_compatible +skip_xp_backends = pytest.mark.skip_xp_backends +pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends"), + skip_xp_backends(cpu_only=True, exceptions=['cupy', 'jax.numpy'],)] + + +eps = 1e-12 + +ndimage_to_numpy_mode = { + 'mirror': 'reflect', + 'reflect': 'symmetric', + 'grid-mirror': 'symmetric', + 'grid-wrap': 'wrap', + 'nearest': 'edge', + 'grid-constant': 'constant', +} + + +class TestBoundaries: + + @skip_xp_backends("cupy", reason="CuPy does not have geometric_transform") + @pytest.mark.parametrize( + 'mode, expected_value', + [('nearest', [1.5, 2.5, 3.5, 4, 4, 4, 4]), + ('wrap', [1.5, 2.5, 3.5, 1.5, 2.5, 3.5, 1.5]), + ('grid-wrap', [1.5, 2.5, 3.5, 2.5, 1.5, 2.5, 3.5]), + ('mirror', [1.5, 2.5, 3.5, 3.5, 2.5, 1.5, 1.5]), + ('reflect', [1.5, 2.5, 3.5, 4, 3.5, 2.5, 1.5]), + ('constant', [1.5, 2.5, 3.5, -1, -1, -1, -1]), + ('grid-constant', [1.5, 2.5, 3.5, 1.5, -1, -1, -1])] + ) + def test_boundaries(self, mode, expected_value, xp): + def shift(x): + return (x[0] + 0.5,) + + data = xp.asarray([1, 2, 3, 4.]) + xp_assert_equal( + ndimage.geometric_transform(data, shift, cval=-1, mode=mode, + output_shape=(7,), order=1), + xp.asarray(expected_value)) + + @skip_xp_backends("cupy", reason="CuPy does not have geometric_transform") + @pytest.mark.parametrize( + 'mode, expected_value', + [('nearest', [1, 1, 2, 3]), + ('wrap', [3, 1, 2, 3]), + ('grid-wrap', [4, 1, 2, 3]), + ('mirror', [2, 1, 2, 3]), + ('reflect', [1, 1, 2, 3]), + ('constant', [-1, 1, 2, 3]), + ('grid-constant', [-1, 1, 2, 3])] + ) + def test_boundaries2(self, mode, expected_value, xp): + def shift(x): + return (x[0] - 0.9,) + + data = xp.asarray([1, 2, 3, 4]) + xp_assert_equal( + ndimage.geometric_transform(data, shift, cval=-1, mode=mode, + output_shape=(4,)), + xp.asarray(expected_value)) + + @pytest.mark.parametrize('mode', ['mirror', 'reflect', 'grid-mirror', + 'grid-wrap', 'grid-constant', + 'nearest']) + @pytest.mark.parametrize('order', range(6)) + def test_boundary_spline_accuracy(self, mode, order, xp): + """Tests based on examples from gh-2640""" + if (is_jax(xp) and + (mode not in ['mirror', 'reflect', 'constant', 'wrap', 'nearest'] + or order > 1) + ): + pytest.xfail("Jax does not support grid- modes or order > 1") + + np_data = np.arange(-6, 7, dtype=np.float64) + data = xp.asarray(np_data) + x = xp.asarray(np.linspace(-8, 15, num=1000)) + newaxis = array_namespace(x).newaxis + y = ndimage.map_coordinates(data, x[newaxis, ...], order=order, mode=mode) + + # compute expected value using explicit padding via np.pad + npad = 32 + pad_mode = ndimage_to_numpy_mode.get(mode) + padded = xp.asarray(np.pad(np_data, npad, mode=pad_mode)) + coords = xp.asarray(npad + x)[newaxis, ...] + expected = ndimage.map_coordinates(padded, coords, order=order, mode=mode) + + atol = 1e-5 if mode == 'grid-constant' else 1e-12 + xp_assert_close(y, expected, rtol=1e-7, atol=atol) + + +@pytest.mark.parametrize('order', range(2, 6)) +@pytest.mark.parametrize('dtype', types) +class TestSpline: + + def test_spline01(self, dtype, order, xp): + dtype = getattr(xp, dtype) + data = xp.ones([], dtype=dtype) + out = ndimage.spline_filter(data, order=order) + assert out == xp.asarray(1, dtype=out.dtype) + + def test_spline02(self, dtype, order, xp): + dtype = getattr(xp, dtype) + data = xp.asarray([1], dtype=dtype) + out = ndimage.spline_filter(data, order=order) + assert_array_almost_equal(out, xp.asarray([1])) + + @skip_xp_backends(np_only=True, reason='output=dtype is numpy-specific') + def test_spline03(self, dtype, order, xp): + dtype = getattr(xp, dtype) + data = xp.ones([], dtype=dtype) + out = ndimage.spline_filter(data, order, output=dtype) + assert out == xp.asarray(1, dtype=out.dtype) + + def test_spline04(self, dtype, order, xp): + dtype = getattr(xp, dtype) + data = xp.ones([4], dtype=dtype) + out = ndimage.spline_filter(data, order) + assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1])) + + def test_spline05(self, dtype, order, xp): + dtype = getattr(xp, dtype) + data = xp.ones([4, 4], dtype=dtype) + out = ndimage.spline_filter(data, order=order) + expected = xp.asarray([[1, 1, 1, 1], + [1, 1, 1, 1], + [1, 1, 1, 1], + [1, 1, 1, 1]]) + assert_array_almost_equal(out, expected) + + +@skip_xp_backends("cupy", reason="CuPy does not have geometric_transform") +@pytest.mark.parametrize('order', range(0, 6)) +class TestGeometricTransform: + + def test_geometric_transform01(self, order, xp): + data = xp.asarray([1]) + + def mapping(x): + return x + + out = ndimage.geometric_transform(data, mapping, data.shape, + order=order) + assert_array_almost_equal(out, xp.asarray([1], dtype=out.dtype)) + + def test_geometric_transform02(self, order, xp): + data = xp.ones([4]) + + def mapping(x): + return x + + out = ndimage.geometric_transform(data, mapping, data.shape, + order=order) + assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1], dtype=out.dtype)) + + def test_geometric_transform03(self, order, xp): + data = xp.ones([4]) + + def mapping(x): + return (x[0] - 1,) + + out = ndimage.geometric_transform(data, mapping, data.shape, + order=order) + assert_array_almost_equal(out, xp.asarray([0, 1, 1, 1], dtype=out.dtype)) + + def test_geometric_transform04(self, order, xp): + data = xp.asarray([4, 1, 3, 2]) + + def mapping(x): + return (x[0] - 1,) + + out = ndimage.geometric_transform(data, mapping, data.shape, + order=order) + assert_array_almost_equal(out, xp.asarray([0, 4, 1, 3], dtype=out.dtype)) + + @pytest.mark.parametrize('dtype', ["float64", "complex128"]) + def test_geometric_transform05(self, order, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.asarray([[1, 1, 1, 1], + [1, 1, 1, 1], + [1, 1, 1, 1]], dtype=dtype) + expected = xp.asarray([[0, 1, 1, 1], + [0, 1, 1, 1], + [0, 1, 1, 1]], dtype=dtype) + + isdtype = array_namespace(data).isdtype + if isdtype(data.dtype, 'complex floating'): + data -= 1j * data + expected -= 1j * expected + + def mapping(x): + return (x[0], x[1] - 1) + + out = ndimage.geometric_transform(data, mapping, data.shape, + order=order) + assert_array_almost_equal(out, expected) + + def test_geometric_transform06(self, order, xp): + data = xp.asarray([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + + def mapping(x): + return (x[0], x[1] - 1) + + out = ndimage.geometric_transform(data, mapping, data.shape, + order=order) + expected = xp.asarray([[0, 4, 1, 3], + [0, 7, 6, 8], + [0, 3, 5, 3]], dtype=out.dtype) + assert_array_almost_equal(out, expected) + + def test_geometric_transform07(self, order, xp): + data = xp.asarray([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + + def mapping(x): + return (x[0] - 1, x[1]) + + out = ndimage.geometric_transform(data, mapping, data.shape, + order=order) + expected = xp.asarray([[0, 0, 0, 0], + [4, 1, 3, 2], + [7, 6, 8, 5]], dtype=out.dtype) + assert_array_almost_equal(out, expected) + + def test_geometric_transform08(self, order, xp): + data = xp.asarray([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + + def mapping(x): + return (x[0] - 1, x[1] - 1) + + out = ndimage.geometric_transform(data, mapping, data.shape, + order=order) + expected = xp.asarray([[0, 0, 0, 0], + [0, 4, 1, 3], + [0, 7, 6, 8]], dtype=out.dtype) + assert_array_almost_equal(out, expected) + + def test_geometric_transform10(self, order, xp): + data = xp.asarray([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + + def mapping(x): + return (x[0] - 1, x[1] - 1) + + if (order > 1): + filtered = ndimage.spline_filter(data, order=order) + else: + filtered = data + out = ndimage.geometric_transform(filtered, mapping, data.shape, + order=order, prefilter=False) + expected = xp.asarray([[0, 0, 0, 0], + [0, 4, 1, 3], + [0, 7, 6, 8]], dtype=out.dtype) + assert_array_almost_equal(out, expected) + + def test_geometric_transform13(self, order, xp): + data = xp.ones([2], dtype=xp.float64) + + def mapping(x): + return (x[0] // 2,) + + out = ndimage.geometric_transform(data, mapping, [4], order=order) + assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1], dtype=out.dtype)) + + def test_geometric_transform14(self, order, xp): + data = xp.asarray([1, 5, 2, 6, 3, 7, 4, 4]) + + def mapping(x): + return (2 * x[0],) + + out = ndimage.geometric_transform(data, mapping, [4], order=order) + assert_array_almost_equal(out, xp.asarray([1, 2, 3, 4], dtype=out.dtype)) + + def test_geometric_transform15(self, order, xp): + data = [1, 2, 3, 4] + + def mapping(x): + return (x[0] / 2,) + + out = ndimage.geometric_transform(data, mapping, [8], order=order) + assert_array_almost_equal(out[::2], [1, 2, 3, 4]) + + def test_geometric_transform16(self, order, xp): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9.0, 10, 11, 12]] + + def mapping(x): + return (x[0], x[1] * 2) + + out = ndimage.geometric_transform(data, mapping, (3, 2), + order=order) + assert_array_almost_equal(out, [[1, 3], [5, 7], [9, 11]]) + + def test_geometric_transform17(self, order, xp): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + + def mapping(x): + return (x[0] * 2, x[1]) + + out = ndimage.geometric_transform(data, mapping, (1, 4), + order=order) + assert_array_almost_equal(out, [[1, 2, 3, 4]]) + + def test_geometric_transform18(self, order, xp): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + + def mapping(x): + return (x[0] * 2, x[1] * 2) + + out = ndimage.geometric_transform(data, mapping, (1, 2), + order=order) + assert_array_almost_equal(out, [[1, 3]]) + + def test_geometric_transform19(self, order, xp): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + + def mapping(x): + return (x[0], x[1] / 2) + + out = ndimage.geometric_transform(data, mapping, (3, 8), + order=order) + assert_array_almost_equal(out[..., ::2], data) + + def test_geometric_transform20(self, order, xp): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + + def mapping(x): + return (x[0] / 2, x[1]) + + out = ndimage.geometric_transform(data, mapping, (6, 4), + order=order) + assert_array_almost_equal(out[::2, ...], data) + + def test_geometric_transform21(self, order, xp): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + + def mapping(x): + return (x[0] / 2, x[1] / 2) + + out = ndimage.geometric_transform(data, mapping, (6, 8), + order=order) + assert_array_almost_equal(out[::2, ::2], data) + + def test_geometric_transform22(self, order, xp): + data = xp.asarray([[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]], dtype=xp.float64) + + def mapping1(x): + return (x[0] / 2, x[1] / 2) + + def mapping2(x): + return (x[0] * 2, x[1] * 2) + + out = ndimage.geometric_transform(data, mapping1, + (6, 8), order=order) + out = ndimage.geometric_transform(out, mapping2, + (3, 4), order=order) + assert_array_almost_equal(out, data) + + def test_geometric_transform23(self, order, xp): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + + def mapping(x): + return (1, x[0] * 2) + + out = ndimage.geometric_transform(data, mapping, (2,), order=order) + out = out.astype(np.int32) + assert_array_almost_equal(out, [5, 7]) + + def test_geometric_transform24(self, order, xp): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + + def mapping(x, a, b): + return (a, x[0] * b) + + out = ndimage.geometric_transform( + data, mapping, (2,), order=order, extra_arguments=(1,), + extra_keywords={'b': 2}) + assert_array_almost_equal(out, [5, 7]) + + +@skip_xp_backends("cupy", reason="CuPy does not have geometric_transform") +class TestGeometricTransformExtra: + + def test_geometric_transform_grid_constant_order1(self, xp): + + # verify interpolation outside the original bounds + x = xp.asarray([[1, 2, 3], + [4, 5, 6]], dtype=xp.float64) + + def mapping(x): + return (x[0] - 0.5), (x[1] - 0.5) + + expected_result = xp.asarray([[0.25, 0.75, 1.25], + [1.25, 3.00, 4.00]]) + assert_array_almost_equal( + ndimage.geometric_transform(x, mapping, mode='grid-constant', + order=1), + expected_result, + ) + + @pytest.mark.parametrize('mode', ['grid-constant', 'grid-wrap', 'nearest', + 'mirror', 'reflect']) + @pytest.mark.parametrize('order', range(6)) + def test_geometric_transform_vs_padded(self, order, mode, xp): + + def mapping(x): + return (x[0] - 0.4), (x[1] + 2.3) + + # Manually pad and then extract center after the transform to get the + # expected result. + x = np.arange(144, dtype=float).reshape(12, 12) + npad = 24 + pad_mode = ndimage_to_numpy_mode.get(mode) + x_padded = np.pad(x, npad, mode=pad_mode) + + x = xp.asarray(x) + x_padded = xp.asarray(x_padded) + + center_slice = tuple([slice(npad, -npad)] * x.ndim) + expected_result = ndimage.geometric_transform( + x_padded, mapping, mode=mode, order=order)[center_slice] + + xp_assert_close( + ndimage.geometric_transform(x, mapping, mode=mode, + order=order), + expected_result, + rtol=1e-7, + ) + + @skip_xp_backends(np_only=True, reason='endianness is numpy-specific') + def test_geometric_transform_endianness_with_output_parameter(self, xp): + # geometric transform given output ndarray or dtype with + # non-native endianness. see issue #4127 + data = np.asarray([1]) + + def mapping(x): + return x + + for out in [data.dtype, data.dtype.newbyteorder(), + np.empty_like(data), + np.empty_like(data).astype(data.dtype.newbyteorder())]: + returned = ndimage.geometric_transform(data, mapping, data.shape, + output=out) + result = out if returned is None else returned + assert_array_almost_equal(result, [1]) + + @skip_xp_backends(np_only=True, reason='string `output` is numpy-specific') + def test_geometric_transform_with_string_output(self, xp): + data = xp.asarray([1]) + + def mapping(x): + return x + + out = ndimage.geometric_transform(data, mapping, output='f') + assert out.dtype is np.dtype('f') + assert_array_almost_equal(out, [1]) + + +class TestMapCoordinates: + + @pytest.mark.parametrize('order', range(0, 6)) + @pytest.mark.parametrize('dtype', [np.float64, np.complex128]) + def test_map_coordinates01(self, order, dtype, xp): + if is_jax(xp) and order > 1: + pytest.xfail("jax map_coordinates requires order <= 1") + + data = xp.asarray([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + expected = xp.asarray([[0, 0, 0, 0], + [0, 4, 1, 3], + [0, 7, 6, 8]]) + isdtype = array_namespace(data).isdtype + if isdtype(data.dtype, 'complex floating'): + data = data - 1j * data + expected = expected - 1j * expected + + idx = np.indices(data.shape) + idx -= 1 + idx = xp.asarray(idx) + + out = ndimage.map_coordinates(data, idx, order=order) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_map_coordinates02(self, order, xp): + if is_jax(xp): + if order > 1: + pytest.xfail("jax map_coordinates requires order <= 1") + if order == 1: + pytest.xfail("output differs. jax bug?") + + data = xp.asarray([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + idx = np.indices(data.shape, np.float64) + idx -= 0.5 + idx = xp.asarray(idx) + + out1 = ndimage.shift(data, 0.5, order=order) + out2 = ndimage.map_coordinates(data, idx, order=order) + assert_array_almost_equal(out1, out2) + + @skip_xp_backends("jax.numpy", reason="`order` is required in jax") + def test_map_coordinates03(self, xp): + data = _asarray([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]], order='F', xp=xp) + idx = np.indices(data.shape) - 1 + idx = xp.asarray(idx) + out = ndimage.map_coordinates(data, idx) + expected = xp.asarray([[0, 0, 0, 0], + [0, 4, 1, 3], + [0, 7, 6, 8]]) + assert_array_almost_equal(out, expected) + assert_array_almost_equal(out, ndimage.shift(data, (1, 1))) + + idx = np.indices(data[::2, ...].shape) - 1 + idx = xp.asarray(idx) + out = ndimage.map_coordinates(data[::2, ...], idx) + assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0], + [0, 4, 1, 3]])) + assert_array_almost_equal(out, ndimage.shift(data[::2, ...], (1, 1))) + + idx = np.indices(data[:, ::2].shape) - 1 + idx = xp.asarray(idx) + out = ndimage.map_coordinates(data[:, ::2], idx) + assert_array_almost_equal(out, xp.asarray([[0, 0], [0, 4], [0, 7]])) + assert_array_almost_equal(out, ndimage.shift(data[:, ::2], (1, 1))) + + @skip_xp_backends(np_only=True) + def test_map_coordinates_endianness_with_output_parameter(self, xp): + # output parameter given as array or dtype with either endianness + # see issue #4127 + # NB: NumPy-only + + data = np.asarray([[1, 2], [7, 6]]) + expected = np.asarray([[0, 0], [0, 1]]) + idx = np.indices(data.shape) + idx -= 1 + for out in [ + data.dtype, + data.dtype.newbyteorder(), + np.empty_like(expected), + np.empty_like(expected).astype(expected.dtype.newbyteorder()) + ]: + returned = ndimage.map_coordinates(data, idx, output=out) + result = out if returned is None else returned + assert_array_almost_equal(result, expected) + + @skip_xp_backends(np_only=True, reason='string `output` is numpy-specific') + def test_map_coordinates_with_string_output(self, xp): + data = xp.asarray([[1]]) + idx = np.indices(data.shape) + idx = xp.asarray(idx) + out = ndimage.map_coordinates(data, idx, output='f') + assert out.dtype is np.dtype('f') + assert_array_almost_equal(out, xp.asarray([[1]])) + + @pytest.mark.skipif('win32' in sys.platform or np.intp(0).itemsize < 8, + reason='do not run on 32 bit or windows ' + '(no sparse memory)') + def test_map_coordinates_large_data(self, xp): + # check crash on large data + try: + n = 30000 + # a = xp.reshape(xp.empty(n**2, dtype=xp.float32), (n, n)) + a = np.empty(n**2, dtype=np.float32).reshape(n, n) + # fill the part we might read + a[n - 3:, n - 3:] = 0 + ndimage.map_coordinates( + xp.asarray(a), xp.asarray([[n - 1.5], [n - 1.5]]), order=1 + ) + except MemoryError as e: + raise pytest.skip('Not enough memory available') from e + + +class TestAffineTransform: + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform01(self, order, xp): + data = xp.asarray([1]) + out = ndimage.affine_transform(data, xp.asarray([[1]]), order=order) + assert_array_almost_equal(out, xp.asarray([1])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform02(self, order, xp): + data = xp.ones([4]) + out = ndimage.affine_transform(data, xp.asarray([[1]]), order=order) + assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform03(self, order, xp): + data = xp.ones([4]) + out = ndimage.affine_transform(data, xp.asarray([[1]]), -1, order=order) + assert_array_almost_equal(out, xp.asarray([0, 1, 1, 1])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform04(self, order, xp): + data = xp.asarray([4, 1, 3, 2]) + out = ndimage.affine_transform(data, xp.asarray([[1]]), -1, order=order) + assert_array_almost_equal(out, xp.asarray([0, 4, 1, 3])) + + @pytest.mark.parametrize('order', range(0, 6)) + @pytest.mark.parametrize('dtype', ["float64", "complex128"]) + def test_affine_transform05(self, order, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.asarray([[1, 1, 1, 1], + [1, 1, 1, 1], + [1, 1, 1, 1]], dtype=dtype) + expected = xp.asarray([[0, 1, 1, 1], + [0, 1, 1, 1], + [0, 1, 1, 1]], dtype=dtype) + isdtype = array_namespace(data).isdtype + if isdtype(data.dtype, 'complex floating'): + data -= 1j * data + expected -= 1j * expected + out = ndimage.affine_transform(data, xp.asarray([[1, 0], [0, 1]]), + [0, -1], order=order) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform06(self, order, xp): + data = xp.asarray([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + out = ndimage.affine_transform(data, xp.asarray([[1, 0], [0, 1]]), + [0, -1], order=order) + assert_array_almost_equal(out, xp.asarray([[0, 4, 1, 3], + [0, 7, 6, 8], + [0, 3, 5, 3]])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform07(self, order, xp): + data = xp.asarray([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + out = ndimage.affine_transform(data, xp.asarray([[1, 0], [0, 1]]), + [-1, 0], order=order) + assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0], + [4, 1, 3, 2], + [7, 6, 8, 5]])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform08(self, order, xp): + data = xp.asarray([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + out = ndimage.affine_transform(data, xp.asarray([[1, 0], [0, 1]]), + [-1, -1], order=order) + assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0], + [0, 4, 1, 3], + [0, 7, 6, 8]])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform09(self, order, xp): + data = xp.asarray([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + if (order > 1): + filtered = ndimage.spline_filter(data, order=order) + else: + filtered = data + out = ndimage.affine_transform(filtered, xp.asarray([[1, 0], [0, 1]]), + [-1, -1], order=order, + prefilter=False) + assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0], + [0, 4, 1, 3], + [0, 7, 6, 8]])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform10(self, order, xp): + data = xp.ones([2], dtype=xp.float64) + out = ndimage.affine_transform(data, xp.asarray([[0.5]]), output_shape=(4,), + order=order) + assert_array_almost_equal(out, xp.asarray([1, 1, 1, 0])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform11(self, order, xp): + data = xp.asarray([1, 5, 2, 6, 3, 7, 4, 4]) + out = ndimage.affine_transform(data, xp.asarray([[2]]), 0, (4,), order=order) + assert_array_almost_equal(out, xp.asarray([1, 2, 3, 4])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform12(self, order, xp): + data = xp.asarray([1, 2, 3, 4]) + out = ndimage.affine_transform(data, xp.asarray([[0.5]]), 0, (8,), order=order) + assert_array_almost_equal(out[::2], xp.asarray([1, 2, 3, 4])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform13(self, order, xp): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9.0, 10, 11, 12]] + data = xp.asarray(data) + out = ndimage.affine_transform(data, xp.asarray([[1, 0], [0, 2]]), 0, (3, 2), + order=order) + assert_array_almost_equal(out, xp.asarray([[1, 3], [5, 7], [9, 11]])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform14(self, order, xp): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + data = xp.asarray(data) + out = ndimage.affine_transform(data, xp.asarray([[2, 0], [0, 1]]), 0, (1, 4), + order=order) + assert_array_almost_equal(out, xp.asarray([[1, 2, 3, 4]])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform15(self, order, xp): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + data = xp.asarray(data) + out = ndimage.affine_transform(data, xp.asarray([[2, 0], [0, 2]]), 0, (1, 2), + order=order) + assert_array_almost_equal(out, xp.asarray([[1, 3]])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform16(self, order, xp): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + data = xp.asarray(data) + out = ndimage.affine_transform(data, xp.asarray([[1, 0.0], [0, 0.5]]), 0, + (3, 8), order=order) + assert_array_almost_equal(out[..., ::2], data) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform17(self, order, xp): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + data = xp.asarray(data) + out = ndimage.affine_transform(data, xp.asarray([[0.5, 0], [0, 1]]), 0, + (6, 4), order=order) + assert_array_almost_equal(out[::2, ...], data) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform18(self, order, xp): + data = xp.asarray([[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]]) + out = ndimage.affine_transform(data, xp.asarray([[0.5, 0], [0, 0.5]]), 0, + (6, 8), order=order) + assert_array_almost_equal(out[::2, ::2], data) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform19(self, order, xp): + data = xp.asarray([[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]], dtype=xp.float64) + out = ndimage.affine_transform(data, xp.asarray([[0.5, 0], [0, 0.5]]), 0, + (6, 8), order=order) + out = ndimage.affine_transform(out, xp.asarray([[2.0, 0], [0, 2.0]]), 0, + (3, 4), order=order) + assert_array_almost_equal(out, data) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform20(self, order, xp): + if is_cupy(xp): + pytest.xfail("https://github.com/cupy/cupy/issues/8394") + + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + data = xp.asarray(data) + out = ndimage.affine_transform(data, xp.asarray([[0], [2]]), 0, (2,), + order=order) + assert_array_almost_equal(out, xp.asarray([1, 3])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform21(self, order, xp): + if is_cupy(xp): + pytest.xfail("https://github.com/cupy/cupy/issues/8394") + + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + data = xp.asarray(data) + out = ndimage.affine_transform(data, xp.asarray([[2], [0]]), 0, (2,), + order=order) + assert_array_almost_equal(out, xp.asarray([1, 9])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform22(self, order, xp): + # shift and offset interaction; see issue #1547 + data = xp.asarray([4, 1, 3, 2]) + out = ndimage.affine_transform(data, xp.asarray([[2]]), [-1], (3,), + order=order) + assert_array_almost_equal(out, xp.asarray([0, 1, 2])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform23(self, order, xp): + # shift and offset interaction; see issue #1547 + data = xp.asarray([4, 1, 3, 2]) + out = ndimage.affine_transform(data, xp.asarray([[0.5]]), [-1], (8,), + order=order) + assert_array_almost_equal(out[::2], xp.asarray([0, 4, 1, 3])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform24(self, order, xp): + # consistency between diagonal and non-diagonal case; see issue #1547 + data = xp.asarray([4, 1, 3, 2]) + with suppress_warnings() as sup: + sup.filter(UserWarning, + 'The behavior of affine_transform with a 1-D array .* ' + 'has changed') + out1 = ndimage.affine_transform(data, xp.asarray([2]), -1, order=order) + out2 = ndimage.affine_transform(data, xp.asarray([[2]]), -1, order=order) + assert_array_almost_equal(out1, out2) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform25(self, order, xp): + # consistency between diagonal and non-diagonal case; see issue #1547 + data = xp.asarray([4, 1, 3, 2]) + with suppress_warnings() as sup: + sup.filter(UserWarning, + 'The behavior of affine_transform with a 1-D array .* ' + 'has changed') + out1 = ndimage.affine_transform(data, xp.asarray([0.5]), -1, order=order) + out2 = ndimage.affine_transform(data, xp.asarray([[0.5]]), -1, order=order) + assert_array_almost_equal(out1, out2) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform26(self, order, xp): + # test homogeneous coordinates + data = xp.asarray([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + if (order > 1): + filtered = ndimage.spline_filter(data, order=order) + else: + filtered = data + tform_original = xp.eye(2) + offset_original = -xp.ones((2, 1)) + + concat = array_namespace(tform_original, offset_original).concat + tform_h1 = concat((tform_original, offset_original), axis=1) # hstack + tform_h2 = concat( (tform_h1, xp.asarray([[0.0, 0, 1]])), axis=0) # vstack + + offs = [float(x) for x in xp.reshape(offset_original, (-1,))] + + out1 = ndimage.affine_transform(filtered, tform_original, + offs, + order=order, prefilter=False) + out2 = ndimage.affine_transform(filtered, tform_h1, order=order, + prefilter=False) + out3 = ndimage.affine_transform(filtered, tform_h2, order=order, + prefilter=False) + for out in [out1, out2, out3]: + assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0], + [0, 4, 1, 3], + [0, 7, 6, 8]])) + + def test_affine_transform27(self, xp): + if is_cupy(xp): + pytest.xfail("CuPy does not raise") + + # test valid homogeneous transformation matrix + data = xp.asarray([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + concat = array_namespace(data).concat + tform_h1 = concat( (xp.eye(2), -xp.ones((2, 1))) , axis=1) # vstack + tform_h2 = concat((tform_h1, xp.asarray([[5.0, 2, 1]])), axis=0) # hstack + + assert_raises(ValueError, ndimage.affine_transform, data, tform_h2) + + @skip_xp_backends(np_only=True, reason='byteorder is numpy-specific') + def test_affine_transform_1d_endianness_with_output_parameter(self, xp): + # 1d affine transform given output ndarray or dtype with + # either endianness. see issue #7388 + data = xp.ones((2, 2)) + for out in [xp.empty_like(data), + xp.empty_like(data).astype(data.dtype.newbyteorder()), + data.dtype, data.dtype.newbyteorder()]: + with suppress_warnings() as sup: + sup.filter(UserWarning, + 'The behavior of affine_transform with a 1-D array ' + '.* has changed') + matrix = xp.asarray([1, 1]) + returned = ndimage.affine_transform(data, matrix, output=out) + result = out if returned is None else returned + assert_array_almost_equal(result, xp.asarray([[1, 1], [1, 1]])) + + @skip_xp_backends(np_only=True, reason='byteorder is numpy-specific') + def test_affine_transform_multi_d_endianness_with_output_parameter(self, xp): + # affine transform given output ndarray or dtype with either endianness + # see issue #4127 + # NB: byteorder is numpy-specific + data = np.asarray([1]) + for out in [data.dtype, data.dtype.newbyteorder(), + np.empty_like(data), + np.empty_like(data).astype(data.dtype.newbyteorder())]: + returned = ndimage.affine_transform(data, np.asarray([[1]]), output=out) + result = out if returned is None else returned + assert_array_almost_equal(result, np.asarray([1])) + + @skip_xp_backends(np_only=True, + reason='`out` of a different size is numpy-specific' + ) + def test_affine_transform_output_shape(self, xp): + # don't require output_shape when out of a different size is given + data = xp.arange(8, dtype=xp.float64) + out = xp.ones((16,)) + + ndimage.affine_transform(data, xp.asarray([[1]]), output=out) + assert_array_almost_equal(out[:8], data) + + # mismatched output shape raises an error + with pytest.raises(RuntimeError): + ndimage.affine_transform( + data, [[1]], output=out, output_shape=(12,)) + + @skip_xp_backends(np_only=True, reason='string `output` is numpy-specific') + def test_affine_transform_with_string_output(self, xp): + data = xp.asarray([1]) + out = ndimage.affine_transform(data, xp.asarray([[1]]), output='f') + assert out.dtype is np.dtype('f') + assert_array_almost_equal(out, xp.asarray([1])) + + @pytest.mark.parametrize('shift', + [(1, 0), (0, 1), (-1, 1), (3, -5), (2, 7)]) + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform_shift_via_grid_wrap(self, shift, order, xp): + # For mode 'grid-wrap', integer shifts should match np.roll + x = np.asarray([[0, 1], + [2, 3]]) + affine = np.zeros((2, 3)) + affine[:2, :2] = np.eye(2) + affine[:, 2] = np.asarray(shift) + + expected = np.roll(x, shift, axis=(0, 1)) + + x = xp.asarray(x) + affine = xp.asarray(affine) + expected = xp.asarray(expected) + + assert_array_almost_equal( + ndimage.affine_transform(x, affine, mode='grid-wrap', order=order), + expected + ) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform_shift_reflect(self, order, xp): + # shift by x.shape results in reflection + x = np.asarray([[0, 1, 2], + [3, 4, 5]]) + expected = x[::-1, ::-1].copy() # strides >0 for torch + x = xp.asarray(x) + expected = xp.asarray(expected) + + affine = np.zeros([2, 3]) + affine[:2, :2] = np.eye(2) + affine[:, 2] = np.asarray(x.shape) + affine = xp.asarray(affine) + + assert_array_almost_equal( + ndimage.affine_transform(x, affine, mode='reflect', order=order), + expected, + ) + + +class TestShift: + + @pytest.mark.parametrize('order', range(0, 6)) + def test_shift01(self, order, xp): + data = xp.asarray([1]) + out = ndimage.shift(data, [1], order=order) + assert_array_almost_equal(out, xp.asarray([0])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_shift02(self, order, xp): + data = xp.ones([4]) + out = ndimage.shift(data, [1], order=order) + assert_array_almost_equal(out, xp.asarray([0, 1, 1, 1])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_shift03(self, order, xp): + data = xp.ones([4]) + out = ndimage.shift(data, -1, order=order) + assert_array_almost_equal(out, xp.asarray([1, 1, 1, 0])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_shift04(self, order, xp): + data = xp.asarray([4, 1, 3, 2]) + out = ndimage.shift(data, 1, order=order) + assert_array_almost_equal(out, xp.asarray([0, 4, 1, 3])) + + @pytest.mark.parametrize('order', range(0, 6)) + @pytest.mark.parametrize('dtype', ["float64", "complex128"]) + def test_shift05(self, order, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.asarray([[1, 1, 1, 1], + [1, 1, 1, 1], + [1, 1, 1, 1]], dtype=dtype) + expected = xp.asarray([[0, 1, 1, 1], + [0, 1, 1, 1], + [0, 1, 1, 1]], dtype=dtype) + isdtype = array_namespace(data).isdtype + if isdtype(data.dtype, 'complex floating'): + data -= 1j * data + expected -= 1j * expected + out = ndimage.shift(data, [0, 1], order=order) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('order', range(0, 6)) + @pytest.mark.parametrize('mode', ['constant', 'grid-constant']) + @pytest.mark.parametrize('dtype', ['float64', 'complex128']) + def test_shift_with_nonzero_cval(self, order, mode, dtype, xp): + data = np.asarray([[1, 1, 1, 1], + [1, 1, 1, 1], + [1, 1, 1, 1]], dtype=dtype) + + expected = np.asarray([[0, 1, 1, 1], + [0, 1, 1, 1], + [0, 1, 1, 1]], dtype=dtype) + + isdtype = array_namespace(data).isdtype + if isdtype(data.dtype, 'complex floating'): + data -= 1j * data + expected -= 1j * expected + cval = 5.0 + expected[:, 0] = cval # specific to shift of [0, 1] used below + + data = xp.asarray(data) + expected = xp.asarray(expected) + out = ndimage.shift(data, [0, 1], order=order, mode=mode, cval=cval) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_shift06(self, order, xp): + data = xp.asarray([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + out = ndimage.shift(data, [0, 1], order=order) + assert_array_almost_equal(out, xp.asarray([[0, 4, 1, 3], + [0, 7, 6, 8], + [0, 3, 5, 3]])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_shift07(self, order, xp): + data = xp.asarray([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + out = ndimage.shift(data, [1, 0], order=order) + assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0], + [4, 1, 3, 2], + [7, 6, 8, 5]])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_shift08(self, order, xp): + data = xp.asarray([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + out = ndimage.shift(data, [1, 1], order=order) + assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0], + [0, 4, 1, 3], + [0, 7, 6, 8]])) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_shift09(self, order, xp): + data = xp.asarray([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + if (order > 1): + filtered = ndimage.spline_filter(data, order=order) + else: + filtered = data + out = ndimage.shift(filtered, [1, 1], order=order, prefilter=False) + assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0], + [0, 4, 1, 3], + [0, 7, 6, 8]])) + + @pytest.mark.parametrize('shift', + [(1, 0), (0, 1), (-1, 1), (3, -5), (2, 7)]) + @pytest.mark.parametrize('order', range(0, 6)) + def test_shift_grid_wrap(self, shift, order, xp): + # For mode 'grid-wrap', integer shifts should match np.roll + x = np.asarray([[0, 1], + [2, 3]]) + expected = np.roll(x, shift, axis=(0,1)) + + x = xp.asarray(x) + expected = xp.asarray(expected) + + assert_array_almost_equal( + ndimage.shift(x, shift, mode='grid-wrap', order=order), + expected + ) + + @pytest.mark.parametrize('shift', + [(1, 0), (0, 1), (-1, 1), (3, -5), (2, 7)]) + @pytest.mark.parametrize('order', range(0, 6)) + def test_shift_grid_constant1(self, shift, order, xp): + # For integer shifts, 'constant' and 'grid-constant' should be equal + x = xp.reshape(xp.arange(20), (5, 4)) + assert_array_almost_equal( + ndimage.shift(x, shift, mode='grid-constant', order=order), + ndimage.shift(x, shift, mode='constant', order=order), + ) + + def test_shift_grid_constant_order1(self, xp): + x = xp.asarray([[1, 2, 3], + [4, 5, 6]], dtype=xp.float64) + expected_result = xp.asarray([[0.25, 0.75, 1.25], + [1.25, 3.00, 4.00]]) + assert_array_almost_equal( + ndimage.shift(x, (0.5, 0.5), mode='grid-constant', order=1), + expected_result, + ) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_shift_reflect(self, order, xp): + # shift by x.shape results in reflection + x = np.asarray([[0, 1, 2], + [3, 4, 5]]) + expected = x[::-1, ::-1].copy() # strides > 0 for torch + + x = xp.asarray(x) + expected = xp.asarray(expected) + assert_array_almost_equal( + ndimage.shift(x, x.shape, mode='reflect', order=order), + expected, + ) + + @pytest.mark.parametrize('order', range(0, 6)) + @pytest.mark.parametrize('prefilter', [False, True]) + def test_shift_nearest_boundary(self, order, prefilter, xp): + # verify that shifting at least order // 2 beyond the end of the array + # gives a value equal to the edge value. + x = xp.arange(16) + kwargs = dict(mode='nearest', order=order, prefilter=prefilter) + assert_array_almost_equal( + ndimage.shift(x, order // 2 + 1, **kwargs)[0], x[0], + ) + assert_array_almost_equal( + ndimage.shift(x, -order // 2 - 1, **kwargs)[-1], x[-1], + ) + + @pytest.mark.parametrize('mode', ['grid-constant', 'grid-wrap', 'nearest', + 'mirror', 'reflect']) + @pytest.mark.parametrize('order', range(6)) + def test_shift_vs_padded(self, order, mode, xp): + x_np = np.arange(144, dtype=float).reshape(12, 12) + shift = (0.4, -2.3) + + # manually pad and then extract center to get expected result + npad = 32 + pad_mode = ndimage_to_numpy_mode.get(mode) + x_padded = xp.asarray(np.pad(x_np, npad, mode=pad_mode)) + x = xp.asarray(x_np) + + center_slice = tuple([slice(npad, -npad)] * x.ndim) + expected_result = ndimage.shift( + x_padded, shift, mode=mode, order=order)[center_slice] + + xp_assert_close( + ndimage.shift(x, shift, mode=mode, order=order), + expected_result, + rtol=1e-7, + ) + + +class TestZoom: + + @pytest.mark.parametrize('order', range(0, 6)) + def test_zoom1(self, order, xp): + for z in [2, [2, 2]]: + arr = xp.reshape(xp.arange(25, dtype=xp.float64), (5, 5)) + arr = ndimage.zoom(arr, z, order=order) + assert arr.shape == (10, 10) + assert xp.all(arr[-1, :] != 0) + assert xp.all(arr[-1, :] >= (20 - eps)) + assert xp.all(arr[0, :] <= (5 + eps)) + assert xp.all(arr >= (0 - eps)) + assert xp.all(arr <= (24 + eps)) + + def test_zoom2(self, xp): + arr = xp.reshape(xp.arange(12), (3, 4)) + out = ndimage.zoom(ndimage.zoom(arr, 2), 0.5) + xp_assert_equal(out, arr) + + def test_zoom3(self, xp): + arr = xp.asarray([[1, 2]]) + out1 = ndimage.zoom(arr, (2, 1)) + out2 = ndimage.zoom(arr, (1, 2)) + + assert_array_almost_equal(out1, xp.asarray([[1, 2], [1, 2]])) + assert_array_almost_equal(out2, xp.asarray([[1, 1, 2, 2]])) + + @pytest.mark.parametrize('order', range(0, 6)) + @pytest.mark.parametrize('dtype', ["float64", "complex128"]) + def test_zoom_affine01(self, order, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.asarray([[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]], dtype=dtype) + isdtype = array_namespace(data).isdtype + if isdtype(data.dtype, 'complex floating'): + data -= 1j * data + with suppress_warnings() as sup: + sup.filter(UserWarning, + 'The behavior of affine_transform with a 1-D array .* ' + 'has changed') + out = ndimage.affine_transform(data, xp.asarray([0.5, 0.5]), 0, + (6, 8), order=order) + assert_array_almost_equal(out[::2, ::2], data) + + def test_zoom_infinity(self, xp): + # Ticket #1419 regression test + dim = 8 + ndimage.zoom(xp.zeros((dim, dim)), 1. / dim, mode='nearest') + + def test_zoom_zoomfactor_one(self, xp): + # Ticket #1122 regression test + arr = xp.zeros((1, 5, 5)) + zoom = (1.0, 2.0, 2.0) + + out = ndimage.zoom(arr, zoom, cval=7) + ref = xp.zeros((1, 10, 10)) + assert_array_almost_equal(out, ref) + + def test_zoom_output_shape_roundoff(self, xp): + arr = xp.zeros((3, 11, 25)) + zoom = (4.0 / 3, 15.0 / 11, 29.0 / 25) + out = ndimage.zoom(arr, zoom) + assert out.shape == (4, 15, 29) + + @pytest.mark.parametrize('zoom', [(1, 1), (3, 5), (8, 2), (8, 8)]) + @pytest.mark.parametrize('mode', ['nearest', 'constant', 'wrap', 'reflect', + 'mirror', 'grid-wrap', 'grid-mirror', + 'grid-constant']) + def test_zoom_by_int_order0(self, zoom, mode, xp): + # order 0 zoom should be the same as replication via np.kron + # Note: This is not True for general x shapes when grid_mode is False, + # but works here for all modes because the size ratio happens to + # always be an integer when x.shape = (2, 2). + x_np = np.asarray([[0, 1], + [2, 3]], dtype=np.float64) + expected = np.kron(x_np, np.ones(zoom)) + + x = xp.asarray(x_np) + expected = xp.asarray(expected) + + assert_array_almost_equal( + ndimage.zoom(x, zoom, order=0, mode=mode), + expected + ) + + @pytest.mark.parametrize('shape', [(2, 3), (4, 4)]) + @pytest.mark.parametrize('zoom', [(1, 1), (3, 5), (8, 2), (8, 8)]) + @pytest.mark.parametrize('mode', ['nearest', 'reflect', 'mirror', + 'grid-wrap', 'grid-constant']) + def test_zoom_grid_by_int_order0(self, shape, zoom, mode, xp): + # When grid_mode is True, order 0 zoom should be the same as + # replication via np.kron. The only exceptions to this are the + # non-grid modes 'constant' and 'wrap'. + x_np = np.arange(np.prod(shape), dtype=float).reshape(shape) + + x = xp.asarray(x_np) + assert_array_almost_equal( + ndimage.zoom(x, zoom, order=0, mode=mode, grid_mode=True), + xp.asarray(np.kron(x_np, np.ones(zoom))) + ) + + @pytest.mark.parametrize('mode', ['constant', 'wrap']) + @pytest.mark.thread_unsafe + def test_zoom_grid_mode_warnings(self, mode, xp): + # Warn on use of non-grid modes when grid_mode is True + x = xp.reshape(xp.arange(9, dtype=xp.float64), (3, 3)) + with pytest.warns(UserWarning, + match="It is recommended to use mode"): + ndimage.zoom(x, 2, mode=mode, grid_mode=True), + + @skip_xp_backends(np_only=True, reason='inplace output= is numpy-specific') + def test_zoom_output_shape(self, xp): + """Ticket #643""" + x = xp.reshape(xp.arange(12), (3, 4)) + ndimage.zoom(x, 2, output=xp.zeros((6, 8))) + + def test_zoom_0d_array(self, xp): + # Ticket #21670 regression test + a = xp.arange(10.) + factor = 2 + actual = ndimage.zoom(a, np.array(factor)) + expected = ndimage.zoom(a, factor) + xp_assert_close(actual, expected) + + +class TestRotate: + + @pytest.mark.parametrize('order', range(0, 6)) + def test_rotate01(self, order, xp): + data = xp.asarray([[0, 0, 0, 0], + [0, 1, 1, 0], + [0, 0, 0, 0]], dtype=xp.float64) + out = ndimage.rotate(data, 0, order=order) + assert_array_almost_equal(out, data) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_rotate02(self, order, xp): + data = xp.asarray([[0, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 0, 0]], dtype=xp.float64) + expected = xp.asarray([[0, 0, 0], + [0, 0, 0], + [0, 1, 0], + [0, 0, 0]], dtype=xp.float64) + out = ndimage.rotate(data, 90, order=order) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('order', range(0, 6)) + @pytest.mark.parametrize('dtype', ["float64", "complex128"]) + def test_rotate03(self, order, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.asarray([[0, 0, 0, 0, 0], + [0, 1, 1, 0, 0], + [0, 0, 0, 0, 0]], dtype=dtype) + expected = xp.asarray([[0, 0, 0], + [0, 0, 0], + [0, 1, 0], + [0, 1, 0], + [0, 0, 0]], dtype=dtype) + isdtype = array_namespace(data).isdtype + if isdtype(data.dtype, 'complex floating'): + data -= 1j * data + expected -= 1j * expected + out = ndimage.rotate(data, 90, order=order) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_rotate04(self, order, xp): + data = xp.asarray([[0, 0, 0, 0, 0], + [0, 1, 1, 0, 0], + [0, 0, 0, 0, 0]], dtype=xp.float64) + expected = xp.asarray([[0, 0, 0, 0, 0], + [0, 0, 1, 0, 0], + [0, 0, 1, 0, 0]], dtype=xp.float64) + out = ndimage.rotate(data, 90, reshape=False, order=order) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_rotate05(self, order, xp): + data = np.empty((4, 3, 3)) + for i in range(3): + data[:, :, i] = np.asarray([[0, 0, 0], + [0, 1, 0], + [0, 1, 0], + [0, 0, 0]], dtype=np.float64) + data = xp.asarray(data) + expected = xp.asarray([[0, 0, 0, 0], + [0, 1, 1, 0], + [0, 0, 0, 0]], dtype=xp.float64) + out = ndimage.rotate(data, 90, order=order) + for i in range(3): + assert_array_almost_equal(out[:, :, i], expected) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_rotate06(self, order, xp): + data = np.empty((3, 4, 3)) + for i in range(3): + data[:, :, i] = np.asarray([[0, 0, 0, 0], + [0, 1, 1, 0], + [0, 0, 0, 0]], dtype=np.float64) + data = xp.asarray(data) + expected = xp.asarray([[0, 0, 0], + [0, 1, 0], + [0, 1, 0], + [0, 0, 0]], dtype=xp.float64) + out = ndimage.rotate(data, 90, order=order) + for i in range(3): + assert_array_almost_equal(out[:, :, i], expected) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_rotate07(self, order, xp): + data = xp.asarray([[[0, 0, 0, 0, 0], + [0, 1, 1, 0, 0], + [0, 0, 0, 0, 0]]] * 2, dtype=xp.float64) + permute_dims = array_namespace(data).permute_dims + data = permute_dims(data, (2, 1, 0)) + expected = xp.asarray([[[0, 0, 0], + [0, 1, 0], + [0, 1, 0], + [0, 0, 0], + [0, 0, 0]]] * 2, dtype=xp.float64) + expected = permute_dims(expected, (2, 1, 0)) + out = ndimage.rotate(data, 90, axes=(0, 1), order=order) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_rotate08(self, order, xp): + data = xp.asarray([[[0, 0, 0, 0, 0], + [0, 1, 1, 0, 0], + [0, 0, 0, 0, 0]]] * 2, dtype=xp.float64) + permute_dims = array_namespace(data).permute_dims + data = permute_dims(data, (2, 1, 0)) # == np.transpose + expected = xp.asarray([[[0, 0, 1, 0, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 0, 0]]] * 2, dtype=xp.float64) + permute_dims = array_namespace(data).permute_dims + expected = permute_dims(expected, (2, 1, 0)) + out = ndimage.rotate(data, 90, axes=(0, 1), reshape=False, order=order) + assert_array_almost_equal(out, expected) + + def test_rotate09(self, xp): + data = xp.asarray([[0, 0, 0, 0, 0], + [0, 1, 1, 0, 0], + [0, 0, 0, 0, 0]] * 2, dtype=xp.float64) + with assert_raises(ValueError): + ndimage.rotate(data, 90, axes=(0, data.ndim)) + + def test_rotate10(self, xp): + data = xp.reshape(xp.arange(45, dtype=xp.float64), (3, 5, 3)) + + # The output of ndimage.rotate before refactoring + expected = xp.asarray([[[0.0, 0.0, 0.0], + [0.0, 0.0, 0.0], + [6.54914793, 7.54914793, 8.54914793], + [10.84520162, 11.84520162, 12.84520162], + [0.0, 0.0, 0.0]], + [[6.19286575, 7.19286575, 8.19286575], + [13.4730712, 14.4730712, 15.4730712], + [21.0, 22.0, 23.0], + [28.5269288, 29.5269288, 30.5269288], + [35.80713425, 36.80713425, 37.80713425]], + [[0.0, 0.0, 0.0], + [31.15479838, 32.15479838, 33.15479838], + [35.45085207, 36.45085207, 37.45085207], + [0.0, 0.0, 0.0], + [0.0, 0.0, 0.0]]], dtype=xp.float64) + + out = ndimage.rotate(data, angle=12, reshape=False) + #assert_array_almost_equal(out, expected) + xp_assert_close(out, expected, rtol=1e-6, atol=2e-6) + + def test_rotate_exact_180(self, xp): + if is_cupy(xp): + pytest.xfail("https://github.com/cupy/cupy/issues/8400") + + a = np.tile(xp.arange(5), (5, 1)) + b = ndimage.rotate(ndimage.rotate(a, 180), -180) + xp_assert_equal(a, b) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/tests/test_measurements.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/tests/test_measurements.py new file mode 100644 index 0000000000000000000000000000000000000000..c8175ba309dd223a6d0fd46df017ea1fbc797a4e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/tests/test_measurements.py @@ -0,0 +1,1609 @@ +import os +import os.path + +import numpy as np +from numpy.testing import suppress_warnings + +from scipy._lib._array_api import ( + is_jax, + is_torch, + array_namespace, + xp_assert_equal, + xp_assert_close, + assert_array_almost_equal, + assert_almost_equal, +) + +import pytest +from pytest import raises as assert_raises + +import scipy.ndimage as ndimage + +from . import types + +from scipy.conftest import array_api_compatible +skip_xp_backends = pytest.mark.skip_xp_backends +pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends"), + skip_xp_backends(cpu_only=True, exceptions=['cupy', 'jax.numpy'],)] + +IS_WINDOWS_AND_NP1 = os.name == 'nt' and np.__version__ < '2' + + +@skip_xp_backends(np_only=True, reason='test internal numpy-only helpers') +class Test_measurements_stats: + """ndimage._measurements._stats() is a utility used by other functions. + + Since internal ndimage/_measurements.py code is NumPy-only, + so is this this test class. + """ + def test_a(self, xp): + x = [0, 1, 2, 6] + labels = [0, 0, 1, 1] + index = [0, 1] + for shp in [(4,), (2, 2)]: + x = np.array(x).reshape(shp) + labels = np.array(labels).reshape(shp) + counts, sums = ndimage._measurements._stats( + x, labels=labels, index=index) + + dtype_arg = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {} + xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg)) + xp_assert_equal(sums, np.asarray([1.0, 8.0])) + + def test_b(self, xp): + # Same data as test_a, but different labels. The label 9 exceeds the + # length of 'labels', so this test will follow a different code path. + x = [0, 1, 2, 6] + labels = [0, 0, 9, 9] + index = [0, 9] + for shp in [(4,), (2, 2)]: + x = np.array(x).reshape(shp) + labels = np.array(labels).reshape(shp) + counts, sums = ndimage._measurements._stats( + x, labels=labels, index=index) + + dtype_arg = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {} + xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg)) + xp_assert_equal(sums, np.asarray([1.0, 8.0])) + + def test_a_centered(self, xp): + x = [0, 1, 2, 6] + labels = [0, 0, 1, 1] + index = [0, 1] + for shp in [(4,), (2, 2)]: + x = np.array(x).reshape(shp) + labels = np.array(labels).reshape(shp) + counts, sums, centers = ndimage._measurements._stats( + x, labels=labels, index=index, centered=True) + + dtype_arg = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {} + xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg)) + xp_assert_equal(sums, np.asarray([1.0, 8.0])) + xp_assert_equal(centers, np.asarray([0.5, 8.0])) + + def test_b_centered(self, xp): + x = [0, 1, 2, 6] + labels = [0, 0, 9, 9] + index = [0, 9] + for shp in [(4,), (2, 2)]: + x = np.array(x).reshape(shp) + labels = np.array(labels).reshape(shp) + counts, sums, centers = ndimage._measurements._stats( + x, labels=labels, index=index, centered=True) + + dtype_arg = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {} + xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg)) + xp_assert_equal(sums, np.asarray([1.0, 8.0])) + xp_assert_equal(centers, np.asarray([0.5, 8.0])) + + def test_nonint_labels(self, xp): + x = [0, 1, 2, 6] + labels = [0.0, 0.0, 9.0, 9.0] + index = [0.0, 9.0] + for shp in [(4,), (2, 2)]: + x = np.array(x).reshape(shp) + labels = np.array(labels).reshape(shp) + counts, sums, centers = ndimage._measurements._stats( + x, labels=labels, index=index, centered=True) + + dtype_arg = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {} + xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg)) + xp_assert_equal(sums, np.asarray([1.0, 8.0])) + xp_assert_equal(centers, np.asarray([0.5, 8.0])) + + +class Test_measurements_select: + """ndimage._measurements._select() is a utility used by other functions.""" + + def test_basic(self, xp): + x = [0, 1, 6, 2] + cases = [ + ([0, 0, 1, 1], [0, 1]), # "Small" integer labels + ([0, 0, 9, 9], [0, 9]), # A label larger than len(labels) + ([0.0, 0.0, 7.0, 7.0], [0.0, 7.0]), # Non-integer labels + ] + for labels, index in cases: + result = ndimage._measurements._select( + x, labels=labels, index=index) + assert len(result) == 0 + result = ndimage._measurements._select( + x, labels=labels, index=index, find_max=True) + assert len(result) == 1 + xp_assert_equal(result[0], [1, 6]) + result = ndimage._measurements._select( + x, labels=labels, index=index, find_min=True) + assert len(result) == 1 + xp_assert_equal(result[0], [0, 2]) + result = ndimage._measurements._select( + x, labels=labels, index=index, find_min=True, + find_min_positions=True) + assert len(result) == 2 + xp_assert_equal(result[0], [0, 2]) + xp_assert_equal(result[1], [0, 3]) + assert result[1].dtype.kind == 'i' + result = ndimage._measurements._select( + x, labels=labels, index=index, find_max=True, + find_max_positions=True) + assert len(result) == 2 + xp_assert_equal(result[0], [1, 6]) + xp_assert_equal(result[1], [1, 2]) + assert result[1].dtype.kind == 'i' + + +def test_label01(xp): + data = xp.ones([]) + out, n = ndimage.label(data) + assert out == 1 + assert n == 1 + + +def test_label02(xp): + data = xp.zeros([]) + out, n = ndimage.label(data) + assert out == 0 + assert n == 0 + + +@pytest.mark.thread_unsafe # due to Cython fused types, see cython#6506 +def test_label03(xp): + data = xp.ones([1]) + out, n = ndimage.label(data) + assert_array_almost_equal(out, xp.asarray([1])) + assert n == 1 + + +def test_label04(xp): + data = xp.zeros([1]) + out, n = ndimage.label(data) + assert_array_almost_equal(out, xp.asarray([0])) + assert n == 0 + + +def test_label05(xp): + data = xp.ones([5]) + out, n = ndimage.label(data) + assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1, 1])) + assert n == 1 + + +def test_label06(xp): + data = xp.asarray([1, 0, 1, 1, 0, 1]) + out, n = ndimage.label(data) + assert_array_almost_equal(out, xp.asarray([1, 0, 2, 2, 0, 3])) + assert n == 3 + + +def test_label07(xp): + data = xp.asarray([[0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0]]) + out, n = ndimage.label(data) + assert_array_almost_equal(out, xp.asarray( + [[0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0]])) + assert n == 0 + + +def test_label08(xp): + data = xp.asarray([[1, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0], + [1, 1, 0, 0, 0, 0], + [1, 1, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 0]]) + out, n = ndimage.label(data) + assert_array_almost_equal(out, xp.asarray([[1, 0, 0, 0, 0, 0], + [0, 0, 2, 2, 0, 0], + [0, 0, 2, 2, 2, 0], + [3, 3, 0, 0, 0, 0], + [3, 3, 0, 0, 0, 0], + [0, 0, 0, 4, 4, 0]])) + assert n == 4 + + +def test_label09(xp): + data = xp.asarray([[1, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0], + [1, 1, 0, 0, 0, 0], + [1, 1, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 0]]) + struct = ndimage.generate_binary_structure(2, 2) + struct = xp.asarray(struct) + out, n = ndimage.label(data, struct) + assert_array_almost_equal(out, xp.asarray([[1, 0, 0, 0, 0, 0], + [0, 0, 2, 2, 0, 0], + [0, 0, 2, 2, 2, 0], + [2, 2, 0, 0, 0, 0], + [2, 2, 0, 0, 0, 0], + [0, 0, 0, 3, 3, 0]])) + assert n == 3 + + +def test_label10(xp): + data = xp.asarray([[0, 0, 0, 0, 0, 0], + [0, 1, 1, 0, 1, 0], + [0, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0]]) + struct = ndimage.generate_binary_structure(2, 2) + struct = xp.asarray(struct) + out, n = ndimage.label(data, struct) + assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0, 0, 0], + [0, 1, 1, 0, 1, 0], + [0, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0]])) + assert n == 1 + + +def test_label11(xp): + for type in types: + dtype = getattr(xp, type) + data = xp.asarray([[1, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0], + [1, 1, 0, 0, 0, 0], + [1, 1, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 0]], dtype=dtype) + out, n = ndimage.label(data) + expected = [[1, 0, 0, 0, 0, 0], + [0, 0, 2, 2, 0, 0], + [0, 0, 2, 2, 2, 0], + [3, 3, 0, 0, 0, 0], + [3, 3, 0, 0, 0, 0], + [0, 0, 0, 4, 4, 0]] + expected = xp.asarray(expected) + assert_array_almost_equal(out, expected) + assert n == 4 + + +@skip_xp_backends(np_only=True, reason='inplace output is numpy-specific') +def test_label11_inplace(xp): + for type in types: + dtype = getattr(xp, type) + data = xp.asarray([[1, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0], + [1, 1, 0, 0, 0, 0], + [1, 1, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 0]], dtype=dtype) + n = ndimage.label(data, output=data) + expected = [[1, 0, 0, 0, 0, 0], + [0, 0, 2, 2, 0, 0], + [0, 0, 2, 2, 2, 0], + [3, 3, 0, 0, 0, 0], + [3, 3, 0, 0, 0, 0], + [0, 0, 0, 4, 4, 0]] + expected = xp.asarray(expected) + assert_array_almost_equal(data, expected) + assert n == 4 + + +def test_label12(xp): + for type in types: + dtype = getattr(xp, type) + data = xp.asarray([[0, 0, 0, 0, 1, 1], + [0, 0, 0, 0, 0, 1], + [0, 0, 1, 0, 1, 1], + [0, 0, 1, 1, 1, 1], + [0, 0, 0, 1, 1, 0]], dtype=dtype) + out, n = ndimage.label(data) + expected = [[0, 0, 0, 0, 1, 1], + [0, 0, 0, 0, 0, 1], + [0, 0, 1, 0, 1, 1], + [0, 0, 1, 1, 1, 1], + [0, 0, 0, 1, 1, 0]] + expected = xp.asarray(expected) + assert_array_almost_equal(out, expected) + assert n == 1 + + +def test_label13(xp): + for type in types: + dtype = getattr(xp, type) + data = xp.asarray([[1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1], + [1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], + dtype=dtype) + out, n = ndimage.label(data) + expected = [[1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1], + [1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] + expected = xp.asarray(expected) + assert_array_almost_equal(out, expected) + assert n == 1 + + +@skip_xp_backends(np_only=True, reason='output=dtype is numpy-specific') +def test_label_output_typed(xp): + data = xp.ones([5]) + for t in types: + dtype = getattr(xp, t) + output = xp.zeros([5], dtype=dtype) + n = ndimage.label(data, output=output) + assert_array_almost_equal(output, + xp.ones(output.shape, dtype=output.dtype)) + assert n == 1 + + +@skip_xp_backends(np_only=True, reason='output=dtype is numpy-specific') +def test_label_output_dtype(xp): + data = xp.ones([5]) + for t in types: + dtype = getattr(xp, t) + output, n = ndimage.label(data, output=dtype) + assert_array_almost_equal(output, + xp.ones(output.shape, dtype=output.dtype)) + assert output.dtype == t + + +def test_label_output_wrong_size(xp): + if is_jax(xp): + pytest.xfail("JAX does not raise") + + data = xp.ones([5]) + for t in types: + dtype = getattr(xp, t) + output = xp.zeros([10], dtype=dtype) + # TypeError is from non-numpy arrays as output + assert_raises((ValueError, TypeError), + ndimage.label, data, output=output) + + +def test_label_structuring_elements(xp): + data = np.loadtxt(os.path.join(os.path.dirname( + __file__), "data", "label_inputs.txt")) + strels = np.loadtxt(os.path.join( + os.path.dirname(__file__), "data", "label_strels.txt")) + results = np.loadtxt(os.path.join( + os.path.dirname(__file__), "data", "label_results.txt")) + data = data.reshape((-1, 7, 7)) + strels = strels.reshape((-1, 3, 3)) + results = results.reshape((-1, 7, 7)) + + data = xp.asarray(data) + strels = xp.asarray(strels) + results = xp.asarray(results) + r = 0 + for i in range(data.shape[0]): + d = data[i, :, :] + for j in range(strels.shape[0]): + s = strels[j, :, :] + xp_assert_equal(ndimage.label(d, s)[0], results[r, :, :], check_dtype=False) + r += 1 + +@skip_xp_backends("cupy", + reason="`cupyx.scipy.ndimage` does not have `find_objects`" +) +def test_ticket_742(xp): + def SE(img, thresh=.7, size=4): + mask = img > thresh + rank = len(mask.shape) + struct = ndimage.generate_binary_structure(rank, rank) + struct = xp.asarray(struct) + la, co = ndimage.label(mask, + struct) + _ = ndimage.find_objects(la) + + if np.dtype(np.intp) != np.dtype('i'): + shape = (3, 1240, 1240) + a = np.random.rand(np.prod(shape)).reshape(shape) + a = xp.asarray(a) + # shouldn't crash + SE(a) + + +def test_gh_issue_3025(xp): + """Github issue #3025 - improper merging of labels""" + d = np.zeros((60, 320)) + d[:, :257] = 1 + d[:, 260:] = 1 + d[36, 257] = 1 + d[35, 258] = 1 + d[35, 259] = 1 + d = xp.asarray(d) + assert ndimage.label(d, xp.ones((3, 3)))[1] == 1 + + +@skip_xp_backends("cupy", reason="cupyx.scipy.ndimage does not have find_object") +class TestFindObjects: + def test_label_default_dtype(self, xp): + test_array = np.random.rand(10, 10) + test_array = xp.asarray(test_array) + label, no_features = ndimage.label(test_array > 0.5) + assert label.dtype in (xp.int32, xp.int64) + # Shouldn't raise an exception + ndimage.find_objects(label) + + + def test_find_objects01(self, xp): + data = xp.ones([], dtype=xp.int64) + out = ndimage.find_objects(data) + assert out == [()] + + + def test_find_objects02(self, xp): + data = xp.zeros([], dtype=xp.int64) + out = ndimage.find_objects(data) + assert out == [] + + + def test_find_objects03(self, xp): + data = xp.ones([1], dtype=xp.int64) + out = ndimage.find_objects(data) + assert out == [(slice(0, 1, None),)] + + + def test_find_objects04(self, xp): + data = xp.zeros([1], dtype=xp.int64) + out = ndimage.find_objects(data) + assert out == [] + + + def test_find_objects05(self, xp): + data = xp.ones([5], dtype=xp.int64) + out = ndimage.find_objects(data) + assert out == [(slice(0, 5, None),)] + + + def test_find_objects06(self, xp): + data = xp.asarray([1, 0, 2, 2, 0, 3]) + out = ndimage.find_objects(data) + assert out == [(slice(0, 1, None),), + (slice(2, 4, None),), + (slice(5, 6, None),)] + + + def test_find_objects07(self, xp): + data = xp.asarray([[0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0]]) + out = ndimage.find_objects(data) + assert out == [] + + + def test_find_objects08(self, xp): + data = xp.asarray([[1, 0, 0, 0, 0, 0], + [0, 0, 2, 2, 0, 0], + [0, 0, 2, 2, 2, 0], + [3, 3, 0, 0, 0, 0], + [3, 3, 0, 0, 0, 0], + [0, 0, 0, 4, 4, 0]]) + out = ndimage.find_objects(data) + assert out == [(slice(0, 1, None), slice(0, 1, None)), + (slice(1, 3, None), slice(2, 5, None)), + (slice(3, 5, None), slice(0, 2, None)), + (slice(5, 6, None), slice(3, 5, None))] + + + def test_find_objects09(self, xp): + data = xp.asarray([[1, 0, 0, 0, 0, 0], + [0, 0, 2, 2, 0, 0], + [0, 0, 2, 2, 2, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 4, 4, 0]]) + out = ndimage.find_objects(data) + assert out == [(slice(0, 1, None), slice(0, 1, None)), + (slice(1, 3, None), slice(2, 5, None)), + None, + (slice(5, 6, None), slice(3, 5, None))] + + +def test_value_indices01(xp): + "Test dictionary keys and entries" + data = xp.asarray([[1, 0, 0, 0, 0, 0], + [0, 0, 2, 2, 0, 0], + [0, 0, 2, 2, 2, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 4, 4, 0]]) + vi = ndimage.value_indices(data, ignore_value=0) + true_keys = [1, 2, 4] + assert list(vi.keys()) == true_keys + + nnz_kwd = {'as_tuple': True} if is_torch(xp) else {} + + truevi = {} + for k in true_keys: + truevi[k] = xp.nonzero(data == k, **nnz_kwd) + + vi = ndimage.value_indices(data, ignore_value=0) + assert vi.keys() == truevi.keys() + for key in vi.keys(): + assert len(vi[key]) == len(truevi[key]) + for v, true_v in zip(vi[key], truevi[key]): + xp_assert_equal(v, true_v) + + +def test_value_indices02(xp): + "Test input checking" + data = xp.zeros((5, 4), dtype=xp.float32) + msg = "Parameter 'arr' must be an integer array" + with assert_raises(ValueError, match=msg): + ndimage.value_indices(data) + + +def test_value_indices03(xp): + "Test different input array shapes, from 1-D to 4-D" + for shape in [(36,), (18, 2), (3, 3, 4), (3, 3, 2, 2)]: + a = xp.asarray((12*[1]+12*[2]+12*[3]), dtype=xp.int32) + a = xp.reshape(a, shape) + + nnz_kwd = {'as_tuple': True} if is_torch(xp) else {} + + unique_values = array_namespace(a).unique_values + trueKeys = unique_values(a) + vi = ndimage.value_indices(a) + assert list(vi.keys()) == list(trueKeys) + for k in [int(x) for x in trueKeys]: + trueNdx = xp.nonzero(a == k, **nnz_kwd) + assert len(vi[k]) == len(trueNdx) + for vik, true_vik in zip(vi[k], trueNdx): + xp_assert_equal(vik, true_vik) + + +def test_sum01(xp): + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([], dtype=dtype) + output = ndimage.sum(input) + assert output == 0 + + +def test_sum02(xp): + for type in types: + dtype = getattr(xp, type) + input = xp.zeros([0, 4], dtype=dtype) + output = ndimage.sum(input) + assert output == 0 + + +def test_sum03(xp): + for type in types: + dtype = getattr(xp, type) + input = xp.ones([], dtype=dtype) + output = ndimage.sum(input) + assert_almost_equal(output, xp.asarray(1.0), check_0d=False) + + +def test_sum04(xp): + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([1, 2], dtype=dtype) + output = ndimage.sum(input) + assert_almost_equal(output, xp.asarray(3.0), check_0d=False) + + +def test_sum05(xp): + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[1, 2], [3, 4]], dtype=dtype) + output = ndimage.sum(input) + assert_almost_equal(output, xp.asarray(10.0), check_0d=False) + + +def test_sum06(xp): + labels = np.asarray([], dtype=bool) + labels = xp.asarray(labels) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([], dtype=dtype) + output = ndimage.sum(input, labels=labels) + assert output == 0 + + +def test_sum07(xp): + labels = np.ones([0, 4], dtype=bool) + labels = xp.asarray(labels) + for type in types: + dtype = getattr(xp, type) + input = xp.zeros([0, 4], dtype=dtype) + output = ndimage.sum(input, labels=labels) + assert output == 0 + + +def test_sum08(xp): + labels = np.asarray([1, 0], dtype=bool) + labels = xp.asarray(labels) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([1, 2], dtype=dtype) + output = ndimage.sum(input, labels=labels) + assert output == 1 + + +def test_sum09(xp): + labels = np.asarray([1, 0], dtype=bool) + labels = xp.asarray(labels) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[1, 2], [3, 4]], dtype=dtype) + output = ndimage.sum(input, labels=labels) + assert_almost_equal(output, xp.asarray(4.0), check_0d=False) + + +def test_sum10(xp): + labels = np.asarray([1, 0], dtype=bool) + input = np.asarray([[1, 2], [3, 4]], dtype=bool) + + labels = xp.asarray(labels) + input = xp.asarray(input) + output = ndimage.sum(input, labels=labels) + assert_almost_equal(output, xp.asarray(2.0), check_0d=False) + + +def test_sum11(xp): + labels = xp.asarray([1, 2], dtype=xp.int8) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[1, 2], [3, 4]], dtype=dtype) + output = ndimage.sum(input, labels=labels, + index=2) + assert_almost_equal(output, xp.asarray(6.0), check_0d=False) + + +def test_sum12(xp): + labels = xp.asarray([[1, 2], [2, 4]], dtype=xp.int8) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[1, 2], [3, 4]], dtype=dtype) + output = ndimage.sum(input, labels=labels, index=xp.asarray([4, 8, 2])) + assert_array_almost_equal(output, xp.asarray([4.0, 0.0, 5.0])) + + +def test_sum_labels(xp): + labels = xp.asarray([[1, 2], [2, 4]], dtype=xp.int8) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[1, 2], [3, 4]], dtype=dtype) + output_sum = ndimage.sum(input, labels=labels, index=xp.asarray([4, 8, 2])) + output_labels = ndimage.sum_labels( + input, labels=labels, index=xp.asarray([4, 8, 2])) + + assert xp.all(output_sum == output_labels) + assert_array_almost_equal(output_labels, xp.asarray([4.0, 0.0, 5.0])) + + +def test_mean01(xp): + labels = np.asarray([1, 0], dtype=bool) + labels = xp.asarray(labels) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[1, 2], [3, 4]], dtype=dtype) + output = ndimage.mean(input, labels=labels) + assert_almost_equal(output, xp.asarray(2.0), check_0d=False) + + +def test_mean02(xp): + labels = np.asarray([1, 0], dtype=bool) + input = np.asarray([[1, 2], [3, 4]], dtype=bool) + + labels = xp.asarray(labels) + input = xp.asarray(input) + output = ndimage.mean(input, labels=labels) + assert_almost_equal(output, xp.asarray(1.0), check_0d=False) + + +def test_mean03(xp): + labels = xp.asarray([1, 2]) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[1, 2], [3, 4]], dtype=dtype) + output = ndimage.mean(input, labels=labels, + index=2) + assert_almost_equal(output, xp.asarray(3.0), check_0d=False) + + +def test_mean04(xp): + labels = xp.asarray([[1, 2], [2, 4]], dtype=xp.int8) + with np.errstate(all='ignore'): + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[1, 2], [3, 4]], dtype=dtype) + output = ndimage.mean(input, labels=labels, + index=xp.asarray([4, 8, 2])) + # XXX: output[[0, 2]] does not work in array-api-strict; annoying + # assert_array_almost_equal(output[[0, 2]], xp.asarray([4.0, 2.5])) + assert output[0] == 4.0 + assert output[2] == 2.5 + assert xp.isnan(output[1]) + + +def test_minimum01(xp): + labels = np.asarray([1, 0], dtype=bool) + labels = xp.asarray(labels) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[1, 2], [3, 4]], dtype=dtype) + output = ndimage.minimum(input, labels=labels) + assert_almost_equal(output, xp.asarray(1.0), check_0d=False) + + +def test_minimum02(xp): + labels = np.asarray([1, 0], dtype=bool) + input = np.asarray([[2, 2], [2, 4]], dtype=bool) + + labels = xp.asarray(labels) + input = xp.asarray(input) + output = ndimage.minimum(input, labels=labels) + assert_almost_equal(output, xp.asarray(1.0), check_0d=False) + + +def test_minimum03(xp): + labels = xp.asarray([1, 2]) + for type in types: + dtype = getattr(xp, type) + + input = xp.asarray([[1, 2], [3, 4]], dtype=dtype) + output = ndimage.minimum(input, labels=labels, + index=2) + assert_almost_equal(output, xp.asarray(2.0), check_0d=False) + + +def test_minimum04(xp): + labels = xp.asarray([[1, 2], [2, 3]]) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[1, 2], [3, 4]], dtype=dtype) + output = ndimage.minimum(input, labels=labels, + index=xp.asarray([2, 3, 8])) + assert_array_almost_equal(output, xp.asarray([2.0, 4.0, 0.0])) + + +def test_maximum01(xp): + labels = np.asarray([1, 0], dtype=bool) + labels = xp.asarray(labels) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[1, 2], [3, 4]], dtype=dtype) + output = ndimage.maximum(input, labels=labels) + assert_almost_equal(output, xp.asarray(3.0), check_0d=False) + + +def test_maximum02(xp): + labels = np.asarray([1, 0], dtype=bool) + input = np.asarray([[2, 2], [2, 4]], dtype=bool) + labels = xp.asarray(labels) + input = xp.asarray(input) + output = ndimage.maximum(input, labels=labels) + assert_almost_equal(output, xp.asarray(1.0), check_0d=False) + + +def test_maximum03(xp): + labels = xp.asarray([1, 2]) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[1, 2], [3, 4]], dtype=dtype) + output = ndimage.maximum(input, labels=labels, + index=2) + assert_almost_equal(output, xp.asarray(4.0), check_0d=False) + + +def test_maximum04(xp): + labels = xp.asarray([[1, 2], [2, 3]]) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[1, 2], [3, 4]], dtype=dtype) + output = ndimage.maximum(input, labels=labels, + index=xp.asarray([2, 3, 8])) + assert_array_almost_equal(output, xp.asarray([3.0, 4.0, 0.0])) + + +def test_maximum05(xp): + # Regression test for ticket #501 (Trac) + x = xp.asarray([-3, -2, -1]) + assert ndimage.maximum(x) == -1 + + +def test_median01(xp): + a = xp.asarray([[1, 2, 0, 1], + [5, 3, 0, 4], + [0, 0, 0, 7], + [9, 3, 0, 0]]) + labels = xp.asarray([[1, 1, 0, 2], + [1, 1, 0, 2], + [0, 0, 0, 2], + [3, 3, 0, 0]]) + output = ndimage.median(a, labels=labels, index=xp.asarray([1, 2, 3])) + assert_array_almost_equal(output, xp.asarray([2.5, 4.0, 6.0])) + + +def test_median02(xp): + a = xp.asarray([[1, 2, 0, 1], + [5, 3, 0, 4], + [0, 0, 0, 7], + [9, 3, 0, 0]]) + output = ndimage.median(a) + assert_almost_equal(output, xp.asarray(1.0), check_0d=False) + + +def test_median03(xp): + a = xp.asarray([[1, 2, 0, 1], + [5, 3, 0, 4], + [0, 0, 0, 7], + [9, 3, 0, 0]]) + labels = xp.asarray([[1, 1, 0, 2], + [1, 1, 0, 2], + [0, 0, 0, 2], + [3, 3, 0, 0]]) + output = ndimage.median(a, labels=labels) + assert_almost_equal(output, xp.asarray(3.0), check_0d=False) + + +def test_median_gh12836_bool(xp): + # test boolean addition fix on example from gh-12836 + a = np.asarray([1, 1], dtype=bool) + a = xp.asarray(a) + output = ndimage.median(a, labels=xp.ones((2,)), index=xp.asarray([1])) + assert_array_almost_equal(output, xp.asarray([1.0])) + + +def test_median_no_int_overflow(xp): + # test integer overflow fix on example from gh-12836 + a = xp.asarray([65, 70], dtype=xp.int8) + output = ndimage.median(a, labels=xp.ones((2,)), index=xp.asarray([1])) + assert_array_almost_equal(output, xp.asarray([67.5])) + + +def test_variance01(xp): + with np.errstate(all='ignore'): + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([], dtype=dtype) + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "Mean of empty slice") + output = ndimage.variance(input) + assert xp.isnan(output) + + +def test_variance02(xp): + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([1], dtype=dtype) + output = ndimage.variance(input) + assert_almost_equal(output, xp.asarray(0.0), check_0d=False) + + +def test_variance03(xp): + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([1, 3], dtype=dtype) + output = ndimage.variance(input) + assert_almost_equal(output, xp.asarray(1.0), check_0d=False) + + +def test_variance04(xp): + input = np.asarray([1, 0], dtype=bool) + input = xp.asarray(input) + output = ndimage.variance(input) + assert_almost_equal(output, xp.asarray(0.25), check_0d=False) + + +def test_variance05(xp): + labels = xp.asarray([2, 2, 3]) + for type in types: + dtype = getattr(xp, type) + + input = xp.asarray([1, 3, 8], dtype=dtype) + output = ndimage.variance(input, labels, 2) + assert_almost_equal(output, xp.asarray(1.0), check_0d=False) + + +def test_variance06(xp): + labels = xp.asarray([2, 2, 3, 3, 4]) + with np.errstate(all='ignore'): + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([1, 3, 8, 10, 8], dtype=dtype) + output = ndimage.variance(input, labels, xp.asarray([2, 3, 4])) + assert_array_almost_equal(output, xp.asarray([1.0, 1.0, 0.0])) + + +def test_standard_deviation01(xp): + with np.errstate(all='ignore'): + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([], dtype=dtype) + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "Mean of empty slice") + output = ndimage.standard_deviation(input) + assert xp.isnan(output) + + +def test_standard_deviation02(xp): + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([1], dtype=dtype) + output = ndimage.standard_deviation(input) + assert_almost_equal(output, xp.asarray(0.0), check_0d=False) + + +def test_standard_deviation03(xp): + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([1, 3], dtype=dtype) + output = ndimage.standard_deviation(input) + assert_almost_equal(output, xp.asarray(1.0), check_0d=False) + + +def test_standard_deviation04(xp): + input = np.asarray([1, 0], dtype=bool) + input = xp.asarray(input) + output = ndimage.standard_deviation(input) + assert_almost_equal(output, xp.asarray(0.5), check_0d=False) + + +def test_standard_deviation05(xp): + labels = xp.asarray([2, 2, 3]) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([1, 3, 8], dtype=dtype) + output = ndimage.standard_deviation(input, labels, 2) + assert_almost_equal(output, xp.asarray(1.0), check_0d=False) + + +def test_standard_deviation06(xp): + labels = xp.asarray([2, 2, 3, 3, 4]) + with np.errstate(all='ignore'): + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([1, 3, 8, 10, 8], dtype=dtype) + output = ndimage.standard_deviation( + input, labels, xp.asarray([2, 3, 4]) + ) + assert_array_almost_equal(output, xp.asarray([1.0, 1.0, 0.0])) + + +def test_standard_deviation07(xp): + labels = xp.asarray([1]) + with np.errstate(all='ignore'): + for type in types: + if is_torch(xp) and type == 'uint8': + pytest.xfail("value cannot be converted to type uint8 " + "without overflow") + dtype = getattr(xp, type) + input = xp.asarray([-0.00619519], dtype=dtype) + output = ndimage.standard_deviation(input, labels, xp.asarray([1])) + assert_array_almost_equal(output, xp.asarray([0])) + + +def test_minimum_position01(xp): + labels = np.asarray([1, 0], dtype=bool) + labels = xp.asarray(labels) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[1, 2], [3, 4]], dtype=dtype) + output = ndimage.minimum_position(input, labels=labels) + assert output == (0, 0) + + +def test_minimum_position02(xp): + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[5, 4, 2, 5], + [3, 7, 0, 2], + [1, 5, 1, 1]], dtype=dtype) + output = ndimage.minimum_position(input) + assert output == (1, 2) + + +def test_minimum_position03(xp): + input = np.asarray([[5, 4, 2, 5], + [3, 7, 0, 2], + [1, 5, 1, 1]], dtype=bool) + input = xp.asarray(input) + output = ndimage.minimum_position(input) + assert output == (1, 2) + + +def test_minimum_position04(xp): + input = np.asarray([[5, 4, 2, 5], + [3, 7, 1, 2], + [1, 5, 1, 1]], dtype=bool) + input = xp.asarray(input) + output = ndimage.minimum_position(input) + assert output == (0, 0) + + +def test_minimum_position05(xp): + labels = xp.asarray([1, 2, 0, 4]) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[5, 4, 2, 5], + [3, 7, 0, 2], + [1, 5, 2, 3]], dtype=dtype) + output = ndimage.minimum_position(input, labels) + assert output == (2, 0) + + +def test_minimum_position06(xp): + labels = xp.asarray([1, 2, 3, 4]) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[5, 4, 2, 5], + [3, 7, 0, 2], + [1, 5, 1, 1]], dtype=dtype) + output = ndimage.minimum_position(input, labels, 2) + assert output == (0, 1) + + +def test_minimum_position07(xp): + labels = xp.asarray([1, 2, 3, 4]) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[5, 4, 2, 5], + [3, 7, 0, 2], + [1, 5, 1, 1]], dtype=dtype) + output = ndimage.minimum_position(input, labels, + xp.asarray([2, 3])) + assert output[0] == (0, 1) + assert output[1] == (1, 2) + + +def test_maximum_position01(xp): + labels = np.asarray([1, 0], dtype=bool) + labels = xp.asarray(labels) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[1, 2], [3, 4]], dtype=dtype) + output = ndimage.maximum_position(input, + labels=labels) + assert output == (1, 0) + + +def test_maximum_position02(xp): + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[5, 4, 2, 5], + [3, 7, 8, 2], + [1, 5, 1, 1]], dtype=dtype) + output = ndimage.maximum_position(input) + assert output == (1, 2) + + +def test_maximum_position03(xp): + input = np.asarray([[5, 4, 2, 5], + [3, 7, 8, 2], + [1, 5, 1, 1]], dtype=bool) + input = xp.asarray(input) + output = ndimage.maximum_position(input) + assert output == (0, 0) + + +def test_maximum_position04(xp): + labels = xp.asarray([1, 2, 0, 4]) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[5, 4, 2, 5], + [3, 7, 8, 2], + [1, 5, 1, 1]], dtype=dtype) + output = ndimage.maximum_position(input, labels) + assert output == (1, 1) + + +def test_maximum_position05(xp): + labels = xp.asarray([1, 2, 0, 4]) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[5, 4, 2, 5], + [3, 7, 8, 2], + [1, 5, 1, 1]], dtype=dtype) + output = ndimage.maximum_position(input, labels, 1) + assert output == (0, 0) + + +def test_maximum_position06(xp): + labels = xp.asarray([1, 2, 0, 4]) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[5, 4, 2, 5], + [3, 7, 8, 2], + [1, 5, 1, 1]], dtype=dtype) + output = ndimage.maximum_position(input, labels, + xp.asarray([1, 2])) + assert output[0] == (0, 0) + assert output[1] == (1, 1) + + +def test_maximum_position07(xp): + # Test float labels + if is_torch(xp): + pytest.xfail("output[1] is wrong on pytorch") + + labels = xp.asarray([1.0, 2.5, 0.0, 4.5]) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[5, 4, 2, 5], + [3, 7, 8, 2], + [1, 5, 1, 1]], dtype=dtype) + output = ndimage.maximum_position(input, labels, + xp.asarray([1.0, 4.5])) + assert output[0] == (0, 0) + assert output[1] == (0, 3) + + +def test_extrema01(xp): + labels = np.asarray([1, 0], dtype=bool) + labels = xp.asarray(labels) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[1, 2], [3, 4]], dtype=dtype) + output1 = ndimage.extrema(input, labels=labels) + output2 = ndimage.minimum(input, labels=labels) + output3 = ndimage.maximum(input, labels=labels) + output4 = ndimage.minimum_position(input, + labels=labels) + output5 = ndimage.maximum_position(input, + labels=labels) + assert output1 == (output2, output3, output4, output5) + + +def test_extrema02(xp): + labels = xp.asarray([1, 2]) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[1, 2], [3, 4]], dtype=dtype) + output1 = ndimage.extrema(input, labels=labels, + index=2) + output2 = ndimage.minimum(input, labels=labels, + index=2) + output3 = ndimage.maximum(input, labels=labels, + index=2) + output4 = ndimage.minimum_position(input, + labels=labels, index=2) + output5 = ndimage.maximum_position(input, + labels=labels, index=2) + assert output1 == (output2, output3, output4, output5) + + +def test_extrema03(xp): + labels = xp.asarray([[1, 2], [2, 3]]) + for type in types: + if is_torch(xp) and type in ("uint16", "uint32", "uint64"): + pytest.xfail("https://github.com/pytorch/pytorch/issues/58734") + + dtype = getattr(xp, type) + input = xp.asarray([[1, 2], [3, 4]], dtype=dtype) + output1 = ndimage.extrema(input, + labels=labels, + index=xp.asarray([2, 3, 8])) + output2 = ndimage.minimum(input, + labels=labels, + index=xp.asarray([2, 3, 8])) + output3 = ndimage.maximum(input, labels=labels, + index=xp.asarray([2, 3, 8])) + output4 = ndimage.minimum_position(input, + labels=labels, + index=xp.asarray([2, 3, 8])) + output5 = ndimage.maximum_position(input, + labels=labels, + index=xp.asarray([2, 3, 8])) + assert_array_almost_equal(output1[0], output2) + assert_array_almost_equal(output1[1], output3) + assert output1[2] == output4 + assert output1[3] == output5 + + +def test_extrema04(xp): + labels = xp.asarray([1, 2, 0, 4]) + for type in types: + if is_torch(xp) and type in ("uint16", "uint32", "uint64"): + pytest.xfail("https://github.com/pytorch/pytorch/issues/58734") + + dtype = getattr(xp, type) + input = xp.asarray([[5, 4, 2, 5], + [3, 7, 8, 2], + [1, 5, 1, 1]], dtype=dtype) + output1 = ndimage.extrema(input, labels, xp.asarray([1, 2])) + output2 = ndimage.minimum(input, labels, xp.asarray([1, 2])) + output3 = ndimage.maximum(input, labels, xp.asarray([1, 2])) + output4 = ndimage.minimum_position(input, labels, + xp.asarray([1, 2])) + output5 = ndimage.maximum_position(input, labels, + xp.asarray([1, 2])) + assert_array_almost_equal(output1[0], output2) + assert_array_almost_equal(output1[1], output3) + assert output1[2] == output4 + assert output1[3] == output5 + + +def test_center_of_mass01(xp): + expected = (0.0, 0.0) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[1, 0], [0, 0]], dtype=dtype) + output = ndimage.center_of_mass(input) + assert output == expected + + +def test_center_of_mass02(xp): + expected = (1, 0) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[0, 0], [1, 0]], dtype=dtype) + output = ndimage.center_of_mass(input) + assert output == expected + + +def test_center_of_mass03(xp): + expected = (0, 1) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[0, 1], [0, 0]], dtype=dtype) + output = ndimage.center_of_mass(input) + assert output == expected + + +def test_center_of_mass04(xp): + expected = (1, 1) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[0, 0], [0, 1]], dtype=dtype) + output = ndimage.center_of_mass(input) + assert output == expected + + +def test_center_of_mass05(xp): + expected = (0.5, 0.5) + for type in types: + dtype = getattr(xp, type) + input = xp.asarray([[1, 1], [1, 1]], dtype=dtype) + output = ndimage.center_of_mass(input) + assert output == expected + + +def test_center_of_mass06(xp): + expected = (0.5, 0.5) + input = np.asarray([[1, 2], [3, 1]], dtype=bool) + input = xp.asarray(input) + output = ndimage.center_of_mass(input) + assert output == expected + + +def test_center_of_mass07(xp): + labels = xp.asarray([1, 0]) + expected = (0.5, 0.0) + input = np.asarray([[1, 2], [3, 1]], dtype=bool) + input = xp.asarray(input) + output = ndimage.center_of_mass(input, labels) + assert output == expected + + +def test_center_of_mass08(xp): + labels = xp.asarray([1, 2]) + expected = (0.5, 1.0) + input = np.asarray([[5, 2], [3, 1]], dtype=bool) + input = xp.asarray(input) + output = ndimage.center_of_mass(input, labels, 2) + assert output == expected + + +def test_center_of_mass09(xp): + labels = xp.asarray((1, 2)) + expected = xp.asarray([(0.5, 0.0), (0.5, 1.0)], dtype=xp.float64) + input = np.asarray([[1, 2], [1, 1]], dtype=bool) + input = xp.asarray(input) + output = ndimage.center_of_mass(input, labels, xp.asarray([1, 2])) + xp_assert_equal(xp.asarray(output), xp.asarray(expected)) + + +def test_histogram01(xp): + expected = xp.ones(10) + input = xp.arange(10) + output = ndimage.histogram(input, 0, 10, 10) + assert_array_almost_equal(output, expected) + + +def test_histogram02(xp): + labels = xp.asarray([1, 1, 1, 1, 2, 2, 2, 2]) + expected = xp.asarray([0, 2, 0, 1, 1]) + input = xp.asarray([1, 1, 3, 4, 3, 3, 3, 3]) + output = ndimage.histogram(input, 0, 4, 5, labels, 1) + assert_array_almost_equal(output, expected) + + +@skip_xp_backends(np_only=True, reason='object arrays') +def test_histogram03(xp): + labels = xp.asarray([1, 0, 1, 1, 2, 2, 2, 2]) + expected1 = xp.asarray([0, 1, 0, 1, 1]) + expected2 = xp.asarray([0, 0, 0, 3, 0]) + input = xp.asarray([1, 1, 3, 4, 3, 5, 3, 3]) + + output = ndimage.histogram(input, 0, 4, 5, labels, (1, 2)) + + assert_array_almost_equal(output[0], expected1) + assert_array_almost_equal(output[1], expected2) + + +def test_stat_funcs_2d(xp): + a = xp.asarray([[5, 6, 0, 0, 0], [8, 9, 0, 0, 0], [0, 0, 0, 3, 5]]) + lbl = xp.asarray([[1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [0, 0, 0, 2, 2]]) + + mean = ndimage.mean(a, labels=lbl, index=xp.asarray([1, 2])) + xp_assert_equal(mean, xp.asarray([7.0, 4.0], dtype=xp.float64)) + + var = ndimage.variance(a, labels=lbl, index=xp.asarray([1, 2])) + xp_assert_equal(var, xp.asarray([2.5, 1.0], dtype=xp.float64)) + + std = ndimage.standard_deviation(a, labels=lbl, index=xp.asarray([1, 2])) + assert_array_almost_equal(std, xp.sqrt(xp.asarray([2.5, 1.0], dtype=xp.float64))) + + med = ndimage.median(a, labels=lbl, index=xp.asarray([1, 2])) + xp_assert_equal(med, xp.asarray([7.0, 4.0], dtype=xp.float64)) + + min = ndimage.minimum(a, labels=lbl, index=xp.asarray([1, 2])) + xp_assert_equal(min, xp.asarray([5, 3]), check_dtype=False) + + max = ndimage.maximum(a, labels=lbl, index=xp.asarray([1, 2])) + xp_assert_equal(max, xp.asarray([9, 5]), check_dtype=False) + + +@skip_xp_backends("cupy", reason="no watershed_ift on CuPy") +class TestWatershedIft: + + def test_watershed_ift01(self, xp): + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 1, 0, 0, 0, 1, 0], + [0, 1, 0, 0, 0, 1, 0], + [0, 1, 0, 0, 0, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8) + markers = xp.asarray([[-1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=xp.int8) + structure=xp.asarray([[1, 1, 1], + [1, 1, 1], + [1, 1, 1]]) + out = ndimage.watershed_ift(data, markers, structure=structure) + expected = [[-1, -1, -1, -1, -1, -1, -1], + [-1, 1, 1, 1, 1, 1, -1], + [-1, 1, 1, 1, 1, 1, -1], + [-1, 1, 1, 1, 1, 1, -1], + [-1, 1, 1, 1, 1, 1, -1], + [-1, 1, 1, 1, 1, 1, -1], + [-1, -1, -1, -1, -1, -1, -1], + [-1, -1, -1, -1, -1, -1, -1]] + assert_array_almost_equal(out, xp.asarray(expected)) + + def test_watershed_ift02(self, xp): + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 1, 0, 0, 0, 1, 0], + [0, 1, 0, 0, 0, 1, 0], + [0, 1, 0, 0, 0, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8) + markers = xp.asarray([[-1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=xp.int8) + out = ndimage.watershed_ift(data, markers) + expected = [[-1, -1, -1, -1, -1, -1, -1], + [-1, -1, 1, 1, 1, -1, -1], + [-1, 1, 1, 1, 1, 1, -1], + [-1, 1, 1, 1, 1, 1, -1], + [-1, 1, 1, 1, 1, 1, -1], + [-1, -1, 1, 1, 1, -1, -1], + [-1, -1, -1, -1, -1, -1, -1], + [-1, -1, -1, -1, -1, -1, -1]] + assert_array_almost_equal(out, xp.asarray(expected)) + + def test_watershed_ift03(self, xp): + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 1, 0, 1, 0, 1, 0], + [0, 1, 0, 1, 0, 1, 0], + [0, 1, 0, 1, 0, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8) + markers = xp.asarray([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 2, 0, 3, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, -1]], dtype=xp.int8) + out = ndimage.watershed_ift(data, markers) + expected = [[-1, -1, -1, -1, -1, -1, -1], + [-1, -1, 2, -1, 3, -1, -1], + [-1, 2, 2, 3, 3, 3, -1], + [-1, 2, 2, 3, 3, 3, -1], + [-1, 2, 2, 3, 3, 3, -1], + [-1, -1, 2, -1, 3, -1, -1], + [-1, -1, -1, -1, -1, -1, -1]] + assert_array_almost_equal(out, xp.asarray(expected)) + + def test_watershed_ift04(self, xp): + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 1, 0, 1, 0, 1, 0], + [0, 1, 0, 1, 0, 1, 0], + [0, 1, 0, 1, 0, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8) + markers = xp.asarray([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 2, 0, 3, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, -1]], + dtype=xp.int8) + + structure=xp.asarray([[1, 1, 1], + [1, 1, 1], + [1, 1, 1]]) + out = ndimage.watershed_ift(data, markers, structure=structure) + expected = [[-1, -1, -1, -1, -1, -1, -1], + [-1, 2, 2, 3, 3, 3, -1], + [-1, 2, 2, 3, 3, 3, -1], + [-1, 2, 2, 3, 3, 3, -1], + [-1, 2, 2, 3, 3, 3, -1], + [-1, 2, 2, 3, 3, 3, -1], + [-1, -1, -1, -1, -1, -1, -1]] + assert_array_almost_equal(out, xp.asarray(expected)) + + def test_watershed_ift05(self, xp): + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 1, 0, 1, 0, 1, 0], + [0, 1, 0, 1, 0, 1, 0], + [0, 1, 0, 1, 0, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8) + markers = xp.asarray([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 3, 0, 2, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, -1]], + dtype=xp.int8) + structure = xp.asarray([[1, 1, 1], + [1, 1, 1], + [1, 1, 1]]) + out = ndimage.watershed_ift(data, markers, structure=structure) + expected = [[-1, -1, -1, -1, -1, -1, -1], + [-1, 3, 3, 2, 2, 2, -1], + [-1, 3, 3, 2, 2, 2, -1], + [-1, 3, 3, 2, 2, 2, -1], + [-1, 3, 3, 2, 2, 2, -1], + [-1, 3, 3, 2, 2, 2, -1], + [-1, -1, -1, -1, -1, -1, -1]] + assert_array_almost_equal(out, xp.asarray(expected)) + + def test_watershed_ift06(self, xp): + data = xp.asarray([[0, 1, 0, 0, 0, 1, 0], + [0, 1, 0, 0, 0, 1, 0], + [0, 1, 0, 0, 0, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8) + markers = xp.asarray([[-1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=xp.int8) + structure=xp.asarray([[1, 1, 1], + [1, 1, 1], + [1, 1, 1]]) + out = ndimage.watershed_ift(data, markers, structure=structure) + expected = [[-1, 1, 1, 1, 1, 1, -1], + [-1, 1, 1, 1, 1, 1, -1], + [-1, 1, 1, 1, 1, 1, -1], + [-1, 1, 1, 1, 1, 1, -1], + [-1, -1, -1, -1, -1, -1, -1], + [-1, -1, -1, -1, -1, -1, -1]] + assert_array_almost_equal(out, xp.asarray(expected)) + + @skip_xp_backends(np_only=True, reason="inplace ops are numpy-specific") + def test_watershed_ift07(self, xp): + shape = (7, 6) + data = np.zeros(shape, dtype=np.uint8) + data = data.transpose() + data[...] = np.asarray([[0, 1, 0, 0, 0, 1, 0], + [0, 1, 0, 0, 0, 1, 0], + [0, 1, 0, 0, 0, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=np.uint8) + data = xp.asarray(data) + markers = xp.asarray([[-1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=xp.int8) + out = xp.zeros(shape, dtype=xp.int16) + out = out.T + structure=xp.asarray([[1, 1, 1], + [1, 1, 1], + [1, 1, 1]]) + ndimage.watershed_ift(data, markers, structure=structure, + output=out) + expected = [[-1, 1, 1, 1, 1, 1, -1], + [-1, 1, 1, 1, 1, 1, -1], + [-1, 1, 1, 1, 1, 1, -1], + [-1, 1, 1, 1, 1, 1, -1], + [-1, -1, -1, -1, -1, -1, -1], + [-1, -1, -1, -1, -1, -1, -1]] + assert_array_almost_equal(out, xp.asarray(expected)) + + @skip_xp_backends("cupy", reason="no watershed_ift on CuPy") + def test_watershed_ift08(self, xp): + # Test cost larger than uint8. See gh-10069. + data = xp.asarray([[256, 0], + [0, 0]], dtype=xp.uint16) + markers = xp.asarray([[1, 0], + [0, 0]], dtype=xp.int8) + out = ndimage.watershed_ift(data, markers) + expected = [[1, 1], + [1, 1]] + assert_array_almost_equal(out, xp.asarray(expected)) + + @skip_xp_backends("cupy", reason="no watershed_ift on CuPy" ) + def test_watershed_ift09(self, xp): + # Test large cost. See gh-19575 + data = xp.asarray([[xp.iinfo(xp.uint16).max, 0], + [0, 0]], dtype=xp.uint16) + markers = xp.asarray([[1, 0], + [0, 0]], dtype=xp.int8) + out = ndimage.watershed_ift(data, markers) + expected = [[1, 1], + [1, 1]] + xp_assert_close(out, xp.asarray(expected), check_dtype=False) + + +@skip_xp_backends(np_only=True) +@pytest.mark.parametrize("dt", [np.intc, np.uintc]) +def test_gh_19423(dt, xp): + rng = np.random.default_rng(123) + max_val = 8 + image = rng.integers(low=0, high=max_val, size=(10, 12)).astype(dtype=dt) + val_idx = ndimage.value_indices(image) + assert len(val_idx.keys()) == max_val diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/tests/test_morphology.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/tests/test_morphology.py new file mode 100644 index 0000000000000000000000000000000000000000..9eff9a2c0f4a05295b7565761292b4ecaac007ac --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/tests/test_morphology.py @@ -0,0 +1,2938 @@ +import numpy as np +from scipy._lib._array_api import ( + is_cupy, is_numpy, is_torch, array_namespace, + xp_assert_close, xp_assert_equal, assert_array_almost_equal +) +import pytest +from pytest import raises as assert_raises + +from scipy import ndimage + +from . import types + +from scipy.conftest import array_api_compatible +skip_xp_backends = pytest.mark.skip_xp_backends +xfail_xp_backends = pytest.mark.xfail_xp_backends +pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends"), + pytest.mark.usefixtures("xfail_xp_backends"), + skip_xp_backends(cpu_only=True, exceptions=['cupy', 'jax.numpy'],)] + + +class TestNdimageMorphology: + + @xfail_xp_backends('cupy', reason='CuPy does not have distance_transform_bf.') + @pytest.mark.parametrize('dtype', types) + def test_distance_transform_bf01(self, dtype, xp): + dtype = getattr(xp, dtype) + + # brute force (bf) distance transform + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out, ft = ndimage.distance_transform_bf(data, 'euclidean', + return_indices=True) + expected = [[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 2, 4, 2, 1, 0, 0], + [0, 0, 1, 4, 8, 4, 1, 0, 0], + [0, 0, 1, 2, 4, 2, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + assert_array_almost_equal(out * out, expected) + + expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 1, 1, 1, 1], + [2, 2, 2, 2, 1, 2, 2, 2, 2], + [3, 3, 3, 2, 1, 2, 3, 3, 3], + [4, 4, 4, 4, 6, 4, 4, 4, 4], + [5, 5, 6, 6, 7, 6, 6, 5, 5], + [6, 6, 6, 7, 7, 7, 6, 6, 6], + [7, 7, 7, 7, 7, 7, 7, 7, 7], + [8, 8, 8, 8, 8, 8, 8, 8, 8]], + [[0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 2, 4, 6, 6, 7, 8], + [0, 1, 1, 2, 4, 6, 7, 7, 8], + [0, 1, 1, 1, 6, 7, 7, 7, 8], + [0, 1, 2, 2, 4, 6, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8]]] + expected = xp.asarray(expected) + assert_array_almost_equal(ft, expected) + + @xfail_xp_backends('cupy', reason='CuPy does not have distance_transform_bf.') + @pytest.mark.parametrize('dtype', types) + def test_distance_transform_bf02(self, dtype, xp): + dtype = getattr(xp, dtype) + + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out, ft = ndimage.distance_transform_bf(data, 'cityblock', + return_indices=True) + + expected = [[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 2, 2, 2, 1, 0, 0], + [0, 0, 1, 2, 3, 2, 1, 0, 0], + [0, 0, 1, 2, 2, 2, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + assert_array_almost_equal(out, expected) + + expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 1, 1, 1, 1], + [2, 2, 2, 2, 1, 2, 2, 2, 2], + [3, 3, 3, 3, 1, 3, 3, 3, 3], + [4, 4, 4, 4, 7, 4, 4, 4, 4], + [5, 5, 6, 7, 7, 7, 6, 5, 5], + [6, 6, 6, 7, 7, 7, 6, 6, 6], + [7, 7, 7, 7, 7, 7, 7, 7, 7], + [8, 8, 8, 8, 8, 8, 8, 8, 8]], + [[0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 2, 4, 6, 6, 7, 8], + [0, 1, 1, 1, 4, 7, 7, 7, 8], + [0, 1, 1, 1, 4, 7, 7, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8]]] + expected = xp.asarray(expected) + assert_array_almost_equal(expected, ft) + + @xfail_xp_backends('cupy', reason='CuPy does not have distance_transform_bf.') + @pytest.mark.parametrize('dtype', types) + def test_distance_transform_bf03(self, dtype, xp): + dtype = getattr(xp, dtype) + + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out, ft = ndimage.distance_transform_bf(data, 'chessboard', + return_indices=True) + + expected = [[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 2, 1, 1, 0, 0], + [0, 0, 1, 2, 2, 2, 1, 0, 0], + [0, 0, 1, 1, 2, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + assert_array_almost_equal(out, expected) + + expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 1, 1, 1, 1], + [2, 2, 2, 2, 1, 2, 2, 2, 2], + [3, 3, 4, 2, 2, 2, 4, 3, 3], + [4, 4, 5, 6, 6, 6, 5, 4, 4], + [5, 5, 6, 6, 7, 6, 6, 5, 5], + [6, 6, 6, 7, 7, 7, 6, 6, 6], + [7, 7, 7, 7, 7, 7, 7, 7, 7], + [8, 8, 8, 8, 8, 8, 8, 8, 8]], + [[0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 2, 5, 6, 6, 7, 8], + [0, 1, 1, 2, 6, 6, 7, 7, 8], + [0, 1, 1, 2, 6, 7, 7, 7, 8], + [0, 1, 2, 2, 6, 6, 7, 7, 8], + [0, 1, 2, 4, 5, 6, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8]]] + expected = xp.asarray(expected) + assert_array_almost_equal(ft, expected) + + @skip_xp_backends( + np_only=True, reason='inplace distances= arrays are numpy-specific' + ) + @pytest.mark.parametrize('dtype', types) + def test_distance_transform_bf04(self, dtype, xp): + dtype = getattr(xp, dtype) + + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + tdt, tft = ndimage.distance_transform_bf(data, return_indices=1) + dts = [] + fts = [] + dt = xp.zeros(data.shape, dtype=xp.float64) + ndimage.distance_transform_bf(data, distances=dt) + dts.append(dt) + ft = ndimage.distance_transform_bf( + data, return_distances=False, return_indices=1) + fts.append(ft) + ft = np.indices(data.shape, dtype=xp.int32) + ndimage.distance_transform_bf( + data, return_distances=False, return_indices=True, indices=ft) + fts.append(ft) + dt, ft = ndimage.distance_transform_bf( + data, return_indices=1) + dts.append(dt) + fts.append(ft) + dt = xp.zeros(data.shape, dtype=xp.float64) + ft = ndimage.distance_transform_bf( + data, distances=dt, return_indices=True) + dts.append(dt) + fts.append(ft) + ft = np.indices(data.shape, dtype=xp.int32) + dt = ndimage.distance_transform_bf( + data, return_indices=True, indices=ft) + dts.append(dt) + fts.append(ft) + dt = xp.zeros(data.shape, dtype=xp.float64) + ft = np.indices(data.shape, dtype=xp.int32) + ndimage.distance_transform_bf( + data, distances=dt, return_indices=True, indices=ft) + dts.append(dt) + fts.append(ft) + for dt in dts: + assert_array_almost_equal(tdt, dt) + for ft in fts: + assert_array_almost_equal(tft, ft) + + @xfail_xp_backends('cupy', reason='CuPy does not have distance_transform_bf.') + @pytest.mark.parametrize('dtype', types) + def test_distance_transform_bf05(self, dtype, xp): + dtype = getattr(xp, dtype) + + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out, ft = ndimage.distance_transform_bf( + data, 'euclidean', return_indices=True, sampling=[2, 2]) + expected = [[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 4, 4, 4, 0, 0, 0], + [0, 0, 4, 8, 16, 8, 4, 0, 0], + [0, 0, 4, 16, 32, 16, 4, 0, 0], + [0, 0, 4, 8, 16, 8, 4, 0, 0], + [0, 0, 0, 4, 4, 4, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + assert_array_almost_equal(out * out, expected) + + expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 1, 1, 1, 1], + [2, 2, 2, 2, 1, 2, 2, 2, 2], + [3, 3, 3, 2, 1, 2, 3, 3, 3], + [4, 4, 4, 4, 6, 4, 4, 4, 4], + [5, 5, 6, 6, 7, 6, 6, 5, 5], + [6, 6, 6, 7, 7, 7, 6, 6, 6], + [7, 7, 7, 7, 7, 7, 7, 7, 7], + [8, 8, 8, 8, 8, 8, 8, 8, 8]], + [[0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 2, 4, 6, 6, 7, 8], + [0, 1, 1, 2, 4, 6, 7, 7, 8], + [0, 1, 1, 1, 6, 7, 7, 7, 8], + [0, 1, 2, 2, 4, 6, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8]]] + expected = xp.asarray(expected) + assert_array_almost_equal(ft, expected) + + @xfail_xp_backends('cupy', reason='CuPy does not have distance_transform_bf.') + @pytest.mark.parametrize('dtype', types) + def test_distance_transform_bf06(self, dtype, xp): + dtype = getattr(xp, dtype) + + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out, ft = ndimage.distance_transform_bf( + data, 'euclidean', return_indices=True, sampling=[2, 1]) + expected = [[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 4, 1, 0, 0, 0], + [0, 0, 1, 4, 8, 4, 1, 0, 0], + [0, 0, 1, 4, 9, 4, 1, 0, 0], + [0, 0, 1, 4, 8, 4, 1, 0, 0], + [0, 0, 0, 1, 4, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + assert_array_almost_equal(out * out, expected) + + expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 1, 1, 1, 1], + [2, 2, 2, 2, 2, 2, 2, 2, 2], + [3, 3, 3, 3, 2, 3, 3, 3, 3], + [4, 4, 4, 4, 4, 4, 4, 4, 4], + [5, 5, 5, 5, 6, 5, 5, 5, 5], + [6, 6, 6, 6, 7, 6, 6, 6, 6], + [7, 7, 7, 7, 7, 7, 7, 7, 7], + [8, 8, 8, 8, 8, 8, 8, 8, 8]], + [[0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 2, 6, 6, 6, 7, 8], + [0, 1, 1, 1, 6, 7, 7, 7, 8], + [0, 1, 1, 1, 7, 7, 7, 7, 8], + [0, 1, 1, 1, 6, 7, 7, 7, 8], + [0, 1, 2, 2, 4, 6, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8]]] + expected = xp.asarray(expected) + assert_array_almost_equal(ft, expected) + + def test_distance_transform_bf07(self, xp): + if is_cupy(xp): + pytest.xfail("CuPy does not have distance_transform_bf.") + + # test input validation per discussion on PR #13302 + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]]) + with assert_raises(RuntimeError): + ndimage.distance_transform_bf( + data, return_distances=False, return_indices=False + ) + + @pytest.mark.parametrize('dtype', types) + def test_distance_transform_cdt01(self, dtype, xp): + dtype = getattr(xp, dtype) + if is_cupy(xp): + pytest.xfail("CuPy does not have distance_transform_cdt.") + + # chamfer type distance (cdt) transform + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out, ft = ndimage.distance_transform_cdt( + data, 'cityblock', return_indices=True) + bf = ndimage.distance_transform_bf(data, 'cityblock') + assert_array_almost_equal(bf, out) + + expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 1, 1, 1, 1], + [2, 2, 2, 1, 1, 1, 2, 2, 2], + [3, 3, 2, 1, 1, 1, 2, 3, 3], + [4, 4, 4, 4, 1, 4, 4, 4, 4], + [5, 5, 5, 5, 7, 7, 6, 5, 5], + [6, 6, 6, 6, 7, 7, 6, 6, 6], + [7, 7, 7, 7, 7, 7, 7, 7, 7], + [8, 8, 8, 8, 8, 8, 8, 8, 8]], + [[0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 1, 1, 4, 7, 7, 7, 8], + [0, 1, 1, 1, 4, 5, 6, 7, 8], + [0, 1, 2, 2, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8]]] + expected = xp.asarray(expected) + assert_array_almost_equal(ft, expected) + + @pytest.mark.parametrize('dtype', types) + def test_distance_transform_cdt02(self, dtype, xp): + dtype = getattr(xp, dtype) + if is_cupy(xp): + pytest.xfail("CuPy does not have distance_transform_cdt.") + + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out, ft = ndimage.distance_transform_cdt(data, 'chessboard', + return_indices=True) + bf = ndimage.distance_transform_bf(data, 'chessboard') + assert_array_almost_equal(bf, out) + + expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 1, 1, 1, 1], + [2, 2, 2, 1, 1, 1, 2, 2, 2], + [3, 3, 2, 2, 1, 2, 2, 3, 3], + [4, 4, 3, 2, 2, 2, 3, 4, 4], + [5, 5, 4, 6, 7, 6, 4, 5, 5], + [6, 6, 6, 6, 7, 7, 6, 6, 6], + [7, 7, 7, 7, 7, 7, 7, 7, 7], + [8, 8, 8, 8, 8, 8, 8, 8, 8]], + [[0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 2, 3, 4, 6, 7, 8], + [0, 1, 1, 2, 2, 6, 6, 7, 8], + [0, 1, 1, 1, 2, 6, 7, 7, 8], + [0, 1, 1, 2, 6, 6, 7, 7, 8], + [0, 1, 2, 2, 5, 6, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8], + [0, 1, 2, 3, 4, 5, 6, 7, 8]]] + expected = xp.asarray(expected) + assert_array_almost_equal(ft, expected) + + @skip_xp_backends( + np_only=True, reason='inplace indices= arrays are numpy-specific' + ) + @pytest.mark.parametrize('dtype', types) + def test_distance_transform_cdt03(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + tdt, tft = ndimage.distance_transform_cdt(data, return_indices=True) + dts = [] + fts = [] + dt = xp.zeros(data.shape, dtype=xp.int32) + ndimage.distance_transform_cdt(data, distances=dt) + dts.append(dt) + ft = ndimage.distance_transform_cdt( + data, return_distances=False, return_indices=True) + fts.append(ft) + ft = xp.asarray(np.indices(data.shape, dtype=np.int32)) + ndimage.distance_transform_cdt( + data, return_distances=False, return_indices=True, indices=ft) + fts.append(ft) + dt, ft = ndimage.distance_transform_cdt( + data, return_indices=True) + dts.append(dt) + fts.append(ft) + dt = xp.zeros(data.shape, dtype=xp.int32) + ft = ndimage.distance_transform_cdt( + data, distances=dt, return_indices=True) + dts.append(dt) + fts.append(ft) + ft = xp.asarray(np.indices(data.shape, dtype=np.int32)) + dt = ndimage.distance_transform_cdt( + data, return_indices=True, indices=ft) + dts.append(dt) + fts.append(ft) + dt = xp.zeros(data.shape, dtype=xp.int32) + ft = xp.asarray(np.indices(data.shape, dtype=np.int32)) + ndimage.distance_transform_cdt(data, distances=dt, + return_indices=True, indices=ft) + dts.append(dt) + fts.append(ft) + for dt in dts: + assert_array_almost_equal(tdt, dt) + for ft in fts: + assert_array_almost_equal(tft, ft) + + @skip_xp_backends( + np_only=True, reason='XXX: does not raise unless indices is a numpy array' + ) + def test_distance_transform_cdt04(self, xp): + # test input validation per discussion on PR #13302 + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]]) + indices_out = xp.zeros((data.ndim,) + data.shape, dtype=xp.int32) + with assert_raises(RuntimeError): + ndimage.distance_transform_bf( + data, + return_distances=True, + return_indices=False, + indices=indices_out + ) + + @pytest.mark.parametrize('dtype', types) + def test_distance_transform_cdt05(self, dtype, xp): + dtype = getattr(xp, dtype) + if is_cupy(xp): + pytest.xfail("CuPy does not have distance_transform_cdt.") + elif is_torch(xp): + pytest.xfail("int overflow") + + # test custom metric type per discussion on issue #17381 + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + metric_arg = xp.ones((3, 3)) + actual = ndimage.distance_transform_cdt(data, metric=metric_arg) + assert xp.sum(actual) == -21 + + @pytest.mark.parametrize('dtype', types) + def test_distance_transform_edt01(self, dtype, xp): + dtype = getattr(xp, dtype) + if is_cupy(xp): + pytest.xfail("CuPy does not have distance_transform_bf") + + # euclidean distance transform (edt) + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out, ft = ndimage.distance_transform_edt(data, return_indices=True) + bf = ndimage.distance_transform_bf(data, 'euclidean') + assert_array_almost_equal(bf, out) + + # np-specific check + np_ft = np.asarray(ft) + dt = np_ft - np.indices(np_ft.shape[1:], dtype=np_ft.dtype) + dt = dt.astype(np.float64) + np.multiply(dt, dt, dt) + dt = np.add.reduce(dt, axis=0) + np.sqrt(dt, dt) + + dt = xp.asarray(dt) + assert_array_almost_equal(bf, dt) + + @skip_xp_backends( + np_only=True, reason='inplace distances= are numpy-specific' + ) + @pytest.mark.parametrize('dtype', types) + def test_distance_transform_edt02(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + tdt, tft = ndimage.distance_transform_edt(data, return_indices=True) + dts = [] + fts = [] + + dt = xp.zeros(data.shape, dtype=xp.float64) + ndimage.distance_transform_edt(data, distances=dt) + dts.append(dt) + + ft = ndimage.distance_transform_edt( + data, return_distances=0, return_indices=True) + fts.append(ft) + + ft = np.indices(data.shape, dtype=xp.int32) + ft = xp.asarray(ft) + ndimage.distance_transform_edt( + data, return_distances=False, return_indices=True, indices=ft) + fts.append(ft) + + dt, ft = ndimage.distance_transform_edt( + data, return_indices=True) + dts.append(dt) + fts.append(ft) + + dt = xp.zeros(data.shape, dtype=xp.float64) + ft = ndimage.distance_transform_edt( + data, distances=dt, return_indices=True) + dts.append(dt) + fts.append(ft) + + ft = np.indices(data.shape, dtype=xp.int32) + ft = xp.asarray(ft) + dt = ndimage.distance_transform_edt( + data, return_indices=True, indices=ft) + dts.append(dt) + fts.append(ft) + + dt = xp.zeros(data.shape, dtype=xp.float64) + ft = np.indices(data.shape, dtype=xp.int32) + ft = xp.asarray(ft) + ndimage.distance_transform_edt( + data, distances=dt, return_indices=True, indices=ft) + dts.append(dt) + fts.append(ft) + + for dt in dts: + assert_array_almost_equal(tdt, dt) + for ft in fts: + assert_array_almost_equal(tft, ft) + + @pytest.mark.parametrize('dtype', types) + def test_distance_transform_edt03(self, dtype, xp): + dtype = getattr(xp, dtype) + if is_cupy(xp): + pytest.xfail("CuPy does not have distance_transform_bf") + + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + ref = ndimage.distance_transform_bf(data, 'euclidean', sampling=[2, 2]) + out = ndimage.distance_transform_edt(data, sampling=[2, 2]) + assert_array_almost_equal(ref, out) + + @pytest.mark.parametrize('dtype', types) + def test_distance_transform_edt4(self, dtype, xp): + dtype = getattr(xp, dtype) + if is_cupy(xp): + pytest.xfail("CuPy does not have distance_transform_bf") + + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + ref = ndimage.distance_transform_bf(data, 'euclidean', sampling=[2, 1]) + out = ndimage.distance_transform_edt(data, sampling=[2, 1]) + assert_array_almost_equal(ref, out) + + def test_distance_transform_edt5(self, xp): + # Ticket #954 regression test + out = ndimage.distance_transform_edt(False) + assert_array_almost_equal(out, [0.]) + + @skip_xp_backends( + np_only=True, reason='XXX: does not raise unless indices is a numpy array' + ) + def test_distance_transform_edt6(self, xp): + # test input validation per discussion on PR #13302 + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]]) + distances_out = xp.zeros(data.shape, dtype=xp.float64) + with assert_raises(RuntimeError): + ndimage.distance_transform_bf( + data, + return_indices=True, + return_distances=False, + distances=distances_out + ) + + def test_generate_structure01(self, xp): + struct = ndimage.generate_binary_structure(0, 1) + assert struct == 1 + + def test_generate_structure02(self, xp): + struct = ndimage.generate_binary_structure(1, 1) + assert_array_almost_equal(struct, [1, 1, 1]) + + def test_generate_structure03(self, xp): + struct = ndimage.generate_binary_structure(2, 1) + assert_array_almost_equal(struct, [[0, 1, 0], + [1, 1, 1], + [0, 1, 0]]) + + def test_generate_structure04(self, xp): + struct = ndimage.generate_binary_structure(2, 2) + assert_array_almost_equal(struct, [[1, 1, 1], + [1, 1, 1], + [1, 1, 1]]) + + def test_iterate_structure01(self, xp): + struct = [[0, 1, 0], + [1, 1, 1], + [0, 1, 0]] + struct = xp.asarray(struct) + out = ndimage.iterate_structure(struct, 2) + expected = np.asarray([[0, 0, 1, 0, 0], + [0, 1, 1, 1, 0], + [1, 1, 1, 1, 1], + [0, 1, 1, 1, 0], + [0, 0, 1, 0, 0]], dtype=bool) + expected = xp.asarray(expected) + assert_array_almost_equal(out, expected) + + def test_iterate_structure02(self, xp): + struct = [[0, 1], + [1, 1], + [0, 1]] + struct = xp.asarray(struct) + out = ndimage.iterate_structure(struct, 2) + expected = np.asarray([[0, 0, 1], + [0, 1, 1], + [1, 1, 1], + [0, 1, 1], + [0, 0, 1]], dtype=bool) + expected = xp.asarray(expected) + + assert_array_almost_equal(out, expected) + + def test_iterate_structure03(self, xp): + struct = [[0, 1, 0], + [1, 1, 1], + [0, 1, 0]] + struct = xp.asarray(struct) + out = ndimage.iterate_structure(struct, 2, 1) + expected = [[0, 0, 1, 0, 0], + [0, 1, 1, 1, 0], + [1, 1, 1, 1, 1], + [0, 1, 1, 1, 0], + [0, 0, 1, 0, 0]] + expected = np.asarray(expected, dtype=bool) + expected = xp.asarray(expected) + assert_array_almost_equal(out[0], expected) + assert out[1] == [2, 2] + + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion01(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones([], dtype=dtype) + out = ndimage.binary_erosion(data) + assert out == xp.asarray(1, dtype=out.dtype) + + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion02(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones([], dtype=dtype) + out = ndimage.binary_erosion(data, border_value=1) + assert out == xp.asarray(1, dtype=out.dtype) + + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion03(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones([1], dtype=dtype) + out = ndimage.binary_erosion(data) + assert_array_almost_equal(out, xp.asarray([0])) + + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion04(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones([1], dtype=dtype) + out = ndimage.binary_erosion(data, border_value=1) + assert_array_almost_equal(out, xp.asarray([1])) + + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion05(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones([3], dtype=dtype) + out = ndimage.binary_erosion(data) + assert_array_almost_equal(out, xp.asarray([0, 1, 0])) + + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion06(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones([3], dtype=dtype) + out = ndimage.binary_erosion(data, border_value=1) + assert_array_almost_equal(out, xp.asarray([1, 1, 1])) + + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion07(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones([5], dtype=dtype) + out = ndimage.binary_erosion(data) + assert_array_almost_equal(out, xp.asarray([0, 1, 1, 1, 0])) + + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion08(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones([5], dtype=dtype) + out = ndimage.binary_erosion(data, border_value=1) + assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1, 1])) + + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion09(self, dtype, xp): + data = np.ones([5], dtype=dtype) + data[2] = 0 + data = xp.asarray(data) + out = ndimage.binary_erosion(data) + assert_array_almost_equal(out, xp.asarray([0, 0, 0, 0, 0])) + + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion10(self, dtype, xp): + data = np.ones([5], dtype=dtype) + data[2] = 0 + data = xp.asarray(data) + out = ndimage.binary_erosion(data, border_value=1) + assert_array_almost_equal(out, xp.asarray([1, 0, 0, 0, 1])) + + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion11(self, dtype, xp): + data = np.ones([5], dtype=dtype) + data[2] = 0 + data = xp.asarray(data) + struct = xp.asarray([1, 0, 1]) + out = ndimage.binary_erosion(data, struct, border_value=1) + assert_array_almost_equal(out, xp.asarray([1, 0, 1, 0, 1])) + + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion12(self, dtype, xp): + data = np.ones([5], dtype=dtype) + data[2] = 0 + data = xp.asarray(data) + struct = xp.asarray([1, 0, 1]) + out = ndimage.binary_erosion(data, struct, border_value=1, origin=-1) + assert_array_almost_equal(out, xp.asarray([0, 1, 0, 1, 1])) + + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion13(self, dtype, xp): + data = np.ones([5], dtype=dtype) + data[2] = 0 + data = xp.asarray(data) + struct = xp.asarray([1, 0, 1]) + out = ndimage.binary_erosion(data, struct, border_value=1, origin=1) + assert_array_almost_equal(out, xp.asarray([1, 1, 0, 1, 0])) + + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion14(self, dtype, xp): + data = np.ones([5], dtype=dtype) + data[2] = 0 + data = xp.asarray(data) + struct = xp.asarray([1, 1]) + out = ndimage.binary_erosion(data, struct, border_value=1) + assert_array_almost_equal(out, xp.asarray([1, 1, 0, 0, 1])) + + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion15(self, dtype, xp): + data = np.ones([5], dtype=dtype) + data[2] = 0 + data = xp.asarray(data) + struct = xp.asarray([1, 1]) + out = ndimage.binary_erosion(data, struct, border_value=1, origin=-1) + assert_array_almost_equal(out, xp.asarray([1, 0, 0, 1, 1])) + + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion16(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones([1, 1], dtype=dtype) + out = ndimage.binary_erosion(data, border_value=1) + assert_array_almost_equal(out, xp.asarray([[1]])) + + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion17(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones([1, 1], dtype=dtype) + out = ndimage.binary_erosion(data) + assert_array_almost_equal(out, xp.asarray([[0]])) + + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion18(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones([1, 3], dtype=dtype) + out = ndimage.binary_erosion(data) + assert_array_almost_equal(out, xp.asarray([[0, 0, 0]])) + + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion19(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones([1, 3], dtype=dtype) + out = ndimage.binary_erosion(data, border_value=1) + assert_array_almost_equal(out, xp.asarray([[1, 1, 1]])) + + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion20(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones([3, 3], dtype=dtype) + out = ndimage.binary_erosion(data) + assert_array_almost_equal(out, xp.asarray([[0, 0, 0], + [0, 1, 0], + [0, 0, 0]])) + + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion21(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones([3, 3], dtype=dtype) + out = ndimage.binary_erosion(data, border_value=1) + assert_array_almost_equal(out, xp.asarray([[1, 1, 1], + [1, 1, 1], + [1, 1, 1]])) + + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion22(self, dtype, xp): + dtype = getattr(xp, dtype) + expected = [[0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 1, 0, 0, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 1, 1], + [0, 0, 1, 1, 1, 1, 1, 1], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 0, 0, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out = ndimage.binary_erosion(data, border_value=1) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion23(self, dtype, xp): + dtype = getattr(xp, dtype) + struct = ndimage.generate_binary_structure(2, 2) + struct = xp.asarray(struct) + expected = [[0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 1, 1], + [0, 0, 1, 1, 1, 1, 1, 1], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 0, 0, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out = ndimage.binary_erosion(data, struct, border_value=1) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion24(self, dtype, xp): + dtype = getattr(xp, dtype) + struct = xp.asarray([[0, 1], + [1, 1]]) + expected = [[0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 1, 1], + [0, 0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 0, 0, 0, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 1, 1], + [0, 0, 1, 1, 1, 1, 1, 1], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 0, 0, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out = ndimage.binary_erosion(data, struct, border_value=1) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion25(self, dtype, xp): + dtype = getattr(xp, dtype) + struct = [[0, 1, 0], + [1, 0, 1], + [0, 1, 0]] + struct = xp.asarray(struct) + expected = [[0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 1, 1], + [0, 0, 1, 1, 1, 0, 1, 1], + [0, 0, 1, 0, 1, 1, 0, 0], + [0, 1, 0, 1, 1, 1, 1, 0], + [0, 1, 1, 0, 0, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out = ndimage.binary_erosion(data, struct, border_value=1) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('dtype', types) + def test_binary_erosion26(self, dtype, xp): + dtype = getattr(xp, dtype) + struct = [[0, 1, 0], + [1, 0, 1], + [0, 1, 0]] + struct = xp.asarray(struct) + expected = [[0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 1], + [0, 0, 0, 0, 1, 0, 0, 1], + [0, 0, 1, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 1]] + expected = xp.asarray(expected) + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 1, 1], + [0, 0, 1, 1, 1, 0, 1, 1], + [0, 0, 1, 0, 1, 1, 0, 0], + [0, 1, 0, 1, 1, 1, 1, 0], + [0, 1, 1, 0, 0, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out = ndimage.binary_erosion(data, struct, border_value=1, + origin=(-1, -1)) + assert_array_almost_equal(out, expected) + + def test_binary_erosion27(self, xp): + if is_cupy(xp): + pytest.xfail("CuPy: NotImplementedError: only brute_force iteration") + + struct = [[0, 1, 0], + [1, 1, 1], + [0, 1, 0]] + struct = xp.asarray(struct) + expected = [[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + data = np.asarray([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + out = ndimage.binary_erosion(data, struct, border_value=1, + iterations=2) + assert_array_almost_equal(out, expected) + + @skip_xp_backends( + np_only=True, reason='inplace out= arguments are numpy-specific' + ) + def test_binary_erosion28(self, xp): + struct = [[0, 1, 0], + [1, 1, 1], + [0, 1, 0]] + struct = xp.asarray(struct) + expected = [[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]] + expected = np.asarray(expected, dtype=bool) + expected = xp.asarray(expected) + data = np.asarray([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + out = np.zeros(data.shape, dtype=bool) + out = xp.asarray(out) + ndimage.binary_erosion(data, struct, border_value=1, + iterations=2, output=out) + assert_array_almost_equal(out, expected) + + def test_binary_erosion29(self, xp): + if is_cupy(xp): + pytest.xfail("CuPy: NotImplementedError: only brute_force iteration") + + struct = [[0, 1, 0], + [1, 1, 1], + [0, 1, 0]] + struct = xp.asarray(struct) + expected = [[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + data = np.asarray([[0, 0, 0, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [1, 1, 1, 1, 1, 1, 1], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + out = ndimage.binary_erosion(data, struct, + border_value=1, iterations=3) + assert_array_almost_equal(out, expected) + + @skip_xp_backends( + np_only=True, reason='inplace out= arguments are numpy-specific' + ) + def test_binary_erosion30(self, xp): + if is_cupy(xp): + pytest.xfail("CuPy: NotImplementedError: only brute_force iteration") + + struct = [[0, 1, 0], + [1, 1, 1], + [0, 1, 0]] + struct = xp.asarray(struct) + expected = [[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]] + expected = np.asarray(expected, dtype=bool) + expected = xp.asarray(expected) + data = np.asarray([[0, 0, 0, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [1, 1, 1, 1, 1, 1, 1], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + out = np.zeros(data.shape, dtype=bool) + out = xp.asarray(out) + ndimage.binary_erosion(data, struct, border_value=1, + iterations=3, output=out) + assert_array_almost_equal(out, expected) + + # test with output memory overlap + ndimage.binary_erosion(data, struct, border_value=1, + iterations=3, output=data) + assert_array_almost_equal(data, expected) + + @skip_xp_backends( + np_only=True, reason='inplace out= arguments are numpy-specific' + ) + def test_binary_erosion31(self, xp): + struct = [[0, 1, 0], + [1, 1, 1], + [0, 1, 0]] + struct = xp.asarray(struct) + expected = [[0, 0, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 0, 0], + [1, 1, 1, 1, 1, 0, 1], + [0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 1]] + expected = np.asarray(expected, dtype=bool) + expected = xp.asarray(expected) + data = np.asarray([[0, 0, 0, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [1, 1, 1, 1, 1, 1, 1], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + out = np.zeros(data.shape, dtype=bool) + out = xp.asarray(out) + ndimage.binary_erosion(data, struct, border_value=1, + iterations=1, output=out, origin=(-1, -1)) + assert_array_almost_equal(out, expected) + + def test_binary_erosion32(self, xp): + if is_cupy(xp): + pytest.xfail("CuPy: NotImplementedError: only brute_force iteration") + + struct = [[0, 1, 0], + [1, 1, 1], + [0, 1, 0]] + struct = xp.asarray(struct) + expected = [[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + data = np.asarray([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + out = ndimage.binary_erosion(data, struct, + border_value=1, iterations=2) + assert_array_almost_equal(out, expected) + + def test_binary_erosion33(self, xp): + if is_cupy(xp): + pytest.xfail("CuPy: NotImplementedError: only brute_force iteration") + + struct = [[0, 1, 0], + [1, 1, 1], + [0, 1, 0]] + struct = xp.asarray(struct) + expected = [[0, 0, 0, 0, 0, 1, 1], + [0, 0, 0, 0, 0, 0, 1], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + mask = [[1, 1, 1, 1, 1, 0, 0], + [1, 1, 1, 1, 1, 1, 0], + [1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1]] + mask = xp.asarray(mask) + data = np.asarray([[0, 0, 0, 0, 0, 1, 1], + [0, 0, 0, 1, 0, 0, 1], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + out = ndimage.binary_erosion(data, struct, + border_value=1, mask=mask, iterations=-1) + assert_array_almost_equal(out, expected) + + def test_binary_erosion34(self, xp): + struct = [[0, 1, 0], + [1, 1, 1], + [0, 1, 0]] + struct = xp.asarray(struct) + expected = [[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + mask = [[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 0, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]] + mask = xp.asarray(mask) + data = np.asarray([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + out = ndimage.binary_erosion(data, struct, + border_value=1, mask=mask) + assert_array_almost_equal(out, expected) + + @skip_xp_backends( + np_only=True, reason='inplace out= arguments are numpy-specific' + ) + def test_binary_erosion35(self, xp): + struct = [[0, 1, 0], + [1, 1, 1], + [0, 1, 0]] + struct = xp.asarray(struct) + mask = [[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 0, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]] + mask = np.asarray(mask, dtype=bool) + mask = xp.asarray(mask) + data = np.asarray([[0, 0, 0, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [1, 1, 1, 1, 1, 1, 1], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + tmp = [[0, 0, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 0, 0], + [1, 1, 1, 1, 1, 0, 1], + [0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 1]] + tmp = np.asarray(tmp, dtype=bool) + tmp = xp.asarray(tmp) + expected = xp.logical_and(tmp, mask) + tmp = xp.logical_and(data, xp.logical_not(mask)) + expected = xp.logical_or(expected, tmp) + out = np.zeros(data.shape, dtype=bool) + out = xp.asarray(out) + ndimage.binary_erosion(data, struct, border_value=1, + iterations=1, output=out, + origin=(-1, -1), mask=mask) + assert_array_almost_equal(out, expected) + + def test_binary_erosion36(self, xp): + if is_cupy(xp): + pytest.xfail("CuPy: NotImplementedError: only brute_force iteration") + + struct = [[0, 1, 0], + [1, 0, 1], + [0, 1, 0]] + struct = xp.asarray(struct) + mask = [[0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 0, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]] + mask = np.asarray(mask, dtype=bool) + mask = xp.asarray(mask) + tmp = [[0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 1], + [0, 0, 0, 0, 1, 0, 0, 1], + [0, 0, 1, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 1]] + tmp = np.asarray(tmp, dtype=bool) + tmp = xp.asarray(tmp) + data = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 1, 1], + [0, 0, 1, 1, 1, 0, 1, 1], + [0, 0, 1, 0, 1, 1, 0, 0], + [0, 1, 0, 1, 1, 1, 1, 0], + [0, 1, 1, 0, 0, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + expected = xp.logical_and(tmp, mask) + tmp = xp.logical_and(data, xp.logical_not(mask)) + expected = xp.logical_or(expected, tmp) + out = ndimage.binary_erosion(data, struct, mask=mask, + border_value=1, origin=(-1, -1)) + assert_array_almost_equal(out, expected) + + @skip_xp_backends( + np_only=True, reason='inplace out= arguments are numpy-specific' + ) + def test_binary_erosion37(self, xp): + a = np.asarray([[1, 0, 1], + [0, 1, 0], + [1, 0, 1]], dtype=bool) + a = xp.asarray(a) + b = xp.zeros_like(a) + out = ndimage.binary_erosion(a, structure=a, output=b, iterations=0, + border_value=True, brute_force=True) + assert out is b + xp_assert_equal( + ndimage.binary_erosion(a, structure=a, iterations=0, + border_value=True), + b) + + def test_binary_erosion38(self, xp): + data = np.asarray([[1, 0, 1], + [0, 1, 0], + [1, 0, 1]], dtype=bool) + data = xp.asarray(data) + iterations = 2.0 + with assert_raises(TypeError): + _ = ndimage.binary_erosion(data, iterations=iterations) + + @skip_xp_backends( + np_only=True, reason='inplace out= arguments are numpy-specific' + ) + def test_binary_erosion39(self, xp): + iterations = np.int32(3) + struct = [[0, 1, 0], + [1, 1, 1], + [0, 1, 0]] + struct = xp.asarray(struct) + expected = [[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected, dtype=bool) + expected = xp.asarray(expected) + data = np.asarray([[0, 0, 0, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [1, 1, 1, 1, 1, 1, 1], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + out = np.zeros(data.shape, dtype=bool) + out = xp.asarray(out) + ndimage.binary_erosion(data, struct, border_value=1, + iterations=iterations, output=out) + assert_array_almost_equal(out, expected) + + @skip_xp_backends( + np_only=True, reason='inplace out= arguments are numpy-specific' + ) + def test_binary_erosion40(self, xp): + iterations = np.int64(3) + struct = [[0, 1, 0], + [1, 1, 1], + [0, 1, 0]] + struct = xp.asarray(struct) + expected = [[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]] + expected = np.asarray(expected, dtype=bool) + expected = xp.asarray(expected) + data = np.asarray([[0, 0, 0, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [1, 1, 1, 1, 1, 1, 1], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + out = np.zeros(data.shape, dtype=bool) + out = xp.asarray(out) + ndimage.binary_erosion(data, struct, border_value=1, + iterations=iterations, output=out) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('dtype', types) + def test_binary_dilation01(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones([], dtype=dtype) + out = ndimage.binary_dilation(data) + assert out == xp.asarray(1, dtype=out.dtype) + + @pytest.mark.parametrize('dtype', types) + def test_binary_dilation02(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.zeros([], dtype=dtype) + out = ndimage.binary_dilation(data) + assert out == xp.asarray(False) + + @pytest.mark.parametrize('dtype', types) + def test_binary_dilation03(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones([1], dtype=dtype) + out = ndimage.binary_dilation(data) + assert_array_almost_equal(out, xp.asarray([1], dtype=out.dtype)) + + @pytest.mark.parametrize('dtype', types) + def test_binary_dilation04(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.zeros([1], dtype=dtype) + out = ndimage.binary_dilation(data) + assert_array_almost_equal(out, xp.asarray([0])) + + @pytest.mark.parametrize('dtype', types) + def test_binary_dilation05(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones([3], dtype=dtype) + out = ndimage.binary_dilation(data) + assert_array_almost_equal(out, xp.asarray([1, 1, 1])) + + @pytest.mark.parametrize('dtype', types) + def test_binary_dilation06(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.zeros([3], dtype=dtype) + out = ndimage.binary_dilation(data) + assert_array_almost_equal(out, xp.asarray([0, 0, 0])) + + @pytest.mark.parametrize('dtype', types) + def test_binary_dilation07(self, dtype, xp): + data = np.zeros([3], dtype=dtype) + data[1] = 1 + data = xp.asarray(data) + out = ndimage.binary_dilation(data) + assert_array_almost_equal(out, xp.asarray([1, 1, 1])) + + @pytest.mark.parametrize('dtype', types) + def test_binary_dilation08(self, dtype, xp): + data = np.zeros([5], dtype=dtype) + data[1] = 1 + data[3] = 1 + data = xp.asarray(data) + out = ndimage.binary_dilation(data) + assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1, 1])) + + @pytest.mark.parametrize('dtype', types) + def test_binary_dilation09(self, dtype, xp): + data = np.zeros([5], dtype=dtype) + data[1] = 1 + data = xp.asarray(data) + out = ndimage.binary_dilation(data) + assert_array_almost_equal(out, xp.asarray([1, 1, 1, 0, 0])) + + @pytest.mark.parametrize('dtype', types) + def test_binary_dilation10(self, dtype, xp): + data = np.zeros([5], dtype=dtype) + data[1] = 1 + data = xp.asarray(data) + out = ndimage.binary_dilation(data, origin=-1) + assert_array_almost_equal(out, xp.asarray([0, 1, 1, 1, 0])) + + @pytest.mark.parametrize('dtype', types) + def test_binary_dilation11(self, dtype, xp): + data = np.zeros([5], dtype=dtype) + data[1] = 1 + data = xp.asarray(data) + out = ndimage.binary_dilation(data, origin=1) + assert_array_almost_equal(out, xp.asarray([1, 1, 0, 0, 0])) + + @pytest.mark.parametrize('dtype', types) + def test_binary_dilation12(self, dtype, xp): + data = np.zeros([5], dtype=dtype) + data[1] = 1 + data = xp.asarray(data) + struct = xp.asarray([1, 0, 1]) + out = ndimage.binary_dilation(data, struct) + assert_array_almost_equal(out, xp.asarray([1, 0, 1, 0, 0])) + + @pytest.mark.parametrize('dtype', types) + def test_binary_dilation13(self, dtype, xp): + data = np.zeros([5], dtype=dtype) + data[1] = 1 + data = xp.asarray(data) + struct = xp.asarray([1, 0, 1]) + out = ndimage.binary_dilation(data, struct, border_value=1) + assert_array_almost_equal(out, xp.asarray([1, 0, 1, 0, 1])) + + @pytest.mark.parametrize('dtype', types) + def test_binary_dilation14(self, dtype, xp): + data = np.zeros([5], dtype=dtype) + data[1] = 1 + data = xp.asarray(data) + struct = xp.asarray([1, 0, 1]) + out = ndimage.binary_dilation(data, struct, origin=-1) + assert_array_almost_equal(out, xp.asarray([0, 1, 0, 1, 0])) + + @pytest.mark.parametrize('dtype', types) + def test_binary_dilation15(self, dtype, xp): + data = np.zeros([5], dtype=dtype) + data[1] = 1 + data = xp.asarray(data) + struct = xp.asarray([1, 0, 1]) + out = ndimage.binary_dilation(data, struct, + origin=-1, border_value=1) + assert_array_almost_equal(out, xp.asarray([1, 1, 0, 1, 0])) + + @pytest.mark.parametrize('dtype', types) + def test_binary_dilation16(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones([1, 1], dtype=dtype) + out = ndimage.binary_dilation(data) + assert_array_almost_equal(out, xp.asarray([[1]])) + + @pytest.mark.parametrize('dtype', types) + def test_binary_dilation17(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.zeros([1, 1], dtype=dtype) + out = ndimage.binary_dilation(data) + assert_array_almost_equal(out, xp.asarray([[0]])) + + @pytest.mark.parametrize('dtype', types) + def test_binary_dilation18(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones([1, 3], dtype=dtype) + out = ndimage.binary_dilation(data) + assert_array_almost_equal(out, xp.asarray([[1, 1, 1]])) + + @pytest.mark.parametrize('dtype', types) + def test_binary_dilation19(self, dtype, xp): + dtype = getattr(xp, dtype) + data = xp.ones([3, 3], dtype=dtype) + out = ndimage.binary_dilation(data) + assert_array_almost_equal(out, xp.asarray([[1, 1, 1], + [1, 1, 1], + [1, 1, 1]])) + + @pytest.mark.parametrize('dtype', types) + def test_binary_dilation20(self, dtype, xp): + data = np.zeros([3, 3], dtype=dtype) + data[1, 1] = 1 + data = xp.asarray(data) + out = ndimage.binary_dilation(data) + assert_array_almost_equal(out, xp.asarray([[0, 1, 0], + [1, 1, 1], + [0, 1, 0]])) + + @pytest.mark.parametrize('dtype', types) + def test_binary_dilation21(self, dtype, xp): + struct = ndimage.generate_binary_structure(2, 2) + struct = xp.asarray(struct) + data = np.zeros([3, 3], dtype=dtype) + data[1, 1] = 1 + data = xp.asarray(data) + out = ndimage.binary_dilation(data, struct) + assert_array_almost_equal(out, xp.asarray([[1, 1, 1], + [1, 1, 1], + [1, 1, 1]])) + + @pytest.mark.parametrize('dtype', types) + def test_binary_dilation22(self, dtype, xp): + dtype = getattr(xp, dtype) + expected = [[0, 1, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 1, 0, 0, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out = ndimage.binary_dilation(data) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('dtype', types) + def test_binary_dilation23(self, dtype, xp): + dtype = getattr(xp, dtype) + expected = [[1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 0, 0, 0, 0, 1], + [1, 1, 0, 0, 0, 1, 0, 1], + [1, 0, 0, 1, 1, 1, 1, 1], + [1, 0, 1, 1, 1, 1, 0, 1], + [1, 1, 1, 1, 1, 1, 1, 1], + [1, 0, 1, 0, 0, 1, 0, 1], + [1, 1, 1, 1, 1, 1, 1, 1]] + expected = xp.asarray(expected) + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 1, 0, 0, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out = ndimage.binary_dilation(data, border_value=1) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('dtype', types) + def test_binary_dilation24(self, dtype, xp): + dtype = getattr(xp, dtype) + expected = [[1, 1, 0, 0, 0, 0, 0, 0], + [1, 0, 0, 0, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 0, 0, 0], + [1, 1, 1, 1, 1, 1, 0, 0], + [0, 1, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 1, 0, 0, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out = ndimage.binary_dilation(data, origin=(1, 1)) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('dtype', types) + def test_binary_dilation25(self, dtype, xp): + dtype = getattr(xp, dtype) + expected = [[1, 1, 0, 0, 0, 0, 1, 1], + [1, 0, 0, 0, 1, 0, 1, 1], + [0, 0, 1, 1, 1, 1, 1, 1], + [0, 1, 1, 1, 1, 0, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1], + [0, 1, 0, 0, 1, 0, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1]] + expected = xp.asarray(expected) + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 1, 0, 0, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out = ndimage.binary_dilation(data, origin=(1, 1), border_value=1) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('dtype', types) + def test_binary_dilation26(self, dtype, xp): + dtype = getattr(xp, dtype) + struct = ndimage.generate_binary_structure(2, 2) + expected = [[1, 1, 1, 0, 0, 0, 0, 0], + [1, 1, 1, 0, 0, 0, 0, 0], + [1, 1, 1, 0, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0]] + struct = xp.asarray(struct) + expected = xp.asarray(expected) + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 1, 0, 0, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out = ndimage.binary_dilation(data, struct) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('dtype', types) + def test_binary_dilation27(self, dtype, xp): + dtype = getattr(xp, dtype) + struct = [[0, 1], + [1, 1]] + expected = [[0, 1, 0, 0, 0, 0, 0, 0], + [1, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 1, 1, 0, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]] + struct = xp.asarray(struct) + expected = xp.asarray(expected) + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 1, 0, 0, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out = ndimage.binary_dilation(data, struct) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('dtype', types) + def test_binary_dilation28(self, dtype, xp): + dtype = getattr(xp, dtype) + expected = [[1, 1, 1, 1], + [1, 0, 0, 1], + [1, 0, 0, 1], + [1, 1, 1, 1]] + expected = xp.asarray(expected) + data = xp.asarray([[0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0]], dtype=dtype) + out = ndimage.binary_dilation(data, border_value=1) + assert_array_almost_equal(out, expected) + + def test_binary_dilation29(self, xp): + if is_cupy(xp): + pytest.xfail("CuPy: NotImplementedError: only brute_force iteration") + + struct = [[0, 1], + [1, 1]] + expected = [[0, 0, 0, 0, 0], + [0, 0, 0, 1, 0], + [0, 0, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 0]] + struct = xp.asarray(struct) + expected = xp.asarray(expected) + data = np.asarray([[0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 1, 0], + [0, 0, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + out = ndimage.binary_dilation(data, struct, iterations=2) + assert_array_almost_equal(out, expected) + + @skip_xp_backends(np_only=True, reason='output= arrays are numpy-specific') + def test_binary_dilation30(self, xp): + if is_cupy(xp): + pytest.xfail("CuPy: NotImplementedError: only brute_force iteration") + struct = [[0, 1], + [1, 1]] + expected = [[0, 0, 0, 0, 0], + [0, 0, 0, 1, 0], + [0, 0, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 0]] + struct = xp.asarray(struct) + expected = xp.asarray(expected) + data = xp.asarray([[0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 1, 0], + [0, 0, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + out = np.zeros(data.shape, dtype=bool) + out = xp.asarray(out) + ndimage.binary_dilation(data, struct, iterations=2, output=out) + assert_array_almost_equal(out, expected) + + def test_binary_dilation31(self, xp): + if is_cupy(xp): + pytest.xfail("CuPy: NotImplementedError: only brute_force iteration") + + struct = [[0, 1], + [1, 1]] + expected = [[0, 0, 0, 1, 0], + [0, 0, 1, 1, 0], + [0, 1, 1, 1, 0], + [1, 1, 1, 1, 0], + [0, 0, 0, 0, 0]] + struct = xp.asarray(struct) + expected = xp.asarray(expected) + data = np.asarray([[0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 1, 0], + [0, 0, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + out = ndimage.binary_dilation(data, struct, iterations=3) + assert_array_almost_equal(out, expected) + + @skip_xp_backends(np_only=True, reason='output= arrays are numpy-specific') + def test_binary_dilation32(self, xp): + if is_cupy(xp): + pytest.xfail("CuPy: NotImplementedError: only brute_force iteration") + + struct = [[0, 1], + [1, 1]] + expected = [[0, 0, 0, 1, 0], + [0, 0, 1, 1, 0], + [0, 1, 1, 1, 0], + [1, 1, 1, 1, 0], + [0, 0, 0, 0, 0]] + struct = xp.asarray(struct) + expected = xp.asarray(expected) + data = np.asarray([[0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 1, 0], + [0, 0, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + out = np.zeros(data.shape, dtype=bool) + out = xp.asarray(out) + ndimage.binary_dilation(data, struct, iterations=3, output=out) + assert_array_almost_equal(out, expected) + + def test_binary_dilation33(self, xp): + if is_cupy(xp): + pytest.xfail("CuPy: NotImplementedError: only brute_force iteration") + struct = [[0, 1, 0], + [1, 1, 1], + [0, 1, 0]] + struct = xp.asarray(struct) + expected = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0, 0], + [0, 1, 1, 0, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) + expected = xp.asarray(expected) + mask = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 1, 0], + [0, 0, 0, 0, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0, 0], + [0, 1, 1, 0, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) + mask = xp.asarray(mask) + data = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + + out = ndimage.binary_dilation(data, struct, iterations=-1, + mask=mask, border_value=0) + assert_array_almost_equal(out, expected) + + @skip_xp_backends( + np_only=True, reason='inplace output= arrays are numpy-specific', + ) + def test_binary_dilation34(self, xp): + if is_cupy(xp): + pytest.xfail("CuPy: NotImplementedError: only brute_force iteration") + + struct = [[0, 1, 0], + [1, 1, 1], + [0, 1, 0]] + struct = xp.asarray(struct) + expected = [[0, 1, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]] + mask = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 1, 0, 0, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) + mask = xp.asarray(mask) + data = np.zeros(mask.shape, dtype=bool) + data = xp.asarray(data) + out = ndimage.binary_dilation(data, struct, iterations=-1, + mask=mask, border_value=1) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('dtype', types) + def test_binary_dilation35(self, dtype, xp): + dtype = getattr(xp, dtype) + tmp = [[1, 1, 0, 0, 0, 0, 1, 1], + [1, 0, 0, 0, 1, 0, 1, 1], + [0, 0, 1, 1, 1, 1, 1, 1], + [0, 1, 1, 1, 1, 0, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1], + [0, 1, 0, 0, 1, 0, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1]] + + data = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 1, 0, 0, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]]) + mask = [[0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]] + mask = np.asarray(mask, dtype=bool) + + expected = np.logical_and(tmp, mask) + tmp = np.logical_and(data, np.logical_not(mask)) + expected = np.logical_or(expected, tmp) + + mask = xp.asarray(mask) + expected = xp.asarray(expected) + + data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 1, 0, 0, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out = ndimage.binary_dilation(data, mask=mask, + origin=(1, 1), border_value=1) + assert_array_almost_equal(out, expected) + + def test_binary_dilation36(self, xp): + # gh-21009 + data = np.zeros([], dtype=bool) + data = xp.asarray(data) + out = ndimage.binary_dilation(data, iterations=-1) + assert out == xp.asarray(False) + + def test_binary_propagation01(self, xp): + struct = [[0, 1, 0], + [1, 1, 1], + [0, 1, 0]] + struct = xp.asarray(struct) + expected = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0, 0], + [0, 1, 1, 0, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) + expected = xp.asarray(expected) + mask = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 1, 0], + [0, 0, 0, 0, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0, 0], + [0, 1, 1, 0, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) + mask = xp.asarray(mask) + data = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + out = ndimage.binary_propagation(data, struct, + mask=mask, border_value=0) + assert_array_almost_equal(out, expected) + + def test_binary_propagation02(self, xp): + struct = [[0, 1, 0], + [1, 1, 1], + [0, 1, 0]] + expected = [[0, 1, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + struct = xp.asarray(struct) + mask = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 1, 0, 0, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) + mask = xp.asarray(mask) + data = np.zeros(mask.shape, dtype=bool) + data = xp.asarray(data) + out = ndimage.binary_propagation(data, struct, + mask=mask, border_value=1) + assert_array_almost_equal(out, expected) + + def test_binary_propagation03(self, xp): + # gh-21009 + data = xp.asarray(np.zeros([], dtype=bool)) + expected = xp.asarray(np.zeros([], dtype=bool)) + out = ndimage.binary_propagation(data) + assert out == expected + + @pytest.mark.parametrize('dtype', types) + def test_binary_opening01(self, dtype, xp): + dtype = getattr(xp, dtype) + expected = [[0, 1, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 1, 1, 1, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + data = xp.asarray([[0, 1, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 0, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out = ndimage.binary_opening(data) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('dtype', types) + def test_binary_opening02(self, dtype, xp): + dtype = getattr(xp, dtype) + struct = ndimage.generate_binary_structure(2, 2) + expected = [[1, 1, 1, 0, 0, 0, 0, 0], + [1, 1, 1, 0, 0, 0, 0, 0], + [1, 1, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + struct = xp.asarray(struct) + data = xp.asarray([[1, 1, 1, 0, 0, 0, 0, 0], + [1, 1, 1, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 0, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out = ndimage.binary_opening(data, struct) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('dtype', types) + def test_binary_closing01(self, dtype, xp): + dtype = getattr(xp, dtype) + expected = [[0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + data = xp.asarray([[0, 1, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 0, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out = ndimage.binary_closing(data) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('dtype', types) + def test_binary_closing02(self, dtype, xp): + dtype = getattr(xp, dtype) + struct = ndimage.generate_binary_structure(2, 2) + expected = [[0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + struct = xp.asarray(struct) + data = xp.asarray([[1, 1, 1, 0, 0, 0, 0, 0], + [1, 1, 1, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 0, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out = ndimage.binary_closing(data, struct) + assert_array_almost_equal(out, expected) + + def test_binary_fill_holes01(self, xp): + expected = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) + expected = xp.asarray(expected) + + data = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + + out = ndimage.binary_fill_holes(data) + assert_array_almost_equal(out, expected) + + def test_binary_fill_holes02(self, xp): + expected = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) + expected = xp.asarray(expected) + data = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 0, 0, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + out = ndimage.binary_fill_holes(data) + assert_array_almost_equal(out, expected) + + def test_binary_fill_holes03(self, xp): + expected = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 1, 1, 1], + [0, 1, 1, 1, 0, 1, 1, 1], + [0, 1, 1, 1, 0, 1, 1, 1], + [0, 0, 1, 0, 0, 1, 1, 1], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) + expected = xp.asarray(expected) + data = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 0, 0], + [0, 1, 0, 1, 0, 1, 1, 1], + [0, 1, 0, 1, 0, 1, 0, 1], + [0, 1, 0, 1, 0, 1, 0, 1], + [0, 0, 1, 0, 0, 1, 1, 1], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) + data = xp.asarray(data) + out = ndimage.binary_fill_holes(data) + assert_array_almost_equal(out, expected) + + @skip_xp_backends(cpu_only=True) + @skip_xp_backends( + "cupy", reason="these filters do not yet have axes support in CuPy") + @skip_xp_backends( + "jax.numpy", reason="these filters are not implemented in JAX.numpy") + @pytest.mark.parametrize('border_value',[0, 1]) + @pytest.mark.parametrize('origin', [(0, 0), (-1, 0)]) + @pytest.mark.parametrize('expand_axis', [0, 1, 2]) + @pytest.mark.parametrize('func_name', ["binary_erosion", + "binary_dilation", + "binary_opening", + "binary_closing", + "binary_hit_or_miss", + "binary_propagation", + "binary_fill_holes"]) + def test_binary_axes(self, xp, func_name, expand_axis, origin, border_value): + struct = np.asarray([[0, 1, 0], + [1, 1, 1], + [0, 1, 0]], bool) + struct = xp.asarray(struct) + + data = np.asarray([[0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 1, 1, 0, 1, 0], + [0, 1, 0, 1, 1, 0, 1], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0]], bool) + data = xp.asarray(data) + if func_name == "binary_hit_or_miss": + kwargs = dict(origin1=origin, origin2=origin) + else: + kwargs = dict(origin=origin) + border_supported = func_name not in ["binary_hit_or_miss", + "binary_fill_holes"] + if border_supported: + kwargs['border_value'] = border_value + elif border_value != 0: + pytest.skip('border_value !=0 unsupported by this function') + func = getattr(ndimage, func_name) + expected = func(data, struct, **kwargs) + + # replicate data and expected result along a new axis + n_reps = 5 + expected = xp.stack([expected] * n_reps, axis=expand_axis) + data = xp.stack([data] * n_reps, axis=expand_axis) + + # filter all axes except expand_axis + axes = [0, 1, 2] + axes.remove(expand_axis) + if is_numpy(xp) or is_cupy(xp): + out = xp.asarray(np.zeros(data.shape, bool)) + func(data, struct, output=out, axes=axes, **kwargs) + else: + # inplace output= is unsupported by JAX + out = func(data, struct, axes=axes, **kwargs) + xp_assert_close(out, expected) + + def test_grey_erosion01(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + output = ndimage.grey_erosion(array, footprint=footprint) + assert_array_almost_equal(output, + xp.asarray([[2, 2, 1, 1, 1], + [2, 3, 1, 3, 1], + [5, 5, 3, 3, 1]])) + + @skip_xp_backends("jax.numpy", reason="output array is read-only.") + @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/issues/8398") + def test_grey_erosion01_overlap(self, xp): + + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + ndimage.grey_erosion(array, footprint=footprint, output=array) + assert_array_almost_equal(array, + xp.asarray([[2, 2, 1, 1, 1], + [2, 3, 1, 3, 1], + [5, 5, 3, 3, 1]]) + ) + + def test_grey_erosion02(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + structure = xp.asarray([[0, 0, 0], [0, 0, 0]]) + output = ndimage.grey_erosion(array, footprint=footprint, + structure=structure) + assert_array_almost_equal(output, + xp.asarray([[2, 2, 1, 1, 1], + [2, 3, 1, 3, 1], + [5, 5, 3, 3, 1]]) + ) + + def test_grey_erosion03(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + structure = xp.asarray([[1, 1, 1], [1, 1, 1]]) + output = ndimage.grey_erosion(array, footprint=footprint, + structure=structure) + assert_array_almost_equal(output, + xp.asarray([[1, 1, 0, 0, 0], + [1, 2, 0, 2, 0], + [4, 4, 2, 2, 0]]) + ) + + def test_grey_dilation01(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[0, 1, 1], [1, 0, 1]]) + output = ndimage.grey_dilation(array, footprint=footprint) + assert_array_almost_equal(output, + xp.asarray([[7, 7, 9, 9, 5], + [7, 9, 8, 9, 7], + [8, 8, 8, 7, 7]]), + ) + + def test_grey_dilation02(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[0, 1, 1], [1, 0, 1]]) + structure = xp.asarray([[0, 0, 0], [0, 0, 0]]) + output = ndimage.grey_dilation(array, footprint=footprint, + structure=structure) + assert_array_almost_equal(output, + xp.asarray([[7, 7, 9, 9, 5], + [7, 9, 8, 9, 7], + [8, 8, 8, 7, 7]]), + ) + + def test_grey_dilation03(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[0, 1, 1], [1, 0, 1]]) + structure = xp.asarray([[1, 1, 1], [1, 1, 1]]) + output = ndimage.grey_dilation(array, footprint=footprint, + structure=structure) + assert_array_almost_equal(output, + xp.asarray([[8, 8, 10, 10, 6], + [8, 10, 9, 10, 8], + [9, 9, 9, 8, 8]]), + ) + + def test_grey_opening01(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + tmp = ndimage.grey_erosion(array, footprint=footprint) + expected = ndimage.grey_dilation(tmp, footprint=footprint) + output = ndimage.grey_opening(array, footprint=footprint) + assert_array_almost_equal(output, expected) + + def test_grey_opening02(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + structure = xp.asarray([[0, 0, 0], [0, 0, 0]]) + tmp = ndimage.grey_erosion(array, footprint=footprint, + structure=structure) + expected = ndimage.grey_dilation(tmp, footprint=footprint, + structure=structure) + output = ndimage.grey_opening(array, footprint=footprint, + structure=structure) + assert_array_almost_equal(output, expected) + + def test_grey_closing01(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + tmp = ndimage.grey_dilation(array, footprint=footprint) + expected = ndimage.grey_erosion(tmp, footprint=footprint) + output = ndimage.grey_closing(array, footprint=footprint) + assert_array_almost_equal(expected, output) + + def test_grey_closing02(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + structure = xp.asarray([[0, 0, 0], [0, 0, 0]]) + tmp = ndimage.grey_dilation(array, footprint=footprint, + structure=structure) + expected = ndimage.grey_erosion(tmp, footprint=footprint, + structure=structure) + output = ndimage.grey_closing(array, footprint=footprint, + structure=structure) + assert_array_almost_equal(expected, output) + + @skip_xp_backends(np_only=True, reason='output= arrays are numpy-specific') + def test_morphological_gradient01(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + structure = xp.asarray([[0, 0, 0], [0, 0, 0]]) + tmp1 = ndimage.grey_dilation(array, footprint=footprint, + structure=structure) + tmp2 = ndimage.grey_erosion(array, footprint=footprint, + structure=structure) + expected = tmp1 - tmp2 + output = xp.zeros(array.shape, dtype=array.dtype) + ndimage.morphological_gradient(array, footprint=footprint, + structure=structure, output=output) + assert_array_almost_equal(expected, output) + + def test_morphological_gradient02(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + structure = xp.asarray([[0, 0, 0], [0, 0, 0]]) + tmp1 = ndimage.grey_dilation(array, footprint=footprint, + structure=structure) + tmp2 = ndimage.grey_erosion(array, footprint=footprint, + structure=structure) + expected = tmp1 - tmp2 + output = ndimage.morphological_gradient(array, footprint=footprint, + structure=structure) + assert_array_almost_equal(expected, output) + + @skip_xp_backends(np_only=True, reason='output= arrays are numpy-specific') + def test_morphological_laplace01(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + structure = xp.asarray([[0, 0, 0], [0, 0, 0]]) + tmp1 = ndimage.grey_dilation(array, footprint=footprint, + structure=structure) + tmp2 = ndimage.grey_erosion(array, footprint=footprint, + structure=structure) + expected = tmp1 + tmp2 - 2 * array + output = xp.zeros(array.shape, dtype=array.dtype) + ndimage.morphological_laplace(array, footprint=footprint, + structure=structure, output=output) + assert_array_almost_equal(expected, output) + + def test_morphological_laplace02(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + structure = xp.asarray([[0, 0, 0], [0, 0, 0]]) + tmp1 = ndimage.grey_dilation(array, footprint=footprint, + structure=structure) + tmp2 = ndimage.grey_erosion(array, footprint=footprint, + structure=structure) + expected = tmp1 + tmp2 - 2 * array + output = ndimage.morphological_laplace(array, footprint=footprint, + structure=structure) + assert_array_almost_equal(expected, output) + + @skip_xp_backends("jax.numpy", reason="output array is read-only.") + def test_white_tophat01(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + structure = xp.asarray([[0, 0, 0], [0, 0, 0]]) + tmp = ndimage.grey_opening(array, footprint=footprint, + structure=structure) + expected = array - tmp + output = xp.zeros(array.shape, dtype=array.dtype) + ndimage.white_tophat(array, footprint=footprint, + structure=structure, output=output) + assert_array_almost_equal(expected, output) + + def test_white_tophat02(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + structure = xp.asarray([[0, 0, 0], [0, 0, 0]]) + tmp = ndimage.grey_opening(array, footprint=footprint, + structure=structure) + expected = array - tmp + output = ndimage.white_tophat(array, footprint=footprint, + structure=structure) + assert_array_almost_equal(expected, output) + + @xfail_xp_backends('cupy', reason="cupy#8399") + def test_white_tophat03(self, xp): + + array = np.asarray([[1, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 0, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 1]], dtype=bool) + array = xp.asarray(array) + structure = np.ones((3, 3), dtype=bool) + structure = xp.asarray(structure) + expected = np.asarray([[0, 1, 1, 0, 0, 0, 0], + [1, 0, 0, 1, 1, 1, 0], + [1, 0, 0, 1, 1, 1, 0], + [0, 1, 1, 0, 0, 0, 1], + [0, 1, 1, 0, 1, 0, 1], + [0, 1, 1, 0, 0, 0, 1], + [0, 0, 0, 1, 1, 1, 1]], dtype=bool) + expected = xp.asarray(expected) + + output = ndimage.white_tophat(array, structure=structure) + xp_assert_equal(expected, output) + + @skip_xp_backends("jax.numpy", reason="output array is read-only.") + def test_white_tophat04(self, xp): + array = np.eye(5, dtype=bool) + structure = np.ones((3, 3), dtype=bool) + + array = xp.asarray(array) + structure = xp.asarray(structure) + + # Check that type mismatch is properly handled + output = xp.empty_like(array, dtype=xp.float64) + ndimage.white_tophat(array, structure=structure, output=output) + + @skip_xp_backends("jax.numpy", reason="output array is read-only.") + def test_black_tophat01(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + structure = xp.asarray([[0, 0, 0], [0, 0, 0]]) + tmp = ndimage.grey_closing(array, footprint=footprint, + structure=structure) + expected = tmp - array + output = xp.zeros(array.shape, dtype=array.dtype) + ndimage.black_tophat(array, footprint=footprint, + structure=structure, output=output) + assert_array_almost_equal(expected, output) + + def test_black_tophat02(self, xp): + array = xp.asarray([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) + structure = xp.asarray([[0, 0, 0], [0, 0, 0]]) + tmp = ndimage.grey_closing(array, footprint=footprint, + structure=structure) + expected = tmp - array + output = ndimage.black_tophat(array, footprint=footprint, + structure=structure) + assert_array_almost_equal(expected, output) + + @xfail_xp_backends('cupy', reason="cupy/cupy#8399") + def test_black_tophat03(self, xp): + + array = np.asarray([[1, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 0, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 1]], dtype=bool) + array = xp.asarray(array) + structure = np.ones((3, 3), dtype=bool) + structure = xp.asarray(structure) + expected = np.asarray([[0, 1, 1, 1, 1, 1, 1], + [1, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 1, 0, 1], + [1, 0, 0, 0, 0, 0, 1], + [1, 1, 1, 1, 1, 1, 0]], dtype=bool) + expected = xp.asarray(expected) + + output = ndimage.black_tophat(array, structure=structure) + xp_assert_equal(expected, output) + + @skip_xp_backends("jax.numpy", reason="output array is read-only.") + def test_black_tophat04(self, xp): + array = xp.asarray(np.eye(5, dtype=bool)) + structure = xp.asarray(np.ones((3, 3), dtype=bool)) + + # Check that type mismatch is properly handled + output = xp.empty_like(array, dtype=xp.float64) + ndimage.black_tophat(array, structure=structure, output=output) + + @skip_xp_backends(cpu_only=True) + @skip_xp_backends( + "cupy", reason="these filters do not yet have axes support in CuPy") + @skip_xp_backends( + "jax.numpy", reason="these filters are not implemented in JAX.numpy") + @pytest.mark.parametrize('origin', [(0, 0), (-1, 0)]) + @pytest.mark.parametrize('expand_axis', [0, 1, 2]) + @pytest.mark.parametrize('mode', ['reflect', 'constant', 'nearest', + 'mirror', 'wrap']) + @pytest.mark.parametrize('footprint_mode', ['size', 'footprint', + 'structure']) + @pytest.mark.parametrize('func_name', ["grey_erosion", + "grey_dilation", + "grey_opening", + "grey_closing", + "morphological_laplace", + "morphological_gradient", + "white_tophat", + "black_tophat"]) + def test_grey_axes(self, xp, func_name, expand_axis, origin, footprint_mode, + mode): + + data = xp.asarray([[0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 4, 0, 0, 0], + [0, 0, 2, 1, 0, 2, 0], + [0, 3, 0, 6, 5, 0, 1], + [0, 4, 5, 3, 3, 4, 0], + [0, 0, 9, 3, 0, 0, 0], + [0, 0, 0, 2, 0, 0, 0]]) + kwargs = dict(origin=origin, mode=mode) + if footprint_mode == 'size': + kwargs['size'] = (2, 3) + else: + kwargs['footprint'] = xp.asarray([[1, 0, 1], [1, 1, 0]]) + if footprint_mode == 'structure': + kwargs['structure'] = xp.ones_like(kwargs['footprint']) + func = getattr(ndimage, func_name) + expected = func(data, **kwargs) + + # replicate data and expected result along a new axis + n_reps = 5 + expected = xp.stack([expected] * n_reps, axis=expand_axis) + data = xp.stack([data] * n_reps, axis=expand_axis) + + # filter all axes except expand_axis + axes = [0, 1, 2] + axes.remove(expand_axis) + + if is_numpy(xp) or is_cupy(xp): + out = xp.zeros(expected.shape, dtype=expected.dtype) + func(data, output=out, axes=axes, **kwargs) + else: + # inplace output= is unsupported by JAX + out = func(data, axes=axes, **kwargs) + xp_assert_close(out, expected) + + @pytest.mark.parametrize('dtype', types) + def test_hit_or_miss01(self, dtype, xp): + if not (is_numpy(xp) or is_cupy(xp)): + pytest.xfail("inplace output= is numpy-specific") + + dtype = getattr(xp, dtype) + struct = [[0, 1, 0], + [1, 1, 1], + [0, 1, 0]] + struct = xp.asarray(struct) + expected = [[0, 0, 0, 0, 0], + [0, 1, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0]] + expected = xp.asarray(expected) + data = xp.asarray([[0, 1, 0, 0, 0], + [1, 1, 1, 0, 0], + [0, 1, 0, 1, 1], + [0, 0, 1, 1, 1], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 1], + [0, 1, 1, 1, 1], + [0, 0, 0, 0, 0]], dtype=dtype) + out = xp.asarray(np.zeros(data.shape, dtype=bool)) + ndimage.binary_hit_or_miss(data, struct, output=out) + assert_array_almost_equal(expected, out) + + @pytest.mark.parametrize('dtype', types) + def test_hit_or_miss02(self, dtype, xp): + dtype = getattr(xp, dtype) + struct = [[0, 1, 0], + [1, 1, 1], + [0, 1, 0]] + expected = [[0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]] + struct = xp.asarray(struct) + expected = xp.asarray(expected) + data = xp.asarray([[0, 1, 0, 0, 1, 1, 1, 0], + [1, 1, 1, 0, 0, 1, 0, 0], + [0, 1, 0, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out = ndimage.binary_hit_or_miss(data, struct) + assert_array_almost_equal(expected, out) + + @pytest.mark.parametrize('dtype', types) + def test_hit_or_miss03(self, dtype, xp): + dtype = getattr(xp, dtype) + struct1 = [[0, 0, 0], + [1, 1, 1], + [0, 0, 0]] + struct2 = [[1, 1, 1], + [0, 0, 0], + [1, 1, 1]] + expected = [[0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0]] + struct1 = xp.asarray(struct1) + struct2 = xp.asarray(struct2) + expected = xp.asarray(expected) + data = xp.asarray([[0, 1, 0, 0, 1, 1, 1, 0], + [1, 1, 1, 0, 0, 0, 0, 0], + [0, 1, 0, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 0, 1, 1, 0], + [0, 0, 0, 0, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype) + out = ndimage.binary_hit_or_miss(data, struct1, struct2) + assert_array_almost_equal(expected, out) + + +class TestDilateFix: + + # pytest's setup_method seems to clash with the autouse `xp` fixture + # so call _setup manually from all methods + def _setup(self, xp): + # dilation related setup + self.array = xp.asarray([[0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 1, 0], + [0, 0, 1, 1, 0], + [0, 0, 0, 0, 0]], dtype=xp.uint8) + + self.sq3x3 = xp.ones((3, 3)) + dilated3x3 = ndimage.binary_dilation(self.array, structure=self.sq3x3) + + if is_numpy(xp): + self.dilated3x3 = dilated3x3.view(xp.uint8) + else: + astype = array_namespace(dilated3x3).astype + self.dilated3x3 = astype(dilated3x3, xp.uint8) + + + def test_dilation_square_structure(self, xp): + self._setup(xp) + result = ndimage.grey_dilation(self.array, structure=self.sq3x3) + # +1 accounts for difference between grey and binary dilation + assert_array_almost_equal(result, self.dilated3x3 + 1) + + def test_dilation_scalar_size(self, xp): + self._setup(xp) + result = ndimage.grey_dilation(self.array, size=3) + assert_array_almost_equal(result, self.dilated3x3) + + +class TestBinaryOpeningClosing: + + def _setup(self, xp): + a = np.zeros((5, 5), dtype=bool) + a[1:4, 1:4] = True + a[4, 4] = True + self.array = xp.asarray(a) + self.sq3x3 = xp.ones((3, 3)) + self.opened_old = ndimage.binary_opening(self.array, self.sq3x3, + 1, None, 0) + self.closed_old = ndimage.binary_closing(self.array, self.sq3x3, + 1, None, 0) + + def test_opening_new_arguments(self, xp): + self._setup(xp) + opened_new = ndimage.binary_opening(self.array, self.sq3x3, 1, None, + 0, None, 0, False) + xp_assert_equal(opened_new, self.opened_old) + + def test_closing_new_arguments(self, xp): + self._setup(xp) + closed_new = ndimage.binary_closing(self.array, self.sq3x3, 1, None, + 0, None, 0, False) + xp_assert_equal(closed_new, self.closed_old) + + +def test_binary_erosion_noninteger_iterations(xp): + # regression test for gh-9905, gh-9909: ValueError for + # non integer iterations + data = xp.ones([1]) + assert_raises(TypeError, ndimage.binary_erosion, data, iterations=0.5) + assert_raises(TypeError, ndimage.binary_erosion, data, iterations=1.5) + + +def test_binary_dilation_noninteger_iterations(xp): + # regression test for gh-9905, gh-9909: ValueError for + # non integer iterations + data = xp.ones([1]) + assert_raises(TypeError, ndimage.binary_dilation, data, iterations=0.5) + assert_raises(TypeError, ndimage.binary_dilation, data, iterations=1.5) + + +def test_binary_opening_noninteger_iterations(xp): + # regression test for gh-9905, gh-9909: ValueError for + # non integer iterations + data = xp.ones([1]) + assert_raises(TypeError, ndimage.binary_opening, data, iterations=0.5) + assert_raises(TypeError, ndimage.binary_opening, data, iterations=1.5) + + +def test_binary_closing_noninteger_iterations(xp): + # regression test for gh-9905, gh-9909: ValueError for + # non integer iterations + data = xp.ones([1]) + assert_raises(TypeError, ndimage.binary_closing, data, iterations=0.5) + assert_raises(TypeError, ndimage.binary_closing, data, iterations=1.5) + + +def test_binary_closing_noninteger_brute_force_passes_when_true(xp): + # regression test for gh-9905, gh-9909: ValueError for + # non integer iterations + if is_cupy(xp): + pytest.xfail("CuPy: NotImplementedError: only brute_force iteration") + + data = xp.ones([1]) + + xp_assert_equal(ndimage.binary_erosion(data, iterations=2, brute_force=1.5), + ndimage.binary_erosion(data, iterations=2, brute_force=bool(1.5)) + ) + xp_assert_equal(ndimage.binary_erosion(data, iterations=2, brute_force=0.0), + ndimage.binary_erosion(data, iterations=2, brute_force=bool(0.0)) + ) + + +@pytest.mark.parametrize( + 'function', + ['binary_erosion', 'binary_dilation', 'binary_opening', 'binary_closing'], +) +@pytest.mark.parametrize('iterations', [1, 5]) +@pytest.mark.parametrize('brute_force', [False, True]) +def test_binary_input_as_output(function, iterations, brute_force, xp): + rstate = np.random.RandomState(123) + data = rstate.randint(low=0, high=2, size=100).astype(bool) + ndi_func = getattr(ndimage, function) + + # input data is not modified + data_orig = data.copy() + expected = ndi_func(data, brute_force=brute_force, iterations=iterations) + xp_assert_equal(data, data_orig) + + # data should now contain the expected result + ndi_func(data, brute_force=brute_force, iterations=iterations, output=data) + xp_assert_equal(expected, data) + + +def test_binary_hit_or_miss_input_as_output(xp): + if not (is_numpy(xp) or is_cupy(xp)): + pytest.xfail("inplace output= is numpy-specific") + + rstate = np.random.RandomState(123) + data = rstate.randint(low=0, high=2, size=100).astype(bool) + + # input data is not modified + data_orig = data.copy() + expected = ndimage.binary_hit_or_miss(data) + xp_assert_equal(data, data_orig) + + # data should now contain the expected result + ndimage.binary_hit_or_miss(data, output=data) + xp_assert_equal(expected, data) + + +def test_distance_transform_cdt_invalid_metric(xp): + if is_cupy(xp): + pytest.xfail("CuPy does not have distance_transform_cdt") + + msg = 'invalid metric provided' + with pytest.raises(ValueError, match=msg): + ndimage.distance_transform_cdt(xp.ones((5, 5)), + metric="garbage") diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/tests/test_ni_support.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/tests/test_ni_support.py new file mode 100644 index 0000000000000000000000000000000000000000..426d1cf0eccd1ac0f10a90412f008f4b3463c333 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/tests/test_ni_support.py @@ -0,0 +1,78 @@ +import pytest + +import numpy as np +from .._ni_support import _get_output + + +@pytest.mark.parametrize( + 'dtype', + [ + # String specifiers + 'f4', 'float32', 'complex64', 'complex128', + # Type and dtype specifiers + np.float32, float, np.dtype('f4'), + # Derive from input + None, + ], +) +def test_get_output_basic(dtype): + shape = (2, 3) + + input_ = np.zeros(shape, dtype='float32') + + # For None, derive dtype from input + expected_dtype = 'float32' if dtype is None else dtype + + # Output is dtype-specifier, retrieve shape from input + result = _get_output(dtype, input_) + assert result.shape == shape + assert result.dtype == np.dtype(expected_dtype) + + # Output is dtype specifier, with explicit shape, overriding input + result = _get_output(dtype, input_, shape=(3, 2)) + assert result.shape == (3, 2) + assert result.dtype == np.dtype(expected_dtype) + + # Output is pre-allocated array, return directly + output = np.zeros(shape, dtype=dtype) + result = _get_output(output, input_) + assert result is output + + +@pytest.mark.thread_unsafe +def test_get_output_complex(): + shape = (2, 3) + + input_ = np.zeros(shape) + + # None, promote input type to complex + result = _get_output(None, input_, complex_output=True) + assert result.shape == shape + assert result.dtype == np.dtype('complex128') + + # Explicit type, promote type to complex + with pytest.warns(UserWarning, match='promoting specified output dtype to complex'): + result = _get_output(float, input_, complex_output=True) + assert result.shape == shape + assert result.dtype == np.dtype('complex128') + + # String specifier, simply verify complex output + result = _get_output('complex64', input_, complex_output=True) + assert result.shape == shape + assert result.dtype == np.dtype('complex64') + + +def test_get_output_error_cases(): + input_ = np.zeros((2, 3), 'float32') + + # Two separate paths can raise the same error + with pytest.raises(RuntimeError, match='output must have complex dtype'): + _get_output('float32', input_, complex_output=True) + with pytest.raises(RuntimeError, match='output must have complex dtype'): + _get_output(np.zeros((2, 3)), input_, complex_output=True) + + with pytest.raises(RuntimeError, match='output must have numeric dtype'): + _get_output('void', input_) + + with pytest.raises(RuntimeError, match='shape not correct'): + _get_output(np.zeros((3, 2)), input_) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/tests/test_splines.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/tests/test_splines.py new file mode 100644 index 0000000000000000000000000000000000000000..2561ba5acef20ac340e06164bae96f187486c06a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/ndimage/tests/test_splines.py @@ -0,0 +1,72 @@ +"""Tests for spline filtering.""" +import pytest + +import numpy as np +from scipy._lib._array_api import assert_almost_equal + +from scipy import ndimage + +from scipy.conftest import array_api_compatible +skip_xp_backends = pytest.mark.skip_xp_backends +pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends"), + skip_xp_backends(cpu_only=True, exceptions=['cupy', 'jax.numpy'],)] + + +def get_spline_knot_values(order): + """Knot values to the right of a B-spline's center.""" + knot_values = {0: [1], + 1: [1], + 2: [6, 1], + 3: [4, 1], + 4: [230, 76, 1], + 5: [66, 26, 1]} + + return knot_values[order] + + +def make_spline_knot_matrix(xp, n, order, mode='mirror'): + """Matrix to invert to find the spline coefficients.""" + knot_values = get_spline_knot_values(order) + + # NB: do computations with numpy, convert to xp as the last step only + + matrix = np.zeros((n, n)) + for diag, knot_value in enumerate(knot_values): + indices = np.arange(diag, n) + if diag == 0: + matrix[indices, indices] = knot_value + else: + matrix[indices, indices - diag] = knot_value + matrix[indices - diag, indices] = knot_value + + knot_values_sum = knot_values[0] + 2 * sum(knot_values[1:]) + + if mode == 'mirror': + start, step = 1, 1 + elif mode == 'reflect': + start, step = 0, 1 + elif mode == 'grid-wrap': + start, step = -1, -1 + else: + raise ValueError(f'unsupported mode {mode}') + + for row in range(len(knot_values) - 1): + for idx, knot_value in enumerate(knot_values[row + 1:]): + matrix[row, start + step*idx] += knot_value + matrix[-row - 1, -start - 1 - step*idx] += knot_value + + return xp.asarray(matrix / knot_values_sum) + + +@pytest.mark.parametrize('order', [0, 1, 2, 3, 4, 5]) +@pytest.mark.parametrize('mode', ['mirror', 'grid-wrap', 'reflect']) +def test_spline_filter_vs_matrix_solution(order, mode, xp): + n = 100 + eye = xp.eye(n, dtype=xp.float64) + spline_filter_axis_0 = ndimage.spline_filter1d(eye, axis=0, order=order, + mode=mode) + spline_filter_axis_1 = ndimage.spline_filter1d(eye, axis=1, order=order, + mode=mode) + matrix = make_spline_knot_matrix(xp, n, order, mode=mode) + assert_almost_equal(eye, spline_filter_axis_0 @ matrix) + assert_almost_equal(eye, spline_filter_axis_1 @ matrix.T) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/odr/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/odr/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a44a8c133b674aea416efeb4da469241b50a547f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/odr/__init__.py @@ -0,0 +1,131 @@ +""" +================================================= +Orthogonal distance regression (:mod:`scipy.odr`) +================================================= + +.. currentmodule:: scipy.odr + +Package Content +=============== + +.. autosummary:: + :toctree: generated/ + + Data -- The data to fit. + RealData -- Data with weights as actual std. dev.s and/or covariances. + Model -- Stores information about the function to be fit. + ODR -- Gathers all info & manages the main fitting routine. + Output -- Result from the fit. + odr -- Low-level function for ODR. + + OdrWarning -- Warning about potential problems when running ODR. + OdrError -- Error exception. + OdrStop -- Stop exception. + + polynomial -- Factory function for a general polynomial model. + exponential -- Exponential model + multilinear -- Arbitrary-dimensional linear model + unilinear -- Univariate linear model + quadratic -- Quadratic model + +Usage information +================= + +Introduction +------------ + +Why Orthogonal Distance Regression (ODR)? Sometimes one has +measurement errors in the explanatory (a.k.a., "independent") +variable(s), not just the response (a.k.a., "dependent") variable(s). +Ordinary Least Squares (OLS) fitting procedures treat the data for +explanatory variables as fixed, i.e., not subject to error of any kind. +Furthermore, OLS procedures require that the response variables be an +explicit function of the explanatory variables; sometimes making the +equation explicit is impractical and/or introduces errors. ODR can +handle both of these cases with ease, and can even reduce to the OLS +case if that is sufficient for the problem. + +ODRPACK is a FORTRAN-77 library for performing ODR with possibly +non-linear fitting functions. It uses a modified trust-region +Levenberg-Marquardt-type algorithm [1]_ to estimate the function +parameters. The fitting functions are provided by Python functions +operating on NumPy arrays. The required derivatives may be provided +by Python functions as well, or may be estimated numerically. ODRPACK +can do explicit or implicit ODR fits, or it can do OLS. Input and +output variables may be multidimensional. Weights can be provided to +account for different variances of the observations, and even +covariances between dimensions of the variables. + +The `scipy.odr` package offers an object-oriented interface to +ODRPACK, in addition to the low-level `odr` function. + +Additional background information about ODRPACK can be found in the +`ODRPACK User's Guide +`_, reading +which is recommended. + +Basic usage +----------- + +1. Define the function you want to fit against.:: + + def f(B, x): + '''Linear function y = m*x + b''' + # B is a vector of the parameters. + # x is an array of the current x values. + # x is in the same format as the x passed to Data or RealData. + # + # Return an array in the same format as y passed to Data or RealData. + return B[0]*x + B[1] + +2. Create a Model.:: + + linear = Model(f) + +3. Create a Data or RealData instance.:: + + mydata = Data(x, y, wd=1./power(sx,2), we=1./power(sy,2)) + + or, when the actual covariances are known:: + + mydata = RealData(x, y, sx=sx, sy=sy) + +4. Instantiate ODR with your data, model and initial parameter estimate.:: + + myodr = ODR(mydata, linear, beta0=[1., 2.]) + +5. Run the fit.:: + + myoutput = myodr.run() + +6. Examine output.:: + + myoutput.pprint() + + +References +---------- +.. [1] P. T. Boggs and J. E. Rogers, "Orthogonal Distance Regression," + in "Statistical analysis of measurement error models and + applications: proceedings of the AMS-IMS-SIAM joint summer research + conference held June 10-16, 1989," Contemporary Mathematics, + vol. 112, pg. 186, 1990. + +""" +# version: 0.7 +# author: Robert Kern +# date: 2006-09-21 + +from ._odrpack import * +from ._models import * +from . import _add_newdocs + +# Deprecated namespaces, to be removed in v2.0.0 +from . import models, odrpack + +__all__ = [s for s in dir() + if not (s.startswith('_') or s in ('odr_stop', 'odr_error'))] + +from scipy._lib._testutils import PytestTester +test = PytestTester(__name__) +del PytestTester diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/odr/_add_newdocs.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/odr/_add_newdocs.py new file mode 100644 index 0000000000000000000000000000000000000000..e09fb6cc8c5f1523dfbeaef466a5b76bd22c01bb --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/odr/_add_newdocs.py @@ -0,0 +1,34 @@ +from numpy.lib import add_newdoc + +add_newdoc('scipy.odr', 'odr', + """ + odr(fcn, beta0, y, x, we=None, wd=None, fjacb=None, fjacd=None, extra_args=None, + ifixx=None, ifixb=None, job=0, iprint=0, errfile=None, rptfile=None, ndigit=0, + taufac=0.0, sstol=-1.0, partol=-1.0, maxit=-1, stpb=None, stpd=None, sclb=None, + scld=None, work=None, iwork=None, full_output=0) + + Low-level function for ODR. + + See Also + -------- + ODR : The ODR class gathers all information and coordinates the running of the + main fitting routine. + Model : The Model class stores information about the function you wish to fit. + Data : The data to fit. + RealData : Data with weights as actual std. dev.s and/or covariances. + + Notes + ----- + This is a function performing the same operation as the `ODR`, + `Model`, and `Data` classes together. The parameters of this + function are explained in the class documentation. + + """) + +add_newdoc('scipy.odr.__odrpack', '_set_exceptions', + """ + _set_exceptions(odr_error, odr_stop) + + Internal function: set exception classes. + + """) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/odr/_models.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/odr/_models.py new file mode 100644 index 0000000000000000000000000000000000000000..e0a8d2275dcc4698a9ea61be5871d62069be2599 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/odr/_models.py @@ -0,0 +1,315 @@ +""" Collection of Model instances for use with the odrpack fitting package. +""" +import numpy as np +from scipy.odr._odrpack import Model + +__all__ = ['Model', 'exponential', 'multilinear', 'unilinear', 'quadratic', + 'polynomial'] + + +def _lin_fcn(B, x): + a, b = B[0], B[1:] + b.shape = (b.shape[0], 1) + + return a + (x*b).sum(axis=0) + + +def _lin_fjb(B, x): + a = np.ones(x.shape[-1], float) + res = np.concatenate((a, x.ravel())) + res.shape = (B.shape[-1], x.shape[-1]) + return res + + +def _lin_fjd(B, x): + b = B[1:] + b = np.repeat(b, (x.shape[-1],)*b.shape[-1], axis=0) + b.shape = x.shape + return b + + +def _lin_est(data): + # Eh. The answer is analytical, so just return all ones. + # Don't return zeros since that will interfere with + # ODRPACK's auto-scaling procedures. + + if len(data.x.shape) == 2: + m = data.x.shape[0] + else: + m = 1 + + return np.ones((m + 1,), float) + + +def _poly_fcn(B, x, powers): + a, b = B[0], B[1:] + b.shape = (b.shape[0], 1) + + return a + np.sum(b * np.power(x, powers), axis=0) + + +def _poly_fjacb(B, x, powers): + res = np.concatenate((np.ones(x.shape[-1], float), + np.power(x, powers).flat)) + res.shape = (B.shape[-1], x.shape[-1]) + return res + + +def _poly_fjacd(B, x, powers): + b = B[1:] + b.shape = (b.shape[0], 1) + + b = b * powers + + return np.sum(b * np.power(x, powers-1), axis=0) + + +def _exp_fcn(B, x): + return B[0] + np.exp(B[1] * x) + + +def _exp_fjd(B, x): + return B[1] * np.exp(B[1] * x) + + +def _exp_fjb(B, x): + res = np.concatenate((np.ones(x.shape[-1], float), x * np.exp(B[1] * x))) + res.shape = (2, x.shape[-1]) + return res + + +def _exp_est(data): + # Eh. + return np.array([1., 1.]) + + +class _MultilinearModel(Model): + r""" + Arbitrary-dimensional linear model + + This model is defined by :math:`y=\beta_0 + \sum_{i=1}^m \beta_i x_i` + + Examples + -------- + We can calculate orthogonal distance regression with an arbitrary + dimensional linear model: + + >>> from scipy import odr + >>> import numpy as np + >>> x = np.linspace(0.0, 5.0) + >>> y = 10.0 + 5.0 * x + >>> data = odr.Data(x, y) + >>> odr_obj = odr.ODR(data, odr.multilinear) + >>> output = odr_obj.run() + >>> print(output.beta) + [10. 5.] + + """ + + def __init__(self): + super().__init__( + _lin_fcn, fjacb=_lin_fjb, fjacd=_lin_fjd, estimate=_lin_est, + meta={'name': 'Arbitrary-dimensional Linear', + 'equ': 'y = B_0 + Sum[i=1..m, B_i * x_i]', + 'TeXequ': r'$y=\beta_0 + \sum_{i=1}^m \beta_i x_i$'}) + + +multilinear = _MultilinearModel() + + +def polynomial(order): + """ + Factory function for a general polynomial model. + + Parameters + ---------- + order : int or sequence + If an integer, it becomes the order of the polynomial to fit. If + a sequence of numbers, then these are the explicit powers in the + polynomial. + A constant term (power 0) is always included, so don't include 0. + Thus, polynomial(n) is equivalent to polynomial(range(1, n+1)). + + Returns + ------- + polynomial : Model instance + Model instance. + + Examples + -------- + We can fit an input data using orthogonal distance regression (ODR) with + a polynomial model: + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy import odr + >>> x = np.linspace(0.0, 5.0) + >>> y = np.sin(x) + >>> poly_model = odr.polynomial(3) # using third order polynomial model + >>> data = odr.Data(x, y) + >>> odr_obj = odr.ODR(data, poly_model) + >>> output = odr_obj.run() # running ODR fitting + >>> poly = np.poly1d(output.beta[::-1]) + >>> poly_y = poly(x) + >>> plt.plot(x, y, label="input data") + >>> plt.plot(x, poly_y, label="polynomial ODR") + >>> plt.legend() + >>> plt.show() + + """ + + powers = np.asarray(order) + if powers.shape == (): + # Scalar. + powers = np.arange(1, powers + 1) + + powers.shape = (len(powers), 1) + len_beta = len(powers) + 1 + + def _poly_est(data, len_beta=len_beta): + # Eh. Ignore data and return all ones. + return np.ones((len_beta,), float) + + return Model(_poly_fcn, fjacd=_poly_fjacd, fjacb=_poly_fjacb, + estimate=_poly_est, extra_args=(powers,), + meta={'name': 'Sorta-general Polynomial', + 'equ': 'y = B_0 + Sum[i=1..%s, B_i * (x**i)]' % (len_beta-1), + 'TeXequ': r'$y=\beta_0 + \sum_{i=1}^{%s} \beta_i x^i$' % + (len_beta-1)}) + + +class _ExponentialModel(Model): + r""" + Exponential model + + This model is defined by :math:`y=\beta_0 + e^{\beta_1 x}` + + Examples + -------- + We can calculate orthogonal distance regression with an exponential model: + + >>> from scipy import odr + >>> import numpy as np + >>> x = np.linspace(0.0, 5.0) + >>> y = -10.0 + np.exp(0.5*x) + >>> data = odr.Data(x, y) + >>> odr_obj = odr.ODR(data, odr.exponential) + >>> output = odr_obj.run() + >>> print(output.beta) + [-10. 0.5] + + """ + + def __init__(self): + super().__init__(_exp_fcn, fjacd=_exp_fjd, fjacb=_exp_fjb, + estimate=_exp_est, + meta={'name': 'Exponential', + 'equ': 'y= B_0 + exp(B_1 * x)', + 'TeXequ': r'$y=\beta_0 + e^{\beta_1 x}$'}) + + +exponential = _ExponentialModel() + + +def _unilin(B, x): + return x*B[0] + B[1] + + +def _unilin_fjd(B, x): + return np.ones(x.shape, float) * B[0] + + +def _unilin_fjb(B, x): + _ret = np.concatenate((x, np.ones(x.shape, float))) + _ret.shape = (2,) + x.shape + + return _ret + + +def _unilin_est(data): + return (1., 1.) + + +def _quadratic(B, x): + return x*(x*B[0] + B[1]) + B[2] + + +def _quad_fjd(B, x): + return 2*x*B[0] + B[1] + + +def _quad_fjb(B, x): + _ret = np.concatenate((x*x, x, np.ones(x.shape, float))) + _ret.shape = (3,) + x.shape + + return _ret + + +def _quad_est(data): + return (1.,1.,1.) + + +class _UnilinearModel(Model): + r""" + Univariate linear model + + This model is defined by :math:`y = \beta_0 x + \beta_1` + + Examples + -------- + We can calculate orthogonal distance regression with an unilinear model: + + >>> from scipy import odr + >>> import numpy as np + >>> x = np.linspace(0.0, 5.0) + >>> y = 1.0 * x + 2.0 + >>> data = odr.Data(x, y) + >>> odr_obj = odr.ODR(data, odr.unilinear) + >>> output = odr_obj.run() + >>> print(output.beta) + [1. 2.] + + """ + + def __init__(self): + super().__init__(_unilin, fjacd=_unilin_fjd, fjacb=_unilin_fjb, + estimate=_unilin_est, + meta={'name': 'Univariate Linear', + 'equ': 'y = B_0 * x + B_1', + 'TeXequ': '$y = \\beta_0 x + \\beta_1$'}) + + +unilinear = _UnilinearModel() + + +class _QuadraticModel(Model): + r""" + Quadratic model + + This model is defined by :math:`y = \beta_0 x^2 + \beta_1 x + \beta_2` + + Examples + -------- + We can calculate orthogonal distance regression with a quadratic model: + + >>> from scipy import odr + >>> import numpy as np + >>> x = np.linspace(0.0, 5.0) + >>> y = 1.0 * x ** 2 + 2.0 * x + 3.0 + >>> data = odr.Data(x, y) + >>> odr_obj = odr.ODR(data, odr.quadratic) + >>> output = odr_obj.run() + >>> print(output.beta) + [1. 2. 3.] + + """ + + def __init__(self): + super().__init__( + _quadratic, fjacd=_quad_fjd, fjacb=_quad_fjb, estimate=_quad_est, + meta={'name': 'Quadratic', + 'equ': 'y = B_0*x**2 + B_1*x + B_2', + 'TeXequ': '$y = \\beta_0 x^2 + \\beta_1 x + \\beta_2'}) + + +quadratic = _QuadraticModel() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/odr/_odrpack.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/odr/_odrpack.py new file mode 100644 index 0000000000000000000000000000000000000000..30d46aa3f4465f31b32e5f13f0b01b940981d489 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/odr/_odrpack.py @@ -0,0 +1,1154 @@ +""" +Python wrappers for Orthogonal Distance Regression (ODRPACK). + +Notes +===== + +* Array formats -- FORTRAN stores its arrays in memory column first, i.e., an + array element A(i, j, k) will be next to A(i+1, j, k). In C and, consequently, + NumPy, arrays are stored row first: A[i, j, k] is next to A[i, j, k+1]. For + efficiency and convenience, the input and output arrays of the fitting + function (and its Jacobians) are passed to FORTRAN without transposition. + Therefore, where the ODRPACK documentation says that the X array is of shape + (N, M), it will be passed to the Python function as an array of shape (M, N). + If M==1, the 1-D case, then nothing matters; if M>1, then your + Python functions will be dealing with arrays that are indexed in reverse of + the ODRPACK documentation. No real issue, but watch out for your indexing of + the Jacobians: the i,jth elements (@f_i/@x_j) evaluated at the nth + observation will be returned as jacd[j, i, n]. Except for the Jacobians, it + really is easier to deal with x[0] and x[1] than x[:,0] and x[:,1]. Of course, + you can always use the transpose() function from SciPy explicitly. + +* Examples -- See the accompanying file test/test.py for examples of how to set + up fits of your own. Some are taken from the User's Guide; some are from + other sources. + +* Models -- Some common models are instantiated in the accompanying module + models.py . Contributions are welcome. + +Credits +======= + +* Thanks to Arnold Moene and Gerard Vermeulen for fixing some killer bugs. + +Robert Kern +robert.kern@gmail.com + +""" +import os +from threading import Lock + +import numpy as np +from warnings import warn +from scipy.odr import __odrpack + +__all__ = ['odr', 'OdrWarning', 'OdrError', 'OdrStop', + 'Data', 'RealData', 'Model', 'Output', 'ODR', + 'odr_error', 'odr_stop'] + +odr = __odrpack.odr +ODR_LOCK = Lock() + + +class OdrWarning(UserWarning): + """ + Warning indicating that the data passed into + ODR will cause problems when passed into 'odr' + that the user should be aware of. + """ + pass + + +class OdrError(Exception): + """ + Exception indicating an error in fitting. + + This is raised by `~scipy.odr.odr` if an error occurs during fitting. + """ + pass + + +class OdrStop(Exception): + """ + Exception stopping fitting. + + You can raise this exception in your objective function to tell + `~scipy.odr.odr` to stop fitting. + """ + pass + + +# Backwards compatibility +odr_error = OdrError +odr_stop = OdrStop + +__odrpack._set_exceptions(OdrError, OdrStop) + + +def _conv(obj, dtype=None): + """ Convert an object to the preferred form for input to the odr routine. + """ + + if obj is None: + return obj + else: + if dtype is None: + obj = np.asarray(obj) + else: + obj = np.asarray(obj, dtype) + if obj.shape == (): + # Scalar. + return obj.dtype.type(obj) + else: + return obj + + +def _report_error(info): + """ Interprets the return code of the odr routine. + + Parameters + ---------- + info : int + The return code of the odr routine. + + Returns + ------- + problems : list(str) + A list of messages about why the odr() routine stopped. + """ + + stopreason = ('Blank', + 'Sum of squares convergence', + 'Parameter convergence', + 'Both sum of squares and parameter convergence', + 'Iteration limit reached')[info % 5] + + if info >= 5: + # questionable results or fatal error + + I = (info//10000 % 10, + info//1000 % 10, + info//100 % 10, + info//10 % 10, + info % 10) + problems = [] + + if I[0] == 0: + if I[1] != 0: + problems.append('Derivatives possibly not correct') + if I[2] != 0: + problems.append('Error occurred in callback') + if I[3] != 0: + problems.append('Problem is not full rank at solution') + problems.append(stopreason) + elif I[0] == 1: + if I[1] != 0: + problems.append('N < 1') + if I[2] != 0: + problems.append('M < 1') + if I[3] != 0: + problems.append('NP < 1 or NP > N') + if I[4] != 0: + problems.append('NQ < 1') + elif I[0] == 2: + if I[1] != 0: + problems.append('LDY and/or LDX incorrect') + if I[2] != 0: + problems.append('LDWE, LD2WE, LDWD, and/or LD2WD incorrect') + if I[3] != 0: + problems.append('LDIFX, LDSTPD, and/or LDSCLD incorrect') + if I[4] != 0: + problems.append('LWORK and/or LIWORK too small') + elif I[0] == 3: + if I[1] != 0: + problems.append('STPB and/or STPD incorrect') + if I[2] != 0: + problems.append('SCLB and/or SCLD incorrect') + if I[3] != 0: + problems.append('WE incorrect') + if I[4] != 0: + problems.append('WD incorrect') + elif I[0] == 4: + problems.append('Error in derivatives') + elif I[0] == 5: + problems.append('Error occurred in callback') + elif I[0] == 6: + problems.append('Numerical error detected') + + return problems + + else: + return [stopreason] + + +class Data: + """ + The data to fit. + + Parameters + ---------- + x : array_like + Observed data for the independent variable of the regression + y : array_like, optional + If array-like, observed data for the dependent variable of the + regression. A scalar input implies that the model to be used on + the data is implicit. + we : array_like, optional + If `we` is a scalar, then that value is used for all data points (and + all dimensions of the response variable). + If `we` is a rank-1 array of length q (the dimensionality of the + response variable), then this vector is the diagonal of the covariant + weighting matrix for all data points. + If `we` is a rank-1 array of length n (the number of data points), then + the i'th element is the weight for the i'th response variable + observation (single-dimensional only). + If `we` is a rank-2 array of shape (q, q), then this is the full + covariant weighting matrix broadcast to each observation. + If `we` is a rank-2 array of shape (q, n), then `we[:,i]` is the + diagonal of the covariant weighting matrix for the i'th observation. + If `we` is a rank-3 array of shape (q, q, n), then `we[:,:,i]` is the + full specification of the covariant weighting matrix for each + observation. + If the fit is implicit, then only a positive scalar value is used. + wd : array_like, optional + If `wd` is a scalar, then that value is used for all data points + (and all dimensions of the input variable). If `wd` = 0, then the + covariant weighting matrix for each observation is set to the identity + matrix (so each dimension of each observation has the same weight). + If `wd` is a rank-1 array of length m (the dimensionality of the input + variable), then this vector is the diagonal of the covariant weighting + matrix for all data points. + If `wd` is a rank-1 array of length n (the number of data points), then + the i'th element is the weight for the ith input variable observation + (single-dimensional only). + If `wd` is a rank-2 array of shape (m, m), then this is the full + covariant weighting matrix broadcast to each observation. + If `wd` is a rank-2 array of shape (m, n), then `wd[:,i]` is the + diagonal of the covariant weighting matrix for the ith observation. + If `wd` is a rank-3 array of shape (m, m, n), then `wd[:,:,i]` is the + full specification of the covariant weighting matrix for each + observation. + fix : array_like of ints, optional + The `fix` argument is the same as ifixx in the class ODR. It is an + array of integers with the same shape as data.x that determines which + input observations are treated as fixed. One can use a sequence of + length m (the dimensionality of the input observations) to fix some + dimensions for all observations. A value of 0 fixes the observation, + a value > 0 makes it free. + meta : dict, optional + Free-form dictionary for metadata. + + Notes + ----- + Each argument is attached to the member of the instance of the same name. + The structures of `x` and `y` are described in the Model class docstring. + If `y` is an integer, then the Data instance can only be used to fit with + implicit models where the dimensionality of the response is equal to the + specified value of `y`. + + The `we` argument weights the effect a deviation in the response variable + has on the fit. The `wd` argument weights the effect a deviation in the + input variable has on the fit. To handle multidimensional inputs and + responses easily, the structure of these arguments has the n'th + dimensional axis first. These arguments heavily use the structured + arguments feature of ODRPACK to conveniently and flexibly support all + options. See the ODRPACK User's Guide for a full explanation of how these + weights are used in the algorithm. Basically, a higher value of the weight + for a particular data point makes a deviation at that point more + detrimental to the fit. + + """ + + def __init__(self, x, y=None, we=None, wd=None, fix=None, meta=None): + self.x = _conv(x) + + if not isinstance(self.x, np.ndarray): + raise ValueError("Expected an 'ndarray' of data for 'x', " + f"but instead got data of type '{type(self.x).__name__}'") + + self.y = _conv(y) + self.we = _conv(we) + self.wd = _conv(wd) + self.fix = _conv(fix) + self.meta = {} if meta is None else meta + + def set_meta(self, **kwds): + """ Update the metadata dictionary with the keywords and data provided + by keywords. + + Examples + -------- + :: + + data.set_meta(lab="Ph 7; Lab 26", title="Ag110 + Ag108 Decay") + """ + + self.meta.update(kwds) + + def __getattr__(self, attr): + """ Dispatch attribute access to the metadata dictionary. + """ + if attr != "meta" and attr in self.meta: + return self.meta[attr] + else: + raise AttributeError(f"'{attr}' not in metadata") + + +class RealData(Data): + """ + The data, with weightings as actual standard deviations and/or + covariances. + + Parameters + ---------- + x : array_like + Observed data for the independent variable of the regression + y : array_like, optional + If array-like, observed data for the dependent variable of the + regression. A scalar input implies that the model to be used on + the data is implicit. + sx : array_like, optional + Standard deviations of `x`. + `sx` are standard deviations of `x` and are converted to weights by + dividing 1.0 by their squares. + sy : array_like, optional + Standard deviations of `y`. + `sy` are standard deviations of `y` and are converted to weights by + dividing 1.0 by their squares. + covx : array_like, optional + Covariance of `x` + `covx` is an array of covariance matrices of `x` and are converted to + weights by performing a matrix inversion on each observation's + covariance matrix. + covy : array_like, optional + Covariance of `y` + `covy` is an array of covariance matrices and are converted to + weights by performing a matrix inversion on each observation's + covariance matrix. + fix : array_like, optional + The argument and member fix is the same as Data.fix and ODR.ifixx: + It is an array of integers with the same shape as `x` that + determines which input observations are treated as fixed. One can + use a sequence of length m (the dimensionality of the input + observations) to fix some dimensions for all observations. A value + of 0 fixes the observation, a value > 0 makes it free. + meta : dict, optional + Free-form dictionary for metadata. + + Notes + ----- + The weights `wd` and `we` are computed from provided values as follows: + + `sx` and `sy` are converted to weights by dividing 1.0 by their squares. + For example, ``wd = 1./np.power(`sx`, 2)``. + + `covx` and `covy` are arrays of covariance matrices and are converted to + weights by performing a matrix inversion on each observation's covariance + matrix. For example, ``we[i] = np.linalg.inv(covy[i])``. + + These arguments follow the same structured argument conventions as wd and + we only restricted by their natures: `sx` and `sy` can't be rank-3, but + `covx` and `covy` can be. + + Only set *either* `sx` or `covx` (not both). Setting both will raise an + exception. Same with `sy` and `covy`. + + """ + + def __init__(self, x, y=None, sx=None, sy=None, covx=None, covy=None, + fix=None, meta=None): + if (sx is not None) and (covx is not None): + raise ValueError("cannot set both sx and covx") + if (sy is not None) and (covy is not None): + raise ValueError("cannot set both sy and covy") + + # Set flags for __getattr__ + self._ga_flags = {} + if sx is not None: + self._ga_flags['wd'] = 'sx' + else: + self._ga_flags['wd'] = 'covx' + if sy is not None: + self._ga_flags['we'] = 'sy' + else: + self._ga_flags['we'] = 'covy' + + self.x = _conv(x) + + if not isinstance(self.x, np.ndarray): + raise ValueError("Expected an 'ndarray' of data for 'x', " + f"but instead got data of type '{type(self.x).__name__}'") + + self.y = _conv(y) + self.sx = _conv(sx) + self.sy = _conv(sy) + self.covx = _conv(covx) + self.covy = _conv(covy) + self.fix = _conv(fix) + self.meta = {} if meta is None else meta + + def _sd2wt(self, sd): + """ Convert standard deviation to weights. + """ + + return 1./np.power(sd, 2) + + def _cov2wt(self, cov): + """ Convert covariance matrix(-ices) to weights. + """ + + from scipy.linalg import inv + + if len(cov.shape) == 2: + return inv(cov) + else: + weights = np.zeros(cov.shape, float) + + for i in range(cov.shape[-1]): # n + weights[:,:,i] = inv(cov[:,:,i]) + + return weights + + def __getattr__(self, attr): + + if attr not in ('wd', 'we'): + if attr != "meta" and attr in self.meta: + return self.meta[attr] + else: + raise AttributeError(f"'{attr}' not in metadata") + else: + lookup_tbl = {('wd', 'sx'): (self._sd2wt, self.sx), + ('wd', 'covx'): (self._cov2wt, self.covx), + ('we', 'sy'): (self._sd2wt, self.sy), + ('we', 'covy'): (self._cov2wt, self.covy)} + + func, arg = lookup_tbl[(attr, self._ga_flags[attr])] + + if arg is not None: + return func(*(arg,)) + else: + return None + + +class Model: + """ + The Model class stores information about the function you wish to fit. + + It stores the function itself, at the least, and optionally stores + functions which compute the Jacobians used during fitting. Also, one + can provide a function that will provide reasonable starting values + for the fit parameters possibly given the set of data. + + Parameters + ---------- + fcn : function + fcn(beta, x) --> y + fjacb : function + Jacobian of fcn wrt the fit parameters beta. + + fjacb(beta, x) --> @f_i(x,B)/@B_j + fjacd : function + Jacobian of fcn wrt the (possibly multidimensional) input + variable. + + fjacd(beta, x) --> @f_i(x,B)/@x_j + extra_args : tuple, optional + If specified, `extra_args` should be a tuple of extra + arguments to pass to `fcn`, `fjacb`, and `fjacd`. Each will be called + by `apply(fcn, (beta, x) + extra_args)` + estimate : array_like of rank-1 + Provides estimates of the fit parameters from the data + + estimate(data) --> estbeta + implicit : boolean + If TRUE, specifies that the model + is implicit; i.e `fcn(beta, x)` ~= 0 and there is no y data to fit + against + meta : dict, optional + freeform dictionary of metadata for the model + + Notes + ----- + Note that the `fcn`, `fjacb`, and `fjacd` operate on NumPy arrays and + return a NumPy array. The `estimate` object takes an instance of the + Data class. + + Here are the rules for the shapes of the argument and return + arrays of the callback functions: + + `x` + if the input data is single-dimensional, then `x` is rank-1 + array; i.e., ``x = array([1, 2, 3, ...]); x.shape = (n,)`` + If the input data is multi-dimensional, then `x` is a rank-2 array; + i.e., ``x = array([[1, 2, ...], [2, 4, ...]]); x.shape = (m, n)``. + In all cases, it has the same shape as the input data array passed to + `~scipy.odr.odr`. `m` is the dimensionality of the input data, + `n` is the number of observations. + `y` + if the response variable is single-dimensional, then `y` is a + rank-1 array, i.e., ``y = array([2, 4, ...]); y.shape = (n,)``. + If the response variable is multi-dimensional, then `y` is a rank-2 + array, i.e., ``y = array([[2, 4, ...], [3, 6, ...]]); y.shape = + (q, n)`` where `q` is the dimensionality of the response variable. + `beta` + rank-1 array of length `p` where `p` is the number of parameters; + i.e. ``beta = array([B_1, B_2, ..., B_p])`` + `fjacb` + if the response variable is multi-dimensional, then the + return array's shape is ``(q, p, n)`` such that ``fjacb(x,beta)[l,k,i] = + d f_l(X,B)/d B_k`` evaluated at the ith data point. If ``q == 1``, then + the return array is only rank-2 and with shape ``(p, n)``. + `fjacd` + as with fjacb, only the return array's shape is ``(q, m, n)`` + such that ``fjacd(x,beta)[l,j,i] = d f_l(X,B)/d X_j`` at the ith data + point. If ``q == 1``, then the return array's shape is ``(m, n)``. If + ``m == 1``, the shape is (q, n). If `m == q == 1`, the shape is ``(n,)``. + + """ + + def __init__(self, fcn, fjacb=None, fjacd=None, + extra_args=None, estimate=None, implicit=0, meta=None): + + self.fcn = fcn + self.fjacb = fjacb + self.fjacd = fjacd + + if extra_args is not None: + extra_args = tuple(extra_args) + + self.extra_args = extra_args + self.estimate = estimate + self.implicit = implicit + self.meta = meta if meta is not None else {} + + def set_meta(self, **kwds): + """ Update the metadata dictionary with the keywords and data provided + here. + + Examples + -------- + set_meta(name="Exponential", equation="y = a exp(b x) + c") + """ + + self.meta.update(kwds) + + def __getattr__(self, attr): + """ Dispatch attribute access to the metadata. + """ + + if attr != "meta" and attr in self.meta: + return self.meta[attr] + else: + raise AttributeError(f"'{attr}' not in metadata") + + +class Output: + """ + The Output class stores the output of an ODR run. + + Attributes + ---------- + beta : ndarray + Estimated parameter values, of shape (q,). + sd_beta : ndarray + Standard deviations of the estimated parameters, of shape (p,). + cov_beta : ndarray + Covariance matrix of the estimated parameters, of shape (p,p). + Note that this `cov_beta` is not scaled by the residual variance + `res_var`, whereas `sd_beta` is. This means + ``np.sqrt(np.diag(output.cov_beta * output.res_var))`` is the same + result as `output.sd_beta`. + delta : ndarray, optional + Array of estimated errors in input variables, of same shape as `x`. + eps : ndarray, optional + Array of estimated errors in response variables, of same shape as `y`. + xplus : ndarray, optional + Array of ``x + delta``. + y : ndarray, optional + Array ``y = fcn(x + delta)``. + res_var : float, optional + Residual variance. + sum_square : float, optional + Sum of squares error. + sum_square_delta : float, optional + Sum of squares of delta error. + sum_square_eps : float, optional + Sum of squares of eps error. + inv_condnum : float, optional + Inverse condition number (cf. ODRPACK UG p. 77). + rel_error : float, optional + Relative error in function values computed within fcn. + work : ndarray, optional + Final work array. + work_ind : dict, optional + Indices into work for drawing out values (cf. ODRPACK UG p. 83). + info : int, optional + Reason for returning, as output by ODRPACK (cf. ODRPACK UG p. 38). + stopreason : list of str, optional + `info` interpreted into English. + + Notes + ----- + Takes one argument for initialization, the return value from the + function `~scipy.odr.odr`. The attributes listed as "optional" above are + only present if `~scipy.odr.odr` was run with ``full_output=1``. + + """ + + def __init__(self, output): + self.beta = output[0] + self.sd_beta = output[1] + self.cov_beta = output[2] + + if len(output) == 4: + # full output + self.__dict__.update(output[3]) + self.stopreason = _report_error(self.info) + + def pprint(self): + """ Pretty-print important results. + """ + + print('Beta:', self.beta) + print('Beta Std Error:', self.sd_beta) + print('Beta Covariance:', self.cov_beta) + if hasattr(self, 'info'): + print('Residual Variance:',self.res_var) + print('Inverse Condition #:', self.inv_condnum) + print('Reason(s) for Halting:') + for r in self.stopreason: + print(f' {r}') + + +class ODR: + """ + The ODR class gathers all information and coordinates the running of the + main fitting routine. + + Members of instances of the ODR class have the same names as the arguments + to the initialization routine. + + Parameters + ---------- + data : Data class instance + instance of the Data class + model : Model class instance + instance of the Model class + + Other Parameters + ---------------- + beta0 : array_like of rank-1 + a rank-1 sequence of initial parameter values. Optional if + model provides an "estimate" function to estimate these values. + delta0 : array_like of floats of rank-1, optional + a (double-precision) float array to hold the initial values of + the errors in the input variables. Must be same shape as data.x + ifixb : array_like of ints of rank-1, optional + sequence of integers with the same length as beta0 that determines + which parameters are held fixed. A value of 0 fixes the parameter, + a value > 0 makes the parameter free. + ifixx : array_like of ints with same shape as data.x, optional + an array of integers with the same shape as data.x that determines + which input observations are treated as fixed. One can use a sequence + of length m (the dimensionality of the input observations) to fix some + dimensions for all observations. A value of 0 fixes the observation, + a value > 0 makes it free. + job : int, optional + an integer telling ODRPACK what tasks to perform. See p. 31 of the + ODRPACK User's Guide if you absolutely must set the value here. Use the + method set_job post-initialization for a more readable interface. + iprint : int, optional + an integer telling ODRPACK what to print. See pp. 33-34 of the + ODRPACK User's Guide if you absolutely must set the value here. Use the + method set_iprint post-initialization for a more readable interface. + errfile : str, optional + string with the filename to print ODRPACK errors to. If the file already + exists, an error will be thrown. The `overwrite` argument can be used to + prevent this. *Do Not Open This File Yourself!* + rptfile : str, optional + string with the filename to print ODRPACK summaries to. If the file + already exists, an error will be thrown. The `overwrite` argument can be + used to prevent this. *Do Not Open This File Yourself!* + ndigit : int, optional + integer specifying the number of reliable digits in the computation + of the function. + taufac : float, optional + float specifying the initial trust region. The default value is 1. + The initial trust region is equal to taufac times the length of the + first computed Gauss-Newton step. taufac must be less than 1. + sstol : float, optional + float specifying the tolerance for convergence based on the relative + change in the sum-of-squares. The default value is eps**(1/2) where eps + is the smallest value such that 1 + eps > 1 for double precision + computation on the machine. sstol must be less than 1. + partol : float, optional + float specifying the tolerance for convergence based on the relative + change in the estimated parameters. The default value is eps**(2/3) for + explicit models and ``eps**(1/3)`` for implicit models. partol must be less + than 1. + maxit : int, optional + integer specifying the maximum number of iterations to perform. For + first runs, maxit is the total number of iterations performed and + defaults to 50. For restarts, maxit is the number of additional + iterations to perform and defaults to 10. + stpb : array_like, optional + sequence (``len(stpb) == len(beta0)``) of relative step sizes to compute + finite difference derivatives wrt the parameters. + stpd : optional + array (``stpd.shape == data.x.shape`` or ``stpd.shape == (m,)``) of relative + step sizes to compute finite difference derivatives wrt the input + variable errors. If stpd is a rank-1 array with length m (the + dimensionality of the input variable), then the values are broadcast to + all observations. + sclb : array_like, optional + sequence (``len(stpb) == len(beta0)``) of scaling factors for the + parameters. The purpose of these scaling factors are to scale all of + the parameters to around unity. Normally appropriate scaling factors + are computed if this argument is not specified. Specify them yourself + if the automatic procedure goes awry. + scld : array_like, optional + array (scld.shape == data.x.shape or scld.shape == (m,)) of scaling + factors for the *errors* in the input variables. Again, these factors + are automatically computed if you do not provide them. If scld.shape == + (m,), then the scaling factors are broadcast to all observations. + work : ndarray, optional + array to hold the double-valued working data for ODRPACK. When + restarting, takes the value of self.output.work. + iwork : ndarray, optional + array to hold the integer-valued working data for ODRPACK. When + restarting, takes the value of self.output.iwork. + overwrite : bool, optional + If it is True, output files defined by `errfile` and `rptfile` are + overwritten. The default is False. + + Attributes + ---------- + data : Data + The data for this fit + model : Model + The model used in fit + output : Output + An instance if the Output class containing all of the returned + data from an invocation of ODR.run() or ODR.restart() + + """ + + def __init__(self, data, model, beta0=None, delta0=None, ifixb=None, + ifixx=None, job=None, iprint=None, errfile=None, rptfile=None, + ndigit=None, taufac=None, sstol=None, partol=None, maxit=None, + stpb=None, stpd=None, sclb=None, scld=None, work=None, iwork=None, + overwrite=False): + + self.data = data + self.model = model + + if beta0 is None: + if self.model.estimate is not None: + self.beta0 = _conv(self.model.estimate(self.data)) + else: + raise ValueError( + "must specify beta0 or provide an estimator with the model" + ) + else: + self.beta0 = _conv(beta0) + + if ifixx is None and data.fix is not None: + ifixx = data.fix + + if overwrite: + # remove output files for overwriting. + if rptfile is not None and os.path.exists(rptfile): + os.remove(rptfile) + if errfile is not None and os.path.exists(errfile): + os.remove(errfile) + + self.delta0 = _conv(delta0) + # These really are 32-bit integers in FORTRAN (gfortran), even on 64-bit + # platforms. + # XXX: some other FORTRAN compilers may not agree. + self.ifixx = _conv(ifixx, dtype=np.int32) + self.ifixb = _conv(ifixb, dtype=np.int32) + self.job = job + self.iprint = iprint + self.errfile = errfile + self.rptfile = rptfile + self.ndigit = ndigit + self.taufac = taufac + self.sstol = sstol + self.partol = partol + self.maxit = maxit + self.stpb = _conv(stpb) + self.stpd = _conv(stpd) + self.sclb = _conv(sclb) + self.scld = _conv(scld) + self.work = _conv(work) + self.iwork = _conv(iwork) + + self.output = None + + self._check() + + def _check(self): + """ Check the inputs for consistency, but don't bother checking things + that the builtin function odr will check. + """ + + x_s = list(self.data.x.shape) + + if isinstance(self.data.y, np.ndarray): + y_s = list(self.data.y.shape) + if self.model.implicit: + raise OdrError("an implicit model cannot use response data") + else: + # implicit model with q == self.data.y + y_s = [self.data.y, x_s[-1]] + if not self.model.implicit: + raise OdrError("an explicit model needs response data") + self.set_job(fit_type=1) + + if x_s[-1] != y_s[-1]: + raise OdrError("number of observations do not match") + + n = x_s[-1] + + if len(x_s) == 2: + m = x_s[0] + else: + m = 1 + if len(y_s) == 2: + q = y_s[0] + else: + q = 1 + + p = len(self.beta0) + + # permissible output array shapes + + fcn_perms = [(q, n)] + fjacd_perms = [(q, m, n)] + fjacb_perms = [(q, p, n)] + + if q == 1: + fcn_perms.append((n,)) + fjacd_perms.append((m, n)) + fjacb_perms.append((p, n)) + if m == 1: + fjacd_perms.append((q, n)) + if p == 1: + fjacb_perms.append((q, n)) + if m == q == 1: + fjacd_perms.append((n,)) + if p == q == 1: + fjacb_perms.append((n,)) + + # try evaluating the supplied functions to make sure they provide + # sensible outputs + + arglist = (self.beta0, self.data.x) + if self.model.extra_args is not None: + arglist = arglist + self.model.extra_args + res = self.model.fcn(*arglist) + + if res.shape not in fcn_perms: + print(res.shape) + print(fcn_perms) + raise OdrError(f"fcn does not output {y_s}-shaped array") + + if self.model.fjacd is not None: + res = self.model.fjacd(*arglist) + if res.shape not in fjacd_perms: + raise OdrError( + f"fjacd does not output {repr((q, m, n))}-shaped array") + if self.model.fjacb is not None: + res = self.model.fjacb(*arglist) + if res.shape not in fjacb_perms: + raise OdrError( + f"fjacb does not output {repr((q, p, n))}-shaped array") + + # check shape of delta0 + + if self.delta0 is not None and self.delta0.shape != self.data.x.shape: + raise OdrError( + f"delta0 is not a {repr(self.data.x.shape)}-shaped array") + + if self.data.x.size == 0: + warn("Empty data detected for ODR instance. " + "Do not expect any fitting to occur", + OdrWarning, stacklevel=3) + + def _gen_work(self): + """ Generate a suitable work array if one does not already exist. + """ + + n = self.data.x.shape[-1] + p = self.beta0.shape[0] + + if len(self.data.x.shape) == 2: + m = self.data.x.shape[0] + else: + m = 1 + + if self.model.implicit: + q = self.data.y + elif len(self.data.y.shape) == 2: + q = self.data.y.shape[0] + else: + q = 1 + + if self.data.we is None: + ldwe = ld2we = 1 + elif len(self.data.we.shape) == 3: + ld2we, ldwe = self.data.we.shape[1:] + else: + we = self.data.we + ldwe = 1 + ld2we = 1 + if we.ndim == 1 and q == 1: + ldwe = n + elif we.ndim == 2: + if we.shape == (q, q): + ld2we = q + elif we.shape == (q, n): + ldwe = n + + if self.job % 10 < 2: + # ODR not OLS + lwork = (18 + 11*p + p*p + m + m*m + 4*n*q + 6*n*m + 2*n*q*p + + 2*n*q*m + q*q + 5*q + q*(p+m) + ldwe*ld2we*q) + else: + # OLS not ODR + lwork = (18 + 11*p + p*p + m + m*m + 4*n*q + 2*n*m + 2*n*q*p + + 5*q + q*(p+m) + ldwe*ld2we*q) + + if isinstance(self.work, np.ndarray) and self.work.shape == (lwork,)\ + and self.work.dtype.str.endswith('f8'): + # the existing array is fine + return + else: + self.work = np.zeros((lwork,), float) + + def set_job(self, fit_type=None, deriv=None, var_calc=None, + del_init=None, restart=None): + """ + Sets the "job" parameter is a hopefully comprehensible way. + + If an argument is not specified, then the value is left as is. The + default value from class initialization is for all of these options set + to 0. + + Parameters + ---------- + fit_type : {0, 1, 2} int + 0 -> explicit ODR + + 1 -> implicit ODR + + 2 -> ordinary least-squares + deriv : {0, 1, 2, 3} int + 0 -> forward finite differences + + 1 -> central finite differences + + 2 -> user-supplied derivatives (Jacobians) with results + checked by ODRPACK + + 3 -> user-supplied derivatives, no checking + var_calc : {0, 1, 2} int + 0 -> calculate asymptotic covariance matrix and fit + parameter uncertainties (V_B, s_B) using derivatives + recomputed at the final solution + + 1 -> calculate V_B and s_B using derivatives from last iteration + + 2 -> do not calculate V_B and s_B + del_init : {0, 1} int + 0 -> initial input variable offsets set to 0 + + 1 -> initial offsets provided by user in variable "work" + restart : {0, 1} int + 0 -> fit is not a restart + + 1 -> fit is a restart + + Notes + ----- + The permissible values are different from those given on pg. 31 of the + ODRPACK User's Guide only in that one cannot specify numbers greater than + the last value for each variable. + + If one does not supply functions to compute the Jacobians, the fitting + procedure will change deriv to 0, finite differences, as a default. To + initialize the input variable offsets by yourself, set del_init to 1 and + put the offsets into the "work" variable correctly. + + """ + + if self.job is None: + job_l = [0, 0, 0, 0, 0] + else: + job_l = [self.job // 10000 % 10, + self.job // 1000 % 10, + self.job // 100 % 10, + self.job // 10 % 10, + self.job % 10] + + if fit_type in (0, 1, 2): + job_l[4] = fit_type + if deriv in (0, 1, 2, 3): + job_l[3] = deriv + if var_calc in (0, 1, 2): + job_l[2] = var_calc + if del_init in (0, 1): + job_l[1] = del_init + if restart in (0, 1): + job_l[0] = restart + + self.job = (job_l[0]*10000 + job_l[1]*1000 + + job_l[2]*100 + job_l[3]*10 + job_l[4]) + + def set_iprint(self, init=None, so_init=None, + iter=None, so_iter=None, iter_step=None, final=None, so_final=None): + """ Set the iprint parameter for the printing of computation reports. + + If any of the arguments are specified here, then they are set in the + iprint member. If iprint is not set manually or with this method, then + ODRPACK defaults to no printing. If no filename is specified with the + member rptfile, then ODRPACK prints to stdout. One can tell ODRPACK to + print to stdout in addition to the specified filename by setting the + so_* arguments to this function, but one cannot specify to print to + stdout but not a file since one can do that by not specifying a rptfile + filename. + + There are three reports: initialization, iteration, and final reports. + They are represented by the arguments init, iter, and final + respectively. The permissible values are 0, 1, and 2 representing "no + report", "short report", and "long report" respectively. + + The argument iter_step (0 <= iter_step <= 9) specifies how often to make + the iteration report; the report will be made for every iter_step'th + iteration starting with iteration one. If iter_step == 0, then no + iteration report is made, regardless of the other arguments. + + If the rptfile is None, then any so_* arguments supplied will raise an + exception. + """ + if self.iprint is None: + self.iprint = 0 + + ip = [self.iprint // 1000 % 10, + self.iprint // 100 % 10, + self.iprint // 10 % 10, + self.iprint % 10] + + # make a list to convert iprint digits to/from argument inputs + # rptfile, stdout + ip2arg = [[0, 0], # none, none + [1, 0], # short, none + [2, 0], # long, none + [1, 1], # short, short + [2, 1], # long, short + [1, 2], # short, long + [2, 2]] # long, long + + if (self.rptfile is None and + (so_init is not None or + so_iter is not None or + so_final is not None)): + raise OdrError( + "no rptfile specified, cannot output to stdout twice") + + iprint_l = ip2arg[ip[0]] + ip2arg[ip[1]] + ip2arg[ip[3]] + + if init is not None: + iprint_l[0] = init + if so_init is not None: + iprint_l[1] = so_init + if iter is not None: + iprint_l[2] = iter + if so_iter is not None: + iprint_l[3] = so_iter + if final is not None: + iprint_l[4] = final + if so_final is not None: + iprint_l[5] = so_final + + if iter_step in range(10): + # 0..9 + ip[2] = iter_step + + ip[0] = ip2arg.index(iprint_l[0:2]) + ip[1] = ip2arg.index(iprint_l[2:4]) + ip[3] = ip2arg.index(iprint_l[4:6]) + + self.iprint = ip[0]*1000 + ip[1]*100 + ip[2]*10 + ip[3] + + def run(self): + """ Run the fitting routine with all of the information given and with ``full_output=1``. + + Returns + ------- + output : Output instance + This object is also assigned to the attribute .output . + """ # noqa: E501 + + args = (self.model.fcn, self.beta0, self.data.y, self.data.x) + kwds = {'full_output': 1} + kwd_l = ['ifixx', 'ifixb', 'job', 'iprint', 'errfile', 'rptfile', + 'ndigit', 'taufac', 'sstol', 'partol', 'maxit', 'stpb', + 'stpd', 'sclb', 'scld', 'work', 'iwork'] + + if self.delta0 is not None and (self.job // 10000) % 10 == 0: + # delta0 provided and fit is not a restart + self._gen_work() + + d0 = np.ravel(self.delta0) + + self.work[:len(d0)] = d0 + + # set the kwds from other objects explicitly + if self.model.fjacb is not None: + kwds['fjacb'] = self.model.fjacb + if self.model.fjacd is not None: + kwds['fjacd'] = self.model.fjacd + if self.data.we is not None: + kwds['we'] = self.data.we + if self.data.wd is not None: + kwds['wd'] = self.data.wd + if self.model.extra_args is not None: + kwds['extra_args'] = self.model.extra_args + + # implicitly set kwds from self's members + for attr in kwd_l: + obj = getattr(self, attr) + if obj is not None: + kwds[attr] = obj + + with ODR_LOCK: + self.output = Output(odr(*args, **kwds)) + + return self.output + + def restart(self, iter=None): + """ Restarts the run with iter more iterations. + + Parameters + ---------- + iter : int, optional + ODRPACK's default for the number of new iterations is 10. + + Returns + ------- + output : Output instance + This object is also assigned to the attribute .output . + """ + + if self.output is None: + raise OdrError("cannot restart: run() has not been called before") + + self.set_job(restart=1) + self.work = self.output.work + self.iwork = self.output.iwork + + self.maxit = iter + + return self.run() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/odr/models.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/odr/models.py new file mode 100644 index 0000000000000000000000000000000000000000..0289b59747bb68a4954e58732ac69d7df144f5f6 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/odr/models.py @@ -0,0 +1,20 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.odr` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__ = [ # noqa: F822 + 'Model', 'exponential', 'multilinear', 'unilinear', + 'quadratic', 'polynomial' +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="odr", module="models", + private_modules=["_models"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/odr/odrpack.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/odr/odrpack.py new file mode 100644 index 0000000000000000000000000000000000000000..192fb3342b7957703996957c882d44656706e41b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/odr/odrpack.py @@ -0,0 +1,21 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.odr` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__ = [ # noqa: F822 + 'odr', 'OdrWarning', 'OdrError', 'OdrStop', + 'Data', 'RealData', 'Model', 'Output', 'ODR', + 'odr_error', 'odr_stop' +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="odr", module="odrpack", + private_modules=["_odrpack"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/odr/tests/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/odr/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/odr/tests/test_odr.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/odr/tests/test_odr.py new file mode 100644 index 0000000000000000000000000000000000000000..971cce6c55a84e08a182e3b25bf9a7e362937e01 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/odr/tests/test_odr.py @@ -0,0 +1,607 @@ +import pickle +import tempfile +import shutil +import os + +import numpy as np +from numpy import pi +from numpy.testing import (assert_array_almost_equal, + assert_equal, assert_warns, + assert_allclose) +import pytest +from pytest import raises as assert_raises + +from scipy.odr import (Data, Model, ODR, RealData, OdrStop, OdrWarning, + multilinear, exponential, unilinear, quadratic, + polynomial) + + +class TestODR: + + # Bad Data for 'x' + + def test_bad_data(self): + assert_raises(ValueError, Data, 2, 1) + assert_raises(ValueError, RealData, 2, 1) + + # Empty Data for 'x' + def empty_data_func(self, B, x): + return B[0]*x + B[1] + + @pytest.mark.thread_unsafe + def test_empty_data(self): + beta0 = [0.02, 0.0] + linear = Model(self.empty_data_func) + + empty_dat = Data([], []) + assert_warns(OdrWarning, ODR, + empty_dat, linear, beta0=beta0) + + empty_dat = RealData([], []) + assert_warns(OdrWarning, ODR, + empty_dat, linear, beta0=beta0) + + # Explicit Example + + def explicit_fcn(self, B, x): + ret = B[0] + B[1] * np.power(np.exp(B[2]*x) - 1.0, 2) + return ret + + def explicit_fjd(self, B, x): + eBx = np.exp(B[2]*x) + ret = B[1] * 2.0 * (eBx-1.0) * B[2] * eBx + return ret + + def explicit_fjb(self, B, x): + eBx = np.exp(B[2]*x) + res = np.vstack([np.ones(x.shape[-1]), + np.power(eBx-1.0, 2), + B[1]*2.0*(eBx-1.0)*eBx*x]) + return res + + def test_explicit(self): + explicit_mod = Model( + self.explicit_fcn, + fjacb=self.explicit_fjb, + fjacd=self.explicit_fjd, + meta=dict(name='Sample Explicit Model', + ref='ODRPACK UG, pg. 39'), + ) + explicit_dat = Data([0.,0.,5.,7.,7.5,10.,16.,26.,30.,34.,34.5,100.], + [1265.,1263.6,1258.,1254.,1253.,1249.8,1237.,1218.,1220.6, + 1213.8,1215.5,1212.]) + explicit_odr = ODR(explicit_dat, explicit_mod, beta0=[1500.0, -50.0, -0.1], + ifixx=[0,0,1,1,1,1,1,1,1,1,1,0]) + explicit_odr.set_job(deriv=2) + explicit_odr.set_iprint(init=0, iter=0, final=0) + + out = explicit_odr.run() + assert_array_almost_equal( + out.beta, + np.array([1.2646548050648876e+03, -5.4018409956678255e+01, + -8.7849712165253724e-02]), + ) + assert_array_almost_equal( + out.sd_beta, + np.array([1.0349270280543437, 1.583997785262061, 0.0063321988657267]), + ) + assert_array_almost_equal( + out.cov_beta, + np.array([[4.4949592379003039e-01, -3.7421976890364739e-01, + -8.0978217468468912e-04], + [-3.7421976890364739e-01, 1.0529686462751804e+00, + -1.9453521827942002e-03], + [-8.0978217468468912e-04, -1.9453521827942002e-03, + 1.6827336938454476e-05]]), + ) + + # Implicit Example + + def implicit_fcn(self, B, x): + return (B[2]*np.power(x[0]-B[0], 2) + + 2.0*B[3]*(x[0]-B[0])*(x[1]-B[1]) + + B[4]*np.power(x[1]-B[1], 2) - 1.0) + + def test_implicit(self): + implicit_mod = Model( + self.implicit_fcn, + implicit=1, + meta=dict(name='Sample Implicit Model', + ref='ODRPACK UG, pg. 49'), + ) + implicit_dat = Data([ + [0.5,1.2,1.6,1.86,2.12,2.36,2.44,2.36,2.06,1.74,1.34,0.9,-0.28, + -0.78,-1.36,-1.9,-2.5,-2.88,-3.18,-3.44], + [-0.12,-0.6,-1.,-1.4,-2.54,-3.36,-4.,-4.75,-5.25,-5.64,-5.97,-6.32, + -6.44,-6.44,-6.41,-6.25,-5.88,-5.5,-5.24,-4.86]], + 1, + ) + implicit_odr = ODR(implicit_dat, implicit_mod, + beta0=[-1.0, -3.0, 0.09, 0.02, 0.08]) + + out = implicit_odr.run() + assert_array_almost_equal( + out.beta, + np.array([-0.9993809167281279, -2.9310484652026476, 0.0875730502693354, + 0.0162299708984738, 0.0797537982976416]), + ) + assert_array_almost_equal( + out.sd_beta, + np.array([0.1113840353364371, 0.1097673310686467, 0.0041060738314314, + 0.0027500347539902, 0.0034962501532468]), + ) + assert_allclose( + out.cov_beta, + np.array([[2.1089274602333052e+00, -1.9437686411979040e+00, + 7.0263550868344446e-02, -4.7175267373474862e-02, + 5.2515575927380355e-02], + [-1.9437686411979040e+00, 2.0481509222414456e+00, + -6.1600515853057307e-02, 4.6268827806232933e-02, + -5.8822307501391467e-02], + [7.0263550868344446e-02, -6.1600515853057307e-02, + 2.8659542561579308e-03, -1.4628662260014491e-03, + 1.4528860663055824e-03], + [-4.7175267373474862e-02, 4.6268827806232933e-02, + -1.4628662260014491e-03, 1.2855592885514335e-03, + -1.2692942951415293e-03], + [5.2515575927380355e-02, -5.8822307501391467e-02, + 1.4528860663055824e-03, -1.2692942951415293e-03, + 2.0778813389755596e-03]]), + rtol=1e-6, atol=2e-6, + ) + + # Multi-variable Example + + def multi_fcn(self, B, x): + if (x < 0.0).any(): + raise OdrStop + theta = pi*B[3]/2. + ctheta = np.cos(theta) + stheta = np.sin(theta) + omega = np.power(2.*pi*x*np.exp(-B[2]), B[3]) + phi = np.arctan2((omega*stheta), (1.0 + omega*ctheta)) + r = (B[0] - B[1]) * np.power(np.sqrt(np.power(1.0 + omega*ctheta, 2) + + np.power(omega*stheta, 2)), -B[4]) + ret = np.vstack([B[1] + r*np.cos(B[4]*phi), + r*np.sin(B[4]*phi)]) + return ret + + def test_multi(self): + multi_mod = Model( + self.multi_fcn, + meta=dict(name='Sample Multi-Response Model', + ref='ODRPACK UG, pg. 56'), + ) + + multi_x = np.array([30.0, 50.0, 70.0, 100.0, 150.0, 200.0, 300.0, 500.0, + 700.0, 1000.0, 1500.0, 2000.0, 3000.0, 5000.0, 7000.0, 10000.0, + 15000.0, 20000.0, 30000.0, 50000.0, 70000.0, 100000.0, 150000.0]) + multi_y = np.array([ + [4.22, 4.167, 4.132, 4.038, 4.019, 3.956, 3.884, 3.784, 3.713, + 3.633, 3.54, 3.433, 3.358, 3.258, 3.193, 3.128, 3.059, 2.984, + 2.934, 2.876, 2.838, 2.798, 2.759], + [0.136, 0.167, 0.188, 0.212, 0.236, 0.257, 0.276, 0.297, 0.309, + 0.311, 0.314, 0.311, 0.305, 0.289, 0.277, 0.255, 0.24, 0.218, + 0.202, 0.182, 0.168, 0.153, 0.139], + ]) + n = len(multi_x) + multi_we = np.zeros((2, 2, n), dtype=float) + multi_ifixx = np.ones(n, dtype=int) + multi_delta = np.zeros(n, dtype=float) + + multi_we[0,0,:] = 559.6 + multi_we[1,0,:] = multi_we[0,1,:] = -1634.0 + multi_we[1,1,:] = 8397.0 + + for i in range(n): + if multi_x[i] < 100.0: + multi_ifixx[i] = 0 + elif multi_x[i] <= 150.0: + pass # defaults are fine + elif multi_x[i] <= 1000.0: + multi_delta[i] = 25.0 + elif multi_x[i] <= 10000.0: + multi_delta[i] = 560.0 + elif multi_x[i] <= 100000.0: + multi_delta[i] = 9500.0 + else: + multi_delta[i] = 144000.0 + if multi_x[i] == 100.0 or multi_x[i] == 150.0: + multi_we[:,:,i] = 0.0 + + multi_dat = Data(multi_x, multi_y, wd=1e-4/np.power(multi_x, 2), + we=multi_we) + multi_odr = ODR(multi_dat, multi_mod, beta0=[4.,2.,7.,.4,.5], + delta0=multi_delta, ifixx=multi_ifixx) + multi_odr.set_job(deriv=1, del_init=1) + + out = multi_odr.run() + assert_array_almost_equal( + out.beta, + np.array([4.3799880305938963, 2.4333057577497703, 8.0028845899503978, + 0.5101147161764654, 0.5173902330489161]), + ) + assert_array_almost_equal( + out.sd_beta, + np.array([0.0130625231081944, 0.0130499785273277, 0.1167085962217757, + 0.0132642749596149, 0.0288529201353984]), + ) + assert_array_almost_equal( + out.cov_beta, + np.array([[0.0064918418231375, 0.0036159705923791, 0.0438637051470406, + -0.0058700836512467, 0.011281212888768], + [0.0036159705923791, 0.0064793789429006, 0.0517610978353126, + -0.0051181304940204, 0.0130726943624117], + [0.0438637051470406, 0.0517610978353126, 0.5182263323095322, + -0.0563083340093696, 0.1269490939468611], + [-0.0058700836512467, -0.0051181304940204, -0.0563083340093696, + 0.0066939246261263, -0.0140184391377962], + [0.011281212888768, 0.0130726943624117, 0.1269490939468611, + -0.0140184391377962, 0.0316733013820852]]), + ) + + # Pearson's Data + # K. Pearson, Philosophical Magazine, 2, 559 (1901) + + def pearson_fcn(self, B, x): + return B[0] + B[1]*x + + def test_pearson(self): + p_x = np.array([0.,.9,1.8,2.6,3.3,4.4,5.2,6.1,6.5,7.4]) + p_y = np.array([5.9,5.4,4.4,4.6,3.5,3.7,2.8,2.8,2.4,1.5]) + p_sx = np.array([.03,.03,.04,.035,.07,.11,.13,.22,.74,1.]) + p_sy = np.array([1.,.74,.5,.35,.22,.22,.12,.12,.1,.04]) + + p_dat = RealData(p_x, p_y, sx=p_sx, sy=p_sy) + + # Reverse the data to test invariance of results + pr_dat = RealData(p_y, p_x, sx=p_sy, sy=p_sx) + + p_mod = Model(self.pearson_fcn, meta=dict(name='Uni-linear Fit')) + + p_odr = ODR(p_dat, p_mod, beta0=[1.,1.]) + pr_odr = ODR(pr_dat, p_mod, beta0=[1.,1.]) + + out = p_odr.run() + assert_array_almost_equal( + out.beta, + np.array([5.4767400299231674, -0.4796082367610305]), + ) + assert_array_almost_equal( + out.sd_beta, + np.array([0.3590121690702467, 0.0706291186037444]), + ) + assert_array_almost_equal( + out.cov_beta, + np.array([[0.0854275622946333, -0.0161807025443155], + [-0.0161807025443155, 0.003306337993922]]), + ) + + rout = pr_odr.run() + assert_array_almost_equal( + rout.beta, + np.array([11.4192022410781231, -2.0850374506165474]), + ) + assert_array_almost_equal( + rout.sd_beta, + np.array([0.9820231665657161, 0.3070515616198911]), + ) + assert_array_almost_equal( + rout.cov_beta, + np.array([[0.6391799462548782, -0.1955657291119177], + [-0.1955657291119177, 0.0624888159223392]]), + ) + + # Lorentz Peak + # The data is taken from one of the undergraduate physics labs I performed. + + def lorentz(self, beta, x): + return (beta[0]*beta[1]*beta[2] / np.sqrt(np.power(x*x - + beta[2]*beta[2], 2.0) + np.power(beta[1]*x, 2.0))) + + def test_lorentz(self): + l_sy = np.array([.29]*18) + l_sx = np.array([.000972971,.000948268,.000707632,.000706679, + .000706074, .000703918,.000698955,.000456856, + .000455207,.000662717,.000654619,.000652694, + .000000859202,.00106589,.00106378,.00125483, .00140818,.00241839]) + + l_dat = RealData( + [3.9094, 3.85945, 3.84976, 3.84716, 3.84551, 3.83964, 3.82608, + 3.78847, 3.78163, 3.72558, 3.70274, 3.6973, 3.67373, 3.65982, + 3.6562, 3.62498, 3.55525, 3.41886], + [652, 910.5, 984, 1000, 1007.5, 1053, 1160.5, 1409.5, 1430, 1122, + 957.5, 920, 777.5, 709.5, 698, 578.5, 418.5, 275.5], + sx=l_sx, + sy=l_sy, + ) + l_mod = Model(self.lorentz, meta=dict(name='Lorentz Peak')) + l_odr = ODR(l_dat, l_mod, beta0=(1000., .1, 3.8)) + + out = l_odr.run() + assert_array_almost_equal( + out.beta, + np.array([1.4306780846149925e+03, 1.3390509034538309e-01, + 3.7798193600109009e+00]), + ) + assert_array_almost_equal( + out.sd_beta, + np.array([7.3621186811330963e-01, 3.5068899941471650e-04, + 2.4451209281408992e-04]), + ) + assert_array_almost_equal( + out.cov_beta, + np.array([[2.4714409064597873e-01, -6.9067261911110836e-05, + -3.1236953270424990e-05], + [-6.9067261911110836e-05, 5.6077531517333009e-08, + 3.6133261832722601e-08], + [-3.1236953270424990e-05, 3.6133261832722601e-08, + 2.7261220025171730e-08]]), + ) + + def test_ticket_1253(self): + def linear(c, x): + return c[0]*x+c[1] + + c = [2.0, 3.0] + x = np.linspace(0, 10) + y = linear(c, x) + + model = Model(linear) + data = Data(x, y, wd=1.0, we=1.0) + job = ODR(data, model, beta0=[1.0, 1.0]) + result = job.run() + assert_equal(result.info, 2) + + # Verify fix for gh-9140 + + def test_ifixx(self): + x1 = [-2.01, -0.99, -0.001, 1.02, 1.98] + x2 = [3.98, 1.01, 0.001, 0.998, 4.01] + fix = np.vstack((np.zeros_like(x1, dtype=int), np.ones_like(x2, dtype=int))) + data = Data(np.vstack((x1, x2)), y=1, fix=fix) + model = Model(lambda beta, x: x[1, :] - beta[0] * x[0, :]**2., implicit=True) + + odr1 = ODR(data, model, beta0=np.array([1.])) + sol1 = odr1.run() + odr2 = ODR(data, model, beta0=np.array([1.]), ifixx=fix) + sol2 = odr2.run() + assert_equal(sol1.beta, sol2.beta) + + # verify bugfix for #11800 in #11802 + def test_ticket_11800(self): + # parameters + beta_true = np.array([1.0, 2.3, 1.1, -1.0, 1.3, 0.5]) + nr_measurements = 10 + + std_dev_x = 0.01 + x_error = np.array([[0.00063445, 0.00515731, 0.00162719, 0.01022866, + -0.01624845, 0.00482652, 0.00275988, -0.00714734, -0.00929201, -0.00687301], + [-0.00831623, -0.00821211, -0.00203459, 0.00938266, -0.00701829, + 0.0032169, 0.00259194, -0.00581017, -0.0030283, 0.01014164]]) + + std_dev_y = 0.05 + y_error = np.array([[0.05275304, 0.04519563, -0.07524086, 0.03575642, + 0.04745194, 0.03806645, 0.07061601, -0.00753604, -0.02592543, -0.02394929], + [0.03632366, 0.06642266, 0.08373122, 0.03988822, -0.0092536, + -0.03750469, -0.03198903, 0.01642066, 0.01293648, -0.05627085]]) + + beta_solution = np.array([ + 2.62920235756665876536e+00, -1.26608484996299608838e+02, + 1.29703572775403074502e+02, -1.88560985401185465804e+00, + 7.83834160771274923718e+01, -7.64124076838087091801e+01]) + + # model's function and Jacobians + def func(beta, x): + y0 = beta[0] + beta[1] * x[0, :] + beta[2] * x[1, :] + y1 = beta[3] + beta[4] * x[0, :] + beta[5] * x[1, :] + + return np.vstack((y0, y1)) + + def df_dbeta_odr(beta, x): + nr_meas = np.shape(x)[1] + zeros = np.zeros(nr_meas) + ones = np.ones(nr_meas) + + dy0 = np.array([ones, x[0, :], x[1, :], zeros, zeros, zeros]) + dy1 = np.array([zeros, zeros, zeros, ones, x[0, :], x[1, :]]) + + return np.stack((dy0, dy1)) + + def df_dx_odr(beta, x): + nr_meas = np.shape(x)[1] + ones = np.ones(nr_meas) + + dy0 = np.array([beta[1] * ones, beta[2] * ones]) + dy1 = np.array([beta[4] * ones, beta[5] * ones]) + return np.stack((dy0, dy1)) + + # do measurements with errors in independent and dependent variables + x0_true = np.linspace(1, 10, nr_measurements) + x1_true = np.linspace(1, 10, nr_measurements) + x_true = np.array([x0_true, x1_true]) + + y_true = func(beta_true, x_true) + + x_meas = x_true + x_error + y_meas = y_true + y_error + + # estimate model's parameters + model_f = Model(func, fjacb=df_dbeta_odr, fjacd=df_dx_odr) + + data = RealData(x_meas, y_meas, sx=std_dev_x, sy=std_dev_y) + + odr_obj = ODR(data, model_f, beta0=0.9 * beta_true, maxit=100) + #odr_obj.set_iprint(init=2, iter=0, iter_step=1, final=1) + odr_obj.set_job(deriv=3) + + odr_out = odr_obj.run() + + # check results + assert_equal(odr_out.info, 1) + assert_array_almost_equal(odr_out.beta, beta_solution) + + def test_multilinear_model(self): + x = np.linspace(0.0, 5.0) + y = 10.0 + 5.0 * x + data = Data(x, y) + odr_obj = ODR(data, multilinear) + output = odr_obj.run() + assert_array_almost_equal(output.beta, [10.0, 5.0]) + + def test_exponential_model(self): + x = np.linspace(0.0, 5.0) + y = -10.0 + np.exp(0.5*x) + data = Data(x, y) + odr_obj = ODR(data, exponential) + output = odr_obj.run() + assert_array_almost_equal(output.beta, [-10.0, 0.5]) + + def test_polynomial_model(self): + x = np.linspace(0.0, 5.0) + y = 1.0 + 2.0 * x + 3.0 * x ** 2 + 4.0 * x ** 3 + poly_model = polynomial(3) + data = Data(x, y) + odr_obj = ODR(data, poly_model) + output = odr_obj.run() + assert_array_almost_equal(output.beta, [1.0, 2.0, 3.0, 4.0]) + + def test_unilinear_model(self): + x = np.linspace(0.0, 5.0) + y = 1.0 * x + 2.0 + data = Data(x, y) + odr_obj = ODR(data, unilinear) + output = odr_obj.run() + assert_array_almost_equal(output.beta, [1.0, 2.0]) + + def test_quadratic_model(self): + x = np.linspace(0.0, 5.0) + y = 1.0 * x ** 2 + 2.0 * x + 3.0 + data = Data(x, y) + odr_obj = ODR(data, quadratic) + output = odr_obj.run() + assert_array_almost_equal(output.beta, [1.0, 2.0, 3.0]) + + def test_work_ind(self): + + def func(par, x): + b0, b1 = par + return b0 + b1 * x + + # generate some data + n_data = 4 + x = np.arange(n_data) + y = np.where(x % 2, x + 0.1, x - 0.1) + x_err = np.full(n_data, 0.1) + y_err = np.full(n_data, 0.1) + + # do the fitting + linear_model = Model(func) + real_data = RealData(x, y, sx=x_err, sy=y_err) + odr_obj = ODR(real_data, linear_model, beta0=[0.4, 0.4]) + odr_obj.set_job(fit_type=0) + out = odr_obj.run() + + sd_ind = out.work_ind['sd'] + assert_array_almost_equal(out.sd_beta, + out.work[sd_ind:sd_ind + len(out.sd_beta)]) + + @pytest.mark.skipif(True, reason="Fortran I/O prone to crashing so better " + "not to run this test, see gh-13127") + def test_output_file_overwrite(self): + """ + Verify fix for gh-1892 + """ + def func(b, x): + return b[0] + b[1] * x + + p = Model(func) + data = Data(np.arange(10), 12 * np.arange(10)) + tmp_dir = tempfile.mkdtemp() + error_file_path = os.path.join(tmp_dir, "error.dat") + report_file_path = os.path.join(tmp_dir, "report.dat") + try: + ODR(data, p, beta0=[0.1, 13], errfile=error_file_path, + rptfile=report_file_path).run() + ODR(data, p, beta0=[0.1, 13], errfile=error_file_path, + rptfile=report_file_path, overwrite=True).run() + finally: + # remove output files for clean up + shutil.rmtree(tmp_dir) + + def test_odr_model_default_meta(self): + def func(b, x): + return b[0] + b[1] * x + + p = Model(func) + p.set_meta(name='Sample Model Meta', ref='ODRPACK') + assert_equal(p.meta, {'name': 'Sample Model Meta', 'ref': 'ODRPACK'}) + + def test_work_array_del_init(self): + """ + Verify fix for gh-18739 where del_init=1 fails. + """ + def func(b, x): + return b[0] + b[1] * x + + # generate some data + n_data = 4 + x = np.arange(n_data) + y = np.where(x % 2, x + 0.1, x - 0.1) + x_err = np.full(n_data, 0.1) + y_err = np.full(n_data, 0.1) + + linear_model = Model(func) + # Try various shapes of the `we` array from various `sy` and `covy` + rd0 = RealData(x, y, sx=x_err, sy=y_err) + rd1 = RealData(x, y, sx=x_err, sy=0.1) + rd2 = RealData(x, y, sx=x_err, sy=[0.1]) + rd3 = RealData(x, y, sx=x_err, sy=np.full((1, n_data), 0.1)) + rd4 = RealData(x, y, sx=x_err, covy=[[0.01]]) + rd5 = RealData(x, y, sx=x_err, covy=np.full((1, 1, n_data), 0.01)) + for rd in [rd0, rd1, rd2, rd3, rd4, rd5]: + odr_obj = ODR(rd, linear_model, beta0=[0.4, 0.4], + delta0=np.full(n_data, -0.1)) + odr_obj.set_job(fit_type=0, del_init=1) + # Just make sure that it runs without raising an exception. + odr_obj.run() + + def test_pickling_data(self): + x = np.linspace(0.0, 5.0) + y = 1.0 * x + 2.0 + data = Data(x, y) + + obj_pickle = pickle.dumps(data) + del data + pickle.loads(obj_pickle) + + def test_pickling_real_data(self): + x = np.linspace(0.0, 5.0) + y = 1.0 * x + 2.0 + data = RealData(x, y) + + obj_pickle = pickle.dumps(data) + del data + pickle.loads(obj_pickle) + + def test_pickling_model(self): + obj_pickle = pickle.dumps(unilinear) + pickle.loads(obj_pickle) + + def test_pickling_odr(self): + x = np.linspace(0.0, 5.0) + y = 1.0 * x + 2.0 + odr_obj = ODR(Data(x, y), unilinear) + + obj_pickle = pickle.dumps(odr_obj) + del odr_obj + pickle.loads(obj_pickle) + + def test_pickling_output(self): + x = np.linspace(0.0, 5.0) + y = 1.0 * x + 2.0 + output = ODR(Data(x, y), unilinear).run + + obj_pickle = pickle.dumps(output) + del output + pickle.loads(obj_pickle) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/__init__.pxd b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/__init__.pxd new file mode 100644 index 0000000000000000000000000000000000000000..2402eeb020d34ad8b82e287e32545423911ff66c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/__init__.pxd @@ -0,0 +1 @@ +from .optimize cimport cython_optimize diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fce4cecd22b165f9975160fe7c1ed718ed358853 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/__init__.py @@ -0,0 +1,460 @@ +""" +===================================================== +Optimization and root finding (:mod:`scipy.optimize`) +===================================================== + +.. currentmodule:: scipy.optimize + +.. toctree:: + :hidden: + + optimize.cython_optimize + +SciPy ``optimize`` provides functions for minimizing (or maximizing) +objective functions, possibly subject to constraints. It includes +solvers for nonlinear problems (with support for both local and global +optimization algorithms), linear programming, constrained +and nonlinear least-squares, root finding, and curve fitting. + +Common functions and objects, shared across different solvers, are: + +.. autosummary:: + :toctree: generated/ + + show_options - Show specific options optimization solvers. + OptimizeResult - The optimization result returned by some optimizers. + OptimizeWarning - The optimization encountered problems. + + +Optimization +============ + +Scalar functions optimization +----------------------------- + +.. autosummary:: + :toctree: generated/ + + minimize_scalar - Interface for minimizers of univariate functions + +The `minimize_scalar` function supports the following methods: + +.. toctree:: + + optimize.minimize_scalar-brent + optimize.minimize_scalar-bounded + optimize.minimize_scalar-golden + +Local (multivariate) optimization +--------------------------------- + +.. autosummary:: + :toctree: generated/ + + minimize - Interface for minimizers of multivariate functions. + +The `minimize` function supports the following methods: + +.. toctree:: + + optimize.minimize-neldermead + optimize.minimize-powell + optimize.minimize-cg + optimize.minimize-bfgs + optimize.minimize-newtoncg + optimize.minimize-lbfgsb + optimize.minimize-tnc + optimize.minimize-cobyla + optimize.minimize-cobyqa + optimize.minimize-slsqp + optimize.minimize-trustconstr + optimize.minimize-dogleg + optimize.minimize-trustncg + optimize.minimize-trustkrylov + optimize.minimize-trustexact + +Constraints are passed to `minimize` function as a single object or +as a list of objects from the following classes: + +.. autosummary:: + :toctree: generated/ + + NonlinearConstraint - Class defining general nonlinear constraints. + LinearConstraint - Class defining general linear constraints. + +Simple bound constraints are handled separately and there is a special class +for them: + +.. autosummary:: + :toctree: generated/ + + Bounds - Bound constraints. + +Quasi-Newton strategies implementing `HessianUpdateStrategy` +interface can be used to approximate the Hessian in `minimize` +function (available only for the 'trust-constr' method). Available +quasi-Newton methods implementing this interface are: + +.. autosummary:: + :toctree: generated/ + + BFGS - Broyden-Fletcher-Goldfarb-Shanno (BFGS) Hessian update strategy. + SR1 - Symmetric-rank-1 Hessian update strategy. + +.. _global_optimization: + +Global optimization +------------------- + +.. autosummary:: + :toctree: generated/ + + basinhopping - Basinhopping stochastic optimizer. + brute - Brute force searching optimizer. + differential_evolution - Stochastic optimizer using differential evolution. + + shgo - Simplicial homology global optimizer. + dual_annealing - Dual annealing stochastic optimizer. + direct - DIRECT (Dividing Rectangles) optimizer. + +Least-squares and curve fitting +=============================== + +Nonlinear least-squares +----------------------- + +.. autosummary:: + :toctree: generated/ + + least_squares - Solve a nonlinear least-squares problem with bounds on the variables. + +Linear least-squares +-------------------- + +.. autosummary:: + :toctree: generated/ + + nnls - Linear least-squares problem with non-negativity constraint. + lsq_linear - Linear least-squares problem with bound constraints. + isotonic_regression - Least squares problem of isotonic regression via PAVA. + +Curve fitting +------------- + +.. autosummary:: + :toctree: generated/ + + curve_fit -- Fit curve to a set of points. + +Root finding +============ + +Scalar functions +---------------- +.. autosummary:: + :toctree: generated/ + + root_scalar - Unified interface for nonlinear solvers of scalar functions. + brentq - quadratic interpolation Brent method. + brenth - Brent method, modified by Harris with hyperbolic extrapolation. + ridder - Ridder's method. + bisect - Bisection method. + newton - Newton's method (also Secant and Halley's methods). + toms748 - Alefeld, Potra & Shi Algorithm 748. + RootResults - The root finding result returned by some root finders. + +The `root_scalar` function supports the following methods: + +.. toctree:: + + optimize.root_scalar-brentq + optimize.root_scalar-brenth + optimize.root_scalar-bisect + optimize.root_scalar-ridder + optimize.root_scalar-newton + optimize.root_scalar-toms748 + optimize.root_scalar-secant + optimize.root_scalar-halley + + + +The table below lists situations and appropriate methods, along with +*asymptotic* convergence rates per iteration (and per function evaluation) +for successful convergence to a simple root(*). +Bisection is the slowest of them all, adding one bit of accuracy for each +function evaluation, but is guaranteed to converge. +The other bracketing methods all (eventually) increase the number of accurate +bits by about 50% for every function evaluation. +The derivative-based methods, all built on `newton`, can converge quite quickly +if the initial value is close to the root. They can also be applied to +functions defined on (a subset of) the complex plane. + ++-------------+----------+----------+-----------+-------------+-------------+----------------+ +| Domain of f | Bracket? | Derivatives? | Solvers | Convergence | ++ + +----------+-----------+ +-------------+----------------+ +| | | `fprime` | `fprime2` | | Guaranteed? | Rate(s)(*) | ++=============+==========+==========+===========+=============+=============+================+ +| `R` | Yes | N/A | N/A | - bisection | - Yes | - 1 "Linear" | +| | | | | - brentq | - Yes | - >=1, <= 1.62 | +| | | | | - brenth | - Yes | - >=1, <= 1.62 | +| | | | | - ridder | - Yes | - 2.0 (1.41) | +| | | | | - toms748 | - Yes | - 2.7 (1.65) | ++-------------+----------+----------+-----------+-------------+-------------+----------------+ +| `R` or `C` | No | No | No | secant | No | 1.62 (1.62) | ++-------------+----------+----------+-----------+-------------+-------------+----------------+ +| `R` or `C` | No | Yes | No | newton | No | 2.00 (1.41) | ++-------------+----------+----------+-----------+-------------+-------------+----------------+ +| `R` or `C` | No | Yes | Yes | halley | No | 3.00 (1.44) | ++-------------+----------+----------+-----------+-------------+-------------+----------------+ + +.. seealso:: + + `scipy.optimize.cython_optimize` -- Typed Cython versions of root finding functions + +Fixed point finding: + +.. autosummary:: + :toctree: generated/ + + fixed_point - Single-variable fixed-point solver. + +Multidimensional +---------------- + +.. autosummary:: + :toctree: generated/ + + root - Unified interface for nonlinear solvers of multivariate functions. + +The `root` function supports the following methods: + +.. toctree:: + + optimize.root-hybr + optimize.root-lm + optimize.root-broyden1 + optimize.root-broyden2 + optimize.root-anderson + optimize.root-linearmixing + optimize.root-diagbroyden + optimize.root-excitingmixing + optimize.root-krylov + optimize.root-dfsane + +Elementwise Minimization and Root Finding +========================================= + +.. toctree:: + :maxdepth: 3 + + optimize.elementwise + +Linear programming / MILP +========================= + +.. autosummary:: + :toctree: generated/ + + milp -- Mixed integer linear programming. + linprog -- Unified interface for minimizers of linear programming problems. + +The `linprog` function supports the following methods: + +.. toctree:: + + optimize.linprog-simplex + optimize.linprog-interior-point + optimize.linprog-revised_simplex + optimize.linprog-highs-ipm + optimize.linprog-highs-ds + optimize.linprog-highs + +The simplex, interior-point, and revised simplex methods support callback +functions, such as: + +.. autosummary:: + :toctree: generated/ + + linprog_verbose_callback -- Sample callback function for linprog (simplex). + +Assignment problems +=================== + +.. autosummary:: + :toctree: generated/ + + linear_sum_assignment -- Solves the linear-sum assignment problem. + quadratic_assignment -- Solves the quadratic assignment problem. + +The `quadratic_assignment` function supports the following methods: + +.. toctree:: + + optimize.qap-faq + optimize.qap-2opt + +Utilities +========= + +Finite-difference approximation +------------------------------- + +.. autosummary:: + :toctree: generated/ + + approx_fprime - Approximate the gradient of a scalar function. + check_grad - Check the supplied derivative using finite differences. + + +Line search +----------- + +.. autosummary:: + :toctree: generated/ + + bracket - Bracket a minimum, given two starting points. + line_search - Return a step that satisfies the strong Wolfe conditions. + +Hessian approximation +--------------------- + +.. autosummary:: + :toctree: generated/ + + LbfgsInvHessProduct - Linear operator for L-BFGS approximate inverse Hessian. + HessianUpdateStrategy - Interface for implementing Hessian update strategies + +Benchmark problems +------------------ + +.. autosummary:: + :toctree: generated/ + + rosen - The Rosenbrock function. + rosen_der - The derivative of the Rosenbrock function. + rosen_hess - The Hessian matrix of the Rosenbrock function. + rosen_hess_prod - Product of the Rosenbrock Hessian with a vector. + +Legacy functions +================ + +The functions below are not recommended for use in new scripts; +all of these methods are accessible via a newer, more consistent +interfaces, provided by the interfaces above. + +Optimization +------------ + +General-purpose multivariate methods: + +.. autosummary:: + :toctree: generated/ + + fmin - Nelder-Mead Simplex algorithm. + fmin_powell - Powell's (modified) conjugate direction method. + fmin_cg - Non-linear (Polak-Ribiere) conjugate gradient algorithm. + fmin_bfgs - Quasi-Newton method (Broydon-Fletcher-Goldfarb-Shanno). + fmin_ncg - Line-search Newton Conjugate Gradient. + +Constrained multivariate methods: + +.. autosummary:: + :toctree: generated/ + + fmin_l_bfgs_b - Zhu, Byrd, and Nocedal's constrained optimizer. + fmin_tnc - Truncated Newton code. + fmin_cobyla - Constrained optimization by linear approximation. + fmin_slsqp - Minimization using sequential least-squares programming. + +Univariate (scalar) minimization methods: + +.. autosummary:: + :toctree: generated/ + + fminbound - Bounded minimization of a scalar function. + brent - 1-D function minimization using Brent method. + golden - 1-D function minimization using Golden Section method. + +Least-squares +------------- + +.. autosummary:: + :toctree: generated/ + + leastsq - Minimize the sum of squares of M equations in N unknowns. + +Root finding +------------ + +General nonlinear solvers: + +.. autosummary:: + :toctree: generated/ + + fsolve - Non-linear multivariable equation solver. + broyden1 - Broyden's first method. + broyden2 - Broyden's second method. + NoConvergence - Exception raised when nonlinear solver does not converge. + +Large-scale nonlinear solvers: + +.. autosummary:: + :toctree: generated/ + + newton_krylov + anderson + + BroydenFirst + InverseJacobian + KrylovJacobian + +Simple iteration solvers: + +.. autosummary:: + :toctree: generated/ + + excitingmixing + linearmixing + diagbroyden + +""" # noqa: E501 + +from ._optimize import * +from ._minimize import * +from ._root import * +from ._root_scalar import * +from ._minpack_py import * +from ._zeros_py import * +from ._lbfgsb_py import fmin_l_bfgs_b, LbfgsInvHessProduct +from ._tnc import fmin_tnc +from ._cobyla_py import fmin_cobyla +from ._nonlin import * +from ._slsqp_py import fmin_slsqp +from ._nnls import nnls +from ._basinhopping import basinhopping +from ._linprog import linprog, linprog_verbose_callback +from ._lsap import linear_sum_assignment +from ._differentialevolution import differential_evolution +from ._lsq import least_squares, lsq_linear +from ._isotonic import isotonic_regression +from ._constraints import (NonlinearConstraint, + LinearConstraint, + Bounds) +from ._hessian_update_strategy import HessianUpdateStrategy, BFGS, SR1 +from ._shgo import shgo +from ._dual_annealing import dual_annealing +from ._qap import quadratic_assignment +from ._direct_py import direct +from ._milp import milp + +# Deprecated namespaces, to be removed in v2.0.0 +from . import ( + cobyla, lbfgsb, linesearch, minpack, minpack2, moduleTNC, nonlin, optimize, + slsqp, tnc, zeros +) + +__all__ = [s for s in dir() if not s.startswith('_')] + +from scipy._lib._testutils import PytestTester +test = PytestTester(__name__) +del PytestTester diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_basinhopping.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_basinhopping.py new file mode 100644 index 0000000000000000000000000000000000000000..90498155887fc45ba0748c0d798bda17caef39f0 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_basinhopping.py @@ -0,0 +1,735 @@ +""" +basinhopping: The basinhopping global optimization algorithm +""" +import numpy as np +import math +import inspect +import scipy.optimize +from scipy._lib._util import check_random_state, _transition_to_rng + +__all__ = ['basinhopping'] + + +_params = (inspect.Parameter('res_new', kind=inspect.Parameter.KEYWORD_ONLY), + inspect.Parameter('res_old', kind=inspect.Parameter.KEYWORD_ONLY)) +_new_accept_test_signature = inspect.Signature(parameters=_params) + + +class Storage: + """ + Class used to store the lowest energy structure + """ + def __init__(self, minres): + self._add(minres) + + def _add(self, minres): + self.minres = minres + self.minres.x = np.copy(minres.x) + + def update(self, minres): + if minres.success and (minres.fun < self.minres.fun + or not self.minres.success): + self._add(minres) + return True + else: + return False + + def get_lowest(self): + return self.minres + + +class BasinHoppingRunner: + """This class implements the core of the basinhopping algorithm. + + x0 : ndarray + The starting coordinates. + minimizer : callable + The local minimizer, with signature ``result = minimizer(x)``. + The return value is an `optimize.OptimizeResult` object. + step_taking : callable + This function displaces the coordinates randomly. Signature should + be ``x_new = step_taking(x)``. Note that `x` may be modified in-place. + accept_tests : list of callables + Each test is passed the kwargs `f_new`, `x_new`, `f_old` and + `x_old`. These tests will be used to judge whether or not to accept + the step. The acceptable return values are True, False, or ``"force + accept"``. If any of the tests return False then the step is rejected. + If ``"force accept"``, then this will override any other tests in + order to accept the step. This can be used, for example, to forcefully + escape from a local minimum that ``basinhopping`` is trapped in. + disp : bool, optional + Display status messages. + + """ + def __init__(self, x0, minimizer, step_taking, accept_tests, disp=False): + self.x = np.copy(x0) + self.minimizer = minimizer + self.step_taking = step_taking + self.accept_tests = accept_tests + self.disp = disp + + self.nstep = 0 + + # initialize return object + self.res = scipy.optimize.OptimizeResult() + self.res.minimization_failures = 0 + + # do initial minimization + minres = minimizer(self.x) + if not minres.success: + self.res.minimization_failures += 1 + if self.disp: + print("warning: basinhopping: local minimization failure") + self.x = np.copy(minres.x) + self.energy = minres.fun + self.incumbent_minres = minres # best minimize result found so far + if self.disp: + print("basinhopping step %d: f %g" % (self.nstep, self.energy)) + + # initialize storage class + self.storage = Storage(minres) + + if hasattr(minres, "nfev"): + self.res.nfev = minres.nfev + if hasattr(minres, "njev"): + self.res.njev = minres.njev + if hasattr(minres, "nhev"): + self.res.nhev = minres.nhev + + def _monte_carlo_step(self): + """Do one Monte Carlo iteration + + Randomly displace the coordinates, minimize, and decide whether + or not to accept the new coordinates. + """ + # Take a random step. Make a copy of x because the step_taking + # algorithm might change x in place + x_after_step = np.copy(self.x) + x_after_step = self.step_taking(x_after_step) + + # do a local minimization + minres = self.minimizer(x_after_step) + x_after_quench = minres.x + energy_after_quench = minres.fun + if not minres.success: + self.res.minimization_failures += 1 + if self.disp: + print("warning: basinhopping: local minimization failure") + if hasattr(minres, "nfev"): + self.res.nfev += minres.nfev + if hasattr(minres, "njev"): + self.res.njev += minres.njev + if hasattr(minres, "nhev"): + self.res.nhev += minres.nhev + + # accept the move based on self.accept_tests. If any test is False, + # then reject the step. If any test returns the special string + # 'force accept', then accept the step regardless. This can be used + # to forcefully escape from a local minimum if normal basin hopping + # steps are not sufficient. + accept = True + for test in self.accept_tests: + if inspect.signature(test) == _new_accept_test_signature: + testres = test(res_new=minres, res_old=self.incumbent_minres) + else: + testres = test(f_new=energy_after_quench, x_new=x_after_quench, + f_old=self.energy, x_old=self.x) + + if testres == 'force accept': + accept = True + break + elif testres is None: + raise ValueError("accept_tests must return True, False, or " + "'force accept'") + elif not testres: + accept = False + + # Report the result of the acceptance test to the take step class. + # This is for adaptive step taking + if hasattr(self.step_taking, "report"): + self.step_taking.report(accept, f_new=energy_after_quench, + x_new=x_after_quench, f_old=self.energy, + x_old=self.x) + + return accept, minres + + def one_cycle(self): + """Do one cycle of the basinhopping algorithm + """ + self.nstep += 1 + new_global_min = False + + accept, minres = self._monte_carlo_step() + + if accept: + self.energy = minres.fun + self.x = np.copy(minres.x) + self.incumbent_minres = minres # best minimize result found so far + new_global_min = self.storage.update(minres) + + # print some information + if self.disp: + self.print_report(minres.fun, accept) + if new_global_min: + print("found new global minimum on step %d with function" + " value %g" % (self.nstep, self.energy)) + + # save some variables as BasinHoppingRunner attributes + self.xtrial = minres.x + self.energy_trial = minres.fun + self.accept = accept + + return new_global_min + + def print_report(self, energy_trial, accept): + """print a status update""" + minres = self.storage.get_lowest() + print("basinhopping step %d: f %g trial_f %g accepted %d " + " lowest_f %g" % (self.nstep, self.energy, energy_trial, + accept, minres.fun)) + + +class AdaptiveStepsize: + """ + Class to implement adaptive stepsize. + + This class wraps the step taking class and modifies the stepsize to + ensure the true acceptance rate is as close as possible to the target. + + Parameters + ---------- + takestep : callable + The step taking routine. Must contain modifiable attribute + takestep.stepsize + accept_rate : float, optional + The target step acceptance rate + interval : int, optional + Interval for how often to update the stepsize + factor : float, optional + The step size is multiplied or divided by this factor upon each + update. + verbose : bool, optional + Print information about each update + + """ + def __init__(self, takestep, accept_rate=0.5, interval=50, factor=0.9, + verbose=True): + self.takestep = takestep + self.target_accept_rate = accept_rate + self.interval = interval + self.factor = factor + self.verbose = verbose + + self.nstep = 0 + self.nstep_tot = 0 + self.naccept = 0 + + def __call__(self, x): + return self.take_step(x) + + def _adjust_step_size(self): + old_stepsize = self.takestep.stepsize + accept_rate = float(self.naccept) / self.nstep + if accept_rate > self.target_accept_rate: + # We're accepting too many steps. This generally means we're + # trapped in a basin. Take bigger steps. + self.takestep.stepsize /= self.factor + else: + # We're not accepting enough steps. Take smaller steps. + self.takestep.stepsize *= self.factor + if self.verbose: + print(f"adaptive stepsize: acceptance rate {accept_rate:f} target " + f"{self.target_accept_rate:f} new stepsize " + f"{self.takestep.stepsize:g} old stepsize {old_stepsize:g}") + + def take_step(self, x): + self.nstep += 1 + self.nstep_tot += 1 + if self.nstep % self.interval == 0: + self._adjust_step_size() + return self.takestep(x) + + def report(self, accept, **kwargs): + "called by basinhopping to report the result of the step" + if accept: + self.naccept += 1 + + +class RandomDisplacement: + """Add a random displacement of maximum size `stepsize` to each coordinate. + + Calling this updates `x` in-place. + + Parameters + ---------- + stepsize : float, optional + Maximum stepsize in any dimension + rng : {None, int, `numpy.random.Generator`}, optional + Random number generator + """ + + def __init__(self, stepsize=0.5, rng=None): + self.stepsize = stepsize + self.rng = check_random_state(rng) + + def __call__(self, x): + x += self.rng.uniform(-self.stepsize, self.stepsize, + np.shape(x)) + return x + + +class MinimizerWrapper: + """ + wrap a minimizer function as a minimizer class + """ + def __init__(self, minimizer, func=None, **kwargs): + self.minimizer = minimizer + self.func = func + self.kwargs = kwargs + + def __call__(self, x0): + if self.func is None: + return self.minimizer(x0, **self.kwargs) + else: + return self.minimizer(self.func, x0, **self.kwargs) + + +class Metropolis: + """Metropolis acceptance criterion. + + Parameters + ---------- + T : float + The "temperature" parameter for the accept or reject criterion. + rng : {None, int, `numpy.random.Generator`}, optional + Random number generator used for acceptance test. + + """ + + def __init__(self, T, rng=None): + # Avoid ZeroDivisionError since "MBH can be regarded as a special case + # of the BH framework with the Metropolis criterion, where temperature + # T = 0." (Reject all steps that increase energy.) + self.beta = 1.0 / T if T != 0 else float('inf') + self.rng = check_random_state(rng) + + def accept_reject(self, res_new, res_old): + """ + Assuming the local search underlying res_new was successful: + If new energy is lower than old, it will always be accepted. + If new is higher than old, there is a chance it will be accepted, + less likely for larger differences. + """ + with np.errstate(invalid='ignore'): + # The energy values being fed to Metropolis are 1-length arrays, and if + # they are equal, their difference is 0, which gets multiplied by beta, + # which is inf, and array([0]) * float('inf') causes + # + # RuntimeWarning: invalid value encountered in multiply + # + # Ignore this warning so when the algorithm is on a flat plane, it always + # accepts the step, to try to move off the plane. + prod = -(res_new.fun - res_old.fun) * self.beta + w = math.exp(min(0, prod)) + + rand = self.rng.uniform() + return w >= rand and (res_new.success or not res_old.success) + + def __call__(self, *, res_new, res_old): + """ + f_new and f_old are mandatory in kwargs + """ + return bool(self.accept_reject(res_new, res_old)) + + +@_transition_to_rng("seed", position_num=12, replace_doc=True) +def basinhopping(func, x0, niter=100, T=1.0, stepsize=0.5, + minimizer_kwargs=None, take_step=None, accept_test=None, + callback=None, interval=50, disp=False, niter_success=None, + rng=None, *, target_accept_rate=0.5, stepwise_factor=0.9): + """Find the global minimum of a function using the basin-hopping algorithm. + + Basin-hopping is a two-phase method that combines a global stepping + algorithm with local minimization at each step. Designed to mimic + the natural process of energy minimization of clusters of atoms, it works + well for similar problems with "funnel-like, but rugged" energy landscapes + [5]_. + + As the step-taking, step acceptance, and minimization methods are all + customizable, this function can also be used to implement other two-phase + methods. + + Parameters + ---------- + func : callable ``f(x, *args)`` + Function to be optimized. ``args`` can be passed as an optional item + in the dict `minimizer_kwargs` + x0 : array_like + Initial guess. + niter : integer, optional + The number of basin-hopping iterations. There will be a total of + ``niter + 1`` runs of the local minimizer. + T : float, optional + The "temperature" parameter for the acceptance or rejection criterion. + Higher "temperatures" mean that larger jumps in function value will be + accepted. For best results `T` should be comparable to the + separation (in function value) between local minima. + stepsize : float, optional + Maximum step size for use in the random displacement. + minimizer_kwargs : dict, optional + Extra keyword arguments to be passed to the local minimizer + `scipy.optimize.minimize` Some important options could be: + + method : str + The minimization method (e.g. ``"L-BFGS-B"``) + args : tuple + Extra arguments passed to the objective function (`func`) and + its derivatives (Jacobian, Hessian). + + take_step : callable ``take_step(x)``, optional + Replace the default step-taking routine with this routine. The default + step-taking routine is a random displacement of the coordinates, but + other step-taking algorithms may be better for some systems. + `take_step` can optionally have the attribute ``take_step.stepsize``. + If this attribute exists, then `basinhopping` will adjust + ``take_step.stepsize`` in order to try to optimize the global minimum + search. + accept_test : callable, ``accept_test(f_new=f_new, x_new=x_new, f_old=fold, x_old=x_old)``, optional + Define a test which will be used to judge whether to accept the + step. This will be used in addition to the Metropolis test based on + "temperature" `T`. The acceptable return values are True, + False, or ``"force accept"``. If any of the tests return False + then the step is rejected. If the latter, then this will override any + other tests in order to accept the step. This can be used, for example, + to forcefully escape from a local minimum that `basinhopping` is + trapped in. + callback : callable, ``callback(x, f, accept)``, optional + A callback function which will be called for all minima found. ``x`` + and ``f`` are the coordinates and function value of the trial minimum, + and ``accept`` is whether that minimum was accepted. This can + be used, for example, to save the lowest N minima found. Also, + `callback` can be used to specify a user defined stop criterion by + optionally returning True to stop the `basinhopping` routine. + interval : integer, optional + interval for how often to update the `stepsize` + disp : bool, optional + Set to True to print status messages + niter_success : integer, optional + Stop the run if the global minimum candidate remains the same for this + number of iterations. + rng : `numpy.random.Generator`, optional + Pseudorandom number generator state. When `rng` is None, a new + `numpy.random.Generator` is created using entropy from the + operating system. Types other than `numpy.random.Generator` are + passed to `numpy.random.default_rng` to instantiate a ``Generator``. + + The random numbers generated only affect the default Metropolis + `accept_test` and the default `take_step`. If you supply your own + `take_step` and `accept_test`, and these functions use random + number generation, then those functions are responsible for the state + of their random number generator. + target_accept_rate : float, optional + The target acceptance rate that is used to adjust the `stepsize`. + If the current acceptance rate is greater than the target, + then the `stepsize` is increased. Otherwise, it is decreased. + Range is (0, 1). Default is 0.5. + + .. versionadded:: 1.8.0 + + stepwise_factor : float, optional + The `stepsize` is multiplied or divided by this stepwise factor upon + each update. Range is (0, 1). Default is 0.9. + + .. versionadded:: 1.8.0 + + Returns + ------- + res : OptimizeResult + The optimization result represented as a `OptimizeResult` object. + Important attributes are: ``x`` the solution array, ``fun`` the value + of the function at the solution, and ``message`` which describes the + cause of the termination. The ``OptimizeResult`` object returned by the + selected minimizer at the lowest minimum is also contained within this + object and can be accessed through the ``lowest_optimization_result`` + attribute. See `OptimizeResult` for a description of other attributes. + + See Also + -------- + minimize : + The local minimization function called once for each basinhopping step. + `minimizer_kwargs` is passed to this routine. + + Notes + ----- + Basin-hopping is a stochastic algorithm which attempts to find the global + minimum of a smooth scalar function of one or more variables [1]_ [2]_ [3]_ + [4]_. The algorithm in its current form was described by David Wales and + Jonathan Doye [2]_ http://www-wales.ch.cam.ac.uk/. + + The algorithm is iterative with each cycle composed of the following + features + + 1) random perturbation of the coordinates + + 2) local minimization + + 3) accept or reject the new coordinates based on the minimized function + value + + The acceptance test used here is the Metropolis criterion of standard Monte + Carlo algorithms, although there are many other possibilities [3]_. + + This global minimization method has been shown to be extremely efficient + for a wide variety of problems in physics and chemistry. It is + particularly useful when the function has many minima separated by large + barriers. See the `Cambridge Cluster Database + `_ for databases of molecular + systems that have been optimized primarily using basin-hopping. This + database includes minimization problems exceeding 300 degrees of freedom. + + See the free software program `GMIN `_ + for a Fortran implementation of basin-hopping. This implementation has many + variations of the procedure described above, including more + advanced step taking algorithms and alternate acceptance criterion. + + For stochastic global optimization there is no way to determine if the true + global minimum has actually been found. Instead, as a consistency check, + the algorithm can be run from a number of different random starting points + to ensure the lowest minimum found in each example has converged to the + global minimum. For this reason, `basinhopping` will by default simply + run for the number of iterations `niter` and return the lowest minimum + found. It is left to the user to ensure that this is in fact the global + minimum. + + Choosing `stepsize`: This is a crucial parameter in `basinhopping` and + depends on the problem being solved. The step is chosen uniformly in the + region from x0-stepsize to x0+stepsize, in each dimension. Ideally, it + should be comparable to the typical separation (in argument values) between + local minima of the function being optimized. `basinhopping` will, by + default, adjust `stepsize` to find an optimal value, but this may take + many iterations. You will get quicker results if you set a sensible + initial value for ``stepsize``. + + Choosing `T`: The parameter `T` is the "temperature" used in the + Metropolis criterion. Basinhopping steps are always accepted if + ``func(xnew) < func(xold)``. Otherwise, they are accepted with + probability:: + + exp( -(func(xnew) - func(xold)) / T ) + + So, for best results, `T` should to be comparable to the typical + difference (in function values) between local minima. (The height of + "walls" between local minima is irrelevant.) + + If `T` is 0, the algorithm becomes Monotonic Basin-Hopping, in which all + steps that increase energy are rejected. + + .. versionadded:: 0.12.0 + + References + ---------- + .. [1] Wales, David J. 2003, Energy Landscapes, Cambridge University Press, + Cambridge, UK. + .. [2] Wales, D J, and Doye J P K, Global Optimization by Basin-Hopping and + the Lowest Energy Structures of Lennard-Jones Clusters Containing up to + 110 Atoms. Journal of Physical Chemistry A, 1997, 101, 5111. + .. [3] Li, Z. and Scheraga, H. A., Monte Carlo-minimization approach to the + multiple-minima problem in protein folding, Proc. Natl. Acad. Sci. USA, + 1987, 84, 6611. + .. [4] Wales, D. J. and Scheraga, H. A., Global optimization of clusters, + crystals, and biomolecules, Science, 1999, 285, 1368. + .. [5] Olson, B., Hashmi, I., Molloy, K., and Shehu1, A., Basin Hopping as + a General and Versatile Optimization Framework for the Characterization + of Biological Macromolecules, Advances in Artificial Intelligence, + Volume 2012 (2012), Article ID 674832, :doi:`10.1155/2012/674832` + + Examples + -------- + The following example is a 1-D minimization problem, with many + local minima superimposed on a parabola. + + >>> import numpy as np + >>> from scipy.optimize import basinhopping + >>> func = lambda x: np.cos(14.5 * x - 0.3) + (x + 0.2) * x + >>> x0 = [1.] + + Basinhopping, internally, uses a local minimization algorithm. We will use + the parameter `minimizer_kwargs` to tell basinhopping which algorithm to + use and how to set up that minimizer. This parameter will be passed to + `scipy.optimize.minimize`. + + >>> minimizer_kwargs = {"method": "BFGS"} + >>> ret = basinhopping(func, x0, minimizer_kwargs=minimizer_kwargs, + ... niter=200) + >>> # the global minimum is: + >>> ret.x, ret.fun + -0.1951, -1.0009 + + Next consider a 2-D minimization problem. Also, this time, we + will use gradient information to significantly speed up the search. + + >>> def func2d(x): + ... f = np.cos(14.5 * x[0] - 0.3) + (x[1] + 0.2) * x[1] + (x[0] + + ... 0.2) * x[0] + ... df = np.zeros(2) + ... df[0] = -14.5 * np.sin(14.5 * x[0] - 0.3) + 2. * x[0] + 0.2 + ... df[1] = 2. * x[1] + 0.2 + ... return f, df + + We'll also use a different local minimization algorithm. Also, we must tell + the minimizer that our function returns both energy and gradient (Jacobian). + + >>> minimizer_kwargs = {"method":"L-BFGS-B", "jac":True} + >>> x0 = [1.0, 1.0] + >>> ret = basinhopping(func2d, x0, minimizer_kwargs=minimizer_kwargs, + ... niter=200) + >>> print("global minimum: x = [%.4f, %.4f], f(x) = %.4f" % (ret.x[0], + ... ret.x[1], + ... ret.fun)) + global minimum: x = [-0.1951, -0.1000], f(x) = -1.0109 + + Here is an example using a custom step-taking routine. Imagine you want + the first coordinate to take larger steps than the rest of the coordinates. + This can be implemented like so: + + >>> class MyTakeStep: + ... def __init__(self, stepsize=0.5): + ... self.stepsize = stepsize + ... self.rng = np.random.default_rng() + ... def __call__(self, x): + ... s = self.stepsize + ... x[0] += self.rng.uniform(-2.*s, 2.*s) + ... x[1:] += self.rng.uniform(-s, s, x[1:].shape) + ... return x + + Since ``MyTakeStep.stepsize`` exists basinhopping will adjust the magnitude + of `stepsize` to optimize the search. We'll use the same 2-D function as + before + + >>> mytakestep = MyTakeStep() + >>> ret = basinhopping(func2d, x0, minimizer_kwargs=minimizer_kwargs, + ... niter=200, take_step=mytakestep) + >>> print("global minimum: x = [%.4f, %.4f], f(x) = %.4f" % (ret.x[0], + ... ret.x[1], + ... ret.fun)) + global minimum: x = [-0.1951, -0.1000], f(x) = -1.0109 + + Now, let's do an example using a custom callback function which prints the + value of every minimum found + + >>> def print_fun(x, f, accepted): + ... print("at minimum %.4f accepted %d" % (f, int(accepted))) + + We'll run it for only 10 basinhopping steps this time. + + >>> rng = np.random.default_rng() + >>> ret = basinhopping(func2d, x0, minimizer_kwargs=minimizer_kwargs, + ... niter=10, callback=print_fun, rng=rng) + at minimum 0.4159 accepted 1 + at minimum -0.4317 accepted 1 + at minimum -1.0109 accepted 1 + at minimum -0.9073 accepted 1 + at minimum -0.4317 accepted 0 + at minimum -0.1021 accepted 1 + at minimum -0.7425 accepted 1 + at minimum -0.9073 accepted 1 + at minimum -0.4317 accepted 0 + at minimum -0.7425 accepted 1 + at minimum -0.9073 accepted 1 + + The minimum at -1.0109 is actually the global minimum, found already on the + 8th iteration. + + """ # numpy/numpydoc#87 # noqa: E501 + if target_accept_rate <= 0. or target_accept_rate >= 1.: + raise ValueError('target_accept_rate has to be in range (0, 1)') + if stepwise_factor <= 0. or stepwise_factor >= 1.: + raise ValueError('stepwise_factor has to be in range (0, 1)') + + x0 = np.array(x0) + + # set up the np.random generator + rng = check_random_state(rng) + + # set up minimizer + if minimizer_kwargs is None: + minimizer_kwargs = dict() + wrapped_minimizer = MinimizerWrapper(scipy.optimize.minimize, func, + **minimizer_kwargs) + + # set up step-taking algorithm + if take_step is not None: + if not callable(take_step): + raise TypeError("take_step must be callable") + # if take_step.stepsize exists then use AdaptiveStepsize to control + # take_step.stepsize + if hasattr(take_step, "stepsize"): + take_step_wrapped = AdaptiveStepsize( + take_step, interval=interval, + accept_rate=target_accept_rate, + factor=stepwise_factor, + verbose=disp) + else: + take_step_wrapped = take_step + else: + # use default + displace = RandomDisplacement(stepsize=stepsize, rng=rng) + take_step_wrapped = AdaptiveStepsize(displace, interval=interval, + accept_rate=target_accept_rate, + factor=stepwise_factor, + verbose=disp) + + # set up accept tests + accept_tests = [] + if accept_test is not None: + if not callable(accept_test): + raise TypeError("accept_test must be callable") + accept_tests = [accept_test] + + # use default + metropolis = Metropolis(T, rng=rng) + accept_tests.append(metropolis) + + if niter_success is None: + niter_success = niter + 2 + + bh = BasinHoppingRunner(x0, wrapped_minimizer, take_step_wrapped, + accept_tests, disp=disp) + + # The wrapped minimizer is called once during construction of + # BasinHoppingRunner, so run the callback + if callable(callback): + callback(bh.storage.minres.x, bh.storage.minres.fun, True) + + # start main iteration loop + count, i = 0, 0 + message = ["requested number of basinhopping iterations completed" + " successfully"] + for i in range(niter): + new_global_min = bh.one_cycle() + + if callable(callback): + # should we pass a copy of x? + val = callback(bh.xtrial, bh.energy_trial, bh.accept) + if val is not None: + if val: + message = ["callback function requested stop early by" + "returning True"] + break + + count += 1 + if new_global_min: + count = 0 + elif count > niter_success: + message = ["success condition satisfied"] + break + + # prepare return object + res = bh.res + res.lowest_optimization_result = bh.storage.get_lowest() + res.x = np.copy(res.lowest_optimization_result.x) + res.fun = res.lowest_optimization_result.fun + res.message = message + res.nit = i + 1 + res.success = res.lowest_optimization_result.success + return res diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_bracket.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_bracket.py new file mode 100644 index 0000000000000000000000000000000000000000..263243c612d08ebdc9939cc892771b49ac766d0c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_bracket.py @@ -0,0 +1,713 @@ +import numpy as np +import scipy._lib._elementwise_iterative_method as eim +from scipy._lib._util import _RichResult +from scipy._lib._array_api import array_namespace, xp_ravel, xp_default_dtype + +_ELIMITS = -1 # used in _bracket_root +_ESTOPONESIDE = 2 # used in _bracket_root + +def _bracket_root_iv(func, xl0, xr0, xmin, xmax, factor, args, maxiter): + + if not callable(func): + raise ValueError('`func` must be callable.') + + if not np.iterable(args): + args = (args,) + + xp = array_namespace(xl0) + xl0 = xp.asarray(xl0)[()] + if (not xp.isdtype(xl0.dtype, "numeric") + or xp.isdtype(xl0.dtype, "complex floating")): + raise ValueError('`xl0` must be numeric and real.') + if not xp.isdtype(xl0.dtype, "real floating"): + xl0 = xp.asarray(xl0, dtype=xp_default_dtype(xp)) + + # If xr0 is not supplied, fill with a dummy value for the sake of + # broadcasting. We need to wait until xmax has been validated to + # compute the default value. + xr0_not_supplied = False + if xr0 is None: + xr0 = xp.nan + xr0_not_supplied = True + + xmin = -xp.inf if xmin is None else xmin + xmax = xp.inf if xmax is None else xmax + factor = 2. if factor is None else factor + xl0, xr0, xmin, xmax, factor = xp.broadcast_arrays( + xl0, xp.asarray(xr0), xp.asarray(xmin), xp.asarray(xmax), xp.asarray(factor)) + + if (not xp.isdtype(xr0.dtype, "numeric") + or xp.isdtype(xr0.dtype, "complex floating")): + raise ValueError('`xr0` must be numeric and real.') + + if (not xp.isdtype(xmin.dtype, "numeric") + or xp.isdtype(xmin.dtype, "complex floating")): + raise ValueError('`xmin` must be numeric and real.') + + if (not xp.isdtype(xmax.dtype, "numeric") + or xp.isdtype(xmax.dtype, "complex floating")): + raise ValueError('`xmax` must be numeric and real.') + + if (not xp.isdtype(factor.dtype, "numeric") + or xp.isdtype(factor.dtype, "complex floating")): + raise ValueError('`factor` must be numeric and real.') + if not xp.all(factor > 1): + raise ValueError('All elements of `factor` must be greater than 1.') + + # Calculate the default value of xr0 if a value has not been supplied. + # Be careful to ensure xr0 is not larger than xmax. + if xr0_not_supplied: + xr0 = xl0 + xp.minimum((xmax - xl0)/ 8, xp.asarray(1.0)) + xr0 = xp.astype(xr0, xl0.dtype, copy=False) + + maxiter = xp.asarray(maxiter) + message = '`maxiter` must be a non-negative integer.' + if (not xp.isdtype(maxiter.dtype, "numeric") or maxiter.shape != tuple() + or xp.isdtype(maxiter.dtype, "complex floating")): + raise ValueError(message) + maxiter_int = int(maxiter[()]) + if not maxiter == maxiter_int or maxiter < 0: + raise ValueError(message) + + return func, xl0, xr0, xmin, xmax, factor, args, maxiter, xp + + +def _bracket_root(func, xl0, xr0=None, *, xmin=None, xmax=None, factor=None, + args=(), maxiter=1000): + """Bracket the root of a monotonic scalar function of one variable + + This function works elementwise when `xl0`, `xr0`, `xmin`, `xmax`, `factor`, and + the elements of `args` are broadcastable arrays. + + Parameters + ---------- + func : callable + The function for which the root is to be bracketed. + The signature must be:: + + func(x: ndarray, *args) -> ndarray + + where each element of ``x`` is a finite real and ``args`` is a tuple, + which may contain an arbitrary number of arrays that are broadcastable + with `x`. ``func`` must be an elementwise function: each element + ``func(x)[i]`` must equal ``func(x[i])`` for all indices ``i``. + xl0, xr0: float array_like + Starting guess of bracket, which need not contain a root. If `xr0` is + not provided, ``xr0 = xl0 + 1``. Must be broadcastable with one another. + xmin, xmax : float array_like, optional + Minimum and maximum allowable endpoints of the bracket, inclusive. Must + be broadcastable with `xl0` and `xr0`. + factor : float array_like, default: 2 + The factor used to grow the bracket. See notes for details. + args : tuple, optional + Additional positional arguments to be passed to `func`. Must be arrays + broadcastable with `xl0`, `xr0`, `xmin`, and `xmax`. If the callable to be + bracketed requires arguments that are not broadcastable with these + arrays, wrap that callable with `func` such that `func` accepts + only `x` and broadcastable arrays. + maxiter : int, optional + The maximum number of iterations of the algorithm to perform. + + Returns + ------- + res : _RichResult + An instance of `scipy._lib._util._RichResult` with the following + attributes. The descriptions are written as though the values will be + scalars; however, if `func` returns an array, the outputs will be + arrays of the same shape. + + xl, xr : float + The lower and upper ends of the bracket, if the algorithm + terminated successfully. + fl, fr : float + The function value at the lower and upper ends of the bracket. + nfev : int + The number of function evaluations required to find the bracket. + This is distinct from the number of times `func` is *called* + because the function may evaluated at multiple points in a single + call. + nit : int + The number of iterations of the algorithm that were performed. + status : int + An integer representing the exit status of the algorithm. + + - ``0`` : The algorithm produced a valid bracket. + - ``-1`` : The bracket expanded to the allowable limits without finding a bracket. + - ``-2`` : The maximum number of iterations was reached. + - ``-3`` : A non-finite value was encountered. + - ``-4`` : Iteration was terminated by `callback`. + - ``-5``: The initial bracket does not satisfy `xmin <= xl0 < xr0 < xmax`. + - ``1`` : The algorithm is proceeding normally (in `callback` only). + - ``2`` : A bracket was found in the opposite search direction (in `callback` only). + + success : bool + ``True`` when the algorithm terminated successfully (status ``0``). + + Notes + ----- + This function generalizes an algorithm found in pieces throughout + `scipy.stats`. The strategy is to iteratively grow the bracket ``(l, r)`` + until ``func(l) < 0 < func(r)``. The bracket grows to the left as follows. + + - If `xmin` is not provided, the distance between `xl0` and `l` is iteratively + increased by `factor`. + - If `xmin` is provided, the distance between `xmin` and `l` is iteratively + decreased by `factor`. Note that this also *increases* the bracket size. + + Growth of the bracket to the right is analogous. + + Growth of the bracket in one direction stops when the endpoint is no longer + finite, the function value at the endpoint is no longer finite, or the + endpoint reaches its limiting value (`xmin` or `xmax`). Iteration terminates + when the bracket stops growing in both directions, the bracket surrounds + the root, or a root is found (accidentally). + + If two brackets are found - that is, a bracket is found on both sides in + the same iteration, the smaller of the two is returned. + If roots of the function are found, both `l` and `r` are set to the + leftmost root. + + """ # noqa: E501 + # Todo: + # - find bracket with sign change in specified direction + # - Add tolerance + # - allow factor < 1? + + callback = None # works; I just don't want to test it + temp = _bracket_root_iv(func, xl0, xr0, xmin, xmax, factor, args, maxiter) + func, xl0, xr0, xmin, xmax, factor, args, maxiter, xp = temp + + xs = (xl0, xr0) + temp = eim._initialize(func, xs, args) + func, xs, fs, args, shape, dtype, xp = temp # line split for PEP8 + xl0, xr0 = xs + xmin = xp_ravel(xp.astype(xp.broadcast_to(xmin, shape), dtype, copy=False), xp=xp) + xmax = xp_ravel(xp.astype(xp.broadcast_to(xmax, shape), dtype, copy=False), xp=xp) + invalid_bracket = ~((xmin <= xl0) & (xl0 < xr0) & (xr0 <= xmax)) + + # The approach is to treat the left and right searches as though they were + # (almost) totally independent one-sided bracket searches. (The interaction + # is considered when checking for termination and preparing the result + # object.) + # `x` is the "moving" end of the bracket + x = xp.concat(xs) + f = xp.concat(fs) + invalid_bracket = xp.concat((invalid_bracket, invalid_bracket)) + n = x.shape[0] // 2 + + # `x_last` is the previous location of the moving end of the bracket. If + # the signs of `f` and `f_last` are different, `x` and `x_last` form a + # bracket. + x_last = xp.concat((x[n:], x[:n])) + f_last = xp.concat((f[n:], f[:n])) + # `x0` is the "fixed" end of the bracket. + x0 = x_last + # We don't need to retain the corresponding function value, since the + # fixed end of the bracket is only needed to compute the new value of the + # moving end; it is never returned. + limit = xp.concat((xmin, xmax)) + + factor = xp_ravel(xp.broadcast_to(factor, shape), xp=xp) + factor = xp.astype(factor, dtype, copy=False) + factor = xp.concat((factor, factor)) + + active = xp.arange(2*n) + args = [xp.concat((arg, arg)) for arg in args] + + # This is needed due to inner workings of `eim._loop`. + # We're abusing it a tiny bit. + shape = shape + (2,) + + # `d` is for "distance". + # For searches without a limit, the distance between the fixed end of the + # bracket `x0` and the moving end `x` will grow by `factor` each iteration. + # For searches with a limit, the distance between the `limit` and moving + # end of the bracket `x` will shrink by `factor` each iteration. + i = xp.isinf(limit) + ni = ~i + d = xp.zeros_like(x) + d[i] = x[i] - x0[i] + d[ni] = limit[ni] - x[ni] + + status = xp.full_like(x, eim._EINPROGRESS, dtype=xp.int32) # in progress + status[invalid_bracket] = eim._EINPUTERR + nit, nfev = 0, 1 # one function evaluation per side performed above + + work = _RichResult(x=x, x0=x0, f=f, limit=limit, factor=factor, + active=active, d=d, x_last=x_last, f_last=f_last, + nit=nit, nfev=nfev, status=status, args=args, + xl=xp.nan, xr=xp.nan, fl=xp.nan, fr=xp.nan, n=n) + res_work_pairs = [('status', 'status'), ('xl', 'xl'), ('xr', 'xr'), + ('nit', 'nit'), ('nfev', 'nfev'), ('fl', 'fl'), + ('fr', 'fr'), ('x', 'x'), ('f', 'f'), + ('x_last', 'x_last'), ('f_last', 'f_last')] + + def pre_func_eval(work): + # Initialize moving end of bracket + x = xp.zeros_like(work.x) + + # Unlimited brackets grow by `factor` by increasing distance from fixed + # end to moving end. + i = xp.isinf(work.limit) # indices of unlimited brackets + work.d[i] *= work.factor[i] + x[i] = work.x0[i] + work.d[i] + + # Limited brackets grow by decreasing the distance from the limit to + # the moving end. + ni = ~i # indices of limited brackets + work.d[ni] /= work.factor[ni] + x[ni] = work.limit[ni] - work.d[ni] + + return x + + def post_func_eval(x, f, work): + # Keep track of the previous location of the moving end so that we can + # return a narrower bracket. (The alternative is to remember the + # original fixed end, but then the bracket would be wider than needed.) + work.x_last = work.x + work.f_last = work.f + work.x = x + work.f = f + + def check_termination(work): + # Condition 0: initial bracket is invalid + stop = (work.status == eim._EINPUTERR) + + # Condition 1: a valid bracket (or the root itself) has been found + sf = xp.sign(work.f) + sf_last = xp.sign(work.f_last) + i = ((sf_last == -sf) | (sf_last == 0) | (sf == 0)) & ~stop + work.status[i] = eim._ECONVERGED + stop[i] = True + + # Condition 2: the other side's search found a valid bracket. + # (If we just found a bracket with the rightward search, we can stop + # the leftward search, and vice-versa.) + # To do this, we need to set the status of the other side's search; + # this is tricky because `work.status` contains only the *active* + # elements, so we don't immediately know the index of the element we + # need to set - or even if it's still there. (That search may have + # terminated already, e.g. by reaching its `limit`.) + # To facilitate this, `work.active` contains a unit integer index of + # each search. Index `k` (`k < n)` and `k + n` correspond with a + # leftward and rightward search, respectively. Elements are removed + # from `work.active` just as they are removed from `work.status`, so + # we use `work.active` to help find the right location in + # `work.status`. + # Get the integer indices of the elements that can also stop + also_stop = (work.active[i] + work.n) % (2*work.n) + # Check whether they are still active. We want to find the indices + # in work.active where the associated values in work.active are + # contained in also_stop. xp.searchsorted let's us take advantage + # of work.active being sorted, but requires some hackery because + # searchsorted solves the separate but related problem of finding + # the indices where the values in also_stop should be added to + # maintain sorted order. + j = xp.searchsorted(work.active, also_stop) + # If the location exceeds the length of the `work.active`, they are + # not there. This happens when a value in also_stop is larger than + # the greatest value in work.active. This case needs special handling + # because we cannot simply check that also_stop == work.active[j]. + mask = j < work.active.shape[0] + # Note that we also have to use the mask to filter also_stop to ensure + # that also_stop and j will still have the same shape. + j, also_stop = j[mask], also_stop[mask] + j = j[also_stop == work.active[j]] + # Now convert these to boolean indices to use with `work.status`. + i = xp.zeros_like(stop) + i[j] = True # boolean indices of elements that can also stop + i = i & ~stop + work.status[i] = _ESTOPONESIDE + stop[i] = True + + # Condition 3: moving end of bracket reaches limit + i = (work.x == work.limit) & ~stop + work.status[i] = _ELIMITS + stop[i] = True + + # Condition 4: non-finite value encountered + i = ~(xp.isfinite(work.x) & xp.isfinite(work.f)) & ~stop + work.status[i] = eim._EVALUEERR + stop[i] = True + + return stop + + def post_termination_check(work): + pass + + def customize_result(res, shape): + n = res['x'].shape[0] // 2 + + # To avoid ambiguity, below we refer to `xl0`, the initial left endpoint + # as `a` and `xr0`, the initial right endpoint, as `b`. + # Because we treat the two one-sided searches as though they were + # independent, what we keep track of in `work` and what we want to + # return in `res` look quite different. Combine the results from the + # two one-sided searches before reporting the results to the user. + # - "a" refers to the leftward search (the moving end started at `a`) + # - "b" refers to the rightward search (the moving end started at `b`) + # - "l" refers to the left end of the bracket (closer to -oo) + # - "r" refers to the right end of the bracket (closer to +oo) + xal = res['x'][:n] + xar = res['x_last'][:n] + xbl = res['x_last'][n:] + xbr = res['x'][n:] + + fal = res['f'][:n] + far = res['f_last'][:n] + fbl = res['f_last'][n:] + fbr = res['f'][n:] + + # Initialize the brackets and corresponding function values to return + # to the user. Brackets may not be valid (e.g. there is no root, + # there weren't enough iterations, NaN encountered), but we still need + # to return something. One option would be all NaNs, but what I've + # chosen here is the left- and right-most points at which the function + # has been evaluated. This gives the user some information about what + # interval of the real line has been searched and shows that there is + # no sign change between the two ends. + xl = xp.asarray(xal, copy=True) + fl = xp.asarray(fal, copy=True) + xr = xp.asarray(xbr, copy=True) + fr = xp.asarray(fbr, copy=True) + + # `status` indicates whether the bracket is valid or not. If so, + # we want to adjust the bracket we return to be the narrowest possible + # given the points at which we evaluated the function. + # For example if bracket "a" is valid and smaller than bracket "b" OR + # if bracket "a" is valid and bracket "b" is not valid, we want to + # return bracket "a" (and vice versa). + sa = res['status'][:n] + sb = res['status'][n:] + + da = xar - xal + db = xbr - xbl + + i1 = ((da <= db) & (sa == 0)) | ((sa == 0) & (sb != 0)) + i2 = ((db <= da) & (sb == 0)) | ((sb == 0) & (sa != 0)) + + xr[i1] = xar[i1] + fr[i1] = far[i1] + xl[i2] = xbl[i2] + fl[i2] = fbl[i2] + + # Finish assembling the result object + res['xl'] = xl + res['xr'] = xr + res['fl'] = fl + res['fr'] = fr + + res['nit'] = xp.maximum(res['nit'][:n], res['nit'][n:]) + res['nfev'] = res['nfev'][:n] + res['nfev'][n:] + # If the status on one side is zero, the status is zero. In any case, + # report the status from one side only. + res['status'] = xp.where(sa == 0, sa, sb) + res['success'] = (res['status'] == 0) + + del res['x'] + del res['f'] + del res['x_last'] + del res['f_last'] + + return shape[:-1] + + return eim._loop(work, callback, shape, maxiter, func, args, dtype, + pre_func_eval, post_func_eval, check_termination, + post_termination_check, customize_result, res_work_pairs, + xp) + + +def _bracket_minimum_iv(func, xm0, xl0, xr0, xmin, xmax, factor, args, maxiter): + + if not callable(func): + raise ValueError('`func` must be callable.') + + if not np.iterable(args): + args = (args,) + + xp = array_namespace(xm0) + xm0 = xp.asarray(xm0)[()] + if (not xp.isdtype(xm0.dtype, "numeric") + or xp.isdtype(xm0.dtype, "complex floating")): + raise ValueError('`xm0` must be numeric and real.') + if not xp.isdtype(xm0.dtype, "real floating"): + xm0 = xp.asarray(xm0, dtype=xp_default_dtype(xp)) + + xmin = -xp.inf if xmin is None else xmin + xmax = xp.inf if xmax is None else xmax + + # If xl0 (xr0) is not supplied, fill with a dummy value for the sake + # of broadcasting. We need to wait until xmin (xmax) has been validated + # to compute the default values. + xl0_not_supplied = False + if xl0 is None: + xl0 = xp.nan + xl0_not_supplied = True + + xr0_not_supplied = False + if xr0 is None: + xr0 = xp.nan + xr0_not_supplied = True + + factor = 2.0 if factor is None else factor + xl0, xm0, xr0, xmin, xmax, factor = xp.broadcast_arrays( + xp.asarray(xl0), xm0, xp.asarray(xr0), xp.asarray(xmin), + xp.asarray(xmax), xp.asarray(factor) + ) + + if (not xp.isdtype(xl0.dtype, "numeric") + or xp.isdtype(xl0.dtype, "complex floating")): + raise ValueError('`xl0` must be numeric and real.') + + if (not xp.isdtype(xr0.dtype, "numeric") + or xp.isdtype(xr0.dtype, "complex floating")): + raise ValueError('`xr0` must be numeric and real.') + + if (not xp.isdtype(xmin.dtype, "numeric") + or xp.isdtype(xmin.dtype, "complex floating")): + raise ValueError('`xmin` must be numeric and real.') + + if (not xp.isdtype(xmax.dtype, "numeric") + or xp.isdtype(xmax.dtype, "complex floating")): + raise ValueError('`xmax` must be numeric and real.') + + if (not xp.isdtype(factor.dtype, "numeric") + or xp.isdtype(factor.dtype, "complex floating")): + raise ValueError('`factor` must be numeric and real.') + if not xp.all(factor > 1): + raise ValueError('All elements of `factor` must be greater than 1.') + + # Calculate default values of xl0 and/or xr0 if they have not been supplied + # by the user. We need to be careful to ensure xl0 and xr0 are not outside + # of (xmin, xmax). + if xl0_not_supplied: + xl0 = xm0 - xp.minimum((xm0 - xmin)/16, xp.asarray(0.5)) + xl0 = xp.astype(xl0, xm0.dtype, copy=False) + if xr0_not_supplied: + xr0 = xm0 + xp.minimum((xmax - xm0)/16, xp.asarray(0.5)) + xr0 = xp.astype(xr0, xm0.dtype, copy=False) + + maxiter = xp.asarray(maxiter) + message = '`maxiter` must be a non-negative integer.' + if (not xp.isdtype(maxiter.dtype, "numeric") or maxiter.shape != tuple() + or xp.isdtype(maxiter.dtype, "complex floating")): + raise ValueError(message) + maxiter_int = int(maxiter[()]) + if not maxiter == maxiter_int or maxiter < 0: + raise ValueError(message) + + return func, xm0, xl0, xr0, xmin, xmax, factor, args, maxiter, xp + + +def _bracket_minimum(func, xm0, *, xl0=None, xr0=None, xmin=None, xmax=None, + factor=None, args=(), maxiter=1000): + """Bracket the minimum of a unimodal scalar function of one variable + + This function works elementwise when `xm0`, `xl0`, `xr0`, `xmin`, `xmax`, + and the elements of `args` are broadcastable arrays. + + Parameters + ---------- + func : callable + The function for which the minimum is to be bracketed. + The signature must be:: + + func(x: ndarray, *args) -> ndarray + + where each element of ``x`` is a finite real and ``args`` is a tuple, + which may contain an arbitrary number of arrays that are broadcastable + with ``x``. `func` must be an elementwise function: each element + ``func(x)[i]`` must equal ``func(x[i])`` for all indices `i`. + xm0: float array_like + Starting guess for middle point of bracket. + xl0, xr0: float array_like, optional + Starting guesses for left and right endpoints of the bracket. Must be + broadcastable with one another and with `xm0`. + xmin, xmax : float array_like, optional + Minimum and maximum allowable endpoints of the bracket, inclusive. Must + be broadcastable with `xl0`, `xm0`, and `xr0`. + factor : float array_like, optional + Controls expansion of bracket endpoint in downhill direction. Works + differently in the cases where a limit is set in the downhill direction + with `xmax` or `xmin`. See Notes. + args : tuple, optional + Additional positional arguments to be passed to `func`. Must be arrays + broadcastable with `xl0`, `xm0`, `xr0`, `xmin`, and `xmax`. If the + callable to be bracketed requires arguments that are not broadcastable + with these arrays, wrap that callable with `func` such that `func` + accepts only ``x`` and broadcastable arrays. + maxiter : int, optional + The maximum number of iterations of the algorithm to perform. The number + of function evaluations is three greater than the number of iterations. + + Returns + ------- + res : _RichResult + An instance of `scipy._lib._util._RichResult` with the following + attributes. The descriptions are written as though the values will be + scalars; however, if `func` returns an array, the outputs will be + arrays of the same shape. + + xl, xm, xr : float + The left, middle, and right points of the bracket, if the algorithm + terminated successfully. + fl, fm, fr : float + The function value at the left, middle, and right points of the bracket. + nfev : int + The number of function evaluations required to find the bracket. + nit : int + The number of iterations of the algorithm that were performed. + status : int + An integer representing the exit status of the algorithm. + + - ``0`` : The algorithm produced a valid bracket. + - ``-1`` : The bracket expanded to the allowable limits. Assuming + unimodality, this implies the endpoint at the limit is a + minimizer. + - ``-2`` : The maximum number of iterations was reached. + - ``-3`` : A non-finite value was encountered. + - ``-4`` : ``None`` shall pass. + - ``-5`` : The initial bracket does not satisfy + `xmin <= xl0 < xm0 < xr0 <= xmax`. + + success : bool + ``True`` when the algorithm terminated successfully (status ``0``). + + Notes + ----- + Similar to `scipy.optimize.bracket`, this function seeks to find real + points ``xl < xm < xr`` such that ``f(xl) >= f(xm)`` and ``f(xr) >= f(xm)``, + where at least one of the inequalities is strict. Unlike `scipy.optimize.bracket`, + this function can operate in a vectorized manner on array input, so long as + the input arrays are broadcastable with each other. Also unlike + `scipy.optimize.bracket`, users may specify minimum and maximum endpoints + for the desired bracket. + + Given an initial trio of points ``xl = xl0``, ``xm = xm0``, ``xr = xr0``, + the algorithm checks if these points already give a valid bracket. If not, + a new endpoint, ``w`` is chosen in the "downhill" direction, ``xm`` becomes the new + opposite endpoint, and either `xl` or `xr` becomes the new middle point, + depending on which direction is downhill. The algorithm repeats from here. + + The new endpoint `w` is chosen differently depending on whether or not a + boundary `xmin` or `xmax` has been set in the downhill direction. Without + loss of generality, suppose the downhill direction is to the right, so that + ``f(xl) > f(xm) > f(xr)``. If there is no boundary to the right, then `w` + is chosen to be ``xr + factor * (xr - xm)`` where `factor` is controlled by + the user (defaults to 2.0) so that step sizes increase in geometric proportion. + If there is a boundary, `xmax` in this case, then `w` is chosen to be + ``xmax - (xmax - xr)/factor``, with steps slowing to a stop at + `xmax`. This cautious approach ensures that a minimum near but distinct from + the boundary isn't missed while also detecting whether or not the `xmax` is + a minimizer when `xmax` is reached after a finite number of steps. + """ # noqa: E501 + callback = None # works; I just don't want to test it + + temp = _bracket_minimum_iv(func, xm0, xl0, xr0, xmin, xmax, factor, args, maxiter) + func, xm0, xl0, xr0, xmin, xmax, factor, args, maxiter, xp = temp + + xs = (xl0, xm0, xr0) + temp = eim._initialize(func, xs, args) + func, xs, fs, args, shape, dtype, xp = temp + + xl0, xm0, xr0 = xs + fl0, fm0, fr0 = fs + xmin = xp.astype(xp.broadcast_to(xmin, shape), dtype, copy=False) + xmin = xp_ravel(xmin, xp=xp) + xmax = xp.astype(xp.broadcast_to(xmax, shape), dtype, copy=False) + xmax = xp_ravel(xmax, xp=xp) + invalid_bracket = ~((xmin <= xl0) & (xl0 < xm0) & (xm0 < xr0) & (xr0 <= xmax)) + # We will modify factor later on so make a copy. np.broadcast_to returns + # a read-only view. + factor = xp.astype(xp.broadcast_to(factor, shape), dtype, copy=True) + factor = xp_ravel(factor) + + # To simplify the logic, swap xl and xr if f(xl) < f(xr). We should always be + # marching downhill in the direction from xl to xr. + comp = fl0 < fr0 + xl0[comp], xr0[comp] = xr0[comp], xl0[comp] + fl0[comp], fr0[comp] = fr0[comp], fl0[comp] + # We only need the boundary in the direction we're traveling. + limit = xp.where(comp, xmin, xmax) + + unlimited = xp.isinf(limit) + limited = ~unlimited + step = xp.empty_like(xl0) + + step[unlimited] = (xr0[unlimited] - xm0[unlimited]) + step[limited] = (limit[limited] - xr0[limited]) + + # Step size is divided by factor for case where there is a limit. + factor[limited] = 1 / factor[limited] + + status = xp.full_like(xl0, eim._EINPROGRESS, dtype=xp.int32) + status[invalid_bracket] = eim._EINPUTERR + nit, nfev = 0, 3 + + work = _RichResult(xl=xl0, xm=xm0, xr=xr0, xr0=xr0, fl=fl0, fm=fm0, fr=fr0, + step=step, limit=limit, limited=limited, factor=factor, nit=nit, + nfev=nfev, status=status, args=args) + + res_work_pairs = [('status', 'status'), ('xl', 'xl'), ('xm', 'xm'), ('xr', 'xr'), + ('nit', 'nit'), ('nfev', 'nfev'), ('fl', 'fl'), ('fm', 'fm'), + ('fr', 'fr')] + + def pre_func_eval(work): + work.step *= work.factor + x = xp.empty_like(work.xr) + x[~work.limited] = work.xr0[~work.limited] + work.step[~work.limited] + x[work.limited] = work.limit[work.limited] - work.step[work.limited] + # Since the new bracket endpoint is calculated from an offset with the + # limit, it may be the case that the new endpoint equals the old endpoint, + # when the old endpoint is sufficiently close to the limit. We use the + # limit itself as the new endpoint in these cases. + x[work.limited] = xp.where( + x[work.limited] == work.xr[work.limited], + work.limit[work.limited], + x[work.limited], + ) + return x + + def post_func_eval(x, f, work): + work.xl, work.xm, work.xr = work.xm, work.xr, x + work.fl, work.fm, work.fr = work.fm, work.fr, f + + def check_termination(work): + # Condition 0: Initial bracket is invalid. + stop = (work.status == eim._EINPUTERR) + + # Condition 1: A valid bracket has been found. + i = ( + (work.fl >= work.fm) & (work.fr > work.fm) + | (work.fl > work.fm) & (work.fr >= work.fm) + ) & ~stop + work.status[i] = eim._ECONVERGED + stop[i] = True + + # Condition 2: Moving end of bracket reaches limit. + i = (work.xr == work.limit) & ~stop + work.status[i] = _ELIMITS + stop[i] = True + + # Condition 3: non-finite value encountered + i = ~(xp.isfinite(work.xr) & xp.isfinite(work.fr)) & ~stop + work.status[i] = eim._EVALUEERR + stop[i] = True + + return stop + + def post_termination_check(work): + pass + + def customize_result(res, shape): + # Reorder entries of xl and xr if they were swapped due to f(xl0) < f(xr0). + comp = res['xl'] > res['xr'] + res['xl'][comp], res['xr'][comp] = res['xr'][comp], res['xl'][comp] + res['fl'][comp], res['fr'][comp] = res['fr'][comp], res['fl'][comp] + return shape + + return eim._loop(work, callback, shape, + maxiter, func, args, dtype, + pre_func_eval, post_func_eval, + check_termination, post_termination_check, + customize_result, res_work_pairs, xp) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_chandrupatla.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_chandrupatla.py new file mode 100644 index 0000000000000000000000000000000000000000..5a4b70098919b9fba626bfecd5c1bcc559ab7702 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_chandrupatla.py @@ -0,0 +1,552 @@ +import math +import numpy as np +import scipy._lib._elementwise_iterative_method as eim +from scipy._lib._util import _RichResult +from scipy._lib._array_api import xp_sign, xp_copy, xp_take_along_axis + +# TODO: +# - (maybe?) don't use fancy indexing assignment +# - figure out how to replace the new `try`/`except`s + + +def _chandrupatla(func, a, b, *, args=(), xatol=None, xrtol=None, + fatol=None, frtol=0, maxiter=None, callback=None): + """Find the root of an elementwise function using Chandrupatla's algorithm. + + For each element of the output of `func`, `chandrupatla` seeks the scalar + root that makes the element 0. This function allows for `a`, `b`, and the + output of `func` to be of any broadcastable shapes. + + Parameters + ---------- + func : callable + The function whose root is desired. The signature must be:: + + func(x: ndarray, *args) -> ndarray + + where each element of ``x`` is a finite real and ``args`` is a tuple, + which may contain an arbitrary number of components of any type(s). + ``func`` must be an elementwise function: each element ``func(x)[i]`` + must equal ``func(x[i])`` for all indices ``i``. `_chandrupatla` + seeks an array ``x`` such that ``func(x)`` is an array of zeros. + a, b : array_like + The lower and upper bounds of the root of the function. Must be + broadcastable with one another. + args : tuple, optional + Additional positional arguments to be passed to `func`. + xatol, xrtol, fatol, frtol : float, optional + Absolute and relative tolerances on the root and function value. + See Notes for details. + maxiter : int, optional + The maximum number of iterations of the algorithm to perform. + The default is the maximum possible number of bisections within + the (normal) floating point numbers of the relevant dtype. + callback : callable, optional + An optional user-supplied function to be called before the first + iteration and after each iteration. + Called as ``callback(res)``, where ``res`` is a ``_RichResult`` + similar to that returned by `_chandrupatla` (but containing the current + iterate's values of all variables). If `callback` raises a + ``StopIteration``, the algorithm will terminate immediately and + `_chandrupatla` will return a result. + + Returns + ------- + res : _RichResult + An instance of `scipy._lib._util._RichResult` with the following + attributes. The descriptions are written as though the values will be + scalars; however, if `func` returns an array, the outputs will be + arrays of the same shape. + + x : float + The root of the function, if the algorithm terminated successfully. + nfev : int + The number of times the function was called to find the root. + nit : int + The number of iterations of Chandrupatla's algorithm performed. + status : int + An integer representing the exit status of the algorithm. + ``0`` : The algorithm converged to the specified tolerances. + ``-1`` : The algorithm encountered an invalid bracket. + ``-2`` : The maximum number of iterations was reached. + ``-3`` : A non-finite value was encountered. + ``-4`` : Iteration was terminated by `callback`. + ``1`` : The algorithm is proceeding normally (in `callback` only). + success : bool + ``True`` when the algorithm terminated successfully (status ``0``). + fun : float + The value of `func` evaluated at `x`. + xl, xr : float + The lower and upper ends of the bracket. + fl, fr : float + The function value at the lower and upper ends of the bracket. + + Notes + ----- + Implemented based on Chandrupatla's original paper [1]_. + + If ``xl`` and ``xr`` are the left and right ends of the bracket, + ``xmin = xl if abs(func(xl)) <= abs(func(xr)) else xr``, + and ``fmin0 = min(func(a), func(b))``, then the algorithm is considered to + have converged when ``abs(xr - xl) < xatol + abs(xmin) * xrtol`` or + ``fun(xmin) <= fatol + abs(fmin0) * frtol``. This is equivalent to the + termination condition described in [1]_ with ``xrtol = 4e-10``, + ``xatol = 1e-5``, and ``fatol = frtol = 0``. The default values are + ``xatol = 4*tiny``, ``xrtol = 4*eps``, ``frtol = 0``, and ``fatol = tiny``, + where ``eps`` and ``tiny`` are the precision and smallest normal number + of the result ``dtype`` of function inputs and outputs. + + References + ---------- + + .. [1] Chandrupatla, Tirupathi R. + "A new hybrid quadratic/bisection algorithm for finding the zero of a + nonlinear function without using derivatives". + Advances in Engineering Software, 28(3), 145-149. + https://doi.org/10.1016/s0965-9978(96)00051-8 + + See Also + -------- + brentq, brenth, ridder, bisect, newton + + Examples + -------- + >>> from scipy import optimize + >>> def f(x, c): + ... return x**3 - 2*x - c + >>> c = 5 + >>> res = optimize._chandrupatla._chandrupatla(f, 0, 3, args=(c,)) + >>> res.x + 2.0945514818937463 + + >>> c = [3, 4, 5] + >>> res = optimize._chandrupatla._chandrupatla(f, 0, 3, args=(c,)) + >>> res.x + array([1.8932892 , 2. , 2.09455148]) + + """ + res = _chandrupatla_iv(func, args, xatol, xrtol, + fatol, frtol, maxiter, callback) + func, args, xatol, xrtol, fatol, frtol, maxiter, callback = res + + # Initialization + temp = eim._initialize(func, (a, b), args) + func, xs, fs, args, shape, dtype, xp = temp + x1, x2 = xs + f1, f2 = fs + status = xp.full_like(x1, xp.asarray(eim._EINPROGRESS), + dtype=xp.int32) # in progress + nit, nfev = 0, 2 # two function evaluations performed above + finfo = xp.finfo(dtype) + xatol = 4*finfo.smallest_normal if xatol is None else xatol + xrtol = 4*finfo.eps if xrtol is None else xrtol + fatol = finfo.smallest_normal if fatol is None else fatol + frtol = frtol * xp.minimum(xp.abs(f1), xp.abs(f2)) + maxiter = (math.log2(finfo.max) - math.log2(finfo.smallest_normal) + if maxiter is None else maxiter) + work = _RichResult(x1=x1, f1=f1, x2=x2, f2=f2, x3=None, f3=None, t=0.5, + xatol=xatol, xrtol=xrtol, fatol=fatol, frtol=frtol, + nit=nit, nfev=nfev, status=status) + res_work_pairs = [('status', 'status'), ('x', 'xmin'), ('fun', 'fmin'), + ('nit', 'nit'), ('nfev', 'nfev'), ('xl', 'x1'), + ('fl', 'f1'), ('xr', 'x2'), ('fr', 'f2')] + + def pre_func_eval(work): + # [1] Figure 1 (first box) + x = work.x1 + work.t * (work.x2 - work.x1) + return x + + def post_func_eval(x, f, work): + # [1] Figure 1 (first diamond and boxes) + # Note: y/n are reversed in figure; compare to BASIC in appendix + work.x3, work.f3 = (xp.asarray(work.x2, copy=True), + xp.asarray(work.f2, copy=True)) + j = xp.sign(f) == xp.sign(work.f1) + nj = ~j + work.x3[j], work.f3[j] = work.x1[j], work.f1[j] + work.x2[nj], work.f2[nj] = work.x1[nj], work.f1[nj] + work.x1, work.f1 = x, f + + def check_termination(work): + # [1] Figure 1 (second diamond) + # Check for all terminal conditions and record statuses. + + # See [1] Section 4 (first two sentences) + i = xp.abs(work.f1) < xp.abs(work.f2) + work.xmin = xp.where(i, work.x1, work.x2) + work.fmin = xp.where(i, work.f1, work.f2) + stop = xp.zeros_like(work.x1, dtype=xp.bool) # termination condition met + + # If function value tolerance is met, report successful convergence, + # regardless of other conditions. Note that `frtol` has been redefined + # as `frtol = frtol * minimum(f1, f2)`, where `f1` and `f2` are the + # function evaluated at the original ends of the bracket. + i = xp.abs(work.fmin) <= work.fatol + work.frtol + work.status[i] = eim._ECONVERGED + stop[i] = True + + # If the bracket is no longer valid, report failure (unless a function + # tolerance is met, as detected above). + i = (xp_sign(work.f1) == xp_sign(work.f2)) & ~stop + NaN = xp.asarray(xp.nan, dtype=work.xmin.dtype) + work.xmin[i], work.fmin[i], work.status[i] = NaN, NaN, eim._ESIGNERR + stop[i] = True + + # If the abscissae are non-finite or either function value is NaN, + # report failure. + x_nonfinite = ~(xp.isfinite(work.x1) & xp.isfinite(work.x2)) + f_nan = xp.isnan(work.f1) & xp.isnan(work.f2) + i = (x_nonfinite | f_nan) & ~stop + work.xmin[i], work.fmin[i], work.status[i] = NaN, NaN, eim._EVALUEERR + stop[i] = True + + # This is the convergence criterion used in bisect. Chandrupatla's + # criterion is equivalent to this except with a factor of 4 on `xrtol`. + work.dx = xp.abs(work.x2 - work.x1) + work.tol = xp.abs(work.xmin) * work.xrtol + work.xatol + i = work.dx < work.tol + work.status[i] = eim._ECONVERGED + stop[i] = True + + return stop + + def post_termination_check(work): + # [1] Figure 1 (third diamond and boxes / Equation 1) + xi1 = (work.x1 - work.x2) / (work.x3 - work.x2) + with np.errstate(divide='ignore', invalid='ignore'): + phi1 = (work.f1 - work.f2) / (work.f3 - work.f2) + alpha = (work.x3 - work.x1) / (work.x2 - work.x1) + j = ((1 - xp.sqrt(1 - xi1)) < phi1) & (phi1 < xp.sqrt(xi1)) + + f1j, f2j, f3j, alphaj = work.f1[j], work.f2[j], work.f3[j], alpha[j] + t = xp.full_like(alpha, xp.asarray(0.5)) + t[j] = (f1j / (f1j - f2j) * f3j / (f3j - f2j) + - alphaj * f1j / (f3j - f1j) * f2j / (f2j - f3j)) + + # [1] Figure 1 (last box; see also BASIC in appendix with comment + # "Adjust T Away from the Interval Boundary") + tl = 0.5 * work.tol / work.dx + work.t = xp.clip(t, tl, 1 - tl) + + def customize_result(res, shape): + xl, xr, fl, fr = res['xl'], res['xr'], res['fl'], res['fr'] + i = res['xl'] < res['xr'] + res['xl'] = xp.where(i, xl, xr) + res['xr'] = xp.where(i, xr, xl) + res['fl'] = xp.where(i, fl, fr) + res['fr'] = xp.where(i, fr, fl) + return shape + + return eim._loop(work, callback, shape, maxiter, func, args, dtype, + pre_func_eval, post_func_eval, check_termination, + post_termination_check, customize_result, res_work_pairs, + xp=xp) + + +def _chandrupatla_iv(func, args, xatol, xrtol, + fatol, frtol, maxiter, callback): + # Input validation for `_chandrupatla` + + if not callable(func): + raise ValueError('`func` must be callable.') + + if not np.iterable(args): + args = (args,) + + # tolerances are floats, not arrays; OK to use NumPy + tols = np.asarray([xatol if xatol is not None else 1, + xrtol if xrtol is not None else 1, + fatol if fatol is not None else 1, + frtol if frtol is not None else 1]) + if (not np.issubdtype(tols.dtype, np.number) or np.any(tols < 0) + or np.any(np.isnan(tols)) or tols.shape != (4,)): + raise ValueError('Tolerances must be non-negative scalars.') + + if maxiter is not None: + maxiter_int = int(maxiter) + if maxiter != maxiter_int or maxiter < 0: + raise ValueError('`maxiter` must be a non-negative integer.') + + if callback is not None and not callable(callback): + raise ValueError('`callback` must be callable.') + + return func, args, xatol, xrtol, fatol, frtol, maxiter, callback + + +def _chandrupatla_minimize(func, x1, x2, x3, *, args=(), xatol=None, + xrtol=None, fatol=None, frtol=None, maxiter=100, + callback=None): + """Find the minimizer of an elementwise function. + + For each element of the output of `func`, `_chandrupatla_minimize` seeks + the scalar minimizer that minimizes the element. This function allows for + `x1`, `x2`, `x3`, and the elements of `args` to be arrays of any + broadcastable shapes. + + Parameters + ---------- + func : callable + The function whose minimizer is desired. The signature must be:: + + func(x: ndarray, *args) -> ndarray + + where each element of ``x`` is a finite real and ``args`` is a tuple, + which may contain an arbitrary number of arrays that are broadcastable + with `x`. ``func`` must be an elementwise function: each element + ``func(x)[i]`` must equal ``func(x[i])`` for all indices ``i``. + `_chandrupatla` seeks an array ``x`` such that ``func(x)`` is an array + of minima. + x1, x2, x3 : array_like + The abscissae of a standard scalar minimization bracket. A bracket is + valid if ``x1 < x2 < x3`` and ``func(x1) > func(x2) <= func(x3)``. + Must be broadcastable with one another and `args`. + args : tuple, optional + Additional positional arguments to be passed to `func`. Must be arrays + broadcastable with `x1`, `x2`, and `x3`. If the callable to be + differentiated requires arguments that are not broadcastable with `x`, + wrap that callable with `func` such that `func` accepts only `x` and + broadcastable arrays. + xatol, xrtol, fatol, frtol : float, optional + Absolute and relative tolerances on the minimizer and function value. + See Notes for details. + maxiter : int, optional + The maximum number of iterations of the algorithm to perform. + callback : callable, optional + An optional user-supplied function to be called before the first + iteration and after each iteration. + Called as ``callback(res)``, where ``res`` is a ``_RichResult`` + similar to that returned by `_chandrupatla_minimize` (but containing + the current iterate's values of all variables). If `callback` raises a + ``StopIteration``, the algorithm will terminate immediately and + `_chandrupatla_minimize` will return a result. + + Returns + ------- + res : _RichResult + An instance of `scipy._lib._util._RichResult` with the following + attributes. (The descriptions are written as though the values will be + scalars; however, if `func` returns an array, the outputs will be + arrays of the same shape.) + + success : bool + ``True`` when the algorithm terminated successfully (status ``0``). + status : int + An integer representing the exit status of the algorithm. + ``0`` : The algorithm converged to the specified tolerances. + ``-1`` : The algorithm encountered an invalid bracket. + ``-2`` : The maximum number of iterations was reached. + ``-3`` : A non-finite value was encountered. + ``-4`` : Iteration was terminated by `callback`. + ``1`` : The algorithm is proceeding normally (in `callback` only). + x : float + The minimizer of the function, if the algorithm terminated + successfully. + fun : float + The value of `func` evaluated at `x`. + nfev : int + The number of points at which `func` was evaluated. + nit : int + The number of iterations of the algorithm that were performed. + xl, xm, xr : float + The final three-point bracket. + fl, fm, fr : float + The function value at the bracket points. + + Notes + ----- + Implemented based on Chandrupatla's original paper [1]_. + + If ``x1 < x2 < x3`` are the points of the bracket and ``f1 > f2 <= f3`` + are the values of ``func`` at those points, then the algorithm is + considered to have converged when ``x3 - x1 <= abs(x2)*xrtol + xatol`` + or ``(f1 - 2*f2 + f3)/2 <= abs(f2)*frtol + fatol``. Note that first of + these differs from the termination conditions described in [1]_. The + default values of `xrtol` is the square root of the precision of the + appropriate dtype, and ``xatol = fatol = frtol`` is the smallest normal + number of the appropriate dtype. + + References + ---------- + .. [1] Chandrupatla, Tirupathi R. (1998). + "An efficient quadratic fit-sectioning algorithm for minimization + without derivatives". + Computer Methods in Applied Mechanics and Engineering, 152 (1-2), + 211-217. https://doi.org/10.1016/S0045-7825(97)00190-4 + + See Also + -------- + golden, brent, bounded + + Examples + -------- + >>> from scipy.optimize._chandrupatla import _chandrupatla_minimize + >>> def f(x, args=1): + ... return (x - args)**2 + >>> res = _chandrupatla_minimize(f, -5, 0, 5) + >>> res.x + 1.0 + >>> c = [1, 1.5, 2] + >>> res = _chandrupatla_minimize(f, -5, 0, 5, args=(c,)) + >>> res.x + array([1. , 1.5, 2. ]) + """ + res = _chandrupatla_iv(func, args, xatol, xrtol, + fatol, frtol, maxiter, callback) + func, args, xatol, xrtol, fatol, frtol, maxiter, callback = res + + # Initialization + xs = (x1, x2, x3) + temp = eim._initialize(func, xs, args) + func, xs, fs, args, shape, dtype, xp = temp # line split for PEP8 + x1, x2, x3 = xs + f1, f2, f3 = fs + phi = xp.asarray(0.5 + 0.5*5**0.5, dtype=dtype)[()] # golden ratio + status = xp.full_like(x1, xp.asarray(eim._EINPROGRESS), + dtype=xp.int32) # in progress + nit, nfev = 0, 3 # three function evaluations performed above + fatol = xp.finfo(dtype).smallest_normal if fatol is None else fatol + frtol = xp.finfo(dtype).smallest_normal if frtol is None else frtol + xatol = xp.finfo(dtype).smallest_normal if xatol is None else xatol + xrtol = math.sqrt(xp.finfo(dtype).eps) if xrtol is None else xrtol + + # Ensure that x1 < x2 < x3 initially. + xs, fs = xp.stack((x1, x2, x3)), xp.stack((f1, f2, f3)) + i = xp.argsort(xs, axis=0) + x1, x2, x3 = xp_take_along_axis(xs, i, axis=0) # data-apis/array-api#808 + f1, f2, f3 = xp_take_along_axis(fs, i, axis=0) # data-apis/array-api#808 + q0 = xp_copy(x3) # "At the start, q0 is set at x3..." ([1] after (7)) + + work = _RichResult(x1=x1, f1=f1, x2=x2, f2=f2, x3=x3, f3=f3, phi=phi, + xatol=xatol, xrtol=xrtol, fatol=fatol, frtol=frtol, + nit=nit, nfev=nfev, status=status, q0=q0, args=args) + res_work_pairs = [('status', 'status'), + ('x', 'x2'), ('fun', 'f2'), + ('nit', 'nit'), ('nfev', 'nfev'), + ('xl', 'x1'), ('xm', 'x2'), ('xr', 'x3'), + ('fl', 'f1'), ('fm', 'f2'), ('fr', 'f3')] + + def pre_func_eval(work): + # `_check_termination` is called first -> `x3 - x2 > x2 - x1` + # But let's calculate a few terms that we'll reuse + x21 = work.x2 - work.x1 + x32 = work.x3 - work.x2 + + # [1] Section 3. "The quadratic minimum point Q1 is calculated using + # the relations developed in the previous section." [1] Section 2 (5/6) + A = x21 * (work.f3 - work.f2) + B = x32 * (work.f1 - work.f2) + C = A / (A + B) + # q1 = C * (work.x1 + work.x2) / 2 + (1 - C) * (work.x2 + work.x3) / 2 + q1 = 0.5 * (C*(work.x1 - work.x3) + work.x2 + work.x3) # much faster + # this is an array, so multiplying by 0.5 does not change dtype + + # "If Q1 and Q0 are sufficiently close... Q1 is accepted if it is + # sufficiently away from the inside point x2" + i = xp.abs(q1 - work.q0) < 0.5 * xp.abs(x21) # [1] (7) + xi = q1[i] + # Later, after (9), "If the point Q1 is in a +/- xtol neighborhood of + # x2, the new point is chosen in the larger interval at a distance + # tol away from x2." + # See also QBASIC code after "Accept Ql adjust if close to X2". + j = xp.abs(q1[i] - work.x2[i]) <= work.xtol[i] + xi[j] = work.x2[i][j] + xp_sign(x32[i][j]) * work.xtol[i][j] + + # "If condition (7) is not satisfied, golden sectioning of the larger + # interval is carried out to introduce the new point." + # (For simplicity, we go ahead and calculate it for all points, but we + # change the elements for which the condition was satisfied.) + x = work.x2 + (2 - work.phi) * x32 + x[i] = xi + + # "We define Q0 as the value of Q1 at the previous iteration." + work.q0 = q1 + return x + + def post_func_eval(x, f, work): + # Standard logic for updating a three-point bracket based on a new + # point. In QBASIC code, see "IF SGN(X-X2) = SGN(X3-X2) THEN...". + # There is an awful lot of data copying going on here; this would + # probably benefit from code optimization or implementation in Pythran. + i = xp_sign(x - work.x2) == xp_sign(work.x3 - work.x2) + xi, x1i, x2i, x3i = x[i], work.x1[i], work.x2[i], work.x3[i], + fi, f1i, f2i, f3i = f[i], work.f1[i], work.f2[i], work.f3[i] + j = fi > f2i + x3i[j], f3i[j] = xi[j], fi[j] + j = ~j + x1i[j], f1i[j], x2i[j], f2i[j] = x2i[j], f2i[j], xi[j], fi[j] + + ni = ~i + xni, x1ni, x2ni, x3ni = x[ni], work.x1[ni], work.x2[ni], work.x3[ni], + fni, f1ni, f2ni, f3ni = f[ni], work.f1[ni], work.f2[ni], work.f3[ni] + j = fni > f2ni + x1ni[j], f1ni[j] = xni[j], fni[j] + j = ~j + x3ni[j], f3ni[j], x2ni[j], f2ni[j] = x2ni[j], f2ni[j], xni[j], fni[j] + + work.x1[i], work.x2[i], work.x3[i] = x1i, x2i, x3i + work.f1[i], work.f2[i], work.f3[i] = f1i, f2i, f3i + work.x1[ni], work.x2[ni], work.x3[ni] = x1ni, x2ni, x3ni, + work.f1[ni], work.f2[ni], work.f3[ni] = f1ni, f2ni, f3ni + + def check_termination(work): + # Check for all terminal conditions and record statuses. + stop = xp.zeros_like(work.x1, dtype=bool) # termination condition met + + # Bracket is invalid; stop and don't return minimizer/minimum + i = ((work.f2 > work.f1) | (work.f2 > work.f3)) + work.x2[i], work.f2[i] = xp.nan, xp.nan + stop[i], work.status[i] = True, eim._ESIGNERR + + # Non-finite values; stop and don't return minimizer/minimum + finite = xp.isfinite(work.x1+work.x2+work.x3+work.f1+work.f2+work.f3) + i = ~(finite | stop) + work.x2[i], work.f2[i] = xp.nan, xp.nan + stop[i], work.status[i] = True, eim._EVALUEERR + + # [1] Section 3 "Points 1 and 3 are interchanged if necessary to make + # the (x2, x3) the larger interval." + # Note: I had used np.choose; this is much faster. This would be a good + # place to save e.g. `work.x3 - work.x2` for reuse, but I tried and + # didn't notice a speed boost, so let's keep it simple. + i = xp.abs(work.x3 - work.x2) < xp.abs(work.x2 - work.x1) + temp = work.x1[i] + work.x1[i] = work.x3[i] + work.x3[i] = temp + temp = work.f1[i] + work.f1[i] = work.f3[i] + work.f3[i] = temp + + # [1] Section 3 (bottom of page 212) + # "We set a tolerance value xtol..." + work.xtol = xp.abs(work.x2) * work.xrtol + work.xatol # [1] (8) + # "The convergence based on interval is achieved when..." + # Note: Equality allowed in case of `xtol=0` + i = xp.abs(work.x3 - work.x2) <= 2 * work.xtol # [1] (9) + + # "We define ftol using..." + ftol = xp.abs(work.f2) * work.frtol + work.fatol # [1] (10) + # "The convergence based on function values is achieved when..." + # Note 1: modify in place to incorporate tolerance on function value. + # Note 2: factor of 2 is not in the text; see QBASIC start of DO loop + i |= (work.f1 - 2 * work.f2 + work.f3) <= 2*ftol # [1] (11) + i &= ~stop + stop[i], work.status[i] = True, eim._ECONVERGED + + return stop + + def post_termination_check(work): + pass + + def customize_result(res, shape): + xl, xr, fl, fr = res['xl'], res['xr'], res['fl'], res['fr'] + i = res['xl'] >= res['xr'] + res['xl'] = xp.where(i, xr, xl) + res['xr'] = xp.where(i, xl, xr) + res['fl'] = xp.where(i, fr, fl) + res['fr'] = xp.where(i, fl, fr) + return shape + + return eim._loop(work, callback, shape, maxiter, func, args, dtype, + pre_func_eval, post_func_eval, check_termination, + post_termination_check, customize_result, res_work_pairs, + xp=xp) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_cobyla_py.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_cobyla_py.py new file mode 100644 index 0000000000000000000000000000000000000000..7e99acf373df59524f66e19f625f50b8d5d3cc76 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_cobyla_py.py @@ -0,0 +1,316 @@ +""" +Interface to Constrained Optimization By Linear Approximation + +Functions +--------- +.. autosummary:: + :toctree: generated/ + + fmin_cobyla + +""" + +import functools +from threading import RLock + +import numpy as np +from scipy.optimize import _cobyla as cobyla +from ._optimize import (OptimizeResult, _check_unknown_options, + _prepare_scalar_function) +try: + from itertools import izip +except ImportError: + izip = zip + +__all__ = ['fmin_cobyla'] + +# Workaround as _cobyla.minimize is not threadsafe +# due to an unknown f2py bug and can segfault, +# see gh-9658. +_module_lock = RLock() +def synchronized(func): + @functools.wraps(func) + def wrapper(*args, **kwargs): + with _module_lock: + return func(*args, **kwargs) + return wrapper + +@synchronized +def fmin_cobyla(func, x0, cons, args=(), consargs=None, rhobeg=1.0, + rhoend=1e-4, maxfun=1000, disp=None, catol=2e-4, + *, callback=None): + """ + Minimize a function using the Constrained Optimization By Linear + Approximation (COBYLA) method. This method wraps a FORTRAN + implementation of the algorithm. + + Parameters + ---------- + func : callable + Function to minimize. In the form func(x, \\*args). + x0 : ndarray + Initial guess. + cons : sequence + Constraint functions; must all be ``>=0`` (a single function + if only 1 constraint). Each function takes the parameters `x` + as its first argument, and it can return either a single number or + an array or list of numbers. + args : tuple, optional + Extra arguments to pass to function. + consargs : tuple, optional + Extra arguments to pass to constraint functions (default of None means + use same extra arguments as those passed to func). + Use ``()`` for no extra arguments. + rhobeg : float, optional + Reasonable initial changes to the variables. + rhoend : float, optional + Final accuracy in the optimization (not precisely guaranteed). This + is a lower bound on the size of the trust region. + disp : {0, 1, 2, 3}, optional + Controls the frequency of output; 0 implies no output. + maxfun : int, optional + Maximum number of function evaluations. + catol : float, optional + Absolute tolerance for constraint violations. + callback : callable, optional + Called after each iteration, as ``callback(x)``, where ``x`` is the + current parameter vector. + + Returns + ------- + x : ndarray + The argument that minimises `f`. + + See also + -------- + minimize: Interface to minimization algorithms for multivariate + functions. See the 'COBYLA' `method` in particular. + + Notes + ----- + This algorithm is based on linear approximations to the objective + function and each constraint. We briefly describe the algorithm. + + Suppose the function is being minimized over k variables. At the + jth iteration the algorithm has k+1 points v_1, ..., v_(k+1), + an approximate solution x_j, and a radius RHO_j. + (i.e., linear plus a constant) approximations to the objective + function and constraint functions such that their function values + agree with the linear approximation on the k+1 points v_1,.., v_(k+1). + This gives a linear program to solve (where the linear approximations + of the constraint functions are constrained to be non-negative). + + However, the linear approximations are likely only good + approximations near the current simplex, so the linear program is + given the further requirement that the solution, which + will become x_(j+1), must be within RHO_j from x_j. RHO_j only + decreases, never increases. The initial RHO_j is rhobeg and the + final RHO_j is rhoend. In this way COBYLA's iterations behave + like a trust region algorithm. + + Additionally, the linear program may be inconsistent, or the + approximation may give poor improvement. For details about + how these issues are resolved, as well as how the points v_i are + updated, refer to the source code or the references below. + + + References + ---------- + Powell M.J.D. (1994), "A direct search optimization method that models + the objective and constraint functions by linear interpolation.", in + Advances in Optimization and Numerical Analysis, eds. S. Gomez and + J-P Hennart, Kluwer Academic (Dordrecht), pp. 51-67 + + Powell M.J.D. (1998), "Direct search algorithms for optimization + calculations", Acta Numerica 7, 287-336 + + Powell M.J.D. (2007), "A view of algorithms for optimization without + derivatives", Cambridge University Technical Report DAMTP 2007/NA03 + + + Examples + -------- + Minimize the objective function f(x,y) = x*y subject + to the constraints x**2 + y**2 < 1 and y > 0:: + + >>> def objective(x): + ... return x[0]*x[1] + ... + >>> def constr1(x): + ... return 1 - (x[0]**2 + x[1]**2) + ... + >>> def constr2(x): + ... return x[1] + ... + >>> from scipy.optimize import fmin_cobyla + >>> fmin_cobyla(objective, [0.0, 0.1], [constr1, constr2], rhoend=1e-7) + array([-0.70710685, 0.70710671]) + + The exact solution is (-sqrt(2)/2, sqrt(2)/2). + + + + """ + err = "cons must be a sequence of callable functions or a single"\ + " callable function." + try: + len(cons) + except TypeError as e: + if callable(cons): + cons = [cons] + else: + raise TypeError(err) from e + else: + for thisfunc in cons: + if not callable(thisfunc): + raise TypeError(err) + + if consargs is None: + consargs = args + + # build constraints + con = tuple({'type': 'ineq', 'fun': c, 'args': consargs} for c in cons) + + # options + opts = {'rhobeg': rhobeg, + 'tol': rhoend, + 'disp': disp, + 'maxiter': maxfun, + 'catol': catol, + 'callback': callback} + + sol = _minimize_cobyla(func, x0, args, constraints=con, + **opts) + if disp and not sol['success']: + print(f"COBYLA failed to find a solution: {sol.message}") + return sol['x'] + + +@synchronized +def _minimize_cobyla(fun, x0, args=(), constraints=(), + rhobeg=1.0, tol=1e-4, maxiter=1000, + disp=False, catol=2e-4, callback=None, bounds=None, + **unknown_options): + """ + Minimize a scalar function of one or more variables using the + Constrained Optimization BY Linear Approximation (COBYLA) algorithm. + + Options + ------- + rhobeg : float + Reasonable initial changes to the variables. + tol : float + Final accuracy in the optimization (not precisely guaranteed). + This is a lower bound on the size of the trust region. + disp : bool + Set to True to print convergence messages. If False, + `verbosity` is ignored as set to 0. + maxiter : int + Maximum number of function evaluations. + catol : float + Tolerance (absolute) for constraint violations + + """ + _check_unknown_options(unknown_options) + maxfun = maxiter + rhoend = tol + iprint = int(bool(disp)) + + # check constraints + if isinstance(constraints, dict): + constraints = (constraints, ) + + if bounds: + i_lb = np.isfinite(bounds.lb) + if np.any(i_lb): + def lb_constraint(x, *args, **kwargs): + return x[i_lb] - bounds.lb[i_lb] + + constraints.append({'type': 'ineq', 'fun': lb_constraint}) + + i_ub = np.isfinite(bounds.ub) + if np.any(i_ub): + def ub_constraint(x): + return bounds.ub[i_ub] - x[i_ub] + + constraints.append({'type': 'ineq', 'fun': ub_constraint}) + + for ic, con in enumerate(constraints): + # check type + try: + ctype = con['type'].lower() + except KeyError as e: + raise KeyError('Constraint %d has no type defined.' % ic) from e + except TypeError as e: + raise TypeError('Constraints must be defined using a ' + 'dictionary.') from e + except AttributeError as e: + raise TypeError("Constraint's type must be a string.") from e + else: + if ctype != 'ineq': + raise ValueError(f"Constraints of type '{con['type']}' not handled by " + "COBYLA.") + + # check function + if 'fun' not in con: + raise KeyError('Constraint %d has no function defined.' % ic) + + # check extra arguments + if 'args' not in con: + con['args'] = () + + # m is the total number of constraint values + # it takes into account that some constraints may be vector-valued + cons_lengths = [] + for c in constraints: + f = c['fun'](x0, *c['args']) + try: + cons_length = len(f) + except TypeError: + cons_length = 1 + cons_lengths.append(cons_length) + m = sum(cons_lengths) + + # create the ScalarFunction, cobyla doesn't require derivative function + def _jac(x, *args): + return None + + sf = _prepare_scalar_function(fun, x0, args=args, jac=_jac) + + def calcfc(x, con): + f = sf.fun(x) + i = 0 + for size, c in izip(cons_lengths, constraints): + con[i: i + size] = c['fun'](x, *c['args']) + i += size + return f + + def wrapped_callback(x): + if callback is not None: + callback(np.copy(x)) + + info = np.zeros(4, np.float64) + xopt, info = cobyla.minimize(calcfc, m=m, x=np.copy(x0), rhobeg=rhobeg, + rhoend=rhoend, iprint=iprint, maxfun=maxfun, + dinfo=info, callback=wrapped_callback) + + if info[3] > catol: + # Check constraint violation + info[0] = 4 + + return OptimizeResult(x=xopt, + status=int(info[0]), + success=info[0] == 1, + message={1: 'Optimization terminated successfully.', + 2: 'Maximum number of function evaluations ' + 'has been exceeded.', + 3: 'Rounding errors are becoming damaging ' + 'in COBYLA subroutine.', + 4: 'Did not converge to a solution ' + 'satisfying the constraints. See ' + '`maxcv` for magnitude of violation.', + 5: 'NaN result encountered.' + }.get(info[0], 'Unknown exit status.'), + nfev=int(info[1]), + fun=info[2], + maxcv=info[3]) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_cobyqa_py.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_cobyqa_py.py new file mode 100644 index 0000000000000000000000000000000000000000..38ae0477ca38e28dda80e0bf2dd1f0905eacff6e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_cobyqa_py.py @@ -0,0 +1,72 @@ +import numpy as np +from threading import Lock + +from ._optimize import _check_unknown_options + + +COBYQA_LOCK = Lock() + + +def _minimize_cobyqa(fun, x0, args=(), bounds=None, constraints=(), + callback=None, disp=False, maxfev=None, maxiter=None, + f_target=-np.inf, feasibility_tol=1e-8, + initial_tr_radius=1.0, final_tr_radius=1e-6, scale=False, + **unknown_options): + """ + Minimize a scalar function of one or more variables using the + Constrained Optimization BY Quadratic Approximations (COBYQA) algorithm [1]_. + + .. versionadded:: 1.14.0 + + Options + ------- + disp : bool + Set to True to print information about the optimization procedure. + Default is ``False``. + maxfev : int + Maximum number of function evaluations. Default is ``500 * n``, where + ``n`` is the number of variables. + maxiter : int + Maximum number of iterations. Default is ``1000 * n``, where ``n`` is + the number of variables. + f_target : float + Target value for the objective function. The optimization procedure is + terminated when the objective function value of a feasible point (see + `feasibility_tol` below) is less than or equal to this target. Default + is ``-numpy.inf``. + feasibility_tol : float + Absolute tolerance for the constraint violation. Default is ``1e-8``. + initial_tr_radius : float + Initial trust-region radius. Typically, this value should be in the + order of one tenth of the greatest expected change to the variables. + Default is ``1.0``. + final_tr_radius : float + Final trust-region radius. It should indicate the accuracy required in + the final values of the variables. If provided, this option overrides + the value of `tol` in the `minimize` function. Default is ``1e-6``. + scale : bool + Set to True to scale the variables according to the bounds. If True and + if all the lower and upper bounds are finite, the variables are scaled + to be within the range :math:`[-1, 1]`. If any of the lower or upper + bounds is infinite, the variables are not scaled. Default is ``False``. + + References + ---------- + .. [1] COBYQA + https://www.cobyqa.com/stable/ + """ + from .._lib.cobyqa import minimize # import here to avoid circular imports + + _check_unknown_options(unknown_options) + options = { + 'disp': bool(disp), + 'maxfev': int(maxfev) if maxfev is not None else 500 * len(x0), + 'maxiter': int(maxiter) if maxiter is not None else 1000 * len(x0), + 'target': float(f_target), + 'feasibility_tol': float(feasibility_tol), + 'radius_init': float(initial_tr_radius), + 'radius_final': float(final_tr_radius), + 'scale': bool(scale), + } + with COBYQA_LOCK: + return minimize(fun, x0, args, bounds, constraints, callback, options) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_constraints.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_constraints.py new file mode 100644 index 0000000000000000000000000000000000000000..1bae893e231eb9bd89308e441b8abf841f4605bb --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_constraints.py @@ -0,0 +1,594 @@ +"""Constraints definition for minimize.""" +import numpy as np +from ._hessian_update_strategy import BFGS +from ._differentiable_functions import ( + VectorFunction, LinearVectorFunction, IdentityVectorFunction) +from ._optimize import OptimizeWarning +from warnings import warn, catch_warnings, simplefilter, filterwarnings +from scipy.sparse import issparse + + +def _arr_to_scalar(x): + # If x is a numpy array, return x.item(). This will + # fail if the array has more than one element. + return x.item() if isinstance(x, np.ndarray) else x + + +class NonlinearConstraint: + """Nonlinear constraint on the variables. + + The constraint has the general inequality form:: + + lb <= fun(x) <= ub + + Here the vector of independent variables x is passed as ndarray of shape + (n,) and ``fun`` returns a vector with m components. + + It is possible to use equal bounds to represent an equality constraint or + infinite bounds to represent a one-sided constraint. + + Parameters + ---------- + fun : callable + The function defining the constraint. + The signature is ``fun(x) -> array_like, shape (m,)``. + lb, ub : array_like + Lower and upper bounds on the constraint. Each array must have the + shape (m,) or be a scalar, in the latter case a bound will be the same + for all components of the constraint. Use ``np.inf`` with an + appropriate sign to specify a one-sided constraint. + Set components of `lb` and `ub` equal to represent an equality + constraint. Note that you can mix constraints of different types: + interval, one-sided or equality, by setting different components of + `lb` and `ub` as necessary. + jac : {callable, '2-point', '3-point', 'cs'}, optional + Method of computing the Jacobian matrix (an m-by-n matrix, + where element (i, j) is the partial derivative of f[i] with + respect to x[j]). The keywords {'2-point', '3-point', + 'cs'} select a finite difference scheme for the numerical estimation. + A callable must have the following signature:: + + jac(x) -> {ndarray, sparse matrix}, shape (m, n) + + Default is '2-point'. + hess : {callable, '2-point', '3-point', 'cs', HessianUpdateStrategy, None}, optional + Method for computing the Hessian matrix. The keywords + {'2-point', '3-point', 'cs'} select a finite difference scheme for + numerical estimation. Alternatively, objects implementing + `HessianUpdateStrategy` interface can be used to approximate the + Hessian. Currently available implementations are: + + - `BFGS` (default option) + - `SR1` + + A callable must return the Hessian matrix of ``dot(fun, v)`` and + must have the following signature: + ``hess(x, v) -> {LinearOperator, sparse matrix, array_like}, shape (n, n)``. + Here ``v`` is ndarray with shape (m,) containing Lagrange multipliers. + keep_feasible : array_like of bool, optional + Whether to keep the constraint components feasible throughout + iterations. A single value set this property for all components. + Default is False. Has no effect for equality constraints. + finite_diff_rel_step: None or array_like, optional + Relative step size for the finite difference approximation. Default is + None, which will select a reasonable value automatically depending + on a finite difference scheme. + finite_diff_jac_sparsity: {None, array_like, sparse matrix}, optional + Defines the sparsity structure of the Jacobian matrix for finite + difference estimation, its shape must be (m, n). If the Jacobian has + only few non-zero elements in *each* row, providing the sparsity + structure will greatly speed up the computations. A zero entry means + that a corresponding element in the Jacobian is identically zero. + If provided, forces the use of 'lsmr' trust-region solver. + If None (default) then dense differencing will be used. + + Notes + ----- + Finite difference schemes {'2-point', '3-point', 'cs'} may be used for + approximating either the Jacobian or the Hessian. We, however, do not allow + its use for approximating both simultaneously. Hence whenever the Jacobian + is estimated via finite-differences, we require the Hessian to be estimated + using one of the quasi-Newton strategies. + + The scheme 'cs' is potentially the most accurate, but requires the function + to correctly handles complex inputs and be analytically continuable to the + complex plane. The scheme '3-point' is more accurate than '2-point' but + requires twice as many operations. + + Examples + -------- + Constrain ``x[0] < sin(x[1]) + 1.9`` + + >>> from scipy.optimize import NonlinearConstraint + >>> import numpy as np + >>> con = lambda x: x[0] - np.sin(x[1]) + >>> nlc = NonlinearConstraint(con, -np.inf, 1.9) + + """ + def __init__(self, fun, lb, ub, jac='2-point', hess=None, + keep_feasible=False, finite_diff_rel_step=None, + finite_diff_jac_sparsity=None): + if hess is None: + hess = BFGS() + self.fun = fun + self.lb = lb + self.ub = ub + self.finite_diff_rel_step = finite_diff_rel_step + self.finite_diff_jac_sparsity = finite_diff_jac_sparsity + self.jac = jac + self.hess = hess + self.keep_feasible = keep_feasible + + +class LinearConstraint: + """Linear constraint on the variables. + + The constraint has the general inequality form:: + + lb <= A.dot(x) <= ub + + Here the vector of independent variables x is passed as ndarray of shape + (n,) and the matrix A has shape (m, n). + + It is possible to use equal bounds to represent an equality constraint or + infinite bounds to represent a one-sided constraint. + + Parameters + ---------- + A : {array_like, sparse matrix}, shape (m, n) + Matrix defining the constraint. + lb, ub : dense array_like, optional + Lower and upper limits on the constraint. Each array must have the + shape (m,) or be a scalar, in the latter case a bound will be the same + for all components of the constraint. Use ``np.inf`` with an + appropriate sign to specify a one-sided constraint. + Set components of `lb` and `ub` equal to represent an equality + constraint. Note that you can mix constraints of different types: + interval, one-sided or equality, by setting different components of + `lb` and `ub` as necessary. Defaults to ``lb = -np.inf`` + and ``ub = np.inf`` (no limits). + keep_feasible : dense array_like of bool, optional + Whether to keep the constraint components feasible throughout + iterations. A single value set this property for all components. + Default is False. Has no effect for equality constraints. + """ + def _input_validation(self): + if self.A.ndim != 2: + message = "`A` must have exactly two dimensions." + raise ValueError(message) + + try: + shape = self.A.shape[0:1] + self.lb = np.broadcast_to(self.lb, shape) + self.ub = np.broadcast_to(self.ub, shape) + self.keep_feasible = np.broadcast_to(self.keep_feasible, shape) + except ValueError: + message = ("`lb`, `ub`, and `keep_feasible` must be broadcastable " + "to shape `A.shape[0:1]`") + raise ValueError(message) + + def __init__(self, A, lb=-np.inf, ub=np.inf, keep_feasible=False): + if not issparse(A): + # In some cases, if the constraint is not valid, this emits a + # VisibleDeprecationWarning about ragged nested sequences + # before eventually causing an error. `scipy.optimize.milp` would + # prefer that this just error out immediately so it can handle it + # rather than concerning the user. + with catch_warnings(): + simplefilter("error") + self.A = np.atleast_2d(A).astype(np.float64) + else: + self.A = A + if issparse(lb) or issparse(ub): + raise ValueError("Constraint limits must be dense arrays.") + self.lb = np.atleast_1d(lb).astype(np.float64) + self.ub = np.atleast_1d(ub).astype(np.float64) + + if issparse(keep_feasible): + raise ValueError("`keep_feasible` must be a dense array.") + self.keep_feasible = np.atleast_1d(keep_feasible).astype(bool) + self._input_validation() + + def residual(self, x): + """ + Calculate the residual between the constraint function and the limits + + For a linear constraint of the form:: + + lb <= A@x <= ub + + the lower and upper residuals between ``A@x`` and the limits are values + ``sl`` and ``sb`` such that:: + + lb + sl == A@x == ub - sb + + When all elements of ``sl`` and ``sb`` are positive, all elements of + the constraint are satisfied; a negative element in ``sl`` or ``sb`` + indicates that the corresponding element of the constraint is not + satisfied. + + Parameters + ---------- + x: array_like + Vector of independent variables + + Returns + ------- + sl, sb : array-like + The lower and upper residuals + """ + return self.A@x - self.lb, self.ub - self.A@x + + +class Bounds: + """Bounds constraint on the variables. + + The constraint has the general inequality form:: + + lb <= x <= ub + + It is possible to use equal bounds to represent an equality constraint or + infinite bounds to represent a one-sided constraint. + + Parameters + ---------- + lb, ub : dense array_like, optional + Lower and upper bounds on independent variables. `lb`, `ub`, and + `keep_feasible` must be the same shape or broadcastable. + Set components of `lb` and `ub` equal + to fix a variable. Use ``np.inf`` with an appropriate sign to disable + bounds on all or some variables. Note that you can mix constraints of + different types: interval, one-sided or equality, by setting different + components of `lb` and `ub` as necessary. Defaults to ``lb = -np.inf`` + and ``ub = np.inf`` (no bounds). + keep_feasible : dense array_like of bool, optional + Whether to keep the constraint components feasible throughout + iterations. Must be broadcastable with `lb` and `ub`. + Default is False. Has no effect for equality constraints. + """ + def _input_validation(self): + try: + res = np.broadcast_arrays(self.lb, self.ub, self.keep_feasible) + self.lb, self.ub, self.keep_feasible = res + except ValueError: + message = "`lb`, `ub`, and `keep_feasible` must be broadcastable." + raise ValueError(message) + + def __init__(self, lb=-np.inf, ub=np.inf, keep_feasible=False): + if issparse(lb) or issparse(ub): + raise ValueError("Lower and upper bounds must be dense arrays.") + self.lb = np.atleast_1d(lb) + self.ub = np.atleast_1d(ub) + + if issparse(keep_feasible): + raise ValueError("`keep_feasible` must be a dense array.") + self.keep_feasible = np.atleast_1d(keep_feasible).astype(bool) + self._input_validation() + + def __repr__(self): + start = f"{type(self).__name__}({self.lb!r}, {self.ub!r}" + if np.any(self.keep_feasible): + end = f", keep_feasible={self.keep_feasible!r})" + else: + end = ")" + return start + end + + def residual(self, x): + """Calculate the residual (slack) between the input and the bounds + + For a bound constraint of the form:: + + lb <= x <= ub + + the lower and upper residuals between `x` and the bounds are values + ``sl`` and ``sb`` such that:: + + lb + sl == x == ub - sb + + When all elements of ``sl`` and ``sb`` are positive, all elements of + ``x`` lie within the bounds; a negative element in ``sl`` or ``sb`` + indicates that the corresponding element of ``x`` is out of bounds. + + Parameters + ---------- + x: array_like + Vector of independent variables + + Returns + ------- + sl, sb : array-like + The lower and upper residuals + """ + return x - self.lb, self.ub - x + + +class PreparedConstraint: + """Constraint prepared from a user defined constraint. + + On creation it will check whether a constraint definition is valid and + the initial point is feasible. If created successfully, it will contain + the attributes listed below. + + Parameters + ---------- + constraint : {NonlinearConstraint, LinearConstraint`, Bounds} + Constraint to check and prepare. + x0 : array_like + Initial vector of independent variables. + sparse_jacobian : bool or None, optional + If bool, then the Jacobian of the constraint will be converted + to the corresponded format if necessary. If None (default), such + conversion is not made. + finite_diff_bounds : 2-tuple, optional + Lower and upper bounds on the independent variables for the finite + difference approximation, if applicable. Defaults to no bounds. + + Attributes + ---------- + fun : {VectorFunction, LinearVectorFunction, IdentityVectorFunction} + Function defining the constraint wrapped by one of the convenience + classes. + bounds : 2-tuple + Contains lower and upper bounds for the constraints --- lb and ub. + These are converted to ndarray and have a size equal to the number of + the constraints. + keep_feasible : ndarray + Array indicating which components must be kept feasible with a size + equal to the number of the constraints. + """ + def __init__(self, constraint, x0, sparse_jacobian=None, + finite_diff_bounds=(-np.inf, np.inf)): + if isinstance(constraint, NonlinearConstraint): + fun = VectorFunction(constraint.fun, x0, + constraint.jac, constraint.hess, + constraint.finite_diff_rel_step, + constraint.finite_diff_jac_sparsity, + finite_diff_bounds, sparse_jacobian) + elif isinstance(constraint, LinearConstraint): + fun = LinearVectorFunction(constraint.A, x0, sparse_jacobian) + elif isinstance(constraint, Bounds): + fun = IdentityVectorFunction(x0, sparse_jacobian) + else: + raise ValueError("`constraint` of an unknown type is passed.") + + m = fun.m + + lb = np.asarray(constraint.lb, dtype=float) + ub = np.asarray(constraint.ub, dtype=float) + keep_feasible = np.asarray(constraint.keep_feasible, dtype=bool) + + lb = np.broadcast_to(lb, m) + ub = np.broadcast_to(ub, m) + keep_feasible = np.broadcast_to(keep_feasible, m) + + if keep_feasible.shape != (m,): + raise ValueError("`keep_feasible` has a wrong shape.") + + mask = keep_feasible & (lb != ub) + f0 = fun.f + if np.any(f0[mask] < lb[mask]) or np.any(f0[mask] > ub[mask]): + raise ValueError("`x0` is infeasible with respect to some " + "inequality constraint with `keep_feasible` " + "set to True.") + + self.fun = fun + self.bounds = (lb, ub) + self.keep_feasible = keep_feasible + + def violation(self, x): + """How much the constraint is exceeded by. + + Parameters + ---------- + x : array-like + Vector of independent variables + + Returns + ------- + excess : array-like + How much the constraint is exceeded by, for each of the + constraints specified by `PreparedConstraint.fun`. + """ + with catch_warnings(): + # Ignore the following warning, it's not important when + # figuring out total violation + # UserWarning: delta_grad == 0.0. Check if the approximated + # function is linear + filterwarnings("ignore", "delta_grad", UserWarning) + ev = self.fun.fun(np.asarray(x)) + + excess_lb = np.maximum(self.bounds[0] - ev, 0) + excess_ub = np.maximum(ev - self.bounds[1], 0) + + return excess_lb + excess_ub + + +def new_bounds_to_old(lb, ub, n): + """Convert the new bounds representation to the old one. + + The new representation is a tuple (lb, ub) and the old one is a list + containing n tuples, ith containing lower and upper bound on a ith + variable. + If any of the entries in lb/ub are -np.inf/np.inf they are replaced by + None. + """ + lb = np.broadcast_to(lb, n) + ub = np.broadcast_to(ub, n) + + lb = [float(x) if x > -np.inf else None for x in lb] + ub = [float(x) if x < np.inf else None for x in ub] + + return list(zip(lb, ub)) + + +def old_bound_to_new(bounds): + """Convert the old bounds representation to the new one. + + The new representation is a tuple (lb, ub) and the old one is a list + containing n tuples, ith containing lower and upper bound on a ith + variable. + If any of the entries in lb/ub are None they are replaced by + -np.inf/np.inf. + """ + lb, ub = zip(*bounds) + + # Convert occurrences of None to -inf or inf, and replace occurrences of + # any numpy array x with x.item(). Then wrap the results in numpy arrays. + lb = np.array([float(_arr_to_scalar(x)) if x is not None else -np.inf + for x in lb]) + ub = np.array([float(_arr_to_scalar(x)) if x is not None else np.inf + for x in ub]) + + return lb, ub + + +def strict_bounds(lb, ub, keep_feasible, n_vars): + """Remove bounds which are not asked to be kept feasible.""" + strict_lb = np.resize(lb, n_vars).astype(float) + strict_ub = np.resize(ub, n_vars).astype(float) + keep_feasible = np.resize(keep_feasible, n_vars) + strict_lb[~keep_feasible] = -np.inf + strict_ub[~keep_feasible] = np.inf + return strict_lb, strict_ub + + +def new_constraint_to_old(con, x0): + """ + Converts new-style constraint objects to old-style constraint dictionaries. + """ + if isinstance(con, NonlinearConstraint): + if (con.finite_diff_jac_sparsity is not None or + con.finite_diff_rel_step is not None or + not isinstance(con.hess, BFGS) or # misses user specified BFGS + con.keep_feasible): + warn("Constraint options `finite_diff_jac_sparsity`, " + "`finite_diff_rel_step`, `keep_feasible`, and `hess`" + "are ignored by this method.", + OptimizeWarning, stacklevel=3) + + fun = con.fun + if callable(con.jac): + jac = con.jac + else: + jac = None + + else: # LinearConstraint + if np.any(con.keep_feasible): + warn("Constraint option `keep_feasible` is ignored by this method.", + OptimizeWarning, stacklevel=3) + + A = con.A + if issparse(A): + A = A.toarray() + def fun(x): + return np.dot(A, x) + def jac(x): + return A + + # FIXME: when bugs in VectorFunction/LinearVectorFunction are worked out, + # use pcon.fun.fun and pcon.fun.jac. Until then, get fun/jac above. + pcon = PreparedConstraint(con, x0) + lb, ub = pcon.bounds + + i_eq = lb == ub + i_bound_below = np.logical_xor(lb != -np.inf, i_eq) + i_bound_above = np.logical_xor(ub != np.inf, i_eq) + i_unbounded = np.logical_and(lb == -np.inf, ub == np.inf) + + if np.any(i_unbounded): + warn("At least one constraint is unbounded above and below. Such " + "constraints are ignored.", + OptimizeWarning, stacklevel=3) + + ceq = [] + if np.any(i_eq): + def f_eq(x): + y = np.array(fun(x)).flatten() + return y[i_eq] - lb[i_eq] + ceq = [{"type": "eq", "fun": f_eq}] + + if jac is not None: + def j_eq(x): + dy = jac(x) + if issparse(dy): + dy = dy.toarray() + dy = np.atleast_2d(dy) + return dy[i_eq, :] + ceq[0]["jac"] = j_eq + + cineq = [] + n_bound_below = np.sum(i_bound_below) + n_bound_above = np.sum(i_bound_above) + if n_bound_below + n_bound_above: + def f_ineq(x): + y = np.zeros(n_bound_below + n_bound_above) + y_all = np.array(fun(x)).flatten() + y[:n_bound_below] = y_all[i_bound_below] - lb[i_bound_below] + y[n_bound_below:] = -(y_all[i_bound_above] - ub[i_bound_above]) + return y + cineq = [{"type": "ineq", "fun": f_ineq}] + + if jac is not None: + def j_ineq(x): + dy = np.zeros((n_bound_below + n_bound_above, len(x0))) + dy_all = jac(x) + if issparse(dy_all): + dy_all = dy_all.toarray() + dy_all = np.atleast_2d(dy_all) + dy[:n_bound_below, :] = dy_all[i_bound_below] + dy[n_bound_below:, :] = -dy_all[i_bound_above] + return dy + cineq[0]["jac"] = j_ineq + + old_constraints = ceq + cineq + + if len(old_constraints) > 1: + warn("Equality and inequality constraints are specified in the same " + "element of the constraint list. For efficient use with this " + "method, equality and inequality constraints should be specified " + "in separate elements of the constraint list. ", + OptimizeWarning, stacklevel=3) + return old_constraints + + +def old_constraint_to_new(ic, con): + """ + Converts old-style constraint dictionaries to new-style constraint objects. + """ + # check type + try: + ctype = con['type'].lower() + except KeyError as e: + raise KeyError('Constraint %d has no type defined.' % ic) from e + except TypeError as e: + raise TypeError( + 'Constraints must be a sequence of dictionaries.' + ) from e + except AttributeError as e: + raise TypeError("Constraint's type must be a string.") from e + else: + if ctype not in ['eq', 'ineq']: + raise ValueError(f"Unknown constraint type '{con['type']}'.") + if 'fun' not in con: + raise ValueError('Constraint %d has no function defined.' % ic) + + lb = 0 + if ctype == 'eq': + ub = 0 + else: + ub = np.inf + + jac = '2-point' + if 'args' in con: + args = con['args'] + def fun(x): + return con["fun"](x, *args) + if 'jac' in con: + def jac(x): + return con["jac"](x, *args) + else: + fun = con['fun'] + if 'jac' in con: + jac = con['jac'] + + return NonlinearConstraint(fun, lb, ub, jac) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_dcsrch.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_dcsrch.py new file mode 100644 index 0000000000000000000000000000000000000000..f8b4df4763ba4f699869431a0b6528383c2f0328 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_dcsrch.py @@ -0,0 +1,728 @@ +import numpy as np + +""" +# 2023 - ported from minpack2.dcsrch, dcstep (Fortran) to Python +c MINPACK-1 Project. June 1983. +c Argonne National Laboratory. +c Jorge J. More' and David J. Thuente. +c +c MINPACK-2 Project. November 1993. +c Argonne National Laboratory and University of Minnesota. +c Brett M. Averick, Richard G. Carter, and Jorge J. More'. +""" + +# NOTE this file was linted by black on first commit, and can be kept that way. + + +class DCSRCH: + """ + Parameters + ---------- + phi : callable phi(alpha) + Function at point `alpha` + derphi : callable phi'(alpha) + Objective function derivative. Returns a scalar. + ftol : float + A nonnegative tolerance for the sufficient decrease condition. + gtol : float + A nonnegative tolerance for the curvature condition. + xtol : float + A nonnegative relative tolerance for an acceptable step. The + subroutine exits with a warning if the relative difference between + sty and stx is less than xtol. + stpmin : float + A nonnegative lower bound for the step. + stpmax : + A nonnegative upper bound for the step. + + Notes + ----- + + This subroutine finds a step that satisfies a sufficient + decrease condition and a curvature condition. + + Each call of the subroutine updates an interval with + endpoints stx and sty. The interval is initially chosen + so that it contains a minimizer of the modified function + + psi(stp) = f(stp) - f(0) - ftol*stp*f'(0). + + If psi(stp) <= 0 and f'(stp) >= 0 for some step, then the + interval is chosen so that it contains a minimizer of f. + + The algorithm is designed to find a step that satisfies + the sufficient decrease condition + + f(stp) <= f(0) + ftol*stp*f'(0), + + and the curvature condition + + abs(f'(stp)) <= gtol*abs(f'(0)). + + If ftol is less than gtol and if, for example, the function + is bounded below, then there is always a step which satisfies + both conditions. + + If no step can be found that satisfies both conditions, then + the algorithm stops with a warning. In this case stp only + satisfies the sufficient decrease condition. + + A typical invocation of dcsrch has the following outline: + + Evaluate the function at stp = 0.0d0; store in f. + Evaluate the gradient at stp = 0.0d0; store in g. + Choose a starting step stp. + + task = 'START' + 10 continue + call dcsrch(stp,f,g,ftol,gtol,xtol,task,stpmin,stpmax, + isave,dsave) + if (task .eq. 'FG') then + Evaluate the function and the gradient at stp + go to 10 + end if + + NOTE: The user must not alter work arrays between calls. + + The subroutine statement is + + subroutine dcsrch(f,g,stp,ftol,gtol,xtol,stpmin,stpmax, + task,isave,dsave) + where + + stp is a double precision variable. + On entry stp is the current estimate of a satisfactory + step. On initial entry, a positive initial estimate + must be provided. + On exit stp is the current estimate of a satisfactory step + if task = 'FG'. If task = 'CONV' then stp satisfies + the sufficient decrease and curvature condition. + + f is a double precision variable. + On initial entry f is the value of the function at 0. + On subsequent entries f is the value of the + function at stp. + On exit f is the value of the function at stp. + + g is a double precision variable. + On initial entry g is the derivative of the function at 0. + On subsequent entries g is the derivative of the + function at stp. + On exit g is the derivative of the function at stp. + + ftol is a double precision variable. + On entry ftol specifies a nonnegative tolerance for the + sufficient decrease condition. + On exit ftol is unchanged. + + gtol is a double precision variable. + On entry gtol specifies a nonnegative tolerance for the + curvature condition. + On exit gtol is unchanged. + + xtol is a double precision variable. + On entry xtol specifies a nonnegative relative tolerance + for an acceptable step. The subroutine exits with a + warning if the relative difference between sty and stx + is less than xtol. + + On exit xtol is unchanged. + + task is a character variable of length at least 60. + On initial entry task must be set to 'START'. + On exit task indicates the required action: + + If task(1:2) = 'FG' then evaluate the function and + derivative at stp and call dcsrch again. + + If task(1:4) = 'CONV' then the search is successful. + + If task(1:4) = 'WARN' then the subroutine is not able + to satisfy the convergence conditions. The exit value of + stp contains the best point found during the search. + + If task(1:5) = 'ERROR' then there is an error in the + input arguments. + + On exit with convergence, a warning or an error, the + variable task contains additional information. + + stpmin is a double precision variable. + On entry stpmin is a nonnegative lower bound for the step. + On exit stpmin is unchanged. + + stpmax is a double precision variable. + On entry stpmax is a nonnegative upper bound for the step. + On exit stpmax is unchanged. + + isave is an integer work array of dimension 2. + + dsave is a double precision work array of dimension 13. + + Subprograms called + + MINPACK-2 ... dcstep + MINPACK-1 Project. June 1983. + Argonne National Laboratory. + Jorge J. More' and David J. Thuente. + + MINPACK-2 Project. November 1993. + Argonne National Laboratory and University of Minnesota. + Brett M. Averick, Richard G. Carter, and Jorge J. More'. + """ + + def __init__(self, phi, derphi, ftol, gtol, xtol, stpmin, stpmax): + self.stage = None + self.ginit = None + self.gtest = None + self.gx = None + self.gy = None + self.finit = None + self.fx = None + self.fy = None + self.stx = None + self.sty = None + self.stmin = None + self.stmax = None + self.width = None + self.width1 = None + + # leave all assessment of tolerances/limits to the first call of + # this object + self.ftol = ftol + self.gtol = gtol + self.xtol = xtol + self.stpmin = stpmin + self.stpmax = stpmax + + self.phi = phi + self.derphi = derphi + + def __call__(self, alpha1, phi0=None, derphi0=None, maxiter=100): + """ + Parameters + ---------- + alpha1 : float + alpha1 is the current estimate of a satisfactory + step. A positive initial estimate must be provided. + phi0 : float + the value of `phi` at 0 (if known). + derphi0 : float + the derivative of `derphi` at 0 (if known). + maxiter : int + + Returns + ------- + alpha : float + Step size, or None if no suitable step was found. + phi : float + Value of `phi` at the new point `alpha`. + phi0 : float + Value of `phi` at `alpha=0`. + task : bytes + On exit task indicates status information. + + If task[:4] == b'CONV' then the search is successful. + + If task[:4] == b'WARN' then the subroutine is not able + to satisfy the convergence conditions. The exit value of + stp contains the best point found during the search. + + If task[:5] == b'ERROR' then there is an error in the + input arguments. + """ + if phi0 is None: + phi0 = self.phi(0.0) + if derphi0 is None: + derphi0 = self.derphi(0.0) + + phi1 = phi0 + derphi1 = derphi0 + + task = b"START" + for i in range(maxiter): + stp, phi1, derphi1, task = self._iterate( + alpha1, phi1, derphi1, task + ) + + if not np.isfinite(stp): + task = b"WARN" + stp = None + break + + if task[:2] == b"FG": + alpha1 = stp + phi1 = self.phi(stp) + derphi1 = self.derphi(stp) + else: + break + else: + # maxiter reached, the line search did not converge + stp = None + task = b"WARNING: dcsrch did not converge within max iterations" + + if task[:5] == b"ERROR" or task[:4] == b"WARN": + stp = None # failed + + return stp, phi1, phi0, task + + def _iterate(self, stp, f, g, task): + """ + Parameters + ---------- + stp : float + The current estimate of a satisfactory step. On initial entry, a + positive initial estimate must be provided. + f : float + On first call f is the value of the function at 0. On subsequent + entries f should be the value of the function at stp. + g : float + On initial entry g is the derivative of the function at 0. On + subsequent entries g is the derivative of the function at stp. + task : bytes + On initial entry task must be set to 'START'. + + On exit with convergence, a warning or an error, the + variable task contains additional information. + + + Returns + ------- + stp, f, g, task: tuple + + stp : float + the current estimate of a satisfactory step if task = 'FG'. If + task = 'CONV' then stp satisfies the sufficient decrease and + curvature condition. + f : float + the value of the function at stp. + g : float + the derivative of the function at stp. + task : bytes + On exit task indicates the required action: + + If task(1:2) == b'FG' then evaluate the function and + derivative at stp and call dcsrch again. + + If task(1:4) == b'CONV' then the search is successful. + + If task(1:4) == b'WARN' then the subroutine is not able + to satisfy the convergence conditions. The exit value of + stp contains the best point found during the search. + + If task(1:5) == b'ERROR' then there is an error in the + input arguments. + """ + p5 = 0.5 + p66 = 0.66 + xtrapl = 1.1 + xtrapu = 4.0 + + if task[:5] == b"START": + if stp < self.stpmin: + task = b"ERROR: STP .LT. STPMIN" + if stp > self.stpmax: + task = b"ERROR: STP .GT. STPMAX" + if g >= 0: + task = b"ERROR: INITIAL G .GE. ZERO" + if self.ftol < 0: + task = b"ERROR: FTOL .LT. ZERO" + if self.gtol < 0: + task = b"ERROR: GTOL .LT. ZERO" + if self.xtol < 0: + task = b"ERROR: XTOL .LT. ZERO" + if self.stpmin < 0: + task = b"ERROR: STPMIN .LT. ZERO" + if self.stpmax < self.stpmin: + task = b"ERROR: STPMAX .LT. STPMIN" + + if task[:5] == b"ERROR": + return stp, f, g, task + + # Initialize local variables. + + self.brackt = False + self.stage = 1 + self.finit = f + self.ginit = g + self.gtest = self.ftol * self.ginit + self.width = self.stpmax - self.stpmin + self.width1 = self.width / p5 + + # The variables stx, fx, gx contain the values of the step, + # function, and derivative at the best step. + # The variables sty, fy, gy contain the value of the step, + # function, and derivative at sty. + # The variables stp, f, g contain the values of the step, + # function, and derivative at stp. + + self.stx = 0.0 + self.fx = self.finit + self.gx = self.ginit + self.sty = 0.0 + self.fy = self.finit + self.gy = self.ginit + self.stmin = 0 + self.stmax = stp + xtrapu * stp + task = b"FG" + return stp, f, g, task + + # in the original Fortran this was a location to restore variables + # we don't need to do that because they're attributes. + + # If psi(stp) <= 0 and f'(stp) >= 0 for some step, then the + # algorithm enters the second stage. + ftest = self.finit + stp * self.gtest + + if self.stage == 1 and f <= ftest and g >= 0: + self.stage = 2 + + # test for warnings + if self.brackt and (stp <= self.stmin or stp >= self.stmax): + task = b"WARNING: ROUNDING ERRORS PREVENT PROGRESS" + if self.brackt and self.stmax - self.stmin <= self.xtol * self.stmax: + task = b"WARNING: XTOL TEST SATISFIED" + if stp == self.stpmax and f <= ftest and g <= self.gtest: + task = b"WARNING: STP = STPMAX" + if stp == self.stpmin and (f > ftest or g >= self.gtest): + task = b"WARNING: STP = STPMIN" + + # test for convergence + if f <= ftest and abs(g) <= self.gtol * -self.ginit: + task = b"CONVERGENCE" + + # test for termination + if task[:4] == b"WARN" or task[:4] == b"CONV": + return stp, f, g, task + + # A modified function is used to predict the step during the + # first stage if a lower function value has been obtained but + # the decrease is not sufficient. + if self.stage == 1 and f <= self.fx and f > ftest: + # Define the modified function and derivative values. + fm = f - stp * self.gtest + fxm = self.fx - self.stx * self.gtest + fym = self.fy - self.sty * self.gtest + gm = g - self.gtest + gxm = self.gx - self.gtest + gym = self.gy - self.gtest + + # Call dcstep to update stx, sty, and to compute the new step. + # dcstep can have several operations which can produce NaN + # e.g. inf/inf. Filter these out. + with np.errstate(invalid="ignore", over="ignore"): + tup = dcstep( + self.stx, + fxm, + gxm, + self.sty, + fym, + gym, + stp, + fm, + gm, + self.brackt, + self.stmin, + self.stmax, + ) + self.stx, fxm, gxm, self.sty, fym, gym, stp, self.brackt = tup + + # Reset the function and derivative values for f + self.fx = fxm + self.stx * self.gtest + self.fy = fym + self.sty * self.gtest + self.gx = gxm + self.gtest + self.gy = gym + self.gtest + + else: + # Call dcstep to update stx, sty, and to compute the new step. + # dcstep can have several operations which can produce NaN + # e.g. inf/inf. Filter these out. + + with np.errstate(invalid="ignore", over="ignore"): + tup = dcstep( + self.stx, + self.fx, + self.gx, + self.sty, + self.fy, + self.gy, + stp, + f, + g, + self.brackt, + self.stmin, + self.stmax, + ) + ( + self.stx, + self.fx, + self.gx, + self.sty, + self.fy, + self.gy, + stp, + self.brackt, + ) = tup + + # Decide if a bisection step is needed + if self.brackt: + if abs(self.sty - self.stx) >= p66 * self.width1: + stp = self.stx + p5 * (self.sty - self.stx) + self.width1 = self.width + self.width = abs(self.sty - self.stx) + + # Set the minimum and maximum steps allowed for stp. + if self.brackt: + self.stmin = min(self.stx, self.sty) + self.stmax = max(self.stx, self.sty) + else: + self.stmin = stp + xtrapl * (stp - self.stx) + self.stmax = stp + xtrapu * (stp - self.stx) + + # Force the step to be within the bounds stpmax and stpmin. + stp = np.clip(stp, self.stpmin, self.stpmax) + + # If further progress is not possible, let stp be the best + # point obtained during the search. + if ( + self.brackt + and (stp <= self.stmin or stp >= self.stmax) + or ( + self.brackt + and self.stmax - self.stmin <= self.xtol * self.stmax + ) + ): + stp = self.stx + + # Obtain another function and derivative + task = b"FG" + return stp, f, g, task + + +def dcstep(stx, fx, dx, sty, fy, dy, stp, fp, dp, brackt, stpmin, stpmax): + """ + Subroutine dcstep + + This subroutine computes a safeguarded step for a search + procedure and updates an interval that contains a step that + satisfies a sufficient decrease and a curvature condition. + + The parameter stx contains the step with the least function + value. If brackt is set to .true. then a minimizer has + been bracketed in an interval with endpoints stx and sty. + The parameter stp contains the current step. + The subroutine assumes that if brackt is set to .true. then + + min(stx,sty) < stp < max(stx,sty), + + and that the derivative at stx is negative in the direction + of the step. + + The subroutine statement is + + subroutine dcstep(stx,fx,dx,sty,fy,dy,stp,fp,dp,brackt, + stpmin,stpmax) + + where + + stx is a double precision variable. + On entry stx is the best step obtained so far and is an + endpoint of the interval that contains the minimizer. + On exit stx is the updated best step. + + fx is a double precision variable. + On entry fx is the function at stx. + On exit fx is the function at stx. + + dx is a double precision variable. + On entry dx is the derivative of the function at + stx. The derivative must be negative in the direction of + the step, that is, dx and stp - stx must have opposite + signs. + On exit dx is the derivative of the function at stx. + + sty is a double precision variable. + On entry sty is the second endpoint of the interval that + contains the minimizer. + On exit sty is the updated endpoint of the interval that + contains the minimizer. + + fy is a double precision variable. + On entry fy is the function at sty. + On exit fy is the function at sty. + + dy is a double precision variable. + On entry dy is the derivative of the function at sty. + On exit dy is the derivative of the function at the exit sty. + + stp is a double precision variable. + On entry stp is the current step. If brackt is set to .true. + then on input stp must be between stx and sty. + On exit stp is a new trial step. + + fp is a double precision variable. + On entry fp is the function at stp + On exit fp is unchanged. + + dp is a double precision variable. + On entry dp is the derivative of the function at stp. + On exit dp is unchanged. + + brackt is an logical variable. + On entry brackt specifies if a minimizer has been bracketed. + Initially brackt must be set to .false. + On exit brackt specifies if a minimizer has been bracketed. + When a minimizer is bracketed brackt is set to .true. + + stpmin is a double precision variable. + On entry stpmin is a lower bound for the step. + On exit stpmin is unchanged. + + stpmax is a double precision variable. + On entry stpmax is an upper bound for the step. + On exit stpmax is unchanged. + + MINPACK-1 Project. June 1983 + Argonne National Laboratory. + Jorge J. More' and David J. Thuente. + + MINPACK-2 Project. November 1993. + Argonne National Laboratory and University of Minnesota. + Brett M. Averick and Jorge J. More'. + + """ + sgn_dp = np.sign(dp) + sgn_dx = np.sign(dx) + + # sgnd = dp * (dx / abs(dx)) + sgnd = sgn_dp * sgn_dx + + # First case: A higher function value. The minimum is bracketed. + # If the cubic step is closer to stx than the quadratic step, the + # cubic step is taken, otherwise the average of the cubic and + # quadratic steps is taken. + if fp > fx: + theta = 3.0 * (fx - fp) / (stp - stx) + dx + dp + s = max(abs(theta), abs(dx), abs(dp)) + gamma = s * np.sqrt((theta / s) ** 2 - (dx / s) * (dp / s)) + if stp < stx: + gamma *= -1 + p = (gamma - dx) + theta + q = ((gamma - dx) + gamma) + dp + r = p / q + stpc = stx + r * (stp - stx) + stpq = stx + ((dx / ((fx - fp) / (stp - stx) + dx)) / 2.0) * (stp - stx) + if abs(stpc - stx) <= abs(stpq - stx): + stpf = stpc + else: + stpf = stpc + (stpq - stpc) / 2.0 + brackt = True + elif sgnd < 0.0: + # Second case: A lower function value and derivatives of opposite + # sign. The minimum is bracketed. If the cubic step is farther from + # stp than the secant step, the cubic step is taken, otherwise the + # secant step is taken. + theta = 3 * (fx - fp) / (stp - stx) + dx + dp + s = max(abs(theta), abs(dx), abs(dp)) + gamma = s * np.sqrt((theta / s) ** 2 - (dx / s) * (dp / s)) + if stp > stx: + gamma *= -1 + p = (gamma - dp) + theta + q = ((gamma - dp) + gamma) + dx + r = p / q + stpc = stp + r * (stx - stp) + stpq = stp + (dp / (dp - dx)) * (stx - stp) + if abs(stpc - stp) > abs(stpq - stp): + stpf = stpc + else: + stpf = stpq + brackt = True + elif abs(dp) < abs(dx): + # Third case: A lower function value, derivatives of the same sign, + # and the magnitude of the derivative decreases. + + # The cubic step is computed only if the cubic tends to infinity + # in the direction of the step or if the minimum of the cubic + # is beyond stp. Otherwise the cubic step is defined to be the + # secant step. + theta = 3 * (fx - fp) / (stp - stx) + dx + dp + s = max(abs(theta), abs(dx), abs(dp)) + + # The case gamma = 0 only arises if the cubic does not tend + # to infinity in the direction of the step. + gamma = s * np.sqrt(max(0, (theta / s) ** 2 - (dx / s) * (dp / s))) + if stp > stx: + gamma = -gamma + p = (gamma - dp) + theta + q = (gamma + (dx - dp)) + gamma + r = p / q + if r < 0 and gamma != 0: + stpc = stp + r * (stx - stp) + elif stp > stx: + stpc = stpmax + else: + stpc = stpmin + stpq = stp + (dp / (dp - dx)) * (stx - stp) + + if brackt: + # A minimizer has been bracketed. If the cubic step is + # closer to stp than the secant step, the cubic step is + # taken, otherwise the secant step is taken. + if abs(stpc - stp) < abs(stpq - stp): + stpf = stpc + else: + stpf = stpq + + if stp > stx: + stpf = min(stp + 0.66 * (sty - stp), stpf) + else: + stpf = max(stp + 0.66 * (sty - stp), stpf) + else: + # A minimizer has not been bracketed. If the cubic step is + # farther from stp than the secant step, the cubic step is + # taken, otherwise the secant step is taken. + if abs(stpc - stp) > abs(stpq - stp): + stpf = stpc + else: + stpf = stpq + stpf = np.clip(stpf, stpmin, stpmax) + + else: + # Fourth case: A lower function value, derivatives of the same sign, + # and the magnitude of the derivative does not decrease. If the + # minimum is not bracketed, the step is either stpmin or stpmax, + # otherwise the cubic step is taken. + if brackt: + theta = 3.0 * (fp - fy) / (sty - stp) + dy + dp + s = max(abs(theta), abs(dy), abs(dp)) + gamma = s * np.sqrt((theta / s) ** 2 - (dy / s) * (dp / s)) + if stp > sty: + gamma = -gamma + p = (gamma - dp) + theta + q = ((gamma - dp) + gamma) + dy + r = p / q + stpc = stp + r * (sty - stp) + stpf = stpc + elif stp > stx: + stpf = stpmax + else: + stpf = stpmin + + # Update the interval which contains a minimizer. + if fp > fx: + sty = stp + fy = fp + dy = dp + else: + if sgnd < 0: + sty = stx + fy = fx + dy = dx + stx = stp + fx = fp + dx = dp + + # Compute the new step. + stp = stpf + + return stx, fx, dx, sty, fy, dy, stp, brackt diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_differentiable_functions.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_differentiable_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..afbb2152c21a7837e77a6a77b3d8f1f6b0114270 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_differentiable_functions.py @@ -0,0 +1,694 @@ +import numpy as np +import scipy.sparse as sps +from ._numdiff import approx_derivative, group_columns +from ._hessian_update_strategy import HessianUpdateStrategy +from scipy.sparse.linalg import LinearOperator +from scipy._lib._array_api import array_namespace +from scipy._lib import array_api_extra as xpx + + +FD_METHODS = ('2-point', '3-point', 'cs') + + +def _wrapper_fun(fun, args=()): + ncalls = [0] + + def wrapped(x): + ncalls[0] += 1 + # Send a copy because the user may overwrite it. + # Overwriting results in undefined behaviour because + # fun(self.x) will change self.x, with the two no longer linked. + fx = fun(np.copy(x), *args) + # Make sure the function returns a true scalar + if not np.isscalar(fx): + try: + fx = np.asarray(fx).item() + except (TypeError, ValueError) as e: + raise ValueError( + "The user-provided objective function " + "must return a scalar value." + ) from e + return fx + return wrapped, ncalls + + +def _wrapper_grad(grad, fun=None, args=(), finite_diff_options=None): + ncalls = [0] + + if callable(grad): + def wrapped(x, **kwds): + # kwds present to give function same signature as numdiff variant + ncalls[0] += 1 + return np.atleast_1d(grad(np.copy(x), *args)) + return wrapped, ncalls + + elif grad in FD_METHODS: + def wrapped1(x, f0=None): + ncalls[0] += 1 + return approx_derivative( + fun, x, f0=f0, **finite_diff_options + ) + + return wrapped1, ncalls + + +def _wrapper_hess(hess, grad=None, x0=None, args=(), finite_diff_options=None): + if callable(hess): + H = hess(np.copy(x0), *args) + ncalls = [1] + + if sps.issparse(H): + def wrapped(x, **kwds): + ncalls[0] += 1 + return sps.csr_matrix(hess(np.copy(x), *args)) + + H = sps.csr_matrix(H) + + elif isinstance(H, LinearOperator): + def wrapped(x, **kwds): + ncalls[0] += 1 + return hess(np.copy(x), *args) + + else: # dense + def wrapped(x, **kwds): + ncalls[0] += 1 + return np.atleast_2d(np.asarray(hess(np.copy(x), *args))) + + H = np.atleast_2d(np.asarray(H)) + + return wrapped, ncalls, H + elif hess in FD_METHODS: + ncalls = [0] + + def wrapped1(x, f0=None): + return approx_derivative( + grad, x, f0=f0, **finite_diff_options + ) + + return wrapped1, ncalls, None + + +class ScalarFunction: + """Scalar function and its derivatives. + + This class defines a scalar function F: R^n->R and methods for + computing or approximating its first and second derivatives. + + Parameters + ---------- + fun : callable + evaluates the scalar function. Must be of the form ``fun(x, *args)``, + where ``x`` is the argument in the form of a 1-D array and ``args`` is + a tuple of any additional fixed parameters needed to completely specify + the function. Should return a scalar. + x0 : array-like + Provides an initial set of variables for evaluating fun. Array of real + elements of size (n,), where 'n' is the number of independent + variables. + args : tuple, optional + Any additional fixed parameters needed to completely specify the scalar + function. + grad : {callable, '2-point', '3-point', 'cs'} + Method for computing the gradient vector. + If it is a callable, it should be a function that returns the gradient + vector: + + ``grad(x, *args) -> array_like, shape (n,)`` + + where ``x`` is an array with shape (n,) and ``args`` is a tuple with + the fixed parameters. + Alternatively, the keywords {'2-point', '3-point', 'cs'} can be used + to select a finite difference scheme for numerical estimation of the + gradient with a relative step size. These finite difference schemes + obey any specified `bounds`. + hess : {callable, '2-point', '3-point', 'cs', HessianUpdateStrategy} + Method for computing the Hessian matrix. If it is callable, it should + return the Hessian matrix: + + ``hess(x, *args) -> {LinearOperator, spmatrix, array}, (n, n)`` + + where x is a (n,) ndarray and `args` is a tuple with the fixed + parameters. Alternatively, the keywords {'2-point', '3-point', 'cs'} + select a finite difference scheme for numerical estimation. Or, objects + implementing `HessianUpdateStrategy` interface can be used to + approximate the Hessian. + Whenever the gradient is estimated via finite-differences, the Hessian + cannot be estimated with options {'2-point', '3-point', 'cs'} and needs + to be estimated using one of the quasi-Newton strategies. + finite_diff_rel_step : None or array_like + Relative step size to use. The absolute step size is computed as + ``h = finite_diff_rel_step * sign(x0) * max(1, abs(x0))``, possibly + adjusted to fit into the bounds. For ``method='3-point'`` the sign + of `h` is ignored. If None then finite_diff_rel_step is selected + automatically, + finite_diff_bounds : tuple of array_like + Lower and upper bounds on independent variables. Defaults to no bounds, + (-np.inf, np.inf). Each bound must match the size of `x0` or be a + scalar, in the latter case the bound will be the same for all + variables. Use it to limit the range of function evaluation. + epsilon : None or array_like, optional + Absolute step size to use, possibly adjusted to fit into the bounds. + For ``method='3-point'`` the sign of `epsilon` is ignored. By default + relative steps are used, only if ``epsilon is not None`` are absolute + steps used. + + Notes + ----- + This class implements a memoization logic. There are methods `fun`, + `grad`, hess` and corresponding attributes `f`, `g` and `H`. The following + things should be considered: + + 1. Use only public methods `fun`, `grad` and `hess`. + 2. After one of the methods is called, the corresponding attribute + will be set. However, a subsequent call with a different argument + of *any* of the methods may overwrite the attribute. + """ + def __init__(self, fun, x0, args, grad, hess, finite_diff_rel_step, + finite_diff_bounds, epsilon=None): + if not callable(grad) and grad not in FD_METHODS: + raise ValueError( + f"`grad` must be either callable or one of {FD_METHODS}." + ) + + if not (callable(hess) or hess in FD_METHODS + or isinstance(hess, HessianUpdateStrategy)): + raise ValueError( + f"`hess` must be either callable, HessianUpdateStrategy" + f" or one of {FD_METHODS}." + ) + + if grad in FD_METHODS and hess in FD_METHODS: + raise ValueError("Whenever the gradient is estimated via " + "finite-differences, we require the Hessian " + "to be estimated using one of the " + "quasi-Newton strategies.") + + self.xp = xp = array_namespace(x0) + _x = xpx.atleast_nd(xp.asarray(x0), ndim=1, xp=xp) + _dtype = xp.float64 + if xp.isdtype(_x.dtype, "real floating"): + _dtype = _x.dtype + + # original arguments + self._wrapped_fun, self._nfev = _wrapper_fun(fun, args=args) + self._orig_fun = fun + self._orig_grad = grad + self._orig_hess = hess + self._args = args + + # promotes to floating + self.x = xp.astype(_x, _dtype) + self.x_dtype = _dtype + self.n = self.x.size + self.f_updated = False + self.g_updated = False + self.H_updated = False + + self._lowest_x = None + self._lowest_f = np.inf + + finite_diff_options = {} + if grad in FD_METHODS: + finite_diff_options["method"] = grad + finite_diff_options["rel_step"] = finite_diff_rel_step + finite_diff_options["abs_step"] = epsilon + finite_diff_options["bounds"] = finite_diff_bounds + if hess in FD_METHODS: + finite_diff_options["method"] = hess + finite_diff_options["rel_step"] = finite_diff_rel_step + finite_diff_options["abs_step"] = epsilon + finite_diff_options["as_linear_operator"] = True + + # Initial function evaluation + self._update_fun() + + # Initial gradient evaluation + self._wrapped_grad, self._ngev = _wrapper_grad( + grad, + fun=self._wrapped_fun, + args=args, + finite_diff_options=finite_diff_options + ) + self._update_grad() + + # Hessian evaluation + if callable(hess): + self._wrapped_hess, self._nhev, self.H = _wrapper_hess( + hess, x0=x0, args=args + ) + self.H_updated = True + elif hess in FD_METHODS: + self._wrapped_hess, self._nhev, self.H = _wrapper_hess( + hess, + grad=self._wrapped_grad, + x0=x0, + finite_diff_options=finite_diff_options + ) + self._update_grad() + self.H = self._wrapped_hess(self.x, f0=self.g) + self.H_updated = True + elif isinstance(hess, HessianUpdateStrategy): + self.H = hess + self.H.initialize(self.n, 'hess') + self.H_updated = True + self.x_prev = None + self.g_prev = None + self._nhev = [0] + + @property + def nfev(self): + return self._nfev[0] + + @property + def ngev(self): + return self._ngev[0] + + @property + def nhev(self): + return self._nhev[0] + + def _update_x(self, x): + if isinstance(self._orig_hess, HessianUpdateStrategy): + self._update_grad() + self.x_prev = self.x + self.g_prev = self.g + # ensure that self.x is a copy of x. Don't store a reference + # otherwise the memoization doesn't work properly. + + _x = xpx.atleast_nd(self.xp.asarray(x), ndim=1, xp=self.xp) + self.x = self.xp.astype(_x, self.x_dtype) + self.f_updated = False + self.g_updated = False + self.H_updated = False + self._update_hess() + else: + # ensure that self.x is a copy of x. Don't store a reference + # otherwise the memoization doesn't work properly. + _x = xpx.atleast_nd(self.xp.asarray(x), ndim=1, xp=self.xp) + self.x = self.xp.astype(_x, self.x_dtype) + self.f_updated = False + self.g_updated = False + self.H_updated = False + + def _update_fun(self): + if not self.f_updated: + fx = self._wrapped_fun(self.x) + if fx < self._lowest_f: + self._lowest_x = self.x + self._lowest_f = fx + + self.f = fx + self.f_updated = True + + def _update_grad(self): + if not self.g_updated: + if self._orig_grad in FD_METHODS: + self._update_fun() + self.g = self._wrapped_grad(self.x, f0=self.f) + self.g_updated = True + + def _update_hess(self): + if not self.H_updated: + if self._orig_hess in FD_METHODS: + self._update_grad() + self.H = self._wrapped_hess(self.x, f0=self.g) + elif isinstance(self._orig_hess, HessianUpdateStrategy): + self._update_grad() + self.H.update(self.x - self.x_prev, self.g - self.g_prev) + else: # should be callable(hess) + self.H = self._wrapped_hess(self.x) + + self.H_updated = True + + def fun(self, x): + if not np.array_equal(x, self.x): + self._update_x(x) + self._update_fun() + return self.f + + def grad(self, x): + if not np.array_equal(x, self.x): + self._update_x(x) + self._update_grad() + return self.g + + def hess(self, x): + if not np.array_equal(x, self.x): + self._update_x(x) + self._update_hess() + return self.H + + def fun_and_grad(self, x): + if not np.array_equal(x, self.x): + self._update_x(x) + self._update_fun() + self._update_grad() + return self.f, self.g + + +class VectorFunction: + """Vector function and its derivatives. + + This class defines a vector function F: R^n->R^m and methods for + computing or approximating its first and second derivatives. + + Notes + ----- + This class implements a memoization logic. There are methods `fun`, + `jac`, hess` and corresponding attributes `f`, `J` and `H`. The following + things should be considered: + + 1. Use only public methods `fun`, `jac` and `hess`. + 2. After one of the methods is called, the corresponding attribute + will be set. However, a subsequent call with a different argument + of *any* of the methods may overwrite the attribute. + """ + def __init__(self, fun, x0, jac, hess, + finite_diff_rel_step, finite_diff_jac_sparsity, + finite_diff_bounds, sparse_jacobian): + if not callable(jac) and jac not in FD_METHODS: + raise ValueError(f"`jac` must be either callable or one of {FD_METHODS}.") + + if not (callable(hess) or hess in FD_METHODS + or isinstance(hess, HessianUpdateStrategy)): + raise ValueError("`hess` must be either callable," + f"HessianUpdateStrategy or one of {FD_METHODS}.") + + if jac in FD_METHODS and hess in FD_METHODS: + raise ValueError("Whenever the Jacobian is estimated via " + "finite-differences, we require the Hessian to " + "be estimated using one of the quasi-Newton " + "strategies.") + + self.xp = xp = array_namespace(x0) + _x = xpx.atleast_nd(xp.asarray(x0), ndim=1, xp=xp) + _dtype = xp.float64 + if xp.isdtype(_x.dtype, "real floating"): + _dtype = _x.dtype + + # promotes to floating + self.x = xp.astype(_x, _dtype) + self.x_dtype = _dtype + + self.n = self.x.size + self.nfev = 0 + self.njev = 0 + self.nhev = 0 + self.f_updated = False + self.J_updated = False + self.H_updated = False + + finite_diff_options = {} + if jac in FD_METHODS: + finite_diff_options["method"] = jac + finite_diff_options["rel_step"] = finite_diff_rel_step + if finite_diff_jac_sparsity is not None: + sparsity_groups = group_columns(finite_diff_jac_sparsity) + finite_diff_options["sparsity"] = (finite_diff_jac_sparsity, + sparsity_groups) + finite_diff_options["bounds"] = finite_diff_bounds + self.x_diff = np.copy(self.x) + if hess in FD_METHODS: + finite_diff_options["method"] = hess + finite_diff_options["rel_step"] = finite_diff_rel_step + finite_diff_options["as_linear_operator"] = True + self.x_diff = np.copy(self.x) + if jac in FD_METHODS and hess in FD_METHODS: + raise ValueError("Whenever the Jacobian is estimated via " + "finite-differences, we require the Hessian to " + "be estimated using one of the quasi-Newton " + "strategies.") + + # Function evaluation + def fun_wrapped(x): + self.nfev += 1 + return np.atleast_1d(fun(x)) + + def update_fun(): + self.f = fun_wrapped(self.x) + + self._update_fun_impl = update_fun + update_fun() + + self.v = np.zeros_like(self.f) + self.m = self.v.size + + # Jacobian Evaluation + if callable(jac): + self.J = jac(self.x) + self.J_updated = True + self.njev += 1 + + if (sparse_jacobian or + sparse_jacobian is None and sps.issparse(self.J)): + def jac_wrapped(x): + self.njev += 1 + return sps.csr_matrix(jac(x)) + self.J = sps.csr_matrix(self.J) + self.sparse_jacobian = True + + elif sps.issparse(self.J): + def jac_wrapped(x): + self.njev += 1 + return jac(x).toarray() + self.J = self.J.toarray() + self.sparse_jacobian = False + + else: + def jac_wrapped(x): + self.njev += 1 + return np.atleast_2d(jac(x)) + self.J = np.atleast_2d(self.J) + self.sparse_jacobian = False + + def update_jac(): + self.J = jac_wrapped(self.x) + + elif jac in FD_METHODS: + self.J = approx_derivative(fun_wrapped, self.x, f0=self.f, + **finite_diff_options) + self.J_updated = True + + if (sparse_jacobian or + sparse_jacobian is None and sps.issparse(self.J)): + def update_jac(): + self._update_fun() + self.J = sps.csr_matrix( + approx_derivative(fun_wrapped, self.x, f0=self.f, + **finite_diff_options)) + self.J = sps.csr_matrix(self.J) + self.sparse_jacobian = True + + elif sps.issparse(self.J): + def update_jac(): + self._update_fun() + self.J = approx_derivative(fun_wrapped, self.x, f0=self.f, + **finite_diff_options).toarray() + self.J = self.J.toarray() + self.sparse_jacobian = False + + else: + def update_jac(): + self._update_fun() + self.J = np.atleast_2d( + approx_derivative(fun_wrapped, self.x, f0=self.f, + **finite_diff_options)) + self.J = np.atleast_2d(self.J) + self.sparse_jacobian = False + + self._update_jac_impl = update_jac + + # Define Hessian + if callable(hess): + self.H = hess(self.x, self.v) + self.H_updated = True + self.nhev += 1 + + if sps.issparse(self.H): + def hess_wrapped(x, v): + self.nhev += 1 + return sps.csr_matrix(hess(x, v)) + self.H = sps.csr_matrix(self.H) + + elif isinstance(self.H, LinearOperator): + def hess_wrapped(x, v): + self.nhev += 1 + return hess(x, v) + + else: + def hess_wrapped(x, v): + self.nhev += 1 + return np.atleast_2d(np.asarray(hess(x, v))) + self.H = np.atleast_2d(np.asarray(self.H)) + + def update_hess(): + self.H = hess_wrapped(self.x, self.v) + elif hess in FD_METHODS: + def jac_dot_v(x, v): + return jac_wrapped(x).T.dot(v) + + def update_hess(): + self._update_jac() + self.H = approx_derivative(jac_dot_v, self.x, + f0=self.J.T.dot(self.v), + args=(self.v,), + **finite_diff_options) + update_hess() + self.H_updated = True + elif isinstance(hess, HessianUpdateStrategy): + self.H = hess + self.H.initialize(self.n, 'hess') + self.H_updated = True + self.x_prev = None + self.J_prev = None + + def update_hess(): + self._update_jac() + # When v is updated before x was updated, then x_prev and + # J_prev are None and we need this check. + if self.x_prev is not None and self.J_prev is not None: + delta_x = self.x - self.x_prev + delta_g = self.J.T.dot(self.v) - self.J_prev.T.dot(self.v) + self.H.update(delta_x, delta_g) + + self._update_hess_impl = update_hess + + if isinstance(hess, HessianUpdateStrategy): + def update_x(x): + self._update_jac() + self.x_prev = self.x + self.J_prev = self.J + _x = xpx.atleast_nd(self.xp.asarray(x), ndim=1, xp=self.xp) + self.x = self.xp.astype(_x, self.x_dtype) + self.f_updated = False + self.J_updated = False + self.H_updated = False + self._update_hess() + else: + def update_x(x): + _x = xpx.atleast_nd(self.xp.asarray(x), ndim=1, xp=self.xp) + self.x = self.xp.astype(_x, self.x_dtype) + self.f_updated = False + self.J_updated = False + self.H_updated = False + + self._update_x_impl = update_x + + def _update_v(self, v): + if not np.array_equal(v, self.v): + self.v = v + self.H_updated = False + + def _update_x(self, x): + if not np.array_equal(x, self.x): + self._update_x_impl(x) + + def _update_fun(self): + if not self.f_updated: + self._update_fun_impl() + self.f_updated = True + + def _update_jac(self): + if not self.J_updated: + self._update_jac_impl() + self.J_updated = True + + def _update_hess(self): + if not self.H_updated: + self._update_hess_impl() + self.H_updated = True + + def fun(self, x): + self._update_x(x) + self._update_fun() + return self.f + + def jac(self, x): + self._update_x(x) + self._update_jac() + return self.J + + def hess(self, x, v): + # v should be updated before x. + self._update_v(v) + self._update_x(x) + self._update_hess() + return self.H + + +class LinearVectorFunction: + """Linear vector function and its derivatives. + + Defines a linear function F = A x, where x is N-D vector and + A is m-by-n matrix. The Jacobian is constant and equals to A. The Hessian + is identically zero and it is returned as a csr matrix. + """ + def __init__(self, A, x0, sparse_jacobian): + if sparse_jacobian or sparse_jacobian is None and sps.issparse(A): + self.J = sps.csr_matrix(A) + self.sparse_jacobian = True + elif sps.issparse(A): + self.J = A.toarray() + self.sparse_jacobian = False + else: + # np.asarray makes sure A is ndarray and not matrix + self.J = np.atleast_2d(np.asarray(A)) + self.sparse_jacobian = False + + self.m, self.n = self.J.shape + + self.xp = xp = array_namespace(x0) + _x = xpx.atleast_nd(xp.asarray(x0), ndim=1, xp=xp) + _dtype = xp.float64 + if xp.isdtype(_x.dtype, "real floating"): + _dtype = _x.dtype + + # promotes to floating + self.x = xp.astype(_x, _dtype) + self.x_dtype = _dtype + + self.f = self.J.dot(self.x) + self.f_updated = True + + self.v = np.zeros(self.m, dtype=float) + self.H = sps.csr_matrix((self.n, self.n)) + + def _update_x(self, x): + if not np.array_equal(x, self.x): + _x = xpx.atleast_nd(self.xp.asarray(x), ndim=1, xp=self.xp) + self.x = self.xp.astype(_x, self.x_dtype) + self.f_updated = False + + def fun(self, x): + self._update_x(x) + if not self.f_updated: + self.f = self.J.dot(x) + self.f_updated = True + return self.f + + def jac(self, x): + self._update_x(x) + return self.J + + def hess(self, x, v): + self._update_x(x) + self.v = v + return self.H + + +class IdentityVectorFunction(LinearVectorFunction): + """Identity vector function and its derivatives. + + The Jacobian is the identity matrix, returned as a dense array when + `sparse_jacobian=False` and as a csr matrix otherwise. The Hessian is + identically zero and it is returned as a csr matrix. + """ + def __init__(self, x0, sparse_jacobian): + n = len(x0) + if sparse_jacobian or sparse_jacobian is None: + A = sps.eye(n, format='csr') + sparse_jacobian = True + else: + A = np.eye(n) + sparse_jacobian = False + super().__init__(A, x0, sparse_jacobian) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_differentialevolution.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_differentialevolution.py new file mode 100644 index 0000000000000000000000000000000000000000..70097b7aea61d3eec9f9dabadd4820e7576b44ce --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_differentialevolution.py @@ -0,0 +1,1969 @@ +""" +differential_evolution: The differential evolution global optimization algorithm +Added by Andrew Nelson 2014 +""" +import warnings + +import numpy as np +from scipy.optimize import OptimizeResult, minimize +from scipy.optimize._optimize import _status_message, _wrap_callback +from scipy._lib._util import (check_random_state, MapWrapper, _FunctionWrapper, + rng_integers, _transition_to_rng) + +from scipy.optimize._constraints import (Bounds, new_bounds_to_old, + NonlinearConstraint, LinearConstraint) +from scipy.sparse import issparse + +__all__ = ['differential_evolution'] + + +_MACHEPS = np.finfo(np.float64).eps + + +@_transition_to_rng("seed", position_num=9) +def differential_evolution(func, bounds, args=(), strategy='best1bin', + maxiter=1000, popsize=15, tol=0.01, + mutation=(0.5, 1), recombination=0.7, rng=None, + callback=None, disp=False, polish=True, + init='latinhypercube', atol=0, updating='immediate', + workers=1, constraints=(), x0=None, *, + integrality=None, vectorized=False): + r"""Finds the global minimum of a multivariate function. + + The differential evolution method [1]_ is stochastic in nature. It does + not use gradient methods to find the minimum, and can search large areas + of candidate space, but often requires larger numbers of function + evaluations than conventional gradient-based techniques. + + The algorithm is due to Storn and Price [2]_. + + Parameters + ---------- + func : callable + The objective function to be minimized. Must be in the form + ``f(x, *args)``, where ``x`` is the argument in the form of a 1-D array + and ``args`` is a tuple of any additional fixed parameters needed to + completely specify the function. The number of parameters, N, is equal + to ``len(x)``. + bounds : sequence or `Bounds` + Bounds for variables. There are two ways to specify the bounds: + + 1. Instance of `Bounds` class. + 2. ``(min, max)`` pairs for each element in ``x``, defining the + finite lower and upper bounds for the optimizing argument of + `func`. + + The total number of bounds is used to determine the number of + parameters, N. If there are parameters whose bounds are equal the total + number of free parameters is ``N - N_equal``. + + args : tuple, optional + Any additional fixed parameters needed to + completely specify the objective function. + strategy : {str, callable}, optional + The differential evolution strategy to use. Should be one of: + + - 'best1bin' + - 'best1exp' + - 'rand1bin' + - 'rand1exp' + - 'rand2bin' + - 'rand2exp' + - 'randtobest1bin' + - 'randtobest1exp' + - 'currenttobest1bin' + - 'currenttobest1exp' + - 'best2exp' + - 'best2bin' + + The default is 'best1bin'. Strategies that may be implemented are + outlined in 'Notes'. + Alternatively the differential evolution strategy can be customized by + providing a callable that constructs a trial vector. The callable must + have the form ``strategy(candidate: int, population: np.ndarray, rng=None)``, + where ``candidate`` is an integer specifying which entry of the + population is being evolved, ``population`` is an array of shape + ``(S, N)`` containing all the population members (where S is the + total population size), and ``rng`` is the random number generator + being used within the solver. + ``candidate`` will be in the range ``[0, S)``. + ``strategy`` must return a trial vector with shape ``(N,)``. The + fitness of this trial vector is compared against the fitness of + ``population[candidate]``. + + .. versionchanged:: 1.12.0 + Customization of evolution strategy via a callable. + + maxiter : int, optional + The maximum number of generations over which the entire population is + evolved. The maximum number of function evaluations (with no polishing) + is: ``(maxiter + 1) * popsize * (N - N_equal)`` + popsize : int, optional + A multiplier for setting the total population size. The population has + ``popsize * (N - N_equal)`` individuals. This keyword is overridden if + an initial population is supplied via the `init` keyword. When using + ``init='sobol'`` the population size is calculated as the next power + of 2 after ``popsize * (N - N_equal)``. + tol : float, optional + Relative tolerance for convergence, the solving stops when + ``np.std(population_energies) <= atol + tol * np.abs(np.mean(population_energies))``, + where and `atol` and `tol` are the absolute and relative tolerance + respectively. + mutation : float or tuple(float, float), optional + The mutation constant. In the literature this is also known as + differential weight, being denoted by :math:`F`. + If specified as a float it should be in the range [0, 2). + If specified as a tuple ``(min, max)`` dithering is employed. Dithering + randomly changes the mutation constant on a generation by generation + basis. The mutation constant for that generation is taken from + ``U[min, max)``. Dithering can help speed convergence significantly. + Increasing the mutation constant increases the search radius, but will + slow down convergence. + recombination : float, optional + The recombination constant, should be in the range [0, 1]. In the + literature this is also known as the crossover probability, being + denoted by CR. Increasing this value allows a larger number of mutants + to progress into the next generation, but at the risk of population + stability. + rng : `numpy.random.Generator`, optional + Pseudorandom number generator state. When `rng` is None, a new + `numpy.random.Generator` is created using entropy from the + operating system. Types other than `numpy.random.Generator` are + passed to `numpy.random.default_rng` to instantiate a ``Generator``. + disp : bool, optional + Prints the evaluated `func` at every iteration. + callback : callable, optional + A callable called after each iteration. Has the signature:: + + callback(intermediate_result: OptimizeResult) + + where ``intermediate_result`` is a keyword parameter containing an + `OptimizeResult` with attributes ``x`` and ``fun``, the best solution + found so far and the objective function. Note that the name + of the parameter must be ``intermediate_result`` for the callback + to be passed an `OptimizeResult`. + + The callback also supports a signature like:: + + callback(x, convergence: float=val) + + ``val`` represents the fractional value of the population convergence. + When ``val`` is greater than ``1.0``, the function halts. + + Introspection is used to determine which of the signatures is invoked. + + Global minimization will halt if the callback raises ``StopIteration`` + or returns ``True``; any polishing is still carried out. + + .. versionchanged:: 1.12.0 + callback accepts the ``intermediate_result`` keyword. + + polish : bool, optional + If True (default), then `scipy.optimize.minimize` with the `L-BFGS-B` + method is used to polish the best population member at the end, which + can improve the minimization slightly. If a constrained problem is + being studied then the `trust-constr` method is used instead. For large + problems with many constraints, polishing can take a long time due to + the Jacobian computations. + + .. versionchanged:: 1.15.0 + If `workers` is specified then the map-like callable that wraps + `func` is supplied to `minimize` instead of it using `func` + directly. This allows the caller to control how and where the + invocations actually run. + + init : str or array-like, optional + Specify which type of population initialization is performed. Should be + one of: + + - 'latinhypercube' + - 'sobol' + - 'halton' + - 'random' + - array specifying the initial population. The array should have + shape ``(S, N)``, where S is the total population size and N is + the number of parameters. + + `init` is clipped to `bounds` before use. + + The default is 'latinhypercube'. Latin Hypercube sampling tries to + maximize coverage of the available parameter space. + + 'sobol' and 'halton' are superior alternatives and maximize even more + the parameter space. 'sobol' will enforce an initial population + size which is calculated as the next power of 2 after + ``popsize * (N - N_equal)``. 'halton' has no requirements but is a bit + less efficient. See `scipy.stats.qmc` for more details. + + 'random' initializes the population randomly - this has the drawback + that clustering can occur, preventing the whole of parameter space + being covered. Use of an array to specify a population could be used, + for example, to create a tight bunch of initial guesses in an location + where the solution is known to exist, thereby reducing time for + convergence. + atol : float, optional + Absolute tolerance for convergence, the solving stops when + ``np.std(pop) <= atol + tol * np.abs(np.mean(population_energies))``, + where and `atol` and `tol` are the absolute and relative tolerance + respectively. + updating : {'immediate', 'deferred'}, optional + If ``'immediate'``, the best solution vector is continuously updated + within a single generation [4]_. This can lead to faster convergence as + trial vectors can take advantage of continuous improvements in the best + solution. + With ``'deferred'``, the best solution vector is updated once per + generation. Only ``'deferred'`` is compatible with parallelization or + vectorization, and the `workers` and `vectorized` keywords can + over-ride this option. + + .. versionadded:: 1.2.0 + + workers : int or map-like callable, optional + If `workers` is an int the population is subdivided into `workers` + sections and evaluated in parallel + (uses `multiprocessing.Pool `). + Supply -1 to use all available CPU cores. + Alternatively supply a map-like callable, such as + `multiprocessing.Pool.map` for evaluating the population in parallel. + This evaluation is carried out as ``workers(func, iterable)``. + This option will override the `updating` keyword to + ``updating='deferred'`` if ``workers != 1``. + This option overrides the `vectorized` keyword if ``workers != 1``. + Requires that `func` be pickleable. + + .. versionadded:: 1.2.0 + + constraints : {NonLinearConstraint, LinearConstraint, Bounds} + Constraints on the solver, over and above those applied by the `bounds` + kwd. Uses the approach by Lampinen [5]_. + + .. versionadded:: 1.4.0 + + x0 : None or array-like, optional + Provides an initial guess to the minimization. Once the population has + been initialized this vector replaces the first (best) member. This + replacement is done even if `init` is given an initial population. + ``x0.shape == (N,)``. + + .. versionadded:: 1.7.0 + + integrality : 1-D array, optional + For each decision variable, a boolean value indicating whether the + decision variable is constrained to integer values. The array is + broadcast to ``(N,)``. + If any decision variables are constrained to be integral, they will not + be changed during polishing. + Only integer values lying between the lower and upper bounds are used. + If there are no integer values lying between the bounds then a + `ValueError` is raised. + + .. versionadded:: 1.9.0 + + vectorized : bool, optional + If ``vectorized is True``, `func` is sent an `x` array with + ``x.shape == (N, S)``, and is expected to return an array of shape + ``(S,)``, where `S` is the number of solution vectors to be calculated. + If constraints are applied, each of the functions used to construct + a `Constraint` object should accept an `x` array with + ``x.shape == (N, S)``, and return an array of shape ``(M, S)``, where + `M` is the number of constraint components. + This option is an alternative to the parallelization offered by + `workers`, and may help in optimization speed by reducing interpreter + overhead from multiple function calls. This keyword is ignored if + ``workers != 1``. + This option will override the `updating` keyword to + ``updating='deferred'``. + See the notes section for further discussion on when to use + ``'vectorized'``, and when to use ``'workers'``. + + .. versionadded:: 1.9.0 + + Returns + ------- + res : OptimizeResult + The optimization result represented as a `OptimizeResult` object. + Important attributes are: ``x`` the solution array, ``success`` a + Boolean flag indicating if the optimizer exited successfully, + ``message`` which describes the cause of the termination, + ``population`` the solution vectors present in the population, and + ``population_energies`` the value of the objective function for each + entry in ``population``. + See `OptimizeResult` for a description of other attributes. If `polish` + was employed, and a lower minimum was obtained by the polishing, then + OptimizeResult also contains the ``jac`` attribute. + If the eventual solution does not satisfy the applied constraints + ``success`` will be `False`. + + Notes + ----- + Differential evolution is a stochastic population based method that is + useful for global optimization problems. At each pass through the + population the algorithm mutates each candidate solution by mixing with + other candidate solutions to create a trial candidate. There are several + strategies [3]_ for creating trial candidates, which suit some problems + more than others. The 'best1bin' strategy is a good starting point for + many systems. In this strategy two members of the population are randomly + chosen. Their difference is used to mutate the best member (the 'best' in + 'best1bin'), :math:`x_0`, so far: + + .. math:: + + b' = x_0 + F \cdot (x_{r_0} - x_{r_1}) + + where :math:`F` is the `mutation` parameter. + A trial vector is then constructed. Starting with a randomly chosen ith + parameter the trial is sequentially filled (in modulo) with parameters + from ``b'`` or the original candidate. The choice of whether to use ``b'`` + or the original candidate is made with a binomial distribution (the 'bin' + in 'best1bin') - a random number in [0, 1) is generated. If this number is + less than the `recombination` constant then the parameter is loaded from + ``b'``, otherwise it is loaded from the original candidate. The final + parameter is always loaded from ``b'``. Once the trial candidate is built + its fitness is assessed. If the trial is better than the original candidate + then it takes its place. If it is also better than the best overall + candidate it also replaces that. + + The other strategies available are outlined in Qiang and + Mitchell (2014) [3]_. + + + - ``rand1`` : :math:`b' = x_{r_0} + F \cdot (x_{r_1} - x_{r_2})` + - ``rand2`` : :math:`b' = x_{r_0} + F \cdot (x_{r_1} + x_{r_2} - x_{r_3} - x_{r_4})` + - ``best1`` : :math:`b' = x_0 + F \cdot (x_{r_0} - x_{r_1})` + - ``best2`` : :math:`b' = x_0 + F \cdot (x_{r_0} + x_{r_1} - x_{r_2} - x_{r_3})` + - ``currenttobest1`` : :math:`b' = x_i + F \cdot (x_0 - x_i + x_{r_0} - x_{r_1})` + - ``randtobest1`` : :math:`b' = x_{r_0} + F \cdot (x_0 - x_{r_0} + x_{r_1} - x_{r_2})` + + where the integers :math:`r_0, r_1, r_2, r_3, r_4` are chosen randomly + from the interval [0, NP) with `NP` being the total population size and + the original candidate having index `i`. The user can fully customize the + generation of the trial candidates by supplying a callable to ``strategy``. + + To improve your chances of finding a global minimum use higher `popsize` + values, with higher `mutation` and (dithering), but lower `recombination` + values. This has the effect of widening the search radius, but slowing + convergence. + + By default the best solution vector is updated continuously within a single + iteration (``updating='immediate'``). This is a modification [4]_ of the + original differential evolution algorithm which can lead to faster + convergence as trial vectors can immediately benefit from improved + solutions. To use the original Storn and Price behaviour, updating the best + solution once per iteration, set ``updating='deferred'``. + The ``'deferred'`` approach is compatible with both parallelization and + vectorization (``'workers'`` and ``'vectorized'`` keywords). These may + improve minimization speed by using computer resources more efficiently. + The ``'workers'`` distribute calculations over multiple processors. By + default the Python `multiprocessing` module is used, but other approaches + are also possible, such as the Message Passing Interface (MPI) used on + clusters [6]_ [7]_. The overhead from these approaches (creating new + Processes, etc) may be significant, meaning that computational speed + doesn't necessarily scale with the number of processors used. + Parallelization is best suited to computationally expensive objective + functions. If the objective function is less expensive, then + ``'vectorized'`` may aid by only calling the objective function once per + iteration, rather than multiple times for all the population members; the + interpreter overhead is reduced. + + .. versionadded:: 0.15.0 + + References + ---------- + .. [1] Differential evolution, Wikipedia, + http://en.wikipedia.org/wiki/Differential_evolution + .. [2] Storn, R and Price, K, Differential Evolution - a Simple and + Efficient Heuristic for Global Optimization over Continuous Spaces, + Journal of Global Optimization, 1997, 11, 341 - 359. + .. [3] Qiang, J., Mitchell, C., A Unified Differential Evolution Algorithm + for Global Optimization, 2014, https://www.osti.gov/servlets/purl/1163659 + .. [4] Wormington, M., Panaccione, C., Matney, K. M., Bowen, D. K., - + Characterization of structures from X-ray scattering data using + genetic algorithms, Phil. Trans. R. Soc. Lond. A, 1999, 357, + 2827-2848 + .. [5] Lampinen, J., A constraint handling approach for the differential + evolution algorithm. Proceedings of the 2002 Congress on + Evolutionary Computation. CEC'02 (Cat. No. 02TH8600). Vol. 2. IEEE, + 2002. + .. [6] https://mpi4py.readthedocs.io/en/stable/ + .. [7] https://schwimmbad.readthedocs.io/en/latest/ + + + Examples + -------- + Let us consider the problem of minimizing the Rosenbrock function. This + function is implemented in `rosen` in `scipy.optimize`. + + >>> import numpy as np + >>> from scipy.optimize import rosen, differential_evolution + >>> bounds = [(0,2), (0, 2), (0, 2), (0, 2), (0, 2)] + >>> result = differential_evolution(rosen, bounds) + >>> result.x, result.fun + (array([1., 1., 1., 1., 1.]), 1.9216496320061384e-19) + + Now repeat, but with parallelization. + + >>> result = differential_evolution(rosen, bounds, updating='deferred', + ... workers=2) + >>> result.x, result.fun + (array([1., 1., 1., 1., 1.]), 1.9216496320061384e-19) + + Let's do a constrained minimization. + + >>> from scipy.optimize import LinearConstraint, Bounds + + We add the constraint that the sum of ``x[0]`` and ``x[1]`` must be less + than or equal to 1.9. This is a linear constraint, which may be written + ``A @ x <= 1.9``, where ``A = array([[1, 1]])``. This can be encoded as + a `LinearConstraint` instance: + + >>> lc = LinearConstraint([[1, 1]], -np.inf, 1.9) + + Specify limits using a `Bounds` object. + + >>> bounds = Bounds([0., 0.], [2., 2.]) + >>> result = differential_evolution(rosen, bounds, constraints=lc, + ... rng=1) + >>> result.x, result.fun + (array([0.96632622, 0.93367155]), 0.0011352416852625719) + + Next find the minimum of the Ackley function + (https://en.wikipedia.org/wiki/Test_functions_for_optimization). + + >>> def ackley(x): + ... arg1 = -0.2 * np.sqrt(0.5 * (x[0] ** 2 + x[1] ** 2)) + ... arg2 = 0.5 * (np.cos(2. * np.pi * x[0]) + np.cos(2. * np.pi * x[1])) + ... return -20. * np.exp(arg1) - np.exp(arg2) + 20. + np.e + >>> bounds = [(-5, 5), (-5, 5)] + >>> result = differential_evolution(ackley, bounds, rng=1) + >>> result.x, result.fun + (array([0., 0.]), 4.440892098500626e-16) + + The Ackley function is written in a vectorized manner, so the + ``'vectorized'`` keyword can be employed. Note the reduced number of + function evaluations. + + >>> result = differential_evolution( + ... ackley, bounds, vectorized=True, updating='deferred', rng=1 + ... ) + >>> result.x, result.fun + (array([0., 0.]), 4.440892098500626e-16) + + The following custom strategy function mimics 'best1bin': + + >>> def custom_strategy_fn(candidate, population, rng=None): + ... parameter_count = population.shape(-1) + ... mutation, recombination = 0.7, 0.9 + ... trial = np.copy(population[candidate]) + ... fill_point = rng.choice(parameter_count) + ... + ... pool = np.arange(len(population)) + ... rng.shuffle(pool) + ... + ... # two unique random numbers that aren't the same, and + ... # aren't equal to candidate. + ... idxs = [] + ... while len(idxs) < 2 and len(pool) > 0: + ... idx = pool[0] + ... pool = pool[1:] + ... if idx != candidate: + ... idxs.append(idx) + ... + ... r0, r1 = idxs[:2] + ... + ... bprime = (population[0] + mutation * + ... (population[r0] - population[r1])) + ... + ... crossovers = rng.uniform(size=parameter_count) + ... crossovers = crossovers < recombination + ... crossovers[fill_point] = True + ... trial = np.where(crossovers, bprime, trial) + ... return trial + + """# noqa: E501 + + # using a context manager means that any created Pool objects are + # cleared up. + with DifferentialEvolutionSolver(func, bounds, args=args, + strategy=strategy, + maxiter=maxiter, + popsize=popsize, tol=tol, + mutation=mutation, + recombination=recombination, + rng=rng, polish=polish, + callback=callback, + disp=disp, init=init, atol=atol, + updating=updating, + workers=workers, + constraints=constraints, + x0=x0, + integrality=integrality, + vectorized=vectorized) as solver: + ret = solver.solve() + + return ret + + +class DifferentialEvolutionSolver: + + """This class implements the differential evolution solver + + Parameters + ---------- + func : callable + The objective function to be minimized. Must be in the form + ``f(x, *args)``, where ``x`` is the argument in the form of a 1-D array + and ``args`` is a tuple of any additional fixed parameters needed to + completely specify the function. The number of parameters, N, is equal + to ``len(x)``. + bounds : sequence or `Bounds` + Bounds for variables. There are two ways to specify the bounds: + + 1. Instance of `Bounds` class. + 2. ``(min, max)`` pairs for each element in ``x``, defining the + finite lower and upper bounds for the optimizing argument of + `func`. + + The total number of bounds is used to determine the number of + parameters, N. If there are parameters whose bounds are equal the total + number of free parameters is ``N - N_equal``. + args : tuple, optional + Any additional fixed parameters needed to + completely specify the objective function. + strategy : {str, callable}, optional + The differential evolution strategy to use. Should be one of: + + - 'best1bin' + - 'best1exp' + - 'rand1bin' + - 'rand1exp' + - 'rand2bin' + - 'rand2exp' + - 'randtobest1bin' + - 'randtobest1exp' + - 'currenttobest1bin' + - 'currenttobest1exp' + - 'best2exp' + - 'best2bin' + + The default is 'best1bin'. Strategies that may be + implemented are outlined in 'Notes'. + + Alternatively the differential evolution strategy can be customized + by providing a callable that constructs a trial vector. The callable + must have the form + ``strategy(candidate: int, population: np.ndarray, rng=None)``, + where ``candidate`` is an integer specifying which entry of the + population is being evolved, ``population`` is an array of shape + ``(S, N)`` containing all the population members (where S is the + total population size), and ``rng`` is the random number generator + being used within the solver. + ``candidate`` will be in the range ``[0, S)``. + ``strategy`` must return a trial vector with shape ``(N,)``. The + fitness of this trial vector is compared against the fitness of + ``population[candidate]``. + maxiter : int, optional + The maximum number of generations over which the entire population is + evolved. The maximum number of function evaluations (with no polishing) + is: ``(maxiter + 1) * popsize * (N - N_equal)`` + popsize : int, optional + A multiplier for setting the total population size. The population has + ``popsize * (N - N_equal)`` individuals. This keyword is overridden if + an initial population is supplied via the `init` keyword. When using + ``init='sobol'`` the population size is calculated as the next power + of 2 after ``popsize * (N - N_equal)``. + tol : float, optional + Relative tolerance for convergence, the solving stops when + ``np.std(population_energies) <= atol + tol * np.abs(np.mean(population_energies))``, + where and `atol` and `tol` are the absolute and relative tolerance + respectively. + mutation : float or tuple(float, float), optional + The mutation constant. In the literature this is also known as + differential weight, being denoted by F. + If specified as a float it should be in the range [0, 2]. + If specified as a tuple ``(min, max)`` dithering is employed. Dithering + randomly changes the mutation constant on a generation by generation + basis. The mutation constant for that generation is taken from + U[min, max). Dithering can help speed convergence significantly. + Increasing the mutation constant increases the search radius, but will + slow down convergence. + recombination : float, optional + The recombination constant, should be in the range [0, 1]. In the + literature this is also known as the crossover probability, being + denoted by CR. Increasing this value allows a larger number of mutants + to progress into the next generation, but at the risk of population + stability. + + rng : {None, int, `numpy.random.Generator`}, optional + + ..versionchanged:: 1.15.0 + As part of the `SPEC-007 `_ + transition from use of `numpy.random.RandomState` to + `numpy.random.Generator` this keyword was changed from `seed` to `rng`. + For an interim period both keywords will continue to work (only specify + one of them). After the interim period using the `seed` keyword will emit + warnings. The behavior of the `seed` and `rng` keywords is outlined below. + + If `rng` is passed by keyword, types other than `numpy.random.Generator` are + passed to `numpy.random.default_rng` to instantiate a `Generator`. + If `rng` is already a `Generator` instance, then the provided instance is + used. + + If this argument is passed by position or `seed` is passed by keyword, the + behavior is: + + - If `seed` is None (or `np.random`), the `numpy.random.RandomState` + singleton is used. + - If `seed` is an int, a new `RandomState` instance is used, + seeded with `seed`. + - If `seed` is already a `Generator` or `RandomState` instance then + that instance is used. + + Specify `seed`/`rng` for repeatable minimizations. + disp : bool, optional + Prints the evaluated `func` at every iteration. + callback : callable, optional + A callable called after each iteration. Has the signature: + + ``callback(intermediate_result: OptimizeResult)`` + + where ``intermediate_result`` is a keyword parameter containing an + `OptimizeResult` with attributes ``x`` and ``fun``, the best solution + found so far and the objective function. Note that the name + of the parameter must be ``intermediate_result`` for the callback + to be passed an `OptimizeResult`. + + The callback also supports a signature like: + + ``callback(x, convergence: float=val)`` + + ``val`` represents the fractional value of the population convergence. + When ``val`` is greater than ``1.0``, the function halts. + + Introspection is used to determine which of the signatures is invoked. + + Global minimization will halt if the callback raises ``StopIteration`` + or returns ``True``; any polishing is still carried out. + + .. versionchanged:: 1.12.0 + callback accepts the ``intermediate_result`` keyword. + + polish : bool, optional + If True (default), then `scipy.optimize.minimize` with the `L-BFGS-B` + method is used to polish the best population member at the end, which + can improve the minimization slightly. If a constrained problem is + being studied then the `trust-constr` method is used instead. For large + problems with many constraints, polishing can take a long time due to + the Jacobian computations. + maxfun : int, optional + Set the maximum number of function evaluations. However, it probably + makes more sense to set `maxiter` instead. + init : str or array-like, optional + Specify which type of population initialization is performed. Should be + one of: + + - 'latinhypercube' + - 'sobol' + - 'halton' + - 'random' + - array specifying the initial population. The array should have + shape ``(S, N)``, where S is the total population size and + N is the number of parameters. + `init` is clipped to `bounds` before use. + + The default is 'latinhypercube'. Latin Hypercube sampling tries to + maximize coverage of the available parameter space. + + 'sobol' and 'halton' are superior alternatives and maximize even more + the parameter space. 'sobol' will enforce an initial population + size which is calculated as the next power of 2 after + ``popsize * (N - N_equal)``. 'halton' has no requirements but is a bit + less efficient. See `scipy.stats.qmc` for more details. + + 'random' initializes the population randomly - this has the drawback + that clustering can occur, preventing the whole of parameter space + being covered. Use of an array to specify a population could be used, + for example, to create a tight bunch of initial guesses in an location + where the solution is known to exist, thereby reducing time for + convergence. + atol : float, optional + Absolute tolerance for convergence, the solving stops when + ``np.std(pop) <= atol + tol * np.abs(np.mean(population_energies))``, + where and `atol` and `tol` are the absolute and relative tolerance + respectively. + updating : {'immediate', 'deferred'}, optional + If ``'immediate'``, the best solution vector is continuously updated + within a single generation [4]_. This can lead to faster convergence as + trial vectors can take advantage of continuous improvements in the best + solution. + With ``'deferred'``, the best solution vector is updated once per + generation. Only ``'deferred'`` is compatible with parallelization or + vectorization, and the `workers` and `vectorized` keywords can + over-ride this option. + workers : int or map-like callable, optional + If `workers` is an int the population is subdivided into `workers` + sections and evaluated in parallel + (uses `multiprocessing.Pool `). + Supply `-1` to use all cores available to the Process. + Alternatively supply a map-like callable, such as + `multiprocessing.Pool.map` for evaluating the population in parallel. + This evaluation is carried out as ``workers(func, iterable)``. + This option will override the `updating` keyword to + `updating='deferred'` if `workers != 1`. + Requires that `func` be pickleable. + constraints : {NonLinearConstraint, LinearConstraint, Bounds} + Constraints on the solver, over and above those applied by the `bounds` + kwd. Uses the approach by Lampinen. + x0 : None or array-like, optional + Provides an initial guess to the minimization. Once the population has + been initialized this vector replaces the first (best) member. This + replacement is done even if `init` is given an initial population. + ``x0.shape == (N,)``. + integrality : 1-D array, optional + For each decision variable, a boolean value indicating whether the + decision variable is constrained to integer values. The array is + broadcast to ``(N,)``. + If any decision variables are constrained to be integral, they will not + be changed during polishing. + Only integer values lying between the lower and upper bounds are used. + If there are no integer values lying between the bounds then a + `ValueError` is raised. + vectorized : bool, optional + If ``vectorized is True``, `func` is sent an `x` array with + ``x.shape == (N, S)``, and is expected to return an array of shape + ``(S,)``, where `S` is the number of solution vectors to be calculated. + If constraints are applied, each of the functions used to construct + a `Constraint` object should accept an `x` array with + ``x.shape == (N, S)``, and return an array of shape ``(M, S)``, where + `M` is the number of constraint components. + This option is an alternative to the parallelization offered by + `workers`, and may help in optimization speed. This keyword is + ignored if ``workers != 1``. + This option will override the `updating` keyword to + ``updating='deferred'``. + """ # noqa: E501 + + # Dispatch of mutation strategy method (binomial or exponential). + _binomial = {'best1bin': '_best1', + 'randtobest1bin': '_randtobest1', + 'currenttobest1bin': '_currenttobest1', + 'best2bin': '_best2', + 'rand2bin': '_rand2', + 'rand1bin': '_rand1'} + _exponential = {'best1exp': '_best1', + 'rand1exp': '_rand1', + 'randtobest1exp': '_randtobest1', + 'currenttobest1exp': '_currenttobest1', + 'best2exp': '_best2', + 'rand2exp': '_rand2'} + + __init_error_msg = ("The population initialization method must be one of " + "'latinhypercube' or 'random', or an array of shape " + "(S, N) where N is the number of parameters and S>5") + + def __init__(self, func, bounds, args=(), + strategy='best1bin', maxiter=1000, popsize=15, + tol=0.01, mutation=(0.5, 1), recombination=0.7, rng=None, + maxfun=np.inf, callback=None, disp=False, polish=True, + init='latinhypercube', atol=0, updating='immediate', + workers=1, constraints=(), x0=None, *, integrality=None, + vectorized=False): + + if callable(strategy): + # a callable strategy is going to be stored in self.strategy anyway + pass + elif strategy in self._binomial: + self.mutation_func = getattr(self, self._binomial[strategy]) + elif strategy in self._exponential: + self.mutation_func = getattr(self, self._exponential[strategy]) + else: + raise ValueError("Please select a valid mutation strategy") + self.strategy = strategy + + self.callback = _wrap_callback(callback, "differential_evolution") + self.polish = polish + + # set the updating / parallelisation options + if updating in ['immediate', 'deferred']: + self._updating = updating + + self.vectorized = vectorized + + # want to use parallelisation, but updating is immediate + if workers != 1 and updating == 'immediate': + warnings.warn("differential_evolution: the 'workers' keyword has" + " overridden updating='immediate' to" + " updating='deferred'", UserWarning, stacklevel=2) + self._updating = 'deferred' + + if vectorized and workers != 1: + warnings.warn("differential_evolution: the 'workers' keyword" + " overrides the 'vectorized' keyword", stacklevel=2) + self.vectorized = vectorized = False + + if vectorized and updating == 'immediate': + warnings.warn("differential_evolution: the 'vectorized' keyword" + " has overridden updating='immediate' to updating" + "='deferred'", UserWarning, stacklevel=2) + self._updating = 'deferred' + + # an object with a map method. + if vectorized: + def maplike_for_vectorized_func(func, x): + # send an array (N, S) to the user func, + # expect to receive (S,). Transposition is required because + # internally the population is held as (S, N) + return np.atleast_1d(func(x.T)) + workers = maplike_for_vectorized_func + + self._mapwrapper = MapWrapper(workers) + + # relative and absolute tolerances for convergence + self.tol, self.atol = tol, atol + + # Mutation constant should be in [0, 2). If specified as a sequence + # then dithering is performed. + self.scale = mutation + if (not np.all(np.isfinite(mutation)) or + np.any(np.array(mutation) >= 2) or + np.any(np.array(mutation) < 0)): + raise ValueError('The mutation constant must be a float in ' + 'U[0, 2), or specified as a tuple(min, max)' + ' where min < max and min, max are in U[0, 2).') + + self.dither = None + if hasattr(mutation, '__iter__') and len(mutation) > 1: + self.dither = [mutation[0], mutation[1]] + self.dither.sort() + + self.cross_over_probability = recombination + + # we create a wrapped function to allow the use of map (and Pool.map + # in the future) + self.func = _FunctionWrapper(func, args) + self.args = args + + # convert tuple of lower and upper bounds to limits + # [(low_0, high_0), ..., (low_n, high_n] + # -> [[low_0, ..., low_n], [high_0, ..., high_n]] + if isinstance(bounds, Bounds): + self.limits = np.array(new_bounds_to_old(bounds.lb, + bounds.ub, + len(bounds.lb)), + dtype=float).T + else: + self.limits = np.array(bounds, dtype='float').T + + if (np.size(self.limits, 0) != 2 or not + np.all(np.isfinite(self.limits))): + raise ValueError('bounds should be a sequence containing finite ' + 'real valued (min, max) pairs for each value' + ' in x') + + if maxiter is None: # the default used to be None + maxiter = 1000 + self.maxiter = maxiter + if maxfun is None: # the default used to be None + maxfun = np.inf + self.maxfun = maxfun + + # population is scaled to between [0, 1]. + # We have to scale between parameter <-> population + # save these arguments for _scale_parameter and + # _unscale_parameter. This is an optimization + self.__scale_arg1 = 0.5 * (self.limits[0] + self.limits[1]) + self.__scale_arg2 = np.fabs(self.limits[0] - self.limits[1]) + with np.errstate(divide='ignore'): + # if lb == ub then the following line will be 1/0, which is why + # we ignore the divide by zero warning. The result from 1/0 is + # inf, so replace those values by 0. + self.__recip_scale_arg2 = 1 / self.__scale_arg2 + self.__recip_scale_arg2[~np.isfinite(self.__recip_scale_arg2)] = 0 + + self.parameter_count = np.size(self.limits, 1) + + self.random_number_generator = check_random_state(rng) + + # Which parameters are going to be integers? + if np.any(integrality): + # # user has provided a truth value for integer constraints + integrality = np.broadcast_to( + integrality, + self.parameter_count + ) + integrality = np.asarray(integrality, bool) + # For integrality parameters change the limits to only allow + # integer values lying between the limits. + lb, ub = np.copy(self.limits) + + lb = np.ceil(lb) + ub = np.floor(ub) + if not (lb[integrality] <= ub[integrality]).all(): + # there's a parameter that doesn't have an integer value + # lying between the limits + raise ValueError("One of the integrality constraints does not" + " have any possible integer values between" + " the lower/upper bounds.") + nlb = np.nextafter(lb[integrality] - 0.5, np.inf) + nub = np.nextafter(ub[integrality] + 0.5, -np.inf) + + self.integrality = integrality + self.limits[0, self.integrality] = nlb + self.limits[1, self.integrality] = nub + else: + self.integrality = False + + # check for equal bounds + eb = self.limits[0] == self.limits[1] + eb_count = np.count_nonzero(eb) + + # default population initialization is a latin hypercube design, but + # there are other population initializations possible. + # the minimum is 5 because 'best2bin' requires a population that's at + # least 5 long + # 202301 - reduced population size to account for parameters with + # equal bounds. If there are no varying parameters set N to at least 1 + self.num_population_members = max( + 5, + popsize * max(1, self.parameter_count - eb_count) + ) + self.population_shape = (self.num_population_members, + self.parameter_count) + + self._nfev = 0 + # check first str otherwise will fail to compare str with array + if isinstance(init, str): + if init == 'latinhypercube': + self.init_population_lhs() + elif init == 'sobol': + # must be Ns = 2**m for Sobol' + n_s = int(2 ** np.ceil(np.log2(self.num_population_members))) + self.num_population_members = n_s + self.population_shape = (self.num_population_members, + self.parameter_count) + self.init_population_qmc(qmc_engine='sobol') + elif init == 'halton': + self.init_population_qmc(qmc_engine='halton') + elif init == 'random': + self.init_population_random() + else: + raise ValueError(self.__init_error_msg) + else: + self.init_population_array(init) + + if x0 is not None: + # scale to within unit interval and + # ensure parameters are within bounds. + x0_scaled = self._unscale_parameters(np.asarray(x0)) + if ((x0_scaled > 1.0) | (x0_scaled < 0.0)).any(): + raise ValueError( + "Some entries in x0 lay outside the specified bounds" + ) + self.population[0] = x0_scaled + + # infrastructure for constraints + self.constraints = constraints + self._wrapped_constraints = [] + + if hasattr(constraints, '__len__'): + # sequence of constraints, this will also deal with default + # keyword parameter + for c in constraints: + self._wrapped_constraints.append( + _ConstraintWrapper(c, self.x) + ) + else: + self._wrapped_constraints = [ + _ConstraintWrapper(constraints, self.x) + ] + self.total_constraints = np.sum( + [c.num_constr for c in self._wrapped_constraints] + ) + self.constraint_violation = np.zeros((self.num_population_members, 1)) + self.feasible = np.ones(self.num_population_members, bool) + + # an array to shuffle when selecting candidates. Create it here + # rather than repeatedly creating it in _select_samples. + self._random_population_index = np.arange(self.num_population_members) + self.disp = disp + + def init_population_lhs(self): + """ + Initializes the population with Latin Hypercube Sampling. + Latin Hypercube Sampling ensures that each parameter is uniformly + sampled over its range. + """ + rng = self.random_number_generator + + # Each parameter range needs to be sampled uniformly. The scaled + # parameter range ([0, 1)) needs to be split into + # `self.num_population_members` segments, each of which has the following + # size: + segsize = 1.0 / self.num_population_members + + # Within each segment we sample from a uniform random distribution. + # We need to do this sampling for each parameter. + samples = (segsize * rng.uniform(size=self.population_shape) + + # Offset each segment to cover the entire parameter range [0, 1) + + np.linspace(0., 1., self.num_population_members, + endpoint=False)[:, np.newaxis]) + + # Create an array for population of candidate solutions. + self.population = np.zeros_like(samples) + + # Initialize population of candidate solutions by permutation of the + # random samples. + for j in range(self.parameter_count): + order = rng.permutation(range(self.num_population_members)) + self.population[:, j] = samples[order, j] + + # reset population energies + self.population_energies = np.full(self.num_population_members, + np.inf) + + # reset number of function evaluations counter + self._nfev = 0 + + def init_population_qmc(self, qmc_engine): + """Initializes the population with a QMC method. + + QMC methods ensures that each parameter is uniformly + sampled over its range. + + Parameters + ---------- + qmc_engine : str + The QMC method to use for initialization. Can be one of + ``latinhypercube``, ``sobol`` or ``halton``. + + """ + from scipy.stats import qmc + + rng = self.random_number_generator + + # Create an array for population of candidate solutions. + if qmc_engine == 'latinhypercube': + sampler = qmc.LatinHypercube(d=self.parameter_count, seed=rng) + elif qmc_engine == 'sobol': + sampler = qmc.Sobol(d=self.parameter_count, seed=rng) + elif qmc_engine == 'halton': + sampler = qmc.Halton(d=self.parameter_count, seed=rng) + else: + raise ValueError(self.__init_error_msg) + + self.population = sampler.random(n=self.num_population_members) + + # reset population energies + self.population_energies = np.full(self.num_population_members, + np.inf) + + # reset number of function evaluations counter + self._nfev = 0 + + def init_population_random(self): + """ + Initializes the population at random. This type of initialization + can possess clustering, Latin Hypercube sampling is generally better. + """ + rng = self.random_number_generator + self.population = rng.uniform(size=self.population_shape) + + # reset population energies + self.population_energies = np.full(self.num_population_members, + np.inf) + + # reset number of function evaluations counter + self._nfev = 0 + + def init_population_array(self, init): + """ + Initializes the population with a user specified population. + + Parameters + ---------- + init : np.ndarray + Array specifying subset of the initial population. The array should + have shape (S, N), where N is the number of parameters. + The population is clipped to the lower and upper bounds. + """ + # make sure you're using a float array + popn = np.asarray(init, dtype=np.float64) + + if (np.size(popn, 0) < 5 or + popn.shape[1] != self.parameter_count or + len(popn.shape) != 2): + raise ValueError("The population supplied needs to have shape" + " (S, len(x)), where S > 4.") + + # scale values and clip to bounds, assigning to population + self.population = np.clip(self._unscale_parameters(popn), 0, 1) + + self.num_population_members = np.size(self.population, 0) + + self.population_shape = (self.num_population_members, + self.parameter_count) + + # reset population energies + self.population_energies = np.full(self.num_population_members, + np.inf) + + # reset number of function evaluations counter + self._nfev = 0 + + @property + def x(self): + """ + The best solution from the solver + """ + return self._scale_parameters(self.population[0]) + + @property + def convergence(self): + """ + The standard deviation of the population energies divided by their + mean. + """ + if np.any(np.isinf(self.population_energies)): + return np.inf + return (np.std(self.population_energies) / + (np.abs(np.mean(self.population_energies)) + _MACHEPS)) + + def converged(self): + """ + Return True if the solver has converged. + """ + if np.any(np.isinf(self.population_energies)): + return False + + return (np.std(self.population_energies) <= + self.atol + + self.tol * np.abs(np.mean(self.population_energies))) + + def solve(self): + """ + Runs the DifferentialEvolutionSolver. + + Returns + ------- + res : OptimizeResult + The optimization result represented as a `OptimizeResult` object. + Important attributes are: ``x`` the solution array, ``success`` a + Boolean flag indicating if the optimizer exited successfully, + ``message`` which describes the cause of the termination, + ``population`` the solution vectors present in the population, and + ``population_energies`` the value of the objective function for + each entry in ``population``. + See `OptimizeResult` for a description of other attributes. If + `polish` was employed, and a lower minimum was obtained by the + polishing, then OptimizeResult also contains the ``jac`` attribute. + If the eventual solution does not satisfy the applied constraints + ``success`` will be `False`. + """ + nit, warning_flag = 0, False + status_message = _status_message['success'] + + # The population may have just been initialized (all entries are + # np.inf). If it has you have to calculate the initial energies. + # Although this is also done in the evolve generator it's possible + # that someone can set maxiter=0, at which point we still want the + # initial energies to be calculated (the following loop isn't run). + if np.all(np.isinf(self.population_energies)): + self.feasible, self.constraint_violation = ( + self._calculate_population_feasibilities(self.population)) + + # only work out population energies for feasible solutions + self.population_energies[self.feasible] = ( + self._calculate_population_energies( + self.population[self.feasible])) + + self._promote_lowest_energy() + + # do the optimization. + for nit in range(1, self.maxiter + 1): + # evolve the population by a generation + try: + next(self) + except StopIteration: + warning_flag = True + if self._nfev > self.maxfun: + status_message = _status_message['maxfev'] + elif self._nfev == self.maxfun: + status_message = ('Maximum number of function evaluations' + ' has been reached.') + break + + if self.disp: + print(f"differential_evolution step {nit}: f(x)=" + f" {self.population_energies[0]}" + ) + + if self.callback: + c = self.tol / (self.convergence + _MACHEPS) + res = self._result(nit=nit, message="in progress") + res.convergence = c + try: + warning_flag = bool(self.callback(res)) + except StopIteration: + warning_flag = True + + if warning_flag: + status_message = 'callback function requested stop early' + + # should the solver terminate? + if warning_flag or self.converged(): + break + + else: + status_message = _status_message['maxiter'] + warning_flag = True + + DE_result = self._result( + nit=nit, message=status_message, warning_flag=warning_flag + ) + + if self.polish and not np.all(self.integrality): + # can't polish if all the parameters are integers + if np.any(self.integrality): + # set the lower/upper bounds equal so that any integrality + # constraints work. + limits, integrality = self.limits, self.integrality + limits[0, integrality] = DE_result.x[integrality] + limits[1, integrality] = DE_result.x[integrality] + + polish_method = 'L-BFGS-B' + + if self._wrapped_constraints: + polish_method = 'trust-constr' + + constr_violation = self._constraint_violation_fn(DE_result.x) + if np.any(constr_violation > 0.): + warnings.warn("differential evolution didn't find a " + "solution satisfying the constraints, " + "attempting to polish from the least " + "infeasible solution", + UserWarning, stacklevel=2) + if self.disp: + print(f"Polishing solution with '{polish_method}'") + result = minimize(lambda x: + list(self._mapwrapper(self.func, np.atleast_2d(x)))[0], + np.copy(DE_result.x), + method=polish_method, + bounds=self.limits.T, + constraints=self.constraints) + + self._nfev += result.nfev + DE_result.nfev = self._nfev + + # Polishing solution is only accepted if there is an improvement in + # cost function, the polishing was successful and the solution lies + # within the bounds. + if (result.fun < DE_result.fun and + result.success and + np.all(result.x <= self.limits[1]) and + np.all(self.limits[0] <= result.x)): + DE_result.fun = result.fun + DE_result.x = result.x + DE_result.jac = result.jac + # to keep internal state consistent + self.population_energies[0] = result.fun + self.population[0] = self._unscale_parameters(result.x) + + if self._wrapped_constraints: + DE_result.constr = [c.violation(DE_result.x) for + c in self._wrapped_constraints] + DE_result.constr_violation = np.max( + np.concatenate(DE_result.constr)) + DE_result.maxcv = DE_result.constr_violation + if DE_result.maxcv > 0: + # if the result is infeasible then success must be False + DE_result.success = False + DE_result.message = ("The solution does not satisfy the " + f"constraints, MAXCV = {DE_result.maxcv}") + + return DE_result + + def _result(self, **kwds): + # form an intermediate OptimizeResult + nit = kwds.get('nit', None) + message = kwds.get('message', None) + warning_flag = kwds.get('warning_flag', False) + result = OptimizeResult( + x=self.x, + fun=self.population_energies[0], + nfev=self._nfev, + nit=nit, + message=message, + success=(warning_flag is not True), + population=self._scale_parameters(self.population), + population_energies=self.population_energies + ) + if self._wrapped_constraints: + result.constr = [c.violation(result.x) + for c in self._wrapped_constraints] + result.constr_violation = np.max(np.concatenate(result.constr)) + result.maxcv = result.constr_violation + if result.maxcv > 0: + result.success = False + + return result + + def _calculate_population_energies(self, population): + """ + Calculate the energies of a population. + + Parameters + ---------- + population : ndarray + An array of parameter vectors normalised to [0, 1] using lower + and upper limits. Has shape ``(np.size(population, 0), N)``. + + Returns + ------- + energies : ndarray + An array of energies corresponding to each population member. If + maxfun will be exceeded during this call, then the number of + function evaluations will be reduced and energies will be + right-padded with np.inf. Has shape ``(np.size(population, 0),)`` + """ + num_members = np.size(population, 0) + # S is the number of function evals left to stay under the + # maxfun budget + S = min(num_members, self.maxfun - self._nfev) + + energies = np.full(num_members, np.inf) + + parameters_pop = self._scale_parameters(population) + try: + calc_energies = list( + self._mapwrapper(self.func, parameters_pop[0:S]) + ) + calc_energies = np.squeeze(calc_energies) + except (TypeError, ValueError) as e: + # wrong number of arguments for _mapwrapper + # or wrong length returned from the mapper + raise RuntimeError( + "The map-like callable must be of the form f(func, iterable), " + "returning a sequence of numbers the same length as 'iterable'" + ) from e + + if calc_energies.size != S: + if self.vectorized: + raise RuntimeError("The vectorized function must return an" + " array of shape (S,) when given an array" + " of shape (len(x), S)") + raise RuntimeError("func(x, *args) must return a scalar value") + + energies[0:S] = calc_energies + + if self.vectorized: + self._nfev += 1 + else: + self._nfev += S + + return energies + + def _promote_lowest_energy(self): + # swaps 'best solution' into first population entry + + idx = np.arange(self.num_population_members) + feasible_solutions = idx[self.feasible] + if feasible_solutions.size: + # find the best feasible solution + idx_t = np.argmin(self.population_energies[feasible_solutions]) + l = feasible_solutions[idx_t] + else: + # no solution was feasible, use 'best' infeasible solution, which + # will violate constraints the least + l = np.argmin(np.sum(self.constraint_violation, axis=1)) + + self.population_energies[[0, l]] = self.population_energies[[l, 0]] + self.population[[0, l], :] = self.population[[l, 0], :] + self.feasible[[0, l]] = self.feasible[[l, 0]] + self.constraint_violation[[0, l], :] = ( + self.constraint_violation[[l, 0], :]) + + def _constraint_violation_fn(self, x): + """ + Calculates total constraint violation for all the constraints, for a + set of solutions. + + Parameters + ---------- + x : ndarray + Solution vector(s). Has shape (S, N), or (N,), where S is the + number of solutions to investigate and N is the number of + parameters. + + Returns + ------- + cv : ndarray + Total violation of constraints. Has shape ``(S, M)``, where M is + the total number of constraint components (which is not necessarily + equal to len(self._wrapped_constraints)). + """ + # how many solution vectors you're calculating constraint violations + # for + S = np.size(x) // self.parameter_count + _out = np.zeros((S, self.total_constraints)) + offset = 0 + for con in self._wrapped_constraints: + # the input/output of the (vectorized) constraint function is + # {(N, S), (N,)} --> (M, S) + # The input to _constraint_violation_fn is (S, N) or (N,), so + # transpose to pass it to the constraint. The output is transposed + # from (M, S) to (S, M) for further use. + c = con.violation(x.T).T + + # The shape of c should be (M,), (1, M), or (S, M). Check for + # those shapes, as an incorrect shape indicates that the + # user constraint function didn't return the right thing, and + # the reshape operation will fail. Intercept the wrong shape + # to give a reasonable error message. I'm not sure what failure + # modes an inventive user will come up with. + if c.shape[-1] != con.num_constr or (S > 1 and c.shape[0] != S): + raise RuntimeError("An array returned from a Constraint has" + " the wrong shape. If `vectorized is False`" + " the Constraint should return an array of" + " shape (M,). If `vectorized is True` then" + " the Constraint must return an array of" + " shape (M, S), where S is the number of" + " solution vectors and M is the number of" + " constraint components in a given" + " Constraint object.") + + # the violation function may return a 1D array, but is it a + # sequence of constraints for one solution (S=1, M>=1), or the + # value of a single constraint for a sequence of solutions + # (S>=1, M=1) + c = np.reshape(c, (S, con.num_constr)) + _out[:, offset:offset + con.num_constr] = c + offset += con.num_constr + + return _out + + def _calculate_population_feasibilities(self, population): + """ + Calculate the feasibilities of a population. + + Parameters + ---------- + population : ndarray + An array of parameter vectors normalised to [0, 1] using lower + and upper limits. Has shape ``(np.size(population, 0), N)``. + + Returns + ------- + feasible, constraint_violation : ndarray, ndarray + Boolean array of feasibility for each population member, and an + array of the constraint violation for each population member. + constraint_violation has shape ``(np.size(population, 0), M)``, + where M is the number of constraints. + """ + num_members = np.size(population, 0) + if not self._wrapped_constraints: + # shortcut for no constraints + return np.ones(num_members, bool), np.zeros((num_members, 1)) + + # (S, N) + parameters_pop = self._scale_parameters(population) + + if self.vectorized: + # (S, M) + constraint_violation = np.array( + self._constraint_violation_fn(parameters_pop) + ) + else: + # (S, 1, M) + constraint_violation = np.array([self._constraint_violation_fn(x) + for x in parameters_pop]) + # if you use the list comprehension in the line above it will + # create an array of shape (S, 1, M), because each iteration + # generates an array of (1, M). In comparison the vectorized + # version returns (S, M). It's therefore necessary to remove axis 1 + constraint_violation = constraint_violation[:, 0] + + feasible = ~(np.sum(constraint_violation, axis=1) > 0) + + return feasible, constraint_violation + + def __iter__(self): + return self + + def __enter__(self): + return self + + def __exit__(self, *args): + return self._mapwrapper.__exit__(*args) + + def _accept_trial(self, energy_trial, feasible_trial, cv_trial, + energy_orig, feasible_orig, cv_orig): + """ + Trial is accepted if: + * it satisfies all constraints and provides a lower or equal objective + function value, while both the compared solutions are feasible + - or - + * it is feasible while the original solution is infeasible, + - or - + * it is infeasible, but provides a lower or equal constraint violation + for all constraint functions. + + This test corresponds to section III of Lampinen [1]_. + + Parameters + ---------- + energy_trial : float + Energy of the trial solution + feasible_trial : float + Feasibility of trial solution + cv_trial : array-like + Excess constraint violation for the trial solution + energy_orig : float + Energy of the original solution + feasible_orig : float + Feasibility of original solution + cv_orig : array-like + Excess constraint violation for the original solution + + Returns + ------- + accepted : bool + + """ + if feasible_orig and feasible_trial: + return energy_trial <= energy_orig + elif feasible_trial and not feasible_orig: + return True + elif not feasible_trial and (cv_trial <= cv_orig).all(): + # cv_trial < cv_orig would imply that both trial and orig are not + # feasible + return True + + return False + + def __next__(self): + """ + Evolve the population by a single generation + + Returns + ------- + x : ndarray + The best solution from the solver. + fun : float + Value of objective function obtained from the best solution. + """ + # the population may have just been initialized (all entries are + # np.inf). If it has you have to calculate the initial energies + if np.all(np.isinf(self.population_energies)): + self.feasible, self.constraint_violation = ( + self._calculate_population_feasibilities(self.population)) + + # only need to work out population energies for those that are + # feasible + self.population_energies[self.feasible] = ( + self._calculate_population_energies( + self.population[self.feasible])) + + self._promote_lowest_energy() + + if self.dither is not None: + self.scale = self.random_number_generator.uniform(self.dither[0], + self.dither[1]) + + if self._updating == 'immediate': + # update best solution immediately + for candidate in range(self.num_population_members): + if self._nfev > self.maxfun: + raise StopIteration + + # create a trial solution + trial = self._mutate(candidate) + + # ensuring that it's in the range [0, 1) + self._ensure_constraint(trial) + + # scale from [0, 1) to the actual parameter value + parameters = self._scale_parameters(trial) + + # determine the energy of the objective function + if self._wrapped_constraints: + cv = self._constraint_violation_fn(parameters) + feasible = False + energy = np.inf + if not np.sum(cv) > 0: + # solution is feasible + feasible = True + energy = self.func(parameters) + self._nfev += 1 + else: + feasible = True + cv = np.atleast_2d([0.]) + energy = self.func(parameters) + self._nfev += 1 + + # compare trial and population member + if self._accept_trial(energy, feasible, cv, + self.population_energies[candidate], + self.feasible[candidate], + self.constraint_violation[candidate]): + self.population[candidate] = trial + self.population_energies[candidate] = np.squeeze(energy) + self.feasible[candidate] = feasible + self.constraint_violation[candidate] = cv + + # if the trial candidate is also better than the best + # solution then promote it. + if self._accept_trial(energy, feasible, cv, + self.population_energies[0], + self.feasible[0], + self.constraint_violation[0]): + self._promote_lowest_energy() + + elif self._updating == 'deferred': + # update best solution once per generation + if self._nfev >= self.maxfun: + raise StopIteration + + # 'deferred' approach, vectorised form. + # create trial solutions + trial_pop = self._mutate_many( + np.arange(self.num_population_members) + ) + + # enforce bounds + self._ensure_constraint(trial_pop) + + # determine the energies of the objective function, but only for + # feasible trials + feasible, cv = self._calculate_population_feasibilities(trial_pop) + trial_energies = np.full(self.num_population_members, np.inf) + + # only calculate for feasible entries + trial_energies[feasible] = self._calculate_population_energies( + trial_pop[feasible]) + + # which solutions are 'improved'? + loc = [self._accept_trial(*val) for val in + zip(trial_energies, feasible, cv, self.population_energies, + self.feasible, self.constraint_violation)] + loc = np.array(loc) + self.population = np.where(loc[:, np.newaxis], + trial_pop, + self.population) + self.population_energies = np.where(loc, + trial_energies, + self.population_energies) + self.feasible = np.where(loc, + feasible, + self.feasible) + self.constraint_violation = np.where(loc[:, np.newaxis], + cv, + self.constraint_violation) + + # make sure the best solution is updated if updating='deferred'. + # put the lowest energy into the best solution position. + self._promote_lowest_energy() + + return self.x, self.population_energies[0] + + def _scale_parameters(self, trial): + """Scale from a number between 0 and 1 to parameters.""" + # trial either has shape (N, ) or (L, N), where L is the number of + # solutions being scaled + scaled = self.__scale_arg1 + (trial - 0.5) * self.__scale_arg2 + if np.count_nonzero(self.integrality): + i = np.broadcast_to(self.integrality, scaled.shape) + scaled[i] = np.round(scaled[i]) + return scaled + + def _unscale_parameters(self, parameters): + """Scale from parameters to a number between 0 and 1.""" + return (parameters - self.__scale_arg1) * self.__recip_scale_arg2 + 0.5 + + def _ensure_constraint(self, trial): + """Make sure the parameters lie between the limits.""" + mask = np.bitwise_or(trial > 1, trial < 0) + if oob := np.count_nonzero(mask): + trial[mask] = self.random_number_generator.uniform(size=oob) + + def _mutate_custom(self, candidate): + rng = self.random_number_generator + msg = ( + "strategy must have signature" + " f(candidate: int, population: np.ndarray, rng=None) returning an" + " array of shape (N,)" + ) + _population = self._scale_parameters(self.population) + if not len(np.shape(candidate)): + # single entry in population + trial = self.strategy(candidate, _population, rng=rng) + if trial.shape != (self.parameter_count,): + raise RuntimeError(msg) + else: + S = candidate.shape[0] + trial = np.array( + [self.strategy(c, _population, rng=rng) for c in candidate], + dtype=float + ) + if trial.shape != (S, self.parameter_count): + raise RuntimeError(msg) + return self._unscale_parameters(trial) + + def _mutate_many(self, candidates): + """Create trial vectors based on a mutation strategy.""" + rng = self.random_number_generator + + S = len(candidates) + if callable(self.strategy): + return self._mutate_custom(candidates) + + trial = np.copy(self.population[candidates]) + samples = np.array([self._select_samples(c, 5) for c in candidates]) + + if self.strategy in ['currenttobest1exp', 'currenttobest1bin']: + bprime = self.mutation_func(candidates, samples) + else: + bprime = self.mutation_func(samples) + + fill_point = rng_integers(rng, self.parameter_count, size=S) + crossovers = rng.uniform(size=(S, self.parameter_count)) + crossovers = crossovers < self.cross_over_probability + if self.strategy in self._binomial: + # the last one is always from the bprime vector for binomial + # If you fill in modulo with a loop you have to set the last one to + # true. If you don't use a loop then you can have any random entry + # be True. + i = np.arange(S) + crossovers[i, fill_point[i]] = True + trial = np.where(crossovers, bprime, trial) + return trial + + elif self.strategy in self._exponential: + crossovers[..., 0] = True + for j in range(S): + i = 0 + init_fill = fill_point[j] + while (i < self.parameter_count and crossovers[j, i]): + trial[j, init_fill] = bprime[j, init_fill] + init_fill = (init_fill + 1) % self.parameter_count + i += 1 + + return trial + + def _mutate(self, candidate): + """Create a trial vector based on a mutation strategy.""" + rng = self.random_number_generator + + if callable(self.strategy): + return self._mutate_custom(candidate) + + fill_point = rng_integers(rng, self.parameter_count) + samples = self._select_samples(candidate, 5) + + trial = np.copy(self.population[candidate]) + + if self.strategy in ['currenttobest1exp', 'currenttobest1bin']: + bprime = self.mutation_func(candidate, samples) + else: + bprime = self.mutation_func(samples) + + crossovers = rng.uniform(size=self.parameter_count) + crossovers = crossovers < self.cross_over_probability + if self.strategy in self._binomial: + # the last one is always from the bprime vector for binomial + # If you fill in modulo with a loop you have to set the last one to + # true. If you don't use a loop then you can have any random entry + # be True. + crossovers[fill_point] = True + trial = np.where(crossovers, bprime, trial) + return trial + + elif self.strategy in self._exponential: + i = 0 + crossovers[0] = True + while i < self.parameter_count and crossovers[i]: + trial[fill_point] = bprime[fill_point] + fill_point = (fill_point + 1) % self.parameter_count + i += 1 + + return trial + + def _best1(self, samples): + """best1bin, best1exp""" + # samples.shape == (S, 5) + # or + # samples.shape(5,) + r0, r1 = samples[..., :2].T + return (self.population[0] + self.scale * + (self.population[r0] - self.population[r1])) + + def _rand1(self, samples): + """rand1bin, rand1exp""" + r0, r1, r2 = samples[..., :3].T + return (self.population[r0] + self.scale * + (self.population[r1] - self.population[r2])) + + def _randtobest1(self, samples): + """randtobest1bin, randtobest1exp""" + r0, r1, r2 = samples[..., :3].T + bprime = np.copy(self.population[r0]) + bprime += self.scale * (self.population[0] - bprime) + bprime += self.scale * (self.population[r1] - + self.population[r2]) + return bprime + + def _currenttobest1(self, candidate, samples): + """currenttobest1bin, currenttobest1exp""" + r0, r1 = samples[..., :2].T + bprime = (self.population[candidate] + self.scale * + (self.population[0] - self.population[candidate] + + self.population[r0] - self.population[r1])) + return bprime + + def _best2(self, samples): + """best2bin, best2exp""" + r0, r1, r2, r3 = samples[..., :4].T + bprime = (self.population[0] + self.scale * + (self.population[r0] + self.population[r1] - + self.population[r2] - self.population[r3])) + + return bprime + + def _rand2(self, samples): + """rand2bin, rand2exp""" + r0, r1, r2, r3, r4 = samples[..., :5].T + bprime = (self.population[r0] + self.scale * + (self.population[r1] + self.population[r2] - + self.population[r3] - self.population[r4])) + + return bprime + + def _select_samples(self, candidate, number_samples): + """ + obtain random integers from range(self.num_population_members), + without replacement. You can't have the original candidate either. + """ + self.random_number_generator.shuffle(self._random_population_index) + idxs = self._random_population_index[:number_samples + 1] + return idxs[idxs != candidate][:number_samples] + + +class _ConstraintWrapper: + """Object to wrap/evaluate user defined constraints. + + Very similar in practice to `PreparedConstraint`, except that no evaluation + of jac/hess is performed (explicit or implicit). + + If created successfully, it will contain the attributes listed below. + + Parameters + ---------- + constraint : {`NonlinearConstraint`, `LinearConstraint`, `Bounds`} + Constraint to check and prepare. + x0 : array_like + Initial vector of independent variables, shape (N,) + + Attributes + ---------- + fun : callable + Function defining the constraint wrapped by one of the convenience + classes. + bounds : 2-tuple + Contains lower and upper bounds for the constraints --- lb and ub. + These are converted to ndarray and have a size equal to the number of + the constraints. + + Notes + ----- + _ConstraintWrapper.fun and _ConstraintWrapper.violation can get sent + arrays of shape (N, S) or (N,), where S is the number of vectors of shape + (N,) to consider constraints for. + """ + def __init__(self, constraint, x0): + self.constraint = constraint + + if isinstance(constraint, NonlinearConstraint): + def fun(x): + x = np.asarray(x) + return np.atleast_1d(constraint.fun(x)) + elif isinstance(constraint, LinearConstraint): + def fun(x): + if issparse(constraint.A): + A = constraint.A + else: + A = np.atleast_2d(constraint.A) + + res = A.dot(x) + # x either has shape (N, S) or (N) + # (M, N) x (N, S) --> (M, S) + # (M, N) x (N,) --> (M,) + # However, if (M, N) is a matrix then: + # (M, N) * (N,) --> (M, 1), we need this to be (M,) + if x.ndim == 1 and res.ndim == 2: + # deal with case that constraint.A is an np.matrix + # see gh20041 + res = np.asarray(res)[:, 0] + + return res + elif isinstance(constraint, Bounds): + def fun(x): + return np.asarray(x) + else: + raise ValueError("`constraint` of an unknown type is passed.") + + self.fun = fun + + lb = np.asarray(constraint.lb, dtype=float) + ub = np.asarray(constraint.ub, dtype=float) + + x0 = np.asarray(x0) + + # find out the number of constraints + f0 = fun(x0) + self.num_constr = m = f0.size + self.parameter_count = x0.size + + if lb.ndim == 0: + lb = np.resize(lb, m) + if ub.ndim == 0: + ub = np.resize(ub, m) + + self.bounds = (lb, ub) + + def __call__(self, x): + return np.atleast_1d(self.fun(x)) + + def violation(self, x): + """How much the constraint is exceeded by. + + Parameters + ---------- + x : array-like + Vector of independent variables, (N, S), where N is number of + parameters and S is the number of solutions to be investigated. + + Returns + ------- + excess : array-like + How much the constraint is exceeded by, for each of the + constraints specified by `_ConstraintWrapper.fun`. + Has shape (M, S) where M is the number of constraint components. + """ + # expect ev to have shape (num_constr, S) or (num_constr,) + ev = self.fun(np.asarray(x)) + + try: + excess_lb = np.maximum(self.bounds[0] - ev.T, 0) + excess_ub = np.maximum(ev.T - self.bounds[1], 0) + except ValueError as e: + raise RuntimeError("An array returned from a Constraint has" + " the wrong shape. If `vectorized is False`" + " the Constraint should return an array of" + " shape (M,). If `vectorized is True` then" + " the Constraint must return an array of" + " shape (M, S), where S is the number of" + " solution vectors and M is the number of" + " constraint components in a given" + " Constraint object.") from e + + v = (excess_lb + excess_ub).T + return v diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_direct.cpython-310-x86_64-linux-gnu.so b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_direct.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..fe89bac4a6f6b828def53da54b5eac17d45a4019 Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_direct.cpython-310-x86_64-linux-gnu.so differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_direct_py.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_direct_py.py new file mode 100644 index 0000000000000000000000000000000000000000..4c01c38747dbef4b9c71e9b593316f466f484bca --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_direct_py.py @@ -0,0 +1,280 @@ +from typing import ( # noqa: UP035 + Any, Callable, Iterable +) + +import numpy as np +from scipy.optimize import OptimizeResult +from ._constraints import old_bound_to_new, Bounds +from ._direct import direct as _direct # type: ignore + +__all__ = ['direct'] + +ERROR_MESSAGES = ( + "Number of function evaluations done is larger than maxfun={}", + "Number of iterations is larger than maxiter={}", + "u[i] < l[i] for some i", + "maxfun is too large", + "Initialization failed", + "There was an error in the creation of the sample points", + "An error occurred while the function was sampled", + "Maximum number of levels has been reached.", + "Forced stop", + "Invalid arguments", + "Out of memory", +) + +SUCCESS_MESSAGES = ( + ("The best function value found is within a relative error={} " + "of the (known) global optimum f_min"), + ("The volume of the hyperrectangle containing the lowest function value " + "found is below vol_tol={}"), + ("The side length measure of the hyperrectangle containing the lowest " + "function value found is below len_tol={}"), +) + + +def direct( + func: Callable[ + [np.ndarray[tuple[int], np.dtype[np.float64]]], + float | np.floating[Any] | np.integer[Any] | np.bool_, + ], + bounds: Iterable | Bounds, + *, + args: tuple = (), + eps: float = 1e-4, + maxfun: int | None = None, + maxiter: int = 1000, + locally_biased: bool = True, + f_min: float = -np.inf, + f_min_rtol: float = 1e-4, + vol_tol: float = 1e-16, + len_tol: float = 1e-6, + callback: Callable[ + [np.ndarray[tuple[int], np.dtype[np.float64]]], + object, + ] | None = None, +) -> OptimizeResult: + """ + Finds the global minimum of a function using the + DIRECT algorithm. + + Parameters + ---------- + func : callable + The objective function to be minimized. + ``func(x, *args) -> float`` + where ``x`` is an 1-D array with shape (n,) and ``args`` is a tuple of + the fixed parameters needed to completely specify the function. + bounds : sequence or `Bounds` + Bounds for variables. There are two ways to specify the bounds: + + 1. Instance of `Bounds` class. + 2. ``(min, max)`` pairs for each element in ``x``. + + args : tuple, optional + Any additional fixed parameters needed to + completely specify the objective function. + eps : float, optional + Minimal required difference of the objective function values + between the current best hyperrectangle and the next potentially + optimal hyperrectangle to be divided. In consequence, `eps` serves as a + tradeoff between local and global search: the smaller, the more local + the search becomes. Default is 1e-4. + maxfun : int or None, optional + Approximate upper bound on objective function evaluations. + If `None`, will be automatically set to ``1000 * N`` where ``N`` + represents the number of dimensions. Will be capped if necessary to + limit DIRECT's RAM usage to app. 1GiB. This will only occur for very + high dimensional problems and excessive `max_fun`. Default is `None`. + maxiter : int, optional + Maximum number of iterations. Default is 1000. + locally_biased : bool, optional + If `True` (default), use the locally biased variant of the + algorithm known as DIRECT_L. If `False`, use the original unbiased + DIRECT algorithm. For hard problems with many local minima, + `False` is recommended. + f_min : float, optional + Function value of the global optimum. Set this value only if the + global optimum is known. Default is ``-np.inf``, so that this + termination criterion is deactivated. + f_min_rtol : float, optional + Terminate the optimization once the relative error between the + current best minimum `f` and the supplied global minimum `f_min` + is smaller than `f_min_rtol`. This parameter is only used if + `f_min` is also set. Must lie between 0 and 1. Default is 1e-4. + vol_tol : float, optional + Terminate the optimization once the volume of the hyperrectangle + containing the lowest function value is smaller than `vol_tol` + of the complete search space. Must lie between 0 and 1. + Default is 1e-16. + len_tol : float, optional + If ``locally_biased=True``, terminate the optimization once half of + the normalized maximal side length of the hyperrectangle containing + the lowest function value is smaller than `len_tol`. + If ``locally_biased=False``, terminate the optimization once half of + the normalized diagonal of the hyperrectangle containing the lowest + function value is smaller than `len_tol`. Must lie between 0 and 1. + Default is 1e-6. + callback : callable, optional + A callback function with signature ``callback(xk)`` where ``xk`` + represents the best function value found so far. + + Returns + ------- + res : OptimizeResult + The optimization result represented as a ``OptimizeResult`` object. + Important attributes are: ``x`` the solution array, ``success`` a + Boolean flag indicating if the optimizer exited successfully and + ``message`` which describes the cause of the termination. See + `OptimizeResult` for a description of other attributes. + + Notes + ----- + DIviding RECTangles (DIRECT) is a deterministic global + optimization algorithm capable of minimizing a black box function with + its variables subject to lower and upper bound constraints by sampling + potential solutions in the search space [1]_. The algorithm starts by + normalising the search space to an n-dimensional unit hypercube. + It samples the function at the center of this hypercube and at 2n + (n is the number of variables) more points, 2 in each coordinate + direction. Using these function values, DIRECT then divides the + domain into hyperrectangles, each having exactly one of the sampling + points as its center. In each iteration, DIRECT chooses, using the `eps` + parameter which defaults to 1e-4, some of the existing hyperrectangles + to be further divided. This division process continues until either the + maximum number of iterations or maximum function evaluations allowed + are exceeded, or the hyperrectangle containing the minimal value found + so far becomes small enough. If `f_min` is specified, the optimization + will stop once this function value is reached within a relative tolerance. + The locally biased variant of DIRECT (originally called DIRECT_L) [2]_ is + used by default. It makes the search more locally biased and more + efficient for cases with only a few local minima. + + A note about termination criteria: `vol_tol` refers to the volume of the + hyperrectangle containing the lowest function value found so far. This + volume decreases exponentially with increasing dimensionality of the + problem. Therefore `vol_tol` should be decreased to avoid premature + termination of the algorithm for higher dimensions. This does not hold + for `len_tol`: it refers either to half of the maximal side length + (for ``locally_biased=True``) or half of the diagonal of the + hyperrectangle (for ``locally_biased=False``). + + This code is based on the DIRECT 2.0.4 Fortran code by Gablonsky et al. at + https://ctk.math.ncsu.edu/SOFTWARE/DIRECTv204.tar.gz . + This original version was initially converted via f2c and then cleaned up + and reorganized by Steven G. Johnson, August 2007, for the NLopt project. + The `direct` function wraps the C implementation. + + .. versionadded:: 1.9.0 + + References + ---------- + .. [1] Jones, D.R., Perttunen, C.D. & Stuckman, B.E. Lipschitzian + optimization without the Lipschitz constant. J Optim Theory Appl + 79, 157-181 (1993). + .. [2] Gablonsky, J., Kelley, C. A Locally-Biased form of the DIRECT + Algorithm. Journal of Global Optimization 21, 27-37 (2001). + + Examples + -------- + The following example is a 2-D problem with four local minima: minimizing + the Styblinski-Tang function + (https://en.wikipedia.org/wiki/Test_functions_for_optimization). + + >>> from scipy.optimize import direct, Bounds + >>> def styblinski_tang(pos): + ... x, y = pos + ... return 0.5 * (x**4 - 16*x**2 + 5*x + y**4 - 16*y**2 + 5*y) + >>> bounds = Bounds([-4., -4.], [4., 4.]) + >>> result = direct(styblinski_tang, bounds) + >>> result.x, result.fun, result.nfev + array([-2.90321597, -2.90321597]), -78.3323279095383, 2011 + + The correct global minimum was found but with a huge number of function + evaluations (2011). Loosening the termination tolerances `vol_tol` and + `len_tol` can be used to stop DIRECT earlier. + + >>> result = direct(styblinski_tang, bounds, len_tol=1e-3) + >>> result.x, result.fun, result.nfev + array([-2.9044353, -2.9044353]), -78.33230330754142, 207 + + """ + # convert bounds to new Bounds class if necessary + if not isinstance(bounds, Bounds): + if isinstance(bounds, list) or isinstance(bounds, tuple): + lb, ub = old_bound_to_new(bounds) + bounds = Bounds(lb, ub) + else: + message = ("bounds must be a sequence or " + "instance of Bounds class") + raise ValueError(message) + + lb = np.ascontiguousarray(bounds.lb, dtype=np.float64) + ub = np.ascontiguousarray(bounds.ub, dtype=np.float64) + + # validate bounds + # check that lower bounds are smaller than upper bounds + if not np.all(lb < ub): + raise ValueError('Bounds are not consistent min < max') + # check for infs + if (np.any(np.isinf(lb)) or np.any(np.isinf(ub))): + raise ValueError("Bounds must not be inf.") + + # validate tolerances + if (vol_tol < 0 or vol_tol > 1): + raise ValueError("vol_tol must be between 0 and 1.") + if (len_tol < 0 or len_tol > 1): + raise ValueError("len_tol must be between 0 and 1.") + if (f_min_rtol < 0 or f_min_rtol > 1): + raise ValueError("f_min_rtol must be between 0 and 1.") + + # validate maxfun and maxiter + if maxfun is None: + maxfun = 1000 * lb.shape[0] + if not isinstance(maxfun, int): + raise ValueError("maxfun must be of type int.") + if maxfun < 0: + raise ValueError("maxfun must be > 0.") + if not isinstance(maxiter, int): + raise ValueError("maxiter must be of type int.") + if maxiter < 0: + raise ValueError("maxiter must be > 0.") + + # validate boolean parameters + if not isinstance(locally_biased, bool): + raise ValueError("locally_biased must be True or False.") + + def _func_wrap(x, args=None): + x = np.asarray(x) + if args is None: + f = func(x) + else: + f = func(x, *args) + # always return a float + return np.asarray(f).item() + + # TODO: fix disp argument + x, fun, ret_code, nfev, nit = _direct( + _func_wrap, + np.asarray(lb), np.asarray(ub), + args, + False, eps, maxfun, maxiter, + locally_biased, + f_min, f_min_rtol, + vol_tol, len_tol, callback + ) + + format_val = (maxfun, maxiter, f_min_rtol, vol_tol, len_tol) + if ret_code > 2: + message = SUCCESS_MESSAGES[ret_code - 3].format( + format_val[ret_code - 1]) + elif 0 < ret_code <= 2: + message = ERROR_MESSAGES[ret_code - 1].format(format_val[ret_code - 1]) + elif 0 > ret_code > -100: + message = ERROR_MESSAGES[abs(ret_code) + 1] + else: + message = ERROR_MESSAGES[ret_code + 99] + + return OptimizeResult(x=np.asarray(x), fun=fun, status=ret_code, + success=ret_code > 2, message=message, + nfev=nfev, nit=nit) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_dual_annealing.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_dual_annealing.py new file mode 100644 index 0000000000000000000000000000000000000000..eb480a902c593ffee1d242d79018c9175bcc6d3a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_dual_annealing.py @@ -0,0 +1,732 @@ +# Dual Annealing implementation. +# Copyright (c) 2018 Sylvain Gubian , +# Yang Xiang +# Author: Sylvain Gubian, Yang Xiang, PMP S.A. + +""" +A Dual Annealing global optimization algorithm +""" + +import numpy as np +from scipy.optimize import OptimizeResult +from scipy.optimize import minimize, Bounds +from scipy.special import gammaln +from scipy._lib._util import check_random_state, _transition_to_rng +from scipy.optimize._constraints import new_bounds_to_old + +__all__ = ['dual_annealing'] + + +class VisitingDistribution: + """ + Class used to generate new coordinates based on the distorted + Cauchy-Lorentz distribution. Depending on the steps within the strategy + chain, the class implements the strategy for generating new location + changes. + + Parameters + ---------- + lb : array_like + A 1-D NumPy ndarray containing lower bounds of the generated + components. Neither NaN or inf are allowed. + ub : array_like + A 1-D NumPy ndarray containing upper bounds for the generated + components. Neither NaN or inf are allowed. + visiting_param : float + Parameter for visiting distribution. Default value is 2.62. + Higher values give the visiting distribution a heavier tail, this + makes the algorithm jump to a more distant region. + The value range is (1, 3]. Its value is fixed for the life of the + object. + rng_gen : {`~numpy.random.Generator`} + A `~numpy.random.Generator` object for generating new locations. + (can be a `~numpy.random.RandomState` object until SPEC007 transition + is fully complete). + + """ + TAIL_LIMIT = 1.e8 + MIN_VISIT_BOUND = 1.e-10 + + def __init__(self, lb, ub, visiting_param, rng_gen): + # if you wish to make _visiting_param adjustable during the life of + # the object then _factor2, _factor3, _factor5, _d1, _factor6 will + # have to be dynamically calculated in `visit_fn`. They're factored + # out here so they don't need to be recalculated all the time. + self._visiting_param = visiting_param + self.rng_gen = rng_gen + self.lower = lb + self.upper = ub + self.bound_range = ub - lb + + # these are invariant numbers unless visiting_param changes + self._factor2 = np.exp((4.0 - self._visiting_param) * np.log( + self._visiting_param - 1.0)) + self._factor3 = np.exp((2.0 - self._visiting_param) * np.log(2.0) + / (self._visiting_param - 1.0)) + self._factor4_p = np.sqrt(np.pi) * self._factor2 / (self._factor3 * ( + 3.0 - self._visiting_param)) + + self._factor5 = 1.0 / (self._visiting_param - 1.0) - 0.5 + self._d1 = 2.0 - self._factor5 + self._factor6 = np.pi * (1.0 - self._factor5) / np.sin( + np.pi * (1.0 - self._factor5)) / np.exp(gammaln(self._d1)) + + def visiting(self, x, step, temperature): + """ Based on the step in the strategy chain, new coordinates are + generated by changing all components is the same time or only + one of them, the new values are computed with visit_fn method + """ + dim = x.size + if step < dim: + # Changing all coordinates with a new visiting value + visits = self.visit_fn(temperature, dim) + upper_sample, lower_sample = self.rng_gen.uniform(size=2) + visits[visits > self.TAIL_LIMIT] = self.TAIL_LIMIT * upper_sample + visits[visits < -self.TAIL_LIMIT] = -self.TAIL_LIMIT * lower_sample + x_visit = visits + x + a = x_visit - self.lower + b = np.fmod(a, self.bound_range) + self.bound_range + x_visit = np.fmod(b, self.bound_range) + self.lower + x_visit[np.fabs( + x_visit - self.lower) < self.MIN_VISIT_BOUND] += 1.e-10 + else: + # Changing only one coordinate at a time based on strategy + # chain step + x_visit = np.copy(x) + visit = self.visit_fn(temperature, 1)[0] + if visit > self.TAIL_LIMIT: + visit = self.TAIL_LIMIT * self.rng_gen.uniform() + elif visit < -self.TAIL_LIMIT: + visit = -self.TAIL_LIMIT * self.rng_gen.uniform() + index = step - dim + x_visit[index] = visit + x[index] + a = x_visit[index] - self.lower[index] + b = np.fmod(a, self.bound_range[index]) + self.bound_range[index] + x_visit[index] = np.fmod(b, self.bound_range[ + index]) + self.lower[index] + if np.fabs(x_visit[index] - self.lower[ + index]) < self.MIN_VISIT_BOUND: + x_visit[index] += self.MIN_VISIT_BOUND + return x_visit + + def visit_fn(self, temperature, dim): + """ Formula Visita from p. 405 of reference [2] """ + x, y = self.rng_gen.normal(size=(dim, 2)).T + + factor1 = np.exp(np.log(temperature) / (self._visiting_param - 1.0)) + factor4 = self._factor4_p * factor1 + + # sigmax + x *= np.exp(-(self._visiting_param - 1.0) * np.log( + self._factor6 / factor4) / (3.0 - self._visiting_param)) + + den = np.exp((self._visiting_param - 1.0) * np.log(np.fabs(y)) / + (3.0 - self._visiting_param)) + + return x / den + + +class EnergyState: + """ + Class used to record the energy state. At any time, it knows what is the + currently used coordinates and the most recent best location. + + Parameters + ---------- + lower : array_like + A 1-D NumPy ndarray containing lower bounds for generating an initial + random components in the `reset` method. + upper : array_like + A 1-D NumPy ndarray containing upper bounds for generating an initial + random components in the `reset` method + components. Neither NaN or inf are allowed. + callback : callable, ``callback(x, f, context)``, optional + A callback function which will be called for all minima found. + ``x`` and ``f`` are the coordinates and function value of the + latest minimum found, and `context` has value in [0, 1, 2] + """ + # Maximum number of trials for generating a valid starting point + MAX_REINIT_COUNT = 1000 + + def __init__(self, lower, upper, callback=None): + self.ebest = None + self.current_energy = None + self.current_location = None + self.xbest = None + self.lower = lower + self.upper = upper + self.callback = callback + + def reset(self, func_wrapper, rng_gen, x0=None): + """ + Initialize current location is the search domain. If `x0` is not + provided, a random location within the bounds is generated. + """ + if x0 is None: + self.current_location = rng_gen.uniform(self.lower, self.upper, + size=len(self.lower)) + else: + self.current_location = np.copy(x0) + init_error = True + reinit_counter = 0 + while init_error: + self.current_energy = func_wrapper.fun(self.current_location) + if self.current_energy is None: + raise ValueError('Objective function is returning None') + if not np.isfinite(self.current_energy): + if reinit_counter >= EnergyState.MAX_REINIT_COUNT: + init_error = False + message = ( + 'Stopping algorithm because function ' + 'create NaN or (+/-) infinity values even with ' + 'trying new random parameters' + ) + raise ValueError(message) + self.current_location = rng_gen.uniform(self.lower, + self.upper, + size=self.lower.size) + reinit_counter += 1 + else: + init_error = False + # If first time reset, initialize ebest and xbest + if self.ebest is None and self.xbest is None: + self.ebest = self.current_energy + self.xbest = np.copy(self.current_location) + # Otherwise, we keep them in case of reannealing reset + + def update_best(self, e, x, context): + self.ebest = e + self.xbest = np.copy(x) + if self.callback is not None: + val = self.callback(x, e, context) + if val is not None: + if val: + return ('Callback function requested to stop early by ' + 'returning True') + + def update_current(self, e, x): + self.current_energy = e + self.current_location = np.copy(x) + + +class StrategyChain: + """ + Class that implements within a Markov chain the strategy for location + acceptance and local search decision making. + + Parameters + ---------- + acceptance_param : float + Parameter for acceptance distribution. It is used to control the + probability of acceptance. The lower the acceptance parameter, the + smaller the probability of acceptance. Default value is -5.0 with + a range (-1e4, -5]. + visit_dist : VisitingDistribution + Instance of `VisitingDistribution` class. + func_wrapper : ObjectiveFunWrapper + Instance of `ObjectiveFunWrapper` class. + minimizer_wrapper: LocalSearchWrapper + Instance of `LocalSearchWrapper` class. + rand_gen : {None, int, `numpy.random.Generator`, + `numpy.random.RandomState`}, optional + + If `seed` is None (or `np.random`), the `numpy.random.RandomState` + singleton is used. + If `seed` is an int, a new ``RandomState`` instance is used, + seeded with `seed`. + If `seed` is already a ``Generator`` or ``RandomState`` instance then + that instance is used. + energy_state: EnergyState + Instance of `EnergyState` class. + + """ + + def __init__(self, acceptance_param, visit_dist, func_wrapper, + minimizer_wrapper, rand_gen, energy_state): + # Local strategy chain minimum energy and location + self.emin = energy_state.current_energy + self.xmin = np.array(energy_state.current_location) + # Global optimizer state + self.energy_state = energy_state + # Acceptance parameter + self.acceptance_param = acceptance_param + # Visiting distribution instance + self.visit_dist = visit_dist + # Wrapper to objective function + self.func_wrapper = func_wrapper + # Wrapper to the local minimizer + self.minimizer_wrapper = minimizer_wrapper + self.not_improved_idx = 0 + self.not_improved_max_idx = 1000 + self._rand_gen = rand_gen + self.temperature_step = 0 + self.K = 100 * len(energy_state.current_location) + + def accept_reject(self, j, e, x_visit): + r = self._rand_gen.uniform() + pqv_temp = 1.0 - ((1.0 - self.acceptance_param) * + (e - self.energy_state.current_energy) / self.temperature_step) + if pqv_temp <= 0.: + pqv = 0. + else: + pqv = np.exp(np.log(pqv_temp) / ( + 1. - self.acceptance_param)) + + if r <= pqv: + # We accept the new location and update state + self.energy_state.update_current(e, x_visit) + self.xmin = np.copy(self.energy_state.current_location) + + # No improvement for a long time + if self.not_improved_idx >= self.not_improved_max_idx: + if j == 0 or self.energy_state.current_energy < self.emin: + self.emin = self.energy_state.current_energy + self.xmin = np.copy(self.energy_state.current_location) + + def run(self, step, temperature): + self.temperature_step = temperature / float(step + 1) + self.not_improved_idx += 1 + for j in range(self.energy_state.current_location.size * 2): + if j == 0: + if step == 0: + self.energy_state_improved = True + else: + self.energy_state_improved = False + x_visit = self.visit_dist.visiting( + self.energy_state.current_location, j, temperature) + # Calling the objective function + e = self.func_wrapper.fun(x_visit) + if e < self.energy_state.current_energy: + # We have got a better energy value + self.energy_state.update_current(e, x_visit) + if e < self.energy_state.ebest: + val = self.energy_state.update_best(e, x_visit, 0) + if val is not None: + if val: + return val + self.energy_state_improved = True + self.not_improved_idx = 0 + else: + # We have not improved but do we accept the new location? + self.accept_reject(j, e, x_visit) + if self.func_wrapper.nfev >= self.func_wrapper.maxfun: + return ('Maximum number of function call reached ' + 'during annealing') + # End of StrategyChain loop + + def local_search(self): + # Decision making for performing a local search + # based on strategy chain results + # If energy has been improved or no improvement since too long, + # performing a local search with the best strategy chain location + if self.energy_state_improved: + # Global energy has improved, let's see if LS improves further + e, x = self.minimizer_wrapper.local_search(self.energy_state.xbest, + self.energy_state.ebest) + if e < self.energy_state.ebest: + self.not_improved_idx = 0 + val = self.energy_state.update_best(e, x, 1) + if val is not None: + if val: + return val + self.energy_state.update_current(e, x) + if self.func_wrapper.nfev >= self.func_wrapper.maxfun: + return ('Maximum number of function call reached ' + 'during local search') + # Check probability of a need to perform a LS even if no improvement + do_ls = False + if self.K < 90 * len(self.energy_state.current_location): + pls = np.exp(self.K * ( + self.energy_state.ebest - self.energy_state.current_energy) / + self.temperature_step) + if pls >= self._rand_gen.uniform(): + do_ls = True + # Global energy not improved, let's see what LS gives + # on the best strategy chain location + if self.not_improved_idx >= self.not_improved_max_idx: + do_ls = True + if do_ls: + e, x = self.minimizer_wrapper.local_search(self.xmin, self.emin) + self.xmin = np.copy(x) + self.emin = e + self.not_improved_idx = 0 + self.not_improved_max_idx = self.energy_state.current_location.size + if e < self.energy_state.ebest: + val = self.energy_state.update_best( + self.emin, self.xmin, 2) + if val is not None: + if val: + return val + self.energy_state.update_current(e, x) + if self.func_wrapper.nfev >= self.func_wrapper.maxfun: + return ('Maximum number of function call reached ' + 'during dual annealing') + + +class ObjectiveFunWrapper: + + def __init__(self, func, maxfun=1e7, *args): + self.func = func + self.args = args + # Number of objective function evaluations + self.nfev = 0 + # Number of gradient function evaluation if used + self.ngev = 0 + # Number of hessian of the objective function if used + self.nhev = 0 + self.maxfun = maxfun + + def fun(self, x): + self.nfev += 1 + return self.func(x, *self.args) + + +class LocalSearchWrapper: + """ + Class used to wrap around the minimizer used for local search + Default local minimizer is SciPy minimizer L-BFGS-B + """ + + LS_MAXITER_RATIO = 6 + LS_MAXITER_MIN = 100 + LS_MAXITER_MAX = 1000 + + def __init__(self, search_bounds, func_wrapper, *args, **kwargs): + self.func_wrapper = func_wrapper + self.kwargs = kwargs + self.jac = self.kwargs.get('jac', None) + self.hess = self.kwargs.get('hess', None) + self.hessp = self.kwargs.get('hessp', None) + self.kwargs.pop("args", None) + self.minimizer = minimize + bounds_list = list(zip(*search_bounds)) + self.lower = np.array(bounds_list[0]) + self.upper = np.array(bounds_list[1]) + + # If no minimizer specified, use SciPy minimize with 'L-BFGS-B' method + if not self.kwargs: + n = len(self.lower) + ls_max_iter = min(max(n * self.LS_MAXITER_RATIO, + self.LS_MAXITER_MIN), + self.LS_MAXITER_MAX) + self.kwargs['method'] = 'L-BFGS-B' + self.kwargs['options'] = { + 'maxiter': ls_max_iter, + } + self.kwargs['bounds'] = list(zip(self.lower, self.upper)) + else: + if callable(self.jac): + def wrapped_jac(x): + return self.jac(x, *args) + self.kwargs['jac'] = wrapped_jac + if callable(self.hess): + def wrapped_hess(x): + return self.hess(x, *args) + self.kwargs['hess'] = wrapped_hess + if callable(self.hessp): + def wrapped_hessp(x, p): + return self.hessp(x, p, *args) + self.kwargs['hessp'] = wrapped_hessp + + def local_search(self, x, e): + # Run local search from the given x location where energy value is e + x_tmp = np.copy(x) + mres = self.minimizer(self.func_wrapper.fun, x, **self.kwargs) + if 'njev' in mres: + self.func_wrapper.ngev += mres.njev + if 'nhev' in mres: + self.func_wrapper.nhev += mres.nhev + # Check if is valid value + is_finite = np.all(np.isfinite(mres.x)) and np.isfinite(mres.fun) + in_bounds = np.all(mres.x >= self.lower) and np.all( + mres.x <= self.upper) + is_valid = is_finite and in_bounds + + # Use the new point only if it is valid and return a better results + if is_valid and mres.fun < e: + return mres.fun, mres.x + else: + return e, x_tmp + + +@_transition_to_rng("seed", position_num=10) +def dual_annealing(func, bounds, args=(), maxiter=1000, + minimizer_kwargs=None, initial_temp=5230., + restart_temp_ratio=2.e-5, visit=2.62, accept=-5.0, + maxfun=1e7, rng=None, no_local_search=False, + callback=None, x0=None): + """ + Find the global minimum of a function using Dual Annealing. + + Parameters + ---------- + func : callable + The objective function to be minimized. Must be in the form + ``f(x, *args)``, where ``x`` is the argument in the form of a 1-D array + and ``args`` is a tuple of any additional fixed parameters needed to + completely specify the function. + bounds : sequence or `Bounds` + Bounds for variables. There are two ways to specify the bounds: + + 1. Instance of `Bounds` class. + 2. Sequence of ``(min, max)`` pairs for each element in `x`. + + args : tuple, optional + Any additional fixed parameters needed to completely specify the + objective function. + maxiter : int, optional + The maximum number of global search iterations. Default value is 1000. + minimizer_kwargs : dict, optional + Keyword arguments to be passed to the local minimizer + (`minimize`). An important option could be ``method`` for the minimizer + method to use. + If no keyword arguments are provided, the local minimizer defaults to + 'L-BFGS-B' and uses the already supplied bounds. If `minimizer_kwargs` + is specified, then the dict must contain all parameters required to + control the local minimization. `args` is ignored in this dict, as it is + passed automatically. `bounds` is not automatically passed on to the + local minimizer as the method may not support them. + initial_temp : float, optional + The initial temperature, use higher values to facilitates a wider + search of the energy landscape, allowing dual_annealing to escape + local minima that it is trapped in. Default value is 5230. Range is + (0.01, 5.e4]. + restart_temp_ratio : float, optional + During the annealing process, temperature is decreasing, when it + reaches ``initial_temp * restart_temp_ratio``, the reannealing process + is triggered. Default value of the ratio is 2e-5. Range is (0, 1). + visit : float, optional + Parameter for visiting distribution. Default value is 2.62. Higher + values give the visiting distribution a heavier tail, this makes + the algorithm jump to a more distant region. The value range is (1, 3]. + accept : float, optional + Parameter for acceptance distribution. It is used to control the + probability of acceptance. The lower the acceptance parameter, the + smaller the probability of acceptance. Default value is -5.0 with + a range (-1e4, -5]. + maxfun : int, optional + Soft limit for the number of objective function calls. If the + algorithm is in the middle of a local search, this number will be + exceeded, the algorithm will stop just after the local search is + done. Default value is 1e7. + rng : `numpy.random.Generator`, optional + Pseudorandom number generator state. When `rng` is None, a new + `numpy.random.Generator` is created using entropy from the + operating system. Types other than `numpy.random.Generator` are + passed to `numpy.random.default_rng` to instantiate a `Generator`. + + Specify `rng` for repeatable minimizations. The random numbers + generated only affect the visiting distribution function + and new coordinates generation. + no_local_search : bool, optional + If `no_local_search` is set to True, a traditional Generalized + Simulated Annealing will be performed with no local search + strategy applied. + callback : callable, optional + A callback function with signature ``callback(x, f, context)``, + which will be called for all minima found. + ``x`` and ``f`` are the coordinates and function value of the + latest minimum found, and ``context`` has one of the following + values: + + - ``0``: minimum detected in the annealing process. + - ``1``: detection occurred in the local search process. + - ``2``: detection done in the dual annealing process. + + If the callback implementation returns True, the algorithm will stop. + x0 : ndarray, shape(n,), optional + Coordinates of a single N-D starting point. + + Returns + ------- + res : OptimizeResult + The optimization result represented as a `OptimizeResult` object. + Important attributes are: ``x`` the solution array, ``fun`` the value + of the function at the solution, and ``message`` which describes the + cause of the termination. + See `OptimizeResult` for a description of other attributes. + + Notes + ----- + This function implements the Dual Annealing optimization. This stochastic + approach derived from [3]_ combines the generalization of CSA (Classical + Simulated Annealing) and FSA (Fast Simulated Annealing) [1]_ [2]_ coupled + to a strategy for applying a local search on accepted locations [4]_. + An alternative implementation of this same algorithm is described in [5]_ + and benchmarks are presented in [6]_. This approach introduces an advanced + method to refine the solution found by the generalized annealing + process. This algorithm uses a distorted Cauchy-Lorentz visiting + distribution, with its shape controlled by the parameter :math:`q_{v}` + + .. math:: + + g_{q_{v}}(\\Delta x(t)) \\propto \\frac{ \\ + \\left[T_{q_{v}}(t) \\right]^{-\\frac{D}{3-q_{v}}}}{ \\ + \\left[{1+(q_{v}-1)\\frac{(\\Delta x(t))^{2}} { \\ + \\left[T_{q_{v}}(t)\\right]^{\\frac{2}{3-q_{v}}}}}\\right]^{ \\ + \\frac{1}{q_{v}-1}+\\frac{D-1}{2}}} + + Where :math:`t` is the artificial time. This visiting distribution is used + to generate a trial jump distance :math:`\\Delta x(t)` of variable + :math:`x(t)` under artificial temperature :math:`T_{q_{v}}(t)`. + + From the starting point, after calling the visiting distribution + function, the acceptance probability is computed as follows: + + .. math:: + + p_{q_{a}} = \\min{\\{1,\\left[1-(1-q_{a}) \\beta \\Delta E \\right]^{ \\ + \\frac{1}{1-q_{a}}}\\}} + + Where :math:`q_{a}` is a acceptance parameter. For :math:`q_{a}<1`, zero + acceptance probability is assigned to the cases where + + .. math:: + + [1-(1-q_{a}) \\beta \\Delta E] < 0 + + The artificial temperature :math:`T_{q_{v}}(t)` is decreased according to + + .. math:: + + T_{q_{v}}(t) = T_{q_{v}}(1) \\frac{2^{q_{v}-1}-1}{\\left( \\ + 1 + t\\right)^{q_{v}-1}-1} + + Where :math:`q_{v}` is the visiting parameter. + + .. versionadded:: 1.2.0 + + References + ---------- + .. [1] Tsallis C. Possible generalization of Boltzmann-Gibbs + statistics. Journal of Statistical Physics, 52, 479-487 (1998). + .. [2] Tsallis C, Stariolo DA. Generalized Simulated Annealing. + Physica A, 233, 395-406 (1996). + .. [3] Xiang Y, Sun DY, Fan W, Gong XG. Generalized Simulated + Annealing Algorithm and Its Application to the Thomson Model. + Physics Letters A, 233, 216-220 (1997). + .. [4] Xiang Y, Gong XG. Efficiency of Generalized Simulated + Annealing. Physical Review E, 62, 4473 (2000). + .. [5] Xiang Y, Gubian S, Suomela B, Hoeng J. Generalized + Simulated Annealing for Efficient Global Optimization: the GenSA + Package for R. The R Journal, Volume 5/1 (2013). + .. [6] Mullen, K. Continuous Global Optimization in R. Journal of + Statistical Software, 60(6), 1 - 45, (2014). + :doi:`10.18637/jss.v060.i06` + + Examples + -------- + The following example is a 10-D problem, with many local minima. + The function involved is called Rastrigin + (https://en.wikipedia.org/wiki/Rastrigin_function) + + >>> import numpy as np + >>> from scipy.optimize import dual_annealing + >>> func = lambda x: np.sum(x*x - 10*np.cos(2*np.pi*x)) + 10*np.size(x) + >>> lw = [-5.12] * 10 + >>> up = [5.12] * 10 + >>> ret = dual_annealing(func, bounds=list(zip(lw, up))) + >>> ret.x + array([-4.26437714e-09, -3.91699361e-09, -1.86149218e-09, -3.97165720e-09, + -6.29151648e-09, -6.53145322e-09, -3.93616815e-09, -6.55623025e-09, + -6.05775280e-09, -5.00668935e-09]) # random + >>> ret.fun + 0.000000 + + """ + + if isinstance(bounds, Bounds): + bounds = new_bounds_to_old(bounds.lb, bounds.ub, len(bounds.lb)) + + if x0 is not None and not len(x0) == len(bounds): + raise ValueError('Bounds size does not match x0') + + lu = list(zip(*bounds)) + lower = np.array(lu[0]) + upper = np.array(lu[1]) + # Check that restart temperature ratio is correct + if restart_temp_ratio <= 0. or restart_temp_ratio >= 1.: + raise ValueError('Restart temperature ratio has to be in range (0, 1)') + # Checking bounds are valid + if (np.any(np.isinf(lower)) or np.any(np.isinf(upper)) or np.any( + np.isnan(lower)) or np.any(np.isnan(upper))): + raise ValueError('Some bounds values are inf values or nan values') + # Checking that bounds are consistent + if not np.all(lower < upper): + raise ValueError('Bounds are not consistent min < max') + # Checking that bounds are the same length + if not len(lower) == len(upper): + raise ValueError('Bounds do not have the same dimensions') + + # Wrapper for the objective function + func_wrapper = ObjectiveFunWrapper(func, maxfun, *args) + + # minimizer_kwargs has to be a dict, not None + minimizer_kwargs = minimizer_kwargs or {} + + minimizer_wrapper = LocalSearchWrapper( + bounds, func_wrapper, *args, **minimizer_kwargs) + + # Initialization of random Generator for reproducible runs if rng provided + rng_gen = check_random_state(rng) + # Initialization of the energy state + energy_state = EnergyState(lower, upper, callback) + energy_state.reset(func_wrapper, rng_gen, x0) + # Minimum value of annealing temperature reached to perform + # re-annealing + temperature_restart = initial_temp * restart_temp_ratio + # VisitingDistribution instance + visit_dist = VisitingDistribution(lower, upper, visit, rng_gen) + # Strategy chain instance + strategy_chain = StrategyChain(accept, visit_dist, func_wrapper, + minimizer_wrapper, rng_gen, energy_state) + need_to_stop = False + iteration = 0 + message = [] + # OptimizeResult object to be returned + optimize_res = OptimizeResult() + optimize_res.success = True + optimize_res.status = 0 + + t1 = np.exp((visit - 1) * np.log(2.0)) - 1.0 + # Run the search loop + while not need_to_stop: + for i in range(maxiter): + # Compute temperature for this step + s = float(i) + 2.0 + t2 = np.exp((visit - 1) * np.log(s)) - 1.0 + temperature = initial_temp * t1 / t2 + if iteration >= maxiter: + message.append("Maximum number of iteration reached") + need_to_stop = True + break + # Need a re-annealing process? + if temperature < temperature_restart: + energy_state.reset(func_wrapper, rng_gen) + break + # starting strategy chain + val = strategy_chain.run(i, temperature) + if val is not None: + message.append(val) + need_to_stop = True + optimize_res.success = False + break + # Possible local search at the end of the strategy chain + if not no_local_search: + val = strategy_chain.local_search() + if val is not None: + message.append(val) + need_to_stop = True + optimize_res.success = False + break + iteration += 1 + + # Setting the OptimizeResult values + optimize_res.x = energy_state.xbest + optimize_res.fun = energy_state.ebest + optimize_res.nit = iteration + optimize_res.nfev = func_wrapper.nfev + optimize_res.njev = func_wrapper.ngev + optimize_res.nhev = func_wrapper.nhev + optimize_res.message = message + return optimize_res diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_elementwise.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_elementwise.py new file mode 100644 index 0000000000000000000000000000000000000000..883c644dbcbbb954ea3e3c184bd610b28f05cca8 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_elementwise.py @@ -0,0 +1,801 @@ +from scipy.optimize._bracket import _bracket_root, _bracket_minimum +from scipy.optimize._chandrupatla import _chandrupatla, _chandrupatla_minimize +from scipy._lib._util import _RichResult + + +def find_root(f, init, /, *, args=(), tolerances=None, maxiter=None, callback=None): + """Find the root of a monotonic, real-valued function of a real variable. + + For each element of the output of `f`, `find_root` seeks the scalar + root that makes the element 0. This function currently uses Chandrupatla's + bracketing algorithm [1]_ and therefore requires argument `init` to + provide a bracket around the root: the function values at the two endpoints + must have opposite signs. + + Provided a valid bracket, `find_root` is guaranteed to converge to a solution + that satisfies the provided `tolerances` if the function is continuous within + the bracket. + + This function works elementwise when `init` and `args` contain (broadcastable) + arrays. + + Parameters + ---------- + f : callable + The function whose root is desired. The signature must be:: + + f(x: array, *args) -> array + + where each element of ``x`` is a finite real and ``args`` is a tuple, + which may contain an arbitrary number of arrays that are broadcastable + with ``x``. + + `f` must be an elementwise function: each element ``f(x)[i]`` + must equal ``f(x[i])`` for all indices ``i``. It must not mutate the + array ``x`` or the arrays in ``args``. + + `find_root` seeks an array ``x`` such that ``f(x)`` is an array of zeros. + init : 2-tuple of float array_like + The lower and upper endpoints of a bracket surrounding the desired root. + A bracket is valid if arrays ``xl, xr = init`` satisfy ``xl < xr`` and + ``sign(f(xl)) == -sign(f(xr))`` elementwise. Arrays be broadcastable with + one another and `args`. + args : tuple of array_like, optional + Additional positional array arguments to be passed to `f`. Arrays + must be broadcastable with one another and the arrays of `init`. + If the callable for which the root is desired requires arguments that are + not broadcastable with `x`, wrap that callable with `f` such that `f` + accepts only `x` and broadcastable ``*args``. + tolerances : dictionary of floats, optional + Absolute and relative tolerances on the root and function value. + Valid keys of the dictionary are: + + - ``xatol`` - absolute tolerance on the root + - ``xrtol`` - relative tolerance on the root + - ``fatol`` - absolute tolerance on the function value + - ``frtol`` - relative tolerance on the function value + + See Notes for default values and explicit termination conditions. + maxiter : int, optional + The maximum number of iterations of the algorithm to perform. + The default is the maximum possible number of bisections within + the (normal) floating point numbers of the relevant dtype. + callback : callable, optional + An optional user-supplied function to be called before the first + iteration and after each iteration. + Called as ``callback(res)``, where ``res`` is a ``_RichResult`` + similar to that returned by `find_root` (but containing the current + iterate's values of all variables). If `callback` raises a + ``StopIteration``, the algorithm will terminate immediately and + `find_root` will return a result. `callback` must not mutate + `res` or its attributes. + + Returns + ------- + res : _RichResult + An object similar to an instance of `scipy.optimize.OptimizeResult` with the + following attributes. The descriptions are written as though the values will + be scalars; however, if `f` returns an array, the outputs will be + arrays of the same shape. + + success : bool array + ``True`` where the algorithm terminated successfully (status ``0``); + ``False`` otherwise. + status : int array + An integer representing the exit status of the algorithm. + + - ``0`` : The algorithm converged to the specified tolerances. + - ``-1`` : The initial bracket was invalid. + - ``-2`` : The maximum number of iterations was reached. + - ``-3`` : A non-finite value was encountered. + - ``-4`` : Iteration was terminated by `callback`. + - ``1`` : The algorithm is proceeding normally (in `callback` only). + + x : float array + The root of the function, if the algorithm terminated successfully. + f_x : float array + The value of `f` evaluated at `x`. + nfev : int array + The number of abscissae at which `f` was evaluated to find the root. + This is distinct from the number of times `f` is *called* because the + the function may evaluated at multiple points in a single call. + nit : int array + The number of iterations of the algorithm that were performed. + bracket : tuple of float arrays + The lower and upper endpoints of the final bracket. + f_bracket : tuple of float arrays + The value of `f` evaluated at the lower and upper endpoints of the + bracket. + + Notes + ----- + Implemented based on Chandrupatla's original paper [1]_. + + Let: + + - ``a, b = init`` be the left and right endpoints of the initial bracket, + - ``xl`` and ``xr`` be the left and right endpoints of the final bracket, + - ``xmin = xl if abs(f(xl)) <= abs(f(xr)) else xr`` be the final bracket + endpoint with the smaller function value, and + - ``fmin0 = min(f(a), f(b))`` be the minimum of the two values of the + function evaluated at the initial bracket endpoints. + + Then the algorithm is considered to have converged when + + - ``abs(xr - xl) < xatol + abs(xmin) * xrtol`` or + - ``fun(xmin) <= fatol + abs(fmin0) * frtol``. + + This is equivalent to the termination condition described in [1]_ with + ``xrtol = 4e-10``, ``xatol = 1e-5``, and ``fatol = frtol = 0``. + However, the default values of the `tolerances` dictionary are + ``xatol = 4*tiny``, ``xrtol = 4*eps``, ``frtol = 0``, and ``fatol = tiny``, + where ``eps`` and ``tiny`` are the precision and smallest normal number + of the result ``dtype`` of function inputs and outputs. + + References + ---------- + + .. [1] Chandrupatla, Tirupathi R. + "A new hybrid quadratic/bisection algorithm for finding the zero of a + nonlinear function without using derivatives". + Advances in Engineering Software, 28(3), 145-149. + https://doi.org/10.1016/s0965-9978(96)00051-8 + + See Also + -------- + bracket_root + + Examples + -------- + Suppose we wish to find the root of the following function. + + >>> def f(x, c=5): + ... return x**3 - 2*x - c + + First, we must find a valid bracket. The function is not monotonic, + but `bracket_root` may be able to provide a bracket. + + >>> from scipy.optimize import elementwise + >>> res_bracket = elementwise.bracket_root(f, 0) + >>> res_bracket.success + True + >>> res_bracket.bracket + (2.0, 4.0) + + Indeed, the values of the function at the bracket endpoints have + opposite signs. + + >>> res_bracket.f_bracket + (-1.0, 51.0) + + Once we have a valid bracket, `find_root` can be used to provide + a precise root. + + >>> res_root = elementwise.find_root(f, res_bracket.bracket) + >>> res_root.x + 2.0945514815423265 + + The final bracket is only a few ULPs wide, so the error between + this value and the true root cannot be much smaller within values + that are representable in double precision arithmetic. + + >>> import numpy as np + >>> xl, xr = res_root.bracket + >>> (xr - xl) / np.spacing(xl) + 2.0 + >>> res_root.f_bracket + (-8.881784197001252e-16, 9.769962616701378e-15) + + `bracket_root` and `find_root` accept arrays for most arguments. + For instance, to find the root for a few values of the parameter ``c`` + at once: + + >>> c = np.asarray([3, 4, 5]) + >>> res_bracket = elementwise.bracket_root(f, 0, args=(c,)) + >>> res_bracket.bracket + (array([1., 1., 2.]), array([2., 2., 4.])) + >>> res_root = elementwise.find_root(f, res_bracket.bracket, args=(c,)) + >>> res_root.x + array([1.8932892 , 2. , 2.09455148]) + + """ + + def reformat_result(res_in): + res_out = _RichResult() + res_out.status = res_in.status + res_out.success = res_in.success + res_out.x = res_in.x + res_out.f_x = res_in.fun + res_out.nfev = res_in.nfev + res_out.nit = res_in.nit + res_out.bracket = (res_in.xl, res_in.xr) + res_out.f_bracket = (res_in.fl, res_in.fr) + res_out._order_keys = ['success', 'status', 'x', 'f_x', + 'nfev', 'nit', 'bracket', 'f_bracket'] + return res_out + + xl, xr = init + default_tolerances = dict(xatol=None, xrtol=None, fatol=None, frtol=0) + tolerances = {} if tolerances is None else tolerances + default_tolerances.update(tolerances) + tolerances = default_tolerances + + if callable(callback): + def _callback(res): + return callback(reformat_result(res)) + else: + _callback = callback + + res = _chandrupatla(f, xl, xr, args=args, **tolerances, + maxiter=maxiter, callback=_callback) + return reformat_result(res) + + +def find_minimum(f, init, /, *, args=(), tolerances=None, maxiter=100, callback=None): + """Find the minimum of an unimodal, real-valued function of a real variable. + + For each element of the output of `f`, `find_minimum` seeks the scalar minimizer + that minimizes the element. This function currently uses Chandrupatla's + bracketing minimization algorithm [1]_ and therefore requires argument `init` + to provide a three-point minimization bracket: ``x1 < x2 < x3`` such that + ``func(x1) >= func(x2) <= func(x3)``, where one of the inequalities is strict. + + Provided a valid bracket, `find_minimum` is guaranteed to converge to a local + minimum that satisfies the provided `tolerances` if the function is continuous + within the bracket. + + This function works elementwise when `init` and `args` contain (broadcastable) + arrays. + + Parameters + ---------- + f : callable + The function whose minimizer is desired. The signature must be:: + + f(x: array, *args) -> array + + where each element of ``x`` is a finite real and ``args`` is a tuple, + which may contain an arbitrary number of arrays that are broadcastable + with ``x``. + + `f` must be an elementwise function: each element ``f(x)[i]`` + must equal ``f(x[i])`` for all indices ``i``. It must not mutate the + array ``x`` or the arrays in ``args``. + + `find_minimum` seeks an array ``x`` such that ``f(x)`` is an array of + local minima. + init : 3-tuple of float array_like + The abscissae of a standard scalar minimization bracket. A bracket is + valid if arrays ``x1, x2, x3 = init`` satisfy ``x1 < x2 < x3`` and + ``func(x1) >= func(x2) <= func(x3)``, where one of the inequalities + is strict. Arrays must be broadcastable with one another and the arrays + of `args`. + args : tuple of array_like, optional + Additional positional array arguments to be passed to `f`. Arrays + must be broadcastable with one another and the arrays of `init`. + If the callable for which the root is desired requires arguments that are + not broadcastable with `x`, wrap that callable with `f` such that `f` + accepts only `x` and broadcastable ``*args``. + tolerances : dictionary of floats, optional + Absolute and relative tolerances on the root and function value. + Valid keys of the dictionary are: + + - ``xatol`` - absolute tolerance on the root + - ``xrtol`` - relative tolerance on the root + - ``fatol`` - absolute tolerance on the function value + - ``frtol`` - relative tolerance on the function value + + See Notes for default values and explicit termination conditions. + maxiter : int, default: 100 + The maximum number of iterations of the algorithm to perform. + callback : callable, optional + An optional user-supplied function to be called before the first + iteration and after each iteration. + Called as ``callback(res)``, where ``res`` is a ``_RichResult`` + similar to that returned by `find_minimum` (but containing the current + iterate's values of all variables). If `callback` raises a + ``StopIteration``, the algorithm will terminate immediately and + `find_root` will return a result. `callback` must not mutate + `res` or its attributes. + + Returns + ------- + res : _RichResult + An object similar to an instance of `scipy.optimize.OptimizeResult` with the + following attributes. The descriptions are written as though the values will + be scalars; however, if `f` returns an array, the outputs will be + arrays of the same shape. + + success : bool array + ``True`` where the algorithm terminated successfully (status ``0``); + ``False`` otherwise. + status : int array + An integer representing the exit status of the algorithm. + + - ``0`` : The algorithm converged to the specified tolerances. + - ``-1`` : The algorithm encountered an invalid bracket. + - ``-2`` : The maximum number of iterations was reached. + - ``-3`` : A non-finite value was encountered. + - ``-4`` : Iteration was terminated by `callback`. + - ``1`` : The algorithm is proceeding normally (in `callback` only). + + x : float array + The minimizer of the function, if the algorithm terminated successfully. + f_x : float array + The value of `f` evaluated at `x`. + nfev : int array + The number of abscissae at which `f` was evaluated to find the root. + This is distinct from the number of times `f` is *called* because the + the function may evaluated at multiple points in a single call. + nit : int array + The number of iterations of the algorithm that were performed. + bracket : tuple of float arrays + The final three-point bracket. + f_bracket : tuple of float arrays + The value of `f` evaluated at the bracket points. + + Notes + ----- + Implemented based on Chandrupatla's original paper [1]_. + + If ``xl < xm < xr`` are the points of the bracket and ``fl >= fm <= fr`` + (where one of the inequalities is strict) are the values of `f` evaluated + at those points, then the algorithm is considered to have converged when: + + - ``xr - xl <= abs(xm)*xrtol + xatol`` or + - ``(fl - 2*fm + fr)/2 <= abs(fm)*frtol + fatol``. + + Note that first of these differs from the termination conditions described + in [1]_. + + The default value of `xrtol` is the square root of the precision of the + appropriate dtype, and ``xatol = fatol = frtol`` is the smallest normal + number of the appropriate dtype. + + References + ---------- + + .. [1] Chandrupatla, Tirupathi R. (1998). + "An efficient quadratic fit-sectioning algorithm for minimization + without derivatives". + Computer Methods in Applied Mechanics and Engineering, 152 (1-2), + 211-217. https://doi.org/10.1016/S0045-7825(97)00190-4 + + See Also + -------- + bracket_minimum + + Examples + -------- + Suppose we wish to minimize the following function. + + >>> def f(x, c=1): + ... return (x - c)**2 + 2 + + First, we must find a valid bracket. The function is unimodal, + so `bracket_minium` will easily find a bracket. + + >>> from scipy.optimize import elementwise + >>> res_bracket = elementwise.bracket_minimum(f, 0) + >>> res_bracket.success + True + >>> res_bracket.bracket + (0.0, 0.5, 1.5) + + Indeed, the bracket points are ordered and the function value + at the middle bracket point is less than at the surrounding + points. + + >>> xl, xm, xr = res_bracket.bracket + >>> fl, fm, fr = res_bracket.f_bracket + >>> (xl < xm < xr) and (fl > fm <= fr) + True + + Once we have a valid bracket, `find_minimum` can be used to provide + an estimate of the minimizer. + + >>> res_minimum = elementwise.find_minimum(f, res_bracket.bracket) + >>> res_minimum.x + 1.0000000149011612 + + The function value changes by only a few ULPs within the bracket, so + the minimizer cannot be determined much more precisely by evaluating + the function alone (i.e. we would need its derivative to do better). + + >>> import numpy as np + >>> fl, fm, fr = res_minimum.f_bracket + >>> (fl - fm) / np.spacing(fm), (fr - fm) / np.spacing(fm) + (0.0, 2.0) + + Therefore, a precise minimum of the function is given by: + + >>> res_minimum.f_x + 2.0 + + `bracket_minimum` and `find_minimum` accept arrays for most arguments. + For instance, to find the minimizers and minima for a few values of the + parameter ``c`` at once: + + >>> c = np.asarray([1, 1.5, 2]) + >>> res_bracket = elementwise.bracket_minimum(f, 0, args=(c,)) + >>> res_bracket.bracket + (array([0. , 0.5, 0.5]), array([0.5, 1.5, 1.5]), array([1.5, 2.5, 2.5])) + >>> res_minimum = elementwise.find_minimum(f, res_bracket.bracket, args=(c,)) + >>> res_minimum.x + array([1.00000001, 1.5 , 2. ]) + >>> res_minimum.f_x + array([2., 2., 2.]) + + """ + + def reformat_result(res_in): + res_out = _RichResult() + res_out.status = res_in.status + res_out.success = res_in.success + res_out.x = res_in.x + res_out.f_x = res_in.fun + res_out.nfev = res_in.nfev + res_out.nit = res_in.nit + res_out.bracket = (res_in.xl, res_in.xm, res_in.xr) + res_out.f_bracket = (res_in.fl, res_in.fm, res_in.fr) + res_out._order_keys = ['success', 'status', 'x', 'f_x', + 'nfev', 'nit', 'bracket', 'f_bracket'] + return res_out + + xl, xm, xr = init + default_tolerances = dict(xatol=None, xrtol=None, fatol=None, frtol=None) + tolerances = {} if tolerances is None else tolerances + default_tolerances.update(tolerances) + tolerances = default_tolerances + + if callable(callback): + def _callback(res): + return callback(reformat_result(res)) + else: + _callback = callback + + res = _chandrupatla_minimize(f, xl, xm, xr, args=args, **tolerances, + maxiter=maxiter, callback=_callback) + return reformat_result(res) + + +def bracket_root(f, xl0, xr0=None, *, xmin=None, xmax=None, factor=None, args=(), + maxiter=1000): + """Bracket the root of a monotonic, real-valued function of a real variable. + + For each element of the output of `f`, `bracket_root` seeks the scalar + bracket endpoints ``xl`` and ``xr`` such that ``sign(f(xl)) == -sign(f(xr))`` + elementwise. + + The function is guaranteed to find a valid bracket if the function is monotonic, + but it may find a bracket under other conditions. + + This function works elementwise when `xl0`, `xr0`, `xmin`, `xmax`, `factor`, and + the elements of `args` are (mutually broadcastable) arrays. + + Parameters + ---------- + f : callable + The function for which the root is to be bracketed. The signature must be:: + + f(x: array, *args) -> array + + where each element of ``x`` is a finite real and ``args`` is a tuple, + which may contain an arbitrary number of arrays that are broadcastable + with ``x``. + + `f` must be an elementwise function: each element ``f(x)[i]`` + must equal ``f(x[i])`` for all indices ``i``. It must not mutate the + array ``x`` or the arrays in ``args``. + xl0, xr0: float array_like + Starting guess of bracket, which need not contain a root. If `xr0` is + not provided, ``xr0 = xl0 + 1``. Must be broadcastable with all other + array inputs. + xmin, xmax : float array_like, optional + Minimum and maximum allowable endpoints of the bracket, inclusive. Must + be broadcastable with all other array inputs. + factor : float array_like, default: 2 + The factor used to grow the bracket. See Notes. + args : tuple of array_like, optional + Additional positional array arguments to be passed to `f`. + If the callable for which the root is desired requires arguments that are + not broadcastable with `x`, wrap that callable with `f` such that `f` + accepts only `x` and broadcastable ``*args``. + maxiter : int, default: 1000 + The maximum number of iterations of the algorithm to perform. + + Returns + ------- + res : _RichResult + An object similar to an instance of `scipy.optimize.OptimizeResult` with the + following attributes. The descriptions are written as though the values will + be scalars; however, if `f` returns an array, the outputs will be + arrays of the same shape. + + success : bool array + ``True`` where the algorithm terminated successfully (status ``0``); + ``False`` otherwise. + status : int array + An integer representing the exit status of the algorithm. + + - ``0`` : The algorithm produced a valid bracket. + - ``-1`` : The bracket expanded to the allowable limits without success. + - ``-2`` : The maximum number of iterations was reached. + - ``-3`` : A non-finite value was encountered. + - ``-4`` : Iteration was terminated by `callback`. + - ``-5``: The initial bracket does not satisfy`xmin <= xl0 < xr0 < xmax`. + + bracket : 2-tuple of float arrays + The lower and upper endpoints of the bracket, if the algorithm + terminated successfully. + f_bracket : 2-tuple of float arrays + The values of `f` evaluated at the endpoints of ``res.bracket``, + respectively. + nfev : int array + The number of abscissae at which `f` was evaluated to find the root. + This is distinct from the number of times `f` is *called* because the + the function may evaluated at multiple points in a single call. + nit : int array + The number of iterations of the algorithm that were performed. + + Notes + ----- + This function generalizes an algorithm found in pieces throughout the + `scipy.stats` codebase. The strategy is to iteratively grow the bracket `(l, r)` + until ``f(l) < 0 < f(r)`` or ``f(r) < 0 < f(l)``. The bracket grows to the left + as follows. + + - If `xmin` is not provided, the distance between `xl0` and `l` is iteratively + increased by `factor`. + - If `xmin` is provided, the distance between `xmin` and `l` is iteratively + decreased by `factor`. Note that this also *increases* the bracket size. + + Growth of the bracket to the right is analogous. + + Growth of the bracket in one direction stops when the endpoint is no longer + finite, the function value at the endpoint is no longer finite, or the + endpoint reaches its limiting value (`xmin` or `xmax`). Iteration terminates + when the bracket stops growing in both directions, the bracket surrounds + the root, or a root is found (by chance). + + If two brackets are found - that is, a bracket is found on both sides in + the same iteration, the smaller of the two is returned. + + If roots of the function are found, both `xl` and `xr` are set to the + leftmost root. + + See Also + -------- + find_root + + Examples + -------- + Suppose we wish to find the root of the following function. + + >>> def f(x, c=5): + ... return x**3 - 2*x - c + + First, we must find a valid bracket. The function is not monotonic, + but `bracket_root` may be able to provide a bracket. + + >>> from scipy.optimize import elementwise + >>> res_bracket = elementwise.bracket_root(f, 0) + >>> res_bracket.success + True + >>> res_bracket.bracket + (2.0, 4.0) + + Indeed, the values of the function at the bracket endpoints have + opposite signs. + + >>> res_bracket.f_bracket + (-1.0, 51.0) + + Once we have a valid bracket, `find_root` can be used to provide + a precise root. + + >>> res_root = elementwise.find_root(f, res_bracket.bracket) + >>> res_root.x + 2.0945514815423265 + + `bracket_root` and `find_root` accept arrays for most arguments. + For instance, to find the root for a few values of the parameter ``c`` + at once: + + >>> import numpy as np + >>> c = np.asarray([3, 4, 5]) + >>> res_bracket = elementwise.bracket_root(f, 0, args=(c,)) + >>> res_bracket.bracket + (array([1., 1., 2.]), array([2., 2., 4.])) + >>> res_root = elementwise.find_root(f, res_bracket.bracket, args=(c,)) + >>> res_root.x + array([1.8932892 , 2. , 2.09455148]) + + """ # noqa: E501 + + res = _bracket_root(f, xl0, xr0=xr0, xmin=xmin, xmax=xmax, factor=factor, + args=args, maxiter=maxiter) + res.bracket = res.xl, res.xr + res.f_bracket = res.fl, res.fr + del res.xl + del res.xr + del res.fl + del res.fr + return res + + +def bracket_minimum(f, xm0, *, xl0=None, xr0=None, xmin=None, xmax=None, + factor=None, args=(), maxiter=1000): + """Bracket the minimum of a unimodal, real-valued function of a real variable. + + For each element of the output of `f`, `bracket_minimum` seeks the scalar + bracket points ``xl < xm < xr`` such that ``fl >= fm <= fr`` where one of the + inequalities is strict. + + The function is guaranteed to find a valid bracket if the function is + strongly unimodal, but it may find a bracket under other conditions. + + This function works elementwise when `xm0`, `xl0`, `xr0`, `xmin`, `xmax`, `factor`, + and the elements of `args` are (mutually broadcastable) arrays. + + Parameters + ---------- + f : callable + The function for which the root is to be bracketed. The signature must be:: + + f(x: array, *args) -> array + + where each element of ``x`` is a finite real and ``args`` is a tuple, + which may contain an arbitrary number of arrays that are broadcastable + with ``x``. + + `f` must be an elementwise function: each element ``f(x)[i]`` + must equal ``f(x[i])`` for all indices ``i``. It must not mutate the + array ``x`` or the arrays in ``args``. + xm0: float array_like + Starting guess for middle point of bracket. + xl0, xr0: float array_like, optional + Starting guesses for left and right endpoints of the bracket. Must + be broadcastable with all other array inputs. + xmin, xmax : float array_like, optional + Minimum and maximum allowable endpoints of the bracket, inclusive. Must + be broadcastable with all other array inputs. + factor : float array_like, default: 2 + The factor used to grow the bracket. See Notes. + args : tuple of array_like, optional + Additional positional array arguments to be passed to `f`. + If the callable for which the root is desired requires arguments that are + not broadcastable with `x`, wrap that callable with `f` such that `f` + accepts only `x` and broadcastable ``*args``. + maxiter : int, default: 1000 + The maximum number of iterations of the algorithm to perform. + + Returns + ------- + res : _RichResult + An object similar to an instance of `scipy.optimize.OptimizeResult` with the + following attributes. The descriptions are written as though the values will + be scalars; however, if `f` returns an array, the outputs will be + arrays of the same shape. + + success : bool array + ``True`` where the algorithm terminated successfully (status ``0``); + ``False`` otherwise. + status : int array + An integer representing the exit status of the algorithm. + + - ``0`` : The algorithm produced a valid bracket. + - ``-1`` : The bracket expanded to the allowable limits. Assuming + unimodality, this implies the endpoint at the limit is a minimizer. + - ``-2`` : The maximum number of iterations was reached. + - ``-3`` : A non-finite value was encountered. + - ``-4`` : ``None`` shall pass. + - ``-5`` : The initial bracket does not satisfy + `xmin <= xl0 < xm0 < xr0 <= xmax`. + + bracket : 3-tuple of float arrays + The left, middle, and right points of the bracket, if the algorithm + terminated successfully. + f_bracket : 3-tuple of float arrays + The function value at the left, middle, and right points of the bracket. + nfev : int array + The number of abscissae at which `f` was evaluated to find the root. + This is distinct from the number of times `f` is *called* because the + the function may evaluated at multiple points in a single call. + nit : int array + The number of iterations of the algorithm that were performed. + + Notes + ----- + Similar to `scipy.optimize.bracket`, this function seeks to find real + points ``xl < xm < xr`` such that ``f(xl) >= f(xm)`` and ``f(xr) >= f(xm)``, + where at least one of the inequalities is strict. Unlike `scipy.optimize.bracket`, + this function can operate in a vectorized manner on array input, so long as + the input arrays are broadcastable with each other. Also unlike + `scipy.optimize.bracket`, users may specify minimum and maximum endpoints + for the desired bracket. + + Given an initial trio of points ``xl = xl0``, ``xm = xm0``, ``xr = xr0``, + the algorithm checks if these points already give a valid bracket. If not, + a new endpoint, ``w`` is chosen in the "downhill" direction, ``xm`` becomes the new + opposite endpoint, and either `xl` or `xr` becomes the new middle point, + depending on which direction is downhill. The algorithm repeats from here. + + The new endpoint `w` is chosen differently depending on whether or not a + boundary `xmin` or `xmax` has been set in the downhill direction. Without + loss of generality, suppose the downhill direction is to the right, so that + ``f(xl) > f(xm) > f(xr)``. If there is no boundary to the right, then `w` + is chosen to be ``xr + factor * (xr - xm)`` where `factor` is controlled by + the user (defaults to 2.0) so that step sizes increase in geometric proportion. + If there is a boundary, `xmax` in this case, then `w` is chosen to be + ``xmax - (xmax - xr)/factor``, with steps slowing to a stop at + `xmax`. This cautious approach ensures that a minimum near but distinct from + the boundary isn't missed while also detecting whether or not the `xmax` is + a minimizer when `xmax` is reached after a finite number of steps. + + See Also + -------- + scipy.optimize.bracket + scipy.optimize.elementwise.find_minimum + + Examples + -------- + Suppose we wish to minimize the following function. + + >>> def f(x, c=1): + ... return (x - c)**2 + 2 + + First, we must find a valid bracket. The function is unimodal, + so `bracket_minium` will easily find a bracket. + + >>> from scipy.optimize import elementwise + >>> res_bracket = elementwise.bracket_minimum(f, 0) + >>> res_bracket.success + True + >>> res_bracket.bracket + (0.0, 0.5, 1.5) + + Indeed, the bracket points are ordered and the function value + at the middle bracket point is less than at the surrounding + points. + + >>> xl, xm, xr = res_bracket.bracket + >>> fl, fm, fr = res_bracket.f_bracket + >>> (xl < xm < xr) and (fl > fm <= fr) + True + + Once we have a valid bracket, `find_minimum` can be used to provide + an estimate of the minimizer. + + >>> res_minimum = elementwise.find_minimum(f, res_bracket.bracket) + >>> res_minimum.x + 1.0000000149011612 + + `bracket_minimum` and `find_minimum` accept arrays for most arguments. + For instance, to find the minimizers and minima for a few values of the + parameter ``c`` at once: + + >>> import numpy as np + >>> c = np.asarray([1, 1.5, 2]) + >>> res_bracket = elementwise.bracket_minimum(f, 0, args=(c,)) + >>> res_bracket.bracket + (array([0. , 0.5, 0.5]), array([0.5, 1.5, 1.5]), array([1.5, 2.5, 2.5])) + >>> res_minimum = elementwise.find_minimum(f, res_bracket.bracket, args=(c,)) + >>> res_minimum.x + array([1.00000001, 1.5 , 2. ]) + >>> res_minimum.f_x + array([2., 2., 2.]) + + """ # noqa: E501 + + res = _bracket_minimum(f, xm0, xl0=xl0, xr0=xr0, xmin=xmin, xmax=xmax, + factor=factor, args=args, maxiter=maxiter) + res.bracket = res.xl, res.xm, res.xr + res.f_bracket = res.fl, res.fm, res.fr + del res.xl + del res.xm + del res.xr + del res.fl + del res.fm + del res.fr + return res diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_group_columns.cpython-310-x86_64-linux-gnu.so b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_group_columns.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..426fa2565038a67cd669485576802658a2f48d8f Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_group_columns.cpython-310-x86_64-linux-gnu.so differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_hessian_update_strategy.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_hessian_update_strategy.py new file mode 100644 index 0000000000000000000000000000000000000000..15989969349025fd42fba9836b4f5d882c3f6791 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_hessian_update_strategy.py @@ -0,0 +1,479 @@ +"""Hessian update strategies for quasi-Newton optimization methods.""" +import numpy as np +from numpy.linalg import norm +from scipy.linalg import get_blas_funcs, issymmetric +from warnings import warn + + +__all__ = ['HessianUpdateStrategy', 'BFGS', 'SR1'] + + +class HessianUpdateStrategy: + """Interface for implementing Hessian update strategies. + + Many optimization methods make use of Hessian (or inverse Hessian) + approximations, such as the quasi-Newton methods BFGS, SR1, L-BFGS. + Some of these approximations, however, do not actually need to store + the entire matrix or can compute the internal matrix product with a + given vector in a very efficiently manner. This class serves as an + abstract interface between the optimization algorithm and the + quasi-Newton update strategies, giving freedom of implementation + to store and update the internal matrix as efficiently as possible. + Different choices of initialization and update procedure will result + in different quasi-Newton strategies. + + Four methods should be implemented in derived classes: ``initialize``, + ``update``, ``dot`` and ``get_matrix``. The matrix multiplication + operator ``@`` is also defined to call the ``dot`` method. + + Notes + ----- + Any instance of a class that implements this interface, + can be accepted by the method ``minimize`` and used by + the compatible solvers to approximate the Hessian (or + inverse Hessian) used by the optimization algorithms. + """ + + def initialize(self, n, approx_type): + """Initialize internal matrix. + + Allocate internal memory for storing and updating + the Hessian or its inverse. + + Parameters + ---------- + n : int + Problem dimension. + approx_type : {'hess', 'inv_hess'} + Selects either the Hessian or the inverse Hessian. + When set to 'hess' the Hessian will be stored and updated. + When set to 'inv_hess' its inverse will be used instead. + """ + raise NotImplementedError("The method ``initialize(n, approx_type)``" + " is not implemented.") + + def update(self, delta_x, delta_grad): + """Update internal matrix. + + Update Hessian matrix or its inverse (depending on how 'approx_type' + is defined) using information about the last evaluated points. + + Parameters + ---------- + delta_x : ndarray + The difference between two points the gradient + function have been evaluated at: ``delta_x = x2 - x1``. + delta_grad : ndarray + The difference between the gradients: + ``delta_grad = grad(x2) - grad(x1)``. + """ + raise NotImplementedError("The method ``update(delta_x, delta_grad)``" + " is not implemented.") + + def dot(self, p): + """Compute the product of the internal matrix with the given vector. + + Parameters + ---------- + p : array_like + 1-D array representing a vector. + + Returns + ------- + Hp : array + 1-D represents the result of multiplying the approximation matrix + by vector p. + """ + raise NotImplementedError("The method ``dot(p)``" + " is not implemented.") + + def get_matrix(self): + """Return current internal matrix. + + Returns + ------- + H : ndarray, shape (n, n) + Dense matrix containing either the Hessian + or its inverse (depending on how 'approx_type' + is defined). + """ + raise NotImplementedError("The method ``get_matrix(p)``" + " is not implemented.") + + def __matmul__(self, p): + return self.dot(p) + + +class FullHessianUpdateStrategy(HessianUpdateStrategy): + """Hessian update strategy with full dimensional internal representation. + """ + _syr = get_blas_funcs('syr', dtype='d') # Symmetric rank 1 update + _syr2 = get_blas_funcs('syr2', dtype='d') # Symmetric rank 2 update + # Symmetric matrix-vector product + _symv = get_blas_funcs('symv', dtype='d') + + def __init__(self, init_scale='auto'): + self.init_scale = init_scale + # Until initialize is called we can't really use the class, + # so it makes sense to set everything to None. + self.first_iteration = None + self.approx_type = None + self.B = None + self.H = None + + def initialize(self, n, approx_type): + """Initialize internal matrix. + + Allocate internal memory for storing and updating + the Hessian or its inverse. + + Parameters + ---------- + n : int + Problem dimension. + approx_type : {'hess', 'inv_hess'} + Selects either the Hessian or the inverse Hessian. + When set to 'hess' the Hessian will be stored and updated. + When set to 'inv_hess' its inverse will be used instead. + """ + self.first_iteration = True + self.n = n + self.approx_type = approx_type + if approx_type not in ('hess', 'inv_hess'): + raise ValueError("`approx_type` must be 'hess' or 'inv_hess'.") + # Create matrix + if self.approx_type == 'hess': + self.B = np.eye(n, dtype=float) + else: + self.H = np.eye(n, dtype=float) + + def _auto_scale(self, delta_x, delta_grad): + # Heuristic to scale matrix at first iteration. + # Described in Nocedal and Wright "Numerical Optimization" + # p.143 formula (6.20). + s_norm2 = np.dot(delta_x, delta_x) + y_norm2 = np.dot(delta_grad, delta_grad) + ys = np.abs(np.dot(delta_grad, delta_x)) + if ys == 0.0 or y_norm2 == 0 or s_norm2 == 0: + return 1 + if self.approx_type == 'hess': + return y_norm2 / ys + else: + return ys / y_norm2 + + def _update_implementation(self, delta_x, delta_grad): + raise NotImplementedError("The method ``_update_implementation``" + " is not implemented.") + + def update(self, delta_x, delta_grad): + """Update internal matrix. + + Update Hessian matrix or its inverse (depending on how 'approx_type' + is defined) using information about the last evaluated points. + + Parameters + ---------- + delta_x : ndarray + The difference between two points the gradient + function have been evaluated at: ``delta_x = x2 - x1``. + delta_grad : ndarray + The difference between the gradients: + ``delta_grad = grad(x2) - grad(x1)``. + """ + if np.all(delta_x == 0.0): + return + if np.all(delta_grad == 0.0): + warn('delta_grad == 0.0. Check if the approximated ' + 'function is linear. If the function is linear ' + 'better results can be obtained by defining the ' + 'Hessian as zero instead of using quasi-Newton ' + 'approximations.', + UserWarning, stacklevel=2) + return + if self.first_iteration: + # Get user specific scale + if isinstance(self.init_scale, str) and self.init_scale == "auto": + scale = self._auto_scale(delta_x, delta_grad) + else: + scale = self.init_scale + + # Check for complex: numpy will silently cast a complex array to + # a real one but not so for scalar as it raises a TypeError. + # Checking here brings a consistent behavior. + replace = False + if np.size(scale) == 1: + # to account for the legacy behavior having the exact same cast + scale = float(scale) + elif np.iscomplexobj(scale): + raise TypeError("init_scale contains complex elements, " + "must be real.") + else: # test explicitly for allowed shapes and values + replace = True + if self.approx_type == 'hess': + shape = np.shape(self.B) + dtype = self.B.dtype + else: + shape = np.shape(self.H) + dtype = self.H.dtype + # copy, will replace the original + scale = np.array(scale, dtype=dtype, copy=True) + + # it has to match the shape of the matrix for the multiplication, + # no implicit broadcasting is allowed + if shape != (init_shape := np.shape(scale)): + raise ValueError("If init_scale is an array, it must have the " + f"dimensions of the hess/inv_hess: {shape}." + f" Got {init_shape}.") + if not issymmetric(scale): + raise ValueError("If init_scale is an array, it must be" + " symmetric (passing scipy.linalg.issymmetric)" + " to be an approximation of a hess/inv_hess.") + + # Scale initial matrix with ``scale * np.eye(n)`` or replace + # This is not ideal, we could assign the scale directly in + # initialize, but we would need to + if self.approx_type == 'hess': + if replace: + self.B = scale + else: + self.B *= scale + else: + if replace: + self.H = scale + else: + self.H *= scale + self.first_iteration = False + self._update_implementation(delta_x, delta_grad) + + def dot(self, p): + """Compute the product of the internal matrix with the given vector. + + Parameters + ---------- + p : array_like + 1-D array representing a vector. + + Returns + ------- + Hp : array + 1-D represents the result of multiplying the approximation matrix + by vector p. + """ + if self.approx_type == 'hess': + return self._symv(1, self.B, p) + else: + return self._symv(1, self.H, p) + + def get_matrix(self): + """Return the current internal matrix. + + Returns + ------- + M : ndarray, shape (n, n) + Dense matrix containing either the Hessian or its inverse + (depending on how `approx_type` was defined). + """ + if self.approx_type == 'hess': + M = np.copy(self.B) + else: + M = np.copy(self.H) + li = np.tril_indices_from(M, k=-1) + M[li] = M.T[li] + return M + + +class BFGS(FullHessianUpdateStrategy): + """Broyden-Fletcher-Goldfarb-Shanno (BFGS) Hessian update strategy. + + Parameters + ---------- + exception_strategy : {'skip_update', 'damp_update'}, optional + Define how to proceed when the curvature condition is violated. + Set it to 'skip_update' to just skip the update. Or, alternatively, + set it to 'damp_update' to interpolate between the actual BFGS + result and the unmodified matrix. Both exceptions strategies + are explained in [1]_, p.536-537. + min_curvature : float + This number, scaled by a normalization factor, defines the + minimum curvature ``dot(delta_grad, delta_x)`` allowed to go + unaffected by the exception strategy. By default is equal to + 1e-8 when ``exception_strategy = 'skip_update'`` and equal + to 0.2 when ``exception_strategy = 'damp_update'``. + init_scale : {float, np.array, 'auto'} + This parameter can be used to initialize the Hessian or its + inverse. When a float is given, the relevant array is initialized + to ``np.eye(n) * init_scale``, where ``n`` is the problem dimension. + Alternatively, if a precisely ``(n, n)`` shaped, symmetric array is given, + this array will be used. Otherwise an error is generated. + Set it to 'auto' in order to use an automatic heuristic for choosing + the initial scale. The heuristic is described in [1]_, p.143. + The default is 'auto'. + + Notes + ----- + The update is based on the description in [1]_, p.140. + + References + ---------- + .. [1] Nocedal, Jorge, and Stephen J. Wright. "Numerical optimization" + Second Edition (2006). + """ + + def __init__(self, exception_strategy='skip_update', min_curvature=None, + init_scale='auto'): + if exception_strategy == 'skip_update': + if min_curvature is not None: + self.min_curvature = min_curvature + else: + self.min_curvature = 1e-8 + elif exception_strategy == 'damp_update': + if min_curvature is not None: + self.min_curvature = min_curvature + else: + self.min_curvature = 0.2 + else: + raise ValueError("`exception_strategy` must be 'skip_update' " + "or 'damp_update'.") + + super().__init__(init_scale) + self.exception_strategy = exception_strategy + + def _update_inverse_hessian(self, ys, Hy, yHy, s): + """Update the inverse Hessian matrix. + + BFGS update using the formula: + + ``H <- H + ((H*y).T*y + s.T*y)/(s.T*y)^2 * (s*s.T) + - 1/(s.T*y) * ((H*y)*s.T + s*(H*y).T)`` + + where ``s = delta_x`` and ``y = delta_grad``. This formula is + equivalent to (6.17) in [1]_ written in a more efficient way + for implementation. + + References + ---------- + .. [1] Nocedal, Jorge, and Stephen J. Wright. "Numerical optimization" + Second Edition (2006). + """ + self.H = self._syr2(-1.0 / ys, s, Hy, a=self.H) + self.H = self._syr((ys + yHy) / ys ** 2, s, a=self.H) + + def _update_hessian(self, ys, Bs, sBs, y): + """Update the Hessian matrix. + + BFGS update using the formula: + + ``B <- B - (B*s)*(B*s).T/s.T*(B*s) + y*y^T/s.T*y`` + + where ``s`` is short for ``delta_x`` and ``y`` is short + for ``delta_grad``. Formula (6.19) in [1]_. + + References + ---------- + .. [1] Nocedal, Jorge, and Stephen J. Wright. "Numerical optimization" + Second Edition (2006). + """ + self.B = self._syr(1.0 / ys, y, a=self.B) + self.B = self._syr(-1.0 / sBs, Bs, a=self.B) + + def _update_implementation(self, delta_x, delta_grad): + # Auxiliary variables w and z + if self.approx_type == 'hess': + w = delta_x + z = delta_grad + else: + w = delta_grad + z = delta_x + # Do some common operations + wz = np.dot(w, z) + Mw = self @ w + wMw = Mw.dot(w) + # Guarantee that wMw > 0 by reinitializing matrix. + # While this is always true in exact arithmetic, + # indefinite matrix may appear due to roundoff errors. + if wMw <= 0.0: + scale = self._auto_scale(delta_x, delta_grad) + # Reinitialize matrix + if self.approx_type == 'hess': + self.B = scale * np.eye(self.n, dtype=float) + else: + self.H = scale * np.eye(self.n, dtype=float) + # Do common operations for new matrix + Mw = self @ w + wMw = Mw.dot(w) + # Check if curvature condition is violated + if wz <= self.min_curvature * wMw: + # If the option 'skip_update' is set + # we just skip the update when the condition + # is violated. + if self.exception_strategy == 'skip_update': + return + # If the option 'damp_update' is set we + # interpolate between the actual BFGS + # result and the unmodified matrix. + elif self.exception_strategy == 'damp_update': + update_factor = (1-self.min_curvature) / (1 - wz/wMw) + z = update_factor*z + (1-update_factor)*Mw + wz = np.dot(w, z) + # Update matrix + if self.approx_type == 'hess': + self._update_hessian(wz, Mw, wMw, z) + else: + self._update_inverse_hessian(wz, Mw, wMw, z) + + +class SR1(FullHessianUpdateStrategy): + """Symmetric-rank-1 Hessian update strategy. + + Parameters + ---------- + min_denominator : float + This number, scaled by a normalization factor, + defines the minimum denominator magnitude allowed + in the update. When the condition is violated we skip + the update. By default uses ``1e-8``. + init_scale : {float, np.array, 'auto'}, optional + This parameter can be used to initialize the Hessian or its + inverse. When a float is given, the relevant array is initialized + to ``np.eye(n) * init_scale``, where ``n`` is the problem dimension. + Alternatively, if a precisely ``(n, n)`` shaped, symmetric array is given, + this array will be used. Otherwise an error is generated. + Set it to 'auto' in order to use an automatic heuristic for choosing + the initial scale. The heuristic is described in [1]_, p.143. + The default is 'auto'. + + Notes + ----- + The update is based on the description in [1]_, p.144-146. + + References + ---------- + .. [1] Nocedal, Jorge, and Stephen J. Wright. "Numerical optimization" + Second Edition (2006). + """ + + def __init__(self, min_denominator=1e-8, init_scale='auto'): + self.min_denominator = min_denominator + super().__init__(init_scale) + + def _update_implementation(self, delta_x, delta_grad): + # Auxiliary variables w and z + if self.approx_type == 'hess': + w = delta_x + z = delta_grad + else: + w = delta_grad + z = delta_x + # Do some common operations + Mw = self @ w + z_minus_Mw = z - Mw + denominator = np.dot(w, z_minus_Mw) + # If the denominator is too small + # we just skip the update. + if np.abs(denominator) <= self.min_denominator*norm(w)*norm(z_minus_Mw): + return + # Update matrix + if self.approx_type == 'hess': + self.B = self._syr(1/denominator, z_minus_Mw, a=self.B) + else: + self.H = self._syr(1/denominator, z_minus_Mw, a=self.H) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_highspy/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_highspy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_highspy/_highs_wrapper.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_highspy/_highs_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..c88f0fb14c627b10584995fbde17f3a0e445b0cf --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_highspy/_highs_wrapper.py @@ -0,0 +1,338 @@ +from warnings import warn + +import numpy as np +import scipy.optimize._highspy._core as _h # type: ignore[import-not-found] +from scipy.optimize._highspy import _highs_options as hopt # type: ignore[attr-defined] +from scipy.optimize import OptimizeWarning + + +def _highs_wrapper(c, indptr, indices, data, lhs, rhs, lb, ub, integrality, options): + '''Solve linear programs using HiGHS [1]_. + + Assume problems of the form: + + MIN c.T @ x + s.t. lhs <= A @ x <= rhs + lb <= x <= ub + + Parameters + ---------- + c : 1-D array, (n,) + Array of objective value coefficients. + astart : 1-D array + CSC format index array. + aindex : 1-D array + CSC format index array. + avalue : 1-D array + Data array of the matrix. + lhs : 1-D array (or None), (m,) + Array of left hand side values of the inequality constraints. + If ``lhs=None``, then an array of ``-inf`` is assumed. + rhs : 1-D array, (m,) + Array of right hand side values of the inequality constraints. + lb : 1-D array (or None), (n,) + Lower bounds on solution variables x. If ``lb=None``, then an + array of all `0` is assumed. + ub : 1-D array (or None), (n,) + Upper bounds on solution variables x. If ``ub=None``, then an + array of ``inf`` is assumed. + options : dict + A dictionary of solver options + + Returns + ------- + res : dict + + If model_status is one of kOptimal, + kObjectiveBound, kTimeLimit, + kIterationLimit: + + - ``status`` : HighsModelStatus + Model status code. + + - ``message`` : str + Message corresponding to model status code. + + - ``x`` : list + Solution variables. + + - ``slack`` : list + Slack variables. + + - ``lambda`` : list + Lagrange multipliers associated with the constraints + Ax = b. + + - ``s`` : list + Lagrange multipliers associated with the constraints + x >= 0. + + - ``fun`` + Final objective value. + + - ``simplex_nit`` : int + Number of iterations accomplished by the simplex + solver. + + - ``ipm_nit`` : int + Number of iterations accomplished by the interior- + point solver. + + If model_status is not one of the above: + + - ``status`` : HighsModelStatus + Model status code. + + - ``message`` : str + Message corresponding to model status code. + + Notes + ----- + If ``options['write_solution_to_file']`` is ``True`` but + ``options['solution_file']`` is unset or ``''``, then the solution + will be printed to ``stdout``. + + If any iteration limit is reached, no solution will be + available. + + ``OptimizeWarning`` will be raised if any option value set by + the user is found to be incorrect. + + References + ---------- + .. [1] https://highs.dev/ + .. [2] https://www.maths.ed.ac.uk/hall/HiGHS/HighsOptions.html + ''' + numcol = c.size + numrow = rhs.size + isMip = integrality is not None and np.sum(integrality) > 0 + + # default "null" return values + res = { + "x": None, + "fun": None, + } + + # Fill up a HighsLp object + lp = _h.HighsLp() + lp.num_col_ = numcol + lp.num_row_ = numrow + lp.a_matrix_.num_col_ = numcol + lp.a_matrix_.num_row_ = numrow + lp.a_matrix_.format_ = _h.MatrixFormat.kColwise + lp.col_cost_ = c + lp.col_lower_ = lb + lp.col_upper_ = ub + lp.row_lower_ = lhs + lp.row_upper_ = rhs + lp.a_matrix_.start_ = indptr + lp.a_matrix_.index_ = indices + lp.a_matrix_.value_ = data + if integrality.size > 0: + lp.integrality_ = [_h.HighsVarType(i) for i in integrality] + + # Make a Highs object and pass it everything + highs = _h._Highs() + highs_options = _h.HighsOptions() + hoptmanager = hopt.HighsOptionsManager() + for key, val in options.items(): + # handle filtering of unsupported and default options + if val is None or key in ("sense",): + continue + + # ask for the option type + opt_type = hoptmanager.get_option_type(key) + if -1 == opt_type: + warn( + f"Unrecognized options detected: {dict({key: val})}", + OptimizeWarning, + stacklevel=2, + ) + continue + else: + if key in ("presolve", "parallel"): + # handle fake bools (require bool -> str conversions) + if isinstance(val, bool): + val = "on" if val else "off" + else: + warn( + f'Option f"{key}" is "{val}", but only True or False is ' + f"allowed. Using default.", + OptimizeWarning, + stacklevel=2, + ) + continue + opt_type = _h.HighsOptionType(opt_type) + status, msg = check_option(highs, key, val) + if opt_type == _h.HighsOptionType.kBool: + if not isinstance(val, bool): + warn( + f'Option f"{key}" is "{val}", but only True or False is ' + f"allowed. Using default.", + OptimizeWarning, + stacklevel=2, + ) + continue + + # warn or set option + if status != 0: + warn(msg, OptimizeWarning, stacklevel=2) + else: + setattr(highs_options, key, val) + + opt_status = highs.passOptions(highs_options) + if opt_status == _h.HighsStatus.kError: + res.update( + { + "status": highs.getModelStatus(), + "message": highs.modelStatusToString(highs.getModelStatus()), + } + ) + return res + + init_status = highs.passModel(lp) + if init_status == _h.HighsStatus.kError: + # if model fails to load, highs.getModelStatus() will be NOT_SET + err_model_status = _h.HighsModelStatus.kModelError + res.update( + { + "status": err_model_status, + "message": highs.modelStatusToString(err_model_status), + } + ) + return res + + # Solve the LP + run_status = highs.run() + if run_status == _h.HighsStatus.kError: + res.update( + { + "status": highs.getModelStatus(), + "message": highs.modelStatusToString(highs.getModelStatus()), + } + ) + return res + + # Extract what we need from the solution + model_status = highs.getModelStatus() + + # it should always be safe to get the info object + info = highs.getInfo() + + # Failure modes: + # LP: if we have anything other than an Optimal status, it + # is unsafe (and unhelpful) to read any results + # MIP: has a non-Optimal status or has timed out/reached max iterations + # 1) If not Optimal/TimedOut/MaxIter status, there is no solution + # 2) If TimedOut/MaxIter status, there may be a feasible solution. + # if the objective function value is not Infinity, then the + # current solution is feasible and can be returned. Else, there + # is no solution. + mipFailCondition = model_status not in ( + _h.HighsModelStatus.kOptimal, + _h.HighsModelStatus.kTimeLimit, + _h.HighsModelStatus.kIterationLimit, + _h.HighsModelStatus.kSolutionLimit, + ) or ( + model_status + in { + _h.HighsModelStatus.kTimeLimit, + _h.HighsModelStatus.kIterationLimit, + _h.HighsModelStatus.kSolutionLimit, + } + and (info.objective_function_value == _h.kHighsInf) + ) + lpFailCondition = model_status != _h.HighsModelStatus.kOptimal + if (isMip and mipFailCondition) or (not isMip and lpFailCondition): + res.update( + { + "status": model_status, + "message": "model_status is " + f"{highs.modelStatusToString(model_status)}; " + "primal_status is " + f"{highs.solutionStatusToString(info.primal_solution_status)}", + "simplex_nit": info.simplex_iteration_count, + "ipm_nit": info.ipm_iteration_count, + "crossover_nit": info.crossover_iteration_count, + } + ) + return res + + # Should be safe to read the solution: + solution = highs.getSolution() + basis = highs.getBasis() + + # Lagrangians for bounds based on column statuses + marg_bnds = np.zeros((2, numcol)) + basis_col_status = basis.col_status + solution_col_dual = solution.col_dual + for ii in range(numcol): + if basis_col_status[ii] == _h.HighsBasisStatus.kLower: + marg_bnds[0, ii] = solution_col_dual[ii] + elif basis_col_status[ii] == _h.HighsBasisStatus.kUpper: + marg_bnds[1, ii] = solution_col_dual[ii] + + res.update( + { + "status": model_status, + "message": highs.modelStatusToString(model_status), + # Primal solution + "x": np.array(solution.col_value), + # Ax + s = b => Ax = b - s + # Note: this is for all constraints (A_ub and A_eq) + "slack": rhs - solution.row_value, + # lambda are the lagrange multipliers associated with Ax=b + "lambda": np.array(solution.row_dual), + "marg_bnds": marg_bnds, + "fun": info.objective_function_value, + "simplex_nit": info.simplex_iteration_count, + "ipm_nit": info.ipm_iteration_count, + "crossover_nit": info.crossover_iteration_count, + } + ) + + if isMip: + res.update( + { + "mip_node_count": info.mip_node_count, + "mip_dual_bound": info.mip_dual_bound, + "mip_gap": info.mip_gap, + } + ) + + return res + + +def check_option(highs_inst, option, value): + status, option_type = highs_inst.getOptionType(option) + hoptmanager = hopt.HighsOptionsManager() + + if status != _h.HighsStatus.kOk: + return -1, "Invalid option name." + + valid_types = { + _h.HighsOptionType.kBool: bool, + _h.HighsOptionType.kInt: int, + _h.HighsOptionType.kDouble: float, + _h.HighsOptionType.kString: str, + } + + expected_type = valid_types.get(option_type, None) + + if expected_type is str: + if not hoptmanager.check_string_option(option, value): + return -1, "Invalid option value." + if expected_type is float: + if not hoptmanager.check_double_option(option, value): + return -1, "Invalid option value." + if expected_type is int: + if not hoptmanager.check_int_option(option, value): + return -1, "Invalid option value." + + if expected_type is None: + return 3, "Unknown option type." + + status, current_value = highs_inst.getOptionValue(option) + if status != _h.HighsStatus.kOk: + return 4, "Failed to validate option value." + return 0, "Check option succeeded." diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_isotonic.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_isotonic.py new file mode 100644 index 0000000000000000000000000000000000000000..825576535402a9acf8bbff009a5f76282cb4f500 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_isotonic.py @@ -0,0 +1,157 @@ +from typing import TYPE_CHECKING + +import numpy as np + +from ._optimize import OptimizeResult +from ._pava_pybind import pava + +if TYPE_CHECKING: + import numpy.typing as npt + + +__all__ = ["isotonic_regression"] + + +def isotonic_regression( + y: "npt.ArrayLike", + *, + weights: "npt.ArrayLike | None" = None, + increasing: bool = True, +) -> OptimizeResult: + r"""Nonparametric isotonic regression. + + A (not strictly) monotonically increasing array `x` with the same length + as `y` is calculated by the pool adjacent violators algorithm (PAVA), see + [1]_. See the Notes section for more details. + + Parameters + ---------- + y : (N,) array_like + Response variable. + weights : (N,) array_like or None + Case weights. + increasing : bool + If True, fit monotonic increasing, i.e. isotonic, regression. + If False, fit a monotonic decreasing, i.e. antitonic, regression. + Default is True. + + Returns + ------- + res : OptimizeResult + The optimization result represented as a ``OptimizeResult`` object. + Important attributes are: + + - ``x``: The isotonic regression solution, i.e. an increasing (or + decreasing) array of the same length than y, with elements in the + range from min(y) to max(y). + - ``weights`` : Array with the sum of case weights for each block + (or pool) B. + - ``blocks``: Array of length B+1 with the indices of the start + positions of each block (or pool) B. The j-th block is given by + ``x[blocks[j]:blocks[j+1]]`` for which all values are the same. + + Notes + ----- + Given data :math:`y` and case weights :math:`w`, the isotonic regression + solves the following optimization problem: + + .. math:: + + \operatorname{argmin}_{x_i} \sum_i w_i (y_i - x_i)^2 \quad + \text{subject to } x_i \leq x_j \text{ whenever } i \leq j \,. + + For every input value :math:`y_i`, it generates a value :math:`x_i` such + that :math:`x` is increasing (but not strictly), i.e. + :math:`x_i \leq x_{i+1}`. This is accomplished by the PAVA. + The solution consists of pools or blocks, i.e. neighboring elements of + :math:`x`, e.g. :math:`x_i` and :math:`x_{i+1}`, that all have the same + value. + + Most interestingly, the solution stays the same if the squared loss is + replaced by the wide class of Bregman functions which are the unique + class of strictly consistent scoring functions for the mean, see [2]_ + and references therein. + + The implemented version of PAVA according to [1]_ has a computational + complexity of O(N) with input size N. + + References + ---------- + .. [1] Busing, F. M. T. A. (2022). + Monotone Regression: A Simple and Fast O(n) PAVA Implementation. + Journal of Statistical Software, Code Snippets, 102(1), 1-25. + :doi:`10.18637/jss.v102.c01` + .. [2] Jordan, A.I., Mühlemann, A. & Ziegel, J.F. + Characterizing the optimal solutions to the isotonic regression + problem for identifiable functionals. + Ann Inst Stat Math 74, 489-514 (2022). + :doi:`10.1007/s10463-021-00808-0` + + Examples + -------- + This example demonstrates that ``isotonic_regression`` really solves a + constrained optimization problem. + + >>> import numpy as np + >>> from scipy.optimize import isotonic_regression, minimize + >>> y = [1.5, 1.0, 4.0, 6.0, 5.7, 5.0, 7.8, 9.0, 7.5, 9.5, 9.0] + >>> def objective(yhat, y): + ... return np.sum((yhat - y)**2) + >>> def constraint(yhat, y): + ... # This is for a monotonically increasing regression. + ... return np.diff(yhat) + >>> result = minimize(objective, x0=y, args=(y,), + ... constraints=[{'type': 'ineq', + ... 'fun': lambda x: constraint(x, y)}]) + >>> result.x + array([1.25 , 1.25 , 4. , 5.56666667, 5.56666667, + 5.56666667, 7.8 , 8.25 , 8.25 , 9.25 , + 9.25 ]) + >>> result = isotonic_regression(y) + >>> result.x + array([1.25 , 1.25 , 4. , 5.56666667, 5.56666667, + 5.56666667, 7.8 , 8.25 , 8.25 , 9.25 , + 9.25 ]) + + The big advantage of ``isotonic_regression`` compared to calling + ``minimize`` is that it is more user friendly, i.e. one does not need to + define objective and constraint functions, and that it is orders of + magnitudes faster. On commodity hardware (in 2023), for normal distributed + input y of length 1000, the minimizer takes about 4 seconds, while + ``isotonic_regression`` takes about 200 microseconds. + """ + yarr = np.atleast_1d(y) # Check yarr.ndim == 1 is implicit (pybind11) in pava. + order = slice(None) if increasing else slice(None, None, -1) + x = np.array(yarr[order], order="C", dtype=np.float64, copy=True) + if weights is None: + wx = np.ones_like(yarr, dtype=np.float64) + else: + warr = np.atleast_1d(weights) + + if not (yarr.ndim == warr.ndim == 1 and yarr.shape[0] == warr.shape[0]): + raise ValueError( + "Input arrays y and w must have one dimension of equal length." + ) + if np.any(warr <= 0): + raise ValueError("Weights w must be strictly positive.") + + wx = np.array(warr[order], order="C", dtype=np.float64, copy=True) + n = x.shape[0] + r = np.full(shape=n + 1, fill_value=-1, dtype=np.intp) + x, wx, r, b = pava(x, wx, r) + # Now that we know the number of blocks b, we only keep the relevant part + # of r and wx. + # As information: Due to the pava implementation, after the last block + # index, there might be smaller numbers appended to r, e.g. + # r = [0, 10, 8, 7] which in the end should be r = [0, 10]. + r = r[:b + 1] # type: ignore[assignment] + wx = wx[:b] + if not increasing: + x = x[::-1] + wx = wx[::-1] + r = r[-1] - r[::-1] + return OptimizeResult( + x=x, + weights=wx, + blocks=r, + ) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_lbfgsb_py.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_lbfgsb_py.py new file mode 100644 index 0000000000000000000000000000000000000000..d0e206feaa9333229c3842850eee1f673c8ef02b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_lbfgsb_py.py @@ -0,0 +1,578 @@ +""" +Functions +--------- +.. autosummary:: + :toctree: generated/ + + fmin_l_bfgs_b + +""" + +## License for the Python wrapper +## ============================== + +## Copyright (c) 2004 David M. Cooke + +## Permission is hereby granted, free of charge, to any person obtaining a +## copy of this software and associated documentation files (the "Software"), +## to deal in the Software without restriction, including without limitation +## the rights to use, copy, modify, merge, publish, distribute, sublicense, +## and/or sell copies of the Software, and to permit persons to whom the +## Software is furnished to do so, subject to the following conditions: + +## The above copyright notice and this permission notice shall be included in +## all copies or substantial portions of the Software. + +## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +## IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +## FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +## AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +## LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +## FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +## DEALINGS IN THE SOFTWARE. + +## Modifications by Travis Oliphant and Enthought, Inc. for inclusion in SciPy + +import numpy as np +from numpy import array, asarray, float64, zeros +from . import _lbfgsb +from ._optimize import (MemoizeJac, OptimizeResult, _call_callback_maybe_halt, + _wrap_callback, _check_unknown_options, + _prepare_scalar_function) +from ._constraints import old_bound_to_new + +from scipy.sparse.linalg import LinearOperator + +__all__ = ['fmin_l_bfgs_b', 'LbfgsInvHessProduct'] + + +status_messages = { + 0 : "START", + 1 : "NEW_X", + 2 : "RESTART", + 3 : "FG", + 4 : "CONVERGENCE", + 5 : "STOP", + 6 : "WARNING", + 7 : "ERROR", + 8 : "ABNORMAL" +} + + +task_messages = { + 0 : "", + 301 : "", + 302 : "", + 401 : "NORM OF PROJECTED GRADIENT <= PGTOL", + 402 : "RELATIVE REDUCTION OF F <= FACTR*EPSMCH", + 501 : "CPU EXCEEDING THE TIME LIMIT", + 502 : "TOTAL NO. OF F,G EVALUATIONS EXCEEDS LIMIT", + 503 : "PROJECTED GRADIENT IS SUFFICIENTLY SMALL", + 504 : "TOTAL NO. OF ITERATIONS REACHED LIMIT", + 505 : "CALLBACK REQUESTED HALT", + 601 : "ROUNDING ERRORS PREVENT PROGRESS", + 602 : "STP = STPMAX", + 603 : "STP = STPMIN", + 604 : "XTOL TEST SATISFIED", + 701 : "NO FEASIBLE SOLUTION", + 702 : "FACTR < 0", + 703 : "FTOL < 0", + 704 : "GTOL < 0", + 705 : "XTOL < 0", + 706 : "STP < STPMIN", + 707 : "STP > STPMAX", + 708 : "STPMIN < 0", + 709 : "STPMAX < STPMIN", + 710 : "INITIAL G >= 0", + 711 : "M <= 0", + 712 : "N <= 0", + 713 : "INVALID NBD", +} + +def fmin_l_bfgs_b(func, x0, fprime=None, args=(), + approx_grad=0, + bounds=None, m=10, factr=1e7, pgtol=1e-5, + epsilon=1e-8, + iprint=-1, maxfun=15000, maxiter=15000, disp=None, + callback=None, maxls=20): + """ + Minimize a function func using the L-BFGS-B algorithm. + + Parameters + ---------- + func : callable f(x,*args) + Function to minimize. + x0 : ndarray + Initial guess. + fprime : callable fprime(x,*args), optional + The gradient of `func`. If None, then `func` returns the function + value and the gradient (``f, g = func(x, *args)``), unless + `approx_grad` is True in which case `func` returns only ``f``. + args : sequence, optional + Arguments to pass to `func` and `fprime`. + approx_grad : bool, optional + Whether to approximate the gradient numerically (in which case + `func` returns only the function value). + bounds : list, optional + ``(min, max)`` pairs for each element in ``x``, defining + the bounds on that parameter. Use None or +-inf for one of ``min`` or + ``max`` when there is no bound in that direction. + m : int, optional + The maximum number of variable metric corrections + used to define the limited memory matrix. (The limited memory BFGS + method does not store the full hessian but uses this many terms in an + approximation to it.) + factr : float, optional + The iteration stops when + ``(f^k - f^{k+1})/max{|f^k|,|f^{k+1}|,1} <= factr * eps``, + where ``eps`` is the machine precision, which is automatically + generated by the code. Typical values for `factr` are: 1e12 for + low accuracy; 1e7 for moderate accuracy; 10.0 for extremely + high accuracy. See Notes for relationship to `ftol`, which is exposed + (instead of `factr`) by the `scipy.optimize.minimize` interface to + L-BFGS-B. + pgtol : float, optional + The iteration will stop when + ``max{|proj g_i | i = 1, ..., n} <= pgtol`` + where ``proj g_i`` is the i-th component of the projected gradient. + epsilon : float, optional + Step size used when `approx_grad` is True, for numerically + calculating the gradient + iprint : int, optional + Deprecated option that previously controlled the text printed on the + screen during the problem solution. Now the code does not emit any + output and this keyword has no function. + + .. deprecated:: 1.15.0 + This keyword is deprecated and will be removed from SciPy 1.17.0. + + disp : int, optional + Deprecated option that previously controlled the text printed on the + screen during the problem solution. Now the code does not emit any + output and this keyword has no function. + + .. deprecated:: 1.15.0 + This keyword is deprecated and will be removed from SciPy 1.17.0. + + maxfun : int, optional + Maximum number of function evaluations. Note that this function + may violate the limit because of evaluating gradients by numerical + differentiation. + maxiter : int, optional + Maximum number of iterations. + callback : callable, optional + Called after each iteration, as ``callback(xk)``, where ``xk`` is the + current parameter vector. + maxls : int, optional + Maximum number of line search steps (per iteration). Default is 20. + + Returns + ------- + x : array_like + Estimated position of the minimum. + f : float + Value of `func` at the minimum. + d : dict + Information dictionary. + + * d['warnflag'] is + + - 0 if converged, + - 1 if too many function evaluations or too many iterations, + - 2 if stopped for another reason, given in d['task'] + + * d['grad'] is the gradient at the minimum (should be 0 ish) + * d['funcalls'] is the number of function calls made. + * d['nit'] is the number of iterations. + + See also + -------- + minimize: Interface to minimization algorithms for multivariate + functions. See the 'L-BFGS-B' `method` in particular. Note that the + `ftol` option is made available via that interface, while `factr` is + provided via this interface, where `factr` is the factor multiplying + the default machine floating-point precision to arrive at `ftol`: + ``ftol = factr * numpy.finfo(float).eps``. + + Notes + ----- + SciPy uses a C-translated and modified version of the Fortran code, + L-BFGS-B v3.0 (released April 25, 2011, BSD-3 licensed). Original Fortran + version was written by Ciyou Zhu, Richard Byrd, Jorge Nocedal and, + Jose Luis Morales. + + References + ---------- + * R. H. Byrd, P. Lu and J. Nocedal. A Limited Memory Algorithm for Bound + Constrained Optimization, (1995), SIAM Journal on Scientific and + Statistical Computing, 16, 5, pp. 1190-1208. + * C. Zhu, R. H. Byrd and J. Nocedal. L-BFGS-B: Algorithm 778: L-BFGS-B, + FORTRAN routines for large scale bound constrained optimization (1997), + ACM Transactions on Mathematical Software, 23, 4, pp. 550 - 560. + * J.L. Morales and J. Nocedal. L-BFGS-B: Remark on Algorithm 778: L-BFGS-B, + FORTRAN routines for large scale bound constrained optimization (2011), + ACM Transactions on Mathematical Software, 38, 1. + + Examples + -------- + Solve a linear regression problem via `fmin_l_bfgs_b`. To do this, first we + define an objective function ``f(m, b) = (y - y_model)**2``, where `y` + describes the observations and `y_model` the prediction of the linear model + as ``y_model = m*x + b``. The bounds for the parameters, ``m`` and ``b``, + are arbitrarily chosen as ``(0,5)`` and ``(5,10)`` for this example. + + >>> import numpy as np + >>> from scipy.optimize import fmin_l_bfgs_b + >>> X = np.arange(0, 10, 1) + >>> M = 2 + >>> B = 3 + >>> Y = M * X + B + >>> def func(parameters, *args): + ... x = args[0] + ... y = args[1] + ... m, b = parameters + ... y_model = m*x + b + ... error = sum(np.power((y - y_model), 2)) + ... return error + + >>> initial_values = np.array([0.0, 1.0]) + + >>> x_opt, f_opt, info = fmin_l_bfgs_b(func, x0=initial_values, args=(X, Y), + ... approx_grad=True) + >>> x_opt, f_opt + array([1.99999999, 3.00000006]), 1.7746231151323805e-14 # may vary + + The optimized parameters in ``x_opt`` agree with the ground truth parameters + ``m`` and ``b``. Next, let us perform a bound constrained optimization using + the `bounds` parameter. + + >>> bounds = [(0, 5), (5, 10)] + >>> x_opt, f_op, info = fmin_l_bfgs_b(func, x0=initial_values, args=(X, Y), + ... approx_grad=True, bounds=bounds) + >>> x_opt, f_opt + array([1.65990508, 5.31649385]), 15.721334516453945 # may vary + """ + # handle fprime/approx_grad + if approx_grad: + fun = func + jac = None + elif fprime is None: + fun = MemoizeJac(func) + jac = fun.derivative + else: + fun = func + jac = fprime + + # build options + callback = _wrap_callback(callback) + opts = {'maxcor': m, + 'ftol': factr * np.finfo(float).eps, + 'gtol': pgtol, + 'eps': epsilon, + 'maxfun': maxfun, + 'maxiter': maxiter, + 'callback': callback, + 'maxls': maxls} + + res = _minimize_lbfgsb(fun, x0, args=args, jac=jac, bounds=bounds, + **opts) + d = {'grad': res['jac'], + 'task': res['message'], + 'funcalls': res['nfev'], + 'nit': res['nit'], + 'warnflag': res['status']} + f = res['fun'] + x = res['x'] + + return x, f, d + + +def _minimize_lbfgsb(fun, x0, args=(), jac=None, bounds=None, + disp=None, maxcor=10, ftol=2.2204460492503131e-09, + gtol=1e-5, eps=1e-8, maxfun=15000, maxiter=15000, + iprint=-1, callback=None, maxls=20, + finite_diff_rel_step=None, **unknown_options): + """ + Minimize a scalar function of one or more variables using the L-BFGS-B + algorithm. + + Options + ------- + disp : None or int + Deprecated option that previously controlled the text printed on the + screen during the problem solution. Now the code does not emit any + output and this keyword has no function. + + .. deprecated:: 1.15.0 + This keyword is deprecated and will be removed from SciPy 1.17.0. + + maxcor : int + The maximum number of variable metric corrections used to + define the limited memory matrix. (The limited memory BFGS + method does not store the full hessian but uses this many terms + in an approximation to it.) + ftol : float + The iteration stops when ``(f^k - + f^{k+1})/max{|f^k|,|f^{k+1}|,1} <= ftol``. + gtol : float + The iteration will stop when ``max{|proj g_i | i = 1, ..., n} + <= gtol`` where ``proj g_i`` is the i-th component of the + projected gradient. + eps : float or ndarray + If `jac is None` the absolute step size used for numerical + approximation of the jacobian via forward differences. + maxfun : int + Maximum number of function evaluations. Note that this function + may violate the limit because of evaluating gradients by numerical + differentiation. + maxiter : int + Maximum number of iterations. + iprint : int, optional + Deprecated option that previously controlled the text printed on the + screen during the problem solution. Now the code does not emit any + output and this keyword has no function. + + .. deprecated:: 1.15.0 + This keyword is deprecated and will be removed from SciPy 1.17.0. + + maxls : int, optional + Maximum number of line search steps (per iteration). Default is 20. + finite_diff_rel_step : None or array_like, optional + If ``jac in ['2-point', '3-point', 'cs']`` the relative step size to + use for numerical approximation of the jacobian. The absolute step + size is computed as ``h = rel_step * sign(x) * max(1, abs(x))``, + possibly adjusted to fit into the bounds. For ``method='3-point'`` + the sign of `h` is ignored. If None (default) then step is selected + automatically. + + Notes + ----- + The option `ftol` is exposed via the `scipy.optimize.minimize` interface, + but calling `scipy.optimize.fmin_l_bfgs_b` directly exposes `factr`. The + relationship between the two is ``ftol = factr * numpy.finfo(float).eps``. + I.e., `factr` multiplies the default machine floating-point precision to + arrive at `ftol`. + + """ + _check_unknown_options(unknown_options) + m = maxcor + pgtol = gtol + factr = ftol / np.finfo(float).eps + + x0 = asarray(x0).ravel() + n, = x0.shape + + # historically old-style bounds were/are expected by lbfgsb. + # That's still the case but we'll deal with new-style from here on, + # it's easier + if bounds is None: + pass + elif len(bounds) != n: + raise ValueError('length of x0 != length of bounds') + else: + bounds = np.array(old_bound_to_new(bounds)) + + # check bounds + if (bounds[0] > bounds[1]).any(): + raise ValueError( + "LBFGSB - one of the lower bounds is greater than an upper bound." + ) + + # initial vector must lie within the bounds. Otherwise ScalarFunction and + # approx_derivative will cause problems + x0 = np.clip(x0, bounds[0], bounds[1]) + + # _prepare_scalar_function can use bounds=None to represent no bounds + sf = _prepare_scalar_function(fun, x0, jac=jac, args=args, epsilon=eps, + bounds=bounds, + finite_diff_rel_step=finite_diff_rel_step) + + func_and_grad = sf.fun_and_grad + + nbd = zeros(n, np.int32) + low_bnd = zeros(n, float64) + upper_bnd = zeros(n, float64) + bounds_map = {(-np.inf, np.inf): 0, + (1, np.inf): 1, + (1, 1): 2, + (-np.inf, 1): 3} + + if bounds is not None: + for i in range(0, n): + L, U = bounds[0, i], bounds[1, i] + if not np.isinf(L): + low_bnd[i] = L + L = 1 + if not np.isinf(U): + upper_bnd[i] = U + U = 1 + nbd[i] = bounds_map[L, U] + + if not maxls > 0: + raise ValueError('maxls must be positive.') + + x = array(x0, dtype=np.float64) + f = array(0.0, dtype=np.int32) + g = zeros((n,), dtype=np.int32) + wa = zeros(2*m*n + 5*n + 11*m*m + 8*m, float64) + iwa = zeros(3*n, dtype=np.int32) + task = zeros(2, dtype=np.int32) + ln_task = zeros(2, dtype=np.int32) + lsave = zeros(4, dtype=np.int32) + isave = zeros(44, dtype=np.int32) + dsave = zeros(29, dtype=float64) + + n_iterations = 0 + + while True: + # g may become float32 if a user provides a function that calculates + # the Jacobian in float32 (see gh-18730). The underlying code expects + # float64, so upcast it + g = g.astype(np.float64) + # x, f, g, wa, iwa, task, csave, lsave, isave, dsave = \ + _lbfgsb.setulb(m, x, low_bnd, upper_bnd, nbd, f, g, factr, pgtol, wa, + iwa, task, lsave, isave, dsave, maxls, ln_task) + + if task[0] == 3: + # The minimization routine wants f and g at the current x. + # Note that interruptions due to maxfun are postponed + # until the completion of the current minimization iteration. + # Overwrite f and g: + f, g = func_and_grad(x) + elif task[0] == 1: + # new iteration + n_iterations += 1 + + intermediate_result = OptimizeResult(x=x, fun=f) + if _call_callback_maybe_halt(callback, intermediate_result): + task[0] = 5 + task[1] = 505 + if n_iterations >= maxiter: + task[0] = 5 + task[1] = 504 + elif sf.nfev > maxfun: + task[0] = 5 + task[1] = 502 + else: + break + + if task[0] == 4: + warnflag = 0 + elif sf.nfev > maxfun or n_iterations >= maxiter: + warnflag = 1 + else: + warnflag = 2 + + # These two portions of the workspace are described in the mainlb + # function docstring in "__lbfgsb.c", ws and wy arguments. + s = wa[0: m*n].reshape(m, n) + y = wa[m*n: 2*m*n].reshape(m, n) + + # isave(31) = the total number of BFGS updates prior the current iteration. + n_bfgs_updates = isave[30] + + n_corrs = min(n_bfgs_updates, maxcor) + hess_inv = LbfgsInvHessProduct(s[:n_corrs], y[:n_corrs]) + + msg = status_messages[task[0]] + ": " + task_messages[task[1]] + + return OptimizeResult(fun=f, jac=g, nfev=sf.nfev, + njev=sf.ngev, + nit=n_iterations, status=warnflag, message=msg, + x=x, success=(warnflag == 0), hess_inv=hess_inv) + + +class LbfgsInvHessProduct(LinearOperator): + """Linear operator for the L-BFGS approximate inverse Hessian. + + This operator computes the product of a vector with the approximate inverse + of the Hessian of the objective function, using the L-BFGS limited + memory approximation to the inverse Hessian, accumulated during the + optimization. + + Objects of this class implement the ``scipy.sparse.linalg.LinearOperator`` + interface. + + Parameters + ---------- + sk : array_like, shape=(n_corr, n) + Array of `n_corr` most recent updates to the solution vector. + (See [1]). + yk : array_like, shape=(n_corr, n) + Array of `n_corr` most recent updates to the gradient. (See [1]). + + References + ---------- + .. [1] Nocedal, Jorge. "Updating quasi-Newton matrices with limited + storage." Mathematics of computation 35.151 (1980): 773-782. + + """ + + def __init__(self, sk, yk): + """Construct the operator.""" + if sk.shape != yk.shape or sk.ndim != 2: + raise ValueError('sk and yk must have matching shape, (n_corrs, n)') + n_corrs, n = sk.shape + + super().__init__(dtype=np.float64, shape=(n, n)) + + self.sk = sk + self.yk = yk + self.n_corrs = n_corrs + self.rho = 1 / np.einsum('ij,ij->i', sk, yk) + + def _matvec(self, x): + """Efficient matrix-vector multiply with the BFGS matrices. + + This calculation is described in Section (4) of [1]. + + Parameters + ---------- + x : ndarray + An array with shape (n,) or (n,1). + + Returns + ------- + y : ndarray + The matrix-vector product + + """ + s, y, n_corrs, rho = self.sk, self.yk, self.n_corrs, self.rho + q = np.array(x, dtype=self.dtype, copy=True) + if q.ndim == 2 and q.shape[1] == 1: + q = q.reshape(-1) + + alpha = np.empty(n_corrs) + + for i in range(n_corrs-1, -1, -1): + alpha[i] = rho[i] * np.dot(s[i], q) + q = q - alpha[i]*y[i] + + r = q + for i in range(n_corrs): + beta = rho[i] * np.dot(y[i], r) + r = r + s[i] * (alpha[i] - beta) + + return r + + def todense(self): + """Return a dense array representation of this operator. + + Returns + ------- + arr : ndarray, shape=(n, n) + An array with the same shape and containing + the same data represented by this `LinearOperator`. + + """ + s, y, n_corrs, rho = self.sk, self.yk, self.n_corrs, self.rho + I_arr = np.eye(*self.shape, dtype=self.dtype) + Hk = I_arr + + for i in range(n_corrs): + A1 = I_arr - s[i][:, np.newaxis] * y[i][np.newaxis, :] * rho[i] + A2 = I_arr - y[i][:, np.newaxis] * s[i][np.newaxis, :] * rho[i] + + Hk = np.dot(A1, np.dot(Hk, A2)) + (rho[i] * s[i][:, np.newaxis] * + s[i][np.newaxis, :]) + return Hk diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_linesearch.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_linesearch.py new file mode 100644 index 0000000000000000000000000000000000000000..31442e02d323e0f6d163505bf77dd30855ce1218 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_linesearch.py @@ -0,0 +1,896 @@ +""" +Functions +--------- +.. autosummary:: + :toctree: generated/ + + line_search_armijo + line_search_wolfe1 + line_search_wolfe2 + scalar_search_wolfe1 + scalar_search_wolfe2 + +""" +from warnings import warn + +from ._dcsrch import DCSRCH +import numpy as np + +__all__ = ['LineSearchWarning', 'line_search_wolfe1', 'line_search_wolfe2', + 'scalar_search_wolfe1', 'scalar_search_wolfe2', + 'line_search_armijo'] + +class LineSearchWarning(RuntimeWarning): + pass + + +def _check_c1_c2(c1, c2): + if not (0 < c1 < c2 < 1): + raise ValueError("'c1' and 'c2' do not satisfy" + "'0 < c1 < c2 < 1'.") + + +#------------------------------------------------------------------------------ +# Minpack's Wolfe line and scalar searches +#------------------------------------------------------------------------------ + +def line_search_wolfe1(f, fprime, xk, pk, gfk=None, + old_fval=None, old_old_fval=None, + args=(), c1=1e-4, c2=0.9, amax=50, amin=1e-8, + xtol=1e-14): + """ + As `scalar_search_wolfe1` but do a line search to direction `pk` + + Parameters + ---------- + f : callable + Function `f(x)` + fprime : callable + Gradient of `f` + xk : array_like + Current point + pk : array_like + Search direction + gfk : array_like, optional + Gradient of `f` at point `xk` + old_fval : float, optional + Value of `f` at point `xk` + old_old_fval : float, optional + Value of `f` at point preceding `xk` + + The rest of the parameters are the same as for `scalar_search_wolfe1`. + + Returns + ------- + stp, f_count, g_count, fval, old_fval + As in `line_search_wolfe1` + gval : array + Gradient of `f` at the final point + + Notes + ----- + Parameters `c1` and `c2` must satisfy ``0 < c1 < c2 < 1``. + + """ + if gfk is None: + gfk = fprime(xk, *args) + + gval = [gfk] + gc = [0] + fc = [0] + + def phi(s): + fc[0] += 1 + return f(xk + s*pk, *args) + + def derphi(s): + gval[0] = fprime(xk + s*pk, *args) + gc[0] += 1 + return np.dot(gval[0], pk) + + derphi0 = np.dot(gfk, pk) + + stp, fval, old_fval = scalar_search_wolfe1( + phi, derphi, old_fval, old_old_fval, derphi0, + c1=c1, c2=c2, amax=amax, amin=amin, xtol=xtol) + + return stp, fc[0], gc[0], fval, old_fval, gval[0] + + +def scalar_search_wolfe1(phi, derphi, phi0=None, old_phi0=None, derphi0=None, + c1=1e-4, c2=0.9, + amax=50, amin=1e-8, xtol=1e-14): + """ + Scalar function search for alpha that satisfies strong Wolfe conditions + + alpha > 0 is assumed to be a descent direction. + + Parameters + ---------- + phi : callable phi(alpha) + Function at point `alpha` + derphi : callable phi'(alpha) + Objective function derivative. Returns a scalar. + phi0 : float, optional + Value of phi at 0 + old_phi0 : float, optional + Value of phi at previous point + derphi0 : float, optional + Value derphi at 0 + c1 : float, optional + Parameter for Armijo condition rule. + c2 : float, optional + Parameter for curvature condition rule. + amax, amin : float, optional + Maximum and minimum step size + xtol : float, optional + Relative tolerance for an acceptable step. + + Returns + ------- + alpha : float + Step size, or None if no suitable step was found + phi : float + Value of `phi` at the new point `alpha` + phi0 : float + Value of `phi` at `alpha=0` + + Notes + ----- + Uses routine DCSRCH from MINPACK. + + Parameters `c1` and `c2` must satisfy ``0 < c1 < c2 < 1`` as described in [1]_. + + References + ---------- + + .. [1] Nocedal, J., & Wright, S. J. (2006). Numerical optimization. + In Springer Series in Operations Research and Financial Engineering. + (Springer Series in Operations Research and Financial Engineering). + Springer Nature. + + """ + _check_c1_c2(c1, c2) + + if phi0 is None: + phi0 = phi(0.) + if derphi0 is None: + derphi0 = derphi(0.) + + if old_phi0 is not None and derphi0 != 0: + alpha1 = min(1.0, 1.01*2*(phi0 - old_phi0)/derphi0) + if alpha1 < 0: + alpha1 = 1.0 + else: + alpha1 = 1.0 + + maxiter = 100 + + dcsrch = DCSRCH(phi, derphi, c1, c2, xtol, amin, amax) + stp, phi1, phi0, task = dcsrch( + alpha1, phi0=phi0, derphi0=derphi0, maxiter=maxiter + ) + + return stp, phi1, phi0 + + +line_search = line_search_wolfe1 + + +#------------------------------------------------------------------------------ +# Pure-Python Wolfe line and scalar searches +#------------------------------------------------------------------------------ + +# Note: `line_search_wolfe2` is the public `scipy.optimize.line_search` + +def line_search_wolfe2(f, myfprime, xk, pk, gfk=None, old_fval=None, + old_old_fval=None, args=(), c1=1e-4, c2=0.9, amax=None, + extra_condition=None, maxiter=10): + """Find alpha that satisfies strong Wolfe conditions. + + Parameters + ---------- + f : callable f(x,*args) + Objective function. + myfprime : callable f'(x,*args) + Objective function gradient. + xk : ndarray + Starting point. + pk : ndarray + Search direction. The search direction must be a descent direction + for the algorithm to converge. + gfk : ndarray, optional + Gradient value for x=xk (xk being the current parameter + estimate). Will be recomputed if omitted. + old_fval : float, optional + Function value for x=xk. Will be recomputed if omitted. + old_old_fval : float, optional + Function value for the point preceding x=xk. + args : tuple, optional + Additional arguments passed to objective function. + c1 : float, optional + Parameter for Armijo condition rule. + c2 : float, optional + Parameter for curvature condition rule. + amax : float, optional + Maximum step size + extra_condition : callable, optional + A callable of the form ``extra_condition(alpha, x, f, g)`` + returning a boolean. Arguments are the proposed step ``alpha`` + and the corresponding ``x``, ``f`` and ``g`` values. The line search + accepts the value of ``alpha`` only if this + callable returns ``True``. If the callable returns ``False`` + for the step length, the algorithm will continue with + new iterates. The callable is only called for iterates + satisfying the strong Wolfe conditions. + maxiter : int, optional + Maximum number of iterations to perform. + + Returns + ------- + alpha : float or None + Alpha for which ``x_new = x0 + alpha * pk``, + or None if the line search algorithm did not converge. + fc : int + Number of function evaluations made. + gc : int + Number of gradient evaluations made. + new_fval : float or None + New function value ``f(x_new)=f(x0+alpha*pk)``, + or None if the line search algorithm did not converge. + old_fval : float + Old function value ``f(x0)``. + new_slope : float or None + The local slope along the search direction at the + new value ````, + or None if the line search algorithm did not converge. + + + Notes + ----- + Uses the line search algorithm to enforce strong Wolfe + conditions. See Wright and Nocedal, 'Numerical Optimization', + 1999, pp. 59-61. + + The search direction `pk` must be a descent direction (e.g. + ``-myfprime(xk)``) to find a step length that satisfies the strong Wolfe + conditions. If the search direction is not a descent direction (e.g. + ``myfprime(xk)``), then `alpha`, `new_fval`, and `new_slope` will be None. + + Examples + -------- + >>> import numpy as np + >>> from scipy.optimize import line_search + + A objective function and its gradient are defined. + + >>> def obj_func(x): + ... return (x[0])**2+(x[1])**2 + >>> def obj_grad(x): + ... return [2*x[0], 2*x[1]] + + We can find alpha that satisfies strong Wolfe conditions. + + >>> start_point = np.array([1.8, 1.7]) + >>> search_gradient = np.array([-1.0, -1.0]) + >>> line_search(obj_func, obj_grad, start_point, search_gradient) + (1.0, 2, 1, 1.1300000000000001, 6.13, [1.6, 1.4]) + + """ + fc = [0] + gc = [0] + gval = [None] + gval_alpha = [None] + + def phi(alpha): + fc[0] += 1 + return f(xk + alpha * pk, *args) + + fprime = myfprime + + def derphi(alpha): + gc[0] += 1 + gval[0] = fprime(xk + alpha * pk, *args) # store for later use + gval_alpha[0] = alpha + return np.dot(gval[0], pk) + + if gfk is None: + gfk = fprime(xk, *args) + derphi0 = np.dot(gfk, pk) + + if extra_condition is not None: + # Add the current gradient as argument, to avoid needless + # re-evaluation + def extra_condition2(alpha, phi): + if gval_alpha[0] != alpha: + derphi(alpha) + x = xk + alpha * pk + return extra_condition(alpha, x, phi, gval[0]) + else: + extra_condition2 = None + + alpha_star, phi_star, old_fval, derphi_star = scalar_search_wolfe2( + phi, derphi, old_fval, old_old_fval, derphi0, c1, c2, amax, + extra_condition2, maxiter=maxiter) + + if derphi_star is None: + warn('The line search algorithm did not converge', + LineSearchWarning, stacklevel=2) + else: + # derphi_star is a number (derphi) -- so use the most recently + # calculated gradient used in computing it derphi = gfk*pk + # this is the gradient at the next step no need to compute it + # again in the outer loop. + derphi_star = gval[0] + + return alpha_star, fc[0], gc[0], phi_star, old_fval, derphi_star + + +def scalar_search_wolfe2(phi, derphi, phi0=None, + old_phi0=None, derphi0=None, + c1=1e-4, c2=0.9, amax=None, + extra_condition=None, maxiter=10): + """Find alpha that satisfies strong Wolfe conditions. + + alpha > 0 is assumed to be a descent direction. + + Parameters + ---------- + phi : callable phi(alpha) + Objective scalar function. + derphi : callable phi'(alpha) + Objective function derivative. Returns a scalar. + phi0 : float, optional + Value of phi at 0. + old_phi0 : float, optional + Value of phi at previous point. + derphi0 : float, optional + Value of derphi at 0 + c1 : float, optional + Parameter for Armijo condition rule. + c2 : float, optional + Parameter for curvature condition rule. + amax : float, optional + Maximum step size. + extra_condition : callable, optional + A callable of the form ``extra_condition(alpha, phi_value)`` + returning a boolean. The line search accepts the value + of ``alpha`` only if this callable returns ``True``. + If the callable returns ``False`` for the step length, + the algorithm will continue with new iterates. + The callable is only called for iterates satisfying + the strong Wolfe conditions. + maxiter : int, optional + Maximum number of iterations to perform. + + Returns + ------- + alpha_star : float or None + Best alpha, or None if the line search algorithm did not converge. + phi_star : float + phi at alpha_star. + phi0 : float + phi at 0. + derphi_star : float or None + derphi at alpha_star, or None if the line search algorithm + did not converge. + + Notes + ----- + Uses the line search algorithm to enforce strong Wolfe + conditions. See Wright and Nocedal, 'Numerical Optimization', + 1999, pp. 59-61. + + """ + _check_c1_c2(c1, c2) + + if phi0 is None: + phi0 = phi(0.) + + if derphi0 is None: + derphi0 = derphi(0.) + + alpha0 = 0 + if old_phi0 is not None and derphi0 != 0: + alpha1 = min(1.0, 1.01*2*(phi0 - old_phi0)/derphi0) + else: + alpha1 = 1.0 + + if alpha1 < 0: + alpha1 = 1.0 + + if amax is not None: + alpha1 = min(alpha1, amax) + + phi_a1 = phi(alpha1) + #derphi_a1 = derphi(alpha1) evaluated below + + phi_a0 = phi0 + derphi_a0 = derphi0 + + if extra_condition is None: + def extra_condition(alpha, phi): + return True + + for i in range(maxiter): + if alpha1 == 0 or (amax is not None and alpha0 > amax): + # alpha1 == 0: This shouldn't happen. Perhaps the increment has + # slipped below machine precision? + alpha_star = None + phi_star = phi0 + phi0 = old_phi0 + derphi_star = None + + if alpha1 == 0: + msg = 'Rounding errors prevent the line search from converging' + else: + msg = "The line search algorithm could not find a solution " + \ + f"less than or equal to amax: {amax}" + + warn(msg, LineSearchWarning, stacklevel=2) + break + + not_first_iteration = i > 0 + if (phi_a1 > phi0 + c1 * alpha1 * derphi0) or \ + ((phi_a1 >= phi_a0) and not_first_iteration): + alpha_star, phi_star, derphi_star = \ + _zoom(alpha0, alpha1, phi_a0, + phi_a1, derphi_a0, phi, derphi, + phi0, derphi0, c1, c2, extra_condition) + break + + derphi_a1 = derphi(alpha1) + if (abs(derphi_a1) <= -c2*derphi0): + if extra_condition(alpha1, phi_a1): + alpha_star = alpha1 + phi_star = phi_a1 + derphi_star = derphi_a1 + break + + if (derphi_a1 >= 0): + alpha_star, phi_star, derphi_star = \ + _zoom(alpha1, alpha0, phi_a1, + phi_a0, derphi_a1, phi, derphi, + phi0, derphi0, c1, c2, extra_condition) + break + + alpha2 = 2 * alpha1 # increase by factor of two on each iteration + if amax is not None: + alpha2 = min(alpha2, amax) + alpha0 = alpha1 + alpha1 = alpha2 + phi_a0 = phi_a1 + phi_a1 = phi(alpha1) + derphi_a0 = derphi_a1 + + else: + # stopping test maxiter reached + alpha_star = alpha1 + phi_star = phi_a1 + derphi_star = None + warn('The line search algorithm did not converge', + LineSearchWarning, stacklevel=2) + + return alpha_star, phi_star, phi0, derphi_star + + +def _cubicmin(a, fa, fpa, b, fb, c, fc): + """ + Finds the minimizer for a cubic polynomial that goes through the + points (a,fa), (b,fb), and (c,fc) with derivative at a of fpa. + + If no minimizer can be found, return None. + + """ + # f(x) = A *(x-a)^3 + B*(x-a)^2 + C*(x-a) + D + + with np.errstate(divide='raise', over='raise', invalid='raise'): + try: + C = fpa + db = b - a + dc = c - a + denom = (db * dc) ** 2 * (db - dc) + d1 = np.empty((2, 2)) + d1[0, 0] = dc ** 2 + d1[0, 1] = -db ** 2 + d1[1, 0] = -dc ** 3 + d1[1, 1] = db ** 3 + [A, B] = np.dot(d1, np.asarray([fb - fa - C * db, + fc - fa - C * dc]).flatten()) + A /= denom + B /= denom + radical = B * B - 3 * A * C + xmin = a + (-B + np.sqrt(radical)) / (3 * A) + except ArithmeticError: + return None + if not np.isfinite(xmin): + return None + return xmin + + +def _quadmin(a, fa, fpa, b, fb): + """ + Finds the minimizer for a quadratic polynomial that goes through + the points (a,fa), (b,fb) with derivative at a of fpa. + + """ + # f(x) = B*(x-a)^2 + C*(x-a) + D + with np.errstate(divide='raise', over='raise', invalid='raise'): + try: + D = fa + C = fpa + db = b - a * 1.0 + B = (fb - D - C * db) / (db * db) + xmin = a - C / (2.0 * B) + except ArithmeticError: + return None + if not np.isfinite(xmin): + return None + return xmin + + +def _zoom(a_lo, a_hi, phi_lo, phi_hi, derphi_lo, + phi, derphi, phi0, derphi0, c1, c2, extra_condition): + """Zoom stage of approximate linesearch satisfying strong Wolfe conditions. + + Part of the optimization algorithm in `scalar_search_wolfe2`. + + Notes + ----- + Implements Algorithm 3.6 (zoom) in Wright and Nocedal, + 'Numerical Optimization', 1999, pp. 61. + + """ + + maxiter = 10 + i = 0 + delta1 = 0.2 # cubic interpolant check + delta2 = 0.1 # quadratic interpolant check + phi_rec = phi0 + a_rec = 0 + while True: + # interpolate to find a trial step length between a_lo and + # a_hi Need to choose interpolation here. Use cubic + # interpolation and then if the result is within delta * + # dalpha or outside of the interval bounded by a_lo or a_hi + # then use quadratic interpolation, if the result is still too + # close, then use bisection + + dalpha = a_hi - a_lo + if dalpha < 0: + a, b = a_hi, a_lo + else: + a, b = a_lo, a_hi + + # minimizer of cubic interpolant + # (uses phi_lo, derphi_lo, phi_hi, and the most recent value of phi) + # + # if the result is too close to the end points (or out of the + # interval), then use quadratic interpolation with phi_lo, + # derphi_lo and phi_hi if the result is still too close to the + # end points (or out of the interval) then use bisection + + if (i > 0): + cchk = delta1 * dalpha + a_j = _cubicmin(a_lo, phi_lo, derphi_lo, a_hi, phi_hi, + a_rec, phi_rec) + if (i == 0) or (a_j is None) or (a_j > b - cchk) or (a_j < a + cchk): + qchk = delta2 * dalpha + a_j = _quadmin(a_lo, phi_lo, derphi_lo, a_hi, phi_hi) + if (a_j is None) or (a_j > b-qchk) or (a_j < a+qchk): + a_j = a_lo + 0.5*dalpha + + # Check new value of a_j + + phi_aj = phi(a_j) + if (phi_aj > phi0 + c1*a_j*derphi0) or (phi_aj >= phi_lo): + phi_rec = phi_hi + a_rec = a_hi + a_hi = a_j + phi_hi = phi_aj + else: + derphi_aj = derphi(a_j) + if abs(derphi_aj) <= -c2*derphi0 and extra_condition(a_j, phi_aj): + a_star = a_j + val_star = phi_aj + valprime_star = derphi_aj + break + if derphi_aj*(a_hi - a_lo) >= 0: + phi_rec = phi_hi + a_rec = a_hi + a_hi = a_lo + phi_hi = phi_lo + else: + phi_rec = phi_lo + a_rec = a_lo + a_lo = a_j + phi_lo = phi_aj + derphi_lo = derphi_aj + i += 1 + if (i > maxiter): + # Failed to find a conforming step size + a_star = None + val_star = None + valprime_star = None + break + return a_star, val_star, valprime_star + + +#------------------------------------------------------------------------------ +# Armijo line and scalar searches +#------------------------------------------------------------------------------ + +def line_search_armijo(f, xk, pk, gfk, old_fval, args=(), c1=1e-4, alpha0=1): + """Minimize over alpha, the function ``f(xk+alpha pk)``. + + Parameters + ---------- + f : callable + Function to be minimized. + xk : array_like + Current point. + pk : array_like + Search direction. + gfk : array_like + Gradient of `f` at point `xk`. + old_fval : float + Value of `f` at point `xk`. + args : tuple, optional + Optional arguments. + c1 : float, optional + Value to control stopping criterion. + alpha0 : scalar, optional + Value of `alpha` at start of the optimization. + + Returns + ------- + alpha + f_count + f_val_at_alpha + + Notes + ----- + Uses the interpolation algorithm (Armijo backtracking) as suggested by + Wright and Nocedal in 'Numerical Optimization', 1999, pp. 56-57 + + """ + xk = np.atleast_1d(xk) + fc = [0] + + def phi(alpha1): + fc[0] += 1 + return f(xk + alpha1*pk, *args) + + if old_fval is None: + phi0 = phi(0.) + else: + phi0 = old_fval # compute f(xk) -- done in past loop + + derphi0 = np.dot(gfk, pk) + alpha, phi1 = scalar_search_armijo(phi, phi0, derphi0, c1=c1, + alpha0=alpha0) + return alpha, fc[0], phi1 + + +def line_search_BFGS(f, xk, pk, gfk, old_fval, args=(), c1=1e-4, alpha0=1): + """ + Compatibility wrapper for `line_search_armijo` + """ + r = line_search_armijo(f, xk, pk, gfk, old_fval, args=args, c1=c1, + alpha0=alpha0) + return r[0], r[1], 0, r[2] + + +def scalar_search_armijo(phi, phi0, derphi0, c1=1e-4, alpha0=1, amin=0): + """Minimize over alpha, the function ``phi(alpha)``. + + Uses the interpolation algorithm (Armijo backtracking) as suggested by + Wright and Nocedal in 'Numerical Optimization', 1999, pp. 56-57 + + alpha > 0 is assumed to be a descent direction. + + Returns + ------- + alpha + phi1 + + """ + phi_a0 = phi(alpha0) + if phi_a0 <= phi0 + c1*alpha0*derphi0: + return alpha0, phi_a0 + + # Otherwise, compute the minimizer of a quadratic interpolant: + + alpha1 = -(derphi0) * alpha0**2 / 2.0 / (phi_a0 - phi0 - derphi0 * alpha0) + phi_a1 = phi(alpha1) + + if (phi_a1 <= phi0 + c1*alpha1*derphi0): + return alpha1, phi_a1 + + # Otherwise, loop with cubic interpolation until we find an alpha which + # satisfies the first Wolfe condition (since we are backtracking, we will + # assume that the value of alpha is not too small and satisfies the second + # condition. + + while alpha1 > amin: # we are assuming alpha>0 is a descent direction + factor = alpha0**2 * alpha1**2 * (alpha1-alpha0) + a = alpha0**2 * (phi_a1 - phi0 - derphi0*alpha1) - \ + alpha1**2 * (phi_a0 - phi0 - derphi0*alpha0) + a = a / factor + b = -alpha0**3 * (phi_a1 - phi0 - derphi0*alpha1) + \ + alpha1**3 * (phi_a0 - phi0 - derphi0*alpha0) + b = b / factor + + alpha2 = (-b + np.sqrt(abs(b**2 - 3 * a * derphi0))) / (3.0*a) + phi_a2 = phi(alpha2) + + if (phi_a2 <= phi0 + c1*alpha2*derphi0): + return alpha2, phi_a2 + + if (alpha1 - alpha2) > alpha1 / 2.0 or (1 - alpha2/alpha1) < 0.96: + alpha2 = alpha1 / 2.0 + + alpha0 = alpha1 + alpha1 = alpha2 + phi_a0 = phi_a1 + phi_a1 = phi_a2 + + # Failed to find a suitable step length + return None, phi_a1 + + +#------------------------------------------------------------------------------ +# Non-monotone line search for DF-SANE +#------------------------------------------------------------------------------ + +def _nonmonotone_line_search_cruz(f, x_k, d, prev_fs, eta, + gamma=1e-4, tau_min=0.1, tau_max=0.5): + """ + Nonmonotone backtracking line search as described in [1]_ + + Parameters + ---------- + f : callable + Function returning a tuple ``(f, F)`` where ``f`` is the value + of a merit function and ``F`` the residual. + x_k : ndarray + Initial position. + d : ndarray + Search direction. + prev_fs : float + List of previous merit function values. Should have ``len(prev_fs) <= M`` + where ``M`` is the nonmonotonicity window parameter. + eta : float + Allowed merit function increase, see [1]_ + gamma, tau_min, tau_max : float, optional + Search parameters, see [1]_ + + Returns + ------- + alpha : float + Step length + xp : ndarray + Next position + fp : float + Merit function value at next position + Fp : ndarray + Residual at next position + + References + ---------- + [1] "Spectral residual method without gradient information for solving + large-scale nonlinear systems of equations." W. La Cruz, + J.M. Martinez, M. Raydan. Math. Comp. **75**, 1429 (2006). + + """ + f_k = prev_fs[-1] + f_bar = max(prev_fs) + + alpha_p = 1 + alpha_m = 1 + alpha = 1 + + while True: + xp = x_k + alpha_p * d + fp, Fp = f(xp) + + if fp <= f_bar + eta - gamma * alpha_p**2 * f_k: + alpha = alpha_p + break + + alpha_tp = alpha_p**2 * f_k / (fp + (2*alpha_p - 1)*f_k) + + xp = x_k - alpha_m * d + fp, Fp = f(xp) + + if fp <= f_bar + eta - gamma * alpha_m**2 * f_k: + alpha = -alpha_m + break + + alpha_tm = alpha_m**2 * f_k / (fp + (2*alpha_m - 1)*f_k) + + alpha_p = np.clip(alpha_tp, tau_min * alpha_p, tau_max * alpha_p) + alpha_m = np.clip(alpha_tm, tau_min * alpha_m, tau_max * alpha_m) + + return alpha, xp, fp, Fp + + +def _nonmonotone_line_search_cheng(f, x_k, d, f_k, C, Q, eta, + gamma=1e-4, tau_min=0.1, tau_max=0.5, + nu=0.85): + """ + Nonmonotone line search from [1] + + Parameters + ---------- + f : callable + Function returning a tuple ``(f, F)`` where ``f`` is the value + of a merit function and ``F`` the residual. + x_k : ndarray + Initial position. + d : ndarray + Search direction. + f_k : float + Initial merit function value. + C, Q : float + Control parameters. On the first iteration, give values + Q=1.0, C=f_k + eta : float + Allowed merit function increase, see [1]_ + nu, gamma, tau_min, tau_max : float, optional + Search parameters, see [1]_ + + Returns + ------- + alpha : float + Step length + xp : ndarray + Next position + fp : float + Merit function value at next position + Fp : ndarray + Residual at next position + C : float + New value for the control parameter C + Q : float + New value for the control parameter Q + + References + ---------- + .. [1] W. Cheng & D.-H. Li, ''A derivative-free nonmonotone line + search and its application to the spectral residual + method'', IMA J. Numer. Anal. 29, 814 (2009). + + """ + alpha_p = 1 + alpha_m = 1 + alpha = 1 + + while True: + xp = x_k + alpha_p * d + fp, Fp = f(xp) + + if fp <= C + eta - gamma * alpha_p**2 * f_k: + alpha = alpha_p + break + + alpha_tp = alpha_p**2 * f_k / (fp + (2*alpha_p - 1)*f_k) + + xp = x_k - alpha_m * d + fp, Fp = f(xp) + + if fp <= C + eta - gamma * alpha_m**2 * f_k: + alpha = -alpha_m + break + + alpha_tm = alpha_m**2 * f_k / (fp + (2*alpha_m - 1)*f_k) + + alpha_p = np.clip(alpha_tp, tau_min * alpha_p, tau_max * alpha_p) + alpha_m = np.clip(alpha_tm, tau_min * alpha_m, tau_max * alpha_m) + + # Update C and Q + Q_next = nu * Q + 1 + C = (nu * Q * (C + eta) + fp) / Q_next + Q = Q_next + + return alpha, xp, fp, Fp, C, Q diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_linprog.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_linprog.py new file mode 100644 index 0000000000000000000000000000000000000000..054ba471dcbd4622ab9c2fb9dda313bb124c0451 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_linprog.py @@ -0,0 +1,733 @@ +""" +A top-level linear programming interface. + +.. versionadded:: 0.15.0 + +Functions +--------- +.. autosummary:: + :toctree: generated/ + + linprog + linprog_verbose_callback + linprog_terse_callback + +""" + +import numpy as np + +from ._optimize import OptimizeResult, OptimizeWarning +from warnings import warn +from ._linprog_highs import _linprog_highs +from ._linprog_ip import _linprog_ip +from ._linprog_simplex import _linprog_simplex +from ._linprog_rs import _linprog_rs +from ._linprog_doc import (_linprog_highs_doc, _linprog_ip_doc, # noqa: F401 + _linprog_rs_doc, _linprog_simplex_doc, + _linprog_highs_ipm_doc, _linprog_highs_ds_doc) +from ._linprog_util import ( + _parse_linprog, _presolve, _get_Abc, _LPProblem, _autoscale, + _postsolve, _check_result, _display_summary) +from copy import deepcopy + +__all__ = ['linprog', 'linprog_verbose_callback', 'linprog_terse_callback'] + +__docformat__ = "restructuredtext en" + +LINPROG_METHODS = [ + 'simplex', 'revised simplex', 'interior-point', 'highs', 'highs-ds', 'highs-ipm' +] + + +def linprog_verbose_callback(res): + """ + A sample callback function demonstrating the linprog callback interface. + This callback produces detailed output to sys.stdout before each iteration + and after the final iteration of the simplex algorithm. + + Parameters + ---------- + res : A `scipy.optimize.OptimizeResult` consisting of the following fields: + + x : 1-D array + The independent variable vector which optimizes the linear + programming problem. + fun : float + Value of the objective function. + success : bool + True if the algorithm succeeded in finding an optimal solution. + slack : 1-D array + The values of the slack variables. Each slack variable corresponds + to an inequality constraint. If the slack is zero, then the + corresponding constraint is active. + con : 1-D array + The (nominally zero) residuals of the equality constraints, that is, + ``b - A_eq @ x`` + phase : int + The phase of the optimization being executed. In phase 1 a basic + feasible solution is sought and the T has an additional row + representing an alternate objective function. + status : int + An integer representing the exit status of the optimization: + + ``0`` : Optimization terminated successfully + + ``1`` : Iteration limit reached + + ``2`` : Problem appears to be infeasible + + ``3`` : Problem appears to be unbounded + + ``4`` : Serious numerical difficulties encountered + + nit : int + The number of iterations performed. + message : str + A string descriptor of the exit status of the optimization. + """ + x = res['x'] + fun = res['fun'] + phase = res['phase'] + status = res['status'] + nit = res['nit'] + message = res['message'] + complete = res['complete'] + + saved_printoptions = np.get_printoptions() + np.set_printoptions(linewidth=500, + formatter={'float': lambda x: f"{x: 12.4f}"}) + if status: + print('--------- Simplex Early Exit -------\n') + print(f'The simplex method exited early with status {status:d}') + print(message) + elif complete: + print('--------- Simplex Complete --------\n') + print(f'Iterations required: {nit}') + else: + print(f'--------- Iteration {nit:d} ---------\n') + + if nit > 0: + if phase == 1: + print('Current Pseudo-Objective Value:') + else: + print('Current Objective Value:') + print('f = ', fun) + print() + print('Current Solution Vector:') + print('x = ', x) + print() + + np.set_printoptions(**saved_printoptions) + + +def linprog_terse_callback(res): + """ + A sample callback function demonstrating the linprog callback interface. + This callback produces brief output to sys.stdout before each iteration + and after the final iteration of the simplex algorithm. + + Parameters + ---------- + res : A `scipy.optimize.OptimizeResult` consisting of the following fields: + + x : 1-D array + The independent variable vector which optimizes the linear + programming problem. + fun : float + Value of the objective function. + success : bool + True if the algorithm succeeded in finding an optimal solution. + slack : 1-D array + The values of the slack variables. Each slack variable corresponds + to an inequality constraint. If the slack is zero, then the + corresponding constraint is active. + con : 1-D array + The (nominally zero) residuals of the equality constraints, that is, + ``b - A_eq @ x``. + phase : int + The phase of the optimization being executed. In phase 1 a basic + feasible solution is sought and the T has an additional row + representing an alternate objective function. + status : int + An integer representing the exit status of the optimization: + + ``0`` : Optimization terminated successfully + + ``1`` : Iteration limit reached + + ``2`` : Problem appears to be infeasible + + ``3`` : Problem appears to be unbounded + + ``4`` : Serious numerical difficulties encountered + + nit : int + The number of iterations performed. + message : str + A string descriptor of the exit status of the optimization. + """ + nit = res['nit'] + x = res['x'] + + if nit == 0: + print("Iter: X:") + print(f"{nit: <5d} ", end="") + print(x) + + +def linprog(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None, + bounds=(0, None), method='highs', callback=None, + options=None, x0=None, integrality=None): + r""" + Linear programming: minimize a linear objective function subject to linear + equality and inequality constraints. + + Linear programming solves problems of the following form: + + .. math:: + + \min_x \ & c^T x \\ + \mbox{such that} \ & A_{ub} x \leq b_{ub},\\ + & A_{eq} x = b_{eq},\\ + & l \leq x \leq u , + + where :math:`x` is a vector of decision variables; :math:`c`, + :math:`b_{ub}`, :math:`b_{eq}`, :math:`l`, and :math:`u` are vectors; and + :math:`A_{ub}` and :math:`A_{eq}` are matrices. + + Alternatively, that's: + + - minimize :: + + c @ x + + - such that :: + + A_ub @ x <= b_ub + A_eq @ x == b_eq + lb <= x <= ub + + Note that by default ``lb = 0`` and ``ub = None``. Other bounds can be + specified with ``bounds``. + + Parameters + ---------- + c : 1-D array + The coefficients of the linear objective function to be minimized. + A_ub : 2-D array, optional + The inequality constraint matrix. Each row of ``A_ub`` specifies the + coefficients of a linear inequality constraint on ``x``. + b_ub : 1-D array, optional + The inequality constraint vector. Each element represents an + upper bound on the corresponding value of ``A_ub @ x``. + A_eq : 2-D array, optional + The equality constraint matrix. Each row of ``A_eq`` specifies the + coefficients of a linear equality constraint on ``x``. + b_eq : 1-D array, optional + The equality constraint vector. Each element of ``A_eq @ x`` must equal + the corresponding element of ``b_eq``. + bounds : sequence, optional + A sequence of ``(min, max)`` pairs for each element in ``x``, defining + the minimum and maximum values of that decision variable. + If a single tuple ``(min, max)`` is provided, then ``min`` and ``max`` + will serve as bounds for all decision variables. + Use ``None`` to indicate that there is no bound. For instance, the + default bound ``(0, None)`` means that all decision variables are + non-negative, and the pair ``(None, None)`` means no bounds at all, + i.e. all variables are allowed to be any real. + method : str, optional + The algorithm used to solve the standard form problem. + The following are supported. + + - :ref:`'highs' ` (default) + - :ref:`'highs-ds' ` + - :ref:`'highs-ipm' ` + - :ref:`'interior-point' ` (legacy) + - :ref:`'revised simplex' ` (legacy) + - :ref:`'simplex' ` (legacy) + + The legacy methods are deprecated and will be removed in SciPy 1.11.0. + callback : callable, optional + If a callback function is provided, it will be called at least once per + iteration of the algorithm. The callback function must accept a single + `scipy.optimize.OptimizeResult` consisting of the following fields: + + x : 1-D array + The current solution vector. + fun : float + The current value of the objective function ``c @ x``. + success : bool + ``True`` when the algorithm has completed successfully. + slack : 1-D array + The (nominally positive) values of the slack, + ``b_ub - A_ub @ x``. + con : 1-D array + The (nominally zero) residuals of the equality constraints, + ``b_eq - A_eq @ x``. + phase : int + The phase of the algorithm being executed. + status : int + An integer representing the status of the algorithm. + + ``0`` : Optimization proceeding nominally. + + ``1`` : Iteration limit reached. + + ``2`` : Problem appears to be infeasible. + + ``3`` : Problem appears to be unbounded. + + ``4`` : Numerical difficulties encountered. + + nit : int + The current iteration number. + message : str + A string descriptor of the algorithm status. + + Callback functions are not currently supported by the HiGHS methods. + + options : dict, optional + A dictionary of solver options. All methods accept the following + options: + + maxiter : int + Maximum number of iterations to perform. + Default: see method-specific documentation. + disp : bool + Set to ``True`` to print convergence messages. + Default: ``False``. + presolve : bool + Set to ``False`` to disable automatic presolve. + Default: ``True``. + + All methods except the HiGHS solvers also accept: + + tol : float + A tolerance which determines when a residual is "close enough" to + zero to be considered exactly zero. + autoscale : bool + Set to ``True`` to automatically perform equilibration. + Consider using this option if the numerical values in the + constraints are separated by several orders of magnitude. + Default: ``False``. + rr : bool + Set to ``False`` to disable automatic redundancy removal. + Default: ``True``. + rr_method : string + Method used to identify and remove redundant rows from the + equality constraint matrix after presolve. For problems with + dense input, the available methods for redundancy removal are: + + ``SVD``: + Repeatedly performs singular value decomposition on + the matrix, detecting redundant rows based on nonzeros + in the left singular vectors that correspond with + zero singular values. May be fast when the matrix is + nearly full rank. + ``pivot``: + Uses the algorithm presented in [5]_ to identify + redundant rows. + ``ID``: + Uses a randomized interpolative decomposition. + Identifies columns of the matrix transpose not used in + a full-rank interpolative decomposition of the matrix. + ``None``: + Uses ``svd`` if the matrix is nearly full rank, that is, + the difference between the matrix rank and the number + of rows is less than five. If not, uses ``pivot``. The + behavior of this default is subject to change without + prior notice. + + Default: None. + For problems with sparse input, this option is ignored, and the + pivot-based algorithm presented in [5]_ is used. + + For method-specific options, see + :func:`show_options('linprog') `. + + x0 : 1-D array, optional + Guess values of the decision variables, which will be refined by + the optimization algorithm. This argument is currently used only by the + :ref:`'revised simplex' ` method, + and can only be used if `x0` represents a basic feasible solution. + + integrality : 1-D array or int, optional + Indicates the type of integrality constraint on each decision variable. + + ``0`` : Continuous variable; no integrality constraint. + + ``1`` : Integer variable; decision variable must be an integer + within `bounds`. + + ``2`` : Semi-continuous variable; decision variable must be within + `bounds` or take value ``0``. + + ``3`` : Semi-integer variable; decision variable must be an integer + within `bounds` or take value ``0``. + + By default, all variables are continuous. + + For mixed integrality constraints, supply an array of shape ``c.shape``. + To infer a constraint on each decision variable from shorter inputs, + the argument will be broadcast to ``c.shape`` using `numpy.broadcast_to`. + + This argument is currently used only by the + :ref:`'highs' ` method and is ignored otherwise. + + Returns + ------- + res : OptimizeResult + A :class:`scipy.optimize.OptimizeResult` consisting of the fields + below. Note that the return types of the fields may depend on whether + the optimization was successful, therefore it is recommended to check + `OptimizeResult.status` before relying on the other fields: + + x : 1-D array + The values of the decision variables that minimizes the + objective function while satisfying the constraints. + fun : float + The optimal value of the objective function ``c @ x``. + slack : 1-D array + The (nominally positive) values of the slack variables, + ``b_ub - A_ub @ x``. + con : 1-D array + The (nominally zero) residuals of the equality constraints, + ``b_eq - A_eq @ x``. + success : bool + ``True`` when the algorithm succeeds in finding an optimal + solution. + status : int + An integer representing the exit status of the algorithm. + + ``0`` : Optimization terminated successfully. + + ``1`` : Iteration limit reached. + + ``2`` : Problem appears to be infeasible. + + ``3`` : Problem appears to be unbounded. + + ``4`` : Numerical difficulties encountered. + + nit : int + The total number of iterations performed in all phases. + message : str + A string descriptor of the exit status of the algorithm. + + See Also + -------- + show_options : Additional options accepted by the solvers. + + Notes + ----- + This section describes the available solvers that can be selected by the + 'method' parameter. + + :ref:`'highs-ds' `, and + :ref:`'highs-ipm' ` are interfaces to the + HiGHS simplex and interior-point method solvers [13]_, respectively. + :ref:`'highs' ` (default) chooses between + the two automatically. These are the fastest linear + programming solvers in SciPy, especially for large, sparse problems; + which of these two is faster is problem-dependent. + The other solvers are legacy methods and will be removed when `callback` is + supported by the HiGHS methods. + + Method :ref:`'highs-ds' `, is a wrapper of the C++ high + performance dual revised simplex implementation (HSOL) [13]_, [14]_. + Method :ref:`'highs-ipm' ` is a wrapper of a C++ + implementation of an **i**\ nterior-\ **p**\ oint **m**\ ethod [13]_; it + features a crossover routine, so it is as accurate as a simplex solver. + Method :ref:`'highs' ` chooses between the two + automatically. + For new code involving `linprog`, we recommend explicitly choosing one of + these three method values. + + .. versionadded:: 1.6.0 + + Method :ref:`'interior-point' ` + uses the primal-dual path following algorithm + as outlined in [4]_. This algorithm supports sparse constraint matrices and + is typically faster than the simplex methods, especially for large, sparse + problems. Note, however, that the solution returned may be slightly less + accurate than those of the simplex methods and will not, in general, + correspond with a vertex of the polytope defined by the constraints. + + .. versionadded:: 1.0.0 + + Method :ref:`'revised simplex' ` + uses the revised simplex method as described in + [9]_, except that a factorization [11]_ of the basis matrix, rather than + its inverse, is efficiently maintained and used to solve the linear systems + at each iteration of the algorithm. + + .. versionadded:: 1.3.0 + + Method :ref:`'simplex' ` uses a traditional, + full-tableau implementation of + Dantzig's simplex algorithm [1]_, [2]_ (*not* the + Nelder-Mead simplex). This algorithm is included for backwards + compatibility and educational purposes. + + .. versionadded:: 0.15.0 + + Before applying :ref:`'interior-point' `, + :ref:`'revised simplex' `, or + :ref:`'simplex' `, + a presolve procedure based on [8]_ attempts + to identify trivial infeasibilities, trivial unboundedness, and potential + problem simplifications. Specifically, it checks for: + + - rows of zeros in ``A_eq`` or ``A_ub``, representing trivial constraints; + - columns of zeros in ``A_eq`` `and` ``A_ub``, representing unconstrained + variables; + - column singletons in ``A_eq``, representing fixed variables; and + - column singletons in ``A_ub``, representing simple bounds. + + If presolve reveals that the problem is unbounded (e.g. an unconstrained + and unbounded variable has negative cost) or infeasible (e.g., a row of + zeros in ``A_eq`` corresponds with a nonzero in ``b_eq``), the solver + terminates with the appropriate status code. Note that presolve terminates + as soon as any sign of unboundedness is detected; consequently, a problem + may be reported as unbounded when in reality the problem is infeasible + (but infeasibility has not been detected yet). Therefore, if it is + important to know whether the problem is actually infeasible, solve the + problem again with option ``presolve=False``. + + If neither infeasibility nor unboundedness are detected in a single pass + of the presolve, bounds are tightened where possible and fixed + variables are removed from the problem. Then, linearly dependent rows + of the ``A_eq`` matrix are removed, (unless they represent an + infeasibility) to avoid numerical difficulties in the primary solve + routine. Note that rows that are nearly linearly dependent (within a + prescribed tolerance) may also be removed, which can change the optimal + solution in rare cases. If this is a concern, eliminate redundancy from + your problem formulation and run with option ``rr=False`` or + ``presolve=False``. + + Several potential improvements can be made here: additional presolve + checks outlined in [8]_ should be implemented, the presolve routine should + be run multiple times (until no further simplifications can be made), and + more of the efficiency improvements from [5]_ should be implemented in the + redundancy removal routines. + + After presolve, the problem is transformed to standard form by converting + the (tightened) simple bounds to upper bound constraints, introducing + non-negative slack variables for inequality constraints, and expressing + unbounded variables as the difference between two non-negative variables. + Optionally, the problem is automatically scaled via equilibration [12]_. + The selected algorithm solves the standard form problem, and a + postprocessing routine converts the result to a solution to the original + problem. + + References + ---------- + .. [1] Dantzig, George B., Linear programming and extensions. Rand + Corporation Research Study Princeton Univ. Press, Princeton, NJ, + 1963 + .. [2] Hillier, S.H. and Lieberman, G.J. (1995), "Introduction to + Mathematical Programming", McGraw-Hill, Chapter 4. + .. [3] Bland, Robert G. New finite pivoting rules for the simplex method. + Mathematics of Operations Research (2), 1977: pp. 103-107. + .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point + optimizer for linear programming: an implementation of the + homogeneous algorithm." High performance optimization. Springer US, + 2000. 197-232. + .. [5] Andersen, Erling D. "Finding all linearly dependent rows in + large-scale linear programming." Optimization Methods and Software + 6.3 (1995): 219-227. + .. [6] Freund, Robert M. "Primal-Dual Interior-Point Methods for Linear + Programming based on Newton's Method." Unpublished Course Notes, + March 2004. Available 2/25/2017 at + https://ocw.mit.edu/courses/sloan-school-of-management/15-084j-nonlinear-programming-spring-2004/lecture-notes/lec14_int_pt_mthd.pdf + .. [7] Fourer, Robert. "Solving Linear Programs by Interior-Point Methods." + Unpublished Course Notes, August 26, 2005. Available 2/25/2017 at + http://www.4er.org/CourseNotes/Book%20B/B-III.pdf + .. [8] Andersen, Erling D., and Knud D. Andersen. "Presolving in linear + programming." Mathematical Programming 71.2 (1995): 221-245. + .. [9] Bertsimas, Dimitris, and J. Tsitsiklis. "Introduction to linear + programming." Athena Scientific 1 (1997): 997. + .. [10] Andersen, Erling D., et al. Implementation of interior point + methods for large scale linear programming. HEC/Universite de + Geneve, 1996. + .. [11] Bartels, Richard H. "A stabilization of the simplex method." + Journal in Numerische Mathematik 16.5 (1971): 414-434. + .. [12] Tomlin, J. A. "On scaling linear programming problems." + Mathematical Programming Study 4 (1975): 146-166. + .. [13] Huangfu, Q., Galabova, I., Feldmeier, M., and Hall, J. A. J. + "HiGHS - high performance software for linear optimization." + https://highs.dev/ + .. [14] Huangfu, Q. and Hall, J. A. J. "Parallelizing the dual revised + simplex method." Mathematical Programming Computation, 10 (1), + 119-142, 2018. DOI: 10.1007/s12532-017-0130-5 + + Examples + -------- + Consider the following problem: + + .. math:: + + \min_{x_0, x_1} \ -x_0 + 4x_1 & \\ + \mbox{such that} \ -3x_0 + x_1 & \leq 6,\\ + -x_0 - 2x_1 & \geq -4,\\ + x_1 & \geq -3. + + The problem is not presented in the form accepted by `linprog`. This is + easily remedied by converting the "greater than" inequality + constraint to a "less than" inequality constraint by + multiplying both sides by a factor of :math:`-1`. Note also that the last + constraint is really the simple bound :math:`-3 \leq x_1 \leq \infty`. + Finally, since there are no bounds on :math:`x_0`, we must explicitly + specify the bounds :math:`-\infty \leq x_0 \leq \infty`, as the + default is for variables to be non-negative. After collecting coeffecients + into arrays and tuples, the input for this problem is: + + >>> from scipy.optimize import linprog + >>> c = [-1, 4] + >>> A = [[-3, 1], [1, 2]] + >>> b = [6, 4] + >>> x0_bounds = (None, None) + >>> x1_bounds = (-3, None) + >>> res = linprog(c, A_ub=A, b_ub=b, bounds=[x0_bounds, x1_bounds]) + >>> res.fun + -22.0 + >>> res.x + array([10., -3.]) + >>> res.message + 'Optimization terminated successfully. (HiGHS Status 7: Optimal)' + + The marginals (AKA dual values / shadow prices / Lagrange multipliers) + and residuals (slacks) are also available. + + >>> res.ineqlin + residual: [ 3.900e+01 0.000e+00] + marginals: [-0.000e+00 -1.000e+00] + + For example, because the marginal associated with the second inequality + constraint is -1, we expect the optimal value of the objective function + to decrease by ``eps`` if we add a small amount ``eps`` to the right hand + side of the second inequality constraint: + + >>> eps = 0.05 + >>> b[1] += eps + >>> linprog(c, A_ub=A, b_ub=b, bounds=[x0_bounds, x1_bounds]).fun + -22.05 + + Also, because the residual on the first inequality constraint is 39, we + can decrease the right hand side of the first constraint by 39 without + affecting the optimal solution. + + >>> b = [6, 4] # reset to original values + >>> b[0] -= 39 + >>> linprog(c, A_ub=A, b_ub=b, bounds=[x0_bounds, x1_bounds]).fun + -22.0 + + """ + + meth = method.lower() + methods = {"highs", "highs-ds", "highs-ipm", + "simplex", "revised simplex", "interior-point"} + + if meth not in methods: + raise ValueError(f"Unknown solver '{method}'") + + if x0 is not None and meth != "revised simplex": + warning_message = "x0 is used only when method is 'revised simplex'. " + warn(warning_message, OptimizeWarning, stacklevel=2) + + if np.any(integrality) and not meth == "highs": + integrality = None + warning_message = ("Only `method='highs'` supports integer " + "constraints. Ignoring `integrality`.") + warn(warning_message, OptimizeWarning, stacklevel=2) + elif np.any(integrality): + integrality = np.broadcast_to(integrality, np.shape(c)) + else: + integrality = None + + lp = _LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0, integrality) + lp, solver_options = _parse_linprog(lp, options, meth) + tol = solver_options.get('tol', 1e-9) + + # Give unmodified problem to HiGHS + if meth.startswith('highs'): + if callback is not None: + raise NotImplementedError("HiGHS solvers do not support the " + "callback interface.") + highs_solvers = {'highs-ipm': 'ipm', 'highs-ds': 'simplex', + 'highs': None} + + sol = _linprog_highs(lp, solver=highs_solvers[meth], + **solver_options) + sol['status'], sol['message'] = ( + _check_result(sol['x'], sol['fun'], sol['status'], sol['slack'], + sol['con'], lp.bounds, tol, sol['message'], + integrality)) + sol['success'] = sol['status'] == 0 + return OptimizeResult(sol) + + warn(f"`method='{meth}'` is deprecated and will be removed in SciPy " + "1.11.0. Please use one of the HiGHS solvers (e.g. " + "`method='highs'`) in new code.", DeprecationWarning, stacklevel=2) + + iteration = 0 + complete = False # will become True if solved in presolve + undo = [] + + # Keep the original arrays to calculate slack/residuals for original + # problem. + lp_o = deepcopy(lp) + + # Solve trivial problem, eliminate variables, tighten bounds, etc. + rr_method = solver_options.pop('rr_method', None) # need to pop these; + rr = solver_options.pop('rr', True) # they're not passed to methods + c0 = 0 # we might get a constant term in the objective + if solver_options.pop('presolve', True): + (lp, c0, x, undo, complete, status, message) = _presolve(lp, rr, + rr_method, + tol) + + C, b_scale = 1, 1 # for trivial unscaling if autoscale is not used + postsolve_args = (lp_o._replace(bounds=lp.bounds), undo, C, b_scale) + + if not complete: + A, b, c, c0, x0 = _get_Abc(lp, c0) + if solver_options.pop('autoscale', False): + A, b, c, x0, C, b_scale = _autoscale(A, b, c, x0) + postsolve_args = postsolve_args[:-2] + (C, b_scale) + + if meth == 'simplex': + x, status, message, iteration = _linprog_simplex( + c, c0=c0, A=A, b=b, callback=callback, + postsolve_args=postsolve_args, **solver_options) + elif meth == 'interior-point': + x, status, message, iteration = _linprog_ip( + c, c0=c0, A=A, b=b, callback=callback, + postsolve_args=postsolve_args, **solver_options) + elif meth == 'revised simplex': + x, status, message, iteration = _linprog_rs( + c, c0=c0, A=A, b=b, x0=x0, callback=callback, + postsolve_args=postsolve_args, **solver_options) + + # Eliminate artificial variables, re-introduce presolved variables, etc. + disp = solver_options.get('disp', False) + + x, fun, slack, con = _postsolve(x, postsolve_args, complete) + + status, message = _check_result(x, fun, status, slack, con, lp_o.bounds, + tol, message, integrality) + + if disp: + _display_summary(message, status, fun, iteration) + + sol = { + 'x': x, + 'fun': fun, + 'slack': slack, + 'con': con, + 'status': status, + 'message': message, + 'nit': iteration, + 'success': status == 0} + + return OptimizeResult(sol) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_linprog_doc.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_linprog_doc.py new file mode 100644 index 0000000000000000000000000000000000000000..ba016aec6dafe74e48076875202704a3b85b822a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_linprog_doc.py @@ -0,0 +1,1434 @@ +""" +Created on Sat Aug 22 19:49:17 2020 + +@author: matth +""" + + +def _linprog_highs_doc(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None, + bounds=None, method='highs', callback=None, + maxiter=None, disp=False, presolve=True, + time_limit=None, + dual_feasibility_tolerance=None, + primal_feasibility_tolerance=None, + ipm_optimality_tolerance=None, + simplex_dual_edge_weight_strategy=None, + mip_rel_gap=None, + **unknown_options): + r""" + Linear programming: minimize a linear objective function subject to linear + equality and inequality constraints using one of the HiGHS solvers. + + Linear programming solves problems of the following form: + + .. math:: + + \min_x \ & c^T x \\ + \mbox{such that} \ & A_{ub} x \leq b_{ub},\\ + & A_{eq} x = b_{eq},\\ + & l \leq x \leq u , + + where :math:`x` is a vector of decision variables; :math:`c`, + :math:`b_{ub}`, :math:`b_{eq}`, :math:`l`, and :math:`u` are vectors; and + :math:`A_{ub}` and :math:`A_{eq}` are matrices. + + Alternatively, that's: + + minimize:: + + c @ x + + such that:: + + A_ub @ x <= b_ub + A_eq @ x == b_eq + lb <= x <= ub + + Note that by default ``lb = 0`` and ``ub = None`` unless specified with + ``bounds``. + + Parameters + ---------- + c : 1-D array + The coefficients of the linear objective function to be minimized. + A_ub : 2-D array, optional + The inequality constraint matrix. Each row of ``A_ub`` specifies the + coefficients of a linear inequality constraint on ``x``. + b_ub : 1-D array, optional + The inequality constraint vector. Each element represents an + upper bound on the corresponding value of ``A_ub @ x``. + A_eq : 2-D array, optional + The equality constraint matrix. Each row of ``A_eq`` specifies the + coefficients of a linear equality constraint on ``x``. + b_eq : 1-D array, optional + The equality constraint vector. Each element of ``A_eq @ x`` must equal + the corresponding element of ``b_eq``. + bounds : sequence, optional + A sequence of ``(min, max)`` pairs for each element in ``x``, defining + the minimum and maximum values of that decision variable. Use ``None`` + to indicate that there is no bound. By default, bounds are + ``(0, None)`` (all decision variables are non-negative). + If a single tuple ``(min, max)`` is provided, then ``min`` and + ``max`` will serve as bounds for all decision variables. + method : str + + This is the method-specific documentation for 'highs', which chooses + automatically between + :ref:`'highs-ds' ` and + :ref:`'highs-ipm' `. + :ref:`'interior-point' ` (default), + :ref:`'revised simplex' `, and + :ref:`'simplex' ` (legacy) + are also available. + integrality : 1-D array or int, optional + Indicates the type of integrality constraint on each decision variable. + + ``0`` : Continuous variable; no integrality constraint. + + ``1`` : Integer variable; decision variable must be an integer + within `bounds`. + + ``2`` : Semi-continuous variable; decision variable must be within + `bounds` or take value ``0``. + + ``3`` : Semi-integer variable; decision variable must be an integer + within `bounds` or take value ``0``. + + By default, all variables are continuous. + + For mixed integrality constraints, supply an array of shape `c.shape`. + To infer a constraint on each decision variable from shorter inputs, + the argument will be broadcast to `c.shape` using `np.broadcast_to`. + + This argument is currently used only by the ``'highs'`` method and + ignored otherwise. + + Options + ------- + maxiter : int + The maximum number of iterations to perform in either phase. + For :ref:`'highs-ipm' `, this does not + include the number of crossover iterations. Default is the largest + possible value for an ``int`` on the platform. + disp : bool (default: ``False``) + Set to ``True`` if indicators of optimization status are to be + printed to the console during optimization. + presolve : bool (default: ``True``) + Presolve attempts to identify trivial infeasibilities, + identify trivial unboundedness, and simplify the problem before + sending it to the main solver. It is generally recommended + to keep the default setting ``True``; set to ``False`` if + presolve is to be disabled. + time_limit : float + The maximum time in seconds allotted to solve the problem; + default is the largest possible value for a ``double`` on the + platform. + dual_feasibility_tolerance : double (default: 1e-07) + Dual feasibility tolerance for + :ref:`'highs-ds' `. + The minimum of this and ``primal_feasibility_tolerance`` + is used for the feasibility tolerance of + :ref:`'highs-ipm' `. + primal_feasibility_tolerance : double (default: 1e-07) + Primal feasibility tolerance for + :ref:`'highs-ds' `. + The minimum of this and ``dual_feasibility_tolerance`` + is used for the feasibility tolerance of + :ref:`'highs-ipm' `. + ipm_optimality_tolerance : double (default: ``1e-08``) + Optimality tolerance for + :ref:`'highs-ipm' `. + Minimum allowable value is 1e-12. + simplex_dual_edge_weight_strategy : str (default: None) + Strategy for simplex dual edge weights. The default, ``None``, + automatically selects one of the following. + + ``'dantzig'`` uses Dantzig's original strategy of choosing the most + negative reduced cost. + + ``'devex'`` uses the strategy described in [15]_. + + ``steepest`` uses the exact steepest edge strategy as described in + [16]_. + + ``'steepest-devex'`` begins with the exact steepest edge strategy + until the computation is too costly or inexact and then switches to + the devex method. + + Currently, ``None`` always selects ``'steepest-devex'``, but this + may change as new options become available. + mip_rel_gap : double (default: None) + Termination criterion for MIP solver: solver will terminate when the + gap between the primal objective value and the dual objective bound, + scaled by the primal objective value, is <= mip_rel_gap. + unknown_options : dict + Optional arguments not used by this particular solver. If + ``unknown_options`` is non-empty, a warning is issued listing + all unused options. + + Returns + ------- + res : OptimizeResult + A :class:`scipy.optimize.OptimizeResult` consisting of the fields: + + x : 1D array + The values of the decision variables that minimizes the + objective function while satisfying the constraints. + fun : float + The optimal value of the objective function ``c @ x``. + slack : 1D array + The (nominally positive) values of the slack, + ``b_ub - A_ub @ x``. + con : 1D array + The (nominally zero) residuals of the equality constraints, + ``b_eq - A_eq @ x``. + success : bool + ``True`` when the algorithm succeeds in finding an optimal + solution. + status : int + An integer representing the exit status of the algorithm. + + ``0`` : Optimization terminated successfully. + + ``1`` : Iteration or time limit reached. + + ``2`` : Problem appears to be infeasible. + + ``3`` : Problem appears to be unbounded. + + ``4`` : The HiGHS solver ran into a problem. + + message : str + A string descriptor of the exit status of the algorithm. + nit : int + The total number of iterations performed. + For the HiGHS simplex method, this includes iterations in all + phases. For the HiGHS interior-point method, this does not include + crossover iterations. + crossover_nit : int + The number of primal/dual pushes performed during the + crossover routine for the HiGHS interior-point method. + This is ``0`` for the HiGHS simplex method. + ineqlin : OptimizeResult + Solution and sensitivity information corresponding to the + inequality constraints, `b_ub`. A dictionary consisting of the + fields: + + residual : np.ndnarray + The (nominally positive) values of the slack variables, + ``b_ub - A_ub @ x``. This quantity is also commonly + referred to as "slack". + + marginals : np.ndarray + The sensitivity (partial derivative) of the objective + function with respect to the right-hand side of the + inequality constraints, `b_ub`. + + eqlin : OptimizeResult + Solution and sensitivity information corresponding to the + equality constraints, `b_eq`. A dictionary consisting of the + fields: + + residual : np.ndarray + The (nominally zero) residuals of the equality constraints, + ``b_eq - A_eq @ x``. + + marginals : np.ndarray + The sensitivity (partial derivative) of the objective + function with respect to the right-hand side of the + equality constraints, `b_eq`. + + lower, upper : OptimizeResult + Solution and sensitivity information corresponding to the + lower and upper bounds on decision variables, `bounds`. + + residual : np.ndarray + The (nominally positive) values of the quantity + ``x - lb`` (lower) or ``ub - x`` (upper). + + marginals : np.ndarray + The sensitivity (partial derivative) of the objective + function with respect to the lower and upper + `bounds`. + + Notes + ----- + + Method :ref:`'highs-ds' ` is a wrapper + of the C++ high performance dual revised simplex implementation (HSOL) + [13]_, [14]_. Method :ref:`'highs-ipm' ` + is a wrapper of a C++ implementation of an **i**\ nterior-\ **p**\ oint + **m**\ ethod [13]_; it features a crossover routine, so it is as accurate + as a simplex solver. Method :ref:`'highs' ` chooses + between the two automatically. For new code involving `linprog`, we + recommend explicitly choosing one of these three method values instead of + :ref:`'interior-point' ` (default), + :ref:`'revised simplex' `, and + :ref:`'simplex' ` (legacy). + + The result fields `ineqlin`, `eqlin`, `lower`, and `upper` all contain + `marginals`, or partial derivatives of the objective function with respect + to the right-hand side of each constraint. These partial derivatives are + also referred to as "Lagrange multipliers", "dual values", and + "shadow prices". The sign convention of `marginals` is opposite that + of Lagrange multipliers produced by many nonlinear solvers. + + References + ---------- + .. [13] Huangfu, Q., Galabova, I., Feldmeier, M., and Hall, J. A. J. + "HiGHS - high performance software for linear optimization." + https://highs.dev/ + .. [14] Huangfu, Q. and Hall, J. A. J. "Parallelizing the dual revised + simplex method." Mathematical Programming Computation, 10 (1), + 119-142, 2018. DOI: 10.1007/s12532-017-0130-5 + .. [15] Harris, Paula MJ. "Pivot selection methods of the Devex LP code." + Mathematical programming 5.1 (1973): 1-28. + .. [16] Goldfarb, Donald, and John Ker Reid. "A practicable steepest-edge + simplex algorithm." Mathematical Programming 12.1 (1977): 361-371. + """ + pass + + +def _linprog_highs_ds_doc(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None, + bounds=None, method='highs-ds', callback=None, + maxiter=None, disp=False, presolve=True, + time_limit=None, + dual_feasibility_tolerance=None, + primal_feasibility_tolerance=None, + simplex_dual_edge_weight_strategy=None, + **unknown_options): + r""" + Linear programming: minimize a linear objective function subject to linear + equality and inequality constraints using the HiGHS dual simplex solver. + + Linear programming solves problems of the following form: + + .. math:: + + \min_x \ & c^T x \\ + \mbox{such that} \ & A_{ub} x \leq b_{ub},\\ + & A_{eq} x = b_{eq},\\ + & l \leq x \leq u , + + where :math:`x` is a vector of decision variables; :math:`c`, + :math:`b_{ub}`, :math:`b_{eq}`, :math:`l`, and :math:`u` are vectors; and + :math:`A_{ub}` and :math:`A_{eq}` are matrices. + + Alternatively, that's: + + minimize:: + + c @ x + + such that:: + + A_ub @ x <= b_ub + A_eq @ x == b_eq + lb <= x <= ub + + Note that by default ``lb = 0`` and ``ub = None`` unless specified with + ``bounds``. + + Parameters + ---------- + c : 1-D array + The coefficients of the linear objective function to be minimized. + A_ub : 2-D array, optional + The inequality constraint matrix. Each row of ``A_ub`` specifies the + coefficients of a linear inequality constraint on ``x``. + b_ub : 1-D array, optional + The inequality constraint vector. Each element represents an + upper bound on the corresponding value of ``A_ub @ x``. + A_eq : 2-D array, optional + The equality constraint matrix. Each row of ``A_eq`` specifies the + coefficients of a linear equality constraint on ``x``. + b_eq : 1-D array, optional + The equality constraint vector. Each element of ``A_eq @ x`` must equal + the corresponding element of ``b_eq``. + bounds : sequence, optional + A sequence of ``(min, max)`` pairs for each element in ``x``, defining + the minimum and maximum values of that decision variable. Use ``None`` + to indicate that there is no bound. By default, bounds are + ``(0, None)`` (all decision variables are non-negative). + If a single tuple ``(min, max)`` is provided, then ``min`` and + ``max`` will serve as bounds for all decision variables. + method : str + + This is the method-specific documentation for 'highs-ds'. + :ref:`'highs' `, + :ref:`'highs-ipm' `, + :ref:`'interior-point' ` (default), + :ref:`'revised simplex' `, and + :ref:`'simplex' ` (legacy) + are also available. + + Options + ------- + maxiter : int + The maximum number of iterations to perform in either phase. + Default is the largest possible value for an ``int`` on the platform. + disp : bool (default: ``False``) + Set to ``True`` if indicators of optimization status are to be + printed to the console during optimization. + presolve : bool (default: ``True``) + Presolve attempts to identify trivial infeasibilities, + identify trivial unboundedness, and simplify the problem before + sending it to the main solver. It is generally recommended + to keep the default setting ``True``; set to ``False`` if + presolve is to be disabled. + time_limit : float + The maximum time in seconds allotted to solve the problem; + default is the largest possible value for a ``double`` on the + platform. + dual_feasibility_tolerance : double (default: 1e-07) + Dual feasibility tolerance for + :ref:`'highs-ds' `. + primal_feasibility_tolerance : double (default: 1e-07) + Primal feasibility tolerance for + :ref:`'highs-ds' `. + simplex_dual_edge_weight_strategy : str (default: None) + Strategy for simplex dual edge weights. The default, ``None``, + automatically selects one of the following. + + ``'dantzig'`` uses Dantzig's original strategy of choosing the most + negative reduced cost. + + ``'devex'`` uses the strategy described in [15]_. + + ``steepest`` uses the exact steepest edge strategy as described in + [16]_. + + ``'steepest-devex'`` begins with the exact steepest edge strategy + until the computation is too costly or inexact and then switches to + the devex method. + + Currently, ``None`` always selects ``'steepest-devex'``, but this + may change as new options become available. + unknown_options : dict + Optional arguments not used by this particular solver. If + ``unknown_options`` is non-empty, a warning is issued listing + all unused options. + + Returns + ------- + res : OptimizeResult + A :class:`scipy.optimize.OptimizeResult` consisting of the fields: + + x : 1D array + The values of the decision variables that minimizes the + objective function while satisfying the constraints. + fun : float + The optimal value of the objective function ``c @ x``. + slack : 1D array + The (nominally positive) values of the slack, + ``b_ub - A_ub @ x``. + con : 1D array + The (nominally zero) residuals of the equality constraints, + ``b_eq - A_eq @ x``. + success : bool + ``True`` when the algorithm succeeds in finding an optimal + solution. + status : int + An integer representing the exit status of the algorithm. + + ``0`` : Optimization terminated successfully. + + ``1`` : Iteration or time limit reached. + + ``2`` : Problem appears to be infeasible. + + ``3`` : Problem appears to be unbounded. + + ``4`` : The HiGHS solver ran into a problem. + + message : str + A string descriptor of the exit status of the algorithm. + nit : int + The total number of iterations performed. This includes iterations + in all phases. + crossover_nit : int + This is always ``0`` for the HiGHS simplex method. + For the HiGHS interior-point method, this is the number of + primal/dual pushes performed during the crossover routine. + ineqlin : OptimizeResult + Solution and sensitivity information corresponding to the + inequality constraints, `b_ub`. A dictionary consisting of the + fields: + + residual : np.ndnarray + The (nominally positive) values of the slack variables, + ``b_ub - A_ub @ x``. This quantity is also commonly + referred to as "slack". + + marginals : np.ndarray + The sensitivity (partial derivative) of the objective + function with respect to the right-hand side of the + inequality constraints, `b_ub`. + + eqlin : OptimizeResult + Solution and sensitivity information corresponding to the + equality constraints, `b_eq`. A dictionary consisting of the + fields: + + residual : np.ndarray + The (nominally zero) residuals of the equality constraints, + ``b_eq - A_eq @ x``. + + marginals : np.ndarray + The sensitivity (partial derivative) of the objective + function with respect to the right-hand side of the + equality constraints, `b_eq`. + + lower, upper : OptimizeResult + Solution and sensitivity information corresponding to the + lower and upper bounds on decision variables, `bounds`. + + residual : np.ndarray + The (nominally positive) values of the quantity + ``x - lb`` (lower) or ``ub - x`` (upper). + + marginals : np.ndarray + The sensitivity (partial derivative) of the objective + function with respect to the lower and upper + `bounds`. + + Notes + ----- + + Method :ref:`'highs-ds' ` is a wrapper + of the C++ high performance dual revised simplex implementation (HSOL) + [13]_, [14]_. Method :ref:`'highs-ipm' ` + is a wrapper of a C++ implementation of an **i**\ nterior-\ **p**\ oint + **m**\ ethod [13]_; it features a crossover routine, so it is as accurate + as a simplex solver. Method :ref:`'highs' ` chooses + between the two automatically. For new code involving `linprog`, we + recommend explicitly choosing one of these three method values instead of + :ref:`'interior-point' ` (default), + :ref:`'revised simplex' `, and + :ref:`'simplex' ` (legacy). + + The result fields `ineqlin`, `eqlin`, `lower`, and `upper` all contain + `marginals`, or partial derivatives of the objective function with respect + to the right-hand side of each constraint. These partial derivatives are + also referred to as "Lagrange multipliers", "dual values", and + "shadow prices". The sign convention of `marginals` is opposite that + of Lagrange multipliers produced by many nonlinear solvers. + + References + ---------- + .. [13] Huangfu, Q., Galabova, I., Feldmeier, M., and Hall, J. A. J. + "HiGHS - high performance software for linear optimization." + https://highs.dev/ + .. [14] Huangfu, Q. and Hall, J. A. J. "Parallelizing the dual revised + simplex method." Mathematical Programming Computation, 10 (1), + 119-142, 2018. DOI: 10.1007/s12532-017-0130-5 + .. [15] Harris, Paula MJ. "Pivot selection methods of the Devex LP code." + Mathematical programming 5.1 (1973): 1-28. + .. [16] Goldfarb, Donald, and John Ker Reid. "A practicable steepest-edge + simplex algorithm." Mathematical Programming 12.1 (1977): 361-371. + """ + pass + + +def _linprog_highs_ipm_doc(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None, + bounds=None, method='highs-ipm', callback=None, + maxiter=None, disp=False, presolve=True, + time_limit=None, + dual_feasibility_tolerance=None, + primal_feasibility_tolerance=None, + ipm_optimality_tolerance=None, + **unknown_options): + r""" + Linear programming: minimize a linear objective function subject to linear + equality and inequality constraints using the HiGHS interior point solver. + + Linear programming solves problems of the following form: + + .. math:: + + \min_x \ & c^T x \\ + \mbox{such that} \ & A_{ub} x \leq b_{ub},\\ + & A_{eq} x = b_{eq},\\ + & l \leq x \leq u , + + where :math:`x` is a vector of decision variables; :math:`c`, + :math:`b_{ub}`, :math:`b_{eq}`, :math:`l`, and :math:`u` are vectors; and + :math:`A_{ub}` and :math:`A_{eq}` are matrices. + + Alternatively, that's: + + minimize:: + + c @ x + + such that:: + + A_ub @ x <= b_ub + A_eq @ x == b_eq + lb <= x <= ub + + Note that by default ``lb = 0`` and ``ub = None`` unless specified with + ``bounds``. + + Parameters + ---------- + c : 1-D array + The coefficients of the linear objective function to be minimized. + A_ub : 2-D array, optional + The inequality constraint matrix. Each row of ``A_ub`` specifies the + coefficients of a linear inequality constraint on ``x``. + b_ub : 1-D array, optional + The inequality constraint vector. Each element represents an + upper bound on the corresponding value of ``A_ub @ x``. + A_eq : 2-D array, optional + The equality constraint matrix. Each row of ``A_eq`` specifies the + coefficients of a linear equality constraint on ``x``. + b_eq : 1-D array, optional + The equality constraint vector. Each element of ``A_eq @ x`` must equal + the corresponding element of ``b_eq``. + bounds : sequence, optional + A sequence of ``(min, max)`` pairs for each element in ``x``, defining + the minimum and maximum values of that decision variable. Use ``None`` + to indicate that there is no bound. By default, bounds are + ``(0, None)`` (all decision variables are non-negative). + If a single tuple ``(min, max)`` is provided, then ``min`` and + ``max`` will serve as bounds for all decision variables. + method : str + + This is the method-specific documentation for 'highs-ipm'. + :ref:`'highs-ipm' `, + :ref:`'highs-ds' `, + :ref:`'interior-point' ` (default), + :ref:`'revised simplex' `, and + :ref:`'simplex' ` (legacy) + are also available. + + Options + ------- + maxiter : int + The maximum number of iterations to perform in either phase. + For :ref:`'highs-ipm' `, this does not + include the number of crossover iterations. Default is the largest + possible value for an ``int`` on the platform. + disp : bool (default: ``False``) + Set to ``True`` if indicators of optimization status are to be + printed to the console during optimization. + presolve : bool (default: ``True``) + Presolve attempts to identify trivial infeasibilities, + identify trivial unboundedness, and simplify the problem before + sending it to the main solver. It is generally recommended + to keep the default setting ``True``; set to ``False`` if + presolve is to be disabled. + time_limit : float + The maximum time in seconds allotted to solve the problem; + default is the largest possible value for a ``double`` on the + platform. + dual_feasibility_tolerance : double (default: 1e-07) + The minimum of this and ``primal_feasibility_tolerance`` + is used for the feasibility tolerance of + :ref:`'highs-ipm' `. + primal_feasibility_tolerance : double (default: 1e-07) + The minimum of this and ``dual_feasibility_tolerance`` + is used for the feasibility tolerance of + :ref:`'highs-ipm' `. + ipm_optimality_tolerance : double (default: ``1e-08``) + Optimality tolerance for + :ref:`'highs-ipm' `. + Minimum allowable value is 1e-12. + unknown_options : dict + Optional arguments not used by this particular solver. If + ``unknown_options`` is non-empty, a warning is issued listing + all unused options. + + Returns + ------- + res : OptimizeResult + A :class:`scipy.optimize.OptimizeResult` consisting of the fields: + + x : 1D array + The values of the decision variables that minimizes the + objective function while satisfying the constraints. + fun : float + The optimal value of the objective function ``c @ x``. + slack : 1D array + The (nominally positive) values of the slack, + ``b_ub - A_ub @ x``. + con : 1D array + The (nominally zero) residuals of the equality constraints, + ``b_eq - A_eq @ x``. + success : bool + ``True`` when the algorithm succeeds in finding an optimal + solution. + status : int + An integer representing the exit status of the algorithm. + + ``0`` : Optimization terminated successfully. + + ``1`` : Iteration or time limit reached. + + ``2`` : Problem appears to be infeasible. + + ``3`` : Problem appears to be unbounded. + + ``4`` : The HiGHS solver ran into a problem. + + message : str + A string descriptor of the exit status of the algorithm. + nit : int + The total number of iterations performed. + For the HiGHS interior-point method, this does not include + crossover iterations. + crossover_nit : int + The number of primal/dual pushes performed during the + crossover routine for the HiGHS interior-point method. + ineqlin : OptimizeResult + Solution and sensitivity information corresponding to the + inequality constraints, `b_ub`. A dictionary consisting of the + fields: + + residual : np.ndnarray + The (nominally positive) values of the slack variables, + ``b_ub - A_ub @ x``. This quantity is also commonly + referred to as "slack". + + marginals : np.ndarray + The sensitivity (partial derivative) of the objective + function with respect to the right-hand side of the + inequality constraints, `b_ub`. + + eqlin : OptimizeResult + Solution and sensitivity information corresponding to the + equality constraints, `b_eq`. A dictionary consisting of the + fields: + + residual : np.ndarray + The (nominally zero) residuals of the equality constraints, + ``b_eq - A_eq @ x``. + + marginals : np.ndarray + The sensitivity (partial derivative) of the objective + function with respect to the right-hand side of the + equality constraints, `b_eq`. + + lower, upper : OptimizeResult + Solution and sensitivity information corresponding to the + lower and upper bounds on decision variables, `bounds`. + + residual : np.ndarray + The (nominally positive) values of the quantity + ``x - lb`` (lower) or ``ub - x`` (upper). + + marginals : np.ndarray + The sensitivity (partial derivative) of the objective + function with respect to the lower and upper + `bounds`. + + Notes + ----- + + Method :ref:`'highs-ipm' ` + is a wrapper of a C++ implementation of an **i**\ nterior-\ **p**\ oint + **m**\ ethod [13]_; it features a crossover routine, so it is as accurate + as a simplex solver. + Method :ref:`'highs-ds' ` is a wrapper + of the C++ high performance dual revised simplex implementation (HSOL) + [13]_, [14]_. Method :ref:`'highs' ` chooses + between the two automatically. For new code involving `linprog`, we + recommend explicitly choosing one of these three method values instead of + :ref:`'interior-point' ` (default), + :ref:`'revised simplex' `, and + :ref:`'simplex' ` (legacy). + + The result fields `ineqlin`, `eqlin`, `lower`, and `upper` all contain + `marginals`, or partial derivatives of the objective function with respect + to the right-hand side of each constraint. These partial derivatives are + also referred to as "Lagrange multipliers", "dual values", and + "shadow prices". The sign convention of `marginals` is opposite that + of Lagrange multipliers produced by many nonlinear solvers. + + References + ---------- + .. [13] Huangfu, Q., Galabova, I., Feldmeier, M., and Hall, J. A. J. + "HiGHS - high performance software for linear optimization." + https://highs.dev/ + .. [14] Huangfu, Q. and Hall, J. A. J. "Parallelizing the dual revised + simplex method." Mathematical Programming Computation, 10 (1), + 119-142, 2018. DOI: 10.1007/s12532-017-0130-5 + """ + pass + + +def _linprog_ip_doc(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None, + bounds=None, method='interior-point', callback=None, + maxiter=1000, disp=False, presolve=True, + tol=1e-8, autoscale=False, rr=True, + alpha0=.99995, beta=0.1, sparse=False, + lstsq=False, sym_pos=True, cholesky=True, pc=True, + ip=False, permc_spec='MMD_AT_PLUS_A', **unknown_options): + r""" + Linear programming: minimize a linear objective function subject to linear + equality and inequality constraints using the interior-point method of + [4]_. + + .. deprecated:: 1.9.0 + `method='interior-point'` will be removed in SciPy 1.11.0. + It is replaced by `method='highs'` because the latter is + faster and more robust. + + Linear programming solves problems of the following form: + + .. math:: + + \min_x \ & c^T x \\ + \mbox{such that} \ & A_{ub} x \leq b_{ub},\\ + & A_{eq} x = b_{eq},\\ + & l \leq x \leq u , + + where :math:`x` is a vector of decision variables; :math:`c`, + :math:`b_{ub}`, :math:`b_{eq}`, :math:`l`, and :math:`u` are vectors; and + :math:`A_{ub}` and :math:`A_{eq}` are matrices. + + Alternatively, that's: + + minimize:: + + c @ x + + such that:: + + A_ub @ x <= b_ub + A_eq @ x == b_eq + lb <= x <= ub + + Note that by default ``lb = 0`` and ``ub = None`` unless specified with + ``bounds``. + + Parameters + ---------- + c : 1-D array + The coefficients of the linear objective function to be minimized. + A_ub : 2-D array, optional + The inequality constraint matrix. Each row of ``A_ub`` specifies the + coefficients of a linear inequality constraint on ``x``. + b_ub : 1-D array, optional + The inequality constraint vector. Each element represents an + upper bound on the corresponding value of ``A_ub @ x``. + A_eq : 2-D array, optional + The equality constraint matrix. Each row of ``A_eq`` specifies the + coefficients of a linear equality constraint on ``x``. + b_eq : 1-D array, optional + The equality constraint vector. Each element of ``A_eq @ x`` must equal + the corresponding element of ``b_eq``. + bounds : sequence, optional + A sequence of ``(min, max)`` pairs for each element in ``x``, defining + the minimum and maximum values of that decision variable. Use ``None`` + to indicate that there is no bound. By default, bounds are + ``(0, None)`` (all decision variables are non-negative). + If a single tuple ``(min, max)`` is provided, then ``min`` and + ``max`` will serve as bounds for all decision variables. + method : str + This is the method-specific documentation for 'interior-point'. + :ref:`'highs' `, + :ref:`'highs-ds' `, + :ref:`'highs-ipm' `, + :ref:`'revised simplex' `, and + :ref:`'simplex' ` (legacy) + are also available. + callback : callable, optional + Callback function to be executed once per iteration. + + Options + ------- + maxiter : int (default: 1000) + The maximum number of iterations of the algorithm. + disp : bool (default: False) + Set to ``True`` if indicators of optimization status are to be printed + to the console each iteration. + presolve : bool (default: True) + Presolve attempts to identify trivial infeasibilities, + identify trivial unboundedness, and simplify the problem before + sending it to the main solver. It is generally recommended + to keep the default setting ``True``; set to ``False`` if + presolve is to be disabled. + tol : float (default: 1e-8) + Termination tolerance to be used for all termination criteria; + see [4]_ Section 4.5. + autoscale : bool (default: False) + Set to ``True`` to automatically perform equilibration. + Consider using this option if the numerical values in the + constraints are separated by several orders of magnitude. + rr : bool (default: True) + Set to ``False`` to disable automatic redundancy removal. + alpha0 : float (default: 0.99995) + The maximal step size for Mehrota's predictor-corrector search + direction; see :math:`\beta_{3}` of [4]_ Table 8.1. + beta : float (default: 0.1) + The desired reduction of the path parameter :math:`\mu` (see [6]_) + when Mehrota's predictor-corrector is not in use (uncommon). + sparse : bool (default: False) + Set to ``True`` if the problem is to be treated as sparse after + presolve. If either ``A_eq`` or ``A_ub`` is a sparse matrix, + this option will automatically be set ``True``, and the problem + will be treated as sparse even during presolve. If your constraint + matrices contain mostly zeros and the problem is not very small (less + than about 100 constraints or variables), consider setting ``True`` + or providing ``A_eq`` and ``A_ub`` as sparse matrices. + lstsq : bool (default: ``False``) + Set to ``True`` if the problem is expected to be very poorly + conditioned. This should always be left ``False`` unless severe + numerical difficulties are encountered. Leave this at the default + unless you receive a warning message suggesting otherwise. + sym_pos : bool (default: True) + Leave ``True`` if the problem is expected to yield a well conditioned + symmetric positive definite normal equation matrix + (almost always). Leave this at the default unless you receive + a warning message suggesting otherwise. + cholesky : bool (default: True) + Set to ``True`` if the normal equations are to be solved by explicit + Cholesky decomposition followed by explicit forward/backward + substitution. This is typically faster for problems + that are numerically well-behaved. + pc : bool (default: True) + Leave ``True`` if the predictor-corrector method of Mehrota is to be + used. This is almost always (if not always) beneficial. + ip : bool (default: False) + Set to ``True`` if the improved initial point suggestion due to [4]_ + Section 4.3 is desired. Whether this is beneficial or not + depends on the problem. + permc_spec : str (default: 'MMD_AT_PLUS_A') + (Has effect only with ``sparse = True``, ``lstsq = False``, ``sym_pos = + True``, and no SuiteSparse.) + A matrix is factorized in each iteration of the algorithm. + This option specifies how to permute the columns of the matrix for + sparsity preservation. Acceptable values are: + + - ``NATURAL``: natural ordering. + - ``MMD_ATA``: minimum degree ordering on the structure of A^T A. + - ``MMD_AT_PLUS_A``: minimum degree ordering on the structure of A^T+A. + - ``COLAMD``: approximate minimum degree column ordering. + + This option can impact the convergence of the + interior point algorithm; test different values to determine which + performs best for your problem. For more information, refer to + ``scipy.sparse.linalg.splu``. + unknown_options : dict + Optional arguments not used by this particular solver. If + `unknown_options` is non-empty a warning is issued listing all + unused options. + + Returns + ------- + res : OptimizeResult + A :class:`scipy.optimize.OptimizeResult` consisting of the fields: + + x : 1-D array + The values of the decision variables that minimizes the + objective function while satisfying the constraints. + fun : float + The optimal value of the objective function ``c @ x``. + slack : 1-D array + The (nominally positive) values of the slack variables, + ``b_ub - A_ub @ x``. + con : 1-D array + The (nominally zero) residuals of the equality constraints, + ``b_eq - A_eq @ x``. + success : bool + ``True`` when the algorithm succeeds in finding an optimal + solution. + status : int + An integer representing the exit status of the algorithm. + + ``0`` : Optimization terminated successfully. + + ``1`` : Iteration limit reached. + + ``2`` : Problem appears to be infeasible. + + ``3`` : Problem appears to be unbounded. + + ``4`` : Numerical difficulties encountered. + + message : str + A string descriptor of the exit status of the algorithm. + nit : int + The total number of iterations performed in all phases. + + + Notes + ----- + This method implements the algorithm outlined in [4]_ with ideas from [8]_ + and a structure inspired by the simpler methods of [6]_. + + The primal-dual path following method begins with initial 'guesses' of + the primal and dual variables of the standard form problem and iteratively + attempts to solve the (nonlinear) Karush-Kuhn-Tucker conditions for the + problem with a gradually reduced logarithmic barrier term added to the + objective. This particular implementation uses a homogeneous self-dual + formulation, which provides certificates of infeasibility or unboundedness + where applicable. + + The default initial point for the primal and dual variables is that + defined in [4]_ Section 4.4 Equation 8.22. Optionally (by setting initial + point option ``ip=True``), an alternate (potentially improved) starting + point can be calculated according to the additional recommendations of + [4]_ Section 4.4. + + A search direction is calculated using the predictor-corrector method + (single correction) proposed by Mehrota and detailed in [4]_ Section 4.1. + (A potential improvement would be to implement the method of multiple + corrections described in [4]_ Section 4.2.) In practice, this is + accomplished by solving the normal equations, [4]_ Section 5.1 Equations + 8.31 and 8.32, derived from the Newton equations [4]_ Section 5 Equations + 8.25 (compare to [4]_ Section 4 Equations 8.6-8.8). The advantage of + solving the normal equations rather than 8.25 directly is that the + matrices involved are symmetric positive definite, so Cholesky + decomposition can be used rather than the more expensive LU factorization. + + With default options, the solver used to perform the factorization depends + on third-party software availability and the conditioning of the problem. + + For dense problems, solvers are tried in the following order: + + 1. ``scipy.linalg.cho_factor`` + + 2. ``scipy.linalg.solve`` with option ``sym_pos=True`` + + 3. ``scipy.linalg.solve`` with option ``sym_pos=False`` + + 4. ``scipy.linalg.lstsq`` + + For sparse problems: + + 1. ``sksparse.cholmod.cholesky`` (if scikit-sparse and SuiteSparse are + installed) + + 2. ``scipy.sparse.linalg.factorized`` (if scikit-umfpack and SuiteSparse + are installed) + + 3. ``scipy.sparse.linalg.splu`` (which uses SuperLU distributed with SciPy) + + 4. ``scipy.sparse.linalg.lsqr`` + + If the solver fails for any reason, successively more robust (but slower) + solvers are attempted in the order indicated. Attempting, failing, and + re-starting factorization can be time consuming, so if the problem is + numerically challenging, options can be set to bypass solvers that are + failing. Setting ``cholesky=False`` skips to solver 2, + ``sym_pos=False`` skips to solver 3, and ``lstsq=True`` skips + to solver 4 for both sparse and dense problems. + + Potential improvements for combating issues associated with dense + columns in otherwise sparse problems are outlined in [4]_ Section 5.3 and + [10]_ Section 4.1-4.2; the latter also discusses the alleviation of + accuracy issues associated with the substitution approach to free + variables. + + After calculating the search direction, the maximum possible step size + that does not activate the non-negativity constraints is calculated, and + the smaller of this step size and unity is applied (as in [4]_ Section + 4.1.) [4]_ Section 4.3 suggests improvements for choosing the step size. + + The new point is tested according to the termination conditions of [4]_ + Section 4.5. The same tolerance, which can be set using the ``tol`` option, + is used for all checks. (A potential improvement would be to expose + the different tolerances to be set independently.) If optimality, + unboundedness, or infeasibility is detected, the solve procedure + terminates; otherwise it repeats. + + Whereas the top level ``linprog`` module expects a problem of form: + + Minimize:: + + c @ x + + Subject to:: + + A_ub @ x <= b_ub + A_eq @ x == b_eq + lb <= x <= ub + + where ``lb = 0`` and ``ub = None`` unless set in ``bounds``. The problem + is automatically converted to the form: + + Minimize:: + + c @ x + + Subject to:: + + A @ x == b + x >= 0 + + for solution. That is, the original problem contains equality, upper-bound + and variable constraints whereas the method specific solver requires + equality constraints and variable non-negativity. ``linprog`` converts the + original problem to standard form by converting the simple bounds to upper + bound constraints, introducing non-negative slack variables for inequality + constraints, and expressing unbounded variables as the difference between + two non-negative variables. The problem is converted back to the original + form before results are reported. + + References + ---------- + .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point + optimizer for linear programming: an implementation of the + homogeneous algorithm." High performance optimization. Springer US, + 2000. 197-232. + .. [6] Freund, Robert M. "Primal-Dual Interior-Point Methods for Linear + Programming based on Newton's Method." Unpublished Course Notes, + March 2004. Available 2/25/2017 at + https://ocw.mit.edu/courses/sloan-school-of-management/15-084j-nonlinear-programming-spring-2004/lecture-notes/lec14_int_pt_mthd.pdf + .. [8] Andersen, Erling D., and Knud D. Andersen. "Presolving in linear + programming." Mathematical Programming 71.2 (1995): 221-245. + .. [9] Bertsimas, Dimitris, and J. Tsitsiklis. "Introduction to linear + programming." Athena Scientific 1 (1997): 997. + .. [10] Andersen, Erling D., et al. Implementation of interior point + methods for large scale linear programming. HEC/Universite de + Geneve, 1996. + """ + pass + + +def _linprog_rs_doc(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None, + bounds=None, method='interior-point', callback=None, + x0=None, maxiter=5000, disp=False, presolve=True, + tol=1e-12, autoscale=False, rr=True, maxupdate=10, + mast=False, pivot="mrc", **unknown_options): + r""" + Linear programming: minimize a linear objective function subject to linear + equality and inequality constraints using the revised simplex method. + + .. deprecated:: 1.9.0 + `method='revised simplex'` will be removed in SciPy 1.11.0. + It is replaced by `method='highs'` because the latter is + faster and more robust. + + Linear programming solves problems of the following form: + + .. math:: + + \min_x \ & c^T x \\ + \mbox{such that} \ & A_{ub} x \leq b_{ub},\\ + & A_{eq} x = b_{eq},\\ + & l \leq x \leq u , + + where :math:`x` is a vector of decision variables; :math:`c`, + :math:`b_{ub}`, :math:`b_{eq}`, :math:`l`, and :math:`u` are vectors; and + :math:`A_{ub}` and :math:`A_{eq}` are matrices. + + Alternatively, that's: + + minimize:: + + c @ x + + such that:: + + A_ub @ x <= b_ub + A_eq @ x == b_eq + lb <= x <= ub + + Note that by default ``lb = 0`` and ``ub = None`` unless specified with + ``bounds``. + + Parameters + ---------- + c : 1-D array + The coefficients of the linear objective function to be minimized. + A_ub : 2-D array, optional + The inequality constraint matrix. Each row of ``A_ub`` specifies the + coefficients of a linear inequality constraint on ``x``. + b_ub : 1-D array, optional + The inequality constraint vector. Each element represents an + upper bound on the corresponding value of ``A_ub @ x``. + A_eq : 2-D array, optional + The equality constraint matrix. Each row of ``A_eq`` specifies the + coefficients of a linear equality constraint on ``x``. + b_eq : 1-D array, optional + The equality constraint vector. Each element of ``A_eq @ x`` must equal + the corresponding element of ``b_eq``. + bounds : sequence, optional + A sequence of ``(min, max)`` pairs for each element in ``x``, defining + the minimum and maximum values of that decision variable. Use ``None`` + to indicate that there is no bound. By default, bounds are + ``(0, None)`` (all decision variables are non-negative). + If a single tuple ``(min, max)`` is provided, then ``min`` and + ``max`` will serve as bounds for all decision variables. + method : str + This is the method-specific documentation for 'revised simplex'. + :ref:`'highs' `, + :ref:`'highs-ds' `, + :ref:`'highs-ipm' `, + :ref:`'interior-point' ` (default), + and :ref:`'simplex' ` (legacy) + are also available. + callback : callable, optional + Callback function to be executed once per iteration. + x0 : 1-D array, optional + Guess values of the decision variables, which will be refined by + the optimization algorithm. This argument is currently used only by the + 'revised simplex' method, and can only be used if `x0` represents a + basic feasible solution. + + Options + ------- + maxiter : int (default: 5000) + The maximum number of iterations to perform in either phase. + disp : bool (default: False) + Set to ``True`` if indicators of optimization status are to be printed + to the console each iteration. + presolve : bool (default: True) + Presolve attempts to identify trivial infeasibilities, + identify trivial unboundedness, and simplify the problem before + sending it to the main solver. It is generally recommended + to keep the default setting ``True``; set to ``False`` if + presolve is to be disabled. + tol : float (default: 1e-12) + The tolerance which determines when a solution is "close enough" to + zero in Phase 1 to be considered a basic feasible solution or close + enough to positive to serve as an optimal solution. + autoscale : bool (default: False) + Set to ``True`` to automatically perform equilibration. + Consider using this option if the numerical values in the + constraints are separated by several orders of magnitude. + rr : bool (default: True) + Set to ``False`` to disable automatic redundancy removal. + maxupdate : int (default: 10) + The maximum number of updates performed on the LU factorization. + After this many updates is reached, the basis matrix is factorized + from scratch. + mast : bool (default: False) + Minimize Amortized Solve Time. If enabled, the average time to solve + a linear system using the basis factorization is measured. Typically, + the average solve time will decrease with each successive solve after + initial factorization, as factorization takes much more time than the + solve operation (and updates). Eventually, however, the updated + factorization becomes sufficiently complex that the average solve time + begins to increase. When this is detected, the basis is refactorized + from scratch. Enable this option to maximize speed at the risk of + nondeterministic behavior. Ignored if ``maxupdate`` is 0. + pivot : "mrc" or "bland" (default: "mrc") + Pivot rule: Minimum Reduced Cost ("mrc") or Bland's rule ("bland"). + Choose Bland's rule if iteration limit is reached and cycling is + suspected. + unknown_options : dict + Optional arguments not used by this particular solver. If + `unknown_options` is non-empty a warning is issued listing all + unused options. + + Returns + ------- + res : OptimizeResult + A :class:`scipy.optimize.OptimizeResult` consisting of the fields: + + x : 1-D array + The values of the decision variables that minimizes the + objective function while satisfying the constraints. + fun : float + The optimal value of the objective function ``c @ x``. + slack : 1-D array + The (nominally positive) values of the slack variables, + ``b_ub - A_ub @ x``. + con : 1-D array + The (nominally zero) residuals of the equality constraints, + ``b_eq - A_eq @ x``. + success : bool + ``True`` when the algorithm succeeds in finding an optimal + solution. + status : int + An integer representing the exit status of the algorithm. + + ``0`` : Optimization terminated successfully. + + ``1`` : Iteration limit reached. + + ``2`` : Problem appears to be infeasible. + + ``3`` : Problem appears to be unbounded. + + ``4`` : Numerical difficulties encountered. + + ``5`` : Problem has no constraints; turn presolve on. + + ``6`` : Invalid guess provided. + + message : str + A string descriptor of the exit status of the algorithm. + nit : int + The total number of iterations performed in all phases. + + + Notes + ----- + Method *revised simplex* uses the revised simplex method as described in + [9]_, except that a factorization [11]_ of the basis matrix, rather than + its inverse, is efficiently maintained and used to solve the linear systems + at each iteration of the algorithm. + + References + ---------- + .. [9] Bertsimas, Dimitris, and J. Tsitsiklis. "Introduction to linear + programming." Athena Scientific 1 (1997): 997. + .. [11] Bartels, Richard H. "A stabilization of the simplex method." + Journal in Numerische Mathematik 16.5 (1971): 414-434. + """ + pass + + +def _linprog_simplex_doc(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None, + bounds=None, method='interior-point', callback=None, + maxiter=5000, disp=False, presolve=True, + tol=1e-12, autoscale=False, rr=True, bland=False, + **unknown_options): + r""" + Linear programming: minimize a linear objective function subject to linear + equality and inequality constraints using the tableau-based simplex method. + + .. deprecated:: 1.9.0 + `method='simplex'` will be removed in SciPy 1.11.0. + It is replaced by `method='highs'` because the latter is + faster and more robust. + + Linear programming solves problems of the following form: + + .. math:: + + \min_x \ & c^T x \\ + \mbox{such that} \ & A_{ub} x \leq b_{ub},\\ + & A_{eq} x = b_{eq},\\ + & l \leq x \leq u , + + where :math:`x` is a vector of decision variables; :math:`c`, + :math:`b_{ub}`, :math:`b_{eq}`, :math:`l`, and :math:`u` are vectors; and + :math:`A_{ub}` and :math:`A_{eq}` are matrices. + + Alternatively, that's: + + minimize:: + + c @ x + + such that:: + + A_ub @ x <= b_ub + A_eq @ x == b_eq + lb <= x <= ub + + Note that by default ``lb = 0`` and ``ub = None`` unless specified with + ``bounds``. + + Parameters + ---------- + c : 1-D array + The coefficients of the linear objective function to be minimized. + A_ub : 2-D array, optional + The inequality constraint matrix. Each row of ``A_ub`` specifies the + coefficients of a linear inequality constraint on ``x``. + b_ub : 1-D array, optional + The inequality constraint vector. Each element represents an + upper bound on the corresponding value of ``A_ub @ x``. + A_eq : 2-D array, optional + The equality constraint matrix. Each row of ``A_eq`` specifies the + coefficients of a linear equality constraint on ``x``. + b_eq : 1-D array, optional + The equality constraint vector. Each element of ``A_eq @ x`` must equal + the corresponding element of ``b_eq``. + bounds : sequence, optional + A sequence of ``(min, max)`` pairs for each element in ``x``, defining + the minimum and maximum values of that decision variable. Use ``None`` + to indicate that there is no bound. By default, bounds are + ``(0, None)`` (all decision variables are non-negative). + If a single tuple ``(min, max)`` is provided, then ``min`` and + ``max`` will serve as bounds for all decision variables. + method : str + This is the method-specific documentation for 'simplex'. + :ref:`'highs' `, + :ref:`'highs-ds' `, + :ref:`'highs-ipm' `, + :ref:`'interior-point' ` (default), + and :ref:`'revised simplex' ` + are also available. + callback : callable, optional + Callback function to be executed once per iteration. + + Options + ------- + maxiter : int (default: 5000) + The maximum number of iterations to perform in either phase. + disp : bool (default: False) + Set to ``True`` if indicators of optimization status are to be printed + to the console each iteration. + presolve : bool (default: True) + Presolve attempts to identify trivial infeasibilities, + identify trivial unboundedness, and simplify the problem before + sending it to the main solver. It is generally recommended + to keep the default setting ``True``; set to ``False`` if + presolve is to be disabled. + tol : float (default: 1e-12) + The tolerance which determines when a solution is "close enough" to + zero in Phase 1 to be considered a basic feasible solution or close + enough to positive to serve as an optimal solution. + autoscale : bool (default: False) + Set to ``True`` to automatically perform equilibration. + Consider using this option if the numerical values in the + constraints are separated by several orders of magnitude. + rr : bool (default: True) + Set to ``False`` to disable automatic redundancy removal. + bland : bool + If True, use Bland's anti-cycling rule [3]_ to choose pivots to + prevent cycling. If False, choose pivots which should lead to a + converged solution more quickly. The latter method is subject to + cycling (non-convergence) in rare instances. + unknown_options : dict + Optional arguments not used by this particular solver. If + `unknown_options` is non-empty a warning is issued listing all + unused options. + + Returns + ------- + res : OptimizeResult + A :class:`scipy.optimize.OptimizeResult` consisting of the fields: + + x : 1-D array + The values of the decision variables that minimizes the + objective function while satisfying the constraints. + fun : float + The optimal value of the objective function ``c @ x``. + slack : 1-D array + The (nominally positive) values of the slack variables, + ``b_ub - A_ub @ x``. + con : 1-D array + The (nominally zero) residuals of the equality constraints, + ``b_eq - A_eq @ x``. + success : bool + ``True`` when the algorithm succeeds in finding an optimal + solution. + status : int + An integer representing the exit status of the algorithm. + + ``0`` : Optimization terminated successfully. + + ``1`` : Iteration limit reached. + + ``2`` : Problem appears to be infeasible. + + ``3`` : Problem appears to be unbounded. + + ``4`` : Numerical difficulties encountered. + + message : str + A string descriptor of the exit status of the algorithm. + nit : int + The total number of iterations performed in all phases. + + References + ---------- + .. [1] Dantzig, George B., Linear programming and extensions. Rand + Corporation Research Study Princeton Univ. Press, Princeton, NJ, + 1963 + .. [2] Hillier, S.H. and Lieberman, G.J. (1995), "Introduction to + Mathematical Programming", McGraw-Hill, Chapter 4. + .. [3] Bland, Robert G. New finite pivoting rules for the simplex method. + Mathematics of Operations Research (2), 1977: pp. 103-107. + """ + pass diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_linprog_highs.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_linprog_highs.py new file mode 100644 index 0000000000000000000000000000000000000000..9455cf460f96b7768c28acfbba76ad9ad08eed3f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_linprog_highs.py @@ -0,0 +1,422 @@ +"""HiGHS Linear Optimization Methods + +Interface to HiGHS linear optimization software. +https://highs.dev/ + +.. versionadded:: 1.5.0 + +References +---------- +.. [1] Q. Huangfu and J.A.J. Hall. "Parallelizing the dual revised simplex + method." Mathematical Programming Computation, 10 (1), 119-142, + 2018. DOI: 10.1007/s12532-017-0130-5 + +""" + +import inspect +import numpy as np +from ._optimize import OptimizeWarning, OptimizeResult +from warnings import warn +from ._highspy._highs_wrapper import _highs_wrapper +from ._highspy._core import( + kHighsInf, + HighsDebugLevel, + ObjSense, + HighsModelStatus, + simplex_constants as s_c, # [1] +) +from scipy.sparse import csc_matrix, vstack, issparse + +# [1]: Directly importing from "._highspy._core.simplex_constants" +# causes problems when reloading. +# See https://github.com/scipy/scipy/pull/22869 for details. + +def _highs_to_scipy_status_message(highs_status, highs_message): + """Converts HiGHS status number/message to SciPy status number/message""" + + scipy_statuses_messages = { + None: (4, "HiGHS did not provide a status code. "), + HighsModelStatus.kNotset: (4, ""), + HighsModelStatus.kLoadError: (4, ""), + HighsModelStatus.kModelError: (2, ""), + HighsModelStatus.kPresolveError: (4, ""), + HighsModelStatus.kSolveError: (4, ""), + HighsModelStatus.kPostsolveError: (4, ""), + HighsModelStatus.kModelEmpty: (4, ""), + HighsModelStatus.kObjectiveBound: (4, ""), + HighsModelStatus.kObjectiveTarget: (4, ""), + HighsModelStatus.kOptimal: (0, "Optimization terminated successfully. "), + HighsModelStatus.kTimeLimit: (1, "Time limit reached. "), + HighsModelStatus.kIterationLimit: (1, "Iteration limit reached. "), + HighsModelStatus.kInfeasible: (2, "The problem is infeasible. "), + HighsModelStatus.kUnbounded: (3, "The problem is unbounded. "), + HighsModelStatus.kUnboundedOrInfeasible: (4, "The problem is unbounded " + "or infeasible. ")} + unrecognized = (4, "The HiGHS status code was not recognized. ") + scipy_status, scipy_message = ( + scipy_statuses_messages.get(highs_status, unrecognized)) + hstat = int(highs_status) if highs_status is not None else None + scipy_message = (f"{scipy_message}" + f"(HiGHS Status {hstat}: {highs_message})") + return scipy_status, scipy_message + + +def _replace_inf(x): + # Replace `np.inf` with kHighsInf + infs = np.isinf(x) + with np.errstate(invalid="ignore"): + x[infs] = np.sign(x[infs])*kHighsInf + return x + + +def _convert_to_highs_enum(option, option_str, choices): + # If option is in the choices we can look it up, if not use + # the default value taken from function signature and warn: + try: + return choices[option.lower()] + except AttributeError: + return choices[option] + except KeyError: + sig = inspect.signature(_linprog_highs) + default_str = sig.parameters[option_str].default + warn(f"Option {option_str} is {option}, but only values in " + f"{set(choices.keys())} are allowed. Using default: " + f"{default_str}.", + OptimizeWarning, stacklevel=3) + return choices[default_str] + + +def _linprog_highs(lp, solver, time_limit=None, presolve=True, + disp=False, maxiter=None, + dual_feasibility_tolerance=None, + primal_feasibility_tolerance=None, + ipm_optimality_tolerance=None, + simplex_dual_edge_weight_strategy=None, + mip_rel_gap=None, + mip_max_nodes=None, + **unknown_options): + r""" + Solve the following linear programming problem using one of the HiGHS + solvers: + + User-facing documentation is in _linprog_doc.py. + + Parameters + ---------- + lp : _LPProblem + A ``scipy.optimize._linprog_util._LPProblem`` ``namedtuple``. + solver : "ipm" or "simplex" or None + Which HiGHS solver to use. If ``None``, "simplex" will be used. + + Options + ------- + maxiter : int + The maximum number of iterations to perform in either phase. For + ``solver='ipm'``, this does not include the number of crossover + iterations. Default is the largest possible value for an ``int`` + on the platform. + disp : bool + Set to ``True`` if indicators of optimization status are to be printed + to the console each iteration; default ``False``. + time_limit : float + The maximum time in seconds allotted to solve the problem; default is + the largest possible value for a ``double`` on the platform. + presolve : bool + Presolve attempts to identify trivial infeasibilities, + identify trivial unboundedness, and simplify the problem before + sending it to the main solver. It is generally recommended + to keep the default setting ``True``; set to ``False`` if presolve is + to be disabled. + dual_feasibility_tolerance : double + Dual feasibility tolerance. Default is 1e-07. + The minimum of this and ``primal_feasibility_tolerance`` + is used for the feasibility tolerance when ``solver='ipm'``. + primal_feasibility_tolerance : double + Primal feasibility tolerance. Default is 1e-07. + The minimum of this and ``dual_feasibility_tolerance`` + is used for the feasibility tolerance when ``solver='ipm'``. + ipm_optimality_tolerance : double + Optimality tolerance for ``solver='ipm'``. Default is 1e-08. + Minimum possible value is 1e-12 and must be smaller than the largest + possible value for a ``double`` on the platform. + simplex_dual_edge_weight_strategy : str (default: None) + Strategy for simplex dual edge weights. The default, ``None``, + automatically selects one of the following. + + ``'dantzig'`` uses Dantzig's original strategy of choosing the most + negative reduced cost. + + ``'devex'`` uses the strategy described in [15]_. + + ``steepest`` uses the exact steepest edge strategy as described in + [16]_. + + ``'steepest-devex'`` begins with the exact steepest edge strategy + until the computation is too costly or inexact and then switches to + the devex method. + + Currently, using ``None`` always selects ``'steepest-devex'``, but this + may change as new options become available. + + mip_max_nodes : int + The maximum number of nodes allotted to solve the problem; default is + the largest possible value for a ``HighsInt`` on the platform. + Ignored if not using the MIP solver. + unknown_options : dict + Optional arguments not used by this particular solver. If + ``unknown_options`` is non-empty, a warning is issued listing all + unused options. + + Returns + ------- + sol : dict + A dictionary consisting of the fields: + + x : 1D array + The values of the decision variables that minimizes the + objective function while satisfying the constraints. + fun : float + The optimal value of the objective function ``c @ x``. + slack : 1D array + The (nominally positive) values of the slack, + ``b_ub - A_ub @ x``. + con : 1D array + The (nominally zero) residuals of the equality constraints, + ``b_eq - A_eq @ x``. + success : bool + ``True`` when the algorithm succeeds in finding an optimal + solution. + status : int + An integer representing the exit status of the algorithm. + + ``0`` : Optimization terminated successfully. + + ``1`` : Iteration or time limit reached. + + ``2`` : Problem appears to be infeasible. + + ``3`` : Problem appears to be unbounded. + + ``4`` : The HiGHS solver ran into a problem. + + message : str + A string descriptor of the exit status of the algorithm. + nit : int + The total number of iterations performed. + For ``solver='simplex'``, this includes iterations in all + phases. For ``solver='ipm'``, this does not include + crossover iterations. + crossover_nit : int + The number of primal/dual pushes performed during the + crossover routine for ``solver='ipm'``. This is ``0`` + for ``solver='simplex'``. + ineqlin : OptimizeResult + Solution and sensitivity information corresponding to the + inequality constraints, `b_ub`. A dictionary consisting of the + fields: + + residual : np.ndnarray + The (nominally positive) values of the slack variables, + ``b_ub - A_ub @ x``. This quantity is also commonly + referred to as "slack". + + marginals : np.ndarray + The sensitivity (partial derivative) of the objective + function with respect to the right-hand side of the + inequality constraints, `b_ub`. + + eqlin : OptimizeResult + Solution and sensitivity information corresponding to the + equality constraints, `b_eq`. A dictionary consisting of the + fields: + + residual : np.ndarray + The (nominally zero) residuals of the equality constraints, + ``b_eq - A_eq @ x``. + + marginals : np.ndarray + The sensitivity (partial derivative) of the objective + function with respect to the right-hand side of the + equality constraints, `b_eq`. + + lower, upper : OptimizeResult + Solution and sensitivity information corresponding to the + lower and upper bounds on decision variables, `bounds`. + + residual : np.ndarray + The (nominally positive) values of the quantity + ``x - lb`` (lower) or ``ub - x`` (upper). + + marginals : np.ndarray + The sensitivity (partial derivative) of the objective + function with respect to the lower and upper + `bounds`. + + mip_node_count : int + The number of subproblems or "nodes" solved by the MILP + solver. Only present when `integrality` is not `None`. + + mip_dual_bound : float + The MILP solver's final estimate of the lower bound on the + optimal solution. Only present when `integrality` is not + `None`. + + mip_gap : float + The difference between the final objective function value + and the final dual bound, scaled by the final objective + function value. Only present when `integrality` is not + `None`. + + Notes + ----- + The result fields `ineqlin`, `eqlin`, `lower`, and `upper` all contain + `marginals`, or partial derivatives of the objective function with respect + to the right-hand side of each constraint. These partial derivatives are + also referred to as "Lagrange multipliers", "dual values", and + "shadow prices". The sign convention of `marginals` is opposite that + of Lagrange multipliers produced by many nonlinear solvers. + + References + ---------- + .. [15] Harris, Paula MJ. "Pivot selection methods of the Devex LP code." + Mathematical programming 5.1 (1973): 1-28. + .. [16] Goldfarb, Donald, and John Ker Reid. "A practicable steepest-edge + simplex algorithm." Mathematical Programming 12.1 (1977): 361-371. + """ + if unknown_options: + message = (f"Unrecognized options detected: {unknown_options}. " + "These will be passed to HiGHS verbatim.") + warn(message, OptimizeWarning, stacklevel=3) + + # Map options to HiGHS enum values + simplex_dual_edge_weight_strategy_enum = _convert_to_highs_enum( + simplex_dual_edge_weight_strategy, + 'simplex_dual_edge_weight_strategy', + choices={'dantzig': \ + s_c.SimplexEdgeWeightStrategy.kSimplexEdgeWeightStrategyDantzig, + 'devex': \ + s_c.SimplexEdgeWeightStrategy.kSimplexEdgeWeightStrategyDevex, + 'steepest-devex': \ + s_c.SimplexEdgeWeightStrategy.kSimplexEdgeWeightStrategyChoose, + 'steepest': \ + s_c.SimplexEdgeWeightStrategy.kSimplexEdgeWeightStrategySteepestEdge, + None: None}) + + c, A_ub, b_ub, A_eq, b_eq, bounds, x0, integrality = lp + + lb, ub = bounds.T.copy() # separate bounds, copy->C-cntgs + # highs_wrapper solves LHS <= A*x <= RHS, not equality constraints + with np.errstate(invalid="ignore"): + lhs_ub = -np.ones_like(b_ub)*np.inf # LHS of UB constraints is -inf + rhs_ub = b_ub # RHS of UB constraints is b_ub + lhs_eq = b_eq # Equality constraint is inequality + rhs_eq = b_eq # constraint with LHS=RHS + lhs = np.concatenate((lhs_ub, lhs_eq)) + rhs = np.concatenate((rhs_ub, rhs_eq)) + + if issparse(A_ub) or issparse(A_eq): + A = vstack((A_ub, A_eq)) + else: + A = np.vstack((A_ub, A_eq)) + A = csc_matrix(A) + + options = { + 'presolve': presolve, + 'sense': ObjSense.kMinimize, + 'solver': solver, + 'time_limit': time_limit, + 'highs_debug_level': HighsDebugLevel.kHighsDebugLevelNone, + 'dual_feasibility_tolerance': dual_feasibility_tolerance, + 'ipm_optimality_tolerance': ipm_optimality_tolerance, + 'log_to_console': disp, + 'mip_max_nodes': mip_max_nodes, + 'output_flag': disp, + 'primal_feasibility_tolerance': primal_feasibility_tolerance, + 'simplex_dual_edge_weight_strategy': + simplex_dual_edge_weight_strategy_enum, + 'simplex_strategy': s_c.SimplexStrategy.kSimplexStrategyDual, + 'ipm_iteration_limit': maxiter, + 'simplex_iteration_limit': maxiter, + 'mip_rel_gap': mip_rel_gap, + } + options.update(unknown_options) + + # np.inf doesn't work; use very large constant + rhs = _replace_inf(rhs) + lhs = _replace_inf(lhs) + lb = _replace_inf(lb) + ub = _replace_inf(ub) + + if integrality is None or np.sum(integrality) == 0: + integrality = np.empty(0) + else: + integrality = np.array(integrality) + + res = _highs_wrapper(c, A.indptr, A.indices, A.data, lhs, rhs, + lb, ub, integrality.astype(np.uint8), options) + + # HiGHS represents constraints as lhs/rhs, so + # Ax + s = b => Ax = b - s + # and we need to split up s by A_ub and A_eq + if 'slack' in res: + slack = res['slack'] + con = np.array(slack[len(b_ub):]) + slack = np.array(slack[:len(b_ub)]) + else: + slack, con = None, None + + # lagrange multipliers for equalities/inequalities and upper/lower bounds + if 'lambda' in res: + lamda = res['lambda'] + marg_ineqlin = np.array(lamda[:len(b_ub)]) + marg_eqlin = np.array(lamda[len(b_ub):]) + marg_upper = np.array(res['marg_bnds'][1, :]) + marg_lower = np.array(res['marg_bnds'][0, :]) + else: + marg_ineqlin, marg_eqlin = None, None + marg_upper, marg_lower = None, None + + # this needs to be updated if we start choosing the solver intelligently + + # Convert to scipy-style status and message + highs_status = res.get('status', None) + highs_message = res.get('message', None) + status, message = _highs_to_scipy_status_message(highs_status, + highs_message) + + x = res['x'] # is None if not set + sol = {'x': x, + 'slack': slack, + 'con': con, + 'ineqlin': OptimizeResult({ + 'residual': slack, + 'marginals': marg_ineqlin, + }), + 'eqlin': OptimizeResult({ + 'residual': con, + 'marginals': marg_eqlin, + }), + 'lower': OptimizeResult({ + 'residual': None if x is None else x - lb, + 'marginals': marg_lower, + }), + 'upper': OptimizeResult({ + 'residual': None if x is None else ub - x, + 'marginals': marg_upper + }), + 'fun': res.get('fun'), + 'status': status, + 'success': res['status'] == HighsModelStatus.kOptimal, + 'message': message, + 'nit': res.get('simplex_nit', 0) or res.get('ipm_nit', 0), + 'crossover_nit': res.get('crossover_nit'), + } + + if np.any(x) and integrality is not None: + sol.update({ + 'mip_node_count': res.get('mip_node_count', 0), + 'mip_dual_bound': res.get('mip_dual_bound', 0.0), + 'mip_gap': res.get('mip_gap', 0.0), + }) + + return sol diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_linprog_ip.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_linprog_ip.py new file mode 100644 index 0000000000000000000000000000000000000000..4e6bf717b4d7becd46d0046cedf5f807004898e4 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_linprog_ip.py @@ -0,0 +1,1126 @@ +"""Interior-point method for linear programming + +The *interior-point* method uses the primal-dual path following algorithm +outlined in [1]_. This algorithm supports sparse constraint matrices and +is typically faster than the simplex methods, especially for large, sparse +problems. Note, however, that the solution returned may be slightly less +accurate than those of the simplex methods and will not, in general, +correspond with a vertex of the polytope defined by the constraints. + + .. versionadded:: 1.0.0 + +References +---------- +.. [1] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point + optimizer for linear programming: an implementation of the + homogeneous algorithm." High performance optimization. Springer US, + 2000. 197-232. +""" +# Author: Matt Haberland + +import numpy as np +import scipy as sp +import scipy.sparse as sps +from warnings import warn +from scipy.linalg import LinAlgError +from ._optimize import OptimizeWarning, OptimizeResult, _check_unknown_options +from ._linprog_util import _postsolve +has_umfpack = True +has_cholmod = True +try: + import sksparse # noqa: F401 + from sksparse.cholmod import cholesky as cholmod # noqa: F401 + from sksparse.cholmod import analyze as cholmod_analyze +except ImportError: + has_cholmod = False +try: + import scikits.umfpack # test whether to use factorized # noqa: F401 +except ImportError: + has_umfpack = False + + +def _get_solver(M, sparse=False, lstsq=False, sym_pos=True, + cholesky=True, permc_spec='MMD_AT_PLUS_A'): + """ + Given solver options, return a handle to the appropriate linear system + solver. + + Parameters + ---------- + M : 2-D array + As defined in [4] Equation 8.31 + sparse : bool (default = False) + True if the system to be solved is sparse. This is typically set + True when the original ``A_ub`` and ``A_eq`` arrays are sparse. + lstsq : bool (default = False) + True if the system is ill-conditioned and/or (nearly) singular and + thus a more robust least-squares solver is desired. This is sometimes + needed as the solution is approached. + sym_pos : bool (default = True) + True if the system matrix is symmetric positive definite + Sometimes this needs to be set false as the solution is approached, + even when the system should be symmetric positive definite, due to + numerical difficulties. + cholesky : bool (default = True) + True if the system is to be solved by Cholesky, rather than LU, + decomposition. This is typically faster unless the problem is very + small or prone to numerical difficulties. + permc_spec : str (default = 'MMD_AT_PLUS_A') + Sparsity preservation strategy used by SuperLU. Acceptable values are: + + - ``NATURAL``: natural ordering. + - ``MMD_ATA``: minimum degree ordering on the structure of A^T A. + - ``MMD_AT_PLUS_A``: minimum degree ordering on the structure of A^T+A. + - ``COLAMD``: approximate minimum degree column ordering. + + See SuperLU documentation. + + Returns + ------- + solve : function + Handle to the appropriate solver function + + """ + try: + if sparse: + if lstsq: + def solve(r, sym_pos=False): + return sps.linalg.lsqr(M, r)[0] + elif cholesky: + try: + # Will raise an exception in the first call, + # or when the matrix changes due to a new problem + _get_solver.cholmod_factor.cholesky_inplace(M) + except Exception: + _get_solver.cholmod_factor = cholmod_analyze(M) + _get_solver.cholmod_factor.cholesky_inplace(M) + solve = _get_solver.cholmod_factor + else: + if has_umfpack and sym_pos: + solve = sps.linalg.factorized(M) + else: # factorized doesn't pass permc_spec + solve = sps.linalg.splu(M, permc_spec=permc_spec).solve + + else: + if lstsq: # sometimes necessary as solution is approached + def solve(r): + return sp.linalg.lstsq(M, r)[0] + elif cholesky: + L = sp.linalg.cho_factor(M) + + def solve(r): + return sp.linalg.cho_solve(L, r) + else: + # this seems to cache the matrix factorization, so solving + # with multiple right hand sides is much faster + def solve(r, sym_pos=sym_pos): + if sym_pos: + return sp.linalg.solve(M, r, assume_a="pos") + else: + return sp.linalg.solve(M, r) + # There are many things that can go wrong here, and it's hard to say + # what all of them are. It doesn't really matter: if the matrix can't be + # factorized, return None. get_solver will be called again with different + # inputs, and a new routine will try to factorize the matrix. + except KeyboardInterrupt: + raise + except Exception: + return None + return solve + + +def _get_delta(A, b, c, x, y, z, tau, kappa, gamma, eta, sparse=False, + lstsq=False, sym_pos=True, cholesky=True, pc=True, ip=False, + permc_spec='MMD_AT_PLUS_A'): + """ + Given standard form problem defined by ``A``, ``b``, and ``c``; + current variable estimates ``x``, ``y``, ``z``, ``tau``, and ``kappa``; + algorithmic parameters ``gamma and ``eta; + and options ``sparse``, ``lstsq``, ``sym_pos``, ``cholesky``, ``pc`` + (predictor-corrector), and ``ip`` (initial point improvement), + get the search direction for increments to the variable estimates. + + Parameters + ---------- + As defined in [4], except: + sparse : bool + True if the system to be solved is sparse. This is typically set + True when the original ``A_ub`` and ``A_eq`` arrays are sparse. + lstsq : bool + True if the system is ill-conditioned and/or (nearly) singular and + thus a more robust least-squares solver is desired. This is sometimes + needed as the solution is approached. + sym_pos : bool + True if the system matrix is symmetric positive definite + Sometimes this needs to be set false as the solution is approached, + even when the system should be symmetric positive definite, due to + numerical difficulties. + cholesky : bool + True if the system is to be solved by Cholesky, rather than LU, + decomposition. This is typically faster unless the problem is very + small or prone to numerical difficulties. + pc : bool + True if the predictor-corrector method of Mehrota is to be used. This + is almost always (if not always) beneficial. Even though it requires + the solution of an additional linear system, the factorization + is typically (implicitly) reused so solution is efficient, and the + number of algorithm iterations is typically reduced. + ip : bool + True if the improved initial point suggestion due to [4] section 4.3 + is desired. It's unclear whether this is beneficial. + permc_spec : str (default = 'MMD_AT_PLUS_A') + (Has effect only with ``sparse = True``, ``lstsq = False``, ``sym_pos = + True``.) A matrix is factorized in each iteration of the algorithm. + This option specifies how to permute the columns of the matrix for + sparsity preservation. Acceptable values are: + + - ``NATURAL``: natural ordering. + - ``MMD_ATA``: minimum degree ordering on the structure of A^T A. + - ``MMD_AT_PLUS_A``: minimum degree ordering on the structure of A^T+A. + - ``COLAMD``: approximate minimum degree column ordering. + + This option can impact the convergence of the + interior point algorithm; test different values to determine which + performs best for your problem. For more information, refer to + ``scipy.sparse.linalg.splu``. + + Returns + ------- + Search directions as defined in [4] + + References + ---------- + .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point + optimizer for linear programming: an implementation of the + homogeneous algorithm." High performance optimization. Springer US, + 2000. 197-232. + + """ + if A.shape[0] == 0: + # If there are no constraints, some solvers fail (understandably) + # rather than returning empty solution. This gets the job done. + sparse, lstsq, sym_pos, cholesky = False, False, True, False + n_x = len(x) + + # [4] Equation 8.8 + r_P = b * tau - A.dot(x) + r_D = c * tau - A.T.dot(y) - z + r_G = c.dot(x) - b.transpose().dot(y) + kappa + mu = (x.dot(z) + tau * kappa) / (n_x + 1) + + # Assemble M from [4] Equation 8.31 + Dinv = x / z + + if sparse: + M = A.dot(sps.diags(Dinv, 0, format="csc").dot(A.T)) + else: + M = A.dot(Dinv.reshape(-1, 1) * A.T) + solve = _get_solver(M, sparse, lstsq, sym_pos, cholesky, permc_spec) + + # pc: "predictor-corrector" [4] Section 4.1 + # In development this option could be turned off + # but it always seems to improve performance substantially + n_corrections = 1 if pc else 0 + + i = 0 + alpha, d_x, d_z, d_tau, d_kappa = 0, 0, 0, 0, 0 + while i <= n_corrections: + # Reference [4] Eq. 8.6 + rhatp = eta(gamma) * r_P + rhatd = eta(gamma) * r_D + rhatg = eta(gamma) * r_G + + # Reference [4] Eq. 8.7 + rhatxs = gamma * mu - x * z + rhattk = gamma * mu - tau * kappa + + if i == 1: + if ip: # if the correction is to get "initial point" + # Reference [4] Eq. 8.23 + rhatxs = ((1 - alpha) * gamma * mu - + x * z - alpha**2 * d_x * d_z) + rhattk = ((1 - alpha) * gamma * mu - + tau * kappa - + alpha**2 * d_tau * d_kappa) + else: # if the correction is for "predictor-corrector" + # Reference [4] Eq. 8.13 + rhatxs -= d_x * d_z + rhattk -= d_tau * d_kappa + + # sometimes numerical difficulties arise as the solution is approached + # this loop tries to solve the equations using a sequence of functions + # for solve. For dense systems, the order is: + # 1. scipy.linalg.cho_factor/scipy.linalg.cho_solve, + # 2. scipy.linalg.solve w/ sym_pos = True, + # 3. scipy.linalg.solve w/ sym_pos = False, and if all else fails + # 4. scipy.linalg.lstsq + # For sparse systems, the order is: + # 1. sksparse.cholmod.cholesky (if available) + # 2. scipy.sparse.linalg.factorized (if umfpack available) + # 3. scipy.sparse.linalg.splu + # 4. scipy.sparse.linalg.lsqr + solved = False + while not solved: + try: + # [4] Equation 8.28 + p, q = _sym_solve(Dinv, A, c, b, solve) + # [4] Equation 8.29 + u, v = _sym_solve(Dinv, A, rhatd - + (1 / x) * rhatxs, rhatp, solve) + if np.any(np.isnan(p)) or np.any(np.isnan(q)): + raise LinAlgError + solved = True + except (LinAlgError, ValueError, TypeError) as e: + # Usually this doesn't happen. If it does, it happens when + # there are redundant constraints or when approaching the + # solution. If so, change solver. + if cholesky: + cholesky = False + warn( + "Solving system with option 'cholesky':True " + "failed. It is normal for this to happen " + "occasionally, especially as the solution is " + "approached. However, if you see this frequently, " + "consider setting option 'cholesky' to False.", + OptimizeWarning, stacklevel=5) + elif sym_pos: + sym_pos = False + warn( + "Solving system with option 'sym_pos':True " + "failed. It is normal for this to happen " + "occasionally, especially as the solution is " + "approached. However, if you see this frequently, " + "consider setting option 'sym_pos' to False.", + OptimizeWarning, stacklevel=5) + elif not lstsq: + lstsq = True + warn( + "Solving system with option 'sym_pos':False " + "failed. This may happen occasionally, " + "especially as the solution is " + "approached. However, if you see this frequently, " + "your problem may be numerically challenging. " + "If you cannot improve the formulation, consider " + "setting 'lstsq' to True. Consider also setting " + "`presolve` to True, if it is not already.", + OptimizeWarning, stacklevel=5) + else: + raise e + solve = _get_solver(M, sparse, lstsq, sym_pos, + cholesky, permc_spec) + # [4] Results after 8.29 + d_tau = ((rhatg + 1 / tau * rhattk - (-c.dot(u) + b.dot(v))) / + (1 / tau * kappa + (-c.dot(p) + b.dot(q)))) + d_x = u + p * d_tau + d_y = v + q * d_tau + + # [4] Relations between after 8.25 and 8.26 + d_z = (1 / x) * (rhatxs - z * d_x) + d_kappa = 1 / tau * (rhattk - kappa * d_tau) + + # [4] 8.12 and "Let alpha be the maximal possible step..." before 8.23 + alpha = _get_step(x, d_x, z, d_z, tau, d_tau, kappa, d_kappa, 1) + if ip: # initial point - see [4] 4.4 + gamma = 10 + else: # predictor-corrector, [4] definition after 8.12 + beta1 = 0.1 # [4] pg. 220 (Table 8.1) + gamma = (1 - alpha)**2 * min(beta1, (1 - alpha)) + i += 1 + + return d_x, d_y, d_z, d_tau, d_kappa + + +def _sym_solve(Dinv, A, r1, r2, solve): + """ + An implementation of [4] equation 8.31 and 8.32 + + References + ---------- + .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point + optimizer for linear programming: an implementation of the + homogeneous algorithm." High performance optimization. Springer US, + 2000. 197-232. + + """ + # [4] 8.31 + r = r2 + A.dot(Dinv * r1) + v = solve(r) + # [4] 8.32 + u = Dinv * (A.T.dot(v) - r1) + return u, v + + +def _get_step(x, d_x, z, d_z, tau, d_tau, kappa, d_kappa, alpha0): + """ + An implementation of [4] equation 8.21 + + References + ---------- + .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point + optimizer for linear programming: an implementation of the + homogeneous algorithm." High performance optimization. Springer US, + 2000. 197-232. + + """ + # [4] 4.3 Equation 8.21, ignoring 8.20 requirement + # same step is taken in primal and dual spaces + # alpha0 is basically beta3 from [4] Table 8.1, but instead of beta3 + # the value 1 is used in Mehrota corrector and initial point correction + i_x = d_x < 0 + i_z = d_z < 0 + alpha_x = alpha0 * np.min(x[i_x] / -d_x[i_x]) if np.any(i_x) else 1 + alpha_tau = alpha0 * tau / -d_tau if d_tau < 0 else 1 + alpha_z = alpha0 * np.min(z[i_z] / -d_z[i_z]) if np.any(i_z) else 1 + alpha_kappa = alpha0 * kappa / -d_kappa if d_kappa < 0 else 1 + alpha = np.min([1, alpha_x, alpha_tau, alpha_z, alpha_kappa]) + return alpha + + +def _get_message(status): + """ + Given problem status code, return a more detailed message. + + Parameters + ---------- + status : int + An integer representing the exit status of the optimization:: + + 0 : Optimization terminated successfully + 1 : Iteration limit reached + 2 : Problem appears to be infeasible + 3 : Problem appears to be unbounded + 4 : Serious numerical difficulties encountered + + Returns + ------- + message : str + A string descriptor of the exit status of the optimization. + + """ + messages = ( + ["Optimization terminated successfully.", + "The iteration limit was reached before the algorithm converged.", + "The algorithm terminated successfully and determined that the " + "problem is infeasible.", + "The algorithm terminated successfully and determined that the " + "problem is unbounded.", + "Numerical difficulties were encountered before the problem " + "converged. Please check your problem formulation for errors, " + "independence of linear equality constraints, and reasonable " + "scaling and matrix condition numbers. If you continue to " + "encounter this error, please submit a bug report." + ]) + return messages[status] + + +def _do_step(x, y, z, tau, kappa, d_x, d_y, d_z, d_tau, d_kappa, alpha): + """ + An implementation of [4] Equation 8.9 + + References + ---------- + .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point + optimizer for linear programming: an implementation of the + homogeneous algorithm." High performance optimization. Springer US, + 2000. 197-232. + + """ + x = x + alpha * d_x + tau = tau + alpha * d_tau + z = z + alpha * d_z + kappa = kappa + alpha * d_kappa + y = y + alpha * d_y + return x, y, z, tau, kappa + + +def _get_blind_start(shape): + """ + Return the starting point from [4] 4.4 + + References + ---------- + .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point + optimizer for linear programming: an implementation of the + homogeneous algorithm." High performance optimization. Springer US, + 2000. 197-232. + + """ + m, n = shape + x0 = np.ones(n) + y0 = np.zeros(m) + z0 = np.ones(n) + tau0 = 1 + kappa0 = 1 + return x0, y0, z0, tau0, kappa0 + + +def _indicators(A, b, c, c0, x, y, z, tau, kappa): + """ + Implementation of several equations from [4] used as indicators of + the status of optimization. + + References + ---------- + .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point + optimizer for linear programming: an implementation of the + homogeneous algorithm." High performance optimization. Springer US, + 2000. 197-232. + + """ + + # residuals for termination are relative to initial values + x0, y0, z0, tau0, kappa0 = _get_blind_start(A.shape) + + # See [4], Section 4 - The Homogeneous Algorithm, Equation 8.8 + def r_p(x, tau): + return b * tau - A.dot(x) + + def r_d(y, z, tau): + return c * tau - A.T.dot(y) - z + + def r_g(x, y, kappa): + return kappa + c.dot(x) - b.dot(y) + + # np.dot unpacks if they are arrays of size one + def mu(x, tau, z, kappa): + return (x.dot(z) + np.dot(tau, kappa)) / (len(x) + 1) + + obj = c.dot(x / tau) + c0 + + def norm(a): + return np.linalg.norm(a) + + # See [4], Section 4.5 - The Stopping Criteria + r_p0 = r_p(x0, tau0) + r_d0 = r_d(y0, z0, tau0) + r_g0 = r_g(x0, y0, kappa0) + mu_0 = mu(x0, tau0, z0, kappa0) + rho_A = norm(c.T.dot(x) - b.T.dot(y)) / (tau + norm(b.T.dot(y))) + rho_p = norm(r_p(x, tau)) / max(1, norm(r_p0)) + rho_d = norm(r_d(y, z, tau)) / max(1, norm(r_d0)) + rho_g = norm(r_g(x, y, kappa)) / max(1, norm(r_g0)) + rho_mu = mu(x, tau, z, kappa) / mu_0 + return rho_p, rho_d, rho_A, rho_g, rho_mu, obj + + +def _display_iter(rho_p, rho_d, rho_g, alpha, rho_mu, obj, header=False): + """ + Print indicators of optimization status to the console. + + Parameters + ---------- + rho_p : float + The (normalized) primal feasibility, see [4] 4.5 + rho_d : float + The (normalized) dual feasibility, see [4] 4.5 + rho_g : float + The (normalized) duality gap, see [4] 4.5 + alpha : float + The step size, see [4] 4.3 + rho_mu : float + The (normalized) path parameter, see [4] 4.5 + obj : float + The objective function value of the current iterate + header : bool + True if a header is to be printed + + References + ---------- + .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point + optimizer for linear programming: an implementation of the + homogeneous algorithm." High performance optimization. Springer US, + 2000. 197-232. + + """ + if header: + print("Primal Feasibility ", + "Dual Feasibility ", + "Duality Gap ", + "Step ", + "Path Parameter ", + "Objective ") + + # no clue why this works + fmt = '{0:<20.13}{1:<20.13}{2:<20.13}{3:<17.13}{4:<20.13}{5:<20.13}' + print(fmt.format( + float(rho_p), + float(rho_d), + float(rho_g), + alpha if isinstance(alpha, str) else float(alpha), + float(rho_mu), + float(obj))) + + +def _ip_hsd(A, b, c, c0, alpha0, beta, maxiter, disp, tol, sparse, lstsq, + sym_pos, cholesky, pc, ip, permc_spec, callback, postsolve_args): + r""" + Solve a linear programming problem in standard form: + + Minimize:: + + c @ x + + Subject to:: + + A @ x == b + x >= 0 + + using the interior point method of [4]. + + Parameters + ---------- + A : 2-D array + 2-D array such that ``A @ x``, gives the values of the equality + constraints at ``x``. + b : 1-D array + 1-D array of values representing the RHS of each equality constraint + (row) in ``A`` (for standard form problem). + c : 1-D array + Coefficients of the linear objective function to be minimized (for + standard form problem). + c0 : float + Constant term in objective function due to fixed (and eliminated) + variables. (Purely for display.) + alpha0 : float + The maximal step size for Mehrota's predictor-corrector search + direction; see :math:`\beta_3`of [4] Table 8.1 + beta : float + The desired reduction of the path parameter :math:`\mu` (see [6]_) + maxiter : int + The maximum number of iterations of the algorithm. + disp : bool + Set to ``True`` if indicators of optimization status are to be printed + to the console each iteration. + tol : float + Termination tolerance; see [4]_ Section 4.5. + sparse : bool + Set to ``True`` if the problem is to be treated as sparse. However, + the inputs ``A_eq`` and ``A_ub`` should nonetheless be provided as + (dense) arrays rather than sparse matrices. + lstsq : bool + Set to ``True`` if the problem is expected to be very poorly + conditioned. This should always be left as ``False`` unless severe + numerical difficulties are frequently encountered, and a better option + would be to improve the formulation of the problem. + sym_pos : bool + Leave ``True`` if the problem is expected to yield a well conditioned + symmetric positive definite normal equation matrix (almost always). + cholesky : bool + Set to ``True`` if the normal equations are to be solved by explicit + Cholesky decomposition followed by explicit forward/backward + substitution. This is typically faster for moderate, dense problems + that are numerically well-behaved. + pc : bool + Leave ``True`` if the predictor-corrector method of Mehrota is to be + used. This is almost always (if not always) beneficial. + ip : bool + Set to ``True`` if the improved initial point suggestion due to [4]_ + Section 4.3 is desired. It's unclear whether this is beneficial. + permc_spec : str (default = 'MMD_AT_PLUS_A') + (Has effect only with ``sparse = True``, ``lstsq = False``, ``sym_pos = + True``.) A matrix is factorized in each iteration of the algorithm. + This option specifies how to permute the columns of the matrix for + sparsity preservation. Acceptable values are: + + - ``NATURAL``: natural ordering. + - ``MMD_ATA``: minimum degree ordering on the structure of A^T A. + - ``MMD_AT_PLUS_A``: minimum degree ordering on the structure of A^T+A. + - ``COLAMD``: approximate minimum degree column ordering. + + This option can impact the convergence of the + interior point algorithm; test different values to determine which + performs best for your problem. For more information, refer to + ``scipy.sparse.linalg.splu``. + callback : callable, optional + If a callback function is provided, it will be called within each + iteration of the algorithm. The callback function must accept a single + `scipy.optimize.OptimizeResult` consisting of the following fields: + + x : 1-D array + Current solution vector + fun : float + Current value of the objective function + success : bool + True only when an algorithm has completed successfully, + so this is always False as the callback function is called + only while the algorithm is still iterating. + slack : 1-D array + The values of the slack variables. Each slack variable + corresponds to an inequality constraint. If the slack is zero, + the corresponding constraint is active. + con : 1-D array + The (nominally zero) residuals of the equality constraints, + that is, ``b - A_eq @ x`` + phase : int + The phase of the algorithm being executed. This is always + 1 for the interior-point method because it has only one phase. + status : int + For revised simplex, this is always 0 because if a different + status is detected, the algorithm terminates. + nit : int + The number of iterations performed. + message : str + A string descriptor of the exit status of the optimization. + postsolve_args : tuple + Data needed by _postsolve to convert the solution to the standard-form + problem into the solution to the original problem. + + Returns + ------- + x_hat : float + Solution vector (for standard form problem). + status : int + An integer representing the exit status of the optimization:: + + 0 : Optimization terminated successfully + 1 : Iteration limit reached + 2 : Problem appears to be infeasible + 3 : Problem appears to be unbounded + 4 : Serious numerical difficulties encountered + + message : str + A string descriptor of the exit status of the optimization. + iteration : int + The number of iterations taken to solve the problem + + References + ---------- + .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point + optimizer for linear programming: an implementation of the + homogeneous algorithm." High performance optimization. Springer US, + 2000. 197-232. + .. [6] Freund, Robert M. "Primal-Dual Interior-Point Methods for Linear + Programming based on Newton's Method." Unpublished Course Notes, + March 2004. Available 2/25/2017 at: + https://ocw.mit.edu/courses/sloan-school-of-management/15-084j-nonlinear-programming-spring-2004/lecture-notes/lec14_int_pt_mthd.pdf + + """ + + iteration = 0 + + # default initial point + x, y, z, tau, kappa = _get_blind_start(A.shape) + + # first iteration is special improvement of initial point + ip = ip if pc else False + + # [4] 4.5 + rho_p, rho_d, rho_A, rho_g, rho_mu, obj = _indicators( + A, b, c, c0, x, y, z, tau, kappa) + go = rho_p > tol or rho_d > tol or rho_A > tol # we might get lucky : ) + + if disp: + _display_iter(rho_p, rho_d, rho_g, "-", rho_mu, obj, header=True) + if callback is not None: + x_o, fun, slack, con = _postsolve(x/tau, postsolve_args) + res = OptimizeResult({'x': x_o, 'fun': fun, 'slack': slack, + 'con': con, 'nit': iteration, 'phase': 1, + 'complete': False, 'status': 0, + 'message': "", 'success': False}) + callback(res) + + status = 0 + message = "Optimization terminated successfully." + + if sparse: + A = sps.csc_matrix(A) + + while go: + + iteration += 1 + + if ip: # initial point + # [4] Section 4.4 + gamma = 1 + + def eta(g): + return 1 + else: + # gamma = 0 in predictor step according to [4] 4.1 + # if predictor/corrector is off, use mean of complementarity [6] + # 5.1 / [4] Below Figure 10-4 + gamma = 0 if pc else beta * np.mean(z * x) + # [4] Section 4.1 + + def eta(g=gamma): + return 1 - g + + try: + # Solve [4] 8.6 and 8.7/8.13/8.23 + d_x, d_y, d_z, d_tau, d_kappa = _get_delta( + A, b, c, x, y, z, tau, kappa, gamma, eta, + sparse, lstsq, sym_pos, cholesky, pc, ip, permc_spec) + + if ip: # initial point + # [4] 4.4 + # Formula after 8.23 takes a full step regardless if this will + # take it negative + alpha = 1.0 + x, y, z, tau, kappa = _do_step( + x, y, z, tau, kappa, d_x, d_y, + d_z, d_tau, d_kappa, alpha) + x[x < 1] = 1 + z[z < 1] = 1 + tau = max(1, tau) + kappa = max(1, kappa) + ip = False # done with initial point + else: + # [4] Section 4.3 + alpha = _get_step(x, d_x, z, d_z, tau, + d_tau, kappa, d_kappa, alpha0) + # [4] Equation 8.9 + x, y, z, tau, kappa = _do_step( + x, y, z, tau, kappa, d_x, d_y, d_z, d_tau, d_kappa, alpha) + + except (LinAlgError, FloatingPointError, + ValueError, ZeroDivisionError): + # this can happen when sparse solver is used and presolve + # is turned off. Also observed ValueError in AppVeyor Python 3.6 + # Win32 build (PR #8676). I've never seen it otherwise. + status = 4 + message = _get_message(status) + break + + # [4] 4.5 + rho_p, rho_d, rho_A, rho_g, rho_mu, obj = _indicators( + A, b, c, c0, x, y, z, tau, kappa) + go = rho_p > tol or rho_d > tol or rho_A > tol + + if disp: + _display_iter(rho_p, rho_d, rho_g, alpha, rho_mu, obj) + if callback is not None: + x_o, fun, slack, con = _postsolve(x/tau, postsolve_args) + res = OptimizeResult({'x': x_o, 'fun': fun, 'slack': slack, + 'con': con, 'nit': iteration, 'phase': 1, + 'complete': False, 'status': 0, + 'message': "", 'success': False}) + callback(res) + + # [4] 4.5 + inf1 = (rho_p < tol and rho_d < tol and rho_g < tol and tau < tol * + max(1, kappa)) + inf2 = rho_mu < tol and tau < tol * min(1, kappa) + if inf1 or inf2: + # [4] Lemma 8.4 / Theorem 8.3 + if b.transpose().dot(y) > tol: + status = 2 + else: # elif c.T.dot(x) < tol: ? Probably not necessary. + status = 3 + message = _get_message(status) + break + elif iteration >= maxiter: + status = 1 + message = _get_message(status) + break + + x_hat = x / tau + # [4] Statement after Theorem 8.2 + return x_hat, status, message, iteration + + +def _linprog_ip(c, c0, A, b, callback, postsolve_args, maxiter=1000, tol=1e-8, + disp=False, alpha0=.99995, beta=0.1, sparse=False, lstsq=False, + sym_pos=True, cholesky=None, pc=True, ip=False, + permc_spec='MMD_AT_PLUS_A', **unknown_options): + r""" + Minimize a linear objective function subject to linear + equality and non-negativity constraints using the interior point method + of [4]_. Linear programming is intended to solve problems + of the following form: + + Minimize:: + + c @ x + + Subject to:: + + A @ x == b + x >= 0 + + User-facing documentation is in _linprog_doc.py. + + Parameters + ---------- + c : 1-D array + Coefficients of the linear objective function to be minimized. + c0 : float + Constant term in objective function due to fixed (and eliminated) + variables. (Purely for display.) + A : 2-D array + 2-D array such that ``A @ x``, gives the values of the equality + constraints at ``x``. + b : 1-D array + 1-D array of values representing the right hand side of each equality + constraint (row) in ``A``. + callback : callable, optional + Callback function to be executed once per iteration. + postsolve_args : tuple + Data needed by _postsolve to convert the solution to the standard-form + problem into the solution to the original problem. + + Options + ------- + maxiter : int (default = 1000) + The maximum number of iterations of the algorithm. + tol : float (default = 1e-8) + Termination tolerance to be used for all termination criteria; + see [4]_ Section 4.5. + disp : bool (default = False) + Set to ``True`` if indicators of optimization status are to be printed + to the console each iteration. + alpha0 : float (default = 0.99995) + The maximal step size for Mehrota's predictor-corrector search + direction; see :math:`\beta_{3}` of [4]_ Table 8.1. + beta : float (default = 0.1) + The desired reduction of the path parameter :math:`\mu` (see [6]_) + when Mehrota's predictor-corrector is not in use (uncommon). + sparse : bool (default = False) + Set to ``True`` if the problem is to be treated as sparse after + presolve. If either ``A_eq`` or ``A_ub`` is a sparse matrix, + this option will automatically be set ``True``, and the problem + will be treated as sparse even during presolve. If your constraint + matrices contain mostly zeros and the problem is not very small (less + than about 100 constraints or variables), consider setting ``True`` + or providing ``A_eq`` and ``A_ub`` as sparse matrices. + lstsq : bool (default = False) + Set to ``True`` if the problem is expected to be very poorly + conditioned. This should always be left ``False`` unless severe + numerical difficulties are encountered. Leave this at the default + unless you receive a warning message suggesting otherwise. + sym_pos : bool (default = True) + Leave ``True`` if the problem is expected to yield a well conditioned + symmetric positive definite normal equation matrix + (almost always). Leave this at the default unless you receive + a warning message suggesting otherwise. + cholesky : bool (default = True) + Set to ``True`` if the normal equations are to be solved by explicit + Cholesky decomposition followed by explicit forward/backward + substitution. This is typically faster for problems + that are numerically well-behaved. + pc : bool (default = True) + Leave ``True`` if the predictor-corrector method of Mehrota is to be + used. This is almost always (if not always) beneficial. + ip : bool (default = False) + Set to ``True`` if the improved initial point suggestion due to [4]_ + Section 4.3 is desired. Whether this is beneficial or not + depends on the problem. + permc_spec : str (default = 'MMD_AT_PLUS_A') + (Has effect only with ``sparse = True``, ``lstsq = False``, ``sym_pos = + True``, and no SuiteSparse.) + A matrix is factorized in each iteration of the algorithm. + This option specifies how to permute the columns of the matrix for + sparsity preservation. Acceptable values are: + + - ``NATURAL``: natural ordering. + - ``MMD_ATA``: minimum degree ordering on the structure of A^T A. + - ``MMD_AT_PLUS_A``: minimum degree ordering on the structure of A^T+A. + - ``COLAMD``: approximate minimum degree column ordering. + + This option can impact the convergence of the + interior point algorithm; test different values to determine which + performs best for your problem. For more information, refer to + ``scipy.sparse.linalg.splu``. + unknown_options : dict + Optional arguments not used by this particular solver. If + `unknown_options` is non-empty a warning is issued listing all + unused options. + + Returns + ------- + x : 1-D array + Solution vector. + status : int + An integer representing the exit status of the optimization:: + + 0 : Optimization terminated successfully + 1 : Iteration limit reached + 2 : Problem appears to be infeasible + 3 : Problem appears to be unbounded + 4 : Serious numerical difficulties encountered + + message : str + A string descriptor of the exit status of the optimization. + iteration : int + The number of iterations taken to solve the problem. + + Notes + ----- + This method implements the algorithm outlined in [4]_ with ideas from [8]_ + and a structure inspired by the simpler methods of [6]_. + + The primal-dual path following method begins with initial 'guesses' of + the primal and dual variables of the standard form problem and iteratively + attempts to solve the (nonlinear) Karush-Kuhn-Tucker conditions for the + problem with a gradually reduced logarithmic barrier term added to the + objective. This particular implementation uses a homogeneous self-dual + formulation, which provides certificates of infeasibility or unboundedness + where applicable. + + The default initial point for the primal and dual variables is that + defined in [4]_ Section 4.4 Equation 8.22. Optionally (by setting initial + point option ``ip=True``), an alternate (potentially improved) starting + point can be calculated according to the additional recommendations of + [4]_ Section 4.4. + + A search direction is calculated using the predictor-corrector method + (single correction) proposed by Mehrota and detailed in [4]_ Section 4.1. + (A potential improvement would be to implement the method of multiple + corrections described in [4]_ Section 4.2.) In practice, this is + accomplished by solving the normal equations, [4]_ Section 5.1 Equations + 8.31 and 8.32, derived from the Newton equations [4]_ Section 5 Equations + 8.25 (compare to [4]_ Section 4 Equations 8.6-8.8). The advantage of + solving the normal equations rather than 8.25 directly is that the + matrices involved are symmetric positive definite, so Cholesky + decomposition can be used rather than the more expensive LU factorization. + + With default options, the solver used to perform the factorization depends + on third-party software availability and the conditioning of the problem. + + For dense problems, solvers are tried in the following order: + + 1. ``scipy.linalg.cho_factor`` + + 2. ``scipy.linalg.solve`` with option ``sym_pos=True`` + + 3. ``scipy.linalg.solve`` with option ``sym_pos=False`` + + 4. ``scipy.linalg.lstsq`` + + For sparse problems: + + 1. ``sksparse.cholmod.cholesky`` (if scikit-sparse and SuiteSparse are installed) + + 2. ``scipy.sparse.linalg.factorized`` + (if scikit-umfpack and SuiteSparse are installed) + + 3. ``scipy.sparse.linalg.splu`` (which uses SuperLU distributed with SciPy) + + 4. ``scipy.sparse.linalg.lsqr`` + + If the solver fails for any reason, successively more robust (but slower) + solvers are attempted in the order indicated. Attempting, failing, and + re-starting factorization can be time consuming, so if the problem is + numerically challenging, options can be set to bypass solvers that are + failing. Setting ``cholesky=False`` skips to solver 2, + ``sym_pos=False`` skips to solver 3, and ``lstsq=True`` skips + to solver 4 for both sparse and dense problems. + + Potential improvements for combating issues associated with dense + columns in otherwise sparse problems are outlined in [4]_ Section 5.3 and + [10]_ Section 4.1-4.2; the latter also discusses the alleviation of + accuracy issues associated with the substitution approach to free + variables. + + After calculating the search direction, the maximum possible step size + that does not activate the non-negativity constraints is calculated, and + the smaller of this step size and unity is applied (as in [4]_ Section + 4.1.) [4]_ Section 4.3 suggests improvements for choosing the step size. + + The new point is tested according to the termination conditions of [4]_ + Section 4.5. The same tolerance, which can be set using the ``tol`` option, + is used for all checks. (A potential improvement would be to expose + the different tolerances to be set independently.) If optimality, + unboundedness, or infeasibility is detected, the solve procedure + terminates; otherwise it repeats. + + The expected problem formulation differs between the top level ``linprog`` + module and the method specific solvers. The method specific solvers expect a + problem in standard form: + + Minimize:: + + c @ x + + Subject to:: + + A @ x == b + x >= 0 + + Whereas the top level ``linprog`` module expects a problem of form: + + Minimize:: + + c @ x + + Subject to:: + + A_ub @ x <= b_ub + A_eq @ x == b_eq + lb <= x <= ub + + where ``lb = 0`` and ``ub = None`` unless set in ``bounds``. + + The original problem contains equality, upper-bound and variable constraints + whereas the method specific solver requires equality constraints and + variable non-negativity. + + ``linprog`` module converts the original problem to standard form by + converting the simple bounds to upper bound constraints, introducing + non-negative slack variables for inequality constraints, and expressing + unbounded variables as the difference between two non-negative variables. + + + References + ---------- + .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point + optimizer for linear programming: an implementation of the + homogeneous algorithm." High performance optimization. Springer US, + 2000. 197-232. + .. [6] Freund, Robert M. "Primal-Dual Interior-Point Methods for Linear + Programming based on Newton's Method." Unpublished Course Notes, + March 2004. Available 2/25/2017 at + https://ocw.mit.edu/courses/sloan-school-of-management/15-084j-nonlinear-programming-spring-2004/lecture-notes/lec14_int_pt_mthd.pdf + .. [8] Andersen, Erling D., and Knud D. Andersen. "Presolving in linear + programming." Mathematical Programming 71.2 (1995): 221-245. + .. [9] Bertsimas, Dimitris, and J. Tsitsiklis. "Introduction to linear + programming." Athena Scientific 1 (1997): 997. + .. [10] Andersen, Erling D., et al. Implementation of interior point methods + for large scale linear programming. HEC/Universite de Geneve, 1996. + + """ + + _check_unknown_options(unknown_options) + + # These should be warnings, not errors + if (cholesky or cholesky is None) and sparse and not has_cholmod: + if cholesky: + warn("Sparse cholesky is only available with scikit-sparse. " + "Setting `cholesky = False`", + OptimizeWarning, stacklevel=3) + cholesky = False + + if sparse and lstsq: + warn("Option combination 'sparse':True and 'lstsq':True " + "is not recommended.", + OptimizeWarning, stacklevel=3) + + if lstsq and cholesky: + warn("Invalid option combination 'lstsq':True " + "and 'cholesky':True; option 'cholesky' has no effect when " + "'lstsq' is set True.", + OptimizeWarning, stacklevel=3) + + valid_permc_spec = ('NATURAL', 'MMD_ATA', 'MMD_AT_PLUS_A', 'COLAMD') + if permc_spec.upper() not in valid_permc_spec: + warn("Invalid permc_spec option: '" + str(permc_spec) + "'. " + "Acceptable values are 'NATURAL', 'MMD_ATA', 'MMD_AT_PLUS_A', " + "and 'COLAMD'. Reverting to default.", + OptimizeWarning, stacklevel=3) + permc_spec = 'MMD_AT_PLUS_A' + + # This can be an error + if not sym_pos and cholesky: + raise ValueError( + "Invalid option combination 'sym_pos':False " + "and 'cholesky':True: Cholesky decomposition is only possible " + "for symmetric positive definite matrices.") + + cholesky = cholesky or (cholesky is None and sym_pos and not lstsq) + + x, status, message, iteration = _ip_hsd(A, b, c, c0, alpha0, beta, + maxiter, disp, tol, sparse, + lstsq, sym_pos, cholesky, + pc, ip, permc_spec, callback, + postsolve_args) + + return x, status, message, iteration diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_linprog_rs.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_linprog_rs.py new file mode 100644 index 0000000000000000000000000000000000000000..43fed5805c4e40f0c38de91f053e3926cf1478e4 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_linprog_rs.py @@ -0,0 +1,572 @@ +"""Revised simplex method for linear programming + +The *revised simplex* method uses the method described in [1]_, except +that a factorization [2]_ of the basis matrix, rather than its inverse, +is efficiently maintained and used to solve the linear systems at each +iteration of the algorithm. + +.. versionadded:: 1.3.0 + +References +---------- +.. [1] Bertsimas, Dimitris, and J. Tsitsiklis. "Introduction to linear + programming." Athena Scientific 1 (1997): 997. +.. [2] Bartels, Richard H. "A stabilization of the simplex method." + Journal in Numerische Mathematik 16.5 (1971): 414-434. + +""" +# Author: Matt Haberland + +import numpy as np +from numpy.linalg import LinAlgError + +from scipy.linalg import solve +from ._optimize import _check_unknown_options +from ._bglu_dense import LU +from ._bglu_dense import BGLU as BGLU +from ._linprog_util import _postsolve +from ._optimize import OptimizeResult + + +def _phase_one(A, b, x0, callback, postsolve_args, maxiter, tol, disp, + maxupdate, mast, pivot): + """ + The purpose of phase one is to find an initial basic feasible solution + (BFS) to the original problem. + + Generates an auxiliary problem with a trivial BFS and an objective that + minimizes infeasibility of the original problem. Solves the auxiliary + problem using the main simplex routine (phase two). This either yields + a BFS to the original problem or determines that the original problem is + infeasible. If feasible, phase one detects redundant rows in the original + constraint matrix and removes them, then chooses additional indices as + necessary to complete a basis/BFS for the original problem. + """ + + m, n = A.shape + status = 0 + + # generate auxiliary problem to get initial BFS + A, b, c, basis, x, status = _generate_auxiliary_problem(A, b, x0, tol) + + if status == 6: + residual = c.dot(x) + iter_k = 0 + return x, basis, A, b, residual, status, iter_k + + # solve auxiliary problem + phase_one_n = n + iter_k = 0 + x, basis, status, iter_k = _phase_two(c, A, x, basis, callback, + postsolve_args, + maxiter, tol, disp, + maxupdate, mast, pivot, + iter_k, phase_one_n) + + # check for infeasibility + residual = c.dot(x) + if status == 0 and residual > tol: + status = 2 + + # drive artificial variables out of basis + # TODO: test redundant row removal better + # TODO: make solve more efficient with BGLU? This could take a while. + keep_rows = np.ones(m, dtype=bool) + for basis_column in basis[basis >= n]: + B = A[:, basis] + try: + basis_finder = np.abs(solve(B, A)) # inefficient + pertinent_row = np.argmax(basis_finder[:, basis_column]) + eligible_columns = np.ones(n, dtype=bool) + eligible_columns[basis[basis < n]] = 0 + eligible_column_indices = np.where(eligible_columns)[0] + index = np.argmax(basis_finder[:, :n] + [pertinent_row, eligible_columns]) + new_basis_column = eligible_column_indices[index] + if basis_finder[pertinent_row, new_basis_column] < tol: + keep_rows[pertinent_row] = False + else: + basis[basis == basis_column] = new_basis_column + except LinAlgError: + status = 4 + + # form solution to original problem + A = A[keep_rows, :n] + basis = basis[keep_rows] + x = x[:n] + m = A.shape[0] + return x, basis, A, b, residual, status, iter_k + + +def _get_more_basis_columns(A, basis): + """ + Called when the auxiliary problem terminates with artificial columns in + the basis, which must be removed and replaced with non-artificial + columns. Finds additional columns that do not make the matrix singular. + """ + m, n = A.shape + + # options for inclusion are those that aren't already in the basis + a = np.arange(m+n) + bl = np.zeros(len(a), dtype=bool) + bl[basis] = 1 + options = a[~bl] + options = options[options < n] # and they have to be non-artificial + + # form basis matrix + B = np.zeros((m, m)) + B[:, 0:len(basis)] = A[:, basis] + + if (basis.size > 0 and + np.linalg.matrix_rank(B[:, :len(basis)]) < len(basis)): + raise Exception("Basis has dependent columns") + + rank = 0 # just enter the loop + for i in range(n): # somewhat arbitrary, but we need another way out + # permute the options, and take as many as needed + new_basis = np.random.permutation(options)[:m-len(basis)] + B[:, len(basis):] = A[:, new_basis] # update the basis matrix + rank = np.linalg.matrix_rank(B) # check the rank + if rank == m: + break + + return np.concatenate((basis, new_basis)) + + +def _generate_auxiliary_problem(A, b, x0, tol): + """ + Modifies original problem to create an auxiliary problem with a trivial + initial basic feasible solution and an objective that minimizes + infeasibility in the original problem. + + Conceptually, this is done by stacking an identity matrix on the right of + the original constraint matrix, adding artificial variables to correspond + with each of these new columns, and generating a cost vector that is all + zeros except for ones corresponding with each of the new variables. + + A initial basic feasible solution is trivial: all variables are zero + except for the artificial variables, which are set equal to the + corresponding element of the right hand side `b`. + + Running the simplex method on this auxiliary problem drives all of the + artificial variables - and thus the cost - to zero if the original problem + is feasible. The original problem is declared infeasible otherwise. + + Much of the complexity below is to improve efficiency by using singleton + columns in the original problem where possible, thus generating artificial + variables only as necessary, and using an initial 'guess' basic feasible + solution. + """ + status = 0 + m, n = A.shape + + if x0 is not None: + x = x0 + else: + x = np.zeros(n) + + r = b - A@x # residual; this must be all zeros for feasibility + + A[r < 0] = -A[r < 0] # express problem with RHS positive for trivial BFS + b[r < 0] = -b[r < 0] # to the auxiliary problem + r[r < 0] *= -1 + + # Rows which we will need to find a trivial way to zero. + # This should just be the rows where there is a nonzero residual. + # But then we would not necessarily have a column singleton in every row. + # This makes it difficult to find an initial basis. + if x0 is None: + nonzero_constraints = np.arange(m) + else: + nonzero_constraints = np.where(r > tol)[0] + + # these are (at least some of) the initial basis columns + basis = np.where(np.abs(x) > tol)[0] + + if len(nonzero_constraints) == 0 and len(basis) <= m: # already a BFS + c = np.zeros(n) + basis = _get_more_basis_columns(A, basis) + return A, b, c, basis, x, status + elif (len(nonzero_constraints) > m - len(basis) or + np.any(x < 0)): # can't get trivial BFS + c = np.zeros(n) + status = 6 + return A, b, c, basis, x, status + + # chooses existing columns appropriate for inclusion in initial basis + cols, rows = _select_singleton_columns(A, r) + + # find the rows we need to zero that we _can_ zero with column singletons + i_tofix = np.isin(rows, nonzero_constraints) + # these columns can't already be in the basis, though + # we are going to add them to the basis and change the corresponding x val + i_notinbasis = np.logical_not(np.isin(cols, basis)) + i_fix_without_aux = np.logical_and(i_tofix, i_notinbasis) + rows = rows[i_fix_without_aux] + cols = cols[i_fix_without_aux] + + # indices of the rows we can only zero with auxiliary variable + # these rows will get a one in each auxiliary column + arows = nonzero_constraints[np.logical_not( + np.isin(nonzero_constraints, rows))] + n_aux = len(arows) + acols = n + np.arange(n_aux) # indices of auxiliary columns + + basis_ng = np.concatenate((cols, acols)) # basis columns not from guess + basis_ng_rows = np.concatenate((rows, arows)) # rows we need to zero + + # add auxiliary singleton columns + A = np.hstack((A, np.zeros((m, n_aux)))) + A[arows, acols] = 1 + + # generate initial BFS + x = np.concatenate((x, np.zeros(n_aux))) + x[basis_ng] = r[basis_ng_rows]/A[basis_ng_rows, basis_ng] + + # generate costs to minimize infeasibility + c = np.zeros(n_aux + n) + c[acols] = 1 + + # basis columns correspond with nonzeros in guess, those with column + # singletons we used to zero remaining constraints, and any additional + # columns to get a full set (m columns) + basis = np.concatenate((basis, basis_ng)) + basis = _get_more_basis_columns(A, basis) # add columns as needed + + return A, b, c, basis, x, status + + +def _select_singleton_columns(A, b): + """ + Finds singleton columns for which the singleton entry is of the same sign + as the right-hand side; these columns are eligible for inclusion in an + initial basis. Determines the rows in which the singleton entries are + located. For each of these rows, returns the indices of the one singleton + column and its corresponding row. + """ + # find indices of all singleton columns and corresponding row indices + column_indices = np.nonzero(np.sum(np.abs(A) != 0, axis=0) == 1)[0] + columns = A[:, column_indices] # array of singleton columns + row_indices = np.zeros(len(column_indices), dtype=int) + nonzero_rows, nonzero_columns = np.nonzero(columns) + row_indices[nonzero_columns] = nonzero_rows # corresponding row indices + + # keep only singletons with entries that have same sign as RHS + # this is necessary because all elements of BFS must be non-negative + same_sign = A[row_indices, column_indices]*b[row_indices] >= 0 + column_indices = column_indices[same_sign][::-1] + row_indices = row_indices[same_sign][::-1] + # Reversing the order so that steps below select rightmost columns + # for initial basis, which will tend to be slack variables. (If the + # guess corresponds with a basic feasible solution but a constraint + # is not satisfied with the corresponding slack variable zero, the slack + # variable must be basic.) + + # for each row, keep rightmost singleton column with an entry in that row + unique_row_indices, first_columns = np.unique(row_indices, + return_index=True) + return column_indices[first_columns], unique_row_indices + + +def _find_nonzero_rows(A, tol): + """ + Returns logical array indicating the locations of rows with at least + one nonzero element. + """ + return np.any(np.abs(A) > tol, axis=1) + + +def _select_enter_pivot(c_hat, bl, a, rule="bland", tol=1e-12): + """ + Selects a pivot to enter the basis. Currently Bland's rule - the smallest + index that has a negative reduced cost - is the default. + """ + if rule.lower() == "mrc": # index with minimum reduced cost + return a[~bl][np.argmin(c_hat)] + else: # smallest index w/ negative reduced cost + return a[~bl][c_hat < -tol][0] + + +def _display_iter(phase, iteration, slack, con, fun): + """ + Print indicators of optimization status to the console. + """ + header = True if not iteration % 20 else False + + if header: + print("Phase", + "Iteration", + "Minimum Slack ", + "Constraint Residual", + "Objective ") + + # := -tol): # all reduced costs positive -> terminate + break + + j = _select_enter_pivot(c_hat, bl, a, rule=pivot, tol=tol) + u = B.solve(A[:, j]) # similar to u = solve(B, A[:, j]) + + i = u > tol # if none of the u are positive, unbounded + if not np.any(i): + status = 3 + break + + th = xb[i]/u[i] + l = np.argmin(th) # implicitly selects smallest subscript + th_star = th[l] # step size + + x[b] = x[b] - th_star*u # take step + x[j] = th_star + B.update(ab[i][l], j) # modify basis + b = B.b # similar to b[ab[i][l]] = + + else: + # If the end of the for loop is reached (without a break statement), + # then another step has been taken, so the iteration counter should + # increment, info should be displayed, and callback should be called. + iteration += 1 + status = 1 + if disp or callback is not None: + _display_and_callback(phase_one_n, x, postsolve_args, status, + iteration, disp, callback) + + return x, b, status, iteration + + +def _linprog_rs(c, c0, A, b, x0, callback, postsolve_args, + maxiter=5000, tol=1e-12, disp=False, + maxupdate=10, mast=False, pivot="mrc", + **unknown_options): + """ + Solve the following linear programming problem via a two-phase + revised simplex algorithm.:: + + minimize: c @ x + + subject to: A @ x == b + 0 <= x < oo + + User-facing documentation is in _linprog_doc.py. + + Parameters + ---------- + c : 1-D array + Coefficients of the linear objective function to be minimized. + c0 : float + Constant term in objective function due to fixed (and eliminated) + variables. (Currently unused.) + A : 2-D array + 2-D array which, when matrix-multiplied by ``x``, gives the values of + the equality constraints at ``x``. + b : 1-D array + 1-D array of values representing the RHS of each equality constraint + (row) in ``A_eq``. + x0 : 1-D array, optional + Starting values of the independent variables, which will be refined by + the optimization algorithm. For the revised simplex method, these must + correspond with a basic feasible solution. + callback : callable, optional + If a callback function is provided, it will be called within each + iteration of the algorithm. The callback function must accept a single + `scipy.optimize.OptimizeResult` consisting of the following fields: + + x : 1-D array + Current solution vector. + fun : float + Current value of the objective function ``c @ x``. + success : bool + True only when an algorithm has completed successfully, + so this is always False as the callback function is called + only while the algorithm is still iterating. + slack : 1-D array + The values of the slack variables. Each slack variable + corresponds to an inequality constraint. If the slack is zero, + the corresponding constraint is active. + con : 1-D array + The (nominally zero) residuals of the equality constraints, + that is, ``b - A_eq @ x``. + phase : int + The phase of the algorithm being executed. + status : int + For revised simplex, this is always 0 because if a different + status is detected, the algorithm terminates. + nit : int + The number of iterations performed. + message : str + A string descriptor of the exit status of the optimization. + postsolve_args : tuple + Data needed by _postsolve to convert the solution to the standard-form + problem into the solution to the original problem. + + Options + ------- + maxiter : int + The maximum number of iterations to perform in either phase. + tol : float + The tolerance which determines when a solution is "close enough" to + zero in Phase 1 to be considered a basic feasible solution or close + enough to positive to serve as an optimal solution. + disp : bool + Set to ``True`` if indicators of optimization status are to be printed + to the console each iteration. + maxupdate : int + The maximum number of updates performed on the LU factorization. + After this many updates is reached, the basis matrix is factorized + from scratch. + mast : bool + Minimize Amortized Solve Time. If enabled, the average time to solve + a linear system using the basis factorization is measured. Typically, + the average solve time will decrease with each successive solve after + initial factorization, as factorization takes much more time than the + solve operation (and updates). Eventually, however, the updated + factorization becomes sufficiently complex that the average solve time + begins to increase. When this is detected, the basis is refactorized + from scratch. Enable this option to maximize speed at the risk of + nondeterministic behavior. Ignored if ``maxupdate`` is 0. + pivot : "mrc" or "bland" + Pivot rule: Minimum Reduced Cost (default) or Bland's rule. Choose + Bland's rule if iteration limit is reached and cycling is suspected. + unknown_options : dict + Optional arguments not used by this particular solver. If + `unknown_options` is non-empty a warning is issued listing all + unused options. + + Returns + ------- + x : 1-D array + Solution vector. + status : int + An integer representing the exit status of the optimization:: + + 0 : Optimization terminated successfully + 1 : Iteration limit reached + 2 : Problem appears to be infeasible + 3 : Problem appears to be unbounded + 4 : Numerical difficulties encountered + 5 : No constraints; turn presolve on + 6 : Guess x0 cannot be converted to a basic feasible solution + + message : str + A string descriptor of the exit status of the optimization. + iteration : int + The number of iterations taken to solve the problem. + """ + + _check_unknown_options(unknown_options) + + messages = ["Optimization terminated successfully.", + "Iteration limit reached.", + "The problem appears infeasible, as the phase one auxiliary " + "problem terminated successfully with a residual of {0:.1e}, " + "greater than the tolerance {1} required for the solution to " + "be considered feasible. Consider increasing the tolerance to " + "be greater than {0:.1e}. If this tolerance is unacceptably " + "large, the problem is likely infeasible.", + "The problem is unbounded, as the simplex algorithm found " + "a basic feasible solution from which there is a direction " + "with negative reduced cost in which all decision variables " + "increase.", + "Numerical difficulties encountered; consider trying " + "method='interior-point'.", + "Problems with no constraints are trivially solved; please " + "turn presolve on.", + "The guess x0 cannot be converted to a basic feasible " + "solution. " + ] + + if A.size == 0: # address test_unbounded_below_no_presolve_corrected + return np.zeros(c.shape), 5, messages[5], 0 + + x, basis, A, b, residual, status, iteration = ( + _phase_one(A, b, x0, callback, postsolve_args, + maxiter, tol, disp, maxupdate, mast, pivot)) + + if status == 0: + x, basis, status, iteration = _phase_two(c, A, x, basis, callback, + postsolve_args, + maxiter, tol, disp, + maxupdate, mast, pivot, + iteration) + + return x, status, messages[status].format(residual, tol), iteration diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_linprog_simplex.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_linprog_simplex.py new file mode 100644 index 0000000000000000000000000000000000000000..c47806c9a595f756b9f86d268c5c146ea86c77c6 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_linprog_simplex.py @@ -0,0 +1,663 @@ +"""Simplex method for linear programming + +The *simplex* method uses a traditional, full-tableau implementation of +Dantzig's simplex algorithm [1]_, [2]_ (*not* the Nelder-Mead simplex). +This algorithm is included for backwards compatibility and educational +purposes. + + .. versionadded:: 0.15.0 + +Warnings +-------- + +The simplex method may encounter numerical difficulties when pivot +values are close to the specified tolerance. If encountered try +remove any redundant constraints, change the pivot strategy to Bland's +rule or increase the tolerance value. + +Alternatively, more robust methods maybe be used. See +:ref:`'interior-point' ` and +:ref:`'revised simplex' `. + +References +---------- +.. [1] Dantzig, George B., Linear programming and extensions. Rand + Corporation Research Study Princeton Univ. Press, Princeton, NJ, + 1963 +.. [2] Hillier, S.H. and Lieberman, G.J. (1995), "Introduction to + Mathematical Programming", McGraw-Hill, Chapter 4. +""" + +import numpy as np +from warnings import warn +from ._optimize import OptimizeResult, OptimizeWarning, _check_unknown_options +from ._linprog_util import _postsolve + + +def _pivot_col(T, tol=1e-9, bland=False): + """ + Given a linear programming simplex tableau, determine the column + of the variable to enter the basis. + + Parameters + ---------- + T : 2-D array + A 2-D array representing the simplex tableau, T, corresponding to the + linear programming problem. It should have the form: + + [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]], + [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]], + . + . + . + [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]], + [c[0], c[1], ..., c[n_total], 0]] + + for a Phase 2 problem, or the form: + + [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]], + [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]], + . + . + . + [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]], + [c[0], c[1], ..., c[n_total], 0], + [c'[0], c'[1], ..., c'[n_total], 0]] + + for a Phase 1 problem (a problem in which a basic feasible solution is + sought prior to maximizing the actual objective. ``T`` is modified in + place by ``_solve_simplex``. + tol : float + Elements in the objective row larger than -tol will not be considered + for pivoting. Nominally this value is zero, but numerical issues + cause a tolerance about zero to be necessary. + bland : bool + If True, use Bland's rule for selection of the column (select the + first column with a negative coefficient in the objective row, + regardless of magnitude). + + Returns + ------- + status: bool + True if a suitable pivot column was found, otherwise False. + A return of False indicates that the linear programming simplex + algorithm is complete. + col: int + The index of the column of the pivot element. + If status is False, col will be returned as nan. + """ + ma = np.ma.masked_where(T[-1, :-1] >= -tol, T[-1, :-1], copy=False) + if ma.count() == 0: + return False, np.nan + if bland: + # ma.mask is sometimes 0d + return True, np.nonzero(np.logical_not(np.atleast_1d(ma.mask)))[0][0] + return True, np.ma.nonzero(ma == ma.min())[0][0] + + +def _pivot_row(T, basis, pivcol, phase, tol=1e-9, bland=False): + """ + Given a linear programming simplex tableau, determine the row for the + pivot operation. + + Parameters + ---------- + T : 2-D array + A 2-D array representing the simplex tableau, T, corresponding to the + linear programming problem. It should have the form: + + [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]], + [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]], + . + . + . + [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]], + [c[0], c[1], ..., c[n_total], 0]] + + for a Phase 2 problem, or the form: + + [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]], + [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]], + . + . + . + [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]], + [c[0], c[1], ..., c[n_total], 0], + [c'[0], c'[1], ..., c'[n_total], 0]] + + for a Phase 1 problem (a Problem in which a basic feasible solution is + sought prior to maximizing the actual objective. ``T`` is modified in + place by ``_solve_simplex``. + basis : array + A list of the current basic variables. + pivcol : int + The index of the pivot column. + phase : int + The phase of the simplex algorithm (1 or 2). + tol : float + Elements in the pivot column smaller than tol will not be considered + for pivoting. Nominally this value is zero, but numerical issues + cause a tolerance about zero to be necessary. + bland : bool + If True, use Bland's rule for selection of the row (if more than one + row can be used, choose the one with the lowest variable index). + + Returns + ------- + status: bool + True if a suitable pivot row was found, otherwise False. A return + of False indicates that the linear programming problem is unbounded. + row: int + The index of the row of the pivot element. If status is False, row + will be returned as nan. + """ + if phase == 1: + k = 2 + else: + k = 1 + ma = np.ma.masked_where(T[:-k, pivcol] <= tol, T[:-k, pivcol], copy=False) + if ma.count() == 0: + return False, np.nan + mb = np.ma.masked_where(T[:-k, pivcol] <= tol, T[:-k, -1], copy=False) + q = mb / ma + min_rows = np.ma.nonzero(q == q.min())[0] + if bland: + return True, min_rows[np.argmin(np.take(basis, min_rows))] + return True, min_rows[0] + + +def _apply_pivot(T, basis, pivrow, pivcol, tol=1e-9): + """ + Pivot the simplex tableau inplace on the element given by (pivrow, pivol). + The entering variable corresponds to the column given by pivcol forcing + the variable basis[pivrow] to leave the basis. + + Parameters + ---------- + T : 2-D array + A 2-D array representing the simplex tableau, T, corresponding to the + linear programming problem. It should have the form: + + [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]], + [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]], + . + . + . + [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]], + [c[0], c[1], ..., c[n_total], 0]] + + for a Phase 2 problem, or the form: + + [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]], + [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]], + . + . + . + [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]], + [c[0], c[1], ..., c[n_total], 0], + [c'[0], c'[1], ..., c'[n_total], 0]] + + for a Phase 1 problem (a problem in which a basic feasible solution is + sought prior to maximizing the actual objective. ``T`` is modified in + place by ``_solve_simplex``. + basis : 1-D array + An array of the indices of the basic variables, such that basis[i] + contains the column corresponding to the basic variable for row i. + Basis is modified in place by _apply_pivot. + pivrow : int + Row index of the pivot. + pivcol : int + Column index of the pivot. + """ + basis[pivrow] = pivcol + pivval = T[pivrow, pivcol] + T[pivrow] = T[pivrow] / pivval + for irow in range(T.shape[0]): + if irow != pivrow: + T[irow] = T[irow] - T[pivrow] * T[irow, pivcol] + + # The selected pivot should never lead to a pivot value less than the tol. + if np.isclose(pivval, tol, atol=0, rtol=1e4): + message = ( + f"The pivot operation produces a pivot value of:{pivval: .1e}, " + "which is only slightly greater than the specified " + f"tolerance{tol: .1e}. This may lead to issues regarding the " + "numerical stability of the simplex method. " + "Removing redundant constraints, changing the pivot strategy " + "via Bland's rule or increasing the tolerance may " + "help reduce the issue.") + warn(message, OptimizeWarning, stacklevel=5) + + +def _solve_simplex(T, n, basis, callback, postsolve_args, + maxiter=1000, tol=1e-9, phase=2, bland=False, nit0=0, + ): + """ + Solve a linear programming problem in "standard form" using the Simplex + Method. Linear Programming is intended to solve the following problem form: + + Minimize:: + + c @ x + + Subject to:: + + A @ x == b + x >= 0 + + Parameters + ---------- + T : 2-D array + A 2-D array representing the simplex tableau, T, corresponding to the + linear programming problem. It should have the form: + + [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]], + [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]], + . + . + . + [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]], + [c[0], c[1], ..., c[n_total], 0]] + + for a Phase 2 problem, or the form: + + [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]], + [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]], + . + . + . + [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]], + [c[0], c[1], ..., c[n_total], 0], + [c'[0], c'[1], ..., c'[n_total], 0]] + + for a Phase 1 problem (a problem in which a basic feasible solution is + sought prior to maximizing the actual objective. ``T`` is modified in + place by ``_solve_simplex``. + n : int + The number of true variables in the problem. + basis : 1-D array + An array of the indices of the basic variables, such that basis[i] + contains the column corresponding to the basic variable for row i. + Basis is modified in place by _solve_simplex + callback : callable, optional + If a callback function is provided, it will be called within each + iteration of the algorithm. The callback must accept a + `scipy.optimize.OptimizeResult` consisting of the following fields: + + x : 1-D array + Current solution vector + fun : float + Current value of the objective function + success : bool + True only when a phase has completed successfully. This + will be False for most iterations. + slack : 1-D array + The values of the slack variables. Each slack variable + corresponds to an inequality constraint. If the slack is zero, + the corresponding constraint is active. + con : 1-D array + The (nominally zero) residuals of the equality constraints, + that is, ``b - A_eq @ x`` + phase : int + The phase of the optimization being executed. In phase 1 a basic + feasible solution is sought and the T has an additional row + representing an alternate objective function. + status : int + An integer representing the exit status of the optimization:: + + 0 : Optimization terminated successfully + 1 : Iteration limit reached + 2 : Problem appears to be infeasible + 3 : Problem appears to be unbounded + 4 : Serious numerical difficulties encountered + + nit : int + The number of iterations performed. + message : str + A string descriptor of the exit status of the optimization. + postsolve_args : tuple + Data needed by _postsolve to convert the solution to the standard-form + problem into the solution to the original problem. + maxiter : int + The maximum number of iterations to perform before aborting the + optimization. + tol : float + The tolerance which determines when a solution is "close enough" to + zero in Phase 1 to be considered a basic feasible solution or close + enough to positive to serve as an optimal solution. + phase : int + The phase of the optimization being executed. In phase 1 a basic + feasible solution is sought and the T has an additional row + representing an alternate objective function. + bland : bool + If True, choose pivots using Bland's rule [3]_. In problems which + fail to converge due to cycling, using Bland's rule can provide + convergence at the expense of a less optimal path about the simplex. + nit0 : int + The initial iteration number used to keep an accurate iteration total + in a two-phase problem. + + Returns + ------- + nit : int + The number of iterations. Used to keep an accurate iteration total + in the two-phase problem. + status : int + An integer representing the exit status of the optimization:: + + 0 : Optimization terminated successfully + 1 : Iteration limit reached + 2 : Problem appears to be infeasible + 3 : Problem appears to be unbounded + 4 : Serious numerical difficulties encountered + + """ + nit = nit0 + status = 0 + message = '' + complete = False + + if phase == 1: + m = T.shape[1]-2 + elif phase == 2: + m = T.shape[1]-1 + else: + raise ValueError("Argument 'phase' to _solve_simplex must be 1 or 2") + + if phase == 2: + # Check if any artificial variables are still in the basis. + # If yes, check if any coefficients from this row and a column + # corresponding to one of the non-artificial variable is non-zero. + # If found, pivot at this term. If not, start phase 2. + # Do this for all artificial variables in the basis. + # Ref: "An Introduction to Linear Programming and Game Theory" + # by Paul R. Thie, Gerard E. Keough, 3rd Ed, + # Chapter 3.7 Redundant Systems (pag 102) + for pivrow in [row for row in range(basis.size) + if basis[row] > T.shape[1] - 2]: + non_zero_row = [col for col in range(T.shape[1] - 1) + if abs(T[pivrow, col]) > tol] + if len(non_zero_row) > 0: + pivcol = non_zero_row[0] + _apply_pivot(T, basis, pivrow, pivcol, tol) + nit += 1 + + if len(basis[:m]) == 0: + solution = np.empty(T.shape[1] - 1, dtype=np.float64) + else: + solution = np.empty(max(T.shape[1] - 1, max(basis[:m]) + 1), + dtype=np.float64) + + while not complete: + # Find the pivot column + pivcol_found, pivcol = _pivot_col(T, tol, bland) + if not pivcol_found: + pivcol = np.nan + pivrow = np.nan + status = 0 + complete = True + else: + # Find the pivot row + pivrow_found, pivrow = _pivot_row(T, basis, pivcol, phase, tol, bland) + if not pivrow_found: + status = 3 + complete = True + + if callback is not None: + solution[:] = 0 + solution[basis[:n]] = T[:n, -1] + x = solution[:m] + x, fun, slack, con = _postsolve( + x, postsolve_args + ) + res = OptimizeResult({ + 'x': x, + 'fun': fun, + 'slack': slack, + 'con': con, + 'status': status, + 'message': message, + 'nit': nit, + 'success': status == 0 and complete, + 'phase': phase, + 'complete': complete, + }) + callback(res) + + if not complete: + if nit >= maxiter: + # Iteration limit exceeded + status = 1 + complete = True + else: + _apply_pivot(T, basis, pivrow, pivcol, tol) + nit += 1 + return nit, status + + +def _linprog_simplex(c, c0, A, b, callback, postsolve_args, + maxiter=1000, tol=1e-9, disp=False, bland=False, + **unknown_options): + """ + Minimize a linear objective function subject to linear equality and + non-negativity constraints using the two phase simplex method. + Linear programming is intended to solve problems of the following form: + + Minimize:: + + c @ x + + Subject to:: + + A @ x == b + x >= 0 + + User-facing documentation is in _linprog_doc.py. + + Parameters + ---------- + c : 1-D array + Coefficients of the linear objective function to be minimized. + c0 : float + Constant term in objective function due to fixed (and eliminated) + variables. (Purely for display.) + A : 2-D array + 2-D array such that ``A @ x``, gives the values of the equality + constraints at ``x``. + b : 1-D array + 1-D array of values representing the right hand side of each equality + constraint (row) in ``A``. + callback : callable, optional + If a callback function is provided, it will be called within each + iteration of the algorithm. The callback function must accept a single + `scipy.optimize.OptimizeResult` consisting of the following fields: + + x : 1-D array + Current solution vector + fun : float + Current value of the objective function + success : bool + True when an algorithm has completed successfully. + slack : 1-D array + The values of the slack variables. Each slack variable + corresponds to an inequality constraint. If the slack is zero, + the corresponding constraint is active. + con : 1-D array + The (nominally zero) residuals of the equality constraints, + that is, ``b - A_eq @ x`` + phase : int + The phase of the algorithm being executed. + status : int + An integer representing the status of the optimization:: + + 0 : Algorithm proceeding nominally + 1 : Iteration limit reached + 2 : Problem appears to be infeasible + 3 : Problem appears to be unbounded + 4 : Serious numerical difficulties encountered + nit : int + The number of iterations performed. + message : str + A string descriptor of the exit status of the optimization. + postsolve_args : tuple + Data needed by _postsolve to convert the solution to the standard-form + problem into the solution to the original problem. + + Options + ------- + maxiter : int + The maximum number of iterations to perform. + disp : bool + If True, print exit status message to sys.stdout + tol : float + The tolerance which determines when a solution is "close enough" to + zero in Phase 1 to be considered a basic feasible solution or close + enough to positive to serve as an optimal solution. + bland : bool + If True, use Bland's anti-cycling rule [3]_ to choose pivots to + prevent cycling. If False, choose pivots which should lead to a + converged solution more quickly. The latter method is subject to + cycling (non-convergence) in rare instances. + unknown_options : dict + Optional arguments not used by this particular solver. If + `unknown_options` is non-empty a warning is issued listing all + unused options. + + Returns + ------- + x : 1-D array + Solution vector. + status : int + An integer representing the exit status of the optimization:: + + 0 : Optimization terminated successfully + 1 : Iteration limit reached + 2 : Problem appears to be infeasible + 3 : Problem appears to be unbounded + 4 : Serious numerical difficulties encountered + + message : str + A string descriptor of the exit status of the optimization. + iteration : int + The number of iterations taken to solve the problem. + + References + ---------- + .. [1] Dantzig, George B., Linear programming and extensions. Rand + Corporation Research Study Princeton Univ. Press, Princeton, NJ, + 1963 + .. [2] Hillier, S.H. and Lieberman, G.J. (1995), "Introduction to + Mathematical Programming", McGraw-Hill, Chapter 4. + .. [3] Bland, Robert G. New finite pivoting rules for the simplex method. + Mathematics of Operations Research (2), 1977: pp. 103-107. + + + Notes + ----- + The expected problem formulation differs between the top level ``linprog`` + module and the method specific solvers. The method specific solvers expect a + problem in standard form: + + Minimize:: + + c @ x + + Subject to:: + + A @ x == b + x >= 0 + + Whereas the top level ``linprog`` module expects a problem of form: + + Minimize:: + + c @ x + + Subject to:: + + A_ub @ x <= b_ub + A_eq @ x == b_eq + lb <= x <= ub + + where ``lb = 0`` and ``ub = None`` unless set in ``bounds``. + + The original problem contains equality, upper-bound and variable constraints + whereas the method specific solver requires equality constraints and + variable non-negativity. + + ``linprog`` module converts the original problem to standard form by + converting the simple bounds to upper bound constraints, introducing + non-negative slack variables for inequality constraints, and expressing + unbounded variables as the difference between two non-negative variables. + """ + _check_unknown_options(unknown_options) + + status = 0 + messages = {0: "Optimization terminated successfully.", + 1: "Iteration limit reached.", + 2: "Optimization failed. Unable to find a feasible" + " starting point.", + 3: "Optimization failed. The problem appears to be unbounded.", + 4: "Optimization failed. Singular matrix encountered."} + + n, m = A.shape + + # All constraints must have b >= 0. + is_negative_constraint = np.less(b, 0) + A[is_negative_constraint] *= -1 + b[is_negative_constraint] *= -1 + + # As all constraints are equality constraints the artificial variables + # will also be basic variables. + av = np.arange(n) + m + basis = av.copy() + + # Format the phase one tableau by adding artificial variables and stacking + # the constraints, the objective row and pseudo-objective row. + row_constraints = np.hstack((A, np.eye(n), b[:, np.newaxis])) + row_objective = np.hstack((c, np.zeros(n), c0)) + row_pseudo_objective = -row_constraints.sum(axis=0) + row_pseudo_objective[av] = 0 + T = np.vstack((row_constraints, row_objective, row_pseudo_objective)) + + nit1, status = _solve_simplex(T, n, basis, callback=callback, + postsolve_args=postsolve_args, + maxiter=maxiter, tol=tol, phase=1, + bland=bland + ) + # if pseudo objective is zero, remove the last row from the tableau and + # proceed to phase 2 + nit2 = nit1 + if abs(T[-1, -1]) < tol: + # Remove the pseudo-objective row from the tableau + T = T[:-1, :] + # Remove the artificial variable columns from the tableau + T = np.delete(T, av, 1) + else: + # Failure to find a feasible starting point + status = 2 + messages[status] = ( + "Phase 1 of the simplex method failed to find a feasible " + "solution. The pseudo-objective function evaluates to " + f"{abs(T[-1, -1]):.1e} " + f"which exceeds the required tolerance of {tol} for a solution to be " + "considered 'close enough' to zero to be a basic solution. " + "Consider increasing the tolerance to be greater than " + f"{abs(T[-1, -1]):.1e}. " + "If this tolerance is unacceptably large the problem may be " + "infeasible." + ) + + if status == 0: + # Phase 2 + nit2, status = _solve_simplex(T, n, basis, callback=callback, + postsolve_args=postsolve_args, + maxiter=maxiter, tol=tol, phase=2, + bland=bland, nit0=nit1 + ) + + solution = np.zeros(n + m) + solution[basis[:n]] = T[:n, -1] + x = solution[:m] + + return x, status, messages[status], int(nit2) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_linprog_util.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_linprog_util.py new file mode 100644 index 0000000000000000000000000000000000000000..405ff0feee7116712a6b0897e2f956a6e8a1760f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_linprog_util.py @@ -0,0 +1,1523 @@ +""" +Method agnostic utility functions for linear programming +""" + +import numpy as np +import scipy.sparse as sps +from warnings import warn +from ._optimize import OptimizeWarning +from scipy.optimize._remove_redundancy import ( + _remove_redundancy_svd, _remove_redundancy_pivot_sparse, + _remove_redundancy_pivot_dense, _remove_redundancy_id + ) +from collections import namedtuple + +_LPProblem = namedtuple('_LPProblem', + 'c A_ub b_ub A_eq b_eq bounds x0 integrality') +_LPProblem.__new__.__defaults__ = (None,) * 7 # make c the only required arg +_LPProblem.__doc__ = \ + """ Represents a linear-programming problem. + + Attributes + ---------- + c : 1D array + The coefficients of the linear objective function to be minimized. + A_ub : 2D array, optional + The inequality constraint matrix. Each row of ``A_ub`` specifies the + coefficients of a linear inequality constraint on ``x``. + b_ub : 1D array, optional + The inequality constraint vector. Each element represents an + upper bound on the corresponding value of ``A_ub @ x``. + A_eq : 2D array, optional + The equality constraint matrix. Each row of ``A_eq`` specifies the + coefficients of a linear equality constraint on ``x``. + b_eq : 1D array, optional + The equality constraint vector. Each element of ``A_eq @ x`` must equal + the corresponding element of ``b_eq``. + bounds : various valid formats, optional + The bounds of ``x``, as ``min`` and ``max`` pairs. + If bounds are specified for all N variables separately, valid formats + are: + * a 2D array (N x 2); + * a sequence of N sequences, each with 2 values. + If all variables have the same bounds, the bounds can be specified as + a 1-D or 2-D array or sequence with 2 scalar values. + If all variables have a lower bound of 0 and no upper bound, the bounds + parameter can be omitted (or given as None). + Absent lower and/or upper bounds can be specified as -numpy.inf (no + lower bound), numpy.inf (no upper bound) or None (both). + x0 : 1D array, optional + Guess values of the decision variables, which will be refined by + the optimization algorithm. This argument is currently used only by the + 'revised simplex' method, and can only be used if `x0` represents a + basic feasible solution. + integrality : 1-D array or int, optional + Indicates the type of integrality constraint on each decision variable. + + ``0`` : Continuous variable; no integrality constraint. + + ``1`` : Integer variable; decision variable must be an integer + within `bounds`. + + ``2`` : Semi-continuous variable; decision variable must be within + `bounds` or take value ``0``. + + ``3`` : Semi-integer variable; decision variable must be an integer + within `bounds` or take value ``0``. + + By default, all variables are continuous. + + For mixed integrality constraints, supply an array of shape `c.shape`. + To infer a constraint on each decision variable from shorter inputs, + the argument will be broadcast to `c.shape` using `np.broadcast_to`. + + This argument is currently used only by the ``'highs'`` method and + ignored otherwise. + + Notes + ----- + This namedtuple supports 2 ways of initialization: + >>> lp1 = _LPProblem(c=[-1, 4], A_ub=[[-3, 1], [1, 2]], b_ub=[6, 4]) + >>> lp2 = _LPProblem([-1, 4], [[-3, 1], [1, 2]], [6, 4]) + + Note that only ``c`` is a required argument here, whereas all other arguments + ``A_ub``, ``b_ub``, ``A_eq``, ``b_eq``, ``bounds``, ``x0`` are optional with + default values of None. + For example, ``A_eq`` and ``b_eq`` can be set without ``A_ub`` or ``b_ub``: + >>> lp3 = _LPProblem(c=[-1, 4], A_eq=[[2, 1]], b_eq=[10]) + """ + + +def _check_sparse_inputs(options, meth, A_ub, A_eq): + """ + Check the provided ``A_ub`` and ``A_eq`` matrices conform to the specified + optional sparsity variables. + + Parameters + ---------- + A_ub : 2-D array, optional + 2-D array such that ``A_ub @ x`` gives the values of the upper-bound + inequality constraints at ``x``. + A_eq : 2-D array, optional + 2-D array such that ``A_eq @ x`` gives the values of the equality + constraints at ``x``. + options : dict + A dictionary of solver options. All methods accept the following + generic options: + + maxiter : int + Maximum number of iterations to perform. + disp : bool + Set to True to print convergence messages. + + For method-specific options, see :func:`show_options('linprog')`. + method : str, optional + The algorithm used to solve the standard form problem. + + Returns + ------- + A_ub : 2-D array, optional + 2-D array such that ``A_ub @ x`` gives the values of the upper-bound + inequality constraints at ``x``. + A_eq : 2-D array, optional + 2-D array such that ``A_eq @ x`` gives the values of the equality + constraints at ``x``. + options : dict + A dictionary of solver options. All methods accept the following + generic options: + + maxiter : int + Maximum number of iterations to perform. + disp : bool + Set to True to print convergence messages. + + For method-specific options, see :func:`show_options('linprog')`. + """ + # This is an undocumented option for unit testing sparse presolve + _sparse_presolve = options.pop('_sparse_presolve', False) + if _sparse_presolve and A_eq is not None: + A_eq = sps.coo_matrix(A_eq) + if _sparse_presolve and A_ub is not None: + A_ub = sps.coo_matrix(A_ub) + + sparse_constraint = sps.issparse(A_eq) or sps.issparse(A_ub) + + preferred_methods = {"highs", "highs-ds", "highs-ipm"} + dense_methods = {"simplex", "revised simplex"} + if meth in dense_methods and sparse_constraint: + raise ValueError(f"Method '{meth}' does not support sparse " + "constraint matrices. Please consider using one of " + f"{preferred_methods}.") + + sparse = options.get('sparse', False) + if not sparse and sparse_constraint and meth == 'interior-point': + options['sparse'] = True + warn("Sparse constraint matrix detected; setting 'sparse':True.", + OptimizeWarning, stacklevel=4) + return options, A_ub, A_eq + + +def _format_A_constraints(A, n_x, sparse_lhs=False): + """Format the left hand side of the constraints to a 2-D array + + Parameters + ---------- + A : 2-D array + 2-D array such that ``A @ x`` gives the values of the upper-bound + (in)equality constraints at ``x``. + n_x : int + The number of variables in the linear programming problem. + sparse_lhs : bool + Whether either of `A_ub` or `A_eq` are sparse. If true return a + coo_matrix instead of a numpy array. + + Returns + ------- + np.ndarray or sparse.coo_matrix + 2-D array such that ``A @ x`` gives the values of the upper-bound + (in)equality constraints at ``x``. + + """ + if sparse_lhs: + return sps.coo_matrix( + (0, n_x) if A is None else A, dtype=float, copy=True + ) + elif A is None: + return np.zeros((0, n_x), dtype=float) + else: + return np.array(A, dtype=float, copy=True) + + +def _format_b_constraints(b): + """Format the upper bounds of the constraints to a 1-D array + + Parameters + ---------- + b : 1-D array + 1-D array of values representing the upper-bound of each (in)equality + constraint (row) in ``A``. + + Returns + ------- + 1-D np.array + 1-D array of values representing the upper-bound of each (in)equality + constraint (row) in ``A``. + + """ + if b is None: + return np.array([], dtype=float) + b = np.array(b, dtype=float, copy=True).squeeze() + return b if b.size != 1 else b.reshape(-1) + + +def _clean_inputs(lp): + """ + Given user inputs for a linear programming problem, return the + objective vector, upper bound constraints, equality constraints, + and simple bounds in a preferred format. + + Parameters + ---------- + lp : A `scipy.optimize._linprog_util._LPProblem` consisting of the following fields: + + c : 1D array + The coefficients of the linear objective function to be minimized. + A_ub : 2D array, optional + The inequality constraint matrix. Each row of ``A_ub`` specifies the + coefficients of a linear inequality constraint on ``x``. + b_ub : 1D array, optional + The inequality constraint vector. Each element represents an + upper bound on the corresponding value of ``A_ub @ x``. + A_eq : 2D array, optional + The equality constraint matrix. Each row of ``A_eq`` specifies the + coefficients of a linear equality constraint on ``x``. + b_eq : 1D array, optional + The equality constraint vector. Each element of ``A_eq @ x`` must equal + the corresponding element of ``b_eq``. + bounds : various valid formats, optional + The bounds of ``x``, as ``min`` and ``max`` pairs. + If bounds are specified for all N variables separately, valid formats are: + * a 2D array (2 x N or N x 2); + * a sequence of N sequences, each with 2 values. + If all variables have the same bounds, a single pair of values can + be specified. Valid formats are: + * a sequence with 2 scalar values; + * a sequence with a single element containing 2 scalar values. + If all variables have a lower bound of 0 and no upper bound, the bounds + parameter can be omitted (or given as None). + x0 : 1D array, optional + Guess values of the decision variables, which will be refined by + the optimization algorithm. This argument is currently used only by the + 'revised simplex' method, and can only be used if `x0` represents a + basic feasible solution. + + Returns + ------- + lp : A `scipy.optimize._linprog_util._LPProblem` consisting of the following fields: + + c : 1D array + The coefficients of the linear objective function to be minimized. + A_ub : 2D array, optional + The inequality constraint matrix. Each row of ``A_ub`` specifies the + coefficients of a linear inequality constraint on ``x``. + b_ub : 1D array, optional + The inequality constraint vector. Each element represents an + upper bound on the corresponding value of ``A_ub @ x``. + A_eq : 2D array, optional + The equality constraint matrix. Each row of ``A_eq`` specifies the + coefficients of a linear equality constraint on ``x``. + b_eq : 1D array, optional + The equality constraint vector. Each element of ``A_eq @ x`` must equal + the corresponding element of ``b_eq``. + bounds : 2D array + The bounds of ``x``, as ``min`` and ``max`` pairs, one for each of the N + elements of ``x``. The N x 2 array contains lower bounds in the first + column and upper bounds in the 2nd. Unbounded variables have lower + bound -np.inf and/or upper bound np.inf. + x0 : 1D array, optional + Guess values of the decision variables, which will be refined by + the optimization algorithm. This argument is currently used only by the + 'revised simplex' method, and can only be used if `x0` represents a + basic feasible solution. + + """ + c, A_ub, b_ub, A_eq, b_eq, bounds, x0, integrality = lp + + if c is None: + raise TypeError + + try: + c = np.array(c, dtype=np.float64, copy=True).squeeze() + except ValueError as e: + raise TypeError( + "Invalid input for linprog: c must be a 1-D array of numerical " + "coefficients") from e + else: + # If c is a single value, convert it to a 1-D array. + if c.size == 1: + c = c.reshape(-1) + + n_x = len(c) + if n_x == 0 or len(c.shape) != 1: + raise ValueError( + "Invalid input for linprog: c must be a 1-D array and must " + "not have more than one non-singleton dimension") + if not np.isfinite(c).all(): + raise ValueError( + "Invalid input for linprog: c must not contain values " + "inf, nan, or None") + + sparse_lhs = sps.issparse(A_eq) or sps.issparse(A_ub) + try: + A_ub = _format_A_constraints(A_ub, n_x, sparse_lhs=sparse_lhs) + except ValueError as e: + raise TypeError( + "Invalid input for linprog: A_ub must be a 2-D array " + "of numerical values") from e + else: + n_ub = A_ub.shape[0] + if len(A_ub.shape) != 2 or A_ub.shape[1] != n_x: + raise ValueError( + "Invalid input for linprog: A_ub must have exactly two " + "dimensions, and the number of columns in A_ub must be " + "equal to the size of c") + if (sps.issparse(A_ub) and not np.isfinite(A_ub.data).all() + or not sps.issparse(A_ub) and not np.isfinite(A_ub).all()): + raise ValueError( + "Invalid input for linprog: A_ub must not contain values " + "inf, nan, or None") + + try: + b_ub = _format_b_constraints(b_ub) + except ValueError as e: + raise TypeError( + "Invalid input for linprog: b_ub must be a 1-D array of " + "numerical values, each representing the upper bound of an " + "inequality constraint (row) in A_ub") from e + else: + if b_ub.shape != (n_ub,): + raise ValueError( + "Invalid input for linprog: b_ub must be a 1-D array; b_ub " + "must not have more than one non-singleton dimension and " + "the number of rows in A_ub must equal the number of values " + "in b_ub") + if not np.isfinite(b_ub).all(): + raise ValueError( + "Invalid input for linprog: b_ub must not contain values " + "inf, nan, or None") + + try: + A_eq = _format_A_constraints(A_eq, n_x, sparse_lhs=sparse_lhs) + except ValueError as e: + raise TypeError( + "Invalid input for linprog: A_eq must be a 2-D array " + "of numerical values") from e + else: + n_eq = A_eq.shape[0] + if len(A_eq.shape) != 2 or A_eq.shape[1] != n_x: + raise ValueError( + "Invalid input for linprog: A_eq must have exactly two " + "dimensions, and the number of columns in A_eq must be " + "equal to the size of c") + + if (sps.issparse(A_eq) and not np.isfinite(A_eq.data).all() + or not sps.issparse(A_eq) and not np.isfinite(A_eq).all()): + raise ValueError( + "Invalid input for linprog: A_eq must not contain values " + "inf, nan, or None") + + try: + b_eq = _format_b_constraints(b_eq) + except ValueError as e: + raise TypeError( + "Invalid input for linprog: b_eq must be a dense, 1-D array of " + "numerical values, each representing the right hand side of an " + "equality constraint (row) in A_eq") from e + else: + if b_eq.shape != (n_eq,): + raise ValueError( + "Invalid input for linprog: b_eq must be a 1-D array; b_eq " + "must not have more than one non-singleton dimension and " + "the number of rows in A_eq must equal the number of values " + "in b_eq") + if not np.isfinite(b_eq).all(): + raise ValueError( + "Invalid input for linprog: b_eq must not contain values " + "inf, nan, or None") + + # x0 gives a (optional) starting solution to the solver. If x0 is None, + # skip the checks. Initial solution will be generated automatically. + if x0 is not None: + try: + x0 = np.array(x0, dtype=float, copy=True).squeeze() + except ValueError as e: + raise TypeError( + "Invalid input for linprog: x0 must be a 1-D array of " + "numerical coefficients") from e + if x0.ndim == 0: + x0 = x0.reshape(-1) + if len(x0) == 0 or x0.ndim != 1: + raise ValueError( + "Invalid input for linprog: x0 should be a 1-D array; it " + "must not have more than one non-singleton dimension") + if not x0.size == c.size: + raise ValueError( + "Invalid input for linprog: x0 and c should contain the " + "same number of elements") + if not np.isfinite(x0).all(): + raise ValueError( + "Invalid input for linprog: x0 must not contain values " + "inf, nan, or None") + + # Bounds can be one of these formats: + # (1) a 2-D array or sequence, with shape N x 2 + # (2) a 1-D or 2-D sequence or array with 2 scalars + # (3) None (or an empty sequence or array) + # Unspecified bounds can be represented by None or (-)np.inf. + # All formats are converted into a N x 2 np.array with (-)np.inf where + # bounds are unspecified. + + # Prepare clean bounds array + bounds_clean = np.zeros((n_x, 2), dtype=float) + + # Convert to a numpy array. + # np.array(..,dtype=float) raises an error if dimensions are inconsistent + # or if there are invalid data types in bounds. Just add a linprog prefix + # to the error and re-raise. + # Creating at least a 2-D array simplifies the cases to distinguish below. + if bounds is None or np.array_equal(bounds, []) or np.array_equal(bounds, [[]]): + bounds = (0, np.inf) + try: + bounds_conv = np.atleast_2d(np.array(bounds, dtype=float)) + except ValueError as e: + raise ValueError( + "Invalid input for linprog: unable to interpret bounds, " + "check values and dimensions: " + e.args[0]) from e + except TypeError as e: + raise TypeError( + "Invalid input for linprog: unable to interpret bounds, " + "check values and dimensions: " + e.args[0]) from e + + # Check bounds options + bsh = bounds_conv.shape + if len(bsh) > 2: + # Do not try to handle multidimensional bounds input + raise ValueError( + "Invalid input for linprog: provide a 2-D array for bounds, " + f"not a {len(bsh):d}-D array.") + elif np.all(bsh == (n_x, 2)): + # Regular N x 2 array + bounds_clean = bounds_conv + elif (np.all(bsh == (2, 1)) or np.all(bsh == (1, 2))): + # 2 values: interpret as overall lower and upper bound + bounds_flat = bounds_conv.flatten() + bounds_clean[:, 0] = bounds_flat[0] + bounds_clean[:, 1] = bounds_flat[1] + elif np.all(bsh == (2, n_x)): + # Reject a 2 x N array + raise ValueError( + f"Invalid input for linprog: provide a {n_x:d} x 2 array for bounds, " + f"not a 2 x {n_x:d} array.") + else: + raise ValueError( + "Invalid input for linprog: unable to interpret bounds with this " + f"dimension tuple: {bsh}.") + + # The process above creates nan-s where the input specified None + # Convert the nan-s in the 1st column to -np.inf and in the 2nd column + # to np.inf + i_none = np.isnan(bounds_clean[:, 0]) + bounds_clean[i_none, 0] = -np.inf + i_none = np.isnan(bounds_clean[:, 1]) + bounds_clean[i_none, 1] = np.inf + + return _LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds_clean, x0, integrality) + + +def _presolve(lp, rr, rr_method, tol=1e-9): + """ + Given inputs for a linear programming problem in preferred format, + presolve the problem: identify trivial infeasibilities, redundancies, + and unboundedness, tighten bounds where possible, and eliminate fixed + variables. + + Parameters + ---------- + lp : A `scipy.optimize._linprog_util._LPProblem` consisting of the following fields: + + c : 1D array + The coefficients of the linear objective function to be minimized. + A_ub : 2D array, optional + The inequality constraint matrix. Each row of ``A_ub`` specifies the + coefficients of a linear inequality constraint on ``x``. + b_ub : 1D array, optional + The inequality constraint vector. Each element represents an + upper bound on the corresponding value of ``A_ub @ x``. + A_eq : 2D array, optional + The equality constraint matrix. Each row of ``A_eq`` specifies the + coefficients of a linear equality constraint on ``x``. + b_eq : 1D array, optional + The equality constraint vector. Each element of ``A_eq @ x`` must equal + the corresponding element of ``b_eq``. + bounds : 2D array + The bounds of ``x``, as ``min`` and ``max`` pairs, one for each of the N + elements of ``x``. The N x 2 array contains lower bounds in the first + column and upper bounds in the 2nd. Unbounded variables have lower + bound -np.inf and/or upper bound np.inf. + x0 : 1D array, optional + Guess values of the decision variables, which will be refined by + the optimization algorithm. This argument is currently used only by the + 'revised simplex' method, and can only be used if `x0` represents a + basic feasible solution. + + rr : bool + If ``True`` attempts to eliminate any redundant rows in ``A_eq``. + Set False if ``A_eq`` is known to be of full row rank, or if you are + looking for a potential speedup (at the expense of reliability). + rr_method : string + Method used to identify and remove redundant rows from the + equality constraint matrix after presolve. + tol : float + The tolerance which determines when a solution is "close enough" to + zero in Phase 1 to be considered a basic feasible solution or close + enough to positive to serve as an optimal solution. + + Returns + ------- + lp : A `scipy.optimize._linprog_util._LPProblem` consisting of the following fields: + + c : 1D array + The coefficients of the linear objective function to be minimized. + A_ub : 2D array, optional + The inequality constraint matrix. Each row of ``A_ub`` specifies the + coefficients of a linear inequality constraint on ``x``. + b_ub : 1D array, optional + The inequality constraint vector. Each element represents an + upper bound on the corresponding value of ``A_ub @ x``. + A_eq : 2D array, optional + The equality constraint matrix. Each row of ``A_eq`` specifies the + coefficients of a linear equality constraint on ``x``. + b_eq : 1D array, optional + The equality constraint vector. Each element of ``A_eq @ x`` must equal + the corresponding element of ``b_eq``. + bounds : 2D array + The bounds of ``x``, as ``min`` and ``max`` pairs, possibly tightened. + x0 : 1D array, optional + Guess values of the decision variables, which will be refined by + the optimization algorithm. This argument is currently used only by the + 'revised simplex' method, and can only be used if `x0` represents a + basic feasible solution. + + c0 : 1D array + Constant term in objective function due to fixed (and eliminated) + variables. + x : 1D array + Solution vector (when the solution is trivial and can be determined + in presolve) + revstack: list of functions + the functions in the list reverse the operations of _presolve() + the function signature is x_org = f(x_mod), where x_mod is the result + of a presolve step and x_org the value at the start of the step + (currently, the revstack contains only one function) + complete: bool + Whether the solution is complete (solved or determined to be infeasible + or unbounded in presolve) + status : int + An integer representing the exit status of the optimization:: + + 0 : Optimization terminated successfully + 1 : Iteration limit reached + 2 : Problem appears to be infeasible + 3 : Problem appears to be unbounded + 4 : Serious numerical difficulties encountered + + message : str + A string descriptor of the exit status of the optimization. + + References + ---------- + .. [5] Andersen, Erling D. "Finding all linearly dependent rows in + large-scale linear programming." Optimization Methods and Software + 6.3 (1995): 219-227. + .. [8] Andersen, Erling D., and Knud D. Andersen. "Presolving in linear + programming." Mathematical Programming 71.2 (1995): 221-245. + + """ + # ideas from Reference [5] by Andersen and Andersen + # however, unlike the reference, this is performed before converting + # problem to standard form + # There are a few advantages: + # * artificial variables have not been added, so matrices are smaller + # * bounds have not been converted to constraints yet. (It is better to + # do that after presolve because presolve may adjust the simple bounds.) + # There are many improvements that can be made, namely: + # * implement remaining checks from [5] + # * loop presolve until no additional changes are made + # * implement additional efficiency improvements in redundancy removal [2] + + c, A_ub, b_ub, A_eq, b_eq, bounds, x0, _ = lp + + revstack = [] # record of variables eliminated from problem + # constant term in cost function may be added if variables are eliminated + c0 = 0 + complete = False # complete is True if detected infeasible/unbounded + x = np.zeros(c.shape) # this is solution vector if completed in presolve + + status = 0 # all OK unless determined otherwise + message = "" + + # Lower and upper bounds. Copy to prevent feedback. + lb = bounds[:, 0].copy() + ub = bounds[:, 1].copy() + + m_eq, n = A_eq.shape + m_ub, n = A_ub.shape + + if (rr_method is not None + and rr_method.lower() not in {"svd", "pivot", "id"}): + message = ("'" + str(rr_method) + "' is not a valid option " + "for redundancy removal. Valid options are 'SVD', " + "'pivot', and 'ID'.") + raise ValueError(message) + + if sps.issparse(A_eq): + A_eq = A_eq.tocsr() + A_ub = A_ub.tocsr() + + def where(A): + return A.nonzero() + + vstack = sps.vstack + else: + where = np.where + vstack = np.vstack + + # upper bounds > lower bounds + if np.any(ub < lb) or np.any(lb == np.inf) or np.any(ub == -np.inf): + status = 2 + message = ("The problem is (trivially) infeasible since one " + "or more upper bounds are smaller than the corresponding " + "lower bounds, a lower bound is np.inf or an upper bound " + "is -np.inf.") + complete = True + return (_LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0), + c0, x, revstack, complete, status, message) + + # zero row in equality constraints + zero_row = np.array(np.sum(A_eq != 0, axis=1) == 0).flatten() + if np.any(zero_row): + if np.any( + np.logical_and( + zero_row, + np.abs(b_eq) > tol)): # test_zero_row_1 + # infeasible if RHS is not zero + status = 2 + message = ("The problem is (trivially) infeasible due to a row " + "of zeros in the equality constraint matrix with a " + "nonzero corresponding constraint value.") + complete = True + return (_LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0), + c0, x, revstack, complete, status, message) + else: # test_zero_row_2 + # if RHS is zero, we can eliminate this equation entirely + A_eq = A_eq[np.logical_not(zero_row), :] + b_eq = b_eq[np.logical_not(zero_row)] + + # zero row in inequality constraints + zero_row = np.array(np.sum(A_ub != 0, axis=1) == 0).flatten() + if np.any(zero_row): + if np.any(np.logical_and(zero_row, b_ub < -tol)): # test_zero_row_1 + # infeasible if RHS is less than zero (because LHS is zero) + status = 2 + message = ("The problem is (trivially) infeasible due to a row " + "of zeros in the equality constraint matrix with a " + "nonzero corresponding constraint value.") + complete = True + return (_LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0), + c0, x, revstack, complete, status, message) + else: # test_zero_row_2 + # if LHS is >= 0, we can eliminate this constraint entirely + A_ub = A_ub[np.logical_not(zero_row), :] + b_ub = b_ub[np.logical_not(zero_row)] + + # zero column in (both) constraints + # this indicates that a variable isn't constrained and can be removed + A = vstack((A_eq, A_ub)) + if A.shape[0] > 0: + zero_col = np.array(np.sum(A != 0, axis=0) == 0).flatten() + # variable will be at upper or lower bound, depending on objective + x[np.logical_and(zero_col, c < 0)] = ub[ + np.logical_and(zero_col, c < 0)] + x[np.logical_and(zero_col, c > 0)] = lb[ + np.logical_and(zero_col, c > 0)] + if np.any(np.isinf(x)): # if an unconstrained variable has no bound + status = 3 + message = ("If feasible, the problem is (trivially) unbounded " + "due to a zero column in the constraint matrices. If " + "you wish to check whether the problem is infeasible, " + "turn presolve off.") + complete = True + return (_LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0), + c0, x, revstack, complete, status, message) + # variables will equal upper/lower bounds will be removed later + lb[np.logical_and(zero_col, c < 0)] = ub[ + np.logical_and(zero_col, c < 0)] + ub[np.logical_and(zero_col, c > 0)] = lb[ + np.logical_and(zero_col, c > 0)] + + # row singleton in equality constraints + # this fixes a variable and removes the constraint + singleton_row = np.array(np.sum(A_eq != 0, axis=1) == 1).flatten() + rows = where(singleton_row)[0] + cols = where(A_eq[rows, :])[1] + if len(rows) > 0: + for row, col in zip(rows, cols): + val = b_eq[row] / A_eq[row, col] + if not lb[col] - tol <= val <= ub[col] + tol: + # infeasible if fixed value is not within bounds + status = 2 + message = ("The problem is (trivially) infeasible because a " + "singleton row in the equality constraints is " + "inconsistent with the bounds.") + complete = True + return (_LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0), + c0, x, revstack, complete, status, message) + else: + # sets upper and lower bounds at that fixed value - variable + # will be removed later + lb[col] = val + ub[col] = val + A_eq = A_eq[np.logical_not(singleton_row), :] + b_eq = b_eq[np.logical_not(singleton_row)] + + # row singleton in inequality constraints + # this indicates a simple bound and the constraint can be removed + # simple bounds may be adjusted here + # After all of the simple bound information is combined here, get_Abc will + # turn the simple bounds into constraints + singleton_row = np.array(np.sum(A_ub != 0, axis=1) == 1).flatten() + cols = where(A_ub[singleton_row, :])[1] + rows = where(singleton_row)[0] + if len(rows) > 0: + for row, col in zip(rows, cols): + val = b_ub[row] / A_ub[row, col] + if A_ub[row, col] > 0: # upper bound + if val < lb[col] - tol: # infeasible + complete = True + elif val < ub[col]: # new upper bound + ub[col] = val + else: # lower bound + if val > ub[col] + tol: # infeasible + complete = True + elif val > lb[col]: # new lower bound + lb[col] = val + if complete: + status = 2 + message = ("The problem is (trivially) infeasible because a " + "singleton row in the upper bound constraints is " + "inconsistent with the bounds.") + return (_LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0), + c0, x, revstack, complete, status, message) + A_ub = A_ub[np.logical_not(singleton_row), :] + b_ub = b_ub[np.logical_not(singleton_row)] + + # identical bounds indicate that variable can be removed + i_f = np.abs(lb - ub) < tol # indices of "fixed" variables + i_nf = np.logical_not(i_f) # indices of "not fixed" variables + + # test_bounds_equal_but_infeasible + if np.all(i_f): # if bounds define solution, check for consistency + residual = b_eq - A_eq.dot(lb) + slack = b_ub - A_ub.dot(lb) + if ((A_ub.size > 0 and np.any(slack < 0)) or + (A_eq.size > 0 and not np.allclose(residual, 0))): + status = 2 + message = ("The problem is (trivially) infeasible because the " + "bounds fix all variables to values inconsistent with " + "the constraints") + complete = True + return (_LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0), + c0, x, revstack, complete, status, message) + + ub_mod = ub + lb_mod = lb + if np.any(i_f): + c0 += c[i_f].dot(lb[i_f]) + b_eq = b_eq - A_eq[:, i_f].dot(lb[i_f]) + b_ub = b_ub - A_ub[:, i_f].dot(lb[i_f]) + c = c[i_nf] + x_undo = lb[i_f] # not x[i_f], x is just zeroes + x = x[i_nf] + # user guess x0 stays separate from presolve solution x + if x0 is not None: + x0 = x0[i_nf] + A_eq = A_eq[:, i_nf] + A_ub = A_ub[:, i_nf] + # modify bounds + lb_mod = lb[i_nf] + ub_mod = ub[i_nf] + + def rev(x_mod): + # Function to restore x: insert x_undo into x_mod. + # When elements have been removed at positions k1, k2, k3, ... + # then these must be replaced at (after) positions k1-1, k2-2, + # k3-3, ... in the modified array to recreate the original + i = np.flatnonzero(i_f) + # Number of variables to restore + N = len(i) + index_offset = np.arange(N) + # Create insert indices + insert_indices = i - index_offset + x_rev = np.insert(x_mod.astype(float), insert_indices, x_undo) + return x_rev + + # Use revstack as a list of functions, currently just this one. + revstack.append(rev) + + # no constraints indicates that problem is trivial + if A_eq.size == 0 and A_ub.size == 0: + b_eq = np.array([]) + b_ub = np.array([]) + # test_empty_constraint_1 + if c.size == 0: + status = 0 + message = ("The solution was determined in presolve as there are " + "no non-trivial constraints.") + elif (np.any(np.logical_and(c < 0, ub_mod == np.inf)) or + np.any(np.logical_and(c > 0, lb_mod == -np.inf))): + # test_no_constraints() + # test_unbounded_no_nontrivial_constraints_1 + # test_unbounded_no_nontrivial_constraints_2 + status = 3 + message = ("The problem is (trivially) unbounded " + "because there are no non-trivial constraints and " + "a) at least one decision variable is unbounded " + "above and its corresponding cost is negative, or " + "b) at least one decision variable is unbounded below " + "and its corresponding cost is positive. ") + else: # test_empty_constraint_2 + status = 0 + message = ("The solution was determined in presolve as there are " + "no non-trivial constraints.") + complete = True + x[c < 0] = ub_mod[c < 0] + x[c > 0] = lb_mod[c > 0] + # where c is zero, set x to a finite bound or zero + x_zero_c = ub_mod[c == 0] + x_zero_c[np.isinf(x_zero_c)] = ub_mod[c == 0][np.isinf(x_zero_c)] + x_zero_c[np.isinf(x_zero_c)] = 0 + x[c == 0] = x_zero_c + # if this is not the last step of presolve, should convert bounds back + # to array and return here + + # Convert modified lb and ub back into N x 2 bounds + bounds = np.hstack((lb_mod[:, np.newaxis], ub_mod[:, np.newaxis])) + + # remove redundant (linearly dependent) rows from equality constraints + n_rows_A = A_eq.shape[0] + redundancy_warning = ("A_eq does not appear to be of full row rank. To " + "improve performance, check the problem formulation " + "for redundant equality constraints.") + if (sps.issparse(A_eq)): + if rr and A_eq.size > 0: # TODO: Fast sparse rank check? + rr_res = _remove_redundancy_pivot_sparse(A_eq, b_eq) + A_eq, b_eq, status, message = rr_res + if A_eq.shape[0] < n_rows_A: + warn(redundancy_warning, OptimizeWarning, stacklevel=1) + if status != 0: + complete = True + return (_LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0), + c0, x, revstack, complete, status, message) + + # This is a wild guess for which redundancy removal algorithm will be + # faster. More testing would be good. + small_nullspace = 5 + if rr and A_eq.size > 0: + try: # TODO: use results of first SVD in _remove_redundancy_svd + rank = np.linalg.matrix_rank(A_eq) + # oh well, we'll have to go with _remove_redundancy_pivot_dense + except Exception: + rank = 0 + if rr and A_eq.size > 0 and rank < A_eq.shape[0]: + warn(redundancy_warning, OptimizeWarning, stacklevel=3) + dim_row_nullspace = A_eq.shape[0]-rank + if rr_method is None: + if dim_row_nullspace <= small_nullspace: + rr_res = _remove_redundancy_svd(A_eq, b_eq) + A_eq, b_eq, status, message = rr_res + if dim_row_nullspace > small_nullspace or status == 4: + rr_res = _remove_redundancy_pivot_dense(A_eq, b_eq) + A_eq, b_eq, status, message = rr_res + + else: + rr_method = rr_method.lower() + if rr_method == "svd": + rr_res = _remove_redundancy_svd(A_eq, b_eq) + A_eq, b_eq, status, message = rr_res + elif rr_method == "pivot": + rr_res = _remove_redundancy_pivot_dense(A_eq, b_eq) + A_eq, b_eq, status, message = rr_res + elif rr_method == "id": + rr_res = _remove_redundancy_id(A_eq, b_eq, rank) + A_eq, b_eq, status, message = rr_res + else: # shouldn't get here; option validity checked above + pass + if A_eq.shape[0] < rank: + message = ("Due to numerical issues, redundant equality " + "constraints could not be removed automatically. " + "Try providing your constraint matrices as sparse " + "matrices to activate sparse presolve, try turning " + "off redundancy removal, or try turning off presolve " + "altogether.") + status = 4 + if status != 0: + complete = True + return (_LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0), + c0, x, revstack, complete, status, message) + + +def _parse_linprog(lp, options, meth): + """ + Parse the provided linear programming problem + + ``_parse_linprog`` employs two main steps ``_check_sparse_inputs`` and + ``_clean_inputs``. ``_check_sparse_inputs`` checks for sparsity in the + provided constraints (``A_ub`` and ``A_eq) and if these match the provided + sparsity optional values. + + ``_clean inputs`` checks of the provided inputs. If no violations are + identified the objective vector, upper bound constraints, equality + constraints, and simple bounds are returned in the expected format. + + Parameters + ---------- + lp : A `scipy.optimize._linprog_util._LPProblem` consisting of the following fields: + + c : 1D array + The coefficients of the linear objective function to be minimized. + A_ub : 2D array, optional + The inequality constraint matrix. Each row of ``A_ub`` specifies the + coefficients of a linear inequality constraint on ``x``. + b_ub : 1D array, optional + The inequality constraint vector. Each element represents an + upper bound on the corresponding value of ``A_ub @ x``. + A_eq : 2D array, optional + The equality constraint matrix. Each row of ``A_eq`` specifies the + coefficients of a linear equality constraint on ``x``. + b_eq : 1D array, optional + The equality constraint vector. Each element of ``A_eq @ x`` must equal + the corresponding element of ``b_eq``. + bounds : various valid formats, optional + The bounds of ``x``, as ``min`` and ``max`` pairs. + If bounds are specified for all N variables separately, valid formats are: + * a 2D array (2 x N or N x 2); + * a sequence of N sequences, each with 2 values. + If all variables have the same bounds, a single pair of values can + be specified. Valid formats are: + * a sequence with 2 scalar values; + * a sequence with a single element containing 2 scalar values. + If all variables have a lower bound of 0 and no upper bound, the bounds + parameter can be omitted (or given as None). + x0 : 1D array, optional + Guess values of the decision variables, which will be refined by + the optimization algorithm. This argument is currently used only by the + 'revised simplex' method, and can only be used if `x0` represents a + basic feasible solution. + + options : dict + A dictionary of solver options. All methods accept the following + generic options: + + maxiter : int + Maximum number of iterations to perform. + disp : bool + Set to True to print convergence messages. + + For method-specific options, see :func:`show_options('linprog')`. + + Returns + ------- + lp : A `scipy.optimize._linprog_util._LPProblem` consisting of the following fields: + + c : 1D array + The coefficients of the linear objective function to be minimized. + A_ub : 2D array, optional + The inequality constraint matrix. Each row of ``A_ub`` specifies the + coefficients of a linear inequality constraint on ``x``. + b_ub : 1D array, optional + The inequality constraint vector. Each element represents an + upper bound on the corresponding value of ``A_ub @ x``. + A_eq : 2D array, optional + The equality constraint matrix. Each row of ``A_eq`` specifies the + coefficients of a linear equality constraint on ``x``. + b_eq : 1D array, optional + The equality constraint vector. Each element of ``A_eq @ x`` must equal + the corresponding element of ``b_eq``. + bounds : 2D array + The bounds of ``x``, as ``min`` and ``max`` pairs, one for each of the N + elements of ``x``. The N x 2 array contains lower bounds in the first + column and upper bounds in the 2nd. Unbounded variables have lower + bound -np.inf and/or upper bound np.inf. + x0 : 1D array, optional + Guess values of the decision variables, which will be refined by + the optimization algorithm. This argument is currently used only by the + 'revised simplex' method, and can only be used if `x0` represents a + basic feasible solution. + + options : dict, optional + A dictionary of solver options. All methods accept the following + generic options: + + maxiter : int + Maximum number of iterations to perform. + disp : bool + Set to True to print convergence messages. + + For method-specific options, see :func:`show_options('linprog')`. + + """ + if options is None: + options = {} + + solver_options = {k: v for k, v in options.items()} + solver_options, A_ub, A_eq = _check_sparse_inputs(solver_options, meth, + lp.A_ub, lp.A_eq) + # Convert lists to numpy arrays, etc... + lp = _clean_inputs(lp._replace(A_ub=A_ub, A_eq=A_eq)) + return lp, solver_options + + +def _get_Abc(lp, c0): + """ + Given a linear programming problem of the form: + + Minimize:: + + c @ x + + Subject to:: + + A_ub @ x <= b_ub + A_eq @ x == b_eq + lb <= x <= ub + + where ``lb = 0`` and ``ub = None`` unless set in ``bounds``. + + Return the problem in standard form: + + Minimize:: + + c @ x + + Subject to:: + + A @ x == b + x >= 0 + + by adding slack variables and making variable substitutions as necessary. + + Parameters + ---------- + lp : A `scipy.optimize._linprog_util._LPProblem` consisting of the following fields: + + c : 1D array + The coefficients of the linear objective function to be minimized. + A_ub : 2D array, optional + The inequality constraint matrix. Each row of ``A_ub`` specifies the + coefficients of a linear inequality constraint on ``x``. + b_ub : 1D array, optional + The inequality constraint vector. Each element represents an + upper bound on the corresponding value of ``A_ub @ x``. + A_eq : 2D array, optional + The equality constraint matrix. Each row of ``A_eq`` specifies the + coefficients of a linear equality constraint on ``x``. + b_eq : 1D array, optional + The equality constraint vector. Each element of ``A_eq @ x`` must equal + the corresponding element of ``b_eq``. + bounds : 2D array + The bounds of ``x``, lower bounds in the 1st column, upper + bounds in the 2nd column. The bounds are possibly tightened + by the presolve procedure. + x0 : 1D array, optional + Guess values of the decision variables, which will be refined by + the optimization algorithm. This argument is currently used only by the + 'revised simplex' method, and can only be used if `x0` represents a + basic feasible solution. + + c0 : float + Constant term in objective function due to fixed (and eliminated) + variables. + + Returns + ------- + A : 2-D array + 2-D array such that ``A`` @ ``x``, gives the values of the equality + constraints at ``x``. + b : 1-D array + 1-D array of values representing the RHS of each equality constraint + (row) in A (for standard form problem). + c : 1-D array + Coefficients of the linear objective function to be minimized (for + standard form problem). + c0 : float + Constant term in objective function due to fixed (and eliminated) + variables. + x0 : 1-D array + Starting values of the independent variables, which will be refined by + the optimization algorithm + + References + ---------- + .. [9] Bertsimas, Dimitris, and J. Tsitsiklis. "Introduction to linear + programming." Athena Scientific 1 (1997): 997. + + """ + c, A_ub, b_ub, A_eq, b_eq, bounds, x0, integrality = lp + + if sps.issparse(A_eq): + sparse = True + A_eq = sps.csr_matrix(A_eq) + A_ub = sps.csr_matrix(A_ub) + + def hstack(blocks): + return sps.hstack(blocks, format="csr") + + def vstack(blocks): + return sps.vstack(blocks, format="csr") + + zeros = sps.csr_matrix + eye = sps.eye + else: + sparse = False + hstack = np.hstack + vstack = np.vstack + zeros = np.zeros + eye = np.eye + + # Variables lbs and ubs (see below) may be changed, which feeds back into + # bounds, so copy. + bounds = np.array(bounds, copy=True) + + # modify problem such that all variables have only non-negativity bounds + lbs = bounds[:, 0] + ubs = bounds[:, 1] + m_ub, n_ub = A_ub.shape + + lb_none = np.equal(lbs, -np.inf) + ub_none = np.equal(ubs, np.inf) + lb_some = np.logical_not(lb_none) + ub_some = np.logical_not(ub_none) + + # unbounded below: substitute xi = -xi' (unbounded above) + # if -inf <= xi <= ub, then -ub <= -xi <= inf, so swap and invert bounds + l_nolb_someub = np.logical_and(lb_none, ub_some) + i_nolb = np.nonzero(l_nolb_someub)[0] + lbs[l_nolb_someub], ubs[l_nolb_someub] = ( + -ubs[l_nolb_someub], -lbs[l_nolb_someub]) + lb_none = np.equal(lbs, -np.inf) + ub_none = np.equal(ubs, np.inf) + lb_some = np.logical_not(lb_none) + ub_some = np.logical_not(ub_none) + c[i_nolb] *= -1 + if x0 is not None: + x0[i_nolb] *= -1 + if len(i_nolb) > 0: + if A_ub.shape[0] > 0: # sometimes needed for sparse arrays... weird + A_ub[:, i_nolb] *= -1 + if A_eq.shape[0] > 0: + A_eq[:, i_nolb] *= -1 + + # upper bound: add inequality constraint + i_newub, = ub_some.nonzero() + ub_newub = ubs[ub_some] + n_bounds = len(i_newub) + if n_bounds > 0: + shape = (n_bounds, A_ub.shape[1]) + if sparse: + idxs = (np.arange(n_bounds), i_newub) + A_ub = vstack((A_ub, sps.csr_matrix((np.ones(n_bounds), idxs), + shape=shape))) + else: + A_ub = vstack((A_ub, np.zeros(shape))) + A_ub[np.arange(m_ub, A_ub.shape[0]), i_newub] = 1 + b_ub = np.concatenate((b_ub, np.zeros(n_bounds))) + b_ub[m_ub:] = ub_newub + + A1 = vstack((A_ub, A_eq)) + b = np.concatenate((b_ub, b_eq)) + c = np.concatenate((c, np.zeros((A_ub.shape[0],)))) + if x0 is not None: + x0 = np.concatenate((x0, np.zeros((A_ub.shape[0],)))) + # unbounded: substitute xi = xi+ + xi- + l_free = np.logical_and(lb_none, ub_none) + i_free = np.nonzero(l_free)[0] + n_free = len(i_free) + c = np.concatenate((c, np.zeros(n_free))) + if x0 is not None: + x0 = np.concatenate((x0, np.zeros(n_free))) + A1 = hstack((A1[:, :n_ub], -A1[:, i_free])) + c[n_ub:n_ub+n_free] = -c[i_free] + if x0 is not None: + i_free_neg = x0[i_free] < 0 + x0[np.arange(n_ub, A1.shape[1])[i_free_neg]] = -x0[i_free[i_free_neg]] + x0[i_free[i_free_neg]] = 0 + + # add slack variables + A2 = vstack([eye(A_ub.shape[0]), zeros((A_eq.shape[0], A_ub.shape[0]))]) + + A = hstack([A1, A2]) + + # lower bound: substitute xi = xi' + lb + # now there is a constant term in objective + i_shift = np.nonzero(lb_some)[0] + lb_shift = lbs[lb_some].astype(float) + c0 += np.sum(lb_shift * c[i_shift]) + if sparse: + b = b.reshape(-1, 1) + A = A.tocsc() + b -= (A[:, i_shift] @ sps.diags(lb_shift)).sum(axis=1) + b = b.ravel() + else: + b -= (A[:, i_shift] * lb_shift).sum(axis=1) + if x0 is not None: + x0[i_shift] -= lb_shift + + return A, b, c, c0, x0 + + +def _round_to_power_of_two(x): + """ + Round elements of the array to the nearest power of two. + """ + return 2**np.around(np.log2(x)) + + +def _autoscale(A, b, c, x0): + """ + Scales the problem according to equilibration from [12]. + Also normalizes the right hand side vector by its maximum element. + """ + m, n = A.shape + + C = 1 + R = 1 + + if A.size > 0: + + R = np.max(np.abs(A), axis=1) + if sps.issparse(A): + R = R.toarray().flatten() + R[R == 0] = 1 + R = 1/_round_to_power_of_two(R) + A = sps.diags(R)@A if sps.issparse(A) else A*R.reshape(m, 1) + b = b*R + + C = np.max(np.abs(A), axis=0) + if sps.issparse(A): + C = C.toarray().flatten() + C[C == 0] = 1 + C = 1/_round_to_power_of_two(C) + A = A@sps.diags(C) if sps.issparse(A) else A*C + c = c*C + + b_scale = np.max(np.abs(b)) if b.size > 0 else 1 + if b_scale == 0: + b_scale = 1. + b = b/b_scale + + if x0 is not None: + x0 = x0/b_scale*(1/C) + return A, b, c, x0, C, b_scale + + +def _unscale(x, C, b_scale): + """ + Converts solution to _autoscale problem -> solution to original problem. + """ + + try: + n = len(C) + # fails if sparse or scalar; that's OK. + # this is only needed for original simplex (never sparse) + except TypeError: + n = len(x) + + return x[:n]*b_scale*C + + +def _display_summary(message, status, fun, iteration): + """ + Print the termination summary of the linear program + + Parameters + ---------- + message : str + A string descriptor of the exit status of the optimization. + status : int + An integer representing the exit status of the optimization:: + + 0 : Optimization terminated successfully + 1 : Iteration limit reached + 2 : Problem appears to be infeasible + 3 : Problem appears to be unbounded + 4 : Serious numerical difficulties encountered + + fun : float + Value of the objective function. + iteration : iteration + The number of iterations performed. + """ + print(message) + if status in (0, 1): + print(f" Current function value: {fun: <12.6f}") + print(f" Iterations: {iteration:d}") + + +def _postsolve(x, postsolve_args, complete=False): + """ + Given solution x to presolved, standard form linear program x, add + fixed variables back into the problem and undo the variable substitutions + to get solution to original linear program. Also, calculate the objective + function value, slack in original upper bound constraints, and residuals + in original equality constraints. + + Parameters + ---------- + x : 1-D array + Solution vector to the standard-form problem. + postsolve_args : tuple + Data needed by _postsolve to convert the solution to the standard-form + problem into the solution to the original problem, including: + + lp : A `scipy.optimize._linprog_util._LPProblem` consisting of the following fields: + + c : 1D array + The coefficients of the linear objective function to be minimized. + A_ub : 2D array, optional + The inequality constraint matrix. Each row of ``A_ub`` specifies the + coefficients of a linear inequality constraint on ``x``. + b_ub : 1D array, optional + The inequality constraint vector. Each element represents an + upper bound on the corresponding value of ``A_ub @ x``. + A_eq : 2D array, optional + The equality constraint matrix. Each row of ``A_eq`` specifies the + coefficients of a linear equality constraint on ``x``. + b_eq : 1D array, optional + The equality constraint vector. Each element of ``A_eq @ x`` must equal + the corresponding element of ``b_eq``. + bounds : 2D array + The bounds of ``x``, lower bounds in the 1st column, upper + bounds in the 2nd column. The bounds are possibly tightened + by the presolve procedure. + x0 : 1D array, optional + Guess values of the decision variables, which will be refined by + the optimization algorithm. This argument is currently used only by the + 'revised simplex' method, and can only be used if `x0` represents a + basic feasible solution. + + revstack: list of functions + the functions in the list reverse the operations of _presolve() + the function signature is x_org = f(x_mod), where x_mod is the result + of a presolve step and x_org the value at the start of the step + complete : bool + Whether the solution is was determined in presolve (``True`` if so) + + Returns + ------- + x : 1-D array + Solution vector to original linear programming problem + fun: float + optimal objective value for original problem + slack : 1-D array + The (non-negative) slack in the upper bound constraints, that is, + ``b_ub - A_ub @ x`` + con : 1-D array + The (nominally zero) residuals of the equality constraints, that is, + ``b - A_eq @ x`` + """ + # note that all the inputs are the ORIGINAL, unmodified versions + # no rows, columns have been removed + + c, A_ub, b_ub, A_eq, b_eq, bounds, x0, integrality = postsolve_args[0] + revstack, C, b_scale = postsolve_args[1:] + + x = _unscale(x, C, b_scale) + + # Undo variable substitutions of _get_Abc() + # if "complete", problem was solved in presolve; don't do anything here + n_x = bounds.shape[0] + if not complete and bounds is not None: # bounds are never none, probably + n_unbounded = 0 + for i, bi in enumerate(bounds): + lbi = bi[0] + ubi = bi[1] + if lbi == -np.inf and ubi == np.inf: + n_unbounded += 1 + x[i] = x[i] - x[n_x + n_unbounded - 1] + else: + if lbi == -np.inf: + x[i] = ubi - x[i] + else: + x[i] += lbi + # all the rest of the variables were artificial + x = x[:n_x] + + # If there were variables removed from the problem, add them back into the + # solution vector + # Apply the functions in revstack (reverse direction) + for rev in reversed(revstack): + x = rev(x) + + fun = x.dot(c) + with np.errstate(invalid="ignore"): + slack = b_ub - A_ub.dot(x) # report slack for ORIGINAL UB constraints + # report residuals of ORIGINAL EQ constraints + con = b_eq - A_eq.dot(x) + + return x, fun, slack, con + + +def _check_result(x, fun, status, slack, con, bounds, tol, message, + integrality): + """ + Check the validity of the provided solution. + + A valid (optimal) solution satisfies all bounds, all slack variables are + negative and all equality constraint residuals are strictly non-zero. + Further, the lower-bounds, upper-bounds, slack and residuals contain + no nan values. + + Parameters + ---------- + x : 1-D array + Solution vector to original linear programming problem + fun: float + optimal objective value for original problem + status : int + An integer representing the exit status of the optimization:: + + 0 : Optimization terminated successfully + 1 : Iteration limit reached + 2 : Problem appears to be infeasible + 3 : Problem appears to be unbounded + 4 : Serious numerical difficulties encountered + + slack : 1-D array + The (non-negative) slack in the upper bound constraints, that is, + ``b_ub - A_ub @ x`` + con : 1-D array + The (nominally zero) residuals of the equality constraints, that is, + ``b - A_eq @ x`` + bounds : 2D array + The bounds on the original variables ``x`` + message : str + A string descriptor of the exit status of the optimization. + tol : float + Termination tolerance; see [1]_ Section 4.5. + + Returns + ------- + status : int + An integer representing the exit status of the optimization:: + + 0 : Optimization terminated successfully + 1 : Iteration limit reached + 2 : Problem appears to be infeasible + 3 : Problem appears to be unbounded + 4 : Serious numerical difficulties encountered + + message : str + A string descriptor of the exit status of the optimization. + """ + # Somewhat arbitrary + tol = np.sqrt(tol) * 10 + + if x is None: + # HiGHS does not provide x if infeasible/unbounded + if status == 0: # Observed with HiGHS Simplex Primal + status = 4 + message = ("The solver did not provide a solution nor did it " + "report a failure. Please submit a bug report.") + return status, message + + contains_nans = ( + np.isnan(x).any() + or np.isnan(fun) + or np.isnan(slack).any() + or np.isnan(con).any() + ) + + if contains_nans: + is_feasible = False + else: + if integrality is None: + integrality = 0 + valid_bounds = (x >= bounds[:, 0] - tol) & (x <= bounds[:, 1] + tol) + # When integrality is 2 or 3, x must be within bounds OR take value 0 + valid_bounds |= (integrality > 1) & np.isclose(x, 0, atol=tol) + invalid_bounds = not np.all(valid_bounds) + + invalid_slack = status != 3 and (slack < -tol).any() + invalid_con = status != 3 and (np.abs(con) > tol).any() + is_feasible = not (invalid_bounds or invalid_slack or invalid_con) + + if status == 0 and not is_feasible: + status = 4 + message = ("The solution does not satisfy the constraints within the " + "required tolerance of " + f"{tol:.2E}" + ", yet " + "no errors were raised and there is no certificate of " + "infeasibility or unboundedness. Check whether " + "the slack and constraint residuals are acceptable; " + "if not, consider enabling presolve, adjusting the " + "tolerance option(s), and/or using a different method. " + "Please consider submitting a bug report.") + elif status == 2 and is_feasible: + # Occurs if the simplex method exits after phase one with a very + # nearly basic feasible solution. Postsolving can make the solution + # basic, however, this solution is NOT optimal + status = 4 + message = ("The solution is feasible, but the solver did not report " + "that the solution was optimal. Please try a different " + "method.") + + return status, message diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_lsap.cpython-310-x86_64-linux-gnu.so b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_lsap.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..b2ea39a10549d1346bada989f573981804d22006 Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_lsap.cpython-310-x86_64-linux-gnu.so differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_lsq/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_lsq/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f60adcc891304e34ac9d85d108b6a232b4bf0c93 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_lsq/__init__.py @@ -0,0 +1,5 @@ +"""This module contains least-squares algorithms.""" +from .least_squares import least_squares +from .lsq_linear import lsq_linear + +__all__ = ['least_squares', 'lsq_linear'] diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_lsq/bvls.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_lsq/bvls.py new file mode 100644 index 0000000000000000000000000000000000000000..8f34ead4a1fc4edbb3c2ab50a204aa9a3cc21cff --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_lsq/bvls.py @@ -0,0 +1,183 @@ +"""Bounded-variable least-squares algorithm.""" +import numpy as np +from numpy.linalg import norm, lstsq +from scipy.optimize import OptimizeResult + +from .common import print_header_linear, print_iteration_linear + + +def compute_kkt_optimality(g, on_bound): + """Compute the maximum violation of KKT conditions.""" + g_kkt = g * on_bound + free_set = on_bound == 0 + g_kkt[free_set] = np.abs(g[free_set]) + return np.max(g_kkt) + + +def bvls(A, b, x_lsq, lb, ub, tol, max_iter, verbose, rcond=None): + m, n = A.shape + + x = x_lsq.copy() + on_bound = np.zeros(n) + + mask = x <= lb + x[mask] = lb[mask] + on_bound[mask] = -1 + + mask = x >= ub + x[mask] = ub[mask] + on_bound[mask] = 1 + + free_set = on_bound == 0 + active_set = ~free_set + free_set, = np.nonzero(free_set) + + r = A.dot(x) - b + cost = 0.5 * np.dot(r, r) + initial_cost = cost + g = A.T.dot(r) + + cost_change = None + step_norm = None + iteration = 0 + + if verbose == 2: + print_header_linear() + + # This is the initialization loop. The requirement is that the + # least-squares solution on free variables is feasible before BVLS starts. + # One possible initialization is to set all variables to lower or upper + # bounds, but many iterations may be required from this state later on. + # The implemented ad-hoc procedure which intuitively should give a better + # initial state: find the least-squares solution on current free variables, + # if its feasible then stop, otherwise, set violating variables to + # corresponding bounds and continue on the reduced set of free variables. + + while free_set.size > 0: + if verbose == 2: + optimality = compute_kkt_optimality(g, on_bound) + print_iteration_linear(iteration, cost, cost_change, step_norm, + optimality) + + iteration += 1 + x_free_old = x[free_set].copy() + + A_free = A[:, free_set] + b_free = b - A.dot(x * active_set) + z = lstsq(A_free, b_free, rcond=rcond)[0] + + lbv = z < lb[free_set] + ubv = z > ub[free_set] + v = lbv | ubv + + if np.any(lbv): + ind = free_set[lbv] + x[ind] = lb[ind] + active_set[ind] = True + on_bound[ind] = -1 + + if np.any(ubv): + ind = free_set[ubv] + x[ind] = ub[ind] + active_set[ind] = True + on_bound[ind] = 1 + + ind = free_set[~v] + x[ind] = z[~v] + + r = A.dot(x) - b + cost_new = 0.5 * np.dot(r, r) + cost_change = cost - cost_new + cost = cost_new + g = A.T.dot(r) + step_norm = norm(x[free_set] - x_free_old) + + if np.any(v): + free_set = free_set[~v] + else: + break + + if max_iter is None: + max_iter = n + max_iter += iteration + + termination_status = None + + # Main BVLS loop. + + optimality = compute_kkt_optimality(g, on_bound) + for iteration in range(iteration, max_iter): # BVLS Loop A + if verbose == 2: + print_iteration_linear(iteration, cost, cost_change, + step_norm, optimality) + + if optimality < tol: + termination_status = 1 + + if termination_status is not None: + break + + move_to_free = np.argmax(g * on_bound) + on_bound[move_to_free] = 0 + + while True: # BVLS Loop B + + free_set = on_bound == 0 + active_set = ~free_set + free_set, = np.nonzero(free_set) + + x_free = x[free_set] + x_free_old = x_free.copy() + lb_free = lb[free_set] + ub_free = ub[free_set] + + A_free = A[:, free_set] + b_free = b - A.dot(x * active_set) + z = lstsq(A_free, b_free, rcond=rcond)[0] + + lbv, = np.nonzero(z < lb_free) + ubv, = np.nonzero(z > ub_free) + v = np.hstack((lbv, ubv)) + + if v.size > 0: + alphas = np.hstack(( + lb_free[lbv] - x_free[lbv], + ub_free[ubv] - x_free[ubv])) / (z[v] - x_free[v]) + + i = np.argmin(alphas) + i_free = v[i] + alpha = alphas[i] + + x_free *= 1 - alpha + x_free += alpha * z + x[free_set] = x_free + + if i < lbv.size: + on_bound[free_set[i_free]] = -1 + else: + on_bound[free_set[i_free]] = 1 + else: + x_free = z + x[free_set] = x_free + break + + step_norm = norm(x_free - x_free_old) + + r = A.dot(x) - b + cost_new = 0.5 * np.dot(r, r) + cost_change = cost - cost_new + + if cost_change < tol * cost: + termination_status = 2 + cost = cost_new + + g = A.T.dot(r) + optimality = compute_kkt_optimality(g, on_bound) + + if termination_status is None: + termination_status = 0 + + return OptimizeResult( + x=x, fun=r, cost=cost, optimality=optimality, active_mask=on_bound, + nit=iteration + 1, status=termination_status, + initial_cost=initial_cost) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_lsq/common.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_lsq/common.py new file mode 100644 index 0000000000000000000000000000000000000000..0f8117f23ec1111d5205537c59931b165e2bfdaf --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_lsq/common.py @@ -0,0 +1,731 @@ +"""Functions used by least-squares algorithms.""" +from math import copysign + +import numpy as np +from numpy.linalg import norm + +from scipy.linalg import cho_factor, cho_solve, LinAlgError +from scipy.sparse import issparse +from scipy.sparse.linalg import LinearOperator, aslinearoperator + + +EPS = np.finfo(float).eps + + +# Functions related to a trust-region problem. + + +def intersect_trust_region(x, s, Delta): + """Find the intersection of a line with the boundary of a trust region. + + This function solves the quadratic equation with respect to t + ||(x + s*t)||**2 = Delta**2. + + Returns + ------- + t_neg, t_pos : tuple of float + Negative and positive roots. + + Raises + ------ + ValueError + If `s` is zero or `x` is not within the trust region. + """ + a = np.dot(s, s) + if a == 0: + raise ValueError("`s` is zero.") + + b = np.dot(x, s) + + c = np.dot(x, x) - Delta**2 + if c > 0: + raise ValueError("`x` is not within the trust region.") + + d = np.sqrt(b*b - a*c) # Root from one fourth of the discriminant. + + # Computations below avoid loss of significance, see "Numerical Recipes". + q = -(b + copysign(d, b)) + t1 = q / a + t2 = c / q + + if t1 < t2: + return t1, t2 + else: + return t2, t1 + + +def solve_lsq_trust_region(n, m, uf, s, V, Delta, initial_alpha=None, + rtol=0.01, max_iter=10): + """Solve a trust-region problem arising in least-squares minimization. + + This function implements a method described by J. J. More [1]_ and used + in MINPACK, but it relies on a single SVD of Jacobian instead of series + of Cholesky decompositions. Before running this function, compute: + ``U, s, VT = svd(J, full_matrices=False)``. + + Parameters + ---------- + n : int + Number of variables. + m : int + Number of residuals. + uf : ndarray + Computed as U.T.dot(f). + s : ndarray + Singular values of J. + V : ndarray + Transpose of VT. + Delta : float + Radius of a trust region. + initial_alpha : float, optional + Initial guess for alpha, which might be available from a previous + iteration. If None, determined automatically. + rtol : float, optional + Stopping tolerance for the root-finding procedure. Namely, the + solution ``p`` will satisfy ``abs(norm(p) - Delta) < rtol * Delta``. + max_iter : int, optional + Maximum allowed number of iterations for the root-finding procedure. + + Returns + ------- + p : ndarray, shape (n,) + Found solution of a trust-region problem. + alpha : float + Positive value such that (J.T*J + alpha*I)*p = -J.T*f. + Sometimes called Levenberg-Marquardt parameter. + n_iter : int + Number of iterations made by root-finding procedure. Zero means + that Gauss-Newton step was selected as the solution. + + References + ---------- + .. [1] More, J. J., "The Levenberg-Marquardt Algorithm: Implementation + and Theory," Numerical Analysis, ed. G. A. Watson, Lecture Notes + in Mathematics 630, Springer Verlag, pp. 105-116, 1977. + """ + def phi_and_derivative(alpha, suf, s, Delta): + """Function of which to find zero. + + It is defined as "norm of regularized (by alpha) least-squares + solution minus `Delta`". Refer to [1]_. + """ + denom = s**2 + alpha + p_norm = norm(suf / denom) + phi = p_norm - Delta + phi_prime = -np.sum(suf ** 2 / denom**3) / p_norm + return phi, phi_prime + + suf = s * uf + + # Check if J has full rank and try Gauss-Newton step. + if m >= n: + threshold = EPS * m * s[0] + full_rank = s[-1] > threshold + else: + full_rank = False + + if full_rank: + p = -V.dot(uf / s) + if norm(p) <= Delta: + return p, 0.0, 0 + + alpha_upper = norm(suf) / Delta + + if full_rank: + phi, phi_prime = phi_and_derivative(0.0, suf, s, Delta) + alpha_lower = -phi / phi_prime + else: + alpha_lower = 0.0 + + if initial_alpha is None or not full_rank and initial_alpha == 0: + alpha = max(0.001 * alpha_upper, (alpha_lower * alpha_upper)**0.5) + else: + alpha = initial_alpha + + for it in range(max_iter): + if alpha < alpha_lower or alpha > alpha_upper: + alpha = max(0.001 * alpha_upper, (alpha_lower * alpha_upper)**0.5) + + phi, phi_prime = phi_and_derivative(alpha, suf, s, Delta) + + if phi < 0: + alpha_upper = alpha + + ratio = phi / phi_prime + alpha_lower = max(alpha_lower, alpha - ratio) + alpha -= (phi + Delta) * ratio / Delta + + if np.abs(phi) < rtol * Delta: + break + + p = -V.dot(suf / (s**2 + alpha)) + + # Make the norm of p equal to Delta, p is changed only slightly during + # this. It is done to prevent p lie outside the trust region (which can + # cause problems later). + p *= Delta / norm(p) + + return p, alpha, it + 1 + + +def solve_trust_region_2d(B, g, Delta): + """Solve a general trust-region problem in 2 dimensions. + + The problem is reformulated as a 4th order algebraic equation, + the solution of which is found by numpy.roots. + + Parameters + ---------- + B : ndarray, shape (2, 2) + Symmetric matrix, defines a quadratic term of the function. + g : ndarray, shape (2,) + Defines a linear term of the function. + Delta : float + Radius of a trust region. + + Returns + ------- + p : ndarray, shape (2,) + Found solution. + newton_step : bool + Whether the returned solution is the Newton step which lies within + the trust region. + """ + try: + R, lower = cho_factor(B) + p = -cho_solve((R, lower), g) + if np.dot(p, p) <= Delta**2: + return p, True + except LinAlgError: + pass + + a = B[0, 0] * Delta**2 + b = B[0, 1] * Delta**2 + c = B[1, 1] * Delta**2 + + d = g[0] * Delta + f = g[1] * Delta + + coeffs = np.array( + [-b + d, 2 * (a - c + f), 6 * b, 2 * (-a + c + f), -b - d]) + t = np.roots(coeffs) # Can handle leading zeros. + t = np.real(t[np.isreal(t)]) + + p = Delta * np.vstack((2 * t / (1 + t**2), (1 - t**2) / (1 + t**2))) + value = 0.5 * np.sum(p * B.dot(p), axis=0) + np.dot(g, p) + i = np.argmin(value) + p = p[:, i] + + return p, False + + +def update_tr_radius(Delta, actual_reduction, predicted_reduction, + step_norm, bound_hit): + """Update the radius of a trust region based on the cost reduction. + + Returns + ------- + Delta : float + New radius. + ratio : float + Ratio between actual and predicted reductions. + """ + if predicted_reduction > 0: + ratio = actual_reduction / predicted_reduction + elif predicted_reduction == actual_reduction == 0: + ratio = 1 + else: + ratio = 0 + + if ratio < 0.25: + Delta = 0.25 * step_norm + elif ratio > 0.75 and bound_hit: + Delta *= 2.0 + + return Delta, ratio + + +# Construction and minimization of quadratic functions. + + +def build_quadratic_1d(J, g, s, diag=None, s0=None): + """Parameterize a multivariate quadratic function along a line. + + The resulting univariate quadratic function is given as follows:: + + f(t) = 0.5 * (s0 + s*t).T * (J.T*J + diag) * (s0 + s*t) + + g.T * (s0 + s*t) + + Parameters + ---------- + J : ndarray, sparse matrix or LinearOperator shape (m, n) + Jacobian matrix, affects the quadratic term. + g : ndarray, shape (n,) + Gradient, defines the linear term. + s : ndarray, shape (n,) + Direction vector of a line. + diag : None or ndarray with shape (n,), optional + Addition diagonal part, affects the quadratic term. + If None, assumed to be 0. + s0 : None or ndarray with shape (n,), optional + Initial point. If None, assumed to be 0. + + Returns + ------- + a : float + Coefficient for t**2. + b : float + Coefficient for t. + c : float + Free term. Returned only if `s0` is provided. + """ + v = J.dot(s) + a = np.dot(v, v) + if diag is not None: + a += np.dot(s * diag, s) + a *= 0.5 + + b = np.dot(g, s) + + if s0 is not None: + u = J.dot(s0) + b += np.dot(u, v) + c = 0.5 * np.dot(u, u) + np.dot(g, s0) + if diag is not None: + b += np.dot(s0 * diag, s) + c += 0.5 * np.dot(s0 * diag, s0) + return a, b, c + else: + return a, b + + +def minimize_quadratic_1d(a, b, lb, ub, c=0): + """Minimize a 1-D quadratic function subject to bounds. + + The free term `c` is 0 by default. Bounds must be finite. + + Returns + ------- + t : float + Minimum point. + y : float + Minimum value. + """ + t = [lb, ub] + if a != 0: + extremum = -0.5 * b / a + if lb < extremum < ub: + t.append(extremum) + t = np.asarray(t) + y = t * (a * t + b) + c + min_index = np.argmin(y) + return t[min_index], y[min_index] + + +def evaluate_quadratic(J, g, s, diag=None): + """Compute values of a quadratic function arising in least squares. + + The function is 0.5 * s.T * (J.T * J + diag) * s + g.T * s. + + Parameters + ---------- + J : ndarray, sparse matrix or LinearOperator, shape (m, n) + Jacobian matrix, affects the quadratic term. + g : ndarray, shape (n,) + Gradient, defines the linear term. + s : ndarray, shape (k, n) or (n,) + Array containing steps as rows. + diag : ndarray, shape (n,), optional + Addition diagonal part, affects the quadratic term. + If None, assumed to be 0. + + Returns + ------- + values : ndarray with shape (k,) or float + Values of the function. If `s` was 2-D, then ndarray is + returned, otherwise, float is returned. + """ + if s.ndim == 1: + Js = J.dot(s) + q = np.dot(Js, Js) + if diag is not None: + q += np.dot(s * diag, s) + else: + Js = J.dot(s.T) + q = np.sum(Js**2, axis=0) + if diag is not None: + q += np.sum(diag * s**2, axis=1) + + l = np.dot(s, g) + + return 0.5 * q + l + + +# Utility functions to work with bound constraints. + + +def in_bounds(x, lb, ub): + """Check if a point lies within bounds.""" + return np.all((x >= lb) & (x <= ub)) + + +def step_size_to_bound(x, s, lb, ub): + """Compute a min_step size required to reach a bound. + + The function computes a positive scalar t, such that x + s * t is on + the bound. + + Returns + ------- + step : float + Computed step. Non-negative value. + hits : ndarray of int with shape of x + Each element indicates whether a corresponding variable reaches the + bound: + + * 0 - the bound was not hit. + * -1 - the lower bound was hit. + * 1 - the upper bound was hit. + """ + non_zero = np.nonzero(s) + s_non_zero = s[non_zero] + steps = np.empty_like(x) + steps.fill(np.inf) + with np.errstate(over='ignore'): + steps[non_zero] = np.maximum((lb - x)[non_zero] / s_non_zero, + (ub - x)[non_zero] / s_non_zero) + min_step = np.min(steps) + return min_step, np.equal(steps, min_step) * np.sign(s).astype(int) + + +def find_active_constraints(x, lb, ub, rtol=1e-10): + """Determine which constraints are active in a given point. + + The threshold is computed using `rtol` and the absolute value of the + closest bound. + + Returns + ------- + active : ndarray of int with shape of x + Each component shows whether the corresponding constraint is active: + + * 0 - a constraint is not active. + * -1 - a lower bound is active. + * 1 - a upper bound is active. + """ + active = np.zeros_like(x, dtype=int) + + if rtol == 0: + active[x <= lb] = -1 + active[x >= ub] = 1 + return active + + lower_dist = x - lb + upper_dist = ub - x + + lower_threshold = rtol * np.maximum(1, np.abs(lb)) + upper_threshold = rtol * np.maximum(1, np.abs(ub)) + + lower_active = (np.isfinite(lb) & + (lower_dist <= np.minimum(upper_dist, lower_threshold))) + active[lower_active] = -1 + + upper_active = (np.isfinite(ub) & + (upper_dist <= np.minimum(lower_dist, upper_threshold))) + active[upper_active] = 1 + + return active + + +def make_strictly_feasible(x, lb, ub, rstep=1e-10): + """Shift a point to the interior of a feasible region. + + Each element of the returned vector is at least at a relative distance + `rstep` from the closest bound. If ``rstep=0`` then `np.nextafter` is used. + """ + x_new = x.copy() + + active = find_active_constraints(x, lb, ub, rstep) + lower_mask = np.equal(active, -1) + upper_mask = np.equal(active, 1) + + if rstep == 0: + x_new[lower_mask] = np.nextafter(lb[lower_mask], ub[lower_mask]) + x_new[upper_mask] = np.nextafter(ub[upper_mask], lb[upper_mask]) + else: + x_new[lower_mask] = (lb[lower_mask] + + rstep * np.maximum(1, np.abs(lb[lower_mask]))) + x_new[upper_mask] = (ub[upper_mask] - + rstep * np.maximum(1, np.abs(ub[upper_mask]))) + + tight_bounds = (x_new < lb) | (x_new > ub) + x_new[tight_bounds] = 0.5 * (lb[tight_bounds] + ub[tight_bounds]) + + return x_new + + +def CL_scaling_vector(x, g, lb, ub): + """Compute Coleman-Li scaling vector and its derivatives. + + Components of a vector v are defined as follows:: + + | ub[i] - x[i], if g[i] < 0 and ub[i] < np.inf + v[i] = | x[i] - lb[i], if g[i] > 0 and lb[i] > -np.inf + | 1, otherwise + + According to this definition v[i] >= 0 for all i. It differs from the + definition in paper [1]_ (eq. (2.2)), where the absolute value of v is + used. Both definitions are equivalent down the line. + Derivatives of v with respect to x take value 1, -1 or 0 depending on a + case. + + Returns + ------- + v : ndarray with shape of x + Scaling vector. + dv : ndarray with shape of x + Derivatives of v[i] with respect to x[i], diagonal elements of v's + Jacobian. + + References + ---------- + .. [1] M.A. Branch, T.F. Coleman, and Y. Li, "A Subspace, Interior, + and Conjugate Gradient Method for Large-Scale Bound-Constrained + Minimization Problems," SIAM Journal on Scientific Computing, + Vol. 21, Number 1, pp 1-23, 1999. + """ + v = np.ones_like(x) + dv = np.zeros_like(x) + + mask = (g < 0) & np.isfinite(ub) + v[mask] = ub[mask] - x[mask] + dv[mask] = -1 + + mask = (g > 0) & np.isfinite(lb) + v[mask] = x[mask] - lb[mask] + dv[mask] = 1 + + return v, dv + + +def reflective_transformation(y, lb, ub): + """Compute reflective transformation and its gradient.""" + if in_bounds(y, lb, ub): + return y, np.ones_like(y) + + lb_finite = np.isfinite(lb) + ub_finite = np.isfinite(ub) + + x = y.copy() + g_negative = np.zeros_like(y, dtype=bool) + + mask = lb_finite & ~ub_finite + x[mask] = np.maximum(y[mask], 2 * lb[mask] - y[mask]) + g_negative[mask] = y[mask] < lb[mask] + + mask = ~lb_finite & ub_finite + x[mask] = np.minimum(y[mask], 2 * ub[mask] - y[mask]) + g_negative[mask] = y[mask] > ub[mask] + + mask = lb_finite & ub_finite + d = ub - lb + t = np.remainder(y[mask] - lb[mask], 2 * d[mask]) + x[mask] = lb[mask] + np.minimum(t, 2 * d[mask] - t) + g_negative[mask] = t > d[mask] + + g = np.ones_like(y) + g[g_negative] = -1 + + return x, g + + +# Functions to display algorithm's progress. + + +def print_header_nonlinear(): + print("{:^15}{:^15}{:^15}{:^15}{:^15}{:^15}" + .format("Iteration", "Total nfev", "Cost", "Cost reduction", + "Step norm", "Optimality")) + + +def print_iteration_nonlinear(iteration, nfev, cost, cost_reduction, + step_norm, optimality): + if cost_reduction is None: + cost_reduction = " " * 15 + else: + cost_reduction = f"{cost_reduction:^15.2e}" + + if step_norm is None: + step_norm = " " * 15 + else: + step_norm = f"{step_norm:^15.2e}" + + print(f"{iteration:^15}{nfev:^15}{cost:^15.4e}{cost_reduction}{step_norm}{optimality:^15.2e}") + + +def print_header_linear(): + print("{:^15}{:^15}{:^15}{:^15}{:^15}" + .format("Iteration", "Cost", "Cost reduction", "Step norm", + "Optimality")) + + +def print_iteration_linear(iteration, cost, cost_reduction, step_norm, + optimality): + if cost_reduction is None: + cost_reduction = " " * 15 + else: + cost_reduction = f"{cost_reduction:^15.2e}" + + if step_norm is None: + step_norm = " " * 15 + else: + step_norm = f"{step_norm:^15.2e}" + + print(f"{iteration:^15}{cost:^15.4e}{cost_reduction}{step_norm}{optimality:^15.2e}") + + +# Simple helper functions. + + +def compute_grad(J, f): + """Compute gradient of the least-squares cost function.""" + if isinstance(J, LinearOperator): + return J.rmatvec(f) + else: + return J.T.dot(f) + + +def compute_jac_scale(J, scale_inv_old=None): + """Compute variables scale based on the Jacobian matrix.""" + if issparse(J): + scale_inv = np.asarray(J.power(2).sum(axis=0)).ravel()**0.5 + else: + scale_inv = np.sum(J**2, axis=0)**0.5 + + if scale_inv_old is None: + scale_inv[scale_inv == 0] = 1 + else: + scale_inv = np.maximum(scale_inv, scale_inv_old) + + return 1 / scale_inv, scale_inv + + +def left_multiplied_operator(J, d): + """Return diag(d) J as LinearOperator.""" + J = aslinearoperator(J) + + def matvec(x): + return d * J.matvec(x) + + def matmat(X): + return d[:, np.newaxis] * J.matmat(X) + + def rmatvec(x): + return J.rmatvec(x.ravel() * d) + + return LinearOperator(J.shape, matvec=matvec, matmat=matmat, + rmatvec=rmatvec) + + +def right_multiplied_operator(J, d): + """Return J diag(d) as LinearOperator.""" + J = aslinearoperator(J) + + def matvec(x): + return J.matvec(np.ravel(x) * d) + + def matmat(X): + return J.matmat(X * d[:, np.newaxis]) + + def rmatvec(x): + return d * J.rmatvec(x) + + return LinearOperator(J.shape, matvec=matvec, matmat=matmat, + rmatvec=rmatvec) + + +def regularized_lsq_operator(J, diag): + """Return a matrix arising in regularized least squares as LinearOperator. + + The matrix is + [ J ] + [ D ] + where D is diagonal matrix with elements from `diag`. + """ + J = aslinearoperator(J) + m, n = J.shape + + def matvec(x): + return np.hstack((J.matvec(x), diag * x)) + + def rmatvec(x): + x1 = x[:m] + x2 = x[m:] + return J.rmatvec(x1) + diag * x2 + + return LinearOperator((m + n, n), matvec=matvec, rmatvec=rmatvec) + + +def right_multiply(J, d, copy=True): + """Compute J diag(d). + + If `copy` is False, `J` is modified in place (unless being LinearOperator). + """ + if copy and not isinstance(J, LinearOperator): + J = J.copy() + + if issparse(J): + J.data *= d.take(J.indices, mode='clip') # scikit-learn recipe. + elif isinstance(J, LinearOperator): + J = right_multiplied_operator(J, d) + else: + J *= d + + return J + + +def left_multiply(J, d, copy=True): + """Compute diag(d) J. + + If `copy` is False, `J` is modified in place (unless being LinearOperator). + """ + if copy and not isinstance(J, LinearOperator): + J = J.copy() + + if issparse(J): + J.data *= np.repeat(d, np.diff(J.indptr)) # scikit-learn recipe. + elif isinstance(J, LinearOperator): + J = left_multiplied_operator(J, d) + else: + J *= d[:, np.newaxis] + + return J + + +def check_termination(dF, F, dx_norm, x_norm, ratio, ftol, xtol): + """Check termination condition for nonlinear least squares.""" + ftol_satisfied = dF < ftol * F and ratio > 0.25 + xtol_satisfied = dx_norm < xtol * (xtol + x_norm) + + if ftol_satisfied and xtol_satisfied: + return 4 + elif ftol_satisfied: + return 2 + elif xtol_satisfied: + return 3 + else: + return None + + +def scale_for_robust_loss_function(J, f, rho): + """Scale Jacobian and residuals for a robust loss function. + + Arrays are modified in place. + """ + J_scale = rho[1] + 2 * rho[2] * f**2 + J_scale[J_scale < EPS] = EPS + J_scale **= 0.5 + + f *= rho[1] / J_scale + + return left_multiply(J, J_scale, copy=False), f diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_lsq/dogbox.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_lsq/dogbox.py new file mode 100644 index 0000000000000000000000000000000000000000..6bb5abbe79028afed7b110603a0d5dfd6affae7f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_lsq/dogbox.py @@ -0,0 +1,331 @@ +""" +Dogleg algorithm with rectangular trust regions for least-squares minimization. + +The description of the algorithm can be found in [Voglis]_. The algorithm does +trust-region iterations, but the shape of trust regions is rectangular as +opposed to conventional elliptical. The intersection of a trust region and +an initial feasible region is again some rectangle. Thus, on each iteration a +bound-constrained quadratic optimization problem is solved. + +A quadratic problem is solved by well-known dogleg approach, where the +function is minimized along piecewise-linear "dogleg" path [NumOpt]_, +Chapter 4. If Jacobian is not rank-deficient then the function is decreasing +along this path, and optimization amounts to simply following along this +path as long as a point stays within the bounds. A constrained Cauchy step +(along the anti-gradient) is considered for safety in rank deficient cases, +in this situations the convergence might be slow. + +If during iterations some variable hit the initial bound and the component +of anti-gradient points outside the feasible region, then a next dogleg step +won't make any progress. At this state such variables satisfy first-order +optimality conditions and they are excluded before computing a next dogleg +step. + +Gauss-Newton step can be computed exactly by `numpy.linalg.lstsq` (for dense +Jacobian matrices) or by iterative procedure `scipy.sparse.linalg.lsmr` (for +dense and sparse matrices, or Jacobian being LinearOperator). The second +option allows to solve very large problems (up to couple of millions of +residuals on a regular PC), provided the Jacobian matrix is sufficiently +sparse. But note that dogbox is not very good for solving problems with +large number of constraints, because of variables exclusion-inclusion on each +iteration (a required number of function evaluations might be high or accuracy +of a solution will be poor), thus its large-scale usage is probably limited +to unconstrained problems. + +References +---------- +.. [Voglis] C. Voglis and I. E. Lagaris, "A Rectangular Trust Region Dogleg + Approach for Unconstrained and Bound Constrained Nonlinear + Optimization", WSEAS International Conference on Applied + Mathematics, Corfu, Greece, 2004. +.. [NumOpt] J. Nocedal and S. J. Wright, "Numerical optimization, 2nd edition". +""" +import numpy as np +from numpy.linalg import lstsq, norm + +from scipy.sparse.linalg import LinearOperator, aslinearoperator, lsmr +from scipy.optimize import OptimizeResult + +from .common import ( + step_size_to_bound, in_bounds, update_tr_radius, evaluate_quadratic, + build_quadratic_1d, minimize_quadratic_1d, compute_grad, + compute_jac_scale, check_termination, scale_for_robust_loss_function, + print_header_nonlinear, print_iteration_nonlinear) + + +def lsmr_operator(Jop, d, active_set): + """Compute LinearOperator to use in LSMR by dogbox algorithm. + + `active_set` mask is used to excluded active variables from computations + of matrix-vector products. + """ + m, n = Jop.shape + + def matvec(x): + x_free = x.ravel().copy() + x_free[active_set] = 0 + return Jop.matvec(x * d) + + def rmatvec(x): + r = d * Jop.rmatvec(x) + r[active_set] = 0 + return r + + return LinearOperator((m, n), matvec=matvec, rmatvec=rmatvec, dtype=float) + + +def find_intersection(x, tr_bounds, lb, ub): + """Find intersection of trust-region bounds and initial bounds. + + Returns + ------- + lb_total, ub_total : ndarray with shape of x + Lower and upper bounds of the intersection region. + orig_l, orig_u : ndarray of bool with shape of x + True means that an original bound is taken as a corresponding bound + in the intersection region. + tr_l, tr_u : ndarray of bool with shape of x + True means that a trust-region bound is taken as a corresponding bound + in the intersection region. + """ + lb_centered = lb - x + ub_centered = ub - x + + lb_total = np.maximum(lb_centered, -tr_bounds) + ub_total = np.minimum(ub_centered, tr_bounds) + + orig_l = np.equal(lb_total, lb_centered) + orig_u = np.equal(ub_total, ub_centered) + + tr_l = np.equal(lb_total, -tr_bounds) + tr_u = np.equal(ub_total, tr_bounds) + + return lb_total, ub_total, orig_l, orig_u, tr_l, tr_u + + +def dogleg_step(x, newton_step, g, a, b, tr_bounds, lb, ub): + """Find dogleg step in a rectangular region. + + Returns + ------- + step : ndarray, shape (n,) + Computed dogleg step. + bound_hits : ndarray of int, shape (n,) + Each component shows whether a corresponding variable hits the + initial bound after the step is taken: + * 0 - a variable doesn't hit the bound. + * -1 - lower bound is hit. + * 1 - upper bound is hit. + tr_hit : bool + Whether the step hit the boundary of the trust-region. + """ + lb_total, ub_total, orig_l, orig_u, tr_l, tr_u = find_intersection( + x, tr_bounds, lb, ub + ) + bound_hits = np.zeros_like(x, dtype=int) + + if in_bounds(newton_step, lb_total, ub_total): + return newton_step, bound_hits, False + + to_bounds, _ = step_size_to_bound(np.zeros_like(x), -g, lb_total, ub_total) + + # The classical dogleg algorithm would check if Cauchy step fits into + # the bounds, and just return it constrained version if not. But in a + # rectangular trust region it makes sense to try to improve constrained + # Cauchy step too. Thus, we don't distinguish these two cases. + + cauchy_step = -minimize_quadratic_1d(a, b, 0, to_bounds)[0] * g + + step_diff = newton_step - cauchy_step + step_size, hits = step_size_to_bound(cauchy_step, step_diff, + lb_total, ub_total) + bound_hits[(hits < 0) & orig_l] = -1 + bound_hits[(hits > 0) & orig_u] = 1 + tr_hit = np.any((hits < 0) & tr_l | (hits > 0) & tr_u) + + return cauchy_step + step_size * step_diff, bound_hits, tr_hit + + +def dogbox(fun, jac, x0, f0, J0, lb, ub, ftol, xtol, gtol, max_nfev, x_scale, + loss_function, tr_solver, tr_options, verbose): + f = f0 + f_true = f.copy() + nfev = 1 + + J = J0 + njev = 1 + + if loss_function is not None: + rho = loss_function(f) + cost = 0.5 * np.sum(rho[0]) + J, f = scale_for_robust_loss_function(J, f, rho) + else: + cost = 0.5 * np.dot(f, f) + + g = compute_grad(J, f) + + jac_scale = isinstance(x_scale, str) and x_scale == 'jac' + if jac_scale: + scale, scale_inv = compute_jac_scale(J) + else: + scale, scale_inv = x_scale, 1 / x_scale + + Delta = norm(x0 * scale_inv, ord=np.inf) + if Delta == 0: + Delta = 1.0 + + on_bound = np.zeros_like(x0, dtype=int) + on_bound[np.equal(x0, lb)] = -1 + on_bound[np.equal(x0, ub)] = 1 + + x = x0 + step = np.empty_like(x0) + + if max_nfev is None: + max_nfev = x0.size * 100 + + termination_status = None + iteration = 0 + step_norm = None + actual_reduction = None + + if verbose == 2: + print_header_nonlinear() + + while True: + active_set = on_bound * g < 0 + free_set = ~active_set + + g_free = g[free_set] + g_full = g.copy() + g[active_set] = 0 + + g_norm = norm(g, ord=np.inf) + if g_norm < gtol: + termination_status = 1 + + if verbose == 2: + print_iteration_nonlinear(iteration, nfev, cost, actual_reduction, + step_norm, g_norm) + + if termination_status is not None or nfev == max_nfev: + break + + x_free = x[free_set] + lb_free = lb[free_set] + ub_free = ub[free_set] + scale_free = scale[free_set] + + # Compute (Gauss-)Newton and build quadratic model for Cauchy step. + if tr_solver == 'exact': + J_free = J[:, free_set] + newton_step = lstsq(J_free, -f, rcond=-1)[0] + + # Coefficients for the quadratic model along the anti-gradient. + a, b = build_quadratic_1d(J_free, g_free, -g_free) + elif tr_solver == 'lsmr': + Jop = aslinearoperator(J) + + # We compute lsmr step in scaled variables and then + # transform back to normal variables, if lsmr would give exact lsq + # solution, this would be equivalent to not doing any + # transformations, but from experience it's better this way. + + # We pass active_set to make computations as if we selected + # the free subset of J columns, but without actually doing any + # slicing, which is expensive for sparse matrices and impossible + # for LinearOperator. + + lsmr_op = lsmr_operator(Jop, scale, active_set) + newton_step = -lsmr(lsmr_op, f, **tr_options)[0][free_set] + newton_step *= scale_free + + # Components of g for active variables were zeroed, so this call + # is correct and equivalent to using J_free and g_free. + a, b = build_quadratic_1d(Jop, g, -g) + + actual_reduction = -1.0 + while actual_reduction <= 0 and nfev < max_nfev: + tr_bounds = Delta * scale_free + + step_free, on_bound_free, tr_hit = dogleg_step( + x_free, newton_step, g_free, a, b, tr_bounds, lb_free, ub_free) + + step.fill(0.0) + step[free_set] = step_free + + if tr_solver == 'exact': + predicted_reduction = -evaluate_quadratic(J_free, g_free, + step_free) + elif tr_solver == 'lsmr': + predicted_reduction = -evaluate_quadratic(Jop, g, step) + + # gh11403 ensure that solution is fully within bounds. + x_new = np.clip(x + step, lb, ub) + + f_new = fun(x_new) + nfev += 1 + + step_h_norm = norm(step * scale_inv, ord=np.inf) + + if not np.all(np.isfinite(f_new)): + Delta = 0.25 * step_h_norm + continue + + # Usual trust-region step quality estimation. + if loss_function is not None: + cost_new = loss_function(f_new, cost_only=True) + else: + cost_new = 0.5 * np.dot(f_new, f_new) + actual_reduction = cost - cost_new + + Delta, ratio = update_tr_radius( + Delta, actual_reduction, predicted_reduction, + step_h_norm, tr_hit + ) + + step_norm = norm(step) + termination_status = check_termination( + actual_reduction, cost, step_norm, norm(x), ratio, ftol, xtol) + + if termination_status is not None: + break + + if actual_reduction > 0: + on_bound[free_set] = on_bound_free + + x = x_new + # Set variables exactly at the boundary. + mask = on_bound == -1 + x[mask] = lb[mask] + mask = on_bound == 1 + x[mask] = ub[mask] + + f = f_new + f_true = f.copy() + + cost = cost_new + + J = jac(x, f) + njev += 1 + + if loss_function is not None: + rho = loss_function(f) + J, f = scale_for_robust_loss_function(J, f, rho) + + g = compute_grad(J, f) + + if jac_scale: + scale, scale_inv = compute_jac_scale(J, scale_inv) + else: + step_norm = 0 + actual_reduction = 0 + + iteration += 1 + + if termination_status is None: + termination_status = 0 + + return OptimizeResult( + x=x, cost=cost, fun=f_true, jac=J, grad=g_full, optimality=g_norm, + active_mask=on_bound, nfev=nfev, njev=njev, status=termination_status) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_lsq/least_squares.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_lsq/least_squares.py new file mode 100644 index 0000000000000000000000000000000000000000..1595e40d16a01b8355510c4721ca0fb6b5b23b4a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_lsq/least_squares.py @@ -0,0 +1,972 @@ +"""Generic interface for least-squares minimization.""" +from warnings import warn + +import numpy as np +from numpy.linalg import norm + +from scipy.sparse import issparse +from scipy.sparse.linalg import LinearOperator +from scipy.optimize import _minpack, OptimizeResult +from scipy.optimize._numdiff import approx_derivative, group_columns +from scipy.optimize._minimize import Bounds + +from .trf import trf +from .dogbox import dogbox +from .common import EPS, in_bounds, make_strictly_feasible + + +TERMINATION_MESSAGES = { + -1: "Improper input parameters status returned from `leastsq`", + 0: "The maximum number of function evaluations is exceeded.", + 1: "`gtol` termination condition is satisfied.", + 2: "`ftol` termination condition is satisfied.", + 3: "`xtol` termination condition is satisfied.", + 4: "Both `ftol` and `xtol` termination conditions are satisfied." +} + + +FROM_MINPACK_TO_COMMON = { + 0: -1, # Improper input parameters from MINPACK. + 1: 2, + 2: 3, + 3: 4, + 4: 1, + 5: 0 + # There are 6, 7, 8 for too small tolerance parameters, + # but we guard against it by checking ftol, xtol, gtol beforehand. +} + + +def call_minpack(fun, x0, jac, ftol, xtol, gtol, max_nfev, x_scale, diff_step): + n = x0.size + + if diff_step is None: + epsfcn = EPS + else: + epsfcn = diff_step**2 + + # Compute MINPACK's `diag`, which is inverse of our `x_scale` and + # ``x_scale='jac'`` corresponds to ``diag=None``. + if isinstance(x_scale, str) and x_scale == 'jac': + diag = None + else: + diag = 1 / x_scale + + full_output = True + col_deriv = False + factor = 100.0 + + if jac is None: + if max_nfev is None: + # n squared to account for Jacobian evaluations. + max_nfev = 100 * n * (n + 1) + x, info, status = _minpack._lmdif( + fun, x0, (), full_output, ftol, xtol, gtol, + max_nfev, epsfcn, factor, diag) + else: + if max_nfev is None: + max_nfev = 100 * n + x, info, status = _minpack._lmder( + fun, jac, x0, (), full_output, col_deriv, + ftol, xtol, gtol, max_nfev, factor, diag) + + f = info['fvec'] + + if callable(jac): + J = jac(x) + else: + J = np.atleast_2d(approx_derivative(fun, x)) + + cost = 0.5 * np.dot(f, f) + g = J.T.dot(f) + g_norm = norm(g, ord=np.inf) + + nfev = info['nfev'] + njev = info.get('njev', None) + + status = FROM_MINPACK_TO_COMMON[status] + active_mask = np.zeros_like(x0, dtype=int) + + return OptimizeResult( + x=x, cost=cost, fun=f, jac=J, grad=g, optimality=g_norm, + active_mask=active_mask, nfev=nfev, njev=njev, status=status) + + +def prepare_bounds(bounds, n): + lb, ub = (np.asarray(b, dtype=float) for b in bounds) + if lb.ndim == 0: + lb = np.resize(lb, n) + + if ub.ndim == 0: + ub = np.resize(ub, n) + + return lb, ub + + +def check_tolerance(ftol, xtol, gtol, method): + def check(tol, name): + if tol is None: + tol = 0 + elif tol < EPS: + warn(f"Setting `{name}` below the machine epsilon ({EPS:.2e}) effectively " + f"disables the corresponding termination condition.", + stacklevel=3) + return tol + + ftol = check(ftol, "ftol") + xtol = check(xtol, "xtol") + gtol = check(gtol, "gtol") + + if method == "lm" and (ftol < EPS or xtol < EPS or gtol < EPS): + raise ValueError("All tolerances must be higher than machine epsilon " + f"({EPS:.2e}) for method 'lm'.") + elif ftol < EPS and xtol < EPS and gtol < EPS: + raise ValueError("At least one of the tolerances must be higher than " + f"machine epsilon ({EPS:.2e}).") + + return ftol, xtol, gtol + + +def check_x_scale(x_scale, x0): + if isinstance(x_scale, str) and x_scale == 'jac': + return x_scale + + try: + x_scale = np.asarray(x_scale, dtype=float) + valid = np.all(np.isfinite(x_scale)) and np.all(x_scale > 0) + except (ValueError, TypeError): + valid = False + + if not valid: + raise ValueError("`x_scale` must be 'jac' or array_like with " + "positive numbers.") + + if x_scale.ndim == 0: + x_scale = np.resize(x_scale, x0.shape) + + if x_scale.shape != x0.shape: + raise ValueError("Inconsistent shapes between `x_scale` and `x0`.") + + return x_scale + + +def check_jac_sparsity(jac_sparsity, m, n): + if jac_sparsity is None: + return None + + if not issparse(jac_sparsity): + jac_sparsity = np.atleast_2d(jac_sparsity) + + if jac_sparsity.shape != (m, n): + raise ValueError("`jac_sparsity` has wrong shape.") + + return jac_sparsity, group_columns(jac_sparsity) + + +# Loss functions. + + +def huber(z, rho, cost_only): + mask = z <= 1 + rho[0, mask] = z[mask] + rho[0, ~mask] = 2 * z[~mask]**0.5 - 1 + if cost_only: + return + rho[1, mask] = 1 + rho[1, ~mask] = z[~mask]**-0.5 + rho[2, mask] = 0 + rho[2, ~mask] = -0.5 * z[~mask]**-1.5 + + +def soft_l1(z, rho, cost_only): + t = 1 + z + rho[0] = 2 * (t**0.5 - 1) + if cost_only: + return + rho[1] = t**-0.5 + rho[2] = -0.5 * t**-1.5 + + +def cauchy(z, rho, cost_only): + rho[0] = np.log1p(z) + if cost_only: + return + t = 1 + z + rho[1] = 1 / t + rho[2] = -1 / t**2 + + +def arctan(z, rho, cost_only): + rho[0] = np.arctan(z) + if cost_only: + return + t = 1 + z**2 + rho[1] = 1 / t + rho[2] = -2 * z / t**2 + + +IMPLEMENTED_LOSSES = dict(linear=None, huber=huber, soft_l1=soft_l1, + cauchy=cauchy, arctan=arctan) + + +def construct_loss_function(m, loss, f_scale): + if loss == 'linear': + return None + + if not callable(loss): + loss = IMPLEMENTED_LOSSES[loss] + rho = np.empty((3, m)) + + def loss_function(f, cost_only=False): + z = (f / f_scale) ** 2 + loss(z, rho, cost_only=cost_only) + if cost_only: + return 0.5 * f_scale ** 2 * np.sum(rho[0]) + rho[0] *= f_scale ** 2 + rho[2] /= f_scale ** 2 + return rho + else: + def loss_function(f, cost_only=False): + z = (f / f_scale) ** 2 + rho = loss(z) + if cost_only: + return 0.5 * f_scale ** 2 * np.sum(rho[0]) + rho[0] *= f_scale ** 2 + rho[2] /= f_scale ** 2 + return rho + + return loss_function + + +def least_squares( + fun, x0, jac='2-point', bounds=(-np.inf, np.inf), method='trf', + ftol=1e-8, xtol=1e-8, gtol=1e-8, x_scale=1.0, loss='linear', + f_scale=1.0, diff_step=None, tr_solver=None, tr_options=None, + jac_sparsity=None, max_nfev=None, verbose=0, args=(), kwargs=None): + """Solve a nonlinear least-squares problem with bounds on the variables. + + Given the residuals f(x) (an m-D real function of n real + variables) and the loss function rho(s) (a scalar function), `least_squares` + finds a local minimum of the cost function F(x):: + + minimize F(x) = 0.5 * sum(rho(f_i(x)**2), i = 0, ..., m - 1) + subject to lb <= x <= ub + + The purpose of the loss function rho(s) is to reduce the influence of + outliers on the solution. + + Parameters + ---------- + fun : callable + Function which computes the vector of residuals, with the signature + ``fun(x, *args, **kwargs)``, i.e., the minimization proceeds with + respect to its first argument. The argument ``x`` passed to this + function is an ndarray of shape (n,) (never a scalar, even for n=1). + It must allocate and return a 1-D array_like of shape (m,) or a scalar. + If the argument ``x`` is complex or the function ``fun`` returns + complex residuals, it must be wrapped in a real function of real + arguments, as shown at the end of the Examples section. + x0 : array_like with shape (n,) or float + Initial guess on independent variables. If float, it will be treated + as a 1-D array with one element. When `method` is 'trf', the initial + guess might be slightly adjusted to lie sufficiently within the given + `bounds`. + jac : {'2-point', '3-point', 'cs', callable}, optional + Method of computing the Jacobian matrix (an m-by-n matrix, where + element (i, j) is the partial derivative of f[i] with respect to + x[j]). The keywords select a finite difference scheme for numerical + estimation. The scheme '3-point' is more accurate, but requires + twice as many operations as '2-point' (default). The scheme 'cs' + uses complex steps, and while potentially the most accurate, it is + applicable only when `fun` correctly handles complex inputs and + can be analytically continued to the complex plane. Method 'lm' + always uses the '2-point' scheme. If callable, it is used as + ``jac(x, *args, **kwargs)`` and should return a good approximation + (or the exact value) for the Jacobian as an array_like (np.atleast_2d + is applied), a sparse matrix (csr_matrix preferred for performance) or + a `scipy.sparse.linalg.LinearOperator`. + bounds : 2-tuple of array_like or `Bounds`, optional + There are two ways to specify bounds: + + 1. Instance of `Bounds` class + 2. Lower and upper bounds on independent variables. Defaults to no + bounds. Each array must match the size of `x0` or be a scalar, + in the latter case a bound will be the same for all variables. + Use ``np.inf`` with an appropriate sign to disable bounds on all + or some variables. + + method : {'trf', 'dogbox', 'lm'}, optional + Algorithm to perform minimization. + + * 'trf' : Trust Region Reflective algorithm, particularly suitable + for large sparse problems with bounds. Generally robust method. + * 'dogbox' : dogleg algorithm with rectangular trust regions, + typical use case is small problems with bounds. Not recommended + for problems with rank-deficient Jacobian. + * 'lm' : Levenberg-Marquardt algorithm as implemented in MINPACK. + Doesn't handle bounds and sparse Jacobians. Usually the most + efficient method for small unconstrained problems. + + Default is 'trf'. See Notes for more information. + ftol : float or None, optional + Tolerance for termination by the change of the cost function. Default + is 1e-8. The optimization process is stopped when ``dF < ftol * F``, + and there was an adequate agreement between a local quadratic model and + the true model in the last step. + + If None and 'method' is not 'lm', the termination by this condition is + disabled. If 'method' is 'lm', this tolerance must be higher than + machine epsilon. + xtol : float or None, optional + Tolerance for termination by the change of the independent variables. + Default is 1e-8. The exact condition depends on the `method` used: + + * For 'trf' and 'dogbox' : ``norm(dx) < xtol * (xtol + norm(x))``. + * For 'lm' : ``Delta < xtol * norm(xs)``, where ``Delta`` is + a trust-region radius and ``xs`` is the value of ``x`` + scaled according to `x_scale` parameter (see below). + + If None and 'method' is not 'lm', the termination by this condition is + disabled. If 'method' is 'lm', this tolerance must be higher than + machine epsilon. + gtol : float or None, optional + Tolerance for termination by the norm of the gradient. Default is 1e-8. + The exact condition depends on a `method` used: + + * For 'trf' : ``norm(g_scaled, ord=np.inf) < gtol``, where + ``g_scaled`` is the value of the gradient scaled to account for + the presence of the bounds [STIR]_. + * For 'dogbox' : ``norm(g_free, ord=np.inf) < gtol``, where + ``g_free`` is the gradient with respect to the variables which + are not in the optimal state on the boundary. + * For 'lm' : the maximum absolute value of the cosine of angles + between columns of the Jacobian and the residual vector is less + than `gtol`, or the residual vector is zero. + + If None and 'method' is not 'lm', the termination by this condition is + disabled. If 'method' is 'lm', this tolerance must be higher than + machine epsilon. + x_scale : array_like or 'jac', optional + Characteristic scale of each variable. Setting `x_scale` is equivalent + to reformulating the problem in scaled variables ``xs = x / x_scale``. + An alternative view is that the size of a trust region along jth + dimension is proportional to ``x_scale[j]``. Improved convergence may + be achieved by setting `x_scale` such that a step of a given size + along any of the scaled variables has a similar effect on the cost + function. If set to 'jac', the scale is iteratively updated using the + inverse norms of the columns of the Jacobian matrix (as described in + [JJMore]_). + loss : str or callable, optional + Determines the loss function. The following keyword values are allowed: + + * 'linear' (default) : ``rho(z) = z``. Gives a standard + least-squares problem. + * 'soft_l1' : ``rho(z) = 2 * ((1 + z)**0.5 - 1)``. The smooth + approximation of l1 (absolute value) loss. Usually a good + choice for robust least squares. + * 'huber' : ``rho(z) = z if z <= 1 else 2*z**0.5 - 1``. Works + similarly to 'soft_l1'. + * 'cauchy' : ``rho(z) = ln(1 + z)``. Severely weakens outliers + influence, but may cause difficulties in optimization process. + * 'arctan' : ``rho(z) = arctan(z)``. Limits a maximum loss on + a single residual, has properties similar to 'cauchy'. + + If callable, it must take a 1-D ndarray ``z=f**2`` and return an + array_like with shape (3, m) where row 0 contains function values, + row 1 contains first derivatives and row 2 contains second + derivatives. Method 'lm' supports only 'linear' loss. + f_scale : float, optional + Value of soft margin between inlier and outlier residuals, default + is 1.0. The loss function is evaluated as follows + ``rho_(f**2) = C**2 * rho(f**2 / C**2)``, where ``C`` is `f_scale`, + and ``rho`` is determined by `loss` parameter. This parameter has + no effect with ``loss='linear'``, but for other `loss` values it is + of crucial importance. + max_nfev : None or int, optional + Maximum number of function evaluations before the termination. + If None (default), the value is chosen automatically: + + * For 'trf' and 'dogbox' : 100 * n. + * For 'lm' : 100 * n if `jac` is callable and 100 * n * (n + 1) + otherwise (because 'lm' counts function calls in Jacobian + estimation). + + diff_step : None or array_like, optional + Determines the relative step size for the finite difference + approximation of the Jacobian. The actual step is computed as + ``x * diff_step``. If None (default), then `diff_step` is taken to be + a conventional "optimal" power of machine epsilon for the finite + difference scheme used [NR]_. + tr_solver : {None, 'exact', 'lsmr'}, optional + Method for solving trust-region subproblems, relevant only for 'trf' + and 'dogbox' methods. + + * 'exact' is suitable for not very large problems with dense + Jacobian matrices. The computational complexity per iteration is + comparable to a singular value decomposition of the Jacobian + matrix. + * 'lsmr' is suitable for problems with sparse and large Jacobian + matrices. It uses the iterative procedure + `scipy.sparse.linalg.lsmr` for finding a solution of a linear + least-squares problem and only requires matrix-vector product + evaluations. + + If None (default), the solver is chosen based on the type of Jacobian + returned on the first iteration. + tr_options : dict, optional + Keyword options passed to trust-region solver. + + * ``tr_solver='exact'``: `tr_options` are ignored. + * ``tr_solver='lsmr'``: options for `scipy.sparse.linalg.lsmr`. + Additionally, ``method='trf'`` supports 'regularize' option + (bool, default is True), which adds a regularization term to the + normal equation, which improves convergence if the Jacobian is + rank-deficient [Byrd]_ (eq. 3.4). + + jac_sparsity : {None, array_like, sparse matrix}, optional + Defines the sparsity structure of the Jacobian matrix for finite + difference estimation, its shape must be (m, n). If the Jacobian has + only few non-zero elements in *each* row, providing the sparsity + structure will greatly speed up the computations [Curtis]_. A zero + entry means that a corresponding element in the Jacobian is identically + zero. If provided, forces the use of 'lsmr' trust-region solver. + If None (default), then dense differencing will be used. Has no effect + for 'lm' method. + verbose : {0, 1, 2}, optional + Level of algorithm's verbosity: + + * 0 (default) : work silently. + * 1 : display a termination report. + * 2 : display progress during iterations (not supported by 'lm' + method). + + args, kwargs : tuple and dict, optional + Additional arguments passed to `fun` and `jac`. Both empty by default. + The calling signature is ``fun(x, *args, **kwargs)`` and the same for + `jac`. + + Returns + ------- + result : OptimizeResult + `OptimizeResult` with the following fields defined: + + x : ndarray, shape (n,) + Solution found. + cost : float + Value of the cost function at the solution. + fun : ndarray, shape (m,) + Vector of residuals at the solution. + jac : ndarray, sparse matrix or LinearOperator, shape (m, n) + Modified Jacobian matrix at the solution, in the sense that J^T J + is a Gauss-Newton approximation of the Hessian of the cost function. + The type is the same as the one used by the algorithm. + grad : ndarray, shape (m,) + Gradient of the cost function at the solution. + optimality : float + First-order optimality measure. In unconstrained problems, it is + always the uniform norm of the gradient. In constrained problems, + it is the quantity which was compared with `gtol` during iterations. + active_mask : ndarray of int, shape (n,) + Each component shows whether a corresponding constraint is active + (that is, whether a variable is at the bound): + + * 0 : a constraint is not active. + * -1 : a lower bound is active. + * 1 : an upper bound is active. + + Might be somewhat arbitrary for 'trf' method as it generates a + sequence of strictly feasible iterates and `active_mask` is + determined within a tolerance threshold. + nfev : int + Number of function evaluations done. Methods 'trf' and 'dogbox' do + not count function calls for numerical Jacobian approximation, as + opposed to 'lm' method. + njev : int or None + Number of Jacobian evaluations done. If numerical Jacobian + approximation is used in 'lm' method, it is set to None. + status : int + The reason for algorithm termination: + + * -1 : improper input parameters status returned from MINPACK. + * 0 : the maximum number of function evaluations is exceeded. + * 1 : `gtol` termination condition is satisfied. + * 2 : `ftol` termination condition is satisfied. + * 3 : `xtol` termination condition is satisfied. + * 4 : Both `ftol` and `xtol` termination conditions are satisfied. + + message : str + Verbal description of the termination reason. + success : bool + True if one of the convergence criteria is satisfied (`status` > 0). + + See Also + -------- + leastsq : A legacy wrapper for the MINPACK implementation of the + Levenberg-Marquadt algorithm. + curve_fit : Least-squares minimization applied to a curve-fitting problem. + + Notes + ----- + Method 'lm' (Levenberg-Marquardt) calls a wrapper over least-squares + algorithms implemented in MINPACK (lmder, lmdif). It runs the + Levenberg-Marquardt algorithm formulated as a trust-region type algorithm. + The implementation is based on paper [JJMore]_, it is very robust and + efficient with a lot of smart tricks. It should be your first choice + for unconstrained problems. Note that it doesn't support bounds. Also, + it doesn't work when m < n. + + Method 'trf' (Trust Region Reflective) is motivated by the process of + solving a system of equations, which constitute the first-order optimality + condition for a bound-constrained minimization problem as formulated in + [STIR]_. The algorithm iteratively solves trust-region subproblems + augmented by a special diagonal quadratic term and with trust-region shape + determined by the distance from the bounds and the direction of the + gradient. This enhancements help to avoid making steps directly into bounds + and efficiently explore the whole space of variables. To further improve + convergence, the algorithm considers search directions reflected from the + bounds. To obey theoretical requirements, the algorithm keeps iterates + strictly feasible. With dense Jacobians trust-region subproblems are + solved by an exact method very similar to the one described in [JJMore]_ + (and implemented in MINPACK). The difference from the MINPACK + implementation is that a singular value decomposition of a Jacobian + matrix is done once per iteration, instead of a QR decomposition and series + of Givens rotation eliminations. For large sparse Jacobians a 2-D subspace + approach of solving trust-region subproblems is used [STIR]_, [Byrd]_. + The subspace is spanned by a scaled gradient and an approximate + Gauss-Newton solution delivered by `scipy.sparse.linalg.lsmr`. When no + constraints are imposed the algorithm is very similar to MINPACK and has + generally comparable performance. The algorithm works quite robust in + unbounded and bounded problems, thus it is chosen as a default algorithm. + + Method 'dogbox' operates in a trust-region framework, but considers + rectangular trust regions as opposed to conventional ellipsoids [Voglis]_. + The intersection of a current trust region and initial bounds is again + rectangular, so on each iteration a quadratic minimization problem subject + to bound constraints is solved approximately by Powell's dogleg method + [NumOpt]_. The required Gauss-Newton step can be computed exactly for + dense Jacobians or approximately by `scipy.sparse.linalg.lsmr` for large + sparse Jacobians. The algorithm is likely to exhibit slow convergence when + the rank of Jacobian is less than the number of variables. The algorithm + often outperforms 'trf' in bounded problems with a small number of + variables. + + Robust loss functions are implemented as described in [BA]_. The idea + is to modify a residual vector and a Jacobian matrix on each iteration + such that computed gradient and Gauss-Newton Hessian approximation match + the true gradient and Hessian approximation of the cost function. Then + the algorithm proceeds in a normal way, i.e., robust loss functions are + implemented as a simple wrapper over standard least-squares algorithms. + + .. versionadded:: 0.17.0 + + References + ---------- + .. [STIR] M. A. Branch, T. F. Coleman, and Y. Li, "A Subspace, Interior, + and Conjugate Gradient Method for Large-Scale Bound-Constrained + Minimization Problems," SIAM Journal on Scientific Computing, + Vol. 21, Number 1, pp 1-23, 1999. + .. [NR] William H. Press et. al., "Numerical Recipes. The Art of Scientific + Computing. 3rd edition", Sec. 5.7. + .. [Byrd] R. H. Byrd, R. B. Schnabel and G. A. Shultz, "Approximate + solution of the trust region problem by minimization over + two-dimensional subspaces", Math. Programming, 40, pp. 247-263, + 1988. + .. [Curtis] A. Curtis, M. J. D. Powell, and J. Reid, "On the estimation of + sparse Jacobian matrices", Journal of the Institute of + Mathematics and its Applications, 13, pp. 117-120, 1974. + .. [JJMore] J. J. More, "The Levenberg-Marquardt Algorithm: Implementation + and Theory," Numerical Analysis, ed. G. A. Watson, Lecture + Notes in Mathematics 630, Springer Verlag, pp. 105-116, 1977. + .. [Voglis] C. Voglis and I. E. Lagaris, "A Rectangular Trust Region + Dogleg Approach for Unconstrained and Bound Constrained + Nonlinear Optimization", WSEAS International Conference on + Applied Mathematics, Corfu, Greece, 2004. + .. [NumOpt] J. Nocedal and S. J. Wright, "Numerical optimization, + 2nd edition", Chapter 4. + .. [BA] B. Triggs et. al., "Bundle Adjustment - A Modern Synthesis", + Proceedings of the International Workshop on Vision Algorithms: + Theory and Practice, pp. 298-372, 1999. + + Examples + -------- + In this example we find a minimum of the Rosenbrock function without bounds + on independent variables. + + >>> import numpy as np + >>> def fun_rosenbrock(x): + ... return np.array([10 * (x[1] - x[0]**2), (1 - x[0])]) + + Notice that we only provide the vector of the residuals. The algorithm + constructs the cost function as a sum of squares of the residuals, which + gives the Rosenbrock function. The exact minimum is at ``x = [1.0, 1.0]``. + + >>> from scipy.optimize import least_squares + >>> x0_rosenbrock = np.array([2, 2]) + >>> res_1 = least_squares(fun_rosenbrock, x0_rosenbrock) + >>> res_1.x + array([ 1., 1.]) + >>> res_1.cost + 9.8669242910846867e-30 + >>> res_1.optimality + 8.8928864934219529e-14 + + We now constrain the variables, in such a way that the previous solution + becomes infeasible. Specifically, we require that ``x[1] >= 1.5``, and + ``x[0]`` left unconstrained. To this end, we specify the `bounds` parameter + to `least_squares` in the form ``bounds=([-np.inf, 1.5], np.inf)``. + + We also provide the analytic Jacobian: + + >>> def jac_rosenbrock(x): + ... return np.array([ + ... [-20 * x[0], 10], + ... [-1, 0]]) + + Putting this all together, we see that the new solution lies on the bound: + + >>> res_2 = least_squares(fun_rosenbrock, x0_rosenbrock, jac_rosenbrock, + ... bounds=([-np.inf, 1.5], np.inf)) + >>> res_2.x + array([ 1.22437075, 1.5 ]) + >>> res_2.cost + 0.025213093946805685 + >>> res_2.optimality + 1.5885401433157753e-07 + + Now we solve a system of equations (i.e., the cost function should be zero + at a minimum) for a Broyden tridiagonal vector-valued function of 100000 + variables: + + >>> def fun_broyden(x): + ... f = (3 - x) * x + 1 + ... f[1:] -= x[:-1] + ... f[:-1] -= 2 * x[1:] + ... return f + + The corresponding Jacobian matrix is sparse. We tell the algorithm to + estimate it by finite differences and provide the sparsity structure of + Jacobian to significantly speed up this process. + + >>> from scipy.sparse import lil_matrix + >>> def sparsity_broyden(n): + ... sparsity = lil_matrix((n, n), dtype=int) + ... i = np.arange(n) + ... sparsity[i, i] = 1 + ... i = np.arange(1, n) + ... sparsity[i, i - 1] = 1 + ... i = np.arange(n - 1) + ... sparsity[i, i + 1] = 1 + ... return sparsity + ... + >>> n = 100000 + >>> x0_broyden = -np.ones(n) + ... + >>> res_3 = least_squares(fun_broyden, x0_broyden, + ... jac_sparsity=sparsity_broyden(n)) + >>> res_3.cost + 4.5687069299604613e-23 + >>> res_3.optimality + 1.1650454296851518e-11 + + Let's also solve a curve fitting problem using robust loss function to + take care of outliers in the data. Define the model function as + ``y = a + b * exp(c * t)``, where t is a predictor variable, y is an + observation and a, b, c are parameters to estimate. + + First, define the function which generates the data with noise and + outliers, define the model parameters, and generate data: + + >>> from numpy.random import default_rng + >>> rng = default_rng() + >>> def gen_data(t, a, b, c, noise=0., n_outliers=0, seed=None): + ... rng = default_rng(seed) + ... + ... y = a + b * np.exp(t * c) + ... + ... error = noise * rng.standard_normal(t.size) + ... outliers = rng.integers(0, t.size, n_outliers) + ... error[outliers] *= 10 + ... + ... return y + error + ... + >>> a = 0.5 + >>> b = 2.0 + >>> c = -1 + >>> t_min = 0 + >>> t_max = 10 + >>> n_points = 15 + ... + >>> t_train = np.linspace(t_min, t_max, n_points) + >>> y_train = gen_data(t_train, a, b, c, noise=0.1, n_outliers=3) + + Define function for computing residuals and initial estimate of + parameters. + + >>> def fun(x, t, y): + ... return x[0] + x[1] * np.exp(x[2] * t) - y + ... + >>> x0 = np.array([1.0, 1.0, 0.0]) + + Compute a standard least-squares solution: + + >>> res_lsq = least_squares(fun, x0, args=(t_train, y_train)) + + Now compute two solutions with two different robust loss functions. The + parameter `f_scale` is set to 0.1, meaning that inlier residuals should + not significantly exceed 0.1 (the noise level used). + + >>> res_soft_l1 = least_squares(fun, x0, loss='soft_l1', f_scale=0.1, + ... args=(t_train, y_train)) + >>> res_log = least_squares(fun, x0, loss='cauchy', f_scale=0.1, + ... args=(t_train, y_train)) + + And, finally, plot all the curves. We see that by selecting an appropriate + `loss` we can get estimates close to optimal even in the presence of + strong outliers. But keep in mind that generally it is recommended to try + 'soft_l1' or 'huber' losses first (if at all necessary) as the other two + options may cause difficulties in optimization process. + + >>> t_test = np.linspace(t_min, t_max, n_points * 10) + >>> y_true = gen_data(t_test, a, b, c) + >>> y_lsq = gen_data(t_test, *res_lsq.x) + >>> y_soft_l1 = gen_data(t_test, *res_soft_l1.x) + >>> y_log = gen_data(t_test, *res_log.x) + ... + >>> import matplotlib.pyplot as plt + >>> plt.plot(t_train, y_train, 'o') + >>> plt.plot(t_test, y_true, 'k', linewidth=2, label='true') + >>> plt.plot(t_test, y_lsq, label='linear loss') + >>> plt.plot(t_test, y_soft_l1, label='soft_l1 loss') + >>> plt.plot(t_test, y_log, label='cauchy loss') + >>> plt.xlabel("t") + >>> plt.ylabel("y") + >>> plt.legend() + >>> plt.show() + + In the next example, we show how complex-valued residual functions of + complex variables can be optimized with ``least_squares()``. Consider the + following function: + + >>> def f(z): + ... return z - (0.5 + 0.5j) + + We wrap it into a function of real variables that returns real residuals + by simply handling the real and imaginary parts as independent variables: + + >>> def f_wrap(x): + ... fx = f(x[0] + 1j*x[1]) + ... return np.array([fx.real, fx.imag]) + + Thus, instead of the original m-D complex function of n complex + variables we optimize a 2m-D real function of 2n real variables: + + >>> from scipy.optimize import least_squares + >>> res_wrapped = least_squares(f_wrap, (0.1, 0.1), bounds=([0, 0], [1, 1])) + >>> z = res_wrapped.x[0] + res_wrapped.x[1]*1j + >>> z + (0.49999999999925893+0.49999999999925893j) + + """ + if method not in ['trf', 'dogbox', 'lm']: + raise ValueError("`method` must be 'trf', 'dogbox' or 'lm'.") + + if jac not in ['2-point', '3-point', 'cs'] and not callable(jac): + raise ValueError("`jac` must be '2-point', '3-point', 'cs' or " + "callable.") + + if tr_solver not in [None, 'exact', 'lsmr']: + raise ValueError("`tr_solver` must be None, 'exact' or 'lsmr'.") + + if loss not in IMPLEMENTED_LOSSES and not callable(loss): + raise ValueError(f"`loss` must be one of {IMPLEMENTED_LOSSES.keys()}" + " or a callable.") + + if method == 'lm' and loss != 'linear': + raise ValueError("method='lm' supports only 'linear' loss function.") + + if verbose not in [0, 1, 2]: + raise ValueError("`verbose` must be in [0, 1, 2].") + + if max_nfev is not None and max_nfev <= 0: + raise ValueError("`max_nfev` must be None or positive integer.") + + if np.iscomplexobj(x0): + raise ValueError("`x0` must be real.") + + x0 = np.atleast_1d(x0).astype(float) + + if x0.ndim > 1: + raise ValueError("`x0` must have at most 1 dimension.") + + if isinstance(bounds, Bounds): + lb, ub = bounds.lb, bounds.ub + bounds = (lb, ub) + else: + if len(bounds) == 2: + lb, ub = prepare_bounds(bounds, x0.shape[0]) + else: + raise ValueError("`bounds` must contain 2 elements.") + + if method == 'lm' and not np.all((lb == -np.inf) & (ub == np.inf)): + raise ValueError("Method 'lm' doesn't support bounds.") + + if lb.shape != x0.shape or ub.shape != x0.shape: + raise ValueError("Inconsistent shapes between bounds and `x0`.") + + if np.any(lb >= ub): + raise ValueError("Each lower bound must be strictly less than each " + "upper bound.") + + if not in_bounds(x0, lb, ub): + raise ValueError("Initial guess is outside of provided bounds") + + x_scale = check_x_scale(x_scale, x0) + + ftol, xtol, gtol = check_tolerance(ftol, xtol, gtol, method) + + if method == 'trf': + x0 = make_strictly_feasible(x0, lb, ub) + + if kwargs is None: + kwargs = {} + if tr_options is None: + tr_options = {} + + def fun_wrapped(x): + return np.atleast_1d(fun(x, *args, **kwargs)) + + f0 = fun_wrapped(x0) + + if f0.ndim != 1: + raise ValueError("`fun` must return at most 1-d array_like. " + f"f0.shape: {f0.shape}") + + if not np.all(np.isfinite(f0)): + raise ValueError("Residuals are not finite in the initial point.") + + n = x0.size + m = f0.size + + if method == 'lm' and m < n: + raise ValueError("Method 'lm' doesn't work when the number of " + "residuals is less than the number of variables.") + + loss_function = construct_loss_function(m, loss, f_scale) + if callable(loss): + rho = loss_function(f0) + if rho.shape != (3, m): + raise ValueError("The return value of `loss` callable has wrong " + "shape.") + initial_cost = 0.5 * np.sum(rho[0]) + elif loss_function is not None: + initial_cost = loss_function(f0, cost_only=True) + else: + initial_cost = 0.5 * np.dot(f0, f0) + + if callable(jac): + J0 = jac(x0, *args, **kwargs) + + if issparse(J0): + J0 = J0.tocsr() + + def jac_wrapped(x, _=None): + return jac(x, *args, **kwargs).tocsr() + + elif isinstance(J0, LinearOperator): + def jac_wrapped(x, _=None): + return jac(x, *args, **kwargs) + + else: + J0 = np.atleast_2d(J0) + + def jac_wrapped(x, _=None): + return np.atleast_2d(jac(x, *args, **kwargs)) + + else: # Estimate Jacobian by finite differences. + if method == 'lm': + if jac_sparsity is not None: + raise ValueError("method='lm' does not support " + "`jac_sparsity`.") + + if jac != '2-point': + warn(f"jac='{jac}' works equivalently to '2-point' for method='lm'.", + stacklevel=2) + + J0 = jac_wrapped = None + else: + if jac_sparsity is not None and tr_solver == 'exact': + raise ValueError("tr_solver='exact' is incompatible " + "with `jac_sparsity`.") + + jac_sparsity = check_jac_sparsity(jac_sparsity, m, n) + + def jac_wrapped(x, f): + J = approx_derivative(fun, x, rel_step=diff_step, method=jac, + f0=f, bounds=bounds, args=args, + kwargs=kwargs, sparsity=jac_sparsity) + if J.ndim != 2: # J is guaranteed not sparse. + J = np.atleast_2d(J) + + return J + + J0 = jac_wrapped(x0, f0) + + if J0 is not None: + if J0.shape != (m, n): + raise ValueError( + f"The return value of `jac` has wrong shape: expected {(m, n)}, " + f"actual {J0.shape}." + ) + + if not isinstance(J0, np.ndarray): + if method == 'lm': + raise ValueError("method='lm' works only with dense " + "Jacobian matrices.") + + if tr_solver == 'exact': + raise ValueError( + "tr_solver='exact' works only with dense " + "Jacobian matrices.") + + jac_scale = isinstance(x_scale, str) and x_scale == 'jac' + if isinstance(J0, LinearOperator) and jac_scale: + raise ValueError("x_scale='jac' can't be used when `jac` " + "returns LinearOperator.") + + if tr_solver is None: + if isinstance(J0, np.ndarray): + tr_solver = 'exact' + else: + tr_solver = 'lsmr' + + if method == 'lm': + result = call_minpack(fun_wrapped, x0, jac_wrapped, ftol, xtol, gtol, + max_nfev, x_scale, diff_step) + + elif method == 'trf': + result = trf(fun_wrapped, jac_wrapped, x0, f0, J0, lb, ub, ftol, xtol, + gtol, max_nfev, x_scale, loss_function, tr_solver, + tr_options.copy(), verbose) + + elif method == 'dogbox': + if tr_solver == 'lsmr' and 'regularize' in tr_options: + warn("The keyword 'regularize' in `tr_options` is not relevant " + "for 'dogbox' method.", + stacklevel=2) + tr_options = tr_options.copy() + del tr_options['regularize'] + + result = dogbox(fun_wrapped, jac_wrapped, x0, f0, J0, lb, ub, ftol, + xtol, gtol, max_nfev, x_scale, loss_function, + tr_solver, tr_options, verbose) + + result.message = TERMINATION_MESSAGES[result.status] + result.success = result.status > 0 + + if verbose >= 1: + print(result.message) + print(f"Function evaluations {result.nfev}, initial cost {initial_cost:.4e}, " + f"final cost {result.cost:.4e}, " + f"first-order optimality {result.optimality:.2e}.") + + return result diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_lsq/lsq_linear.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_lsq/lsq_linear.py new file mode 100644 index 0000000000000000000000000000000000000000..b077c45e40874fc63490748f75f8463bc2adb08d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_lsq/lsq_linear.py @@ -0,0 +1,361 @@ +"""Linear least squares with bound constraints on independent variables.""" +import numpy as np +from numpy.linalg import norm +from scipy.sparse import issparse, csr_matrix +from scipy.sparse.linalg import LinearOperator, lsmr +from scipy.optimize import OptimizeResult +from scipy.optimize._minimize import Bounds + +from .common import in_bounds, compute_grad +from .trf_linear import trf_linear +from .bvls import bvls + + +def prepare_bounds(bounds, n): + if len(bounds) != 2: + raise ValueError("`bounds` must contain 2 elements.") + lb, ub = (np.asarray(b, dtype=float) for b in bounds) + + if lb.ndim == 0: + lb = np.resize(lb, n) + + if ub.ndim == 0: + ub = np.resize(ub, n) + + return lb, ub + + +TERMINATION_MESSAGES = { + -1: "The algorithm was not able to make progress on the last iteration.", + 0: "The maximum number of iterations is exceeded.", + 1: "The first-order optimality measure is less than `tol`.", + 2: "The relative change of the cost function is less than `tol`.", + 3: "The unconstrained solution is optimal." +} + + +def lsq_linear(A, b, bounds=(-np.inf, np.inf), method='trf', tol=1e-10, + lsq_solver=None, lsmr_tol=None, max_iter=None, + verbose=0, *, lsmr_maxiter=None,): + r"""Solve a linear least-squares problem with bounds on the variables. + + Given a m-by-n design matrix A and a target vector b with m elements, + `lsq_linear` solves the following optimization problem:: + + minimize 0.5 * ||A x - b||**2 + subject to lb <= x <= ub + + This optimization problem is convex, hence a found minimum (if iterations + have converged) is guaranteed to be global. + + Parameters + ---------- + A : array_like, sparse matrix of LinearOperator, shape (m, n) + Design matrix. Can be `scipy.sparse.linalg.LinearOperator`. + b : array_like, shape (m,) + Target vector. + bounds : 2-tuple of array_like or `Bounds`, optional + Lower and upper bounds on parameters. Defaults to no bounds. + There are two ways to specify the bounds: + + - Instance of `Bounds` class. + - 2-tuple of array_like: Each element of the tuple must be either + an array with the length equal to the number of parameters, or a + scalar (in which case the bound is taken to be the same for all + parameters). Use ``np.inf`` with an appropriate sign to disable + bounds on all or some parameters. + + method : 'trf' or 'bvls', optional + Method to perform minimization. + + * 'trf' : Trust Region Reflective algorithm adapted for a linear + least-squares problem. This is an interior-point-like method + and the required number of iterations is weakly correlated with + the number of variables. + * 'bvls' : Bounded-variable least-squares algorithm. This is + an active set method, which requires the number of iterations + comparable to the number of variables. Can't be used when `A` is + sparse or LinearOperator. + + Default is 'trf'. + tol : float, optional + Tolerance parameter. The algorithm terminates if a relative change + of the cost function is less than `tol` on the last iteration. + Additionally, the first-order optimality measure is considered: + + * ``method='trf'`` terminates if the uniform norm of the gradient, + scaled to account for the presence of the bounds, is less than + `tol`. + * ``method='bvls'`` terminates if Karush-Kuhn-Tucker conditions + are satisfied within `tol` tolerance. + + lsq_solver : {None, 'exact', 'lsmr'}, optional + Method of solving unbounded least-squares problems throughout + iterations: + + * 'exact' : Use dense QR or SVD decomposition approach. Can't be + used when `A` is sparse or LinearOperator. + * 'lsmr' : Use `scipy.sparse.linalg.lsmr` iterative procedure + which requires only matrix-vector product evaluations. Can't + be used with ``method='bvls'``. + + If None (default), the solver is chosen based on type of `A`. + lsmr_tol : None, float or 'auto', optional + Tolerance parameters 'atol' and 'btol' for `scipy.sparse.linalg.lsmr` + If None (default), it is set to ``1e-2 * tol``. If 'auto', the + tolerance will be adjusted based on the optimality of the current + iterate, which can speed up the optimization process, but is not always + reliable. + max_iter : None or int, optional + Maximum number of iterations before termination. If None (default), it + is set to 100 for ``method='trf'`` or to the number of variables for + ``method='bvls'`` (not counting iterations for 'bvls' initialization). + verbose : {0, 1, 2}, optional + Level of algorithm's verbosity: + + * 0 : work silently (default). + * 1 : display a termination report. + * 2 : display progress during iterations. + + lsmr_maxiter : None or int, optional + Maximum number of iterations for the lsmr least squares solver, + if it is used (by setting ``lsq_solver='lsmr'``). If None (default), it + uses lsmr's default of ``min(m, n)`` where ``m`` and ``n`` are the + number of rows and columns of `A`, respectively. Has no effect if + ``lsq_solver='exact'``. + + Returns + ------- + OptimizeResult with the following fields defined: + x : ndarray, shape (n,) + Solution found. + cost : float + Value of the cost function at the solution. + fun : ndarray, shape (m,) + Vector of residuals at the solution. + optimality : float + First-order optimality measure. The exact meaning depends on `method`, + refer to the description of `tol` parameter. + active_mask : ndarray of int, shape (n,) + Each component shows whether a corresponding constraint is active + (that is, whether a variable is at the bound): + + * 0 : a constraint is not active. + * -1 : a lower bound is active. + * 1 : an upper bound is active. + + Might be somewhat arbitrary for the `trf` method as it generates a + sequence of strictly feasible iterates and active_mask is determined + within a tolerance threshold. + unbounded_sol : tuple + Unbounded least squares solution tuple returned by the least squares + solver (set with `lsq_solver` option). If `lsq_solver` is not set or is + set to ``'exact'``, the tuple contains an ndarray of shape (n,) with + the unbounded solution, an ndarray with the sum of squared residuals, + an int with the rank of `A`, and an ndarray with the singular values + of `A` (see NumPy's ``linalg.lstsq`` for more information). If + `lsq_solver` is set to ``'lsmr'``, the tuple contains an ndarray of + shape (n,) with the unbounded solution, an int with the exit code, + an int with the number of iterations, and five floats with + various norms and the condition number of `A` (see SciPy's + ``sparse.linalg.lsmr`` for more information). This output can be + useful for determining the convergence of the least squares solver, + particularly the iterative ``'lsmr'`` solver. The unbounded least + squares problem is to minimize ``0.5 * ||A x - b||**2``. + nit : int + Number of iterations. Zero if the unconstrained solution is optimal. + status : int + Reason for algorithm termination: + + * -1 : the algorithm was not able to make progress on the last + iteration. + * 0 : the maximum number of iterations is exceeded. + * 1 : the first-order optimality measure is less than `tol`. + * 2 : the relative change of the cost function is less than `tol`. + * 3 : the unconstrained solution is optimal. + + message : str + Verbal description of the termination reason. + success : bool + True if one of the convergence criteria is satisfied (`status` > 0). + + See Also + -------- + nnls : Linear least squares with non-negativity constraint. + least_squares : Nonlinear least squares with bounds on the variables. + + Notes + ----- + The algorithm first computes the unconstrained least-squares solution by + `numpy.linalg.lstsq` or `scipy.sparse.linalg.lsmr` depending on + `lsq_solver`. This solution is returned as optimal if it lies within the + bounds. + + Method 'trf' runs the adaptation of the algorithm described in [STIR]_ for + a linear least-squares problem. The iterations are essentially the same as + in the nonlinear least-squares algorithm, but as the quadratic function + model is always accurate, we don't need to track or modify the radius of + a trust region. The line search (backtracking) is used as a safety net + when a selected step does not decrease the cost function. Read more + detailed description of the algorithm in `scipy.optimize.least_squares`. + + Method 'bvls' runs a Python implementation of the algorithm described in + [BVLS]_. The algorithm maintains active and free sets of variables, on + each iteration chooses a new variable to move from the active set to the + free set and then solves the unconstrained least-squares problem on free + variables. This algorithm is guaranteed to give an accurate solution + eventually, but may require up to n iterations for a problem with n + variables. Additionally, an ad-hoc initialization procedure is + implemented, that determines which variables to set free or active + initially. It takes some number of iterations before actual BVLS starts, + but can significantly reduce the number of further iterations. + + References + ---------- + .. [STIR] M. A. Branch, T. F. Coleman, and Y. Li, "A Subspace, Interior, + and Conjugate Gradient Method for Large-Scale Bound-Constrained + Minimization Problems," SIAM Journal on Scientific Computing, + Vol. 21, Number 1, pp 1-23, 1999. + .. [BVLS] P. B. Start and R. L. Parker, "Bounded-Variable Least-Squares: + an Algorithm and Applications", Computational Statistics, 10, + 129-141, 1995. + + Examples + -------- + In this example, a problem with a large sparse matrix and bounds on the + variables is solved. + + >>> import numpy as np + >>> from scipy.sparse import rand + >>> from scipy.optimize import lsq_linear + >>> rng = np.random.default_rng() + ... + >>> m = 2000 + >>> n = 1000 + ... + >>> A = rand(m, n, density=1e-4, random_state=rng) + >>> b = rng.standard_normal(m) + ... + >>> lb = rng.standard_normal(n) + >>> ub = lb + 1 + ... + >>> res = lsq_linear(A, b, bounds=(lb, ub), lsmr_tol='auto', verbose=1) + The relative change of the cost function is less than `tol`. + Number of iterations 10, initial cost 1.0070e+03, final cost 9.6602e+02, + first-order optimality 2.21e-09. # may vary + """ + if method not in ['trf', 'bvls']: + raise ValueError("`method` must be 'trf' or 'bvls'") + + if lsq_solver not in [None, 'exact', 'lsmr']: + raise ValueError("`solver` must be None, 'exact' or 'lsmr'.") + + if verbose not in [0, 1, 2]: + raise ValueError("`verbose` must be in [0, 1, 2].") + + if issparse(A): + A = csr_matrix(A) + elif not isinstance(A, LinearOperator): + A = np.atleast_2d(np.asarray(A)) + + if method == 'bvls': + if lsq_solver == 'lsmr': + raise ValueError("method='bvls' can't be used with " + "lsq_solver='lsmr'") + + if not isinstance(A, np.ndarray): + raise ValueError("method='bvls' can't be used with `A` being " + "sparse or LinearOperator.") + + if lsq_solver is None: + if isinstance(A, np.ndarray): + lsq_solver = 'exact' + else: + lsq_solver = 'lsmr' + elif lsq_solver == 'exact' and not isinstance(A, np.ndarray): + raise ValueError("`exact` solver can't be used when `A` is " + "sparse or LinearOperator.") + + if len(A.shape) != 2: # No ndim for LinearOperator. + raise ValueError("`A` must have at most 2 dimensions.") + + if max_iter is not None and max_iter <= 0: + raise ValueError("`max_iter` must be None or positive integer.") + + m, n = A.shape + + b = np.atleast_1d(b) + if b.ndim != 1: + raise ValueError("`b` must have at most 1 dimension.") + + if b.size != m: + raise ValueError("Inconsistent shapes between `A` and `b`.") + + if isinstance(bounds, Bounds): + lb = bounds.lb + ub = bounds.ub + else: + lb, ub = prepare_bounds(bounds, n) + + if lb.shape != (n,) and ub.shape != (n,): + raise ValueError("Bounds have wrong shape.") + + if np.any(lb >= ub): + raise ValueError("Each lower bound must be strictly less than each " + "upper bound.") + + if lsmr_maxiter is not None and lsmr_maxiter < 1: + raise ValueError("`lsmr_maxiter` must be None or positive integer.") + + if not ((isinstance(lsmr_tol, float) and lsmr_tol > 0) or + lsmr_tol in ('auto', None)): + raise ValueError("`lsmr_tol` must be None, 'auto', or positive float.") + + if lsq_solver == 'exact': + unbd_lsq = np.linalg.lstsq(A, b, rcond=-1) + elif lsq_solver == 'lsmr': + first_lsmr_tol = lsmr_tol # tol of first call to lsmr + if lsmr_tol is None or lsmr_tol == 'auto': + first_lsmr_tol = 1e-2 * tol # default if lsmr_tol not defined + unbd_lsq = lsmr(A, b, maxiter=lsmr_maxiter, + atol=first_lsmr_tol, btol=first_lsmr_tol) + x_lsq = unbd_lsq[0] # extract the solution from the least squares solver + + if in_bounds(x_lsq, lb, ub): + r = A @ x_lsq - b + cost = 0.5 * np.dot(r, r) + termination_status = 3 + termination_message = TERMINATION_MESSAGES[termination_status] + g = compute_grad(A, r) + g_norm = norm(g, ord=np.inf) + + if verbose > 0: + print(termination_message) + print(f"Final cost {cost:.4e}, first-order optimality {g_norm:.2e}") + + return OptimizeResult( + x=x_lsq, fun=r, cost=cost, optimality=g_norm, + active_mask=np.zeros(n), unbounded_sol=unbd_lsq, + nit=0, status=termination_status, + message=termination_message, success=True) + + if method == 'trf': + res = trf_linear(A, b, x_lsq, lb, ub, tol, lsq_solver, lsmr_tol, + max_iter, verbose, lsmr_maxiter=lsmr_maxiter) + elif method == 'bvls': + res = bvls(A, b, x_lsq, lb, ub, tol, max_iter, verbose) + + res.unbounded_sol = unbd_lsq + res.message = TERMINATION_MESSAGES[res.status] + res.success = res.status > 0 + + if verbose > 0: + print(res.message) + print( + f"Number of iterations {res.nit}, initial cost {res.initial_cost:.4e}, " + f"final cost {res.cost:.4e}, first-order optimality {res.optimality:.2e}." + ) + + del res.initial_cost + + return res diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_lsq/trf.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_lsq/trf.py new file mode 100644 index 0000000000000000000000000000000000000000..9154bdba5b2cc41883811ba1820dfc251e515d6c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_lsq/trf.py @@ -0,0 +1,560 @@ +"""Trust Region Reflective algorithm for least-squares optimization. + +The algorithm is based on ideas from paper [STIR]_. The main idea is to +account for the presence of the bounds by appropriate scaling of the variables (or, +equivalently, changing a trust-region shape). Let's introduce a vector v: + + | ub[i] - x[i], if g[i] < 0 and ub[i] < np.inf + v[i] = | x[i] - lb[i], if g[i] > 0 and lb[i] > -np.inf + | 1, otherwise + +where g is the gradient of a cost function and lb, ub are the bounds. Its +components are distances to the bounds at which the anti-gradient points (if +this distance is finite). Define a scaling matrix D = diag(v**0.5). +First-order optimality conditions can be stated as + + D^2 g(x) = 0. + +Meaning that components of the gradient should be zero for strictly interior +variables, and components must point inside the feasible region for variables +on the bound. + +Now consider this system of equations as a new optimization problem. If the +point x is strictly interior (not on the bound), then the left-hand side is +differentiable and the Newton step for it satisfies + + (D^2 H + diag(g) Jv) p = -D^2 g + +where H is the Hessian matrix (or its J^T J approximation in least squares), +Jv is the Jacobian matrix of v with components -1, 1 or 0, such that all +elements of matrix C = diag(g) Jv are non-negative. Introduce the change +of the variables x = D x_h (_h would be "hat" in LaTeX). In the new variables, +we have a Newton step satisfying + + B_h p_h = -g_h, + +where B_h = D H D + C, g_h = D g. In least squares B_h = J_h^T J_h, where +J_h = J D. Note that J_h and g_h are proper Jacobian and gradient with respect +to "hat" variables. To guarantee global convergence we formulate a +trust-region problem based on the Newton step in the new variables: + + 0.5 * p_h^T B_h p + g_h^T p_h -> min, ||p_h|| <= Delta + +In the original space B = H + D^{-1} C D^{-1}, and the equivalent trust-region +problem is + + 0.5 * p^T B p + g^T p -> min, ||D^{-1} p|| <= Delta + +Here, the meaning of the matrix D becomes more clear: it alters the shape +of a trust-region, such that large steps towards the bounds are not allowed. +In the implementation, the trust-region problem is solved in "hat" space, +but handling of the bounds is done in the original space (see below and read +the code). + +The introduction of the matrix D doesn't allow to ignore bounds, the algorithm +must keep iterates strictly feasible (to satisfy aforementioned +differentiability), the parameter theta controls step back from the boundary +(see the code for details). + +The algorithm does another important trick. If the trust-region solution +doesn't fit into the bounds, then a reflected (from a firstly encountered +bound) search direction is considered. For motivation and analysis refer to +[STIR]_ paper (and other papers of the authors). In practice, it doesn't need +a lot of justifications, the algorithm simply chooses the best step among +three: a constrained trust-region step, a reflected step and a constrained +Cauchy step (a minimizer along -g_h in "hat" space, or -D^2 g in the original +space). + +Another feature is that a trust-region radius control strategy is modified to +account for appearance of the diagonal C matrix (called diag_h in the code). + +Note that all described peculiarities are completely gone as we consider +problems without bounds (the algorithm becomes a standard trust-region type +algorithm very similar to ones implemented in MINPACK). + +The implementation supports two methods of solving the trust-region problem. +The first, called 'exact', applies SVD on Jacobian and then solves the problem +very accurately using the algorithm described in [JJMore]_. It is not +applicable to large problem. The second, called 'lsmr', uses the 2-D subspace +approach (sometimes called "indefinite dogleg"), where the problem is solved +in a subspace spanned by the gradient and the approximate Gauss-Newton step +found by ``scipy.sparse.linalg.lsmr``. A 2-D trust-region problem is +reformulated as a 4th order algebraic equation and solved very accurately by +``numpy.roots``. The subspace approach allows to solve very large problems +(up to couple of millions of residuals on a regular PC), provided the Jacobian +matrix is sufficiently sparse. + +References +---------- +.. [STIR] Branch, M.A., T.F. Coleman, and Y. Li, "A Subspace, Interior, + and Conjugate Gradient Method for Large-Scale Bound-Constrained + Minimization Problems," SIAM Journal on Scientific Computing, + Vol. 21, Number 1, pp 1-23, 1999. +.. [JJMore] More, J. J., "The Levenberg-Marquardt Algorithm: Implementation + and Theory," Numerical Analysis, ed. G. A. Watson, Lecture +""" +import numpy as np +from numpy.linalg import norm +from scipy.linalg import svd, qr +from scipy.sparse.linalg import lsmr +from scipy.optimize import OptimizeResult + +from .common import ( + step_size_to_bound, find_active_constraints, in_bounds, + make_strictly_feasible, intersect_trust_region, solve_lsq_trust_region, + solve_trust_region_2d, minimize_quadratic_1d, build_quadratic_1d, + evaluate_quadratic, right_multiplied_operator, regularized_lsq_operator, + CL_scaling_vector, compute_grad, compute_jac_scale, check_termination, + update_tr_radius, scale_for_robust_loss_function, print_header_nonlinear, + print_iteration_nonlinear) + + +def trf(fun, jac, x0, f0, J0, lb, ub, ftol, xtol, gtol, max_nfev, x_scale, + loss_function, tr_solver, tr_options, verbose): + # For efficiency, it makes sense to run the simplified version of the + # algorithm when no bounds are imposed. We decided to write the two + # separate functions. It violates the DRY principle, but the individual + # functions are kept the most readable. + if np.all(lb == -np.inf) and np.all(ub == np.inf): + return trf_no_bounds( + fun, jac, x0, f0, J0, ftol, xtol, gtol, max_nfev, x_scale, + loss_function, tr_solver, tr_options, verbose) + else: + return trf_bounds( + fun, jac, x0, f0, J0, lb, ub, ftol, xtol, gtol, max_nfev, x_scale, + loss_function, tr_solver, tr_options, verbose) + + +def select_step(x, J_h, diag_h, g_h, p, p_h, d, Delta, lb, ub, theta): + """Select the best step according to Trust Region Reflective algorithm.""" + if in_bounds(x + p, lb, ub): + p_value = evaluate_quadratic(J_h, g_h, p_h, diag=diag_h) + return p, p_h, -p_value + + p_stride, hits = step_size_to_bound(x, p, lb, ub) + + # Compute the reflected direction. + r_h = np.copy(p_h) + r_h[hits.astype(bool)] *= -1 + r = d * r_h + + # Restrict trust-region step, such that it hits the bound. + p *= p_stride + p_h *= p_stride + x_on_bound = x + p + + # Reflected direction will cross first either feasible region or trust + # region boundary. + _, to_tr = intersect_trust_region(p_h, r_h, Delta) + to_bound, _ = step_size_to_bound(x_on_bound, r, lb, ub) + + # Find lower and upper bounds on a step size along the reflected + # direction, considering the strict feasibility requirement. There is no + # single correct way to do that, the chosen approach seems to work best + # on test problems. + r_stride = min(to_bound, to_tr) + if r_stride > 0: + r_stride_l = (1 - theta) * p_stride / r_stride + if r_stride == to_bound: + r_stride_u = theta * to_bound + else: + r_stride_u = to_tr + else: + r_stride_l = 0 + r_stride_u = -1 + + # Check if reflection step is available. + if r_stride_l <= r_stride_u: + a, b, c = build_quadratic_1d(J_h, g_h, r_h, s0=p_h, diag=diag_h) + r_stride, r_value = minimize_quadratic_1d( + a, b, r_stride_l, r_stride_u, c=c) + r_h *= r_stride + r_h += p_h + r = r_h * d + else: + r_value = np.inf + + # Now correct p_h to make it strictly interior. + p *= theta + p_h *= theta + p_value = evaluate_quadratic(J_h, g_h, p_h, diag=diag_h) + + ag_h = -g_h + ag = d * ag_h + + to_tr = Delta / norm(ag_h) + to_bound, _ = step_size_to_bound(x, ag, lb, ub) + if to_bound < to_tr: + ag_stride = theta * to_bound + else: + ag_stride = to_tr + + a, b = build_quadratic_1d(J_h, g_h, ag_h, diag=diag_h) + ag_stride, ag_value = minimize_quadratic_1d(a, b, 0, ag_stride) + ag_h *= ag_stride + ag *= ag_stride + + if p_value < r_value and p_value < ag_value: + return p, p_h, -p_value + elif r_value < p_value and r_value < ag_value: + return r, r_h, -r_value + else: + return ag, ag_h, -ag_value + + +def trf_bounds(fun, jac, x0, f0, J0, lb, ub, ftol, xtol, gtol, max_nfev, + x_scale, loss_function, tr_solver, tr_options, verbose): + x = x0.copy() + + f = f0 + f_true = f.copy() + nfev = 1 + + J = J0 + njev = 1 + m, n = J.shape + + if loss_function is not None: + rho = loss_function(f) + cost = 0.5 * np.sum(rho[0]) + J, f = scale_for_robust_loss_function(J, f, rho) + else: + cost = 0.5 * np.dot(f, f) + + g = compute_grad(J, f) + + jac_scale = isinstance(x_scale, str) and x_scale == 'jac' + if jac_scale: + scale, scale_inv = compute_jac_scale(J) + else: + scale, scale_inv = x_scale, 1 / x_scale + + v, dv = CL_scaling_vector(x, g, lb, ub) + v[dv != 0] *= scale_inv[dv != 0] + Delta = norm(x0 * scale_inv / v**0.5) + if Delta == 0: + Delta = 1.0 + + g_norm = norm(g * v, ord=np.inf) + + f_augmented = np.zeros(m + n) + if tr_solver == 'exact': + J_augmented = np.empty((m + n, n)) + elif tr_solver == 'lsmr': + reg_term = 0.0 + regularize = tr_options.pop('regularize', True) + + if max_nfev is None: + max_nfev = x0.size * 100 + + alpha = 0.0 # "Levenberg-Marquardt" parameter + + termination_status = None + iteration = 0 + step_norm = None + actual_reduction = None + + if verbose == 2: + print_header_nonlinear() + + while True: + v, dv = CL_scaling_vector(x, g, lb, ub) + + g_norm = norm(g * v, ord=np.inf) + if g_norm < gtol: + termination_status = 1 + + if verbose == 2: + print_iteration_nonlinear(iteration, nfev, cost, actual_reduction, + step_norm, g_norm) + + if termination_status is not None or nfev == max_nfev: + break + + # Now compute variables in "hat" space. Here, we also account for + # scaling introduced by `x_scale` parameter. This part is a bit tricky, + # you have to write down the formulas and see how the trust-region + # problem is formulated when the two types of scaling are applied. + # The idea is that first we apply `x_scale` and then apply Coleman-Li + # approach in the new variables. + + # v is recomputed in the variables after applying `x_scale`, note that + # components which were identically 1 not affected. + v[dv != 0] *= scale_inv[dv != 0] + + # Here, we apply two types of scaling. + d = v**0.5 * scale + + # C = diag(g * scale) Jv + diag_h = g * dv * scale + + # After all this has been done, we continue normally. + + # "hat" gradient. + g_h = d * g + + f_augmented[:m] = f + if tr_solver == 'exact': + J_augmented[:m] = J * d + J_h = J_augmented[:m] # Memory view. + J_augmented[m:] = np.diag(diag_h**0.5) + U, s, V = svd(J_augmented, full_matrices=False) + V = V.T + uf = U.T.dot(f_augmented) + elif tr_solver == 'lsmr': + J_h = right_multiplied_operator(J, d) + + if regularize: + a, b = build_quadratic_1d(J_h, g_h, -g_h, diag=diag_h) + to_tr = Delta / norm(g_h) + ag_value = minimize_quadratic_1d(a, b, 0, to_tr)[1] + reg_term = -ag_value / Delta**2 + + lsmr_op = regularized_lsq_operator(J_h, (diag_h + reg_term)**0.5) + gn_h = lsmr(lsmr_op, f_augmented, **tr_options)[0] + S = np.vstack((g_h, gn_h)).T + S, _ = qr(S, mode='economic') + JS = J_h.dot(S) # LinearOperator does dot too. + B_S = np.dot(JS.T, JS) + np.dot(S.T * diag_h, S) + g_S = S.T.dot(g_h) + + # theta controls step back step ratio from the bounds. + theta = max(0.995, 1 - g_norm) + + actual_reduction = -1 + while actual_reduction <= 0 and nfev < max_nfev: + if tr_solver == 'exact': + p_h, alpha, n_iter = solve_lsq_trust_region( + n, m, uf, s, V, Delta, initial_alpha=alpha) + elif tr_solver == 'lsmr': + p_S, _ = solve_trust_region_2d(B_S, g_S, Delta) + p_h = S.dot(p_S) + + p = d * p_h # Trust-region solution in the original space. + step, step_h, predicted_reduction = select_step( + x, J_h, diag_h, g_h, p, p_h, d, Delta, lb, ub, theta) + + x_new = make_strictly_feasible(x + step, lb, ub, rstep=0) + f_new = fun(x_new) + nfev += 1 + + step_h_norm = norm(step_h) + + if not np.all(np.isfinite(f_new)): + Delta = 0.25 * step_h_norm + continue + + # Usual trust-region step quality estimation. + if loss_function is not None: + cost_new = loss_function(f_new, cost_only=True) + else: + cost_new = 0.5 * np.dot(f_new, f_new) + actual_reduction = cost - cost_new + Delta_new, ratio = update_tr_radius( + Delta, actual_reduction, predicted_reduction, + step_h_norm, step_h_norm > 0.95 * Delta) + + step_norm = norm(step) + termination_status = check_termination( + actual_reduction, cost, step_norm, norm(x), ratio, ftol, xtol) + if termination_status is not None: + break + + alpha *= Delta / Delta_new + Delta = Delta_new + + if actual_reduction > 0: + x = x_new + + f = f_new + f_true = f.copy() + + cost = cost_new + + J = jac(x, f) + njev += 1 + + if loss_function is not None: + rho = loss_function(f) + J, f = scale_for_robust_loss_function(J, f, rho) + + g = compute_grad(J, f) + + if jac_scale: + scale, scale_inv = compute_jac_scale(J, scale_inv) + else: + step_norm = 0 + actual_reduction = 0 + + iteration += 1 + + if termination_status is None: + termination_status = 0 + + active_mask = find_active_constraints(x, lb, ub, rtol=xtol) + return OptimizeResult( + x=x, cost=cost, fun=f_true, jac=J, grad=g, optimality=g_norm, + active_mask=active_mask, nfev=nfev, njev=njev, + status=termination_status) + + +def trf_no_bounds(fun, jac, x0, f0, J0, ftol, xtol, gtol, max_nfev, + x_scale, loss_function, tr_solver, tr_options, verbose): + x = x0.copy() + + f = f0 + f_true = f.copy() + nfev = 1 + + J = J0 + njev = 1 + m, n = J.shape + + if loss_function is not None: + rho = loss_function(f) + cost = 0.5 * np.sum(rho[0]) + J, f = scale_for_robust_loss_function(J, f, rho) + else: + cost = 0.5 * np.dot(f, f) + + g = compute_grad(J, f) + + jac_scale = isinstance(x_scale, str) and x_scale == 'jac' + if jac_scale: + scale, scale_inv = compute_jac_scale(J) + else: + scale, scale_inv = x_scale, 1 / x_scale + + Delta = norm(x0 * scale_inv) + if Delta == 0: + Delta = 1.0 + + if tr_solver == 'lsmr': + reg_term = 0 + damp = tr_options.pop('damp', 0.0) + regularize = tr_options.pop('regularize', True) + + if max_nfev is None: + max_nfev = x0.size * 100 + + alpha = 0.0 # "Levenberg-Marquardt" parameter + + termination_status = None + iteration = 0 + step_norm = None + actual_reduction = None + + if verbose == 2: + print_header_nonlinear() + + while True: + g_norm = norm(g, ord=np.inf) + if g_norm < gtol: + termination_status = 1 + + if verbose == 2: + print_iteration_nonlinear(iteration, nfev, cost, actual_reduction, + step_norm, g_norm) + + if termination_status is not None or nfev == max_nfev: + break + + d = scale + g_h = d * g + + if tr_solver == 'exact': + J_h = J * d + U, s, V = svd(J_h, full_matrices=False) + V = V.T + uf = U.T.dot(f) + elif tr_solver == 'lsmr': + J_h = right_multiplied_operator(J, d) + + if regularize: + a, b = build_quadratic_1d(J_h, g_h, -g_h) + to_tr = Delta / norm(g_h) + ag_value = minimize_quadratic_1d(a, b, 0, to_tr)[1] + reg_term = -ag_value / Delta**2 + + damp_full = (damp**2 + reg_term)**0.5 + gn_h = lsmr(J_h, f, damp=damp_full, **tr_options)[0] + S = np.vstack((g_h, gn_h)).T + S, _ = qr(S, mode='economic') + JS = J_h.dot(S) + B_S = np.dot(JS.T, JS) + g_S = S.T.dot(g_h) + + actual_reduction = -1 + while actual_reduction <= 0 and nfev < max_nfev: + if tr_solver == 'exact': + step_h, alpha, n_iter = solve_lsq_trust_region( + n, m, uf, s, V, Delta, initial_alpha=alpha) + elif tr_solver == 'lsmr': + p_S, _ = solve_trust_region_2d(B_S, g_S, Delta) + step_h = S.dot(p_S) + + predicted_reduction = -evaluate_quadratic(J_h, g_h, step_h) + step = d * step_h + x_new = x + step + f_new = fun(x_new) + nfev += 1 + + step_h_norm = norm(step_h) + + if not np.all(np.isfinite(f_new)): + Delta = 0.25 * step_h_norm + continue + + # Usual trust-region step quality estimation. + if loss_function is not None: + cost_new = loss_function(f_new, cost_only=True) + else: + cost_new = 0.5 * np.dot(f_new, f_new) + actual_reduction = cost - cost_new + + Delta_new, ratio = update_tr_radius( + Delta, actual_reduction, predicted_reduction, + step_h_norm, step_h_norm > 0.95 * Delta) + + step_norm = norm(step) + termination_status = check_termination( + actual_reduction, cost, step_norm, norm(x), ratio, ftol, xtol) + if termination_status is not None: + break + + alpha *= Delta / Delta_new + Delta = Delta_new + + if actual_reduction > 0: + x = x_new + + f = f_new + f_true = f.copy() + + cost = cost_new + + J = jac(x, f) + njev += 1 + + if loss_function is not None: + rho = loss_function(f) + J, f = scale_for_robust_loss_function(J, f, rho) + + g = compute_grad(J, f) + + if jac_scale: + scale, scale_inv = compute_jac_scale(J, scale_inv) + else: + step_norm = 0 + actual_reduction = 0 + + iteration += 1 + + if termination_status is None: + termination_status = 0 + + active_mask = np.zeros_like(x) + return OptimizeResult( + x=x, cost=cost, fun=f_true, jac=J, grad=g, optimality=g_norm, + active_mask=active_mask, nfev=nfev, njev=njev, + status=termination_status) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_lsq/trf_linear.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_lsq/trf_linear.py new file mode 100644 index 0000000000000000000000000000000000000000..dd752763179bcf97945c7f34ce6a9e49e85c819e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_lsq/trf_linear.py @@ -0,0 +1,249 @@ +"""The adaptation of Trust Region Reflective algorithm for a linear +least-squares problem.""" +import numpy as np +from numpy.linalg import norm +from scipy.linalg import qr, solve_triangular +from scipy.sparse.linalg import lsmr +from scipy.optimize import OptimizeResult + +from .givens_elimination import givens_elimination +from .common import ( + EPS, step_size_to_bound, find_active_constraints, in_bounds, + make_strictly_feasible, build_quadratic_1d, evaluate_quadratic, + minimize_quadratic_1d, CL_scaling_vector, reflective_transformation, + print_header_linear, print_iteration_linear, compute_grad, + regularized_lsq_operator, right_multiplied_operator) + + +def regularized_lsq_with_qr(m, n, R, QTb, perm, diag, copy_R=True): + """Solve regularized least squares using information from QR-decomposition. + + The initial problem is to solve the following system in a least-squares + sense:: + + A x = b + D x = 0 + + where D is diagonal matrix. The method is based on QR decomposition + of the form A P = Q R, where P is a column permutation matrix, Q is an + orthogonal matrix and R is an upper triangular matrix. + + Parameters + ---------- + m, n : int + Initial shape of A. + R : ndarray, shape (n, n) + Upper triangular matrix from QR decomposition of A. + QTb : ndarray, shape (n,) + First n components of Q^T b. + perm : ndarray, shape (n,) + Array defining column permutation of A, such that ith column of + P is perm[i]-th column of identity matrix. + diag : ndarray, shape (n,) + Array containing diagonal elements of D. + + Returns + ------- + x : ndarray, shape (n,) + Found least-squares solution. + """ + if copy_R: + R = R.copy() + v = QTb.copy() + + givens_elimination(R, v, diag[perm]) + + abs_diag_R = np.abs(np.diag(R)) + threshold = EPS * max(m, n) * np.max(abs_diag_R) + nns, = np.nonzero(abs_diag_R > threshold) + + R = R[np.ix_(nns, nns)] + v = v[nns] + + x = np.zeros(n) + x[perm[nns]] = solve_triangular(R, v) + + return x + + +def backtracking(A, g, x, p, theta, p_dot_g, lb, ub): + """Find an appropriate step size using backtracking line search.""" + alpha = 1 + while True: + x_new, _ = reflective_transformation(x + alpha * p, lb, ub) + step = x_new - x + cost_change = -evaluate_quadratic(A, g, step) + if cost_change > -0.1 * alpha * p_dot_g: + break + alpha *= 0.5 + + active = find_active_constraints(x_new, lb, ub) + if np.any(active != 0): + x_new, _ = reflective_transformation(x + theta * alpha * p, lb, ub) + x_new = make_strictly_feasible(x_new, lb, ub, rstep=0) + step = x_new - x + cost_change = -evaluate_quadratic(A, g, step) + + return x, step, cost_change + + +def select_step(x, A_h, g_h, c_h, p, p_h, d, lb, ub, theta): + """Select the best step according to Trust Region Reflective algorithm.""" + if in_bounds(x + p, lb, ub): + return p + + p_stride, hits = step_size_to_bound(x, p, lb, ub) + r_h = np.copy(p_h) + r_h[hits.astype(bool)] *= -1 + r = d * r_h + + # Restrict step, such that it hits the bound. + p *= p_stride + p_h *= p_stride + x_on_bound = x + p + + # Find the step size along reflected direction. + r_stride_u, _ = step_size_to_bound(x_on_bound, r, lb, ub) + + # Stay interior. + r_stride_l = (1 - theta) * r_stride_u + r_stride_u *= theta + + if r_stride_u > 0: + a, b, c = build_quadratic_1d(A_h, g_h, r_h, s0=p_h, diag=c_h) + r_stride, r_value = minimize_quadratic_1d( + a, b, r_stride_l, r_stride_u, c=c) + r_h = p_h + r_h * r_stride + r = d * r_h + else: + r_value = np.inf + + # Now correct p_h to make it strictly interior. + p_h *= theta + p *= theta + p_value = evaluate_quadratic(A_h, g_h, p_h, diag=c_h) + + ag_h = -g_h + ag = d * ag_h + ag_stride_u, _ = step_size_to_bound(x, ag, lb, ub) + ag_stride_u *= theta + a, b = build_quadratic_1d(A_h, g_h, ag_h, diag=c_h) + ag_stride, ag_value = minimize_quadratic_1d(a, b, 0, ag_stride_u) + ag *= ag_stride + + if p_value < r_value and p_value < ag_value: + return p + elif r_value < p_value and r_value < ag_value: + return r + else: + return ag + + +def trf_linear(A, b, x_lsq, lb, ub, tol, lsq_solver, lsmr_tol, + max_iter, verbose, *, lsmr_maxiter=None): + m, n = A.shape + x, _ = reflective_transformation(x_lsq, lb, ub) + x = make_strictly_feasible(x, lb, ub, rstep=0.1) + + if lsq_solver == 'exact': + QT, R, perm = qr(A, mode='economic', pivoting=True) + QT = QT.T + + if m < n: + R = np.vstack((R, np.zeros((n - m, n)))) + + QTr = np.zeros(n) + k = min(m, n) + elif lsq_solver == 'lsmr': + r_aug = np.zeros(m + n) + auto_lsmr_tol = False + if lsmr_tol is None: + lsmr_tol = 1e-2 * tol + elif lsmr_tol == 'auto': + auto_lsmr_tol = True + + r = A.dot(x) - b + g = compute_grad(A, r) + cost = 0.5 * np.dot(r, r) + initial_cost = cost + + termination_status = None + step_norm = None + cost_change = None + + if max_iter is None: + max_iter = 100 + + if verbose == 2: + print_header_linear() + + for iteration in range(max_iter): + v, dv = CL_scaling_vector(x, g, lb, ub) + g_scaled = g * v + g_norm = norm(g_scaled, ord=np.inf) + if g_norm < tol: + termination_status = 1 + + if verbose == 2: + print_iteration_linear(iteration, cost, cost_change, + step_norm, g_norm) + + if termination_status is not None: + break + + diag_h = g * dv + diag_root_h = diag_h ** 0.5 + d = v ** 0.5 + g_h = d * g + + A_h = right_multiplied_operator(A, d) + if lsq_solver == 'exact': + QTr[:k] = QT.dot(r) + p_h = -regularized_lsq_with_qr(m, n, R * d[perm], QTr, perm, + diag_root_h, copy_R=False) + elif lsq_solver == 'lsmr': + lsmr_op = regularized_lsq_operator(A_h, diag_root_h) + r_aug[:m] = r + if auto_lsmr_tol: + eta = 1e-2 * min(0.5, g_norm) + lsmr_tol = max(EPS, min(0.1, eta * g_norm)) + p_h = -lsmr(lsmr_op, r_aug, maxiter=lsmr_maxiter, + atol=lsmr_tol, btol=lsmr_tol)[0] + + p = d * p_h + + p_dot_g = np.dot(p, g) + if p_dot_g > 0: + termination_status = -1 + + theta = 1 - min(0.005, g_norm) + step = select_step(x, A_h, g_h, diag_h, p, p_h, d, lb, ub, theta) + cost_change = -evaluate_quadratic(A, g, step) + + # Perhaps almost never executed, the idea is that `p` is descent + # direction thus we must find acceptable cost decrease using simple + # "backtracking", otherwise the algorithm's logic would break. + if cost_change < 0: + x, step, cost_change = backtracking( + A, g, x, p, theta, p_dot_g, lb, ub) + else: + x = make_strictly_feasible(x + step, lb, ub, rstep=0) + + step_norm = norm(step) + r = A.dot(x) - b + g = compute_grad(A, r) + + if cost_change < tol * cost: + termination_status = 2 + + cost = 0.5 * np.dot(r, r) + + if termination_status is None: + termination_status = 0 + + active_mask = find_active_constraints(x, lb, ub, rtol=tol) + + return OptimizeResult( + x=x, fun=r, cost=cost, optimality=g_norm, active_mask=active_mask, + nit=iteration + 1, status=termination_status, + initial_cost=initial_cost) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_milp.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_milp.py new file mode 100644 index 0000000000000000000000000000000000000000..b97a00d15406700cfedbe50e1b3714d36a60f8fb --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_milp.py @@ -0,0 +1,392 @@ +import warnings +import numpy as np +from scipy.sparse import csc_array, vstack, issparse +from scipy._lib._util import VisibleDeprecationWarning +from ._highspy._highs_wrapper import _highs_wrapper # type: ignore[import-not-found,import-untyped] +from ._constraints import LinearConstraint, Bounds +from ._optimize import OptimizeResult +from ._linprog_highs import _highs_to_scipy_status_message + + +def _constraints_to_components(constraints): + """ + Convert sequence of constraints to a single set of components A, b_l, b_u. + + `constraints` could be + + 1. A LinearConstraint + 2. A tuple representing a LinearConstraint + 3. An invalid object + 4. A sequence of composed entirely of objects of type 1/2 + 5. A sequence containing at least one object of type 3 + + We want to accept 1, 2, and 4 and reject 3 and 5. + """ + message = ("`constraints` (or each element within `constraints`) must be " + "convertible into an instance of " + "`scipy.optimize.LinearConstraint`.") + As = [] + b_ls = [] + b_us = [] + + # Accept case 1 by standardizing as case 4 + if isinstance(constraints, LinearConstraint): + constraints = [constraints] + else: + # Reject case 3 + try: + iter(constraints) + except TypeError as exc: + raise ValueError(message) from exc + + # Accept case 2 by standardizing as case 4 + if len(constraints) == 3: + # argument could be a single tuple representing a LinearConstraint + try: + constraints = [LinearConstraint(*constraints)] + except (TypeError, ValueError, VisibleDeprecationWarning): + # argument was not a tuple representing a LinearConstraint + pass + + # Address cases 4/5 + for constraint in constraints: + # if it's not a LinearConstraint or something that represents a + # LinearConstraint at this point, it's invalid + if not isinstance(constraint, LinearConstraint): + try: + constraint = LinearConstraint(*constraint) + except TypeError as exc: + raise ValueError(message) from exc + As.append(csc_array(constraint.A)) + b_ls.append(np.atleast_1d(constraint.lb).astype(np.float64)) + b_us.append(np.atleast_1d(constraint.ub).astype(np.float64)) + + if len(As) > 1: + A = vstack(As, format="csc") + b_l = np.concatenate(b_ls) + b_u = np.concatenate(b_us) + else: # avoid unnecessary copying + A = As[0] + b_l = b_ls[0] + b_u = b_us[0] + + return A, b_l, b_u + + +def _milp_iv(c, integrality, bounds, constraints, options): + # objective IV + if issparse(c): + raise ValueError("`c` must be a dense array.") + c = np.atleast_1d(c).astype(np.float64) + if c.ndim != 1 or c.size == 0 or not np.all(np.isfinite(c)): + message = ("`c` must be a one-dimensional array of finite numbers " + "with at least one element.") + raise ValueError(message) + + # integrality IV + if issparse(integrality): + raise ValueError("`integrality` must be a dense array.") + message = ("`integrality` must contain integers 0-3 and be broadcastable " + "to `c.shape`.") + if integrality is None: + integrality = 0 + try: + integrality = np.broadcast_to(integrality, c.shape).astype(np.uint8) + except ValueError: + raise ValueError(message) + if integrality.min() < 0 or integrality.max() > 3: + raise ValueError(message) + + # bounds IV + if bounds is None: + bounds = Bounds(0, np.inf) + elif not isinstance(bounds, Bounds): + message = ("`bounds` must be convertible into an instance of " + "`scipy.optimize.Bounds`.") + try: + bounds = Bounds(*bounds) + except TypeError as exc: + raise ValueError(message) from exc + + try: + lb = np.broadcast_to(bounds.lb, c.shape).astype(np.float64) + ub = np.broadcast_to(bounds.ub, c.shape).astype(np.float64) + except (ValueError, TypeError) as exc: + message = ("`bounds.lb` and `bounds.ub` must contain reals and " + "be broadcastable to `c.shape`.") + raise ValueError(message) from exc + + # constraints IV + if not constraints: + constraints = [LinearConstraint(np.empty((0, c.size)), + np.empty((0,)), np.empty((0,)))] + try: + A, b_l, b_u = _constraints_to_components(constraints) + except ValueError as exc: + message = ("`constraints` (or each element within `constraints`) must " + "be convertible into an instance of " + "`scipy.optimize.LinearConstraint`.") + raise ValueError(message) from exc + + if A.shape != (b_l.size, c.size): + message = "The shape of `A` must be (len(b_l), len(c))." + raise ValueError(message) + indptr, indices, data = A.indptr, A.indices, A.data.astype(np.float64) + + # options IV + options = options or {} + supported_options = {'disp', 'presolve', 'time_limit', 'node_limit', + 'mip_rel_gap'} + unsupported_options = set(options).difference(supported_options) + if unsupported_options: + message = (f"Unrecognized options detected: {unsupported_options}. " + "These will be passed to HiGHS verbatim.") + warnings.warn(message, RuntimeWarning, stacklevel=3) + options_iv = {'log_to_console': options.pop("disp", False), + 'mip_max_nodes': options.pop("node_limit", None)} + options_iv.update(options) + + return c, integrality, lb, ub, indptr, indices, data, b_l, b_u, options_iv + + +def milp(c, *, integrality=None, bounds=None, constraints=None, options=None): + r""" + Mixed-integer linear programming + + Solves problems of the following form: + + .. math:: + + \min_x \ & c^T x \\ + \mbox{such that} \ & b_l \leq A x \leq b_u,\\ + & l \leq x \leq u, \\ + & x_i \in \mathbb{Z}, i \in X_i + + where :math:`x` is a vector of decision variables; + :math:`c`, :math:`b_l`, :math:`b_u`, :math:`l`, and :math:`u` are vectors; + :math:`A` is a matrix, and :math:`X_i` is the set of indices of + decision variables that must be integral. (In this context, a + variable that can assume only integer values is said to be "integral"; + it has an "integrality" constraint.) + + Alternatively, that's: + + minimize:: + + c @ x + + such that:: + + b_l <= A @ x <= b_u + l <= x <= u + Specified elements of x must be integers + + By default, ``l = 0`` and ``u = np.inf`` unless specified with + ``bounds``. + + Parameters + ---------- + c : 1D dense array_like + The coefficients of the linear objective function to be minimized. + `c` is converted to a double precision array before the problem is + solved. + integrality : 1D dense array_like, optional + Indicates the type of integrality constraint on each decision variable. + + ``0`` : Continuous variable; no integrality constraint. + + ``1`` : Integer variable; decision variable must be an integer + within `bounds`. + + ``2`` : Semi-continuous variable; decision variable must be within + `bounds` or take value ``0``. + + ``3`` : Semi-integer variable; decision variable must be an integer + within `bounds` or take value ``0``. + + By default, all variables are continuous. `integrality` is converted + to an array of integers before the problem is solved. + + bounds : scipy.optimize.Bounds, optional + Bounds on the decision variables. Lower and upper bounds are converted + to double precision arrays before the problem is solved. The + ``keep_feasible`` parameter of the `Bounds` object is ignored. If + not specified, all decision variables are constrained to be + non-negative. + constraints : sequence of scipy.optimize.LinearConstraint, optional + Linear constraints of the optimization problem. Arguments may be + one of the following: + + 1. A single `LinearConstraint` object + 2. A single tuple that can be converted to a `LinearConstraint` object + as ``LinearConstraint(*constraints)`` + 3. A sequence composed entirely of objects of type 1. and 2. + + Before the problem is solved, all values are converted to double + precision, and the matrices of constraint coefficients are converted to + instances of `scipy.sparse.csc_array`. The ``keep_feasible`` parameter + of `LinearConstraint` objects is ignored. + options : dict, optional + A dictionary of solver options. The following keys are recognized. + + disp : bool (default: ``False``) + Set to ``True`` if indicators of optimization status are to be + printed to the console during optimization. + node_limit : int, optional + The maximum number of nodes (linear program relaxations) to solve + before stopping. Default is no maximum number of nodes. + presolve : bool (default: ``True``) + Presolve attempts to identify trivial infeasibilities, + identify trivial unboundedness, and simplify the problem before + sending it to the main solver. + time_limit : float, optional + The maximum number of seconds allotted to solve the problem. + Default is no time limit. + mip_rel_gap : float, optional + Termination criterion for MIP solver: solver will terminate when + the gap between the primal objective value and the dual objective + bound, scaled by the primal objective value, is <= mip_rel_gap. + + Returns + ------- + res : OptimizeResult + An instance of :class:`scipy.optimize.OptimizeResult`. The object + is guaranteed to have the following attributes. + + status : int + An integer representing the exit status of the algorithm. + + ``0`` : Optimal solution found. + + ``1`` : Iteration or time limit reached. + + ``2`` : Problem is infeasible. + + ``3`` : Problem is unbounded. + + ``4`` : Other; see message for details. + + success : bool + ``True`` when an optimal solution is found and ``False`` otherwise. + + message : str + A string descriptor of the exit status of the algorithm. + + The following attributes will also be present, but the values may be + ``None``, depending on the solution status. + + x : ndarray + The values of the decision variables that minimize the + objective function while satisfying the constraints. + fun : float + The optimal value of the objective function ``c @ x``. + mip_node_count : int + The number of subproblems or "nodes" solved by the MILP solver. + mip_dual_bound : float + The MILP solver's final estimate of the lower bound on the optimal + solution. + mip_gap : float + The difference between the primal objective value and the dual + objective bound, scaled by the primal objective value. + + Notes + ----- + `milp` is a wrapper of the HiGHS linear optimization software [1]_. The + algorithm is deterministic, and it typically finds the global optimum of + moderately challenging mixed-integer linear programs (when it exists). + + References + ---------- + .. [1] Huangfu, Q., Galabova, I., Feldmeier, M., and Hall, J. A. J. + "HiGHS - high performance software for linear optimization." + https://highs.dev/ + .. [2] Huangfu, Q. and Hall, J. A. J. "Parallelizing the dual revised + simplex method." Mathematical Programming Computation, 10 (1), + 119-142, 2018. DOI: 10.1007/s12532-017-0130-5 + + Examples + -------- + Consider the problem at + https://en.wikipedia.org/wiki/Integer_programming#Example, which is + expressed as a maximization problem of two variables. Since `milp` requires + that the problem be expressed as a minimization problem, the objective + function coefficients on the decision variables are: + + >>> import numpy as np + >>> c = -np.array([0, 1]) + + Note the negative sign: we maximize the original objective function + by minimizing the negative of the objective function. + + We collect the coefficients of the constraints into arrays like: + + >>> A = np.array([[-1, 1], [3, 2], [2, 3]]) + >>> b_u = np.array([1, 12, 12]) + >>> b_l = np.full_like(b_u, -np.inf, dtype=float) + + Because there is no lower limit on these constraints, we have defined a + variable ``b_l`` full of values representing negative infinity. This may + be unfamiliar to users of `scipy.optimize.linprog`, which only accepts + "less than" (or "upper bound") inequality constraints of the form + ``A_ub @ x <= b_u``. By accepting both ``b_l`` and ``b_u`` of constraints + ``b_l <= A_ub @ x <= b_u``, `milp` makes it easy to specify "greater than" + inequality constraints, "less than" inequality constraints, and equality + constraints concisely. + + These arrays are collected into a single `LinearConstraint` object like: + + >>> from scipy.optimize import LinearConstraint + >>> constraints = LinearConstraint(A, b_l, b_u) + + The non-negativity bounds on the decision variables are enforced by + default, so we do not need to provide an argument for `bounds`. + + Finally, the problem states that both decision variables must be integers: + + >>> integrality = np.ones_like(c) + + We solve the problem like: + + >>> from scipy.optimize import milp + >>> res = milp(c=c, constraints=constraints, integrality=integrality) + >>> res.x + [2.0, 2.0] + + Note that had we solved the relaxed problem (without integrality + constraints): + + >>> res = milp(c=c, constraints=constraints) # OR: + >>> # from scipy.optimize import linprog; res = linprog(c, A, b_u) + >>> res.x + [1.8, 2.8] + + we would not have obtained the correct solution by rounding to the nearest + integers. + + Other examples are given :ref:`in the tutorial `. + + """ + args_iv = _milp_iv(c, integrality, bounds, constraints, options) + c, integrality, lb, ub, indptr, indices, data, b_l, b_u, options = args_iv + + highs_res = _highs_wrapper(c, indptr, indices, data, b_l, b_u, + lb, ub, integrality, options) + + res = {} + + # Convert to scipy-style status and message + highs_status = highs_res.get('status', None) + highs_message = highs_res.get('message', None) + status, message = _highs_to_scipy_status_message(highs_status, + highs_message) + res['status'] = status + res['message'] = message + res['success'] = (status == 0) + x = highs_res.get('x', None) + res['x'] = np.array(x) if x is not None else None + res['fun'] = highs_res.get('fun', None) + res['mip_node_count'] = highs_res.get('mip_node_count', None) + res['mip_dual_bound'] = highs_res.get('mip_dual_bound', None) + res['mip_gap'] = highs_res.get('mip_gap', None) + + return OptimizeResult(res) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_minimize.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_minimize.py new file mode 100644 index 0000000000000000000000000000000000000000..0b47c57cb3a12c6f4a7adb5506089c569336b4c4 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_minimize.py @@ -0,0 +1,1131 @@ +""" +Unified interfaces to minimization algorithms. + +Functions +--------- +- minimize : minimization of a function of several variables. +- minimize_scalar : minimization of a function of one variable. +""" + +__all__ = ['minimize', 'minimize_scalar'] + + +from warnings import warn + +import numpy as np + +# unconstrained minimization +from ._optimize import (_minimize_neldermead, _minimize_powell, _minimize_cg, + _minimize_bfgs, _minimize_newtoncg, + _minimize_scalar_brent, _minimize_scalar_bounded, + _minimize_scalar_golden, MemoizeJac, OptimizeResult, + _wrap_callback, _recover_from_bracket_error) +from ._trustregion_dogleg import _minimize_dogleg +from ._trustregion_ncg import _minimize_trust_ncg +from ._trustregion_krylov import _minimize_trust_krylov +from ._trustregion_exact import _minimize_trustregion_exact +from ._trustregion_constr import _minimize_trustregion_constr + +# constrained minimization +from ._lbfgsb_py import _minimize_lbfgsb +from ._tnc import _minimize_tnc +from ._cobyla_py import _minimize_cobyla +from ._cobyqa_py import _minimize_cobyqa +from ._slsqp_py import _minimize_slsqp +from ._constraints import (old_bound_to_new, new_bounds_to_old, + old_constraint_to_new, new_constraint_to_old, + NonlinearConstraint, LinearConstraint, Bounds, + PreparedConstraint) +from ._differentiable_functions import FD_METHODS + +MINIMIZE_METHODS = ['nelder-mead', 'powell', 'cg', 'bfgs', 'newton-cg', + 'l-bfgs-b', 'tnc', 'cobyla', 'cobyqa', 'slsqp', + 'trust-constr', 'dogleg', 'trust-ncg', 'trust-exact', + 'trust-krylov'] + +# These methods support the new callback interface (passed an OptimizeResult) +MINIMIZE_METHODS_NEW_CB = ['nelder-mead', 'powell', 'cg', 'bfgs', 'newton-cg', + 'l-bfgs-b', 'trust-constr', 'dogleg', 'trust-ncg', + 'trust-exact', 'trust-krylov', 'cobyqa'] + +MINIMIZE_SCALAR_METHODS = ['brent', 'bounded', 'golden'] + +def minimize(fun, x0, args=(), method=None, jac=None, hess=None, + hessp=None, bounds=None, constraints=(), tol=None, + callback=None, options=None): + """Minimization of scalar function of one or more variables. + + Parameters + ---------- + fun : callable + The objective function to be minimized:: + + fun(x, *args) -> float + + where ``x`` is a 1-D array with shape (n,) and ``args`` + is a tuple of the fixed parameters needed to completely + specify the function. + + Suppose the callable has signature ``f0(x, *my_args, **my_kwargs)``, where + ``my_args`` and ``my_kwargs`` are required positional and keyword arguments. + Rather than passing ``f0`` as the callable, wrap it to accept + only ``x``; e.g., pass ``fun=lambda x: f0(x, *my_args, **my_kwargs)`` as the + callable, where ``my_args`` (tuple) and ``my_kwargs`` (dict) have been + gathered before invoking this function. + x0 : ndarray, shape (n,) + Initial guess. Array of real elements of size (n,), + where ``n`` is the number of independent variables. + args : tuple, optional + Extra arguments passed to the objective function and its + derivatives (`fun`, `jac` and `hess` functions). + method : str or callable, optional + Type of solver. Should be one of + + - 'Nelder-Mead' :ref:`(see here) ` + - 'Powell' :ref:`(see here) ` + - 'CG' :ref:`(see here) ` + - 'BFGS' :ref:`(see here) ` + - 'Newton-CG' :ref:`(see here) ` + - 'L-BFGS-B' :ref:`(see here) ` + - 'TNC' :ref:`(see here) ` + - 'COBYLA' :ref:`(see here) ` + - 'COBYQA' :ref:`(see here) ` + - 'SLSQP' :ref:`(see here) ` + - 'trust-constr':ref:`(see here) ` + - 'dogleg' :ref:`(see here) ` + - 'trust-ncg' :ref:`(see here) ` + - 'trust-exact' :ref:`(see here) ` + - 'trust-krylov' :ref:`(see here) ` + - custom - a callable object, see below for description. + + If not given, chosen to be one of ``BFGS``, ``L-BFGS-B``, ``SLSQP``, + depending on whether or not the problem has constraints or bounds. + jac : {callable, '2-point', '3-point', 'cs', bool}, optional + Method for computing the gradient vector. Only for CG, BFGS, + Newton-CG, L-BFGS-B, TNC, SLSQP, dogleg, trust-ncg, trust-krylov, + trust-exact and trust-constr. + If it is a callable, it should be a function that returns the gradient + vector:: + + jac(x, *args) -> array_like, shape (n,) + + where ``x`` is an array with shape (n,) and ``args`` is a tuple with + the fixed parameters. If `jac` is a Boolean and is True, `fun` is + assumed to return a tuple ``(f, g)`` containing the objective + function and the gradient. + Methods 'Newton-CG', 'trust-ncg', 'dogleg', 'trust-exact', and + 'trust-krylov' require that either a callable be supplied, or that + `fun` return the objective and gradient. + If None or False, the gradient will be estimated using 2-point finite + difference estimation with an absolute step size. + Alternatively, the keywords {'2-point', '3-point', 'cs'} can be used + to select a finite difference scheme for numerical estimation of the + gradient with a relative step size. These finite difference schemes + obey any specified `bounds`. + hess : {callable, '2-point', '3-point', 'cs', HessianUpdateStrategy}, optional + Method for computing the Hessian matrix. Only for Newton-CG, dogleg, + trust-ncg, trust-krylov, trust-exact and trust-constr. + If it is callable, it should return the Hessian matrix:: + + hess(x, *args) -> {LinearOperator, spmatrix, array}, (n, n) + + where ``x`` is a (n,) ndarray and ``args`` is a tuple with the fixed + parameters. + The keywords {'2-point', '3-point', 'cs'} can also be used to select + a finite difference scheme for numerical estimation of the hessian. + Alternatively, objects implementing the `HessianUpdateStrategy` + interface can be used to approximate the Hessian. Available + quasi-Newton methods implementing this interface are: + + - `BFGS` + - `SR1` + + Not all of the options are available for each of the methods; for + availability refer to the notes. + hessp : callable, optional + Hessian of objective function times an arbitrary vector p. Only for + Newton-CG, trust-ncg, trust-krylov, trust-constr. + Only one of `hessp` or `hess` needs to be given. If `hess` is + provided, then `hessp` will be ignored. `hessp` must compute the + Hessian times an arbitrary vector:: + + hessp(x, p, *args) -> ndarray shape (n,) + + where ``x`` is a (n,) ndarray, ``p`` is an arbitrary vector with + dimension (n,) and ``args`` is a tuple with the fixed + parameters. + bounds : sequence or `Bounds`, optional + Bounds on variables for Nelder-Mead, L-BFGS-B, TNC, SLSQP, Powell, + trust-constr, COBYLA, and COBYQA methods. There are two ways to specify + the bounds: + + 1. Instance of `Bounds` class. + 2. Sequence of ``(min, max)`` pairs for each element in `x`. None + is used to specify no bound. + + constraints : {Constraint, dict} or List of {Constraint, dict}, optional + Constraints definition. Only for COBYLA, COBYQA, SLSQP and trust-constr. + + Constraints for 'trust-constr' and 'cobyqa' are defined as a single object + or a list of objects specifying constraints to the optimization problem. + Available constraints are: + + - `LinearConstraint` + - `NonlinearConstraint` + + Constraints for COBYLA, SLSQP are defined as a list of dictionaries. + Each dictionary with fields: + + type : str + Constraint type: 'eq' for equality, 'ineq' for inequality. + fun : callable + The function defining the constraint. + jac : callable, optional + The Jacobian of `fun` (only for SLSQP). + args : sequence, optional + Extra arguments to be passed to the function and Jacobian. + + Equality constraint means that the constraint function result is to + be zero whereas inequality means that it is to be non-negative. + Note that COBYLA only supports inequality constraints. + + tol : float, optional + Tolerance for termination. When `tol` is specified, the selected + minimization algorithm sets some relevant solver-specific tolerance(s) + equal to `tol`. For detailed control, use solver-specific + options. + options : dict, optional + A dictionary of solver options. All methods except `TNC` accept the + following generic options: + + maxiter : int + Maximum number of iterations to perform. Depending on the + method each iteration may use several function evaluations. + + For `TNC` use `maxfun` instead of `maxiter`. + disp : bool + Set to True to print convergence messages. + + For method-specific options, see :func:`show_options()`. + callback : callable, optional + A callable called after each iteration. + + All methods except TNC, SLSQP, and COBYLA support a callable with + the signature:: + + callback(intermediate_result: OptimizeResult) + + where ``intermediate_result`` is a keyword parameter containing an + `OptimizeResult` with attributes ``x`` and ``fun``, the present values + of the parameter vector and objective function. Note that the name + of the parameter must be ``intermediate_result`` for the callback + to be passed an `OptimizeResult`. These methods will also terminate if + the callback raises ``StopIteration``. + + All methods except trust-constr (also) support a signature like:: + + callback(xk) + + where ``xk`` is the current parameter vector. + + Introspection is used to determine which of the signatures above to + invoke. + + Returns + ------- + res : OptimizeResult + The optimization result represented as a ``OptimizeResult`` object. + Important attributes are: ``x`` the solution array, ``success`` a + Boolean flag indicating if the optimizer exited successfully and + ``message`` which describes the cause of the termination. See + `OptimizeResult` for a description of other attributes. + + See also + -------- + minimize_scalar : Interface to minimization algorithms for scalar + univariate functions + show_options : Additional options accepted by the solvers + + Notes + ----- + This section describes the available solvers that can be selected by the + 'method' parameter. The default method is *BFGS*. + + **Unconstrained minimization** + + Method :ref:`CG ` uses a nonlinear conjugate + gradient algorithm by Polak and Ribiere, a variant of the + Fletcher-Reeves method described in [5]_ pp.120-122. Only the + first derivatives are used. + + Method :ref:`BFGS ` uses the quasi-Newton + method of Broyden, Fletcher, Goldfarb, and Shanno (BFGS) [5]_ + pp. 136. It uses the first derivatives only. BFGS has proven good + performance even for non-smooth optimizations. This method also + returns an approximation of the Hessian inverse, stored as + `hess_inv` in the OptimizeResult object. + + Method :ref:`Newton-CG ` uses a + Newton-CG algorithm [5]_ pp. 168 (also known as the truncated + Newton method). It uses a CG method to the compute the search + direction. See also *TNC* method for a box-constrained + minimization with a similar algorithm. Suitable for large-scale + problems. + + Method :ref:`dogleg ` uses the dog-leg + trust-region algorithm [5]_ for unconstrained minimization. This + algorithm requires the gradient and Hessian; furthermore the + Hessian is required to be positive definite. + + Method :ref:`trust-ncg ` uses the + Newton conjugate gradient trust-region algorithm [5]_ for + unconstrained minimization. This algorithm requires the gradient + and either the Hessian or a function that computes the product of + the Hessian with a given vector. Suitable for large-scale problems. + + Method :ref:`trust-krylov ` uses + the Newton GLTR trust-region algorithm [14]_, [15]_ for unconstrained + minimization. This algorithm requires the gradient + and either the Hessian or a function that computes the product of + the Hessian with a given vector. Suitable for large-scale problems. + On indefinite problems it requires usually less iterations than the + `trust-ncg` method and is recommended for medium and large-scale problems. + + Method :ref:`trust-exact ` + is a trust-region method for unconstrained minimization in which + quadratic subproblems are solved almost exactly [13]_. This + algorithm requires the gradient and the Hessian (which is + *not* required to be positive definite). It is, in many + situations, the Newton method to converge in fewer iterations + and the most recommended for small and medium-size problems. + + **Bound-Constrained minimization** + + Method :ref:`Nelder-Mead ` uses the + Simplex algorithm [1]_, [2]_. This algorithm is robust in many + applications. However, if numerical computation of derivative can be + trusted, other algorithms using the first and/or second derivatives + information might be preferred for their better performance in + general. + + Method :ref:`L-BFGS-B ` uses the L-BFGS-B + algorithm [6]_, [7]_ for bound constrained minimization. + + Method :ref:`Powell ` is a modification + of Powell's method [3]_, [4]_ which is a conjugate direction + method. It performs sequential one-dimensional minimizations along + each vector of the directions set (`direc` field in `options` and + `info`), which is updated at each iteration of the main + minimization loop. The function need not be differentiable, and no + derivatives are taken. If bounds are not provided, then an + unbounded line search will be used. If bounds are provided and + the initial guess is within the bounds, then every function + evaluation throughout the minimization procedure will be within + the bounds. If bounds are provided, the initial guess is outside + the bounds, and `direc` is full rank (default has full rank), then + some function evaluations during the first iteration may be + outside the bounds, but every function evaluation after the first + iteration will be within the bounds. If `direc` is not full rank, + then some parameters may not be optimized and the solution is not + guaranteed to be within the bounds. + + Method :ref:`TNC ` uses a truncated Newton + algorithm [5]_, [8]_ to minimize a function with variables subject + to bounds. This algorithm uses gradient information; it is also + called Newton Conjugate-Gradient. It differs from the *Newton-CG* + method described above as it wraps a C implementation and allows + each variable to be given upper and lower bounds. + + **Constrained Minimization** + + Method :ref:`COBYLA ` uses the + Constrained Optimization BY Linear Approximation (COBYLA) method + [9]_, [10]_, [11]_. The algorithm is based on linear + approximations to the objective function and each constraint. The + method wraps a FORTRAN implementation of the algorithm. The + constraints functions 'fun' may return either a single number + or an array or list of numbers. + + Method :ref:`COBYQA ` uses the Constrained + Optimization BY Quadratic Approximations (COBYQA) method [18]_. The + algorithm is a derivative-free trust-region SQP method based on quadratic + approximations to the objective function and each nonlinear constraint. The + bounds are treated as unrelaxable constraints, in the sense that the + algorithm always respects them throughout the optimization process. + + Method :ref:`SLSQP ` uses Sequential + Least SQuares Programming to minimize a function of several + variables with any combination of bounds, equality and inequality + constraints. The method wraps the SLSQP Optimization subroutine + originally implemented by Dieter Kraft [12]_. Note that the + wrapper handles infinite values in bounds by converting them into + large floating values. + + Method :ref:`trust-constr ` is a + trust-region algorithm for constrained optimization. It switches + between two implementations depending on the problem definition. + It is the most versatile constrained minimization algorithm + implemented in SciPy and the most appropriate for large-scale problems. + For equality constrained problems it is an implementation of Byrd-Omojokun + Trust-Region SQP method described in [17]_ and in [5]_, p. 549. When + inequality constraints are imposed as well, it switches to the trust-region + interior point method described in [16]_. This interior point algorithm, + in turn, solves inequality constraints by introducing slack variables + and solving a sequence of equality-constrained barrier problems + for progressively smaller values of the barrier parameter. + The previously described equality constrained SQP method is + used to solve the subproblems with increasing levels of accuracy + as the iterate gets closer to a solution. + + **Finite-Difference Options** + + For Method :ref:`trust-constr ` + the gradient and the Hessian may be approximated using + three finite-difference schemes: {'2-point', '3-point', 'cs'}. + The scheme 'cs' is, potentially, the most accurate but it + requires the function to correctly handle complex inputs and to + be differentiable in the complex plane. The scheme '3-point' is more + accurate than '2-point' but requires twice as many operations. If the + gradient is estimated via finite-differences the Hessian must be + estimated using one of the quasi-Newton strategies. + + **Method specific options for the** `hess` **keyword** + + +--------------+------+----------+-------------------------+-----+ + | method/Hess | None | callable | '2-point/'3-point'/'cs' | HUS | + +==============+======+==========+=========================+=====+ + | Newton-CG | x | (n, n) | x | x | + | | | LO | | | + +--------------+------+----------+-------------------------+-----+ + | dogleg | | (n, n) | | | + +--------------+------+----------+-------------------------+-----+ + | trust-ncg | | (n, n) | x | x | + +--------------+------+----------+-------------------------+-----+ + | trust-krylov | | (n, n) | x | x | + +--------------+------+----------+-------------------------+-----+ + | trust-exact | | (n, n) | | | + +--------------+------+----------+-------------------------+-----+ + | trust-constr | x | (n, n) | x | x | + | | | LO | | | + | | | sp | | | + +--------------+------+----------+-------------------------+-----+ + + where LO=LinearOperator, sp=Sparse matrix, HUS=HessianUpdateStrategy + + **Custom minimizers** + + It may be useful to pass a custom minimization method, for example + when using a frontend to this method such as `scipy.optimize.basinhopping` + or a different library. You can simply pass a callable as the ``method`` + parameter. + + The callable is called as ``method(fun, x0, args, **kwargs, **options)`` + where ``kwargs`` corresponds to any other parameters passed to `minimize` + (such as `callback`, `hess`, etc.), except the `options` dict, which has + its contents also passed as `method` parameters pair by pair. Also, if + `jac` has been passed as a bool type, `jac` and `fun` are mangled so that + `fun` returns just the function values and `jac` is converted to a function + returning the Jacobian. The method shall return an `OptimizeResult` + object. + + The provided `method` callable must be able to accept (and possibly ignore) + arbitrary parameters; the set of parameters accepted by `minimize` may + expand in future versions and then these parameters will be passed to + the method. You can find an example in the scipy.optimize tutorial. + + References + ---------- + .. [1] Nelder, J A, and R Mead. 1965. A Simplex Method for Function + Minimization. The Computer Journal 7: 308-13. + .. [2] Wright M H. 1996. Direct search methods: Once scorned, now + respectable, in Numerical Analysis 1995: Proceedings of the 1995 + Dundee Biennial Conference in Numerical Analysis (Eds. D F + Griffiths and G A Watson). Addison Wesley Longman, Harlow, UK. + 191-208. + .. [3] Powell, M J D. 1964. An efficient method for finding the minimum of + a function of several variables without calculating derivatives. The + Computer Journal 7: 155-162. + .. [4] Press W, S A Teukolsky, W T Vetterling and B P Flannery. + Numerical Recipes (any edition), Cambridge University Press. + .. [5] Nocedal, J, and S J Wright. 2006. Numerical Optimization. + Springer New York. + .. [6] Byrd, R H and P Lu and J. Nocedal. 1995. A Limited Memory + Algorithm for Bound Constrained Optimization. SIAM Journal on + Scientific and Statistical Computing 16 (5): 1190-1208. + .. [7] Zhu, C and R H Byrd and J Nocedal. 1997. L-BFGS-B: Algorithm + 778: L-BFGS-B, FORTRAN routines for large scale bound constrained + optimization. ACM Transactions on Mathematical Software 23 (4): + 550-560. + .. [8] Nash, S G. Newton-Type Minimization Via the Lanczos Method. + 1984. SIAM Journal of Numerical Analysis 21: 770-778. + .. [9] Powell, M J D. A direct search optimization method that models + the objective and constraint functions by linear interpolation. + 1994. Advances in Optimization and Numerical Analysis, eds. S. Gomez + and J-P Hennart, Kluwer Academic (Dordrecht), 51-67. + .. [10] Powell M J D. Direct search algorithms for optimization + calculations. 1998. Acta Numerica 7: 287-336. + .. [11] Powell M J D. A view of algorithms for optimization without + derivatives. 2007.Cambridge University Technical Report DAMTP + 2007/NA03 + .. [12] Kraft, D. A software package for sequential quadratic + programming. 1988. Tech. Rep. DFVLR-FB 88-28, DLR German Aerospace + Center -- Institute for Flight Mechanics, Koln, Germany. + .. [13] Conn, A. R., Gould, N. I., and Toint, P. L. + Trust region methods. 2000. Siam. pp. 169-200. + .. [14] F. Lenders, C. Kirches, A. Potschka: "trlib: A vector-free + implementation of the GLTR method for iterative solution of + the trust region problem", :arxiv:`1611.04718` + .. [15] N. Gould, S. Lucidi, M. Roma, P. Toint: "Solving the + Trust-Region Subproblem using the Lanczos Method", + SIAM J. Optim., 9(2), 504--525, (1999). + .. [16] Byrd, Richard H., Mary E. Hribar, and Jorge Nocedal. 1999. + An interior point algorithm for large-scale nonlinear programming. + SIAM Journal on Optimization 9.4: 877-900. + .. [17] Lalee, Marucha, Jorge Nocedal, and Todd Plantenga. 1998. On the + implementation of an algorithm for large-scale equality constrained + optimization. SIAM Journal on Optimization 8.3: 682-706. + .. [18] Ragonneau, T. M. *Model-Based Derivative-Free Optimization Methods + and Software*. PhD thesis, Department of Applied Mathematics, The Hong + Kong Polytechnic University, Hong Kong, China, 2022. URL: + https://theses.lib.polyu.edu.hk/handle/200/12294. + + Examples + -------- + Let us consider the problem of minimizing the Rosenbrock function. This + function (and its respective derivatives) is implemented in `rosen` + (resp. `rosen_der`, `rosen_hess`) in the `scipy.optimize`. + + >>> from scipy.optimize import minimize, rosen, rosen_der + + A simple application of the *Nelder-Mead* method is: + + >>> x0 = [1.3, 0.7, 0.8, 1.9, 1.2] + >>> res = minimize(rosen, x0, method='Nelder-Mead', tol=1e-6) + >>> res.x + array([ 1., 1., 1., 1., 1.]) + + Now using the *BFGS* algorithm, using the first derivative and a few + options: + + >>> res = minimize(rosen, x0, method='BFGS', jac=rosen_der, + ... options={'gtol': 1e-6, 'disp': True}) + Optimization terminated successfully. + Current function value: 0.000000 + Iterations: 26 + Function evaluations: 31 + Gradient evaluations: 31 + >>> res.x + array([ 1., 1., 1., 1., 1.]) + >>> print(res.message) + Optimization terminated successfully. + >>> res.hess_inv + array([ + [ 0.00749589, 0.01255155, 0.02396251, 0.04750988, 0.09495377], # may vary + [ 0.01255155, 0.02510441, 0.04794055, 0.09502834, 0.18996269], + [ 0.02396251, 0.04794055, 0.09631614, 0.19092151, 0.38165151], + [ 0.04750988, 0.09502834, 0.19092151, 0.38341252, 0.7664427 ], + [ 0.09495377, 0.18996269, 0.38165151, 0.7664427, 1.53713523] + ]) + + + Next, consider a minimization problem with several constraints (namely + Example 16.4 from [5]_). The objective function is: + + >>> fun = lambda x: (x[0] - 1)**2 + (x[1] - 2.5)**2 + + There are three constraints defined as: + + >>> cons = ({'type': 'ineq', 'fun': lambda x: x[0] - 2 * x[1] + 2}, + ... {'type': 'ineq', 'fun': lambda x: -x[0] - 2 * x[1] + 6}, + ... {'type': 'ineq', 'fun': lambda x: -x[0] + 2 * x[1] + 2}) + + And variables must be positive, hence the following bounds: + + >>> bnds = ((0, None), (0, None)) + + The optimization problem is solved using the SLSQP method as: + + >>> res = minimize(fun, (2, 0), method='SLSQP', bounds=bnds, + ... constraints=cons) + + It should converge to the theoretical solution (1.4 ,1.7). + + """ + x0 = np.atleast_1d(np.asarray(x0)) + + if x0.ndim != 1: + raise ValueError("'x0' must only have one dimension.") + + if x0.dtype.kind in np.typecodes["AllInteger"]: + x0 = np.asarray(x0, dtype=float) + + if not isinstance(args, tuple): + args = (args,) + + if method is None: + # Select automatically + if constraints: + method = 'SLSQP' + elif bounds is not None: + method = 'L-BFGS-B' + else: + method = 'BFGS' + + if callable(method): + meth = "_custom" + else: + meth = method.lower() + + if options is None: + options = {} + # check if optional parameters are supported by the selected method + # - jac + if meth in ('nelder-mead', 'powell', 'cobyla', 'cobyqa') and bool(jac): + warn(f'Method {method} does not use gradient information (jac).', + RuntimeWarning, stacklevel=2) + # - hess + if meth not in ('newton-cg', 'dogleg', 'trust-ncg', 'trust-constr', + 'trust-krylov', 'trust-exact', '_custom') and hess is not None: + warn(f'Method {method} does not use Hessian information (hess).', + RuntimeWarning, stacklevel=2) + # - hessp + if meth not in ('newton-cg', 'trust-ncg', 'trust-constr', + 'trust-krylov', '_custom') \ + and hessp is not None: + warn(f'Method {method} does not use Hessian-vector product' + ' information (hessp).', + RuntimeWarning, stacklevel=2) + # - constraints or bounds + if (meth not in ('cobyla', 'cobyqa', 'slsqp', 'trust-constr', '_custom') and + np.any(constraints)): + warn(f'Method {method} cannot handle constraints.', + RuntimeWarning, stacklevel=2) + if meth not in ( + 'nelder-mead', 'powell', 'l-bfgs-b', 'cobyla', 'cobyqa', 'slsqp', + 'tnc', 'trust-constr', '_custom') and bounds is not None: + warn(f'Method {method} cannot handle bounds.', + RuntimeWarning, stacklevel=2) + # - return_all + if (meth in ('l-bfgs-b', 'tnc', 'cobyla', 'cobyqa', 'slsqp') and + options.get('return_all', False)): + warn(f'Method {method} does not support the return_all option.', + RuntimeWarning, stacklevel=2) + + # check gradient vector + if callable(jac): + pass + elif jac is True: + # fun returns func and grad + fun = MemoizeJac(fun) + jac = fun.derivative + elif (jac in FD_METHODS and + meth in ['trust-constr', 'bfgs', 'cg', 'l-bfgs-b', 'tnc', 'slsqp']): + # finite differences with relative step + pass + elif meth in ['trust-constr']: + # default jac calculation for this method + jac = '2-point' + elif jac is None or bool(jac) is False: + # this will cause e.g. LBFGS to use forward difference, absolute step + jac = None + else: + # default if jac option is not understood + jac = None + + # set default tolerances + if tol is not None: + options = dict(options) + if meth == 'nelder-mead': + options.setdefault('xatol', tol) + options.setdefault('fatol', tol) + if meth in ('newton-cg', 'powell', 'tnc'): + options.setdefault('xtol', tol) + if meth in ('powell', 'l-bfgs-b', 'tnc', 'slsqp'): + options.setdefault('ftol', tol) + if meth in ('bfgs', 'cg', 'l-bfgs-b', 'tnc', 'dogleg', + 'trust-ncg', 'trust-exact', 'trust-krylov'): + options.setdefault('gtol', tol) + if meth in ('cobyla', '_custom'): + options.setdefault('tol', tol) + if meth == 'cobyqa': + options.setdefault('final_tr_radius', tol) + if meth == 'trust-constr': + options.setdefault('xtol', tol) + options.setdefault('gtol', tol) + options.setdefault('barrier_tol', tol) + + if meth == '_custom': + # custom method called before bounds and constraints are 'standardised' + # custom method should be able to accept whatever bounds/constraints + # are provided to it. + return method(fun, x0, args=args, jac=jac, hess=hess, hessp=hessp, + bounds=bounds, constraints=constraints, + callback=callback, **options) + + constraints = standardize_constraints(constraints, x0, meth) + + remove_vars = False + if bounds is not None: + # convert to new-style bounds so we only have to consider one case + bounds = standardize_bounds(bounds, x0, 'new') + bounds = _validate_bounds(bounds, x0, meth) + + if meth in {"tnc", "slsqp", "l-bfgs-b"}: + # These methods can't take the finite-difference derivatives they + # need when a variable is fixed by the bounds. To avoid this issue, + # remove fixed variables from the problem. + # NOTE: if this list is expanded, then be sure to update the + # accompanying tests and test_optimize.eb_data. Consider also if + # default OptimizeResult will need updating. + + # determine whether any variables are fixed + i_fixed = (bounds.lb == bounds.ub) + + if np.all(i_fixed): + # all the parameters are fixed, a minimizer is not able to do + # anything + return _optimize_result_for_equal_bounds( + fun, bounds, meth, args=args, constraints=constraints + ) + + # determine whether finite differences are needed for any grad/jac + fd_needed = (not callable(jac)) + for con in constraints: + if not callable(con.get('jac', None)): + fd_needed = True + + # If finite differences are ever used, remove all fixed variables + # Always remove fixed variables for TNC; see gh-14565 + remove_vars = i_fixed.any() and (fd_needed or meth == "tnc") + if remove_vars: + x_fixed = (bounds.lb)[i_fixed] + x0 = x0[~i_fixed] + bounds = _remove_from_bounds(bounds, i_fixed) + fun = _remove_from_func(fun, i_fixed, x_fixed) + if callable(callback): + callback = _remove_from_func(callback, i_fixed, x_fixed) + if callable(jac): + jac = _remove_from_func(jac, i_fixed, x_fixed, remove=1) + + # make a copy of the constraints so the user's version doesn't + # get changed. (Shallow copy is ok) + constraints = [con.copy() for con in constraints] + for con in constraints: # yes, guaranteed to be a list + con['fun'] = _remove_from_func(con['fun'], i_fixed, + x_fixed, min_dim=1, + remove=0) + if callable(con.get('jac', None)): + con['jac'] = _remove_from_func(con['jac'], i_fixed, + x_fixed, min_dim=2, + remove=1) + bounds = standardize_bounds(bounds, x0, meth) + + callback = _wrap_callback(callback, meth) + + if meth == 'nelder-mead': + res = _minimize_neldermead(fun, x0, args, callback, bounds=bounds, + **options) + elif meth == 'powell': + res = _minimize_powell(fun, x0, args, callback, bounds, **options) + elif meth == 'cg': + res = _minimize_cg(fun, x0, args, jac, callback, **options) + elif meth == 'bfgs': + res = _minimize_bfgs(fun, x0, args, jac, callback, **options) + elif meth == 'newton-cg': + res = _minimize_newtoncg(fun, x0, args, jac, hess, hessp, callback, + **options) + elif meth == 'l-bfgs-b': + res = _minimize_lbfgsb(fun, x0, args, jac, bounds, + callback=callback, **options) + elif meth == 'tnc': + res = _minimize_tnc(fun, x0, args, jac, bounds, callback=callback, + **options) + elif meth == 'cobyla': + res = _minimize_cobyla(fun, x0, args, constraints, callback=callback, + bounds=bounds, **options) + elif meth == 'cobyqa': + res = _minimize_cobyqa(fun, x0, args, bounds, constraints, callback, + **options) + elif meth == 'slsqp': + res = _minimize_slsqp(fun, x0, args, jac, bounds, + constraints, callback=callback, **options) + elif meth == 'trust-constr': + res = _minimize_trustregion_constr(fun, x0, args, jac, hess, hessp, + bounds, constraints, + callback=callback, **options) + elif meth == 'dogleg': + res = _minimize_dogleg(fun, x0, args, jac, hess, + callback=callback, **options) + elif meth == 'trust-ncg': + res = _minimize_trust_ncg(fun, x0, args, jac, hess, hessp, + callback=callback, **options) + elif meth == 'trust-krylov': + res = _minimize_trust_krylov(fun, x0, args, jac, hess, hessp, + callback=callback, **options) + elif meth == 'trust-exact': + res = _minimize_trustregion_exact(fun, x0, args, jac, hess, + callback=callback, **options) + else: + raise ValueError(f'Unknown solver {method}') + + if remove_vars: + res.x = _add_to_array(res.x, i_fixed, x_fixed) + res.jac = _add_to_array(res.jac, i_fixed, np.nan) + if "hess_inv" in res: + res.hess_inv = None # unknown + + if getattr(callback, 'stop_iteration', False): + res.success = False + res.status = 99 + res.message = "`callback` raised `StopIteration`." + + return res + + +def minimize_scalar(fun, bracket=None, bounds=None, args=(), + method=None, tol=None, options=None): + """Local minimization of scalar function of one variable. + + Parameters + ---------- + fun : callable + Objective function. + Scalar function, must return a scalar. + + Suppose the callable has signature ``f0(x, *my_args, **my_kwargs)``, where + ``my_args`` and ``my_kwargs`` are required positional and keyword arguments. + Rather than passing ``f0`` as the callable, wrap it to accept + only ``x``; e.g., pass ``fun=lambda x: f0(x, *my_args, **my_kwargs)`` as the + callable, where ``my_args`` (tuple) and ``my_kwargs`` (dict) have been + gathered before invoking this function. + + bracket : sequence, optional + For methods 'brent' and 'golden', `bracket` defines the bracketing + interval and is required. + Either a triple ``(xa, xb, xc)`` satisfying ``xa < xb < xc`` and + ``func(xb) < func(xa) and func(xb) < func(xc)``, or a pair + ``(xa, xb)`` to be used as initial points for a downhill bracket search + (see `scipy.optimize.bracket`). + The minimizer ``res.x`` will not necessarily satisfy + ``xa <= res.x <= xb``. + bounds : sequence, optional + For method 'bounded', `bounds` is mandatory and must have two finite + items corresponding to the optimization bounds. + args : tuple, optional + Extra arguments passed to the objective function. + method : str or callable, optional + Type of solver. Should be one of: + + - :ref:`Brent ` + - :ref:`Bounded ` + - :ref:`Golden ` + - custom - a callable object (added in version 0.14.0), see below + + Default is "Bounded" if bounds are provided and "Brent" otherwise. + See the 'Notes' section for details of each solver. + + tol : float, optional + Tolerance for termination. For detailed control, use solver-specific + options. + options : dict, optional + A dictionary of solver options. + + maxiter : int + Maximum number of iterations to perform. + disp : bool + Set to True to print convergence messages. + + See :func:`show_options()` for solver-specific options. + + Returns + ------- + res : OptimizeResult + The optimization result represented as a ``OptimizeResult`` object. + Important attributes are: ``x`` the solution array, ``success`` a + Boolean flag indicating if the optimizer exited successfully and + ``message`` which describes the cause of the termination. See + `OptimizeResult` for a description of other attributes. + + See also + -------- + minimize : Interface to minimization algorithms for scalar multivariate + functions + show_options : Additional options accepted by the solvers + + Notes + ----- + This section describes the available solvers that can be selected by the + 'method' parameter. The default method is the ``"Bounded"`` Brent method if + `bounds` are passed and unbounded ``"Brent"`` otherwise. + + Method :ref:`Brent ` uses Brent's + algorithm [1]_ to find a local minimum. The algorithm uses inverse + parabolic interpolation when possible to speed up convergence of + the golden section method. + + Method :ref:`Golden ` uses the + golden section search technique [1]_. It uses analog of the bisection + method to decrease the bracketed interval. It is usually + preferable to use the *Brent* method. + + Method :ref:`Bounded ` can + perform bounded minimization [2]_ [3]_. It uses the Brent method to find a + local minimum in the interval x1 < xopt < x2. + + Note that the Brent and Golden methods do not guarantee success unless a + valid ``bracket`` triple is provided. If a three-point bracket cannot be + found, consider `scipy.optimize.minimize`. Also, all methods are intended + only for local minimization. When the function of interest has more than + one local minimum, consider :ref:`global_optimization`. + + **Custom minimizers** + + It may be useful to pass a custom minimization method, for example + when using some library frontend to minimize_scalar. You can simply + pass a callable as the ``method`` parameter. + + The callable is called as ``method(fun, args, **kwargs, **options)`` + where ``kwargs`` corresponds to any other parameters passed to `minimize` + (such as `bracket`, `tol`, etc.), except the `options` dict, which has + its contents also passed as `method` parameters pair by pair. The method + shall return an `OptimizeResult` object. + + The provided `method` callable must be able to accept (and possibly ignore) + arbitrary parameters; the set of parameters accepted by `minimize` may + expand in future versions and then these parameters will be passed to + the method. You can find an example in the scipy.optimize tutorial. + + .. versionadded:: 0.11.0 + + References + ---------- + .. [1] Press, W., S.A. Teukolsky, W.T. Vetterling, and B.P. Flannery. + Numerical Recipes in C. Cambridge University Press. + .. [2] Forsythe, G.E., M. A. Malcolm, and C. B. Moler. "Computer Methods + for Mathematical Computations." Prentice-Hall Series in Automatic + Computation 259 (1977). + .. [3] Brent, Richard P. Algorithms for Minimization Without Derivatives. + Courier Corporation, 2013. + + Examples + -------- + Consider the problem of minimizing the following function. + + >>> def f(x): + ... return (x - 2) * x * (x + 2)**2 + + Using the *Brent* method, we find the local minimum as: + + >>> from scipy.optimize import minimize_scalar + >>> res = minimize_scalar(f) + >>> res.fun + -9.9149495908 + + The minimizer is: + + >>> res.x + 1.28077640403 + + Using the *Bounded* method, we find a local minimum with specified + bounds as: + + >>> res = minimize_scalar(f, bounds=(-3, -1), method='bounded') + >>> res.fun # minimum + 3.28365179850e-13 + >>> res.x # minimizer + -2.0000002026 + + """ + if not isinstance(args, tuple): + args = (args,) + + if callable(method): + meth = "_custom" + elif method is None: + meth = 'brent' if bounds is None else 'bounded' + else: + meth = method.lower() + if options is None: + options = {} + + if bounds is not None and meth in {'brent', 'golden'}: + message = f"Use of `bounds` is incompatible with 'method={method}'." + raise ValueError(message) + + if tol is not None: + options = dict(options) + if meth == 'bounded' and 'xatol' not in options: + warn("Method 'bounded' does not support relative tolerance in x; " + "defaulting to absolute tolerance.", + RuntimeWarning, stacklevel=2) + options['xatol'] = tol + elif meth == '_custom': + options.setdefault('tol', tol) + else: + options.setdefault('xtol', tol) + + # replace boolean "disp" option, if specified, by an integer value. + disp = options.get('disp') + if isinstance(disp, bool): + options['disp'] = 2 * int(disp) + + if meth == '_custom': + res = method(fun, args=args, bracket=bracket, bounds=bounds, **options) + elif meth == 'brent': + res = _recover_from_bracket_error(_minimize_scalar_brent, + fun, bracket, args, **options) + elif meth == 'bounded': + if bounds is None: + raise ValueError('The `bounds` parameter is mandatory for ' + 'method `bounded`.') + res = _minimize_scalar_bounded(fun, bounds, args, **options) + elif meth == 'golden': + res = _recover_from_bracket_error(_minimize_scalar_golden, + fun, bracket, args, **options) + else: + raise ValueError(f'Unknown solver {method}') + + # gh-16196 reported inconsistencies in the output shape of `res.x`. While + # fixing this, future-proof it for when the function is vectorized: + # the shape of `res.x` should match that of `res.fun`. + res.fun = np.asarray(res.fun)[()] + res.x = np.reshape(res.x, res.fun.shape)[()] + return res + + +def _remove_from_bounds(bounds, i_fixed): + """Removes fixed variables from a `Bounds` instance""" + lb = bounds.lb[~i_fixed] + ub = bounds.ub[~i_fixed] + return Bounds(lb, ub) # don't mutate original Bounds object + + +def _remove_from_func(fun_in, i_fixed, x_fixed, min_dim=None, remove=0): + """Wraps a function such that fixed variables need not be passed in""" + def fun_out(x_in, *args, **kwargs): + x_out = np.zeros_like(i_fixed, dtype=x_in.dtype) + x_out[i_fixed] = x_fixed + x_out[~i_fixed] = x_in + y_out = fun_in(x_out, *args, **kwargs) + y_out = np.array(y_out) + + if min_dim == 1: + y_out = np.atleast_1d(y_out) + elif min_dim == 2: + y_out = np.atleast_2d(y_out) + + if remove == 1: + y_out = y_out[..., ~i_fixed] + elif remove == 2: + y_out = y_out[~i_fixed, ~i_fixed] + + return y_out + return fun_out + + +def _add_to_array(x_in, i_fixed, x_fixed): + """Adds fixed variables back to an array""" + i_free = ~i_fixed + if x_in.ndim == 2: + i_free = i_free[:, None] @ i_free[None, :] + x_out = np.zeros_like(i_free, dtype=x_in.dtype) + x_out[~i_free] = x_fixed + x_out[i_free] = x_in.ravel() + return x_out + + +def _validate_bounds(bounds, x0, meth): + """Check that bounds are valid.""" + + msg = "An upper bound is less than the corresponding lower bound." + if np.any(bounds.ub < bounds.lb): + raise ValueError(msg) + + msg = "The number of bounds is not compatible with the length of `x0`." + try: + bounds.lb = np.broadcast_to(bounds.lb, x0.shape) + bounds.ub = np.broadcast_to(bounds.ub, x0.shape) + except Exception as e: + raise ValueError(msg) from e + + return bounds + +def standardize_bounds(bounds, x0, meth): + """Converts bounds to the form required by the solver.""" + if meth in {'trust-constr', 'powell', 'nelder-mead', 'cobyla', 'cobyqa', + 'new'}: + if not isinstance(bounds, Bounds): + lb, ub = old_bound_to_new(bounds) + bounds = Bounds(lb, ub) + elif meth in ('l-bfgs-b', 'tnc', 'slsqp', 'old'): + if isinstance(bounds, Bounds): + bounds = new_bounds_to_old(bounds.lb, bounds.ub, x0.shape[0]) + return bounds + + +def standardize_constraints(constraints, x0, meth): + """Converts constraints to the form required by the solver.""" + all_constraint_types = (NonlinearConstraint, LinearConstraint, dict) + new_constraint_types = all_constraint_types[:-1] + if constraints is None: + constraints = [] + elif isinstance(constraints, all_constraint_types): + constraints = [constraints] + else: + constraints = list(constraints) # ensure it's a mutable sequence + + if meth in ['trust-constr', 'cobyqa', 'new']: + for i, con in enumerate(constraints): + if not isinstance(con, new_constraint_types): + constraints[i] = old_constraint_to_new(i, con) + else: + # iterate over copy, changing original + for i, con in enumerate(list(constraints)): + if isinstance(con, new_constraint_types): + old_constraints = new_constraint_to_old(con, x0) + constraints[i] = old_constraints[0] + constraints.extend(old_constraints[1:]) # appends 1 if present + + return constraints + + +def _optimize_result_for_equal_bounds( + fun, bounds, method, args=(), constraints=() +): + """ + Provides a default OptimizeResult for when a bounded minimization method + has (lb == ub).all(). + + Parameters + ---------- + fun: callable + bounds: Bounds + method: str + constraints: Constraint + """ + success = True + message = 'All independent variables were fixed by bounds.' + + # bounds is new-style + x0 = bounds.lb + + if constraints: + message = ("All independent variables were fixed by bounds at values" + " that satisfy the constraints.") + constraints = standardize_constraints(constraints, x0, 'new') + + maxcv = 0 + for c in constraints: + pc = PreparedConstraint(c, x0) + violation = pc.violation(x0) + if np.sum(violation): + maxcv = max(maxcv, np.max(violation)) + success = False + message = (f"All independent variables were fixed by bounds, but " + f"the independent variables do not satisfy the " + f"constraints exactly. (Maximum violation: {maxcv}).") + + return OptimizeResult( + x=x0, fun=fun(x0, *args), success=success, message=message, nfev=1, + njev=0, nhev=0, + ) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_minpack.cpython-310-x86_64-linux-gnu.so b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_minpack.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..710d8c41decf596e7481bfb8d88d30f008d6f967 Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_minpack.cpython-310-x86_64-linux-gnu.so differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_minpack_py.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_minpack_py.py new file mode 100644 index 0000000000000000000000000000000000000000..8cfce8aae21b7533fb1cb7385d0d5f48740e743b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_minpack_py.py @@ -0,0 +1,1171 @@ +import warnings +from . import _minpack + +import numpy as np +from numpy import (atleast_1d, triu, shape, transpose, zeros, prod, greater, + asarray, inf, + finfo, inexact, issubdtype, dtype) +from scipy import linalg +from scipy.linalg import svd, cholesky, solve_triangular, LinAlgError +from scipy._lib._util import _asarray_validated, _lazywhere, _contains_nan +from scipy._lib._util import getfullargspec_no_self as _getfullargspec +from ._optimize import OptimizeResult, _check_unknown_options, OptimizeWarning +from ._lsq import least_squares +# from ._lsq.common import make_strictly_feasible +from ._lsq.least_squares import prepare_bounds +from scipy.optimize._minimize import Bounds + +__all__ = ['fsolve', 'leastsq', 'fixed_point', 'curve_fit'] + + +def _check_func(checker, argname, thefunc, x0, args, numinputs, + output_shape=None): + res = atleast_1d(thefunc(*((x0[:numinputs],) + args))) + if (output_shape is not None) and (shape(res) != output_shape): + if (output_shape[0] != 1): + if len(output_shape) > 1: + if output_shape[1] == 1: + return shape(res) + msg = f"{checker}: there is a mismatch between the input and output " \ + f"shape of the '{argname}' argument" + func_name = getattr(thefunc, '__name__', None) + if func_name: + msg += f" '{func_name}'." + else: + msg += "." + msg += f'Shape should be {output_shape} but it is {shape(res)}.' + raise TypeError(msg) + if issubdtype(res.dtype, inexact): + dt = res.dtype + else: + dt = dtype(float) + return shape(res), dt + + +def fsolve(func, x0, args=(), fprime=None, full_output=0, + col_deriv=0, xtol=1.49012e-8, maxfev=0, band=None, + epsfcn=None, factor=100, diag=None): + """ + Find the roots of a function. + + Return the roots of the (non-linear) equations defined by + ``func(x) = 0`` given a starting estimate. + + Parameters + ---------- + func : callable ``f(x, *args)`` + A function that takes at least one (possibly vector) argument, + and returns a value of the same length. + x0 : ndarray + The starting estimate for the roots of ``func(x) = 0``. + args : tuple, optional + Any extra arguments to `func`. + fprime : callable ``f(x, *args)``, optional + A function to compute the Jacobian of `func` with derivatives + across the rows. By default, the Jacobian will be estimated. + full_output : bool, optional + If True, return optional outputs. + col_deriv : bool, optional + Specify whether the Jacobian function computes derivatives down + the columns (faster, because there is no transpose operation). + xtol : float, optional + The calculation will terminate if the relative error between two + consecutive iterates is at most `xtol`. + maxfev : int, optional + The maximum number of calls to the function. If zero, then + ``100*(N+1)`` is the maximum where N is the number of elements + in `x0`. + band : tuple, optional + If set to a two-sequence containing the number of sub- and + super-diagonals within the band of the Jacobi matrix, the + Jacobi matrix is considered banded (only for ``fprime=None``). + epsfcn : float, optional + A suitable step length for the forward-difference + approximation of the Jacobian (for ``fprime=None``). If + `epsfcn` is less than the machine precision, it is assumed + that the relative errors in the functions are of the order of + the machine precision. + factor : float, optional + A parameter determining the initial step bound + (``factor * || diag * x||``). Should be in the interval + ``(0.1, 100)``. + diag : sequence, optional + N positive entries that serve as a scale factors for the + variables. + + Returns + ------- + x : ndarray + The solution (or the result of the last iteration for + an unsuccessful call). + infodict : dict + A dictionary of optional outputs with the keys: + + ``nfev`` + number of function calls + ``njev`` + number of Jacobian calls + ``fvec`` + function evaluated at the output + ``fjac`` + the orthogonal matrix, q, produced by the QR + factorization of the final approximate Jacobian + matrix, stored column wise + ``r`` + upper triangular matrix produced by QR factorization + of the same matrix + ``qtf`` + the vector ``(transpose(q) * fvec)`` + + ier : int + An integer flag. Set to 1 if a solution was found, otherwise refer + to `mesg` for more information. + mesg : str + If no solution is found, `mesg` details the cause of failure. + + See Also + -------- + root : Interface to root finding algorithms for multivariate + functions. See the ``method='hybr'`` in particular. + + Notes + ----- + ``fsolve`` is a wrapper around MINPACK's hybrd and hybrj algorithms. + + Examples + -------- + Find a solution to the system of equations: + ``x0*cos(x1) = 4, x1*x0 - x1 = 5``. + + >>> import numpy as np + >>> from scipy.optimize import fsolve + >>> def func(x): + ... return [x[0] * np.cos(x[1]) - 4, + ... x[1] * x[0] - x[1] - 5] + >>> root = fsolve(func, [1, 1]) + >>> root + array([6.50409711, 0.90841421]) + >>> np.isclose(func(root), [0.0, 0.0]) # func(root) should be almost 0.0. + array([ True, True]) + + """ + def _wrapped_func(*fargs): + """ + Wrapped `func` to track the number of times + the function has been called. + """ + _wrapped_func.nfev += 1 + return func(*fargs) + + _wrapped_func.nfev = 0 + + options = {'col_deriv': col_deriv, + 'xtol': xtol, + 'maxfev': maxfev, + 'band': band, + 'eps': epsfcn, + 'factor': factor, + 'diag': diag} + + res = _root_hybr(_wrapped_func, x0, args, jac=fprime, **options) + res.nfev = _wrapped_func.nfev + + if full_output: + x = res['x'] + info = {k: res.get(k) + for k in ('nfev', 'njev', 'fjac', 'r', 'qtf') if k in res} + info['fvec'] = res['fun'] + return x, info, res['status'], res['message'] + else: + status = res['status'] + msg = res['message'] + if status == 0: + raise TypeError(msg) + elif status == 1: + pass + elif status in [2, 3, 4, 5]: + warnings.warn(msg, RuntimeWarning, stacklevel=2) + else: + raise TypeError(msg) + return res['x'] + + +def _root_hybr(func, x0, args=(), jac=None, + col_deriv=0, xtol=1.49012e-08, maxfev=0, band=None, eps=None, + factor=100, diag=None, **unknown_options): + """ + Find the roots of a multivariate function using MINPACK's hybrd and + hybrj routines (modified Powell method). + + Options + ------- + col_deriv : bool + Specify whether the Jacobian function computes derivatives down + the columns (faster, because there is no transpose operation). + xtol : float + The calculation will terminate if the relative error between two + consecutive iterates is at most `xtol`. + maxfev : int + The maximum number of calls to the function. If zero, then + ``100*(N+1)`` is the maximum where N is the number of elements + in `x0`. + band : tuple + If set to a two-sequence containing the number of sub- and + super-diagonals within the band of the Jacobi matrix, the + Jacobi matrix is considered banded (only for ``jac=None``). + eps : float + A suitable step length for the forward-difference + approximation of the Jacobian (for ``jac=None``). If + `eps` is less than the machine precision, it is assumed + that the relative errors in the functions are of the order of + the machine precision. + factor : float + A parameter determining the initial step bound + (``factor * || diag * x||``). Should be in the interval + ``(0.1, 100)``. + diag : sequence + N positive entries that serve as a scale factors for the + variables. + + """ + _check_unknown_options(unknown_options) + epsfcn = eps + + x0 = asarray(x0).flatten() + n = len(x0) + if not isinstance(args, tuple): + args = (args,) + shape, dtype = _check_func('fsolve', 'func', func, x0, args, n, (n,)) + if epsfcn is None: + epsfcn = finfo(dtype).eps + Dfun = jac + if Dfun is None: + if band is None: + ml, mu = -10, -10 + else: + ml, mu = band[:2] + if maxfev == 0: + maxfev = 200 * (n + 1) + retval = _minpack._hybrd(func, x0, args, 1, xtol, maxfev, + ml, mu, epsfcn, factor, diag) + else: + _check_func('fsolve', 'fprime', Dfun, x0, args, n, (n, n)) + if (maxfev == 0): + maxfev = 100 * (n + 1) + retval = _minpack._hybrj(func, Dfun, x0, args, 1, + col_deriv, xtol, maxfev, factor, diag) + + x, status = retval[0], retval[-1] + + errors = {0: "Improper input parameters were entered.", + 1: "The solution converged.", + 2: "The number of calls to function has " + "reached maxfev = %d." % maxfev, + 3: f"xtol={xtol:f} is too small, no further improvement " + "in the approximate\n solution is possible.", + 4: "The iteration is not making good progress, as measured " + "by the \n improvement from the last five " + "Jacobian evaluations.", + 5: "The iteration is not making good progress, " + "as measured by the \n improvement from the last " + "ten iterations.", + 'unknown': "An error occurred."} + + info = retval[1] + info['fun'] = info.pop('fvec') + sol = OptimizeResult(x=x, success=(status == 1), status=status, + method="hybr") + sol.update(info) + try: + sol['message'] = errors[status] + except KeyError: + sol['message'] = errors['unknown'] + + return sol + + +LEASTSQ_SUCCESS = [1, 2, 3, 4] +LEASTSQ_FAILURE = [5, 6, 7, 8] + + +def leastsq(func, x0, args=(), Dfun=None, full_output=False, + col_deriv=False, ftol=1.49012e-8, xtol=1.49012e-8, + gtol=0.0, maxfev=0, epsfcn=None, factor=100, diag=None): + """ + Minimize the sum of squares of a set of equations. + + :: + + x = arg min(sum(func(y)**2,axis=0)) + y + + Parameters + ---------- + func : callable + Should take at least one (possibly length ``N`` vector) argument and + returns ``M`` floating point numbers. It must not return NaNs or + fitting might fail. ``M`` must be greater than or equal to ``N``. + x0 : ndarray + The starting estimate for the minimization. + args : tuple, optional + Any extra arguments to func are placed in this tuple. + Dfun : callable, optional + A function or method to compute the Jacobian of func with derivatives + across the rows. If this is None, the Jacobian will be estimated. + full_output : bool, optional + If ``True``, return all optional outputs (not just `x` and `ier`). + col_deriv : bool, optional + If ``True``, specify that the Jacobian function computes derivatives + down the columns (faster, because there is no transpose operation). + ftol : float, optional + Relative error desired in the sum of squares. + xtol : float, optional + Relative error desired in the approximate solution. + gtol : float, optional + Orthogonality desired between the function vector and the columns of + the Jacobian. + maxfev : int, optional + The maximum number of calls to the function. If `Dfun` is provided, + then the default `maxfev` is 100*(N+1) where N is the number of elements + in x0, otherwise the default `maxfev` is 200*(N+1). + epsfcn : float, optional + A variable used in determining a suitable step length for the forward- + difference approximation of the Jacobian (for Dfun=None). + Normally the actual step length will be sqrt(epsfcn)*x + If epsfcn is less than the machine precision, it is assumed that the + relative errors are of the order of the machine precision. + factor : float, optional + A parameter determining the initial step bound + (``factor * || diag * x||``). Should be in interval ``(0.1, 100)``. + diag : sequence, optional + N positive entries that serve as a scale factors for the variables. + + Returns + ------- + x : ndarray + The solution (or the result of the last iteration for an unsuccessful + call). + cov_x : ndarray + The inverse of the Hessian. `fjac` and `ipvt` are used to construct an + estimate of the Hessian. A value of None indicates a singular matrix, + which means the curvature in parameters `x` is numerically flat. To + obtain the covariance matrix of the parameters `x`, `cov_x` must be + multiplied by the variance of the residuals -- see curve_fit. Only + returned if `full_output` is ``True``. + infodict : dict + a dictionary of optional outputs with the keys: + + ``nfev`` + The number of function calls + ``fvec`` + The function evaluated at the output + ``fjac`` + A permutation of the R matrix of a QR + factorization of the final approximate + Jacobian matrix, stored column wise. + Together with ipvt, the covariance of the + estimate can be approximated. + ``ipvt`` + An integer array of length N which defines + a permutation matrix, p, such that + fjac*p = q*r, where r is upper triangular + with diagonal elements of nonincreasing + magnitude. Column j of p is column ipvt(j) + of the identity matrix. + ``qtf`` + The vector (transpose(q) * fvec). + + Only returned if `full_output` is ``True``. + mesg : str + A string message giving information about the cause of failure. + Only returned if `full_output` is ``True``. + ier : int + An integer flag. If it is equal to 1, 2, 3 or 4, the solution was + found. Otherwise, the solution was not found. In either case, the + optional output variable 'mesg' gives more information. + + See Also + -------- + least_squares : Newer interface to solve nonlinear least-squares problems + with bounds on the variables. See ``method='lm'`` in particular. + + Notes + ----- + "leastsq" is a wrapper around MINPACK's lmdif and lmder algorithms. + + cov_x is a Jacobian approximation to the Hessian of the least squares + objective function. + This approximation assumes that the objective function is based on the + difference between some observed target data (ydata) and a (non-linear) + function of the parameters `f(xdata, params)` :: + + func(params) = ydata - f(xdata, params) + + so that the objective function is :: + + min sum((ydata - f(xdata, params))**2, axis=0) + params + + The solution, `x`, is always a 1-D array, regardless of the shape of `x0`, + or whether `x0` is a scalar. + + Examples + -------- + >>> from scipy.optimize import leastsq + >>> def func(x): + ... return 2*(x-3)**2+1 + >>> leastsq(func, 0) + (array([2.99999999]), 1) + + """ + x0 = asarray(x0).flatten() + n = len(x0) + if not isinstance(args, tuple): + args = (args,) + shape, dtype = _check_func('leastsq', 'func', func, x0, args, n) + m = shape[0] + + if n > m: + raise TypeError(f"Improper input: func input vector length N={n} must" + f" not exceed func output vector length M={m}") + + if epsfcn is None: + epsfcn = finfo(dtype).eps + + if Dfun is None: + if maxfev == 0: + maxfev = 200*(n + 1) + retval = _minpack._lmdif(func, x0, args, full_output, ftol, xtol, + gtol, maxfev, epsfcn, factor, diag) + else: + if col_deriv: + _check_func('leastsq', 'Dfun', Dfun, x0, args, n, (n, m)) + else: + _check_func('leastsq', 'Dfun', Dfun, x0, args, n, (m, n)) + if maxfev == 0: + maxfev = 100 * (n + 1) + retval = _minpack._lmder(func, Dfun, x0, args, full_output, + col_deriv, ftol, xtol, gtol, maxfev, + factor, diag) + + errors = {0: ["Improper input parameters.", TypeError], + 1: ["Both actual and predicted relative reductions " + f"in the sum of squares\n are at most {ftol:f}", None], + 2: ["The relative error between two consecutive " + f"iterates is at most {xtol:f}", None], + 3: ["Both actual and predicted relative reductions in " + f"the sum of squares\n are at most {ftol:f} and the " + "relative error between two consecutive " + f"iterates is at \n most {xtol:f}", None], + 4: ["The cosine of the angle between func(x) and any " + f"column of the\n Jacobian is at most {gtol:f} in " + "absolute value", None], + 5: ["Number of calls to function has reached " + "maxfev = %d." % maxfev, ValueError], + 6: [f"ftol={ftol:f} is too small, no further reduction " + "in the sum of squares\n is possible.", + ValueError], + 7: [f"xtol={xtol:f} is too small, no further improvement in " + "the approximate\n solution is possible.", + ValueError], + 8: [f"gtol={gtol:f} is too small, func(x) is orthogonal to the " + "columns of\n the Jacobian to machine precision.", ValueError]} + + # The FORTRAN return value (possible return values are >= 0 and <= 8) + info = retval[-1] + + if full_output: + cov_x = None + if info in LEASTSQ_SUCCESS: + # This was + # perm = take(eye(n), retval[1]['ipvt'] - 1, 0) + # r = triu(transpose(retval[1]['fjac'])[:n, :]) + # R = dot(r, perm) + # cov_x = inv(dot(transpose(R), R)) + # but the explicit dot product was not necessary and sometimes + # the result was not symmetric positive definite. See gh-4555. + perm = retval[1]['ipvt'] + n = len(perm) + r = triu(transpose(retval[1]['fjac'])[:n, :]) + inv_triu = linalg.get_lapack_funcs('trtri', (r,)) + try: + # inverse of permuted matrix is a permutation of matrix inverse + invR, trtri_info = inv_triu(r) # default: upper, non-unit diag + if trtri_info != 0: # explicit comparison for readability + raise LinAlgError(f'trtri returned info {trtri_info}') + invR[perm] = invR.copy() + cov_x = invR @ invR.T + except (LinAlgError, ValueError): + pass + return (retval[0], cov_x) + retval[1:-1] + (errors[info][0], info) + else: + if info in LEASTSQ_FAILURE: + warnings.warn(errors[info][0], RuntimeWarning, stacklevel=2) + elif info == 0: + raise errors[info][1](errors[info][0]) + return retval[0], info + + +def _lightweight_memoizer(f): + # very shallow memoization to address gh-13670: only remember the first set + # of parameters and corresponding function value, and only attempt to use + # them twice (the number of times the function is evaluated at x0). + def _memoized_func(params): + if _memoized_func.skip_lookup: + return f(params) + + if np.all(_memoized_func.last_params == params): + return _memoized_func.last_val + elif _memoized_func.last_params is not None: + _memoized_func.skip_lookup = True + + val = f(params) + + if _memoized_func.last_params is None: + _memoized_func.last_params = np.copy(params) + _memoized_func.last_val = val + + return val + + _memoized_func.last_params = None + _memoized_func.last_val = None + _memoized_func.skip_lookup = False + return _memoized_func + + +def _wrap_func(func, xdata, ydata, transform): + if transform is None: + def func_wrapped(params): + return func(xdata, *params) - ydata + elif transform.size == 1 or transform.ndim == 1: + def func_wrapped(params): + return transform * (func(xdata, *params) - ydata) + else: + # Chisq = (y - yd)^T C^{-1} (y-yd) + # transform = L such that C = L L^T + # C^{-1} = L^{-T} L^{-1} + # Chisq = (y - yd)^T L^{-T} L^{-1} (y-yd) + # Define (y-yd)' = L^{-1} (y-yd) + # by solving + # L (y-yd)' = (y-yd) + # and minimize (y-yd)'^T (y-yd)' + def func_wrapped(params): + return solve_triangular(transform, func(xdata, *params) - ydata, lower=True) + return func_wrapped + + +def _wrap_jac(jac, xdata, transform): + if transform is None: + def jac_wrapped(params): + return jac(xdata, *params) + elif transform.ndim == 1: + def jac_wrapped(params): + return transform[:, np.newaxis] * np.asarray(jac(xdata, *params)) + else: + def jac_wrapped(params): + return solve_triangular(transform, + np.asarray(jac(xdata, *params)), + lower=True) + return jac_wrapped + + +def _initialize_feasible(lb, ub): + p0 = np.ones_like(lb) + lb_finite = np.isfinite(lb) + ub_finite = np.isfinite(ub) + + mask = lb_finite & ub_finite + p0[mask] = 0.5 * (lb[mask] + ub[mask]) + + mask = lb_finite & ~ub_finite + p0[mask] = lb[mask] + 1 + + mask = ~lb_finite & ub_finite + p0[mask] = ub[mask] - 1 + + return p0 + + +def curve_fit(f, xdata, ydata, p0=None, sigma=None, absolute_sigma=False, + check_finite=None, bounds=(-np.inf, np.inf), method=None, + jac=None, *, full_output=False, nan_policy=None, + **kwargs): + """ + Use non-linear least squares to fit a function, f, to data. + + Assumes ``ydata = f(xdata, *params) + eps``. + + Parameters + ---------- + f : callable + The model function, f(x, ...). It must take the independent + variable as the first argument and the parameters to fit as + separate remaining arguments. + xdata : array_like + The independent variable where the data is measured. + Should usually be an M-length sequence or an (k,M)-shaped array for + functions with k predictors, and each element should be float + convertible if it is an array like object. + ydata : array_like + The dependent data, a length M array - nominally ``f(xdata, ...)``. + p0 : array_like, optional + Initial guess for the parameters (length N). If None, then the + initial values will all be 1 (if the number of parameters for the + function can be determined using introspection, otherwise a + ValueError is raised). + sigma : None or scalar or M-length sequence or MxM array, optional + Determines the uncertainty in `ydata`. If we define residuals as + ``r = ydata - f(xdata, *popt)``, then the interpretation of `sigma` + depends on its number of dimensions: + + - A scalar or 1-D `sigma` should contain values of standard deviations of + errors in `ydata`. In this case, the optimized function is + ``chisq = sum((r / sigma) ** 2)``. + + - A 2-D `sigma` should contain the covariance matrix of + errors in `ydata`. In this case, the optimized function is + ``chisq = r.T @ inv(sigma) @ r``. + + .. versionadded:: 0.19 + + None (default) is equivalent of 1-D `sigma` filled with ones. + absolute_sigma : bool, optional + If True, `sigma` is used in an absolute sense and the estimated parameter + covariance `pcov` reflects these absolute values. + + If False (default), only the relative magnitudes of the `sigma` values matter. + The returned parameter covariance matrix `pcov` is based on scaling + `sigma` by a constant factor. This constant is set by demanding that the + reduced `chisq` for the optimal parameters `popt` when using the + *scaled* `sigma` equals unity. In other words, `sigma` is scaled to + match the sample variance of the residuals after the fit. Default is False. + Mathematically, + ``pcov(absolute_sigma=False) = pcov(absolute_sigma=True) * chisq(popt)/(M-N)`` + check_finite : bool, optional + If True, check that the input arrays do not contain nans of infs, + and raise a ValueError if they do. Setting this parameter to + False may silently produce nonsensical results if the input arrays + do contain nans. Default is True if `nan_policy` is not specified + explicitly and False otherwise. + bounds : 2-tuple of array_like or `Bounds`, optional + Lower and upper bounds on parameters. Defaults to no bounds. + There are two ways to specify the bounds: + + - Instance of `Bounds` class. + + - 2-tuple of array_like: Each element of the tuple must be either + an array with the length equal to the number of parameters, or a + scalar (in which case the bound is taken to be the same for all + parameters). Use ``np.inf`` with an appropriate sign to disable + bounds on all or some parameters. + + method : {'lm', 'trf', 'dogbox'}, optional + Method to use for optimization. See `least_squares` for more details. + Default is 'lm' for unconstrained problems and 'trf' if `bounds` are + provided. The method 'lm' won't work when the number of observations + is less than the number of variables, use 'trf' or 'dogbox' in this + case. + + .. versionadded:: 0.17 + jac : callable, string or None, optional + Function with signature ``jac(x, ...)`` which computes the Jacobian + matrix of the model function with respect to parameters as a dense + array_like structure. It will be scaled according to provided `sigma`. + If None (default), the Jacobian will be estimated numerically. + String keywords for 'trf' and 'dogbox' methods can be used to select + a finite difference scheme, see `least_squares`. + + .. versionadded:: 0.18 + full_output : boolean, optional + If True, this function returns additional information: `infodict`, + `mesg`, and `ier`. + + .. versionadded:: 1.9 + nan_policy : {'raise', 'omit', None}, optional + Defines how to handle when input contains nan. + The following options are available (default is None): + + * 'raise': throws an error + * 'omit': performs the calculations ignoring nan values + * None: no special handling of NaNs is performed + (except what is done by check_finite); the behavior when NaNs + are present is implementation-dependent and may change. + + Note that if this value is specified explicitly (not None), + `check_finite` will be set as False. + + .. versionadded:: 1.11 + **kwargs + Keyword arguments passed to `leastsq` for ``method='lm'`` or + `least_squares` otherwise. + + Returns + ------- + popt : array + Optimal values for the parameters so that the sum of the squared + residuals of ``f(xdata, *popt) - ydata`` is minimized. + pcov : 2-D array + The estimated approximate covariance of popt. The diagonals provide + the variance of the parameter estimate. To compute one standard + deviation errors on the parameters, use + ``perr = np.sqrt(np.diag(pcov))``. Note that the relationship between + `cov` and parameter error estimates is derived based on a linear + approximation to the model function around the optimum [1]_. + When this approximation becomes inaccurate, `cov` may not provide an + accurate measure of uncertainty. + + How the `sigma` parameter affects the estimated covariance + depends on `absolute_sigma` argument, as described above. + + If the Jacobian matrix at the solution doesn't have a full rank, then + 'lm' method returns a matrix filled with ``np.inf``, on the other hand + 'trf' and 'dogbox' methods use Moore-Penrose pseudoinverse to compute + the covariance matrix. Covariance matrices with large condition numbers + (e.g. computed with `numpy.linalg.cond`) may indicate that results are + unreliable. + infodict : dict (returned only if `full_output` is True) + a dictionary of optional outputs with the keys: + + ``nfev`` + The number of function calls. Methods 'trf' and 'dogbox' do not + count function calls for numerical Jacobian approximation, + as opposed to 'lm' method. + ``fvec`` + The residual values evaluated at the solution, for a 1-D `sigma` + this is ``(f(x, *popt) - ydata)/sigma``. + ``fjac`` + A permutation of the R matrix of a QR + factorization of the final approximate + Jacobian matrix, stored column wise. + Together with ipvt, the covariance of the + estimate can be approximated. + Method 'lm' only provides this information. + ``ipvt`` + An integer array of length N which defines + a permutation matrix, p, such that + fjac*p = q*r, where r is upper triangular + with diagonal elements of nonincreasing + magnitude. Column j of p is column ipvt(j) + of the identity matrix. + Method 'lm' only provides this information. + ``qtf`` + The vector (transpose(q) * fvec). + Method 'lm' only provides this information. + + .. versionadded:: 1.9 + mesg : str (returned only if `full_output` is True) + A string message giving information about the solution. + + .. versionadded:: 1.9 + ier : int (returned only if `full_output` is True) + An integer flag. If it is equal to 1, 2, 3 or 4, the solution was + found. Otherwise, the solution was not found. In either case, the + optional output variable `mesg` gives more information. + + .. versionadded:: 1.9 + + Raises + ------ + ValueError + if either `ydata` or `xdata` contain NaNs, or if incompatible options + are used. + + RuntimeError + if the least-squares minimization fails. + + OptimizeWarning + if covariance of the parameters can not be estimated. + + See Also + -------- + least_squares : Minimize the sum of squares of nonlinear functions. + scipy.stats.linregress : Calculate a linear least squares regression for + two sets of measurements. + + Notes + ----- + Users should ensure that inputs `xdata`, `ydata`, and the output of `f` + are ``float64``, or else the optimization may return incorrect results. + + With ``method='lm'``, the algorithm uses the Levenberg-Marquardt algorithm + through `leastsq`. Note that this algorithm can only deal with + unconstrained problems. + + Box constraints can be handled by methods 'trf' and 'dogbox'. Refer to + the docstring of `least_squares` for more information. + + Parameters to be fitted must have similar scale. Differences of multiple + orders of magnitude can lead to incorrect results. For the 'trf' and + 'dogbox' methods, the `x_scale` keyword argument can be used to scale + the parameters. + + References + ---------- + .. [1] K. Vugrin et al. Confidence region estimation techniques for nonlinear + regression in groundwater flow: Three case studies. Water Resources + Research, Vol. 43, W03423, :doi:`10.1029/2005WR004804` + + Examples + -------- + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.optimize import curve_fit + + >>> def func(x, a, b, c): + ... return a * np.exp(-b * x) + c + + Define the data to be fit with some noise: + + >>> xdata = np.linspace(0, 4, 50) + >>> y = func(xdata, 2.5, 1.3, 0.5) + >>> rng = np.random.default_rng() + >>> y_noise = 0.2 * rng.normal(size=xdata.size) + >>> ydata = y + y_noise + >>> plt.plot(xdata, ydata, 'b-', label='data') + + Fit for the parameters a, b, c of the function `func`: + + >>> popt, pcov = curve_fit(func, xdata, ydata) + >>> popt + array([2.56274217, 1.37268521, 0.47427475]) + >>> plt.plot(xdata, func(xdata, *popt), 'r-', + ... label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt)) + + Constrain the optimization to the region of ``0 <= a <= 3``, + ``0 <= b <= 1`` and ``0 <= c <= 0.5``: + + >>> popt, pcov = curve_fit(func, xdata, ydata, bounds=(0, [3., 1., 0.5])) + >>> popt + array([2.43736712, 1. , 0.34463856]) + >>> plt.plot(xdata, func(xdata, *popt), 'g--', + ... label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt)) + + >>> plt.xlabel('x') + >>> plt.ylabel('y') + >>> plt.legend() + >>> plt.show() + + For reliable results, the model `func` should not be overparametrized; + redundant parameters can cause unreliable covariance matrices and, in some + cases, poorer quality fits. As a quick check of whether the model may be + overparameterized, calculate the condition number of the covariance matrix: + + >>> np.linalg.cond(pcov) + 34.571092161547405 # may vary + + The value is small, so it does not raise much concern. If, however, we were + to add a fourth parameter ``d`` to `func` with the same effect as ``a``: + + >>> def func2(x, a, b, c, d): + ... return a * d * np.exp(-b * x) + c # a and d are redundant + >>> popt, pcov = curve_fit(func2, xdata, ydata) + >>> np.linalg.cond(pcov) + 1.13250718925596e+32 # may vary + + Such a large value is cause for concern. The diagonal elements of the + covariance matrix, which is related to uncertainty of the fit, gives more + information: + + >>> np.diag(pcov) + array([1.48814742e+29, 3.78596560e-02, 5.39253738e-03, 2.76417220e+28]) # may vary + + Note that the first and last terms are much larger than the other elements, + suggesting that the optimal values of these parameters are ambiguous and + that only one of these parameters is needed in the model. + + If the optimal parameters of `f` differ by multiple orders of magnitude, the + resulting fit can be inaccurate. Sometimes, `curve_fit` can fail to find any + results: + + >>> ydata = func(xdata, 500000, 0.01, 15) + >>> try: + ... popt, pcov = curve_fit(func, xdata, ydata, method = 'trf') + ... except RuntimeError as e: + ... print(e) + Optimal parameters not found: The maximum number of function evaluations is + exceeded. + + If parameter scale is roughly known beforehand, it can be defined in + `x_scale` argument: + + >>> popt, pcov = curve_fit(func, xdata, ydata, method = 'trf', + ... x_scale = [1000, 1, 1]) + >>> popt + array([5.00000000e+05, 1.00000000e-02, 1.49999999e+01]) + """ + if p0 is None: + # determine number of parameters by inspecting the function + sig = _getfullargspec(f) + args = sig.args + if len(args) < 2: + raise ValueError("Unable to determine number of fit parameters.") + n = len(args) - 1 + else: + p0 = np.atleast_1d(p0) + n = p0.size + + if isinstance(bounds, Bounds): + lb, ub = bounds.lb, bounds.ub + else: + lb, ub = prepare_bounds(bounds, n) + if p0 is None: + p0 = _initialize_feasible(lb, ub) + + bounded_problem = np.any((lb > -np.inf) | (ub < np.inf)) + if method is None: + if bounded_problem: + method = 'trf' + else: + method = 'lm' + + if method == 'lm' and bounded_problem: + raise ValueError("Method 'lm' only works for unconstrained problems. " + "Use 'trf' or 'dogbox' instead.") + + if check_finite is None: + check_finite = True if nan_policy is None else False + + # optimization may produce garbage for float32 inputs, cast them to float64 + if check_finite: + ydata = np.asarray_chkfinite(ydata, float) + else: + ydata = np.asarray(ydata, float) + + if isinstance(xdata, (list, tuple, np.ndarray)): + # `xdata` is passed straight to the user-defined `f`, so allow + # non-array_like `xdata`. + if check_finite: + xdata = np.asarray_chkfinite(xdata, float) + else: + xdata = np.asarray(xdata, float) + + if ydata.size == 0: + raise ValueError("`ydata` must not be empty!") + + # nan handling is needed only if check_finite is False because if True, + # the x-y data are already checked, and they don't contain nans. + if not check_finite and nan_policy is not None: + if nan_policy == "propagate": + raise ValueError("`nan_policy='propagate'` is not supported " + "by this function.") + + policies = [None, 'raise', 'omit'] + x_contains_nan, nan_policy = _contains_nan(xdata, nan_policy, + policies=policies) + y_contains_nan, nan_policy = _contains_nan(ydata, nan_policy, + policies=policies) + + if (x_contains_nan or y_contains_nan) and nan_policy == 'omit': + # ignore NaNs for N dimensional arrays + has_nan = np.isnan(xdata) + has_nan = has_nan.any(axis=tuple(range(has_nan.ndim-1))) + has_nan |= np.isnan(ydata) + + xdata = xdata[..., ~has_nan] + ydata = ydata[~has_nan] + + # Also omit the corresponding entries from sigma + if sigma is not None: + sigma = np.asarray(sigma) + if sigma.ndim == 1: + sigma = sigma[~has_nan] + elif sigma.ndim == 2: + sigma = sigma[~has_nan, :] + sigma = sigma[:, ~has_nan] + + # Determine type of sigma + if sigma is not None: + sigma = np.asarray(sigma) + + # if 1-D or a scalar, sigma are errors, define transform = 1/sigma + if sigma.size == 1 or sigma.shape == (ydata.size,): + transform = 1.0 / sigma + # if 2-D, sigma is the covariance matrix, + # define transform = L such that L L^T = C + elif sigma.shape == (ydata.size, ydata.size): + try: + # scipy.linalg.cholesky requires lower=True to return L L^T = A + transform = cholesky(sigma, lower=True) + except LinAlgError as e: + raise ValueError("`sigma` must be positive definite.") from e + else: + raise ValueError("`sigma` has incorrect shape.") + else: + transform = None + + func = _lightweight_memoizer(_wrap_func(f, xdata, ydata, transform)) + + if callable(jac): + jac = _lightweight_memoizer(_wrap_jac(jac, xdata, transform)) + elif jac is None and method != 'lm': + jac = '2-point' + + if 'args' in kwargs: + # The specification for the model function `f` does not support + # additional arguments. Refer to the `curve_fit` docstring for + # acceptable call signatures of `f`. + raise ValueError("'args' is not a supported keyword argument.") + + if method == 'lm': + # if ydata.size == 1, this might be used for broadcast. + if ydata.size != 1 and n > ydata.size: + raise TypeError(f"The number of func parameters={n} must not" + f" exceed the number of data points={ydata.size}") + res = leastsq(func, p0, Dfun=jac, full_output=1, **kwargs) + popt, pcov, infodict, errmsg, ier = res + ysize = len(infodict['fvec']) + cost = np.sum(infodict['fvec'] ** 2) + if ier not in [1, 2, 3, 4]: + raise RuntimeError("Optimal parameters not found: " + errmsg) + else: + # Rename maxfev (leastsq) to max_nfev (least_squares), if specified. + if 'max_nfev' not in kwargs: + kwargs['max_nfev'] = kwargs.pop('maxfev', None) + + res = least_squares(func, p0, jac=jac, bounds=bounds, method=method, + **kwargs) + + if not res.success: + raise RuntimeError("Optimal parameters not found: " + res.message) + + infodict = dict(nfev=res.nfev, fvec=res.fun) + ier = res.status + errmsg = res.message + + ysize = len(res.fun) + cost = 2 * res.cost # res.cost is half sum of squares! + popt = res.x + + # Do Moore-Penrose inverse discarding zero singular values. + _, s, VT = svd(res.jac, full_matrices=False) + threshold = np.finfo(float).eps * max(res.jac.shape) * s[0] + s = s[s > threshold] + VT = VT[:s.size] + pcov = np.dot(VT.T / s**2, VT) + + warn_cov = False + if pcov is None or np.isnan(pcov).any(): + # indeterminate covariance + pcov = zeros((len(popt), len(popt)), dtype=float) + pcov.fill(inf) + warn_cov = True + elif not absolute_sigma: + if ysize > p0.size: + s_sq = cost / (ysize - p0.size) + pcov = pcov * s_sq + else: + pcov.fill(inf) + warn_cov = True + + if warn_cov: + warnings.warn('Covariance of the parameters could not be estimated', + category=OptimizeWarning, stacklevel=2) + + if full_output: + return popt, pcov, infodict, errmsg, ier + else: + return popt, pcov + + +def check_gradient(fcn, Dfcn, x0, args=(), col_deriv=0): + """Perform a simple check on the gradient for correctness. + + """ + + x = atleast_1d(x0) + n = len(x) + x = x.reshape((n,)) + fvec = atleast_1d(fcn(x, *args)) + m = len(fvec) + fvec = fvec.reshape((m,)) + ldfjac = m + fjac = atleast_1d(Dfcn(x, *args)) + fjac = fjac.reshape((m, n)) + if col_deriv == 0: + fjac = transpose(fjac) + + xp = zeros((n,), float) + err = zeros((m,), float) + fvecp = None + _minpack._chkder(m, n, x, fvec, fjac, ldfjac, xp, fvecp, 1, err) + + fvecp = atleast_1d(fcn(xp, *args)) + fvecp = fvecp.reshape((m,)) + _minpack._chkder(m, n, x, fvec, fjac, ldfjac, xp, fvecp, 2, err) + + good = (prod(greater(err, 0.5), axis=0)) + + return (good, err) + + +def _del2(p0, p1, d): + return p0 - np.square(p1 - p0) / d + + +def _relerr(actual, desired): + return (actual - desired) / desired + + +def _fixed_point_helper(func, x0, args, xtol, maxiter, use_accel): + p0 = x0 + for i in range(maxiter): + p1 = func(p0, *args) + if use_accel: + p2 = func(p1, *args) + d = p2 - 2.0 * p1 + p0 + p = _lazywhere(d != 0, (p0, p1, d), f=_del2, fillvalue=p2) + else: + p = p1 + relerr = _lazywhere(p0 != 0, (p, p0), f=_relerr, fillvalue=p) + if np.all(np.abs(relerr) < xtol): + return p + p0 = p + msg = "Failed to converge after %d iterations, value is %s" % (maxiter, p) + raise RuntimeError(msg) + + +def fixed_point(func, x0, args=(), xtol=1e-8, maxiter=500, method='del2'): + """ + Find a fixed point of the function. + + Given a function of one or more variables and a starting point, find a + fixed point of the function: i.e., where ``func(x0) == x0``. + + Parameters + ---------- + func : function + Function to evaluate. + x0 : array_like + Fixed point of function. + args : tuple, optional + Extra arguments to `func`. + xtol : float, optional + Convergence tolerance, defaults to 1e-08. + maxiter : int, optional + Maximum number of iterations, defaults to 500. + method : {"del2", "iteration"}, optional + Method of finding the fixed-point, defaults to "del2", + which uses Steffensen's Method with Aitken's ``Del^2`` + convergence acceleration [1]_. The "iteration" method simply iterates + the function until convergence is detected, without attempting to + accelerate the convergence. + + References + ---------- + .. [1] Burden, Faires, "Numerical Analysis", 5th edition, pg. 80 + + Examples + -------- + >>> import numpy as np + >>> from scipy import optimize + >>> def func(x, c1, c2): + ... return np.sqrt(c1/(x+c2)) + >>> c1 = np.array([10,12.]) + >>> c2 = np.array([3, 5.]) + >>> optimize.fixed_point(func, [1.2, 1.3], args=(c1,c2)) + array([ 1.4920333 , 1.37228132]) + + """ + use_accel = {'del2': True, 'iteration': False}[method] + x0 = _asarray_validated(x0, as_inexact=True) + return _fixed_point_helper(func, x0, args, xtol, maxiter, use_accel) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_nnls.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_nnls.py new file mode 100644 index 0000000000000000000000000000000000000000..be904c90d715583faaf7751ce62b9c992e07e208 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_nnls.py @@ -0,0 +1,97 @@ +import numpy as np +from ._cython_nnls import _nnls + + +__all__ = ['nnls'] + + +def nnls(A, b, maxiter=None, *, atol=None): + """ + Solve ``argmin_x || Ax - b ||_2`` for ``x>=0``. + + This problem, often called as NonNegative Least Squares, is a convex + optimization problem with convex constraints. It typically arises when + the ``x`` models quantities for which only nonnegative values are + attainable; weight of ingredients, component costs and so on. + + Parameters + ---------- + A : (m, n) ndarray + Coefficient array + b : (m,) ndarray, float + Right-hand side vector. + maxiter: int, optional + Maximum number of iterations, optional. Default value is ``3 * n``. + atol: float + Tolerance value used in the algorithm to assess closeness to zero in + the projected residual ``(A.T @ (A x - b)`` entries. Increasing this + value relaxes the solution constraints. A typical relaxation value can + be selected as ``max(m, n) * np.linalg.norm(a, 1) * np.spacing(1.)``. + This value is not set as default since the norm operation becomes + expensive for large problems hence can be used only when necessary. + + Returns + ------- + x : ndarray + Solution vector. + rnorm : float + The 2-norm of the residual, ``|| Ax-b ||_2``. + + See Also + -------- + lsq_linear : Linear least squares with bounds on the variables + + Notes + ----- + The code is based on [2]_ which is an improved version of the classical + algorithm of [1]_. It utilizes an active set method and solves the KKT + (Karush-Kuhn-Tucker) conditions for the non-negative least squares problem. + + References + ---------- + .. [1] : Lawson C., Hanson R.J., "Solving Least Squares Problems", SIAM, + 1995, :doi:`10.1137/1.9781611971217` + .. [2] : Bro, Rasmus and de Jong, Sijmen, "A Fast Non-Negativity- + Constrained Least Squares Algorithm", Journal Of Chemometrics, 1997, + :doi:`10.1002/(SICI)1099-128X(199709/10)11:5<393::AID-CEM483>3.0.CO;2-L` + + Examples + -------- + >>> import numpy as np + >>> from scipy.optimize import nnls + ... + >>> A = np.array([[1, 0], [1, 0], [0, 1]]) + >>> b = np.array([2, 1, 1]) + >>> nnls(A, b) + (array([1.5, 1. ]), 0.7071067811865475) + + >>> b = np.array([-1, -1, -1]) + >>> nnls(A, b) + (array([0., 0.]), 1.7320508075688772) + + """ + + A = np.asarray_chkfinite(A, dtype=np.float64, order='C') + b = np.asarray_chkfinite(b, dtype=np.float64) + + if len(A.shape) != 2: + raise ValueError("Expected a two-dimensional array (matrix)" + + f", but the shape of A is {A.shape}") + if len(b.shape) != 1: + raise ValueError("Expected a one-dimensional array (vector)" + + f", but the shape of b is {b.shape}") + + m, n = A.shape + + if m != b.shape[0]: + raise ValueError( + "Incompatible dimensions. The first dimension of " + + f"A is {m}, while the shape of b is {(b.shape[0], )}") + + if not maxiter: + maxiter = 3*n + x, rnorm, info = _nnls(A, b, maxiter) + if info == -1: + raise RuntimeError("Maximum number of iterations reached.") + + return x, rnorm diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_nonlin.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_nonlin.py new file mode 100644 index 0000000000000000000000000000000000000000..b6e07683500bb01c195b1cdfa8a13157353b5370 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_nonlin.py @@ -0,0 +1,1603 @@ +# Copyright (C) 2009, Pauli Virtanen +# Distributed under the same license as SciPy. + +import inspect +import sys +import warnings + +import numpy as np +from numpy import asarray, dot, vdot + +from scipy.linalg import norm, solve, inv, qr, svd, LinAlgError +import scipy.sparse.linalg +import scipy.sparse +from scipy.linalg import get_blas_funcs +from scipy._lib._util import copy_if_needed +from scipy._lib._util import getfullargspec_no_self as _getfullargspec +from ._linesearch import scalar_search_wolfe1, scalar_search_armijo + + +__all__ = [ + 'broyden1', 'broyden2', 'anderson', 'linearmixing', + 'diagbroyden', 'excitingmixing', 'newton_krylov', + 'BroydenFirst', 'KrylovJacobian', 'InverseJacobian', 'NoConvergence'] + +#------------------------------------------------------------------------------ +# Utility functions +#------------------------------------------------------------------------------ + + +class NoConvergence(Exception): + """Exception raised when nonlinear solver fails to converge within the specified + `maxiter`.""" + pass + + +def maxnorm(x): + return np.absolute(x).max() + + +def _as_inexact(x): + """Return `x` as an array, of either floats or complex floats""" + x = asarray(x) + if not np.issubdtype(x.dtype, np.inexact): + return asarray(x, dtype=np.float64) + return x + + +def _array_like(x, x0): + """Return ndarray `x` as same array subclass and shape as `x0`""" + x = np.reshape(x, np.shape(x0)) + wrap = getattr(x0, '__array_wrap__', x.__array_wrap__) + return wrap(x) + + +def _safe_norm(v): + if not np.isfinite(v).all(): + return np.array(np.inf) + return norm(v) + +#------------------------------------------------------------------------------ +# Generic nonlinear solver machinery +#------------------------------------------------------------------------------ + + +_doc_parts = dict( + params_basic=""" + F : function(x) -> f + Function whose root to find; should take and return an array-like + object. + xin : array_like + Initial guess for the solution + """.strip(), + params_extra=""" + iter : int, optional + Number of iterations to make. If omitted (default), make as many + as required to meet tolerances. + verbose : bool, optional + Print status to stdout on every iteration. + maxiter : int, optional + Maximum number of iterations to make. If more are needed to + meet convergence, `NoConvergence` is raised. + f_tol : float, optional + Absolute tolerance (in max-norm) for the residual. + If omitted, default is 6e-6. + f_rtol : float, optional + Relative tolerance for the residual. If omitted, not used. + x_tol : float, optional + Absolute minimum step size, as determined from the Jacobian + approximation. If the step size is smaller than this, optimization + is terminated as successful. If omitted, not used. + x_rtol : float, optional + Relative minimum step size. If omitted, not used. + tol_norm : function(vector) -> scalar, optional + Norm to use in convergence check. Default is the maximum norm. + line_search : {None, 'armijo' (default), 'wolfe'}, optional + Which type of a line search to use to determine the step size in the + direction given by the Jacobian approximation. Defaults to 'armijo'. + callback : function, optional + Optional callback function. It is called on every iteration as + ``callback(x, f)`` where `x` is the current solution and `f` + the corresponding residual. + + Returns + ------- + sol : ndarray + An array (of similar array type as `x0`) containing the final solution. + + Raises + ------ + NoConvergence + When a solution was not found. + + """.strip() +) + + +def _set_doc(obj): + if obj.__doc__: + obj.__doc__ = obj.__doc__ % _doc_parts + + +def nonlin_solve(F, x0, jacobian='krylov', iter=None, verbose=False, + maxiter=None, f_tol=None, f_rtol=None, x_tol=None, x_rtol=None, + tol_norm=None, line_search='armijo', callback=None, + full_output=False, raise_exception=True): + """ + Find a root of a function, in a way suitable for large-scale problems. + + Parameters + ---------- + %(params_basic)s + jacobian : Jacobian + A Jacobian approximation: `Jacobian` object or something that + `asjacobian` can transform to one. Alternatively, a string specifying + which of the builtin Jacobian approximations to use: + + krylov, broyden1, broyden2, anderson + diagbroyden, linearmixing, excitingmixing + + %(params_extra)s + full_output : bool + If true, returns a dictionary `info` containing convergence + information. + raise_exception : bool + If True, a `NoConvergence` exception is raise if no solution is found. + + See Also + -------- + asjacobian, Jacobian + + Notes + ----- + This algorithm implements the inexact Newton method, with + backtracking or full line searches. Several Jacobian + approximations are available, including Krylov and Quasi-Newton + methods. + + References + ---------- + .. [KIM] C. T. Kelley, \"Iterative Methods for Linear and Nonlinear + Equations\". Society for Industrial and Applied Mathematics. (1995) + https://archive.siam.org/books/kelley/fr16/ + + """ + # Can't use default parameters because it's being explicitly passed as None + # from the calling function, so we need to set it here. + tol_norm = maxnorm if tol_norm is None else tol_norm + condition = TerminationCondition(f_tol=f_tol, f_rtol=f_rtol, + x_tol=x_tol, x_rtol=x_rtol, + iter=iter, norm=tol_norm) + + x0 = _as_inexact(x0) + def func(z): + return _as_inexact(F(_array_like(z, x0))).flatten() + x = x0.flatten() + + dx = np.full_like(x, np.inf) + Fx = func(x) + Fx_norm = norm(Fx) + + jacobian = asjacobian(jacobian) + jacobian.setup(x.copy(), Fx, func) + + if maxiter is None: + if iter is not None: + maxiter = iter + 1 + else: + maxiter = 100*(x.size+1) + + if line_search is True: + line_search = 'armijo' + elif line_search is False: + line_search = None + + if line_search not in (None, 'armijo', 'wolfe'): + raise ValueError("Invalid line search") + + # Solver tolerance selection + gamma = 0.9 + eta_max = 0.9999 + eta_treshold = 0.1 + eta = 1e-3 + + for n in range(maxiter): + status = condition.check(Fx, x, dx) + if status: + break + + # The tolerance, as computed for scipy.sparse.linalg.* routines + tol = min(eta, eta*Fx_norm) + dx = -jacobian.solve(Fx, tol=tol) + + if norm(dx) == 0: + raise ValueError("Jacobian inversion yielded zero vector. " + "This indicates a bug in the Jacobian " + "approximation.") + + # Line search, or Newton step + if line_search: + s, x, Fx, Fx_norm_new = _nonlin_line_search(func, x, Fx, dx, + line_search) + else: + s = 1.0 + x = x + dx + Fx = func(x) + Fx_norm_new = norm(Fx) + + jacobian.update(x.copy(), Fx) + + if callback: + callback(x, Fx) + + # Adjust forcing parameters for inexact methods + eta_A = gamma * Fx_norm_new**2 / Fx_norm**2 + if gamma * eta**2 < eta_treshold: + eta = min(eta_max, eta_A) + else: + eta = min(eta_max, max(eta_A, gamma*eta**2)) + + Fx_norm = Fx_norm_new + + # Print status + if verbose: + sys.stdout.write("%d: |F(x)| = %g; step %g\n" % ( + n, tol_norm(Fx), s)) + sys.stdout.flush() + else: + if raise_exception: + raise NoConvergence(_array_like(x, x0)) + else: + status = 2 + + if full_output: + info = {'nit': condition.iteration, + 'fun': Fx, + 'status': status, + 'success': status == 1, + 'message': {1: 'A solution was found at the specified ' + 'tolerance.', + 2: 'The maximum number of iterations allowed ' + 'has been reached.' + }[status] + } + return _array_like(x, x0), info + else: + return _array_like(x, x0) + + +_set_doc(nonlin_solve) + + +def _nonlin_line_search(func, x, Fx, dx, search_type='armijo', rdiff=1e-8, + smin=1e-2): + tmp_s = [0] + tmp_Fx = [Fx] + tmp_phi = [norm(Fx)**2] + s_norm = norm(x) / norm(dx) + + def phi(s, store=True): + if s == tmp_s[0]: + return tmp_phi[0] + xt = x + s*dx + v = func(xt) + p = _safe_norm(v)**2 + if store: + tmp_s[0] = s + tmp_phi[0] = p + tmp_Fx[0] = v + return p + + def derphi(s): + ds = (abs(s) + s_norm + 1) * rdiff + return (phi(s+ds, store=False) - phi(s)) / ds + + if search_type == 'wolfe': + s, phi1, phi0 = scalar_search_wolfe1(phi, derphi, tmp_phi[0], + xtol=1e-2, amin=smin) + elif search_type == 'armijo': + s, phi1 = scalar_search_armijo(phi, tmp_phi[0], -tmp_phi[0], + amin=smin) + + if s is None: + # XXX: No suitable step length found. Take the full Newton step, + # and hope for the best. + s = 1.0 + + x = x + s*dx + if s == tmp_s[0]: + Fx = tmp_Fx[0] + else: + Fx = func(x) + Fx_norm = norm(Fx) + + return s, x, Fx, Fx_norm + + +class TerminationCondition: + """ + Termination condition for an iteration. It is terminated if + + - |F| < f_rtol*|F_0|, AND + - |F| < f_tol + + AND + + - |dx| < x_rtol*|x|, AND + - |dx| < x_tol + + """ + def __init__(self, f_tol=None, f_rtol=None, x_tol=None, x_rtol=None, + iter=None, norm=maxnorm): + + if f_tol is None: + f_tol = np.finfo(np.float64).eps ** (1./3) + if f_rtol is None: + f_rtol = np.inf + if x_tol is None: + x_tol = np.inf + if x_rtol is None: + x_rtol = np.inf + + self.x_tol = x_tol + self.x_rtol = x_rtol + self.f_tol = f_tol + self.f_rtol = f_rtol + + self.norm = norm + + self.iter = iter + + self.f0_norm = None + self.iteration = 0 + + def check(self, f, x, dx): + self.iteration += 1 + f_norm = self.norm(f) + x_norm = self.norm(x) + dx_norm = self.norm(dx) + + if self.f0_norm is None: + self.f0_norm = f_norm + + if f_norm == 0: + return 1 + + if self.iter is not None: + # backwards compatibility with SciPy 0.6.0 + return 2 * (self.iteration > self.iter) + + # NB: condition must succeed for rtol=inf even if norm == 0 + return int((f_norm <= self.f_tol + and f_norm/self.f_rtol <= self.f0_norm) + and (dx_norm <= self.x_tol + and dx_norm/self.x_rtol <= x_norm)) + + +#------------------------------------------------------------------------------ +# Generic Jacobian approximation +#------------------------------------------------------------------------------ + +class Jacobian: + """ + Common interface for Jacobians or Jacobian approximations. + + The optional methods come useful when implementing trust region + etc., algorithms that often require evaluating transposes of the + Jacobian. + + Methods + ------- + solve + Returns J^-1 * v + update + Updates Jacobian to point `x` (where the function has residual `Fx`) + + matvec : optional + Returns J * v + rmatvec : optional + Returns A^H * v + rsolve : optional + Returns A^-H * v + matmat : optional + Returns A * V, where V is a dense matrix with dimensions (N,K). + todense : optional + Form the dense Jacobian matrix. Necessary for dense trust region + algorithms, and useful for testing. + + Attributes + ---------- + shape + Matrix dimensions (M, N) + dtype + Data type of the matrix. + func : callable, optional + Function the Jacobian corresponds to + + """ + + def __init__(self, **kw): + names = ["solve", "update", "matvec", "rmatvec", "rsolve", + "matmat", "todense", "shape", "dtype"] + for name, value in kw.items(): + if name not in names: + raise ValueError(f"Unknown keyword argument {name}") + if value is not None: + setattr(self, name, kw[name]) + + + if hasattr(self, "todense"): + def __array__(self, dtype=None, copy=None): + if dtype is not None: + raise ValueError(f"`dtype` must be None, was {dtype}") + return self.todense() + + def aspreconditioner(self): + return InverseJacobian(self) + + def solve(self, v, tol=0): + raise NotImplementedError + + def update(self, x, F): + pass + + def setup(self, x, F, func): + self.func = func + self.shape = (F.size, x.size) + self.dtype = F.dtype + if self.__class__.setup is Jacobian.setup: + # Call on the first point unless overridden + self.update(x, F) + + +class InverseJacobian: + """ + A simple wrapper that inverts the Jacobian using the `solve` method. + + .. legacy:: class + + See the newer, more consistent interfaces in :mod:`scipy.optimize`. + + Parameters + ---------- + jacobian : Jacobian + The Jacobian to invert. + + Attributes + ---------- + shape + Matrix dimensions (M, N) + dtype + Data type of the matrix. + + """ + def __init__(self, jacobian): + self.jacobian = jacobian + self.matvec = jacobian.solve + self.update = jacobian.update + if hasattr(jacobian, 'setup'): + self.setup = jacobian.setup + if hasattr(jacobian, 'rsolve'): + self.rmatvec = jacobian.rsolve + + @property + def shape(self): + return self.jacobian.shape + + @property + def dtype(self): + return self.jacobian.dtype + + +def asjacobian(J): + """ + Convert given object to one suitable for use as a Jacobian. + """ + spsolve = scipy.sparse.linalg.spsolve + if isinstance(J, Jacobian): + return J + elif inspect.isclass(J) and issubclass(J, Jacobian): + return J() + elif isinstance(J, np.ndarray): + if J.ndim > 2: + raise ValueError('array must have rank <= 2') + J = np.atleast_2d(np.asarray(J)) + if J.shape[0] != J.shape[1]: + raise ValueError('array must be square') + + return Jacobian(matvec=lambda v: dot(J, v), + rmatvec=lambda v: dot(J.conj().T, v), + solve=lambda v, tol=0: solve(J, v), + rsolve=lambda v, tol=0: solve(J.conj().T, v), + dtype=J.dtype, shape=J.shape) + elif scipy.sparse.issparse(J): + if J.shape[0] != J.shape[1]: + raise ValueError('matrix must be square') + return Jacobian(matvec=lambda v: J @ v, + rmatvec=lambda v: J.conj().T @ v, + solve=lambda v, tol=0: spsolve(J, v), + rsolve=lambda v, tol=0: spsolve(J.conj().T, v), + dtype=J.dtype, shape=J.shape) + elif hasattr(J, 'shape') and hasattr(J, 'dtype') and hasattr(J, 'solve'): + return Jacobian(matvec=getattr(J, 'matvec'), + rmatvec=getattr(J, 'rmatvec'), + solve=J.solve, + rsolve=getattr(J, 'rsolve'), + update=getattr(J, 'update'), + setup=getattr(J, 'setup'), + dtype=J.dtype, + shape=J.shape) + elif callable(J): + # Assume it's a function J(x) that returns the Jacobian + class Jac(Jacobian): + def update(self, x, F): + self.x = x + + def solve(self, v, tol=0): + m = J(self.x) + if isinstance(m, np.ndarray): + return solve(m, v) + elif scipy.sparse.issparse(m): + return spsolve(m, v) + else: + raise ValueError("Unknown matrix type") + + def matvec(self, v): + m = J(self.x) + if isinstance(m, np.ndarray): + return dot(m, v) + elif scipy.sparse.issparse(m): + return m @ v + else: + raise ValueError("Unknown matrix type") + + def rsolve(self, v, tol=0): + m = J(self.x) + if isinstance(m, np.ndarray): + return solve(m.conj().T, v) + elif scipy.sparse.issparse(m): + return spsolve(m.conj().T, v) + else: + raise ValueError("Unknown matrix type") + + def rmatvec(self, v): + m = J(self.x) + if isinstance(m, np.ndarray): + return dot(m.conj().T, v) + elif scipy.sparse.issparse(m): + return m.conj().T @ v + else: + raise ValueError("Unknown matrix type") + return Jac() + elif isinstance(J, str): + return dict(broyden1=BroydenFirst, + broyden2=BroydenSecond, + anderson=Anderson, + diagbroyden=DiagBroyden, + linearmixing=LinearMixing, + excitingmixing=ExcitingMixing, + krylov=KrylovJacobian)[J]() + else: + raise TypeError('Cannot convert object to a Jacobian') + + +#------------------------------------------------------------------------------ +# Broyden +#------------------------------------------------------------------------------ + +class GenericBroyden(Jacobian): + def setup(self, x0, f0, func): + Jacobian.setup(self, x0, f0, func) + self.last_f = f0 + self.last_x = x0 + + if hasattr(self, 'alpha') and self.alpha is None: + # Autoscale the initial Jacobian parameter + # unless we have already guessed the solution. + normf0 = norm(f0) + if normf0: + self.alpha = 0.5*max(norm(x0), 1) / normf0 + else: + self.alpha = 1.0 + + def _update(self, x, f, dx, df, dx_norm, df_norm): + raise NotImplementedError + + def update(self, x, f): + df = f - self.last_f + dx = x - self.last_x + self._update(x, f, dx, df, norm(dx), norm(df)) + self.last_f = f + self.last_x = x + + +class LowRankMatrix: + r""" + A matrix represented as + + .. math:: \alpha I + \sum_{n=0}^{n=M} c_n d_n^\dagger + + However, if the rank of the matrix reaches the dimension of the vectors, + full matrix representation will be used thereon. + + """ + + def __init__(self, alpha, n, dtype): + self.alpha = alpha + self.cs = [] + self.ds = [] + self.n = n + self.dtype = dtype + self.collapsed = None + + @staticmethod + def _matvec(v, alpha, cs, ds): + axpy, scal, dotc = get_blas_funcs(['axpy', 'scal', 'dotc'], + cs[:1] + [v]) + w = alpha * v + for c, d in zip(cs, ds): + a = dotc(d, v) + w = axpy(c, w, w.size, a) + return w + + @staticmethod + def _solve(v, alpha, cs, ds): + """Evaluate w = M^-1 v""" + if len(cs) == 0: + return v/alpha + + # (B + C D^H)^-1 = B^-1 - B^-1 C (I + D^H B^-1 C)^-1 D^H B^-1 + + axpy, dotc = get_blas_funcs(['axpy', 'dotc'], cs[:1] + [v]) + + c0 = cs[0] + A = alpha * np.identity(len(cs), dtype=c0.dtype) + for i, d in enumerate(ds): + for j, c in enumerate(cs): + A[i,j] += dotc(d, c) + + q = np.zeros(len(cs), dtype=c0.dtype) + for j, d in enumerate(ds): + q[j] = dotc(d, v) + q /= alpha + q = solve(A, q) + + w = v/alpha + for c, qc in zip(cs, q): + w = axpy(c, w, w.size, -qc) + + return w + + def matvec(self, v): + """Evaluate w = M v""" + if self.collapsed is not None: + return np.dot(self.collapsed, v) + return LowRankMatrix._matvec(v, self.alpha, self.cs, self.ds) + + def rmatvec(self, v): + """Evaluate w = M^H v""" + if self.collapsed is not None: + return np.dot(self.collapsed.T.conj(), v) + return LowRankMatrix._matvec(v, np.conj(self.alpha), self.ds, self.cs) + + def solve(self, v, tol=0): + """Evaluate w = M^-1 v""" + if self.collapsed is not None: + return solve(self.collapsed, v) + return LowRankMatrix._solve(v, self.alpha, self.cs, self.ds) + + def rsolve(self, v, tol=0): + """Evaluate w = M^-H v""" + if self.collapsed is not None: + return solve(self.collapsed.T.conj(), v) + return LowRankMatrix._solve(v, np.conj(self.alpha), self.ds, self.cs) + + def append(self, c, d): + if self.collapsed is not None: + self.collapsed += c[:,None] * d[None,:].conj() + return + + self.cs.append(c) + self.ds.append(d) + + if len(self.cs) > c.size: + self.collapse() + + def __array__(self, dtype=None, copy=None): + if dtype is not None: + warnings.warn("LowRankMatrix is scipy-internal code, `dtype` " + f"should only be None but was {dtype} (not handled)", + stacklevel=3) + if copy is not None: + warnings.warn("LowRankMatrix is scipy-internal code, `copy` " + f"should only be None but was {copy} (not handled)", + stacklevel=3) + if self.collapsed is not None: + return self.collapsed + + Gm = self.alpha*np.identity(self.n, dtype=self.dtype) + for c, d in zip(self.cs, self.ds): + Gm += c[:,None]*d[None,:].conj() + return Gm + + def collapse(self): + """Collapse the low-rank matrix to a full-rank one.""" + self.collapsed = np.array(self, copy=copy_if_needed) + self.cs = None + self.ds = None + self.alpha = None + + def restart_reduce(self, rank): + """ + Reduce the rank of the matrix by dropping all vectors. + """ + if self.collapsed is not None: + return + assert rank > 0 + if len(self.cs) > rank: + del self.cs[:] + del self.ds[:] + + def simple_reduce(self, rank): + """ + Reduce the rank of the matrix by dropping oldest vectors. + """ + if self.collapsed is not None: + return + assert rank > 0 + while len(self.cs) > rank: + del self.cs[0] + del self.ds[0] + + def svd_reduce(self, max_rank, to_retain=None): + """ + Reduce the rank of the matrix by retaining some SVD components. + + This corresponds to the \"Broyden Rank Reduction Inverse\" + algorithm described in [1]_. + + Note that the SVD decomposition can be done by solving only a + problem whose size is the effective rank of this matrix, which + is viable even for large problems. + + Parameters + ---------- + max_rank : int + Maximum rank of this matrix after reduction. + to_retain : int, optional + Number of SVD components to retain when reduction is done + (ie. rank > max_rank). Default is ``max_rank - 2``. + + References + ---------- + .. [1] B.A. van der Rotten, PhD thesis, + \"A limited memory Broyden method to solve high-dimensional + systems of nonlinear equations\". Mathematisch Instituut, + Universiteit Leiden, The Netherlands (2003). + + https://web.archive.org/web/20161022015821/http://www.math.leidenuniv.nl/scripties/Rotten.pdf + + """ + if self.collapsed is not None: + return + + p = max_rank + if to_retain is not None: + q = to_retain + else: + q = p - 2 + + if self.cs: + p = min(p, len(self.cs[0])) + q = max(0, min(q, p-1)) + + m = len(self.cs) + if m < p: + # nothing to do + return + + C = np.array(self.cs).T + D = np.array(self.ds).T + + D, R = qr(D, mode='economic') + C = dot(C, R.T.conj()) + + U, S, WH = svd(C, full_matrices=False) + + C = dot(C, inv(WH)) + D = dot(D, WH.T.conj()) + + for k in range(q): + self.cs[k] = C[:,k].copy() + self.ds[k] = D[:,k].copy() + + del self.cs[q:] + del self.ds[q:] + + +_doc_parts['broyden_params'] = """ + alpha : float, optional + Initial guess for the Jacobian is ``(-1/alpha)``. + reduction_method : str or tuple, optional + Method used in ensuring that the rank of the Broyden matrix + stays low. Can either be a string giving the name of the method, + or a tuple of the form ``(method, param1, param2, ...)`` + that gives the name of the method and values for additional parameters. + + Methods available: + + - ``restart``: drop all matrix columns. Has no extra parameters. + - ``simple``: drop oldest matrix column. Has no extra parameters. + - ``svd``: keep only the most significant SVD components. + Takes an extra parameter, ``to_retain``, which determines the + number of SVD components to retain when rank reduction is done. + Default is ``max_rank - 2``. + + max_rank : int, optional + Maximum rank for the Broyden matrix. + Default is infinity (i.e., no rank reduction). + """.strip() + + +class BroydenFirst(GenericBroyden): + """ + Find a root of a function, using Broyden's first Jacobian approximation. + + This method is also known as "Broyden's good method". + + Parameters + ---------- + %(params_basic)s + %(broyden_params)s + %(params_extra)s + + See Also + -------- + root : Interface to root finding algorithms for multivariate + functions. See ``method='broyden1'`` in particular. + + Notes + ----- + This algorithm implements the inverse Jacobian Quasi-Newton update + + .. math:: H_+ = H + (dx - H df) dx^\\dagger H / ( dx^\\dagger H df) + + which corresponds to Broyden's first Jacobian update + + .. math:: J_+ = J + (df - J dx) dx^\\dagger / dx^\\dagger dx + + + References + ---------- + .. [1] B.A. van der Rotten, PhD thesis, + "A limited memory Broyden method to solve high-dimensional + systems of nonlinear equations". Mathematisch Instituut, + Universiteit Leiden, The Netherlands (2003). + https://math.leidenuniv.nl/scripties/Rotten.pdf + + Examples + -------- + The following functions define a system of nonlinear equations + + >>> def fun(x): + ... return [x[0] + 0.5 * (x[0] - x[1])**3 - 1.0, + ... 0.5 * (x[1] - x[0])**3 + x[1]] + + A solution can be obtained as follows. + + >>> from scipy import optimize + >>> sol = optimize.broyden1(fun, [0, 0]) + >>> sol + array([0.84116396, 0.15883641]) + + """ + + def __init__(self, alpha=None, reduction_method='restart', max_rank=None): + GenericBroyden.__init__(self) + self.alpha = alpha + self.Gm = None + + if max_rank is None: + max_rank = np.inf + self.max_rank = max_rank + + if isinstance(reduction_method, str): + reduce_params = () + else: + reduce_params = reduction_method[1:] + reduction_method = reduction_method[0] + reduce_params = (max_rank - 1,) + reduce_params + + if reduction_method == 'svd': + self._reduce = lambda: self.Gm.svd_reduce(*reduce_params) + elif reduction_method == 'simple': + self._reduce = lambda: self.Gm.simple_reduce(*reduce_params) + elif reduction_method == 'restart': + self._reduce = lambda: self.Gm.restart_reduce(*reduce_params) + else: + raise ValueError(f"Unknown rank reduction method '{reduction_method}'") + + def setup(self, x, F, func): + GenericBroyden.setup(self, x, F, func) + self.Gm = LowRankMatrix(-self.alpha, self.shape[0], self.dtype) + + def todense(self): + return inv(self.Gm) + + def solve(self, f, tol=0): + r = self.Gm.matvec(f) + if not np.isfinite(r).all(): + # singular; reset the Jacobian approximation + self.setup(self.last_x, self.last_f, self.func) + return self.Gm.matvec(f) + return r + + def matvec(self, f): + return self.Gm.solve(f) + + def rsolve(self, f, tol=0): + return self.Gm.rmatvec(f) + + def rmatvec(self, f): + return self.Gm.rsolve(f) + + def _update(self, x, f, dx, df, dx_norm, df_norm): + self._reduce() # reduce first to preserve secant condition + + v = self.Gm.rmatvec(dx) + c = dx - self.Gm.matvec(df) + d = v / vdot(df, v) + + self.Gm.append(c, d) + + +class BroydenSecond(BroydenFirst): + """ + Find a root of a function, using Broyden\'s second Jacobian approximation. + + This method is also known as \"Broyden's bad method\". + + Parameters + ---------- + %(params_basic)s + %(broyden_params)s + %(params_extra)s + + See Also + -------- + root : Interface to root finding algorithms for multivariate + functions. See ``method='broyden2'`` in particular. + + Notes + ----- + This algorithm implements the inverse Jacobian Quasi-Newton update + + .. math:: H_+ = H + (dx - H df) df^\\dagger / ( df^\\dagger df) + + corresponding to Broyden's second method. + + References + ---------- + .. [1] B.A. van der Rotten, PhD thesis, + \"A limited memory Broyden method to solve high-dimensional + systems of nonlinear equations\". Mathematisch Instituut, + Universiteit Leiden, The Netherlands (2003). + + https://web.archive.org/web/20161022015821/http://www.math.leidenuniv.nl/scripties/Rotten.pdf + + Examples + -------- + The following functions define a system of nonlinear equations + + >>> def fun(x): + ... return [x[0] + 0.5 * (x[0] - x[1])**3 - 1.0, + ... 0.5 * (x[1] - x[0])**3 + x[1]] + + A solution can be obtained as follows. + + >>> from scipy import optimize + >>> sol = optimize.broyden2(fun, [0, 0]) + >>> sol + array([0.84116365, 0.15883529]) + + """ + + def _update(self, x, f, dx, df, dx_norm, df_norm): + self._reduce() # reduce first to preserve secant condition + + v = df + c = dx - self.Gm.matvec(df) + d = v / df_norm**2 + self.Gm.append(c, d) + + +#------------------------------------------------------------------------------ +# Broyden-like (restricted memory) +#------------------------------------------------------------------------------ + +class Anderson(GenericBroyden): + """ + Find a root of a function, using (extended) Anderson mixing. + + The Jacobian is formed by for a 'best' solution in the space + spanned by last `M` vectors. As a result, only a MxM matrix + inversions and MxN multiplications are required. [Ey]_ + + Parameters + ---------- + %(params_basic)s + alpha : float, optional + Initial guess for the Jacobian is (-1/alpha). + M : float, optional + Number of previous vectors to retain. Defaults to 5. + w0 : float, optional + Regularization parameter for numerical stability. + Compared to unity, good values of the order of 0.01. + %(params_extra)s + + See Also + -------- + root : Interface to root finding algorithms for multivariate + functions. See ``method='anderson'`` in particular. + + References + ---------- + .. [Ey] V. Eyert, J. Comp. Phys., 124, 271 (1996). + + Examples + -------- + The following functions define a system of nonlinear equations + + >>> def fun(x): + ... return [x[0] + 0.5 * (x[0] - x[1])**3 - 1.0, + ... 0.5 * (x[1] - x[0])**3 + x[1]] + + A solution can be obtained as follows. + + >>> from scipy import optimize + >>> sol = optimize.anderson(fun, [0, 0]) + >>> sol + array([0.84116588, 0.15883789]) + + """ + + # Note: + # + # Anderson method maintains a rank M approximation of the inverse Jacobian, + # + # J^-1 v ~ -v*alpha + (dX + alpha dF) A^-1 dF^H v + # A = W + dF^H dF + # W = w0^2 diag(dF^H dF) + # + # so that for w0 = 0 the secant condition applies for last M iterates, i.e., + # + # J^-1 df_j = dx_j + # + # for all j = 0 ... M-1. + # + # Moreover, (from Sherman-Morrison-Woodbury formula) + # + # J v ~ [ b I - b^2 C (I + b dF^H A^-1 C)^-1 dF^H ] v + # C = (dX + alpha dF) A^-1 + # b = -1/alpha + # + # and after simplification + # + # J v ~ -v/alpha + (dX/alpha + dF) (dF^H dX - alpha W)^-1 dF^H v + # + + def __init__(self, alpha=None, w0=0.01, M=5): + GenericBroyden.__init__(self) + self.alpha = alpha + self.M = M + self.dx = [] + self.df = [] + self.gamma = None + self.w0 = w0 + + def solve(self, f, tol=0): + dx = -self.alpha*f + + n = len(self.dx) + if n == 0: + return dx + + df_f = np.empty(n, dtype=f.dtype) + for k in range(n): + df_f[k] = vdot(self.df[k], f) + + try: + gamma = solve(self.a, df_f) + except LinAlgError: + # singular; reset the Jacobian approximation + del self.dx[:] + del self.df[:] + return dx + + for m in range(n): + dx += gamma[m]*(self.dx[m] + self.alpha*self.df[m]) + return dx + + def matvec(self, f): + dx = -f/self.alpha + + n = len(self.dx) + if n == 0: + return dx + + df_f = np.empty(n, dtype=f.dtype) + for k in range(n): + df_f[k] = vdot(self.df[k], f) + + b = np.empty((n, n), dtype=f.dtype) + for i in range(n): + for j in range(n): + b[i,j] = vdot(self.df[i], self.dx[j]) + if i == j and self.w0 != 0: + b[i,j] -= vdot(self.df[i], self.df[i])*self.w0**2*self.alpha + gamma = solve(b, df_f) + + for m in range(n): + dx += gamma[m]*(self.df[m] + self.dx[m]/self.alpha) + return dx + + def _update(self, x, f, dx, df, dx_norm, df_norm): + if self.M == 0: + return + + self.dx.append(dx) + self.df.append(df) + + while len(self.dx) > self.M: + self.dx.pop(0) + self.df.pop(0) + + n = len(self.dx) + a = np.zeros((n, n), dtype=f.dtype) + + for i in range(n): + for j in range(i, n): + if i == j: + wd = self.w0**2 + else: + wd = 0 + a[i,j] = (1+wd)*vdot(self.df[i], self.df[j]) + + a += np.triu(a, 1).T.conj() + self.a = a + +#------------------------------------------------------------------------------ +# Simple iterations +#------------------------------------------------------------------------------ + + +class DiagBroyden(GenericBroyden): + """ + Find a root of a function, using diagonal Broyden Jacobian approximation. + + The Jacobian approximation is derived from previous iterations, by + retaining only the diagonal of Broyden matrices. + + .. warning:: + + This algorithm may be useful for specific problems, but whether + it will work may depend strongly on the problem. + + Parameters + ---------- + %(params_basic)s + alpha : float, optional + Initial guess for the Jacobian is (-1/alpha). + %(params_extra)s + + See Also + -------- + root : Interface to root finding algorithms for multivariate + functions. See ``method='diagbroyden'`` in particular. + + Examples + -------- + The following functions define a system of nonlinear equations + + >>> def fun(x): + ... return [x[0] + 0.5 * (x[0] - x[1])**3 - 1.0, + ... 0.5 * (x[1] - x[0])**3 + x[1]] + + A solution can be obtained as follows. + + >>> from scipy import optimize + >>> sol = optimize.diagbroyden(fun, [0, 0]) + >>> sol + array([0.84116403, 0.15883384]) + + """ + + def __init__(self, alpha=None): + GenericBroyden.__init__(self) + self.alpha = alpha + + def setup(self, x, F, func): + GenericBroyden.setup(self, x, F, func) + self.d = np.full((self.shape[0],), 1 / self.alpha, dtype=self.dtype) + + def solve(self, f, tol=0): + return -f / self.d + + def matvec(self, f): + return -f * self.d + + def rsolve(self, f, tol=0): + return -f / self.d.conj() + + def rmatvec(self, f): + return -f * self.d.conj() + + def todense(self): + return np.diag(-self.d) + + def _update(self, x, f, dx, df, dx_norm, df_norm): + self.d -= (df + self.d*dx)*dx/dx_norm**2 + + +class LinearMixing(GenericBroyden): + """ + Find a root of a function, using a scalar Jacobian approximation. + + .. warning:: + + This algorithm may be useful for specific problems, but whether + it will work may depend strongly on the problem. + + Parameters + ---------- + %(params_basic)s + alpha : float, optional + The Jacobian approximation is (-1/alpha). + %(params_extra)s + + See Also + -------- + root : Interface to root finding algorithms for multivariate + functions. See ``method='linearmixing'`` in particular. + + """ + + def __init__(self, alpha=None): + GenericBroyden.__init__(self) + self.alpha = alpha + + def solve(self, f, tol=0): + return -f*self.alpha + + def matvec(self, f): + return -f/self.alpha + + def rsolve(self, f, tol=0): + return -f*np.conj(self.alpha) + + def rmatvec(self, f): + return -f/np.conj(self.alpha) + + def todense(self): + return np.diag(np.full(self.shape[0], -1/self.alpha)) + + def _update(self, x, f, dx, df, dx_norm, df_norm): + pass + + +class ExcitingMixing(GenericBroyden): + """ + Find a root of a function, using a tuned diagonal Jacobian approximation. + + The Jacobian matrix is diagonal and is tuned on each iteration. + + .. warning:: + + This algorithm may be useful for specific problems, but whether + it will work may depend strongly on the problem. + + See Also + -------- + root : Interface to root finding algorithms for multivariate + functions. See ``method='excitingmixing'`` in particular. + + Parameters + ---------- + %(params_basic)s + alpha : float, optional + Initial Jacobian approximation is (-1/alpha). + alphamax : float, optional + The entries of the diagonal Jacobian are kept in the range + ``[alpha, alphamax]``. + %(params_extra)s + """ + + def __init__(self, alpha=None, alphamax=1.0): + GenericBroyden.__init__(self) + self.alpha = alpha + self.alphamax = alphamax + self.beta = None + + def setup(self, x, F, func): + GenericBroyden.setup(self, x, F, func) + self.beta = np.full((self.shape[0],), self.alpha, dtype=self.dtype) + + def solve(self, f, tol=0): + return -f*self.beta + + def matvec(self, f): + return -f/self.beta + + def rsolve(self, f, tol=0): + return -f*self.beta.conj() + + def rmatvec(self, f): + return -f/self.beta.conj() + + def todense(self): + return np.diag(-1/self.beta) + + def _update(self, x, f, dx, df, dx_norm, df_norm): + incr = f*self.last_f > 0 + self.beta[incr] += self.alpha + self.beta[~incr] = self.alpha + np.clip(self.beta, 0, self.alphamax, out=self.beta) + + +#------------------------------------------------------------------------------ +# Iterative/Krylov approximated Jacobians +#------------------------------------------------------------------------------ + +class KrylovJacobian(Jacobian): + """ + Find a root of a function, using Krylov approximation for inverse Jacobian. + + This method is suitable for solving large-scale problems. + + Parameters + ---------- + %(params_basic)s + rdiff : float, optional + Relative step size to use in numerical differentiation. + method : str or callable, optional + Krylov method to use to approximate the Jacobian. Can be a string, + or a function implementing the same interface as the iterative + solvers in `scipy.sparse.linalg`. If a string, needs to be one of: + ``'lgmres'``, ``'gmres'``, ``'bicgstab'``, ``'cgs'``, ``'minres'``, + ``'tfqmr'``. + + The default is `scipy.sparse.linalg.lgmres`. + inner_maxiter : int, optional + Parameter to pass to the "inner" Krylov solver: maximum number of + iterations. Iteration will stop after maxiter steps even if the + specified tolerance has not been achieved. + inner_M : LinearOperator or InverseJacobian + Preconditioner for the inner Krylov iteration. + Note that you can use also inverse Jacobians as (adaptive) + preconditioners. For example, + + >>> from scipy.optimize import BroydenFirst, KrylovJacobian + >>> from scipy.optimize import InverseJacobian + >>> jac = BroydenFirst() + >>> kjac = KrylovJacobian(inner_M=InverseJacobian(jac)) + + If the preconditioner has a method named 'update', it will be called + as ``update(x, f)`` after each nonlinear step, with ``x`` giving + the current point, and ``f`` the current function value. + outer_k : int, optional + Size of the subspace kept across LGMRES nonlinear iterations. + See `scipy.sparse.linalg.lgmres` for details. + inner_kwargs : kwargs + Keyword parameters for the "inner" Krylov solver + (defined with `method`). Parameter names must start with + the `inner_` prefix which will be stripped before passing on + the inner method. See, e.g., `scipy.sparse.linalg.gmres` for details. + %(params_extra)s + + See Also + -------- + root : Interface to root finding algorithms for multivariate + functions. See ``method='krylov'`` in particular. + scipy.sparse.linalg.gmres + scipy.sparse.linalg.lgmres + + Notes + ----- + This function implements a Newton-Krylov solver. The basic idea is + to compute the inverse of the Jacobian with an iterative Krylov + method. These methods require only evaluating the Jacobian-vector + products, which are conveniently approximated by a finite difference: + + .. math:: J v \\approx (f(x + \\omega*v/|v|) - f(x)) / \\omega + + Due to the use of iterative matrix inverses, these methods can + deal with large nonlinear problems. + + SciPy's `scipy.sparse.linalg` module offers a selection of Krylov + solvers to choose from. The default here is `lgmres`, which is a + variant of restarted GMRES iteration that reuses some of the + information obtained in the previous Newton steps to invert + Jacobians in subsequent steps. + + For a review on Newton-Krylov methods, see for example [1]_, + and for the LGMRES sparse inverse method, see [2]_. + + References + ---------- + .. [1] C. T. Kelley, Solving Nonlinear Equations with Newton's Method, + SIAM, pp.57-83, 2003. + :doi:`10.1137/1.9780898718898.ch3` + .. [2] D.A. Knoll and D.E. Keyes, J. Comp. Phys. 193, 357 (2004). + :doi:`10.1016/j.jcp.2003.08.010` + .. [3] A.H. Baker and E.R. Jessup and T. Manteuffel, + SIAM J. Matrix Anal. Appl. 26, 962 (2005). + :doi:`10.1137/S0895479803422014` + + Examples + -------- + The following functions define a system of nonlinear equations + + >>> def fun(x): + ... return [x[0] + 0.5 * x[1] - 1.0, + ... 0.5 * (x[1] - x[0]) ** 2] + + A solution can be obtained as follows. + + >>> from scipy import optimize + >>> sol = optimize.newton_krylov(fun, [0, 0]) + >>> sol + array([0.66731771, 0.66536458]) + + """ + + def __init__(self, rdiff=None, method='lgmres', inner_maxiter=20, + inner_M=None, outer_k=10, **kw): + self.preconditioner = inner_M + self.rdiff = rdiff + # Note that this retrieves one of the named functions, or otherwise + # uses `method` as is (i.e., for a user-provided callable). + self.method = dict( + bicgstab=scipy.sparse.linalg.bicgstab, + gmres=scipy.sparse.linalg.gmres, + lgmres=scipy.sparse.linalg.lgmres, + cgs=scipy.sparse.linalg.cgs, + minres=scipy.sparse.linalg.minres, + tfqmr=scipy.sparse.linalg.tfqmr, + ).get(method, method) + + self.method_kw = dict(maxiter=inner_maxiter, M=self.preconditioner) + + if self.method is scipy.sparse.linalg.gmres: + # Replace GMRES's outer iteration with Newton steps + self.method_kw['restart'] = inner_maxiter + self.method_kw['maxiter'] = 1 + self.method_kw.setdefault('atol', 0) + elif self.method in (scipy.sparse.linalg.gcrotmk, + scipy.sparse.linalg.bicgstab, + scipy.sparse.linalg.cgs): + self.method_kw.setdefault('atol', 0) + elif self.method is scipy.sparse.linalg.lgmres: + self.method_kw['outer_k'] = outer_k + # Replace LGMRES's outer iteration with Newton steps + self.method_kw['maxiter'] = 1 + # Carry LGMRES's `outer_v` vectors across nonlinear iterations + self.method_kw.setdefault('outer_v', []) + self.method_kw.setdefault('prepend_outer_v', True) + # But don't carry the corresponding Jacobian*v products, in case + # the Jacobian changes a lot in the nonlinear step + # + # XXX: some trust-region inspired ideas might be more efficient... + # See e.g., Brown & Saad. But needs to be implemented separately + # since it's not an inexact Newton method. + self.method_kw.setdefault('store_outer_Av', False) + self.method_kw.setdefault('atol', 0) + + for key, value in kw.items(): + if not key.startswith('inner_'): + raise ValueError(f"Unknown parameter {key}") + self.method_kw[key[6:]] = value + + def _update_diff_step(self): + mx = abs(self.x0).max() + mf = abs(self.f0).max() + self.omega = self.rdiff * max(1, mx) / max(1, mf) + + def matvec(self, v): + nv = norm(v) + if nv == 0: + return 0*v + sc = self.omega / nv + r = (self.func(self.x0 + sc*v) - self.f0) / sc + if not np.all(np.isfinite(r)) and np.all(np.isfinite(v)): + raise ValueError('Function returned non-finite results') + return r + + def solve(self, rhs, tol=0): + if 'rtol' in self.method_kw: + sol, info = self.method(self.op, rhs, **self.method_kw) + else: + sol, info = self.method(self.op, rhs, rtol=tol, **self.method_kw) + return sol + + def update(self, x, f): + self.x0 = x + self.f0 = f + self._update_diff_step() + + # Update also the preconditioner, if possible + if self.preconditioner is not None: + if hasattr(self.preconditioner, 'update'): + self.preconditioner.update(x, f) + + def setup(self, x, f, func): + Jacobian.setup(self, x, f, func) + self.x0 = x + self.f0 = f + self.op = scipy.sparse.linalg.aslinearoperator(self) + + if self.rdiff is None: + self.rdiff = np.finfo(x.dtype).eps ** (1./2) + + self._update_diff_step() + + # Setup also the preconditioner, if possible + if self.preconditioner is not None: + if hasattr(self.preconditioner, 'setup'): + self.preconditioner.setup(x, f, func) + + +#------------------------------------------------------------------------------ +# Wrapper functions +#------------------------------------------------------------------------------ + +def _nonlin_wrapper(name, jac): + """ + Construct a solver wrapper with given name and Jacobian approx. + + It inspects the keyword arguments of ``jac.__init__``, and allows to + use the same arguments in the wrapper function, in addition to the + keyword arguments of `nonlin_solve` + + """ + signature = _getfullargspec(jac.__init__) + args, varargs, varkw, defaults, kwonlyargs, kwdefaults, _ = signature + kwargs = list(zip(args[-len(defaults):], defaults)) + kw_str = ", ".join([f"{k}={v!r}" for k, v in kwargs]) + if kw_str: + kw_str = ", " + kw_str + kwkw_str = ", ".join([f"{k}={k}" for k, v in kwargs]) + if kwkw_str: + kwkw_str = kwkw_str + ", " + if kwonlyargs: + raise ValueError(f'Unexpected signature {signature}') + + # Construct the wrapper function so that its keyword arguments + # are visible in pydoc.help etc. + wrapper = """ +def %(name)s(F, xin, iter=None %(kw)s, verbose=False, maxiter=None, + f_tol=None, f_rtol=None, x_tol=None, x_rtol=None, + tol_norm=None, line_search='armijo', callback=None, **kw): + jac = %(jac)s(%(kwkw)s **kw) + return nonlin_solve(F, xin, jac, iter, verbose, maxiter, + f_tol, f_rtol, x_tol, x_rtol, tol_norm, line_search, + callback) +""" + + wrapper = wrapper % dict(name=name, kw=kw_str, jac=jac.__name__, + kwkw=kwkw_str) + ns = {} + ns.update(globals()) + exec(wrapper, ns) + func = ns[name] + func.__doc__ = jac.__doc__ + _set_doc(func) + return func + + +broyden1 = _nonlin_wrapper('broyden1', BroydenFirst) +broyden2 = _nonlin_wrapper('broyden2', BroydenSecond) +anderson = _nonlin_wrapper('anderson', Anderson) +linearmixing = _nonlin_wrapper('linearmixing', LinearMixing) +diagbroyden = _nonlin_wrapper('diagbroyden', DiagBroyden) +excitingmixing = _nonlin_wrapper('excitingmixing', ExcitingMixing) +newton_krylov = _nonlin_wrapper('newton_krylov', KrylovJacobian) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_numdiff.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_numdiff.py new file mode 100644 index 0000000000000000000000000000000000000000..6f847a8ebdaec7df7428ca1267a024fb9212d824 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_numdiff.py @@ -0,0 +1,785 @@ +"""Routines for numerical differentiation.""" +import functools +import numpy as np +from numpy.linalg import norm + +from scipy.sparse.linalg import LinearOperator +from ..sparse import issparse, csc_matrix, csr_matrix, coo_matrix, find +from ._group_columns import group_dense, group_sparse +from scipy._lib._array_api import array_namespace +from scipy._lib import array_api_extra as xpx + + +def _adjust_scheme_to_bounds(x0, h, num_steps, scheme, lb, ub): + """Adjust final difference scheme to the presence of bounds. + + Parameters + ---------- + x0 : ndarray, shape (n,) + Point at which we wish to estimate derivative. + h : ndarray, shape (n,) + Desired absolute finite difference steps. + num_steps : int + Number of `h` steps in one direction required to implement finite + difference scheme. For example, 2 means that we need to evaluate + f(x0 + 2 * h) or f(x0 - 2 * h) + scheme : {'1-sided', '2-sided'} + Whether steps in one or both directions are required. In other + words '1-sided' applies to forward and backward schemes, '2-sided' + applies to center schemes. + lb : ndarray, shape (n,) + Lower bounds on independent variables. + ub : ndarray, shape (n,) + Upper bounds on independent variables. + + Returns + ------- + h_adjusted : ndarray, shape (n,) + Adjusted absolute step sizes. Step size decreases only if a sign flip + or switching to one-sided scheme doesn't allow to take a full step. + use_one_sided : ndarray of bool, shape (n,) + Whether to switch to one-sided scheme. Informative only for + ``scheme='2-sided'``. + """ + if scheme == '1-sided': + use_one_sided = np.ones_like(h, dtype=bool) + elif scheme == '2-sided': + h = np.abs(h) + use_one_sided = np.zeros_like(h, dtype=bool) + else: + raise ValueError("`scheme` must be '1-sided' or '2-sided'.") + + if np.all((lb == -np.inf) & (ub == np.inf)): + return h, use_one_sided + + h_total = h * num_steps + h_adjusted = h.copy() + + lower_dist = x0 - lb + upper_dist = ub - x0 + + if scheme == '1-sided': + x = x0 + h_total + violated = (x < lb) | (x > ub) + fitting = np.abs(h_total) <= np.maximum(lower_dist, upper_dist) + h_adjusted[violated & fitting] *= -1 + + forward = (upper_dist >= lower_dist) & ~fitting + h_adjusted[forward] = upper_dist[forward] / num_steps + backward = (upper_dist < lower_dist) & ~fitting + h_adjusted[backward] = -lower_dist[backward] / num_steps + elif scheme == '2-sided': + central = (lower_dist >= h_total) & (upper_dist >= h_total) + + forward = (upper_dist >= lower_dist) & ~central + h_adjusted[forward] = np.minimum( + h[forward], 0.5 * upper_dist[forward] / num_steps) + use_one_sided[forward] = True + + backward = (upper_dist < lower_dist) & ~central + h_adjusted[backward] = -np.minimum( + h[backward], 0.5 * lower_dist[backward] / num_steps) + use_one_sided[backward] = True + + min_dist = np.minimum(upper_dist, lower_dist) / num_steps + adjusted_central = (~central & (np.abs(h_adjusted) <= min_dist)) + h_adjusted[adjusted_central] = min_dist[adjusted_central] + use_one_sided[adjusted_central] = False + + return h_adjusted, use_one_sided + + +@functools.lru_cache +def _eps_for_method(x0_dtype, f0_dtype, method): + """ + Calculates relative EPS step to use for a given data type + and numdiff step method. + + Progressively smaller steps are used for larger floating point types. + + Parameters + ---------- + f0_dtype: np.dtype + dtype of function evaluation + + x0_dtype: np.dtype + dtype of parameter vector + + method: {'2-point', '3-point', 'cs'} + + Returns + ------- + EPS: float + relative step size. May be np.float16, np.float32, np.float64 + + Notes + ----- + The default relative step will be np.float64. However, if x0 or f0 are + smaller floating point types (np.float16, np.float32), then the smallest + floating point type is chosen. + """ + # the default EPS value + EPS = np.finfo(np.float64).eps + + x0_is_fp = False + if np.issubdtype(x0_dtype, np.inexact): + # if you're a floating point type then over-ride the default EPS + EPS = np.finfo(x0_dtype).eps + x0_itemsize = np.dtype(x0_dtype).itemsize + x0_is_fp = True + + if np.issubdtype(f0_dtype, np.inexact): + f0_itemsize = np.dtype(f0_dtype).itemsize + # choose the smallest itemsize between x0 and f0 + if x0_is_fp and f0_itemsize < x0_itemsize: + EPS = np.finfo(f0_dtype).eps + + if method in ["2-point", "cs"]: + return EPS**0.5 + elif method in ["3-point"]: + return EPS**(1/3) + else: + raise RuntimeError("Unknown step method, should be one of " + "{'2-point', '3-point', 'cs'}") + + +def _compute_absolute_step(rel_step, x0, f0, method): + """ + Computes an absolute step from a relative step for finite difference + calculation. + + Parameters + ---------- + rel_step: None or array-like + Relative step for the finite difference calculation + x0 : np.ndarray + Parameter vector + f0 : np.ndarray or scalar + method : {'2-point', '3-point', 'cs'} + + Returns + ------- + h : float + The absolute step size + + Notes + ----- + `h` will always be np.float64. However, if `x0` or `f0` are + smaller floating point dtypes (e.g. np.float32), then the absolute + step size will be calculated from the smallest floating point size. + """ + # this is used instead of np.sign(x0) because we need + # sign_x0 to be 1 when x0 == 0. + sign_x0 = (x0 >= 0).astype(float) * 2 - 1 + + rstep = _eps_for_method(x0.dtype, f0.dtype, method) + + if rel_step is None: + abs_step = rstep * sign_x0 * np.maximum(1.0, np.abs(x0)) + else: + # User has requested specific relative steps. + # Don't multiply by max(1, abs(x0) because if x0 < 1 then their + # requested step is not used. + abs_step = rel_step * sign_x0 * np.abs(x0) + + # however we don't want an abs_step of 0, which can happen if + # rel_step is 0, or x0 is 0. Instead, substitute a realistic step + dx = ((x0 + abs_step) - x0) + abs_step = np.where(dx == 0, + rstep * sign_x0 * np.maximum(1.0, np.abs(x0)), + abs_step) + + return abs_step + + +def _prepare_bounds(bounds, x0): + """ + Prepares new-style bounds from a two-tuple specifying the lower and upper + limits for values in x0. If a value is not bound then the lower/upper bound + will be expected to be -np.inf/np.inf. + + Examples + -------- + >>> _prepare_bounds([(0, 1, 2), (1, 2, np.inf)], [0.5, 1.5, 2.5]) + (array([0., 1., 2.]), array([ 1., 2., inf])) + """ + lb, ub = (np.asarray(b, dtype=float) for b in bounds) + if lb.ndim == 0: + lb = np.resize(lb, x0.shape) + + if ub.ndim == 0: + ub = np.resize(ub, x0.shape) + + return lb, ub + + +def group_columns(A, order=0): + """Group columns of a 2-D matrix for sparse finite differencing [1]_. + + Two columns are in the same group if in each row at least one of them + has zero. A greedy sequential algorithm is used to construct groups. + + Parameters + ---------- + A : array_like or sparse matrix, shape (m, n) + Matrix of which to group columns. + order : int, iterable of int with shape (n,) or None + Permutation array which defines the order of columns enumeration. + If int or None, a random permutation is used with `order` used as + a random seed. Default is 0, that is use a random permutation but + guarantee repeatability. + + Returns + ------- + groups : ndarray of int, shape (n,) + Contains values from 0 to n_groups-1, where n_groups is the number + of found groups. Each value ``groups[i]`` is an index of a group to + which ith column assigned. The procedure was helpful only if + n_groups is significantly less than n. + + References + ---------- + .. [1] A. Curtis, M. J. D. Powell, and J. Reid, "On the estimation of + sparse Jacobian matrices", Journal of the Institute of Mathematics + and its Applications, 13 (1974), pp. 117-120. + """ + if issparse(A): + A = csc_matrix(A) + else: + A = np.atleast_2d(A) + A = (A != 0).astype(np.int32) + + if A.ndim != 2: + raise ValueError("`A` must be 2-dimensional.") + + m, n = A.shape + + if order is None or np.isscalar(order): + rng = np.random.RandomState(order) + order = rng.permutation(n) + else: + order = np.asarray(order) + if order.shape != (n,): + raise ValueError("`order` has incorrect shape.") + + A = A[:, order] + + if issparse(A): + groups = group_sparse(m, n, A.indices, A.indptr) + else: + groups = group_dense(m, n, A) + + groups[order] = groups.copy() + + return groups + + +def approx_derivative(fun, x0, method='3-point', rel_step=None, abs_step=None, + f0=None, bounds=(-np.inf, np.inf), sparsity=None, + as_linear_operator=False, args=(), kwargs=None): + """Compute finite difference approximation of the derivatives of a + vector-valued function. + + If a function maps from R^n to R^m, its derivatives form m-by-n matrix + called the Jacobian, where an element (i, j) is a partial derivative of + f[i] with respect to x[j]. + + Parameters + ---------- + fun : callable + Function of which to estimate the derivatives. The argument x + passed to this function is ndarray of shape (n,) (never a scalar + even if n=1). It must return 1-D array_like of shape (m,) or a scalar. + x0 : array_like of shape (n,) or float + Point at which to estimate the derivatives. Float will be converted + to a 1-D array. + method : {'3-point', '2-point', 'cs'}, optional + Finite difference method to use: + - '2-point' - use the first order accuracy forward or backward + difference. + - '3-point' - use central difference in interior points and the + second order accuracy forward or backward difference + near the boundary. + - 'cs' - use a complex-step finite difference scheme. This assumes + that the user function is real-valued and can be + analytically continued to the complex plane. Otherwise, + produces bogus results. + rel_step : None or array_like, optional + Relative step size to use. If None (default) the absolute step size is + computed as ``h = rel_step * sign(x0) * max(1, abs(x0))``, with + `rel_step` being selected automatically, see Notes. Otherwise + ``h = rel_step * sign(x0) * abs(x0)``. For ``method='3-point'`` the + sign of `h` is ignored. The calculated step size is possibly adjusted + to fit into the bounds. + abs_step : array_like, optional + Absolute step size to use, possibly adjusted to fit into the bounds. + For ``method='3-point'`` the sign of `abs_step` is ignored. By default + relative steps are used, only if ``abs_step is not None`` are absolute + steps used. + f0 : None or array_like, optional + If not None it is assumed to be equal to ``fun(x0)``, in this case + the ``fun(x0)`` is not called. Default is None. + bounds : tuple of array_like, optional + Lower and upper bounds on independent variables. Defaults to no bounds. + Each bound must match the size of `x0` or be a scalar, in the latter + case the bound will be the same for all variables. Use it to limit the + range of function evaluation. Bounds checking is not implemented + when `as_linear_operator` is True. + sparsity : {None, array_like, sparse matrix, 2-tuple}, optional + Defines a sparsity structure of the Jacobian matrix. If the Jacobian + matrix is known to have only few non-zero elements in each row, then + it's possible to estimate its several columns by a single function + evaluation [3]_. To perform such economic computations two ingredients + are required: + + * structure : array_like or sparse matrix of shape (m, n). A zero + element means that a corresponding element of the Jacobian + identically equals to zero. + * groups : array_like of shape (n,). A column grouping for a given + sparsity structure, use `group_columns` to obtain it. + + A single array or a sparse matrix is interpreted as a sparsity + structure, and groups are computed inside the function. A tuple is + interpreted as (structure, groups). If None (default), a standard + dense differencing will be used. + + Note, that sparse differencing makes sense only for large Jacobian + matrices where each row contains few non-zero elements. + as_linear_operator : bool, optional + When True the function returns an `scipy.sparse.linalg.LinearOperator`. + Otherwise it returns a dense array or a sparse matrix depending on + `sparsity`. The linear operator provides an efficient way of computing + ``J.dot(p)`` for any vector ``p`` of shape (n,), but does not allow + direct access to individual elements of the matrix. By default + `as_linear_operator` is False. + args, kwargs : tuple and dict, optional + Additional arguments passed to `fun`. Both empty by default. + The calling signature is ``fun(x, *args, **kwargs)``. + + Returns + ------- + J : {ndarray, sparse matrix, LinearOperator} + Finite difference approximation of the Jacobian matrix. + If `as_linear_operator` is True returns a LinearOperator + with shape (m, n). Otherwise it returns a dense array or sparse + matrix depending on how `sparsity` is defined. If `sparsity` + is None then a ndarray with shape (m, n) is returned. If + `sparsity` is not None returns a csr_matrix with shape (m, n). + For sparse matrices and linear operators it is always returned as + a 2-D structure, for ndarrays, if m=1 it is returned + as a 1-D gradient array with shape (n,). + + See Also + -------- + check_derivative : Check correctness of a function computing derivatives. + + Notes + ----- + If `rel_step` is not provided, it assigned as ``EPS**(1/s)``, where EPS is + determined from the smallest floating point dtype of `x0` or `fun(x0)`, + ``np.finfo(x0.dtype).eps``, s=2 for '2-point' method and + s=3 for '3-point' method. Such relative step approximately minimizes a sum + of truncation and round-off errors, see [1]_. Relative steps are used by + default. However, absolute steps are used when ``abs_step is not None``. + If any of the absolute or relative steps produces an indistinguishable + difference from the original `x0`, ``(x0 + dx) - x0 == 0``, then a + automatic step size is substituted for that particular entry. + + A finite difference scheme for '3-point' method is selected automatically. + The well-known central difference scheme is used for points sufficiently + far from the boundary, and 3-point forward or backward scheme is used for + points near the boundary. Both schemes have the second-order accuracy in + terms of Taylor expansion. Refer to [2]_ for the formulas of 3-point + forward and backward difference schemes. + + For dense differencing when m=1 Jacobian is returned with a shape (n,), + on the other hand when n=1 Jacobian is returned with a shape (m, 1). + Our motivation is the following: a) It handles a case of gradient + computation (m=1) in a conventional way. b) It clearly separates these two + different cases. b) In all cases np.atleast_2d can be called to get 2-D + Jacobian with correct dimensions. + + References + ---------- + .. [1] W. H. Press et. al. "Numerical Recipes. The Art of Scientific + Computing. 3rd edition", sec. 5.7. + + .. [2] A. Curtis, M. J. D. Powell, and J. Reid, "On the estimation of + sparse Jacobian matrices", Journal of the Institute of Mathematics + and its Applications, 13 (1974), pp. 117-120. + + .. [3] B. Fornberg, "Generation of Finite Difference Formulas on + Arbitrarily Spaced Grids", Mathematics of Computation 51, 1988. + + Examples + -------- + >>> import numpy as np + >>> from scipy.optimize._numdiff import approx_derivative + >>> + >>> def f(x, c1, c2): + ... return np.array([x[0] * np.sin(c1 * x[1]), + ... x[0] * np.cos(c2 * x[1])]) + ... + >>> x0 = np.array([1.0, 0.5 * np.pi]) + >>> approx_derivative(f, x0, args=(1, 2)) + array([[ 1., 0.], + [-1., 0.]]) + + Bounds can be used to limit the region of function evaluation. + In the example below we compute left and right derivative at point 1.0. + + >>> def g(x): + ... return x**2 if x >= 1 else x + ... + >>> x0 = 1.0 + >>> approx_derivative(g, x0, bounds=(-np.inf, 1.0)) + array([ 1.]) + >>> approx_derivative(g, x0, bounds=(1.0, np.inf)) + array([ 2.]) + """ + if method not in ['2-point', '3-point', 'cs']: + raise ValueError(f"Unknown method '{method}'. ") + + xp = array_namespace(x0) + _x = xpx.atleast_nd(xp.asarray(x0), ndim=1, xp=xp) + _dtype = xp.float64 + if xp.isdtype(_x.dtype, "real floating"): + _dtype = _x.dtype + + # promotes to floating + x0 = xp.astype(_x, _dtype) + + if x0.ndim > 1: + raise ValueError("`x0` must have at most 1 dimension.") + + lb, ub = _prepare_bounds(bounds, x0) + + if lb.shape != x0.shape or ub.shape != x0.shape: + raise ValueError("Inconsistent shapes between bounds and `x0`.") + + if as_linear_operator and not (np.all(np.isinf(lb)) + and np.all(np.isinf(ub))): + raise ValueError("Bounds not supported when " + "`as_linear_operator` is True.") + + if kwargs is None: + kwargs = {} + + def fun_wrapped(x): + # send user function same fp type as x0. (but only if cs is not being + # used + if xp.isdtype(x.dtype, "real floating"): + x = xp.astype(x, x0.dtype) + + f = np.atleast_1d(fun(x, *args, **kwargs)) + if f.ndim > 1: + raise RuntimeError("`fun` return value has " + "more than 1 dimension.") + return f + + if f0 is None: + f0 = fun_wrapped(x0) + else: + f0 = np.atleast_1d(f0) + if f0.ndim > 1: + raise ValueError("`f0` passed has more than 1 dimension.") + + if np.any((x0 < lb) | (x0 > ub)): + raise ValueError("`x0` violates bound constraints.") + + if as_linear_operator: + if rel_step is None: + rel_step = _eps_for_method(x0.dtype, f0.dtype, method) + + return _linear_operator_difference(fun_wrapped, x0, + f0, rel_step, method) + else: + # by default we use rel_step + if abs_step is None: + h = _compute_absolute_step(rel_step, x0, f0, method) + else: + # user specifies an absolute step + sign_x0 = (x0 >= 0).astype(float) * 2 - 1 + h = abs_step + + # cannot have a zero step. This might happen if x0 is very large + # or small. In which case fall back to relative step. + dx = ((x0 + h) - x0) + h = np.where(dx == 0, + _eps_for_method(x0.dtype, f0.dtype, method) * + sign_x0 * np.maximum(1.0, np.abs(x0)), + h) + + if method == '2-point': + h, use_one_sided = _adjust_scheme_to_bounds( + x0, h, 1, '1-sided', lb, ub) + elif method == '3-point': + h, use_one_sided = _adjust_scheme_to_bounds( + x0, h, 1, '2-sided', lb, ub) + elif method == 'cs': + use_one_sided = False + + if sparsity is None: + return _dense_difference(fun_wrapped, x0, f0, h, + use_one_sided, method) + else: + if not issparse(sparsity) and len(sparsity) == 2: + structure, groups = sparsity + else: + structure = sparsity + groups = group_columns(sparsity) + + if issparse(structure): + structure = csc_matrix(structure) + else: + structure = np.atleast_2d(structure) + + groups = np.atleast_1d(groups) + return _sparse_difference(fun_wrapped, x0, f0, h, + use_one_sided, structure, + groups, method) + + +def _linear_operator_difference(fun, x0, f0, h, method): + m = f0.size + n = x0.size + + if method == '2-point': + def matvec(p): + if np.array_equal(p, np.zeros_like(p)): + return np.zeros(m) + dx = h / norm(p) + x = x0 + dx*p + df = fun(x) - f0 + return df / dx + + elif method == '3-point': + def matvec(p): + if np.array_equal(p, np.zeros_like(p)): + return np.zeros(m) + dx = 2*h / norm(p) + x1 = x0 - (dx/2)*p + x2 = x0 + (dx/2)*p + f1 = fun(x1) + f2 = fun(x2) + df = f2 - f1 + return df / dx + + elif method == 'cs': + def matvec(p): + if np.array_equal(p, np.zeros_like(p)): + return np.zeros(m) + dx = h / norm(p) + x = x0 + dx*p*1.j + f1 = fun(x) + df = f1.imag + return df / dx + + else: + raise RuntimeError("Never be here.") + + return LinearOperator((m, n), matvec) + + +def _dense_difference(fun, x0, f0, h, use_one_sided, method): + m = f0.size + n = x0.size + J_transposed = np.empty((n, m)) + x1 = x0.copy() + x2 = x0.copy() + xc = x0.astype(complex, copy=True) + + for i in range(h.size): + if method == '2-point': + x1[i] += h[i] + dx = x1[i] - x0[i] # Recompute dx as exactly representable number. + df = fun(x1) - f0 + elif method == '3-point' and use_one_sided[i]: + x1[i] += h[i] + x2[i] += 2 * h[i] + dx = x2[i] - x0[i] + f1 = fun(x1) + f2 = fun(x2) + df = -3.0 * f0 + 4 * f1 - f2 + elif method == '3-point' and not use_one_sided[i]: + x1[i] -= h[i] + x2[i] += h[i] + dx = x2[i] - x1[i] + f1 = fun(x1) + f2 = fun(x2) + df = f2 - f1 + elif method == 'cs': + xc[i] += h[i] * 1.j + f1 = fun(xc) + df = f1.imag + dx = h[i] + else: + raise RuntimeError("Never be here.") + + J_transposed[i] = df / dx + x1[i] = x2[i] = xc[i] = x0[i] + + if m == 1: + J_transposed = np.ravel(J_transposed) + + return J_transposed.T + + +def _sparse_difference(fun, x0, f0, h, use_one_sided, + structure, groups, method): + m = f0.size + n = x0.size + row_indices = [] + col_indices = [] + fractions = [] + + n_groups = np.max(groups) + 1 + for group in range(n_groups): + # Perturb variables which are in the same group simultaneously. + e = np.equal(group, groups) + h_vec = h * e + if method == '2-point': + x = x0 + h_vec + dx = x - x0 + df = fun(x) - f0 + # The result is written to columns which correspond to perturbed + # variables. + cols, = np.nonzero(e) + # Find all non-zero elements in selected columns of Jacobian. + i, j, _ = find(structure[:, cols]) + # Restore column indices in the full array. + j = cols[j] + elif method == '3-point': + # Here we do conceptually the same but separate one-sided + # and two-sided schemes. + x1 = x0.copy() + x2 = x0.copy() + + mask_1 = use_one_sided & e + x1[mask_1] += h_vec[mask_1] + x2[mask_1] += 2 * h_vec[mask_1] + + mask_2 = ~use_one_sided & e + x1[mask_2] -= h_vec[mask_2] + x2[mask_2] += h_vec[mask_2] + + dx = np.zeros(n) + dx[mask_1] = x2[mask_1] - x0[mask_1] + dx[mask_2] = x2[mask_2] - x1[mask_2] + + f1 = fun(x1) + f2 = fun(x2) + + cols, = np.nonzero(e) + i, j, _ = find(structure[:, cols]) + j = cols[j] + + mask = use_one_sided[j] + df = np.empty(m) + + rows = i[mask] + df[rows] = -3 * f0[rows] + 4 * f1[rows] - f2[rows] + + rows = i[~mask] + df[rows] = f2[rows] - f1[rows] + elif method == 'cs': + f1 = fun(x0 + h_vec*1.j) + df = f1.imag + dx = h_vec + cols, = np.nonzero(e) + i, j, _ = find(structure[:, cols]) + j = cols[j] + else: + raise ValueError("Never be here.") + + # All that's left is to compute the fraction. We store i, j and + # fractions as separate arrays and later construct coo_matrix. + row_indices.append(i) + col_indices.append(j) + fractions.append(df[i] / dx[j]) + + row_indices = np.hstack(row_indices) + col_indices = np.hstack(col_indices) + fractions = np.hstack(fractions) + J = coo_matrix((fractions, (row_indices, col_indices)), shape=(m, n)) + return csr_matrix(J) + + +def check_derivative(fun, jac, x0, bounds=(-np.inf, np.inf), args=(), + kwargs=None): + """Check correctness of a function computing derivatives (Jacobian or + gradient) by comparison with a finite difference approximation. + + Parameters + ---------- + fun : callable + Function of which to estimate the derivatives. The argument x + passed to this function is ndarray of shape (n,) (never a scalar + even if n=1). It must return 1-D array_like of shape (m,) or a scalar. + jac : callable + Function which computes Jacobian matrix of `fun`. It must work with + argument x the same way as `fun`. The return value must be array_like + or sparse matrix with an appropriate shape. + x0 : array_like of shape (n,) or float + Point at which to estimate the derivatives. Float will be converted + to 1-D array. + bounds : 2-tuple of array_like, optional + Lower and upper bounds on independent variables. Defaults to no bounds. + Each bound must match the size of `x0` or be a scalar, in the latter + case the bound will be the same for all variables. Use it to limit the + range of function evaluation. + args, kwargs : tuple and dict, optional + Additional arguments passed to `fun` and `jac`. Both empty by default. + The calling signature is ``fun(x, *args, **kwargs)`` and the same + for `jac`. + + Returns + ------- + accuracy : float + The maximum among all relative errors for elements with absolute values + higher than 1 and absolute errors for elements with absolute values + less or equal than 1. If `accuracy` is on the order of 1e-6 or lower, + then it is likely that your `jac` implementation is correct. + + See Also + -------- + approx_derivative : Compute finite difference approximation of derivative. + + Examples + -------- + >>> import numpy as np + >>> from scipy.optimize._numdiff import check_derivative + >>> + >>> + >>> def f(x, c1, c2): + ... return np.array([x[0] * np.sin(c1 * x[1]), + ... x[0] * np.cos(c2 * x[1])]) + ... + >>> def jac(x, c1, c2): + ... return np.array([ + ... [np.sin(c1 * x[1]), c1 * x[0] * np.cos(c1 * x[1])], + ... [np.cos(c2 * x[1]), -c2 * x[0] * np.sin(c2 * x[1])] + ... ]) + ... + >>> + >>> x0 = np.array([1.0, 0.5 * np.pi]) + >>> check_derivative(f, jac, x0, args=(1, 2)) + 2.4492935982947064e-16 + """ + if kwargs is None: + kwargs = {} + J_to_test = jac(x0, *args, **kwargs) + if issparse(J_to_test): + J_diff = approx_derivative(fun, x0, bounds=bounds, sparsity=J_to_test, + args=args, kwargs=kwargs) + J_to_test = csr_matrix(J_to_test) + abs_err = J_to_test - J_diff + i, j, abs_err_data = find(abs_err) + J_diff_data = np.asarray(J_diff[i, j]).ravel() + return np.max(np.abs(abs_err_data) / + np.maximum(1, np.abs(J_diff_data))) + else: + J_diff = approx_derivative(fun, x0, bounds=bounds, + args=args, kwargs=kwargs) + abs_err = np.abs(J_to_test - J_diff) + return np.max(abs_err / np.maximum(1, np.abs(J_diff))) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_optimize.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_optimize.py new file mode 100644 index 0000000000000000000000000000000000000000..4c0214daad371c51c5b860e4773e2bb01faf123d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_optimize.py @@ -0,0 +1,4131 @@ +#__docformat__ = "restructuredtext en" +# ******NOTICE*************** +# optimize.py module by Travis E. Oliphant +# +# You may copy and use this module as you see fit with no +# guarantee implied provided you keep this notice in all copies. +# *****END NOTICE************ + +# A collection of optimization algorithms. Version 0.5 +# CHANGES +# Added fminbound (July 2001) +# Added brute (Aug. 2002) +# Finished line search satisfying strong Wolfe conditions (Mar. 2004) +# Updated strong Wolfe conditions line search to use +# cubic-interpolation (Mar. 2004) + + +# Minimization routines + +__all__ = ['fmin', 'fmin_powell', 'fmin_bfgs', 'fmin_ncg', 'fmin_cg', + 'fminbound', 'brent', 'golden', 'bracket', 'rosen', 'rosen_der', + 'rosen_hess', 'rosen_hess_prod', 'brute', 'approx_fprime', + 'line_search', 'check_grad', 'OptimizeResult', 'show_options', + 'OptimizeWarning'] + +__docformat__ = "restructuredtext en" + +import math +import warnings +import sys +import inspect +from numpy import eye, argmin, zeros, shape, asarray, sqrt +import numpy as np +from scipy.linalg import cholesky, issymmetric, LinAlgError +from scipy.sparse.linalg import LinearOperator +from ._linesearch import (line_search_wolfe1, line_search_wolfe2, + line_search_wolfe2 as line_search, + LineSearchWarning) +from ._numdiff import approx_derivative +from scipy._lib._util import getfullargspec_no_self as _getfullargspec +from scipy._lib._util import (MapWrapper, check_random_state, _RichResult, + _call_callback_maybe_halt, _transition_to_rng) +from scipy.optimize._differentiable_functions import ScalarFunction, FD_METHODS +from scipy._lib._array_api import array_namespace +from scipy._lib import array_api_extra as xpx + + +# standard status messages of optimizers +_status_message = {'success': 'Optimization terminated successfully.', + 'maxfev': 'Maximum number of function evaluations has ' + 'been exceeded.', + 'maxiter': 'Maximum number of iterations has been ' + 'exceeded.', + 'pr_loss': 'Desired error not necessarily achieved due ' + 'to precision loss.', + 'nan': 'NaN result encountered.', + 'out_of_bounds': 'The result is outside of the provided ' + 'bounds.'} + + +class MemoizeJac: + """Decorator that caches the return values of a function returning ``(fun, grad)`` + each time it is called.""" + + def __init__(self, fun): + self.fun = fun + self.jac = None + self._value = None + self.x = None + + def _compute_if_needed(self, x, *args): + if not np.all(x == self.x) or self._value is None or self.jac is None: + self.x = np.asarray(x).copy() + fg = self.fun(x, *args) + self.jac = fg[1] + self._value = fg[0] + + def __call__(self, x, *args): + """ returns the function value """ + self._compute_if_needed(x, *args) + return self._value + + def derivative(self, x, *args): + self._compute_if_needed(x, *args) + return self.jac + + +def _wrap_callback(callback, method=None): + """Wrap a user-provided callback so that attributes can be attached.""" + if callback is None or method in {'tnc', 'slsqp', 'cobyla', 'cobyqa'}: + return callback # don't wrap + + sig = inspect.signature(callback) + + if set(sig.parameters) == {'intermediate_result'}: + def wrapped_callback(res): + return callback(intermediate_result=res) + elif method == 'trust-constr': + def wrapped_callback(res): + return callback(np.copy(res.x), res) + elif method == 'differential_evolution': + def wrapped_callback(res): + return callback(np.copy(res.x), res.convergence) + else: + def wrapped_callback(res): + return callback(np.copy(res.x)) + + wrapped_callback.stop_iteration = False + return wrapped_callback + + +class OptimizeResult(_RichResult): + """ + Represents the optimization result. + + Attributes + ---------- + x : ndarray + The solution of the optimization. + success : bool + Whether or not the optimizer exited successfully. + status : int + Termination status of the optimizer. Its value depends on the + underlying solver. Refer to `message` for details. + message : str + Description of the cause of the termination. + fun : float + Value of objective function at `x`. + jac, hess : ndarray + Values of objective function's Jacobian and its Hessian at `x` (if + available). The Hessian may be an approximation, see the documentation + of the function in question. + hess_inv : object + Inverse of the objective function's Hessian; may be an approximation. + Not available for all solvers. The type of this attribute may be + either np.ndarray or scipy.sparse.linalg.LinearOperator. + nfev, njev, nhev : int + Number of evaluations of the objective functions and of its + Jacobian and Hessian. + nit : int + Number of iterations performed by the optimizer. + maxcv : float + The maximum constraint violation. + + Notes + ----- + Depending on the specific solver being used, `OptimizeResult` may + not have all attributes listed here, and they may have additional + attributes not listed here. Since this class is essentially a + subclass of dict with attribute accessors, one can see which + attributes are available using the `OptimizeResult.keys` method. + + """ + pass + + +class OptimizeWarning(UserWarning): + pass + +def _check_positive_definite(Hk): + def is_pos_def(A): + if issymmetric(A): + try: + cholesky(A) + return True + except LinAlgError: + return False + else: + return False + if Hk is not None: + if not is_pos_def(Hk): + raise ValueError("'hess_inv0' matrix isn't positive definite.") + + +def _check_unknown_options(unknown_options): + if unknown_options: + msg = ", ".join(map(str, unknown_options.keys())) + # Stack level 4: this is called from _minimize_*, which is + # called from another function in SciPy. Level 4 is the first + # level in user code. + warnings.warn(f"Unknown solver options: {msg}", OptimizeWarning, stacklevel=4) + + +def is_finite_scalar(x): + """Test whether `x` is either a finite scalar or a finite array scalar. + + """ + return np.size(x) == 1 and np.isfinite(x) + + +_epsilon = sqrt(np.finfo(float).eps) + + +def vecnorm(x, ord=2): + if ord == np.inf: + return np.amax(np.abs(x)) + elif ord == -np.inf: + return np.amin(np.abs(x)) + else: + return np.sum(np.abs(x)**ord, axis=0)**(1.0 / ord) + + +def _prepare_scalar_function(fun, x0, jac=None, args=(), bounds=None, + epsilon=None, finite_diff_rel_step=None, + hess=None): + """ + Creates a ScalarFunction object for use with scalar minimizers + (BFGS/LBFGSB/SLSQP/TNC/CG/etc). + + Parameters + ---------- + fun : callable + The objective function to be minimized. + + ``fun(x, *args) -> float`` + + where ``x`` is an 1-D array with shape (n,) and ``args`` + is a tuple of the fixed parameters needed to completely + specify the function. + x0 : ndarray, shape (n,) + Initial guess. Array of real elements of size (n,), + where 'n' is the number of independent variables. + jac : {callable, '2-point', '3-point', 'cs', None}, optional + Method for computing the gradient vector. If it is a callable, it + should be a function that returns the gradient vector: + + ``jac(x, *args) -> array_like, shape (n,)`` + + If one of `{'2-point', '3-point', 'cs'}` is selected then the gradient + is calculated with a relative step for finite differences. If `None`, + then two-point finite differences with an absolute step is used. + args : tuple, optional + Extra arguments passed to the objective function and its + derivatives (`fun`, `jac` functions). + bounds : sequence, optional + Bounds on variables. 'new-style' bounds are required. + eps : float or ndarray + If ``jac is None`` the absolute step size used for numerical + approximation of the jacobian via forward differences. + finite_diff_rel_step : None or array_like, optional + If ``jac in ['2-point', '3-point', 'cs']`` the relative step size to + use for numerical approximation of the jacobian. The absolute step + size is computed as ``h = rel_step * sign(x0) * max(1, abs(x0))``, + possibly adjusted to fit into the bounds. For ``jac='3-point'`` + the sign of `h` is ignored. If None (default) then step is selected + automatically. + hess : {callable, '2-point', '3-point', 'cs', None} + Computes the Hessian matrix. If it is callable, it should return the + Hessian matrix: + + ``hess(x, *args) -> {LinearOperator, spmatrix, array}, (n, n)`` + + Alternatively, the keywords {'2-point', '3-point', 'cs'} select a + finite difference scheme for numerical estimation. + Whenever the gradient is estimated via finite-differences, the Hessian + cannot be estimated with options {'2-point', '3-point', 'cs'} and needs + to be estimated using one of the quasi-Newton strategies. + + Returns + ------- + sf : ScalarFunction + """ + if callable(jac): + grad = jac + elif jac in FD_METHODS: + # epsilon is set to None so that ScalarFunction is made to use + # rel_step + epsilon = None + grad = jac + else: + # default (jac is None) is to do 2-point finite differences with + # absolute step size. ScalarFunction has to be provided an + # epsilon value that is not None to use absolute steps. This is + # normally the case from most _minimize* methods. + grad = '2-point' + epsilon = epsilon + + if hess is None: + # ScalarFunction requires something for hess, so we give a dummy + # implementation here if nothing is provided, return a value of None + # so that downstream minimisers halt. The results of `fun.hess` + # should not be used. + def hess(x, *args): + return None + + if bounds is None: + bounds = (-np.inf, np.inf) + + # ScalarFunction caches. Reuse of fun(x) during grad + # calculation reduces overall function evaluations. + sf = ScalarFunction(fun, x0, args, grad, hess, + finite_diff_rel_step, bounds, epsilon=epsilon) + + return sf + + +def _clip_x_for_func(func, bounds): + # ensures that x values sent to func are clipped to bounds + + # this is used as a mitigation for gh11403, slsqp/tnc sometimes + # suggest a move that is outside the limits by 1 or 2 ULP. This + # unclean fix makes sure x is strictly within bounds. + def eval(x): + x = _check_clip_x(x, bounds) + return func(x) + + return eval + + +def _check_clip_x(x, bounds): + if (x < bounds[0]).any() or (x > bounds[1]).any(): + warnings.warn("Values in x were outside bounds during a " + "minimize step, clipping to bounds", + RuntimeWarning, stacklevel=3) + x = np.clip(x, bounds[0], bounds[1]) + return x + + return x + + +def rosen(x): + """ + The Rosenbrock function. + + The function computed is:: + + sum(100.0*(x[1:] - x[:-1]**2.0)**2.0 + (1 - x[:-1])**2.0) + + Parameters + ---------- + x : array_like + 1-D array of points at which the Rosenbrock function is to be computed. + + Returns + ------- + f : float + The value of the Rosenbrock function. + + See Also + -------- + rosen_der, rosen_hess, rosen_hess_prod + + Examples + -------- + >>> import numpy as np + >>> from scipy.optimize import rosen + >>> X = 0.1 * np.arange(10) + >>> rosen(X) + 76.56 + + For higher-dimensional input ``rosen`` broadcasts. + In the following example, we use this to plot a 2D landscape. + Note that ``rosen_hess`` does not broadcast in this manner. + + >>> import matplotlib.pyplot as plt + >>> from mpl_toolkits.mplot3d import Axes3D + >>> x = np.linspace(-1, 1, 50) + >>> X, Y = np.meshgrid(x, x) + >>> ax = plt.subplot(111, projection='3d') + >>> ax.plot_surface(X, Y, rosen([X, Y])) + >>> plt.show() + """ + xp = array_namespace(x) + x = xp.asarray(x) + if xp.isdtype(x.dtype, 'integral'): + x = xp.astype(x, xp.asarray(1.).dtype) + r = xp.sum(100.0 * (x[1:] - x[:-1]**2.0)**2.0 + (1 - x[:-1])**2.0, + axis=0, dtype=x.dtype) + return r + + +def rosen_der(x): + """ + The derivative (i.e. gradient) of the Rosenbrock function. + + Parameters + ---------- + x : array_like + 1-D array of points at which the derivative is to be computed. + + Returns + ------- + rosen_der : (N,) ndarray + The gradient of the Rosenbrock function at `x`. + + See Also + -------- + rosen, rosen_hess, rosen_hess_prod + + Examples + -------- + >>> import numpy as np + >>> from scipy.optimize import rosen_der + >>> X = 0.1 * np.arange(9) + >>> rosen_der(X) + array([ -2. , 10.6, 15.6, 13.4, 6.4, -3. , -12.4, -19.4, 62. ]) + + """ + xp = array_namespace(x) + x = xp.asarray(x) + if xp.isdtype(x.dtype, 'integral'): + x = xp.astype(x, xp.asarray(1.).dtype) + xm = x[1:-1] + xm_m1 = x[:-2] + xm_p1 = x[2:] + der = xp.zeros_like(x) + der[1:-1] = (200 * (xm - xm_m1**2) - + 400 * (xm_p1 - xm**2) * xm - 2 * (1 - xm)) + der[0] = -400 * x[0] * (x[1] - x[0]**2) - 2 * (1 - x[0]) + der[-1] = 200 * (x[-1] - x[-2]**2) + return der + + +def rosen_hess(x): + """ + The Hessian matrix of the Rosenbrock function. + + Parameters + ---------- + x : array_like + 1-D array of points at which the Hessian matrix is to be computed. + + Returns + ------- + rosen_hess : ndarray + The Hessian matrix of the Rosenbrock function at `x`. + + See Also + -------- + rosen, rosen_der, rosen_hess_prod + + Examples + -------- + >>> import numpy as np + >>> from scipy.optimize import rosen_hess + >>> X = 0.1 * np.arange(4) + >>> rosen_hess(X) + array([[-38., 0., 0., 0.], + [ 0., 134., -40., 0.], + [ 0., -40., 130., -80.], + [ 0., 0., -80., 200.]]) + + """ + xp = array_namespace(x) + x = xpx.atleast_nd(x, ndim=1, xp=xp) + if xp.isdtype(x.dtype, 'integral'): + x = xp.astype(x, xp.asarray(1.).dtype) + H = (xpx.create_diagonal(-400 * x[:-1], offset=1, xp=xp) + - xpx.create_diagonal(400 * x[:-1], offset=-1, xp=xp)) + diagonal = xp.zeros(x.shape[0], dtype=x.dtype) + diagonal[0] = 1200 * x[0]**2 - 400 * x[1] + 2 + diagonal[-1] = 200 + diagonal[1:-1] = 202 + 1200 * x[1:-1]**2 - 400 * x[2:] + return H + xpx.create_diagonal(diagonal, xp=xp) + + +def rosen_hess_prod(x, p): + """ + Product of the Hessian matrix of the Rosenbrock function with a vector. + + Parameters + ---------- + x : array_like + 1-D array of points at which the Hessian matrix is to be computed. + p : array_like + 1-D array, the vector to be multiplied by the Hessian matrix. + + Returns + ------- + rosen_hess_prod : ndarray + The Hessian matrix of the Rosenbrock function at `x` multiplied + by the vector `p`. + + See Also + -------- + rosen, rosen_der, rosen_hess + + Examples + -------- + >>> import numpy as np + >>> from scipy.optimize import rosen_hess_prod + >>> X = 0.1 * np.arange(9) + >>> p = 0.5 * np.arange(9) + >>> rosen_hess_prod(X, p) + array([ -0., 27., -10., -95., -192., -265., -278., -195., -180.]) + + """ + xp = array_namespace(x, p) + x = xpx.atleast_nd(x, ndim=1, xp=xp) + if xp.isdtype(x.dtype, 'integral'): + x = xp.astype(x, xp.asarray(1.).dtype) + p = xp.asarray(p, dtype=x.dtype) + Hp = xp.zeros(x.shape[0], dtype=x.dtype) + Hp[0] = (1200 * x[0]**2 - 400 * x[1] + 2) * p[0] - 400 * x[0] * p[1] + Hp[1:-1] = (-400 * x[:-2] * p[:-2] + + (202 + 1200 * x[1:-1]**2 - 400 * x[2:]) * p[1:-1] - + 400 * x[1:-1] * p[2:]) + Hp[-1] = -400 * x[-2] * p[-2] + 200*p[-1] + return Hp + + +def _wrap_scalar_function(function, args): + # wraps a minimizer function to count number of evaluations + # and to easily provide an args kwd. + ncalls = [0] + if function is None: + return ncalls, None + + def function_wrapper(x, *wrapper_args): + ncalls[0] += 1 + # A copy of x is sent to the user function (gh13740) + fx = function(np.copy(x), *(wrapper_args + args)) + # Ideally, we'd like to a have a true scalar returned from f(x). For + # backwards-compatibility, also allow np.array([1.3]), np.array([[1.3]]) etc. + if not np.isscalar(fx): + try: + fx = np.asarray(fx).item() + except (TypeError, ValueError) as e: + raise ValueError("The user-provided objective function " + "must return a scalar value.") from e + return fx + + return ncalls, function_wrapper + + +class _MaxFuncCallError(RuntimeError): + pass + + +def _wrap_scalar_function_maxfun_validation(function, args, maxfun): + # wraps a minimizer function to count number of evaluations + # and to easily provide an args kwd. + ncalls = [0] + if function is None: + return ncalls, None + + def function_wrapper(x, *wrapper_args): + if ncalls[0] >= maxfun: + raise _MaxFuncCallError("Too many function calls") + ncalls[0] += 1 + # A copy of x is sent to the user function (gh13740) + fx = function(np.copy(x), *(wrapper_args + args)) + # Ideally, we'd like to a have a true scalar returned from f(x). For + # backwards-compatibility, also allow np.array([1.3]), + # np.array([[1.3]]) etc. + if not np.isscalar(fx): + try: + fx = np.asarray(fx).item() + except (TypeError, ValueError) as e: + raise ValueError("The user-provided objective function " + "must return a scalar value.") from e + return fx + + return ncalls, function_wrapper + + +def fmin(func, x0, args=(), xtol=1e-4, ftol=1e-4, maxiter=None, maxfun=None, + full_output=0, disp=1, retall=0, callback=None, initial_simplex=None): + """ + Minimize a function using the downhill simplex algorithm. + + This algorithm only uses function values, not derivatives or second + derivatives. + + Parameters + ---------- + func : callable func(x,*args) + The objective function to be minimized. + x0 : ndarray + Initial guess. + args : tuple, optional + Extra arguments passed to func, i.e., ``f(x,*args)``. + xtol : float, optional + Absolute error in xopt between iterations that is acceptable for + convergence. + ftol : number, optional + Absolute error in func(xopt) between iterations that is acceptable for + convergence. + maxiter : int, optional + Maximum number of iterations to perform. + maxfun : number, optional + Maximum number of function evaluations to make. + full_output : bool, optional + Set to True if fopt and warnflag outputs are desired. + disp : bool, optional + Set to True to print convergence messages. + retall : bool, optional + Set to True to return list of solutions at each iteration. + callback : callable, optional + Called after each iteration, as callback(xk), where xk is the + current parameter vector. + initial_simplex : array_like of shape (N + 1, N), optional + Initial simplex. If given, overrides `x0`. + ``initial_simplex[j,:]`` should contain the coordinates of + the jth vertex of the ``N+1`` vertices in the simplex, where + ``N`` is the dimension. + + Returns + ------- + xopt : ndarray + Parameter that minimizes function. + fopt : float + Value of function at minimum: ``fopt = func(xopt)``. + iter : int + Number of iterations performed. + funcalls : int + Number of function calls made. + warnflag : int + 1 : Maximum number of function evaluations made. + 2 : Maximum number of iterations reached. + allvecs : list + Solution at each iteration. + + See also + -------- + minimize: Interface to minimization algorithms for multivariate + functions. See the 'Nelder-Mead' `method` in particular. + + Notes + ----- + Uses a Nelder-Mead simplex algorithm to find the minimum of function of + one or more variables. + + This algorithm has a long history of successful use in applications. + But it will usually be slower than an algorithm that uses first or + second derivative information. In practice, it can have poor + performance in high-dimensional problems and is not robust to + minimizing complicated functions. Additionally, there currently is no + complete theory describing when the algorithm will successfully + converge to the minimum, or how fast it will if it does. Both the ftol and + xtol criteria must be met for convergence. + + Examples + -------- + >>> def f(x): + ... return x**2 + + >>> from scipy import optimize + + >>> minimum = optimize.fmin(f, 1) + Optimization terminated successfully. + Current function value: 0.000000 + Iterations: 17 + Function evaluations: 34 + >>> minimum[0] + -8.8817841970012523e-16 + + References + ---------- + .. [1] Nelder, J.A. and Mead, R. (1965), "A simplex method for function + minimization", The Computer Journal, 7, pp. 308-313 + + .. [2] Wright, M.H. (1996), "Direct Search Methods: Once Scorned, Now + Respectable", in Numerical Analysis 1995, Proceedings of the + 1995 Dundee Biennial Conference in Numerical Analysis, D.F. + Griffiths and G.A. Watson (Eds.), Addison Wesley Longman, + Harlow, UK, pp. 191-208. + + """ + opts = {'xatol': xtol, + 'fatol': ftol, + 'maxiter': maxiter, + 'maxfev': maxfun, + 'disp': disp, + 'return_all': retall, + 'initial_simplex': initial_simplex} + + callback = _wrap_callback(callback) + res = _minimize_neldermead(func, x0, args, callback=callback, **opts) + if full_output: + retlist = res['x'], res['fun'], res['nit'], res['nfev'], res['status'] + if retall: + retlist += (res['allvecs'], ) + return retlist + else: + if retall: + return res['x'], res['allvecs'] + else: + return res['x'] + + +def _minimize_neldermead(func, x0, args=(), callback=None, + maxiter=None, maxfev=None, disp=False, + return_all=False, initial_simplex=None, + xatol=1e-4, fatol=1e-4, adaptive=False, bounds=None, + **unknown_options): + """ + Minimization of scalar function of one or more variables using the + Nelder-Mead algorithm. + + Options + ------- + disp : bool + Set to True to print convergence messages. + maxiter, maxfev : int + Maximum allowed number of iterations and function evaluations. + Will default to ``N*200``, where ``N`` is the number of + variables, if neither `maxiter` or `maxfev` is set. If both + `maxiter` and `maxfev` are set, minimization will stop at the + first reached. + return_all : bool, optional + Set to True to return a list of the best solution at each of the + iterations. + initial_simplex : array_like of shape (N + 1, N) + Initial simplex. If given, overrides `x0`. + ``initial_simplex[j,:]`` should contain the coordinates of + the jth vertex of the ``N+1`` vertices in the simplex, where + ``N`` is the dimension. + xatol : float, optional + Absolute error in xopt between iterations that is acceptable for + convergence. + fatol : number, optional + Absolute error in func(xopt) between iterations that is acceptable for + convergence. + adaptive : bool, optional + Adapt algorithm parameters to dimensionality of problem. Useful for + high-dimensional minimization [1]_. + bounds : sequence or `Bounds`, optional + Bounds on variables. There are two ways to specify the bounds: + + 1. Instance of `Bounds` class. + 2. Sequence of ``(min, max)`` pairs for each element in `x`. None + is used to specify no bound. + + Note that this just clips all vertices in simplex based on + the bounds. + + References + ---------- + .. [1] Gao, F. and Han, L. + Implementing the Nelder-Mead simplex algorithm with adaptive + parameters. 2012. Computational Optimization and Applications. + 51:1, pp. 259-277 + + """ + _check_unknown_options(unknown_options) + maxfun = maxfev + retall = return_all + + x0 = np.atleast_1d(x0).flatten() + dtype = x0.dtype if np.issubdtype(x0.dtype, np.inexact) else np.float64 + x0 = np.asarray(x0, dtype=dtype) + + if adaptive: + dim = float(len(x0)) + rho = 1 + chi = 1 + 2/dim + psi = 0.75 - 1/(2*dim) + sigma = 1 - 1/dim + else: + rho = 1 + chi = 2 + psi = 0.5 + sigma = 0.5 + + nonzdelt = 0.05 + zdelt = 0.00025 + + if bounds is not None: + lower_bound, upper_bound = bounds.lb, bounds.ub + # check bounds + if (lower_bound > upper_bound).any(): + raise ValueError("Nelder Mead - one of the lower bounds " + "is greater than an upper bound.") + if np.any(lower_bound > x0) or np.any(x0 > upper_bound): + warnings.warn("Initial guess is not within the specified bounds", + OptimizeWarning, stacklevel=3) + + if bounds is not None: + x0 = np.clip(x0, lower_bound, upper_bound) + + if initial_simplex is None: + N = len(x0) + + sim = np.empty((N + 1, N), dtype=x0.dtype) + sim[0] = x0 + for k in range(N): + y = np.array(x0, copy=True) + if y[k] != 0: + y[k] = (1 + nonzdelt)*y[k] + else: + y[k] = zdelt + sim[k + 1] = y + else: + sim = np.atleast_2d(initial_simplex).copy() + dtype = sim.dtype if np.issubdtype(sim.dtype, np.inexact) else np.float64 + sim = np.asarray(sim, dtype=dtype) + if sim.ndim != 2 or sim.shape[0] != sim.shape[1] + 1: + raise ValueError("`initial_simplex` should be an array of shape (N+1,N)") + if len(x0) != sim.shape[1]: + raise ValueError("Size of `initial_simplex` is not consistent with `x0`") + N = sim.shape[1] + + if retall: + allvecs = [sim[0]] + + # If neither are set, then set both to default + if maxiter is None and maxfun is None: + maxiter = N * 200 + maxfun = N * 200 + elif maxiter is None: + # Convert remaining Nones, to np.inf, unless the other is np.inf, in + # which case use the default to avoid unbounded iteration + if maxfun == np.inf: + maxiter = N * 200 + else: + maxiter = np.inf + elif maxfun is None: + if maxiter == np.inf: + maxfun = N * 200 + else: + maxfun = np.inf + + if bounds is not None: + # The default simplex construction may make all entries (for a given + # parameter) greater than an upper bound if x0 is very close to the + # upper bound. If one simply clips the simplex to the bounds this could + # make the simplex entries degenerate. If that occurs reflect into the + # interior. + msk = sim > upper_bound + # reflect into the interior + sim = np.where(msk, 2*upper_bound - sim, sim) + # but make sure the reflection is no less than the lower_bound + sim = np.clip(sim, lower_bound, upper_bound) + + one2np1 = list(range(1, N + 1)) + fsim = np.full((N + 1,), np.inf, dtype=float) + + fcalls, func = _wrap_scalar_function_maxfun_validation(func, args, maxfun) + + try: + for k in range(N + 1): + fsim[k] = func(sim[k]) + except _MaxFuncCallError: + pass + finally: + ind = np.argsort(fsim) + sim = np.take(sim, ind, 0) + fsim = np.take(fsim, ind, 0) + + ind = np.argsort(fsim) + fsim = np.take(fsim, ind, 0) + # sort so sim[0,:] has the lowest function value + sim = np.take(sim, ind, 0) + + iterations = 1 + + while (fcalls[0] < maxfun and iterations < maxiter): + try: + if (np.max(np.ravel(np.abs(sim[1:] - sim[0]))) <= xatol and + np.max(np.abs(fsim[0] - fsim[1:])) <= fatol): + break + + xbar = np.add.reduce(sim[:-1], 0) / N + xr = (1 + rho) * xbar - rho * sim[-1] + if bounds is not None: + xr = np.clip(xr, lower_bound, upper_bound) + fxr = func(xr) + doshrink = 0 + + if fxr < fsim[0]: + xe = (1 + rho * chi) * xbar - rho * chi * sim[-1] + if bounds is not None: + xe = np.clip(xe, lower_bound, upper_bound) + fxe = func(xe) + + if fxe < fxr: + sim[-1] = xe + fsim[-1] = fxe + else: + sim[-1] = xr + fsim[-1] = fxr + else: # fsim[0] <= fxr + if fxr < fsim[-2]: + sim[-1] = xr + fsim[-1] = fxr + else: # fxr >= fsim[-2] + # Perform contraction + if fxr < fsim[-1]: + xc = (1 + psi * rho) * xbar - psi * rho * sim[-1] + if bounds is not None: + xc = np.clip(xc, lower_bound, upper_bound) + fxc = func(xc) + + if fxc <= fxr: + sim[-1] = xc + fsim[-1] = fxc + else: + doshrink = 1 + else: + # Perform an inside contraction + xcc = (1 - psi) * xbar + psi * sim[-1] + if bounds is not None: + xcc = np.clip(xcc, lower_bound, upper_bound) + fxcc = func(xcc) + + if fxcc < fsim[-1]: + sim[-1] = xcc + fsim[-1] = fxcc + else: + doshrink = 1 + + if doshrink: + for j in one2np1: + sim[j] = sim[0] + sigma * (sim[j] - sim[0]) + if bounds is not None: + sim[j] = np.clip( + sim[j], lower_bound, upper_bound) + fsim[j] = func(sim[j]) + iterations += 1 + except _MaxFuncCallError: + pass + finally: + ind = np.argsort(fsim) + sim = np.take(sim, ind, 0) + fsim = np.take(fsim, ind, 0) + if retall: + allvecs.append(sim[0]) + intermediate_result = OptimizeResult(x=sim[0], fun=fsim[0]) + if _call_callback_maybe_halt(callback, intermediate_result): + break + + x = sim[0] + fval = np.min(fsim) + warnflag = 0 + + if fcalls[0] >= maxfun: + warnflag = 1 + msg = _status_message['maxfev'] + if disp: + warnings.warn(msg, RuntimeWarning, stacklevel=3) + elif iterations >= maxiter: + warnflag = 2 + msg = _status_message['maxiter'] + if disp: + warnings.warn(msg, RuntimeWarning, stacklevel=3) + else: + msg = _status_message['success'] + if disp: + print(msg) + print(f" Current function value: {fval:f}") + print(" Iterations: %d" % iterations) + print(" Function evaluations: %d" % fcalls[0]) + + result = OptimizeResult(fun=fval, nit=iterations, nfev=fcalls[0], + status=warnflag, success=(warnflag == 0), + message=msg, x=x, final_simplex=(sim, fsim)) + if retall: + result['allvecs'] = allvecs + return result + + +def approx_fprime(xk, f, epsilon=_epsilon, *args): + """Finite difference approximation of the derivatives of a + scalar or vector-valued function. + + If a function maps from :math:`R^n` to :math:`R^m`, its derivatives form + an m-by-n matrix + called the Jacobian, where an element :math:`(i, j)` is a partial + derivative of f[i] with respect to ``xk[j]``. + + Parameters + ---------- + xk : array_like + The coordinate vector at which to determine the gradient of `f`. + f : callable + Function of which to estimate the derivatives of. Has the signature + ``f(xk, *args)`` where `xk` is the argument in the form of a 1-D array + and `args` is a tuple of any additional fixed parameters needed to + completely specify the function. The argument `xk` passed to this + function is an ndarray of shape (n,) (never a scalar even if n=1). + It must return a 1-D array_like of shape (m,) or a scalar. + + Suppose the callable has signature ``f0(x, *my_args, **my_kwargs)``, where + ``my_args`` and ``my_kwargs`` are required positional and keyword arguments. + Rather than passing ``f0`` as the callable, wrap it to accept + only ``x``; e.g., pass ``fun=lambda x: f0(x, *my_args, **my_kwargs)`` as the + callable, where ``my_args`` (tuple) and ``my_kwargs`` (dict) have been + gathered before invoking this function. + + .. versionchanged:: 1.9.0 + `f` is now able to return a 1-D array-like, with the :math:`(m, n)` + Jacobian being estimated. + + epsilon : {float, array_like}, optional + Increment to `xk` to use for determining the function gradient. + If a scalar, uses the same finite difference delta for all partial + derivatives. If an array, should contain one value per element of + `xk`. Defaults to ``sqrt(np.finfo(float).eps)``, which is approximately + 1.49e-08. + \\*args : args, optional + Any other arguments that are to be passed to `f`. + + Returns + ------- + jac : ndarray + The partial derivatives of `f` to `xk`. + + See Also + -------- + check_grad : Check correctness of gradient function against approx_fprime. + + Notes + ----- + The function gradient is determined by the forward finite difference + formula:: + + f(xk[i] + epsilon[i]) - f(xk[i]) + f'[i] = --------------------------------- + epsilon[i] + + Examples + -------- + >>> import numpy as np + >>> from scipy import optimize + >>> def func(x, c0, c1): + ... "Coordinate vector `x` should be an array of size two." + ... return c0 * x[0]**2 + c1*x[1]**2 + + >>> x = np.ones(2) + >>> c0, c1 = (1, 200) + >>> eps = np.sqrt(np.finfo(float).eps) + >>> optimize.approx_fprime(x, func, [eps, np.sqrt(200) * eps], c0, c1) + array([ 2. , 400.00004208]) + + """ + xk = np.asarray(xk, float) + f0 = f(xk, *args) + + return approx_derivative(f, xk, method='2-point', abs_step=epsilon, + args=args, f0=f0) + + +@_transition_to_rng("seed", position_num=6) +def check_grad(func, grad, x0, *args, epsilon=_epsilon, + direction='all', rng=None): + r"""Check the correctness of a gradient function by comparing it against a + (forward) finite-difference approximation of the gradient. + + Parameters + ---------- + func : callable ``func(x0, *args)`` + Function whose derivative is to be checked. + grad : callable ``grad(x0, *args)`` + Jacobian of `func`. + x0 : ndarray + Points to check `grad` against forward difference approximation of grad + using `func`. + args : \\*args, optional + Extra arguments passed to `func` and `grad`. + epsilon : float, optional + Step size used for the finite difference approximation. It defaults to + ``sqrt(np.finfo(float).eps)``, which is approximately 1.49e-08. + direction : str, optional + If set to ``'random'``, then gradients along a random vector + are used to check `grad` against forward difference approximation + using `func`. By default it is ``'all'``, in which case, all + the one hot direction vectors are considered to check `grad`. + If `func` is a vector valued function then only ``'all'`` can be used. + rng : `numpy.random.Generator`, optional + Pseudorandom number generator state. When `rng` is None, a new + `numpy.random.Generator` is created using entropy from the + operating system. Types other than `numpy.random.Generator` are + passed to `numpy.random.default_rng` to instantiate a ``Generator``. + + The random numbers generated affect the random vector along which gradients + are computed to check ``grad``. Note that `rng` is only used when `direction` + argument is set to `'random'`. + + Returns + ------- + err : float + The square root of the sum of squares (i.e., the 2-norm) of the + difference between ``grad(x0, *args)`` and the finite difference + approximation of `grad` using func at the points `x0`. + + See Also + -------- + approx_fprime + + Examples + -------- + >>> import numpy as np + >>> def func(x): + ... return x[0]**2 - 0.5 * x[1]**3 + >>> def grad(x): + ... return [2 * x[0], -1.5 * x[1]**2] + >>> from scipy.optimize import check_grad + >>> check_grad(func, grad, [1.5, -1.5]) + 2.9802322387695312e-08 # may vary + >>> rng = np.random.default_rng() + >>> check_grad(func, grad, [1.5, -1.5], + ... direction='random', seed=rng) + 2.9802322387695312e-08 + + """ + step = epsilon + x0 = np.asarray(x0) + + def g(w, func, x0, v, *args): + return func(x0 + w*v, *args) + + if direction == 'random': + _grad = np.asanyarray(grad(x0, *args)) + if _grad.ndim > 1: + raise ValueError("'random' can only be used with scalar valued" + " func") + rng_gen = check_random_state(rng) + v = rng_gen.standard_normal(size=(x0.shape)) + _args = (func, x0, v) + args + _func = g + vars = np.zeros((1,)) + analytical_grad = np.dot(_grad, v) + elif direction == 'all': + _args = args + _func = func + vars = x0 + analytical_grad = grad(x0, *args) + else: + raise ValueError(f"{direction} is not a valid string for " + "``direction`` argument") + + return np.sqrt(np.sum(np.abs( + (analytical_grad - approx_fprime(vars, _func, step, *_args))**2 + ))) + + +def approx_fhess_p(x0, p, fprime, epsilon, *args): + # calculate fprime(x0) first, as this may be cached by ScalarFunction + f1 = fprime(*((x0,) + args)) + f2 = fprime(*((x0 + epsilon*p,) + args)) + return (f2 - f1) / epsilon + + +class _LineSearchError(RuntimeError): + pass + + +def _line_search_wolfe12(f, fprime, xk, pk, gfk, old_fval, old_old_fval, + **kwargs): + """ + Same as line_search_wolfe1, but fall back to line_search_wolfe2 if + suitable step length is not found, and raise an exception if a + suitable step length is not found. + + Raises + ------ + _LineSearchError + If no suitable step size is found + + """ + + extra_condition = kwargs.pop('extra_condition', None) + + ret = line_search_wolfe1(f, fprime, xk, pk, gfk, + old_fval, old_old_fval, + **kwargs) + + if ret[0] is not None and extra_condition is not None: + xp1 = xk + ret[0] * pk + if not extra_condition(ret[0], xp1, ret[3], ret[5]): + # Reject step if extra_condition fails + ret = (None,) + + if ret[0] is None: + # line search failed: try different one. + with warnings.catch_warnings(): + warnings.simplefilter('ignore', LineSearchWarning) + kwargs2 = {} + for key in ('c1', 'c2', 'amax'): + if key in kwargs: + kwargs2[key] = kwargs[key] + ret = line_search_wolfe2(f, fprime, xk, pk, gfk, + old_fval, old_old_fval, + extra_condition=extra_condition, + **kwargs2) + + if ret[0] is None: + raise _LineSearchError() + + return ret + + +def fmin_bfgs(f, x0, fprime=None, args=(), gtol=1e-5, norm=np.inf, + epsilon=_epsilon, maxiter=None, full_output=0, disp=1, + retall=0, callback=None, xrtol=0, c1=1e-4, c2=0.9, + hess_inv0=None): + """ + Minimize a function using the BFGS algorithm. + + Parameters + ---------- + f : callable ``f(x,*args)`` + Objective function to be minimized. + x0 : ndarray + Initial guess, shape (n,) + fprime : callable ``f'(x,*args)``, optional + Gradient of f. + args : tuple, optional + Extra arguments passed to f and fprime. + gtol : float, optional + Terminate successfully if gradient norm is less than `gtol` + norm : float, optional + Order of norm (Inf is max, -Inf is min) + epsilon : int or ndarray, optional + If `fprime` is approximated, use this value for the step size. + callback : callable, optional + An optional user-supplied function to call after each + iteration. Called as ``callback(xk)``, where ``xk`` is the + current parameter vector. + maxiter : int, optional + Maximum number of iterations to perform. + full_output : bool, optional + If True, return ``fopt``, ``func_calls``, ``grad_calls``, and + ``warnflag`` in addition to ``xopt``. + disp : bool, optional + Print convergence message if True. + retall : bool, optional + Return a list of results at each iteration if True. + xrtol : float, default: 0 + Relative tolerance for `x`. Terminate successfully if step + size is less than ``xk * xrtol`` where ``xk`` is the current + parameter vector. + c1 : float, default: 1e-4 + Parameter for Armijo condition rule. + c2 : float, default: 0.9 + Parameter for curvature condition rule. + hess_inv0 : None or ndarray, optional`` + Initial inverse hessian estimate, shape (n, n). If None (default) then + the identity matrix is used. + + Returns + ------- + xopt : ndarray + Parameters which minimize f, i.e., ``f(xopt) == fopt``. + fopt : float + Minimum value. + gopt : ndarray + Value of gradient at minimum, f'(xopt), which should be near 0. + Bopt : ndarray + Value of 1/f''(xopt), i.e., the inverse Hessian matrix. + func_calls : int + Number of function_calls made. + grad_calls : int + Number of gradient calls made. + warnflag : integer + 1 : Maximum number of iterations exceeded. + 2 : Gradient and/or function calls not changing. + 3 : NaN result encountered. + allvecs : list + The value of `xopt` at each iteration. Only returned if `retall` is + True. + + Notes + ----- + Optimize the function, `f`, whose gradient is given by `fprime` + using the quasi-Newton method of Broyden, Fletcher, Goldfarb, + and Shanno (BFGS). + + Parameters `c1` and `c2` must satisfy ``0 < c1 < c2 < 1``. + + See Also + -------- + minimize: Interface to minimization algorithms for multivariate + functions. See ``method='BFGS'`` in particular. + + References + ---------- + Wright, and Nocedal 'Numerical Optimization', 1999, p. 198. + + Examples + -------- + >>> import numpy as np + >>> from scipy.optimize import fmin_bfgs + >>> def quadratic_cost(x, Q): + ... return x @ Q @ x + ... + >>> x0 = np.array([-3, -4]) + >>> cost_weight = np.diag([1., 10.]) + >>> # Note that a trailing comma is necessary for a tuple with single element + >>> fmin_bfgs(quadratic_cost, x0, args=(cost_weight,)) + Optimization terminated successfully. + Current function value: 0.000000 + Iterations: 7 # may vary + Function evaluations: 24 # may vary + Gradient evaluations: 8 # may vary + array([ 2.85169950e-06, -4.61820139e-07]) + + >>> def quadratic_cost_grad(x, Q): + ... return 2 * Q @ x + ... + >>> fmin_bfgs(quadratic_cost, x0, quadratic_cost_grad, args=(cost_weight,)) + Optimization terminated successfully. + Current function value: 0.000000 + Iterations: 7 + Function evaluations: 8 + Gradient evaluations: 8 + array([ 2.85916637e-06, -4.54371951e-07]) + + """ + opts = {'gtol': gtol, + 'norm': norm, + 'eps': epsilon, + 'disp': disp, + 'maxiter': maxiter, + 'return_all': retall, + 'xrtol': xrtol, + 'c1': c1, + 'c2': c2, + 'hess_inv0': hess_inv0} + + callback = _wrap_callback(callback) + res = _minimize_bfgs(f, x0, args, fprime, callback=callback, **opts) + + if full_output: + retlist = (res['x'], res['fun'], res['jac'], res['hess_inv'], + res['nfev'], res['njev'], res['status']) + if retall: + retlist += (res['allvecs'], ) + return retlist + else: + if retall: + return res['x'], res['allvecs'] + else: + return res['x'] + + +def _minimize_bfgs(fun, x0, args=(), jac=None, callback=None, + gtol=1e-5, norm=np.inf, eps=_epsilon, maxiter=None, + disp=False, return_all=False, finite_diff_rel_step=None, + xrtol=0, c1=1e-4, c2=0.9, + hess_inv0=None, **unknown_options): + """ + Minimization of scalar function of one or more variables using the + BFGS algorithm. + + Options + ------- + disp : bool + Set to True to print convergence messages. + maxiter : int + Maximum number of iterations to perform. + gtol : float + Terminate successfully if gradient norm is less than `gtol`. + norm : float + Order of norm (Inf is max, -Inf is min). + eps : float or ndarray + If `jac is None` the absolute step size used for numerical + approximation of the jacobian via forward differences. + return_all : bool, optional + Set to True to return a list of the best solution at each of the + iterations. + finite_diff_rel_step : None or array_like, optional + If ``jac in ['2-point', '3-point', 'cs']`` the relative step size to + use for numerical approximation of the jacobian. The absolute step + size is computed as ``h = rel_step * sign(x) * max(1, abs(x))``, + possibly adjusted to fit into the bounds. For ``jac='3-point'`` + the sign of `h` is ignored. If None (default) then step is selected + automatically. + xrtol : float, default: 0 + Relative tolerance for `x`. Terminate successfully if step size is + less than ``xk * xrtol`` where ``xk`` is the current parameter vector. + c1 : float, default: 1e-4 + Parameter for Armijo condition rule. + c2 : float, default: 0.9 + Parameter for curvature condition rule. + hess_inv0 : None or ndarray, optional + Initial inverse hessian estimate, shape (n, n). If None (default) then + the identity matrix is used. + + Notes + ----- + Parameters `c1` and `c2` must satisfy ``0 < c1 < c2 < 1``. + + If minimization doesn't complete successfully, with an error message of + ``Desired error not necessarily achieved due to precision loss``, then + consider setting `gtol` to a higher value. This precision loss typically + occurs when the (finite difference) numerical differentiation cannot provide + sufficient precision to satisfy the `gtol` termination criterion. + This can happen when working in single precision and a callable jac is not + provided. For single precision problems a `gtol` of 1e-3 seems to work. + """ + _check_unknown_options(unknown_options) + _check_positive_definite(hess_inv0) + retall = return_all + + x0 = asarray(x0).flatten() + if x0.ndim == 0: + x0.shape = (1,) + if maxiter is None: + maxiter = len(x0) * 200 + + sf = _prepare_scalar_function(fun, x0, jac, args=args, epsilon=eps, + finite_diff_rel_step=finite_diff_rel_step) + + f = sf.fun + myfprime = sf.grad + + old_fval = f(x0) + gfk = myfprime(x0) + + k = 0 + N = len(x0) + I = np.eye(N, dtype=int) + Hk = I if hess_inv0 is None else hess_inv0 + + # Sets the initial step guess to dx ~ 1 + old_old_fval = old_fval + np.linalg.norm(gfk) / 2 + + xk = x0 + if retall: + allvecs = [x0] + warnflag = 0 + gnorm = vecnorm(gfk, ord=norm) + while (gnorm > gtol) and (k < maxiter): + pk = -np.dot(Hk, gfk) + try: + alpha_k, fc, gc, old_fval, old_old_fval, gfkp1 = \ + _line_search_wolfe12(f, myfprime, xk, pk, gfk, + old_fval, old_old_fval, amin=1e-100, + amax=1e100, c1=c1, c2=c2) + except _LineSearchError: + # Line search failed to find a better solution. + warnflag = 2 + break + + sk = alpha_k * pk + xkp1 = xk + sk + + if retall: + allvecs.append(xkp1) + xk = xkp1 + if gfkp1 is None: + gfkp1 = myfprime(xkp1) + + yk = gfkp1 - gfk + gfk = gfkp1 + k += 1 + intermediate_result = OptimizeResult(x=xk, fun=old_fval) + if _call_callback_maybe_halt(callback, intermediate_result): + break + gnorm = vecnorm(gfk, ord=norm) + if (gnorm <= gtol): + break + + # See Chapter 5 in P.E. Frandsen, K. Jonasson, H.B. Nielsen, + # O. Tingleff: "Unconstrained Optimization", IMM, DTU. 1999. + # These notes are available here: + # http://www2.imm.dtu.dk/documents/ftp/publlec.html + if (alpha_k*vecnorm(pk) <= xrtol*(xrtol + vecnorm(xk))): + break + + if not np.isfinite(old_fval): + # We correctly found +-Inf as optimal value, or something went + # wrong. + warnflag = 2 + break + + rhok_inv = np.dot(yk, sk) + # this was handled in numeric, let it remains for more safety + # Cryptic comment above is preserved for posterity. Future reader: + # consider change to condition below proposed in gh-1261/gh-17345. + if rhok_inv == 0.: + rhok = 1000.0 + if disp: + msg = "Divide-by-zero encountered: rhok assumed large" + _print_success_message_or_warn(True, msg) + else: + rhok = 1. / rhok_inv + + A1 = I - sk[:, np.newaxis] * yk[np.newaxis, :] * rhok + A2 = I - yk[:, np.newaxis] * sk[np.newaxis, :] * rhok + Hk = np.dot(A1, np.dot(Hk, A2)) + (rhok * sk[:, np.newaxis] * + sk[np.newaxis, :]) + + fval = old_fval + + if warnflag == 2: + msg = _status_message['pr_loss'] + elif k >= maxiter: + warnflag = 1 + msg = _status_message['maxiter'] + elif np.isnan(gnorm) or np.isnan(fval) or np.isnan(xk).any(): + warnflag = 3 + msg = _status_message['nan'] + else: + msg = _status_message['success'] + + if disp: + _print_success_message_or_warn(warnflag, msg) + print(f" Current function value: {fval:f}") + print(" Iterations: %d" % k) + print(" Function evaluations: %d" % sf.nfev) + print(" Gradient evaluations: %d" % sf.ngev) + + result = OptimizeResult(fun=fval, jac=gfk, hess_inv=Hk, nfev=sf.nfev, + njev=sf.ngev, status=warnflag, + success=(warnflag == 0), message=msg, x=xk, + nit=k) + if retall: + result['allvecs'] = allvecs + return result + + +def _print_success_message_or_warn(warnflag, message, warntype=None): + if not warnflag: + print(message) + else: + warnings.warn(message, warntype or OptimizeWarning, stacklevel=3) + + +def fmin_cg(f, x0, fprime=None, args=(), gtol=1e-5, norm=np.inf, + epsilon=_epsilon, maxiter=None, full_output=0, disp=1, retall=0, + callback=None, c1=1e-4, c2=0.4): + """ + Minimize a function using a nonlinear conjugate gradient algorithm. + + Parameters + ---------- + f : callable, ``f(x, *args)`` + Objective function to be minimized. Here `x` must be a 1-D array of + the variables that are to be changed in the search for a minimum, and + `args` are the other (fixed) parameters of `f`. + x0 : ndarray + A user-supplied initial estimate of `xopt`, the optimal value of `x`. + It must be a 1-D array of values. + fprime : callable, ``fprime(x, *args)``, optional + A function that returns the gradient of `f` at `x`. Here `x` and `args` + are as described above for `f`. The returned value must be a 1-D array. + Defaults to None, in which case the gradient is approximated + numerically (see `epsilon`, below). + args : tuple, optional + Parameter values passed to `f` and `fprime`. Must be supplied whenever + additional fixed parameters are needed to completely specify the + functions `f` and `fprime`. + gtol : float, optional + Stop when the norm of the gradient is less than `gtol`. + norm : float, optional + Order to use for the norm of the gradient + (``-np.inf`` is min, ``np.inf`` is max). + epsilon : float or ndarray, optional + Step size(s) to use when `fprime` is approximated numerically. Can be a + scalar or a 1-D array. Defaults to ``sqrt(eps)``, with eps the + floating point machine precision. Usually ``sqrt(eps)`` is about + 1.5e-8. + maxiter : int, optional + Maximum number of iterations to perform. Default is ``200 * len(x0)``. + full_output : bool, optional + If True, return `fopt`, `func_calls`, `grad_calls`, and `warnflag` in + addition to `xopt`. See the Returns section below for additional + information on optional return values. + disp : bool, optional + If True, return a convergence message, followed by `xopt`. + retall : bool, optional + If True, add to the returned values the results of each iteration. + callback : callable, optional + An optional user-supplied function, called after each iteration. + Called as ``callback(xk)``, where ``xk`` is the current value of `x0`. + c1 : float, default: 1e-4 + Parameter for Armijo condition rule. + c2 : float, default: 0.4 + Parameter for curvature condition rule. + + Returns + ------- + xopt : ndarray + Parameters which minimize f, i.e., ``f(xopt) == fopt``. + fopt : float, optional + Minimum value found, f(xopt). Only returned if `full_output` is True. + func_calls : int, optional + The number of function_calls made. Only returned if `full_output` + is True. + grad_calls : int, optional + The number of gradient calls made. Only returned if `full_output` is + True. + warnflag : int, optional + Integer value with warning status, only returned if `full_output` is + True. + + 0 : Success. + + 1 : The maximum number of iterations was exceeded. + + 2 : Gradient and/or function calls were not changing. May indicate + that precision was lost, i.e., the routine did not converge. + + 3 : NaN result encountered. + + allvecs : list of ndarray, optional + List of arrays, containing the results at each iteration. + Only returned if `retall` is True. + + See Also + -------- + minimize : common interface to all `scipy.optimize` algorithms for + unconstrained and constrained minimization of multivariate + functions. It provides an alternative way to call + ``fmin_cg``, by specifying ``method='CG'``. + + Notes + ----- + This conjugate gradient algorithm is based on that of Polak and Ribiere + [1]_. + + Conjugate gradient methods tend to work better when: + + 1. `f` has a unique global minimizing point, and no local minima or + other stationary points, + 2. `f` is, at least locally, reasonably well approximated by a + quadratic function of the variables, + 3. `f` is continuous and has a continuous gradient, + 4. `fprime` is not too large, e.g., has a norm less than 1000, + 5. The initial guess, `x0`, is reasonably close to `f` 's global + minimizing point, `xopt`. + + Parameters `c1` and `c2` must satisfy ``0 < c1 < c2 < 1``. + + References + ---------- + .. [1] Wright & Nocedal, "Numerical Optimization", 1999, pp. 120-122. + + Examples + -------- + Example 1: seek the minimum value of the expression + ``a*u**2 + b*u*v + c*v**2 + d*u + e*v + f`` for given values + of the parameters and an initial guess ``(u, v) = (0, 0)``. + + >>> import numpy as np + >>> args = (2, 3, 7, 8, 9, 10) # parameter values + >>> def f(x, *args): + ... u, v = x + ... a, b, c, d, e, f = args + ... return a*u**2 + b*u*v + c*v**2 + d*u + e*v + f + >>> def gradf(x, *args): + ... u, v = x + ... a, b, c, d, e, f = args + ... gu = 2*a*u + b*v + d # u-component of the gradient + ... gv = b*u + 2*c*v + e # v-component of the gradient + ... return np.asarray((gu, gv)) + >>> x0 = np.asarray((0, 0)) # Initial guess. + >>> from scipy import optimize + >>> res1 = optimize.fmin_cg(f, x0, fprime=gradf, args=args) + Optimization terminated successfully. + Current function value: 1.617021 + Iterations: 4 + Function evaluations: 8 + Gradient evaluations: 8 + >>> res1 + array([-1.80851064, -0.25531915]) + + Example 2: solve the same problem using the `minimize` function. + (This `myopts` dictionary shows all of the available options, + although in practice only non-default values would be needed. + The returned value will be a dictionary.) + + >>> opts = {'maxiter' : None, # default value. + ... 'disp' : True, # non-default value. + ... 'gtol' : 1e-5, # default value. + ... 'norm' : np.inf, # default value. + ... 'eps' : 1.4901161193847656e-08} # default value. + >>> res2 = optimize.minimize(f, x0, jac=gradf, args=args, + ... method='CG', options=opts) + Optimization terminated successfully. + Current function value: 1.617021 + Iterations: 4 + Function evaluations: 8 + Gradient evaluations: 8 + >>> res2.x # minimum found + array([-1.80851064, -0.25531915]) + + """ + opts = {'gtol': gtol, + 'norm': norm, + 'eps': epsilon, + 'disp': disp, + 'maxiter': maxiter, + 'return_all': retall} + + callback = _wrap_callback(callback) + res = _minimize_cg(f, x0, args, fprime, callback=callback, c1=c1, c2=c2, + **opts) + + if full_output: + retlist = res['x'], res['fun'], res['nfev'], res['njev'], res['status'] + if retall: + retlist += (res['allvecs'], ) + return retlist + else: + if retall: + return res['x'], res['allvecs'] + else: + return res['x'] + + +def _minimize_cg(fun, x0, args=(), jac=None, callback=None, + gtol=1e-5, norm=np.inf, eps=_epsilon, maxiter=None, + disp=False, return_all=False, finite_diff_rel_step=None, + c1=1e-4, c2=0.4, **unknown_options): + """ + Minimization of scalar function of one or more variables using the + conjugate gradient algorithm. + + Options + ------- + disp : bool + Set to True to print convergence messages. + maxiter : int + Maximum number of iterations to perform. + gtol : float + Gradient norm must be less than `gtol` before successful + termination. + norm : float + Order of norm (Inf is max, -Inf is min). + eps : float or ndarray + If `jac is None` the absolute step size used for numerical + approximation of the jacobian via forward differences. + return_all : bool, optional + Set to True to return a list of the best solution at each of the + iterations. + finite_diff_rel_step : None or array_like, optional + If ``jac in ['2-point', '3-point', 'cs']`` the relative step size to + use for numerical approximation of the jacobian. The absolute step + size is computed as ``h = rel_step * sign(x) * max(1, abs(x))``, + possibly adjusted to fit into the bounds. For ``jac='3-point'`` + the sign of `h` is ignored. If None (default) then step is selected + automatically. + c1 : float, default: 1e-4 + Parameter for Armijo condition rule. + c2 : float, default: 0.4 + Parameter for curvature condition rule. + + Notes + ----- + Parameters `c1` and `c2` must satisfy ``0 < c1 < c2 < 1``. + """ + _check_unknown_options(unknown_options) + + retall = return_all + + x0 = asarray(x0).flatten() + if maxiter is None: + maxiter = len(x0) * 200 + + sf = _prepare_scalar_function(fun, x0, jac=jac, args=args, epsilon=eps, + finite_diff_rel_step=finite_diff_rel_step) + + f = sf.fun + myfprime = sf.grad + + old_fval = f(x0) + gfk = myfprime(x0) + + k = 0 + xk = x0 + # Sets the initial step guess to dx ~ 1 + old_old_fval = old_fval + np.linalg.norm(gfk) / 2 + + if retall: + allvecs = [xk] + warnflag = 0 + pk = -gfk + gnorm = vecnorm(gfk, ord=norm) + + sigma_3 = 0.01 + + while (gnorm > gtol) and (k < maxiter): + deltak = np.dot(gfk, gfk) + + cached_step = [None] + + def polak_ribiere_powell_step(alpha, gfkp1=None): + xkp1 = xk + alpha * pk + if gfkp1 is None: + gfkp1 = myfprime(xkp1) + yk = gfkp1 - gfk + beta_k = max(0, np.dot(yk, gfkp1) / deltak) + pkp1 = -gfkp1 + beta_k * pk + gnorm = vecnorm(gfkp1, ord=norm) + return (alpha, xkp1, pkp1, gfkp1, gnorm) + + def descent_condition(alpha, xkp1, fp1, gfkp1): + # Polak-Ribiere+ needs an explicit check of a sufficient + # descent condition, which is not guaranteed by strong Wolfe. + # + # See Gilbert & Nocedal, "Global convergence properties of + # conjugate gradient methods for optimization", + # SIAM J. Optimization 2, 21 (1992). + cached_step[:] = polak_ribiere_powell_step(alpha, gfkp1) + alpha, xk, pk, gfk, gnorm = cached_step + + # Accept step if it leads to convergence. + if gnorm <= gtol: + return True + + # Accept step if sufficient descent condition applies. + return np.dot(pk, gfk) <= -sigma_3 * np.dot(gfk, gfk) + + try: + alpha_k, fc, gc, old_fval, old_old_fval, gfkp1 = \ + _line_search_wolfe12(f, myfprime, xk, pk, gfk, old_fval, + old_old_fval, c1=c1, c2=c2, amin=1e-100, + amax=1e100, extra_condition=descent_condition) + except _LineSearchError: + # Line search failed to find a better solution. + warnflag = 2 + break + + # Reuse already computed results if possible + if alpha_k == cached_step[0]: + alpha_k, xk, pk, gfk, gnorm = cached_step + else: + alpha_k, xk, pk, gfk, gnorm = polak_ribiere_powell_step(alpha_k, gfkp1) + + if retall: + allvecs.append(xk) + k += 1 + intermediate_result = OptimizeResult(x=xk, fun=old_fval) + if _call_callback_maybe_halt(callback, intermediate_result): + break + + fval = old_fval + if warnflag == 2: + msg = _status_message['pr_loss'] + elif k >= maxiter: + warnflag = 1 + msg = _status_message['maxiter'] + elif np.isnan(gnorm) or np.isnan(fval) or np.isnan(xk).any(): + warnflag = 3 + msg = _status_message['nan'] + else: + msg = _status_message['success'] + + if disp: + _print_success_message_or_warn(warnflag, msg) + print(f" Current function value: {fval:f}") + print(" Iterations: %d" % k) + print(" Function evaluations: %d" % sf.nfev) + print(" Gradient evaluations: %d" % sf.ngev) + + result = OptimizeResult(fun=fval, jac=gfk, nfev=sf.nfev, + njev=sf.ngev, status=warnflag, + success=(warnflag == 0), message=msg, x=xk, + nit=k) + if retall: + result['allvecs'] = allvecs + return result + + +def fmin_ncg(f, x0, fprime, fhess_p=None, fhess=None, args=(), avextol=1e-5, + epsilon=_epsilon, maxiter=None, full_output=0, disp=1, retall=0, + callback=None, c1=1e-4, c2=0.9): + """ + Unconstrained minimization of a function using the Newton-CG method. + + Parameters + ---------- + f : callable ``f(x, *args)`` + Objective function to be minimized. + x0 : ndarray + Initial guess. + fprime : callable ``f'(x, *args)`` + Gradient of f. + fhess_p : callable ``fhess_p(x, p, *args)``, optional + Function which computes the Hessian of f times an + arbitrary vector, p. + fhess : callable ``fhess(x, *args)``, optional + Function to compute the Hessian matrix of f. + args : tuple, optional + Extra arguments passed to f, fprime, fhess_p, and fhess + (the same set of extra arguments is supplied to all of + these functions). + epsilon : float or ndarray, optional + If fhess is approximated, use this value for the step size. + callback : callable, optional + An optional user-supplied function which is called after + each iteration. Called as callback(xk), where xk is the + current parameter vector. + avextol : float, optional + Convergence is assumed when the average relative error in + the minimizer falls below this amount. + maxiter : int, optional + Maximum number of iterations to perform. + full_output : bool, optional + If True, return the optional outputs. + disp : bool, optional + If True, print convergence message. + retall : bool, optional + If True, return a list of results at each iteration. + c1 : float, default: 1e-4 + Parameter for Armijo condition rule. + c2 : float, default: 0.9 + Parameter for curvature condition rule + + Returns + ------- + xopt : ndarray + Parameters which minimize f, i.e., ``f(xopt) == fopt``. + fopt : float + Value of the function at xopt, i.e., ``fopt = f(xopt)``. + fcalls : int + Number of function calls made. + gcalls : int + Number of gradient calls made. + hcalls : int + Number of Hessian calls made. + warnflag : int + Warnings generated by the algorithm. + 1 : Maximum number of iterations exceeded. + 2 : Line search failure (precision loss). + 3 : NaN result encountered. + allvecs : list + The result at each iteration, if retall is True (see below). + + See also + -------- + minimize: Interface to minimization algorithms for multivariate + functions. See the 'Newton-CG' `method` in particular. + + Notes + ----- + Only one of `fhess_p` or `fhess` need to be given. If `fhess` + is provided, then `fhess_p` will be ignored. If neither `fhess` + nor `fhess_p` is provided, then the hessian product will be + approximated using finite differences on `fprime`. `fhess_p` + must compute the hessian times an arbitrary vector. If it is not + given, finite-differences on `fprime` are used to compute + it. + + Newton-CG methods are also called truncated Newton methods. This + function differs from scipy.optimize.fmin_tnc because + + 1. scipy.optimize.fmin_ncg is written purely in Python using NumPy + and scipy while scipy.optimize.fmin_tnc calls a C function. + 2. scipy.optimize.fmin_ncg is only for unconstrained minimization + while scipy.optimize.fmin_tnc is for unconstrained minimization + or box constrained minimization. (Box constraints give + lower and upper bounds for each variable separately.) + + Parameters `c1` and `c2` must satisfy ``0 < c1 < c2 < 1``. + + References + ---------- + Wright & Nocedal, 'Numerical Optimization', 1999, p. 140. + + """ + opts = {'xtol': avextol, + 'eps': epsilon, + 'maxiter': maxiter, + 'disp': disp, + 'return_all': retall} + + callback = _wrap_callback(callback) + res = _minimize_newtoncg(f, x0, args, fprime, fhess, fhess_p, + callback=callback, c1=c1, c2=c2, **opts) + + if full_output: + retlist = (res['x'], res['fun'], res['nfev'], res['njev'], + res['nhev'], res['status']) + if retall: + retlist += (res['allvecs'], ) + return retlist + else: + if retall: + return res['x'], res['allvecs'] + else: + return res['x'] + + +def _minimize_newtoncg(fun, x0, args=(), jac=None, hess=None, hessp=None, + callback=None, xtol=1e-5, eps=_epsilon, maxiter=None, + disp=False, return_all=False, c1=1e-4, c2=0.9, + **unknown_options): + """ + Minimization of scalar function of one or more variables using the + Newton-CG algorithm. + + Note that the `jac` parameter (Jacobian) is required. + + Options + ------- + disp : bool + Set to True to print convergence messages. + xtol : float + Average relative error in solution `xopt` acceptable for + convergence. + maxiter : int + Maximum number of iterations to perform. + eps : float or ndarray + If `hessp` is approximated, use this value for the step size. + return_all : bool, optional + Set to True to return a list of the best solution at each of the + iterations. + c1 : float, default: 1e-4 + Parameter for Armijo condition rule. + c2 : float, default: 0.9 + Parameter for curvature condition rule. + + Notes + ----- + Parameters `c1` and `c2` must satisfy ``0 < c1 < c2 < 1``. + """ + _check_unknown_options(unknown_options) + if jac is None: + raise ValueError('Jacobian is required for Newton-CG method') + fhess_p = hessp + fhess = hess + avextol = xtol + epsilon = eps + retall = return_all + + x0 = asarray(x0).flatten() + # TODO: add hessp (callable or FD) to ScalarFunction? + sf = _prepare_scalar_function( + fun, x0, jac, args=args, epsilon=eps, hess=hess + ) + f = sf.fun + fprime = sf.grad + _h = sf.hess(x0) + + # Logic for hess/hessp + # - If a callable(hess) is provided, then use that + # - If hess is a FD_METHOD, or the output from hess(x) is a LinearOperator + # then create a hessp function using those. + # - If hess is None but you have callable(hessp) then use the hessp. + # - If hess and hessp are None then approximate hessp using the grad/jac. + + if (hess in FD_METHODS or isinstance(_h, LinearOperator)): + fhess = None + + def _hessp(x, p, *args): + return sf.hess(x).dot(p) + + fhess_p = _hessp + + def terminate(warnflag, msg): + if disp: + _print_success_message_or_warn(warnflag, msg) + print(f" Current function value: {old_fval:f}") + print(" Iterations: %d" % k) + print(" Function evaluations: %d" % sf.nfev) + print(" Gradient evaluations: %d" % sf.ngev) + print(" Hessian evaluations: %d" % hcalls) + fval = old_fval + result = OptimizeResult(fun=fval, jac=gfk, nfev=sf.nfev, + njev=sf.ngev, nhev=hcalls, status=warnflag, + success=(warnflag == 0), message=msg, x=xk, + nit=k) + if retall: + result['allvecs'] = allvecs + return result + + hcalls = 0 + if maxiter is None: + maxiter = len(x0)*200 + cg_maxiter = 20*len(x0) + + xtol = len(x0) * avextol + # Make sure we enter the while loop. + update_l1norm = np.finfo(float).max + xk = np.copy(x0) + if retall: + allvecs = [xk] + k = 0 + gfk = None + old_fval = f(x0) + old_old_fval = None + float64eps = np.finfo(np.float64).eps + while update_l1norm > xtol: + if k >= maxiter: + msg = "Warning: " + _status_message['maxiter'] + return terminate(1, msg) + # Compute a search direction pk by applying the CG method to + # del2 f(xk) p = - grad f(xk) starting from 0. + b = -fprime(xk) + maggrad = np.linalg.norm(b, ord=1) + eta = min(0.5, math.sqrt(maggrad)) + termcond = eta * maggrad + xsupi = zeros(len(x0), dtype=x0.dtype) + ri = -b + psupi = -ri + i = 0 + dri0 = np.dot(ri, ri) + + if fhess is not None: # you want to compute hessian once. + A = sf.hess(xk) + hcalls += 1 + + for k2 in range(cg_maxiter): + if np.add.reduce(np.abs(ri)) <= termcond: + break + if fhess is None: + if fhess_p is None: + Ap = approx_fhess_p(xk, psupi, fprime, epsilon) + else: + Ap = fhess_p(xk, psupi, *args) + hcalls += 1 + else: + # hess was supplied as a callable or hessian update strategy, so + # A is a dense numpy array or sparse matrix + Ap = A.dot(psupi) + # check curvature + Ap = asarray(Ap).squeeze() # get rid of matrices... + curv = np.dot(psupi, Ap) + if 0 <= curv <= 3 * float64eps: + break + elif curv < 0: + if (i > 0): + break + else: + # fall back to steepest descent direction + xsupi = dri0 / (-curv) * b + break + alphai = dri0 / curv + xsupi += alphai * psupi + ri += alphai * Ap + dri1 = np.dot(ri, ri) + betai = dri1 / dri0 + psupi = -ri + betai * psupi + i += 1 + dri0 = dri1 # update np.dot(ri,ri) for next time. + else: + # curvature keeps increasing, bail out + msg = ("Warning: CG iterations didn't converge. The Hessian is not " + "positive definite.") + return terminate(3, msg) + + pk = xsupi # search direction is solution to system. + gfk = -b # gradient at xk + + try: + alphak, fc, gc, old_fval, old_old_fval, gfkp1 = \ + _line_search_wolfe12(f, fprime, xk, pk, gfk, + old_fval, old_old_fval, c1=c1, c2=c2) + except _LineSearchError: + # Line search failed to find a better solution. + msg = "Warning: " + _status_message['pr_loss'] + return terminate(2, msg) + + update = alphak * pk + xk += update # upcast if necessary + if retall: + allvecs.append(xk) + k += 1 + intermediate_result = OptimizeResult(x=xk, fun=old_fval) + if _call_callback_maybe_halt(callback, intermediate_result): + return terminate(5, "") + update_l1norm = np.linalg.norm(update, ord=1) + + else: + if np.isnan(old_fval) or np.isnan(update_l1norm): + return terminate(3, _status_message['nan']) + + msg = _status_message['success'] + return terminate(0, msg) + + +def fminbound(func, x1, x2, args=(), xtol=1e-5, maxfun=500, + full_output=0, disp=1): + """Bounded minimization for scalar functions. + + Parameters + ---------- + func : callable f(x,*args) + Objective function to be minimized (must accept and return scalars). + x1, x2 : float or array scalar + Finite optimization bounds. + args : tuple, optional + Extra arguments passed to function. + xtol : float, optional + The convergence tolerance. + maxfun : int, optional + Maximum number of function evaluations allowed. + full_output : bool, optional + If True, return optional outputs. + disp: int, optional + If non-zero, print messages. + + ``0`` : no message printing. + + ``1`` : non-convergence notification messages only. + + ``2`` : print a message on convergence too. + + ``3`` : print iteration results. + + Returns + ------- + xopt : ndarray + Parameters (over given interval) which minimize the + objective function. + fval : number + (Optional output) The function value evaluated at the minimizer. + ierr : int + (Optional output) An error flag (0 if converged, 1 if maximum number of + function calls reached). + numfunc : int + (Optional output) The number of function calls made. + + See also + -------- + minimize_scalar: Interface to minimization algorithms for scalar + univariate functions. See the 'Bounded' `method` in particular. + + Notes + ----- + Finds a local minimizer of the scalar function `func` in the + interval x1 < xopt < x2 using Brent's method. (See `brent` + for auto-bracketing.) + + References + ---------- + .. [1] Forsythe, G.E., M. A. Malcolm, and C. B. Moler. "Computer Methods + for Mathematical Computations." Prentice-Hall Series in Automatic + Computation 259 (1977). + .. [2] Brent, Richard P. Algorithms for Minimization Without Derivatives. + Courier Corporation, 2013. + + Examples + -------- + `fminbound` finds the minimizer of the function in the given range. + The following examples illustrate this. + + >>> from scipy import optimize + >>> def f(x): + ... return (x-1)**2 + >>> minimizer = optimize.fminbound(f, -4, 4) + >>> minimizer + 1.0 + >>> minimum = f(minimizer) + >>> minimum + 0.0 + >>> res = optimize.fminbound(f, 3, 4, full_output=True) + >>> minimizer, fval, ierr, numfunc = res + >>> minimizer + 3.000005960860986 + >>> minimum = f(minimizer) + >>> minimum, fval + (4.000023843479476, 4.000023843479476) + """ + options = {'xatol': xtol, + 'maxiter': maxfun, + 'disp': disp} + + res = _minimize_scalar_bounded(func, (x1, x2), args, **options) + if full_output: + return res['x'], res['fun'], res['status'], res['nfev'] + else: + return res['x'] + + +def _minimize_scalar_bounded(func, bounds, args=(), + xatol=1e-5, maxiter=500, disp=0, + **unknown_options): + """ + Options + ------- + maxiter : int + Maximum number of iterations to perform. + disp: int, optional + If non-zero, print messages. + + ``0`` : no message printing. + + ``1`` : non-convergence notification messages only. + + ``2`` : print a message on convergence too. + + ``3`` : print iteration results. + + xatol : float + Absolute error in solution `xopt` acceptable for convergence. + + """ + _check_unknown_options(unknown_options) + maxfun = maxiter + # Test bounds are of correct form + if len(bounds) != 2: + raise ValueError('bounds must have two elements.') + x1, x2 = bounds + + if not (is_finite_scalar(x1) and is_finite_scalar(x2)): + raise ValueError("Optimization bounds must be finite scalars.") + + if x1 > x2: + raise ValueError("The lower bound exceeds the upper bound.") + + flag = 0 + header = ' Func-count x f(x) Procedure' + step = ' initial' + + sqrt_eps = sqrt(2.2e-16) + golden_mean = 0.5 * (3.0 - sqrt(5.0)) + a, b = x1, x2 + fulc = a + golden_mean * (b - a) + nfc, xf = fulc, fulc + rat = e = 0.0 + x = xf + fx = func(x, *args) + num = 1 + fmin_data = (1, xf, fx) + fu = np.inf + + ffulc = fnfc = fx + xm = 0.5 * (a + b) + tol1 = sqrt_eps * np.abs(xf) + xatol / 3.0 + tol2 = 2.0 * tol1 + + if disp > 2: + print(" ") + print(header) + print("%5.0f %12.6g %12.6g %s" % (fmin_data + (step,))) + + while (np.abs(xf - xm) > (tol2 - 0.5 * (b - a))): + golden = 1 + # Check for parabolic fit + if np.abs(e) > tol1: + golden = 0 + r = (xf - nfc) * (fx - ffulc) + q = (xf - fulc) * (fx - fnfc) + p = (xf - fulc) * q - (xf - nfc) * r + q = 2.0 * (q - r) + if q > 0.0: + p = -p + q = np.abs(q) + r = e + e = rat + + # Check for acceptability of parabola + if ((np.abs(p) < np.abs(0.5*q*r)) and (p > q*(a - xf)) and + (p < q * (b - xf))): + rat = (p + 0.0) / q + x = xf + rat + step = ' parabolic' + + if ((x - a) < tol2) or ((b - x) < tol2): + si = np.sign(xm - xf) + ((xm - xf) == 0) + rat = tol1 * si + else: # do a golden-section step + golden = 1 + + if golden: # do a golden-section step + if xf >= xm: + e = a - xf + else: + e = b - xf + rat = golden_mean*e + step = ' golden' + + si = np.sign(rat) + (rat == 0) + x = xf + si * np.maximum(np.abs(rat), tol1) + fu = func(x, *args) + num += 1 + fmin_data = (num, x, fu) + if disp > 2: + print("%5.0f %12.6g %12.6g %s" % (fmin_data + (step,))) + + if fu <= fx: + if x >= xf: + a = xf + else: + b = xf + fulc, ffulc = nfc, fnfc + nfc, fnfc = xf, fx + xf, fx = x, fu + else: + if x < xf: + a = x + else: + b = x + if (fu <= fnfc) or (nfc == xf): + fulc, ffulc = nfc, fnfc + nfc, fnfc = x, fu + elif (fu <= ffulc) or (fulc == xf) or (fulc == nfc): + fulc, ffulc = x, fu + + xm = 0.5 * (a + b) + tol1 = sqrt_eps * np.abs(xf) + xatol / 3.0 + tol2 = 2.0 * tol1 + + if num >= maxfun: + flag = 1 + break + + if np.isnan(xf) or np.isnan(fx) or np.isnan(fu): + flag = 2 + + fval = fx + if disp > 0: + _endprint(x, flag, fval, maxfun, xatol, disp) + + result = OptimizeResult(fun=fval, status=flag, success=(flag == 0), + message={0: 'Solution found.', + 1: 'Maximum number of function calls ' + 'reached.', + 2: _status_message['nan']}.get(flag, ''), + x=xf, nfev=num, nit=num) + + return result + + +class Brent: + #need to rethink design of __init__ + def __init__(self, func, args=(), tol=1.48e-8, maxiter=500, + full_output=0, disp=0): + self.func = func + self.args = args + self.tol = tol + self.maxiter = maxiter + self._mintol = 1.0e-11 + self._cg = 0.3819660 + self.xmin = None + self.fval = None + self.iter = 0 + self.funcalls = 0 + self.disp = disp + + # need to rethink design of set_bracket (new options, etc.) + def set_bracket(self, brack=None): + self.brack = brack + + def get_bracket_info(self): + #set up + func = self.func + args = self.args + brack = self.brack + ### BEGIN core bracket_info code ### + ### carefully DOCUMENT any CHANGES in core ## + if brack is None: + xa, xb, xc, fa, fb, fc, funcalls = bracket(func, args=args) + elif len(brack) == 2: + xa, xb, xc, fa, fb, fc, funcalls = bracket(func, xa=brack[0], + xb=brack[1], args=args) + elif len(brack) == 3: + xa, xb, xc = brack + if (xa > xc): # swap so xa < xc can be assumed + xc, xa = xa, xc + if not ((xa < xb) and (xb < xc)): + raise ValueError( + "Bracketing values (xa, xb, xc) do not" + " fulfill this requirement: (xa < xb) and (xb < xc)" + ) + fa = func(*((xa,) + args)) + fb = func(*((xb,) + args)) + fc = func(*((xc,) + args)) + if not ((fb < fa) and (fb < fc)): + raise ValueError( + "Bracketing values (xa, xb, xc) do not fulfill" + " this requirement: (f(xb) < f(xa)) and (f(xb) < f(xc))" + ) + + funcalls = 3 + else: + raise ValueError("Bracketing interval must be " + "length 2 or 3 sequence.") + ### END core bracket_info code ### + + return xa, xb, xc, fa, fb, fc, funcalls + + def optimize(self): + # set up for optimization + func = self.func + xa, xb, xc, fa, fb, fc, funcalls = self.get_bracket_info() + _mintol = self._mintol + _cg = self._cg + ################################# + #BEGIN CORE ALGORITHM + ################################# + x = w = v = xb + fw = fv = fx = fb + if (xa < xc): + a = xa + b = xc + else: + a = xc + b = xa + deltax = 0.0 + iter = 0 + + if self.disp > 2: + print(" ") + print(f"{'Func-count':^12} {'x':^12} {'f(x)': ^12}") + print(f"{funcalls:^12g} {x:^12.6g} {fx:^12.6g}") + + while (iter < self.maxiter): + tol1 = self.tol * np.abs(x) + _mintol + tol2 = 2.0 * tol1 + xmid = 0.5 * (a + b) + # check for convergence + if np.abs(x - xmid) < (tol2 - 0.5 * (b - a)): + break + # XXX In the first iteration, rat is only bound in the true case + # of this conditional. This used to cause an UnboundLocalError + # (gh-4140). It should be set before the if (but to what?). + if (np.abs(deltax) <= tol1): + if (x >= xmid): + deltax = a - x # do a golden section step + else: + deltax = b - x + rat = _cg * deltax + else: # do a parabolic step + tmp1 = (x - w) * (fx - fv) + tmp2 = (x - v) * (fx - fw) + p = (x - v) * tmp2 - (x - w) * tmp1 + tmp2 = 2.0 * (tmp2 - tmp1) + if (tmp2 > 0.0): + p = -p + tmp2 = np.abs(tmp2) + dx_temp = deltax + deltax = rat + # check parabolic fit + if ((p > tmp2 * (a - x)) and (p < tmp2 * (b - x)) and + (np.abs(p) < np.abs(0.5 * tmp2 * dx_temp))): + rat = p * 1.0 / tmp2 # if parabolic step is useful. + u = x + rat + if ((u - a) < tol2 or (b - u) < tol2): + if xmid - x >= 0: + rat = tol1 + else: + rat = -tol1 + else: + if (x >= xmid): + deltax = a - x # if it's not do a golden section step + else: + deltax = b - x + rat = _cg * deltax + + if (np.abs(rat) < tol1): # update by at least tol1 + if rat >= 0: + u = x + tol1 + else: + u = x - tol1 + else: + u = x + rat + fu = func(*((u,) + self.args)) # calculate new output value + funcalls += 1 + + if (fu > fx): # if it's bigger than current + if (u < x): + a = u + else: + b = u + if (fu <= fw) or (w == x): + v = w + w = u + fv = fw + fw = fu + elif (fu <= fv) or (v == x) or (v == w): + v = u + fv = fu + else: + if (u >= x): + a = x + else: + b = x + v = w + w = x + x = u + fv = fw + fw = fx + fx = fu + + if self.disp > 2: + print(f"{funcalls:^12g} {x:^12.6g} {fx:^12.6g}") + + iter += 1 + ################################# + #END CORE ALGORITHM + ################################# + + self.xmin = x + self.fval = fx + self.iter = iter + self.funcalls = funcalls + + def get_result(self, full_output=False): + if full_output: + return self.xmin, self.fval, self.iter, self.funcalls + else: + return self.xmin + + +def brent(func, args=(), brack=None, tol=1.48e-8, full_output=0, maxiter=500): + """ + Given a function of one variable and a possible bracket, return + a local minimizer of the function isolated to a fractional precision + of tol. + + Parameters + ---------- + func : callable f(x,*args) + Objective function. + args : tuple, optional + Additional arguments (if present). + brack : tuple, optional + Either a triple ``(xa, xb, xc)`` satisfying ``xa < xb < xc`` and + ``func(xb) < func(xa) and func(xb) < func(xc)``, or a pair + ``(xa, xb)`` to be used as initial points for a downhill bracket search + (see `scipy.optimize.bracket`). + The minimizer ``x`` will not necessarily satisfy ``xa <= x <= xb``. + tol : float, optional + Relative error in solution `xopt` acceptable for convergence. + full_output : bool, optional + If True, return all output args (xmin, fval, iter, + funcalls). + maxiter : int, optional + Maximum number of iterations in solution. + + Returns + ------- + xmin : ndarray + Optimum point. + fval : float + (Optional output) Optimum function value. + iter : int + (Optional output) Number of iterations. + funcalls : int + (Optional output) Number of objective function evaluations made. + + See also + -------- + minimize_scalar: Interface to minimization algorithms for scalar + univariate functions. See the 'Brent' `method` in particular. + + Notes + ----- + Uses inverse parabolic interpolation when possible to speed up + convergence of golden section method. + + Does not ensure that the minimum lies in the range specified by + `brack`. See `scipy.optimize.fminbound`. + + Examples + -------- + We illustrate the behaviour of the function when `brack` is of + size 2 and 3 respectively. In the case where `brack` is of the + form ``(xa, xb)``, we can see for the given values, the output does + not necessarily lie in the range ``(xa, xb)``. + + >>> def f(x): + ... return (x-1)**2 + + >>> from scipy import optimize + + >>> minimizer = optimize.brent(f, brack=(1, 2)) + >>> minimizer + 1 + >>> res = optimize.brent(f, brack=(-1, 0.5, 2), full_output=True) + >>> xmin, fval, iter, funcalls = res + >>> f(xmin), fval + (0.0, 0.0) + + """ + options = {'xtol': tol, + 'maxiter': maxiter} + res = _minimize_scalar_brent(func, brack, args, **options) + if full_output: + return res['x'], res['fun'], res['nit'], res['nfev'] + else: + return res['x'] + + +def _minimize_scalar_brent(func, brack=None, args=(), xtol=1.48e-8, + maxiter=500, disp=0, + **unknown_options): + """ + Options + ------- + maxiter : int + Maximum number of iterations to perform. + xtol : float + Relative error in solution `xopt` acceptable for convergence. + disp : int, optional + If non-zero, print messages. + + ``0`` : no message printing. + + ``1`` : non-convergence notification messages only. + + ``2`` : print a message on convergence too. + + ``3`` : print iteration results. + + Notes + ----- + Uses inverse parabolic interpolation when possible to speed up + convergence of golden section method. + + """ + _check_unknown_options(unknown_options) + tol = xtol + if tol < 0: + raise ValueError(f'tolerance should be >= 0, got {tol!r}') + + brent = Brent(func=func, args=args, tol=tol, + full_output=True, maxiter=maxiter, disp=disp) + brent.set_bracket(brack) + brent.optimize() + x, fval, nit, nfev = brent.get_result(full_output=True) + + success = nit < maxiter and not (np.isnan(x) or np.isnan(fval)) + + if success: + message = ("\nOptimization terminated successfully;\n" + "The returned value satisfies the termination criteria\n" + f"(using xtol = {xtol} )") + else: + if nit >= maxiter: + message = "\nMaximum number of iterations exceeded" + if np.isnan(x) or np.isnan(fval): + message = f"{_status_message['nan']}" + + if disp: + _print_success_message_or_warn(not success, message) + + return OptimizeResult(fun=fval, x=x, nit=nit, nfev=nfev, + success=success, message=message) + + +def golden(func, args=(), brack=None, tol=_epsilon, + full_output=0, maxiter=5000): + """ + Return the minimizer of a function of one variable using the golden section + method. + + Given a function of one variable and a possible bracketing interval, + return a minimizer of the function isolated to a fractional precision of + tol. + + Parameters + ---------- + func : callable func(x,*args) + Objective function to minimize. + args : tuple, optional + Additional arguments (if present), passed to func. + brack : tuple, optional + Either a triple ``(xa, xb, xc)`` where ``xa < xb < xc`` and + ``func(xb) < func(xa) and func(xb) < func(xc)``, or a pair (xa, xb) + to be used as initial points for a downhill bracket search (see + `scipy.optimize.bracket`). + The minimizer ``x`` will not necessarily satisfy ``xa <= x <= xb``. + tol : float, optional + x tolerance stop criterion + full_output : bool, optional + If True, return optional outputs. + maxiter : int + Maximum number of iterations to perform. + + Returns + ------- + xmin : ndarray + Optimum point. + fval : float + (Optional output) Optimum function value. + funcalls : int + (Optional output) Number of objective function evaluations made. + + See also + -------- + minimize_scalar: Interface to minimization algorithms for scalar + univariate functions. See the 'Golden' `method` in particular. + + Notes + ----- + Uses analog of bisection method to decrease the bracketed + interval. + + Examples + -------- + We illustrate the behaviour of the function when `brack` is of + size 2 and 3, respectively. In the case where `brack` is of the + form (xa,xb), we can see for the given values, the output need + not necessarily lie in the range ``(xa, xb)``. + + >>> def f(x): + ... return (x-1)**2 + + >>> from scipy import optimize + + >>> minimizer = optimize.golden(f, brack=(1, 2)) + >>> minimizer + 1 + >>> res = optimize.golden(f, brack=(-1, 0.5, 2), full_output=True) + >>> xmin, fval, funcalls = res + >>> f(xmin), fval + (9.925165290385052e-18, 9.925165290385052e-18) + + """ + options = {'xtol': tol, 'maxiter': maxiter} + res = _minimize_scalar_golden(func, brack, args, **options) + if full_output: + return res['x'], res['fun'], res['nfev'] + else: + return res['x'] + + +def _minimize_scalar_golden(func, brack=None, args=(), + xtol=_epsilon, maxiter=5000, disp=0, + **unknown_options): + """ + Options + ------- + xtol : float + Relative error in solution `xopt` acceptable for convergence. + maxiter : int + Maximum number of iterations to perform. + disp: int, optional + If non-zero, print messages. + + ``0`` : no message printing. + + ``1`` : non-convergence notification messages only. + + ``2`` : print a message on convergence too. + + ``3`` : print iteration results. + """ + _check_unknown_options(unknown_options) + tol = xtol + if brack is None: + xa, xb, xc, fa, fb, fc, funcalls = bracket(func, args=args) + elif len(brack) == 2: + xa, xb, xc, fa, fb, fc, funcalls = bracket(func, xa=brack[0], + xb=brack[1], args=args) + elif len(brack) == 3: + xa, xb, xc = brack + if (xa > xc): # swap so xa < xc can be assumed + xc, xa = xa, xc + if not ((xa < xb) and (xb < xc)): + raise ValueError( + "Bracketing values (xa, xb, xc) do not" + " fulfill this requirement: (xa < xb) and (xb < xc)" + ) + fa = func(*((xa,) + args)) + fb = func(*((xb,) + args)) + fc = func(*((xc,) + args)) + if not ((fb < fa) and (fb < fc)): + raise ValueError( + "Bracketing values (xa, xb, xc) do not fulfill" + " this requirement: (f(xb) < f(xa)) and (f(xb) < f(xc))" + ) + funcalls = 3 + else: + raise ValueError("Bracketing interval must be length 2 or 3 sequence.") + + _gR = 0.61803399 # golden ratio conjugate: 2.0/(1.0+sqrt(5.0)) + _gC = 1.0 - _gR + x3 = xc + x0 = xa + if (np.abs(xc - xb) > np.abs(xb - xa)): + x1 = xb + x2 = xb + _gC * (xc - xb) + else: + x2 = xb + x1 = xb - _gC * (xb - xa) + f1 = func(*((x1,) + args)) + f2 = func(*((x2,) + args)) + funcalls += 2 + nit = 0 + + if disp > 2: + print(" ") + print(f"{'Func-count':^12} {'x':^12} {'f(x)': ^12}") + + for i in range(maxiter): + if np.abs(x3 - x0) <= tol * (np.abs(x1) + np.abs(x2)): + break + if (f2 < f1): + x0 = x1 + x1 = x2 + x2 = _gR * x1 + _gC * x3 + f1 = f2 + f2 = func(*((x2,) + args)) + else: + x3 = x2 + x2 = x1 + x1 = _gR * x2 + _gC * x0 + f2 = f1 + f1 = func(*((x1,) + args)) + funcalls += 1 + if disp > 2: + if (f1 < f2): + xmin, fval = x1, f1 + else: + xmin, fval = x2, f2 + print(f"{funcalls:^12g} {xmin:^12.6g} {fval:^12.6g}") + + nit += 1 + # end of iteration loop + + if (f1 < f2): + xmin = x1 + fval = f1 + else: + xmin = x2 + fval = f2 + + success = nit < maxiter and not (np.isnan(fval) or np.isnan(xmin)) + + if success: + message = ("\nOptimization terminated successfully;\n" + "The returned value satisfies the termination criteria\n" + f"(using xtol = {xtol} )") + else: + if nit >= maxiter: + message = "\nMaximum number of iterations exceeded" + if np.isnan(xmin) or np.isnan(fval): + message = f"{_status_message['nan']}" + + if disp: + _print_success_message_or_warn(not success, message) + + return OptimizeResult(fun=fval, nfev=funcalls, x=xmin, nit=nit, + success=success, message=message) + + +def bracket(func, xa=0.0, xb=1.0, args=(), grow_limit=110.0, maxiter=1000): + """ + Bracket the minimum of a function. + + Given a function and distinct initial points, search in the + downhill direction (as defined by the initial points) and return + three points that bracket the minimum of the function. + + Parameters + ---------- + func : callable f(x,*args) + Objective function to minimize. + xa, xb : float, optional + Initial points. Defaults `xa` to 0.0, and `xb` to 1.0. + A local minimum need not be contained within this interval. + args : tuple, optional + Additional arguments (if present), passed to `func`. + grow_limit : float, optional + Maximum grow limit. Defaults to 110.0 + maxiter : int, optional + Maximum number of iterations to perform. Defaults to 1000. + + Returns + ------- + xa, xb, xc : float + Final points of the bracket. + fa, fb, fc : float + Objective function values at the bracket points. + funcalls : int + Number of function evaluations made. + + Raises + ------ + BracketError + If no valid bracket is found before the algorithm terminates. + See notes for conditions of a valid bracket. + + Notes + ----- + The algorithm attempts to find three strictly ordered points (i.e. + :math:`x_a < x_b < x_c` or :math:`x_c < x_b < x_a`) satisfying + :math:`f(x_b) ≤ f(x_a)` and :math:`f(x_b) ≤ f(x_c)`, where one of the + inequalities must be satisfied strictly and all :math:`x_i` must be + finite. + + Examples + -------- + This function can find a downward convex region of a function: + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.optimize import bracket + >>> def f(x): + ... return 10*x**2 + 3*x + 5 + >>> x = np.linspace(-2, 2) + >>> y = f(x) + >>> init_xa, init_xb = 0.1, 1 + >>> xa, xb, xc, fa, fb, fc, funcalls = bracket(f, xa=init_xa, xb=init_xb) + >>> plt.axvline(x=init_xa, color="k", linestyle="--") + >>> plt.axvline(x=init_xb, color="k", linestyle="--") + >>> plt.plot(x, y, "-k") + >>> plt.plot(xa, fa, "bx") + >>> plt.plot(xb, fb, "rx") + >>> plt.plot(xc, fc, "bx") + >>> plt.show() + + Note that both initial points were to the right of the minimum, and the + third point was found in the "downhill" direction: the direction + in which the function appeared to be decreasing (to the left). + The final points are strictly ordered, and the function value + at the middle point is less than the function values at the endpoints; + it follows that a minimum must lie within the bracket. + + """ + _gold = 1.618034 # golden ratio: (1.0+sqrt(5.0))/2.0 + _verysmall_num = 1e-21 + # convert to numpy floats if not already + xa, xb = np.asarray([xa, xb]) + fa = func(*(xa,) + args) + fb = func(*(xb,) + args) + if (fa < fb): # Switch so fa > fb + xa, xb = xb, xa + fa, fb = fb, fa + xc = xb + _gold * (xb - xa) + fc = func(*((xc,) + args)) + funcalls = 3 + iter = 0 + while (fc < fb): + tmp1 = (xb - xa) * (fb - fc) + tmp2 = (xb - xc) * (fb - fa) + val = tmp2 - tmp1 + if np.abs(val) < _verysmall_num: + denom = 2.0 * _verysmall_num + else: + denom = 2.0 * val + w = xb - ((xb - xc) * tmp2 - (xb - xa) * tmp1) / denom + wlim = xb + grow_limit * (xc - xb) + msg = ("No valid bracket was found before the iteration limit was " + "reached. Consider trying different initial points or " + "increasing `maxiter`.") + if iter > maxiter: + raise RuntimeError(msg) + iter += 1 + if (w - xc) * (xb - w) > 0.0: + fw = func(*((w,) + args)) + funcalls += 1 + if (fw < fc): + xa = xb + xb = w + fa = fb + fb = fw + break + elif (fw > fb): + xc = w + fc = fw + break + w = xc + _gold * (xc - xb) + fw = func(*((w,) + args)) + funcalls += 1 + elif (w - wlim)*(wlim - xc) >= 0.0: + w = wlim + fw = func(*((w,) + args)) + funcalls += 1 + elif (w - wlim)*(xc - w) > 0.0: + fw = func(*((w,) + args)) + funcalls += 1 + if (fw < fc): + xb = xc + xc = w + w = xc + _gold * (xc - xb) + fb = fc + fc = fw + fw = func(*((w,) + args)) + funcalls += 1 + else: + w = xc + _gold * (xc - xb) + fw = func(*((w,) + args)) + funcalls += 1 + xa = xb + xb = xc + xc = w + fa = fb + fb = fc + fc = fw + + # three conditions for a valid bracket + cond1 = (fb < fc and fb <= fa) or (fb < fa and fb <= fc) + cond2 = (xa < xb < xc or xc < xb < xa) + cond3 = np.isfinite(xa) and np.isfinite(xb) and np.isfinite(xc) + msg = ("The algorithm terminated without finding a valid bracket. " + "Consider trying different initial points.") + if not (cond1 and cond2 and cond3): + e = BracketError(msg) + e.data = (xa, xb, xc, fa, fb, fc, funcalls) + raise e + + return xa, xb, xc, fa, fb, fc, funcalls + + +class BracketError(RuntimeError): + pass + + +def _recover_from_bracket_error(solver, fun, bracket, args, **options): + # `bracket` was originally written without checking whether the resulting + # bracket is valid. `brent` and `golden` built on top of it without + # checking the returned bracket for validity, and their output can be + # incorrect without warning/error if the original bracket is invalid. + # gh-14858 noticed the problem, and the following is the desired + # behavior: + # - `scipy.optimize.bracket`, `scipy.optimize.brent`, and + # `scipy.optimize.golden` should raise an error if the bracket is + # invalid, as opposed to silently returning garbage + # - `scipy.optimize.minimize_scalar` should return with `success=False` + # and other information + # The changes that would be required to achieve this the traditional + # way (`return`ing all the required information from bracket all the way + # up to `minimizer_scalar`) are extensive and invasive. (See a6aa40d.) + # We can achieve the same thing by raising the error in `bracket`, but + # storing the information needed by `minimize_scalar` in the error object, + # and intercepting it here. + try: + res = solver(fun, bracket, args, **options) + except BracketError as e: + msg = str(e) + xa, xb, xc, fa, fb, fc, funcalls = e.data + xs, fs = [xa, xb, xc], [fa, fb, fc] + if np.any(np.isnan([xs, fs])): + x, fun = np.nan, np.nan + else: + imin = np.argmin(fs) + x, fun = xs[imin], fs[imin] + return OptimizeResult(fun=fun, nfev=funcalls, x=x, + nit=0, success=False, message=msg) + return res + + +def _line_for_search(x0, alpha, lower_bound, upper_bound): + """ + Given a parameter vector ``x0`` with length ``n`` and a direction + vector ``alpha`` with length ``n``, and lower and upper bounds on + each of the ``n`` parameters, what are the bounds on a scalar + ``l`` such that ``lower_bound <= x0 + alpha * l <= upper_bound``. + + + Parameters + ---------- + x0 : np.array. + The vector representing the current location. + Note ``np.shape(x0) == (n,)``. + alpha : np.array. + The vector representing the direction. + Note ``np.shape(alpha) == (n,)``. + lower_bound : np.array. + The lower bounds for each parameter in ``x0``. If the ``i``th + parameter in ``x0`` is unbounded below, then ``lower_bound[i]`` + should be ``-np.inf``. + Note ``np.shape(lower_bound) == (n,)``. + upper_bound : np.array. + The upper bounds for each parameter in ``x0``. If the ``i``th + parameter in ``x0`` is unbounded above, then ``upper_bound[i]`` + should be ``np.inf``. + Note ``np.shape(upper_bound) == (n,)``. + + Returns + ------- + res : tuple ``(lmin, lmax)`` + The bounds for ``l`` such that + ``lower_bound[i] <= x0[i] + alpha[i] * l <= upper_bound[i]`` + for all ``i``. + + """ + # get nonzero indices of alpha so we don't get any zero division errors. + # alpha will not be all zero, since it is called from _linesearch_powell + # where we have a check for this. + nonzero, = alpha.nonzero() + lower_bound, upper_bound = lower_bound[nonzero], upper_bound[nonzero] + x0, alpha = x0[nonzero], alpha[nonzero] + low = (lower_bound - x0) / alpha + high = (upper_bound - x0) / alpha + + # positive and negative indices + pos = alpha > 0 + + lmin_pos = np.where(pos, low, 0) + lmin_neg = np.where(pos, 0, high) + lmax_pos = np.where(pos, high, 0) + lmax_neg = np.where(pos, 0, low) + + lmin = np.max(lmin_pos + lmin_neg) + lmax = np.min(lmax_pos + lmax_neg) + + # if x0 is outside the bounds, then it is possible that there is + # no way to get back in the bounds for the parameters being updated + # with the current direction alpha. + # when this happens, lmax < lmin. + # If this is the case, then we can just return (0, 0) + return (lmin, lmax) if lmax >= lmin else (0, 0) + + +def _linesearch_powell(func, p, xi, tol=1e-3, + lower_bound=None, upper_bound=None, fval=None): + """Line-search algorithm using fminbound. + + Find the minimum of the function ``func(x0 + alpha*direc)``. + + lower_bound : np.array. + The lower bounds for each parameter in ``x0``. If the ``i``th + parameter in ``x0`` is unbounded below, then ``lower_bound[i]`` + should be ``-np.inf``. + Note ``np.shape(lower_bound) == (n,)``. + upper_bound : np.array. + The upper bounds for each parameter in ``x0``. If the ``i``th + parameter in ``x0`` is unbounded above, then ``upper_bound[i]`` + should be ``np.inf``. + Note ``np.shape(upper_bound) == (n,)``. + fval : number. + ``fval`` is equal to ``func(p)``, the idea is just to avoid + recomputing it so we can limit the ``fevals``. + + """ + def myfunc(alpha): + return func(p + alpha*xi) + + # if xi is zero, then don't optimize + if not np.any(xi): + return ((fval, p, xi) if fval is not None else (func(p), p, xi)) + elif lower_bound is None and upper_bound is None: + # non-bounded minimization + res = _recover_from_bracket_error(_minimize_scalar_brent, + myfunc, None, tuple(), xtol=tol) + alpha_min, fret = res.x, res.fun + xi = alpha_min * xi + return fret, p + xi, xi + else: + bound = _line_for_search(p, xi, lower_bound, upper_bound) + if np.isneginf(bound[0]) and np.isposinf(bound[1]): + # equivalent to unbounded + return _linesearch_powell(func, p, xi, fval=fval, tol=tol) + elif not np.isneginf(bound[0]) and not np.isposinf(bound[1]): + # we can use a bounded scalar minimization + res = _minimize_scalar_bounded(myfunc, bound, xatol=tol / 100) + xi = res.x * xi + return res.fun, p + xi, xi + else: + # only bounded on one side. use the tangent function to convert + # the infinity bound to a finite bound. The new bounded region + # is a subregion of the region bounded by -np.pi/2 and np.pi/2. + bound = np.arctan(bound[0]), np.arctan(bound[1]) + res = _minimize_scalar_bounded( + lambda x: myfunc(np.tan(x)), + bound, + xatol=tol / 100) + xi = np.tan(res.x) * xi + return res.fun, p + xi, xi + + +def fmin_powell(func, x0, args=(), xtol=1e-4, ftol=1e-4, maxiter=None, + maxfun=None, full_output=0, disp=1, retall=0, callback=None, + direc=None): + """ + Minimize a function using modified Powell's method. + + This method only uses function values, not derivatives. + + Parameters + ---------- + func : callable f(x,*args) + Objective function to be minimized. + x0 : ndarray + Initial guess. + args : tuple, optional + Extra arguments passed to func. + xtol : float, optional + Line-search error tolerance. + ftol : float, optional + Relative error in ``func(xopt)`` acceptable for convergence. + maxiter : int, optional + Maximum number of iterations to perform. + maxfun : int, optional + Maximum number of function evaluations to make. + full_output : bool, optional + If True, ``fopt``, ``xi``, ``direc``, ``iter``, ``funcalls``, and + ``warnflag`` are returned. + disp : bool, optional + If True, print convergence messages. + retall : bool, optional + If True, return a list of the solution at each iteration. + callback : callable, optional + An optional user-supplied function, called after each + iteration. Called as ``callback(xk)``, where ``xk`` is the + current parameter vector. + direc : ndarray, optional + Initial fitting step and parameter order set as an (N, N) array, where N + is the number of fitting parameters in `x0`. Defaults to step size 1.0 + fitting all parameters simultaneously (``np.eye((N, N))``). To + prevent initial consideration of values in a step or to change initial + step size, set to 0 or desired step size in the Jth position in the Mth + block, where J is the position in `x0` and M is the desired evaluation + step, with steps being evaluated in index order. Step size and ordering + will change freely as minimization proceeds. + + Returns + ------- + xopt : ndarray + Parameter which minimizes `func`. + fopt : number + Value of function at minimum: ``fopt = func(xopt)``. + direc : ndarray + Current direction set. + iter : int + Number of iterations. + funcalls : int + Number of function calls made. + warnflag : int + Integer warning flag: + 1 : Maximum number of function evaluations. + 2 : Maximum number of iterations. + 3 : NaN result encountered. + 4 : The result is out of the provided bounds. + allvecs : list + List of solutions at each iteration. + + See also + -------- + minimize: Interface to unconstrained minimization algorithms for + multivariate functions. See the 'Powell' method in particular. + + Notes + ----- + Uses a modification of Powell's method to find the minimum of + a function of N variables. Powell's method is a conjugate + direction method. + + The algorithm has two loops. The outer loop merely iterates over the inner + loop. The inner loop minimizes over each current direction in the direction + set. At the end of the inner loop, if certain conditions are met, the + direction that gave the largest decrease is dropped and replaced with the + difference between the current estimated x and the estimated x from the + beginning of the inner-loop. + + The technical conditions for replacing the direction of greatest + increase amount to checking that + + 1. No further gain can be made along the direction of greatest increase + from that iteration. + 2. The direction of greatest increase accounted for a large sufficient + fraction of the decrease in the function value from that iteration of + the inner loop. + + References + ---------- + Powell M.J.D. (1964) An efficient method for finding the minimum of a + function of several variables without calculating derivatives, + Computer Journal, 7 (2):155-162. + + Press W., Teukolsky S.A., Vetterling W.T., and Flannery B.P.: + Numerical Recipes (any edition), Cambridge University Press + + Examples + -------- + >>> def f(x): + ... return x**2 + + >>> from scipy import optimize + + >>> minimum = optimize.fmin_powell(f, -1) + Optimization terminated successfully. + Current function value: 0.000000 + Iterations: 2 + Function evaluations: 16 + >>> minimum + array(0.0) + + """ + opts = {'xtol': xtol, + 'ftol': ftol, + 'maxiter': maxiter, + 'maxfev': maxfun, + 'disp': disp, + 'direc': direc, + 'return_all': retall} + + callback = _wrap_callback(callback) + res = _minimize_powell(func, x0, args, callback=callback, **opts) + + if full_output: + retlist = (res['x'], res['fun'], res['direc'], res['nit'], + res['nfev'], res['status']) + if retall: + retlist += (res['allvecs'], ) + return retlist + else: + if retall: + return res['x'], res['allvecs'] + else: + return res['x'] + + +def _minimize_powell(func, x0, args=(), callback=None, bounds=None, + xtol=1e-4, ftol=1e-4, maxiter=None, maxfev=None, + disp=False, direc=None, return_all=False, + **unknown_options): + """ + Minimization of scalar function of one or more variables using the + modified Powell algorithm. + + Parameters + ---------- + fun : callable + The objective function to be minimized:: + + fun(x, *args) -> float + + where ``x`` is a 1-D array with shape (n,) and ``args`` + is a tuple of the fixed parameters needed to completely + specify the function. + x0 : ndarray, shape (n,) + Initial guess. Array of real elements of size (n,), + where ``n`` is the number of independent variables. + args : tuple, optional + Extra arguments passed to the objective function and its + derivatives (`fun`, `jac` and `hess` functions). + method : str or callable, optional + The present documentation is specific to ``method='powell'``, but other + options are available. See documentation for `scipy.optimize.minimize`. + bounds : sequence or `Bounds`, optional + Bounds on decision variables. There are two ways to specify the bounds: + + 1. Instance of `Bounds` class. + 2. Sequence of ``(min, max)`` pairs for each element in `x`. None + is used to specify no bound. + + If bounds are not provided, then an unbounded line search will be used. + If bounds are provided and the initial guess is within the bounds, then + every function evaluation throughout the minimization procedure will be + within the bounds. If bounds are provided, the initial guess is outside + the bounds, and `direc` is full rank (or left to default), then some + function evaluations during the first iteration may be outside the + bounds, but every function evaluation after the first iteration will be + within the bounds. If `direc` is not full rank, then some parameters + may not be optimized and the solution is not guaranteed to be within + the bounds. + + options : dict, optional + A dictionary of solver options. All methods accept the following + generic options: + + maxiter : int + Maximum number of iterations to perform. Depending on the + method each iteration may use several function evaluations. + disp : bool + Set to True to print convergence messages. + + See method-specific options for ``method='powell'`` below. + callback : callable, optional + Called after each iteration. The signature is:: + + callback(xk) + + where ``xk`` is the current parameter vector. + + Returns + ------- + res : OptimizeResult + The optimization result represented as a ``OptimizeResult`` object. + Important attributes are: ``x`` the solution array, ``success`` a + Boolean flag indicating if the optimizer exited successfully and + ``message`` which describes the cause of the termination. See + `OptimizeResult` for a description of other attributes. + + Options + ------- + disp : bool + Set to True to print convergence messages. + xtol : float + Relative error in solution `xopt` acceptable for convergence. + ftol : float + Relative error in ``fun(xopt)`` acceptable for convergence. + maxiter, maxfev : int + Maximum allowed number of iterations and function evaluations. + Will default to ``N*1000``, where ``N`` is the number of + variables, if neither `maxiter` or `maxfev` is set. If both + `maxiter` and `maxfev` are set, minimization will stop at the + first reached. + direc : ndarray + Initial set of direction vectors for the Powell method. + return_all : bool, optional + Set to True to return a list of the best solution at each of the + iterations. + """ + _check_unknown_options(unknown_options) + maxfun = maxfev + retall = return_all + + x = asarray(x0).flatten() + if retall: + allvecs = [x] + N = len(x) + # If neither are set, then set both to default + if maxiter is None and maxfun is None: + maxiter = N * 1000 + maxfun = N * 1000 + elif maxiter is None: + # Convert remaining Nones, to np.inf, unless the other is np.inf, in + # which case use the default to avoid unbounded iteration + if maxfun == np.inf: + maxiter = N * 1000 + else: + maxiter = np.inf + elif maxfun is None: + if maxiter == np.inf: + maxfun = N * 1000 + else: + maxfun = np.inf + + # we need to use a mutable object here that we can update in the + # wrapper function + fcalls, func = _wrap_scalar_function_maxfun_validation(func, args, maxfun) + + if direc is None: + direc = eye(N, dtype=float) + else: + direc = asarray(direc, dtype=float) + if np.linalg.matrix_rank(direc) != direc.shape[0]: + warnings.warn("direc input is not full rank, some parameters may " + "not be optimized", + OptimizeWarning, stacklevel=3) + + if bounds is None: + # don't make these arrays of all +/- inf. because + # _linesearch_powell will do an unnecessary check of all the elements. + # just keep them None, _linesearch_powell will not have to check + # all the elements. + lower_bound, upper_bound = None, None + else: + # bounds is standardized in _minimize.py. + lower_bound, upper_bound = bounds.lb, bounds.ub + if np.any(lower_bound > x0) or np.any(x0 > upper_bound): + warnings.warn("Initial guess is not within the specified bounds", + OptimizeWarning, stacklevel=3) + + fval = func(x) + x1 = x.copy() + iter = 0 + while True: + try: + fx = fval + bigind = 0 + delta = 0.0 + for i in range(N): + direc1 = direc[i] + fx2 = fval + fval, x, direc1 = _linesearch_powell(func, x, direc1, + tol=xtol * 100, + lower_bound=lower_bound, + upper_bound=upper_bound, + fval=fval) + if (fx2 - fval) > delta: + delta = fx2 - fval + bigind = i + iter += 1 + if retall: + allvecs.append(x) + intermediate_result = OptimizeResult(x=x, fun=fval) + if _call_callback_maybe_halt(callback, intermediate_result): + break + bnd = ftol * (np.abs(fx) + np.abs(fval)) + 1e-20 + if 2.0 * (fx - fval) <= bnd: + break + if fcalls[0] >= maxfun: + break + if iter >= maxiter: + break + if np.isnan(fx) and np.isnan(fval): + # Ended up in a nan-region: bail out + break + + # Construct the extrapolated point + direc1 = x - x1 + x1 = x.copy() + # make sure that we don't go outside the bounds when extrapolating + if lower_bound is None and upper_bound is None: + lmax = 1 + else: + _, lmax = _line_for_search(x, direc1, lower_bound, upper_bound) + x2 = x + min(lmax, 1) * direc1 + fx2 = func(x2) + + if (fx > fx2): + t = 2.0*(fx + fx2 - 2.0*fval) + temp = (fx - fval - delta) + t *= temp*temp + temp = fx - fx2 + t -= delta*temp*temp + if t < 0.0: + fval, x, direc1 = _linesearch_powell( + func, x, direc1, + tol=xtol * 100, + lower_bound=lower_bound, + upper_bound=upper_bound, + fval=fval + ) + if np.any(direc1): + direc[bigind] = direc[-1] + direc[-1] = direc1 + except _MaxFuncCallError: + break + + warnflag = 0 + msg = _status_message['success'] + # out of bounds is more urgent than exceeding function evals or iters, + # but I don't want to cause inconsistencies by changing the + # established warning flags for maxfev and maxiter, so the out of bounds + # warning flag becomes 3, but is checked for first. + if bounds and (np.any(lower_bound > x) or np.any(x > upper_bound)): + warnflag = 4 + msg = _status_message['out_of_bounds'] + elif fcalls[0] >= maxfun: + warnflag = 1 + msg = _status_message['maxfev'] + elif iter >= maxiter: + warnflag = 2 + msg = _status_message['maxiter'] + elif np.isnan(fval) or np.isnan(x).any(): + warnflag = 3 + msg = _status_message['nan'] + + if disp: + _print_success_message_or_warn(warnflag, msg, RuntimeWarning) + print(f" Current function value: {fval:f}") + print(" Iterations: %d" % iter) + print(" Function evaluations: %d" % fcalls[0]) + result = OptimizeResult(fun=fval, direc=direc, nit=iter, nfev=fcalls[0], + status=warnflag, success=(warnflag == 0), + message=msg, x=x) + if retall: + result['allvecs'] = allvecs + return result + + +def _endprint(x, flag, fval, maxfun, xtol, disp): + if flag == 0: + if disp > 1: + print("\nOptimization terminated successfully;\n" + "The returned value satisfies the termination criteria\n" + "(using xtol = ", xtol, ")") + return + + if flag == 1: + msg = ("\nMaximum number of function evaluations exceeded --- " + "increase maxfun argument.\n") + elif flag == 2: + msg = f"\n{_status_message['nan']}" + + _print_success_message_or_warn(flag, msg) + return + + +def brute(func, ranges, args=(), Ns=20, full_output=0, finish=fmin, + disp=False, workers=1): + """Minimize a function over a given range by brute force. + + Uses the "brute force" method, i.e., computes the function's value + at each point of a multidimensional grid of points, to find the global + minimum of the function. + + The function is evaluated everywhere in the range with the datatype of the + first call to the function, as enforced by the ``vectorize`` NumPy + function. The value and type of the function evaluation returned when + ``full_output=True`` are affected in addition by the ``finish`` argument + (see Notes). + + The brute force approach is inefficient because the number of grid points + increases exponentially - the number of grid points to evaluate is + ``Ns ** len(x)``. Consequently, even with coarse grid spacing, even + moderately sized problems can take a long time to run, and/or run into + memory limitations. + + Parameters + ---------- + func : callable + The objective function to be minimized. Must be in the + form ``f(x, *args)``, where ``x`` is the argument in + the form of a 1-D array and ``args`` is a tuple of any + additional fixed parameters needed to completely specify + the function. + ranges : tuple + Each component of the `ranges` tuple must be either a + "slice object" or a range tuple of the form ``(low, high)``. + The program uses these to create the grid of points on which + the objective function will be computed. See `Note 2` for + more detail. + args : tuple, optional + Any additional fixed parameters needed to completely specify + the function. + Ns : int, optional + Number of grid points along the axes, if not otherwise + specified. See `Note2`. + full_output : bool, optional + If True, return the evaluation grid and the objective function's + values on it. + finish : callable, optional + An optimization function that is called with the result of brute force + minimization as initial guess. `finish` should take `func` and + the initial guess as positional arguments, and take `args` as + keyword arguments. It may additionally take `full_output` + and/or `disp` as keyword arguments. Use None if no "polishing" + function is to be used. See Notes for more details. + disp : bool, optional + Set to True to print convergence messages from the `finish` callable. + workers : int or map-like callable, optional + If `workers` is an int the grid is subdivided into `workers` + sections and evaluated in parallel (uses + `multiprocessing.Pool `). + Supply `-1` to use all cores available to the Process. + Alternatively supply a map-like callable, such as + `multiprocessing.Pool.map` for evaluating the grid in parallel. + This evaluation is carried out as ``workers(func, iterable)``. + Requires that `func` be pickleable. + + .. versionadded:: 1.3.0 + + Returns + ------- + x0 : ndarray + A 1-D array containing the coordinates of a point at which the + objective function had its minimum value. (See `Note 1` for + which point is returned.) + fval : float + Function value at the point `x0`. (Returned when `full_output` is + True.) + grid : tuple + Representation of the evaluation grid. It has the same + length as `x0`. (Returned when `full_output` is True.) + Jout : ndarray + Function values at each point of the evaluation + grid, i.e., ``Jout = func(*grid)``. (Returned + when `full_output` is True.) + + See Also + -------- + basinhopping, differential_evolution + + Notes + ----- + *Note 1*: The program finds the gridpoint at which the lowest value + of the objective function occurs. If `finish` is None, that is the + point returned. When the global minimum occurs within (or not very far + outside) the grid's boundaries, and the grid is fine enough, that + point will be in the neighborhood of the global minimum. + + However, users often employ some other optimization program to + "polish" the gridpoint values, i.e., to seek a more precise + (local) minimum near `brute's` best gridpoint. + The `brute` function's `finish` option provides a convenient way to do + that. Any polishing program used must take `brute's` output as its + initial guess as a positional argument, and take `brute's` input values + for `args` as keyword arguments, otherwise an error will be raised. + It may additionally take `full_output` and/or `disp` as keyword arguments. + + `brute` assumes that the `finish` function returns either an + `OptimizeResult` object or a tuple in the form: + ``(xmin, Jmin, ... , statuscode)``, where ``xmin`` is the minimizing + value of the argument, ``Jmin`` is the minimum value of the objective + function, "..." may be some other returned values (which are not used + by `brute`), and ``statuscode`` is the status code of the `finish` program. + + Note that when `finish` is not None, the values returned are those + of the `finish` program, *not* the gridpoint ones. Consequently, + while `brute` confines its search to the input grid points, + the `finish` program's results usually will not coincide with any + gridpoint, and may fall outside the grid's boundary. Thus, if a + minimum only needs to be found over the provided grid points, make + sure to pass in ``finish=None``. + + *Note 2*: The grid of points is a `numpy.mgrid` object. + For `brute` the `ranges` and `Ns` inputs have the following effect. + Each component of the `ranges` tuple can be either a slice object or a + two-tuple giving a range of values, such as (0, 5). If the component is a + slice object, `brute` uses it directly. If the component is a two-tuple + range, `brute` internally converts it to a slice object that interpolates + `Ns` points from its low-value to its high-value, inclusive. + + Examples + -------- + We illustrate the use of `brute` to seek the global minimum of a function + of two variables that is given as the sum of a positive-definite + quadratic and two deep "Gaussian-shaped" craters. Specifically, define + the objective function `f` as the sum of three other functions, + ``f = f1 + f2 + f3``. We suppose each of these has a signature + ``(z, *params)``, where ``z = (x, y)``, and ``params`` and the functions + are as defined below. + + >>> import numpy as np + >>> params = (2, 3, 7, 8, 9, 10, 44, -1, 2, 26, 1, -2, 0.5) + >>> def f1(z, *params): + ... x, y = z + ... a, b, c, d, e, f, g, h, i, j, k, l, scale = params + ... return (a * x**2 + b * x * y + c * y**2 + d*x + e*y + f) + + >>> def f2(z, *params): + ... x, y = z + ... a, b, c, d, e, f, g, h, i, j, k, l, scale = params + ... return (-g*np.exp(-((x-h)**2 + (y-i)**2) / scale)) + + >>> def f3(z, *params): + ... x, y = z + ... a, b, c, d, e, f, g, h, i, j, k, l, scale = params + ... return (-j*np.exp(-((x-k)**2 + (y-l)**2) / scale)) + + >>> def f(z, *params): + ... return f1(z, *params) + f2(z, *params) + f3(z, *params) + + Thus, the objective function may have local minima near the minimum + of each of the three functions of which it is composed. To + use `fmin` to polish its gridpoint result, we may then continue as + follows: + + >>> rranges = (slice(-4, 4, 0.25), slice(-4, 4, 0.25)) + >>> from scipy import optimize + >>> resbrute = optimize.brute(f, rranges, args=params, full_output=True, + ... finish=optimize.fmin) + >>> resbrute[0] # global minimum + array([-1.05665192, 1.80834843]) + >>> resbrute[1] # function value at global minimum + -3.4085818767 + + Note that if `finish` had been set to None, we would have gotten the + gridpoint [-1.0 1.75] where the rounded function value is -2.892. + + """ + N = len(ranges) + if N > 40: + raise ValueError("Brute Force not possible with more " + "than 40 variables.") + lrange = list(ranges) + for k in range(N): + if not isinstance(lrange[k], slice): + if len(lrange[k]) < 3: + lrange[k] = tuple(lrange[k]) + (complex(Ns),) + lrange[k] = slice(*lrange[k]) + if (N == 1): + lrange = lrange[0] + + grid = np.mgrid[lrange] + + # obtain an array of parameters that is iterable by a map-like callable + inpt_shape = grid.shape + if (N > 1): + grid = np.reshape(grid, (inpt_shape[0], np.prod(inpt_shape[1:]))).T + + if not np.iterable(args): + args = (args,) + + wrapped_func = _Brute_Wrapper(func, args) + + # iterate over input arrays, possibly in parallel + with MapWrapper(pool=workers) as mapper: + Jout = np.array(list(mapper(wrapped_func, grid))) + if (N == 1): + grid = (grid,) + Jout = np.squeeze(Jout) + elif (N > 1): + Jout = np.reshape(Jout, inpt_shape[1:]) + grid = np.reshape(grid.T, inpt_shape) + + Nshape = shape(Jout) + + indx = argmin(Jout.ravel(), axis=-1) + Nindx = np.empty(N, int) + xmin = np.empty(N, float) + for k in range(N - 1, -1, -1): + thisN = Nshape[k] + Nindx[k] = indx % Nshape[k] + indx = indx // thisN + for k in range(N): + xmin[k] = grid[k][tuple(Nindx)] + + Jmin = Jout[tuple(Nindx)] + if (N == 1): + grid = grid[0] + xmin = xmin[0] + + if callable(finish): + # set up kwargs for `finish` function + finish_args = _getfullargspec(finish).args + finish_kwargs = dict() + if 'full_output' in finish_args: + finish_kwargs['full_output'] = 1 + if 'disp' in finish_args: + finish_kwargs['disp'] = disp + elif 'options' in finish_args: + # pass 'disp' as `options` + # (e.g., if `finish` is `minimize`) + finish_kwargs['options'] = {'disp': disp} + + # run minimizer + res = finish(func, xmin, args=args, **finish_kwargs) + + if isinstance(res, OptimizeResult): + xmin = res.x + Jmin = res.fun + success = res.success + else: + xmin = res[0] + Jmin = res[1] + success = res[-1] == 0 + if not success: + if disp: + warnings.warn("Either final optimization did not succeed or `finish` " + "does not return `statuscode` as its last argument.", + RuntimeWarning, stacklevel=2) + + if full_output: + return xmin, Jmin, grid, Jout + else: + return xmin + + +class _Brute_Wrapper: + """ + Object to wrap user cost function for optimize.brute, allowing picklability + """ + + def __init__(self, f, args): + self.f = f + self.args = [] if args is None else args + + def __call__(self, x): + # flatten needed for one dimensional case. + return self.f(np.asarray(x).flatten(), *self.args) + + +def show_options(solver=None, method=None, disp=True): + """ + Show documentation for additional options of optimization solvers. + + These are method-specific options that can be supplied through the + ``options`` dict. + + Parameters + ---------- + solver : str + Type of optimization solver. One of 'minimize', 'minimize_scalar', + 'root', 'root_scalar', 'linprog', or 'quadratic_assignment'. + method : str, optional + If not given, shows all methods of the specified solver. Otherwise, + show only the options for the specified method. Valid values + corresponds to methods' names of respective solver (e.g., 'BFGS' for + 'minimize'). + disp : bool, optional + Whether to print the result rather than returning it. + + Returns + ------- + text + Either None (for disp=True) or the text string (disp=False) + + Notes + ----- + The solver-specific methods are: + + `scipy.optimize.minimize` + + - :ref:`Nelder-Mead ` + - :ref:`Powell ` + - :ref:`CG ` + - :ref:`BFGS ` + - :ref:`Newton-CG ` + - :ref:`L-BFGS-B ` + - :ref:`TNC ` + - :ref:`COBYLA ` + - :ref:`COBYQA ` + - :ref:`SLSQP ` + - :ref:`dogleg ` + - :ref:`trust-ncg ` + + `scipy.optimize.root` + + - :ref:`hybr ` + - :ref:`lm ` + - :ref:`broyden1 ` + - :ref:`broyden2 ` + - :ref:`anderson ` + - :ref:`linearmixing ` + - :ref:`diagbroyden ` + - :ref:`excitingmixing ` + - :ref:`krylov ` + - :ref:`df-sane ` + + `scipy.optimize.minimize_scalar` + + - :ref:`brent ` + - :ref:`golden ` + - :ref:`bounded ` + + `scipy.optimize.root_scalar` + + - :ref:`bisect ` + - :ref:`brentq ` + - :ref:`brenth ` + - :ref:`ridder ` + - :ref:`toms748 ` + - :ref:`newton ` + - :ref:`secant ` + - :ref:`halley ` + + `scipy.optimize.linprog` + + - :ref:`simplex ` + - :ref:`interior-point ` + - :ref:`revised simplex ` + - :ref:`highs ` + - :ref:`highs-ds ` + - :ref:`highs-ipm ` + + `scipy.optimize.quadratic_assignment` + + - :ref:`faq ` + - :ref:`2opt ` + + Examples + -------- + We can print documentations of a solver in stdout: + + >>> from scipy.optimize import show_options + >>> show_options(solver="minimize") + ... + + Specifying a method is possible: + + >>> show_options(solver="minimize", method="Nelder-Mead") + ... + + We can also get the documentations as a string: + + >>> show_options(solver="minimize", method="Nelder-Mead", disp=False) + Minimization of scalar function of one or more variables using the ... + + """ + import textwrap + + doc_routines = { + 'minimize': ( + ('bfgs', 'scipy.optimize._optimize._minimize_bfgs'), + ('cg', 'scipy.optimize._optimize._minimize_cg'), + ('cobyla', 'scipy.optimize._cobyla_py._minimize_cobyla'), + ('cobyqa', 'scipy.optimize._cobyqa_py._minimize_cobyqa'), + ('dogleg', 'scipy.optimize._trustregion_dogleg._minimize_dogleg'), + ('l-bfgs-b', 'scipy.optimize._lbfgsb_py._minimize_lbfgsb'), + ('nelder-mead', 'scipy.optimize._optimize._minimize_neldermead'), + ('newton-cg', 'scipy.optimize._optimize._minimize_newtoncg'), + ('powell', 'scipy.optimize._optimize._minimize_powell'), + ('slsqp', 'scipy.optimize._slsqp_py._minimize_slsqp'), + ('tnc', 'scipy.optimize._tnc._minimize_tnc'), + ('trust-ncg', + 'scipy.optimize._trustregion_ncg._minimize_trust_ncg'), + ('trust-constr', + 'scipy.optimize._trustregion_constr.' + '_minimize_trustregion_constr'), + ('trust-exact', + 'scipy.optimize._trustregion_exact._minimize_trustregion_exact'), + ('trust-krylov', + 'scipy.optimize._trustregion_krylov._minimize_trust_krylov'), + ), + 'root': ( + ('hybr', 'scipy.optimize._minpack_py._root_hybr'), + ('lm', 'scipy.optimize._root._root_leastsq'), + ('broyden1', 'scipy.optimize._root._root_broyden1_doc'), + ('broyden2', 'scipy.optimize._root._root_broyden2_doc'), + ('anderson', 'scipy.optimize._root._root_anderson_doc'), + ('diagbroyden', 'scipy.optimize._root._root_diagbroyden_doc'), + ('excitingmixing', 'scipy.optimize._root._root_excitingmixing_doc'), + ('linearmixing', 'scipy.optimize._root._root_linearmixing_doc'), + ('krylov', 'scipy.optimize._root._root_krylov_doc'), + ('df-sane', 'scipy.optimize._spectral._root_df_sane'), + ), + 'root_scalar': ( + ('bisect', 'scipy.optimize._root_scalar._root_scalar_bisect_doc'), + ('brentq', 'scipy.optimize._root_scalar._root_scalar_brentq_doc'), + ('brenth', 'scipy.optimize._root_scalar._root_scalar_brenth_doc'), + ('ridder', 'scipy.optimize._root_scalar._root_scalar_ridder_doc'), + ('toms748', 'scipy.optimize._root_scalar._root_scalar_toms748_doc'), + ('secant', 'scipy.optimize._root_scalar._root_scalar_secant_doc'), + ('newton', 'scipy.optimize._root_scalar._root_scalar_newton_doc'), + ('halley', 'scipy.optimize._root_scalar._root_scalar_halley_doc'), + ), + 'linprog': ( + ('simplex', 'scipy.optimize._linprog._linprog_simplex_doc'), + ('interior-point', 'scipy.optimize._linprog._linprog_ip_doc'), + ('revised simplex', 'scipy.optimize._linprog._linprog_rs_doc'), + ('highs-ipm', 'scipy.optimize._linprog._linprog_highs_ipm_doc'), + ('highs-ds', 'scipy.optimize._linprog._linprog_highs_ds_doc'), + ('highs', 'scipy.optimize._linprog._linprog_highs_doc'), + ), + 'quadratic_assignment': ( + ('faq', 'scipy.optimize._qap._quadratic_assignment_faq'), + ('2opt', 'scipy.optimize._qap._quadratic_assignment_2opt'), + ), + 'minimize_scalar': ( + ('brent', 'scipy.optimize._optimize._minimize_scalar_brent'), + ('bounded', 'scipy.optimize._optimize._minimize_scalar_bounded'), + ('golden', 'scipy.optimize._optimize._minimize_scalar_golden'), + ), + } + + if solver is None: + text = ["\n\n\n========\n", "minimize\n", "========\n"] + text.append(show_options('minimize', disp=False)) + text.extend(["\n\n===============\n", "minimize_scalar\n", + "===============\n"]) + text.append(show_options('minimize_scalar', disp=False)) + text.extend(["\n\n\n====\n", "root\n", + "====\n"]) + text.append(show_options('root', disp=False)) + text.extend(['\n\n\n=======\n', 'linprog\n', + '=======\n']) + text.append(show_options('linprog', disp=False)) + text = "".join(text) + else: + solver = solver.lower() + if solver not in doc_routines: + raise ValueError(f'Unknown solver {solver!r}') + + if method is None: + text = [] + for name, _ in doc_routines[solver]: + text.extend(["\n\n" + name, "\n" + "="*len(name) + "\n\n"]) + text.append(show_options(solver, name, disp=False)) + text = "".join(text) + else: + method = method.lower() + methods = dict(doc_routines[solver]) + if method not in methods: + raise ValueError(f"Unknown method {method!r}") + name = methods[method] + + # Import function object + parts = name.split('.') + mod_name = ".".join(parts[:-1]) + __import__(mod_name) + obj = getattr(sys.modules[mod_name], parts[-1]) + + # Get doc + doc = obj.__doc__ + if doc is not None: + text = textwrap.dedent(doc).strip() + else: + text = "" + + if disp: + print(text) + return + else: + return text diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_qap.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_qap.py new file mode 100644 index 0000000000000000000000000000000000000000..03fe3b128c066adb21406021ec2e34effbf65703 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_qap.py @@ -0,0 +1,760 @@ +import numpy as np +import operator +import warnings +import numbers +from . import (linear_sum_assignment, OptimizeResult) +from ._optimize import _check_unknown_options + +from scipy._lib._util import check_random_state +import itertools + +QUADRATIC_ASSIGNMENT_METHODS = ['faq', '2opt'] + + +def quadratic_assignment(A, B, method="faq", options=None): + r""" + Approximates solution to the quadratic assignment problem and + the graph matching problem. + + Quadratic assignment solves problems of the following form: + + .. math:: + + \min_P & \ {\ \text{trace}(A^T P B P^T)}\\ + \mbox{s.t. } & {P \ \epsilon \ \mathcal{P}}\\ + + where :math:`\mathcal{P}` is the set of all permutation matrices, + and :math:`A` and :math:`B` are square matrices. + + Graph matching tries to *maximize* the same objective function. + This algorithm can be thought of as finding the alignment of the + nodes of two graphs that minimizes the number of induced edge + disagreements, or, in the case of weighted graphs, the sum of squared + edge weight differences. + + Note that the quadratic assignment problem is NP-hard. The results given + here are approximations and are not guaranteed to be optimal. + + + Parameters + ---------- + A : 2-D array, square + The square matrix :math:`A` in the objective function above. + + B : 2-D array, square + The square matrix :math:`B` in the objective function above. + + method : str in {'faq', '2opt'} (default: 'faq') + The algorithm used to solve the problem. + :ref:`'faq' ` (default) and + :ref:`'2opt' ` are available. + + options : dict, optional + A dictionary of solver options. All solvers support the following: + + maximize : bool (default: False) + Maximizes the objective function if ``True``. + + partial_match : 2-D array of integers, optional (default: None) + Fixes part of the matching. Also known as a "seed" [2]_. + + Each row of `partial_match` specifies a pair of matched nodes: + node ``partial_match[i, 0]`` of `A` is matched to node + ``partial_match[i, 1]`` of `B`. The array has shape ``(m, 2)``, + where ``m`` is not greater than the number of nodes, :math:`n`. + + rng : `numpy.random.Generator`, optional + Pseudorandom number generator state. When `rng` is None, a new + `numpy.random.Generator` is created using entropy from the + operating system. Types other than `numpy.random.Generator` are + passed to `numpy.random.default_rng` to instantiate a ``Generator``. + + .. versionchanged:: 1.15.0 + As part of the `SPEC-007 `_ + transition from use of `numpy.random.RandomState` to + `numpy.random.Generator` is occurring. Supplying + `np.random.RandomState` to this function will now emit a + `DeprecationWarning`. In SciPy 1.17 its use will raise an exception. + In addition relying on global state using `np.random.seed` + will emit a `FutureWarning`. In SciPy 1.17 the global random number + generator will no longer be used. + Use of an int-like seed will raise a `FutureWarning`, in SciPy 1.17 it + will be normalized via `np.random.default_rng` rather than + `np.random.RandomState`. + + For method-specific options, see + :func:`show_options('quadratic_assignment') `. + + Returns + ------- + res : OptimizeResult + `OptimizeResult` containing the following fields. + + col_ind : 1-D array + Column indices corresponding to the best permutation found of the + nodes of `B`. + fun : float + The objective value of the solution. + nit : int + The number of iterations performed during optimization. + + Notes + ----- + The default method :ref:`'faq' ` uses the Fast + Approximate QAP algorithm [1]_; it typically offers the best combination of + speed and accuracy. + Method :ref:`'2opt' ` can be computationally expensive, + but may be a useful alternative, or it can be used to refine the solution + returned by another method. + + References + ---------- + .. [1] J.T. Vogelstein, J.M. Conroy, V. Lyzinski, L.J. Podrazik, + S.G. Kratzer, E.T. Harley, D.E. Fishkind, R.J. Vogelstein, and + C.E. Priebe, "Fast approximate quadratic programming for graph + matching," PLOS one, vol. 10, no. 4, p. e0121002, 2015, + :doi:`10.1371/journal.pone.0121002` + + .. [2] D. Fishkind, S. Adali, H. Patsolic, L. Meng, D. Singh, V. Lyzinski, + C. Priebe, "Seeded graph matching", Pattern Recognit. 87 (2019): + 203-215, :doi:`10.1016/j.patcog.2018.09.014` + + .. [3] "2-opt," Wikipedia. + https://en.wikipedia.org/wiki/2-opt + + Examples + -------- + >>> import numpy as np + >>> from scipy.optimize import quadratic_assignment + >>> rng = np.random.default_rng() + >>> A = np.array([[0, 80, 150, 170], [80, 0, 130, 100], + ... [150, 130, 0, 120], [170, 100, 120, 0]]) + >>> B = np.array([[0, 5, 2, 7], [0, 0, 3, 8], + ... [0, 0, 0, 3], [0, 0, 0, 0]]) + >>> res = quadratic_assignment(A, B, options={'rng': rng}) + >>> print(res) + fun: 3260 + col_ind: [0 3 2 1] + nit: 9 + + The see the relationship between the returned ``col_ind`` and ``fun``, + use ``col_ind`` to form the best permutation matrix found, then evaluate + the objective function :math:`f(P) = trace(A^T P B P^T )`. + + >>> perm = res['col_ind'] + >>> P = np.eye(len(A), dtype=int)[perm] + >>> fun = np.trace(A.T @ P @ B @ P.T) + >>> print(fun) + 3260 + + Alternatively, to avoid constructing the permutation matrix explicitly, + directly permute the rows and columns of the distance matrix. + + >>> fun = np.trace(A.T @ B[perm][:, perm]) + >>> print(fun) + 3260 + + Although not guaranteed in general, ``quadratic_assignment`` happens to + have found the globally optimal solution. + + >>> from itertools import permutations + >>> perm_opt, fun_opt = None, np.inf + >>> for perm in permutations([0, 1, 2, 3]): + ... perm = np.array(perm) + ... fun = np.trace(A.T @ B[perm][:, perm]) + ... if fun < fun_opt: + ... fun_opt, perm_opt = fun, perm + >>> print(np.array_equal(perm_opt, res['col_ind'])) + True + + Here is an example for which the default method, + :ref:`'faq' `, does not find the global optimum. + + >>> A = np.array([[0, 5, 8, 6], [5, 0, 5, 1], + ... [8, 5, 0, 2], [6, 1, 2, 0]]) + >>> B = np.array([[0, 1, 8, 4], [1, 0, 5, 2], + ... [8, 5, 0, 5], [4, 2, 5, 0]]) + >>> res = quadratic_assignment(A, B, options={'rng': rng}) + >>> print(res) + fun: 178 + col_ind: [1 0 3 2] + nit: 13 + + If accuracy is important, consider using :ref:`'2opt' ` + to refine the solution. + + >>> guess = np.array([np.arange(len(A)), res.col_ind]).T + >>> res = quadratic_assignment(A, B, method="2opt", + ... options = {'rng': rng, 'partial_guess': guess}) + >>> print(res) + fun: 176 + col_ind: [1 2 3 0] + nit: 17 + + """ + + if options is None: + options = {} + + method = method.lower() + methods = {"faq": _quadratic_assignment_faq, + "2opt": _quadratic_assignment_2opt} + if method not in methods: + raise ValueError(f"method {method} must be in {methods}.") + + _spec007_transition(options.get("rng", None)) + res = methods[method](A, B, **options) + return res + + +def _spec007_transition(rng): + if isinstance(rng, np.random.RandomState): + warnings.warn( + "Use of `RandomState` with `quadratic_assignment` is deprecated" + " and will result in an exception in SciPy 1.17", + DeprecationWarning, + stacklevel=2 + ) + if ((rng is None or rng is np.random) and + np.random.mtrand._rand._bit_generator._seed_seq is None): + warnings.warn( + "The NumPy global RNG was seeded by calling `np.random.seed`." + " From SciPy 1.17, this function will no longer use the global RNG.", + FutureWarning, + stacklevel=2 + ) + if isinstance(rng, numbers.Integral | np.integer): + warnings.warn( + "The behavior when the rng option is an integer is changing: the value" + " will be normalized using np.random.default_rng beginning in SciPy 1.17," + " and the resulting Generator will be used to generate random numbers.", + FutureWarning, + stacklevel=2 + ) + + +def _calc_score(A, B, perm): + # equivalent to objective function but avoids matmul + return np.sum(A * B[perm][:, perm]) + + +def _common_input_validation(A, B, partial_match): + A = np.atleast_2d(A) + B = np.atleast_2d(B) + + if partial_match is None: + partial_match = np.array([[], []]).T + partial_match = np.atleast_2d(partial_match).astype(int) + + msg = None + if A.shape[0] != A.shape[1]: + msg = "`A` must be square" + elif B.shape[0] != B.shape[1]: + msg = "`B` must be square" + elif A.ndim != 2 or B.ndim != 2: + msg = "`A` and `B` must have exactly two dimensions" + elif A.shape != B.shape: + msg = "`A` and `B` matrices must be of equal size" + elif partial_match.shape[0] > A.shape[0]: + msg = "`partial_match` can have only as many seeds as there are nodes" + elif partial_match.shape[1] != 2: + msg = "`partial_match` must have two columns" + elif partial_match.ndim != 2: + msg = "`partial_match` must have exactly two dimensions" + elif (partial_match < 0).any(): + msg = "`partial_match` must contain only positive indices" + elif (partial_match >= len(A)).any(): + msg = "`partial_match` entries must be less than number of nodes" + elif (not len(set(partial_match[:, 0])) == len(partial_match[:, 0]) or + not len(set(partial_match[:, 1])) == len(partial_match[:, 1])): + msg = "`partial_match` column entries must be unique" + + if msg is not None: + raise ValueError(msg) + + return A, B, partial_match + + +def _quadratic_assignment_faq(A, B, + maximize=False, partial_match=None, rng=None, + P0="barycenter", shuffle_input=False, maxiter=30, + tol=0.03, **unknown_options): + r"""Solve the quadratic assignment problem (approximately). + + This function solves the Quadratic Assignment Problem (QAP) and the + Graph Matching Problem (GMP) using the Fast Approximate QAP Algorithm + (FAQ) [1]_. + + Quadratic assignment solves problems of the following form: + + .. math:: + + \min_P & \ {\ \text{trace}(A^T P B P^T)}\\ + \mbox{s.t. } & {P \ \epsilon \ \mathcal{P}}\\ + + where :math:`\mathcal{P}` is the set of all permutation matrices, + and :math:`A` and :math:`B` are square matrices. + + Graph matching tries to *maximize* the same objective function. + This algorithm can be thought of as finding the alignment of the + nodes of two graphs that minimizes the number of induced edge + disagreements, or, in the case of weighted graphs, the sum of squared + edge weight differences. + + Note that the quadratic assignment problem is NP-hard. The results given + here are approximations and are not guaranteed to be optimal. + + Parameters + ---------- + A : 2-D array, square + The square matrix :math:`A` in the objective function above. + B : 2-D array, square + The square matrix :math:`B` in the objective function above. + method : str in {'faq', '2opt'} (default: 'faq') + The algorithm used to solve the problem. This is the method-specific + documentation for 'faq'. + :ref:`'2opt' ` is also available. + + Options + ------- + maximize : bool (default: False) + Maximizes the objective function if ``True``. + partial_match : 2-D array of integers, optional (default: None) + Fixes part of the matching. Also known as a "seed" [2]_. + + Each row of `partial_match` specifies a pair of matched nodes: + node ``partial_match[i, 0]`` of `A` is matched to node + ``partial_match[i, 1]`` of `B`. The array has shape ``(m, 2)``, where + ``m`` is not greater than the number of nodes, :math:`n`. + + rng : {None, int, `numpy.random.Generator`}, optional + Pseudorandom number generator state. See `quadratic_assignment` for details. + P0 : 2-D array, "barycenter", or "randomized" (default: "barycenter") + Initial position. Must be a doubly-stochastic matrix [3]_. + + If the initial position is an array, it must be a doubly stochastic + matrix of size :math:`m' \times m'` where :math:`m' = n - m`. + + If ``"barycenter"`` (default), the initial position is the barycenter + of the Birkhoff polytope (the space of doubly stochastic matrices). + This is a :math:`m' \times m'` matrix with all entries equal to + :math:`1 / m'`. + + If ``"randomized"`` the initial search position is + :math:`P_0 = (J + K) / 2`, where :math:`J` is the barycenter and + :math:`K` is a random doubly stochastic matrix. + shuffle_input : bool (default: False) + Set to `True` to resolve degenerate gradients randomly. For + non-degenerate gradients this option has no effect. + maxiter : int, positive (default: 30) + Integer specifying the max number of Frank-Wolfe iterations performed. + tol : float (default: 0.03) + Tolerance for termination. Frank-Wolfe iteration terminates when + :math:`\frac{||P_{i}-P_{i+1}||_F}{\sqrt{m'}} \leq tol`, + where :math:`i` is the iteration number. + + Returns + ------- + res : OptimizeResult + `OptimizeResult` containing the following fields. + + col_ind : 1-D array + Column indices corresponding to the best permutation found of the + nodes of `B`. + fun : float + The objective value of the solution. + nit : int + The number of Frank-Wolfe iterations performed. + + Notes + ----- + The algorithm may be sensitive to the initial permutation matrix (or + search "position") due to the possibility of several local minima + within the feasible region. A barycenter initialization is more likely to + result in a better solution than a single random initialization. However, + calling ``quadratic_assignment`` several times with different random + initializations may result in a better optimum at the cost of longer + total execution time. + + Examples + -------- + As mentioned above, a barycenter initialization often results in a better + solution than a single random initialization. + + >>> from scipy.optimize import quadratic_assignment + >>> import numpy as np + >>> rng = np.random.default_rng() + >>> n = 15 + >>> A = rng.random((n, n)) + >>> B = rng.random((n, n)) + >>> options = {"rng": rng} + >>> res = quadratic_assignment(A, B, options=options) # FAQ is default method + >>> print(res.fun) + 47.797048706380636 # may vary + + >>> options = {"rng": rng, "P0": "randomized"} # use randomized initialization + >>> res = quadratic_assignment(A, B, options=options) + >>> print(res.fun) + 47.37287069769966 # may vary + + However, consider running from several randomized initializations and + keeping the best result. + + >>> res = min([quadratic_assignment(A, B, options=options) + ... for i in range(30)], key=lambda x: x.fun) + >>> print(res.fun) + 46.55974835248574 # may vary + + The '2-opt' method can be used to attempt to refine the results. + + >>> options = {"partial_guess": np.array([np.arange(n), res.col_ind]).T, "rng": rng} + >>> res = quadratic_assignment(A, B, method="2opt", options=options) + >>> print(res.fun) + 46.55974835248574 # may vary + + References + ---------- + .. [1] J.T. Vogelstein, J.M. Conroy, V. Lyzinski, L.J. Podrazik, + S.G. Kratzer, E.T. Harley, D.E. Fishkind, R.J. Vogelstein, and + C.E. Priebe, "Fast approximate quadratic programming for graph + matching," PLOS one, vol. 10, no. 4, p. e0121002, 2015, + :doi:`10.1371/journal.pone.0121002` + + .. [2] D. Fishkind, S. Adali, H. Patsolic, L. Meng, D. Singh, V. Lyzinski, + C. Priebe, "Seeded graph matching", Pattern Recognit. 87 (2019): + 203-215, :doi:`10.1016/j.patcog.2018.09.014` + + .. [3] "Doubly stochastic Matrix," Wikipedia. + https://en.wikipedia.org/wiki/Doubly_stochastic_matrix + + """ + + _check_unknown_options(unknown_options) + + maxiter = operator.index(maxiter) + + # ValueError check + A, B, partial_match = _common_input_validation(A, B, partial_match) + + msg = None + if isinstance(P0, str) and P0 not in {'barycenter', 'randomized'}: + msg = "Invalid 'P0' parameter string" + elif maxiter <= 0: + msg = "'maxiter' must be a positive integer" + elif tol <= 0: + msg = "'tol' must be a positive float" + if msg is not None: + raise ValueError(msg) + + rng = check_random_state(rng) + n = len(A) # number of vertices in graphs + n_seeds = len(partial_match) # number of seeds + n_unseed = n - n_seeds + + # [1] Algorithm 1 Line 1 - choose initialization + if not isinstance(P0, str): + P0 = np.atleast_2d(P0) + if P0.shape != (n_unseed, n_unseed): + msg = "`P0` matrix must have shape m' x m', where m'=n-m" + elif ((P0 < 0).any() or not np.allclose(np.sum(P0, axis=0), 1) + or not np.allclose(np.sum(P0, axis=1), 1)): + msg = "`P0` matrix must be doubly stochastic" + if msg is not None: + raise ValueError(msg) + elif P0 == 'barycenter': + P0 = np.ones((n_unseed, n_unseed)) / n_unseed + elif P0 == 'randomized': + J = np.ones((n_unseed, n_unseed)) / n_unseed + # generate a nxn matrix where each entry is a random number [0, 1] + # would use rand, but Generators don't have it + # would use random, but old mtrand.RandomStates don't have it + K = _doubly_stochastic(rng.uniform(size=(n_unseed, n_unseed))) + P0 = (J + K) / 2 + + # check trivial cases + if n == 0 or n_seeds == n: + score = _calc_score(A, B, partial_match[:, 1]) + res = {"col_ind": partial_match[:, 1], "fun": score, "nit": 0} + return OptimizeResult(res) + + obj_func_scalar = 1 + if maximize: + obj_func_scalar = -1 + + nonseed_B = np.setdiff1d(range(n), partial_match[:, 1]) + if shuffle_input: + nonseed_B = rng.permutation(nonseed_B) + + nonseed_A = np.setdiff1d(range(n), partial_match[:, 0]) + perm_A = np.concatenate([partial_match[:, 0], nonseed_A]) + perm_B = np.concatenate([partial_match[:, 1], nonseed_B]) + + # definitions according to Seeded Graph Matching [2]. + A11, A12, A21, A22 = _split_matrix(A[perm_A][:, perm_A], n_seeds) + B11, B12, B21, B22 = _split_matrix(B[perm_B][:, perm_B], n_seeds) + const_sum = A21 @ B21.T + A12.T @ B12 + + P = P0 + # [1] Algorithm 1 Line 2 - loop while stopping criteria not met + for n_iter in range(1, maxiter+1): + # [1] Algorithm 1 Line 3 - compute the gradient of f(P) = -tr(APB^tP^t) + grad_fp = (const_sum + A22 @ P @ B22.T + A22.T @ P @ B22) + # [1] Algorithm 1 Line 4 - get direction Q by solving Eq. 8 + _, cols = linear_sum_assignment(grad_fp, maximize=maximize) + Q = np.eye(n_unseed)[cols] + + # [1] Algorithm 1 Line 5 - compute the step size + # Noting that e.g. trace(Ax) = trace(A)*x, expand and re-collect + # terms as ax**2 + bx + c. c does not affect location of minimum + # and can be ignored. Also, note that trace(A@B) = (A.T*B).sum(); + # apply where possible for efficiency. + R = P - Q + b21 = ((R.T @ A21) * B21).sum() + b12 = ((R.T @ A12.T) * B12.T).sum() + AR22 = A22.T @ R + BR22 = B22 @ R.T + b22a = (AR22 * B22.T[cols]).sum() + b22b = (A22 * BR22[cols]).sum() + a = (AR22.T * BR22).sum() + b = b21 + b12 + b22a + b22b + # critical point of ax^2 + bx + c is at x = -d/(2*e) + # if a * obj_func_scalar > 0, it is a minimum + # if minimum is not in [0, 1], only endpoints need to be considered + if a*obj_func_scalar > 0 and 0 <= -b/(2*a) <= 1: + alpha = -b/(2*a) + else: + alpha = np.argmin([0, (b + a)*obj_func_scalar]) + + # [1] Algorithm 1 Line 6 - Update P + P_i1 = alpha * P + (1 - alpha) * Q + if np.linalg.norm(P - P_i1) / np.sqrt(n_unseed) < tol: + P = P_i1 + break + P = P_i1 + # [1] Algorithm 1 Line 7 - end main loop + + # [1] Algorithm 1 Line 8 - project onto the set of permutation matrices + _, col = linear_sum_assignment(P, maximize=True) + perm = np.concatenate((np.arange(n_seeds), col + n_seeds)) + + unshuffled_perm = np.zeros(n, dtype=int) + unshuffled_perm[perm_A] = perm_B[perm] + + score = _calc_score(A, B, unshuffled_perm) + res = {"col_ind": unshuffled_perm, "fun": score, "nit": n_iter} + return OptimizeResult(res) + + +def _split_matrix(X, n): + # definitions according to Seeded Graph Matching [2]. + upper, lower = X[:n], X[n:] + return upper[:, :n], upper[:, n:], lower[:, :n], lower[:, n:] + + +def _doubly_stochastic(P, tol=1e-3): + # Adapted from @btaba implementation + # https://github.com/btaba/sinkhorn_knopp + # of Sinkhorn-Knopp algorithm + # https://projecteuclid.org/euclid.pjm/1102992505 + + max_iter = 1000 + c = 1 / P.sum(axis=0) + r = 1 / (P @ c) + P_eps = P + + for it in range(max_iter): + if ((np.abs(P_eps.sum(axis=1) - 1) < tol).all() and + (np.abs(P_eps.sum(axis=0) - 1) < tol).all()): + # All column/row sums ~= 1 within threshold + break + + c = 1 / (r @ P) + r = 1 / (P @ c) + P_eps = r[:, None] * P * c + + return P_eps + + +def _quadratic_assignment_2opt(A, B, maximize=False, rng=None, + partial_match=None, + partial_guess=None, + **unknown_options): + r"""Solve the quadratic assignment problem (approximately). + + This function solves the Quadratic Assignment Problem (QAP) and the + Graph Matching Problem (GMP) using the 2-opt algorithm [1]_. + + Quadratic assignment solves problems of the following form: + + .. math:: + + \min_P & \ {\ \text{trace}(A^T P B P^T)}\\ + \mbox{s.t. } & {P \ \epsilon \ \mathcal{P}}\\ + + where :math:`\mathcal{P}` is the set of all permutation matrices, + and :math:`A` and :math:`B` are square matrices. + + Graph matching tries to *maximize* the same objective function. + This algorithm can be thought of as finding the alignment of the + nodes of two graphs that minimizes the number of induced edge + disagreements, or, in the case of weighted graphs, the sum of squared + edge weight differences. + + Note that the quadratic assignment problem is NP-hard. The results given + here are approximations and are not guaranteed to be optimal. + + Parameters + ---------- + A : 2-D array, square + The square matrix :math:`A` in the objective function above. + B : 2-D array, square + The square matrix :math:`B` in the objective function above. + method : str in {'faq', '2opt'} (default: 'faq') + The algorithm used to solve the problem. This is the method-specific + documentation for '2opt'. + :ref:`'faq' ` is also available. + + Options + ------- + maximize : bool (default: False) + Maximizes the objective function if ``True``. + rng : {None, int, `numpy.random.Generator`}, optional + Pseudorandom number generator state. See `quadratic_assignment` for details. + partial_match : 2-D array of integers, optional (default: None) + Fixes part of the matching. Also known as a "seed" [2]_. + + Each row of `partial_match` specifies a pair of matched nodes: node + ``partial_match[i, 0]`` of `A` is matched to node + ``partial_match[i, 1]`` of `B`. The array has shape ``(m, 2)``, + where ``m`` is not greater than the number of nodes, :math:`n`. + + .. note:: + `partial_match` must be sorted by the first column. + + partial_guess : 2-D array of integers, optional (default: None) + A guess for the matching between the two matrices. Unlike + `partial_match`, `partial_guess` does not fix the indices; they are + still free to be optimized. + + Each row of `partial_guess` specifies a pair of matched nodes: node + ``partial_guess[i, 0]`` of `A` is matched to node + ``partial_guess[i, 1]`` of `B`. The array has shape ``(m, 2)``, + where ``m`` is not greater than the number of nodes, :math:`n`. + + .. note:: + `partial_guess` must be sorted by the first column. + + Returns + ------- + res : OptimizeResult + `OptimizeResult` containing the following fields. + + col_ind : 1-D array + Column indices corresponding to the best permutation found of the + nodes of `B`. + fun : float + The objective value of the solution. + nit : int + The number of iterations performed during optimization. + + Notes + ----- + This is a greedy algorithm that works similarly to bubble sort: beginning + with an initial permutation, it iteratively swaps pairs of indices to + improve the objective function until no such improvements are possible. + + References + ---------- + .. [1] "2-opt," Wikipedia. + https://en.wikipedia.org/wiki/2-opt + + .. [2] D. Fishkind, S. Adali, H. Patsolic, L. Meng, D. Singh, V. Lyzinski, + C. Priebe, "Seeded graph matching", Pattern Recognit. 87 (2019): + 203-215, https://doi.org/10.1016/j.patcog.2018.09.014 + + """ + _check_unknown_options(unknown_options) + rng = check_random_state(rng) + A, B, partial_match = _common_input_validation(A, B, partial_match) + + N = len(A) + # check trivial cases + if N == 0 or partial_match.shape[0] == N: + score = _calc_score(A, B, partial_match[:, 1]) + res = {"col_ind": partial_match[:, 1], "fun": score, "nit": 0} + return OptimizeResult(res) + + if partial_guess is None: + partial_guess = np.array([[], []]).T + partial_guess = np.atleast_2d(partial_guess).astype(int) + + msg = None + if partial_guess.shape[0] > A.shape[0]: + msg = ("`partial_guess` can have only as " + "many entries as there are nodes") + elif partial_guess.shape[1] != 2: + msg = "`partial_guess` must have two columns" + elif partial_guess.ndim != 2: + msg = "`partial_guess` must have exactly two dimensions" + elif (partial_guess < 0).any(): + msg = "`partial_guess` must contain only positive indices" + elif (partial_guess >= len(A)).any(): + msg = "`partial_guess` entries must be less than number of nodes" + elif (not len(set(partial_guess[:, 0])) == len(partial_guess[:, 0]) or + not len(set(partial_guess[:, 1])) == len(partial_guess[:, 1])): + msg = "`partial_guess` column entries must be unique" + if msg is not None: + raise ValueError(msg) + + fixed_rows = None + if partial_match.size or partial_guess.size: + # use partial_match and partial_guess for initial permutation, + # but randomly permute the rest. + guess_rows = np.zeros(N, dtype=bool) + guess_cols = np.zeros(N, dtype=bool) + fixed_rows = np.zeros(N, dtype=bool) + fixed_cols = np.zeros(N, dtype=bool) + perm = np.zeros(N, dtype=int) + + rg, cg = partial_guess.T + guess_rows[rg] = True + guess_cols[cg] = True + perm[guess_rows] = cg + + # match overrides guess + rf, cf = partial_match.T + fixed_rows[rf] = True + fixed_cols[cf] = True + perm[fixed_rows] = cf + + random_rows = ~fixed_rows & ~guess_rows + random_cols = ~fixed_cols & ~guess_cols + perm[random_rows] = rng.permutation(np.arange(N)[random_cols]) + else: + perm = rng.permutation(np.arange(N)) + + best_score = _calc_score(A, B, perm) + + i_free = np.arange(N) + if fixed_rows is not None: + i_free = i_free[~fixed_rows] + + better = operator.gt if maximize else operator.lt + n_iter = 0 + done = False + while not done: + # equivalent to nested for loops i in range(N), j in range(i, N) + for i, j in itertools.combinations_with_replacement(i_free, 2): + n_iter += 1 + perm[i], perm[j] = perm[j], perm[i] + score = _calc_score(A, B, perm) + if better(score, best_score): + best_score = score + break + # faster to swap back than to create a new list every time + perm[i], perm[j] = perm[j], perm[i] + else: # no swaps made + done = True + + res = {"col_ind": perm, "fun": best_score, "nit": n_iter} + return OptimizeResult(res) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_remove_redundancy.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_remove_redundancy.py new file mode 100644 index 0000000000000000000000000000000000000000..cb81ad1696b768d2304b2fc42a80cc9678cbde00 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_remove_redundancy.py @@ -0,0 +1,522 @@ +""" +Routines for removing redundant (linearly dependent) equations from linear +programming equality constraints. +""" +# Author: Matt Haberland + +import numpy as np +from scipy.linalg import svd +from scipy.linalg.interpolative import interp_decomp +import scipy +from scipy.linalg.blas import dtrsm + + +def _row_count(A): + """ + Counts the number of nonzeros in each row of input array A. + Nonzeros are defined as any element with absolute value greater than + tol = 1e-13. This value should probably be an input to the function. + + Parameters + ---------- + A : 2-D array + An array representing a matrix + + Returns + ------- + rowcount : 1-D array + Number of nonzeros in each row of A + + """ + tol = 1e-13 + return np.array((abs(A) > tol).sum(axis=1)).flatten() + + +def _get_densest(A, eligibleRows): + """ + Returns the index of the densest row of A. Ignores rows that are not + eligible for consideration. + + Parameters + ---------- + A : 2-D array + An array representing a matrix + eligibleRows : 1-D logical array + Values indicate whether the corresponding row of A is eligible + to be considered + + Returns + ------- + i_densest : int + Index of the densest row in A eligible for consideration + + """ + rowCounts = _row_count(A) + return np.argmax(rowCounts * eligibleRows) + + +def _remove_zero_rows(A, b): + """ + Eliminates trivial equations from system of equations defined by Ax = b + and identifies trivial infeasibilities + + Parameters + ---------- + A : 2-D array + An array representing the left-hand side of a system of equations + b : 1-D array + An array representing the right-hand side of a system of equations + + Returns + ------- + A : 2-D array + An array representing the left-hand side of a system of equations + b : 1-D array + An array representing the right-hand side of a system of equations + status: int + An integer indicating the status of the removal operation + 0: No infeasibility identified + 2: Trivially infeasible + message : str + A string descriptor of the exit status of the optimization. + + """ + status = 0 + message = "" + i_zero = _row_count(A) == 0 + A = A[np.logical_not(i_zero), :] + if not np.allclose(b[i_zero], 0): + status = 2 + message = "There is a zero row in A_eq with a nonzero corresponding " \ + "entry in b_eq. The problem is infeasible." + b = b[np.logical_not(i_zero)] + return A, b, status, message + + +def bg_update_dense(plu, perm_r, v, j): + LU, p = plu + + vperm = v[perm_r] + u = dtrsm(1, LU, vperm, lower=1, diag=1) + LU[:j+1, j] = u[:j+1] + l = u[j+1:] + piv = LU[j, j] + LU[j+1:, j] += (l/piv) + return LU, p + + +def _remove_redundancy_pivot_dense(A, rhs, true_rank=None): + """ + Eliminates redundant equations from system of equations defined by Ax = b + and identifies infeasibilities. + + Parameters + ---------- + A : 2-D sparse matrix + An matrix representing the left-hand side of a system of equations + rhs : 1-D array + An array representing the right-hand side of a system of equations + + Returns + ------- + A : 2-D sparse matrix + A matrix representing the left-hand side of a system of equations + rhs : 1-D array + An array representing the right-hand side of a system of equations + status: int + An integer indicating the status of the system + 0: No infeasibility identified + 2: Trivially infeasible + message : str + A string descriptor of the exit status of the optimization. + + References + ---------- + .. [2] Andersen, Erling D. "Finding all linearly dependent rows in + large-scale linear programming." Optimization Methods and Software + 6.3 (1995): 219-227. + + """ + tolapiv = 1e-8 + tolprimal = 1e-8 + status = 0 + message = "" + inconsistent = ("There is a linear combination of rows of A_eq that " + "results in zero, suggesting a redundant constraint. " + "However the same linear combination of b_eq is " + "nonzero, suggesting that the constraints conflict " + "and the problem is infeasible.") + A, rhs, status, message = _remove_zero_rows(A, rhs) + + if status != 0: + return A, rhs, status, message + + m, n = A.shape + + v = list(range(m)) # Artificial column indices. + b = list(v) # Basis column indices. + # This is better as a list than a set because column order of basis matrix + # needs to be consistent. + d = [] # Indices of dependent rows + perm_r = None + + A_orig = A + A = np.zeros((m, m + n), order='F') + np.fill_diagonal(A, 1) + A[:, m:] = A_orig + e = np.zeros(m) + + js_candidates = np.arange(m, m+n, dtype=int) # candidate columns for basis + # manual masking was faster than masked array + js_mask = np.ones(js_candidates.shape, dtype=bool) + + # Implements basic algorithm from [2] + # Uses some of the suggested improvements (removing zero rows and + # Bartels-Golub update idea). + # Removing column singletons would be easy, but it is not as important + # because the procedure is performed only on the equality constraint + # matrix from the original problem - not on the canonical form matrix, + # which would have many more column singletons due to slack variables + # from the inequality constraints. + # The thoughts on "crashing" the initial basis are only really useful if + # the matrix is sparse. + + lu = np.eye(m, order='F'), np.arange(m) # initial LU is trivial + perm_r = lu[1] + for i in v: + + e[i] = 1 + if i > 0: + e[i-1] = 0 + + try: # fails for i==0 and any time it gets ill-conditioned + j = b[i-1] + lu = bg_update_dense(lu, perm_r, A[:, j], i-1) + except Exception: + lu = scipy.linalg.lu_factor(A[:, b]) + LU, p = lu + perm_r = list(range(m)) + for i1, i2 in enumerate(p): + perm_r[i1], perm_r[i2] = perm_r[i2], perm_r[i1] + + pi = scipy.linalg.lu_solve(lu, e, trans=1) + + js = js_candidates[js_mask] + batch = 50 + + # This is a tiny bit faster than looping over columns individually, + # like for j in js: if abs(A[:,j].transpose().dot(pi)) > tolapiv: + for j_index in range(0, len(js), batch): + j_indices = js[j_index: min(j_index+batch, len(js))] + + c = abs(A[:, j_indices].transpose().dot(pi)) + if (c > tolapiv).any(): + j = js[j_index + np.argmax(c)] # very independent column + b[i] = j + js_mask[j-m] = False + break + else: + bibar = pi.T.dot(rhs.reshape(-1, 1)) + bnorm = np.linalg.norm(rhs) + if abs(bibar)/(1+bnorm) > tolprimal: # inconsistent + status = 2 + message = inconsistent + return A_orig, rhs, status, message + else: # dependent + d.append(i) + if true_rank is not None and len(d) == m - true_rank: + break # found all redundancies + + keep = set(range(m)) + keep = list(keep - set(d)) + return A_orig[keep, :], rhs[keep], status, message + + +def _remove_redundancy_pivot_sparse(A, rhs): + """ + Eliminates redundant equations from system of equations defined by Ax = b + and identifies infeasibilities. + + Parameters + ---------- + A : 2-D sparse matrix + An matrix representing the left-hand side of a system of equations + rhs : 1-D array + An array representing the right-hand side of a system of equations + + Returns + ------- + A : 2-D sparse matrix + A matrix representing the left-hand side of a system of equations + rhs : 1-D array + An array representing the right-hand side of a system of equations + status: int + An integer indicating the status of the system + 0: No infeasibility identified + 2: Trivially infeasible + message : str + A string descriptor of the exit status of the optimization. + + References + ---------- + .. [2] Andersen, Erling D. "Finding all linearly dependent rows in + large-scale linear programming." Optimization Methods and Software + 6.3 (1995): 219-227. + + """ + + tolapiv = 1e-8 + tolprimal = 1e-8 + status = 0 + message = "" + inconsistent = ("There is a linear combination of rows of A_eq that " + "results in zero, suggesting a redundant constraint. " + "However the same linear combination of b_eq is " + "nonzero, suggesting that the constraints conflict " + "and the problem is infeasible.") + A, rhs, status, message = _remove_zero_rows(A, rhs) + + if status != 0: + return A, rhs, status, message + + m, n = A.shape + + v = list(range(m)) # Artificial column indices. + b = list(v) # Basis column indices. + # This is better as a list than a set because column order of basis matrix + # needs to be consistent. + k = set(range(m, m+n)) # Structural column indices. + d = [] # Indices of dependent rows + + A_orig = A + A = scipy.sparse.hstack((scipy.sparse.eye(m), A)).tocsc() + e = np.zeros(m) + + # Implements basic algorithm from [2] + # Uses only one of the suggested improvements (removing zero rows). + # Removing column singletons would be easy, but it is not as important + # because the procedure is performed only on the equality constraint + # matrix from the original problem - not on the canonical form matrix, + # which would have many more column singletons due to slack variables + # from the inequality constraints. + # The thoughts on "crashing" the initial basis sound useful, but the + # description of the procedure seems to assume a lot of familiarity with + # the subject; it is not very explicit. I already went through enough + # trouble getting the basic algorithm working, so I was not interested in + # trying to decipher this, too. (Overall, the paper is fraught with + # mistakes and ambiguities - which is strange, because the rest of + # Andersen's papers are quite good.) + # I tried and tried and tried to improve performance using the + # Bartels-Golub update. It works, but it's only practical if the LU + # factorization can be specialized as described, and that is not possible + # until the SciPy SuperLU interface permits control over column + # permutation - see issue #7700. + + for i in v: + B = A[:, b] + + e[i] = 1 + if i > 0: + e[i-1] = 0 + + pi = scipy.sparse.linalg.spsolve(B.transpose(), e).reshape(-1, 1) + + js = list(k-set(b)) # not efficient, but this is not the time sink... + + # Due to overhead, it tends to be faster (for problems tested) to + # compute the full matrix-vector product rather than individual + # vector-vector products (with the chance of terminating as soon + # as any are nonzero). For very large matrices, it might be worth + # it to compute, say, 100 or 1000 at a time and stop when a nonzero + # is found. + + c = (np.abs(A[:, js].transpose().dot(pi)) > tolapiv).nonzero()[0] + if len(c) > 0: # independent + j = js[c[0]] + # in a previous commit, the previous line was changed to choose + # index j corresponding with the maximum dot product. + # While this avoided issues with almost + # singular matrices, it slowed the routine in most NETLIB tests. + # I think this is because these columns were denser than the + # first column with nonzero dot product (c[0]). + # It would be nice to have a heuristic that balances sparsity with + # high dot product, but I don't think it's worth the time to + # develop one right now. Bartels-Golub update is a much higher + # priority. + b[i] = j # replace artificial column + else: + bibar = pi.T.dot(rhs.reshape(-1, 1)) + bnorm = np.linalg.norm(rhs) + if abs(bibar)/(1 + bnorm) > tolprimal: + status = 2 + message = inconsistent + return A_orig, rhs, status, message + else: # dependent + d.append(i) + + keep = set(range(m)) + keep = list(keep - set(d)) + return A_orig[keep, :], rhs[keep], status, message + + +def _remove_redundancy_svd(A, b): + """ + Eliminates redundant equations from system of equations defined by Ax = b + and identifies infeasibilities. + + Parameters + ---------- + A : 2-D array + An array representing the left-hand side of a system of equations + b : 1-D array + An array representing the right-hand side of a system of equations + + Returns + ------- + A : 2-D array + An array representing the left-hand side of a system of equations + b : 1-D array + An array representing the right-hand side of a system of equations + status: int + An integer indicating the status of the system + 0: No infeasibility identified + 2: Trivially infeasible + message : str + A string descriptor of the exit status of the optimization. + + References + ---------- + .. [2] Andersen, Erling D. "Finding all linearly dependent rows in + large-scale linear programming." Optimization Methods and Software + 6.3 (1995): 219-227. + + """ + + A, b, status, message = _remove_zero_rows(A, b) + + if status != 0: + return A, b, status, message + + U, s, Vh = svd(A) + eps = np.finfo(float).eps + tol = s.max() * max(A.shape) * eps + + m, n = A.shape + s_min = s[-1] if m <= n else 0 + + # this algorithm is faster than that of [2] when the nullspace is small + # but it could probably be improvement by randomized algorithms and with + # a sparse implementation. + # it relies on repeated singular value decomposition to find linearly + # dependent rows (as identified by columns of U that correspond with zero + # singular values). Unfortunately, only one row can be removed per + # decomposition (I tried otherwise; doing so can cause problems.) + # It would be nice if we could do truncated SVD like sp.sparse.linalg.svds + # but that function is unreliable at finding singular values near zero. + # Finding max eigenvalue L of A A^T, then largest eigenvalue (and + # associated eigenvector) of -A A^T + L I (I is identity) via power + # iteration would also work in theory, but is only efficient if the + # smallest nonzero eigenvalue of A A^T is close to the largest nonzero + # eigenvalue. + + while abs(s_min) < tol: + v = U[:, -1] # TODO: return these so user can eliminate from problem? + # rows need to be represented in significant amount + eligibleRows = np.abs(v) > tol * 10e6 + if not np.any(eligibleRows) or np.any(np.abs(v.dot(A)) > tol): + status = 4 + message = ("Due to numerical issues, redundant equality " + "constraints could not be removed automatically. " + "Try providing your constraint matrices as sparse " + "matrices to activate sparse presolve, try turning " + "off redundancy removal, or try turning off presolve " + "altogether.") + break + if np.any(np.abs(v.dot(b)) > tol * 100): # factor of 100 to fix 10038 and 10349 + status = 2 + message = ("There is a linear combination of rows of A_eq that " + "results in zero, suggesting a redundant constraint. " + "However the same linear combination of b_eq is " + "nonzero, suggesting that the constraints conflict " + "and the problem is infeasible.") + break + + i_remove = _get_densest(A, eligibleRows) + A = np.delete(A, i_remove, axis=0) + b = np.delete(b, i_remove) + U, s, Vh = svd(A) + m, n = A.shape + s_min = s[-1] if m <= n else 0 + + return A, b, status, message + + +def _remove_redundancy_id(A, rhs, rank=None, randomized=True): + """Eliminates redundant equations from a system of equations. + + Eliminates redundant equations from system of equations defined by Ax = b + and identifies infeasibilities. + + Parameters + ---------- + A : 2-D array + An array representing the left-hand side of a system of equations + rhs : 1-D array + An array representing the right-hand side of a system of equations + rank : int, optional + The rank of A + randomized: bool, optional + True for randomized interpolative decomposition + + Returns + ------- + A : 2-D array + An array representing the left-hand side of a system of equations + rhs : 1-D array + An array representing the right-hand side of a system of equations + status: int + An integer indicating the status of the system + 0: No infeasibility identified + 2: Trivially infeasible + message : str + A string descriptor of the exit status of the optimization. + + """ + + status = 0 + message = "" + inconsistent = ("There is a linear combination of rows of A_eq that " + "results in zero, suggesting a redundant constraint. " + "However the same linear combination of b_eq is " + "nonzero, suggesting that the constraints conflict " + "and the problem is infeasible.") + + A, rhs, status, message = _remove_zero_rows(A, rhs) + + if status != 0: + return A, rhs, status, message + + m, n = A.shape + + k = rank + if rank is None: + k = np.linalg.matrix_rank(A) + + idx, proj = interp_decomp(A.T, k, rand=randomized) + + # first k entries in idx are indices of the independent rows + # remaining entries are the indices of the m-k dependent rows + # proj provides a linear combinations of rows of A2 that form the + # remaining m-k (dependent) rows. The same linear combination of entries + # in rhs2 must give the remaining m-k entries. If not, the system is + # inconsistent, and the problem is infeasible. + if not np.allclose(rhs[idx[:k]] @ proj, rhs[idx[k:]]): + status = 2 + message = inconsistent + + # sort indices because the other redundancy removal routines leave rows + # in original order and tests were written with that in mind + idx = sorted(idx[:k]) + A2 = A[idx, :] + rhs2 = rhs[idx] + return A2, rhs2, status, message diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_root.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_root.py new file mode 100644 index 0000000000000000000000000000000000000000..fdf5a0cf409392d4c3ece21f23ad2e061860c699 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_root.py @@ -0,0 +1,732 @@ +""" +Unified interfaces to root finding algorithms. + +Functions +--------- +- root : find a root of a vector function. +""" +__all__ = ['root'] + +import numpy as np + +from warnings import warn + +from ._optimize import MemoizeJac, OptimizeResult, _check_unknown_options +from ._minpack_py import _root_hybr, leastsq +from ._spectral import _root_df_sane +from . import _nonlin as nonlin + + +ROOT_METHODS = ['hybr', 'lm', 'broyden1', 'broyden2', 'anderson', + 'linearmixing', 'diagbroyden', 'excitingmixing', 'krylov', + 'df-sane'] + + +def root(fun, x0, args=(), method='hybr', jac=None, tol=None, callback=None, + options=None): + r""" + Find a root of a vector function. + + Parameters + ---------- + fun : callable + A vector function to find a root of. + + Suppose the callable has signature ``f0(x, *my_args, **my_kwargs)``, where + ``my_args`` and ``my_kwargs`` are required positional and keyword arguments. + Rather than passing ``f0`` as the callable, wrap it to accept + only ``x``; e.g., pass ``fun=lambda x: f0(x, *my_args, **my_kwargs)`` as the + callable, where ``my_args`` (tuple) and ``my_kwargs`` (dict) have been + gathered before invoking this function. + x0 : ndarray + Initial guess. + args : tuple, optional + Extra arguments passed to the objective function and its Jacobian. + method : str, optional + Type of solver. Should be one of + + - 'hybr' :ref:`(see here) ` + - 'lm' :ref:`(see here) ` + - 'broyden1' :ref:`(see here) ` + - 'broyden2' :ref:`(see here) ` + - 'anderson' :ref:`(see here) ` + - 'linearmixing' :ref:`(see here) ` + - 'diagbroyden' :ref:`(see here) ` + - 'excitingmixing' :ref:`(see here) ` + - 'krylov' :ref:`(see here) ` + - 'df-sane' :ref:`(see here) ` + + jac : bool or callable, optional + If `jac` is a Boolean and is True, `fun` is assumed to return the + value of Jacobian along with the objective function. If False, the + Jacobian will be estimated numerically. + `jac` can also be a callable returning the Jacobian of `fun`. In + this case, it must accept the same arguments as `fun`. + tol : float, optional + Tolerance for termination. For detailed control, use solver-specific + options. + callback : function, optional + Optional callback function. It is called on every iteration as + ``callback(x, f)`` where `x` is the current solution and `f` + the corresponding residual. For all methods but 'hybr' and 'lm'. + options : dict, optional + A dictionary of solver options. E.g., `xtol` or `maxiter`, see + :obj:`show_options()` for details. + + Returns + ------- + sol : OptimizeResult + The solution represented as a ``OptimizeResult`` object. + Important attributes are: ``x`` the solution array, ``success`` a + Boolean flag indicating if the algorithm exited successfully and + ``message`` which describes the cause of the termination. See + `OptimizeResult` for a description of other attributes. + + See also + -------- + show_options : Additional options accepted by the solvers + + Notes + ----- + This section describes the available solvers that can be selected by the + 'method' parameter. The default method is *hybr*. + + Method *hybr* uses a modification of the Powell hybrid method as + implemented in MINPACK [1]_. + + Method *lm* solves the system of nonlinear equations in a least squares + sense using a modification of the Levenberg-Marquardt algorithm as + implemented in MINPACK [1]_. + + Method *df-sane* is a derivative-free spectral method. [3]_ + + Methods *broyden1*, *broyden2*, *anderson*, *linearmixing*, + *diagbroyden*, *excitingmixing*, *krylov* are inexact Newton methods, + with backtracking or full line searches [2]_. Each method corresponds + to a particular Jacobian approximations. + + - Method *broyden1* uses Broyden's first Jacobian approximation, it is + known as Broyden's good method. + - Method *broyden2* uses Broyden's second Jacobian approximation, it + is known as Broyden's bad method. + - Method *anderson* uses (extended) Anderson mixing. + - Method *Krylov* uses Krylov approximation for inverse Jacobian. It + is suitable for large-scale problem. + - Method *diagbroyden* uses diagonal Broyden Jacobian approximation. + - Method *linearmixing* uses a scalar Jacobian approximation. + - Method *excitingmixing* uses a tuned diagonal Jacobian + approximation. + + .. warning:: + + The algorithms implemented for methods *diagbroyden*, + *linearmixing* and *excitingmixing* may be useful for specific + problems, but whether they will work may depend strongly on the + problem. + + .. versionadded:: 0.11.0 + + References + ---------- + .. [1] More, Jorge J., Burton S. Garbow, and Kenneth E. Hillstrom. + 1980. User Guide for MINPACK-1. + .. [2] C. T. Kelley. 1995. Iterative Methods for Linear and Nonlinear + Equations. Society for Industrial and Applied Mathematics. + + .. [3] W. La Cruz, J.M. Martinez, M. Raydan. Math. Comp. 75, 1429 (2006). + + Examples + -------- + The following functions define a system of nonlinear equations and its + jacobian. + + >>> import numpy as np + >>> def fun(x): + ... return [x[0] + 0.5 * (x[0] - x[1])**3 - 1.0, + ... 0.5 * (x[1] - x[0])**3 + x[1]] + + >>> def jac(x): + ... return np.array([[1 + 1.5 * (x[0] - x[1])**2, + ... -1.5 * (x[0] - x[1])**2], + ... [-1.5 * (x[1] - x[0])**2, + ... 1 + 1.5 * (x[1] - x[0])**2]]) + + A solution can be obtained as follows. + + >>> from scipy import optimize + >>> sol = optimize.root(fun, [0, 0], jac=jac, method='hybr') + >>> sol.x + array([ 0.8411639, 0.1588361]) + + **Large problem** + + Suppose that we needed to solve the following integrodifferential + equation on the square :math:`[0,1]\times[0,1]`: + + .. math:: + + \nabla^2 P = 10 \left(\int_0^1\int_0^1\cosh(P)\,dx\,dy\right)^2 + + with :math:`P(x,1) = 1` and :math:`P=0` elsewhere on the boundary of + the square. + + The solution can be found using the ``method='krylov'`` solver: + + >>> from scipy import optimize + >>> # parameters + >>> nx, ny = 75, 75 + >>> hx, hy = 1./(nx-1), 1./(ny-1) + + >>> P_left, P_right = 0, 0 + >>> P_top, P_bottom = 1, 0 + + >>> def residual(P): + ... d2x = np.zeros_like(P) + ... d2y = np.zeros_like(P) + ... + ... d2x[1:-1] = (P[2:] - 2*P[1:-1] + P[:-2]) / hx/hx + ... d2x[0] = (P[1] - 2*P[0] + P_left)/hx/hx + ... d2x[-1] = (P_right - 2*P[-1] + P[-2])/hx/hx + ... + ... d2y[:,1:-1] = (P[:,2:] - 2*P[:,1:-1] + P[:,:-2])/hy/hy + ... d2y[:,0] = (P[:,1] - 2*P[:,0] + P_bottom)/hy/hy + ... d2y[:,-1] = (P_top - 2*P[:,-1] + P[:,-2])/hy/hy + ... + ... return d2x + d2y - 10*np.cosh(P).mean()**2 + + >>> guess = np.zeros((nx, ny), float) + >>> sol = optimize.root(residual, guess, method='krylov') + >>> print('Residual: %g' % abs(residual(sol.x)).max()) + Residual: 5.7972e-06 # may vary + + >>> import matplotlib.pyplot as plt + >>> x, y = np.mgrid[0:1:(nx*1j), 0:1:(ny*1j)] + >>> plt.pcolormesh(x, y, sol.x, shading='gouraud') + >>> plt.colorbar() + >>> plt.show() + + """ + def _wrapped_fun(*fargs): + """ + Wrapped `func` to track the number of times + the function has been called. + """ + _wrapped_fun.nfev += 1 + return fun(*fargs) + + _wrapped_fun.nfev = 0 + + if not isinstance(args, tuple): + args = (args,) + + meth = method.lower() + if options is None: + options = {} + + if callback is not None and meth in ('hybr', 'lm'): + warn(f'Method {method} does not accept callback.', + RuntimeWarning, stacklevel=2) + + # fun also returns the Jacobian + if not callable(jac) and meth in ('hybr', 'lm'): + if bool(jac): + fun = MemoizeJac(fun) + jac = fun.derivative + else: + jac = None + + # set default tolerances + if tol is not None: + options = dict(options) + if meth in ('hybr', 'lm'): + options.setdefault('xtol', tol) + elif meth in ('df-sane',): + options.setdefault('ftol', tol) + elif meth in ('broyden1', 'broyden2', 'anderson', 'linearmixing', + 'diagbroyden', 'excitingmixing', 'krylov'): + options.setdefault('xtol', tol) + options.setdefault('xatol', np.inf) + options.setdefault('ftol', np.inf) + options.setdefault('fatol', np.inf) + + if meth == 'hybr': + sol = _root_hybr(_wrapped_fun, x0, args=args, jac=jac, **options) + elif meth == 'lm': + sol = _root_leastsq(_wrapped_fun, x0, args=args, jac=jac, **options) + elif meth == 'df-sane': + _warn_jac_unused(jac, method) + sol = _root_df_sane(_wrapped_fun, x0, args=args, callback=callback, + **options) + elif meth in ('broyden1', 'broyden2', 'anderson', 'linearmixing', + 'diagbroyden', 'excitingmixing', 'krylov'): + _warn_jac_unused(jac, method) + sol = _root_nonlin_solve(_wrapped_fun, x0, args=args, jac=jac, + _method=meth, _callback=callback, + **options) + else: + raise ValueError(f'Unknown solver {method}') + + sol.nfev = _wrapped_fun.nfev + return sol + + +def _warn_jac_unused(jac, method): + if jac is not None: + warn(f'Method {method} does not use the jacobian (jac).', + RuntimeWarning, stacklevel=2) + + +def _root_leastsq(fun, x0, args=(), jac=None, + col_deriv=0, xtol=1.49012e-08, ftol=1.49012e-08, + gtol=0.0, maxiter=0, eps=0.0, factor=100, diag=None, + **unknown_options): + """ + Solve for least squares with Levenberg-Marquardt + + Options + ------- + col_deriv : bool + non-zero to specify that the Jacobian function computes derivatives + down the columns (faster, because there is no transpose operation). + ftol : float + Relative error desired in the sum of squares. + xtol : float + Relative error desired in the approximate solution. + gtol : float + Orthogonality desired between the function vector and the columns + of the Jacobian. + maxiter : int + The maximum number of calls to the function. If zero, then + 100*(N+1) is the maximum where N is the number of elements in x0. + eps : float + A suitable step length for the forward-difference approximation of + the Jacobian (for Dfun=None). If `eps` is less than the machine + precision, it is assumed that the relative errors in the functions + are of the order of the machine precision. + factor : float + A parameter determining the initial step bound + (``factor * || diag * x||``). Should be in interval ``(0.1, 100)``. + diag : sequence + N positive entries that serve as a scale factors for the variables. + """ + nfev = 0 + def _wrapped_fun(*fargs): + """ + Wrapped `func` to track the number of times + the function has been called. + """ + nonlocal nfev + nfev += 1 + return fun(*fargs) + + _check_unknown_options(unknown_options) + x, cov_x, info, msg, ier = leastsq(_wrapped_fun, x0, args=args, + Dfun=jac, full_output=True, + col_deriv=col_deriv, xtol=xtol, + ftol=ftol, gtol=gtol, + maxfev=maxiter, epsfcn=eps, + factor=factor, diag=diag) + sol = OptimizeResult(x=x, message=msg, status=ier, + success=ier in (1, 2, 3, 4), cov_x=cov_x, + fun=info.pop('fvec'), method="lm") + sol.update(info) + sol.nfev = nfev + return sol + + +def _root_nonlin_solve(fun, x0, args=(), jac=None, + _callback=None, _method=None, + nit=None, disp=False, maxiter=None, + ftol=None, fatol=None, xtol=None, xatol=None, + tol_norm=None, line_search='armijo', jac_options=None, + **unknown_options): + _check_unknown_options(unknown_options) + + f_tol = fatol + f_rtol = ftol + x_tol = xatol + x_rtol = xtol + verbose = disp + if jac_options is None: + jac_options = dict() + + jacobian = {'broyden1': nonlin.BroydenFirst, + 'broyden2': nonlin.BroydenSecond, + 'anderson': nonlin.Anderson, + 'linearmixing': nonlin.LinearMixing, + 'diagbroyden': nonlin.DiagBroyden, + 'excitingmixing': nonlin.ExcitingMixing, + 'krylov': nonlin.KrylovJacobian + }[_method] + + if args: + if jac is True: + def f(x): + return fun(x, *args)[0] + else: + def f(x): + return fun(x, *args) + else: + f = fun + + x, info = nonlin.nonlin_solve(f, x0, jacobian=jacobian(**jac_options), + iter=nit, verbose=verbose, + maxiter=maxiter, f_tol=f_tol, + f_rtol=f_rtol, x_tol=x_tol, + x_rtol=x_rtol, tol_norm=tol_norm, + line_search=line_search, + callback=_callback, full_output=True, + raise_exception=False) + sol = OptimizeResult(x=x, method=_method) + sol.update(info) + return sol + +def _root_broyden1_doc(): + """ + Options + ------- + nit : int, optional + Number of iterations to make. If omitted (default), make as many + as required to meet tolerances. + disp : bool, optional + Print status to stdout on every iteration. + maxiter : int, optional + Maximum number of iterations to make. + ftol : float, optional + Relative tolerance for the residual. If omitted, not used. + fatol : float, optional + Absolute tolerance (in max-norm) for the residual. + If omitted, default is 6e-6. + xtol : float, optional + Relative minimum step size. If omitted, not used. + xatol : float, optional + Absolute minimum step size, as determined from the Jacobian + approximation. If the step size is smaller than this, optimization + is terminated as successful. If omitted, not used. + tol_norm : function(vector) -> scalar, optional + Norm to use in convergence check. Default is the maximum norm. + line_search : {None, 'armijo' (default), 'wolfe'}, optional + Which type of a line search to use to determine the step size in + the direction given by the Jacobian approximation. Defaults to + 'armijo'. + jac_options : dict, optional + Options for the respective Jacobian approximation. + + alpha : float, optional + Initial guess for the Jacobian is (-1/alpha). + reduction_method : str or tuple, optional + Method used in ensuring that the rank of the Broyden + matrix stays low. Can either be a string giving the + name of the method, or a tuple of the form ``(method, + param1, param2, ...)`` that gives the name of the + method and values for additional parameters. + + Methods available: + + - ``restart``: drop all matrix columns. Has no extra parameters. + - ``simple``: drop oldest matrix column. Has no extra parameters. + - ``svd``: keep only the most significant SVD components. + Takes an extra parameter, ``to_retain``, which determines the + number of SVD components to retain when rank reduction is done. + Default is ``max_rank - 2``. + + max_rank : int, optional + Maximum rank for the Broyden matrix. + Default is infinity (i.e., no rank reduction). + + Examples + -------- + >>> def func(x): + ... return np.cos(x) + x[::-1] - [1, 2, 3, 4] + ... + >>> from scipy import optimize + >>> res = optimize.root(func, [1, 1, 1, 1], method='broyden1', tol=1e-14) + >>> x = res.x + >>> x + array([4.04674914, 3.91158389, 2.71791677, 1.61756251]) + >>> np.cos(x) + x[::-1] + array([1., 2., 3., 4.]) + + """ + pass + + +def _root_broyden2_doc(): + """ + Options + ------- + nit : int, optional + Number of iterations to make. If omitted (default), make as many + as required to meet tolerances. + disp : bool, optional + Print status to stdout on every iteration. + maxiter : int, optional + Maximum number of iterations to make. + ftol : float, optional + Relative tolerance for the residual. If omitted, not used. + fatol : float, optional + Absolute tolerance (in max-norm) for the residual. + If omitted, default is 6e-6. + xtol : float, optional + Relative minimum step size. If omitted, not used. + xatol : float, optional + Absolute minimum step size, as determined from the Jacobian + approximation. If the step size is smaller than this, optimization + is terminated as successful. If omitted, not used. + tol_norm : function(vector) -> scalar, optional + Norm to use in convergence check. Default is the maximum norm. + line_search : {None, 'armijo' (default), 'wolfe'}, optional + Which type of a line search to use to determine the step size in + the direction given by the Jacobian approximation. Defaults to + 'armijo'. + jac_options : dict, optional + Options for the respective Jacobian approximation. + + alpha : float, optional + Initial guess for the Jacobian is (-1/alpha). + reduction_method : str or tuple, optional + Method used in ensuring that the rank of the Broyden + matrix stays low. Can either be a string giving the + name of the method, or a tuple of the form ``(method, + param1, param2, ...)`` that gives the name of the + method and values for additional parameters. + + Methods available: + + - ``restart``: drop all matrix columns. Has no extra parameters. + - ``simple``: drop oldest matrix column. Has no extra parameters. + - ``svd``: keep only the most significant SVD components. + Takes an extra parameter, ``to_retain``, which determines the + number of SVD components to retain when rank reduction is done. + Default is ``max_rank - 2``. + + max_rank : int, optional + Maximum rank for the Broyden matrix. + Default is infinity (i.e., no rank reduction). + """ + pass + + +def _root_anderson_doc(): + """ + Options + ------- + nit : int, optional + Number of iterations to make. If omitted (default), make as many + as required to meet tolerances. + disp : bool, optional + Print status to stdout on every iteration. + maxiter : int, optional + Maximum number of iterations to make. + ftol : float, optional + Relative tolerance for the residual. If omitted, not used. + fatol : float, optional + Absolute tolerance (in max-norm) for the residual. + If omitted, default is 6e-6. + xtol : float, optional + Relative minimum step size. If omitted, not used. + xatol : float, optional + Absolute minimum step size, as determined from the Jacobian + approximation. If the step size is smaller than this, optimization + is terminated as successful. If omitted, not used. + tol_norm : function(vector) -> scalar, optional + Norm to use in convergence check. Default is the maximum norm. + line_search : {None, 'armijo' (default), 'wolfe'}, optional + Which type of a line search to use to determine the step size in + the direction given by the Jacobian approximation. Defaults to + 'armijo'. + jac_options : dict, optional + Options for the respective Jacobian approximation. + + alpha : float, optional + Initial guess for the Jacobian is (-1/alpha). + M : float, optional + Number of previous vectors to retain. Defaults to 5. + w0 : float, optional + Regularization parameter for numerical stability. + Compared to unity, good values of the order of 0.01. + """ + pass + +def _root_linearmixing_doc(): + """ + Options + ------- + nit : int, optional + Number of iterations to make. If omitted (default), make as many + as required to meet tolerances. + disp : bool, optional + Print status to stdout on every iteration. + maxiter : int, optional + Maximum number of iterations to make. + ftol : float, optional + Relative tolerance for the residual. If omitted, not used. + fatol : float, optional + Absolute tolerance (in max-norm) for the residual. + If omitted, default is 6e-6. + xtol : float, optional + Relative minimum step size. If omitted, not used. + xatol : float, optional + Absolute minimum step size, as determined from the Jacobian + approximation. If the step size is smaller than this, optimization + is terminated as successful. If omitted, not used. + tol_norm : function(vector) -> scalar, optional + Norm to use in convergence check. Default is the maximum norm. + line_search : {None, 'armijo' (default), 'wolfe'}, optional + Which type of a line search to use to determine the step size in + the direction given by the Jacobian approximation. Defaults to + 'armijo'. + jac_options : dict, optional + Options for the respective Jacobian approximation. + + alpha : float, optional + initial guess for the jacobian is (-1/alpha). + """ + pass + +def _root_diagbroyden_doc(): + """ + Options + ------- + nit : int, optional + Number of iterations to make. If omitted (default), make as many + as required to meet tolerances. + disp : bool, optional + Print status to stdout on every iteration. + maxiter : int, optional + Maximum number of iterations to make. + ftol : float, optional + Relative tolerance for the residual. If omitted, not used. + fatol : float, optional + Absolute tolerance (in max-norm) for the residual. + If omitted, default is 6e-6. + xtol : float, optional + Relative minimum step size. If omitted, not used. + xatol : float, optional + Absolute minimum step size, as determined from the Jacobian + approximation. If the step size is smaller than this, optimization + is terminated as successful. If omitted, not used. + tol_norm : function(vector) -> scalar, optional + Norm to use in convergence check. Default is the maximum norm. + line_search : {None, 'armijo' (default), 'wolfe'}, optional + Which type of a line search to use to determine the step size in + the direction given by the Jacobian approximation. Defaults to + 'armijo'. + jac_options : dict, optional + Options for the respective Jacobian approximation. + + alpha : float, optional + initial guess for the jacobian is (-1/alpha). + """ + pass + +def _root_excitingmixing_doc(): + """ + Options + ------- + nit : int, optional + Number of iterations to make. If omitted (default), make as many + as required to meet tolerances. + disp : bool, optional + Print status to stdout on every iteration. + maxiter : int, optional + Maximum number of iterations to make. + ftol : float, optional + Relative tolerance for the residual. If omitted, not used. + fatol : float, optional + Absolute tolerance (in max-norm) for the residual. + If omitted, default is 6e-6. + xtol : float, optional + Relative minimum step size. If omitted, not used. + xatol : float, optional + Absolute minimum step size, as determined from the Jacobian + approximation. If the step size is smaller than this, optimization + is terminated as successful. If omitted, not used. + tol_norm : function(vector) -> scalar, optional + Norm to use in convergence check. Default is the maximum norm. + line_search : {None, 'armijo' (default), 'wolfe'}, optional + Which type of a line search to use to determine the step size in + the direction given by the Jacobian approximation. Defaults to + 'armijo'. + jac_options : dict, optional + Options for the respective Jacobian approximation. + + alpha : float, optional + Initial Jacobian approximation is (-1/alpha). + alphamax : float, optional + The entries of the diagonal Jacobian are kept in the range + ``[alpha, alphamax]``. + """ + pass + +def _root_krylov_doc(): + """ + Options + ------- + nit : int, optional + Number of iterations to make. If omitted (default), make as many + as required to meet tolerances. + disp : bool, optional + Print status to stdout on every iteration. + maxiter : int, optional + Maximum number of iterations to make. + ftol : float, optional + Relative tolerance for the residual. If omitted, not used. + fatol : float, optional + Absolute tolerance (in max-norm) for the residual. + If omitted, default is 6e-6. + xtol : float, optional + Relative minimum step size. If omitted, not used. + xatol : float, optional + Absolute minimum step size, as determined from the Jacobian + approximation. If the step size is smaller than this, optimization + is terminated as successful. If omitted, not used. + tol_norm : function(vector) -> scalar, optional + Norm to use in convergence check. Default is the maximum norm. + line_search : {None, 'armijo' (default), 'wolfe'}, optional + Which type of a line search to use to determine the step size in + the direction given by the Jacobian approximation. Defaults to + 'armijo'. + jac_options : dict, optional + Options for the respective Jacobian approximation. + + rdiff : float, optional + Relative step size to use in numerical differentiation. + method : str or callable, optional + Krylov method to use to approximate the Jacobian. Can be a string, + or a function implementing the same interface as the iterative + solvers in `scipy.sparse.linalg`. If a string, needs to be one of: + ``'lgmres'``, ``'gmres'``, ``'bicgstab'``, ``'cgs'``, ``'minres'``, + ``'tfqmr'``. + + The default is `scipy.sparse.linalg.lgmres`. + inner_M : LinearOperator or InverseJacobian + Preconditioner for the inner Krylov iteration. + Note that you can use also inverse Jacobians as (adaptive) + preconditioners. For example, + + >>> jac = BroydenFirst() + >>> kjac = KrylovJacobian(inner_M=jac.inverse). + + If the preconditioner has a method named 'update', it will + be called as ``update(x, f)`` after each nonlinear step, + with ``x`` giving the current point, and ``f`` the current + function value. + inner_rtol, inner_atol, inner_callback, ... + Parameters to pass on to the "inner" Krylov solver. + + For a full list of options, see the documentation for the + solver you are using. By default this is `scipy.sparse.linalg.lgmres`. + If the solver has been overridden through `method`, see the documentation + for that solver instead. + To use an option for that solver, prepend ``inner_`` to it. + For example, to control the ``rtol`` argument to the solver, + set the `inner_rtol` option here. + + outer_k : int, optional + Size of the subspace kept across LGMRES nonlinear + iterations. + + See `scipy.sparse.linalg.lgmres` for details. + """ + pass diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_root_scalar.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_root_scalar.py new file mode 100644 index 0000000000000000000000000000000000000000..668565de62ea36e0cc9be378875604855e489d17 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_root_scalar.py @@ -0,0 +1,538 @@ +""" +Unified interfaces to root finding algorithms for real or complex +scalar functions. + +Functions +--------- +- root : find a root of a scalar function. +""" +import numpy as np + +from . import _zeros_py as optzeros +from ._numdiff import approx_derivative + +__all__ = ['root_scalar'] + +ROOT_SCALAR_METHODS = ['bisect', 'brentq', 'brenth', 'ridder', 'toms748', + 'newton', 'secant', 'halley'] + + +class MemoizeDer: + """Decorator that caches the value and derivative(s) of function each + time it is called. + + This is a simplistic memoizer that calls and caches a single value + of ``f(x, *args)``. + It assumes that `args` does not change between invocations. + It supports the use case of a root-finder where `args` is fixed, + `x` changes, and only rarely, if at all, does x assume the same value + more than once.""" + def __init__(self, fun): + self.fun = fun + self.vals = None + self.x = None + self.n_calls = 0 + + def __call__(self, x, *args): + r"""Calculate f or use cached value if available""" + # Derivative may be requested before the function itself, always check + if self.vals is None or x != self.x: + fg = self.fun(x, *args) + self.x = x + self.n_calls += 1 + self.vals = fg[:] + return self.vals[0] + + def fprime(self, x, *args): + r"""Calculate f' or use a cached value if available""" + if self.vals is None or x != self.x: + self(x, *args) + return self.vals[1] + + def fprime2(self, x, *args): + r"""Calculate f'' or use a cached value if available""" + if self.vals is None or x != self.x: + self(x, *args) + return self.vals[2] + + def ncalls(self): + return self.n_calls + + +def root_scalar(f, args=(), method=None, bracket=None, + fprime=None, fprime2=None, + x0=None, x1=None, + xtol=None, rtol=None, maxiter=None, + options=None): + """ + Find a root of a scalar function. + + Parameters + ---------- + f : callable + A function to find a root of. + + Suppose the callable has signature ``f0(x, *my_args, **my_kwargs)``, where + ``my_args`` and ``my_kwargs`` are required positional and keyword arguments. + Rather than passing ``f0`` as the callable, wrap it to accept + only ``x``; e.g., pass ``fun=lambda x: f0(x, *my_args, **my_kwargs)`` as the + callable, where ``my_args`` (tuple) and ``my_kwargs`` (dict) have been + gathered before invoking this function. + args : tuple, optional + Extra arguments passed to the objective function and its derivative(s). + method : str, optional + Type of solver. Should be one of + + - 'bisect' :ref:`(see here) ` + - 'brentq' :ref:`(see here) ` + - 'brenth' :ref:`(see here) ` + - 'ridder' :ref:`(see here) ` + - 'toms748' :ref:`(see here) ` + - 'newton' :ref:`(see here) ` + - 'secant' :ref:`(see here) ` + - 'halley' :ref:`(see here) ` + + bracket: A sequence of 2 floats, optional + An interval bracketing a root. ``f(x, *args)`` must have different + signs at the two endpoints. + x0 : float, optional + Initial guess. + x1 : float, optional + A second guess. + fprime : bool or callable, optional + If `fprime` is a boolean and is True, `f` is assumed to return the + value of the objective function and of the derivative. + `fprime` can also be a callable returning the derivative of `f`. In + this case, it must accept the same arguments as `f`. + fprime2 : bool or callable, optional + If `fprime2` is a boolean and is True, `f` is assumed to return the + value of the objective function and of the + first and second derivatives. + `fprime2` can also be a callable returning the second derivative of `f`. + In this case, it must accept the same arguments as `f`. + xtol : float, optional + Tolerance (absolute) for termination. + rtol : float, optional + Tolerance (relative) for termination. + maxiter : int, optional + Maximum number of iterations. + options : dict, optional + A dictionary of solver options. E.g., ``k``, see + :obj:`show_options()` for details. + + Returns + ------- + sol : RootResults + The solution represented as a ``RootResults`` object. + Important attributes are: ``root`` the solution , ``converged`` a + boolean flag indicating if the algorithm exited successfully and + ``flag`` which describes the cause of the termination. See + `RootResults` for a description of other attributes. + + See also + -------- + show_options : Additional options accepted by the solvers + root : Find a root of a vector function. + + Notes + ----- + This section describes the available solvers that can be selected by the + 'method' parameter. + + The default is to use the best method available for the situation + presented. + If a bracket is provided, it may use one of the bracketing methods. + If a derivative and an initial value are specified, it may + select one of the derivative-based methods. + If no method is judged applicable, it will raise an Exception. + + Arguments for each method are as follows (x=required, o=optional). + + +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+ + | method | f | args | bracket | x0 | x1 | fprime | fprime2 | xtol | rtol | maxiter | options | + +===============================================+===+======+=========+====+====+========+=========+======+======+=========+=========+ + | :ref:`bisect ` | x | o | x | | | | | o | o | o | o | + +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+ + | :ref:`brentq ` | x | o | x | | | | | o | o | o | o | + +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+ + | :ref:`brenth ` | x | o | x | | | | | o | o | o | o | + +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+ + | :ref:`ridder ` | x | o | x | | | | | o | o | o | o | + +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+ + | :ref:`toms748 ` | x | o | x | | | | | o | o | o | o | + +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+ + | :ref:`secant ` | x | o | | x | o | | | o | o | o | o | + +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+ + | :ref:`newton ` | x | o | | x | | o | | o | o | o | o | + +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+ + | :ref:`halley ` | x | o | | x | | x | x | o | o | o | o | + +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+ + + Examples + -------- + + Find the root of a simple cubic + + >>> from scipy import optimize + >>> def f(x): + ... return (x**3 - 1) # only one real root at x = 1 + + >>> def fprime(x): + ... return 3*x**2 + + The `brentq` method takes as input a bracket + + >>> sol = optimize.root_scalar(f, bracket=[0, 3], method='brentq') + >>> sol.root, sol.iterations, sol.function_calls + (1.0, 10, 11) + + The `newton` method takes as input a single point and uses the + derivative(s). + + >>> sol = optimize.root_scalar(f, x0=0.2, fprime=fprime, method='newton') + >>> sol.root, sol.iterations, sol.function_calls + (1.0, 11, 22) + + The function can provide the value and derivative(s) in a single call. + + >>> def f_p_pp(x): + ... return (x**3 - 1), 3*x**2, 6*x + + >>> sol = optimize.root_scalar( + ... f_p_pp, x0=0.2, fprime=True, method='newton' + ... ) + >>> sol.root, sol.iterations, sol.function_calls + (1.0, 11, 11) + + >>> sol = optimize.root_scalar( + ... f_p_pp, x0=0.2, fprime=True, fprime2=True, method='halley' + ... ) + >>> sol.root, sol.iterations, sol.function_calls + (1.0, 7, 8) + + + """ # noqa: E501 + if not isinstance(args, tuple): + args = (args,) + + if options is None: + options = {} + + # fun also returns the derivative(s) + is_memoized = False + if fprime2 is not None and not callable(fprime2): + if bool(fprime2): + f = MemoizeDer(f) + is_memoized = True + fprime2 = f.fprime2 + fprime = f.fprime + else: + fprime2 = None + if fprime is not None and not callable(fprime): + if bool(fprime): + f = MemoizeDer(f) + is_memoized = True + fprime = f.fprime + else: + fprime = None + + # respect solver-specific default tolerances - only pass in if actually set + kwargs = {} + for k in ['xtol', 'rtol', 'maxiter']: + v = locals().get(k) + if v is not None: + kwargs[k] = v + + # Set any solver-specific options + if options: + kwargs.update(options) + # Always request full_output from the underlying method as _root_scalar + # always returns a RootResults object + kwargs.update(full_output=True, disp=False) + + # Pick a method if not specified. + # Use the "best" method available for the situation. + if not method: + if bracket is not None: + method = 'brentq' + elif x0 is not None: + if fprime: + if fprime2: + method = 'halley' + else: + method = 'newton' + elif x1 is not None: + method = 'secant' + else: + method = 'newton' + if not method: + raise ValueError('Unable to select a solver as neither bracket ' + 'nor starting point provided.') + + meth = method.lower() + map2underlying = {'halley': 'newton', 'secant': 'newton'} + + try: + methodc = getattr(optzeros, map2underlying.get(meth, meth)) + except AttributeError as e: + raise ValueError(f'Unknown solver {meth}') from e + + if meth in ['bisect', 'ridder', 'brentq', 'brenth', 'toms748']: + if not isinstance(bracket, (list, tuple, np.ndarray)): + raise ValueError(f'Bracket needed for {method}') + + a, b = bracket[:2] + try: + r, sol = methodc(f, a, b, args=args, **kwargs) + except ValueError as e: + # gh-17622 fixed some bugs in low-level solvers by raising an error + # (rather than returning incorrect results) when the callable + # returns a NaN. It did so by wrapping the callable rather than + # modifying compiled code, so the iteration count is not available. + if hasattr(e, "_x"): + sol = optzeros.RootResults(root=e._x, + iterations=np.nan, + function_calls=e._function_calls, + flag=str(e), method=method) + else: + raise + + elif meth in ['secant']: + if x0 is None: + raise ValueError(f'x0 must not be None for {method}') + if 'xtol' in kwargs: + kwargs['tol'] = kwargs.pop('xtol') + r, sol = methodc(f, x0, args=args, fprime=None, fprime2=None, + x1=x1, **kwargs) + elif meth in ['newton']: + if x0 is None: + raise ValueError(f'x0 must not be None for {method}') + if not fprime: + # approximate fprime with finite differences + + def fprime(x, *args): + # `root_scalar` doesn't actually seem to support vectorized + # use of `newton`. In that case, `approx_derivative` will + # always get scalar input. Nonetheless, it always returns an + # array, so we extract the element to produce scalar output. + # Similarly, `approx_derivative` always passes array input, so + # we extract the element to ensure the user's function gets + # scalar input. + def f_wrapped(x, *args): + return f(x[0], *args) + return approx_derivative(f_wrapped, x, method='2-point', args=args)[0] + + if 'xtol' in kwargs: + kwargs['tol'] = kwargs.pop('xtol') + r, sol = methodc(f, x0, args=args, fprime=fprime, fprime2=None, + **kwargs) + elif meth in ['halley']: + if x0 is None: + raise ValueError(f'x0 must not be None for {method}') + if not fprime: + raise ValueError(f'fprime must be specified for {method}') + if not fprime2: + raise ValueError(f'fprime2 must be specified for {method}') + if 'xtol' in kwargs: + kwargs['tol'] = kwargs.pop('xtol') + r, sol = methodc(f, x0, args=args, fprime=fprime, fprime2=fprime2, **kwargs) + else: + raise ValueError(f'Unknown solver {method}') + + if is_memoized: + # Replace the function_calls count with the memoized count. + # Avoids double and triple-counting. + n_calls = f.n_calls + sol.function_calls = n_calls + + return sol + + +def _root_scalar_brentq_doc(): + r""" + Options + ------- + args : tuple, optional + Extra arguments passed to the objective function. + bracket: A sequence of 2 floats, optional + An interval bracketing a root. ``f(x, *args)`` must have different + signs at the two endpoints. + xtol : float, optional + Tolerance (absolute) for termination. + rtol : float, optional + Tolerance (relative) for termination. + maxiter : int, optional + Maximum number of iterations. + options: dict, optional + Specifies any method-specific options not covered above + + """ + pass + + +def _root_scalar_brenth_doc(): + r""" + Options + ------- + args : tuple, optional + Extra arguments passed to the objective function. + bracket: A sequence of 2 floats, optional + An interval bracketing a root. ``f(x, *args)`` must have different + signs at the two endpoints. + xtol : float, optional + Tolerance (absolute) for termination. + rtol : float, optional + Tolerance (relative) for termination. + maxiter : int, optional + Maximum number of iterations. + options: dict, optional + Specifies any method-specific options not covered above. + + """ + pass + +def _root_scalar_toms748_doc(): + r""" + Options + ------- + args : tuple, optional + Extra arguments passed to the objective function. + bracket: A sequence of 2 floats, optional + An interval bracketing a root. ``f(x, *args)`` must have different + signs at the two endpoints. + xtol : float, optional + Tolerance (absolute) for termination. + rtol : float, optional + Tolerance (relative) for termination. + maxiter : int, optional + Maximum number of iterations. + options: dict, optional + Specifies any method-specific options not covered above. + + """ + pass + + +def _root_scalar_secant_doc(): + r""" + Options + ------- + args : tuple, optional + Extra arguments passed to the objective function. + xtol : float, optional + Tolerance (absolute) for termination. + rtol : float, optional + Tolerance (relative) for termination. + maxiter : int, optional + Maximum number of iterations. + x0 : float, required + Initial guess. + x1 : float, optional + A second guess. Must be different from `x0`. If not specified, + a value near `x0` will be chosen. + options: dict, optional + Specifies any method-specific options not covered above. + + """ + pass + + +def _root_scalar_newton_doc(): + r""" + Options + ------- + args : tuple, optional + Extra arguments passed to the objective function and its derivative. + xtol : float, optional + Tolerance (absolute) for termination. + rtol : float, optional + Tolerance (relative) for termination. + maxiter : int, optional + Maximum number of iterations. + x0 : float, required + Initial guess. + fprime : bool or callable, optional + If `fprime` is a boolean and is True, `f` is assumed to return the + value of derivative along with the objective function. + `fprime` can also be a callable returning the derivative of `f`. In + this case, it must accept the same arguments as `f`. + options: dict, optional + Specifies any method-specific options not covered above. + + """ + pass + + +def _root_scalar_halley_doc(): + r""" + Options + ------- + args : tuple, optional + Extra arguments passed to the objective function and its derivatives. + xtol : float, optional + Tolerance (absolute) for termination. + rtol : float, optional + Tolerance (relative) for termination. + maxiter : int, optional + Maximum number of iterations. + x0 : float, required + Initial guess. + fprime : bool or callable, required + If `fprime` is a boolean and is True, `f` is assumed to return the + value of derivative along with the objective function. + `fprime` can also be a callable returning the derivative of `f`. In + this case, it must accept the same arguments as `f`. + fprime2 : bool or callable, required + If `fprime2` is a boolean and is True, `f` is assumed to return the + value of 1st and 2nd derivatives along with the objective function. + `fprime2` can also be a callable returning the 2nd derivative of `f`. + In this case, it must accept the same arguments as `f`. + options: dict, optional + Specifies any method-specific options not covered above. + + """ + pass + + +def _root_scalar_ridder_doc(): + r""" + Options + ------- + args : tuple, optional + Extra arguments passed to the objective function. + bracket: A sequence of 2 floats, optional + An interval bracketing a root. ``f(x, *args)`` must have different + signs at the two endpoints. + xtol : float, optional + Tolerance (absolute) for termination. + rtol : float, optional + Tolerance (relative) for termination. + maxiter : int, optional + Maximum number of iterations. + options: dict, optional + Specifies any method-specific options not covered above. + + """ + pass + + +def _root_scalar_bisect_doc(): + r""" + Options + ------- + args : tuple, optional + Extra arguments passed to the objective function. + bracket: A sequence of 2 floats, optional + An interval bracketing a root. ``f(x, *args)`` must have different + signs at the two endpoints. + xtol : float, optional + Tolerance (absolute) for termination. + rtol : float, optional + Tolerance (relative) for termination. + maxiter : int, optional + Maximum number of iterations. + options: dict, optional + Specifies any method-specific options not covered above. + + """ + pass diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_shgo.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_shgo.py new file mode 100644 index 0000000000000000000000000000000000000000..9e9f37ce003ba42df054e25f03fbcdfe1478a423 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_shgo.py @@ -0,0 +1,1600 @@ +"""shgo: The simplicial homology global optimisation algorithm.""" +from collections import namedtuple +import time +import logging +import warnings +import sys + +import numpy as np + +from scipy import spatial +from scipy.optimize import OptimizeResult, minimize, Bounds +from scipy.optimize._optimize import MemoizeJac +from scipy.optimize._constraints import new_bounds_to_old +from scipy.optimize._minimize import standardize_constraints +from scipy._lib._util import _FunctionWrapper + +from scipy.optimize._shgo_lib._complex import Complex + +__all__ = ['shgo'] + + +def shgo( + func, bounds, args=(), constraints=None, n=100, iters=1, callback=None, + minimizer_kwargs=None, options=None, sampling_method='simplicial', *, + workers=1 +): + """ + Finds the global minimum of a function using SHG optimization. + + SHGO stands for "simplicial homology global optimization". + + Parameters + ---------- + func : callable + The objective function to be minimized. Must be in the form + ``f(x, *args)``, where ``x`` is the argument in the form of a 1-D array + and ``args`` is a tuple of any additional fixed parameters needed to + completely specify the function. + bounds : sequence or `Bounds` + Bounds for variables. There are two ways to specify the bounds: + + 1. Instance of `Bounds` class. + 2. Sequence of ``(min, max)`` pairs for each element in `x`. + + args : tuple, optional + Any additional fixed parameters needed to completely specify the + objective function. + constraints : {Constraint, dict} or List of {Constraint, dict}, optional + Constraints definition. Only for COBYLA, COBYQA, SLSQP and trust-constr. + See the tutorial [5]_ for further details on specifying constraints. + + .. note:: + + Only COBYLA, COBYQA, SLSQP, and trust-constr local minimize methods + currently support constraint arguments. If the ``constraints`` + sequence used in the local optimization problem is not defined in + ``minimizer_kwargs`` and a constrained method is used then the + global ``constraints`` will be used. + (Defining a ``constraints`` sequence in ``minimizer_kwargs`` + means that ``constraints`` will not be added so if equality + constraints and so forth need to be added then the inequality + functions in ``constraints`` need to be added to + ``minimizer_kwargs`` too). + COBYLA only supports inequality constraints. + + .. versionchanged:: 1.11.0 + + ``constraints`` accepts `NonlinearConstraint`, `LinearConstraint`. + + n : int, optional + Number of sampling points used in the construction of the simplicial + complex. For the default ``simplicial`` sampling method 2**dim + 1 + sampling points are generated instead of the default ``n=100``. For all + other specified values `n` sampling points are generated. For + ``sobol``, ``halton`` and other arbitrary `sampling_methods` ``n=100`` or + another specified number of sampling points are generated. + iters : int, optional + Number of iterations used in the construction of the simplicial + complex. Default is 1. + callback : callable, optional + Called after each iteration, as ``callback(xk)``, where ``xk`` is the + current parameter vector. + minimizer_kwargs : dict, optional + Extra keyword arguments to be passed to the minimizer + ``scipy.optimize.minimize``. Some important options could be: + + method : str + The minimization method. If not given, chosen to be one of + BFGS, L-BFGS-B, SLSQP, depending on whether or not the + problem has constraints or bounds. + args : tuple + Extra arguments passed to the objective function (``func``) and + its derivatives (Jacobian, Hessian). + options : dict, optional + Note that by default the tolerance is specified as + ``{ftol: 1e-12}`` + + options : dict, optional + A dictionary of solver options. Many of the options specified for the + global routine are also passed to the ``scipy.optimize.minimize`` + routine. The options that are also passed to the local routine are + marked with "(L)". + + Stopping criteria, the algorithm will terminate if any of the specified + criteria are met. However, the default algorithm does not require any + to be specified: + + maxfev : int (L) + Maximum number of function evaluations in the feasible domain. + (Note only methods that support this option will terminate + the routine at precisely exact specified value. Otherwise the + criterion will only terminate during a global iteration) + f_min : float + Specify the minimum objective function value, if it is known. + f_tol : float + Precision goal for the value of f in the stopping + criterion. Note that the global routine will also + terminate if a sampling point in the global routine is + within this tolerance. + maxiter : int + Maximum number of iterations to perform. + maxev : int + Maximum number of sampling evaluations to perform (includes + searching in infeasible points). + maxtime : float + Maximum processing runtime allowed + minhgrd : int + Minimum homology group rank differential. The homology group of the + objective function is calculated (approximately) during every + iteration. The rank of this group has a one-to-one correspondence + with the number of locally convex subdomains in the objective + function (after adequate sampling points each of these subdomains + contain a unique global minimum). If the difference in the hgr is 0 + between iterations for ``maxhgrd`` specified iterations the + algorithm will terminate. + + Objective function knowledge: + + symmetry : list or bool + Specify if the objective function contains symmetric variables. + The search space (and therefore performance) is decreased by up to + O(n!) times in the fully symmetric case. If `True` is specified + then all variables will be set symmetric to the first variable. + Default + is set to False. + + E.g. f(x) = (x_1 + x_2 + x_3) + (x_4)**2 + (x_5)**2 + (x_6)**2 + + In this equation x_2 and x_3 are symmetric to x_1, while x_5 and + x_6 are symmetric to x_4, this can be specified to the solver as:: + + symmetry = [0, # Variable 1 + 0, # symmetric to variable 1 + 0, # symmetric to variable 1 + 3, # Variable 4 + 3, # symmetric to variable 4 + 3, # symmetric to variable 4 + ] + + jac : bool or callable, optional + Jacobian (gradient) of objective function. Only for CG, BFGS, + Newton-CG, L-BFGS-B, TNC, SLSQP, dogleg, trust-ncg. If ``jac`` is a + boolean and is True, ``fun`` is assumed to return the gradient + along with the objective function. If False, the gradient will be + estimated numerically. ``jac`` can also be a callable returning the + gradient of the objective. In this case, it must accept the same + arguments as ``fun``. (Passed to `scipy.optimize.minimize` + automatically) + + hess, hessp : callable, optional + Hessian (matrix of second-order derivatives) of objective function + or Hessian of objective function times an arbitrary vector p. + Only for Newton-CG, dogleg, trust-ncg. Only one of ``hessp`` or + ``hess`` needs to be given. If ``hess`` is provided, then + ``hessp`` will be ignored. If neither ``hess`` nor ``hessp`` is + provided, then the Hessian product will be approximated using + finite differences on ``jac``. ``hessp`` must compute the Hessian + times an arbitrary vector. (Passed to `scipy.optimize.minimize` + automatically) + + Algorithm settings: + + minimize_every_iter : bool + If True then promising global sampling points will be passed to a + local minimization routine every iteration. If True then only the + final minimizer pool will be run. Defaults to True. + + local_iter : int + Only evaluate a few of the best minimizer pool candidates every + iteration. If False all potential points are passed to the local + minimization routine. + + infty_constraints : bool + If True then any sampling points generated which are outside will + the feasible domain will be saved and given an objective function + value of ``inf``. If False then these points will be discarded. + Using this functionality could lead to higher performance with + respect to function evaluations before the global minimum is found, + specifying False will use less memory at the cost of a slight + decrease in performance. Defaults to True. + + Feedback: + + disp : bool (L) + Set to True to print convergence messages. + + sampling_method : str or function, optional + Current built in sampling method options are ``halton``, ``sobol`` and + ``simplicial``. The default ``simplicial`` provides + the theoretical guarantee of convergence to the global minimum in + finite time. ``halton`` and ``sobol`` method are faster in terms of + sampling point generation at the cost of the loss of + guaranteed convergence. It is more appropriate for most "easier" + problems where the convergence is relatively fast. + User defined sampling functions must accept two arguments of ``n`` + sampling points of dimension ``dim`` per call and output an array of + sampling points with shape `n x dim`. + + workers : int or map-like callable, optional + Sample and run the local serial minimizations in parallel. + Supply -1 to use all available CPU cores, or an int to use + that many Processes (uses `multiprocessing.Pool `). + + Alternatively supply a map-like callable, such as + `multiprocessing.Pool.map` for parallel evaluation. + This evaluation is carried out as ``workers(func, iterable)``. + Requires that `func` be pickleable. + + .. versionadded:: 1.11.0 + + Returns + ------- + res : OptimizeResult + The optimization result represented as a `OptimizeResult` object. + Important attributes are: + ``x`` the solution array corresponding to the global minimum, + ``fun`` the function output at the global solution, + ``xl`` an ordered list of local minima solutions, + ``funl`` the function output at the corresponding local solutions, + ``success`` a Boolean flag indicating if the optimizer exited + successfully, + ``message`` which describes the cause of the termination, + ``nfev`` the total number of objective function evaluations including + the sampling calls, + ``nlfev`` the total number of objective function evaluations + culminating from all local search optimizations, + ``nit`` number of iterations performed by the global routine. + + Notes + ----- + Global optimization using simplicial homology global optimization [1]_. + Appropriate for solving general purpose NLP and blackbox optimization + problems to global optimality (low-dimensional problems). + + In general, the optimization problems are of the form:: + + minimize f(x) subject to + + g_i(x) >= 0, i = 1,...,m + h_j(x) = 0, j = 1,...,p + + where x is a vector of one or more variables. ``f(x)`` is the objective + function ``R^n -> R``, ``g_i(x)`` are the inequality constraints, and + ``h_j(x)`` are the equality constraints. + + Optionally, the lower and upper bounds for each element in x can also be + specified using the `bounds` argument. + + While most of the theoretical advantages of SHGO are only proven for when + ``f(x)`` is a Lipschitz smooth function, the algorithm is also proven to + converge to the global optimum for the more general case where ``f(x)`` is + non-continuous, non-convex and non-smooth, if the default sampling method + is used [1]_. + + The local search method may be specified using the ``minimizer_kwargs`` + parameter which is passed on to ``scipy.optimize.minimize``. By default, + the ``SLSQP`` method is used. In general, it is recommended to use the + ``SLSQP``, ``COBYLA``, or ``COBYQA`` local minimization if inequality + constraints are defined for the problem since the other methods do not use + constraints. + + The ``halton`` and ``sobol`` method points are generated using + `scipy.stats.qmc`. Any other QMC method could be used. + + References + ---------- + .. [1] Endres, SC, Sandrock, C, Focke, WW (2018) "A simplicial homology + algorithm for lipschitz optimisation", Journal of Global + Optimization. + .. [2] Joe, SW and Kuo, FY (2008) "Constructing Sobol' sequences with + better two-dimensional projections", SIAM J. Sci. Comput. 30, + 2635-2654. + .. [3] Hock, W and Schittkowski, K (1981) "Test examples for nonlinear + programming codes", Lecture Notes in Economics and Mathematical + Systems, 187. Springer-Verlag, New York. + http://www.ai7.uni-bayreuth.de/test_problem_coll.pdf + .. [4] Wales, DJ (2015) "Perspective: Insight into reaction coordinates and + dynamics from the potential energy landscape", + Journal of Chemical Physics, 142(13), 2015. + .. [5] https://docs.scipy.org/doc/scipy/tutorial/optimize.html#constrained-minimization-of-multivariate-scalar-functions-minimize + + Examples + -------- + First consider the problem of minimizing the Rosenbrock function, `rosen`: + + >>> from scipy.optimize import rosen, shgo + >>> bounds = [(0,2), (0, 2), (0, 2), (0, 2), (0, 2)] + >>> result = shgo(rosen, bounds) + >>> result.x, result.fun + (array([1., 1., 1., 1., 1.]), 2.920392374190081e-18) + + Note that bounds determine the dimensionality of the objective + function and is therefore a required input, however you can specify + empty bounds using ``None`` or objects like ``np.inf`` which will be + converted to large float numbers. + + >>> bounds = [(None, None), ]*4 + >>> result = shgo(rosen, bounds) + >>> result.x + array([0.99999851, 0.99999704, 0.99999411, 0.9999882 ]) + + Next, we consider the Eggholder function, a problem with several local + minima and one global minimum. We will demonstrate the use of arguments and + the capabilities of `shgo`. + (https://en.wikipedia.org/wiki/Test_functions_for_optimization) + + >>> import numpy as np + >>> def eggholder(x): + ... return (-(x[1] + 47.0) + ... * np.sin(np.sqrt(abs(x[0]/2.0 + (x[1] + 47.0)))) + ... - x[0] * np.sin(np.sqrt(abs(x[0] - (x[1] + 47.0)))) + ... ) + ... + >>> bounds = [(-512, 512), (-512, 512)] + + `shgo` has built-in low discrepancy sampling sequences. First, we will + input 64 initial sampling points of the *Sobol'* sequence: + + >>> result = shgo(eggholder, bounds, n=64, sampling_method='sobol') + >>> result.x, result.fun + (array([512. , 404.23180824]), -959.6406627208397) + + `shgo` also has a return for any other local minima that was found, these + can be called using: + + >>> result.xl + array([[ 512. , 404.23180824], + [ 283.0759062 , -487.12565635], + [-294.66820039, -462.01964031], + [-105.87688911, 423.15323845], + [-242.97926 , 274.38030925], + [-506.25823477, 6.3131022 ], + [-408.71980731, -156.10116949], + [ 150.23207937, 301.31376595], + [ 91.00920901, -391.283763 ], + [ 202.89662724, -269.38043241], + [ 361.66623976, -106.96493868], + [-219.40612786, -244.06020508]]) + + >>> result.funl + array([-959.64066272, -718.16745962, -704.80659592, -565.99778097, + -559.78685655, -557.36868733, -507.87385942, -493.9605115 , + -426.48799655, -421.15571437, -419.31194957, -410.98477763]) + + These results are useful in applications where there are many global minima + and the values of other global minima are desired or where the local minima + can provide insight into the system (for example morphologies + in physical chemistry [4]_). + + If we want to find a larger number of local minima, we can increase the + number of sampling points or the number of iterations. We'll increase the + number of sampling points to 64 and the number of iterations from the + default of 1 to 3. Using ``simplicial`` this would have given us + 64 x 3 = 192 initial sampling points. + + >>> result_2 = shgo(eggholder, + ... bounds, n=64, iters=3, sampling_method='sobol') + >>> len(result.xl), len(result_2.xl) + (12, 23) + + Note the difference between, e.g., ``n=192, iters=1`` and ``n=64, + iters=3``. + In the first case the promising points contained in the minimiser pool + are processed only once. In the latter case it is processed every 64 + sampling points for a total of 3 times. + + To demonstrate solving problems with non-linear constraints consider the + following example from Hock and Schittkowski problem 73 (cattle-feed) + [3]_:: + + minimize: f = 24.55 * x_1 + 26.75 * x_2 + 39 * x_3 + 40.50 * x_4 + + subject to: 2.3 * x_1 + 5.6 * x_2 + 11.1 * x_3 + 1.3 * x_4 - 5 >= 0, + + 12 * x_1 + 11.9 * x_2 + 41.8 * x_3 + 52.1 * x_4 - 21 + -1.645 * sqrt(0.28 * x_1**2 + 0.19 * x_2**2 + + 20.5 * x_3**2 + 0.62 * x_4**2) >= 0, + + x_1 + x_2 + x_3 + x_4 - 1 == 0, + + 1 >= x_i >= 0 for all i + + The approximate answer given in [3]_ is:: + + f([0.6355216, -0.12e-11, 0.3127019, 0.05177655]) = 29.894378 + + >>> def f(x): # (cattle-feed) + ... return 24.55*x[0] + 26.75*x[1] + 39*x[2] + 40.50*x[3] + ... + >>> def g1(x): + ... return 2.3*x[0] + 5.6*x[1] + 11.1*x[2] + 1.3*x[3] - 5 # >=0 + ... + >>> def g2(x): + ... return (12*x[0] + 11.9*x[1] +41.8*x[2] + 52.1*x[3] - 21 + ... - 1.645 * np.sqrt(0.28*x[0]**2 + 0.19*x[1]**2 + ... + 20.5*x[2]**2 + 0.62*x[3]**2) + ... ) # >=0 + ... + >>> def h1(x): + ... return x[0] + x[1] + x[2] + x[3] - 1 # == 0 + ... + >>> cons = ({'type': 'ineq', 'fun': g1}, + ... {'type': 'ineq', 'fun': g2}, + ... {'type': 'eq', 'fun': h1}) + >>> bounds = [(0, 1.0),]*4 + >>> res = shgo(f, bounds, n=150, constraints=cons) + >>> res + message: Optimization terminated successfully. + success: True + fun: 29.894378159142136 + funl: [ 2.989e+01] + x: [ 6.355e-01 1.137e-13 3.127e-01 5.178e-02] # may vary + xl: [[ 6.355e-01 1.137e-13 3.127e-01 5.178e-02]] # may vary + nit: 1 + nfev: 142 # may vary + nlfev: 35 # may vary + nljev: 5 + nlhev: 0 + + >>> g1(res.x), g2(res.x), h1(res.x) + (-5.062616992290714e-14, -2.9594104944408173e-12, 0.0) + + """ + # if necessary, convert bounds class to old bounds + if isinstance(bounds, Bounds): + bounds = new_bounds_to_old(bounds.lb, bounds.ub, len(bounds.lb)) + + # Initiate SHGO class + # use in context manager to make sure that any parallelization + # resources are freed. + with SHGO(func, bounds, args=args, constraints=constraints, n=n, + iters=iters, callback=callback, + minimizer_kwargs=minimizer_kwargs, + options=options, sampling_method=sampling_method, + workers=workers) as shc: + # Run the algorithm, process results and test success + shc.iterate_all() + + if not shc.break_routine: + if shc.disp: + logging.info("Successfully completed construction of complex.") + + # Test post iterations success + if len(shc.LMC.xl_maps) == 0: + # If sampling failed to find pool, return lowest sampled point + # with a warning + shc.find_lowest_vertex() + shc.break_routine = True + shc.fail_routine(mes="Failed to find a feasible minimizer point. " + f"Lowest sampling point = {shc.f_lowest}") + shc.res.fun = shc.f_lowest + shc.res.x = shc.x_lowest + shc.res.nfev = shc.fn + shc.res.tnev = shc.n_sampled + else: + # Test that the optimal solutions do not violate any constraints + pass # TODO + + # Confirm the routine ran successfully + if not shc.break_routine: + shc.res.message = 'Optimization terminated successfully.' + shc.res.success = True + + # Return the final results + return shc.res + + +class SHGO: + def __init__(self, func, bounds, args=(), constraints=None, n=None, + iters=None, callback=None, minimizer_kwargs=None, + options=None, sampling_method='simplicial', workers=1): + from scipy.stats import qmc + # Input checks + methods = ['halton', 'sobol', 'simplicial'] + if isinstance(sampling_method, str) and sampling_method not in methods: + raise ValueError(("Unknown sampling_method specified." + " Valid methods: {}").format(', '.join(methods))) + + # Split obj func if given with Jac + try: + if ((minimizer_kwargs['jac'] is True) and + (not callable(minimizer_kwargs['jac']))): + self.func = MemoizeJac(func) + jac = self.func.derivative + minimizer_kwargs['jac'] = jac + func = self.func # .fun + else: + self.func = func # Normal definition of objective function + except (TypeError, KeyError): + self.func = func # Normal definition of objective function + + # Initiate class + self.func = _FunctionWrapper(func, args) + self.bounds = bounds + self.args = args + self.callback = callback + + # Bounds + abound = np.array(bounds, float) + self.dim = np.shape(abound)[0] # Dimensionality of problem + + # Set none finite values to large floats + infind = ~np.isfinite(abound) + abound[infind[:, 0], 0] = -1e50 + abound[infind[:, 1], 1] = 1e50 + + # Check if bounds are correctly specified + bnderr = abound[:, 0] > abound[:, 1] + if bnderr.any(): + raise ValueError("Error: lb > ub in bounds " + f"{', '.join(str(b) for b in bnderr)}.") + + self.bounds = abound + + # Constraints + # Process constraint dict sequence: + self.constraints = constraints + if constraints is not None: + self.min_cons = constraints + self.g_cons = [] + self.g_args = [] + + # shgo internals deals with old-style constraints + # self.constraints is used to create Complex, so need + # to be stored internally in old-style. + # `minimize` takes care of normalising these constraints + # for slsqp/cobyla/cobyqa/trust-constr. + self.constraints = standardize_constraints( + constraints, + np.empty(self.dim, float), + 'old' + ) + for cons in self.constraints: + if cons['type'] in ('ineq'): + self.g_cons.append(cons['fun']) + try: + self.g_args.append(cons['args']) + except KeyError: + self.g_args.append(()) + self.g_cons = tuple(self.g_cons) + self.g_args = tuple(self.g_args) + else: + self.g_cons = None + self.g_args = None + + # Define local minimization keyword arguments + # Start with defaults + self.minimizer_kwargs = {'method': 'SLSQP', + 'bounds': self.bounds, + 'options': {}, + 'callback': self.callback + } + if minimizer_kwargs is not None: + # Overwrite with supplied values + self.minimizer_kwargs.update(minimizer_kwargs) + + else: + self.minimizer_kwargs['options'] = {'ftol': 1e-12} + + if ( + self.minimizer_kwargs['method'].lower() in ('slsqp', 'cobyla', + 'cobyqa', + 'trust-constr') + and ( + minimizer_kwargs is not None and + 'constraints' not in minimizer_kwargs and + constraints is not None + ) or + (self.g_cons is not None) + ): + self.minimizer_kwargs['constraints'] = self.min_cons + + # Process options dict + if options is not None: + self.init_options(options) + else: # Default settings: + self.f_min_true = None + self.minimize_every_iter = True + + # Algorithm limits + self.maxiter = None + self.maxfev = None + self.maxev = None + self.maxtime = None + self.f_min_true = None + self.minhgrd = None + + # Objective function knowledge + self.symmetry = None + + # Algorithm functionality + self.infty_cons_sampl = True + self.local_iter = False + + # Feedback + self.disp = False + + # Remove unknown arguments in self.minimizer_kwargs + # Start with arguments all the solvers have in common + self.min_solver_args = ['fun', 'x0', 'args', + 'callback', 'options', 'method'] + # then add the ones unique to specific solvers + solver_args = { + '_custom': ['jac', 'hess', 'hessp', 'bounds', 'constraints'], + 'nelder-mead': [], + 'powell': [], + 'cg': ['jac'], + 'bfgs': ['jac'], + 'newton-cg': ['jac', 'hess', 'hessp'], + 'l-bfgs-b': ['jac', 'bounds'], + 'tnc': ['jac', 'bounds'], + 'cobyla': ['constraints', 'catol'], + 'cobyqa': ['bounds', 'constraints', 'feasibility_tol'], + 'slsqp': ['jac', 'bounds', 'constraints'], + 'dogleg': ['jac', 'hess'], + 'trust-ncg': ['jac', 'hess', 'hessp'], + 'trust-krylov': ['jac', 'hess', 'hessp'], + 'trust-exact': ['jac', 'hess'], + 'trust-constr': ['jac', 'hess', 'hessp', 'constraints'], + } + method = self.minimizer_kwargs['method'] + self.min_solver_args += solver_args[method.lower()] + + # Only retain the known arguments + def _restrict_to_keys(dictionary, goodkeys): + """Remove keys from dictionary if not in goodkeys - inplace""" + existingkeys = set(dictionary) + for key in existingkeys - set(goodkeys): + dictionary.pop(key, None) + + _restrict_to_keys(self.minimizer_kwargs, self.min_solver_args) + _restrict_to_keys(self.minimizer_kwargs['options'], + self.min_solver_args + ['ftol']) + + # Algorithm controls + # Global controls + self.stop_global = False # Used in the stopping_criteria method + self.break_routine = False # Break the algorithm globally + self.iters = iters # Iterations to be ran + self.iters_done = 0 # Iterations completed + self.n = n # Sampling points per iteration + self.nc = 0 # n # Sampling points to sample in current iteration + self.n_prc = 0 # Processed points (used to track Delaunay iters) + self.n_sampled = 0 # To track no. of sampling points already generated + self.fn = 0 # Number of feasible sampling points evaluations performed + self.hgr = 0 # Homology group rank + # Initially attempt to build the triangulation incrementally: + self.qhull_incremental = True + + # Default settings if no sampling criteria. + if (self.n is None) and (self.iters is None) \ + and (sampling_method == 'simplicial'): + self.n = 2 ** self.dim + 1 + self.nc = 0 # self.n + if self.iters is None: + self.iters = 1 + if (self.n is None) and not (sampling_method == 'simplicial'): + self.n = self.n = 100 + self.nc = 0 # self.n + if (self.n == 100) and (sampling_method == 'simplicial'): + self.n = 2 ** self.dim + 1 + + if not ((self.maxiter is None) and (self.maxfev is None) and ( + self.maxev is None) + and (self.minhgrd is None) and (self.f_min_true is None)): + self.iters = None + + # Set complex construction mode based on a provided stopping criteria: + # Initialise sampling Complex and function cache + # Note that sfield_args=() since args are already wrapped in self.func + # using the_FunctionWrapper class. + self.HC = Complex(dim=self.dim, domain=self.bounds, + sfield=self.func, sfield_args=(), + symmetry=self.symmetry, + constraints=self.constraints, + workers=workers) + + # Choose complex constructor + if sampling_method == 'simplicial': + self.iterate_complex = self.iterate_hypercube + self.sampling_method = sampling_method + + elif sampling_method in ['halton', 'sobol'] or \ + not isinstance(sampling_method, str): + self.iterate_complex = self.iterate_delaunay + # Sampling method used + if sampling_method in ['halton', 'sobol']: + if sampling_method == 'sobol': + self.n = int(2 ** np.ceil(np.log2(self.n))) + # self.n #TODO: Should always be self.n, this is + # unacceptable for shgo, check that nfev behaves as + # expected. + self.nc = 0 + self.sampling_method = 'sobol' + self.qmc_engine = qmc.Sobol(d=self.dim, scramble=False, + seed=0) + else: + self.sampling_method = 'halton' + self.qmc_engine = qmc.Halton(d=self.dim, scramble=True, + seed=0) + + def sampling_method(n, d): + return self.qmc_engine.random(n) + + else: + # A user defined sampling method: + self.sampling_method = 'custom' + + self.sampling = self.sampling_custom + self.sampling_function = sampling_method # F(n, d) + + # Local controls + self.stop_l_iter = False # Local minimisation iterations + self.stop_complex_iter = False # Sampling iterations + + # Initiate storage objects used in algorithm classes + self.minimizer_pool = [] + + # Cache of local minimizers mapped + self.LMC = LMapCache() + + # Initialize return object + self.res = OptimizeResult() # scipy.optimize.OptimizeResult object + self.res.nfev = 0 # Includes each sampling point as func evaluation + self.res.nlfev = 0 # Local function evals for all minimisers + self.res.nljev = 0 # Local Jacobian evals for all minimisers + self.res.nlhev = 0 # Local Hessian evals for all minimisers + + # Initiation aids + def init_options(self, options): + """ + Initiates the options. + + Can also be useful to change parameters after class initiation. + + Parameters + ---------- + options : dict + + Returns + ------- + None + + """ + # Update 'options' dict passed to optimize.minimize + # Do this first so we don't mutate `options` below. + self.minimizer_kwargs['options'].update(options) + + # Ensure that 'jac', 'hess', and 'hessp' are passed directly to + # `minimize` as keywords, not as part of its 'options' dictionary. + for opt in ['jac', 'hess', 'hessp']: + if opt in self.minimizer_kwargs['options']: + self.minimizer_kwargs[opt] = ( + self.minimizer_kwargs['options'].pop(opt)) + + # Default settings: + self.minimize_every_iter = options.get('minimize_every_iter', True) + + # Algorithm limits + # Maximum number of iterations to perform. + self.maxiter = options.get('maxiter', None) + # Maximum number of function evaluations in the feasible domain + self.maxfev = options.get('maxfev', None) + # Maximum number of sampling evaluations (includes searching in + # infeasible points + self.maxev = options.get('maxev', None) + # Maximum processing runtime allowed + self.init = time.time() + self.maxtime = options.get('maxtime', None) + if 'f_min' in options: + # Specify the minimum objective function value, if it is known. + self.f_min_true = options['f_min'] + self.f_tol = options.get('f_tol', 1e-4) + else: + self.f_min_true = None + + self.minhgrd = options.get('minhgrd', None) + + # Objective function knowledge + self.symmetry = options.get('symmetry', False) + if self.symmetry: + self.symmetry = [0, ]*len(self.bounds) + else: + self.symmetry = None + # Algorithm functionality + # Only evaluate a few of the best candidates + self.local_iter = options.get('local_iter', False) + self.infty_cons_sampl = options.get('infty_constraints', True) + + # Feedback + self.disp = options.get('disp', False) + + def __enter__(self): + return self + + def __exit__(self, *args): + return self.HC.V._mapwrapper.__exit__(*args) + + # Iteration properties + # Main construction loop: + def iterate_all(self): + """ + Construct for `iters` iterations. + + If uniform sampling is used, every iteration adds 'n' sampling points. + + Iterations if a stopping criteria (e.g., sampling points or + processing time) has been met. + + """ + if self.disp: + logging.info('Splitting first generation') + + while not self.stop_global: + if self.break_routine: + break + # Iterate complex, process minimisers + self.iterate() + self.stopping_criteria() + + # Build minimiser pool + # Final iteration only needed if pools weren't minimised every + # iteration + if not self.minimize_every_iter: + if not self.break_routine: + self.find_minima() + + self.res.nit = self.iters_done # + 1 + self.fn = self.HC.V.nfev + + def find_minima(self): + """ + Construct the minimizer pool, map the minimizers to local minima + and sort the results into a global return object. + """ + if self.disp: + logging.info('Searching for minimizer pool...') + + self.minimizers() + + if len(self.X_min) != 0: + # Minimize the pool of minimizers with local minimization methods + # Note that if Options['local_iter'] is an `int` instead of default + # value False then only that number of candidates will be minimized + self.minimise_pool(self.local_iter) + # Sort results and build the global return object + self.sort_result() + + # Lowest values used to report in case of failures + self.f_lowest = self.res.fun + self.x_lowest = self.res.x + else: + self.find_lowest_vertex() + + if self.disp: + logging.info(f"Minimiser pool = SHGO.X_min = {self.X_min}") + + def find_lowest_vertex(self): + # Find the lowest objective function value on one of + # the vertices of the simplicial complex + self.f_lowest = np.inf + for x in self.HC.V.cache: + if self.HC.V[x].f < self.f_lowest: + if self.disp: + logging.info(f'self.HC.V[x].f = {self.HC.V[x].f}') + self.f_lowest = self.HC.V[x].f + self.x_lowest = self.HC.V[x].x_a + for lmc in self.LMC.cache: + if self.LMC[lmc].f_min < self.f_lowest: + self.f_lowest = self.LMC[lmc].f_min + self.x_lowest = self.LMC[lmc].x_l + + if self.f_lowest == np.inf: # no feasible point + self.f_lowest = None + self.x_lowest = None + + # Stopping criteria functions: + def finite_iterations(self): + mi = min(x for x in [self.iters, self.maxiter] if x is not None) + if self.disp: + logging.info(f'Iterations done = {self.iters_done} / {mi}') + if self.iters is not None: + if self.iters_done >= (self.iters): + self.stop_global = True + + if self.maxiter is not None: # Stop for infeasible sampling + if self.iters_done >= (self.maxiter): + self.stop_global = True + return self.stop_global + + def finite_fev(self): + # Finite function evals in the feasible domain + if self.disp: + logging.info(f'Function evaluations done = {self.fn} / {self.maxfev}') + if self.fn >= self.maxfev: + self.stop_global = True + return self.stop_global + + def finite_ev(self): + # Finite evaluations including infeasible sampling points + if self.disp: + logging.info(f'Sampling evaluations done = {self.n_sampled} ' + f'/ {self.maxev}') + if self.n_sampled >= self.maxev: + self.stop_global = True + + def finite_time(self): + if self.disp: + logging.info(f'Time elapsed = {time.time() - self.init} ' + f'/ {self.maxtime}') + if (time.time() - self.init) >= self.maxtime: + self.stop_global = True + + def finite_precision(self): + """ + Stop the algorithm if the final function value is known + + Specify in options (with ``self.f_min_true = options['f_min']``) + and the tolerance with ``f_tol = options['f_tol']`` + """ + # If no minimizer has been found use the lowest sampling value + self.find_lowest_vertex() + if self.disp: + logging.info(f'Lowest function evaluation = {self.f_lowest}') + logging.info(f'Specified minimum = {self.f_min_true}') + # If no feasible point was return from test + if self.f_lowest is None: + return self.stop_global + + # Function to stop algorithm at specified percentage error: + if self.f_min_true == 0.0: + if self.f_lowest <= self.f_tol: + self.stop_global = True + else: + pe = (self.f_lowest - self.f_min_true) / abs(self.f_min_true) + if self.f_lowest <= self.f_min_true: + self.stop_global = True + # 2if (pe - self.f_tol) <= abs(1.0 / abs(self.f_min_true)): + if abs(pe) >= 2 * self.f_tol: + warnings.warn( + f"A much lower value than expected f* = {self.f_min_true} " + f"was found f_lowest = {self.f_lowest}", + stacklevel=3 + ) + if pe <= self.f_tol: + self.stop_global = True + + return self.stop_global + + def finite_homology_growth(self): + """ + Stop the algorithm if homology group rank did not grow in iteration. + """ + if self.LMC.size == 0: + return # pass on no reason to stop yet. + self.hgrd = self.LMC.size - self.hgr + + self.hgr = self.LMC.size + if self.hgrd <= self.minhgrd: + self.stop_global = True + if self.disp: + logging.info(f'Current homology growth = {self.hgrd} ' + f' (minimum growth = {self.minhgrd})') + return self.stop_global + + def stopping_criteria(self): + """ + Various stopping criteria ran every iteration + + Returns + ------- + stop : bool + """ + if self.maxiter is not None: + self.finite_iterations() + if self.iters is not None: + self.finite_iterations() + if self.maxfev is not None: + self.finite_fev() + if self.maxev is not None: + self.finite_ev() + if self.maxtime is not None: + self.finite_time() + if self.f_min_true is not None: + self.finite_precision() + if self.minhgrd is not None: + self.finite_homology_growth() + return self.stop_global + + def iterate(self): + self.iterate_complex() + + # Build minimizer pool + if self.minimize_every_iter: + if not self.break_routine: + self.find_minima() # Process minimizer pool + + # Algorithm updates + self.iters_done += 1 + + def iterate_hypercube(self): + """ + Iterate a subdivision of the complex + + Note: called with ``self.iterate_complex()`` after class initiation + """ + # Iterate the complex + if self.disp: + logging.info('Constructing and refining simplicial complex graph ' + 'structure') + if self.n is None: + self.HC.refine_all() + self.n_sampled = self.HC.V.size() # nevs counted + else: + self.HC.refine(self.n) + self.n_sampled += self.n + + if self.disp: + logging.info('Triangulation completed, evaluating all constraints ' + 'and objective function values.') + + # Re-add minimisers to complex + if len(self.LMC.xl_maps) > 0: + for xl in self.LMC.cache: + v = self.HC.V[xl] + v_near = v.star() + for v in v.nn: + v_near = v_near.union(v.nn) + # Reconnect vertices to complex + # if self.HC.connect_vertex_non_symm(tuple(self.LMC[xl].x_l), + # near=v_near): + # continue + # else: + # If failure to find in v_near, then search all vertices + # (very expensive operation: + # self.HC.connect_vertex_non_symm(tuple(self.LMC[xl].x_l) + # ) + + # Evaluate all constraints and functions + self.HC.V.process_pools() + if self.disp: + logging.info('Evaluations completed.') + + # feasible sampling points counted by the triangulation.py routines + self.fn = self.HC.V.nfev + return + + def iterate_delaunay(self): + """ + Build a complex of Delaunay triangulated points + + Note: called with ``self.iterate_complex()`` after class initiation + """ + self.nc += self.n + self.sampled_surface(infty_cons_sampl=self.infty_cons_sampl) + + # Add sampled points to a triangulation, construct self.Tri + if self.disp: + logging.info(f'self.n = {self.n}') + logging.info(f'self.nc = {self.nc}') + logging.info('Constructing and refining simplicial complex graph ' + 'structure from sampling points.') + + if self.dim < 2: + self.Ind_sorted = np.argsort(self.C, axis=0) + self.Ind_sorted = self.Ind_sorted.flatten() + tris = [] + for ind, ind_s in enumerate(self.Ind_sorted): + if ind > 0: + tris.append(self.Ind_sorted[ind - 1:ind + 1]) + + tris = np.array(tris) + # Store 1D triangulation: + self.Tri = namedtuple('Tri', ['points', 'simplices'])(self.C, tris) + self.points = {} + else: + if self.C.shape[0] > self.dim + 1: # Ensure a simplex can be built + self.delaunay_triangulation(n_prc=self.n_prc) + self.n_prc = self.C.shape[0] + + if self.disp: + logging.info('Triangulation completed, evaluating all ' + 'constraints and objective function values.') + + if hasattr(self, 'Tri'): + self.HC.vf_to_vv(self.Tri.points, self.Tri.simplices) + + # Process all pools + # Evaluate all constraints and functions + if self.disp: + logging.info('Triangulation completed, evaluating all constraints ' + 'and objective function values.') + + # Evaluate all constraints and functions + self.HC.V.process_pools() + if self.disp: + logging.info('Evaluations completed.') + + # feasible sampling points counted by the triangulation.py routines + self.fn = self.HC.V.nfev + self.n_sampled = self.nc # nevs counted in triangulation + return + + # Hypercube minimizers + def minimizers(self): + """ + Returns the indexes of all minimizers + """ + self.minimizer_pool = [] + # Note: Can implement parallelization here + for x in self.HC.V.cache: + in_LMC = False + if len(self.LMC.xl_maps) > 0: + for xlmi in self.LMC.xl_maps: + if np.all(np.array(x) == np.array(xlmi)): + in_LMC = True + if in_LMC: + continue + + if self.HC.V[x].minimiser(): + if self.disp: + logging.info('=' * 60) + logging.info(f'v.x = {self.HC.V[x].x_a} is minimizer') + logging.info(f'v.f = {self.HC.V[x].f} is minimizer') + logging.info('=' * 30) + + if self.HC.V[x] not in self.minimizer_pool: + self.minimizer_pool.append(self.HC.V[x]) + + if self.disp: + logging.info('Neighbors:') + logging.info('=' * 30) + for vn in self.HC.V[x].nn: + logging.info(f'x = {vn.x} || f = {vn.f}') + + logging.info('=' * 60) + self.minimizer_pool_F = [] + self.X_min = [] + # normalized tuple in the Vertex cache + self.X_min_cache = {} # Cache used in hypercube sampling + + for v in self.minimizer_pool: + self.X_min.append(v.x_a) + self.minimizer_pool_F.append(v.f) + self.X_min_cache[tuple(v.x_a)] = v.x + + self.minimizer_pool_F = np.array(self.minimizer_pool_F) + self.X_min = np.array(self.X_min) + + # TODO: Only do this if global mode + self.sort_min_pool() + + return self.X_min + + # Local minimisation + # Minimiser pool processing + def minimise_pool(self, force_iter=False): + """ + This processing method can optionally minimise only the best candidate + solutions in the minimiser pool + + Parameters + ---------- + force_iter : int + Number of starting minimizers to process (can be specified + globally or locally) + + """ + # Find first local minimum + # NOTE: Since we always minimize this value regardless it is a waste to + # build the topograph first before minimizing + lres_f_min = self.minimize(self.X_min[0], ind=self.minimizer_pool[0]) + + # Trim minimized point from current minimizer set + self.trim_min_pool(0) + + while not self.stop_l_iter: + # Global stopping criteria: + self.stopping_criteria() + + # Note first iteration is outside loop: + if force_iter: + force_iter -= 1 + if force_iter == 0: + self.stop_l_iter = True + break + + if np.shape(self.X_min)[0] == 0: + self.stop_l_iter = True + break + + # Construct topograph from current minimizer set + # (NOTE: This is a very small topograph using only the minizer pool + # , it might be worth using some graph theory tools instead. + self.g_topograph(lres_f_min.x, self.X_min) + + # Find local minimum at the miniser with the greatest Euclidean + # distance from the current solution + ind_xmin_l = self.Z[:, -1] + lres_f_min = self.minimize(self.Ss[-1, :], self.minimizer_pool[-1]) + + # Trim minimised point from current minimizer set + self.trim_min_pool(ind_xmin_l) + + # Reset controls + self.stop_l_iter = False + return + + def sort_min_pool(self): + # Sort to find minimum func value in min_pool + self.ind_f_min = np.argsort(self.minimizer_pool_F) + self.minimizer_pool = np.array(self.minimizer_pool)[self.ind_f_min] + self.minimizer_pool_F = np.array(self.minimizer_pool_F)[ + self.ind_f_min] + return + + def trim_min_pool(self, trim_ind): + self.X_min = np.delete(self.X_min, trim_ind, axis=0) + self.minimizer_pool_F = np.delete(self.minimizer_pool_F, trim_ind) + self.minimizer_pool = np.delete(self.minimizer_pool, trim_ind) + return + + def g_topograph(self, x_min, X_min): + """ + Returns the topographical vector stemming from the specified value + ``x_min`` for the current feasible set ``X_min`` with True boolean + values indicating positive entries and False values indicating + negative entries. + + """ + x_min = np.array([x_min]) + self.Y = spatial.distance.cdist(x_min, X_min, 'euclidean') + # Find sorted indexes of spatial distances: + self.Z = np.argsort(self.Y, axis=-1) + + self.Ss = X_min[self.Z][0] + self.minimizer_pool = self.minimizer_pool[self.Z] + self.minimizer_pool = self.minimizer_pool[0] + return self.Ss + + # Local bound functions + def construct_lcb_simplicial(self, v_min): + """ + Construct locally (approximately) convex bounds + + Parameters + ---------- + v_min : Vertex object + The minimizer vertex + + Returns + ------- + cbounds : list of lists + List of size dimension with length-2 list of bounds for each + dimension. + + """ + cbounds = [[x_b_i[0], x_b_i[1]] for x_b_i in self.bounds] + # Loop over all bounds + for vn in v_min.nn: + for i, x_i in enumerate(vn.x_a): + # Lower bound + if (x_i < v_min.x_a[i]) and (x_i > cbounds[i][0]): + cbounds[i][0] = x_i + + # Upper bound + if (x_i > v_min.x_a[i]) and (x_i < cbounds[i][1]): + cbounds[i][1] = x_i + + if self.disp: + logging.info(f'cbounds found for v_min.x_a = {v_min.x_a}') + logging.info(f'cbounds = {cbounds}') + + return cbounds + + def construct_lcb_delaunay(self, v_min, ind=None): + """ + Construct locally (approximately) convex bounds + + Parameters + ---------- + v_min : Vertex object + The minimizer vertex + + Returns + ------- + cbounds : list of lists + List of size dimension with length-2 list of bounds for each + dimension. + """ + cbounds = [[x_b_i[0], x_b_i[1]] for x_b_i in self.bounds] + + return cbounds + + # Minimize a starting point locally + def minimize(self, x_min, ind=None): + """ + This function is used to calculate the local minima using the specified + sampling point as a starting value. + + Parameters + ---------- + x_min : vector of floats + Current starting point to minimize. + + Returns + ------- + lres : OptimizeResult + The local optimization result represented as a `OptimizeResult` + object. + """ + # Use minima maps if vertex was already run + if self.disp: + logging.info(f'Vertex minimiser maps = {self.LMC.v_maps}') + + if self.LMC[x_min].lres is not None: + logging.info(f'Found self.LMC[x_min].lres = ' + f'{self.LMC[x_min].lres}') + return self.LMC[x_min].lres + + if self.callback is not None: + logging.info(f'Callback for minimizer starting at {x_min}:') + + if self.disp: + logging.info(f'Starting minimization at {x_min}...') + + if self.sampling_method == 'simplicial': + x_min_t = tuple(x_min) + # Find the normalized tuple in the Vertex cache: + x_min_t_norm = self.X_min_cache[tuple(x_min_t)] + x_min_t_norm = tuple(x_min_t_norm) + g_bounds = self.construct_lcb_simplicial(self.HC.V[x_min_t_norm]) + if 'bounds' in self.min_solver_args: + self.minimizer_kwargs['bounds'] = g_bounds + logging.info(self.minimizer_kwargs['bounds']) + + else: + g_bounds = self.construct_lcb_delaunay(x_min, ind=ind) + if 'bounds' in self.min_solver_args: + self.minimizer_kwargs['bounds'] = g_bounds + logging.info(self.minimizer_kwargs['bounds']) + + if self.disp and 'bounds' in self.minimizer_kwargs: + logging.info('bounds in kwarg:') + logging.info(self.minimizer_kwargs['bounds']) + + # Local minimization using scipy.optimize.minimize: + lres = minimize(self.func, x_min, **self.minimizer_kwargs) + + if self.disp: + logging.info(f'lres = {lres}') + + # Local function evals for all minimizers + self.res.nlfev += lres.nfev + if 'njev' in lres: + self.res.nljev += lres.njev + if 'nhev' in lres: + self.res.nlhev += lres.nhev + + try: # Needed because of the brain dead 1x1 NumPy arrays + lres.fun = lres.fun[0] + except (IndexError, TypeError): + lres.fun + + # Append minima maps + self.LMC[x_min] + self.LMC.add_res(x_min, lres, bounds=g_bounds) + + return lres + + # Post local minimization processing + def sort_result(self): + """ + Sort results and build the global return object + """ + # Sort results in local minima cache + results = self.LMC.sort_cache_result() + self.res.xl = results['xl'] + self.res.funl = results['funl'] + self.res.x = results['x'] + self.res.fun = results['fun'] + + # Add local func evals to sampling func evals + # Count the number of feasible vertices and add to local func evals: + self.res.nfev = self.fn + self.res.nlfev + return self.res + + # Algorithm controls + def fail_routine(self, mes=("Failed to converge")): + self.break_routine = True + self.res.success = False + self.X_min = [None] + self.res.message = mes + + def sampled_surface(self, infty_cons_sampl=False): + """ + Sample the function surface. + + There are 2 modes, if ``infty_cons_sampl`` is True then the sampled + points that are generated outside the feasible domain will be + assigned an ``inf`` value in accordance with SHGO rules. + This guarantees convergence and usually requires less objective + function evaluations at the computational costs of more Delaunay + triangulation points. + + If ``infty_cons_sampl`` is False, then the infeasible points are + discarded and only a subspace of the sampled points are used. This + comes at the cost of the loss of guaranteed convergence and usually + requires more objective function evaluations. + """ + # Generate sampling points + if self.disp: + logging.info('Generating sampling points') + self.sampling(self.nc, self.dim) + if len(self.LMC.xl_maps) > 0: + self.C = np.vstack((self.C, np.array(self.LMC.xl_maps))) + if not infty_cons_sampl: + # Find subspace of feasible points + if self.g_cons is not None: + self.sampling_subspace() + + # Sort remaining samples + self.sorted_samples() + + # Find objective function references + self.n_sampled = self.nc + + def sampling_custom(self, n, dim): + """ + Generates uniform sampling points in a hypercube and scales the points + to the bound limits. + """ + # Generate sampling points. + # Generate uniform sample points in [0, 1]^m \subset R^m + if self.n_sampled == 0: + self.C = self.sampling_function(n, dim) + else: + self.C = self.sampling_function(n, dim) + # Distribute over bounds + for i in range(len(self.bounds)): + self.C[:, i] = (self.C[:, i] * + (self.bounds[i][1] - self.bounds[i][0]) + + self.bounds[i][0]) + return self.C + + def sampling_subspace(self): + """Find subspace of feasible points from g_func definition""" + # Subspace of feasible points. + for ind, g in enumerate(self.g_cons): + # C.shape = (Z, dim) where Z is the number of sampling points to + # evaluate and dim is the dimensionality of the problem. + # the constraint function may not be vectorised so have to step + # through each sampling point sequentially. + feasible = np.array( + [np.all(g(x_C, *self.g_args[ind]) >= 0.0) for x_C in self.C], + dtype=bool + ) + self.C = self.C[feasible] + + if self.C.size == 0: + self.res.message = ('No sampling point found within the ' + + 'feasible set. Increasing sampling ' + + 'size.') + # sampling correctly for both 1-D and >1-D cases + if self.disp: + logging.info(self.res.message) + + def sorted_samples(self): # Validated + """Find indexes of the sorted sampling points""" + self.Ind_sorted = np.argsort(self.C, axis=0) + self.Xs = self.C[self.Ind_sorted] + return self.Ind_sorted, self.Xs + + def delaunay_triangulation(self, n_prc=0): + if hasattr(self, 'Tri') and self.qhull_incremental: + # TODO: Uncertain if n_prc needs to add len(self.LMC.xl_maps) + # in self.sampled_surface + self.Tri.add_points(self.C[n_prc:, :]) + else: + try: + self.Tri = spatial.Delaunay(self.C, + incremental=self.qhull_incremental, + ) + except spatial.QhullError: + if str(sys.exc_info()[1])[:6] == 'QH6239': + logging.warning('QH6239 Qhull precision error detected, ' + 'this usually occurs when no bounds are ' + 'specified, Qhull can only run with ' + 'handling cocircular/cospherical points' + ' and in this case incremental mode is ' + 'switched off. The performance of shgo ' + 'will be reduced in this mode.') + self.qhull_incremental = False + self.Tri = spatial.Delaunay(self.C, + incremental= + self.qhull_incremental) + else: + raise + + return self.Tri + + +class LMap: + def __init__(self, v): + self.v = v + self.x_l = None + self.lres = None + self.f_min = None + self.lbounds = [] + + +class LMapCache: + def __init__(self): + self.cache = {} + + # Lists for search queries + self.v_maps = [] + self.xl_maps = [] + self.xl_maps_set = set() + self.f_maps = [] + self.lbound_maps = [] + self.size = 0 + + def __getitem__(self, v): + try: + v = np.ndarray.tolist(v) + except TypeError: + pass + v = tuple(v) + try: + return self.cache[v] + except KeyError: + xval = LMap(v) + self.cache[v] = xval + + return self.cache[v] + + def add_res(self, v, lres, bounds=None): + v = np.ndarray.tolist(v) + v = tuple(v) + self.cache[v].x_l = lres.x + self.cache[v].lres = lres + self.cache[v].f_min = lres.fun + self.cache[v].lbounds = bounds + + # Update cache size + self.size += 1 + + # Cache lists for search queries + self.v_maps.append(v) + self.xl_maps.append(lres.x) + self.xl_maps_set.add(tuple(lres.x)) + self.f_maps.append(lres.fun) + self.lbound_maps.append(bounds) + + def sort_cache_result(self): + """ + Sort results and build the global return object + """ + results = {} + # Sort results and save + self.xl_maps = np.array(self.xl_maps) + self.f_maps = np.array(self.f_maps) + + # Sorted indexes in Func_min + ind_sorted = np.argsort(self.f_maps) + + # Save ordered list of minima + results['xl'] = self.xl_maps[ind_sorted] # Ordered x vals + self.f_maps = np.array(self.f_maps) + results['funl'] = self.f_maps[ind_sorted] + results['funl'] = results['funl'].T + + # Find global of all minimizers + results['x'] = self.xl_maps[ind_sorted[0]] # Save global minima + results['fun'] = self.f_maps[ind_sorted[0]] # Save global fun value + + self.xl_maps = np.ndarray.tolist(self.xl_maps) + self.f_maps = np.ndarray.tolist(self.f_maps) + return results diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_shgo_lib/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_shgo_lib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_shgo_lib/_complex.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_shgo_lib/_complex.py new file mode 100644 index 0000000000000000000000000000000000000000..178e9daea2d03e335a6901483f574d7453fb9340 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_shgo_lib/_complex.py @@ -0,0 +1,1225 @@ +"""Base classes for low memory simplicial complex structures.""" +import copy +import logging +import itertools +import decimal +from functools import cache + +import numpy as np + +from ._vertex import (VertexCacheField, VertexCacheIndex) + + +class Complex: + """ + Base class for a simplicial complex described as a cache of vertices + together with their connections. + + Important methods: + Domain triangulation: + Complex.triangulate, Complex.split_generation + Triangulating arbitrary points (must be traingulable, + may exist outside domain): + Complex.triangulate(sample_set) + Converting another simplicial complex structure data type to the + structure used in Complex (ex. OBJ wavefront) + Complex.convert(datatype, data) + + Important objects: + HC.V: The cache of vertices and their connection + HC.H: Storage structure of all vertex groups + + Parameters + ---------- + dim : int + Spatial dimensionality of the complex R^dim + domain : list of tuples, optional + The bounds [x_l, x_u]^dim of the hyperrectangle space + ex. The default domain is the hyperrectangle [0, 1]^dim + Note: The domain must be convex, non-convex spaces can be cut + away from this domain using the non-linear + g_cons functions to define any arbitrary domain + (these domains may also be disconnected from each other) + sfield : + A scalar function defined in the associated domain f: R^dim --> R + sfield_args : tuple + Additional arguments to be passed to `sfield` + vfield : + A scalar function defined in the associated domain + f: R^dim --> R^m + (for example a gradient function of the scalar field) + vfield_args : tuple + Additional arguments to be passed to vfield + symmetry : None or list + Specify if the objective function contains symmetric variables. + The search space (and therefore performance) is decreased by up to + O(n!) times in the fully symmetric case. + + E.g. f(x) = (x_1 + x_2 + x_3) + (x_4)**2 + (x_5)**2 + (x_6)**2 + + In this equation x_2 and x_3 are symmetric to x_1, while x_5 and + x_6 are symmetric to x_4, this can be specified to the solver as: + + symmetry = [0, # Variable 1 + 0, # symmetric to variable 1 + 0, # symmetric to variable 1 + 3, # Variable 4 + 3, # symmetric to variable 4 + 3, # symmetric to variable 4 + ] + + constraints : dict or sequence of dict, optional + Constraints definition. + Function(s) ``R**n`` in the form:: + + g(x) <= 0 applied as g : R^n -> R^m + h(x) == 0 applied as h : R^n -> R^p + + Each constraint is defined in a dictionary with fields: + + type : str + Constraint type: 'eq' for equality, 'ineq' for inequality. + fun : callable + The function defining the constraint. + jac : callable, optional + The Jacobian of `fun` (only for SLSQP). + args : sequence, optional + Extra arguments to be passed to the function and Jacobian. + + Equality constraint means that the constraint function result is to + be zero whereas inequality means that it is to be + non-negative.constraints : dict or sequence of dict, optional + Constraints definition. + Function(s) ``R**n`` in the form:: + + g(x) <= 0 applied as g : R^n -> R^m + h(x) == 0 applied as h : R^n -> R^p + + Each constraint is defined in a dictionary with fields: + + type : str + Constraint type: 'eq' for equality, 'ineq' for inequality. + fun : callable + The function defining the constraint. + jac : callable, optional + The Jacobian of `fun` (unused). + args : sequence, optional + Extra arguments to be passed to the function and Jacobian. + + Equality constraint means that the constraint function result is to + be zero whereas inequality means that it is to be non-negative. + + workers : int optional + Uses `multiprocessing.Pool `) to compute the field + functions in parallel. + """ + def __init__(self, dim, domain=None, sfield=None, sfield_args=(), + symmetry=None, constraints=None, workers=1): + self.dim = dim + + # Domains + self.domain = domain + if domain is None: + self.bounds = [(0.0, 1.0), ] * dim + else: + self.bounds = domain + self.symmetry = symmetry + # here in init to avoid if checks + + # Field functions + self.sfield = sfield + self.sfield_args = sfield_args + + # Process constraints + # Constraints + # Process constraint dict sequence: + if constraints is not None: + self.min_cons = constraints + self.g_cons = [] + self.g_args = [] + if not isinstance(constraints, (tuple, list)): + constraints = (constraints,) + + for cons in constraints: + if cons['type'] in ('ineq'): + self.g_cons.append(cons['fun']) + try: + self.g_args.append(cons['args']) + except KeyError: + self.g_args.append(()) + self.g_cons = tuple(self.g_cons) + self.g_args = tuple(self.g_args) + else: + self.g_cons = None + self.g_args = None + + # Homology properties + self.gen = 0 + self.perm_cycle = 0 + + # Every cell is stored in a list of its generation, + # ex. the initial cell is stored in self.H[0] + # 1st get new cells are stored in self.H[1] etc. + # When a cell is sub-generated it is removed from this list + + self.H = [] # Storage structure of vertex groups + + # Cache of all vertices + if (sfield is not None) or (self.g_cons is not None): + # Initiate a vertex cache and an associated field cache, note that + # the field case is always initiated inside the vertex cache if an + # associated field scalar field is defined: + if sfield is not None: + self.V = VertexCacheField(field=sfield, field_args=sfield_args, + g_cons=self.g_cons, + g_cons_args=self.g_args, + workers=workers) + elif self.g_cons is not None: + self.V = VertexCacheField(field=sfield, field_args=sfield_args, + g_cons=self.g_cons, + g_cons_args=self.g_args, + workers=workers) + else: + self.V = VertexCacheIndex() + + self.V_non_symm = [] # List of non-symmetric vertices + + def __call__(self): + return self.H + + # %% Triangulation methods + def cyclic_product(self, bounds, origin, supremum, centroid=True): + """Generate initial triangulation using cyclic product""" + # Define current hyperrectangle + vot = tuple(origin) + vut = tuple(supremum) # Hyperrectangle supremum + self.V[vot] + vo = self.V[vot] + yield vo.x + self.V[vut].connect(self.V[vot]) + yield vut + # Cyclic group approach with second x_l --- x_u operation. + + # These containers store the "lower" and "upper" vertices + # corresponding to the origin or supremum of every C2 group. + # It has the structure of `dim` times embedded lists each containing + # these vertices as the entire complex grows. Bounds[0] has to be done + # outside the loops before we have symmetric containers. + # NOTE: This means that bounds[0][1] must always exist + C0x = [[self.V[vot]]] + a_vo = copy.copy(list(origin)) + a_vo[0] = vut[0] # Update aN Origin + a_vo = self.V[tuple(a_vo)] + # self.V[vot].connect(self.V[tuple(a_vo)]) + self.V[vot].connect(a_vo) + yield a_vo.x + C1x = [[a_vo]] + # C1x = [[self.V[tuple(a_vo)]]] + ab_C = [] # Container for a + b operations + + # Loop over remaining bounds + for i, x in enumerate(bounds[1:]): + # Update lower and upper containers + C0x.append([]) + C1x.append([]) + # try to access a second bound (if not, C1 is symmetric) + try: + # Early try so that we don't have to copy the cache before + # moving on to next C1/C2: Try to add the operation of a new + # C2 product by accessing the upper bound + x[1] + # Copy lists for iteration + cC0x = [x[:] for x in C0x[:i + 1]] + cC1x = [x[:] for x in C1x[:i + 1]] + for j, (VL, VU) in enumerate(zip(cC0x, cC1x)): + for k, (vl, vu) in enumerate(zip(VL, VU)): + # Build aN vertices for each lower-upper pair in N: + a_vl = list(vl.x) + a_vu = list(vu.x) + a_vl[i + 1] = vut[i + 1] + a_vu[i + 1] = vut[i + 1] + a_vl = self.V[tuple(a_vl)] + + # Connect vertices in N to corresponding vertices + # in aN: + vl.connect(a_vl) + + yield a_vl.x + + a_vu = self.V[tuple(a_vu)] + # Connect vertices in N to corresponding vertices + # in aN: + vu.connect(a_vu) + + # Connect new vertex pair in aN: + a_vl.connect(a_vu) + + # Connect lower pair to upper (triangulation + # operation of a + b (two arbitrary operations): + vl.connect(a_vu) + ab_C.append((vl, a_vu)) + + # Update the containers + C0x[i + 1].append(vl) + C0x[i + 1].append(vu) + C1x[i + 1].append(a_vl) + C1x[i + 1].append(a_vu) + + # Update old containers + C0x[j].append(a_vl) + C1x[j].append(a_vu) + + # Yield new points + yield a_vu.x + + # Try to connect aN lower source of previous a + b + # operation with a aN vertex + ab_Cc = copy.copy(ab_C) + + for vp in ab_Cc: + b_v = list(vp[0].x) + ab_v = list(vp[1].x) + b_v[i + 1] = vut[i + 1] + ab_v[i + 1] = vut[i + 1] + b_v = self.V[tuple(b_v)] # b + vl + ab_v = self.V[tuple(ab_v)] # b + a_vl + # Note o---o is already connected + vp[0].connect(ab_v) # o-s + b_v.connect(ab_v) # s-s + + # Add new list of cross pairs + ab_C.append((vp[0], ab_v)) + ab_C.append((b_v, ab_v)) + + except IndexError: + cC0x = C0x[i] + cC1x = C1x[i] + VL, VU = cC0x, cC1x + for k, (vl, vu) in enumerate(zip(VL, VU)): + # Build aN vertices for each lower-upper pair in N: + a_vu = list(vu.x) + a_vu[i + 1] = vut[i + 1] + # Connect vertices in N to corresponding vertices + # in aN: + a_vu = self.V[tuple(a_vu)] + # Connect vertices in N to corresponding vertices + # in aN: + vu.connect(a_vu) + # Connect new vertex pair in aN: + # a_vl.connect(a_vu) + # Connect lower pair to upper (triangulation + # operation of a + b (two arbitrary operations): + vl.connect(a_vu) + ab_C.append((vl, a_vu)) + C0x[i + 1].append(vu) + C1x[i + 1].append(a_vu) + # Yield new points + a_vu.connect(self.V[vut]) + yield a_vu.x + ab_Cc = copy.copy(ab_C) + for vp in ab_Cc: + if vp[1].x[i] == vut[i]: + ab_v = list(vp[1].x) + ab_v[i + 1] = vut[i + 1] + ab_v = self.V[tuple(ab_v)] # b + a_vl + # Note o---o is already connected + vp[0].connect(ab_v) # o-s + + # Add new list of cross pairs + ab_C.append((vp[0], ab_v)) + + # Clean class trash + try: + del C0x + del cC0x + del C1x + del cC1x + del ab_C + del ab_Cc + except UnboundLocalError: + pass + + # Extra yield to ensure that the triangulation is completed + if centroid: + vo = self.V[vot] + vs = self.V[vut] + # Disconnect the origin and supremum + vo.disconnect(vs) + # Build centroid + vc = self.split_edge(vot, vut) + for v in vo.nn: + v.connect(vc) + yield vc.x + return vc.x + else: + yield vut + return vut + + def triangulate(self, n=None, symmetry=None, centroid=True, + printout=False): + """ + Triangulate the initial domain, if n is not None then a limited number + of points will be generated + + Parameters + ---------- + n : int, Number of points to be sampled. + symmetry : + + Ex. Dictionary/hashtable + f(x) = (x_1 + x_2 + x_3) + (x_4)**2 + (x_5)**2 + (x_6)**2 + + symmetry = symmetry[0]: 0, # Variable 1 + symmetry[1]: 0, # symmetric to variable 1 + symmetry[2]: 0, # symmetric to variable 1 + symmetry[3]: 3, # Variable 4 + symmetry[4]: 3, # symmetric to variable 4 + symmetry[5]: 3, # symmetric to variable 4 + } + centroid : bool, if True add a central point to the hypercube + printout : bool, if True print out results + + NOTES: + ------ + Rather than using the combinatorial algorithm to connect vertices we + make the following observation: + + The bound pairs are similar a C2 cyclic group and the structure is + formed using the cartesian product: + + H = C2 x C2 x C2 ... x C2 (dim times) + + So construct any normal subgroup N and consider H/N first, we connect + all vertices within N (ex. N is C2 (the first dimension), then we move + to a left coset aN (an operation moving around the defined H/N group by + for example moving from the lower bound in C2 (dimension 2) to the + higher bound in C2. During this operation connection all the vertices. + Now repeat the N connections. Note that these elements can be connected + in parallel. + """ + # Inherit class arguments + if symmetry is None: + symmetry = self.symmetry + # Build origin and supremum vectors + origin = [i[0] for i in self.bounds] + self.origin = origin + supremum = [i[1] for i in self.bounds] + + self.supremum = supremum + + if symmetry is None: + cbounds = self.bounds + else: + cbounds = copy.copy(self.bounds) + for i, j in enumerate(symmetry): + if i is not j: + # pop second entry on second symmetry vars + cbounds[i] = [self.bounds[symmetry[i]][0]] + # Sole (first) entry is the sup value and there is no + # origin: + cbounds[i] = [self.bounds[symmetry[i]][1]] + if (self.bounds[symmetry[i]] is not + self.bounds[symmetry[j]]): + logging.warning(f"Variable {i} was specified as " + f"symmetric to variable {j}, however" + f", the bounds {i} =" + f" {self.bounds[symmetry[i]]} and {j}" + f" =" + f" {self.bounds[symmetry[j]]} do not " + f"match, the mismatch was ignored in " + f"the initial triangulation.") + cbounds[i] = self.bounds[symmetry[j]] + + if n is None: + # Build generator + self.cp = self.cyclic_product(cbounds, origin, supremum, centroid) + for i in self.cp: + i + + try: + self.triangulated_vectors.append((tuple(self.origin), + tuple(self.supremum))) + except (AttributeError, KeyError): + self.triangulated_vectors = [(tuple(self.origin), + tuple(self.supremum))] + + else: + # Check if generator already exists + try: + self.cp + except (AttributeError, KeyError): + self.cp = self.cyclic_product(cbounds, origin, supremum, + centroid) + + try: + while len(self.V.cache) < n: + next(self.cp) + except StopIteration: + try: + self.triangulated_vectors.append((tuple(self.origin), + tuple(self.supremum))) + except (AttributeError, KeyError): + self.triangulated_vectors = [(tuple(self.origin), + tuple(self.supremum))] + + if printout: + # for v in self.C0(): + # v.print_out() + for v in self.V.cache: + self.V[v].print_out() + + return + + def refine(self, n=1): + if n is None: + try: + self.triangulated_vectors + self.refine_all() + return + except AttributeError as ae: + if str(ae) == "'Complex' object has no attribute " \ + "'triangulated_vectors'": + self.triangulate(symmetry=self.symmetry) + return + else: + raise + + nt = len(self.V.cache) + n # Target number of total vertices + # In the outer while loop we iterate until we have added an extra `n` + # vertices to the complex: + while len(self.V.cache) < nt: # while loop 1 + try: # try 1 + # Try to access triangulated_vectors, this should only be + # defined if an initial triangulation has already been + # performed: + self.triangulated_vectors + # Try a usual iteration of the current generator, if it + # does not exist or is exhausted then produce a new generator + try: # try 2 + next(self.rls) + except (AttributeError, StopIteration, KeyError): + vp = self.triangulated_vectors[0] + self.rls = self.refine_local_space(*vp, bounds=self.bounds) + next(self.rls) + + except (AttributeError, KeyError): + # If an initial triangulation has not been completed, then + # we start/continue the initial triangulation targeting `nt` + # vertices, if nt is greater than the initial number of + # vertices then the `refine` routine will move back to try 1. + self.triangulate(nt, self.symmetry) + return + + def refine_all(self, centroids=True): + """Refine the entire domain of the current complex.""" + try: + self.triangulated_vectors + tvs = copy.copy(self.triangulated_vectors) + for i, vp in enumerate(tvs): + self.rls = self.refine_local_space(*vp, bounds=self.bounds) + for i in self.rls: + i + except AttributeError as ae: + if str(ae) == "'Complex' object has no attribute " \ + "'triangulated_vectors'": + self.triangulate(symmetry=self.symmetry, centroid=centroids) + else: + raise + + # This adds a centroid to every new sub-domain generated and defined + # by self.triangulated_vectors, in addition the vertices ! to complete + # the triangulation + return + + def refine_local_space(self, origin, supremum, bounds, centroid=1): + # Copy for later removal + origin_c = copy.copy(origin) + supremum_c = copy.copy(supremum) + + # Initiate local variables redefined in later inner `for` loop: + vl, vu, a_vu = None, None, None + + # Change the vector orientation so that it is only increasing + s_ov = list(origin) + s_origin = list(origin) + s_sv = list(supremum) + s_supremum = list(supremum) + for i, vi in enumerate(s_origin): + if s_ov[i] > s_sv[i]: + s_origin[i] = s_sv[i] + s_supremum[i] = s_ov[i] + + vot = tuple(s_origin) + vut = tuple(s_supremum) # Hyperrectangle supremum + + vo = self.V[vot] # initiate if doesn't exist yet + vs = self.V[vut] + # Start by finding the old centroid of the new space: + vco = self.split_edge(vo.x, vs.x) # Split in case not centroid arg + + # Find set of extreme vertices in current local space + sup_set = copy.copy(vco.nn) + # Cyclic group approach with second x_l --- x_u operation. + + # These containers store the "lower" and "upper" vertices + # corresponding to the origin or supremum of every C2 group. + # It has the structure of `dim` times embedded lists each containing + # these vertices as the entire complex grows. Bounds[0] has to be done + # outside the loops before we have symmetric containers. + # NOTE: This means that bounds[0][1] must always exist + + a_vl = copy.copy(list(vot)) + a_vl[0] = vut[0] # Update aN Origin + if tuple(a_vl) not in self.V.cache: + vo = self.V[vot] # initiate if doesn't exist yet + vs = self.V[vut] + # Start by finding the old centroid of the new space: + vco = self.split_edge(vo.x, vs.x) # Split in case not centroid arg + + # Find set of extreme vertices in current local space + sup_set = copy.copy(vco.nn) + a_vl = copy.copy(list(vot)) + a_vl[0] = vut[0] # Update aN Origin + a_vl = self.V[tuple(a_vl)] + else: + a_vl = self.V[tuple(a_vl)] + + c_v = self.split_edge(vo.x, a_vl.x) + c_v.connect(vco) + yield c_v.x + Cox = [[vo]] + Ccx = [[c_v]] + Cux = [[a_vl]] + ab_C = [] # Container for a + b operations + s_ab_C = [] # Container for symmetric a + b operations + + # Loop over remaining bounds + for i, x in enumerate(bounds[1:]): + # Update lower and upper containers + Cox.append([]) + Ccx.append([]) + Cux.append([]) + # try to access a second bound (if not, C1 is symmetric) + try: + t_a_vl = list(vot) + t_a_vl[i + 1] = vut[i + 1] + + # New: lists are used anyway, so copy all + # %% + # Copy lists for iteration + cCox = [x[:] for x in Cox[:i + 1]] + cCcx = [x[:] for x in Ccx[:i + 1]] + cCux = [x[:] for x in Cux[:i + 1]] + # Try to connect aN lower source of previous a + b + # operation with a aN vertex + ab_Cc = copy.copy(ab_C) # NOTE: We append ab_C in the + # (VL, VC, VU) for-loop, but we use the copy of the list in the + # ab_Cc for-loop. + s_ab_Cc = copy.copy(s_ab_C) + + # Early try so that we don't have to copy the cache before + # moving on to next C1/C2: Try to add the operation of a new + # C2 product by accessing the upper bound + if tuple(t_a_vl) not in self.V.cache: + # Raise error to continue symmetric refine + raise IndexError + t_a_vu = list(vut) + t_a_vu[i + 1] = vut[i + 1] + if tuple(t_a_vu) not in self.V.cache: + # Raise error to continue symmetric refine: + raise IndexError + + for vectors in s_ab_Cc: + # s_ab_C.append([c_vc, vl, vu, a_vu]) + bc_vc = list(vectors[0].x) + b_vl = list(vectors[1].x) + b_vu = list(vectors[2].x) + ba_vu = list(vectors[3].x) + + bc_vc[i + 1] = vut[i + 1] + b_vl[i + 1] = vut[i + 1] + b_vu[i + 1] = vut[i + 1] + ba_vu[i + 1] = vut[i + 1] + + bc_vc = self.V[tuple(bc_vc)] + bc_vc.connect(vco) # NOTE: Unneeded? + yield bc_vc + + # Split to centre, call this centre group "d = 0.5*a" + d_bc_vc = self.split_edge(vectors[0].x, bc_vc.x) + d_bc_vc.connect(bc_vc) + d_bc_vc.connect(vectors[1]) # Connect all to centroid + d_bc_vc.connect(vectors[2]) # Connect all to centroid + d_bc_vc.connect(vectors[3]) # Connect all to centroid + yield d_bc_vc.x + b_vl = self.V[tuple(b_vl)] + bc_vc.connect(b_vl) # Connect aN cross pairs + d_bc_vc.connect(b_vl) # Connect all to centroid + + yield b_vl + b_vu = self.V[tuple(b_vu)] + bc_vc.connect(b_vu) # Connect aN cross pairs + d_bc_vc.connect(b_vu) # Connect all to centroid + + b_vl_c = self.split_edge(b_vu.x, b_vl.x) + bc_vc.connect(b_vl_c) + + yield b_vu + ba_vu = self.V[tuple(ba_vu)] + bc_vc.connect(ba_vu) # Connect aN cross pairs + d_bc_vc.connect(ba_vu) # Connect all to centroid + + # Split the a + b edge of the initial triangulation: + os_v = self.split_edge(vectors[1].x, ba_vu.x) # o-s + ss_v = self.split_edge(b_vl.x, ba_vu.x) # s-s + b_vu_c = self.split_edge(b_vu.x, ba_vu.x) + bc_vc.connect(b_vu_c) + yield os_v.x # often equal to vco, but not always + yield ss_v.x # often equal to bc_vu, but not always + yield ba_vu + # Split remaining to centre, call this centre group + # "d = 0.5*a" + d_bc_vc = self.split_edge(vectors[0].x, bc_vc.x) + d_bc_vc.connect(vco) # NOTE: Unneeded? + yield d_bc_vc.x + d_b_vl = self.split_edge(vectors[1].x, b_vl.x) + d_bc_vc.connect(vco) # NOTE: Unneeded? + d_bc_vc.connect(d_b_vl) # Connect dN cross pairs + yield d_b_vl.x + d_b_vu = self.split_edge(vectors[2].x, b_vu.x) + d_bc_vc.connect(vco) # NOTE: Unneeded? + d_bc_vc.connect(d_b_vu) # Connect dN cross pairs + yield d_b_vu.x + d_ba_vu = self.split_edge(vectors[3].x, ba_vu.x) + d_bc_vc.connect(vco) # NOTE: Unneeded? + d_bc_vc.connect(d_ba_vu) # Connect dN cross pairs + yield d_ba_vu + + # comb = [c_vc, vl, vu, a_vl, a_vu, + # bc_vc, b_vl, b_vu, ba_vl, ba_vu] + comb = [vl, vu, a_vu, + b_vl, b_vu, ba_vu] + comb_iter = itertools.combinations(comb, 2) + for vecs in comb_iter: + self.split_edge(vecs[0].x, vecs[1].x) + # Add new list of cross pairs + ab_C.append((d_bc_vc, vectors[1], b_vl, a_vu, ba_vu)) + ab_C.append((d_bc_vc, vl, b_vl, a_vu, ba_vu)) # = prev + + for vectors in ab_Cc: + bc_vc = list(vectors[0].x) + b_vl = list(vectors[1].x) + b_vu = list(vectors[2].x) + ba_vl = list(vectors[3].x) + ba_vu = list(vectors[4].x) + bc_vc[i + 1] = vut[i + 1] + b_vl[i + 1] = vut[i + 1] + b_vu[i + 1] = vut[i + 1] + ba_vl[i + 1] = vut[i + 1] + ba_vu[i + 1] = vut[i + 1] + bc_vc = self.V[tuple(bc_vc)] + bc_vc.connect(vco) # NOTE: Unneeded? + yield bc_vc + + # Split to centre, call this centre group "d = 0.5*a" + d_bc_vc = self.split_edge(vectors[0].x, bc_vc.x) + d_bc_vc.connect(bc_vc) + d_bc_vc.connect(vectors[1]) # Connect all to centroid + d_bc_vc.connect(vectors[2]) # Connect all to centroid + d_bc_vc.connect(vectors[3]) # Connect all to centroid + d_bc_vc.connect(vectors[4]) # Connect all to centroid + yield d_bc_vc.x + b_vl = self.V[tuple(b_vl)] + bc_vc.connect(b_vl) # Connect aN cross pairs + d_bc_vc.connect(b_vl) # Connect all to centroid + yield b_vl + b_vu = self.V[tuple(b_vu)] + bc_vc.connect(b_vu) # Connect aN cross pairs + d_bc_vc.connect(b_vu) # Connect all to centroid + yield b_vu + ba_vl = self.V[tuple(ba_vl)] + bc_vc.connect(ba_vl) # Connect aN cross pairs + d_bc_vc.connect(ba_vl) # Connect all to centroid + self.split_edge(b_vu.x, ba_vl.x) + yield ba_vl + ba_vu = self.V[tuple(ba_vu)] + bc_vc.connect(ba_vu) # Connect aN cross pairs + d_bc_vc.connect(ba_vu) # Connect all to centroid + # Split the a + b edge of the initial triangulation: + os_v = self.split_edge(vectors[1].x, ba_vu.x) # o-s + ss_v = self.split_edge(b_vl.x, ba_vu.x) # s-s + yield os_v.x # often equal to vco, but not always + yield ss_v.x # often equal to bc_vu, but not always + yield ba_vu + # Split remaining to centre, call this centre group + # "d = 0.5*a" + d_bc_vc = self.split_edge(vectors[0].x, bc_vc.x) + d_bc_vc.connect(vco) # NOTE: Unneeded? + yield d_bc_vc.x + d_b_vl = self.split_edge(vectors[1].x, b_vl.x) + d_bc_vc.connect(vco) # NOTE: Unneeded? + d_bc_vc.connect(d_b_vl) # Connect dN cross pairs + yield d_b_vl.x + d_b_vu = self.split_edge(vectors[2].x, b_vu.x) + d_bc_vc.connect(vco) # NOTE: Unneeded? + d_bc_vc.connect(d_b_vu) # Connect dN cross pairs + yield d_b_vu.x + d_ba_vl = self.split_edge(vectors[3].x, ba_vl.x) + d_bc_vc.connect(vco) # NOTE: Unneeded? + d_bc_vc.connect(d_ba_vl) # Connect dN cross pairs + yield d_ba_vl + d_ba_vu = self.split_edge(vectors[4].x, ba_vu.x) + d_bc_vc.connect(vco) # NOTE: Unneeded? + d_bc_vc.connect(d_ba_vu) # Connect dN cross pairs + yield d_ba_vu + c_vc, vl, vu, a_vl, a_vu = vectors + + comb = [vl, vu, a_vl, a_vu, + b_vl, b_vu, ba_vl, ba_vu] + comb_iter = itertools.combinations(comb, 2) + for vecs in comb_iter: + self.split_edge(vecs[0].x, vecs[1].x) + + # Add new list of cross pairs + ab_C.append((bc_vc, b_vl, b_vu, ba_vl, ba_vu)) + ab_C.append((d_bc_vc, d_b_vl, d_b_vu, d_ba_vl, d_ba_vu)) + ab_C.append((d_bc_vc, vectors[1], b_vl, a_vu, ba_vu)) + ab_C.append((d_bc_vc, vu, b_vu, a_vl, ba_vl)) + + for j, (VL, VC, VU) in enumerate(zip(cCox, cCcx, cCux)): + for k, (vl, vc, vu) in enumerate(zip(VL, VC, VU)): + # Build aN vertices for each lower-upper C3 group in N: + a_vl = list(vl.x) + a_vu = list(vu.x) + a_vl[i + 1] = vut[i + 1] + a_vu[i + 1] = vut[i + 1] + a_vl = self.V[tuple(a_vl)] + a_vu = self.V[tuple(a_vu)] + # Note, build (a + vc) later for consistent yields + # Split the a + b edge of the initial triangulation: + c_vc = self.split_edge(vl.x, a_vu.x) + self.split_edge(vl.x, vu.x) # Equal to vc + # Build cN vertices for each lower-upper C3 group in N: + c_vc.connect(vco) + c_vc.connect(vc) + c_vc.connect(vl) # Connect c + ac operations + c_vc.connect(vu) # Connect c + ac operations + c_vc.connect(a_vl) # Connect c + ac operations + c_vc.connect(a_vu) # Connect c + ac operations + yield c_vc.x + c_vl = self.split_edge(vl.x, a_vl.x) + c_vl.connect(vco) + c_vc.connect(c_vl) # Connect cN group vertices + yield c_vl.x + # yield at end of loop: + c_vu = self.split_edge(vu.x, a_vu.x) + c_vu.connect(vco) + # Connect remaining cN group vertices + c_vc.connect(c_vu) # Connect cN group vertices + yield c_vu.x + + a_vc = self.split_edge(a_vl.x, a_vu.x) # is (a + vc) ? + a_vc.connect(vco) + a_vc.connect(c_vc) + + # Storage for connecting c + ac operations: + ab_C.append((c_vc, vl, vu, a_vl, a_vu)) + + # Update the containers + Cox[i + 1].append(vl) + Cox[i + 1].append(vc) + Cox[i + 1].append(vu) + Ccx[i + 1].append(c_vl) + Ccx[i + 1].append(c_vc) + Ccx[i + 1].append(c_vu) + Cux[i + 1].append(a_vl) + Cux[i + 1].append(a_vc) + Cux[i + 1].append(a_vu) + + # Update old containers + Cox[j].append(c_vl) # ! + Cox[j].append(a_vl) + Ccx[j].append(c_vc) # ! + Ccx[j].append(a_vc) # ! + Cux[j].append(c_vu) # ! + Cux[j].append(a_vu) + + # Yield new points + yield a_vc.x + + except IndexError: + for vectors in ab_Cc: + ba_vl = list(vectors[3].x) + ba_vu = list(vectors[4].x) + ba_vl[i + 1] = vut[i + 1] + ba_vu[i + 1] = vut[i + 1] + ba_vu = self.V[tuple(ba_vu)] + yield ba_vu + d_bc_vc = self.split_edge(vectors[1].x, ba_vu.x) # o-s + yield ba_vu + d_bc_vc.connect(vectors[1]) # Connect all to centroid + d_bc_vc.connect(vectors[2]) # Connect all to centroid + d_bc_vc.connect(vectors[3]) # Connect all to centroid + d_bc_vc.connect(vectors[4]) # Connect all to centroid + yield d_bc_vc.x + ba_vl = self.V[tuple(ba_vl)] + yield ba_vl + d_ba_vl = self.split_edge(vectors[3].x, ba_vl.x) + d_ba_vu = self.split_edge(vectors[4].x, ba_vu.x) + d_ba_vc = self.split_edge(d_ba_vl.x, d_ba_vu.x) + yield d_ba_vl + yield d_ba_vu + yield d_ba_vc + c_vc, vl, vu, a_vl, a_vu = vectors + comb = [vl, vu, a_vl, a_vu, + ba_vl, + ba_vu] + comb_iter = itertools.combinations(comb, 2) + for vecs in comb_iter: + self.split_edge(vecs[0].x, vecs[1].x) + + # Copy lists for iteration + cCox = Cox[i] + cCcx = Ccx[i] + cCux = Cux[i] + VL, VC, VU = cCox, cCcx, cCux + for k, (vl, vc, vu) in enumerate(zip(VL, VC, VU)): + # Build aN vertices for each lower-upper pair in N: + a_vu = list(vu.x) + a_vu[i + 1] = vut[i + 1] + + # Connect vertices in N to corresponding vertices + # in aN: + a_vu = self.V[tuple(a_vu)] + yield a_vl.x + # Split the a + b edge of the initial triangulation: + c_vc = self.split_edge(vl.x, a_vu.x) + self.split_edge(vl.x, vu.x) # Equal to vc + c_vc.connect(vco) + c_vc.connect(vc) + c_vc.connect(vl) # Connect c + ac operations + c_vc.connect(vu) # Connect c + ac operations + c_vc.connect(a_vu) # Connect c + ac operations + yield (c_vc.x) + c_vu = self.split_edge(vu.x, + a_vu.x) # yield at end of loop + c_vu.connect(vco) + # Connect remaining cN group vertices + c_vc.connect(c_vu) # Connect cN group vertices + yield (c_vu.x) + + # Update the containers + Cox[i + 1].append(vu) + Ccx[i + 1].append(c_vu) + Cux[i + 1].append(a_vu) + + # Update old containers + s_ab_C.append([c_vc, vl, vu, a_vu]) + + yield a_vu.x + + # Clean class trash + try: + del Cox + del Ccx + del Cux + del ab_C + del ab_Cc + except UnboundLocalError: + pass + + try: + self.triangulated_vectors.remove((tuple(origin_c), + tuple(supremum_c))) + except ValueError: + # Turn this into a logging warning? + pass + # Add newly triangulated vectors: + for vs in sup_set: + self.triangulated_vectors.append((tuple(vco.x), tuple(vs.x))) + + # Extra yield to ensure that the triangulation is completed + if centroid: + vcn_set = set() + c_nn_lists = [] + for vs in sup_set: + # Build centroid + c_nn = self.vpool(vco.x, vs.x) + try: + c_nn.remove(vcn_set) + except KeyError: + pass + c_nn_lists.append(c_nn) + + for c_nn in c_nn_lists: + try: + c_nn.remove(vcn_set) + except KeyError: + pass + + for vs, c_nn in zip(sup_set, c_nn_lists): + # Build centroid + vcn = self.split_edge(vco.x, vs.x) + vcn_set.add(vcn) + try: # Shouldn't be needed? + c_nn.remove(vcn_set) + except KeyError: + pass + for vnn in c_nn: + vcn.connect(vnn) + yield vcn.x + else: + pass + + yield vut + return + + def refine_star(self, v): + """Refine the star domain of a vertex `v`.""" + # Copy lists before iteration + vnn = copy.copy(v.nn) + v1nn = [] + d_v0v1_set = set() + for v1 in vnn: + v1nn.append(copy.copy(v1.nn)) + + for v1, v1nn in zip(vnn, v1nn): + vnnu = v1nn.intersection(vnn) + + d_v0v1 = self.split_edge(v.x, v1.x) + for o_d_v0v1 in d_v0v1_set: + d_v0v1.connect(o_d_v0v1) + d_v0v1_set.add(d_v0v1) + for v2 in vnnu: + d_v1v2 = self.split_edge(v1.x, v2.x) + d_v0v1.connect(d_v1v2) + return + + @cache + def split_edge(self, v1, v2): + v1 = self.V[v1] + v2 = self.V[v2] + # Destroy original edge, if it exists: + v1.disconnect(v2) + # Compute vertex on centre of edge: + try: + vct = (v2.x_a - v1.x_a) / 2.0 + v1.x_a + except TypeError: # Allow for decimal operations + vct = (v2.x_a - v1.x_a) / decimal.Decimal(2.0) + v1.x_a + + vc = self.V[tuple(vct)] + # Connect to original 2 vertices to the new centre vertex + vc.connect(v1) + vc.connect(v2) + return vc + + def vpool(self, origin, supremum): + vot = tuple(origin) + vst = tuple(supremum) + # Initiate vertices in case they don't exist + vo = self.V[vot] + vs = self.V[vst] + + # Remove origin - supremum disconnect + + # Find the lower/upper bounds of the refinement hyperrectangle + bl = list(vot) + bu = list(vst) + for i, (voi, vsi) in enumerate(zip(vot, vst)): + if bl[i] > vsi: + bl[i] = vsi + if bu[i] < voi: + bu[i] = voi + + # NOTE: This is mostly done with sets/lists because we aren't sure + # how well the numpy arrays will scale to thousands of + # dimensions. + vn_pool = set() + vn_pool.update(vo.nn) + vn_pool.update(vs.nn) + cvn_pool = copy.copy(vn_pool) + for vn in cvn_pool: + for i, xi in enumerate(vn.x): + if bl[i] <= xi <= bu[i]: + pass + else: + try: + vn_pool.remove(vn) + except KeyError: + pass # NOTE: Not all neighbours are in initial pool + return vn_pool + + def vf_to_vv(self, vertices, simplices): + """ + Convert a vertex-face mesh to a vertex-vertex mesh used by this class + + Parameters + ---------- + vertices : list + Vertices + simplices : list + Simplices + """ + if self.dim > 1: + for s in simplices: + edges = itertools.combinations(s, self.dim) + for e in edges: + self.V[tuple(vertices[e[0]])].connect( + self.V[tuple(vertices[e[1]])]) + else: + for e in simplices: + self.V[tuple(vertices[e[0]])].connect( + self.V[tuple(vertices[e[1]])]) + return + + def connect_vertex_non_symm(self, v_x, near=None): + """ + Adds a vertex at coords v_x to the complex that is not symmetric to the + initial triangulation and sub-triangulation. + + If near is specified (for example; a star domain or collections of + cells known to contain v) then only those simplices containd in near + will be searched, this greatly speeds up the process. + + If near is not specified this method will search the entire simplicial + complex structure. + + Parameters + ---------- + v_x : tuple + Coordinates of non-symmetric vertex + near : set or list + List of vertices, these are points near v to check for + """ + if near is None: + star = self.V + else: + star = near + # Create the vertex origin + if tuple(v_x) in self.V.cache: + if self.V[v_x] in self.V_non_symm: + pass + else: + return + + self.V[v_x] + found_nn = False + S_rows = [] + for v in star: + S_rows.append(v.x) + + S_rows = np.array(S_rows) + A = np.array(S_rows) - np.array(v_x) + # Iterate through all the possible simplices of S_rows + for s_i in itertools.combinations(range(S_rows.shape[0]), + r=self.dim + 1): + # Check if connected, else s_i is not a simplex + valid_simplex = True + for i in itertools.combinations(s_i, r=2): + # Every combination of vertices must be connected, we check of + # the current iteration of all combinations of s_i are + # connected we break the loop if it is not. + if ((self.V[tuple(S_rows[i[1]])] not in + self.V[tuple(S_rows[i[0]])].nn) + and (self.V[tuple(S_rows[i[0]])] not in + self.V[tuple(S_rows[i[1]])].nn)): + valid_simplex = False + break + + S = S_rows[tuple([s_i])] + if valid_simplex: + if self.deg_simplex(S, proj=None): + valid_simplex = False + + # If s_i is a valid simplex we can test if v_x is inside si + if valid_simplex: + # Find the A_j0 value from the precalculated values + A_j0 = A[tuple([s_i])] + if self.in_simplex(S, v_x, A_j0): + found_nn = True + # breaks the main for loop, s_i is the target simplex: + break + + # Connect the simplex to point + if found_nn: + for i in s_i: + self.V[v_x].connect(self.V[tuple(S_rows[i])]) + # Attached the simplex to storage for all non-symmetric vertices + self.V_non_symm.append(self.V[v_x]) + # this bool value indicates a successful connection if True: + return found_nn + + def in_simplex(self, S, v_x, A_j0=None): + """Check if a vector v_x is in simplex `S`. + + Parameters + ---------- + S : array_like + Array containing simplex entries of vertices as rows + v_x : + A candidate vertex + A_j0 : array, optional, + Allows for A_j0 to be pre-calculated + + Returns + ------- + res : boolean + True if `v_x` is in `S` + """ + A_11 = np.delete(S, 0, 0) - S[0] + + sign_det_A_11 = np.sign(np.linalg.det(A_11)) + if sign_det_A_11 == 0: + # NOTE: We keep the variable A_11, but we loop through A_jj + # ind= + # while sign_det_A_11 == 0: + # A_11 = np.delete(S, ind, 0) - S[ind] + # sign_det_A_11 = np.sign(np.linalg.det(A_11)) + + sign_det_A_11 = -1 # TODO: Choose another det of j instead? + # TODO: Unlikely to work in many cases + + if A_j0 is None: + A_j0 = S - v_x + + for d in range(self.dim + 1): + det_A_jj = (-1)**d * sign_det_A_11 + # TODO: Note that scipy might be faster to add as an optional + # dependency + sign_det_A_j0 = np.sign(np.linalg.det(np.delete(A_j0, d, + 0))) + # TODO: Note if sign_det_A_j0 == then the point is coplanar to the + # current simplex facet, so perhaps return True and attach? + if det_A_jj == sign_det_A_j0: + continue + else: + return False + + return True + + def deg_simplex(self, S, proj=None): + """Test a simplex S for degeneracy (linear dependence in R^dim). + + Parameters + ---------- + S : np.array + Simplex with rows as vertex vectors + proj : array, optional, + If the projection S[1:] - S[0] is already + computed it can be added as an optional argument. + """ + # Strategy: we test all combination of faces, if any of the + # determinants are zero then the vectors lie on the same face and is + # therefore linearly dependent in the space of R^dim + if proj is None: + proj = S[1:] - S[0] + + # TODO: Is checking the projection of one vertex against faces of other + # vertices sufficient? Or do we need to check more vertices in + # dimensions higher than 2? + # TODO: Literature seems to suggest using proj.T, but why is this + # needed? + if np.linalg.det(proj) == 0.0: # TODO: Replace with tolerance? + return True # Simplex is degenerate + else: + return False # Simplex is not degenerate diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_shgo_lib/_vertex.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_shgo_lib/_vertex.py new file mode 100644 index 0000000000000000000000000000000000000000..e47558ee7b9a181638841c34bb63603b5d37e221 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_shgo_lib/_vertex.py @@ -0,0 +1,460 @@ +import collections +from abc import ABC, abstractmethod + +import numpy as np + +from scipy._lib._util import MapWrapper + + +class VertexBase(ABC): + """ + Base class for a vertex. + """ + def __init__(self, x, nn=None, index=None): + """ + Initiation of a vertex object. + + Parameters + ---------- + x : tuple or vector + The geometric location (domain). + nn : list, optional + Nearest neighbour list. + index : int, optional + Index of vertex. + """ + self.x = x + self.hash = hash(self.x) # Save precomputed hash + + if nn is not None: + self.nn = set(nn) # can use .indexupdate to add a new list + else: + self.nn = set() + + self.index = index + + def __hash__(self): + return self.hash + + def __getattr__(self, item): + if item not in ['x_a']: + raise AttributeError(f"{type(self)} object has no attribute " + f"'{item}'") + if item == 'x_a': + self.x_a = np.array(self.x) + return self.x_a + + @abstractmethod + def connect(self, v): + raise NotImplementedError("This method is only implemented with an " + "associated child of the base class.") + + @abstractmethod + def disconnect(self, v): + raise NotImplementedError("This method is only implemented with an " + "associated child of the base class.") + + def star(self): + """Returns the star domain ``st(v)`` of the vertex. + + Parameters + ---------- + v : + The vertex ``v`` in ``st(v)`` + + Returns + ------- + st : set + A set containing all the vertices in ``st(v)`` + """ + self.st = self.nn + self.st.add(self) + return self.st + + +class VertexScalarField(VertexBase): + """ + Add homology properties of a scalar field f: R^n --> R associated with + the geometry built from the VertexBase class + """ + + def __init__(self, x, field=None, nn=None, index=None, field_args=(), + g_cons=None, g_cons_args=()): + """ + Parameters + ---------- + x : tuple, + vector of vertex coordinates + field : callable, optional + a scalar field f: R^n --> R associated with the geometry + nn : list, optional + list of nearest neighbours + index : int, optional + index of the vertex + field_args : tuple, optional + additional arguments to be passed to field + g_cons : callable, optional + constraints on the vertex + g_cons_args : tuple, optional + additional arguments to be passed to g_cons + + """ + super().__init__(x, nn=nn, index=index) + + # Note Vertex is only initiated once for all x so only + # evaluated once + # self.feasible = None + + # self.f is externally defined by the cache to allow parallel + # processing + # None type that will break arithmetic operations unless defined + # self.f = None + + self.check_min = True + self.check_max = True + + def connect(self, v): + """Connects self to another vertex object v. + + Parameters + ---------- + v : VertexBase or VertexScalarField object + """ + if v is not self and v not in self.nn: + self.nn.add(v) + v.nn.add(self) + + # Flags for checking homology properties: + self.check_min = True + self.check_max = True + v.check_min = True + v.check_max = True + + def disconnect(self, v): + if v in self.nn: + self.nn.remove(v) + v.nn.remove(self) + + # Flags for checking homology properties: + self.check_min = True + self.check_max = True + v.check_min = True + v.check_max = True + + def minimiser(self): + """Check whether this vertex is strictly less than all its + neighbours""" + if self.check_min: + self._min = all(self.f < v.f for v in self.nn) + self.check_min = False + + return self._min + + def maximiser(self): + """ + Check whether this vertex is strictly greater than all its + neighbours. + """ + if self.check_max: + self._max = all(self.f > v.f for v in self.nn) + self.check_max = False + + return self._max + + +class VertexVectorField(VertexBase): + """ + Add homology properties of a scalar field f: R^n --> R^m associated with + the geometry built from the VertexBase class. + """ + + def __init__(self, x, sfield=None, vfield=None, field_args=(), + vfield_args=(), g_cons=None, + g_cons_args=(), nn=None, index=None): + super().__init__(x, nn=nn, index=index) + + raise NotImplementedError("This class is still a work in progress") + + +class VertexCacheBase: + """Base class for a vertex cache for a simplicial complex.""" + def __init__(self): + + self.cache = collections.OrderedDict() + self.nfev = 0 # Feasible points + self.index = -1 + + def __iter__(self): + for v in self.cache: + yield self.cache[v] + return + + def size(self): + """Returns the size of the vertex cache.""" + return self.index + 1 + + def print_out(self): + headlen = len(f"Vertex cache of size: {len(self.cache)}:") + print('=' * headlen) + print(f"Vertex cache of size: {len(self.cache)}:") + print('=' * headlen) + for v in self.cache: + self.cache[v].print_out() + + +class VertexCube(VertexBase): + """Vertex class to be used for a pure simplicial complex with no associated + differential geometry (single level domain that exists in R^n)""" + def __init__(self, x, nn=None, index=None): + super().__init__(x, nn=nn, index=index) + + def connect(self, v): + if v is not self and v not in self.nn: + self.nn.add(v) + v.nn.add(self) + + def disconnect(self, v): + if v in self.nn: + self.nn.remove(v) + v.nn.remove(self) + + +class VertexCacheIndex(VertexCacheBase): + def __init__(self): + """ + Class for a vertex cache for a simplicial complex without an associated + field. Useful only for building and visualising a domain complex. + + Parameters + ---------- + """ + super().__init__() + self.Vertex = VertexCube + + def __getitem__(self, x, nn=None): + try: + return self.cache[x] + except KeyError: + self.index += 1 + xval = self.Vertex(x, index=self.index) + # logging.info("New generated vertex at x = {}".format(x)) + # NOTE: Surprisingly high performance increase if logging + # is commented out + self.cache[x] = xval + return self.cache[x] + + +class VertexCacheField(VertexCacheBase): + def __init__(self, field=None, field_args=(), g_cons=None, g_cons_args=(), + workers=1): + """ + Class for a vertex cache for a simplicial complex with an associated + field. + + Parameters + ---------- + field : callable + Scalar or vector field callable. + field_args : tuple, optional + Any additional fixed parameters needed to completely specify the + field function + g_cons : dict or sequence of dict, optional + Constraints definition. + Function(s) ``R**n`` in the form:: + g_cons_args : tuple, optional + Any additional fixed parameters needed to completely specify the + constraint functions + workers : int optional + Uses `multiprocessing.Pool `) to compute the field + functions in parallel. + + """ + super().__init__() + self.index = -1 + self.Vertex = VertexScalarField + self.field = field + self.field_args = field_args + self.wfield = FieldWrapper(field, field_args) # if workers is not 1 + + self.g_cons = g_cons + self.g_cons_args = g_cons_args + self.wgcons = ConstraintWrapper(g_cons, g_cons_args) + self.gpool = set() # A set of tuples to process for feasibility + + # Field processing objects + self.fpool = set() # A set of tuples to process for scalar function + self.sfc_lock = False # True if self.fpool is non-Empty + + self.workers = workers + self._mapwrapper = MapWrapper(workers) + + if workers == 1: + self.process_gpool = self.proc_gpool + if g_cons is None: + self.process_fpool = self.proc_fpool_nog + else: + self.process_fpool = self.proc_fpool_g + else: + self.process_gpool = self.pproc_gpool + if g_cons is None: + self.process_fpool = self.pproc_fpool_nog + else: + self.process_fpool = self.pproc_fpool_g + + def __getitem__(self, x, nn=None): + try: + return self.cache[x] + except KeyError: + self.index += 1 + xval = self.Vertex(x, field=self.field, nn=nn, index=self.index, + field_args=self.field_args, + g_cons=self.g_cons, + g_cons_args=self.g_cons_args) + + self.cache[x] = xval # Define in cache + self.gpool.add(xval) # Add to pool for processing feasibility + self.fpool.add(xval) # Add to pool for processing field values + return self.cache[x] + + def __getstate__(self): + self_dict = self.__dict__.copy() + del self_dict['pool'] + return self_dict + + def process_pools(self): + if self.g_cons is not None: + self.process_gpool() + self.process_fpool() + self.proc_minimisers() + + def feasibility_check(self, v): + v.feasible = True + for g, args in zip(self.g_cons, self.g_cons_args): + # constraint may return more than 1 value. + if np.any(g(v.x_a, *args) < 0.0): + v.f = np.inf + v.feasible = False + break + + def compute_sfield(self, v): + """Compute the scalar field values of a vertex object `v`. + + Parameters + ---------- + v : VertexBase or VertexScalarField object + """ + try: + v.f = self.field(v.x_a, *self.field_args) + self.nfev += 1 + except AttributeError: + v.f = np.inf + # logging.warning(f"Field function not found at x = {self.x_a}") + if np.isnan(v.f): + v.f = np.inf + + def proc_gpool(self): + """Process all constraints.""" + if self.g_cons is not None: + for v in self.gpool: + self.feasibility_check(v) + # Clean the pool + self.gpool = set() + + def pproc_gpool(self): + """Process all constraints in parallel.""" + gpool_l = [] + for v in self.gpool: + gpool_l.append(v.x_a) + + G = self._mapwrapper(self.wgcons.gcons, gpool_l) + for v, g in zip(self.gpool, G): + v.feasible = g # set vertex object attribute v.feasible = g (bool) + + def proc_fpool_g(self): + """Process all field functions with constraints supplied.""" + for v in self.fpool: + if v.feasible: + self.compute_sfield(v) + # Clean the pool + self.fpool = set() + + def proc_fpool_nog(self): + """Process all field functions with no constraints supplied.""" + for v in self.fpool: + self.compute_sfield(v) + # Clean the pool + self.fpool = set() + + def pproc_fpool_g(self): + """ + Process all field functions with constraints supplied in parallel. + """ + self.wfield.func + fpool_l = [] + for v in self.fpool: + if v.feasible: + fpool_l.append(v.x_a) + else: + v.f = np.inf + F = self._mapwrapper(self.wfield.func, fpool_l) + for va, f in zip(fpool_l, F): + vt = tuple(va) + self[vt].f = f # set vertex object attribute v.f = f + self.nfev += 1 + # Clean the pool + self.fpool = set() + + def pproc_fpool_nog(self): + """ + Process all field functions with no constraints supplied in parallel. + """ + self.wfield.func + fpool_l = [] + for v in self.fpool: + fpool_l.append(v.x_a) + F = self._mapwrapper(self.wfield.func, fpool_l) + for va, f in zip(fpool_l, F): + vt = tuple(va) + self[vt].f = f # set vertex object attribute v.f = f + self.nfev += 1 + # Clean the pool + self.fpool = set() + + def proc_minimisers(self): + """Check for minimisers.""" + for v in self: + v.minimiser() + v.maximiser() + + +class ConstraintWrapper: + """Object to wrap constraints to pass to `multiprocessing.Pool`.""" + def __init__(self, g_cons, g_cons_args): + self.g_cons = g_cons + self.g_cons_args = g_cons_args + + def gcons(self, v_x_a): + vfeasible = True + for g, args in zip(self.g_cons, self.g_cons_args): + # constraint may return more than 1 value. + if np.any(g(v_x_a, *args) < 0.0): + vfeasible = False + break + return vfeasible + + +class FieldWrapper: + """Object to wrap field to pass to `multiprocessing.Pool`.""" + def __init__(self, field, field_args): + self.field = field + self.field_args = field_args + + def func(self, v_x_a): + try: + v_f = self.field(v_x_a, *self.field_args) + except Exception: + v_f = np.inf + if np.isnan(v_f): + v_f = np.inf + + return v_f diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_slsqp.cpython-310-x86_64-linux-gnu.so b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_slsqp.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..1f64a0469d430cfacd71e0d9a2e72eb73fb28c66 Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_slsqp.cpython-310-x86_64-linux-gnu.so differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_slsqp_py.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_slsqp_py.py new file mode 100644 index 0000000000000000000000000000000000000000..0ab66837497a6626d042d56530ead46ea134ad9c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_slsqp_py.py @@ -0,0 +1,511 @@ +""" +This module implements the Sequential Least Squares Programming optimization +algorithm (SLSQP), originally developed by Dieter Kraft. +See http://www.netlib.org/toms/733 + +Functions +--------- +.. autosummary:: + :toctree: generated/ + + approx_jacobian + fmin_slsqp + +""" + +__all__ = ['approx_jacobian', 'fmin_slsqp'] + +import numpy as np +from scipy.optimize._slsqp import slsqp +from numpy import (zeros, array, linalg, append, concatenate, finfo, + sqrt, vstack, isfinite, atleast_1d) +from ._optimize import (OptimizeResult, _check_unknown_options, + _prepare_scalar_function, _clip_x_for_func, + _check_clip_x) +from ._numdiff import approx_derivative +from ._constraints import old_bound_to_new, _arr_to_scalar +from scipy._lib._array_api import array_namespace +from scipy._lib import array_api_extra as xpx + + +__docformat__ = "restructuredtext en" + +_epsilon = sqrt(finfo(float).eps) + + +def approx_jacobian(x, func, epsilon, *args): + """ + Approximate the Jacobian matrix of a callable function. + + Parameters + ---------- + x : array_like + The state vector at which to compute the Jacobian matrix. + func : callable f(x,*args) + The vector-valued function. + epsilon : float + The perturbation used to determine the partial derivatives. + args : sequence + Additional arguments passed to func. + + Returns + ------- + An array of dimensions ``(lenf, lenx)`` where ``lenf`` is the length + of the outputs of `func`, and ``lenx`` is the number of elements in + `x`. + + Notes + ----- + The approximation is done using forward differences. + + """ + # approx_derivative returns (m, n) == (lenf, lenx) + jac = approx_derivative(func, x, method='2-point', abs_step=epsilon, + args=args) + # if func returns a scalar jac.shape will be (lenx,). Make sure + # it's at least a 2D array. + return np.atleast_2d(jac) + + +def fmin_slsqp(func, x0, eqcons=(), f_eqcons=None, ieqcons=(), f_ieqcons=None, + bounds=(), fprime=None, fprime_eqcons=None, + fprime_ieqcons=None, args=(), iter=100, acc=1.0E-6, + iprint=1, disp=None, full_output=0, epsilon=_epsilon, + callback=None): + """ + Minimize a function using Sequential Least Squares Programming + + Python interface function for the SLSQP Optimization subroutine + originally implemented by Dieter Kraft. + + Parameters + ---------- + func : callable f(x,*args) + Objective function. Must return a scalar. + x0 : 1-D ndarray of float + Initial guess for the independent variable(s). + eqcons : list, optional + A list of functions of length n such that + eqcons[j](x,*args) == 0.0 in a successfully optimized + problem. + f_eqcons : callable f(x,*args), optional + Returns a 1-D array in which each element must equal 0.0 in a + successfully optimized problem. If f_eqcons is specified, + eqcons is ignored. + ieqcons : list, optional + A list of functions of length n such that + ieqcons[j](x,*args) >= 0.0 in a successfully optimized + problem. + f_ieqcons : callable f(x,*args), optional + Returns a 1-D ndarray in which each element must be greater or + equal to 0.0 in a successfully optimized problem. If + f_ieqcons is specified, ieqcons is ignored. + bounds : list, optional + A list of tuples specifying the lower and upper bound + for each independent variable [(xl0, xu0),(xl1, xu1),...] + Infinite values will be interpreted as large floating values. + fprime : callable ``f(x,*args)``, optional + A function that evaluates the partial derivatives of func. + fprime_eqcons : callable ``f(x,*args)``, optional + A function of the form ``f(x, *args)`` that returns the m by n + array of equality constraint normals. If not provided, + the normals will be approximated. The array returned by + fprime_eqcons should be sized as ( len(eqcons), len(x0) ). + fprime_ieqcons : callable ``f(x,*args)``, optional + A function of the form ``f(x, *args)`` that returns the m by n + array of inequality constraint normals. If not provided, + the normals will be approximated. The array returned by + fprime_ieqcons should be sized as ( len(ieqcons), len(x0) ). + args : sequence, optional + Additional arguments passed to func and fprime. + iter : int, optional + The maximum number of iterations. + acc : float, optional + Requested accuracy. + iprint : int, optional + The verbosity of fmin_slsqp : + + * iprint <= 0 : Silent operation + * iprint == 1 : Print summary upon completion (default) + * iprint >= 2 : Print status of each iterate and summary + disp : int, optional + Overrides the iprint interface (preferred). + full_output : bool, optional + If False, return only the minimizer of func (default). + Otherwise, output final objective function and summary + information. + epsilon : float, optional + The step size for finite-difference derivative estimates. + callback : callable, optional + Called after each iteration, as ``callback(x)``, where ``x`` is the + current parameter vector. + + Returns + ------- + out : ndarray of float + The final minimizer of func. + fx : ndarray of float, if full_output is true + The final value of the objective function. + its : int, if full_output is true + The number of iterations. + imode : int, if full_output is true + The exit mode from the optimizer (see below). + smode : string, if full_output is true + Message describing the exit mode from the optimizer. + + See also + -------- + minimize: Interface to minimization algorithms for multivariate + functions. See the 'SLSQP' `method` in particular. + + Notes + ----- + Exit modes are defined as follows: + + - ``-1`` : Gradient evaluation required (g & a) + - ``0`` : Optimization terminated successfully + - ``1`` : Function evaluation required (f & c) + - ``2`` : More equality constraints than independent variables + - ``3`` : More than 3*n iterations in LSQ subproblem + - ``4`` : Inequality constraints incompatible + - ``5`` : Singular matrix E in LSQ subproblem + - ``6`` : Singular matrix C in LSQ subproblem + - ``7`` : Rank-deficient equality constraint subproblem HFTI + - ``8`` : Positive directional derivative for linesearch + - ``9`` : Iteration limit reached + + Examples + -------- + Examples are given :ref:`in the tutorial `. + + """ + if disp is not None: + iprint = disp + + opts = {'maxiter': iter, + 'ftol': acc, + 'iprint': iprint, + 'disp': iprint != 0, + 'eps': epsilon, + 'callback': callback} + + # Build the constraints as a tuple of dictionaries + cons = () + # 1. constraints of the 1st kind (eqcons, ieqcons); no Jacobian; take + # the same extra arguments as the objective function. + cons += tuple({'type': 'eq', 'fun': c, 'args': args} for c in eqcons) + cons += tuple({'type': 'ineq', 'fun': c, 'args': args} for c in ieqcons) + # 2. constraints of the 2nd kind (f_eqcons, f_ieqcons) and their Jacobian + # (fprime_eqcons, fprime_ieqcons); also take the same extra arguments + # as the objective function. + if f_eqcons: + cons += ({'type': 'eq', 'fun': f_eqcons, 'jac': fprime_eqcons, + 'args': args}, ) + if f_ieqcons: + cons += ({'type': 'ineq', 'fun': f_ieqcons, 'jac': fprime_ieqcons, + 'args': args}, ) + + res = _minimize_slsqp(func, x0, args, jac=fprime, bounds=bounds, + constraints=cons, **opts) + if full_output: + return res['x'], res['fun'], res['nit'], res['status'], res['message'] + else: + return res['x'] + + +def _minimize_slsqp(func, x0, args=(), jac=None, bounds=None, + constraints=(), + maxiter=100, ftol=1.0E-6, iprint=1, disp=False, + eps=_epsilon, callback=None, finite_diff_rel_step=None, + **unknown_options): + """ + Minimize a scalar function of one or more variables using Sequential + Least Squares Programming (SLSQP). + + Options + ------- + ftol : float + Precision goal for the value of f in the stopping criterion. + eps : float + Step size used for numerical approximation of the Jacobian. + disp : bool + Set to True to print convergence messages. If False, + `verbosity` is ignored and set to 0. + maxiter : int + Maximum number of iterations. + finite_diff_rel_step : None or array_like, optional + If ``jac in ['2-point', '3-point', 'cs']`` the relative step size to + use for numerical approximation of `jac`. The absolute step + size is computed as ``h = rel_step * sign(x) * max(1, abs(x))``, + possibly adjusted to fit into the bounds. For ``method='3-point'`` + the sign of `h` is ignored. If None (default) then step is selected + automatically. + """ + _check_unknown_options(unknown_options) + iter = maxiter - 1 + acc = ftol + epsilon = eps + + if not disp: + iprint = 0 + + # Transform x0 into an array. + xp = array_namespace(x0) + x0 = xpx.atleast_nd(xp.asarray(x0), ndim=1, xp=xp) + dtype = xp.float64 + if xp.isdtype(x0.dtype, "real floating"): + dtype = x0.dtype + x = xp.reshape(xp.astype(x0, dtype), -1) + + # SLSQP is sent 'old-style' bounds, 'new-style' bounds are required by + # ScalarFunction + if bounds is None or len(bounds) == 0: + new_bounds = (-np.inf, np.inf) + else: + new_bounds = old_bound_to_new(bounds) + + # clip the initial guess to bounds, otherwise ScalarFunction doesn't work + x = np.clip(x, new_bounds[0], new_bounds[1]) + + # Constraints are triaged per type into a dictionary of tuples + if isinstance(constraints, dict): + constraints = (constraints, ) + + cons = {'eq': (), 'ineq': ()} + for ic, con in enumerate(constraints): + # check type + try: + ctype = con['type'].lower() + except KeyError as e: + raise KeyError('Constraint %d has no type defined.' % ic) from e + except TypeError as e: + raise TypeError('Constraints must be defined using a ' + 'dictionary.') from e + except AttributeError as e: + raise TypeError("Constraint's type must be a string.") from e + else: + if ctype not in ['eq', 'ineq']: + raise ValueError(f"Unknown constraint type '{con['type']}'.") + + # check function + if 'fun' not in con: + raise ValueError('Constraint %d has no function defined.' % ic) + + # check Jacobian + cjac = con.get('jac') + if cjac is None: + # approximate Jacobian function. The factory function is needed + # to keep a reference to `fun`, see gh-4240. + def cjac_factory(fun): + def cjac(x, *args): + x = _check_clip_x(x, new_bounds) + + if jac in ['2-point', '3-point', 'cs']: + return approx_derivative(fun, x, method=jac, args=args, + rel_step=finite_diff_rel_step, + bounds=new_bounds) + else: + return approx_derivative(fun, x, method='2-point', + abs_step=epsilon, args=args, + bounds=new_bounds) + + return cjac + cjac = cjac_factory(con['fun']) + + # update constraints' dictionary + cons[ctype] += ({'fun': con['fun'], + 'jac': cjac, + 'args': con.get('args', ())}, ) + + exit_modes = {-1: "Gradient evaluation required (g & a)", + 0: "Optimization terminated successfully", + 1: "Function evaluation required (f & c)", + 2: "More equality constraints than independent variables", + 3: "More than 3*n iterations in LSQ subproblem", + 4: "Inequality constraints incompatible", + 5: "Singular matrix E in LSQ subproblem", + 6: "Singular matrix C in LSQ subproblem", + 7: "Rank-deficient equality constraint subproblem HFTI", + 8: "Positive directional derivative for linesearch", + 9: "Iteration limit reached"} + + # Set the parameters that SLSQP will need + # meq, mieq: number of equality and inequality constraints + meq = sum(map(len, [atleast_1d(c['fun'](x, *c['args'])) + for c in cons['eq']])) + mieq = sum(map(len, [atleast_1d(c['fun'](x, *c['args'])) + for c in cons['ineq']])) + # m = The total number of constraints + m = meq + mieq + # la = The number of constraints, or 1 if there are no constraints + la = array([1, m]).max() + # n = The number of independent variables + n = len(x) + + # Define the workspaces for SLSQP + n1 = n + 1 + mineq = m - meq + n1 + n1 + len_w = (3*n1+m)*(n1+1)+(n1-meq+1)*(mineq+2) + 2*mineq+(n1+mineq)*(n1-meq) \ + + 2*meq + n1 + ((n+1)*n)//2 + 2*m + 3*n + 3*n1 + 1 + len_jw = mineq + w = zeros(len_w) + jw = zeros(len_jw) + + # Decompose bounds into xl and xu + if bounds is None or len(bounds) == 0: + xl = np.empty(n, dtype=float) + xu = np.empty(n, dtype=float) + xl.fill(np.nan) + xu.fill(np.nan) + else: + bnds = array([(_arr_to_scalar(l), _arr_to_scalar(u)) + for (l, u) in bounds], float) + if bnds.shape[0] != n: + raise IndexError('SLSQP Error: the length of bounds is not ' + 'compatible with that of x0.') + + with np.errstate(invalid='ignore'): + bnderr = bnds[:, 0] > bnds[:, 1] + + if bnderr.any(): + raise ValueError("SLSQP Error: lb > ub in bounds " + f"{', '.join(str(b) for b in bnderr)}.") + xl, xu = bnds[:, 0], bnds[:, 1] + + # Mark infinite bounds with nans; the Fortran code understands this + infbnd = ~isfinite(bnds) + xl[infbnd[:, 0]] = np.nan + xu[infbnd[:, 1]] = np.nan + + # ScalarFunction provides function and gradient evaluation + sf = _prepare_scalar_function(func, x, jac=jac, args=args, epsilon=eps, + finite_diff_rel_step=finite_diff_rel_step, + bounds=new_bounds) + # gh11403 SLSQP sometimes exceeds bounds by 1 or 2 ULP, make sure this + # doesn't get sent to the func/grad evaluator. + wrapped_fun = _clip_x_for_func(sf.fun, new_bounds) + wrapped_grad = _clip_x_for_func(sf.grad, new_bounds) + + # Initialize the iteration counter and the mode value + mode = array(0, int) + acc = array(acc, float) + majiter = array(iter, int) + majiter_prev = 0 + + # Initialize internal SLSQP state variables + alpha = array(0, float) + f0 = array(0, float) + gs = array(0, float) + h1 = array(0, float) + h2 = array(0, float) + h3 = array(0, float) + h4 = array(0, float) + t = array(0, float) + t0 = array(0, float) + tol = array(0, float) + iexact = array(0, int) + incons = array(0, int) + ireset = array(0, int) + itermx = array(0, int) + line = array(0, int) + n1 = array(0, int) + n2 = array(0, int) + n3 = array(0, int) + + # Print the header if iprint >= 2 + if iprint >= 2: + print("%5s %5s %16s %16s" % ("NIT", "FC", "OBJFUN", "GNORM")) + + # mode is zero on entry, so call objective, constraints and gradients + # there should be no func evaluations here because it's cached from + # ScalarFunction + fx = wrapped_fun(x) + g = append(wrapped_grad(x), 0.0) + c = _eval_constraint(x, cons) + a = _eval_con_normals(x, cons, la, n, m, meq, mieq) + + while 1: + # Call SLSQP + slsqp(m, meq, x, xl, xu, fx, c, g, a, acc, majiter, mode, w, jw, + alpha, f0, gs, h1, h2, h3, h4, t, t0, tol, + iexact, incons, ireset, itermx, line, + n1, n2, n3) + + if mode == 1: # objective and constraint evaluation required + fx = wrapped_fun(x) + c = _eval_constraint(x, cons) + + if mode == -1: # gradient evaluation required + g = append(wrapped_grad(x), 0.0) + a = _eval_con_normals(x, cons, la, n, m, meq, mieq) + + if majiter > majiter_prev: + # call callback if major iteration has incremented + if callback is not None: + callback(np.copy(x)) + + # Print the status of the current iterate if iprint > 2 + if iprint >= 2: + print("%5i %5i % 16.6E % 16.6E" % (majiter, sf.nfev, + fx, linalg.norm(g))) + + # If exit mode is not -1 or 1, slsqp has completed + if abs(mode) != 1: + break + + majiter_prev = int(majiter) + + # Optimization loop complete. Print status if requested + if iprint >= 1: + print(exit_modes[int(mode)] + " (Exit mode " + str(mode) + ')') + print(" Current function value:", fx) + print(" Iterations:", majiter) + print(" Function evaluations:", sf.nfev) + print(" Gradient evaluations:", sf.ngev) + + return OptimizeResult(x=x, fun=fx, jac=g[:-1], nit=int(majiter), + nfev=sf.nfev, njev=sf.ngev, status=int(mode), + message=exit_modes[int(mode)], success=(mode == 0)) + + +def _eval_constraint(x, cons): + # Compute constraints + if cons['eq']: + c_eq = concatenate([atleast_1d(con['fun'](x, *con['args'])) + for con in cons['eq']]) + else: + c_eq = zeros(0) + + if cons['ineq']: + c_ieq = concatenate([atleast_1d(con['fun'](x, *con['args'])) + for con in cons['ineq']]) + else: + c_ieq = zeros(0) + + # Now combine c_eq and c_ieq into a single matrix + c = concatenate((c_eq, c_ieq)) + return c + + +def _eval_con_normals(x, cons, la, n, m, meq, mieq): + # Compute the normals of the constraints + if cons['eq']: + a_eq = vstack([con['jac'](x, *con['args']) + for con in cons['eq']]) + else: # no equality constraint + a_eq = zeros((meq, n)) + + if cons['ineq']: + a_ieq = vstack([con['jac'](x, *con['args']) + for con in cons['ineq']]) + else: # no inequality constraint + a_ieq = zeros((mieq, n)) + + # Now combine a_eq and a_ieq into a single a matrix + if m == 0: # no constraints + a = zeros((la, n)) + else: + a = vstack((a_eq, a_ieq)) + a = concatenate((a, zeros([la, 1])), 1) + + return a diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_spectral.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_spectral.py new file mode 100644 index 0000000000000000000000000000000000000000..5ff5bef0283b2d6b6c018c1c8b98cd46a335d7cb --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_spectral.py @@ -0,0 +1,260 @@ +""" +Spectral Algorithm for Nonlinear Equations +""" +import collections + +import numpy as np +from scipy.optimize import OptimizeResult +from scipy.optimize._optimize import _check_unknown_options +from ._linesearch import _nonmonotone_line_search_cruz, _nonmonotone_line_search_cheng + +class _NoConvergence(Exception): + pass + + +def _root_df_sane(func, x0, args=(), ftol=1e-8, fatol=1e-300, maxfev=1000, + fnorm=None, callback=None, disp=False, M=10, eta_strategy=None, + sigma_eps=1e-10, sigma_0=1.0, line_search='cruz', **unknown_options): + r""" + Solve nonlinear equation with the DF-SANE method + + Options + ------- + ftol : float, optional + Relative norm tolerance. + fatol : float, optional + Absolute norm tolerance. + Algorithm terminates when ``||func(x)|| < fatol + ftol ||func(x_0)||``. + fnorm : callable, optional + Norm to use in the convergence check. If None, 2-norm is used. + maxfev : int, optional + Maximum number of function evaluations. + disp : bool, optional + Whether to print convergence process to stdout. + eta_strategy : callable, optional + Choice of the ``eta_k`` parameter, which gives slack for growth + of ``||F||**2``. Called as ``eta_k = eta_strategy(k, x, F)`` with + `k` the iteration number, `x` the current iterate and `F` the current + residual. Should satisfy ``eta_k > 0`` and ``sum(eta, k=0..inf) < inf``. + Default: ``||F||**2 / (1 + k)**2``. + sigma_eps : float, optional + The spectral coefficient is constrained to ``sigma_eps < sigma < 1/sigma_eps``. + Default: 1e-10 + sigma_0 : float, optional + Initial spectral coefficient. + Default: 1.0 + M : int, optional + Number of iterates to include in the nonmonotonic line search. + Default: 10 + line_search : {'cruz', 'cheng'} + Type of line search to employ. 'cruz' is the original one defined in + [Martinez & Raydan. Math. Comp. 75, 1429 (2006)], 'cheng' is + a modified search defined in [Cheng & Li. IMA J. Numer. Anal. 29, 814 (2009)]. + Default: 'cruz' + + References + ---------- + .. [1] "Spectral residual method without gradient information for solving + large-scale nonlinear systems of equations." W. La Cruz, + J.M. Martinez, M. Raydan. Math. Comp. **75**, 1429 (2006). + .. [2] W. La Cruz, Opt. Meth. Software, 29, 24 (2014). + .. [3] W. Cheng, D.-H. Li. IMA J. Numer. Anal. **29**, 814 (2009). + + """ + _check_unknown_options(unknown_options) + + if line_search not in ('cheng', 'cruz'): + raise ValueError(f"Invalid value {line_search!r} for 'line_search'") + + nexp = 2 + + if eta_strategy is None: + # Different choice from [1], as their eta is not invariant + # vs. scaling of F. + def eta_strategy(k, x, F): + # Obtain squared 2-norm of the initial residual from the outer scope + return f_0 / (1 + k)**2 + + if fnorm is None: + def fnorm(F): + # Obtain squared 2-norm of the current residual from the outer scope + return f_k**(1.0/nexp) + + def fmerit(F): + return np.linalg.norm(F)**nexp + + nfev = [0] + f, x_k, x_shape, f_k, F_k, is_complex = _wrap_func(func, x0, fmerit, + nfev, maxfev, args) + + k = 0 + f_0 = f_k + sigma_k = sigma_0 + + F_0_norm = fnorm(F_k) + + # For the 'cruz' line search + prev_fs = collections.deque([f_k], M) + + # For the 'cheng' line search + Q = 1.0 + C = f_0 + + converged = False + message = "too many function evaluations required" + + while True: + F_k_norm = fnorm(F_k) + + if disp: + print("iter %d: ||F|| = %g, sigma = %g" % (k, F_k_norm, sigma_k)) + + if callback is not None: + callback(x_k, F_k) + + if F_k_norm < ftol * F_0_norm + fatol: + # Converged! + message = "successful convergence" + converged = True + break + + # Control spectral parameter, from [2] + if abs(sigma_k) > 1/sigma_eps: + sigma_k = 1/sigma_eps * np.sign(sigma_k) + elif abs(sigma_k) < sigma_eps: + sigma_k = sigma_eps + + # Line search direction + d = -sigma_k * F_k + + # Nonmonotone line search + eta = eta_strategy(k, x_k, F_k) + try: + if line_search == 'cruz': + alpha, xp, fp, Fp = _nonmonotone_line_search_cruz(f, x_k, d, prev_fs, + eta=eta) + elif line_search == 'cheng': + alpha, xp, fp, Fp, C, Q = _nonmonotone_line_search_cheng(f, x_k, d, f_k, + C, Q, eta=eta) + except _NoConvergence: + break + + # Update spectral parameter + s_k = xp - x_k + y_k = Fp - F_k + sigma_k = np.vdot(s_k, s_k) / np.vdot(s_k, y_k) + + # Take step + x_k = xp + F_k = Fp + f_k = fp + + # Store function value + if line_search == 'cruz': + prev_fs.append(fp) + + k += 1 + + x = _wrap_result(x_k, is_complex, shape=x_shape) + F = _wrap_result(F_k, is_complex) + + result = OptimizeResult(x=x, success=converged, + message=message, + fun=F, nfev=nfev[0], nit=k, method="df-sane") + + return result + + +def _wrap_func(func, x0, fmerit, nfev_list, maxfev, args=()): + """ + Wrap a function and an initial value so that (i) complex values + are wrapped to reals, and (ii) value for a merit function + fmerit(x, f) is computed at the same time, (iii) iteration count + is maintained and an exception is raised if it is exceeded. + + Parameters + ---------- + func : callable + Function to wrap + x0 : ndarray + Initial value + fmerit : callable + Merit function fmerit(f) for computing merit value from residual. + nfev_list : list + List to store number of evaluations in. Should be [0] in the beginning. + maxfev : int + Maximum number of evaluations before _NoConvergence is raised. + args : tuple + Extra arguments to func + + Returns + ------- + wrap_func : callable + Wrapped function, to be called as + ``F, fp = wrap_func(x0)`` + x0_wrap : ndarray of float + Wrapped initial value; raveled to 1-D and complex + values mapped to reals. + x0_shape : tuple + Shape of the initial value array + f : float + Merit function at F + F : ndarray of float + Residual at x0_wrap + is_complex : bool + Whether complex values were mapped to reals + + """ + x0 = np.asarray(x0) + x0_shape = x0.shape + F = np.asarray(func(x0, *args)).ravel() + is_complex = np.iscomplexobj(x0) or np.iscomplexobj(F) + x0 = x0.ravel() + + nfev_list[0] = 1 + + if is_complex: + def wrap_func(x): + if nfev_list[0] >= maxfev: + raise _NoConvergence() + nfev_list[0] += 1 + z = _real2complex(x).reshape(x0_shape) + v = np.asarray(func(z, *args)).ravel() + F = _complex2real(v) + f = fmerit(F) + return f, F + + x0 = _complex2real(x0) + F = _complex2real(F) + else: + def wrap_func(x): + if nfev_list[0] >= maxfev: + raise _NoConvergence() + nfev_list[0] += 1 + x = x.reshape(x0_shape) + F = np.asarray(func(x, *args)).ravel() + f = fmerit(F) + return f, F + + return wrap_func, x0, x0_shape, fmerit(F), F, is_complex + + +def _wrap_result(result, is_complex, shape=None): + """ + Convert from real to complex and reshape result arrays. + """ + if is_complex: + z = _real2complex(result) + else: + z = result + if shape is not None: + z = z.reshape(shape) + return z + + +def _real2complex(x): + return np.ascontiguousarray(x, dtype=float).view(np.complex128) + + +def _complex2real(z): + return np.ascontiguousarray(z, dtype=complex).view(np.float64) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_tnc.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_tnc.py new file mode 100644 index 0000000000000000000000000000000000000000..327fe4262e25f2f7e2c95d7e5261b6f188e72881 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_tnc.py @@ -0,0 +1,431 @@ +# TNC Python interface +# @(#) $Jeannot: tnc.py,v 1.11 2005/01/28 18:27:31 js Exp $ + +# Copyright (c) 2004-2005, Jean-Sebastien Roy (js@jeannot.org) + +# Permission is hereby granted, free of charge, to any person obtaining a +# copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: + +# The above copyright notice and this permission notice shall be included +# in all copies or substantial portions of the Software. + +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +""" +TNC: A Python interface to the TNC non-linear optimizer + +TNC is a non-linear optimizer. To use it, you must provide a function to +minimize. The function must take one argument: the list of coordinates where to +evaluate the function; and it must return either a tuple, whose first element is the +value of the function, and whose second argument is the gradient of the function +(as a list of values); or None, to abort the minimization. +""" + +from scipy.optimize import _moduleTNC as moduleTNC +from ._optimize import (MemoizeJac, OptimizeResult, _check_unknown_options, + _prepare_scalar_function) +from ._constraints import old_bound_to_new +from scipy._lib._array_api import array_namespace +from scipy._lib import array_api_extra as xpx + +from numpy import inf, array, zeros + +__all__ = ['fmin_tnc'] + + +MSG_NONE = 0 # No messages +MSG_ITER = 1 # One line per iteration +MSG_INFO = 2 # Informational messages +MSG_VERS = 4 # Version info +MSG_EXIT = 8 # Exit reasons +MSG_ALL = MSG_ITER + MSG_INFO + MSG_VERS + MSG_EXIT + +MSGS = { + MSG_NONE: "No messages", + MSG_ITER: "One line per iteration", + MSG_INFO: "Informational messages", + MSG_VERS: "Version info", + MSG_EXIT: "Exit reasons", + MSG_ALL: "All messages" +} + +INFEASIBLE = -1 # Infeasible (lower bound > upper bound) +LOCALMINIMUM = 0 # Local minimum reached (|pg| ~= 0) +FCONVERGED = 1 # Converged (|f_n-f_(n-1)| ~= 0) +XCONVERGED = 2 # Converged (|x_n-x_(n-1)| ~= 0) +MAXFUN = 3 # Max. number of function evaluations reached +LSFAIL = 4 # Linear search failed +CONSTANT = 5 # All lower bounds are equal to the upper bounds +NOPROGRESS = 6 # Unable to progress +USERABORT = 7 # User requested end of minimization + +RCSTRINGS = { + INFEASIBLE: "Infeasible (lower bound > upper bound)", + LOCALMINIMUM: "Local minimum reached (|pg| ~= 0)", + FCONVERGED: "Converged (|f_n-f_(n-1)| ~= 0)", + XCONVERGED: "Converged (|x_n-x_(n-1)| ~= 0)", + MAXFUN: "Max. number of function evaluations reached", + LSFAIL: "Linear search failed", + CONSTANT: "All lower bounds are equal to the upper bounds", + NOPROGRESS: "Unable to progress", + USERABORT: "User requested end of minimization" +} + +# Changes to interface made by Travis Oliphant, Apr. 2004 for inclusion in +# SciPy + + +def fmin_tnc(func, x0, fprime=None, args=(), approx_grad=0, + bounds=None, epsilon=1e-8, scale=None, offset=None, + messages=MSG_ALL, maxCGit=-1, maxfun=None, eta=-1, + stepmx=0, accuracy=0, fmin=0, ftol=-1, xtol=-1, pgtol=-1, + rescale=-1, disp=None, callback=None): + r""" + Minimize a function with variables subject to bounds, using + gradient information in a truncated Newton algorithm. This + method wraps a C implementation of the algorithm. + + Parameters + ---------- + func : callable ``func(x, *args)`` + Function to minimize. Must do one of: + + 1. Return f and g, where f is the value of the function and g its + gradient (a list of floats). + + 2. Return the function value but supply gradient function + separately as `fprime`. + + 3. Return the function value and set ``approx_grad=True``. + + If the function returns None, the minimization + is aborted. + x0 : array_like + Initial estimate of minimum. + fprime : callable ``fprime(x, *args)``, optional + Gradient of `func`. If None, then either `func` must return the + function value and the gradient (``f,g = func(x, *args)``) + or `approx_grad` must be True. + args : tuple, optional + Arguments to pass to function. + approx_grad : bool, optional + If true, approximate the gradient numerically. + bounds : list, optional + (min, max) pairs for each element in x0, defining the + bounds on that parameter. Use None or +/-inf for one of + min or max when there is no bound in that direction. + epsilon : float, optional + Used if approx_grad is True. The stepsize in a finite + difference approximation for fprime. + scale : array_like, optional + Scaling factors to apply to each variable. If None, the + factors are up-low for interval bounded variables and + 1+|x| for the others. Defaults to None. + offset : array_like, optional + Value to subtract from each variable. If None, the + offsets are (up+low)/2 for interval bounded variables + and x for the others. + messages : int, optional + Bit mask used to select messages display during + minimization values defined in the MSGS dict. Defaults to + MGS_ALL. + disp : int, optional + Integer interface to messages. 0 = no message, 5 = all messages + maxCGit : int, optional + Maximum number of hessian*vector evaluations per main + iteration. If maxCGit == 0, the direction chosen is + -gradient if maxCGit < 0, maxCGit is set to + max(1,min(50,n/2)). Defaults to -1. + maxfun : int, optional + Maximum number of function evaluation. If None, maxfun is + set to max(100, 10*len(x0)). Defaults to None. Note that this function + may violate the limit because of evaluating gradients by numerical + differentiation. + eta : float, optional + Severity of the line search. If < 0 or > 1, set to 0.25. + Defaults to -1. + stepmx : float, optional + Maximum step for the line search. May be increased during + call. If too small, it will be set to 10.0. Defaults to 0. + accuracy : float, optional + Relative precision for finite difference calculations. If + <= machine_precision, set to sqrt(machine_precision). + Defaults to 0. + fmin : float, optional + Minimum function value estimate. Defaults to 0. + ftol : float, optional + Precision goal for the value of f in the stopping criterion. + If ftol < 0.0, ftol is set to 0.0 defaults to -1. + xtol : float, optional + Precision goal for the value of x in the stopping + criterion (after applying x scaling factors). If xtol < + 0.0, xtol is set to sqrt(machine_precision). Defaults to + -1. + pgtol : float, optional + Precision goal for the value of the projected gradient in + the stopping criterion (after applying x scaling factors). + If pgtol < 0.0, pgtol is set to 1e-2 * sqrt(accuracy). + Setting it to 0.0 is not recommended. Defaults to -1. + rescale : float, optional + Scaling factor (in log10) used to trigger f value + rescaling. If 0, rescale at each iteration. If a large + value, never rescale. If < 0, rescale is set to 1.3. + callback : callable, optional + Called after each iteration, as callback(xk), where xk is the + current parameter vector. + + Returns + ------- + x : ndarray + The solution. + nfeval : int + The number of function evaluations. + rc : int + Return code, see below + + See also + -------- + minimize: Interface to minimization algorithms for multivariate + functions. See the 'TNC' `method` in particular. + + Notes + ----- + The underlying algorithm is truncated Newton, also called + Newton Conjugate-Gradient. This method differs from + scipy.optimize.fmin_ncg in that + + 1. it wraps a C implementation of the algorithm + 2. it allows each variable to be given an upper and lower bound. + + The algorithm incorporates the bound constraints by determining + the descent direction as in an unconstrained truncated Newton, + but never taking a step-size large enough to leave the space + of feasible x's. The algorithm keeps track of a set of + currently active constraints, and ignores them when computing + the minimum allowable step size. (The x's associated with the + active constraint are kept fixed.) If the maximum allowable + step size is zero then a new constraint is added. At the end + of each iteration one of the constraints may be deemed no + longer active and removed. A constraint is considered + no longer active is if it is currently active + but the gradient for that variable points inward from the + constraint. The specific constraint removed is the one + associated with the variable of largest index whose + constraint is no longer active. + + Return codes are defined as follows: + + - ``-1`` : Infeasible (lower bound > upper bound) + - ``0`` : Local minimum reached (:math:`|pg| \approx 0`) + - ``1`` : Converged (:math:`|f_n-f_(n-1)| \approx 0`) + - ``2`` : Converged (:math:`|x_n-x_(n-1)| \approx 0`) + - ``3`` : Max. number of function evaluations reached + - ``4`` : Linear search failed + - ``5`` : All lower bounds are equal to the upper bounds + - ``6`` : Unable to progress + - ``7`` : User requested end of minimization + + References + ---------- + Wright S., Nocedal J. (2006), 'Numerical Optimization' + + Nash S.G. (1984), "Newton-Type Minimization Via the Lanczos Method", + SIAM Journal of Numerical Analysis 21, pp. 770-778 + + """ + # handle fprime/approx_grad + if approx_grad: + fun = func + jac = None + elif fprime is None: + fun = MemoizeJac(func) + jac = fun.derivative + else: + fun = func + jac = fprime + + if disp is not None: # disp takes precedence over messages + mesg_num = disp + else: + mesg_num = {0:MSG_NONE, 1:MSG_ITER, 2:MSG_INFO, 3:MSG_VERS, + 4:MSG_EXIT, 5:MSG_ALL}.get(messages, MSG_ALL) + # build options + opts = {'eps': epsilon, + 'scale': scale, + 'offset': offset, + 'mesg_num': mesg_num, + 'maxCGit': maxCGit, + 'maxfun': maxfun, + 'eta': eta, + 'stepmx': stepmx, + 'accuracy': accuracy, + 'minfev': fmin, + 'ftol': ftol, + 'xtol': xtol, + 'gtol': pgtol, + 'rescale': rescale, + 'disp': False} + + res = _minimize_tnc(fun, x0, args, jac, bounds, callback=callback, **opts) + + return res['x'], res['nfev'], res['status'] + + +def _minimize_tnc(fun, x0, args=(), jac=None, bounds=None, + eps=1e-8, scale=None, offset=None, mesg_num=None, + maxCGit=-1, eta=-1, stepmx=0, accuracy=0, + minfev=0, ftol=-1, xtol=-1, gtol=-1, rescale=-1, disp=False, + callback=None, finite_diff_rel_step=None, maxfun=None, + **unknown_options): + """ + Minimize a scalar function of one or more variables using a truncated + Newton (TNC) algorithm. + + Options + ------- + eps : float or ndarray + If `jac is None` the absolute step size used for numerical + approximation of the jacobian via forward differences. + scale : list of floats + Scaling factors to apply to each variable. If None, the + factors are up-low for interval bounded variables and + 1+|x] for the others. Defaults to None. + offset : float + Value to subtract from each variable. If None, the + offsets are (up+low)/2 for interval bounded variables + and x for the others. + disp : bool + Set to True to print convergence messages. + maxCGit : int + Maximum number of hessian*vector evaluations per main + iteration. If maxCGit == 0, the direction chosen is + -gradient if maxCGit < 0, maxCGit is set to + max(1,min(50,n/2)). Defaults to -1. + eta : float + Severity of the line search. If < 0 or > 1, set to 0.25. + Defaults to -1. + stepmx : float + Maximum step for the line search. May be increased during + call. If too small, it will be set to 10.0. Defaults to 0. + accuracy : float + Relative precision for finite difference calculations. If + <= machine_precision, set to sqrt(machine_precision). + Defaults to 0. + minfev : float + Minimum function value estimate. Defaults to 0. + ftol : float + Precision goal for the value of f in the stopping criterion. + If ftol < 0.0, ftol is set to 0.0 defaults to -1. + xtol : float + Precision goal for the value of x in the stopping + criterion (after applying x scaling factors). If xtol < + 0.0, xtol is set to sqrt(machine_precision). Defaults to + -1. + gtol : float + Precision goal for the value of the projected gradient in + the stopping criterion (after applying x scaling factors). + If gtol < 0.0, gtol is set to 1e-2 * sqrt(accuracy). + Setting it to 0.0 is not recommended. Defaults to -1. + rescale : float + Scaling factor (in log10) used to trigger f value + rescaling. If 0, rescale at each iteration. If a large + value, never rescale. If < 0, rescale is set to 1.3. + finite_diff_rel_step : None or array_like, optional + If ``jac in ['2-point', '3-point', 'cs']`` the relative step size to + use for numerical approximation of the jacobian. The absolute step + size is computed as ``h = rel_step * sign(x) * max(1, abs(x))``, + possibly adjusted to fit into the bounds. For ``method='3-point'`` + the sign of `h` is ignored. If None (default) then step is selected + automatically. + maxfun : int + Maximum number of function evaluations. If None, `maxfun` is + set to max(100, 10*len(x0)). Defaults to None. + """ + _check_unknown_options(unknown_options) + fmin = minfev + pgtol = gtol + + xp = array_namespace(x0) + x0 = xpx.atleast_nd(xp.asarray(x0), ndim=1, xp=xp) + dtype = xp.float64 + if xp.isdtype(x0.dtype, "real floating"): + dtype = x0.dtype + x0 = xp.reshape(xp.astype(x0, dtype), -1) + + n = len(x0) + + if bounds is None: + bounds = [(None,None)] * n + if len(bounds) != n: + raise ValueError('length of x0 != length of bounds') + new_bounds = old_bound_to_new(bounds) + + if mesg_num is not None: + messages = {0:MSG_NONE, 1:MSG_ITER, 2:MSG_INFO, 3:MSG_VERS, + 4:MSG_EXIT, 5:MSG_ALL}.get(mesg_num, MSG_ALL) + elif disp: + messages = MSG_ALL + else: + messages = MSG_NONE + + sf = _prepare_scalar_function(fun, x0, jac=jac, args=args, epsilon=eps, + finite_diff_rel_step=finite_diff_rel_step, + bounds=new_bounds) + func_and_grad = sf.fun_and_grad + + """ + low, up : the bounds (lists of floats) + if low is None, the lower bounds are removed. + if up is None, the upper bounds are removed. + low and up defaults to None + """ + low = zeros(n) + up = zeros(n) + for i in range(n): + if bounds[i] is None: + l, u = -inf, inf + else: + l,u = bounds[i] + if l is None: + low[i] = -inf + else: + low[i] = l + if u is None: + up[i] = inf + else: + up[i] = u + + if scale is None: + scale = array([]) + + if offset is None: + offset = array([]) + + if maxfun is None: + maxfun = max(100, 10*len(x0)) + + rc, nf, nit, x, funv, jacv = moduleTNC.tnc_minimize( + func_and_grad, x0, low, up, scale, + offset, messages, maxCGit, maxfun, + eta, stepmx, accuracy, fmin, ftol, + xtol, pgtol, rescale, callback + ) + # the TNC documentation states: "On output, x, f and g may be very + # slightly out of sync because of scaling". Therefore re-evaluate + # func_and_grad so they are synced. + funv, jacv = func_and_grad(x) + + return OptimizeResult(x=x, fun=funv, jac=jacv, nfev=sf.nfev, + nit=nit, status=rc, message=RCSTRINGS[rc], + success=(-1 < rc < 3)) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trlib/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trlib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..537b73b3aeb36df09863a0cd24957e5612deb030 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trlib/__init__.py @@ -0,0 +1,12 @@ +from ._trlib import TRLIBQuadraticSubproblem + +__all__ = ['TRLIBQuadraticSubproblem', 'get_trlib_quadratic_subproblem'] + + +def get_trlib_quadratic_subproblem(tol_rel_i=-2.0, tol_rel_b=-3.0, disp=False): + def subproblem_factory(x, fun, jac, hess, hessp): + return TRLIBQuadraticSubproblem(x, fun, jac, hess, hessp, + tol_rel_i=tol_rel_i, + tol_rel_b=tol_rel_b, + disp=disp) + return subproblem_factory diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion.py new file mode 100644 index 0000000000000000000000000000000000000000..0dadc727e74e40b5200810191b21cdeda941c5f6 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion.py @@ -0,0 +1,304 @@ +"""Trust-region optimization.""" +import math +import warnings + +import numpy as np +import scipy.linalg +from ._optimize import (_check_unknown_options, _status_message, + OptimizeResult, _prepare_scalar_function, + _call_callback_maybe_halt) +from scipy.optimize._hessian_update_strategy import HessianUpdateStrategy +from scipy.optimize._differentiable_functions import FD_METHODS +__all__ = [] + + +def _wrap_function(function, args): + # wraps a minimizer function to count number of evaluations + # and to easily provide an args kwd. + ncalls = [0] + if function is None: + return ncalls, None + + def function_wrapper(x, *wrapper_args): + ncalls[0] += 1 + # A copy of x is sent to the user function (gh13740) + return function(np.copy(x), *(wrapper_args + args)) + + return ncalls, function_wrapper + + +class BaseQuadraticSubproblem: + """ + Base/abstract class defining the quadratic model for trust-region + minimization. Child classes must implement the ``solve`` method. + + Values of the objective function, Jacobian and Hessian (if provided) at + the current iterate ``x`` are evaluated on demand and then stored as + attributes ``fun``, ``jac``, ``hess``. + """ + + def __init__(self, x, fun, jac, hess=None, hessp=None): + self._x = x + self._f = None + self._g = None + self._h = None + self._g_mag = None + self._cauchy_point = None + self._newton_point = None + self._fun = fun + self._jac = jac + self._hess = hess + self._hessp = hessp + + def __call__(self, p): + return self.fun + np.dot(self.jac, p) + 0.5 * np.dot(p, self.hessp(p)) + + @property + def fun(self): + """Value of objective function at current iteration.""" + if self._f is None: + self._f = self._fun(self._x) + return self._f + + @property + def jac(self): + """Value of Jacobian of objective function at current iteration.""" + if self._g is None: + self._g = self._jac(self._x) + return self._g + + @property + def hess(self): + """Value of Hessian of objective function at current iteration.""" + if self._h is None: + self._h = self._hess(self._x) + return self._h + + def hessp(self, p): + if self._hessp is not None: + return self._hessp(self._x, p) + else: + return np.dot(self.hess, p) + + @property + def jac_mag(self): + """Magnitude of jacobian of objective function at current iteration.""" + if self._g_mag is None: + self._g_mag = scipy.linalg.norm(self.jac) + return self._g_mag + + def get_boundaries_intersections(self, z, d, trust_radius): + """ + Solve the scalar quadratic equation ``||z + t d|| == trust_radius``. + This is like a line-sphere intersection. + Return the two values of t, sorted from low to high. + """ + a = np.dot(d, d) + b = 2 * np.dot(z, d) + c = np.dot(z, z) - trust_radius**2 + sqrt_discriminant = math.sqrt(b*b - 4*a*c) + + # The following calculation is mathematically + # equivalent to: + # ta = (-b - sqrt_discriminant) / (2*a) + # tb = (-b + sqrt_discriminant) / (2*a) + # but produce smaller round off errors. + # Look at Matrix Computation p.97 + # for a better justification. + aux = b + math.copysign(sqrt_discriminant, b) + ta = -aux / (2*a) + tb = -2*c / aux + return sorted([ta, tb]) + + def solve(self, trust_radius): + raise NotImplementedError('The solve method should be implemented by ' + 'the child class') + + +def _minimize_trust_region(fun, x0, args=(), jac=None, hess=None, hessp=None, + subproblem=None, initial_trust_radius=1.0, + max_trust_radius=1000.0, eta=0.15, gtol=1e-4, + maxiter=None, disp=False, return_all=False, + callback=None, inexact=True, **unknown_options): + """ + Minimization of scalar function of one or more variables using a + trust-region algorithm. + + Options for the trust-region algorithm are: + initial_trust_radius : float + Initial trust radius. + max_trust_radius : float + Never propose steps that are longer than this value. + eta : float + Trust region related acceptance stringency for proposed steps. + gtol : float + Gradient norm must be less than `gtol` + before successful termination. + maxiter : int + Maximum number of iterations to perform. + disp : bool + If True, print convergence message. + inexact : bool + Accuracy to solve subproblems. If True requires less nonlinear + iterations, but more vector products. Only effective for method + trust-krylov. + + This function is called by the `minimize` function. + It is not supposed to be called directly. + """ + _check_unknown_options(unknown_options) + + if jac is None: + raise ValueError('Jacobian is currently required for trust-region ' + 'methods') + if hess is None and hessp is None: + raise ValueError('Either the Hessian or the Hessian-vector product ' + 'is currently required for trust-region methods') + if subproblem is None: + raise ValueError('A subproblem solving strategy is required for ' + 'trust-region methods') + if not (0 <= eta < 0.25): + raise Exception('invalid acceptance stringency') + if max_trust_radius <= 0: + raise Exception('the max trust radius must be positive') + if initial_trust_radius <= 0: + raise ValueError('the initial trust radius must be positive') + if initial_trust_radius >= max_trust_radius: + raise ValueError('the initial trust radius must be less than the ' + 'max trust radius') + + # force the initial guess into a nice format + x0 = np.asarray(x0).flatten() + + # A ScalarFunction representing the problem. This caches calls to fun, jac, + # hess. + sf = _prepare_scalar_function(fun, x0, jac=jac, hess=hess, args=args) + fun = sf.fun + jac = sf.grad + if callable(hess): + hess = sf.hess + elif callable(hessp): + # this elif statement must come before examining whether hess + # is estimated by FD methods or a HessianUpdateStrategy + pass + elif (hess in FD_METHODS or isinstance(hess, HessianUpdateStrategy)): + # If the Hessian is being estimated by finite differences or a + # Hessian update strategy then ScalarFunction.hess returns a + # LinearOperator or a HessianUpdateStrategy. This enables the + # calculation/creation of a hessp. BUT you only want to do this + # if the user *hasn't* provided a callable(hessp) function. + hess = None + + def hessp(x, p, *args): + return sf.hess(x).dot(p) + else: + raise ValueError('Either the Hessian or the Hessian-vector product ' + 'is currently required for trust-region methods') + + # ScalarFunction doesn't represent hessp + nhessp, hessp = _wrap_function(hessp, args) + + # limit the number of iterations + if maxiter is None: + maxiter = len(x0)*200 + + # init the search status + warnflag = 0 + + # initialize the search + trust_radius = initial_trust_radius + x = x0 + if return_all: + allvecs = [x] + m = subproblem(x, fun, jac, hess, hessp) + k = 0 + + # search for the function min + # do not even start if the gradient is small enough + while m.jac_mag >= gtol: + + # Solve the sub-problem. + # This gives us the proposed step relative to the current position + # and it tells us whether the proposed step + # has reached the trust region boundary or not. + try: + p, hits_boundary = m.solve(trust_radius) + except np.linalg.LinAlgError: + warnflag = 3 + break + + # calculate the predicted value at the proposed point + predicted_value = m(p) + + # define the local approximation at the proposed point + x_proposed = x + p + m_proposed = subproblem(x_proposed, fun, jac, hess, hessp) + + # evaluate the ratio defined in equation (4.4) + actual_reduction = m.fun - m_proposed.fun + predicted_reduction = m.fun - predicted_value + if predicted_reduction <= 0: + warnflag = 2 + break + rho = actual_reduction / predicted_reduction + + # update the trust radius according to the actual/predicted ratio + if rho < 0.25: + trust_radius *= 0.25 + elif rho > 0.75 and hits_boundary: + trust_radius = min(2*trust_radius, max_trust_radius) + + # if the ratio is high enough then accept the proposed step + if rho > eta: + x = x_proposed + m = m_proposed + + # append the best guess, call back, increment the iteration count + if return_all: + allvecs.append(np.copy(x)) + k += 1 + + intermediate_result = OptimizeResult(x=x, fun=m.fun) + if _call_callback_maybe_halt(callback, intermediate_result): + break + + # check if the gradient is small enough to stop + if m.jac_mag < gtol: + warnflag = 0 + break + + # check if we have looked at enough iterations + if k >= maxiter: + warnflag = 1 + break + + # print some stuff if requested + status_messages = ( + _status_message['success'], + _status_message['maxiter'], + 'A bad approximation caused failure to predict improvement.', + 'A linalg error occurred, such as a non-psd Hessian.', + ) + if disp: + if warnflag == 0: + print(status_messages[warnflag]) + else: + warnings.warn(status_messages[warnflag], RuntimeWarning, stacklevel=3) + print(f" Current function value: {m.fun:f}") + print(" Iterations: %d" % k) + print(" Function evaluations: %d" % sf.nfev) + print(" Gradient evaluations: %d" % sf.ngev) + print(" Hessian evaluations: %d" % (sf.nhev + nhessp[0])) + + result = OptimizeResult(x=x, success=(warnflag == 0), status=warnflag, + fun=m.fun, jac=m.jac, nfev=sf.nfev, njev=sf.ngev, + nhev=sf.nhev + nhessp[0], nit=k, + message=status_messages[warnflag]) + + if hess is not None: + result['hess'] = m.hess + + if return_all: + result['allvecs'] = allvecs + + return result diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..549cfb9760dda474cb858b7b36d236af48111067 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/__init__.py @@ -0,0 +1,6 @@ +"""This module contains the equality constrained SQP solver.""" + + +from .minimize_trustregion_constr import _minimize_trustregion_constr + +__all__ = ['_minimize_trustregion_constr'] diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/canonical_constraint.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/canonical_constraint.py new file mode 100644 index 0000000000000000000000000000000000000000..7e9e75f04c032e5be077f9b7db210b96072092c9 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/canonical_constraint.py @@ -0,0 +1,390 @@ +import numpy as np +import scipy.sparse as sps + + +class CanonicalConstraint: + """Canonical constraint to use with trust-constr algorithm. + + It represents the set of constraints of the form:: + + f_eq(x) = 0 + f_ineq(x) <= 0 + + where ``f_eq`` and ``f_ineq`` are evaluated by a single function, see + below. + + The class is supposed to be instantiated by factory methods, which + should prepare the parameters listed below. + + Parameters + ---------- + n_eq, n_ineq : int + Number of equality and inequality constraints respectively. + fun : callable + Function defining the constraints. The signature is + ``fun(x) -> c_eq, c_ineq``, where ``c_eq`` is ndarray with `n_eq` + components and ``c_ineq`` is ndarray with `n_ineq` components. + jac : callable + Function to evaluate the Jacobian of the constraint. The signature + is ``jac(x) -> J_eq, J_ineq``, where ``J_eq`` and ``J_ineq`` are + either ndarray of csr_matrix of shapes (n_eq, n) and (n_ineq, n), + respectively. + hess : callable + Function to evaluate the Hessian of the constraints multiplied + by Lagrange multipliers, that is + ``dot(f_eq, v_eq) + dot(f_ineq, v_ineq)``. The signature is + ``hess(x, v_eq, v_ineq) -> H``, where ``H`` has an implied + shape (n, n) and provide a matrix-vector product operation + ``H.dot(p)``. + keep_feasible : ndarray, shape (n_ineq,) + Mask indicating which inequality constraints should be kept feasible. + """ + def __init__(self, n_eq, n_ineq, fun, jac, hess, keep_feasible): + self.n_eq = n_eq + self.n_ineq = n_ineq + self.fun = fun + self.jac = jac + self.hess = hess + self.keep_feasible = keep_feasible + + @classmethod + def from_PreparedConstraint(cls, constraint): + """Create an instance from `PreparedConstrained` object.""" + lb, ub = constraint.bounds + cfun = constraint.fun + keep_feasible = constraint.keep_feasible + + if np.all(lb == -np.inf) and np.all(ub == np.inf): + return cls.empty(cfun.n) + + if np.all(lb == -np.inf) and np.all(ub == np.inf): + return cls.empty(cfun.n) + elif np.all(lb == ub): + return cls._equal_to_canonical(cfun, lb) + elif np.all(lb == -np.inf): + return cls._less_to_canonical(cfun, ub, keep_feasible) + elif np.all(ub == np.inf): + return cls._greater_to_canonical(cfun, lb, keep_feasible) + else: + return cls._interval_to_canonical(cfun, lb, ub, keep_feasible) + + @classmethod + def empty(cls, n): + """Create an "empty" instance. + + This "empty" instance is required to allow working with unconstrained + problems as if they have some constraints. + """ + empty_fun = np.empty(0) + empty_jac = np.empty((0, n)) + empty_hess = sps.csr_matrix((n, n)) + + def fun(x): + return empty_fun, empty_fun + + def jac(x): + return empty_jac, empty_jac + + def hess(x, v_eq, v_ineq): + return empty_hess + + return cls(0, 0, fun, jac, hess, np.empty(0, dtype=np.bool_)) + + @classmethod + def concatenate(cls, canonical_constraints, sparse_jacobian): + """Concatenate multiple `CanonicalConstraint` into one. + + `sparse_jacobian` (bool) determines the Jacobian format of the + concatenated constraint. Note that items in `canonical_constraints` + must have their Jacobians in the same format. + """ + def fun(x): + if canonical_constraints: + eq_all, ineq_all = zip( + *[c.fun(x) for c in canonical_constraints]) + else: + eq_all, ineq_all = [], [] + + return np.hstack(eq_all), np.hstack(ineq_all) + + if sparse_jacobian: + vstack = sps.vstack + else: + vstack = np.vstack + + def jac(x): + if canonical_constraints: + eq_all, ineq_all = zip( + *[c.jac(x) for c in canonical_constraints]) + else: + eq_all, ineq_all = [], [] + + return vstack(eq_all), vstack(ineq_all) + + def hess(x, v_eq, v_ineq): + hess_all = [] + index_eq = 0 + index_ineq = 0 + for c in canonical_constraints: + vc_eq = v_eq[index_eq:index_eq + c.n_eq] + vc_ineq = v_ineq[index_ineq:index_ineq + c.n_ineq] + hess_all.append(c.hess(x, vc_eq, vc_ineq)) + index_eq += c.n_eq + index_ineq += c.n_ineq + + def matvec(p): + result = np.zeros_like(p, dtype=float) + for h in hess_all: + result += h.dot(p) + return result + + n = x.shape[0] + return sps.linalg.LinearOperator((n, n), matvec, dtype=float) + + n_eq = sum(c.n_eq for c in canonical_constraints) + n_ineq = sum(c.n_ineq for c in canonical_constraints) + keep_feasible = np.hstack([c.keep_feasible for c in + canonical_constraints]) + + return cls(n_eq, n_ineq, fun, jac, hess, keep_feasible) + + @classmethod + def _equal_to_canonical(cls, cfun, value): + empty_fun = np.empty(0) + n = cfun.n + + n_eq = value.shape[0] + n_ineq = 0 + keep_feasible = np.empty(0, dtype=bool) + + if cfun.sparse_jacobian: + empty_jac = sps.csr_matrix((0, n)) + else: + empty_jac = np.empty((0, n)) + + def fun(x): + return cfun.fun(x) - value, empty_fun + + def jac(x): + return cfun.jac(x), empty_jac + + def hess(x, v_eq, v_ineq): + return cfun.hess(x, v_eq) + + empty_fun = np.empty(0) + n = cfun.n + if cfun.sparse_jacobian: + empty_jac = sps.csr_matrix((0, n)) + else: + empty_jac = np.empty((0, n)) + + return cls(n_eq, n_ineq, fun, jac, hess, keep_feasible) + + @classmethod + def _less_to_canonical(cls, cfun, ub, keep_feasible): + empty_fun = np.empty(0) + n = cfun.n + if cfun.sparse_jacobian: + empty_jac = sps.csr_matrix((0, n)) + else: + empty_jac = np.empty((0, n)) + + finite_ub = ub < np.inf + n_eq = 0 + n_ineq = np.sum(finite_ub) + + if np.all(finite_ub): + def fun(x): + return empty_fun, cfun.fun(x) - ub + + def jac(x): + return empty_jac, cfun.jac(x) + + def hess(x, v_eq, v_ineq): + return cfun.hess(x, v_ineq) + else: + finite_ub = np.nonzero(finite_ub)[0] + keep_feasible = keep_feasible[finite_ub] + ub = ub[finite_ub] + + def fun(x): + return empty_fun, cfun.fun(x)[finite_ub] - ub + + def jac(x): + return empty_jac, cfun.jac(x)[finite_ub] + + def hess(x, v_eq, v_ineq): + v = np.zeros(cfun.m) + v[finite_ub] = v_ineq + return cfun.hess(x, v) + + return cls(n_eq, n_ineq, fun, jac, hess, keep_feasible) + + @classmethod + def _greater_to_canonical(cls, cfun, lb, keep_feasible): + empty_fun = np.empty(0) + n = cfun.n + if cfun.sparse_jacobian: + empty_jac = sps.csr_matrix((0, n)) + else: + empty_jac = np.empty((0, n)) + + finite_lb = lb > -np.inf + n_eq = 0 + n_ineq = np.sum(finite_lb) + + if np.all(finite_lb): + def fun(x): + return empty_fun, lb - cfun.fun(x) + + def jac(x): + return empty_jac, -cfun.jac(x) + + def hess(x, v_eq, v_ineq): + return cfun.hess(x, -v_ineq) + else: + finite_lb = np.nonzero(finite_lb)[0] + keep_feasible = keep_feasible[finite_lb] + lb = lb[finite_lb] + + def fun(x): + return empty_fun, lb - cfun.fun(x)[finite_lb] + + def jac(x): + return empty_jac, -cfun.jac(x)[finite_lb] + + def hess(x, v_eq, v_ineq): + v = np.zeros(cfun.m) + v[finite_lb] = -v_ineq + return cfun.hess(x, v) + + return cls(n_eq, n_ineq, fun, jac, hess, keep_feasible) + + @classmethod + def _interval_to_canonical(cls, cfun, lb, ub, keep_feasible): + lb_inf = lb == -np.inf + ub_inf = ub == np.inf + equal = lb == ub + less = lb_inf & ~ub_inf + greater = ub_inf & ~lb_inf + interval = ~equal & ~lb_inf & ~ub_inf + + equal = np.nonzero(equal)[0] + less = np.nonzero(less)[0] + greater = np.nonzero(greater)[0] + interval = np.nonzero(interval)[0] + n_less = less.shape[0] + n_greater = greater.shape[0] + n_interval = interval.shape[0] + n_ineq = n_less + n_greater + 2 * n_interval + n_eq = equal.shape[0] + + keep_feasible = np.hstack((keep_feasible[less], + keep_feasible[greater], + keep_feasible[interval], + keep_feasible[interval])) + + def fun(x): + f = cfun.fun(x) + eq = f[equal] - lb[equal] + le = f[less] - ub[less] + ge = lb[greater] - f[greater] + il = f[interval] - ub[interval] + ig = lb[interval] - f[interval] + return eq, np.hstack((le, ge, il, ig)) + + def jac(x): + J = cfun.jac(x) + eq = J[equal] + le = J[less] + ge = -J[greater] + il = J[interval] + ig = -il + if sps.issparse(J): + ineq = sps.vstack((le, ge, il, ig)) + else: + ineq = np.vstack((le, ge, il, ig)) + return eq, ineq + + def hess(x, v_eq, v_ineq): + n_start = 0 + v_l = v_ineq[n_start:n_start + n_less] + n_start += n_less + v_g = v_ineq[n_start:n_start + n_greater] + n_start += n_greater + v_il = v_ineq[n_start:n_start + n_interval] + n_start += n_interval + v_ig = v_ineq[n_start:n_start + n_interval] + + v = np.zeros_like(lb) + v[equal] = v_eq + v[less] = v_l + v[greater] = -v_g + v[interval] = v_il - v_ig + + return cfun.hess(x, v) + + return cls(n_eq, n_ineq, fun, jac, hess, keep_feasible) + + +def initial_constraints_as_canonical(n, prepared_constraints, sparse_jacobian): + """Convert initial values of the constraints to the canonical format. + + The purpose to avoid one additional call to the constraints at the initial + point. It takes saved values in `PreparedConstraint`, modifies and + concatenates them to the canonical constraint format. + """ + c_eq = [] + c_ineq = [] + J_eq = [] + J_ineq = [] + + for c in prepared_constraints: + f = c.fun.f + J = c.fun.J + lb, ub = c.bounds + if np.all(lb == ub): + c_eq.append(f - lb) + J_eq.append(J) + elif np.all(lb == -np.inf): + finite_ub = ub < np.inf + c_ineq.append(f[finite_ub] - ub[finite_ub]) + J_ineq.append(J[finite_ub]) + elif np.all(ub == np.inf): + finite_lb = lb > -np.inf + c_ineq.append(lb[finite_lb] - f[finite_lb]) + J_ineq.append(-J[finite_lb]) + else: + lb_inf = lb == -np.inf + ub_inf = ub == np.inf + equal = lb == ub + less = lb_inf & ~ub_inf + greater = ub_inf & ~lb_inf + interval = ~equal & ~lb_inf & ~ub_inf + + c_eq.append(f[equal] - lb[equal]) + c_ineq.append(f[less] - ub[less]) + c_ineq.append(lb[greater] - f[greater]) + c_ineq.append(f[interval] - ub[interval]) + c_ineq.append(lb[interval] - f[interval]) + + J_eq.append(J[equal]) + J_ineq.append(J[less]) + J_ineq.append(-J[greater]) + J_ineq.append(J[interval]) + J_ineq.append(-J[interval]) + + c_eq = np.hstack(c_eq) if c_eq else np.empty(0) + c_ineq = np.hstack(c_ineq) if c_ineq else np.empty(0) + + if sparse_jacobian: + vstack = sps.vstack + empty = sps.csr_matrix((0, n)) + else: + vstack = np.vstack + empty = np.empty((0, n)) + + J_eq = vstack(J_eq) if J_eq else empty + J_ineq = vstack(J_ineq) if J_ineq else empty + + return c_eq, c_ineq, J_eq, J_ineq diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/equality_constrained_sqp.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/equality_constrained_sqp.py new file mode 100644 index 0000000000000000000000000000000000000000..88a9f8deb1abfaa82533eeb6308bbfbd5516ed4d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/equality_constrained_sqp.py @@ -0,0 +1,231 @@ +"""Byrd-Omojokun Trust-Region SQP method.""" + +from scipy.sparse import eye as speye +from .projections import projections +from .qp_subproblem import modified_dogleg, projected_cg, box_intersections +import numpy as np +from numpy.linalg import norm + +__all__ = ['equality_constrained_sqp'] + + +def default_scaling(x): + n, = np.shape(x) + return speye(n) + + +def equality_constrained_sqp(fun_and_constr, grad_and_jac, lagr_hess, + x0, fun0, grad0, constr0, + jac0, stop_criteria, + state, + initial_penalty, + initial_trust_radius, + factorization_method, + trust_lb=None, + trust_ub=None, + scaling=default_scaling): + """Solve nonlinear equality-constrained problem using trust-region SQP. + + Solve optimization problem: + + minimize fun(x) + subject to: constr(x) = 0 + + using Byrd-Omojokun Trust-Region SQP method described in [1]_. Several + implementation details are based on [2]_ and [3]_, p. 549. + + References + ---------- + .. [1] Lalee, Marucha, Jorge Nocedal, and Todd Plantenga. "On the + implementation of an algorithm for large-scale equality + constrained optimization." SIAM Journal on + Optimization 8.3 (1998): 682-706. + .. [2] Byrd, Richard H., Mary E. Hribar, and Jorge Nocedal. + "An interior point algorithm for large-scale nonlinear + programming." SIAM Journal on Optimization 9.4 (1999): 877-900. + .. [3] Nocedal, Jorge, and Stephen J. Wright. "Numerical optimization" + Second Edition (2006). + """ + PENALTY_FACTOR = 0.3 # Rho from formula (3.51), reference [2]_, p.891. + LARGE_REDUCTION_RATIO = 0.9 + INTERMEDIARY_REDUCTION_RATIO = 0.3 + SUFFICIENT_REDUCTION_RATIO = 1e-8 # Eta from reference [2]_, p.892. + TRUST_ENLARGEMENT_FACTOR_L = 7.0 + TRUST_ENLARGEMENT_FACTOR_S = 2.0 + MAX_TRUST_REDUCTION = 0.5 + MIN_TRUST_REDUCTION = 0.1 + SOC_THRESHOLD = 0.1 + TR_FACTOR = 0.8 # Zeta from formula (3.21), reference [2]_, p.885. + BOX_FACTOR = 0.5 + + n, = np.shape(x0) # Number of parameters + + # Set default lower and upper bounds. + if trust_lb is None: + trust_lb = np.full(n, -np.inf) + if trust_ub is None: + trust_ub = np.full(n, np.inf) + + # Initial values + x = np.copy(x0) + trust_radius = initial_trust_radius + penalty = initial_penalty + # Compute Values + f = fun0 + c = grad0 + b = constr0 + A = jac0 + S = scaling(x) + # Get projections + try: + Z, LS, Y = projections(A, factorization_method) + except ValueError as e: + if str(e) == "expected square matrix": + # can be the case if there are more equality + # constraints than independent variables + raise ValueError( + "The 'expected square matrix' error can occur if there are" + " more equality constraints than independent variables." + " Consider how your constraints are set up, or use" + " factorization_method='SVDFactorization'." + ) from e + else: + raise e + + # Compute least-square lagrange multipliers + v = -LS.dot(c) + # Compute Hessian + H = lagr_hess(x, v) + + # Update state parameters + optimality = norm(c + A.T.dot(v), np.inf) + constr_violation = norm(b, np.inf) if len(b) > 0 else 0 + cg_info = {'niter': 0, 'stop_cond': 0, + 'hits_boundary': False} + + last_iteration_failed = False + while not stop_criteria(state, x, last_iteration_failed, + optimality, constr_violation, + trust_radius, penalty, cg_info): + # Normal Step - `dn` + # minimize 1/2*||A dn + b||^2 + # subject to: + # ||dn|| <= TR_FACTOR * trust_radius + # BOX_FACTOR * lb <= dn <= BOX_FACTOR * ub. + dn = modified_dogleg(A, Y, b, + TR_FACTOR*trust_radius, + BOX_FACTOR*trust_lb, + BOX_FACTOR*trust_ub) + + # Tangential Step - `dt` + # Solve the QP problem: + # minimize 1/2 dt.T H dt + dt.T (H dn + c) + # subject to: + # A dt = 0 + # ||dt|| <= sqrt(trust_radius**2 - ||dn||**2) + # lb - dn <= dt <= ub - dn + c_t = H.dot(dn) + c + b_t = np.zeros_like(b) + trust_radius_t = np.sqrt(trust_radius**2 - np.linalg.norm(dn)**2) + lb_t = trust_lb - dn + ub_t = trust_ub - dn + dt, cg_info = projected_cg(H, c_t, Z, Y, b_t, + trust_radius_t, + lb_t, ub_t) + + # Compute update (normal + tangential steps). + d = dn + dt + + # Compute second order model: 1/2 d H d + c.T d + f. + quadratic_model = 1/2*(H.dot(d)).dot(d) + c.T.dot(d) + # Compute linearized constraint: l = A d + b. + linearized_constr = A.dot(d)+b + # Compute new penalty parameter according to formula (3.52), + # reference [2]_, p.891. + vpred = norm(b) - norm(linearized_constr) + # Guarantee `vpred` always positive, + # regardless of roundoff errors. + vpred = max(1e-16, vpred) + previous_penalty = penalty + if quadratic_model > 0: + new_penalty = quadratic_model / ((1-PENALTY_FACTOR)*vpred) + penalty = max(penalty, new_penalty) + # Compute predicted reduction according to formula (3.52), + # reference [2]_, p.891. + predicted_reduction = -quadratic_model + penalty*vpred + + # Compute merit function at current point + merit_function = f + penalty*norm(b) + # Evaluate function and constraints at trial point + x_next = x + S.dot(d) + f_next, b_next = fun_and_constr(x_next) + # Compute merit function at trial point + merit_function_next = f_next + penalty*norm(b_next) + # Compute actual reduction according to formula (3.54), + # reference [2]_, p.892. + actual_reduction = merit_function - merit_function_next + # Compute reduction ratio + reduction_ratio = actual_reduction / predicted_reduction + + # Second order correction (SOC), reference [2]_, p.892. + if reduction_ratio < SUFFICIENT_REDUCTION_RATIO and \ + norm(dn) <= SOC_THRESHOLD * norm(dt): + # Compute second order correction + y = -Y.dot(b_next) + # Make sure increment is inside box constraints + _, t, intersect = box_intersections(d, y, trust_lb, trust_ub) + # Compute tentative point + x_soc = x + S.dot(d + t*y) + f_soc, b_soc = fun_and_constr(x_soc) + # Recompute actual reduction + merit_function_soc = f_soc + penalty*norm(b_soc) + actual_reduction_soc = merit_function - merit_function_soc + # Recompute reduction ratio + reduction_ratio_soc = actual_reduction_soc / predicted_reduction + if intersect and reduction_ratio_soc >= SUFFICIENT_REDUCTION_RATIO: + x_next = x_soc + f_next = f_soc + b_next = b_soc + reduction_ratio = reduction_ratio_soc + + # Readjust trust region step, formula (3.55), reference [2]_, p.892. + if reduction_ratio >= LARGE_REDUCTION_RATIO: + trust_radius = max(TRUST_ENLARGEMENT_FACTOR_L * norm(d), + trust_radius) + elif reduction_ratio >= INTERMEDIARY_REDUCTION_RATIO: + trust_radius = max(TRUST_ENLARGEMENT_FACTOR_S * norm(d), + trust_radius) + # Reduce trust region step, according to reference [3]_, p.696. + elif reduction_ratio < SUFFICIENT_REDUCTION_RATIO: + trust_reduction = ((1-SUFFICIENT_REDUCTION_RATIO) / + (1-reduction_ratio)) + new_trust_radius = trust_reduction * norm(d) + if new_trust_radius >= MAX_TRUST_REDUCTION * trust_radius: + trust_radius *= MAX_TRUST_REDUCTION + elif new_trust_radius >= MIN_TRUST_REDUCTION * trust_radius: + trust_radius = new_trust_radius + else: + trust_radius *= MIN_TRUST_REDUCTION + + # Update iteration + if reduction_ratio >= SUFFICIENT_REDUCTION_RATIO: + x = x_next + f, b = f_next, b_next + c, A = grad_and_jac(x) + S = scaling(x) + # Get projections + Z, LS, Y = projections(A, factorization_method) + # Compute least-square lagrange multipliers + v = -LS.dot(c) + # Compute Hessian + H = lagr_hess(x, v) + # Set Flag + last_iteration_failed = False + # Optimality values + optimality = norm(c + A.T.dot(v), np.inf) + constr_violation = norm(b, np.inf) if len(b) > 0 else 0 + else: + penalty = previous_penalty + last_iteration_failed = True + + return x, state diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/minimize_trustregion_constr.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/minimize_trustregion_constr.py new file mode 100644 index 0000000000000000000000000000000000000000..580f9ccf8eab9f22d73ae41f130b2e5e541a71da --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/minimize_trustregion_constr.py @@ -0,0 +1,576 @@ +import time +import numpy as np +from scipy.sparse.linalg import LinearOperator +from .._differentiable_functions import VectorFunction +from .._constraints import ( + NonlinearConstraint, LinearConstraint, PreparedConstraint, Bounds, strict_bounds) +from .._hessian_update_strategy import BFGS +from .._optimize import OptimizeResult +from .._differentiable_functions import ScalarFunction +from .equality_constrained_sqp import equality_constrained_sqp +from .canonical_constraint import (CanonicalConstraint, + initial_constraints_as_canonical) +from .tr_interior_point import tr_interior_point +from .report import BasicReport, SQPReport, IPReport + + +TERMINATION_MESSAGES = { + 0: "The maximum number of function evaluations is exceeded.", + 1: "`gtol` termination condition is satisfied.", + 2: "`xtol` termination condition is satisfied.", + 3: "`callback` function requested termination.", + 4: "Constraint violation exceeds 'gtol'" +} + + +class HessianLinearOperator: + """Build LinearOperator from hessp""" + def __init__(self, hessp, n): + self.hessp = hessp + self.n = n + + def __call__(self, x, *args): + def matvec(p): + return self.hessp(x, p, *args) + + return LinearOperator((self.n, self.n), matvec=matvec) + + +class LagrangianHessian: + """The Hessian of the Lagrangian as LinearOperator. + + The Lagrangian is computed as the objective function plus all the + constraints multiplied with some numbers (Lagrange multipliers). + """ + def __init__(self, n, objective_hess, constraints_hess): + self.n = n + self.objective_hess = objective_hess + self.constraints_hess = constraints_hess + + def __call__(self, x, v_eq, v_ineq=None): + if v_ineq is None: + v_ineq = np.empty(0) + H_objective = self.objective_hess(x) + H_constraints = self.constraints_hess(x, v_eq, v_ineq) + + def matvec(p): + return H_objective.dot(p) + H_constraints.dot(p) + + return LinearOperator((self.n, self.n), matvec) + + +def update_state_sqp(state, x, last_iteration_failed, objective, prepared_constraints, + start_time, tr_radius, constr_penalty, cg_info): + state.nit += 1 + state.nfev = objective.nfev + state.njev = objective.ngev + state.nhev = objective.nhev + state.constr_nfev = [c.fun.nfev if isinstance(c.fun, VectorFunction) else 0 + for c in prepared_constraints] + state.constr_njev = [c.fun.njev if isinstance(c.fun, VectorFunction) else 0 + for c in prepared_constraints] + state.constr_nhev = [c.fun.nhev if isinstance(c.fun, VectorFunction) else 0 + for c in prepared_constraints] + + if not last_iteration_failed: + state.x = x + state.fun = objective.f + state.grad = objective.g + state.v = [c.fun.v for c in prepared_constraints] + state.constr = [c.fun.f for c in prepared_constraints] + state.jac = [c.fun.J for c in prepared_constraints] + # Compute Lagrangian Gradient + state.lagrangian_grad = np.copy(state.grad) + for c in prepared_constraints: + state.lagrangian_grad += c.fun.J.T.dot(c.fun.v) + state.optimality = np.linalg.norm(state.lagrangian_grad, np.inf) + # Compute maximum constraint violation + state.constr_violation = 0 + for i in range(len(prepared_constraints)): + lb, ub = prepared_constraints[i].bounds + c = state.constr[i] + state.constr_violation = np.max([state.constr_violation, + np.max(lb - c), + np.max(c - ub)]) + + state.execution_time = time.time() - start_time + state.tr_radius = tr_radius + state.constr_penalty = constr_penalty + state.cg_niter += cg_info["niter"] + state.cg_stop_cond = cg_info["stop_cond"] + + return state + + +def update_state_ip(state, x, last_iteration_failed, objective, + prepared_constraints, start_time, + tr_radius, constr_penalty, cg_info, + barrier_parameter, barrier_tolerance): + state = update_state_sqp(state, x, last_iteration_failed, objective, + prepared_constraints, start_time, tr_radius, + constr_penalty, cg_info) + state.barrier_parameter = barrier_parameter + state.barrier_tolerance = barrier_tolerance + return state + + +def _minimize_trustregion_constr(fun, x0, args, grad, + hess, hessp, bounds, constraints, + xtol=1e-8, gtol=1e-8, + barrier_tol=1e-8, + sparse_jacobian=None, + callback=None, maxiter=1000, + verbose=0, finite_diff_rel_step=None, + initial_constr_penalty=1.0, initial_tr_radius=1.0, + initial_barrier_parameter=0.1, + initial_barrier_tolerance=0.1, + factorization_method=None, + disp=False): + """Minimize a scalar function subject to constraints. + + Parameters + ---------- + gtol : float, optional + Tolerance for termination by the norm of the Lagrangian gradient. + The algorithm will terminate when both the infinity norm (i.e., max + abs value) of the Lagrangian gradient and the constraint violation + are smaller than ``gtol``. Default is 1e-8. + xtol : float, optional + Tolerance for termination by the change of the independent variable. + The algorithm will terminate when ``tr_radius < xtol``, where + ``tr_radius`` is the radius of the trust region used in the algorithm. + Default is 1e-8. + barrier_tol : float, optional + Threshold on the barrier parameter for the algorithm termination. + When inequality constraints are present, the algorithm will terminate + only when the barrier parameter is less than `barrier_tol`. + Default is 1e-8. + sparse_jacobian : {bool, None}, optional + Determines how to represent Jacobians of the constraints. If bool, + then Jacobians of all the constraints will be converted to the + corresponding format. If None (default), then Jacobians won't be + converted, but the algorithm can proceed only if they all have the + same format. + initial_tr_radius: float, optional + Initial trust radius. The trust radius gives the maximum distance + between solution points in consecutive iterations. It reflects the + trust the algorithm puts in the local approximation of the optimization + problem. For an accurate local approximation the trust-region should be + large and for an approximation valid only close to the current point it + should be a small one. The trust radius is automatically updated throughout + the optimization process, with ``initial_tr_radius`` being its initial value. + Default is 1 (recommended in [1]_, p. 19). + initial_constr_penalty : float, optional + Initial constraints penalty parameter. The penalty parameter is used for + balancing the requirements of decreasing the objective function + and satisfying the constraints. It is used for defining the merit function: + ``merit_function(x) = fun(x) + constr_penalty * constr_norm_l2(x)``, + where ``constr_norm_l2(x)`` is the l2 norm of a vector containing all + the constraints. The merit function is used for accepting or rejecting + trial points and ``constr_penalty`` weights the two conflicting goals + of reducing objective function and constraints. The penalty is automatically + updated throughout the optimization process, with + ``initial_constr_penalty`` being its initial value. Default is 1 + (recommended in [1]_, p 19). + initial_barrier_parameter, initial_barrier_tolerance: float, optional + Initial barrier parameter and initial tolerance for the barrier subproblem. + Both are used only when inequality constraints are present. For dealing with + optimization problems ``min_x f(x)`` subject to inequality constraints + ``c(x) <= 0`` the algorithm introduces slack variables, solving the problem + ``min_(x,s) f(x) + barrier_parameter*sum(ln(s))`` subject to the equality + constraints ``c(x) + s = 0`` instead of the original problem. This subproblem + is solved for decreasing values of ``barrier_parameter`` and with decreasing + tolerances for the termination, starting with ``initial_barrier_parameter`` + for the barrier parameter and ``initial_barrier_tolerance`` for the + barrier tolerance. Default is 0.1 for both values (recommended in [1]_ p. 19). + Also note that ``barrier_parameter`` and ``barrier_tolerance`` are updated + with the same prefactor. + factorization_method : string or None, optional + Method to factorize the Jacobian of the constraints. Use None (default) + for the auto selection or one of: + + - 'NormalEquation' (requires scikit-sparse) + - 'AugmentedSystem' + - 'QRFactorization' + - 'SVDFactorization' + + The methods 'NormalEquation' and 'AugmentedSystem' can be used only + with sparse constraints. The projections required by the algorithm + will be computed using, respectively, the normal equation and the + augmented system approaches explained in [1]_. 'NormalEquation' + computes the Cholesky factorization of ``A A.T`` and 'AugmentedSystem' + performs the LU factorization of an augmented system. They usually + provide similar results. 'AugmentedSystem' is used by default for + sparse matrices. + + The methods 'QRFactorization' and 'SVDFactorization' can be used + only with dense constraints. They compute the required projections + using, respectively, QR and SVD factorizations. The 'SVDFactorization' + method can cope with Jacobian matrices with deficient row rank and will + be used whenever other factorization methods fail (which may imply the + conversion of sparse matrices to a dense format when required). + By default, 'QRFactorization' is used for dense matrices. + finite_diff_rel_step : None or array_like, optional + Relative step size for the finite difference approximation. + maxiter : int, optional + Maximum number of algorithm iterations. Default is 1000. + verbose : {0, 1, 2, 3}, optional + Level of algorithm's verbosity: + + * 0 (default) : work silently. + * 1 : display a termination report. + * 2 : display progress during iterations. + * 3 : display progress during iterations (more complete report). + + disp : bool, optional + If True (default), then `verbose` will be set to 1 if it was 0. + + Returns + ------- + `OptimizeResult` with the fields documented below. Note the following: + + 1. All values corresponding to the constraints are ordered as they + were passed to the solver. And values corresponding to `bounds` + constraints are put *after* other constraints. + 2. All numbers of function, Jacobian or Hessian evaluations correspond + to numbers of actual Python function calls. It means, for example, + that if a Jacobian is estimated by finite differences, then the + number of Jacobian evaluations will be zero and the number of + function evaluations will be incremented by all calls during the + finite difference estimation. + + x : ndarray, shape (n,) + Solution found. + optimality : float + Infinity norm of the Lagrangian gradient at the solution. + constr_violation : float + Maximum constraint violation at the solution. + fun : float + Objective function at the solution. + grad : ndarray, shape (n,) + Gradient of the objective function at the solution. + lagrangian_grad : ndarray, shape (n,) + Gradient of the Lagrangian function at the solution. + nit : int + Total number of iterations. + nfev : integer + Number of the objective function evaluations. + njev : integer + Number of the objective function gradient evaluations. + nhev : integer + Number of the objective function Hessian evaluations. + cg_niter : int + Total number of the conjugate gradient method iterations. + method : {'equality_constrained_sqp', 'tr_interior_point'} + Optimization method used. + constr : list of ndarray + List of constraint values at the solution. + jac : list of {ndarray, sparse matrix} + List of the Jacobian matrices of the constraints at the solution. + v : list of ndarray + List of the Lagrange multipliers for the constraints at the solution. + For an inequality constraint a positive multiplier means that the upper + bound is active, a negative multiplier means that the lower bound is + active and if a multiplier is zero it means the constraint is not + active. + constr_nfev : list of int + Number of constraint evaluations for each of the constraints. + constr_njev : list of int + Number of Jacobian matrix evaluations for each of the constraints. + constr_nhev : list of int + Number of Hessian evaluations for each of the constraints. + tr_radius : float + Radius of the trust region at the last iteration. + constr_penalty : float + Penalty parameter at the last iteration, see `initial_constr_penalty`. + barrier_tolerance : float + Tolerance for the barrier subproblem at the last iteration. + Only for problems with inequality constraints. + barrier_parameter : float + Barrier parameter at the last iteration. Only for problems + with inequality constraints. + execution_time : float + Total execution time. + message : str + Termination message. + status : {0, 1, 2, 3, 4} + Termination status: + + * 0 : The maximum number of function evaluations is exceeded. + * 1 : `gtol` termination condition is satisfied. + * 2 : `xtol` termination condition is satisfied. + * 3 : `callback` function requested termination. + * 4 : Constraint violation exceeds 'gtol'. + + .. versionchanged:: 1.15.0 + If the constraint violation exceeds `gtol`, then ``result.success`` + will now be False. + + cg_stop_cond : int + Reason for CG subproblem termination at the last iteration: + + * 0 : CG subproblem not evaluated. + * 1 : Iteration limit was reached. + * 2 : Reached the trust-region boundary. + * 3 : Negative curvature detected. + * 4 : Tolerance was satisfied. + + References + ---------- + .. [1] Conn, A. R., Gould, N. I., & Toint, P. L. + Trust region methods. 2000. Siam. pp. 19. + """ + x0 = np.atleast_1d(x0).astype(float) + n_vars = np.size(x0) + if hess is None: + if callable(hessp): + hess = HessianLinearOperator(hessp, n_vars) + else: + hess = BFGS() + if disp and verbose == 0: + verbose = 1 + + if bounds is not None: + modified_lb = np.nextafter(bounds.lb, -np.inf, where=bounds.lb > -np.inf) + modified_ub = np.nextafter(bounds.ub, np.inf, where=bounds.ub < np.inf) + modified_lb = np.where(np.isfinite(bounds.lb), modified_lb, bounds.lb) + modified_ub = np.where(np.isfinite(bounds.ub), modified_ub, bounds.ub) + bounds = Bounds(modified_lb, modified_ub, keep_feasible=bounds.keep_feasible) + finite_diff_bounds = strict_bounds(bounds.lb, bounds.ub, + bounds.keep_feasible, n_vars) + else: + finite_diff_bounds = (-np.inf, np.inf) + + # Define Objective Function + objective = ScalarFunction(fun, x0, args, grad, hess, + finite_diff_rel_step, finite_diff_bounds) + + # Put constraints in list format when needed. + if isinstance(constraints, (NonlinearConstraint | LinearConstraint)): + constraints = [constraints] + + # Prepare constraints. + prepared_constraints = [ + PreparedConstraint(c, x0, sparse_jacobian, finite_diff_bounds) + for c in constraints] + + # Check that all constraints are either sparse or dense. + n_sparse = sum(c.fun.sparse_jacobian for c in prepared_constraints) + if 0 < n_sparse < len(prepared_constraints): + raise ValueError("All constraints must have the same kind of the " + "Jacobian --- either all sparse or all dense. " + "You can set the sparsity globally by setting " + "`sparse_jacobian` to either True of False.") + if prepared_constraints: + sparse_jacobian = n_sparse > 0 + + if bounds is not None: + if sparse_jacobian is None: + sparse_jacobian = True + prepared_constraints.append(PreparedConstraint(bounds, x0, + sparse_jacobian)) + + # Concatenate initial constraints to the canonical form. + c_eq0, c_ineq0, J_eq0, J_ineq0 = initial_constraints_as_canonical( + n_vars, prepared_constraints, sparse_jacobian) + + # Prepare all canonical constraints and concatenate it into one. + canonical_all = [CanonicalConstraint.from_PreparedConstraint(c) + for c in prepared_constraints] + + if len(canonical_all) == 0: + canonical = CanonicalConstraint.empty(n_vars) + elif len(canonical_all) == 1: + canonical = canonical_all[0] + else: + canonical = CanonicalConstraint.concatenate(canonical_all, + sparse_jacobian) + + # Generate the Hessian of the Lagrangian. + lagrangian_hess = LagrangianHessian(n_vars, objective.hess, canonical.hess) + + # Choose appropriate method + if canonical.n_ineq == 0: + method = 'equality_constrained_sqp' + else: + method = 'tr_interior_point' + + # Construct OptimizeResult + state = OptimizeResult( + nit=0, nfev=0, njev=0, nhev=0, + cg_niter=0, cg_stop_cond=0, + fun=objective.f, grad=objective.g, + lagrangian_grad=np.copy(objective.g), + constr=[c.fun.f for c in prepared_constraints], + jac=[c.fun.J for c in prepared_constraints], + constr_nfev=[0 for c in prepared_constraints], + constr_njev=[0 for c in prepared_constraints], + constr_nhev=[0 for c in prepared_constraints], + v=[c.fun.v for c in prepared_constraints], + method=method) + + # Start counting + start_time = time.time() + + # Define stop criteria + if method == 'equality_constrained_sqp': + def stop_criteria(state, x, last_iteration_failed, + optimality, constr_violation, + tr_radius, constr_penalty, cg_info): + state = update_state_sqp(state, x, last_iteration_failed, + objective, prepared_constraints, + start_time, tr_radius, constr_penalty, + cg_info) + if verbose == 2: + BasicReport.print_iteration(state.nit, + state.nfev, + state.cg_niter, + state.fun, + state.tr_radius, + state.optimality, + state.constr_violation) + elif verbose > 2: + SQPReport.print_iteration(state.nit, + state.nfev, + state.cg_niter, + state.fun, + state.tr_radius, + state.optimality, + state.constr_violation, + state.constr_penalty, + state.cg_stop_cond) + state.status = None + state.niter = state.nit # Alias for callback (backward-compatibility) + if callback is not None: + callback_stop = False + try: + callback_stop = callback(state) + except StopIteration: + callback_stop = True + if callback_stop: + state.status = 3 + return True + if state.optimality < gtol and state.constr_violation < gtol: + state.status = 1 + elif state.tr_radius < xtol: + state.status = 2 + elif state.nit >= maxiter: + state.status = 0 + return state.status in (0, 1, 2, 3) + elif method == 'tr_interior_point': + def stop_criteria(state, x, last_iteration_failed, tr_radius, + constr_penalty, cg_info, barrier_parameter, + barrier_tolerance): + state = update_state_ip(state, x, last_iteration_failed, + objective, prepared_constraints, + start_time, tr_radius, constr_penalty, + cg_info, barrier_parameter, barrier_tolerance) + if verbose == 2: + BasicReport.print_iteration(state.nit, + state.nfev, + state.cg_niter, + state.fun, + state.tr_radius, + state.optimality, + state.constr_violation) + elif verbose > 2: + IPReport.print_iteration(state.nit, + state.nfev, + state.cg_niter, + state.fun, + state.tr_radius, + state.optimality, + state.constr_violation, + state.constr_penalty, + state.barrier_parameter, + state.cg_stop_cond) + state.status = None + state.niter = state.nit # Alias for callback (backward compatibility) + if callback is not None: + callback_stop = False + try: + callback_stop = callback(state) + except StopIteration: + callback_stop = True + if callback_stop: + state.status = 3 + return True + if state.optimality < gtol and state.constr_violation < gtol: + state.status = 1 + elif (state.tr_radius < xtol + and state.barrier_parameter < barrier_tol): + state.status = 2 + elif state.nit >= maxiter: + state.status = 0 + return state.status in (0, 1, 2, 3) + + if verbose == 2: + BasicReport.print_header() + elif verbose > 2: + if method == 'equality_constrained_sqp': + SQPReport.print_header() + elif method == 'tr_interior_point': + IPReport.print_header() + + # Call inferior function to do the optimization + if method == 'equality_constrained_sqp': + def fun_and_constr(x): + f = objective.fun(x) + c_eq, _ = canonical.fun(x) + return f, c_eq + + def grad_and_jac(x): + g = objective.grad(x) + J_eq, _ = canonical.jac(x) + return g, J_eq + + _, result = equality_constrained_sqp( + fun_and_constr, grad_and_jac, lagrangian_hess, + x0, objective.f, objective.g, + c_eq0, J_eq0, + stop_criteria, state, + initial_constr_penalty, initial_tr_radius, + factorization_method) + + elif method == 'tr_interior_point': + _, result = tr_interior_point( + objective.fun, objective.grad, lagrangian_hess, + n_vars, canonical.n_ineq, canonical.n_eq, + canonical.fun, canonical.jac, + x0, objective.f, objective.g, + c_ineq0, J_ineq0, c_eq0, J_eq0, + stop_criteria, + canonical.keep_feasible, + xtol, state, initial_barrier_parameter, + initial_barrier_tolerance, + initial_constr_penalty, initial_tr_radius, + factorization_method, finite_diff_bounds) + + # Status 4 occurs when minimize is successful but constraints are not satisfied. + if result.status in (1, 2) and state.constr_violation > gtol: + result.status = 4 + + # Status 3 occurs when the callback function requests termination, + # this is assumed to not be a success. + result.success = True if result.status in (1, 2) else False + result.message = TERMINATION_MESSAGES[result.status] + + # Alias (for backward compatibility with 1.1.0) + result.niter = result.nit + + if verbose == 2: + BasicReport.print_footer() + elif verbose > 2: + if method == 'equality_constrained_sqp': + SQPReport.print_footer() + elif method == 'tr_interior_point': + IPReport.print_footer() + if verbose >= 1: + print(result.message) + print(f"Number of iterations: {result.nit}, " + f"function evaluations: {result.nfev}, " + f"CG iterations: {result.cg_niter}, " + f"optimality: {result.optimality:.2e}, " + f"constraint violation: {result.constr_violation:.2e}, " + f"execution time: {result.execution_time:4.2} s.") + return result diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/projections.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/projections.py new file mode 100644 index 0000000000000000000000000000000000000000..a07b836bdbad688a265ae34ce91a361fd5050eb1 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/projections.py @@ -0,0 +1,407 @@ +"""Basic linear factorizations needed by the solver.""" + +from scipy.sparse import (bmat, csc_matrix, eye, issparse) +from scipy.sparse.linalg import LinearOperator +import scipy.linalg +import scipy.sparse.linalg +try: + from sksparse.cholmod import cholesky_AAt + sksparse_available = True +except ImportError: + import warnings + sksparse_available = False +import numpy as np +from warnings import warn + +__all__ = [ + 'orthogonality', + 'projections', +] + + +def orthogonality(A, g): + """Measure orthogonality between a vector and the null space of a matrix. + + Compute a measure of orthogonality between the null space + of the (possibly sparse) matrix ``A`` and a given vector ``g``. + + The formula is a simplified (and cheaper) version of formula (3.13) + from [1]_. + ``orth = norm(A g, ord=2)/(norm(A, ord='fro')*norm(g, ord=2))``. + + References + ---------- + .. [1] Gould, Nicholas IM, Mary E. Hribar, and Jorge Nocedal. + "On the solution of equality constrained quadratic + programming problems arising in optimization." + SIAM Journal on Scientific Computing 23.4 (2001): 1376-1395. + """ + # Compute vector norms + norm_g = np.linalg.norm(g) + # Compute Froebnius norm of the matrix A + if issparse(A): + norm_A = scipy.sparse.linalg.norm(A, ord='fro') + else: + norm_A = np.linalg.norm(A, ord='fro') + + # Check if norms are zero + if norm_g == 0 or norm_A == 0: + return 0 + + norm_A_g = np.linalg.norm(A.dot(g)) + # Orthogonality measure + orth = norm_A_g / (norm_A*norm_g) + return orth + + +def normal_equation_projections(A, m, n, orth_tol, max_refin, tol): + """Return linear operators for matrix A using ``NormalEquation`` approach. + """ + # Cholesky factorization + factor = cholesky_AAt(A) + + # z = x - A.T inv(A A.T) A x + def null_space(x): + v = factor(A.dot(x)) + z = x - A.T.dot(v) + + # Iterative refinement to improve roundoff + # errors described in [2]_, algorithm 5.1. + k = 0 + while orthogonality(A, z) > orth_tol: + if k >= max_refin: + break + # z_next = z - A.T inv(A A.T) A z + v = factor(A.dot(z)) + z = z - A.T.dot(v) + k += 1 + + return z + + # z = inv(A A.T) A x + def least_squares(x): + return factor(A.dot(x)) + + # z = A.T inv(A A.T) x + def row_space(x): + return A.T.dot(factor(x)) + + return null_space, least_squares, row_space + + +def augmented_system_projections(A, m, n, orth_tol, max_refin, tol): + """Return linear operators for matrix A - ``AugmentedSystem``.""" + # Form augmented system + K = csc_matrix(bmat([[eye(n), A.T], [A, None]])) + # LU factorization + # TODO: Use a symmetric indefinite factorization + # to solve the system twice as fast (because + # of the symmetry). + try: + solve = scipy.sparse.linalg.factorized(K) + except RuntimeError: + warn("Singular Jacobian matrix. Using dense SVD decomposition to " + "perform the factorizations.", + stacklevel=3) + return svd_factorization_projections(A.toarray(), + m, n, orth_tol, + max_refin, tol) + + # z = x - A.T inv(A A.T) A x + # is computed solving the extended system: + # [I A.T] * [ z ] = [x] + # [A O ] [aux] [0] + def null_space(x): + # v = [x] + # [0] + v = np.hstack([x, np.zeros(m)]) + # lu_sol = [ z ] + # [aux] + lu_sol = solve(v) + z = lu_sol[:n] + + # Iterative refinement to improve roundoff + # errors described in [2]_, algorithm 5.2. + k = 0 + while orthogonality(A, z) > orth_tol: + if k >= max_refin: + break + # new_v = [x] - [I A.T] * [ z ] + # [0] [A O ] [aux] + new_v = v - K.dot(lu_sol) + # [I A.T] * [delta z ] = new_v + # [A O ] [delta aux] + lu_update = solve(new_v) + # [ z ] += [delta z ] + # [aux] [delta aux] + lu_sol += lu_update + z = lu_sol[:n] + k += 1 + + # return z = x - A.T inv(A A.T) A x + return z + + # z = inv(A A.T) A x + # is computed solving the extended system: + # [I A.T] * [aux] = [x] + # [A O ] [ z ] [0] + def least_squares(x): + # v = [x] + # [0] + v = np.hstack([x, np.zeros(m)]) + # lu_sol = [aux] + # [ z ] + lu_sol = solve(v) + # return z = inv(A A.T) A x + return lu_sol[n:m+n] + + # z = A.T inv(A A.T) x + # is computed solving the extended system: + # [I A.T] * [ z ] = [0] + # [A O ] [aux] [x] + def row_space(x): + # v = [0] + # [x] + v = np.hstack([np.zeros(n), x]) + # lu_sol = [ z ] + # [aux] + lu_sol = solve(v) + # return z = A.T inv(A A.T) x + return lu_sol[:n] + + return null_space, least_squares, row_space + + +def qr_factorization_projections(A, m, n, orth_tol, max_refin, tol): + """Return linear operators for matrix A using ``QRFactorization`` approach. + """ + # QRFactorization + Q, R, P = scipy.linalg.qr(A.T, pivoting=True, mode='economic') + + if np.linalg.norm(R[-1, :], np.inf) < tol: + warn('Singular Jacobian matrix. Using SVD decomposition to ' + + 'perform the factorizations.', + stacklevel=3) + return svd_factorization_projections(A, m, n, + orth_tol, + max_refin, + tol) + + # z = x - A.T inv(A A.T) A x + def null_space(x): + # v = P inv(R) Q.T x + aux1 = Q.T.dot(x) + aux2 = scipy.linalg.solve_triangular(R, aux1, lower=False) + v = np.zeros(m) + v[P] = aux2 + z = x - A.T.dot(v) + + # Iterative refinement to improve roundoff + # errors described in [2]_, algorithm 5.1. + k = 0 + while orthogonality(A, z) > orth_tol: + if k >= max_refin: + break + # v = P inv(R) Q.T x + aux1 = Q.T.dot(z) + aux2 = scipy.linalg.solve_triangular(R, aux1, lower=False) + v[P] = aux2 + # z_next = z - A.T v + z = z - A.T.dot(v) + k += 1 + + return z + + # z = inv(A A.T) A x + def least_squares(x): + # z = P inv(R) Q.T x + aux1 = Q.T.dot(x) + aux2 = scipy.linalg.solve_triangular(R, aux1, lower=False) + z = np.zeros(m) + z[P] = aux2 + return z + + # z = A.T inv(A A.T) x + def row_space(x): + # z = Q inv(R.T) P.T x + aux1 = x[P] + aux2 = scipy.linalg.solve_triangular(R, aux1, + lower=False, + trans='T') + z = Q.dot(aux2) + return z + + return null_space, least_squares, row_space + + +def svd_factorization_projections(A, m, n, orth_tol, max_refin, tol): + """Return linear operators for matrix A using ``SVDFactorization`` approach. + """ + # SVD Factorization + U, s, Vt = scipy.linalg.svd(A, full_matrices=False) + + # Remove dimensions related with very small singular values + U = U[:, s > tol] + Vt = Vt[s > tol, :] + s = s[s > tol] + + # z = x - A.T inv(A A.T) A x + def null_space(x): + # v = U 1/s V.T x = inv(A A.T) A x + aux1 = Vt.dot(x) + aux2 = 1/s*aux1 + v = U.dot(aux2) + z = x - A.T.dot(v) + + # Iterative refinement to improve roundoff + # errors described in [2]_, algorithm 5.1. + k = 0 + while orthogonality(A, z) > orth_tol: + if k >= max_refin: + break + # v = U 1/s V.T x = inv(A A.T) A x + aux1 = Vt.dot(z) + aux2 = 1/s*aux1 + v = U.dot(aux2) + # z_next = z - A.T v + z = z - A.T.dot(v) + k += 1 + + return z + + # z = inv(A A.T) A x + def least_squares(x): + # z = U 1/s V.T x = inv(A A.T) A x + aux1 = Vt.dot(x) + aux2 = 1/s*aux1 + z = U.dot(aux2) + return z + + # z = A.T inv(A A.T) x + def row_space(x): + # z = V 1/s U.T x + aux1 = U.T.dot(x) + aux2 = 1/s*aux1 + z = Vt.T.dot(aux2) + return z + + return null_space, least_squares, row_space + + +def projections(A, method=None, orth_tol=1e-12, max_refin=3, tol=1e-15): + """Return three linear operators related with a given matrix A. + + Parameters + ---------- + A : sparse matrix (or ndarray), shape (m, n) + Matrix ``A`` used in the projection. + method : string, optional + Method used for compute the given linear + operators. Should be one of: + + - 'NormalEquation': The operators + will be computed using the + so-called normal equation approach + explained in [1]_. In order to do + so the Cholesky factorization of + ``(A A.T)`` is computed. Exclusive + for sparse matrices. + - 'AugmentedSystem': The operators + will be computed using the + so-called augmented system approach + explained in [1]_. Exclusive + for sparse matrices. + - 'QRFactorization': Compute projections + using QR factorization. Exclusive for + dense matrices. + - 'SVDFactorization': Compute projections + using SVD factorization. Exclusive for + dense matrices. + + orth_tol : float, optional + Tolerance for iterative refinements. + max_refin : int, optional + Maximum number of iterative refinements. + tol : float, optional + Tolerance for singular values. + + Returns + ------- + Z : LinearOperator, shape (n, n) + Null-space operator. For a given vector ``x``, + the null space operator is equivalent to apply + a projection matrix ``P = I - A.T inv(A A.T) A`` + to the vector. It can be shown that this is + equivalent to project ``x`` into the null space + of A. + LS : LinearOperator, shape (m, n) + Least-squares operator. For a given vector ``x``, + the least-squares operator is equivalent to apply a + pseudoinverse matrix ``pinv(A.T) = inv(A A.T) A`` + to the vector. It can be shown that this vector + ``pinv(A.T) x`` is the least_square solution to + ``A.T y = x``. + Y : LinearOperator, shape (n, m) + Row-space operator. For a given vector ``x``, + the row-space operator is equivalent to apply a + projection matrix ``Q = A.T inv(A A.T)`` + to the vector. It can be shown that this + vector ``y = Q x`` the minimum norm solution + of ``A y = x``. + + Notes + ----- + Uses iterative refinements described in [1] + during the computation of ``Z`` in order to + cope with the possibility of large roundoff errors. + + References + ---------- + .. [1] Gould, Nicholas IM, Mary E. Hribar, and Jorge Nocedal. + "On the solution of equality constrained quadratic + programming problems arising in optimization." + SIAM Journal on Scientific Computing 23.4 (2001): 1376-1395. + """ + m, n = np.shape(A) + + # The factorization of an empty matrix + # only works for the sparse representation. + if m*n == 0: + A = csc_matrix(A) + + # Check Argument + if issparse(A): + if method is None: + method = "AugmentedSystem" + if method not in ("NormalEquation", "AugmentedSystem"): + raise ValueError("Method not allowed for sparse matrix.") + if method == "NormalEquation" and not sksparse_available: + warnings.warn("Only accepts 'NormalEquation' option when " + "scikit-sparse is available. Using " + "'AugmentedSystem' option instead.", + ImportWarning, stacklevel=3) + method = 'AugmentedSystem' + else: + if method is None: + method = "QRFactorization" + if method not in ("QRFactorization", "SVDFactorization"): + raise ValueError("Method not allowed for dense array.") + + if method == 'NormalEquation': + null_space, least_squares, row_space \ + = normal_equation_projections(A, m, n, orth_tol, max_refin, tol) + elif method == 'AugmentedSystem': + null_space, least_squares, row_space \ + = augmented_system_projections(A, m, n, orth_tol, max_refin, tol) + elif method == "QRFactorization": + null_space, least_squares, row_space \ + = qr_factorization_projections(A, m, n, orth_tol, max_refin, tol) + elif method == "SVDFactorization": + null_space, least_squares, row_space \ + = svd_factorization_projections(A, m, n, orth_tol, max_refin, tol) + + Z = LinearOperator((n, n), null_space) + LS = LinearOperator((m, n), least_squares) + Y = LinearOperator((n, m), row_space) + + return Z, LS, Y diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/qp_subproblem.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/qp_subproblem.py new file mode 100644 index 0000000000000000000000000000000000000000..a039a7738c283f90f30fd7c4583bf9e1a8f559d5 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/qp_subproblem.py @@ -0,0 +1,637 @@ +"""Equality-constrained quadratic programming solvers.""" + +from scipy.sparse import (linalg, bmat, csc_matrix) +from math import copysign +import numpy as np +from numpy.linalg import norm + +__all__ = [ + 'eqp_kktfact', + 'sphere_intersections', + 'box_intersections', + 'box_sphere_intersections', + 'inside_box_boundaries', + 'modified_dogleg', + 'projected_cg' +] + + +# For comparison with the projected CG +def eqp_kktfact(H, c, A, b): + """Solve equality-constrained quadratic programming (EQP) problem. + + Solve ``min 1/2 x.T H x + x.t c`` subject to ``A x + b = 0`` + using direct factorization of the KKT system. + + Parameters + ---------- + H : sparse matrix, shape (n, n) + Hessian matrix of the EQP problem. + c : array_like, shape (n,) + Gradient of the quadratic objective function. + A : sparse matrix + Jacobian matrix of the EQP problem. + b : array_like, shape (m,) + Right-hand side of the constraint equation. + + Returns + ------- + x : array_like, shape (n,) + Solution of the KKT problem. + lagrange_multipliers : ndarray, shape (m,) + Lagrange multipliers of the KKT problem. + """ + n, = np.shape(c) # Number of parameters + m, = np.shape(b) # Number of constraints + + # Karush-Kuhn-Tucker matrix of coefficients. + # Defined as in Nocedal/Wright "Numerical + # Optimization" p.452 in Eq. (16.4). + kkt_matrix = csc_matrix(bmat([[H, A.T], [A, None]])) + # Vector of coefficients. + kkt_vec = np.hstack([-c, -b]) + + # TODO: Use a symmetric indefinite factorization + # to solve the system twice as fast (because + # of the symmetry). + lu = linalg.splu(kkt_matrix) + kkt_sol = lu.solve(kkt_vec) + x = kkt_sol[:n] + lagrange_multipliers = -kkt_sol[n:n+m] + + return x, lagrange_multipliers + + +def sphere_intersections(z, d, trust_radius, + entire_line=False): + """Find the intersection between segment (or line) and spherical constraints. + + Find the intersection between the segment (or line) defined by the + parametric equation ``x(t) = z + t*d`` and the ball + ``||x|| <= trust_radius``. + + Parameters + ---------- + z : array_like, shape (n,) + Initial point. + d : array_like, shape (n,) + Direction. + trust_radius : float + Ball radius. + entire_line : bool, optional + When ``True``, the function returns the intersection between the line + ``x(t) = z + t*d`` (``t`` can assume any value) and the ball + ``||x|| <= trust_radius``. When ``False``, the function returns the intersection + between the segment ``x(t) = z + t*d``, ``0 <= t <= 1``, and the ball. + + Returns + ------- + ta, tb : float + The line/segment ``x(t) = z + t*d`` is inside the ball for + for ``ta <= t <= tb``. + intersect : bool + When ``True``, there is a intersection between the line/segment + and the sphere. On the other hand, when ``False``, there is no + intersection. + """ + # Special case when d=0 + if norm(d) == 0: + return 0, 0, False + # Check for inf trust_radius + if np.isinf(trust_radius): + if entire_line: + ta = -np.inf + tb = np.inf + else: + ta = 0 + tb = 1 + intersect = True + return ta, tb, intersect + + a = np.dot(d, d) + b = 2 * np.dot(z, d) + c = np.dot(z, z) - trust_radius**2 + discriminant = b*b - 4*a*c + if discriminant < 0: + intersect = False + return 0, 0, intersect + sqrt_discriminant = np.sqrt(discriminant) + + # The following calculation is mathematically + # equivalent to: + # ta = (-b - sqrt_discriminant) / (2*a) + # tb = (-b + sqrt_discriminant) / (2*a) + # but produce smaller round off errors. + # Look at Matrix Computation p.97 + # for a better justification. + aux = b + copysign(sqrt_discriminant, b) + ta = -aux / (2*a) + tb = -2*c / aux + ta, tb = sorted([ta, tb]) + + if entire_line: + intersect = True + else: + # Checks to see if intersection happens + # within vectors length. + if tb < 0 or ta > 1: + intersect = False + ta = 0 + tb = 0 + else: + intersect = True + # Restrict intersection interval + # between 0 and 1. + ta = max(0, ta) + tb = min(1, tb) + + return ta, tb, intersect + + +def box_intersections(z, d, lb, ub, + entire_line=False): + """Find the intersection between segment (or line) and box constraints. + + Find the intersection between the segment (or line) defined by the + parametric equation ``x(t) = z + t*d`` and the rectangular box + ``lb <= x <= ub``. + + Parameters + ---------- + z : array_like, shape (n,) + Initial point. + d : array_like, shape (n,) + Direction. + lb : array_like, shape (n,) + Lower bounds to each one of the components of ``x``. Used + to delimit the rectangular box. + ub : array_like, shape (n, ) + Upper bounds to each one of the components of ``x``. Used + to delimit the rectangular box. + entire_line : bool, optional + When ``True``, the function returns the intersection between the line + ``x(t) = z + t*d`` (``t`` can assume any value) and the rectangular + box. When ``False``, the function returns the intersection between the segment + ``x(t) = z + t*d``, ``0 <= t <= 1``, and the rectangular box. + + Returns + ------- + ta, tb : float + The line/segment ``x(t) = z + t*d`` is inside the box for + for ``ta <= t <= tb``. + intersect : bool + When ``True``, there is a intersection between the line (or segment) + and the rectangular box. On the other hand, when ``False``, there is no + intersection. + """ + # Make sure it is a numpy array + z = np.asarray(z) + d = np.asarray(d) + lb = np.asarray(lb) + ub = np.asarray(ub) + # Special case when d=0 + if norm(d) == 0: + return 0, 0, False + + # Get values for which d==0 + zero_d = (d == 0) + # If the boundaries are not satisfied for some coordinate + # for which "d" is zero, there is no box-line intersection. + if (z[zero_d] < lb[zero_d]).any() or (z[zero_d] > ub[zero_d]).any(): + intersect = False + return 0, 0, intersect + # Remove values for which d is zero + not_zero_d = np.logical_not(zero_d) + z = z[not_zero_d] + d = d[not_zero_d] + lb = lb[not_zero_d] + ub = ub[not_zero_d] + + # Find a series of intervals (t_lb[i], t_ub[i]). + t_lb = (lb-z) / d + t_ub = (ub-z) / d + # Get the intersection of all those intervals. + ta = max(np.minimum(t_lb, t_ub)) + tb = min(np.maximum(t_lb, t_ub)) + + # Check if intersection is feasible + if ta <= tb: + intersect = True + else: + intersect = False + # Checks to see if intersection happens within vectors length. + if not entire_line: + if tb < 0 or ta > 1: + intersect = False + ta = 0 + tb = 0 + else: + # Restrict intersection interval between 0 and 1. + ta = max(0, ta) + tb = min(1, tb) + + return ta, tb, intersect + + +def box_sphere_intersections(z, d, lb, ub, trust_radius, + entire_line=False, + extra_info=False): + """Find the intersection between segment (or line) and box/sphere constraints. + + Find the intersection between the segment (or line) defined by the + parametric equation ``x(t) = z + t*d``, the rectangular box + ``lb <= x <= ub`` and the ball ``||x|| <= trust_radius``. + + Parameters + ---------- + z : array_like, shape (n,) + Initial point. + d : array_like, shape (n,) + Direction. + lb : array_like, shape (n,) + Lower bounds to each one of the components of ``x``. Used + to delimit the rectangular box. + ub : array_like, shape (n, ) + Upper bounds to each one of the components of ``x``. Used + to delimit the rectangular box. + trust_radius : float + Ball radius. + entire_line : bool, optional + When ``True``, the function returns the intersection between the line + ``x(t) = z + t*d`` (``t`` can assume any value) and the constraints. + When ``False``, the function returns the intersection between the segment + ``x(t) = z + t*d``, ``0 <= t <= 1`` and the constraints. + extra_info : bool, optional + When ``True``, the function returns ``intersect_sphere`` and ``intersect_box``. + + Returns + ------- + ta, tb : float + The line/segment ``x(t) = z + t*d`` is inside the rectangular box and + inside the ball for ``ta <= t <= tb``. + intersect : bool + When ``True``, there is a intersection between the line (or segment) + and both constraints. On the other hand, when ``False``, there is no + intersection. + sphere_info : dict, optional + Dictionary ``{ta, tb, intersect}`` containing the interval ``[ta, tb]`` + for which the line intercepts the ball. And a boolean value indicating + whether the sphere is intersected by the line. + box_info : dict, optional + Dictionary ``{ta, tb, intersect}`` containing the interval ``[ta, tb]`` + for which the line intercepts the box. And a boolean value indicating + whether the box is intersected by the line. + """ + ta_b, tb_b, intersect_b = box_intersections(z, d, lb, ub, + entire_line) + ta_s, tb_s, intersect_s = sphere_intersections(z, d, + trust_radius, + entire_line) + ta = np.maximum(ta_b, ta_s) + tb = np.minimum(tb_b, tb_s) + if intersect_b and intersect_s and ta <= tb: + intersect = True + else: + intersect = False + + if extra_info: + sphere_info = {'ta': ta_s, 'tb': tb_s, 'intersect': intersect_s} + box_info = {'ta': ta_b, 'tb': tb_b, 'intersect': intersect_b} + return ta, tb, intersect, sphere_info, box_info + else: + return ta, tb, intersect + + +def inside_box_boundaries(x, lb, ub): + """Check if lb <= x <= ub.""" + return (lb <= x).all() and (x <= ub).all() + + +def reinforce_box_boundaries(x, lb, ub): + """Return clipped value of x""" + return np.minimum(np.maximum(x, lb), ub) + + +def modified_dogleg(A, Y, b, trust_radius, lb, ub): + """Approximately minimize ``1/2*|| A x + b ||^2`` inside trust-region. + + Approximately solve the problem of minimizing ``1/2*|| A x + b ||^2`` + subject to ``||x|| < Delta`` and ``lb <= x <= ub`` using a modification + of the classical dogleg approach. + + Parameters + ---------- + A : LinearOperator (or sparse matrix or ndarray), shape (m, n) + Matrix ``A`` in the minimization problem. It should have + dimension ``(m, n)`` such that ``m < n``. + Y : LinearOperator (or sparse matrix or ndarray), shape (n, m) + LinearOperator that apply the projection matrix + ``Q = A.T inv(A A.T)`` to the vector. The obtained vector + ``y = Q x`` being the minimum norm solution of ``A y = x``. + b : array_like, shape (m,) + Vector ``b``in the minimization problem. + trust_radius: float + Trust radius to be considered. Delimits a sphere boundary + to the problem. + lb : array_like, shape (n,) + Lower bounds to each one of the components of ``x``. + It is expected that ``lb <= 0``, otherwise the algorithm + may fail. If ``lb[i] = -Inf``, the lower + bound for the ith component is just ignored. + ub : array_like, shape (n, ) + Upper bounds to each one of the components of ``x``. + It is expected that ``ub >= 0``, otherwise the algorithm + may fail. If ``ub[i] = Inf``, the upper bound for the ith + component is just ignored. + + Returns + ------- + x : array_like, shape (n,) + Solution to the problem. + + Notes + ----- + Based on implementations described in pp. 885-886 from [1]_. + + References + ---------- + .. [1] Byrd, Richard H., Mary E. Hribar, and Jorge Nocedal. + "An interior point algorithm for large-scale nonlinear + programming." SIAM Journal on Optimization 9.4 (1999): 877-900. + """ + # Compute minimum norm minimizer of 1/2*|| A x + b ||^2. + newton_point = -Y.dot(b) + # Check for interior point + if inside_box_boundaries(newton_point, lb, ub) \ + and norm(newton_point) <= trust_radius: + x = newton_point + return x + + # Compute gradient vector ``g = A.T b`` + g = A.T.dot(b) + # Compute Cauchy point + # `cauchy_point = g.T g / (g.T A.T A g)``. + A_g = A.dot(g) + cauchy_point = -np.dot(g, g) / np.dot(A_g, A_g) * g + # Origin + origin_point = np.zeros_like(cauchy_point) + + # Check the segment between cauchy_point and newton_point + # for a possible solution. + z = cauchy_point + p = newton_point - cauchy_point + _, alpha, intersect = box_sphere_intersections(z, p, lb, ub, + trust_radius) + if intersect: + x1 = z + alpha*p + else: + # Check the segment between the origin and cauchy_point + # for a possible solution. + z = origin_point + p = cauchy_point + _, alpha, _ = box_sphere_intersections(z, p, lb, ub, + trust_radius) + x1 = z + alpha*p + + # Check the segment between origin and newton_point + # for a possible solution. + z = origin_point + p = newton_point + _, alpha, _ = box_sphere_intersections(z, p, lb, ub, + trust_radius) + x2 = z + alpha*p + + # Return the best solution among x1 and x2. + if norm(A.dot(x1) + b) < norm(A.dot(x2) + b): + return x1 + else: + return x2 + + +def projected_cg(H, c, Z, Y, b, trust_radius=np.inf, + lb=None, ub=None, tol=None, + max_iter=None, max_infeasible_iter=None, + return_all=False): + """Solve EQP problem with projected CG method. + + Solve equality-constrained quadratic programming problem + ``min 1/2 x.T H x + x.t c`` subject to ``A x + b = 0`` and, + possibly, to trust region constraints ``||x|| < trust_radius`` + and box constraints ``lb <= x <= ub``. + + Parameters + ---------- + H : LinearOperator (or sparse matrix or ndarray), shape (n, n) + Operator for computing ``H v``. + c : array_like, shape (n,) + Gradient of the quadratic objective function. + Z : LinearOperator (or sparse matrix or ndarray), shape (n, n) + Operator for projecting ``x`` into the null space of A. + Y : LinearOperator, sparse matrix, ndarray, shape (n, m) + Operator that, for a given a vector ``b``, compute smallest + norm solution of ``A x + b = 0``. + b : array_like, shape (m,) + Right-hand side of the constraint equation. + trust_radius : float, optional + Trust radius to be considered. By default, uses ``trust_radius=inf``, + which means no trust radius at all. + lb : array_like, shape (n,), optional + Lower bounds to each one of the components of ``x``. + If ``lb[i] = -Inf`` the lower bound for the i-th + component is just ignored (default). + ub : array_like, shape (n, ), optional + Upper bounds to each one of the components of ``x``. + If ``ub[i] = Inf`` the upper bound for the i-th + component is just ignored (default). + tol : float, optional + Tolerance used to interrupt the algorithm. + max_iter : int, optional + Maximum algorithm iterations. Where ``max_inter <= n-m``. + By default, uses ``max_iter = n-m``. + max_infeasible_iter : int, optional + Maximum infeasible (regarding box constraints) iterations the + algorithm is allowed to take. + By default, uses ``max_infeasible_iter = n-m``. + return_all : bool, optional + When ``true``, return the list of all vectors through the iterations. + + Returns + ------- + x : array_like, shape (n,) + Solution of the EQP problem. + info : Dict + Dictionary containing the following: + + - niter : Number of iterations. + - stop_cond : Reason for algorithm termination: + 1. Iteration limit was reached; + 2. Reached the trust-region boundary; + 3. Negative curvature detected; + 4. Tolerance was satisfied. + - allvecs : List containing all intermediary vectors (optional). + - hits_boundary : True if the proposed step is on the boundary + of the trust region. + + Notes + ----- + Implementation of Algorithm 6.2 on [1]_. + + In the absence of spherical and box constraints, for sufficient + iterations, the method returns a truly optimal result. + In the presence of those constraints, the value returned is only + a inexpensive approximation of the optimal value. + + References + ---------- + .. [1] Gould, Nicholas IM, Mary E. Hribar, and Jorge Nocedal. + "On the solution of equality constrained quadratic + programming problems arising in optimization." + SIAM Journal on Scientific Computing 23.4 (2001): 1376-1395. + """ + CLOSE_TO_ZERO = 1e-25 + + n, = np.shape(c) # Number of parameters + m, = np.shape(b) # Number of constraints + + # Initial Values + x = Y.dot(-b) + r = Z.dot(H.dot(x) + c) + g = Z.dot(r) + p = -g + + # Store ``x`` value + if return_all: + allvecs = [x] + # Values for the first iteration + H_p = H.dot(p) + rt_g = norm(g)**2 # g.T g = r.T Z g = r.T g (ref [1]_ p.1389) + + # If x > trust-region the problem does not have a solution. + tr_distance = trust_radius - norm(x) + if tr_distance < 0: + raise ValueError("Trust region problem does not have a solution.") + # If x == trust_radius, then x is the solution + # to the optimization problem, since x is the + # minimum norm solution to Ax=b. + elif tr_distance < CLOSE_TO_ZERO: + info = {'niter': 0, 'stop_cond': 2, 'hits_boundary': True} + if return_all: + allvecs.append(x) + info['allvecs'] = allvecs + return x, info + + # Set default tolerance + if tol is None: + tol = max(min(0.01 * np.sqrt(rt_g), 0.1 * rt_g), CLOSE_TO_ZERO) + # Set default lower and upper bounds + if lb is None: + lb = np.full(n, -np.inf) + if ub is None: + ub = np.full(n, np.inf) + # Set maximum iterations + if max_iter is None: + max_iter = n-m + max_iter = min(max_iter, n-m) + # Set maximum infeasible iterations + if max_infeasible_iter is None: + max_infeasible_iter = n-m + + hits_boundary = False + stop_cond = 1 + counter = 0 + last_feasible_x = np.zeros_like(x) + k = 0 + for i in range(max_iter): + # Stop criteria - Tolerance : r.T g < tol + if rt_g < tol: + stop_cond = 4 + break + k += 1 + # Compute curvature + pt_H_p = H_p.dot(p) + # Stop criteria - Negative curvature + if pt_H_p <= 0: + if np.isinf(trust_radius): + raise ValueError("Negative curvature not allowed " + "for unrestricted problems.") + else: + # Find intersection with constraints + _, alpha, intersect = box_sphere_intersections( + x, p, lb, ub, trust_radius, entire_line=True) + # Update solution + if intersect: + x = x + alpha*p + # Reinforce variables are inside box constraints. + # This is only necessary because of roundoff errors. + x = reinforce_box_boundaries(x, lb, ub) + # Attribute information + stop_cond = 3 + hits_boundary = True + break + + # Get next step + alpha = rt_g / pt_H_p + x_next = x + alpha*p + + # Stop criteria - Hits boundary + if np.linalg.norm(x_next) >= trust_radius: + # Find intersection with box constraints + _, theta, intersect = box_sphere_intersections(x, alpha*p, lb, ub, + trust_radius) + # Update solution + if intersect: + x = x + theta*alpha*p + # Reinforce variables are inside box constraints. + # This is only necessary because of roundoff errors. + x = reinforce_box_boundaries(x, lb, ub) + # Attribute information + stop_cond = 2 + hits_boundary = True + break + + # Check if ``x`` is inside the box and start counter if it is not. + if inside_box_boundaries(x_next, lb, ub): + counter = 0 + else: + counter += 1 + # Whenever outside box constraints keep looking for intersections. + if counter > 0: + _, theta, intersect = box_sphere_intersections(x, alpha*p, lb, ub, + trust_radius) + if intersect: + last_feasible_x = x + theta*alpha*p + # Reinforce variables are inside box constraints. + # This is only necessary because of roundoff errors. + last_feasible_x = reinforce_box_boundaries(last_feasible_x, + lb, ub) + counter = 0 + # Stop after too many infeasible (regarding box constraints) iteration. + if counter > max_infeasible_iter: + break + # Store ``x_next`` value + if return_all: + allvecs.append(x_next) + + # Update residual + r_next = r + alpha*H_p + # Project residual g+ = Z r+ + g_next = Z.dot(r_next) + # Compute conjugate direction step d + rt_g_next = norm(g_next)**2 # g.T g = r.T g (ref [1]_ p.1389) + beta = rt_g_next / rt_g + p = - g_next + beta*p + # Prepare for next iteration + x = x_next + g = g_next + r = g_next + rt_g = norm(g)**2 # g.T g = r.T Z g = r.T g (ref [1]_ p.1389) + H_p = H.dot(p) + + if not inside_box_boundaries(x, lb, ub): + x = last_feasible_x + hits_boundary = True + info = {'niter': k, 'stop_cond': stop_cond, + 'hits_boundary': hits_boundary} + if return_all: + info['allvecs'] = allvecs + return x, info diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/report.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/report.py new file mode 100644 index 0000000000000000000000000000000000000000..f7f997d663cd5ce6265e77f940622b6105362bf7 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/report.py @@ -0,0 +1,49 @@ +"""Progress report printers.""" + +class ReportBase: + COLUMN_NAMES: list[str] = NotImplemented + COLUMN_WIDTHS: list[int] = NotImplemented + ITERATION_FORMATS: list[str] = NotImplemented + + @classmethod + def print_header(cls): + fmt = ("|" + + "|".join([f"{{:^{x}}}" for x in cls.COLUMN_WIDTHS]) + + "|") + separators = ['-' * x for x in cls.COLUMN_WIDTHS] + print(fmt.format(*cls.COLUMN_NAMES)) + print(fmt.format(*separators)) + + @classmethod + def print_iteration(cls, *args): + iteration_format = [f"{{:{x}}}" for x in cls.ITERATION_FORMATS] + fmt = "|" + "|".join(iteration_format) + "|" + print(fmt.format(*args)) + + @classmethod + def print_footer(cls): + print() + + +class BasicReport(ReportBase): + COLUMN_NAMES = ["niter", "f evals", "CG iter", "obj func", "tr radius", + "opt", "c viol"] + COLUMN_WIDTHS = [7, 7, 7, 13, 10, 10, 10] + ITERATION_FORMATS = ["^7", "^7", "^7", "^+13.4e", + "^10.2e", "^10.2e", "^10.2e"] + + +class SQPReport(ReportBase): + COLUMN_NAMES = ["niter", "f evals", "CG iter", "obj func", "tr radius", + "opt", "c viol", "penalty", "CG stop"] + COLUMN_WIDTHS = [7, 7, 7, 13, 10, 10, 10, 10, 7] + ITERATION_FORMATS = ["^7", "^7", "^7", "^+13.4e", "^10.2e", "^10.2e", + "^10.2e", "^10.2e", "^7"] + + +class IPReport(ReportBase): + COLUMN_NAMES = ["niter", "f evals", "CG iter", "obj func", "tr radius", + "opt", "c viol", "penalty", "barrier param", "CG stop"] + COLUMN_WIDTHS = [7, 7, 7, 13, 10, 10, 10, 10, 13, 7] + ITERATION_FORMATS = ["^7", "^7", "^7", "^+13.4e", "^10.2e", "^10.2e", + "^10.2e", "^10.2e", "^13.2e", "^7"] diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/test_canonical_constraint.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/test_canonical_constraint.py new file mode 100644 index 0000000000000000000000000000000000000000..452b327d02da3b3bd3fab9592bdef4d56d6aff57 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/test_canonical_constraint.py @@ -0,0 +1,296 @@ +import numpy as np +from numpy.testing import assert_array_equal, assert_equal +from scipy.optimize._constraints import (NonlinearConstraint, Bounds, + PreparedConstraint) +from scipy.optimize._trustregion_constr.canonical_constraint \ + import CanonicalConstraint, initial_constraints_as_canonical + + +def create_quadratic_function(n, m, rng): + a = rng.rand(m) + A = rng.rand(m, n) + H = rng.rand(m, n, n) + HT = np.transpose(H, (1, 2, 0)) + + def fun(x): + return a + A.dot(x) + 0.5 * H.dot(x).dot(x) + + def jac(x): + return A + H.dot(x) + + def hess(x, v): + return HT.dot(v) + + return fun, jac, hess + + +def test_bounds_cases(): + # Test 1: no constraints. + user_constraint = Bounds(-np.inf, np.inf) + x0 = np.array([-1, 2]) + prepared_constraint = PreparedConstraint(user_constraint, x0, False) + c = CanonicalConstraint.from_PreparedConstraint(prepared_constraint) + + assert_equal(c.n_eq, 0) + assert_equal(c.n_ineq, 0) + + c_eq, c_ineq = c.fun(x0) + assert_array_equal(c_eq, []) + assert_array_equal(c_ineq, []) + + J_eq, J_ineq = c.jac(x0) + assert_array_equal(J_eq, np.empty((0, 2))) + assert_array_equal(J_ineq, np.empty((0, 2))) + + assert_array_equal(c.keep_feasible, []) + + # Test 2: infinite lower bound. + user_constraint = Bounds(-np.inf, [0, np.inf, 1], [False, True, True]) + x0 = np.array([-1, -2, -3], dtype=float) + prepared_constraint = PreparedConstraint(user_constraint, x0, False) + c = CanonicalConstraint.from_PreparedConstraint(prepared_constraint) + + assert_equal(c.n_eq, 0) + assert_equal(c.n_ineq, 2) + + c_eq, c_ineq = c.fun(x0) + assert_array_equal(c_eq, []) + assert_array_equal(c_ineq, [-1, -4]) + + J_eq, J_ineq = c.jac(x0) + assert_array_equal(J_eq, np.empty((0, 3))) + assert_array_equal(J_ineq, np.array([[1, 0, 0], [0, 0, 1]])) + + assert_array_equal(c.keep_feasible, [False, True]) + + # Test 3: infinite upper bound. + user_constraint = Bounds([0, 1, -np.inf], np.inf, [True, False, True]) + x0 = np.array([1, 2, 3], dtype=float) + prepared_constraint = PreparedConstraint(user_constraint, x0, False) + c = CanonicalConstraint.from_PreparedConstraint(prepared_constraint) + + assert_equal(c.n_eq, 0) + assert_equal(c.n_ineq, 2) + + c_eq, c_ineq = c.fun(x0) + assert_array_equal(c_eq, []) + assert_array_equal(c_ineq, [-1, -1]) + + J_eq, J_ineq = c.jac(x0) + assert_array_equal(J_eq, np.empty((0, 3))) + assert_array_equal(J_ineq, np.array([[-1, 0, 0], [0, -1, 0]])) + + assert_array_equal(c.keep_feasible, [True, False]) + + # Test 4: interval constraint. + user_constraint = Bounds([-1, -np.inf, 2, 3], [1, np.inf, 10, 3], + [False, True, True, True]) + x0 = np.array([0, 10, 8, 5]) + prepared_constraint = PreparedConstraint(user_constraint, x0, False) + c = CanonicalConstraint.from_PreparedConstraint(prepared_constraint) + + assert_equal(c.n_eq, 1) + assert_equal(c.n_ineq, 4) + + c_eq, c_ineq = c.fun(x0) + assert_array_equal(c_eq, [2]) + assert_array_equal(c_ineq, [-1, -2, -1, -6]) + + J_eq, J_ineq = c.jac(x0) + assert_array_equal(J_eq, [[0, 0, 0, 1]]) + assert_array_equal(J_ineq, [[1, 0, 0, 0], + [0, 0, 1, 0], + [-1, 0, 0, 0], + [0, 0, -1, 0]]) + + assert_array_equal(c.keep_feasible, [False, True, False, True]) + + +def test_nonlinear_constraint(): + n = 3 + m = 5 + rng = np.random.RandomState(0) + x0 = rng.rand(n) + + fun, jac, hess = create_quadratic_function(n, m, rng) + f = fun(x0) + J = jac(x0) + + lb = [-10, 3, -np.inf, -np.inf, -5] + ub = [10, 3, np.inf, 3, np.inf] + user_constraint = NonlinearConstraint( + fun, lb, ub, jac, hess, [True, False, False, True, False]) + + for sparse_jacobian in [False, True]: + prepared_constraint = PreparedConstraint(user_constraint, x0, + sparse_jacobian) + c = CanonicalConstraint.from_PreparedConstraint(prepared_constraint) + + assert_array_equal(c.n_eq, 1) + assert_array_equal(c.n_ineq, 4) + + c_eq, c_ineq = c.fun(x0) + assert_array_equal(c_eq, [f[1] - lb[1]]) + assert_array_equal(c_ineq, [f[3] - ub[3], lb[4] - f[4], + f[0] - ub[0], lb[0] - f[0]]) + + J_eq, J_ineq = c.jac(x0) + if sparse_jacobian: + J_eq = J_eq.toarray() + J_ineq = J_ineq.toarray() + + assert_array_equal(J_eq, J[1, None]) + assert_array_equal(J_ineq, np.vstack((J[3], -J[4], J[0], -J[0]))) + + v_eq = rng.rand(c.n_eq) + v_ineq = rng.rand(c.n_ineq) + v = np.zeros(m) + v[1] = v_eq[0] + v[3] = v_ineq[0] + v[4] = -v_ineq[1] + v[0] = v_ineq[2] - v_ineq[3] + assert_array_equal(c.hess(x0, v_eq, v_ineq), hess(x0, v)) + + assert_array_equal(c.keep_feasible, [True, False, True, True]) + + +def test_concatenation(): + rng = np.random.RandomState(0) + n = 4 + x0 = rng.rand(n) + + f1 = x0 + J1 = np.eye(n) + lb1 = [-1, -np.inf, -2, 3] + ub1 = [1, np.inf, np.inf, 3] + bounds = Bounds(lb1, ub1, [False, False, True, False]) + + fun, jac, hess = create_quadratic_function(n, 5, rng) + f2 = fun(x0) + J2 = jac(x0) + lb2 = [-10, 3, -np.inf, -np.inf, -5] + ub2 = [10, 3, np.inf, 5, np.inf] + nonlinear = NonlinearConstraint( + fun, lb2, ub2, jac, hess, [True, False, False, True, False]) + + for sparse_jacobian in [False, True]: + bounds_prepared = PreparedConstraint(bounds, x0, sparse_jacobian) + nonlinear_prepared = PreparedConstraint(nonlinear, x0, sparse_jacobian) + + c1 = CanonicalConstraint.from_PreparedConstraint(bounds_prepared) + c2 = CanonicalConstraint.from_PreparedConstraint(nonlinear_prepared) + c = CanonicalConstraint.concatenate([c1, c2], sparse_jacobian) + + assert_equal(c.n_eq, 2) + assert_equal(c.n_ineq, 7) + + c_eq, c_ineq = c.fun(x0) + assert_array_equal(c_eq, [f1[3] - lb1[3], f2[1] - lb2[1]]) + assert_array_equal(c_ineq, [lb1[2] - f1[2], f1[0] - ub1[0], + lb1[0] - f1[0], f2[3] - ub2[3], + lb2[4] - f2[4], f2[0] - ub2[0], + lb2[0] - f2[0]]) + + J_eq, J_ineq = c.jac(x0) + if sparse_jacobian: + J_eq = J_eq.toarray() + J_ineq = J_ineq.toarray() + + assert_array_equal(J_eq, np.vstack((J1[3], J2[1]))) + assert_array_equal(J_ineq, np.vstack((-J1[2], J1[0], -J1[0], J2[3], + -J2[4], J2[0], -J2[0]))) + + v_eq = rng.rand(c.n_eq) + v_ineq = rng.rand(c.n_ineq) + v = np.zeros(5) + v[1] = v_eq[1] + v[3] = v_ineq[3] + v[4] = -v_ineq[4] + v[0] = v_ineq[5] - v_ineq[6] + H = c.hess(x0, v_eq, v_ineq).dot(np.eye(n)) + assert_array_equal(H, hess(x0, v)) + + assert_array_equal(c.keep_feasible, + [True, False, False, True, False, True, True]) + + +def test_empty(): + x = np.array([1, 2, 3]) + c = CanonicalConstraint.empty(3) + assert_equal(c.n_eq, 0) + assert_equal(c.n_ineq, 0) + + c_eq, c_ineq = c.fun(x) + assert_array_equal(c_eq, []) + assert_array_equal(c_ineq, []) + + J_eq, J_ineq = c.jac(x) + assert_array_equal(J_eq, np.empty((0, 3))) + assert_array_equal(J_ineq, np.empty((0, 3))) + + H = c.hess(x, None, None).toarray() + assert_array_equal(H, np.zeros((3, 3))) + + +def test_initial_constraints_as_canonical(): + # rng is only used to generate the coefficients of the quadratic + # function that is used by the nonlinear constraint. + rng = np.random.RandomState(0) + + x0 = np.array([0.5, 0.4, 0.3, 0.2]) + n = len(x0) + + lb1 = [-1, -np.inf, -2, 3] + ub1 = [1, np.inf, np.inf, 3] + bounds = Bounds(lb1, ub1, [False, False, True, False]) + + fun, jac, hess = create_quadratic_function(n, 5, rng) + lb2 = [-10, 3, -np.inf, -np.inf, -5] + ub2 = [10, 3, np.inf, 5, np.inf] + nonlinear = NonlinearConstraint( + fun, lb2, ub2, jac, hess, [True, False, False, True, False]) + + for sparse_jacobian in [False, True]: + bounds_prepared = PreparedConstraint(bounds, x0, sparse_jacobian) + nonlinear_prepared = PreparedConstraint(nonlinear, x0, sparse_jacobian) + + f1 = bounds_prepared.fun.f + J1 = bounds_prepared.fun.J + f2 = nonlinear_prepared.fun.f + J2 = nonlinear_prepared.fun.J + + c_eq, c_ineq, J_eq, J_ineq = initial_constraints_as_canonical( + n, [bounds_prepared, nonlinear_prepared], sparse_jacobian) + + assert_array_equal(c_eq, [f1[3] - lb1[3], f2[1] - lb2[1]]) + assert_array_equal(c_ineq, [lb1[2] - f1[2], f1[0] - ub1[0], + lb1[0] - f1[0], f2[3] - ub2[3], + lb2[4] - f2[4], f2[0] - ub2[0], + lb2[0] - f2[0]]) + + if sparse_jacobian: + J1 = J1.toarray() + J2 = J2.toarray() + J_eq = J_eq.toarray() + J_ineq = J_ineq.toarray() + + assert_array_equal(J_eq, np.vstack((J1[3], J2[1]))) + assert_array_equal(J_ineq, np.vstack((-J1[2], J1[0], -J1[0], J2[3], + -J2[4], J2[0], -J2[0]))) + + +def test_initial_constraints_as_canonical_empty(): + n = 3 + for sparse_jacobian in [False, True]: + c_eq, c_ineq, J_eq, J_ineq = initial_constraints_as_canonical( + n, [], sparse_jacobian) + + assert_array_equal(c_eq, []) + assert_array_equal(c_ineq, []) + + if sparse_jacobian: + J_eq = J_eq.toarray() + J_ineq = J_ineq.toarray() + + assert_array_equal(J_eq, np.empty((0, n))) + assert_array_equal(J_ineq, np.empty((0, n))) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/test_nested_minimize.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/test_nested_minimize.py new file mode 100644 index 0000000000000000000000000000000000000000..f9aa57058c6523d4106b26840ef447431d615cd6 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/test_nested_minimize.py @@ -0,0 +1,39 @@ +import pytest +import numpy as np +from scipy.optimize import minimize, NonlinearConstraint, rosen, rosen_der + + +# Ignore this warning about inefficient use of Hessians +# The bug only shows up with the default HUS +@pytest.mark.filterwarnings( + "ignore:delta_grad == 0.0. Check if the approximated function is linear." +) +def test_gh21193(): + # Test that nested minimization does not share Hessian objects + def identity(x): + return x[0] + def identity_jac(x): + a = np.zeros(len(x)) + a[0] = 1 + return a + constraint1 = NonlinearConstraint(identity, 0, 0, identity_jac) + constraint2 = NonlinearConstraint(identity, 0, 0, identity_jac) + + # The default HUS for each should be distinct + assert constraint1.hess is not constraint2.hess + + _ = minimize( + lambda x: minimize( + rosen, + x[1:], + jac=rosen_der, + constraints=constraint1, + method="trust-constr", + options={'maxiter': 2}, + ).fun, + [1, 0, 0], + constraints=constraint2, + method="trust-constr", + options={'maxiter': 2}, + ) + # This test doesn't check that the output is correct, just that it doesn't crash diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/test_projections.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/test_projections.py new file mode 100644 index 0000000000000000000000000000000000000000..6ff3c39d649d0ac663d9b71bb906f1daac021118 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/test_projections.py @@ -0,0 +1,214 @@ +import numpy as np +import scipy.linalg +from scipy.sparse import csc_matrix +from scipy.optimize._trustregion_constr.projections \ + import projections, orthogonality +from numpy.testing import (TestCase, assert_array_almost_equal, + assert_equal, assert_allclose) + +try: + from sksparse.cholmod import cholesky_AAt # noqa: F401 + sksparse_available = True + available_sparse_methods = ("NormalEquation", "AugmentedSystem") +except ImportError: + sksparse_available = False + available_sparse_methods = ("AugmentedSystem",) +available_dense_methods = ('QRFactorization', 'SVDFactorization') + + +class TestProjections(TestCase): + + def test_nullspace_and_least_squares_sparse(self): + A_dense = np.array([[1, 2, 3, 4, 0, 5, 0, 7], + [0, 8, 7, 0, 1, 5, 9, 0], + [1, 0, 0, 0, 0, 1, 2, 3]]) + At_dense = A_dense.T + A = csc_matrix(A_dense) + test_points = ([1, 2, 3, 4, 5, 6, 7, 8], + [1, 10, 3, 0, 1, 6, 7, 8], + [1.12, 10, 0, 0, 100000, 6, 0.7, 8]) + + for method in available_sparse_methods: + Z, LS, _ = projections(A, method) + for z in test_points: + # Test if x is in the null_space + x = Z.matvec(z) + assert_array_almost_equal(A.dot(x), 0) + # Test orthogonality + assert_array_almost_equal(orthogonality(A, x), 0) + # Test if x is the least square solution + x = LS.matvec(z) + x2 = scipy.linalg.lstsq(At_dense, z)[0] + assert_array_almost_equal(x, x2) + + def test_iterative_refinements_sparse(self): + A_dense = np.array([[1, 2, 3, 4, 0, 5, 0, 7], + [0, 8, 7, 0, 1, 5, 9, 0], + [1, 0, 0, 0, 0, 1, 2, 3]]) + A = csc_matrix(A_dense) + test_points = ([1, 2, 3, 4, 5, 6, 7, 8], + [1, 10, 3, 0, 1, 6, 7, 8], + [1.12, 10, 0, 0, 100000, 6, 0.7, 8], + [1, 0, 0, 0, 0, 1, 2, 3+1e-10]) + + for method in available_sparse_methods: + Z, LS, _ = projections(A, method, orth_tol=1e-18, max_refin=100) + for z in test_points: + # Test if x is in the null_space + x = Z.matvec(z) + atol = 1e-13 * abs(x).max() + assert_allclose(A.dot(x), 0, atol=atol) + # Test orthogonality + assert_allclose(orthogonality(A, x), 0, atol=1e-13) + + def test_rowspace_sparse(self): + A_dense = np.array([[1, 2, 3, 4, 0, 5, 0, 7], + [0, 8, 7, 0, 1, 5, 9, 0], + [1, 0, 0, 0, 0, 1, 2, 3]]) + A = csc_matrix(A_dense) + test_points = ([1, 2, 3], + [1, 10, 3], + [1.12, 10, 0]) + + for method in available_sparse_methods: + _, _, Y = projections(A, method) + for z in test_points: + # Test if x is solution of A x = z + x = Y.matvec(z) + assert_array_almost_equal(A.dot(x), z) + # Test if x is in the return row space of A + A_ext = np.vstack((A_dense, x)) + assert_equal(np.linalg.matrix_rank(A_dense), + np.linalg.matrix_rank(A_ext)) + + def test_nullspace_and_least_squares_dense(self): + A = np.array([[1, 2, 3, 4, 0, 5, 0, 7], + [0, 8, 7, 0, 1, 5, 9, 0], + [1, 0, 0, 0, 0, 1, 2, 3]]) + At = A.T + test_points = ([1, 2, 3, 4, 5, 6, 7, 8], + [1, 10, 3, 0, 1, 6, 7, 8], + [1.12, 10, 0, 0, 100000, 6, 0.7, 8]) + + for method in available_dense_methods: + Z, LS, _ = projections(A, method) + for z in test_points: + # Test if x is in the null_space + x = Z.matvec(z) + assert_array_almost_equal(A.dot(x), 0) + # Test orthogonality + assert_array_almost_equal(orthogonality(A, x), 0) + # Test if x is the least square solution + x = LS.matvec(z) + x2 = scipy.linalg.lstsq(At, z)[0] + assert_array_almost_equal(x, x2) + + def test_compare_dense_and_sparse(self): + D = np.diag(range(1, 101)) + A = np.hstack([D, D, D, D]) + A_sparse = csc_matrix(A) + np.random.seed(0) + + Z, LS, Y = projections(A) + Z_sparse, LS_sparse, Y_sparse = projections(A_sparse) + for k in range(20): + z = np.random.normal(size=(400,)) + assert_array_almost_equal(Z.dot(z), Z_sparse.dot(z)) + assert_array_almost_equal(LS.dot(z), LS_sparse.dot(z)) + x = np.random.normal(size=(100,)) + assert_array_almost_equal(Y.dot(x), Y_sparse.dot(x)) + + def test_compare_dense_and_sparse2(self): + D1 = np.diag([-1.7, 1, 0.5]) + D2 = np.diag([1, -0.6, -0.3]) + D3 = np.diag([-0.3, -1.5, 2]) + A = np.hstack([D1, D2, D3]) + A_sparse = csc_matrix(A) + np.random.seed(0) + + Z, LS, Y = projections(A) + Z_sparse, LS_sparse, Y_sparse = projections(A_sparse) + for k in range(1): + z = np.random.normal(size=(9,)) + assert_array_almost_equal(Z.dot(z), Z_sparse.dot(z)) + assert_array_almost_equal(LS.dot(z), LS_sparse.dot(z)) + x = np.random.normal(size=(3,)) + assert_array_almost_equal(Y.dot(x), Y_sparse.dot(x)) + + def test_iterative_refinements_dense(self): + A = np.array([[1, 2, 3, 4, 0, 5, 0, 7], + [0, 8, 7, 0, 1, 5, 9, 0], + [1, 0, 0, 0, 0, 1, 2, 3]]) + test_points = ([1, 2, 3, 4, 5, 6, 7, 8], + [1, 10, 3, 0, 1, 6, 7, 8], + [1, 0, 0, 0, 0, 1, 2, 3+1e-10]) + + for method in available_dense_methods: + Z, LS, _ = projections(A, method, orth_tol=1e-18, max_refin=10) + for z in test_points: + # Test if x is in the null_space + x = Z.matvec(z) + assert_allclose(A.dot(x), 0, rtol=0, atol=2.5e-14) + # Test orthogonality + assert_allclose(orthogonality(A, x), 0, rtol=0, atol=5e-16) + + def test_rowspace_dense(self): + A = np.array([[1, 2, 3, 4, 0, 5, 0, 7], + [0, 8, 7, 0, 1, 5, 9, 0], + [1, 0, 0, 0, 0, 1, 2, 3]]) + test_points = ([1, 2, 3], + [1, 10, 3], + [1.12, 10, 0]) + + for method in available_dense_methods: + _, _, Y = projections(A, method) + for z in test_points: + # Test if x is solution of A x = z + x = Y.matvec(z) + assert_array_almost_equal(A.dot(x), z) + # Test if x is in the return row space of A + A_ext = np.vstack((A, x)) + assert_equal(np.linalg.matrix_rank(A), + np.linalg.matrix_rank(A_ext)) + + +class TestOrthogonality(TestCase): + + def test_dense_matrix(self): + A = np.array([[1, 2, 3, 4, 0, 5, 0, 7], + [0, 8, 7, 0, 1, 5, 9, 0], + [1, 0, 0, 0, 0, 1, 2, 3]]) + test_vectors = ([-1.98931144, -1.56363389, + -0.84115584, 2.2864762, + 5.599141, 0.09286976, + 1.37040802, -0.28145812], + [697.92794044, -4091.65114008, + -3327.42316335, 836.86906951, + 99434.98929065, -1285.37653682, + -4109.21503806, 2935.29289083]) + test_expected_orth = (0, 0) + + for i in range(len(test_vectors)): + x = test_vectors[i] + orth = test_expected_orth[i] + assert_array_almost_equal(orthogonality(A, x), orth) + + def test_sparse_matrix(self): + A = np.array([[1, 2, 3, 4, 0, 5, 0, 7], + [0, 8, 7, 0, 1, 5, 9, 0], + [1, 0, 0, 0, 0, 1, 2, 3]]) + A = csc_matrix(A) + test_vectors = ([-1.98931144, -1.56363389, + -0.84115584, 2.2864762, + 5.599141, 0.09286976, + 1.37040802, -0.28145812], + [697.92794044, -4091.65114008, + -3327.42316335, 836.86906951, + 99434.98929065, -1285.37653682, + -4109.21503806, 2935.29289083]) + test_expected_orth = (0, 0) + + for i in range(len(test_vectors)): + x = test_vectors[i] + orth = test_expected_orth[i] + assert_array_almost_equal(orthogonality(A, x), orth) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/test_qp_subproblem.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/test_qp_subproblem.py new file mode 100644 index 0000000000000000000000000000000000000000..70e65e53b9d2389541c0aab45b94b1d30dcdd146 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/test_qp_subproblem.py @@ -0,0 +1,645 @@ +import numpy as np +from scipy.sparse import csc_matrix +from scipy.optimize._trustregion_constr.qp_subproblem \ + import (eqp_kktfact, + projected_cg, + box_intersections, + sphere_intersections, + box_sphere_intersections, + modified_dogleg) +from scipy.optimize._trustregion_constr.projections \ + import projections +from numpy.testing import TestCase, assert_array_almost_equal, assert_equal +import pytest + + +class TestEQPDirectFactorization(TestCase): + + # From Example 16.2 Nocedal/Wright "Numerical + # Optimization" p.452. + def test_nocedal_example(self): + H = csc_matrix([[6, 2, 1], + [2, 5, 2], + [1, 2, 4]]) + A = csc_matrix([[1, 0, 1], + [0, 1, 1]]) + c = np.array([-8, -3, -3]) + b = -np.array([3, 0]) + x, lagrange_multipliers = eqp_kktfact(H, c, A, b) + assert_array_almost_equal(x, [2, -1, 1]) + assert_array_almost_equal(lagrange_multipliers, [3, -2]) + + +class TestSphericalBoundariesIntersections(TestCase): + + def test_2d_sphere_constraints(self): + # Interior initial point + ta, tb, intersect = sphere_intersections([0, 0], + [1, 0], 0.5) + assert_array_almost_equal([ta, tb], [0, 0.5]) + assert_equal(intersect, True) + + # No intersection between line and circle + ta, tb, intersect = sphere_intersections([2, 0], + [0, 1], 1) + assert_equal(intersect, False) + + # Outside initial point pointing toward outside the circle + ta, tb, intersect = sphere_intersections([2, 0], + [1, 0], 1) + assert_equal(intersect, False) + + # Outside initial point pointing toward inside the circle + ta, tb, intersect = sphere_intersections([2, 0], + [-1, 0], 1.5) + assert_array_almost_equal([ta, tb], [0.5, 1]) + assert_equal(intersect, True) + + # Initial point on the boundary + ta, tb, intersect = sphere_intersections([2, 0], + [1, 0], 2) + assert_array_almost_equal([ta, tb], [0, 0]) + assert_equal(intersect, True) + + def test_2d_sphere_constraints_line_intersections(self): + # Interior initial point + ta, tb, intersect = sphere_intersections([0, 0], + [1, 0], 0.5, + entire_line=True) + assert_array_almost_equal([ta, tb], [-0.5, 0.5]) + assert_equal(intersect, True) + + # No intersection between line and circle + ta, tb, intersect = sphere_intersections([2, 0], + [0, 1], 1, + entire_line=True) + assert_equal(intersect, False) + + # Outside initial point pointing toward outside the circle + ta, tb, intersect = sphere_intersections([2, 0], + [1, 0], 1, + entire_line=True) + assert_array_almost_equal([ta, tb], [-3, -1]) + assert_equal(intersect, True) + + # Outside initial point pointing toward inside the circle + ta, tb, intersect = sphere_intersections([2, 0], + [-1, 0], 1.5, + entire_line=True) + assert_array_almost_equal([ta, tb], [0.5, 3.5]) + assert_equal(intersect, True) + + # Initial point on the boundary + ta, tb, intersect = sphere_intersections([2, 0], + [1, 0], 2, + entire_line=True) + assert_array_almost_equal([ta, tb], [-4, 0]) + assert_equal(intersect, True) + + +class TestBoxBoundariesIntersections(TestCase): + + def test_2d_box_constraints(self): + # Box constraint in the direction of vector d + ta, tb, intersect = box_intersections([2, 0], [0, 2], + [1, 1], [3, 3]) + assert_array_almost_equal([ta, tb], [0.5, 1]) + assert_equal(intersect, True) + + # Negative direction + ta, tb, intersect = box_intersections([2, 0], [0, 2], + [1, -3], [3, -1]) + assert_equal(intersect, False) + + # Some constraints are absent (set to +/- inf) + ta, tb, intersect = box_intersections([2, 0], [0, 2], + [-np.inf, 1], + [np.inf, np.inf]) + assert_array_almost_equal([ta, tb], [0.5, 1]) + assert_equal(intersect, True) + + # Intersect on the face of the box + ta, tb, intersect = box_intersections([1, 0], [0, 1], + [1, 1], [3, 3]) + assert_array_almost_equal([ta, tb], [1, 1]) + assert_equal(intersect, True) + + # Interior initial point + ta, tb, intersect = box_intersections([0, 0], [4, 4], + [-2, -3], [3, 2]) + assert_array_almost_equal([ta, tb], [0, 0.5]) + assert_equal(intersect, True) + + # No intersection between line and box constraints + ta, tb, intersect = box_intersections([2, 0], [0, 2], + [-3, -3], [-1, -1]) + assert_equal(intersect, False) + ta, tb, intersect = box_intersections([2, 0], [0, 2], + [-3, 3], [-1, 1]) + assert_equal(intersect, False) + ta, tb, intersect = box_intersections([2, 0], [0, 2], + [-3, -np.inf], + [-1, np.inf]) + assert_equal(intersect, False) + ta, tb, intersect = box_intersections([0, 0], [1, 100], + [1, 1], [3, 3]) + assert_equal(intersect, False) + ta, tb, intersect = box_intersections([0.99, 0], [0, 2], + [1, 1], [3, 3]) + assert_equal(intersect, False) + + # Initial point on the boundary + ta, tb, intersect = box_intersections([2, 2], [0, 1], + [-2, -2], [2, 2]) + assert_array_almost_equal([ta, tb], [0, 0]) + assert_equal(intersect, True) + + def test_2d_box_constraints_entire_line(self): + # Box constraint in the direction of vector d + ta, tb, intersect = box_intersections([2, 0], [0, 2], + [1, 1], [3, 3], + entire_line=True) + assert_array_almost_equal([ta, tb], [0.5, 1.5]) + assert_equal(intersect, True) + + # Negative direction + ta, tb, intersect = box_intersections([2, 0], [0, 2], + [1, -3], [3, -1], + entire_line=True) + assert_array_almost_equal([ta, tb], [-1.5, -0.5]) + assert_equal(intersect, True) + + # Some constraints are absent (set to +/- inf) + ta, tb, intersect = box_intersections([2, 0], [0, 2], + [-np.inf, 1], + [np.inf, np.inf], + entire_line=True) + assert_array_almost_equal([ta, tb], [0.5, np.inf]) + assert_equal(intersect, True) + + # Intersect on the face of the box + ta, tb, intersect = box_intersections([1, 0], [0, 1], + [1, 1], [3, 3], + entire_line=True) + assert_array_almost_equal([ta, tb], [1, 3]) + assert_equal(intersect, True) + + # Interior initial point + ta, tb, intersect = box_intersections([0, 0], [4, 4], + [-2, -3], [3, 2], + entire_line=True) + assert_array_almost_equal([ta, tb], [-0.5, 0.5]) + assert_equal(intersect, True) + + # No intersection between line and box constraints + ta, tb, intersect = box_intersections([2, 0], [0, 2], + [-3, -3], [-1, -1], + entire_line=True) + assert_equal(intersect, False) + ta, tb, intersect = box_intersections([2, 0], [0, 2], + [-3, 3], [-1, 1], + entire_line=True) + assert_equal(intersect, False) + ta, tb, intersect = box_intersections([2, 0], [0, 2], + [-3, -np.inf], + [-1, np.inf], + entire_line=True) + assert_equal(intersect, False) + ta, tb, intersect = box_intersections([0, 0], [1, 100], + [1, 1], [3, 3], + entire_line=True) + assert_equal(intersect, False) + ta, tb, intersect = box_intersections([0.99, 0], [0, 2], + [1, 1], [3, 3], + entire_line=True) + assert_equal(intersect, False) + + # Initial point on the boundary + ta, tb, intersect = box_intersections([2, 2], [0, 1], + [-2, -2], [2, 2], + entire_line=True) + assert_array_almost_equal([ta, tb], [-4, 0]) + assert_equal(intersect, True) + + def test_3d_box_constraints(self): + # Simple case + ta, tb, intersect = box_intersections([1, 1, 0], [0, 0, 1], + [1, 1, 1], [3, 3, 3]) + assert_array_almost_equal([ta, tb], [1, 1]) + assert_equal(intersect, True) + + # Negative direction + ta, tb, intersect = box_intersections([1, 1, 0], [0, 0, -1], + [1, 1, 1], [3, 3, 3]) + assert_equal(intersect, False) + + # Interior point + ta, tb, intersect = box_intersections([2, 2, 2], [0, -1, 1], + [1, 1, 1], [3, 3, 3]) + assert_array_almost_equal([ta, tb], [0, 1]) + assert_equal(intersect, True) + + def test_3d_box_constraints_entire_line(self): + # Simple case + ta, tb, intersect = box_intersections([1, 1, 0], [0, 0, 1], + [1, 1, 1], [3, 3, 3], + entire_line=True) + assert_array_almost_equal([ta, tb], [1, 3]) + assert_equal(intersect, True) + + # Negative direction + ta, tb, intersect = box_intersections([1, 1, 0], [0, 0, -1], + [1, 1, 1], [3, 3, 3], + entire_line=True) + assert_array_almost_equal([ta, tb], [-3, -1]) + assert_equal(intersect, True) + + # Interior point + ta, tb, intersect = box_intersections([2, 2, 2], [0, -1, 1], + [1, 1, 1], [3, 3, 3], + entire_line=True) + assert_array_almost_equal([ta, tb], [-1, 1]) + assert_equal(intersect, True) + + +class TestBoxSphereBoundariesIntersections(TestCase): + + def test_2d_box_constraints(self): + # Both constraints are active + ta, tb, intersect = box_sphere_intersections([1, 1], [-2, 2], + [-1, -2], [1, 2], 2, + entire_line=False) + assert_array_almost_equal([ta, tb], [0, 0.5]) + assert_equal(intersect, True) + + # None of the constraints are active + ta, tb, intersect = box_sphere_intersections([1, 1], [-1, 1], + [-1, -3], [1, 3], 10, + entire_line=False) + assert_array_almost_equal([ta, tb], [0, 1]) + assert_equal(intersect, True) + + # Box constraints are active + ta, tb, intersect = box_sphere_intersections([1, 1], [-4, 4], + [-1, -3], [1, 3], 10, + entire_line=False) + assert_array_almost_equal([ta, tb], [0, 0.5]) + assert_equal(intersect, True) + + # Spherical constraints are active + ta, tb, intersect = box_sphere_intersections([1, 1], [-4, 4], + [-1, -3], [1, 3], 2, + entire_line=False) + assert_array_almost_equal([ta, tb], [0, 0.25]) + assert_equal(intersect, True) + + # Infeasible problems + ta, tb, intersect = box_sphere_intersections([2, 2], [-4, 4], + [-1, -3], [1, 3], 2, + entire_line=False) + assert_equal(intersect, False) + ta, tb, intersect = box_sphere_intersections([1, 1], [-4, 4], + [2, 4], [2, 4], 2, + entire_line=False) + assert_equal(intersect, False) + + def test_2d_box_constraints_entire_line(self): + # Both constraints are active + ta, tb, intersect = box_sphere_intersections([1, 1], [-2, 2], + [-1, -2], [1, 2], 2, + entire_line=True) + assert_array_almost_equal([ta, tb], [0, 0.5]) + assert_equal(intersect, True) + + # None of the constraints are active + ta, tb, intersect = box_sphere_intersections([1, 1], [-1, 1], + [-1, -3], [1, 3], 10, + entire_line=True) + assert_array_almost_equal([ta, tb], [0, 2]) + assert_equal(intersect, True) + + # Box constraints are active + ta, tb, intersect = box_sphere_intersections([1, 1], [-4, 4], + [-1, -3], [1, 3], 10, + entire_line=True) + assert_array_almost_equal([ta, tb], [0, 0.5]) + assert_equal(intersect, True) + + # Spherical constraints are active + ta, tb, intersect = box_sphere_intersections([1, 1], [-4, 4], + [-1, -3], [1, 3], 2, + entire_line=True) + assert_array_almost_equal([ta, tb], [0, 0.25]) + assert_equal(intersect, True) + + # Infeasible problems + ta, tb, intersect = box_sphere_intersections([2, 2], [-4, 4], + [-1, -3], [1, 3], 2, + entire_line=True) + assert_equal(intersect, False) + ta, tb, intersect = box_sphere_intersections([1, 1], [-4, 4], + [2, 4], [2, 4], 2, + entire_line=True) + assert_equal(intersect, False) + + +class TestModifiedDogleg(TestCase): + + def test_cauchypoint_equalsto_newtonpoint(self): + A = np.array([[1, 8]]) + b = np.array([-16]) + _, _, Y = projections(A) + newton_point = np.array([0.24615385, 1.96923077]) + + # Newton point inside boundaries + x = modified_dogleg(A, Y, b, 2, [-np.inf, -np.inf], [np.inf, np.inf]) + assert_array_almost_equal(x, newton_point) + + # Spherical constraint active + x = modified_dogleg(A, Y, b, 1, [-np.inf, -np.inf], [np.inf, np.inf]) + assert_array_almost_equal(x, newton_point/np.linalg.norm(newton_point)) + + # Box constraints active + x = modified_dogleg(A, Y, b, 2, [-np.inf, -np.inf], [0.1, np.inf]) + assert_array_almost_equal(x, (newton_point/newton_point[0]) * 0.1) + + def test_3d_example(self): + A = np.array([[1, 8, 1], + [4, 2, 2]]) + b = np.array([-16, 2]) + Z, LS, Y = projections(A) + + newton_point = np.array([-1.37090909, 2.23272727, -0.49090909]) + cauchy_point = np.array([0.11165723, 1.73068711, 0.16748585]) + origin = np.zeros_like(newton_point) + + # newton_point inside boundaries + x = modified_dogleg(A, Y, b, 3, [-np.inf, -np.inf, -np.inf], + [np.inf, np.inf, np.inf]) + assert_array_almost_equal(x, newton_point) + + # line between cauchy_point and newton_point contains best point + # (spherical constraint is active). + x = modified_dogleg(A, Y, b, 2, [-np.inf, -np.inf, -np.inf], + [np.inf, np.inf, np.inf]) + z = cauchy_point + d = newton_point-cauchy_point + t = ((x-z)/(d)) + assert_array_almost_equal(t, np.full(3, 0.40807330)) + assert_array_almost_equal(np.linalg.norm(x), 2) + + # line between cauchy_point and newton_point contains best point + # (box constraint is active). + x = modified_dogleg(A, Y, b, 5, [-1, -np.inf, -np.inf], + [np.inf, np.inf, np.inf]) + z = cauchy_point + d = newton_point-cauchy_point + t = ((x-z)/(d)) + assert_array_almost_equal(t, np.full(3, 0.7498195)) + assert_array_almost_equal(x[0], -1) + + # line between origin and cauchy_point contains best point + # (spherical constraint is active). + x = modified_dogleg(A, Y, b, 1, [-np.inf, -np.inf, -np.inf], + [np.inf, np.inf, np.inf]) + z = origin + d = cauchy_point + t = ((x-z)/(d)) + assert_array_almost_equal(t, np.full(3, 0.573936265)) + assert_array_almost_equal(np.linalg.norm(x), 1) + + # line between origin and newton_point contains best point + # (box constraint is active). + x = modified_dogleg(A, Y, b, 2, [-np.inf, -np.inf, -np.inf], + [np.inf, 1, np.inf]) + z = origin + d = newton_point + t = ((x-z)/(d)) + assert_array_almost_equal(t, np.full(3, 0.4478827364)) + assert_array_almost_equal(x[1], 1) + + +class TestProjectCG(TestCase): + + # From Example 16.2 Nocedal/Wright "Numerical + # Optimization" p.452. + def test_nocedal_example(self): + H = csc_matrix([[6, 2, 1], + [2, 5, 2], + [1, 2, 4]]) + A = csc_matrix([[1, 0, 1], + [0, 1, 1]]) + c = np.array([-8, -3, -3]) + b = -np.array([3, 0]) + Z, _, Y = projections(A) + x, info = projected_cg(H, c, Z, Y, b) + assert_equal(info["stop_cond"], 4) + assert_equal(info["hits_boundary"], False) + assert_array_almost_equal(x, [2, -1, 1]) + + def test_compare_with_direct_fact(self): + H = csc_matrix([[6, 2, 1, 3], + [2, 5, 2, 4], + [1, 2, 4, 5], + [3, 4, 5, 7]]) + A = csc_matrix([[1, 0, 1, 0], + [0, 1, 1, 1]]) + c = np.array([-2, -3, -3, 1]) + b = -np.array([3, 0]) + Z, _, Y = projections(A) + x, info = projected_cg(H, c, Z, Y, b, tol=0) + x_kkt, _ = eqp_kktfact(H, c, A, b) + assert_equal(info["stop_cond"], 1) + assert_equal(info["hits_boundary"], False) + assert_array_almost_equal(x, x_kkt) + + def test_trust_region_infeasible(self): + H = csc_matrix([[6, 2, 1, 3], + [2, 5, 2, 4], + [1, 2, 4, 5], + [3, 4, 5, 7]]) + A = csc_matrix([[1, 0, 1, 0], + [0, 1, 1, 1]]) + c = np.array([-2, -3, -3, 1]) + b = -np.array([3, 0]) + trust_radius = 1 + Z, _, Y = projections(A) + with pytest.raises(ValueError): + projected_cg(H, c, Z, Y, b, trust_radius=trust_radius) + + def test_trust_region_barely_feasible(self): + H = csc_matrix([[6, 2, 1, 3], + [2, 5, 2, 4], + [1, 2, 4, 5], + [3, 4, 5, 7]]) + A = csc_matrix([[1, 0, 1, 0], + [0, 1, 1, 1]]) + c = np.array([-2, -3, -3, 1]) + b = -np.array([3, 0]) + trust_radius = 2.32379000772445021283 + Z, _, Y = projections(A) + x, info = projected_cg(H, c, Z, Y, b, + tol=0, + trust_radius=trust_radius) + assert_equal(info["stop_cond"], 2) + assert_equal(info["hits_boundary"], True) + assert_array_almost_equal(np.linalg.norm(x), trust_radius) + assert_array_almost_equal(x, -Y.dot(b)) + + def test_hits_boundary(self): + H = csc_matrix([[6, 2, 1, 3], + [2, 5, 2, 4], + [1, 2, 4, 5], + [3, 4, 5, 7]]) + A = csc_matrix([[1, 0, 1, 0], + [0, 1, 1, 1]]) + c = np.array([-2, -3, -3, 1]) + b = -np.array([3, 0]) + trust_radius = 3 + Z, _, Y = projections(A) + x, info = projected_cg(H, c, Z, Y, b, + tol=0, + trust_radius=trust_radius) + assert_equal(info["stop_cond"], 2) + assert_equal(info["hits_boundary"], True) + assert_array_almost_equal(np.linalg.norm(x), trust_radius) + + def test_negative_curvature_unconstrained(self): + H = csc_matrix([[1, 2, 1, 3], + [2, 0, 2, 4], + [1, 2, 0, 2], + [3, 4, 2, 0]]) + A = csc_matrix([[1, 0, 1, 0], + [0, 1, 0, 1]]) + c = np.array([-2, -3, -3, 1]) + b = -np.array([3, 0]) + Z, _, Y = projections(A) + with pytest.raises(ValueError): + projected_cg(H, c, Z, Y, b, tol=0) + + def test_negative_curvature(self): + H = csc_matrix([[1, 2, 1, 3], + [2, 0, 2, 4], + [1, 2, 0, 2], + [3, 4, 2, 0]]) + A = csc_matrix([[1, 0, 1, 0], + [0, 1, 0, 1]]) + c = np.array([-2, -3, -3, 1]) + b = -np.array([3, 0]) + Z, _, Y = projections(A) + trust_radius = 1000 + x, info = projected_cg(H, c, Z, Y, b, + tol=0, + trust_radius=trust_radius) + assert_equal(info["stop_cond"], 3) + assert_equal(info["hits_boundary"], True) + assert_array_almost_equal(np.linalg.norm(x), trust_radius) + + # The box constraints are inactive at the solution but + # are active during the iterations. + def test_inactive_box_constraints(self): + H = csc_matrix([[6, 2, 1, 3], + [2, 5, 2, 4], + [1, 2, 4, 5], + [3, 4, 5, 7]]) + A = csc_matrix([[1, 0, 1, 0], + [0, 1, 1, 1]]) + c = np.array([-2, -3, -3, 1]) + b = -np.array([3, 0]) + Z, _, Y = projections(A) + x, info = projected_cg(H, c, Z, Y, b, + tol=0, + lb=[0.5, -np.inf, + -np.inf, -np.inf], + return_all=True) + x_kkt, _ = eqp_kktfact(H, c, A, b) + assert_equal(info["stop_cond"], 1) + assert_equal(info["hits_boundary"], False) + assert_array_almost_equal(x, x_kkt) + + # The box constraints active and the termination is + # by maximum iterations (infeasible interaction). + def test_active_box_constraints_maximum_iterations_reached(self): + H = csc_matrix([[6, 2, 1, 3], + [2, 5, 2, 4], + [1, 2, 4, 5], + [3, 4, 5, 7]]) + A = csc_matrix([[1, 0, 1, 0], + [0, 1, 1, 1]]) + c = np.array([-2, -3, -3, 1]) + b = -np.array([3, 0]) + Z, _, Y = projections(A) + x, info = projected_cg(H, c, Z, Y, b, + tol=0, + lb=[0.8, -np.inf, + -np.inf, -np.inf], + return_all=True) + assert_equal(info["stop_cond"], 1) + assert_equal(info["hits_boundary"], True) + assert_array_almost_equal(A.dot(x), -b) + assert_array_almost_equal(x[0], 0.8) + + # The box constraints are active and the termination is + # because it hits boundary (without infeasible interaction). + def test_active_box_constraints_hits_boundaries(self): + H = csc_matrix([[6, 2, 1, 3], + [2, 5, 2, 4], + [1, 2, 4, 5], + [3, 4, 5, 7]]) + A = csc_matrix([[1, 0, 1, 0], + [0, 1, 1, 1]]) + c = np.array([-2, -3, -3, 1]) + b = -np.array([3, 0]) + trust_radius = 3 + Z, _, Y = projections(A) + x, info = projected_cg(H, c, Z, Y, b, + tol=0, + ub=[np.inf, np.inf, 1.6, np.inf], + trust_radius=trust_radius, + return_all=True) + assert_equal(info["stop_cond"], 2) + assert_equal(info["hits_boundary"], True) + assert_array_almost_equal(x[2], 1.6) + + # The box constraints are active and the termination is + # because it hits boundary (infeasible interaction). + def test_active_box_constraints_hits_boundaries_infeasible_iter(self): + H = csc_matrix([[6, 2, 1, 3], + [2, 5, 2, 4], + [1, 2, 4, 5], + [3, 4, 5, 7]]) + A = csc_matrix([[1, 0, 1, 0], + [0, 1, 1, 1]]) + c = np.array([-2, -3, -3, 1]) + b = -np.array([3, 0]) + trust_radius = 4 + Z, _, Y = projections(A) + x, info = projected_cg(H, c, Z, Y, b, + tol=0, + ub=[np.inf, 0.1, np.inf, np.inf], + trust_radius=trust_radius, + return_all=True) + assert_equal(info["stop_cond"], 2) + assert_equal(info["hits_boundary"], True) + assert_array_almost_equal(x[1], 0.1) + + # The box constraints are active and the termination is + # because it hits boundary (no infeasible interaction). + def test_active_box_constraints_negative_curvature(self): + H = csc_matrix([[1, 2, 1, 3], + [2, 0, 2, 4], + [1, 2, 0, 2], + [3, 4, 2, 0]]) + A = csc_matrix([[1, 0, 1, 0], + [0, 1, 0, 1]]) + c = np.array([-2, -3, -3, 1]) + b = -np.array([3, 0]) + Z, _, Y = projections(A) + trust_radius = 1000 + x, info = projected_cg(H, c, Z, Y, b, + tol=0, + ub=[np.inf, np.inf, 100, np.inf], + trust_radius=trust_radius) + assert_equal(info["stop_cond"], 3) + assert_equal(info["hits_boundary"], True) + assert_array_almost_equal(x[2], 100) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/test_report.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/test_report.py new file mode 100644 index 0000000000000000000000000000000000000000..66fa5bd17f80a907db425c927c08e5dc0797028e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/test_report.py @@ -0,0 +1,34 @@ +import pytest +import numpy as np +from scipy.optimize import minimize, Bounds + +def test_gh10880(): + # checks that verbose reporting works with trust-constr for + # bound-constrained problems + bnds = Bounds(1, 2) + opts = {'maxiter': 1000, 'verbose': 2} + minimize(lambda x: x**2, x0=2., method='trust-constr', + bounds=bnds, options=opts) + + opts = {'maxiter': 1000, 'verbose': 3} + minimize(lambda x: x**2, x0=2., method='trust-constr', + bounds=bnds, options=opts) + +@pytest.mark.xslow +def test_gh12922(): + # checks that verbose reporting works with trust-constr for + # general constraints + def objective(x): + return np.array([(np.sum((x+1)**4))]) + + cons = {'type': 'ineq', 'fun': lambda x: -x[0]**2} + n = 25 + x0 = np.linspace(-5, 5, n) + + opts = {'maxiter': 1000, 'verbose': 2} + minimize(objective, x0=x0, method='trust-constr', + constraints=cons, options=opts) + + opts = {'maxiter': 1000, 'verbose': 3} + minimize(objective, x0=x0, method='trust-constr', + constraints=cons, options=opts) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tr_interior_point.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tr_interior_point.py new file mode 100644 index 0000000000000000000000000000000000000000..e14b3f366fba818d9174af97fa91e065bf26e826 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tr_interior_point.py @@ -0,0 +1,361 @@ +"""Trust-region interior point method. + +References +---------- +.. [1] Byrd, Richard H., Mary E. Hribar, and Jorge Nocedal. + "An interior point algorithm for large-scale nonlinear + programming." SIAM Journal on Optimization 9.4 (1999): 877-900. +.. [2] Byrd, Richard H., Guanghui Liu, and Jorge Nocedal. + "On the local behavior of an interior point method for + nonlinear programming." Numerical analysis 1997 (1997): 37-56. +.. [3] Nocedal, Jorge, and Stephen J. Wright. "Numerical optimization" + Second Edition (2006). +""" + +import scipy.sparse as sps +import numpy as np +from .equality_constrained_sqp import equality_constrained_sqp +from scipy.sparse.linalg import LinearOperator + +__all__ = ['tr_interior_point'] + + +class BarrierSubproblem: + """ + Barrier optimization problem: + minimize fun(x) - barrier_parameter*sum(log(s)) + subject to: constr_eq(x) = 0 + constr_ineq(x) + s = 0 + """ + + def __init__(self, x0, s0, fun, grad, lagr_hess, n_vars, n_ineq, n_eq, + constr, jac, barrier_parameter, tolerance, + enforce_feasibility, global_stop_criteria, + xtol, fun0, grad0, constr_ineq0, jac_ineq0, constr_eq0, + jac_eq0, finite_diff_bounds): + # Store parameters + self.n_vars = n_vars + self.x0 = x0 + self.s0 = s0 + self.fun = fun + self.grad = grad + self.lagr_hess = lagr_hess + self.constr = constr + self.jac = jac + self.barrier_parameter = barrier_parameter + self.tolerance = tolerance + self.n_eq = n_eq + self.n_ineq = n_ineq + self.enforce_feasibility = enforce_feasibility + self.global_stop_criteria = global_stop_criteria + self.xtol = xtol + self.fun0 = self._compute_function(fun0, constr_ineq0, s0) + self.grad0 = self._compute_gradient(grad0) + self.constr0 = self._compute_constr(constr_ineq0, constr_eq0, s0) + self.jac0 = self._compute_jacobian(jac_eq0, jac_ineq0, s0) + self.terminate = False + self.lb = finite_diff_bounds[0] + self.ub = finite_diff_bounds[1] + + def update(self, barrier_parameter, tolerance): + self.barrier_parameter = barrier_parameter + self.tolerance = tolerance + + def get_slack(self, z): + return z[self.n_vars:self.n_vars+self.n_ineq] + + def get_variables(self, z): + return z[:self.n_vars] + + def function_and_constraints(self, z): + """Returns barrier function and constraints at given point. + + For z = [x, s], returns barrier function: + function(z) = fun(x) - barrier_parameter*sum(log(s)) + and barrier constraints: + constraints(z) = [ constr_eq(x) ] + [ constr_ineq(x) + s ] + + """ + # Get variables and slack variables + x = self.get_variables(z) + s = self.get_slack(z) + + # Compute function and constraints, + # making sure x is within any strict bounds + if np.any((x < self.lb) | (x > self.ub)): + # If x is out of the strict bounds, set f = inf, + # and just set both equality and inequality + # constraints to 0 since we can't evaluate + # them separately. + f = np.inf + c_eq = np.full(self.n_eq, 0.) + c_ineq = np.full(self.n_ineq, 0.) + else: + f = self.fun(x) + c_eq, c_ineq = self.constr(x) + + # Return objective function and constraints + return (self._compute_function(f, c_ineq, s), + self._compute_constr(c_ineq, c_eq, s)) + + def _compute_function(self, f, c_ineq, s): + # Use technique from Nocedal and Wright book, ref [3]_, p.576, + # to guarantee constraints from `enforce_feasibility` + # stay feasible along iterations. + s[self.enforce_feasibility] = -c_ineq[self.enforce_feasibility] + log_s = [np.log(s_i) if s_i > 0 else -np.inf for s_i in s] + # Compute barrier objective function + return f - self.barrier_parameter*np.sum(log_s) + + def _compute_constr(self, c_ineq, c_eq, s): + # Compute barrier constraint + return np.hstack((c_eq, + c_ineq + s)) + + def scaling(self, z): + """Returns scaling vector. + Given by: + scaling = [ones(n_vars), s] + """ + s = self.get_slack(z) + diag_elements = np.hstack((np.ones(self.n_vars), s)) + + # Diagonal matrix + def matvec(vec): + return diag_elements*vec + return LinearOperator((self.n_vars+self.n_ineq, + self.n_vars+self.n_ineq), + matvec) + + def gradient_and_jacobian(self, z): + """Returns scaled gradient. + + Return scaled gradient: + gradient = [ grad(x) ] + [ -barrier_parameter*ones(n_ineq) ] + and scaled Jacobian matrix: + jacobian = [ jac_eq(x) 0 ] + [ jac_ineq(x) S ] + Both of them scaled by the previously defined scaling factor. + """ + # Get variables and slack variables + x = self.get_variables(z) + s = self.get_slack(z) + # Compute first derivatives + g = self.grad(x) + J_eq, J_ineq = self.jac(x) + # Return gradient and Jacobian + return (self._compute_gradient(g), + self._compute_jacobian(J_eq, J_ineq, s)) + + def _compute_gradient(self, g): + return np.hstack((g, -self.barrier_parameter*np.ones(self.n_ineq))) + + def _compute_jacobian(self, J_eq, J_ineq, s): + if self.n_ineq == 0: + return J_eq + else: + if sps.issparse(J_eq) or sps.issparse(J_ineq): + # It is expected that J_eq and J_ineq + # are already `csr_matrix` because of + # the way ``BoxConstraint``, ``NonlinearConstraint`` + # and ``LinearConstraint`` are defined. + J_eq = sps.csr_matrix(J_eq) + J_ineq = sps.csr_matrix(J_ineq) + return self._assemble_sparse_jacobian(J_eq, J_ineq, s) + else: + S = np.diag(s) + zeros = np.zeros((self.n_eq, self.n_ineq)) + # Convert to matrix + if sps.issparse(J_ineq): + J_ineq = J_ineq.toarray() + if sps.issparse(J_eq): + J_eq = J_eq.toarray() + # Concatenate matrices + return np.block([[J_eq, zeros], + [J_ineq, S]]) + + def _assemble_sparse_jacobian(self, J_eq, J_ineq, s): + """Assemble sparse Jacobian given its components. + + Given ``J_eq``, ``J_ineq`` and ``s`` returns: + jacobian = [ J_eq, 0 ] + [ J_ineq, diag(s) ] + + It is equivalent to: + sps.bmat([[ J_eq, None ], + [ J_ineq, diag(s) ]], "csr") + but significantly more efficient for this + given structure. + """ + n_vars, n_ineq, n_eq = self.n_vars, self.n_ineq, self.n_eq + J_aux = sps.vstack([J_eq, J_ineq], "csr") + indptr, indices, data = J_aux.indptr, J_aux.indices, J_aux.data + new_indptr = indptr + np.hstack((np.zeros(n_eq, dtype=int), + np.arange(n_ineq+1, dtype=int))) + size = indices.size+n_ineq + new_indices = np.empty(size) + new_data = np.empty(size) + mask = np.full(size, False, bool) + mask[new_indptr[-n_ineq:]-1] = True + new_indices[mask] = n_vars+np.arange(n_ineq) + new_indices[~mask] = indices + new_data[mask] = s + new_data[~mask] = data + J = sps.csr_matrix((new_data, new_indices, new_indptr), + (n_eq + n_ineq, n_vars + n_ineq)) + return J + + def lagrangian_hessian_x(self, z, v): + """Returns Lagrangian Hessian (in relation to `x`) -> Hx""" + x = self.get_variables(z) + # Get lagrange multipliers related to nonlinear equality constraints + v_eq = v[:self.n_eq] + # Get lagrange multipliers related to nonlinear ineq. constraints + v_ineq = v[self.n_eq:self.n_eq+self.n_ineq] + lagr_hess = self.lagr_hess + return lagr_hess(x, v_eq, v_ineq) + + def lagrangian_hessian_s(self, z, v): + """Returns scaled Lagrangian Hessian (in relation to`s`) -> S Hs S""" + s = self.get_slack(z) + # Using the primal formulation: + # S Hs S = diag(s)*diag(barrier_parameter/s**2)*diag(s). + # Reference [1]_ p. 882, formula (3.1) + primal = self.barrier_parameter + # Using the primal-dual formulation + # S Hs S = diag(s)*diag(v/s)*diag(s) + # Reference [1]_ p. 883, formula (3.11) + primal_dual = v[-self.n_ineq:]*s + # Uses the primal-dual formulation for + # positives values of v_ineq, and primal + # formulation for the remaining ones. + return np.where(v[-self.n_ineq:] > 0, primal_dual, primal) + + def lagrangian_hessian(self, z, v): + """Returns scaled Lagrangian Hessian""" + # Compute Hessian in relation to x and s + Hx = self.lagrangian_hessian_x(z, v) + if self.n_ineq > 0: + S_Hs_S = self.lagrangian_hessian_s(z, v) + + # The scaled Lagragian Hessian is: + # [ Hx 0 ] + # [ 0 S Hs S ] + def matvec(vec): + vec_x = self.get_variables(vec) + vec_s = self.get_slack(vec) + if self.n_ineq > 0: + return np.hstack((Hx.dot(vec_x), S_Hs_S*vec_s)) + else: + return Hx.dot(vec_x) + return LinearOperator((self.n_vars+self.n_ineq, + self.n_vars+self.n_ineq), + matvec) + + def stop_criteria(self, state, z, last_iteration_failed, + optimality, constr_violation, + trust_radius, penalty, cg_info): + """Stop criteria to the barrier problem. + The criteria here proposed is similar to formula (2.3) + from [1]_, p.879. + """ + x = self.get_variables(z) + if self.global_stop_criteria(state, x, + last_iteration_failed, + trust_radius, penalty, + cg_info, + self.barrier_parameter, + self.tolerance): + self.terminate = True + return True + else: + g_cond = (optimality < self.tolerance and + constr_violation < self.tolerance) + x_cond = trust_radius < self.xtol + return g_cond or x_cond + + +def tr_interior_point(fun, grad, lagr_hess, n_vars, n_ineq, n_eq, + constr, jac, x0, fun0, grad0, + constr_ineq0, jac_ineq0, constr_eq0, + jac_eq0, stop_criteria, + enforce_feasibility, xtol, state, + initial_barrier_parameter, + initial_tolerance, + initial_penalty, + initial_trust_radius, + factorization_method, + finite_diff_bounds): + """Trust-region interior points method. + + Solve problem: + minimize fun(x) + subject to: constr_ineq(x) <= 0 + constr_eq(x) = 0 + using trust-region interior point method described in [1]_. + """ + # BOUNDARY_PARAMETER controls the decrease on the slack + # variables. Represents ``tau`` from [1]_ p.885, formula (3.18). + BOUNDARY_PARAMETER = 0.995 + # BARRIER_DECAY_RATIO controls the decay of the barrier parameter + # and of the subproblem tolerance. Represents ``theta`` from [1]_ p.879. + BARRIER_DECAY_RATIO = 0.2 + # TRUST_ENLARGEMENT controls the enlargement on trust radius + # after each iteration + TRUST_ENLARGEMENT = 5 + + # Default enforce_feasibility + if enforce_feasibility is None: + enforce_feasibility = np.zeros(n_ineq, bool) + # Initial Values + barrier_parameter = initial_barrier_parameter + tolerance = initial_tolerance + trust_radius = initial_trust_radius + # Define initial value for the slack variables + s0 = np.maximum(-1.5*constr_ineq0, np.ones(n_ineq)) + # Define barrier subproblem + subprob = BarrierSubproblem( + x0, s0, fun, grad, lagr_hess, n_vars, n_ineq, n_eq, constr, jac, + barrier_parameter, tolerance, enforce_feasibility, + stop_criteria, xtol, fun0, grad0, constr_ineq0, jac_ineq0, + constr_eq0, jac_eq0, finite_diff_bounds) + # Define initial parameter for the first iteration. + z = np.hstack((x0, s0)) + fun0_subprob, constr0_subprob = subprob.fun0, subprob.constr0 + grad0_subprob, jac0_subprob = subprob.grad0, subprob.jac0 + # Define trust region bounds + trust_lb = np.hstack((np.full(subprob.n_vars, -np.inf), + np.full(subprob.n_ineq, -BOUNDARY_PARAMETER))) + trust_ub = np.full(subprob.n_vars+subprob.n_ineq, np.inf) + + # Solves a sequence of barrier problems + while True: + # Solve SQP subproblem + z, state = equality_constrained_sqp( + subprob.function_and_constraints, + subprob.gradient_and_jacobian, + subprob.lagrangian_hessian, + z, fun0_subprob, grad0_subprob, + constr0_subprob, jac0_subprob, subprob.stop_criteria, + state, initial_penalty, trust_radius, + factorization_method, trust_lb, trust_ub, subprob.scaling) + if subprob.terminate: + break + # Update parameters + trust_radius = max(initial_trust_radius, + TRUST_ENLARGEMENT*state.tr_radius) + # TODO: Use more advanced strategies from [2]_ + # to update this parameters. + barrier_parameter *= BARRIER_DECAY_RATIO + tolerance *= BARRIER_DECAY_RATIO + # Update Barrier Problem + subprob.update(barrier_parameter, tolerance) + # Compute initial values for next iteration + fun0_subprob, constr0_subprob = subprob.function_and_constraints(z) + grad0_subprob, jac0_subprob = subprob.gradient_and_jacobian(z) + + # Get x and s + x = subprob.get_variables(z) + return x, state diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_dogleg.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_dogleg.py new file mode 100644 index 0000000000000000000000000000000000000000..a54abd60c703408d6c87cb5020d6781fdf0213c7 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_dogleg.py @@ -0,0 +1,122 @@ +"""Dog-leg trust-region optimization.""" +import numpy as np +import scipy.linalg +from ._trustregion import (_minimize_trust_region, BaseQuadraticSubproblem) + +__all__ = [] + + +def _minimize_dogleg(fun, x0, args=(), jac=None, hess=None, + **trust_region_options): + """ + Minimization of scalar function of one or more variables using + the dog-leg trust-region algorithm. + + Options + ------- + initial_trust_radius : float + Initial trust-region radius. + max_trust_radius : float + Maximum value of the trust-region radius. No steps that are longer + than this value will be proposed. + eta : float + Trust region related acceptance stringency for proposed steps. + gtol : float + Gradient norm must be less than `gtol` before successful + termination. + + """ + if jac is None: + raise ValueError('Jacobian is required for dogleg minimization') + if not callable(hess): + raise ValueError('Hessian is required for dogleg minimization') + return _minimize_trust_region(fun, x0, args=args, jac=jac, hess=hess, + subproblem=DoglegSubproblem, + **trust_region_options) + + +class DoglegSubproblem(BaseQuadraticSubproblem): + """Quadratic subproblem solved by the dogleg method""" + + def cauchy_point(self): + """ + The Cauchy point is minimal along the direction of steepest descent. + """ + if self._cauchy_point is None: + g = self.jac + Bg = self.hessp(g) + self._cauchy_point = -(np.dot(g, g) / np.dot(g, Bg)) * g + return self._cauchy_point + + def newton_point(self): + """ + The Newton point is a global minimum of the approximate function. + """ + if self._newton_point is None: + g = self.jac + B = self.hess + cho_info = scipy.linalg.cho_factor(B) + self._newton_point = -scipy.linalg.cho_solve(cho_info, g) + return self._newton_point + + def solve(self, trust_radius): + """ + Minimize a function using the dog-leg trust-region algorithm. + + This algorithm requires function values and first and second derivatives. + It also performs a costly Hessian decomposition for most iterations, + and the Hessian is required to be positive definite. + + Parameters + ---------- + trust_radius : float + We are allowed to wander only this far away from the origin. + + Returns + ------- + p : ndarray + The proposed step. + hits_boundary : bool + True if the proposed step is on the boundary of the trust region. + + Notes + ----- + The Hessian is required to be positive definite. + + References + ---------- + .. [1] Jorge Nocedal and Stephen Wright, + Numerical Optimization, second edition, + Springer-Verlag, 2006, page 73. + """ + + # Compute the Newton point. + # This is the optimum for the quadratic model function. + # If it is inside the trust radius then return this point. + p_best = self.newton_point() + if scipy.linalg.norm(p_best) < trust_radius: + hits_boundary = False + return p_best, hits_boundary + + # Compute the Cauchy point. + # This is the predicted optimum along the direction of steepest descent. + p_u = self.cauchy_point() + + # If the Cauchy point is outside the trust region, + # then return the point where the path intersects the boundary. + p_u_norm = scipy.linalg.norm(p_u) + if p_u_norm >= trust_radius: + p_boundary = p_u * (trust_radius / p_u_norm) + hits_boundary = True + return p_boundary, hits_boundary + + # Compute the intersection of the trust region boundary + # and the line segment connecting the Cauchy and Newton points. + # This requires solving a quadratic equation. + # ||p_u + t*(p_best - p_u)||**2 == trust_radius**2 + # Solve this for positive time t using the quadratic formula. + _, tb = self.get_boundaries_intersections(p_u, p_best - p_u, + trust_radius) + p_boundary = p_u + tb * (p_best - p_u) + hits_boundary = True + return p_boundary, hits_boundary diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_exact.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_exact.py new file mode 100644 index 0000000000000000000000000000000000000000..956e4f261907f001cf5bbb3616f331c18a676af0 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_exact.py @@ -0,0 +1,438 @@ +"""Nearly exact trust-region optimization subproblem.""" +import numpy as np +from scipy.linalg import (norm, get_lapack_funcs, solve_triangular, + cho_solve) +from ._trustregion import (_minimize_trust_region, BaseQuadraticSubproblem) + +__all__ = ['_minimize_trustregion_exact', + 'estimate_smallest_singular_value', + 'singular_leading_submatrix', + 'IterativeSubproblem'] + + +def _minimize_trustregion_exact(fun, x0, args=(), jac=None, hess=None, + **trust_region_options): + """ + Minimization of scalar function of one or more variables using + a nearly exact trust-region algorithm. + + Options + ------- + initial_trust_radius : float + Initial trust-region radius. + max_trust_radius : float + Maximum value of the trust-region radius. No steps that are longer + than this value will be proposed. + eta : float + Trust region related acceptance stringency for proposed steps. + gtol : float + Gradient norm must be less than ``gtol`` before successful + termination. + """ + + if jac is None: + raise ValueError('Jacobian is required for trust region ' + 'exact minimization.') + if not callable(hess): + raise ValueError('Hessian matrix is required for trust region ' + 'exact minimization.') + return _minimize_trust_region(fun, x0, args=args, jac=jac, hess=hess, + subproblem=IterativeSubproblem, + **trust_region_options) + + +def estimate_smallest_singular_value(U): + """Given upper triangular matrix ``U`` estimate the smallest singular + value and the correspondent right singular vector in O(n**2) operations. + + Parameters + ---------- + U : ndarray + Square upper triangular matrix. + + Returns + ------- + s_min : float + Estimated smallest singular value of the provided matrix. + z_min : ndarray + Estimated right singular vector. + + Notes + ----- + The procedure is based on [1]_ and is done in two steps. First, it finds + a vector ``e`` with components selected from {+1, -1} such that the + solution ``w`` from the system ``U.T w = e`` is as large as possible. + Next it estimate ``U v = w``. The smallest singular value is close + to ``norm(w)/norm(v)`` and the right singular vector is close + to ``v/norm(v)``. + + The estimation will be better more ill-conditioned is the matrix. + + References + ---------- + .. [1] Cline, A. K., Moler, C. B., Stewart, G. W., Wilkinson, J. H. + An estimate for the condition number of a matrix. 1979. + SIAM Journal on Numerical Analysis, 16(2), 368-375. + """ + + U = np.atleast_2d(U) + m, n = U.shape + + if m != n: + raise ValueError("A square triangular matrix should be provided.") + + # A vector `e` with components selected from {+1, -1} + # is selected so that the solution `w` to the system + # `U.T w = e` is as large as possible. Implementation + # based on algorithm 3.5.1, p. 142, from reference [2] + # adapted for lower triangular matrix. + + p = np.zeros(n) + w = np.empty(n) + + # Implemented according to: Golub, G. H., Van Loan, C. F. (2013). + # "Matrix computations". Forth Edition. JHU press. pp. 140-142. + for k in range(n): + wp = (1-p[k]) / U.T[k, k] + wm = (-1-p[k]) / U.T[k, k] + pp = p[k+1:] + U.T[k+1:, k]*wp + pm = p[k+1:] + U.T[k+1:, k]*wm + + if abs(wp) + norm(pp, 1) >= abs(wm) + norm(pm, 1): + w[k] = wp + p[k+1:] = pp + else: + w[k] = wm + p[k+1:] = pm + + # The system `U v = w` is solved using backward substitution. + v = solve_triangular(U, w) + + v_norm = norm(v) + w_norm = norm(w) + + # Smallest singular value + s_min = w_norm / v_norm + + # Associated vector + z_min = v / v_norm + + return s_min, z_min + + +def gershgorin_bounds(H): + """ + Given a square matrix ``H`` compute upper + and lower bounds for its eigenvalues (Gregoshgorin Bounds). + Defined ref. [1]. + + References + ---------- + .. [1] Conn, A. R., Gould, N. I., & Toint, P. L. + Trust region methods. 2000. Siam. pp. 19. + """ + + H_diag = np.diag(H) + H_diag_abs = np.abs(H_diag) + H_row_sums = np.sum(np.abs(H), axis=1) + lb = np.min(H_diag + H_diag_abs - H_row_sums) + ub = np.max(H_diag - H_diag_abs + H_row_sums) + + return lb, ub + + +def singular_leading_submatrix(A, U, k): + """ + Compute term that makes the leading ``k`` by ``k`` + submatrix from ``A`` singular. + + Parameters + ---------- + A : ndarray + Symmetric matrix that is not positive definite. + U : ndarray + Upper triangular matrix resulting of an incomplete + Cholesky decomposition of matrix ``A``. + k : int + Positive integer such that the leading k by k submatrix from + `A` is the first non-positive definite leading submatrix. + + Returns + ------- + delta : float + Amount that should be added to the element (k, k) of the + leading k by k submatrix of ``A`` to make it singular. + v : ndarray + A vector such that ``v.T B v = 0``. Where B is the matrix A after + ``delta`` is added to its element (k, k). + """ + + # Compute delta + delta = np.sum(U[:k-1, k-1]**2) - A[k-1, k-1] + + n = len(A) + + # Initialize v + v = np.zeros(n) + v[k-1] = 1 + + # Compute the remaining values of v by solving a triangular system. + if k != 1: + v[:k-1] = solve_triangular(U[:k-1, :k-1], -U[:k-1, k-1]) + + return delta, v + + +class IterativeSubproblem(BaseQuadraticSubproblem): + """Quadratic subproblem solved by nearly exact iterative method. + + Notes + ----- + This subproblem solver was based on [1]_, [2]_ and [3]_, + which implement similar algorithms. The algorithm is basically + that of [1]_ but ideas from [2]_ and [3]_ were also used. + + References + ---------- + .. [1] A.R. Conn, N.I. Gould, and P.L. Toint, "Trust region methods", + Siam, pp. 169-200, 2000. + .. [2] J. Nocedal and S. Wright, "Numerical optimization", + Springer Science & Business Media. pp. 83-91, 2006. + .. [3] J.J. More and D.C. Sorensen, "Computing a trust region step", + SIAM Journal on Scientific and Statistical Computing, vol. 4(3), + pp. 553-572, 1983. + """ + + # UPDATE_COEFF appears in reference [1]_ + # in formula 7.3.14 (p. 190) named as "theta". + # As recommended there it value is fixed in 0.01. + UPDATE_COEFF = 0.01 + + EPS = np.finfo(float).eps + + def __init__(self, x, fun, jac, hess, hessp=None, + k_easy=0.1, k_hard=0.2): + + super().__init__(x, fun, jac, hess) + + # When the trust-region shrinks in two consecutive + # calculations (``tr_radius < previous_tr_radius``) + # the lower bound ``lambda_lb`` may be reused, + # facilitating the convergence. To indicate no + # previous value is known at first ``previous_tr_radius`` + # is set to -1 and ``lambda_lb`` to None. + self.previous_tr_radius = -1 + self.lambda_lb = None + + self.niter = 0 + + # ``k_easy`` and ``k_hard`` are parameters used + # to determine the stop criteria to the iterative + # subproblem solver. Take a look at pp. 194-197 + # from reference _[1] for a more detailed description. + self.k_easy = k_easy + self.k_hard = k_hard + + # Get Lapack function for cholesky decomposition. + # The implemented SciPy wrapper does not return + # the incomplete factorization needed by the method. + self.cholesky, = get_lapack_funcs(('potrf',), (self.hess,)) + + # Get info about Hessian + self.dimension = len(self.hess) + self.hess_gershgorin_lb,\ + self.hess_gershgorin_ub = gershgorin_bounds(self.hess) + self.hess_inf = norm(self.hess, np.inf) + self.hess_fro = norm(self.hess, 'fro') + + # A constant such that for vectors smaller than that + # backward substitution is not reliable. It was established + # based on Golub, G. H., Van Loan, C. F. (2013). + # "Matrix computations". Forth Edition. JHU press., p.165. + self.CLOSE_TO_ZERO = self.dimension * self.EPS * self.hess_inf + + def _initial_values(self, tr_radius): + """Given a trust radius, return a good initial guess for + the damping factor, the lower bound and the upper bound. + The values were chosen accordingly to the guidelines on + section 7.3.8 (p. 192) from [1]_. + """ + + # Upper bound for the damping factor + lambda_ub = max(0, self.jac_mag/tr_radius + min(-self.hess_gershgorin_lb, + self.hess_fro, + self.hess_inf)) + + # Lower bound for the damping factor + lambda_lb = max(0, -min(self.hess.diagonal()), + self.jac_mag/tr_radius - min(self.hess_gershgorin_ub, + self.hess_fro, + self.hess_inf)) + + # Improve bounds with previous info + if tr_radius < self.previous_tr_radius: + lambda_lb = max(self.lambda_lb, lambda_lb) + + # Initial guess for the damping factor + if lambda_lb == 0: + lambda_initial = 0 + else: + lambda_initial = max(np.sqrt(lambda_lb * lambda_ub), + lambda_lb + self.UPDATE_COEFF*(lambda_ub-lambda_lb)) + + return lambda_initial, lambda_lb, lambda_ub + + def solve(self, tr_radius): + """Solve quadratic subproblem""" + + lambda_current, lambda_lb, lambda_ub = self._initial_values(tr_radius) + n = self.dimension + hits_boundary = True + already_factorized = False + self.niter = 0 + + while True: + + # Compute Cholesky factorization + if already_factorized: + already_factorized = False + else: + H = self.hess+lambda_current*np.eye(n) + U, info = self.cholesky(H, lower=False, + overwrite_a=False, + clean=True) + + self.niter += 1 + + # Check if factorization succeeded + if info == 0 and self.jac_mag > self.CLOSE_TO_ZERO: + # Successful factorization + + # Solve `U.T U p = s` + p = cho_solve((U, False), -self.jac) + + p_norm = norm(p) + + # Check for interior convergence + if p_norm <= tr_radius and lambda_current == 0: + hits_boundary = False + break + + # Solve `U.T w = p` + w = solve_triangular(U, p, trans='T') + + w_norm = norm(w) + + # Compute Newton step accordingly to + # formula (4.44) p.87 from ref [2]_. + delta_lambda = (p_norm/w_norm)**2 * (p_norm-tr_radius)/tr_radius + lambda_new = lambda_current + delta_lambda + + if p_norm < tr_radius: # Inside boundary + s_min, z_min = estimate_smallest_singular_value(U) + + ta, tb = self.get_boundaries_intersections(p, z_min, + tr_radius) + + # Choose `step_len` with the smallest magnitude. + # The reason for this choice is explained at + # ref [3]_, p. 6 (Immediately before the formula + # for `tau`). + step_len = min([ta, tb], key=abs) + + # Compute the quadratic term (p.T*H*p) + quadratic_term = np.dot(p, np.dot(H, p)) + + # Check stop criteria + relative_error = ((step_len**2 * s_min**2) + / (quadratic_term + lambda_current*tr_radius**2)) + if relative_error <= self.k_hard: + p += step_len * z_min + break + + # Update uncertainty bounds + lambda_ub = lambda_current + lambda_lb = max(lambda_lb, lambda_current - s_min**2) + + # Compute Cholesky factorization + H = self.hess + lambda_new*np.eye(n) + c, info = self.cholesky(H, lower=False, + overwrite_a=False, + clean=True) + + # Check if the factorization have succeeded + # + if info == 0: # Successful factorization + # Update damping factor + lambda_current = lambda_new + already_factorized = True + else: # Unsuccessful factorization + # Update uncertainty bounds + lambda_lb = max(lambda_lb, lambda_new) + + # Update damping factor + lambda_current = max( + np.sqrt(lambda_lb * lambda_ub), + lambda_lb + self.UPDATE_COEFF*(lambda_ub-lambda_lb) + ) + + else: # Outside boundary + # Check stop criteria + relative_error = abs(p_norm - tr_radius) / tr_radius + if relative_error <= self.k_easy: + break + + # Update uncertainty bounds + lambda_lb = lambda_current + + # Update damping factor + lambda_current = lambda_new + + elif info == 0 and self.jac_mag <= self.CLOSE_TO_ZERO: + # jac_mag very close to zero + + # Check for interior convergence + if lambda_current == 0: + p = np.zeros(n) + hits_boundary = False + break + + s_min, z_min = estimate_smallest_singular_value(U) + step_len = tr_radius + + # Check stop criteria + if (step_len**2 * s_min**2 + <= self.k_hard * lambda_current * tr_radius**2): + p = step_len * z_min + break + + # Update uncertainty bounds + lambda_ub = lambda_current + lambda_lb = max(lambda_lb, lambda_current - s_min**2) + + # Update damping factor + lambda_current = max( + np.sqrt(lambda_lb * lambda_ub), + lambda_lb + self.UPDATE_COEFF*(lambda_ub-lambda_lb) + ) + + else: # Unsuccessful factorization + + # Compute auxiliary terms + delta, v = singular_leading_submatrix(H, U, info) + v_norm = norm(v) + + # Update uncertainty interval + lambda_lb = max(lambda_lb, lambda_current + delta/v_norm**2) + + # Update damping factor + lambda_current = max( + np.sqrt(lambda_lb * lambda_ub), + lambda_lb + self.UPDATE_COEFF*(lambda_ub-lambda_lb) + ) + + self.lambda_lb = lambda_lb + self.lambda_current = lambda_current + self.previous_tr_radius = tr_radius + + return p, hits_boundary diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_krylov.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_krylov.py new file mode 100644 index 0000000000000000000000000000000000000000..54e861ae2de02164966a33c437e5fdb08ba3006c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_krylov.py @@ -0,0 +1,65 @@ +from ._trustregion import (_minimize_trust_region) +from ._trlib import (get_trlib_quadratic_subproblem) + +__all__ = ['_minimize_trust_krylov'] + +def _minimize_trust_krylov(fun, x0, args=(), jac=None, hess=None, hessp=None, + inexact=True, **trust_region_options): + """ + Minimization of a scalar function of one or more variables using + a nearly exact trust-region algorithm that only requires matrix + vector products with the hessian matrix. + + .. versionadded:: 1.0.0 + + Options + ------- + inexact : bool, optional + Accuracy to solve subproblems. If True requires less nonlinear + iterations, but more vector products. + """ + + if jac is None: + raise ValueError('Jacobian is required for trust region ', + 'exact minimization.') + if hess is None and hessp is None: + raise ValueError('Either the Hessian or the Hessian-vector product ' + 'is required for Krylov trust-region minimization') + + # tol_rel specifies the termination tolerance relative to the initial + # gradient norm in the Krylov subspace iteration. + + # - tol_rel_i specifies the tolerance for interior convergence. + # - tol_rel_b specifies the tolerance for boundary convergence. + # in nonlinear programming applications it is not necessary to solve + # the boundary case as exact as the interior case. + + # - setting tol_rel_i=-2 leads to a forcing sequence in the Krylov + # subspace iteration leading to quadratic convergence if eventually + # the trust region stays inactive. + # - setting tol_rel_b=-3 leads to a forcing sequence in the Krylov + # subspace iteration leading to superlinear convergence as long + # as the iterates hit the trust region boundary. + + # For details consult the documentation of trlib_krylov_min + # in _trlib/trlib_krylov.h + # + # Optimality of this choice of parameters among a range of possibilities + # has been tested on the unconstrained subset of the CUTEst library. + + if inexact: + return _minimize_trust_region(fun, x0, args=args, jac=jac, + hess=hess, hessp=hessp, + subproblem=get_trlib_quadratic_subproblem( + tol_rel_i=-2.0, tol_rel_b=-3.0, + disp=trust_region_options.get('disp', False) + ), + **trust_region_options) + else: + return _minimize_trust_region(fun, x0, args=args, jac=jac, + hess=hess, hessp=hessp, + subproblem=get_trlib_quadratic_subproblem( + tol_rel_i=1e-8, tol_rel_b=1e-6, + disp=trust_region_options.get('disp', False) + ), + **trust_region_options) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_ncg.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_ncg.py new file mode 100644 index 0000000000000000000000000000000000000000..fed17ff8b84eaf019c0ad69a03f260ca674477ad --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_trustregion_ncg.py @@ -0,0 +1,126 @@ +"""Newton-CG trust-region optimization.""" +import math + +import numpy as np +import scipy.linalg +from ._trustregion import (_minimize_trust_region, BaseQuadraticSubproblem) + +__all__ = [] + + +def _minimize_trust_ncg(fun, x0, args=(), jac=None, hess=None, hessp=None, + **trust_region_options): + """ + Minimization of scalar function of one or more variables using + the Newton conjugate gradient trust-region algorithm. + + Options + ------- + initial_trust_radius : float + Initial trust-region radius. + max_trust_radius : float + Maximum value of the trust-region radius. No steps that are longer + than this value will be proposed. + eta : float + Trust region related acceptance stringency for proposed steps. + gtol : float + Gradient norm must be less than `gtol` before successful + termination. + + """ + if jac is None: + raise ValueError('Jacobian is required for Newton-CG trust-region ' + 'minimization') + if hess is None and hessp is None: + raise ValueError('Either the Hessian or the Hessian-vector product ' + 'is required for Newton-CG trust-region minimization') + return _minimize_trust_region(fun, x0, args=args, jac=jac, hess=hess, + hessp=hessp, subproblem=CGSteihaugSubproblem, + **trust_region_options) + + +class CGSteihaugSubproblem(BaseQuadraticSubproblem): + """Quadratic subproblem solved by a conjugate gradient method""" + def solve(self, trust_radius): + """ + Solve the subproblem using a conjugate gradient method. + + Parameters + ---------- + trust_radius : float + We are allowed to wander only this far away from the origin. + + Returns + ------- + p : ndarray + The proposed step. + hits_boundary : bool + True if the proposed step is on the boundary of the trust region. + + Notes + ----- + This is algorithm (7.2) of Nocedal and Wright 2nd edition. + Only the function that computes the Hessian-vector product is required. + The Hessian itself is not required, and the Hessian does + not need to be positive semidefinite. + """ + + # get the norm of jacobian and define the origin + p_origin = np.zeros_like(self.jac) + + # define a default tolerance + tolerance = min(0.5, math.sqrt(self.jac_mag)) * self.jac_mag + + # Stop the method if the search direction + # is a direction of nonpositive curvature. + if self.jac_mag < tolerance: + hits_boundary = False + return p_origin, hits_boundary + + # init the state for the first iteration + z = p_origin + r = self.jac + d = -r + + # Search for the min of the approximation of the objective function. + while True: + + # do an iteration + Bd = self.hessp(d) + dBd = np.dot(d, Bd) + if dBd <= 0: + # Look at the two boundary points. + # Find both values of t to get the boundary points such that + # ||z + t d|| == trust_radius + # and then choose the one with the predicted min value. + ta, tb = self.get_boundaries_intersections(z, d, trust_radius) + pa = z + ta * d + pb = z + tb * d + if self(pa) < self(pb): + p_boundary = pa + else: + p_boundary = pb + hits_boundary = True + return p_boundary, hits_boundary + r_squared = np.dot(r, r) + alpha = r_squared / dBd + z_next = z + alpha * d + if scipy.linalg.norm(z_next) >= trust_radius: + # Find t >= 0 to get the boundary point such that + # ||z + t d|| == trust_radius + ta, tb = self.get_boundaries_intersections(z, d, trust_radius) + p_boundary = z + tb * d + hits_boundary = True + return p_boundary, hits_boundary + r_next = r + alpha * Bd + r_next_squared = np.dot(r_next, r_next) + if math.sqrt(r_next_squared) < tolerance: + hits_boundary = False + return z_next, hits_boundary + beta_next = r_next_squared / r_squared + d_next = -r_next + beta_next * d + + # update the state for the next iteration + z = z_next + r = r_next + d = d_next diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_tstutils.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_tstutils.py new file mode 100644 index 0000000000000000000000000000000000000000..f56e835e345d66023efae81114a45ed29269f18d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_tstutils.py @@ -0,0 +1,972 @@ +r""" +Parameters used in test and benchmark methods. + +Collections of test cases suitable for testing 1-D root-finders + 'original': The original benchmarking functions. + Real-valued functions of real-valued inputs on an interval + with a zero. + f1, .., f3 are continuous and infinitely differentiable + f4 has a left- and right- discontinuity at the root + f5 has a root at 1 replacing a 1st order pole + f6 is randomly positive on one side of the root, + randomly negative on the other. + f4 - f6 are not continuous at the root. + + 'aps': The test problems in the 1995 paper + TOMS "Algorithm 748: Enclosing Zeros of Continuous Functions" + by Alefeld, Potra and Shi. Real-valued functions of + real-valued inputs on an interval with a zero. + Suitable for methods which start with an enclosing interval, and + derivatives up to 2nd order. + + 'complex': Some complex-valued functions of complex-valued inputs. + No enclosing bracket is provided. + Suitable for methods which use one or more starting values, and + derivatives up to 2nd order. + + The test cases are provided as a list of dictionaries. The dictionary + keys will be a subset of: + ["f", "fprime", "fprime2", "args", "bracket", "smoothness", + "a", "b", "x0", "x1", "root", "ID"] +""" + +# Sources: +# [1] Alefeld, G. E. and Potra, F. A. and Shi, Yixun, +# "Algorithm 748: Enclosing Zeros of Continuous Functions", +# ACM Trans. Math. Softw. Volume 221(1995) +# doi = {10.1145/210089.210111}, +# [2] Chandrupatla, Tirupathi R. "A new hybrid quadratic/bisection algorithm +# for finding the zero of a nonlinear function without using derivatives." +# Advances in Engineering Software 28.3 (1997): 145-149. + +from random import random + +import numpy as np + +from scipy.optimize import _zeros_py as cc +from scipy._lib._array_api import array_namespace + +# "description" refers to the original functions +description = """ +f2 is a symmetric parabola, x**2 - 1 +f3 is a quartic polynomial with large hump in interval +f4 is step function with a discontinuity at 1 +f5 is a hyperbola with vertical asymptote at 1 +f6 has random values positive to left of 1, negative to right + +Of course, these are not real problems. They just test how the +'good' solvers behave in bad circumstances where bisection is +really the best. A good solver should not be much worse than +bisection in such circumstance, while being faster for smooth +monotone sorts of functions. +""" + + +def f1(x): + r"""f1 is a quadratic with roots at 0 and 1""" + return x * (x - 1.) + + +def f1_fp(x): + return 2 * x - 1 + + +def f1_fpp(x): + return 2 + + +def f2(x): + r"""f2 is a symmetric parabola, x**2 - 1""" + return x**2 - 1 + + +def f2_fp(x): + return 2 * x + + +def f2_fpp(x): + return 2 + + +def f3(x): + r"""A quartic with roots at 0, 1, 2 and 3""" + return x * (x - 1.) * (x - 2.) * (x - 3.) # x**4 - 6x**3 + 11x**2 - 6x + + +def f3_fp(x): + return 4 * x**3 - 18 * x**2 + 22 * x - 6 + + +def f3_fpp(x): + return 12 * x**2 - 36 * x + 22 + + +def f4(x): + r"""Piecewise linear, left- and right- discontinuous at x=1, the root.""" + if x > 1: + return 1.0 + .1 * x + if x < 1: + return -1.0 + .1 * x + return 0 + + +def f5(x): + r""" + Hyperbola with a pole at x=1, but pole replaced with 0. Not continuous at root. + """ + if x != 1: + return 1.0 / (1. - x) + return 0 + + +# f6(x) returns random value. Without memoization, calling twice with the +# same x returns different values, hence a "random value", not a +# "function with random values" +_f6_cache = {} +def f6(x): + v = _f6_cache.get(x, None) + if v is None: + if x > 1: + v = random() + elif x < 1: + v = -random() + else: + v = 0 + _f6_cache[x] = v + return v + + +# Each Original test case has +# - a function and its two derivatives, +# - additional arguments, +# - a bracket enclosing a root, +# - the order of differentiability (smoothness) on this interval +# - a starting value for methods which don't require a bracket +# - the root (inside the bracket) +# - an Identifier of the test case + +_ORIGINAL_TESTS_KEYS = [ + "f", "fprime", "fprime2", "args", "bracket", "smoothness", "x0", "root", "ID" +] +_ORIGINAL_TESTS = [ + [f1, f1_fp, f1_fpp, (), [0.5, np.sqrt(3)], np.inf, 0.6, 1.0, "original.01.00"], + [f2, f2_fp, f2_fpp, (), [0.5, np.sqrt(3)], np.inf, 0.6, 1.0, "original.02.00"], + [f3, f3_fp, f3_fpp, (), [0.5, np.sqrt(3)], np.inf, 0.6, 1.0, "original.03.00"], + [f4, None, None, (), [0.5, np.sqrt(3)], -1, 0.6, 1.0, "original.04.00"], + [f5, None, None, (), [0.5, np.sqrt(3)], -1, 0.6, 1.0, "original.05.00"], + [f6, None, None, (), [0.5, np.sqrt(3)], -np.inf, 0.6, 1.0, "original.05.00"] +] + +_ORIGINAL_TESTS_DICTS = [ + dict(zip(_ORIGINAL_TESTS_KEYS, testcase)) for testcase in _ORIGINAL_TESTS +] + +# ################## +# "APS" test cases +# Functions and test cases that appear in [1] + + +def aps01_f(x): + r"""Straightforward sum of trigonometric function and polynomial""" + return np.sin(x) - x / 2 + + +def aps01_fp(x): + return np.cos(x) - 1.0 / 2 + + +def aps01_fpp(x): + return -np.sin(x) + + +def aps02_f(x): + r"""poles at x=n**2, 1st and 2nd derivatives at root are also close to 0""" + ii = np.arange(1, 21) + return -2 * np.sum((2 * ii - 5)**2 / (x - ii**2)**3) + + +def aps02_fp(x): + ii = np.arange(1, 21) + return 6 * np.sum((2 * ii - 5)**2 / (x - ii**2)**4) + + +def aps02_fpp(x): + ii = np.arange(1, 21) + return 24 * np.sum((2 * ii - 5)**2 / (x - ii**2)**5) + + +def aps03_f(x, a, b): + r"""Rapidly changing at the root""" + return a * x * np.exp(b * x) + + +def aps03_fp(x, a, b): + return a * (b * x + 1) * np.exp(b * x) + + +def aps03_fpp(x, a, b): + return a * (b * (b * x + 1) + b) * np.exp(b * x) + + +def aps04_f(x, n, a): + r"""Medium-degree polynomial""" + return x**n - a + + +def aps04_fp(x, n, a): + return n * x**(n - 1) + + +def aps04_fpp(x, n, a): + return n * (n - 1) * x**(n - 2) + + +def aps05_f(x): + r"""Simple Trigonometric function""" + return np.sin(x) - 1.0 / 2 + + +def aps05_fp(x): + return np.cos(x) + + +def aps05_fpp(x): + return -np.sin(x) + + +def aps06_f(x, n): + r"""Exponential rapidly changing from -1 to 1 at x=0""" + return 2 * x * np.exp(-n) - 2 * np.exp(-n * x) + 1 + + +def aps06_fp(x, n): + return 2 * np.exp(-n) + 2 * n * np.exp(-n * x) + + +def aps06_fpp(x, n): + return -2 * n * n * np.exp(-n * x) + + +def aps07_f(x, n): + r"""Upside down parabola with parametrizable height""" + return (1 + (1 - n)**2) * x - (1 - n * x)**2 + + +def aps07_fp(x, n): + return (1 + (1 - n)**2) + 2 * n * (1 - n * x) + + +def aps07_fpp(x, n): + return -2 * n * n + + +def aps08_f(x, n): + r"""Degree n polynomial""" + return x * x - (1 - x)**n + + +def aps08_fp(x, n): + return 2 * x + n * (1 - x)**(n - 1) + + +def aps08_fpp(x, n): + return 2 - n * (n - 1) * (1 - x)**(n - 2) + + +def aps09_f(x, n): + r"""Upside down quartic with parametrizable height""" + return (1 + (1 - n)**4) * x - (1 - n * x)**4 + + +def aps09_fp(x, n): + return (1 + (1 - n)**4) + 4 * n * (1 - n * x)**3 + + +def aps09_fpp(x, n): + return -12 * n * (1 - n * x)**2 + + +def aps10_f(x, n): + r"""Exponential plus a polynomial""" + return np.exp(-n * x) * (x - 1) + x**n + + +def aps10_fp(x, n): + return np.exp(-n * x) * (-n * (x - 1) + 1) + n * x**(n - 1) + + +def aps10_fpp(x, n): + return (np.exp(-n * x) * (-n * (-n * (x - 1) + 1) + -n * x) + + n * (n - 1) * x**(n - 2)) + + +def aps11_f(x, n): + r"""Rational function with a zero at x=1/n and a pole at x=0""" + return (n * x - 1) / ((n - 1) * x) + + +def aps11_fp(x, n): + return 1 / (n - 1) / x**2 + + +def aps11_fpp(x, n): + return -2 / (n - 1) / x**3 + + +def aps12_f(x, n): + r"""nth root of x, with a zero at x=n""" + return np.power(x, 1.0 / n) - np.power(n, 1.0 / n) + + +def aps12_fp(x, n): + return np.power(x, (1.0 - n) / n) / n + + +def aps12_fpp(x, n): + return np.power(x, (1.0 - 2 * n) / n) * (1.0 / n) * (1.0 - n) / n + + +_MAX_EXPABLE = np.log(np.finfo(float).max) + + +def aps13_f(x): + r"""Function with *all* derivatives 0 at the root""" + if x == 0: + return 0 + # x2 = 1.0/x**2 + # if x2 > 708: + # return 0 + y = 1 / x**2 + if y > _MAX_EXPABLE: + return 0 + return x / np.exp(y) + + +def aps13_fp(x): + if x == 0: + return 0 + y = 1 / x**2 + if y > _MAX_EXPABLE: + return 0 + return (1 + 2 / x**2) / np.exp(y) + + +def aps13_fpp(x): + if x == 0: + return 0 + y = 1 / x**2 + if y > _MAX_EXPABLE: + return 0 + return 2 * (2 - x**2) / x**5 / np.exp(y) + + +def aps14_f(x, n): + r"""0 for negative x-values, trigonometric+linear for x positive""" + if x <= 0: + return -n / 20.0 + return n / 20.0 * (x / 1.5 + np.sin(x) - 1) + + +def aps14_fp(x, n): + if x <= 0: + return 0 + return n / 20.0 * (1.0 / 1.5 + np.cos(x)) + + +def aps14_fpp(x, n): + if x <= 0: + return 0 + return -n / 20.0 * (np.sin(x)) + + +def aps15_f(x, n): + r"""piecewise linear, constant outside of [0, 0.002/(1+n)]""" + if x < 0: + return -0.859 + if x > 2 * 1e-3 / (1 + n): + return np.e - 1.859 + return np.exp((n + 1) * x / 2 * 1000) - 1.859 + + +def aps15_fp(x, n): + if not 0 <= x <= 2 * 1e-3 / (1 + n): + return np.e - 1.859 + return np.exp((n + 1) * x / 2 * 1000) * (n + 1) / 2 * 1000 + + +def aps15_fpp(x, n): + if not 0 <= x <= 2 * 1e-3 / (1 + n): + return np.e - 1.859 + return np.exp((n + 1) * x / 2 * 1000) * (n + 1) / 2 * 1000 * (n + 1) / 2 * 1000 + + +# Each APS test case has +# - a function and its two derivatives, +# - additional arguments, +# - a bracket enclosing a root, +# - the order of differentiability of the function on this interval +# - a starting value for methods which don't require a bracket +# - the root (inside the bracket) +# - an Identifier of the test case +# +# Algorithm 748 is a bracketing algorithm so a bracketing interval was provided +# in [1] for each test case. Newton and Halley methods need a single +# starting point x0, which was chosen to be near the middle of the interval, +# unless that would have made the problem too easy. + +_APS_TESTS_KEYS = [ + "f", "fprime", "fprime2", "args", "bracket", "smoothness", "x0", "root", "ID" +] +_APS_TESTS = [ + [aps01_f, aps01_fp, aps01_fpp, (), [np.pi / 2, np.pi], np.inf, + 3, 1.89549426703398094e+00, "aps.01.00"], + [aps02_f, aps02_fp, aps02_fpp, (), [1 + 1e-9, 4 - 1e-9], np.inf, + 2, 3.02291534727305677e+00, "aps.02.00"], + [aps02_f, aps02_fp, aps02_fpp, (), [4 + 1e-9, 9 - 1e-9], np.inf, + 5, 6.68375356080807848e+00, "aps.02.01"], + [aps02_f, aps02_fp, aps02_fpp, (), [9 + 1e-9, 16 - 1e-9], np.inf, + 10, 1.12387016550022114e+01, "aps.02.02"], + [aps02_f, aps02_fp, aps02_fpp, (), [16 + 1e-9, 25 - 1e-9], np.inf, + 17, 1.96760000806234103e+01, "aps.02.03"], + [aps02_f, aps02_fp, aps02_fpp, (), [25 + 1e-9, 36 - 1e-9], np.inf, + 26, 2.98282273265047557e+01, "aps.02.04"], + [aps02_f, aps02_fp, aps02_fpp, (), [36 + 1e-9, 49 - 1e-9], np.inf, + 37, 4.19061161952894139e+01, "aps.02.05"], + [aps02_f, aps02_fp, aps02_fpp, (), [49 + 1e-9, 64 - 1e-9], np.inf, + 50, 5.59535958001430913e+01, "aps.02.06"], + [aps02_f, aps02_fp, aps02_fpp, (), [64 + 1e-9, 81 - 1e-9], np.inf, + 65, 7.19856655865877997e+01, "aps.02.07"], + [aps02_f, aps02_fp, aps02_fpp, (), [81 + 1e-9, 100 - 1e-9], np.inf, + 82, 9.00088685391666701e+01, "aps.02.08"], + [aps02_f, aps02_fp, aps02_fpp, (), [100 + 1e-9, 121 - 1e-9], np.inf, + 101, 1.10026532748330197e+02, "aps.02.09"], + [aps03_f, aps03_fp, aps03_fpp, (-40, -1), [-9, 31], np.inf, + -2, 0, "aps.03.00"], + [aps03_f, aps03_fp, aps03_fpp, (-100, -2), [-9, 31], np.inf, + -2, 0, "aps.03.01"], + [aps03_f, aps03_fp, aps03_fpp, (-200, -3), [-9, 31], np.inf, + -2, 0, "aps.03.02"], + [aps04_f, aps04_fp, aps04_fpp, (4, 0.2), [0, 5], np.inf, + 2.5, 6.68740304976422006e-01, "aps.04.00"], + [aps04_f, aps04_fp, aps04_fpp, (6, 0.2), [0, 5], np.inf, + 2.5, 7.64724491331730039e-01, "aps.04.01"], + [aps04_f, aps04_fp, aps04_fpp, (8, 0.2), [0, 5], np.inf, + 2.5, 8.17765433957942545e-01, "aps.04.02"], + [aps04_f, aps04_fp, aps04_fpp, (10, 0.2), [0, 5], np.inf, + 2.5, 8.51339922520784609e-01, "aps.04.03"], + [aps04_f, aps04_fp, aps04_fpp, (12, 0.2), [0, 5], np.inf, + 2.5, 8.74485272221167897e-01, "aps.04.04"], + [aps04_f, aps04_fp, aps04_fpp, (4, 1), [0, 5], np.inf, + 2.5, 1, "aps.04.05"], + [aps04_f, aps04_fp, aps04_fpp, (6, 1), [0, 5], np.inf, + 2.5, 1, "aps.04.06"], + [aps04_f, aps04_fp, aps04_fpp, (8, 1), [0, 5], np.inf, + 2.5, 1, "aps.04.07"], + [aps04_f, aps04_fp, aps04_fpp, (10, 1), [0, 5], np.inf, + 2.5, 1, "aps.04.08"], + [aps04_f, aps04_fp, aps04_fpp, (12, 1), [0, 5], np.inf, + 2.5, 1, "aps.04.09"], + [aps04_f, aps04_fp, aps04_fpp, (8, 1), [-0.95, 4.05], np.inf, + 1.5, 1, "aps.04.10"], + [aps04_f, aps04_fp, aps04_fpp, (10, 1), [-0.95, 4.05], np.inf, + 1.5, 1, "aps.04.11"], + [aps04_f, aps04_fp, aps04_fpp, (12, 1), [-0.95, 4.05], np.inf, + 1.5, 1, "aps.04.12"], + [aps04_f, aps04_fp, aps04_fpp, (14, 1), [-0.95, 4.05], np.inf, + 1.5, 1, "aps.04.13"], + [aps05_f, aps05_fp, aps05_fpp, (), [0, 1.5], np.inf, + 1.3, np.pi / 6, "aps.05.00"], + [aps06_f, aps06_fp, aps06_fpp, (1,), [0, 1], np.inf, + 0.5, 4.22477709641236709e-01, "aps.06.00"], + [aps06_f, aps06_fp, aps06_fpp, (2,), [0, 1], np.inf, + 0.5, 3.06699410483203705e-01, "aps.06.01"], + [aps06_f, aps06_fp, aps06_fpp, (3,), [0, 1], np.inf, + 0.5, 2.23705457654662959e-01, "aps.06.02"], + [aps06_f, aps06_fp, aps06_fpp, (4,), [0, 1], np.inf, + 0.5, 1.71719147519508369e-01, "aps.06.03"], + [aps06_f, aps06_fp, aps06_fpp, (5,), [0, 1], np.inf, + 0.4, 1.38257155056824066e-01, "aps.06.04"], + [aps06_f, aps06_fp, aps06_fpp, (20,), [0, 1], np.inf, + 0.1, 3.46573590208538521e-02, "aps.06.05"], + [aps06_f, aps06_fp, aps06_fpp, (40,), [0, 1], np.inf, + 5e-02, 1.73286795139986315e-02, "aps.06.06"], + [aps06_f, aps06_fp, aps06_fpp, (60,), [0, 1], np.inf, + 1.0 / 30, 1.15524530093324210e-02, "aps.06.07"], + [aps06_f, aps06_fp, aps06_fpp, (80,), [0, 1], np.inf, + 2.5e-02, 8.66433975699931573e-03, "aps.06.08"], + [aps06_f, aps06_fp, aps06_fpp, (100,), [0, 1], np.inf, + 2e-02, 6.93147180559945415e-03, "aps.06.09"], + [aps07_f, aps07_fp, aps07_fpp, (5,), [0, 1], np.inf, + 0.4, 3.84025518406218985e-02, "aps.07.00"], + [aps07_f, aps07_fp, aps07_fpp, (10,), [0, 1], np.inf, + 0.4, 9.90000999800049949e-03, "aps.07.01"], + [aps07_f, aps07_fp, aps07_fpp, (20,), [0, 1], np.inf, + 0.4, 2.49375003906201174e-03, "aps.07.02"], + [aps08_f, aps08_fp, aps08_fpp, (2,), [0, 1], np.inf, + 0.9, 0.5, "aps.08.00"], + [aps08_f, aps08_fp, aps08_fpp, (5,), [0, 1], np.inf, + 0.9, 3.45954815848242059e-01, "aps.08.01"], + [aps08_f, aps08_fp, aps08_fpp, (10,), [0, 1], np.inf, + 0.9, 2.45122333753307220e-01, "aps.08.02"], + [aps08_f, aps08_fp, aps08_fpp, (15,), [0, 1], np.inf, + 0.9, 1.95547623536565629e-01, "aps.08.03"], + [aps08_f, aps08_fp, aps08_fpp, (20,), [0, 1], np.inf, + 0.9, 1.64920957276440960e-01, "aps.08.04"], + [aps09_f, aps09_fp, aps09_fpp, (1,), [0, 1], np.inf, + 0.5, 2.75508040999484394e-01, "aps.09.00"], + [aps09_f, aps09_fp, aps09_fpp, (2,), [0, 1], np.inf, + 0.5, 1.37754020499742197e-01, "aps.09.01"], + [aps09_f, aps09_fp, aps09_fpp, (4,), [0, 1], np.inf, + 0.5, 1.03052837781564422e-02, "aps.09.02"], + [aps09_f, aps09_fp, aps09_fpp, (5,), [0, 1], np.inf, + 0.5, 3.61710817890406339e-03, "aps.09.03"], + [aps09_f, aps09_fp, aps09_fpp, (8,), [0, 1], np.inf, + 0.5, 4.10872918496395375e-04, "aps.09.04"], + [aps09_f, aps09_fp, aps09_fpp, (15,), [0, 1], np.inf, + 0.5, 2.59895758929076292e-05, "aps.09.05"], + [aps09_f, aps09_fp, aps09_fpp, (20,), [0, 1], np.inf, + 0.5, 7.66859512218533719e-06, "aps.09.06"], + [aps10_f, aps10_fp, aps10_fpp, (1,), [0, 1], np.inf, + 0.9, 4.01058137541547011e-01, "aps.10.00"], + [aps10_f, aps10_fp, aps10_fpp, (5,), [0, 1], np.inf, + 0.9, 5.16153518757933583e-01, "aps.10.01"], + [aps10_f, aps10_fp, aps10_fpp, (10,), [0, 1], np.inf, + 0.9, 5.39522226908415781e-01, "aps.10.02"], + [aps10_f, aps10_fp, aps10_fpp, (15,), [0, 1], np.inf, + 0.9, 5.48182294340655241e-01, "aps.10.03"], + [aps10_f, aps10_fp, aps10_fpp, (20,), [0, 1], np.inf, + 0.9, 5.52704666678487833e-01, "aps.10.04"], + [aps11_f, aps11_fp, aps11_fpp, (2,), [0.01, 1], np.inf, + 1e-02, 1.0 / 2, "aps.11.00"], + [aps11_f, aps11_fp, aps11_fpp, (5,), [0.01, 1], np.inf, + 1e-02, 1.0 / 5, "aps.11.01"], + [aps11_f, aps11_fp, aps11_fpp, (15,), [0.01, 1], np.inf, + 1e-02, 1.0 / 15, "aps.11.02"], + [aps11_f, aps11_fp, aps11_fpp, (20,), [0.01, 1], np.inf, + 1e-02, 1.0 / 20, "aps.11.03"], + [aps12_f, aps12_fp, aps12_fpp, (2,), [1, 100], np.inf, + 1.1, 2, "aps.12.00"], + [aps12_f, aps12_fp, aps12_fpp, (3,), [1, 100], np.inf, + 1.1, 3, "aps.12.01"], + [aps12_f, aps12_fp, aps12_fpp, (4,), [1, 100], np.inf, + 1.1, 4, "aps.12.02"], + [aps12_f, aps12_fp, aps12_fpp, (5,), [1, 100], np.inf, + 1.1, 5, "aps.12.03"], + [aps12_f, aps12_fp, aps12_fpp, (6,), [1, 100], np.inf, + 1.1, 6, "aps.12.04"], + [aps12_f, aps12_fp, aps12_fpp, (7,), [1, 100], np.inf, + 1.1, 7, "aps.12.05"], + [aps12_f, aps12_fp, aps12_fpp, (9,), [1, 100], np.inf, + 1.1, 9, "aps.12.06"], + [aps12_f, aps12_fp, aps12_fpp, (11,), [1, 100], np.inf, + 1.1, 11, "aps.12.07"], + [aps12_f, aps12_fp, aps12_fpp, (13,), [1, 100], np.inf, + 1.1, 13, "aps.12.08"], + [aps12_f, aps12_fp, aps12_fpp, (15,), [1, 100], np.inf, + 1.1, 15, "aps.12.09"], + [aps12_f, aps12_fp, aps12_fpp, (17,), [1, 100], np.inf, + 1.1, 17, "aps.12.10"], + [aps12_f, aps12_fp, aps12_fpp, (19,), [1, 100], np.inf, + 1.1, 19, "aps.12.11"], + [aps12_f, aps12_fp, aps12_fpp, (21,), [1, 100], np.inf, + 1.1, 21, "aps.12.12"], + [aps12_f, aps12_fp, aps12_fpp, (23,), [1, 100], np.inf, + 1.1, 23, "aps.12.13"], + [aps12_f, aps12_fp, aps12_fpp, (25,), [1, 100], np.inf, + 1.1, 25, "aps.12.14"], + [aps12_f, aps12_fp, aps12_fpp, (27,), [1, 100], np.inf, + 1.1, 27, "aps.12.15"], + [aps12_f, aps12_fp, aps12_fpp, (29,), [1, 100], np.inf, + 1.1, 29, "aps.12.16"], + [aps12_f, aps12_fp, aps12_fpp, (31,), [1, 100], np.inf, + 1.1, 31, "aps.12.17"], + [aps12_f, aps12_fp, aps12_fpp, (33,), [1, 100], np.inf, + 1.1, 33, "aps.12.18"], + [aps13_f, aps13_fp, aps13_fpp, (), [-1, 4], np.inf, + 1.5, 0, "aps.13.00"], + [aps14_f, aps14_fp, aps14_fpp, (1,), [-1000, np.pi / 2], 0, + 1, 6.23806518961612433e-01, "aps.14.00"], + [aps14_f, aps14_fp, aps14_fpp, (2,), [-1000, np.pi / 2], 0, + 1, 6.23806518961612433e-01, "aps.14.01"], + [aps14_f, aps14_fp, aps14_fpp, (3,), [-1000, np.pi / 2], 0, + 1, 6.23806518961612433e-01, "aps.14.02"], + [aps14_f, aps14_fp, aps14_fpp, (4,), [-1000, np.pi / 2], 0, + 1, 6.23806518961612433e-01, "aps.14.03"], + [aps14_f, aps14_fp, aps14_fpp, (5,), [-1000, np.pi / 2], 0, + 1, 6.23806518961612433e-01, "aps.14.04"], + [aps14_f, aps14_fp, aps14_fpp, (6,), [-1000, np.pi / 2], 0, + 1, 6.23806518961612433e-01, "aps.14.05"], + [aps14_f, aps14_fp, aps14_fpp, (7,), [-1000, np.pi / 2], 0, + 1, 6.23806518961612433e-01, "aps.14.06"], + [aps14_f, aps14_fp, aps14_fpp, (8,), [-1000, np.pi / 2], 0, + 1, 6.23806518961612433e-01, "aps.14.07"], + [aps14_f, aps14_fp, aps14_fpp, (9,), [-1000, np.pi / 2], 0, + 1, 6.23806518961612433e-01, "aps.14.08"], + [aps14_f, aps14_fp, aps14_fpp, (10,), [-1000, np.pi / 2], 0, + 1, 6.23806518961612433e-01, "aps.14.09"], + [aps14_f, aps14_fp, aps14_fpp, (11,), [-1000, np.pi / 2], 0, + 1, 6.23806518961612433e-01, "aps.14.10"], + [aps14_f, aps14_fp, aps14_fpp, (12,), [-1000, np.pi / 2], 0, + 1, 6.23806518961612433e-01, "aps.14.11"], + [aps14_f, aps14_fp, aps14_fpp, (13,), [-1000, np.pi / 2], 0, + 1, 6.23806518961612433e-01, "aps.14.12"], + [aps14_f, aps14_fp, aps14_fpp, (14,), [-1000, np.pi / 2], 0, + 1, 6.23806518961612433e-01, "aps.14.13"], + [aps14_f, aps14_fp, aps14_fpp, (15,), [-1000, np.pi / 2], 0, + 1, 6.23806518961612433e-01, "aps.14.14"], + [aps14_f, aps14_fp, aps14_fpp, (16,), [-1000, np.pi / 2], 0, + 1, 6.23806518961612433e-01, "aps.14.15"], + [aps14_f, aps14_fp, aps14_fpp, (17,), [-1000, np.pi / 2], 0, + 1, 6.23806518961612433e-01, "aps.14.16"], + [aps14_f, aps14_fp, aps14_fpp, (18,), [-1000, np.pi / 2], 0, + 1, 6.23806518961612433e-01, "aps.14.17"], + [aps14_f, aps14_fp, aps14_fpp, (19,), [-1000, np.pi / 2], 0, + 1, 6.23806518961612433e-01, "aps.14.18"], + [aps14_f, aps14_fp, aps14_fpp, (20,), [-1000, np.pi / 2], 0, + 1, 6.23806518961612433e-01, "aps.14.19"], + [aps14_f, aps14_fp, aps14_fpp, (21,), [-1000, np.pi / 2], 0, + 1, 6.23806518961612433e-01, "aps.14.20"], + [aps14_f, aps14_fp, aps14_fpp, (22,), [-1000, np.pi / 2], 0, + 1, 6.23806518961612433e-01, "aps.14.21"], + [aps14_f, aps14_fp, aps14_fpp, (23,), [-1000, np.pi / 2], 0, + 1, 6.23806518961612433e-01, "aps.14.22"], + [aps14_f, aps14_fp, aps14_fpp, (24,), [-1000, np.pi / 2], 0, + 1, 6.23806518961612433e-01, "aps.14.23"], + [aps14_f, aps14_fp, aps14_fpp, (25,), [-1000, np.pi / 2], 0, + 1, 6.23806518961612433e-01, "aps.14.24"], + [aps14_f, aps14_fp, aps14_fpp, (26,), [-1000, np.pi / 2], 0, + 1, 6.23806518961612433e-01, "aps.14.25"], + [aps14_f, aps14_fp, aps14_fpp, (27,), [-1000, np.pi / 2], 0, + 1, 6.23806518961612433e-01, "aps.14.26"], + [aps14_f, aps14_fp, aps14_fpp, (28,), [-1000, np.pi / 2], 0, + 1, 6.23806518961612433e-01, "aps.14.27"], + [aps14_f, aps14_fp, aps14_fpp, (29,), [-1000, np.pi / 2], 0, + 1, 6.23806518961612433e-01, "aps.14.28"], + [aps14_f, aps14_fp, aps14_fpp, (30,), [-1000, np.pi / 2], 0, + 1, 6.23806518961612433e-01, "aps.14.29"], + [aps14_f, aps14_fp, aps14_fpp, (31,), [-1000, np.pi / 2], 0, + 1, 6.23806518961612433e-01, "aps.14.30"], + [aps14_f, aps14_fp, aps14_fpp, (32,), [-1000, np.pi / 2], 0, + 1, 6.23806518961612433e-01, "aps.14.31"], + [aps14_f, aps14_fp, aps14_fpp, (33,), [-1000, np.pi / 2], 0, + 1, 6.23806518961612433e-01, "aps.14.32"], + [aps14_f, aps14_fp, aps14_fpp, (34,), [-1000, np.pi / 2], 0, + 1, 6.23806518961612433e-01, "aps.14.33"], + [aps14_f, aps14_fp, aps14_fpp, (35,), [-1000, np.pi / 2], 0, + 1, 6.23806518961612433e-01, "aps.14.34"], + [aps14_f, aps14_fp, aps14_fpp, (36,), [-1000, np.pi / 2], 0, + 1, 6.23806518961612433e-01, "aps.14.35"], + [aps14_f, aps14_fp, aps14_fpp, (37,), [-1000, np.pi / 2], 0, + 1, 6.23806518961612433e-01, "aps.14.36"], + [aps14_f, aps14_fp, aps14_fpp, (38,), [-1000, np.pi / 2], 0, + 1, 6.23806518961612433e-01, "aps.14.37"], + [aps14_f, aps14_fp, aps14_fpp, (39,), [-1000, np.pi / 2], 0, + 1, 6.23806518961612433e-01, "aps.14.38"], + [aps14_f, aps14_fp, aps14_fpp, (40,), [-1000, np.pi / 2], 0, + 1, 6.23806518961612433e-01, "aps.14.39"], + [aps15_f, aps15_fp, aps15_fpp, (20,), [-1000, 1e-4], 0, + -2, 5.90513055942197166e-05, "aps.15.00"], + [aps15_f, aps15_fp, aps15_fpp, (21,), [-1000, 1e-4], 0, + -2, 5.63671553399369967e-05, "aps.15.01"], + [aps15_f, aps15_fp, aps15_fpp, (22,), [-1000, 1e-4], 0, + -2, 5.39164094555919196e-05, "aps.15.02"], + [aps15_f, aps15_fp, aps15_fpp, (23,), [-1000, 1e-4], 0, + -2, 5.16698923949422470e-05, "aps.15.03"], + [aps15_f, aps15_fp, aps15_fpp, (24,), [-1000, 1e-4], 0, + -2, 4.96030966991445609e-05, "aps.15.04"], + [aps15_f, aps15_fp, aps15_fpp, (25,), [-1000, 1e-4], 0, + -2, 4.76952852876389951e-05, "aps.15.05"], + [aps15_f, aps15_fp, aps15_fpp, (26,), [-1000, 1e-4], 0, + -2, 4.59287932399486662e-05, "aps.15.06"], + [aps15_f, aps15_fp, aps15_fpp, (27,), [-1000, 1e-4], 0, + -2, 4.42884791956647841e-05, "aps.15.07"], + [aps15_f, aps15_fp, aps15_fpp, (28,), [-1000, 1e-4], 0, + -2, 4.27612902578832391e-05, "aps.15.08"], + [aps15_f, aps15_fp, aps15_fpp, (29,), [-1000, 1e-4], 0, + -2, 4.13359139159538030e-05, "aps.15.09"], + [aps15_f, aps15_fp, aps15_fpp, (30,), [-1000, 1e-4], 0, + -2, 4.00024973380198076e-05, "aps.15.10"], + [aps15_f, aps15_fp, aps15_fpp, (31,), [-1000, 1e-4], 0, + -2, 3.87524192962066869e-05, "aps.15.11"], + [aps15_f, aps15_fp, aps15_fpp, (32,), [-1000, 1e-4], 0, + -2, 3.75781035599579910e-05, "aps.15.12"], + [aps15_f, aps15_fp, aps15_fpp, (33,), [-1000, 1e-4], 0, + -2, 3.64728652199592355e-05, "aps.15.13"], + [aps15_f, aps15_fp, aps15_fpp, (34,), [-1000, 1e-4], 0, + -2, 3.54307833565318273e-05, "aps.15.14"], + [aps15_f, aps15_fp, aps15_fpp, (35,), [-1000, 1e-4], 0, + -2, 3.44465949299614980e-05, "aps.15.15"], + [aps15_f, aps15_fp, aps15_fpp, (36,), [-1000, 1e-4], 0, + -2, 3.35156058778003705e-05, "aps.15.16"], + [aps15_f, aps15_fp, aps15_fpp, (37,), [-1000, 1e-4], 0, + -2, 3.26336162494372125e-05, "aps.15.17"], + [aps15_f, aps15_fp, aps15_fpp, (38,), [-1000, 1e-4], 0, + -2, 3.17968568584260013e-05, "aps.15.18"], + [aps15_f, aps15_fp, aps15_fpp, (39,), [-1000, 1e-4], 0, + -2, 3.10019354369653455e-05, "aps.15.19"], + [aps15_f, aps15_fp, aps15_fpp, (40,), [-1000, 1e-4], 0, + -2, 3.02457906702100968e-05, "aps.15.20"], + [aps15_f, aps15_fp, aps15_fpp, (100,), [-1000, 1e-4], 0, + -2, 1.22779942324615231e-05, "aps.15.21"], + [aps15_f, aps15_fp, aps15_fpp, (200,), [-1000, 1e-4], 0, + -2, 6.16953939044086617e-06, "aps.15.22"], + [aps15_f, aps15_fp, aps15_fpp, (300,), [-1000, 1e-4], 0, + -2, 4.11985852982928163e-06, "aps.15.23"], + [aps15_f, aps15_fp, aps15_fpp, (400,), [-1000, 1e-4], 0, + -2, 3.09246238772721682e-06, "aps.15.24"], + [aps15_f, aps15_fp, aps15_fpp, (500,), [-1000, 1e-4], 0, + -2, 2.47520442610501789e-06, "aps.15.25"], + [aps15_f, aps15_fp, aps15_fpp, (600,), [-1000, 1e-4], 0, + -2, 2.06335676785127107e-06, "aps.15.26"], + [aps15_f, aps15_fp, aps15_fpp, (700,), [-1000, 1e-4], 0, + -2, 1.76901200781542651e-06, "aps.15.27"], + [aps15_f, aps15_fp, aps15_fpp, (800,), [-1000, 1e-4], 0, + -2, 1.54816156988591016e-06, "aps.15.28"], + [aps15_f, aps15_fp, aps15_fpp, (900,), [-1000, 1e-4], 0, + -2, 1.37633453660223511e-06, "aps.15.29"], + [aps15_f, aps15_fp, aps15_fpp, (1000,), [-1000, 1e-4], 0, + -2, 1.23883857889971403e-06, "aps.15.30"] +] + +_APS_TESTS_DICTS = [dict(zip(_APS_TESTS_KEYS, testcase)) for testcase in _APS_TESTS] + + +# ################## +# "complex" test cases +# A few simple, complex-valued, functions, defined on the complex plane. + + +def cplx01_f(z, n, a): + r"""z**n-a: Use to find the nth root of a""" + return z**n - a + + +def cplx01_fp(z, n, a): + return n * z**(n - 1) + + +def cplx01_fpp(z, n, a): + return n * (n - 1) * z**(n - 2) + + +def cplx02_f(z, a): + r"""e**z - a: Use to find the log of a""" + return np.exp(z) - a + + +def cplx02_fp(z, a): + return np.exp(z) + + +def cplx02_fpp(z, a): + return np.exp(z) + + +# Each "complex" test case has +# - a function and its two derivatives, +# - additional arguments, +# - the order of differentiability of the function on this interval +# - two starting values x0 and x1 +# - the root +# - an Identifier of the test case +# +# Algorithm 748 is a bracketing algorithm so a bracketing interval was provided +# in [1] for each test case. Newton and Halley need a single starting point +# x0, which was chosen to be near the middle of the interval, unless that +# would make the problem too easy. + + +_COMPLEX_TESTS_KEYS = [ + "f", "fprime", "fprime2", "args", "smoothness", "x0", "x1", "root", "ID" +] +_COMPLEX_TESTS = [ + [cplx01_f, cplx01_fp, cplx01_fpp, (2, -1), np.inf, + (1 + 1j), (0.5 + 0.5j), 1j, "complex.01.00"], + [cplx01_f, cplx01_fp, cplx01_fpp, (3, 1), np.inf, + (-1 + 1j), (-0.5 + 2.0j), (-0.5 + np.sqrt(3) / 2 * 1.0j), + "complex.01.01"], + [cplx01_f, cplx01_fp, cplx01_fpp, (3, -1), np.inf, + 1j, (0.5 + 0.5j), (0.5 + np.sqrt(3) / 2 * 1.0j), + "complex.01.02"], + [cplx01_f, cplx01_fp, cplx01_fpp, (3, 8), np.inf, + 5, 4, 2, "complex.01.03"], + [cplx02_f, cplx02_fp, cplx02_fpp, (-1,), np.inf, + (1 + 2j), (0.5 + 0.5j), np.pi * 1.0j, "complex.02.00"], + [cplx02_f, cplx02_fp, cplx02_fpp, (1j,), np.inf, + (1 + 2j), (0.5 + 0.5j), np.pi * 0.5j, "complex.02.01"], +] + +_COMPLEX_TESTS_DICTS = [ + dict(zip(_COMPLEX_TESTS_KEYS, testcase)) for testcase in _COMPLEX_TESTS +] + + +def _add_a_b(tests): + r"""Add "a" and "b" keys to each test from the "bracket" value""" + for d in tests: + for k, v in zip(['a', 'b'], d.get('bracket', [])): + d[k] = v + + +_add_a_b(_ORIGINAL_TESTS_DICTS) +_add_a_b(_APS_TESTS_DICTS) +_add_a_b(_COMPLEX_TESTS_DICTS) + + +def get_tests(collection='original', smoothness=None): + r"""Return the requested collection of test cases, as an array of dicts with subset-specific keys + + Allowed values of collection: + 'original': The original benchmarking functions. + Real-valued functions of real-valued inputs on an interval with a zero. + f1, .., f3 are continuous and infinitely differentiable + f4 has a single discontinuity at the root + f5 has a root at 1 replacing a 1st order pole + f6 is randomly positive on one side of the root, randomly negative on the other + 'aps': The test problems in the TOMS "Algorithm 748: Enclosing Zeros of Continuous Functions" + paper by Alefeld, Potra and Shi. Real-valued functions of + real-valued inputs on an interval with a zero. + Suitable for methods which start with an enclosing interval, and + derivatives up to 2nd order. + 'complex': Some complex-valued functions of complex-valued inputs. + No enclosing bracket is provided. + Suitable for methods which use one or more starting values, and + derivatives up to 2nd order. + + The dictionary keys will be a subset of + ["f", "fprime", "fprime2", "args", "bracket", "a", b", "smoothness", "x0", "x1", "root", "ID"] + """ # noqa: E501 + collection = collection or "original" + subsets = {"aps": _APS_TESTS_DICTS, + "complex": _COMPLEX_TESTS_DICTS, + "original": _ORIGINAL_TESTS_DICTS, + "chandrupatla": _CHANDRUPATLA_TESTS_DICTS} + tests = subsets.get(collection, []) + if smoothness is not None: + tests = [tc for tc in tests if tc['smoothness'] >= smoothness] + return tests + + +# Backwards compatibility +methods = [cc.bisect, cc.ridder, cc.brenth, cc.brentq] +mstrings = ['cc.bisect', 'cc.ridder', 'cc.brenth', 'cc.brentq'] +functions = [f2, f3, f4, f5, f6] +fstrings = ['f2', 'f3', 'f4', 'f5', 'f6'] + +# ################## +# "Chandrupatla" test cases +# Functions and test cases that appear in [2] + +def fun1(x): + return x**3 - 2*x - 5 +fun1.root = 2.0945514815423265 # additional precision using mpmath.findroot + + +def fun2(x): + return 1 - 1/x**2 +fun2.root = 1 + + +def fun3(x): + return (x-3)**3 +fun3.root = 3 + + +def fun4(x): + return 6*(x-2)**5 +fun4.root = 2 + + +def fun5(x): + return x**9 +fun5.root = 0 + + +def fun6(x): + return x**19 +fun6.root = 0 + + +def fun7(x): + xp = array_namespace(x) + return 0 if xp.abs(x) < 3.8e-4 else x*xp.exp(-x**(-2)) +fun7.root = 0 + + +def fun8(x): + xp = array_namespace(x) + xi = 0.61489 + return -(3062*(1-xi)*xp.exp(-x))/(xi + (1-xi)*xp.exp(-x)) - 1013 + 1628/x +fun8.root = 1.0375360332870405 + + +def fun9(x): + xp = array_namespace(x) + return xp.exp(x) - 2 - 0.01/x**2 + .000002/x**3 +fun9.root = 0.7032048403631358 + +# Each "chandropatla" test case has +# - a function, +# - two starting values x0 and x1 +# - the root +# - the number of function evaluations required by Chandrupatla's algorithm +# - an Identifier of the test case +# +# Chandrupatla's is a bracketing algorithm, so a bracketing interval was +# provided in [2] for each test case. No special support for testing with +# secant/Newton/Halley is provided. + +_CHANDRUPATLA_TESTS_KEYS = ["f", "bracket", "root", "nfeval", "ID"] +_CHANDRUPATLA_TESTS = [ + [fun1, [2, 3], fun1.root, 7], + [fun1, [1, 10], fun1.root, 11], + [fun1, [1, 100], fun1.root, 14], + [fun1, [-1e4, 1e4], fun1.root, 23], + [fun1, [-1e10, 1e10], fun1.root, 43], + [fun2, [0.5, 1.51], fun2.root, 8], + [fun2, [1e-4, 1e4], fun2.root, 22], + [fun2, [1e-6, 1e6], fun2.root, 28], + [fun2, [1e-10, 1e10], fun2.root, 41], + [fun2, [1e-12, 1e12], fun2.root, 48], + [fun3, [0, 5], fun3.root, 21], + [fun3, [-10, 10], fun3.root, 23], + [fun3, [-1e4, 1e4], fun3.root, 36], + [fun3, [-1e6, 1e6], fun3.root, 45], + [fun3, [-1e10, 1e10], fun3.root, 55], + [fun4, [0, 5], fun4.root, 21], + [fun4, [-10, 10], fun4.root, 23], + [fun4, [-1e4, 1e4], fun4.root, 33], + [fun4, [-1e6, 1e6], fun4.root, 43], + [fun4, [-1e10, 1e10], fun4.root, 54], + [fun5, [-1, 4], fun5.root, 21], + [fun5, [-2, 5], fun5.root, 22], + [fun5, [-1, 10], fun5.root, 23], + [fun5, [-5, 50], fun5.root, 25], + [fun5, [-10, 100], fun5.root, 26], + [fun6, [-1., 4.], fun6.root, 21], + [fun6, [-2., 5.], fun6.root, 22], + [fun6, [-1., 10.], fun6.root, 23], + [fun6, [-5., 50.], fun6.root, 25], + [fun6, [-10., 100.], fun6.root, 26], + [fun7, [-1, 4], fun7.root, 8], + [fun7, [-2, 5], fun7.root, 8], + [fun7, [-1, 10], fun7.root, 11], + [fun7, [-5, 50], fun7.root, 18], + [fun7, [-10, 100], fun7.root, 19], + [fun8, [2e-4, 2], fun8.root, 9], + [fun8, [2e-4, 3], fun8.root, 10], + [fun8, [2e-4, 9], fun8.root, 11], + [fun8, [2e-4, 27], fun8.root, 12], + [fun8, [2e-4, 81], fun8.root, 14], + [fun9, [2e-4, 1], fun9.root, 7], + [fun9, [2e-4, 3], fun9.root, 8], + [fun9, [2e-4, 9], fun9.root, 10], + [fun9, [2e-4, 27], fun9.root, 11], + [fun9, [2e-4, 81], fun9.root, 13], +] +_CHANDRUPATLA_TESTS = [test + [f'{test[0].__name__}.{i%5+1}'] + for i, test in enumerate(_CHANDRUPATLA_TESTS)] + +_CHANDRUPATLA_TESTS_DICTS = [dict(zip(_CHANDRUPATLA_TESTS_KEYS, testcase)) + for testcase in _CHANDRUPATLA_TESTS] +_add_a_b(_CHANDRUPATLA_TESTS_DICTS) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_zeros.cpython-310-x86_64-linux-gnu.so b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_zeros.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..7af3971d3d8f44903d9da2be40e4e414cbf6463d Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_zeros.cpython-310-x86_64-linux-gnu.so differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_zeros_py.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_zeros_py.py new file mode 100644 index 0000000000000000000000000000000000000000..2b96902ccbd58ed8fb6de3bbafe551f53fb8bf86 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/_zeros_py.py @@ -0,0 +1,1395 @@ +import warnings +from collections import namedtuple +import operator +from . import _zeros +from ._optimize import OptimizeResult +import numpy as np + + +_iter = 100 +_xtol = 2e-12 +_rtol = 4 * np.finfo(float).eps + +__all__ = ['newton', 'bisect', 'ridder', 'brentq', 'brenth', 'toms748', + 'RootResults'] + +# Must agree with CONVERGED, SIGNERR, CONVERR, ... in zeros.h +_ECONVERGED = 0 +_ESIGNERR = -1 # used in _chandrupatla +_ECONVERR = -2 +_EVALUEERR = -3 +_ECALLBACK = -4 +_EINPROGRESS = 1 + +CONVERGED = 'converged' +SIGNERR = 'sign error' +CONVERR = 'convergence error' +VALUEERR = 'value error' +INPROGRESS = 'No error' + + +flag_map = {_ECONVERGED: CONVERGED, _ESIGNERR: SIGNERR, _ECONVERR: CONVERR, + _EVALUEERR: VALUEERR, _EINPROGRESS: INPROGRESS} + + +class RootResults(OptimizeResult): + """Represents the root finding result. + + Attributes + ---------- + root : float + Estimated root location. + iterations : int + Number of iterations needed to find the root. + function_calls : int + Number of times the function was called. + converged : bool + True if the routine converged. + flag : str + Description of the cause of termination. + method : str + Root finding method used. + + """ + + def __init__(self, root, iterations, function_calls, flag, method): + self.root = root + self.iterations = iterations + self.function_calls = function_calls + self.converged = flag == _ECONVERGED + if flag in flag_map: + self.flag = flag_map[flag] + else: + self.flag = flag + self.method = method + + +def results_c(full_output, r, method): + if full_output: + x, funcalls, iterations, flag = r + results = RootResults(root=x, + iterations=iterations, + function_calls=funcalls, + flag=flag, method=method) + return x, results + else: + return r + + +def _results_select(full_output, r, method): + """Select from a tuple of (root, funccalls, iterations, flag)""" + x, funcalls, iterations, flag = r + if full_output: + results = RootResults(root=x, + iterations=iterations, + function_calls=funcalls, + flag=flag, method=method) + return x, results + return x + + +def _wrap_nan_raise(f): + + def f_raise(x, *args): + fx = f(x, *args) + f_raise._function_calls += 1 + if np.isnan(fx): + msg = (f'The function value at x={x} is NaN; ' + 'solver cannot continue.') + err = ValueError(msg) + err._x = x + err._function_calls = f_raise._function_calls + raise err + return fx + + f_raise._function_calls = 0 + return f_raise + + +def newton(func, x0, fprime=None, args=(), tol=1.48e-8, maxiter=50, + fprime2=None, x1=None, rtol=0.0, + full_output=False, disp=True): + """ + Find a root of a real or complex function using the Newton-Raphson + (or secant or Halley's) method. + + Find a root of the scalar-valued function `func` given a nearby scalar + starting point `x0`. + The Newton-Raphson method is used if the derivative `fprime` of `func` + is provided, otherwise the secant method is used. If the second order + derivative `fprime2` of `func` is also provided, then Halley's method is + used. + + If `x0` is a sequence with more than one item, `newton` returns an array: + the roots of the function from each (scalar) starting point in `x0`. + In this case, `func` must be vectorized to return a sequence or array of + the same shape as its first argument. If `fprime` (`fprime2`) is given, + then its return must also have the same shape: each element is the first + (second) derivative of `func` with respect to its only variable evaluated + at each element of its first argument. + + `newton` is for finding roots of a scalar-valued functions of a single + variable. For problems involving several variables, see `root`. + + Parameters + ---------- + func : callable + The function whose root is wanted. It must be a function of a + single variable of the form ``f(x,a,b,c...)``, where ``a,b,c...`` + are extra arguments that can be passed in the `args` parameter. + x0 : float, sequence, or ndarray + An initial estimate of the root that should be somewhere near the + actual root. If not scalar, then `func` must be vectorized and return + a sequence or array of the same shape as its first argument. + fprime : callable, optional + The derivative of the function when available and convenient. If it + is None (default), then the secant method is used. + args : tuple, optional + Extra arguments to be used in the function call. + tol : float, optional + The allowable error of the root's value. If `func` is complex-valued, + a larger `tol` is recommended as both the real and imaginary parts + of `x` contribute to ``|x - x0|``. + maxiter : int, optional + Maximum number of iterations. + fprime2 : callable, optional + The second order derivative of the function when available and + convenient. If it is None (default), then the normal Newton-Raphson + or the secant method is used. If it is not None, then Halley's method + is used. + x1 : float, optional + Another estimate of the root that should be somewhere near the + actual root. Used if `fprime` is not provided. + rtol : float, optional + Tolerance (relative) for termination. + full_output : bool, optional + If `full_output` is False (default), the root is returned. + If True and `x0` is scalar, the return value is ``(x, r)``, where ``x`` + is the root and ``r`` is a `RootResults` object. + If True and `x0` is non-scalar, the return value is ``(x, converged, + zero_der)`` (see Returns section for details). + disp : bool, optional + If True, raise a RuntimeError if the algorithm didn't converge, with + the error message containing the number of iterations and current + function value. Otherwise, the convergence status is recorded in a + `RootResults` return object. + Ignored if `x0` is not scalar. + *Note: this has little to do with displaying, however, + the `disp` keyword cannot be renamed for backwards compatibility.* + + Returns + ------- + root : float, sequence, or ndarray + Estimated location where function is zero. + r : `RootResults`, optional + Present if ``full_output=True`` and `x0` is scalar. + Object containing information about the convergence. In particular, + ``r.converged`` is True if the routine converged. + converged : ndarray of bool, optional + Present if ``full_output=True`` and `x0` is non-scalar. + For vector functions, indicates which elements converged successfully. + zero_der : ndarray of bool, optional + Present if ``full_output=True`` and `x0` is non-scalar. + For vector functions, indicates which elements had a zero derivative. + + See Also + -------- + root_scalar : interface to root solvers for scalar functions + root : interface to root solvers for multi-input, multi-output functions + + Notes + ----- + The convergence rate of the Newton-Raphson method is quadratic, + the Halley method is cubic, and the secant method is + sub-quadratic. This means that if the function is well-behaved + the actual error in the estimated root after the nth iteration + is approximately the square (cube for Halley) of the error + after the (n-1)th step. However, the stopping criterion used + here is the step size and there is no guarantee that a root + has been found. Consequently, the result should be verified. + Safer algorithms are brentq, brenth, ridder, and bisect, + but they all require that the root first be bracketed in an + interval where the function changes sign. The brentq algorithm + is recommended for general use in one dimensional problems + when such an interval has been found. + + When `newton` is used with arrays, it is best suited for the following + types of problems: + + * The initial guesses, `x0`, are all relatively the same distance from + the roots. + * Some or all of the extra arguments, `args`, are also arrays so that a + class of similar problems can be solved together. + * The size of the initial guesses, `x0`, is larger than O(100) elements. + Otherwise, a naive loop may perform as well or better than a vector. + + Examples + -------- + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy import optimize + + >>> def f(x): + ... return (x**3 - 1) # only one real root at x = 1 + + ``fprime`` is not provided, use the secant method: + + >>> root = optimize.newton(f, 1.5) + >>> root + 1.0000000000000016 + >>> root = optimize.newton(f, 1.5, fprime2=lambda x: 6 * x) + >>> root + 1.0000000000000016 + + Only ``fprime`` is provided, use the Newton-Raphson method: + + >>> root = optimize.newton(f, 1.5, fprime=lambda x: 3 * x**2) + >>> root + 1.0 + + Both ``fprime2`` and ``fprime`` are provided, use Halley's method: + + >>> root = optimize.newton(f, 1.5, fprime=lambda x: 3 * x**2, + ... fprime2=lambda x: 6 * x) + >>> root + 1.0 + + When we want to find roots for a set of related starting values and/or + function parameters, we can provide both of those as an array of inputs: + + >>> f = lambda x, a: x**3 - a + >>> fder = lambda x, a: 3 * x**2 + >>> rng = np.random.default_rng() + >>> x = rng.standard_normal(100) + >>> a = np.arange(-50, 50) + >>> vec_res = optimize.newton(f, x, fprime=fder, args=(a, ), maxiter=200) + + The above is the equivalent of solving for each value in ``(x, a)`` + separately in a for-loop, just faster: + + >>> loop_res = [optimize.newton(f, x0, fprime=fder, args=(a0,), + ... maxiter=200) + ... for x0, a0 in zip(x, a)] + >>> np.allclose(vec_res, loop_res) + True + + Plot the results found for all values of ``a``: + + >>> analytical_result = np.sign(a) * np.abs(a)**(1/3) + >>> fig, ax = plt.subplots() + >>> ax.plot(a, analytical_result, 'o') + >>> ax.plot(a, vec_res, '.') + >>> ax.set_xlabel('$a$') + >>> ax.set_ylabel('$x$ where $f(x, a)=0$') + >>> plt.show() + + """ + if tol <= 0: + raise ValueError(f"tol too small ({tol:g} <= 0)") + maxiter = operator.index(maxiter) + if maxiter < 1: + raise ValueError("maxiter must be greater than 0") + if np.size(x0) > 1: + return _array_newton(func, x0, fprime, args, tol, maxiter, fprime2, + full_output) + + # Convert to float (don't use float(x0); this works also for complex x0) + # Use np.asarray because we want x0 to be a numpy object, not a Python + # object. e.g. np.complex(1+1j) > 0 is possible, but (1 + 1j) > 0 raises + # a TypeError + x0 = np.asarray(x0)[()] * 1.0 + p0 = x0 + funcalls = 0 + if fprime is not None: + # Newton-Raphson method + method = "newton" + for itr in range(maxiter): + # first evaluate fval + fval = func(p0, *args) + funcalls += 1 + # If fval is 0, a root has been found, then terminate + if fval == 0: + return _results_select( + full_output, (p0, funcalls, itr, _ECONVERGED), method) + fder = fprime(p0, *args) + funcalls += 1 + if fder == 0: + msg = "Derivative was zero." + if disp: + msg += ( + " Failed to converge after %d iterations, value is %s." + % (itr + 1, p0)) + raise RuntimeError(msg) + warnings.warn(msg, RuntimeWarning, stacklevel=2) + return _results_select( + full_output, (p0, funcalls, itr + 1, _ECONVERR), method) + newton_step = fval / fder + if fprime2: + fder2 = fprime2(p0, *args) + funcalls += 1 + method = "halley" + # Halley's method: + # newton_step /= (1.0 - 0.5 * newton_step * fder2 / fder) + # Only do it if denominator stays close enough to 1 + # Rationale: If 1-adj < 0, then Halley sends x in the + # opposite direction to Newton. Doesn't happen if x is close + # enough to root. + adj = newton_step * fder2 / fder / 2 + if np.abs(adj) < 1: + newton_step /= 1.0 - adj + p = p0 - newton_step + if np.isclose(p, p0, rtol=rtol, atol=tol): + return _results_select( + full_output, (p, funcalls, itr + 1, _ECONVERGED), method) + p0 = p + else: + # Secant method + method = "secant" + if x1 is not None: + if x1 == x0: + raise ValueError("x1 and x0 must be different") + p1 = x1 + else: + eps = 1e-4 + p1 = x0 * (1 + eps) + p1 += (eps if p1 >= 0 else -eps) + q0 = func(p0, *args) + funcalls += 1 + q1 = func(p1, *args) + funcalls += 1 + if abs(q1) < abs(q0): + p0, p1, q0, q1 = p1, p0, q1, q0 + for itr in range(maxiter): + if q1 == q0: + if p1 != p0: + msg = f"Tolerance of {p1 - p0} reached." + if disp: + msg += ( + " Failed to converge after %d iterations, value is %s." + % (itr + 1, p1)) + raise RuntimeError(msg) + warnings.warn(msg, RuntimeWarning, stacklevel=2) + p = (p1 + p0) / 2.0 + return _results_select( + full_output, (p, funcalls, itr + 1, _ECONVERR), method) + else: + if abs(q1) > abs(q0): + p = (-q0 / q1 * p1 + p0) / (1 - q0 / q1) + else: + p = (-q1 / q0 * p0 + p1) / (1 - q1 / q0) + if np.isclose(p, p1, rtol=rtol, atol=tol): + return _results_select( + full_output, (p, funcalls, itr + 1, _ECONVERGED), method) + p0, q0 = p1, q1 + p1 = p + q1 = func(p1, *args) + funcalls += 1 + + if disp: + msg = ("Failed to converge after %d iterations, value is %s." + % (itr + 1, p)) + raise RuntimeError(msg) + + return _results_select(full_output, (p, funcalls, itr + 1, _ECONVERR), method) + + +def _array_newton(func, x0, fprime, args, tol, maxiter, fprime2, full_output): + """ + A vectorized version of Newton, Halley, and secant methods for arrays. + + Do not use this method directly. This method is called from `newton` + when ``np.size(x0) > 1`` is ``True``. For docstring, see `newton`. + """ + # Explicitly copy `x0` as `p` will be modified inplace, but the + # user's array should not be altered. + p = np.array(x0, copy=True) + + failures = np.ones_like(p, dtype=bool) + nz_der = np.ones_like(failures) + if fprime is not None: + # Newton-Raphson method + for iteration in range(maxiter): + # first evaluate fval + fval = np.asarray(func(p, *args)) + # If all fval are 0, all roots have been found, then terminate + if not fval.any(): + failures = fval.astype(bool) + break + fder = np.asarray(fprime(p, *args)) + nz_der = (fder != 0) + # stop iterating if all derivatives are zero + if not nz_der.any(): + break + # Newton step + dp = fval[nz_der] / fder[nz_der] + if fprime2 is not None: + fder2 = np.asarray(fprime2(p, *args)) + dp = dp / (1.0 - 0.5 * dp * fder2[nz_der] / fder[nz_der]) + # only update nonzero derivatives + p = np.asarray(p, dtype=np.result_type(p, dp, np.float64)) + p[nz_der] -= dp + failures[nz_der] = np.abs(dp) >= tol # items not yet converged + # stop iterating if there aren't any failures, not incl zero der + if not failures[nz_der].any(): + break + else: + # Secant method + dx = np.finfo(float).eps**0.33 + p1 = p * (1 + dx) + np.where(p >= 0, dx, -dx) + q0 = np.asarray(func(p, *args)) + q1 = np.asarray(func(p1, *args)) + active = np.ones_like(p, dtype=bool) + for iteration in range(maxiter): + nz_der = (q1 != q0) + # stop iterating if all derivatives are zero + if not nz_der.any(): + p = (p1 + p) / 2.0 + break + # Secant Step + dp = (q1 * (p1 - p))[nz_der] / (q1 - q0)[nz_der] + # only update nonzero derivatives + p = np.asarray(p, dtype=np.result_type(p, p1, dp, np.float64)) + p[nz_der] = p1[nz_der] - dp + active_zero_der = ~nz_der & active + p[active_zero_der] = (p1 + p)[active_zero_der] / 2.0 + active &= nz_der # don't assign zero derivatives again + failures[nz_der] = np.abs(dp) >= tol # not yet converged + # stop iterating if there aren't any failures, not incl zero der + if not failures[nz_der].any(): + break + p1, p = p, p1 + q0 = q1 + q1 = np.asarray(func(p1, *args)) + + zero_der = ~nz_der & failures # don't include converged with zero-ders + if zero_der.any(): + # Secant warnings + if fprime is None: + nonzero_dp = (p1 != p) + # non-zero dp, but infinite newton step + zero_der_nz_dp = (zero_der & nonzero_dp) + if zero_der_nz_dp.any(): + rms = np.sqrt( + sum((p1[zero_der_nz_dp] - p[zero_der_nz_dp]) ** 2) + ) + warnings.warn(f'RMS of {rms:g} reached', RuntimeWarning, stacklevel=3) + # Newton or Halley warnings + else: + all_or_some = 'all' if zero_der.all() else 'some' + msg = f'{all_or_some:s} derivatives were zero' + warnings.warn(msg, RuntimeWarning, stacklevel=3) + elif failures.any(): + all_or_some = 'all' if failures.all() else 'some' + msg = f'{all_or_some:s} failed to converge after {maxiter:d} iterations' + if failures.all(): + raise RuntimeError(msg) + warnings.warn(msg, RuntimeWarning, stacklevel=3) + + if full_output: + result = namedtuple('result', ('root', 'converged', 'zero_der')) + p = result(p, ~failures, zero_der) + + return p + + +def bisect(f, a, b, args=(), + xtol=_xtol, rtol=_rtol, maxiter=_iter, + full_output=False, disp=True): + """ + Find root of a function within an interval using bisection. + + Basic bisection routine to find a root of the function `f` between the + arguments `a` and `b`. `f(a)` and `f(b)` cannot have the same signs. + Slow but sure. + + Parameters + ---------- + f : function + Python function returning a number. `f` must be continuous, and + f(a) and f(b) must have opposite signs. + a : scalar + One end of the bracketing interval [a,b]. + b : scalar + The other end of the bracketing interval [a,b]. + xtol : number, optional + The computed root ``x0`` will satisfy ``np.allclose(x, x0, + atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The + parameter must be positive. + rtol : number, optional + The computed root ``x0`` will satisfy ``np.allclose(x, x0, + atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The + parameter cannot be smaller than its default value of + ``4*np.finfo(float).eps``. + maxiter : int, optional + If convergence is not achieved in `maxiter` iterations, an error is + raised. Must be >= 0. + args : tuple, optional + Containing extra arguments for the function `f`. + `f` is called by ``apply(f, (x)+args)``. + full_output : bool, optional + If `full_output` is False, the root is returned. If `full_output` is + True, the return value is ``(x, r)``, where x is the root, and r is + a `RootResults` object. + disp : bool, optional + If True, raise RuntimeError if the algorithm didn't converge. + Otherwise, the convergence status is recorded in a `RootResults` + return object. + + Returns + ------- + root : float + Root of `f` between `a` and `b`. + r : `RootResults` (present if ``full_output = True``) + Object containing information about the convergence. In particular, + ``r.converged`` is True if the routine converged. + + Examples + -------- + + >>> def f(x): + ... return (x**2 - 1) + + >>> from scipy import optimize + + >>> root = optimize.bisect(f, 0, 2) + >>> root + 1.0 + + >>> root = optimize.bisect(f, -2, 0) + >>> root + -1.0 + + See Also + -------- + brentq, brenth, bisect, newton + fixed_point : scalar fixed-point finder + fsolve : n-dimensional root-finding + + """ + if not isinstance(args, tuple): + args = (args,) + maxiter = operator.index(maxiter) + if xtol <= 0: + raise ValueError(f"xtol too small ({xtol:g} <= 0)") + if rtol < _rtol: + raise ValueError(f"rtol too small ({rtol:g} < {_rtol:g})") + f = _wrap_nan_raise(f) + r = _zeros._bisect(f, a, b, xtol, rtol, maxiter, args, full_output, disp) + return results_c(full_output, r, "bisect") + + +def ridder(f, a, b, args=(), + xtol=_xtol, rtol=_rtol, maxiter=_iter, + full_output=False, disp=True): + """ + Find a root of a function in an interval using Ridder's method. + + Parameters + ---------- + f : function + Python function returning a number. f must be continuous, and f(a) and + f(b) must have opposite signs. + a : scalar + One end of the bracketing interval [a,b]. + b : scalar + The other end of the bracketing interval [a,b]. + xtol : number, optional + The computed root ``x0`` will satisfy ``np.allclose(x, x0, + atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The + parameter must be positive. + rtol : number, optional + The computed root ``x0`` will satisfy ``np.allclose(x, x0, + atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The + parameter cannot be smaller than its default value of + ``4*np.finfo(float).eps``. + maxiter : int, optional + If convergence is not achieved in `maxiter` iterations, an error is + raised. Must be >= 0. + args : tuple, optional + Containing extra arguments for the function `f`. + `f` is called by ``apply(f, (x)+args)``. + full_output : bool, optional + If `full_output` is False, the root is returned. If `full_output` is + True, the return value is ``(x, r)``, where `x` is the root, and `r` is + a `RootResults` object. + disp : bool, optional + If True, raise RuntimeError if the algorithm didn't converge. + Otherwise, the convergence status is recorded in any `RootResults` + return object. + + Returns + ------- + root : float + Root of `f` between `a` and `b`. + r : `RootResults` (present if ``full_output = True``) + Object containing information about the convergence. + In particular, ``r.converged`` is True if the routine converged. + + See Also + -------- + brentq, brenth, bisect, newton : 1-D root-finding + fixed_point : scalar fixed-point finder + + Notes + ----- + Uses [Ridders1979]_ method to find a root of the function `f` between the + arguments `a` and `b`. Ridders' method is faster than bisection, but not + generally as fast as the Brent routines. [Ridders1979]_ provides the + classic description and source of the algorithm. A description can also be + found in any recent edition of Numerical Recipes. + + The routine used here diverges slightly from standard presentations in + order to be a bit more careful of tolerance. + + References + ---------- + .. [Ridders1979] + Ridders, C. F. J. "A New Algorithm for Computing a + Single Root of a Real Continuous Function." + IEEE Trans. Circuits Systems 26, 979-980, 1979. + + Examples + -------- + + >>> def f(x): + ... return (x**2 - 1) + + >>> from scipy import optimize + + >>> root = optimize.ridder(f, 0, 2) + >>> root + 1.0 + + >>> root = optimize.ridder(f, -2, 0) + >>> root + -1.0 + """ + if not isinstance(args, tuple): + args = (args,) + maxiter = operator.index(maxiter) + if xtol <= 0: + raise ValueError(f"xtol too small ({xtol:g} <= 0)") + if rtol < _rtol: + raise ValueError(f"rtol too small ({rtol:g} < {_rtol:g})") + f = _wrap_nan_raise(f) + r = _zeros._ridder(f, a, b, xtol, rtol, maxiter, args, full_output, disp) + return results_c(full_output, r, "ridder") + + +def brentq(f, a, b, args=(), + xtol=_xtol, rtol=_rtol, maxiter=_iter, + full_output=False, disp=True): + """ + Find a root of a function in a bracketing interval using Brent's method. + + Uses the classic Brent's method to find a root of the function `f` on + the sign changing interval [a , b]. Generally considered the best of the + rootfinding routines here. It is a safe version of the secant method that + uses inverse quadratic extrapolation. Brent's method combines root + bracketing, interval bisection, and inverse quadratic interpolation. It is + sometimes known as the van Wijngaarden-Dekker-Brent method. Brent (1973) + claims convergence is guaranteed for functions computable within [a,b]. + + [Brent1973]_ provides the classic description of the algorithm. Another + description can be found in a recent edition of Numerical Recipes, including + [PressEtal1992]_. A third description is at + http://mathworld.wolfram.com/BrentsMethod.html. It should be easy to + understand the algorithm just by reading our code. Our code diverges a bit + from standard presentations: we choose a different formula for the + extrapolation step. + + Parameters + ---------- + f : function + Python function returning a number. The function :math:`f` + must be continuous, and :math:`f(a)` and :math:`f(b)` must + have opposite signs. + a : scalar + One end of the bracketing interval :math:`[a, b]`. + b : scalar + The other end of the bracketing interval :math:`[a, b]`. + xtol : number, optional + The computed root ``x0`` will satisfy ``np.allclose(x, x0, + atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The + parameter must be positive. For nice functions, Brent's + method will often satisfy the above condition with ``xtol/2`` + and ``rtol/2``. [Brent1973]_ + rtol : number, optional + The computed root ``x0`` will satisfy ``np.allclose(x, x0, + atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The + parameter cannot be smaller than its default value of + ``4*np.finfo(float).eps``. For nice functions, Brent's + method will often satisfy the above condition with ``xtol/2`` + and ``rtol/2``. [Brent1973]_ + maxiter : int, optional + If convergence is not achieved in `maxiter` iterations, an error is + raised. Must be >= 0. + args : tuple, optional + Containing extra arguments for the function `f`. + `f` is called by ``apply(f, (x)+args)``. + full_output : bool, optional + If `full_output` is False, the root is returned. If `full_output` is + True, the return value is ``(x, r)``, where `x` is the root, and `r` is + a `RootResults` object. + disp : bool, optional + If True, raise RuntimeError if the algorithm didn't converge. + Otherwise, the convergence status is recorded in any `RootResults` + return object. + + Returns + ------- + root : float + Root of `f` between `a` and `b`. + r : `RootResults` (present if ``full_output = True``) + Object containing information about the convergence. In particular, + ``r.converged`` is True if the routine converged. + + See Also + -------- + fmin, fmin_powell, fmin_cg, fmin_bfgs, fmin_ncg : multivariate local optimizers + leastsq : nonlinear least squares minimizer + fmin_l_bfgs_b, fmin_tnc, fmin_cobyla : constrained multivariate optimizers + basinhopping, differential_evolution, brute : global optimizers + fminbound, brent, golden, bracket : local scalar minimizers + fsolve : N-D root-finding + brenth, ridder, bisect, newton : 1-D root-finding + fixed_point : scalar fixed-point finder + + Notes + ----- + `f` must be continuous. f(a) and f(b) must have opposite signs. + + References + ---------- + .. [Brent1973] + Brent, R. P., + *Algorithms for Minimization Without Derivatives*. + Englewood Cliffs, NJ: Prentice-Hall, 1973. Ch. 3-4. + + .. [PressEtal1992] + Press, W. H.; Flannery, B. P.; Teukolsky, S. A.; and Vetterling, W. T. + *Numerical Recipes in FORTRAN: The Art of Scientific Computing*, 2nd ed. + Cambridge, England: Cambridge University Press, pp. 352-355, 1992. + Section 9.3: "Van Wijngaarden-Dekker-Brent Method." + + Examples + -------- + >>> def f(x): + ... return (x**2 - 1) + + >>> from scipy import optimize + + >>> root = optimize.brentq(f, -2, 0) + >>> root + -1.0 + + >>> root = optimize.brentq(f, 0, 2) + >>> root + 1.0 + """ + if not isinstance(args, tuple): + args = (args,) + maxiter = operator.index(maxiter) + if xtol <= 0: + raise ValueError(f"xtol too small ({xtol:g} <= 0)") + if rtol < _rtol: + raise ValueError(f"rtol too small ({rtol:g} < {_rtol:g})") + f = _wrap_nan_raise(f) + r = _zeros._brentq(f, a, b, xtol, rtol, maxiter, args, full_output, disp) + return results_c(full_output, r, "brentq") + + +def brenth(f, a, b, args=(), + xtol=_xtol, rtol=_rtol, maxiter=_iter, + full_output=False, disp=True): + """Find a root of a function in a bracketing interval using Brent's + method with hyperbolic extrapolation. + + A variation on the classic Brent routine to find a root of the function f + between the arguments a and b that uses hyperbolic extrapolation instead of + inverse quadratic extrapolation. Bus & Dekker (1975) guarantee convergence + for this method, claiming that the upper bound of function evaluations here + is 4 or 5 times that of bisection. + f(a) and f(b) cannot have the same signs. Generally, on a par with the + brent routine, but not as heavily tested. It is a safe version of the + secant method that uses hyperbolic extrapolation. + The version here is by Chuck Harris, and implements Algorithm M of + [BusAndDekker1975]_, where further details (convergence properties, + additional remarks and such) can be found + + Parameters + ---------- + f : function + Python function returning a number. f must be continuous, and f(a) and + f(b) must have opposite signs. + a : scalar + One end of the bracketing interval [a,b]. + b : scalar + The other end of the bracketing interval [a,b]. + xtol : number, optional + The computed root ``x0`` will satisfy ``np.allclose(x, x0, + atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The + parameter must be positive. As with `brentq`, for nice + functions the method will often satisfy the above condition + with ``xtol/2`` and ``rtol/2``. + rtol : number, optional + The computed root ``x0`` will satisfy ``np.allclose(x, x0, + atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The + parameter cannot be smaller than its default value of + ``4*np.finfo(float).eps``. As with `brentq`, for nice functions + the method will often satisfy the above condition with + ``xtol/2`` and ``rtol/2``. + maxiter : int, optional + If convergence is not achieved in `maxiter` iterations, an error is + raised. Must be >= 0. + args : tuple, optional + Containing extra arguments for the function `f`. + `f` is called by ``apply(f, (x)+args)``. + full_output : bool, optional + If `full_output` is False, the root is returned. If `full_output` is + True, the return value is ``(x, r)``, where `x` is the root, and `r` is + a `RootResults` object. + disp : bool, optional + If True, raise RuntimeError if the algorithm didn't converge. + Otherwise, the convergence status is recorded in any `RootResults` + return object. + + Returns + ------- + root : float + Root of `f` between `a` and `b`. + r : `RootResults` (present if ``full_output = True``) + Object containing information about the convergence. In particular, + ``r.converged`` is True if the routine converged. + + See Also + -------- + fmin, fmin_powell, fmin_cg, fmin_bfgs, fmin_ncg : multivariate local optimizers + leastsq : nonlinear least squares minimizer + fmin_l_bfgs_b, fmin_tnc, fmin_cobyla : constrained multivariate optimizers + basinhopping, differential_evolution, brute : global optimizers + fminbound, brent, golden, bracket : local scalar minimizers + fsolve : N-D root-finding + brentq, ridder, bisect, newton : 1-D root-finding + fixed_point : scalar fixed-point finder + + References + ---------- + .. [BusAndDekker1975] + Bus, J. C. P., Dekker, T. J., + "Two Efficient Algorithms with Guaranteed Convergence for Finding a Zero + of a Function", ACM Transactions on Mathematical Software, Vol. 1, Issue + 4, Dec. 1975, pp. 330-345. Section 3: "Algorithm M". + :doi:`10.1145/355656.355659` + + Examples + -------- + >>> def f(x): + ... return (x**2 - 1) + + >>> from scipy import optimize + + >>> root = optimize.brenth(f, -2, 0) + >>> root + -1.0 + + >>> root = optimize.brenth(f, 0, 2) + >>> root + 1.0 + + """ + if not isinstance(args, tuple): + args = (args,) + maxiter = operator.index(maxiter) + if xtol <= 0: + raise ValueError(f"xtol too small ({xtol:g} <= 0)") + if rtol < _rtol: + raise ValueError(f"rtol too small ({rtol:g} < {_rtol:g})") + f = _wrap_nan_raise(f) + r = _zeros._brenth(f, a, b, xtol, rtol, maxiter, args, full_output, disp) + return results_c(full_output, r, "brenth") + + +################################ +# TOMS "Algorithm 748: Enclosing Zeros of Continuous Functions", by +# Alefeld, G. E. and Potra, F. A. and Shi, Yixun, +# See [1] + + +def _notclose(fs, rtol=_rtol, atol=_xtol): + # Ensure not None, not 0, all finite, and not very close to each other + notclosefvals = ( + all(fs) and all(np.isfinite(fs)) and + not any(any(np.isclose(_f, fs[i + 1:], rtol=rtol, atol=atol)) + for i, _f in enumerate(fs[:-1]))) + return notclosefvals + + +def _secant(xvals, fvals): + """Perform a secant step, taking a little care""" + # Secant has many "mathematically" equivalent formulations + # x2 = x0 - (x1 - x0)/(f1 - f0) * f0 + # = x1 - (x1 - x0)/(f1 - f0) * f1 + # = (-x1 * f0 + x0 * f1) / (f1 - f0) + # = (-f0 / f1 * x1 + x0) / (1 - f0 / f1) + # = (-f1 / f0 * x0 + x1) / (1 - f1 / f0) + x0, x1 = xvals[:2] + f0, f1 = fvals[:2] + if f0 == f1: + return np.nan + if np.abs(f1) > np.abs(f0): + x2 = (-f0 / f1 * x1 + x0) / (1 - f0 / f1) + else: + x2 = (-f1 / f0 * x0 + x1) / (1 - f1 / f0) + return x2 + + +def _update_bracket(ab, fab, c, fc): + """Update a bracket given (c, fc), return the discarded endpoints.""" + fa, fb = fab + idx = (0 if np.sign(fa) * np.sign(fc) > 0 else 1) + rx, rfx = ab[idx], fab[idx] + fab[idx] = fc + ab[idx] = c + return rx, rfx + + +def _compute_divided_differences(xvals, fvals, N=None, full=True, + forward=True): + """Return a matrix of divided differences for the xvals, fvals pairs + + DD[i, j] = f[x_{i-j}, ..., x_i] for 0 <= j <= i + + If full is False, just return the main diagonal(or last row): + f[a], f[a, b] and f[a, b, c]. + If forward is False, return f[c], f[b, c], f[a, b, c].""" + if full: + if forward: + xvals = np.asarray(xvals) + else: + xvals = np.array(xvals)[::-1] + M = len(xvals) + N = M if N is None else min(N, M) + DD = np.zeros([M, N]) + DD[:, 0] = fvals[:] + for i in range(1, N): + DD[i:, i] = (np.diff(DD[i - 1:, i - 1]) / + (xvals[i:] - xvals[:M - i])) + return DD + + xvals = np.asarray(xvals) + dd = np.array(fvals) + row = np.array(fvals) + idx2Use = (0 if forward else -1) + dd[0] = fvals[idx2Use] + for i in range(1, len(xvals)): + denom = xvals[i:i + len(row) - 1] - xvals[:len(row) - 1] + row = np.diff(row)[:] / denom + dd[i] = row[idx2Use] + return dd + + +def _interpolated_poly(xvals, fvals, x): + """Compute p(x) for the polynomial passing through the specified locations. + + Use Neville's algorithm to compute p(x) where p is the minimal degree + polynomial passing through the points xvals, fvals""" + xvals = np.asarray(xvals) + N = len(xvals) + Q = np.zeros([N, N]) + D = np.zeros([N, N]) + Q[:, 0] = fvals[:] + D[:, 0] = fvals[:] + for k in range(1, N): + alpha = D[k:, k - 1] - Q[k - 1:N - 1, k - 1] + diffik = xvals[0:N - k] - xvals[k:N] + Q[k:, k] = (xvals[k:] - x) / diffik * alpha + D[k:, k] = (xvals[:N - k] - x) / diffik * alpha + # Expect Q[-1, 1:] to be small relative to Q[-1, 0] as x approaches a root + return np.sum(Q[-1, 1:]) + Q[-1, 0] + + +def _inverse_poly_zero(a, b, c, d, fa, fb, fc, fd): + """Inverse cubic interpolation f-values -> x-values + + Given four points (fa, a), (fb, b), (fc, c), (fd, d) with + fa, fb, fc, fd all distinct, find poly IP(y) through the 4 points + and compute x=IP(0). + """ + return _interpolated_poly([fa, fb, fc, fd], [a, b, c, d], 0) + + +def _newton_quadratic(ab, fab, d, fd, k): + """Apply Newton-Raphson like steps, using divided differences to approximate f' + + ab is a real interval [a, b] containing a root, + fab holds the real values of f(a), f(b) + d is a real number outside [ab, b] + k is the number of steps to apply + """ + a, b = ab + fa, fb = fab + _, B, A = _compute_divided_differences([a, b, d], [fa, fb, fd], + forward=True, full=False) + + # _P is the quadratic polynomial through the 3 points + def _P(x): + # Horner evaluation of fa + B * (x - a) + A * (x - a) * (x - b) + return (A * (x - b) + B) * (x - a) + fa + + if A == 0: + r = a - fa / B + else: + r = (a if np.sign(A) * np.sign(fa) > 0 else b) + # Apply k Newton-Raphson steps to _P(x), starting from x=r + for i in range(k): + r1 = r - _P(r) / (B + A * (2 * r - a - b)) + if not (ab[0] < r1 < ab[1]): + if (ab[0] < r < ab[1]): + return r + r = sum(ab) / 2.0 + break + r = r1 + + return r + + +class TOMS748Solver: + """Solve f(x, *args) == 0 using Algorithm748 of Alefeld, Potro & Shi. + """ + _MU = 0.5 + _K_MIN = 1 + _K_MAX = 100 # A very high value for real usage. Expect 1, 2, maybe 3. + + def __init__(self): + self.f = None + self.args = None + self.function_calls = 0 + self.iterations = 0 + self.k = 2 + # ab=[a,b] is a global interval containing a root + self.ab = [np.nan, np.nan] + # fab is function values at a, b + self.fab = [np.nan, np.nan] + self.d = None + self.fd = None + self.e = None + self.fe = None + self.disp = False + self.xtol = _xtol + self.rtol = _rtol + self.maxiter = _iter + + def configure(self, xtol, rtol, maxiter, disp, k): + self.disp = disp + self.xtol = xtol + self.rtol = rtol + self.maxiter = maxiter + # Silently replace a low value of k with 1 + self.k = max(k, self._K_MIN) + # Noisily replace a high value of k with self._K_MAX + if self.k > self._K_MAX: + msg = "toms748: Overriding k: ->%d" % self._K_MAX + warnings.warn(msg, RuntimeWarning, stacklevel=3) + self.k = self._K_MAX + + def _callf(self, x, error=True): + """Call the user-supplied function, update book-keeping""" + fx = self.f(x, *self.args) + self.function_calls += 1 + if not np.isfinite(fx) and error: + raise ValueError(f"Invalid function value: f({x:f}) -> {fx} ") + return fx + + def get_result(self, x, flag=_ECONVERGED): + r"""Package the result and statistics into a tuple.""" + return (x, self.function_calls, self.iterations, flag) + + def _update_bracket(self, c, fc): + return _update_bracket(self.ab, self.fab, c, fc) + + def start(self, f, a, b, args=()): + r"""Prepare for the iterations.""" + self.function_calls = 0 + self.iterations = 0 + + self.f = f + self.args = args + self.ab[:] = [a, b] + if not np.isfinite(a) or np.imag(a) != 0: + raise ValueError(f"Invalid x value: {a} ") + if not np.isfinite(b) or np.imag(b) != 0: + raise ValueError(f"Invalid x value: {b} ") + + fa = self._callf(a) + if not np.isfinite(fa) or np.imag(fa) != 0: + raise ValueError(f"Invalid function value: f({a:f}) -> {fa} ") + if fa == 0: + return _ECONVERGED, a + fb = self._callf(b) + if not np.isfinite(fb) or np.imag(fb) != 0: + raise ValueError(f"Invalid function value: f({b:f}) -> {fb} ") + if fb == 0: + return _ECONVERGED, b + + if np.sign(fb) * np.sign(fa) > 0: + raise ValueError("f(a) and f(b) must have different signs, but " + f"f({a:e})={fa:e}, f({b:e})={fb:e} ") + self.fab[:] = [fa, fb] + + return _EINPROGRESS, sum(self.ab) / 2.0 + + def get_status(self): + """Determine the current status.""" + a, b = self.ab[:2] + if np.isclose(a, b, rtol=self.rtol, atol=self.xtol): + return _ECONVERGED, sum(self.ab) / 2.0 + if self.iterations >= self.maxiter: + return _ECONVERR, sum(self.ab) / 2.0 + return _EINPROGRESS, sum(self.ab) / 2.0 + + def iterate(self): + """Perform one step in the algorithm. + + Implements Algorithm 4.1(k=1) or 4.2(k=2) in [APS1995] + """ + self.iterations += 1 + eps = np.finfo(float).eps + d, fd, e, fe = self.d, self.fd, self.e, self.fe + ab_width = self.ab[1] - self.ab[0] # Need the start width below + c = None + + for nsteps in range(2, self.k+2): + # If the f-values are sufficiently separated, perform an inverse + # polynomial interpolation step. Otherwise, nsteps repeats of + # an approximate Newton-Raphson step. + if _notclose(self.fab + [fd, fe], rtol=0, atol=32*eps): + c0 = _inverse_poly_zero(self.ab[0], self.ab[1], d, e, + self.fab[0], self.fab[1], fd, fe) + if self.ab[0] < c0 < self.ab[1]: + c = c0 + if c is None: + c = _newton_quadratic(self.ab, self.fab, d, fd, nsteps) + + fc = self._callf(c) + if fc == 0: + return _ECONVERGED, c + + # re-bracket + e, fe = d, fd + d, fd = self._update_bracket(c, fc) + + # u is the endpoint with the smallest f-value + uix = (0 if np.abs(self.fab[0]) < np.abs(self.fab[1]) else 1) + u, fu = self.ab[uix], self.fab[uix] + + _, A = _compute_divided_differences(self.ab, self.fab, + forward=(uix == 0), full=False) + c = u - 2 * fu / A + if np.abs(c - u) > 0.5 * (self.ab[1] - self.ab[0]): + c = sum(self.ab) / 2.0 + else: + if np.isclose(c, u, rtol=eps, atol=0): + # c didn't change (much). + # Either because the f-values at the endpoints have vastly + # differing magnitudes, or because the root is very close to + # that endpoint + frs = np.frexp(self.fab)[1] + if frs[uix] < frs[1 - uix] - 50: # Differ by more than 2**50 + c = (31 * self.ab[uix] + self.ab[1 - uix]) / 32 + else: + # Make a bigger adjustment, about the + # size of the requested tolerance. + mm = (1 if uix == 0 else -1) + adj = mm * np.abs(c) * self.rtol + mm * self.xtol + c = u + adj + if not self.ab[0] < c < self.ab[1]: + c = sum(self.ab) / 2.0 + + fc = self._callf(c) + if fc == 0: + return _ECONVERGED, c + + e, fe = d, fd + d, fd = self._update_bracket(c, fc) + + # If the width of the new interval did not decrease enough, bisect + if self.ab[1] - self.ab[0] > self._MU * ab_width: + e, fe = d, fd + z = sum(self.ab) / 2.0 + fz = self._callf(z) + if fz == 0: + return _ECONVERGED, z + d, fd = self._update_bracket(z, fz) + + # Record d and e for next iteration + self.d, self.fd = d, fd + self.e, self.fe = e, fe + + status, xn = self.get_status() + return status, xn + + def solve(self, f, a, b, args=(), + xtol=_xtol, rtol=_rtol, k=2, maxiter=_iter, disp=True): + r"""Solve f(x) = 0 given an interval containing a root.""" + self.configure(xtol=xtol, rtol=rtol, maxiter=maxiter, disp=disp, k=k) + status, xn = self.start(f, a, b, args) + if status == _ECONVERGED: + return self.get_result(xn) + + # The first step only has two x-values. + c = _secant(self.ab, self.fab) + if not self.ab[0] < c < self.ab[1]: + c = sum(self.ab) / 2.0 + fc = self._callf(c) + if fc == 0: + return self.get_result(c) + + self.d, self.fd = self._update_bracket(c, fc) + self.e, self.fe = None, None + self.iterations += 1 + + while True: + status, xn = self.iterate() + if status == _ECONVERGED: + return self.get_result(xn) + if status == _ECONVERR: + fmt = "Failed to converge after %d iterations, bracket is %s" + if disp: + msg = fmt % (self.iterations + 1, self.ab) + raise RuntimeError(msg) + return self.get_result(xn, _ECONVERR) + + +def toms748(f, a, b, args=(), k=1, + xtol=_xtol, rtol=_rtol, maxiter=_iter, + full_output=False, disp=True): + """ + Find a root using TOMS Algorithm 748 method. + + Implements the Algorithm 748 method of Alefeld, Potro and Shi to find a + root of the function `f` on the interval ``[a , b]``, where ``f(a)`` and + `f(b)` must have opposite signs. + + It uses a mixture of inverse cubic interpolation and + "Newton-quadratic" steps. [APS1995]. + + Parameters + ---------- + f : function + Python function returning a scalar. The function :math:`f` + must be continuous, and :math:`f(a)` and :math:`f(b)` + have opposite signs. + a : scalar, + lower boundary of the search interval + b : scalar, + upper boundary of the search interval + args : tuple, optional + containing extra arguments for the function `f`. + `f` is called by ``f(x, *args)``. + k : int, optional + The number of Newton quadratic steps to perform each + iteration. ``k>=1``. + xtol : scalar, optional + The computed root ``x0`` will satisfy ``np.allclose(x, x0, + atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The + parameter must be positive. + rtol : scalar, optional + The computed root ``x0`` will satisfy ``np.allclose(x, x0, + atol=xtol, rtol=rtol)``, where ``x`` is the exact root. + maxiter : int, optional + If convergence is not achieved in `maxiter` iterations, an error is + raised. Must be >= 0. + full_output : bool, optional + If `full_output` is False, the root is returned. If `full_output` is + True, the return value is ``(x, r)``, where `x` is the root, and `r` is + a `RootResults` object. + disp : bool, optional + If True, raise RuntimeError if the algorithm didn't converge. + Otherwise, the convergence status is recorded in the `RootResults` + return object. + + Returns + ------- + root : float + Approximate root of `f` + r : `RootResults` (present if ``full_output = True``) + Object containing information about the convergence. In particular, + ``r.converged`` is True if the routine converged. + + See Also + -------- + brentq, brenth, ridder, bisect, newton + fsolve : find roots in N dimensions. + + Notes + ----- + `f` must be continuous. + Algorithm 748 with ``k=2`` is asymptotically the most efficient + algorithm known for finding roots of a four times continuously + differentiable function. + In contrast with Brent's algorithm, which may only decrease the length of + the enclosing bracket on the last step, Algorithm 748 decreases it each + iteration with the same asymptotic efficiency as it finds the root. + + For easy statement of efficiency indices, assume that `f` has 4 + continuous deriviatives. + For ``k=1``, the convergence order is at least 2.7, and with about + asymptotically 2 function evaluations per iteration, the efficiency + index is approximately 1.65. + For ``k=2``, the order is about 4.6 with asymptotically 3 function + evaluations per iteration, and the efficiency index 1.66. + For higher values of `k`, the efficiency index approaches + the kth root of ``(3k-2)``, hence ``k=1`` or ``k=2`` are + usually appropriate. + + References + ---------- + .. [APS1995] + Alefeld, G. E. and Potra, F. A. and Shi, Yixun, + *Algorithm 748: Enclosing Zeros of Continuous Functions*, + ACM Trans. Math. Softw. Volume 221(1995) + doi = {10.1145/210089.210111} + + Examples + -------- + >>> def f(x): + ... return (x**3 - 1) # only one real root at x = 1 + + >>> from scipy import optimize + >>> root, results = optimize.toms748(f, 0, 2, full_output=True) + >>> root + 1.0 + >>> results + converged: True + flag: converged + function_calls: 11 + iterations: 5 + root: 1.0 + method: toms748 + """ + if xtol <= 0: + raise ValueError(f"xtol too small ({xtol:g} <= 0)") + if rtol < _rtol / 4: + raise ValueError(f"rtol too small ({rtol:g} < {_rtol/4:g})") + maxiter = operator.index(maxiter) + if maxiter < 1: + raise ValueError("maxiter must be greater than 0") + if not np.isfinite(a): + raise ValueError(f"a is not finite {a}") + if not np.isfinite(b): + raise ValueError(f"b is not finite {b}") + if a >= b: + raise ValueError(f"a and b are not an interval [{a}, {b}]") + if not k >= 1: + raise ValueError(f"k too small ({k} < 1)") + + if not isinstance(args, tuple): + args = (args,) + f = _wrap_nan_raise(f) + solver = TOMS748Solver() + result = solver.solve(f, a, b, args=args, k=k, xtol=xtol, rtol=rtol, + maxiter=maxiter, disp=disp) + x, function_calls, iterations, flag = result + return _results_select(full_output, (x, function_calls, iterations, flag), + "toms748") diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/cobyla.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/cobyla.py new file mode 100644 index 0000000000000000000000000000000000000000..87d111d8fc1634e54d3766a3f1c58abd37ac58cb --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/cobyla.py @@ -0,0 +1,19 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.optimize` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'OptimizeResult', + 'fmin_cobyla', +] + +def __dir__(): + return __all__ + +def __getattr__(name): + return _sub_module_deprecation(sub_package="optimize", module="cobyla", + private_modules=["_cobyla_py"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/cython_optimize.pxd b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/cython_optimize.pxd new file mode 100644 index 0000000000000000000000000000000000000000..d35f8da68b34d3a587f3a99326770d8550a2135c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/cython_optimize.pxd @@ -0,0 +1,11 @@ +# Public Cython API declarations +# +# See doc/source/dev/contributor/public_cython_api.rst for guidelines + + +# The following cimport statement provides legacy ABI +# support. Changing it causes an ABI forward-compatibility break +# (gh-11793), so we currently leave it as is (no further cimport +# statements should be used in this file). +from scipy.optimize.cython_optimize._zeros cimport ( + brentq, brenth, ridder, bisect, zeros_full_output) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/cython_optimize/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/cython_optimize/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a07250bbeb06542721480c42005307992558fced --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/cython_optimize/__init__.py @@ -0,0 +1,133 @@ +""" +Cython optimize root finding API +================================ +The underlying C functions for the following root finders can be accessed +directly using Cython: + +- `~scipy.optimize.bisect` +- `~scipy.optimize.ridder` +- `~scipy.optimize.brenth` +- `~scipy.optimize.brentq` + +The Cython API for the root finding functions is similar except there is no +``disp`` argument. Import the root finding functions using ``cimport`` from +`scipy.optimize.cython_optimize`. :: + + from scipy.optimize.cython_optimize cimport bisect, ridder, brentq, brenth + + +Callback signature +------------------ +The zeros functions in `~scipy.optimize.cython_optimize` expect a callback that +takes a double for the scalar independent variable as the 1st argument and a +user defined ``struct`` with any extra parameters as the 2nd argument. :: + + double (*callback_type)(double, void*) noexcept + + +Examples +-------- +Usage of `~scipy.optimize.cython_optimize` requires Cython to write callbacks +that are compiled into C. For more information on compiling Cython, see the +`Cython Documentation `_. + +These are the basic steps: + +1. Create a Cython ``.pyx`` file, for example: ``myexample.pyx``. +2. Import the desired root finder from `~scipy.optimize.cython_optimize`. +3. Write the callback function, and call the selected root finding function + passing the callback, any extra arguments, and the other solver + parameters. :: + + from scipy.optimize.cython_optimize cimport brentq + + # import math from Cython + from libc cimport math + + myargs = {'C0': 1.0, 'C1': 0.7} # a dictionary of extra arguments + XLO, XHI = 0.5, 1.0 # lower and upper search boundaries + XTOL, RTOL, MITR = 1e-3, 1e-3, 10 # other solver parameters + + # user-defined struct for extra parameters + ctypedef struct test_params: + double C0 + double C1 + + + # user-defined callback + cdef double f(double x, void *args) noexcept: + cdef test_params *myargs = args + return myargs.C0 - math.exp(-(x - myargs.C1)) + + + # Cython wrapper function + cdef double brentq_wrapper_example(dict args, double xa, double xb, + double xtol, double rtol, int mitr): + # Cython automatically casts dictionary to struct + cdef test_params myargs = args + return brentq( + f, xa, xb, &myargs, xtol, rtol, mitr, NULL) + + + # Python function + def brentq_example(args=myargs, xa=XLO, xb=XHI, xtol=XTOL, rtol=RTOL, + mitr=MITR): + '''Calls Cython wrapper from Python.''' + return brentq_wrapper_example(args, xa, xb, xtol, rtol, mitr) + +4. If you want to call your function from Python, create a Cython wrapper, and + a Python function that calls the wrapper, or use ``cpdef``. Then, in Python, + you can import and run the example. :: + + from myexample import brentq_example + + x = brentq_example() + # 0.6999942848231314 + +5. Create a Cython ``.pxd`` file if you need to export any Cython functions. + + +Full output +----------- +The functions in `~scipy.optimize.cython_optimize` can also copy the full +output from the solver to a C ``struct`` that is passed as its last argument. +If you don't want the full output, just pass ``NULL``. The full output +``struct`` must be type ``zeros_full_output``, which is defined in +`scipy.optimize.cython_optimize` with the following fields: + +- ``int funcalls``: number of function calls +- ``int iterations``: number of iterations +- ``int error_num``: error number +- ``double root``: root of function + +The root is copied by `~scipy.optimize.cython_optimize` to the full output +``struct``. An error number of -1 means a sign error, -2 means a convergence +error, and 0 means the solver converged. Continuing from the previous example:: + + from scipy.optimize.cython_optimize cimport zeros_full_output + + + # cython brentq solver with full output + cdef zeros_full_output brentq_full_output_wrapper_example( + dict args, double xa, double xb, double xtol, double rtol, + int mitr): + cdef test_params myargs = args + cdef zeros_full_output my_full_output + # use my_full_output instead of NULL + brentq(f, xa, xb, &myargs, xtol, rtol, mitr, &my_full_output) + return my_full_output + + + # Python function + def brent_full_output_example(args=myargs, xa=XLO, xb=XHI, xtol=XTOL, + rtol=RTOL, mitr=MITR): + '''Returns full output''' + return brentq_full_output_wrapper_example(args, xa, xb, xtol, rtol, + mitr) + + result = brent_full_output_example() + # {'error_num': 0, + # 'funcalls': 6, + # 'iterations': 5, + # 'root': 0.6999942848231314} +""" diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/cython_optimize/_zeros.pxd b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/cython_optimize/_zeros.pxd new file mode 100644 index 0000000000000000000000000000000000000000..d3c9e98f0a24d80d15d1f7052f690d608f66dd80 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/cython_optimize/_zeros.pxd @@ -0,0 +1,33 @@ +# Legacy public Cython API declarations +# +# NOTE: due to the way Cython ABI compatibility works, **no changes +# should be made to this file** --- any API additions/changes should be +# done in `cython_optimize.pxd` (see gh-11793). + +ctypedef double (*callback_type)(double, void*) noexcept + +ctypedef struct zeros_parameters: + callback_type function + void* args + +ctypedef struct zeros_full_output: + int funcalls + int iterations + int error_num + double root + +cdef double bisect(callback_type f, double xa, double xb, void* args, + double xtol, double rtol, int iter, + zeros_full_output *full_output) noexcept nogil + +cdef double ridder(callback_type f, double xa, double xb, void* args, + double xtol, double rtol, int iter, + zeros_full_output *full_output) noexcept nogil + +cdef double brenth(callback_type f, double xa, double xb, void* args, + double xtol, double rtol, int iter, + zeros_full_output *full_output) noexcept nogil + +cdef double brentq(callback_type f, double xa, double xb, void* args, + double xtol, double rtol, int iter, + zeros_full_output *full_output) noexcept nogil diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/cython_optimize/c_zeros.pxd b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/cython_optimize/c_zeros.pxd new file mode 100644 index 0000000000000000000000000000000000000000..0d83c80eb886846ddbbd6927e37e05812911f856 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/cython_optimize/c_zeros.pxd @@ -0,0 +1,26 @@ +cdef extern from "../Zeros/zeros.h": + ctypedef double (*callback_type)(double, void*) noexcept + ctypedef struct scipy_zeros_info: + int funcalls + int iterations + int error_num + +cdef extern from "../Zeros/bisect.c" nogil: + double bisect(callback_type f, double xa, double xb, double xtol, + double rtol, int iter, void *func_data_param, + scipy_zeros_info *solver_stats) + +cdef extern from "../Zeros/ridder.c" nogil: + double ridder(callback_type f, double xa, double xb, double xtol, + double rtol, int iter, void *func_data_param, + scipy_zeros_info *solver_stats) + +cdef extern from "../Zeros/brenth.c" nogil: + double brenth(callback_type f, double xa, double xb, double xtol, + double rtol, int iter, void *func_data_param, + scipy_zeros_info *solver_stats) + +cdef extern from "../Zeros/brentq.c" nogil: + double brentq(callback_type f, double xa, double xb, double xtol, + double rtol, int iter, void *func_data_param, + scipy_zeros_info *solver_stats) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/elementwise.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/elementwise.py new file mode 100644 index 0000000000000000000000000000000000000000..f7be4484626880182a17acf883d72388937578d1 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/elementwise.py @@ -0,0 +1,38 @@ +""" +=================================================================== +Elementwise Scalar Optimization (:mod:`scipy.optimize.elementwise`) +=================================================================== + +.. currentmodule:: scipy.optimize.elementwise + +This module provides a collection of functions for root finding and +minimization of scalar, real-valued functions of one variable. Unlike their +counterparts in the base :mod:`scipy.optimize` namespace, these functions work +elementwise, enabling the solution of many related problems in an efficient, +vectorized call. Furthermore, when environment variable ``SCIPY_ARRAY_API=1``, +these functions can accept non-NumPy, array API standard compatible arrays and +perform all calculations using the corresponding array library (e.g. PyTorch, +JAX, CuPy). + +Root finding +============ + +.. autosummary:: + :toctree: generated/ + + find_root + bracket_root + +Minimization +============ + +.. autosummary:: + :toctree: generated/ + + find_minimum + bracket_minimum + +""" +from ._elementwise import find_root, find_minimum, bracket_root, bracket_minimum # noqa: F401, E501 + +__all__ = ["find_root", "find_minimum", "bracket_root", "bracket_minimum"] diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/lbfgsb.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/lbfgsb.py new file mode 100644 index 0000000000000000000000000000000000000000..866407cabb3decf0ff72239e6fd372f69f7550c0 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/lbfgsb.py @@ -0,0 +1,23 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.optimize` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'LbfgsInvHessProduct', + 'OptimizeResult', + 'fmin_l_bfgs_b', + 'zeros', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="optimize", module="lbfgsb", + private_modules=["_lbfgsb_py"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/linesearch.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/linesearch.py new file mode 100644 index 0000000000000000000000000000000000000000..cb34b25092da34991c868683da3d6a894d1a7f80 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/linesearch.py @@ -0,0 +1,18 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.optimize` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = ["line_search"] # noqa: F822 + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="optimize", module="linesearch", + private_modules=["_linesearch"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/minpack.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/minpack.py new file mode 100644 index 0000000000000000000000000000000000000000..29fddef537361d8508e6343d23b2c3c7d6d12ec6 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/minpack.py @@ -0,0 +1,27 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.optimize` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'OptimizeResult', + 'OptimizeWarning', + 'curve_fit', + 'fixed_point', + 'fsolve', + 'least_squares', + 'leastsq', + 'zeros', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="optimize", module="minpack", + private_modules=["_minpack_py"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/minpack2.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/minpack2.py new file mode 100644 index 0000000000000000000000000000000000000000..cdb3503e0e1e4c886c89bfb62e6a2efc3ba54549 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/minpack2.py @@ -0,0 +1,17 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.optimize` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__: list[str] = [] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="optimize", module="minpack2", + private_modules=["_minpack2"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/moduleTNC.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/moduleTNC.py new file mode 100644 index 0000000000000000000000000000000000000000..3fc5884ed5c39437b7681395419d641443a1fdb8 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/moduleTNC.py @@ -0,0 +1,19 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.optimize` namespace for importing the functions +# included below. + + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="optimize", module="moduleTNC", + private_modules=["_moduleTNC"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/nonlin.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/nonlin.py new file mode 100644 index 0000000000000000000000000000000000000000..20b490b40ef790a2943d539790b45fc378df2c76 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/nonlin.py @@ -0,0 +1,29 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.optimize` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'BroydenFirst', + 'InverseJacobian', + 'KrylovJacobian', + 'anderson', + 'broyden1', + 'broyden2', + 'diagbroyden', + 'excitingmixing', + 'linearmixing', + 'newton_krylov', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="optimize", module="nonlin", + private_modules=["_nonlin"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/optimize.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/optimize.py new file mode 100644 index 0000000000000000000000000000000000000000..4db770e5f6e921906c916f2650003d92f5507791 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/optimize.py @@ -0,0 +1,40 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.optimize` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'OptimizeResult', + 'OptimizeWarning', + 'approx_fprime', + 'bracket', + 'brent', + 'brute', + 'check_grad', + 'fmin', + 'fmin_bfgs', + 'fmin_cg', + 'fmin_ncg', + 'fmin_powell', + 'fminbound', + 'golden', + 'line_search', + 'rosen', + 'rosen_der', + 'rosen_hess', + 'rosen_hess_prod', + 'show_options', + 'zeros', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="optimize", module="optimize", + private_modules=["_optimize"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/slsqp.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/slsqp.py new file mode 100644 index 0000000000000000000000000000000000000000..c2b77d2eb447527cd91e92907e06ad53dd1ad3d8 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/slsqp.py @@ -0,0 +1,23 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.optimize` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'OptimizeResult', + 'fmin_slsqp', + 'slsqp', + 'zeros', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="optimize", module="slsqp", + private_modules=["_slsqp_py"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/_cython_examples/extending.pyx b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/_cython_examples/extending.pyx new file mode 100644 index 0000000000000000000000000000000000000000..d831b3c7f5dcaee71371027c7ee95aa9ee51d157 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/_cython_examples/extending.pyx @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 +#cython: language_level=3 +#cython: boundscheck=False +#cython: wraparound=False +""" +Taken from docstring for scipy.optimize.cython_optimize module. +""" + +from scipy.optimize.cython_optimize cimport brentq + +# import math from Cython +from libc cimport math + +myargs = {'C0': 1.0, 'C1': 0.7} # a dictionary of extra arguments +XLO, XHI = 0.5, 1.0 # lower and upper search boundaries +XTOL, RTOL, MITR = 1e-3, 1e-3, 10 # other solver parameters + +# user-defined struct for extra parameters +ctypedef struct test_params: + double C0 + double C1 + + +# user-defined callback +cdef double f(double x, void *args) noexcept: + cdef test_params *myargs = args + return myargs.C0 - math.exp(-(x - myargs.C1)) + + +# Cython wrapper function +cdef double brentq_wrapper_example(dict args, double xa, double xb, + double xtol, double rtol, int mitr): + # Cython automatically casts dictionary to struct + cdef test_params myargs = args + return brentq( + f, xa, xb, &myargs, xtol, rtol, mitr, NULL) + + +# Python function +def brentq_example(args=myargs, xa=XLO, xb=XHI, xtol=XTOL, rtol=RTOL, + mitr=MITR): + '''Calls Cython wrapper from Python.''' + return brentq_wrapper_example(args, xa, xb, xtol, rtol, mitr) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/_cython_examples/meson.build b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/_cython_examples/meson.build new file mode 100644 index 0000000000000000000000000000000000000000..1fb210fbecb84a21518ad8828a789376410f02aa --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/_cython_examples/meson.build @@ -0,0 +1,32 @@ +project('random-build-examples', 'c', 'cpp', 'cython') + +fs = import('fs') + +py3 = import('python').find_installation(pure: false) + +cy = meson.get_compiler('cython') + +if not cy.version().version_compare('>=3.0.8') + error('tests requires Cython >= 3.0.8') +endif + +cython_args = [] +if cy.version().version_compare('>=3.1.0') + cython_args += ['-Xfreethreading_compatible=True'] +endif + +py3.extension_module( + 'extending', + 'extending.pyx', + cython_args: cython_args, + install: false, +) + +extending_cpp = fs.copyfile('extending.pyx', 'extending_cpp.pyx') +py3.extension_module( + 'extending_cpp', + extending_cpp, + cython_args: cython_args, + install: false, + override_options : ['cython_language=cpp'] +) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test__basinhopping.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test__basinhopping.py new file mode 100644 index 0000000000000000000000000000000000000000..80729460ee6aa596d7dc2c398ce43ff4aacc7bff --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test__basinhopping.py @@ -0,0 +1,535 @@ +""" +Unit tests for the basin hopping global minimization algorithm. +""" +import copy + +from numpy.testing import (assert_almost_equal, assert_equal, assert_, + assert_allclose) +import pytest +from pytest import raises as assert_raises +import numpy as np +from numpy import cos, sin + +from scipy.optimize import basinhopping, OptimizeResult +from scipy.optimize._basinhopping import ( + Storage, RandomDisplacement, Metropolis, AdaptiveStepsize) + + +def func1d(x): + f = cos(14.5 * x - 0.3) + (x + 0.2) * x + df = np.array(-14.5 * sin(14.5 * x - 0.3) + 2. * x + 0.2) + return f, df + + +def func2d_nograd(x): + f = cos(14.5 * x[0] - 0.3) + (x[1] + 0.2) * x[1] + (x[0] + 0.2) * x[0] + return f + + +def func2d(x): + f = cos(14.5 * x[0] - 0.3) + (x[1] + 0.2) * x[1] + (x[0] + 0.2) * x[0] + df = np.zeros(2) + df[0] = -14.5 * sin(14.5 * x[0] - 0.3) + 2. * x[0] + 0.2 + df[1] = 2. * x[1] + 0.2 + return f, df + + +def func2d_easyderiv(x): + f = 2.0*x[0]**2 + 2.0*x[0]*x[1] + 2.0*x[1]**2 - 6.0*x[0] + df = np.zeros(2) + df[0] = 4.0*x[0] + 2.0*x[1] - 6.0 + df[1] = 2.0*x[0] + 4.0*x[1] + + return f, df + + +class MyTakeStep1(RandomDisplacement): + """use a copy of displace, but have it set a special parameter to + make sure it's actually being used.""" + def __init__(self): + self.been_called = False + super().__init__() + + def __call__(self, x): + self.been_called = True + return super().__call__(x) + + +def myTakeStep2(x): + """redo RandomDisplacement in function form without the attribute stepsize + to make sure everything still works ok + """ + s = 0.5 + x += np.random.uniform(-s, s, np.shape(x)) + return x + + +class MyAcceptTest: + """pass a custom accept test + + This does nothing but make sure it's being used and ensure all the + possible return values are accepted + """ + def __init__(self): + self.been_called = False + self.ncalls = 0 + self.testres = [False, 'force accept', True, np.bool_(True), + np.bool_(False), [], {}, 0, 1] + + def __call__(self, **kwargs): + self.been_called = True + self.ncalls += 1 + if self.ncalls - 1 < len(self.testres): + return self.testres[self.ncalls - 1] + else: + return True + + +class MyCallBack: + """pass a custom callback function + + This makes sure it's being used. It also returns True after 10 + steps to ensure that it's stopping early. + + """ + def __init__(self): + self.been_called = False + self.ncalls = 0 + + def __call__(self, x, f, accepted): + self.been_called = True + self.ncalls += 1 + if self.ncalls == 10: + return True + + +class TestBasinHopping: + + def setup_method(self): + """ Tests setup. + + Run tests based on the 1-D and 2-D functions described above. + """ + self.x0 = (1.0, [1.0, 1.0]) + self.sol = (-0.195, np.array([-0.195, -0.1])) + + self.tol = 3 # number of decimal places + + self.niter = 100 + self.disp = False + + self.kwargs = {"method": "L-BFGS-B", "jac": True} + self.kwargs_nograd = {"method": "L-BFGS-B"} + + def test_TypeError(self): + # test the TypeErrors are raised on bad input + i = 1 + # if take_step is passed, it must be callable + assert_raises(TypeError, basinhopping, func2d, self.x0[i], + take_step=1) + # if accept_test is passed, it must be callable + assert_raises(TypeError, basinhopping, func2d, self.x0[i], + accept_test=1) + + def test_input_validation(self): + msg = 'target_accept_rate has to be in range \\(0, 1\\)' + with assert_raises(ValueError, match=msg): + basinhopping(func1d, self.x0[0], target_accept_rate=0.) + with assert_raises(ValueError, match=msg): + basinhopping(func1d, self.x0[0], target_accept_rate=1.) + + msg = 'stepwise_factor has to be in range \\(0, 1\\)' + with assert_raises(ValueError, match=msg): + basinhopping(func1d, self.x0[0], stepwise_factor=0.) + with assert_raises(ValueError, match=msg): + basinhopping(func1d, self.x0[0], stepwise_factor=1.) + + def test_1d_grad(self): + # test 1-D minimizations with gradient + i = 0 + res = basinhopping(func1d, self.x0[i], minimizer_kwargs=self.kwargs, + niter=self.niter, disp=self.disp) + assert_almost_equal(res.x, self.sol[i], self.tol) + + def test_2d(self): + # test 2d minimizations with gradient + i = 1 + res = basinhopping(func2d, self.x0[i], minimizer_kwargs=self.kwargs, + niter=self.niter, disp=self.disp) + assert_almost_equal(res.x, self.sol[i], self.tol) + assert_(res.nfev > 0) + + def test_njev(self): + # test njev is returned correctly + i = 1 + minimizer_kwargs = self.kwargs.copy() + # L-BFGS-B doesn't use njev, but BFGS does + minimizer_kwargs["method"] = "BFGS" + res = basinhopping(func2d, self.x0[i], + minimizer_kwargs=minimizer_kwargs, niter=self.niter, + disp=self.disp) + assert_(res.nfev > 0) + assert_equal(res.nfev, res.njev) + + def test_jac(self): + # test Jacobian returned + minimizer_kwargs = self.kwargs.copy() + # BFGS returns a Jacobian + minimizer_kwargs["method"] = "BFGS" + + res = basinhopping(func2d_easyderiv, [0.0, 0.0], + minimizer_kwargs=minimizer_kwargs, niter=self.niter, + disp=self.disp) + + assert_(hasattr(res.lowest_optimization_result, "jac")) + + # in this case, the Jacobian is just [df/dx, df/dy] + _, jacobian = func2d_easyderiv(res.x) + assert_almost_equal(res.lowest_optimization_result.jac, jacobian, + self.tol) + + def test_2d_nograd(self): + # test 2-D minimizations without gradient + i = 1 + res = basinhopping(func2d_nograd, self.x0[i], + minimizer_kwargs=self.kwargs_nograd, + niter=self.niter, disp=self.disp) + assert_almost_equal(res.x, self.sol[i], self.tol) + + @pytest.mark.fail_slow(10) + def test_all_minimizers(self): + # Test 2-D minimizations with gradient. Nelder-Mead, Powell, COBYLA, and + # COBYQA don't accept jac=True, so aren't included here. + i = 1 + methods = ['CG', 'BFGS', 'Newton-CG', 'L-BFGS-B', 'TNC', 'SLSQP'] + minimizer_kwargs = copy.copy(self.kwargs) + for method in methods: + minimizer_kwargs["method"] = method + res = basinhopping(func2d, self.x0[i], + minimizer_kwargs=minimizer_kwargs, + niter=self.niter, disp=self.disp) + assert_almost_equal(res.x, self.sol[i], self.tol) + + @pytest.mark.fail_slow(20) + def test_all_nograd_minimizers(self): + # Test 2-D minimizations without gradient. Newton-CG requires jac=True, + # so not included here. + i = 1 + methods = ['CG', 'BFGS', 'L-BFGS-B', 'TNC', 'SLSQP', + 'Nelder-Mead', 'Powell', 'COBYLA', 'COBYQA'] + minimizer_kwargs = copy.copy(self.kwargs_nograd) + for method in methods: + # COBYQA takes extensive amount of time on this problem + niter = 10 if method == 'COBYQA' else self.niter + minimizer_kwargs["method"] = method + res = basinhopping(func2d_nograd, self.x0[i], + minimizer_kwargs=minimizer_kwargs, + niter=niter, disp=self.disp, seed=1234) + tol = self.tol + if method == 'COBYLA': + tol = 2 + assert_almost_equal(res.x, self.sol[i], decimal=tol) + + def test_pass_takestep(self): + # test that passing a custom takestep works + # also test that the stepsize is being adjusted + takestep = MyTakeStep1() + initial_step_size = takestep.stepsize + i = 1 + res = basinhopping(func2d, self.x0[i], minimizer_kwargs=self.kwargs, + niter=self.niter, disp=self.disp, + take_step=takestep) + assert_almost_equal(res.x, self.sol[i], self.tol) + assert_(takestep.been_called) + # make sure that the build in adaptive step size has been used + assert_(initial_step_size != takestep.stepsize) + + def test_pass_simple_takestep(self): + # test that passing a custom takestep without attribute stepsize + takestep = myTakeStep2 + i = 1 + res = basinhopping(func2d_nograd, self.x0[i], + minimizer_kwargs=self.kwargs_nograd, + niter=self.niter, disp=self.disp, + take_step=takestep) + assert_almost_equal(res.x, self.sol[i], self.tol) + + def test_pass_accept_test(self): + # test passing a custom accept test + # makes sure it's being used and ensures all the possible return values + # are accepted. + accept_test = MyAcceptTest() + i = 1 + # there's no point in running it more than a few steps. + basinhopping(func2d, self.x0[i], minimizer_kwargs=self.kwargs, + niter=10, disp=self.disp, accept_test=accept_test) + assert_(accept_test.been_called) + + def test_pass_callback(self): + # test passing a custom callback function + # This makes sure it's being used. It also returns True after 10 steps + # to ensure that it's stopping early. + callback = MyCallBack() + i = 1 + # there's no point in running it more than a few steps. + res = basinhopping(func2d, self.x0[i], minimizer_kwargs=self.kwargs, + niter=30, disp=self.disp, callback=callback) + assert_(callback.been_called) + assert_("callback" in res.message[0]) + # One of the calls of MyCallBack is during BasinHoppingRunner + # construction, so there are only 9 remaining before MyCallBack stops + # the minimization. + assert_equal(res.nit, 9) + + def test_minimizer_fail(self): + # test if a minimizer fails + i = 1 + self.kwargs["options"] = dict(maxiter=0) + self.niter = 10 + res = basinhopping(func2d, self.x0[i], minimizer_kwargs=self.kwargs, + niter=self.niter, disp=self.disp) + # the number of failed minimizations should be the number of + # iterations + 1 + assert_equal(res.nit + 1, res.minimization_failures) + + def test_niter_zero(self): + # gh5915, what happens if you call basinhopping with niter=0 + i = 0 + basinhopping(func1d, self.x0[i], minimizer_kwargs=self.kwargs, + niter=0, disp=self.disp) + + def test_rng_reproducibility(self): + # rng should ensure reproducibility between runs + minimizer_kwargs = {"method": "L-BFGS-B", "jac": True} + + f_1 = [] + + def callback(x, f, accepted): + f_1.append(f) + + basinhopping(func2d, [1.0, 1.0], minimizer_kwargs=minimizer_kwargs, + niter=10, callback=callback, rng=10) + + f_2 = [] + + def callback2(x, f, accepted): + f_2.append(f) + + basinhopping(func2d, [1.0, 1.0], minimizer_kwargs=minimizer_kwargs, + niter=10, callback=callback2, rng=10) + assert_equal(np.array(f_1), np.array(f_2)) + + def test_random_gen(self): + # check that np.random.Generator can be used (numpy >= 1.17) + rng = np.random.default_rng(1) + + minimizer_kwargs = {"method": "L-BFGS-B", "jac": True} + + res1 = basinhopping(func2d, [1.0, 1.0], + minimizer_kwargs=minimizer_kwargs, + niter=10, rng=rng) + + rng = np.random.default_rng(1) + res2 = basinhopping(func2d, [1.0, 1.0], + minimizer_kwargs=minimizer_kwargs, + niter=10, rng=rng) + assert_equal(res1.x, res2.x) + + def test_monotonic_basin_hopping(self): + # test 1-D minimizations with gradient and T=0 + i = 0 + + res = basinhopping(func1d, self.x0[i], minimizer_kwargs=self.kwargs, + niter=self.niter, disp=self.disp, T=0) + assert_almost_equal(res.x, self.sol[i], self.tol) + + +@pytest.mark.thread_unsafe +class Test_Storage: + def setup_method(self): + self.x0 = np.array(1) + self.f0 = 0 + + minres = OptimizeResult(success=True) + minres.x = self.x0 + minres.fun = self.f0 + + self.storage = Storage(minres) + + def test_higher_f_rejected(self): + new_minres = OptimizeResult(success=True) + new_minres.x = self.x0 + 1 + new_minres.fun = self.f0 + 1 + + ret = self.storage.update(new_minres) + minres = self.storage.get_lowest() + assert_equal(self.x0, minres.x) + assert_equal(self.f0, minres.fun) + assert_(not ret) + + @pytest.mark.parametrize('success', [True, False]) + def test_lower_f_accepted(self, success): + new_minres = OptimizeResult(success=success) + new_minres.x = self.x0 + 1 + new_minres.fun = self.f0 - 1 + + ret = self.storage.update(new_minres) + minres = self.storage.get_lowest() + assert (self.x0 != minres.x) == success # can't use `is` + assert (self.f0 != minres.fun) == success # left side is NumPy bool + assert ret is success + + +class Test_RandomDisplacement: + def setup_method(self): + self.stepsize = 1.0 + self.N = 300000 + + def test_random(self): + # the mean should be 0 + # the variance should be (2*stepsize)**2 / 12 + # note these tests are random, they will fail from time to time + rng = np.random.RandomState(0) + x0 = np.zeros([self.N]) + displace = RandomDisplacement(stepsize=self.stepsize, rng=rng) + x = displace(x0) + v = (2. * self.stepsize) ** 2 / 12 + assert_almost_equal(np.mean(x), 0., 1) + assert_almost_equal(np.var(x), v, 1) + + +class Test_Metropolis: + def setup_method(self): + self.T = 2. + self.met = Metropolis(self.T) + self.res_new = OptimizeResult(success=True, fun=0.) + self.res_old = OptimizeResult(success=True, fun=1.) + + def test_boolean_return(self): + # the return must be a bool, else an error will be raised in + # basinhopping + ret = self.met(res_new=self.res_new, res_old=self.res_old) + assert isinstance(ret, bool) + + def test_lower_f_accepted(self): + assert_(self.met(res_new=self.res_new, res_old=self.res_old)) + + def test_accept(self): + # test that steps are randomly accepted for f_new > f_old + one_accept = False + one_reject = False + for i in range(1000): + if one_accept and one_reject: + break + res_new = OptimizeResult(success=True, fun=1.) + res_old = OptimizeResult(success=True, fun=0.5) + ret = self.met(res_new=res_new, res_old=res_old) + if ret: + one_accept = True + else: + one_reject = True + assert_(one_accept) + assert_(one_reject) + + def test_GH7495(self): + # an overflow in exp was producing a RuntimeWarning + # create own object here in case someone changes self.T + met = Metropolis(2) + res_new = OptimizeResult(success=True, fun=0.) + res_old = OptimizeResult(success=True, fun=2000) + with np.errstate(over='raise'): + met.accept_reject(res_new=res_new, res_old=res_old) + + def test_gh7799(self): + # gh-7799 reported a problem in which local search was successful but + # basinhopping returned an invalid solution. Show that this is fixed. + def func(x): + return (x**2-8)**2+(x+2)**2 + + x0 = -4 + limit = 50 # Constrain to func value >= 50 + con = {'type': 'ineq', 'fun': lambda x: func(x) - limit}, + res = basinhopping( + func, + x0, + 30, + seed=np.random.RandomState(1234), + minimizer_kwargs={'constraints': con} + ) + assert res.success + assert_allclose(res.fun, limit, rtol=1e-6) + + def test_accept_gh7799(self): + # Metropolis should not accept the result of an unsuccessful new local + # search if the old local search was successful + + met = Metropolis(0) # monotonic basin hopping + res_new = OptimizeResult(success=True, fun=0.) + res_old = OptimizeResult(success=True, fun=1.) + + # if new local search was successful and energy is lower, accept + assert met(res_new=res_new, res_old=res_old) + # if new res is unsuccessful, don't accept - even if energy is lower + res_new.success = False + assert not met(res_new=res_new, res_old=res_old) + # ...unless the old res was unsuccessful, too. In that case, why not? + res_old.success = False + assert met(res_new=res_new, res_old=res_old) + + def test_reject_all_gh7799(self): + # Test the behavior when there is no feasible solution + def fun(x): + return x@x + + def constraint(x): + return x + 1 + + kwargs = {'constraints': {'type': 'eq', 'fun': constraint}, + 'bounds': [(0, 1), (0, 1)], 'method': 'slsqp'} + res = basinhopping(fun, x0=[2, 3], niter=10, minimizer_kwargs=kwargs) + assert not res.success + + +class Test_AdaptiveStepsize: + def setup_method(self): + self.stepsize = 1. + self.ts = RandomDisplacement(stepsize=self.stepsize) + self.target_accept_rate = 0.5 + self.takestep = AdaptiveStepsize(takestep=self.ts, verbose=False, + accept_rate=self.target_accept_rate) + + def test_adaptive_increase(self): + # if few steps are rejected, the stepsize should increase + x = 0. + self.takestep(x) + self.takestep.report(False) + for i in range(self.takestep.interval): + self.takestep(x) + self.takestep.report(True) + assert_(self.ts.stepsize > self.stepsize) + + def test_adaptive_decrease(self): + # if few steps are rejected, the stepsize should increase + x = 0. + self.takestep(x) + self.takestep.report(True) + for i in range(self.takestep.interval): + self.takestep(x) + self.takestep.report(False) + assert_(self.ts.stepsize < self.stepsize) + + def test_all_accepted(self): + # test that everything works OK if all steps were accepted + x = 0. + for i in range(self.takestep.interval + 1): + self.takestep(x) + self.takestep.report(True) + assert_(self.ts.stepsize > self.stepsize) + + def test_all_rejected(self): + # test that everything works OK if all steps were rejected + x = 0. + for i in range(self.takestep.interval + 1): + self.takestep(x) + self.takestep.report(False) + assert_(self.ts.stepsize < self.stepsize) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test__differential_evolution.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test__differential_evolution.py new file mode 100644 index 0000000000000000000000000000000000000000..3f81877f08abe436211210d5bd15d876c9a7177c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test__differential_evolution.py @@ -0,0 +1,1703 @@ +""" +Unit tests for the differential global minimization algorithm. +""" +import multiprocessing +from multiprocessing.dummy import Pool as ThreadPool +import platform + +from scipy.optimize._differentialevolution import (DifferentialEvolutionSolver, + _ConstraintWrapper) +from scipy.optimize import differential_evolution, OptimizeResult +from scipy.optimize._constraints import (Bounds, NonlinearConstraint, + LinearConstraint) +from scipy.optimize import rosen, minimize +from scipy.sparse import csr_matrix +from scipy import stats + +import numpy as np +from numpy.testing import (assert_equal, assert_allclose, assert_almost_equal, + assert_string_equal, assert_, suppress_warnings) +from pytest import raises as assert_raises, warns +import pytest + + +class TestDifferentialEvolutionSolver: + + def setup_method(self): + self.old_seterr = np.seterr(invalid='raise') + self.limits = np.array([[0., 0.], + [2., 2.]]) + self.bounds = [(0., 2.), (0., 2.)] + + self.dummy_solver = DifferentialEvolutionSolver(self.quadratic, + [(0, 100)]) + + # dummy_solver2 will be used to test mutation strategies + self.dummy_solver2 = DifferentialEvolutionSolver(self.quadratic, + [(0, 1)], + popsize=7, + mutation=0.5) + # create a population that's only 7 members long + # [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7] + population = np.atleast_2d(np.arange(0.1, 0.8, 0.1)).T + self.dummy_solver2.population = population + + def teardown_method(self): + np.seterr(**self.old_seterr) + + def quadratic(self, x): + return x[0]**2 + + def test__strategy_resolves(self): + # test that the correct mutation function is resolved by + # different requested strategy arguments + solver = DifferentialEvolutionSolver(rosen, + self.bounds, + strategy='best1exp') + assert_equal(solver.strategy, 'best1exp') + assert_equal(solver.mutation_func.__name__, '_best1') + + solver = DifferentialEvolutionSolver(rosen, + self.bounds, + strategy='best1bin') + assert_equal(solver.strategy, 'best1bin') + assert_equal(solver.mutation_func.__name__, '_best1') + + solver = DifferentialEvolutionSolver(rosen, + self.bounds, + strategy='rand1bin') + assert_equal(solver.strategy, 'rand1bin') + assert_equal(solver.mutation_func.__name__, '_rand1') + + solver = DifferentialEvolutionSolver(rosen, + self.bounds, + strategy='rand1exp') + assert_equal(solver.strategy, 'rand1exp') + assert_equal(solver.mutation_func.__name__, '_rand1') + + solver = DifferentialEvolutionSolver(rosen, + self.bounds, + strategy='rand2exp') + assert_equal(solver.strategy, 'rand2exp') + assert_equal(solver.mutation_func.__name__, '_rand2') + + solver = DifferentialEvolutionSolver(rosen, + self.bounds, + strategy='best2bin') + assert_equal(solver.strategy, 'best2bin') + assert_equal(solver.mutation_func.__name__, '_best2') + + solver = DifferentialEvolutionSolver(rosen, + self.bounds, + strategy='rand2bin') + assert_equal(solver.strategy, 'rand2bin') + assert_equal(solver.mutation_func.__name__, '_rand2') + + solver = DifferentialEvolutionSolver(rosen, + self.bounds, + strategy='rand2exp') + assert_equal(solver.strategy, 'rand2exp') + assert_equal(solver.mutation_func.__name__, '_rand2') + + solver = DifferentialEvolutionSolver(rosen, + self.bounds, + strategy='randtobest1bin') + assert_equal(solver.strategy, 'randtobest1bin') + assert_equal(solver.mutation_func.__name__, '_randtobest1') + + solver = DifferentialEvolutionSolver(rosen, + self.bounds, + strategy='randtobest1exp') + assert_equal(solver.strategy, 'randtobest1exp') + assert_equal(solver.mutation_func.__name__, '_randtobest1') + + solver = DifferentialEvolutionSolver(rosen, + self.bounds, + strategy='currenttobest1bin') + assert_equal(solver.strategy, 'currenttobest1bin') + assert_equal(solver.mutation_func.__name__, '_currenttobest1') + + solver = DifferentialEvolutionSolver(rosen, + self.bounds, + strategy='currenttobest1exp') + assert_equal(solver.strategy, 'currenttobest1exp') + assert_equal(solver.mutation_func.__name__, '_currenttobest1') + + def test__mutate1(self): + # strategies */1/*, i.e. rand/1/bin, best/1/exp, etc. + result = np.array([0.05]) + trial = self.dummy_solver2._best1(np.array([2, 3, 4, 5, 6])) + assert_allclose(trial, result) + + result = np.array([0.25]) + trial = self.dummy_solver2._rand1(np.array([2, 3, 4, 5, 6])) + assert_allclose(trial, result) + + def test__mutate2(self): + # strategies */2/*, i.e. rand/2/bin, best/2/exp, etc. + # [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7] + + result = np.array([-0.1]) + trial = self.dummy_solver2._best2(np.array([2, 3, 4, 5, 6])) + assert_allclose(trial, result) + + result = np.array([0.1]) + trial = self.dummy_solver2._rand2(np.array([2, 3, 4, 5, 6])) + assert_allclose(trial, result) + + def test__randtobest1(self): + # strategies randtobest/1/* + result = np.array([0.15]) + trial = self.dummy_solver2._randtobest1(np.array([2, 3, 4, 5, 6])) + assert_allclose(trial, result) + + def test__currenttobest1(self): + # strategies currenttobest/1/* + result = np.array([0.1]) + trial = self.dummy_solver2._currenttobest1( + 1, + np.array([2, 3, 4, 5, 6]) + ) + assert_allclose(trial, result) + + def test_can_init_with_dithering(self): + mutation = (0.5, 1) + solver = DifferentialEvolutionSolver(self.quadratic, + self.bounds, + mutation=mutation) + + assert_equal(solver.dither, list(mutation)) + + def test_invalid_mutation_values_arent_accepted(self): + func = rosen + mutation = (0.5, 3) + assert_raises(ValueError, + DifferentialEvolutionSolver, + func, + self.bounds, + mutation=mutation) + + mutation = (-1, 1) + assert_raises(ValueError, + DifferentialEvolutionSolver, + func, + self.bounds, + mutation=mutation) + + mutation = (0.1, np.nan) + assert_raises(ValueError, + DifferentialEvolutionSolver, + func, + self.bounds, + mutation=mutation) + + mutation = 0.5 + solver = DifferentialEvolutionSolver(func, + self.bounds, + mutation=mutation) + assert_equal(0.5, solver.scale) + assert_equal(None, solver.dither) + + def test_invalid_functional(self): + def func(x): + return np.array([np.sum(x ** 2), np.sum(x)]) + + with assert_raises( + RuntimeError, + match=r"func\(x, \*args\) must return a scalar value"): + differential_evolution(func, [(-2, 2), (-2, 2)]) + + def test__scale_parameters(self): + trial = np.array([0.3]) + assert_equal(30, self.dummy_solver._scale_parameters(trial)) + + # it should also work with the limits reversed + self.dummy_solver.limits = np.array([[100], [0.]]) + assert_equal(30, self.dummy_solver._scale_parameters(trial)) + + def test__unscale_parameters(self): + trial = np.array([30]) + assert_equal(0.3, self.dummy_solver._unscale_parameters(trial)) + + # it should also work with the limits reversed + self.dummy_solver.limits = np.array([[100], [0.]]) + assert_equal(0.3, self.dummy_solver._unscale_parameters(trial)) + + def test_equal_bounds(self): + with np.errstate(invalid='raise'): + solver = DifferentialEvolutionSolver( + self.quadratic, + bounds=[(2.0, 2.0), (1.0, 3.0)] + ) + v = solver._unscale_parameters([2.0, 2.0]) + assert_allclose(v, 0.5) + + res = differential_evolution(self.quadratic, [(2.0, 2.0), (3.0, 3.0)]) + assert_equal(res.x, [2.0, 3.0]) + + def test__ensure_constraint(self): + trial = np.array([1.1, -100, 0.9, 2., 300., -0.00001]) + self.dummy_solver._ensure_constraint(trial) + + assert_equal(trial[2], 0.9) + assert_(np.logical_and(trial >= 0, trial <= 1).all()) + + def test_differential_evolution(self): + # test that the Jmin of DifferentialEvolutionSolver + # is the same as the function evaluation + solver = DifferentialEvolutionSolver( + self.quadratic, [(-2, 2)], maxiter=1, polish=False + ) + result = solver.solve() + assert_equal(result.fun, self.quadratic(result.x)) + + solver = DifferentialEvolutionSolver( + self.quadratic, [(-2, 2)], maxiter=1, polish=True + ) + result = solver.solve() + assert_equal(result.fun, self.quadratic(result.x)) + + def test_best_solution_retrieval(self): + # test that the getter property method for the best solution works. + solver = DifferentialEvolutionSolver(self.quadratic, [(-2, 2)]) + result = solver.solve() + assert_equal(result.x, solver.x) + + def test_intermediate_result(self): + # Check that intermediate result object passed into the callback + # function contains the expected information and that raising + # `StopIteration` causes the expected behavior. + maxiter = 10 + + def func(x): + val = rosen(x) + if val < func.val: + func.x = x + func.val = val + return val + func.x = None + func.val = np.inf + + def callback(intermediate_result): + callback.nit += 1 + callback.intermediate_result = intermediate_result + assert intermediate_result.population.ndim == 2 + assert intermediate_result.population.shape[1] == 2 + assert intermediate_result.nit == callback.nit + + # Check that `x` and `fun` attributes are the best found so far + assert_equal(intermediate_result.x, callback.func.x) + assert_equal(intermediate_result.fun, callback.func.val) + + # Check for consistency between `fun`, `population_energies`, + # `x`, and `population` + assert_equal(intermediate_result.fun, rosen(intermediate_result.x)) + for i in range(len(intermediate_result.population_energies)): + res = intermediate_result.population_energies[i] + ref = rosen(intermediate_result.population[i]) + assert_equal(res, ref) + assert_equal(intermediate_result.x, + intermediate_result.population[0]) + assert_equal(intermediate_result.fun, + intermediate_result.population_energies[0]) + + assert intermediate_result.message == 'in progress' + assert intermediate_result.success is True + assert isinstance(intermediate_result, OptimizeResult) + if callback.nit == maxiter: + raise StopIteration + callback.nit = 0 + callback.intermediate_result = None + callback.func = func + + bounds = [(0, 2), (0, 2)] + kwargs = dict(func=func, bounds=bounds, rng=838245, polish=False) + res = differential_evolution(**kwargs, callback=callback) + ref = differential_evolution(**kwargs, maxiter=maxiter) + + # Check that final `intermediate_result` is equivalent to returned + # result object and that terminating with callback `StopIteration` + # after `maxiter` iterations is equivalent to terminating with + # `maxiter` parameter. + assert res.success is ref.success is False + assert callback.nit == res.nit == maxiter + assert res.message == 'callback function requested stop early' + assert ref.message == 'Maximum number of iterations has been exceeded.' + for field, val in ref.items(): + if field in {'message', 'success'}: # checked separately + continue + assert_equal(callback.intermediate_result[field], val) + assert_equal(res[field], val) + + # Check that polish occurs after `StopIteration` as advertised + callback.nit = 0 + func.val = np.inf + kwargs['polish'] = True + res = differential_evolution(**kwargs, callback=callback) + assert res.fun < ref.fun + + def test_callback_terminates(self): + # test that if the callback returns true, then the minimization halts + bounds = [(0, 2), (0, 2)] + expected_msg = 'callback function requested stop early' + def callback_python_true(param, convergence=0.): + return True + + result = differential_evolution( + rosen, bounds, callback=callback_python_true + ) + assert_string_equal(result.message, expected_msg) + + # if callback raises StopIteration then solve should be interrupted + def callback_stop(intermediate_result): + raise StopIteration + + result = differential_evolution(rosen, bounds, callback=callback_stop) + assert not result.success + + def callback_evaluates_true(param, convergence=0.): + # DE should stop if bool(self.callback) is True + return [10] + + result = differential_evolution(rosen, bounds, callback=callback_evaluates_true) + assert_string_equal(result.message, expected_msg) + assert not result.success + + def callback_evaluates_false(param, convergence=0.): + return [] + + result = differential_evolution(rosen, bounds, + callback=callback_evaluates_false) + assert result.success + + def test_args_tuple_is_passed(self): + # test that the args tuple is passed to the cost function properly. + bounds = [(-10, 10)] + args = (1., 2., 3.) + + def quadratic(x, *args): + if not isinstance(args, tuple): + raise ValueError('args should be a tuple') + return args[0] + args[1] * x + args[2] * x**2. + + result = differential_evolution(quadratic, + bounds, + args=args, + polish=True) + assert_almost_equal(result.fun, 2 / 3.) + + def test_init_with_invalid_strategy(self): + # test that passing an invalid strategy raises ValueError + func = rosen + bounds = [(-3, 3)] + assert_raises(ValueError, + differential_evolution, + func, + bounds, + strategy='abc') + + def test_bounds_checking(self): + # test that the bounds checking works + func = rosen + bounds = [(-3)] + assert_raises(ValueError, + differential_evolution, + func, + bounds) + bounds = [(-3, 3), (3, 4, 5)] + assert_raises(ValueError, + differential_evolution, + func, + bounds) + + # test that we can use a new-type Bounds object + result = differential_evolution(rosen, Bounds([0, 0], [2, 2])) + assert_almost_equal(result.x, (1., 1.)) + + def test_select_samples(self): + # select_samples should return 5 separate random numbers. + limits = np.arange(12., dtype='float64').reshape(2, 6) + bounds = list(zip(limits[0, :], limits[1, :])) + solver = DifferentialEvolutionSolver(None, bounds, popsize=1) + candidate = 0 + r1, r2, r3, r4, r5 = solver._select_samples(candidate, 5) + assert_equal( + len(np.unique(np.array([candidate, r1, r2, r3, r4, r5]))), 6) + + def test_maxiter_stops_solve(self): + # test that if the maximum number of iterations is exceeded + # the solver stops. + solver = DifferentialEvolutionSolver(rosen, self.bounds, maxiter=1) + result = solver.solve() + assert_equal(result.success, False) + assert_equal(result.message, + 'Maximum number of iterations has been exceeded.') + + def test_maxfun_stops_solve(self): + # test that if the maximum number of function evaluations is exceeded + # during initialisation the solver stops + solver = DifferentialEvolutionSolver(rosen, self.bounds, maxfun=1, + polish=False) + result = solver.solve() + + assert_equal(result.nfev, 2) + assert_equal(result.success, False) + assert_equal(result.message, + 'Maximum number of function evaluations has ' + 'been exceeded.') + + # test that if the maximum number of function evaluations is exceeded + # during the actual minimisation, then the solver stops. + # Have to turn polishing off, as this will still occur even if maxfun + # is reached. For popsize=5 and len(bounds)=2, then there are only 10 + # function evaluations during initialisation. + solver = DifferentialEvolutionSolver(rosen, + self.bounds, + popsize=5, + polish=False, + maxfun=40) + result = solver.solve() + + assert_equal(result.nfev, 41) + assert_equal(result.success, False) + assert_equal(result.message, + 'Maximum number of function evaluations has ' + 'been exceeded.') + + # now repeat for updating='deferred version + # 47 function evaluations is not a multiple of the population size, + # so maxfun is reached partway through a population evaluation. + solver = DifferentialEvolutionSolver(rosen, + self.bounds, + popsize=5, + polish=False, + maxfun=47, + updating='deferred') + result = solver.solve() + + assert_equal(result.nfev, 47) + assert_equal(result.success, False) + assert_equal(result.message, + 'Maximum number of function evaluations has ' + 'been reached.') + + def test_quadratic(self): + # test the quadratic function from object + solver = DifferentialEvolutionSolver(self.quadratic, + [(-100, 100)], + tol=0.02) + solver.solve() + assert_equal(np.argmin(solver.population_energies), 0) + + def test_quadratic_from_diff_ev(self): + # test the quadratic function from differential_evolution function + differential_evolution(self.quadratic, + [(-100, 100)], + tol=0.02, + seed=1) + + def test_rng_gives_repeatability(self): + result = differential_evolution(self.quadratic, + [(-100, 100)], + polish=False, + rng=1, + tol=0.5) + result2 = differential_evolution(self.quadratic, + [(-100, 100)], + polish=False, + rng=1, + tol=0.5) + assert_equal(result.x, result2.x) + assert_equal(result.nfev, result2.nfev) + + def test_random_generator(self): + # check that np.random.Generator can be used (numpy >= 1.17) + # obtain a np.random.Generator object + rng = np.random.default_rng() + + inits = ['random', 'latinhypercube', 'sobol', 'halton'] + for init in inits: + differential_evolution(self.quadratic, + [(-100, 100)], + polish=False, + rng=rng, + tol=0.5, + init=init) + + def test_exp_runs(self): + # test whether exponential mutation loop runs + solver = DifferentialEvolutionSolver(rosen, + self.bounds, + strategy='best1exp', + maxiter=1) + + solver.solve() + + def test_gh_4511_regression(self): + # This modification of the differential evolution docstring example + # uses a custom popsize that had triggered an off-by-one error. + # Because we do not care about solving the optimization problem in + # this test, we use maxiter=1 to reduce the testing time. + bounds = [(-5, 5), (-5, 5)] + # result = differential_evolution(rosen, bounds, popsize=1815, + # maxiter=1) + + # the original issue arose because of rounding error in arange, with + # linspace being a much better solution. 1815 is quite a large popsize + # to use and results in a long test time (~13s). I used the original + # issue to figure out the lowest number of samples that would cause + # this rounding error to occur, 49. + differential_evolution(rosen, bounds, popsize=49, maxiter=1) + + def test_calculate_population_energies(self): + # if popsize is 3, then the overall generation has size (6,) + solver = DifferentialEvolutionSolver(rosen, self.bounds, popsize=3) + solver._calculate_population_energies(solver.population) + solver._promote_lowest_energy() + assert_equal(np.argmin(solver.population_energies), 0) + + # initial calculation of the energies should require 6 nfev. + assert_equal(solver._nfev, 6) + + def test_iteration(self): + # test that DifferentialEvolutionSolver is iterable + # if popsize is 3, then the overall generation has size (6,) + solver = DifferentialEvolutionSolver(rosen, self.bounds, popsize=3, + maxfun=12) + x, fun = next(solver) + assert_equal(np.size(x, 0), 2) + + # 6 nfev are required for initial calculation of energies, 6 nfev are + # required for the evolution of the 6 population members. + assert_equal(solver._nfev, 12) + + # the next generation should halt because it exceeds maxfun + assert_raises(StopIteration, next, solver) + + # check a proper minimisation can be done by an iterable solver + solver = DifferentialEvolutionSolver(rosen, self.bounds) + _, fun_prev = next(solver) + for i, soln in enumerate(solver): + x_current, fun_current = soln + assert fun_prev >= fun_current + _, fun_prev = x_current, fun_current + # need to have this otherwise the solver would never stop. + if i == 50: + break + + def test_convergence(self): + solver = DifferentialEvolutionSolver(rosen, self.bounds, tol=0.2, + polish=False) + solver.solve() + assert_(solver.convergence < 0.2) + + def test_maxiter_none_GH5731(self): + # Pre 0.17 the previous default for maxiter and maxfun was None. + # the numerical defaults are now 1000 and np.inf. However, some scripts + # will still supply None for both of those, this will raise a TypeError + # in the solve method. + solver = DifferentialEvolutionSolver(rosen, self.bounds, maxiter=None, + maxfun=None) + solver.solve() + + def test_population_initiation(self): + # test the different modes of population initiation + + # init must be either 'latinhypercube' or 'random' + # raising ValueError is something else is passed in + assert_raises(ValueError, + DifferentialEvolutionSolver, + *(rosen, self.bounds), + **{'init': 'rubbish'}) + + solver = DifferentialEvolutionSolver(rosen, self.bounds) + + # check that population initiation: + # 1) resets _nfev to 0 + # 2) all population energies are np.inf + solver.init_population_random() + assert_equal(solver._nfev, 0) + assert_(np.all(np.isinf(solver.population_energies))) + + solver.init_population_lhs() + assert_equal(solver._nfev, 0) + assert_(np.all(np.isinf(solver.population_energies))) + + solver.init_population_qmc(qmc_engine='halton') + assert_equal(solver._nfev, 0) + assert_(np.all(np.isinf(solver.population_energies))) + + solver = DifferentialEvolutionSolver(rosen, self.bounds, init='sobol') + solver.init_population_qmc(qmc_engine='sobol') + assert_equal(solver._nfev, 0) + assert_(np.all(np.isinf(solver.population_energies))) + + # we should be able to initialize with our own array + population = np.linspace(-1, 3, 10).reshape(5, 2) + solver = DifferentialEvolutionSolver(rosen, self.bounds, + init=population, + strategy='best2bin', + atol=0.01, rng=1, popsize=5) + + assert_equal(solver._nfev, 0) + assert_(np.all(np.isinf(solver.population_energies))) + assert_(solver.num_population_members == 5) + assert_(solver.population_shape == (5, 2)) + + # check that the population was initialized correctly + unscaled_population = np.clip(solver._unscale_parameters(population), + 0, 1) + assert_almost_equal(solver.population[:5], unscaled_population) + + # population values need to be clipped to bounds + assert_almost_equal(np.min(solver.population[:5]), 0) + assert_almost_equal(np.max(solver.population[:5]), 1) + + # shouldn't be able to initialize with an array if it's the wrong shape + # this would have too many parameters + population = np.linspace(-1, 3, 15).reshape(5, 3) + assert_raises(ValueError, + DifferentialEvolutionSolver, + *(rosen, self.bounds), + **{'init': population}) + + # provide an initial solution + # bounds are [(0, 2), (0, 2)] + x0 = np.random.uniform(low=0.0, high=2.0, size=2) + solver = DifferentialEvolutionSolver( + rosen, self.bounds, x0=x0 + ) + # parameters are scaled to unit interval + assert_allclose(solver.population[0], x0 / 2.0) + + def test_x0(self): + # smoke test that checks that x0 is usable. + res = differential_evolution(rosen, self.bounds, x0=[0.2, 0.8]) + assert res.success + + # check what happens if some of the x0 lay outside the bounds + with assert_raises(ValueError): + differential_evolution(rosen, self.bounds, x0=[0.2, 2.1]) + + def test_infinite_objective_function(self): + # Test that there are no problems if the objective function + # returns inf on some runs + def sometimes_inf(x): + if x[0] < .5: + return np.inf + return x[1] + bounds = [(0, 1), (0, 1)] + differential_evolution(sometimes_inf, bounds=bounds, disp=False) + + def test_deferred_updating(self): + # check setting of deferred updating, with default workers + bounds = [(0., 2.), (0., 2.)] + solver = DifferentialEvolutionSolver(rosen, bounds, updating='deferred') + assert_(solver._updating == 'deferred') + assert_(solver._mapwrapper._mapfunc is map) + res = solver.solve() + assert res.success + + # check that deferred updating works with an exponential crossover + res = differential_evolution( + rosen, bounds, updating='deferred', strategy='best1exp' + ) + assert res.success + + @pytest.mark.thread_unsafe + def test_immediate_updating(self): + # check setting of immediate updating, with default workers + bounds = [(0., 2.), (0., 2.)] + solver = DifferentialEvolutionSolver(rosen, bounds) + assert_(solver._updating == 'immediate') + + # Safely forking from a multithreaded process is + # problematic, and deprecated in Python 3.12, so + # we use a slower but portable alternative + # see gh-19848 + ctx = multiprocessing.get_context("spawn") + with ctx.Pool(2) as p: + # should raise a UserWarning because the updating='immediate' + # is being overridden by the workers keyword + with warns(UserWarning): + with DifferentialEvolutionSolver(rosen, bounds, workers=p.map) as s: + solver.solve() + assert s._updating == 'deferred' + + @pytest.mark.fail_slow(10) + def test_parallel(self): + # smoke test for parallelization with deferred updating + bounds = [(0., 2.), (0., 2.)] + # use threads instead of Process to speed things up for this simple example + with ThreadPool(2) as p, DifferentialEvolutionSolver( + rosen, bounds, updating='deferred', workers=p.map, tol=0.1, popsize=3 + ) as solver: + assert solver._mapwrapper.pool is not None + assert solver._updating == 'deferred' + solver.solve() + + with DifferentialEvolutionSolver( + rosen, bounds, updating='deferred', workers=2, popsize=3, tol=0.1 + ) as solver: + assert solver._mapwrapper.pool is not None + assert solver._updating == 'deferred' + solver.solve() + + def test_converged(self): + solver = DifferentialEvolutionSolver(rosen, [(0, 2), (0, 2)]) + solver.solve() + assert_(solver.converged()) + + def test_constraint_violation_fn(self): + def constr_f(x): + return [x[0] + x[1]] + + def constr_f2(x): + return np.array([x[0]**2 + x[1], x[0] - x[1]]) + + nlc = NonlinearConstraint(constr_f, -np.inf, 1.9) + + solver = DifferentialEvolutionSolver(rosen, [(0, 2), (0, 2)], + constraints=(nlc,)) + + cv = solver._constraint_violation_fn(np.array([1.0, 1.0])) + assert_almost_equal(cv, 0.1) + + nlc2 = NonlinearConstraint(constr_f2, -np.inf, 1.8) + solver = DifferentialEvolutionSolver(rosen, [(0, 2), (0, 2)], + constraints=(nlc, nlc2)) + + # for multiple constraints the constraint violations should + # be concatenated. + xs = [(1.2, 1), (2.0, 2.0), (0.5, 0.5)] + vs = [(0.3, 0.64, 0.0), (2.1, 4.2, 0.0), (0, 0, 0)] + + for x, v in zip(xs, vs): + cv = solver._constraint_violation_fn(np.array(x)) + assert_allclose(cv, np.atleast_2d(v)) + + # vectorized calculation of a series of solutions + assert_allclose( + solver._constraint_violation_fn(np.array(xs)), np.array(vs) + ) + + # the following line is used in _calculate_population_feasibilities. + # _constraint_violation_fn returns an (1, M) array when + # x.shape == (N,), i.e. a single solution. Therefore this list + # comprehension should generate (S, 1, M) array. + constraint_violation = np.array([solver._constraint_violation_fn(x) + for x in np.array(xs)]) + assert constraint_violation.shape == (3, 1, 3) + + # we need reasonable error messages if the constraint function doesn't + # return the right thing + def constr_f3(x): + # returns (S, M), rather than (M, S) + return constr_f2(x).T + + nlc2 = NonlinearConstraint(constr_f3, -np.inf, 1.8) + solver = DifferentialEvolutionSolver(rosen, [(0, 2), (0, 2)], + constraints=(nlc, nlc2), + vectorized=False) + solver.vectorized = True + with pytest.raises( + RuntimeError, match="An array returned from a Constraint" + ): + solver._constraint_violation_fn(np.array(xs)) + + def test_constraint_population_feasibilities(self): + def constr_f(x): + return [x[0] + x[1]] + + def constr_f2(x): + return [x[0]**2 + x[1], x[0] - x[1]] + + nlc = NonlinearConstraint(constr_f, -np.inf, 1.9) + + solver = DifferentialEvolutionSolver(rosen, [(0, 2), (0, 2)], + constraints=(nlc,)) + + # are population feasibilities correct + # [0.5, 0.5] corresponds to scaled values of [1., 1.] + feas, cv = solver._calculate_population_feasibilities( + np.array([[0.5, 0.5], [1., 1.]])) + assert_equal(feas, [False, False]) + assert_almost_equal(cv, np.array([[0.1], [2.1]])) + assert cv.shape == (2, 1) + + nlc2 = NonlinearConstraint(constr_f2, -np.inf, 1.8) + + for vectorize in [False, True]: + solver = DifferentialEvolutionSolver(rosen, [(0, 2), (0, 2)], + constraints=(nlc, nlc2), + vectorized=vectorize, + updating='deferred') + + feas, cv = solver._calculate_population_feasibilities( + np.array([[0.5, 0.5], [0.6, 0.5]])) + assert_equal(feas, [False, False]) + assert_almost_equal(cv, np.array([[0.1, 0.2, 0], [0.3, 0.64, 0]])) + + feas, cv = solver._calculate_population_feasibilities( + np.array([[0.5, 0.5], [1., 1.]])) + assert_equal(feas, [False, False]) + assert_almost_equal(cv, np.array([[0.1, 0.2, 0], [2.1, 4.2, 0]])) + assert cv.shape == (2, 3) + + feas, cv = solver._calculate_population_feasibilities( + np.array([[0.25, 0.25], [1., 1.]])) + assert_equal(feas, [True, False]) + assert_almost_equal(cv, np.array([[0.0, 0.0, 0.], [2.1, 4.2, 0]])) + assert cv.shape == (2, 3) + + @pytest.mark.thread_unsafe + def test_constraint_solve(self): + def constr_f(x): + return np.array([x[0] + x[1]]) + + nlc = NonlinearConstraint(constr_f, -np.inf, 1.9) + + solver = DifferentialEvolutionSolver(rosen, [(0, 2), (0, 2)], + constraints=(nlc,)) + + # trust-constr warns if the constraint function is linear + with warns(UserWarning): + res = solver.solve() + + assert constr_f(res.x) <= 1.9 + assert res.success + + @pytest.mark.fail_slow(10) + @pytest.mark.thread_unsafe + def test_impossible_constraint(self): + def constr_f(x): + return np.array([x[0] + x[1]]) + + nlc = NonlinearConstraint(constr_f, -np.inf, -1) + + solver = DifferentialEvolutionSolver( + rosen, [(0, 2), (0, 2)], constraints=(nlc,), popsize=1, rng=1, maxiter=100 + ) + + # a UserWarning is issued because the 'trust-constr' polishing is + # attempted on the least infeasible solution found. + with warns(UserWarning): + res = solver.solve() + + assert res.maxcv > 0 + assert not res.success + + # test _promote_lowest_energy works when none of the population is + # feasible. In this case, the solution with the lowest constraint + # violation should be promoted. + solver = DifferentialEvolutionSolver( + rosen, [(0, 2), (0, 2)], constraints=(nlc,), polish=False) + next(solver) + assert not solver.feasible.all() + assert not np.isfinite(solver.population_energies).all() + + # now swap two of the entries in the population + l = 20 + cv = solver.constraint_violation[0] + + solver.population_energies[[0, l]] = solver.population_energies[[l, 0]] + solver.population[[0, l], :] = solver.population[[l, 0], :] + solver.constraint_violation[[0, l], :] = ( + solver.constraint_violation[[l, 0], :]) + + solver._promote_lowest_energy() + assert_equal(solver.constraint_violation[0], cv) + + def test_accept_trial(self): + # _accept_trial(self, energy_trial, feasible_trial, cv_trial, + # energy_orig, feasible_orig, cv_orig) + def constr_f(x): + return [x[0] + x[1]] + nlc = NonlinearConstraint(constr_f, -np.inf, 1.9) + solver = DifferentialEvolutionSolver(rosen, [(0, 2), (0, 2)], + constraints=(nlc,)) + fn = solver._accept_trial + # both solutions are feasible, select lower energy + assert fn(0.1, True, np.array([0.]), 1.0, True, np.array([0.])) + assert (fn(1.0, True, np.array([0.0]), 0.1, True, np.array([0.0])) is False) + assert fn(0.1, True, np.array([0.]), 0.1, True, np.array([0.])) + + # trial is feasible, original is not + assert fn(9.9, True, np.array([0.]), 1.0, False, np.array([1.])) + + # trial and original are infeasible + # cv_trial have to be <= cv_original to be better + assert (fn(0.1, False, np.array([0.5, 0.5]), + 1.0, False, np.array([1., 1.0]))) + assert (fn(0.1, False, np.array([0.5, 0.5]), + 1.0, False, np.array([1., 0.50]))) + assert not (fn(1.0, False, np.array([0.5, 0.5]), + 1.0, False, np.array([1.0, 0.4]))) + + def test_constraint_wrapper(self): + lb = np.array([0, 20, 30]) + ub = np.array([0.5, np.inf, 70]) + x0 = np.array([1, 2, 3]) + pc = _ConstraintWrapper(Bounds(lb, ub), x0) + assert (pc.violation(x0) > 0).any() + assert (pc.violation([0.25, 21, 31]) == 0).all() + + # check vectorized Bounds constraint + xs = np.arange(1, 16).reshape(5, 3) + violations = [] + for x in xs: + violations.append(pc.violation(x)) + np.testing.assert_allclose(pc.violation(xs.T), np.array(violations).T) + + x0 = np.array([1, 2, 3, 4]) + A = np.array([[1, 2, 3, 4], [5, 0, 0, 6], [7, 0, 8, 0]]) + pc = _ConstraintWrapper(LinearConstraint(A, -np.inf, 0), x0) + assert (pc.violation(x0) > 0).any() + assert (pc.violation([-10, 2, -10, 4]) == 0).all() + + # check vectorized LinearConstraint, for 7 lots of parameter vectors + # with each parameter vector being 4 long, with 3 constraints + # xs is the same shape as stored in the differential evolution + # population, but it's sent to the violation function as (len(x), M) + xs = np.arange(1, 29).reshape(7, 4) + violations = [] + for x in xs: + violations.append(pc.violation(x)) + np.testing.assert_allclose(pc.violation(xs.T), np.array(violations).T) + + pc = _ConstraintWrapper(LinearConstraint(csr_matrix(A), -np.inf, 0), + x0) + assert (pc.violation(x0) > 0).any() + assert (pc.violation([-10, 2, -10, 4]) == 0).all() + + def fun(x): + return A.dot(x) + + nonlinear = NonlinearConstraint(fun, -np.inf, 0) + pc = _ConstraintWrapper(nonlinear, [-10, 2, -10, 4]) + assert (pc.violation(x0) > 0).any() + assert (pc.violation([-10, 2, -10, 4]) == 0).all() + + def test_constraint_wrapper_violation(self): + def cons_f(x): + # written in vectorised form to accept an array of (N, S) + # returning (M, S) + # where N is the number of parameters, + # S is the number of solution vectors to be examined, + # and M is the number of constraint components + return np.array([x[0] ** 2 + x[1], + x[0] ** 2 - x[1]]) + + nlc = NonlinearConstraint(cons_f, [-1, -0.8500], [2, 2]) + pc = _ConstraintWrapper(nlc, [0.5, 1]) + assert np.size(pc.bounds[0]) == 2 + + xs = [(0.5, 1), (0.5, 1.2), (1.2, 1.2), (0.1, -1.2), (0.1, 2.0)] + vs = [(0, 0), (0, 0.1), (0.64, 0), (0.19, 0), (0.01, 1.14)] + + for x, v in zip(xs, vs): + assert_allclose(pc.violation(x), v) + + # now check that we can vectorize the constraint wrapper + assert_allclose(pc.violation(np.array(xs).T), + np.array(vs).T) + assert pc.fun(np.array(xs).T).shape == (2, len(xs)) + assert pc.violation(np.array(xs).T).shape == (2, len(xs)) + assert pc.num_constr == 2 + assert pc.parameter_count == 2 + + def test_matrix_linear_constraint(self): + # gh20041 supplying an np.matrix to construct a LinearConstraint caused + # _ConstraintWrapper to start returning constraint violations of the + # wrong shape. + with suppress_warnings() as sup: + sup.filter(PendingDeprecationWarning) + matrix = np.matrix([[1, 1, 1, 1.], + [2, 2, 2, 2.]]) + lc = LinearConstraint(matrix, 0, 1) + x0 = np.ones(4) + cw = _ConstraintWrapper(lc, x0) + # the shape of the constraint violation should be the same as the number + # of constraints applied. + assert cw.violation(x0).shape == (2,) + + # let's try a vectorised violation call. + xtrial = np.arange(4 * 5).reshape(4, 5) + assert cw.violation(xtrial).shape == (2, 5) + + @pytest.mark.fail_slow(20) + def test_L1(self): + # Lampinen ([5]) test problem 1 + + def f(x): + x = np.hstack(([0], x)) # 1-indexed to match reference + fun = np.sum(5*x[1:5]) - 5*x[1:5]@x[1:5] - np.sum(x[5:]) + return fun + + A = np.zeros((10, 14)) # 1-indexed to match reference + A[1, [1, 2, 10, 11]] = 2, 2, 1, 1 + A[2, [1, 10]] = -8, 1 + A[3, [4, 5, 10]] = -2, -1, 1 + A[4, [1, 3, 10, 11]] = 2, 2, 1, 1 + A[5, [2, 11]] = -8, 1 + A[6, [6, 7, 11]] = -2, -1, 1 + A[7, [2, 3, 11, 12]] = 2, 2, 1, 1 + A[8, [3, 12]] = -8, 1 + A[9, [8, 9, 12]] = -2, -1, 1 + A = A[1:, 1:] + + b = np.array([10, 0, 0, 10, 0, 0, 10, 0, 0]) + + L = LinearConstraint(A, -np.inf, b) + + bounds = [(0, 1)]*9 + [(0, 100)]*3 + [(0, 1)] + + # using a lower popsize to speed the test up + res = differential_evolution( + f, bounds, strategy='best1bin', rng=12345, constraints=(L,), + popsize=5, tol=0.01 + ) + + x_opt = (1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 1) + f_opt = -15 + + assert_allclose(f(x_opt), f_opt, atol=6e-4) + assert res.success + assert_allclose(res.x, x_opt, atol=6e-4) + assert_allclose(res.fun, f_opt, atol=5e-3) + assert_(np.all(A@res.x <= b)) + assert_(np.all(res.x >= np.array(bounds)[:, 0])) + assert_(np.all(res.x <= np.array(bounds)[:, 1])) + + # now repeat the same solve, using the same overall constraints, + # but using a sparse matrix for the LinearConstraint instead of an + # array + + L = LinearConstraint(csr_matrix(A), -np.inf, b) + + # using a lower popsize to speed the test up + res = differential_evolution( + f, bounds, strategy='best1bin', rng=1211134, constraints=(L,), + popsize=2, tol=0.05 + ) + + assert_allclose(f(x_opt), f_opt) + assert res.success + assert_allclose(res.x, x_opt, atol=5e-4) + assert_allclose(res.fun, f_opt, atol=5e-3) + assert_(np.all(A@res.x <= b)) + assert_(np.all(res.x >= np.array(bounds)[:, 0])) + assert_(np.all(res.x <= np.array(bounds)[:, 1])) + + # now repeat the same solve, using the same overall constraints, + # but specify half the constraints in terms of LinearConstraint, + # and the other half by NonlinearConstraint + def c1(x): + x = np.hstack(([0], x)) + return [2*x[2] + 2*x[3] + x[11] + x[12], + -8*x[3] + x[12]] + + def c2(x): + x = np.hstack(([0], x)) + return -2*x[8] - x[9] + x[12] + + L = LinearConstraint(A[:5, :], -np.inf, b[:5]) + L2 = LinearConstraint(A[5:6, :], -np.inf, b[5:6]) + N = NonlinearConstraint(c1, -np.inf, b[6:8]) + N2 = NonlinearConstraint(c2, -np.inf, b[8:9]) + constraints = (L, N, L2, N2) + + with suppress_warnings() as sup: + sup.filter(UserWarning) + res = differential_evolution( + f, bounds, strategy='best1bin', rng=1211134, + constraints=constraints, popsize=2, tol=0.05 + ) + + assert_allclose(res.x, x_opt, atol=6e-4) + assert_allclose(res.fun, f_opt, atol=5e-3) + assert_(np.all(A@res.x <= b)) + assert_(np.all(res.x >= np.array(bounds)[:, 0])) + assert_(np.all(res.x <= np.array(bounds)[:, 1])) + + @pytest.mark.fail_slow(10) + def test_L2(self): + # Lampinen ([5]) test problem 2 + + def f(x): + x = np.hstack(([0], x)) # 1-indexed to match reference + fun = ((x[1]-10)**2 + 5*(x[2]-12)**2 + x[3]**4 + 3*(x[4]-11)**2 + + 10*x[5]**6 + 7*x[6]**2 + x[7]**4 - 4*x[6]*x[7] - 10*x[6] - + 8*x[7]) + return fun + + def c1(x): + x = np.hstack(([0], x)) # 1-indexed to match reference + return [127 - 2*x[1]**2 - 3*x[2]**4 - x[3] - 4*x[4]**2 - 5*x[5], + 196 - 23*x[1] - x[2]**2 - 6*x[6]**2 + 8*x[7], + 282 - 7*x[1] - 3*x[2] - 10*x[3]**2 - x[4] + x[5], + -4*x[1]**2 - x[2]**2 + 3*x[1]*x[2] - 2*x[3]**2 - + 5*x[6] + 11*x[7]] + + N = NonlinearConstraint(c1, 0, np.inf) + bounds = [(-10, 10)]*7 + constraints = (N) + + with suppress_warnings() as sup: + sup.filter(UserWarning) + res = differential_evolution(f, bounds, strategy='best1bin', + rng=1234, constraints=constraints) + + f_opt = 680.6300599487869 + x_opt = (2.330499, 1.951372, -0.4775414, 4.365726, + -0.6244870, 1.038131, 1.594227) + + assert_allclose(f(x_opt), f_opt) + assert_allclose(res.fun, f_opt) + assert_allclose(res.x, x_opt, atol=1e-5) + assert res.success + assert_(np.all(np.array(c1(res.x)) >= 0)) + assert_(np.all(res.x >= np.array(bounds)[:, 0])) + assert_(np.all(res.x <= np.array(bounds)[:, 1])) + + @pytest.mark.fail_slow(10) + def test_L3(self): + # Lampinen ([5]) test problem 3 + + def f(x): + x = np.hstack(([0], x)) # 1-indexed to match reference + fun = (x[1]**2 + x[2]**2 + x[1]*x[2] - 14*x[1] - 16*x[2] + + (x[3]-10)**2 + 4*(x[4]-5)**2 + (x[5]-3)**2 + 2*(x[6]-1)**2 + + 5*x[7]**2 + 7*(x[8]-11)**2 + 2*(x[9]-10)**2 + + (x[10] - 7)**2 + 45 + ) + return fun # maximize + + A = np.zeros((4, 11)) + A[1, [1, 2, 7, 8]] = -4, -5, 3, -9 + A[2, [1, 2, 7, 8]] = -10, 8, 17, -2 + A[3, [1, 2, 9, 10]] = 8, -2, -5, 2 + A = A[1:, 1:] + b = np.array([-105, 0, -12]) + + def c1(x): + x = np.hstack(([0], x)) # 1-indexed to match reference + return [3*x[1] - 6*x[2] - 12*(x[9]-8)**2 + 7*x[10], + -3*(x[1]-2)**2 - 4*(x[2]-3)**2 - 2*x[3]**2 + 7*x[4] + 120, + -x[1]**2 - 2*(x[2]-2)**2 + 2*x[1]*x[2] - 14*x[5] + 6*x[6], + -5*x[1]**2 - 8*x[2] - (x[3]-6)**2 + 2*x[4] + 40, + -0.5*(x[1]-8)**2 - 2*(x[2]-4)**2 - 3*x[5]**2 + x[6] + 30] + + L = LinearConstraint(A, b, np.inf) + N = NonlinearConstraint(c1, 0, np.inf) + bounds = [(-10, 10)]*10 + constraints = (L, N) + + with suppress_warnings() as sup: + sup.filter(UserWarning) + res = differential_evolution(f, bounds, rng=1234, + constraints=constraints, popsize=3) + + x_opt = (2.171996, 2.363683, 8.773926, 5.095984, 0.9906548, + 1.430574, 1.321644, 9.828726, 8.280092, 8.375927) + f_opt = 24.3062091 + + assert_allclose(f(x_opt), f_opt, atol=1e-5) + assert_allclose(res.x, x_opt, atol=1e-6) + assert_allclose(res.fun, f_opt, atol=1e-5) + assert res.success + assert_(np.all(A @ res.x >= b)) + assert_(np.all(np.array(c1(res.x)) >= 0)) + assert_(np.all(res.x >= np.array(bounds)[:, 0])) + assert_(np.all(res.x <= np.array(bounds)[:, 1])) + + @pytest.mark.fail_slow(10) + def test_L4(self): + # Lampinen ([5]) test problem 4 + def f(x): + return np.sum(x[:3]) + + A = np.zeros((4, 9)) + A[1, [4, 6]] = 0.0025, 0.0025 + A[2, [5, 7, 4]] = 0.0025, 0.0025, -0.0025 + A[3, [8, 5]] = 0.01, -0.01 + A = A[1:, 1:] + b = np.array([1, 1, 1]) + + def c1(x): + x = np.hstack(([0], x)) # 1-indexed to match reference + return [x[1]*x[6] - 833.33252*x[4] - 100*x[1] + 83333.333, + x[2]*x[7] - 1250*x[5] - x[2]*x[4] + 1250*x[4], + x[3]*x[8] - 1250000 - x[3]*x[5] + 2500*x[5]] + + L = LinearConstraint(A, -np.inf, 1) + N = NonlinearConstraint(c1, 0, np.inf) + + bounds = [(100, 10000)] + [(1000, 10000)]*2 + [(10, 1000)]*5 + constraints = (L, N) + + with suppress_warnings() as sup: + sup.filter(UserWarning) + res = differential_evolution( + f, bounds, strategy='best1bin', rng=1234, + constraints=constraints, popsize=3, tol=0.05 + ) + + f_opt = 7049.248 + + x_opt = [579.306692, 1359.97063, 5109.9707, 182.0177, 295.601172, + 217.9823, 286.416528, 395.601172] + + assert_allclose(f(x_opt), f_opt, atol=0.001) + assert_allclose(res.fun, f_opt, atol=0.001) + + # use higher tol here for 32-bit Windows, see gh-11693 + if (platform.system() == 'Windows' and np.dtype(np.intp).itemsize < 8): + assert_allclose(res.x, x_opt, rtol=2.4e-6, atol=0.0035) + else: + # tolerance determined from macOS + MKL failure, see gh-12701 + assert_allclose(res.x, x_opt, rtol=5e-6, atol=0.0024) + + assert res.success + assert_(np.all(A @ res.x <= b)) + assert_(np.all(np.array(c1(res.x)) >= 0)) + assert_(np.all(res.x >= np.array(bounds)[:, 0])) + assert_(np.all(res.x <= np.array(bounds)[:, 1])) + + @pytest.mark.fail_slow(10) + def test_L5(self): + # Lampinen ([5]) test problem 5 + + def f(x): + x = np.hstack(([0], x)) # 1-indexed to match reference + fun = (np.sin(2*np.pi*x[1])**3*np.sin(2*np.pi*x[2]) / + (x[1]**3*(x[1]+x[2]))) + return -fun # maximize + + def c1(x): + x = np.hstack(([0], x)) # 1-indexed to match reference + return [x[1]**2 - x[2] + 1, + 1 - x[1] + (x[2]-4)**2] + + N = NonlinearConstraint(c1, -np.inf, 0) + bounds = [(0, 10)]*2 + constraints = (N) + + res = differential_evolution(f, bounds, strategy='rand1bin', rng=1234, + constraints=constraints) + + x_opt = (1.22797135, 4.24537337) + f_opt = -0.095825 + assert_allclose(f(x_opt), f_opt, atol=2e-5) + assert_allclose(res.fun, f_opt, atol=1e-4) + assert res.success + assert_(np.all(np.array(c1(res.x)) <= 0)) + assert_(np.all(res.x >= np.array(bounds)[:, 0])) + assert_(np.all(res.x <= np.array(bounds)[:, 1])) + + @pytest.mark.fail_slow(10) + def test_L6(self): + # Lampinen ([5]) test problem 6 + def f(x): + x = np.hstack(([0], x)) # 1-indexed to match reference + fun = (x[1]-10)**3 + (x[2] - 20)**3 + return fun + + def c1(x): + x = np.hstack(([0], x)) # 1-indexed to match reference + return [(x[1]-5)**2 + (x[2] - 5)**2 - 100, + -(x[1]-6)**2 - (x[2] - 5)**2 + 82.81] + + N = NonlinearConstraint(c1, 0, np.inf) + bounds = [(13, 100), (0, 100)] + constraints = (N) + res = differential_evolution(f, bounds, strategy='rand1bin', rng=1234, + constraints=constraints, tol=1e-7) + x_opt = (14.095, 0.84296) + f_opt = -6961.814744 + + assert_allclose(f(x_opt), f_opt, atol=1e-6) + assert_allclose(res.fun, f_opt, atol=0.001) + assert_allclose(res.x, x_opt, atol=1e-4) + assert res.success + assert_(np.all(np.array(c1(res.x)) >= 0)) + assert_(np.all(res.x >= np.array(bounds)[:, 0])) + assert_(np.all(res.x <= np.array(bounds)[:, 1])) + + def test_L7(self): + # Lampinen ([5]) test problem 7 + def f(x): + x = np.hstack(([0], x)) # 1-indexed to match reference + fun = (5.3578547*x[3]**2 + 0.8356891*x[1]*x[5] + + 37.293239*x[1] - 40792.141) + return fun + + def c1(x): + x = np.hstack(([0], x)) # 1-indexed to match reference + return [ + 85.334407 + 0.0056858*x[2]*x[5] + 0.0006262*x[1]*x[4] - + 0.0022053*x[3]*x[5], + + 80.51249 + 0.0071317*x[2]*x[5] + 0.0029955*x[1]*x[2] + + 0.0021813*x[3]**2, + + 9.300961 + 0.0047026*x[3]*x[5] + 0.0012547*x[1]*x[3] + + 0.0019085*x[3]*x[4] + ] + + N = NonlinearConstraint(c1, [0, 90, 20], [92, 110, 25]) + + bounds = [(78, 102), (33, 45)] + [(27, 45)]*3 + constraints = (N) + + res = differential_evolution(f, bounds, strategy='rand1bin', rng=1234, + constraints=constraints) + + # using our best solution, rather than Lampinen/Koziel. Koziel solution + # doesn't satisfy constraints, Lampinen f_opt just plain wrong. + x_opt = [78.00000686, 33.00000362, 29.99526064, 44.99999971, + 36.77579979] + + f_opt = -30665.537578 + + assert_allclose(f(x_opt), f_opt) + assert_allclose(res.x, x_opt, atol=1e-3) + assert_allclose(res.fun, f_opt, atol=1e-3) + + assert res.success + assert_(np.all(np.array(c1(res.x)) >= np.array([0, 90, 20]))) + assert_(np.all(np.array(c1(res.x)) <= np.array([92, 110, 25]))) + assert_(np.all(res.x >= np.array(bounds)[:, 0])) + assert_(np.all(res.x <= np.array(bounds)[:, 1])) + + @pytest.mark.xslow + @pytest.mark.xfail(platform.machine() == 'ppc64le', + reason="fails on ppc64le") + def test_L8(self): + def f(x): + x = np.hstack(([0], x)) # 1-indexed to match reference + fun = 3*x[1] + 0.000001*x[1]**3 + 2*x[2] + 0.000002/3*x[2]**3 + return fun + + A = np.zeros((3, 5)) + A[1, [4, 3]] = 1, -1 + A[2, [3, 4]] = 1, -1 + A = A[1:, 1:] + b = np.array([-.55, -.55]) + + def c1(x): + x = np.hstack(([0], x)) # 1-indexed to match reference + return [ + 1000*np.sin(-x[3]-0.25) + 1000*np.sin(-x[4]-0.25) + + 894.8 - x[1], + 1000*np.sin(x[3]-0.25) + 1000*np.sin(x[3]-x[4]-0.25) + + 894.8 - x[2], + 1000*np.sin(x[4]-0.25) + 1000*np.sin(x[4]-x[3]-0.25) + + 1294.8 + ] + L = LinearConstraint(A, b, np.inf) + N = NonlinearConstraint(c1, np.full(3, -0.001), np.full(3, 0.001)) + + bounds = [(0, 1200)]*2+[(-.55, .55)]*2 + constraints = (L, N) + + with suppress_warnings() as sup: + sup.filter(UserWarning) + # original Lampinen test was with rand1bin, but that takes a + # huge amount of CPU time. Changing strategy to best1bin speeds + # things up a lot + res = differential_evolution(f, bounds, strategy='best1bin', + rng=1234, constraints=constraints, + maxiter=5000) + + x_opt = (679.9453, 1026.067, 0.1188764, -0.3962336) + f_opt = 5126.4981 + + assert_allclose(f(x_opt), f_opt, atol=1e-3) + assert_allclose(res.x[:2], x_opt[:2], atol=2e-3) + assert_allclose(res.x[2:], x_opt[2:], atol=2e-3) + assert_allclose(res.fun, f_opt, atol=2e-2) + assert res.success + assert_(np.all(A@res.x >= b)) + assert_(np.all(np.array(c1(res.x)) >= -0.001)) + assert_(np.all(np.array(c1(res.x)) <= 0.001)) + assert_(np.all(res.x >= np.array(bounds)[:, 0])) + assert_(np.all(res.x <= np.array(bounds)[:, 1])) + + @pytest.mark.fail_slow(5) + def test_L9(self): + # Lampinen ([5]) test problem 9 + + def f(x): + x = np.hstack(([0], x)) # 1-indexed to match reference + return x[1]**2 + (x[2]-1)**2 + + def c1(x): + x = np.hstack(([0], x)) # 1-indexed to match reference + return [x[2] - x[1]**2] + + N = NonlinearConstraint(c1, [-.001], [0.001]) + + bounds = [(-1, 1)]*2 + constraints = (N) + res = differential_evolution(f, bounds, strategy='rand1bin', rng=1234, + constraints=constraints) + + x_opt = [np.sqrt(2)/2, 0.5] + f_opt = 0.75 + + assert_allclose(f(x_opt), f_opt) + assert_allclose(np.abs(res.x), x_opt, atol=1e-3) + assert_allclose(res.fun, f_opt, atol=1e-3) + assert res.success + assert_(np.all(np.array(c1(res.x)) >= -0.001)) + assert_(np.all(np.array(c1(res.x)) <= 0.001)) + assert_(np.all(res.x >= np.array(bounds)[:, 0])) + assert_(np.all(res.x <= np.array(bounds)[:, 1])) + + @pytest.mark.fail_slow(10) + def test_integrality(self): + # test fitting discrete distribution to data + rng = np.random.default_rng(6519843218105) + dist = stats.nbinom + shapes = (5, 0.5) + x = dist.rvs(*shapes, size=10000, random_state=rng) + + def func(p, *args): + dist, x = args + # negative log-likelihood function + ll = -np.log(dist.pmf(x, *p)).sum(axis=-1) + if np.isnan(ll): # occurs when x is outside of support + ll = np.inf # we don't want that + return ll + + integrality = [True, False] + bounds = [(1, 18), (0, 0.95)] + + res = differential_evolution(func, bounds, args=(dist, x), + integrality=integrality, polish=False, + rng=rng) + # tolerance has to be fairly relaxed for the second parameter + # because we're fitting a distribution to random variates. + assert res.x[0] == 5 + assert_allclose(res.x, shapes, rtol=0.025) + + # check that we can still use integrality constraints with polishing + res2 = differential_evolution(func, bounds, args=(dist, x), + integrality=integrality, polish=True, + rng=rng) + + def func2(p, *args): + n, dist, x = args + return func(np.array([n, p[0]]), dist, x) + + # compare the DE derived solution to an LBFGSB solution (that doesn't + # have to find the integral values). Note we're setting x0 to be the + # output from the first DE result, thereby making the polishing step + # and this minimisation pretty much equivalent. + LBFGSB = minimize(func2, res2.x[1], args=(5, dist, x), + bounds=[(0, 0.95)]) + assert_allclose(res2.x[1], LBFGSB.x) + assert res2.fun <= res.fun + + def test_integrality_limits(self): + def f(x): + return x + + integrality = [True, False, True] + bounds = [(0.2, 1.1), (0.9, 2.2), (3.3, 4.9)] + + # no integrality constraints + solver = DifferentialEvolutionSolver(f, bounds=bounds, polish=False, + integrality=False) + assert_allclose(solver.limits[0], [0.2, 0.9, 3.3]) + assert_allclose(solver.limits[1], [1.1, 2.2, 4.9]) + + # with integrality constraints + solver = DifferentialEvolutionSolver(f, bounds=bounds, polish=False, + integrality=integrality) + assert_allclose(solver.limits[0], [0.5, 0.9, 3.5]) + assert_allclose(solver.limits[1], [1.5, 2.2, 4.5]) + assert_equal(solver.integrality, [True, False, True]) + assert solver.polish is False + + bounds = [(-1.2, -0.9), (0.9, 2.2), (-10.3, 4.1)] + solver = DifferentialEvolutionSolver(f, bounds=bounds, polish=False, + integrality=integrality) + assert_allclose(solver.limits[0], [-1.5, 0.9, -10.5]) + assert_allclose(solver.limits[1], [-0.5, 2.2, 4.5]) + + # A lower bound of -1.2 is converted to + # np.nextafter(np.ceil(-1.2) - 0.5, np.inf) + # with a similar process to the upper bound. Check that the + # conversions work + assert_allclose(np.round(solver.limits[0]), [-1.0, 1.0, -10.0]) + assert_allclose(np.round(solver.limits[1]), [-1.0, 2.0, 4.0]) + + bounds = [(-10.2, -8.1), (0.9, 2.2), (-10.9, -9.9999)] + solver = DifferentialEvolutionSolver(f, bounds=bounds, polish=False, + integrality=integrality) + assert_allclose(solver.limits[0], [-10.5, 0.9, -10.5]) + assert_allclose(solver.limits[1], [-8.5, 2.2, -9.5]) + + bounds = [(-10.2, -10.1), (0.9, 2.2), (-10.9, -9.9999)] + with pytest.raises(ValueError, match='One of the integrality'): + DifferentialEvolutionSolver(f, bounds=bounds, polish=False, + integrality=integrality) + + @pytest.mark.thread_unsafe + @pytest.mark.fail_slow(10) + def test_vectorized(self): + def quadratic(x): + return np.sum(x**2) + + def quadratic_vec(x): + return np.sum(x**2, axis=0) + + # A vectorized function needs to accept (len(x), S) and return (S,) + with pytest.raises(RuntimeError, match='The vectorized function'): + differential_evolution(quadratic, self.bounds, + vectorized=True, updating='deferred') + + # vectorized overrides the updating keyword, check for warning + with warns(UserWarning, match="differential_evolution: the 'vector"): + differential_evolution(quadratic_vec, self.bounds, + vectorized=True) + + # vectorized defers to the workers keyword, check for warning + with warns(UserWarning, match="differential_evolution: the 'workers"): + differential_evolution(quadratic_vec, self.bounds, + vectorized=True, workers=map, + updating='deferred') + + ncalls = [0] + + def rosen_vec(x): + ncalls[0] += 1 + return rosen(x) + + bounds = [(0, 10), (0, 10)] + res1 = differential_evolution(rosen, bounds, updating='deferred', + rng=1) + res2 = differential_evolution(rosen_vec, bounds, vectorized=True, + updating='deferred', rng=1) + + # the two minimisation runs should be functionally equivalent + assert_allclose(res1.x, res2.x) + assert ncalls[0] == res2.nfev + assert res1.nit == res2.nit + + def test_vectorized_constraints(self): + def constr_f(x): + return np.array([x[0] + x[1]]) + + def constr_f2(x): + return np.array([x[0]**2 + x[1], x[0] - x[1]]) + + nlc1 = NonlinearConstraint(constr_f, -np.inf, 1.9) + nlc2 = NonlinearConstraint(constr_f2, (0.9, 0.5), (2.0, 2.0)) + + def rosen_vec(x): + # accept an (len(x0), S) array, returning a (S,) array + v = 100 * (x[1:] - x[:-1]**2.0)**2.0 + v += (1 - x[:-1])**2.0 + return np.squeeze(v) + + bounds = [(0, 10), (0, 10)] + + res1 = differential_evolution(rosen, bounds, updating='deferred', + rng=1, constraints=[nlc1, nlc2], + polish=False) + res2 = differential_evolution(rosen_vec, bounds, vectorized=True, + updating='deferred', rng=1, + constraints=[nlc1, nlc2], + polish=False) + # the two minimisation runs should be functionally equivalent + assert_allclose(res1.x, res2.x) + + def test_constraint_violation_error_message(self): + + def func(x): + return np.cos(x[0]) + np.sin(x[1]) + + # Intentionally infeasible constraints. + c0 = NonlinearConstraint(lambda x: x[1] - (x[0]-1)**2, 0, np.inf) + c1 = NonlinearConstraint(lambda x: x[1] + x[0]**2, -np.inf, 0) + + result = differential_evolution(func, + bounds=[(-1, 2), (-1, 1)], + constraints=[c0, c1], + maxiter=10, + polish=False, + rng=864197532) + assert result.success is False + # The numerical value in the error message might be sensitive to + # changes in the implementation. It can be updated if the code is + # changed. The essential part of the test is that there is a number + # after the '=', so if necessary, the text could be reduced to, say, + # "MAXCV = 0.". + assert "MAXCV = 0." in result.message + + @pytest.mark.fail_slow(20) # fail-slow exception by request - see gh-20806 + def test_strategy_fn(self): + # examines ability to customize strategy by mimicking one of the + # in-built strategies + parameter_count = 4 + popsize = 10 + bounds = [(0, 10.)] * parameter_count + total_popsize = parameter_count * popsize + mutation = 0.8 + recombination = 0.7 + + calls = [0] + def custom_strategy_fn(candidate, population, rng=None): + calls[0] += 1 + trial = np.copy(population[candidate]) + fill_point = rng.choice(parameter_count) + + pool = np.arange(total_popsize) + rng.shuffle(pool) + idxs = pool[:2 + 1] + idxs = idxs[idxs != candidate][:2] + + r0, r1 = idxs[:2] + + bprime = (population[0] + mutation * + (population[r0] - population[r1])) + + crossovers = rng.uniform(size=parameter_count) + crossovers = crossovers < recombination + crossovers[fill_point] = True + trial = np.where(crossovers, bprime, trial) + return trial + + solver = DifferentialEvolutionSolver( + rosen, + bounds, + popsize=popsize, + recombination=recombination, + mutation=mutation, + maxiter=2, + strategy=custom_strategy_fn, + rng=10, + polish=False + ) + assert solver.strategy is custom_strategy_fn + solver.solve() + assert calls[0] > 0 + + # check custom strategy works with updating='deferred' + res = differential_evolution( + rosen, bounds, strategy=custom_strategy_fn, updating='deferred' + ) + assert res.success + + def custom_strategy_fn(candidate, population, rng=None): + return np.array([1.0, 2.0]) + + with pytest.raises(RuntimeError, match="strategy*"): + differential_evolution( + rosen, + bounds, + strategy=custom_strategy_fn + ) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test__dual_annealing.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test__dual_annealing.py new file mode 100644 index 0000000000000000000000000000000000000000..3465be508491aae411e113167b8fdd84f6d2d70b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test__dual_annealing.py @@ -0,0 +1,416 @@ +# Dual annealing unit tests implementation. +# Copyright (c) 2018 Sylvain Gubian , +# Yang Xiang +# Author: Sylvain Gubian, PMP S.A. +""" +Unit tests for the dual annealing global optimizer +""" +from scipy.optimize import dual_annealing, Bounds + +from scipy.optimize._dual_annealing import EnergyState +from scipy.optimize._dual_annealing import LocalSearchWrapper +from scipy.optimize._dual_annealing import ObjectiveFunWrapper +from scipy.optimize._dual_annealing import StrategyChain +from scipy.optimize._dual_annealing import VisitingDistribution +from scipy.optimize import rosen, rosen_der +import pytest +import numpy as np +from numpy.testing import assert_equal, assert_allclose, assert_array_less +from pytest import raises as assert_raises +from scipy._lib._util import check_random_state + +import threading + + +class TestDualAnnealing: + + def setup_method(self): + # A function that returns always infinity for initialization tests + self.weirdfunc = lambda x: np.inf + # 2-D bounds for testing function + self.ld_bounds = [(-5.12, 5.12)] * 2 + # 4-D bounds for testing function + self.hd_bounds = self.ld_bounds * 4 + # Number of values to be generated for testing visit function + self.nbtestvalues = 5000 + self.high_temperature = 5230 + self.low_temperature = 0.1 + self.qv = 2.62 + self.seed = 1234 + self.rng = check_random_state(self.seed) + self.nb_fun_call = threading.local() + self.ngev = threading.local() + + def callback(self, x, f, context): + # For testing callback mechanism. Should stop for e <= 1 as + # the callback function returns True + if f <= 1.0: + return True + + def func(self, x, args=()): + # Using Rastrigin function for performing tests + if args: + shift = args + else: + shift = 0 + y = np.sum((x - shift) ** 2 - 10 * np.cos(2 * np.pi * ( + x - shift))) + 10 * np.size(x) + shift + if not hasattr(self.nb_fun_call, 'c'): + self.nb_fun_call.c = 0 + self.nb_fun_call.c += 1 + return y + + def rosen_der_wrapper(self, x, args=()): + if not hasattr(self.ngev, 'c'): + self.ngev.c = 0 + self.ngev.c += 1 + return rosen_der(x, *args) + + # FIXME: there are some discontinuities in behaviour as a function of `qv`, + # this needs investigating - see gh-12384 + @pytest.mark.parametrize('qv', [1.1, 1.41, 2, 2.62, 2.9]) + def test_visiting_stepping(self, qv): + lu = list(zip(*self.ld_bounds)) + lower = np.array(lu[0]) + upper = np.array(lu[1]) + dim = lower.size + vd = VisitingDistribution(lower, upper, qv, self.rng) + values = np.zeros(dim) + x_step_low = vd.visiting(values, 0, self.high_temperature) + # Make sure that only the first component is changed + assert_equal(np.not_equal(x_step_low, 0), True) + values = np.zeros(dim) + x_step_high = vd.visiting(values, dim, self.high_temperature) + # Make sure that component other than at dim has changed + assert_equal(np.not_equal(x_step_high[0], 0), True) + + @pytest.mark.parametrize('qv', [2.25, 2.62, 2.9]) + def test_visiting_dist_high_temperature(self, qv): + lu = list(zip(*self.ld_bounds)) + lower = np.array(lu[0]) + upper = np.array(lu[1]) + vd = VisitingDistribution(lower, upper, qv, self.rng) + # values = np.zeros(self.nbtestvalues) + # for i in np.arange(self.nbtestvalues): + # values[i] = vd.visit_fn(self.high_temperature) + values = vd.visit_fn(self.high_temperature, self.nbtestvalues) + + # Visiting distribution is a distorted version of Cauchy-Lorentz + # distribution, and as no 1st and higher moments (no mean defined, + # no variance defined). + # Check that big tails values are generated + assert_array_less(np.min(values), 1e-10) + assert_array_less(1e+10, np.max(values)) + + def test_reset(self): + owf = ObjectiveFunWrapper(self.weirdfunc) + lu = list(zip(*self.ld_bounds)) + lower = np.array(lu[0]) + upper = np.array(lu[1]) + es = EnergyState(lower, upper) + assert_raises(ValueError, es.reset, owf, check_random_state(None)) + + def test_low_dim(self): + ret = dual_annealing( + self.func, self.ld_bounds, rng=self.seed) + assert_allclose(ret.fun, 0., atol=1e-12) + assert ret.success + + @pytest.mark.fail_slow(10) + def test_high_dim(self): + ret = dual_annealing(self.func, self.hd_bounds, rng=self.seed) + assert_allclose(ret.fun, 0., atol=1e-12) + assert ret.success + + def test_low_dim_no_ls(self): + ret = dual_annealing(self.func, self.ld_bounds, + no_local_search=True, seed=self.seed) + assert_allclose(ret.fun, 0., atol=1e-4) + + @pytest.mark.fail_slow(10) + def test_high_dim_no_ls(self): + ret = dual_annealing(self.func, self.hd_bounds, + no_local_search=True, rng=self.seed) + assert_allclose(ret.fun, 0., atol=1.2e-4) + + def test_nb_fun_call(self): + self.nb_fun_call.c = 0 + ret = dual_annealing(self.func, self.ld_bounds, rng=self.seed) + assert_equal(self.nb_fun_call.c, ret.nfev) + + def test_nb_fun_call_no_ls(self): + self.nb_fun_call.c = 0 + ret = dual_annealing(self.func, self.ld_bounds, + no_local_search=True, rng=self.seed) + assert_equal(self.nb_fun_call.c, ret.nfev) + + def test_max_reinit(self): + assert_raises(ValueError, dual_annealing, self.weirdfunc, + self.ld_bounds) + + @pytest.mark.fail_slow(10) + def test_reproduce(self): + res1 = dual_annealing(self.func, self.ld_bounds, rng=self.seed) + res2 = dual_annealing(self.func, self.ld_bounds, rng=self.seed) + res3 = dual_annealing(self.func, self.ld_bounds, rng=self.seed) + # If we have reproducible results, x components found has to + # be exactly the same, which is not the case with no seeding + assert_equal(res1.x, res2.x) + assert_equal(res1.x, res3.x) + + def test_rand_gen(self): + # check that np.random.Generator can be used (numpy >= 1.17) + # obtain a np.random.Generator object + rng = np.random.default_rng(1) + + res1 = dual_annealing(self.func, self.ld_bounds, rng=rng) + # seed again + rng = np.random.default_rng(1) + res2 = dual_annealing(self.func, self.ld_bounds, rng=rng) + # If we have reproducible results, x components found has to + # be exactly the same, which is not the case with no seeding + assert_equal(res1.x, res2.x) + + def test_bounds_integrity(self): + wrong_bounds = [(-5.12, 5.12), (1, 0), (5.12, 5.12)] + assert_raises(ValueError, dual_annealing, self.func, + wrong_bounds) + + def test_bound_validity(self): + invalid_bounds = [(-5, 5), (-np.inf, 0), (-5, 5)] + assert_raises(ValueError, dual_annealing, self.func, + invalid_bounds) + invalid_bounds = [(-5, 5), (0, np.inf), (-5, 5)] + assert_raises(ValueError, dual_annealing, self.func, + invalid_bounds) + invalid_bounds = [(-5, 5), (0, np.nan), (-5, 5)] + assert_raises(ValueError, dual_annealing, self.func, + invalid_bounds) + + @pytest.mark.thread_unsafe + def test_deprecated_local_search_options_bounds(self): + def func(x): + return np.sum((x - 5) * (x - 1)) + bounds = list(zip([-6, -5], [6, 5])) + # Test bounds can be passed (see gh-10831) + + with pytest.warns(RuntimeWarning, match=r"Method CG cannot handle "): + dual_annealing( + func, + bounds=bounds, + minimizer_kwargs={"method": "CG", "bounds": bounds}) + + @pytest.mark.thread_unsafe + def test_minimizer_kwargs_bounds(self): + def func(x): + return np.sum((x - 5) * (x - 1)) + bounds = list(zip([-6, -5], [6, 5])) + # Test bounds can be passed (see gh-10831) + dual_annealing( + func, + bounds=bounds, + minimizer_kwargs={"method": "SLSQP", "bounds": bounds}) + + with pytest.warns(RuntimeWarning, match=r"Method CG cannot handle "): + dual_annealing( + func, + bounds=bounds, + minimizer_kwargs={"method": "CG", "bounds": bounds}) + + def test_max_fun_ls(self): + ret = dual_annealing(self.func, self.ld_bounds, maxfun=100, + rng=self.seed) + + ls_max_iter = min(max( + len(self.ld_bounds) * LocalSearchWrapper.LS_MAXITER_RATIO, + LocalSearchWrapper.LS_MAXITER_MIN), + LocalSearchWrapper.LS_MAXITER_MAX) + assert ret.nfev <= 100 + ls_max_iter + assert not ret.success + + def test_max_fun_no_ls(self): + ret = dual_annealing(self.func, self.ld_bounds, + no_local_search=True, maxfun=500, rng=self.seed) + assert ret.nfev <= 500 + assert not ret.success + + def test_maxiter(self): + ret = dual_annealing(self.func, self.ld_bounds, maxiter=700, + rng=self.seed) + assert ret.nit <= 700 + + # Testing that args are passed correctly for dual_annealing + def test_fun_args_ls(self): + ret = dual_annealing(self.func, self.ld_bounds, + args=((3.14159,)), rng=self.seed) + assert_allclose(ret.fun, 3.14159, atol=1e-6) + + # Testing that args are passed correctly for pure simulated annealing + def test_fun_args_no_ls(self): + ret = dual_annealing(self.func, self.ld_bounds, + args=((3.14159, )), no_local_search=True, + rng=self.seed) + assert_allclose(ret.fun, 3.14159, atol=1e-4) + + def test_callback_stop(self): + # Testing that callback make the algorithm stop for + # fun value <= 1.0 (see callback method) + ret = dual_annealing(self.func, self.ld_bounds, + callback=self.callback, rng=self.seed) + assert ret.fun <= 1.0 + assert 'stop early' in ret.message[0] + assert not ret.success + + @pytest.mark.parametrize('method, atol', [ + ('Nelder-Mead', 2e-5), + ('COBYLA', 1e-5), + ('COBYQA', 1e-8), + ('Powell', 1e-8), + ('CG', 1e-8), + ('BFGS', 1e-8), + ('TNC', 1e-8), + ('SLSQP', 2e-7), + ]) + def test_multi_ls_minimizer(self, method, atol): + ret = dual_annealing(self.func, self.ld_bounds, + minimizer_kwargs=dict(method=method), + rng=self.seed) + assert_allclose(ret.fun, 0., atol=atol) + + def test_wrong_restart_temp(self): + assert_raises(ValueError, dual_annealing, self.func, + self.ld_bounds, restart_temp_ratio=1) + assert_raises(ValueError, dual_annealing, self.func, + self.ld_bounds, restart_temp_ratio=0) + + def test_gradient_gnev(self): + minimizer_opts = { + 'jac': self.rosen_der_wrapper, + } + ret = dual_annealing(rosen, self.ld_bounds, + minimizer_kwargs=minimizer_opts, + rng=self.seed) + assert ret.njev == self.ngev.c + + @pytest.mark.fail_slow(10) + def test_from_docstring(self): + def func(x): + return np.sum(x * x - 10 * np.cos(2 * np.pi * x)) + 10 * np.size(x) + lw = [-5.12] * 10 + up = [5.12] * 10 + ret = dual_annealing(func, bounds=list(zip(lw, up)), rng=1234) + assert_allclose(ret.x, + [-4.26437714e-09, -3.91699361e-09, -1.86149218e-09, + -3.97165720e-09, -6.29151648e-09, -6.53145322e-09, + -3.93616815e-09, -6.55623025e-09, -6.05775280e-09, + -5.00668935e-09], atol=4e-8) + assert_allclose(ret.fun, 0.000000, atol=5e-13) + + @pytest.mark.parametrize('new_e, temp_step, accepted, accept_rate', [ + (0, 100, 1000, 1.0097587941791923), + (0, 2, 1000, 1.2599210498948732), + (10, 100, 878, 0.8786035869128718), + (10, 60, 695, 0.6812920690579612), + (2, 100, 990, 0.9897404249173424), + ]) + def test_accept_reject_probabilistic( + self, new_e, temp_step, accepted, accept_rate): + # Test accepts unconditionally with e < current_energy and + # probabilistically with e > current_energy + + rs = check_random_state(123) + + count_accepted = 0 + iterations = 1000 + + accept_param = -5 + current_energy = 1 + for _ in range(iterations): + energy_state = EnergyState(lower=None, upper=None) + # Set energy state with current_energy, any location. + energy_state.update_current(current_energy, [0]) + + chain = StrategyChain( + accept_param, None, None, None, rs, energy_state) + # Normally this is set in run() + chain.temperature_step = temp_step + + # Check if update is accepted. + chain.accept_reject(j=1, e=new_e, x_visit=[2]) + if energy_state.current_energy == new_e: + count_accepted += 1 + + assert count_accepted == accepted + + # Check accept rate + pqv = 1 - (1 - accept_param) * (new_e - current_energy) / temp_step + rate = 0 if pqv <= 0 else np.exp(np.log(pqv) / (1 - accept_param)) + + assert_allclose(rate, accept_rate) + + @pytest.mark.fail_slow(10) + def test_bounds_class(self): + # test that result does not depend on the bounds type + def func(x): + f = np.sum(x * x - 10 * np.cos(2 * np.pi * x)) + 10 * np.size(x) + return f + lw = [-5.12] * 5 + up = [5.12] * 5 + + # Unbounded global minimum is all zeros. Most bounds below will force + # a DV away from unbounded minimum and be active at solution. + up[0] = -2.0 + up[1] = -1.0 + lw[3] = 1.0 + lw[4] = 2.0 + + # run optimizations + bounds = Bounds(lw, up) + ret_bounds_class = dual_annealing(func, bounds=bounds, rng=1234) + + bounds_old = list(zip(lw, up)) + ret_bounds_list = dual_annealing(func, bounds=bounds_old, rng=1234) + + # test that found minima, function evaluations and iterations match + assert_allclose(ret_bounds_class.x, ret_bounds_list.x, atol=1e-8) + assert_allclose(ret_bounds_class.x, np.arange(-2, 3), atol=1e-7) + assert_allclose(ret_bounds_list.fun, ret_bounds_class.fun, atol=1e-9) + assert ret_bounds_list.nfev == ret_bounds_class.nfev + + @pytest.mark.fail_slow(10) + def test_callable_jac_hess_with_args_gh11052(self): + # dual_annealing used to fail when `jac` was callable and `args` were + # used; check that this is resolved. Example is from gh-11052. + + # extended to hess as part of closing gh20614 + rng = np.random.default_rng(94253637693657847462) + def f(x, power): + return np.sum(np.exp(x ** power)) + + def jac(x, power): + return np.exp(x ** power) * power * x ** (power - 1) + + def hess(x, power): + # calculated using WolframAlpha as d^2/dx^2 e^(x^p) + return np.diag( + power * np.exp(x ** power) * x ** (power - 2) * + (power * x ** power + power - 1) + ) + + def hessp(x, p, power): + return hess(x, power) @ p + + res1 = dual_annealing(f, args=(2, ), bounds=[[0, 1], [0, 1]], rng=rng, + minimizer_kwargs=dict(method='L-BFGS-B')) + res2 = dual_annealing(f, args=(2, ), bounds=[[0, 1], [0, 1]], rng=rng, + minimizer_kwargs=dict(method='L-BFGS-B', + jac=jac)) + res3 = dual_annealing(f, args=(2, ), bounds=[[0, 1], [0, 1]], rng=rng, + minimizer_kwargs=dict(method='newton-cg', + jac=jac, hess=hess)) + res4 = dual_annealing(f, args=(2, ), bounds=[[0, 1], [0, 1]], rng=rng, + minimizer_kwargs=dict(method='newton-cg', + jac=jac, hessp=hessp)) + assert_allclose(res1.fun, res2.fun, rtol=1e-6) + assert_allclose(res3.fun, res2.fun, rtol=1e-6) + assert_allclose(res4.fun, res2.fun, rtol=1e-6) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test__linprog_clean_inputs.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test__linprog_clean_inputs.py new file mode 100644 index 0000000000000000000000000000000000000000..3b0e4097bc9aadbfd3335aa3a86d063216f2c69a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test__linprog_clean_inputs.py @@ -0,0 +1,310 @@ +""" +Unit test for Linear Programming via Simplex Algorithm. +""" +import numpy as np +from numpy.testing import assert_, assert_allclose, assert_equal +from pytest import raises as assert_raises +from scipy.optimize._linprog_util import _clean_inputs, _LPProblem +from scipy._lib._util import VisibleDeprecationWarning +from copy import deepcopy +from datetime import date + + +def test_aliasing(): + """ + Test for ensuring that no objects referred to by `lp` attributes, + `c`, `A_ub`, `b_ub`, `A_eq`, `b_eq`, `bounds`, have been modified + by `_clean_inputs` as a side effect. + """ + lp = _LPProblem( + c=1, + A_ub=[[1]], + b_ub=[1], + A_eq=[[1]], + b_eq=[1], + bounds=(-np.inf, np.inf) + ) + lp_copy = deepcopy(lp) + + _clean_inputs(lp) + + assert_(lp.c == lp_copy.c, "c modified by _clean_inputs") + assert_(lp.A_ub == lp_copy.A_ub, "A_ub modified by _clean_inputs") + assert_(lp.b_ub == lp_copy.b_ub, "b_ub modified by _clean_inputs") + assert_(lp.A_eq == lp_copy.A_eq, "A_eq modified by _clean_inputs") + assert_(lp.b_eq == lp_copy.b_eq, "b_eq modified by _clean_inputs") + assert_(lp.bounds == lp_copy.bounds, "bounds modified by _clean_inputs") + + +def test_aliasing2(): + """ + Similar purpose as `test_aliasing` above. + """ + lp = _LPProblem( + c=np.array([1, 1]), + A_ub=np.array([[1, 1], [2, 2]]), + b_ub=np.array([[1], [1]]), + A_eq=np.array([[1, 1]]), + b_eq=np.array([1]), + bounds=[(-np.inf, np.inf), (None, 1)] + ) + lp_copy = deepcopy(lp) + + _clean_inputs(lp) + + assert_allclose(lp.c, lp_copy.c, err_msg="c modified by _clean_inputs") + assert_allclose(lp.A_ub, lp_copy.A_ub, err_msg="A_ub modified by _clean_inputs") + assert_allclose(lp.b_ub, lp_copy.b_ub, err_msg="b_ub modified by _clean_inputs") + assert_allclose(lp.A_eq, lp_copy.A_eq, err_msg="A_eq modified by _clean_inputs") + assert_allclose(lp.b_eq, lp_copy.b_eq, err_msg="b_eq modified by _clean_inputs") + assert_(lp.bounds == lp_copy.bounds, "bounds modified by _clean_inputs") + + +def test_missing_inputs(): + c = [1, 2] + A_ub = np.array([[1, 1], [2, 2]]) + b_ub = np.array([1, 1]) + A_eq = np.array([[1, 1], [2, 2]]) + b_eq = np.array([1, 1]) + + assert_raises(TypeError, _clean_inputs) + assert_raises(TypeError, _clean_inputs, _LPProblem(c=None)) + assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, A_ub=A_ub)) + assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, A_ub=A_ub, b_ub=None)) + assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, b_ub=b_ub)) + assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, A_ub=None, b_ub=b_ub)) + assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, A_eq=A_eq)) + assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, A_eq=A_eq, b_eq=None)) + assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, b_eq=b_eq)) + assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, A_eq=None, b_eq=b_eq)) + + +def test_too_many_dimensions(): + cb = [1, 2, 3, 4] + A = np.random.rand(4, 4) + bad2D = [[1, 2], [3, 4]] + bad3D = np.random.rand(4, 4, 4) + assert_raises(ValueError, _clean_inputs, _LPProblem(c=bad2D, A_ub=A, b_ub=cb)) + assert_raises(ValueError, _clean_inputs, _LPProblem(c=cb, A_ub=bad3D, b_ub=cb)) + assert_raises(ValueError, _clean_inputs, _LPProblem(c=cb, A_ub=A, b_ub=bad2D)) + assert_raises(ValueError, _clean_inputs, _LPProblem(c=cb, A_eq=bad3D, b_eq=cb)) + assert_raises(ValueError, _clean_inputs, _LPProblem(c=cb, A_eq=A, b_eq=bad2D)) + + +def test_too_few_dimensions(): + bad = np.random.rand(4, 4).ravel() + cb = np.random.rand(4) + assert_raises(ValueError, _clean_inputs, _LPProblem(c=cb, A_ub=bad, b_ub=cb)) + assert_raises(ValueError, _clean_inputs, _LPProblem(c=cb, A_eq=bad, b_eq=cb)) + + +def test_inconsistent_dimensions(): + m = 2 + n = 4 + c = [1, 2, 3, 4] + + Agood = np.random.rand(m, n) + Abad = np.random.rand(m, n + 1) + bgood = np.random.rand(m) + bbad = np.random.rand(m + 1) + boundsbad = [(0, 1)] * (n + 1) + assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, A_ub=Abad, b_ub=bgood)) + assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, A_ub=Agood, b_ub=bbad)) + assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, A_eq=Abad, b_eq=bgood)) + assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, A_eq=Agood, b_eq=bbad)) + assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, bounds=boundsbad)) + with np.testing.suppress_warnings() as sup: + sup.filter(VisibleDeprecationWarning, "Creating an ndarray from ragged") + assert_raises(ValueError, _clean_inputs, + _LPProblem(c=c, bounds=[[1, 2], [2, 3], [3, 4], [4, 5, 6]])) + + +def test_type_errors(): + lp = _LPProblem( + c=[1, 2], + A_ub=np.array([[1, 1], [2, 2]]), + b_ub=np.array([1, 1]), + A_eq=np.array([[1, 1], [2, 2]]), + b_eq=np.array([1, 1]), + bounds=[(0, 1)] + ) + bad = "hello" + + assert_raises(TypeError, _clean_inputs, lp._replace(c=bad)) + assert_raises(TypeError, _clean_inputs, lp._replace(A_ub=bad)) + assert_raises(TypeError, _clean_inputs, lp._replace(b_ub=bad)) + assert_raises(TypeError, _clean_inputs, lp._replace(A_eq=bad)) + assert_raises(TypeError, _clean_inputs, lp._replace(b_eq=bad)) + + assert_raises(ValueError, _clean_inputs, lp._replace(bounds=bad)) + assert_raises(ValueError, _clean_inputs, lp._replace(bounds="hi")) + assert_raises(ValueError, _clean_inputs, lp._replace(bounds=["hi"])) + assert_raises(ValueError, _clean_inputs, lp._replace(bounds=[("hi")])) + assert_raises(ValueError, _clean_inputs, lp._replace(bounds=[(1, "")])) + assert_raises(ValueError, _clean_inputs, lp._replace(bounds=[(1, 2), (1, "")])) + assert_raises(TypeError, _clean_inputs, + lp._replace(bounds=[(1, date(2020, 2, 29))])) + assert_raises(ValueError, _clean_inputs, lp._replace(bounds=[[[1, 2]]])) + + +def test_non_finite_errors(): + lp = _LPProblem( + c=[1, 2], + A_ub=np.array([[1, 1], [2, 2]]), + b_ub=np.array([1, 1]), + A_eq=np.array([[1, 1], [2, 2]]), + b_eq=np.array([1, 1]), + bounds=[(0, 1)] + ) + assert_raises(ValueError, _clean_inputs, lp._replace(c=[0, None])) + assert_raises(ValueError, _clean_inputs, lp._replace(c=[np.inf, 0])) + assert_raises(ValueError, _clean_inputs, lp._replace(c=[0, -np.inf])) + assert_raises(ValueError, _clean_inputs, lp._replace(c=[np.nan, 0])) + + assert_raises(ValueError, _clean_inputs, lp._replace(A_ub=[[1, 2], [None, 1]])) + assert_raises(ValueError, _clean_inputs, lp._replace(b_ub=[np.inf, 1])) + assert_raises(ValueError, _clean_inputs, lp._replace(A_eq=[[1, 2], [1, -np.inf]])) + assert_raises(ValueError, _clean_inputs, lp._replace(b_eq=[1, np.nan])) + + +def test__clean_inputs1(): + lp = _LPProblem( + c=[1, 2], + A_ub=[[1, 1], [2, 2]], + b_ub=[1, 1], + A_eq=[[1, 1], [2, 2]], + b_eq=[1, 1], + bounds=None + ) + + lp_cleaned = _clean_inputs(lp) + + assert_allclose(lp_cleaned.c, np.array(lp.c)) + assert_allclose(lp_cleaned.A_ub, np.array(lp.A_ub)) + assert_allclose(lp_cleaned.b_ub, np.array(lp.b_ub)) + assert_allclose(lp_cleaned.A_eq, np.array(lp.A_eq)) + assert_allclose(lp_cleaned.b_eq, np.array(lp.b_eq)) + assert_equal(lp_cleaned.bounds, [(0, np.inf)] * 2) + + assert_(lp_cleaned.c.shape == (2,), "") + assert_(lp_cleaned.A_ub.shape == (2, 2), "") + assert_(lp_cleaned.b_ub.shape == (2,), "") + assert_(lp_cleaned.A_eq.shape == (2, 2), "") + assert_(lp_cleaned.b_eq.shape == (2,), "") + + +def test__clean_inputs2(): + lp = _LPProblem( + c=1, + A_ub=[[1]], + b_ub=1, + A_eq=[[1]], + b_eq=1, + bounds=(0, 1) + ) + + lp_cleaned = _clean_inputs(lp) + + assert_allclose(lp_cleaned.c, np.array(lp.c)) + assert_allclose(lp_cleaned.A_ub, np.array(lp.A_ub)) + assert_allclose(lp_cleaned.b_ub, np.array(lp.b_ub)) + assert_allclose(lp_cleaned.A_eq, np.array(lp.A_eq)) + assert_allclose(lp_cleaned.b_eq, np.array(lp.b_eq)) + assert_equal(lp_cleaned.bounds, [(0, 1)]) + + assert_(lp_cleaned.c.shape == (1,), "") + assert_(lp_cleaned.A_ub.shape == (1, 1), "") + assert_(lp_cleaned.b_ub.shape == (1,), "") + assert_(lp_cleaned.A_eq.shape == (1, 1), "") + assert_(lp_cleaned.b_eq.shape == (1,), "") + + +def test__clean_inputs3(): + lp = _LPProblem( + c=[[1, 2]], + A_ub=np.random.rand(2, 2), + b_ub=[[1], [2]], + A_eq=np.random.rand(2, 2), + b_eq=[[1], [2]], + bounds=[(0, 1)] + ) + + lp_cleaned = _clean_inputs(lp) + + assert_allclose(lp_cleaned.c, np.array([1, 2])) + assert_allclose(lp_cleaned.b_ub, np.array([1, 2])) + assert_allclose(lp_cleaned.b_eq, np.array([1, 2])) + assert_equal(lp_cleaned.bounds, [(0, 1)] * 2) + + assert_(lp_cleaned.c.shape == (2,), "") + assert_(lp_cleaned.b_ub.shape == (2,), "") + assert_(lp_cleaned.b_eq.shape == (2,), "") + + +def test_bad_bounds(): + lp = _LPProblem(c=[1, 2]) + + assert_raises(ValueError, _clean_inputs, lp._replace(bounds=(1, 2, 2))) + assert_raises(ValueError, _clean_inputs, lp._replace(bounds=[(1, 2, 2)])) + with np.testing.suppress_warnings() as sup: + sup.filter(VisibleDeprecationWarning, "Creating an ndarray from ragged") + assert_raises(ValueError, _clean_inputs, + lp._replace(bounds=[(1, 2), (1, 2, 2)])) + assert_raises(ValueError, _clean_inputs, + lp._replace(bounds=[(1, 2), (1, 2), (1, 2)])) + + lp = _LPProblem(c=[1, 2, 3, 4]) + + assert_raises(ValueError, _clean_inputs, + lp._replace(bounds=[(1, 2, 3, 4), (1, 2, 3, 4)])) + + +def test_good_bounds(): + lp = _LPProblem(c=[1, 2]) + + lp_cleaned = _clean_inputs(lp) # lp.bounds is None by default + assert_equal(lp_cleaned.bounds, [(0, np.inf)] * 2) + + lp_cleaned = _clean_inputs(lp._replace(bounds=[])) + assert_equal(lp_cleaned.bounds, [(0, np.inf)] * 2) + + lp_cleaned = _clean_inputs(lp._replace(bounds=[[]])) + assert_equal(lp_cleaned.bounds, [(0, np.inf)] * 2) + + lp_cleaned = _clean_inputs(lp._replace(bounds=(1, 2))) + assert_equal(lp_cleaned.bounds, [(1, 2)] * 2) + + lp_cleaned = _clean_inputs(lp._replace(bounds=[(1, 2)])) + assert_equal(lp_cleaned.bounds, [(1, 2)] * 2) + + lp_cleaned = _clean_inputs(lp._replace(bounds=[(1, None)])) + assert_equal(lp_cleaned.bounds, [(1, np.inf)] * 2) + + lp_cleaned = _clean_inputs(lp._replace(bounds=[(None, 1)])) + assert_equal(lp_cleaned.bounds, [(-np.inf, 1)] * 2) + + lp_cleaned = _clean_inputs(lp._replace(bounds=[(None, None), (-np.inf, None)])) + assert_equal(lp_cleaned.bounds, [(-np.inf, np.inf)] * 2) + + lp = _LPProblem(c=[1, 2, 3, 4]) + + lp_cleaned = _clean_inputs(lp) # lp.bounds is None by default + assert_equal(lp_cleaned.bounds, [(0, np.inf)] * 4) + + lp_cleaned = _clean_inputs(lp._replace(bounds=(1, 2))) + assert_equal(lp_cleaned.bounds, [(1, 2)] * 4) + + lp_cleaned = _clean_inputs(lp._replace(bounds=[(1, 2)])) + assert_equal(lp_cleaned.bounds, [(1, 2)] * 4) + + lp_cleaned = _clean_inputs(lp._replace(bounds=[(1, None)])) + assert_equal(lp_cleaned.bounds, [(1, np.inf)] * 4) + + lp_cleaned = _clean_inputs(lp._replace(bounds=[(None, 1)])) + assert_equal(lp_cleaned.bounds, [(-np.inf, 1)] * 4) + + lp_cleaned = _clean_inputs(lp._replace(bounds=[(None, None), + (-np.inf, None), + (None, np.inf), + (-np.inf, np.inf)])) + assert_equal(lp_cleaned.bounds, [(-np.inf, np.inf)] * 4) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test__numdiff.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test__numdiff.py new file mode 100644 index 0000000000000000000000000000000000000000..21fcf36b01f480ea23e15b67e4bebb1270d63c3b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test__numdiff.py @@ -0,0 +1,841 @@ +import math +from itertools import product + +import numpy as np +from numpy.testing import assert_allclose, assert_equal, assert_ +from pytest import raises as assert_raises + +from scipy.sparse import csr_matrix, csc_matrix, lil_matrix + +from scipy.optimize._numdiff import ( + _adjust_scheme_to_bounds, approx_derivative, check_derivative, + group_columns, _eps_for_method, _compute_absolute_step) + + +def test_group_columns(): + structure = [ + [1, 1, 0, 0, 0, 0], + [1, 1, 1, 0, 0, 0], + [0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0], + [0, 0, 0, 1, 1, 1], + [0, 0, 0, 0, 1, 1], + [0, 0, 0, 0, 0, 0] + ] + for transform in [np.asarray, csr_matrix, csc_matrix, lil_matrix]: + A = transform(structure) + order = np.arange(6) + groups_true = np.array([0, 1, 2, 0, 1, 2]) + groups = group_columns(A, order) + assert_equal(groups, groups_true) + + order = [1, 2, 4, 3, 5, 0] + groups_true = np.array([2, 0, 1, 2, 0, 1]) + groups = group_columns(A, order) + assert_equal(groups, groups_true) + + # Test repeatability. + groups_1 = group_columns(A) + groups_2 = group_columns(A) + assert_equal(groups_1, groups_2) + + +def test_correct_fp_eps(): + # check that relative step size is correct for FP size + EPS = np.finfo(np.float64).eps + relative_step = {"2-point": EPS**0.5, + "3-point": EPS**(1/3), + "cs": EPS**0.5} + for method in ['2-point', '3-point', 'cs']: + assert_allclose( + _eps_for_method(np.float64, np.float64, method), + relative_step[method]) + assert_allclose( + _eps_for_method(np.complex128, np.complex128, method), + relative_step[method] + ) + + # check another FP size + EPS = np.finfo(np.float32).eps + relative_step = {"2-point": EPS**0.5, + "3-point": EPS**(1/3), + "cs": EPS**0.5} + + for method in ['2-point', '3-point', 'cs']: + assert_allclose( + _eps_for_method(np.float64, np.float32, method), + relative_step[method] + ) + assert_allclose( + _eps_for_method(np.float32, np.float64, method), + relative_step[method] + ) + assert_allclose( + _eps_for_method(np.float32, np.float32, method), + relative_step[method] + ) + + +class TestAdjustSchemeToBounds: + def test_no_bounds(self): + x0 = np.zeros(3) + h = np.full(3, 1e-2) + inf_lower = np.empty_like(x0) + inf_upper = np.empty_like(x0) + inf_lower.fill(-np.inf) + inf_upper.fill(np.inf) + + h_adjusted, one_sided = _adjust_scheme_to_bounds( + x0, h, 1, '1-sided', inf_lower, inf_upper) + assert_allclose(h_adjusted, h) + assert_(np.all(one_sided)) + + h_adjusted, one_sided = _adjust_scheme_to_bounds( + x0, h, 2, '1-sided', inf_lower, inf_upper) + assert_allclose(h_adjusted, h) + assert_(np.all(one_sided)) + + h_adjusted, one_sided = _adjust_scheme_to_bounds( + x0, h, 1, '2-sided', inf_lower, inf_upper) + assert_allclose(h_adjusted, h) + assert_(np.all(~one_sided)) + + h_adjusted, one_sided = _adjust_scheme_to_bounds( + x0, h, 2, '2-sided', inf_lower, inf_upper) + assert_allclose(h_adjusted, h) + assert_(np.all(~one_sided)) + + def test_with_bound(self): + x0 = np.array([0.0, 0.85, -0.85]) + lb = -np.ones(3) + ub = np.ones(3) + h = np.array([1, 1, -1]) * 1e-1 + + h_adjusted, _ = _adjust_scheme_to_bounds(x0, h, 1, '1-sided', lb, ub) + assert_allclose(h_adjusted, h) + + h_adjusted, _ = _adjust_scheme_to_bounds(x0, h, 2, '1-sided', lb, ub) + assert_allclose(h_adjusted, np.array([1, -1, 1]) * 1e-1) + + h_adjusted, one_sided = _adjust_scheme_to_bounds( + x0, h, 1, '2-sided', lb, ub) + assert_allclose(h_adjusted, np.abs(h)) + assert_(np.all(~one_sided)) + + h_adjusted, one_sided = _adjust_scheme_to_bounds( + x0, h, 2, '2-sided', lb, ub) + assert_allclose(h_adjusted, np.array([1, -1, 1]) * 1e-1) + assert_equal(one_sided, np.array([False, True, True])) + + def test_tight_bounds(self): + lb = np.array([-0.03, -0.03]) + ub = np.array([0.05, 0.05]) + x0 = np.array([0.0, 0.03]) + h = np.array([-0.1, -0.1]) + + h_adjusted, _ = _adjust_scheme_to_bounds(x0, h, 1, '1-sided', lb, ub) + assert_allclose(h_adjusted, np.array([0.05, -0.06])) + + h_adjusted, _ = _adjust_scheme_to_bounds(x0, h, 2, '1-sided', lb, ub) + assert_allclose(h_adjusted, np.array([0.025, -0.03])) + + h_adjusted, one_sided = _adjust_scheme_to_bounds( + x0, h, 1, '2-sided', lb, ub) + assert_allclose(h_adjusted, np.array([0.03, -0.03])) + assert_equal(one_sided, np.array([False, True])) + + h_adjusted, one_sided = _adjust_scheme_to_bounds( + x0, h, 2, '2-sided', lb, ub) + assert_allclose(h_adjusted, np.array([0.015, -0.015])) + assert_equal(one_sided, np.array([False, True])) + + +class TestApproxDerivativesDense: + def fun_scalar_scalar(self, x): + return np.sinh(x) + + def jac_scalar_scalar(self, x): + return np.cosh(x) + + def fun_scalar_vector(self, x): + return np.array([x[0]**2, np.tan(x[0]), np.exp(x[0])]) + + def jac_scalar_vector(self, x): + return np.array( + [2 * x[0], np.cos(x[0]) ** -2, np.exp(x[0])]).reshape(-1, 1) + + def fun_vector_scalar(self, x): + return np.sin(x[0] * x[1]) * np.log(x[0]) + + def wrong_dimensions_fun(self, x): + return np.array([x**2, np.tan(x), np.exp(x)]) + + def jac_vector_scalar(self, x): + return np.array([ + x[1] * np.cos(x[0] * x[1]) * np.log(x[0]) + + np.sin(x[0] * x[1]) / x[0], + x[0] * np.cos(x[0] * x[1]) * np.log(x[0]) + ]) + + def fun_vector_vector(self, x): + return np.array([ + x[0] * np.sin(x[1]), + x[1] * np.cos(x[0]), + x[0] ** 3 * x[1] ** -0.5 + ]) + + def fun_vector_vector_with_arg(self, x, arg): + """Used to test passing custom arguments with check_derivative()""" + assert arg == 42 + return np.array([ + x[0] * np.sin(x[1]), + x[1] * np.cos(x[0]), + x[0] ** 3 * x[1] ** -0.5 + ]) + + def jac_vector_vector(self, x): + return np.array([ + [np.sin(x[1]), x[0] * np.cos(x[1])], + [-x[1] * np.sin(x[0]), np.cos(x[0])], + [3 * x[0] ** 2 * x[1] ** -0.5, -0.5 * x[0] ** 3 * x[1] ** -1.5] + ]) + + def jac_vector_vector_with_arg(self, x, arg): + """Used to test passing custom arguments with check_derivative()""" + assert arg == 42 + return np.array([ + [np.sin(x[1]), x[0] * np.cos(x[1])], + [-x[1] * np.sin(x[0]), np.cos(x[0])], + [3 * x[0] ** 2 * x[1] ** -0.5, -0.5 * x[0] ** 3 * x[1] ** -1.5] + ]) + + def fun_parametrized(self, x, c0, c1=1.0): + return np.array([np.exp(c0 * x[0]), np.exp(c1 * x[1])]) + + def jac_parametrized(self, x, c0, c1=0.1): + return np.array([ + [c0 * np.exp(c0 * x[0]), 0], + [0, c1 * np.exp(c1 * x[1])] + ]) + + def fun_with_nan(self, x): + return x if np.abs(x) <= 1e-8 else np.nan + + def jac_with_nan(self, x): + return 1.0 if np.abs(x) <= 1e-8 else np.nan + + def fun_zero_jacobian(self, x): + return np.array([x[0] * x[1], np.cos(x[0] * x[1])]) + + def jac_zero_jacobian(self, x): + return np.array([ + [x[1], x[0]], + [-x[1] * np.sin(x[0] * x[1]), -x[0] * np.sin(x[0] * x[1])] + ]) + + def jac_non_numpy(self, x): + # x can be a scalar or an array [val]. + # Cast to true scalar before handing over to math.exp + xp = np.asarray(x).item() + return math.exp(xp) + + def test_scalar_scalar(self): + x0 = 1.0 + jac_diff_2 = approx_derivative(self.fun_scalar_scalar, x0, + method='2-point') + jac_diff_3 = approx_derivative(self.fun_scalar_scalar, x0) + jac_diff_4 = approx_derivative(self.fun_scalar_scalar, x0, + method='cs') + jac_true = self.jac_scalar_scalar(x0) + assert_allclose(jac_diff_2, jac_true, rtol=1e-6) + assert_allclose(jac_diff_3, jac_true, rtol=1e-9) + assert_allclose(jac_diff_4, jac_true, rtol=1e-12) + + def test_scalar_scalar_abs_step(self): + # can approx_derivative use abs_step? + x0 = 1.0 + jac_diff_2 = approx_derivative(self.fun_scalar_scalar, x0, + method='2-point', abs_step=1.49e-8) + jac_diff_3 = approx_derivative(self.fun_scalar_scalar, x0, + abs_step=1.49e-8) + jac_diff_4 = approx_derivative(self.fun_scalar_scalar, x0, + method='cs', abs_step=1.49e-8) + jac_true = self.jac_scalar_scalar(x0) + assert_allclose(jac_diff_2, jac_true, rtol=1e-6) + assert_allclose(jac_diff_3, jac_true, rtol=1e-9) + assert_allclose(jac_diff_4, jac_true, rtol=1e-12) + + def test_scalar_vector(self): + x0 = 0.5 + jac_diff_2 = approx_derivative(self.fun_scalar_vector, x0, + method='2-point') + jac_diff_3 = approx_derivative(self.fun_scalar_vector, x0) + jac_diff_4 = approx_derivative(self.fun_scalar_vector, x0, + method='cs') + jac_true = self.jac_scalar_vector(np.atleast_1d(x0)) + assert_allclose(jac_diff_2, jac_true, rtol=1e-6) + assert_allclose(jac_diff_3, jac_true, rtol=1e-9) + assert_allclose(jac_diff_4, jac_true, rtol=1e-12) + + def test_vector_scalar(self): + x0 = np.array([100.0, -0.5]) + jac_diff_2 = approx_derivative(self.fun_vector_scalar, x0, + method='2-point') + jac_diff_3 = approx_derivative(self.fun_vector_scalar, x0) + jac_diff_4 = approx_derivative(self.fun_vector_scalar, x0, + method='cs') + jac_true = self.jac_vector_scalar(x0) + assert_allclose(jac_diff_2, jac_true, rtol=1e-6) + assert_allclose(jac_diff_3, jac_true, rtol=1e-7) + assert_allclose(jac_diff_4, jac_true, rtol=1e-12) + + def test_vector_scalar_abs_step(self): + # can approx_derivative use abs_step? + x0 = np.array([100.0, -0.5]) + jac_diff_2 = approx_derivative(self.fun_vector_scalar, x0, + method='2-point', abs_step=1.49e-8) + jac_diff_3 = approx_derivative(self.fun_vector_scalar, x0, + abs_step=1.49e-8, rel_step=np.inf) + jac_diff_4 = approx_derivative(self.fun_vector_scalar, x0, + method='cs', abs_step=1.49e-8) + jac_true = self.jac_vector_scalar(x0) + assert_allclose(jac_diff_2, jac_true, rtol=1e-6) + assert_allclose(jac_diff_3, jac_true, rtol=3e-9) + assert_allclose(jac_diff_4, jac_true, rtol=1e-12) + + def test_vector_vector(self): + x0 = np.array([-100.0, 0.2]) + jac_diff_2 = approx_derivative(self.fun_vector_vector, x0, + method='2-point') + jac_diff_3 = approx_derivative(self.fun_vector_vector, x0) + jac_diff_4 = approx_derivative(self.fun_vector_vector, x0, + method='cs') + jac_true = self.jac_vector_vector(x0) + assert_allclose(jac_diff_2, jac_true, rtol=1e-5) + assert_allclose(jac_diff_3, jac_true, rtol=1e-6) + assert_allclose(jac_diff_4, jac_true, rtol=1e-12) + + def test_wrong_dimensions(self): + x0 = 1.0 + assert_raises(RuntimeError, approx_derivative, + self.wrong_dimensions_fun, x0) + f0 = self.wrong_dimensions_fun(np.atleast_1d(x0)) + assert_raises(ValueError, approx_derivative, + self.wrong_dimensions_fun, x0, f0=f0) + + def test_custom_rel_step(self): + x0 = np.array([-0.1, 0.1]) + jac_diff_2 = approx_derivative(self.fun_vector_vector, x0, + method='2-point', rel_step=1e-4) + jac_diff_3 = approx_derivative(self.fun_vector_vector, x0, + rel_step=1e-4) + jac_true = self.jac_vector_vector(x0) + assert_allclose(jac_diff_2, jac_true, rtol=1e-2) + assert_allclose(jac_diff_3, jac_true, rtol=1e-4) + + def test_options(self): + x0 = np.array([1.0, 1.0]) + c0 = -1.0 + c1 = 1.0 + lb = 0.0 + ub = 2.0 + f0 = self.fun_parametrized(x0, c0, c1=c1) + rel_step = np.array([-1e-6, 1e-7]) + jac_true = self.jac_parametrized(x0, c0, c1) + jac_diff_2 = approx_derivative( + self.fun_parametrized, x0, method='2-point', rel_step=rel_step, + f0=f0, args=(c0,), kwargs=dict(c1=c1), bounds=(lb, ub)) + jac_diff_3 = approx_derivative( + self.fun_parametrized, x0, rel_step=rel_step, + f0=f0, args=(c0,), kwargs=dict(c1=c1), bounds=(lb, ub)) + assert_allclose(jac_diff_2, jac_true, rtol=1e-6) + assert_allclose(jac_diff_3, jac_true, rtol=1e-9) + + def test_with_bounds_2_point(self): + lb = -np.ones(2) + ub = np.ones(2) + + x0 = np.array([-2.0, 0.2]) + assert_raises(ValueError, approx_derivative, + self.fun_vector_vector, x0, bounds=(lb, ub)) + + x0 = np.array([-1.0, 1.0]) + jac_diff = approx_derivative(self.fun_vector_vector, x0, + method='2-point', bounds=(lb, ub)) + jac_true = self.jac_vector_vector(x0) + assert_allclose(jac_diff, jac_true, rtol=1e-6) + + def test_with_bounds_3_point(self): + lb = np.array([1.0, 1.0]) + ub = np.array([2.0, 2.0]) + + x0 = np.array([1.0, 2.0]) + jac_true = self.jac_vector_vector(x0) + + jac_diff = approx_derivative(self.fun_vector_vector, x0) + assert_allclose(jac_diff, jac_true, rtol=1e-9) + + jac_diff = approx_derivative(self.fun_vector_vector, x0, + bounds=(lb, np.inf)) + assert_allclose(jac_diff, jac_true, rtol=1e-9) + + jac_diff = approx_derivative(self.fun_vector_vector, x0, + bounds=(-np.inf, ub)) + assert_allclose(jac_diff, jac_true, rtol=1e-9) + + jac_diff = approx_derivative(self.fun_vector_vector, x0, + bounds=(lb, ub)) + assert_allclose(jac_diff, jac_true, rtol=1e-9) + + def test_tight_bounds(self): + x0 = np.array([10.0, 10.0]) + lb = x0 - 3e-9 + ub = x0 + 2e-9 + jac_true = self.jac_vector_vector(x0) + jac_diff = approx_derivative( + self.fun_vector_vector, x0, method='2-point', bounds=(lb, ub)) + assert_allclose(jac_diff, jac_true, rtol=1e-6) + jac_diff = approx_derivative( + self.fun_vector_vector, x0, method='2-point', + rel_step=1e-6, bounds=(lb, ub)) + assert_allclose(jac_diff, jac_true, rtol=1e-6) + + jac_diff = approx_derivative( + self.fun_vector_vector, x0, bounds=(lb, ub)) + assert_allclose(jac_diff, jac_true, rtol=1e-6) + jac_diff = approx_derivative( + self.fun_vector_vector, x0, rel_step=1e-6, bounds=(lb, ub)) + assert_allclose(jac_true, jac_diff, rtol=1e-6) + + def test_bound_switches(self): + lb = -1e-8 + ub = 1e-8 + x0 = 0.0 + jac_true = self.jac_with_nan(x0) + jac_diff_2 = approx_derivative( + self.fun_with_nan, x0, method='2-point', rel_step=1e-6, + bounds=(lb, ub)) + jac_diff_3 = approx_derivative( + self.fun_with_nan, x0, rel_step=1e-6, bounds=(lb, ub)) + assert_allclose(jac_diff_2, jac_true, rtol=1e-6) + assert_allclose(jac_diff_3, jac_true, rtol=1e-9) + + x0 = 1e-8 + jac_true = self.jac_with_nan(x0) + jac_diff_2 = approx_derivative( + self.fun_with_nan, x0, method='2-point', rel_step=1e-6, + bounds=(lb, ub)) + jac_diff_3 = approx_derivative( + self.fun_with_nan, x0, rel_step=1e-6, bounds=(lb, ub)) + assert_allclose(jac_diff_2, jac_true, rtol=1e-6) + assert_allclose(jac_diff_3, jac_true, rtol=1e-9) + + def test_non_numpy(self): + x0 = 1.0 + jac_true = self.jac_non_numpy(x0) + jac_diff_2 = approx_derivative(self.jac_non_numpy, x0, + method='2-point') + jac_diff_3 = approx_derivative(self.jac_non_numpy, x0) + assert_allclose(jac_diff_2, jac_true, rtol=1e-6) + assert_allclose(jac_diff_3, jac_true, rtol=1e-8) + + # math.exp cannot handle complex arguments, hence this raises + assert_raises(TypeError, approx_derivative, self.jac_non_numpy, x0, + **dict(method='cs')) + + def test_fp(self): + # checks that approx_derivative works for FP size other than 64. + # Example is derived from the minimal working example in gh12991. + np.random.seed(1) + + def func(p, x): + return p[0] + p[1] * x + + def err(p, x, y): + return func(p, x) - y + + x = np.linspace(0, 1, 100, dtype=np.float64) + y = np.random.random(100).astype(np.float64) + p0 = np.array([-1.0, -1.0]) + + jac_fp64 = approx_derivative(err, p0, method='2-point', args=(x, y)) + + # parameter vector is float32, func output is float64 + jac_fp = approx_derivative(err, p0.astype(np.float32), + method='2-point', args=(x, y)) + assert err(p0, x, y).dtype == np.float64 + assert_allclose(jac_fp, jac_fp64, atol=1e-3) + + # parameter vector is float64, func output is float32 + def err_fp32(p): + assert p.dtype == np.float32 + return err(p, x, y).astype(np.float32) + + jac_fp = approx_derivative(err_fp32, p0.astype(np.float32), + method='2-point') + assert_allclose(jac_fp, jac_fp64, atol=1e-3) + + # check upper bound of error on the derivative for 2-point + def f(x): + return np.sin(x) + def g(x): + return np.cos(x) + def hess(x): + return -np.sin(x) + + def calc_atol(h, x0, f, hess, EPS): + # truncation error + t0 = h / 2 * max(np.abs(hess(x0)), np.abs(hess(x0 + h))) + # roundoff error. There may be a divisor (>1) missing from + # the following line, so this contribution is possibly + # overestimated + t1 = EPS / h * max(np.abs(f(x0)), np.abs(f(x0 + h))) + return t0 + t1 + + for dtype in [np.float16, np.float32, np.float64]: + EPS = np.finfo(dtype).eps + x0 = np.array(1.0).astype(dtype) + h = _compute_absolute_step(None, x0, f(x0), '2-point') + atol = calc_atol(h, x0, f, hess, EPS) + err = approx_derivative(f, x0, method='2-point', + abs_step=h) - g(x0) + assert abs(err) < atol + + def test_check_derivative(self): + x0 = np.array([-10.0, 10]) + accuracy = check_derivative(self.fun_vector_vector, + self.jac_vector_vector, x0) + assert_(accuracy < 1e-9) + accuracy = check_derivative(self.fun_vector_vector, + self.jac_vector_vector, x0) + assert_(accuracy < 1e-6) + + x0 = np.array([0.0, 0.0]) + accuracy = check_derivative(self.fun_zero_jacobian, + self.jac_zero_jacobian, x0) + assert_(accuracy == 0) + accuracy = check_derivative(self.fun_zero_jacobian, + self.jac_zero_jacobian, x0) + assert_(accuracy == 0) + + def test_check_derivative_with_kwargs(self): + x0 = np.array([-10.0, 10]) + accuracy = check_derivative(self.fun_vector_vector_with_arg, + self.jac_vector_vector_with_arg, + x0, + kwargs={'arg': 42}) + assert_(accuracy < 1e-9) + + +class TestApproxDerivativeSparse: + # Example from Numerical Optimization 2nd edition, p. 198. + def setup_method(self): + np.random.seed(0) + self.n = 50 + self.lb = -0.1 * (1 + np.arange(self.n)) + self.ub = 0.1 * (1 + np.arange(self.n)) + self.x0 = np.empty(self.n) + self.x0[::2] = (1 - 1e-7) * self.lb[::2] + self.x0[1::2] = (1 - 1e-7) * self.ub[1::2] + + self.J_true = self.jac(self.x0) + + def fun(self, x): + e = x[1:]**3 - x[:-1]**2 + return np.hstack((0, 3 * e)) + np.hstack((2 * e, 0)) + + def jac(self, x): + n = x.size + J = np.zeros((n, n)) + J[0, 0] = -4 * x[0] + J[0, 1] = 6 * x[1]**2 + for i in range(1, n - 1): + J[i, i - 1] = -6 * x[i-1] + J[i, i] = 9 * x[i]**2 - 4 * x[i] + J[i, i + 1] = 6 * x[i+1]**2 + J[-1, -1] = 9 * x[-1]**2 + J[-1, -2] = -6 * x[-2] + + return J + + def structure(self, n): + A = np.zeros((n, n), dtype=int) + A[0, 0] = 1 + A[0, 1] = 1 + for i in range(1, n - 1): + A[i, i - 1: i + 2] = 1 + A[-1, -1] = 1 + A[-1, -2] = 1 + + return A + + def test_all(self): + A = self.structure(self.n) + order = np.arange(self.n) + groups_1 = group_columns(A, order) + np.random.shuffle(order) + groups_2 = group_columns(A, order) + + for method, groups, l, u in product( + ['2-point', '3-point', 'cs'], [groups_1, groups_2], + [-np.inf, self.lb], [np.inf, self.ub]): + J = approx_derivative(self.fun, self.x0, method=method, + bounds=(l, u), sparsity=(A, groups)) + assert_(isinstance(J, csr_matrix)) + assert_allclose(J.toarray(), self.J_true, rtol=1e-6) + + rel_step = np.full_like(self.x0, 1e-8) + rel_step[::2] *= -1 + J = approx_derivative(self.fun, self.x0, method=method, + rel_step=rel_step, sparsity=(A, groups)) + assert_allclose(J.toarray(), self.J_true, rtol=1e-5) + + def test_no_precomputed_groups(self): + A = self.structure(self.n) + J = approx_derivative(self.fun, self.x0, sparsity=A) + assert_allclose(J.toarray(), self.J_true, rtol=1e-6) + + def test_equivalence(self): + structure = np.ones((self.n, self.n), dtype=int) + groups = np.arange(self.n) + for method in ['2-point', '3-point', 'cs']: + J_dense = approx_derivative(self.fun, self.x0, method=method) + J_sparse = approx_derivative( + self.fun, self.x0, sparsity=(structure, groups), method=method) + assert_allclose(J_dense, J_sparse.toarray(), + rtol=5e-16, atol=7e-15) + + def test_check_derivative(self): + def jac(x): + return csr_matrix(self.jac(x)) + + accuracy = check_derivative(self.fun, jac, self.x0, + bounds=(self.lb, self.ub)) + assert_(accuracy < 1e-9) + + accuracy = check_derivative(self.fun, jac, self.x0, + bounds=(self.lb, self.ub)) + assert_(accuracy < 1e-9) + + +class TestApproxDerivativeLinearOperator: + + def fun_scalar_scalar(self, x): + return np.sinh(x) + + def jac_scalar_scalar(self, x): + return np.cosh(x) + + def fun_scalar_vector(self, x): + return np.array([x[0]**2, np.tan(x[0]), np.exp(x[0])]) + + def jac_scalar_vector(self, x): + return np.array( + [2 * x[0], np.cos(x[0]) ** -2, np.exp(x[0])]).reshape(-1, 1) + + def fun_vector_scalar(self, x): + return np.sin(x[0] * x[1]) * np.log(x[0]) + + def jac_vector_scalar(self, x): + return np.array([ + x[1] * np.cos(x[0] * x[1]) * np.log(x[0]) + + np.sin(x[0] * x[1]) / x[0], + x[0] * np.cos(x[0] * x[1]) * np.log(x[0]) + ]) + + def fun_vector_vector(self, x): + return np.array([ + x[0] * np.sin(x[1]), + x[1] * np.cos(x[0]), + x[0] ** 3 * x[1] ** -0.5 + ]) + + def jac_vector_vector(self, x): + return np.array([ + [np.sin(x[1]), x[0] * np.cos(x[1])], + [-x[1] * np.sin(x[0]), np.cos(x[0])], + [3 * x[0] ** 2 * x[1] ** -0.5, -0.5 * x[0] ** 3 * x[1] ** -1.5] + ]) + + def test_scalar_scalar(self): + x0 = 1.0 + jac_diff_2 = approx_derivative(self.fun_scalar_scalar, x0, + method='2-point', + as_linear_operator=True) + jac_diff_3 = approx_derivative(self.fun_scalar_scalar, x0, + as_linear_operator=True) + jac_diff_4 = approx_derivative(self.fun_scalar_scalar, x0, + method='cs', + as_linear_operator=True) + jac_true = self.jac_scalar_scalar(x0) + np.random.seed(1) + for i in range(10): + p = np.random.uniform(-10, 10, size=(1,)) + assert_allclose(jac_diff_2.dot(p), jac_true*p, + rtol=1e-5) + assert_allclose(jac_diff_3.dot(p), jac_true*p, + rtol=5e-6) + assert_allclose(jac_diff_4.dot(p), jac_true*p, + rtol=5e-6) + + def test_scalar_vector(self): + x0 = 0.5 + jac_diff_2 = approx_derivative(self.fun_scalar_vector, x0, + method='2-point', + as_linear_operator=True) + jac_diff_3 = approx_derivative(self.fun_scalar_vector, x0, + as_linear_operator=True) + jac_diff_4 = approx_derivative(self.fun_scalar_vector, x0, + method='cs', + as_linear_operator=True) + jac_true = self.jac_scalar_vector(np.atleast_1d(x0)) + np.random.seed(1) + for i in range(10): + p = np.random.uniform(-10, 10, size=(1,)) + assert_allclose(jac_diff_2.dot(p), jac_true.dot(p), + rtol=1e-5) + assert_allclose(jac_diff_3.dot(p), jac_true.dot(p), + rtol=5e-6) + assert_allclose(jac_diff_4.dot(p), jac_true.dot(p), + rtol=5e-6) + + def test_vector_scalar(self): + x0 = np.array([100.0, -0.5]) + jac_diff_2 = approx_derivative(self.fun_vector_scalar, x0, + method='2-point', + as_linear_operator=True) + jac_diff_3 = approx_derivative(self.fun_vector_scalar, x0, + as_linear_operator=True) + jac_diff_4 = approx_derivative(self.fun_vector_scalar, x0, + method='cs', + as_linear_operator=True) + jac_true = self.jac_vector_scalar(x0) + np.random.seed(1) + for i in range(10): + p = np.random.uniform(-10, 10, size=x0.shape) + assert_allclose(jac_diff_2.dot(p), np.atleast_1d(jac_true.dot(p)), + rtol=1e-5) + assert_allclose(jac_diff_3.dot(p), np.atleast_1d(jac_true.dot(p)), + rtol=5e-6) + assert_allclose(jac_diff_4.dot(p), np.atleast_1d(jac_true.dot(p)), + rtol=1e-7) + + def test_vector_vector(self): + x0 = np.array([-100.0, 0.2]) + jac_diff_2 = approx_derivative(self.fun_vector_vector, x0, + method='2-point', + as_linear_operator=True) + jac_diff_3 = approx_derivative(self.fun_vector_vector, x0, + as_linear_operator=True) + jac_diff_4 = approx_derivative(self.fun_vector_vector, x0, + method='cs', + as_linear_operator=True) + jac_true = self.jac_vector_vector(x0) + np.random.seed(1) + for i in range(10): + p = np.random.uniform(-10, 10, size=x0.shape) + assert_allclose(jac_diff_2.dot(p), jac_true.dot(p), rtol=1e-5) + assert_allclose(jac_diff_3.dot(p), jac_true.dot(p), rtol=1e-6) + assert_allclose(jac_diff_4.dot(p), jac_true.dot(p), rtol=1e-7) + + def test_exception(self): + x0 = np.array([-100.0, 0.2]) + assert_raises(ValueError, approx_derivative, + self.fun_vector_vector, x0, + method='2-point', bounds=(1, np.inf)) + + +def test_absolute_step_sign(): + # test for gh12487 + # if an absolute step is specified for 2-point differences make sure that + # the side corresponds to the step. i.e. if step is positive then forward + # differences should be used, if step is negative then backwards + # differences should be used. + + # function has double discontinuity at x = [-1, -1] + # first component is \/, second component is /\ + def f(x): + return -np.abs(x[0] + 1) + np.abs(x[1] + 1) + + # check that the forward difference is used + grad = approx_derivative(f, [-1, -1], method='2-point', abs_step=1e-8) + assert_allclose(grad, [-1.0, 1.0]) + + # check that the backwards difference is used + grad = approx_derivative(f, [-1, -1], method='2-point', abs_step=-1e-8) + assert_allclose(grad, [1.0, -1.0]) + + # check that the forwards difference is used with a step for both + # parameters + grad = approx_derivative( + f, [-1, -1], method='2-point', abs_step=[1e-8, 1e-8] + ) + assert_allclose(grad, [-1.0, 1.0]) + + # check that we can mix forward/backwards steps. + grad = approx_derivative( + f, [-1, -1], method='2-point', abs_step=[1e-8, -1e-8] + ) + assert_allclose(grad, [-1.0, -1.0]) + grad = approx_derivative( + f, [-1, -1], method='2-point', abs_step=[-1e-8, 1e-8] + ) + assert_allclose(grad, [1.0, 1.0]) + + # the forward step should reverse to a backwards step if it runs into a + # bound + # This is kind of tested in TestAdjustSchemeToBounds, but only for a lower level + # function. + grad = approx_derivative( + f, [-1, -1], method='2-point', abs_step=1e-8, + bounds=(-np.inf, -1) + ) + assert_allclose(grad, [1.0, -1.0]) + + grad = approx_derivative( + f, [-1, -1], method='2-point', abs_step=-1e-8, bounds=(-1, np.inf) + ) + assert_allclose(grad, [-1.0, 1.0]) + + +def test__compute_absolute_step(): + # tests calculation of absolute step from rel_step + methods = ['2-point', '3-point', 'cs'] + + x0 = np.array([1e-5, 0, 1, 1e5]) + + EPS = np.finfo(np.float64).eps + relative_step = { + "2-point": EPS**0.5, + "3-point": EPS**(1/3), + "cs": EPS**0.5 + } + f0 = np.array(1.0) + + for method in methods: + rel_step = relative_step[method] + correct_step = np.array([rel_step, + rel_step * 1., + rel_step * 1., + rel_step * np.abs(x0[3])]) + + abs_step = _compute_absolute_step(None, x0, f0, method) + assert_allclose(abs_step, correct_step) + + sign_x0 = (-x0 >= 0).astype(float) * 2 - 1 + abs_step = _compute_absolute_step(None, -x0, f0, method) + assert_allclose(abs_step, sign_x0 * correct_step) + + # if a relative step is provided it should be used + rel_step = np.array([0.1, 1, 10, 100]) + correct_step = np.array([rel_step[0] * x0[0], + relative_step['2-point'], + rel_step[2] * 1., + rel_step[3] * np.abs(x0[3])]) + + abs_step = _compute_absolute_step(rel_step, x0, f0, '2-point') + assert_allclose(abs_step, correct_step) + + sign_x0 = (-x0 >= 0).astype(float) * 2 - 1 + abs_step = _compute_absolute_step(rel_step, -x0, f0, '2-point') + assert_allclose(abs_step, sign_x0 * correct_step) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test__remove_redundancy.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test__remove_redundancy.py new file mode 100644 index 0000000000000000000000000000000000000000..817282011699dea333042a4173f65c999a2925fc --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test__remove_redundancy.py @@ -0,0 +1,228 @@ +""" +Unit test for Linear Programming via Simplex Algorithm. +""" + +# TODO: add tests for: +# https://github.com/scipy/scipy/issues/5400 +# https://github.com/scipy/scipy/issues/6690 + +import numpy as np +from numpy.testing import ( + assert_, + assert_allclose, + assert_equal) + +from .test_linprog import magic_square +from scipy.optimize._remove_redundancy import _remove_redundancy_svd +from scipy.optimize._remove_redundancy import _remove_redundancy_pivot_dense +from scipy.optimize._remove_redundancy import _remove_redundancy_pivot_sparse +from scipy.optimize._remove_redundancy import _remove_redundancy_id + +from scipy.sparse import csc_matrix + + +def setup_module(): + np.random.seed(2017) + + +def redundancy_removed(A, B): + """Checks whether a matrix contains only independent rows of another""" + for rowA in A: + # `rowA in B` is not a reliable check + for rowB in B: + if np.all(rowA == rowB): + break + else: + return False + return A.shape[0] == np.linalg.matrix_rank(A) == np.linalg.matrix_rank(B) + + +class RRCommonTests: + def test_no_redundancy(self): + m, n = 10, 10 + A0 = np.random.rand(m, n) + b0 = np.random.rand(m) + A1, b1, status, message = self.rr(A0, b0) + assert_allclose(A0, A1) + assert_allclose(b0, b1) + assert_equal(status, 0) + + def test_infeasible_zero_row(self): + A = np.eye(3) + A[1, :] = 0 + b = np.random.rand(3) + A1, b1, status, message = self.rr(A, b) + assert_equal(status, 2) + + def test_remove_zero_row(self): + A = np.eye(3) + A[1, :] = 0 + b = np.random.rand(3) + b[1] = 0 + A1, b1, status, message = self.rr(A, b) + assert_equal(status, 0) + assert_allclose(A1, A[[0, 2], :]) + assert_allclose(b1, b[[0, 2]]) + + def test_infeasible_m_gt_n(self): + m, n = 20, 10 + A0 = np.random.rand(m, n) + b0 = np.random.rand(m) + A1, b1, status, message = self.rr(A0, b0) + assert_equal(status, 2) + + def test_infeasible_m_eq_n(self): + m, n = 10, 10 + A0 = np.random.rand(m, n) + b0 = np.random.rand(m) + A0[-1, :] = 2 * A0[-2, :] + A1, b1, status, message = self.rr(A0, b0) + assert_equal(status, 2) + + def test_infeasible_m_lt_n(self): + m, n = 9, 10 + A0 = np.random.rand(m, n) + b0 = np.random.rand(m) + A0[-1, :] = np.arange(m - 1).dot(A0[:-1]) + A1, b1, status, message = self.rr(A0, b0) + assert_equal(status, 2) + + def test_m_gt_n(self): + np.random.seed(2032) + m, n = 20, 10 + A0 = np.random.rand(m, n) + b0 = np.random.rand(m) + x = np.linalg.solve(A0[:n, :], b0[:n]) + b0[n:] = A0[n:, :].dot(x) + A1, b1, status, message = self.rr(A0, b0) + assert_equal(status, 0) + assert_equal(A1.shape[0], n) + assert_equal(np.linalg.matrix_rank(A1), n) + + def test_m_gt_n_rank_deficient(self): + m, n = 20, 10 + A0 = np.zeros((m, n)) + A0[:, 0] = 1 + b0 = np.ones(m) + A1, b1, status, message = self.rr(A0, b0) + assert_equal(status, 0) + assert_allclose(A1, A0[0:1, :]) + assert_allclose(b1, b0[0]) + + def test_m_lt_n_rank_deficient(self): + m, n = 9, 10 + A0 = np.random.rand(m, n) + b0 = np.random.rand(m) + A0[-1, :] = np.arange(m - 1).dot(A0[:-1]) + b0[-1] = np.arange(m - 1).dot(b0[:-1]) + A1, b1, status, message = self.rr(A0, b0) + assert_equal(status, 0) + assert_equal(A1.shape[0], 8) + assert_equal(np.linalg.matrix_rank(A1), 8) + + def test_dense1(self): + A = np.ones((6, 6)) + A[0, :3] = 0 + A[1, 3:] = 0 + A[3:, ::2] = -1 + A[3, :2] = 0 + A[4, 2:] = 0 + b = np.zeros(A.shape[0]) + + A1, b1, status, message = self.rr(A, b) + assert_(redundancy_removed(A1, A)) + assert_equal(status, 0) + + def test_dense2(self): + A = np.eye(6) + A[-2, -1] = 1 + A[-1, :] = 1 + b = np.zeros(A.shape[0]) + A1, b1, status, message = self.rr(A, b) + assert_(redundancy_removed(A1, A)) + assert_equal(status, 0) + + def test_dense3(self): + A = np.eye(6) + A[-2, -1] = 1 + A[-1, :] = 1 + b = np.random.rand(A.shape[0]) + b[-1] = np.sum(b[:-1]) + A1, b1, status, message = self.rr(A, b) + assert_(redundancy_removed(A1, A)) + assert_equal(status, 0) + + def test_m_gt_n_sparse(self): + np.random.seed(2013) + m, n = 20, 5 + p = 0.1 + A = np.random.rand(m, n) + A[np.random.rand(m, n) > p] = 0 + rank = np.linalg.matrix_rank(A) + b = np.zeros(A.shape[0]) + A1, b1, status, message = self.rr(A, b) + assert_equal(status, 0) + assert_equal(A1.shape[0], rank) + assert_equal(np.linalg.matrix_rank(A1), rank) + + def test_m_lt_n_sparse(self): + np.random.seed(2017) + m, n = 20, 50 + p = 0.05 + A = np.random.rand(m, n) + A[np.random.rand(m, n) > p] = 0 + rank = np.linalg.matrix_rank(A) + b = np.zeros(A.shape[0]) + A1, b1, status, message = self.rr(A, b) + assert_equal(status, 0) + assert_equal(A1.shape[0], rank) + assert_equal(np.linalg.matrix_rank(A1), rank) + + def test_m_eq_n_sparse(self): + np.random.seed(2017) + m, n = 100, 100 + p = 0.01 + A = np.random.rand(m, n) + A[np.random.rand(m, n) > p] = 0 + rank = np.linalg.matrix_rank(A) + b = np.zeros(A.shape[0]) + A1, b1, status, message = self.rr(A, b) + assert_equal(status, 0) + assert_equal(A1.shape[0], rank) + assert_equal(np.linalg.matrix_rank(A1), rank) + + def test_magic_square(self): + A, b, c, numbers, _ = magic_square(3) + A1, b1, status, message = self.rr(A, b) + assert_equal(status, 0) + assert_equal(A1.shape[0], 23) + assert_equal(np.linalg.matrix_rank(A1), 23) + + def test_magic_square2(self): + A, b, c, numbers, _ = magic_square(4) + A1, b1, status, message = self.rr(A, b) + assert_equal(status, 0) + assert_equal(A1.shape[0], 39) + assert_equal(np.linalg.matrix_rank(A1), 39) + + +class TestRRSVD(RRCommonTests): + def rr(self, A, b): + return _remove_redundancy_svd(A, b) + + +class TestRRPivotDense(RRCommonTests): + def rr(self, A, b): + return _remove_redundancy_pivot_dense(A, b) + + +class TestRRID(RRCommonTests): + def rr(self, A, b): + return _remove_redundancy_id(A, b) + + +class TestRRPivotSparse(RRCommonTests): + def rr(self, A, b): + rr_res = _remove_redundancy_pivot_sparse(csc_matrix(A), b) + A1, b1, status, message = rr_res + return A1.toarray(), b1, status, message diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test__root.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test__root.py new file mode 100644 index 0000000000000000000000000000000000000000..1e2f45a10d3d976d02be18084d241adea8612b05 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test__root.py @@ -0,0 +1,124 @@ +""" +Unit tests for optimization routines from _root.py. +""" +from numpy.testing import assert_, assert_equal +import pytest +from pytest import raises as assert_raises, warns as assert_warns +import numpy as np + +from scipy.optimize import root + + +class TestRoot: + def test_tol_parameter(self): + # Check that the minimize() tol= argument does something + def func(z): + x, y = z + return np.array([x**3 - 1, y**3 - 1]) + + def dfunc(z): + x, y = z + return np.array([[3*x**2, 0], [0, 3*y**2]]) + + for method in ['hybr', 'lm', 'broyden1', 'broyden2', 'anderson', + 'diagbroyden', 'krylov']: + if method in ('linearmixing', 'excitingmixing'): + # doesn't converge + continue + + if method in ('hybr', 'lm'): + jac = dfunc + else: + jac = None + + sol1 = root(func, [1.1,1.1], jac=jac, tol=1e-4, method=method) + sol2 = root(func, [1.1,1.1], jac=jac, tol=0.5, method=method) + msg = f"{method}: {func(sol1.x)} vs. {func(sol2.x)}" + assert_(sol1.success, msg) + assert_(sol2.success, msg) + assert_(abs(func(sol1.x)).max() < abs(func(sol2.x)).max(), + msg) + + def test_tol_norm(self): + + def norm(x): + return abs(x[0]) + + for method in ['excitingmixing', + 'diagbroyden', + 'linearmixing', + 'anderson', + 'broyden1', + 'broyden2', + 'krylov']: + + root(np.zeros_like, np.zeros(2), method=method, + options={"tol_norm": norm}) + + def test_minimize_scalar_coerce_args_param(self): + # GitHub issue #3503 + def func(z, f=1): + x, y = z + return np.array([x**3 - 1, y**3 - f]) + root(func, [1.1, 1.1], args=1.5) + + def test_f_size(self): + # gh8320 + # check that decreasing the size of the returned array raises an error + # and doesn't segfault + class fun: + def __init__(self): + self.count = 0 + + def __call__(self, x): + self.count += 1 + + if not (self.count % 5): + ret = x[0] + 0.5 * (x[0] - x[1]) ** 3 - 1.0 + else: + ret = ([x[0] + 0.5 * (x[0] - x[1]) ** 3 - 1.0, + 0.5 * (x[1] - x[0]) ** 3 + x[1]]) + + return ret + + F = fun() + with assert_raises(ValueError): + root(F, [0.1, 0.0], method='lm') + + @pytest.mark.thread_unsafe + def test_gh_10370(self): + # gh-10370 reported that passing both `args` and `jac` to `root` with + # `method='krylov'` caused a failure. Ensure that this is fixed whether + # the gradient is passed via `jac` or as a second output of `fun`. + def fun(x, ignored): + return [3*x[0] - 0.25*x[1]**2 + 10, 0.1*x[0]**2 + 5*x[1] - 2] + + def grad(x, ignored): + return [[3, 0.5 * x[1]], [0.2 * x[0], 5]] + + def fun_grad(x, ignored): + return fun(x, ignored), grad(x, ignored) + + x0 = np.zeros(2) + + ref = root(fun, x0, args=(1,), method='krylov') + message = 'Method krylov does not use the jacobian' + with assert_warns(RuntimeWarning, match=message): + res1 = root(fun, x0, args=(1,), method='krylov', jac=grad) + with assert_warns(RuntimeWarning, match=message): + res2 = root(fun_grad, x0, args=(1,), method='krylov', jac=True) + + assert_equal(res1.x, ref.x) + assert_equal(res2.x, ref.x) + assert res1.success is res2.success is ref.success is True + + @pytest.mark.parametrize("method", ["hybr", "lm", "broyden1", "broyden2", + "anderson", "linearmixing", + "diagbroyden", "excitingmixing", + "krylov", "df-sane"]) + def test_method_in_result(self, method): + def func(x): + return x - 1 + + res = root(func, x0=[1], method=method) + assert res.method == method diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test__shgo.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test__shgo.py new file mode 100644 index 0000000000000000000000000000000000000000..82efb74beee92eacc75f64c6c705374fa5ada322 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test__shgo.py @@ -0,0 +1,1156 @@ +import logging +import sys + +import numpy as np +import time +from multiprocessing import Pool +from numpy.testing import assert_allclose, IS_PYPY +import pytest +from pytest import raises as assert_raises, warns +from scipy.optimize import (shgo, Bounds, minimize_scalar, minimize, rosen, + rosen_der, rosen_hess, NonlinearConstraint) +from scipy.optimize._constraints import new_constraint_to_old +from scipy.optimize._shgo import SHGO + + +class StructTestFunction: + def __init__(self, bounds, expected_x, expected_fun=None, + expected_xl=None, expected_funl=None): + self.bounds = bounds + self.expected_x = expected_x + self.expected_fun = expected_fun + self.expected_xl = expected_xl + self.expected_funl = expected_funl + + +def wrap_constraints(g): + cons = [] + if g is not None: + if not isinstance(g, (tuple, list)): + g = (g,) + else: + pass + for g in g: + cons.append({'type': 'ineq', + 'fun': g}) + cons = tuple(cons) + else: + cons = None + return cons + + +class StructTest1(StructTestFunction): + def f(self, x): + return x[0] ** 2 + x[1] ** 2 + + def g(x): + return -(np.sum(x, axis=0) - 6.0) + + cons = wrap_constraints(g) + + +test1_1 = StructTest1(bounds=[(-1, 6), (-1, 6)], + expected_x=[0, 0]) +test1_2 = StructTest1(bounds=[(0, 1), (0, 1)], + expected_x=[0, 0]) +test1_3 = StructTest1(bounds=[(None, None), (None, None)], + expected_x=[0, 0]) + + +class StructTest2(StructTestFunction): + """ + Scalar function with several minima to test all minimiser retrievals + """ + + def f(self, x): + return (x - 30) * np.sin(x) + + def g(x): + return 58 - np.sum(x, axis=0) + + cons = wrap_constraints(g) + + +test2_1 = StructTest2(bounds=[(0, 60)], + expected_x=[1.53567906], + expected_fun=-28.44677132, + # Important: test that funl return is in the correct + # order + expected_xl=np.array([[1.53567906], + [55.01782167], + [7.80894889], + [48.74797493], + [14.07445705], + [42.4913859], + [20.31743841], + [36.28607535], + [26.43039605], + [30.76371366]]), + + expected_funl=np.array([-28.44677132, -24.99785984, + -22.16855376, -18.72136195, + -15.89423937, -12.45154942, + -9.63133158, -6.20801301, + -3.43727232, -0.46353338]) + ) + +test2_2 = StructTest2(bounds=[(0, 4.5)], + expected_x=[1.53567906], + expected_fun=[-28.44677132], + expected_xl=np.array([[1.53567906]]), + expected_funl=np.array([-28.44677132]) + ) + + +class StructTest3(StructTestFunction): + """ + Hock and Schittkowski 18 problem (HS18). Hoch and Schittkowski (1981) + http://www.ai7.uni-bayreuth.de/test_problem_coll.pdf + Minimize: f = 0.01 * (x_1)**2 + (x_2)**2 + + Subject to: x_1 * x_2 - 25.0 >= 0, + (x_1)**2 + (x_2)**2 - 25.0 >= 0, + 2 <= x_1 <= 50, + 0 <= x_2 <= 50. + + Approx. Answer: + f([(250)**0.5 , (2.5)**0.5]) = 5.0 + + + """ + + # amended to test vectorisation of constraints + def f(self, x): + return 0.01 * (x[0]) ** 2 + (x[1]) ** 2 + + def g1(x): + return x[0] * x[1] - 25.0 + + def g2(x): + return x[0] ** 2 + x[1] ** 2 - 25.0 + + # g = (g1, g2) + # cons = wrap_constraints(g) + + def g(x): + return x[0] * x[1] - 25.0, x[0] ** 2 + x[1] ** 2 - 25.0 + + # this checks that shgo can be sent new-style constraints + __nlc = NonlinearConstraint(g, 0, np.inf) + cons = (__nlc,) + +test3_1 = StructTest3(bounds=[(2, 50), (0, 50)], + expected_x=[250 ** 0.5, 2.5 ** 0.5], + expected_fun=5.0 + ) + + +class StructTest4(StructTestFunction): + """ + Hock and Schittkowski 11 problem (HS11). Hoch and Schittkowski (1981) + + NOTE: Did not find in original reference to HS collection, refer to + Henderson (2015) problem 7 instead. 02.03.2016 + """ + + def f(self, x): + return ((x[0] - 10) ** 2 + 5 * (x[1] - 12) ** 2 + x[2] ** 4 + + 3 * (x[3] - 11) ** 2 + 10 * x[4] ** 6 + 7 * x[5] ** 2 + x[ + 6] ** 4 + - 4 * x[5] * x[6] - 10 * x[5] - 8 * x[6] + ) + + def g1(x): + return -(2 * x[0] ** 2 + 3 * x[1] ** 4 + x[2] + 4 * x[3] ** 2 + + 5 * x[4] - 127) + + def g2(x): + return -(7 * x[0] + 3 * x[1] + 10 * x[2] ** 2 + x[3] - x[4] - 282.0) + + def g3(x): + return -(23 * x[0] + x[1] ** 2 + 6 * x[5] ** 2 - 8 * x[6] - 196) + + def g4(x): + return -(4 * x[0] ** 2 + x[1] ** 2 - 3 * x[0] * x[1] + 2 * x[2] ** 2 + + 5 * x[5] - 11 * x[6]) + + g = (g1, g2, g3, g4) + + cons = wrap_constraints(g) + + +test4_1 = StructTest4(bounds=[(-10, 10), ] * 7, + expected_x=[2.330499, 1.951372, -0.4775414, + 4.365726, -0.6244870, 1.038131, 1.594227], + expected_fun=680.6300573 + ) + + +class StructTest5(StructTestFunction): + def f(self, x): + return ( + -(x[1] + 47.0)*np.sin(np.sqrt(abs(x[0]/2.0 + (x[1] + 47.0)))) + - x[0]*np.sin(np.sqrt(abs(x[0] - (x[1] + 47.0)))) + ) + + g = None + cons = wrap_constraints(g) + + +test5_1 = StructTest5(bounds=[(-512, 512), (-512, 512)], + expected_fun=[-959.64066272085051], + expected_x=[512., 404.23180542]) + + +class StructTestLJ(StructTestFunction): + """ + LennardJones objective function. Used to test symmetry constraints + settings. + """ + + def f(self, x, *args): + print(f'x = {x}') + self.N = args[0] + k = int(self.N / 3) + s = 0.0 + + for i in range(k - 1): + for j in range(i + 1, k): + a = 3 * i + b = 3 * j + xd = x[a] - x[b] + yd = x[a + 1] - x[b + 1] + zd = x[a + 2] - x[b + 2] + ed = xd * xd + yd * yd + zd * zd + ud = ed * ed * ed + if ed > 0.0: + s += (1.0 / ud - 2.0) / ud + + return s + + g = None + cons = wrap_constraints(g) + + +N = 6 +boundsLJ = list(zip([-4.0] * 6, [4.0] * 6)) + +testLJ = StructTestLJ(bounds=boundsLJ, + expected_fun=[-1.0], + expected_x=None, + # expected_x=[-2.71247337e-08, + # -2.71247337e-08, + # -2.50000222e+00, + # -2.71247337e-08, + # -2.71247337e-08, + # -1.50000222e+00] + ) + + +class StructTestS(StructTestFunction): + def f(self, x): + return ((x[0] - 0.5) ** 2 + (x[1] - 0.5) ** 2 + + (x[2] - 0.5) ** 2 + (x[3] - 0.5) ** 2) + + g = None + cons = wrap_constraints(g) + + +test_s = StructTestS(bounds=[(0, 2.0), ] * 4, + expected_fun=0.0, + expected_x=np.ones(4) - 0.5 + ) + + +class StructTestTable(StructTestFunction): + def f(self, x): + if x[0] == 3.0 and x[1] == 3.0: + return 50 + else: + return 100 + + g = None + cons = wrap_constraints(g) + + +test_table = StructTestTable(bounds=[(-10, 10), (-10, 10)], + expected_fun=[50], + expected_x=[3.0, 3.0]) + + +class StructTestInfeasible(StructTestFunction): + """ + Test function with no feasible domain. + """ + + def f(self, x, *args): + return x[0] ** 2 + x[1] ** 2 + + def g1(x): + return x[0] + x[1] - 1 + + def g2(x): + return -(x[0] + x[1] - 1) + + def g3(x): + return -x[0] + x[1] - 1 + + def g4(x): + return -(-x[0] + x[1] - 1) + + g = (g1, g2, g3, g4) + cons = wrap_constraints(g) + + +test_infeasible = StructTestInfeasible(bounds=[(2, 50), (-1, 1)], + expected_fun=None, + expected_x=None + ) + + +@pytest.mark.skip("Not a test") +def run_test(test, args=(), test_atol=1e-5, n=100, iters=None, + callback=None, minimizer_kwargs=None, options=None, + sampling_method='sobol', workers=1): + res = shgo(test.f, test.bounds, args=args, constraints=test.cons, + n=n, iters=iters, callback=callback, + minimizer_kwargs=minimizer_kwargs, options=options, + sampling_method=sampling_method, workers=workers) + + print(f'res = {res}') + logging.info(f'res = {res}') + if test.expected_x is not None: + np.testing.assert_allclose(res.x, test.expected_x, + rtol=test_atol, + atol=test_atol) + + # (Optional tests) + if test.expected_fun is not None: + np.testing.assert_allclose(res.fun, + test.expected_fun, + atol=test_atol) + + if test.expected_xl is not None: + np.testing.assert_allclose(res.xl, + test.expected_xl, + atol=test_atol) + + if test.expected_funl is not None: + np.testing.assert_allclose(res.funl, + test.expected_funl, + atol=test_atol) + return + + +# Base test functions: +class TestShgoSobolTestFunctions: + """ + Global optimisation tests with Sobol sampling: + """ + + # Sobol algorithm + def test_f1_1_sobol(self): + """Multivariate test function 1: + x[0]**2 + x[1]**2 with bounds=[(-1, 6), (-1, 6)]""" + run_test(test1_1) + + def test_f1_2_sobol(self): + """Multivariate test function 1: + x[0]**2 + x[1]**2 with bounds=[(0, 1), (0, 1)]""" + run_test(test1_2) + + def test_f1_3_sobol(self): + """Multivariate test function 1: + x[0]**2 + x[1]**2 with bounds=[(None, None),(None, None)]""" + options = {'disp': True} + run_test(test1_3, options=options) + + def test_f2_1_sobol(self): + """Univariate test function on + f(x) = (x - 30) * sin(x) with bounds=[(0, 60)]""" + run_test(test2_1) + + def test_f2_2_sobol(self): + """Univariate test function on + f(x) = (x - 30) * sin(x) bounds=[(0, 4.5)]""" + run_test(test2_2) + + def test_f3_sobol(self): + """NLP: Hock and Schittkowski problem 18""" + run_test(test3_1) + + @pytest.mark.slow + def test_f4_sobol(self): + """NLP: (High dimensional) Hock and Schittkowski 11 problem (HS11)""" + options = {'infty_constraints': False} + # run_test(test4_1, n=990, options=options) + run_test(test4_1, n=990 * 2, options=options) + + def test_f5_1_sobol(self): + """NLP: Eggholder, multimodal""" + # run_test(test5_1, n=30) + run_test(test5_1, n=60) + + def test_f5_2_sobol(self): + """NLP: Eggholder, multimodal""" + # run_test(test5_1, n=60, iters=5) + run_test(test5_1, n=60, iters=5) + + # def test_t911(self): + # """1D tabletop function""" + # run_test(test11_1) + + +class TestShgoSimplicialTestFunctions: + """ + Global optimisation tests with Simplicial sampling: + """ + + def test_f1_1_simplicial(self): + """Multivariate test function 1: + x[0]**2 + x[1]**2 with bounds=[(-1, 6), (-1, 6)]""" + run_test(test1_1, n=1, sampling_method='simplicial') + + def test_f1_2_simplicial(self): + """Multivariate test function 1: + x[0]**2 + x[1]**2 with bounds=[(0, 1), (0, 1)]""" + run_test(test1_2, n=1, sampling_method='simplicial') + + def test_f1_3_simplicial(self): + """Multivariate test function 1: x[0]**2 + x[1]**2 + with bounds=[(None, None),(None, None)]""" + run_test(test1_3, n=5, sampling_method='simplicial') + + def test_f2_1_simplicial(self): + """Univariate test function on + f(x) = (x - 30) * sin(x) with bounds=[(0, 60)]""" + options = {'minimize_every_iter': False} + run_test(test2_1, n=200, iters=7, options=options, + sampling_method='simplicial') + + def test_f2_2_simplicial(self): + """Univariate test function on + f(x) = (x - 30) * sin(x) bounds=[(0, 4.5)]""" + run_test(test2_2, n=1, sampling_method='simplicial') + + def test_f3_simplicial(self): + """NLP: Hock and Schittkowski problem 18""" + run_test(test3_1, n=1, sampling_method='simplicial') + + @pytest.mark.slow + def test_f4_simplicial(self): + """NLP: (High dimensional) Hock and Schittkowski 11 problem (HS11)""" + run_test(test4_1, n=1, sampling_method='simplicial') + + def test_lj_symmetry_old(self): + """LJ: Symmetry-constrained test function""" + options = {'symmetry': True, + 'disp': True} + args = (6,) # Number of atoms + run_test(testLJ, args=args, n=300, + options=options, iters=1, + sampling_method='simplicial') + + def test_f5_1_lj_symmetry(self): + """LJ: Symmetry constrained test function""" + options = {'symmetry': [0, ] * 6, + 'disp': True} + args = (6,) # No. of atoms + + run_test(testLJ, args=args, n=300, + options=options, iters=1, + sampling_method='simplicial') + + def test_f5_2_cons_symmetry(self): + """Symmetry constrained test function""" + options = {'symmetry': [0, 0], + 'disp': True} + + run_test(test1_1, n=200, + options=options, iters=1, + sampling_method='simplicial') + + @pytest.mark.fail_slow(10) + def test_f5_3_cons_symmetry(self): + """Asymmetrically constrained test function""" + options = {'symmetry': [0, 0, 0, 3], + 'disp': True} + + run_test(test_s, n=10000, + options=options, + iters=1, + sampling_method='simplicial') + + @pytest.mark.skip("Not a test") + def test_f0_min_variance(self): + """Return a minimum on a perfectly symmetric problem, based on + gh10429""" + avg = 0.5 # Given average value of x + cons = {'type': 'eq', 'fun': lambda x: np.mean(x) - avg} + + # Minimize the variance of x under the given constraint + res = shgo(np.var, bounds=6 * [(0, 1)], constraints=cons) + assert res.success + assert_allclose(res.fun, 0, atol=1e-15) + assert_allclose(res.x, 0.5) + + @pytest.mark.skip("Not a test") + def test_f0_min_variance_1D(self): + """Return a minimum on a perfectly symmetric 1D problem, based on + gh10538""" + + def fun(x): + return x * (x - 1.0) * (x - 0.5) + + bounds = [(0, 1)] + res = shgo(fun, bounds=bounds) + ref = minimize_scalar(fun, bounds=bounds[0]) + assert res.success + assert_allclose(res.fun, ref.fun) + assert_allclose(res.x, ref.x, rtol=1e-6) + +# Argument test functions +class TestShgoArguments: + def test_1_1_simpl_iter(self): + """Iterative simplicial sampling on TestFunction 1 (multivariate)""" + run_test(test1_2, n=None, iters=2, sampling_method='simplicial') + + def test_1_2_simpl_iter(self): + """Iterative simplicial on TestFunction 2 (univariate)""" + options = {'minimize_every_iter': False} + run_test(test2_1, n=None, iters=9, options=options, + sampling_method='simplicial') + + def test_2_1_sobol_iter(self): + """Iterative Sobol sampling on TestFunction 1 (multivariate)""" + run_test(test1_2, n=None, iters=1, sampling_method='sobol') + + def test_2_2_sobol_iter(self): + """Iterative Sobol sampling on TestFunction 2 (univariate)""" + res = shgo(test2_1.f, test2_1.bounds, constraints=test2_1.cons, + n=None, iters=1, sampling_method='sobol') + + np.testing.assert_allclose(res.x, test2_1.expected_x, rtol=1e-5, atol=1e-5) + np.testing.assert_allclose(res.fun, test2_1.expected_fun, atol=1e-5) + + def test_3_1_disp_simplicial(self): + """Iterative sampling on TestFunction 1 and 2 (multi and univariate) + """ + + def callback_func(x): + print("Local minimization callback test") + + for test in [test1_1, test2_1]: + shgo(test.f, test.bounds, iters=1, + sampling_method='simplicial', + callback=callback_func, options={'disp': True}) + shgo(test.f, test.bounds, n=1, sampling_method='simplicial', + callback=callback_func, options={'disp': True}) + + def test_3_2_disp_sobol(self): + """Iterative sampling on TestFunction 1 and 2 (multi and univariate)""" + + def callback_func(x): + print("Local minimization callback test") + + for test in [test1_1, test2_1]: + shgo(test.f, test.bounds, iters=1, sampling_method='sobol', + callback=callback_func, options={'disp': True}) + + shgo(test.f, test.bounds, n=1, sampling_method='simplicial', + callback=callback_func, options={'disp': True}) + + def test_args_gh14589(self): + """Using `args` used to cause `shgo` to fail; see #14589, #15986, + #16506""" + res = shgo(func=lambda x, y, z: x * z + y, bounds=[(0, 3)], args=(1, 2) + ) + ref = shgo(func=lambda x: 2 * x + 1, bounds=[(0, 3)]) + assert_allclose(res.fun, ref.fun) + assert_allclose(res.x, ref.x) + + @pytest.mark.slow + def test_4_1_known_f_min(self): + """Test known function minima stopping criteria""" + # Specify known function value + options = {'f_min': test4_1.expected_fun, + 'f_tol': 1e-6, + 'minimize_every_iter': True} + # TODO: Make default n higher for faster tests + run_test(test4_1, n=None, test_atol=1e-5, options=options, + sampling_method='simplicial') + + @pytest.mark.slow + def test_4_2_known_f_min(self): + """Test Global mode limiting local evaluations""" + options = { # Specify known function value + 'f_min': test4_1.expected_fun, + 'f_tol': 1e-6, + # Specify number of local iterations to perform + 'minimize_every_iter': True, + 'local_iter': 1} + + run_test(test4_1, n=None, test_atol=1e-5, options=options, + sampling_method='simplicial') + + def test_4_4_known_f_min(self): + """Test Global mode limiting local evaluations for 1D funcs""" + options = { # Specify known function value + 'f_min': test2_1.expected_fun, + 'f_tol': 1e-6, + # Specify number of local iterations to perform+ + 'minimize_every_iter': True, + 'local_iter': 1, + 'infty_constraints': False} + + res = shgo(test2_1.f, test2_1.bounds, constraints=test2_1.cons, + n=None, iters=None, options=options, + sampling_method='sobol') + np.testing.assert_allclose(res.x, test2_1.expected_x, rtol=1e-5, atol=1e-5) + + def test_5_1_simplicial_argless(self): + """Test Default simplicial sampling settings on TestFunction 1""" + res = shgo(test1_1.f, test1_1.bounds, constraints=test1_1.cons) + np.testing.assert_allclose(res.x, test1_1.expected_x, rtol=1e-5, atol=1e-5) + + def test_5_2_sobol_argless(self): + """Test Default sobol sampling settings on TestFunction 1""" + res = shgo(test1_1.f, test1_1.bounds, constraints=test1_1.cons, + sampling_method='sobol') + np.testing.assert_allclose(res.x, test1_1.expected_x, rtol=1e-5, atol=1e-5) + + def test_6_1_simplicial_max_iter(self): + """Test that maximum iteration option works on TestFunction 3""" + options = {'max_iter': 2} + res = shgo(test3_1.f, test3_1.bounds, constraints=test3_1.cons, + options=options, sampling_method='simplicial') + np.testing.assert_allclose(res.x, test3_1.expected_x, rtol=1e-5, atol=1e-5) + np.testing.assert_allclose(res.fun, test3_1.expected_fun, atol=1e-5) + + def test_6_2_simplicial_min_iter(self): + """Test that maximum iteration option works on TestFunction 3""" + options = {'min_iter': 2} + res = shgo(test3_1.f, test3_1.bounds, constraints=test3_1.cons, + options=options, sampling_method='simplicial') + np.testing.assert_allclose(res.x, test3_1.expected_x, rtol=1e-5, atol=1e-5) + np.testing.assert_allclose(res.fun, test3_1.expected_fun, atol=1e-5) + + def test_7_1_minkwargs(self): + """Test the minimizer_kwargs arguments for solvers with constraints""" + # Test solvers + for solver in ['COBYLA', 'COBYQA', 'SLSQP']: + # Note that passing global constraints to SLSQP is tested in other + # unittests which run test4_1 normally + minimizer_kwargs = {'method': solver, + 'constraints': test3_1.cons} + run_test(test3_1, n=100, test_atol=1e-3, + minimizer_kwargs=minimizer_kwargs, + sampling_method='sobol') + + def test_7_2_minkwargs(self): + """Test the minimizer_kwargs default inits""" + minimizer_kwargs = {'ftol': 1e-5} + options = {'disp': True} # For coverage purposes + SHGO(test3_1.f, test3_1.bounds, constraints=test3_1.cons[0], + minimizer_kwargs=minimizer_kwargs, options=options) + + def test_7_3_minkwargs(self): + """Test minimizer_kwargs arguments for solvers without constraints""" + for solver in ['Nelder-Mead', 'Powell', 'CG', 'BFGS', 'Newton-CG', + 'L-BFGS-B', 'TNC', 'dogleg', 'trust-ncg', 'trust-exact', + 'trust-krylov']: + def jac(x): + return np.array([2 * x[0], 2 * x[1]]).T + + def hess(x): + return np.array([[2, 0], [0, 2]]) + + minimizer_kwargs = {'method': solver, + 'jac': jac, + 'hess': hess} + logging.info(f"Solver = {solver}") + logging.info("=" * 100) + run_test(test1_1, n=100, test_atol=1e-3, + minimizer_kwargs=minimizer_kwargs, + sampling_method='sobol') + + def test_8_homology_group_diff(self): + options = {'minhgrd': 1, + 'minimize_every_iter': True} + + run_test(test1_1, n=None, iters=None, options=options, + sampling_method='simplicial') + + def test_9_cons_g(self): + """Test single function constraint passing""" + SHGO(test3_1.f, test3_1.bounds, constraints=test3_1.cons[0]) + + @pytest.mark.xfail(IS_PYPY and sys.platform == 'win32', + reason="Failing and fix in PyPy not planned (see gh-18632)") + def test_10_finite_time(self): + """Test single function constraint passing""" + options = {'maxtime': 1e-15} + + def f(x): + time.sleep(1e-14) + return 0.0 + + res = shgo(f, test1_1.bounds, iters=5, options=options) + # Assert that only 1 rather than 5 requested iterations ran: + assert res.nit == 1 + + def test_11_f_min_0(self): + """Test to cover the case where f_lowest == 0""" + options = {'f_min': 0.0, + 'disp': True} + res = shgo(test1_2.f, test1_2.bounds, n=10, iters=None, + options=options, sampling_method='sobol') + np.testing.assert_equal(0, res.x[0]) + np.testing.assert_equal(0, res.x[1]) + + # @nottest + @pytest.mark.skip(reason="no way of currently testing this") + def test_12_sobol_inf_cons(self): + """Test to cover the case where f_lowest == 0""" + # TODO: This test doesn't cover anything new, it is unknown what the + # original test was intended for as it was never complete. Delete or + # replace in the future. + options = {'maxtime': 1e-15, + 'f_min': 0.0} + res = shgo(test1_2.f, test1_2.bounds, n=1, iters=None, + options=options, sampling_method='sobol') + np.testing.assert_equal(0.0, res.fun) + + def test_13_high_sobol(self): + """Test init of high-dimensional sobol sequences""" + + def f(x): + return 0 + + bounds = [(None, None), ] * 41 + SHGOc = SHGO(f, bounds, sampling_method='sobol') + # SHGOc.sobol_points(2, 50) + SHGOc.sampling_function(2, 50) + + def test_14_local_iter(self): + """Test limited local iterations for a pseudo-global mode""" + options = {'local_iter': 4} + run_test(test5_1, n=60, options=options) + + def test_15_min_every_iter(self): + """Test minimize every iter options and cover function cache""" + options = {'minimize_every_iter': True} + run_test(test1_1, n=1, iters=7, options=options, + sampling_method='sobol') + + def test_16_disp_bounds_minimizer(self, capsys): + """Test disp=True with minimizers that do not support bounds """ + options = {'disp': True} + minimizer_kwargs = {'method': 'nelder-mead'} + run_test(test1_2, sampling_method='simplicial', + options=options, minimizer_kwargs=minimizer_kwargs) + + def test_17_custom_sampling(self): + """Test the functionality to add custom sampling methods to shgo""" + + def sample(n, d): + return np.random.uniform(size=(n, d)) + + run_test(test1_1, n=30, sampling_method=sample) + + def test_18_bounds_class(self): + # test that new and old bounds yield same result + def f(x): + return np.square(x).sum() + + lb = [-6., 1., -5.] + ub = [-1., 3., 5.] + bounds_old = list(zip(lb, ub)) + bounds_new = Bounds(lb, ub) + + res_old_bounds = shgo(f, bounds_old) + res_new_bounds = shgo(f, bounds_new) + + assert res_new_bounds.nfev == res_old_bounds.nfev + assert res_new_bounds.message == res_old_bounds.message + assert res_new_bounds.success == res_old_bounds.success + x_opt = np.array([-1., 1., 0.]) + np.testing.assert_allclose(res_new_bounds.x, x_opt) + np.testing.assert_allclose(res_new_bounds.x, res_old_bounds.x) + + @pytest.mark.fail_slow(10) + def test_19_parallelization(self): + """Test the functionality to add custom sampling methods to shgo""" + + with Pool(2) as p: + run_test(test1_1, n=30, workers=p.map) # Constrained + run_test(test1_1, n=30, workers=map) # Constrained + with Pool(2) as p: + run_test(test_s, n=30, workers=p.map) # Unconstrained + run_test(test_s, n=30, workers=map) # Unconstrained + + def test_20_constrained_args(self): + """Test that constraints can be passed to arguments""" + + def eggholder(x): + return ( + -(x[1] + 47.0)*np.sin(np.sqrt(abs(x[0] / 2.0 + (x[1] + 47.0)))) + - x[0]*np.sin(np.sqrt(abs(x[0] - (x[1] + 47.0)))) + ) + + def f(x): # (cattle-feed) + return 24.55 * x[0] + 26.75 * x[1] + 39 * x[2] + 40.50 * x[3] + + bounds = [(0, 1.0), ] * 4 + + def g1_modified(x, i): + return i * 2.3 * x[0] + i * 5.6 * x[1] + 11.1 * x[2] + 1.3 * x[ + 3] - 5 # >=0 + + def g2(x): + return ( + 12*x[0] + 11.9*x[1] + 41.8*x[2] + 52.1*x[3] - 21 + - 1.645*np.sqrt( + 0.28*x[0]**2 + 0.19*x[1]**2 + 20.5*x[2]**2 + 0.62*x[3]**2 + ) + ) # >=0 + + def h1(x): + return x[0] + x[1] + x[2] + x[3] - 1 # == 0 + + cons = ({'type': 'ineq', 'fun': g1_modified, "args": (0,)}, + {'type': 'ineq', 'fun': g2}, + {'type': 'eq', 'fun': h1}) + + shgo(f, bounds, n=300, iters=1, constraints=cons) + # using constrain with arguments AND sampling method sobol + shgo(f, bounds, n=300, iters=1, constraints=cons, + sampling_method='sobol') + + def test_21_1_jac_true(self): + """Test that shgo can handle objective functions that return the + gradient alongside the objective value. Fixes gh-13547""" + # previous + def func(x): + return np.sum(np.power(x, 2)), 2 * x + + shgo( + func, + bounds=[[-1, 1], [1, 2]], + n=100, iters=5, + sampling_method="sobol", + minimizer_kwargs={'method': 'SLSQP', 'jac': True} + ) + + # new + def func(x): + return np.sum(x ** 2), 2 * x + + bounds = [[-1, 1], [1, 2], [-1, 1], [1, 2], [0, 3]] + + res = shgo(func, bounds=bounds, sampling_method="sobol", + minimizer_kwargs={'method': 'SLSQP', 'jac': True}) + ref = minimize(func, x0=[1, 1, 1, 1, 1], bounds=bounds, + jac=True) + assert res.success + assert_allclose(res.fun, ref.fun) + assert_allclose(res.x, ref.x, atol=1e-15) + + @pytest.mark.parametrize('derivative', ['jac', 'hess', 'hessp']) + def test_21_2_derivative_options(self, derivative): + """shgo used to raise an error when passing `options` with 'jac' + # see gh-12963. check that this is resolved + """ + + def objective(x): + return 3 * x[0] * x[0] + 2 * x[0] + 5 + + def gradient(x): + return 6 * x[0] + 2 + + def hess(x): + return 6 + + def hessp(x, p): + return 6 * p + + derivative_funcs = {'jac': gradient, 'hess': hess, 'hessp': hessp} + options = {derivative: derivative_funcs[derivative]} + minimizer_kwargs = {'method': 'trust-constr'} + + bounds = [(-100, 100)] + res = shgo(objective, bounds, minimizer_kwargs=minimizer_kwargs, + options=options) + ref = minimize(objective, x0=[0], bounds=bounds, **minimizer_kwargs, + **options) + + assert res.success + np.testing.assert_allclose(res.fun, ref.fun) + np.testing.assert_allclose(res.x, ref.x) + + def test_21_3_hess_options_rosen(self): + """Ensure the Hessian gets passed correctly to the local minimizer + routine. Previous report gh-14533. + """ + bounds = [(0, 1.6), (0, 1.6), (0, 1.4), (0, 1.4), (0, 1.4)] + options = {'jac': rosen_der, 'hess': rosen_hess} + minimizer_kwargs = {'method': 'Newton-CG'} + res = shgo(rosen, bounds, minimizer_kwargs=minimizer_kwargs, + options=options) + ref = minimize(rosen, np.zeros(5), method='Newton-CG', + **options) + assert res.success + assert_allclose(res.fun, ref.fun) + assert_allclose(res.x, ref.x, atol=1e-15) + + def test_21_arg_tuple_sobol(self): + """shgo used to raise an error when passing `args` with Sobol sampling + # see gh-12114. check that this is resolved""" + + def fun(x, k): + return x[0] ** k + + constraints = ({'type': 'ineq', 'fun': lambda x: x[0] - 1}) + + bounds = [(0, 10)] + res = shgo(fun, bounds, args=(1,), constraints=constraints, + sampling_method='sobol') + ref = minimize(fun, np.zeros(1), bounds=bounds, args=(1,), + constraints=constraints) + assert res.success + assert_allclose(res.fun, ref.fun) + assert_allclose(res.x, ref.x) + + +# Failure test functions +class TestShgoFailures: + def test_1_maxiter(self): + """Test failure on insufficient iterations""" + options = {'maxiter': 2} + res = shgo(test4_1.f, test4_1.bounds, n=2, iters=None, + options=options, sampling_method='sobol') + + np.testing.assert_equal(False, res.success) + # np.testing.assert_equal(4, res.nfev) + np.testing.assert_equal(4, res.tnev) + + def test_2_sampling(self): + """Rejection of unknown sampling method""" + assert_raises(ValueError, shgo, test1_1.f, test1_1.bounds, + sampling_method='not_Sobol') + + def test_3_1_no_min_pool_sobol(self): + """Check that the routine stops when no minimiser is found + after maximum specified function evaluations""" + options = {'maxfev': 10, + # 'maxev': 10, + 'disp': True} + res = shgo(test_table.f, test_table.bounds, n=3, options=options, + sampling_method='sobol') + np.testing.assert_equal(False, res.success) + # np.testing.assert_equal(9, res.nfev) + np.testing.assert_equal(12, res.nfev) + + def test_3_2_no_min_pool_simplicial(self): + """Check that the routine stops when no minimiser is found + after maximum specified sampling evaluations""" + options = {'maxev': 10, + 'disp': True} + res = shgo(test_table.f, test_table.bounds, n=3, options=options, + sampling_method='simplicial') + np.testing.assert_equal(False, res.success) + + def test_4_1_bound_err(self): + """Specified bounds ub > lb""" + bounds = [(6, 3), (3, 5)] + assert_raises(ValueError, shgo, test1_1.f, bounds) + + def test_4_2_bound_err(self): + """Specified bounds are of the form (lb, ub)""" + bounds = [(3, 5, 5), (3, 5)] + assert_raises(ValueError, shgo, test1_1.f, bounds) + + def test_5_1_1_infeasible_sobol(self): + """Ensures the algorithm terminates on infeasible problems + after maxev is exceeded. Use infty constraints option""" + options = {'maxev': 100, + 'disp': True} + + res = shgo(test_infeasible.f, test_infeasible.bounds, + constraints=test_infeasible.cons, n=100, options=options, + sampling_method='sobol') + + np.testing.assert_equal(False, res.success) + + def test_5_1_2_infeasible_sobol(self): + """Ensures the algorithm terminates on infeasible problems + after maxev is exceeded. Do not use infty constraints option""" + options = {'maxev': 100, + 'disp': True, + 'infty_constraints': False} + + res = shgo(test_infeasible.f, test_infeasible.bounds, + constraints=test_infeasible.cons, n=100, options=options, + sampling_method='sobol') + + np.testing.assert_equal(False, res.success) + + def test_5_2_infeasible_simplicial(self): + """Ensures the algorithm terminates on infeasible problems + after maxev is exceeded.""" + options = {'maxev': 1000, + 'disp': False} + + res = shgo(test_infeasible.f, test_infeasible.bounds, + constraints=test_infeasible.cons, n=100, options=options, + sampling_method='simplicial') + + np.testing.assert_equal(False, res.success) + + @pytest.mark.thread_unsafe + def test_6_1_lower_known_f_min(self): + """Test Global mode limiting local evaluations with f* too high""" + options = { # Specify known function value + 'f_min': test2_1.expected_fun + 2.0, + 'f_tol': 1e-6, + # Specify number of local iterations to perform+ + 'minimize_every_iter': True, + 'local_iter': 1, + 'infty_constraints': False} + args = (test2_1.f, test2_1.bounds) + kwargs = {'constraints': test2_1.cons, + 'n': None, + 'iters': None, + 'options': options, + 'sampling_method': 'sobol' + } + warns(UserWarning, shgo, *args, **kwargs) + + def test(self): + from scipy.optimize import rosen, shgo + bounds = [(0, 2), (0, 2), (0, 2), (0, 2), (0, 2)] + + def fun(x): + fun.nfev += 1 + return rosen(x) + + fun.nfev = 0 + + result = shgo(fun, bounds) + print(result.x, result.fun, fun.nfev) # 50 + + +# Returns +class TestShgoReturns: + def test_1_nfev_simplicial(self): + bounds = [(0, 2), (0, 2), (0, 2), (0, 2), (0, 2)] + + def fun(x): + fun.nfev += 1 + return rosen(x) + + fun.nfev = 0 + + result = shgo(fun, bounds) + np.testing.assert_equal(fun.nfev, result.nfev) + + def test_1_nfev_sobol(self): + bounds = [(0, 2), (0, 2), (0, 2), (0, 2), (0, 2)] + + def fun(x): + fun.nfev += 1 + return rosen(x) + + fun.nfev = 0 + + result = shgo(fun, bounds, sampling_method='sobol') + np.testing.assert_equal(fun.nfev, result.nfev) + + +def test_vector_constraint(): + # gh15514 + def quad(x): + x = np.asarray(x) + return [np.sum(x ** 2)] + + nlc = NonlinearConstraint(quad, [2.2], [3]) + oldc = new_constraint_to_old(nlc, np.array([1.0, 1.0])) + + res = shgo(rosen, [(0, 10), (0, 10)], constraints=oldc, sampling_method='sobol') + assert np.all(np.sum((res.x)**2) >= 2.2) + assert np.all(np.sum((res.x) ** 2) <= 3.0) + assert res.success + + +@pytest.mark.filterwarnings("ignore:delta_grad") +def test_trust_constr(): + def quad(x): + x = np.asarray(x) + return [np.sum(x ** 2)] + + nlc = NonlinearConstraint(quad, [2.6], [3]) + minimizer_kwargs = {'method': 'trust-constr'} + # note that we don't supply the constraints in minimizer_kwargs, + # so if the final result obeys the constraints we know that shgo + # passed them on to 'trust-constr' + res = shgo( + rosen, + [(0, 10), (0, 10)], + constraints=nlc, + sampling_method='sobol', + minimizer_kwargs=minimizer_kwargs + ) + assert np.all(np.sum((res.x)**2) >= 2.6) + assert np.all(np.sum((res.x) ** 2) <= 3.0) + assert res.success + + +def test_equality_constraints(): + # gh16260 + bounds = [(0.9, 4.0)] * 2 # Constrain probabilities to 0 and 1. + + def faulty(x): + return x[0] + x[1] + + nlc = NonlinearConstraint(faulty, 3.9, 3.9) + res = shgo(rosen, bounds=bounds, constraints=nlc) + assert_allclose(np.sum(res.x), 3.9) + + def faulty(x): + return x[0] + x[1] - 3.9 + + constraints = {'type': 'eq', 'fun': faulty} + res = shgo(rosen, bounds=bounds, constraints=constraints) + assert_allclose(np.sum(res.x), 3.9) + + bounds = [(0, 1.0)] * 4 + # sum of variable should equal 1. + def faulty(x): + return x[0] + x[1] + x[2] + x[3] - 1 + + # options = {'minimize_every_iter': True, 'local_iter':10} + constraints = {'type': 'eq', 'fun': faulty} + res = shgo( + lambda x: - np.prod(x), + bounds=bounds, + constraints=constraints, + sampling_method='sobol' + ) + assert_allclose(np.sum(res.x), 1.0) + +def test_gh16971(): + def cons(x): + return np.sum(x**2) - 0 + + c = {'fun': cons, 'type': 'ineq'} + minimizer_kwargs = { + 'method': 'COBYLA', + 'options': {'rhobeg': 5, 'tol': 5e-1, 'catol': 0.05} + } + + s = SHGO( + rosen, [(0, 10)]*2, constraints=c, minimizer_kwargs=minimizer_kwargs + ) + + assert s.minimizer_kwargs['method'].lower() == 'cobyla' + assert s.minimizer_kwargs['options']['catol'] == 0.05 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test__spectral.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test__spectral.py new file mode 100644 index 0000000000000000000000000000000000000000..7b4dc52cc20caf0206fe53933d4dfc6d0fbb2c34 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test__spectral.py @@ -0,0 +1,226 @@ +import itertools + +import numpy as np +from numpy import exp +from numpy.testing import assert_, assert_equal + +from scipy.optimize import root + + +def test_performance(): + # Compare performance results to those listed in + # [Cheng & Li, IMA J. Num. An. 29, 814 (2008)] + # and + # [W. La Cruz, J.M. Martinez, M. Raydan, Math. Comp. 75, 1429 (2006)]. + # and those produced by dfsane.f from M. Raydan's website. + # + # Where the results disagree, the largest limits are taken. + + e_a = 1e-5 + e_r = 1e-4 + + table_1 = [ + dict(F=F_1, x0=x0_1, n=1000, nit=5, nfev=5), + dict(F=F_1, x0=x0_1, n=10000, nit=2, nfev=2), + dict(F=F_2, x0=x0_2, n=500, nit=11, nfev=11), + dict(F=F_2, x0=x0_2, n=2000, nit=11, nfev=11), + # dict(F=F_4, x0=x0_4, n=999, nit=243, nfev=1188) removed: + # too sensitive to rounding errors + # Results from dfsane.f; papers list nit=3, nfev=3 + dict(F=F_6, x0=x0_6, n=100, nit=6, nfev=6), + # Must have n%3==0, typo in papers? + dict(F=F_7, x0=x0_7, n=99, nit=23, nfev=29), + # Must have n%3==0, typo in papers? + dict(F=F_7, x0=x0_7, n=999, nit=23, nfev=29), + # Results from dfsane.f; papers list nit=nfev=6? + dict(F=F_9, x0=x0_9, n=100, nit=12, nfev=18), + dict(F=F_9, x0=x0_9, n=1000, nit=12, nfev=18), + # Results from dfsane.f; papers list nit=2, nfev=12 + dict(F=F_10, x0=x0_10, n=1000, nit=5, nfev=5), + ] + + # Check also scaling invariance + for xscale, yscale, line_search in itertools.product( + [1.0, 1e-10, 1e10], [1.0, 1e-10, 1e10], ['cruz', 'cheng'] + ): + for problem in table_1: + n = problem['n'] + def func(x, n): + return yscale * problem['F'](x / xscale, n) + args = (n,) + x0 = problem['x0'](n) * xscale + + fatol = np.sqrt(n) * e_a * yscale + e_r * np.linalg.norm(func(x0, n)) + + sigma_eps = 1e-10 * min(yscale/xscale, xscale/yscale) + sigma_0 = xscale/yscale + + with np.errstate(over='ignore'): + sol = root(func, x0, args=args, + options=dict(ftol=0, fatol=fatol, maxfev=problem['nfev'] + 1, + sigma_0=sigma_0, sigma_eps=sigma_eps, + line_search=line_search), + method='DF-SANE') + + err_msg = repr( + [xscale, yscale, line_search, problem, np.linalg.norm(func(sol.x, n)), + fatol, sol.success, sol.nit, sol.nfev] + ) + assert sol.success, err_msg + # nfev+1: dfsane.f doesn't count first eval + assert sol.nfev <= problem['nfev'] + 1, err_msg + assert sol.nit <= problem['nit'], err_msg + assert np.linalg.norm(func(sol.x, n)) <= fatol, err_msg + + +def test_complex(): + def func(z): + return z**2 - 1 + 2j + x0 = 2.0j + + ftol = 1e-4 + sol = root(func, x0, tol=ftol, method='DF-SANE') + + assert_(sol.success) + + f0 = np.linalg.norm(func(x0)) + fx = np.linalg.norm(func(sol.x)) + assert_(fx <= ftol*f0) + + +def test_linear_definite(): + # The DF-SANE paper proves convergence for "strongly isolated" + # solutions. + # + # For linear systems F(x) = A x - b = 0, with A positive or + # negative definite, the solution is strongly isolated. + + def check_solvability(A, b, line_search='cruz'): + def func(x): + return A.dot(x) - b + xp = np.linalg.solve(A, b) + eps = np.linalg.norm(func(xp)) * 1e3 + sol = root( + func, b, + options=dict(fatol=eps, ftol=0, maxfev=17523, line_search=line_search), + method='DF-SANE', + ) + assert_(sol.success) + assert_(np.linalg.norm(func(sol.x)) <= eps) + + n = 90 + + # Test linear pos.def. system + np.random.seed(1234) + A = np.arange(n*n).reshape(n, n) + A = A + n*n * np.diag(1 + np.arange(n)) + assert_(np.linalg.eigvals(A).min() > 0) + b = np.arange(n) * 1.0 + check_solvability(A, b, 'cruz') + check_solvability(A, b, 'cheng') + + # Test linear neg.def. system + check_solvability(-A, b, 'cruz') + check_solvability(-A, b, 'cheng') + + +def test_shape(): + def f(x, arg): + return x - arg + + for dt in [float, complex]: + x = np.zeros([2,2]) + arg = np.ones([2,2], dtype=dt) + + sol = root(f, x, args=(arg,), method='DF-SANE') + assert_(sol.success) + assert_equal(sol.x.shape, x.shape) + + +# Some of the test functions and initial guesses listed in +# [W. La Cruz, M. Raydan. Optimization Methods and Software, 18, 583 (2003)] + +def F_1(x, n): + g = np.zeros([n]) + i = np.arange(2, n+1) + g[0] = exp(x[0] - 1) - 1 + g[1:] = i*(exp(x[1:] - 1) - x[1:]) + return g + +def x0_1(n): + x0 = np.empty([n]) + x0.fill(n/(n-1)) + return x0 + +def F_2(x, n): + g = np.zeros([n]) + i = np.arange(2, n+1) + g[0] = exp(x[0]) - 1 + g[1:] = 0.1*i*(exp(x[1:]) + x[:-1] - 1) + return g + +def x0_2(n): + x0 = np.empty([n]) + x0.fill(1/n**2) + return x0 + + +def F_4(x, n): # skip name check + assert_equal(n % 3, 0) + g = np.zeros([n]) + # Note: the first line is typoed in some of the references; + # correct in original [Gasparo, Optimization Meth. 13, 79 (2000)] + g[::3] = 0.6 * x[::3] + 1.6 * x[1::3]**3 - 7.2 * x[1::3]**2 + 9.6 * x[1::3] - 4.8 + g[1::3] = (0.48 * x[::3] - 0.72 * x[1::3]**3 + 3.24 * x[1::3]**2 - 4.32 * x[1::3] + - x[2::3] + 0.2 * x[2::3]**3 + 2.16) + g[2::3] = 1.25 * x[2::3] - 0.25*x[2::3]**3 + return g + + +def x0_4(n): # skip name check + assert_equal(n % 3, 0) + x0 = np.array([-1, 1/2, -1] * (n//3)) + return x0 + +def F_6(x, n): + c = 0.9 + mu = (np.arange(1, n+1) - 0.5)/n + return x - 1/(1 - c/(2*n) * (mu[:,None]*x / (mu[:,None] + mu)).sum(axis=1)) + +def x0_6(n): + return np.ones([n]) + +def F_7(x, n): + assert_equal(n % 3, 0) + + def phi(t): + v = 0.5*t - 2 + v[t > -1] = ((-592*t**3 + 888*t**2 + 4551*t - 1924)/1998)[t > -1] + v[t >= 2] = (0.5*t + 2)[t >= 2] + return v + g = np.zeros([n]) + g[::3] = 1e4 * x[1::3]**2 - 1 + g[1::3] = exp(-x[::3]) + exp(-x[1::3]) - 1.0001 + g[2::3] = phi(x[2::3]) + return g + +def x0_7(n): + assert_equal(n % 3, 0) + return np.array([1e-3, 18, 1] * (n//3)) + +def F_9(x, n): + g = np.zeros([n]) + i = np.arange(2, n) + g[0] = x[0]**3/3 + x[1]**2/2 + g[1:-1] = -x[1:-1]**2/2 + i*x[1:-1]**3/3 + x[2:]**2/2 + g[-1] = -x[-1]**2/2 + n*x[-1]**3/3 + return g + +def x0_9(n): + return np.ones([n]) + +def F_10(x, n): + return np.log(1 + x) - x/n + +def x0_10(n): + return np.ones([n]) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_bracket.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_bracket.py new file mode 100644 index 0000000000000000000000000000000000000000..f3a47fc005a2af6bbd02465634fdb72fa131f8f8 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_bracket.py @@ -0,0 +1,906 @@ +import pytest + +import numpy as np + +from scipy.optimize._bracket import _ELIMITS +from scipy.optimize.elementwise import bracket_root, bracket_minimum +import scipy._lib._elementwise_iterative_method as eim +from scipy import stats +from scipy._lib._array_api_no_0d import (xp_assert_close, xp_assert_equal, + xp_assert_less, array_namespace) +from scipy._lib._array_api import xp_ravel +from scipy.conftest import array_api_compatible + + +# These tests were originally written for the private `optimize._bracket` +# interfaces, but now we want the tests to check the behavior of the public +# `optimize.elementwise` interfaces. Therefore, rather than importing +# `_bracket_root`/`_bracket_minimum` from `_bracket.py`, we import +# `bracket_root`/`bracket_minimum` from `optimize.elementwise` and wrap those +# functions to conform to the private interface. This may look a little strange, +# since it effectively just inverts the interface transformation done within the +# `bracket_root`/`bracket_minimum` functions, but it allows us to run the original, +# unmodified tests on the public interfaces, simplifying the PR that adds +# the public interfaces. We'll refactor this when we want to @parametrize the +# tests over multiple `method`s. +def _bracket_root(*args, **kwargs): + res = bracket_root(*args, **kwargs) + res.xl, res.xr = res.bracket + res.fl, res.fr = res.f_bracket + del res.bracket + del res.f_bracket + return res + + +def _bracket_minimum(*args, **kwargs): + res = bracket_minimum(*args, **kwargs) + res.xl, res.xm, res.xr = res.bracket + res.fl, res.fm, res.fr = res.f_bracket + del res.bracket + del res.f_bracket + return res + + +array_api_strict_skip_reason = 'Array API does not support fancy indexing assignment.' +jax_skip_reason = 'JAX arrays do not support item assignment.' + +@pytest.mark.skip_xp_backends('array_api_strict', reason=array_api_strict_skip_reason) +@pytest.mark.skip_xp_backends('jax.numpy', reason=jax_skip_reason) +@array_api_compatible +@pytest.mark.usefixtures("skip_xp_backends") +class TestBracketRoot: + @pytest.mark.parametrize("seed", (615655101, 3141866013, 238075752)) + @pytest.mark.parametrize("use_xmin", (False, True)) + @pytest.mark.parametrize("other_side", (False, True)) + @pytest.mark.parametrize("fix_one_side", (False, True)) + def test_nfev_expected(self, seed, use_xmin, other_side, fix_one_side, xp): + # Property-based test to confirm that _bracket_root is behaving as + # expected. The basic case is when root < a < b. + # The number of times bracket expands (per side) can be found by + # setting the expression for the left endpoint of the bracket to the + # root of f (x=0), solving for i, and rounding up. The corresponding + # lower and upper ends of the bracket are found by plugging this back + # into the expression for the ends of the bracket. + # `other_side=True` is the case that a < b < root + # Special cases like a < root < b are tested separately + rng = np.random.default_rng(seed) + xl0, d, factor = xp.asarray(rng.random(size=3) * [1e5, 10, 5]) + factor = 1 + factor # factor must be greater than 1 + xr0 = xl0 + d # xr0 must be greater than a in basic case + + def f(x): + f.count += 1 + return x # root is 0 + + if use_xmin: + xmin = xp.asarray(-rng.random()) + n = xp.ceil(xp.log(-(xl0 - xmin) / xmin) / xp.log(factor)) + l, u = xmin + (xl0 - xmin)*factor**-n, xmin + (xl0 - xmin)*factor**-(n - 1) + kwargs = dict(xl0=xl0, xr0=xr0, factor=factor, xmin=xmin) + else: + n = xp.ceil(xp.log(xr0/d) / xp.log(factor)) + l, u = xr0 - d*factor**n, xr0 - d*factor**(n-1) + kwargs = dict(xl0=xl0, xr0=xr0, factor=factor) + + if other_side: + kwargs['xl0'], kwargs['xr0'] = -kwargs['xr0'], -kwargs['xl0'] + l, u = -u, -l + if 'xmin' in kwargs: + kwargs['xmax'] = -kwargs.pop('xmin') + + if fix_one_side: + if other_side: + kwargs['xmin'] = -xr0 + else: + kwargs['xmax'] = xr0 + + f.count = 0 + res = _bracket_root(f, **kwargs) + + # Compare reported number of function evaluations `nfev` against + # reported `nit`, actual function call count `f.count`, and theoretical + # number of expansions `n`. + # When both sides are free, these get multiplied by 2 because function + # is evaluated on the left and the right each iteration. + # When one side is fixed, however, we add one: on the right side, the + # function gets evaluated once at b. + # Add 1 to `n` and `res.nit` because function evaluations occur at + # iterations *0*, 1, ..., `n`. Subtract 1 from `f.count` because + # function is called separately for left and right in iteration 0. + if not fix_one_side: + assert res.nfev == 2*(res.nit+1) == 2*(f.count-1) == 2*(n + 1) + else: + assert res.nfev == (res.nit+1)+1 == (f.count-1)+1 == (n+1)+1 + + # Compare reported bracket to theoretical bracket and reported function + # values to function evaluated at bracket. + bracket = xp.asarray([res.xl, res.xr]) + xp_assert_close(bracket, xp.asarray([l, u])) + f_bracket = xp.asarray([res.fl, res.fr]) + xp_assert_close(f_bracket, f(bracket)) + + # Check that bracket is valid and that status and success are correct + assert res.xr > res.xl + signs = xp.sign(f_bracket) + assert signs[0] == -signs[1] + assert res.status == 0 + assert res.success + + def f(self, q, p): + return stats._stats_py._SimpleNormal().cdf(q) - p + + @pytest.mark.parametrize('p', [0.6, np.linspace(0.05, 0.95, 10)]) + @pytest.mark.parametrize('xmin', [-5, None]) + @pytest.mark.parametrize('xmax', [5, None]) + @pytest.mark.parametrize('factor', [1.2, 2]) + def test_basic(self, p, xmin, xmax, factor, xp): + # Test basic functionality to bracket root (distribution PPF) + res = _bracket_root(self.f, xp.asarray(-0.01), 0.01, xmin=xmin, xmax=xmax, + factor=factor, args=(xp.asarray(p),)) + xp_assert_equal(-xp.sign(res.fl), xp.sign(res.fr)) + + @pytest.mark.parametrize('shape', [tuple(), (12,), (3, 4), (3, 2, 2)]) + def test_vectorization(self, shape, xp): + # Test for correct functionality, output shapes, and dtypes for various + # input shapes. + p = np.linspace(-0.05, 1.05, 12).reshape(shape) if shape else np.float64(0.6) + args = (p,) + maxiter = 10 + + @np.vectorize + def bracket_root_single(xl0, xr0, xmin, xmax, factor, p): + return _bracket_root(self.f, xl0, xr0, xmin=xmin, xmax=xmax, + factor=factor, args=(p,), + maxiter=maxiter) + + def f(*args, **kwargs): + f.f_evals += 1 + return self.f(*args, **kwargs) + f.f_evals = 0 + + rng = np.random.default_rng(2348234) + xl0 = -rng.random(size=shape) + xr0 = rng.random(size=shape) + xmin, xmax = 1e3*xl0, 1e3*xr0 + if shape: # make some elements un + i = rng.random(size=shape) > 0.5 + xmin[i], xmax[i] = -np.inf, np.inf + factor = rng.random(size=shape) + 1.5 + refs = bracket_root_single(xl0, xr0, xmin, xmax, factor, p).ravel() + xl0, xr0, xmin, xmax, factor = (xp.asarray(xl0), xp.asarray(xr0), + xp.asarray(xmin), xp.asarray(xmax), + xp.asarray(factor)) + args = tuple(map(xp.asarray, args)) + res = _bracket_root(f, xl0, xr0, xmin=xmin, xmax=xmax, factor=factor, + args=args, maxiter=maxiter) + + attrs = ['xl', 'xr', 'fl', 'fr', 'success', 'nfev', 'nit'] + for attr in attrs: + ref_attr = [xp.asarray(getattr(ref, attr)) for ref in refs] + res_attr = getattr(res, attr) + xp_assert_close(xp_ravel(res_attr, xp=xp), xp.stack(ref_attr)) + xp_assert_equal(res_attr.shape, shape) + + xp_test = array_namespace(xp.asarray(1.)) + assert res.success.dtype == xp_test.bool + if shape: + assert xp.all(res.success[1:-1]) + assert res.status.dtype == xp.int32 + assert res.nfev.dtype == xp.int32 + assert res.nit.dtype == xp.int32 + assert xp.max(res.nit) == f.f_evals - 2 + xp_assert_less(res.xl, res.xr) + xp_assert_close(res.fl, xp.asarray(self.f(res.xl, *args))) + xp_assert_close(res.fr, xp.asarray(self.f(res.xr, *args))) + + def test_flags(self, xp): + # Test cases that should produce different status flags; show that all + # can be produced simultaneously. + def f(xs, js): + funcs = [lambda x: x - 1.5, + lambda x: x - 1000, + lambda x: x - 1000, + lambda x: x * xp.nan, + lambda x: x] + + return [funcs[int(j)](x) for x, j in zip(xs, js)] + + args = (xp.arange(5, dtype=xp.int64),) + res = _bracket_root(f, + xl0=xp.asarray([-1., -1., -1., -1., 4.]), + xr0=xp.asarray([1, 1, 1, 1, -4]), + xmin=xp.asarray([-xp.inf, -1, -xp.inf, -xp.inf, 6]), + xmax=xp.asarray([xp.inf, 1, xp.inf, xp.inf, 2]), + args=args, maxiter=3) + + ref_flags = xp.asarray([eim._ECONVERGED, + _ELIMITS, + eim._ECONVERR, + eim._EVALUEERR, + eim._EINPUTERR], + dtype=xp.int32) + + xp_assert_equal(res.status, ref_flags) + + @pytest.mark.parametrize("root", (0.622, [0.622, 0.623])) + @pytest.mark.parametrize('xmin', [-5, None]) + @pytest.mark.parametrize('xmax', [5, None]) + @pytest.mark.parametrize("dtype", ("float16", "float32", "float64")) + def test_dtype(self, root, xmin, xmax, dtype, xp): + # Test that dtypes are preserved + dtype = getattr(xp, dtype) + xp_test = array_namespace(xp.asarray(1.)) + + xmin = xmin if xmin is None else xp.asarray(xmin, dtype=dtype) + xmax = xmax if xmax is None else xp.asarray(xmax, dtype=dtype) + root = xp.asarray(root, dtype=dtype) + def f(x, root): + return xp_test.astype((x - root) ** 3, dtype) + + bracket = xp.asarray([-0.01, 0.01], dtype=dtype) + res = _bracket_root(f, *bracket, xmin=xmin, xmax=xmax, args=(root,)) + assert xp.all(res.success) + assert res.xl.dtype == res.xr.dtype == dtype + assert res.fl.dtype == res.fr.dtype == dtype + + def test_input_validation(self, xp): + # Test input validation for appropriate error messages + + message = '`func` must be callable.' + with pytest.raises(ValueError, match=message): + _bracket_root(None, -4, 4) + + message = '...must be numeric and real.' + with pytest.raises(ValueError, match=message): + _bracket_root(lambda x: x, -4+1j, 4) + with pytest.raises(ValueError, match=message): + _bracket_root(lambda x: x, -4, 'hello') + with pytest.raises(ValueError, match=message): + _bracket_root(lambda x: x, -4, 4, xmin=np) + with pytest.raises(ValueError, match=message): + _bracket_root(lambda x: x, -4, 4, xmax=object()) + with pytest.raises(ValueError, match=message): + _bracket_root(lambda x: x, -4, 4, factor=sum) + + message = "All elements of `factor` must be greater than 1." + with pytest.raises(ValueError, match=message): + _bracket_root(lambda x: x, -4, 4, factor=0.5) + + message = "broadcast" + # raised by `xp.broadcast, but the traceback is readable IMO + with pytest.raises(Exception, match=message): + _bracket_root(lambda x: x, xp.asarray([-2, -3]), xp.asarray([3, 4, 5])) + # Consider making this give a more readable error message + # with pytest.raises(ValueError, match=message): + # _bracket_root(lambda x: [x[0], x[1], x[1]], [-3, -3], [5, 5]) + + message = '`maxiter` must be a non-negative integer.' + with pytest.raises(ValueError, match=message): + _bracket_root(lambda x: x, -4, 4, maxiter=1.5) + with pytest.raises(ValueError, match=message): + _bracket_root(lambda x: x, -4, 4, maxiter=-1) + with pytest.raises(ValueError, match=message): + _bracket_root(lambda x: x, -4, 4, maxiter="shrubbery") + + def test_special_cases(self, xp): + # Test edge cases and other special cases + xp_test = array_namespace(xp.asarray(1.)) + + # Test that integers are not passed to `f` + # (otherwise this would overflow) + def f(x): + assert xp_test.isdtype(x.dtype, "real floating") + return x ** 99 - 1 + + res = _bracket_root(f, xp.asarray(-7.), xp.asarray(5.)) + assert res.success + + # Test maxiter = 0. Should do nothing to bracket. + def f(x): + return x - 10 + + bracket = (xp.asarray(-3.), xp.asarray(5.)) + res = _bracket_root(f, *bracket, maxiter=0) + assert res.xl, res.xr == bracket + assert res.nit == 0 + assert res.nfev == 2 + assert res.status == -2 + + # Test scalar `args` (not in tuple) + def f(x, c): + return c*x - 1 + + res = _bracket_root(f, xp.asarray(-1.), xp.asarray(1.), + args=xp.asarray(3.)) + assert res.success + xp_assert_close(res.fl, f(res.xl, 3)) + + # Test other edge cases + + def f(x): + f.count += 1 + return x + + # 1. root lies within guess of bracket + f.count = 0 + _bracket_root(f, xp.asarray(-10), xp.asarray(20)) + assert f.count == 2 + + # 2. bracket endpoint hits root exactly + f.count = 0 + res = _bracket_root(f, xp.asarray(5.), xp.asarray(10.), + factor=2) + + assert res.nfev == 4 + xp_assert_close(res.xl, xp.asarray(0.), atol=1e-15) + xp_assert_close(res.xr, xp.asarray(5.), atol=1e-15) + + # 3. bracket limit hits root exactly + with np.errstate(over='ignore'): + res = _bracket_root(f, xp.asarray(5.), xp.asarray(10.), + xmin=0) + xp_assert_close(res.xl, xp.asarray(0.), atol=1e-15) + + with np.errstate(over='ignore'): + res = _bracket_root(f, xp.asarray(-10.), xp.asarray(-5.), + xmax=0) + xp_assert_close(res.xr, xp.asarray(0.), atol=1e-15) + + # 4. bracket not within min, max + with np.errstate(over='ignore'): + res = _bracket_root(f, xp.asarray(5.), xp.asarray(10.), + xmin=1) + assert not res.success + + def test_bug_fixes(self): + # 1. Bug in double sided bracket search. + # Happened in some cases where there are terminations on one side + # after corresponding searches on other side failed due to reaching the + # boundary. + + # https://github.com/scipy/scipy/pull/22560#discussion_r1962853839 + def f(x, p): + return np.exp(x) - p + + p = np.asarray([0.29, 0.35]) + res = _bracket_root(f, xl0=-1, xmin=-np.inf, xmax=0, args=(p, )) + + # https://github.com/scipy/scipy/pull/22560/files#r1962952517 + def f(x, p, c): + return np.exp(x*c) - p + + p = [0.32061201, 0.39175242, 0.40047535, 0.50527218, 0.55654373, + 0.11911647, 0.37507896, 0.66554191] + c = [1., -1., 1., 1., -1., 1., 1., 1.] + xl0 = [-7.63108551, 3.27840947, -8.36968526, -1.78124372, + 0.92201295, -2.48930123, -0.66733533, -0.44606749] + xr0 = [-6.63108551, 4.27840947, -7.36968526, -0.78124372, + 1.92201295, -1.48930123, 0., 0.] + xmin = [-np.inf, 0., -np.inf, -np.inf, 0., -np.inf, -np.inf, + -np.inf] + xmax = [0., np.inf, 0., 0., np.inf, 0., 0., 0.] + + res = _bracket_root(f, xl0=xl0, xr0=xr0, xmin=xmin, xmax=xmax, args=(p, c)) + + # 2. Default xl0 + 1 for xr0 exceeds xmax. + # https://github.com/scipy/scipy/pull/22560#discussion_r1962947434 + res = _bracket_root(lambda x: x + 0.25, xl0=-0.5, xmin=-np.inf, xmax=0) + assert res.success + + +@pytest.mark.skip_xp_backends('array_api_strict', reason=array_api_strict_skip_reason) +@pytest.mark.skip_xp_backends('jax.numpy', reason=jax_skip_reason) +@array_api_compatible +@pytest.mark.usefixtures("skip_xp_backends") +class TestBracketMinimum: + def init_f(self): + def f(x, a, b): + f.count += 1 + return (x - a)**2 + b + f.count = 0 + return f + + def assert_valid_bracket(self, result, xp): + assert xp.all( + (result.xl < result.xm) & (result.xm < result.xr) + ) + assert xp.all( + (result.fl >= result.fm) & (result.fr > result.fm) + | (result.fl > result.fm) & (result.fr > result.fm) + ) + + def get_kwargs( + self, *, xl0=None, xr0=None, factor=None, xmin=None, xmax=None, args=None + ): + names = ("xl0", "xr0", "xmin", "xmax", "factor", "args") + return { + name: val for name, val in zip(names, (xl0, xr0, xmin, xmax, factor, args)) + if val is not None + } + + @pytest.mark.parametrize( + "seed", + ( + 307448016549685229886351382450158984917, + 11650702770735516532954347931959000479, + 113767103358505514764278732330028568336, + ) + ) + @pytest.mark.parametrize("use_xmin", (False, True)) + @pytest.mark.parametrize("other_side", (False, True)) + def test_nfev_expected(self, seed, use_xmin, other_side, xp): + rng = np.random.default_rng(seed) + args = (xp.asarray(0.), xp.asarray(0.)) # f(x) = x^2 with minimum at 0 + # xl0, xm0, xr0 are chosen such that the initial bracket is to + # the right of the minimum, and the bracket will expand + # downhill towards zero. + xl0, d1, d2, factor = xp.asarray(rng.random(size=4) * [1e5, 10, 10, 5]) + xm0 = xl0 + d1 + xr0 = xm0 + d2 + # Factor should be greater than one. + factor += 1 + + if use_xmin: + xmin = xp.asarray(-rng.random() * 5, dtype=xp.float64) + n = int(xp.ceil(xp.log(-(xl0 - xmin) / xmin) / xp.log(factor))) + lower = xmin + (xl0 - xmin)*factor**-n + middle = xmin + (xl0 - xmin)*factor**-(n-1) + upper = xmin + (xl0 - xmin)*factor**-(n-2) if n > 1 else xm0 + # It may be the case the lower is below the minimum, but we still + # don't have a valid bracket. + if middle**2 > lower**2: + n += 1 + lower, middle, upper = ( + xmin + (xl0 - xmin)*factor**-n, lower, middle + ) + else: + xmin = None + n = int(xp.ceil(xp.log(xl0 / d1) / xp.log(factor))) + lower = xl0 - d1*factor**n + middle = xl0 - d1*factor**(n-1) if n > 1 else xl0 + upper = xl0 - d1*factor**(n-2) if n > 1 else xm0 + # It may be the case the lower is below the minimum, but we still + # don't have a valid bracket. + if middle**2 > lower**2: + n += 1 + lower, middle, upper = ( + xl0 - d1*factor**n, lower, middle + ) + f = self.init_f() + + xmax = None + if other_side: + xl0, xm0, xr0 = -xr0, -xm0, -xl0 + xmin, xmax = None, -xmin if xmin is not None else None + lower, middle, upper = -upper, -middle, -lower + + kwargs = self.get_kwargs( + xl0=xl0, xr0=xr0, xmin=xmin, xmax=xmax, factor=factor, args=args + ) + result = _bracket_minimum(f, xp.asarray(xm0), **kwargs) + + # Check that `nfev` and `nit` have the correct relationship + assert result.nfev == result.nit + 3 + # Check that `nfev` reports the correct number of function evaluations. + assert result.nfev == f.count + # Check that the number of iterations matches the theoretical value. + assert result.nit == n + + # Compare reported bracket to theoretical bracket and reported function + # values to function evaluated at bracket. + xp_assert_close(result.xl, lower) + xp_assert_close(result.xm, middle) + xp_assert_close(result.xr, upper) + xp_assert_close(result.fl, f(lower, *args)) + xp_assert_close(result.fm, f(middle, *args)) + xp_assert_close(result.fr, f(upper, *args)) + + self.assert_valid_bracket(result, xp) + assert result.status == 0 + assert result.success + + def test_flags(self, xp): + # Test cases that should produce different status flags; show that all + # can be produced simultaneously + def f(xs, js): + funcs = [lambda x: (x - 1.5)**2, + lambda x: x, + lambda x: x, + lambda x: xp.nan, + lambda x: x**2] + + return [funcs[j](x) for x, j in zip(xs, js)] + + args = (xp.arange(5, dtype=xp.int64),) + xl0 = xp.asarray([-1.0, -1.0, -1.0, -1.0, 6.0]) + xm0 = xp.asarray([0.0, 0.0, 0.0, 0.0, 4.0]) + xr0 = xp.asarray([1.0, 1.0, 1.0, 1.0, 2.0]) + xmin = xp.asarray([-xp.inf, -1.0, -xp.inf, -xp.inf, 8.0]) + + result = _bracket_minimum(f, xm0, xl0=xl0, xr0=xr0, xmin=xmin, + args=args, maxiter=3) + + reference_flags = xp.asarray([eim._ECONVERGED, _ELIMITS, + eim._ECONVERR, eim._EVALUEERR, + eim._EINPUTERR], dtype=xp.int32) + xp_assert_equal(result.status, reference_flags) + + @pytest.mark.parametrize("minimum", (0.622, [0.622, 0.623])) + @pytest.mark.parametrize("dtype", ("float16", "float32", "float64")) + @pytest.mark.parametrize("xmin", [-5, None]) + @pytest.mark.parametrize("xmax", [5, None]) + def test_dtypes(self, minimum, xmin, xmax, dtype, xp): + dtype = getattr(xp, dtype) + xp_test = array_namespace(xp.asarray(1.)) + xmin = xmin if xmin is None else xp.asarray(xmin, dtype=dtype) + xmax = xmax if xmax is None else xp.asarray(xmax, dtype=dtype) + minimum = xp.asarray(minimum, dtype=dtype) + + def f(x, minimum): + return xp_test.astype((x - minimum)**2, dtype) + + xl0, xm0, xr0 = [-0.01, 0.0, 0.01] + result = _bracket_minimum( + f, xp.asarray(xm0, dtype=dtype), xl0=xp.asarray(xl0, dtype=dtype), + xr0=xp.asarray(xr0, dtype=dtype), xmin=xmin, xmax=xmax, args=(minimum, ) + ) + assert xp.all(result.success) + assert result.xl.dtype == result.xm.dtype == result.xr.dtype == dtype + assert result.fl.dtype == result.fm.dtype == result.fr.dtype == dtype + + @pytest.mark.skip_xp_backends(np_only=True, reason="str/object arrays") + def test_input_validation(self, xp): + # Test input validation for appropriate error messages + + message = '`func` must be callable.' + with pytest.raises(ValueError, match=message): + _bracket_minimum(None, -4, xl0=4) + + message = '...must be numeric and real.' + with pytest.raises(ValueError, match=message): + _bracket_minimum(lambda x: x**2, xp.asarray(4+1j)) + with pytest.raises(ValueError, match=message): + _bracket_minimum(lambda x: x**2, xp.asarray(-4), xl0='hello') + with pytest.raises(ValueError, match=message): + _bracket_minimum(lambda x: x**2, xp.asarray(-4), + xr0='farcical aquatic ceremony') + with pytest.raises(ValueError, match=message): + _bracket_minimum(lambda x: x**2, xp.asarray(-4), xmin=np) + with pytest.raises(ValueError, match=message): + _bracket_minimum(lambda x: x**2, xp.asarray(-4), xmax=object()) + with pytest.raises(ValueError, match=message): + _bracket_minimum(lambda x: x**2, xp.asarray(-4), factor=sum) + + message = "All elements of `factor` must be greater than 1." + with pytest.raises(ValueError, match=message): + _bracket_minimum(lambda x: x, xp.asarray(-4), factor=0.5) + + message = "shape mismatch: objects cannot be broadcast" + # raised by `xp.broadcast, but the traceback is readable IMO + with pytest.raises(ValueError, match=message): + _bracket_minimum(lambda x: x**2, xp.asarray([-2, -3]), xl0=[-3, -4, -5]) + + message = '`maxiter` must be a non-negative integer.' + with pytest.raises(ValueError, match=message): + _bracket_minimum(lambda x: x**2, xp.asarray(-4), xr0=4, maxiter=1.5) + with pytest.raises(ValueError, match=message): + _bracket_minimum(lambda x: x**2, xp.asarray(-4), xr0=4, maxiter=-1) + with pytest.raises(ValueError, match=message): + _bracket_minimum(lambda x: x**2, xp.asarray(-4), xr0=4, maxiter="ekki") + + @pytest.mark.parametrize("xl0", [0.0, None]) + @pytest.mark.parametrize("xm0", (0.05, 0.1, 0.15)) + @pytest.mark.parametrize("xr0", (0.2, 0.4, 0.6, None)) + # Minimum is ``a`` for each tuple ``(a, b)`` below. Tests cases where minimum + # is within, or at varying distances to the left or right of the initial + # bracket. + @pytest.mark.parametrize( + "args", + ( + (1.2, 0), (-0.5, 0), (0.1, 0), (0.2, 0), (3.6, 0), (21.4, 0), + (121.6, 0), (5764.1, 0), (-6.4, 0), (-12.9, 0), (-146.2, 0) + ) + ) + def test_scalar_no_limits(self, xl0, xm0, xr0, args, xp): + f = self.init_f() + kwargs = self.get_kwargs(xl0=xl0, xr0=xr0, args=tuple(map(xp.asarray, args))) + result = _bracket_minimum(f, xp.asarray(xm0, dtype=xp.float64), **kwargs) + self.assert_valid_bracket(result, xp) + assert result.status == 0 + assert result.success + assert result.nfev == f.count + + @pytest.mark.parametrize( + # xmin is set at 0.0 in all cases. + "xl0,xm0,xr0,xmin", + ( + # Initial bracket at varying distances from the xmin. + (0.5, 0.75, 1.0, 0.0), + (1.0, 2.5, 4.0, 0.0), + (2.0, 4.0, 6.0, 0.0), + (12.0, 16.0, 20.0, 0.0), + # Test default initial left endpoint selection. It should not + # be below xmin. + (None, 0.75, 1.0, 0.0), + (None, 2.5, 4.0, 0.0), + (None, 4.0, 6.0, 0.0), + (None, 16.0, 20.0, 0.0), + ) + ) + @pytest.mark.parametrize( + "args", ( + (0.0, 0.0), # Minimum is directly at xmin. + (1e-300, 0.0), # Minimum is extremely close to xmin. + (1e-20, 0.0), # Minimum is very close to xmin. + # Minimum at varying distances from xmin. + (0.1, 0.0), + (0.2, 0.0), + (0.4, 0.0) + ) + ) + def test_scalar_with_limit_left(self, xl0, xm0, xr0, xmin, args, xp): + f = self.init_f() + kwargs = self.get_kwargs(xl0=xl0, xr0=xr0, xmin=xmin, + args=tuple(map(xp.asarray, args))) + result = _bracket_minimum(f, xp.asarray(xm0), **kwargs) + self.assert_valid_bracket(result, xp) + assert result.status == 0 + assert result.success + assert result.nfev == f.count + + @pytest.mark.parametrize( + #xmax is set to 1.0 in all cases. + "xl0,xm0,xr0,xmax", + ( + # Bracket at varying distances from xmax. + (0.2, 0.3, 0.4, 1.0), + (0.05, 0.075, 0.1, 1.0), + (-0.2, -0.1, 0.0, 1.0), + (-21.2, -17.7, -14.2, 1.0), + # Test default right endpoint selection. It should not exceed xmax. + (0.2, 0.3, None, 1.0), + (0.05, 0.075, None, 1.0), + (-0.2, -0.1, None, 1.0), + (-21.2, -17.7, None, 1.0), + ) + ) + @pytest.mark.parametrize( + "args", ( + (0.9999999999999999, 0.0), # Minimum very close to xmax. + # Minimum at varying distances from xmax. + (0.9, 0.0), + (0.7, 0.0), + (0.5, 0.0) + ) + ) + def test_scalar_with_limit_right(self, xl0, xm0, xr0, xmax, args, xp): + f = self.init_f() + args = tuple(xp.asarray(arg, dtype=xp.float64) for arg in args) + kwargs = self.get_kwargs(xl0=xl0, xr0=xr0, xmax=xmax, args=args) + result = _bracket_minimum(f, xp.asarray(xm0, dtype=xp.float64), **kwargs) + self.assert_valid_bracket(result, xp) + assert result.status == 0 + assert result.success + assert result.nfev == f.count + + @pytest.mark.parametrize( + "xl0,xm0,xr0,xmin,xmax,args", + ( + ( # Case 1: + # Initial bracket. + 0.2, + 0.3, + 0.4, + # Function slopes down to the right from the bracket to a minimum + # at 1.0. xmax is also at 1.0 + None, + 1.0, + (1.0, 0.0) + ), + ( # Case 2: + # Initial bracket. + 1.4, + 1.95, + 2.5, + # Function slopes down to the left from the bracket to a minimum at + # 0.3 with xmin set to 0.3. + 0.3, + None, + (0.3, 0.0) + ), + ( + # Case 3: + # Initial bracket. + 2.6, + 3.25, + 3.9, + # Function slopes down and to the right to a minimum at 99.4 with xmax + # at 99.4. Tests case where minimum is at xmax relatively further from + # the bracket. + None, + 99.4, + (99.4, 0) + ), + ( + # Case 4: + # Initial bracket. + 4, + 4.5, + 5, + # Function slopes down and to the left away from the bracket with a + # minimum at -26.3 with xmin set to -26.3. Tests case where minimum is + # at xmin relatively far from the bracket. + -26.3, + None, + (-26.3, 0) + ), + ( + # Case 5: + # Similar to Case 1 above, but tests default values of xl0 and xr0. + None, + 0.3, + None, + None, + 1.0, + (1.0, 0.0) + ), + ( # Case 6: + # Similar to Case 2 above, but tests default values of xl0 and xr0. + None, + 1.95, + None, + 0.3, + None, + (0.3, 0.0) + ), + ( + # Case 7: + # Similar to Case 3 above, but tests default values of xl0 and xr0. + None, + 3.25, + None, + None, + 99.4, + (99.4, 0) + ), + ( + # Case 8: + # Similar to Case 4 above, but tests default values of xl0 and xr0. + None, + 4.5, + None, + -26.3, + None, + (-26.3, 0) + ), + ) + ) + def test_minimum_at_boundary_point(self, xl0, xm0, xr0, xmin, xmax, args, xp): + f = self.init_f() + kwargs = self.get_kwargs(xr0=xr0, xmin=xmin, xmax=xmax, + args=tuple(map(xp.asarray, args))) + result = _bracket_minimum(f, xp.asarray(xm0), **kwargs) + assert result.status == -1 + assert args[0] in (result.xl, result.xr) + assert result.nfev == f.count + + @pytest.mark.parametrize('shape', [tuple(), (12, ), (3, 4), (3, 2, 2)]) + def test_vectorization(self, shape, xp): + # Test for correct functionality, output shapes, and dtypes for + # various input shapes. + a = np.linspace(-0.05, 1.05, 12).reshape(shape) if shape else 0.6 + args = (a, 0.) + maxiter = 10 + + @np.vectorize + def bracket_minimum_single(xm0, xl0, xr0, xmin, xmax, factor, a): + return _bracket_minimum(self.init_f(), xm0, xl0=xl0, xr0=xr0, xmin=xmin, + xmax=xmax, factor=factor, maxiter=maxiter, + args=(a, 0.0)) + + f = self.init_f() + + rng = np.random.default_rng(2348234) + xl0 = -rng.random(size=shape) + xr0 = rng.random(size=shape) + xm0 = xl0 + rng.random(size=shape) * (xr0 - xl0) + xmin, xmax = 1e3*xl0, 1e3*xr0 + if shape: # make some elements un + i = rng.random(size=shape) > 0.5 + xmin[i], xmax[i] = -np.inf, np.inf + factor = rng.random(size=shape) + 1.5 + refs = bracket_minimum_single(xm0, xl0, xr0, xmin, xmax, factor, a).ravel() + args = tuple(xp.asarray(arg, dtype=xp.float64) for arg in args) + res = _bracket_minimum(f, xp.asarray(xm0), xl0=xl0, xr0=xr0, xmin=xmin, + xmax=xmax, factor=factor, args=args, maxiter=maxiter) + + attrs = ['xl', 'xm', 'xr', 'fl', 'fm', 'fr', 'success', 'nfev', 'nit'] + for attr in attrs: + ref_attr = [xp.asarray(getattr(ref, attr)) for ref in refs] + res_attr = getattr(res, attr) + xp_assert_close(xp_ravel(res_attr, xp=xp), xp.stack(ref_attr)) + xp_assert_equal(res_attr.shape, shape) + + xp_test = array_namespace(xp.asarray(1.)) + assert res.success.dtype == xp_test.bool + if shape: + assert xp.all(res.success[1:-1]) + assert res.status.dtype == xp.int32 + assert res.nfev.dtype == xp.int32 + assert res.nit.dtype == xp.int32 + assert xp.max(res.nit) == f.count - 3 + self.assert_valid_bracket(res, xp) + xp_assert_close(res.fl, f(res.xl, *args)) + xp_assert_close(res.fm, f(res.xm, *args)) + xp_assert_close(res.fr, f(res.xr, *args)) + + def test_special_cases(self, xp): + # Test edge cases and other special cases. + xp_test = array_namespace(xp.asarray(1.)) + + # Test that integers are not passed to `f` + # (otherwise this would overflow) + def f(x): + assert xp_test.isdtype(x.dtype, "numeric") + return x ** 98 - 1 + + result = _bracket_minimum(f, xp.asarray(-7., dtype=xp.float64), xr0=5) + assert result.success + + # Test maxiter = 0. Should do nothing to bracket. + def f(x): + return x**2 - 10 + + xl0, xm0, xr0 = xp.asarray(-3.), xp.asarray(-1.), xp.asarray(2.) + result = _bracket_minimum(f, xm0, xl0=xl0, xr0=xr0, maxiter=0) + xp_assert_equal(result.xl, xl0) + xp_assert_equal(result.xm, xm0) + xp_assert_equal(result.xr, xr0) + + # Test scalar `args` (not in tuple) + def f(x, c): + return c*x**2 - 1 + + result = _bracket_minimum(f, xp.asarray(-1.), args=xp.asarray(3.)) + assert result.success + xp_assert_close(result.fl, f(result.xl, 3)) + + # Initial bracket is valid. + f = self.init_f() + xl0, xm0, xr0 = xp.asarray(-1.0), xp.asarray(-0.2), xp.asarray(1.0) + args = (xp.asarray(0.), xp.asarray(0.)) + result = _bracket_minimum(f, xm0, xl0=xl0, xr0=xr0, args=args) + assert f.count == 3 + + xp_assert_equal(result.xl, xl0) + xp_assert_equal(result.xm , xm0) + xp_assert_equal(result.xr, xr0) + xp_assert_equal(result.fl, f(xl0, *args)) + xp_assert_equal(result.fm, f(xm0, *args)) + xp_assert_equal(result.fr, f(xr0, *args)) + + def test_gh_20562_left(self, xp): + # Regression test for https://github.com/scipy/scipy/issues/20562 + # minimum of f in [xmin, xmax] is at xmin. + xmin, xmax = xp.asarray(0.21933608), xp.asarray(1.39713606) + + def f(x): + log_a, log_b = xp.log(xmin), xp.log(xmax) + return -((log_b - log_a)*x)**-1 + + result = _bracket_minimum(f, xp.asarray(0.5535723499480897), xmin=xmin, + xmax=xmax) + assert xmin == result.xl + + def test_gh_20562_right(self, xp): + # Regression test for https://github.com/scipy/scipy/issues/20562 + # minimum of f in [xmin, xmax] is at xmax. + xmin, xmax = xp.asarray(-1.39713606), xp.asarray(-0.21933608) + + def f(x): + log_a, log_b = xp.log(-xmax), xp.log(-xmin) + return ((log_b - log_a)*x)**-1 + + result = _bracket_minimum(f, xp.asarray(-0.5535723499480897), + xmin=xmin, xmax=xmax) + assert xmax == result.xr diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_chandrupatla.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_chandrupatla.py new file mode 100644 index 0000000000000000000000000000000000000000..bcc2ae1a70be2883a3d2346a1cb8d95d8ac027fa --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_chandrupatla.py @@ -0,0 +1,984 @@ +import math +import pytest +import numpy as np + +from scipy import stats, special +import scipy._lib._elementwise_iterative_method as eim +from scipy.conftest import array_api_compatible +from scipy._lib._array_api import array_namespace, is_cupy, is_numpy, xp_ravel, xp_size +from scipy._lib._array_api_no_0d import (xp_assert_close, xp_assert_equal, + xp_assert_less) + +from scipy.optimize.elementwise import find_minimum, find_root +from scipy.optimize._tstutils import _CHANDRUPATLA_TESTS + +from itertools import permutations +from .test_zeros import TestScalarRootFinders + + +def _vectorize(xp): + # xp-compatible version of np.vectorize + # assumes arguments are all arrays of the same shape + def decorator(f): + def wrapped(*arg_arrays): + shape = arg_arrays[0].shape + arg_arrays = [xp_ravel(arg_array, xp=xp) for arg_array in arg_arrays] + res = [] + for i in range(math.prod(shape)): + arg_scalars = [arg_array[i] for arg_array in arg_arrays] + res.append(f(*arg_scalars)) + return res + + return wrapped + + return decorator + + +# These tests were originally written for the private `optimize._chandrupatla` +# interfaces, but now we want the tests to check the behavior of the public +# `optimize.elementwise` interfaces. Therefore, rather than importing +# `_chandrupatla`/`_chandrupatla_minimize` from `_chandrupatla.py`, we import +# `find_root`/`find_minimum` from `optimize.elementwise` and wrap those +# functions to conform to the private interface. This may look a little strange, +# since it effectively just inverts the interface transformation done within the +# `find_root`/`find_minimum` functions, but it allows us to run the original, +# unmodified tests on the public interfaces, simplifying the PR that adds +# the public interfaces. We'll refactor this when we want to @parametrize the +# tests over multiple `method`s. +def _wrap_chandrupatla(func): + def _chandrupatla_wrapper(f, *bracket, **kwargs): + # avoid passing arguments to `find_minimum` to this function + tol_keys = {'xatol', 'xrtol', 'fatol', 'frtol'} + tolerances = {key: kwargs.pop(key) for key in tol_keys if key in kwargs} + _callback = kwargs.pop('callback', None) + if callable(_callback): + def callback(res): + if func == find_root: + res.xl, res.xr = res.bracket + res.fl, res.fr = res.f_bracket + else: + res.xl, res.xm, res.xr = res.bracket + res.fl, res.fm, res.fr = res.f_bracket + res.fun = res.f_x + del res.bracket + del res.f_bracket + del res.f_x + return _callback(res) + else: + callback = _callback + + res = func(f, bracket, tolerances=tolerances, callback=callback, **kwargs) + if func == find_root: + res.xl, res.xr = res.bracket + res.fl, res.fr = res.f_bracket + else: + res.xl, res.xm, res.xr = res.bracket + res.fl, res.fm, res.fr = res.f_bracket + res.fun = res.f_x + del res.bracket + del res.f_bracket + del res.f_x + return res + return _chandrupatla_wrapper + + +_chandrupatla_root = _wrap_chandrupatla(find_root) +_chandrupatla_minimize = _wrap_chandrupatla(find_minimum) + + +def f1(x): + return 100*(1 - x**3.)**2 + (1-x**2.) + 2*(1-x)**2. + + +def f2(x): + return 5 + (x - 2.)**6 + + +def f3(x): + xp = array_namespace(x) + return xp.exp(x) - 5*x + + +def f4(x): + return x**5. - 5*x**3. - 20.*x + 5. + + +def f5(x): + return 8*x**3 - 2*x**2 - 7*x + 3 + + +def _bracket_minimum(func, x1, x2): + phi = 1.61803398875 + maxiter = 100 + f1 = func(x1) + f2 = func(x2) + step = x2 - x1 + x1, x2, f1, f2, step = ((x2, x1, f2, f1, -step) if f2 > f1 + else (x1, x2, f1, f2, step)) + + for i in range(maxiter): + step *= phi + x3 = x2 + step + f3 = func(x3) + if f3 < f2: + x1, x2, f1, f2 = x2, x3, f2, f3 + else: + break + return x1, x2, x3, f1, f2, f3 + + +cases = [ + (f1, -1, 11), + (f1, -2, 13), + (f1, -4, 13), + (f1, -8, 15), + (f1, -16, 16), + (f1, -32, 19), + (f1, -64, 20), + (f1, -128, 21), + (f1, -256, 21), + (f1, -512, 19), + (f1, -1024, 24), + (f2, -1, 8), + (f2, -2, 6), + (f2, -4, 6), + (f2, -8, 7), + (f2, -16, 8), + (f2, -32, 8), + (f2, -64, 9), + (f2, -128, 11), + (f2, -256, 13), + (f2, -512, 12), + (f2, -1024, 13), + (f3, -1, 11), + (f3, -2, 11), + (f3, -4, 11), + (f3, -8, 10), + (f3, -16, 14), + (f3, -32, 12), + (f3, -64, 15), + (f3, -128, 18), + (f3, -256, 18), + (f3, -512, 19), + (f3, -1024, 19), + (f4, -0.05, 9), + (f4, -0.10, 11), + (f4, -0.15, 11), + (f4, -0.20, 11), + (f4, -0.25, 11), + (f4, -0.30, 9), + (f4, -0.35, 9), + (f4, -0.40, 9), + (f4, -0.45, 10), + (f4, -0.50, 10), + (f4, -0.55, 10), + (f5, -0.05, 6), + (f5, -0.10, 7), + (f5, -0.15, 8), + (f5, -0.20, 10), + (f5, -0.25, 9), + (f5, -0.30, 8), + (f5, -0.35, 7), + (f5, -0.40, 7), + (f5, -0.45, 9), + (f5, -0.50, 9), + (f5, -0.55, 8) +] + + +@array_api_compatible +@pytest.mark.usefixtures("skip_xp_backends") +@pytest.mark.skip_xp_backends('jax.numpy', + reason='JAX arrays do not support item assignment.') +@pytest.mark.skip_xp_backends('array_api_strict', + reason='Currently uses fancy indexing assignment.') +class TestChandrupatlaMinimize: + + def f(self, x, loc): + xp = array_namespace(x, loc) + res = -xp.exp(-1/2 * (x-loc)**2) / (2*xp.pi)**0.5 + return xp.asarray(res, dtype=x.dtype)[()] + + @pytest.mark.parametrize('dtype', ('float32', 'float64')) + @pytest.mark.parametrize('loc', [0.6, np.linspace(-1.05, 1.05, 10)]) + def test_basic(self, loc, xp, dtype): + # Find mode of normal distribution. Compare mode against location + # parameter and value of pdf at mode against expected pdf. + rtol = {'float32': 5e-3, 'float64': 5e-7}[dtype] + dtype = getattr(xp, dtype) + bracket = (xp.asarray(xi, dtype=dtype) for xi in (-5, 0, 5)) + loc = xp.asarray(loc, dtype=dtype) + fun = xp.broadcast_to(xp.asarray(-stats.norm.pdf(0), dtype=dtype), loc.shape) + + res = _chandrupatla_minimize(self.f, *bracket, args=(loc,)) + xp_assert_close(res.x, loc, rtol=rtol) + xp_assert_equal(res.fun, fun) + + @pytest.mark.parametrize('shape', [tuple(), (12,), (3, 4), (3, 2, 2)]) + def test_vectorization(self, shape, xp): + # Test for correct functionality, output shapes, and dtypes for various + # input shapes. + loc = xp.linspace(-0.05, 1.05, 12).reshape(shape) if shape else xp.asarray(0.6) + args = (loc,) + bracket = xp.asarray(-5.), xp.asarray(0.), xp.asarray(5.) + xp_test = array_namespace(loc) # need xp.stack + + @_vectorize(xp) + def chandrupatla_single(loc_single): + return _chandrupatla_minimize(self.f, *bracket, args=(loc_single,)) + + def f(*args, **kwargs): + f.f_evals += 1 + return self.f(*args, **kwargs) + f.f_evals = 0 + + res = _chandrupatla_minimize(f, *bracket, args=args) + refs = chandrupatla_single(loc) + + attrs = ['x', 'fun', 'success', 'status', 'nfev', 'nit', + 'xl', 'xm', 'xr', 'fl', 'fm', 'fr'] + for attr in attrs: + ref_attr = xp_test.stack([getattr(ref, attr) for ref in refs]) + res_attr = xp_ravel(getattr(res, attr)) + xp_assert_equal(res_attr, ref_attr) + assert getattr(res, attr).shape == shape + + xp_assert_equal(res.fun, self.f(res.x, *args)) + xp_assert_equal(res.fl, self.f(res.xl, *args)) + xp_assert_equal(res.fm, self.f(res.xm, *args)) + xp_assert_equal(res.fr, self.f(res.xr, *args)) + assert xp.max(res.nfev) == f.f_evals + assert xp.max(res.nit) == f.f_evals - 3 + + assert xp_test.isdtype(res.success.dtype, 'bool') + assert xp_test.isdtype(res.status.dtype, 'integral') + assert xp_test.isdtype(res.nfev.dtype, 'integral') + assert xp_test.isdtype(res.nit.dtype, 'integral') + + + def test_flags(self, xp): + # Test cases that should produce different status flags; show that all + # can be produced simultaneously. + def f(xs, js): + funcs = [lambda x: (x - 2.5) ** 2, + lambda x: x - 10, + lambda x: (x - 2.5) ** 4, + lambda x: xp.full_like(x, xp.asarray(xp.nan))] + res = [] + for i in range(xp_size(js)): + x = xs[i, ...] + j = int(xp_ravel(js)[i]) + res.append(funcs[j](x)) + return xp.stack(res) + + args = (xp.arange(4, dtype=xp.int64),) + bracket = (xp.asarray([0]*4, dtype=xp.float64), + xp.asarray([2]*4, dtype=xp.float64), + xp.asarray([np.pi]*4, dtype=xp.float64)) + res = _chandrupatla_minimize(f, *bracket, args=args, maxiter=10) + + ref_flags = xp.asarray([eim._ECONVERGED, eim._ESIGNERR, eim._ECONVERR, + eim._EVALUEERR], dtype=xp.int32) + xp_assert_equal(res.status, ref_flags) + + def test_convergence(self, xp): + # Test that the convergence tolerances behave as expected + rng = np.random.default_rng(2585255913088665241) + p = xp.asarray(rng.random(size=3)) + bracket = (xp.asarray(-5), xp.asarray(0), xp.asarray(5)) + args = (p,) + kwargs0 = dict(args=args, xatol=0, xrtol=0, fatol=0, frtol=0) + + kwargs = kwargs0.copy() + kwargs['xatol'] = 1e-3 + res1 = _chandrupatla_minimize(self.f, *bracket, **kwargs) + j1 = xp.abs(res1.xr - res1.xl) + tol = xp.asarray(4*kwargs['xatol'], dtype=p.dtype) + xp_assert_less(j1, xp.full((3,), tol, dtype=p.dtype)) + kwargs['xatol'] = 1e-6 + res2 = _chandrupatla_minimize(self.f, *bracket, **kwargs) + j2 = xp.abs(res2.xr - res2.xl) + tol = xp.asarray(4*kwargs['xatol'], dtype=p.dtype) + xp_assert_less(j2, xp.full((3,), tol, dtype=p.dtype)) + xp_assert_less(j2, j1) + + kwargs = kwargs0.copy() + kwargs['xrtol'] = 1e-3 + res1 = _chandrupatla_minimize(self.f, *bracket, **kwargs) + j1 = xp.abs(res1.xr - res1.xl) + tol = xp.asarray(4*kwargs['xrtol']*xp.abs(res1.x), dtype=p.dtype) + xp_assert_less(j1, tol) + kwargs['xrtol'] = 1e-6 + res2 = _chandrupatla_minimize(self.f, *bracket, **kwargs) + j2 = xp.abs(res2.xr - res2.xl) + tol = xp.asarray(4*kwargs['xrtol']*xp.abs(res2.x), dtype=p.dtype) + xp_assert_less(j2, tol) + xp_assert_less(j2, j1) + + kwargs = kwargs0.copy() + kwargs['fatol'] = 1e-3 + res1 = _chandrupatla_minimize(self.f, *bracket, **kwargs) + h1 = xp.abs(res1.fl - 2 * res1.fm + res1.fr) + tol = xp.asarray(2*kwargs['fatol'], dtype=p.dtype) + xp_assert_less(h1, xp.full((3,), tol, dtype=p.dtype)) + kwargs['fatol'] = 1e-6 + res2 = _chandrupatla_minimize(self.f, *bracket, **kwargs) + h2 = xp.abs(res2.fl - 2 * res2.fm + res2.fr) + tol = xp.asarray(2*kwargs['fatol'], dtype=p.dtype) + xp_assert_less(h2, xp.full((3,), tol, dtype=p.dtype)) + xp_assert_less(h2, h1) + + kwargs = kwargs0.copy() + kwargs['frtol'] = 1e-3 + res1 = _chandrupatla_minimize(self.f, *bracket, **kwargs) + h1 = xp.abs(res1.fl - 2 * res1.fm + res1.fr) + tol = xp.asarray(2*kwargs['frtol']*xp.abs(res1.fun), dtype=p.dtype) + xp_assert_less(h1, tol) + kwargs['frtol'] = 1e-6 + res2 = _chandrupatla_minimize(self.f, *bracket, **kwargs) + h2 = xp.abs(res2.fl - 2 * res2.fm + res2.fr) + tol = xp.asarray(2*kwargs['frtol']*abs(res2.fun), dtype=p.dtype) + xp_assert_less(h2, tol) + xp_assert_less(h2, h1) + + def test_maxiter_callback(self, xp): + # Test behavior of `maxiter` parameter and `callback` interface + loc = xp.asarray(0.612814) + bracket = (xp.asarray(-5), xp.asarray(0), xp.asarray(5)) + maxiter = 5 + + res = _chandrupatla_minimize(self.f, *bracket, args=(loc,), + maxiter=maxiter) + assert not xp.any(res.success) + assert xp.all(res.nfev == maxiter+3) + assert xp.all(res.nit == maxiter) + + def callback(res): + callback.iter += 1 + callback.res = res + assert hasattr(res, 'x') + if callback.iter == 0: + # callback is called once with initial bracket + assert (res.xl, res.xm, res.xr) == bracket + else: + changed_xr = (res.xl == callback.xl) & (res.xr != callback.xr) + changed_xl = (res.xl != callback.xl) & (res.xr == callback.xr) + assert xp.all(changed_xr | changed_xl) + + callback.xl = res.xl + callback.xr = res.xr + assert res.status == eim._EINPROGRESS + xp_assert_equal(self.f(res.xl, loc), res.fl) + xp_assert_equal(self.f(res.xm, loc), res.fm) + xp_assert_equal(self.f(res.xr, loc), res.fr) + xp_assert_equal(self.f(res.x, loc), res.fun) + if callback.iter == maxiter: + raise StopIteration + + callback.xl = xp.nan + callback.xr = xp.nan + callback.iter = -1 # callback called once before first iteration + callback.res = None + + res2 = _chandrupatla_minimize(self.f, *bracket, args=(loc,), + callback=callback) + + # terminating with callback is identical to terminating due to maxiter + # (except for `status`) + for key in res.keys(): + if key == 'status': + assert res[key] == eim._ECONVERR + # assert callback.res[key] == eim._EINPROGRESS + assert res2[key] == eim._ECALLBACK + else: + assert res2[key] == callback.res[key] == res[key] + + @pytest.mark.parametrize('case', cases) + def test_nit_expected(self, case, xp): + # Test that `_chandrupatla` implements Chandrupatla's algorithm: + # in all 55 test cases, the number of iterations performed + # matches the number reported in the original paper. + func, x1, nit = case + + # Find bracket using the algorithm in the paper + step = 0.2 + x2 = x1 + step + x1, x2, x3, f1, f2, f3 = _bracket_minimum(func, x1, x2) + + # Use tolerances from original paper + xatol = 0.0001 + fatol = 0.000001 + xrtol = 1e-16 + frtol = 1e-16 + + bracket = xp.asarray(x1), xp.asarray(x2), xp.asarray(x3, dtype=xp.float64) + res = _chandrupatla_minimize(func, *bracket, xatol=xatol, + fatol=fatol, xrtol=xrtol, frtol=frtol) + xp_assert_equal(res.nit, xp.asarray(nit, dtype=xp.int32)) + + @pytest.mark.parametrize("loc", (0.65, [0.65, 0.7])) + @pytest.mark.parametrize("dtype", ('float16', 'float32', 'float64')) + def test_dtype(self, loc, dtype, xp): + # Test that dtypes are preserved + dtype = getattr(xp, dtype) + + loc = xp.asarray(loc, dtype=dtype) + bracket = (xp.asarray(-3, dtype=dtype), + xp.asarray(1, dtype=dtype), + xp.asarray(5, dtype=dtype)) + + xp_test = array_namespace(loc) # need astype + def f(x, loc): + assert x.dtype == dtype + return xp_test.astype((x - loc)**2, dtype) + + res = _chandrupatla_minimize(f, *bracket, args=(loc,)) + assert res.x.dtype == dtype + xp_assert_close(res.x, loc, rtol=math.sqrt(xp.finfo(dtype).eps)) + + def test_input_validation(self, xp): + # Test input validation for appropriate error messages + + message = '`func` must be callable.' + bracket = xp.asarray(-4), xp.asarray(0), xp.asarray(4) + with pytest.raises(ValueError, match=message): + _chandrupatla_minimize(None, *bracket) + + message = 'Abscissae and function output must be real numbers.' + bracket = xp.asarray(-4 + 1j), xp.asarray(0), xp.asarray(4) + with pytest.raises(ValueError, match=message): + _chandrupatla_minimize(lambda x: x, *bracket) + + message = "...be broadcast..." + bracket = xp.asarray([-2, -3]), xp.asarray([0, 0]), xp.asarray([3, 4, 5]) + # raised by `np.broadcast, but the traceback is readable IMO + with pytest.raises((ValueError, RuntimeError), match=message): + _chandrupatla_minimize(lambda x: x, *bracket) + + message = "The shape of the array returned by `func` must be the same" + bracket = xp.asarray([-3, -3]), xp.asarray([0, 0]), xp.asarray([5, 5]) + with pytest.raises(ValueError, match=message): + _chandrupatla_minimize(lambda x: [x[0, ...], x[1, ...], x[1, ...]], + *bracket) + + message = 'Tolerances must be non-negative scalars.' + bracket = xp.asarray(-4), xp.asarray(0), xp.asarray(4) + with pytest.raises(ValueError, match=message): + _chandrupatla_minimize(lambda x: x, *bracket, xatol=-1) + with pytest.raises(ValueError, match=message): + _chandrupatla_minimize(lambda x: x, *bracket, xrtol=xp.nan) + with pytest.raises(ValueError, match=message): + _chandrupatla_minimize(lambda x: x, *bracket, fatol='ekki') + with pytest.raises(ValueError, match=message): + _chandrupatla_minimize(lambda x: x, *bracket, frtol=xp.nan) + + message = '`maxiter` must be a non-negative integer.' + with pytest.raises(ValueError, match=message): + _chandrupatla_minimize(lambda x: x, *bracket, maxiter=1.5) + with pytest.raises(ValueError, match=message): + _chandrupatla_minimize(lambda x: x, *bracket, maxiter=-1) + + message = '`callback` must be callable.' + with pytest.raises(ValueError, match=message): + _chandrupatla_minimize(lambda x: x, *bracket, callback='shrubbery') + + def test_bracket_order(self, xp): + # Confirm that order of points in bracket doesn't + xp_test = array_namespace(xp.asarray(1.)) # need `xp.newaxis` + loc = xp.linspace(-1, 1, 6)[:, xp_test.newaxis] + brackets = xp.asarray(list(permutations([-5, 0, 5]))).T + res = _chandrupatla_minimize(self.f, *brackets, args=(loc,)) + assert xp.all(xp.isclose(res.x, loc) | (res.fun == self.f(loc, loc))) + ref = res.x[:, 0] # all columns should be the same + xp_test = array_namespace(loc) # need `xp.broadcast_arrays + xp_assert_close(*xp_test.broadcast_arrays(res.x.T, ref), rtol=1e-15) + + def test_special_cases(self, xp): + # Test edge cases and other special cases + + # Test that integers are not passed to `f` + xp_test = array_namespace(xp.asarray(1.)) # need `xp.isdtype` + def f(x): + assert xp_test.isdtype(x.dtype, "real floating") + return (x - 1)**2 + + bracket = xp.asarray(-7), xp.asarray(0), xp.asarray(8) + with np.errstate(invalid='ignore'): + res = _chandrupatla_minimize(f, *bracket, fatol=0, frtol=0) + assert res.success + xp_assert_close(res.x, xp.asarray(1.), rtol=1e-3) + xp_assert_close(res.fun, xp.asarray(0.), atol=1e-200) + + # Test that if all elements of bracket equal minimizer, algorithm + # reports convergence + def f(x): + return (x-1)**2 + + bracket = xp.asarray(1), xp.asarray(1), xp.asarray(1) + res = _chandrupatla_minimize(f, *bracket) + assert res.success + xp_assert_equal(res.x, xp.asarray(1.)) + + # Test maxiter = 0. Should do nothing to bracket. + def f(x): + return (x-1)**2 + + bracket = xp.asarray(-3), xp.asarray(1.1), xp.asarray(5) + res = _chandrupatla_minimize(f, *bracket, maxiter=0) + assert res.xl, res.xr == bracket + assert res.nit == 0 + assert res.nfev == 3 + assert res.status == -2 + assert res.x == 1.1 # best so far + + # Test scalar `args` (not in tuple) + def f(x, c): + return (x-c)**2 - 1 + + bracket = xp.asarray(-1), xp.asarray(0), xp.asarray(1) + c = xp.asarray(1/3) + res = _chandrupatla_minimize(f, *bracket, args=(c,)) + xp_assert_close(res.x, c) + + # Test zero tolerances + def f(x): + return -xp.sin(x) + + bracket = xp.asarray(0), xp.asarray(1), xp.asarray(xp.pi) + res = _chandrupatla_minimize(f, *bracket, xatol=0, xrtol=0, fatol=0, frtol=0) + assert res.success + # found a minimum exactly (according to floating point arithmetic) + assert res.xl < res.xm < res.xr + assert f(res.xl) == f(res.xm) == f(res.xr) + + +@array_api_compatible +@pytest.mark.usefixtures("skip_xp_backends") +@pytest.mark.skip_xp_backends('array_api_strict', + reason='Currently uses fancy indexing assignment.') +@pytest.mark.skip_xp_backends('jax.numpy', + reason='JAX arrays do not support item assignment.') +@pytest.mark.skip_xp_backends('cupy', + reason='cupy/cupy#8391') +class TestChandrupatla(TestScalarRootFinders): + + def f(self, q, p): + return special.ndtr(q) - p + + @pytest.mark.parametrize('p', [0.6, np.linspace(-0.05, 1.05, 10)]) + def test_basic(self, p, xp): + # Invert distribution CDF and compare against distribution `ppf` + a, b = xp.asarray(-5.), xp.asarray(5.) + res = _chandrupatla_root(self.f, a, b, args=(xp.asarray(p),)) + ref = xp.asarray(stats.norm().ppf(p), dtype=xp.asarray(p).dtype) + xp_assert_close(res.x, ref) + + @pytest.mark.parametrize('shape', [tuple(), (12,), (3, 4), (3, 2, 2)]) + def test_vectorization(self, shape, xp): + # Test for correct functionality, output shapes, and dtypes for various + # input shapes. + p = (np.linspace(-0.05, 1.05, 12).reshape(shape) if shape + else np.float64(0.6)) + p_xp = xp.asarray(p) + args_xp = (p_xp,) + dtype = p_xp.dtype + xp_test = array_namespace(p_xp) # need xp.bool + + @np.vectorize + def chandrupatla_single(p): + return _chandrupatla_root(self.f, -5, 5, args=(p,)) + + def f(*args, **kwargs): + f.f_evals += 1 + return self.f(*args, **kwargs) + f.f_evals = 0 + + res = _chandrupatla_root(f, xp.asarray(-5.), xp.asarray(5.), args=args_xp) + refs = chandrupatla_single(p).ravel() + + ref_x = [ref.x for ref in refs] + ref_x = xp.reshape(xp.asarray(ref_x, dtype=dtype), shape) + xp_assert_close(res.x, ref_x) + + ref_fun = [ref.fun for ref in refs] + ref_fun = xp.reshape(xp.asarray(ref_fun, dtype=dtype), shape) + xp_assert_close(res.fun, ref_fun, atol=1e-15) + xp_assert_equal(res.fun, self.f(res.x, *args_xp)) + + ref_success = [bool(ref.success) for ref in refs] + ref_success = xp.reshape(xp.asarray(ref_success, dtype=xp_test.bool), shape) + xp_assert_equal(res.success, ref_success) + + ref_flag = [ref.status for ref in refs] + ref_flag = xp.reshape(xp.asarray(ref_flag, dtype=xp.int32), shape) + xp_assert_equal(res.status, ref_flag) + + ref_nfev = [ref.nfev for ref in refs] + ref_nfev = xp.reshape(xp.asarray(ref_nfev, dtype=xp.int32), shape) + if is_numpy(xp): + xp_assert_equal(res.nfev, ref_nfev) + assert xp.max(res.nfev) == f.f_evals + else: # different backend may lead to different nfev + assert res.nfev.shape == shape + assert res.nfev.dtype == xp.int32 + + ref_nit = [ref.nit for ref in refs] + ref_nit = xp.reshape(xp.asarray(ref_nit, dtype=xp.int32), shape) + if is_numpy(xp): + xp_assert_equal(res.nit, ref_nit) + assert xp.max(res.nit) == f.f_evals-2 + else: + assert res.nit.shape == shape + assert res.nit.dtype == xp.int32 + + ref_xl = [ref.xl for ref in refs] + ref_xl = xp.reshape(xp.asarray(ref_xl, dtype=dtype), shape) + xp_assert_close(res.xl, ref_xl) + + ref_xr = [ref.xr for ref in refs] + ref_xr = xp.reshape(xp.asarray(ref_xr, dtype=dtype), shape) + xp_assert_close(res.xr, ref_xr) + + xp_assert_less(res.xl, res.xr) + finite = xp.isfinite(res.x) + assert xp.all((res.x[finite] == res.xl[finite]) + | (res.x[finite] == res.xr[finite])) + + # PyTorch and CuPy don't solve to the same accuracy as NumPy - that's OK. + atol = 1e-15 if is_numpy(xp) else 1e-9 + + ref_fl = [ref.fl for ref in refs] + ref_fl = xp.reshape(xp.asarray(ref_fl, dtype=dtype), shape) + xp_assert_close(res.fl, ref_fl, atol=atol) + xp_assert_equal(res.fl, self.f(res.xl, *args_xp)) + + ref_fr = [ref.fr for ref in refs] + ref_fr = xp.reshape(xp.asarray(ref_fr, dtype=dtype), shape) + xp_assert_close(res.fr, ref_fr, atol=atol) + xp_assert_equal(res.fr, self.f(res.xr, *args_xp)) + + assert xp.all(xp.abs(res.fun[finite]) == + xp.minimum(xp.abs(res.fl[finite]), + xp.abs(res.fr[finite]))) + + def test_flags(self, xp): + # Test cases that should produce different status flags; show that all + # can be produced simultaneously. + def f(xs, js): + # Note that full_like and int(j) shouldn't really be required. CuPy + # is just really picky here, so I'm making it a special case to + # make sure the other backends work when the user is less careful. + assert js.dtype == xp.int64 + if is_cupy(xp): + funcs = [lambda x: x - 2.5, + lambda x: x - 10, + lambda x: (x - 0.1)**3, + lambda x: xp.full_like(x, xp.asarray(xp.nan))] + return [funcs[int(j)](x) for x, j in zip(xs, js)] + + funcs = [lambda x: x - 2.5, + lambda x: x - 10, + lambda x: (x - 0.1) ** 3, + lambda x: xp.nan] + return [funcs[j](x) for x, j in zip(xs, js)] + + args = (xp.arange(4, dtype=xp.int64),) + a, b = xp.asarray([0.]*4), xp.asarray([xp.pi]*4) + res = _chandrupatla_root(f, a, b, args=args, maxiter=2) + + ref_flags = xp.asarray([eim._ECONVERGED, + eim._ESIGNERR, + eim._ECONVERR, + eim._EVALUEERR], dtype=xp.int32) + xp_assert_equal(res.status, ref_flags) + + def test_convergence(self, xp): + # Test that the convergence tolerances behave as expected + rng = np.random.default_rng(2585255913088665241) + p = xp.asarray(rng.random(size=3)) + bracket = (-xp.asarray(5.), xp.asarray(5.)) + args = (p,) + kwargs0 = dict(args=args, xatol=0, xrtol=0, fatol=0, frtol=0) + + kwargs = kwargs0.copy() + kwargs['xatol'] = 1e-3 + res1 = _chandrupatla_root(self.f, *bracket, **kwargs) + xp_assert_less(res1.xr - res1.xl, xp.full_like(p, xp.asarray(1e-3))) + kwargs['xatol'] = 1e-6 + res2 = _chandrupatla_root(self.f, *bracket, **kwargs) + xp_assert_less(res2.xr - res2.xl, xp.full_like(p, xp.asarray(1e-6))) + xp_assert_less(res2.xr - res2.xl, res1.xr - res1.xl) + + kwargs = kwargs0.copy() + kwargs['xrtol'] = 1e-3 + res1 = _chandrupatla_root(self.f, *bracket, **kwargs) + xp_assert_less(res1.xr - res1.xl, 1e-3 * xp.abs(res1.x)) + kwargs['xrtol'] = 1e-6 + res2 = _chandrupatla_root(self.f, *bracket, **kwargs) + xp_assert_less(res2.xr - res2.xl, 1e-6 * xp.abs(res2.x)) + xp_assert_less(res2.xr - res2.xl, res1.xr - res1.xl) + + kwargs = kwargs0.copy() + kwargs['fatol'] = 1e-3 + res1 = _chandrupatla_root(self.f, *bracket, **kwargs) + xp_assert_less(xp.abs(res1.fun), xp.full_like(p, xp.asarray(1e-3))) + kwargs['fatol'] = 1e-6 + res2 = _chandrupatla_root(self.f, *bracket, **kwargs) + xp_assert_less(xp.abs(res2.fun), xp.full_like(p, xp.asarray(1e-6))) + xp_assert_less(xp.abs(res2.fun), xp.abs(res1.fun)) + + kwargs = kwargs0.copy() + kwargs['frtol'] = 1e-3 + x1, x2 = bracket + f0 = xp.minimum(xp.abs(self.f(x1, *args)), xp.abs(self.f(x2, *args))) + res1 = _chandrupatla_root(self.f, *bracket, **kwargs) + xp_assert_less(xp.abs(res1.fun), 1e-3*f0) + kwargs['frtol'] = 1e-6 + res2 = _chandrupatla_root(self.f, *bracket, **kwargs) + xp_assert_less(xp.abs(res2.fun), 1e-6*f0) + xp_assert_less(xp.abs(res2.fun), xp.abs(res1.fun)) + + def test_maxiter_callback(self, xp): + # Test behavior of `maxiter` parameter and `callback` interface + p = xp.asarray(0.612814) + bracket = (xp.asarray(-5.), xp.asarray(5.)) + maxiter = 5 + + def f(q, p): + res = special.ndtr(q) - p + f.x = q + f.fun = res + return res + f.x = None + f.fun = None + + res = _chandrupatla_root(f, *bracket, args=(p,), maxiter=maxiter) + assert not xp.any(res.success) + assert xp.all(res.nfev == maxiter+2) + assert xp.all(res.nit == maxiter) + + def callback(res): + callback.iter += 1 + callback.res = res + assert hasattr(res, 'x') + if callback.iter == 0: + # callback is called once with initial bracket + assert (res.xl, res.xr) == bracket + else: + changed = (((res.xl == callback.xl) & (res.xr != callback.xr)) + | ((res.xl != callback.xl) & (res.xr == callback.xr))) + assert xp.all(changed) + + callback.xl = res.xl + callback.xr = res.xr + assert res.status == eim._EINPROGRESS + xp_assert_equal(self.f(res.xl, p), res.fl) + xp_assert_equal(self.f(res.xr, p), res.fr) + xp_assert_equal(self.f(res.x, p), res.fun) + if callback.iter == maxiter: + raise StopIteration + callback.iter = -1 # callback called once before first iteration + callback.res = None + callback.xl = None + callback.xr = None + + res2 = _chandrupatla_root(f, *bracket, args=(p,), callback=callback) + + # terminating with callback is identical to terminating due to maxiter + # (except for `status`) + for key in res.keys(): + if key == 'status': + xp_assert_equal(res[key], xp.asarray(eim._ECONVERR, dtype=xp.int32)) + xp_assert_equal(res2[key], xp.asarray(eim._ECALLBACK, dtype=xp.int32)) + elif key.startswith('_'): + continue + else: + xp_assert_equal(res2[key], res[key]) + + @pytest.mark.parametrize('case', _CHANDRUPATLA_TESTS) + def test_nit_expected(self, case, xp): + # Test that `_chandrupatla` implements Chandrupatla's algorithm: + # in all 40 test cases, the number of iterations performed + # matches the number reported in the original paper. + f, bracket, root, nfeval, id = case + # Chandrupatla's criterion is equivalent to + # abs(x2-x1) < 4*abs(xmin)*xrtol + xatol, but we use the more standard + # abs(x2-x1) < abs(xmin)*xrtol + xatol. Therefore, set xrtol to 4x + # that used by Chandrupatla in tests. + bracket = (xp.asarray(bracket[0], dtype=xp.float64), + xp.asarray(bracket[1], dtype=xp.float64)) + root = xp.asarray(root, dtype=xp.float64) + + res = _chandrupatla_root(f, *bracket, xrtol=4e-10, xatol=1e-5) + xp_assert_close(res.fun, xp.asarray(f(root), dtype=xp.float64), + rtol=1e-8, atol=2e-3) + xp_assert_equal(res.nfev, xp.asarray(nfeval, dtype=xp.int32)) + + @pytest.mark.parametrize("root", (0.622, [0.622, 0.623])) + @pytest.mark.parametrize("dtype", ('float16', 'float32', 'float64')) + def test_dtype(self, root, dtype, xp): + # Test that dtypes are preserved + not_numpy = not is_numpy(xp) + if not_numpy and dtype == 'float16': + pytest.skip("`float16` dtype only supported for NumPy arrays.") + + dtype = getattr(xp, dtype, None) + if dtype is None: + pytest.skip(f"{xp} does not support {dtype}") + + def f(x, root): + res = (x - root) ** 3. + if is_numpy(xp): # NumPy does not preserve dtype + return xp.asarray(res, dtype=dtype) + return res + + a, b = xp.asarray(-3, dtype=dtype), xp.asarray(3, dtype=dtype) + root = xp.asarray(root, dtype=dtype) + res = _chandrupatla_root(f, a, b, args=(root,), xatol=1e-3) + try: + xp_assert_close(res.x, root, atol=1e-3) + except AssertionError: + assert res.x.dtype == dtype + xp.all(res.fun == 0) + + def test_input_validation(self, xp): + # Test input validation for appropriate error messages + + def func(x): + return x + + message = '`func` must be callable.' + with pytest.raises(ValueError, match=message): + bracket = xp.asarray(-4), xp.asarray(4) + _chandrupatla_root(None, *bracket) + + message = 'Abscissae and function output must be real numbers.' + with pytest.raises(ValueError, match=message): + bracket = xp.asarray(-4+1j), xp.asarray(4) + _chandrupatla_root(func, *bracket) + + # raised by `np.broadcast, but the traceback is readable IMO + message = "...not be broadcast..." # all messages include this part + with pytest.raises((ValueError, RuntimeError), match=message): + bracket = xp.asarray([-2, -3]), xp.asarray([3, 4, 5]) + _chandrupatla_root(func, *bracket) + + message = "The shape of the array returned by `func`..." + with pytest.raises(ValueError, match=message): + bracket = xp.asarray([-3, -3]), xp.asarray([5, 5]) + _chandrupatla_root(lambda x: [x[0], x[1], x[1]], *bracket) + + message = 'Tolerances must be non-negative scalars.' + bracket = xp.asarray(-4), xp.asarray(4) + with pytest.raises(ValueError, match=message): + _chandrupatla_root(func, *bracket, xatol=-1) + with pytest.raises(ValueError, match=message): + _chandrupatla_root(func, *bracket, xrtol=xp.nan) + with pytest.raises(ValueError, match=message): + _chandrupatla_root(func, *bracket, fatol='ekki') + with pytest.raises(ValueError, match=message): + _chandrupatla_root(func, *bracket, frtol=xp.nan) + + message = '`maxiter` must be a non-negative integer.' + with pytest.raises(ValueError, match=message): + _chandrupatla_root(func, *bracket, maxiter=1.5) + with pytest.raises(ValueError, match=message): + _chandrupatla_root(func, *bracket, maxiter=-1) + + message = '`callback` must be callable.' + with pytest.raises(ValueError, match=message): + _chandrupatla_root(func, *bracket, callback='shrubbery') + + def test_special_cases(self, xp): + # Test edge cases and other special cases + + # Test infinite function values + def f(x): + return 1 / x + 1 - 1 / (-x + 1) + + a, b = xp.asarray([0.1, 0., 0., 0.1]), xp.asarray([0.9, 1.0, 0.9, 1.0]) + + with np.errstate(divide='ignore', invalid='ignore'): + res = _chandrupatla_root(f, a, b) + + assert xp.all(res.success) + xp_assert_close(res.x[1:], xp.full((3,), res.x[0])) + + # Test that integers are not passed to `f` + # (otherwise this would overflow) + xp_test = array_namespace(a) # need isdtype + def f(x): + assert xp_test.isdtype(x.dtype, "real floating") + # this would overflow if x were an xp integer dtype + return x ** 31 - 1 + + # note that all inputs are integer type; result is automatically default float + res = _chandrupatla_root(f, xp.asarray(-7), xp.asarray(5)) + assert res.success + xp_assert_close(res.x, xp.asarray(1.)) + + # Test that if both ends of bracket equal root, algorithm reports + # convergence. + def f(x, root): + return x**2 - root + + root = xp.asarray([0, 1]) + res = _chandrupatla_root(f, xp.asarray(1), xp.asarray(1), args=(root,)) + xp_assert_equal(res.success, xp.asarray([False, True])) + xp_assert_equal(res.x, xp.asarray([xp.nan, 1.])) + + def f(x): + return 1/x + + with np.errstate(invalid='ignore'): + inf = xp.asarray(xp.inf) + res = _chandrupatla_root(f, inf, inf) + assert res.success + xp_assert_equal(res.x, xp.asarray(xp.inf)) + + # Test maxiter = 0. Should do nothing to bracket. + def f(x): + return x**3 - 1 + + a, b = xp.asarray(-3.), xp.asarray(5.) + res = _chandrupatla_root(f, a, b, maxiter=0) + xp_assert_equal(res.success, xp.asarray(False)) + xp_assert_equal(res.status, xp.asarray(-2, dtype=xp.int32)) + xp_assert_equal(res.nit, xp.asarray(0, dtype=xp.int32)) + xp_assert_equal(res.nfev, xp.asarray(2, dtype=xp.int32)) + xp_assert_equal(res.xl, a) + xp_assert_equal(res.xr, b) + # The `x` attribute is the one with the smaller function value + xp_assert_equal(res.x, a) + # Reverse bracket; check that this is still true + res = _chandrupatla_root(f, -b, -a, maxiter=0) + xp_assert_equal(res.x, -a) + + # Test maxiter = 1 + res = _chandrupatla_root(f, a, b, maxiter=1) + xp_assert_equal(res.success, xp.asarray(True)) + xp_assert_equal(res.status, xp.asarray(0, dtype=xp.int32)) + xp_assert_equal(res.nit, xp.asarray(1, dtype=xp.int32)) + xp_assert_equal(res.nfev, xp.asarray(3, dtype=xp.int32)) + xp_assert_close(res.x, xp.asarray(1.)) + + # Test scalar `args` (not in tuple) + def f(x, c): + return c*x - 1 + + res = _chandrupatla_root(f, xp.asarray(-1), xp.asarray(1), args=xp.asarray(3)) + xp_assert_close(res.x, xp.asarray(1/3)) + + # # TODO: Test zero tolerance + # # ~~What's going on here - why are iterations repeated?~~ + # # tl goes to zero when xatol=xrtol=0. When function is nearly linear, + # # this causes convergence issues. + # def f(x): + # return np.cos(x) + # + # res = _chandrupatla_root(f, 0, np.pi, xatol=0, xrtol=0) + # assert res.nit < 100 + # xp = np.nextafter(res.x, np.inf) + # xm = np.nextafter(res.x, -np.inf) + # assert np.abs(res.fun) < np.abs(f(xp)) + # assert np.abs(res.fun) < np.abs(f(xm)) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_cobyla.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_cobyla.py new file mode 100644 index 0000000000000000000000000000000000000000..bd27eb9baa27433d1f801e8582dd2e8d29db3da2 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_cobyla.py @@ -0,0 +1,166 @@ +import math + +import numpy as np +from numpy.testing import assert_allclose, assert_, assert_array_equal +import pytest + +from scipy.optimize import fmin_cobyla, minimize, Bounds + + +class TestCobyla: + def setup_method(self): + self.x0 = [4.95, 0.66] + self.solution = [math.sqrt(25 - (2.0/3)**2), 2.0/3] + self.opts = {'disp': False, 'rhobeg': 1, 'tol': 1e-5, + 'maxiter': 100} + + def fun(self, x): + return x[0]**2 + abs(x[1])**3 + + def con1(self, x): + return x[0]**2 + x[1]**2 - 25 + + def con2(self, x): + return -self.con1(x) + + @pytest.mark.xslow(True, reason='not slow, but noisy so only run rarely') + def test_simple(self, capfd): + # use disp=True as smoke test for gh-8118 + x = fmin_cobyla(self.fun, self.x0, [self.con1, self.con2], rhobeg=1, + rhoend=1e-5, maxfun=100, disp=True) + assert_allclose(x, self.solution, atol=1e-4) + + def test_minimize_simple(self): + class Callback: + def __init__(self): + self.n_calls = 0 + self.last_x = None + + def __call__(self, x): + self.n_calls += 1 + self.last_x = x + + callback = Callback() + + # Minimize with method='COBYLA' + cons = ({'type': 'ineq', 'fun': self.con1}, + {'type': 'ineq', 'fun': self.con2}) + sol = minimize(self.fun, self.x0, method='cobyla', constraints=cons, + callback=callback, options=self.opts) + assert_allclose(sol.x, self.solution, atol=1e-4) + assert_(sol.success, sol.message) + assert_(sol.maxcv < 1e-5, sol) + assert_(sol.nfev < 70, sol) + assert_(sol.fun < self.fun(self.solution) + 1e-3, sol) + assert_(sol.nfev == callback.n_calls, + "Callback is not called exactly once for every function eval.") + assert_array_equal( + sol.x, + callback.last_x, + "Last design vector sent to the callback is not equal to returned value.", + ) + + def test_minimize_constraint_violation(self): + rng = np.random.RandomState(1234) + pb = rng.rand(10, 10) + spread = rng.rand(10) + + def p(w): + return pb.dot(w) + + def f(w): + return -(w * spread).sum() + + def c1(w): + return 500 - abs(p(w)).sum() + + def c2(w): + return 5 - abs(p(w).sum()) + + def c3(w): + return 5 - abs(p(w)).max() + + cons = ({'type': 'ineq', 'fun': c1}, + {'type': 'ineq', 'fun': c2}, + {'type': 'ineq', 'fun': c3}) + w0 = np.zeros((10,)) + sol = minimize(f, w0, method='cobyla', constraints=cons, + options={'catol': 1e-6}) + assert_(sol.maxcv > 1e-6) + assert_(not sol.success) + + +def test_vector_constraints(): + # test that fmin_cobyla and minimize can take a combination + # of constraints, some returning a number and others an array + def fun(x): + return (x[0] - 1)**2 + (x[1] - 2.5)**2 + + def fmin(x): + return fun(x) - 1 + + def cons1(x): + a = np.array([[1, -2, 2], [-1, -2, 6], [-1, 2, 2]]) + return np.array([a[i, 0] * x[0] + a[i, 1] * x[1] + + a[i, 2] for i in range(len(a))]) + + def cons2(x): + return x # identity, acts as bounds x > 0 + + x0 = np.array([2, 0]) + cons_list = [fun, cons1, cons2] + + xsol = [1.4, 1.7] + fsol = 0.8 + + # testing fmin_cobyla + sol = fmin_cobyla(fun, x0, cons_list, rhoend=1e-5) + assert_allclose(sol, xsol, atol=1e-4) + + sol = fmin_cobyla(fun, x0, fmin, rhoend=1e-5) + assert_allclose(fun(sol), 1, atol=1e-4) + + # testing minimize + constraints = [{'type': 'ineq', 'fun': cons} for cons in cons_list] + sol = minimize(fun, x0, constraints=constraints, tol=1e-5) + assert_allclose(sol.x, xsol, atol=1e-4) + assert_(sol.success, sol.message) + assert_allclose(sol.fun, fsol, atol=1e-4) + + constraints = {'type': 'ineq', 'fun': fmin} + sol = minimize(fun, x0, constraints=constraints, tol=1e-5) + assert_allclose(sol.fun, 1, atol=1e-4) + + +class TestBounds: + # Test cobyla support for bounds (only when used via `minimize`) + # Invalid bounds is tested in + # test_optimize.TestOptimizeSimple.test_minimize_invalid_bounds + + def test_basic(self): + def f(x): + return np.sum(x**2) + + lb = [-1, None, 1, None, -0.5] + ub = [-0.5, -0.5, None, None, -0.5] + bounds = [(a, b) for a, b in zip(lb, ub)] + # these are converted to Bounds internally + + res = minimize(f, x0=[1, 2, 3, 4, 5], method='cobyla', bounds=bounds) + ref = [-0.5, -0.5, 1, 0, -0.5] + assert res.success + assert_allclose(res.x, ref, atol=1e-3) + + def test_unbounded(self): + def f(x): + return np.sum(x**2) + + bounds = Bounds([-np.inf, -np.inf], [np.inf, np.inf]) + res = minimize(f, x0=[1, 2], method='cobyla', bounds=bounds) + assert res.success + assert_allclose(res.x, 0, atol=1e-3) + + bounds = Bounds([1, -np.inf], [np.inf, np.inf]) + res = minimize(f, x0=[1, 2], method='cobyla', bounds=bounds) + assert res.success + assert_allclose(res.x, [1, 0], atol=1e-3) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_cobyqa.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_cobyqa.py new file mode 100644 index 0000000000000000000000000000000000000000..bf16af71625c4d476353407f9708c981915b098a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_cobyqa.py @@ -0,0 +1,252 @@ +import numpy as np +import pytest +import threading +from numpy.testing import assert_allclose, assert_equal + +from scipy.optimize import ( + Bounds, + LinearConstraint, + NonlinearConstraint, + OptimizeResult, + minimize, +) + + +class TestCOBYQA: + + def setup_method(self): + self.x0 = [4.95, 0.66] + self.options = {'maxfev': 100} + + @staticmethod + def fun(x, c=1.0): + return x[0]**2 + c * abs(x[1])**3 + + @staticmethod + def con(x): + return x[0]**2 + x[1]**2 - 25.0 + + def test_minimize_simple(self): + class Callback: + def __init__(self): + self.lock = threading.Lock() + self.n_calls = 0 + + def __call__(self, x): + assert isinstance(x, np.ndarray) + with self.lock: + self.n_calls += 1 + + class CallbackNewSyntax: + def __init__(self): + self.lock = threading.Lock() + self.n_calls = 0 + + def __call__(self, intermediate_result): + assert isinstance(intermediate_result, OptimizeResult) + with self.lock: + self.n_calls += 1 + + x0 = [4.95, 0.66] + callback = Callback() + callback_new_syntax = CallbackNewSyntax() + + # Minimize with method='cobyqa'. + constraints = NonlinearConstraint(self.con, 0.0, 0.0) + sol = minimize( + self.fun, + x0, + method='cobyqa', + constraints=constraints, + callback=callback, + options=self.options, + ) + sol_new = minimize( + self.fun, + x0, + method='cobyqa', + constraints=constraints, + callback=callback_new_syntax, + options=self.options, + ) + solution = [np.sqrt(25.0 - 4.0 / 9.0), 2.0 / 3.0] + assert_allclose(sol.x, solution, atol=1e-4) + assert sol.success, sol.message + assert sol.maxcv < 1e-8, sol + assert sol.nfev <= 100, sol + assert sol.fun < self.fun(solution) + 1e-3, sol + assert sol.nfev == callback.n_calls, \ + "Callback is not called exactly once for every function eval." + assert_equal(sol.x, sol_new.x) + assert sol_new.success, sol_new.message + assert sol.fun == sol_new.fun + assert sol.maxcv == sol_new.maxcv + assert sol.nfev == sol_new.nfev + assert sol.nit == sol_new.nit + assert sol_new.nfev == callback_new_syntax.n_calls, \ + "Callback is not called exactly once for every function eval." + + def test_minimize_bounds(self): + def fun_check_bounds(x): + assert np.all(bounds.lb <= x) and np.all(x <= bounds.ub) + return self.fun(x) + + # Case where the bounds are not active at the solution. + bounds = Bounds([4.5, 0.6], [5.0, 0.7]) + constraints = NonlinearConstraint(self.con, 0.0, 0.0) + sol = minimize( + fun_check_bounds, + self.x0, + method='cobyqa', + bounds=bounds, + constraints=constraints, + options=self.options, + ) + solution = [np.sqrt(25.0 - 4.0 / 9.0), 2.0 / 3.0] + assert_allclose(sol.x, solution, atol=1e-4) + assert sol.success, sol.message + assert sol.maxcv < 1e-8, sol + assert np.all(bounds.lb <= sol.x) and np.all(sol.x <= bounds.ub), sol + assert sol.nfev <= 100, sol + assert sol.fun < self.fun(solution) + 1e-3, sol + + # Case where the bounds are active at the solution. + bounds = Bounds([5.0, 0.6], [5.5, 0.65]) + sol = minimize( + fun_check_bounds, + self.x0, + method='cobyqa', + bounds=bounds, + constraints=constraints, + options=self.options, + ) + assert not sol.success, sol.message + assert sol.maxcv > 0.35, sol + assert np.all(bounds.lb <= sol.x) and np.all(sol.x <= bounds.ub), sol + assert sol.nfev <= 100, sol + + def test_minimize_linear_constraints(self): + constraints = LinearConstraint([1.0, 1.0], 1.0, 1.0) + sol = minimize( + self.fun, + self.x0, + method='cobyqa', + constraints=constraints, + options=self.options, + ) + solution = [(4 - np.sqrt(7)) / 3, (np.sqrt(7) - 1) / 3] + assert_allclose(sol.x, solution, atol=1e-4) + assert sol.success, sol.message + assert sol.maxcv < 1e-8, sol + assert sol.nfev <= 100, sol + assert sol.fun < self.fun(solution) + 1e-3, sol + + def test_minimize_args(self): + constraints = NonlinearConstraint(self.con, 0.0, 0.0) + sol = minimize( + self.fun, + self.x0, + args=(2.0,), + method='cobyqa', + constraints=constraints, + options=self.options, + ) + solution = [np.sqrt(25.0 - 4.0 / 36.0), 2.0 / 6.0] + assert_allclose(sol.x, solution, atol=1e-4) + assert sol.success, sol.message + assert sol.maxcv < 1e-8, sol + assert sol.nfev <= 100, sol + assert sol.fun < self.fun(solution, 2.0) + 1e-3, sol + + def test_minimize_array(self): + def fun_array(x, dim): + f = np.array(self.fun(x)) + return np.reshape(f, (1,) * dim) + + # The argument fun can return an array with a single element. + bounds = Bounds([4.5, 0.6], [5.0, 0.7]) + constraints = NonlinearConstraint(self.con, 0.0, 0.0) + sol = minimize( + self.fun, + self.x0, + method='cobyqa', + bounds=bounds, + constraints=constraints, + options=self.options, + ) + for dim in [0, 1, 2]: + sol_array = minimize( + fun_array, + self.x0, + args=(dim,), + method='cobyqa', + bounds=bounds, + constraints=constraints, + options=self.options, + ) + assert_equal(sol.x, sol_array.x) + assert sol_array.success, sol_array.message + assert sol.fun == sol_array.fun + assert sol.maxcv == sol_array.maxcv + assert sol.nfev == sol_array.nfev + assert sol.nit == sol_array.nit + + # The argument fun cannot return an array with more than one element. + with pytest.raises(TypeError): + minimize( + lambda x: np.array([self.fun(x), self.fun(x)]), + self.x0, + method='cobyqa', + bounds=bounds, + constraints=constraints, + options=self.options, + ) + + def test_minimize_maxfev(self): + constraints = NonlinearConstraint(self.con, 0.0, 0.0) + options = {'maxfev': 2} + sol = minimize( + self.fun, + self.x0, + method='cobyqa', + constraints=constraints, + options=options, + ) + assert not sol.success, sol.message + assert sol.nfev <= 2, sol + + def test_minimize_maxiter(self): + constraints = NonlinearConstraint(self.con, 0.0, 0.0) + options = {'maxiter': 2} + sol = minimize( + self.fun, + self.x0, + method='cobyqa', + constraints=constraints, + options=options, + ) + assert not sol.success, sol.message + assert sol.nit <= 2, sol + + def test_minimize_f_target(self): + constraints = NonlinearConstraint(self.con, 0.0, 0.0) + sol_ref = minimize( + self.fun, + self.x0, + method='cobyqa', + constraints=constraints, + options=self.options, + ) + options = dict(self.options) + options['f_target'] = sol_ref.fun + sol = minimize( + self.fun, + self.x0, + method='cobyqa', + constraints=constraints, + options=options, + ) + assert sol.success, sol.message + assert sol.maxcv < 1e-8, sol + assert sol.nfev <= sol_ref.nfev, sol + assert sol.fun <= sol_ref.fun, sol diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_constraint_conversion.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_constraint_conversion.py new file mode 100644 index 0000000000000000000000000000000000000000..c33183d5cb4e7ccaf4d755cbd2d8b28afaf46395 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_constraint_conversion.py @@ -0,0 +1,286 @@ +""" +Unit test for constraint conversion +""" + +import numpy as np +from numpy.testing import (assert_array_almost_equal, + assert_allclose, assert_warns, suppress_warnings) +import pytest +from scipy.optimize import (NonlinearConstraint, LinearConstraint, + OptimizeWarning, minimize, BFGS) +from .test_minimize_constrained import (Maratos, HyperbolicIneq, Rosenbrock, + IneqRosenbrock, EqIneqRosenbrock, + BoundedRosenbrock, Elec) + + +class TestOldToNew: + x0 = (2, 0) + bnds = ((0, None), (0, None)) + method = "trust-constr" + + def test_constraint_dictionary_1(self): + def fun(x): + return (x[0] - 1) ** 2 + (x[1] - 2.5) ** 2 + cons = ({'type': 'ineq', 'fun': lambda x: x[0] - 2 * x[1] + 2}, + {'type': 'ineq', 'fun': lambda x: -x[0] - 2 * x[1] + 6}, + {'type': 'ineq', 'fun': lambda x: -x[0] + 2 * x[1] + 2}) + + with suppress_warnings() as sup: + sup.filter(UserWarning, "delta_grad == 0.0") + res = minimize(fun, self.x0, method=self.method, + bounds=self.bnds, constraints=cons) + assert_allclose(res.x, [1.4, 1.7], rtol=1e-4) + assert_allclose(res.fun, 0.8, rtol=1e-4) + + def test_constraint_dictionary_2(self): + def fun(x): + return (x[0] - 1) ** 2 + (x[1] - 2.5) ** 2 + cons = {'type': 'eq', + 'fun': lambda x, p1, p2: p1*x[0] - p2*x[1], + 'args': (1, 1.1), + 'jac': lambda x, p1, p2: np.array([[p1, -p2]])} + with suppress_warnings() as sup: + sup.filter(UserWarning, "delta_grad == 0.0") + res = minimize(fun, self.x0, method=self.method, + bounds=self.bnds, constraints=cons) + assert_allclose(res.x, [1.7918552, 1.62895927]) + assert_allclose(res.fun, 1.3857466063348418) + + def test_constraint_dictionary_3(self): + def fun(x): + return (x[0] - 1) ** 2 + (x[1] - 2.5) ** 2 + cons = [{'type': 'ineq', 'fun': lambda x: x[0] - 2 * x[1] + 2}, + NonlinearConstraint(lambda x: x[0] - x[1], 0, 0)] + + with suppress_warnings() as sup: + sup.filter(UserWarning, "delta_grad == 0.0") + res = minimize(fun, self.x0, method=self.method, + bounds=self.bnds, constraints=cons) + assert_allclose(res.x, [1.75, 1.75], rtol=1e-4) + assert_allclose(res.fun, 1.125, rtol=1e-4) + + +class TestNewToOld: + @pytest.mark.fail_slow(2) + def test_multiple_constraint_objects(self, num_parallel_threads): + def fun(x): + return (x[0] - 1) ** 2 + (x[1] - 2.5) ** 2 + (x[2] - 0.75) ** 2 + x0 = [2, 0, 1] + coni = [] # only inequality constraints (can use cobyla) + methods = ["slsqp", "cobyla", "cobyqa", "trust-constr"] + + # mixed old and new + coni.append([{'type': 'ineq', 'fun': lambda x: x[0] - 2 * x[1] + 2}, + NonlinearConstraint(lambda x: x[0] - x[1], -1, 1)]) + + coni.append([LinearConstraint([1, -2, 0], -2, np.inf), + NonlinearConstraint(lambda x: x[0] - x[1], -1, 1)]) + + coni.append([NonlinearConstraint(lambda x: x[0] - 2 * x[1] + 2, 0, np.inf), + NonlinearConstraint(lambda x: x[0] - x[1], -1, 1)]) + + for con in coni: + funs = {} + for method in methods: + with suppress_warnings() as sup: + sup.filter(UserWarning) + result = minimize(fun, x0, method=method, constraints=con) + funs[method] = result.fun + assert_allclose(funs['slsqp'], funs['trust-constr'], rtol=1e-4) + assert_allclose(funs['cobyla'], funs['trust-constr'], rtol=1e-4) + if num_parallel_threads == 1: + assert_allclose(funs['cobyqa'], funs['trust-constr'], + rtol=1e-4) + + @pytest.mark.fail_slow(20) + def test_individual_constraint_objects(self, num_parallel_threads): + def fun(x): + return (x[0] - 1) ** 2 + (x[1] - 2.5) ** 2 + (x[2] - 0.75) ** 2 + x0 = [2, 0, 1] + + cone = [] # with equality constraints (can't use cobyla) + coni = [] # only inequality constraints (can use cobyla) + methods = ["slsqp", "cobyla", "cobyqa", "trust-constr"] + + # nonstandard data types for constraint equality bounds + cone.append(NonlinearConstraint(lambda x: x[0] - x[1], 1, 1)) + cone.append(NonlinearConstraint(lambda x: x[0] - x[1], [1.21], [1.21])) + cone.append(NonlinearConstraint(lambda x: x[0] - x[1], + 1.21, np.array([1.21]))) + + # multiple equalities + cone.append(NonlinearConstraint( + lambda x: [x[0] - x[1], x[1] - x[2]], + 1.21, 1.21)) # two same equalities + cone.append(NonlinearConstraint( + lambda x: [x[0] - x[1], x[1] - x[2]], + [1.21, 1.4], [1.21, 1.4])) # two different equalities + cone.append(NonlinearConstraint( + lambda x: [x[0] - x[1], x[1] - x[2]], + [1.21, 1.21], 1.21)) # equality specified two ways + cone.append(NonlinearConstraint( + lambda x: [x[0] - x[1], x[1] - x[2]], + [1.21, -np.inf], [1.21, np.inf])) # equality + unbounded + + # nonstandard data types for constraint inequality bounds + coni.append(NonlinearConstraint(lambda x: x[0] - x[1], 1.21, np.inf)) + coni.append(NonlinearConstraint(lambda x: x[0] - x[1], [1.21], np.inf)) + coni.append(NonlinearConstraint(lambda x: x[0] - x[1], + 1.21, np.array([np.inf]))) + coni.append(NonlinearConstraint(lambda x: x[0] - x[1], -np.inf, -3)) + coni.append(NonlinearConstraint(lambda x: x[0] - x[1], + np.array(-np.inf), -3)) + + # multiple inequalities/equalities + coni.append(NonlinearConstraint( + lambda x: [x[0] - x[1], x[1] - x[2]], + 1.21, np.inf)) # two same inequalities + cone.append(NonlinearConstraint( + lambda x: [x[0] - x[1], x[1] - x[2]], + [1.21, -np.inf], [1.21, 1.4])) # mixed equality/inequality + coni.append(NonlinearConstraint( + lambda x: [x[0] - x[1], x[1] - x[2]], + [1.1, .8], [1.2, 1.4])) # bounded above and below + coni.append(NonlinearConstraint( + lambda x: [x[0] - x[1], x[1] - x[2]], + [-1.2, -1.4], [-1.1, -.8])) # - bounded above and below + + # quick check of LinearConstraint class (very little new code to test) + cone.append(LinearConstraint([1, -1, 0], 1.21, 1.21)) + cone.append(LinearConstraint([[1, -1, 0], [0, 1, -1]], 1.21, 1.21)) + cone.append(LinearConstraint([[1, -1, 0], [0, 1, -1]], + [1.21, -np.inf], [1.21, 1.4])) + + for con in coni: + funs = {} + for method in methods: + with suppress_warnings() as sup: + sup.filter(UserWarning) + result = minimize(fun, x0, method=method, constraints=con) + funs[method] = result.fun + assert_allclose(funs['slsqp'], funs['trust-constr'], rtol=1e-3) + assert_allclose(funs['cobyla'], funs['trust-constr'], rtol=1e-3) + if num_parallel_threads == 1: + assert_allclose(funs['cobyqa'], funs['trust-constr'], + rtol=1e-3) + + for con in cone: + funs = {} + for method in [method for method in methods if method != 'cobyla']: + with suppress_warnings() as sup: + sup.filter(UserWarning) + result = minimize(fun, x0, method=method, constraints=con) + funs[method] = result.fun + assert_allclose(funs['slsqp'], funs['trust-constr'], rtol=1e-3) + if num_parallel_threads == 1: + assert_allclose(funs['cobyqa'], funs['trust-constr'], + rtol=1e-3) + + +class TestNewToOldSLSQP: + method = 'slsqp' + elec = Elec(n_electrons=2) + elec.x_opt = np.array([-0.58438468, 0.58438466, 0.73597047, + -0.73597044, 0.34180668, -0.34180667]) + brock = BoundedRosenbrock() + brock.x_opt = [0, 0] + list_of_problems = [Maratos(), + HyperbolicIneq(), + Rosenbrock(), + IneqRosenbrock(), + EqIneqRosenbrock(), + elec, + brock + ] + + def test_list_of_problems(self): + + for prob in self.list_of_problems: + + with suppress_warnings() as sup: + sup.filter(UserWarning) + result = minimize(prob.fun, prob.x0, + method=self.method, + bounds=prob.bounds, + constraints=prob.constr) + + assert_array_almost_equal(result.x, prob.x_opt, decimal=3) + + @pytest.mark.thread_unsafe + def test_warn_mixed_constraints(self): + # warns about inefficiency of mixed equality/inequality constraints + def fun(x): + return (x[0] - 1) ** 2 + (x[1] - 2.5) ** 2 + (x[2] - 0.75) ** 2 + cons = NonlinearConstraint(lambda x: [x[0]**2 - x[1], x[1] - x[2]], + [1.1, .8], [1.1, 1.4]) + bnds = ((0, None), (0, None), (0, None)) + with suppress_warnings() as sup: + sup.filter(UserWarning, "delta_grad == 0.0") + assert_warns(OptimizeWarning, minimize, fun, (2, 0, 1), + method=self.method, bounds=bnds, constraints=cons) + + @pytest.mark.thread_unsafe + def test_warn_ignored_options(self): + # warns about constraint options being ignored + def fun(x): + return (x[0] - 1) ** 2 + (x[1] - 2.5) ** 2 + (x[2] - 0.75) ** 2 + x0 = (2, 0, 1) + + if self.method == "slsqp": + bnds = ((0, None), (0, None), (0, None)) + else: + bnds = None + + cons = NonlinearConstraint(lambda x: x[0], 2, np.inf) + res = minimize(fun, x0, method=self.method, + bounds=bnds, constraints=cons) + # no warnings without constraint options + assert_allclose(res.fun, 1) + + cons = LinearConstraint([1, 0, 0], 2, np.inf) + res = minimize(fun, x0, method=self.method, + bounds=bnds, constraints=cons) + # no warnings without constraint options + assert_allclose(res.fun, 1) + + cons = [] + cons.append(NonlinearConstraint(lambda x: x[0]**2, 2, np.inf, + keep_feasible=True)) + cons.append(NonlinearConstraint(lambda x: x[0]**2, 2, np.inf, + hess=BFGS())) + cons.append(NonlinearConstraint(lambda x: x[0]**2, 2, np.inf, + finite_diff_jac_sparsity=42)) + cons.append(NonlinearConstraint(lambda x: x[0]**2, 2, np.inf, + finite_diff_rel_step=42)) + cons.append(LinearConstraint([1, 0, 0], 2, np.inf, + keep_feasible=True)) + for con in cons: + assert_warns(OptimizeWarning, minimize, fun, x0, + method=self.method, bounds=bnds, constraints=cons) + + +class TestNewToOldCobyla: + method = 'cobyla' + + list_of_problems = [ + Elec(n_electrons=2), + Elec(n_electrons=4), + ] + + @pytest.mark.slow + def test_list_of_problems(self): + + for prob in self.list_of_problems: + + with suppress_warnings() as sup: + sup.filter(UserWarning) + truth = minimize(prob.fun, prob.x0, + method='trust-constr', + bounds=prob.bounds, + constraints=prob.constr) + result = minimize(prob.fun, prob.x0, + method=self.method, + bounds=prob.bounds, + constraints=prob.constr) + + assert_allclose(result.fun, truth.fun, rtol=1e-3) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_constraints.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_constraints.py new file mode 100644 index 0000000000000000000000000000000000000000..4c4186ba7b6dd6f56b89e2f39add9eb16e6beccb --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_constraints.py @@ -0,0 +1,255 @@ +import pytest +import numpy as np +from numpy.testing import TestCase, assert_array_equal +import scipy.sparse as sps +from scipy.optimize._constraints import ( + Bounds, LinearConstraint, NonlinearConstraint, PreparedConstraint, + new_bounds_to_old, old_bound_to_new, strict_bounds) + + +class TestStrictBounds(TestCase): + def test_scalarvalue_unique_enforce_feasibility(self): + m = 3 + lb = 2 + ub = 4 + enforce_feasibility = False + strict_lb, strict_ub = strict_bounds(lb, ub, + enforce_feasibility, + m) + assert_array_equal(strict_lb, [-np.inf, -np.inf, -np.inf]) + assert_array_equal(strict_ub, [np.inf, np.inf, np.inf]) + + enforce_feasibility = True + strict_lb, strict_ub = strict_bounds(lb, ub, + enforce_feasibility, + m) + assert_array_equal(strict_lb, [2, 2, 2]) + assert_array_equal(strict_ub, [4, 4, 4]) + + def test_vectorvalue_unique_enforce_feasibility(self): + m = 3 + lb = [1, 2, 3] + ub = [4, 5, 6] + enforce_feasibility = False + strict_lb, strict_ub = strict_bounds(lb, ub, + enforce_feasibility, + m) + assert_array_equal(strict_lb, [-np.inf, -np.inf, -np.inf]) + assert_array_equal(strict_ub, [np.inf, np.inf, np.inf]) + + enforce_feasibility = True + strict_lb, strict_ub = strict_bounds(lb, ub, + enforce_feasibility, + m) + assert_array_equal(strict_lb, [1, 2, 3]) + assert_array_equal(strict_ub, [4, 5, 6]) + + def test_scalarvalue_vector_enforce_feasibility(self): + m = 3 + lb = 2 + ub = 4 + enforce_feasibility = [False, True, False] + strict_lb, strict_ub = strict_bounds(lb, ub, + enforce_feasibility, + m) + assert_array_equal(strict_lb, [-np.inf, 2, -np.inf]) + assert_array_equal(strict_ub, [np.inf, 4, np.inf]) + + def test_vectorvalue_vector_enforce_feasibility(self): + m = 3 + lb = [1, 2, 3] + ub = [4, 6, np.inf] + enforce_feasibility = [True, False, True] + strict_lb, strict_ub = strict_bounds(lb, ub, + enforce_feasibility, + m) + assert_array_equal(strict_lb, [1, -np.inf, 3]) + assert_array_equal(strict_ub, [4, np.inf, np.inf]) + + +def test_prepare_constraint_infeasible_x0(): + lb = np.array([0, 20, 30]) + ub = np.array([0.5, np.inf, 70]) + x0 = np.array([1, 2, 3]) + enforce_feasibility = np.array([False, True, True], dtype=bool) + bounds = Bounds(lb, ub, enforce_feasibility) + pytest.raises(ValueError, PreparedConstraint, bounds, x0) + + pc = PreparedConstraint(Bounds(lb, ub), [1, 2, 3]) + assert (pc.violation([1, 2, 3]) > 0).any() + assert (pc.violation([0.25, 21, 31]) == 0).all() + + x0 = np.array([1, 2, 3, 4]) + A = np.array([[1, 2, 3, 4], [5, 0, 0, 6], [7, 0, 8, 0]]) + enforce_feasibility = np.array([True, True, True], dtype=bool) + linear = LinearConstraint(A, -np.inf, 0, enforce_feasibility) + pytest.raises(ValueError, PreparedConstraint, linear, x0) + + pc = PreparedConstraint(LinearConstraint(A, -np.inf, 0), + [1, 2, 3, 4]) + assert (pc.violation([1, 2, 3, 4]) > 0).any() + assert (pc.violation([-10, 2, -10, 4]) == 0).all() + + def fun(x): + return A.dot(x) + + def jac(x): + return A + + def hess(x, v): + return sps.csr_matrix((4, 4)) + + nonlinear = NonlinearConstraint(fun, -np.inf, 0, jac, hess, + enforce_feasibility) + pytest.raises(ValueError, PreparedConstraint, nonlinear, x0) + + pc = PreparedConstraint(nonlinear, [-10, 2, -10, 4]) + assert (pc.violation([1, 2, 3, 4]) > 0).any() + assert (pc.violation([-10, 2, -10, 4]) == 0).all() + + +def test_violation(): + def cons_f(x): + return np.array([x[0] ** 2 + x[1], x[0] ** 2 - x[1]]) + + nlc = NonlinearConstraint(cons_f, [-1, -0.8500], [2, 2]) + pc = PreparedConstraint(nlc, [0.5, 1]) + + assert_array_equal(pc.violation([0.5, 1]), [0., 0.]) + + np.testing.assert_almost_equal(pc.violation([0.5, 1.2]), [0., 0.1]) + + np.testing.assert_almost_equal(pc.violation([1.2, 1.2]), [0.64, 0]) + + np.testing.assert_almost_equal(pc.violation([0.1, -1.2]), [0.19, 0]) + + np.testing.assert_almost_equal(pc.violation([0.1, 2]), [0.01, 1.14]) + + +def test_new_bounds_to_old(): + lb = np.array([-np.inf, 2, 3]) + ub = np.array([3, np.inf, 10]) + + bounds = [(None, 3), (2, None), (3, 10)] + assert_array_equal(new_bounds_to_old(lb, ub, 3), bounds) + + bounds_single_lb = [(-1, 3), (-1, None), (-1, 10)] + assert_array_equal(new_bounds_to_old(-1, ub, 3), bounds_single_lb) + + bounds_no_lb = [(None, 3), (None, None), (None, 10)] + assert_array_equal(new_bounds_to_old(-np.inf, ub, 3), bounds_no_lb) + + bounds_single_ub = [(None, 20), (2, 20), (3, 20)] + assert_array_equal(new_bounds_to_old(lb, 20, 3), bounds_single_ub) + + bounds_no_ub = [(None, None), (2, None), (3, None)] + assert_array_equal(new_bounds_to_old(lb, np.inf, 3), bounds_no_ub) + + bounds_single_both = [(1, 2), (1, 2), (1, 2)] + assert_array_equal(new_bounds_to_old(1, 2, 3), bounds_single_both) + + bounds_no_both = [(None, None), (None, None), (None, None)] + assert_array_equal(new_bounds_to_old(-np.inf, np.inf, 3), bounds_no_both) + + +def test_old_bounds_to_new(): + bounds = ([1, 2], (None, 3), (-1, None)) + lb_true = np.array([1, -np.inf, -1]) + ub_true = np.array([2, 3, np.inf]) + + lb, ub = old_bound_to_new(bounds) + assert_array_equal(lb, lb_true) + assert_array_equal(ub, ub_true) + + bounds = [(-np.inf, np.inf), (np.array([1]), np.array([1]))] + lb, ub = old_bound_to_new(bounds) + + assert_array_equal(lb, [-np.inf, 1]) + assert_array_equal(ub, [np.inf, 1]) + + +class TestBounds: + def test_repr(self): + # so that eval works + from numpy import array, inf # noqa: F401 + for args in ( + (-1.0, 5.0), + (-1.0, np.inf, True), + (np.array([1.0, -np.inf]), np.array([2.0, np.inf])), + (np.array([1.0, -np.inf]), np.array([2.0, np.inf]), + np.array([True, False])), + ): + bounds = Bounds(*args) + bounds2 = eval(repr(Bounds(*args))) + assert_array_equal(bounds.lb, bounds2.lb) + assert_array_equal(bounds.ub, bounds2.ub) + assert_array_equal(bounds.keep_feasible, bounds2.keep_feasible) + + def test_array(self): + # gh13501 + b = Bounds(lb=[0.0, 0.0], ub=[1.0, 1.0]) + assert isinstance(b.lb, np.ndarray) + assert isinstance(b.ub, np.ndarray) + + def test_defaults(self): + b1 = Bounds() + b2 = Bounds(np.asarray(-np.inf), np.asarray(np.inf)) + assert b1.lb == b2.lb + assert b1.ub == b2.ub + + def test_input_validation(self): + message = "Lower and upper bounds must be dense arrays." + with pytest.raises(ValueError, match=message): + Bounds(sps.coo_array([1, 2]), [1, 2]) + with pytest.raises(ValueError, match=message): + Bounds([1, 2], sps.coo_array([1, 2])) + + message = "`keep_feasible` must be a dense array." + with pytest.raises(ValueError, match=message): + Bounds([1, 2], [1, 2], keep_feasible=sps.coo_array([True, True])) + + message = "`lb`, `ub`, and `keep_feasible` must be broadcastable." + with pytest.raises(ValueError, match=message): + Bounds([1, 2], [1, 2, 3]) + + def test_residual(self): + bounds = Bounds(-2, 4) + x0 = [-1, 2] + np.testing.assert_allclose(bounds.residual(x0), ([1, 4], [5, 2])) + + +class TestLinearConstraint: + def test_defaults(self): + A = np.eye(4) + lc = LinearConstraint(A) + lc2 = LinearConstraint(A, -np.inf, np.inf) + assert_array_equal(lc.lb, lc2.lb) + assert_array_equal(lc.ub, lc2.ub) + + def test_input_validation(self): + A = np.eye(4) + message = "`lb`, `ub`, and `keep_feasible` must be broadcastable" + with pytest.raises(ValueError, match=message): + LinearConstraint(A, [1, 2], [1, 2, 3]) + + message = "Constraint limits must be dense arrays" + with pytest.raises(ValueError, match=message): + LinearConstraint(A, sps.coo_array([1, 2]), [2, 3]) + with pytest.raises(ValueError, match=message): + LinearConstraint(A, [1, 2], sps.coo_array([2, 3])) + + message = "`keep_feasible` must be a dense array" + with pytest.raises(ValueError, match=message): + keep_feasible = sps.coo_array([True, True]) + LinearConstraint(A, [1, 2], [2, 3], keep_feasible=keep_feasible) + + A = np.empty((4, 3, 5)) + message = "`A` must have exactly two dimensions." + with pytest.raises(ValueError, match=message): + LinearConstraint(A) + + def test_residual(self): + A = np.eye(2) + lc = LinearConstraint(A, -2, 4) + x0 = [-1, 2] + np.testing.assert_allclose(lc.residual(x0), ([1, 4], [5, 2])) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_cython_optimize.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_cython_optimize.py new file mode 100644 index 0000000000000000000000000000000000000000..2f859c1143eb6b63c439fe278bfdd4fdaa15410f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_cython_optimize.py @@ -0,0 +1,92 @@ +""" +Test Cython optimize zeros API functions: ``bisect``, ``ridder``, ``brenth``, +and ``brentq`` in `scipy.optimize.cython_optimize`, by finding the roots of a +3rd order polynomial given a sequence of constant terms, ``a0``, and fixed 1st, +2nd, and 3rd order terms in ``args``. + +.. math:: + + f(x, a0, args) = ((args[2]*x + args[1])*x + args[0])*x + a0 + +The 3rd order polynomial function is written in Cython and called in a Python +wrapper named after the zero function. See the private ``_zeros`` Cython module +in `scipy.optimize.cython_optimze` for more information. +""" + +import numpy.testing as npt +from scipy.optimize.cython_optimize import _zeros + +# CONSTANTS +# Solve x**3 - A0 = 0 for A0 = [2.0, 2.1, ..., 2.9]. +# The ARGS have 3 elements just to show how this could be done for any cubic +# polynomial. +A0 = tuple(-2.0 - x/10.0 for x in range(10)) # constant term +ARGS = (0.0, 0.0, 1.0) # 1st, 2nd, and 3rd order terms +XLO, XHI = 0.0, 2.0 # first and second bounds of zeros functions +# absolute and relative tolerances and max iterations for zeros functions +XTOL, RTOL, MITR = 0.001, 0.001, 10 +EXPECTED = [(-a0) ** (1.0/3.0) for a0 in A0] +# = [1.2599210498948732, +# 1.2805791649874942, +# 1.300591446851387, +# 1.3200061217959123, +# 1.338865900164339, +# 1.3572088082974532, +# 1.375068867074141, +# 1.3924766500838337, +# 1.4094597464129783, +# 1.4260431471424087] + + +# test bisect +def test_bisect(): + npt.assert_allclose( + EXPECTED, + list( + _zeros.loop_example('bisect', A0, ARGS, XLO, XHI, XTOL, RTOL, MITR) + ), + rtol=RTOL, atol=XTOL + ) + + +# test ridder +def test_ridder(): + npt.assert_allclose( + EXPECTED, + list( + _zeros.loop_example('ridder', A0, ARGS, XLO, XHI, XTOL, RTOL, MITR) + ), + rtol=RTOL, atol=XTOL + ) + + +# test brenth +def test_brenth(): + npt.assert_allclose( + EXPECTED, + list( + _zeros.loop_example('brenth', A0, ARGS, XLO, XHI, XTOL, RTOL, MITR) + ), + rtol=RTOL, atol=XTOL + ) + + +# test brentq +def test_brentq(): + npt.assert_allclose( + EXPECTED, + list( + _zeros.loop_example('brentq', A0, ARGS, XLO, XHI, XTOL, RTOL, MITR) + ), + rtol=RTOL, atol=XTOL + ) + + +# test brentq with full output +def test_brentq_full_output(): + output = _zeros.full_output_example( + (A0[0],) + ARGS, XLO, XHI, XTOL, RTOL, MITR) + npt.assert_allclose(EXPECTED[0], output['root'], rtol=RTOL, atol=XTOL) + npt.assert_equal(6, output['iterations']) + npt.assert_equal(7, output['funcalls']) + npt.assert_equal(0, output['error_num']) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_differentiable_functions.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_differentiable_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..cac12af0033c09c3fbf73c52a9c2cb52b84d8239 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_differentiable_functions.py @@ -0,0 +1,805 @@ +import pytest +import platform +import numpy as np +from numpy.testing import (TestCase, assert_array_almost_equal, + assert_array_equal, assert_, assert_allclose, + assert_equal) +from scipy._lib._gcutils import assert_deallocated +from scipy.sparse import csr_matrix +from scipy.sparse.linalg import LinearOperator +from scipy.optimize._differentiable_functions import (ScalarFunction, + VectorFunction, + LinearVectorFunction, + IdentityVectorFunction) +from scipy.optimize import rosen, rosen_der, rosen_hess +from scipy.optimize._hessian_update_strategy import BFGS + + +class ExScalarFunction: + + def __init__(self): + self.nfev = 0 + self.ngev = 0 + self.nhev = 0 + + def fun(self, x): + self.nfev += 1 + return 2*(x[0]**2 + x[1]**2 - 1) - x[0] + + def grad(self, x): + self.ngev += 1 + return np.array([4*x[0]-1, 4*x[1]]) + + def hess(self, x): + self.nhev += 1 + return 4*np.eye(2) + + +class TestScalarFunction(TestCase): + + def test_finite_difference_grad(self): + ex = ExScalarFunction() + nfev = 0 + ngev = 0 + + x0 = [1.0, 0.0] + analit = ScalarFunction(ex.fun, x0, (), ex.grad, + ex.hess, None, (-np.inf, np.inf)) + nfev += 1 + ngev += 1 + assert_array_equal(ex.nfev, nfev) + assert_array_equal(analit.nfev, nfev) + assert_array_equal(ex.ngev, ngev) + assert_array_equal(analit.ngev, nfev) + approx = ScalarFunction(ex.fun, x0, (), '2-point', + ex.hess, None, (-np.inf, np.inf)) + nfev += 3 + ngev += 1 + assert_array_equal(ex.nfev, nfev) + assert_array_equal(analit.nfev+approx.nfev, nfev) + assert_array_equal(analit.ngev+approx.ngev, ngev) + assert_array_equal(analit.f, approx.f) + assert_array_almost_equal(analit.g, approx.g) + + x = [10, 0.3] + f_analit = analit.fun(x) + g_analit = analit.grad(x) + nfev += 1 + ngev += 1 + assert_array_equal(ex.nfev, nfev) + assert_array_equal(analit.nfev+approx.nfev, nfev) + assert_array_equal(analit.ngev+approx.ngev, ngev) + f_approx = approx.fun(x) + g_approx = approx.grad(x) + nfev += 3 + ngev += 1 + assert_array_equal(ex.nfev, nfev) + assert_array_equal(analit.nfev+approx.nfev, nfev) + assert_array_equal(analit.ngev+approx.ngev, ngev) + assert_array_almost_equal(f_analit, f_approx) + assert_array_almost_equal(g_analit, g_approx) + + x = [2.0, 1.0] + g_analit = analit.grad(x) + ngev += 1 + assert_array_equal(ex.nfev, nfev) + assert_array_equal(analit.nfev+approx.nfev, nfev) + assert_array_equal(analit.ngev+approx.ngev, ngev) + + g_approx = approx.grad(x) + nfev += 3 + ngev += 1 + assert_array_equal(ex.nfev, nfev) + assert_array_equal(analit.nfev+approx.nfev, nfev) + assert_array_equal(analit.ngev+approx.ngev, ngev) + assert_array_almost_equal(g_analit, g_approx) + + x = [2.5, 0.3] + f_analit = analit.fun(x) + g_analit = analit.grad(x) + nfev += 1 + ngev += 1 + assert_array_equal(ex.nfev, nfev) + assert_array_equal(analit.nfev+approx.nfev, nfev) + assert_array_equal(analit.ngev+approx.ngev, ngev) + f_approx = approx.fun(x) + g_approx = approx.grad(x) + nfev += 3 + ngev += 1 + assert_array_equal(ex.nfev, nfev) + assert_array_equal(analit.nfev+approx.nfev, nfev) + assert_array_equal(analit.ngev+approx.ngev, ngev) + assert_array_almost_equal(f_analit, f_approx) + assert_array_almost_equal(g_analit, g_approx) + + x = [2, 0.3] + f_analit = analit.fun(x) + g_analit = analit.grad(x) + nfev += 1 + ngev += 1 + assert_array_equal(ex.nfev, nfev) + assert_array_equal(analit.nfev+approx.nfev, nfev) + assert_array_equal(analit.ngev+approx.ngev, ngev) + f_approx = approx.fun(x) + g_approx = approx.grad(x) + nfev += 3 + ngev += 1 + assert_array_equal(ex.nfev, nfev) + assert_array_equal(analit.nfev+approx.nfev, nfev) + assert_array_equal(analit.ngev+approx.ngev, ngev) + assert_array_almost_equal(f_analit, f_approx) + assert_array_almost_equal(g_analit, g_approx) + + def test_fun_and_grad(self): + ex = ExScalarFunction() + + def fg_allclose(x, y): + assert_allclose(x[0], y[0]) + assert_allclose(x[1], y[1]) + + # with analytic gradient + x0 = [2.0, 0.3] + analit = ScalarFunction(ex.fun, x0, (), ex.grad, + ex.hess, None, (-np.inf, np.inf)) + + fg = ex.fun(x0), ex.grad(x0) + fg_allclose(analit.fun_and_grad(x0), fg) + assert analit.ngev == 1 + + x0[1] = 1. + fg = ex.fun(x0), ex.grad(x0) + fg_allclose(analit.fun_and_grad(x0), fg) + + # with finite difference gradient + x0 = [2.0, 0.3] + sf = ScalarFunction(ex.fun, x0, (), '3-point', + ex.hess, None, (-np.inf, np.inf)) + assert sf.ngev == 1 + fg = ex.fun(x0), ex.grad(x0) + fg_allclose(sf.fun_and_grad(x0), fg) + assert sf.ngev == 1 + + x0[1] = 1. + fg = ex.fun(x0), ex.grad(x0) + fg_allclose(sf.fun_and_grad(x0), fg) + + def test_finite_difference_hess_linear_operator(self): + ex = ExScalarFunction() + nfev = 0 + ngev = 0 + nhev = 0 + + x0 = [1.0, 0.0] + analit = ScalarFunction(ex.fun, x0, (), ex.grad, + ex.hess, None, (-np.inf, np.inf)) + nfev += 1 + ngev += 1 + nhev += 1 + assert_array_equal(ex.nfev, nfev) + assert_array_equal(analit.nfev, nfev) + assert_array_equal(ex.ngev, ngev) + assert_array_equal(analit.ngev, ngev) + assert_array_equal(ex.nhev, nhev) + assert_array_equal(analit.nhev, nhev) + approx = ScalarFunction(ex.fun, x0, (), ex.grad, + '2-point', None, (-np.inf, np.inf)) + assert_(isinstance(approx.H, LinearOperator)) + for v in ([1.0, 2.0], [3.0, 4.0], [5.0, 2.0]): + assert_array_equal(analit.f, approx.f) + assert_array_almost_equal(analit.g, approx.g) + assert_array_almost_equal(analit.H.dot(v), approx.H.dot(v)) + nfev += 1 + ngev += 4 + assert_array_equal(ex.nfev, nfev) + assert_array_equal(analit.nfev+approx.nfev, nfev) + assert_array_equal(ex.ngev, ngev) + assert_array_equal(analit.ngev+approx.ngev, ngev) + assert_array_equal(ex.nhev, nhev) + assert_array_equal(analit.nhev+approx.nhev, nhev) + + x = [2.0, 1.0] + H_analit = analit.hess(x) + nhev += 1 + assert_array_equal(ex.nfev, nfev) + assert_array_equal(analit.nfev+approx.nfev, nfev) + assert_array_equal(ex.ngev, ngev) + assert_array_equal(analit.ngev+approx.ngev, ngev) + assert_array_equal(ex.nhev, nhev) + assert_array_equal(analit.nhev+approx.nhev, nhev) + H_approx = approx.hess(x) + assert_(isinstance(H_approx, LinearOperator)) + for v in ([1.0, 2.0], [3.0, 4.0], [5.0, 2.0]): + assert_array_almost_equal(H_analit.dot(v), H_approx.dot(v)) + ngev += 4 + assert_array_equal(ex.nfev, nfev) + assert_array_equal(analit.nfev+approx.nfev, nfev) + assert_array_equal(ex.ngev, ngev) + assert_array_equal(analit.ngev+approx.ngev, ngev) + assert_array_equal(ex.nhev, nhev) + assert_array_equal(analit.nhev+approx.nhev, nhev) + + x = [2.1, 1.2] + H_analit = analit.hess(x) + nhev += 1 + assert_array_equal(ex.nfev, nfev) + assert_array_equal(analit.nfev+approx.nfev, nfev) + assert_array_equal(ex.ngev, ngev) + assert_array_equal(analit.ngev+approx.ngev, ngev) + assert_array_equal(ex.nhev, nhev) + assert_array_equal(analit.nhev+approx.nhev, nhev) + H_approx = approx.hess(x) + assert_(isinstance(H_approx, LinearOperator)) + for v in ([1.0, 2.0], [3.0, 4.0], [5.0, 2.0]): + assert_array_almost_equal(H_analit.dot(v), H_approx.dot(v)) + ngev += 4 + assert_array_equal(ex.nfev, nfev) + assert_array_equal(analit.nfev+approx.nfev, nfev) + assert_array_equal(ex.ngev, ngev) + assert_array_equal(analit.ngev+approx.ngev, ngev) + assert_array_equal(ex.nhev, nhev) + assert_array_equal(analit.nhev+approx.nhev, nhev) + + x = [2.5, 0.3] + _ = analit.grad(x) + H_analit = analit.hess(x) + ngev += 1 + nhev += 1 + assert_array_equal(ex.nfev, nfev) + assert_array_equal(analit.nfev+approx.nfev, nfev) + assert_array_equal(ex.ngev, ngev) + assert_array_equal(analit.ngev+approx.ngev, ngev) + assert_array_equal(ex.nhev, nhev) + assert_array_equal(analit.nhev+approx.nhev, nhev) + _ = approx.grad(x) + H_approx = approx.hess(x) + assert_(isinstance(H_approx, LinearOperator)) + for v in ([1.0, 2.0], [3.0, 4.0], [5.0, 2.0]): + assert_array_almost_equal(H_analit.dot(v), H_approx.dot(v)) + ngev += 4 + assert_array_equal(ex.nfev, nfev) + assert_array_equal(analit.nfev+approx.nfev, nfev) + assert_array_equal(ex.ngev, ngev) + assert_array_equal(analit.ngev+approx.ngev, ngev) + assert_array_equal(ex.nhev, nhev) + assert_array_equal(analit.nhev+approx.nhev, nhev) + + x = [5.2, 2.3] + _ = analit.grad(x) + H_analit = analit.hess(x) + ngev += 1 + nhev += 1 + assert_array_equal(ex.nfev, nfev) + assert_array_equal(analit.nfev+approx.nfev, nfev) + assert_array_equal(ex.ngev, ngev) + assert_array_equal(analit.ngev+approx.ngev, ngev) + assert_array_equal(ex.nhev, nhev) + assert_array_equal(analit.nhev+approx.nhev, nhev) + _ = approx.grad(x) + H_approx = approx.hess(x) + assert_(isinstance(H_approx, LinearOperator)) + for v in ([1.0, 2.0], [3.0, 4.0], [5.0, 2.0]): + assert_array_almost_equal(H_analit.dot(v), H_approx.dot(v)) + ngev += 4 + assert_array_equal(ex.nfev, nfev) + assert_array_equal(analit.nfev+approx.nfev, nfev) + assert_array_equal(ex.ngev, ngev) + assert_array_equal(analit.ngev+approx.ngev, ngev) + assert_array_equal(ex.nhev, nhev) + assert_array_equal(analit.nhev+approx.nhev, nhev) + + @pytest.mark.thread_unsafe + def test_x_storage_overlap(self): + # Scalar_Function should not store references to arrays, it should + # store copies - this checks that updating an array in-place causes + # Scalar_Function.x to be updated. + + def f(x): + return np.sum(np.asarray(x) ** 2) + + x = np.array([1., 2., 3.]) + sf = ScalarFunction(f, x, (), '3-point', lambda x: x, None, (-np.inf, np.inf)) + + assert x is not sf.x + assert_equal(sf.fun(x), 14.0) + assert x is not sf.x + + x[0] = 0. + f1 = sf.fun(x) + assert_equal(f1, 13.0) + + x[0] = 1 + f2 = sf.fun(x) + assert_equal(f2, 14.0) + assert x is not sf.x + + # now test with a HessianUpdate strategy specified + hess = BFGS() + x = np.array([1., 2., 3.]) + sf = ScalarFunction(f, x, (), '3-point', hess, None, (-np.inf, np.inf)) + + assert x is not sf.x + assert_equal(sf.fun(x), 14.0) + assert x is not sf.x + + x[0] = 0. + f1 = sf.fun(x) + assert_equal(f1, 13.0) + + x[0] = 1 + f2 = sf.fun(x) + assert_equal(f2, 14.0) + assert x is not sf.x + + # gh13740 x is changed in user function + def ff(x): + x *= x # overwrite x + return np.sum(x) + + x = np.array([1., 2., 3.]) + sf = ScalarFunction( + ff, x, (), '3-point', lambda x: x, None, (-np.inf, np.inf) + ) + assert x is not sf.x + assert_equal(sf.fun(x), 14.0) + assert_equal(sf.x, np.array([1., 2., 3.])) + assert x is not sf.x + + def test_lowest_x(self): + # ScalarFunction should remember the lowest func(x) visited. + x0 = np.array([2, 3, 4]) + sf = ScalarFunction(rosen, x0, (), rosen_der, rosen_hess, + None, None) + sf.fun([1, 1, 1]) + sf.fun(x0) + sf.fun([1.01, 1, 1.0]) + sf.grad([1.01, 1, 1.0]) + assert_equal(sf._lowest_f, 0.0) + assert_equal(sf._lowest_x, [1.0, 1.0, 1.0]) + + sf = ScalarFunction(rosen, x0, (), '2-point', rosen_hess, + None, (-np.inf, np.inf)) + sf.fun([1, 1, 1]) + sf.fun(x0) + sf.fun([1.01, 1, 1.0]) + sf.grad([1.01, 1, 1.0]) + assert_equal(sf._lowest_f, 0.0) + assert_equal(sf._lowest_x, [1.0, 1.0, 1.0]) + + def test_float_size(self): + x0 = np.array([2, 3, 4]).astype(np.float32) + + # check that ScalarFunction/approx_derivative always send the correct + # float width + def rosen_(x): + assert x.dtype == np.float32 + return rosen(x) + + sf = ScalarFunction(rosen_, x0, (), '2-point', rosen_hess, + None, (-np.inf, np.inf)) + res = sf.fun(x0) + assert res.dtype == np.float32 + + +class ExVectorialFunction: + + def __init__(self): + self.nfev = 0 + self.njev = 0 + self.nhev = 0 + + def fun(self, x): + self.nfev += 1 + return np.array([2*(x[0]**2 + x[1]**2 - 1) - x[0], + 4*(x[0]**3 + x[1]**2 - 4) - 3*x[0]], dtype=x.dtype) + + def jac(self, x): + self.njev += 1 + return np.array([[4*x[0]-1, 4*x[1]], + [12*x[0]**2-3, 8*x[1]]], dtype=x.dtype) + + def hess(self, x, v): + self.nhev += 1 + return v[0]*4*np.eye(2) + v[1]*np.array([[24*x[0], 0], + [0, 8]]) + + +class TestVectorialFunction(TestCase): + + def test_finite_difference_jac(self): + ex = ExVectorialFunction() + nfev = 0 + njev = 0 + + x0 = [1.0, 0.0] + analit = VectorFunction(ex.fun, x0, ex.jac, ex.hess, None, None, + (-np.inf, np.inf), None) + nfev += 1 + njev += 1 + assert_array_equal(ex.nfev, nfev) + assert_array_equal(analit.nfev, nfev) + assert_array_equal(ex.njev, njev) + assert_array_equal(analit.njev, njev) + approx = VectorFunction(ex.fun, x0, '2-point', ex.hess, None, None, + (-np.inf, np.inf), None) + nfev += 3 + assert_array_equal(ex.nfev, nfev) + assert_array_equal(analit.nfev+approx.nfev, nfev) + assert_array_equal(ex.njev, njev) + assert_array_equal(analit.njev+approx.njev, njev) + assert_array_equal(analit.f, approx.f) + assert_array_almost_equal(analit.J, approx.J) + + x = [10, 0.3] + f_analit = analit.fun(x) + J_analit = analit.jac(x) + nfev += 1 + njev += 1 + assert_array_equal(ex.nfev, nfev) + assert_array_equal(analit.nfev+approx.nfev, nfev) + assert_array_equal(ex.njev, njev) + assert_array_equal(analit.njev+approx.njev, njev) + f_approx = approx.fun(x) + J_approx = approx.jac(x) + nfev += 3 + assert_array_equal(ex.nfev, nfev) + assert_array_equal(analit.nfev+approx.nfev, nfev) + assert_array_equal(ex.njev, njev) + assert_array_equal(analit.njev+approx.njev, njev) + assert_array_almost_equal(f_analit, f_approx) + assert_array_almost_equal(J_analit, J_approx, decimal=4) + + x = [2.0, 1.0] + J_analit = analit.jac(x) + njev += 1 + assert_array_equal(ex.nfev, nfev) + assert_array_equal(analit.nfev+approx.nfev, nfev) + assert_array_equal(ex.njev, njev) + assert_array_equal(analit.njev+approx.njev, njev) + J_approx = approx.jac(x) + nfev += 3 + assert_array_equal(ex.nfev, nfev) + assert_array_equal(analit.nfev+approx.nfev, nfev) + assert_array_equal(ex.njev, njev) + assert_array_equal(analit.njev+approx.njev, njev) + assert_array_almost_equal(J_analit, J_approx) + + x = [2.5, 0.3] + f_analit = analit.fun(x) + J_analit = analit.jac(x) + nfev += 1 + njev += 1 + assert_array_equal(ex.nfev, nfev) + assert_array_equal(analit.nfev+approx.nfev, nfev) + assert_array_equal(ex.njev, njev) + assert_array_equal(analit.njev+approx.njev, njev) + f_approx = approx.fun(x) + J_approx = approx.jac(x) + nfev += 3 + assert_array_equal(ex.nfev, nfev) + assert_array_equal(analit.nfev+approx.nfev, nfev) + assert_array_equal(ex.njev, njev) + assert_array_equal(analit.njev+approx.njev, njev) + assert_array_almost_equal(f_analit, f_approx) + assert_array_almost_equal(J_analit, J_approx) + + x = [2, 0.3] + f_analit = analit.fun(x) + J_analit = analit.jac(x) + nfev += 1 + njev += 1 + assert_array_equal(ex.nfev, nfev) + assert_array_equal(analit.nfev+approx.nfev, nfev) + assert_array_equal(ex.njev, njev) + assert_array_equal(analit.njev+approx.njev, njev) + f_approx = approx.fun(x) + J_approx = approx.jac(x) + nfev += 3 + assert_array_equal(ex.nfev, nfev) + assert_array_equal(analit.nfev+approx.nfev, nfev) + assert_array_equal(ex.njev, njev) + assert_array_equal(analit.njev+approx.njev, njev) + assert_array_almost_equal(f_analit, f_approx) + assert_array_almost_equal(J_analit, J_approx) + + def test_finite_difference_hess_linear_operator(self): + ex = ExVectorialFunction() + nfev = 0 + njev = 0 + nhev = 0 + + x0 = [1.0, 0.0] + v0 = [1.0, 2.0] + analit = VectorFunction(ex.fun, x0, ex.jac, ex.hess, None, None, + (-np.inf, np.inf), None) + nfev += 1 + njev += 1 + nhev += 1 + assert_array_equal(ex.nfev, nfev) + assert_array_equal(analit.nfev, nfev) + assert_array_equal(ex.njev, njev) + assert_array_equal(analit.njev, njev) + assert_array_equal(ex.nhev, nhev) + assert_array_equal(analit.nhev, nhev) + approx = VectorFunction(ex.fun, x0, ex.jac, '2-point', None, None, + (-np.inf, np.inf), None) + assert_(isinstance(approx.H, LinearOperator)) + for p in ([1.0, 2.0], [3.0, 4.0], [5.0, 2.0]): + assert_array_equal(analit.f, approx.f) + assert_array_almost_equal(analit.J, approx.J) + assert_array_almost_equal(analit.H.dot(p), approx.H.dot(p)) + nfev += 1 + njev += 4 + assert_array_equal(ex.nfev, nfev) + assert_array_equal(analit.nfev+approx.nfev, nfev) + assert_array_equal(ex.njev, njev) + assert_array_equal(analit.njev+approx.njev, njev) + assert_array_equal(ex.nhev, nhev) + assert_array_equal(analit.nhev+approx.nhev, nhev) + + x = [2.0, 1.0] + H_analit = analit.hess(x, v0) + nhev += 1 + assert_array_equal(ex.nfev, nfev) + assert_array_equal(analit.nfev+approx.nfev, nfev) + assert_array_equal(ex.njev, njev) + assert_array_equal(analit.njev+approx.njev, njev) + assert_array_equal(ex.nhev, nhev) + assert_array_equal(analit.nhev+approx.nhev, nhev) + H_approx = approx.hess(x, v0) + assert_(isinstance(H_approx, LinearOperator)) + for p in ([1.0, 2.0], [3.0, 4.0], [5.0, 2.0]): + assert_array_almost_equal(H_analit.dot(p), H_approx.dot(p), + decimal=5) + njev += 4 + assert_array_equal(ex.nfev, nfev) + assert_array_equal(analit.nfev+approx.nfev, nfev) + assert_array_equal(ex.njev, njev) + assert_array_equal(analit.njev+approx.njev, njev) + assert_array_equal(ex.nhev, nhev) + assert_array_equal(analit.nhev+approx.nhev, nhev) + + x = [2.1, 1.2] + v = [1.0, 1.0] + H_analit = analit.hess(x, v) + nhev += 1 + assert_array_equal(ex.nfev, nfev) + assert_array_equal(analit.nfev+approx.nfev, nfev) + assert_array_equal(ex.njev, njev) + assert_array_equal(analit.njev+approx.njev, njev) + assert_array_equal(ex.nhev, nhev) + assert_array_equal(analit.nhev+approx.nhev, nhev) + H_approx = approx.hess(x, v) + assert_(isinstance(H_approx, LinearOperator)) + for v in ([1.0, 2.0], [3.0, 4.0], [5.0, 2.0]): + assert_array_almost_equal(H_analit.dot(v), H_approx.dot(v)) + njev += 4 + assert_array_equal(ex.nfev, nfev) + assert_array_equal(analit.nfev+approx.nfev, nfev) + assert_array_equal(ex.njev, njev) + assert_array_equal(analit.njev+approx.njev, njev) + assert_array_equal(ex.nhev, nhev) + assert_array_equal(analit.nhev+approx.nhev, nhev) + + x = [2.5, 0.3] + _ = analit.jac(x) + H_analit = analit.hess(x, v0) + njev += 1 + nhev += 1 + assert_array_equal(ex.nfev, nfev) + assert_array_equal(analit.nfev+approx.nfev, nfev) + assert_array_equal(ex.njev, njev) + assert_array_equal(analit.njev+approx.njev, njev) + assert_array_equal(ex.nhev, nhev) + assert_array_equal(analit.nhev+approx.nhev, nhev) + _ = approx.jac(x) + H_approx = approx.hess(x, v0) + assert_(isinstance(H_approx, LinearOperator)) + for v in ([1.0, 2.0], [3.0, 4.0], [5.0, 2.0]): + assert_array_almost_equal(H_analit.dot(v), H_approx.dot(v), decimal=4) + njev += 4 + assert_array_equal(ex.nfev, nfev) + assert_array_equal(analit.nfev+approx.nfev, nfev) + assert_array_equal(ex.njev, njev) + assert_array_equal(analit.njev+approx.njev, njev) + assert_array_equal(ex.nhev, nhev) + assert_array_equal(analit.nhev+approx.nhev, nhev) + + x = [5.2, 2.3] + v = [2.3, 5.2] + _ = analit.jac(x) + H_analit = analit.hess(x, v) + njev += 1 + nhev += 1 + assert_array_equal(ex.nfev, nfev) + assert_array_equal(analit.nfev+approx.nfev, nfev) + assert_array_equal(ex.njev, njev) + assert_array_equal(analit.njev+approx.njev, njev) + assert_array_equal(ex.nhev, nhev) + assert_array_equal(analit.nhev+approx.nhev, nhev) + _ = approx.jac(x) + H_approx = approx.hess(x, v) + assert_(isinstance(H_approx, LinearOperator)) + for v in ([1.0, 2.0], [3.0, 4.0], [5.0, 2.0]): + assert_array_almost_equal(H_analit.dot(v), H_approx.dot(v), decimal=4) + njev += 4 + assert_array_equal(ex.nfev, nfev) + assert_array_equal(analit.nfev+approx.nfev, nfev) + assert_array_equal(ex.njev, njev) + assert_array_equal(analit.njev+approx.njev, njev) + assert_array_equal(ex.nhev, nhev) + assert_array_equal(analit.nhev+approx.nhev, nhev) + + @pytest.mark.thread_unsafe + def test_x_storage_overlap(self): + # VectorFunction should not store references to arrays, it should + # store copies - this checks that updating an array in-place causes + # Scalar_Function.x to be updated. + ex = ExVectorialFunction() + x0 = np.array([1.0, 0.0]) + + vf = VectorFunction(ex.fun, x0, '3-point', ex.hess, None, None, + (-np.inf, np.inf), None) + + assert x0 is not vf.x + assert_equal(vf.fun(x0), ex.fun(x0)) + assert x0 is not vf.x + + x0[0] = 2. + assert_equal(vf.fun(x0), ex.fun(x0)) + assert x0 is not vf.x + + x0[0] = 1. + assert_equal(vf.fun(x0), ex.fun(x0)) + assert x0 is not vf.x + + # now test with a HessianUpdate strategy specified + hess = BFGS() + x0 = np.array([1.0, 0.0]) + vf = VectorFunction(ex.fun, x0, '3-point', hess, None, None, + (-np.inf, np.inf), None) + + with pytest.warns(UserWarning): + # filter UserWarning because ExVectorialFunction is linear and + # a quasi-Newton approximation is used for the Hessian. + assert x0 is not vf.x + assert_equal(vf.fun(x0), ex.fun(x0)) + assert x0 is not vf.x + + x0[0] = 2. + assert_equal(vf.fun(x0), ex.fun(x0)) + assert x0 is not vf.x + + x0[0] = 1. + assert_equal(vf.fun(x0), ex.fun(x0)) + assert x0 is not vf.x + + def test_float_size(self): + ex = ExVectorialFunction() + x0 = np.array([1.0, 0.0]).astype(np.float32) + + vf = VectorFunction(ex.fun, x0, ex.jac, ex.hess, None, None, + (-np.inf, np.inf), None) + + res = vf.fun(x0) + assert res.dtype == np.float32 + + res = vf.jac(x0) + assert res.dtype == np.float32 + + +def test_LinearVectorFunction(): + A_dense = np.array([ + [-1, 2, 0], + [0, 4, 2] + ]) + x0 = np.zeros(3) + A_sparse = csr_matrix(A_dense) + x = np.array([1, -1, 0]) + v = np.array([-1, 1]) + Ax = np.array([-3, -4]) + + f1 = LinearVectorFunction(A_dense, x0, None) + assert_(not f1.sparse_jacobian) + + f2 = LinearVectorFunction(A_dense, x0, True) + assert_(f2.sparse_jacobian) + + f3 = LinearVectorFunction(A_dense, x0, False) + assert_(not f3.sparse_jacobian) + + f4 = LinearVectorFunction(A_sparse, x0, None) + assert_(f4.sparse_jacobian) + + f5 = LinearVectorFunction(A_sparse, x0, True) + assert_(f5.sparse_jacobian) + + f6 = LinearVectorFunction(A_sparse, x0, False) + assert_(not f6.sparse_jacobian) + + assert_array_equal(f1.fun(x), Ax) + assert_array_equal(f2.fun(x), Ax) + assert_array_equal(f1.jac(x), A_dense) + assert_array_equal(f2.jac(x).toarray(), A_sparse.toarray()) + assert_array_equal(f1.hess(x, v).toarray(), np.zeros((3, 3))) + + +def test_LinearVectorFunction_memoization(): + A = np.array([[-1, 2, 0], [0, 4, 2]]) + x0 = np.array([1, 2, -1]) + fun = LinearVectorFunction(A, x0, False) + + assert_array_equal(x0, fun.x) + assert_array_equal(A.dot(x0), fun.f) + + x1 = np.array([-1, 3, 10]) + assert_array_equal(A, fun.jac(x1)) + assert_array_equal(x1, fun.x) + assert_array_equal(A.dot(x0), fun.f) + assert_array_equal(A.dot(x1), fun.fun(x1)) + assert_array_equal(A.dot(x1), fun.f) + + +def test_IdentityVectorFunction(): + x0 = np.zeros(3) + + f1 = IdentityVectorFunction(x0, None) + f2 = IdentityVectorFunction(x0, False) + f3 = IdentityVectorFunction(x0, True) + + assert_(f1.sparse_jacobian) + assert_(not f2.sparse_jacobian) + assert_(f3.sparse_jacobian) + + x = np.array([-1, 2, 1]) + v = np.array([-2, 3, 0]) + + assert_array_equal(f1.fun(x), x) + assert_array_equal(f2.fun(x), x) + + assert_array_equal(f1.jac(x).toarray(), np.eye(3)) + assert_array_equal(f2.jac(x), np.eye(3)) + + assert_array_equal(f1.hess(x, v).toarray(), np.zeros((3, 3))) + + +@pytest.mark.skipif( + platform.python_implementation() == "PyPy", + reason="assert_deallocate not available on PyPy" +) +def test_ScalarFunctionNoReferenceCycle(): + """Regression test for gh-20768.""" + ex = ExScalarFunction() + x0 = np.zeros(3) + with assert_deallocated(lambda: ScalarFunction(ex.fun, x0, (), ex.grad, + ex.hess, None, (-np.inf, np.inf))): + pass + + +@pytest.mark.skipif( + platform.python_implementation() == "PyPy", + reason="assert_deallocate not available on PyPy" +) +@pytest.mark.xfail(reason="TODO remove reference cycle from VectorFunction") +def test_VectorFunctionNoReferenceCycle(): + """Regression test for gh-20768.""" + ex = ExVectorialFunction() + x0 = [1.0, 0.0] + with assert_deallocated(lambda: VectorFunction(ex.fun, x0, ex.jac, + ex.hess, None, None, (-np.inf, np.inf), None)): + pass + + +@pytest.mark.skipif( + platform.python_implementation() == "PyPy", + reason="assert_deallocate not available on PyPy" +) +def test_LinearVectorFunctionNoReferenceCycle(): + """Regression test for gh-20768.""" + A_dense = np.array([ + [-1, 2, 0], + [0, 4, 2] + ]) + x0 = np.zeros(3) + A_sparse = csr_matrix(A_dense) + with assert_deallocated(lambda: LinearVectorFunction(A_sparse, x0, None)): + pass diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_direct.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_direct.py new file mode 100644 index 0000000000000000000000000000000000000000..835d3164c8d547599a507550dcc7629e7d327394 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_direct.py @@ -0,0 +1,321 @@ +""" +Unit test for DIRECT optimization algorithm. +""" +from numpy.testing import (assert_allclose, + assert_array_less) +import pytest +import numpy as np +from scipy.optimize import direct, Bounds +import threading + + +class TestDIRECT: + + def setup_method(self): + self.fun_calls = threading.local() + self.bounds_sphere = 4*[(-2, 3)] + self.optimum_sphere_pos = np.zeros((4, )) + self.optimum_sphere = 0.0 + self.bounds_stylinski_tang = Bounds([-4., -4.], [4., 4.]) + self.maxiter = 1000 + + # test functions + def sphere(self, x): + if not hasattr(self.fun_calls, 'c'): + self.fun_calls.c = 0 + self.fun_calls.c += 1 + return np.square(x).sum() + + def inv(self, x): + if np.sum(x) == 0: + raise ZeroDivisionError() + return 1/np.sum(x) + + def nan_fun(self, x): + return np.nan + + def inf_fun(self, x): + return np.inf + + def styblinski_tang(self, pos): + x, y = pos + return 0.5 * (x**4 - 16 * x**2 + 5 * x + y**4 - 16 * y**2 + 5 * y) + + @pytest.mark.parametrize("locally_biased", [True, False]) + def test_direct(self, locally_biased): + res = direct(self.sphere, self.bounds_sphere, + locally_biased=locally_biased) + + # test accuracy + assert_allclose(res.x, self.optimum_sphere_pos, + rtol=1e-3, atol=1e-3) + assert_allclose(res.fun, self.optimum_sphere, atol=1e-5, rtol=1e-5) + + # test that result lies within bounds + _bounds = np.asarray(self.bounds_sphere) + assert_array_less(_bounds[:, 0], res.x) + assert_array_less(res.x, _bounds[:, 1]) + + # test number of function evaluations. Original DIRECT overshoots by + # up to 500 evaluations in last iteration + assert res.nfev <= 1000 * (len(self.bounds_sphere) + 1) + # test that number of function evaluations is correct + assert res.nfev == self.fun_calls.c + + # test that number of iterations is below supplied maximum + assert res.nit <= self.maxiter + + @pytest.mark.parametrize("locally_biased", [True, False]) + def test_direct_callback(self, locally_biased): + # test that callback does not change the result + res = direct(self.sphere, self.bounds_sphere, + locally_biased=locally_biased) + + def callback(x): + x = 2*x + dummy = np.square(x) + print("DIRECT minimization algorithm callback test") + return dummy + + res_callback = direct(self.sphere, self.bounds_sphere, + locally_biased=locally_biased, + callback=callback) + + assert_allclose(res.x, res_callback.x) + + assert res.nit == res_callback.nit + assert res.nfev == res_callback.nfev + assert res.status == res_callback.status + assert res.success == res_callback.success + assert res.fun == res_callback.fun + assert_allclose(res.x, res_callback.x) + assert res.message == res_callback.message + + # test accuracy + assert_allclose(res_callback.x, self.optimum_sphere_pos, + rtol=1e-3, atol=1e-3) + assert_allclose(res_callback.fun, self.optimum_sphere, + atol=1e-5, rtol=1e-5) + + @pytest.mark.parametrize("locally_biased", [True, False]) + def test_exception(self, locally_biased): + bounds = 4*[(-10, 10)] + with pytest.raises(ZeroDivisionError): + direct(self.inv, bounds=bounds, + locally_biased=locally_biased) + + @pytest.mark.parametrize("locally_biased", [True, False]) + def test_nan(self, locally_biased): + bounds = 4*[(-10, 10)] + direct(self.nan_fun, bounds=bounds, + locally_biased=locally_biased) + + @pytest.mark.parametrize("len_tol", [1e-3, 1e-4]) + @pytest.mark.parametrize("locally_biased", [True, False]) + def test_len_tol(self, len_tol, locally_biased): + bounds = 4*[(-10., 10.)] + res = direct(self.sphere, bounds=bounds, len_tol=len_tol, + vol_tol=1e-30, locally_biased=locally_biased) + assert res.status == 5 + assert res.success + assert_allclose(res.x, np.zeros((4, ))) + message = ("The side length measure of the hyperrectangle containing " + "the lowest function value found is below " + f"len_tol={len_tol}") + assert res.message == message + + @pytest.mark.parametrize("vol_tol", [1e-6, 1e-8]) + @pytest.mark.parametrize("locally_biased", [True, False]) + def test_vol_tol(self, vol_tol, locally_biased): + bounds = 4*[(-10., 10.)] + res = direct(self.sphere, bounds=bounds, vol_tol=vol_tol, + len_tol=0., locally_biased=locally_biased) + assert res.status == 4 + assert res.success + assert_allclose(res.x, np.zeros((4, ))) + message = ("The volume of the hyperrectangle containing the lowest " + f"function value found is below vol_tol={vol_tol}") + assert res.message == message + + @pytest.mark.parametrize("f_min_rtol", [1e-3, 1e-5, 1e-7]) + @pytest.mark.parametrize("locally_biased", [True, False]) + def test_f_min(self, f_min_rtol, locally_biased): + # test that desired function value is reached within + # relative tolerance of f_min_rtol + f_min = 1. + bounds = 4*[(-2., 10.)] + res = direct(self.sphere, bounds=bounds, f_min=f_min, + f_min_rtol=f_min_rtol, + locally_biased=locally_biased) + assert res.status == 3 + assert res.success + assert res.fun < f_min * (1. + f_min_rtol) + message = ("The best function value found is within a relative " + f"error={f_min_rtol} of the (known) global optimum f_min") + assert res.message == message + + def circle_with_args(self, x, a, b): + return np.square(x[0] - a) + np.square(x[1] - b).sum() + + @pytest.mark.parametrize("locally_biased", [True, False]) + def test_f_circle_with_args(self, locally_biased): + bounds = 2*[(-2.0, 2.0)] + + res = direct(self.circle_with_args, bounds, args=(1, 1), maxfun=1250, + locally_biased=locally_biased) + assert_allclose(res.x, np.array([1., 1.]), rtol=1e-5) + + @pytest.mark.parametrize("locally_biased", [True, False]) + def test_failure_maxfun(self, locally_biased): + # test that if optimization runs for the maximal number of + # evaluations, success = False is returned + + maxfun = 100 + result = direct(self.styblinski_tang, self.bounds_stylinski_tang, + maxfun=maxfun, locally_biased=locally_biased) + assert result.success is False + assert result.status == 1 + assert result.nfev >= maxfun + message = ("Number of function evaluations done is " + f"larger than maxfun={maxfun}") + assert result.message == message + + @pytest.mark.parametrize("locally_biased", [True, False]) + def test_failure_maxiter(self, locally_biased): + # test that if optimization runs for the maximal number of + # iterations, success = False is returned + + maxiter = 10 + result = direct(self.styblinski_tang, self.bounds_stylinski_tang, + maxiter=maxiter, locally_biased=locally_biased) + assert result.success is False + assert result.status == 2 + assert result.nit >= maxiter + message = f"Number of iterations is larger than maxiter={maxiter}" + assert result.message == message + + @pytest.mark.parametrize("locally_biased", [True, False]) + def test_bounds_variants(self, locally_biased): + # test that new and old bounds yield same result + + lb = [-6., 1., -5.] + ub = [-1., 3., 5.] + x_opt = np.array([-1., 1., 0.]) + bounds_old = list(zip(lb, ub)) + bounds_new = Bounds(lb, ub) + + res_old_bounds = direct(self.sphere, bounds_old, + locally_biased=locally_biased) + res_new_bounds = direct(self.sphere, bounds_new, + locally_biased=locally_biased) + + assert res_new_bounds.nfev == res_old_bounds.nfev + assert res_new_bounds.message == res_old_bounds.message + assert res_new_bounds.success == res_old_bounds.success + assert res_new_bounds.nit == res_old_bounds.nit + assert_allclose(res_new_bounds.x, res_old_bounds.x) + assert_allclose(res_new_bounds.x, x_opt, rtol=1e-2) + + @pytest.mark.parametrize("locally_biased", [True, False]) + @pytest.mark.parametrize("eps", [1e-5, 1e-4, 1e-3]) + def test_epsilon(self, eps, locally_biased): + result = direct(self.styblinski_tang, self.bounds_stylinski_tang, + eps=eps, vol_tol=1e-6, + locally_biased=locally_biased) + assert result.status == 4 + assert result.success + + @pytest.mark.xslow + @pytest.mark.parametrize("locally_biased", [True, False]) + def test_no_segmentation_fault(self, locally_biased): + # test that an excessive number of function evaluations + # does not result in segmentation fault + bounds = [(-5., 20.)] * 100 + result = direct(self.sphere, bounds, maxfun=10000000, + maxiter=1000000, locally_biased=locally_biased) + assert result is not None + + @pytest.mark.parametrize("locally_biased", [True, False]) + def test_inf_fun(self, locally_biased): + # test that an objective value of infinity does not crash DIRECT + bounds = [(-5., 5.)] * 2 + result = direct(self.inf_fun, bounds, + locally_biased=locally_biased) + assert result is not None + + @pytest.mark.parametrize("len_tol", [-1, 2]) + def test_len_tol_validation(self, len_tol): + error_msg = "len_tol must be between 0 and 1." + with pytest.raises(ValueError, match=error_msg): + direct(self.styblinski_tang, self.bounds_stylinski_tang, + len_tol=len_tol) + + @pytest.mark.parametrize("vol_tol", [-1, 2]) + def test_vol_tol_validation(self, vol_tol): + error_msg = "vol_tol must be between 0 and 1." + with pytest.raises(ValueError, match=error_msg): + direct(self.styblinski_tang, self.bounds_stylinski_tang, + vol_tol=vol_tol) + + @pytest.mark.parametrize("f_min_rtol", [-1, 2]) + def test_fmin_rtol_validation(self, f_min_rtol): + error_msg = "f_min_rtol must be between 0 and 1." + with pytest.raises(ValueError, match=error_msg): + direct(self.styblinski_tang, self.bounds_stylinski_tang, + f_min_rtol=f_min_rtol, f_min=0.) + + @pytest.mark.parametrize("maxfun", [1.5, "string", (1, 2)]) + def test_maxfun_wrong_type(self, maxfun): + error_msg = "maxfun must be of type int." + with pytest.raises(ValueError, match=error_msg): + direct(self.styblinski_tang, self.bounds_stylinski_tang, + maxfun=maxfun) + + @pytest.mark.parametrize("maxiter", [1.5, "string", (1, 2)]) + def test_maxiter_wrong_type(self, maxiter): + error_msg = "maxiter must be of type int." + with pytest.raises(ValueError, match=error_msg): + direct(self.styblinski_tang, self.bounds_stylinski_tang, + maxiter=maxiter) + + def test_negative_maxiter(self): + error_msg = "maxiter must be > 0." + with pytest.raises(ValueError, match=error_msg): + direct(self.styblinski_tang, self.bounds_stylinski_tang, + maxiter=-1) + + def test_negative_maxfun(self): + error_msg = "maxfun must be > 0." + with pytest.raises(ValueError, match=error_msg): + direct(self.styblinski_tang, self.bounds_stylinski_tang, + maxfun=-1) + + @pytest.mark.parametrize("bounds", ["bounds", 2., 0]) + def test_invalid_bounds_type(self, bounds): + error_msg = ("bounds must be a sequence or " + "instance of Bounds class") + with pytest.raises(ValueError, match=error_msg): + direct(self.styblinski_tang, bounds) + + @pytest.mark.parametrize("bounds", + [Bounds([-1., -1], [-2, 1]), + Bounds([-np.nan, -1], [-2, np.nan]), + ] + ) + def test_incorrect_bounds(self, bounds): + error_msg = 'Bounds are not consistent min < max' + with pytest.raises(ValueError, match=error_msg): + direct(self.styblinski_tang, bounds) + + def test_inf_bounds(self): + error_msg = 'Bounds must not be inf.' + bounds = Bounds([-np.inf, -1], [-2, np.inf]) + with pytest.raises(ValueError, match=error_msg): + direct(self.styblinski_tang, bounds) + + @pytest.mark.parametrize("locally_biased", ["bias", [0, 0], 2.]) + def test_locally_biased_validation(self, locally_biased): + error_msg = 'locally_biased must be True or False.' + with pytest.raises(ValueError, match=error_msg): + direct(self.styblinski_tang, self.bounds_stylinski_tang, + locally_biased=locally_biased) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_extending.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_extending.py new file mode 100644 index 0000000000000000000000000000000000000000..279cac794e5f453fee52f19026f96eb530259485 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_extending.py @@ -0,0 +1,28 @@ +import os +import platform +import sysconfig + +import pytest + +from scipy._lib._testutils import IS_EDITABLE, _test_cython_extension, cython + + +@pytest.mark.fail_slow(40) +# essential per https://github.com/scipy/scipy/pull/20487#discussion_r1567057247 +@pytest.mark.skipif(IS_EDITABLE, + reason='Editable install cannot find .pxd headers.') +@pytest.mark.skipif((platform.system() == 'Windows' and + sysconfig.get_config_var('Py_GIL_DISABLED')), + reason='gh-22039') +@pytest.mark.skipif(platform.machine() in ["wasm32", "wasm64"], + reason="Can't start subprocess") +@pytest.mark.skipif(cython is None, reason="requires cython") +def test_cython(tmp_path): + srcdir = os.path.dirname(os.path.dirname(__file__)) + extensions, extensions_cpp = _test_cython_extension(tmp_path, srcdir) + # actually test the cython c-extensions + # From docstring for scipy.optimize.cython_optimize module + x = extensions.brentq_example() + assert x == 0.6999942848231314 + x = extensions_cpp.brentq_example() + assert x == 0.6999942848231314 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_hessian_update_strategy.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_hessian_update_strategy.py new file mode 100644 index 0000000000000000000000000000000000000000..2434e92434ff2ecc74ce2e8b8119632207fd0853 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_hessian_update_strategy.py @@ -0,0 +1,300 @@ +import re +from copy import deepcopy + +import numpy as np +import pytest +from numpy.linalg import norm +from numpy.testing import (TestCase, assert_array_almost_equal, + assert_array_equal, assert_array_less) +from scipy.optimize import (BFGS, SR1) + + +class Rosenbrock: + """Rosenbrock function. + + The following optimization problem: + minimize sum(100.0*(x[1:] - x[:-1]**2.0)**2.0 + (1 - x[:-1])**2.0) + """ + + def __init__(self, n=2, random_state=0): + rng = np.random.RandomState(random_state) + self.x0 = rng.uniform(-1, 1, n) + self.x_opt = np.ones(n) + + def fun(self, x): + x = np.asarray(x) + r = np.sum(100.0 * (x[1:] - x[:-1]**2.0)**2.0 + (1 - x[:-1])**2.0, + axis=0) + return r + + def grad(self, x): + x = np.asarray(x) + xm = x[1:-1] + xm_m1 = x[:-2] + xm_p1 = x[2:] + der = np.zeros_like(x) + der[1:-1] = (200 * (xm - xm_m1**2) - + 400 * (xm_p1 - xm**2) * xm - 2 * (1 - xm)) + der[0] = -400 * x[0] * (x[1] - x[0]**2) - 2 * (1 - x[0]) + der[-1] = 200 * (x[-1] - x[-2]**2) + return der + + def hess(self, x): + x = np.atleast_1d(x) + H = np.diag(-400 * x[:-1], 1) - np.diag(400 * x[:-1], -1) + diagonal = np.zeros(len(x), dtype=x.dtype) + diagonal[0] = 1200 * x[0]**2 - 400 * x[1] + 2 + diagonal[-1] = 200 + diagonal[1:-1] = 202 + 1200 * x[1:-1]**2 - 400 * x[2:] + H = H + np.diag(diagonal) + return H + + +class TestHessianUpdateStrategy(TestCase): + + + def test_hessian_initialization(self): + + ndims = 5 + symmetric_matrix = np.array([[43, 24, 33, 34, 49], + [24, 36, 44, 15, 44], + [33, 44, 37, 1, 30], + [34, 15, 1, 5, 46], + [49, 44, 30, 46, 22]]) + init_scales = ( + ('auto', np.eye(ndims)), + (2, np.eye(ndims) * 2), + (np.arange(1, ndims + 1) * np.eye(ndims), + np.arange(1, ndims + 1) * np.eye(ndims)), + (symmetric_matrix, symmetric_matrix),) + for approx_type in ['hess', 'inv_hess']: + for init_scale, true_matrix in init_scales: + # large min_{denominator,curvatur} makes them skip an update, + # so we can have our initial matrix + quasi_newton = (BFGS(init_scale=init_scale, + min_curvature=1e50, + exception_strategy='skip_update'), + SR1(init_scale=init_scale, + min_denominator=1e50)) + + for qn in quasi_newton: + qn.initialize(ndims, approx_type) + B = qn.get_matrix() + + assert_array_equal(B, np.eye(ndims)) + # don't test the auto init scale + if isinstance(init_scale, str) and init_scale == 'auto': + continue + + qn.update(np.ones(ndims) * 1e-5, np.arange(ndims) + 0.2) + B = qn.get_matrix() + assert_array_equal(B, true_matrix) + + # For this list of points, it is known + # that no exception occur during the + # Hessian update. Hence no update is + # skiped or damped. + + + def test_initialize_catch_illegal(self): + ndims = 3 + # no complex allowed + inits_msg_errtype = ((complex(3.14), + r"float\(\) argument must be a string or a " + r"(real )?number, not 'complex'", + TypeError), + + (np.array([3.2, 2.3, 1.2]).astype(np.complex128), + "init_scale contains complex elements, " + "must be real.", + TypeError), + + (np.array([[43, 24, 33], + [24, 36, 44, ], + [33, 44, 37, ]]).astype(np.complex128), + "init_scale contains complex elements, " + "must be real.", + TypeError), + + # not square + (np.array([[43, 55, 66]]), + re.escape( + "If init_scale is an array, it must have the " + "dimensions of the hess/inv_hess: (3, 3)." + " Got (1, 3)."), + ValueError), + + # not symmetric + (np.array([[43, 24, 33], + [24.1, 36, 44, ], + [33, 44, 37, ]]), + re.escape("If init_scale is an array, it must be" + " symmetric (passing scipy.linalg.issymmetric)" + " to be an approximation of a hess/inv_hess."), + ValueError), + ) + for approx_type in ['hess', 'inv_hess']: + for init_scale, message, errortype in inits_msg_errtype: + # large min_{denominator,curvatur} makes it skip an update, + # so we can retrieve our initial matrix + quasi_newton = (BFGS(init_scale=init_scale), + SR1(init_scale=init_scale)) + + for qn in quasi_newton: + qn.initialize(ndims, approx_type) + with pytest.raises(errortype, match=message): + qn.update(np.ones(ndims), np.arange(ndims)) + + def test_rosenbrock_with_no_exception(self): + # Define auxiliary problem + prob = Rosenbrock(n=5) + # Define iteration points + x_list = [[0.0976270, 0.4303787, 0.2055267, 0.0897663, -0.15269040], + [0.1847239, 0.0505757, 0.2123832, 0.0255081, 0.00083286], + [0.2142498, -0.0188480, 0.0503822, 0.0347033, 0.03323606], + [0.2071680, -0.0185071, 0.0341337, -0.0139298, 0.02881750], + [0.1533055, -0.0322935, 0.0280418, -0.0083592, 0.01503699], + [0.1382378, -0.0276671, 0.0266161, -0.0074060, 0.02801610], + [0.1651957, -0.0049124, 0.0269665, -0.0040025, 0.02138184], + [0.2354930, 0.0443711, 0.0173959, 0.0041872, 0.00794563], + [0.4168118, 0.1433867, 0.0111714, 0.0126265, -0.00658537], + [0.4681972, 0.2153273, 0.0225249, 0.0152704, -0.00463809], + [0.6023068, 0.3346815, 0.0731108, 0.0186618, -0.00371541], + [0.6415743, 0.3985468, 0.1324422, 0.0214160, -0.00062401], + [0.7503690, 0.5447616, 0.2804541, 0.0539851, 0.00242230], + [0.7452626, 0.5644594, 0.3324679, 0.0865153, 0.00454960], + [0.8059782, 0.6586838, 0.4229577, 0.1452990, 0.00976702], + [0.8549542, 0.7226562, 0.4991309, 0.2420093, 0.02772661], + [0.8571332, 0.7285741, 0.5279076, 0.2824549, 0.06030276], + [0.8835633, 0.7727077, 0.5957984, 0.3411303, 0.09652185], + [0.9071558, 0.8299587, 0.6771400, 0.4402896, 0.17469338], + [0.9190793, 0.8486480, 0.7163332, 0.5083780, 0.26107691], + [0.9371223, 0.8762177, 0.7653702, 0.5773109, 0.32181041], + [0.9554613, 0.9119893, 0.8282687, 0.6776178, 0.43162744], + [0.9545744, 0.9099264, 0.8270244, 0.6822220, 0.45237623], + [0.9688112, 0.9351710, 0.8730961, 0.7546601, 0.56622448], + [0.9743227, 0.9491953, 0.9005150, 0.8086497, 0.64505437], + [0.9807345, 0.9638853, 0.9283012, 0.8631675, 0.73812581], + [0.9886746, 0.9777760, 0.9558950, 0.9123417, 0.82726553], + [0.9899096, 0.9803828, 0.9615592, 0.9255600, 0.85822149], + [0.9969510, 0.9935441, 0.9864657, 0.9726775, 0.94358663], + [0.9979533, 0.9960274, 0.9921724, 0.9837415, 0.96626288], + [0.9995981, 0.9989171, 0.9974178, 0.9949954, 0.99023356], + [1.0002640, 1.0005088, 1.0010594, 1.0021161, 1.00386912], + [0.9998903, 0.9998459, 0.9997795, 0.9995484, 0.99916305], + [1.0000008, 0.9999905, 0.9999481, 0.9998903, 0.99978047], + [1.0000004, 0.9999983, 1.0000001, 1.0000031, 1.00000297], + [0.9999995, 1.0000003, 1.0000005, 1.0000001, 1.00000032], + [0.9999999, 0.9999997, 0.9999994, 0.9999989, 0.99999786], + [0.9999999, 0.9999999, 0.9999999, 0.9999999, 0.99999991]] + # Get iteration points + grad_list = [prob.grad(x) for x in x_list] + delta_x = [np.array(x_list[i+1])-np.array(x_list[i]) + for i in range(len(x_list)-1)] + delta_grad = [grad_list[i+1]-grad_list[i] + for i in range(len(grad_list)-1)] + # Check curvature condition + for s, y in zip(delta_x, delta_grad): + if np.dot(s, y) <= 0: + raise ArithmeticError() + # Define QuasiNewton update + for quasi_newton in (BFGS(init_scale=1, min_curvature=1e-4), + SR1(init_scale=1)): + hess = deepcopy(quasi_newton) + inv_hess = deepcopy(quasi_newton) + hess.initialize(len(x_list[0]), 'hess') + inv_hess.initialize(len(x_list[0]), 'inv_hess') + # Compare the hessian and its inverse + for s, y in zip(delta_x, delta_grad): + hess.update(s, y) + inv_hess.update(s, y) + B = hess.get_matrix() + H = inv_hess.get_matrix() + assert_array_almost_equal(np.linalg.inv(B), H, decimal=10) + B_true = prob.hess(x_list[len(delta_x)]) + assert_array_less(norm(B - B_true)/norm(B_true), 0.1) + + def test_SR1_skip_update(self): + # Define auxiliary problem + prob = Rosenbrock(n=5) + # Define iteration points + x_list = [[0.0976270, 0.4303787, 0.2055267, 0.0897663, -0.15269040], + [0.1847239, 0.0505757, 0.2123832, 0.0255081, 0.00083286], + [0.2142498, -0.0188480, 0.0503822, 0.0347033, 0.03323606], + [0.2071680, -0.0185071, 0.0341337, -0.0139298, 0.02881750], + [0.1533055, -0.0322935, 0.0280418, -0.0083592, 0.01503699], + [0.1382378, -0.0276671, 0.0266161, -0.0074060, 0.02801610], + [0.1651957, -0.0049124, 0.0269665, -0.0040025, 0.02138184], + [0.2354930, 0.0443711, 0.0173959, 0.0041872, 0.00794563], + [0.4168118, 0.1433867, 0.0111714, 0.0126265, -0.00658537], + [0.4681972, 0.2153273, 0.0225249, 0.0152704, -0.00463809], + [0.6023068, 0.3346815, 0.0731108, 0.0186618, -0.00371541], + [0.6415743, 0.3985468, 0.1324422, 0.0214160, -0.00062401], + [0.7503690, 0.5447616, 0.2804541, 0.0539851, 0.00242230], + [0.7452626, 0.5644594, 0.3324679, 0.0865153, 0.00454960], + [0.8059782, 0.6586838, 0.4229577, 0.1452990, 0.00976702], + [0.8549542, 0.7226562, 0.4991309, 0.2420093, 0.02772661], + [0.8571332, 0.7285741, 0.5279076, 0.2824549, 0.06030276], + [0.8835633, 0.7727077, 0.5957984, 0.3411303, 0.09652185], + [0.9071558, 0.8299587, 0.6771400, 0.4402896, 0.17469338]] + # Get iteration points + grad_list = [prob.grad(x) for x in x_list] + delta_x = [np.array(x_list[i+1])-np.array(x_list[i]) + for i in range(len(x_list)-1)] + delta_grad = [grad_list[i+1]-grad_list[i] + for i in range(len(grad_list)-1)] + hess = SR1(init_scale=1, min_denominator=1e-2) + hess.initialize(len(x_list[0]), 'hess') + # Compare the Hessian and its inverse + for i in range(len(delta_x)-1): + s = delta_x[i] + y = delta_grad[i] + hess.update(s, y) + # Test skip update + B = np.copy(hess.get_matrix()) + s = delta_x[17] + y = delta_grad[17] + hess.update(s, y) + B_updated = np.copy(hess.get_matrix()) + assert_array_equal(B, B_updated) + + def test_BFGS_skip_update(self): + # Define auxiliary problem + prob = Rosenbrock(n=5) + # Define iteration points + x_list = [[0.0976270, 0.4303787, 0.2055267, 0.0897663, -0.15269040], + [0.1847239, 0.0505757, 0.2123832, 0.0255081, 0.00083286], + [0.2142498, -0.0188480, 0.0503822, 0.0347033, 0.03323606], + [0.2071680, -0.0185071, 0.0341337, -0.0139298, 0.02881750], + [0.1533055, -0.0322935, 0.0280418, -0.0083592, 0.01503699], + [0.1382378, -0.0276671, 0.0266161, -0.0074060, 0.02801610], + [0.1651957, -0.0049124, 0.0269665, -0.0040025, 0.02138184]] + # Get iteration points + grad_list = [prob.grad(x) for x in x_list] + delta_x = [np.array(x_list[i+1])-np.array(x_list[i]) + for i in range(len(x_list)-1)] + delta_grad = [grad_list[i+1]-grad_list[i] + for i in range(len(grad_list)-1)] + hess = BFGS(init_scale=1, min_curvature=10) + hess.initialize(len(x_list[0]), 'hess') + # Compare the Hessian and its inverse + for i in range(len(delta_x)-1): + s = delta_x[i] + y = delta_grad[i] + hess.update(s, y) + # Test skip update + B = np.copy(hess.get_matrix()) + s = delta_x[5] + y = delta_grad[5] + hess.update(s, y) + B_updated = np.copy(hess.get_matrix()) + assert_array_equal(B, B_updated) + + +@pytest.mark.parametrize('strategy', [BFGS, SR1]) +@pytest.mark.parametrize('approx_type', ['hess', 'inv_hess']) +def test_matmul_equals_dot(strategy, approx_type): + H = strategy(init_scale=1) + H.initialize(2, approx_type) + v = np.array([1, 2]) + assert_array_equal(H @ v, H.dot(v)) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_isotonic_regression.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_isotonic_regression.py new file mode 100644 index 0000000000000000000000000000000000000000..b49c56db5b4470c1e4e0f787df52c80eb055c120 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_isotonic_regression.py @@ -0,0 +1,167 @@ +import numpy as np +from numpy.testing import assert_allclose, assert_equal +import pytest + +from scipy.optimize._pava_pybind import pava +from scipy.optimize import isotonic_regression + + +class TestIsotonicRegression: + @pytest.mark.parametrize( + ("y", "w", "msg"), + [ + ([[0, 1]], None, + "array has incorrect number of dimensions: 2; expected 1"), + ([0, 1], [[1, 2]], + "Input arrays y and w must have one dimension of equal length"), + ([0, 1], [1], + "Input arrays y and w must have one dimension of equal length"), + (1, [1, 2], + "Input arrays y and w must have one dimension of equal length"), + ([1, 2], 1, + "Input arrays y and w must have one dimension of equal length"), + ([0, 1], [0, 1], + "Weights w must be strictly positive"), + ] + ) + def test_raise_error(self, y, w, msg): + with pytest.raises(ValueError, match=msg): + isotonic_regression(y=y, weights=w) + + def test_simple_pava(self): + # Test case of Busing 2020 + # https://doi.org/10.18637/jss.v102.c01 + y = np.array([8, 4, 8, 2, 2, 0, 8], dtype=np.float64) + w = np.ones_like(y) + r = np.full(shape=y.shape[0] + 1, fill_value=-1, dtype=np.intp) + pava(y, w, r) + assert_allclose(y, [4, 4, 4, 4, 4, 4, 8]) + # Only first 2 elements of w are changed. + assert_allclose(w, [6, 1, 1, 1, 1, 1, 1]) + # Only first 3 elements of r are changed. + assert_allclose(r, [0, 6, 7, -1, -1, -1, -1, -1]) + + @pytest.mark.parametrize("y_dtype", [np.float64, np.float32, np.int64, np.int32]) + @pytest.mark.parametrize("w_dtype", [np.float64, np.float32, np.int64, np.int32]) + @pytest.mark.parametrize("w", [None, "ones"]) + def test_simple_isotonic_regression(self, w, w_dtype, y_dtype): + # Test case of Busing 2020 + # https://doi.org/10.18637/jss.v102.c01 + y = np.array([8, 4, 8, 2, 2, 0, 8], dtype=y_dtype) + if w is not None: + w = np.ones_like(y, dtype=w_dtype) + res = isotonic_regression(y, weights=w) + assert res.x.dtype == np.float64 + assert res.weights.dtype == np.float64 + assert_allclose(res.x, [4, 4, 4, 4, 4, 4, 8]) + assert_allclose(res.weights, [6, 1]) + assert_allclose(res.blocks, [0, 6, 7]) + # Assert that y was not overwritten + assert_equal(y, np.array([8, 4, 8, 2, 2, 0, 8], dtype=np.float64)) + + @pytest.mark.parametrize("increasing", [True, False]) + def test_linspace(self, increasing): + n = 10 + y = np.linspace(0, 1, n) if increasing else np.linspace(1, 0, n) + res = isotonic_regression(y, increasing=increasing) + assert_allclose(res.x, y) + assert_allclose(res.blocks, np.arange(n + 1)) + + def test_weights(self): + w = np.array([1, 2, 5, 0.5, 0.5, 0.5, 1, 3]) + y = np.array([3, 2, 1, 10, 9, 8, 20, 10]) + res = isotonic_regression(y, weights=w) + assert_allclose(res.x, [12/8, 12/8, 12/8, 9, 9, 9, 50/4, 50/4]) + assert_allclose(res.weights, [8, 1.5, 4]) + assert_allclose(res.blocks, [0, 3, 6, 8]) + + # weights are like repeated observations, we repeat the 3rd element 5 + # times. + w2 = np.array([1, 2, 1, 1, 1, 1, 1, 0.5, 0.5, 0.5, 1, 3]) + y2 = np.array([3, 2, 1, 1, 1, 1, 1, 10, 9, 8, 20, 10]) + res2 = isotonic_regression(y2, weights=w2) + assert_allclose(np.diff(res2.x[0:7]), 0) + assert_allclose(res2.x[4:], res.x) + assert_allclose(res2.weights, res.weights) + assert_allclose(res2.blocks[1:] - 4, res.blocks[1:]) + + def test_against_R_monotone(self): + y = [0, 6, 8, 3, 5, 2, 1, 7, 9, 4] + res = isotonic_regression(y) + # R code + # library(monotone) + # options(digits=8) + # monotone(c(0, 6, 8, 3, 5, 2, 1, 7, 9, 4)) + x_R = [ + 0, 4.1666667, 4.1666667, 4.1666667, 4.1666667, 4.1666667, + 4.1666667, 6.6666667, 6.6666667, 6.6666667, + ] + assert_allclose(res.x, x_R) + assert_equal(res.blocks, [0, 1, 7, 10]) + + n = 100 + y = np.linspace(0, 1, num=n, endpoint=False) + y = 5 * y + np.sin(10 * y) + res = isotonic_regression(y) + # R code + # library(monotone) + # n <- 100 + # y <- 5 * ((1:n)-1)/n + sin(10 * ((1:n)-1)/n) + # options(digits=8) + # monotone(y) + x_R = [ + 0.00000000, 0.14983342, 0.29866933, 0.44552021, 0.58941834, 0.72942554, + 0.86464247, 0.99421769, 1.11735609, 1.23332691, 1.34147098, 1.44120736, + 1.53203909, 1.57081100, 1.57081100, 1.57081100, 1.57081100, 1.57081100, + 1.57081100, 1.57081100, 1.57081100, 1.57081100, 1.57081100, 1.57081100, + 1.57081100, 1.57081100, 1.57081100, 1.57081100, 1.57081100, 1.57081100, + 1.57081100, 1.57081100, 1.57081100, 1.57081100, 1.57081100, 1.57081100, + 1.57081100, 1.57081100, 1.57081100, 1.57081100, 1.57081100, 1.57081100, + 1.57081100, 1.57081100, 1.57081100, 1.57081100, 1.57081100, 1.57081100, + 1.57081100, 1.57081100, 1.57081100, 1.62418532, 1.71654534, 1.81773256, + 1.92723551, 2.04445967, 2.16873336, 2.29931446, 2.43539782, 2.57612334, + 2.72058450, 2.86783750, 3.01691060, 3.16681390, 3.31654920, 3.46511999, + 3.61154136, 3.75484992, 3.89411335, 4.02843976, 4.15698660, 4.27896904, + 4.39366786, 4.50043662, 4.59870810, 4.68799998, 4.76791967, 4.83816823, + 4.86564130, 4.86564130, 4.86564130, 4.86564130, 4.86564130, 4.86564130, + 4.86564130, 4.86564130, 4.86564130, 4.86564130, 4.86564130, 4.86564130, + 4.86564130, 4.86564130, 4.86564130, 4.86564130, 4.86564130, 4.86564130, + 4.86564130, 4.86564130, 4.86564130, 4.86564130, + ] + assert_allclose(res.x, x_R) + + # Test increasing + assert np.all(np.diff(res.x) >= 0) + + # Test balance property: sum(y) == sum(x) + assert_allclose(np.sum(res.x), np.sum(y)) + + # Reverse order + res_inv = isotonic_regression(-y, increasing=False) + assert_allclose(-res_inv.x, res.x) + assert_equal(res_inv.blocks, res.blocks) + + def test_readonly(self): + x = np.arange(3, dtype=float) + w = np.ones(3, dtype=float) + + x.flags.writeable = False + w.flags.writeable = False + + res = isotonic_regression(x, weights=w) + assert np.all(np.isfinite(res.x)) + assert np.all(np.isfinite(res.weights)) + assert np.all(np.isfinite(res.blocks)) + + def test_non_contiguous_arrays(self): + x = np.arange(10, dtype=float)[::3] + w = np.ones(10, dtype=float)[::3] + assert not x.flags.c_contiguous + assert not x.flags.f_contiguous + assert not w.flags.c_contiguous + assert not w.flags.f_contiguous + + res = isotonic_regression(x, weights=w) + assert np.all(np.isfinite(res.x)) + assert np.all(np.isfinite(res.weights)) + assert np.all(np.isfinite(res.blocks)) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_lbfgsb_hessinv.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_lbfgsb_hessinv.py new file mode 100644 index 0000000000000000000000000000000000000000..8e4452cd61c5400c13f4f239055352bae754ad7e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_lbfgsb_hessinv.py @@ -0,0 +1,43 @@ +import numpy as np +from numpy.testing import assert_allclose +import scipy.linalg +from scipy.optimize import minimize + + +def test_1(): + def f(x): + return x**4, 4*x**3 + + for gtol in [1e-8, 1e-12, 1e-20]: + for maxcor in range(20, 35): + result = minimize(fun=f, jac=True, method='L-BFGS-B', x0=20, + options={'gtol': gtol, 'maxcor': maxcor}) + + H1 = result.hess_inv(np.array([1])).reshape(1,1) + H2 = result.hess_inv.todense() + + assert_allclose(H1, H2) + + +def test_2(): + H0 = [[3, 0], [1, 2]] + + def f(x): + return np.dot(x, np.dot(scipy.linalg.inv(H0), x)) + + result1 = minimize(fun=f, method='L-BFGS-B', x0=[10, 20]) + result2 = minimize(fun=f, method='BFGS', x0=[10, 20]) + + H1 = result1.hess_inv.todense() + + H2 = np.vstack(( + result1.hess_inv(np.array([1, 0])), + result1.hess_inv(np.array([0, 1])))) + + assert_allclose( + result1.hess_inv(np.array([1, 0]).reshape(2,1)).reshape(-1), + result1.hess_inv(np.array([1, 0]))) + assert_allclose(H1, H2) + assert_allclose(H1, result2.hess_inv, rtol=1e-2, atol=0.03) + + diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_lbfgsb_setulb.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_lbfgsb_setulb.py new file mode 100644 index 0000000000000000000000000000000000000000..ee47f45509c86968b9b551eb8740ad301fd37958 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_lbfgsb_setulb.py @@ -0,0 +1,122 @@ +import numpy as np +from scipy.optimize import _lbfgsb, minimize + + +def objfun(x): + """simplified objective func to test lbfgsb bound violation""" + x0 = [0.8750000000000278, + 0.7500000000000153, + 0.9499999999999722, + 0.8214285714285992, + 0.6363636363636085] + x1 = [1.0, 0.0, 1.0, 0.0, 0.0] + x2 = [1.0, + 0.0, + 0.9889733043149325, + 0.0, + 0.026353554421041155] + x3 = [1.0, + 0.0, + 0.9889917442915558, + 0.0, + 0.020341986743231205] + + f0 = 5163.647901211178 + f1 = 5149.8181642072905 + f2 = 5149.379332309634 + f3 = 5149.374490771297 + + g0 = np.array([-0.5934820547965749, + 1.6251549718258351, + -71.99168459202559, + 5.346636965797545, + 37.10732723092604]) + g1 = np.array([-0.43295349282641515, + 1.008607936794592, + 18.223666726602975, + 31.927010036981997, + -19.667512518739386]) + g2 = np.array([-0.4699874455100256, + 0.9466285353668347, + -0.016874360242016825, + 48.44999161133457, + 5.819631620590712]) + g3 = np.array([-0.46970678696829116, + 0.9612719312174818, + 0.006129809488833699, + 48.43557729419473, + 6.005481418498221]) + + if np.allclose(x, x0): + f = f0 + g = g0 + elif np.allclose(x, x1): + f = f1 + g = g1 + elif np.allclose(x, x2): + f = f2 + g = g2 + elif np.allclose(x, x3): + f = f3 + g = g3 + else: + raise ValueError( + 'Simplified objective function not defined ' + 'at requested point') + return (np.copy(f), np.copy(g)) + + +def test_setulb_floatround(): + """test if setulb() violates bounds + + checks for violation due to floating point rounding error + """ + + n = 5 + m = 10 + factr = 1e7 + pgtol = 1e-5 + maxls = 20 + nbd = np.full(shape=(n,), fill_value=2, dtype=np.int32) + low_bnd = np.zeros(n, dtype=np.float64) + upper_bnd = np.ones(n, dtype=np.float64) + + x0 = np.array( + [0.8750000000000278, + 0.7500000000000153, + 0.9499999999999722, + 0.8214285714285992, + 0.6363636363636085]) + x = np.copy(x0) + + f = np.array(0.0, dtype=np.float64) + g = np.zeros(n, dtype=np.float64) + + wa = np.zeros(2*m*n + 5*n + 11*m*m + 8*m, dtype=np.float64) + iwa = np.zeros(3*n, dtype=np.int32) + task = np.zeros(2, dtype=np.int32) + ln_task = np.zeros(2, dtype=np.int32) + lsave = np.zeros(4, dtype=np.int32) + isave = np.zeros(44, dtype=np.int32) + dsave = np.zeros(29, dtype=np.float64) + + for n_iter in range(7): # 7 steps required to reproduce error + f, g = objfun(x) + + _lbfgsb.setulb(m, x, low_bnd, upper_bnd, nbd, f, g, factr, pgtol, wa, + iwa, task, lsave, isave, dsave, maxls, ln_task) + + assert (x <= upper_bnd).all() and (x >= low_bnd).all(), ( + "_lbfgsb.setulb() stepped to a point outside of the bounds") + + +def test_gh_issue18730(): + # issue 18730 reported that l-bfgs-b did not work with objectives + # returning single precision gradient arrays + def fun_single_precision(x): + x = x.astype(np.float32) + return np.sum(x**2), (2*x) + + res = minimize(fun_single_precision, x0=np.array([1., 1.]), jac=True, + method="l-bfgs-b") + np.testing.assert_allclose(res.fun, 0., atol=1e-15) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_least_squares.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_least_squares.py new file mode 100644 index 0000000000000000000000000000000000000000..d27d670a1aac01f7129d483e0a048a38dce35404 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_least_squares.py @@ -0,0 +1,874 @@ +from itertools import product + +import numpy as np +from numpy.linalg import norm +from numpy.testing import (assert_, assert_allclose, + assert_equal, suppress_warnings) +import pytest +from pytest import raises as assert_raises +from scipy.sparse import issparse, lil_matrix +from scipy.sparse.linalg import aslinearoperator + +from scipy.optimize import least_squares, Bounds +from scipy.optimize._lsq.least_squares import IMPLEMENTED_LOSSES +from scipy.optimize._lsq.common import EPS, make_strictly_feasible, CL_scaling_vector + + +def fun_trivial(x, a=0): + return (x - a)**2 + 5.0 + + +def jac_trivial(x, a=0.0): + return 2 * (x - a) + + +def fun_2d_trivial(x): + return np.array([x[0], x[1]]) + + +def jac_2d_trivial(x): + return np.identity(2) + + +def fun_rosenbrock(x): + return np.array([10 * (x[1] - x[0]**2), (1 - x[0])]) + + +def jac_rosenbrock(x): + return np.array([ + [-20 * x[0], 10], + [-1, 0] + ]) + + +def jac_rosenbrock_bad_dim(x): + return np.array([ + [-20 * x[0], 10], + [-1, 0], + [0.0, 0.0] + ]) + + +def fun_rosenbrock_cropped(x): + return fun_rosenbrock(x)[0] + + +def jac_rosenbrock_cropped(x): + return jac_rosenbrock(x)[0] + + +# When x is 1-D array, return is 2-D array. +def fun_wrong_dimensions(x): + return np.array([x, x**2, x**3]) + + +def jac_wrong_dimensions(x, a=0.0): + return np.atleast_3d(jac_trivial(x, a=a)) + + +def fun_bvp(x): + n = int(np.sqrt(x.shape[0])) + u = np.zeros((n + 2, n + 2)) + x = x.reshape((n, n)) + u[1:-1, 1:-1] = x + y = u[:-2, 1:-1] + u[2:, 1:-1] + u[1:-1, :-2] + u[1:-1, 2:] - 4 * x + x**3 + return y.ravel() + + +class BroydenTridiagonal: + def __init__(self, n=100, mode='sparse'): + rng = np.random.RandomState(0) + + self.n = n + + self.x0 = -np.ones(n) + self.lb = np.linspace(-2, -1.5, n) + self.ub = np.linspace(-0.8, 0.0, n) + + self.lb += 0.1 * rng.randn(n) + self.ub += 0.1 * rng.randn(n) + + self.x0 += 0.1 * rng.randn(n) + self.x0 = make_strictly_feasible(self.x0, self.lb, self.ub) + + if mode == 'sparse': + self.sparsity = lil_matrix((n, n), dtype=int) + i = np.arange(n) + self.sparsity[i, i] = 1 + i = np.arange(1, n) + self.sparsity[i, i - 1] = 1 + i = np.arange(n - 1) + self.sparsity[i, i + 1] = 1 + + self.jac = self._jac + elif mode == 'operator': + self.jac = lambda x: aslinearoperator(self._jac(x)) + elif mode == 'dense': + self.sparsity = None + self.jac = lambda x: self._jac(x).toarray() + else: + assert_(False) + + def fun(self, x): + f = (3 - x) * x + 1 + f[1:] -= x[:-1] + f[:-1] -= 2 * x[1:] + return f + + def _jac(self, x): + J = lil_matrix((self.n, self.n)) + i = np.arange(self.n) + J[i, i] = 3 - 2 * x + i = np.arange(1, self.n) + J[i, i - 1] = -1 + i = np.arange(self.n - 1) + J[i, i + 1] = -2 + return J + + +class ExponentialFittingProblem: + """Provide data and function for exponential fitting in the form + y = a + exp(b * x) + noise.""" + + def __init__(self, a, b, noise, n_outliers=1, x_range=(-1, 1), + n_points=11, random_seed=None): + rng = np.random.RandomState(random_seed) + self.m = n_points + self.n = 2 + + self.p0 = np.zeros(2) + self.x = np.linspace(x_range[0], x_range[1], n_points) + + self.y = a + np.exp(b * self.x) + self.y += noise * rng.randn(self.m) + + outliers = rng.randint(0, self.m, n_outliers) + self.y[outliers] += 50 * noise * rng.rand(n_outliers) + + self.p_opt = np.array([a, b]) + + def fun(self, p): + return p[0] + np.exp(p[1] * self.x) - self.y + + def jac(self, p): + J = np.empty((self.m, self.n)) + J[:, 0] = 1 + J[:, 1] = self.x * np.exp(p[1] * self.x) + return J + + +def cubic_soft_l1(z): + rho = np.empty((3, z.size)) + + t = 1 + z + rho[0] = 3 * (t**(1/3) - 1) + rho[1] = t ** (-2/3) + rho[2] = -2/3 * t**(-5/3) + + return rho + + +LOSSES = list(IMPLEMENTED_LOSSES.keys()) + [cubic_soft_l1] + + +class BaseMixin: + def test_basic(self): + # Test that the basic calling sequence works. + res = least_squares(fun_trivial, 2., method=self.method) + assert_allclose(res.x, 0, atol=1e-4) + assert_allclose(res.fun, fun_trivial(res.x)) + + def test_args_kwargs(self): + # Test that args and kwargs are passed correctly to the functions. + a = 3.0 + for jac in ['2-point', '3-point', 'cs', jac_trivial]: + with suppress_warnings() as sup: + sup.filter( + UserWarning, + "jac='(3-point|cs)' works equivalently to '2-point' for method='lm'" + ) + res = least_squares(fun_trivial, 2.0, jac, args=(a,), + method=self.method) + res1 = least_squares(fun_trivial, 2.0, jac, kwargs={'a': a}, + method=self.method) + + assert_allclose(res.x, a, rtol=1e-4) + assert_allclose(res1.x, a, rtol=1e-4) + + assert_raises(TypeError, least_squares, fun_trivial, 2.0, + args=(3, 4,), method=self.method) + assert_raises(TypeError, least_squares, fun_trivial, 2.0, + kwargs={'kaboom': 3}, method=self.method) + + def test_jac_options(self): + for jac in ['2-point', '3-point', 'cs', jac_trivial]: + with suppress_warnings() as sup: + sup.filter( + UserWarning, + "jac='(3-point|cs)' works equivalently to '2-point' for method='lm'" + ) + res = least_squares(fun_trivial, 2.0, jac, method=self.method) + assert_allclose(res.x, 0, atol=1e-4) + + assert_raises(ValueError, least_squares, fun_trivial, 2.0, jac='oops', + method=self.method) + + def test_nfev_options(self): + for max_nfev in [None, 20]: + res = least_squares(fun_trivial, 2.0, max_nfev=max_nfev, + method=self.method) + assert_allclose(res.x, 0, atol=1e-4) + + def test_x_scale_options(self): + for x_scale in [1.0, np.array([0.5]), 'jac']: + res = least_squares(fun_trivial, 2.0, x_scale=x_scale) + assert_allclose(res.x, 0) + assert_raises(ValueError, least_squares, fun_trivial, + 2.0, x_scale='auto', method=self.method) + assert_raises(ValueError, least_squares, fun_trivial, + 2.0, x_scale=-1.0, method=self.method) + assert_raises(ValueError, least_squares, fun_trivial, + 2.0, x_scale=None, method=self.method) + assert_raises(ValueError, least_squares, fun_trivial, + 2.0, x_scale=1.0+2.0j, method=self.method) + + def test_diff_step(self): + # res1 and res2 should be equivalent. + # res2 and res3 should be different. + res1 = least_squares(fun_trivial, 2.0, diff_step=1e-1, + method=self.method) + res2 = least_squares(fun_trivial, 2.0, diff_step=-1e-1, + method=self.method) + res3 = least_squares(fun_trivial, 2.0, + diff_step=None, method=self.method) + assert_allclose(res1.x, 0, atol=1e-4) + assert_allclose(res2.x, 0, atol=1e-4) + assert_allclose(res3.x, 0, atol=1e-4) + assert_equal(res1.x, res2.x) + assert_equal(res1.nfev, res2.nfev) + + def test_incorrect_options_usage(self): + assert_raises(TypeError, least_squares, fun_trivial, 2.0, + method=self.method, options={'no_such_option': 100}) + assert_raises(TypeError, least_squares, fun_trivial, 2.0, + method=self.method, options={'max_nfev': 100}) + + def test_full_result(self): + # MINPACK doesn't work very well with factor=100 on this problem, + # thus using low 'atol'. + res = least_squares(fun_trivial, 2.0, method=self.method) + assert_allclose(res.x, 0, atol=1e-4) + assert_allclose(res.cost, 12.5) + assert_allclose(res.fun, 5) + assert_allclose(res.jac, 0, atol=1e-4) + assert_allclose(res.grad, 0, atol=1e-2) + assert_allclose(res.optimality, 0, atol=1e-2) + assert_equal(res.active_mask, 0) + if self.method == 'lm': + assert_(res.nfev < 30) + assert_(res.njev is None) + else: + assert_(res.nfev < 10) + assert_(res.njev < 10) + assert_(res.status > 0) + assert_(res.success) + + def test_full_result_single_fev(self): + # MINPACK checks the number of nfev after the iteration, + # so it's hard to tell what he is going to compute. + if self.method == 'lm': + return + + res = least_squares(fun_trivial, 2.0, method=self.method, + max_nfev=1) + assert_equal(res.x, np.array([2])) + assert_equal(res.cost, 40.5) + assert_equal(res.fun, np.array([9])) + assert_equal(res.jac, np.array([[4]])) + assert_equal(res.grad, np.array([36])) + assert_equal(res.optimality, 36) + assert_equal(res.active_mask, np.array([0])) + assert_equal(res.nfev, 1) + assert_equal(res.njev, 1) + assert_equal(res.status, 0) + assert_equal(res.success, 0) + + def test_rosenbrock(self): + x0 = [-2, 1] + x_opt = [1, 1] + for jac, x_scale, tr_solver in product( + ['2-point', '3-point', 'cs', jac_rosenbrock], + [1.0, np.array([1.0, 0.2]), 'jac'], + ['exact', 'lsmr']): + with suppress_warnings() as sup: + sup.filter( + UserWarning, + "jac='(3-point|cs)' works equivalently to '2-point' for method='lm'" + ) + res = least_squares(fun_rosenbrock, x0, jac, x_scale=x_scale, + tr_solver=tr_solver, method=self.method) + assert_allclose(res.x, x_opt) + + def test_rosenbrock_cropped(self): + x0 = [-2, 1] + if self.method == 'lm': + assert_raises(ValueError, least_squares, fun_rosenbrock_cropped, + x0, method='lm') + else: + for jac, x_scale, tr_solver in product( + ['2-point', '3-point', 'cs', jac_rosenbrock_cropped], + [1.0, np.array([1.0, 0.2]), 'jac'], + ['exact', 'lsmr']): + res = least_squares( + fun_rosenbrock_cropped, x0, jac, x_scale=x_scale, + tr_solver=tr_solver, method=self.method) + assert_allclose(res.cost, 0, atol=1e-14) + + def test_fun_wrong_dimensions(self): + assert_raises(ValueError, least_squares, fun_wrong_dimensions, + 2.0, method=self.method) + + def test_jac_wrong_dimensions(self): + assert_raises(ValueError, least_squares, fun_trivial, + 2.0, jac_wrong_dimensions, method=self.method) + + def test_fun_and_jac_inconsistent_dimensions(self): + x0 = [1, 2] + assert_raises(ValueError, least_squares, fun_rosenbrock, x0, + jac_rosenbrock_bad_dim, method=self.method) + + def test_x0_multidimensional(self): + x0 = np.ones(4).reshape(2, 2) + assert_raises(ValueError, least_squares, fun_trivial, x0, + method=self.method) + + def test_x0_complex_scalar(self): + x0 = 2.0 + 0.0*1j + assert_raises(ValueError, least_squares, fun_trivial, x0, + method=self.method) + + def test_x0_complex_array(self): + x0 = [1.0, 2.0 + 0.0*1j] + assert_raises(ValueError, least_squares, fun_trivial, x0, + method=self.method) + + def test_bvp(self): + # This test was introduced with fix #5556. It turned out that + # dogbox solver had a bug with trust-region radius update, which + # could block its progress and create an infinite loop. And this + # discrete boundary value problem is the one which triggers it. + n = 10 + x0 = np.ones(n**2) + if self.method == 'lm': + max_nfev = 5000 # To account for Jacobian estimation. + else: + max_nfev = 100 + res = least_squares(fun_bvp, x0, ftol=1e-2, method=self.method, + max_nfev=max_nfev) + + assert_(res.nfev < max_nfev) + assert_(res.cost < 0.5) + + def test_error_raised_when_all_tolerances_below_eps(self): + # Test that all 0 tolerances are not allowed. + assert_raises(ValueError, least_squares, fun_trivial, 2.0, + method=self.method, ftol=None, xtol=None, gtol=None) + + def test_convergence_with_only_one_tolerance_enabled(self): + if self.method == 'lm': + return # should not do test + x0 = [-2, 1] + x_opt = [1, 1] + for ftol, xtol, gtol in [(1e-8, None, None), + (None, 1e-8, None), + (None, None, 1e-8)]: + res = least_squares(fun_rosenbrock, x0, jac=jac_rosenbrock, + ftol=ftol, gtol=gtol, xtol=xtol, + method=self.method) + assert_allclose(res.x, x_opt) + + +class BoundsMixin: + def test_inconsistent(self): + assert_raises(ValueError, least_squares, fun_trivial, 2.0, + bounds=(10.0, 0.0), method=self.method) + + def test_infeasible(self): + assert_raises(ValueError, least_squares, fun_trivial, 2.0, + bounds=(3., 4), method=self.method) + + def test_wrong_number(self): + assert_raises(ValueError, least_squares, fun_trivial, 2., + bounds=(1., 2, 3), method=self.method) + + def test_inconsistent_shape(self): + assert_raises(ValueError, least_squares, fun_trivial, 2.0, + bounds=(1.0, [2.0, 3.0]), method=self.method) + # 1-D array won't be broadcast + assert_raises(ValueError, least_squares, fun_rosenbrock, [1.0, 2.0], + bounds=([0.0], [3.0, 4.0]), method=self.method) + + def test_in_bounds(self): + for jac in ['2-point', '3-point', 'cs', jac_trivial]: + res = least_squares(fun_trivial, 2.0, jac=jac, + bounds=(-1.0, 3.0), method=self.method) + assert_allclose(res.x, 0.0, atol=1e-4) + assert_equal(res.active_mask, [0]) + assert_(-1 <= res.x <= 3) + res = least_squares(fun_trivial, 2.0, jac=jac, + bounds=(0.5, 3.0), method=self.method) + assert_allclose(res.x, 0.5, atol=1e-4) + assert_equal(res.active_mask, [-1]) + assert_(0.5 <= res.x <= 3) + + def test_bounds_shape(self): + def get_bounds_direct(lb, ub): + return lb, ub + + def get_bounds_instances(lb, ub): + return Bounds(lb, ub) + + for jac in ['2-point', '3-point', 'cs', jac_2d_trivial]: + for bounds_func in [get_bounds_direct, get_bounds_instances]: + x0 = [1.0, 1.0] + res = least_squares(fun_2d_trivial, x0, jac=jac) + assert_allclose(res.x, [0.0, 0.0]) + res = least_squares(fun_2d_trivial, x0, jac=jac, + bounds=bounds_func(0.5, [2.0, 2.0]), + method=self.method) + assert_allclose(res.x, [0.5, 0.5]) + res = least_squares(fun_2d_trivial, x0, jac=jac, + bounds=bounds_func([0.3, 0.2], 3.0), + method=self.method) + assert_allclose(res.x, [0.3, 0.2]) + res = least_squares( + fun_2d_trivial, x0, jac=jac, + bounds=bounds_func([-1, 0.5], [1.0, 3.0]), + method=self.method) + assert_allclose(res.x, [0.0, 0.5], atol=1e-5) + + def test_bounds_instances(self): + res = least_squares(fun_trivial, 0.5, bounds=Bounds()) + assert_allclose(res.x, 0.0, atol=1e-4) + + res = least_squares(fun_trivial, 3.0, bounds=Bounds(lb=1.0)) + assert_allclose(res.x, 1.0, atol=1e-4) + + res = least_squares(fun_trivial, 0.5, bounds=Bounds(lb=-1.0, ub=1.0)) + assert_allclose(res.x, 0.0, atol=1e-4) + + res = least_squares(fun_trivial, -3.0, bounds=Bounds(ub=-1.0)) + assert_allclose(res.x, -1.0, atol=1e-4) + + res = least_squares(fun_2d_trivial, [0.5, 0.5], + bounds=Bounds(lb=[-1.0, -1.0], ub=1.0)) + assert_allclose(res.x, [0.0, 0.0], atol=1e-5) + + res = least_squares(fun_2d_trivial, [0.5, 0.5], + bounds=Bounds(lb=[0.1, 0.1])) + assert_allclose(res.x, [0.1, 0.1], atol=1e-5) + + @pytest.mark.fail_slow(10) + def test_rosenbrock_bounds(self): + x0_1 = np.array([-2.0, 1.0]) + x0_2 = np.array([2.0, 2.0]) + x0_3 = np.array([-2.0, 2.0]) + x0_4 = np.array([0.0, 2.0]) + x0_5 = np.array([-1.2, 1.0]) + problems = [ + (x0_1, ([-np.inf, -1.5], np.inf)), + (x0_2, ([-np.inf, 1.5], np.inf)), + (x0_3, ([-np.inf, 1.5], np.inf)), + (x0_4, ([-np.inf, 1.5], [1.0, np.inf])), + (x0_2, ([1.0, 1.5], [3.0, 3.0])), + (x0_5, ([-50.0, 0.0], [0.5, 100])) + ] + for x0, bounds in problems: + for jac, x_scale, tr_solver in product( + ['2-point', '3-point', 'cs', jac_rosenbrock], + [1.0, [1.0, 0.5], 'jac'], + ['exact', 'lsmr']): + res = least_squares(fun_rosenbrock, x0, jac, bounds, + x_scale=x_scale, tr_solver=tr_solver, + method=self.method) + assert_allclose(res.optimality, 0.0, atol=1e-5) + + +class SparseMixin: + def test_exact_tr_solver(self): + p = BroydenTridiagonal() + assert_raises(ValueError, least_squares, p.fun, p.x0, p.jac, + tr_solver='exact', method=self.method) + assert_raises(ValueError, least_squares, p.fun, p.x0, + tr_solver='exact', jac_sparsity=p.sparsity, + method=self.method) + + def test_equivalence(self): + sparse = BroydenTridiagonal(mode='sparse') + dense = BroydenTridiagonal(mode='dense') + res_sparse = least_squares( + sparse.fun, sparse.x0, jac=sparse.jac, + method=self.method) + res_dense = least_squares( + dense.fun, dense.x0, jac=sparse.jac, + method=self.method) + assert_equal(res_sparse.nfev, res_dense.nfev) + assert_allclose(res_sparse.x, res_dense.x, atol=1e-20) + assert_allclose(res_sparse.cost, 0, atol=1e-20) + assert_allclose(res_dense.cost, 0, atol=1e-20) + + def test_tr_options(self): + p = BroydenTridiagonal() + res = least_squares(p.fun, p.x0, p.jac, method=self.method, + tr_options={'btol': 1e-10}) + assert_allclose(res.cost, 0, atol=1e-20) + + def test_wrong_parameters(self): + p = BroydenTridiagonal() + assert_raises(ValueError, least_squares, p.fun, p.x0, p.jac, + tr_solver='best', method=self.method) + assert_raises(TypeError, least_squares, p.fun, p.x0, p.jac, + tr_solver='lsmr', tr_options={'tol': 1e-10}) + + def test_solver_selection(self): + sparse = BroydenTridiagonal(mode='sparse') + dense = BroydenTridiagonal(mode='dense') + res_sparse = least_squares(sparse.fun, sparse.x0, jac=sparse.jac, + method=self.method) + res_dense = least_squares(dense.fun, dense.x0, jac=dense.jac, + method=self.method) + assert_allclose(res_sparse.cost, 0, atol=1e-20) + assert_allclose(res_dense.cost, 0, atol=1e-20) + assert_(issparse(res_sparse.jac)) + assert_(isinstance(res_dense.jac, np.ndarray)) + + def test_numerical_jac(self): + p = BroydenTridiagonal() + for jac in ['2-point', '3-point', 'cs']: + res_dense = least_squares(p.fun, p.x0, jac, method=self.method) + res_sparse = least_squares( + p.fun, p.x0, jac,method=self.method, + jac_sparsity=p.sparsity) + assert_equal(res_dense.nfev, res_sparse.nfev) + assert_allclose(res_dense.x, res_sparse.x, atol=1e-20) + assert_allclose(res_dense.cost, 0, atol=1e-20) + assert_allclose(res_sparse.cost, 0, atol=1e-20) + + @pytest.mark.fail_slow(10) + def test_with_bounds(self): + p = BroydenTridiagonal() + for jac, jac_sparsity in product( + [p.jac, '2-point', '3-point', 'cs'], [None, p.sparsity]): + res_1 = least_squares( + p.fun, p.x0, jac, bounds=(p.lb, np.inf), + method=self.method,jac_sparsity=jac_sparsity) + res_2 = least_squares( + p.fun, p.x0, jac, bounds=(-np.inf, p.ub), + method=self.method, jac_sparsity=jac_sparsity) + res_3 = least_squares( + p.fun, p.x0, jac, bounds=(p.lb, p.ub), + method=self.method, jac_sparsity=jac_sparsity) + assert_allclose(res_1.optimality, 0, atol=1e-10) + assert_allclose(res_2.optimality, 0, atol=1e-10) + assert_allclose(res_3.optimality, 0, atol=1e-10) + + def test_wrong_jac_sparsity(self): + p = BroydenTridiagonal() + sparsity = p.sparsity[:-1] + assert_raises(ValueError, least_squares, p.fun, p.x0, + jac_sparsity=sparsity, method=self.method) + + def test_linear_operator(self): + p = BroydenTridiagonal(mode='operator') + res = least_squares(p.fun, p.x0, p.jac, method=self.method) + assert_allclose(res.cost, 0.0, atol=1e-20) + assert_raises(ValueError, least_squares, p.fun, p.x0, p.jac, + method=self.method, tr_solver='exact') + + def test_x_scale_jac_scale(self): + p = BroydenTridiagonal() + res = least_squares(p.fun, p.x0, p.jac, method=self.method, + x_scale='jac') + assert_allclose(res.cost, 0.0, atol=1e-20) + + p = BroydenTridiagonal(mode='operator') + assert_raises(ValueError, least_squares, p.fun, p.x0, p.jac, + method=self.method, x_scale='jac') + + +class LossFunctionMixin: + def test_options(self): + for loss in LOSSES: + res = least_squares(fun_trivial, 2.0, loss=loss, + method=self.method) + assert_allclose(res.x, 0, atol=1e-15) + + assert_raises(ValueError, least_squares, fun_trivial, 2.0, + loss='hinge', method=self.method) + + def test_fun(self): + # Test that res.fun is actual residuals, and not modified by loss + # function stuff. + for loss in LOSSES: + res = least_squares(fun_trivial, 2.0, loss=loss, + method=self.method) + assert_equal(res.fun, fun_trivial(res.x)) + + def test_grad(self): + # Test that res.grad is true gradient of loss function at the + # solution. Use max_nfev = 1, to avoid reaching minimum. + x = np.array([2.0]) # res.x will be this. + + res = least_squares(fun_trivial, x, jac_trivial, loss='linear', + max_nfev=1, method=self.method) + assert_equal(res.grad, 2 * x * (x**2 + 5)) + + res = least_squares(fun_trivial, x, jac_trivial, loss='huber', + max_nfev=1, method=self.method) + assert_equal(res.grad, 2 * x) + + res = least_squares(fun_trivial, x, jac_trivial, loss='soft_l1', + max_nfev=1, method=self.method) + assert_allclose(res.grad, + 2 * x * (x**2 + 5) / (1 + (x**2 + 5)**2)**0.5) + + res = least_squares(fun_trivial, x, jac_trivial, loss='cauchy', + max_nfev=1, method=self.method) + assert_allclose(res.grad, 2 * x * (x**2 + 5) / (1 + (x**2 + 5)**2)) + + res = least_squares(fun_trivial, x, jac_trivial, loss='arctan', + max_nfev=1, method=self.method) + assert_allclose(res.grad, 2 * x * (x**2 + 5) / (1 + (x**2 + 5)**4)) + + res = least_squares(fun_trivial, x, jac_trivial, loss=cubic_soft_l1, + max_nfev=1, method=self.method) + assert_allclose(res.grad, + 2 * x * (x**2 + 5) / (1 + (x**2 + 5)**2)**(2/3)) + + def test_jac(self): + # Test that res.jac.T.dot(res.jac) gives Gauss-Newton approximation + # of Hessian. This approximation is computed by doubly differentiating + # the cost function and dropping the part containing second derivative + # of f. For a scalar function it is computed as + # H = (rho' + 2 * rho'' * f**2) * f'**2, if the expression inside the + # brackets is less than EPS it is replaced by EPS. Here, we check + # against the root of H. + + x = 2.0 # res.x will be this. + f = x**2 + 5 # res.fun will be this. + + res = least_squares(fun_trivial, x, jac_trivial, loss='linear', + max_nfev=1, method=self.method) + assert_equal(res.jac, 2 * x) + + # For `huber` loss the Jacobian correction is identically zero + # in outlier region, in such cases it is modified to be equal EPS**0.5. + res = least_squares(fun_trivial, x, jac_trivial, loss='huber', + max_nfev=1, method=self.method) + assert_equal(res.jac, 2 * x * EPS**0.5) + + # Now, let's apply `loss_scale` to turn the residual into an inlier. + # The loss function becomes linear. + res = least_squares(fun_trivial, x, jac_trivial, loss='huber', + f_scale=10, max_nfev=1) + assert_equal(res.jac, 2 * x) + + # 'soft_l1' always gives a positive scaling. + res = least_squares(fun_trivial, x, jac_trivial, loss='soft_l1', + max_nfev=1, method=self.method) + assert_allclose(res.jac, 2 * x * (1 + f**2)**-0.75) + + # For 'cauchy' the correction term turns out to be negative, and it + # replaced by EPS**0.5. + res = least_squares(fun_trivial, x, jac_trivial, loss='cauchy', + max_nfev=1, method=self.method) + assert_allclose(res.jac, 2 * x * EPS**0.5) + + # Now use scaling to turn the residual to inlier. + res = least_squares(fun_trivial, x, jac_trivial, loss='cauchy', + f_scale=10, max_nfev=1, method=self.method) + fs = f / 10 + assert_allclose(res.jac, 2 * x * (1 - fs**2)**0.5 / (1 + fs**2)) + + # 'arctan' gives an outlier. + res = least_squares(fun_trivial, x, jac_trivial, loss='arctan', + max_nfev=1, method=self.method) + assert_allclose(res.jac, 2 * x * EPS**0.5) + + # Turn to inlier. + res = least_squares(fun_trivial, x, jac_trivial, loss='arctan', + f_scale=20.0, max_nfev=1, method=self.method) + fs = f / 20 + assert_allclose(res.jac, 2 * x * (1 - 3 * fs**4)**0.5 / (1 + fs**4)) + + # cubic_soft_l1 will give an outlier. + res = least_squares(fun_trivial, x, jac_trivial, loss=cubic_soft_l1, + max_nfev=1) + assert_allclose(res.jac, 2 * x * EPS**0.5) + + # Turn to inlier. + res = least_squares(fun_trivial, x, jac_trivial, + loss=cubic_soft_l1, f_scale=6, max_nfev=1) + fs = f / 6 + assert_allclose(res.jac, + 2 * x * (1 - fs**2 / 3)**0.5 * (1 + fs**2)**(-5/6)) + + def test_robustness(self): + for noise in [0.1, 1.0]: + p = ExponentialFittingProblem(1, 0.1, noise, random_seed=0) + + for jac in ['2-point', '3-point', 'cs', p.jac]: + res_lsq = least_squares(p.fun, p.p0, jac=jac, + method=self.method) + assert_allclose(res_lsq.optimality, 0, atol=1e-2) + for loss in LOSSES: + if loss == 'linear': + continue + res_robust = least_squares( + p.fun, p.p0, jac=jac, loss=loss, f_scale=noise, + method=self.method) + assert_allclose(res_robust.optimality, 0, atol=1e-2) + assert_(norm(res_robust.x - p.p_opt) < + norm(res_lsq.x - p.p_opt)) + + +class TestDogbox(BaseMixin, BoundsMixin, SparseMixin, LossFunctionMixin): + method = 'dogbox' + + +class TestTRF(BaseMixin, BoundsMixin, SparseMixin, LossFunctionMixin): + method = 'trf' + + def test_lsmr_regularization(self): + p = BroydenTridiagonal() + for regularize in [True, False]: + res = least_squares(p.fun, p.x0, p.jac, method='trf', + tr_options={'regularize': regularize}) + assert_allclose(res.cost, 0, atol=1e-20) + + +class TestLM(BaseMixin): + method = 'lm' + + def test_bounds_not_supported(self): + assert_raises(ValueError, least_squares, fun_trivial, + 2.0, bounds=(-3.0, 3.0), method='lm') + + def test_m_less_n_not_supported(self): + x0 = [-2, 1] + assert_raises(ValueError, least_squares, fun_rosenbrock_cropped, x0, + method='lm') + + def test_sparse_not_supported(self): + p = BroydenTridiagonal() + assert_raises(ValueError, least_squares, p.fun, p.x0, p.jac, + method='lm') + + def test_jac_sparsity_not_supported(self): + assert_raises(ValueError, least_squares, fun_trivial, 2.0, + jac_sparsity=[1], method='lm') + + def test_LinearOperator_not_supported(self): + p = BroydenTridiagonal(mode="operator") + assert_raises(ValueError, least_squares, p.fun, p.x0, p.jac, + method='lm') + + def test_loss(self): + res = least_squares(fun_trivial, 2.0, loss='linear', method='lm') + assert_allclose(res.x, 0.0, atol=1e-4) + + assert_raises(ValueError, least_squares, fun_trivial, 2.0, + method='lm', loss='huber') + + +def test_basic(): + # test that 'method' arg is really optional + res = least_squares(fun_trivial, 2.0) + assert_allclose(res.x, 0, atol=1e-10) + + +def test_small_tolerances_for_lm(): + for ftol, xtol, gtol in [(None, 1e-13, 1e-13), + (1e-13, None, 1e-13), + (1e-13, 1e-13, None)]: + assert_raises(ValueError, least_squares, fun_trivial, 2.0, xtol=xtol, + ftol=ftol, gtol=gtol, method='lm') + + +def test_fp32_gh12991(): + # checks that smaller FP sizes can be used in least_squares + # this is the minimum working example reported for gh12991 + rng = np.random.RandomState(1) + + x = np.linspace(0, 1, 100).astype("float32") + y = rng.random(100).astype("float32") + + def func(p, x): + return p[0] + p[1] * x + + def err(p, x, y): + return func(p, x) - y + + res = least_squares(err, [-1.0, -1.0], args=(x, y)) + # previously the initial jacobian calculated for this would be all 0 + # and the minimize would terminate immediately, with nfev=1, would + # report a successful minimization (it shouldn't have done), but be + # unchanged from the initial solution. + # It was terminating early because the underlying approx_derivative + # used a step size for FP64 when the working space was FP32. + assert res.nfev > 2 + assert_allclose(res.x, np.array([0.4082241, 0.15530563]), atol=5e-5) + + +def test_gh_18793_and_19351(): + answer = 1e-12 + initial_guess = 1.1e-12 + + def chi2(x): + return (x-answer)**2 + + gtol = 1e-15 + res = least_squares(chi2, x0=initial_guess, gtol=1e-15, bounds=(0, np.inf)) + # Original motivation: gh-18793 + # if we choose an initial condition that is close to the solution + # we shouldn't return an answer that is further away from the solution + + # Update: gh-19351 + # However this requirement does not go well with 'trf' algorithm logic. + # Some regressions were reported after the presumed fix. + # The returned solution is good as long as it satisfies the convergence + # conditions. + # Specifically in this case the scaled gradient will be sufficiently low. + + scaling, _ = CL_scaling_vector(res.x, res.grad, + np.atleast_1d(0), np.atleast_1d(np.inf)) + assert res.status == 1 # Converged by gradient + assert np.linalg.norm(res.grad * scaling, ord=np.inf) < gtol + + +def test_gh_19103(): + # Checks that least_squares trf method selects a strictly feasible point, + # and thus succeeds instead of failing, + # when the initial guess is reported exactly at a boundary point. + # This is a reduced example from gh191303 + + ydata = np.array([0.] * 66 + [ + 1., 0., 0., 0., 0., 0., 1., 1., 0., 0., 1., + 1., 1., 1., 0., 0., 0., 1., 0., 0., 2., 1., + 0., 3., 1., 6., 5., 0., 0., 2., 8., 4., 4., + 6., 9., 7., 2., 7., 8., 2., 13., 9., 8., 11., + 10., 13., 14., 19., 11., 15., 18., 26., 19., 32., 29., + 28., 36., 32., 35., 36., 43., 52., 32., 58., 56., 52., + 67., 53., 72., 88., 77., 95., 94., 84., 86., 101., 107., + 108., 118., 96., 115., 138., 137., + ]) + xdata = np.arange(0, ydata.size) * 0.1 + + def exponential_wrapped(params): + A, B, x0 = params + return A * np.exp(B * (xdata - x0)) - ydata + + x0 = [0.01, 1., 5.] + bounds = ((0.01, 0, 0), (np.inf, 10, 20.9)) + res = least_squares(exponential_wrapped, x0, method='trf', bounds=bounds) + assert res.success diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_linear_assignment.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_linear_assignment.py new file mode 100644 index 0000000000000000000000000000000000000000..d59792da9eef38e313eaa0bca70f873627f8d3cf --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_linear_assignment.py @@ -0,0 +1,116 @@ +# Author: Brian M. Clapper, G. Varoquaux, Lars Buitinck +# License: BSD + +from numpy.testing import assert_array_equal +import pytest + +import numpy as np + +from scipy.optimize import linear_sum_assignment +from scipy.sparse import random +from scipy.sparse._sputils import matrix +from scipy.sparse.csgraph import min_weight_full_bipartite_matching +from scipy.sparse.csgraph.tests.test_matching import ( + linear_sum_assignment_assertions, linear_sum_assignment_test_cases +) + + +def test_linear_sum_assignment_input_shape(): + with pytest.raises(ValueError, match="expected a matrix"): + linear_sum_assignment([1, 2, 3]) + + +def test_linear_sum_assignment_input_object(): + C = [[1, 2, 3], [4, 5, 6]] + assert_array_equal(linear_sum_assignment(C), + linear_sum_assignment(np.asarray(C))) + assert_array_equal(linear_sum_assignment(C), + linear_sum_assignment(matrix(C))) + + +def test_linear_sum_assignment_input_bool(): + I = np.identity(3) + assert_array_equal(linear_sum_assignment(I.astype(np.bool_)), + linear_sum_assignment(I)) + + +def test_linear_sum_assignment_input_string(): + I = np.identity(3) + with pytest.raises(TypeError, match="Cannot cast array data"): + linear_sum_assignment(I.astype(str)) + + +def test_linear_sum_assignment_input_nan(): + I = np.diag([np.nan, 1, 1]) + with pytest.raises(ValueError, match="contains invalid numeric entries"): + linear_sum_assignment(I) + + +def test_linear_sum_assignment_input_neginf(): + I = np.diag([1, -np.inf, 1]) + with pytest.raises(ValueError, match="contains invalid numeric entries"): + linear_sum_assignment(I) + + +def test_linear_sum_assignment_input_inf(): + I = np.identity(3) + I[:, 0] = np.inf + with pytest.raises(ValueError, match="cost matrix is infeasible"): + linear_sum_assignment(I) + + +def test_constant_cost_matrix(): + # Fixes #11602 + n = 8 + C = np.ones((n, n)) + row_ind, col_ind = linear_sum_assignment(C) + assert_array_equal(row_ind, np.arange(n)) + assert_array_equal(col_ind, np.arange(n)) + + +@pytest.mark.parametrize('num_rows,num_cols', [(0, 0), (2, 0), (0, 3)]) +def test_linear_sum_assignment_trivial_cost(num_rows, num_cols): + C = np.empty(shape=(num_cols, num_rows)) + row_ind, col_ind = linear_sum_assignment(C) + assert len(row_ind) == 0 + assert len(col_ind) == 0 + + +@pytest.mark.parametrize('sign,test_case', linear_sum_assignment_test_cases) +def test_linear_sum_assignment_small_inputs(sign, test_case): + linear_sum_assignment_assertions( + linear_sum_assignment, np.array, sign, test_case) + + +# Tests that combine scipy.optimize.linear_sum_assignment and +# scipy.sparse.csgraph.min_weight_full_bipartite_matching +def test_two_methods_give_same_result_on_many_sparse_inputs(): + # As opposed to the test above, here we do not spell out the expected + # output; only assert that the two methods give the same result. + # Concretely, the below tests 100 cases of size 100x100, out of which + # 36 are infeasible. + np.random.seed(1234) + for _ in range(100): + lsa_raises = False + mwfbm_raises = False + sparse = random(100, 100, density=0.06, + data_rvs=lambda size: np.random.randint(1, 100, size)) + # In csgraph, zeros correspond to missing edges, so we explicitly + # replace those with infinities + dense = np.full(sparse.shape, np.inf) + dense[sparse.row, sparse.col] = sparse.data + sparse = sparse.tocsr() + try: + row_ind, col_ind = linear_sum_assignment(dense) + lsa_cost = dense[row_ind, col_ind].sum() + except ValueError: + lsa_raises = True + try: + row_ind, col_ind = min_weight_full_bipartite_matching(sparse) + mwfbm_cost = sparse[row_ind, col_ind].sum() + except ValueError: + mwfbm_raises = True + # Ensure that if one method raises, so does the other one. + assert lsa_raises == mwfbm_raises + if not lsa_raises: + assert lsa_cost == mwfbm_cost diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_linesearch.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_linesearch.py new file mode 100644 index 0000000000000000000000000000000000000000..6eee0743d97665185c35cf144d66e00542925480 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_linesearch.py @@ -0,0 +1,328 @@ +""" +Tests for line search routines +""" +from numpy.testing import (assert_equal, assert_array_almost_equal, + assert_array_almost_equal_nulp, assert_warns, + suppress_warnings) +import scipy.optimize._linesearch as ls +from scipy.optimize._linesearch import LineSearchWarning +import numpy as np +import pytest +import threading + + +def assert_wolfe(s, phi, derphi, c1=1e-4, c2=0.9, err_msg=""): + """ + Check that strong Wolfe conditions apply + """ + phi1 = phi(s) + phi0 = phi(0) + derphi0 = derphi(0) + derphi1 = derphi(s) + msg = (f"s = {s}; phi(0) = {phi0}; phi(s) = {phi1}; phi'(0) = {derphi0};" + f" phi'(s) = {derphi1}; {err_msg}") + + assert phi1 <= phi0 + c1*s*derphi0, "Wolfe 1 failed: " + msg + assert abs(derphi1) <= abs(c2*derphi0), "Wolfe 2 failed: " + msg + + +def assert_armijo(s, phi, c1=1e-4, err_msg=""): + """ + Check that Armijo condition applies + """ + phi1 = phi(s) + phi0 = phi(0) + msg = f"s = {s}; phi(0) = {phi0}; phi(s) = {phi1}; {err_msg}" + assert phi1 <= (1 - c1*s)*phi0, msg + + +def assert_line_wolfe(x, p, s, f, fprime, **kw): + assert_wolfe(s, phi=lambda sp: f(x + p*sp), + derphi=lambda sp: np.dot(fprime(x + p*sp), p), **kw) + + +def assert_line_armijo(x, p, s, f, **kw): + assert_armijo(s, phi=lambda sp: f(x + p*sp), **kw) + + +def assert_fp_equal(x, y, err_msg="", nulp=50): + """Assert two arrays are equal, up to some floating-point rounding error""" + try: + assert_array_almost_equal_nulp(x, y, nulp) + except AssertionError as e: + raise AssertionError(f"{e}\n{err_msg}") from e + + +class TestLineSearch: + # -- scalar functions; must have dphi(0.) < 0 + def _scalar_func_1(self, s): # skip name check + if not hasattr(self.fcount, 'c'): + self.fcount.c = 0 + self.fcount.c += 1 + p = -s - s**3 + s**4 + dp = -1 - 3*s**2 + 4*s**3 + return p, dp + + def _scalar_func_2(self, s): # skip name check + if not hasattr(self.fcount, 'c'): + self.fcount.c = 0 + self.fcount.c += 1 + p = np.exp(-4*s) + s**2 + dp = -4*np.exp(-4*s) + 2*s + return p, dp + + def _scalar_func_3(self, s): # skip name check + if not hasattr(self.fcount, 'c'): + self.fcount.c = 0 + self.fcount.c += 1 + p = -np.sin(10*s) + dp = -10*np.cos(10*s) + return p, dp + + # -- n-d functions + + def _line_func_1(self, x): # skip name check + if not hasattr(self.fcount, 'c'): + self.fcount.c = 0 + self.fcount.c += 1 + f = np.dot(x, x) + df = 2*x + return f, df + + def _line_func_2(self, x): # skip name check + if not hasattr(self.fcount, 'c'): + self.fcount.c = 0 + self.fcount.c += 1 + f = np.dot(x, np.dot(self.A, x)) + 1 + df = np.dot(self.A + self.A.T, x) + return f, df + + # -- + + def setup_method(self): + self.scalar_funcs = [] + self.line_funcs = [] + self.N = 20 + self.fcount = threading.local() + + def bind_index(func, idx): + # Remember Python's closure semantics! + return lambda *a, **kw: func(*a, **kw)[idx] + + for name in sorted(dir(self)): + if name.startswith('_scalar_func_'): + value = getattr(self, name) + self.scalar_funcs.append( + (name, bind_index(value, 0), bind_index(value, 1))) + elif name.startswith('_line_func_'): + value = getattr(self, name) + self.line_funcs.append( + (name, bind_index(value, 0), bind_index(value, 1))) + + np.random.seed(1234) + self.A = np.random.randn(self.N, self.N) + + def scalar_iter(self): + for name, phi, derphi in self.scalar_funcs: + for old_phi0 in np.random.randn(3): + yield name, phi, derphi, old_phi0 + + def line_iter(self): + rng = np.random.RandomState(1234) + for name, f, fprime in self.line_funcs: + k = 0 + while k < 9: + x = rng.randn(self.N) + p = rng.randn(self.N) + if np.dot(p, fprime(x)) >= 0: + # always pick a descent direction + continue + k += 1 + old_fv = float(rng.randn()) + yield name, f, fprime, x, p, old_fv + + # -- Generic scalar searches + + def test_scalar_search_wolfe1(self): + c = 0 + for name, phi, derphi, old_phi0 in self.scalar_iter(): + c += 1 + s, phi1, phi0 = ls.scalar_search_wolfe1(phi, derphi, phi(0), + old_phi0, derphi(0)) + assert_fp_equal(phi0, phi(0), name) + assert_fp_equal(phi1, phi(s), name) + assert_wolfe(s, phi, derphi, err_msg=name) + + assert c > 3 # check that the iterator really works... + + def test_scalar_search_wolfe2(self): + for name, phi, derphi, old_phi0 in self.scalar_iter(): + s, phi1, phi0, derphi1 = ls.scalar_search_wolfe2( + phi, derphi, phi(0), old_phi0, derphi(0)) + assert_fp_equal(phi0, phi(0), name) + assert_fp_equal(phi1, phi(s), name) + if derphi1 is not None: + assert_fp_equal(derphi1, derphi(s), name) + assert_wolfe(s, phi, derphi, err_msg=f"{name} {old_phi0:g}") + + def test_scalar_search_wolfe2_with_low_amax(self): + def phi(alpha): + return (alpha - 5) ** 2 + + def derphi(alpha): + return 2 * (alpha - 5) + + alpha_star, _, _, derphi_star = ls.scalar_search_wolfe2(phi, derphi, amax=0.001) + assert alpha_star is None # Not converged + assert derphi_star is None # Not converged + + def test_scalar_search_wolfe2_regression(self): + # Regression test for gh-12157 + # This phi has its minimum at alpha=4/3 ~ 1.333. + def phi(alpha): + if alpha < 1: + return - 3*np.pi/2 * (alpha - 1) + else: + return np.cos(3*np.pi/2 * alpha - np.pi) + + def derphi(alpha): + if alpha < 1: + return - 3*np.pi/2 + else: + return - 3*np.pi/2 * np.sin(3*np.pi/2 * alpha - np.pi) + + s, _, _, _ = ls.scalar_search_wolfe2(phi, derphi) + # Without the fix in gh-13073, the scalar_search_wolfe2 + # returned s=2.0 instead. + assert s < 1.5 + + def test_scalar_search_armijo(self): + for name, phi, derphi, old_phi0 in self.scalar_iter(): + s, phi1 = ls.scalar_search_armijo(phi, phi(0), derphi(0)) + assert_fp_equal(phi1, phi(s), name) + assert_armijo(s, phi, err_msg=f"{name} {old_phi0:g}") + + # -- Generic line searches + + def test_line_search_wolfe1(self): + c = 0 + smax = 100 + for name, f, fprime, x, p, old_f in self.line_iter(): + f0 = f(x) + g0 = fprime(x) + self.fcount.c = 0 + s, fc, gc, fv, ofv, gv = ls.line_search_wolfe1(f, fprime, x, p, + g0, f0, old_f, + amax=smax) + assert_equal(self.fcount.c, fc+gc) + assert_fp_equal(ofv, f(x)) + if s is None: + continue + assert_fp_equal(fv, f(x + s*p)) + assert_array_almost_equal(gv, fprime(x + s*p), decimal=14) + if s < smax: + c += 1 + assert_line_wolfe(x, p, s, f, fprime, err_msg=name) + + assert c > 3 # check that the iterator really works... + + def test_line_search_wolfe2(self): + c = 0 + smax = 512 + for name, f, fprime, x, p, old_f in self.line_iter(): + f0 = f(x) + g0 = fprime(x) + self.fcount.c = 0 + with suppress_warnings() as sup: + sup.filter(LineSearchWarning, + "The line search algorithm could not find a solution") + sup.filter(LineSearchWarning, + "The line search algorithm did not converge") + s, fc, gc, fv, ofv, gv = ls.line_search_wolfe2(f, fprime, x, p, + g0, f0, old_f, + amax=smax) + assert_equal(self.fcount.c, fc+gc) + assert_fp_equal(ofv, f(x)) + assert_fp_equal(fv, f(x + s*p)) + if gv is not None: + assert_array_almost_equal(gv, fprime(x + s*p), decimal=14) + if s < smax: + c += 1 + assert_line_wolfe(x, p, s, f, fprime, err_msg=name) + assert c > 3 # check that the iterator really works... + + @pytest.mark.thread_unsafe + def test_line_search_wolfe2_bounds(self): + # See gh-7475 + + # For this f and p, starting at a point on axis 0, the strong Wolfe + # condition 2 is met if and only if the step length s satisfies + # |x + s| <= c2 * |x| + def f(x): + return np.dot(x, x) + def fp(x): + return 2 * x + p = np.array([1, 0]) + + # Smallest s satisfying strong Wolfe conditions for these arguments is 30 + x = -60 * p + c2 = 0.5 + + s, _, _, _, _, _ = ls.line_search_wolfe2(f, fp, x, p, amax=30, c2=c2) + assert_line_wolfe(x, p, s, f, fp) + + s, _, _, _, _, _ = assert_warns(LineSearchWarning, + ls.line_search_wolfe2, f, fp, x, p, + amax=29, c2=c2) + assert s is None + + # s=30 will only be tried on the 6th iteration, so this won't converge + assert_warns(LineSearchWarning, ls.line_search_wolfe2, f, fp, x, p, + c2=c2, maxiter=5) + + def test_line_search_armijo(self): + c = 0 + for name, f, fprime, x, p, old_f in self.line_iter(): + f0 = f(x) + g0 = fprime(x) + self.fcount.c = 0 + s, fc, fv = ls.line_search_armijo(f, x, p, g0, f0) + c += 1 + assert_equal(self.fcount.c, fc) + assert_fp_equal(fv, f(x + s*p)) + assert_line_armijo(x, p, s, f, err_msg=name) + assert c >= 9 + + # -- More specific tests + + def test_armijo_terminate_1(self): + # Armijo should evaluate the function only once if the trial step + # is already suitable + count = [0] + + def phi(s): + count[0] += 1 + return -s + 0.01*s**2 + s, phi1 = ls.scalar_search_armijo(phi, phi(0), -1, alpha0=1) + assert_equal(s, 1) + assert_equal(count[0], 2) + assert_armijo(s, phi) + + def test_wolfe_terminate(self): + # wolfe1 and wolfe2 should also evaluate the function only a few + # times if the trial step is already suitable + + def phi(s): + count[0] += 1 + return -s + 0.05*s**2 + + def derphi(s): + count[0] += 1 + return -1 + 0.05*2*s + + for func in [ls.scalar_search_wolfe1, ls.scalar_search_wolfe2]: + count = [0] + r = func(phi, derphi, phi(0), None, derphi(0)) + assert r[0] is not None, (r, func) + assert count[0] <= 2 + 2, (count, func) + assert_wolfe(r[0], phi, derphi, err_msg=str(func)) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_linprog.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_linprog.py new file mode 100644 index 0000000000000000000000000000000000000000..4d18e68e394c31e3bc19f49e80c8e9adbc055193 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_linprog.py @@ -0,0 +1,2577 @@ +""" +Unit test for Linear Programming +""" +import sys +import platform + +import numpy as np +from numpy.testing import (assert_, assert_allclose, assert_equal, + assert_array_less, assert_warns, suppress_warnings) +from pytest import raises as assert_raises +from scipy.optimize import linprog, OptimizeWarning +from scipy.optimize._numdiff import approx_derivative +from scipy.sparse.linalg import MatrixRankWarning +from scipy.linalg import LinAlgWarning +from scipy._lib._util import VisibleDeprecationWarning +import scipy.sparse +import pytest + +has_umfpack = True +try: + from scikits.umfpack import UmfpackWarning +except ImportError: + has_umfpack = False + +has_cholmod = True +try: + import sksparse # noqa: F401 + from sksparse.cholmod import cholesky as cholmod # noqa: F401 +except ImportError: + has_cholmod = False + + +def _assert_iteration_limit_reached(res, maxiter): + assert_(not res.success, "Incorrectly reported success") + assert_(res.success < maxiter, "Incorrectly reported number of iterations") + assert_equal(res.status, 1, "Failed to report iteration limit reached") + + +def _assert_infeasible(res): + # res: linprog result object + assert_(not res.success, "incorrectly reported success") + assert_equal(res.status, 2, "failed to report infeasible status") + + +def _assert_unbounded(res): + # res: linprog result object + assert_(not res.success, "incorrectly reported success") + assert_equal(res.status, 3, "failed to report unbounded status") + + +def _assert_unable_to_find_basic_feasible_sol(res): + # res: linprog result object + + # The status may be either 2 or 4 depending on why the feasible solution + # could not be found. If the underlying problem is expected to not have a + # feasible solution, _assert_infeasible should be used. + assert_(not res.success, "incorrectly reported success") + assert_(res.status in (2, 4), "failed to report optimization failure") + + +def _assert_success(res, desired_fun=None, desired_x=None, + rtol=1e-8, atol=1e-8): + # res: linprog result object + # desired_fun: desired objective function value or None + # desired_x: desired solution or None + if not res.success: + msg = f"linprog status {res.status}, message: {res.message}" + raise AssertionError(msg) + + assert_equal(res.status, 0) + if desired_fun is not None: + assert_allclose(res.fun, desired_fun, + err_msg="converged to an unexpected objective value", + rtol=rtol, atol=atol) + if desired_x is not None: + assert_allclose(res.x, desired_x, + err_msg="converged to an unexpected solution", + rtol=rtol, atol=atol) + + +def magic_square(n): + """ + Generates a linear program for which integer solutions represent an + n x n magic square; binary decision variables represent the presence + (or absence) of an integer 1 to n^2 in each position of the square. + """ + + rng = np.random.RandomState(0) + M = n * (n**2 + 1) / 2 + + numbers = np.arange(n**4) // n**2 + 1 + + numbers = numbers.reshape(n**2, n, n) + + zeros = np.zeros((n**2, n, n)) + + A_list = [] + b_list = [] + + # Rule 1: use every number exactly once + for i in range(n**2): + A_row = zeros.copy() + A_row[i, :, :] = 1 + A_list.append(A_row.flatten()) + b_list.append(1) + + # Rule 2: Only one number per square + for i in range(n): + for j in range(n): + A_row = zeros.copy() + A_row[:, i, j] = 1 + A_list.append(A_row.flatten()) + b_list.append(1) + + # Rule 3: sum of rows is M + for i in range(n): + A_row = zeros.copy() + A_row[:, i, :] = numbers[:, i, :] + A_list.append(A_row.flatten()) + b_list.append(M) + + # Rule 4: sum of columns is M + for i in range(n): + A_row = zeros.copy() + A_row[:, :, i] = numbers[:, :, i] + A_list.append(A_row.flatten()) + b_list.append(M) + + # Rule 5: sum of diagonals is M + A_row = zeros.copy() + A_row[:, range(n), range(n)] = numbers[:, range(n), range(n)] + A_list.append(A_row.flatten()) + b_list.append(M) + A_row = zeros.copy() + A_row[:, range(n), range(-1, -n - 1, -1)] = \ + numbers[:, range(n), range(-1, -n - 1, -1)] + A_list.append(A_row.flatten()) + b_list.append(M) + + A = np.array(np.vstack(A_list), dtype=float) + b = np.array(b_list, dtype=float) + c = rng.rand(A.shape[1]) + + return A, b, c, numbers, M + + +def lpgen_2d(m, n): + """ -> A b c LP test: m*n vars, m+n constraints + row sums == n/m, col sums == 1 + https://gist.github.com/denis-bz/8647461 + """ + rng = np.random.RandomState(0) + c = - rng.exponential(size=(m, n)) + Arow = np.zeros((m, m * n)) + brow = np.zeros(m) + for j in range(m): + j1 = j + 1 + Arow[j, j * n:j1 * n] = 1 + brow[j] = n / m + + Acol = np.zeros((n, m * n)) + bcol = np.zeros(n) + for j in range(n): + j1 = j + 1 + Acol[j, j::n] = 1 + bcol[j] = 1 + + A = np.vstack((Arow, Acol)) + b = np.hstack((brow, bcol)) + + return A, b, c.ravel() + + +def very_random_gen(seed=0): + rng = np.random.RandomState(seed) + m_eq, m_ub, n = 10, 20, 50 + c = rng.rand(n)-0.5 + A_ub = rng.rand(m_ub, n)-0.5 + b_ub = rng.rand(m_ub)-0.5 + A_eq = rng.rand(m_eq, n)-0.5 + b_eq = rng.rand(m_eq)-0.5 + lb = -rng.rand(n) + ub = rng.rand(n) + lb[lb < -rng.rand()] = -np.inf + ub[ub > rng.rand()] = np.inf + bounds = np.vstack((lb, ub)).T + return c, A_ub, b_ub, A_eq, b_eq, bounds + + +def nontrivial_problem(): + c = [-1, 8, 4, -6] + A_ub = [[-7, -7, 6, 9], + [1, -1, -3, 0], + [10, -10, -7, 7], + [6, -1, 3, 4]] + b_ub = [-3, 6, -6, 6] + A_eq = [[-10, 1, 1, -8]] + b_eq = [-4] + x_star = [101 / 1391, 1462 / 1391, 0, 752 / 1391] + f_star = 7083 / 1391 + return c, A_ub, b_ub, A_eq, b_eq, x_star, f_star + + +def l1_regression_prob(seed=0, m=8, d=9, n=100): + ''' + Training data is {(x0, y0), (x1, y2), ..., (xn-1, yn-1)} + x in R^d + y in R + n: number of training samples + d: dimension of x, i.e. x in R^d + phi: feature map R^d -> R^m + m: dimension of feature space + ''' + rng = np.random.RandomState(seed) + phi = rng.normal(0, 1, size=(m, d)) # random feature mapping + w_true = rng.randn(m) + x = rng.normal(0, 1, size=(d, n)) # features + y = w_true @ (phi @ x) + rng.normal(0, 1e-5, size=n) # measurements + + # construct the problem + c = np.ones(m+n) + c[:m] = 0 + A_ub = scipy.sparse.lil_matrix((2*n, n+m)) + idx = 0 + for ii in range(n): + A_ub[idx, :m] = phi @ x[:, ii] + A_ub[idx, m+ii] = -1 + A_ub[idx+1, :m] = -1*phi @ x[:, ii] + A_ub[idx+1, m+ii] = -1 + idx += 2 + A_ub = A_ub.tocsc() + b_ub = np.zeros(2*n) + b_ub[0::2] = y + b_ub[1::2] = -y + bnds = [(None, None)]*m + [(0, None)]*n + return c, A_ub, b_ub, bnds + + +def generic_callback_test(self): + # Check that callback is as advertised + last_cb = {} + + def cb(res): + message = res.pop('message') + complete = res.pop('complete') + + assert_(res.pop('phase') in (1, 2)) + assert_(res.pop('status') in range(4)) + assert_(isinstance(res.pop('nit'), int)) + assert_(isinstance(complete, bool)) + assert_(isinstance(message, str)) + + last_cb['x'] = res['x'] + last_cb['fun'] = res['fun'] + last_cb['slack'] = res['slack'] + last_cb['con'] = res['con'] + + c = np.array([-3, -2]) + A_ub = [[2, 1], [1, 1], [1, 0]] + b_ub = [10, 8, 4] + res = linprog(c, A_ub=A_ub, b_ub=b_ub, callback=cb, method=self.method) + + _assert_success(res, desired_fun=-18.0, desired_x=[2, 6]) + assert_allclose(last_cb['fun'], res['fun']) + assert_allclose(last_cb['x'], res['x']) + assert_allclose(last_cb['con'], res['con']) + assert_allclose(last_cb['slack'], res['slack']) + + +@pytest.mark.thread_unsafe +def test_unknown_solvers_and_options(): + c = np.array([-3, -2]) + A_ub = [[2, 1], [1, 1], [1, 0]] + b_ub = [10, 8, 4] + + assert_raises(ValueError, linprog, + c, A_ub=A_ub, b_ub=b_ub, method='ekki-ekki-ekki') + assert_raises(ValueError, linprog, + c, A_ub=A_ub, b_ub=b_ub, method='highs-ekki') + message = "Unrecognized options detected: {'rr_method': 'ekki-ekki-ekki'}" + with pytest.warns(OptimizeWarning, match=message): + linprog(c, A_ub=A_ub, b_ub=b_ub, + options={"rr_method": 'ekki-ekki-ekki'}) + + +def test_choose_solver(): + # 'highs' chooses 'dual' + c = np.array([-3, -2]) + A_ub = [[2, 1], [1, 1], [1, 0]] + b_ub = [10, 8, 4] + + res = linprog(c, A_ub, b_ub, method='highs') + _assert_success(res, desired_fun=-18.0, desired_x=[2, 6]) + + +@pytest.mark.thread_unsafe +def test_deprecation(): + with pytest.warns(DeprecationWarning): + linprog(1, method='interior-point') + with pytest.warns(DeprecationWarning): + linprog(1, method='revised simplex') + with pytest.warns(DeprecationWarning): + linprog(1, method='simplex') + + +def test_highs_status_message(): + res = linprog(1, method='highs') + msg = "Optimization terminated successfully. (HiGHS Status 7:" + assert res.status == 0 + assert res.message.startswith(msg) + + A, b, c, numbers, M = magic_square(6) + bounds = [(0, 1)] * len(c) + integrality = [1] * len(c) + options = {"time_limit": 0.1} + res = linprog(c=c, A_eq=A, b_eq=b, bounds=bounds, method='highs', + options=options, integrality=integrality) + msg = "Time limit reached. (HiGHS Status 13:" + assert res.status == 1 + assert res.message.startswith(msg) + + options = {"maxiter": 10} + res = linprog(c=c, A_eq=A, b_eq=b, bounds=bounds, method='highs-ds', + options=options) + msg = "Iteration limit reached. (HiGHS Status 14:" + assert res.status == 1 + assert res.message.startswith(msg) + + res = linprog(1, bounds=(1, -1), method='highs') + msg = "The problem is infeasible. (HiGHS Status 8:" + assert res.status == 2 + assert res.message.startswith(msg) + + res = linprog(-1, method='highs') + msg = "The problem is unbounded. (HiGHS Status 10:" + assert res.status == 3 + assert res.message.startswith(msg) + + from scipy.optimize._linprog_highs import _highs_to_scipy_status_message + status, message = _highs_to_scipy_status_message(58, "Hello!") + msg = "The HiGHS status code was not recognized. (HiGHS Status 58:" + assert status == 4 + assert message.startswith(msg) + + status, message = _highs_to_scipy_status_message(None, None) + msg = "HiGHS did not provide a status code. (HiGHS Status None: None)" + assert status == 4 + assert message.startswith(msg) + + +def test_bug_17380(): + linprog([1, 1], A_ub=[[-1, 0]], b_ub=[-2.5], integrality=[1, 1]) + + +A_ub = None +b_ub = None +A_eq = None +b_eq = None +bounds = None + +################ +# Common Tests # +################ + + +class LinprogCommonTests: + """ + Base class for `linprog` tests. Generally, each test will be performed + once for every derived class of LinprogCommonTests, each of which will + typically change self.options and/or self.method. Effectively, these tests + are run for many combination of method (simplex, revised simplex, and + interior point) and options (such as pivoting rule or sparse treatment). + """ + + ################## + # Targeted Tests # + ################## + + def test_callback(self): + generic_callback_test(self) + + def test_disp(self): + # test that display option does not break anything. + A, b, c = lpgen_2d(20, 20) + res = linprog(c, A_ub=A, b_ub=b, method=self.method, + options={"disp": True}) + _assert_success(res, desired_fun=-64.049494229) + + def test_docstring_example(self): + # Example from linprog docstring. + c = [-1, 4] + A = [[-3, 1], [1, 2]] + b = [6, 4] + x0_bounds = (None, None) + x1_bounds = (-3, None) + res = linprog(c, A_ub=A, b_ub=b, bounds=(x0_bounds, x1_bounds), + options=self.options, method=self.method) + _assert_success(res, desired_fun=-22) + + def test_type_error(self): + # (presumably) checks that linprog recognizes type errors + # This is tested more carefully in test__linprog_clean_inputs.py + c = [1] + A_eq = [[1]] + b_eq = "hello" + assert_raises(TypeError, linprog, + c, A_eq=A_eq, b_eq=b_eq, + method=self.method, options=self.options) + + def test_aliasing_b_ub(self): + # (presumably) checks that linprog does not modify b_ub + # This is tested more carefully in test__linprog_clean_inputs.py + c = np.array([1.0]) + A_ub = np.array([[1.0]]) + b_ub_orig = np.array([3.0]) + b_ub = b_ub_orig.copy() + bounds = (-4.0, np.inf) + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_success(res, desired_fun=-4, desired_x=[-4]) + assert_allclose(b_ub_orig, b_ub) + + def test_aliasing_b_eq(self): + # (presumably) checks that linprog does not modify b_eq + # This is tested more carefully in test__linprog_clean_inputs.py + c = np.array([1.0]) + A_eq = np.array([[1.0]]) + b_eq_orig = np.array([3.0]) + b_eq = b_eq_orig.copy() + bounds = (-4.0, np.inf) + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_success(res, desired_fun=3, desired_x=[3]) + assert_allclose(b_eq_orig, b_eq) + + def test_non_ndarray_args(self): + # (presumably) checks that linprog accepts list in place of arrays + # This is tested more carefully in test__linprog_clean_inputs.py + c = [1.0] + A_ub = [[1.0]] + b_ub = [3.0] + A_eq = [[1.0]] + b_eq = [2.0] + bounds = (-1.0, 10.0) + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_success(res, desired_fun=2, desired_x=[2]) + + @pytest.mark.thread_unsafe + def test_unknown_options(self): + c = np.array([-3, -2]) + A_ub = [[2, 1], [1, 1], [1, 0]] + b_ub = [10, 8, 4] + + def f(c, A_ub=None, b_ub=None, A_eq=None, + b_eq=None, bounds=None, options=None): + linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=options) + + o = {key: self.options[key] for key in self.options} + o['spam'] = 42 + + assert_warns(OptimizeWarning, f, + c, A_ub=A_ub, b_ub=b_ub, options=o) + + @pytest.mark.thread_unsafe + def test_integrality_without_highs(self): + # ensure that using `integrality` parameter without `method='highs'` + # raises warning and produces correct solution to relaxed problem + # source: https://en.wikipedia.org/wiki/Integer_programming#Example + A_ub = np.array([[-1, 1], [3, 2], [2, 3]]) + b_ub = np.array([1, 12, 12]) + c = -np.array([0, 1]) + + bounds = [(0, np.inf)] * len(c) + integrality = [1] * len(c) + + with np.testing.assert_warns(OptimizeWarning): + res = linprog(c=c, A_ub=A_ub, b_ub=b_ub, bounds=bounds, + method=self.method, integrality=integrality) + + np.testing.assert_allclose(res.x, [1.8, 2.8]) + np.testing.assert_allclose(res.fun, -2.8) + + def test_invalid_inputs(self): + + def f(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None, bounds=None): + linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + + # Test ill-formatted bounds + assert_raises(ValueError, f, [1, 2, 3], bounds=[(1, 2), (3, 4)]) + with np.testing.suppress_warnings() as sup: + sup.filter(VisibleDeprecationWarning, "Creating an ndarray from ragged") + assert_raises(ValueError, f, [1, 2, 3], bounds=[(1, 2), (3, 4), (3, 4, 5)]) + assert_raises(ValueError, f, [1, 2, 3], bounds=[(1, -2), (1, 2)]) + + # Test other invalid inputs + assert_raises(ValueError, f, [1, 2], A_ub=[[1, 2]], b_ub=[1, 2]) + assert_raises(ValueError, f, [1, 2], A_ub=[[1]], b_ub=[1]) + assert_raises(ValueError, f, [1, 2], A_eq=[[1, 2]], b_eq=[1, 2]) + assert_raises(ValueError, f, [1, 2], A_eq=[[1]], b_eq=[1]) + assert_raises(ValueError, f, [1, 2], A_eq=[1], b_eq=1) + + # this last check doesn't make sense for sparse presolve + if ("_sparse_presolve" in self.options and + self.options["_sparse_presolve"]): + return + # there aren't 3-D sparse matrices + + assert_raises(ValueError, f, [1, 2], A_ub=np.zeros((1, 1, 3)), b_eq=1) + + def test_sparse_constraints(self): + # gh-13559: improve error message for sparse inputs when unsupported + def f(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None, bounds=None): + linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + + rng = np.random.RandomState(0) + m = 100 + n = 150 + A_eq = scipy.sparse.rand(m, n, 0.5) + x_valid = rng.randn(n) + c = rng.randn(n) + ub = x_valid + rng.rand(n) + lb = x_valid - rng.rand(n) + bounds = np.column_stack((lb, ub)) + b_eq = A_eq @ x_valid + + if self.method in {'simplex', 'revised simplex'}: + # simplex and revised simplex should raise error + with assert_raises(ValueError, match=f"Method '{self.method}' " + "does not support sparse constraint matrices."): + linprog(c=c, A_eq=A_eq, b_eq=b_eq, bounds=bounds, + method=self.method, options=self.options) + else: + # other methods should succeed + options = {**self.options} + if self.method in {'interior-point'}: + options['sparse'] = True + + res = linprog(c=c, A_eq=A_eq, b_eq=b_eq, bounds=bounds, + method=self.method, options=options) + assert res.success + + def test_maxiter(self): + # test iteration limit w/ Enzo example + c = [4, 8, 3, 0, 0, 0] + A = [ + [2, 5, 3, -1, 0, 0], + [3, 2.5, 8, 0, -1, 0], + [8, 10, 4, 0, 0, -1]] + b = [185, 155, 600] + np.random.seed(0) + maxiter = 3 + res = linprog(c, A_eq=A, b_eq=b, method=self.method, + options={"maxiter": maxiter}) + _assert_iteration_limit_reached(res, maxiter) + assert_equal(res.nit, maxiter) + + def test_bounds_fixed(self): + + # Test fixed bounds (upper equal to lower) + # If presolve option True, test if solution found in presolve (i.e. + # number of iterations is 0). + do_presolve = self.options.get('presolve', True) + + res = linprog([1], bounds=(1, 1), + method=self.method, options=self.options) + _assert_success(res, 1, 1) + if do_presolve: + assert_equal(res.nit, 0) + + res = linprog([1, 2, 3], bounds=[(5, 5), (-1, -1), (3, 3)], + method=self.method, options=self.options) + _assert_success(res, 12, [5, -1, 3]) + if do_presolve: + assert_equal(res.nit, 0) + + res = linprog([1, 1], bounds=[(1, 1), (1, 3)], + method=self.method, options=self.options) + _assert_success(res, 2, [1, 1]) + if do_presolve: + assert_equal(res.nit, 0) + + res = linprog([1, 1, 2], A_eq=[[1, 0, 0], [0, 1, 0]], b_eq=[1, 7], + bounds=[(-5, 5), (0, 10), (3.5, 3.5)], + method=self.method, options=self.options) + _assert_success(res, 15, [1, 7, 3.5]) + if do_presolve: + assert_equal(res.nit, 0) + + def test_bounds_infeasible(self): + + # Test ill-valued bounds (upper less than lower) + # If presolve option True, test if solution found in presolve (i.e. + # number of iterations is 0). + do_presolve = self.options.get('presolve', True) + + res = linprog([1], bounds=(1, -2), method=self.method, options=self.options) + _assert_infeasible(res) + if do_presolve: + assert_equal(res.nit, 0) + + res = linprog([1], bounds=[(1, -2)], method=self.method, options=self.options) + _assert_infeasible(res) + if do_presolve: + assert_equal(res.nit, 0) + + res = linprog([1, 2, 3], bounds=[(5, 0), (1, 2), (3, 4)], + method=self.method, options=self.options) + _assert_infeasible(res) + if do_presolve: + assert_equal(res.nit, 0) + + @pytest.mark.thread_unsafe + def test_bounds_infeasible_2(self): + + # Test ill-valued bounds (lower inf, upper -inf) + # If presolve option True, test if solution found in presolve (i.e. + # number of iterations is 0). + # For the simplex method, the cases do not result in an + # infeasible status, but in a RuntimeWarning. This is a + # consequence of having _presolve() take care of feasibility + # checks. See issue gh-11618. + do_presolve = self.options.get('presolve', True) + simplex_without_presolve = not do_presolve and self.method == 'simplex' + + c = [1, 2, 3] + bounds_1 = [(1, 2), (np.inf, np.inf), (3, 4)] + bounds_2 = [(1, 2), (-np.inf, -np.inf), (3, 4)] + + if simplex_without_presolve: + def g(c, bounds): + res = linprog(c, bounds=bounds, + method=self.method, options=self.options) + return res + + with pytest.warns(RuntimeWarning): + with pytest.raises(IndexError): + g(c, bounds=bounds_1) + + with pytest.warns(RuntimeWarning): + with pytest.raises(IndexError): + g(c, bounds=bounds_2) + else: + res = linprog(c=c, bounds=bounds_1, + method=self.method, options=self.options) + _assert_infeasible(res) + if do_presolve: + assert_equal(res.nit, 0) + res = linprog(c=c, bounds=bounds_2, + method=self.method, options=self.options) + _assert_infeasible(res) + if do_presolve: + assert_equal(res.nit, 0) + + def test_empty_constraint_1(self): + c = [-1, -2] + res = linprog(c, method=self.method, options=self.options) + _assert_unbounded(res) + + def test_empty_constraint_2(self): + c = [-1, 1, -1, 1] + bounds = [(0, np.inf), (-np.inf, 0), (-1, 1), (-1, 1)] + res = linprog(c, bounds=bounds, + method=self.method, options=self.options) + _assert_unbounded(res) + # Unboundedness detected in presolve requires no iterations + if self.options.get('presolve', True): + assert_equal(res.nit, 0) + + def test_empty_constraint_3(self): + c = [1, -1, 1, -1] + bounds = [(0, np.inf), (-np.inf, 0), (-1, 1), (-1, 1)] + res = linprog(c, bounds=bounds, + method=self.method, options=self.options) + _assert_success(res, desired_x=[0, 0, -1, 1], desired_fun=-2) + + def test_inequality_constraints(self): + # Minimize linear function subject to linear inequality constraints. + # http://www.dam.brown.edu/people/huiwang/classes/am121/Archive/simplex_121_c.pdf + c = np.array([3, 2]) * -1 # maximize + A_ub = [[2, 1], + [1, 1], + [1, 0]] + b_ub = [10, 8, 4] + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_success(res, desired_fun=-18, desired_x=[2, 6]) + + def test_inequality_constraints2(self): + # Minimize linear function subject to linear inequality constraints. + # http://www.statslab.cam.ac.uk/~ff271/teaching/opt/notes/notes8.pdf + # (dead link) + c = [6, 3] + A_ub = [[0, 3], + [-1, -1], + [-2, 1]] + b_ub = [2, -1, -1] + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_success(res, desired_fun=5, desired_x=[2 / 3, 1 / 3]) + + def test_bounds_simple(self): + c = [1, 2] + bounds = (1, 2) + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_success(res, desired_x=[1, 1]) + + bounds = [(1, 2), (1, 2)] + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_success(res, desired_x=[1, 1]) + + def test_bounded_below_only_1(self): + c = np.array([1.0]) + A_eq = np.array([[1.0]]) + b_eq = np.array([3.0]) + bounds = (1.0, None) + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_success(res, desired_fun=3, desired_x=[3]) + + def test_bounded_below_only_2(self): + c = np.ones(3) + A_eq = np.eye(3) + b_eq = np.array([1, 2, 3]) + bounds = (0.5, np.inf) + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_success(res, desired_x=b_eq, desired_fun=np.sum(b_eq)) + + def test_bounded_above_only_1(self): + c = np.array([1.0]) + A_eq = np.array([[1.0]]) + b_eq = np.array([3.0]) + bounds = (None, 10.0) + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_success(res, desired_fun=3, desired_x=[3]) + + def test_bounded_above_only_2(self): + c = np.ones(3) + A_eq = np.eye(3) + b_eq = np.array([1, 2, 3]) + bounds = (-np.inf, 4) + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_success(res, desired_x=b_eq, desired_fun=np.sum(b_eq)) + + def test_bounds_infinity(self): + c = np.ones(3) + A_eq = np.eye(3) + b_eq = np.array([1, 2, 3]) + bounds = (-np.inf, np.inf) + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_success(res, desired_x=b_eq, desired_fun=np.sum(b_eq)) + + def test_bounds_mixed(self): + # Problem has one unbounded variable and + # another with a negative lower bound. + c = np.array([-1, 4]) * -1 # maximize + A_ub = np.array([[-3, 1], + [1, 2]], dtype=np.float64) + b_ub = [6, 4] + x0_bounds = (-np.inf, np.inf) + x1_bounds = (-3, np.inf) + bounds = (x0_bounds, x1_bounds) + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_success(res, desired_fun=-80 / 7, desired_x=[-8 / 7, 18 / 7]) + + def test_bounds_equal_but_infeasible(self): + c = [-4, 1] + A_ub = [[7, -2], [0, 1], [2, -2]] + b_ub = [14, 0, 3] + bounds = [(2, 2), (0, None)] + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_infeasible(res) + + def test_bounds_equal_but_infeasible2(self): + c = [-4, 1] + A_eq = [[7, -2], [0, 1], [2, -2]] + b_eq = [14, 0, 3] + bounds = [(2, 2), (0, None)] + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_infeasible(res) + + def test_bounds_equal_no_presolve(self): + # There was a bug when a lower and upper bound were equal but + # presolve was not on to eliminate the variable. The bound + # was being converted to an equality constraint, but the bound + # was not eliminated, leading to issues in postprocessing. + c = [1, 2] + A_ub = [[1, 2], [1.1, 2.2]] + b_ub = [4, 8] + bounds = [(1, 2), (2, 2)] + + o = {key: self.options[key] for key in self.options} + o["presolve"] = False + + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=o) + _assert_infeasible(res) + + def test_zero_column_1(self): + m, n = 3, 4 + rng = np.random.RandomState(0) + c = rng.rand(n) + c[1] = 1 + A_eq = rng.rand(m, n) + A_eq[:, 1] = 0 + b_eq = rng.rand(m) + A_ub = [[1, 0, 1, 1]] + b_ub = 3 + bounds = [(-10, 10), (-10, 10), (-10, None), (None, None)] + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_success(res, desired_fun=-9.7087836730413404) + + def test_zero_column_2(self): + if self.method in {'highs-ds', 'highs-ipm'}: + # See upstream issue https://github.com/ERGO-Code/HiGHS/issues/648 + pytest.xfail() + + rng = np.random.RandomState(0) + m, n = 2, 4 + c = rng.rand(n) + c[1] = -1 + A_eq = rng.rand(m, n) + A_eq[:, 1] = 0 + b_eq = rng.rand(m) + + A_ub = rng.rand(m, n) + A_ub[:, 1] = 0 + b_ub = rng.rand(m) + bounds = (None, None) + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_unbounded(res) + # Unboundedness detected in presolve + if self.options.get('presolve', True) and "highs" not in self.method: + # HiGHS detects unboundedness or infeasibility in presolve + # It needs an iteration of simplex to be sure of unboundedness + # Other solvers report that the problem is unbounded if feasible + assert_equal(res.nit, 0) + + def test_zero_row_1(self): + c = [1, 2, 3] + A_eq = [[0, 0, 0], [1, 1, 1], [0, 0, 0]] + b_eq = [0, 3, 0] + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_success(res, desired_fun=3) + + def test_zero_row_2(self): + A_ub = [[0, 0, 0], [1, 1, 1], [0, 0, 0]] + b_ub = [0, 3, 0] + c = [1, 2, 3] + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_success(res, desired_fun=0) + + def test_zero_row_3(self): + m, n = 2, 4 + rng = np.random.RandomState(1234) + c = rng.rand(n) + A_eq = rng.rand(m, n) + A_eq[0, :] = 0 + b_eq = rng.rand(m) + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_infeasible(res) + + # Infeasibility detected in presolve + if self.options.get('presolve', True): + assert_equal(res.nit, 0) + + def test_zero_row_4(self): + m, n = 2, 4 + rng = np.random.RandomState(1234) + c = rng.rand(n) + A_ub = rng.rand(m, n) + A_ub[0, :] = 0 + b_ub = -rng.rand(m) + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_infeasible(res) + + # Infeasibility detected in presolve + if self.options.get('presolve', True): + assert_equal(res.nit, 0) + + def test_singleton_row_eq_1(self): + c = [1, 1, 1, 2] + A_eq = [[1, 0, 0, 0], [0, 2, 0, 0], [1, 0, 0, 0], [1, 1, 1, 1]] + b_eq = [1, 2, 2, 4] + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_infeasible(res) + + # Infeasibility detected in presolve + if self.options.get('presolve', True): + assert_equal(res.nit, 0) + + def test_singleton_row_eq_2(self): + c = [1, 1, 1, 2] + A_eq = [[1, 0, 0, 0], [0, 2, 0, 0], [1, 0, 0, 0], [1, 1, 1, 1]] + b_eq = [1, 2, 1, 4] + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_success(res, desired_fun=4) + + def test_singleton_row_ub_1(self): + c = [1, 1, 1, 2] + A_ub = [[1, 0, 0, 0], [0, 2, 0, 0], [-1, 0, 0, 0], [1, 1, 1, 1]] + b_ub = [1, 2, -2, 4] + bounds = [(None, None), (0, None), (0, None), (0, None)] + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_infeasible(res) + + # Infeasibility detected in presolve + if self.options.get('presolve', True): + assert_equal(res.nit, 0) + + def test_singleton_row_ub_2(self): + c = [1, 1, 1, 2] + A_ub = [[1, 0, 0, 0], [0, 2, 0, 0], [-1, 0, 0, 0], [1, 1, 1, 1]] + b_ub = [1, 2, -0.5, 4] + bounds = [(None, None), (0, None), (0, None), (0, None)] + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_success(res, desired_fun=0.5) + + def test_infeasible(self): + # Test linprog response to an infeasible problem + c = [-1, -1] + A_ub = [[1, 0], + [0, 1], + [-1, -1]] + b_ub = [2, 2, -5] + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_infeasible(res) + + def test_infeasible_inequality_bounds(self): + c = [1] + A_ub = [[2]] + b_ub = 4 + bounds = (5, 6) + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_infeasible(res) + + # Infeasibility detected in presolve + if self.options.get('presolve', True): + assert_equal(res.nit, 0) + + def test_unbounded(self): + # Test linprog response to an unbounded problem + c = np.array([1, 1]) * -1 # maximize + A_ub = [[-1, 1], + [-1, -1]] + b_ub = [-1, -2] + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_unbounded(res) + + def test_unbounded_below_no_presolve_corrected(self): + c = [1] + bounds = [(None, 1)] + + o = {key: self.options[key] for key in self.options} + o["presolve"] = False + + res = linprog(c=c, bounds=bounds, + method=self.method, + options=o) + if self.method == "revised simplex": + # Revised simplex has a special pathway for no constraints. + assert_equal(res.status, 5) + else: + _assert_unbounded(res) + + def test_unbounded_no_nontrivial_constraints_1(self): + """ + Test whether presolve pathway for detecting unboundedness after + constraint elimination is working. + """ + c = np.array([0, 0, 0, 1, -1, -1]) + A_ub = np.array([[1, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, -1]]) + b_ub = np.array([2, -2, 0]) + bounds = [(None, None), (None, None), (None, None), + (-1, 1), (-1, 1), (0, None)] + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_unbounded(res) + if not self.method.lower().startswith("highs"): + assert_equal(res.x[-1], np.inf) + assert_equal(res.message[:36], + "The problem is (trivially) unbounded") + + def test_unbounded_no_nontrivial_constraints_2(self): + """ + Test whether presolve pathway for detecting unboundedness after + constraint elimination is working. + """ + c = np.array([0, 0, 0, 1, -1, 1]) + A_ub = np.array([[1, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1]]) + b_ub = np.array([2, -2, 0]) + bounds = [(None, None), (None, None), (None, None), + (-1, 1), (-1, 1), (None, 0)] + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_unbounded(res) + if not self.method.lower().startswith("highs"): + assert_equal(res.x[-1], -np.inf) + assert_equal(res.message[:36], + "The problem is (trivially) unbounded") + + def test_cyclic_recovery(self): + # Test linprogs recovery from cycling using the Klee-Minty problem + # Klee-Minty https://www.math.ubc.ca/~israel/m340/kleemin3.pdf + c = np.array([100, 10, 1]) * -1 # maximize + A_ub = [[1, 0, 0], + [20, 1, 0], + [200, 20, 1]] + b_ub = [1, 100, 10000] + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_success(res, desired_x=[0, 0, 10000], atol=5e-6, rtol=1e-7) + + def test_cyclic_bland(self): + # Test the effect of Bland's rule on a cycling problem + c = np.array([-10, 57, 9, 24.]) + A_ub = np.array([[0.5, -5.5, -2.5, 9], + [0.5, -1.5, -0.5, 1], + [1, 0, 0, 0]]) + b_ub = [0, 0, 1] + + # copy the existing options dictionary but change maxiter + maxiter = 100 + o = {key: val for key, val in self.options.items()} + o['maxiter'] = maxiter + + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=o) + + if self.method == 'simplex' and not self.options.get('bland'): + # simplex cycles without Bland's rule + _assert_iteration_limit_reached(res, o['maxiter']) + else: + # other methods, including simplex with Bland's rule, succeed + _assert_success(res, desired_x=[1, 0, 1, 0]) + # note that revised simplex skips this test because it may or may not + # cycle depending on the initial basis + + def test_remove_redundancy_infeasibility(self): + # mostly a test of redundancy removal, which is carefully tested in + # test__remove_redundancy.py + m, n = 10, 10 + rng = np.random.RandomState(0) + c = rng.rand(n) + A_eq = rng.rand(m, n) + b_eq = rng.rand(m) + A_eq[-1, :] = 2 * A_eq[-2, :] + b_eq[-1] *= -1 + with suppress_warnings() as sup: + sup.filter(OptimizeWarning, "A_eq does not appear...") + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_infeasible(res) + + ################# + # General Tests # + ################# + + def test_nontrivial_problem(self): + # Problem involves all constraint types, + # negative resource limits, and rounding issues. + c, A_ub, b_ub, A_eq, b_eq, x_star, f_star = nontrivial_problem() + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_success(res, desired_fun=f_star, desired_x=x_star) + + def test_lpgen_problem(self): + # Test linprog with a rather large problem (400 variables, + # 40 constraints) generated by https://gist.github.com/denis-bz/8647461 + A_ub, b_ub, c = lpgen_2d(20, 20) + + with suppress_warnings() as sup: + sup.filter(OptimizeWarning, "Solving system with option 'sym_pos'") + sup.filter(RuntimeWarning, "invalid value encountered") + sup.filter(LinAlgWarning) + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_success(res, desired_fun=-64.049494229) + + def test_network_flow(self): + # A network flow problem with supply and demand at nodes + # and with costs along directed edges. + # https://www.princeton.edu/~rvdb/542/lectures/lec10.pdf + c = [2, 4, 9, 11, 4, 3, 8, 7, 0, 15, 16, 18] + n, p = -1, 1 + A_eq = [ + [n, n, p, 0, p, 0, 0, 0, 0, p, 0, 0], + [p, 0, 0, p, 0, p, 0, 0, 0, 0, 0, 0], + [0, 0, n, n, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, p, p, 0, 0, p, 0], + [0, 0, 0, 0, n, n, n, 0, p, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, n, n, 0, 0, p], + [0, 0, 0, 0, 0, 0, 0, 0, 0, n, n, n]] + b_eq = [0, 19, -16, 33, 0, 0, -36] + with suppress_warnings() as sup: + sup.filter(LinAlgWarning) + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_success(res, desired_fun=755, atol=1e-6, rtol=1e-7) + + def test_network_flow_limited_capacity(self): + # A network flow problem with supply and demand at nodes + # and with costs and capacities along directed edges. + # http://blog.sommer-forst.de/2013/04/10/ + c = [2, 2, 1, 3, 1] + bounds = [ + [0, 4], + [0, 2], + [0, 2], + [0, 3], + [0, 5]] + n, p = -1, 1 + A_eq = [ + [n, n, 0, 0, 0], + [p, 0, n, n, 0], + [0, p, p, 0, n], + [0, 0, 0, p, p]] + b_eq = [-4, 0, 0, 4] + + with suppress_warnings() as sup: + # this is an UmfpackWarning but I had trouble importing it + if has_umfpack: + sup.filter(UmfpackWarning) + sup.filter(RuntimeWarning, "scipy.linalg.solve\nIll...") + sup.filter(OptimizeWarning, "A_eq does not appear...") + sup.filter(OptimizeWarning, "Solving system with option...") + sup.filter(LinAlgWarning) + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_success(res, desired_fun=14) + + def test_simplex_algorithm_wikipedia_example(self): + # https://en.wikipedia.org/wiki/Simplex_algorithm#Example + c = [-2, -3, -4] + A_ub = [ + [3, 2, 1], + [2, 5, 3]] + b_ub = [10, 15] + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_success(res, desired_fun=-20) + + def test_enzo_example(self): + # https://github.com/scipy/scipy/issues/1779 lp2.py + # + # Translated from Octave code at: + # http://www.ecs.shimane-u.ac.jp/~kyoshida/lpeng.htm + # and placed under MIT licence by Enzo Michelangeli + # with permission explicitly granted by the original author, + # Prof. Kazunobu Yoshida + c = [4, 8, 3, 0, 0, 0] + A_eq = [ + [2, 5, 3, -1, 0, 0], + [3, 2.5, 8, 0, -1, 0], + [8, 10, 4, 0, 0, -1]] + b_eq = [185, 155, 600] + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_success(res, desired_fun=317.5, + desired_x=[66.25, 0, 17.5, 0, 183.75, 0], + atol=6e-6, rtol=1e-7) + + def test_enzo_example_b(self): + # rescued from https://github.com/scipy/scipy/pull/218 + c = [2.8, 6.3, 10.8, -2.8, -6.3, -10.8] + A_eq = [[-1, -1, -1, 0, 0, 0], + [0, 0, 0, 1, 1, 1], + [1, 0, 0, 1, 0, 0], + [0, 1, 0, 0, 1, 0], + [0, 0, 1, 0, 0, 1]] + b_eq = [-0.5, 0.4, 0.3, 0.3, 0.3] + + with suppress_warnings() as sup: + sup.filter(OptimizeWarning, "A_eq does not appear...") + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_success(res, desired_fun=-1.77, + desired_x=[0.3, 0.2, 0.0, 0.0, 0.1, 0.3]) + + def test_enzo_example_c_with_degeneracy(self): + # rescued from https://github.com/scipy/scipy/pull/218 + m = 20 + c = -np.ones(m) + tmp = 2 * np.pi * np.arange(1, m + 1) / (m + 1) + A_eq = np.vstack((np.cos(tmp) - 1, np.sin(tmp))) + b_eq = [0, 0] + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_success(res, desired_fun=0, desired_x=np.zeros(m)) + + def test_enzo_example_c_with_unboundedness(self): + # rescued from https://github.com/scipy/scipy/pull/218 + m = 50 + c = -np.ones(m) + tmp = 2 * np.pi * np.arange(m) / (m + 1) + # This test relies on `cos(0) -1 == sin(0)`, so ensure that's true + # (SIMD code or -ffast-math may cause spurious failures otherwise) + row0 = np.cos(tmp) - 1 + row0[0] = 0.0 + row1 = np.sin(tmp) + row1[0] = 0.0 + A_eq = np.vstack((row0, row1)) + b_eq = [0, 0] + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_unbounded(res) + + def test_enzo_example_c_with_infeasibility(self): + # rescued from https://github.com/scipy/scipy/pull/218 + m = 50 + c = -np.ones(m) + tmp = 2 * np.pi * np.arange(m) / (m + 1) + A_eq = np.vstack((np.cos(tmp) - 1, np.sin(tmp))) + b_eq = [1, 1] + + o = {key: self.options[key] for key in self.options} + o["presolve"] = False + + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=o) + _assert_infeasible(res) + + def test_basic_artificial_vars(self): + # Problem is chosen to test two phase simplex methods when at the end + # of phase 1 some artificial variables remain in the basis. + # Also, for `method='simplex'`, the row in the tableau corresponding + # with the artificial variables is not all zero. + c = np.array([-0.1, -0.07, 0.004, 0.004, 0.004, 0.004]) + A_ub = np.array([[1.0, 0, 0, 0, 0, 0], [-1.0, 0, 0, 0, 0, 0], + [0, -1.0, 0, 0, 0, 0], [0, 1.0, 0, 0, 0, 0], + [1.0, 1.0, 0, 0, 0, 0]]) + b_ub = np.array([3.0, 3.0, 3.0, 3.0, 20.0]) + A_eq = np.array([[1.0, 0, -1, 1, -1, 1], [0, -1.0, -1, 1, -1, 1]]) + b_eq = np.array([0, 0]) + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_success(res, desired_fun=0, desired_x=np.zeros_like(c), + atol=2e-6) + + def test_optimize_result(self): + # check all fields in OptimizeResult + c, A_ub, b_ub, A_eq, b_eq, bounds = very_random_gen(0) + res = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq, + bounds=bounds, method=self.method, options=self.options) + assert_(res.success) + assert_(res.nit) + assert_(not res.status) + if 'highs' not in self.method: + # HiGHS status/message tested separately + assert_(res.message == "Optimization terminated successfully.") + assert_allclose(c @ res.x, res.fun) + assert_allclose(b_eq - A_eq @ res.x, res.con, atol=1e-11) + assert_allclose(b_ub - A_ub @ res.x, res.slack, atol=1e-11) + for key in ['eqlin', 'ineqlin', 'lower', 'upper']: + if key in res.keys(): + assert isinstance(res[key]['marginals'], np.ndarray) + assert isinstance(res[key]['residual'], np.ndarray) + + ################# + # Bug Fix Tests # + ################# + + def test_bug_5400(self): + # https://github.com/scipy/scipy/issues/5400 + bounds = [ + (0, None), + (0, 100), (0, 100), (0, 100), (0, 100), (0, 100), (0, 100), + (0, 900), (0, 900), (0, 900), (0, 900), (0, 900), (0, 900), + (0, None), (0, None), (0, None), (0, None), (0, None), (0, None)] + + f = 1 / 9 + g = -1e4 + h = -3.1 + A_ub = np.array([ + [1, -2.99, 0, 0, -3, 0, 0, 0, -1, -1, 0, -1, -1, 1, 1, 0, 0, 0, 0], + [1, 0, -2.9, h, 0, -3, 0, -1, 0, 0, -1, 0, -1, 0, 0, 1, 1, 0, 0], + [1, 0, 0, h, 0, 0, -3, -1, -1, 0, -1, -1, 0, 0, 0, 0, 0, 1, 1], + [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1], + [0, 1.99, -1, -1, 0, 0, 0, -1, f, f, 0, 0, 0, g, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 2, -1, -1, 0, 0, 0, -1, f, f, 0, g, 0, 0, 0, 0], + [0, -1, 1.9, 2.1, 0, 0, 0, f, -1, -1, 0, 0, 0, 0, 0, g, 0, 0, 0], + [0, 0, 0, 0, -1, 2, -1, 0, 0, 0, f, -1, f, 0, 0, 0, g, 0, 0], + [0, -1, -1, 2.1, 0, 0, 0, f, f, -1, 0, 0, 0, 0, 0, 0, 0, g, 0], + [0, 0, 0, 0, -1, -1, 2, 0, 0, 0, f, f, -1, 0, 0, 0, 0, 0, g]]) + + b_ub = np.array([ + 0.0, 0, 0, 100, 100, 100, 100, 100, 100, 900, 900, 900, 900, 900, + 900, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) + + c = np.array([-1.0, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 0, 0, 0, 0, 0, 0]) + with suppress_warnings() as sup: + sup.filter(OptimizeWarning, + "Solving system with option 'sym_pos'") + sup.filter(RuntimeWarning, "invalid value encountered") + sup.filter(LinAlgWarning) + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_success(res, desired_fun=-106.63507541835018) + + def test_bug_6139(self): + # linprog(method='simplex') fails to find a basic feasible solution + # if phase 1 pseudo-objective function is outside the provided tol. + # https://github.com/scipy/scipy/issues/6139 + + # Note: This is not strictly a bug as the default tolerance determines + # if a result is "close enough" to zero and should not be expected + # to work for all cases. + + c = np.array([1, 1, 1]) + A_eq = np.array([[1., 0., 0.], [-1000., 0., - 1000.]]) + b_eq = np.array([5.00000000e+00, -1.00000000e+04]) + A_ub = -np.array([[0., 1000000., 1010000.]]) + b_ub = -np.array([10000000.]) + bounds = (None, None) + + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + + _assert_success(res, desired_fun=14.95, + desired_x=np.array([5, 4.95, 5])) + + def test_bug_6690(self): + # linprog simplex used to violate bound constraint despite reporting + # success. + # https://github.com/scipy/scipy/issues/6690 + + A_eq = np.array([[0, 0, 0, 0.93, 0, 0.65, 0, 0, 0.83, 0]]) + b_eq = np.array([0.9626]) + A_ub = np.array([ + [0, 0, 0, 1.18, 0, 0, 0, -0.2, 0, -0.22], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0.43, 0, 0, 0, 0, 0, 0], + [0, -1.22, -0.25, 0, 0, 0, -2.06, 0, 0, 1.37], + [0, 0, 0, 0, 0, 0, 0, -0.25, 0, 0] + ]) + b_ub = np.array([0.615, 0, 0.172, -0.869, -0.022]) + bounds = np.array([ + [-0.84, -0.97, 0.34, 0.4, -0.33, -0.74, 0.47, 0.09, -1.45, -0.73], + [0.37, 0.02, 2.86, 0.86, 1.18, 0.5, 1.76, 0.17, 0.32, -0.15] + ]).T + c = np.array([ + -1.64, 0.7, 1.8, -1.06, -1.16, 0.26, 2.13, 1.53, 0.66, 0.28 + ]) + + with suppress_warnings() as sup: + if has_umfpack: + sup.filter(UmfpackWarning) + sup.filter(OptimizeWarning, + "Solving system with option 'cholesky'") + sup.filter(OptimizeWarning, "Solving system with option 'sym_pos'") + sup.filter(RuntimeWarning, "invalid value encountered") + sup.filter(LinAlgWarning) + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + + desired_fun = -1.19099999999 + desired_x = np.array([0.3700, -0.9700, 0.3400, 0.4000, 1.1800, + 0.5000, 0.4700, 0.0900, 0.3200, -0.7300]) + _assert_success(res, desired_fun=desired_fun, desired_x=desired_x) + + # Add small tol value to ensure arrays are less than or equal. + atol = 1e-6 + assert_array_less(bounds[:, 0] - atol, res.x) + assert_array_less(res.x, bounds[:, 1] + atol) + + def test_bug_7044(self): + # linprog simplex failed to "identify correct constraints" (?) + # leading to a non-optimal solution if A is rank-deficient. + # https://github.com/scipy/scipy/issues/7044 + + A_eq, b_eq, c, _, _ = magic_square(3) + with suppress_warnings() as sup: + sup.filter(OptimizeWarning, "A_eq does not appear...") + sup.filter(RuntimeWarning, "invalid value encountered") + sup.filter(LinAlgWarning) + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + + desired_fun = 1.730550597 + _assert_success(res, desired_fun=desired_fun) + assert_allclose(A_eq.dot(res.x), b_eq) + assert_array_less(np.zeros(res.x.size) - 1e-5, res.x) + + def test_bug_7237(self): + # https://github.com/scipy/scipy/issues/7237 + # linprog simplex "explodes" when the pivot value is very + # close to zero. + + c = np.array([-1, 0, 0, 0, 0, 0, 0, 0, 0]) + A_ub = np.array([ + [1., -724., 911., -551., -555., -896., 478., -80., -293.], + [1., 566., 42., 937., 233., 883., 392., -909., 57.], + [1., -208., -894., 539., 321., 532., -924., 942., 55.], + [1., 857., -859., 83., 462., -265., -971., 826., 482.], + [1., 314., -424., 245., -424., 194., -443., -104., -429.], + [1., 540., 679., 361., 149., -827., 876., 633., 302.], + [0., -1., -0., -0., -0., -0., -0., -0., -0.], + [0., -0., -1., -0., -0., -0., -0., -0., -0.], + [0., -0., -0., -1., -0., -0., -0., -0., -0.], + [0., -0., -0., -0., -1., -0., -0., -0., -0.], + [0., -0., -0., -0., -0., -1., -0., -0., -0.], + [0., -0., -0., -0., -0., -0., -1., -0., -0.], + [0., -0., -0., -0., -0., -0., -0., -1., -0.], + [0., -0., -0., -0., -0., -0., -0., -0., -1.], + [0., 1., 0., 0., 0., 0., 0., 0., 0.], + [0., 0., 1., 0., 0., 0., 0., 0., 0.], + [0., 0., 0., 1., 0., 0., 0., 0., 0.], + [0., 0., 0., 0., 1., 0., 0., 0., 0.], + [0., 0., 0., 0., 0., 1., 0., 0., 0.], + [0., 0., 0., 0., 0., 0., 1., 0., 0.], + [0., 0., 0., 0., 0., 0., 0., 1., 0.], + [0., 0., 0., 0., 0., 0., 0., 0., 1.] + ]) + b_ub = np.array([ + 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., + 0., 0., 0., 1., 1., 1., 1., 1., 1., 1., 1.]) + A_eq = np.array([[0., 1., 1., 1., 1., 1., 1., 1., 1.]]) + b_eq = np.array([[1.]]) + bounds = [(None, None)] * 9 + + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_success(res, desired_fun=108.568535, atol=1e-6) + + def test_bug_8174(self): + # https://github.com/scipy/scipy/issues/8174 + # The simplex method sometimes "explodes" if the pivot value is very + # close to zero. + A_ub = np.array([ + [22714, 1008, 13380, -2713.5, -1116], + [-4986, -1092, -31220, 17386.5, 684], + [-4986, 0, 0, -2713.5, 0], + [22714, 0, 0, 17386.5, 0]]) + b_ub = np.zeros(A_ub.shape[0]) + c = -np.ones(A_ub.shape[1]) + bounds = [(0, 1)] * A_ub.shape[1] + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "invalid value encountered") + sup.filter(LinAlgWarning) + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + + if self.options.get('tol', 1e-9) < 1e-10 and self.method == 'simplex': + _assert_unable_to_find_basic_feasible_sol(res) + else: + _assert_success(res, desired_fun=-2.0080717488789235, atol=1e-6) + + def test_bug_8174_2(self): + # Test supplementary example from issue 8174. + # https://github.com/scipy/scipy/issues/8174 + # https://stackoverflow.com/questions/47717012/linprog-in-scipy-optimize-checking-solution + c = np.array([1, 0, 0, 0, 0, 0, 0]) + A_ub = -np.identity(7) + b_ub = np.array([[-2], [-2], [-2], [-2], [-2], [-2], [-2]]) + A_eq = np.array([ + [1, 1, 1, 1, 1, 1, 0], + [0.3, 1.3, 0.9, 0, 0, 0, -1], + [0.3, 0, 0, 0, 0, 0, -2/3], + [0, 0.65, 0, 0, 0, 0, -1/15], + [0, 0, 0.3, 0, 0, 0, -1/15] + ]) + b_eq = np.array([[100], [0], [0], [0], [0]]) + + with suppress_warnings() as sup: + if has_umfpack: + sup.filter(UmfpackWarning) + sup.filter(OptimizeWarning, "A_eq does not appear...") + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_success(res, desired_fun=43.3333333331385) + + def test_bug_8561(self): + # Test that pivot row is chosen correctly when using Bland's rule + # This was originally written for the simplex method with + # Bland's rule only, but it doesn't hurt to test all methods/options + # https://github.com/scipy/scipy/issues/8561 + c = np.array([7, 0, -4, 1.5, 1.5]) + A_ub = np.array([ + [4, 5.5, 1.5, 1.0, -3.5], + [1, -2.5, -2, 2.5, 0.5], + [3, -0.5, 4, -12.5, -7], + [-1, 4.5, 2, -3.5, -2], + [5.5, 2, -4.5, -1, 9.5]]) + b_ub = np.array([0, 0, 0, 0, 1]) + res = linprog(c, A_ub=A_ub, b_ub=b_ub, options=self.options, + method=self.method) + _assert_success(res, desired_x=[0, 0, 19, 16/3, 29/3]) + + def test_bug_8662(self): + # linprog simplex used to report incorrect optimal results + # https://github.com/scipy/scipy/issues/8662 + c = [-10, 10, 6, 3] + A_ub = [[8, -8, -4, 6], + [-8, 8, 4, -6], + [-4, 4, 8, -4], + [3, -3, -3, -10]] + b_ub = [9, -9, -9, -4] + bounds = [(0, None), (0, None), (0, None), (0, None)] + desired_fun = 36.0000000000 + + with suppress_warnings() as sup: + if has_umfpack: + sup.filter(UmfpackWarning) + sup.filter(RuntimeWarning, "invalid value encountered") + sup.filter(LinAlgWarning) + res1 = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + + # Set boundary condition as a constraint + A_ub.append([0, 0, -1, 0]) + b_ub.append(0) + bounds[2] = (None, None) + + with suppress_warnings() as sup: + if has_umfpack: + sup.filter(UmfpackWarning) + sup.filter(RuntimeWarning, "invalid value encountered") + sup.filter(LinAlgWarning) + res2 = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + rtol = 1e-5 + _assert_success(res1, desired_fun=desired_fun, rtol=rtol) + _assert_success(res2, desired_fun=desired_fun, rtol=rtol) + + def test_bug_8663(self): + # exposed a bug in presolve + # https://github.com/scipy/scipy/issues/8663 + c = [1, 5] + A_eq = [[0, -7]] + b_eq = [-6] + bounds = [(0, None), (None, None)] + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_success(res, desired_x=[0, 6./7], desired_fun=5*6./7) + + def test_bug_8664(self): + # interior-point has trouble with this when presolve is off + # tested for interior-point with presolve off in TestLinprogIPSpecific + # https://github.com/scipy/scipy/issues/8664 + c = [4] + A_ub = [[2], [5]] + b_ub = [4, 4] + A_eq = [[0], [-8], [9]] + b_eq = [3, 2, 10] + with suppress_warnings() as sup: + sup.filter(RuntimeWarning) + sup.filter(OptimizeWarning, "Solving system with option...") + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_infeasible(res) + + def test_bug_8973(self): + """ + Test whether bug described at: + https://github.com/scipy/scipy/issues/8973 + was fixed. + """ + c = np.array([0, 0, 0, 1, -1]) + A_ub = np.array([[1, 0, 0, 0, 0], [0, 1, 0, 0, 0]]) + b_ub = np.array([2, -2]) + bounds = [(None, None), (None, None), (None, None), (-1, 1), (-1, 1)] + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + # solution vector x is not unique + _assert_success(res, desired_fun=-2) + # HiGHS IPM had an issue where the following wasn't true! + assert_equal(c @ res.x, res.fun) + + def test_bug_8973_2(self): + """ + Additional test for: + https://github.com/scipy/scipy/issues/8973 + suggested in + https://github.com/scipy/scipy/pull/8985 + review by @antonior92 + """ + c = np.zeros(1) + A_ub = np.array([[1]]) + b_ub = np.array([-2]) + bounds = (None, None) + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_success(res, desired_x=[-2], desired_fun=0) + + def test_bug_10124(self): + """ + Test for linprog docstring problem + 'disp'=True caused revised simplex failure + """ + c = np.zeros(1) + A_ub = np.array([[1]]) + b_ub = np.array([-2]) + bounds = (None, None) + c = [-1, 4] + A_ub = [[-3, 1], [1, 2]] + b_ub = [6, 4] + bounds = [(None, None), (-3, None)] + o = {"disp": True} + o.update(self.options) + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=o) + _assert_success(res, desired_x=[10, -3], desired_fun=-22) + + def test_bug_10349(self): + """ + Test for redundancy removal tolerance issue + https://github.com/scipy/scipy/issues/10349 + """ + A_eq = np.array([[1, 1, 0, 0, 0, 0], + [0, 0, 1, 1, 0, 0], + [0, 0, 0, 0, 1, 1], + [1, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 1, 0], + [0, 1, 0, 0, 0, 1]]) + b_eq = np.array([221, 210, 10, 141, 198, 102]) + c = np.concatenate((0, 1, np.zeros(4)), axis=None) + with suppress_warnings() as sup: + sup.filter(OptimizeWarning, "A_eq does not appear...") + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options) + _assert_success(res, desired_x=[129, 92, 12, 198, 0, 10], desired_fun=92) + + @pytest.mark.skipif(sys.platform == 'darwin', + reason=("Failing on some local macOS builds, " + "see gh-13846")) + def test_bug_10466(self): + """ + Test that autoscale fixes poorly-scaled problem + """ + c = [-8., -0., -8., -0., -8., -0., -0., -0., -0., -0., -0., -0., -0.] + A_eq = [[1., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], + [0., 0., 1., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0.], + [0., 0., 0., 0., 1., 1., 0., 0., 0., 0., 0., 0., 0.], + [1., 0., 1., 0., 1., 0., -1., 0., 0., 0., 0., 0., 0.], + [1., 0., 1., 0., 1., 0., 0., 1., 0., 0., 0., 0., 0.], + [1., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0.], + [1., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0.], + [1., 0., 1., 0., 1., 0., 0., 0., 0., 0., 1., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0., 0., 0., 0., 1., 0.], + [0., 0., 1., 0., 1., 0., 0., 0., 0., 0., 0., 0., 1.]] + + b_eq = [3.14572800e+08, 4.19430400e+08, 5.24288000e+08, + 1.00663296e+09, 1.07374182e+09, 1.07374182e+09, + 1.07374182e+09, 1.07374182e+09, 1.07374182e+09, + 1.07374182e+09] + + o = {} + # HiGHS methods don't use autoscale option + if not self.method.startswith("highs"): + o = {"autoscale": True} + o.update(self.options) + + with suppress_warnings() as sup: + sup.filter(OptimizeWarning, "Solving system with option...") + if has_umfpack: + sup.filter(UmfpackWarning) + sup.filter(RuntimeWarning, "scipy.linalg.solve\nIll...") + sup.filter(RuntimeWarning, "divide by zero encountered...") + sup.filter(RuntimeWarning, "overflow encountered...") + sup.filter(RuntimeWarning, "invalid value encountered...") + sup.filter(LinAlgWarning, "Ill-conditioned matrix...") + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=o) + assert_allclose(res.fun, -8589934560) + + +######################### +# Method-specific Tests # +######################### + + +@pytest.mark.filterwarnings("ignore::DeprecationWarning") +class LinprogSimplexTests(LinprogCommonTests): + method = "simplex" + + +@pytest.mark.filterwarnings("ignore::DeprecationWarning") +class LinprogIPTests(LinprogCommonTests): + method = "interior-point" + + def test_bug_10466(self): + pytest.skip("Test is failing, but solver is deprecated.") + + +@pytest.mark.filterwarnings("ignore::DeprecationWarning") +class LinprogRSTests(LinprogCommonTests): + method = "revised simplex" + + # Revised simplex does not reliably solve these problems. + # Failure is intermittent due to the random choice of elements to complete + # the basis after phase 1 terminates. In any case, linprog exists + # gracefully, reporting numerical difficulties. I do not think this should + # prevent revised simplex from being merged, as it solves the problems + # most of the time and solves a broader range of problems than the existing + # simplex implementation. + # I believe that the root cause is the same for all three and that this + # same issue prevents revised simplex from solving many other problems + # reliably. Somehow the pivoting rule allows the algorithm to pivot into + # a singular basis. I haven't been able to find a reference that + # acknowledges this possibility, suggesting that there is a bug. On the + # other hand, the pivoting rule is quite simple, and I can't find a + # mistake, which suggests that this is a possibility with the pivoting + # rule. Hopefully, a better pivoting rule will fix the issue. + + def test_bug_5400(self): + pytest.skip("Intermittent failure acceptable.") + + def test_bug_8662(self): + pytest.skip("Intermittent failure acceptable.") + + def test_network_flow(self): + pytest.skip("Intermittent failure acceptable.") + + +class LinprogHiGHSTests(LinprogCommonTests): + def test_callback(self): + # this is the problem from test_callback + def cb(res): + return None + c = np.array([-3, -2]) + A_ub = [[2, 1], [1, 1], [1, 0]] + b_ub = [10, 8, 4] + assert_raises(NotImplementedError, linprog, c, A_ub=A_ub, b_ub=b_ub, + callback=cb, method=self.method) + res = linprog(c, A_ub=A_ub, b_ub=b_ub, method=self.method) + _assert_success(res, desired_fun=-18.0, desired_x=[2, 6]) + + @pytest.mark.thread_unsafe + @pytest.mark.parametrize("options", + [{"maxiter": -1}, + {"disp": -1}, + {"presolve": -1}, + {"time_limit": -1}, + {"dual_feasibility_tolerance": -1}, + {"primal_feasibility_tolerance": -1}, + {"ipm_optimality_tolerance": -1}, + {"simplex_dual_edge_weight_strategy": "ekki"}, + ]) + def test_invalid_option_values(self, options): + def f(options): + linprog(1, method=self.method, options=options) + options.update(self.options) + assert_warns(OptimizeWarning, f, options=options) + + def test_crossover(self): + A_eq, b_eq, c, _, _ = magic_square(4) + bounds = (0, 1) + res = linprog(c, A_eq=A_eq, b_eq=b_eq, + bounds=bounds, method=self.method, options=self.options) + # there should be nonzero crossover iterations for IPM (only) + assert_equal(res.crossover_nit == 0, self.method != "highs-ipm") + + @pytest.mark.fail_slow(10) + def test_marginals(self): + # Ensure lagrange multipliers are correct by comparing the derivative + # w.r.t. b_ub/b_eq/ub/lb to the reported duals. + c, A_ub, b_ub, A_eq, b_eq, bounds = very_random_gen(seed=0) + res = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq, + bounds=bounds, method=self.method, options=self.options) + lb, ub = bounds.T + + # sensitivity w.r.t. b_ub + def f_bub(x): + return linprog(c, A_ub, x, A_eq, b_eq, bounds, + method=self.method).fun + + dfdbub = approx_derivative(f_bub, b_ub, method='3-point', f0=res.fun) + assert_allclose(res.ineqlin.marginals, dfdbub) + + # sensitivity w.r.t. b_eq + def f_beq(x): + return linprog(c, A_ub, b_ub, A_eq, x, bounds, + method=self.method).fun + + dfdbeq = approx_derivative(f_beq, b_eq, method='3-point', f0=res.fun) + assert_allclose(res.eqlin.marginals, dfdbeq) + + # sensitivity w.r.t. lb + def f_lb(x): + bounds = np.array([x, ub]).T + return linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method).fun + + with np.errstate(invalid='ignore'): + # approx_derivative has trouble where lb is infinite + dfdlb = approx_derivative(f_lb, lb, method='3-point', f0=res.fun) + dfdlb[~np.isfinite(lb)] = 0 + + assert_allclose(res.lower.marginals, dfdlb) + + # sensitivity w.r.t. ub + def f_ub(x): + bounds = np.array([lb, x]).T + return linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method).fun + + with np.errstate(invalid='ignore'): + dfdub = approx_derivative(f_ub, ub, method='3-point', f0=res.fun) + dfdub[~np.isfinite(ub)] = 0 + + assert_allclose(res.upper.marginals, dfdub) + + def test_dual_feasibility(self): + # Ensure solution is dual feasible using marginals + c, A_ub, b_ub, A_eq, b_eq, bounds = very_random_gen(seed=42) + res = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq, + bounds=bounds, method=self.method, options=self.options) + + # KKT dual feasibility equation from Theorem 1 from + # http://www.personal.psu.edu/cxg286/LPKKT.pdf + resid = (-c + A_ub.T @ res.ineqlin.marginals + + A_eq.T @ res.eqlin.marginals + + res.upper.marginals + + res.lower.marginals) + assert_allclose(resid, 0, atol=1e-12) + + def test_complementary_slackness(self): + # Ensure that the complementary slackness condition is satisfied. + c, A_ub, b_ub, A_eq, b_eq, bounds = very_random_gen(seed=42) + res = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq, + bounds=bounds, method=self.method, options=self.options) + + # KKT complementary slackness equation from Theorem 1 from + # http://www.personal.psu.edu/cxg286/LPKKT.pdf modified for + # non-zero RHS + assert np.allclose(res.ineqlin.marginals @ (b_ub - A_ub @ res.x), 0) + + @pytest.mark.xfail(reason='Upstream / Wrapper issue, see gh-20589') + def test_bug_20336(self): + """ + Test that `linprog` now solves a poorly-scaled problem + """ + boundaries = [(10000.0, 9010000.0), (0.0, None), (10000.0, None), + (0.0, 84.62623413258109), (10000.0, None), (10000.0, None), + (10000.0, None), (10000.0, None), (10000.0, None), + (10000.0, None), (10000.0, None), (10000.0, None), + (10000.0, None), (None, None), (None, None), (None, None), + (None, None), (None, None), (None, None), (None, None), + (None, None), (None, None), (None, None), (None, None), + (None, None), (None, None), (None, None), (None, None), + (None, None), (None, None), (None, None), (None, None), + (None, None)] + eq_entries = [-1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, + -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, 1.0, 1.0, -1.0, 0.001, + -0.001, 3.7337777768059636e-10, 3.7337777768059636e-10, 1.0, -1.0, + 0.001, -0.001, 3.7337777768059636e-10, 3.7337777768059636e-10, + 1.0, -1.0, 0.001, -0.001, 3.7337777768059636e-10, + 3.7337777768059636e-10, 1.0, -1.0, 0.001, -0.001, + 3.7337777768059636e-10, 3.7337777768059636e-10, 1.0, -1.0, 0.001, + -0.001, 3.7337777768059636e-10, 3.7337777768059636e-10, 1.0, -1.0, + 0.001, -0.001, 3.7337777768059636e-10, 3.7337777768059636e-10, + 1.0, -1.0, 0.001, -0.001, 3.7337777768059636e-10, + 3.7337777768059636e-10, 1.0, -1.0, 0.001, -0.001, + 3.7337777768059636e-10, 3.7337777768059636e-10, 1.0, -1.0, 0.001, + -0.001, 3.7337777768059636e-10, 3.7337777768059636e-10, 1.0, + -1.0, 0.001, -0.001, 3.7337777768059636e-10, + 3.7337777768059636e-10, 1.0, -1.0] + eq_indizes = [0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, + 11, 11, 12, 12, 12, 12, 13, 13, 14, 14, 14, 14, 15, 15, 16, 16, + 16, 16, 17, 17, 18, 18, 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, + 22, 22, 22, 22, 23, 23, 24, 24, 24, 24, 25, 25, 26, 26, 26, 26, + 27, 27, 28, 28, 28, 28, 29, 29, 30, 30, 30, 30, 31, 31] + eq_vars = [15, 14, 17, 16, 19, 18, 21, 20, 23, 22, 25, 24, 27, 26, 29, 28, 31, + 30, 13, 1, 0, 32, 3, 14, 13, 4, 0, 4, 0, 32, 31, 2, 12, 2, 12, 16, + 15, 5, 4, 5, 4, 18, 17, 6, 5, 6, 5, 20, 19, 7, 6, 7, 6, 22, 21, 8, + 7, 8, 7, 24, 23, 9, 8, 9, 8, 26, 25, 10, 9, 10, 9, 28, 27, 11, 10, + 11, 10, 30, 29, 12, 11, 12, 11] + eq_values = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 9000000.0, 0.0, + 0.006587392118285457, -5032.197406716549, 0.0041860502789104696, + -7918.93439542944, 0.0063205763583549035, -5244.625751707402, + 0.006053760598424349, -5475.7793929428, 0.005786944838493795, + -5728.248403917573, 0.0055201290785632405, -6005.123623538355, + 0.005253313318632687, -6310.123825488683, 0.004986497558702133, + -6647.763714796453, 0.004719681798771578, -7023.578908071522, + 0.004452866038841024, -7444.431798646482] + coefficients = [0.0, 0.0, 0.0, -0.011816666666666668, 0.0, 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] + np_eq_entries = np.asarray(eq_entries, dtype=np.float64) + np_eq_indizes = np.asarray(eq_indizes, dtype=np.int32) + np_eq_vars = np.asarray(eq_vars, dtype=np.int32) + + a_eq= scipy.sparse.csr_array((np_eq_entries,(np_eq_indizes, np_eq_vars)), + shape=(32, 33)) + b_eq = np.asarray(eq_values, dtype=np.float64) + c = np.asarray(coefficients, dtype=np.float64) + + result = scipy.optimize.linprog(c, A_ub=None, b_ub=None, A_eq=a_eq, b_eq=b_eq, + bounds=boundaries) + assert result.status==0 + x = result.x + n_r_x = np.linalg.norm(a_eq @ x - b_eq) + n_r = np.linalg.norm(result.eqlin.residual) + assert_allclose(n_r, n_r_x) + + +################################ +# Simplex Option-Specific Tests# +################################ + + +class TestLinprogSimplexDefault(LinprogSimplexTests): + + def setup_method(self): + self.options = {} + + def test_bug_5400(self): + pytest.skip("Simplex fails on this problem.") + + def test_bug_7237_low_tol(self): + # Fails if the tolerance is too strict. Here, we test that + # even if the solution is wrong, the appropriate error is raised. + pytest.skip("Simplex fails on this problem.") + + @pytest.mark.thread_unsafe + def test_bug_8174_low_tol(self): + # Fails if the tolerance is too strict. Here, we test that + # even if the solution is wrong, the appropriate warning is issued. + self.options.update({'tol': 1e-12}) + with pytest.warns(OptimizeWarning): + super().test_bug_8174() + + +class TestLinprogSimplexBland(LinprogSimplexTests): + + def setup_method(self): + self.options = {'bland': True} + + def test_bug_5400(self): + pytest.skip("Simplex fails on this problem.") + + @pytest.mark.thread_unsafe + def test_bug_8174_low_tol(self): + # Fails if the tolerance is too strict. Here, we test that + # even if the solution is wrong, the appropriate error is raised. + self.options.update({'tol': 1e-12}) + with pytest.raises(AssertionError): + with pytest.warns(OptimizeWarning): + super().test_bug_8174() + + +class TestLinprogSimplexNoPresolve(LinprogSimplexTests): + + def setup_method(self): + self.options = {'presolve': False} + + is_32_bit = np.intp(0).itemsize < 8 + is_linux = sys.platform.startswith('linux') + + @pytest.mark.xfail( + condition=is_32_bit and is_linux, + reason='Fails with warning on 32-bit linux') + def test_bug_5400(self): + super().test_bug_5400() + + def test_bug_6139_low_tol(self): + # Linprog(method='simplex') fails to find a basic feasible solution + # if phase 1 pseudo-objective function is outside the provided tol. + # https://github.com/scipy/scipy/issues/6139 + # Without ``presolve`` eliminating such rows the result is incorrect. + self.options.update({'tol': 1e-12}) + with pytest.raises(AssertionError, match='linprog status 4'): + return super().test_bug_6139() + + def test_bug_7237_low_tol(self): + pytest.skip("Simplex fails on this problem.") + + @pytest.mark.thread_unsafe + def test_bug_8174_low_tol(self): + # Fails if the tolerance is too strict. Here, we test that + # even if the solution is wrong, the appropriate warning is issued. + self.options.update({'tol': 1e-12}) + with pytest.warns(OptimizeWarning): + super().test_bug_8174() + + def test_unbounded_no_nontrivial_constraints_1(self): + pytest.skip("Tests behavior specific to presolve") + + def test_unbounded_no_nontrivial_constraints_2(self): + pytest.skip("Tests behavior specific to presolve") + + +####################################### +# Interior-Point Option-Specific Tests# +####################################### + + +class TestLinprogIPDense(LinprogIPTests): + options = {"sparse": False} + + # see https://github.com/scipy/scipy/issues/20216 for skip reason + @pytest.mark.skipif( + sys.platform == 'darwin', + reason="Fails on some macOS builds for reason not relevant to test" + ) + def test_bug_6139(self): + super().test_bug_6139() + +if has_cholmod: + class TestLinprogIPSparseCholmod(LinprogIPTests): + options = {"sparse": True, "cholesky": True} + + +if has_umfpack: + class TestLinprogIPSparseUmfpack(LinprogIPTests): + options = {"sparse": True, "cholesky": False} + + def test_network_flow_limited_capacity(self): + pytest.skip("Failing due to numerical issues on some platforms.") + + +class TestLinprogIPSparse(LinprogIPTests): + options = {"sparse": True, "cholesky": False, "sym_pos": False} + + @pytest.mark.skipif( + sys.platform == 'darwin', + reason="Fails on macOS x86 Accelerate builds (gh-20510)" + ) + @pytest.mark.xfail_on_32bit("This test is sensitive to machine epsilon level " + "perturbations in linear system solution in " + "_linprog_ip._sym_solve.") + def test_bug_6139(self): + super().test_bug_6139() + + @pytest.mark.xfail(reason='Fails with ATLAS, see gh-7877') + def test_bug_6690(self): + # Test defined in base class, but can't mark as xfail there + super().test_bug_6690() + + def test_magic_square_sparse_no_presolve(self): + # test linprog with a problem with a rank-deficient A_eq matrix + A_eq, b_eq, c, _, _ = magic_square(3) + bounds = (0, 1) + + with suppress_warnings() as sup: + if has_umfpack: + sup.filter(UmfpackWarning) + sup.filter(MatrixRankWarning, "Matrix is exactly singular") + sup.filter(OptimizeWarning, "Solving system with option...") + + o = {key: self.options[key] for key in self.options} + o["presolve"] = False + + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=o) + _assert_success(res, desired_fun=1.730550597) + + def test_sparse_solve_options(self): + # checking that problem is solved with all column permutation options + A_eq, b_eq, c, _, _ = magic_square(3) + with suppress_warnings() as sup: + sup.filter(OptimizeWarning, "A_eq does not appear...") + sup.filter(OptimizeWarning, "Invalid permc_spec option") + o = {key: self.options[key] for key in self.options} + permc_specs = ('NATURAL', 'MMD_ATA', 'MMD_AT_PLUS_A', + 'COLAMD', 'ekki-ekki-ekki') + # 'ekki-ekki-ekki' raises warning about invalid permc_spec option + # and uses default + for permc_spec in permc_specs: + o["permc_spec"] = permc_spec + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=o) + _assert_success(res, desired_fun=1.730550597) + + +class TestLinprogIPSparsePresolve(LinprogIPTests): + options = {"sparse": True, "_sparse_presolve": True} + + @pytest.mark.skipif( + sys.platform == 'darwin', + reason="Fails on macOS x86 Accelerate builds (gh-20510)" + ) + @pytest.mark.xfail_on_32bit("This test is sensitive to machine epsilon level " + "perturbations in linear system solution in " + "_linprog_ip._sym_solve.") + def test_bug_6139(self): + super().test_bug_6139() + + def test_enzo_example_c_with_infeasibility(self): + pytest.skip('_sparse_presolve=True incompatible with presolve=False') + + @pytest.mark.xfail(reason='Fails with ATLAS, see gh-7877') + def test_bug_6690(self): + # Test defined in base class, but can't mark as xfail there + super().test_bug_6690() + + +@pytest.mark.filterwarnings("ignore::DeprecationWarning") +class TestLinprogIPSpecific: + method = "interior-point" + # the following tests don't need to be performed separately for + # sparse presolve, sparse after presolve, and dense + + def test_solver_select(self): + # check that default solver is selected as expected + if has_cholmod: + options = {'sparse': True, 'cholesky': True} + elif has_umfpack: + options = {'sparse': True, 'cholesky': False} + else: + options = {'sparse': True, 'cholesky': False, 'sym_pos': False} + A, b, c = lpgen_2d(20, 20) + res1 = linprog(c, A_ub=A, b_ub=b, method=self.method, options=options) + res2 = linprog(c, A_ub=A, b_ub=b, method=self.method) # default solver + assert_allclose(res1.fun, res2.fun, + err_msg="linprog default solver unexpected result", + rtol=2e-15, atol=1e-15) + + def test_unbounded_below_no_presolve_original(self): + # formerly caused segfault in TravisCI w/ "cholesky":True + c = [-1] + bounds = [(None, 1)] + res = linprog(c=c, bounds=bounds, + method=self.method, + options={"presolve": False, "cholesky": True}) + _assert_success(res, desired_fun=-1) + + def test_cholesky(self): + # use cholesky factorization and triangular solves + A, b, c = lpgen_2d(20, 20) + res = linprog(c, A_ub=A, b_ub=b, method=self.method, + options={"cholesky": True}) # only for dense + _assert_success(res, desired_fun=-64.049494229) + + def test_alternate_initial_point(self): + # use "improved" initial point + A, b, c = lpgen_2d(20, 20) + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "scipy.linalg.solve\nIll...") + sup.filter(OptimizeWarning, "Solving system with option...") + sup.filter(LinAlgWarning, "Ill-conditioned matrix...") + res = linprog(c, A_ub=A, b_ub=b, method=self.method, + options={"ip": True, "disp": True}) + # ip code is independent of sparse/dense + _assert_success(res, desired_fun=-64.049494229) + + def test_bug_8664(self): + # interior-point has trouble with this when presolve is off + c = [4] + A_ub = [[2], [5]] + b_ub = [4, 4] + A_eq = [[0], [-8], [9]] + b_eq = [3, 2, 10] + with suppress_warnings() as sup: + sup.filter(RuntimeWarning) + sup.filter(OptimizeWarning, "Solving system with option...") + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options={"presolve": False}) + assert_(not res.success, "Incorrectly reported success") + + +######################################## +# Revised Simplex Option-Specific Tests# +######################################## + + +class TestLinprogRSCommon(LinprogRSTests): + options = {} + + def test_cyclic_bland(self): + pytest.skip("Intermittent failure acceptable.") + + def test_nontrivial_problem_with_guess(self): + c, A_ub, b_ub, A_eq, b_eq, x_star, f_star = nontrivial_problem() + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options, x0=x_star) + _assert_success(res, desired_fun=f_star, desired_x=x_star) + assert_equal(res.nit, 0) + + def test_nontrivial_problem_with_unbounded_variables(self): + c, A_ub, b_ub, A_eq, b_eq, x_star, f_star = nontrivial_problem() + bounds = [(None, None), (None, None), (0, None), (None, None)] + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options, x0=x_star) + _assert_success(res, desired_fun=f_star, desired_x=x_star) + assert_equal(res.nit, 0) + + def test_nontrivial_problem_with_bounded_variables(self): + c, A_ub, b_ub, A_eq, b_eq, x_star, f_star = nontrivial_problem() + bounds = [(None, 1), (1, None), (0, None), (.4, .6)] + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options, x0=x_star) + _assert_success(res, desired_fun=f_star, desired_x=x_star) + assert_equal(res.nit, 0) + + def test_nontrivial_problem_with_negative_unbounded_variable(self): + c, A_ub, b_ub, A_eq, b_eq, x_star, f_star = nontrivial_problem() + b_eq = [4] + x_star = np.array([-219/385, 582/385, 0, 4/10]) + f_star = 3951/385 + bounds = [(None, None), (1, None), (0, None), (.4, .6)] + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options, x0=x_star) + _assert_success(res, desired_fun=f_star, desired_x=x_star) + assert_equal(res.nit, 0) + + def test_nontrivial_problem_with_bad_guess(self): + c, A_ub, b_ub, A_eq, b_eq, x_star, f_star = nontrivial_problem() + bad_guess = [1, 2, 3, .5] + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options, x0=bad_guess) + assert_equal(res.status, 6) + + def test_redundant_constraints_with_guess(self): + A, b, c, _, _ = magic_square(3) + p = np.random.rand(*c.shape) + with suppress_warnings() as sup: + sup.filter(OptimizeWarning, "A_eq does not appear...") + sup.filter(RuntimeWarning, "invalid value encountered") + sup.filter(LinAlgWarning) + res = linprog(c, A_eq=A, b_eq=b, method=self.method) + res2 = linprog(c, A_eq=A, b_eq=b, method=self.method, x0=res.x) + res3 = linprog(c + p, A_eq=A, b_eq=b, method=self.method, x0=res.x) + _assert_success(res2, desired_fun=1.730550597) + assert_equal(res2.nit, 0) + _assert_success(res3) + assert_(res3.nit < res.nit) # hot start reduces iterations + + +class TestLinprogRSBland(LinprogRSTests): + options = {"pivot": "bland"} + + +############################################ +# HiGHS-Simplex-Dual Option-Specific Tests # +############################################ + + +class TestLinprogHiGHSSimplexDual(LinprogHiGHSTests): + method = "highs-ds" + options = {} + + def test_lad_regression(self): + ''' + The scaled model should be optimal, i.e. not produce unscaled model + infeasible. See https://github.com/ERGO-Code/HiGHS/issues/494. + ''' + # Test to ensure gh-13610 is resolved (mismatch between HiGHS scaled + # and unscaled model statuses) + c, A_ub, b_ub, bnds = l1_regression_prob() + res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bnds, + method=self.method, options=self.options) + assert_equal(res.status, 0) + assert_(res.x is not None) + assert_(np.all(res.slack > -1e-6)) + assert_(np.all(res.x <= [np.inf if ub is None else ub + for lb, ub in bnds])) + assert_(np.all(res.x >= [-np.inf if lb is None else lb - 1e-7 + for lb, ub in bnds])) + + +################################### +# HiGHS-IPM Option-Specific Tests # +################################### + + +class TestLinprogHiGHSIPM(LinprogHiGHSTests): + method = "highs-ipm" + options = {} + + +################################### +# HiGHS-MIP Option-Specific Tests # +################################### + + +class TestLinprogHiGHSMIP: + method = "highs" + options = {} + + @pytest.mark.fail_slow(10) + @pytest.mark.xfail(condition=(sys.maxsize < 2 ** 32 and + platform.system() == "Linux"), + run=False, + reason="gh-16347") + def test_mip1(self): + # solve non-relaxed magic square problem (finally!) + # also check that values are all integers - they don't always + # come out of HiGHS that way + n = 4 + A, b, c, numbers, M = magic_square(n) + bounds = [(0, 1)] * len(c) + integrality = [1] * len(c) + + res = linprog(c=c*0, A_eq=A, b_eq=b, bounds=bounds, + method=self.method, integrality=integrality) + + s = (numbers.flatten() * res.x).reshape(n**2, n, n) + square = np.sum(s, axis=0) + np.testing.assert_allclose(square.sum(axis=0), M) + np.testing.assert_allclose(square.sum(axis=1), M) + np.testing.assert_allclose(np.diag(square).sum(), M) + np.testing.assert_allclose(np.diag(square[:, ::-1]).sum(), M) + + np.testing.assert_allclose(res.x, np.round(res.x), atol=1e-12) + + def test_mip2(self): + # solve MIP with inequality constraints and all integer constraints + # source: slide 5, + # https://www.cs.upc.edu/~erodri/webpage/cps/theory/lp/milp/slides.pdf + + # use all array inputs to test gh-16681 (integrality couldn't be array) + A_ub = np.array([[2, -2], [-8, 10]]) + b_ub = np.array([-1, 13]) + c = -np.array([1, 1]) + + bounds = np.array([(0, np.inf)] * len(c)) + integrality = np.ones_like(c) + + res = linprog(c=c, A_ub=A_ub, b_ub=b_ub, bounds=bounds, + method=self.method, integrality=integrality) + + np.testing.assert_allclose(res.x, [1, 2]) + np.testing.assert_allclose(res.fun, -3) + + def test_mip3(self): + # solve MIP with inequality constraints and all integer constraints + # source: https://en.wikipedia.org/wiki/Integer_programming#Example + A_ub = np.array([[-1, 1], [3, 2], [2, 3]]) + b_ub = np.array([1, 12, 12]) + c = -np.array([0, 1]) + + bounds = [(0, np.inf)] * len(c) + integrality = [1] * len(c) + + res = linprog(c=c, A_ub=A_ub, b_ub=b_ub, bounds=bounds, + method=self.method, integrality=integrality) + + np.testing.assert_allclose(res.fun, -2) + # two optimal solutions possible, just need one of them + assert np.allclose(res.x, [1, 2]) or np.allclose(res.x, [2, 2]) + + def test_mip4(self): + # solve MIP with inequality constraints and only one integer constraint + # source: https://www.mathworks.com/help/optim/ug/intlinprog.html + A_ub = np.array([[-1, -2], [-4, -1], [2, 1]]) + b_ub = np.array([14, -33, 20]) + c = np.array([8, 1]) + + bounds = [(0, np.inf)] * len(c) + integrality = [0, 1] + + res = linprog(c=c, A_ub=A_ub, b_ub=b_ub, bounds=bounds, + method=self.method, integrality=integrality) + + np.testing.assert_allclose(res.x, [6.5, 7]) + np.testing.assert_allclose(res.fun, 59) + + def test_mip5(self): + # solve MIP with inequality and inequality constraints + # source: https://www.mathworks.com/help/optim/ug/intlinprog.html + A_ub = np.array([[1, 1, 1]]) + b_ub = np.array([7]) + A_eq = np.array([[4, 2, 1]]) + b_eq = np.array([12]) + c = np.array([-3, -2, -1]) + + bounds = [(0, np.inf), (0, np.inf), (0, 1)] + integrality = [0, 1, 0] + + res = linprog(c=c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq, + bounds=bounds, method=self.method, + integrality=integrality) + + np.testing.assert_allclose(res.x, [0, 6, 0]) + np.testing.assert_allclose(res.fun, -12) + + # gh-16897: these fields were not present, ensure that they are now + assert res.get("mip_node_count", None) is not None + assert res.get("mip_dual_bound", None) is not None + assert res.get("mip_gap", None) is not None + + @pytest.mark.xslow + def test_mip6(self): + # solve a larger MIP with only equality constraints + # source: https://www.mathworks.com/help/optim/ug/intlinprog.html + A_eq = np.array([[22, 13, 26, 33, 21, 3, 14, 26], + [39, 16, 22, 28, 26, 30, 23, 24], + [18, 14, 29, 27, 30, 38, 26, 26], + [41, 26, 28, 36, 18, 38, 16, 26]]) + b_eq = np.array([7872, 10466, 11322, 12058]) + c = np.array([2, 10, 13, 17, 7, 5, 7, 3]) + + bounds = [(0, np.inf)]*8 + integrality = [1]*8 + + res = linprog(c=c, A_eq=A_eq, b_eq=b_eq, bounds=bounds, + method=self.method, integrality=integrality) + + np.testing.assert_allclose(res.fun, 1854) + + @pytest.mark.xslow + def test_mip_rel_gap_passdown(self): + # MIP taken from test_mip6, solved with different values of mip_rel_gap + # solve a larger MIP with only equality constraints + # source: https://www.mathworks.com/help/optim/ug/intlinprog.html + A_eq = np.array([[22, 13, 26, 33, 21, 3, 14, 26], + [39, 16, 22, 28, 26, 30, 23, 24], + [18, 14, 29, 27, 30, 38, 26, 26], + [41, 26, 28, 36, 18, 38, 16, 26]]) + b_eq = np.array([7872, 10466, 11322, 12058]) + c = np.array([2, 10, 13, 17, 7, 5, 7, 3]) + + bounds = [(0, np.inf)]*8 + integrality = [1]*8 + + mip_rel_gaps = [0.5, 0.25, 0.01, 0.001] + sol_mip_gaps = [] + for mip_rel_gap in mip_rel_gaps: + res = linprog(c=c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq, + bounds=bounds, method=self.method, + integrality=integrality, + options={"mip_rel_gap": mip_rel_gap}) + final_mip_gap = res["mip_gap"] + # assert that the solution actually has mip_gap lower than the + # required mip_rel_gap supplied + assert final_mip_gap <= mip_rel_gap + sol_mip_gaps.append(final_mip_gap) + + # make sure that the mip_rel_gap parameter is actually doing something + # check that differences between solution gaps are declining + # monotonically with the mip_rel_gap parameter. np.diff does + # x[i+1] - x[i], so flip the array before differencing to get + # what should be a positive, monotone decreasing series of solution + # gaps + gap_diffs = np.diff(np.flip(sol_mip_gaps)) + assert np.all(gap_diffs >= 0) + assert not np.all(gap_diffs == 0) + + def test_semi_continuous(self): + # See issue #18106. This tests whether the solution is being + # checked correctly (status is 0) when integrality > 1: + # values are allowed to be 0 even if 0 is out of bounds. + + c = np.array([1., 1., -1, -1]) + bounds = np.array([[0.5, 1.5], [0.5, 1.5], [0.5, 1.5], [0.5, 1.5]]) + integrality = np.array([2, 3, 2, 3]) + + res = linprog(c, bounds=bounds, + integrality=integrality, method='highs') + + np.testing.assert_allclose(res.x, [0, 0, 1.5, 1]) + assert res.status == 0 + + def test_bug_20584(self): + """ + Test that when integrality is a list of all zeros, linprog gives the + same result as when it is an array of all zeros / integrality=None + """ + c = [1, 1] + A_ub = [[-1, 0]] + b_ub = [-2.5] + res1 = linprog(c, A_ub=A_ub, b_ub=b_ub, integrality=[0, 0]) + res2 = linprog(c, A_ub=A_ub, b_ub=b_ub, integrality=np.asarray([0, 0])) + res3 = linprog(c, A_ub=A_ub, b_ub=b_ub, integrality=None) + assert_equal(res1.x, res2.x) + assert_equal(res1.x, res3.x) + + +########################### +# Autoscale-Specific Tests# +########################### + + +@pytest.mark.filterwarnings("ignore::DeprecationWarning") +class AutoscaleTests: + options = {"autoscale": True} + + test_bug_6139 = LinprogCommonTests.test_bug_6139 + test_bug_6690 = LinprogCommonTests.test_bug_6690 + test_bug_7237 = LinprogCommonTests.test_bug_7237 + + +class TestAutoscaleIP(AutoscaleTests): + method = "interior-point" + + def test_bug_6139(self): + self.options['tol'] = 1e-10 + return AutoscaleTests.test_bug_6139(self) + + +class TestAutoscaleSimplex(AutoscaleTests): + method = "simplex" + + +class TestAutoscaleRS(AutoscaleTests): + method = "revised simplex" + + def test_nontrivial_problem_with_guess(self): + c, A_ub, b_ub, A_eq, b_eq, x_star, f_star = nontrivial_problem() + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options, x0=x_star) + _assert_success(res, desired_fun=f_star, desired_x=x_star) + assert_equal(res.nit, 0) + + def test_nontrivial_problem_with_bad_guess(self): + c, A_ub, b_ub, A_eq, b_eq, x_star, f_star = nontrivial_problem() + bad_guess = [1, 2, 3, .5] + res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, + method=self.method, options=self.options, x0=bad_guess) + assert_equal(res.status, 6) + + +########################### +# Redundancy Removal Tests# +########################### + + +@pytest.mark.filterwarnings("ignore::DeprecationWarning") +class RRTests: + method = "interior-point" + LCT = LinprogCommonTests + # these are a few of the existing tests that have redundancy + test_RR_infeasibility = LCT.test_remove_redundancy_infeasibility + test_bug_10349 = LCT.test_bug_10349 + test_bug_7044 = LCT.test_bug_7044 + test_NFLC = LCT.test_network_flow_limited_capacity + test_enzo_example_b = LCT.test_enzo_example_b + + +class TestRRSVD(RRTests): + options = {"rr_method": "SVD"} + + +class TestRRPivot(RRTests): + options = {"rr_method": "pivot"} + + +class TestRRID(RRTests): + options = {"rr_method": "ID"} diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_lsq_common.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_lsq_common.py new file mode 100644 index 0000000000000000000000000000000000000000..650deedce88b6babd8a3f2b62a5839f1a6cb966c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_lsq_common.py @@ -0,0 +1,297 @@ +from numpy.testing import assert_, assert_allclose, assert_equal +from pytest import raises as assert_raises +import numpy as np + +from scipy.optimize._lsq.common import ( + step_size_to_bound, find_active_constraints, make_strictly_feasible, + CL_scaling_vector, intersect_trust_region, build_quadratic_1d, + minimize_quadratic_1d, evaluate_quadratic, reflective_transformation, + left_multiplied_operator, right_multiplied_operator) + + +class TestBounds: + def test_step_size_to_bounds(self): + lb = np.array([-1.0, 2.5, 10.0]) + ub = np.array([1.0, 5.0, 100.0]) + x = np.array([0.0, 2.5, 12.0]) + + s = np.array([0.1, 0.0, 0.0]) + step, hits = step_size_to_bound(x, s, lb, ub) + assert_equal(step, 10) + assert_equal(hits, [1, 0, 0]) + + s = np.array([0.01, 0.05, -1.0]) + step, hits = step_size_to_bound(x, s, lb, ub) + assert_equal(step, 2) + assert_equal(hits, [0, 0, -1]) + + s = np.array([10.0, -0.0001, 100.0]) + step, hits = step_size_to_bound(x, s, lb, ub) + assert_equal(step, np.array(-0)) + assert_equal(hits, [0, -1, 0]) + + s = np.array([1.0, 0.5, -2.0]) + step, hits = step_size_to_bound(x, s, lb, ub) + assert_equal(step, 1.0) + assert_equal(hits, [1, 0, -1]) + + s = np.zeros(3) + step, hits = step_size_to_bound(x, s, lb, ub) + assert_equal(step, np.inf) + assert_equal(hits, [0, 0, 0]) + + def test_find_active_constraints(self): + lb = np.array([0.0, -10.0, 1.0]) + ub = np.array([1.0, 0.0, 100.0]) + + x = np.array([0.5, -5.0, 2.0]) + active = find_active_constraints(x, lb, ub) + assert_equal(active, [0, 0, 0]) + + x = np.array([0.0, 0.0, 10.0]) + active = find_active_constraints(x, lb, ub) + assert_equal(active, [-1, 1, 0]) + + active = find_active_constraints(x, lb, ub, rtol=0) + assert_equal(active, [-1, 1, 0]) + + x = np.array([1e-9, -1e-8, 100 - 1e-9]) + active = find_active_constraints(x, lb, ub) + assert_equal(active, [0, 0, 1]) + + active = find_active_constraints(x, lb, ub, rtol=1.5e-9) + assert_equal(active, [-1, 0, 1]) + + lb = np.array([1.0, -np.inf, -np.inf]) + ub = np.array([np.inf, 10.0, np.inf]) + + x = np.ones(3) + active = find_active_constraints(x, lb, ub) + assert_equal(active, [-1, 0, 0]) + + # Handles out-of-bound cases. + x = np.array([0.0, 11.0, 0.0]) + active = find_active_constraints(x, lb, ub) + assert_equal(active, [-1, 1, 0]) + + active = find_active_constraints(x, lb, ub, rtol=0) + assert_equal(active, [-1, 1, 0]) + + def test_make_strictly_feasible(self): + lb = np.array([-0.5, -0.8, 2.0]) + ub = np.array([0.8, 1.0, 3.0]) + + x = np.array([-0.5, 0.0, 2 + 1e-10]) + + x_new = make_strictly_feasible(x, lb, ub, rstep=0) + assert_(x_new[0] > -0.5) + assert_equal(x_new[1:], x[1:]) + + x_new = make_strictly_feasible(x, lb, ub, rstep=1e-4) + assert_equal(x_new, [-0.5 + 1e-4, 0.0, 2 * (1 + 1e-4)]) + + x = np.array([-0.5, -1, 3.1]) + x_new = make_strictly_feasible(x, lb, ub) + assert_(np.all((x_new >= lb) & (x_new <= ub))) + + x_new = make_strictly_feasible(x, lb, ub, rstep=0) + assert_(np.all((x_new >= lb) & (x_new <= ub))) + + lb = np.array([-1, 100.0]) + ub = np.array([1, 100.0 + 1e-10]) + x = np.array([0, 100.0]) + x_new = make_strictly_feasible(x, lb, ub, rstep=1e-8) + assert_equal(x_new, [0, 100.0 + 0.5e-10]) + + def test_scaling_vector(self): + lb = np.array([-np.inf, -5.0, 1.0, -np.inf]) + ub = np.array([1.0, np.inf, 10.0, np.inf]) + x = np.array([0.5, 2.0, 5.0, 0.0]) + g = np.array([1.0, 0.1, -10.0, 0.0]) + v, dv = CL_scaling_vector(x, g, lb, ub) + assert_equal(v, [1.0, 7.0, 5.0, 1.0]) + assert_equal(dv, [0.0, 1.0, -1.0, 0.0]) + + +class TestQuadraticFunction: + def setup_method(self): + self.J = np.array([ + [0.1, 0.2], + [-1.0, 1.0], + [0.5, 0.2]]) + self.g = np.array([0.8, -2.0]) + self.diag = np.array([1.0, 2.0]) + + def test_build_quadratic_1d(self): + s = np.zeros(2) + a, b = build_quadratic_1d(self.J, self.g, s) + assert_equal(a, 0) + assert_equal(b, 0) + + a, b = build_quadratic_1d(self.J, self.g, s, diag=self.diag) + assert_equal(a, 0) + assert_equal(b, 0) + + s = np.array([1.0, -1.0]) + a, b = build_quadratic_1d(self.J, self.g, s) + assert_equal(a, 2.05) + assert_equal(b, 2.8) + + a, b = build_quadratic_1d(self.J, self.g, s, diag=self.diag) + assert_equal(a, 3.55) + assert_equal(b, 2.8) + + s0 = np.array([0.5, 0.5]) + a, b, c = build_quadratic_1d(self.J, self.g, s, diag=self.diag, s0=s0) + assert_equal(a, 3.55) + assert_allclose(b, 2.39) + assert_allclose(c, -0.1525) + + def test_minimize_quadratic_1d(self): + a = 5 + b = -1 + + t, y = minimize_quadratic_1d(a, b, 1, 2) + assert_equal(t, 1) + assert_allclose(y, a * t**2 + b * t, rtol=1e-15) + + t, y = minimize_quadratic_1d(a, b, -2, -1) + assert_equal(t, -1) + assert_allclose(y, a * t**2 + b * t, rtol=1e-15) + + t, y = minimize_quadratic_1d(a, b, -1, 1) + assert_equal(t, 0.1) + assert_allclose(y, a * t**2 + b * t, rtol=1e-15) + + c = 10 + t, y = minimize_quadratic_1d(a, b, -1, 1, c=c) + assert_equal(t, 0.1) + assert_allclose(y, a * t**2 + b * t + c, rtol=1e-15) + + t, y = minimize_quadratic_1d(a, b, -np.inf, np.inf, c=c) + assert_equal(t, 0.1) + assert_allclose(y, a * t ** 2 + b * t + c, rtol=1e-15) + + t, y = minimize_quadratic_1d(a, b, 0, np.inf, c=c) + assert_equal(t, 0.1) + assert_allclose(y, a * t ** 2 + b * t + c, rtol=1e-15) + + t, y = minimize_quadratic_1d(a, b, -np.inf, 0, c=c) + assert_equal(t, 0) + assert_allclose(y, a * t ** 2 + b * t + c, rtol=1e-15) + + a = -1 + b = 0.2 + t, y = minimize_quadratic_1d(a, b, -np.inf, np.inf) + assert_equal(y, -np.inf) + + t, y = minimize_quadratic_1d(a, b, 0, np.inf) + assert_equal(t, np.inf) + assert_equal(y, -np.inf) + + t, y = minimize_quadratic_1d(a, b, -np.inf, 0) + assert_equal(t, -np.inf) + assert_equal(y, -np.inf) + + def test_evaluate_quadratic(self): + s = np.array([1.0, -1.0]) + + value = evaluate_quadratic(self.J, self.g, s) + assert_equal(value, 4.85) + + value = evaluate_quadratic(self.J, self.g, s, diag=self.diag) + assert_equal(value, 6.35) + + s = np.array([[1.0, -1.0], + [1.0, 1.0], + [0.0, 0.0]]) + + values = evaluate_quadratic(self.J, self.g, s) + assert_allclose(values, [4.85, -0.91, 0.0]) + + values = evaluate_quadratic(self.J, self.g, s, diag=self.diag) + assert_allclose(values, [6.35, 0.59, 0.0]) + + +class TestTrustRegion: + def test_intersect(self): + Delta = 1.0 + + x = np.zeros(3) + s = np.array([1.0, 0.0, 0.0]) + t_neg, t_pos = intersect_trust_region(x, s, Delta) + assert_equal(t_neg, -1) + assert_equal(t_pos, 1) + + s = np.array([-1.0, 1.0, -1.0]) + t_neg, t_pos = intersect_trust_region(x, s, Delta) + assert_allclose(t_neg, -3**-0.5) + assert_allclose(t_pos, 3**-0.5) + + x = np.array([0.5, -0.5, 0]) + s = np.array([0, 0, 1.0]) + t_neg, t_pos = intersect_trust_region(x, s, Delta) + assert_allclose(t_neg, -2**-0.5) + assert_allclose(t_pos, 2**-0.5) + + x = np.ones(3) + assert_raises(ValueError, intersect_trust_region, x, s, Delta) + + x = np.zeros(3) + s = np.zeros(3) + assert_raises(ValueError, intersect_trust_region, x, s, Delta) + + +def test_reflective_transformation(): + lb = np.array([-1, -2], dtype=float) + ub = np.array([5, 3], dtype=float) + + y = np.array([0, 0]) + x, g = reflective_transformation(y, lb, ub) + assert_equal(x, y) + assert_equal(g, np.ones(2)) + + y = np.array([-4, 4], dtype=float) + + x, g = reflective_transformation(y, lb, np.array([np.inf, np.inf])) + assert_equal(x, [2, 4]) + assert_equal(g, [-1, 1]) + + x, g = reflective_transformation(y, np.array([-np.inf, -np.inf]), ub) + assert_equal(x, [-4, 2]) + assert_equal(g, [1, -1]) + + x, g = reflective_transformation(y, lb, ub) + assert_equal(x, [2, 2]) + assert_equal(g, [-1, -1]) + + lb = np.array([-np.inf, -2]) + ub = np.array([5, np.inf]) + y = np.array([10, 10], dtype=float) + x, g = reflective_transformation(y, lb, ub) + assert_equal(x, [0, 10]) + assert_equal(g, [-1, 1]) + + +def test_linear_operators(): + A = np.arange(6).reshape((3, 2)) + + d_left = np.array([-1, 2, 5]) + DA = np.diag(d_left).dot(A) + J_left = left_multiplied_operator(A, d_left) + + d_right = np.array([5, 10]) + AD = A.dot(np.diag(d_right)) + J_right = right_multiplied_operator(A, d_right) + + x = np.array([-2, 3]) + X = -2 * np.arange(2, 8).reshape((2, 3)) + xt = np.array([0, -2, 15]) + + assert_allclose(DA.dot(x), J_left.matvec(x)) + assert_allclose(DA.dot(X), J_left.matmat(X)) + assert_allclose(DA.T.dot(xt), J_left.rmatvec(xt)) + + assert_allclose(AD.dot(x), J_right.matvec(x)) + assert_allclose(AD.dot(X), J_right.matmat(X)) + assert_allclose(AD.T.dot(xt), J_right.rmatvec(xt)) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_lsq_linear.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_lsq_linear.py new file mode 100644 index 0000000000000000000000000000000000000000..23032e99764ed2e90d7192c078e5cb4518e328fd --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_lsq_linear.py @@ -0,0 +1,287 @@ +import pytest + +import numpy as np +from numpy.linalg import lstsq +from numpy.testing import assert_allclose, assert_equal, assert_ + +from scipy.sparse import rand, coo_matrix +from scipy.sparse.linalg import aslinearoperator +from scipy.optimize import lsq_linear +from scipy.optimize._minimize import Bounds + + +A = np.array([ + [0.171, -0.057], + [-0.049, -0.248], + [-0.166, 0.054], +]) +b = np.array([0.074, 1.014, -0.383]) + + +class BaseMixin: + def setup_method(self): + self.rnd = np.random.RandomState(0) + + def test_dense_no_bounds(self): + for lsq_solver in self.lsq_solvers: + res = lsq_linear(A, b, method=self.method, lsq_solver=lsq_solver) + assert_allclose(res.x, lstsq(A, b, rcond=-1)[0]) + assert_allclose(res.x, res.unbounded_sol[0]) + + def test_dense_bounds(self): + # Solutions for comparison are taken from MATLAB. + lb = np.array([-1, -10]) + ub = np.array([1, 0]) + unbounded_sol = lstsq(A, b, rcond=-1)[0] + for lsq_solver in self.lsq_solvers: + res = lsq_linear(A, b, (lb, ub), method=self.method, + lsq_solver=lsq_solver) + assert_allclose(res.x, lstsq(A, b, rcond=-1)[0]) + assert_allclose(res.unbounded_sol[0], unbounded_sol) + + lb = np.array([0.0, -np.inf]) + for lsq_solver in self.lsq_solvers: + res = lsq_linear(A, b, (lb, np.inf), method=self.method, + lsq_solver=lsq_solver) + assert_allclose(res.x, np.array([0.0, -4.084174437334673]), + atol=1e-6) + assert_allclose(res.unbounded_sol[0], unbounded_sol) + + lb = np.array([-1, 0]) + for lsq_solver in self.lsq_solvers: + res = lsq_linear(A, b, (lb, np.inf), method=self.method, + lsq_solver=lsq_solver) + assert_allclose(res.x, np.array([0.448427311733504, 0]), + atol=1e-15) + assert_allclose(res.unbounded_sol[0], unbounded_sol) + + ub = np.array([np.inf, -5]) + for lsq_solver in self.lsq_solvers: + res = lsq_linear(A, b, (-np.inf, ub), method=self.method, + lsq_solver=lsq_solver) + assert_allclose(res.x, np.array([-0.105560998682388, -5])) + assert_allclose(res.unbounded_sol[0], unbounded_sol) + + ub = np.array([-1, np.inf]) + for lsq_solver in self.lsq_solvers: + res = lsq_linear(A, b, (-np.inf, ub), method=self.method, + lsq_solver=lsq_solver) + assert_allclose(res.x, np.array([-1, -4.181102129483254])) + assert_allclose(res.unbounded_sol[0], unbounded_sol) + + lb = np.array([0, -4]) + ub = np.array([1, 0]) + for lsq_solver in self.lsq_solvers: + res = lsq_linear(A, b, (lb, ub), method=self.method, + lsq_solver=lsq_solver) + assert_allclose(res.x, np.array([0.005236663400791, -4])) + assert_allclose(res.unbounded_sol[0], unbounded_sol) + + def test_bounds_variants(self): + x = np.array([1, 3]) + A = self.rnd.uniform(size=(2, 2)) + b = A@x + lb = np.array([1, 1]) + ub = np.array([2, 2]) + bounds_old = (lb, ub) + bounds_new = Bounds(lb, ub) + res_old = lsq_linear(A, b, bounds_old) + res_new = lsq_linear(A, b, bounds_new) + assert not np.allclose(res_new.x, res_new.unbounded_sol[0]) + assert_allclose(res_old.x, res_new.x) + + def test_np_matrix(self): + # gh-10711 + with np.testing.suppress_warnings() as sup: + sup.filter(PendingDeprecationWarning) + A = np.matrix([[20, -4, 0, 2, 3], [10, -2, 1, 0, -1]]) + k = np.array([20, 15]) + lsq_linear(A, k) + + def test_dense_rank_deficient(self): + A = np.array([[-0.307, -0.184]]) + b = np.array([0.773]) + lb = [-0.1, -0.1] + ub = [0.1, 0.1] + for lsq_solver in self.lsq_solvers: + res = lsq_linear(A, b, (lb, ub), method=self.method, + lsq_solver=lsq_solver) + assert_allclose(res.x, [-0.1, -0.1]) + assert_allclose(res.unbounded_sol[0], lstsq(A, b, rcond=-1)[0]) + + A = np.array([ + [0.334, 0.668], + [-0.516, -1.032], + [0.192, 0.384], + ]) + b = np.array([-1.436, 0.135, 0.909]) + lb = [0, -1] + ub = [1, -0.5] + for lsq_solver in self.lsq_solvers: + res = lsq_linear(A, b, (lb, ub), method=self.method, + lsq_solver=lsq_solver) + assert_allclose(res.optimality, 0, atol=1e-11) + assert_allclose(res.unbounded_sol[0], lstsq(A, b, rcond=-1)[0]) + + def test_full_result(self): + lb = np.array([0, -4]) + ub = np.array([1, 0]) + res = lsq_linear(A, b, (lb, ub), method=self.method) + + assert_allclose(res.x, [0.005236663400791, -4]) + assert_allclose(res.unbounded_sol[0], lstsq(A, b, rcond=-1)[0]) + + r = A.dot(res.x) - b + assert_allclose(res.cost, 0.5 * np.dot(r, r)) + assert_allclose(res.fun, r) + + assert_allclose(res.optimality, 0.0, atol=1e-12) + assert_equal(res.active_mask, [0, -1]) + assert_(res.nit < 15) + assert_(res.status == 1 or res.status == 3) + assert_(isinstance(res.message, str)) + assert_(res.success) + + # This is a test for issue #9982. + def test_almost_singular(self): + A = np.array( + [[0.8854232310355122, 0.0365312146937765, 0.0365312146836789], + [0.3742460132129041, 0.0130523214078376, 0.0130523214077873], + [0.9680633871281361, 0.0319366128718639, 0.0319366128718388]]) + + b = np.array( + [0.0055029366538097, 0.0026677442422208, 0.0066612514782381]) + + result = lsq_linear(A, b, method=self.method) + assert_(result.cost < 1.1e-8) + + @pytest.mark.xslow + def test_large_rank_deficient(self): + np.random.seed(0) + n, m = np.sort(np.random.randint(2, 1000, size=2)) + m *= 2 # make m >> n + A = 1.0 * np.random.randint(-99, 99, size=[m, n]) + b = 1.0 * np.random.randint(-99, 99, size=[m]) + bounds = 1.0 * np.sort(np.random.randint(-99, 99, size=(2, n)), axis=0) + bounds[1, :] += 1.0 # ensure up > lb + + # Make the A matrix strongly rank deficient by replicating some columns + w = np.random.choice(n, n) # Select random columns with duplicates + A = A[:, w] + + x_bvls = lsq_linear(A, b, bounds=bounds, method='bvls').x + x_trf = lsq_linear(A, b, bounds=bounds, method='trf').x + + cost_bvls = np.sum((A @ x_bvls - b)**2) + cost_trf = np.sum((A @ x_trf - b)**2) + + assert_(abs(cost_bvls - cost_trf) < cost_trf*1e-10) + + def test_convergence_small_matrix(self): + A = np.array([[49.0, 41.0, -32.0], + [-19.0, -32.0, -8.0], + [-13.0, 10.0, 69.0]]) + b = np.array([-41.0, -90.0, 47.0]) + bounds = np.array([[31.0, -44.0, 26.0], + [54.0, -32.0, 28.0]]) + + x_bvls = lsq_linear(A, b, bounds=bounds, method='bvls').x + x_trf = lsq_linear(A, b, bounds=bounds, method='trf').x + + cost_bvls = np.sum((A @ x_bvls - b)**2) + cost_trf = np.sum((A @ x_trf - b)**2) + + assert_(abs(cost_bvls - cost_trf) < cost_trf*1e-10) + + +class SparseMixin: + def test_sparse_and_LinearOperator(self): + m = 5000 + n = 1000 + rng = np.random.RandomState(0) + A = rand(m, n, random_state=rng) + b = rng.randn(m) + res = lsq_linear(A, b) + assert_allclose(res.optimality, 0, atol=1e-6) + + A = aslinearoperator(A) + res = lsq_linear(A, b) + assert_allclose(res.optimality, 0, atol=1e-6) + + @pytest.mark.fail_slow(10) + def test_sparse_bounds(self): + m = 5000 + n = 1000 + rng = np.random.RandomState(0) + A = rand(m, n, random_state=rng) + b = rng.randn(m) + lb = rng.randn(n) + ub = lb + 1 + res = lsq_linear(A, b, (lb, ub)) + assert_allclose(res.optimality, 0.0, atol=1e-6) + + res = lsq_linear(A, b, (lb, ub), lsmr_tol=1e-13, + lsmr_maxiter=1500) + assert_allclose(res.optimality, 0.0, atol=1e-6) + + res = lsq_linear(A, b, (lb, ub), lsmr_tol='auto') + assert_allclose(res.optimality, 0.0, atol=1e-6) + + def test_sparse_ill_conditioned(self): + # Sparse matrix with condition number of ~4 million + data = np.array([1., 1., 1., 1. + 1e-6, 1.]) + row = np.array([0, 0, 1, 2, 2]) + col = np.array([0, 2, 1, 0, 2]) + A = coo_matrix((data, (row, col)), shape=(3, 3)) + + # Get the exact solution + exact_sol = lsq_linear(A.toarray(), b, lsq_solver='exact') + + # Default lsmr arguments should not fully converge the solution + default_lsmr_sol = lsq_linear(A, b, lsq_solver='lsmr') + with pytest.raises(AssertionError, match=""): + assert_allclose(exact_sol.x, default_lsmr_sol.x) + + # By increasing the maximum lsmr iters, it will converge + conv_lsmr = lsq_linear(A, b, lsq_solver='lsmr', lsmr_maxiter=10) + assert_allclose(exact_sol.x, conv_lsmr.x) + + +class TestTRF(BaseMixin, SparseMixin): + method = 'trf' + lsq_solvers = ['exact', 'lsmr'] + + +class TestBVLS(BaseMixin): + method = 'bvls' + lsq_solvers = ['exact'] + + +class TestErrorChecking: + def test_option_lsmr_tol(self): + # Should work with a positive float, string equal to 'auto', or None + _ = lsq_linear(A, b, lsq_solver='lsmr', lsmr_tol=1e-2) + _ = lsq_linear(A, b, lsq_solver='lsmr', lsmr_tol='auto') + _ = lsq_linear(A, b, lsq_solver='lsmr', lsmr_tol=None) + + # Should raise error with negative float, strings + # other than 'auto', and integers + err_message = "`lsmr_tol` must be None, 'auto', or positive float." + with pytest.raises(ValueError, match=err_message): + _ = lsq_linear(A, b, lsq_solver='lsmr', lsmr_tol=-0.1) + with pytest.raises(ValueError, match=err_message): + _ = lsq_linear(A, b, lsq_solver='lsmr', lsmr_tol='foo') + with pytest.raises(ValueError, match=err_message): + _ = lsq_linear(A, b, lsq_solver='lsmr', lsmr_tol=1) + + def test_option_lsmr_maxiter(self): + # Should work with positive integers or None + _ = lsq_linear(A, b, lsq_solver='lsmr', lsmr_maxiter=1) + _ = lsq_linear(A, b, lsq_solver='lsmr', lsmr_maxiter=None) + + # Should raise error with 0 or negative max iter + err_message = "`lsmr_maxiter` must be None or positive integer." + with pytest.raises(ValueError, match=err_message): + _ = lsq_linear(A, b, lsq_solver='lsmr', lsmr_maxiter=0) + with pytest.raises(ValueError, match=err_message): + _ = lsq_linear(A, b, lsq_solver='lsmr', lsmr_maxiter=-1) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_milp.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_milp.py new file mode 100644 index 0000000000000000000000000000000000000000..165417fa1c0a9799056fd67a7218499c611a673e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_milp.py @@ -0,0 +1,459 @@ +""" +Unit test for Mixed Integer Linear Programming +""" +import re +import sys + +import numpy as np +from numpy.testing import assert_allclose, assert_array_equal +import pytest + +from .test_linprog import magic_square +from scipy.optimize import milp, Bounds, LinearConstraint +from scipy import sparse + + +_IS_32BIT = (sys.maxsize < 2**32) + +def test_milp_iv(): + + message = "`c` must be a dense array" + with pytest.raises(ValueError, match=message): + milp(sparse.coo_array([0, 0])) + + message = "`c` must be a one-dimensional array of finite numbers with" + with pytest.raises(ValueError, match=message): + milp(np.zeros((3, 4))) + with pytest.raises(ValueError, match=message): + milp([]) + with pytest.raises(ValueError, match=message): + milp(None) + + message = "`bounds` must be convertible into an instance of..." + with pytest.raises(ValueError, match=message): + milp(1, bounds=10) + + message = "`constraints` (or each element within `constraints`) must be" + with pytest.raises(ValueError, match=re.escape(message)): + milp(1, constraints=10) + with pytest.raises(ValueError, match=re.escape(message)): + milp(np.zeros(3), constraints=([[1, 2, 3]], [2, 3], [2, 3])) + with pytest.raises(ValueError, match=re.escape(message)): + milp(np.zeros(2), constraints=([[1, 2]], [2], sparse.coo_array([2]))) + + message = "The shape of `A` must be (len(b_l), len(c))." + with pytest.raises(ValueError, match=re.escape(message)): + milp(np.zeros(3), constraints=([[1, 2]], [2], [2])) + + message = "`integrality` must be a dense array" + with pytest.raises(ValueError, match=message): + milp([1, 2], integrality=sparse.coo_array([1, 2])) + + message = ("`integrality` must contain integers 0-3 and be broadcastable " + "to `c.shape`.") + with pytest.raises(ValueError, match=message): + milp([1, 2, 3], integrality=[1, 2]) + with pytest.raises(ValueError, match=message): + milp([1, 2, 3], integrality=[1, 5, 3]) + + message = "Lower and upper bounds must be dense arrays." + with pytest.raises(ValueError, match=message): + milp([1, 2, 3], bounds=([1, 2], sparse.coo_array([3, 4]))) + + message = "`lb`, `ub`, and `keep_feasible` must be broadcastable." + with pytest.raises(ValueError, match=message): + milp([1, 2, 3], bounds=([1, 2], [3, 4, 5])) + with pytest.raises(ValueError, match=message): + milp([1, 2, 3], bounds=([1, 2, 3], [4, 5])) + + message = "`bounds.lb` and `bounds.ub` must contain reals and..." + with pytest.raises(ValueError, match=message): + milp([1, 2, 3], bounds=([1, 2], [3, 4])) + with pytest.raises(ValueError, match=message): + milp([1, 2, 3], bounds=([1, 2, 3], ["3+4", 4, 5])) + with pytest.raises(ValueError, match=message): + milp([1, 2, 3], bounds=([1, 2, 3], [set(), 4, 5])) + + +@pytest.mark.xfail(run=False, + reason="Needs to be fixed in `_highs_wrapper`") +def test_milp_options(capsys): + # run=False now because of gh-16347 + message = "Unrecognized options detected: {'ekki'}..." + options = {'ekki': True} + with pytest.warns(RuntimeWarning, match=message): + milp(1, options=options) + + A, b, c, numbers, M = magic_square(3) + options = {"disp": True, "presolve": False, "time_limit": 0.05} + res = milp(c=c, constraints=(A, b, b), bounds=(0, 1), integrality=1, + options=options) + + captured = capsys.readouterr() + assert "Presolve is switched off" in captured.out + assert "Time Limit Reached" in captured.out + assert not res.success + + +def test_result(): + A, b, c, numbers, M = magic_square(3) + res = milp(c=c, constraints=(A, b, b), bounds=(0, 1), integrality=1) + assert res.status == 0 + assert res.success + msg = "Optimization terminated successfully. (HiGHS Status 7:" + assert res.message.startswith(msg) + assert isinstance(res.x, np.ndarray) + assert isinstance(res.fun, float) + assert isinstance(res.mip_node_count, int) + assert isinstance(res.mip_dual_bound, float) + assert isinstance(res.mip_gap, float) + + A, b, c, numbers, M = magic_square(6) + res = milp(c=c*0, constraints=(A, b, b), bounds=(0, 1), integrality=1, + options={'time_limit': 0.05}) + assert res.status == 1 + assert not res.success + msg = "Time limit reached. (HiGHS Status 13:" + assert res.message.startswith(msg) + assert (res.fun is res.mip_dual_bound is res.mip_gap + is res.mip_node_count is res.x is None) + + res = milp(1, bounds=(1, -1)) + assert res.status == 2 + assert not res.success + msg = "The problem is infeasible. (HiGHS Status 8:" + assert res.message.startswith(msg) + assert (res.fun is res.mip_dual_bound is res.mip_gap + is res.mip_node_count is res.x is None) + + res = milp(-1) + assert res.status == 3 + assert not res.success + msg = "The problem is unbounded. (HiGHS Status 10:" + assert res.message.startswith(msg) + assert (res.fun is res.mip_dual_bound is res.mip_gap + is res.mip_node_count is res.x is None) + + +def test_milp_optional_args(): + # check that arguments other than `c` are indeed optional + res = milp(1) + assert res.fun == 0 + assert_array_equal(res.x, [0]) + + +def test_milp_1(): + # solve magic square problem + n = 3 + A, b, c, numbers, M = magic_square(n) + A = sparse.csc_array(A) # confirm that sparse arrays are accepted + res = milp(c=c*0, constraints=(A, b, b), bounds=(0, 1), integrality=1) + + # check that solution is a magic square + x = np.round(res.x) + s = (numbers.flatten() * x).reshape(n**2, n, n) + square = np.sum(s, axis=0) + np.testing.assert_allclose(square.sum(axis=0), M) + np.testing.assert_allclose(square.sum(axis=1), M) + np.testing.assert_allclose(np.diag(square).sum(), M) + np.testing.assert_allclose(np.diag(square[:, ::-1]).sum(), M) + + +def test_milp_2(): + # solve MIP with inequality constraints and all integer constraints + # source: slide 5, + # https://www.cs.upc.edu/~erodri/webpage/cps/theory/lp/milp/slides.pdf + # also check that `milp` accepts all valid ways of specifying constraints + c = -np.ones(2) + A = [[-2, 2], [-8, 10]] + b_l = [1, -np.inf] + b_u = [np.inf, 13] + linear_constraint = LinearConstraint(A, b_l, b_u) + + # solve original problem + res1 = milp(c=c, constraints=(A, b_l, b_u), integrality=True) + res2 = milp(c=c, constraints=linear_constraint, integrality=True) + res3 = milp(c=c, constraints=[(A, b_l, b_u)], integrality=True) + res4 = milp(c=c, constraints=[linear_constraint], integrality=True) + res5 = milp(c=c, integrality=True, + constraints=[(A[:1], b_l[:1], b_u[:1]), + (A[1:], b_l[1:], b_u[1:])]) + res6 = milp(c=c, integrality=True, + constraints=[LinearConstraint(A[:1], b_l[:1], b_u[:1]), + LinearConstraint(A[1:], b_l[1:], b_u[1:])]) + res7 = milp(c=c, integrality=True, + constraints=[(A[:1], b_l[:1], b_u[:1]), + LinearConstraint(A[1:], b_l[1:], b_u[1:])]) + xs = np.array([res1.x, res2.x, res3.x, res4.x, res5.x, res6.x, res7.x]) + funs = np.array([res1.fun, res2.fun, res3.fun, + res4.fun, res5.fun, res6.fun, res7.fun]) + np.testing.assert_allclose(xs, np.broadcast_to([1, 2], xs.shape)) + np.testing.assert_allclose(funs, -3) + + # solve relaxed problem + res = milp(c=c, constraints=(A, b_l, b_u)) + np.testing.assert_allclose(res.x, [4, 4.5]) + np.testing.assert_allclose(res.fun, -8.5) + + +def test_milp_3(): + # solve MIP with inequality constraints and all integer constraints + # source: https://en.wikipedia.org/wiki/Integer_programming#Example + c = [0, -1] + A = [[-1, 1], [3, 2], [2, 3]] + b_u = [1, 12, 12] + b_l = np.full_like(b_u, -np.inf, dtype=np.float64) + constraints = LinearConstraint(A, b_l, b_u) + + integrality = np.ones_like(c) + + # solve original problem + res = milp(c=c, constraints=constraints, integrality=integrality) + assert_allclose(res.fun, -2) + # two optimal solutions possible, just need one of them + assert np.allclose(res.x, [1, 2]) or np.allclose(res.x, [2, 2]) + + # solve relaxed problem + res = milp(c=c, constraints=constraints) + assert_allclose(res.fun, -2.8) + assert_allclose(res.x, [1.8, 2.8]) + + +def test_milp_4(): + # solve MIP with inequality constraints and only one integer constraint + # source: https://www.mathworks.com/help/optim/ug/intlinprog.html + c = [8, 1] + integrality = [0, 1] + A = [[1, 2], [-4, -1], [2, 1]] + b_l = [-14, -np.inf, -np.inf] + b_u = [np.inf, -33, 20] + constraints = LinearConstraint(A, b_l, b_u) + bounds = Bounds(-np.inf, np.inf) + + res = milp(c, integrality=integrality, bounds=bounds, + constraints=constraints) + assert_allclose(res.fun, 59) + assert_allclose(res.x, [6.5, 7]) + + +def test_milp_5(): + # solve MIP with inequality and equality constraints + # source: https://www.mathworks.com/help/optim/ug/intlinprog.html + c = [-3, -2, -1] + integrality = [0, 0, 1] + lb = [0, 0, 0] + ub = [np.inf, np.inf, 1] + bounds = Bounds(lb, ub) + A = [[1, 1, 1], [4, 2, 1]] + b_l = [-np.inf, 12] + b_u = [7, 12] + constraints = LinearConstraint(A, b_l, b_u) + + res = milp(c, integrality=integrality, bounds=bounds, + constraints=constraints) + # there are multiple solutions + assert_allclose(res.fun, -12) + + +@pytest.mark.xslow +def test_milp_6(): + # solve a larger MIP with only equality constraints + # source: https://www.mathworks.com/help/optim/ug/intlinprog.html + integrality = 1 + A_eq = np.array([[22, 13, 26, 33, 21, 3, 14, 26], + [39, 16, 22, 28, 26, 30, 23, 24], + [18, 14, 29, 27, 30, 38, 26, 26], + [41, 26, 28, 36, 18, 38, 16, 26]]) + b_eq = np.array([7872, 10466, 11322, 12058]) + c = np.array([2, 10, 13, 17, 7, 5, 7, 3]) + + res = milp(c=c, constraints=(A_eq, b_eq, b_eq), integrality=integrality) + + np.testing.assert_allclose(res.fun, 1854) + + +def test_infeasible_prob_16609(): + # Ensure presolve does not mark trivially infeasible problems + # as Optimal -- see gh-16609 + c = [1.0, 0.0] + integrality = [0, 1] + + lb = [0, -np.inf] + ub = [np.inf, np.inf] + bounds = Bounds(lb, ub) + + A_eq = [[0.0, 1.0]] + b_eq = [0.5] + constraints = LinearConstraint(A_eq, b_eq, b_eq) + + res = milp(c, integrality=integrality, bounds=bounds, + constraints=constraints) + np.testing.assert_equal(res.status, 2) + + +_msg_time = "Time limit reached. (HiGHS Status 13:" +_msg_iter = "Iteration limit reached. (HiGHS Status 14:" + +@pytest.mark.thread_unsafe +# See https://github.com/scipy/scipy/pull/19255#issuecomment-1778438888 +@pytest.mark.xfail(reason="Often buggy, revisit with callbacks, gh-19255") +@pytest.mark.skipif(np.intp(0).itemsize < 8, + reason="Unhandled 32-bit GCC FP bug") +@pytest.mark.slow +@pytest.mark.parametrize(["options", "msg"], [({"time_limit": 0.1}, _msg_time), + ({"node_limit": 1}, _msg_iter)]) +def test_milp_timeout_16545(options, msg): + # Ensure solution is not thrown away if MILP solver times out + # -- see gh-16545 + rng = np.random.default_rng(5123833489170494244) + A = rng.integers(0, 5, size=(100, 100)) + b_lb = np.full(100, fill_value=-np.inf) + b_ub = np.full(100, fill_value=25) + constraints = LinearConstraint(A, b_lb, b_ub) + variable_lb = np.zeros(100) + variable_ub = np.ones(100) + variable_bounds = Bounds(variable_lb, variable_ub) + integrality = np.ones(100) + c_vector = -np.ones(100) + res = milp( + c_vector, + integrality=integrality, + bounds=variable_bounds, + constraints=constraints, + options=options, + ) + + assert res.message.startswith(msg) + assert res["x"] is not None + + # ensure solution is feasible + x = res["x"] + tol = 1e-8 # sometimes needed due to finite numerical precision + assert np.all(b_lb - tol <= A @ x) and np.all(A @ x <= b_ub + tol) + assert np.all(variable_lb - tol <= x) and np.all(x <= variable_ub + tol) + assert np.allclose(x, np.round(x)) + + +def test_three_constraints_16878(): + # `milp` failed when exactly three constraints were passed + # Ensure that this is no longer the case. + rng = np.random.default_rng(5123833489170494244) + A = rng.integers(0, 5, size=(6, 6)) + bl = np.full(6, fill_value=-np.inf) + bu = np.full(6, fill_value=10) + constraints = [LinearConstraint(A[:2], bl[:2], bu[:2]), + LinearConstraint(A[2:4], bl[2:4], bu[2:4]), + LinearConstraint(A[4:], bl[4:], bu[4:])] + constraints2 = [(A[:2], bl[:2], bu[:2]), + (A[2:4], bl[2:4], bu[2:4]), + (A[4:], bl[4:], bu[4:])] + lb = np.zeros(6) + ub = np.ones(6) + variable_bounds = Bounds(lb, ub) + c = -np.ones(6) + res1 = milp(c, bounds=variable_bounds, constraints=constraints) + res2 = milp(c, bounds=variable_bounds, constraints=constraints2) + ref = milp(c, bounds=variable_bounds, constraints=(A, bl, bu)) + assert res1.success and res2.success + assert_allclose(res1.x, ref.x) + assert_allclose(res2.x, ref.x) + + +@pytest.mark.xslow +def test_mip_rel_gap_passdown(): + # Solve problem with decreasing mip_gap to make sure mip_rel_gap decreases + # Adapted from test_linprog::TestLinprogHiGHSMIP::test_mip_rel_gap_passdown + # MIP taken from test_mip_6 above + A_eq = np.array([[22, 13, 26, 33, 21, 3, 14, 26], + [39, 16, 22, 28, 26, 30, 23, 24], + [18, 14, 29, 27, 30, 38, 26, 26], + [41, 26, 28, 36, 18, 38, 16, 26]]) + b_eq = np.array([7872, 10466, 11322, 12058]) + c = np.array([2, 10, 13, 17, 7, 5, 7, 3]) + + mip_rel_gaps = [0.25, 0.01, 0.001] + sol_mip_gaps = [] + for mip_rel_gap in mip_rel_gaps: + res = milp(c=c, bounds=(0, np.inf), constraints=(A_eq, b_eq, b_eq), + integrality=True, options={"mip_rel_gap": mip_rel_gap}) + # assert that the solution actually has mip_gap lower than the + # required mip_rel_gap supplied + assert res.mip_gap <= mip_rel_gap + # check that `res.mip_gap` is as defined in the documentation + assert res.mip_gap == (res.fun - res.mip_dual_bound)/res.fun + sol_mip_gaps.append(res.mip_gap) + + # make sure that the mip_rel_gap parameter is actually doing something + # check that differences between solution gaps are declining + # monotonically with the mip_rel_gap parameter. + assert np.all(np.diff(sol_mip_gaps) < 0) + +@pytest.mark.xfail(reason='Upstream / Wrapper issue, see gh-20116') +def test_large_numbers_gh20116(): + h = 10 ** 12 + A = np.array([[100.4534, h], [100.4534, -h]]) + b = np.array([h, 0]) + constraints = LinearConstraint(A=A, ub=b) + bounds = Bounds([0, 0], [1, 1]) + c = np.array([0, 0]) + res = milp(c=c, constraints=constraints, bounds=bounds, integrality=1) + assert res.status == 0 + assert np.all(A @ res.x < b) + + +def test_presolve_gh18907(): + from scipy.optimize import milp + import numpy as np + inf = np.inf + + # set up problem + c = np.array([-0.85850509, -0.82892676, -0.80026454, -0.63015535, -0.5099006, + -0.50077193, -0.4894404, -0.47285865, -0.39867774, -0.38069646, + -0.36733012, -0.36733012, -0.35820411, -0.31576141, -0.20626091, + -0.12466144, -0.10679516, -0.1061887, -0.1061887, -0.1061887, + -0., -0., -0., -0., 0., 0., 0., 0.]) + + A = np.array([[1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., + 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 0., 0., 0., 0.], + [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., + 1., 0., 0., 0., 0., 0., 1., 0., 0., 0., -25., -0., -0., -0.], + [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., + -1., 0., 0., 0., 0., 0., -1., 0., 0., 0., 2., 0., 0., 0.], + [0., 0., 0., 0., 1., 1., 1., 1., 0., 1., 0., 0., 0., 0., 0., + 0., 0., 0., 0., 0., 0., 0., 0., 0., -0., -25., -0., -0.], + [0., 0., 0., 0., -1., -1., -1., -1., 0., -1., 0., 0., 0., + 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 2., 0., 0.], + [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., + 0., 0., 1., 1., 1., 0., 0., 0., 0., -0., -0., -25., -0.], + [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., + 0., 0., -1., -1., -1., 0., 0., 0., 0., 0., 0., 2., 0.], + [1., 1., 1., 1., 0., 0., 0., 0., 1., 0., 1., 1., 1., 1., 0., + 1., 1., 0., 0., 0., 0., 1., 1., 1., -0., -0., -0., -25.], + [-1., -1., -1., -1., 0., 0., 0., 0., -1., 0., -1., -1., -1., -1., + 0., -1., -1., 0., 0., 0., 0., -1., -1., -1., 0., 0., 0., 2.]]) + bl = np.array([-inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf]) + bu = np.array([100., 0., 0., 0., 0., 0., 0., 0., 0.]) + constraints = LinearConstraint(A, bl, bu) + integrality = 1 + bounds = (0, 1) + r1 = milp(c=c, constraints=constraints, integrality=integrality, bounds=bounds, + options={'presolve': True}) + r2 = milp(c=c, constraints=constraints, integrality=integrality, bounds=bounds, + options={'presolve': False}) + assert r1.status == r2.status + assert_allclose(r1.x, r2.x) + + # another example from the same issue + bounds = Bounds(lb=0, ub=1) + integrality = [1, 1, 0, 0] + c = [10, 9.52380952, -1000, -952.38095238] + A = [[1, 1, 0, 0], [0, 0, 1, 1], [200, 0, 0, 0], [0, 200, 0, 0], + [0, 0, 2000, 0], [0, 0, 0, 2000], [-1, 0, 1, 0], [-1, -1, 0, 1]] + ub = [1, 1, 200, 200, 1000, 1000, 0, 0] + constraints = LinearConstraint(A, ub=ub) + r1 = milp(c=c, constraints=constraints, bounds=bounds, + integrality=integrality, options={"presolve": False}) + r2 = milp(c=c, constraints=constraints, bounds=bounds, + integrality=integrality, options={"presolve": False}) + assert r1.status == r2.status + assert_allclose(r1.x, r2.x) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_minimize_constrained.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_minimize_constrained.py new file mode 100644 index 0000000000000000000000000000000000000000..cda21fd1dc2b24b128e47405e01353fdae41a75c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_minimize_constrained.py @@ -0,0 +1,845 @@ +import numpy as np +import pytest +from scipy.linalg import block_diag +from scipy.sparse import csc_matrix +from numpy.testing import (assert_array_almost_equal, + assert_array_less, assert_, + suppress_warnings) +from scipy.optimize import (NonlinearConstraint, + LinearConstraint, + Bounds, + minimize, + BFGS, + SR1, + rosen) + + +class Maratos: + """Problem 15.4 from Nocedal and Wright + + The following optimization problem: + minimize 2*(x[0]**2 + x[1]**2 - 1) - x[0] + Subject to: x[0]**2 + x[1]**2 - 1 = 0 + """ + + def __init__(self, degrees=60, constr_jac=None, constr_hess=None): + rads = degrees/180*np.pi + self.x0 = [np.cos(rads), np.sin(rads)] + self.x_opt = np.array([1.0, 0.0]) + self.constr_jac = constr_jac + self.constr_hess = constr_hess + self.bounds = None + + def fun(self, x): + return 2*(x[0]**2 + x[1]**2 - 1) - x[0] + + def grad(self, x): + return np.array([4*x[0]-1, 4*x[1]]) + + def hess(self, x): + return 4*np.eye(2) + + @property + def constr(self): + def fun(x): + return x[0]**2 + x[1]**2 + + if self.constr_jac is None: + def jac(x): + return [[2*x[0], 2*x[1]]] + else: + jac = self.constr_jac + + if self.constr_hess is None: + def hess(x, v): + return 2*v[0]*np.eye(2) + else: + hess = self.constr_hess + + return NonlinearConstraint(fun, 1, 1, jac, hess) + + +class MaratosTestArgs: + """Problem 15.4 from Nocedal and Wright + + The following optimization problem: + minimize 2*(x[0]**2 + x[1]**2 - 1) - x[0] + Subject to: x[0]**2 + x[1]**2 - 1 = 0 + """ + + def __init__(self, a, b, degrees=60, constr_jac=None, constr_hess=None): + rads = degrees/180*np.pi + self.x0 = [np.cos(rads), np.sin(rads)] + self.x_opt = np.array([1.0, 0.0]) + self.constr_jac = constr_jac + self.constr_hess = constr_hess + self.a = a + self.b = b + self.bounds = None + + def _test_args(self, a, b): + if self.a != a or self.b != b: + raise ValueError() + + def fun(self, x, a, b): + self._test_args(a, b) + return 2*(x[0]**2 + x[1]**2 - 1) - x[0] + + def grad(self, x, a, b): + self._test_args(a, b) + return np.array([4*x[0]-1, 4*x[1]]) + + def hess(self, x, a, b): + self._test_args(a, b) + return 4*np.eye(2) + + @property + def constr(self): + def fun(x): + return x[0]**2 + x[1]**2 + + if self.constr_jac is None: + def jac(x): + return [[4*x[0], 4*x[1]]] + else: + jac = self.constr_jac + + if self.constr_hess is None: + def hess(x, v): + return 2*v[0]*np.eye(2) + else: + hess = self.constr_hess + + return NonlinearConstraint(fun, 1, 1, jac, hess) + + +class MaratosGradInFunc: + """Problem 15.4 from Nocedal and Wright + + The following optimization problem: + minimize 2*(x[0]**2 + x[1]**2 - 1) - x[0] + Subject to: x[0]**2 + x[1]**2 - 1 = 0 + """ + + def __init__(self, degrees=60, constr_jac=None, constr_hess=None): + rads = degrees/180*np.pi + self.x0 = [np.cos(rads), np.sin(rads)] + self.x_opt = np.array([1.0, 0.0]) + self.constr_jac = constr_jac + self.constr_hess = constr_hess + self.bounds = None + + def fun(self, x): + return (2*(x[0]**2 + x[1]**2 - 1) - x[0], + np.array([4*x[0]-1, 4*x[1]])) + + @property + def grad(self): + return True + + def hess(self, x): + return 4*np.eye(2) + + @property + def constr(self): + def fun(x): + return x[0]**2 + x[1]**2 + + if self.constr_jac is None: + def jac(x): + return [[4*x[0], 4*x[1]]] + else: + jac = self.constr_jac + + if self.constr_hess is None: + def hess(x, v): + return 2*v[0]*np.eye(2) + else: + hess = self.constr_hess + + return NonlinearConstraint(fun, 1, 1, jac, hess) + + +class HyperbolicIneq: + """Problem 15.1 from Nocedal and Wright + + The following optimization problem: + minimize 1/2*(x[0] - 2)**2 + 1/2*(x[1] - 1/2)**2 + Subject to: 1/(x[0] + 1) - x[1] >= 1/4 + x[0] >= 0 + x[1] >= 0 + """ + def __init__(self, constr_jac=None, constr_hess=None): + self.x0 = [0, 0] + self.x_opt = [1.952823, 0.088659] + self.constr_jac = constr_jac + self.constr_hess = constr_hess + self.bounds = Bounds(0, np.inf) + + def fun(self, x): + return 1/2*(x[0] - 2)**2 + 1/2*(x[1] - 1/2)**2 + + def grad(self, x): + return [x[0] - 2, x[1] - 1/2] + + def hess(self, x): + return np.eye(2) + + @property + def constr(self): + def fun(x): + return 1/(x[0] + 1) - x[1] + + if self.constr_jac is None: + def jac(x): + return [[-1/(x[0] + 1)**2, -1]] + else: + jac = self.constr_jac + + if self.constr_hess is None: + def hess(x, v): + return 2*v[0]*np.array([[1/(x[0] + 1)**3, 0], + [0, 0]]) + else: + hess = self.constr_hess + + return NonlinearConstraint(fun, 0.25, np.inf, jac, hess) + + +class Rosenbrock: + """Rosenbrock function. + + The following optimization problem: + minimize sum(100.0*(x[1:] - x[:-1]**2.0)**2.0 + (1 - x[:-1])**2.0) + """ + + def __init__(self, n=2, random_state=0): + rng = np.random.RandomState(random_state) + self.x0 = rng.uniform(-1, 1, n) + self.x_opt = np.ones(n) + self.bounds = None + + def fun(self, x): + x = np.asarray(x) + r = np.sum(100.0 * (x[1:] - x[:-1]**2.0)**2.0 + (1 - x[:-1])**2.0, + axis=0) + return r + + def grad(self, x): + x = np.asarray(x) + xm = x[1:-1] + xm_m1 = x[:-2] + xm_p1 = x[2:] + der = np.zeros_like(x) + der[1:-1] = (200 * (xm - xm_m1**2) - + 400 * (xm_p1 - xm**2) * xm - 2 * (1 - xm)) + der[0] = -400 * x[0] * (x[1] - x[0]**2) - 2 * (1 - x[0]) + der[-1] = 200 * (x[-1] - x[-2]**2) + return der + + def hess(self, x): + x = np.atleast_1d(x) + H = np.diag(-400 * x[:-1], 1) - np.diag(400 * x[:-1], -1) + diagonal = np.zeros(len(x), dtype=x.dtype) + diagonal[0] = 1200 * x[0]**2 - 400 * x[1] + 2 + diagonal[-1] = 200 + diagonal[1:-1] = 202 + 1200 * x[1:-1]**2 - 400 * x[2:] + H = H + np.diag(diagonal) + return H + + @property + def constr(self): + return () + + +class IneqRosenbrock(Rosenbrock): + """Rosenbrock subject to inequality constraints. + + The following optimization problem: + minimize sum(100.0*(x[1] - x[0]**2)**2.0 + (1 - x[0])**2) + subject to: x[0] + 2 x[1] <= 1 + + Taken from matlab ``fmincon`` documentation. + """ + def __init__(self, random_state=0): + Rosenbrock.__init__(self, 2, random_state) + self.x0 = [-1, -0.5] + self.x_opt = [0.5022, 0.2489] + self.bounds = None + + @property + def constr(self): + A = [[1, 2]] + b = 1 + return LinearConstraint(A, -np.inf, b) + + +class BoundedRosenbrock(Rosenbrock): + """Rosenbrock subject to inequality constraints. + + The following optimization problem: + minimize sum(100.0*(x[1] - x[0]**2)**2.0 + (1 - x[0])**2) + subject to: -2 <= x[0] <= 0 + 0 <= x[1] <= 2 + + Taken from matlab ``fmincon`` documentation. + """ + def __init__(self, random_state=0): + Rosenbrock.__init__(self, 2, random_state) + self.x0 = [-0.2, 0.2] + self.x_opt = None + self.bounds = Bounds([-2, 0], [0, 2]) + + +class EqIneqRosenbrock(Rosenbrock): + """Rosenbrock subject to equality and inequality constraints. + + The following optimization problem: + minimize sum(100.0*(x[1] - x[0]**2)**2.0 + (1 - x[0])**2) + subject to: x[0] + 2 x[1] <= 1 + 2 x[0] + x[1] = 1 + + Taken from matlab ``fimincon`` documentation. + """ + def __init__(self, random_state=0): + Rosenbrock.__init__(self, 2, random_state) + self.x0 = [-1, -0.5] + self.x_opt = [0.41494, 0.17011] + self.bounds = None + + @property + def constr(self): + A_ineq = [[1, 2]] + b_ineq = 1 + A_eq = [[2, 1]] + b_eq = 1 + return (LinearConstraint(A_ineq, -np.inf, b_ineq), + LinearConstraint(A_eq, b_eq, b_eq)) + + +class Elec: + """Distribution of electrons on a sphere. + + Problem no 2 from COPS collection [2]_. Find + the equilibrium state distribution (of minimal + potential) of the electrons positioned on a + conducting sphere. + + References + ---------- + .. [1] E. D. Dolan, J. J. Mor\'{e}, and T. S. Munson, + "Benchmarking optimization software with COPS 3.0.", + Argonne National Lab., Argonne, IL (US), 2004. + """ + def __init__(self, n_electrons=200, random_state=0, + constr_jac=None, constr_hess=None): + self.n_electrons = n_electrons + self.rng = np.random.RandomState(random_state) + # Initial Guess + phi = self.rng.uniform(0, 2 * np.pi, self.n_electrons) + theta = self.rng.uniform(-np.pi, np.pi, self.n_electrons) + x = np.cos(theta) * np.cos(phi) + y = np.cos(theta) * np.sin(phi) + z = np.sin(theta) + self.x0 = np.hstack((x, y, z)) + self.x_opt = None + self.constr_jac = constr_jac + self.constr_hess = constr_hess + self.bounds = None + + def _get_cordinates(self, x): + x_coord = x[:self.n_electrons] + y_coord = x[self.n_electrons:2 * self.n_electrons] + z_coord = x[2 * self.n_electrons:] + return x_coord, y_coord, z_coord + + def _compute_coordinate_deltas(self, x): + x_coord, y_coord, z_coord = self._get_cordinates(x) + dx = x_coord[:, None] - x_coord + dy = y_coord[:, None] - y_coord + dz = z_coord[:, None] - z_coord + return dx, dy, dz + + def fun(self, x): + dx, dy, dz = self._compute_coordinate_deltas(x) + with np.errstate(divide='ignore'): + dm1 = (dx**2 + dy**2 + dz**2) ** -0.5 + dm1[np.diag_indices_from(dm1)] = 0 + return 0.5 * np.sum(dm1) + + def grad(self, x): + dx, dy, dz = self._compute_coordinate_deltas(x) + + with np.errstate(divide='ignore'): + dm3 = (dx**2 + dy**2 + dz**2) ** -1.5 + dm3[np.diag_indices_from(dm3)] = 0 + + grad_x = -np.sum(dx * dm3, axis=1) + grad_y = -np.sum(dy * dm3, axis=1) + grad_z = -np.sum(dz * dm3, axis=1) + + return np.hstack((grad_x, grad_y, grad_z)) + + def hess(self, x): + dx, dy, dz = self._compute_coordinate_deltas(x) + d = (dx**2 + dy**2 + dz**2) ** 0.5 + + with np.errstate(divide='ignore'): + dm3 = d ** -3 + dm5 = d ** -5 + + i = np.arange(self.n_electrons) + dm3[i, i] = 0 + dm5[i, i] = 0 + + Hxx = dm3 - 3 * dx**2 * dm5 + Hxx[i, i] = -np.sum(Hxx, axis=1) + + Hxy = -3 * dx * dy * dm5 + Hxy[i, i] = -np.sum(Hxy, axis=1) + + Hxz = -3 * dx * dz * dm5 + Hxz[i, i] = -np.sum(Hxz, axis=1) + + Hyy = dm3 - 3 * dy**2 * dm5 + Hyy[i, i] = -np.sum(Hyy, axis=1) + + Hyz = -3 * dy * dz * dm5 + Hyz[i, i] = -np.sum(Hyz, axis=1) + + Hzz = dm3 - 3 * dz**2 * dm5 + Hzz[i, i] = -np.sum(Hzz, axis=1) + + H = np.vstack(( + np.hstack((Hxx, Hxy, Hxz)), + np.hstack((Hxy, Hyy, Hyz)), + np.hstack((Hxz, Hyz, Hzz)) + )) + + return H + + @property + def constr(self): + def fun(x): + x_coord, y_coord, z_coord = self._get_cordinates(x) + return x_coord**2 + y_coord**2 + z_coord**2 - 1 + + if self.constr_jac is None: + def jac(x): + x_coord, y_coord, z_coord = self._get_cordinates(x) + Jx = 2 * np.diag(x_coord) + Jy = 2 * np.diag(y_coord) + Jz = 2 * np.diag(z_coord) + return csc_matrix(np.hstack((Jx, Jy, Jz))) + else: + jac = self.constr_jac + + if self.constr_hess is None: + def hess(x, v): + D = 2 * np.diag(v) + return block_diag(D, D, D) + else: + hess = self.constr_hess + + return NonlinearConstraint(fun, -np.inf, 0, jac, hess) + + +class TestTrustRegionConstr: + list_of_problems = [Maratos(), + Maratos(constr_hess='2-point'), + Maratos(constr_hess=SR1()), + Maratos(constr_jac='2-point', constr_hess=SR1()), + MaratosGradInFunc(), + HyperbolicIneq(), + HyperbolicIneq(constr_hess='3-point'), + HyperbolicIneq(constr_hess=BFGS()), + HyperbolicIneq(constr_jac='3-point', + constr_hess=BFGS()), + Rosenbrock(), + IneqRosenbrock(), + EqIneqRosenbrock(), + BoundedRosenbrock(), + Elec(n_electrons=2), + Elec(n_electrons=2, constr_hess='2-point'), + Elec(n_electrons=2, constr_hess=SR1()), + Elec(n_electrons=2, constr_jac='3-point', + constr_hess=SR1())] + + @pytest.mark.thread_unsafe + @pytest.mark.parametrize('prob', list_of_problems) + @pytest.mark.parametrize('grad', ('prob.grad', '3-point', False)) + @pytest.mark.parametrize('hess', ("prob.hess", '3-point', SR1(), + BFGS(exception_strategy='damp_update'), + BFGS(exception_strategy='skip_update'))) + def test_list_of_problems(self, prob, grad, hess): + grad = prob.grad if grad == "prob.grad" else grad + hess = prob.hess if hess == "prob.hess" else hess + # Remove exceptions + if (grad in {'2-point', '3-point', 'cs', False} and + hess in {'2-point', '3-point', 'cs'}): + pytest.skip("Numerical Hessian needs analytical gradient") + if prob.grad is True and grad in {'3-point', False}: + pytest.skip("prob.grad incompatible with grad in {'3-point', False}") + sensitive = (isinstance(prob, BoundedRosenbrock) and grad == '3-point' + and isinstance(hess, BFGS)) + if sensitive: + pytest.xfail("Seems sensitive to initial conditions w/ Accelerate") + with suppress_warnings() as sup: + sup.filter(UserWarning, "delta_grad == 0.0") + result = minimize(prob.fun, prob.x0, + method='trust-constr', + jac=grad, hess=hess, + bounds=prob.bounds, + constraints=prob.constr) + + if prob.x_opt is not None: + assert_array_almost_equal(result.x, prob.x_opt, + decimal=5) + # gtol + if result.status == 1: + assert_array_less(result.optimality, 1e-8) + # xtol + if result.status == 2: + assert_array_less(result.tr_radius, 1e-8) + + if result.method == "tr_interior_point": + assert_array_less(result.barrier_parameter, 1e-8) + + # check for max iter + message = f"Invalid termination condition: {result.status}." + assert result.status not in {0, 3}, message + + + def test_default_jac_and_hess(self): + def fun(x): + return (x - 1) ** 2 + bounds = [(-2, 2)] + res = minimize(fun, x0=[-1.5], bounds=bounds, method='trust-constr') + assert_array_almost_equal(res.x, 1, decimal=5) + + def test_default_hess(self): + def fun(x): + return (x - 1) ** 2 + bounds = [(-2, 2)] + res = minimize(fun, x0=[-1.5], bounds=bounds, method='trust-constr', + jac='2-point') + assert_array_almost_equal(res.x, 1, decimal=5) + + def test_no_constraints(self): + prob = Rosenbrock() + result = minimize(prob.fun, prob.x0, + method='trust-constr', + jac=prob.grad, hess=prob.hess) + result1 = minimize(prob.fun, prob.x0, + method='L-BFGS-B', + jac='2-point') + + result2 = minimize(prob.fun, prob.x0, + method='L-BFGS-B', + jac='3-point') + assert_array_almost_equal(result.x, prob.x_opt, decimal=5) + assert_array_almost_equal(result1.x, prob.x_opt, decimal=5) + assert_array_almost_equal(result2.x, prob.x_opt, decimal=5) + + def test_hessp(self): + prob = Maratos() + + def hessp(x, p): + H = prob.hess(x) + return H.dot(p) + + result = minimize(prob.fun, prob.x0, + method='trust-constr', + jac=prob.grad, hessp=hessp, + bounds=prob.bounds, + constraints=prob.constr) + + if prob.x_opt is not None: + assert_array_almost_equal(result.x, prob.x_opt, decimal=2) + + # gtol + if result.status == 1: + assert_array_less(result.optimality, 1e-8) + # xtol + if result.status == 2: + assert_array_less(result.tr_radius, 1e-8) + + if result.method == "tr_interior_point": + assert_array_less(result.barrier_parameter, 1e-8) + # max iter + if result.status in (0, 3): + raise RuntimeError("Invalid termination condition.") + + def test_args(self): + prob = MaratosTestArgs("a", 234) + + result = minimize(prob.fun, prob.x0, ("a", 234), + method='trust-constr', + jac=prob.grad, hess=prob.hess, + bounds=prob.bounds, + constraints=prob.constr) + + if prob.x_opt is not None: + assert_array_almost_equal(result.x, prob.x_opt, decimal=2) + + # gtol + if result.status == 1: + assert_array_less(result.optimality, 1e-8) + # xtol + if result.status == 2: + assert_array_less(result.tr_radius, 1e-8) + if result.method == "tr_interior_point": + assert_array_less(result.barrier_parameter, 1e-8) + # max iter + if result.status in (0, 3): + raise RuntimeError("Invalid termination condition.") + + def test_raise_exception(self): + prob = Maratos() + message = "Whenever the gradient is estimated via finite-differences" + with pytest.raises(ValueError, match=message): + minimize(prob.fun, prob.x0, method='trust-constr', jac='2-point', + hess='2-point', constraints=prob.constr) + + def test_issue_9044(self): + # https://github.com/scipy/scipy/issues/9044 + # Test the returned `OptimizeResult` contains keys consistent with + # other solvers. + + def callback(x, info): + assert_('nit' in info) + assert_('niter' in info) + + result = minimize(lambda x: x**2, [0], jac=lambda x: 2*x, + hess=lambda x: 2, callback=callback, + method='trust-constr') + assert_(result.get('success')) + assert_(result.get('nit', -1) == 1) + + # Also check existence of the 'niter' attribute, for backward + # compatibility + assert_(result.get('niter', -1) == 1) + + def test_issue_15093(self): + # scipy docs define bounds as inclusive, so it shouldn't be + # an issue to set x0 on the bounds even if keep_feasible is + # True. Previously, trust-constr would treat bounds as + # exclusive. + + x0 = np.array([0., 0.5]) + + def obj(x): + x1 = x[0] + x2 = x[1] + return x1 ** 2 + x2 ** 2 + + bounds = Bounds(np.array([0., 0.]), np.array([1., 1.]), + keep_feasible=True) + + with suppress_warnings() as sup: + sup.filter(UserWarning, "delta_grad == 0.0") + result = minimize( + method='trust-constr', + fun=obj, + x0=x0, + bounds=bounds) + + assert result['success'] + +class TestEmptyConstraint: + """ + Here we minimize x^2+y^2 subject to x^2-y^2>1. + The actual minimum is at (0, 0) which fails the constraint. + Therefore we will find a minimum on the boundary at (+/-1, 0). + + When minimizing on the boundary, optimize uses a set of + constraints that removes the constraint that sets that + boundary. In our case, there's only one constraint, so + the result is an empty constraint. + + This tests that the empty constraint works. + """ + def test_empty_constraint(self): + + def function(x): + return x[0]**2 + x[1]**2 + + def functionjacobian(x): + return np.array([2.*x[0], 2.*x[1]]) + + def functionhvp(x, v): + return 2.*v + + def constraint(x): + return np.array([x[0]**2 - x[1]**2]) + + def constraintjacobian(x): + return np.array([[2*x[0], -2*x[1]]]) + + def constraintlcoh(x, v): + return np.array([[2., 0.], [0., -2.]]) * v[0] + + constraint = NonlinearConstraint(constraint, 1., np.inf, + constraintjacobian, constraintlcoh) + + startpoint = [1., 2.] + + bounds = Bounds([-np.inf, -np.inf], [np.inf, np.inf]) + + result = minimize( + function, + startpoint, + method='trust-constr', + jac=functionjacobian, + hessp=functionhvp, + constraints=[constraint], + bounds=bounds, + ) + + assert_array_almost_equal(abs(result.x), np.array([1, 0]), decimal=4) + + +def test_bug_11886(): + def opt(x): + return x[0]**2+x[1]**2 + + with np.testing.suppress_warnings() as sup: + sup.filter(PendingDeprecationWarning) + A = np.matrix(np.diag([1, 1])) + lin_cons = LinearConstraint(A, -1, np.inf) + # just checking that there are no errors + minimize(opt, 2*[1], constraints = lin_cons) + + +def test_gh11649(): + # trust - constr error when attempting to keep bound constrained solutions + # feasible. Algorithm attempts to go outside bounds when evaluating finite + # differences. (don't give objective an analytic gradient) + bnds = Bounds(lb=[-1, -1], ub=[1, 1], keep_feasible=True) + + def assert_inbounds(x): + assert np.all(x >= bnds.lb) + assert np.all(x <= bnds.ub) + + def obj(x): + assert_inbounds(x) + return np.exp(x[0])*(4*x[0]**2 + 2*x[1]**2 + 4*x[0]*x[1] + 2*x[1] + 1) + + def nce(x): + assert_inbounds(x) + return x[0]**2 + x[1] + + def nce_jac(x): + return np.array([2*x[0], 1]) + + def nci(x): + assert_inbounds(x) + return x[0]*x[1] + + x0 = np.array((0.99, -0.99)) + nlcs = [NonlinearConstraint(nci, -10, np.inf), + NonlinearConstraint(nce, 1, 1, jac=nce_jac)] + + res = minimize(fun=obj, x0=x0, method='trust-constr', + bounds=bnds, constraints=nlcs) + assert_inbounds(res.x) + assert nlcs[0].lb < nlcs[0].fun(res.x) < nlcs[0].ub + + +def test_gh20665_too_many_constraints(): + # gh-20665 reports a confusing error message when there are more equality + # constraints than variables. Check that the error message is improved. + message = "...more equality constraints than independent variables..." + with pytest.raises(ValueError, match=message): + x0 = np.ones((2,)) + A_eq, b_eq = np.arange(6).reshape((3, 2)), np.ones((3,)) + g = NonlinearConstraint(lambda x: A_eq @ x, lb=b_eq, ub=b_eq) + minimize(rosen, x0, method='trust-constr', constraints=[g]) + # no error with `SVDFactorization` + with np.testing.suppress_warnings() as sup: + sup.filter(UserWarning) + minimize(rosen, x0, method='trust-constr', constraints=[g], + options={'factorization_method': 'SVDFactorization'}) + +def test_issue_18882(): + def lsf(u): + u1, u2 = u + a, b = [3.0, 4.0] + return 1.0 + u1**2 / a**2 - u2**2 / b**2 + + def of(u): + return np.sum(u**2) + + with suppress_warnings() as sup: + sup.filter(UserWarning, "delta_grad == 0.0") + sup.filter(UserWarning, "Singular Jacobian matrix.") + res = minimize( + of, + [0.0, 0.0], + method="trust-constr", + constraints=NonlinearConstraint(lsf, 0, 0), + ) + assert (not res.success) and (res.constr_violation > 1e-8) + +class TestBoundedNelderMead: + + @pytest.mark.parametrize('bounds, x_opt', + [(Bounds(-np.inf, np.inf), Rosenbrock().x_opt), + (Bounds(-np.inf, -0.8), [-0.8, -0.8]), + (Bounds(3.0, np.inf), [3.0, 9.0]), + (Bounds([3.0, 1.0], [4.0, 5.0]), [3., 5.]), + ]) + def test_rosen_brock_with_bounds(self, bounds, x_opt): + prob = Rosenbrock() + with suppress_warnings() as sup: + sup.filter(UserWarning, "Initial guess is not within " + "the specified bounds") + result = minimize(prob.fun, [-10, -10], + method='Nelder-Mead', + bounds=bounds) + assert np.less_equal(bounds.lb, result.x).all() + assert np.less_equal(result.x, bounds.ub).all() + assert np.allclose(prob.fun(result.x), result.fun) + assert np.allclose(result.x, x_opt, atol=1.e-3) + + def test_equal_all_bounds(self): + prob = Rosenbrock() + bounds = Bounds([4.0, 5.0], [4.0, 5.0]) + with suppress_warnings() as sup: + sup.filter(UserWarning, "Initial guess is not within " + "the specified bounds") + result = minimize(prob.fun, [-10, 8], + method='Nelder-Mead', + bounds=bounds) + assert np.allclose(result.x, [4.0, 5.0]) + + def test_equal_one_bounds(self): + prob = Rosenbrock() + bounds = Bounds([4.0, 5.0], [4.0, 20.0]) + with suppress_warnings() as sup: + sup.filter(UserWarning, "Initial guess is not within " + "the specified bounds") + result = minimize(prob.fun, [-10, 8], + method='Nelder-Mead', + bounds=bounds) + assert np.allclose(result.x, [4.0, 16.0]) + + def test_invalid_bounds(self): + prob = Rosenbrock() + message = 'An upper bound is less than the corresponding lower bound.' + with pytest.raises(ValueError, match=message): + bounds = Bounds([-np.inf, 1.0], [4.0, -5.0]) + minimize(prob.fun, [-10, 3], + method='Nelder-Mead', + bounds=bounds) + + @pytest.mark.xfail(reason="Failing on Azure Linux and macOS builds, " + "see gh-13846") + def test_outside_bounds_warning(self): + prob = Rosenbrock() + message = "Initial guess is not within the specified bounds" + with pytest.warns(UserWarning, match=message): + bounds = Bounds([-np.inf, 1.0], [4.0, 5.0]) + minimize(prob.fun, [-10, 8], + method='Nelder-Mead', + bounds=bounds) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_minpack.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_minpack.py new file mode 100644 index 0000000000000000000000000000000000000000..ef107c5692c2d30a06b6943542696b95bc21e818 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_minpack.py @@ -0,0 +1,1194 @@ +""" +Unit tests for optimization routines from minpack.py. +""" +import warnings +import pytest +import threading + +from numpy.testing import (assert_, assert_almost_equal, assert_array_equal, + assert_array_almost_equal, assert_allclose, + assert_warns, suppress_warnings) +from pytest import raises as assert_raises +import numpy as np +from numpy import array, float64 +from multiprocessing.pool import ThreadPool + +from scipy import optimize, linalg +from scipy.special import lambertw +from scipy.optimize._minpack_py import leastsq, curve_fit, fixed_point +from scipy.optimize import OptimizeWarning +from scipy.optimize._minimize import Bounds + + +class ReturnShape: + """This class exists to create a callable that does not have a '__name__' attribute. + + __init__ takes the argument 'shape', which should be a tuple of ints. + When an instance is called with a single argument 'x', it returns numpy.ones(shape). + """ + + def __init__(self, shape): + self.shape = shape + + def __call__(self, x): + return np.ones(self.shape) + + +def dummy_func(x, shape): + """A function that returns an array of ones of the given shape. + `x` is ignored. + """ + return np.ones(shape) + + +def sequence_parallel(fs): + with ThreadPool(len(fs)) as pool: + return pool.map(lambda f: f(), fs) + + +# Function and Jacobian for tests of solvers for systems of nonlinear +# equations + + +def pressure_network(flow_rates, Qtot, k): + """Evaluate non-linear equation system representing + the pressures and flows in a system of n parallel pipes:: + + f_i = P_i - P_0, for i = 1..n + f_0 = sum(Q_i) - Qtot + + where Q_i is the flow rate in pipe i and P_i the pressure in that pipe. + Pressure is modeled as a P=kQ**2 where k is a valve coefficient and + Q is the flow rate. + + Parameters + ---------- + flow_rates : float + A 1-D array of n flow rates [kg/s]. + k : float + A 1-D array of n valve coefficients [1/kg m]. + Qtot : float + A scalar, the total input flow rate [kg/s]. + + Returns + ------- + F : float + A 1-D array, F[i] == f_i. + + """ + P = k * flow_rates**2 + F = np.hstack((P[1:] - P[0], flow_rates.sum() - Qtot)) + return F + + +def pressure_network_jacobian(flow_rates, Qtot, k): + """Return the jacobian of the equation system F(flow_rates) + computed by `pressure_network` with respect to + *flow_rates*. See `pressure_network` for the detailed + description of parameters. + + Returns + ------- + jac : float + *n* by *n* matrix ``df_i/dQ_i`` where ``n = len(flow_rates)`` + and *f_i* and *Q_i* are described in the doc for `pressure_network` + """ + n = len(flow_rates) + pdiff = np.diag(flow_rates[1:] * 2 * k[1:] - 2 * flow_rates[0] * k[0]) + + jac = np.empty((n, n)) + jac[:n-1, :n-1] = pdiff * 0 + jac[:n-1, n-1] = 0 + jac[n-1, :] = np.ones(n) + + return jac + + +def pressure_network_fun_and_grad(flow_rates, Qtot, k): + return (pressure_network(flow_rates, Qtot, k), + pressure_network_jacobian(flow_rates, Qtot, k)) + + +class TestFSolve: + def test_pressure_network_no_gradient(self): + # fsolve without gradient, equal pipes -> equal flows. + k = np.full(4, 0.5) + Qtot = 4 + initial_guess = array([2., 0., 2., 0.]) + final_flows, info, ier, mesg = optimize.fsolve( + pressure_network, initial_guess, args=(Qtot, k), + full_output=True) + assert_array_almost_equal(final_flows, np.ones(4)) + assert_(ier == 1, mesg) + + def test_pressure_network_with_gradient(self): + # fsolve with gradient, equal pipes -> equal flows + k = np.full(4, 0.5) + Qtot = 4 + initial_guess = array([2., 0., 2., 0.]) + final_flows = optimize.fsolve( + pressure_network, initial_guess, args=(Qtot, k), + fprime=pressure_network_jacobian) + assert_array_almost_equal(final_flows, np.ones(4)) + + def test_wrong_shape_func_callable(self): + func = ReturnShape(1) + # x0 is a list of two elements, but func will return an array with + # length 1, so this should result in a TypeError. + x0 = [1.5, 2.0] + assert_raises(TypeError, optimize.fsolve, func, x0) + + def test_wrong_shape_func_function(self): + # x0 is a list of two elements, but func will return an array with + # length 1, so this should result in a TypeError. + x0 = [1.5, 2.0] + assert_raises(TypeError, optimize.fsolve, dummy_func, x0, args=((1,),)) + + def test_wrong_shape_fprime_callable(self): + func = ReturnShape(1) + deriv_func = ReturnShape((2,2)) + assert_raises(TypeError, optimize.fsolve, func, x0=[0,1], fprime=deriv_func) + + def test_wrong_shape_fprime_function(self): + def func(x): + return dummy_func(x, (2,)) + def deriv_func(x): + return dummy_func(x, (3, 3)) + assert_raises(TypeError, optimize.fsolve, func, x0=[0,1], fprime=deriv_func) + + def test_func_can_raise(self): + def func(*args): + raise ValueError('I raised') + + with assert_raises(ValueError, match='I raised'): + optimize.fsolve(func, x0=[0]) + + def test_Dfun_can_raise(self): + def func(x): + return x - np.array([10]) + + def deriv_func(*args): + raise ValueError('I raised') + + with assert_raises(ValueError, match='I raised'): + optimize.fsolve(func, x0=[0], fprime=deriv_func) + + def test_float32(self): + def func(x): + return np.array([x[0] - 100, x[1] - 1000], dtype=np.float32) ** 2 + p = optimize.fsolve(func, np.array([1, 1], np.float32)) + assert_allclose(func(p), [0, 0], atol=1e-3) + + def test_reentrant_func(self): + def func(*args): + self.test_pressure_network_no_gradient() + return pressure_network(*args) + + # fsolve without gradient, equal pipes -> equal flows. + k = np.full(4, 0.5) + Qtot = 4 + initial_guess = array([2., 0., 2., 0.]) + final_flows, info, ier, mesg = optimize.fsolve( + func, initial_guess, args=(Qtot, k), + full_output=True) + assert_array_almost_equal(final_flows, np.ones(4)) + assert_(ier == 1, mesg) + + def test_reentrant_Dfunc(self): + def deriv_func(*args): + self.test_pressure_network_with_gradient() + return pressure_network_jacobian(*args) + + # fsolve with gradient, equal pipes -> equal flows + k = np.full(4, 0.5) + Qtot = 4 + initial_guess = array([2., 0., 2., 0.]) + final_flows = optimize.fsolve( + pressure_network, initial_guess, args=(Qtot, k), + fprime=deriv_func) + assert_array_almost_equal(final_flows, np.ones(4)) + + def test_concurrent_no_gradient(self): + v = sequence_parallel([self.test_pressure_network_no_gradient] * 10) + assert all([result is None for result in v]) + + def test_concurrent_with_gradient(self): + v = sequence_parallel([self.test_pressure_network_with_gradient] * 10) + assert all([result is None for result in v]) + + +class TestRootHybr: + def test_pressure_network_no_gradient(self): + # root/hybr without gradient, equal pipes -> equal flows + k = np.full(4, 0.5) + Qtot = 4 + initial_guess = array([2., 0., 2., 0.]) + final_flows = optimize.root(pressure_network, initial_guess, + method='hybr', args=(Qtot, k)).x + assert_array_almost_equal(final_flows, np.ones(4)) + + def test_pressure_network_with_gradient(self): + # root/hybr with gradient, equal pipes -> equal flows + k = np.full(4, 0.5) + Qtot = 4 + initial_guess = array([[2., 0., 2., 0.]]) + final_flows = optimize.root(pressure_network, initial_guess, + args=(Qtot, k), method='hybr', + jac=pressure_network_jacobian).x + assert_array_almost_equal(final_flows, np.ones(4)) + + def test_pressure_network_with_gradient_combined(self): + # root/hybr with gradient and function combined, equal pipes -> equal + # flows + k = np.full(4, 0.5) + Qtot = 4 + initial_guess = array([2., 0., 2., 0.]) + final_flows = optimize.root(pressure_network_fun_and_grad, + initial_guess, args=(Qtot, k), + method='hybr', jac=True).x + assert_array_almost_equal(final_flows, np.ones(4)) + + +class TestRootLM: + def test_pressure_network_no_gradient(self): + # root/lm without gradient, equal pipes -> equal flows + k = np.full(4, 0.5) + Qtot = 4 + initial_guess = array([2., 0., 2., 0.]) + final_flows = optimize.root(pressure_network, initial_guess, + method='lm', args=(Qtot, k)).x + assert_array_almost_equal(final_flows, np.ones(4)) + + +class TestNfev: + def setup_method(self): + self.nfev = threading.local() + + def zero_f(self, y): + if not hasattr(self.nfev, 'c'): + self.nfev.c = 0 + self.nfev.c += 1 + return y**2-3 + + @pytest.mark.parametrize('method', ['hybr', 'lm', 'broyden1', + 'broyden2', 'anderson', + 'linearmixing', 'diagbroyden', + 'excitingmixing', 'krylov', + 'df-sane']) + def test_root_nfev(self, method): + self.nfev.c = 0 + solution = optimize.root(self.zero_f, 100, method=method) + assert solution.nfev == self.nfev.c + + def test_fsolve_nfev(self): + self.nfev.c = 0 + x, info, ier, mesg = optimize.fsolve(self.zero_f, 100, full_output=True) + assert info['nfev'] == self.nfev.c + + +class TestLeastSq: + def setup_method(self): + x = np.linspace(0, 10, 40) + a,b,c = 3.1, 42, -304.2 + self.x = x + self.abc = a,b,c + y_true = a*x**2 + b*x + c + np.random.seed(0) + self.y_meas = y_true + 0.01*np.random.standard_normal(y_true.shape) + + def residuals(self, p, y, x): + a,b,c = p + err = y-(a*x**2 + b*x + c) + return err + + def residuals_jacobian(self, _p, _y, x): + return -np.vstack([x**2, x, np.ones_like(x)]).T + + def test_basic(self): + p0 = array([0,0,0]) + params_fit, ier = leastsq(self.residuals, p0, + args=(self.y_meas, self.x)) + assert_(ier in (1,2,3,4), 'solution not found (ier=%d)' % ier) + # low precision due to random + assert_array_almost_equal(params_fit, self.abc, decimal=2) + + def test_basic_with_gradient(self): + p0 = array([0,0,0]) + params_fit, ier = leastsq(self.residuals, p0, + args=(self.y_meas, self.x), + Dfun=self.residuals_jacobian) + assert_(ier in (1,2,3,4), 'solution not found (ier=%d)' % ier) + # low precision due to random + assert_array_almost_equal(params_fit, self.abc, decimal=2) + + def test_full_output(self): + p0 = array([[0,0,0]]) + full_output = leastsq(self.residuals, p0, + args=(self.y_meas, self.x), + full_output=True) + params_fit, cov_x, infodict, mesg, ier = full_output + assert_(ier in (1,2,3,4), f'solution not found: {mesg}') + + def test_input_untouched(self): + p0 = array([0,0,0],dtype=float64) + p0_copy = array(p0, copy=True) + full_output = leastsq(self.residuals, p0, + args=(self.y_meas, self.x), + full_output=True) + params_fit, cov_x, infodict, mesg, ier = full_output + assert_(ier in (1,2,3,4), f'solution not found: {mesg}') + assert_array_equal(p0, p0_copy) + + def test_wrong_shape_func_callable(self): + func = ReturnShape(1) + # x0 is a list of two elements, but func will return an array with + # length 1, so this should result in a TypeError. + x0 = [1.5, 2.0] + assert_raises(TypeError, optimize.leastsq, func, x0) + + def test_wrong_shape_func_function(self): + # x0 is a list of two elements, but func will return an array with + # length 1, so this should result in a TypeError. + x0 = [1.5, 2.0] + assert_raises(TypeError, optimize.leastsq, dummy_func, x0, args=((1,),)) + + def test_wrong_shape_Dfun_callable(self): + func = ReturnShape(1) + deriv_func = ReturnShape((2,2)) + assert_raises(TypeError, optimize.leastsq, func, x0=[0,1], Dfun=deriv_func) + + def test_wrong_shape_Dfun_function(self): + def func(x): + return dummy_func(x, (2,)) + def deriv_func(x): + return dummy_func(x, (3, 3)) + assert_raises(TypeError, optimize.leastsq, func, x0=[0,1], Dfun=deriv_func) + + def test_float32(self): + # Regression test for gh-1447 + def func(p,x,y): + q = p[0]*np.exp(-(x-p[1])**2/(2.0*p[2]**2))+p[3] + return q - y + + x = np.array([1.475,1.429,1.409,1.419,1.455,1.519,1.472, 1.368,1.286, + 1.231], dtype=np.float32) + y = np.array([0.0168,0.0193,0.0211,0.0202,0.0171,0.0151,0.0185,0.0258, + 0.034,0.0396], dtype=np.float32) + p0 = np.array([1.0,1.0,1.0,1.0]) + p1, success = optimize.leastsq(func, p0, args=(x,y)) + + assert_(success in [1,2,3,4]) + assert_((func(p1,x,y)**2).sum() < 1e-4 * (func(p0,x,y)**2).sum()) + + def test_func_can_raise(self): + def func(*args): + raise ValueError('I raised') + + with assert_raises(ValueError, match='I raised'): + optimize.leastsq(func, x0=[0]) + + def test_Dfun_can_raise(self): + def func(x): + return x - np.array([10]) + + def deriv_func(*args): + raise ValueError('I raised') + + with assert_raises(ValueError, match='I raised'): + optimize.leastsq(func, x0=[0], Dfun=deriv_func) + + def test_reentrant_func(self): + def func(*args): + self.test_basic() + return self.residuals(*args) + + p0 = array([0,0,0]) + params_fit, ier = leastsq(func, p0, + args=(self.y_meas, self.x)) + assert_(ier in (1,2,3,4), 'solution not found (ier=%d)' % ier) + # low precision due to random + assert_array_almost_equal(params_fit, self.abc, decimal=2) + + def test_reentrant_Dfun(self): + def deriv_func(*args): + self.test_basic() + return self.residuals_jacobian(*args) + + p0 = array([0,0,0]) + params_fit, ier = leastsq(self.residuals, p0, + args=(self.y_meas, self.x), + Dfun=deriv_func) + assert_(ier in (1,2,3,4), 'solution not found (ier=%d)' % ier) + # low precision due to random + assert_array_almost_equal(params_fit, self.abc, decimal=2) + + def test_concurrent_no_gradient(self): + v = sequence_parallel([self.test_basic] * 10) + assert all([result is None for result in v]) + + def test_concurrent_with_gradient(self): + v = sequence_parallel([self.test_basic_with_gradient] * 10) + assert all([result is None for result in v]) + + def test_func_input_output_length_check(self): + + def func(x): + return 2 * (x[0] - 3) ** 2 + 1 + + with assert_raises(TypeError, + match='Improper input: func input vector length N='): + optimize.leastsq(func, x0=[0, 1]) + + +class TestCurveFit: + def setup_method(self): + self.y = array([1.0, 3.2, 9.5, 13.7]) + self.x = array([1.0, 2.0, 3.0, 4.0]) + + def test_one_argument(self): + def func(x,a): + return x**a + popt, pcov = curve_fit(func, self.x, self.y) + assert_(len(popt) == 1) + assert_(pcov.shape == (1,1)) + assert_almost_equal(popt[0], 1.9149, decimal=4) + assert_almost_equal(pcov[0,0], 0.0016, decimal=4) + + # Test if we get the same with full_output. Regression test for #1415. + # Also test if check_finite can be turned off. + res = curve_fit(func, self.x, self.y, + full_output=1, check_finite=False) + (popt2, pcov2, infodict, errmsg, ier) = res + assert_array_almost_equal(popt, popt2) + + def test_two_argument(self): + def func(x, a, b): + return b*x**a + popt, pcov = curve_fit(func, self.x, self.y) + assert_(len(popt) == 2) + assert_(pcov.shape == (2,2)) + assert_array_almost_equal(popt, [1.7989, 1.1642], decimal=4) + assert_array_almost_equal(pcov, [[0.0852, -0.1260], [-0.1260, 0.1912]], + decimal=4) + + def test_func_is_classmethod(self): + class test_self: + """This class tests if curve_fit passes the correct number of + arguments when the model function is a class instance method. + """ + + def func(self, x, a, b): + return b * x**a + + test_self_inst = test_self() + popt, pcov = curve_fit(test_self_inst.func, self.x, self.y) + assert_(pcov.shape == (2,2)) + assert_array_almost_equal(popt, [1.7989, 1.1642], decimal=4) + assert_array_almost_equal(pcov, [[0.0852, -0.1260], [-0.1260, 0.1912]], + decimal=4) + + def test_regression_2639(self): + # This test fails if epsfcn in leastsq is too large. + x = [574.14200000000005, 574.154, 574.16499999999996, + 574.17700000000002, 574.18799999999999, 574.19899999999996, + 574.21100000000001, 574.22199999999998, 574.23400000000004, + 574.245] + y = [859.0, 997.0, 1699.0, 2604.0, 2013.0, 1964.0, 2435.0, + 1550.0, 949.0, 841.0] + guess = [574.1861428571428, 574.2155714285715, 1302.0, 1302.0, + 0.0035019999999983615, 859.0] + good = [5.74177150e+02, 5.74209188e+02, 1.74187044e+03, 1.58646166e+03, + 1.0068462e-02, 8.57450661e+02] + + def f_double_gauss(x, x0, x1, A0, A1, sigma, c): + return (A0*np.exp(-(x-x0)**2/(2.*sigma**2)) + + A1*np.exp(-(x-x1)**2/(2.*sigma**2)) + c) + popt, pcov = curve_fit(f_double_gauss, x, y, guess, maxfev=10000) + assert_allclose(popt, good, rtol=1e-5) + + def test_pcov(self): + xdata = np.array([0, 1, 2, 3, 4, 5]) + ydata = np.array([1, 1, 5, 7, 8, 12]) + sigma = np.array([1, 2, 1, 2, 1, 2]) + + def f(x, a, b): + return a*x + b + + for method in ['lm', 'trf', 'dogbox']: + popt, pcov = curve_fit(f, xdata, ydata, p0=[2, 0], sigma=sigma, + method=method) + perr_scaled = np.sqrt(np.diag(pcov)) + assert_allclose(perr_scaled, [0.20659803, 0.57204404], rtol=1e-3) + + popt, pcov = curve_fit(f, xdata, ydata, p0=[2, 0], sigma=3*sigma, + method=method) + perr_scaled = np.sqrt(np.diag(pcov)) + assert_allclose(perr_scaled, [0.20659803, 0.57204404], rtol=1e-3) + + popt, pcov = curve_fit(f, xdata, ydata, p0=[2, 0], sigma=sigma, + absolute_sigma=True, method=method) + perr = np.sqrt(np.diag(pcov)) + assert_allclose(perr, [0.30714756, 0.85045308], rtol=1e-3) + + popt, pcov = curve_fit(f, xdata, ydata, p0=[2, 0], sigma=3*sigma, + absolute_sigma=True, method=method) + perr = np.sqrt(np.diag(pcov)) + assert_allclose(perr, [3*0.30714756, 3*0.85045308], rtol=1e-3) + + # infinite variances + + def f_flat(x, a, b): + return a*x + + pcov_expected = np.array([np.inf]*4).reshape(2, 2) + + with suppress_warnings() as sup: + sup.filter(OptimizeWarning, + "Covariance of the parameters could not be estimated") + popt, pcov = curve_fit(f_flat, xdata, ydata, p0=[2, 0], sigma=sigma) + popt1, pcov1 = curve_fit(f, xdata[:2], ydata[:2], p0=[2, 0]) + + assert_(pcov.shape == (2, 2)) + assert_array_equal(pcov, pcov_expected) + + assert_(pcov1.shape == (2, 2)) + assert_array_equal(pcov1, pcov_expected) + + def test_array_like(self): + # Test sequence input. Regression test for gh-3037. + def f_linear(x, a, b): + return a*x + b + + x = [1, 2, 3, 4] + y = [3, 5, 7, 9] + assert_allclose(curve_fit(f_linear, x, y)[0], [2, 1], atol=1e-10) + + @pytest.mark.thread_unsafe + def test_indeterminate_covariance(self): + # Test that a warning is returned when pcov is indeterminate + xdata = np.array([1, 2, 3, 4, 5, 6]) + ydata = np.array([1, 2, 3, 4, 5.5, 6]) + assert_warns(OptimizeWarning, curve_fit, + lambda x, a, b: a*x, xdata, ydata) + + def test_NaN_handling(self): + # Test for correct handling of NaNs in input data: gh-3422 + + # create input with NaNs + xdata = np.array([1, np.nan, 3]) + ydata = np.array([1, 2, 3]) + + assert_raises(ValueError, curve_fit, + lambda x, a, b: a*x + b, xdata, ydata) + assert_raises(ValueError, curve_fit, + lambda x, a, b: a*x + b, ydata, xdata) + + assert_raises(ValueError, curve_fit, lambda x, a, b: a*x + b, + xdata, ydata, **{"check_finite": True}) + + @staticmethod + def _check_nan_policy(f, xdata_with_nan, xdata_without_nan, + ydata_with_nan, ydata_without_nan, method): + kwargs = {'f': f, 'xdata': xdata_with_nan, 'ydata': ydata_with_nan, + 'method': method, 'check_finite': False} + # propagate test + error_msg = ("`nan_policy='propagate'` is not supported " + "by this function.") + with assert_raises(ValueError, match=error_msg): + curve_fit(**kwargs, nan_policy="propagate", maxfev=2000) + + # raise test + with assert_raises(ValueError, match="The input contains nan"): + curve_fit(**kwargs, nan_policy="raise") + + # omit test + result_with_nan, _ = curve_fit(**kwargs, nan_policy="omit") + kwargs['xdata'] = xdata_without_nan + kwargs['ydata'] = ydata_without_nan + result_without_nan, _ = curve_fit(**kwargs) + assert_allclose(result_with_nan, result_without_nan) + + # not valid policy test + # check for argument names in any order + error_msg = (r"nan_policy must be one of \{(?:'raise'|'omit'|None)" + r"(?:, ?(?:'raise'|'omit'|None))*\}") + with assert_raises(ValueError, match=error_msg): + curve_fit(**kwargs, nan_policy="hi") + + @pytest.mark.parametrize('method', ["lm", "trf", "dogbox"]) + def test_nan_policy_1d(self, method): + def f(x, a, b): + return a*x + b + + xdata_with_nan = np.array([2, 3, np.nan, 4, 4, np.nan]) + ydata_with_nan = np.array([1, 2, 5, 3, np.nan, 7]) + xdata_without_nan = np.array([2, 3, 4]) + ydata_without_nan = np.array([1, 2, 3]) + + self._check_nan_policy(f, xdata_with_nan, xdata_without_nan, + ydata_with_nan, ydata_without_nan, method) + + @pytest.mark.parametrize('method', ["lm", "trf", "dogbox"]) + def test_nan_policy_2d(self, method): + def f(x, a, b): + x1 = x[0, :] + x2 = x[1, :] + return a*x1 + b + x2 + + xdata_with_nan = np.array([[2, 3, np.nan, 4, 4, np.nan, 5], + [2, 3, np.nan, np.nan, 4, np.nan, 7]]) + ydata_with_nan = np.array([1, 2, 5, 3, np.nan, 7, 10]) + xdata_without_nan = np.array([[2, 3, 5], [2, 3, 7]]) + ydata_without_nan = np.array([1, 2, 10]) + + self._check_nan_policy(f, xdata_with_nan, xdata_without_nan, + ydata_with_nan, ydata_without_nan, method) + + @pytest.mark.parametrize('n', [2, 3]) + @pytest.mark.parametrize('method', ["lm", "trf", "dogbox"]) + def test_nan_policy_2_3d(self, n, method): + def f(x, a, b): + x1 = x[..., 0, :].squeeze() + x2 = x[..., 1, :].squeeze() + return a*x1 + b + x2 + + xdata_with_nan = np.array([[[2, 3, np.nan, 4, 4, np.nan, 5], + [2, 3, np.nan, np.nan, 4, np.nan, 7]]]) + xdata_with_nan = xdata_with_nan.squeeze() if n == 2 else xdata_with_nan + ydata_with_nan = np.array([1, 2, 5, 3, np.nan, 7, 10]) + xdata_without_nan = np.array([[[2, 3, 5], [2, 3, 7]]]) + ydata_without_nan = np.array([1, 2, 10]) + + self._check_nan_policy(f, xdata_with_nan, xdata_without_nan, + ydata_with_nan, ydata_without_nan, method) + + def test_empty_inputs(self): + # Test both with and without bounds (regression test for gh-9864) + assert_raises(ValueError, curve_fit, lambda x, a: a*x, [], []) + assert_raises(ValueError, curve_fit, lambda x, a: a*x, [], [], + bounds=(1, 2)) + assert_raises(ValueError, curve_fit, lambda x, a: a*x, [1], []) + assert_raises(ValueError, curve_fit, lambda x, a: a*x, [2], [], + bounds=(1, 2)) + + def test_function_zero_params(self): + # Fit args is zero, so "Unable to determine number of fit parameters." + assert_raises(ValueError, curve_fit, lambda x: x, [1, 2], [3, 4]) + + def test_None_x(self): # Added in GH10196 + popt, pcov = curve_fit(lambda _, a: a * np.arange(10), + None, 2 * np.arange(10)) + assert_allclose(popt, [2.]) + + def test_method_argument(self): + def f(x, a, b): + return a * np.exp(-b*x) + + xdata = np.linspace(0, 1, 11) + ydata = f(xdata, 2., 2.) + + for method in ['trf', 'dogbox', 'lm', None]: + popt, pcov = curve_fit(f, xdata, ydata, method=method) + assert_allclose(popt, [2., 2.]) + + assert_raises(ValueError, curve_fit, f, xdata, ydata, method='unknown') + + def test_full_output(self): + def f(x, a, b): + return a * np.exp(-b * x) + + xdata = np.linspace(0, 1, 11) + ydata = f(xdata, 2., 2.) + + for method in ['trf', 'dogbox', 'lm', None]: + popt, pcov, infodict, errmsg, ier = curve_fit( + f, xdata, ydata, method=method, full_output=True) + assert_allclose(popt, [2., 2.]) + assert "nfev" in infodict + assert "fvec" in infodict + if method == 'lm' or method is None: + assert "fjac" in infodict + assert "ipvt" in infodict + assert "qtf" in infodict + assert isinstance(errmsg, str) + assert ier in (1, 2, 3, 4) + + def test_bounds(self): + def f(x, a, b): + return a * np.exp(-b*x) + + xdata = np.linspace(0, 1, 11) + ydata = f(xdata, 2., 2.) + + # The minimum w/out bounds is at [2., 2.], + # and with bounds it's at [1.5, smth]. + lb = [1., 0] + ub = [1.5, 3.] + + # Test that both variants of the bounds yield the same result + bounds = (lb, ub) + bounds_class = Bounds(lb, ub) + for method in [None, 'trf', 'dogbox']: + popt, pcov = curve_fit(f, xdata, ydata, bounds=bounds, + method=method) + assert_allclose(popt[0], 1.5) + + popt_class, pcov_class = curve_fit(f, xdata, ydata, + bounds=bounds_class, + method=method) + assert_allclose(popt_class, popt) + + # With bounds, the starting estimate is feasible. + popt, pcov = curve_fit(f, xdata, ydata, method='trf', + bounds=([0., 0], [0.6, np.inf])) + assert_allclose(popt[0], 0.6) + + # method='lm' doesn't support bounds. + assert_raises(ValueError, curve_fit, f, xdata, ydata, bounds=bounds, + method='lm') + + def test_bounds_p0(self): + # This test is for issue #5719. The problem was that an initial guess + # was ignored when 'trf' or 'dogbox' methods were invoked. + def f(x, a): + return np.sin(x + a) + + xdata = np.linspace(-2*np.pi, 2*np.pi, 40) + ydata = np.sin(xdata) + bounds = (-3 * np.pi, 3 * np.pi) + for method in ['trf', 'dogbox']: + popt_1, _ = curve_fit(f, xdata, ydata, p0=2.1*np.pi) + popt_2, _ = curve_fit(f, xdata, ydata, p0=2.1*np.pi, + bounds=bounds, method=method) + + # If the initial guess is ignored, then popt_2 would be close 0. + assert_allclose(popt_1, popt_2) + + def test_jac(self): + # Test that Jacobian callable is handled correctly and + # weighted if sigma is provided. + def f(x, a, b): + return a * np.exp(-b*x) + + def jac(x, a, b): + e = np.exp(-b*x) + return np.vstack((e, -a * x * e)).T + + xdata = np.linspace(0, 1, 11) + ydata = f(xdata, 2., 2.) + + # Test numerical options for least_squares backend. + for method in ['trf', 'dogbox']: + for scheme in ['2-point', '3-point', 'cs']: + popt, pcov = curve_fit(f, xdata, ydata, jac=scheme, + method=method) + assert_allclose(popt, [2, 2]) + + # Test the analytic option. + for method in ['lm', 'trf', 'dogbox']: + popt, pcov = curve_fit(f, xdata, ydata, method=method, jac=jac) + assert_allclose(popt, [2, 2]) + + # Now add an outlier and provide sigma. + ydata[5] = 100 + sigma = np.ones(xdata.shape[0]) + sigma[5] = 200 + for method in ['lm', 'trf', 'dogbox']: + popt, pcov = curve_fit(f, xdata, ydata, sigma=sigma, method=method, + jac=jac) + # Still the optimization process is influenced somehow, + # have to set rtol=1e-3. + assert_allclose(popt, [2, 2], rtol=1e-3) + + def test_maxfev_and_bounds(self): + # gh-6340: with no bounds, curve_fit accepts parameter maxfev (via leastsq) + # but with bounds, the parameter is `max_nfev` (via least_squares) + x = np.arange(0, 10) + y = 2*x + popt1, _ = curve_fit(lambda x,p: p*x, x, y, bounds=(0, 3), maxfev=100) + popt2, _ = curve_fit(lambda x,p: p*x, x, y, bounds=(0, 3), max_nfev=100) + + assert_allclose(popt1, 2, atol=1e-14) + assert_allclose(popt2, 2, atol=1e-14) + + @pytest.mark.parametrize("sigma_dim", [0, 1, 2]) + def test_curvefit_omitnan(self, sigma_dim): + def exponential(x, a, b): + return b * np.exp(a * x) + + rng = np.random.default_rng(578285731148908) + N = 100 + x = np.linspace(1, 10, N) + y = exponential(x, 0.2, 0.5) + + if (sigma_dim == 0): + sigma = 0.05 + y += rng.normal(0, sigma, N) + + elif (sigma_dim == 1): + sigma = x * 0.05 + y += rng.normal(0, sigma, N) + + elif (sigma_dim == 2): + # The covariance matrix must be symmetric positive-semidefinite + a = rng.normal(0, 2, (N, N)) + sigma = a @ a.T + y += rng.multivariate_normal(np.zeros_like(x), sigma) + else: + assert False, "The sigma must be a scalar, 1D array or 2D array." + + p0 = [0.1, 1.0] + + # Choose indices to place NaNs. + i_x = rng.integers(N, size=5) + i_y = rng.integers(N, size=5) + + # Add NaNs and compute result using `curve_fit` + x[i_x] = np.nan + y[i_y] = np.nan + res_opt, res_cov = curve_fit(exponential, x, y, p0=p0, sigma=sigma, + nan_policy="omit") + + # Manually remove elements that should be eliminated, and + # calculate reference using `curve_fit` + i_delete = np.unique(np.concatenate((i_x, i_y))) + x = np.delete(x, i_delete, axis=0) + y = np.delete(y, i_delete, axis=0) + + sigma = np.asarray(sigma) + if sigma.ndim == 1: + sigma = np.delete(sigma, i_delete) + elif sigma.ndim == 2: + sigma = np.delete(sigma, i_delete, axis=0) + sigma = np.delete(sigma, i_delete, axis=1) + ref_opt, ref_cov = curve_fit(exponential, x, y, p0=p0, sigma=sigma) + + assert_allclose(res_opt, ref_opt, atol=1e-14) + assert_allclose(res_cov, ref_cov, atol=1e-14) + + def test_curvefit_simplecovariance(self): + + def func(x, a, b): + return a * np.exp(-b*x) + + def jac(x, a, b): + e = np.exp(-b*x) + return np.vstack((e, -a * x * e)).T + + np.random.seed(0) + xdata = np.linspace(0, 4, 50) + y = func(xdata, 2.5, 1.3) + ydata = y + 0.2 * np.random.normal(size=len(xdata)) + + sigma = np.zeros(len(xdata)) + 0.2 + covar = np.diag(sigma**2) + + for jac1, jac2 in [(jac, jac), (None, None)]: + for absolute_sigma in [False, True]: + popt1, pcov1 = curve_fit(func, xdata, ydata, sigma=sigma, + jac=jac1, absolute_sigma=absolute_sigma) + popt2, pcov2 = curve_fit(func, xdata, ydata, sigma=covar, + jac=jac2, absolute_sigma=absolute_sigma) + + assert_allclose(popt1, popt2, atol=1e-14) + assert_allclose(pcov1, pcov2, atol=1e-14) + + def test_curvefit_covariance(self): + + def funcp(x, a, b): + rotn = np.array([[1./np.sqrt(2), -1./np.sqrt(2), 0], + [1./np.sqrt(2), 1./np.sqrt(2), 0], + [0, 0, 1.0]]) + return rotn.dot(a * np.exp(-b*x)) + + def jacp(x, a, b): + rotn = np.array([[1./np.sqrt(2), -1./np.sqrt(2), 0], + [1./np.sqrt(2), 1./np.sqrt(2), 0], + [0, 0, 1.0]]) + e = np.exp(-b*x) + return rotn.dot(np.vstack((e, -a * x * e)).T) + + def func(x, a, b): + return a * np.exp(-b*x) + + def jac(x, a, b): + e = np.exp(-b*x) + return np.vstack((e, -a * x * e)).T + + rng = np.random.RandomState(0) + xdata = np.arange(1, 4) + y = func(xdata, 2.5, 1.0) + ydata = y + 0.2 * rng.normal(size=len(xdata)) + sigma = np.zeros(len(xdata)) + 0.2 + covar = np.diag(sigma**2) + # Get a rotation matrix, and obtain ydatap = R ydata + # Chisq = ydata^T C^{-1} ydata + # = ydata^T R^T R C^{-1} R^T R ydata + # = ydatap^T Cp^{-1} ydatap + # Cp^{-1} = R C^{-1} R^T + # Cp = R C R^T, since R^-1 = R^T + rotn = np.array([[1./np.sqrt(2), -1./np.sqrt(2), 0], + [1./np.sqrt(2), 1./np.sqrt(2), 0], + [0, 0, 1.0]]) + ydatap = rotn.dot(ydata) + covarp = rotn.dot(covar).dot(rotn.T) + + for jac1, jac2 in [(jac, jacp), (None, None)]: + for absolute_sigma in [False, True]: + popt1, pcov1 = curve_fit(func, xdata, ydata, sigma=sigma, + jac=jac1, absolute_sigma=absolute_sigma) + popt2, pcov2 = curve_fit(funcp, xdata, ydatap, sigma=covarp, + jac=jac2, absolute_sigma=absolute_sigma) + + assert_allclose(popt1, popt2, rtol=1.2e-7, atol=1e-14) + assert_allclose(pcov1, pcov2, rtol=1.2e-7, atol=1e-14) + + @pytest.mark.parametrize("absolute_sigma", [False, True]) + def test_curvefit_scalar_sigma(self, absolute_sigma): + def func(x, a, b): + return a * x + b + + x, y = self.x, self.y + _, pcov1 = curve_fit(func, x, y, sigma=2, absolute_sigma=absolute_sigma) + # Explicitly building the sigma 1D array + _, pcov2 = curve_fit( + func, x, y, sigma=np.full_like(y, 2), absolute_sigma=absolute_sigma + ) + assert np.all(pcov1 == pcov2) + + def test_dtypes(self): + # regression test for gh-9581: curve_fit fails if x and y dtypes differ + x = np.arange(-3, 5) + y = 1.5*x + 3.0 + 0.5*np.sin(x) + + def func(x, a, b): + return a*x + b + + for method in ['lm', 'trf', 'dogbox']: + for dtx in [np.float32, np.float64]: + for dty in [np.float32, np.float64]: + x = x.astype(dtx) + y = y.astype(dty) + + with warnings.catch_warnings(): + warnings.simplefilter("error", OptimizeWarning) + p, cov = curve_fit(func, x, y, method=method) + + assert np.isfinite(cov).all() + assert not np.allclose(p, 1) # curve_fit's initial value + + def test_dtypes2(self): + # regression test for gh-7117: curve_fit fails if + # both inputs are float32 + def hyperbola(x, s_1, s_2, o_x, o_y, c): + b_2 = (s_1 + s_2) / 2 + b_1 = (s_2 - s_1) / 2 + return o_y + b_1*(x-o_x) + b_2*np.sqrt((x-o_x)**2 + c**2/4) + + min_fit = np.array([-3.0, 0.0, -2.0, -10.0, 0.0]) + max_fit = np.array([0.0, 3.0, 3.0, 0.0, 10.0]) + guess = np.array([-2.5/3.0, 4/3.0, 1.0, -4.0, 0.5]) + + params = [-2, .4, -1, -5, 9.5] + xdata = np.array([-32, -16, -8, 4, 4, 8, 16, 32]) + ydata = hyperbola(xdata, *params) + + # run optimization twice, with xdata being float32 and float64 + popt_64, _ = curve_fit(f=hyperbola, xdata=xdata, ydata=ydata, p0=guess, + bounds=(min_fit, max_fit)) + + xdata = xdata.astype(np.float32) + ydata = hyperbola(xdata, *params) + + popt_32, _ = curve_fit(f=hyperbola, xdata=xdata, ydata=ydata, p0=guess, + bounds=(min_fit, max_fit)) + + assert_allclose(popt_32, popt_64, atol=2e-5) + + def test_broadcast_y(self): + xdata = np.arange(10) + target = 4.7 * xdata ** 2 + 3.5 * xdata + np.random.rand(len(xdata)) + def fit_func(x, a, b): + return a * x ** 2 + b * x - target + for method in ['lm', 'trf', 'dogbox']: + popt0, pcov0 = curve_fit(fit_func, + xdata=xdata, + ydata=np.zeros_like(xdata), + method=method) + popt1, pcov1 = curve_fit(fit_func, + xdata=xdata, + ydata=0, + method=method) + assert_allclose(pcov0, pcov1) + + def test_args_in_kwargs(self): + # Ensure that `args` cannot be passed as keyword argument to `curve_fit` + + def func(x, a, b): + return a * x + b + + with assert_raises(ValueError): + curve_fit(func, + xdata=[1, 2, 3, 4], + ydata=[5, 9, 13, 17], + p0=[1], + args=(1,)) + + def test_data_point_number_validation(self): + def func(x, a, b, c, d, e): + return a * np.exp(-b * x) + c + d + e + + with assert_raises(TypeError, match="The number of func parameters="): + curve_fit(func, + xdata=[1, 2, 3, 4], + ydata=[5, 9, 13, 17]) + + @pytest.mark.filterwarnings('ignore::RuntimeWarning') + def test_gh4555(self): + # gh-4555 reported that covariance matrices returned by `leastsq` + # can have negative diagonal elements and eigenvalues. (In fact, + # they can also be asymmetric.) This shows up in the output of + # `scipy.optimize.curve_fit`. Check that it has been resolved.giit + def f(x, a, b, c, d, e): + return a*np.log(x + 1 + b) + c*np.log(x + 1 + d) + e + + rng = np.random.default_rng(408113519974467917) + n = 100 + x = np.arange(n) + y = np.linspace(2, 7, n) + rng.random(n) + p, cov = optimize.curve_fit(f, x, y, maxfev=100000) + assert np.all(np.diag(cov) > 0) + eigs = linalg.eigh(cov)[0] # separate line for debugging + # some platforms see a small negative eigevenvalue + assert np.all(eigs > -1e-2) + assert_allclose(cov, cov.T) + + def test_gh4555b(self): + # check that PR gh-17247 did not significantly change covariance matrix + # for simple cases + rng = np.random.default_rng(408113519974467917) + + def func(x, a, b, c): + return a * np.exp(-b * x) + c + + xdata = np.linspace(0, 4, 50) + y = func(xdata, 2.5, 1.3, 0.5) + y_noise = 0.2 * rng.normal(size=xdata.size) + ydata = y + y_noise + _, res = curve_fit(func, xdata, ydata) + # reference from commit 1d80a2f254380d2b45733258ca42eb6b55c8755b + ref = [[+0.0158972536486215, 0.0069207183284242, -0.0007474400714749], + [+0.0069207183284242, 0.0205057958128679, +0.0053997711275403], + [-0.0007474400714749, 0.0053997711275403, +0.0027833930320877]] + # Linux_Python_38_32bit_full fails with default tolerance + assert_allclose(res, ref, 2e-7) + + def test_gh13670(self): + # gh-13670 reported that `curve_fit` executes callables + # with the same values of the parameters at the beginning of + # optimization. Check that this has been resolved. + + rng = np.random.default_rng(8250058582555444926) + x = np.linspace(0, 3, 101) + y = 2 * x + 1 + rng.normal(size=101) * 0.5 + + def line(x, *p): + assert not np.all(line.last_p == p) + line.last_p = p + return x * p[0] + p[1] + + def jac(x, *p): + assert not np.all(jac.last_p == p) + jac.last_p = p + return np.array([x, np.ones_like(x)]).T + + line.last_p = None + jac.last_p = None + p0 = np.array([1.0, 5.0]) + curve_fit(line, x, y, p0, method='lm', jac=jac) + + @pytest.mark.parametrize('method', ['trf', 'dogbox']) + def test_gh20155_error_mentions_x0(self, method): + # `curve_fit` produced an error message that referred to an undocumented + # variable `x0`, which was really `p0`. Check that this is resolved. + def func(x,a): + return x**a + message = "Initial guess is outside of provided bounds" + with pytest.raises(ValueError, match=message): + curve_fit(func, self.x, self.y, p0=[1], bounds=(1000, 1001), + method=method) + + +class TestFixedPoint: + + def test_scalar_trivial(self): + # f(x) = 2x; fixed point should be x=0 + def func(x): + return 2.0*x + x0 = 1.0 + x = fixed_point(func, x0) + assert_almost_equal(x, 0.0) + + def test_scalar_basic1(self): + # f(x) = x**2; x0=1.05; fixed point should be x=1 + def func(x): + return x**2 + x0 = 1.05 + x = fixed_point(func, x0) + assert_almost_equal(x, 1.0) + + def test_scalar_basic2(self): + # f(x) = x**0.5; x0=1.05; fixed point should be x=1 + def func(x): + return x**0.5 + x0 = 1.05 + x = fixed_point(func, x0) + assert_almost_equal(x, 1.0) + + def test_array_trivial(self): + def func(x): + return 2.0*x + x0 = [0.3, 0.15] + with np.errstate(all='ignore'): + x = fixed_point(func, x0) + assert_almost_equal(x, [0.0, 0.0]) + + def test_array_basic1(self): + # f(x) = c * x**2; fixed point should be x=1/c + def func(x, c): + return c * x**2 + c = array([0.75, 1.0, 1.25]) + x0 = [1.1, 1.15, 0.9] + with np.errstate(all='ignore'): + x = fixed_point(func, x0, args=(c,)) + assert_almost_equal(x, 1.0/c) + + def test_array_basic2(self): + # f(x) = c * x**0.5; fixed point should be x=c**2 + def func(x, c): + return c * x**0.5 + c = array([0.75, 1.0, 1.25]) + x0 = [0.8, 1.1, 1.1] + x = fixed_point(func, x0, args=(c,)) + assert_almost_equal(x, c**2) + + def test_lambertw(self): + # python-list/2010-December/594592.html + xxroot = fixed_point(lambda xx: np.exp(-2.0*xx)/2.0, 1.0, + args=(), xtol=1e-12, maxiter=500) + assert_allclose(xxroot, np.exp(-2.0*xxroot)/2.0) + assert_allclose(xxroot, lambertw(1)/2) + + def test_no_acceleration(self): + # GitHub issue 5460 + ks = 2 + kl = 6 + m = 1.3 + n0 = 1.001 + i0 = ((m-1)/m)*(kl/ks/m)**(1/(m-1)) + + def func(n): + return np.log(kl/ks/n) / np.log(i0*n/(n - 1)) + 1 + + n = fixed_point(func, n0, method='iteration') + assert_allclose(n, m) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_nnls.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_nnls.py new file mode 100644 index 0000000000000000000000000000000000000000..67443dd6147bd7ee8898bac2a1a7993f6e56e799 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_nnls.py @@ -0,0 +1,429 @@ +import numpy as np +from numpy.testing import assert_allclose +from pytest import raises as assert_raises +from scipy.optimize import nnls + + +class TestNNLS: + def setup_method(self): + self.rng = np.random.default_rng(1685225766635251) + + def test_nnls(self): + a = np.arange(25.0).reshape(-1, 5) + x = np.arange(5.0) + y = a @ x + x, res = nnls(a, y) + assert res < 1e-7 + assert np.linalg.norm((a @ x) - y) < 1e-7 + + def test_nnls_tall(self): + a = self.rng.uniform(low=-10, high=10, size=[50, 10]) + x = np.abs(self.rng.uniform(low=-2, high=2, size=[10])) + x[::2] = 0 + b = a @ x + xact, rnorm = nnls(a, b, atol=500*np.linalg.norm(a, 1)*np.spacing(1.)) + assert_allclose(xact, x, rtol=0., atol=1e-10) + assert rnorm < 1e-12 + + def test_nnls_wide(self): + # If too wide then problem becomes too ill-conditioned ans starts + # emitting warnings, hence small m, n difference. + a = self.rng.uniform(low=-10, high=10, size=[100, 120]) + x = np.abs(self.rng.uniform(low=-2, high=2, size=[120])) + x[::2] = 0 + b = a @ x + xact, rnorm = nnls(a, b, atol=500*np.linalg.norm(a, 1)*np.spacing(1.)) + assert_allclose(xact, x, rtol=0., atol=1e-10) + assert rnorm < 1e-12 + + def test_maxiter(self): + # test that maxiter argument does stop iterations + a = self.rng.uniform(size=(5, 10)) + b = self.rng.uniform(size=5) + with assert_raises(RuntimeError): + nnls(a, b, maxiter=1) + + def test_nnls_inner_loop_case1(self): + # See gh-20168 + n = np.array( + [3, 2, 0, 1, 1, 1, 3, 8, 14, 16, 29, 23, 41, 47, 53, 57, 67, 76, + 103, 89, 97, 94, 85, 95, 78, 78, 78, 77, 73, 50, 50, 56, 68, 98, + 95, 112, 134, 145, 158, 172, 213, 234, 222, 215, 216, 216, 206, + 183, 135, 156, 110, 92, 63, 60, 52, 29, 20, 16, 12, 5, 5, 5, 1, 2, + 3, 0, 2]) + k = np.array( + [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., + 0., 0., 0., 0.7205812007860187, 0., 1.4411624015720375, + 0.7205812007860187, 2.882324803144075, 5.76464960628815, + 5.76464960628815, 12.249880413362318, 15.132205216506394, + 20.176273622008523, 27.382085629868712, 48.27894045266326, + 47.558359251877235, 68.45521407467177, 97.99904330689854, + 108.0871801179028, 135.46926574777152, 140.51333415327366, + 184.4687874012208, 171.49832578707245, 205.36564222401535, + 244.27702706646033, 214.01261663344755, 228.42424064916793, + 232.02714665309804, 205.36564222401535, 172.9394881886445, + 191.67459940908097, 162.1307701768542, 153.48379576742198, + 110.96950492104689, 103.04311171240067, 86.46974409432225, + 60.528820866025576, 43.234872047161126, 23.779179625938617, + 24.499760826724636, 17.29394881886445, 11.5292992125763, + 5.76464960628815, 5.044068405502131, 3.6029060039300935, 0., + 2.882324803144075, 0., 0., 0.]) + d = np.array( + [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., + 0., 0., 0., 0.003889242101538, 0., 0.007606268390096, 0., + 0.025457371599973, 0.036952882091577, 0., 0.08518359183449, + 0.048201126400243, 0.196234990022205, 0.144116240157247, + 0.171145134062442, 0., 0., 0.269555036538714, 0., 0., 0., + 0.010893241091872, 0., 0., 0., 0., 0., 0., 0., 0., + 0.048167058272886, 0.011238724891049, 0., 0., 0.055162603456078, + 0., 0., 0., 0., 0.027753339088588, 0., 0., 0., 0., 0., 0., 0., 0., + 0., 0.]) + # The following code sets up a system of equations such that + # $k_i-p_i*n_i$ is minimized for $p_i$ with weights $n_i$ and + # monotonicity constraints on $p_i$. This translates to a system of + # equations of the form $k_i - (d_1 + ... + d_i) * n_i$ and + # non-negativity constraints on the $d_i$. If $n_i$ is zero the + # system is modified such that $d_i - d_{i+1}$ is then minimized. + N = len(n) + A = np.diag(n) @ np.tril(np.ones((N, N))) + w = n ** 0.5 + + nz = (n == 0).nonzero()[0] + A[nz, nz] = 1 + A[nz, np.minimum(nz + 1, N - 1)] = -1 + w[nz] = 1 + k[nz] = 0 + W = np.diag(w) + + # Small perturbations can already make the infinite loop go away (just + # uncomment the next line) + # k = k + 1e-10 * np.random.normal(size=N) + dact, _ = nnls(W @ A, W @ k) + assert_allclose(dact, d, rtol=0., atol=1e-10) + + def test_nnls_inner_loop_case2(self): + # See gh-20168 + n = np.array( + [1, 0, 1, 2, 2, 2, 3, 3, 5, 4, 14, 14, 19, 26, 36, 42, 36, 64, 64, + 64, 81, 85, 85, 95, 95, 95, 75, 76, 69, 81, 62, 59, 68, 64, 71, 67, + 74, 78, 118, 135, 153, 159, 210, 195, 218, 243, 236, 215, 196, 175, + 185, 149, 144, 103, 104, 75, 56, 40, 32, 26, 17, 9, 12, 8, 2, 1, 1, + 1]) + k = np.array( + [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., + 0., 0., 0., 0., 0., 0.7064355064917867, 0., 0., 2.11930651947536, + 0.7064355064917867, 0., 3.5321775324589333, 7.064355064917867, + 11.302968103868587, 16.95445215580288, 20.486629688261814, + 20.486629688261814, 37.44108184406469, 55.808405012851146, + 78.41434122058831, 103.13958394780086, 105.965325973768, + 125.74552015553803, 149.057891869767, 176.60887662294667, + 197.09550631120848, 211.930651947536, 204.86629688261814, + 233.8301526487814, 221.1143135319292, 195.6826352982249, + 197.80194181770025, 191.4440222592742, 187.91184472681525, + 144.11284332432447, 131.39700420747232, 116.5618585711448, + 93.24948685691584, 89.01087381796512, 53.68909849337579, + 45.211872415474346, 31.083162285638615, 24.72524272721253, + 16.95445215580288, 9.890097090885014, 9.890097090885014, + 2.8257420259671466, 2.8257420259671466, 1.4128710129835733, + 0.7064355064917867, 1.4128710129835733]) + d = np.array( + [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., + 0., 0., 0., 0., 0., 0.0021916146355674473, 0., 0., + 0.011252740799789484, 0., 0., 0.037746623295934395, + 0.03602328132946222, 0.09509167709829734, 0.10505765870204821, + 0.01391037014274718, 0.0188296228752321, 0.20723559202324254, + 0.3056220879462608, 0.13304643490426477, 0., 0., 0., 0., 0., 0., + 0., 0., 0., 0., 0., 0.043185876949706214, 0.0037266261379722554, + 0., 0., 0., 0., 0., 0.094797899357143, 0., 0., 0., 0., 0., 0., 0., + 0., 0.23450935613672663, 0., 0., 0.07064355064917871]) + # The following code sets up a system of equations such that + # $k_i-p_i*n_i$ is minimized for $p_i$ with weights $n_i$ and + # monotonicity constraints on $p_i$. This translates to a system of + # equations of the form $k_i - (d_1 + ... + d_i) * n_i$ and + # non-negativity constraints on the $d_i$. If $n_i$ is zero the + # system is modified such that $d_i - d_{i+1}$ is then minimized. + N = len(n) + A = np.diag(n) @ np.tril(np.ones((N, N))) + w = n ** 0.5 + + nz = (n == 0).nonzero()[0] + A[nz, nz] = 1 + A[nz, np.minimum(nz + 1, N - 1)] = -1 + w[nz] = 1 + k[nz] = 0 + W = np.diag(w) + + dact, _ = nnls(W @ A, W @ k, atol=1e-7) + + p = np.cumsum(dact) + assert np.all(dact >= 0) + assert np.linalg.norm(k - n * p, ord=np.inf) < 28 + assert_allclose(dact, d, rtol=0., atol=1e-10) + + def test_nnls_gh20302(self): + # See gh-20302 + A = np.array( + [0.33408569134321575, 0.11136189711440525, 0.049140798007949286, + 0.03712063237146841, 0.055680948557202625, 0.16642814595936478, + 0.11095209730624318, 0.09791993030943345, 0.14793612974165757, + 0.44380838922497273, 0.11099502671044059, 0.11099502671044059, + 0.14693672599330593, 0.3329850801313218, 1.498432860590948, + 0.0832374225132955, 0.11098323001772734, 0.19589481249472837, + 0.5919105600945457, 3.5514633605672747, 0.06658716751427037, + 0.11097861252378394, 0.24485832778293645, 0.9248217710315328, + 6.936163282736496, 0.05547609388181014, 0.11095218776362029, + 0.29376003042571264, 1.3314262531634435, 11.982836278470993, + 0.047506113282944136, 0.11084759766020298, 0.3423969672933396, + 1.8105107617833156, 19.010362998724812, 0.041507335004505576, + 0.11068622667868154, 0.39074115283013344, 2.361306169145206, + 28.335674029742474, 0.03682846280947718, 0.11048538842843154, + 0.4387861797121048, 2.9831054875676517, 40.2719240821633, + 0.03311278164362387, 0.11037593881207958, 0.4870572300443105, + 3.6791979604026523, 55.187969406039784, 0.030079304092299915, + 0.11029078167176636, 0.5353496017200152, 4.448394860761242, + 73.3985152025605, 0.02545939709595835, 0.11032405408248619, + 0.6328767609778363, 6.214921713313388, 121.19097340961108, + 0.022080881724881523, 0.11040440862440762, 0.7307742886903428, + 8.28033064683057, 186.30743955368786, 0.020715838214945492, + 0.1104844704797093, 0.7800578384588346, 9.42800814760186, + 226.27219554244465, 0.01843179728340054, 0.11059078370040323, + 0.8784095015912599, 11.94380463964355, 322.48272527037585, + 0.015812787653789077, 0.11068951357652354, 1.0257259848595766, + 16.27135849574896, 512.5477926160922, 0.014438550529330062, + 0.11069555405819713, 1.1234754801775881, 19.519316032262093, + 673.4164031130423, 0.012760770585072577, 0.110593345070629, + 1.2688431112524712, 24.920367089248398, 971.8943164806875, + 0.011427556646114315, 0.11046638091243838, 1.413623342459821, + 30.967408782453557, 1347.0822820367298, 0.010033330264470307, + 0.11036663290917338, 1.6071533470570285, 40.063087746029936, + 1983.122843428482, 0.008950061496507258, 0.11038409179025618, + 1.802244865119193, 50.37194055362024, 2795.642700725923, + 0.008071078821135658, 0.11030474388885401, 1.9956465761433504, + 61.80742482572119, 3801.1566267818534, 0.007191031207777556, + 0.11026247851925586, 2.238160187262168, 77.7718015155818, + 5366.2543045751445, 0.00636834224248, 0.11038459886965334, + 2.5328963107984297, 99.49331844784753, 7760.4788389321075, + 0.005624259098118485, 0.11061042892966355, 2.879742607664547, + 128.34496770138628, 11358.529641572684, 0.0050354270614989555, + 0.11077939535297703, 3.2263279459292575, 160.85168205252265, + 15924.316523199741, 0.0044997853165982555, 0.1109947044760903, + 3.6244287189055613, 202.60233390369015, 22488.859063309606, + 0.004023601950058174, 0.1113196539516095, 4.07713905729421, + 255.6270320242126, 31825.565487014468, 0.0036024117873727094, + 0.111674765408554, 4.582933773135057, 321.9583486728612, + 44913.18963986413, 0.003201503089582304, 0.11205260813538065, + 5.191786833370116, 411.79333489752383, 64857.45024636, + 0.0028633044552448853, 0.11262330857296549, 5.864295861648949, + 522.7223161899905, 92521.84996562831, 0.0025691897303891965, + 0.11304434813712465, 6.584584405106342, 656.5615739804199, + 129999.19164812315, 0.0022992911894424675, 0.11343169867916175, + 7.4080129906658305, 828.2026426227864, 183860.98666225857, + 0.0020449922071108764, 0.11383789952917212, 8.388975556433872, + 1058.2750599896935, 265097.9025274183, 0.001831274615120854, + 0.11414945100919989, 9.419351803810935, 1330.564050780237, + 373223.2162438565, 0.0016363333454631633, 0.11454333418242145, + 10.6143816579462, 1683.787012481595, 530392.9089317025, + 0.0014598610433380044, 0.11484240207592301, 11.959688127956882, + 2132.0874753402027, 754758.9662704318, 0.0012985240015312626, + 0.11513579480243862, 13.514425358573531, 2715.5160990137824, + 1083490.9235064993, 0.0011614735761289934, 0.11537304189548002, + 15.171418602667567, 3415.195870828736, 1526592.554260445, + 0.0010347472698811352, 0.11554677847006009, 17.080800985009617, + 4322.412404600832, 2172012.2333119176, 0.0009232988811258664, + 0.1157201264344419, 19.20004861829407, 5453.349531598553, + 3075689.135821584, 0.0008228871862975205, 0.11602709326795038, + 21.65735242414206, 6920.203923780365, 4390869.389638642, + 0.00073528900066722, 0.11642075843897651, 24.40223571298994, + 8755.811207598026, 6238515.485413593, 0.0006602764384729194, + 0.11752920604817965, 27.694443541914293, 11171.386093291572, + 8948280.260726549, 0.0005935538977939806, 0.11851292825953147, + 31.325508920763063, 14174.185724149384, 12735505.873148222, + 0.0005310755355633124, 0.11913794514470308, 35.381052949627765, + 17987.010118815077, 18157886.71494382, 0.00047239949671590953, + 0.1190446731724092, 39.71342528048061, 22679.438775422022, + 25718483.571328573, 0.00041829129789387623, 0.11851586773659825, + 44.45299332965028, 28542.57147989741, 36391778.63686921, + 0.00037321512015419886, 0.11880681324908665, 50.0668539579632, + 36118.26128449941, 51739409.29004541, 0.0003315539616702064, + 0.1184752823034871, 56.04387059062639, 45383.29960621684, + 72976345.76679668, 0.00029456064937920213, 0.11831519416731286, + 62.91195073220101, 57265.53993693082, 103507463.43600245, + 0.00026301867496859703, 0.11862142241083726, 70.8217262087034, + 72383.14781936012, 146901598.49939138, 0.00023618734450420032, + 0.11966825454879482, 80.26535457124461, 92160.51176984518, + 210125966.835247, 0.00021165918071578316, 0.12043407382728061, + 90.7169587544247, 116975.56852918258, 299515943.218972, + 0.00018757727511329545, 0.11992440455576689, 101.49899864101785, + 147056.26174166967, 423080865.0307836, 0.00016654469159895833, + 0.11957908856805206, 113.65970431102812, 184937.67016486943, + 597533612.3026931, 0.00014717439179415048, 0.11872067604728138, + 126.77899683346702, 231758.58906776624, 841283678.3159915, + 0.00012868496382376066, 0.1166314722122684, 139.93635237349534, + 287417.30847929465, 1172231492.6328032, 0.00011225559452625302, + 0.11427619522772557, 154.0034283704458, 355281.4912295324, + 1627544511.322488, 9.879511142981067e-05, 0.11295574406808354, + 170.96532050841535, 442971.0111288653, 2279085852.2580123, + 8.71257780313587e-05, 0.11192758284428547, 190.35067416684697, + 554165.2523674504, 3203629323.93623, 7.665069027765277e-05, + 0.11060694607065294, 211.28835951100046, 690933.608546013, + 4486577387.093535, 6.734021094824451e-05, 0.10915848194710433, + 234.24338803525194, 860487.9079859136, 6276829044.8032465, + 5.9191625040287665e-05, 0.10776821865668373, 259.7454711820425, + 1071699.0387579766, 8780430224.544102, 5.1856803674907676e-05, + 0.10606444911641115, 287.1843540288165, 1331126.3723998806, + 12251687131.5685, 4.503421404759231e-05, 0.10347361247668461, + 314.7338642485931, 1638796.0697522392, 16944331963.203278, + 3.90470387455642e-05, 0.1007804070023012, 344.3427560918527, + 2014064.4865519698, 23392351979.057854, 3.46557661636393e-05, + 0.10046706610839032, 385.56603915081587, 2533036.2523656, + 33044724430.235435, 3.148745865254635e-05, 0.1025441570117926, + 442.09038234164746, 3262712.3882769793, 47815050050.199135, + 2.9790762078715404e-05, 0.1089845379379672, 527.8068231298969, + 4375751.903321453, 72035815708.42941, 2.8772639817606534e-05, + 0.11823636789048445, 643.2048194503195, 5989838.001888927, + 110764084330.93005, 2.7951691815106586e-05, 0.12903432664913705, + 788.5500418523591, 8249371.000613411, 171368308481.2427, + 2.6844392423114212e-05, 0.1392060709754626, 955.6296403631383, + 11230229.319931043, 262063016295.25085, 2.499458273851386e-05, + 0.14559344445184325, 1122.7022399726002, 14820229.698461473, + 388475270970.9214, 2.337386729019776e-05, 0.15294300496886065, + 1324.8158105672455, 19644861.137128454, 578442936182.7473, + 2.0081014872174113e-05, 0.14760215298210377, 1436.2385042492353, + 23923681.729276657, 791311658718.4193, 1.773374462991839e-05, + 0.14642752940923615, 1600.5596278736678, 29949429.82503553, + 1112815989293.9326, 1.5303115839590797e-05, 0.14194150045081785, + 1742.873058605698, 36634451.931305364, 1529085389160.7544, + 1.3148448731163076e-05, 0.13699368732998807, 1889.5284359054356, + 44614279.74469635, 2091762812969.9607, 1.1739194407590062e-05, + 0.13739553134643406, 2128.794599579694, 56462810.11822766, + 2973783283306.8145, 1.0293367506254706e-05, 0.13533033372723272, + 2355.372854690074, 70176508.28667311, 4151852759764.441, + 9.678312586863569e-06, 0.14293577249119244, 2794.531827932675, + 93528671.31952812, 6215821967224.52, -1.174086323572049e-05, + 0.1429501325944908, 3139.4804810720925, 118031680.16618933, + -6466892421886.174, -2.1188265307407812e-05, 0.1477108290912869, + 3644.1133424610953, 153900132.62392554, -4828013117542.036, + -8.614483025123122e-05, 0.16037100755883044, 4444.386620899393, + 210846007.89660168, -1766340937974.433, 4.981445776141726e-05, + 0.16053420251962536, 4997.558254401547, 266327328.4755411, + 3862250287024.725, 1.8500019169456637e-05, 0.15448417164977674, + 5402.289867444643, 323399508.1475582, 12152445411933.408, + -5.647882376069748e-05, 0.1406372975946189, 5524.633133597753, + 371512945.9909363, -4162951345292.1514, 2.8048523486337994e-05, + 0.13183417571186926, 5817.462495763679, 439447252.3728975, + 9294740538175.03]).reshape(89, 5) + b = np.ones(89, dtype=np.float64) + sol, rnorm = nnls(A, b) + assert_allclose(sol, np.array([0.61124315, 8.22262829, 0., 0., 0.])) + assert_allclose(rnorm, 1.0556460808977297) + + def test_nnls_gh21021_ex1(self): + # Review examples used in gh-21021 + A = [[0.004734199143798789, -0.09661916455815653, -0.04308779048103441, + 0.4039475561867938, -0.27742598780954364, -0.20816924034369574, + -0.17264070902176, 0.05251808558963846], + [-0.030263548855047975, -0.30356483926431466, 0.18080406600591398, + -0.06892233941254086, -0.41837298885432317, 0.30245352819647003, + -0.19008975278116397, -0.00990809825429995], + [-0.2561747595787612, -0.04376282125249583, 0.4422181991706678, + -0.13720906318924858, -0.0069523811763796475, -0.059238287107464795, + 0.028663214369642594, 0.5415531284893763], + [0.2949336072968401, 0.33997647534935094, 0.38441519339815755, + -0.306001783010386, 0.18120773805949028, -0.36669767490747895, + -0.021539960590992304, -0.2784251712424615], + [0.5009075736232653, -0.20161970347571165, 0.08404512586550646, + 0.2520496489348788, 0.14812015101612894, -0.25823455803981266, + -0.1596872058396596, 0.5960141613922691] + ] + b = [18.036779281222124, -18.126530733870887, 13.535652034584029, + -2.6654275476795966, 9.166315328199575] + + # Obtained from matlab's lstnonneg + des_sol = np.array([0., 118.017802006619, 45.1996532316584, 102.62156313537, + 0., 55.8590204314398, 0., 29.7328833253434]) + sol, res = nnls(A, b) + assert_allclose(sol, des_sol) + assert np.abs(np.linalg.norm(A@sol - b) - res) < 5e-14 + + def test_nnls_gh21021_ex2(self): + A = np.array([ + [0.2508259992635229, -0.24031300195203256], + [0.510647748500133, 0.2872936081767836], + [0.8196387904102849, -0.03520620107046682], + [0.030739759120097084, -0.07768656359879388]]) + b = np.array([24.456141951303913, + 28.047143273432333, + 41.10526799545987, + -1.2078282698324068]) + + sol, res = nnls(A, b) + assert_allclose(sol, np.array([54.3047953202271, 0.0])) + assert np.abs(np.linalg.norm(A@sol - b) - res) < 5e-14 + + def test_nnls_gh21021_ex3(self): + A = np.array([ + [0.08247592017366788, 0.058398241636675674, -0.1031496693415968, + 0.03156983127072098, -0.029503680182026665], + [0.21463607509982277, -0.2164518969308173, -0.10816833396662294, + 0.12133867146012027, -0.15025010408668332], + [0.07251900316494089, -0.003044559315020767, 0.042682817961676424, + -0.018157525489298176, 0.11561953260568134], + [0.2328797918159187, -0.09112909645892767, 0.21348169727099078, + 0.00449447624089599, -0.16615256386885716], + [-0.02440856024843897, -0.20131427208575386, 0.030275781997161483, + -0.04560777213546784, 0.11007266012013553], + [-0.2928391429686263, -0.20437574856615687, -0.020892110811574407, + -0.10455040720819309, 0.05337267000160461], + [0.22041503019400316, 0.014262782992311842, 0.08274606359871121, + -0.17933172096518907, -0.11809690350702161], + [0.10440436007469953, 0.09171452270577712, 0.03942347724809893, + 0.11457669688231396, 0.07529747295631585], + [-0.052087576116032056, -0.15787717158077047, -0.08232202515883282, + -0.03194837933710708, -0.0546812506025729], + [-0.010388407673304468, 0.015174707581808923, 0.04764509565386281, + -0.1781221936030805, 0.10218894080536609], + [0.03272263140115928, -0.27576456949442574, 0.024897570959901753, + -0.1417129166632282, -0.03320796462136591], + [-0.12490006751823997, -0.03012003515442302, -0.051495264012509506, + 0.012070729698374614, 0.04811700123118234], + [0.15254854117990788, -0.051863547789218374, 0.058012914127346174, + -0.06717991061422621, -0.14514671564242257], + [0.12251250415395559, -0.17462495626695362, -0.025334728552179834, + 0.11425350676877533, 0.06183915953812639], + [0.19334259720491218, 0.2164301986218955, -0.018882278726614483, + 0.07950236716817938, -0.2220529357431092], + [-0.01822205701890852, 0.12630444976752267, -0.03118092027244001, + 0.02773743885242581, 0.06444433740044248], + [0.13344116850581977, -0.05142877469996826, 0.3385702016705455, + -0.25814970787123004, 0.2679034842977378], + [0.1309747058619377, 0.12090608957940627, -0.13957978654106512, + 0.17048819760322642, -0.241775259969348], + [0.28613102173467275, -0.47153463906732174, 0.20359970518269746, + -0.0962095202871843, -0.07703076550836387], + [0.2212788380372723, 0.02569245145758152, -0.021596152392209966, + 0.04610005150029433, -0.2024454395619734], + [-0.043225338359410316, 0.17816095186290315, -0.014709092962616079, + 0.06993970293287989, -0.09033722782555903], + [0.17747622942563512, -0.20991014784011458, 0.06265720409894943, + 0.0689704059061795, 0.024474319398401525], + [-0.1163880385601698, 0.29989570587630027, 0.033443765320984545, + 0.008470296514656, -0.0014457113271462002], + [0.024375314902718406, 0.05279830705548363, 0.02691082431023144, + 0.05265079368002343, 0.15542988147487913], + [-0.01855218360922308, -0.050265869142888164, 0.2567912677240452, + -0.2606428528561333, 0.25334396245022245]]) + + b = np.array([-7.876625373734849, -8.259856278691373, 3.2593082374900963, + 16.30170376973345, 2.311892943629045, -1.595345202555738, + 6.318582970536518, 3.0104212955340093, -6.286202915842167, + 3.6382333725029294, 1.9012066681249356, -3.932236581436514, + 4.4299317131740406, -1.9345885161292682, -1.4418721521970805, + -2.3810103256943926, 25.853603392922526, -10.658470311610483, + 15.547103681119214, -1.6491066136547277, -1.1232029689817422, + 4.7845749463206975, 2.553803732013229, 2.0549409701753705, + 19.60887153608244]) + + sol, res = nnls(A, b) + assert_allclose(sol, np.array([0.0, 0.0, 76.3611306173957, 0.0, 0.0]), + atol=5e-14) + assert np.abs(np.linalg.norm(A@sol - b) - res) < 5e-14 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_nonlin.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_nonlin.py new file mode 100644 index 0000000000000000000000000000000000000000..e5eb094c15902eca6e089ba3bbf6dfd8eb06970e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_nonlin.py @@ -0,0 +1,536 @@ +""" Unit tests for nonlinear solvers +Author: Ondrej Certik +May 2007 +""" +from numpy.testing import assert_ +import pytest +from functools import partial + +from scipy.optimize import _nonlin as nonlin, root +from scipy.sparse import csr_array +from numpy import diag, dot +from numpy.linalg import inv +import numpy as np +import scipy + +from .test_minpack import pressure_network + +SOLVERS = {'anderson': nonlin.anderson, + 'diagbroyden': nonlin.diagbroyden, + 'linearmixing': nonlin.linearmixing, + 'excitingmixing': nonlin.excitingmixing, + 'broyden1': nonlin.broyden1, + 'broyden2': nonlin.broyden2, + 'krylov': nonlin.newton_krylov} +MUST_WORK = {'anderson': nonlin.anderson, 'broyden1': nonlin.broyden1, + 'broyden2': nonlin.broyden2, 'krylov': nonlin.newton_krylov} + +# ---------------------------------------------------------------------------- +# Test problems +# ---------------------------------------------------------------------------- + + +def F(x): + x = np.asarray(x).T + d = diag([3, 2, 1.5, 1, 0.5]) + c = 0.01 + f = -d @ x - c * float(x.T @ x) * x + return f + + +F.xin = [1, 1, 1, 1, 1] +F.KNOWN_BAD = {} +F.JAC_KSP_BAD = {} +F.ROOT_JAC_KSP_BAD = {} + + +def F2(x): + return x + + +F2.xin = [1, 2, 3, 4, 5, 6] +F2.KNOWN_BAD = {'linearmixing': nonlin.linearmixing, + 'excitingmixing': nonlin.excitingmixing} +F2.JAC_KSP_BAD = {} +F2.ROOT_JAC_KSP_BAD = {} + + +def F2_lucky(x): + return x + + +F2_lucky.xin = [0, 0, 0, 0, 0, 0] +F2_lucky.KNOWN_BAD = {} +F2_lucky.JAC_KSP_BAD = {} +F2_lucky.ROOT_JAC_KSP_BAD = {} + + +def F3(x): + A = np.array([[-2, 1, 0.], [1, -2, 1], [0, 1, -2]]) + b = np.array([1, 2, 3.]) + return A @ x - b + + +F3.xin = [1, 2, 3] +F3.KNOWN_BAD = {} +F3.JAC_KSP_BAD = {} +F3.ROOT_JAC_KSP_BAD = {} + + +def F4_powell(x): + A = 1e4 + return [A*x[0]*x[1] - 1, np.exp(-x[0]) + np.exp(-x[1]) - (1 + 1/A)] + + +F4_powell.xin = [-1, -2] +F4_powell.KNOWN_BAD = {'linearmixing': nonlin.linearmixing, + 'excitingmixing': nonlin.excitingmixing, + 'diagbroyden': nonlin.diagbroyden} +# In the extreme case, it does not converge for nolinear problem solved by +# MINRES and root problem solved by GMRES/BiCGStab/CGS/MINRES/TFQMR when using +# Krylov method to approximate Jacobian +F4_powell.JAC_KSP_BAD = {'minres'} +F4_powell.ROOT_JAC_KSP_BAD = {'gmres', 'bicgstab', 'cgs', 'minres', 'tfqmr'} + + +def F5(x): + return pressure_network(x, 4, np.array([.5, .5, .5, .5])) + + +F5.xin = [2., 0, 2, 0] +F5.KNOWN_BAD = {'excitingmixing': nonlin.excitingmixing, + 'linearmixing': nonlin.linearmixing, + 'diagbroyden': nonlin.diagbroyden} +# In the extreme case, the Jacobian inversion yielded zero vector for nonlinear +# problem solved by CGS/MINRES and it does not converge for root problem solved +# by MINRES and when using Krylov method to approximate Jacobian +F5.JAC_KSP_BAD = {'cgs', 'minres'} +F5.ROOT_JAC_KSP_BAD = {'minres'} + + +def F6(x): + x1, x2 = x + J0 = np.array([[-4.256, 14.7], + [0.8394989, 0.59964207]]) + v = np.array([(x1 + 3) * (x2**5 - 7) + 3*6, + np.sin(x2 * np.exp(x1) - 1)]) + return -np.linalg.solve(J0, v) + + +F6.xin = [-0.5, 1.4] +F6.KNOWN_BAD = {'excitingmixing': nonlin.excitingmixing, + 'linearmixing': nonlin.linearmixing, + 'diagbroyden': nonlin.diagbroyden} +F6.JAC_KSP_BAD = {} +F6.ROOT_JAC_KSP_BAD = {} + + +# ---------------------------------------------------------------------------- +# Tests +# ---------------------------------------------------------------------------- + + +class TestNonlin: + """ + Check the Broyden methods for a few test problems. + + broyden1, broyden2, and newton_krylov must succeed for + all functions. Some of the others don't -- tests in KNOWN_BAD are skipped. + + """ + + def _check_nonlin_func(self, f, func, f_tol=1e-2): + # Test all methods mentioned in the class `KrylovJacobian` + if func == SOLVERS['krylov']: + for method in ['gmres', 'bicgstab', 'cgs', 'minres', 'tfqmr']: + if method in f.JAC_KSP_BAD: + continue + + x = func(f, f.xin, method=method, line_search=None, + f_tol=f_tol, maxiter=200, verbose=0) + assert_(np.absolute(f(x)).max() < f_tol) + + x = func(f, f.xin, f_tol=f_tol, maxiter=200, verbose=0) + assert_(np.absolute(f(x)).max() < f_tol) + + def _check_root(self, f, method, f_tol=1e-2): + # Test Krylov methods + if method == 'krylov': + for jac_method in ['gmres', 'bicgstab', 'cgs', 'minres', 'tfqmr']: + if jac_method in f.ROOT_JAC_KSP_BAD: + continue + + res = root(f, f.xin, method=method, + options={'ftol': f_tol, 'maxiter': 200, + 'disp': 0, + 'jac_options': {'method': jac_method}}) + assert_(np.absolute(res.fun).max() < f_tol) + + res = root(f, f.xin, method=method, + options={'ftol': f_tol, 'maxiter': 200, 'disp': 0}) + assert_(np.absolute(res.fun).max() < f_tol) + + @pytest.mark.xfail + def _check_func_fail(self, *a, **kw): + pass + + @pytest.mark.filterwarnings('ignore::DeprecationWarning') + def test_problem_nonlin(self): + for f in [F, F2, F2_lucky, F3, F4_powell, F5, F6]: + for func in SOLVERS.values(): + if func in f.KNOWN_BAD.values(): + if func in MUST_WORK.values(): + self._check_func_fail(f, func) + continue + self._check_nonlin_func(f, func) + + @pytest.mark.filterwarnings('ignore::DeprecationWarning') + @pytest.mark.parametrize("method", ['lgmres', 'gmres', 'bicgstab', 'cgs', + 'minres', 'tfqmr']) + def test_tol_norm_called(self, method): + # Check that supplying tol_norm keyword to nonlin_solve works + self._tol_norm_used = False + + def local_norm_func(x): + self._tol_norm_used = True + return np.absolute(x).max() + + nonlin.newton_krylov(F, F.xin, method=method, f_tol=1e-2, + maxiter=200, verbose=0, + tol_norm=local_norm_func) + assert_(self._tol_norm_used) + + @pytest.mark.filterwarnings('ignore::DeprecationWarning') + def test_problem_root(self): + for f in [F, F2, F2_lucky, F3, F4_powell, F5, F6]: + for meth in SOLVERS: + if meth in f.KNOWN_BAD: + if meth in MUST_WORK: + self._check_func_fail(f, meth) + continue + self._check_root(f, meth) + + def test_no_convergence(self): + def wont_converge(x): + return 1e3 + x + + with pytest.raises(scipy.optimize.NoConvergence): + nonlin.newton_krylov(wont_converge, xin=[0], maxiter=1) + + +class TestSecant: + """Check that some Jacobian approximations satisfy the secant condition""" + + xs = [np.array([1., 2., 3., 4., 5.]), + np.array([2., 3., 4., 5., 1.]), + np.array([3., 4., 5., 1., 2.]), + np.array([4., 5., 1., 2., 3.]), + np.array([9., 1., 9., 1., 3.]), + np.array([0., 1., 9., 1., 3.]), + np.array([5., 5., 7., 1., 1.]), + np.array([1., 2., 7., 5., 1.]),] + fs = [x**2 - 1 for x in xs] + + def _check_secant(self, jac_cls, npoints=1, **kw): + """ + Check that the given Jacobian approximation satisfies secant + conditions for last `npoints` points. + """ + jac = jac_cls(**kw) + jac.setup(self.xs[0], self.fs[0], None) + for j, (x, f) in enumerate(zip(self.xs[1:], self.fs[1:])): + jac.update(x, f) + + for k in range(min(npoints, j+1)): + dx = self.xs[j-k+1] - self.xs[j-k] + df = self.fs[j-k+1] - self.fs[j-k] + assert_(np.allclose(dx, jac.solve(df))) + + # Check that the `npoints` secant bound is strict + if j >= npoints: + dx = self.xs[j-npoints+1] - self.xs[j-npoints] + df = self.fs[j-npoints+1] - self.fs[j-npoints] + assert_(not np.allclose(dx, jac.solve(df))) + + def test_broyden1(self): + self._check_secant(nonlin.BroydenFirst) + + def test_broyden2(self): + self._check_secant(nonlin.BroydenSecond) + + def test_broyden1_update(self): + # Check that BroydenFirst update works as for a dense matrix + jac = nonlin.BroydenFirst(alpha=0.1) + jac.setup(self.xs[0], self.fs[0], None) + + B = np.identity(5) * (-1/0.1) + + for last_j, (x, f) in enumerate(zip(self.xs[1:], self.fs[1:])): + df = f - self.fs[last_j] + dx = x - self.xs[last_j] + B += (df - dot(B, dx))[:, None] * dx[None, :] / dot(dx, dx) + jac.update(x, f) + assert_(np.allclose(jac.todense(), B, rtol=1e-10, atol=1e-13)) + + def test_broyden2_update(self): + # Check that BroydenSecond update works as for a dense matrix + jac = nonlin.BroydenSecond(alpha=0.1) + jac.setup(self.xs[0], self.fs[0], None) + + H = np.identity(5) * (-0.1) + + for last_j, (x, f) in enumerate(zip(self.xs[1:], self.fs[1:])): + df = f - self.fs[last_j] + dx = x - self.xs[last_j] + H += (dx - dot(H, df))[:, None] * df[None, :] / dot(df, df) + jac.update(x, f) + assert_(np.allclose(jac.todense(), inv(H), rtol=1e-10, atol=1e-13)) + + def test_anderson(self): + # Anderson mixing (with w0=0) satisfies secant conditions + # for the last M iterates, see [Ey]_ + # + # .. [Ey] V. Eyert, J. Comp. Phys., 124, 271 (1996). + self._check_secant(nonlin.Anderson, M=3, w0=0, npoints=3) + + +class TestLinear: + """Solve a linear equation; + some methods find the exact solution in a finite number of steps""" + + def _check(self, jac, N, maxiter, complex=False, **kw): + np.random.seed(123) + + A = np.random.randn(N, N) + if complex: + A = A + 1j*np.random.randn(N, N) + b = np.random.randn(N) + if complex: + b = b + 1j*np.random.randn(N) + + def func(x): + return dot(A, x) - b + + sol = nonlin.nonlin_solve(func, np.zeros(N), jac, maxiter=maxiter, + f_tol=1e-6, line_search=None, verbose=0) + assert_(np.allclose(dot(A, sol), b, atol=1e-6)) + + def test_broyden1(self): + # Broyden methods solve linear systems exactly in 2*N steps + self._check(nonlin.BroydenFirst(alpha=1.0), 20, 41, False) + self._check(nonlin.BroydenFirst(alpha=1.0), 20, 41, True) + + def test_broyden2(self): + # Broyden methods solve linear systems exactly in 2*N steps + self._check(nonlin.BroydenSecond(alpha=1.0), 20, 41, False) + self._check(nonlin.BroydenSecond(alpha=1.0), 20, 41, True) + + def test_anderson(self): + # Anderson is rather similar to Broyden, if given enough storage space + self._check(nonlin.Anderson(M=50, alpha=1.0), 20, 29, False) + self._check(nonlin.Anderson(M=50, alpha=1.0), 20, 29, True) + + def test_krylov(self): + # Krylov methods solve linear systems exactly in N inner steps + self._check(nonlin.KrylovJacobian, 20, 2, False, inner_m=10) + self._check(nonlin.KrylovJacobian, 20, 2, True, inner_m=10) + + def _check_autojac(self, A, b): + def func(x): + return A.dot(x) - b + + def jac(v): + return A + + sol = nonlin.nonlin_solve(func, np.zeros(b.shape[0]), jac, maxiter=2, + f_tol=1e-6, line_search=None, verbose=0) + np.testing.assert_allclose(A @ sol, b, atol=1e-6) + # test jac input as array -- not a function + sol = nonlin.nonlin_solve(func, np.zeros(b.shape[0]), A, maxiter=2, + f_tol=1e-6, line_search=None, verbose=0) + np.testing.assert_allclose(A @ sol, b, atol=1e-6) + + def test_jac_sparse(self): + A = csr_array([[1, 2], [2, 1]]) + b = np.array([1, -1]) + self._check_autojac(A, b) + self._check_autojac((1 + 2j) * A, (2 + 2j) * b) + + def test_jac_ndarray(self): + A = np.array([[1, 2], [2, 1]]) + b = np.array([1, -1]) + self._check_autojac(A, b) + self._check_autojac((1 + 2j) * A, (2 + 2j) * b) + + +class TestJacobianDotSolve: + """ + Check that solve/dot methods in Jacobian approximations are consistent + """ + + def _func(self, x, A=None): + return x**2 - 1 + np.dot(A, x) + + def _check_dot(self, jac_cls, complex=False, tol=1e-6, **kw): + rng = np.random.RandomState(123) + + N = 7 + + def rand(*a): + q = rng.rand(*a) + if complex: + q = q + 1j*rng.rand(*a) + return q + + def assert_close(a, b, msg): + d = abs(a - b).max() + f = tol + abs(b).max()*tol + if d > f: + raise AssertionError(f'{msg}: err {d:g}') + + A = rand(N, N) + + # initialize + x0 = rng.rand(N) + jac = jac_cls(**kw) + jac.setup(x0, self._func(x0, A), partial(self._func, A=A)) + + # check consistency + for k in range(2*N): + v = rand(N) + + if hasattr(jac, '__array__'): + Jd = np.array(jac) + if hasattr(jac, 'solve'): + Gv = jac.solve(v) + Gv2 = np.linalg.solve(Jd, v) + assert_close(Gv, Gv2, 'solve vs array') + if hasattr(jac, 'rsolve'): + Gv = jac.rsolve(v) + Gv2 = np.linalg.solve(Jd.T.conj(), v) + assert_close(Gv, Gv2, 'rsolve vs array') + if hasattr(jac, 'matvec'): + Jv = jac.matvec(v) + Jv2 = np.dot(Jd, v) + assert_close(Jv, Jv2, 'dot vs array') + if hasattr(jac, 'rmatvec'): + Jv = jac.rmatvec(v) + Jv2 = np.dot(Jd.T.conj(), v) + assert_close(Jv, Jv2, 'rmatvec vs array') + + if hasattr(jac, 'matvec') and hasattr(jac, 'solve'): + Jv = jac.matvec(v) + Jv2 = jac.solve(jac.matvec(Jv)) + assert_close(Jv, Jv2, 'dot vs solve') + + if hasattr(jac, 'rmatvec') and hasattr(jac, 'rsolve'): + Jv = jac.rmatvec(v) + Jv2 = jac.rmatvec(jac.rsolve(Jv)) + assert_close(Jv, Jv2, 'rmatvec vs rsolve') + + x = rand(N) + jac.update(x, self._func(x, A)) + + def test_broyden1(self): + self._check_dot(nonlin.BroydenFirst, complex=False) + self._check_dot(nonlin.BroydenFirst, complex=True) + + def test_broyden2(self): + self._check_dot(nonlin.BroydenSecond, complex=False) + self._check_dot(nonlin.BroydenSecond, complex=True) + + def test_anderson(self): + self._check_dot(nonlin.Anderson, complex=False) + self._check_dot(nonlin.Anderson, complex=True) + + def test_diagbroyden(self): + self._check_dot(nonlin.DiagBroyden, complex=False) + self._check_dot(nonlin.DiagBroyden, complex=True) + + def test_linearmixing(self): + self._check_dot(nonlin.LinearMixing, complex=False) + self._check_dot(nonlin.LinearMixing, complex=True) + + def test_excitingmixing(self): + self._check_dot(nonlin.ExcitingMixing, complex=False) + self._check_dot(nonlin.ExcitingMixing, complex=True) + + @pytest.mark.thread_unsafe + def test_krylov(self): + self._check_dot(nonlin.KrylovJacobian, complex=False, tol=1e-3) + self._check_dot(nonlin.KrylovJacobian, complex=True, tol=1e-3) + + +class TestNonlinOldTests: + """ Test case for a simple constrained entropy maximization problem + (the machine translation example of Berger et al in + Computational Linguistics, vol 22, num 1, pp 39--72, 1996.) + """ + + def test_broyden1(self): + x = nonlin.broyden1(F, F.xin, iter=12, alpha=1) + assert_(nonlin.norm(x) < 1e-9) + assert_(nonlin.norm(F(x)) < 1e-9) + + def test_broyden2(self): + x = nonlin.broyden2(F, F.xin, iter=12, alpha=1) + assert_(nonlin.norm(x) < 1e-9) + assert_(nonlin.norm(F(x)) < 1e-9) + + def test_anderson(self): + x = nonlin.anderson(F, F.xin, iter=12, alpha=0.03, M=5) + assert_(nonlin.norm(x) < 0.33) + + def test_linearmixing(self): + x = nonlin.linearmixing(F, F.xin, iter=60, alpha=0.5) + assert_(nonlin.norm(x) < 1e-7) + assert_(nonlin.norm(F(x)) < 1e-7) + + def test_exciting(self): + x = nonlin.excitingmixing(F, F.xin, iter=20, alpha=0.5) + assert_(nonlin.norm(x) < 1e-5) + assert_(nonlin.norm(F(x)) < 1e-5) + + def test_diagbroyden(self): + x = nonlin.diagbroyden(F, F.xin, iter=11, alpha=1) + assert_(nonlin.norm(x) < 1e-8) + assert_(nonlin.norm(F(x)) < 1e-8) + + def test_root_broyden1(self): + res = root(F, F.xin, method='broyden1', + options={'nit': 12, 'jac_options': {'alpha': 1}}) + assert_(nonlin.norm(res.x) < 1e-9) + assert_(nonlin.norm(res.fun) < 1e-9) + + def test_root_broyden2(self): + res = root(F, F.xin, method='broyden2', + options={'nit': 12, 'jac_options': {'alpha': 1}}) + assert_(nonlin.norm(res.x) < 1e-9) + assert_(nonlin.norm(res.fun) < 1e-9) + + def test_root_anderson(self): + res = root(F, F.xin, method='anderson', + options={'nit': 12, + 'jac_options': {'alpha': 0.03, 'M': 5}}) + assert_(nonlin.norm(res.x) < 0.33) + + def test_root_linearmixing(self): + res = root(F, F.xin, method='linearmixing', + options={'nit': 60, + 'jac_options': {'alpha': 0.5}}) + assert_(nonlin.norm(res.x) < 1e-7) + assert_(nonlin.norm(res.fun) < 1e-7) + + def test_root_excitingmixing(self): + res = root(F, F.xin, method='excitingmixing', + options={'nit': 20, + 'jac_options': {'alpha': 0.5}}) + assert_(nonlin.norm(res.x) < 1e-5) + assert_(nonlin.norm(res.fun) < 1e-5) + + def test_root_diagbroyden(self): + res = root(F, F.xin, method='diagbroyden', + options={'nit': 11, + 'jac_options': {'alpha': 1}}) + assert_(nonlin.norm(res.x) < 1e-8) + assert_(nonlin.norm(res.fun) < 1e-8) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_optimize.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_optimize.py new file mode 100644 index 0000000000000000000000000000000000000000..913ef51f049386a06c61164a3fc07c15111ed212 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_optimize.py @@ -0,0 +1,3257 @@ +""" +Unit tests for optimization routines from optimize.py + +Authors: + Ed Schofield, Nov 2005 + Andrew Straw, April 2008 + +""" +import itertools +import platform +import threading +import numpy as np +from numpy.testing import (assert_allclose, assert_equal, + assert_almost_equal, + assert_no_warnings, assert_warns, + assert_array_less, suppress_warnings) +import pytest +from pytest import raises as assert_raises + +import scipy +from scipy import optimize +from scipy.optimize._minimize import Bounds, NonlinearConstraint +from scipy.optimize._minimize import (MINIMIZE_METHODS, + MINIMIZE_METHODS_NEW_CB, + MINIMIZE_SCALAR_METHODS) +from scipy.optimize._linprog import LINPROG_METHODS +from scipy.optimize._root import ROOT_METHODS +from scipy.optimize._root_scalar import ROOT_SCALAR_METHODS +from scipy.optimize._qap import QUADRATIC_ASSIGNMENT_METHODS +from scipy.optimize._differentiable_functions import ScalarFunction, FD_METHODS +from scipy.optimize._optimize import MemoizeJac, show_options, OptimizeResult +from scipy.optimize import rosen, rosen_der, rosen_hess + +from scipy.sparse import (coo_matrix, csc_matrix, csr_matrix, coo_array, + csr_array, csc_array) +from scipy.conftest import array_api_compatible +from scipy._lib._array_api_no_0d import xp_assert_equal, array_namespace + +skip_xp_backends = pytest.mark.skip_xp_backends + + +def test_check_grad(): + # Verify if check_grad is able to estimate the derivative of the + # expit (logistic sigmoid) function. + + def expit(x): + return 1 / (1 + np.exp(-x)) + + def der_expit(x): + return np.exp(-x) / (1 + np.exp(-x))**2 + + x0 = np.array([1.5]) + + r = optimize.check_grad(expit, der_expit, x0) + assert_almost_equal(r, 0) + # SPEC-007 leave one call with seed to check it still works + r = optimize.check_grad(expit, der_expit, x0, + direction='random', seed=1234) + assert_almost_equal(r, 0) + + r = optimize.check_grad(expit, der_expit, x0, epsilon=1e-6) + assert_almost_equal(r, 0) + r = optimize.check_grad(expit, der_expit, x0, epsilon=1e-6, + direction='random', rng=1234) + assert_almost_equal(r, 0) + + # Check if the epsilon parameter is being considered. + r = abs(optimize.check_grad(expit, der_expit, x0, epsilon=1e-1) - 0) + assert r > 1e-7 + r = abs(optimize.check_grad(expit, der_expit, x0, epsilon=1e-1, + direction='random', rng=1234) - 0) + assert r > 1e-7 + + def x_sinx(x): + return (x*np.sin(x)).sum() + + def der_x_sinx(x): + return np.sin(x) + x*np.cos(x) + + x0 = np.arange(0, 2, 0.2) + + r = optimize.check_grad(x_sinx, der_x_sinx, x0, + direction='random', rng=1234) + assert_almost_equal(r, 0) + + assert_raises(ValueError, optimize.check_grad, + x_sinx, der_x_sinx, x0, + direction='random_projection', rng=1234) + + # checking can be done for derivatives of vector valued functions + r = optimize.check_grad(himmelblau_grad, himmelblau_hess, himmelblau_x0, + direction='all', rng=1234) + assert r < 5e-7 + + +class CheckOptimize: + """ Base test case for a simple constrained entropy maximization problem + (the machine translation example of Berger et al in + Computational Linguistics, vol 22, num 1, pp 39--72, 1996.) + """ + + def setup_method(self): + self.F = np.array([[1, 1, 1], + [1, 1, 0], + [1, 0, 1], + [1, 0, 0], + [1, 0, 0]]) + self.K = np.array([1., 0.3, 0.5]) + self.startparams = np.zeros(3, np.float64) + self.solution = np.array([0., -0.524869316, 0.487525860]) + self.maxiter = 1000 + self.funccalls = threading.local() + self.gradcalls = threading.local() + self.trace = threading.local() + + def func(self, x): + if not hasattr(self.funccalls, 'c'): + self.funccalls.c = 0 + + if not hasattr(self.gradcalls, 'c'): + self.gradcalls.c = 0 + + self.funccalls.c += 1 + if self.funccalls.c > 6000: + raise RuntimeError("too many iterations in optimization routine") + log_pdot = np.dot(self.F, x) + logZ = np.log(sum(np.exp(log_pdot))) + f = logZ - np.dot(self.K, x) + if not hasattr(self.trace, 't'): + self.trace.t = [] + self.trace.t.append(np.copy(x)) + return f + + def grad(self, x): + if not hasattr(self.gradcalls, 'c'): + self.gradcalls.c = 0 + self.gradcalls.c += 1 + log_pdot = np.dot(self.F, x) + logZ = np.log(sum(np.exp(log_pdot))) + p = np.exp(log_pdot - logZ) + return np.dot(self.F.transpose(), p) - self.K + + def hess(self, x): + log_pdot = np.dot(self.F, x) + logZ = np.log(sum(np.exp(log_pdot))) + p = np.exp(log_pdot - logZ) + return np.dot(self.F.T, + np.dot(np.diag(p), self.F - np.dot(self.F.T, p))) + + def hessp(self, x, p): + return np.dot(self.hess(x), p) + + +class CheckOptimizeParameterized(CheckOptimize): + + def test_cg(self): + # conjugate gradient optimization routine + if self.use_wrapper: + opts = {'maxiter': self.maxiter, 'disp': self.disp, + 'return_all': False} + res = optimize.minimize(self.func, self.startparams, args=(), + method='CG', jac=self.grad, + options=opts) + params, fopt, func_calls, grad_calls, warnflag = \ + res['x'], res['fun'], res['nfev'], res['njev'], res['status'] + else: + retval = optimize.fmin_cg(self.func, self.startparams, + self.grad, (), maxiter=self.maxiter, + full_output=True, disp=self.disp, + retall=False) + (params, fopt, func_calls, grad_calls, warnflag) = retval + + assert_allclose(self.func(params), self.func(self.solution), + atol=1e-6) + + # Ensure that function call counts are 'known good'; these are from + # SciPy 0.7.0. Don't allow them to increase. + assert self.funccalls.c == 9, self.funccalls.c + assert self.gradcalls.c == 7, self.gradcalls.c + + # Ensure that the function behaves the same; this is from SciPy 0.7.0 + assert_allclose(self.trace.t[2:4], + [[0, -0.5, 0.5], + [0, -5.05700028e-01, 4.95985862e-01]], + atol=1e-14, rtol=1e-7) + + def test_cg_cornercase(self): + def f(r): + return 2.5 * (1 - np.exp(-1.5*(r - 0.5)))**2 + + # Check several initial guesses. (Too far away from the + # minimum, the function ends up in the flat region of exp.) + for x0 in np.linspace(-0.75, 3, 71): + sol = optimize.minimize(f, [x0], method='CG') + assert sol.success + assert_allclose(sol.x, [0.5], rtol=1e-5) + + def test_bfgs(self): + # Broyden-Fletcher-Goldfarb-Shanno optimization routine + if self.use_wrapper: + opts = {'maxiter': self.maxiter, 'disp': self.disp, + 'return_all': False} + res = optimize.minimize(self.func, self.startparams, + jac=self.grad, method='BFGS', args=(), + options=opts) + + params, fopt, gopt, Hopt, func_calls, grad_calls, warnflag = ( + res['x'], res['fun'], res['jac'], res['hess_inv'], + res['nfev'], res['njev'], res['status']) + else: + retval = optimize.fmin_bfgs(self.func, self.startparams, self.grad, + args=(), maxiter=self.maxiter, + full_output=True, disp=self.disp, + retall=False) + (params, fopt, gopt, Hopt, + func_calls, grad_calls, warnflag) = retval + + assert_allclose(self.func(params), self.func(self.solution), + atol=1e-6) + + # Ensure that function call counts are 'known good'; these are from + # SciPy 0.7.0. Don't allow them to increase. + assert self.funccalls.c == 10, self.funccalls.c + assert self.gradcalls.c == 8, self.gradcalls.c + + # Ensure that the function behaves the same; this is from SciPy 0.7.0 + assert_allclose(self.trace.t[6:8], + [[0, -5.25060743e-01, 4.87748473e-01], + [0, -5.24885582e-01, 4.87530347e-01]], + atol=1e-14, rtol=1e-7) + + def test_bfgs_hess_inv0_neg(self): + # Ensure that BFGS does not accept neg. def. initial inverse + # Hessian estimate. + with pytest.raises(ValueError, match="'hess_inv0' matrix isn't " + "positive definite."): + x0 = np.array([1.3, 0.7, 0.8, 1.9, 1.2]) + opts = {'disp': self.disp, 'hess_inv0': -np.eye(5)} + optimize.minimize(optimize.rosen, x0=x0, method='BFGS', args=(), + options=opts) + + def test_bfgs_hess_inv0_semipos(self): + # Ensure that BFGS does not accept semi pos. def. initial inverse + # Hessian estimate. + with pytest.raises(ValueError, match="'hess_inv0' matrix isn't " + "positive definite."): + x0 = np.array([1.3, 0.7, 0.8, 1.9, 1.2]) + hess_inv0 = np.eye(5) + hess_inv0[0, 0] = 0 + opts = {'disp': self.disp, 'hess_inv0': hess_inv0} + optimize.minimize(optimize.rosen, x0=x0, method='BFGS', args=(), + options=opts) + + def test_bfgs_hess_inv0_sanity(self): + # Ensure that BFGS handles `hess_inv0` parameter correctly. + fun = optimize.rosen + x0 = np.array([1.3, 0.7, 0.8, 1.9, 1.2]) + opts = {'disp': self.disp, 'hess_inv0': 1e-2 * np.eye(5)} + res = optimize.minimize(fun, x0=x0, method='BFGS', args=(), + options=opts) + res_true = optimize.minimize(fun, x0=x0, method='BFGS', args=(), + options={'disp': self.disp}) + assert_allclose(res.fun, res_true.fun, atol=1e-6) + + @pytest.mark.filterwarnings('ignore::UserWarning') + def test_bfgs_infinite(self): + # Test corner case where -Inf is the minimum. See gh-2019. + def func(x): + return -np.e ** (-x) + def fprime(x): + return -func(x) + x0 = [0] + with np.errstate(over='ignore'): + if self.use_wrapper: + opts = {'disp': self.disp} + x = optimize.minimize(func, x0, jac=fprime, method='BFGS', + args=(), options=opts)['x'] + else: + x = optimize.fmin_bfgs(func, x0, fprime, disp=self.disp) + assert not np.isfinite(func(x)) + + def test_bfgs_xrtol(self): + # test for #17345 to test xrtol parameter + x0 = [1.3, 0.7, 0.8, 1.9, 1.2] + res = optimize.minimize(optimize.rosen, + x0, method='bfgs', options={'xrtol': 1e-3}) + ref = optimize.minimize(optimize.rosen, + x0, method='bfgs', options={'gtol': 1e-3}) + assert res.nit != ref.nit + + def test_bfgs_c1(self): + # test for #18977 insufficiently low value of c1 leads to precision loss + # for poor starting parameters + x0 = [10.3, 20.7, 10.8, 1.9, -1.2] + res_c1_small = optimize.minimize(optimize.rosen, + x0, method='bfgs', options={'c1': 1e-8}) + res_c1_big = optimize.minimize(optimize.rosen, + x0, method='bfgs', options={'c1': 1e-1}) + + assert res_c1_small.nfev > res_c1_big.nfev + + def test_bfgs_c2(self): + # test that modification of c2 parameter + # results in different number of iterations + x0 = [1.3, 0.7, 0.8, 1.9, 1.2] + res_default = optimize.minimize(optimize.rosen, + x0, method='bfgs', options={'c2': .9}) + res_mod = optimize.minimize(optimize.rosen, + x0, method='bfgs', options={'c2': 1e-2}) + assert res_default.nit > res_mod.nit + + @pytest.mark.parametrize(["c1", "c2"], [[0.5, 2], + [-0.1, 0.1], + [0.2, 0.1]]) + def test_invalid_c1_c2(self, c1, c2): + with pytest.raises(ValueError, match="'c1' and 'c2'"): + x0 = [10.3, 20.7, 10.8, 1.9, -1.2] + optimize.minimize(optimize.rosen, x0, method='cg', + options={'c1': c1, 'c2': c2}) + + def test_powell(self): + # Powell (direction set) optimization routine + if self.use_wrapper: + opts = {'maxiter': self.maxiter, 'disp': self.disp, + 'return_all': False} + res = optimize.minimize(self.func, self.startparams, args=(), + method='Powell', options=opts) + params, fopt, direc, numiter, func_calls, warnflag = ( + res['x'], res['fun'], res['direc'], res['nit'], + res['nfev'], res['status']) + else: + retval = optimize.fmin_powell(self.func, self.startparams, + args=(), maxiter=self.maxiter, + full_output=True, disp=self.disp, + retall=False) + (params, fopt, direc, numiter, func_calls, warnflag) = retval + + assert_allclose(self.func(params), self.func(self.solution), + atol=1e-6) + # params[0] does not affect the objective function + assert_allclose(params[1:], self.solution[1:], atol=5e-6) + + # Ensure that function call counts are 'known good'; these are from + # SciPy 0.7.0. Don't allow them to increase. + # + # However, some leeway must be added: the exact evaluation + # count is sensitive to numerical error, and floating-point + # computations are not bit-for-bit reproducible across + # machines, and when using e.g., MKL, data alignment + # etc., affect the rounding error. + # + assert self.funccalls.c <= 116 + 20, self.funccalls.c + assert self.gradcalls.c == 0, self.gradcalls.c + + @pytest.mark.xfail(reason="This part of test_powell fails on some " + "platforms, but the solution returned by powell is " + "still valid.") + def test_powell_gh14014(self): + # This part of test_powell started failing on some CI platforms; + # see gh-14014. Since the solution is still correct and the comments + # in test_powell suggest that small differences in the bits are known + # to change the "trace" of the solution, seems safe to xfail to get CI + # green now and investigate later. + + # Powell (direction set) optimization routine + if self.use_wrapper: + opts = {'maxiter': self.maxiter, 'disp': self.disp, + 'return_all': False} + res = optimize.minimize(self.func, self.startparams, args=(), + method='Powell', options=opts) + params, fopt, direc, numiter, func_calls, warnflag = ( + res['x'], res['fun'], res['direc'], res['nit'], + res['nfev'], res['status']) + else: + retval = optimize.fmin_powell(self.func, self.startparams, + args=(), maxiter=self.maxiter, + full_output=True, disp=self.disp, + retall=False) + (params, fopt, direc, numiter, func_calls, warnflag) = retval + + # Ensure that the function behaves the same; this is from SciPy 0.7.0 + assert_allclose(self.trace[34:39], + [[0.72949016, -0.44156936, 0.47100962], + [0.72949016, -0.44156936, 0.48052496], + [1.45898031, -0.88313872, 0.95153458], + [0.72949016, -0.44156936, 0.47576729], + [1.72949016, -0.44156936, 0.47576729]], + atol=1e-14, rtol=1e-7) + + def test_powell_bounded(self): + # Powell (direction set) optimization routine + # same as test_powell above, but with bounds + bounds = [(-np.pi, np.pi) for _ in self.startparams] + if self.use_wrapper: + opts = {'maxiter': self.maxiter, 'disp': self.disp, + 'return_all': False} + res = optimize.minimize(self.func, self.startparams, args=(), + bounds=bounds, + method='Powell', options=opts) + params, func_calls = (res['x'], res['nfev']) + + assert func_calls == self.funccalls.c + assert_allclose(self.func(params), self.func(self.solution), + atol=1e-6, rtol=1e-5) + + # The exact evaluation count is sensitive to numerical error, and + # floating-point computations are not bit-for-bit reproducible + # across machines, and when using e.g. MKL, data alignment etc. + # affect the rounding error. + # It takes 155 calls on my machine, but we can add the same +20 + # margin as is used in `test_powell` + assert self.funccalls.c <= 155 + 20 + assert self.gradcalls.c == 0 + + def test_neldermead(self): + # Nelder-Mead simplex algorithm + if self.use_wrapper: + opts = {'maxiter': self.maxiter, 'disp': self.disp, + 'return_all': False} + res = optimize.minimize(self.func, self.startparams, args=(), + method='Nelder-mead', options=opts) + params, fopt, numiter, func_calls, warnflag = ( + res['x'], res['fun'], res['nit'], res['nfev'], + res['status']) + else: + retval = optimize.fmin(self.func, self.startparams, + args=(), maxiter=self.maxiter, + full_output=True, disp=self.disp, + retall=False) + (params, fopt, numiter, func_calls, warnflag) = retval + + assert_allclose(self.func(params), self.func(self.solution), + atol=1e-6) + + # Ensure that function call counts are 'known good'; these are from + # SciPy 0.7.0. Don't allow them to increase. + assert self.funccalls.c == 167, self.funccalls.c + assert self.gradcalls.c == 0, self.gradcalls.c + + # Ensure that the function behaves the same; this is from SciPy 0.7.0 + assert_allclose(self.trace.t[76:78], + [[0.1928968, -0.62780447, 0.35166118], + [0.19572515, -0.63648426, 0.35838135]], + atol=1e-14, rtol=1e-7) + + def test_neldermead_initial_simplex(self): + # Nelder-Mead simplex algorithm + simplex = np.zeros((4, 3)) + simplex[...] = self.startparams + for j in range(3): + simplex[j+1, j] += 0.1 + + if self.use_wrapper: + opts = {'maxiter': self.maxiter, 'disp': False, + 'return_all': True, 'initial_simplex': simplex} + res = optimize.minimize(self.func, self.startparams, args=(), + method='Nelder-mead', options=opts) + params, fopt, numiter, func_calls, warnflag = (res['x'], + res['fun'], + res['nit'], + res['nfev'], + res['status']) + assert_allclose(res['allvecs'][0], simplex[0]) + else: + retval = optimize.fmin(self.func, self.startparams, + args=(), maxiter=self.maxiter, + full_output=True, disp=False, retall=False, + initial_simplex=simplex) + + (params, fopt, numiter, func_calls, warnflag) = retval + + assert_allclose(self.func(params), self.func(self.solution), + atol=1e-6) + + # Ensure that function call counts are 'known good'; these are from + # SciPy 0.17.0. Don't allow them to increase. + assert self.funccalls.c == 100, self.funccalls.c + assert self.gradcalls.c == 0, self.gradcalls.c + + # Ensure that the function behaves the same; this is from SciPy 0.15.0 + assert_allclose(self.trace.t[50:52], + [[0.14687474, -0.5103282, 0.48252111], + [0.14474003, -0.5282084, 0.48743951]], + atol=1e-14, rtol=1e-7) + + def test_neldermead_initial_simplex_bad(self): + # Check it fails with a bad simplices + bad_simplices = [] + + simplex = np.zeros((3, 2)) + simplex[...] = self.startparams[:2] + for j in range(2): + simplex[j+1, j] += 0.1 + bad_simplices.append(simplex) + + simplex = np.zeros((3, 3)) + bad_simplices.append(simplex) + + for simplex in bad_simplices: + if self.use_wrapper: + opts = {'maxiter': self.maxiter, 'disp': False, + 'return_all': False, 'initial_simplex': simplex} + assert_raises(ValueError, + optimize.minimize, + self.func, + self.startparams, + args=(), + method='Nelder-mead', + options=opts) + else: + assert_raises(ValueError, optimize.fmin, + self.func, self.startparams, + args=(), maxiter=self.maxiter, + full_output=True, disp=False, retall=False, + initial_simplex=simplex) + + def test_neldermead_x0_ub(self): + # checks whether minimisation occurs correctly for entries where + # x0 == ub + # gh19991 + def quad(x): + return np.sum(x**2) + + res = optimize.minimize( + quad, + [1], + bounds=[(0, 1.)], + method='nelder-mead' + ) + assert_allclose(res.x, [0]) + + res = optimize.minimize( + quad, + [1, 2], + bounds=[(0, 1.), (1, 3.)], + method='nelder-mead' + ) + assert_allclose(res.x, [0, 1]) + + def test_ncg_negative_maxiter(self): + # Regression test for gh-8241 + opts = {'maxiter': -1} + result = optimize.minimize(self.func, self.startparams, + method='Newton-CG', jac=self.grad, + args=(), options=opts) + assert result.status == 1 + + def test_ncg_zero_xtol(self): + # Regression test for gh-20214 + def cosine(x): + return np.cos(x[0]) + + def jac(x): + return -np.sin(x[0]) + + x0 = [0.1] + xtol = 0 + result = optimize.minimize(cosine, + x0=x0, + jac=jac, + method="newton-cg", + options=dict(xtol=xtol)) + assert result.status == 0 + assert_almost_equal(result.x[0], np.pi) + + def test_ncg(self): + # line-search Newton conjugate gradient optimization routine + if self.use_wrapper: + opts = {'maxiter': self.maxiter, 'disp': self.disp, + 'return_all': False} + retval = optimize.minimize(self.func, self.startparams, + method='Newton-CG', jac=self.grad, + args=(), options=opts)['x'] + else: + retval = optimize.fmin_ncg(self.func, self.startparams, self.grad, + args=(), maxiter=self.maxiter, + full_output=False, disp=self.disp, + retall=False) + + params = retval + + assert_allclose(self.func(params), self.func(self.solution), + atol=1e-6) + + # Ensure that function call counts are 'known good'; these are from + # SciPy 0.7.0. Don't allow them to increase. + assert self.funccalls.c == 7, self.funccalls.c + assert self.gradcalls.c <= 22, self.gradcalls.c # 0.13.0 + # assert self.gradcalls <= 18, self.gradcalls # 0.9.0 + # assert self.gradcalls == 18, self.gradcalls # 0.8.0 + # assert self.gradcalls == 22, self.gradcalls # 0.7.0 + + # Ensure that the function behaves the same; this is from SciPy 0.7.0 + assert_allclose(self.trace.t[3:5], + [[-4.35700753e-07, -5.24869435e-01, 4.87527480e-01], + [-4.35700753e-07, -5.24869401e-01, 4.87527774e-01]], + atol=1e-6, rtol=1e-7) + + def test_ncg_hess(self): + # Newton conjugate gradient with Hessian + if self.use_wrapper: + opts = {'maxiter': self.maxiter, 'disp': self.disp, + 'return_all': False} + retval = optimize.minimize(self.func, self.startparams, + method='Newton-CG', jac=self.grad, + hess=self.hess, + args=(), options=opts)['x'] + else: + retval = optimize.fmin_ncg(self.func, self.startparams, self.grad, + fhess=self.hess, + args=(), maxiter=self.maxiter, + full_output=False, disp=self.disp, + retall=False) + + params = retval + + assert_allclose(self.func(params), self.func(self.solution), + atol=1e-6) + + # Ensure that function call counts are 'known good'; these are from + # SciPy 0.7.0. Don't allow them to increase. + assert self.funccalls.c <= 7, self.funccalls.c # gh10673 + assert self.gradcalls.c <= 18, self.gradcalls.c # 0.9.0 + # assert self.gradcalls == 18, self.gradcalls # 0.8.0 + # assert self.gradcalls == 22, self.gradcalls # 0.7.0 + + # Ensure that the function behaves the same; this is from SciPy 0.7.0 + assert_allclose(self.trace.t[3:5], + [[-4.35700753e-07, -5.24869435e-01, 4.87527480e-01], + [-4.35700753e-07, -5.24869401e-01, 4.87527774e-01]], + atol=1e-6, rtol=1e-7) + + def test_ncg_hessp(self): + # Newton conjugate gradient with Hessian times a vector p. + if self.use_wrapper: + opts = {'maxiter': self.maxiter, 'disp': self.disp, + 'return_all': False} + retval = optimize.minimize(self.func, self.startparams, + method='Newton-CG', jac=self.grad, + hessp=self.hessp, + args=(), options=opts)['x'] + else: + retval = optimize.fmin_ncg(self.func, self.startparams, self.grad, + fhess_p=self.hessp, + args=(), maxiter=self.maxiter, + full_output=False, disp=self.disp, + retall=False) + + params = retval + + assert_allclose(self.func(params), self.func(self.solution), + atol=1e-6) + + # Ensure that function call counts are 'known good'; these are from + # SciPy 0.7.0. Don't allow them to increase. + assert self.funccalls.c <= 7, self.funccalls.c # gh10673 + assert self.gradcalls.c <= 18, self.gradcalls.c # 0.9.0 + # assert self.gradcalls == 18, self.gradcalls # 0.8.0 + # assert self.gradcalls == 22, self.gradcalls # 0.7.0 + + # Ensure that the function behaves the same; this is from SciPy 0.7.0 + assert_allclose(self.trace.t[3:5], + [[-4.35700753e-07, -5.24869435e-01, 4.87527480e-01], + [-4.35700753e-07, -5.24869401e-01, 4.87527774e-01]], + atol=1e-6, rtol=1e-7) + + def test_cobyqa(self): + # COBYQA method. + if self.use_wrapper: + res = optimize.minimize( + self.func, + self.startparams, + method='cobyqa', + options={'maxiter': self.maxiter, 'disp': self.disp}, + ) + assert_allclose(res.fun, self.func(self.solution), atol=1e-6) + + # Ensure that function call counts are 'known good'; these are from + # SciPy 1.14.0. Don't allow them to increase. The exact evaluation + # count is sensitive to numerical error and floating-point + # computations are not bit-for-bit reproducible across machines. It + # takes 45 calls on my machine, but we can add the same +20 margin + # as is used in `test_powell` + assert self.funccalls.c <= 45 + 20, self.funccalls.c + + +def test_maxfev_test(): + rng = np.random.default_rng(271707100830272976862395227613146332411) + + def cost(x): + return rng.random(1) * 1000 # never converged problem + + for imaxfev in [1, 10, 50]: + # "TNC" and "L-BFGS-B" also supports max function evaluation, but + # these may violate the limit because of evaluating gradients + # by numerical differentiation. See the discussion in PR #14805. + for method in ['Powell', 'Nelder-Mead']: + result = optimize.minimize(cost, rng.random(10), + method=method, + options={'maxfev': imaxfev}) + assert result["nfev"] == imaxfev + + +def test_wrap_scalar_function_with_validation(): + + def func_(x): + return x + + fcalls, func = optimize._optimize.\ + _wrap_scalar_function_maxfun_validation(func_, np.asarray(1), 5) + + for i in range(5): + func(np.asarray(i)) + assert fcalls[0] == i+1 + + msg = "Too many function calls" + with assert_raises(optimize._optimize._MaxFuncCallError, match=msg): + func(np.asarray(i)) # exceeded maximum function call + + fcalls, func = optimize._optimize.\ + _wrap_scalar_function_maxfun_validation(func_, np.asarray(1), 5) + + msg = "The user-provided objective function must return a scalar value." + with assert_raises(ValueError, match=msg): + func(np.array([1, 1])) + + +def test_obj_func_returns_scalar(): + match = ("The user-provided " + "objective function must " + "return a scalar value.") + with assert_raises(ValueError, match=match): + optimize.minimize(lambda x: x, np.array([1, 1]), method='BFGS') + + +def test_neldermead_iteration_num(): + x0 = np.array([1.3, 0.7, 0.8, 1.9, 1.2]) + res = optimize._minimize._minimize_neldermead(optimize.rosen, x0, + xatol=1e-8) + assert res.nit <= 339 + + +def test_neldermead_respect_fp(): + # Nelder-Mead should respect the fp type of the input + function + x0 = np.array([5.0, 4.0]).astype(np.float32) + def rosen_(x): + assert x.dtype == np.float32 + return optimize.rosen(x) + + optimize.minimize(rosen_, x0, method='Nelder-Mead') + + +def test_neldermead_xatol_fatol(): + # gh4484 + # test we can call with fatol, xatol specified + def func(x): + return x[0] ** 2 + x[1] ** 2 + + optimize._minimize._minimize_neldermead(func, [1, 1], maxiter=2, + xatol=1e-3, fatol=1e-3) + + +def test_neldermead_adaptive(): + def func(x): + return np.sum(x ** 2) + p0 = [0.15746215, 0.48087031, 0.44519198, 0.4223638, 0.61505159, + 0.32308456, 0.9692297, 0.4471682, 0.77411992, 0.80441652, + 0.35994957, 0.75487856, 0.99973421, 0.65063887, 0.09626474] + + res = optimize.minimize(func, p0, method='Nelder-Mead') + assert_equal(res.success, False) + + res = optimize.minimize(func, p0, method='Nelder-Mead', + options={'adaptive': True}) + assert_equal(res.success, True) + + +@pytest.mark.thread_unsafe +def test_bounded_powell_outsidebounds(): + # With the bounded Powell method if you start outside the bounds the final + # should still be within the bounds (provided that the user doesn't make a + # bad choice for the `direc` argument). + def func(x): + return np.sum(x ** 2) + bounds = (-1, 1), (-1, 1), (-1, 1) + x0 = [-4, .5, -.8] + + # we're starting outside the bounds, so we should get a warning + with assert_warns(optimize.OptimizeWarning): + res = optimize.minimize(func, x0, bounds=bounds, method="Powell") + assert_allclose(res.x, np.array([0.] * len(x0)), atol=1e-6) + assert_equal(res.success, True) + assert_equal(res.status, 0) + + # However, now if we change the `direc` argument such that the + # set of vectors does not span the parameter space, then we may + # not end up back within the bounds. Here we see that the first + # parameter cannot be updated! + direc = [[0, 0, 0], [0, 1, 0], [0, 0, 1]] + # we're starting outside the bounds, so we should get a warning + with assert_warns(optimize.OptimizeWarning): + res = optimize.minimize(func, x0, + bounds=bounds, method="Powell", + options={'direc': direc}) + assert_allclose(res.x, np.array([-4., 0, 0]), atol=1e-6) + assert_equal(res.success, False) + assert_equal(res.status, 4) + + +@pytest.mark.thread_unsafe +def test_bounded_powell_vs_powell(): + # here we test an example where the bounded Powell method + # will return a different result than the standard Powell + # method. + + # first we test a simple example where the minimum is at + # the origin and the minimum that is within the bounds is + # larger than the minimum at the origin. + def func(x): + return np.sum(x ** 2) + bounds = (-5, -1), (-10, -0.1), (1, 9.2), (-4, 7.6), (-15.9, -2) + x0 = [-2.1, -5.2, 1.9, 0, -2] + + options = {'ftol': 1e-10, 'xtol': 1e-10} + + res_powell = optimize.minimize(func, x0, method="Powell", options=options) + assert_allclose(res_powell.x, 0., atol=1e-6) + assert_allclose(res_powell.fun, 0., atol=1e-6) + + res_bounded_powell = optimize.minimize(func, x0, options=options, + bounds=bounds, + method="Powell") + p = np.array([-1, -0.1, 1, 0, -2]) + assert_allclose(res_bounded_powell.x, p, atol=1e-6) + assert_allclose(res_bounded_powell.fun, func(p), atol=1e-6) + + # now we test bounded Powell but with a mix of inf bounds. + bounds = (None, -1), (-np.inf, -.1), (1, np.inf), (-4, None), (-15.9, -2) + res_bounded_powell = optimize.minimize(func, x0, options=options, + bounds=bounds, + method="Powell") + p = np.array([-1, -0.1, 1, 0, -2]) + assert_allclose(res_bounded_powell.x, p, atol=1e-6) + assert_allclose(res_bounded_powell.fun, func(p), atol=1e-6) + + # next we test an example where the global minimum is within + # the bounds, but the bounded Powell method performs better + # than the standard Powell method. + def func(x): + t = np.sin(-x[0]) * np.cos(x[1]) * np.sin(-x[0] * x[1]) * np.cos(x[1]) + t -= np.cos(np.sin(x[1] * x[2]) * np.cos(x[2])) + return t**2 + + bounds = [(-2, 5)] * 3 + x0 = [-0.5, -0.5, -0.5] + + res_powell = optimize.minimize(func, x0, method="Powell") + res_bounded_powell = optimize.minimize(func, x0, + bounds=bounds, + method="Powell") + assert_allclose(res_powell.fun, 0.007136253919761627, atol=1e-6) + assert_allclose(res_bounded_powell.fun, 0, atol=1e-6) + + # next we test the previous example where the we provide Powell + # with (-inf, inf) bounds, and compare it to providing Powell + # with no bounds. They should end up the same. + bounds = [(-np.inf, np.inf)] * 3 + + res_bounded_powell = optimize.minimize(func, x0, + bounds=bounds, + method="Powell") + assert_allclose(res_powell.fun, res_bounded_powell.fun, atol=1e-6) + assert_allclose(res_powell.nfev, res_bounded_powell.nfev, atol=1e-6) + assert_allclose(res_powell.x, res_bounded_powell.x, atol=1e-6) + + # now test when x0 starts outside of the bounds. + x0 = [45.46254415, -26.52351498, 31.74830248] + bounds = [(-2, 5)] * 3 + # we're starting outside the bounds, so we should get a warning + with assert_warns(optimize.OptimizeWarning): + res_bounded_powell = optimize.minimize(func, x0, + bounds=bounds, + method="Powell") + assert_allclose(res_bounded_powell.fun, 0, atol=1e-6) + + +def test_onesided_bounded_powell_stability(): + # When the Powell method is bounded on only one side, a + # np.tan transform is done in order to convert it into a + # completely bounded problem. Here we do some simple tests + # of one-sided bounded Powell where the optimal solutions + # are large to test the stability of the transformation. + kwargs = {'method': 'Powell', + 'bounds': [(-np.inf, 1e6)] * 3, + 'options': {'ftol': 1e-8, 'xtol': 1e-8}} + x0 = [1, 1, 1] + + # df/dx is constant. + def f(x): + return -np.sum(x) + res = optimize.minimize(f, x0, **kwargs) + assert_allclose(res.fun, -3e6, atol=1e-4) + + # df/dx gets smaller and smaller. + def f(x): + return -np.abs(np.sum(x)) ** (0.1) * (1 if np.all(x > 0) else -1) + + res = optimize.minimize(f, x0, **kwargs) + assert_allclose(res.fun, -(3e6) ** (0.1)) + + # df/dx gets larger and larger. + def f(x): + return -np.abs(np.sum(x)) ** 10 * (1 if np.all(x > 0) else -1) + + res = optimize.minimize(f, x0, **kwargs) + assert_allclose(res.fun, -(3e6) ** 10, rtol=1e-7) + + # df/dx gets larger for some of the variables and smaller for others. + def f(x): + t = -np.abs(np.sum(x[:2])) ** 5 - np.abs(np.sum(x[2:])) ** (0.1) + t *= (1 if np.all(x > 0) else -1) + return t + + kwargs['bounds'] = [(-np.inf, 1e3)] * 3 + res = optimize.minimize(f, x0, **kwargs) + assert_allclose(res.fun, -(2e3) ** 5 - (1e6) ** (0.1), rtol=1e-7) + + +class TestOptimizeWrapperDisp(CheckOptimizeParameterized): + use_wrapper = True + disp = True + + +class TestOptimizeWrapperNoDisp(CheckOptimizeParameterized): + use_wrapper = True + disp = False + + +class TestOptimizeNoWrapperDisp(CheckOptimizeParameterized): + use_wrapper = False + disp = True + + +class TestOptimizeNoWrapperNoDisp(CheckOptimizeParameterized): + use_wrapper = False + disp = False + + +class TestOptimizeSimple(CheckOptimize): + + def test_bfgs_nan(self): + # Test corner case where nan is fed to optimizer. See gh-2067. + def func(x): + return x + def fprime(x): + return np.ones_like(x) + x0 = [np.nan] + with np.errstate(over='ignore', invalid='ignore'): + x = optimize.fmin_bfgs(func, x0, fprime, disp=False) + assert np.isnan(func(x)) + + def test_bfgs_nan_return(self): + # Test corner cases where fun returns NaN. See gh-4793. + + # First case: NaN from first call. + def func(x): + return np.nan + with np.errstate(invalid='ignore'): + result = optimize.minimize(func, 0) + + assert np.isnan(result['fun']) + assert result['success'] is False + + # Second case: NaN from second call. + def func(x): + return 0 if x == 0 else np.nan + def fprime(x): + return np.ones_like(x) # Steer away from zero. + with np.errstate(invalid='ignore'): + result = optimize.minimize(func, 0, jac=fprime) + + assert np.isnan(result['fun']) + assert result['success'] is False + + def test_bfgs_numerical_jacobian(self): + # BFGS with numerical Jacobian and a vector epsilon parameter. + # define the epsilon parameter using a random vector + epsilon = np.sqrt(np.spacing(1.)) * np.random.rand(len(self.solution)) + + params = optimize.fmin_bfgs(self.func, self.startparams, + epsilon=epsilon, args=(), + maxiter=self.maxiter, disp=False) + + assert_allclose(self.func(params), self.func(self.solution), + atol=1e-6) + + def test_finite_differences_jac(self): + methods = ['BFGS', 'CG', 'TNC'] + jacs = ['2-point', '3-point', None] + for method, jac in itertools.product(methods, jacs): + result = optimize.minimize(self.func, self.startparams, + method=method, jac=jac) + assert_allclose(self.func(result.x), self.func(self.solution), + atol=1e-6) + + def test_finite_differences_hess(self): + # test that all the methods that require hess can use finite-difference + # For Newton-CG, trust-ncg, trust-krylov the FD estimated hessian is + # wrapped in a hessp function + # dogleg, trust-exact actually require true hessians at the moment, so + # they're excluded. + methods = ['trust-constr', 'Newton-CG', 'trust-ncg', 'trust-krylov'] + hesses = FD_METHODS + (optimize.BFGS,) + for method, hess in itertools.product(methods, hesses): + if hess is optimize.BFGS: + hess = hess() + result = optimize.minimize(self.func, self.startparams, + method=method, jac=self.grad, + hess=hess) + assert result.success + + # check that the methods demand some sort of Hessian specification + # Newton-CG creates its own hessp, and trust-constr doesn't need a hess + # specified either + methods = ['trust-ncg', 'trust-krylov', 'dogleg', 'trust-exact'] + for method in methods: + with pytest.raises(ValueError): + optimize.minimize(self.func, self.startparams, + method=method, jac=self.grad, + hess=None) + + def test_bfgs_gh_2169(self): + def f(x): + if x < 0: + return 1.79769313e+308 + else: + return x + 1./x + xs = optimize.fmin_bfgs(f, [10.], disp=False) + assert_allclose(xs, 1.0, rtol=1e-4, atol=1e-4) + + def test_bfgs_double_evaluations(self): + # check BFGS does not evaluate twice in a row at same point + def f(x): + xp = x[0] + assert xp not in seen + seen.add(xp) + return 10*x**2, 20*x + + seen = set() + optimize.minimize(f, -100, method='bfgs', jac=True, tol=1e-7) + + def test_l_bfgs_b(self): + # limited-memory bound-constrained BFGS algorithm + retval = optimize.fmin_l_bfgs_b(self.func, self.startparams, + self.grad, args=(), + maxiter=self.maxiter) + + (params, fopt, d) = retval + + assert_allclose(self.func(params), self.func(self.solution), + atol=1e-6) + + # Ensure that function call counts are 'known good'; these are from + # SciPy 0.7.0. Don't allow them to increase. + assert self.funccalls.c == 7, self.funccalls.c + assert self.gradcalls.c == 5, self.gradcalls.c + + # Ensure that the function behaves the same; this is from SciPy 0.7.0 + # test fixed in gh10673 + assert_allclose(self.trace.t[3:5], + [[8.117083e-16, -5.196198e-01, 4.897617e-01], + [0., -0.52489628, 0.48753042]], + atol=1e-14, rtol=1e-7) + + def test_l_bfgs_b_numjac(self): + # L-BFGS-B with numerical Jacobian + retval = optimize.fmin_l_bfgs_b(self.func, self.startparams, + approx_grad=True, + maxiter=self.maxiter) + + (params, fopt, d) = retval + + assert_allclose(self.func(params), self.func(self.solution), + atol=1e-6) + + def test_l_bfgs_b_funjac(self): + # L-BFGS-B with combined objective function and Jacobian + def fun(x): + return self.func(x), self.grad(x) + + retval = optimize.fmin_l_bfgs_b(fun, self.startparams, + maxiter=self.maxiter) + + (params, fopt, d) = retval + + assert_allclose(self.func(params), self.func(self.solution), + atol=1e-6) + + def test_l_bfgs_b_maxiter(self): + # gh7854 + # Ensure that not more than maxiters are ever run. + class Callback: + def __init__(self): + self.nit = 0 + self.fun = None + self.x = None + + def __call__(self, x): + self.x = x + self.fun = optimize.rosen(x) + self.nit += 1 + + c = Callback() + res = optimize.minimize(optimize.rosen, [0., 0.], method='l-bfgs-b', + callback=c, options={'maxiter': 5}) + + assert_equal(res.nit, 5) + assert_almost_equal(res.x, c.x) + assert_almost_equal(res.fun, c.fun) + assert_equal(res.status, 1) + assert res.success is False + assert_equal(res.message, + 'STOP: TOTAL NO. OF ITERATIONS REACHED LIMIT') + + def test_minimize_l_bfgs_b(self): + # Minimize with L-BFGS-B method + opts = {'disp': False, 'maxiter': self.maxiter} + r = optimize.minimize(self.func, self.startparams, + method='L-BFGS-B', jac=self.grad, + options=opts) + assert_allclose(self.func(r.x), self.func(self.solution), + atol=1e-6) + assert self.gradcalls.c == r.njev + + self.funccalls.c = self.gradcalls.c = 0 + # approximate jacobian + ra = optimize.minimize(self.func, self.startparams, + method='L-BFGS-B', options=opts) + # check that function evaluations in approximate jacobian are counted + # assert_(ra.nfev > r.nfev) + assert self.funccalls.c == ra.nfev + assert_allclose(self.func(ra.x), self.func(self.solution), + atol=1e-6) + + self.funccalls.c = self.gradcalls.c = 0 + # approximate jacobian + ra = optimize.minimize(self.func, self.startparams, jac='3-point', + method='L-BFGS-B', options=opts) + assert self.funccalls.c == ra.nfev + assert_allclose(self.func(ra.x), self.func(self.solution), + atol=1e-6) + + def test_minimize_l_bfgs_b_ftol(self): + # Check that the `ftol` parameter in l_bfgs_b works as expected + v0 = None + for tol in [1e-1, 1e-4, 1e-7, 1e-10]: + opts = {'disp': False, 'maxiter': self.maxiter, 'ftol': tol} + sol = optimize.minimize(self.func, self.startparams, + method='L-BFGS-B', jac=self.grad, + options=opts) + v = self.func(sol.x) + + if v0 is None: + v0 = v + else: + assert v < v0 + + assert_allclose(v, self.func(self.solution), rtol=tol) + + def test_minimize_l_bfgs_maxls(self): + # check that the maxls is passed down to the Fortran routine + sol = optimize.minimize(optimize.rosen, np.array([-1.2, 1.0]), + method='L-BFGS-B', jac=optimize.rosen_der, + options={'disp': False, 'maxls': 1}) + assert not sol.success + + def test_minimize_l_bfgs_b_maxfun_interruption(self): + # gh-6162 + f = optimize.rosen + g = optimize.rosen_der + values = [] + x0 = np.full(7, 1000) + + def objfun(x): + value = f(x) + values.append(value) + return value + + # Look for an interesting test case. + # Request a maxfun that stops at a particularly bad function + # evaluation somewhere between 100 and 300 evaluations. + low, medium, high = 30, 100, 300 + optimize.fmin_l_bfgs_b(objfun, x0, fprime=g, maxfun=high) + v, k = max((y, i) for i, y in enumerate(values[medium:])) + maxfun = medium + k + # If the minimization strategy is reasonable, + # the minimize() result should not be worse than the best + # of the first 30 function evaluations. + target = min(values[:low]) + xmin, fmin, d = optimize.fmin_l_bfgs_b(f, x0, fprime=g, maxfun=maxfun) + assert_array_less(fmin, target) + + def test_custom(self): + # This function comes from the documentation example. + def custmin(fun, x0, args=(), maxfev=None, stepsize=0.1, + maxiter=100, callback=None, **options): + bestx = x0 + besty = fun(x0) + funcalls = 1 + niter = 0 + improved = True + stop = False + + while improved and not stop and niter < maxiter: + improved = False + niter += 1 + for dim in range(np.size(x0)): + for s in [bestx[dim] - stepsize, bestx[dim] + stepsize]: + testx = np.copy(bestx) + testx[dim] = s + testy = fun(testx, *args) + funcalls += 1 + if testy < besty: + besty = testy + bestx = testx + improved = True + if callback is not None: + callback(bestx) + if maxfev is not None and funcalls >= maxfev: + stop = True + break + + return optimize.OptimizeResult(fun=besty, x=bestx, nit=niter, + nfev=funcalls, success=(niter > 1)) + + x0 = [1.35, 0.9, 0.8, 1.1, 1.2] + res = optimize.minimize(optimize.rosen, x0, method=custmin, + options=dict(stepsize=0.05)) + assert_allclose(res.x, 1.0, rtol=1e-4, atol=1e-4) + + def test_gh10771(self): + # check that minimize passes bounds and constraints to a custom + # minimizer without altering them. + bounds = [(-2, 2), (0, 3)] + constraints = 'constraints' + + def custmin(fun, x0, **options): + assert options['bounds'] is bounds + assert options['constraints'] is constraints + return optimize.OptimizeResult() + + x0 = [1, 1] + optimize.minimize(optimize.rosen, x0, method=custmin, + bounds=bounds, constraints=constraints) + + def test_minimize_tol_parameter(self): + # Check that the minimize() tol= argument does something + def func(z): + x, y = z + return x**2*y**2 + x**4 + 1 + + def dfunc(z): + x, y = z + return np.array([2*x*y**2 + 4*x**3, 2*x**2*y]) + + for method in ['nelder-mead', 'powell', 'cg', 'bfgs', + 'newton-cg', 'l-bfgs-b', 'tnc', + 'cobyla', 'cobyqa', 'slsqp']: + if method in ('nelder-mead', 'powell', 'cobyla', 'cobyqa'): + jac = None + else: + jac = dfunc + + sol1 = optimize.minimize(func, [2, 2], jac=jac, tol=1e-10, + method=method) + sol2 = optimize.minimize(func, [2, 2], jac=jac, tol=1.0, + method=method) + assert func(sol1.x) < func(sol2.x), \ + f"{method}: {func(sol1.x)} vs. {func(sol2.x)}" + + @pytest.mark.fail_slow(10) + @pytest.mark.filterwarnings('ignore::UserWarning') + @pytest.mark.filterwarnings('ignore::RuntimeWarning') # See gh-18547 + @pytest.mark.parametrize('method', + ['fmin', 'fmin_powell', 'fmin_cg', 'fmin_bfgs', + 'fmin_ncg', 'fmin_l_bfgs_b', 'fmin_tnc', + 'fmin_slsqp'] + MINIMIZE_METHODS) + def test_minimize_callback_copies_array(self, method): + # Check that arrays passed to callbacks are not modified + # inplace by the optimizer afterward + + if method in ('fmin_tnc', 'fmin_l_bfgs_b'): + def func(x): + return optimize.rosen(x), optimize.rosen_der(x) + else: + func = optimize.rosen + jac = optimize.rosen_der + hess = optimize.rosen_hess + + x0 = np.zeros(10) + + # Set options + kwargs = {} + if method.startswith('fmin'): + routine = getattr(optimize, method) + if method == 'fmin_slsqp': + kwargs['iter'] = 5 + elif method == 'fmin_tnc': + kwargs['maxfun'] = 100 + elif method in ('fmin', 'fmin_powell'): + kwargs['maxiter'] = 3500 + else: + kwargs['maxiter'] = 5 + else: + def routine(*a, **kw): + kw['method'] = method + return optimize.minimize(*a, **kw) + + if method == 'tnc': + kwargs['options'] = dict(maxfun=100) + else: + kwargs['options'] = dict(maxiter=5) + + if method in ('fmin_ncg',): + kwargs['fprime'] = jac + elif method in ('newton-cg',): + kwargs['jac'] = jac + elif method in ('trust-krylov', 'trust-exact', 'trust-ncg', 'dogleg', + 'trust-constr'): + kwargs['jac'] = jac + kwargs['hess'] = hess + + # Run with callback + results = [] + + def callback(x, *args, **kwargs): + assert not isinstance(x, optimize.OptimizeResult) + results.append((x, np.copy(x))) + + routine(func, x0, callback=callback, **kwargs) + + # Check returned arrays coincide with their copies + # and have no memory overlap + assert len(results) > 2 + assert all(np.all(x == y) for x, y in results) + combinations = itertools.combinations(results, 2) + assert not any(np.may_share_memory(x[0], y[0]) for x, y in combinations) + + @pytest.mark.parametrize('method', ['nelder-mead', 'powell', 'cg', + 'bfgs', 'newton-cg', 'l-bfgs-b', + 'tnc', 'cobyla', 'cobyqa', 'slsqp']) + def test_no_increase(self, method): + # Check that the solver doesn't return a value worse than the + # initial point. + + def func(x): + return (x - 1)**2 + + def bad_grad(x): + # purposefully invalid gradient function, simulates a case + # where line searches start failing + return 2*(x - 1) * (-1) - 2 + + x0 = np.array([2.0]) + f0 = func(x0) + jac = bad_grad + options = dict(maxfun=20) if method == 'tnc' else dict(maxiter=20) + if method in ['nelder-mead', 'powell', 'cobyla', 'cobyqa']: + jac = None + sol = optimize.minimize(func, x0, jac=jac, method=method, + options=options) + assert_equal(func(sol.x), sol.fun) + + if method == 'slsqp': + pytest.xfail("SLSQP returns slightly worse") + assert func(sol.x) <= f0 + + def test_slsqp_respect_bounds(self): + # Regression test for gh-3108 + def f(x): + return sum((x - np.array([1., 2., 3., 4.]))**2) + + def cons(x): + a = np.array([[-1, -1, -1, -1], [-3, -3, -2, -1]]) + return np.concatenate([np.dot(a, x) + np.array([5, 10]), x]) + + x0 = np.array([0.5, 1., 1.5, 2.]) + res = optimize.minimize(f, x0, method='slsqp', + constraints={'type': 'ineq', 'fun': cons}) + assert_allclose(res.x, np.array([0., 2, 5, 8])/3, atol=1e-12) + + @pytest.mark.parametrize('method', ['Nelder-Mead', 'Powell', 'CG', 'BFGS', + 'Newton-CG', 'L-BFGS-B', 'SLSQP', + 'trust-constr', 'dogleg', 'trust-ncg', + 'trust-exact', 'trust-krylov', + 'cobyqa']) + def test_respect_maxiter(self, method): + # Check that the number of iterations equals max_iter, assuming + # convergence doesn't establish before + MAXITER = 4 + + x0 = np.zeros(10) + + sf = ScalarFunction(optimize.rosen, x0, (), optimize.rosen_der, + optimize.rosen_hess, None, None) + + # Set options + kwargs = {'method': method, 'options': dict(maxiter=MAXITER)} + + if method in ('Newton-CG',): + kwargs['jac'] = sf.grad + elif method in ('trust-krylov', 'trust-exact', 'trust-ncg', 'dogleg', + 'trust-constr'): + kwargs['jac'] = sf.grad + kwargs['hess'] = sf.hess + + sol = optimize.minimize(sf.fun, x0, **kwargs) + assert sol.nit == MAXITER + assert sol.nfev >= sf.nfev + if hasattr(sol, 'njev'): + assert sol.njev >= sf.ngev + + # method specific tests + if method == 'SLSQP': + assert sol.status == 9 # Iteration limit reached + elif method == 'cobyqa': + assert sol.status == 6 # Iteration limit reached + + @pytest.mark.thread_unsafe + @pytest.mark.parametrize('method', ['Nelder-Mead', 'Powell', + 'fmin', 'fmin_powell']) + def test_runtime_warning(self, method): + x0 = np.zeros(10) + sf = ScalarFunction(optimize.rosen, x0, (), optimize.rosen_der, + optimize.rosen_hess, None, None) + options = {"maxiter": 1, "disp": True} + with pytest.warns(RuntimeWarning, + match=r'Maximum number of iterations'): + if method.startswith('fmin'): + routine = getattr(optimize, method) + routine(sf.fun, x0, **options) + else: + optimize.minimize(sf.fun, x0, method=method, options=options) + + def test_respect_maxiter_trust_constr_ineq_constraints(self): + # special case of minimization with trust-constr and inequality + # constraints to check maxiter limit is obeyed when using internal + # method 'tr_interior_point' + MAXITER = 4 + f = optimize.rosen + jac = optimize.rosen_der + hess = optimize.rosen_hess + + def fun(x): + return np.array([0.2 * x[0] - 0.4 * x[1] - 0.33 * x[2]]) + cons = ({'type': 'ineq', + 'fun': fun},) + + x0 = np.zeros(10) + sol = optimize.minimize(f, x0, constraints=cons, jac=jac, hess=hess, + method='trust-constr', + options=dict(maxiter=MAXITER)) + assert sol.nit == MAXITER + + def test_minimize_automethod(self): + def f(x): + return x**2 + + def cons(x): + return x - 2 + + x0 = np.array([10.]) + sol_0 = optimize.minimize(f, x0) + sol_1 = optimize.minimize(f, x0, constraints=[{'type': 'ineq', + 'fun': cons}]) + sol_2 = optimize.minimize(f, x0, bounds=[(5, 10)]) + sol_3 = optimize.minimize(f, x0, + constraints=[{'type': 'ineq', 'fun': cons}], + bounds=[(5, 10)]) + sol_4 = optimize.minimize(f, x0, + constraints=[{'type': 'ineq', 'fun': cons}], + bounds=[(1, 10)]) + for sol in [sol_0, sol_1, sol_2, sol_3, sol_4]: + assert sol.success + assert_allclose(sol_0.x, 0, atol=1e-7) + assert_allclose(sol_1.x, 2, atol=1e-7) + assert_allclose(sol_2.x, 5, atol=1e-7) + assert_allclose(sol_3.x, 5, atol=1e-7) + assert_allclose(sol_4.x, 2, atol=1e-7) + + def test_minimize_coerce_args_param(self): + # Regression test for gh-3503 + def Y(x, c): + return np.sum((x-c)**2) + + def dY_dx(x, c=None): + return 2*(x-c) + + c = np.array([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]) + xinit = np.random.randn(len(c)) + optimize.minimize(Y, xinit, jac=dY_dx, args=(c), method="BFGS") + + def test_initial_step_scaling(self): + # Check that optimizer initial step is not huge even if the + # function and gradients are + + scales = [1e-50, 1, 1e50] + methods = ['CG', 'BFGS', 'L-BFGS-B', 'Newton-CG'] + + def f(x): + if first_step_size[0] is None and x[0] != x0[0]: + first_step_size[0] = abs(x[0] - x0[0]) + if abs(x).max() > 1e4: + raise AssertionError("Optimization stepped far away!") + return scale*(x[0] - 1)**2 + + def g(x): + return np.array([scale*(x[0] - 1)]) + + for scale, method in itertools.product(scales, methods): + if method in ('CG', 'BFGS'): + options = dict(gtol=scale*1e-8) + else: + options = dict() + + if scale < 1e-10 and method in ('L-BFGS-B', 'Newton-CG'): + # XXX: return initial point if they see small gradient + continue + + x0 = [-1.0] + first_step_size = [None] + res = optimize.minimize(f, x0, jac=g, method=method, + options=options) + + err_msg = f"{method} {scale}: {first_step_size}: {res}" + + assert res.success, err_msg + assert_allclose(res.x, [1.0], err_msg=err_msg) + assert res.nit <= 3, err_msg + + if scale > 1e-10: + if method in ('CG', 'BFGS'): + assert_allclose(first_step_size[0], 1.01, err_msg=err_msg) + else: + # Newton-CG and L-BFGS-B use different logic for the first + # step, but are both scaling invariant with step sizes ~ 1 + assert first_step_size[0] > 0.5 and first_step_size[0] < 3, err_msg + else: + # step size has upper bound of ||grad||, so line + # search makes many small steps + pass + + @pytest.mark.parametrize('method', ['nelder-mead', 'powell', 'cg', 'bfgs', + 'newton-cg', 'l-bfgs-b', 'tnc', + 'cobyla', 'cobyqa', 'slsqp', + 'trust-constr', 'dogleg', 'trust-ncg', + 'trust-exact', 'trust-krylov']) + def test_nan_values(self, method, num_parallel_threads): + if num_parallel_threads > 1 and method == 'cobyqa': + pytest.skip('COBYQA does not support concurrent execution') + + # Check nan values result to failed exit status + rng = np.random.RandomState(1234) + + count = [0] + + def func(x): + return np.nan + + def func2(x): + count[0] += 1 + if count[0] > 2: + return np.nan + else: + return rng.rand() + + def grad(x): + return np.array([1.0]) + + def hess(x): + return np.array([[1.0]]) + + x0 = np.array([1.0]) + + needs_grad = method in ('newton-cg', 'trust-krylov', 'trust-exact', + 'trust-ncg', 'dogleg') + needs_hess = method in ('trust-krylov', 'trust-exact', 'trust-ncg', + 'dogleg') + + funcs = [func, func2] + grads = [grad] if needs_grad else [grad, None] + hesss = [hess] if needs_hess else [hess, None] + options = dict(maxfun=20) if method == 'tnc' else dict(maxiter=20) + + with np.errstate(invalid='ignore'), suppress_warnings() as sup: + sup.filter(UserWarning, "delta_grad == 0.*") + sup.filter(RuntimeWarning, ".*does not use Hessian.*") + sup.filter(RuntimeWarning, ".*does not use gradient.*") + + for f, g, h in itertools.product(funcs, grads, hesss): + count = [0] + sol = optimize.minimize(f, x0, jac=g, hess=h, method=method, + options=options) + assert_equal(sol.success, False) + + @pytest.mark.parametrize('method', ['nelder-mead', 'cg', 'bfgs', + 'l-bfgs-b', 'tnc', + 'cobyla', 'cobyqa', 'slsqp', + 'trust-constr', 'dogleg', 'trust-ncg', + 'trust-exact', 'trust-krylov']) + def test_duplicate_evaluations(self, method): + # check that there are no duplicate evaluations for any methods + jac = hess = None + if method in ('newton-cg', 'trust-krylov', 'trust-exact', + 'trust-ncg', 'dogleg'): + jac = self.grad + if method in ('trust-krylov', 'trust-exact', 'trust-ncg', + 'dogleg'): + hess = self.hess + + with np.errstate(invalid='ignore'), suppress_warnings() as sup: + # for trust-constr + sup.filter(UserWarning, "delta_grad == 0.*") + optimize.minimize(self.func, self.startparams, + method=method, jac=jac, hess=hess) + + for i in range(1, len(self.trace.t)): + if np.array_equal(self.trace.t[i - 1], self.trace.t[i]): + raise RuntimeError( + f"Duplicate evaluations made by {method}") + + @pytest.mark.filterwarnings('ignore::RuntimeWarning') + @pytest.mark.parametrize('method', MINIMIZE_METHODS_NEW_CB) + @pytest.mark.parametrize('new_cb_interface', [0, 1, 2]) + def test_callback_stopiteration(self, method, new_cb_interface): + # Check that if callback raises StopIteration, optimization + # terminates with the same result as if iterations were limited + + def f(x): + f.flag = False # check that f isn't called after StopIteration + return optimize.rosen(x) + f.flag = False + + def g(x): + f.flag = False + return optimize.rosen_der(x) + + def h(x): + f.flag = False + return optimize.rosen_hess(x) + + maxiter = 5 + + if new_cb_interface == 1: + def callback_interface(*, intermediate_result): + assert intermediate_result.fun == f(intermediate_result.x) + callback() + elif new_cb_interface == 2: + class Callback: + def __call__(self, intermediate_result: OptimizeResult): + assert intermediate_result.fun == f(intermediate_result.x) + callback() + callback_interface = Callback() + else: + def callback_interface(xk, *args): # type: ignore[misc] + callback() + + def callback(): + callback.i += 1 + callback.flag = False + if callback.i == maxiter: + callback.flag = True + raise StopIteration() + callback.i = 0 + callback.flag = False + + kwargs = {'x0': [1.1]*5, 'method': method, + 'fun': f, 'jac': g, 'hess': h} + + res = optimize.minimize(**kwargs, callback=callback_interface) + if method == 'nelder-mead': + maxiter = maxiter + 1 # nelder-mead counts differently + if method == 'cobyqa': + ref = optimize.minimize(**kwargs, options={'maxfev': maxiter}) + assert res.nfev == ref.nfev == maxiter + else: + ref = optimize.minimize(**kwargs, options={'maxiter': maxiter}) + assert res.nit == ref.nit == maxiter + assert res.fun == ref.fun + assert_equal(res.x, ref.x) + assert res.status == (3 if method in [ + 'trust-constr', + 'cobyqa', + ] else 99) + + def test_ndim_error(self): + msg = "'x0' must only have one dimension." + with assert_raises(ValueError, match=msg): + optimize.minimize(lambda x: x, np.ones((2, 1))) + + @pytest.mark.parametrize('method', ('nelder-mead', 'l-bfgs-b', 'tnc', + 'powell', 'cobyla', 'cobyqa', + 'trust-constr')) + def test_minimize_invalid_bounds(self, method): + def f(x): + return np.sum(x**2) + + bounds = Bounds([1, 2], [3, 4]) + msg = 'The number of bounds is not compatible with the length of `x0`.' + with pytest.raises(ValueError, match=msg): + optimize.minimize(f, x0=[1, 2, 3], method=method, bounds=bounds) + + bounds = Bounds([1, 6, 1], [3, 4, 2]) + msg = 'An upper bound is less than the corresponding lower bound.' + with pytest.raises(ValueError, match=msg): + optimize.minimize(f, x0=[1, 2, 3], method=method, bounds=bounds) + + @pytest.mark.thread_unsafe + @pytest.mark.parametrize('method', ['bfgs', 'cg', 'newton-cg', 'powell']) + def test_minimize_warnings_gh1953(self, method): + # test that minimize methods produce warnings rather than just using + # `print`; see gh-1953. + kwargs = {} if method=='powell' else {'jac': optimize.rosen_der} + warning_type = (RuntimeWarning if method=='powell' + else optimize.OptimizeWarning) + + options = {'disp': True, 'maxiter': 10} + with pytest.warns(warning_type, match='Maximum number'): + optimize.minimize(lambda x: optimize.rosen(x), [0, 0], + method=method, options=options, **kwargs) + + options['disp'] = False + optimize.minimize(lambda x: optimize.rosen(x), [0, 0], + method=method, options=options, **kwargs) + + +@pytest.mark.parametrize( + 'method', + ['l-bfgs-b', 'tnc', 'Powell', 'Nelder-Mead', 'cobyqa'] +) +def test_minimize_with_scalar(method): + # checks that minimize works with a scalar being provided to it. + def f(x): + return np.sum(x ** 2) + + res = optimize.minimize(f, 17, bounds=[(-100, 100)], method=method) + assert res.success + assert_allclose(res.x, [0.0], atol=1e-5) + + +class TestLBFGSBBounds: + def setup_method(self): + self.bounds = ((1, None), (None, None)) + self.solution = (1, 0) + + def fun(self, x, p=2.0): + return 1.0 / p * (x[0]**p + x[1]**p) + + def jac(self, x, p=2.0): + return x**(p - 1) + + def fj(self, x, p=2.0): + return self.fun(x, p), self.jac(x, p) + + def test_l_bfgs_b_bounds(self): + x, f, d = optimize.fmin_l_bfgs_b(self.fun, [0, -1], + fprime=self.jac, + bounds=self.bounds) + assert d['warnflag'] == 0, d['task'] + assert_allclose(x, self.solution, atol=1e-6) + + def test_l_bfgs_b_funjac(self): + # L-BFGS-B with fun and jac combined and extra arguments + x, f, d = optimize.fmin_l_bfgs_b(self.fj, [0, -1], args=(2.0, ), + bounds=self.bounds) + assert d['warnflag'] == 0, d['task'] + assert_allclose(x, self.solution, atol=1e-6) + + def test_minimize_l_bfgs_b_bounds(self): + # Minimize with method='L-BFGS-B' with bounds + res = optimize.minimize(self.fun, [0, -1], method='L-BFGS-B', + jac=self.jac, bounds=self.bounds) + assert res['success'], res['message'] + assert_allclose(res.x, self.solution, atol=1e-6) + + @pytest.mark.parametrize('bounds', [ + ([(10, 1), (1, 10)]), + ([(1, 10), (10, 1)]), + ([(10, 1), (10, 1)]) + ]) + def test_minimize_l_bfgs_b_incorrect_bounds(self, bounds): + with pytest.raises(ValueError, match='.*bound.*'): + optimize.minimize(self.fun, [0, -1], method='L-BFGS-B', + jac=self.jac, bounds=bounds) + + def test_minimize_l_bfgs_b_bounds_FD(self): + # test that initial starting value outside bounds doesn't raise + # an error (done with clipping). + # test all different finite differences combos, with and without args + + jacs = ['2-point', '3-point', None] + argss = [(2.,), ()] + for jac, args in itertools.product(jacs, argss): + res = optimize.minimize(self.fun, [0, -1], args=args, + method='L-BFGS-B', + jac=jac, bounds=self.bounds, + options={'finite_diff_rel_step': None}) + assert res['success'], res['message'] + assert_allclose(res.x, self.solution, atol=1e-6) + + +class TestOptimizeScalar: + def setup_method(self): + self.solution = 1.5 + + def fun(self, x, a=1.5): + """Objective function""" + return (x - a)**2 - 0.8 + + def test_brent(self): + x = optimize.brent(self.fun) + assert_allclose(x, self.solution, atol=1e-6) + + x = optimize.brent(self.fun, brack=(-3, -2)) + assert_allclose(x, self.solution, atol=1e-6) + + x = optimize.brent(self.fun, full_output=True) + assert_allclose(x[0], self.solution, atol=1e-6) + + x = optimize.brent(self.fun, brack=(-15, -1, 15)) + assert_allclose(x, self.solution, atol=1e-6) + + message = r"\(f\(xb\) < f\(xa\)\) and \(f\(xb\) < f\(xc\)\)" + with pytest.raises(ValueError, match=message): + optimize.brent(self.fun, brack=(-1, 0, 1)) + + message = r"\(xa < xb\) and \(xb < xc\)" + with pytest.raises(ValueError, match=message): + optimize.brent(self.fun, brack=(0, -1, 1)) + + @pytest.mark.filterwarnings('ignore::UserWarning') + def test_golden(self): + x = optimize.golden(self.fun) + assert_allclose(x, self.solution, atol=1e-6) + + x = optimize.golden(self.fun, brack=(-3, -2)) + assert_allclose(x, self.solution, atol=1e-6) + + x = optimize.golden(self.fun, full_output=True) + assert_allclose(x[0], self.solution, atol=1e-6) + + x = optimize.golden(self.fun, brack=(-15, -1, 15)) + assert_allclose(x, self.solution, atol=1e-6) + + x = optimize.golden(self.fun, tol=0) + assert_allclose(x, self.solution) + + maxiter_test_cases = [0, 1, 5] + for maxiter in maxiter_test_cases: + x0 = optimize.golden(self.fun, maxiter=0, full_output=True) + x = optimize.golden(self.fun, maxiter=maxiter, full_output=True) + nfev0, nfev = x0[2], x[2] + assert_equal(nfev - nfev0, maxiter) + + message = r"\(f\(xb\) < f\(xa\)\) and \(f\(xb\) < f\(xc\)\)" + with pytest.raises(ValueError, match=message): + optimize.golden(self.fun, brack=(-1, 0, 1)) + + message = r"\(xa < xb\) and \(xb < xc\)" + with pytest.raises(ValueError, match=message): + optimize.golden(self.fun, brack=(0, -1, 1)) + + def test_fminbound(self): + x = optimize.fminbound(self.fun, 0, 1) + assert_allclose(x, 1, atol=1e-4) + + x = optimize.fminbound(self.fun, 1, 5) + assert_allclose(x, self.solution, atol=1e-6) + + x = optimize.fminbound(self.fun, np.array([1]), np.array([5])) + assert_allclose(x, self.solution, atol=1e-6) + assert_raises(ValueError, optimize.fminbound, self.fun, 5, 1) + + def test_fminbound_scalar(self): + with pytest.raises(ValueError, match='.*must be finite scalars.*'): + optimize.fminbound(self.fun, np.zeros((1, 2)), 1) + + x = optimize.fminbound(self.fun, 1, np.array(5)) + assert_allclose(x, self.solution, atol=1e-6) + + def test_gh11207(self): + def fun(x): + return x**2 + optimize.fminbound(fun, 0, 0) + + def test_minimize_scalar(self): + # combine all tests above for the minimize_scalar wrapper + x = optimize.minimize_scalar(self.fun).x + assert_allclose(x, self.solution, atol=1e-6) + + x = optimize.minimize_scalar(self.fun, method='Brent') + assert x.success + + x = optimize.minimize_scalar(self.fun, method='Brent', + options=dict(maxiter=3)) + assert not x.success + + x = optimize.minimize_scalar(self.fun, bracket=(-3, -2), + args=(1.5, ), method='Brent').x + assert_allclose(x, self.solution, atol=1e-6) + + x = optimize.minimize_scalar(self.fun, method='Brent', + args=(1.5,)).x + assert_allclose(x, self.solution, atol=1e-6) + + x = optimize.minimize_scalar(self.fun, bracket=(-15, -1, 15), + args=(1.5, ), method='Brent').x + assert_allclose(x, self.solution, atol=1e-6) + + x = optimize.minimize_scalar(self.fun, bracket=(-3, -2), + args=(1.5, ), method='golden').x + assert_allclose(x, self.solution, atol=1e-6) + + x = optimize.minimize_scalar(self.fun, method='golden', + args=(1.5,)).x + assert_allclose(x, self.solution, atol=1e-6) + + x = optimize.minimize_scalar(self.fun, bracket=(-15, -1, 15), + args=(1.5, ), method='golden').x + assert_allclose(x, self.solution, atol=1e-6) + + x = optimize.minimize_scalar(self.fun, bounds=(0, 1), args=(1.5,), + method='Bounded').x + assert_allclose(x, 1, atol=1e-4) + + x = optimize.minimize_scalar(self.fun, bounds=(1, 5), args=(1.5, ), + method='bounded').x + assert_allclose(x, self.solution, atol=1e-6) + + x = optimize.minimize_scalar(self.fun, bounds=(np.array([1]), + np.array([5])), + args=(np.array([1.5]), ), + method='bounded').x + assert_allclose(x, self.solution, atol=1e-6) + + assert_raises(ValueError, optimize.minimize_scalar, self.fun, + bounds=(5, 1), method='bounded', args=(1.5, )) + + assert_raises(ValueError, optimize.minimize_scalar, self.fun, + bounds=(np.zeros(2), 1), method='bounded', args=(1.5, )) + + x = optimize.minimize_scalar(self.fun, bounds=(1, np.array(5)), + method='bounded').x + assert_allclose(x, self.solution, atol=1e-6) + + def test_minimize_scalar_custom(self): + # This function comes from the documentation example. + def custmin(fun, bracket, args=(), maxfev=None, stepsize=0.1, + maxiter=100, callback=None, **options): + bestx = (bracket[1] + bracket[0]) / 2.0 + besty = fun(bestx) + funcalls = 1 + niter = 0 + improved = True + stop = False + + while improved and not stop and niter < maxiter: + improved = False + niter += 1 + for testx in [bestx - stepsize, bestx + stepsize]: + testy = fun(testx, *args) + funcalls += 1 + if testy < besty: + besty = testy + bestx = testx + improved = True + if callback is not None: + callback(bestx) + if maxfev is not None and funcalls >= maxfev: + stop = True + break + + return optimize.OptimizeResult(fun=besty, x=bestx, nit=niter, + nfev=funcalls, success=(niter > 1)) + + res = optimize.minimize_scalar(self.fun, bracket=(0, 4), + method=custmin, + options=dict(stepsize=0.05)) + assert_allclose(res.x, self.solution, atol=1e-6) + + def test_minimize_scalar_coerce_args_param(self): + # Regression test for gh-3503 + optimize.minimize_scalar(self.fun, args=1.5) + + @pytest.mark.parametrize('method', ['brent', 'bounded', 'golden']) + def test_disp(self, method): + # test that all minimize_scalar methods accept a disp option. + for disp in [0, 1, 2, 3]: + optimize.minimize_scalar(self.fun, options={"disp": disp}) + + @pytest.mark.parametrize('method', ['brent', 'bounded', 'golden']) + def test_result_attributes(self, method): + kwargs = {"bounds": [-10, 10]} if method == 'bounded' else {} + result = optimize.minimize_scalar(self.fun, method=method, **kwargs) + assert hasattr(result, "x") + assert hasattr(result, "success") + assert hasattr(result, "message") + assert hasattr(result, "fun") + assert hasattr(result, "nfev") + assert hasattr(result, "nit") + + @pytest.mark.filterwarnings('ignore::UserWarning') + @pytest.mark.parametrize('method', ['brent', 'bounded', 'golden']) + def test_nan_values(self, method): + # Check nan values result to failed exit status + np.random.seed(1234) + + count = [0] + + def func(x): + count[0] += 1 + if count[0] > 4: + return np.nan + else: + return x**2 + 0.1 * np.sin(x) + + bracket = (-1, 0, 1) + bounds = (-1, 1) + + with np.errstate(invalid='ignore'), suppress_warnings() as sup: + sup.filter(UserWarning, "delta_grad == 0.*") + sup.filter(RuntimeWarning, ".*does not use Hessian.*") + sup.filter(RuntimeWarning, ".*does not use gradient.*") + + count = [0] + + kwargs = {"bounds": bounds} if method == 'bounded' else {} + sol = optimize.minimize_scalar(func, bracket=bracket, + **kwargs, method=method, + options=dict(maxiter=20)) + assert_equal(sol.success, False) + + def test_minimize_scalar_defaults_gh10911(self): + # Previously, bounds were silently ignored unless `method='bounds'` + # was chosen. See gh-10911. Check that this is no longer the case. + def f(x): + return x**2 + + res = optimize.minimize_scalar(f) + assert_allclose(res.x, 0, atol=1e-8) + + res = optimize.minimize_scalar(f, bounds=(1, 100), + options={'xatol': 1e-10}) + assert_allclose(res.x, 1) + + def test_minimize_non_finite_bounds_gh10911(self): + # Previously, minimize_scalar misbehaved with infinite bounds. + # See gh-10911. Check that it now raises an error, instead. + msg = "Optimization bounds must be finite scalars." + with pytest.raises(ValueError, match=msg): + optimize.minimize_scalar(np.sin, bounds=(1, np.inf)) + with pytest.raises(ValueError, match=msg): + optimize.minimize_scalar(np.sin, bounds=(np.nan, 1)) + + @pytest.mark.parametrize("method", ['brent', 'golden']) + def test_minimize_unbounded_method_with_bounds_gh10911(self, method): + # Previously, `bounds` were silently ignored when `method='brent'` or + # `method='golden'`. See gh-10911. Check that error is now raised. + msg = "Use of `bounds` is incompatible with..." + with pytest.raises(ValueError, match=msg): + optimize.minimize_scalar(np.sin, method=method, bounds=(1, 2)) + + @pytest.mark.filterwarnings('ignore::RuntimeWarning') + @pytest.mark.parametrize("method", MINIMIZE_SCALAR_METHODS) + @pytest.mark.parametrize("tol", [1, 1e-6]) + @pytest.mark.parametrize("fshape", [(), (1,), (1, 1)]) + def test_minimize_scalar_dimensionality_gh16196(self, method, tol, fshape): + # gh-16196 reported that the output shape of `minimize_scalar` was not + # consistent when an objective function returned an array. Check that + # `res.fun` and `res.x` are now consistent. + def f(x): + return np.array(x**4).reshape(fshape) + + a, b = -0.1, 0.2 + kwargs = (dict(bracket=(a, b)) if method != "bounded" + else dict(bounds=(a, b))) + kwargs.update(dict(method=method, tol=tol)) + + res = optimize.minimize_scalar(f, **kwargs) + assert res.x.shape == res.fun.shape == f(res.x).shape == fshape + + @pytest.mark.thread_unsafe + @pytest.mark.parametrize('method', ['bounded', 'brent', 'golden']) + def test_minimize_scalar_warnings_gh1953(self, method): + # test that minimize_scalar methods produce warnings rather than just + # using `print`; see gh-1953. + def f(x): + return (x - 1)**2 + + kwargs = {} + kwd = 'bounds' if method == 'bounded' else 'bracket' + kwargs[kwd] = [-2, 10] + + options = {'disp': True, 'maxiter': 3} + with pytest.warns(optimize.OptimizeWarning, match='Maximum number'): + optimize.minimize_scalar(f, method=method, options=options, + **kwargs) + + options['disp'] = False + optimize.minimize_scalar(f, method=method, options=options, **kwargs) + + +class TestBracket: + + @pytest.mark.filterwarnings('ignore::RuntimeWarning') + def test_errors_and_status_false(self): + # Check that `bracket` raises the errors it is supposed to + def f(x): # gh-14858 + return x**2 if ((-1 < x) & (x < 1)) else 100.0 + + message = "The algorithm terminated without finding a valid bracket." + with pytest.raises(RuntimeError, match=message): + optimize.bracket(f, -1, 1) + with pytest.raises(RuntimeError, match=message): + optimize.bracket(f, -1, np.inf) + with pytest.raises(RuntimeError, match=message): + optimize.brent(f, brack=(-1, 1)) + with pytest.raises(RuntimeError, match=message): + optimize.golden(f, brack=(-1, 1)) + + def f(x): # gh-5899 + return -5 * x**5 + 4 * x**4 - 12 * x**3 + 11 * x**2 - 2 * x + 1 + + message = "No valid bracket was found before the iteration limit..." + with pytest.raises(RuntimeError, match=message): + optimize.bracket(f, -0.5, 0.5, maxiter=10) + + @pytest.mark.parametrize('method', ('brent', 'golden')) + def test_minimize_scalar_success_false(self, method): + # Check that status information from `bracket` gets to minimize_scalar + def f(x): # gh-14858 + return x**2 if ((-1 < x) & (x < 1)) else 100.0 + + message = "The algorithm terminated without finding a valid bracket." + + res = optimize.minimize_scalar(f, bracket=(-1, 1), method=method) + assert not res.success + assert message in res.message + assert res.nfev == 3 + assert res.nit == 0 + assert res.fun == 100 + + +def test_brent_negative_tolerance(): + assert_raises(ValueError, optimize.brent, np.cos, tol=-.01) + + +class TestNewtonCg: + def test_rosenbrock(self): + x0 = np.array([-1.2, 1.0]) + sol = optimize.minimize(optimize.rosen, x0, + jac=optimize.rosen_der, + hess=optimize.rosen_hess, + tol=1e-5, + method='Newton-CG') + assert sol.success, sol.message + assert_allclose(sol.x, np.array([1, 1]), rtol=1e-4) + + def test_himmelblau(self): + x0 = np.array(himmelblau_x0) + sol = optimize.minimize(himmelblau, + x0, + jac=himmelblau_grad, + hess=himmelblau_hess, + method='Newton-CG', + tol=1e-6) + assert sol.success, sol.message + assert_allclose(sol.x, himmelblau_xopt, rtol=1e-4) + assert_allclose(sol.fun, himmelblau_min, atol=1e-4) + + def test_finite_difference(self): + x0 = np.array([-1.2, 1.0]) + sol = optimize.minimize(optimize.rosen, x0, + jac=optimize.rosen_der, + hess='2-point', + tol=1e-5, + method='Newton-CG') + assert sol.success, sol.message + assert_allclose(sol.x, np.array([1, 1]), rtol=1e-4) + + def test_hessian_update_strategy(self): + x0 = np.array([-1.2, 1.0]) + sol = optimize.minimize(optimize.rosen, x0, + jac=optimize.rosen_der, + hess=optimize.BFGS(), + tol=1e-5, + method='Newton-CG') + assert sol.success, sol.message + assert_allclose(sol.x, np.array([1, 1]), rtol=1e-4) + + +def test_line_for_search(): + # _line_for_search is only used in _linesearch_powell, which is also + # tested below. Thus there are more tests of _line_for_search in the + # test_linesearch_powell_bounded function. + + line_for_search = optimize._optimize._line_for_search + # args are x0, alpha, lower_bound, upper_bound + # returns lmin, lmax + + lower_bound = np.array([-5.3, -1, -1.5, -3]) + upper_bound = np.array([1.9, 1, 2.8, 3]) + + # test when starting in the bounds + x0 = np.array([0., 0, 0, 0]) + # and when starting outside of the bounds + x1 = np.array([0., 2, -3, 0]) + + all_tests = ( + (x0, np.array([1., 0, 0, 0]), -5.3, 1.9), + (x0, np.array([0., 1, 0, 0]), -1, 1), + (x0, np.array([0., 0, 1, 0]), -1.5, 2.8), + (x0, np.array([0., 0, 0, 1]), -3, 3), + (x0, np.array([1., 1, 0, 0]), -1, 1), + (x0, np.array([1., 0, -1, 2]), -1.5, 1.5), + (x0, np.array([2., 0, -1, 2]), -1.5, 0.95), + (x1, np.array([1., 0, 0, 0]), -5.3, 1.9), + (x1, np.array([0., 1, 0, 0]), -3, -1), + (x1, np.array([0., 0, 1, 0]), 1.5, 5.8), + (x1, np.array([0., 0, 0, 1]), -3, 3), + (x1, np.array([1., 1, 0, 0]), -3, -1), + (x1, np.array([1., 0, -1, 0]), -5.3, -1.5), + ) + + for x, alpha, lmin, lmax in all_tests: + mi, ma = line_for_search(x, alpha, lower_bound, upper_bound) + assert_allclose(mi, lmin, atol=1e-6) + assert_allclose(ma, lmax, atol=1e-6) + + # now with infinite bounds + lower_bound = np.array([-np.inf, -1, -np.inf, -3]) + upper_bound = np.array([np.inf, 1, 2.8, np.inf]) + + all_tests = ( + (x0, np.array([1., 0, 0, 0]), -np.inf, np.inf), + (x0, np.array([0., 1, 0, 0]), -1, 1), + (x0, np.array([0., 0, 1, 0]), -np.inf, 2.8), + (x0, np.array([0., 0, 0, 1]), -3, np.inf), + (x0, np.array([1., 1, 0, 0]), -1, 1), + (x0, np.array([1., 0, -1, 2]), -1.5, np.inf), + (x1, np.array([1., 0, 0, 0]), -np.inf, np.inf), + (x1, np.array([0., 1, 0, 0]), -3, -1), + (x1, np.array([0., 0, 1, 0]), -np.inf, 5.8), + (x1, np.array([0., 0, 0, 1]), -3, np.inf), + (x1, np.array([1., 1, 0, 0]), -3, -1), + (x1, np.array([1., 0, -1, 0]), -5.8, np.inf), + ) + + for x, alpha, lmin, lmax in all_tests: + mi, ma = line_for_search(x, alpha, lower_bound, upper_bound) + assert_allclose(mi, lmin, atol=1e-6) + assert_allclose(ma, lmax, atol=1e-6) + + +def test_linesearch_powell(): + # helper function in optimize.py, not a public function. + linesearch_powell = optimize._optimize._linesearch_powell + # args are func, p, xi, fval, lower_bound=None, upper_bound=None, tol=1e-3 + # returns new_fval, p + direction, direction + def func(x): + return np.sum((x - np.array([-1.0, 2.0, 1.5, -0.4])) ** 2) + p0 = np.array([0., 0, 0, 0]) + fval = func(p0) + lower_bound = np.array([-np.inf] * 4) + upper_bound = np.array([np.inf] * 4) + + all_tests = ( + (np.array([1., 0, 0, 0]), -1), + (np.array([0., 1, 0, 0]), 2), + (np.array([0., 0, 1, 0]), 1.5), + (np.array([0., 0, 0, 1]), -.4), + (np.array([-1., 0, 1, 0]), 1.25), + (np.array([0., 0, 1, 1]), .55), + (np.array([2., 0, -1, 1]), -.65), + ) + + for xi, l in all_tests: + f, p, direction = linesearch_powell(func, p0, xi, + fval=fval, tol=1e-5) + assert_allclose(f, func(l * xi), atol=1e-6) + assert_allclose(p, l * xi, atol=1e-6) + assert_allclose(direction, l * xi, atol=1e-6) + + f, p, direction = linesearch_powell(func, p0, xi, tol=1e-5, + lower_bound=lower_bound, + upper_bound=upper_bound, + fval=fval) + assert_allclose(f, func(l * xi), atol=1e-6) + assert_allclose(p, l * xi, atol=1e-6) + assert_allclose(direction, l * xi, atol=1e-6) + + +def test_linesearch_powell_bounded(): + # helper function in optimize.py, not a public function. + linesearch_powell = optimize._optimize._linesearch_powell + # args are func, p, xi, fval, lower_bound=None, upper_bound=None, tol=1e-3 + # returns new_fval, p+direction, direction + def func(x): + return np.sum((x - np.array([-1.0, 2.0, 1.5, -0.4])) ** 2) + p0 = np.array([0., 0, 0, 0]) + fval = func(p0) + + # first choose bounds such that the same tests from + # test_linesearch_powell should pass. + lower_bound = np.array([-2.]*4) + upper_bound = np.array([2.]*4) + + all_tests = ( + (np.array([1., 0, 0, 0]), -1), + (np.array([0., 1, 0, 0]), 2), + (np.array([0., 0, 1, 0]), 1.5), + (np.array([0., 0, 0, 1]), -.4), + (np.array([-1., 0, 1, 0]), 1.25), + (np.array([0., 0, 1, 1]), .55), + (np.array([2., 0, -1, 1]), -.65), + ) + + for xi, l in all_tests: + f, p, direction = linesearch_powell(func, p0, xi, tol=1e-5, + lower_bound=lower_bound, + upper_bound=upper_bound, + fval=fval) + assert_allclose(f, func(l * xi), atol=1e-6) + assert_allclose(p, l * xi, atol=1e-6) + assert_allclose(direction, l * xi, atol=1e-6) + + # now choose bounds such that unbounded vs bounded gives different results + lower_bound = np.array([-.3]*3 + [-1]) + upper_bound = np.array([.45]*3 + [.9]) + + all_tests = ( + (np.array([1., 0, 0, 0]), -.3), + (np.array([0., 1, 0, 0]), .45), + (np.array([0., 0, 1, 0]), .45), + (np.array([0., 0, 0, 1]), -.4), + (np.array([-1., 0, 1, 0]), .3), + (np.array([0., 0, 1, 1]), .45), + (np.array([2., 0, -1, 1]), -.15), + ) + + for xi, l in all_tests: + f, p, direction = linesearch_powell(func, p0, xi, tol=1e-5, + lower_bound=lower_bound, + upper_bound=upper_bound, + fval=fval) + assert_allclose(f, func(l * xi), atol=1e-6) + assert_allclose(p, l * xi, atol=1e-6) + assert_allclose(direction, l * xi, atol=1e-6) + + # now choose as above but start outside the bounds + p0 = np.array([-1., 0, 0, 2]) + fval = func(p0) + + all_tests = ( + (np.array([1., 0, 0, 0]), .7), + (np.array([0., 1, 0, 0]), .45), + (np.array([0., 0, 1, 0]), .45), + (np.array([0., 0, 0, 1]), -2.4), + ) + + for xi, l in all_tests: + f, p, direction = linesearch_powell(func, p0, xi, tol=1e-5, + lower_bound=lower_bound, + upper_bound=upper_bound, + fval=fval) + assert_allclose(f, func(p0 + l * xi), atol=1e-6) + assert_allclose(p, p0 + l * xi, atol=1e-6) + assert_allclose(direction, l * xi, atol=1e-6) + + # now mix in inf + p0 = np.array([0., 0, 0, 0]) + fval = func(p0) + + # now choose bounds that mix inf + lower_bound = np.array([-.3, -np.inf, -np.inf, -1]) + upper_bound = np.array([np.inf, .45, np.inf, .9]) + + all_tests = ( + (np.array([1., 0, 0, 0]), -.3), + (np.array([0., 1, 0, 0]), .45), + (np.array([0., 0, 1, 0]), 1.5), + (np.array([0., 0, 0, 1]), -.4), + (np.array([-1., 0, 1, 0]), .3), + (np.array([0., 0, 1, 1]), .55), + (np.array([2., 0, -1, 1]), -.15), + ) + + for xi, l in all_tests: + f, p, direction = linesearch_powell(func, p0, xi, tol=1e-5, + lower_bound=lower_bound, + upper_bound=upper_bound, + fval=fval) + assert_allclose(f, func(l * xi), atol=1e-6) + assert_allclose(p, l * xi, atol=1e-6) + assert_allclose(direction, l * xi, atol=1e-6) + + # now choose as above but start outside the bounds + p0 = np.array([-1., 0, 0, 2]) + fval = func(p0) + + all_tests = ( + (np.array([1., 0, 0, 0]), .7), + (np.array([0., 1, 0, 0]), .45), + (np.array([0., 0, 1, 0]), 1.5), + (np.array([0., 0, 0, 1]), -2.4), + ) + + for xi, l in all_tests: + f, p, direction = linesearch_powell(func, p0, xi, tol=1e-5, + lower_bound=lower_bound, + upper_bound=upper_bound, + fval=fval) + assert_allclose(f, func(p0 + l * xi), atol=1e-6) + assert_allclose(p, p0 + l * xi, atol=1e-6) + assert_allclose(direction, l * xi, atol=1e-6) + + +def test_powell_limits(): + # gh15342 - powell was going outside bounds for some function evaluations. + bounds = optimize.Bounds([0, 0], [0.6, 20]) + + def fun(x): + a, b = x + assert (x >= bounds.lb).all() and (x <= bounds.ub).all() + return a ** 2 + b ** 2 + + optimize.minimize(fun, x0=[0.6, 20], method='Powell', bounds=bounds) + + # Another test from the original report - gh-13411 + bounds = optimize.Bounds(lb=[0,], ub=[1,], keep_feasible=[True,]) + + def func(x): + assert x >= 0 and x <= 1 + return np.exp(x) + + optimize.minimize(fun=func, x0=[0.5], method='powell', bounds=bounds) + + +def test_powell_output(): + funs = [rosen, lambda x: np.array(rosen(x)), lambda x: np.array([rosen(x)])] + for fun in funs: + res = optimize.minimize(fun, x0=[0.6, 20], method='Powell') + assert np.isscalar(res.fun) + + +@array_api_compatible +class TestRosen: + def test_rosen(self, xp): + # integer input should be promoted to the default floating type + x = xp.asarray([1, 1, 1]) + xp_assert_equal(optimize.rosen(x), + xp.asarray(0.)) + + @skip_xp_backends('jax.numpy', + reasons=["JAX arrays do not support item assignment"]) + @pytest.mark.usefixtures("skip_xp_backends") + def test_rosen_der(self, xp): + x = xp.asarray([1, 1, 1, 1]) + xp_assert_equal(optimize.rosen_der(x), + xp.zeros_like(x, dtype=xp.asarray(1.).dtype)) + + @skip_xp_backends('jax.numpy', + reasons=["JAX arrays do not support item assignment"]) + @pytest.mark.usefixtures("skip_xp_backends") + def test_hess_prod(self, xp): + one = xp.asarray(1.) + xp_test = array_namespace(one) + # Compare rosen_hess(x) times p with rosen_hess_prod(x,p). See gh-1775. + x = xp.asarray([3, 4, 5]) + p = xp.asarray([2, 2, 2]) + hp = optimize.rosen_hess_prod(x, p) + p = xp_test.astype(p, one.dtype) + dothp = optimize.rosen_hess(x) @ p + xp_assert_equal(hp, dothp) + + +def himmelblau(p): + """ + R^2 -> R^1 test function for optimization. The function has four local + minima where himmelblau(xopt) == 0. + """ + x, y = p + a = x*x + y - 11 + b = x + y*y - 7 + return a*a + b*b + + +def himmelblau_grad(p): + x, y = p + return np.array([4*x**3 + 4*x*y - 42*x + 2*y**2 - 14, + 2*x**2 + 4*x*y + 4*y**3 - 26*y - 22]) + + +def himmelblau_hess(p): + x, y = p + return np.array([[12*x**2 + 4*y - 42, 4*x + 4*y], + [4*x + 4*y, 4*x + 12*y**2 - 26]]) + + +himmelblau_x0 = [-0.27, -0.9] +himmelblau_xopt = [3, 2] +himmelblau_min = 0.0 + + +def test_minimize_multiple_constraints(): + # Regression test for gh-4240. + def func(x): + return np.array([25 - 0.2 * x[0] - 0.4 * x[1] - 0.33 * x[2]]) + + def func1(x): + return np.array([x[1]]) + + def func2(x): + return np.array([x[2]]) + + cons = ({'type': 'ineq', 'fun': func}, + {'type': 'ineq', 'fun': func1}, + {'type': 'ineq', 'fun': func2}) + + def f(x): + return -1 * (x[0] + x[1] + x[2]) + + res = optimize.minimize(f, [0, 0, 0], method='SLSQP', constraints=cons) + assert_allclose(res.x, [125, 0, 0], atol=1e-10) + + +class TestOptimizeResultAttributes: + # Test that all minimizers return an OptimizeResult containing + # all the OptimizeResult attributes + def setup_method(self): + self.x0 = [5, 5] + self.func = optimize.rosen + self.jac = optimize.rosen_der + self.hess = optimize.rosen_hess + self.hessp = optimize.rosen_hess_prod + self.bounds = [(0., 10.), (0., 10.)] + + @pytest.mark.fail_slow(2) + def test_attributes_present(self): + attributes = ['nit', 'nfev', 'x', 'success', 'status', 'fun', + 'message'] + skip = {'cobyla': ['nit']} + for method in MINIMIZE_METHODS: + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, + ("Method .+ does not use (gradient|Hessian.*)" + " information")) + res = optimize.minimize(self.func, self.x0, method=method, + jac=self.jac, hess=self.hess, + hessp=self.hessp) + for attribute in attributes: + if method in skip and attribute in skip[method]: + continue + + assert hasattr(res, attribute) + assert attribute in dir(res) + + # gh13001, OptimizeResult.message should be a str + assert isinstance(res.message, str) + + +def f1(z, *params): + x, y = z + a, b, c, d, e, f, g, h, i, j, k, l, scale = params + return (a * x**2 + b * x * y + c * y**2 + d*x + e*y + f) + + +def f2(z, *params): + x, y = z + a, b, c, d, e, f, g, h, i, j, k, l, scale = params + return (-g*np.exp(-((x-h)**2 + (y-i)**2) / scale)) + + +def f3(z, *params): + x, y = z + a, b, c, d, e, f, g, h, i, j, k, l, scale = params + return (-j*np.exp(-((x-k)**2 + (y-l)**2) / scale)) + + +def brute_func(z, *params): + return f1(z, *params) + f2(z, *params) + f3(z, *params) + + +class TestBrute: + # Test the "brute force" method + def setup_method(self): + self.params = (2, 3, 7, 8, 9, 10, 44, -1, 2, 26, 1, -2, 0.5) + self.rranges = (slice(-4, 4, 0.25), slice(-4, 4, 0.25)) + self.solution = np.array([-1.05665192, 1.80834843]) + + def brute_func(self, z, *params): + # an instance method optimizing + return brute_func(z, *params) + + def test_brute(self): + # test fmin + resbrute = optimize.brute(brute_func, self.rranges, args=self.params, + full_output=True, finish=optimize.fmin) + assert_allclose(resbrute[0], self.solution, atol=1e-3) + assert_allclose(resbrute[1], brute_func(self.solution, *self.params), + atol=1e-3) + + # test minimize + resbrute = optimize.brute(brute_func, self.rranges, args=self.params, + full_output=True, + finish=optimize.minimize) + assert_allclose(resbrute[0], self.solution, atol=1e-3) + assert_allclose(resbrute[1], brute_func(self.solution, *self.params), + atol=1e-3) + + # test that brute can optimize an instance method (the other tests use + # a non-class based function + resbrute = optimize.brute(self.brute_func, self.rranges, + args=self.params, full_output=True, + finish=optimize.minimize) + assert_allclose(resbrute[0], self.solution, atol=1e-3) + + def test_1D(self): + # test that for a 1-D problem the test function is passed an array, + # not a scalar. + def f(x): + assert len(x.shape) == 1 + assert x.shape[0] == 1 + return x ** 2 + + optimize.brute(f, [(-1, 1)], Ns=3, finish=None) + + @pytest.mark.fail_slow(10) + def test_workers(self): + # check that parallel evaluation works + resbrute = optimize.brute(brute_func, self.rranges, args=self.params, + full_output=True, finish=None) + + resbrute1 = optimize.brute(brute_func, self.rranges, args=self.params, + full_output=True, finish=None, workers=2) + + assert_allclose(resbrute1[-1], resbrute[-1]) + assert_allclose(resbrute1[0], resbrute[0]) + + @pytest.mark.thread_unsafe + def test_runtime_warning(self, capsys): + rng = np.random.default_rng(1234) + + def func(z, *params): + return rng.random(1) * 1000 # never converged problem + + msg = "final optimization did not succeed.*|Maximum number of function eval.*" + with pytest.warns(RuntimeWarning, match=msg): + optimize.brute(func, self.rranges, args=self.params, disp=True) + + def test_coerce_args_param(self): + # optimize.brute should coerce non-iterable args to a tuple. + def f(x, *args): + return x ** args[0] + + resbrute = optimize.brute(f, (slice(-4, 4, .25),), args=2) + assert_allclose(resbrute, 0) + + +@pytest.mark.thread_unsafe +@pytest.mark.fail_slow(20) +def test_cobyla_threadsafe(): + + # Verify that cobyla is threadsafe. Will segfault if it is not. + + import concurrent.futures + import time + + def objective1(x): + time.sleep(0.1) + return x[0]**2 + + def objective2(x): + time.sleep(0.1) + return (x[0]-1)**2 + + min_method = "COBYLA" + + def minimizer1(): + return optimize.minimize(objective1, + [0.0], + method=min_method) + + def minimizer2(): + return optimize.minimize(objective2, + [0.0], + method=min_method) + + with concurrent.futures.ThreadPoolExecutor() as pool: + tasks = [] + tasks.append(pool.submit(minimizer1)) + tasks.append(pool.submit(minimizer2)) + for t in tasks: + t.result() + + +class TestIterationLimits: + # Tests that optimisation does not give up before trying requested + # number of iterations or evaluations. And that it does not succeed + # by exceeding the limits. + def setup_method(self): + self.funcalls = threading.local() + + def slow_func(self, v): + if not hasattr(self.funcalls, 'c'): + self.funcalls.c = 0 + self.funcalls.c += 1 + r, t = np.sqrt(v[0]**2+v[1]**2), np.arctan2(v[0], v[1]) + return np.sin(r*20 + t)+r*0.5 + + @pytest.mark.fail_slow(10) + def test_neldermead_limit(self): + self.check_limits("Nelder-Mead", 200) + + def test_powell_limit(self): + self.check_limits("powell", 1000) + + def check_limits(self, method, default_iters): + for start_v in [[0.1, 0.1], [1, 1], [2, 2]]: + for mfev in [50, 500, 5000]: + self.funcalls.c = 0 + res = optimize.minimize(self.slow_func, start_v, + method=method, + options={"maxfev": mfev}) + assert self.funcalls.c == res["nfev"] + if res["success"]: + assert res["nfev"] < mfev + else: + assert res["nfev"] >= mfev + for mit in [50, 500, 5000]: + res = optimize.minimize(self.slow_func, start_v, + method=method, + options={"maxiter": mit}) + if res["success"]: + assert res["nit"] <= mit + else: + assert res["nit"] >= mit + for mfev, mit in [[50, 50], [5000, 5000], [5000, np.inf]]: + self.funcalls.c = 0 + res = optimize.minimize(self.slow_func, start_v, + method=method, + options={"maxiter": mit, + "maxfev": mfev}) + assert self.funcalls.c == res["nfev"] + if res["success"]: + assert res["nfev"] < mfev and res["nit"] <= mit + else: + assert res["nfev"] >= mfev or res["nit"] >= mit + for mfev, mit in [[np.inf, None], [None, np.inf]]: + self.funcalls.c = 0 + res = optimize.minimize(self.slow_func, start_v, + method=method, + options={"maxiter": mit, + "maxfev": mfev}) + assert self.funcalls.c == res["nfev"] + if res["success"]: + if mfev is None: + assert res["nfev"] < default_iters*2 + else: + assert res["nit"] <= default_iters*2 + else: + assert (res["nfev"] >= default_iters*2 + or res["nit"] >= default_iters*2) + + +def test_result_x_shape_when_len_x_is_one(): + def fun(x): + return x * x + + def jac(x): + return 2. * x + + def hess(x): + return np.array([[2.]]) + + methods = ['Nelder-Mead', 'Powell', 'CG', 'BFGS', 'L-BFGS-B', 'TNC', + 'COBYLA', 'COBYQA', 'SLSQP'] + for method in methods: + res = optimize.minimize(fun, np.array([0.1]), method=method) + assert res.x.shape == (1,) + + # use jac + hess + methods = ['trust-constr', 'dogleg', 'trust-ncg', 'trust-exact', + 'trust-krylov', 'Newton-CG'] + for method in methods: + res = optimize.minimize(fun, np.array([0.1]), method=method, jac=jac, + hess=hess) + assert res.x.shape == (1,) + + +class FunctionWithGradient: + def __init__(self): + self.number_of_calls = threading.local() + + def __call__(self, x): + if not hasattr(self.number_of_calls, 'c'): + self.number_of_calls.c = 0 + self.number_of_calls.c += 1 + return np.sum(x**2), 2 * x + + +@pytest.fixture +def function_with_gradient(): + return FunctionWithGradient() + + +def test_memoize_jac_function_before_gradient(function_with_gradient): + memoized_function = MemoizeJac(function_with_gradient) + + x0 = np.array([1.0, 2.0]) + assert_allclose(memoized_function(x0), 5.0) + assert function_with_gradient.number_of_calls.c == 1 + + assert_allclose(memoized_function.derivative(x0), 2 * x0) + assert function_with_gradient.number_of_calls.c == 1, \ + "function is not recomputed " \ + "if gradient is requested after function value" + + assert_allclose( + memoized_function(2 * x0), 20.0, + err_msg="different input triggers new computation") + assert function_with_gradient.number_of_calls.c == 2, \ + "different input triggers new computation" + + +def test_memoize_jac_gradient_before_function(function_with_gradient): + memoized_function = MemoizeJac(function_with_gradient) + + x0 = np.array([1.0, 2.0]) + assert_allclose(memoized_function.derivative(x0), 2 * x0) + assert function_with_gradient.number_of_calls.c == 1 + + assert_allclose(memoized_function(x0), 5.0) + assert function_with_gradient.number_of_calls.c == 1, \ + "function is not recomputed " \ + "if function value is requested after gradient" + + assert_allclose( + memoized_function.derivative(2 * x0), 4 * x0, + err_msg="different input triggers new computation") + assert function_with_gradient.number_of_calls.c == 2, \ + "different input triggers new computation" + + +def test_memoize_jac_with_bfgs(function_with_gradient): + """ Tests that using MemoizedJac in combination with ScalarFunction + and BFGS does not lead to repeated function evaluations. + Tests changes made in response to GH11868. + """ + memoized_function = MemoizeJac(function_with_gradient) + jac = memoized_function.derivative + hess = optimize.BFGS() + + x0 = np.array([1.0, 0.5]) + scalar_function = ScalarFunction( + memoized_function, x0, (), jac, hess, None, None) + assert function_with_gradient.number_of_calls.c == 1 + + scalar_function.fun(x0 + 0.1) + assert function_with_gradient.number_of_calls.c == 2 + + scalar_function.fun(x0 + 0.2) + assert function_with_gradient.number_of_calls.c == 3 + + +def test_gh12696(): + # Test that optimize doesn't throw warning gh-12696 + with assert_no_warnings(): + optimize.fminbound( + lambda x: np.array([x**2]), -np.pi, np.pi, disp=False) + + +# --- Test minimize with equal upper and lower bounds --- # + +def setup_test_equal_bounds(): + + rng = np.random.RandomState(0) + x0 = rng.rand(4) + lb = np.array([0, 2, -1, -1.0]) + ub = np.array([3, 2, 2, -1.0]) + i_eb = (lb == ub) + + def check_x(x, check_size=True, check_values=True): + if check_size: + assert x.size == 4 + if check_values: + assert_allclose(x[i_eb], lb[i_eb]) + + def func(x): + check_x(x) + return optimize.rosen(x) + + def grad(x): + check_x(x) + return optimize.rosen_der(x) + + def callback(x, *args): + check_x(x) + + def constraint1(x): + check_x(x, check_values=False) + return x[0:1] - 1 + + def jacobian1(x): + check_x(x, check_values=False) + dc = np.zeros_like(x) + dc[0] = 1 + return dc + + def constraint2(x): + check_x(x, check_values=False) + return x[2:3] - 0.5 + + def jacobian2(x): + check_x(x, check_values=False) + dc = np.zeros_like(x) + dc[2] = 1 + return dc + + c1a = NonlinearConstraint(constraint1, -np.inf, 0) + c1b = NonlinearConstraint(constraint1, -np.inf, 0, jacobian1) + c2a = NonlinearConstraint(constraint2, -np.inf, 0) + c2b = NonlinearConstraint(constraint2, -np.inf, 0, jacobian2) + + # test using the three methods that accept bounds, use derivatives, and + # have some trouble when bounds fix variables + methods = ('L-BFGS-B', 'SLSQP', 'TNC') + + # test w/out gradient, w/ gradient, and w/ combined objective/gradient + kwds = ({"fun": func, "jac": False}, + {"fun": func, "jac": grad}, + {"fun": (lambda x: (func(x), grad(x))), + "jac": True}) + + # test with both old- and new-style bounds + bound_types = (lambda lb, ub: list(zip(lb, ub)), + Bounds) + + # Test for many combinations of constraints w/ and w/out jacobian + # Pairs in format: (test constraints, reference constraints) + # (always use analytical jacobian in reference) + constraints = ((None, None), ([], []), + (c1a, c1b), (c2b, c2b), + ([c1b], [c1b]), ([c2a], [c2b]), + ([c1a, c2a], [c1b, c2b]), + ([c1a, c2b], [c1b, c2b]), + ([c1b, c2b], [c1b, c2b])) + + # test with and without callback function + callbacks = (None, callback) + + data = {"methods": methods, "kwds": kwds, "bound_types": bound_types, + "constraints": constraints, "callbacks": callbacks, + "lb": lb, "ub": ub, "x0": x0, "i_eb": i_eb} + + return data + + +eb_data = setup_test_equal_bounds() + + +# This test is about handling fixed variables, not the accuracy of the solvers +@pytest.mark.xfail_on_32bit("Failures due to floating point issues, not logic") +@pytest.mark.xfail(scipy.show_config(mode='dicts')['Compilers']['fortran']['name'] == + "intel-llvm", + reason="Failures due to floating point issues, not logic") +@pytest.mark.parametrize('method', eb_data["methods"]) +@pytest.mark.parametrize('kwds', eb_data["kwds"]) +@pytest.mark.parametrize('bound_type', eb_data["bound_types"]) +@pytest.mark.parametrize('constraints', eb_data["constraints"]) +@pytest.mark.parametrize('callback', eb_data["callbacks"]) +def test_equal_bounds(method, kwds, bound_type, constraints, callback): + """ + Tests that minimizers still work if (bounds.lb == bounds.ub).any() + gh12502 - Divide by zero in Jacobian numerical differentiation when + equality bounds constraints are used + """ + # GH-15051; slightly more skips than necessary; hopefully fixed by GH-14882 + if (platform.machine() == 'aarch64' and method == "TNC" + and kwds["jac"] is False and callback is not None): + pytest.skip('Tolerance violation on aarch') + + lb, ub = eb_data["lb"], eb_data["ub"] + x0, i_eb = eb_data["x0"], eb_data["i_eb"] + + test_constraints, reference_constraints = constraints + if test_constraints and not method == 'SLSQP': + pytest.skip('Only SLSQP supports nonlinear constraints') + # reference constraints always have analytical jacobian + # if test constraints are not the same, we'll need finite differences + fd_needed = (test_constraints != reference_constraints) + + bounds = bound_type(lb, ub) # old- or new-style + + kwds.update({"x0": x0, "method": method, "bounds": bounds, + "constraints": test_constraints, "callback": callback}) + res = optimize.minimize(**kwds) + + expected = optimize.minimize(optimize.rosen, x0, method=method, + jac=optimize.rosen_der, bounds=bounds, + constraints=reference_constraints) + + # compare the output of a solution with FD vs that of an analytic grad + assert res.success + assert_allclose(res.fun, expected.fun, rtol=1.5e-6) + assert_allclose(res.x, expected.x, rtol=5e-4) + + if fd_needed or kwds['jac'] is False: + expected.jac[i_eb] = np.nan + assert res.jac.shape[0] == 4 + assert_allclose(res.jac[i_eb], expected.jac[i_eb], rtol=1e-6) + + if not (kwds['jac'] or test_constraints or isinstance(bounds, Bounds)): + # compare the output to an equivalent FD minimization that doesn't + # need factorization + def fun(x): + new_x = np.array([np.nan, 2, np.nan, -1]) + new_x[[0, 2]] = x + return optimize.rosen(new_x) + + fd_res = optimize.minimize(fun, + x0[[0, 2]], + method=method, + bounds=bounds[::2]) + assert_allclose(res.fun, fd_res.fun) + # TODO this test should really be equivalent to factorized version + # above, down to res.nfev. However, testing found that when TNC is + # called with or without a callback the output is different. The two + # should be the same! This indicates that the TNC callback may be + # mutating something when it shouldn't. + assert_allclose(res.x[[0, 2]], fd_res.x, rtol=2e-6) + + +@pytest.mark.parametrize('method', eb_data["methods"]) +def test_all_bounds_equal(method): + # this only tests methods that have parameters factored out when lb==ub + # it does not test other methods that work with bounds + def f(x, p1=1): + return np.linalg.norm(x) + p1 + + bounds = [(1, 1), (2, 2)] + x0 = (1.0, 3.0) + res = optimize.minimize(f, x0, bounds=bounds, method=method) + assert res.success + assert_allclose(res.fun, f([1.0, 2.0])) + assert res.nfev == 1 + assert res.message == 'All independent variables were fixed by bounds.' + + args = (2,) + res = optimize.minimize(f, x0, bounds=bounds, method=method, args=args) + assert res.success + assert_allclose(res.fun, f([1.0, 2.0], 2)) + + if method.upper() == 'SLSQP': + def con(x): + return np.sum(x) + nlc = NonlinearConstraint(con, -np.inf, 0.0) + res = optimize.minimize( + f, x0, bounds=bounds, method=method, constraints=[nlc] + ) + assert res.success is False + assert_allclose(res.fun, f([1.0, 2.0])) + assert res.nfev == 1 + message = "All independent variables were fixed by bounds, but" + assert res.message.startswith(message) + + nlc = NonlinearConstraint(con, -np.inf, 4) + res = optimize.minimize( + f, x0, bounds=bounds, method=method, constraints=[nlc] + ) + assert res.success is True + assert_allclose(res.fun, f([1.0, 2.0])) + assert res.nfev == 1 + message = "All independent variables were fixed by bounds at values" + assert res.message.startswith(message) + + +def test_eb_constraints(): + # make sure constraint functions aren't overwritten when equal bounds + # are employed, and a parameter is factored out. GH14859 + def f(x): + return x[0]**3 + x[1]**2 + x[2]*x[3] + + def cfun(x): + return x[0] + x[1] + x[2] + x[3] - 40 + + constraints = [{'type': 'ineq', 'fun': cfun}] + + bounds = [(0, 20)] * 4 + bounds[1] = (5, 5) + optimize.minimize( + f, + x0=[1, 2, 3, 4], + method='SLSQP', + bounds=bounds, + constraints=constraints, + ) + assert constraints[0]['fun'] == cfun + + +def test_show_options(): + solver_methods = { + 'minimize': MINIMIZE_METHODS, + 'minimize_scalar': MINIMIZE_SCALAR_METHODS, + 'root': ROOT_METHODS, + 'root_scalar': ROOT_SCALAR_METHODS, + 'linprog': LINPROG_METHODS, + 'quadratic_assignment': QUADRATIC_ASSIGNMENT_METHODS, + } + for solver, methods in solver_methods.items(): + for method in methods: + # testing that `show_options` works without error + show_options(solver, method) + + unknown_solver_method = { + 'minimize': "ekki", # unknown method + 'maximize': "cg", # unknown solver + 'maximize_scalar': "ekki", # unknown solver and method + } + for solver, method in unknown_solver_method.items(): + # testing that `show_options` raises ValueError + assert_raises(ValueError, show_options, solver, method) + + +def test_bounds_with_list(): + # gh13501. Bounds created with lists weren't working for Powell. + bounds = optimize.Bounds(lb=[5., 5.], ub=[10., 10.]) + optimize.minimize( + optimize.rosen, x0=np.array([9, 9]), method='Powell', bounds=bounds + ) + + +def test_x_overwritten_user_function(): + # if the user overwrites the x-array in the user function it's likely + # that the minimizer stops working properly. + # gh13740 + def fquad(x): + a = np.arange(np.size(x)) + x -= a + x *= x + return np.sum(x) + + def fquad_jac(x): + a = np.arange(np.size(x)) + x *= 2 + x -= 2 * a + return x + + def fquad_hess(x): + return np.eye(np.size(x)) * 2.0 + + meth_jac = [ + 'newton-cg', 'dogleg', 'trust-ncg', 'trust-exact', + 'trust-krylov', 'trust-constr' + ] + meth_hess = [ + 'dogleg', 'trust-ncg', 'trust-exact', 'trust-krylov', 'trust-constr' + ] + + x0 = np.ones(5) * 1.5 + + for meth in MINIMIZE_METHODS: + jac = None + hess = None + if meth in meth_jac: + jac = fquad_jac + if meth in meth_hess: + hess = fquad_hess + res = optimize.minimize(fquad, x0, method=meth, jac=jac, hess=hess) + assert_allclose(res.x, np.arange(np.size(x0)), atol=2e-4) + + +class TestGlobalOptimization: + + def test_optimize_result_attributes(self): + def func(x): + return x ** 2 + + # Note that `brute` solver does not return `OptimizeResult` + results = [optimize.basinhopping(func, x0=1), + optimize.differential_evolution(func, [(-4, 4)]), + optimize.shgo(func, [(-4, 4)]), + optimize.dual_annealing(func, [(-4, 4)]), + optimize.direct(func, [(-4, 4)]), + ] + + for result in results: + assert isinstance(result, optimize.OptimizeResult) + assert hasattr(result, "x") + assert hasattr(result, "success") + assert hasattr(result, "message") + assert hasattr(result, "fun") + assert hasattr(result, "nfev") + assert hasattr(result, "nit") + + +def test_approx_fprime(): + # check that approx_fprime (serviced by approx_derivative) works for + # jac and hess + g = optimize.approx_fprime(himmelblau_x0, himmelblau) + assert_allclose(g, himmelblau_grad(himmelblau_x0), rtol=5e-6) + + h = optimize.approx_fprime(himmelblau_x0, himmelblau_grad) + assert_allclose(h, himmelblau_hess(himmelblau_x0), rtol=5e-6) + + +def test_gh12594(): + # gh-12594 reported an error in `_linesearch_powell` and + # `_line_for_search` when `Bounds` was passed lists instead of arrays. + # Check that results are the same whether the inputs are lists or arrays. + + def f(x): + return x[0]**2 + (x[1] - 1)**2 + + bounds = Bounds(lb=[-10, -10], ub=[10, 10]) + res = optimize.minimize(f, x0=(0, 0), method='Powell', bounds=bounds) + bounds = Bounds(lb=np.array([-10, -10]), ub=np.array([10, 10])) + ref = optimize.minimize(f, x0=(0, 0), method='Powell', bounds=bounds) + + assert_allclose(res.fun, ref.fun) + assert_allclose(res.x, ref.x) + + +@pytest.mark.parametrize('method', ['Newton-CG', 'trust-constr']) +@pytest.mark.parametrize('sparse_type', [coo_matrix, csc_matrix, csr_matrix, + coo_array, csr_array, csc_array]) +def test_sparse_hessian(method, sparse_type): + # gh-8792 reported an error for minimization with `newton_cg` when `hess` + # returns a sparse matrix. Check that results are the same whether `hess` + # returns a dense or sparse matrix for optimization methods that accept + # sparse Hessian matrices. + + def sparse_rosen_hess(x): + return sparse_type(rosen_hess(x)) + + x0 = [2., 2.] + + res_sparse = optimize.minimize(rosen, x0, method=method, + jac=rosen_der, hess=sparse_rosen_hess) + res_dense = optimize.minimize(rosen, x0, method=method, + jac=rosen_der, hess=rosen_hess) + + assert_allclose(res_dense.fun, res_sparse.fun) + assert_allclose(res_dense.x, res_sparse.x) + assert res_dense.nfev == res_sparse.nfev + assert res_dense.njev == res_sparse.njev + assert res_dense.nhev == res_sparse.nhev diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_quadratic_assignment.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_quadratic_assignment.py new file mode 100644 index 0000000000000000000000000000000000000000..3f7f26158d8e7ddb33012db4dfc4030661aa75bb --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_quadratic_assignment.py @@ -0,0 +1,455 @@ +import pytest +import numpy as np +from numpy.random import default_rng +from scipy.optimize import quadratic_assignment, OptimizeWarning +from scipy.optimize._qap import _calc_score as _score +from numpy.testing import assert_equal, assert_, assert_warns + + +################ +# Common Tests # +################ + +def chr12c(): + A = [ + [0, 90, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [90, 0, 0, 23, 0, 0, 0, 0, 0, 0, 0, 0], + [10, 0, 0, 0, 43, 0, 0, 0, 0, 0, 0, 0], + [0, 23, 0, 0, 0, 88, 0, 0, 0, 0, 0, 0], + [0, 0, 43, 0, 0, 0, 26, 0, 0, 0, 0, 0], + [0, 0, 0, 88, 0, 0, 0, 16, 0, 0, 0, 0], + [0, 0, 0, 0, 26, 0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 16, 0, 0, 0, 96, 0, 0], + [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 29, 0], + [0, 0, 0, 0, 0, 0, 0, 96, 0, 0, 0, 37], + [0, 0, 0, 0, 0, 0, 0, 0, 29, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 37, 0, 0], + ] + B = [ + [0, 36, 54, 26, 59, 72, 9, 34, 79, 17, 46, 95], + [36, 0, 73, 35, 90, 58, 30, 78, 35, 44, 79, 36], + [54, 73, 0, 21, 10, 97, 58, 66, 69, 61, 54, 63], + [26, 35, 21, 0, 93, 12, 46, 40, 37, 48, 68, 85], + [59, 90, 10, 93, 0, 64, 5, 29, 76, 16, 5, 76], + [72, 58, 97, 12, 64, 0, 96, 55, 38, 54, 0, 34], + [9, 30, 58, 46, 5, 96, 0, 83, 35, 11, 56, 37], + [34, 78, 66, 40, 29, 55, 83, 0, 44, 12, 15, 80], + [79, 35, 69, 37, 76, 38, 35, 44, 0, 64, 39, 33], + [17, 44, 61, 48, 16, 54, 11, 12, 64, 0, 70, 86], + [46, 79, 54, 68, 5, 0, 56, 15, 39, 70, 0, 18], + [95, 36, 63, 85, 76, 34, 37, 80, 33, 86, 18, 0], + ] + A, B = np.array(A), np.array(B) + n = A.shape[0] + + opt_perm = np.array([7, 5, 1, 3, 10, 4, 8, 6, 9, 11, 2, 12]) - [1] * n + + return A, B, opt_perm + + +@pytest.mark.filterwarnings("ignore:The NumPy global RNG was seeded by calling") +class QAPCommonTests: + """ + Base class for `quadratic_assignment` tests. + """ + # Test global optima of problem from Umeyama IVB + # https://pcl.sitehost.iu.edu/rgoldsto/papers/weighted%20graph%20match2.pdf + # Graph matching maximum is in the paper + # QAP minimum determined by brute force + def test_accuracy_1(self): + # besides testing accuracy, check that A and B can be lists + rng = np.random.default_rng(4358764578823597324) + + A = [[0, 3, 4, 2], + [0, 0, 1, 2], + [1, 0, 0, 1], + [0, 0, 1, 0]] + + B = [[0, 4, 2, 4], + [0, 0, 1, 0], + [0, 2, 0, 2], + [0, 1, 2, 0]] + + res = quadratic_assignment(A, B, method=self.method, + options={"rng": rng, "maximize": False}) + + assert_equal(res.fun, 10) + assert_equal(res.col_ind, np.array([1, 2, 3, 0])) + + res = quadratic_assignment(A, B, method=self.method, + options={"rng": rng, "maximize": True}) + + if self.method == 'faq': + # Global optimum is 40, but FAQ gets 37 + assert_equal(res.fun, 37) + assert_equal(res.col_ind, np.array([0, 2, 3, 1])) + else: + assert_equal(res.fun, 40) + assert_equal(res.col_ind, np.array([0, 3, 1, 2])) + + quadratic_assignment(A, B, method=self.method, + options={"rng": rng, "maximize": True}) + + # Test global optima of problem from Umeyama IIIB + # https://pcl.sitehost.iu.edu/rgoldsto/papers/weighted%20graph%20match2.pdf + # Graph matching maximum is in the paper + # QAP minimum determined by brute force + def test_accuracy_2(self): + rng = np.random.default_rng(4358764578823597324) + + A = np.array([[0, 5, 8, 6], + [5, 0, 5, 1], + [8, 5, 0, 2], + [6, 1, 2, 0]]) + + B = np.array([[0, 1, 8, 4], + [1, 0, 5, 2], + [8, 5, 0, 5], + [4, 2, 5, 0]]) + + res = quadratic_assignment(A, B, method=self.method, + options={"rng": rng, "maximize": False}) + + if self.method == 'faq': + # Global optimum is 176, but FAQ gets 178 + assert_equal(res.fun, 178) + assert_equal(res.col_ind, np.array([1, 0, 3, 2])) + else: + assert_equal(res.fun, 176) + assert_equal(res.col_ind, np.array([1, 2, 3, 0])) + + res = quadratic_assignment(A, B, method=self.method, + options={"rng": rng, "maximize": True}) + + assert_equal(res.fun, 286) + assert_equal(res.col_ind, np.array([2, 3, 0, 1])) + + def test_accuracy_3(self): + rng = np.random.default_rng(4358764578823597324) + A, B, opt_perm = chr12c() + + # basic minimization + res = quadratic_assignment(A, B, method=self.method, + options={"rng": rng}) + assert_(11156 <= res.fun < 21000) + assert_equal(res.fun, _score(A, B, res.col_ind)) + + # basic maximization + res = quadratic_assignment(A, B, method=self.method, + options={"rng": rng, 'maximize': True}) + assert_(74000 <= res.fun < 85000) + assert_equal(res.fun, _score(A, B, res.col_ind)) + + # check ofv with strictly partial match + seed_cost = np.array([4, 8, 10]) + seed = np.asarray([seed_cost, opt_perm[seed_cost]]).T + res = quadratic_assignment(A, B, method=self.method, + options={'partial_match': seed, "rng": rng}) + assert_(11156 <= res.fun < 21000) + assert_equal(res.col_ind[seed_cost], opt_perm[seed_cost]) + + # check performance when partial match is the global optimum + seed = np.asarray([np.arange(len(A)), opt_perm]).T + res = quadratic_assignment(A, B, method=self.method, + options={'partial_match': seed, "rng": rng}) + assert_equal(res.col_ind, seed[:, 1].T) + assert_equal(res.fun, 11156) + assert_equal(res.nit, 0) + + # check performance with zero sized matrix inputs + empty = np.empty((0, 0)) + res = quadratic_assignment(empty, empty, method=self.method, + options={"rng": rng}) + assert_equal(res.nit, 0) + assert_equal(res.fun, 0) + + @pytest.mark.thread_unsafe + def test_unknown_options(self): + A, B, opt_perm = chr12c() + + def f(): + quadratic_assignment(A, B, method=self.method, + options={"ekki-ekki": True}) + assert_warns(OptimizeWarning, f) + + @pytest.mark.thread_unsafe + def test_deprecation_future_warnings(self): + # May be removed after SPEC-7 transition is complete in SciPy 1.17 + A = np.arange(16).reshape((4, 4)) + B = np.arange(16).reshape((4, 4)) + + with pytest.warns(DeprecationWarning, match="Use of `RandomState`*"): + rng = np.random.RandomState(0) + quadratic_assignment(A, B, method=self.method, + options={"rng": rng, "maximize": False}) + + with pytest.warns(FutureWarning, match="The NumPy global RNG was seeded*"): + np.random.seed(0) + quadratic_assignment(A, B, method=self.method, + options={"maximize": False}) + + with pytest.warns(FutureWarning, match="The behavior when the rng option*"): + quadratic_assignment(A, B, method=self.method, + options={"rng": 0, "maximize": False}) + + +class TestFAQ(QAPCommonTests): + method = "faq" + + def test_options(self): + # cost and distance matrices of QAPLIB instance chr12c + rng = np.random.default_rng(4358764578823597324) + + A, B, opt_perm = chr12c() + n = len(A) + + # check that max_iter is obeying with low input value + res = quadratic_assignment(A, B, options={'maxiter': 5}) + assert_equal(res.nit, 5) + + # test with shuffle + res = quadratic_assignment(A, B, options={'shuffle_input': True}) + assert_(11156 <= res.fun < 21000) + + # test with randomized init + res = quadratic_assignment(A, B, options={'rng': rng, 'P0': "randomized"}) + assert_(11156 <= res.fun < 21000) + + # check with specified P0 + K = np.ones((n, n)) / float(n) + K = _doubly_stochastic(K) + res = quadratic_assignment(A, B, options={'P0': K}) + assert_(11156 <= res.fun < 21000) + + def test_specific_input_validation(self): + + A = np.identity(2) + B = A + + # method is implicitly faq + + # ValueError Checks: making sure single value parameters are of + # correct value + with pytest.raises(ValueError, match="Invalid 'P0' parameter"): + quadratic_assignment(A, B, options={'P0': "random"}) + with pytest.raises( + ValueError, match="'maxiter' must be a positive integer"): + quadratic_assignment(A, B, options={'maxiter': -1}) + with pytest.raises(ValueError, match="'tol' must be a positive float"): + quadratic_assignment(A, B, options={'tol': -1}) + + # TypeError Checks: making sure single value parameters are of + # correct type + with pytest.raises(TypeError): + quadratic_assignment(A, B, options={'maxiter': 1.5}) + + # test P0 matrix input + with pytest.raises( + ValueError, + match="`P0` matrix must have shape m' x m', where m'=n-m"): + quadratic_assignment( + np.identity(4), np.identity(4), + options={'P0': np.ones((3, 3))} + ) + + K = [[0.4, 0.2, 0.3], + [0.3, 0.6, 0.2], + [0.2, 0.2, 0.7]] + # matrix that isn't quite doubly stochastic + with pytest.raises( + ValueError, match="`P0` matrix must be doubly stochastic"): + quadratic_assignment( + np.identity(3), np.identity(3), options={'P0': K} + ) + + +class Test2opt(QAPCommonTests): + method = "2opt" + + def test_deterministic(self): + n = 20 + rng = default_rng(51982908) + A = rng.random(size=(n, n)) + B = rng.random(size=(n, n)) + res1 = quadratic_assignment(A, B, method=self.method, options={'rng': rng}) + + rng = default_rng(51982908) + A = rng.random(size=(n, n)) + B = rng.random(size=(n, n)) + res2 = quadratic_assignment(A, B, method=self.method, options={'rng': rng}) + + assert_equal(res1.nit, res2.nit) + + def test_partial_guess(self): + n = 5 + rng = np.random.default_rng(4358764578823597324) + + A = rng.random(size=(n, n)) + B = rng.random(size=(n, n)) + + res1 = quadratic_assignment(A, B, method=self.method, + options={'rng': rng}) + guess = np.array([np.arange(5), res1.col_ind]).T + res2 = quadratic_assignment(A, B, method=self.method, + options={'rng': rng, 'partial_guess': guess}) + fix = [2, 4] + match = np.array([np.arange(5)[fix], res1.col_ind[fix]]).T + res3 = quadratic_assignment(A, B, method=self.method, + options={'rng': rng, 'partial_guess': guess, + 'partial_match': match}) + assert_(res1.nit != n*(n+1)/2) + assert_equal(res2.nit, n*(n+1)/2) # tests each swap exactly once + assert_equal(res3.nit, (n-2)*(n-1)/2) # tests free swaps exactly once + + def test_specific_input_validation(self): + # can't have more seed nodes than cost/dist nodes + _rm = _range_matrix + with pytest.raises( + ValueError, + match="`partial_guess` can have only as many entries as"): + quadratic_assignment(np.identity(3), np.identity(3), + method=self.method, + options={'partial_guess': _rm(5, 2)}) + # test for only two seed columns + with pytest.raises( + ValueError, match="`partial_guess` must have two columns"): + quadratic_assignment( + np.identity(3), np.identity(3), method=self.method, + options={'partial_guess': _range_matrix(2, 3)} + ) + # test that seed has no more than two dimensions + with pytest.raises( + ValueError, match="`partial_guess` must have exactly two"): + quadratic_assignment( + np.identity(3), np.identity(3), method=self.method, + options={'partial_guess': np.random.rand(3, 2, 2)} + ) + # seeds cannot be negative valued + with pytest.raises( + ValueError, match="`partial_guess` must contain only pos"): + quadratic_assignment( + np.identity(3), np.identity(3), method=self.method, + options={'partial_guess': -1 * _range_matrix(2, 2)} + ) + # seeds can't have values greater than number of nodes + with pytest.raises( + ValueError, + match="`partial_guess` entries must be less than number"): + quadratic_assignment( + np.identity(5), np.identity(5), method=self.method, + options={'partial_guess': 2 * _range_matrix(4, 2)} + ) + # columns of seed matrix must be unique + with pytest.raises( + ValueError, + match="`partial_guess` column entries must be unique"): + quadratic_assignment( + np.identity(3), np.identity(3), method=self.method, + options={'partial_guess': np.ones((2, 2))} + ) + + +@pytest.mark.filterwarnings("ignore:The NumPy global RNG was seeded by calling") +class TestQAPOnce: + + # these don't need to be repeated for each method + def test_common_input_validation(self): + rng = default_rng(12349038) + # test that non square matrices return error + with pytest.raises(ValueError, match="`A` must be square"): + quadratic_assignment( + rng.random((3, 4)), + rng.random((3, 3)), + ) + with pytest.raises(ValueError, match="`B` must be square"): + quadratic_assignment( + rng.random((3, 3)), + rng.random((3, 4)), + ) + # test that cost and dist matrices have no more than two dimensions + with pytest.raises( + ValueError, match="`A` and `B` must have exactly two"): + quadratic_assignment( + rng.random((3, 3, 3)), + rng.random((3, 3, 3)), + ) + # test that cost and dist matrices of different sizes return error + with pytest.raises( + ValueError, + match="`A` and `B` matrices must be of equal size"): + quadratic_assignment( + rng.random((3, 3)), + rng.random((4, 4)), + ) + # can't have more seed nodes than cost/dist nodes + _rm = _range_matrix + with pytest.raises( + ValueError, + match="`partial_match` can have only as many seeds as"): + quadratic_assignment(np.identity(3), np.identity(3), + options={'partial_match': _rm(5, 2)}) + # test for only two seed columns + with pytest.raises( + ValueError, match="`partial_match` must have two columns"): + quadratic_assignment( + np.identity(3), np.identity(3), + options={'partial_match': _range_matrix(2, 3)} + ) + # test that seed has no more than two dimensions + with pytest.raises( + ValueError, match="`partial_match` must have exactly two"): + quadratic_assignment( + np.identity(3), np.identity(3), + options={'partial_match': np.random.rand(3, 2, 2)} + ) + # seeds cannot be negative valued + with pytest.raises( + ValueError, match="`partial_match` must contain only pos"): + quadratic_assignment( + np.identity(3), np.identity(3), + options={'partial_match': -1 * _range_matrix(2, 2)} + ) + # seeds can't have values greater than number of nodes + with pytest.raises( + ValueError, + match="`partial_match` entries must be less than number"): + quadratic_assignment( + np.identity(5), np.identity(5), + options={'partial_match': 2 * _range_matrix(4, 2)} + ) + # columns of seed matrix must be unique + with pytest.raises( + ValueError, + match="`partial_match` column entries must be unique"): + quadratic_assignment( + np.identity(3), np.identity(3), + options={'partial_match': np.ones((2, 2))} + ) + + +def _range_matrix(a, b): + mat = np.zeros((a, b)) + for i in range(b): + mat[:, i] = np.arange(a) + return mat + + +def _doubly_stochastic(P, tol=1e-3): + # cleaner implementation of btaba/sinkhorn_knopp + + max_iter = 1000 + c = 1 / P.sum(axis=0) + r = 1 / (P @ c) + P_eps = P + + for it in range(max_iter): + if ((np.abs(P_eps.sum(axis=1) - 1) < tol).all() and + (np.abs(P_eps.sum(axis=0) - 1) < tol).all()): + # All column/row sums ~= 1 within threshold + break + + c = 1 / (r @ P) + r = 1 / (P @ c) + P_eps = r[:, None] * P * c + + return P_eps diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_regression.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_regression.py new file mode 100644 index 0000000000000000000000000000000000000000..44916ba96293db19756b8222422e76945aa48ebb --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_regression.py @@ -0,0 +1,40 @@ +"""Regression tests for optimize. + +""" +import numpy as np +from numpy.testing import assert_almost_equal +from pytest import raises as assert_raises + +import scipy.optimize + + +class TestRegression: + + def test_newton_x0_is_0(self): + # Regression test for gh-1601 + tgt = 1 + res = scipy.optimize.newton(lambda x: x - 1, 0) + assert_almost_equal(res, tgt) + + def test_newton_integers(self): + # Regression test for gh-1741 + root = scipy.optimize.newton(lambda x: x**2 - 1, x0=2, + fprime=lambda x: 2*x) + assert_almost_equal(root, 1.0) + + def test_lmdif_errmsg(self): + # This shouldn't cause a crash on Python 3 + class SomeError(Exception): + pass + counter = [0] + + def func(x): + counter[0] += 1 + if counter[0] < 3: + return x**2 - np.array([9, 10, 11]) + else: + raise SomeError() + assert_raises(SomeError, + scipy.optimize.leastsq, + func, [1, 2, 3]) + diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_slsqp.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_slsqp.py new file mode 100644 index 0000000000000000000000000000000000000000..45216aa296b56a6a71b89c994e8fc360b826ba00 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_slsqp.py @@ -0,0 +1,613 @@ +""" +Unit test for SLSQP optimization. +""" +from numpy.testing import (assert_, assert_array_almost_equal, + assert_allclose, assert_equal) +from pytest import raises as assert_raises +import pytest +import numpy as np +import scipy + +from scipy.optimize import fmin_slsqp, minimize, Bounds, NonlinearConstraint + + +class MyCallBack: + """pass a custom callback function + + This makes sure it's being used. + """ + def __init__(self): + self.been_called = False + self.ncalls = 0 + + def __call__(self, x): + self.been_called = True + self.ncalls += 1 + + +class TestSLSQP: + """ + Test SLSQP algorithm using Example 14.4 from Numerical Methods for + Engineers by Steven Chapra and Raymond Canale. + This example maximizes the function f(x) = 2*x*y + 2*x - x**2 - 2*y**2, + which has a maximum at x=2, y=1. + """ + def setup_method(self): + self.opts = {'disp': False} + + def fun(self, d, sign=1.0): + """ + Arguments: + d - A list of two elements, where d[0] represents x and d[1] represents y + in the following equation. + sign - A multiplier for f. Since we want to optimize it, and the SciPy + optimizers can only minimize functions, we need to multiply it by + -1 to achieve the desired solution + Returns: + 2*x*y + 2*x - x**2 - 2*y**2 + + """ + x = d[0] + y = d[1] + return sign*(2*x*y + 2*x - x**2 - 2*y**2) + + def jac(self, d, sign=1.0): + """ + This is the derivative of fun, returning a NumPy array + representing df/dx and df/dy. + + """ + x = d[0] + y = d[1] + dfdx = sign*(-2*x + 2*y + 2) + dfdy = sign*(2*x - 4*y) + return np.array([dfdx, dfdy], float) + + def fun_and_jac(self, d, sign=1.0): + return self.fun(d, sign), self.jac(d, sign) + + def f_eqcon(self, x, sign=1.0): + """ Equality constraint """ + return np.array([x[0] - x[1]]) + + def fprime_eqcon(self, x, sign=1.0): + """ Equality constraint, derivative """ + return np.array([[1, -1]]) + + def f_eqcon_scalar(self, x, sign=1.0): + """ Scalar equality constraint """ + return self.f_eqcon(x, sign)[0] + + def fprime_eqcon_scalar(self, x, sign=1.0): + """ Scalar equality constraint, derivative """ + return self.fprime_eqcon(x, sign)[0].tolist() + + def f_ieqcon(self, x, sign=1.0): + """ Inequality constraint """ + return np.array([x[0] - x[1] - 1.0]) + + def fprime_ieqcon(self, x, sign=1.0): + """ Inequality constraint, derivative """ + return np.array([[1, -1]]) + + def f_ieqcon2(self, x): + """ Vector inequality constraint """ + return np.asarray(x) + + def fprime_ieqcon2(self, x): + """ Vector inequality constraint, derivative """ + return np.identity(x.shape[0]) + + # minimize + def test_minimize_unbounded_approximated(self): + # Minimize, method='SLSQP': unbounded, approximated jacobian. + jacs = [None, False, '2-point', '3-point'] + for jac in jacs: + res = minimize(self.fun, [-1.0, 1.0], args=(-1.0, ), + jac=jac, method='SLSQP', + options=self.opts) + assert_(res['success'], res['message']) + assert_allclose(res.x, [2, 1]) + + def test_minimize_unbounded_given(self): + # Minimize, method='SLSQP': unbounded, given Jacobian. + res = minimize(self.fun, [-1.0, 1.0], args=(-1.0, ), + jac=self.jac, method='SLSQP', options=self.opts) + assert_(res['success'], res['message']) + assert_allclose(res.x, [2, 1]) + + def test_minimize_bounded_approximated(self): + # Minimize, method='SLSQP': bounded, approximated jacobian. + jacs = [None, False, '2-point', '3-point'] + for jac in jacs: + with np.errstate(invalid='ignore'): + res = minimize(self.fun, [-1.0, 1.0], args=(-1.0, ), + jac=jac, + bounds=((2.5, None), (None, 0.5)), + method='SLSQP', options=self.opts) + assert_(res['success'], res['message']) + assert_allclose(res.x, [2.5, 0.5]) + assert_(2.5 <= res.x[0]) + assert_(res.x[1] <= 0.5) + + def test_minimize_unbounded_combined(self): + # Minimize, method='SLSQP': unbounded, combined function and Jacobian. + res = minimize(self.fun_and_jac, [-1.0, 1.0], args=(-1.0, ), + jac=True, method='SLSQP', options=self.opts) + assert_(res['success'], res['message']) + assert_allclose(res.x, [2, 1]) + + def test_minimize_equality_approximated(self): + # Minimize with method='SLSQP': equality constraint, approx. jacobian. + jacs = [None, False, '2-point', '3-point'] + for jac in jacs: + res = minimize(self.fun, [-1.0, 1.0], args=(-1.0, ), + jac=jac, + constraints={'type': 'eq', + 'fun': self.f_eqcon, + 'args': (-1.0, )}, + method='SLSQP', options=self.opts) + assert_(res['success'], res['message']) + assert_allclose(res.x, [1, 1]) + + def test_minimize_equality_given(self): + # Minimize with method='SLSQP': equality constraint, given Jacobian. + res = minimize(self.fun, [-1.0, 1.0], jac=self.jac, + method='SLSQP', args=(-1.0,), + constraints={'type': 'eq', 'fun':self.f_eqcon, + 'args': (-1.0, )}, + options=self.opts) + assert_(res['success'], res['message']) + assert_allclose(res.x, [1, 1]) + + def test_minimize_equality_given2(self): + # Minimize with method='SLSQP': equality constraint, given Jacobian + # for fun and const. + res = minimize(self.fun, [-1.0, 1.0], method='SLSQP', + jac=self.jac, args=(-1.0,), + constraints={'type': 'eq', + 'fun': self.f_eqcon, + 'args': (-1.0, ), + 'jac': self.fprime_eqcon}, + options=self.opts) + assert_(res['success'], res['message']) + assert_allclose(res.x, [1, 1]) + + def test_minimize_equality_given_cons_scalar(self): + # Minimize with method='SLSQP': scalar equality constraint, given + # Jacobian for fun and const. + res = minimize(self.fun, [-1.0, 1.0], method='SLSQP', + jac=self.jac, args=(-1.0,), + constraints={'type': 'eq', + 'fun': self.f_eqcon_scalar, + 'args': (-1.0, ), + 'jac': self.fprime_eqcon_scalar}, + options=self.opts) + assert_(res['success'], res['message']) + assert_allclose(res.x, [1, 1]) + + def test_minimize_inequality_given(self): + # Minimize with method='SLSQP': inequality constraint, given Jacobian. + res = minimize(self.fun, [-1.0, 1.0], method='SLSQP', + jac=self.jac, args=(-1.0, ), + constraints={'type': 'ineq', + 'fun': self.f_ieqcon, + 'args': (-1.0, )}, + options=self.opts) + assert_(res['success'], res['message']) + assert_allclose(res.x, [2, 1], atol=1e-3) + + def test_minimize_inequality_given_vector_constraints(self): + # Minimize with method='SLSQP': vector inequality constraint, given + # Jacobian. + res = minimize(self.fun, [-1.0, 1.0], jac=self.jac, + method='SLSQP', args=(-1.0,), + constraints={'type': 'ineq', + 'fun': self.f_ieqcon2, + 'jac': self.fprime_ieqcon2}, + options=self.opts) + assert_(res['success'], res['message']) + assert_allclose(res.x, [2, 1]) + + def test_minimize_bounded_constraint(self): + # when the constraint makes the solver go up against a parameter + # bound make sure that the numerical differentiation of the + # jacobian doesn't try to exceed that bound using a finite difference. + # gh11403 + def c(x): + assert 0 <= x[0] <= 1 and 0 <= x[1] <= 1, x + return x[0] ** 0.5 + x[1] + + def f(x): + assert 0 <= x[0] <= 1 and 0 <= x[1] <= 1, x + return -x[0] ** 2 + x[1] ** 2 + + cns = [NonlinearConstraint(c, 0, 1.5)] + x0 = np.asarray([0.9, 0.5]) + bnd = Bounds([0., 0.], [1.0, 1.0]) + minimize(f, x0, method='SLSQP', bounds=bnd, constraints=cns) + + def test_minimize_bound_equality_given2(self): + # Minimize with method='SLSQP': bounds, eq. const., given jac. for + # fun. and const. + res = minimize(self.fun, [-1.0, 1.0], method='SLSQP', + jac=self.jac, args=(-1.0, ), + bounds=[(-0.8, 1.), (-1, 0.8)], + constraints={'type': 'eq', + 'fun': self.f_eqcon, + 'args': (-1.0, ), + 'jac': self.fprime_eqcon}, + options=self.opts) + assert_(res['success'], res['message']) + assert_allclose(res.x, [0.8, 0.8], atol=1e-3) + assert_(-0.8 <= res.x[0] <= 1) + assert_(-1 <= res.x[1] <= 0.8) + + # fmin_slsqp + def test_unbounded_approximated(self): + # SLSQP: unbounded, approximated Jacobian. + res = fmin_slsqp(self.fun, [-1.0, 1.0], args=(-1.0, ), + iprint = 0, full_output = 1) + x, fx, its, imode, smode = res + assert_(imode == 0, imode) + assert_array_almost_equal(x, [2, 1]) + + def test_unbounded_given(self): + # SLSQP: unbounded, given Jacobian. + res = fmin_slsqp(self.fun, [-1.0, 1.0], args=(-1.0, ), + fprime = self.jac, iprint = 0, + full_output = 1) + x, fx, its, imode, smode = res + assert_(imode == 0, imode) + assert_array_almost_equal(x, [2, 1]) + + def test_equality_approximated(self): + # SLSQP: equality constraint, approximated Jacobian. + res = fmin_slsqp(self.fun,[-1.0,1.0], args=(-1.0,), + eqcons = [self.f_eqcon], + iprint = 0, full_output = 1) + x, fx, its, imode, smode = res + assert_(imode == 0, imode) + assert_array_almost_equal(x, [1, 1]) + + def test_equality_given(self): + # SLSQP: equality constraint, given Jacobian. + res = fmin_slsqp(self.fun, [-1.0, 1.0], + fprime=self.jac, args=(-1.0,), + eqcons = [self.f_eqcon], iprint = 0, + full_output = 1) + x, fx, its, imode, smode = res + assert_(imode == 0, imode) + assert_array_almost_equal(x, [1, 1]) + + def test_equality_given2(self): + # SLSQP: equality constraint, given Jacobian for fun and const. + res = fmin_slsqp(self.fun, [-1.0, 1.0], + fprime=self.jac, args=(-1.0,), + f_eqcons = self.f_eqcon, + fprime_eqcons = self.fprime_eqcon, + iprint = 0, + full_output = 1) + x, fx, its, imode, smode = res + assert_(imode == 0, imode) + assert_array_almost_equal(x, [1, 1]) + + def test_inequality_given(self): + # SLSQP: inequality constraint, given Jacobian. + res = fmin_slsqp(self.fun, [-1.0, 1.0], + fprime=self.jac, args=(-1.0, ), + ieqcons = [self.f_ieqcon], + iprint = 0, full_output = 1) + x, fx, its, imode, smode = res + assert_(imode == 0, imode) + assert_array_almost_equal(x, [2, 1], decimal=3) + + def test_bound_equality_given2(self): + # SLSQP: bounds, eq. const., given jac. for fun. and const. + res = fmin_slsqp(self.fun, [-1.0, 1.0], + fprime=self.jac, args=(-1.0, ), + bounds = [(-0.8, 1.), (-1, 0.8)], + f_eqcons = self.f_eqcon, + fprime_eqcons = self.fprime_eqcon, + iprint = 0, full_output = 1) + x, fx, its, imode, smode = res + assert_(imode == 0, imode) + assert_array_almost_equal(x, [0.8, 0.8], decimal=3) + assert_(-0.8 <= x[0] <= 1) + assert_(-1 <= x[1] <= 0.8) + + def test_scalar_constraints(self): + # Regression test for gh-2182 + x = fmin_slsqp(lambda z: z**2, [3.], + ieqcons=[lambda z: z[0] - 1], + iprint=0) + assert_array_almost_equal(x, [1.]) + + x = fmin_slsqp(lambda z: z**2, [3.], + f_ieqcons=lambda z: [z[0] - 1], + iprint=0) + assert_array_almost_equal(x, [1.]) + + def test_integer_bounds(self): + # This should not raise an exception + fmin_slsqp(lambda z: z**2 - 1, [0], bounds=[[0, 1]], iprint=0) + + def test_array_bounds(self): + # NumPy used to treat n-dimensional 1-element arrays as scalars + # in some cases. The handling of `bounds` by `fmin_slsqp` still + # supports this behavior. + bounds = [(-np.inf, np.inf), (np.array([2]), np.array([3]))] + x = fmin_slsqp(lambda z: np.sum(z**2 - 1), [2.5, 2.5], bounds=bounds, + iprint=0) + assert_array_almost_equal(x, [0, 2]) + + def test_obj_must_return_scalar(self): + # Regression test for Github Issue #5433 + # If objective function does not return a scalar, raises ValueError + with assert_raises(ValueError): + fmin_slsqp(lambda x: [0, 1], [1, 2, 3]) + + def test_obj_returns_scalar_in_list(self): + # Test for Github Issue #5433 and PR #6691 + # Objective function should be able to return length-1 Python list + # containing the scalar + fmin_slsqp(lambda x: [0], [1, 2, 3], iprint=0) + + def test_callback(self): + # Minimize, method='SLSQP': unbounded, approximated jacobian. Check for callback + callback = MyCallBack() + res = minimize(self.fun, [-1.0, 1.0], args=(-1.0, ), + method='SLSQP', callback=callback, options=self.opts) + assert_(res['success'], res['message']) + assert_(callback.been_called) + assert_equal(callback.ncalls, res['nit']) + + def test_inconsistent_linearization(self): + # SLSQP must be able to solve this problem, even if the + # linearized problem at the starting point is infeasible. + + # Linearized constraints are + # + # 2*x0[0]*x[0] >= 1 + # + # At x0 = [0, 1], the second constraint is clearly infeasible. + # This triggers a call with n2==1 in the LSQ subroutine. + x = [0, 1] + def f1(x): + return x[0] + x[1] - 2 + def f2(x): + return x[0] ** 2 - 1 + sol = minimize( + lambda x: x[0]**2 + x[1]**2, + x, + constraints=({'type':'eq','fun': f1}, + {'type':'ineq','fun': f2}), + bounds=((0,None), (0,None)), + method='SLSQP') + x = sol.x + + assert_allclose(f1(x), 0, atol=1e-8) + assert_(f2(x) >= -1e-8) + assert_(sol.success, sol) + + def test_regression_5743(self): + # SLSQP must not indicate success for this problem, + # which is infeasible. + x = [1, 2] + sol = minimize( + lambda x: x[0]**2 + x[1]**2, + x, + constraints=({'type':'eq','fun': lambda x: x[0]+x[1]-1}, + {'type':'ineq','fun': lambda x: x[0]-2}), + bounds=((0,None), (0,None)), + method='SLSQP') + assert_(not sol.success, sol) + + def test_gh_6676(self): + def func(x): + return (x[0] - 1)**2 + 2*(x[1] - 1)**2 + 0.5*(x[2] - 1)**2 + + sol = minimize(func, [0, 0, 0], method='SLSQP') + assert_(sol.jac.shape == (3,)) + + def test_invalid_bounds(self): + # Raise correct error when lower bound is greater than upper bound. + # See Github issue 6875. + bounds_list = [ + ((1, 2), (2, 1)), + ((2, 1), (1, 2)), + ((2, 1), (2, 1)), + ((np.inf, 0), (np.inf, 0)), + ((1, -np.inf), (0, 1)), + ] + for bounds in bounds_list: + with assert_raises(ValueError): + minimize(self.fun, [-1.0, 1.0], bounds=bounds, method='SLSQP') + + def test_bounds_clipping(self): + # + # SLSQP returns bogus results for initial guess out of bounds, gh-6859 + # + def f(x): + return (x[0] - 1)**2 + + sol = minimize(f, [10], method='slsqp', bounds=[(None, 0)]) + assert_(sol.success) + assert_allclose(sol.x, 0, atol=1e-10) + + sol = minimize(f, [-10], method='slsqp', bounds=[(2, None)]) + assert_(sol.success) + assert_allclose(sol.x, 2, atol=1e-10) + + sol = minimize(f, [-10], method='slsqp', bounds=[(None, 0)]) + assert_(sol.success) + assert_allclose(sol.x, 0, atol=1e-10) + + sol = minimize(f, [10], method='slsqp', bounds=[(2, None)]) + assert_(sol.success) + assert_allclose(sol.x, 2, atol=1e-10) + + sol = minimize(f, [-0.5], method='slsqp', bounds=[(-1, 0)]) + assert_(sol.success) + assert_allclose(sol.x, 0, atol=1e-10) + + sol = minimize(f, [10], method='slsqp', bounds=[(-1, 0)]) + assert_(sol.success) + assert_allclose(sol.x, 0, atol=1e-10) + + def test_infeasible_initial(self): + # Check SLSQP behavior with infeasible initial point + def f(x): + x, = x + return x*x - 2*x + 1 + + cons_u = [{'type': 'ineq', 'fun': lambda x: 0 - x}] + cons_l = [{'type': 'ineq', 'fun': lambda x: x - 2}] + cons_ul = [{'type': 'ineq', 'fun': lambda x: 0 - x}, + {'type': 'ineq', 'fun': lambda x: x + 1}] + + sol = minimize(f, [10], method='slsqp', constraints=cons_u) + assert_(sol.success) + assert_allclose(sol.x, 0, atol=1e-10) + + sol = minimize(f, [-10], method='slsqp', constraints=cons_l) + assert_(sol.success) + assert_allclose(sol.x, 2, atol=1e-10) + + sol = minimize(f, [-10], method='slsqp', constraints=cons_u) + assert_(sol.success) + assert_allclose(sol.x, 0, atol=1e-10) + + sol = minimize(f, [10], method='slsqp', constraints=cons_l) + assert_(sol.success) + assert_allclose(sol.x, 2, atol=1e-10) + + sol = minimize(f, [-0.5], method='slsqp', constraints=cons_ul) + assert_(sol.success) + assert_allclose(sol.x, 0, atol=1e-10) + + sol = minimize(f, [10], method='slsqp', constraints=cons_ul) + assert_(sol.success) + assert_allclose(sol.x, 0, atol=1e-10) + + @pytest.mark.xfail(scipy.show_config(mode='dicts')['Compilers']['fortran']['name'] + == "intel-llvm", + reason="Runtime warning due to floating point issues, not logic") + def test_inconsistent_inequalities(self): + # gh-7618 + + def cost(x): + return -1 * x[0] + 4 * x[1] + + def ineqcons1(x): + return x[1] - x[0] - 1 + + def ineqcons2(x): + return x[0] - x[1] + + # The inequalities are inconsistent, so no solution can exist: + # + # x1 >= x0 + 1 + # x0 >= x1 + + x0 = (1,5) + bounds = ((-5, 5), (-5, 5)) + cons = (dict(type='ineq', fun=ineqcons1), dict(type='ineq', fun=ineqcons2)) + res = minimize(cost, x0, method='SLSQP', bounds=bounds, constraints=cons) + + assert_(not res.success) + + def test_new_bounds_type(self): + def f(x): + return x[0] ** 2 + x[1] ** 2 + bounds = Bounds([1, 0], [np.inf, np.inf]) + sol = minimize(f, [0, 0], method='slsqp', bounds=bounds) + assert_(sol.success) + assert_allclose(sol.x, [1, 0]) + + def test_nested_minimization(self): + + class NestedProblem: + + def __init__(self): + self.F_outer_count = 0 + + def F_outer(self, x): + self.F_outer_count += 1 + if self.F_outer_count > 1000: + raise Exception("Nested minimization failed to terminate.") + inner_res = minimize(self.F_inner, (3, 4), method="SLSQP") + assert_(inner_res.success) + assert_allclose(inner_res.x, [1, 1]) + return x[0]**2 + x[1]**2 + x[2]**2 + + def F_inner(self, x): + return (x[0] - 1)**2 + (x[1] - 1)**2 + + def solve(self): + outer_res = minimize(self.F_outer, (5, 5, 5), method="SLSQP") + assert_(outer_res.success) + assert_allclose(outer_res.x, [0, 0, 0]) + + problem = NestedProblem() + problem.solve() + + def test_gh1758(self): + # the test suggested in gh1758 + # https://nlopt.readthedocs.io/en/latest/NLopt_Tutorial/ + # implement two equality constraints, in R^2. + def fun(x): + return np.sqrt(x[1]) + + def f_eqcon(x): + """ Equality constraint """ + return x[1] - (2 * x[0]) ** 3 + + def f_eqcon2(x): + """ Equality constraint """ + return x[1] - (-x[0] + 1) ** 3 + + c1 = {'type': 'eq', 'fun': f_eqcon} + c2 = {'type': 'eq', 'fun': f_eqcon2} + + res = minimize(fun, [8, 0.25], method='SLSQP', + constraints=[c1, c2], bounds=[(-0.5, 1), (0, 8)]) + + np.testing.assert_allclose(res.fun, 0.5443310539518) + np.testing.assert_allclose(res.x, [0.33333333, 0.2962963]) + assert res.success + + def test_gh9640(self): + np.random.seed(10) + cons = ({'type': 'ineq', 'fun': lambda x: -x[0] - x[1] - 3}, + {'type': 'ineq', 'fun': lambda x: x[1] + x[2] - 2}) + bnds = ((-2, 2), (-2, 2), (-2, 2)) + + def target(x): + return 1 + x0 = [-1.8869783504471584, -0.640096352696244, -0.8174212253407696] + res = minimize(target, x0, method='SLSQP', bounds=bnds, constraints=cons, + options={'disp':False, 'maxiter':10000}) + + # The problem is infeasible, so it cannot succeed + assert not res.success + + @pytest.mark.thread_unsafe + def test_parameters_stay_within_bounds(self): + # gh11403. For some problems the SLSQP Fortran code suggests a step + # outside one of the lower/upper bounds. When this happens + # approx_derivative complains because it's being asked to evaluate + # a gradient outside its domain. + np.random.seed(1) + bounds = Bounds(np.array([0.1]), np.array([1.0])) + n_inputs = len(bounds.lb) + x0 = np.array(bounds.lb + (bounds.ub - bounds.lb) * + np.random.random(n_inputs)) + + def f(x): + assert (x >= bounds.lb).all() + return np.linalg.norm(x) + + with pytest.warns(RuntimeWarning, match='x were outside bounds'): + res = minimize(f, x0, method='SLSQP', bounds=bounds) + assert res.success diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_tnc.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_tnc.py new file mode 100644 index 0000000000000000000000000000000000000000..2cde9837bfd08e62916660a9750d833629b6b547 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_tnc.py @@ -0,0 +1,345 @@ +""" +Unit tests for TNC optimization routine from tnc.py +""" +import pytest +from numpy.testing import assert_allclose, assert_equal + +import numpy as np +from math import pow + +from scipy import optimize + + +class TestTnc: + """TNC non-linear optimization. + + These tests are taken from Prof. K. Schittkowski's test examples + for constrained non-linear programming. + + http://www.uni-bayreuth.de/departments/math/~kschittkowski/home.htm + + """ + def setup_method(self): + # options for minimize + self.opts = {'disp': False, 'maxfun': 200} + + # objective functions and Jacobian for each test + def f1(self, x, a=100.0): + return a * pow((x[1] - pow(x[0], 2)), 2) + pow(1.0 - x[0], 2) + + def g1(self, x, a=100.0): + dif = [0, 0] + dif[1] = 2 * a * (x[1] - pow(x[0], 2)) + dif[0] = -2.0 * (x[0] * (dif[1] - 1.0) + 1.0) + return dif + + def fg1(self, x, a=100.0): + return self.f1(x, a), self.g1(x, a) + + def f3(self, x): + return x[1] + pow(x[1] - x[0], 2) * 1.0e-5 + + def g3(self, x): + dif = [0, 0] + dif[0] = -2.0 * (x[1] - x[0]) * 1.0e-5 + dif[1] = 1.0 - dif[0] + return dif + + def fg3(self, x): + return self.f3(x), self.g3(x) + + def f4(self, x): + return pow(x[0] + 1.0, 3) / 3.0 + x[1] + + def g4(self, x): + dif = [0, 0] + dif[0] = pow(x[0] + 1.0, 2) + dif[1] = 1.0 + return dif + + def fg4(self, x): + return self.f4(x), self.g4(x) + + def f5(self, x): + return np.sin(x[0] + x[1]) + pow(x[0] - x[1], 2) - \ + 1.5 * x[0] + 2.5 * x[1] + 1.0 + + def g5(self, x): + dif = [0, 0] + v1 = np.cos(x[0] + x[1]) + v2 = 2.0*(x[0] - x[1]) + + dif[0] = v1 + v2 - 1.5 + dif[1] = v1 - v2 + 2.5 + return dif + + def fg5(self, x): + return self.f5(x), self.g5(x) + + def f38(self, x): + return (100.0 * pow(x[1] - pow(x[0], 2), 2) + + pow(1.0 - x[0], 2) + 90.0 * pow(x[3] - pow(x[2], 2), 2) + + pow(1.0 - x[2], 2) + 10.1 * (pow(x[1] - 1.0, 2) + + pow(x[3] - 1.0, 2)) + + 19.8 * (x[1] - 1.0) * (x[3] - 1.0)) * 1.0e-5 + + def g38(self, x): + dif = [0, 0, 0, 0] + dif[0] = (-400.0 * x[0] * (x[1] - pow(x[0], 2)) - + 2.0 * (1.0 - x[0])) * 1.0e-5 + dif[1] = (200.0 * (x[1] - pow(x[0], 2)) + 20.2 * (x[1] - 1.0) + + 19.8 * (x[3] - 1.0)) * 1.0e-5 + dif[2] = (- 360.0 * x[2] * (x[3] - pow(x[2], 2)) - + 2.0 * (1.0 - x[2])) * 1.0e-5 + dif[3] = (180.0 * (x[3] - pow(x[2], 2)) + 20.2 * (x[3] - 1.0) + + 19.8 * (x[1] - 1.0)) * 1.0e-5 + return dif + + def fg38(self, x): + return self.f38(x), self.g38(x) + + def f45(self, x): + return 2.0 - x[0] * x[1] * x[2] * x[3] * x[4] / 120.0 + + def g45(self, x): + dif = [0] * 5 + dif[0] = - x[1] * x[2] * x[3] * x[4] / 120.0 + dif[1] = - x[0] * x[2] * x[3] * x[4] / 120.0 + dif[2] = - x[0] * x[1] * x[3] * x[4] / 120.0 + dif[3] = - x[0] * x[1] * x[2] * x[4] / 120.0 + dif[4] = - x[0] * x[1] * x[2] * x[3] / 120.0 + return dif + + def fg45(self, x): + return self.f45(x), self.g45(x) + + # tests + # minimize with method=TNC + def test_minimize_tnc1(self): + x0, bnds = [-2, 1], ([-np.inf, None], [-1.5, None]) + xopt = [1, 1] + iterx = [] # to test callback + + res = optimize.minimize(self.f1, x0, method='TNC', jac=self.g1, + bounds=bnds, options=self.opts, + callback=iterx.append) + assert_allclose(res.fun, self.f1(xopt), atol=1e-8) + assert_equal(len(iterx), res.nit) + + def test_minimize_tnc1b(self): + x0, bnds = np.array([-2, 1]), ([-np.inf, None], [-1.5, None]) + xopt = [1, 1] + x = optimize.minimize(self.f1, x0, method='TNC', + bounds=bnds, options=self.opts).x + assert_allclose(self.f1(x), self.f1(xopt), atol=1e-4) + + def test_minimize_tnc1c(self): + x0, bnds = [-2, 1], ([-np.inf, None],[-1.5, None]) + xopt = [1, 1] + x = optimize.minimize(self.fg1, x0, method='TNC', + jac=True, bounds=bnds, + options=self.opts).x + assert_allclose(self.f1(x), self.f1(xopt), atol=1e-8) + + def test_minimize_tnc2(self): + x0, bnds = [-2, 1], ([-np.inf, None], [1.5, None]) + xopt = [-1.2210262419616387, 1.5] + x = optimize.minimize(self.f1, x0, method='TNC', + jac=self.g1, bounds=bnds, + options=self.opts).x + assert_allclose(self.f1(x), self.f1(xopt), atol=1e-8) + + def test_minimize_tnc3(self): + x0, bnds = [10, 1], ([-np.inf, None], [0.0, None]) + xopt = [0, 0] + x = optimize.minimize(self.f3, x0, method='TNC', + jac=self.g3, bounds=bnds, + options=self.opts).x + assert_allclose(self.f3(x), self.f3(xopt), atol=1e-8) + + def test_minimize_tnc4(self): + x0,bnds = [1.125, 0.125], [(1, None), (0, None)] + xopt = [1, 0] + x = optimize.minimize(self.f4, x0, method='TNC', + jac=self.g4, bounds=bnds, + options=self.opts).x + assert_allclose(self.f4(x), self.f4(xopt), atol=1e-8) + + def test_minimize_tnc5(self): + x0, bnds = [0, 0], [(-1.5, 4),(-3, 3)] + xopt = [-0.54719755119659763, -1.5471975511965976] + x = optimize.minimize(self.f5, x0, method='TNC', + jac=self.g5, bounds=bnds, + options=self.opts).x + assert_allclose(self.f5(x), self.f5(xopt), atol=1e-8) + + def test_minimize_tnc38(self): + x0, bnds = np.array([-3, -1, -3, -1]), [(-10, 10)]*4 + xopt = [1]*4 + x = optimize.minimize(self.f38, x0, method='TNC', + jac=self.g38, bounds=bnds, + options=self.opts).x + assert_allclose(self.f38(x), self.f38(xopt), atol=1e-8) + + def test_minimize_tnc45(self): + x0, bnds = [2] * 5, [(0, 1), (0, 2), (0, 3), (0, 4), (0, 5)] + xopt = [1, 2, 3, 4, 5] + x = optimize.minimize(self.f45, x0, method='TNC', + jac=self.g45, bounds=bnds, + options=self.opts).x + assert_allclose(self.f45(x), self.f45(xopt), atol=1e-8) + + # fmin_tnc + def test_tnc1(self): + fg, x, bounds = self.fg1, [-2, 1], ([-np.inf, None], [-1.5, None]) + xopt = [1, 1] + + x, nf, rc = optimize.fmin_tnc(fg, x, bounds=bounds, args=(100.0, ), + messages=optimize._tnc.MSG_NONE, + maxfun=200) + + assert_allclose(self.f1(x), self.f1(xopt), atol=1e-8, + err_msg="TNC failed with status: " + + optimize._tnc.RCSTRINGS[rc]) + + def test_tnc1b(self): + x, bounds = [-2, 1], ([-np.inf, None], [-1.5, None]) + xopt = [1, 1] + + x, nf, rc = optimize.fmin_tnc(self.f1, x, approx_grad=True, + bounds=bounds, + messages=optimize._tnc.MSG_NONE, + maxfun=200) + + assert_allclose(self.f1(x), self.f1(xopt), atol=1e-4, + err_msg="TNC failed with status: " + + optimize._tnc.RCSTRINGS[rc]) + + def test_tnc1c(self): + x, bounds = [-2, 1], ([-np.inf, None], [-1.5, None]) + xopt = [1, 1] + + x, nf, rc = optimize.fmin_tnc(self.f1, x, fprime=self.g1, + bounds=bounds, + messages=optimize._tnc.MSG_NONE, + maxfun=200) + + assert_allclose(self.f1(x), self.f1(xopt), atol=1e-8, + err_msg="TNC failed with status: " + + optimize._tnc.RCSTRINGS[rc]) + + def test_tnc2(self): + fg, x, bounds = self.fg1, [-2, 1], ([-np.inf, None], [1.5, None]) + xopt = [-1.2210262419616387, 1.5] + + x, nf, rc = optimize.fmin_tnc(fg, x, bounds=bounds, + messages=optimize._tnc.MSG_NONE, + maxfun=200) + + assert_allclose(self.f1(x), self.f1(xopt), atol=1e-8, + err_msg="TNC failed with status: " + + optimize._tnc.RCSTRINGS[rc]) + + def test_tnc3(self): + fg, x, bounds = self.fg3, [10, 1], ([-np.inf, None], [0.0, None]) + xopt = [0, 0] + + x, nf, rc = optimize.fmin_tnc(fg, x, bounds=bounds, + messages=optimize._tnc.MSG_NONE, + maxfun=200) + + assert_allclose(self.f3(x), self.f3(xopt), atol=1e-8, + err_msg="TNC failed with status: " + + optimize._tnc.RCSTRINGS[rc]) + + def test_tnc4(self): + fg, x, bounds = self.fg4, [1.125, 0.125], [(1, None), (0, None)] + xopt = [1, 0] + + x, nf, rc = optimize.fmin_tnc(fg, x, bounds=bounds, + messages=optimize._tnc.MSG_NONE, + maxfun=200) + + assert_allclose(self.f4(x), self.f4(xopt), atol=1e-8, + err_msg="TNC failed with status: " + + optimize._tnc.RCSTRINGS[rc]) + + def test_tnc5(self): + fg, x, bounds = self.fg5, [0, 0], [(-1.5, 4),(-3, 3)] + xopt = [-0.54719755119659763, -1.5471975511965976] + + x, nf, rc = optimize.fmin_tnc(fg, x, bounds=bounds, + messages=optimize._tnc.MSG_NONE, + maxfun=200) + + assert_allclose(self.f5(x), self.f5(xopt), atol=1e-8, + err_msg="TNC failed with status: " + + optimize._tnc.RCSTRINGS[rc]) + + def test_tnc38(self): + fg, x, bounds = self.fg38, np.array([-3, -1, -3, -1]), [(-10, 10)]*4 + xopt = [1]*4 + + x, nf, rc = optimize.fmin_tnc(fg, x, bounds=bounds, + messages=optimize._tnc.MSG_NONE, + maxfun=200) + + assert_allclose(self.f38(x), self.f38(xopt), atol=1e-8, + err_msg="TNC failed with status: " + + optimize._tnc.RCSTRINGS[rc]) + + def test_tnc45(self): + fg, x, bounds = self.fg45, [2] * 5, [(0, 1), (0, 2), (0, 3), + (0, 4), (0, 5)] + xopt = [1, 2, 3, 4, 5] + + x, nf, rc = optimize.fmin_tnc(fg, x, bounds=bounds, + messages=optimize._tnc.MSG_NONE, + maxfun=200) + + assert_allclose(self.f45(x), self.f45(xopt), atol=1e-8, + err_msg="TNC failed with status: " + + optimize._tnc.RCSTRINGS[rc]) + + def test_raising_exceptions(self): + # tnc was ported to cython from hand-crafted cpython code + # check that Exception handling works. + def myfunc(x): + raise RuntimeError("myfunc") + + def myfunc1(x): + return optimize.rosen(x) + + def callback(x): + raise ValueError("callback") + + with pytest.raises(RuntimeError): + optimize.minimize(myfunc, [0, 1], method="TNC") + + with pytest.raises(ValueError): + optimize.minimize( + myfunc1, [0, 1], method="TNC", callback=callback + ) + + def test_callback_shouldnt_affect_minimization(self): + # gh14879. The output of a TNC minimization was different depending + # on whether a callback was used or not. The two should be equivalent. + # The issue was that TNC was unscaling/scaling x, and this process was + # altering x in the process. Now the callback uses an unscaled + # temporary copy of x. + def callback(x): + pass + + fun = optimize.rosen + bounds = [(0, 10)] * 4 + x0 = [1, 2, 3, 4.] + res = optimize.minimize( + fun, x0, bounds=bounds, method="TNC", options={"maxfun": 1000} + ) + res2 = optimize.minimize( + fun, x0, bounds=bounds, method="TNC", options={"maxfun": 1000}, + callback=callback + ) + assert_allclose(res2.x, res.x) + assert_allclose(res2.fun, res.fun) + assert_equal(res2.nfev, res.nfev) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_trustregion.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_trustregion.py new file mode 100644 index 0000000000000000000000000000000000000000..0439f8125c565d70cbed8c6c41f762fdae06d4ce --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_trustregion.py @@ -0,0 +1,110 @@ +""" +Unit tests for trust-region optimization routines. + +""" +import pytest +import numpy as np +from numpy.testing import assert_, assert_equal, assert_allclose +from scipy.optimize import (minimize, rosen, rosen_der, rosen_hess, + rosen_hess_prod) + + +class Accumulator: + """ This is for testing callbacks.""" + def __init__(self): + self.count = 0 + self.accum = None + + def __call__(self, x): + self.count += 1 + if self.accum is None: + self.accum = np.array(x) + else: + self.accum += x + + +class TestTrustRegionSolvers: + + def setup_method(self): + self.x_opt = [1.0, 1.0] + self.easy_guess = [2.0, 2.0] + self.hard_guess = [-1.2, 1.0] + + def test_dogleg_accuracy(self): + # test the accuracy and the return_all option + x0 = self.hard_guess + r = minimize(rosen, x0, jac=rosen_der, hess=rosen_hess, tol=1e-8, + method='dogleg', options={'return_all': True},) + assert_allclose(x0, r['allvecs'][0]) + assert_allclose(r['x'], r['allvecs'][-1]) + assert_allclose(r['x'], self.x_opt) + + def test_dogleg_callback(self): + # test the callback mechanism and the maxiter and return_all options + accumulator = Accumulator() + maxiter = 5 + r = minimize(rosen, self.hard_guess, jac=rosen_der, hess=rosen_hess, + callback=accumulator, method='dogleg', + options={'return_all': True, 'maxiter': maxiter},) + assert_equal(accumulator.count, maxiter) + assert_equal(len(r['allvecs']), maxiter+1) + assert_allclose(r['x'], r['allvecs'][-1]) + assert_allclose(sum(r['allvecs'][1:]), accumulator.accum) + + @pytest.mark.thread_unsafe + def test_dogleg_user_warning(self): + with pytest.warns(RuntimeWarning, + match=r'Maximum number of iterations'): + minimize(rosen, self.hard_guess, jac=rosen_der, + hess=rosen_hess, method='dogleg', + options={'disp': True, 'maxiter': 1}, ) + + def test_solver_concordance(self): + # Assert that dogleg uses fewer iterations than ncg on the Rosenbrock + # test function, although this does not necessarily mean + # that dogleg is faster or better than ncg even for this function + # and especially not for other test functions. + f = rosen + g = rosen_der + h = rosen_hess + for x0 in (self.easy_guess, self.hard_guess): + r_dogleg = minimize(f, x0, jac=g, hess=h, tol=1e-8, + method='dogleg', options={'return_all': True}) + r_trust_ncg = minimize(f, x0, jac=g, hess=h, tol=1e-8, + method='trust-ncg', + options={'return_all': True}) + r_trust_krylov = minimize(f, x0, jac=g, hess=h, tol=1e-8, + method='trust-krylov', + options={'return_all': True}) + r_ncg = minimize(f, x0, jac=g, hess=h, tol=1e-8, + method='newton-cg', options={'return_all': True}) + r_iterative = minimize(f, x0, jac=g, hess=h, tol=1e-8, + method='trust-exact', + options={'return_all': True}) + assert_allclose(self.x_opt, r_dogleg['x']) + assert_allclose(self.x_opt, r_trust_ncg['x']) + assert_allclose(self.x_opt, r_trust_krylov['x']) + assert_allclose(self.x_opt, r_ncg['x']) + assert_allclose(self.x_opt, r_iterative['x']) + assert_(len(r_dogleg['allvecs']) < len(r_ncg['allvecs'])) + + def test_trust_ncg_hessp(self): + for x0 in (self.easy_guess, self.hard_guess, self.x_opt): + r = minimize(rosen, x0, jac=rosen_der, hessp=rosen_hess_prod, + tol=1e-8, method='trust-ncg') + assert_allclose(self.x_opt, r['x']) + + def test_trust_ncg_start_in_optimum(self): + r = minimize(rosen, x0=self.x_opt, jac=rosen_der, hess=rosen_hess, + tol=1e-8, method='trust-ncg') + assert_allclose(self.x_opt, r['x']) + + def test_trust_krylov_start_in_optimum(self): + r = minimize(rosen, x0=self.x_opt, jac=rosen_der, hess=rosen_hess, + tol=1e-8, method='trust-krylov') + assert_allclose(self.x_opt, r['x']) + + def test_trust_exact_start_in_optimum(self): + r = minimize(rosen, x0=self.x_opt, jac=rosen_der, hess=rosen_hess, + tol=1e-8, method='trust-exact') + assert_allclose(self.x_opt, r['x']) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_trustregion_exact.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_trustregion_exact.py new file mode 100644 index 0000000000000000000000000000000000000000..020b6d883a5fa59006c142df4fcb8c3e115c46bf --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_trustregion_exact.py @@ -0,0 +1,351 @@ +""" +Unit tests for trust-region iterative subproblem. + +""" +import pytest +import numpy as np +from scipy.optimize._trustregion_exact import ( + estimate_smallest_singular_value, + singular_leading_submatrix, + IterativeSubproblem) +from scipy.linalg import (svd, get_lapack_funcs, det, qr, norm) +from numpy.testing import (assert_array_equal, + assert_equal, assert_array_almost_equal) + + +def random_entry(n, min_eig, max_eig, case): + + # Generate random matrix + rand = np.random.uniform(-1, 1, (n, n)) + + # QR decomposition + Q, _, _ = qr(rand, pivoting='True') + + # Generate random eigenvalues + eigvalues = np.random.uniform(min_eig, max_eig, n) + eigvalues = np.sort(eigvalues)[::-1] + + # Generate matrix + Qaux = np.multiply(eigvalues, Q) + A = np.dot(Qaux, Q.T) + + # Generate gradient vector accordingly + # to the case is being tested. + if case == 'hard': + g = np.zeros(n) + g[:-1] = np.random.uniform(-1, 1, n-1) + g = np.dot(Q, g) + elif case == 'jac_equal_zero': + g = np.zeros(n) + else: + g = np.random.uniform(-1, 1, n) + + return A, g + + +class TestEstimateSmallestSingularValue: + + def test_for_ill_condiotioned_matrix(self): + + # Ill-conditioned triangular matrix + C = np.array([[1, 2, 3, 4], + [0, 0.05, 60, 7], + [0, 0, 0.8, 9], + [0, 0, 0, 10]]) + + # Get svd decomposition + U, s, Vt = svd(C) + + # Get smallest singular value and correspondent right singular vector. + smin_svd = s[-1] + zmin_svd = Vt[-1, :] + + # Estimate smallest singular value + smin, zmin = estimate_smallest_singular_value(C) + + # Check the estimation + assert_array_almost_equal(smin, smin_svd, decimal=8) + assert_array_almost_equal(abs(zmin), abs(zmin_svd), decimal=8) + + +class TestSingularLeadingSubmatrix: + + def test_for_already_singular_leading_submatrix(self): + + # Define test matrix A. + # Note that the leading 2x2 submatrix is singular. + A = np.array([[1, 2, 3], + [2, 4, 5], + [3, 5, 6]]) + + # Get Cholesky from lapack functions + cholesky, = get_lapack_funcs(('potrf',), (A,)) + + # Compute Cholesky Decomposition + c, k = cholesky(A, lower=False, overwrite_a=False, clean=True) + + delta, v = singular_leading_submatrix(A, c, k) + + A[k-1, k-1] += delta + + # Check if the leading submatrix is singular. + assert_array_almost_equal(det(A[:k, :k]), 0) + + # Check if `v` fulfil the specified properties + quadratic_term = np.dot(v, np.dot(A, v)) + assert_array_almost_equal(quadratic_term, 0) + + def test_for_simetric_indefinite_matrix(self): + + # Define test matrix A. + # Note that the leading 5x5 submatrix is indefinite. + A = np.asarray([[1, 2, 3, 7, 8], + [2, 5, 5, 9, 0], + [3, 5, 11, 1, 2], + [7, 9, 1, 7, 5], + [8, 0, 2, 5, 8]]) + + # Get Cholesky from lapack functions + cholesky, = get_lapack_funcs(('potrf',), (A,)) + + # Compute Cholesky Decomposition + c, k = cholesky(A, lower=False, overwrite_a=False, clean=True) + + delta, v = singular_leading_submatrix(A, c, k) + + A[k-1, k-1] += delta + + # Check if the leading submatrix is singular. + assert_array_almost_equal(det(A[:k, :k]), 0) + + # Check if `v` fulfil the specified properties + quadratic_term = np.dot(v, np.dot(A, v)) + assert_array_almost_equal(quadratic_term, 0) + + def test_for_first_element_equal_to_zero(self): + + # Define test matrix A. + # Note that the leading 2x2 submatrix is singular. + A = np.array([[0, 3, 11], + [3, 12, 5], + [11, 5, 6]]) + + # Get Cholesky from lapack functions + cholesky, = get_lapack_funcs(('potrf',), (A,)) + + # Compute Cholesky Decomposition + c, k = cholesky(A, lower=False, overwrite_a=False, clean=True) + + delta, v = singular_leading_submatrix(A, c, k) + + A[k-1, k-1] += delta + + # Check if the leading submatrix is singular + assert_array_almost_equal(det(A[:k, :k]), 0) + + # Check if `v` fulfil the specified properties + quadratic_term = np.dot(v, np.dot(A, v)) + assert_array_almost_equal(quadratic_term, 0) + + +class TestIterativeSubproblem: + + def test_for_the_easy_case(self): + + # `H` is chosen such that `g` is not orthogonal to the + # eigenvector associated with the smallest eigenvalue `s`. + H = [[10, 2, 3, 4], + [2, 1, 7, 1], + [3, 7, 1, 7], + [4, 1, 7, 2]] + g = [1, 1, 1, 1] + + # Trust Radius + trust_radius = 1 + + # Solve Subproblem + subprob = IterativeSubproblem(x=0, + fun=lambda x: 0, + jac=lambda x: np.array(g), + hess=lambda x: np.array(H), + k_easy=1e-10, + k_hard=1e-10) + p, hits_boundary = subprob.solve(trust_radius) + + assert_array_almost_equal(p, [0.00393332, -0.55260862, + 0.67065477, -0.49480341]) + assert_array_almost_equal(hits_boundary, True) + + def test_for_the_hard_case(self): + + # `H` is chosen such that `g` is orthogonal to the + # eigenvector associated with the smallest eigenvalue `s`. + H = [[10, 2, 3, 4], + [2, 1, 7, 1], + [3, 7, 1, 7], + [4, 1, 7, 2]] + g = [6.4852641521327437, 1, 1, 1] + s = -8.2151519874416614 + + # Trust Radius + trust_radius = 1 + + # Solve Subproblem + subprob = IterativeSubproblem(x=0, + fun=lambda x: 0, + jac=lambda x: np.array(g), + hess=lambda x: np.array(H), + k_easy=1e-10, + k_hard=1e-10) + p, hits_boundary = subprob.solve(trust_radius) + + assert_array_almost_equal(-s, subprob.lambda_current) + + def test_for_interior_convergence(self): + + H = [[1.812159, 0.82687265, 0.21838879, -0.52487006, 0.25436988], + [0.82687265, 2.66380283, 0.31508988, -0.40144163, 0.08811588], + [0.21838879, 0.31508988, 2.38020726, -0.3166346, 0.27363867], + [-0.52487006, -0.40144163, -0.3166346, 1.61927182, -0.42140166], + [0.25436988, 0.08811588, 0.27363867, -0.42140166, 1.33243101]] + + g = [0.75798952, 0.01421945, 0.33847612, 0.83725004, -0.47909534] + + # Solve Subproblem + subprob = IterativeSubproblem(x=0, + fun=lambda x: 0, + jac=lambda x: np.array(g), + hess=lambda x: np.array(H)) + p, hits_boundary = subprob.solve(1.1) + + assert_array_almost_equal(p, [-0.68585435, 0.1222621, -0.22090999, + -0.67005053, 0.31586769]) + assert_array_almost_equal(hits_boundary, False) + assert_array_almost_equal(subprob.lambda_current, 0) + assert_array_almost_equal(subprob.niter, 1) + + def test_for_jac_equal_zero(self): + + H = [[0.88547534, 2.90692271, 0.98440885, -0.78911503, -0.28035809], + [2.90692271, -0.04618819, 0.32867263, -0.83737945, 0.17116396], + [0.98440885, 0.32867263, -0.87355957, -0.06521957, -1.43030957], + [-0.78911503, -0.83737945, -0.06521957, -1.645709, -0.33887298], + [-0.28035809, 0.17116396, -1.43030957, -0.33887298, -1.68586978]] + + g = [0, 0, 0, 0, 0] + + # Solve Subproblem + subprob = IterativeSubproblem(x=0, + fun=lambda x: 0, + jac=lambda x: np.array(g), + hess=lambda x: np.array(H), + k_easy=1e-10, + k_hard=1e-10) + p, hits_boundary = subprob.solve(1.1) + + assert_array_almost_equal(p, [0.06910534, -0.01432721, + -0.65311947, -0.23815972, + -0.84954934]) + assert_array_almost_equal(hits_boundary, True) + + def test_for_jac_very_close_to_zero(self): + + H = [[0.88547534, 2.90692271, 0.98440885, -0.78911503, -0.28035809], + [2.90692271, -0.04618819, 0.32867263, -0.83737945, 0.17116396], + [0.98440885, 0.32867263, -0.87355957, -0.06521957, -1.43030957], + [-0.78911503, -0.83737945, -0.06521957, -1.645709, -0.33887298], + [-0.28035809, 0.17116396, -1.43030957, -0.33887298, -1.68586978]] + + g = [0, 0, 0, 0, 1e-15] + + # Solve Subproblem + subprob = IterativeSubproblem(x=0, + fun=lambda x: 0, + jac=lambda x: np.array(g), + hess=lambda x: np.array(H), + k_easy=1e-10, + k_hard=1e-10) + p, hits_boundary = subprob.solve(1.1) + + assert_array_almost_equal(p, [0.06910534, -0.01432721, + -0.65311947, -0.23815972, + -0.84954934]) + assert_array_almost_equal(hits_boundary, True) + + @pytest.mark.fail_slow(10) + def test_for_random_entries(self): + # Seed + np.random.seed(1) + + # Dimension + n = 5 + + for case in ('easy', 'hard', 'jac_equal_zero'): + + eig_limits = [(-20, -15), + (-10, -5), + (-10, 0), + (-5, 5), + (-10, 10), + (0, 10), + (5, 10), + (15, 20)] + + for min_eig, max_eig in eig_limits: + # Generate random symmetric matrix H with + # eigenvalues between min_eig and max_eig. + H, g = random_entry(n, min_eig, max_eig, case) + + # Trust radius + trust_radius_list = [0.1, 0.3, 0.6, 0.8, 1, 1.2, 3.3, 5.5, 10] + + for trust_radius in trust_radius_list: + # Solve subproblem with very high accuracy + subprob_ac = IterativeSubproblem(0, + lambda x: 0, + lambda x: g, + lambda x: H, + k_easy=1e-10, + k_hard=1e-10) + + p_ac, hits_boundary_ac = subprob_ac.solve(trust_radius) + + # Compute objective function value + J_ac = 1/2*np.dot(p_ac, np.dot(H, p_ac))+np.dot(g, p_ac) + + stop_criteria = [(0.1, 2), + (0.5, 1.1), + (0.9, 1.01)] + + for k_opt, k_trf in stop_criteria: + + # k_easy and k_hard computed in function + # of k_opt and k_trf accordingly to + # Conn, A. R., Gould, N. I., & Toint, P. L. (2000). + # "Trust region methods". Siam. p. 197. + k_easy = min(k_trf-1, + 1-np.sqrt(k_opt)) + k_hard = 1-k_opt + + # Solve subproblem + subprob = IterativeSubproblem(0, + lambda x: 0, + lambda x: g, + lambda x: H, + k_easy=k_easy, + k_hard=k_hard) + p, hits_boundary = subprob.solve(trust_radius) + + # Compute objective function value + J = 1/2*np.dot(p, np.dot(H, p))+np.dot(g, p) + + # Check if it respect k_trf + if hits_boundary: + assert_array_equal(np.abs(norm(p)-trust_radius) <= + (k_trf-1)*trust_radius, True) + else: + assert_equal(norm(p) <= trust_radius, True) + + # Check if it respect k_opt + assert_equal(J <= k_opt*J_ac, True) + diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_trustregion_krylov.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_trustregion_krylov.py new file mode 100644 index 0000000000000000000000000000000000000000..ee288c1b1348d280141bb62c09aba8fa67027142 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_trustregion_krylov.py @@ -0,0 +1,170 @@ +""" +Unit tests for Krylov space trust-region subproblem solver. + +""" +import pytest +import numpy as np +from scipy.optimize._trlib import (get_trlib_quadratic_subproblem) +from numpy.testing import (assert_, + assert_almost_equal, + assert_equal, assert_array_almost_equal) + +KrylovQP = get_trlib_quadratic_subproblem(tol_rel_i=1e-8, tol_rel_b=1e-6) +KrylovQP_disp = get_trlib_quadratic_subproblem(tol_rel_i=1e-8, tol_rel_b=1e-6, + disp=True) + +class TestKrylovQuadraticSubproblem: + + def test_for_the_easy_case(self): + + # `H` is chosen such that `g` is not orthogonal to the + # eigenvector associated with the smallest eigenvalue. + H = np.array([[1.0, 0.0, 4.0], + [0.0, 2.0, 0.0], + [4.0, 0.0, 3.0]]) + g = np.array([5.0, 0.0, 4.0]) + + # Trust Radius + trust_radius = 1.0 + + # Solve Subproblem + subprob = KrylovQP(x=0, + fun=lambda x: 0, + jac=lambda x: g, + hess=lambda x: None, + hessp=lambda x, y: H.dot(y)) + p, hits_boundary = subprob.solve(trust_radius) + + assert_array_almost_equal(p, np.array([-1.0, 0.0, 0.0])) + assert_equal(hits_boundary, True) + # check kkt satisfaction + assert_almost_equal( + np.linalg.norm(H.dot(p) + subprob.lam * p + g), + 0.0) + # check trust region constraint + assert_almost_equal(np.linalg.norm(p), trust_radius) + + trust_radius = 0.5 + p, hits_boundary = subprob.solve(trust_radius) + + assert_array_almost_equal(p, + np.array([-0.46125446, 0., -0.19298788])) + assert_equal(hits_boundary, True) + # check kkt satisfaction + assert_almost_equal( + np.linalg.norm(H.dot(p) + subprob.lam * p + g), + 0.0) + # check trust region constraint + assert_almost_equal(np.linalg.norm(p), trust_radius) + + def test_for_the_hard_case(self): + + # `H` is chosen such that `g` is orthogonal to the + # eigenvector associated with the smallest eigenvalue. + H = np.array([[1.0, 0.0, 4.0], + [0.0, 2.0, 0.0], + [4.0, 0.0, 3.0]]) + g = np.array([0.0, 2.0, 0.0]) + + # Trust Radius + trust_radius = 1.0 + + # Solve Subproblem + subprob = KrylovQP(x=0, + fun=lambda x: 0, + jac=lambda x: g, + hess=lambda x: None, + hessp=lambda x, y: H.dot(y)) + p, hits_boundary = subprob.solve(trust_radius) + + assert_array_almost_equal(p, np.array([0.0, -1.0, 0.0])) + # check kkt satisfaction + assert_almost_equal( + np.linalg.norm(H.dot(p) + subprob.lam * p + g), + 0.0) + # check trust region constraint + assert_almost_equal(np.linalg.norm(p), trust_radius) + + trust_radius = 0.5 + p, hits_boundary = subprob.solve(trust_radius) + + assert_array_almost_equal(p, np.array([0.0, -0.5, 0.0])) + # check kkt satisfaction + assert_almost_equal( + np.linalg.norm(H.dot(p) + subprob.lam * p + g), + 0.0) + # check trust region constraint + assert_almost_equal(np.linalg.norm(p), trust_radius) + + def test_for_interior_convergence(self): + + H = np.array([[1.812159, 0.82687265, 0.21838879, -0.52487006, 0.25436988], + [0.82687265, 2.66380283, 0.31508988, -0.40144163, 0.08811588], + [0.21838879, 0.31508988, 2.38020726, -0.3166346, 0.27363867], + [-0.52487006, -0.40144163, -0.3166346, 1.61927182, -0.42140166], + [0.25436988, 0.08811588, 0.27363867, -0.42140166, 1.33243101]]) + g = np.array([0.75798952, 0.01421945, 0.33847612, 0.83725004, -0.47909534]) + trust_radius = 1.1 + + # Solve Subproblem + subprob = KrylovQP(x=0, + fun=lambda x: 0, + jac=lambda x: g, + hess=lambda x: None, + hessp=lambda x, y: H.dot(y)) + p, hits_boundary = subprob.solve(trust_radius) + + # check kkt satisfaction + assert_almost_equal( + np.linalg.norm(H.dot(p) + subprob.lam * p + g), + 0.0) + + assert_array_almost_equal(p, [-0.68585435, 0.1222621, -0.22090999, + -0.67005053, 0.31586769]) + assert_array_almost_equal(hits_boundary, False) + + def test_for_very_close_to_zero(self): + + H = np.array([[0.88547534, 2.90692271, 0.98440885, -0.78911503, -0.28035809], + [2.90692271, -0.04618819, 0.32867263, -0.83737945, 0.17116396], + [0.98440885, 0.32867263, -0.87355957, -0.06521957, -1.43030957], + [-0.78911503, -0.83737945, -0.06521957, -1.645709, -0.33887298], + [-0.28035809, 0.17116396, -1.43030957, -0.33887298, -1.68586978]]) + g = np.array([0, 0, 0, 0, 1e-6]) + trust_radius = 1.1 + + # Solve Subproblem + subprob = KrylovQP(x=0, + fun=lambda x: 0, + jac=lambda x: g, + hess=lambda x: None, + hessp=lambda x, y: H.dot(y)) + p, hits_boundary = subprob.solve(trust_radius) + + # check kkt satisfaction + assert_almost_equal( + np.linalg.norm(H.dot(p) + subprob.lam * p + g), + 0.0) + # check trust region constraint + assert_almost_equal(np.linalg.norm(p), trust_radius) + + assert_array_almost_equal(p, [0.06910534, -0.01432721, + -0.65311947, -0.23815972, + -0.84954934]) + assert_array_almost_equal(hits_boundary, True) + + @pytest.mark.thread_unsafe + def test_disp(self, capsys): + H = -np.eye(5) + g = np.array([0, 0, 0, 0, 1e-6]) + trust_radius = 1.1 + + subprob = KrylovQP_disp(x=0, + fun=lambda x: 0, + jac=lambda x: g, + hess=lambda x: None, + hessp=lambda x, y: H.dot(y)) + p, hits_boundary = subprob.solve(trust_radius) + out, err = capsys.readouterr() + assert_(out.startswith(' TR Solving trust region problem'), repr(out)) + diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_zeros.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_zeros.py new file mode 100644 index 0000000000000000000000000000000000000000..99fedb181424a3669719f9d4703b739bb53fa8c4 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tests/test_zeros.py @@ -0,0 +1,965 @@ +import pytest + +from functools import lru_cache + +from numpy.testing import (assert_warns, assert_, + assert_allclose, + assert_equal, + assert_array_equal, + suppress_warnings) +import numpy as np +from numpy import finfo, power, nan, isclose, sqrt, exp, sin, cos + +from scipy import optimize +from scipy.optimize import (_zeros_py as zeros, newton, root_scalar, + OptimizeResult) + +from scipy._lib._util import getfullargspec_no_self as _getfullargspec + +# Import testing parameters +from scipy.optimize._tstutils import get_tests, functions as tstutils_functions + +TOL = 4*np.finfo(float).eps # tolerance + +_FLOAT_EPS = finfo(float).eps + +bracket_methods = [zeros.bisect, zeros.ridder, zeros.brentq, zeros.brenth, + zeros.toms748] +gradient_methods = [zeros.newton] +all_methods = bracket_methods + gradient_methods + +# A few test functions used frequently: +# # A simple quadratic, (x-1)^2 - 1 +def f1(x): + return x ** 2 - 2 * x - 1 + + +def f1_1(x): + return 2 * x - 2 + + +def f1_2(x): + return 2.0 + 0 * x + + +def f1_and_p_and_pp(x): + return f1(x), f1_1(x), f1_2(x) + + +# Simple transcendental function +def f2(x): + return exp(x) - cos(x) + + +def f2_1(x): + return exp(x) + sin(x) + + +def f2_2(x): + return exp(x) + cos(x) + + +# lru cached function +@lru_cache +def f_lrucached(x): + return x + + +class TestScalarRootFinders: + # Basic tests for all scalar root finders + + xtol = 4 * np.finfo(float).eps + rtol = 4 * np.finfo(float).eps + + def _run_one_test(self, tc, method, sig_args_keys=None, + sig_kwargs_keys=None, **kwargs): + method_args = [] + for k in sig_args_keys or []: + if k not in tc: + # If a,b not present use x0, x1. Similarly for f and func + k = {'a': 'x0', 'b': 'x1', 'func': 'f'}.get(k, k) + method_args.append(tc[k]) + + method_kwargs = dict(**kwargs) + method_kwargs.update({'full_output': True, 'disp': False}) + for k in sig_kwargs_keys or []: + method_kwargs[k] = tc[k] + + root = tc.get('root') + func_args = tc.get('args', ()) + + try: + r, rr = method(*method_args, args=func_args, **method_kwargs) + return root, rr, tc + except Exception: + return root, zeros.RootResults(nan, -1, -1, zeros._EVALUEERR, method), tc + + def run_tests(self, tests, method, name, known_fail=None, **kwargs): + r"""Run test-cases using the specified method and the supplied signature. + + Extract the arguments for the method call from the test case + dictionary using the supplied keys for the method's signature.""" + # The methods have one of two base signatures: + # (f, a, b, **kwargs) # newton + # (func, x0, **kwargs) # bisect/brentq/... + + # FullArgSpec with args, varargs, varkw, defaults, ... + sig = _getfullargspec(method) + assert_(not sig.kwonlyargs) + nDefaults = len(sig.defaults) + nRequired = len(sig.args) - nDefaults + sig_args_keys = sig.args[:nRequired] + sig_kwargs_keys = [] + if name in ['secant', 'newton', 'halley']: + if name in ['newton', 'halley']: + sig_kwargs_keys.append('fprime') + if name in ['halley']: + sig_kwargs_keys.append('fprime2') + kwargs['tol'] = self.xtol + else: + kwargs['xtol'] = self.xtol + kwargs['rtol'] = self.rtol + + results = [list(self._run_one_test( + tc, method, sig_args_keys=sig_args_keys, + sig_kwargs_keys=sig_kwargs_keys, **kwargs)) for tc in tests] + # results= [[true root, full output, tc], ...] + + known_fail = known_fail or [] + notcvgd = [elt for elt in results if not elt[1].converged] + notcvgd = [elt for elt in notcvgd if elt[-1]['ID'] not in known_fail] + notcvged_IDS = [elt[-1]['ID'] for elt in notcvgd] + assert_equal([len(notcvged_IDS), notcvged_IDS], [0, []]) + + # The usable xtol and rtol depend on the test + tols = {'xtol': self.xtol, 'rtol': self.rtol} + tols.update(**kwargs) + rtol = tols['rtol'] + atol = tols.get('tol', tols['xtol']) + + cvgd = [elt for elt in results if elt[1].converged] + approx = [elt[1].root for elt in cvgd] + correct = [elt[0] for elt in cvgd] + # See if the root matches the reference value + notclose = [[a] + elt for a, c, elt in zip(approx, correct, cvgd) if + not isclose(a, c, rtol=rtol, atol=atol) + and elt[-1]['ID'] not in known_fail] + # If not, evaluate the function and see if is 0 at the purported root + fvs = [tc['f'](aroot, *tc.get('args', tuple())) + for aroot, c, fullout, tc in notclose] + notclose = [[fv] + elt for fv, elt in zip(fvs, notclose) if fv != 0] + assert_equal([notclose, len(notclose)], [[], 0]) + method_from_result = [result[1].method for result in results] + expected_method = [name for _ in results] + assert_equal(method_from_result, expected_method) + + def run_collection(self, collection, method, name, smoothness=None, + known_fail=None, **kwargs): + r"""Run a collection of tests using the specified method. + + The name is used to determine some optional arguments.""" + tests = get_tests(collection, smoothness=smoothness) + self.run_tests(tests, method, name, known_fail=known_fail, **kwargs) + + +class TestBracketMethods(TestScalarRootFinders): + @pytest.mark.parametrize('method', bracket_methods) + @pytest.mark.parametrize('function', tstutils_functions) + def test_basic_root_scalar(self, method, function): + # Tests bracketing root finders called via `root_scalar` on a small + # set of simple problems, each of which has a root at `x=1`. Checks for + # converged status and that the root was found. + a, b = .5, sqrt(3) + + r = root_scalar(function, method=method.__name__, bracket=[a, b], x0=a, + xtol=self.xtol, rtol=self.rtol) + assert r.converged + assert_allclose(r.root, 1.0, atol=self.xtol, rtol=self.rtol) + assert r.method == method.__name__ + + @pytest.mark.parametrize('method', bracket_methods) + @pytest.mark.parametrize('function', tstutils_functions) + def test_basic_individual(self, method, function): + # Tests individual bracketing root finders on a small set of simple + # problems, each of which has a root at `x=1`. Checks for converged + # status and that the root was found. + a, b = .5, sqrt(3) + root, r = method(function, a, b, xtol=self.xtol, rtol=self.rtol, + full_output=True) + + assert r.converged + assert_allclose(root, 1.0, atol=self.xtol, rtol=self.rtol) + + @pytest.mark.parametrize('method', bracket_methods) + @pytest.mark.parametrize('function', tstutils_functions) + def test_bracket_is_array(self, method, function): + # Test bracketing root finders called via `root_scalar` on a small set + # of simple problems, each of which has a root at `x=1`. Check that + # passing `bracket` as a `ndarray` is accepted and leads to finding the + # correct root. + a, b = .5, sqrt(3) + r = root_scalar(function, method=method.__name__, + bracket=np.array([a, b]), x0=a, xtol=self.xtol, + rtol=self.rtol) + assert r.converged + assert_allclose(r.root, 1.0, atol=self.xtol, rtol=self.rtol) + assert r.method == method.__name__ + + @pytest.mark.parametrize('method', bracket_methods) + def test_aps_collection(self, method): + self.run_collection('aps', method, method.__name__, smoothness=1) + + @pytest.mark.parametrize('method', [zeros.bisect, zeros.ridder, + zeros.toms748]) + def test_chandrupatla_collection(self, method): + known_fail = {'fun7.4'} if method == zeros.ridder else {} + self.run_collection('chandrupatla', method, method.__name__, + known_fail=known_fail) + + @pytest.mark.parametrize('method', bracket_methods) + def test_lru_cached_individual(self, method): + # check that https://github.com/scipy/scipy/issues/10846 is fixed + # (`root_scalar` failed when passed a function that was `@lru_cache`d) + a, b = -1, 1 + root, r = method(f_lrucached, a, b, full_output=True) + assert r.converged + assert_allclose(root, 0) + + +class TestNewton(TestScalarRootFinders): + def test_newton_collections(self): + known_fail = ['aps.13.00'] + known_fail += ['aps.12.05', 'aps.12.17'] # fails under Windows Py27 + for collection in ['aps', 'complex']: + self.run_collection(collection, zeros.newton, 'newton', + smoothness=2, known_fail=known_fail) + + def test_halley_collections(self): + known_fail = ['aps.12.06', 'aps.12.07', 'aps.12.08', 'aps.12.09', + 'aps.12.10', 'aps.12.11', 'aps.12.12', 'aps.12.13', + 'aps.12.14', 'aps.12.15', 'aps.12.16', 'aps.12.17', + 'aps.12.18', 'aps.13.00'] + for collection in ['aps', 'complex']: + self.run_collection(collection, zeros.newton, 'halley', + smoothness=2, known_fail=known_fail) + + def test_newton(self): + for f, f_1, f_2 in [(f1, f1_1, f1_2), (f2, f2_1, f2_2)]: + x = zeros.newton(f, 3, tol=1e-6) + assert_allclose(f(x), 0, atol=1e-6) + x = zeros.newton(f, 3, x1=5, tol=1e-6) # secant, x0 and x1 + assert_allclose(f(x), 0, atol=1e-6) + x = zeros.newton(f, 3, fprime=f_1, tol=1e-6) # newton + assert_allclose(f(x), 0, atol=1e-6) + x = zeros.newton(f, 3, fprime=f_1, fprime2=f_2, tol=1e-6) # halley + assert_allclose(f(x), 0, atol=1e-6) + + def test_newton_by_name(self): + r"""Invoke newton through root_scalar()""" + for f, f_1, f_2 in [(f1, f1_1, f1_2), (f2, f2_1, f2_2)]: + r = root_scalar(f, method='newton', x0=3, fprime=f_1, xtol=1e-6) + assert_allclose(f(r.root), 0, atol=1e-6) + for f, f_1, f_2 in [(f1, f1_1, f1_2), (f2, f2_1, f2_2)]: + r = root_scalar(f, method='newton', x0=3, xtol=1e-6) # without f' + assert_allclose(f(r.root), 0, atol=1e-6) + + def test_secant_by_name(self): + r"""Invoke secant through root_scalar()""" + for f, f_1, f_2 in [(f1, f1_1, f1_2), (f2, f2_1, f2_2)]: + r = root_scalar(f, method='secant', x0=3, x1=2, xtol=1e-6) + assert_allclose(f(r.root), 0, atol=1e-6) + r = root_scalar(f, method='secant', x0=3, x1=5, xtol=1e-6) + assert_allclose(f(r.root), 0, atol=1e-6) + for f, f_1, f_2 in [(f1, f1_1, f1_2), (f2, f2_1, f2_2)]: + r = root_scalar(f, method='secant', x0=3, xtol=1e-6) # without x1 + assert_allclose(f(r.root), 0, atol=1e-6) + + def test_halley_by_name(self): + r"""Invoke halley through root_scalar()""" + for f, f_1, f_2 in [(f1, f1_1, f1_2), (f2, f2_1, f2_2)]: + r = root_scalar(f, method='halley', x0=3, + fprime=f_1, fprime2=f_2, xtol=1e-6) + assert_allclose(f(r.root), 0, atol=1e-6) + + def test_root_scalar_fail(self): + message = 'fprime2 must be specified for halley' + with pytest.raises(ValueError, match=message): + root_scalar(f1, method='halley', fprime=f1_1, x0=3, xtol=1e-6) # no fprime2 + message = 'fprime must be specified for halley' + with pytest.raises(ValueError, match=message): + root_scalar(f1, method='halley', fprime2=f1_2, x0=3, xtol=1e-6) # no fprime + + def test_array_newton(self): + """test newton with array""" + + def f1(x, *a): + b = a[0] + x * a[3] + return a[1] - a[2] * (np.exp(b / a[5]) - 1.0) - b / a[4] - x + + def f1_1(x, *a): + b = a[3] / a[5] + return -a[2] * np.exp(a[0] / a[5] + x * b) * b - a[3] / a[4] - 1 + + def f1_2(x, *a): + b = a[3] / a[5] + return -a[2] * np.exp(a[0] / a[5] + x * b) * b**2 + + a0 = np.array([ + 5.32725221, 5.48673747, 5.49539973, + 5.36387202, 4.80237316, 1.43764452, + 5.23063958, 5.46094772, 5.50512718, + 5.42046290 + ]) + a1 = (np.sin(range(10)) + 1.0) * 7.0 + args = (a0, a1, 1e-09, 0.004, 10, 0.27456) + x0 = [7.0] * 10 + x = zeros.newton(f1, x0, f1_1, args) + x_expected = ( + 6.17264965, 11.7702805, 12.2219954, + 7.11017681, 1.18151293, 0.143707955, + 4.31928228, 10.5419107, 12.7552490, + 8.91225749 + ) + assert_allclose(x, x_expected) + # test halley's + x = zeros.newton(f1, x0, f1_1, args, fprime2=f1_2) + assert_allclose(x, x_expected) + # test secant + x = zeros.newton(f1, x0, args=args) + assert_allclose(x, x_expected) + + def test_array_newton_complex(self): + def f(x): + return x + 1+1j + + def fprime(x): + return 1.0 + + t = np.full(4, 1j) + x = zeros.newton(f, t, fprime=fprime) + assert_allclose(f(x), 0.) + + # should work even if x0 is not complex + t = np.ones(4) + x = zeros.newton(f, t, fprime=fprime) + assert_allclose(f(x), 0.) + + x = zeros.newton(f, t) + assert_allclose(f(x), 0.) + + def test_array_secant_active_zero_der(self): + """test secant doesn't continue to iterate zero derivatives""" + x = zeros.newton(lambda x, *a: x*x - a[0], x0=[4.123, 5], + args=[np.array([17, 25])]) + assert_allclose(x, (4.123105625617661, 5.0)) + + def test_array_newton_integers(self): + # test secant with float + x = zeros.newton(lambda y, z: z - y ** 2, [4.0] * 2, + args=([15.0, 17.0],)) + assert_allclose(x, (3.872983346207417, 4.123105625617661)) + # test integer becomes float + x = zeros.newton(lambda y, z: z - y ** 2, [4] * 2, args=([15, 17],)) + assert_allclose(x, (3.872983346207417, 4.123105625617661)) + + @pytest.mark.thread_unsafe + def test_array_newton_zero_der_failures(self): + # test derivative zero warning + assert_warns(RuntimeWarning, zeros.newton, + lambda y: y**2 - 2, [0., 0.], lambda y: 2 * y) + # test failures and zero_der + with pytest.warns(RuntimeWarning): + results = zeros.newton(lambda y: y**2 - 2, [0., 0.], + lambda y: 2*y, full_output=True) + assert_allclose(results.root, 0) + assert results.zero_der.all() + assert not results.converged.any() + + def test_newton_combined(self): + def f1(x): + return x ** 2 - 2 * x - 1 + def f1_1(x): + return 2 * x - 2 + def f1_2(x): + return 2.0 + 0 * x + + def f1_and_p_and_pp(x): + return x**2 - 2*x-1, 2*x-2, 2.0 + + sol0 = root_scalar(f1, method='newton', x0=3, fprime=f1_1) + sol = root_scalar(f1_and_p_and_pp, method='newton', x0=3, fprime=True) + assert_allclose(sol0.root, sol.root, atol=1e-8) + assert_equal(2*sol.function_calls, sol0.function_calls) + + sol0 = root_scalar(f1, method='halley', x0=3, fprime=f1_1, fprime2=f1_2) + sol = root_scalar(f1_and_p_and_pp, method='halley', x0=3, fprime2=True) + assert_allclose(sol0.root, sol.root, atol=1e-8) + assert_equal(3*sol.function_calls, sol0.function_calls) + + def test_newton_full_output(self, capsys): + # Test the full_output capability, both when converging and not. + # Use simple polynomials, to avoid hitting platform dependencies + # (e.g., exp & trig) in number of iterations + + x0 = 3 + expected_counts = [(6, 7), (5, 10), (3, 9)] + + for derivs in range(3): + kwargs = {'tol': 1e-6, 'full_output': True, } + for k, v in [['fprime', f1_1], ['fprime2', f1_2]][:derivs]: + kwargs[k] = v + + x, r = zeros.newton(f1, x0, disp=False, **kwargs) + assert_(r.converged) + assert_equal(x, r.root) + assert_equal((r.iterations, r.function_calls), expected_counts[derivs]) + if derivs == 0: + assert r.function_calls <= r.iterations + 1 + else: + assert_equal(r.function_calls, (derivs + 1) * r.iterations) + + # Now repeat, allowing one fewer iteration to force convergence failure + iters = r.iterations - 1 + x, r = zeros.newton(f1, x0, maxiter=iters, disp=False, **kwargs) + assert_(not r.converged) + assert_equal(x, r.root) + assert_equal(r.iterations, iters) + + if derivs == 1: + # Check that the correct Exception is raised and + # validate the start of the message. + msg = 'Failed to converge after %d iterations, value is .*' % (iters) + with pytest.raises(RuntimeError, match=msg): + x, r = zeros.newton(f1, x0, maxiter=iters, disp=True, **kwargs) + + @pytest.mark.thread_unsafe + def test_deriv_zero_warning(self): + def func(x): + return x ** 2 - 2.0 + def dfunc(x): + return 2 * x + assert_warns(RuntimeWarning, zeros.newton, func, 0.0, dfunc, disp=False) + with pytest.raises(RuntimeError, match='Derivative was zero'): + zeros.newton(func, 0.0, dfunc) + + def test_newton_does_not_modify_x0(self): + # https://github.com/scipy/scipy/issues/9964 + x0 = np.array([0.1, 3]) + x0_copy = x0.copy() # Copy to test for equality. + newton(np.sin, x0, np.cos) + assert_array_equal(x0, x0_copy) + + def test_gh17570_defaults(self): + # Previously, when fprime was not specified, root_scalar would default + # to secant. When x1 was not specified, secant failed. + # Check that without fprime, the default is secant if x1 is specified + # and newton otherwise. + # Also confirm that `x` is always a scalar (gh-21148) + def f(x): + assert np.isscalar(x) + return f1(x) + + res_newton_default = root_scalar(f, method='newton', x0=3, xtol=1e-6) + res_secant_default = root_scalar(f, method='secant', x0=3, x1=2, + xtol=1e-6) + # `newton` uses the secant method when `x1` and `x2` are specified + res_secant = newton(f, x0=3, x1=2, tol=1e-6, full_output=True)[1] + + # all three found a root + assert_allclose(f(res_newton_default.root), 0, atol=1e-6) + assert res_newton_default.root.shape == tuple() + assert_allclose(f(res_secant_default.root), 0, atol=1e-6) + assert res_secant_default.root.shape == tuple() + assert_allclose(f(res_secant.root), 0, atol=1e-6) + assert res_secant.root.shape == tuple() + + # Defaults are correct + assert (res_secant_default.root + == res_secant.root + != res_newton_default.iterations) + assert (res_secant_default.iterations + == res_secant_default.function_calls - 1 # true for secant + == res_secant.iterations + != res_newton_default.iterations + == res_newton_default.function_calls/2) # newton 2-point diff + + @pytest.mark.parametrize('kwargs', [dict(), {'method': 'newton'}]) + def test_args_gh19090(self, kwargs): + def f(x, a, b): + assert a == 3 + assert b == 1 + return (x ** a - b) + + res = optimize.root_scalar(f, x0=3, args=(3, 1), **kwargs) + assert res.converged + assert_allclose(res.root, 1) + + @pytest.mark.parametrize('method', ['secant', 'newton']) + def test_int_x0_gh19280(self, method): + # Originally, `newton` ensured that only floats were passed to the + # callable. This was inadvertently changed by gh-17669. Check that + # it has been changed back. + def f(x): + # an integer raised to a negative integer power would fail + return x**-2 - 2 + + res = optimize.root_scalar(f, x0=1, method=method) + assert res.converged + assert_allclose(abs(res.root), 2**-0.5) + assert res.root.dtype == np.dtype(np.float64) + + +def test_gh_5555(): + root = 0.1 + + def f(x): + return x - root + + methods = [zeros.bisect, zeros.ridder] + xtol = rtol = TOL + for method in methods: + res = method(f, -1e8, 1e7, xtol=xtol, rtol=rtol) + assert_allclose(root, res, atol=xtol, rtol=rtol, + err_msg=f'method {method.__name__}') + + +def test_gh_5557(): + # Show that without the changes in 5557 brentq and brenth might + # only achieve a tolerance of 2*(xtol + rtol*|res|). + + # f linearly interpolates (0, -0.1), (0.5, -0.1), and (1, + # 0.4). The important parts are that |f(0)| < |f(1)| (so that + # brent takes 0 as the initial guess), |f(0)| < atol (so that + # brent accepts 0 as the root), and that the exact root of f lies + # more than atol away from 0 (so that brent doesn't achieve the + # desired tolerance). + def f(x): + if x < 0.5: + return -0.1 + else: + return x - 0.6 + + atol = 0.51 + rtol = 4 * _FLOAT_EPS + methods = [zeros.brentq, zeros.brenth] + for method in methods: + res = method(f, 0, 1, xtol=atol, rtol=rtol) + assert_allclose(0.6, res, atol=atol, rtol=rtol) + + +def test_brent_underflow_in_root_bracketing(): + # Testing if an interval [a,b] brackets a zero of a function + # by checking f(a)*f(b) < 0 is not reliable when the product + # underflows/overflows. (reported in issue# 13737) + + underflow_scenario = (-450.0, -350.0, -400.0) + overflow_scenario = (350.0, 450.0, 400.0) + + for a, b, root in [underflow_scenario, overflow_scenario]: + c = np.exp(root) + for method in [zeros.brenth, zeros.brentq]: + res = method(lambda x: np.exp(x)-c, a, b) + assert_allclose(root, res) + + +class TestRootResults: + r = zeros.RootResults(root=1.0, iterations=44, function_calls=46, flag=0, + method="newton") + + def test_repr(self): + expected_repr = (" converged: True\n flag: converged" + "\n function_calls: 46\n iterations: 44\n" + " root: 1.0\n method: newton") + assert_equal(repr(self.r), expected_repr) + + def test_type(self): + assert isinstance(self.r, OptimizeResult) + + +def test_complex_halley(): + """Test Halley's works with complex roots""" + def f(x, *a): + return a[0] * x**2 + a[1] * x + a[2] + + def f_1(x, *a): + return 2 * a[0] * x + a[1] + + def f_2(x, *a): + retval = 2 * a[0] + try: + size = len(x) + except TypeError: + return retval + else: + return [retval] * size + + z = complex(1.0, 2.0) + coeffs = (2.0, 3.0, 4.0) + y = zeros.newton(f, z, args=coeffs, fprime=f_1, fprime2=f_2, tol=1e-6) + # (-0.75000000000000078+1.1989578808281789j) + assert_allclose(f(y, *coeffs), 0, atol=1e-6) + z = [z] * 10 + coeffs = (2.0, 3.0, 4.0) + y = zeros.newton(f, z, args=coeffs, fprime=f_1, fprime2=f_2, tol=1e-6) + assert_allclose(f(y, *coeffs), 0, atol=1e-6) + + +@pytest.mark.thread_unsafe +def test_zero_der_nz_dp(capsys): + """Test secant method with a non-zero dp, but an infinite newton step""" + # pick a symmetrical functions and choose a point on the side that with dx + # makes a secant that is a flat line with zero slope, EG: f = (x - 100)**2, + # which has a root at x = 100 and is symmetrical around the line x = 100 + # we have to pick a really big number so that it is consistently true + # now find a point on each side so that the secant has a zero slope + dx = np.finfo(float).eps ** 0.33 + # 100 - p0 = p1 - 100 = p0 * (1 + dx) + dx - 100 + # -> 200 = p0 * (2 + dx) + dx + p0 = (200.0 - dx) / (2.0 + dx) + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "RMS of") + x = zeros.newton(lambda y: (y - 100.0)**2, x0=[p0] * 10) + assert_allclose(x, [100] * 10) + # test scalar cases too + p0 = (2.0 - 1e-4) / (2.0 + 1e-4) + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "Tolerance of") + x = zeros.newton(lambda y: (y - 1.0) ** 2, x0=p0, disp=False) + assert_allclose(x, 1) + with pytest.raises(RuntimeError, match='Tolerance of'): + x = zeros.newton(lambda y: (y - 1.0) ** 2, x0=p0, disp=True) + p0 = (-2.0 + 1e-4) / (2.0 + 1e-4) + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "Tolerance of") + x = zeros.newton(lambda y: (y + 1.0) ** 2, x0=p0, disp=False) + assert_allclose(x, -1) + with pytest.raises(RuntimeError, match='Tolerance of'): + x = zeros.newton(lambda y: (y + 1.0) ** 2, x0=p0, disp=True) + + +@pytest.mark.thread_unsafe +def test_array_newton_failures(): + """Test that array newton fails as expected""" + # p = 0.68 # [MPa] + # dp = -0.068 * 1e6 # [Pa] + # T = 323 # [K] + diameter = 0.10 # [m] + # L = 100 # [m] + roughness = 0.00015 # [m] + rho = 988.1 # [kg/m**3] + mu = 5.4790e-04 # [Pa*s] + u = 2.488 # [m/s] + reynolds_number = rho * u * diameter / mu # Reynolds number + + def colebrook_eqn(darcy_friction, re, dia): + return (1 / np.sqrt(darcy_friction) + + 2 * np.log10(roughness / 3.7 / dia + + 2.51 / re / np.sqrt(darcy_friction))) + + # only some failures + with pytest.warns(RuntimeWarning): + result = zeros.newton( + colebrook_eqn, x0=[0.01, 0.2, 0.02223, 0.3], maxiter=2, + args=[reynolds_number, diameter], full_output=True + ) + assert not result.converged.all() + # they all fail + with pytest.raises(RuntimeError): + result = zeros.newton( + colebrook_eqn, x0=[0.01] * 2, maxiter=2, + args=[reynolds_number, diameter], full_output=True + ) + + +# this test should **not** raise a RuntimeWarning +def test_gh8904_zeroder_at_root_fails(): + """Test that Newton or Halley don't warn if zero derivative at root""" + + # a function that has a zero derivative at it's root + def f_zeroder_root(x): + return x**3 - x**2 + + # should work with secant + r = zeros.newton(f_zeroder_root, x0=0) + assert_allclose(r, 0, atol=zeros._xtol, rtol=zeros._rtol) + # test again with array + r = zeros.newton(f_zeroder_root, x0=[0]*10) + assert_allclose(r, 0, atol=zeros._xtol, rtol=zeros._rtol) + + # 1st derivative + def fder(x): + return 3 * x**2 - 2 * x + + # 2nd derivative + def fder2(x): + return 6*x - 2 + + # should work with newton and halley + r = zeros.newton(f_zeroder_root, x0=0, fprime=fder) + assert_allclose(r, 0, atol=zeros._xtol, rtol=zeros._rtol) + r = zeros.newton(f_zeroder_root, x0=0, fprime=fder, + fprime2=fder2) + assert_allclose(r, 0, atol=zeros._xtol, rtol=zeros._rtol) + # test again with array + r = zeros.newton(f_zeroder_root, x0=[0]*10, fprime=fder) + assert_allclose(r, 0, atol=zeros._xtol, rtol=zeros._rtol) + r = zeros.newton(f_zeroder_root, x0=[0]*10, fprime=fder, + fprime2=fder2) + assert_allclose(r, 0, atol=zeros._xtol, rtol=zeros._rtol) + + # also test that if a root is found we do not raise RuntimeWarning even if + # the derivative is zero, EG: at x = 0.5, then fval = -0.125 and + # fder = -0.25 so the next guess is 0.5 - (-0.125/-0.5) = 0 which is the + # root, but if the solver continued with that guess, then it will calculate + # a zero derivative, so it should return the root w/o RuntimeWarning + r = zeros.newton(f_zeroder_root, x0=0.5, fprime=fder) + assert_allclose(r, 0, atol=zeros._xtol, rtol=zeros._rtol) + # test again with array + r = zeros.newton(f_zeroder_root, x0=[0.5]*10, fprime=fder) + assert_allclose(r, 0, atol=zeros._xtol, rtol=zeros._rtol) + # doesn't apply to halley + + +def test_gh_8881(): + r"""Test that Halley's method realizes that the 2nd order adjustment + is too big and drops off to the 1st order adjustment.""" + n = 9 + + def f(x): + return power(x, 1.0/n) - power(n, 1.0/n) + + def fp(x): + return power(x, (1.0-n)/n)/n + + def fpp(x): + return power(x, (1.0-2*n)/n) * (1.0/n) * (1.0-n)/n + + x0 = 0.1 + # The root is at x=9. + # The function has positive slope, x0 < root. + # Newton succeeds in 8 iterations + rt, r = newton(f, x0, fprime=fp, full_output=True) + assert r.converged + # Before the Issue 8881/PR 8882, halley would send x in the wrong direction. + # Check that it now succeeds. + rt, r = newton(f, x0, fprime=fp, fprime2=fpp, full_output=True) + assert r.converged + + +def test_gh_9608_preserve_array_shape(): + """ + Test that shape is preserved for array inputs even if fprime or fprime2 is + scalar + """ + def f(x): + return x**2 + + def fp(x): + return 2 * x + + def fpp(x): + return 2 + + x0 = np.array([-2], dtype=np.float32) + rt, r = newton(f, x0, fprime=fp, fprime2=fpp, full_output=True) + assert r.converged + + x0_array = np.array([-2, -3], dtype=np.float32) + # This next invocation should fail + with pytest.raises(IndexError): + result = zeros.newton( + f, x0_array, fprime=fp, fprime2=fpp, full_output=True + ) + + def fpp_array(x): + return np.full(np.shape(x), 2, dtype=np.float32) + + result = zeros.newton( + f, x0_array, fprime=fp, fprime2=fpp_array, full_output=True + ) + assert result.converged.all() + + +@pytest.mark.parametrize( + "maximum_iterations,flag_expected", + [(10, zeros.CONVERR), (100, zeros.CONVERGED)]) +def test_gh9254_flag_if_maxiter_exceeded(maximum_iterations, flag_expected): + """ + Test that if the maximum iterations is exceeded that the flag is not + converged. + """ + result = zeros.brentq( + lambda x: ((1.2*x - 2.3)*x + 3.4)*x - 4.5, + -30, 30, (), 1e-6, 1e-6, maximum_iterations, + full_output=True, disp=False) + assert result[1].flag == flag_expected + if flag_expected == zeros.CONVERR: + # didn't converge because exceeded maximum iterations + assert result[1].iterations == maximum_iterations + elif flag_expected == zeros.CONVERGED: + # converged before maximum iterations + assert result[1].iterations < maximum_iterations + + +@pytest.mark.thread_unsafe +def test_gh9551_raise_error_if_disp_true(): + """Test that if disp is true then zero derivative raises RuntimeError""" + + def f(x): + return x*x + 1 + + def f_p(x): + return 2*x + + assert_warns(RuntimeWarning, zeros.newton, f, 1.0, f_p, disp=False) + with pytest.raises( + RuntimeError, + match=r'^Derivative was zero\. Failed to converge after \d+ iterations, ' + r'value is [+-]?\d*\.\d+\.$'): + zeros.newton(f, 1.0, f_p) + root = zeros.newton(f, complex(10.0, 10.0), f_p) + assert_allclose(root, complex(0.0, 1.0)) + + +@pytest.mark.parametrize('solver_name', + ['brentq', 'brenth', 'bisect', 'ridder', 'toms748']) +def test_gh3089_8394(solver_name): + # gh-3089 and gh-8394 reported that bracketing solvers returned incorrect + # results when they encountered NaNs. Check that this is resolved. + def f(x): + return np.nan + + solver = getattr(zeros, solver_name) + with pytest.raises(ValueError, match="The function value at x..."): + solver(f, 0, 1) + + +@pytest.mark.parametrize('method', + ['brentq', 'brenth', 'bisect', 'ridder', 'toms748']) +def test_gh18171(method): + # gh-3089 and gh-8394 reported that bracketing solvers returned incorrect + # results when they encountered NaNs. Check that `root_scalar` returns + # normally but indicates that convergence was unsuccessful. See gh-18171. + def f(x): + f._count += 1 + return np.nan + f._count = 0 + + res = root_scalar(f, bracket=(0, 1), method=method) + assert res.converged is False + assert res.flag.startswith("The function value at x") + assert res.function_calls == f._count + assert str(res.root) in res.flag + + +@pytest.mark.parametrize('solver_name', + ['brentq', 'brenth', 'bisect', 'ridder', 'toms748']) +@pytest.mark.parametrize('rs_interface', [True, False]) +def test_function_calls(solver_name, rs_interface): + # There do not appear to be checks that the bracketing solvers report the + # correct number of function evaluations. Check that this is the case. + solver = ((lambda f, a, b, **kwargs: root_scalar(f, bracket=(a, b))) + if rs_interface else getattr(zeros, solver_name)) + + def f(x): + f.calls += 1 + return x**2 - 1 + f.calls = 0 + + res = solver(f, 0, 10, full_output=True) + + if rs_interface: + assert res.function_calls == f.calls + else: + assert res[1].function_calls == f.calls + + +@pytest.mark.thread_unsafe +def test_gh_14486_converged_false(): + """Test that zero slope with secant method results in a converged=False""" + def lhs(x): + return x * np.exp(-x*x) - 0.07 + + with pytest.warns(RuntimeWarning, match='Tolerance of'): + res = root_scalar(lhs, method='secant', x0=-0.15, x1=1.0) + assert not res.converged + assert res.flag == 'convergence error' + + with pytest.warns(RuntimeWarning, match='Tolerance of'): + res = newton(lhs, x0=-0.15, x1=1.0, disp=False, full_output=True)[1] + assert not res.converged + assert res.flag == 'convergence error' + + +@pytest.mark.parametrize('solver_name', + ['brentq', 'brenth', 'bisect', 'ridder', 'toms748']) +@pytest.mark.parametrize('rs_interface', [True, False]) +def test_gh5584(solver_name, rs_interface): + # gh-5584 reported that an underflow can cause sign checks in the algorithm + # to fail. Check that this is resolved. + solver = ((lambda f, a, b, **kwargs: root_scalar(f, bracket=(a, b))) + if rs_interface else getattr(zeros, solver_name)) + + def f(x): + return 1e-200*x + + # Report failure when signs are the same + with pytest.raises(ValueError, match='...must have different signs'): + solver(f, -0.5, -0.4, full_output=True) + + # Solve successfully when signs are different + res = solver(f, -0.5, 0.4, full_output=True) + res = res if rs_interface else res[1] + assert res.converged + assert_allclose(res.root, 0, atol=1e-8) + + # Solve successfully when one side is negative zero + res = solver(f, -0.5, float('-0.0'), full_output=True) + res = res if rs_interface else res[1] + assert res.converged + assert_allclose(res.root, 0, atol=1e-8) + + +def test_gh13407(): + # gh-13407 reported that the message produced by `scipy.optimize.toms748` + # when `rtol < eps` is incorrect, and also that toms748 is unusual in + # accepting `rtol` as low as eps while other solvers raise at 4*eps. Check + # that the error message has been corrected and that `rtol=eps` can produce + # a lower function value than `rtol=4*eps`. + def f(x): + return x**3 - 2*x - 5 + + xtol = 1e-300 + eps = np.finfo(float).eps + x1 = zeros.toms748(f, 1e-10, 1e10, xtol=xtol, rtol=1*eps) + f1 = f(x1) + x4 = zeros.toms748(f, 1e-10, 1e10, xtol=xtol, rtol=4*eps) + f4 = f(x4) + assert f1 < f4 + + # using old-style syntax to get exactly the same message + message = fr"rtol too small \({eps/2:g} < {eps:g}\)" + with pytest.raises(ValueError, match=message): + zeros.toms748(f, 1e-10, 1e10, xtol=xtol, rtol=eps/2) + + +def test_newton_complex_gh10103(): + # gh-10103 reported a problem when `newton` is pass a Python complex x0, + # no `fprime` (secant method), and no `x1` (`x1` must be constructed). + # Check that this is resolved. + def f(z): + return z - 1 + res = newton(f, 1+1j) + assert_allclose(res, 1, atol=1e-12) + + res = root_scalar(f, x0=1+1j, x1=2+1.5j, method='secant') + assert_allclose(res.root, 1, atol=1e-12) + + +@pytest.mark.parametrize('method', all_methods) +def test_maxiter_int_check_gh10236(method): + # gh-10236 reported that the error message when `maxiter` is not an integer + # was difficult to interpret. Check that this was resolved (by gh-10907). + message = "'float' object cannot be interpreted as an integer" + with pytest.raises(TypeError, match=message): + method(f1, 0.0, 1.0, maxiter=72.45) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tnc.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tnc.py new file mode 100644 index 0000000000000000000000000000000000000000..e0f66058bbcc501eb1303eb3075cb55705b93192 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/tnc.py @@ -0,0 +1,22 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.optimize` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'OptimizeResult', + 'fmin_tnc', + 'zeros', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="optimize", module="tnc", + private_modules=["_tnc"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/zeros.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/zeros.py new file mode 100644 index 0000000000000000000000000000000000000000..907d49d37fc1e7476e81a25dbbc0d3910cbbe004 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/optimize/zeros.py @@ -0,0 +1,26 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.optimize` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'RootResults', + 'bisect', + 'brenth', + 'brentq', + 'newton', + 'ridder', + 'toms748', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="optimize", module="zeros", + private_modules=["_zeros_py"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a1eaa9243ff83caa8e8078adc0cfb268119a4c72 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/__init__.py @@ -0,0 +1,327 @@ +""" +======================================= +Signal processing (:mod:`scipy.signal`) +======================================= + +Convolution +=========== + +.. autosummary:: + :toctree: generated/ + + convolve -- N-D convolution. + correlate -- N-D correlation. + fftconvolve -- N-D convolution using the FFT. + oaconvolve -- N-D convolution using the overlap-add method. + convolve2d -- 2-D convolution (more options). + correlate2d -- 2-D correlation (more options). + sepfir2d -- Convolve with a 2-D separable FIR filter. + choose_conv_method -- Chooses faster of FFT and direct convolution methods. + correlation_lags -- Determines lag indices for 1D cross-correlation. + +B-splines +========= + +.. autosummary:: + :toctree: generated/ + + gauss_spline -- Gaussian approximation to the B-spline basis function. + cspline1d -- Coefficients for 1-D cubic (3rd order) B-spline. + qspline1d -- Coefficients for 1-D quadratic (2nd order) B-spline. + cspline2d -- Coefficients for 2-D cubic (3rd order) B-spline. + qspline2d -- Coefficients for 2-D quadratic (2nd order) B-spline. + cspline1d_eval -- Evaluate a cubic spline at the given points. + qspline1d_eval -- Evaluate a quadratic spline at the given points. + spline_filter -- Smoothing spline (cubic) filtering of a rank-2 array. + +Filtering +========= + +.. autosummary:: + :toctree: generated/ + + order_filter -- N-D order filter. + medfilt -- N-D median filter. + medfilt2d -- 2-D median filter (faster). + wiener -- N-D Wiener filter. + + symiirorder1 -- 2nd-order IIR filter (cascade of first-order systems). + symiirorder2 -- 4th-order IIR filter (cascade of second-order systems). + lfilter -- 1-D FIR and IIR digital linear filtering. + lfiltic -- Construct initial conditions for `lfilter`. + lfilter_zi -- Compute an initial state zi for the lfilter function that + -- corresponds to the steady state of the step response. + filtfilt -- A forward-backward filter. + savgol_filter -- Filter a signal using the Savitzky-Golay filter. + + deconvolve -- 1-D deconvolution using lfilter. + + sosfilt -- 1-D IIR digital linear filtering using + -- a second-order sections filter representation. + sosfilt_zi -- Compute an initial state zi for the sosfilt function that + -- corresponds to the steady state of the step response. + sosfiltfilt -- A forward-backward filter for second-order sections. + hilbert -- Compute 1-D analytic signal, using the Hilbert transform. + hilbert2 -- Compute 2-D analytic signal, using the Hilbert transform. + envelope -- Compute the envelope of a real- or complex-valued signal. + + decimate -- Downsample a signal. + detrend -- Remove linear and/or constant trends from data. + resample -- Resample using Fourier method. + resample_poly -- Resample using polyphase filtering method. + upfirdn -- Upsample, apply FIR filter, downsample. + +Filter design +============= + +.. autosummary:: + :toctree: generated/ + + bilinear -- Digital filter from an analog filter using + -- the bilinear transform. + bilinear_zpk -- Digital filter from an analog filter using + -- the bilinear transform. + findfreqs -- Find array of frequencies for computing filter response. + firls -- FIR filter design using least-squares error minimization. + firwin -- Windowed FIR filter design, with frequency response + -- defined as pass and stop bands. + firwin2 -- Windowed FIR filter design, with arbitrary frequency + -- response. + freqs -- Analog filter frequency response from TF coefficients. + freqs_zpk -- Analog filter frequency response from ZPK coefficients. + freqz -- Digital filter frequency response from TF coefficients. + freqz_sos -- Digital filter frequency response for SOS format filter. + freqz_zpk -- Digital filter frequency response from ZPK coefficients. + gammatone -- FIR and IIR gammatone filter design. + group_delay -- Digital filter group delay. + iirdesign -- IIR filter design given bands and gains. + iirfilter -- IIR filter design given order and critical frequencies. + kaiser_atten -- Compute the attenuation of a Kaiser FIR filter, given + -- the number of taps and the transition width at + -- discontinuities in the frequency response. + kaiser_beta -- Compute the Kaiser parameter beta, given the desired + -- FIR filter attenuation. + kaiserord -- Design a Kaiser window to limit ripple and width of + -- transition region. + minimum_phase -- Convert a linear phase FIR filter to minimum phase. + savgol_coeffs -- Compute the FIR filter coefficients for a Savitzky-Golay + -- filter. + remez -- Optimal FIR filter design. + + unique_roots -- Unique roots and their multiplicities. + residue -- Partial fraction expansion of b(s) / a(s). + residuez -- Partial fraction expansion of b(z) / a(z). + invres -- Inverse partial fraction expansion for analog filter. + invresz -- Inverse partial fraction expansion for digital filter. + BadCoefficients -- Warning on badly conditioned filter coefficients. + +Lower-level filter design functions: + +.. autosummary:: + :toctree: generated/ + + abcd_normalize -- Check state-space matrices and ensure they are rank-2. + band_stop_obj -- Band Stop Objective Function for order minimization. + besselap -- Return (z,p,k) for analog prototype of Bessel filter. + buttap -- Return (z,p,k) for analog prototype of Butterworth filter. + cheb1ap -- Return (z,p,k) for type I Chebyshev filter. + cheb2ap -- Return (z,p,k) for type II Chebyshev filter. + ellipap -- Return (z,p,k) for analog prototype of elliptic filter. + lp2bp -- Transform a lowpass filter prototype to a bandpass filter. + lp2bp_zpk -- Transform a lowpass filter prototype to a bandpass filter. + lp2bs -- Transform a lowpass filter prototype to a bandstop filter. + lp2bs_zpk -- Transform a lowpass filter prototype to a bandstop filter. + lp2hp -- Transform a lowpass filter prototype to a highpass filter. + lp2hp_zpk -- Transform a lowpass filter prototype to a highpass filter. + lp2lp -- Transform a lowpass filter prototype to a lowpass filter. + lp2lp_zpk -- Transform a lowpass filter prototype to a lowpass filter. + normalize -- Normalize polynomial representation of a transfer function. + + + +Matlab-style IIR filter design +============================== + +.. autosummary:: + :toctree: generated/ + + butter -- Butterworth + buttord + cheby1 -- Chebyshev Type I + cheb1ord + cheby2 -- Chebyshev Type II + cheb2ord + ellip -- Elliptic (Cauer) + ellipord + bessel -- Bessel (no order selection available -- try butterod) + iirnotch -- Design second-order IIR notch digital filter. + iirpeak -- Design second-order IIR peak (resonant) digital filter. + iircomb -- Design IIR comb filter. + +Continuous-time linear systems +============================== + +.. autosummary:: + :toctree: generated/ + + lti -- Continuous-time linear time invariant system base class. + StateSpace -- Linear time invariant system in state space form. + TransferFunction -- Linear time invariant system in transfer function form. + ZerosPolesGain -- Linear time invariant system in zeros, poles, gain form. + lsim -- Continuous-time simulation of output to linear system. + impulse -- Impulse response of linear, time-invariant (LTI) system. + step -- Step response of continuous-time LTI system. + freqresp -- Frequency response of a continuous-time LTI system. + bode -- Bode magnitude and phase data (continuous-time LTI). + +Discrete-time linear systems +============================ + +.. autosummary:: + :toctree: generated/ + + dlti -- Discrete-time linear time invariant system base class. + StateSpace -- Linear time invariant system in state space form. + TransferFunction -- Linear time invariant system in transfer function form. + ZerosPolesGain -- Linear time invariant system in zeros, poles, gain form. + dlsim -- Simulation of output to a discrete-time linear system. + dimpulse -- Impulse response of a discrete-time LTI system. + dstep -- Step response of a discrete-time LTI system. + dfreqresp -- Frequency response of a discrete-time LTI system. + dbode -- Bode magnitude and phase data (discrete-time LTI). + +LTI representations +=================== + +.. autosummary:: + :toctree: generated/ + + tf2zpk -- Transfer function to zero-pole-gain. + tf2sos -- Transfer function to second-order sections. + tf2ss -- Transfer function to state-space. + zpk2tf -- Zero-pole-gain to transfer function. + zpk2sos -- Zero-pole-gain to second-order sections. + zpk2ss -- Zero-pole-gain to state-space. + ss2tf -- State-pace to transfer function. + ss2zpk -- State-space to pole-zero-gain. + sos2zpk -- Second-order sections to zero-pole-gain. + sos2tf -- Second-order sections to transfer function. + cont2discrete -- Continuous-time to discrete-time LTI conversion. + place_poles -- Pole placement. + +Waveforms +========= + +.. autosummary:: + :toctree: generated/ + + chirp -- Frequency swept cosine signal, with several freq functions. + gausspulse -- Gaussian modulated sinusoid. + max_len_seq -- Maximum length sequence. + sawtooth -- Periodic sawtooth. + square -- Square wave. + sweep_poly -- Frequency swept cosine signal; freq is arbitrary polynomial. + unit_impulse -- Discrete unit impulse. + +Window functions +================ + +For window functions, see the `scipy.signal.windows` namespace. + +In the `scipy.signal` namespace, there is a convenience function to +obtain these windows by name: + +.. autosummary:: + :toctree: generated/ + + get_window -- Return a window of a given length and type. + +Peak finding +============ + +.. autosummary:: + :toctree: generated/ + + argrelmin -- Calculate the relative minima of data. + argrelmax -- Calculate the relative maxima of data. + argrelextrema -- Calculate the relative extrema of data. + find_peaks -- Find a subset of peaks inside a signal. + find_peaks_cwt -- Find peaks in a 1-D array with wavelet transformation. + peak_prominences -- Calculate the prominence of each peak in a signal. + peak_widths -- Calculate the width of each peak in a signal. + +Spectral analysis +================= + +.. autosummary:: + :toctree: generated/ + + periodogram -- Compute a (modified) periodogram. + welch -- Compute a periodogram using Welch's method. + csd -- Compute the cross spectral density, using Welch's method. + coherence -- Compute the magnitude squared coherence, using Welch's method. + spectrogram -- Compute the spectrogram (legacy). + lombscargle -- Computes the Lomb-Scargle periodogram. + vectorstrength -- Computes the vector strength. + ShortTimeFFT -- Interface for calculating the \ + :ref:`Short Time Fourier Transform ` and \ + its inverse. + stft -- Compute the Short Time Fourier Transform (legacy). + istft -- Compute the Inverse Short Time Fourier Transform (legacy). + check_COLA -- Check the COLA constraint for iSTFT reconstruction. + check_NOLA -- Check the NOLA constraint for iSTFT reconstruction. + +Chirp Z-transform and Zoom FFT +============================================ + +.. autosummary:: + :toctree: generated/ + + czt - Chirp z-transform convenience function + zoom_fft - Zoom FFT convenience function + CZT - Chirp z-transform function generator + ZoomFFT - Zoom FFT function generator + czt_points - Output the z-plane points sampled by a chirp z-transform + +The functions are simpler to use than the classes, but are less efficient when +using the same transform on many arrays of the same length, since they +repeatedly generate the same chirp signal with every call. In these cases, +use the classes to create a reusable function instead. + +""" + +from . import _sigtools, windows +from ._waveforms import * +from ._max_len_seq import max_len_seq +from ._upfirdn import upfirdn + +from ._spline import ( + sepfir2d +) + +from ._spline_filters import * +from ._filter_design import * +from ._fir_filter_design import * +from ._ltisys import * +from ._lti_conversion import * +from ._signaltools import * +from ._savitzky_golay import savgol_coeffs, savgol_filter +from ._spectral_py import * +from ._short_time_fft import * +from ._peak_finding import * +from ._czt import * +from .windows import get_window # keep this one in signal namespace + +# Deprecated namespaces, to be removed in v2.0.0 +from . import ( + bsplines, filter_design, fir_filter_design, lti_conversion, ltisys, + spectral, signaltools, waveforms, wavelets, spline +) + +__all__ = [ + s for s in dir() if not s.startswith("_") +] + +from scipy._lib._testutils import PytestTester +test = PytestTester(__name__) +del PytestTester diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_arraytools.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_arraytools.py new file mode 100644 index 0000000000000000000000000000000000000000..87ce75d8d892a64021da7abc5d149556c22cf983 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_arraytools.py @@ -0,0 +1,264 @@ +""" +Functions for acting on a axis of an array. +""" +import numpy as np + + +def axis_slice(a, start=None, stop=None, step=None, axis=-1): + """Take a slice along axis 'axis' from 'a'. + + Parameters + ---------- + a : numpy.ndarray + The array to be sliced. + start, stop, step : int or None + The slice parameters. + axis : int, optional + The axis of `a` to be sliced. + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal._arraytools import axis_slice + >>> a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + >>> axis_slice(a, start=0, stop=1, axis=1) + array([[1], + [4], + [7]]) + >>> axis_slice(a, start=1, axis=0) + array([[4, 5, 6], + [7, 8, 9]]) + + Notes + ----- + The keyword arguments start, stop and step are used by calling + slice(start, stop, step). This implies axis_slice() does not + handle its arguments the exactly the same as indexing. To select + a single index k, for example, use + axis_slice(a, start=k, stop=k+1) + In this case, the length of the axis 'axis' in the result will + be 1; the trivial dimension is not removed. (Use numpy.squeeze() + to remove trivial axes.) + """ + a_slice = [slice(None)] * a.ndim + a_slice[axis] = slice(start, stop, step) + b = a[tuple(a_slice)] + return b + + +def axis_reverse(a, axis=-1): + """Reverse the 1-D slices of `a` along axis `axis`. + + Returns axis_slice(a, step=-1, axis=axis). + """ + return axis_slice(a, step=-1, axis=axis) + + +def odd_ext(x, n, axis=-1): + """ + Odd extension at the boundaries of an array + + Generate a new ndarray by making an odd extension of `x` along an axis. + + Parameters + ---------- + x : ndarray + The array to be extended. + n : int + The number of elements by which to extend `x` at each end of the axis. + axis : int, optional + The axis along which to extend `x`. Default is -1. + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal._arraytools import odd_ext + >>> a = np.array([[1, 2, 3, 4, 5], [0, 1, 4, 9, 16]]) + >>> odd_ext(a, 2) + array([[-1, 0, 1, 2, 3, 4, 5, 6, 7], + [-4, -1, 0, 1, 4, 9, 16, 23, 28]]) + + Odd extension is a "180 degree rotation" at the endpoints of the original + array: + + >>> t = np.linspace(0, 1.5, 100) + >>> a = 0.9 * np.sin(2 * np.pi * t**2) + >>> b = odd_ext(a, 40) + >>> import matplotlib.pyplot as plt + >>> plt.plot(np.arange(-40, 140), b, 'b', lw=1, label='odd extension') + >>> plt.plot(np.arange(100), a, 'r', lw=2, label='original') + >>> plt.legend(loc='best') + >>> plt.show() + """ + if n < 1: + return x + if n > x.shape[axis] - 1: + raise ValueError(("The extension length n (%d) is too big. " + + "It must not exceed x.shape[axis]-1, which is %d.") + % (n, x.shape[axis] - 1)) + left_end = axis_slice(x, start=0, stop=1, axis=axis) + left_ext = axis_slice(x, start=n, stop=0, step=-1, axis=axis) + right_end = axis_slice(x, start=-1, axis=axis) + right_ext = axis_slice(x, start=-2, stop=-(n + 2), step=-1, axis=axis) + ext = np.concatenate((2 * left_end - left_ext, + x, + 2 * right_end - right_ext), + axis=axis) + return ext + + +def even_ext(x, n, axis=-1): + """ + Even extension at the boundaries of an array + + Generate a new ndarray by making an even extension of `x` along an axis. + + Parameters + ---------- + x : ndarray + The array to be extended. + n : int + The number of elements by which to extend `x` at each end of the axis. + axis : int, optional + The axis along which to extend `x`. Default is -1. + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal._arraytools import even_ext + >>> a = np.array([[1, 2, 3, 4, 5], [0, 1, 4, 9, 16]]) + >>> even_ext(a, 2) + array([[ 3, 2, 1, 2, 3, 4, 5, 4, 3], + [ 4, 1, 0, 1, 4, 9, 16, 9, 4]]) + + Even extension is a "mirror image" at the boundaries of the original array: + + >>> t = np.linspace(0, 1.5, 100) + >>> a = 0.9 * np.sin(2 * np.pi * t**2) + >>> b = even_ext(a, 40) + >>> import matplotlib.pyplot as plt + >>> plt.plot(np.arange(-40, 140), b, 'b', lw=1, label='even extension') + >>> plt.plot(np.arange(100), a, 'r', lw=2, label='original') + >>> plt.legend(loc='best') + >>> plt.show() + """ + if n < 1: + return x + if n > x.shape[axis] - 1: + raise ValueError(("The extension length n (%d) is too big. " + + "It must not exceed x.shape[axis]-1, which is %d.") + % (n, x.shape[axis] - 1)) + left_ext = axis_slice(x, start=n, stop=0, step=-1, axis=axis) + right_ext = axis_slice(x, start=-2, stop=-(n + 2), step=-1, axis=axis) + ext = np.concatenate((left_ext, + x, + right_ext), + axis=axis) + return ext + + +def const_ext(x, n, axis=-1): + """ + Constant extension at the boundaries of an array + + Generate a new ndarray that is a constant extension of `x` along an axis. + + The extension repeats the values at the first and last element of + the axis. + + Parameters + ---------- + x : ndarray + The array to be extended. + n : int + The number of elements by which to extend `x` at each end of the axis. + axis : int, optional + The axis along which to extend `x`. Default is -1. + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal._arraytools import const_ext + >>> a = np.array([[1, 2, 3, 4, 5], [0, 1, 4, 9, 16]]) + >>> const_ext(a, 2) + array([[ 1, 1, 1, 2, 3, 4, 5, 5, 5], + [ 0, 0, 0, 1, 4, 9, 16, 16, 16]]) + + Constant extension continues with the same values as the endpoints of the + array: + + >>> t = np.linspace(0, 1.5, 100) + >>> a = 0.9 * np.sin(2 * np.pi * t**2) + >>> b = const_ext(a, 40) + >>> import matplotlib.pyplot as plt + >>> plt.plot(np.arange(-40, 140), b, 'b', lw=1, label='constant extension') + >>> plt.plot(np.arange(100), a, 'r', lw=2, label='original') + >>> plt.legend(loc='best') + >>> plt.show() + """ + if n < 1: + return x + left_end = axis_slice(x, start=0, stop=1, axis=axis) + ones_shape = [1] * x.ndim + ones_shape[axis] = n + ones = np.ones(ones_shape, dtype=x.dtype) + left_ext = ones * left_end + right_end = axis_slice(x, start=-1, axis=axis) + right_ext = ones * right_end + ext = np.concatenate((left_ext, + x, + right_ext), + axis=axis) + return ext + + +def zero_ext(x, n, axis=-1): + """ + Zero padding at the boundaries of an array + + Generate a new ndarray that is a zero-padded extension of `x` along + an axis. + + Parameters + ---------- + x : ndarray + The array to be extended. + n : int + The number of elements by which to extend `x` at each end of the + axis. + axis : int, optional + The axis along which to extend `x`. Default is -1. + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal._arraytools import zero_ext + >>> a = np.array([[1, 2, 3, 4, 5], [0, 1, 4, 9, 16]]) + >>> zero_ext(a, 2) + array([[ 0, 0, 1, 2, 3, 4, 5, 0, 0], + [ 0, 0, 0, 1, 4, 9, 16, 0, 0]]) + """ + if n < 1: + return x + zeros_shape = list(x.shape) + zeros_shape[axis] = n + zeros = np.zeros(zeros_shape, dtype=x.dtype) + ext = np.concatenate((zeros, x, zeros), axis=axis) + return ext + + +def _validate_fs(fs, allow_none=True): + """ + Check if the given sampling frequency is a scalar and raises an exception + otherwise. If allow_none is False, also raises an exception for none + sampling rates. Returns the sampling frequency as float or none if the + input is none. + """ + if fs is None: + if not allow_none: + raise ValueError("Sampling frequency can not be none.") + else: # should be float + if not np.isscalar(fs): + raise ValueError("Sampling frequency fs must be a single scalar.") + fs = float(fs) + return fs diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_czt.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_czt.py new file mode 100644 index 0000000000000000000000000000000000000000..c5e5715b460fb2719b68d4694474bc1efc0a9fa0 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_czt.py @@ -0,0 +1,575 @@ +# This program is public domain +# Authors: Paul Kienzle, Nadav Horesh +""" +Chirp z-transform. + +We provide two interfaces to the chirp z-transform: an object interface +which precalculates part of the transform and can be applied efficiently +to many different data sets, and a functional interface which is applied +only to the given data set. + +Transforms +---------- + +CZT : callable (x, axis=-1) -> array + Define a chirp z-transform that can be applied to different signals. +ZoomFFT : callable (x, axis=-1) -> array + Define a Fourier transform on a range of frequencies. + +Functions +--------- + +czt : array + Compute the chirp z-transform for a signal. +zoom_fft : array + Compute the Fourier transform on a range of frequencies. +""" + +import cmath +import numbers +import numpy as np +from numpy import pi, arange +from scipy.fft import fft, ifft, next_fast_len + +__all__ = ['czt', 'zoom_fft', 'CZT', 'ZoomFFT', 'czt_points'] + + +def _validate_sizes(n, m): + if n < 1 or not isinstance(n, numbers.Integral): + raise ValueError('Invalid number of CZT data ' + f'points ({n}) specified. ' + 'n must be positive and integer type.') + + if m is None: + m = n + elif m < 1 or not isinstance(m, numbers.Integral): + raise ValueError('Invalid number of CZT output ' + f'points ({m}) specified. ' + 'm must be positive and integer type.') + + return m + + +def czt_points(m, w=None, a=1+0j): + """ + Return the points at which the chirp z-transform is computed. + + Parameters + ---------- + m : int + The number of points desired. + w : complex, optional + The ratio between points in each step. + Defaults to equally spaced points around the entire unit circle. + a : complex, optional + The starting point in the complex plane. Default is 1+0j. + + Returns + ------- + out : ndarray + The points in the Z plane at which `CZT` samples the z-transform, + when called with arguments `m`, `w`, and `a`, as complex numbers. + + See Also + -------- + CZT : Class that creates a callable chirp z-transform function. + czt : Convenience function for quickly calculating CZT. + + Examples + -------- + Plot the points of a 16-point FFT: + + >>> import numpy as np + >>> from scipy.signal import czt_points + >>> points = czt_points(16) + >>> import matplotlib.pyplot as plt + >>> plt.plot(points.real, points.imag, 'o') + >>> plt.gca().add_patch(plt.Circle((0,0), radius=1, fill=False, alpha=.3)) + >>> plt.axis('equal') + >>> plt.show() + + and a 91-point logarithmic spiral that crosses the unit circle: + + >>> m, w, a = 91, 0.995*np.exp(-1j*np.pi*.05), 0.8*np.exp(1j*np.pi/6) + >>> points = czt_points(m, w, a) + >>> plt.plot(points.real, points.imag, 'o') + >>> plt.gca().add_patch(plt.Circle((0,0), radius=1, fill=False, alpha=.3)) + >>> plt.axis('equal') + >>> plt.show() + """ + m = _validate_sizes(1, m) + + k = arange(m) + + a = 1.0 * a # at least float + + if w is None: + # Nothing specified, default to FFT + return a * np.exp(2j * pi * k / m) + else: + # w specified + w = 1.0 * w # at least float + return a * w**-k + + +class CZT: + """ + Create a callable chirp z-transform function. + + Transform to compute the frequency response around a spiral. + Objects of this class are callables which can compute the + chirp z-transform on their inputs. This object precalculates the constant + chirps used in the given transform. + + Parameters + ---------- + n : int + The size of the signal. + m : int, optional + The number of output points desired. Default is `n`. + w : complex, optional + The ratio between points in each step. This must be precise or the + accumulated error will degrade the tail of the output sequence. + Defaults to equally spaced points around the entire unit circle. + a : complex, optional + The starting point in the complex plane. Default is 1+0j. + + Returns + ------- + f : CZT + Callable object ``f(x, axis=-1)`` for computing the chirp z-transform + on `x`. + + See Also + -------- + czt : Convenience function for quickly calculating CZT. + ZoomFFT : Class that creates a callable partial FFT function. + + Notes + ----- + The defaults are chosen such that ``f(x)`` is equivalent to + ``fft.fft(x)`` and, if ``m > len(x)``, that ``f(x, m)`` is equivalent to + ``fft.fft(x, m)``. + + If `w` does not lie on the unit circle, then the transform will be + around a spiral with exponentially-increasing radius. Regardless, + angle will increase linearly. + + For transforms that do lie on the unit circle, accuracy is better when + using `ZoomFFT`, since any numerical error in `w` is + accumulated for long data lengths, drifting away from the unit circle. + + The chirp z-transform can be faster than an equivalent FFT with + zero padding. Try it with your own array sizes to see. + + However, the chirp z-transform is considerably less precise than the + equivalent zero-padded FFT. + + As this CZT is implemented using the Bluestein algorithm, it can compute + large prime-length Fourier transforms in O(N log N) time, rather than the + O(N**2) time required by the direct DFT calculation. (`scipy.fft` also + uses Bluestein's algorithm'.) + + (The name "chirp z-transform" comes from the use of a chirp in the + Bluestein algorithm. It does not decompose signals into chirps, like + other transforms with "chirp" in the name.) + + References + ---------- + .. [1] Leo I. Bluestein, "A linear filtering approach to the computation + of the discrete Fourier transform," Northeast Electronics Research + and Engineering Meeting Record 10, 218-219 (1968). + .. [2] Rabiner, Schafer, and Rader, "The chirp z-transform algorithm and + its application," Bell Syst. Tech. J. 48, 1249-1292 (1969). + + Examples + -------- + Compute multiple prime-length FFTs: + + >>> from scipy.signal import CZT + >>> import numpy as np + >>> a = np.random.rand(7) + >>> b = np.random.rand(7) + >>> c = np.random.rand(7) + >>> czt_7 = CZT(n=7) + >>> A = czt_7(a) + >>> B = czt_7(b) + >>> C = czt_7(c) + + Display the points at which the FFT is calculated: + + >>> czt_7.points() + array([ 1.00000000+0.j , 0.62348980+0.78183148j, + -0.22252093+0.97492791j, -0.90096887+0.43388374j, + -0.90096887-0.43388374j, -0.22252093-0.97492791j, + 0.62348980-0.78183148j]) + >>> import matplotlib.pyplot as plt + >>> plt.plot(czt_7.points().real, czt_7.points().imag, 'o') + >>> plt.gca().add_patch(plt.Circle((0,0), radius=1, fill=False, alpha=.3)) + >>> plt.axis('equal') + >>> plt.show() + """ + + def __init__(self, n, m=None, w=None, a=1+0j): + m = _validate_sizes(n, m) + + k = arange(max(m, n), dtype=np.min_scalar_type(-max(m, n)**2)) + + if w is None: + # Nothing specified, default to FFT-like + w = cmath.exp(-2j*pi/m) + wk2 = np.exp(-(1j * pi * ((k**2) % (2*m))) / m) + else: + # w specified + wk2 = w**(k**2/2.) + + a = 1.0 * a # at least float + + self.w, self.a = w, a + self.m, self.n = m, n + + nfft = next_fast_len(n + m - 1) + self._Awk2 = a**-k[:n] * wk2[:n] + self._nfft = nfft + self._Fwk2 = fft(1/np.hstack((wk2[n-1:0:-1], wk2[:m])), nfft) + self._wk2 = wk2[:m] + self._yidx = slice(n-1, n+m-1) + + def __call__(self, x, *, axis=-1): + """ + Calculate the chirp z-transform of a signal. + + Parameters + ---------- + x : array + The signal to transform. + axis : int, optional + Axis over which to compute the FFT. If not given, the last axis is + used. + + Returns + ------- + out : ndarray + An array of the same dimensions as `x`, but with the length of the + transformed axis set to `m`. + """ + x = np.asarray(x) + if x.shape[axis] != self.n: + raise ValueError(f"CZT defined for length {self.n}, not " + f"{x.shape[axis]}") + # Calculate transpose coordinates, to allow operation on any given axis + trnsp = np.arange(x.ndim) + trnsp[[axis, -1]] = [-1, axis] + x = x.transpose(*trnsp) + y = ifft(self._Fwk2 * fft(x*self._Awk2, self._nfft)) + y = y[..., self._yidx] * self._wk2 + return y.transpose(*trnsp) + + def points(self): + """ + Return the points at which the chirp z-transform is computed. + """ + return czt_points(self.m, self.w, self.a) + + +class ZoomFFT(CZT): + """ + Create a callable zoom FFT transform function. + + This is a specialization of the chirp z-transform (`CZT`) for a set of + equally-spaced frequencies around the unit circle, used to calculate a + section of the FFT more efficiently than calculating the entire FFT and + truncating. + + Parameters + ---------- + n : int + The size of the signal. + fn : array_like + A length-2 sequence [`f1`, `f2`] giving the frequency range, or a + scalar, for which the range [0, `fn`] is assumed. + m : int, optional + The number of points to evaluate. Default is `n`. + fs : float, optional + The sampling frequency. If ``fs=10`` represented 10 kHz, for example, + then `f1` and `f2` would also be given in kHz. + The default sampling frequency is 2, so `f1` and `f2` should be + in the range [0, 1] to keep the transform below the Nyquist + frequency. + endpoint : bool, optional + If True, `f2` is the last sample. Otherwise, it is not included. + Default is False. + + Returns + ------- + f : ZoomFFT + Callable object ``f(x, axis=-1)`` for computing the zoom FFT on `x`. + + See Also + -------- + zoom_fft : Convenience function for calculating a zoom FFT. + + Notes + ----- + The defaults are chosen such that ``f(x, 2)`` is equivalent to + ``fft.fft(x)`` and, if ``m > len(x)``, that ``f(x, 2, m)`` is equivalent to + ``fft.fft(x, m)``. + + Sampling frequency is 1/dt, the time step between samples in the + signal `x`. The unit circle corresponds to frequencies from 0 up + to the sampling frequency. The default sampling frequency of 2 + means that `f1`, `f2` values up to the Nyquist frequency are in the + range [0, 1). For `f1`, `f2` values expressed in radians, a sampling + frequency of 2*pi should be used. + + Remember that a zoom FFT can only interpolate the points of the existing + FFT. It cannot help to resolve two separate nearby frequencies. + Frequency resolution can only be increased by increasing acquisition + time. + + These functions are implemented using Bluestein's algorithm (as is + `scipy.fft`). [2]_ + + References + ---------- + .. [1] Steve Alan Shilling, "A study of the chirp z-transform and its + applications", pg 29 (1970) + https://krex.k-state.edu/dspace/bitstream/handle/2097/7844/LD2668R41972S43.pdf + .. [2] Leo I. Bluestein, "A linear filtering approach to the computation + of the discrete Fourier transform," Northeast Electronics Research + and Engineering Meeting Record 10, 218-219 (1968). + + Examples + -------- + To plot the transform results use something like the following: + + >>> import numpy as np + >>> from scipy.signal import ZoomFFT + >>> t = np.linspace(0, 1, 1021) + >>> x = np.cos(2*np.pi*15*t) + np.sin(2*np.pi*17*t) + >>> f1, f2 = 5, 27 + >>> transform = ZoomFFT(len(x), [f1, f2], len(x), fs=1021) + >>> X = transform(x) + >>> f = np.linspace(f1, f2, len(x)) + >>> import matplotlib.pyplot as plt + >>> plt.plot(f, 20*np.log10(np.abs(X))) + >>> plt.show() + """ + + def __init__(self, n, fn, m=None, *, fs=2, endpoint=False): + m = _validate_sizes(n, m) + + k = arange(max(m, n), dtype=np.min_scalar_type(-max(m, n)**2)) + + if np.size(fn) == 2: + f1, f2 = fn + elif np.size(fn) == 1: + f1, f2 = 0.0, fn + else: + raise ValueError('fn must be a scalar or 2-length sequence') + + self.f1, self.f2, self.fs = f1, f2, fs + + if endpoint: + scale = ((f2 - f1) * m) / (fs * (m - 1)) + else: + scale = (f2 - f1) / fs + a = cmath.exp(2j * pi * f1/fs) + wk2 = np.exp(-(1j * pi * scale * k**2) / m) + + self.w = cmath.exp(-2j*pi/m * scale) + self.a = a + self.m, self.n = m, n + + ak = np.exp(-2j * pi * f1/fs * k[:n]) + self._Awk2 = ak * wk2[:n] + + nfft = next_fast_len(n + m - 1) + self._nfft = nfft + self._Fwk2 = fft(1/np.hstack((wk2[n-1:0:-1], wk2[:m])), nfft) + self._wk2 = wk2[:m] + self._yidx = slice(n-1, n+m-1) + + +def czt(x, m=None, w=None, a=1+0j, *, axis=-1): + """ + Compute the frequency response around a spiral in the Z plane. + + Parameters + ---------- + x : array + The signal to transform. + m : int, optional + The number of output points desired. Default is the length of the + input data. + w : complex, optional + The ratio between points in each step. This must be precise or the + accumulated error will degrade the tail of the output sequence. + Defaults to equally spaced points around the entire unit circle. + a : complex, optional + The starting point in the complex plane. Default is 1+0j. + axis : int, optional + Axis over which to compute the FFT. If not given, the last axis is + used. + + Returns + ------- + out : ndarray + An array of the same dimensions as `x`, but with the length of the + transformed axis set to `m`. + + See Also + -------- + CZT : Class that creates a callable chirp z-transform function. + zoom_fft : Convenience function for partial FFT calculations. + + Notes + ----- + The defaults are chosen such that ``signal.czt(x)`` is equivalent to + ``fft.fft(x)`` and, if ``m > len(x)``, that ``signal.czt(x, m)`` is + equivalent to ``fft.fft(x, m)``. + + If the transform needs to be repeated, use `CZT` to construct a + specialized transform function which can be reused without + recomputing constants. + + An example application is in system identification, repeatedly evaluating + small slices of the z-transform of a system, around where a pole is + expected to exist, to refine the estimate of the pole's true location. [1]_ + + References + ---------- + .. [1] Steve Alan Shilling, "A study of the chirp z-transform and its + applications", pg 20 (1970) + https://krex.k-state.edu/dspace/bitstream/handle/2097/7844/LD2668R41972S43.pdf + + Examples + -------- + Generate a sinusoid: + + >>> import numpy as np + >>> f1, f2, fs = 8, 10, 200 # Hz + >>> t = np.linspace(0, 1, fs, endpoint=False) + >>> x = np.sin(2*np.pi*t*f2) + >>> import matplotlib.pyplot as plt + >>> plt.plot(t, x) + >>> plt.axis([0, 1, -1.1, 1.1]) + >>> plt.show() + + Its discrete Fourier transform has all of its energy in a single frequency + bin: + + >>> from scipy.fft import rfft, rfftfreq + >>> from scipy.signal import czt, czt_points + >>> plt.plot(rfftfreq(fs, 1/fs), abs(rfft(x))) + >>> plt.margins(0, 0.1) + >>> plt.show() + + However, if the sinusoid is logarithmically-decaying: + + >>> x = np.exp(-t*f1) * np.sin(2*np.pi*t*f2) + >>> plt.plot(t, x) + >>> plt.axis([0, 1, -1.1, 1.1]) + >>> plt.show() + + the DFT will have spectral leakage: + + >>> plt.plot(rfftfreq(fs, 1/fs), abs(rfft(x))) + >>> plt.margins(0, 0.1) + >>> plt.show() + + While the DFT always samples the z-transform around the unit circle, the + chirp z-transform allows us to sample the Z-transform along any + logarithmic spiral, such as a circle with radius smaller than unity: + + >>> M = fs // 2 # Just positive frequencies, like rfft + >>> a = np.exp(-f1/fs) # Starting point of the circle, radius < 1 + >>> w = np.exp(-1j*np.pi/M) # "Step size" of circle + >>> points = czt_points(M + 1, w, a) # M + 1 to include Nyquist + >>> plt.plot(points.real, points.imag, '.') + >>> plt.gca().add_patch(plt.Circle((0,0), radius=1, fill=False, alpha=.3)) + >>> plt.axis('equal'); plt.axis([-1.05, 1.05, -0.05, 1.05]) + >>> plt.show() + + With the correct radius, this transforms the decaying sinusoid (and others + with the same decay rate) without spectral leakage: + + >>> z_vals = czt(x, M + 1, w, a) # Include Nyquist for comparison to rfft + >>> freqs = np.angle(points)*fs/(2*np.pi) # angle = omega, radius = sigma + >>> plt.plot(freqs, abs(z_vals)) + >>> plt.margins(0, 0.1) + >>> plt.show() + """ + x = np.asarray(x) + transform = CZT(x.shape[axis], m=m, w=w, a=a) + return transform(x, axis=axis) + + +def zoom_fft(x, fn, m=None, *, fs=2, endpoint=False, axis=-1): + """ + Compute the DFT of `x` only for frequencies in range `fn`. + + Parameters + ---------- + x : array + The signal to transform. + fn : array_like + A length-2 sequence [`f1`, `f2`] giving the frequency range, or a + scalar, for which the range [0, `fn`] is assumed. + m : int, optional + The number of points to evaluate. The default is the length of `x`. + fs : float, optional + The sampling frequency. If ``fs=10`` represented 10 kHz, for example, + then `f1` and `f2` would also be given in kHz. + The default sampling frequency is 2, so `f1` and `f2` should be + in the range [0, 1] to keep the transform below the Nyquist + frequency. + endpoint : bool, optional + If True, `f2` is the last sample. Otherwise, it is not included. + Default is False. + axis : int, optional + Axis over which to compute the FFT. If not given, the last axis is + used. + + Returns + ------- + out : ndarray + The transformed signal. The Fourier transform will be calculated + at the points f1, f1+df, f1+2df, ..., f2, where df=(f2-f1)/m. + + See Also + -------- + ZoomFFT : Class that creates a callable partial FFT function. + + Notes + ----- + The defaults are chosen such that ``signal.zoom_fft(x, 2)`` is equivalent + to ``fft.fft(x)`` and, if ``m > len(x)``, that ``signal.zoom_fft(x, 2, m)`` + is equivalent to ``fft.fft(x, m)``. + + To graph the magnitude of the resulting transform, use:: + + plot(linspace(f1, f2, m, endpoint=False), abs(zoom_fft(x, [f1, f2], m))) + + If the transform needs to be repeated, use `ZoomFFT` to construct + a specialized transform function which can be reused without + recomputing constants. + + Examples + -------- + To plot the transform results use something like the following: + + >>> import numpy as np + >>> from scipy.signal import zoom_fft + >>> t = np.linspace(0, 1, 1021) + >>> x = np.cos(2*np.pi*15*t) + np.sin(2*np.pi*17*t) + >>> f1, f2 = 5, 27 + >>> X = zoom_fft(x, [f1, f2], len(x), fs=1021) + >>> f = np.linspace(f1, f2, len(x)) + >>> import matplotlib.pyplot as plt + >>> plt.plot(f, 20*np.log10(np.abs(X))) + >>> plt.show() + """ + x = np.asarray(x) + transform = ZoomFFT(x.shape[axis], fn, m=m, fs=fs, endpoint=endpoint) + return transform(x, axis=axis) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_filter_design.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_filter_design.py new file mode 100644 index 0000000000000000000000000000000000000000..0f177247c602cd529a064cc043d8052aa6cbc811 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_filter_design.py @@ -0,0 +1,5663 @@ +"""Filter design.""" +import math +import operator +import warnings + +import numpy as np +from numpy import (atleast_1d, poly, polyval, roots, real, asarray, + resize, pi, absolute, sqrt, tan, log10, + arcsinh, sin, exp, cosh, arccosh, ceil, conjugate, + zeros, sinh, append, concatenate, prod, ones, full, array, + mintypecode) +from numpy.polynomial.polynomial import polyval as npp_polyval +from numpy.polynomial.polynomial import polyvalfromroots + +from scipy import special, optimize, fft as sp_fft +from scipy.special import comb +from scipy._lib._util import float_factorial +from scipy.signal._arraytools import _validate_fs + + +__all__ = ['findfreqs', 'freqs', 'freqz', 'tf2zpk', 'zpk2tf', 'normalize', + 'lp2lp', 'lp2hp', 'lp2bp', 'lp2bs', 'bilinear', 'iirdesign', + 'iirfilter', 'butter', 'cheby1', 'cheby2', 'ellip', 'bessel', + 'band_stop_obj', 'buttord', 'cheb1ord', 'cheb2ord', 'ellipord', + 'buttap', 'cheb1ap', 'cheb2ap', 'ellipap', 'besselap', + 'BadCoefficients', 'freqs_zpk', 'freqz_zpk', + 'tf2sos', 'sos2tf', 'zpk2sos', 'sos2zpk', 'group_delay', + 'sosfreqz', 'freqz_sos', 'iirnotch', 'iirpeak', 'bilinear_zpk', + 'lp2lp_zpk', 'lp2hp_zpk', 'lp2bp_zpk', 'lp2bs_zpk', + 'gammatone', 'iircomb'] + + +class BadCoefficients(UserWarning): + """Warning about badly conditioned filter coefficients""" + pass + + +abs = absolute + + +def _is_int_type(x): + """ + Check if input is of a scalar integer type (so ``5`` and ``array(5)`` will + pass, while ``5.0`` and ``array([5])`` will fail. + """ + if np.ndim(x) != 0: + # Older versions of NumPy did not raise for np.array([1]).__index__() + # This is safe to remove when support for those versions is dropped + return False + try: + operator.index(x) + except TypeError: + return False + else: + return True + + +def findfreqs(num, den, N, kind='ba'): + """ + Find array of frequencies for computing the response of an analog filter. + + Parameters + ---------- + num, den : array_like, 1-D + The polynomial coefficients of the numerator and denominator of the + transfer function of the filter or LTI system, where the coefficients + are ordered from highest to lowest degree. Or, the roots of the + transfer function numerator and denominator (i.e., zeroes and poles). + N : int + The length of the array to be computed. + kind : str {'ba', 'zp'}, optional + Specifies whether the numerator and denominator are specified by their + polynomial coefficients ('ba'), or their roots ('zp'). + + Returns + ------- + w : (N,) ndarray + A 1-D array of frequencies, logarithmically spaced. + + Examples + -------- + Find a set of nine frequencies that span the "interesting part" of the + frequency response for the filter with the transfer function + + H(s) = s / (s^2 + 8s + 25) + + >>> from scipy import signal + >>> signal.findfreqs([1, 0], [1, 8, 25], N=9) + array([ 1.00000000e-02, 3.16227766e-02, 1.00000000e-01, + 3.16227766e-01, 1.00000000e+00, 3.16227766e+00, + 1.00000000e+01, 3.16227766e+01, 1.00000000e+02]) + """ + if kind == 'ba': + ep = atleast_1d(roots(den)) + 0j + tz = atleast_1d(roots(num)) + 0j + elif kind == 'zp': + ep = atleast_1d(den) + 0j + tz = atleast_1d(num) + 0j + else: + raise ValueError("input must be one of {'ba', 'zp'}") + + if len(ep) == 0: + ep = atleast_1d(-1000) + 0j + + ez = np.r_[ep[ep.imag >= 0], tz[(np.abs(tz) < 1e5) & (tz.imag >= 0)]] + + integ = np.abs(ez) < 1e-10 + hfreq = np.round(np.log10(np.max(3 * np.abs(ez.real + integ) + + 1.5 * ez.imag)) + 0.5) + lfreq = np.round(np.log10(0.1 * np.min(np.abs((ez + integ).real) + + 2 * ez.imag)) - 0.5) + + w = np.logspace(lfreq, hfreq, N) + return w + + +def freqs(b, a, worN=200, plot=None): + """ + Compute frequency response of analog filter. + + Given the M-order numerator `b` and N-order denominator `a` of an analog + filter, compute its frequency response:: + + b[0]*(jw)**M + b[1]*(jw)**(M-1) + ... + b[M] + H(w) = ---------------------------------------------- + a[0]*(jw)**N + a[1]*(jw)**(N-1) + ... + a[N] + + Parameters + ---------- + b : array_like + Numerator of a linear filter. + a : array_like + Denominator of a linear filter. + worN : {None, int, array_like}, optional + If None, then compute at 200 frequencies around the interesting parts + of the response curve (determined by pole-zero locations). If a single + integer, then compute at that many frequencies. Otherwise, compute the + response at the angular frequencies (e.g., rad/s) given in `worN`. + plot : callable, optional + A callable that takes two arguments. If given, the return parameters + `w` and `h` are passed to plot. Useful for plotting the frequency + response inside `freqs`. + + Returns + ------- + w : ndarray + The angular frequencies at which `h` was computed. + h : ndarray + The frequency response. + + See Also + -------- + freqz : Compute the frequency response of a digital filter. + + Notes + ----- + Using Matplotlib's "plot" function as the callable for `plot` produces + unexpected results, this plots the real part of the complex transfer + function, not the magnitude. Try ``lambda w, h: plot(w, abs(h))``. + + Examples + -------- + >>> from scipy.signal import freqs, iirfilter + >>> import numpy as np + + >>> b, a = iirfilter(4, [1, 10], 1, 60, analog=True, ftype='cheby1') + + >>> w, h = freqs(b, a, worN=np.logspace(-1, 2, 1000)) + + >>> import matplotlib.pyplot as plt + >>> plt.semilogx(w, 20 * np.log10(abs(h))) + >>> plt.xlabel('Frequency [rad/s]') + >>> plt.ylabel('Amplitude response [dB]') + >>> plt.grid(True) + >>> plt.show() + + """ + if worN is None: + # For backwards compatibility + w = findfreqs(b, a, 200) + elif _is_int_type(worN): + w = findfreqs(b, a, worN) + else: + w = atleast_1d(worN) + + s = 1j * w + h = polyval(b, s) / polyval(a, s) + if plot is not None: + plot(w, h) + + return w, h + + +def freqs_zpk(z, p, k, worN=200): + """ + Compute frequency response of analog filter. + + Given the zeros `z`, poles `p`, and gain `k` of a filter, compute its + frequency response:: + + (jw-z[0]) * (jw-z[1]) * ... * (jw-z[-1]) + H(w) = k * ---------------------------------------- + (jw-p[0]) * (jw-p[1]) * ... * (jw-p[-1]) + + Parameters + ---------- + z : array_like + Zeroes of a linear filter + p : array_like + Poles of a linear filter + k : scalar + Gain of a linear filter + worN : {None, int, array_like}, optional + If None, then compute at 200 frequencies around the interesting parts + of the response curve (determined by pole-zero locations). If a single + integer, then compute at that many frequencies. Otherwise, compute the + response at the angular frequencies (e.g., rad/s) given in `worN`. + + Returns + ------- + w : ndarray + The angular frequencies at which `h` was computed. + h : ndarray + The frequency response. + + See Also + -------- + freqs : Compute the frequency response of an analog filter in TF form + freqz : Compute the frequency response of a digital filter in TF form + freqz_zpk : Compute the frequency response of a digital filter in ZPK form + + Notes + ----- + .. versionadded:: 0.19.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal import freqs_zpk, iirfilter + + >>> z, p, k = iirfilter(4, [1, 10], 1, 60, analog=True, ftype='cheby1', + ... output='zpk') + + >>> w, h = freqs_zpk(z, p, k, worN=np.logspace(-1, 2, 1000)) + + >>> import matplotlib.pyplot as plt + >>> plt.semilogx(w, 20 * np.log10(abs(h))) + >>> plt.xlabel('Frequency [rad/s]') + >>> plt.ylabel('Amplitude response [dB]') + >>> plt.grid(True) + >>> plt.show() + + """ + k = np.asarray(k) + if k.size > 1: + raise ValueError('k must be a single scalar gain') + + if worN is None: + # For backwards compatibility + w = findfreqs(z, p, 200, kind='zp') + elif _is_int_type(worN): + w = findfreqs(z, p, worN, kind='zp') + else: + w = worN + + w = atleast_1d(w) + s = 1j * w + num = polyvalfromroots(s, z) + den = polyvalfromroots(s, p) + h = k * num/den + return w, h + + +def freqz(b, a=1, worN=512, whole=False, plot=None, fs=2*pi, + include_nyquist=False): + """ + Compute the frequency response of a digital filter. + + Given the M-order numerator `b` and N-order denominator `a` of a digital + filter, compute its frequency response:: + + jw -jw -jwM + jw B(e ) b[0] + b[1]e + ... + b[M]e + H(e ) = ------ = ----------------------------------- + jw -jw -jwN + A(e ) a[0] + a[1]e + ... + a[N]e + + Parameters + ---------- + b : array_like + Numerator of a linear filter. If `b` has dimension greater than 1, + it is assumed that the coefficients are stored in the first dimension, + and ``b.shape[1:]``, ``a.shape[1:]``, and the shape of the frequencies + array must be compatible for broadcasting. + a : array_like + Denominator of a linear filter. If `b` has dimension greater than 1, + it is assumed that the coefficients are stored in the first dimension, + and ``b.shape[1:]``, ``a.shape[1:]``, and the shape of the frequencies + array must be compatible for broadcasting. + worN : {None, int, array_like}, optional + If a single integer, then compute at that many frequencies (default is + N=512). This is a convenient alternative to:: + + np.linspace(0, fs if whole else fs/2, N, endpoint=include_nyquist) + + Using a number that is fast for FFT computations can result in + faster computations (see Notes). + + If an array_like, compute the response at the frequencies given. + These are in the same units as `fs`. + whole : bool, optional + Normally, frequencies are computed from 0 to the Nyquist frequency, + fs/2 (upper-half of unit-circle). If `whole` is True, compute + frequencies from 0 to fs. Ignored if worN is array_like. + plot : callable + A callable that takes two arguments. If given, the return parameters + `w` and `h` are passed to plot. Useful for plotting the frequency + response inside `freqz`. + fs : float, optional + The sampling frequency of the digital system. Defaults to 2*pi + radians/sample (so w is from 0 to pi). + + .. versionadded:: 1.2.0 + include_nyquist : bool, optional + If `whole` is False and `worN` is an integer, setting `include_nyquist` + to True will include the last frequency (Nyquist frequency) and is + otherwise ignored. + + .. versionadded:: 1.5.0 + + Returns + ------- + w : ndarray + The frequencies at which `h` was computed, in the same units as `fs`. + By default, `w` is normalized to the range [0, pi) (radians/sample). + h : ndarray + The frequency response, as complex numbers. + + See Also + -------- + freqz_zpk + freqz_sos + + Notes + ----- + Using Matplotlib's :func:`matplotlib.pyplot.plot` function as the callable + for `plot` produces unexpected results, as this plots the real part of the + complex transfer function, not the magnitude. + Try ``lambda w, h: plot(w, np.abs(h))``. + + A direct computation via (R)FFT is used to compute the frequency response + when the following conditions are met: + + 1. An integer value is given for `worN`. + 2. `worN` is fast to compute via FFT (i.e., + `next_fast_len(worN) ` equals `worN`). + 3. The denominator coefficients are a single value (``a.shape[0] == 1``). + 4. `worN` is at least as long as the numerator coefficients + (``worN >= b.shape[0]``). + 5. If ``b.ndim > 1``, then ``b.shape[-1] == 1``. + + For long FIR filters, the FFT approach can have lower error and be much + faster than the equivalent direct polynomial calculation. + + Examples + -------- + >>> from scipy import signal + >>> import numpy as np + >>> taps, f_c = 80, 1.0 # number of taps and cut-off frequency + >>> b = signal.firwin(taps, f_c, window=('kaiser', 8), fs=2*np.pi) + >>> w, h = signal.freqz(b) + + >>> import matplotlib.pyplot as plt + >>> fig, ax1 = plt.subplots(tight_layout=True) + >>> ax1.set_title(f"Frequency Response of {taps} tap FIR Filter" + + ... f"($f_c={f_c}$ rad/sample)") + >>> ax1.axvline(f_c, color='black', linestyle=':', linewidth=0.8) + >>> ax1.plot(w, 20 * np.log10(abs(h)), 'C0') + >>> ax1.set_ylabel("Amplitude in dB", color='C0') + >>> ax1.set(xlabel="Frequency in rad/sample", xlim=(0, np.pi)) + + >>> ax2 = ax1.twinx() + >>> phase = np.unwrap(np.angle(h)) + >>> ax2.plot(w, phase, 'C1') + >>> ax2.set_ylabel('Phase [rad]', color='C1') + >>> ax2.grid(True) + >>> ax2.axis('tight') + >>> plt.show() + + Broadcasting Examples + + Suppose we have two FIR filters whose coefficients are stored in the + rows of an array with shape (2, 25). For this demonstration, we'll + use random data: + + >>> rng = np.random.default_rng() + >>> b = rng.random((2, 25)) + + To compute the frequency response for these two filters with one call + to `freqz`, we must pass in ``b.T``, because `freqz` expects the first + axis to hold the coefficients. We must then extend the shape with a + trivial dimension of length 1 to allow broadcasting with the array + of frequencies. That is, we pass in ``b.T[..., np.newaxis]``, which has + shape (25, 2, 1): + + >>> w, h = signal.freqz(b.T[..., np.newaxis], worN=1024) + >>> w.shape + (1024,) + >>> h.shape + (2, 1024) + + Now, suppose we have two transfer functions, with the same numerator + coefficients ``b = [0.5, 0.5]``. The coefficients for the two denominators + are stored in the first dimension of the 2-D array `a`:: + + a = [ 1 1 ] + [ -0.25, -0.5 ] + + >>> b = np.array([0.5, 0.5]) + >>> a = np.array([[1, 1], [-0.25, -0.5]]) + + Only `a` is more than 1-D. To make it compatible for + broadcasting with the frequencies, we extend it with a trivial dimension + in the call to `freqz`: + + >>> w, h = signal.freqz(b, a[..., np.newaxis], worN=1024) + >>> w.shape + (1024,) + >>> h.shape + (2, 1024) + + """ + b = atleast_1d(b) + a = atleast_1d(a) + + fs = _validate_fs(fs, allow_none=False) + + if worN is None: + # For backwards compatibility + worN = 512 + + h = None + + if _is_int_type(worN): + N = operator.index(worN) + del worN + if N < 0: + raise ValueError(f'worN must be nonnegative, got {N}') + lastpoint = 2 * pi if whole else pi + # if include_nyquist is true and whole is false, w should + # include end point + w = np.linspace(0, lastpoint, N, + endpoint=include_nyquist and not whole) + n_fft = N if whole else 2 * (N - 1) if include_nyquist else 2 * N + if (a.size == 1 and (b.ndim == 1 or (b.shape[-1] == 1)) + and n_fft >= b.shape[0] + and n_fft > 0): # TODO: review threshold acc. to benchmark? + if np.isrealobj(b) and np.isrealobj(a): + fft_func = sp_fft.rfft + else: + fft_func = sp_fft.fft + h = fft_func(b, n=n_fft, axis=0)[:N] + h /= a + if fft_func is sp_fft.rfft and whole: + # exclude DC and maybe Nyquist (no need to use axis_reverse + # here because we can build reversal with the truncation) + stop = -1 if n_fft % 2 == 1 else -2 + h_flip = slice(stop, 0, -1) + h = np.concatenate((h, h[h_flip].conj())) + if b.ndim > 1: + # Last axis of h has length 1, so drop it. + h = h[..., 0] + # Move the first axis of h to the end. + h = np.moveaxis(h, 0, -1) + else: + w = atleast_1d(worN) + del worN + w = 2*pi*w/fs + + if h is None: # still need to compute using freqs w + zm1 = exp(-1j * w) + h = (npp_polyval(zm1, b, tensor=False) / + npp_polyval(zm1, a, tensor=False)) + + w = w*(fs/(2*pi)) + + if plot is not None: + plot(w, h) + + return w, h + + +def freqz_zpk(z, p, k, worN=512, whole=False, fs=2*pi): + r""" + Compute the frequency response of a digital filter in ZPK form. + + Given the Zeros, Poles and Gain of a digital filter, compute its frequency + response: + + :math:`H(z)=k \prod_i (z - Z[i]) / \prod_j (z - P[j])` + + where :math:`k` is the `gain`, :math:`Z` are the `zeros` and :math:`P` are + the `poles`. + + Parameters + ---------- + z : array_like + Zeroes of a linear filter + p : array_like + Poles of a linear filter + k : scalar + Gain of a linear filter + worN : {None, int, array_like}, optional + If a single integer, then compute at that many frequencies (default is + N=512). + + If an array_like, compute the response at the frequencies given. + These are in the same units as `fs`. + whole : bool, optional + Normally, frequencies are computed from 0 to the Nyquist frequency, + fs/2 (upper-half of unit-circle). If `whole` is True, compute + frequencies from 0 to fs. Ignored if w is array_like. + fs : float, optional + The sampling frequency of the digital system. Defaults to 2*pi + radians/sample (so w is from 0 to pi). + + .. versionadded:: 1.2.0 + + Returns + ------- + w : ndarray + The frequencies at which `h` was computed, in the same units as `fs`. + By default, `w` is normalized to the range [0, pi) (radians/sample). + h : ndarray + The frequency response, as complex numbers. + + See Also + -------- + freqs : Compute the frequency response of an analog filter in TF form + freqs_zpk : Compute the frequency response of an analog filter in ZPK form + freqz : Compute the frequency response of a digital filter in TF form + + Notes + ----- + .. versionadded:: 0.19.0 + + Examples + -------- + Design a 4th-order digital Butterworth filter with cut-off of 100 Hz in a + system with sample rate of 1000 Hz, and plot the frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> z, p, k = signal.butter(4, 100, output='zpk', fs=1000) + >>> w, h = signal.freqz_zpk(z, p, k, fs=1000) + + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> ax1 = fig.add_subplot(1, 1, 1) + >>> ax1.set_title('Digital filter frequency response') + + >>> ax1.plot(w, 20 * np.log10(abs(h)), 'b') + >>> ax1.set_ylabel('Amplitude [dB]', color='b') + >>> ax1.set_xlabel('Frequency [Hz]') + >>> ax1.grid(True) + + >>> ax2 = ax1.twinx() + >>> phase = np.unwrap(np.angle(h)) + >>> ax2.plot(w, phase, 'g') + >>> ax2.set_ylabel('Phase [rad]', color='g') + + >>> plt.axis('tight') + >>> plt.show() + + """ + z, p = map(atleast_1d, (z, p)) + + fs = _validate_fs(fs, allow_none=False) + + if whole: + lastpoint = 2 * pi + else: + lastpoint = pi + + if worN is None: + # For backwards compatibility + w = np.linspace(0, lastpoint, 512, endpoint=False) + elif _is_int_type(worN): + w = np.linspace(0, lastpoint, worN, endpoint=False) + else: + w = atleast_1d(worN) + w = 2*pi*w/fs + + zm1 = exp(1j * w) + h = k * polyvalfromroots(zm1, z) / polyvalfromroots(zm1, p) + + w = w*(fs/(2*pi)) + + return w, h + + +def group_delay(system, w=512, whole=False, fs=2*pi): + r"""Compute the group delay of a digital filter. + + The group delay measures by how many samples amplitude envelopes of + various spectral components of a signal are delayed by a filter. + It is formally defined as the derivative of continuous (unwrapped) phase:: + + d jw + D(w) = - -- arg H(e) + dw + + Parameters + ---------- + system : tuple of array_like (b, a) + Numerator and denominator coefficients of a filter transfer function. + w : {None, int, array_like}, optional + If a single integer, then compute at that many frequencies (default is + N=512). + + If an array_like, compute the delay at the frequencies given. These + are in the same units as `fs`. + whole : bool, optional + Normally, frequencies are computed from 0 to the Nyquist frequency, + fs/2 (upper-half of unit-circle). If `whole` is True, compute + frequencies from 0 to fs. Ignored if w is array_like. + fs : float, optional + The sampling frequency of the digital system. Defaults to 2*pi + radians/sample (so w is from 0 to pi). + + .. versionadded:: 1.2.0 + + Returns + ------- + w : ndarray + The frequencies at which group delay was computed, in the same units + as `fs`. By default, `w` is normalized to the range [0, pi) + (radians/sample). + gd : ndarray + The group delay. + + See Also + -------- + freqz : Frequency response of a digital filter + + Notes + ----- + The similar function in MATLAB is called `grpdelay`. + + If the transfer function :math:`H(z)` has zeros or poles on the unit + circle, the group delay at corresponding frequencies is undefined. + When such a case arises the warning is raised and the group delay + is set to 0 at those frequencies. + + For the details of numerical computation of the group delay refer to [1]_ or [2]_. + + .. versionadded:: 0.16.0 + + References + ---------- + .. [1] Richard G. Lyons, "Understanding Digital Signal Processing, + 3rd edition", p. 830. + .. [2] Julius O. Smith III, "Numerical Computation of Group Delay", + in "Introduction to Digital Filters with Audio Applications", + online book, 2007, + https://ccrma.stanford.edu/~jos/fp/Numerical_Computation_Group_Delay.html + + Examples + -------- + >>> from scipy import signal + >>> b, a = signal.iirdesign(0.1, 0.3, 5, 50, ftype='cheby1') + >>> w, gd = signal.group_delay((b, a)) + + >>> import matplotlib.pyplot as plt + >>> plt.title('Digital filter group delay') + >>> plt.plot(w, gd) + >>> plt.ylabel('Group delay [samples]') + >>> plt.xlabel('Frequency [rad/sample]') + >>> plt.show() + + """ + if w is None: + # For backwards compatibility + w = 512 + + fs = _validate_fs(fs, allow_none=False) + + if _is_int_type(w): + if whole: + w = np.linspace(0, 2 * pi, w, endpoint=False) + else: + w = np.linspace(0, pi, w, endpoint=False) + else: + w = np.atleast_1d(w) + w = 2*pi*w/fs + + b, a = map(np.atleast_1d, system) + c = np.convolve(b, conjugate(a[::-1])) + cr = c * np.arange(c.size) + z = np.exp(-1j * w) + num = np.polyval(cr[::-1], z) + den = np.polyval(c[::-1], z) + gd = np.real(num / den) - a.size + 1 + singular = ~np.isfinite(gd) + near_singular = np.absolute(den) < 10 * EPSILON + + if np.any(singular): + gd[singular] = 0 + warnings.warn( + "The group delay is singular at frequencies " + f"[{', '.join(f'{ws:.3f}' for ws in w[singular])}], setting to 0", + stacklevel=2 + ) + + elif np.any(near_singular): + warnings.warn( + "The filter's denominator is extremely small at frequencies " + f"[{', '.join(f'{ws:.3f}' for ws in w[near_singular])}], " + "around which a singularity may be present", + stacklevel=2 + ) + + w = w*(fs/(2*pi)) + + return w, gd + + +def _validate_sos(sos): + """Helper to validate a SOS input""" + sos = np.atleast_2d(sos) + if sos.ndim != 2: + raise ValueError('sos array must be 2D') + n_sections, m = sos.shape + if m != 6: + raise ValueError('sos array must be shape (n_sections, 6)') + if not (sos[:, 3] == 1).all(): + raise ValueError('sos[:, 3] should be all ones') + return sos, n_sections + + +def freqz_sos(sos, worN=512, whole=False, fs=2*pi): + r""" + Compute the frequency response of a digital filter in SOS format. + + Given `sos`, an array with shape (n, 6) of second order sections of + a digital filter, compute the frequency response of the system function:: + + B0(z) B1(z) B{n-1}(z) + H(z) = ----- * ----- * ... * --------- + A0(z) A1(z) A{n-1}(z) + + for z = exp(omega*1j), where B{k}(z) and A{k}(z) are numerator and + denominator of the transfer function of the k-th second order section. + + Parameters + ---------- + sos : array_like + Array of second-order filter coefficients, must have shape + ``(n_sections, 6)``. Each row corresponds to a second-order + section, with the first three columns providing the numerator + coefficients and the last three providing the denominator + coefficients. + worN : {None, int, array_like}, optional + If a single integer, then compute at that many frequencies (default is + N=512). Using a number that is fast for FFT computations can result + in faster computations (see Notes of `freqz`). + + If an array_like, compute the response at the frequencies given (must + be 1-D). These are in the same units as `fs`. + whole : bool, optional + Normally, frequencies are computed from 0 to the Nyquist frequency, + fs/2 (upper-half of unit-circle). If `whole` is True, compute + frequencies from 0 to fs. + fs : float, optional + The sampling frequency of the digital system. Defaults to 2*pi + radians/sample (so w is from 0 to pi). + + .. versionadded:: 1.2.0 + + Returns + ------- + w : ndarray + The frequencies at which `h` was computed, in the same units as `fs`. + By default, `w` is normalized to the range [0, pi) (radians/sample). + h : ndarray + The frequency response, as complex numbers. + + See Also + -------- + freqz, sosfilt + + Notes + ----- + .. versionadded:: 0.19.0 + + Examples + -------- + Design a 15th-order bandpass filter in SOS format. + + >>> from scipy import signal + >>> import numpy as np + >>> sos = signal.ellip(15, 0.5, 60, (0.2, 0.4), btype='bandpass', + ... output='sos') + + Compute the frequency response at 1500 points from DC to Nyquist. + + >>> w, h = signal.freqz_sos(sos, worN=1500) + + Plot the response. + + >>> import matplotlib.pyplot as plt + >>> plt.subplot(2, 1, 1) + >>> db = 20*np.log10(np.maximum(np.abs(h), 1e-5)) + >>> plt.plot(w/np.pi, db) + >>> plt.ylim(-75, 5) + >>> plt.grid(True) + >>> plt.yticks([0, -20, -40, -60]) + >>> plt.ylabel('Gain [dB]') + >>> plt.title('Frequency Response') + >>> plt.subplot(2, 1, 2) + >>> plt.plot(w/np.pi, np.angle(h)) + >>> plt.grid(True) + >>> plt.yticks([-np.pi, -0.5*np.pi, 0, 0.5*np.pi, np.pi], + ... [r'$-\pi$', r'$-\pi/2$', '0', r'$\pi/2$', r'$\pi$']) + >>> plt.ylabel('Phase [rad]') + >>> plt.xlabel('Normalized frequency (1.0 = Nyquist)') + >>> plt.show() + + If the same filter is implemented as a single transfer function, + numerical error corrupts the frequency response: + + >>> b, a = signal.ellip(15, 0.5, 60, (0.2, 0.4), btype='bandpass', + ... output='ba') + >>> w, h = signal.freqz(b, a, worN=1500) + >>> plt.subplot(2, 1, 1) + >>> db = 20*np.log10(np.maximum(np.abs(h), 1e-5)) + >>> plt.plot(w/np.pi, db) + >>> plt.ylim(-75, 5) + >>> plt.grid(True) + >>> plt.yticks([0, -20, -40, -60]) + >>> plt.ylabel('Gain [dB]') + >>> plt.title('Frequency Response') + >>> plt.subplot(2, 1, 2) + >>> plt.plot(w/np.pi, np.angle(h)) + >>> plt.grid(True) + >>> plt.yticks([-np.pi, -0.5*np.pi, 0, 0.5*np.pi, np.pi], + ... [r'$-\pi$', r'$-\pi/2$', '0', r'$\pi/2$', r'$\pi$']) + >>> plt.ylabel('Phase [rad]') + >>> plt.xlabel('Normalized frequency (1.0 = Nyquist)') + >>> plt.show() + + """ + fs = _validate_fs(fs, allow_none=False) + + sos, n_sections = _validate_sos(sos) + if n_sections == 0: + raise ValueError('Cannot compute frequencies with no sections') + h = 1. + for row in sos: + w, rowh = freqz(row[:3], row[3:], worN=worN, whole=whole, fs=fs) + h *= rowh + return w, h + + +def sosfreqz(*args, **kwargs): + """ + Compute the frequency response of a digital filter in SOS format. + + .. warning:: This function is an alias, provided for backward + compatibility. New code should use the function + :func:`scipy.signal.freqz_sos`. + """ + return freqz_sos(*args, **kwargs) + + +def _cplxreal(z, tol=None): + """ + Split into complex and real parts, combining conjugate pairs. + + The 1-D input vector `z` is split up into its complex (`zc`) and real (`zr`) + elements. Every complex element must be part of a complex-conjugate pair, + which are combined into a single number (with positive imaginary part) in + the output. Two complex numbers are considered a conjugate pair if their + real and imaginary parts differ in magnitude by less than ``tol * abs(z)``. + + Parameters + ---------- + z : array_like + Vector of complex numbers to be sorted and split + tol : float, optional + Relative tolerance for testing realness and conjugate equality. + Default is ``100 * spacing(1)`` of `z`'s data type (i.e., 2e-14 for + float64) + + Returns + ------- + zc : ndarray + Complex elements of `z`, with each pair represented by a single value + having positive imaginary part, sorted first by real part, and then + by magnitude of imaginary part. The pairs are averaged when combined + to reduce error. + zr : ndarray + Real elements of `z` (those having imaginary part less than + `tol` times their magnitude), sorted by value. + + Raises + ------ + ValueError + If there are any complex numbers in `z` for which a conjugate + cannot be found. + + See Also + -------- + _cplxpair + + Examples + -------- + >>> from scipy.signal._filter_design import _cplxreal + >>> a = [4, 3, 1, 2-2j, 2+2j, 2-1j, 2+1j, 2-1j, 2+1j, 1+1j, 1-1j] + >>> zc, zr = _cplxreal(a) + >>> print(zc) + [ 1.+1.j 2.+1.j 2.+1.j 2.+2.j] + >>> print(zr) + [ 1. 3. 4.] + """ + + z = atleast_1d(z) + if z.size == 0: + return z, z + elif z.ndim != 1: + raise ValueError('_cplxreal only accepts 1-D input') + + if tol is None: + # Get tolerance from dtype of input + tol = 100 * np.finfo((1.0 * z).dtype).eps + + # Sort by real part, magnitude of imaginary part (speed up further sorting) + z = z[np.lexsort((abs(z.imag), z.real))] + + # Split reals from conjugate pairs + real_indices = abs(z.imag) <= tol * abs(z) + zr = z[real_indices].real + + if len(zr) == len(z): + # Input is entirely real + return array([]), zr + + # Split positive and negative halves of conjugates + z = z[~real_indices] + zp = z[z.imag > 0] + zn = z[z.imag < 0] + + if len(zp) != len(zn): + raise ValueError('Array contains complex value with no matching ' + 'conjugate.') + + # Find runs of (approximately) the same real part + same_real = np.diff(zp.real) <= tol * abs(zp[:-1]) + diffs = np.diff(concatenate(([0], same_real, [0]))) + run_starts = np.nonzero(diffs > 0)[0] + run_stops = np.nonzero(diffs < 0)[0] + + # Sort each run by their imaginary parts + for i in range(len(run_starts)): + start = run_starts[i] + stop = run_stops[i] + 1 + for chunk in (zp[start:stop], zn[start:stop]): + chunk[...] = chunk[np.lexsort([abs(chunk.imag)])] + + # Check that negatives match positives + if any(abs(zp - zn.conj()) > tol * abs(zn)): + raise ValueError('Array contains complex value with no matching ' + 'conjugate.') + + # Average out numerical inaccuracy in real vs imag parts of pairs + zc = (zp + zn.conj()) / 2 + + return zc, zr + + +def _cplxpair(z, tol=None): + """ + Sort into pairs of complex conjugates. + + Complex conjugates in `z` are sorted by increasing real part. In each + pair, the number with negative imaginary part appears first. + + If pairs have identical real parts, they are sorted by increasing + imaginary magnitude. + + Two complex numbers are considered a conjugate pair if their real and + imaginary parts differ in magnitude by less than ``tol * abs(z)``. The + pairs are forced to be exact complex conjugates by averaging the positive + and negative values. + + Purely real numbers are also sorted, but placed after the complex + conjugate pairs. A number is considered real if its imaginary part is + smaller than `tol` times the magnitude of the number. + + Parameters + ---------- + z : array_like + 1-D input array to be sorted. + tol : float, optional + Relative tolerance for testing realness and conjugate equality. + Default is ``100 * spacing(1)`` of `z`'s data type (i.e., 2e-14 for + float64) + + Returns + ------- + y : ndarray + Complex conjugate pairs followed by real numbers. + + Raises + ------ + ValueError + If there are any complex numbers in `z` for which a conjugate + cannot be found. + + See Also + -------- + _cplxreal + + Examples + -------- + >>> from scipy.signal._filter_design import _cplxpair + >>> a = [4, 3, 1, 2-2j, 2+2j, 2-1j, 2+1j, 2-1j, 2+1j, 1+1j, 1-1j] + >>> z = _cplxpair(a) + >>> print(z) + [ 1.-1.j 1.+1.j 2.-1.j 2.+1.j 2.-1.j 2.+1.j 2.-2.j 2.+2.j 1.+0.j + 3.+0.j 4.+0.j] + """ + + z = atleast_1d(z) + if z.size == 0 or np.isrealobj(z): + return np.sort(z) + + if z.ndim != 1: + raise ValueError('z must be 1-D') + + zc, zr = _cplxreal(z, tol) + + # Interleave complex values and their conjugates, with negative imaginary + # parts first in each pair + zc = np.dstack((zc.conj(), zc)).flatten() + z = np.append(zc, zr) + return z + + +def tf2zpk(b, a): + r"""Return zero, pole, gain (z, p, k) representation from a numerator, + denominator representation of a linear filter. + + Parameters + ---------- + b : array_like + Numerator polynomial coefficients. + a : array_like + Denominator polynomial coefficients. + + Returns + ------- + z : ndarray + Zeros of the transfer function. + p : ndarray + Poles of the transfer function. + k : float + System gain. + + Notes + ----- + If some values of `b` are too close to 0, they are removed. In that case, + a BadCoefficients warning is emitted. + + The `b` and `a` arrays are interpreted as coefficients for positive, + descending powers of the transfer function variable. So the inputs + :math:`b = [b_0, b_1, ..., b_M]` and :math:`a =[a_0, a_1, ..., a_N]` + can represent an analog filter of the form: + + .. math:: + + H(s) = \frac + {b_0 s^M + b_1 s^{(M-1)} + \cdots + b_M} + {a_0 s^N + a_1 s^{(N-1)} + \cdots + a_N} + + or a discrete-time filter of the form: + + .. math:: + + H(z) = \frac + {b_0 z^M + b_1 z^{(M-1)} + \cdots + b_M} + {a_0 z^N + a_1 z^{(N-1)} + \cdots + a_N} + + This "positive powers" form is found more commonly in controls + engineering. If `M` and `N` are equal (which is true for all filters + generated by the bilinear transform), then this happens to be equivalent + to the "negative powers" discrete-time form preferred in DSP: + + .. math:: + + H(z) = \frac + {b_0 + b_1 z^{-1} + \cdots + b_M z^{-M}} + {a_0 + a_1 z^{-1} + \cdots + a_N z^{-N}} + + Although this is true for common filters, remember that this is not true + in the general case. If `M` and `N` are not equal, the discrete-time + transfer function coefficients must first be converted to the "positive + powers" form before finding the poles and zeros. + + Examples + -------- + Find the zeroes, poles and gain of + a filter with the transfer function + + .. math:: + + H(s) = \frac{3s^2}{s^2 + 5s + 13} + + >>> from scipy.signal import tf2zpk + >>> tf2zpk([3, 0, 0], [1, 5, 13]) + ( array([ 0. , 0. ]), + array([ -2.5+2.59807621j , -2.5-2.59807621j]), + 3.0) + """ + b, a = normalize(b, a) + b = (b + 0.0) / a[0] + a = (a + 0.0) / a[0] + k = b[0] + b /= b[0] + z = roots(b) + p = roots(a) + return z, p, k + + +def zpk2tf(z, p, k): + r""" + Return polynomial transfer function representation from zeros and poles + + Parameters + ---------- + z : array_like + Zeros of the transfer function. + p : array_like + Poles of the transfer function. + k : float + System gain. + + Returns + ------- + b : ndarray + Numerator polynomial coefficients. + a : ndarray + Denominator polynomial coefficients. + + Examples + -------- + Find the polynomial representation of a transfer function H(s) + using its 'zpk' (Zero-Pole-Gain) representation. + + .. math:: + + H(z) = 5 \frac + { (s - 2)(s - 6) } + { (s - 1)(s - 8) } + + >>> from scipy.signal import zpk2tf + >>> z = [2, 6] + >>> p = [1, 8] + >>> k = 5 + >>> zpk2tf(z, p, k) + ( array([ 5., -40., 60.]), array([ 1., -9., 8.])) + """ + z = atleast_1d(z) + k = atleast_1d(k) + if len(z.shape) > 1: + temp = poly(z[0]) + b = np.empty((z.shape[0], z.shape[1] + 1), temp.dtype.char) + if len(k) == 1: + k = [k[0]] * z.shape[0] + for i in range(z.shape[0]): + b[i] = k[i] * poly(z[i]) + else: + b = k * poly(z) + a = atleast_1d(poly(p)) + + # Use real output if possible. Copied from np.poly, since + # we can't depend on a specific version of numpy. + if issubclass(b.dtype.type, np.complexfloating): + # if complex roots are all complex conjugates, the roots are real. + roots = np.asarray(z, complex) + pos_roots = np.compress(roots.imag > 0, roots) + neg_roots = np.conjugate(np.compress(roots.imag < 0, roots)) + if len(pos_roots) == len(neg_roots): + if np.all(np.sort_complex(neg_roots) == np.sort_complex(pos_roots)): + b = b.real.copy() + + if issubclass(a.dtype.type, np.complexfloating): + # if complex roots are all complex conjugates, the roots are real. + roots = np.asarray(p, complex) + pos_roots = np.compress(roots.imag > 0, roots) + neg_roots = np.conjugate(np.compress(roots.imag < 0, roots)) + if len(pos_roots) == len(neg_roots): + if np.all(np.sort_complex(neg_roots) == np.sort_complex(pos_roots)): + a = a.real.copy() + + return b, a + + +def tf2sos(b, a, pairing=None, *, analog=False): + r""" + Return second-order sections from transfer function representation + + Parameters + ---------- + b : array_like + Numerator polynomial coefficients. + a : array_like + Denominator polynomial coefficients. + pairing : {None, 'nearest', 'keep_odd', 'minimal'}, optional + The method to use to combine pairs of poles and zeros into sections. + See `zpk2sos` for information and restrictions on `pairing` and + `analog` arguments. + analog : bool, optional + If True, system is analog, otherwise discrete. + + .. versionadded:: 1.8.0 + + Returns + ------- + sos : ndarray + Array of second-order filter coefficients, with shape + ``(n_sections, 6)``. See `sosfilt` for the SOS filter format + specification. + + See Also + -------- + zpk2sos, sosfilt + + Notes + ----- + It is generally discouraged to convert from TF to SOS format, since doing + so usually will not improve numerical precision errors. Instead, consider + designing filters in ZPK format and converting directly to SOS. TF is + converted to SOS by first converting to ZPK format, then converting + ZPK to SOS. + + .. versionadded:: 0.16.0 + + Examples + -------- + Find the 'sos' (second-order sections) of the transfer function H(s) + using its polynomial representation. + + .. math:: + + H(s) = \frac{s^2 - 3.5s - 2}{s^4 + 3s^3 - 15s^2 - 19s + 30} + + >>> from scipy.signal import tf2sos + >>> tf2sos([1, -3.5, -2], [1, 3, -15, -19, 30], analog=True) + array([[ 0. , 0. , 1. , 1. , 2. , -15. ], + [ 1. , -3.5, -2. , 1. , 1. , -2. ]]) + """ + return zpk2sos(*tf2zpk(b, a), pairing=pairing, analog=analog) + + +def sos2tf(sos): + r""" + Return a single transfer function from a series of second-order sections + + Parameters + ---------- + sos : array_like + Array of second-order filter coefficients, must have shape + ``(n_sections, 6)``. See `sosfilt` for the SOS filter format + specification. + + Returns + ------- + b : ndarray + Numerator polynomial coefficients. + a : ndarray + Denominator polynomial coefficients. + + Notes + ----- + .. versionadded:: 0.16.0 + + Examples + -------- + Find the polynomial representation of an elliptic filter + using its 'sos' (second-order sections) format. + + >>> from scipy.signal import sos2tf + >>> from scipy import signal + >>> sos = signal.ellip(1, 0.001, 50, 0.1, output='sos') + >>> sos2tf(sos) + ( array([0.91256522, 0.91256522, 0. ]), + array([1. , 0.82513043, 0. ])) + """ + sos = np.asarray(sos) + result_type = sos.dtype + if result_type.kind in 'bui': + result_type = np.float64 + + b = np.array([1], dtype=result_type) + a = np.array([1], dtype=result_type) + n_sections = sos.shape[0] + for section in range(n_sections): + b = np.polymul(b, sos[section, :3]) + a = np.polymul(a, sos[section, 3:]) + return b, a + + +def sos2zpk(sos): + """ + Return zeros, poles, and gain of a series of second-order sections + + Parameters + ---------- + sos : array_like + Array of second-order filter coefficients, must have shape + ``(n_sections, 6)``. See `sosfilt` for the SOS filter format + specification. + + Returns + ------- + z : ndarray + Zeros of the transfer function. + p : ndarray + Poles of the transfer function. + k : float + System gain. + + Notes + ----- + The number of zeros and poles returned will be ``n_sections * 2`` + even if some of these are (effectively) zero. + + .. versionadded:: 0.16.0 + """ + sos = np.asarray(sos) + n_sections = sos.shape[0] + z = np.zeros(n_sections*2, np.complex128) + p = np.zeros(n_sections*2, np.complex128) + k = 1. + for section in range(n_sections): + zpk = tf2zpk(sos[section, :3], sos[section, 3:]) + z[2*section:2*section+len(zpk[0])] = zpk[0] + p[2*section:2*section+len(zpk[1])] = zpk[1] + k *= zpk[2] + return z, p, k + + +def _nearest_real_complex_idx(fro, to, which): + """Get the next closest real or complex element based on distance""" + assert which in ('real', 'complex', 'any') + order = np.argsort(np.abs(fro - to)) + if which == 'any': + return order[0] + else: + mask = np.isreal(fro[order]) + if which == 'complex': + mask = ~mask + return order[np.nonzero(mask)[0][0]] + + +def _single_zpksos(z, p, k): + """Create one second-order section from up to two zeros and poles""" + sos = np.zeros(6) + b, a = zpk2tf(z, p, k) + sos[3-len(b):3] = b + sos[6-len(a):6] = a + return sos + + +def zpk2sos(z, p, k, pairing=None, *, analog=False): + """Return second-order sections from zeros, poles, and gain of a system + + Parameters + ---------- + z : array_like + Zeros of the transfer function. + p : array_like + Poles of the transfer function. + k : float + System gain. + pairing : {None, 'nearest', 'keep_odd', 'minimal'}, optional + The method to use to combine pairs of poles and zeros into sections. + If analog is False and pairing is None, pairing is set to 'nearest'; + if analog is True, pairing must be 'minimal', and is set to that if + it is None. + analog : bool, optional + If True, system is analog, otherwise discrete. + + .. versionadded:: 1.8.0 + + Returns + ------- + sos : ndarray + Array of second-order filter coefficients, with shape + ``(n_sections, 6)``. See `sosfilt` for the SOS filter format + specification. + + See Also + -------- + sosfilt + + Notes + ----- + The algorithm used to convert ZPK to SOS format is designed to + minimize errors due to numerical precision issues. The pairing + algorithm attempts to minimize the peak gain of each biquadratic + section. This is done by pairing poles with the nearest zeros, starting + with the poles closest to the unit circle for discrete-time systems, and + poles closest to the imaginary axis for continuous-time systems. + + ``pairing='minimal'`` outputs may not be suitable for `sosfilt`, + and ``analog=True`` outputs will never be suitable for `sosfilt`. + + *Algorithms* + + The steps in the ``pairing='nearest'``, ``pairing='keep_odd'``, + and ``pairing='minimal'`` algorithms are mostly shared. The + ``'nearest'`` algorithm attempts to minimize the peak gain, while + ``'keep_odd'`` minimizes peak gain under the constraint that + odd-order systems should retain one section as first order. + ``'minimal'`` is similar to ``'keep_odd'``, but no additional + poles or zeros are introduced + + The algorithm steps are as follows: + + As a pre-processing step for ``pairing='nearest'``, + ``pairing='keep_odd'``, add poles or zeros to the origin as + necessary to obtain the same number of poles and zeros for + pairing. If ``pairing == 'nearest'`` and there are an odd number + of poles, add an additional pole and a zero at the origin. + + The following steps are then iterated over until no more poles or + zeros remain: + + 1. Take the (next remaining) pole (complex or real) closest to the + unit circle (or imaginary axis, for ``analog=True``) to + begin a new filter section. + + 2. If the pole is real and there are no other remaining real poles [#]_, + add the closest real zero to the section and leave it as a first + order section. Note that after this step we are guaranteed to be + left with an even number of real poles, complex poles, real zeros, + and complex zeros for subsequent pairing iterations. + + 3. Else: + + 1. If the pole is complex and the zero is the only remaining real + zero*, then pair the pole with the *next* closest zero + (guaranteed to be complex). This is necessary to ensure that + there will be a real zero remaining to eventually create a + first-order section (thus keeping the odd order). + + 2. Else pair the pole with the closest remaining zero (complex or + real). + + 3. Proceed to complete the second-order section by adding another + pole and zero to the current pole and zero in the section: + + 1. If the current pole and zero are both complex, add their + conjugates. + + 2. Else if the pole is complex and the zero is real, add the + conjugate pole and the next closest real zero. + + 3. Else if the pole is real and the zero is complex, add the + conjugate zero and the real pole closest to those zeros. + + 4. Else (we must have a real pole and real zero) add the next + real pole closest to the unit circle, and then add the real + zero closest to that pole. + + .. [#] This conditional can only be met for specific odd-order inputs + with the ``pairing = 'keep_odd'`` or ``'minimal'`` methods. + + .. versionadded:: 0.16.0 + + Examples + -------- + + Design a 6th order low-pass elliptic digital filter for a system with a + sampling rate of 8000 Hz that has a pass-band corner frequency of + 1000 Hz. The ripple in the pass-band should not exceed 0.087 dB, and + the attenuation in the stop-band should be at least 90 dB. + + In the following call to `ellip`, we could use ``output='sos'``, + but for this example, we'll use ``output='zpk'``, and then convert + to SOS format with `zpk2sos`: + + >>> from scipy import signal + >>> import numpy as np + >>> z, p, k = signal.ellip(6, 0.087, 90, 1000/(0.5*8000), output='zpk') + + Now convert to SOS format. + + >>> sos = signal.zpk2sos(z, p, k) + + The coefficients of the numerators of the sections: + + >>> sos[:, :3] + array([[0.0014152 , 0.00248677, 0.0014152 ], + [1. , 0.72976874, 1. ], + [1. , 0.17607852, 1. ]]) + + The symmetry in the coefficients occurs because all the zeros are on the + unit circle. + + The coefficients of the denominators of the sections: + + >>> sos[:, 3:] + array([[ 1. , -1.32544025, 0.46989976], + [ 1. , -1.26118294, 0.62625924], + [ 1. , -1.2570723 , 0.8619958 ]]) + + The next example shows the effect of the `pairing` option. We have a + system with three poles and three zeros, so the SOS array will have + shape (2, 6). The means there is, in effect, an extra pole and an extra + zero at the origin in the SOS representation. + + >>> z1 = np.array([-1, -0.5-0.5j, -0.5+0.5j]) + >>> p1 = np.array([0.75, 0.8+0.1j, 0.8-0.1j]) + + With ``pairing='nearest'`` (the default), we obtain + + >>> signal.zpk2sos(z1, p1, 1) + array([[ 1. , 1. , 0.5 , 1. , -0.75, 0. ], + [ 1. , 1. , 0. , 1. , -1.6 , 0.65]]) + + The first section has the zeros {-0.5-0.05j, -0.5+0.5j} and the poles + {0, 0.75}, and the second section has the zeros {-1, 0} and poles + {0.8+0.1j, 0.8-0.1j}. Note that the extra pole and zero at the origin + have been assigned to different sections. + + With ``pairing='keep_odd'``, we obtain: + + >>> signal.zpk2sos(z1, p1, 1, pairing='keep_odd') + array([[ 1. , 1. , 0. , 1. , -0.75, 0. ], + [ 1. , 1. , 0.5 , 1. , -1.6 , 0.65]]) + + The extra pole and zero at the origin are in the same section. + The first section is, in effect, a first-order section. + + With ``pairing='minimal'``, the first-order section doesn't have + the extra pole and zero at the origin: + + >>> signal.zpk2sos(z1, p1, 1, pairing='minimal') + array([[ 0. , 1. , 1. , 0. , 1. , -0.75], + [ 1. , 1. , 0.5 , 1. , -1.6 , 0.65]]) + + """ + # TODO in the near future: + # 1. Add SOS capability to `filtfilt`, `freqz`, etc. somehow (#3259). + # 2. Make `decimate` use `sosfilt` instead of `lfilter`. + # 3. Make sosfilt automatically simplify sections to first order + # when possible. Note this might make `sosfiltfilt` a bit harder (ICs). + # 4. Further optimizations of the section ordering / pole-zero pairing. + # See the wiki for other potential issues. + + if pairing is None: + pairing = 'minimal' if analog else 'nearest' + + valid_pairings = ['nearest', 'keep_odd', 'minimal'] + if pairing not in valid_pairings: + raise ValueError(f'pairing must be one of {valid_pairings}, not {pairing}') + + if analog and pairing != 'minimal': + raise ValueError('for analog zpk2sos conversion, ' + 'pairing must be "minimal"') + + if len(z) == len(p) == 0: + if not analog: + return np.array([[k, 0., 0., 1., 0., 0.]]) + else: + return np.array([[0., 0., k, 0., 0., 1.]]) + + if pairing != 'minimal': + # ensure we have the same number of poles and zeros, and make copies + p = np.concatenate((p, np.zeros(max(len(z) - len(p), 0)))) + z = np.concatenate((z, np.zeros(max(len(p) - len(z), 0)))) + n_sections = (max(len(p), len(z)) + 1) // 2 + + if len(p) % 2 == 1 and pairing == 'nearest': + p = np.concatenate((p, [0.])) + z = np.concatenate((z, [0.])) + assert len(p) == len(z) + else: + if len(p) < len(z): + raise ValueError('for analog zpk2sos conversion, ' + 'must have len(p)>=len(z)') + + n_sections = (len(p) + 1) // 2 + + # Ensure we have complex conjugate pairs + # (note that _cplxreal only gives us one element of each complex pair): + z = np.concatenate(_cplxreal(z)) + p = np.concatenate(_cplxreal(p)) + if not np.isreal(k): + raise ValueError('k must be real') + k = k.real + + if not analog: + # digital: "worst" is the closest to the unit circle + def idx_worst(p): + return np.argmin(np.abs(1 - np.abs(p))) + else: + # analog: "worst" is the closest to the imaginary axis + def idx_worst(p): + return np.argmin(np.abs(np.real(p))) + + sos = np.zeros((n_sections, 6)) + + # Construct the system, reversing order so the "worst" are last + for si in range(n_sections-1, -1, -1): + # Select the next "worst" pole + p1_idx = idx_worst(p) + p1 = p[p1_idx] + p = np.delete(p, p1_idx) + + # Pair that pole with a zero + + if np.isreal(p1) and np.isreal(p).sum() == 0: + # Special case (1): last remaining real pole + if pairing != 'minimal': + z1_idx = _nearest_real_complex_idx(z, p1, 'real') + z1 = z[z1_idx] + z = np.delete(z, z1_idx) + sos[si] = _single_zpksos([z1, 0], [p1, 0], 1) + elif len(z) > 0: + z1_idx = _nearest_real_complex_idx(z, p1, 'real') + z1 = z[z1_idx] + z = np.delete(z, z1_idx) + sos[si] = _single_zpksos([z1], [p1], 1) + else: + sos[si] = _single_zpksos([], [p1], 1) + + elif (len(p) + 1 == len(z) + and not np.isreal(p1) + and np.isreal(p).sum() == 1 + and np.isreal(z).sum() == 1): + + # Special case (2): there's one real pole and one real zero + # left, and an equal number of poles and zeros to pair up. + # We *must* pair with a complex zero + + z1_idx = _nearest_real_complex_idx(z, p1, 'complex') + z1 = z[z1_idx] + z = np.delete(z, z1_idx) + sos[si] = _single_zpksos([z1, z1.conj()], [p1, p1.conj()], 1) + + else: + if np.isreal(p1): + prealidx = np.flatnonzero(np.isreal(p)) + p2_idx = prealidx[idx_worst(p[prealidx])] + p2 = p[p2_idx] + p = np.delete(p, p2_idx) + else: + p2 = p1.conj() + + # find closest zero + if len(z) > 0: + z1_idx = _nearest_real_complex_idx(z, p1, 'any') + z1 = z[z1_idx] + z = np.delete(z, z1_idx) + + if not np.isreal(z1): + sos[si] = _single_zpksos([z1, z1.conj()], [p1, p2], 1) + else: + if len(z) > 0: + z2_idx = _nearest_real_complex_idx(z, p1, 'real') + z2 = z[z2_idx] + assert np.isreal(z2) + z = np.delete(z, z2_idx) + sos[si] = _single_zpksos([z1, z2], [p1, p2], 1) + else: + sos[si] = _single_zpksos([z1], [p1, p2], 1) + else: + # no more zeros + sos[si] = _single_zpksos([], [p1, p2], 1) + + assert len(p) == len(z) == 0 # we've consumed all poles and zeros + del p, z + + # put gain in first sos + sos[0][:3] *= k + return sos + + +def _align_nums(nums): + """Aligns the shapes of multiple numerators. + + Given an array of numerator coefficient arrays [[a_1, a_2,..., + a_n],..., [b_1, b_2,..., b_m]], this function pads shorter numerator + arrays with zero's so that all numerators have the same length. Such + alignment is necessary for functions like 'tf2ss', which needs the + alignment when dealing with SIMO transfer functions. + + Parameters + ---------- + nums: array_like + Numerator or list of numerators. Not necessarily with same length. + + Returns + ------- + nums: array + The numerator. If `nums` input was a list of numerators then a 2-D + array with padded zeros for shorter numerators is returned. Otherwise + returns ``np.asarray(nums)``. + """ + try: + # The statement can throw a ValueError if one + # of the numerators is a single digit and another + # is array-like e.g. if nums = [5, [1, 2, 3]] + nums = asarray(nums) + + if not np.issubdtype(nums.dtype, np.number): + raise ValueError("dtype of numerator is non-numeric") + + return nums + + except ValueError: + nums = [np.atleast_1d(num) for num in nums] + max_width = max(num.size for num in nums) + + # pre-allocate + aligned_nums = np.zeros((len(nums), max_width)) + + # Create numerators with padded zeros + for index, num in enumerate(nums): + aligned_nums[index, -num.size:] = num + + return aligned_nums + + +def normalize(b, a): + """Normalize numerator/denominator of a continuous-time transfer function. + + If values of `b` are too close to 0, they are removed. In that case, a + BadCoefficients warning is emitted. + + Parameters + ---------- + b: array_like + Numerator of the transfer function. Can be a 2-D array to normalize + multiple transfer functions. + a: array_like + Denominator of the transfer function. At most 1-D. + + Returns + ------- + num: array + The numerator of the normalized transfer function. At least a 1-D + array. A 2-D array if the input `num` is a 2-D array. + den: 1-D array + The denominator of the normalized transfer function. + + Notes + ----- + Coefficients for both the numerator and denominator should be specified in + descending exponent order (e.g., ``s^2 + 3s + 5`` would be represented as + ``[1, 3, 5]``). + + Examples + -------- + >>> from scipy.signal import normalize + + Normalize the coefficients of the transfer function + ``(3*s^2 - 2*s + 5) / (2*s^2 + 3*s + 1)``: + + >>> b = [3, -2, 5] + >>> a = [2, 3, 1] + >>> normalize(b, a) + (array([ 1.5, -1. , 2.5]), array([1. , 1.5, 0.5])) + + A warning is generated if, for example, the first coefficient of + `b` is 0. In the following example, the result is as expected: + + >>> import warnings + >>> with warnings.catch_warnings(record=True) as w: + ... num, den = normalize([0, 3, 6], [2, -5, 4]) + + >>> num + array([1.5, 3. ]) + >>> den + array([ 1. , -2.5, 2. ]) + + >>> print(w[0].message) + Badly conditioned filter coefficients (numerator): the results may be meaningless + + """ + num, den = b, a + + den = np.atleast_1d(den) + num = np.atleast_2d(_align_nums(num)) + + if den.ndim != 1: + raise ValueError("Denominator polynomial must be rank-1 array.") + if num.ndim > 2: + raise ValueError("Numerator polynomial must be rank-1 or" + " rank-2 array.") + if np.all(den == 0): + raise ValueError("Denominator must have at least on nonzero element.") + + # Trim leading zeros in denominator, leave at least one. + den = np.trim_zeros(den, 'f') + + # Normalize transfer function + num, den = num / den[0], den / den[0] + + # Count numerator columns that are all zero + leading_zeros = 0 + for col in num.T: + if np.allclose(col, 0, atol=1e-14): + leading_zeros += 1 + else: + break + + # Trim leading zeros of numerator + if leading_zeros > 0: + warnings.warn("Badly conditioned filter coefficients (numerator): the " + "results may be meaningless", + BadCoefficients, stacklevel=2) + # Make sure at least one column remains + if leading_zeros == num.shape[1]: + leading_zeros -= 1 + num = num[:, leading_zeros:] + + # Squeeze first dimension if singular + if num.shape[0] == 1: + num = num[0, :] + + return num, den + + +def lp2lp(b, a, wo=1.0): + r""" + Transform a lowpass filter prototype to a different frequency. + + Return an analog low-pass filter with cutoff frequency `wo` + from an analog low-pass filter prototype with unity cutoff frequency, in + transfer function ('ba') representation. + + Parameters + ---------- + b : array_like + Numerator polynomial coefficients. + a : array_like + Denominator polynomial coefficients. + wo : float + Desired cutoff, as angular frequency (e.g. rad/s). + Defaults to no change. + + Returns + ------- + b : array_like + Numerator polynomial coefficients of the transformed low-pass filter. + a : array_like + Denominator polynomial coefficients of the transformed low-pass filter. + + See Also + -------- + lp2hp, lp2bp, lp2bs, bilinear + lp2lp_zpk + + Notes + ----- + This is derived from the s-plane substitution + + .. math:: s \rightarrow \frac{s}{\omega_0} + + Examples + -------- + + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + + >>> lp = signal.lti([1.0], [1.0, 1.0]) + >>> lp2 = signal.lti(*signal.lp2lp(lp.num, lp.den, 2)) + >>> w, mag_lp, p_lp = lp.bode() + >>> w, mag_lp2, p_lp2 = lp2.bode(w) + + >>> plt.plot(w, mag_lp, label='Lowpass') + >>> plt.plot(w, mag_lp2, label='Transformed Lowpass') + >>> plt.semilogx() + >>> plt.grid(True) + >>> plt.xlabel('Frequency [rad/s]') + >>> plt.ylabel('Amplitude [dB]') + >>> plt.legend() + + """ + a, b = map(atleast_1d, (a, b)) + try: + wo = float(wo) + except TypeError: + wo = float(wo[0]) + d = len(a) + n = len(b) + M = max((d, n)) + pwo = pow(wo, np.arange(M - 1, -1, -1)) + start1 = max((n - d, 0)) + start2 = max((d - n, 0)) + b = b * pwo[start1] / pwo[start2:] + a = a * pwo[start1] / pwo[start1:] + return normalize(b, a) + + +def lp2hp(b, a, wo=1.0): + r""" + Transform a lowpass filter prototype to a highpass filter. + + Return an analog high-pass filter with cutoff frequency `wo` + from an analog low-pass filter prototype with unity cutoff frequency, in + transfer function ('ba') representation. + + Parameters + ---------- + b : array_like + Numerator polynomial coefficients. + a : array_like + Denominator polynomial coefficients. + wo : float + Desired cutoff, as angular frequency (e.g., rad/s). + Defaults to no change. + + Returns + ------- + b : array_like + Numerator polynomial coefficients of the transformed high-pass filter. + a : array_like + Denominator polynomial coefficients of the transformed high-pass filter. + + See Also + -------- + lp2lp, lp2bp, lp2bs, bilinear + lp2hp_zpk + + Notes + ----- + This is derived from the s-plane substitution + + .. math:: s \rightarrow \frac{\omega_0}{s} + + This maintains symmetry of the lowpass and highpass responses on a + logarithmic scale. + + Examples + -------- + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + + >>> lp = signal.lti([1.0], [1.0, 1.0]) + >>> hp = signal.lti(*signal.lp2hp(lp.num, lp.den)) + >>> w, mag_lp, p_lp = lp.bode() + >>> w, mag_hp, p_hp = hp.bode(w) + + >>> plt.plot(w, mag_lp, label='Lowpass') + >>> plt.plot(w, mag_hp, label='Highpass') + >>> plt.semilogx() + >>> plt.grid(True) + >>> plt.xlabel('Frequency [rad/s]') + >>> plt.ylabel('Amplitude [dB]') + >>> plt.legend() + + """ + a, b = map(atleast_1d, (a, b)) + try: + wo = float(wo) + except TypeError: + wo = float(wo[0]) + d = len(a) + n = len(b) + if wo != 1: + pwo = pow(wo, np.arange(max((d, n)))) + else: + pwo = np.ones(max((d, n)), b.dtype.char) + if d >= n: + outa = a[::-1] * pwo + outb = resize(b, (d,)) + outb[n:] = 0.0 + outb[:n] = b[::-1] * pwo[:n] + else: + outb = b[::-1] * pwo + outa = resize(a, (n,)) + outa[d:] = 0.0 + outa[:d] = a[::-1] * pwo[:d] + + return normalize(outb, outa) + + +def lp2bp(b, a, wo=1.0, bw=1.0): + r""" + Transform a lowpass filter prototype to a bandpass filter. + + Return an analog band-pass filter with center frequency `wo` and + bandwidth `bw` from an analog low-pass filter prototype with unity + cutoff frequency, in transfer function ('ba') representation. + + Parameters + ---------- + b : array_like + Numerator polynomial coefficients. + a : array_like + Denominator polynomial coefficients. + wo : float + Desired passband center, as angular frequency (e.g., rad/s). + Defaults to no change. + bw : float + Desired passband width, as angular frequency (e.g., rad/s). + Defaults to 1. + + Returns + ------- + b : array_like + Numerator polynomial coefficients of the transformed band-pass filter. + a : array_like + Denominator polynomial coefficients of the transformed band-pass filter. + + See Also + -------- + lp2lp, lp2hp, lp2bs, bilinear + lp2bp_zpk + + Notes + ----- + This is derived from the s-plane substitution + + .. math:: s \rightarrow \frac{s^2 + {\omega_0}^2}{s \cdot \mathrm{BW}} + + This is the "wideband" transformation, producing a passband with + geometric (log frequency) symmetry about `wo`. + + Examples + -------- + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + + >>> lp = signal.lti([1.0], [1.0, 1.0]) + >>> bp = signal.lti(*signal.lp2bp(lp.num, lp.den)) + >>> w, mag_lp, p_lp = lp.bode() + >>> w, mag_bp, p_bp = bp.bode(w) + + >>> plt.plot(w, mag_lp, label='Lowpass') + >>> plt.plot(w, mag_bp, label='Bandpass') + >>> plt.semilogx() + >>> plt.grid(True) + >>> plt.xlabel('Frequency [rad/s]') + >>> plt.ylabel('Amplitude [dB]') + >>> plt.legend() + """ + + a, b = map(atleast_1d, (a, b)) + D = len(a) - 1 + N = len(b) - 1 + artype = mintypecode((a, b)) + ma = max([N, D]) + Np = N + ma + Dp = D + ma + bprime = np.empty(Np + 1, artype) + aprime = np.empty(Dp + 1, artype) + wosq = wo * wo + for j in range(Np + 1): + val = 0.0 + for i in range(0, N + 1): + for k in range(0, i + 1): + if ma - i + 2 * k == j: + val += comb(i, k) * b[N - i] * (wosq) ** (i - k) / bw ** i + bprime[Np - j] = val + for j in range(Dp + 1): + val = 0.0 + for i in range(0, D + 1): + for k in range(0, i + 1): + if ma - i + 2 * k == j: + val += comb(i, k) * a[D - i] * (wosq) ** (i - k) / bw ** i + aprime[Dp - j] = val + + return normalize(bprime, aprime) + + +def lp2bs(b, a, wo=1.0, bw=1.0): + r""" + Transform a lowpass filter prototype to a bandstop filter. + + Return an analog band-stop filter with center frequency `wo` and + bandwidth `bw` from an analog low-pass filter prototype with unity + cutoff frequency, in transfer function ('ba') representation. + + Parameters + ---------- + b : array_like + Numerator polynomial coefficients. + a : array_like + Denominator polynomial coefficients. + wo : float + Desired stopband center, as angular frequency (e.g., rad/s). + Defaults to no change. + bw : float + Desired stopband width, as angular frequency (e.g., rad/s). + Defaults to 1. + + Returns + ------- + b : array_like + Numerator polynomial coefficients of the transformed band-stop filter. + a : array_like + Denominator polynomial coefficients of the transformed band-stop filter. + + See Also + -------- + lp2lp, lp2hp, lp2bp, bilinear + lp2bs_zpk + + Notes + ----- + This is derived from the s-plane substitution + + .. math:: s \rightarrow \frac{s \cdot \mathrm{BW}}{s^2 + {\omega_0}^2} + + This is the "wideband" transformation, producing a stopband with + geometric (log frequency) symmetry about `wo`. + + Examples + -------- + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + + >>> lp = signal.lti([1.0], [1.0, 1.5]) + >>> bs = signal.lti(*signal.lp2bs(lp.num, lp.den)) + >>> w, mag_lp, p_lp = lp.bode() + >>> w, mag_bs, p_bs = bs.bode(w) + >>> plt.plot(w, mag_lp, label='Lowpass') + >>> plt.plot(w, mag_bs, label='Bandstop') + >>> plt.semilogx() + >>> plt.grid(True) + >>> plt.xlabel('Frequency [rad/s]') + >>> plt.ylabel('Amplitude [dB]') + >>> plt.legend() + """ + a, b = map(atleast_1d, (a, b)) + D = len(a) - 1 + N = len(b) - 1 + artype = mintypecode((a, b)) + M = max([N, D]) + Np = M + M + Dp = M + M + bprime = np.empty(Np + 1, artype) + aprime = np.empty(Dp + 1, artype) + wosq = wo * wo + for j in range(Np + 1): + val = 0.0 + for i in range(0, N + 1): + for k in range(0, M - i + 1): + if i + 2 * k == j: + val += (comb(M - i, k) * b[N - i] * + (wosq) ** (M - i - k) * bw ** i) + bprime[Np - j] = val + for j in range(Dp + 1): + val = 0.0 + for i in range(0, D + 1): + for k in range(0, M - i + 1): + if i + 2 * k == j: + val += (comb(M - i, k) * a[D - i] * + (wosq) ** (M - i - k) * bw ** i) + aprime[Dp - j] = val + + return normalize(bprime, aprime) + + +def bilinear(b, a, fs=1.0): + r""" + Return a digital IIR filter from an analog one using a bilinear transform. + + Transform a set of poles and zeros from the analog s-plane to the digital + z-plane using Tustin's method, which substitutes ``2*fs*(z-1) / (z+1)`` for + ``s``, maintaining the shape of the frequency response. + + Parameters + ---------- + b : array_like + Numerator of the analog filter transfer function. + a : array_like + Denominator of the analog filter transfer function. + fs : float + Sample rate, as ordinary frequency (e.g., hertz). No prewarping is + done in this function. + + Returns + ------- + b : ndarray + Numerator of the transformed digital filter transfer function. + a : ndarray + Denominator of the transformed digital filter transfer function. + + See Also + -------- + lp2lp, lp2hp, lp2bp, lp2bs + bilinear_zpk + + Examples + -------- + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> import numpy as np + + >>> fs = 100 + >>> bf = 2 * np.pi * np.array([7, 13]) + >>> filts = signal.lti(*signal.butter(4, bf, btype='bandpass', + ... analog=True)) + >>> filtz = signal.lti(*signal.bilinear(filts.num, filts.den, fs)) + >>> wz, hz = signal.freqz(filtz.num, filtz.den) + >>> ws, hs = signal.freqs(filts.num, filts.den, worN=fs*wz) + + >>> plt.semilogx(wz*fs/(2*np.pi), 20*np.log10(np.abs(hz).clip(1e-15)), + ... label=r'$|H_z(e^{j \omega})|$') + >>> plt.semilogx(wz*fs/(2*np.pi), 20*np.log10(np.abs(hs).clip(1e-15)), + ... label=r'$|H(j \omega)|$') + >>> plt.legend() + >>> plt.xlabel('Frequency [Hz]') + >>> plt.ylabel('Amplitude [dB]') + >>> plt.grid(True) + """ + fs = _validate_fs(fs, allow_none=False) + a, b = map(atleast_1d, (a, b)) + D = len(a) - 1 + N = len(b) - 1 + artype = float + M = max([N, D]) + Np = M + Dp = M + bprime = np.empty(Np + 1, artype) + aprime = np.empty(Dp + 1, artype) + for j in range(Np + 1): + val = 0.0 + for i in range(N + 1): + for k in range(i + 1): + for l in range(M - i + 1): + if k + l == j: + val += (comb(i, k) * comb(M - i, l) * b[N - i] * + pow(2 * fs, i) * (-1) ** k) + bprime[j] = real(val) + for j in range(Dp + 1): + val = 0.0 + for i in range(D + 1): + for k in range(i + 1): + for l in range(M - i + 1): + if k + l == j: + val += (comb(i, k) * comb(M - i, l) * a[D - i] * + pow(2 * fs, i) * (-1) ** k) + aprime[j] = real(val) + + return normalize(bprime, aprime) + + +def _validate_gpass_gstop(gpass, gstop): + + if gpass <= 0.0: + raise ValueError("gpass should be larger than 0.0") + elif gstop <= 0.0: + raise ValueError("gstop should be larger than 0.0") + elif gpass > gstop: + raise ValueError("gpass should be smaller than gstop") + + +def iirdesign(wp, ws, gpass, gstop, analog=False, ftype='ellip', output='ba', + fs=None): + """Complete IIR digital and analog filter design. + + Given passband and stopband frequencies and gains, construct an analog or + digital IIR filter of minimum order for a given basic type. Return the + output in numerator, denominator ('ba'), pole-zero ('zpk') or second order + sections ('sos') form. + + Parameters + ---------- + wp, ws : float or array like, shape (2,) + Passband and stopband edge frequencies. Possible values are scalars + (for lowpass and highpass filters) or ranges (for bandpass and bandstop + filters). + For digital filters, these are in the same units as `fs`. By default, + `fs` is 2 half-cycles/sample, so these are normalized from 0 to 1, + where 1 is the Nyquist frequency. For example: + + - Lowpass: wp = 0.2, ws = 0.3 + - Highpass: wp = 0.3, ws = 0.2 + - Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6] + - Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5] + + For analog filters, `wp` and `ws` are angular frequencies (e.g., rad/s). + Note, that for bandpass and bandstop filters passband must lie strictly + inside stopband or vice versa. Also note that the cutoff at the band edges + for IIR filters is defined as half-power, so -3dB, not half-amplitude (-6dB) + like for `scipy.signal.fiwin`. + gpass : float + The maximum loss in the passband (dB). + gstop : float + The minimum attenuation in the stopband (dB). + analog : bool, optional + When True, return an analog filter, otherwise a digital filter is + returned. + ftype : str, optional + The type of IIR filter to design: + + - Butterworth : 'butter' + - Chebyshev I : 'cheby1' + - Chebyshev II : 'cheby2' + - Cauer/elliptic: 'ellip' + + output : {'ba', 'zpk', 'sos'}, optional + Filter form of the output: + + - second-order sections (recommended): 'sos' + - numerator/denominator (default) : 'ba' + - pole-zero : 'zpk' + + In general the second-order sections ('sos') form is + recommended because inferring the coefficients for the + numerator/denominator form ('ba') suffers from numerical + instabilities. For reasons of backward compatibility the default + form is the numerator/denominator form ('ba'), where the 'b' + and the 'a' in 'ba' refer to the commonly used names of the + coefficients used. + + Note: Using the second-order sections form ('sos') is sometimes + associated with additional computational costs: for + data-intense use cases it is therefore recommended to also + investigate the numerator/denominator form ('ba'). + + fs : float, optional + The sampling frequency of the digital system. + + .. versionadded:: 1.2.0 + + Returns + ------- + b, a : ndarray, ndarray + Numerator (`b`) and denominator (`a`) polynomials of the IIR filter. + Only returned if ``output='ba'``. + z, p, k : ndarray, ndarray, float + Zeros, poles, and system gain of the IIR filter transfer + function. Only returned if ``output='zpk'``. + sos : ndarray + Second-order sections representation of the IIR filter. + Only returned if ``output='sos'``. + + See Also + -------- + butter : Filter design using order and critical points + cheby1, cheby2, ellip, bessel + buttord : Find order and critical points from passband and stopband spec + cheb1ord, cheb2ord, ellipord + iirfilter : General filter design using order and critical frequencies + + Notes + ----- + The ``'sos'`` output parameter was added in 0.16.0. + + Examples + -------- + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> import matplotlib.ticker + + >>> wp = 0.2 + >>> ws = 0.3 + >>> gpass = 1 + >>> gstop = 40 + + >>> system = signal.iirdesign(wp, ws, gpass, gstop) + >>> w, h = signal.freqz(*system) + + >>> fig, ax1 = plt.subplots() + >>> ax1.set_title('Digital filter frequency response') + >>> ax1.plot(w, 20 * np.log10(abs(h)), 'b') + >>> ax1.set_ylabel('Amplitude [dB]', color='b') + >>> ax1.set_xlabel('Frequency [rad/sample]') + >>> ax1.grid(True) + >>> ax1.set_ylim([-120, 20]) + >>> ax2 = ax1.twinx() + >>> phase = np.unwrap(np.angle(h)) + >>> ax2.plot(w, phase, 'g') + >>> ax2.set_ylabel('Phase [rad]', color='g') + >>> ax2.grid(True) + >>> ax2.axis('tight') + >>> ax2.set_ylim([-6, 1]) + >>> nticks = 8 + >>> ax1.yaxis.set_major_locator(matplotlib.ticker.LinearLocator(nticks)) + >>> ax2.yaxis.set_major_locator(matplotlib.ticker.LinearLocator(nticks)) + + """ + try: + ordfunc = filter_dict[ftype][1] + except KeyError as e: + raise ValueError(f"Invalid IIR filter type: {ftype}") from e + except IndexError as e: + raise ValueError(f"{ftype} does not have order selection. " + "Use iirfilter function.") from e + + _validate_gpass_gstop(gpass, gstop) + + wp = atleast_1d(wp) + ws = atleast_1d(ws) + + fs = _validate_fs(fs, allow_none=True) + + if wp.shape[0] != ws.shape[0] or wp.shape not in [(1,), (2,)]: + raise ValueError("wp and ws must have one or two elements each, and " + f"the same shape, got {wp.shape} and {ws.shape}") + + if any(wp <= 0) or any(ws <= 0): + raise ValueError("Values for wp, ws must be greater than 0") + + if not analog: + if fs is None: + if any(wp >= 1) or any(ws >= 1): + raise ValueError("Values for wp, ws must be less than 1") + elif any(wp >= fs/2) or any(ws >= fs/2): + raise ValueError("Values for wp, ws must be less than fs/2 " + f"(fs={fs} -> fs/2={fs/2})") + + if wp.shape[0] == 2: + if not ((ws[0] < wp[0] and wp[1] < ws[1]) or + (wp[0] < ws[0] and ws[1] < wp[1])): + raise ValueError("Passband must lie strictly inside stopband " + "or vice versa") + + band_type = 2 * (len(wp) - 1) + band_type += 1 + if wp[0] >= ws[0]: + band_type += 1 + + btype = {1: 'lowpass', 2: 'highpass', + 3: 'bandstop', 4: 'bandpass'}[band_type] + + N, Wn = ordfunc(wp, ws, gpass, gstop, analog=analog, fs=fs) + return iirfilter(N, Wn, rp=gpass, rs=gstop, analog=analog, btype=btype, + ftype=ftype, output=output, fs=fs) + + +def iirfilter(N, Wn, rp=None, rs=None, btype='band', analog=False, + ftype='butter', output='ba', fs=None): + """ + IIR digital and analog filter design given order and critical points. + + Design an Nth-order digital or analog filter and return the filter + coefficients. + + Parameters + ---------- + N : int + The order of the filter. + Wn : array_like + A scalar or length-2 sequence giving the critical frequencies. + + For digital filters, `Wn` are in the same units as `fs`. By default, + `fs` is 2 half-cycles/sample, so these are normalized from 0 to 1, + where 1 is the Nyquist frequency. (`Wn` is thus in + half-cycles / sample.) + + For analog filters, `Wn` is an angular frequency (e.g., rad/s). + + When Wn is a length-2 sequence, ``Wn[0]`` must be less than ``Wn[1]``. + rp : float, optional + For Chebyshev and elliptic filters, provides the maximum ripple + in the passband. (dB) + rs : float, optional + For Chebyshev and elliptic filters, provides the minimum attenuation + in the stop band. (dB) + btype : {'bandpass', 'lowpass', 'highpass', 'bandstop'}, optional + The type of filter. Default is 'bandpass'. + analog : bool, optional + When True, return an analog filter, otherwise a digital filter is + returned. + ftype : str, optional + The type of IIR filter to design: + + - Butterworth : 'butter' + - Chebyshev I : 'cheby1' + - Chebyshev II : 'cheby2' + - Cauer/elliptic: 'ellip' + - Bessel/Thomson: 'bessel' + + output : {'ba', 'zpk', 'sos'}, optional + Filter form of the output: + + - second-order sections (recommended): 'sos' + - numerator/denominator (default) : 'ba' + - pole-zero : 'zpk' + + In general the second-order sections ('sos') form is + recommended because inferring the coefficients for the + numerator/denominator form ('ba') suffers from numerical + instabilities. For reasons of backward compatibility the default + form is the numerator/denominator form ('ba'), where the 'b' + and the 'a' in 'ba' refer to the commonly used names of the + coefficients used. + + Note: Using the second-order sections form ('sos') is sometimes + associated with additional computational costs: for + data-intense use cases it is therefore recommended to also + investigate the numerator/denominator form ('ba'). + + fs : float, optional + The sampling frequency of the digital system. + + .. versionadded:: 1.2.0 + + Returns + ------- + b, a : ndarray, ndarray + Numerator (`b`) and denominator (`a`) polynomials of the IIR filter. + Only returned if ``output='ba'``. + z, p, k : ndarray, ndarray, float + Zeros, poles, and system gain of the IIR filter transfer + function. Only returned if ``output='zpk'``. + sos : ndarray + Second-order sections representation of the IIR filter. + Only returned if ``output='sos'``. + + See Also + -------- + butter : Filter design using order and critical points + cheby1, cheby2, ellip, bessel + buttord : Find order and critical points from passband and stopband spec + cheb1ord, cheb2ord, ellipord + iirdesign : General filter design using passband and stopband spec + + Notes + ----- + The ``'sos'`` output parameter was added in 0.16.0. + + Examples + -------- + Generate a 17th-order Chebyshev II analog bandpass filter from 50 Hz to + 200 Hz and plot the frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + + >>> b, a = signal.iirfilter(17, [2*np.pi*50, 2*np.pi*200], rs=60, + ... btype='band', analog=True, ftype='cheby2') + >>> w, h = signal.freqs(b, a, 1000) + >>> fig = plt.figure() + >>> ax = fig.add_subplot(1, 1, 1) + >>> ax.semilogx(w / (2*np.pi), 20 * np.log10(np.maximum(abs(h), 1e-5))) + >>> ax.set_title('Chebyshev Type II bandpass frequency response') + >>> ax.set_xlabel('Frequency [Hz]') + >>> ax.set_ylabel('Amplitude [dB]') + >>> ax.axis((10, 1000, -100, 10)) + >>> ax.grid(which='both', axis='both') + >>> plt.show() + + Create a digital filter with the same properties, in a system with + sampling rate of 2000 Hz, and plot the frequency response. (Second-order + sections implementation is required to ensure stability of a filter of + this order): + + >>> sos = signal.iirfilter(17, [50, 200], rs=60, btype='band', + ... analog=False, ftype='cheby2', fs=2000, + ... output='sos') + >>> w, h = signal.freqz_sos(sos, 2000, fs=2000) + >>> fig = plt.figure() + >>> ax = fig.add_subplot(1, 1, 1) + >>> ax.semilogx(w, 20 * np.log10(np.maximum(abs(h), 1e-5))) + >>> ax.set_title('Chebyshev Type II bandpass frequency response') + >>> ax.set_xlabel('Frequency [Hz]') + >>> ax.set_ylabel('Amplitude [dB]') + >>> ax.axis((10, 1000, -100, 10)) + >>> ax.grid(which='both', axis='both') + >>> plt.show() + + """ + fs = _validate_fs(fs, allow_none=True) + ftype, btype, output = (x.lower() for x in (ftype, btype, output)) + Wn = asarray(Wn) + if fs is not None: + if analog: + raise ValueError("fs cannot be specified for an analog filter") + Wn = Wn / (fs/2) + + if np.any(Wn <= 0): + raise ValueError("filter critical frequencies must be greater than 0") + + if Wn.size > 1 and not Wn[0] < Wn[1]: + raise ValueError("Wn[0] must be less than Wn[1]") + + try: + btype = band_dict[btype] + except KeyError as e: + raise ValueError(f"'{btype}' is an invalid bandtype for filter.") from e + + try: + typefunc = filter_dict[ftype][0] + except KeyError as e: + raise ValueError(f"'{ftype}' is not a valid basic IIR filter.") from e + + if output not in ['ba', 'zpk', 'sos']: + raise ValueError(f"'{output}' is not a valid output form.") + + if rp is not None and rp < 0: + raise ValueError("passband ripple (rp) must be positive") + + if rs is not None and rs < 0: + raise ValueError("stopband attenuation (rs) must be positive") + + # Get analog lowpass prototype + if typefunc == buttap: + z, p, k = typefunc(N) + elif typefunc == besselap: + z, p, k = typefunc(N, norm=bessel_norms[ftype]) + elif typefunc == cheb1ap: + if rp is None: + raise ValueError("passband ripple (rp) must be provided to " + "design a Chebyshev I filter.") + z, p, k = typefunc(N, rp) + elif typefunc == cheb2ap: + if rs is None: + raise ValueError("stopband attenuation (rs) must be provided to " + "design an Chebyshev II filter.") + z, p, k = typefunc(N, rs) + elif typefunc == ellipap: + if rs is None or rp is None: + raise ValueError("Both rp and rs must be provided to design an " + "elliptic filter.") + z, p, k = typefunc(N, rp, rs) + else: + raise NotImplementedError(f"'{ftype}' not implemented in iirfilter.") + + # Pre-warp frequencies for digital filter design + if not analog: + if np.any(Wn <= 0) or np.any(Wn >= 1): + if fs is not None: + raise ValueError("Digital filter critical frequencies must " + f"be 0 < Wn < fs/2 (fs={fs} -> fs/2={fs/2})") + raise ValueError("Digital filter critical frequencies " + "must be 0 < Wn < 1") + fs = 2.0 + warped = 2 * fs * tan(pi * Wn / fs) + else: + warped = Wn + + # transform to lowpass, bandpass, highpass, or bandstop + if btype in ('lowpass', 'highpass'): + if np.size(Wn) != 1: + raise ValueError('Must specify a single critical frequency Wn ' + 'for lowpass or highpass filter') + + if btype == 'lowpass': + z, p, k = lp2lp_zpk(z, p, k, wo=warped) + elif btype == 'highpass': + z, p, k = lp2hp_zpk(z, p, k, wo=warped) + elif btype in ('bandpass', 'bandstop'): + try: + bw = warped[1] - warped[0] + wo = sqrt(warped[0] * warped[1]) + except IndexError as e: + raise ValueError('Wn must specify start and stop frequencies for ' + 'bandpass or bandstop filter') from e + + if btype == 'bandpass': + z, p, k = lp2bp_zpk(z, p, k, wo=wo, bw=bw) + elif btype == 'bandstop': + z, p, k = lp2bs_zpk(z, p, k, wo=wo, bw=bw) + else: + raise NotImplementedError(f"'{btype}' not implemented in iirfilter.") + + # Find discrete equivalent if necessary + if not analog: + z, p, k = bilinear_zpk(z, p, k, fs=fs) + + # Transform to proper out type (pole-zero, state-space, numer-denom) + if output == 'zpk': + return z, p, k + elif output == 'ba': + return zpk2tf(z, p, k) + elif output == 'sos': + return zpk2sos(z, p, k, analog=analog) + + +def _relative_degree(z, p): + """ + Return relative degree of transfer function from zeros and poles + """ + degree = len(p) - len(z) + if degree < 0: + raise ValueError("Improper transfer function. " + "Must have at least as many poles as zeros.") + else: + return degree + + +def bilinear_zpk(z, p, k, fs): + r""" + Return a digital IIR filter from an analog one using a bilinear transform. + + Transform a set of poles and zeros from the analog s-plane to the digital + z-plane using Tustin's method, which substitutes ``2*fs*(z-1) / (z+1)`` for + ``s``, maintaining the shape of the frequency response. + + Parameters + ---------- + z : array_like + Zeros of the analog filter transfer function. + p : array_like + Poles of the analog filter transfer function. + k : float + System gain of the analog filter transfer function. + fs : float + Sample rate, as ordinary frequency (e.g., hertz). No prewarping is + done in this function. + + Returns + ------- + z : ndarray + Zeros of the transformed digital filter transfer function. + p : ndarray + Poles of the transformed digital filter transfer function. + k : float + System gain of the transformed digital filter. + + See Also + -------- + lp2lp_zpk, lp2hp_zpk, lp2bp_zpk, lp2bs_zpk + bilinear + + Notes + ----- + .. versionadded:: 1.1.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + + >>> fs = 100 + >>> bf = 2 * np.pi * np.array([7, 13]) + >>> filts = signal.lti(*signal.butter(4, bf, btype='bandpass', analog=True, + ... output='zpk')) + >>> filtz = signal.lti(*signal.bilinear_zpk(filts.zeros, filts.poles, + ... filts.gain, fs)) + >>> wz, hz = signal.freqz_zpk(filtz.zeros, filtz.poles, filtz.gain) + >>> ws, hs = signal.freqs_zpk(filts.zeros, filts.poles, filts.gain, + ... worN=fs*wz) + >>> plt.semilogx(wz*fs/(2*np.pi), 20*np.log10(np.abs(hz).clip(1e-15)), + ... label=r'$|H_z(e^{j \omega})|$') + >>> plt.semilogx(wz*fs/(2*np.pi), 20*np.log10(np.abs(hs).clip(1e-15)), + ... label=r'$|H(j \omega)|$') + >>> plt.legend() + >>> plt.xlabel('Frequency [Hz]') + >>> plt.ylabel('Amplitude [dB]') + >>> plt.grid(True) + """ + z = atleast_1d(z) + p = atleast_1d(p) + + fs = _validate_fs(fs, allow_none=False) + + degree = _relative_degree(z, p) + + fs2 = 2.0*fs + + # Bilinear transform the poles and zeros + z_z = (fs2 + z) / (fs2 - z) + p_z = (fs2 + p) / (fs2 - p) + + # Any zeros that were at infinity get moved to the Nyquist frequency + z_z = append(z_z, -ones(degree)) + + # Compensate for gain change + k_z = k * real(prod(fs2 - z) / prod(fs2 - p)) + + return z_z, p_z, k_z + + +def lp2lp_zpk(z, p, k, wo=1.0): + r""" + Transform a lowpass filter prototype to a different frequency. + + Return an analog low-pass filter with cutoff frequency `wo` + from an analog low-pass filter prototype with unity cutoff frequency, + using zeros, poles, and gain ('zpk') representation. + + Parameters + ---------- + z : array_like + Zeros of the analog filter transfer function. + p : array_like + Poles of the analog filter transfer function. + k : float + System gain of the analog filter transfer function. + wo : float + Desired cutoff, as angular frequency (e.g., rad/s). + Defaults to no change. + + Returns + ------- + z : ndarray + Zeros of the transformed low-pass filter transfer function. + p : ndarray + Poles of the transformed low-pass filter transfer function. + k : float + System gain of the transformed low-pass filter. + + See Also + -------- + lp2hp_zpk, lp2bp_zpk, lp2bs_zpk, bilinear + lp2lp + + Notes + ----- + This is derived from the s-plane substitution + + .. math:: s \rightarrow \frac{s}{\omega_0} + + .. versionadded:: 1.1.0 + + Examples + -------- + Use the 'zpk' (Zero-Pole-Gain) representation of a lowpass filter to + transform it to a new 'zpk' representation associated with a cutoff frequency wo. + + >>> from scipy.signal import lp2lp_zpk + >>> z = [7, 2] + >>> p = [5, 13] + >>> k = 0.8 + >>> wo = 0.4 + >>> lp2lp_zpk(z, p, k, wo) + ( array([2.8, 0.8]), array([2. , 5.2]), 0.8) + """ + z = atleast_1d(z) + p = atleast_1d(p) + wo = float(wo) # Avoid int wraparound + + degree = _relative_degree(z, p) + + # Scale all points radially from origin to shift cutoff frequency + z_lp = wo * z + p_lp = wo * p + + # Each shifted pole decreases gain by wo, each shifted zero increases it. + # Cancel out the net change to keep overall gain the same + k_lp = k * wo**degree + + return z_lp, p_lp, k_lp + + +def lp2hp_zpk(z, p, k, wo=1.0): + r""" + Transform a lowpass filter prototype to a highpass filter. + + Return an analog high-pass filter with cutoff frequency `wo` + from an analog low-pass filter prototype with unity cutoff frequency, + using zeros, poles, and gain ('zpk') representation. + + Parameters + ---------- + z : array_like + Zeros of the analog filter transfer function. + p : array_like + Poles of the analog filter transfer function. + k : float + System gain of the analog filter transfer function. + wo : float + Desired cutoff, as angular frequency (e.g., rad/s). + Defaults to no change. + + Returns + ------- + z : ndarray + Zeros of the transformed high-pass filter transfer function. + p : ndarray + Poles of the transformed high-pass filter transfer function. + k : float + System gain of the transformed high-pass filter. + + See Also + -------- + lp2lp_zpk, lp2bp_zpk, lp2bs_zpk, bilinear + lp2hp + + Notes + ----- + This is derived from the s-plane substitution + + .. math:: s \rightarrow \frac{\omega_0}{s} + + This maintains symmetry of the lowpass and highpass responses on a + logarithmic scale. + + .. versionadded:: 1.1.0 + + Examples + -------- + Use the 'zpk' (Zero-Pole-Gain) representation of a lowpass filter to + transform it to a highpass filter with a cutoff frequency wo. + + >>> from scipy.signal import lp2hp_zpk + >>> z = [ -2 + 3j , -0.5 - 0.8j ] + >>> p = [ -1 , -4 ] + >>> k = 10 + >>> wo = 0.6 + >>> lp2hp_zpk(z, p, k, wo) + ( array([-0.09230769-0.13846154j, -0.33707865+0.53932584j]), + array([-0.6 , -0.15]), + 8.5) + """ + z = atleast_1d(z) + p = atleast_1d(p) + wo = float(wo) + + degree = _relative_degree(z, p) + + # Invert positions radially about unit circle to convert LPF to HPF + # Scale all points radially from origin to shift cutoff frequency + z_hp = wo / z + p_hp = wo / p + + # If lowpass had zeros at infinity, inverting moves them to origin. + z_hp = append(z_hp, zeros(degree)) + + # Cancel out gain change caused by inversion + k_hp = k * real(prod(-z) / prod(-p)) + + return z_hp, p_hp, k_hp + + +def lp2bp_zpk(z, p, k, wo=1.0, bw=1.0): + r""" + Transform a lowpass filter prototype to a bandpass filter. + + Return an analog band-pass filter with center frequency `wo` and + bandwidth `bw` from an analog low-pass filter prototype with unity + cutoff frequency, using zeros, poles, and gain ('zpk') representation. + + Parameters + ---------- + z : array_like + Zeros of the analog filter transfer function. + p : array_like + Poles of the analog filter transfer function. + k : float + System gain of the analog filter transfer function. + wo : float + Desired passband center, as angular frequency (e.g., rad/s). + Defaults to no change. + bw : float + Desired passband width, as angular frequency (e.g., rad/s). + Defaults to 1. + + Returns + ------- + z : ndarray + Zeros of the transformed band-pass filter transfer function. + p : ndarray + Poles of the transformed band-pass filter transfer function. + k : float + System gain of the transformed band-pass filter. + + See Also + -------- + lp2lp_zpk, lp2hp_zpk, lp2bs_zpk, bilinear + lp2bp + + Notes + ----- + This is derived from the s-plane substitution + + .. math:: s \rightarrow \frac{s^2 + {\omega_0}^2}{s \cdot \mathrm{BW}} + + This is the "wideband" transformation, producing a passband with + geometric (log frequency) symmetry about `wo`. + + .. versionadded:: 1.1.0 + + Examples + -------- + Use the 'zpk' (Zero-Pole-Gain) representation of a lowpass filter to + transform it to a bandpass filter with a center frequency wo and + bandwidth bw. + + >>> from scipy.signal import lp2bp_zpk + >>> z = [ 5 + 2j , 5 - 2j ] + >>> p = [ 7 , -16 ] + >>> k = 0.8 + >>> wo = 0.62 + >>> bw = 15 + >>> lp2bp_zpk(z, p, k, wo, bw) + ( array([7.49955815e+01+3.00017676e+01j, 7.49955815e+01-3.00017676e+01j, + 4.41850748e-03-1.76761126e-03j, 4.41850748e-03+1.76761126e-03j]), + array([1.04996339e+02+0.j, -1.60167736e-03+0.j, 3.66108003e-03+0.j, + -2.39998398e+02+0.j]), 0.8) + """ + z = atleast_1d(z) + p = atleast_1d(p) + wo = float(wo) + bw = float(bw) + + degree = _relative_degree(z, p) + + # Scale poles and zeros to desired bandwidth + z_lp = z * bw/2 + p_lp = p * bw/2 + + # Square root needs to produce complex result, not NaN + z_lp = z_lp.astype(complex) + p_lp = p_lp.astype(complex) + + # Duplicate poles and zeros and shift from baseband to +wo and -wo + z_bp = concatenate((z_lp + sqrt(z_lp**2 - wo**2), + z_lp - sqrt(z_lp**2 - wo**2))) + p_bp = concatenate((p_lp + sqrt(p_lp**2 - wo**2), + p_lp - sqrt(p_lp**2 - wo**2))) + + # Move degree zeros to origin, leaving degree zeros at infinity for BPF + z_bp = append(z_bp, zeros(degree)) + + # Cancel out gain change from frequency scaling + k_bp = k * bw**degree + + return z_bp, p_bp, k_bp + + +def lp2bs_zpk(z, p, k, wo=1.0, bw=1.0): + r""" + Transform a lowpass filter prototype to a bandstop filter. + + Return an analog band-stop filter with center frequency `wo` and + stopband width `bw` from an analog low-pass filter prototype with unity + cutoff frequency, using zeros, poles, and gain ('zpk') representation. + + Parameters + ---------- + z : array_like + Zeros of the analog filter transfer function. + p : array_like + Poles of the analog filter transfer function. + k : float + System gain of the analog filter transfer function. + wo : float + Desired stopband center, as angular frequency (e.g., rad/s). + Defaults to no change. + bw : float + Desired stopband width, as angular frequency (e.g., rad/s). + Defaults to 1. + + Returns + ------- + z : ndarray + Zeros of the transformed band-stop filter transfer function. + p : ndarray + Poles of the transformed band-stop filter transfer function. + k : float + System gain of the transformed band-stop filter. + + See Also + -------- + lp2lp_zpk, lp2hp_zpk, lp2bp_zpk, bilinear + lp2bs + + Notes + ----- + This is derived from the s-plane substitution + + .. math:: s \rightarrow \frac{s \cdot \mathrm{BW}}{s^2 + {\omega_0}^2} + + This is the "wideband" transformation, producing a stopband with + geometric (log frequency) symmetry about `wo`. + + .. versionadded:: 1.1.0 + + Examples + -------- + Transform a low-pass filter represented in 'zpk' (Zero-Pole-Gain) form + into a bandstop filter represented in 'zpk' form, with a center frequency wo and + bandwidth bw. + + >>> from scipy.signal import lp2bs_zpk + >>> z = [ ] + >>> p = [ 0.7 , -1 ] + >>> k = 9 + >>> wo = 0.5 + >>> bw = 10 + >>> lp2bs_zpk(z, p, k, wo, bw) + ( array([0.+0.5j, 0.+0.5j, 0.-0.5j, 0.-0.5j]), + array([14.2681928 +0.j, -0.02506281+0.j, 0.01752149+0.j, -9.97493719+0.j]), + -12.857142857142858) + """ + z = atleast_1d(z) + p = atleast_1d(p) + wo = float(wo) + bw = float(bw) + + degree = _relative_degree(z, p) + + # Invert to a highpass filter with desired bandwidth + z_hp = (bw/2) / z + p_hp = (bw/2) / p + + # Square root needs to produce complex result, not NaN + z_hp = z_hp.astype(complex) + p_hp = p_hp.astype(complex) + + # Duplicate poles and zeros and shift from baseband to +wo and -wo + z_bs = concatenate((z_hp + sqrt(z_hp**2 - wo**2), + z_hp - sqrt(z_hp**2 - wo**2))) + p_bs = concatenate((p_hp + sqrt(p_hp**2 - wo**2), + p_hp - sqrt(p_hp**2 - wo**2))) + + # Move any zeros that were at infinity to the center of the stopband + z_bs = append(z_bs, full(degree, +1j*wo)) + z_bs = append(z_bs, full(degree, -1j*wo)) + + # Cancel out gain change caused by inversion + k_bs = k * real(prod(-z) / prod(-p)) + + return z_bs, p_bs, k_bs + + +def butter(N, Wn, btype='low', analog=False, output='ba', fs=None): + """ + Butterworth digital and analog filter design. + + Design an Nth-order digital or analog Butterworth filter and return + the filter coefficients. + + Parameters + ---------- + N : int + The order of the filter. For 'bandpass' and 'bandstop' filters, + the resulting order of the final second-order sections ('sos') + matrix is ``2*N``, with `N` the number of biquad sections + of the desired system. + Wn : array_like + The critical frequency or frequencies. For lowpass and highpass + filters, Wn is a scalar; for bandpass and bandstop filters, + Wn is a length-2 sequence. + + For a Butterworth filter, this is the point at which the gain + drops to 1/sqrt(2) that of the passband (the "-3 dB point"). + + For digital filters, if `fs` is not specified, `Wn` units are + normalized from 0 to 1, where 1 is the Nyquist frequency (`Wn` is + thus in half cycles / sample and defined as 2*critical frequencies + / `fs`). If `fs` is specified, `Wn` is in the same units as `fs`. + + For analog filters, `Wn` is an angular frequency (e.g. rad/s). + btype : {'lowpass', 'highpass', 'bandpass', 'bandstop'}, optional + The type of filter. Default is 'lowpass'. + analog : bool, optional + When True, return an analog filter, otherwise a digital filter is + returned. + output : {'ba', 'zpk', 'sos'}, optional + Type of output: numerator/denominator ('ba'), pole-zero ('zpk'), or + second-order sections ('sos'). Default is 'ba' for backwards + compatibility, but 'sos' should be used for general-purpose filtering. + fs : float, optional + The sampling frequency of the digital system. + + .. versionadded:: 1.2.0 + + Returns + ------- + b, a : ndarray, ndarray + Numerator (`b`) and denominator (`a`) polynomials of the IIR filter. + Only returned if ``output='ba'``. + z, p, k : ndarray, ndarray, float + Zeros, poles, and system gain of the IIR filter transfer + function. Only returned if ``output='zpk'``. + sos : ndarray + Second-order sections representation of the IIR filter. + Only returned if ``output='sos'``. + + See Also + -------- + buttord, buttap + + Notes + ----- + The Butterworth filter has maximally flat frequency response in the + passband. + + The ``'sos'`` output parameter was added in 0.16.0. + + If the transfer function form ``[b, a]`` is requested, numerical + problems can occur since the conversion between roots and + the polynomial coefficients is a numerically sensitive operation, + even for N >= 4. It is recommended to work with the SOS + representation. + + .. warning:: + Designing high-order and narrowband IIR filters in TF form can + result in unstable or incorrect filtering due to floating point + numerical precision issues. Consider inspecting output filter + characteristics `freqz` or designing the filters with second-order + sections via ``output='sos'``. + + Examples + -------- + Design an analog filter and plot its frequency response, showing the + critical points: + + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> import numpy as np + + >>> b, a = signal.butter(4, 100, 'low', analog=True) + >>> w, h = signal.freqs(b, a) + >>> plt.semilogx(w, 20 * np.log10(abs(h))) + >>> plt.title('Butterworth filter frequency response') + >>> plt.xlabel('Frequency [rad/s]') + >>> plt.ylabel('Amplitude [dB]') + >>> plt.margins(0, 0.1) + >>> plt.grid(which='both', axis='both') + >>> plt.axvline(100, color='green') # cutoff frequency + >>> plt.show() + + Generate a signal made up of 10 Hz and 20 Hz, sampled at 1 kHz + + >>> t = np.linspace(0, 1, 1000, False) # 1 second + >>> sig = np.sin(2*np.pi*10*t) + np.sin(2*np.pi*20*t) + >>> fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True) + >>> ax1.plot(t, sig) + >>> ax1.set_title('10 Hz and 20 Hz sinusoids') + >>> ax1.axis([0, 1, -2, 2]) + + Design a digital high-pass filter at 15 Hz to remove the 10 Hz tone, and + apply it to the signal. (It's recommended to use second-order sections + format when filtering, to avoid numerical error with transfer function + (``ba``) format): + + >>> sos = signal.butter(10, 15, 'hp', fs=1000, output='sos') + >>> filtered = signal.sosfilt(sos, sig) + >>> ax2.plot(t, filtered) + >>> ax2.set_title('After 15 Hz high-pass filter') + >>> ax2.axis([0, 1, -2, 2]) + >>> ax2.set_xlabel('Time [s]') + >>> plt.tight_layout() + >>> plt.show() + """ + return iirfilter(N, Wn, btype=btype, analog=analog, + output=output, ftype='butter', fs=fs) + + +def cheby1(N, rp, Wn, btype='low', analog=False, output='ba', fs=None): + """ + Chebyshev type I digital and analog filter design. + + Design an Nth-order digital or analog Chebyshev type I filter and + return the filter coefficients. + + Parameters + ---------- + N : int + The order of the filter. + rp : float + The maximum ripple allowed below unity gain in the passband. + Specified in decibels, as a positive number. + Wn : array_like + A scalar or length-2 sequence giving the critical frequencies. + For Type I filters, this is the point in the transition band at which + the gain first drops below -`rp`. + + For digital filters, `Wn` are in the same units as `fs`. By default, + `fs` is 2 half-cycles/sample, so these are normalized from 0 to 1, + where 1 is the Nyquist frequency. (`Wn` is thus in + half-cycles / sample.) + + For analog filters, `Wn` is an angular frequency (e.g., rad/s). + btype : {'lowpass', 'highpass', 'bandpass', 'bandstop'}, optional + The type of filter. Default is 'lowpass'. + analog : bool, optional + When True, return an analog filter, otherwise a digital filter is + returned. + output : {'ba', 'zpk', 'sos'}, optional + Type of output: numerator/denominator ('ba'), pole-zero ('zpk'), or + second-order sections ('sos'). Default is 'ba' for backwards + compatibility, but 'sos' should be used for general-purpose filtering. + fs : float, optional + The sampling frequency of the digital system. + + .. versionadded:: 1.2.0 + + Returns + ------- + b, a : ndarray, ndarray + Numerator (`b`) and denominator (`a`) polynomials of the IIR filter. + Only returned if ``output='ba'``. + z, p, k : ndarray, ndarray, float + Zeros, poles, and system gain of the IIR filter transfer + function. Only returned if ``output='zpk'``. + sos : ndarray + Second-order sections representation of the IIR filter. + Only returned if ``output='sos'``. + + See Also + -------- + cheb1ord, cheb1ap + + Notes + ----- + The Chebyshev type I filter maximizes the rate of cutoff between the + frequency response's passband and stopband, at the expense of ripple in + the passband and increased ringing in the step response. + + Type I filters roll off faster than Type II (`cheby2`), but Type II + filters do not have any ripple in the passband. + + The equiripple passband has N maxima or minima (for example, a + 5th-order filter has 3 maxima and 2 minima). Consequently, the DC gain is + unity for odd-order filters, or -rp dB for even-order filters. + + The ``'sos'`` output parameter was added in 0.16.0. + + Examples + -------- + Design an analog filter and plot its frequency response, showing the + critical points: + + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> import numpy as np + + >>> b, a = signal.cheby1(4, 5, 100, 'low', analog=True) + >>> w, h = signal.freqs(b, a) + >>> plt.semilogx(w, 20 * np.log10(abs(h))) + >>> plt.title('Chebyshev Type I frequency response (rp=5)') + >>> plt.xlabel('Frequency [rad/s]') + >>> plt.ylabel('Amplitude [dB]') + >>> plt.margins(0, 0.1) + >>> plt.grid(which='both', axis='both') + >>> plt.axvline(100, color='green') # cutoff frequency + >>> plt.axhline(-5, color='green') # rp + >>> plt.show() + + Generate a signal made up of 10 Hz and 20 Hz, sampled at 1 kHz + + >>> t = np.linspace(0, 1, 1000, False) # 1 second + >>> sig = np.sin(2*np.pi*10*t) + np.sin(2*np.pi*20*t) + >>> fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True) + >>> ax1.plot(t, sig) + >>> ax1.set_title('10 Hz and 20 Hz sinusoids') + >>> ax1.axis([0, 1, -2, 2]) + + Design a digital high-pass filter at 15 Hz to remove the 10 Hz tone, and + apply it to the signal. (It's recommended to use second-order sections + format when filtering, to avoid numerical error with transfer function + (``ba``) format): + + >>> sos = signal.cheby1(10, 1, 15, 'hp', fs=1000, output='sos') + >>> filtered = signal.sosfilt(sos, sig) + >>> ax2.plot(t, filtered) + >>> ax2.set_title('After 15 Hz high-pass filter') + >>> ax2.axis([0, 1, -2, 2]) + >>> ax2.set_xlabel('Time [s]') + >>> plt.tight_layout() + >>> plt.show() + """ + return iirfilter(N, Wn, rp=rp, btype=btype, analog=analog, + output=output, ftype='cheby1', fs=fs) + + +def cheby2(N, rs, Wn, btype='low', analog=False, output='ba', fs=None): + """ + Chebyshev type II digital and analog filter design. + + Design an Nth-order digital or analog Chebyshev type II filter and + return the filter coefficients. + + Parameters + ---------- + N : int + The order of the filter. + rs : float + The minimum attenuation required in the stop band. + Specified in decibels, as a positive number. + Wn : array_like + A scalar or length-2 sequence giving the critical frequencies. + For Type II filters, this is the point in the transition band at which + the gain first reaches -`rs`. + + For digital filters, `Wn` are in the same units as `fs`. By default, + `fs` is 2 half-cycles/sample, so these are normalized from 0 to 1, + where 1 is the Nyquist frequency. (`Wn` is thus in + half-cycles / sample.) + + For analog filters, `Wn` is an angular frequency (e.g., rad/s). + btype : {'lowpass', 'highpass', 'bandpass', 'bandstop'}, optional + The type of filter. Default is 'lowpass'. + analog : bool, optional + When True, return an analog filter, otherwise a digital filter is + returned. + output : {'ba', 'zpk', 'sos'}, optional + Type of output: numerator/denominator ('ba'), pole-zero ('zpk'), or + second-order sections ('sos'). Default is 'ba' for backwards + compatibility, but 'sos' should be used for general-purpose filtering. + fs : float, optional + The sampling frequency of the digital system. + + .. versionadded:: 1.2.0 + + Returns + ------- + b, a : ndarray, ndarray + Numerator (`b`) and denominator (`a`) polynomials of the IIR filter. + Only returned if ``output='ba'``. + z, p, k : ndarray, ndarray, float + Zeros, poles, and system gain of the IIR filter transfer + function. Only returned if ``output='zpk'``. + sos : ndarray + Second-order sections representation of the IIR filter. + Only returned if ``output='sos'``. + + See Also + -------- + cheb2ord, cheb2ap + + Notes + ----- + The Chebyshev type II filter maximizes the rate of cutoff between the + frequency response's passband and stopband, at the expense of ripple in + the stopband and increased ringing in the step response. + + Type II filters do not roll off as fast as Type I (`cheby1`). + + The ``'sos'`` output parameter was added in 0.16.0. + + Examples + -------- + Design an analog filter and plot its frequency response, showing the + critical points: + + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> import numpy as np + + >>> b, a = signal.cheby2(4, 40, 100, 'low', analog=True) + >>> w, h = signal.freqs(b, a) + >>> plt.semilogx(w, 20 * np.log10(abs(h))) + >>> plt.title('Chebyshev Type II frequency response (rs=40)') + >>> plt.xlabel('Frequency [rad/s]') + >>> plt.ylabel('Amplitude [dB]') + >>> plt.margins(0, 0.1) + >>> plt.grid(which='both', axis='both') + >>> plt.axvline(100, color='green') # cutoff frequency + >>> plt.axhline(-40, color='green') # rs + >>> plt.show() + + Generate a signal made up of 10 Hz and 20 Hz, sampled at 1 kHz + + >>> t = np.linspace(0, 1, 1000, False) # 1 second + >>> sig = np.sin(2*np.pi*10*t) + np.sin(2*np.pi*20*t) + >>> fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True) + >>> ax1.plot(t, sig) + >>> ax1.set_title('10 Hz and 20 Hz sinusoids') + >>> ax1.axis([0, 1, -2, 2]) + + Design a digital high-pass filter at 17 Hz to remove the 10 Hz tone, and + apply it to the signal. (It's recommended to use second-order sections + format when filtering, to avoid numerical error with transfer function + (``ba``) format): + + >>> sos = signal.cheby2(12, 20, 17, 'hp', fs=1000, output='sos') + >>> filtered = signal.sosfilt(sos, sig) + >>> ax2.plot(t, filtered) + >>> ax2.set_title('After 17 Hz high-pass filter') + >>> ax2.axis([0, 1, -2, 2]) + >>> ax2.set_xlabel('Time [s]') + >>> plt.show() + """ + return iirfilter(N, Wn, rs=rs, btype=btype, analog=analog, + output=output, ftype='cheby2', fs=fs) + + +def ellip(N, rp, rs, Wn, btype='low', analog=False, output='ba', fs=None): + """ + Elliptic (Cauer) digital and analog filter design. + + Design an Nth-order digital or analog elliptic filter and return + the filter coefficients. + + Parameters + ---------- + N : int + The order of the filter. + rp : float + The maximum ripple allowed below unity gain in the passband. + Specified in decibels, as a positive number. + rs : float + The minimum attenuation required in the stop band. + Specified in decibels, as a positive number. + Wn : array_like + A scalar or length-2 sequence giving the critical frequencies. + For elliptic filters, this is the point in the transition band at + which the gain first drops below -`rp`. + + For digital filters, `Wn` are in the same units as `fs`. By default, + `fs` is 2 half-cycles/sample, so these are normalized from 0 to 1, + where 1 is the Nyquist frequency. (`Wn` is thus in + half-cycles / sample.) + + For analog filters, `Wn` is an angular frequency (e.g., rad/s). + btype : {'lowpass', 'highpass', 'bandpass', 'bandstop'}, optional + The type of filter. Default is 'lowpass'. + analog : bool, optional + When True, return an analog filter, otherwise a digital filter is + returned. + output : {'ba', 'zpk', 'sos'}, optional + Type of output: numerator/denominator ('ba'), pole-zero ('zpk'), or + second-order sections ('sos'). Default is 'ba' for backwards + compatibility, but 'sos' should be used for general-purpose filtering. + fs : float, optional + The sampling frequency of the digital system. + + .. versionadded:: 1.2.0 + + Returns + ------- + b, a : ndarray, ndarray + Numerator (`b`) and denominator (`a`) polynomials of the IIR filter. + Only returned if ``output='ba'``. + z, p, k : ndarray, ndarray, float + Zeros, poles, and system gain of the IIR filter transfer + function. Only returned if ``output='zpk'``. + sos : ndarray + Second-order sections representation of the IIR filter. + Only returned if ``output='sos'``. + + See Also + -------- + ellipord, ellipap + + Notes + ----- + Also known as Cauer or Zolotarev filters, the elliptical filter maximizes + the rate of transition between the frequency response's passband and + stopband, at the expense of ripple in both, and increased ringing in the + step response. + + As `rp` approaches 0, the elliptical filter becomes a Chebyshev + type II filter (`cheby2`). As `rs` approaches 0, it becomes a Chebyshev + type I filter (`cheby1`). As both approach 0, it becomes a Butterworth + filter (`butter`). + + The equiripple passband has N maxima or minima (for example, a + 5th-order filter has 3 maxima and 2 minima). Consequently, the DC gain is + unity for odd-order filters, or -rp dB for even-order filters. + + The ``'sos'`` output parameter was added in 0.16.0. + + Examples + -------- + Design an analog filter and plot its frequency response, showing the + critical points: + + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> import numpy as np + + >>> b, a = signal.ellip(4, 5, 40, 100, 'low', analog=True) + >>> w, h = signal.freqs(b, a) + >>> plt.semilogx(w, 20 * np.log10(abs(h))) + >>> plt.title('Elliptic filter frequency response (rp=5, rs=40)') + >>> plt.xlabel('Frequency [rad/s]') + >>> plt.ylabel('Amplitude [dB]') + >>> plt.margins(0, 0.1) + >>> plt.grid(which='both', axis='both') + >>> plt.axvline(100, color='green') # cutoff frequency + >>> plt.axhline(-40, color='green') # rs + >>> plt.axhline(-5, color='green') # rp + >>> plt.show() + + Generate a signal made up of 10 Hz and 20 Hz, sampled at 1 kHz + + >>> t = np.linspace(0, 1, 1000, False) # 1 second + >>> sig = np.sin(2*np.pi*10*t) + np.sin(2*np.pi*20*t) + >>> fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True) + >>> ax1.plot(t, sig) + >>> ax1.set_title('10 Hz and 20 Hz sinusoids') + >>> ax1.axis([0, 1, -2, 2]) + + Design a digital high-pass filter at 17 Hz to remove the 10 Hz tone, and + apply it to the signal. (It's recommended to use second-order sections + format when filtering, to avoid numerical error with transfer function + (``ba``) format): + + >>> sos = signal.ellip(8, 1, 100, 17, 'hp', fs=1000, output='sos') + >>> filtered = signal.sosfilt(sos, sig) + >>> ax2.plot(t, filtered) + >>> ax2.set_title('After 17 Hz high-pass filter') + >>> ax2.axis([0, 1, -2, 2]) + >>> ax2.set_xlabel('Time [s]') + >>> plt.tight_layout() + >>> plt.show() + """ + return iirfilter(N, Wn, rs=rs, rp=rp, btype=btype, analog=analog, + output=output, ftype='elliptic', fs=fs) + + +def bessel(N, Wn, btype='low', analog=False, output='ba', norm='phase', + fs=None): + """ + Bessel/Thomson digital and analog filter design. + + Design an Nth-order digital or analog Bessel filter and return the + filter coefficients. + + Parameters + ---------- + N : int + The order of the filter. + Wn : array_like + A scalar or length-2 sequence giving the critical frequencies (defined + by the `norm` parameter). + For analog filters, `Wn` is an angular frequency (e.g., rad/s). + + For digital filters, `Wn` are in the same units as `fs`. By default, + `fs` is 2 half-cycles/sample, so these are normalized from 0 to 1, + where 1 is the Nyquist frequency. (`Wn` is thus in + half-cycles / sample.) + btype : {'lowpass', 'highpass', 'bandpass', 'bandstop'}, optional + The type of filter. Default is 'lowpass'. + analog : bool, optional + When True, return an analog filter, otherwise a digital filter is + returned. (See Notes.) + output : {'ba', 'zpk', 'sos'}, optional + Type of output: numerator/denominator ('ba'), pole-zero ('zpk'), or + second-order sections ('sos'). Default is 'ba'. + norm : {'phase', 'delay', 'mag'}, optional + Critical frequency normalization: + + ``phase`` + The filter is normalized such that the phase response reaches its + midpoint at angular (e.g. rad/s) frequency `Wn`. This happens for + both low-pass and high-pass filters, so this is the + "phase-matched" case. + + The magnitude response asymptotes are the same as a Butterworth + filter of the same order with a cutoff of `Wn`. + + This is the default, and matches MATLAB's implementation. + + ``delay`` + The filter is normalized such that the group delay in the passband + is 1/`Wn` (e.g., seconds). This is the "natural" type obtained by + solving Bessel polynomials. + + ``mag`` + The filter is normalized such that the gain magnitude is -3 dB at + angular frequency `Wn`. + + .. versionadded:: 0.18.0 + fs : float, optional + The sampling frequency of the digital system. + + .. versionadded:: 1.2.0 + + Returns + ------- + b, a : ndarray, ndarray + Numerator (`b`) and denominator (`a`) polynomials of the IIR filter. + Only returned if ``output='ba'``. + z, p, k : ndarray, ndarray, float + Zeros, poles, and system gain of the IIR filter transfer + function. Only returned if ``output='zpk'``. + sos : ndarray + Second-order sections representation of the IIR filter. + Only returned if ``output='sos'``. + + Notes + ----- + Also known as a Thomson filter, the analog Bessel filter has maximally + flat group delay and maximally linear phase response, with very little + ringing in the step response. [1]_ + + The Bessel is inherently an analog filter. This function generates digital + Bessel filters using the bilinear transform, which does not preserve the + phase response of the analog filter. As such, it is only approximately + correct at frequencies below about fs/4. To get maximally-flat group + delay at higher frequencies, the analog Bessel filter must be transformed + using phase-preserving techniques. + + See `besselap` for implementation details and references. + + The ``'sos'`` output parameter was added in 0.16.0. + + References + ---------- + .. [1] Thomson, W.E., "Delay Networks having Maximally Flat Frequency + Characteristics", Proceedings of the Institution of Electrical + Engineers, Part III, November 1949, Vol. 96, No. 44, pp. 487-490. + + Examples + -------- + Plot the phase-normalized frequency response, showing the relationship + to the Butterworth's cutoff frequency (green): + + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> import numpy as np + + >>> b, a = signal.butter(4, 100, 'low', analog=True) + >>> w, h = signal.freqs(b, a) + >>> plt.semilogx(w, 20 * np.log10(np.abs(h)), color='silver', ls='dashed') + >>> b, a = signal.bessel(4, 100, 'low', analog=True, norm='phase') + >>> w, h = signal.freqs(b, a) + >>> plt.semilogx(w, 20 * np.log10(np.abs(h))) + >>> plt.title('Bessel filter magnitude response (with Butterworth)') + >>> plt.xlabel('Frequency [rad/s]') + >>> plt.ylabel('Amplitude [dB]') + >>> plt.margins(0, 0.1) + >>> plt.grid(which='both', axis='both') + >>> plt.axvline(100, color='green') # cutoff frequency + >>> plt.show() + + and the phase midpoint: + + >>> plt.figure() + >>> plt.semilogx(w, np.unwrap(np.angle(h))) + >>> plt.axvline(100, color='green') # cutoff frequency + >>> plt.axhline(-np.pi, color='red') # phase midpoint + >>> plt.title('Bessel filter phase response') + >>> plt.xlabel('Frequency [rad/s]') + >>> plt.ylabel('Phase [rad]') + >>> plt.margins(0, 0.1) + >>> plt.grid(which='both', axis='both') + >>> plt.show() + + Plot the magnitude-normalized frequency response, showing the -3 dB cutoff: + + >>> b, a = signal.bessel(3, 10, 'low', analog=True, norm='mag') + >>> w, h = signal.freqs(b, a) + >>> plt.semilogx(w, 20 * np.log10(np.abs(h))) + >>> plt.axhline(-3, color='red') # -3 dB magnitude + >>> plt.axvline(10, color='green') # cutoff frequency + >>> plt.title('Amplitude-normalized Bessel filter frequency response') + >>> plt.xlabel('Frequency [rad/s]') + >>> plt.ylabel('Amplitude [dB]') + >>> plt.margins(0, 0.1) + >>> plt.grid(which='both', axis='both') + >>> plt.show() + + Plot the delay-normalized filter, showing the maximally-flat group delay + at 0.1 seconds: + + >>> b, a = signal.bessel(5, 1/0.1, 'low', analog=True, norm='delay') + >>> w, h = signal.freqs(b, a) + >>> plt.figure() + >>> plt.semilogx(w[1:], -np.diff(np.unwrap(np.angle(h)))/np.diff(w)) + >>> plt.axhline(0.1, color='red') # 0.1 seconds group delay + >>> plt.title('Bessel filter group delay') + >>> plt.xlabel('Frequency [rad/s]') + >>> plt.ylabel('Group delay [s]') + >>> plt.margins(0, 0.1) + >>> plt.grid(which='both', axis='both') + >>> plt.show() + + """ + return iirfilter(N, Wn, btype=btype, analog=analog, + output=output, ftype='bessel_'+norm, fs=fs) + + +def maxflat(): + pass + + +def yulewalk(): + pass + + +def band_stop_obj(wp, ind, passb, stopb, gpass, gstop, type): + """ + Band Stop Objective Function for order minimization. + + Returns the non-integer order for an analog band stop filter. + + Parameters + ---------- + wp : scalar + Edge of passband `passb`. + ind : int, {0, 1} + Index specifying which `passb` edge to vary (0 or 1). + passb : ndarray + Two element sequence of fixed passband edges. + stopb : ndarray + Two element sequence of fixed stopband edges. + gstop : float + Amount of attenuation in stopband in dB. + gpass : float + Amount of ripple in the passband in dB. + type : {'butter', 'cheby', 'ellip'} + Type of filter. + + Returns + ------- + n : scalar + Filter order (possibly non-integer). + + Notes + ----- + Band-stop filters are used in applications where certain frequency + components need to be blocked while others are allowed; for instance, + removing noise at specific frequencies while allowing the desired signal + to pass through. The order of a filter often determines its complexity and + accuracy. Determining the right order can be a challenge. This function + aims to provide an appropriate order for an analog band stop filter. + + Examples + -------- + + >>> import numpy as np + >>> from scipy.signal import band_stop_obj + >>> wp = 2 + >>> ind = 1 + >>> passb = np.array([1, 3]) + >>> stopb = np.array([0.5, 4]) + >>> gstop = 30 + >>> gpass = 3 + >>> filter_type = 'butter' + >>> band_stop_obj(wp, ind, passb, stopb, gpass, gstop, filter_type) + np.float64(-2.758504160760643) + + """ + + _validate_gpass_gstop(gpass, gstop) + + passbC = passb.copy() + passbC[ind] = wp + nat = (stopb * (passbC[0] - passbC[1]) / + (stopb ** 2 - passbC[0] * passbC[1])) + nat = min(abs(nat)) + + if type == 'butter': + GSTOP = 10 ** (0.1 * abs(gstop)) + GPASS = 10 ** (0.1 * abs(gpass)) + n = (log10((GSTOP - 1.0) / (GPASS - 1.0)) / (2 * log10(nat))) + elif type == 'cheby': + GSTOP = 10 ** (0.1 * abs(gstop)) + GPASS = 10 ** (0.1 * abs(gpass)) + n = arccosh(sqrt((GSTOP - 1.0) / (GPASS - 1.0))) / arccosh(nat) + elif type == 'ellip': + GSTOP = 10 ** (0.1 * gstop) + GPASS = 10 ** (0.1 * gpass) + arg1 = sqrt((GPASS - 1.0) / (GSTOP - 1.0)) + arg0 = 1.0 / nat + d0 = special.ellipk([arg0 ** 2, 1 - arg0 ** 2]) + d1 = special.ellipk([arg1 ** 2, 1 - arg1 ** 2]) + n = (d0[0] * d1[1] / (d0[1] * d1[0])) + else: + raise ValueError(f"Incorrect type: {type}") + return n + + +def _pre_warp(wp, ws, analog): + # Pre-warp frequencies for digital filter design + if not analog: + passb = np.tan(pi * wp / 2.0) + stopb = np.tan(pi * ws / 2.0) + else: + passb = wp * 1.0 + stopb = ws * 1.0 + return passb, stopb + + +def _validate_wp_ws(wp, ws, fs, analog): + wp = atleast_1d(wp) + ws = atleast_1d(ws) + if fs is not None: + if analog: + raise ValueError("fs cannot be specified for an analog filter") + wp = 2 * wp / fs + ws = 2 * ws / fs + + filter_type = 2 * (len(wp) - 1) + 1 + if wp[0] >= ws[0]: + filter_type += 1 + + return wp, ws, filter_type + + +def _find_nat_freq(stopb, passb, gpass, gstop, filter_type, filter_kind): + if filter_type == 1: # low + nat = stopb / passb + elif filter_type == 2: # high + nat = passb / stopb + elif filter_type == 3: # stop + + ### breakpoint() + + wp0 = optimize.fminbound(band_stop_obj, passb[0], stopb[0] - 1e-12, + args=(0, passb, stopb, gpass, gstop, + filter_kind), + disp=0) + passb[0] = wp0 + wp1 = optimize.fminbound(band_stop_obj, stopb[1] + 1e-12, passb[1], + args=(1, passb, stopb, gpass, gstop, + filter_kind), + disp=0) + passb[1] = wp1 + nat = ((stopb * (passb[0] - passb[1])) / + (stopb ** 2 - passb[0] * passb[1])) + elif filter_type == 4: # pass + nat = ((stopb ** 2 - passb[0] * passb[1]) / + (stopb * (passb[0] - passb[1]))) + else: + raise ValueError(f"should not happen: {filter_type =}.") + + nat = min(abs(nat)) + return nat, passb + + +def _postprocess_wn(WN, analog, fs): + wn = WN if analog else np.arctan(WN) * 2.0 / pi + if len(wn) == 1: + wn = wn[0] + if fs is not None: + wn = wn * fs / 2 + return wn + + +def buttord(wp, ws, gpass, gstop, analog=False, fs=None): + """Butterworth filter order selection. + + Return the order of the lowest order digital or analog Butterworth filter + that loses no more than `gpass` dB in the passband and has at least + `gstop` dB attenuation in the stopband. + + Parameters + ---------- + wp, ws : float + Passband and stopband edge frequencies. + + For digital filters, these are in the same units as `fs`. By default, + `fs` is 2 half-cycles/sample, so these are normalized from 0 to 1, + where 1 is the Nyquist frequency. (`wp` and `ws` are thus in + half-cycles / sample.) For example: + + - Lowpass: wp = 0.2, ws = 0.3 + - Highpass: wp = 0.3, ws = 0.2 + - Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6] + - Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5] + + For analog filters, `wp` and `ws` are angular frequencies (e.g., rad/s). + gpass : float + The maximum loss in the passband (dB). + gstop : float + The minimum attenuation in the stopband (dB). + analog : bool, optional + When True, return an analog filter, otherwise a digital filter is + returned. + fs : float, optional + The sampling frequency of the digital system. + + .. versionadded:: 1.2.0 + + Returns + ------- + ord : int + The lowest order for a Butterworth filter which meets specs. + wn : ndarray or float + The Butterworth natural frequency (i.e. the "3dB frequency"). Should + be used with `butter` to give filter results. If `fs` is specified, + this is in the same units, and `fs` must also be passed to `butter`. + + See Also + -------- + butter : Filter design using order and critical points + cheb1ord : Find order and critical points from passband and stopband spec + cheb2ord, ellipord + iirfilter : General filter design using order and critical frequencies + iirdesign : General filter design using passband and stopband spec + + Examples + -------- + Design an analog bandpass filter with passband within 3 dB from 20 to + 50 rad/s, while rejecting at least -40 dB below 14 and above 60 rad/s. + Plot its frequency response, showing the passband and stopband + constraints in gray. + + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> import numpy as np + + >>> N, Wn = signal.buttord([20, 50], [14, 60], 3, 40, True) + >>> b, a = signal.butter(N, Wn, 'band', True) + >>> w, h = signal.freqs(b, a, np.logspace(1, 2, 500)) + >>> plt.semilogx(w, 20 * np.log10(abs(h))) + >>> plt.title('Butterworth bandpass filter fit to constraints') + >>> plt.xlabel('Frequency [rad/s]') + >>> plt.ylabel('Amplitude [dB]') + >>> plt.grid(which='both', axis='both') + >>> plt.fill([1, 14, 14, 1], [-40, -40, 99, 99], '0.9', lw=0) # stop + >>> plt.fill([20, 20, 50, 50], [-99, -3, -3, -99], '0.9', lw=0) # pass + >>> plt.fill([60, 60, 1e9, 1e9], [99, -40, -40, 99], '0.9', lw=0) # stop + >>> plt.axis([10, 100, -60, 3]) + >>> plt.show() + + """ + _validate_gpass_gstop(gpass, gstop) + fs = _validate_fs(fs, allow_none=True) + wp, ws, filter_type = _validate_wp_ws(wp, ws, fs, analog) + passb, stopb = _pre_warp(wp, ws, analog) + nat, passb = _find_nat_freq(stopb, passb, gpass, gstop, filter_type, 'butter') + + GSTOP = 10 ** (0.1 * abs(gstop)) + GPASS = 10 ** (0.1 * abs(gpass)) + ord = int(ceil(log10((GSTOP - 1.0) / (GPASS - 1.0)) / (2 * log10(nat)))) + + # Find the Butterworth natural frequency WN (or the "3dB" frequency") + # to give exactly gpass at passb. + try: + W0 = (GPASS - 1.0) ** (-1.0 / (2.0 * ord)) + except ZeroDivisionError: + W0 = 1.0 + warnings.warn("Order is zero...check input parameters.", + RuntimeWarning, stacklevel=2) + + # now convert this frequency back from lowpass prototype + # to the original analog filter + + if filter_type == 1: # low + WN = W0 * passb + elif filter_type == 2: # high + WN = passb / W0 + elif filter_type == 3: # stop + WN = np.empty(2, float) + discr = sqrt((passb[1] - passb[0]) ** 2 + + 4 * W0 ** 2 * passb[0] * passb[1]) + WN[0] = ((passb[1] - passb[0]) + discr) / (2 * W0) + WN[1] = ((passb[1] - passb[0]) - discr) / (2 * W0) + WN = np.sort(abs(WN)) + elif filter_type == 4: # pass + W0 = np.array([-W0, W0], float) + WN = (-W0 * (passb[1] - passb[0]) / 2.0 + + sqrt(W0 ** 2 / 4.0 * (passb[1] - passb[0]) ** 2 + + passb[0] * passb[1])) + WN = np.sort(abs(WN)) + else: + raise ValueError(f"Bad type: {filter_type}") + + wn = _postprocess_wn(WN, analog, fs) + + return ord, wn + + +def cheb1ord(wp, ws, gpass, gstop, analog=False, fs=None): + """Chebyshev type I filter order selection. + + Return the order of the lowest order digital or analog Chebyshev Type I + filter that loses no more than `gpass` dB in the passband and has at + least `gstop` dB attenuation in the stopband. + + Parameters + ---------- + wp, ws : float + Passband and stopband edge frequencies. + + For digital filters, these are in the same units as `fs`. By default, + `fs` is 2 half-cycles/sample, so these are normalized from 0 to 1, + where 1 is the Nyquist frequency. (`wp` and `ws` are thus in + half-cycles / sample.) For example: + + - Lowpass: wp = 0.2, ws = 0.3 + - Highpass: wp = 0.3, ws = 0.2 + - Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6] + - Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5] + + For analog filters, `wp` and `ws` are angular frequencies (e.g., rad/s). + gpass : float + The maximum loss in the passband (dB). + gstop : float + The minimum attenuation in the stopband (dB). + analog : bool, optional + When True, return an analog filter, otherwise a digital filter is + returned. + fs : float, optional + The sampling frequency of the digital system. + + .. versionadded:: 1.2.0 + + Returns + ------- + ord : int + The lowest order for a Chebyshev type I filter that meets specs. + wn : ndarray or float + The Chebyshev natural frequency (the "3dB frequency") for use with + `cheby1` to give filter results. If `fs` is specified, + this is in the same units, and `fs` must also be passed to `cheby1`. + + See Also + -------- + cheby1 : Filter design using order and critical points + buttord : Find order and critical points from passband and stopband spec + cheb2ord, ellipord + iirfilter : General filter design using order and critical frequencies + iirdesign : General filter design using passband and stopband spec + + Examples + -------- + Design a digital lowpass filter such that the passband is within 3 dB up + to 0.2*(fs/2), while rejecting at least -40 dB above 0.3*(fs/2). Plot its + frequency response, showing the passband and stopband constraints in gray. + + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> import numpy as np + + >>> N, Wn = signal.cheb1ord(0.2, 0.3, 3, 40) + >>> b, a = signal.cheby1(N, 3, Wn, 'low') + >>> w, h = signal.freqz(b, a) + >>> plt.semilogx(w / np.pi, 20 * np.log10(abs(h))) + >>> plt.title('Chebyshev I lowpass filter fit to constraints') + >>> plt.xlabel('Normalized frequency') + >>> plt.ylabel('Amplitude [dB]') + >>> plt.grid(which='both', axis='both') + >>> plt.fill([.01, 0.2, 0.2, .01], [-3, -3, -99, -99], '0.9', lw=0) # stop + >>> plt.fill([0.3, 0.3, 2, 2], [ 9, -40, -40, 9], '0.9', lw=0) # pass + >>> plt.axis([0.08, 1, -60, 3]) + >>> plt.show() + + """ + fs = _validate_fs(fs, allow_none=True) + _validate_gpass_gstop(gpass, gstop) + wp, ws, filter_type = _validate_wp_ws(wp, ws, fs, analog) + passb, stopb = _pre_warp(wp, ws, analog) + nat, passb = _find_nat_freq(stopb, passb, gpass, gstop, filter_type, 'cheby') + + GSTOP = 10 ** (0.1 * abs(gstop)) + GPASS = 10 ** (0.1 * abs(gpass)) + v_pass_stop = np.arccosh(np.sqrt((GSTOP - 1.0) / (GPASS - 1.0))) + ord = int(ceil(v_pass_stop / np.arccosh(nat))) + + # Natural frequencies are just the passband edges + wn = _postprocess_wn(passb, analog, fs) + + return ord, wn + + +def cheb2ord(wp, ws, gpass, gstop, analog=False, fs=None): + """Chebyshev type II filter order selection. + + Return the order of the lowest order digital or analog Chebyshev Type II + filter that loses no more than `gpass` dB in the passband and has at least + `gstop` dB attenuation in the stopband. + + Parameters + ---------- + wp, ws : float + Passband and stopband edge frequencies. + + For digital filters, these are in the same units as `fs`. By default, + `fs` is 2 half-cycles/sample, so these are normalized from 0 to 1, + where 1 is the Nyquist frequency. (`wp` and `ws` are thus in + half-cycles / sample.) For example: + + - Lowpass: wp = 0.2, ws = 0.3 + - Highpass: wp = 0.3, ws = 0.2 + - Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6] + - Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5] + + For analog filters, `wp` and `ws` are angular frequencies (e.g., rad/s). + gpass : float + The maximum loss in the passband (dB). + gstop : float + The minimum attenuation in the stopband (dB). + analog : bool, optional + When True, return an analog filter, otherwise a digital filter is + returned. + fs : float, optional + The sampling frequency of the digital system. + + .. versionadded:: 1.2.0 + + Returns + ------- + ord : int + The lowest order for a Chebyshev type II filter that meets specs. + wn : ndarray or float + The Chebyshev natural frequency (the "3dB frequency") for use with + `cheby2` to give filter results. If `fs` is specified, + this is in the same units, and `fs` must also be passed to `cheby2`. + + See Also + -------- + cheby2 : Filter design using order and critical points + buttord : Find order and critical points from passband and stopband spec + cheb1ord, ellipord + iirfilter : General filter design using order and critical frequencies + iirdesign : General filter design using passband and stopband spec + + Examples + -------- + Design a digital bandstop filter which rejects -60 dB from 0.2*(fs/2) to + 0.5*(fs/2), while staying within 3 dB below 0.1*(fs/2) or above + 0.6*(fs/2). Plot its frequency response, showing the passband and + stopband constraints in gray. + + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> import numpy as np + + >>> N, Wn = signal.cheb2ord([0.1, 0.6], [0.2, 0.5], 3, 60) + >>> b, a = signal.cheby2(N, 60, Wn, 'stop') + >>> w, h = signal.freqz(b, a) + >>> plt.semilogx(w / np.pi, 20 * np.log10(abs(h))) + >>> plt.title('Chebyshev II bandstop filter fit to constraints') + >>> plt.xlabel('Normalized frequency') + >>> plt.ylabel('Amplitude [dB]') + >>> plt.grid(which='both', axis='both') + >>> plt.fill([.01, .1, .1, .01], [-3, -3, -99, -99], '0.9', lw=0) # stop + >>> plt.fill([.2, .2, .5, .5], [ 9, -60, -60, 9], '0.9', lw=0) # pass + >>> plt.fill([.6, .6, 2, 2], [-99, -3, -3, -99], '0.9', lw=0) # stop + >>> plt.axis([0.06, 1, -80, 3]) + >>> plt.show() + + """ + fs = _validate_fs(fs, allow_none=True) + _validate_gpass_gstop(gpass, gstop) + wp, ws, filter_type = _validate_wp_ws(wp, ws, fs, analog) + passb, stopb = _pre_warp(wp, ws, analog) + nat, passb = _find_nat_freq(stopb, passb, gpass, gstop, filter_type, 'cheby') + + GSTOP = 10 ** (0.1 * abs(gstop)) + GPASS = 10 ** (0.1 * abs(gpass)) + v_pass_stop = np.arccosh(np.sqrt((GSTOP - 1.0) / (GPASS - 1.0))) + ord = int(ceil(v_pass_stop / arccosh(nat))) + + # Find frequency where analog response is -gpass dB. + # Then convert back from low-pass prototype to the original filter. + + new_freq = cosh(1.0 / ord * v_pass_stop) + new_freq = 1.0 / new_freq + + if filter_type == 1: + nat = passb / new_freq + elif filter_type == 2: + nat = passb * new_freq + elif filter_type == 3: + nat = np.empty(2, float) + nat[0] = (new_freq / 2.0 * (passb[0] - passb[1]) + + sqrt(new_freq ** 2 * (passb[1] - passb[0]) ** 2 / 4.0 + + passb[1] * passb[0])) + nat[1] = passb[1] * passb[0] / nat[0] + elif filter_type == 4: + nat = np.empty(2, float) + nat[0] = (1.0 / (2.0 * new_freq) * (passb[0] - passb[1]) + + sqrt((passb[1] - passb[0]) ** 2 / (4.0 * new_freq ** 2) + + passb[1] * passb[0])) + nat[1] = passb[0] * passb[1] / nat[0] + + wn = _postprocess_wn(nat, analog, fs) + + return ord, wn + + +_POW10_LOG10 = np.log(10) + + +def _pow10m1(x): + """10 ** x - 1 for x near 0""" + return np.expm1(_POW10_LOG10 * x) + + +def ellipord(wp, ws, gpass, gstop, analog=False, fs=None): + """Elliptic (Cauer) filter order selection. + + Return the order of the lowest order digital or analog elliptic filter + that loses no more than `gpass` dB in the passband and has at least + `gstop` dB attenuation in the stopband. + + Parameters + ---------- + wp, ws : float + Passband and stopband edge frequencies. + + For digital filters, these are in the same units as `fs`. By default, + `fs` is 2 half-cycles/sample, so these are normalized from 0 to 1, + where 1 is the Nyquist frequency. (`wp` and `ws` are thus in + half-cycles / sample.) For example: + + - Lowpass: wp = 0.2, ws = 0.3 + - Highpass: wp = 0.3, ws = 0.2 + - Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6] + - Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5] + + For analog filters, `wp` and `ws` are angular frequencies (e.g., rad/s). + gpass : float + The maximum loss in the passband (dB). + gstop : float + The minimum attenuation in the stopband (dB). + analog : bool, optional + When True, return an analog filter, otherwise a digital filter is + returned. + fs : float, optional + The sampling frequency of the digital system. + + .. versionadded:: 1.2.0 + + Returns + ------- + ord : int + The lowest order for an Elliptic (Cauer) filter that meets specs. + wn : ndarray or float + The Chebyshev natural frequency (the "3dB frequency") for use with + `ellip` to give filter results. If `fs` is specified, + this is in the same units, and `fs` must also be passed to `ellip`. + + See Also + -------- + ellip : Filter design using order and critical points + buttord : Find order and critical points from passband and stopband spec + cheb1ord, cheb2ord + iirfilter : General filter design using order and critical frequencies + iirdesign : General filter design using passband and stopband spec + + Examples + -------- + Design an analog highpass filter such that the passband is within 3 dB + above 30 rad/s, while rejecting -60 dB at 10 rad/s. Plot its + frequency response, showing the passband and stopband constraints in gray. + + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> import numpy as np + + >>> N, Wn = signal.ellipord(30, 10, 3, 60, True) + >>> b, a = signal.ellip(N, 3, 60, Wn, 'high', True) + >>> w, h = signal.freqs(b, a, np.logspace(0, 3, 500)) + >>> plt.semilogx(w, 20 * np.log10(abs(h))) + >>> plt.title('Elliptical highpass filter fit to constraints') + >>> plt.xlabel('Frequency [rad/s]') + >>> plt.ylabel('Amplitude [dB]') + >>> plt.grid(which='both', axis='both') + >>> plt.fill([.1, 10, 10, .1], [1e4, 1e4, -60, -60], '0.9', lw=0) # stop + >>> plt.fill([30, 30, 1e9, 1e9], [-99, -3, -3, -99], '0.9', lw=0) # pass + >>> plt.axis([1, 300, -80, 3]) + >>> plt.show() + + """ + fs = _validate_fs(fs, allow_none=True) + _validate_gpass_gstop(gpass, gstop) + wp, ws, filter_type = _validate_wp_ws(wp, ws, fs, analog) + passb, stopb = _pre_warp(wp, ws, analog) + nat, passb = _find_nat_freq(stopb, passb, gpass, gstop, filter_type, 'ellip') + + arg1_sq = _pow10m1(0.1 * gpass) / _pow10m1(0.1 * gstop) + arg0 = 1.0 / nat + d0 = special.ellipk(arg0 ** 2), special.ellipkm1(arg0 ** 2) + d1 = special.ellipk(arg1_sq), special.ellipkm1(arg1_sq) + ord = int(ceil(d0[0] * d1[1] / (d0[1] * d1[0]))) + + wn = _postprocess_wn(passb, analog, fs) + + return ord, wn + + +def buttap(N): + """Return (z,p,k) for analog prototype of Nth-order Butterworth filter. + + The filter will have an angular (e.g., rad/s) cutoff frequency of 1. + + See Also + -------- + butter : Filter design function using this prototype + + """ + if abs(int(N)) != N: + raise ValueError("Filter order must be a nonnegative integer") + z = np.array([]) + m = np.arange(-N+1, N, 2) + # Middle value is 0 to ensure an exactly real pole + p = -np.exp(1j * pi * m / (2 * N)) + k = 1 + return z, p, k + + +def cheb1ap(N, rp): + """ + Return (z,p,k) for Nth-order Chebyshev type I analog lowpass filter. + + The returned filter prototype has `rp` decibels of ripple in the passband. + + The filter's angular (e.g. rad/s) cutoff frequency is normalized to 1, + defined as the point at which the gain first drops below ``-rp``. + + See Also + -------- + cheby1 : Filter design function using this prototype + + """ + if abs(int(N)) != N: + raise ValueError("Filter order must be a nonnegative integer") + elif N == 0: + # Avoid divide-by-zero error + # Even order filters have DC gain of -rp dB + return np.array([]), np.array([]), 10**(-rp/20) + z = np.array([]) + + # Ripple factor (epsilon) + eps = np.sqrt(10 ** (0.1 * rp) - 1.0) + mu = 1.0 / N * arcsinh(1 / eps) + + # Arrange poles in an ellipse on the left half of the S-plane + m = np.arange(-N+1, N, 2) + theta = pi * m / (2*N) + p = -sinh(mu + 1j*theta) + + k = np.prod(-p, axis=0).real + if N % 2 == 0: + k = k / sqrt(1 + eps * eps) + + return z, p, k + + +def cheb2ap(N, rs): + """ + Return (z,p,k) for Nth-order Chebyshev type II analog lowpass filter. + + The returned filter prototype has attenuation of at least ``rs`` decibels + in the stopband. + + The filter's angular (e.g. rad/s) cutoff frequency is normalized to 1, + defined as the point at which the attenuation first reaches ``rs``. + + See Also + -------- + cheby2 : Filter design function using this prototype + + """ + if abs(int(N)) != N: + raise ValueError("Filter order must be a nonnegative integer") + elif N == 0: + # Avoid divide-by-zero warning + return np.array([]), np.array([]), 1 + + # Ripple factor (epsilon) + de = 1.0 / sqrt(10 ** (0.1 * rs) - 1) + mu = arcsinh(1.0 / de) / N + + if N % 2: + m = np.concatenate((np.arange(-N+1, 0, 2), np.arange(2, N, 2))) + else: + m = np.arange(-N+1, N, 2) + + z = -conjugate(1j / sin(m * pi / (2.0 * N))) + + # Poles around the unit circle like Butterworth + p = -exp(1j * pi * np.arange(-N+1, N, 2) / (2 * N)) + # Warp into Chebyshev II + p = sinh(mu) * p.real + 1j * cosh(mu) * p.imag + p = 1.0 / p + + k = (np.prod(-p, axis=0) / np.prod(-z, axis=0)).real + return z, p, k + + +EPSILON = 2e-16 + +# number of terms in solving degree equation +_ELLIPDEG_MMAX = 7 + + +def _ellipdeg(n, m1): + """Solve degree equation using nomes + + Given n, m1, solve + n * K(m) / K'(m) = K1(m1) / K1'(m1) + for m + + See [1], Eq. (49) + + References + ---------- + .. [1] Orfanidis, "Lecture Notes on Elliptic Filter Design", + https://www.ece.rutgers.edu/~orfanidi/ece521/notes.pdf + """ + K1 = special.ellipk(m1) + K1p = special.ellipkm1(m1) + + q1 = np.exp(-np.pi * K1p / K1) + q = q1 ** (1/n) + + mnum = np.arange(_ELLIPDEG_MMAX + 1) + mden = np.arange(1, _ELLIPDEG_MMAX + 2) + + num = np.sum(q ** (mnum * (mnum+1))) + den = 1 + 2 * np.sum(q ** (mden**2)) + + return 16 * q * (num / den) ** 4 + + +# Maximum number of iterations in Landen transformation recursion +# sequence. 10 is conservative; unit tests pass with 4, Orfanidis +# (see _arc_jac_cn [1]) suggests 5. +_ARC_JAC_SN_MAXITER = 10 + + +def _arc_jac_sn(w, m): + """Inverse Jacobian elliptic sn + + Solve for z in w = sn(z, m) + + Parameters + ---------- + w : complex scalar + argument + + m : scalar + modulus; in interval [0, 1] + + + See [1], Eq. (56) + + References + ---------- + .. [1] Orfanidis, "Lecture Notes on Elliptic Filter Design", + https://www.ece.rutgers.edu/~orfanidi/ece521/notes.pdf + + """ + + def _complement(kx): + # (1-k**2) ** 0.5; the expression below + # works for small kx + return ((1 - kx) * (1 + kx)) ** 0.5 + + k = m ** 0.5 + + if k > 1: + return np.nan + elif k == 1: + return np.arctanh(w) + + ks = [k] + niter = 0 + while ks[-1] != 0: + k_ = ks[-1] + k_p = _complement(k_) + ks.append((1 - k_p) / (1 + k_p)) + niter += 1 + if niter > _ARC_JAC_SN_MAXITER: + raise ValueError('Landen transformation not converging') + + K = np.prod(1 + np.array(ks[1:])) * np.pi/2 + + wns = [w] + + for kn, knext in zip(ks[:-1], ks[1:]): + wn = wns[-1] + wnext = (2 * wn / + ((1 + knext) * (1 + _complement(kn * wn)))) + wns.append(wnext) + + u = 2 / np.pi * np.arcsin(wns[-1]) + + z = K * u + return z + + +def _arc_jac_sc1(w, m): + """Real inverse Jacobian sc, with complementary modulus + + Solve for z in w = sc(z, 1-m) + + w - real scalar + + m - modulus + + From [1], sc(z, m) = -i * sn(i * z, 1 - m) + + References + ---------- + # noqa: E501 + .. [1] https://functions.wolfram.com/EllipticFunctions/JacobiSC/introductions/JacobiPQs/ShowAll.html, + "Representations through other Jacobi functions" + + """ + + zcomplex = _arc_jac_sn(1j * w, m) + if abs(zcomplex.real) > 1e-14: + raise ValueError + + return zcomplex.imag + + +def ellipap(N, rp, rs): + """Return (z,p,k) of Nth-order elliptic analog lowpass filter. + + The filter is a normalized prototype that has `rp` decibels of ripple + in the passband and a stopband `rs` decibels down. + + The filter's angular (e.g., rad/s) cutoff frequency is normalized to 1, + defined as the point at which the gain first drops below ``-rp``. + + See Also + -------- + ellip : Filter design function using this prototype + + References + ---------- + .. [1] Lutovac, Tosic, and Evans, "Filter Design for Signal Processing", + Chapters 5 and 12. + + .. [2] Orfanidis, "Lecture Notes on Elliptic Filter Design", + https://www.ece.rutgers.edu/~orfanidi/ece521/notes.pdf + + """ + if abs(int(N)) != N: + raise ValueError("Filter order must be a nonnegative integer") + elif N == 0: + # Avoid divide-by-zero warning + # Even order filters have DC gain of -rp dB + return np.array([]), np.array([]), 10**(-rp/20) + elif N == 1: + p = -sqrt(1.0 / _pow10m1(0.1 * rp)) + k = -p + z = [] + return asarray(z), asarray(p), k + + eps_sq = _pow10m1(0.1 * rp) + + eps = np.sqrt(eps_sq) + ck1_sq = eps_sq / _pow10m1(0.1 * rs) + if ck1_sq == 0: + raise ValueError("Cannot design a filter with given rp and rs" + " specifications.") + + val = special.ellipk(ck1_sq), special.ellipkm1(ck1_sq) + + m = _ellipdeg(N, ck1_sq) + + capk = special.ellipk(m) + + j = np.arange(1 - N % 2, N, 2) + jj = len(j) + + [s, c, d, phi] = special.ellipj(j * capk / N, m * np.ones(jj)) + snew = np.compress(abs(s) > EPSILON, s, axis=-1) + z = 1.0 / (sqrt(m) * snew) + z = 1j * z + z = np.concatenate((z, conjugate(z))) + + r = _arc_jac_sc1(1. / eps, ck1_sq) + v0 = capk * r / (N * val[0]) + + [sv, cv, dv, phi] = special.ellipj(v0, 1 - m) + p = -(c * d * sv * cv + 1j * s * dv) / (1 - (d * sv) ** 2.0) + + if N % 2: + newp = np.compress( + abs(p.imag) > EPSILON * np.sqrt(np.sum(p * np.conjugate(p), axis=0).real), + p, axis=-1 + ) + p = np.concatenate((p, conjugate(newp))) + else: + p = np.concatenate((p, conjugate(p))) + + k = (np.prod(-p, axis=0) / np.prod(-z, axis=0)).real + if N % 2 == 0: + k = k / np.sqrt(1 + eps_sq) + + return z, p, k + + +# TODO: Make this a real public function scipy.misc.ff +def _falling_factorial(x, n): + r""" + Return the factorial of `x` to the `n` falling. + + This is defined as: + + .. math:: x^\underline n = (x)_n = x (x-1) \cdots (x-n+1) + + This can more efficiently calculate ratios of factorials, since: + + n!/m! == falling_factorial(n, n-m) + + where n >= m + + skipping the factors that cancel out + + the usual factorial n! == ff(n, n) + """ + val = 1 + for k in range(x - n + 1, x + 1): + val *= k + return val + + +def _bessel_poly(n, reverse=False): + """ + Return the coefficients of Bessel polynomial of degree `n` + + If `reverse` is true, a reverse Bessel polynomial is output. + + Output is a list of coefficients: + [1] = 1 + [1, 1] = 1*s + 1 + [1, 3, 3] = 1*s^2 + 3*s + 3 + [1, 6, 15, 15] = 1*s^3 + 6*s^2 + 15*s + 15 + [1, 10, 45, 105, 105] = 1*s^4 + 10*s^3 + 45*s^2 + 105*s + 105 + etc. + + Output is a Python list of arbitrary precision long ints, so n is only + limited by your hardware's memory. + + Sequence is http://oeis.org/A001498, and output can be confirmed to + match http://oeis.org/A001498/b001498.txt : + + >>> from scipy.signal._filter_design import _bessel_poly + >>> i = 0 + >>> for n in range(51): + ... for x in _bessel_poly(n, reverse=True): + ... print(i, x) + ... i += 1 + + """ + if abs(int(n)) != n: + raise ValueError("Polynomial order must be a nonnegative integer") + else: + n = int(n) # np.int32 doesn't work, for instance + + out = [] + for k in range(n + 1): + num = _falling_factorial(2*n - k, n) + den = 2**(n - k) * math.factorial(k) + out.append(num // den) + + if reverse: + return out[::-1] + else: + return out + + +def _campos_zeros(n): + """ + Return approximate zero locations of Bessel polynomials y_n(x) for order + `n` using polynomial fit (Campos-Calderon 2011) + """ + if n == 1: + return asarray([-1+0j]) + + s = npp_polyval(n, [0, 0, 2, 0, -3, 1]) + b3 = npp_polyval(n, [16, -8]) / s + b2 = npp_polyval(n, [-24, -12, 12]) / s + b1 = npp_polyval(n, [8, 24, -12, -2]) / s + b0 = npp_polyval(n, [0, -6, 0, 5, -1]) / s + + r = npp_polyval(n, [0, 0, 2, 1]) + a1 = npp_polyval(n, [-6, -6]) / r + a2 = 6 / r + + k = np.arange(1, n+1) + x = npp_polyval(k, [0, a1, a2]) + y = npp_polyval(k, [b0, b1, b2, b3]) + + return x + 1j*y + + +def _aberth(f, fp, x0, tol=1e-15, maxiter=50): + """ + Given a function `f`, its first derivative `fp`, and a set of initial + guesses `x0`, simultaneously find the roots of the polynomial using the + Aberth-Ehrlich method. + + ``len(x0)`` should equal the number of roots of `f`. + + (This is not a complete implementation of Bini's algorithm.) + """ + + N = len(x0) + + x = array(x0, complex) + beta = np.empty_like(x0) + + for iteration in range(maxiter): + alpha = -f(x) / fp(x) # Newton's method + + # Model "repulsion" between zeros + for k in range(N): + beta[k] = np.sum(1/(x[k] - x[k+1:])) + beta[k] += np.sum(1/(x[k] - x[:k])) + + x += alpha / (1 + alpha * beta) + + if not all(np.isfinite(x)): + raise RuntimeError('Root-finding calculation failed') + + # Mekwi: The iterative process can be stopped when |hn| has become + # less than the largest error one is willing to permit in the root. + if all(abs(alpha) <= tol): + break + else: + raise Exception('Zeros failed to converge') + + return x + + +def _bessel_zeros(N): + """ + Find zeros of ordinary Bessel polynomial of order `N`, by root-finding of + modified Bessel function of the second kind + """ + if N == 0: + return asarray([]) + + # Generate starting points + x0 = _campos_zeros(N) + + # Zeros are the same for exp(1/x)*K_{N+0.5}(1/x) and Nth-order ordinary + # Bessel polynomial y_N(x) + def f(x): + return special.kve(N+0.5, 1/x) + + # First derivative of above + def fp(x): + return (special.kve(N-0.5, 1/x)/(2*x**2) - + special.kve(N+0.5, 1/x)/(x**2) + + special.kve(N+1.5, 1/x)/(2*x**2)) + + # Starting points converge to true zeros + x = _aberth(f, fp, x0) + + # Improve precision using Newton's method on each + for i in range(len(x)): + x[i] = optimize.newton(f, x[i], fp, tol=1e-15) + + # Average complex conjugates to make them exactly symmetrical + x = np.mean((x, x[::-1].conj()), 0) + + # Zeros should sum to -1 + if abs(np.sum(x) + 1) > 1e-15: + raise RuntimeError('Generated zeros are inaccurate') + + return x + + +def _norm_factor(p, k): + """ + Numerically find frequency shift to apply to delay-normalized filter such + that -3 dB point is at 1 rad/sec. + + `p` is an array_like of polynomial poles + `k` is a float gain + + First 10 values are listed in "Bessel Scale Factors" table, + "Bessel Filters Polynomials, Poles and Circuit Elements 2003, C. Bond." + """ + p = asarray(p, dtype=complex) + + def G(w): + """ + Gain of filter + """ + return abs(k / prod(1j*w - p)) + + def cutoff(w): + """ + When gain = -3 dB, return 0 + """ + return G(w) - 1/np.sqrt(2) + + return optimize.newton(cutoff, 1.5) + + +def besselap(N, norm='phase'): + """ + Return (z,p,k) for analog prototype of an Nth-order Bessel filter. + + Parameters + ---------- + N : int + The order of the filter. + norm : {'phase', 'delay', 'mag'}, optional + Frequency normalization: + + ``phase`` + The filter is normalized such that the phase response reaches its + midpoint at an angular (e.g., rad/s) cutoff frequency of 1. This + happens for both low-pass and high-pass filters, so this is the + "phase-matched" case. [6]_ + + The magnitude response asymptotes are the same as a Butterworth + filter of the same order with a cutoff of `Wn`. + + This is the default, and matches MATLAB's implementation. + + ``delay`` + The filter is normalized such that the group delay in the passband + is 1 (e.g., 1 second). This is the "natural" type obtained by + solving Bessel polynomials + + ``mag`` + The filter is normalized such that the gain magnitude is -3 dB at + angular frequency 1. This is called "frequency normalization" by + Bond. [1]_ + + .. versionadded:: 0.18.0 + + Returns + ------- + z : ndarray + Zeros of the transfer function. Is always an empty array. + p : ndarray + Poles of the transfer function. + k : scalar + Gain of the transfer function. For phase-normalized, this is always 1. + + See Also + -------- + bessel : Filter design function using this prototype + + Notes + ----- + To find the pole locations, approximate starting points are generated [2]_ + for the zeros of the ordinary Bessel polynomial [3]_, then the + Aberth-Ehrlich method [4]_ [5]_ is used on the Kv(x) Bessel function to + calculate more accurate zeros, and these locations are then inverted about + the unit circle. + + References + ---------- + .. [1] C.R. Bond, "Bessel Filter Constants", + http://www.crbond.com/papers/bsf.pdf + .. [2] Campos and Calderon, "Approximate closed-form formulas for the + zeros of the Bessel Polynomials", :arXiv:`1105.0957`. + .. [3] Thomson, W.E., "Delay Networks having Maximally Flat Frequency + Characteristics", Proceedings of the Institution of Electrical + Engineers, Part III, November 1949, Vol. 96, No. 44, pp. 487-490. + .. [4] Aberth, "Iteration Methods for Finding all Zeros of a Polynomial + Simultaneously", Mathematics of Computation, Vol. 27, No. 122, + April 1973 + .. [5] Ehrlich, "A modified Newton method for polynomials", Communications + of the ACM, Vol. 10, Issue 2, pp. 107-108, Feb. 1967, + :DOI:`10.1145/363067.363115` + .. [6] Miller and Bohn, "A Bessel Filter Crossover, and Its Relation to + Others", RaneNote 147, 1998, + https://www.ranecommercial.com/legacy/note147.html + + """ + if abs(int(N)) != N: + raise ValueError("Filter order must be a nonnegative integer") + + N = int(N) # calculation below doesn't always fit in np.int64 + if N == 0: + p = [] + k = 1 + else: + # Find roots of reverse Bessel polynomial + p = 1/_bessel_zeros(N) + + a_last = _falling_factorial(2*N, N) // 2**N + + # Shift them to a different normalization if required + if norm in ('delay', 'mag'): + # Normalized for group delay of 1 + k = a_last + if norm == 'mag': + # -3 dB magnitude point is at 1 rad/sec + norm_factor = _norm_factor(p, k) + p /= norm_factor + k = norm_factor**-N * a_last + elif norm == 'phase': + # Phase-matched (1/2 max phase shift at 1 rad/sec) + # Asymptotes are same as Butterworth filter + p *= 10**(-math.log10(a_last)/N) + k = 1 + else: + raise ValueError('normalization not understood') + + return asarray([]), asarray(p, dtype=complex), float(k) + + +def iirnotch(w0, Q, fs=2.0): + """ + Design second-order IIR notch digital filter. + + A notch filter is a band-stop filter with a narrow bandwidth + (high quality factor). It rejects a narrow frequency band and + leaves the rest of the spectrum little changed. + + Parameters + ---------- + w0 : float + Frequency to remove from a signal. If `fs` is specified, this is in + the same units as `fs`. By default, it is a normalized scalar that must + satisfy ``0 < w0 < 1``, with ``w0 = 1`` corresponding to half of the + sampling frequency. + Q : float + Quality factor. Dimensionless parameter that characterizes + notch filter -3 dB bandwidth ``bw`` relative to its center + frequency, ``Q = w0/bw``. + fs : float, optional + The sampling frequency of the digital system. + + .. versionadded:: 1.2.0 + + Returns + ------- + b, a : ndarray, ndarray + Numerator (``b``) and denominator (``a``) polynomials + of the IIR filter. + + See Also + -------- + iirpeak + + Notes + ----- + .. versionadded:: 0.19.0 + + References + ---------- + .. [1] Sophocles J. Orfanidis, "Introduction To Signal Processing", + Prentice-Hall, 1996 + + Examples + -------- + Design and plot filter to remove the 60 Hz component from a + signal sampled at 200 Hz, using a quality factor Q = 30 + + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> import numpy as np + + >>> fs = 200.0 # Sample frequency (Hz) + >>> f0 = 60.0 # Frequency to be removed from signal (Hz) + >>> Q = 30.0 # Quality factor + >>> # Design notch filter + >>> b, a = signal.iirnotch(f0, Q, fs) + + >>> # Frequency response + >>> freq, h = signal.freqz(b, a, fs=fs) + >>> # Plot + >>> fig, ax = plt.subplots(2, 1, figsize=(8, 6)) + >>> ax[0].plot(freq, 20*np.log10(abs(h)), color='blue') + >>> ax[0].set_title("Frequency Response") + >>> ax[0].set_ylabel("Amplitude [dB]", color='blue') + >>> ax[0].set_xlim([0, 100]) + >>> ax[0].set_ylim([-25, 10]) + >>> ax[0].grid(True) + >>> ax[1].plot(freq, np.unwrap(np.angle(h))*180/np.pi, color='green') + >>> ax[1].set_ylabel("Phase [deg]", color='green') + >>> ax[1].set_xlabel("Frequency [Hz]") + >>> ax[1].set_xlim([0, 100]) + >>> ax[1].set_yticks([-90, -60, -30, 0, 30, 60, 90]) + >>> ax[1].set_ylim([-90, 90]) + >>> ax[1].grid(True) + >>> plt.show() + """ + + return _design_notch_peak_filter(w0, Q, "notch", fs) + + +def iirpeak(w0, Q, fs=2.0): + """ + Design second-order IIR peak (resonant) digital filter. + + A peak filter is a band-pass filter with a narrow bandwidth + (high quality factor). It rejects components outside a narrow + frequency band. + + Parameters + ---------- + w0 : float + Frequency to be retained in a signal. If `fs` is specified, this is in + the same units as `fs`. By default, it is a normalized scalar that must + satisfy ``0 < w0 < 1``, with ``w0 = 1`` corresponding to half of the + sampling frequency. + Q : float + Quality factor. Dimensionless parameter that characterizes + peak filter -3 dB bandwidth ``bw`` relative to its center + frequency, ``Q = w0/bw``. + fs : float, optional + The sampling frequency of the digital system. + + .. versionadded:: 1.2.0 + + Returns + ------- + b, a : ndarray, ndarray + Numerator (``b``) and denominator (``a``) polynomials + of the IIR filter. + + See Also + -------- + iirnotch + + Notes + ----- + .. versionadded:: 0.19.0 + + References + ---------- + .. [1] Sophocles J. Orfanidis, "Introduction To Signal Processing", + Prentice-Hall, 1996 + + Examples + -------- + Design and plot filter to remove the frequencies other than the 300 Hz + component from a signal sampled at 1000 Hz, using a quality factor Q = 30 + + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + + >>> fs = 1000.0 # Sample frequency (Hz) + >>> f0 = 300.0 # Frequency to be retained (Hz) + >>> Q = 30.0 # Quality factor + >>> # Design peak filter + >>> b, a = signal.iirpeak(f0, Q, fs) + + >>> # Frequency response + >>> freq, h = signal.freqz(b, a, fs=fs) + >>> # Plot + >>> fig, ax = plt.subplots(2, 1, figsize=(8, 6)) + >>> ax[0].plot(freq, 20*np.log10(np.maximum(abs(h), 1e-5)), color='blue') + >>> ax[0].set_title("Frequency Response") + >>> ax[0].set_ylabel("Amplitude [dB]", color='blue') + >>> ax[0].set_xlim([0, 500]) + >>> ax[0].set_ylim([-50, 10]) + >>> ax[0].grid(True) + >>> ax[1].plot(freq, np.unwrap(np.angle(h))*180/np.pi, color='green') + >>> ax[1].set_ylabel("Phase [deg]", color='green') + >>> ax[1].set_xlabel("Frequency [Hz]") + >>> ax[1].set_xlim([0, 500]) + >>> ax[1].set_yticks([-90, -60, -30, 0, 30, 60, 90]) + >>> ax[1].set_ylim([-90, 90]) + >>> ax[1].grid(True) + >>> plt.show() + """ + + return _design_notch_peak_filter(w0, Q, "peak", fs) + + +def _design_notch_peak_filter(w0, Q, ftype, fs=2.0): + """ + Design notch or peak digital filter. + + Parameters + ---------- + w0 : float + Normalized frequency to remove from a signal. If `fs` is specified, + this is in the same units as `fs`. By default, it is a normalized + scalar that must satisfy ``0 < w0 < 1``, with ``w0 = 1`` + corresponding to half of the sampling frequency. + Q : float + Quality factor. Dimensionless parameter that characterizes + notch filter -3 dB bandwidth ``bw`` relative to its center + frequency, ``Q = w0/bw``. + ftype : str + The type of IIR filter to design: + + - notch filter : ``notch`` + - peak filter : ``peak`` + fs : float, optional + The sampling frequency of the digital system. + + .. versionadded:: 1.2.0: + + Returns + ------- + b, a : ndarray, ndarray + Numerator (``b``) and denominator (``a``) polynomials + of the IIR filter. + """ + fs = _validate_fs(fs, allow_none=False) + + # Guarantee that the inputs are floats + w0 = float(w0) + Q = float(Q) + w0 = 2*w0/fs + + # Checks if w0 is within the range + if w0 > 1.0 or w0 < 0.0: + raise ValueError("w0 should be such that 0 < w0 < 1") + + # Get bandwidth + bw = w0/Q + + # Normalize inputs + bw = bw*np.pi + w0 = w0*np.pi + + if ftype not in ("notch", "peak"): + raise ValueError("Unknown ftype.") + + # Compute beta according to Eqs. 11.3.4 (p.575) and 11.3.19 (p.579) from + # reference [1]. Due to assuming a -3 dB attenuation value, i.e, assuming + # gb = 1 / np.sqrt(2), the following terms simplify to: + # (np.sqrt(1.0 - gb**2.0) / gb) = 1 + # (gb / np.sqrt(1.0 - gb**2.0)) = 1 + beta = np.tan(bw/2.0) + + # Compute gain: formula 11.3.6 (p.575) from reference [1] + gain = 1.0/(1.0+beta) + + # Compute numerator b and denominator a + # formulas 11.3.7 (p.575) and 11.3.21 (p.579) + # from reference [1] + if ftype == "notch": + b = gain*np.array([1.0, -2.0*np.cos(w0), 1.0]) + else: + b = (1.0-gain)*np.array([1.0, 0.0, -1.0]) + a = np.array([1.0, -2.0*gain*np.cos(w0), (2.0*gain-1.0)]) + + return b, a + + +def iircomb(w0, Q, ftype='notch', fs=2.0, *, pass_zero=False): + """ + Design IIR notching or peaking digital comb filter. + + A notching comb filter consists of regularly-spaced band-stop filters with + a narrow bandwidth (high quality factor). Each rejects a narrow frequency + band and leaves the rest of the spectrum little changed. + + A peaking comb filter consists of regularly-spaced band-pass filters with + a narrow bandwidth (high quality factor). Each rejects components outside + a narrow frequency band. + + Parameters + ---------- + w0 : float + The fundamental frequency of the comb filter (the spacing between its + peaks). This must evenly divide the sampling frequency. If `fs` is + specified, this is in the same units as `fs`. By default, it is + a normalized scalar that must satisfy ``0 < w0 < 1``, with + ``w0 = 1`` corresponding to half of the sampling frequency. + Q : float + Quality factor. Dimensionless parameter that characterizes + notch filter -3 dB bandwidth ``bw`` relative to its center + frequency, ``Q = w0/bw``. + ftype : {'notch', 'peak'} + The type of comb filter generated by the function. If 'notch', then + the Q factor applies to the notches. If 'peak', then the Q factor + applies to the peaks. Default is 'notch'. + fs : float, optional + The sampling frequency of the signal. Default is 2.0. + pass_zero : bool, optional + If False (default), the notches (nulls) of the filter are centered on + frequencies [0, w0, 2*w0, ...], and the peaks are centered on the + midpoints [w0/2, 3*w0/2, 5*w0/2, ...]. If True, the peaks are centered + on [0, w0, 2*w0, ...] (passing zero frequency) and vice versa. + + .. versionadded:: 1.9.0 + + Returns + ------- + b, a : ndarray, ndarray + Numerator (``b``) and denominator (``a``) polynomials + of the IIR filter. + + Raises + ------ + ValueError + If `w0` is less than or equal to 0 or greater than or equal to + ``fs/2``, if `fs` is not divisible by `w0`, if `ftype` + is not 'notch' or 'peak' + + See Also + -------- + iirnotch + iirpeak + + Notes + ----- + For implementation details, see [1]_. The TF implementation of the + comb filter is numerically stable even at higher orders due to the + use of a single repeated pole, which won't suffer from precision loss. + + References + ---------- + .. [1] Sophocles J. Orfanidis, "Introduction To Signal Processing", + Prentice-Hall, 1996, ch. 11, "Digital Filter Design" + + Examples + -------- + Design and plot notching comb filter at 20 Hz for a + signal sampled at 200 Hz, using quality factor Q = 30 + + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> import numpy as np + + >>> fs = 200.0 # Sample frequency (Hz) + >>> f0 = 20.0 # Frequency to be removed from signal (Hz) + >>> Q = 30.0 # Quality factor + >>> # Design notching comb filter + >>> b, a = signal.iircomb(f0, Q, ftype='notch', fs=fs) + + >>> # Frequency response + >>> freq, h = signal.freqz(b, a, fs=fs) + >>> response = abs(h) + >>> # To avoid divide by zero when graphing + >>> response[response == 0] = 1e-20 + >>> # Plot + >>> fig, ax = plt.subplots(2, 1, figsize=(8, 6), sharex=True) + >>> ax[0].plot(freq, 20*np.log10(abs(response)), color='blue') + >>> ax[0].set_title("Frequency Response") + >>> ax[0].set_ylabel("Amplitude [dB]", color='blue') + >>> ax[0].set_xlim([0, 100]) + >>> ax[0].set_ylim([-30, 10]) + >>> ax[0].grid(True) + >>> ax[1].plot(freq, (np.angle(h)*180/np.pi+180)%360 - 180, color='green') + >>> ax[1].set_ylabel("Phase [deg]", color='green') + >>> ax[1].set_xlabel("Frequency [Hz]") + >>> ax[1].set_xlim([0, 100]) + >>> ax[1].set_yticks([-90, -60, -30, 0, 30, 60, 90]) + >>> ax[1].set_ylim([-90, 90]) + >>> ax[1].grid(True) + >>> plt.show() + + Design and plot peaking comb filter at 250 Hz for a + signal sampled at 1000 Hz, using quality factor Q = 30 + + >>> fs = 1000.0 # Sample frequency (Hz) + >>> f0 = 250.0 # Frequency to be retained (Hz) + >>> Q = 30.0 # Quality factor + >>> # Design peaking filter + >>> b, a = signal.iircomb(f0, Q, ftype='peak', fs=fs, pass_zero=True) + + >>> # Frequency response + >>> freq, h = signal.freqz(b, a, fs=fs) + >>> response = abs(h) + >>> # To avoid divide by zero when graphing + >>> response[response == 0] = 1e-20 + >>> # Plot + >>> fig, ax = plt.subplots(2, 1, figsize=(8, 6), sharex=True) + >>> ax[0].plot(freq, 20*np.log10(np.maximum(abs(h), 1e-5)), color='blue') + >>> ax[0].set_title("Frequency Response") + >>> ax[0].set_ylabel("Amplitude [dB]", color='blue') + >>> ax[0].set_xlim([0, 500]) + >>> ax[0].set_ylim([-80, 10]) + >>> ax[0].grid(True) + >>> ax[1].plot(freq, (np.angle(h)*180/np.pi+180)%360 - 180, color='green') + >>> ax[1].set_ylabel("Phase [deg]", color='green') + >>> ax[1].set_xlabel("Frequency [Hz]") + >>> ax[1].set_xlim([0, 500]) + >>> ax[1].set_yticks([-90, -60, -30, 0, 30, 60, 90]) + >>> ax[1].set_ylim([-90, 90]) + >>> ax[1].grid(True) + >>> plt.show() + """ + + # Convert w0, Q, and fs to float + w0 = float(w0) + Q = float(Q) + fs = _validate_fs(fs, allow_none=False) + + # Check for invalid cutoff frequency or filter type + ftype = ftype.lower() + if not 0 < w0 < fs / 2: + raise ValueError(f"w0 must be between 0 and {fs / 2}" + f" (Nyquist), but given {w0}.") + if ftype not in ('notch', 'peak'): + raise ValueError('ftype must be either notch or peak.') + + # Compute the order of the filter + N = round(fs / w0) + + # Check for cutoff frequency divisibility + if abs(w0 - fs/N)/fs > 1e-14: + raise ValueError('fs must be divisible by w0.') + + # Compute frequency in radians and filter bandwidth + # Eq. 11.3.1 (p. 574) from reference [1] + w0 = (2 * np.pi * w0) / fs + w_delta = w0 / Q + + # Define base gain values depending on notch or peak filter + # Compute -3dB attenuation + # Eqs. 11.4.1 and 11.4.2 (p. 582) from reference [1] + if ftype == 'notch': + G0, G = 1, 0 + elif ftype == 'peak': + G0, G = 0, 1 + + # Compute beta according to Eq. 11.5.3 (p. 591) from reference [1]. Due to + # assuming a -3 dB attenuation value, i.e, assuming GB = 1 / np.sqrt(2), + # the following term simplifies to: + # np.sqrt((GB**2 - G0**2) / (G**2 - GB**2)) = 1 + beta = np.tan(N * w_delta / 4) + + # Compute filter coefficients + # Eq 11.5.1 (p. 590) variables a, b, c from reference [1] + ax = (1 - beta) / (1 + beta) + bx = (G0 + G * beta) / (1 + beta) + cx = (G0 - G * beta) / (1 + beta) + + # Last coefficients are negative to get peaking comb that passes zero or + # notching comb that doesn't. + negative_coef = ((ftype == 'peak' and pass_zero) or + (ftype == 'notch' and not pass_zero)) + + # Compute numerator coefficients + # Eq 11.5.1 (p. 590) or Eq 11.5.4 (p. 591) from reference [1] + # b - cz^-N or b + cz^-N + b = np.zeros(N + 1) + b[0] = bx + if negative_coef: + b[-1] = -cx + else: + b[-1] = +cx + + # Compute denominator coefficients + # Eq 11.5.1 (p. 590) or Eq 11.5.4 (p. 591) from reference [1] + # 1 - az^-N or 1 + az^-N + a = np.zeros(N + 1) + a[0] = 1 + if negative_coef: + a[-1] = -ax + else: + a[-1] = +ax + + return b, a + + +def _hz_to_erb(hz): + """ + Utility for converting from frequency (Hz) to the + Equivalent Rectangular Bandwidth (ERB) scale + ERB = frequency / EarQ + minBW + """ + EarQ = 9.26449 + minBW = 24.7 + return hz / EarQ + minBW + + +def gammatone(freq, ftype, order=None, numtaps=None, fs=None): + """ + Gammatone filter design. + + This function computes the coefficients of an FIR or IIR gammatone + digital filter [1]_. + + Parameters + ---------- + freq : float + Center frequency of the filter (expressed in the same units + as `fs`). + ftype : {'fir', 'iir'} + The type of filter the function generates. If 'fir', the function + will generate an Nth order FIR gammatone filter. If 'iir', the + function will generate an 8th order digital IIR filter, modeled as + as 4th order gammatone filter. + order : int, optional + The order of the filter. Only used when ``ftype='fir'``. + Default is 4 to model the human auditory system. Must be between + 0 and 24. + numtaps : int, optional + Length of the filter. Only used when ``ftype='fir'``. + Default is ``fs*0.015`` if `fs` is greater than 1000, + 15 if `fs` is less than or equal to 1000. + fs : float, optional + The sampling frequency of the signal. `freq` must be between + 0 and ``fs/2``. Default is 2. + + Returns + ------- + b, a : ndarray, ndarray + Numerator (``b``) and denominator (``a``) polynomials of the filter. + + Raises + ------ + ValueError + If `freq` is less than or equal to 0 or greater than or equal to + ``fs/2``, if `ftype` is not 'fir' or 'iir', if `order` is less than + or equal to 0 or greater than 24 when ``ftype='fir'`` + + See Also + -------- + firwin + iirfilter + + References + ---------- + .. [1] Slaney, Malcolm, "An Efficient Implementation of the + Patterson-Holdsworth Auditory Filter Bank", Apple Computer + Technical Report 35, 1993, pp.3-8, 34-39. + + Examples + -------- + 16-sample 4th order FIR Gammatone filter centered at 440 Hz + + >>> from scipy import signal + >>> signal.gammatone(440, 'fir', numtaps=16, fs=16000) + (array([ 0.00000000e+00, 2.22196719e-07, 1.64942101e-06, 4.99298227e-06, + 1.01993969e-05, 1.63125770e-05, 2.14648940e-05, 2.29947263e-05, + 1.76776931e-05, 2.04980537e-06, -2.72062858e-05, -7.28455299e-05, + -1.36651076e-04, -2.19066855e-04, -3.18905076e-04, -4.33156712e-04]), + [1.0]) + + IIR Gammatone filter centered at 440 Hz + + >>> import matplotlib.pyplot as plt + >>> import numpy as np + + >>> fc, fs = 440, 16000 + >>> b, a = signal.gammatone(fc, 'iir', fs=fs) + >>> w, h = signal.freqz(b, a) + >>> plt.plot(w * fs / (2 * np.pi), 20 * np.log10(abs(h))) + >>> plt.xscale('log') + >>> plt.title('Gammatone filter frequency response') + >>> plt.xlabel('Frequency [Hz]') + >>> plt.ylabel('Amplitude [dB]') + >>> plt.margins(0, 0.1) + >>> plt.grid(which='both', axis='both') + >>> plt.axvline(fc, color='green') # cutoff frequency + >>> plt.show() + """ + # Converts freq to float + freq = float(freq) + + # Set sampling rate if not passed + if fs is None: + fs = 2 + fs = _validate_fs(fs, allow_none=False) + + # Check for invalid cutoff frequency or filter type + ftype = ftype.lower() + filter_types = ['fir', 'iir'] + if not 0 < freq < fs / 2: + raise ValueError(f"The frequency must be between 0 and {fs / 2}" + f" (Nyquist), but given {freq}.") + if ftype not in filter_types: + raise ValueError('ftype must be either fir or iir.') + + # Calculate FIR gammatone filter + if ftype == 'fir': + # Set order and numtaps if not passed + if order is None: + order = 4 + order = operator.index(order) + + if numtaps is None: + numtaps = max(int(fs * 0.015), 15) + numtaps = operator.index(numtaps) + + # Check for invalid order + if not 0 < order <= 24: + raise ValueError("Invalid order: order must be > 0 and <= 24.") + + # Gammatone impulse response settings + t = np.arange(numtaps) / fs + bw = 1.019 * _hz_to_erb(freq) + + # Calculate the FIR gammatone filter + b = (t ** (order - 1)) * np.exp(-2 * np.pi * bw * t) + b *= np.cos(2 * np.pi * freq * t) + + # Scale the FIR filter so the frequency response is 1 at cutoff + scale_factor = 2 * (2 * np.pi * bw) ** (order) + scale_factor /= float_factorial(order - 1) + scale_factor /= fs + b *= scale_factor + a = [1.0] + + # Calculate IIR gammatone filter + elif ftype == 'iir': + # Raise warning if order and/or numtaps is passed + if order is not None: + warnings.warn('order is not used for IIR gammatone filter.', stacklevel=2) + if numtaps is not None: + warnings.warn('numtaps is not used for IIR gammatone filter.', stacklevel=2) + + # Gammatone impulse response settings + T = 1./fs + bw = 2 * np.pi * 1.019 * _hz_to_erb(freq) + fr = 2 * freq * np.pi * T + bwT = bw * T + + # Calculate the gain to normalize the volume at the center frequency + g1 = -2 * np.exp(2j * fr) * T + g2 = 2 * np.exp(-(bwT) + 1j * fr) * T + g3 = np.sqrt(3 + 2 ** (3 / 2)) * np.sin(fr) + g4 = np.sqrt(3 - 2 ** (3 / 2)) * np.sin(fr) + g5 = np.exp(2j * fr) + + g = g1 + g2 * (np.cos(fr) - g4) + g *= (g1 + g2 * (np.cos(fr) + g4)) + g *= (g1 + g2 * (np.cos(fr) - g3)) + g *= (g1 + g2 * (np.cos(fr) + g3)) + g /= ((-2 / np.exp(2 * bwT) - 2 * g5 + 2 * (1 + g5) / np.exp(bwT)) ** 4) + g = np.abs(g) + + # Create empty filter coefficient lists + b = np.empty(5) + a = np.empty(9) + + # Calculate the numerator coefficients + b[0] = (T ** 4) / g + b[1] = -4 * T ** 4 * np.cos(fr) / np.exp(bw * T) / g + b[2] = 6 * T ** 4 * np.cos(2 * fr) / np.exp(2 * bw * T) / g + b[3] = -4 * T ** 4 * np.cos(3 * fr) / np.exp(3 * bw * T) / g + b[4] = T ** 4 * np.cos(4 * fr) / np.exp(4 * bw * T) / g + + # Calculate the denominator coefficients + a[0] = 1 + a[1] = -8 * np.cos(fr) / np.exp(bw * T) + a[2] = 4 * (4 + 3 * np.cos(2 * fr)) / np.exp(2 * bw * T) + a[3] = -8 * (6 * np.cos(fr) + np.cos(3 * fr)) + a[3] /= np.exp(3 * bw * T) + a[4] = 2 * (18 + 16 * np.cos(2 * fr) + np.cos(4 * fr)) + a[4] /= np.exp(4 * bw * T) + a[5] = -8 * (6 * np.cos(fr) + np.cos(3 * fr)) + a[5] /= np.exp(5 * bw * T) + a[6] = 4 * (4 + 3 * np.cos(2 * fr)) / np.exp(6 * bw * T) + a[7] = -8 * np.cos(fr) / np.exp(7 * bw * T) + a[8] = np.exp(-8 * bw * T) + + return b, a + + +filter_dict = {'butter': [buttap, buttord], + 'butterworth': [buttap, buttord], + + 'cauer': [ellipap, ellipord], + 'elliptic': [ellipap, ellipord], + 'ellip': [ellipap, ellipord], + + 'bessel': [besselap], + 'bessel_phase': [besselap], + 'bessel_delay': [besselap], + 'bessel_mag': [besselap], + + 'cheby1': [cheb1ap, cheb1ord], + 'chebyshev1': [cheb1ap, cheb1ord], + 'chebyshevi': [cheb1ap, cheb1ord], + + 'cheby2': [cheb2ap, cheb2ord], + 'chebyshev2': [cheb2ap, cheb2ord], + 'chebyshevii': [cheb2ap, cheb2ord], + } + +band_dict = {'band': 'bandpass', + 'bandpass': 'bandpass', + 'pass': 'bandpass', + 'bp': 'bandpass', + + 'bs': 'bandstop', + 'bandstop': 'bandstop', + 'bands': 'bandstop', + 'stop': 'bandstop', + + 'l': 'lowpass', + 'low': 'lowpass', + 'lowpass': 'lowpass', + 'lp': 'lowpass', + + 'high': 'highpass', + 'highpass': 'highpass', + 'h': 'highpass', + 'hp': 'highpass', + } + +bessel_norms = {'bessel': 'phase', + 'bessel_phase': 'phase', + 'bessel_delay': 'delay', + 'bessel_mag': 'mag'} diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_fir_filter_design.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_fir_filter_design.py new file mode 100644 index 0000000000000000000000000000000000000000..b46d1bcc72f5fb03965b66cf131c25c2ca2f5585 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_fir_filter_design.py @@ -0,0 +1,1286 @@ +"""Functions for FIR filter design.""" + +from math import ceil, log +import operator +import warnings +from typing import Literal + +import numpy as np +from numpy.fft import irfft, fft, ifft +from scipy.special import sinc +from scipy.linalg import (toeplitz, hankel, solve, LinAlgError, LinAlgWarning, + lstsq) +from scipy.signal._arraytools import _validate_fs + +from . import _sigtools + +__all__ = ['kaiser_beta', 'kaiser_atten', 'kaiserord', + 'firwin', 'firwin2', 'remez', 'firls', 'minimum_phase'] + + +# Some notes on function parameters: +# +# `cutoff` and `width` are given as numbers between 0 and 1. These are +# relative frequencies, expressed as a fraction of the Nyquist frequency. +# For example, if the Nyquist frequency is 2 KHz, then width=0.15 is a width +# of 300 Hz. +# +# The `order` of a FIR filter is one less than the number of taps. +# This is a potential source of confusion, so in the following code, +# we will always use the number of taps as the parameterization of +# the 'size' of the filter. The "number of taps" means the number +# of coefficients, which is the same as the length of the impulse +# response of the filter. + + +def kaiser_beta(a): + """Compute the Kaiser parameter `beta`, given the attenuation `a`. + + Parameters + ---------- + a : float + The desired attenuation in the stopband and maximum ripple in + the passband, in dB. This should be a *positive* number. + + Returns + ------- + beta : float + The `beta` parameter to be used in the formula for a Kaiser window. + + References + ---------- + Oppenheim, Schafer, "Discrete-Time Signal Processing", p.475-476. + + Examples + -------- + Suppose we want to design a lowpass filter, with 65 dB attenuation + in the stop band. The Kaiser window parameter to be used in the + window method is computed by ``kaiser_beta(65)``: + + >>> from scipy.signal import kaiser_beta + >>> kaiser_beta(65) + 6.20426 + + """ + if a > 50: + beta = 0.1102 * (a - 8.7) + elif a > 21: + beta = 0.5842 * (a - 21) ** 0.4 + 0.07886 * (a - 21) + else: + beta = 0.0 + return beta + + +def kaiser_atten(numtaps, width): + """Compute the attenuation of a Kaiser FIR filter. + + Given the number of taps `N` and the transition width `width`, compute the + attenuation `a` in dB, given by Kaiser's formula: + + a = 2.285 * (N - 1) * pi * width + 7.95 + + Parameters + ---------- + numtaps : int + The number of taps in the FIR filter. + width : float + The desired width of the transition region between passband and + stopband (or, in general, at any discontinuity) for the filter, + expressed as a fraction of the Nyquist frequency. + + Returns + ------- + a : float + The attenuation of the ripple, in dB. + + See Also + -------- + kaiserord, kaiser_beta + + Examples + -------- + Suppose we want to design a FIR filter using the Kaiser window method + that will have 211 taps and a transition width of 9 Hz for a signal that + is sampled at 480 Hz. Expressed as a fraction of the Nyquist frequency, + the width is 9/(0.5*480) = 0.0375. The approximate attenuation (in dB) + is computed as follows: + + >>> from scipy.signal import kaiser_atten + >>> kaiser_atten(211, 0.0375) + 64.48099630593983 + + """ + a = 2.285 * (numtaps - 1) * np.pi * width + 7.95 + return a + + +def kaiserord(ripple, width): + """ + Determine the filter window parameters for the Kaiser window method. + + The parameters returned by this function are generally used to create + a finite impulse response filter using the window method, with either + `firwin` or `firwin2`. + + Parameters + ---------- + ripple : float + Upper bound for the deviation (in dB) of the magnitude of the + filter's frequency response from that of the desired filter (not + including frequencies in any transition intervals). That is, if w + is the frequency expressed as a fraction of the Nyquist frequency, + A(w) is the actual frequency response of the filter and D(w) is the + desired frequency response, the design requirement is that:: + + abs(A(w) - D(w))) < 10**(-ripple/20) + + for 0 <= w <= 1 and w not in a transition interval. + width : float + Width of transition region, normalized so that 1 corresponds to pi + radians / sample. That is, the frequency is expressed as a fraction + of the Nyquist frequency. + + Returns + ------- + numtaps : int + The length of the Kaiser window. + beta : float + The beta parameter for the Kaiser window. + + See Also + -------- + kaiser_beta, kaiser_atten + + Notes + ----- + There are several ways to obtain the Kaiser window: + + - ``signal.windows.kaiser(numtaps, beta, sym=True)`` + - ``signal.get_window(beta, numtaps)`` + - ``signal.get_window(('kaiser', beta), numtaps)`` + + The empirical equations discovered by Kaiser are used. + + References + ---------- + Oppenheim, Schafer, "Discrete-Time Signal Processing", pp.475-476. + + Examples + -------- + We will use the Kaiser window method to design a lowpass FIR filter + for a signal that is sampled at 1000 Hz. + + We want at least 65 dB rejection in the stop band, and in the pass + band the gain should vary no more than 0.5%. + + We want a cutoff frequency of 175 Hz, with a transition between the + pass band and the stop band of 24 Hz. That is, in the band [0, 163], + the gain varies no more than 0.5%, and in the band [187, 500], the + signal is attenuated by at least 65 dB. + + >>> import numpy as np + >>> from scipy.signal import kaiserord, firwin, freqz + >>> import matplotlib.pyplot as plt + >>> fs = 1000.0 + >>> cutoff = 175 + >>> width = 24 + + The Kaiser method accepts just a single parameter to control the pass + band ripple and the stop band rejection, so we use the more restrictive + of the two. In this case, the pass band ripple is 0.005, or 46.02 dB, + so we will use 65 dB as the design parameter. + + Use `kaiserord` to determine the length of the filter and the + parameter for the Kaiser window. + + >>> numtaps, beta = kaiserord(65, width/(0.5*fs)) + >>> numtaps + 167 + >>> beta + 6.20426 + + Use `firwin` to create the FIR filter. + + >>> taps = firwin(numtaps, cutoff, window=('kaiser', beta), + ... scale=False, fs=fs) + + Compute the frequency response of the filter. ``w`` is the array of + frequencies, and ``h`` is the corresponding complex array of frequency + responses. + + >>> w, h = freqz(taps, worN=8000) + >>> w *= 0.5*fs/np.pi # Convert w to Hz. + + Compute the deviation of the magnitude of the filter's response from + that of the ideal lowpass filter. Values in the transition region are + set to ``nan``, so they won't appear in the plot. + + >>> ideal = w < cutoff # The "ideal" frequency response. + >>> deviation = np.abs(np.abs(h) - ideal) + >>> deviation[(w > cutoff - 0.5*width) & (w < cutoff + 0.5*width)] = np.nan + + Plot the deviation. A close look at the left end of the stop band shows + that the requirement for 65 dB attenuation is violated in the first lobe + by about 0.125 dB. This is not unusual for the Kaiser window method. + + >>> plt.plot(w, 20*np.log10(np.abs(deviation))) + >>> plt.xlim(0, 0.5*fs) + >>> plt.ylim(-90, -60) + >>> plt.grid(alpha=0.25) + >>> plt.axhline(-65, color='r', ls='--', alpha=0.3) + >>> plt.xlabel('Frequency (Hz)') + >>> plt.ylabel('Deviation from ideal (dB)') + >>> plt.title('Lowpass Filter Frequency Response') + >>> plt.show() + + """ + A = abs(ripple) # in case somebody is confused as to what's meant + if A < 8: + # Formula for N is not valid in this range. + raise ValueError("Requested maximum ripple attenuation " + f"{A:f} is too small for the Kaiser formula.") + beta = kaiser_beta(A) + + # Kaiser's formula (as given in Oppenheim and Schafer) is for the filter + # order, so we have to add 1 to get the number of taps. + numtaps = (A - 7.95) / 2.285 / (np.pi * width) + 1 + + return int(ceil(numtaps)), beta + + +def firwin(numtaps, cutoff, *, width=None, window='hamming', pass_zero=True, + scale=True, fs=None): + """ + FIR filter design using the window method. + + This function computes the coefficients of a finite impulse response + filter. The filter will have linear phase; it will be Type I if + `numtaps` is odd and Type II if `numtaps` is even. + + Type II filters always have zero response at the Nyquist frequency, so a + ValueError exception is raised if firwin is called with `numtaps` even and + having a passband whose right end is at the Nyquist frequency. + + Parameters + ---------- + numtaps : int + Length of the filter (number of coefficients, i.e. the filter + order + 1). `numtaps` must be odd if a passband includes the + Nyquist frequency. + cutoff : float or 1-D array_like + Cutoff frequency of filter (expressed in the same units as `fs`) + OR an array of cutoff frequencies (that is, band edges). In the + former case, as a float, the cutoff frequency should correspond + with the half-amplitude point, where the attenuation will be -6dB. + In the latter case, the frequencies in `cutoff` should be positive + and monotonically increasing between 0 and `fs/2`. The values 0 + and `fs/2` must not be included in `cutoff`. It should be noted + that this is different than the behavior of `scipy.signal.iirdesign`, + where the cutoff is the half-power point (-3dB). + width : float or None, optional + If `width` is not None, then assume it is the approximate width + of the transition region (expressed in the same units as `fs`) + for use in Kaiser FIR filter design. In this case, the `window` + argument is ignored. + window : string or tuple of string and parameter values, optional + Desired window to use. See `scipy.signal.get_window` for a list + of windows and required parameters. + pass_zero : {True, False, 'bandpass', 'lowpass', 'highpass', 'bandstop'}, optional + If True, the gain at the frequency 0 (i.e., the "DC gain") is 1. + If False, the DC gain is 0. Can also be a string argument for the + desired filter type (equivalent to ``btype`` in IIR design functions). + + .. versionadded:: 1.3.0 + Support for string arguments. + scale : bool, optional + Set to True to scale the coefficients so that the frequency + response is exactly unity at a certain frequency. + That frequency is either: + + - 0 (DC) if the first passband starts at 0 (i.e. pass_zero + is True) + - `fs/2` (the Nyquist frequency) if the first passband ends at + `fs/2` (i.e the filter is a single band highpass filter); + center of first passband otherwise + + fs : float, optional + The sampling frequency of the signal. Each frequency in `cutoff` + must be between 0 and ``fs/2``. Default is 2. + + Returns + ------- + h : (numtaps,) ndarray + Coefficients of length `numtaps` FIR filter. + + Raises + ------ + ValueError + If any value in `cutoff` is less than or equal to 0 or greater + than or equal to ``fs/2``, if the values in `cutoff` are not strictly + monotonically increasing, or if `numtaps` is even but a passband + includes the Nyquist frequency. + + See Also + -------- + firwin2 + firls + minimum_phase + remez + + Examples + -------- + Low-pass from 0 to f: + + >>> from scipy import signal + >>> numtaps = 3 + >>> f = 0.1 + >>> signal.firwin(numtaps, f) + array([ 0.06799017, 0.86401967, 0.06799017]) + + Use a specific window function: + + >>> signal.firwin(numtaps, f, window='nuttall') + array([ 3.56607041e-04, 9.99286786e-01, 3.56607041e-04]) + + High-pass ('stop' from 0 to f): + + >>> signal.firwin(numtaps, f, pass_zero=False) + array([-0.00859313, 0.98281375, -0.00859313]) + + Band-pass: + + >>> f1, f2 = 0.1, 0.2 + >>> signal.firwin(numtaps, [f1, f2], pass_zero=False) + array([ 0.06301614, 0.88770441, 0.06301614]) + + Band-stop: + + >>> signal.firwin(numtaps, [f1, f2]) + array([-0.00801395, 1.0160279 , -0.00801395]) + + Multi-band (passbands are [0, f1], [f2, f3] and [f4, 1]): + + >>> f3, f4 = 0.3, 0.4 + >>> signal.firwin(numtaps, [f1, f2, f3, f4]) + array([-0.01376344, 1.02752689, -0.01376344]) + + Multi-band (passbands are [f1, f2] and [f3,f4]): + + >>> signal.firwin(numtaps, [f1, f2, f3, f4], pass_zero=False) + array([ 0.04890915, 0.91284326, 0.04890915]) + + """ + # The major enhancements to this function added in November 2010 were + # developed by Tom Krauss (see ticket #902). + fs = _validate_fs(fs, allow_none=True) + fs = 2 if fs is None else fs + + nyq = 0.5 * fs + + cutoff = np.atleast_1d(cutoff) / float(nyq) + + # Check for invalid input. + if cutoff.ndim > 1: + raise ValueError("The cutoff argument must be at most " + "one-dimensional.") + if cutoff.size == 0: + raise ValueError("At least one cutoff frequency must be given.") + if cutoff.min() <= 0 or cutoff.max() >= 1: + raise ValueError("Invalid cutoff frequency: frequencies must be " + "greater than 0 and less than fs/2.") + if np.any(np.diff(cutoff) <= 0): + raise ValueError("Invalid cutoff frequencies: the frequencies " + "must be strictly increasing.") + + if width is not None: + # A width was given. Find the beta parameter of the Kaiser window + # and set `window`. This overrides the value of `window` passed in. + atten = kaiser_atten(numtaps, float(width) / nyq) + beta = kaiser_beta(atten) + window = ('kaiser', beta) + + if isinstance(pass_zero, str): + if pass_zero in ('bandstop', 'lowpass'): + if pass_zero == 'lowpass': + if cutoff.size != 1: + raise ValueError('cutoff must have one element if ' + f'pass_zero=="lowpass", got {cutoff.shape}') + elif cutoff.size <= 1: + raise ValueError('cutoff must have at least two elements if ' + f'pass_zero=="bandstop", got {cutoff.shape}') + pass_zero = True + elif pass_zero in ('bandpass', 'highpass'): + if pass_zero == 'highpass': + if cutoff.size != 1: + raise ValueError('cutoff must have one element if ' + f'pass_zero=="highpass", got {cutoff.shape}') + elif cutoff.size <= 1: + raise ValueError('cutoff must have at least two elements if ' + f'pass_zero=="bandpass", got {cutoff.shape}') + pass_zero = False + else: + raise ValueError('pass_zero must be True, False, "bandpass", ' + '"lowpass", "highpass", or "bandstop", got ' + f'{pass_zero}') + pass_zero = bool(operator.index(pass_zero)) # ensure bool-like + + pass_nyquist = bool(cutoff.size & 1) ^ pass_zero + if pass_nyquist and numtaps % 2 == 0: + raise ValueError("A filter with an even number of coefficients must " + "have zero response at the Nyquist frequency.") + + # Insert 0 and/or 1 at the ends of cutoff so that the length of cutoff + # is even, and each pair in cutoff corresponds to passband. + cutoff = np.hstack(([0.0] * pass_zero, cutoff, [1.0] * pass_nyquist)) + + # `bands` is a 2-D array; each row gives the left and right edges of + # a passband. + bands = cutoff.reshape(-1, 2) + + # Build up the coefficients. + alpha = 0.5 * (numtaps - 1) + m = np.arange(0, numtaps) - alpha + h = 0 + for left, right in bands: + h += right * sinc(right * m) + h -= left * sinc(left * m) + + # Get and apply the window function. + from .windows import get_window + win = get_window(window, numtaps, fftbins=False) + h *= win + + # Now handle scaling if desired. + if scale: + # Get the first passband. + left, right = bands[0] + if left == 0: + scale_frequency = 0.0 + elif right == 1: + scale_frequency = 1.0 + else: + scale_frequency = 0.5 * (left + right) + c = np.cos(np.pi * m * scale_frequency) + s = np.sum(h * c) + h /= s + + return h + + +# Original version of firwin2 from scipy ticket #457, submitted by "tash". +# +# Rewritten by Warren Weckesser, 2010. +def firwin2(numtaps, freq, gain, *, nfreqs=None, window='hamming', + antisymmetric=False, fs=None): + """ + FIR filter design using the window method. + + From the given frequencies `freq` and corresponding gains `gain`, + this function constructs an FIR filter with linear phase and + (approximately) the given frequency response. + + Parameters + ---------- + numtaps : int + The number of taps in the FIR filter. `numtaps` must be less than + `nfreqs`. + freq : array_like, 1-D + The frequency sampling points. Typically 0.0 to 1.0 with 1.0 being + Nyquist. The Nyquist frequency is half `fs`. + The values in `freq` must be nondecreasing. A value can be repeated + once to implement a discontinuity. The first value in `freq` must + be 0, and the last value must be ``fs/2``. Values 0 and ``fs/2`` must + not be repeated. + gain : array_like + The filter gains at the frequency sampling points. Certain + constraints to gain values, depending on the filter type, are applied, + see Notes for details. + nfreqs : int, optional + The size of the interpolation mesh used to construct the filter. + For most efficient behavior, this should be a power of 2 plus 1 + (e.g, 129, 257, etc). The default is one more than the smallest + power of 2 that is not less than `numtaps`. `nfreqs` must be greater + than `numtaps`. + window : string or (string, float) or float, or None, optional + Window function to use. Default is "hamming". See + `scipy.signal.get_window` for the complete list of possible values. + If None, no window function is applied. + antisymmetric : bool, optional + Whether resulting impulse response is symmetric/antisymmetric. + See Notes for more details. + fs : float, optional + The sampling frequency of the signal. Each frequency in `cutoff` + must be between 0 and ``fs/2``. Default is 2. + + Returns + ------- + taps : ndarray + The filter coefficients of the FIR filter, as a 1-D array of length + `numtaps`. + + See Also + -------- + firls + firwin + minimum_phase + remez + + Notes + ----- + From the given set of frequencies and gains, the desired response is + constructed in the frequency domain. The inverse FFT is applied to the + desired response to create the associated convolution kernel, and the + first `numtaps` coefficients of this kernel, scaled by `window`, are + returned. + + The FIR filter will have linear phase. The type of filter is determined by + the value of 'numtaps` and `antisymmetric` flag. + There are four possible combinations: + + - odd `numtaps`, `antisymmetric` is False, type I filter is produced + - even `numtaps`, `antisymmetric` is False, type II filter is produced + - odd `numtaps`, `antisymmetric` is True, type III filter is produced + - even `numtaps`, `antisymmetric` is True, type IV filter is produced + + Magnitude response of all but type I filters are subjects to following + constraints: + + - type II -- zero at the Nyquist frequency + - type III -- zero at zero and Nyquist frequencies + - type IV -- zero at zero frequency + + .. versionadded:: 0.9.0 + + References + ---------- + .. [1] Oppenheim, A. V. and Schafer, R. W., "Discrete-Time Signal + Processing", Prentice-Hall, Englewood Cliffs, New Jersey (1989). + (See, for example, Section 7.4.) + + .. [2] Smith, Steven W., "The Scientist and Engineer's Guide to Digital + Signal Processing", Ch. 17. http://www.dspguide.com/ch17/1.htm + + Examples + -------- + A lowpass FIR filter with a response that is 1 on [0.0, 0.5], and + that decreases linearly on [0.5, 1.0] from 1 to 0: + + >>> from scipy import signal + >>> taps = signal.firwin2(150, [0.0, 0.5, 1.0], [1.0, 1.0, 0.0]) + >>> print(taps[72:78]) + [-0.02286961 -0.06362756 0.57310236 0.57310236 -0.06362756 -0.02286961] + + """ + fs = _validate_fs(fs, allow_none=True) + fs = 2 if fs is None else fs + nyq = 0.5 * fs + + if len(freq) != len(gain): + raise ValueError('freq and gain must be of same length.') + + if nfreqs is not None and numtaps >= nfreqs: + raise ValueError(('ntaps must be less than nfreqs, but firwin2 was ' + 'called with ntaps=%d and nfreqs=%s') % + (numtaps, nfreqs)) + + if freq[0] != 0 or freq[-1] != nyq: + raise ValueError('freq must start with 0 and end with fs/2.') + d = np.diff(freq) + if (d < 0).any(): + raise ValueError('The values in freq must be nondecreasing.') + d2 = d[:-1] + d[1:] + if (d2 == 0).any(): + raise ValueError('A value in freq must not occur more than twice.') + if freq[1] == 0: + raise ValueError('Value 0 must not be repeated in freq') + if freq[-2] == nyq: + raise ValueError('Value fs/2 must not be repeated in freq') + + if antisymmetric: + if numtaps % 2 == 0: + ftype = 4 + else: + ftype = 3 + else: + if numtaps % 2 == 0: + ftype = 2 + else: + ftype = 1 + + if ftype == 2 and gain[-1] != 0.0: + raise ValueError("A Type II filter must have zero gain at the " + "Nyquist frequency.") + elif ftype == 3 and (gain[0] != 0.0 or gain[-1] != 0.0): + raise ValueError("A Type III filter must have zero gain at zero " + "and Nyquist frequencies.") + elif ftype == 4 and gain[0] != 0.0: + raise ValueError("A Type IV filter must have zero gain at zero " + "frequency.") + + if nfreqs is None: + nfreqs = 1 + 2 ** int(ceil(log(numtaps, 2))) + + if (d == 0).any(): + # Tweak any repeated values in freq so that interp works. + freq = np.array(freq, copy=True) + eps = np.finfo(float).eps * nyq + for k in range(len(freq) - 1): + if freq[k] == freq[k + 1]: + freq[k] = freq[k] - eps + freq[k + 1] = freq[k + 1] + eps + # Check if freq is strictly increasing after tweak + d = np.diff(freq) + if (d <= 0).any(): + raise ValueError("freq cannot contain numbers that are too close " + "(within eps * (fs/2): " + f"{eps}) to a repeated value") + + # Linearly interpolate the desired response on a uniform mesh `x`. + x = np.linspace(0.0, nyq, nfreqs) + fx = np.interp(x, freq, gain) + + # Adjust the phases of the coefficients so that the first `ntaps` of the + # inverse FFT are the desired filter coefficients. + shift = np.exp(-(numtaps - 1) / 2. * 1.j * np.pi * x / nyq) + if ftype > 2: + shift *= 1j + + fx2 = fx * shift + + # Use irfft to compute the inverse FFT. + out_full = irfft(fx2) + + if window is not None: + # Create the window to apply to the filter coefficients. + from .windows import get_window + wind = get_window(window, numtaps, fftbins=False) + else: + wind = 1 + + # Keep only the first `numtaps` coefficients in `out`, and multiply by + # the window. + out = out_full[:numtaps] * wind + + if ftype == 3: + out[out.size // 2] = 0.0 + + return out + + +def remez(numtaps, bands, desired, *, weight=None, type='bandpass', + maxiter=25, grid_density=16, fs=None): + """ + Calculate the minimax optimal filter using the Remez exchange algorithm. + + Calculate the filter-coefficients for the finite impulse response + (FIR) filter whose transfer function minimizes the maximum error + between the desired gain and the realized gain in the specified + frequency bands using the Remez exchange algorithm. + + Parameters + ---------- + numtaps : int + The desired number of taps in the filter. The number of taps is + the number of terms in the filter, or the filter order plus one. + bands : array_like + A monotonic sequence containing the band edges. + All elements must be non-negative and less than half the sampling + frequency as given by `fs`. + desired : array_like + A sequence half the size of bands containing the desired gain + in each of the specified bands. + weight : array_like, optional + A relative weighting to give to each band region. The length of + `weight` has to be half the length of `bands`. + type : {'bandpass', 'differentiator', 'hilbert'}, optional + The type of filter: + + * 'bandpass' : flat response in bands. This is the default. + + * 'differentiator' : frequency proportional response in bands. + + * 'hilbert' : filter with odd symmetry, that is, type III + (for even order) or type IV (for odd order) + linear phase filters. + + maxiter : int, optional + Maximum number of iterations of the algorithm. Default is 25. + grid_density : int, optional + Grid density. The dense grid used in `remez` is of size + ``(numtaps + 1) * grid_density``. Default is 16. + fs : float, optional + The sampling frequency of the signal. Default is 1. + + Returns + ------- + out : ndarray + A rank-1 array containing the coefficients of the optimal + (in a minimax sense) filter. + + See Also + -------- + firls + firwin + firwin2 + minimum_phase + + References + ---------- + .. [1] J. H. McClellan and T. W. Parks, "A unified approach to the + design of optimum FIR linear phase digital filters", + IEEE Trans. Circuit Theory, vol. CT-20, pp. 697-701, 1973. + .. [2] J. H. McClellan, T. W. Parks and L. R. Rabiner, "A Computer + Program for Designing Optimum FIR Linear Phase Digital + Filters", IEEE Trans. Audio Electroacoust., vol. AU-21, + pp. 506-525, 1973. + + Examples + -------- + In these examples, `remez` is used to design low-pass, high-pass, + band-pass and band-stop filters. The parameters that define each filter + are the filter order, the band boundaries, the transition widths of the + boundaries, the desired gains in each band, and the sampling frequency. + + We'll use a sample frequency of 22050 Hz in all the examples. In each + example, the desired gain in each band is either 0 (for a stop band) + or 1 (for a pass band). + + `freqz` is used to compute the frequency response of each filter, and + the utility function ``plot_response`` defined below is used to plot + the response. + + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + + >>> fs = 22050 # Sample rate, Hz + + >>> def plot_response(w, h, title): + ... "Utility function to plot response functions" + ... fig = plt.figure() + ... ax = fig.add_subplot(111) + ... ax.plot(w, 20*np.log10(np.abs(h))) + ... ax.set_ylim(-40, 5) + ... ax.grid(True) + ... ax.set_xlabel('Frequency (Hz)') + ... ax.set_ylabel('Gain (dB)') + ... ax.set_title(title) + + The first example is a low-pass filter, with cutoff frequency 8 kHz. + The filter length is 325, and the transition width from pass to stop + is 100 Hz. + + >>> cutoff = 8000.0 # Desired cutoff frequency, Hz + >>> trans_width = 100 # Width of transition from pass to stop, Hz + >>> numtaps = 325 # Size of the FIR filter. + >>> taps = signal.remez(numtaps, [0, cutoff, cutoff + trans_width, 0.5*fs], + ... [1, 0], fs=fs) + >>> w, h = signal.freqz(taps, [1], worN=2000, fs=fs) + >>> plot_response(w, h, "Low-pass Filter") + >>> plt.show() + + This example shows a high-pass filter: + + >>> cutoff = 2000.0 # Desired cutoff frequency, Hz + >>> trans_width = 250 # Width of transition from pass to stop, Hz + >>> numtaps = 125 # Size of the FIR filter. + >>> taps = signal.remez(numtaps, [0, cutoff - trans_width, cutoff, 0.5*fs], + ... [0, 1], fs=fs) + >>> w, h = signal.freqz(taps, [1], worN=2000, fs=fs) + >>> plot_response(w, h, "High-pass Filter") + >>> plt.show() + + This example shows a band-pass filter with a pass-band from 2 kHz to + 5 kHz. The transition width is 260 Hz and the length of the filter + is 63, which is smaller than in the other examples: + + >>> band = [2000, 5000] # Desired pass band, Hz + >>> trans_width = 260 # Width of transition from pass to stop, Hz + >>> numtaps = 63 # Size of the FIR filter. + >>> edges = [0, band[0] - trans_width, band[0], band[1], + ... band[1] + trans_width, 0.5*fs] + >>> taps = signal.remez(numtaps, edges, [0, 1, 0], fs=fs) + >>> w, h = signal.freqz(taps, [1], worN=2000, fs=fs) + >>> plot_response(w, h, "Band-pass Filter") + >>> plt.show() + + The low order leads to higher ripple and less steep transitions. + + The next example shows a band-stop filter. + + >>> band = [6000, 8000] # Desired stop band, Hz + >>> trans_width = 200 # Width of transition from pass to stop, Hz + >>> numtaps = 175 # Size of the FIR filter. + >>> edges = [0, band[0] - trans_width, band[0], band[1], + ... band[1] + trans_width, 0.5*fs] + >>> taps = signal.remez(numtaps, edges, [1, 0, 1], fs=fs) + >>> w, h = signal.freqz(taps, [1], worN=2000, fs=fs) + >>> plot_response(w, h, "Band-stop Filter") + >>> plt.show() + + """ + fs = _validate_fs(fs, allow_none=True) + fs = 1.0 if fs is None else fs + + # Convert type + try: + tnum = {'bandpass': 1, 'differentiator': 2, 'hilbert': 3}[type] + except KeyError as e: + raise ValueError("Type must be 'bandpass', 'differentiator', " + "or 'hilbert'") from e + + # Convert weight + if weight is None: + weight = [1] * len(desired) + + bands = np.asarray(bands).copy() + return _sigtools._remez(numtaps, bands, desired, weight, tnum, fs, + maxiter, grid_density) + + +def firls(numtaps, bands, desired, *, weight=None, fs=None): + """ + FIR filter design using least-squares error minimization. + + Calculate the filter coefficients for the linear-phase finite + impulse response (FIR) filter which has the best approximation + to the desired frequency response described by `bands` and + `desired` in the least squares sense (i.e., the integral of the + weighted mean-squared error within the specified bands is + minimized). + + Parameters + ---------- + numtaps : int + The number of taps in the FIR filter. `numtaps` must be odd. + bands : array_like + A monotonic nondecreasing sequence containing the band edges in + Hz. All elements must be non-negative and less than or equal to + the Nyquist frequency given by `nyq`. The bands are specified as + frequency pairs, thus, if using a 1D array, its length must be + even, e.g., `np.array([0, 1, 2, 3, 4, 5])`. Alternatively, the + bands can be specified as an nx2 sized 2D array, where n is the + number of bands, e.g, `np.array([[0, 1], [2, 3], [4, 5]])`. + desired : array_like + A sequence the same size as `bands` containing the desired gain + at the start and end point of each band. + weight : array_like, optional + A relative weighting to give to each band region when solving + the least squares problem. `weight` has to be half the size of + `bands`. + fs : float, optional + The sampling frequency of the signal. Each frequency in `bands` + must be between 0 and ``fs/2`` (inclusive). Default is 2. + + Returns + ------- + coeffs : ndarray + Coefficients of the optimal (in a least squares sense) FIR filter. + + See Also + -------- + firwin + firwin2 + minimum_phase + remez + + Notes + ----- + This implementation follows the algorithm given in [1]_. + As noted there, least squares design has multiple advantages: + + 1. Optimal in a least-squares sense. + 2. Simple, non-iterative method. + 3. The general solution can obtained by solving a linear + system of equations. + 4. Allows the use of a frequency dependent weighting function. + + This function constructs a Type I linear phase FIR filter, which + contains an odd number of `coeffs` satisfying for :math:`n < numtaps`: + + .. math:: coeffs(n) = coeffs(numtaps - 1 - n) + + The odd number of coefficients and filter symmetry avoid boundary + conditions that could otherwise occur at the Nyquist and 0 frequencies + (e.g., for Type II, III, or IV variants). + + .. versionadded:: 0.18 + + References + ---------- + .. [1] Ivan Selesnick, Linear-Phase Fir Filter Design By Least Squares. + OpenStax CNX. Aug 9, 2005. + https://eeweb.engineering.nyu.edu/iselesni/EL713/firls/firls.pdf + + Examples + -------- + We want to construct a band-pass filter. Note that the behavior in the + frequency ranges between our stop bands and pass bands is unspecified, + and thus may overshoot depending on the parameters of our filter: + + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> fig, axs = plt.subplots(2) + >>> fs = 10.0 # Hz + >>> desired = (0, 0, 1, 1, 0, 0) + >>> for bi, bands in enumerate(((0, 1, 2, 3, 4, 5), (0, 1, 2, 4, 4.5, 5))): + ... fir_firls = signal.firls(73, bands, desired, fs=fs) + ... fir_remez = signal.remez(73, bands, desired[::2], fs=fs) + ... fir_firwin2 = signal.firwin2(73, bands, desired, fs=fs) + ... hs = list() + ... ax = axs[bi] + ... for fir in (fir_firls, fir_remez, fir_firwin2): + ... freq, response = signal.freqz(fir) + ... hs.append(ax.semilogy(0.5*fs*freq/np.pi, np.abs(response))[0]) + ... for band, gains in zip(zip(bands[::2], bands[1::2]), + ... zip(desired[::2], desired[1::2])): + ... ax.semilogy(band, np.maximum(gains, 1e-7), 'k--', linewidth=2) + ... if bi == 0: + ... ax.legend(hs, ('firls', 'remez', 'firwin2'), + ... loc='lower center', frameon=False) + ... else: + ... ax.set_xlabel('Frequency (Hz)') + ... ax.grid(True) + ... ax.set(title='Band-pass %d-%d Hz' % bands[2:4], ylabel='Magnitude') + ... + >>> fig.tight_layout() + >>> plt.show() + + """ + fs = _validate_fs(fs, allow_none=True) + fs = 2 if fs is None else fs + nyq = 0.5 * fs + + numtaps = int(numtaps) + if numtaps % 2 == 0 or numtaps < 1: + raise ValueError("numtaps must be odd and >= 1") + M = (numtaps-1) // 2 + + # normalize bands 0->1 and make it 2 columns + nyq = float(nyq) + if nyq <= 0: + raise ValueError(f'nyq must be positive, got {nyq} <= 0.') + bands = np.asarray(bands).flatten() / nyq + if len(bands) % 2 != 0: + raise ValueError("bands must contain frequency pairs.") + if (bands < 0).any() or (bands > 1).any(): + raise ValueError("bands must be between 0 and 1 relative to Nyquist") + bands.shape = (-1, 2) + + # check remaining params + desired = np.asarray(desired).flatten() + if bands.size != desired.size: + raise ValueError( + f"desired must have one entry per frequency, got {desired.size} " + f"gains for {bands.size} frequencies." + ) + desired.shape = (-1, 2) + if (np.diff(bands) <= 0).any() or (np.diff(bands[:, 0]) < 0).any(): + raise ValueError("bands must be monotonically nondecreasing and have " + "width > 0.") + if (bands[:-1, 1] > bands[1:, 0]).any(): + raise ValueError("bands must not overlap.") + if (desired < 0).any(): + raise ValueError("desired must be non-negative.") + if weight is None: + weight = np.ones(len(desired)) + weight = np.asarray(weight).flatten() + if len(weight) != len(desired): + raise ValueError("weight must be the same size as the number of " + f"band pairs ({len(bands)}).") + if (weight < 0).any(): + raise ValueError("weight must be non-negative.") + + # Set up the linear matrix equation to be solved, Qa = b + + # We can express Q(k,n) = 0.5 Q1(k,n) + 0.5 Q2(k,n) + # where Q1(k,n)=q(k-n) and Q2(k,n)=q(k+n), i.e. a Toeplitz plus Hankel. + + # We omit the factor of 0.5 above, instead adding it during coefficient + # calculation. + + # We also omit the 1/π from both Q and b equations, as they cancel + # during solving. + + # We have that: + # q(n) = 1/π ∫W(ω)cos(nω)dω (over 0->π) + # Using our normalization ω=πf and with a constant weight W over each + # interval f1->f2 we get: + # q(n) = W∫cos(πnf)df (0->1) = Wf sin(πnf)/πnf + # integrated over each f1->f2 pair (i.e., value at f2 - value at f1). + n = np.arange(numtaps)[:, np.newaxis, np.newaxis] + q = np.dot(np.diff(np.sinc(bands * n) * bands, axis=2)[:, :, 0], weight) + + # Now we assemble our sum of Toeplitz and Hankel + Q1 = toeplitz(q[:M+1]) + Q2 = hankel(q[:M+1], q[M:]) + Q = Q1 + Q2 + + # Now for b(n) we have that: + # b(n) = 1/π ∫ W(ω)D(ω)cos(nω)dω (over 0->π) + # Using our normalization ω=πf and with a constant weight W over each + # interval and a linear term for D(ω) we get (over each f1->f2 interval): + # b(n) = W ∫ (mf+c)cos(πnf)df + # = f(mf+c)sin(πnf)/πnf + mf**2 cos(nπf)/(πnf)**2 + # integrated over each f1->f2 pair (i.e., value at f2 - value at f1). + n = n[:M + 1] # only need this many coefficients here + # Choose m and c such that we are at the start and end weights + m = (np.diff(desired, axis=1) / np.diff(bands, axis=1)) + c = desired[:, [0]] - bands[:, [0]] * m + b = bands * (m*bands + c) * np.sinc(bands * n) + # Use L'Hospital's rule here for cos(nπf)/(πnf)**2 @ n=0 + b[0] -= m * bands * bands / 2. + b[1:] += m * np.cos(n[1:] * np.pi * bands) / (np.pi * n[1:]) ** 2 + b = np.dot(np.diff(b, axis=2)[:, :, 0], weight) + + # Now we can solve the equation + try: # try the fast way + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter('always') + a = solve(Q, b, assume_a="pos", check_finite=False) + for ww in w: + if (ww.category == LinAlgWarning and + str(ww.message).startswith('Ill-conditioned matrix')): + raise LinAlgError(str(ww.message)) + except LinAlgError: # in case Q is rank deficient + # This is faster than pinvh, even though we don't explicitly use + # the symmetry here. gelsy was faster than gelsd and gelss in + # some non-exhaustive tests. + a = lstsq(Q, b, lapack_driver='gelsy')[0] + + # make coefficients symmetric (linear phase) + coeffs = np.hstack((a[:0:-1], 2 * a[0], a[1:])) + return coeffs + + +def _dhtm(mag): + """Compute the modified 1-D discrete Hilbert transform + + Parameters + ---------- + mag : ndarray + The magnitude spectrum. Should be 1-D with an even length, and + preferably a fast length for FFT/IFFT. + """ + # Adapted based on code by Niranjan Damera-Venkata, + # Brian L. Evans and Shawn R. McCaslin (see refs for `minimum_phase`) + sig = np.zeros(len(mag)) + # Leave Nyquist and DC at 0, knowing np.abs(fftfreq(N)[midpt]) == 0.5 + midpt = len(mag) // 2 + sig[1:midpt] = 1 + sig[midpt+1:] = -1 + # eventually if we want to support complex filters, we will need a + # np.abs() on the mag inside the log, and should remove the .real + recon = ifft(mag * np.exp(fft(sig * ifft(np.log(mag))))).real + return recon + + +def minimum_phase(h: np.ndarray, + method: Literal['homomorphic', 'hilbert'] = 'homomorphic', + n_fft: int | None = None, *, half: bool = True) -> np.ndarray: + """Convert a linear-phase FIR filter to minimum phase + + Parameters + ---------- + h : array + Linear-phase FIR filter coefficients. + method : {'hilbert', 'homomorphic'} + The provided methods are: + + 'homomorphic' (default) + This method [4]_ [5]_ works best with filters with an + odd number of taps, and the resulting minimum phase filter + will have a magnitude response that approximates the square + root of the original filter's magnitude response using half + the number of taps when ``half=True`` (default), or the + original magnitude spectrum using the same number of taps + when ``half=False``. + + 'hilbert' + This method [1]_ is designed to be used with equiripple + filters (e.g., from `remez`) with unity or zero gain + regions. + + n_fft : int + The number of points to use for the FFT. Should be at least a + few times larger than the signal length (see Notes). + half : bool + If ``True``, create a filter that is half the length of the original, with a + magnitude spectrum that is the square root of the original. If ``False``, + create a filter that is the same length as the original, with a magnitude + spectrum that is designed to match the original (only supported when + ``method='homomorphic'``). + + .. versionadded:: 1.14.0 + + Returns + ------- + h_minimum : array + The minimum-phase version of the filter, with length + ``(len(h) + 1) // 2`` when ``half is True`` or ``len(h)`` otherwise. + + See Also + -------- + firwin + firwin2 + remez + + Notes + ----- + Both the Hilbert [1]_ or homomorphic [4]_ [5]_ methods require selection + of an FFT length to estimate the complex cepstrum of the filter. + + In the case of the Hilbert method, the deviation from the ideal + spectrum ``epsilon`` is related to the number of stopband zeros + ``n_stop`` and FFT length ``n_fft`` as:: + + epsilon = 2. * n_stop / n_fft + + For example, with 100 stopband zeros and a FFT length of 2048, + ``epsilon = 0.0976``. If we conservatively assume that the number of + stopband zeros is one less than the filter length, we can take the FFT + length to be the next power of 2 that satisfies ``epsilon=0.01`` as:: + + n_fft = 2 ** int(np.ceil(np.log2(2 * (len(h) - 1) / 0.01))) + + This gives reasonable results for both the Hilbert and homomorphic + methods, and gives the value used when ``n_fft=None``. + + Alternative implementations exist for creating minimum-phase filters, + including zero inversion [2]_ and spectral factorization [3]_ [4]_. + For more information, see `this DSPGuru page + `__. + + References + ---------- + .. [1] N. Damera-Venkata and B. L. Evans, "Optimal design of real and + complex minimum phase digital FIR filters," Acoustics, Speech, + and Signal Processing, 1999. Proceedings., 1999 IEEE International + Conference on, Phoenix, AZ, 1999, pp. 1145-1148 vol.3. + :doi:`10.1109/ICASSP.1999.756179` + .. [2] X. Chen and T. W. Parks, "Design of optimal minimum phase FIR + filters by direct factorization," Signal Processing, + vol. 10, no. 4, pp. 369-383, Jun. 1986. + .. [3] T. Saramaki, "Finite Impulse Response Filter Design," in + Handbook for Digital Signal Processing, chapter 4, + New York: Wiley-Interscience, 1993. + .. [4] J. S. Lim, Advanced Topics in Signal Processing. + Englewood Cliffs, N.J.: Prentice Hall, 1988. + .. [5] A. V. Oppenheim, R. W. Schafer, and J. R. Buck, + "Discrete-Time Signal Processing," 3rd edition. + Upper Saddle River, N.J.: Pearson, 2009. + + Examples + -------- + Create an optimal linear-phase low-pass filter `h` with a transition band of + [0.2, 0.3] (assuming a Nyquist frequency of 1): + + >>> import numpy as np + >>> from scipy.signal import remez, minimum_phase, freqz, group_delay + >>> import matplotlib.pyplot as plt + >>> freq = [0, 0.2, 0.3, 1.0] + >>> desired = [1, 0] + >>> h_linear = remez(151, freq, desired, fs=2) + + Convert it to minimum phase: + + >>> h_hil = minimum_phase(h_linear, method='hilbert') + >>> h_hom = minimum_phase(h_linear, method='homomorphic') + >>> h_hom_full = minimum_phase(h_linear, method='homomorphic', half=False) + + Compare the impulse and frequency response of the four filters: + + >>> fig0, ax0 = plt.subplots(figsize=(6, 3), tight_layout=True) + >>> fig1, axs = plt.subplots(3, sharex='all', figsize=(6, 6), tight_layout=True) + >>> ax0.set_title("Impulse response") + >>> ax0.set(xlabel='Samples', ylabel='Amplitude', xlim=(0, len(h_linear) - 1)) + >>> axs[0].set_title("Frequency Response") + >>> axs[0].set(xlim=(0, .65), ylabel="Magnitude / dB") + >>> axs[1].set(ylabel="Phase / rad") + >>> axs[2].set(ylabel="Group Delay / samples", ylim=(-31, 81), + ... xlabel='Normalized Frequency (Nyqist frequency: 1)') + >>> for h, lb in ((h_linear, f'Linear ({len(h_linear)})'), + ... (h_hil, f'Min-Hilbert ({len(h_hil)})'), + ... (h_hom, f'Min-Homomorphic ({len(h_hom)})'), + ... (h_hom_full, f'Min-Homom. Full ({len(h_hom_full)})')): + ... w_H, H = freqz(h, fs=2) + ... w_gd, gd = group_delay((h, 1), fs=2) + ... + ... alpha = 1.0 if lb == 'linear' else 0.5 # full opacity for 'linear' line + ... ax0.plot(h, '.-', alpha=alpha, label=lb) + ... axs[0].plot(w_H, 20 * np.log10(np.abs(H)), alpha=alpha) + ... axs[1].plot(w_H, np.unwrap(np.angle(H)), alpha=alpha, label=lb) + ... axs[2].plot(w_gd, gd, alpha=alpha) + >>> ax0.grid(True) + >>> ax0.legend(title='Filter Phase (Order)') + >>> axs[1].legend(title='Filter Phase (Order)', loc='lower right') + >>> for ax_ in axs: # shade transition band: + ... ax_.axvspan(freq[1], freq[2], color='y', alpha=.25) + ... ax_.grid(True) + >>> plt.show() + + The impulse response and group delay plot depict the 75 sample delay of the linear + phase filter `h`. The phase should also be linear in the stop band--due to the small + magnitude, numeric noise dominates there. Furthermore, the plots show that the + minimum phase filters clearly show a reduced (negative) phase slope in the pass and + transition band. The plots also illustrate that the filter with parameters + ``method='homomorphic', half=False`` has same order and magnitude response as the + linear filter `h` whereas the other minimum phase filters have only half the order + and the square root of the magnitude response. + """ + h = np.asarray(h) + if np.iscomplexobj(h): + raise ValueError('Complex filters not supported') + if h.ndim != 1 or h.size <= 2: + raise ValueError('h must be 1-D and at least 2 samples long') + n_half = len(h) // 2 + if not np.allclose(h[-n_half:][::-1], h[:n_half]): + warnings.warn('h does not appear to by symmetric, conversion may fail', + RuntimeWarning, stacklevel=2) + if not isinstance(method, str) or method not in \ + ('homomorphic', 'hilbert',): + raise ValueError(f'method must be "homomorphic" or "hilbert", got {method!r}') + if method == "hilbert" and not half: + raise ValueError("`half=False` is only supported when `method='homomorphic'`") + if n_fft is None: + n_fft = 2 ** int(np.ceil(np.log2(2 * (len(h) - 1) / 0.01))) + n_fft = int(n_fft) + if n_fft < len(h): + raise ValueError(f'n_fft must be at least len(h)=={len(h)}') + if method == 'hilbert': + w = np.arange(n_fft) * (2 * np.pi / n_fft * n_half) + H = np.real(fft(h, n_fft) * np.exp(1j * w)) + dp = max(H) - 1 + ds = 0 - min(H) + S = 4. / (np.sqrt(1+dp+ds) + np.sqrt(1-dp+ds)) ** 2 + H += ds + H *= S + H = np.sqrt(H, out=H) + H += 1e-10 # ensure that the log does not explode + h_minimum = _dhtm(H) + else: # method == 'homomorphic' + # zero-pad; calculate the DFT + h_temp = np.abs(fft(h, n_fft)) + # take 0.25*log(|H|**2) = 0.5*log(|H|) + h_temp += 1e-7 * h_temp[h_temp > 0].min() # don't let log blow up + np.log(h_temp, out=h_temp) + if half: # halving of magnitude spectrum optional + h_temp *= 0.5 + # IDFT + h_temp = ifft(h_temp).real + # multiply pointwise by the homomorphic filter + # lmin[n] = 2u[n] - d[n] + # i.e., double the positive frequencies and zero out the negative ones; + # Oppenheim+Shafer 3rd ed p991 eq13.42b and p1004 fig13.7 + win = np.zeros(n_fft) + win[0] = 1 + stop = n_fft // 2 + win[1:stop] = 2 + if n_fft % 2: + win[stop] = 1 + h_temp *= win + h_temp = ifft(np.exp(fft(h_temp))) + h_minimum = h_temp.real + n_out = (n_half + len(h) % 2) if half else len(h) + return h_minimum[:n_out] diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_lti_conversion.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_lti_conversion.py new file mode 100644 index 0000000000000000000000000000000000000000..52c6efbbfa53288934d12918566016db6c742ef1 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_lti_conversion.py @@ -0,0 +1,533 @@ +""" +ltisys -- a collection of functions to convert linear time invariant systems +from one representation to another. +""" + +import numpy as np +from numpy import (r_, eye, atleast_2d, poly, dot, + asarray, zeros, array, outer) +from scipy import linalg + +from ._filter_design import tf2zpk, zpk2tf, normalize + + +__all__ = ['tf2ss', 'abcd_normalize', 'ss2tf', 'zpk2ss', 'ss2zpk', + 'cont2discrete'] + + +def tf2ss(num, den): + r"""Transfer function to state-space representation. + + Parameters + ---------- + num, den : array_like + Sequences representing the coefficients of the numerator and + denominator polynomials, in order of descending degree. The + denominator needs to be at least as long as the numerator. + + Returns + ------- + A, B, C, D : ndarray + State space representation of the system, in controller canonical + form. + + Examples + -------- + Convert the transfer function: + + .. math:: H(s) = \frac{s^2 + 3s + 3}{s^2 + 2s + 1} + + >>> num = [1, 3, 3] + >>> den = [1, 2, 1] + + to the state-space representation: + + .. math:: + + \dot{\textbf{x}}(t) = + \begin{bmatrix} -2 & -1 \\ 1 & 0 \end{bmatrix} \textbf{x}(t) + + \begin{bmatrix} 1 \\ 0 \end{bmatrix} \textbf{u}(t) \\ + + \textbf{y}(t) = \begin{bmatrix} 1 & 2 \end{bmatrix} \textbf{x}(t) + + \begin{bmatrix} 1 \end{bmatrix} \textbf{u}(t) + + >>> from scipy.signal import tf2ss + >>> A, B, C, D = tf2ss(num, den) + >>> A + array([[-2., -1.], + [ 1., 0.]]) + >>> B + array([[ 1.], + [ 0.]]) + >>> C + array([[ 1., 2.]]) + >>> D + array([[ 1.]]) + """ + # Controller canonical state-space representation. + # if M+1 = len(num) and K+1 = len(den) then we must have M <= K + # states are found by asserting that X(s) = U(s) / D(s) + # then Y(s) = N(s) * X(s) + # + # A, B, C, and D follow quite naturally. + # + num, den = normalize(num, den) # Strips zeros, checks arrays + nn = len(num.shape) + if nn == 1: + num = asarray([num], num.dtype) + M = num.shape[1] + K = len(den) + if M > K: + msg = "Improper transfer function. `num` is longer than `den`." + raise ValueError(msg) + if M == 0 or K == 0: # Null system + return (array([], float), array([], float), array([], float), + array([], float)) + + # pad numerator to have same number of columns has denominator + num = np.hstack((np.zeros((num.shape[0], K - M), dtype=num.dtype), num)) + + if num.shape[-1] > 0: + D = atleast_2d(num[:, 0]) + + else: + # We don't assign it an empty array because this system + # is not 'null'. It just doesn't have a non-zero D + # matrix. Thus, it should have a non-zero shape so that + # it can be operated on by functions like 'ss2tf' + D = array([[0]], float) + + if K == 1: + D = D.reshape(num.shape) + + return (zeros((1, 1)), zeros((1, D.shape[1])), + zeros((D.shape[0], 1)), D) + + frow = -array([den[1:]]) + A = r_[frow, eye(K - 2, K - 1)] + B = eye(K - 1, 1) + C = num[:, 1:] - outer(num[:, 0], den[1:]) + D = D.reshape((C.shape[0], B.shape[1])) + + return A, B, C, D + + +def _none_to_empty_2d(arg): + if arg is None: + return zeros((0, 0)) + else: + return arg + + +def _atleast_2d_or_none(arg): + if arg is not None: + return atleast_2d(arg) + + +def _shape_or_none(M): + if M is not None: + return M.shape + else: + return (None,) * 2 + + +def _choice_not_none(*args): + for arg in args: + if arg is not None: + return arg + + +def _restore(M, shape): + if M.shape == (0, 0): + return zeros(shape) + else: + if M.shape != shape: + raise ValueError("The input arrays have incompatible shapes.") + return M + + +def abcd_normalize(A=None, B=None, C=None, D=None): + """Check state-space matrices and ensure they are 2-D. + + If enough information on the system is provided, that is, enough + properly-shaped arrays are passed to the function, the missing ones + are built from this information, ensuring the correct number of + rows and columns. Otherwise a ValueError is raised. + + Parameters + ---------- + A, B, C, D : array_like, optional + State-space matrices. All of them are None (missing) by default. + See `ss2tf` for format. + + Returns + ------- + A, B, C, D : array + Properly shaped state-space matrices. + + Raises + ------ + ValueError + If not enough information on the system was provided. + + """ + A, B, C, D = map(_atleast_2d_or_none, (A, B, C, D)) + + MA, NA = _shape_or_none(A) + MB, NB = _shape_or_none(B) + MC, NC = _shape_or_none(C) + MD, ND = _shape_or_none(D) + + p = _choice_not_none(MA, MB, NC) + q = _choice_not_none(NB, ND) + r = _choice_not_none(MC, MD) + if p is None or q is None or r is None: + raise ValueError("Not enough information on the system.") + + A, B, C, D = map(_none_to_empty_2d, (A, B, C, D)) + A = _restore(A, (p, p)) + B = _restore(B, (p, q)) + C = _restore(C, (r, p)) + D = _restore(D, (r, q)) + + return A, B, C, D + + +def ss2tf(A, B, C, D, input=0): + r"""State-space to transfer function. + + A, B, C, D defines a linear state-space system with `p` inputs, + `q` outputs, and `n` state variables. + + Parameters + ---------- + A : array_like + State (or system) matrix of shape ``(n, n)`` + B : array_like + Input matrix of shape ``(n, p)`` + C : array_like + Output matrix of shape ``(q, n)`` + D : array_like + Feedthrough (or feedforward) matrix of shape ``(q, p)`` + input : int, optional + For multiple-input systems, the index of the input to use. + + Returns + ------- + num : 2-D ndarray + Numerator(s) of the resulting transfer function(s). `num` has one row + for each of the system's outputs. Each row is a sequence representation + of the numerator polynomial. + den : 1-D ndarray + Denominator of the resulting transfer function(s). `den` is a sequence + representation of the denominator polynomial. + + Examples + -------- + Convert the state-space representation: + + .. math:: + + \dot{\textbf{x}}(t) = + \begin{bmatrix} -2 & -1 \\ 1 & 0 \end{bmatrix} \textbf{x}(t) + + \begin{bmatrix} 1 \\ 0 \end{bmatrix} \textbf{u}(t) \\ + + \textbf{y}(t) = \begin{bmatrix} 1 & 2 \end{bmatrix} \textbf{x}(t) + + \begin{bmatrix} 1 \end{bmatrix} \textbf{u}(t) + + >>> A = [[-2, -1], [1, 0]] + >>> B = [[1], [0]] # 2-D column vector + >>> C = [[1, 2]] # 2-D row vector + >>> D = 1 + + to the transfer function: + + .. math:: H(s) = \frac{s^2 + 3s + 3}{s^2 + 2s + 1} + + >>> from scipy.signal import ss2tf + >>> ss2tf(A, B, C, D) + (array([[1., 3., 3.]]), array([ 1., 2., 1.])) + """ + # transfer function is C (sI - A)**(-1) B + D + + # Check consistency and make them all rank-2 arrays + A, B, C, D = abcd_normalize(A, B, C, D) + + nout, nin = D.shape + if input >= nin: + raise ValueError("System does not have the input specified.") + + # make SIMO from possibly MIMO system. + B = B[:, input:input + 1] + D = D[:, input:input + 1] + + try: + den = poly(A) + except ValueError: + den = 1 + + if (B.size == 0) and (C.size == 0): + num = np.ravel(D) + if (D.size == 0) and (A.size == 0): + den = [] + return num, den + + num_states = A.shape[0] + type_test = A[:, 0] + B[:, 0] + C[0, :] + D + 0.0 + num = np.empty((nout, num_states + 1), type_test.dtype) + for k in range(nout): + Ck = atleast_2d(C[k, :]) + num[k] = poly(A - dot(B, Ck)) + (D[k] - 1) * den + + return num, den + + +def zpk2ss(z, p, k): + """Zero-pole-gain representation to state-space representation + + Parameters + ---------- + z, p : sequence + Zeros and poles. + k : float + System gain. + + Returns + ------- + A, B, C, D : ndarray + State space representation of the system, in controller canonical + form. + + """ + return tf2ss(*zpk2tf(z, p, k)) + + +def ss2zpk(A, B, C, D, input=0): + """State-space representation to zero-pole-gain representation. + + A, B, C, D defines a linear state-space system with `p` inputs, + `q` outputs, and `n` state variables. + + Parameters + ---------- + A : array_like + State (or system) matrix of shape ``(n, n)`` + B : array_like + Input matrix of shape ``(n, p)`` + C : array_like + Output matrix of shape ``(q, n)`` + D : array_like + Feedthrough (or feedforward) matrix of shape ``(q, p)`` + input : int, optional + For multiple-input systems, the index of the input to use. + + Returns + ------- + z, p : sequence + Zeros and poles. + k : float + System gain. + + """ + return tf2zpk(*ss2tf(A, B, C, D, input=input)) + + +def cont2discrete(system, dt, method="zoh", alpha=None): + """ + Transform a continuous to a discrete state-space system. + + Parameters + ---------- + system : a tuple describing the system or an instance of `lti` + The following gives the number of elements in the tuple and + the interpretation: + + * 1: (instance of `lti`) + * 2: (num, den) + * 3: (zeros, poles, gain) + * 4: (A, B, C, D) + + dt : float + The discretization time step. + method : str, optional + Which method to use: + + * gbt: generalized bilinear transformation + * bilinear: Tustin's approximation ("gbt" with alpha=0.5) + * euler: Euler (or forward differencing) method ("gbt" with alpha=0) + * backward_diff: Backwards differencing ("gbt" with alpha=1.0) + * zoh: zero-order hold (default) + * foh: first-order hold (*versionadded: 1.3.0*) + * impulse: equivalent impulse response (*versionadded: 1.3.0*) + + alpha : float within [0, 1], optional + The generalized bilinear transformation weighting parameter, which + should only be specified with method="gbt", and is ignored otherwise + + Returns + ------- + sysd : tuple containing the discrete system + Based on the input type, the output will be of the form + + * (num, den, dt) for transfer function input + * (zeros, poles, gain, dt) for zeros-poles-gain input + * (A, B, C, D, dt) for state-space system input + + Notes + ----- + By default, the routine uses a Zero-Order Hold (zoh) method to perform + the transformation. Alternatively, a generalized bilinear transformation + may be used, which includes the common Tustin's bilinear approximation, + an Euler's method technique, or a backwards differencing technique. + + The Zero-Order Hold (zoh) method is based on [1]_, the generalized bilinear + approximation is based on [2]_ and [3]_, the First-Order Hold (foh) method + is based on [4]_. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Discretization#Discretization_of_linear_state_space_models + + .. [2] http://techteach.no/publications/discretetime_signals_systems/discrete.pdf + + .. [3] G. Zhang, X. Chen, and T. Chen, Digital redesign via the generalized + bilinear transformation, Int. J. Control, vol. 82, no. 4, pp. 741-754, + 2009. + (https://www.mypolyuweb.hk/~magzhang/Research/ZCC09_IJC.pdf) + + .. [4] G. F. Franklin, J. D. Powell, and M. L. Workman, Digital control + of dynamic systems, 3rd ed. Menlo Park, Calif: Addison-Wesley, + pp. 204-206, 1998. + + Examples + -------- + We can transform a continuous state-space system to a discrete one: + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.signal import cont2discrete, lti, dlti, dstep + + Define a continuous state-space system. + + >>> A = np.array([[0, 1],[-10., -3]]) + >>> B = np.array([[0],[10.]]) + >>> C = np.array([[1., 0]]) + >>> D = np.array([[0.]]) + >>> l_system = lti(A, B, C, D) + >>> t, x = l_system.step(T=np.linspace(0, 5, 100)) + >>> fig, ax = plt.subplots() + >>> ax.plot(t, x, label='Continuous', linewidth=3) + + Transform it to a discrete state-space system using several methods. + + >>> dt = 0.1 + >>> for method in ['zoh', 'bilinear', 'euler', 'backward_diff', 'foh', 'impulse']: + ... d_system = cont2discrete((A, B, C, D), dt, method=method) + ... s, x_d = dstep(d_system) + ... ax.step(s, np.squeeze(x_d), label=method, where='post') + >>> ax.axis([t[0], t[-1], x[0], 1.4]) + >>> ax.legend(loc='best') + >>> fig.tight_layout() + >>> plt.show() + + """ + if len(system) == 1: + return system.to_discrete() + if len(system) == 2: + sysd = cont2discrete(tf2ss(system[0], system[1]), dt, method=method, + alpha=alpha) + return ss2tf(sysd[0], sysd[1], sysd[2], sysd[3]) + (dt,) + elif len(system) == 3: + sysd = cont2discrete(zpk2ss(system[0], system[1], system[2]), dt, + method=method, alpha=alpha) + return ss2zpk(sysd[0], sysd[1], sysd[2], sysd[3]) + (dt,) + elif len(system) == 4: + a, b, c, d = system + else: + raise ValueError("First argument must either be a tuple of 2 (tf), " + "3 (zpk), or 4 (ss) arrays.") + + if method == 'gbt': + if alpha is None: + raise ValueError("Alpha parameter must be specified for the " + "generalized bilinear transform (gbt) method") + elif alpha < 0 or alpha > 1: + raise ValueError("Alpha parameter must be within the interval " + "[0,1] for the gbt method") + + if method == 'gbt': + # This parameter is used repeatedly - compute once here + ima = np.eye(a.shape[0]) - alpha*dt*a + ad = linalg.solve(ima, np.eye(a.shape[0]) + (1.0-alpha)*dt*a) + bd = linalg.solve(ima, dt*b) + + # Similarly solve for the output equation matrices + cd = linalg.solve(ima.transpose(), c.transpose()) + cd = cd.transpose() + dd = d + alpha*np.dot(c, bd) + + elif method == 'bilinear' or method == 'tustin': + return cont2discrete(system, dt, method="gbt", alpha=0.5) + + elif method == 'euler' or method == 'forward_diff': + return cont2discrete(system, dt, method="gbt", alpha=0.0) + + elif method == 'backward_diff': + return cont2discrete(system, dt, method="gbt", alpha=1.0) + + elif method == 'zoh': + # Build an exponential matrix + em_upper = np.hstack((a, b)) + + # Need to stack zeros under the a and b matrices + em_lower = np.hstack((np.zeros((b.shape[1], a.shape[0])), + np.zeros((b.shape[1], b.shape[1])))) + + em = np.vstack((em_upper, em_lower)) + ms = linalg.expm(dt * em) + + # Dispose of the lower rows + ms = ms[:a.shape[0], :] + + ad = ms[:, 0:a.shape[1]] + bd = ms[:, a.shape[1]:] + + cd = c + dd = d + + elif method == 'foh': + # Size parameters for convenience + n = a.shape[0] + m = b.shape[1] + + # Build an exponential matrix similar to 'zoh' method + em_upper = linalg.block_diag(np.block([a, b]) * dt, np.eye(m)) + em_lower = zeros((m, n + 2 * m)) + em = np.block([[em_upper], [em_lower]]) + + ms = linalg.expm(em) + + # Get the three blocks from upper rows + ms11 = ms[:n, 0:n] + ms12 = ms[:n, n:n + m] + ms13 = ms[:n, n + m:] + + ad = ms11 + bd = ms12 - ms13 + ms11 @ ms13 + cd = c + dd = d + c @ ms13 + + elif method == 'impulse': + if not np.allclose(d, 0): + raise ValueError("Impulse method is only applicable " + "to strictly proper systems") + + ad = linalg.expm(a * dt) + bd = ad @ b * dt + cd = c + dd = c @ b * dt + + else: + raise ValueError(f"Unknown transformation method '{method}'") + + return ad, bd, cd, dd, dt diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_ltisys.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_ltisys.py new file mode 100644 index 0000000000000000000000000000000000000000..3992797a09a3ceee4be1f052603fcd6593ae6274 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_ltisys.py @@ -0,0 +1,3519 @@ +""" +ltisys -- a collection of classes and functions for modeling linear +time invariant systems. +""" +# +# Author: Travis Oliphant 2001 +# +# Feb 2010: Warren Weckesser +# Rewrote lsim2 and added impulse2. +# Apr 2011: Jeffrey Armstrong +# Added dlsim, dstep, dimpulse, cont2discrete +# Aug 2013: Juan Luis Cano +# Rewrote abcd_normalize. +# Jan 2015: Irvin Probst irvin DOT probst AT ensta-bretagne DOT fr +# Added pole placement +# Mar 2015: Clancy Rowley +# Rewrote lsim +# May 2015: Felix Berkenkamp +# Split lti class into subclasses +# Merged discrete systems and added dlti + +import warnings + +# np.linalg.qr fails on some tests with LinAlgError: zgeqrf returns -7 +# use scipy's qr until this is solved + +from scipy.linalg import qr as s_qr +from scipy import linalg +from scipy.interpolate import make_interp_spline +from ._filter_design import (tf2zpk, zpk2tf, normalize, freqs, freqz, freqs_zpk, + freqz_zpk) +from ._lti_conversion import (tf2ss, abcd_normalize, ss2tf, zpk2ss, ss2zpk, + cont2discrete, _atleast_2d_or_none) + +import numpy as np +from numpy import (real, atleast_1d, squeeze, asarray, zeros, + dot, transpose, ones, linspace) +import copy + +__all__ = ['lti', 'dlti', 'TransferFunction', 'ZerosPolesGain', 'StateSpace', + 'lsim', 'impulse', 'step', 'bode', + 'freqresp', 'place_poles', 'dlsim', 'dstep', 'dimpulse', + 'dfreqresp', 'dbode'] + + +class LinearTimeInvariant: + def __new__(cls, *system, **kwargs): + """Create a new object, don't allow direct instances.""" + if cls is LinearTimeInvariant: + raise NotImplementedError('The LinearTimeInvariant class is not ' + 'meant to be used directly, use `lti` ' + 'or `dlti` instead.') + return super().__new__(cls) + + def __init__(self): + """ + Initialize the `lti` baseclass. + + The heavy lifting is done by the subclasses. + """ + super().__init__() + + self.inputs = None + self.outputs = None + self._dt = None + + @property + def dt(self): + """Return the sampling time of the system, `None` for `lti` systems.""" + return self._dt + + @property + def _dt_dict(self): + if self.dt is None: + return {} + else: + return {'dt': self.dt} + + @property + def zeros(self): + """Zeros of the system.""" + return self.to_zpk().zeros + + @property + def poles(self): + """Poles of the system.""" + return self.to_zpk().poles + + def _as_ss(self): + """Convert to `StateSpace` system, without copying. + + Returns + ------- + sys: StateSpace + The `StateSpace` system. If the class is already an instance of + `StateSpace` then this instance is returned. + """ + if isinstance(self, StateSpace): + return self + else: + return self.to_ss() + + def _as_zpk(self): + """Convert to `ZerosPolesGain` system, without copying. + + Returns + ------- + sys: ZerosPolesGain + The `ZerosPolesGain` system. If the class is already an instance of + `ZerosPolesGain` then this instance is returned. + """ + if isinstance(self, ZerosPolesGain): + return self + else: + return self.to_zpk() + + def _as_tf(self): + """Convert to `TransferFunction` system, without copying. + + Returns + ------- + sys: ZerosPolesGain + The `TransferFunction` system. If the class is already an instance of + `TransferFunction` then this instance is returned. + """ + if isinstance(self, TransferFunction): + return self + else: + return self.to_tf() + + +class lti(LinearTimeInvariant): + r""" + Continuous-time linear time invariant system base class. + + Parameters + ---------- + *system : arguments + The `lti` class can be instantiated with either 2, 3 or 4 arguments. + The following gives the number of arguments and the corresponding + continuous-time subclass that is created: + + * 2: `TransferFunction`: (numerator, denominator) + * 3: `ZerosPolesGain`: (zeros, poles, gain) + * 4: `StateSpace`: (A, B, C, D) + + Each argument can be an array or a sequence. + + See Also + -------- + ZerosPolesGain, StateSpace, TransferFunction, dlti + + Notes + ----- + `lti` instances do not exist directly. Instead, `lti` creates an instance + of one of its subclasses: `StateSpace`, `TransferFunction` or + `ZerosPolesGain`. + + If (numerator, denominator) is passed in for ``*system``, coefficients for + both the numerator and denominator should be specified in descending + exponent order (e.g., ``s^2 + 3s + 5`` would be represented as ``[1, 3, + 5]``). + + Changing the value of properties that are not directly part of the current + system representation (such as the `zeros` of a `StateSpace` system) is + very inefficient and may lead to numerical inaccuracies. It is better to + convert to the specific system representation first. For example, call + ``sys = sys.to_zpk()`` before accessing/changing the zeros, poles or gain. + + Examples + -------- + >>> from scipy import signal + + >>> signal.lti(1, 2, 3, 4) + StateSpaceContinuous( + array([[1]]), + array([[2]]), + array([[3]]), + array([[4]]), + dt: None + ) + + Construct the transfer function + :math:`H(s) = \frac{5(s - 1)(s - 2)}{(s - 3)(s - 4)}`: + + >>> signal.lti([1, 2], [3, 4], 5) + ZerosPolesGainContinuous( + array([1, 2]), + array([3, 4]), + 5, + dt: None + ) + + Construct the transfer function :math:`H(s) = \frac{3s + 4}{1s + 2}`: + + >>> signal.lti([3, 4], [1, 2]) + TransferFunctionContinuous( + array([3., 4.]), + array([1., 2.]), + dt: None + ) + + """ + def __new__(cls, *system): + """Create an instance of the appropriate subclass.""" + if cls is lti: + N = len(system) + if N == 2: + return TransferFunctionContinuous.__new__( + TransferFunctionContinuous, *system) + elif N == 3: + return ZerosPolesGainContinuous.__new__( + ZerosPolesGainContinuous, *system) + elif N == 4: + return StateSpaceContinuous.__new__(StateSpaceContinuous, + *system) + else: + raise ValueError("`system` needs to be an instance of `lti` " + "or have 2, 3 or 4 arguments.") + # __new__ was called from a subclass, let it call its own functions + return super().__new__(cls) + + def __init__(self, *system): + """ + Initialize the `lti` baseclass. + + The heavy lifting is done by the subclasses. + """ + super().__init__(*system) + + def impulse(self, X0=None, T=None, N=None): + """ + Return the impulse response of a continuous-time system. + See `impulse` for details. + """ + return impulse(self, X0=X0, T=T, N=N) + + def step(self, X0=None, T=None, N=None): + """ + Return the step response of a continuous-time system. + See `step` for details. + """ + return step(self, X0=X0, T=T, N=N) + + def output(self, U, T, X0=None): + """ + Return the response of a continuous-time system to input `U`. + See `lsim` for details. + """ + return lsim(self, U, T, X0=X0) + + def bode(self, w=None, n=100): + """ + Calculate Bode magnitude and phase data of a continuous-time system. + + Returns a 3-tuple containing arrays of frequencies [rad/s], magnitude + [dB] and phase [deg]. See `bode` for details. + + Examples + -------- + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + + >>> sys = signal.TransferFunction([1], [1, 1]) + >>> w, mag, phase = sys.bode() + + >>> plt.figure() + >>> plt.semilogx(w, mag) # Bode magnitude plot + >>> plt.figure() + >>> plt.semilogx(w, phase) # Bode phase plot + >>> plt.show() + + """ + return bode(self, w=w, n=n) + + def freqresp(self, w=None, n=10000): + """ + Calculate the frequency response of a continuous-time system. + + Returns a 2-tuple containing arrays of frequencies [rad/s] and + complex magnitude. + See `freqresp` for details. + """ + return freqresp(self, w=w, n=n) + + def to_discrete(self, dt, method='zoh', alpha=None): + """Return a discretized version of the current system. + + Parameters: See `cont2discrete` for details. + + Returns + ------- + sys: instance of `dlti` + """ + raise NotImplementedError('to_discrete is not implemented for this ' + 'system class.') + + +class dlti(LinearTimeInvariant): + r""" + Discrete-time linear time invariant system base class. + + Parameters + ---------- + *system: arguments + The `dlti` class can be instantiated with either 2, 3 or 4 arguments. + The following gives the number of arguments and the corresponding + discrete-time subclass that is created: + + * 2: `TransferFunction`: (numerator, denominator) + * 3: `ZerosPolesGain`: (zeros, poles, gain) + * 4: `StateSpace`: (A, B, C, D) + + Each argument can be an array or a sequence. + dt: float, optional + Sampling time [s] of the discrete-time systems. Defaults to ``True`` + (unspecified sampling time). Must be specified as a keyword argument, + for example, ``dt=0.1``. + + See Also + -------- + ZerosPolesGain, StateSpace, TransferFunction, lti + + Notes + ----- + `dlti` instances do not exist directly. Instead, `dlti` creates an instance + of one of its subclasses: `StateSpace`, `TransferFunction` or + `ZerosPolesGain`. + + Changing the value of properties that are not directly part of the current + system representation (such as the `zeros` of a `StateSpace` system) is + very inefficient and may lead to numerical inaccuracies. It is better to + convert to the specific system representation first. For example, call + ``sys = sys.to_zpk()`` before accessing/changing the zeros, poles or gain. + + If (numerator, denominator) is passed in for ``*system``, coefficients for + both the numerator and denominator should be specified in descending + exponent order (e.g., ``z^2 + 3z + 5`` would be represented as ``[1, 3, + 5]``). + + .. versionadded:: 0.18.0 + + Examples + -------- + >>> from scipy import signal + + >>> signal.dlti(1, 2, 3, 4) + StateSpaceDiscrete( + array([[1]]), + array([[2]]), + array([[3]]), + array([[4]]), + dt: True + ) + + >>> signal.dlti(1, 2, 3, 4, dt=0.1) + StateSpaceDiscrete( + array([[1]]), + array([[2]]), + array([[3]]), + array([[4]]), + dt: 0.1 + ) + + Construct the transfer function + :math:`H(z) = \frac{5(z - 1)(z - 2)}{(z - 3)(z - 4)}` with a sampling time + of 0.1 seconds: + + >>> signal.dlti([1, 2], [3, 4], 5, dt=0.1) + ZerosPolesGainDiscrete( + array([1, 2]), + array([3, 4]), + 5, + dt: 0.1 + ) + + Construct the transfer function :math:`H(z) = \frac{3z + 4}{1z + 2}` with + a sampling time of 0.1 seconds: + + >>> signal.dlti([3, 4], [1, 2], dt=0.1) + TransferFunctionDiscrete( + array([3., 4.]), + array([1., 2.]), + dt: 0.1 + ) + + """ + def __new__(cls, *system, **kwargs): + """Create an instance of the appropriate subclass.""" + if cls is dlti: + N = len(system) + if N == 2: + return TransferFunctionDiscrete.__new__( + TransferFunctionDiscrete, *system, **kwargs) + elif N == 3: + return ZerosPolesGainDiscrete.__new__(ZerosPolesGainDiscrete, + *system, **kwargs) + elif N == 4: + return StateSpaceDiscrete.__new__(StateSpaceDiscrete, *system, + **kwargs) + else: + raise ValueError("`system` needs to be an instance of `dlti` " + "or have 2, 3 or 4 arguments.") + # __new__ was called from a subclass, let it call its own functions + return super().__new__(cls) + + def __init__(self, *system, **kwargs): + """ + Initialize the `lti` baseclass. + + The heavy lifting is done by the subclasses. + """ + dt = kwargs.pop('dt', True) + super().__init__(*system, **kwargs) + + self.dt = dt + + @property + def dt(self): + """Return the sampling time of the system.""" + return self._dt + + @dt.setter + def dt(self, dt): + self._dt = dt + + def impulse(self, x0=None, t=None, n=None): + """ + Return the impulse response of the discrete-time `dlti` system. + See `dimpulse` for details. + """ + return dimpulse(self, x0=x0, t=t, n=n) + + def step(self, x0=None, t=None, n=None): + """ + Return the step response of the discrete-time `dlti` system. + See `dstep` for details. + """ + return dstep(self, x0=x0, t=t, n=n) + + def output(self, u, t, x0=None): + """ + Return the response of the discrete-time system to input `u`. + See `dlsim` for details. + """ + return dlsim(self, u, t, x0=x0) + + def bode(self, w=None, n=100): + r""" + Calculate Bode magnitude and phase data of a discrete-time system. + + Returns a 3-tuple containing arrays of frequencies [rad/s], magnitude + [dB] and phase [deg]. See `dbode` for details. + + Examples + -------- + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + + Construct the transfer function :math:`H(z) = \frac{1}{z^2 + 2z + 3}` + with sampling time 0.5s: + + >>> sys = signal.TransferFunction([1], [1, 2, 3], dt=0.5) + + Equivalent: signal.dbode(sys) + + >>> w, mag, phase = sys.bode() + + >>> plt.figure() + >>> plt.semilogx(w, mag) # Bode magnitude plot + >>> plt.figure() + >>> plt.semilogx(w, phase) # Bode phase plot + >>> plt.show() + + """ + return dbode(self, w=w, n=n) + + def freqresp(self, w=None, n=10000, whole=False): + """ + Calculate the frequency response of a discrete-time system. + + Returns a 2-tuple containing arrays of frequencies [rad/s] and + complex magnitude. + See `dfreqresp` for details. + + """ + return dfreqresp(self, w=w, n=n, whole=whole) + + +class TransferFunction(LinearTimeInvariant): + r"""Linear Time Invariant system class in transfer function form. + + Represents the system as the continuous-time transfer function + :math:`H(s)=\sum_{i=0}^N b[N-i] s^i / \sum_{j=0}^M a[M-j] s^j` or the + discrete-time transfer function + :math:`H(z)=\sum_{i=0}^N b[N-i] z^i / \sum_{j=0}^M a[M-j] z^j`, where + :math:`b` are elements of the numerator `num`, :math:`a` are elements of + the denominator `den`, and ``N == len(b) - 1``, ``M == len(a) - 1``. + `TransferFunction` systems inherit additional + functionality from the `lti`, respectively the `dlti` classes, depending on + which system representation is used. + + Parameters + ---------- + *system: arguments + The `TransferFunction` class can be instantiated with 1 or 2 + arguments. The following gives the number of input arguments and their + interpretation: + + * 1: `lti` or `dlti` system: (`StateSpace`, `TransferFunction` or + `ZerosPolesGain`) + * 2: array_like: (numerator, denominator) + dt: float, optional + Sampling time [s] of the discrete-time systems. Defaults to `None` + (continuous-time). Must be specified as a keyword argument, for + example, ``dt=0.1``. + + See Also + -------- + ZerosPolesGain, StateSpace, lti, dlti + tf2ss, tf2zpk, tf2sos + + Notes + ----- + Changing the value of properties that are not part of the + `TransferFunction` system representation (such as the `A`, `B`, `C`, `D` + state-space matrices) is very inefficient and may lead to numerical + inaccuracies. It is better to convert to the specific system + representation first. For example, call ``sys = sys.to_ss()`` before + accessing/changing the A, B, C, D system matrices. + + If (numerator, denominator) is passed in for ``*system``, coefficients + for both the numerator and denominator should be specified in descending + exponent order (e.g. ``s^2 + 3s + 5`` or ``z^2 + 3z + 5`` would be + represented as ``[1, 3, 5]``) + + Examples + -------- + Construct the transfer function + :math:`H(s) = \frac{s^2 + 3s + 3}{s^2 + 2s + 1}`: + + >>> from scipy import signal + + >>> num = [1, 3, 3] + >>> den = [1, 2, 1] + + >>> signal.TransferFunction(num, den) + TransferFunctionContinuous( + array([1., 3., 3.]), + array([1., 2., 1.]), + dt: None + ) + + Construct the transfer function + :math:`H(z) = \frac{z^2 + 3z + 3}{z^2 + 2z + 1}` with a sampling time of + 0.1 seconds: + + >>> signal.TransferFunction(num, den, dt=0.1) + TransferFunctionDiscrete( + array([1., 3., 3.]), + array([1., 2., 1.]), + dt: 0.1 + ) + + """ + def __new__(cls, *system, **kwargs): + """Handle object conversion if input is an instance of lti.""" + if len(system) == 1 and isinstance(system[0], LinearTimeInvariant): + return system[0].to_tf() + + # Choose whether to inherit from `lti` or from `dlti` + if cls is TransferFunction: + if kwargs.get('dt') is None: + return TransferFunctionContinuous.__new__( + TransferFunctionContinuous, + *system, + **kwargs) + else: + return TransferFunctionDiscrete.__new__( + TransferFunctionDiscrete, + *system, + **kwargs) + + # No special conversion needed + return super().__new__(cls) + + def __init__(self, *system, **kwargs): + """Initialize the state space LTI system.""" + # Conversion of lti instances is handled in __new__ + if isinstance(system[0], LinearTimeInvariant): + return + + # Remove system arguments, not needed by parents anymore + super().__init__(**kwargs) + + self._num = None + self._den = None + + self.num, self.den = normalize(*system) + + def __repr__(self): + """Return representation of the system's transfer function""" + return ( + f'{self.__class__.__name__}(\n' + f'{repr(self.num)},\n' + f'{repr(self.den)},\n' + f'dt: {repr(self.dt)}\n)' + ) + + @property + def num(self): + """Numerator of the `TransferFunction` system.""" + return self._num + + @num.setter + def num(self, num): + self._num = atleast_1d(num) + + # Update dimensions + if len(self.num.shape) > 1: + self.outputs, self.inputs = self.num.shape + else: + self.outputs = 1 + self.inputs = 1 + + @property + def den(self): + """Denominator of the `TransferFunction` system.""" + return self._den + + @den.setter + def den(self, den): + self._den = atleast_1d(den) + + def _copy(self, system): + """ + Copy the parameters of another `TransferFunction` object + + Parameters + ---------- + system : `TransferFunction` + The `StateSpace` system that is to be copied + + """ + self.num = system.num + self.den = system.den + + def to_tf(self): + """ + Return a copy of the current `TransferFunction` system. + + Returns + ------- + sys : instance of `TransferFunction` + The current system (copy) + + """ + return copy.deepcopy(self) + + def to_zpk(self): + """ + Convert system representation to `ZerosPolesGain`. + + Returns + ------- + sys : instance of `ZerosPolesGain` + Zeros, poles, gain representation of the current system + + """ + return ZerosPolesGain(*tf2zpk(self.num, self.den), + **self._dt_dict) + + def to_ss(self): + """ + Convert system representation to `StateSpace`. + + Returns + ------- + sys : instance of `StateSpace` + State space model of the current system + + """ + return StateSpace(*tf2ss(self.num, self.den), + **self._dt_dict) + + @staticmethod + def _z_to_zinv(num, den): + """Change a transfer function from the variable `z` to `z**-1`. + + Parameters + ---------- + num, den: 1d array_like + Sequences representing the coefficients of the numerator and + denominator polynomials, in order of descending degree of 'z'. + That is, ``5z**2 + 3z + 2`` is presented as ``[5, 3, 2]``. + + Returns + ------- + num, den: 1d array_like + Sequences representing the coefficients of the numerator and + denominator polynomials, in order of ascending degree of 'z**-1'. + That is, ``5 + 3 z**-1 + 2 z**-2`` is presented as ``[5, 3, 2]``. + """ + diff = len(num) - len(den) + if diff > 0: + den = np.hstack((np.zeros(diff), den)) + elif diff < 0: + num = np.hstack((np.zeros(-diff), num)) + return num, den + + @staticmethod + def _zinv_to_z(num, den): + """Change a transfer function from the variable `z` to `z**-1`. + + Parameters + ---------- + num, den: 1d array_like + Sequences representing the coefficients of the numerator and + denominator polynomials, in order of ascending degree of 'z**-1'. + That is, ``5 + 3 z**-1 + 2 z**-2`` is presented as ``[5, 3, 2]``. + + Returns + ------- + num, den: 1d array_like + Sequences representing the coefficients of the numerator and + denominator polynomials, in order of descending degree of 'z'. + That is, ``5z**2 + 3z + 2`` is presented as ``[5, 3, 2]``. + """ + diff = len(num) - len(den) + if diff > 0: + den = np.hstack((den, np.zeros(diff))) + elif diff < 0: + num = np.hstack((num, np.zeros(-diff))) + return num, den + + +class TransferFunctionContinuous(TransferFunction, lti): + r""" + Continuous-time Linear Time Invariant system in transfer function form. + + Represents the system as the transfer function + :math:`H(s)=\sum_{i=0}^N b[N-i] s^i / \sum_{j=0}^M a[M-j] s^j`, where + :math:`b` are elements of the numerator `num`, :math:`a` are elements of + the denominator `den`, and ``N == len(b) - 1``, ``M == len(a) - 1``. + Continuous-time `TransferFunction` systems inherit additional + functionality from the `lti` class. + + Parameters + ---------- + *system: arguments + The `TransferFunction` class can be instantiated with 1 or 2 + arguments. The following gives the number of input arguments and their + interpretation: + + * 1: `lti` system: (`StateSpace`, `TransferFunction` or + `ZerosPolesGain`) + * 2: array_like: (numerator, denominator) + + See Also + -------- + ZerosPolesGain, StateSpace, lti + tf2ss, tf2zpk, tf2sos + + Notes + ----- + Changing the value of properties that are not part of the + `TransferFunction` system representation (such as the `A`, `B`, `C`, `D` + state-space matrices) is very inefficient and may lead to numerical + inaccuracies. It is better to convert to the specific system + representation first. For example, call ``sys = sys.to_ss()`` before + accessing/changing the A, B, C, D system matrices. + + If (numerator, denominator) is passed in for ``*system``, coefficients + for both the numerator and denominator should be specified in descending + exponent order (e.g. ``s^2 + 3s + 5`` would be represented as + ``[1, 3, 5]``) + + Examples + -------- + Construct the transfer function + :math:`H(s) = \frac{s^2 + 3s + 3}{s^2 + 2s + 1}`: + + >>> from scipy import signal + + >>> num = [1, 3, 3] + >>> den = [1, 2, 1] + + >>> signal.TransferFunction(num, den) + TransferFunctionContinuous( + array([ 1., 3., 3.]), + array([ 1., 2., 1.]), + dt: None + ) + + """ + + def to_discrete(self, dt, method='zoh', alpha=None): + """ + Returns the discretized `TransferFunction` system. + + Parameters: See `cont2discrete` for details. + + Returns + ------- + sys: instance of `dlti` and `StateSpace` + """ + return TransferFunction(*cont2discrete((self.num, self.den), + dt, + method=method, + alpha=alpha)[:-1], + dt=dt) + + +class TransferFunctionDiscrete(TransferFunction, dlti): + r""" + Discrete-time Linear Time Invariant system in transfer function form. + + Represents the system as the transfer function + :math:`H(z)=\sum_{i=0}^N b[N-i] z^i / \sum_{j=0}^M a[M-j] z^j`, where + :math:`b` are elements of the numerator `num`, :math:`a` are elements of + the denominator `den`, and ``N == len(b) - 1``, ``M == len(a) - 1``. + Discrete-time `TransferFunction` systems inherit additional functionality + from the `dlti` class. + + Parameters + ---------- + *system: arguments + The `TransferFunction` class can be instantiated with 1 or 2 + arguments. The following gives the number of input arguments and their + interpretation: + + * 1: `dlti` system: (`StateSpace`, `TransferFunction` or + `ZerosPolesGain`) + * 2: array_like: (numerator, denominator) + dt: float, optional + Sampling time [s] of the discrete-time systems. Defaults to `True` + (unspecified sampling time). Must be specified as a keyword argument, + for example, ``dt=0.1``. + + See Also + -------- + ZerosPolesGain, StateSpace, dlti + tf2ss, tf2zpk, tf2sos + + Notes + ----- + Changing the value of properties that are not part of the + `TransferFunction` system representation (such as the `A`, `B`, `C`, `D` + state-space matrices) is very inefficient and may lead to numerical + inaccuracies. + + If (numerator, denominator) is passed in for ``*system``, coefficients + for both the numerator and denominator should be specified in descending + exponent order (e.g., ``z^2 + 3z + 5`` would be represented as + ``[1, 3, 5]``). + + Examples + -------- + Construct the transfer function + :math:`H(z) = \frac{z^2 + 3z + 3}{z^2 + 2z + 1}` with a sampling time of + 0.5 seconds: + + >>> from scipy import signal + + >>> num = [1, 3, 3] + >>> den = [1, 2, 1] + + >>> signal.TransferFunction(num, den, dt=0.5) + TransferFunctionDiscrete( + array([ 1., 3., 3.]), + array([ 1., 2., 1.]), + dt: 0.5 + ) + + """ + pass + + +class ZerosPolesGain(LinearTimeInvariant): + r""" + Linear Time Invariant system class in zeros, poles, gain form. + + Represents the system as the continuous- or discrete-time transfer function + :math:`H(s)=k \prod_i (s - z[i]) / \prod_j (s - p[j])`, where :math:`k` is + the `gain`, :math:`z` are the `zeros` and :math:`p` are the `poles`. + `ZerosPolesGain` systems inherit additional functionality from the `lti`, + respectively the `dlti` classes, depending on which system representation + is used. + + Parameters + ---------- + *system : arguments + The `ZerosPolesGain` class can be instantiated with 1 or 3 + arguments. The following gives the number of input arguments and their + interpretation: + + * 1: `lti` or `dlti` system: (`StateSpace`, `TransferFunction` or + `ZerosPolesGain`) + * 3: array_like: (zeros, poles, gain) + dt: float, optional + Sampling time [s] of the discrete-time systems. Defaults to `None` + (continuous-time). Must be specified as a keyword argument, for + example, ``dt=0.1``. + + + See Also + -------- + TransferFunction, StateSpace, lti, dlti + zpk2ss, zpk2tf, zpk2sos + + Notes + ----- + Changing the value of properties that are not part of the + `ZerosPolesGain` system representation (such as the `A`, `B`, `C`, `D` + state-space matrices) is very inefficient and may lead to numerical + inaccuracies. It is better to convert to the specific system + representation first. For example, call ``sys = sys.to_ss()`` before + accessing/changing the A, B, C, D system matrices. + + Examples + -------- + Construct the transfer function + :math:`H(s) = \frac{5(s - 1)(s - 2)}{(s - 3)(s - 4)}`: + + >>> from scipy import signal + + >>> signal.ZerosPolesGain([1, 2], [3, 4], 5) + ZerosPolesGainContinuous( + array([1, 2]), + array([3, 4]), + 5, + dt: None + ) + + Construct the transfer function + :math:`H(z) = \frac{5(z - 1)(z - 2)}{(z - 3)(z - 4)}` with a sampling time + of 0.1 seconds: + + >>> signal.ZerosPolesGain([1, 2], [3, 4], 5, dt=0.1) + ZerosPolesGainDiscrete( + array([1, 2]), + array([3, 4]), + 5, + dt: 0.1 + ) + + """ + def __new__(cls, *system, **kwargs): + """Handle object conversion if input is an instance of `lti`""" + if len(system) == 1 and isinstance(system[0], LinearTimeInvariant): + return system[0].to_zpk() + + # Choose whether to inherit from `lti` or from `dlti` + if cls is ZerosPolesGain: + if kwargs.get('dt') is None: + return ZerosPolesGainContinuous.__new__( + ZerosPolesGainContinuous, + *system, + **kwargs) + else: + return ZerosPolesGainDiscrete.__new__( + ZerosPolesGainDiscrete, + *system, + **kwargs + ) + + # No special conversion needed + return super().__new__(cls) + + def __init__(self, *system, **kwargs): + """Initialize the zeros, poles, gain system.""" + # Conversion of lti instances is handled in __new__ + if isinstance(system[0], LinearTimeInvariant): + return + + super().__init__(**kwargs) + + self._zeros = None + self._poles = None + self._gain = None + + self.zeros, self.poles, self.gain = system + + def __repr__(self): + """Return representation of the `ZerosPolesGain` system.""" + return ( + f'{self.__class__.__name__}(\n' + f'{repr(self.zeros)},\n' + f'{repr(self.poles)},\n' + f'{repr(self.gain)},\n' + f'dt: {repr(self.dt)}\n)' + ) + + @property + def zeros(self): + """Zeros of the `ZerosPolesGain` system.""" + return self._zeros + + @zeros.setter + def zeros(self, zeros): + self._zeros = atleast_1d(zeros) + + # Update dimensions + if len(self.zeros.shape) > 1: + self.outputs, self.inputs = self.zeros.shape + else: + self.outputs = 1 + self.inputs = 1 + + @property + def poles(self): + """Poles of the `ZerosPolesGain` system.""" + return self._poles + + @poles.setter + def poles(self, poles): + self._poles = atleast_1d(poles) + + @property + def gain(self): + """Gain of the `ZerosPolesGain` system.""" + return self._gain + + @gain.setter + def gain(self, gain): + self._gain = gain + + def _copy(self, system): + """ + Copy the parameters of another `ZerosPolesGain` system. + + Parameters + ---------- + system : instance of `ZerosPolesGain` + The zeros, poles gain system that is to be copied + + """ + self.poles = system.poles + self.zeros = system.zeros + self.gain = system.gain + + def to_tf(self): + """ + Convert system representation to `TransferFunction`. + + Returns + ------- + sys : instance of `TransferFunction` + Transfer function of the current system + + """ + return TransferFunction(*zpk2tf(self.zeros, self.poles, self.gain), + **self._dt_dict) + + def to_zpk(self): + """ + Return a copy of the current 'ZerosPolesGain' system. + + Returns + ------- + sys : instance of `ZerosPolesGain` + The current system (copy) + + """ + return copy.deepcopy(self) + + def to_ss(self): + """ + Convert system representation to `StateSpace`. + + Returns + ------- + sys : instance of `StateSpace` + State space model of the current system + + """ + return StateSpace(*zpk2ss(self.zeros, self.poles, self.gain), + **self._dt_dict) + + +class ZerosPolesGainContinuous(ZerosPolesGain, lti): + r""" + Continuous-time Linear Time Invariant system in zeros, poles, gain form. + + Represents the system as the continuous time transfer function + :math:`H(s)=k \prod_i (s - z[i]) / \prod_j (s - p[j])`, where :math:`k` is + the `gain`, :math:`z` are the `zeros` and :math:`p` are the `poles`. + Continuous-time `ZerosPolesGain` systems inherit additional functionality + from the `lti` class. + + Parameters + ---------- + *system : arguments + The `ZerosPolesGain` class can be instantiated with 1 or 3 + arguments. The following gives the number of input arguments and their + interpretation: + + * 1: `lti` system: (`StateSpace`, `TransferFunction` or + `ZerosPolesGain`) + * 3: array_like: (zeros, poles, gain) + + See Also + -------- + TransferFunction, StateSpace, lti + zpk2ss, zpk2tf, zpk2sos + + Notes + ----- + Changing the value of properties that are not part of the + `ZerosPolesGain` system representation (such as the `A`, `B`, `C`, `D` + state-space matrices) is very inefficient and may lead to numerical + inaccuracies. It is better to convert to the specific system + representation first. For example, call ``sys = sys.to_ss()`` before + accessing/changing the A, B, C, D system matrices. + + Examples + -------- + Construct the transfer function + :math:`H(s)=\frac{5(s - 1)(s - 2)}{(s - 3)(s - 4)}`: + + >>> from scipy import signal + + >>> signal.ZerosPolesGain([1, 2], [3, 4], 5) + ZerosPolesGainContinuous( + array([1, 2]), + array([3, 4]), + 5, + dt: None + ) + + """ + + def to_discrete(self, dt, method='zoh', alpha=None): + """ + Returns the discretized `ZerosPolesGain` system. + + Parameters: See `cont2discrete` for details. + + Returns + ------- + sys: instance of `dlti` and `ZerosPolesGain` + """ + return ZerosPolesGain( + *cont2discrete((self.zeros, self.poles, self.gain), + dt, + method=method, + alpha=alpha)[:-1], + dt=dt) + + +class ZerosPolesGainDiscrete(ZerosPolesGain, dlti): + r""" + Discrete-time Linear Time Invariant system in zeros, poles, gain form. + + Represents the system as the discrete-time transfer function + :math:`H(z)=k \prod_i (z - q[i]) / \prod_j (z - p[j])`, where :math:`k` is + the `gain`, :math:`q` are the `zeros` and :math:`p` are the `poles`. + Discrete-time `ZerosPolesGain` systems inherit additional functionality + from the `dlti` class. + + Parameters + ---------- + *system : arguments + The `ZerosPolesGain` class can be instantiated with 1 or 3 + arguments. The following gives the number of input arguments and their + interpretation: + + * 1: `dlti` system: (`StateSpace`, `TransferFunction` or + `ZerosPolesGain`) + * 3: array_like: (zeros, poles, gain) + dt: float, optional + Sampling time [s] of the discrete-time systems. Defaults to `True` + (unspecified sampling time). Must be specified as a keyword argument, + for example, ``dt=0.1``. + + See Also + -------- + TransferFunction, StateSpace, dlti + zpk2ss, zpk2tf, zpk2sos + + Notes + ----- + Changing the value of properties that are not part of the + `ZerosPolesGain` system representation (such as the `A`, `B`, `C`, `D` + state-space matrices) is very inefficient and may lead to numerical + inaccuracies. It is better to convert to the specific system + representation first. For example, call ``sys = sys.to_ss()`` before + accessing/changing the A, B, C, D system matrices. + + Examples + -------- + Construct the transfer function + :math:`H(s) = \frac{5(s - 1)(s - 2)}{(s - 3)(s - 4)}`: + + >>> from scipy import signal + + >>> signal.ZerosPolesGain([1, 2], [3, 4], 5) + ZerosPolesGainContinuous( + array([1, 2]), + array([3, 4]), + 5, + dt: None + ) + + Construct the transfer function + :math:`H(z) = \frac{5(z - 1)(z - 2)}{(z - 3)(z - 4)}` with a sampling time + of 0.1 seconds: + + >>> signal.ZerosPolesGain([1, 2], [3, 4], 5, dt=0.1) + ZerosPolesGainDiscrete( + array([1, 2]), + array([3, 4]), + 5, + dt: 0.1 + ) + + """ + pass + + +class StateSpace(LinearTimeInvariant): + r""" + Linear Time Invariant system in state-space form. + + Represents the system as the continuous-time, first order differential + equation :math:`\dot{x} = A x + B u` or the discrete-time difference + equation :math:`x[k+1] = A x[k] + B u[k]`. `StateSpace` systems + inherit additional functionality from the `lti`, respectively the `dlti` + classes, depending on which system representation is used. + + Parameters + ---------- + *system: arguments + The `StateSpace` class can be instantiated with 1 or 4 arguments. + The following gives the number of input arguments and their + interpretation: + + * 1: `lti` or `dlti` system: (`StateSpace`, `TransferFunction` or + `ZerosPolesGain`) + * 4: array_like: (A, B, C, D) + dt: float, optional + Sampling time [s] of the discrete-time systems. Defaults to `None` + (continuous-time). Must be specified as a keyword argument, for + example, ``dt=0.1``. + + See Also + -------- + TransferFunction, ZerosPolesGain, lti, dlti + ss2zpk, ss2tf, zpk2sos + + Notes + ----- + Changing the value of properties that are not part of the + `StateSpace` system representation (such as `zeros` or `poles`) is very + inefficient and may lead to numerical inaccuracies. It is better to + convert to the specific system representation first. For example, call + ``sys = sys.to_zpk()`` before accessing/changing the zeros, poles or gain. + + Examples + -------- + >>> from scipy import signal + >>> import numpy as np + >>> a = np.array([[0, 1], [0, 0]]) + >>> b = np.array([[0], [1]]) + >>> c = np.array([[1, 0]]) + >>> d = np.array([[0]]) + + >>> sys = signal.StateSpace(a, b, c, d) + >>> print(sys) + StateSpaceContinuous( + array([[0, 1], + [0, 0]]), + array([[0], + [1]]), + array([[1, 0]]), + array([[0]]), + dt: None + ) + + >>> sys.to_discrete(0.1) + StateSpaceDiscrete( + array([[1. , 0.1], + [0. , 1. ]]), + array([[0.005], + [0.1 ]]), + array([[1, 0]]), + array([[0]]), + dt: 0.1 + ) + + >>> a = np.array([[1, 0.1], [0, 1]]) + >>> b = np.array([[0.005], [0.1]]) + + >>> signal.StateSpace(a, b, c, d, dt=0.1) + StateSpaceDiscrete( + array([[1. , 0.1], + [0. , 1. ]]), + array([[0.005], + [0.1 ]]), + array([[1, 0]]), + array([[0]]), + dt: 0.1 + ) + + """ + + # Override NumPy binary operations and ufuncs + __array_priority__ = 100.0 + __array_ufunc__ = None + + def __new__(cls, *system, **kwargs): + """Create new StateSpace object and settle inheritance.""" + # Handle object conversion if input is an instance of `lti` + if len(system) == 1 and isinstance(system[0], LinearTimeInvariant): + return system[0].to_ss() + + # Choose whether to inherit from `lti` or from `dlti` + if cls is StateSpace: + if kwargs.get('dt') is None: + return StateSpaceContinuous.__new__(StateSpaceContinuous, + *system, **kwargs) + else: + return StateSpaceDiscrete.__new__(StateSpaceDiscrete, + *system, **kwargs) + + # No special conversion needed + return super().__new__(cls) + + def __init__(self, *system, **kwargs): + """Initialize the state space lti/dlti system.""" + # Conversion of lti instances is handled in __new__ + if isinstance(system[0], LinearTimeInvariant): + return + + # Remove system arguments, not needed by parents anymore + super().__init__(**kwargs) + + self._A = None + self._B = None + self._C = None + self._D = None + + self.A, self.B, self.C, self.D = abcd_normalize(*system) + + def __repr__(self): + """Return representation of the `StateSpace` system.""" + return ( + f'{self.__class__.__name__}(\n' + f'{repr(self.A)},\n' + f'{repr(self.B)},\n' + f'{repr(self.C)},\n' + f'{repr(self.D)},\n' + f'dt: {repr(self.dt)}\n)' + ) + + def _check_binop_other(self, other): + return isinstance(other, (StateSpace, np.ndarray, float, complex, + np.number, int)) + + def __mul__(self, other): + """ + Post-multiply another system or a scalar + + Handles multiplication of systems in the sense of a frequency domain + multiplication. That means, given two systems E1(s) and E2(s), their + multiplication, H(s) = E1(s) * E2(s), means that applying H(s) to U(s) + is equivalent to first applying E2(s), and then E1(s). + + Notes + ----- + For SISO systems the order of system application does not matter. + However, for MIMO systems, where the two systems are matrices, the + order above ensures standard Matrix multiplication rules apply. + """ + if not self._check_binop_other(other): + return NotImplemented + + if isinstance(other, StateSpace): + # Disallow mix of discrete and continuous systems. + if type(other) is not type(self): + return NotImplemented + + if self.dt != other.dt: + raise TypeError('Cannot multiply systems with different `dt`.') + + n1 = self.A.shape[0] + n2 = other.A.shape[0] + + # Interconnection of systems + # x1' = A1 x1 + B1 u1 + # y1 = C1 x1 + D1 u1 + # x2' = A2 x2 + B2 y1 + # y2 = C2 x2 + D2 y1 + # + # Plugging in with u1 = y2 yields + # [x1'] [A1 B1*C2 ] [x1] [B1*D2] + # [x2'] = [0 A2 ] [x2] + [B2 ] u2 + # [x1] + # y2 = [C1 D1*C2] [x2] + D1*D2 u2 + a = np.vstack((np.hstack((self.A, np.dot(self.B, other.C))), + np.hstack((zeros((n2, n1)), other.A)))) + b = np.vstack((np.dot(self.B, other.D), other.B)) + c = np.hstack((self.C, np.dot(self.D, other.C))) + d = np.dot(self.D, other.D) + else: + # Assume that other is a scalar / matrix + # For post multiplication the input gets scaled + a = self.A + b = np.dot(self.B, other) + c = self.C + d = np.dot(self.D, other) + + common_dtype = np.result_type(a.dtype, b.dtype, c.dtype, d.dtype) + return StateSpace(np.asarray(a, dtype=common_dtype), + np.asarray(b, dtype=common_dtype), + np.asarray(c, dtype=common_dtype), + np.asarray(d, dtype=common_dtype), + **self._dt_dict) + + def __rmul__(self, other): + """Pre-multiply a scalar or matrix (but not StateSpace)""" + if not self._check_binop_other(other) or isinstance(other, StateSpace): + return NotImplemented + + # For pre-multiplication only the output gets scaled + a = self.A + b = self.B + c = np.dot(other, self.C) + d = np.dot(other, self.D) + + common_dtype = np.result_type(a.dtype, b.dtype, c.dtype, d.dtype) + return StateSpace(np.asarray(a, dtype=common_dtype), + np.asarray(b, dtype=common_dtype), + np.asarray(c, dtype=common_dtype), + np.asarray(d, dtype=common_dtype), + **self._dt_dict) + + def __neg__(self): + """Negate the system (equivalent to pre-multiplying by -1).""" + return StateSpace(self.A, self.B, -self.C, -self.D, **self._dt_dict) + + def __add__(self, other): + """ + Adds two systems in the sense of frequency domain addition. + """ + if not self._check_binop_other(other): + return NotImplemented + + if isinstance(other, StateSpace): + # Disallow mix of discrete and continuous systems. + if type(other) is not type(self): + raise TypeError(f'Cannot add {type(self)} and {type(other)}') + + if self.dt != other.dt: + raise TypeError('Cannot add systems with different `dt`.') + # Interconnection of systems + # x1' = A1 x1 + B1 u + # y1 = C1 x1 + D1 u + # x2' = A2 x2 + B2 u + # y2 = C2 x2 + D2 u + # y = y1 + y2 + # + # Plugging in yields + # [x1'] [A1 0 ] [x1] [B1] + # [x2'] = [0 A2] [x2] + [B2] u + # [x1] + # y = [C1 C2] [x2] + [D1 + D2] u + a = linalg.block_diag(self.A, other.A) + b = np.vstack((self.B, other.B)) + c = np.hstack((self.C, other.C)) + d = self.D + other.D + else: + other = np.atleast_2d(other) + if self.D.shape == other.shape: + # A scalar/matrix is really just a static system (A=0, B=0, C=0) + a = self.A + b = self.B + c = self.C + d = self.D + other + else: + raise ValueError("Cannot add systems with incompatible " + f"dimensions ({self.D.shape} and {other.shape})") + + common_dtype = np.result_type(a.dtype, b.dtype, c.dtype, d.dtype) + return StateSpace(np.asarray(a, dtype=common_dtype), + np.asarray(b, dtype=common_dtype), + np.asarray(c, dtype=common_dtype), + np.asarray(d, dtype=common_dtype), + **self._dt_dict) + + def __sub__(self, other): + if not self._check_binop_other(other): + return NotImplemented + + return self.__add__(-other) + + def __radd__(self, other): + if not self._check_binop_other(other): + return NotImplemented + + return self.__add__(other) + + def __rsub__(self, other): + if not self._check_binop_other(other): + return NotImplemented + + return (-self).__add__(other) + + def __truediv__(self, other): + """ + Divide by a scalar + """ + # Division by non-StateSpace scalars + if not self._check_binop_other(other) or isinstance(other, StateSpace): + return NotImplemented + + if isinstance(other, np.ndarray) and other.ndim > 0: + # It's ambiguous what this means, so disallow it + raise ValueError("Cannot divide StateSpace by non-scalar numpy arrays") + + return self.__mul__(1/other) + + @property + def A(self): + """State matrix of the `StateSpace` system.""" + return self._A + + @A.setter + def A(self, A): + self._A = _atleast_2d_or_none(A) + + @property + def B(self): + """Input matrix of the `StateSpace` system.""" + return self._B + + @B.setter + def B(self, B): + self._B = _atleast_2d_or_none(B) + self.inputs = self.B.shape[-1] + + @property + def C(self): + """Output matrix of the `StateSpace` system.""" + return self._C + + @C.setter + def C(self, C): + self._C = _atleast_2d_or_none(C) + self.outputs = self.C.shape[0] + + @property + def D(self): + """Feedthrough matrix of the `StateSpace` system.""" + return self._D + + @D.setter + def D(self, D): + self._D = _atleast_2d_or_none(D) + + def _copy(self, system): + """ + Copy the parameters of another `StateSpace` system. + + Parameters + ---------- + system : instance of `StateSpace` + The state-space system that is to be copied + + """ + self.A = system.A + self.B = system.B + self.C = system.C + self.D = system.D + + def to_tf(self, **kwargs): + """ + Convert system representation to `TransferFunction`. + + Parameters + ---------- + kwargs : dict, optional + Additional keywords passed to `ss2zpk` + + Returns + ------- + sys : instance of `TransferFunction` + Transfer function of the current system + + """ + return TransferFunction(*ss2tf(self._A, self._B, self._C, self._D, + **kwargs), **self._dt_dict) + + def to_zpk(self, **kwargs): + """ + Convert system representation to `ZerosPolesGain`. + + Parameters + ---------- + kwargs : dict, optional + Additional keywords passed to `ss2zpk` + + Returns + ------- + sys : instance of `ZerosPolesGain` + Zeros, poles, gain representation of the current system + + """ + return ZerosPolesGain(*ss2zpk(self._A, self._B, self._C, self._D, + **kwargs), **self._dt_dict) + + def to_ss(self): + """ + Return a copy of the current `StateSpace` system. + + Returns + ------- + sys : instance of `StateSpace` + The current system (copy) + + """ + return copy.deepcopy(self) + + +class StateSpaceContinuous(StateSpace, lti): + r""" + Continuous-time Linear Time Invariant system in state-space form. + + Represents the system as the continuous-time, first order differential + equation :math:`\dot{x} = A x + B u`. + Continuous-time `StateSpace` systems inherit additional functionality + from the `lti` class. + + Parameters + ---------- + *system: arguments + The `StateSpace` class can be instantiated with 1 or 3 arguments. + The following gives the number of input arguments and their + interpretation: + + * 1: `lti` system: (`StateSpace`, `TransferFunction` or + `ZerosPolesGain`) + * 4: array_like: (A, B, C, D) + + See Also + -------- + TransferFunction, ZerosPolesGain, lti + ss2zpk, ss2tf, zpk2sos + + Notes + ----- + Changing the value of properties that are not part of the + `StateSpace` system representation (such as `zeros` or `poles`) is very + inefficient and may lead to numerical inaccuracies. It is better to + convert to the specific system representation first. For example, call + ``sys = sys.to_zpk()`` before accessing/changing the zeros, poles or gain. + + Examples + -------- + >>> import numpy as np + >>> from scipy import signal + + >>> a = np.array([[0, 1], [0, 0]]) + >>> b = np.array([[0], [1]]) + >>> c = np.array([[1, 0]]) + >>> d = np.array([[0]]) + + >>> sys = signal.StateSpace(a, b, c, d) + >>> print(sys) + StateSpaceContinuous( + array([[0, 1], + [0, 0]]), + array([[0], + [1]]), + array([[1, 0]]), + array([[0]]), + dt: None + ) + + """ + + def to_discrete(self, dt, method='zoh', alpha=None): + """ + Returns the discretized `StateSpace` system. + + Parameters: See `cont2discrete` for details. + + Returns + ------- + sys: instance of `dlti` and `StateSpace` + """ + return StateSpace(*cont2discrete((self.A, self.B, self.C, self.D), + dt, + method=method, + alpha=alpha)[:-1], + dt=dt) + + +class StateSpaceDiscrete(StateSpace, dlti): + r""" + Discrete-time Linear Time Invariant system in state-space form. + + Represents the system as the discrete-time difference equation + :math:`x[k+1] = A x[k] + B u[k]`. + `StateSpace` systems inherit additional functionality from the `dlti` + class. + + Parameters + ---------- + *system: arguments + The `StateSpace` class can be instantiated with 1 or 3 arguments. + The following gives the number of input arguments and their + interpretation: + + * 1: `dlti` system: (`StateSpace`, `TransferFunction` or + `ZerosPolesGain`) + * 4: array_like: (A, B, C, D) + dt: float, optional + Sampling time [s] of the discrete-time systems. Defaults to `True` + (unspecified sampling time). Must be specified as a keyword argument, + for example, ``dt=0.1``. + + See Also + -------- + TransferFunction, ZerosPolesGain, dlti + ss2zpk, ss2tf, zpk2sos + + Notes + ----- + Changing the value of properties that are not part of the + `StateSpace` system representation (such as `zeros` or `poles`) is very + inefficient and may lead to numerical inaccuracies. It is better to + convert to the specific system representation first. For example, call + ``sys = sys.to_zpk()`` before accessing/changing the zeros, poles or gain. + + Examples + -------- + >>> import numpy as np + >>> from scipy import signal + + >>> a = np.array([[1, 0.1], [0, 1]]) + >>> b = np.array([[0.005], [0.1]]) + >>> c = np.array([[1, 0]]) + >>> d = np.array([[0]]) + + >>> signal.StateSpace(a, b, c, d, dt=0.1) + StateSpaceDiscrete( + array([[ 1. , 0.1], + [ 0. , 1. ]]), + array([[ 0.005], + [ 0.1 ]]), + array([[1, 0]]), + array([[0]]), + dt: 0.1 + ) + + """ + pass + + +def lsim(system, U, T, X0=None, interp=True): + """ + Simulate output of a continuous-time linear system. + + Parameters + ---------- + system : an instance of the LTI class or a tuple describing the system. + The following gives the number of elements in the tuple and + the interpretation: + + * 1: (instance of `lti`) + * 2: (num, den) + * 3: (zeros, poles, gain) + * 4: (A, B, C, D) + + U : array_like + An input array describing the input at each time `T` + (interpolation is assumed between given times). If there are + multiple inputs, then each column of the rank-2 array + represents an input. If U = 0 or None, a zero input is used. + T : array_like + The time steps at which the input is defined and at which the + output is desired. Must be nonnegative, increasing, and equally spaced. + X0 : array_like, optional + The initial conditions on the state vector (zero by default). + interp : bool, optional + Whether to use linear (True, the default) or zero-order-hold (False) + interpolation for the input array. + + Returns + ------- + T : 1D ndarray + Time values for the output. + yout : 1D ndarray + System response. + xout : ndarray + Time evolution of the state vector. + + Notes + ----- + If (num, den) is passed in for ``system``, coefficients for both the + numerator and denominator should be specified in descending exponent + order (e.g. ``s^2 + 3s + 5`` would be represented as ``[1, 3, 5]``). + + Examples + -------- + We'll use `lsim` to simulate an analog Bessel filter applied to + a signal. + + >>> import numpy as np + >>> from scipy.signal import bessel, lsim + >>> import matplotlib.pyplot as plt + + Create a low-pass Bessel filter with a cutoff of 12 Hz. + + >>> b, a = bessel(N=5, Wn=2*np.pi*12, btype='lowpass', analog=True) + + Generate data to which the filter is applied. + + >>> t = np.linspace(0, 1.25, 500, endpoint=False) + + The input signal is the sum of three sinusoidal curves, with + frequencies 4 Hz, 40 Hz, and 80 Hz. The filter should mostly + eliminate the 40 Hz and 80 Hz components, leaving just the 4 Hz signal. + + >>> u = (np.cos(2*np.pi*4*t) + 0.6*np.sin(2*np.pi*40*t) + + ... 0.5*np.cos(2*np.pi*80*t)) + + Simulate the filter with `lsim`. + + >>> tout, yout, xout = lsim((b, a), U=u, T=t) + + Plot the result. + + >>> plt.plot(t, u, 'r', alpha=0.5, linewidth=1, label='input') + >>> plt.plot(tout, yout, 'k', linewidth=1.5, label='output') + >>> plt.legend(loc='best', shadow=True, framealpha=1) + >>> plt.grid(alpha=0.3) + >>> plt.xlabel('t') + >>> plt.show() + + In a second example, we simulate a double integrator ``y'' = u``, with + a constant input ``u = 1``. We'll use the state space representation + of the integrator. + + >>> from scipy.signal import lti + >>> A = np.array([[0.0, 1.0], [0.0, 0.0]]) + >>> B = np.array([[0.0], [1.0]]) + >>> C = np.array([[1.0, 0.0]]) + >>> D = 0.0 + >>> system = lti(A, B, C, D) + + `t` and `u` define the time and input signal for the system to + be simulated. + + >>> t = np.linspace(0, 5, num=50) + >>> u = np.ones_like(t) + + Compute the simulation, and then plot `y`. As expected, the plot shows + the curve ``y = 0.5*t**2``. + + >>> tout, y, x = lsim(system, u, t) + >>> plt.plot(t, y) + >>> plt.grid(alpha=0.3) + >>> plt.xlabel('t') + >>> plt.show() + + """ + if isinstance(system, lti): + sys = system._as_ss() + elif isinstance(system, dlti): + raise AttributeError('lsim can only be used with continuous-time ' + 'systems.') + else: + sys = lti(*system)._as_ss() + T = atleast_1d(T) + if len(T.shape) != 1: + raise ValueError("T must be a rank-1 array.") + + A, B, C, D = map(np.asarray, (sys.A, sys.B, sys.C, sys.D)) + n_states = A.shape[0] + n_inputs = B.shape[1] + + n_steps = T.size + if X0 is None: + X0 = zeros(n_states, sys.A.dtype) + xout = np.empty((n_steps, n_states), sys.A.dtype) + + if T[0] == 0: + xout[0] = X0 + elif T[0] > 0: + # step forward to initial time, with zero input + xout[0] = dot(X0, linalg.expm(transpose(A) * T[0])) + else: + raise ValueError("Initial time must be nonnegative") + + no_input = (U is None or + (isinstance(U, (int, float)) and U == 0.) or + not np.any(U)) + + if n_steps == 1: + yout = squeeze(xout @ C.T) + if not no_input: + yout += squeeze(U @ D.T) + return T, yout, squeeze(xout) + + dt = T[1] - T[0] + if not np.allclose(np.diff(T), dt): + raise ValueError("Time steps are not equally spaced.") + + if no_input: + # Zero input: just use matrix exponential + # take transpose because state is a row vector + expAT_dt = linalg.expm(A.T * dt) + for i in range(1, n_steps): + xout[i] = xout[i-1] @ expAT_dt + yout = squeeze(xout @ C.T) + return T, yout, squeeze(xout) + + # Nonzero input + U = atleast_1d(U) + if U.ndim == 1: + U = U[:, np.newaxis] + + if U.shape[0] != n_steps: + raise ValueError("U must have the same number of rows " + "as elements in T.") + + if U.shape[1] != n_inputs: + raise ValueError("System does not define that many inputs.") + + if not interp: + # Zero-order hold + # Algorithm: to integrate from time 0 to time dt, we solve + # xdot = A x + B u, x(0) = x0 + # udot = 0, u(0) = u0. + # + # Solution is + # [ x(dt) ] [ A*dt B*dt ] [ x0 ] + # [ u(dt) ] = exp [ 0 0 ] [ u0 ] + M = np.vstack([np.hstack([A * dt, B * dt]), + np.zeros((n_inputs, n_states + n_inputs))]) + # transpose everything because the state and input are row vectors + expMT = linalg.expm(M.T) + Ad = expMT[:n_states, :n_states] + Bd = expMT[n_states:, :n_states] + for i in range(1, n_steps): + xout[i] = xout[i-1] @ Ad + U[i-1] @ Bd + else: + # Linear interpolation between steps + # Algorithm: to integrate from time 0 to time dt, with linear + # interpolation between inputs u(0) = u0 and u(dt) = u1, we solve + # xdot = A x + B u, x(0) = x0 + # udot = (u1 - u0) / dt, u(0) = u0. + # + # Solution is + # [ x(dt) ] [ A*dt B*dt 0 ] [ x0 ] + # [ u(dt) ] = exp [ 0 0 I ] [ u0 ] + # [u1 - u0] [ 0 0 0 ] [u1 - u0] + M = np.vstack([np.hstack([A * dt, B * dt, + np.zeros((n_states, n_inputs))]), + np.hstack([np.zeros((n_inputs, n_states + n_inputs)), + np.identity(n_inputs)]), + np.zeros((n_inputs, n_states + 2 * n_inputs))]) + expMT = linalg.expm(M.T) + Ad = expMT[:n_states, :n_states] + Bd1 = expMT[n_states+n_inputs:, :n_states] + Bd0 = expMT[n_states:n_states + n_inputs, :n_states] - Bd1 + for i in range(1, n_steps): + xout[i] = xout[i-1] @ Ad + U[i-1] @ Bd0 + U[i] @ Bd1 + + yout = squeeze(xout @ C.T) + squeeze(U @ D.T) + return T, yout, squeeze(xout) + + +def _default_response_times(A, n): + """Compute a reasonable set of time samples for the response time. + + This function is used by `impulse` and `step` to compute the response time + when the `T` argument to the function is None. + + Parameters + ---------- + A : array_like + The system matrix, which is square. + n : int + The number of time samples to generate. + + Returns + ------- + t : ndarray + The 1-D array of length `n` of time samples at which the response + is to be computed. + """ + # Create a reasonable time interval. + # TODO: This could use some more work. + # For example, what is expected when the system is unstable? + vals = linalg.eigvals(A) + r = min(abs(real(vals))) + if r == 0.0: + r = 1.0 + tc = 1.0 / r + t = linspace(0.0, 7 * tc, n) + return t + + +def impulse(system, X0=None, T=None, N=None): + """Impulse response of continuous-time system. + + Parameters + ---------- + system : an instance of the LTI class or a tuple of array_like + describing the system. + The following gives the number of elements in the tuple and + the interpretation: + + * 1 (instance of `lti`) + * 2 (num, den) + * 3 (zeros, poles, gain) + * 4 (A, B, C, D) + + X0 : array_like, optional + Initial state-vector. Defaults to zero. + T : array_like, optional + Time points. Computed if not given. + N : int, optional + The number of time points to compute (if `T` is not given). + + Returns + ------- + T : ndarray + A 1-D array of time points. + yout : ndarray + A 1-D array containing the impulse response of the system (except for + singularities at zero). + + Notes + ----- + If (num, den) is passed in for ``system``, coefficients for both the + numerator and denominator should be specified in descending exponent + order (e.g. ``s^2 + 3s + 5`` would be represented as ``[1, 3, 5]``). + + Examples + -------- + Compute the impulse response of a second order system with a repeated + root: ``x''(t) + 2*x'(t) + x(t) = u(t)`` + + >>> from scipy import signal + >>> system = ([1.0], [1.0, 2.0, 1.0]) + >>> t, y = signal.impulse(system) + >>> import matplotlib.pyplot as plt + >>> plt.plot(t, y) + + """ + if isinstance(system, lti): + sys = system._as_ss() + elif isinstance(system, dlti): + raise AttributeError('impulse can only be used with continuous-time ' + 'systems.') + else: + sys = lti(*system)._as_ss() + if X0 is None: + X = squeeze(sys.B) + else: + X = squeeze(sys.B + X0) + if N is None: + N = 100 + if T is None: + T = _default_response_times(sys.A, N) + else: + T = asarray(T) + + _, h, _ = lsim(sys, 0., T, X, interp=False) + return T, h + + +def step(system, X0=None, T=None, N=None): + """Step response of continuous-time system. + + Parameters + ---------- + system : an instance of the LTI class or a tuple of array_like + describing the system. + The following gives the number of elements in the tuple and + the interpretation: + + * 1 (instance of `lti`) + * 2 (num, den) + * 3 (zeros, poles, gain) + * 4 (A, B, C, D) + + X0 : array_like, optional + Initial state-vector (default is zero). + T : array_like, optional + Time points (computed if not given). + N : int, optional + Number of time points to compute if `T` is not given. + + Returns + ------- + T : 1D ndarray + Output time points. + yout : 1D ndarray + Step response of system. + + + Notes + ----- + If (num, den) is passed in for ``system``, coefficients for both the + numerator and denominator should be specified in descending exponent + order (e.g. ``s^2 + 3s + 5`` would be represented as ``[1, 3, 5]``). + + Examples + -------- + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> lti = signal.lti([1.0], [1.0, 1.0]) + >>> t, y = signal.step(lti) + >>> plt.plot(t, y) + >>> plt.xlabel('Time [s]') + >>> plt.ylabel('Amplitude') + >>> plt.title('Step response for 1. Order Lowpass') + >>> plt.grid() + + """ + if isinstance(system, lti): + sys = system._as_ss() + elif isinstance(system, dlti): + raise AttributeError('step can only be used with continuous-time ' + 'systems.') + else: + sys = lti(*system)._as_ss() + if N is None: + N = 100 + if T is None: + T = _default_response_times(sys.A, N) + else: + T = asarray(T) + U = ones(T.shape, sys.A.dtype) + vals = lsim(sys, U, T, X0=X0, interp=False) + return vals[0], vals[1] + + +def bode(system, w=None, n=100): + """ + Calculate Bode magnitude and phase data of a continuous-time system. + + Parameters + ---------- + system : an instance of the LTI class or a tuple describing the system. + The following gives the number of elements in the tuple and + the interpretation: + + * 1 (instance of `lti`) + * 2 (num, den) + * 3 (zeros, poles, gain) + * 4 (A, B, C, D) + + w : array_like, optional + Array of frequencies (in rad/s). Magnitude and phase data is calculated + for every value in this array. If not given a reasonable set will be + calculated. + n : int, optional + Number of frequency points to compute if `w` is not given. The `n` + frequencies are logarithmically spaced in an interval chosen to + include the influence of the poles and zeros of the system. + + Returns + ------- + w : 1D ndarray + Frequency array [rad/s] + mag : 1D ndarray + Magnitude array [dB] + phase : 1D ndarray + Phase array [deg] + + Notes + ----- + If (num, den) is passed in for ``system``, coefficients for both the + numerator and denominator should be specified in descending exponent + order (e.g. ``s^2 + 3s + 5`` would be represented as ``[1, 3, 5]``). + + .. versionadded:: 0.11.0 + + Examples + -------- + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + + >>> sys = signal.TransferFunction([1], [1, 1]) + >>> w, mag, phase = signal.bode(sys) + + >>> plt.figure() + >>> plt.semilogx(w, mag) # Bode magnitude plot + >>> plt.figure() + >>> plt.semilogx(w, phase) # Bode phase plot + >>> plt.show() + + """ + w, y = freqresp(system, w=w, n=n) + + mag = 20.0 * np.log10(abs(y)) + phase = np.unwrap(np.arctan2(y.imag, y.real)) * 180.0 / np.pi + + return w, mag, phase + + +def freqresp(system, w=None, n=10000): + r"""Calculate the frequency response of a continuous-time system. + + Parameters + ---------- + system : an instance of the `lti` class or a tuple describing the system. + The following gives the number of elements in the tuple and + the interpretation: + + * 1 (instance of `lti`) + * 2 (num, den) + * 3 (zeros, poles, gain) + * 4 (A, B, C, D) + + w : array_like, optional + Array of frequencies (in rad/s). Magnitude and phase data is + calculated for every value in this array. If not given, a reasonable + set will be calculated. + n : int, optional + Number of frequency points to compute if `w` is not given. The `n` + frequencies are logarithmically spaced in an interval chosen to + include the influence of the poles and zeros of the system. + + Returns + ------- + w : 1D ndarray + Frequency array [rad/s] + H : 1D ndarray + Array of complex magnitude values + + Notes + ----- + If (num, den) is passed in for ``system``, coefficients for both the + numerator and denominator should be specified in descending exponent + order (e.g. ``s^2 + 3s + 5`` would be represented as ``[1, 3, 5]``). + + Examples + -------- + Generating the Nyquist plot of a transfer function + + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + + Construct the transfer function :math:`H(s) = \frac{5}{(s-1)^3}`: + + >>> s1 = signal.ZerosPolesGain([], [1, 1, 1], [5]) + + >>> w, H = signal.freqresp(s1) + + >>> plt.figure() + >>> plt.plot(H.real, H.imag, "b") + >>> plt.plot(H.real, -H.imag, "r") + >>> plt.show() + """ + if isinstance(system, lti): + if isinstance(system, (TransferFunction, ZerosPolesGain)): + sys = system + else: + sys = system._as_zpk() + elif isinstance(system, dlti): + raise AttributeError('freqresp can only be used with continuous-time ' + 'systems.') + else: + sys = lti(*system)._as_zpk() + + if sys.inputs != 1 or sys.outputs != 1: + raise ValueError("freqresp() requires a SISO (single input, single " + "output) system.") + + if w is not None: + worN = w + else: + worN = n + + if isinstance(sys, TransferFunction): + # In the call to freqs(), sys.num.ravel() is used because there are + # cases where sys.num is a 2-D array with a single row. + w, h = freqs(sys.num.ravel(), sys.den, worN=worN) + + elif isinstance(sys, ZerosPolesGain): + w, h = freqs_zpk(sys.zeros, sys.poles, sys.gain, worN=worN) + + return w, h + + +# This class will be used by place_poles to return its results +# see https://code.activestate.com/recipes/52308/ +class Bunch: + def __init__(self, **kwds): + self.__dict__.update(kwds) + + +def _valid_inputs(A, B, poles, method, rtol, maxiter): + """ + Check the poles come in complex conjugate pairs + Check shapes of A, B and poles are compatible. + Check the method chosen is compatible with provided poles + Return update method to use and ordered poles + + """ + poles = np.asarray(poles) + if poles.ndim > 1: + raise ValueError("Poles must be a 1D array like.") + # Will raise ValueError if poles do not come in complex conjugates pairs + poles = _order_complex_poles(poles) + if A.ndim > 2: + raise ValueError("A must be a 2D array/matrix.") + if B.ndim > 2: + raise ValueError("B must be a 2D array/matrix") + if A.shape[0] != A.shape[1]: + raise ValueError("A must be square") + if len(poles) > A.shape[0]: + raise ValueError("maximum number of poles is %d but you asked for %d" % + (A.shape[0], len(poles))) + if len(poles) < A.shape[0]: + raise ValueError("number of poles is %d but you should provide %d" % + (len(poles), A.shape[0])) + r = np.linalg.matrix_rank(B) + for p in poles: + if sum(p == poles) > r: + raise ValueError("at least one of the requested pole is repeated " + "more than rank(B) times") + # Choose update method + update_loop = _YT_loop + if method not in ('KNV0','YT'): + raise ValueError("The method keyword must be one of 'YT' or 'KNV0'") + + if method == "KNV0": + update_loop = _KNV0_loop + if not all(np.isreal(poles)): + raise ValueError("Complex poles are not supported by KNV0") + + if maxiter < 1: + raise ValueError("maxiter must be at least equal to 1") + + # We do not check rtol <= 0 as the user can use a negative rtol to + # force maxiter iterations + if rtol > 1: + raise ValueError("rtol can not be greater than 1") + + return update_loop, poles + + +def _order_complex_poles(poles): + """ + Check we have complex conjugates pairs and reorder P according to YT, ie + real_poles, complex_i, conjugate complex_i, .... + The lexicographic sort on the complex poles is added to help the user to + compare sets of poles. + """ + ordered_poles = np.sort(poles[np.isreal(poles)]) + im_poles = [] + for p in np.sort(poles[np.imag(poles) < 0]): + if np.conj(p) in poles: + im_poles.extend((p, np.conj(p))) + + ordered_poles = np.hstack((ordered_poles, im_poles)) + + if poles.shape[0] != len(ordered_poles): + raise ValueError("Complex poles must come with their conjugates") + return ordered_poles + + +def _KNV0(B, ker_pole, transfer_matrix, j, poles): + """ + Algorithm "KNV0" Kautsky et Al. Robust pole + assignment in linear state feedback, Int journal of Control + 1985, vol 41 p 1129->1155 + https://la.epfl.ch/files/content/sites/la/files/ + users/105941/public/KautskyNicholsDooren + + """ + # Remove xj form the base + transfer_matrix_not_j = np.delete(transfer_matrix, j, axis=1) + # If we QR this matrix in full mode Q=Q0|Q1 + # then Q1 will be a single column orthogonal to + # Q0, that's what we are looking for ! + + # After merge of gh-4249 great speed improvements could be achieved + # using QR updates instead of full QR in the line below + + # To debug with numpy qr uncomment the line below + # Q, R = np.linalg.qr(transfer_matrix_not_j, mode="complete") + Q, R = s_qr(transfer_matrix_not_j, mode="full") + + mat_ker_pj = np.dot(ker_pole[j], ker_pole[j].T) + yj = np.dot(mat_ker_pj, Q[:, -1]) + + # If Q[:, -1] is "almost" orthogonal to ker_pole[j] its + # projection into ker_pole[j] will yield a vector + # close to 0. As we are looking for a vector in ker_pole[j] + # simply stick with transfer_matrix[:, j] (unless someone provides me with + # a better choice ?) + + if not np.allclose(yj, 0): + xj = yj/np.linalg.norm(yj) + transfer_matrix[:, j] = xj + + # KNV does not support complex poles, using YT technique the two lines + # below seem to work 9 out of 10 times but it is not reliable enough: + # transfer_matrix[:, j]=real(xj) + # transfer_matrix[:, j+1]=imag(xj) + + # Add this at the beginning of this function if you wish to test + # complex support: + # if ~np.isreal(P[j]) and (j>=B.shape[0]-1 or P[j]!=np.conj(P[j+1])): + # return + # Problems arise when imag(xj)=>0 I have no idea on how to fix this + + +def _YT_real(ker_pole, Q, transfer_matrix, i, j): + """ + Applies algorithm from YT section 6.1 page 19 related to real pairs + """ + # step 1 page 19 + u = Q[:, -2, np.newaxis] + v = Q[:, -1, np.newaxis] + + # step 2 page 19 + m = np.dot(np.dot(ker_pole[i].T, np.dot(u, v.T) - + np.dot(v, u.T)), ker_pole[j]) + + # step 3 page 19 + um, sm, vm = np.linalg.svd(m) + # mu1, mu2 two first columns of U => 2 first lines of U.T + mu1, mu2 = um.T[:2, :, np.newaxis] + # VM is V.T with numpy we want the first two lines of V.T + nu1, nu2 = vm[:2, :, np.newaxis] + + # what follows is a rough python translation of the formulas + # in section 6.2 page 20 (step 4) + transfer_matrix_j_mo_transfer_matrix_j = np.vstack(( + transfer_matrix[:, i, np.newaxis], + transfer_matrix[:, j, np.newaxis])) + + if not np.allclose(sm[0], sm[1]): + ker_pole_imo_mu1 = np.dot(ker_pole[i], mu1) + ker_pole_i_nu1 = np.dot(ker_pole[j], nu1) + ker_pole_mu_nu = np.vstack((ker_pole_imo_mu1, ker_pole_i_nu1)) + else: + ker_pole_ij = np.vstack(( + np.hstack((ker_pole[i], + np.zeros(ker_pole[i].shape))), + np.hstack((np.zeros(ker_pole[j].shape), + ker_pole[j])) + )) + mu_nu_matrix = np.vstack( + (np.hstack((mu1, mu2)), np.hstack((nu1, nu2))) + ) + ker_pole_mu_nu = np.dot(ker_pole_ij, mu_nu_matrix) + transfer_matrix_ij = np.dot(np.dot(ker_pole_mu_nu, ker_pole_mu_nu.T), + transfer_matrix_j_mo_transfer_matrix_j) + if not np.allclose(transfer_matrix_ij, 0): + transfer_matrix_ij = (np.sqrt(2)*transfer_matrix_ij / + np.linalg.norm(transfer_matrix_ij)) + transfer_matrix[:, i] = transfer_matrix_ij[ + :transfer_matrix[:, i].shape[0], 0 + ] + transfer_matrix[:, j] = transfer_matrix_ij[ + transfer_matrix[:, i].shape[0]:, 0 + ] + else: + # As in knv0 if transfer_matrix_j_mo_transfer_matrix_j is orthogonal to + # Vect{ker_pole_mu_nu} assign transfer_matrixi/transfer_matrix_j to + # ker_pole_mu_nu and iterate. As we are looking for a vector in + # Vect{Matker_pole_MU_NU} (see section 6.1 page 19) this might help + # (that's a guess, not a claim !) + transfer_matrix[:, i] = ker_pole_mu_nu[ + :transfer_matrix[:, i].shape[0], 0 + ] + transfer_matrix[:, j] = ker_pole_mu_nu[ + transfer_matrix[:, i].shape[0]:, 0 + ] + + +def _YT_complex(ker_pole, Q, transfer_matrix, i, j): + """ + Applies algorithm from YT section 6.2 page 20 related to complex pairs + """ + # step 1 page 20 + ur = np.sqrt(2)*Q[:, -2, np.newaxis] + ui = np.sqrt(2)*Q[:, -1, np.newaxis] + u = ur + 1j*ui + + # step 2 page 20 + ker_pole_ij = ker_pole[i] + m = np.dot(np.dot(np.conj(ker_pole_ij.T), np.dot(u, np.conj(u).T) - + np.dot(np.conj(u), u.T)), ker_pole_ij) + + # step 3 page 20 + e_val, e_vec = np.linalg.eig(m) + # sort eigenvalues according to their module + e_val_idx = np.argsort(np.abs(e_val)) + mu1 = e_vec[:, e_val_idx[-1], np.newaxis] + mu2 = e_vec[:, e_val_idx[-2], np.newaxis] + + # what follows is a rough python translation of the formulas + # in section 6.2 page 20 (step 4) + + # remember transfer_matrix_i has been split as + # transfer_matrix[i]=real(transfer_matrix_i) and + # transfer_matrix[j]=imag(transfer_matrix_i) + transfer_matrix_j_mo_transfer_matrix_j = ( + transfer_matrix[:, i, np.newaxis] + + 1j*transfer_matrix[:, j, np.newaxis] + ) + if not np.allclose(np.abs(e_val[e_val_idx[-1]]), + np.abs(e_val[e_val_idx[-2]])): + ker_pole_mu = np.dot(ker_pole_ij, mu1) + else: + mu1_mu2_matrix = np.hstack((mu1, mu2)) + ker_pole_mu = np.dot(ker_pole_ij, mu1_mu2_matrix) + transfer_matrix_i_j = np.dot(np.dot(ker_pole_mu, np.conj(ker_pole_mu.T)), + transfer_matrix_j_mo_transfer_matrix_j) + + if not np.allclose(transfer_matrix_i_j, 0): + transfer_matrix_i_j = (transfer_matrix_i_j / + np.linalg.norm(transfer_matrix_i_j)) + transfer_matrix[:, i] = np.real(transfer_matrix_i_j[:, 0]) + transfer_matrix[:, j] = np.imag(transfer_matrix_i_j[:, 0]) + else: + # same idea as in YT_real + transfer_matrix[:, i] = np.real(ker_pole_mu[:, 0]) + transfer_matrix[:, j] = np.imag(ker_pole_mu[:, 0]) + + +def _YT_loop(ker_pole, transfer_matrix, poles, B, maxiter, rtol): + """ + Algorithm "YT" Tits, Yang. Globally Convergent + Algorithms for Robust Pole Assignment by State Feedback + https://hdl.handle.net/1903/5598 + The poles P have to be sorted accordingly to section 6.2 page 20 + + """ + # The IEEE edition of the YT paper gives useful information on the + # optimal update order for the real poles in order to minimize the number + # of times we have to loop over all poles, see page 1442 + nb_real = poles[np.isreal(poles)].shape[0] + # hnb => Half Nb Real + hnb = nb_real // 2 + + # Stick to the indices in the paper and then remove one to get numpy array + # index it is a bit easier to link the code to the paper this way even if it + # is not very clean. The paper is unclear about what should be done when + # there is only one real pole => use KNV0 on this real pole seem to work + if nb_real > 0: + #update the biggest real pole with the smallest one + update_order = [[nb_real], [1]] + else: + update_order = [[],[]] + + r_comp = np.arange(nb_real+1, len(poles)+1, 2) + # step 1.a + r_p = np.arange(1, hnb+nb_real % 2) + update_order[0].extend(2*r_p) + update_order[1].extend(2*r_p+1) + # step 1.b + update_order[0].extend(r_comp) + update_order[1].extend(r_comp+1) + # step 1.c + r_p = np.arange(1, hnb+1) + update_order[0].extend(2*r_p-1) + update_order[1].extend(2*r_p) + # step 1.d + if hnb == 0 and np.isreal(poles[0]): + update_order[0].append(1) + update_order[1].append(1) + update_order[0].extend(r_comp) + update_order[1].extend(r_comp+1) + # step 2.a + r_j = np.arange(2, hnb+nb_real % 2) + for j in r_j: + for i in range(1, hnb+1): + update_order[0].append(i) + update_order[1].append(i+j) + # step 2.b + if hnb == 0 and np.isreal(poles[0]): + update_order[0].append(1) + update_order[1].append(1) + update_order[0].extend(r_comp) + update_order[1].extend(r_comp+1) + # step 2.c + r_j = np.arange(2, hnb+nb_real % 2) + for j in r_j: + for i in range(hnb+1, nb_real+1): + idx_1 = i+j + if idx_1 > nb_real: + idx_1 = i+j-nb_real + update_order[0].append(i) + update_order[1].append(idx_1) + # step 2.d + if hnb == 0 and np.isreal(poles[0]): + update_order[0].append(1) + update_order[1].append(1) + update_order[0].extend(r_comp) + update_order[1].extend(r_comp+1) + # step 3.a + for i in range(1, hnb+1): + update_order[0].append(i) + update_order[1].append(i+hnb) + # step 3.b + if hnb == 0 and np.isreal(poles[0]): + update_order[0].append(1) + update_order[1].append(1) + update_order[0].extend(r_comp) + update_order[1].extend(r_comp+1) + + update_order = np.array(update_order).T-1 + stop = False + nb_try = 0 + while nb_try < maxiter and not stop: + det_transfer_matrixb = np.abs(np.linalg.det(transfer_matrix)) + for i, j in update_order: + if i == j: + assert i == 0, "i!=0 for KNV call in YT" + assert np.isreal(poles[i]), "calling KNV on a complex pole" + _KNV0(B, ker_pole, transfer_matrix, i, poles) + else: + transfer_matrix_not_i_j = np.delete(transfer_matrix, (i, j), + axis=1) + # after merge of gh-4249 great speed improvements could be + # achieved using QR updates instead of full QR in the line below + + #to debug with numpy qr uncomment the line below + #Q, _ = np.linalg.qr(transfer_matrix_not_i_j, mode="complete") + Q, _ = s_qr(transfer_matrix_not_i_j, mode="full") + + if np.isreal(poles[i]): + assert np.isreal(poles[j]), "mixing real and complex " + \ + "in YT_real" + str(poles) + _YT_real(ker_pole, Q, transfer_matrix, i, j) + else: + assert ~np.isreal(poles[i]), "mixing real and complex " + \ + "in YT_real" + str(poles) + _YT_complex(ker_pole, Q, transfer_matrix, i, j) + + det_transfer_matrix = np.max((np.sqrt(np.spacing(1)), + np.abs(np.linalg.det(transfer_matrix)))) + cur_rtol = np.abs( + (det_transfer_matrix - + det_transfer_matrixb) / + det_transfer_matrix) + if cur_rtol < rtol and det_transfer_matrix > np.sqrt(np.spacing(1)): + # Convergence test from YT page 21 + stop = True + nb_try += 1 + return stop, cur_rtol, nb_try + + +def _KNV0_loop(ker_pole, transfer_matrix, poles, B, maxiter, rtol): + """ + Loop over all poles one by one and apply KNV method 0 algorithm + """ + # This method is useful only because we need to be able to call + # _KNV0 from YT without looping over all poles, otherwise it would + # have been fine to mix _KNV0_loop and _KNV0 in a single function + stop = False + nb_try = 0 + while nb_try < maxiter and not stop: + det_transfer_matrixb = np.abs(np.linalg.det(transfer_matrix)) + for j in range(B.shape[0]): + _KNV0(B, ker_pole, transfer_matrix, j, poles) + + det_transfer_matrix = np.max((np.sqrt(np.spacing(1)), + np.abs(np.linalg.det(transfer_matrix)))) + cur_rtol = np.abs((det_transfer_matrix - det_transfer_matrixb) / + det_transfer_matrix) + if cur_rtol < rtol and det_transfer_matrix > np.sqrt(np.spacing(1)): + # Convergence test from YT page 21 + stop = True + + nb_try += 1 + return stop, cur_rtol, nb_try + + +def place_poles(A, B, poles, method="YT", rtol=1e-3, maxiter=30): + """ + Compute K such that eigenvalues (A - dot(B, K))=poles. + + K is the gain matrix such as the plant described by the linear system + ``AX+BU`` will have its closed-loop poles, i.e the eigenvalues ``A - B*K``, + as close as possible to those asked for in poles. + + SISO, MISO and MIMO systems are supported. + + Parameters + ---------- + A, B : ndarray + State-space representation of linear system ``AX + BU``. + poles : array_like + Desired real poles and/or complex conjugates poles. + Complex poles are only supported with ``method="YT"`` (default). + method: {'YT', 'KNV0'}, optional + Which method to choose to find the gain matrix K. One of: + + - 'YT': Yang Tits + - 'KNV0': Kautsky, Nichols, Van Dooren update method 0 + + See References and Notes for details on the algorithms. + rtol: float, optional + After each iteration the determinant of the eigenvectors of + ``A - B*K`` is compared to its previous value, when the relative + error between these two values becomes lower than `rtol` the algorithm + stops. Default is 1e-3. + maxiter: int, optional + Maximum number of iterations to compute the gain matrix. + Default is 30. + + Returns + ------- + full_state_feedback : Bunch object + full_state_feedback is composed of: + gain_matrix : 1-D ndarray + The closed loop matrix K such as the eigenvalues of ``A-BK`` + are as close as possible to the requested poles. + computed_poles : 1-D ndarray + The poles corresponding to ``A-BK`` sorted as first the real + poles in increasing order, then the complex conjugates in + lexicographic order. + requested_poles : 1-D ndarray + The poles the algorithm was asked to place sorted as above, + they may differ from what was achieved. + X : 2-D ndarray + The transfer matrix such as ``X * diag(poles) = (A - B*K)*X`` + (see Notes) + rtol : float + The relative tolerance achieved on ``det(X)`` (see Notes). + `rtol` will be NaN if it is possible to solve the system + ``diag(poles) = (A - B*K)``, or 0 when the optimization + algorithms can't do anything i.e when ``B.shape[1] == 1``. + nb_iter : int + The number of iterations performed before converging. + `nb_iter` will be NaN if it is possible to solve the system + ``diag(poles) = (A - B*K)``, or 0 when the optimization + algorithms can't do anything i.e when ``B.shape[1] == 1``. + + Notes + ----- + The Tits and Yang (YT), [2]_ paper is an update of the original Kautsky et + al. (KNV) paper [1]_. KNV relies on rank-1 updates to find the transfer + matrix X such that ``X * diag(poles) = (A - B*K)*X``, whereas YT uses + rank-2 updates. This yields on average more robust solutions (see [2]_ + pp 21-22), furthermore the YT algorithm supports complex poles whereas KNV + does not in its original version. Only update method 0 proposed by KNV has + been implemented here, hence the name ``'KNV0'``. + + KNV extended to complex poles is used in Matlab's ``place`` function, YT is + distributed under a non-free licence by Slicot under the name ``robpole``. + It is unclear and undocumented how KNV0 has been extended to complex poles + (Tits and Yang claim on page 14 of their paper that their method can not be + used to extend KNV to complex poles), therefore only YT supports them in + this implementation. + + As the solution to the problem of pole placement is not unique for MIMO + systems, both methods start with a tentative transfer matrix which is + altered in various way to increase its determinant. Both methods have been + proven to converge to a stable solution, however depending on the way the + initial transfer matrix is chosen they will converge to different + solutions and therefore there is absolutely no guarantee that using + ``'KNV0'`` will yield results similar to Matlab's or any other + implementation of these algorithms. + + Using the default method ``'YT'`` should be fine in most cases; ``'KNV0'`` + is only provided because it is needed by ``'YT'`` in some specific cases. + Furthermore ``'YT'`` gives on average more robust results than ``'KNV0'`` + when ``abs(det(X))`` is used as a robustness indicator. + + [2]_ is available as a technical report on the following URL: + https://hdl.handle.net/1903/5598 + + References + ---------- + .. [1] J. Kautsky, N.K. Nichols and P. van Dooren, "Robust pole assignment + in linear state feedback", International Journal of Control, Vol. 41 + pp. 1129-1155, 1985. + .. [2] A.L. Tits and Y. Yang, "Globally convergent algorithms for robust + pole assignment by state feedback", IEEE Transactions on Automatic + Control, Vol. 41, pp. 1432-1452, 1996. + + Examples + -------- + A simple example demonstrating real pole placement using both KNV and YT + algorithms. This is example number 1 from section 4 of the reference KNV + publication ([1]_): + + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + + >>> A = np.array([[ 1.380, -0.2077, 6.715, -5.676 ], + ... [-0.5814, -4.290, 0, 0.6750 ], + ... [ 1.067, 4.273, -6.654, 5.893 ], + ... [ 0.0480, 4.273, 1.343, -2.104 ]]) + >>> B = np.array([[ 0, 5.679 ], + ... [ 1.136, 1.136 ], + ... [ 0, 0, ], + ... [-3.146, 0 ]]) + >>> P = np.array([-0.2, -0.5, -5.0566, -8.6659]) + + Now compute K with KNV method 0, with the default YT method and with the YT + method while forcing 100 iterations of the algorithm and print some results + after each call. + + >>> fsf1 = signal.place_poles(A, B, P, method='KNV0') + >>> fsf1.gain_matrix + array([[ 0.20071427, -0.96665799, 0.24066128, -0.10279785], + [ 0.50587268, 0.57779091, 0.51795763, -0.41991442]]) + + >>> fsf2 = signal.place_poles(A, B, P) # uses YT method + >>> fsf2.computed_poles + array([-8.6659, -5.0566, -0.5 , -0.2 ]) + + >>> fsf3 = signal.place_poles(A, B, P, rtol=-1, maxiter=100) + >>> fsf3.X + array([[ 0.52072442+0.j, -0.08409372+0.j, -0.56847937+0.j, 0.74823657+0.j], + [-0.04977751+0.j, -0.80872954+0.j, 0.13566234+0.j, -0.29322906+0.j], + [-0.82266932+0.j, -0.19168026+0.j, -0.56348322+0.j, -0.43815060+0.j], + [ 0.22267347+0.j, 0.54967577+0.j, -0.58387806+0.j, -0.40271926+0.j]]) + + The absolute value of the determinant of X is a good indicator to check the + robustness of the results, both ``'KNV0'`` and ``'YT'`` aim at maximizing + it. Below a comparison of the robustness of the results above: + + >>> abs(np.linalg.det(fsf1.X)) < abs(np.linalg.det(fsf2.X)) + True + >>> abs(np.linalg.det(fsf2.X)) < abs(np.linalg.det(fsf3.X)) + True + + Now a simple example for complex poles: + + >>> A = np.array([[ 0, 7/3., 0, 0 ], + ... [ 0, 0, 0, 7/9. ], + ... [ 0, 0, 0, 0 ], + ... [ 0, 0, 0, 0 ]]) + >>> B = np.array([[ 0, 0 ], + ... [ 0, 0 ], + ... [ 1, 0 ], + ... [ 0, 1 ]]) + >>> P = np.array([-3, -1, -2-1j, -2+1j]) / 3. + >>> fsf = signal.place_poles(A, B, P, method='YT') + + We can plot the desired and computed poles in the complex plane: + + >>> t = np.linspace(0, 2*np.pi, 401) + >>> plt.plot(np.cos(t), np.sin(t), 'k--') # unit circle + >>> plt.plot(fsf.requested_poles.real, fsf.requested_poles.imag, + ... 'wo', label='Desired') + >>> plt.plot(fsf.computed_poles.real, fsf.computed_poles.imag, 'bx', + ... label='Placed') + >>> plt.grid() + >>> plt.axis('image') + >>> plt.axis([-1.1, 1.1, -1.1, 1.1]) + >>> plt.legend(bbox_to_anchor=(1.05, 1), loc=2, numpoints=1) + + """ + # Move away all the inputs checking, it only adds noise to the code + update_loop, poles = _valid_inputs(A, B, poles, method, rtol, maxiter) + + # The current value of the relative tolerance we achieved + cur_rtol = 0 + # The number of iterations needed before converging + nb_iter = 0 + + # Step A: QR decomposition of B page 1132 KN + # to debug with numpy qr uncomment the line below + # u, z = np.linalg.qr(B, mode="complete") + u, z = s_qr(B, mode="full") + rankB = np.linalg.matrix_rank(B) + u0 = u[:, :rankB] + u1 = u[:, rankB:] + z = z[:rankB, :] + + # If we can use the identity matrix as X the solution is obvious + if B.shape[0] == rankB: + # if B is square and full rank there is only one solution + # such as (A+BK)=inv(X)*diag(P)*X with X=eye(A.shape[0]) + # i.e K=inv(B)*(diag(P)-A) + # if B has as many lines as its rank (but not square) there are many + # solutions and we can choose one using least squares + # => use lstsq in both cases. + # In both cases the transfer matrix X will be eye(A.shape[0]) and I + # can hardly think of a better one so there is nothing to optimize + # + # for complex poles we use the following trick + # + # |a -b| has for eigenvalues a+b and a-b + # |b a| + # + # |a+bi 0| has the obvious eigenvalues a+bi and a-bi + # |0 a-bi| + # + # e.g solving the first one in R gives the solution + # for the second one in C + diag_poles = np.zeros(A.shape) + idx = 0 + while idx < poles.shape[0]: + p = poles[idx] + diag_poles[idx, idx] = np.real(p) + if ~np.isreal(p): + diag_poles[idx, idx+1] = -np.imag(p) + diag_poles[idx+1, idx+1] = np.real(p) + diag_poles[idx+1, idx] = np.imag(p) + idx += 1 # skip next one + idx += 1 + gain_matrix = np.linalg.lstsq(B, diag_poles-A, rcond=-1)[0] + transfer_matrix = np.eye(A.shape[0]) + cur_rtol = np.nan + nb_iter = np.nan + else: + # step A (p1144 KNV) and beginning of step F: decompose + # dot(U1.T, A-P[i]*I).T and build our set of transfer_matrix vectors + # in the same loop + ker_pole = [] + + # flag to skip the conjugate of a complex pole + skip_conjugate = False + # select orthonormal base ker_pole for each Pole and vectors for + # transfer_matrix + for j in range(B.shape[0]): + if skip_conjugate: + skip_conjugate = False + continue + pole_space_j = np.dot(u1.T, A-poles[j]*np.eye(B.shape[0])).T + + # after QR Q=Q0|Q1 + # only Q0 is used to reconstruct the qr'ed (dot Q, R) matrix. + # Q1 is orthogonal to Q0 and will be multiplied by the zeros in + # R when using mode "complete". In default mode Q1 and the zeros + # in R are not computed + + # To debug with numpy qr uncomment the line below + # Q, _ = np.linalg.qr(pole_space_j, mode="complete") + Q, _ = s_qr(pole_space_j, mode="full") + + ker_pole_j = Q[:, pole_space_j.shape[1]:] + + # We want to select one vector in ker_pole_j to build the transfer + # matrix, however qr returns sometimes vectors with zeros on the + # same line for each pole and this yields very long convergence + # times. + # Or some other times a set of vectors, one with zero imaginary + # part and one (or several) with imaginary parts. After trying + # many ways to select the best possible one (eg ditch vectors + # with zero imaginary part for complex poles) I ended up summing + # all vectors in ker_pole_j, this solves 100% of the problems and + # is a valid choice for transfer_matrix. + # This way for complex poles we are sure to have a non zero + # imaginary part that way, and the problem of lines full of zeros + # in transfer_matrix is solved too as when a vector from + # ker_pole_j has a zero the other one(s) when + # ker_pole_j.shape[1]>1) for sure won't have a zero there. + + transfer_matrix_j = np.sum(ker_pole_j, axis=1)[:, np.newaxis] + transfer_matrix_j = (transfer_matrix_j / + np.linalg.norm(transfer_matrix_j)) + if ~np.isreal(poles[j]): # complex pole + transfer_matrix_j = np.hstack([np.real(transfer_matrix_j), + np.imag(transfer_matrix_j)]) + ker_pole.extend([ker_pole_j, ker_pole_j]) + + # Skip next pole as it is the conjugate + skip_conjugate = True + else: # real pole, nothing to do + ker_pole.append(ker_pole_j) + + if j == 0: + transfer_matrix = transfer_matrix_j + else: + transfer_matrix = np.hstack((transfer_matrix, transfer_matrix_j)) + + if rankB > 1: # otherwise there is nothing we can optimize + stop, cur_rtol, nb_iter = update_loop(ker_pole, transfer_matrix, + poles, B, maxiter, rtol) + if not stop and rtol > 0: + # if rtol<=0 the user has probably done that on purpose, + # don't annoy them + err_msg = ( + "Convergence was not reached after maxiter iterations.\n" + f"You asked for a tolerance of {rtol}, we got {cur_rtol}." + ) + warnings.warn(err_msg, stacklevel=2) + + # reconstruct transfer_matrix to match complex conjugate pairs, + # ie transfer_matrix_j/transfer_matrix_j+1 are + # Re(Complex_pole), Im(Complex_pole) now and will be Re-Im/Re+Im after + transfer_matrix = transfer_matrix.astype(complex) + idx = 0 + while idx < poles.shape[0]-1: + if ~np.isreal(poles[idx]): + rel = transfer_matrix[:, idx].copy() + img = transfer_matrix[:, idx+1] + # rel will be an array referencing a column of transfer_matrix + # if we don't copy() it will changer after the next line and + # and the line after will not yield the correct value + transfer_matrix[:, idx] = rel-1j*img + transfer_matrix[:, idx+1] = rel+1j*img + idx += 1 # skip next one + idx += 1 + + try: + m = np.linalg.solve(transfer_matrix.T, np.dot(np.diag(poles), + transfer_matrix.T)).T + gain_matrix = np.linalg.solve(z, np.dot(u0.T, m-A)) + except np.linalg.LinAlgError as e: + raise ValueError("The poles you've chosen can't be placed. " + "Check the controllability matrix and try " + "another set of poles") from e + + # Beware: Kautsky solves A+BK but the usual form is A-BK + gain_matrix = -gain_matrix + # K still contains complex with ~=0j imaginary parts, get rid of them + gain_matrix = np.real(gain_matrix) + + full_state_feedback = Bunch() + full_state_feedback.gain_matrix = gain_matrix + full_state_feedback.computed_poles = _order_complex_poles( + np.linalg.eig(A - np.dot(B, gain_matrix))[0] + ) + full_state_feedback.requested_poles = poles + full_state_feedback.X = transfer_matrix + full_state_feedback.rtol = cur_rtol + full_state_feedback.nb_iter = nb_iter + + return full_state_feedback + + +def dlsim(system, u, t=None, x0=None): + """ + Simulate output of a discrete-time linear system. + + Parameters + ---------- + system : tuple of array_like or instance of `dlti` + A tuple describing the system. + The following gives the number of elements in the tuple and + the interpretation: + + * 1: (instance of `dlti`) + * 3: (num, den, dt) + * 4: (zeros, poles, gain, dt) + * 5: (A, B, C, D, dt) + + u : array_like + An input array describing the input at each time `t` (interpolation is + assumed between given times). If there are multiple inputs, then each + column of the rank-2 array represents an input. + t : array_like, optional + The time steps at which the input is defined. If `t` is given, it + must be the same length as `u`, and the final value in `t` determines + the number of steps returned in the output. + x0 : array_like, optional + The initial conditions on the state vector (zero by default). + + Returns + ------- + tout : ndarray + Time values for the output, as a 1-D array. + yout : ndarray + System response, as a 1-D array. + xout : ndarray, optional + Time-evolution of the state-vector. Only generated if the input is a + `StateSpace` system. + + See Also + -------- + lsim, dstep, dimpulse, cont2discrete + + Examples + -------- + A simple integrator transfer function with a discrete time step of 1.0 + could be implemented as: + + >>> import numpy as np + >>> from scipy import signal + >>> tf = ([1.0,], [1.0, -1.0], 1.0) + >>> t_in = [0.0, 1.0, 2.0, 3.0] + >>> u = np.asarray([0.0, 0.0, 1.0, 1.0]) + >>> t_out, y = signal.dlsim(tf, u, t=t_in) + >>> y.T + array([[ 0., 0., 0., 1.]]) + + """ + # Convert system to dlti-StateSpace + if isinstance(system, lti): + raise AttributeError('dlsim can only be used with discrete-time dlti ' + 'systems.') + elif not isinstance(system, dlti): + system = dlti(*system[:-1], dt=system[-1]) + + # Condition needed to ensure output remains compatible + is_ss_input = isinstance(system, StateSpace) + system = system._as_ss() + + u = np.atleast_1d(u) + + if u.ndim == 1: + u = np.atleast_2d(u).T + + if t is None: + out_samples = len(u) + stoptime = (out_samples - 1) * system.dt + else: + stoptime = t[-1] + out_samples = int(np.floor(stoptime / system.dt)) + 1 + + # Pre-build output arrays + xout = np.zeros((out_samples, system.A.shape[0])) + yout = np.zeros((out_samples, system.C.shape[0])) + tout = np.linspace(0.0, stoptime, num=out_samples) + + # Check initial condition + if x0 is None: + xout[0, :] = np.zeros((system.A.shape[1],)) + else: + xout[0, :] = np.asarray(x0) + + # Pre-interpolate inputs into the desired time steps + if t is None: + u_dt = u + else: + if len(u.shape) == 1: + u = u[:, np.newaxis] + + u_dt = make_interp_spline(t, u, k=1)(tout) + + # Simulate the system + for i in range(0, out_samples - 1): + xout[i+1, :] = (np.dot(system.A, xout[i, :]) + + np.dot(system.B, u_dt[i, :])) + yout[i, :] = (np.dot(system.C, xout[i, :]) + + np.dot(system.D, u_dt[i, :])) + + # Last point + yout[out_samples-1, :] = (np.dot(system.C, xout[out_samples-1, :]) + + np.dot(system.D, u_dt[out_samples-1, :])) + + if is_ss_input: + return tout, yout, xout + else: + return tout, yout + + +def dimpulse(system, x0=None, t=None, n=None): + """ + Impulse response of discrete-time system. + + Parameters + ---------- + system : tuple of array_like or instance of `dlti` + A tuple describing the system. + The following gives the number of elements in the tuple and + the interpretation: + + * 1: (instance of `dlti`) + * 3: (num, den, dt) + * 4: (zeros, poles, gain, dt) + * 5: (A, B, C, D, dt) + + x0 : array_like, optional + Initial state-vector. Defaults to zero. + t : array_like, optional + Time points. Computed if not given. + n : int, optional + The number of time points to compute (if `t` is not given). + + Returns + ------- + tout : ndarray + Time values for the output, as a 1-D array. + yout : tuple of ndarray + Impulse response of system. Each element of the tuple represents + the output of the system based on an impulse in each input. + + See Also + -------- + impulse, dstep, dlsim, cont2discrete + + Examples + -------- + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + + >>> butter = signal.dlti(*signal.butter(3, 0.5)) + >>> t, y = signal.dimpulse(butter, n=25) + >>> plt.step(t, np.squeeze(y)) + >>> plt.grid() + >>> plt.xlabel('n [samples]') + >>> plt.ylabel('Amplitude') + + """ + # Convert system to dlti-StateSpace + if isinstance(system, dlti): + system = system._as_ss() + elif isinstance(system, lti): + raise AttributeError('dimpulse can only be used with discrete-time ' + 'dlti systems.') + else: + system = dlti(*system[:-1], dt=system[-1])._as_ss() + + # Default to 100 samples if unspecified + if n is None: + n = 100 + + # If time is not specified, use the number of samples + # and system dt + if t is None: + t = np.linspace(0, n * system.dt, n, endpoint=False) + else: + t = np.asarray(t) + + # For each input, implement a step change + yout = None + for i in range(0, system.inputs): + u = np.zeros((t.shape[0], system.inputs)) + u[0, i] = 1.0 + + one_output = dlsim(system, u, t=t, x0=x0) + + if yout is None: + yout = (one_output[1],) + else: + yout = yout + (one_output[1],) + + tout = one_output[0] + + return tout, yout + + +def dstep(system, x0=None, t=None, n=None): + """ + Step response of discrete-time system. + + Parameters + ---------- + system : tuple of array_like + A tuple describing the system. + The following gives the number of elements in the tuple and + the interpretation: + + * 1: (instance of `dlti`) + * 3: (num, den, dt) + * 4: (zeros, poles, gain, dt) + * 5: (A, B, C, D, dt) + + x0 : array_like, optional + Initial state-vector. Defaults to zero. + t : array_like, optional + Time points. Computed if not given. + n : int, optional + The number of time points to compute (if `t` is not given). + + Returns + ------- + tout : ndarray + Output time points, as a 1-D array. + yout : tuple of ndarray + Step response of system. Each element of the tuple represents + the output of the system based on a step response to each input. + + See Also + -------- + step, dimpulse, dlsim, cont2discrete + + Examples + -------- + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + + >>> butter = signal.dlti(*signal.butter(3, 0.5)) + >>> t, y = signal.dstep(butter, n=25) + >>> plt.step(t, np.squeeze(y)) + >>> plt.grid() + >>> plt.xlabel('n [samples]') + >>> plt.ylabel('Amplitude') + """ + # Convert system to dlti-StateSpace + if isinstance(system, dlti): + system = system._as_ss() + elif isinstance(system, lti): + raise AttributeError('dstep can only be used with discrete-time dlti ' + 'systems.') + else: + system = dlti(*system[:-1], dt=system[-1])._as_ss() + + # Default to 100 samples if unspecified + if n is None: + n = 100 + + # If time is not specified, use the number of samples + # and system dt + if t is None: + t = np.linspace(0, n * system.dt, n, endpoint=False) + else: + t = np.asarray(t) + + # For each input, implement a step change + yout = None + for i in range(0, system.inputs): + u = np.zeros((t.shape[0], system.inputs)) + u[:, i] = np.ones((t.shape[0],)) + + one_output = dlsim(system, u, t=t, x0=x0) + + if yout is None: + yout = (one_output[1],) + else: + yout = yout + (one_output[1],) + + tout = one_output[0] + + return tout, yout + + +def dfreqresp(system, w=None, n=10000, whole=False): + r""" + Calculate the frequency response of a discrete-time system. + + Parameters + ---------- + system : an instance of the `dlti` class or a tuple describing the system. + The following gives the number of elements in the tuple and + the interpretation: + + * 1 (instance of `dlti`) + * 2 (numerator, denominator, dt) + * 3 (zeros, poles, gain, dt) + * 4 (A, B, C, D, dt) + + w : array_like, optional + Array of frequencies (in radians/sample). Magnitude and phase data is + calculated for every value in this array. If not given a reasonable + set will be calculated. + n : int, optional + Number of frequency points to compute if `w` is not given. The `n` + frequencies are logarithmically spaced in an interval chosen to + include the influence of the poles and zeros of the system. + whole : bool, optional + Normally, if 'w' is not given, frequencies are computed from 0 to the + Nyquist frequency, pi radians/sample (upper-half of unit-circle). If + `whole` is True, compute frequencies from 0 to 2*pi radians/sample. + + Returns + ------- + w : 1D ndarray + Frequency array [radians/sample] + H : 1D ndarray + Array of complex magnitude values + + Notes + ----- + If (num, den) is passed in for ``system``, coefficients for both the + numerator and denominator should be specified in descending exponent + order (e.g. ``z^2 + 3z + 5`` would be represented as ``[1, 3, 5]``). + + .. versionadded:: 0.18.0 + + Examples + -------- + Generating the Nyquist plot of a transfer function + + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + + Construct the transfer function + :math:`H(z) = \frac{1}{z^2 + 2z + 3}` with a sampling time of 0.05 + seconds: + + >>> sys = signal.TransferFunction([1], [1, 2, 3], dt=0.05) + + >>> w, H = signal.dfreqresp(sys) + + >>> plt.figure() + >>> plt.plot(H.real, H.imag, "b") + >>> plt.plot(H.real, -H.imag, "r") + >>> plt.show() + + """ + if not isinstance(system, dlti): + if isinstance(system, lti): + raise AttributeError('dfreqresp can only be used with ' + 'discrete-time systems.') + + system = dlti(*system[:-1], dt=system[-1]) + + if isinstance(system, StateSpace): + # No SS->ZPK code exists right now, just SS->TF->ZPK + system = system._as_tf() + + if not isinstance(system, (TransferFunction, ZerosPolesGain)): + raise ValueError('Unknown system type') + + if system.inputs != 1 or system.outputs != 1: + raise ValueError("dfreqresp requires a SISO (single input, single " + "output) system.") + + if w is not None: + worN = w + else: + worN = n + + if isinstance(system, TransferFunction): + # Convert numerator and denominator from polynomials in the variable + # 'z' to polynomials in the variable 'z^-1', as freqz expects. + num, den = TransferFunction._z_to_zinv(system.num.ravel(), system.den) + w, h = freqz(num, den, worN=worN, whole=whole) + + elif isinstance(system, ZerosPolesGain): + w, h = freqz_zpk(system.zeros, system.poles, system.gain, worN=worN, + whole=whole) + + return w, h + + +def dbode(system, w=None, n=100): + r""" + Calculate Bode magnitude and phase data of a discrete-time system. + + Parameters + ---------- + system : + An instance of the LTI class `dlti` or a tuple describing the system. + The number of elements in the tuple determine the interpretation, i.e.: + + 1. ``(sys_dlti)``: Instance of LTI class `dlti`. Note that derived instances, + such as instances of `TransferFunction`, `ZerosPolesGain`, or `StateSpace`, + are allowed as well. + 2. ``(num, den, dt)``: Rational polynomial as described in `TransferFunction`. + The coefficients of the polynomials should be specified in descending + exponent order, e.g., z² + 3z + 5 would be represented as ``[1, 3, 5]``. + 3. ``(zeros, poles, gain, dt)``: Zeros, poles, gain form as described + in `ZerosPolesGain`. + 4. ``(A, B, C, D, dt)``: State-space form as described in `StateSpace`. + + w : array_like, optional + Array of frequencies normalized to the Nyquist frequency being π, i.e., + having unit radiant / sample. Magnitude and phase data is calculated for every + value in this array. If not given, a reasonable set will be calculated. + n : int, optional + Number of frequency points to compute if `w` is not given. The `n` + frequencies are logarithmically spaced in an interval chosen to + include the influence of the poles and zeros of the system. + + Returns + ------- + w : 1D ndarray + Array of frequencies normalized to the Nyquist frequency being ``np.pi/dt`` + with ``dt`` being the sampling interval of the `system` parameter. + The unit is rad/s assuming ``dt`` is in seconds. + mag : 1D ndarray + Magnitude array in dB + phase : 1D ndarray + Phase array in degrees + + Notes + ----- + This function is a convenience wrapper around `dfreqresp` for extracting + magnitude and phase from the calculated complex-valued amplitude of the + frequency response. + + .. versionadded:: 0.18.0 + + See Also + -------- + dfreqresp, dlti, TransferFunction, ZerosPolesGain, StateSpace + + + Examples + -------- + The following example shows how to create a Bode plot of a 5-th order + Butterworth lowpass filter with a corner frequency of 100 Hz: + + >>> import matplotlib.pyplot as plt + >>> import numpy as np + >>> from scipy import signal + ... + >>> T = 1e-4 # sampling interval in s + >>> f_c, o = 1e2, 5 # corner frequency in Hz (i.e., -3 dB value) and filter order + >>> bb, aa = signal.butter(o, f_c, 'lowpass', fs=1/T) + ... + >>> w, mag, phase = signal.dbode((bb, aa, T)) + >>> w /= 2*np.pi # convert unit of frequency into Hertz + ... + >>> fg, (ax0, ax1) = plt.subplots(2, 1, sharex='all', figsize=(5, 4), + ... tight_layout=True) + >>> ax0.set_title("Bode Plot of Butterworth Lowpass Filter " + + ... rf"($f_c={f_c:g}\,$Hz, order={o})") + >>> ax0.set_ylabel(r"Magnitude in dB") + >>> ax1.set(ylabel=r"Phase in Degrees", + ... xlabel="Frequency $f$ in Hertz", xlim=(w[1], w[-1])) + >>> ax0.semilogx(w, mag, 'C0-', label=r"$20\,\log_{10}|G(f)|$") # Magnitude plot + >>> ax1.semilogx(w, phase, 'C1-', label=r"$\angle G(f)$") # Phase plot + ... + >>> for ax_ in (ax0, ax1): + ... ax_.axvline(f_c, color='m', alpha=0.25, label=rf"${f_c=:g}\,$Hz") + ... ax_.grid(which='both', axis='x') # plot major & minor vertical grid lines + ... ax_.grid(which='major', axis='y') + ... ax_.legend() + >>> plt.show() + """ + w, y = dfreqresp(system, w=w, n=n) + + if isinstance(system, dlti): + dt = system.dt + else: + dt = system[-1] + + mag = 20.0 * np.log10(abs(y)) + phase = np.rad2deg(np.unwrap(np.angle(y))) + + return w / dt, mag, phase diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_max_len_seq.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_max_len_seq.py new file mode 100644 index 0000000000000000000000000000000000000000..4d64beaca86d1da50b563668679b6fc52c954ab0 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_max_len_seq.py @@ -0,0 +1,139 @@ +# Author: Eric Larson +# 2014 + +"""Tools for MLS generation""" + +import numpy as np + +from ._max_len_seq_inner import _max_len_seq_inner + +__all__ = ['max_len_seq'] + + +# These are definitions of linear shift register taps for use in max_len_seq() +_mls_taps = {2: [1], 3: [2], 4: [3], 5: [3], 6: [5], 7: [6], 8: [7, 6, 1], + 9: [5], 10: [7], 11: [9], 12: [11, 10, 4], 13: [12, 11, 8], + 14: [13, 12, 2], 15: [14], 16: [15, 13, 4], 17: [14], + 18: [11], 19: [18, 17, 14], 20: [17], 21: [19], 22: [21], + 23: [18], 24: [23, 22, 17], 25: [22], 26: [25, 24, 20], + 27: [26, 25, 22], 28: [25], 29: [27], 30: [29, 28, 7], + 31: [28], 32: [31, 30, 10]} + +def max_len_seq(nbits, state=None, length=None, taps=None): + """ + Maximum length sequence (MLS) generator. + + Parameters + ---------- + nbits : int + Number of bits to use. Length of the resulting sequence will + be ``(2**nbits) - 1``. Note that generating long sequences + (e.g., greater than ``nbits == 16``) can take a long time. + state : array_like, optional + If array, must be of length ``nbits``, and will be cast to binary + (bool) representation. If None, a seed of ones will be used, + producing a repeatable representation. If ``state`` is all + zeros, an error is raised as this is invalid. Default: None. + length : int, optional + Number of samples to compute. If None, the entire length + ``(2**nbits) - 1`` is computed. + taps : array_like, optional + Polynomial taps to use (e.g., ``[7, 6, 1]`` for an 8-bit sequence). + If None, taps will be automatically selected (for up to + ``nbits == 32``). + + Returns + ------- + seq : array + Resulting MLS sequence of 0's and 1's. + state : array + The final state of the shift register. + + Notes + ----- + The algorithm for MLS generation is generically described in: + + https://en.wikipedia.org/wiki/Maximum_length_sequence + + The default values for taps are specifically taken from the first + option listed for each value of ``nbits`` in: + + https://web.archive.org/web/20181001062252/http://www.newwaveinstruments.com/resources/articles/m_sequence_linear_feedback_shift_register_lfsr.htm + + .. versionadded:: 0.15.0 + + Examples + -------- + MLS uses binary convention: + + >>> from scipy.signal import max_len_seq + >>> max_len_seq(4)[0] + array([1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0], dtype=int8) + + MLS has a white spectrum (except for DC): + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from numpy.fft import fft, ifft, fftshift, fftfreq + >>> seq = max_len_seq(6)[0]*2-1 # +1 and -1 + >>> spec = fft(seq) + >>> N = len(seq) + >>> plt.plot(fftshift(fftfreq(N)), fftshift(np.abs(spec)), '.-') + >>> plt.margins(0.1, 0.1) + >>> plt.grid(True) + >>> plt.show() + + Circular autocorrelation of MLS is an impulse: + + >>> acorrcirc = ifft(spec * np.conj(spec)).real + >>> plt.figure() + >>> plt.plot(np.arange(-N/2+1, N/2+1), fftshift(acorrcirc), '.-') + >>> plt.margins(0.1, 0.1) + >>> plt.grid(True) + >>> plt.show() + + Linear autocorrelation of MLS is approximately an impulse: + + >>> acorr = np.correlate(seq, seq, 'full') + >>> plt.figure() + >>> plt.plot(np.arange(-N+1, N), acorr, '.-') + >>> plt.margins(0.1, 0.1) + >>> plt.grid(True) + >>> plt.show() + + """ + taps_dtype = np.int32 if np.intp().itemsize == 4 else np.int64 + if taps is None: + if nbits not in _mls_taps: + known_taps = np.array(list(_mls_taps.keys())) + raise ValueError(f'nbits must be between {known_taps.min()} and ' + f'{known_taps.max()} if taps is None') + taps = np.array(_mls_taps[nbits], taps_dtype) + else: + taps = np.unique(np.array(taps, taps_dtype))[::-1] + if np.any(taps < 0) or np.any(taps > nbits) or taps.size < 1: + raise ValueError('taps must be non-empty with values between ' + 'zero and nbits (inclusive)') + taps = np.array(taps) # needed for Cython and Pythran + n_max = (2**nbits) - 1 + if length is None: + length = n_max + else: + length = int(length) + if length < 0: + raise ValueError('length must be greater than or equal to 0') + # We use int8 instead of bool here because NumPy arrays of bools + # don't seem to work nicely with Cython + if state is None: + state = np.ones(nbits, dtype=np.int8, order='c') + else: + # makes a copy if need be, ensuring it's 0's and 1's + state = np.array(state, dtype=bool, order='c').astype(np.int8) + if state.ndim != 1 or state.size != nbits: + raise ValueError('state must be a 1-D array of size nbits') + if np.all(state == 0): + raise ValueError('state must not be all zeros') + + seq = np.empty(length, dtype=np.int8, order='c') + state = _max_len_seq_inner(taps, state, nbits, length, seq) + return seq, state diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_max_len_seq_inner.cpython-310-x86_64-linux-gnu.so b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_max_len_seq_inner.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..4eb7c7b2a3b658919f14450c20cad1e612a327d7 Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_max_len_seq_inner.cpython-310-x86_64-linux-gnu.so differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_peak_finding.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_peak_finding.py new file mode 100644 index 0000000000000000000000000000000000000000..ccbeca5b7a4839bbc28e9c1cfd1ebd1d028a82cf --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_peak_finding.py @@ -0,0 +1,1310 @@ +""" +Functions for identifying peaks in signals. +""" +import math +import numpy as np + +from scipy.signal._wavelets import _cwt, _ricker +from scipy.stats import scoreatpercentile + +from ._peak_finding_utils import ( + _local_maxima_1d, + _select_by_peak_distance, + _peak_prominences, + _peak_widths +) + + +__all__ = ['argrelmin', 'argrelmax', 'argrelextrema', 'peak_prominences', + 'peak_widths', 'find_peaks', 'find_peaks_cwt'] + + +def _boolrelextrema(data, comparator, axis=0, order=1, mode='clip'): + """ + Calculate the relative extrema of `data`. + + Relative extrema are calculated by finding locations where + ``comparator(data[n], data[n+1:n+order+1])`` is True. + + Parameters + ---------- + data : ndarray + Array in which to find the relative extrema. + comparator : callable + Function to use to compare two data points. + Should take two arrays as arguments. + axis : int, optional + Axis over which to select from `data`. Default is 0. + order : int, optional + How many points on each side to use for the comparison + to consider ``comparator(n,n+x)`` to be True. + mode : str, optional + How the edges of the vector are treated. 'wrap' (wrap around) or + 'clip' (treat overflow as the same as the last (or first) element). + Default 'clip'. See numpy.take. + + Returns + ------- + extrema : ndarray + Boolean array of the same shape as `data` that is True at an extrema, + False otherwise. + + See also + -------- + argrelmax, argrelmin + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal._peak_finding import _boolrelextrema + >>> testdata = np.array([1,2,3,2,1]) + >>> _boolrelextrema(testdata, np.greater, axis=0) + array([False, False, True, False, False], dtype=bool) + + """ + if (int(order) != order) or (order < 1): + raise ValueError('Order must be an int >= 1') + + datalen = data.shape[axis] + locs = np.arange(0, datalen) + + results = np.ones(data.shape, dtype=bool) + main = data.take(locs, axis=axis, mode=mode) + for shift in range(1, order + 1): + plus = data.take(locs + shift, axis=axis, mode=mode) + minus = data.take(locs - shift, axis=axis, mode=mode) + results &= comparator(main, plus) + results &= comparator(main, minus) + if ~results.any(): + return results + return results + + +def argrelmin(data, axis=0, order=1, mode='clip'): + """ + Calculate the relative minima of `data`. + + Parameters + ---------- + data : ndarray + Array in which to find the relative minima. + axis : int, optional + Axis over which to select from `data`. Default is 0. + order : int, optional + How many points on each side to use for the comparison + to consider ``comparator(n, n+x)`` to be True. + mode : str, optional + How the edges of the vector are treated. + Available options are 'wrap' (wrap around) or 'clip' (treat overflow + as the same as the last (or first) element). + Default 'clip'. See numpy.take. + + Returns + ------- + extrema : tuple of ndarrays + Indices of the minima in arrays of integers. ``extrema[k]`` is + the array of indices of axis `k` of `data`. Note that the + return value is a tuple even when `data` is 1-D. + + See Also + -------- + argrelextrema, argrelmax, find_peaks + + Notes + ----- + This function uses `argrelextrema` with np.less as comparator. Therefore, it + requires a strict inequality on both sides of a value to consider it a + minimum. This means flat minima (more than one sample wide) are not detected. + In case of 1-D `data` `find_peaks` can be used to detect all + local minima, including flat ones, by calling it with negated `data`. + + .. versionadded:: 0.11.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal import argrelmin + >>> x = np.array([2, 1, 2, 3, 2, 0, 1, 0]) + >>> argrelmin(x) + (array([1, 5]),) + >>> y = np.array([[1, 2, 1, 2], + ... [2, 2, 0, 0], + ... [5, 3, 4, 4]]) + ... + >>> argrelmin(y, axis=1) + (array([0, 2]), array([2, 1])) + + """ + return argrelextrema(data, np.less, axis, order, mode) + + +def argrelmax(data, axis=0, order=1, mode='clip'): + """ + Calculate the relative maxima of `data`. + + Parameters + ---------- + data : ndarray + Array in which to find the relative maxima. + axis : int, optional + Axis over which to select from `data`. Default is 0. + order : int, optional + How many points on each side to use for the comparison + to consider ``comparator(n, n+x)`` to be True. + mode : str, optional + How the edges of the vector are treated. + Available options are 'wrap' (wrap around) or 'clip' (treat overflow + as the same as the last (or first) element). + Default 'clip'. See `numpy.take`. + + Returns + ------- + extrema : tuple of ndarrays + Indices of the maxima in arrays of integers. ``extrema[k]`` is + the array of indices of axis `k` of `data`. Note that the + return value is a tuple even when `data` is 1-D. + + See Also + -------- + argrelextrema, argrelmin, find_peaks + + Notes + ----- + This function uses `argrelextrema` with np.greater as comparator. Therefore, + it requires a strict inequality on both sides of a value to consider it a + maximum. This means flat maxima (more than one sample wide) are not detected. + In case of 1-D `data` `find_peaks` can be used to detect all + local maxima, including flat ones. + + .. versionadded:: 0.11.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal import argrelmax + >>> x = np.array([2, 1, 2, 3, 2, 0, 1, 0]) + >>> argrelmax(x) + (array([3, 6]),) + >>> y = np.array([[1, 2, 1, 2], + ... [2, 2, 0, 0], + ... [5, 3, 4, 4]]) + ... + >>> argrelmax(y, axis=1) + (array([0]), array([1])) + """ + return argrelextrema(data, np.greater, axis, order, mode) + + +def argrelextrema(data, comparator, axis=0, order=1, mode='clip'): + """ + Calculate the relative extrema of `data`. + + Parameters + ---------- + data : ndarray + Array in which to find the relative extrema. + comparator : callable + Function to use to compare two data points. + Should take two arrays as arguments. + axis : int, optional + Axis over which to select from `data`. Default is 0. + order : int, optional + How many points on each side to use for the comparison + to consider ``comparator(n, n+x)`` to be True. + mode : str, optional + How the edges of the vector are treated. 'wrap' (wrap around) or + 'clip' (treat overflow as the same as the last (or first) element). + Default is 'clip'. See `numpy.take`. + + Returns + ------- + extrema : tuple of ndarrays + Indices of the maxima in arrays of integers. ``extrema[k]`` is + the array of indices of axis `k` of `data`. Note that the + return value is a tuple even when `data` is 1-D. + + See Also + -------- + argrelmin, argrelmax + + Notes + ----- + + .. versionadded:: 0.11.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal import argrelextrema + >>> x = np.array([2, 1, 2, 3, 2, 0, 1, 0]) + >>> argrelextrema(x, np.greater) + (array([3, 6]),) + >>> y = np.array([[1, 2, 1, 2], + ... [2, 2, 0, 0], + ... [5, 3, 4, 4]]) + ... + >>> argrelextrema(y, np.less, axis=1) + (array([0, 2]), array([2, 1])) + + """ + results = _boolrelextrema(data, comparator, + axis, order, mode) + return np.nonzero(results) + + +def _arg_x_as_expected(value): + """Ensure argument `x` is a 1-D C-contiguous array of dtype('float64'). + + Used in `find_peaks`, `peak_prominences` and `peak_widths` to make `x` + compatible with the signature of the wrapped Cython functions. + + Returns + ------- + value : ndarray + A 1-D C-contiguous array with dtype('float64'). + """ + value = np.asarray(value, order='C', dtype=np.float64) + if value.ndim != 1: + raise ValueError('`x` must be a 1-D array') + return value + + +def _arg_peaks_as_expected(value): + """Ensure argument `peaks` is a 1-D C-contiguous array of dtype('intp'). + + Used in `peak_prominences` and `peak_widths` to make `peaks` compatible + with the signature of the wrapped Cython functions. + + Returns + ------- + value : ndarray + A 1-D C-contiguous array with dtype('intp'). + """ + value = np.asarray(value) + if value.size == 0: + # Empty arrays default to np.float64 but are valid input + value = np.array([], dtype=np.intp) + try: + # Safely convert to C-contiguous array of type np.intp + value = value.astype(np.intp, order='C', casting='safe', + subok=False, copy=False) + except TypeError as e: + raise TypeError("cannot safely cast `peaks` to dtype('intp')") from e + if value.ndim != 1: + raise ValueError('`peaks` must be a 1-D array') + return value + + +def _arg_wlen_as_expected(value): + """Ensure argument `wlen` is of type `np.intp` and larger than 1. + + Used in `peak_prominences` and `peak_widths`. + + Returns + ------- + value : np.intp + The original `value` rounded up to an integer or -1 if `value` was + None. + """ + if value is None: + # _peak_prominences expects an intp; -1 signals that no value was + # supplied by the user + value = -1 + elif 1 < value: + # Round up to a positive integer + if isinstance(value, float): + value = math.ceil(value) + value = np.intp(value) + else: + raise ValueError(f'`wlen` must be larger than 1, was {value}') + return value + + +def peak_prominences(x, peaks, wlen=None): + """ + Calculate the prominence of each peak in a signal. + + The prominence of a peak measures how much a peak stands out from the + surrounding baseline of the signal and is defined as the vertical distance + between the peak and its lowest contour line. + + Parameters + ---------- + x : sequence + A signal with peaks. + peaks : sequence + Indices of peaks in `x`. + wlen : int, optional + A window length in samples that optionally limits the evaluated area for + each peak to a subset of `x`. The peak is always placed in the middle of + the window therefore the given length is rounded up to the next odd + integer. This parameter can speed up the calculation (see Notes). + + Returns + ------- + prominences : ndarray + The calculated prominences for each peak in `peaks`. + left_bases, right_bases : ndarray + The peaks' bases as indices in `x` to the left and right of each peak. + The higher base of each pair is a peak's lowest contour line. + + Raises + ------ + ValueError + If a value in `peaks` is an invalid index for `x`. + + Warns + ----- + PeakPropertyWarning + For indices in `peaks` that don't point to valid local maxima in `x`, + the returned prominence will be 0 and this warning is raised. This + also happens if `wlen` is smaller than the plateau size of a peak. + + Warnings + -------- + This function may return unexpected results for data containing NaNs. To + avoid this, NaNs should either be removed or replaced. + + See Also + -------- + find_peaks + Find peaks inside a signal based on peak properties. + peak_widths + Calculate the width of peaks. + + Notes + ----- + Strategy to compute a peak's prominence: + + 1. Extend a horizontal line from the current peak to the left and right + until the line either reaches the window border (see `wlen`) or + intersects the signal again at the slope of a higher peak. An + intersection with a peak of the same height is ignored. + 2. On each side find the minimal signal value within the interval defined + above. These points are the peak's bases. + 3. The higher one of the two bases marks the peak's lowest contour line. The + prominence can then be calculated as the vertical difference between the + peaks height itself and its lowest contour line. + + Searching for the peak's bases can be slow for large `x` with periodic + behavior because large chunks or even the full signal need to be evaluated + for the first algorithmic step. This evaluation area can be limited with the + parameter `wlen` which restricts the algorithm to a window around the + current peak and can shorten the calculation time if the window length is + short in relation to `x`. + However, this may stop the algorithm from finding the true global contour + line if the peak's true bases are outside this window. Instead, a higher + contour line is found within the restricted window leading to a smaller + calculated prominence. In practice, this is only relevant for the highest set + of peaks in `x`. This behavior may even be used intentionally to calculate + "local" prominences. + + .. versionadded:: 1.1.0 + + References + ---------- + .. [1] Wikipedia Article for Topographic Prominence: + https://en.wikipedia.org/wiki/Topographic_prominence + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal import find_peaks, peak_prominences + >>> import matplotlib.pyplot as plt + + Create a test signal with two overlaid harmonics + + >>> x = np.linspace(0, 6 * np.pi, 1000) + >>> x = np.sin(x) + 0.6 * np.sin(2.6 * x) + + Find all peaks and calculate prominences + + >>> peaks, _ = find_peaks(x) + >>> prominences = peak_prominences(x, peaks)[0] + >>> prominences + array([1.24159486, 0.47840168, 0.28470524, 3.10716793, 0.284603 , + 0.47822491, 2.48340261, 0.47822491]) + + Calculate the height of each peak's contour line and plot the results + + >>> contour_heights = x[peaks] - prominences + >>> plt.plot(x) + >>> plt.plot(peaks, x[peaks], "x") + >>> plt.vlines(x=peaks, ymin=contour_heights, ymax=x[peaks]) + >>> plt.show() + + Let's evaluate a second example that demonstrates several edge cases for + one peak at index 5. + + >>> x = np.array([0, 1, 0, 3, 1, 3, 0, 4, 0]) + >>> peaks = np.array([5]) + >>> plt.plot(x) + >>> plt.plot(peaks, x[peaks], "x") + >>> plt.show() + >>> peak_prominences(x, peaks) # -> (prominences, left_bases, right_bases) + (array([3.]), array([2]), array([6])) + + Note how the peak at index 3 of the same height is not considered as a + border while searching for the left base. Instead, two minima at 0 and 2 + are found in which case the one closer to the evaluated peak is always + chosen. On the right side, however, the base must be placed at 6 because the + higher peak represents the right border to the evaluated area. + + >>> peak_prominences(x, peaks, wlen=3.1) + (array([2.]), array([4]), array([6])) + + Here, we restricted the algorithm to a window from 3 to 7 (the length is 5 + samples because `wlen` was rounded up to the next odd integer). Thus, the + only two candidates in the evaluated area are the two neighboring samples + and a smaller prominence is calculated. + """ + x = _arg_x_as_expected(x) + peaks = _arg_peaks_as_expected(peaks) + wlen = _arg_wlen_as_expected(wlen) + return _peak_prominences(x, peaks, wlen) + + +def peak_widths(x, peaks, rel_height=0.5, prominence_data=None, wlen=None): + """ + Calculate the width of each peak in a signal. + + This function calculates the width of a peak in samples at a relative + distance to the peak's height and prominence. + + Parameters + ---------- + x : sequence + A signal with peaks. + peaks : sequence + Indices of peaks in `x`. + rel_height : float, optional + Chooses the relative height at which the peak width is measured as a + percentage of its prominence. 1.0 calculates the width of the peak at + its lowest contour line while 0.5 evaluates at half the prominence + height. Must be at least 0. See notes for further explanation. + prominence_data : tuple, optional + A tuple of three arrays matching the output of `peak_prominences` when + called with the same arguments `x` and `peaks`. This data are calculated + internally if not provided. + wlen : int, optional + A window length in samples passed to `peak_prominences` as an optional + argument for internal calculation of `prominence_data`. This argument + is ignored if `prominence_data` is given. + + Returns + ------- + widths : ndarray + The widths for each peak in samples. + width_heights : ndarray + The height of the contour lines at which the `widths` where evaluated. + left_ips, right_ips : ndarray + Interpolated positions of left and right intersection points of a + horizontal line at the respective evaluation height. + + Raises + ------ + ValueError + If `prominence_data` is supplied but doesn't satisfy the condition + ``0 <= left_base <= peak <= right_base < x.shape[0]`` for each peak, + has the wrong dtype, is not C-contiguous or does not have the same + shape. + + Warns + ----- + PeakPropertyWarning + Raised if any calculated width is 0. This may stem from the supplied + `prominence_data` or if `rel_height` is set to 0. + + Warnings + -------- + This function may return unexpected results for data containing NaNs. To + avoid this, NaNs should either be removed or replaced. + + See Also + -------- + find_peaks + Find peaks inside a signal based on peak properties. + peak_prominences + Calculate the prominence of peaks. + + Notes + ----- + The basic algorithm to calculate a peak's width is as follows: + + * Calculate the evaluation height :math:`h_{eval}` with the formula + :math:`h_{eval} = h_{Peak} - P \\cdot R`, where :math:`h_{Peak}` is the + height of the peak itself, :math:`P` is the peak's prominence and + :math:`R` a positive ratio specified with the argument `rel_height`. + * Draw a horizontal line at the evaluation height to both sides, starting at + the peak's current vertical position until the lines either intersect a + slope, the signal border or cross the vertical position of the peak's + base (see `peak_prominences` for an definition). For the first case, + intersection with the signal, the true intersection point is estimated + with linear interpolation. + * Calculate the width as the horizontal distance between the chosen + endpoints on both sides. As a consequence of this the maximal possible + width for each peak is the horizontal distance between its bases. + + As shown above to calculate a peak's width its prominence and bases must be + known. You can supply these yourself with the argument `prominence_data`. + Otherwise, they are internally calculated (see `peak_prominences`). + + .. versionadded:: 1.1.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal import chirp, find_peaks, peak_widths + >>> import matplotlib.pyplot as plt + + Create a test signal with two overlaid harmonics + + >>> x = np.linspace(0, 6 * np.pi, 1000) + >>> x = np.sin(x) + 0.6 * np.sin(2.6 * x) + + Find all peaks and calculate their widths at the relative height of 0.5 + (contour line at half the prominence height) and 1 (at the lowest contour + line at full prominence height). + + >>> peaks, _ = find_peaks(x) + >>> results_half = peak_widths(x, peaks, rel_height=0.5) + >>> results_half[0] # widths + array([ 64.25172825, 41.29465463, 35.46943289, 104.71586081, + 35.46729324, 41.30429622, 181.93835853, 45.37078546]) + >>> results_full = peak_widths(x, peaks, rel_height=1) + >>> results_full[0] # widths + array([181.9396084 , 72.99284945, 61.28657872, 373.84622694, + 61.78404617, 72.48822812, 253.09161876, 79.36860878]) + + Plot signal, peaks and contour lines at which the widths where calculated + + >>> plt.plot(x) + >>> plt.plot(peaks, x[peaks], "x") + >>> plt.hlines(*results_half[1:], color="C2") + >>> plt.hlines(*results_full[1:], color="C3") + >>> plt.show() + """ + x = _arg_x_as_expected(x) + peaks = _arg_peaks_as_expected(peaks) + if prominence_data is None: + # Calculate prominence if not supplied and use wlen if supplied. + wlen = _arg_wlen_as_expected(wlen) + prominence_data = _peak_prominences(x, peaks, wlen) + return _peak_widths(x, peaks, rel_height, *prominence_data) + + +def _unpack_condition_args(interval, x, peaks): + """ + Parse condition arguments for `find_peaks`. + + Parameters + ---------- + interval : number or ndarray or sequence + Either a number or ndarray or a 2-element sequence of the former. The + first value is always interpreted as `imin` and the second, if supplied, + as `imax`. + x : ndarray + The signal with `peaks`. + peaks : ndarray + An array with indices used to reduce `imin` and / or `imax` if those are + arrays. + + Returns + ------- + imin, imax : number or ndarray or None + Minimal and maximal value in `argument`. + + Raises + ------ + ValueError : + If interval border is given as array and its size does not match the size + of `x`. + + Notes + ----- + + .. versionadded:: 1.1.0 + """ + try: + imin, imax = interval + except (TypeError, ValueError): + imin, imax = (interval, None) + + # Reduce arrays if arrays + if isinstance(imin, np.ndarray): + if imin.size != x.size: + raise ValueError('array size of lower interval border must match x') + imin = imin[peaks] + if isinstance(imax, np.ndarray): + if imax.size != x.size: + raise ValueError('array size of upper interval border must match x') + imax = imax[peaks] + + return imin, imax + + +def _select_by_property(peak_properties, pmin, pmax): + """ + Evaluate where the generic property of peaks confirms to an interval. + + Parameters + ---------- + peak_properties : ndarray + An array with properties for each peak. + pmin : None or number or ndarray + Lower interval boundary for `peak_properties`. ``None`` is interpreted as + an open border. + pmax : None or number or ndarray + Upper interval boundary for `peak_properties`. ``None`` is interpreted as + an open border. + + Returns + ------- + keep : bool + A boolean mask evaluating to true where `peak_properties` confirms to the + interval. + + See Also + -------- + find_peaks + + Notes + ----- + + .. versionadded:: 1.1.0 + """ + keep = np.ones(peak_properties.size, dtype=bool) + if pmin is not None: + keep &= (pmin <= peak_properties) + if pmax is not None: + keep &= (peak_properties <= pmax) + return keep + + +def _select_by_peak_threshold(x, peaks, tmin, tmax): + """ + Evaluate which peaks fulfill the threshold condition. + + Parameters + ---------- + x : ndarray + A 1-D array which is indexable by `peaks`. + peaks : ndarray + Indices of peaks in `x`. + tmin, tmax : scalar or ndarray or None + Minimal and / or maximal required thresholds. If supplied as ndarrays + their size must match `peaks`. ``None`` is interpreted as an open + border. + + Returns + ------- + keep : bool + A boolean mask evaluating to true where `peaks` fulfill the threshold + condition. + left_thresholds, right_thresholds : ndarray + Array matching `peak` containing the thresholds of each peak on + both sides. + + Notes + ----- + + .. versionadded:: 1.1.0 + """ + # Stack thresholds on both sides to make min / max operations easier: + # tmin is compared with the smaller, and tmax with the greater threshold to + # each peak's side + stacked_thresholds = np.vstack([x[peaks] - x[peaks - 1], + x[peaks] - x[peaks + 1]]) + keep = np.ones(peaks.size, dtype=bool) + if tmin is not None: + min_thresholds = np.min(stacked_thresholds, axis=0) + keep &= (tmin <= min_thresholds) + if tmax is not None: + max_thresholds = np.max(stacked_thresholds, axis=0) + keep &= (max_thresholds <= tmax) + + return keep, stacked_thresholds[0], stacked_thresholds[1] + + +def find_peaks(x, height=None, threshold=None, distance=None, + prominence=None, width=None, wlen=None, rel_height=0.5, + plateau_size=None): + """ + Find peaks inside a signal based on peak properties. + + This function takes a 1-D array and finds all local maxima by + simple comparison of neighboring values. Optionally, a subset of these + peaks can be selected by specifying conditions for a peak's properties. + + Parameters + ---------- + x : sequence + A signal with peaks. + height : number or ndarray or sequence, optional + Required height of peaks. Either a number, ``None``, an array matching + `x` or a 2-element sequence of the former. The first element is + always interpreted as the minimal and the second, if supplied, as the + maximal required height. + threshold : number or ndarray or sequence, optional + Required threshold of peaks, the vertical distance to its neighboring + samples. Either a number, ``None``, an array matching `x` or a + 2-element sequence of the former. The first element is always + interpreted as the minimal and the second, if supplied, as the maximal + required threshold. + distance : number, optional + Required minimal horizontal distance (>= 1) in samples between + neighbouring peaks. Smaller peaks are removed first until the condition + is fulfilled for all remaining peaks. + prominence : number or ndarray or sequence, optional + Required prominence of peaks. Either a number, ``None``, an array + matching `x` or a 2-element sequence of the former. The first + element is always interpreted as the minimal and the second, if + supplied, as the maximal required prominence. + width : number or ndarray or sequence, optional + Required width of peaks in samples. Either a number, ``None``, an array + matching `x` or a 2-element sequence of the former. The first + element is always interpreted as the minimal and the second, if + supplied, as the maximal required width. + wlen : int, optional + Used for calculation of the peaks prominences, thus it is only used if + one of the arguments `prominence` or `width` is given. See argument + `wlen` in `peak_prominences` for a full description of its effects. + rel_height : float, optional + Used for calculation of the peaks width, thus it is only used if `width` + is given. See argument `rel_height` in `peak_widths` for a full + description of its effects. + plateau_size : number or ndarray or sequence, optional + Required size of the flat top of peaks in samples. Either a number, + ``None``, an array matching `x` or a 2-element sequence of the former. + The first element is always interpreted as the minimal and the second, + if supplied as the maximal required plateau size. + + .. versionadded:: 1.2.0 + + Returns + ------- + peaks : ndarray + Indices of peaks in `x` that satisfy all given conditions. + properties : dict + A dictionary containing properties of the returned peaks which were + calculated as intermediate results during evaluation of the specified + conditions: + + * 'peak_heights' + If `height` is given, the height of each peak in `x`. + * 'left_thresholds', 'right_thresholds' + If `threshold` is given, these keys contain a peaks vertical + distance to its neighbouring samples. + * 'prominences', 'right_bases', 'left_bases' + If `prominence` is given, these keys are accessible. See + `peak_prominences` for a description of their content. + * 'widths', 'width_heights', 'left_ips', 'right_ips' + If `width` is given, these keys are accessible. See `peak_widths` + for a description of their content. + * 'plateau_sizes', left_edges', 'right_edges' + If `plateau_size` is given, these keys are accessible and contain + the indices of a peak's edges (edges are still part of the + plateau) and the calculated plateau sizes. + + .. versionadded:: 1.2.0 + + To calculate and return properties without excluding peaks, provide the + open interval ``(None, None)`` as a value to the appropriate argument + (excluding `distance`). + + Warns + ----- + PeakPropertyWarning + Raised if a peak's properties have unexpected values (see + `peak_prominences` and `peak_widths`). + + Warnings + -------- + This function may return unexpected results for data containing NaNs. To + avoid this, NaNs should either be removed or replaced. + + See Also + -------- + find_peaks_cwt + Find peaks using the wavelet transformation. + peak_prominences + Directly calculate the prominence of peaks. + peak_widths + Directly calculate the width of peaks. + + Notes + ----- + In the context of this function, a peak or local maximum is defined as any + sample whose two direct neighbours have a smaller amplitude. For flat peaks + (more than one sample of equal amplitude wide) the index of the middle + sample is returned (rounded down in case the number of samples is even). + For noisy signals the peak locations can be off because the noise might + change the position of local maxima. In those cases consider smoothing the + signal before searching for peaks or use other peak finding and fitting + methods (like `find_peaks_cwt`). + + Some additional comments on specifying conditions: + + * Almost all conditions (excluding `distance`) can be given as half-open or + closed intervals, e.g., ``1`` or ``(1, None)`` defines the half-open + interval :math:`[1, \\infty]` while ``(None, 1)`` defines the interval + :math:`[-\\infty, 1]`. The open interval ``(None, None)`` can be specified + as well, which returns the matching properties without exclusion of peaks. + * The border is always included in the interval used to select valid peaks. + * For several conditions the interval borders can be specified with + arrays matching `x` in shape which enables dynamic constrains based on + the sample position. + * The conditions are evaluated in the following order: `plateau_size`, + `height`, `threshold`, `distance`, `prominence`, `width`. In most cases + this order is the fastest one because faster operations are applied first + to reduce the number of peaks that need to be evaluated later. + * While indices in `peaks` are guaranteed to be at least `distance` samples + apart, edges of flat peaks may be closer than the allowed `distance`. + * Use `wlen` to reduce the time it takes to evaluate the conditions for + `prominence` or `width` if `x` is large or has many local maxima + (see `peak_prominences`). + + .. versionadded:: 1.1.0 + + Examples + -------- + To demonstrate this function's usage we use a signal `x` supplied with + SciPy (see `scipy.datasets.electrocardiogram`). Let's find all peaks (local + maxima) in `x` whose amplitude lies above 0. + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.datasets import electrocardiogram + >>> from scipy.signal import find_peaks + >>> x = electrocardiogram()[2000:4000] + >>> peaks, _ = find_peaks(x, height=0) + >>> plt.plot(x) + >>> plt.plot(peaks, x[peaks], "x") + >>> plt.plot(np.zeros_like(x), "--", color="gray") + >>> plt.show() + + We can select peaks below 0 with ``height=(None, 0)`` or use arrays matching + `x` in size to reflect a changing condition for different parts of the + signal. + + >>> border = np.sin(np.linspace(0, 3 * np.pi, x.size)) + >>> peaks, _ = find_peaks(x, height=(-border, border)) + >>> plt.plot(x) + >>> plt.plot(-border, "--", color="gray") + >>> plt.plot(border, ":", color="gray") + >>> plt.plot(peaks, x[peaks], "x") + >>> plt.show() + + Another useful condition for periodic signals can be given with the + `distance` argument. In this case, we can easily select the positions of + QRS complexes within the electrocardiogram (ECG) by demanding a distance of + at least 150 samples. + + >>> peaks, _ = find_peaks(x, distance=150) + >>> np.diff(peaks) + array([186, 180, 177, 171, 177, 169, 167, 164, 158, 162, 172]) + >>> plt.plot(x) + >>> plt.plot(peaks, x[peaks], "x") + >>> plt.show() + + Especially for noisy signals peaks can be easily grouped by their + prominence (see `peak_prominences`). E.g., we can select all peaks except + for the mentioned QRS complexes by limiting the allowed prominence to 0.6. + + >>> peaks, properties = find_peaks(x, prominence=(None, 0.6)) + >>> properties["prominences"].max() + 0.5049999999999999 + >>> plt.plot(x) + >>> plt.plot(peaks, x[peaks], "x") + >>> plt.show() + + And, finally, let's examine a different section of the ECG which contains + beat forms of different shape. To select only the atypical heart beats, we + combine two conditions: a minimal prominence of 1 and width of at least 20 + samples. + + >>> x = electrocardiogram()[17000:18000] + >>> peaks, properties = find_peaks(x, prominence=1, width=20) + >>> properties["prominences"], properties["widths"] + (array([1.495, 2.3 ]), array([36.93773946, 39.32723577])) + >>> plt.plot(x) + >>> plt.plot(peaks, x[peaks], "x") + >>> plt.vlines(x=peaks, ymin=x[peaks] - properties["prominences"], + ... ymax = x[peaks], color = "C1") + >>> plt.hlines(y=properties["width_heights"], xmin=properties["left_ips"], + ... xmax=properties["right_ips"], color = "C1") + >>> plt.show() + """ + # _argmaxima1d expects array of dtype 'float64' + x = _arg_x_as_expected(x) + if distance is not None and distance < 1: + raise ValueError('`distance` must be greater or equal to 1') + + peaks, left_edges, right_edges = _local_maxima_1d(x) + properties = {} + + if plateau_size is not None: + # Evaluate plateau size + plateau_sizes = right_edges - left_edges + 1 + pmin, pmax = _unpack_condition_args(plateau_size, x, peaks) + keep = _select_by_property(plateau_sizes, pmin, pmax) + peaks = peaks[keep] + properties["plateau_sizes"] = plateau_sizes + properties["left_edges"] = left_edges + properties["right_edges"] = right_edges + properties = {key: array[keep] for key, array in properties.items()} + + if height is not None: + # Evaluate height condition + peak_heights = x[peaks] + hmin, hmax = _unpack_condition_args(height, x, peaks) + keep = _select_by_property(peak_heights, hmin, hmax) + peaks = peaks[keep] + properties["peak_heights"] = peak_heights + properties = {key: array[keep] for key, array in properties.items()} + + if threshold is not None: + # Evaluate threshold condition + tmin, tmax = _unpack_condition_args(threshold, x, peaks) + keep, left_thresholds, right_thresholds = _select_by_peak_threshold( + x, peaks, tmin, tmax) + peaks = peaks[keep] + properties["left_thresholds"] = left_thresholds + properties["right_thresholds"] = right_thresholds + properties = {key: array[keep] for key, array in properties.items()} + + if distance is not None: + # Evaluate distance condition + keep = _select_by_peak_distance(peaks, x[peaks], distance) + peaks = peaks[keep] + properties = {key: array[keep] for key, array in properties.items()} + + if prominence is not None or width is not None: + # Calculate prominence (required for both conditions) + wlen = _arg_wlen_as_expected(wlen) + properties.update(zip( + ['prominences', 'left_bases', 'right_bases'], + _peak_prominences(x, peaks, wlen=wlen) + )) + + if prominence is not None: + # Evaluate prominence condition + pmin, pmax = _unpack_condition_args(prominence, x, peaks) + keep = _select_by_property(properties['prominences'], pmin, pmax) + peaks = peaks[keep] + properties = {key: array[keep] for key, array in properties.items()} + + if width is not None: + # Calculate widths + properties.update(zip( + ['widths', 'width_heights', 'left_ips', 'right_ips'], + _peak_widths(x, peaks, rel_height, properties['prominences'], + properties['left_bases'], properties['right_bases']) + )) + # Evaluate width condition + wmin, wmax = _unpack_condition_args(width, x, peaks) + keep = _select_by_property(properties['widths'], wmin, wmax) + peaks = peaks[keep] + properties = {key: array[keep] for key, array in properties.items()} + + return peaks, properties + + +def _identify_ridge_lines(matr, max_distances, gap_thresh): + """ + Identify ridges in the 2-D matrix. + + Expect that the width of the wavelet feature increases with increasing row + number. + + Parameters + ---------- + matr : 2-D ndarray + Matrix in which to identify ridge lines. + max_distances : 1-D sequence + At each row, a ridge line is only connected + if the relative max at row[n] is within + `max_distances`[n] from the relative max at row[n+1]. + gap_thresh : int + If a relative maximum is not found within `max_distances`, + there will be a gap. A ridge line is discontinued if + there are more than `gap_thresh` points without connecting + a new relative maximum. + + Returns + ------- + ridge_lines : tuple + Tuple of 2 1-D sequences. `ridge_lines`[ii][0] are the rows of the + ii-th ridge-line, `ridge_lines`[ii][1] are the columns. Empty if none + found. Each ridge-line will be sorted by row (increasing), but the + order of the ridge lines is not specified. + + References + ---------- + .. [1] Bioinformatics (2006) 22 (17): 2059-2065. + :doi:`10.1093/bioinformatics/btl355` + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal._peak_finding import _identify_ridge_lines + >>> rng = np.random.default_rng() + >>> data = rng.random((5,5)) + >>> max_dist = 3 + >>> max_distances = np.full(20, max_dist) + >>> ridge_lines = _identify_ridge_lines(data, max_distances, 1) + + Notes + ----- + This function is intended to be used in conjunction with `cwt` + as part of `find_peaks_cwt`. + + """ + if len(max_distances) < matr.shape[0]: + raise ValueError('Max_distances must have at least as many rows ' + 'as matr') + + all_max_cols = _boolrelextrema(matr, np.greater, axis=1, order=1) + # Highest row for which there are any relative maxima + has_relmax = np.nonzero(all_max_cols.any(axis=1))[0] + if len(has_relmax) == 0: + return [] + start_row = has_relmax[-1] + # Each ridge line is a 3-tuple: + # rows, cols,Gap number + ridge_lines = [[[start_row], + [col], + 0] for col in np.nonzero(all_max_cols[start_row])[0]] + final_lines = [] + rows = np.arange(start_row - 1, -1, -1) + cols = np.arange(0, matr.shape[1]) + for row in rows: + this_max_cols = cols[all_max_cols[row]] + + # Increment gap number of each line, + # set it to zero later if appropriate + for line in ridge_lines: + line[2] += 1 + + # XXX These should always be all_max_cols[row] + # But the order might be different. Might be an efficiency gain + # to make sure the order is the same and avoid this iteration + prev_ridge_cols = np.array([line[1][-1] for line in ridge_lines]) + # Look through every relative maximum found at current row + # Attempt to connect them with existing ridge lines. + for ind, col in enumerate(this_max_cols): + # If there is a previous ridge line within + # the max_distance to connect to, do so. + # Otherwise start a new one. + line = None + if len(prev_ridge_cols) > 0: + diffs = np.abs(col - prev_ridge_cols) + closest = np.argmin(diffs) + if diffs[closest] <= max_distances[row]: + line = ridge_lines[closest] + if line is not None: + # Found a point close enough, extend current ridge line + line[1].append(col) + line[0].append(row) + line[2] = 0 + else: + new_line = [[row], + [col], + 0] + ridge_lines.append(new_line) + + # Remove the ridge lines with gap_number too high + # XXX Modifying a list while iterating over it. + # Should be safe, since we iterate backwards, but + # still tacky. + for ind in range(len(ridge_lines) - 1, -1, -1): + line = ridge_lines[ind] + if line[2] > gap_thresh: + final_lines.append(line) + del ridge_lines[ind] + + out_lines = [] + for line in (final_lines + ridge_lines): + sortargs = np.array(np.argsort(line[0])) + rows, cols = np.zeros_like(sortargs), np.zeros_like(sortargs) + rows[sortargs] = line[0] + cols[sortargs] = line[1] + out_lines.append([rows, cols]) + + return out_lines + + +def _filter_ridge_lines(cwt, ridge_lines, window_size=None, min_length=None, + min_snr=1, noise_perc=10): + """ + Filter ridge lines according to prescribed criteria. Intended + to be used for finding relative maxima. + + Parameters + ---------- + cwt : 2-D ndarray + Continuous wavelet transform from which the `ridge_lines` were defined. + ridge_lines : 1-D sequence + Each element should contain 2 sequences, the rows and columns + of the ridge line (respectively). + window_size : int, optional + Size of window to use to calculate noise floor. + Default is ``cwt.shape[1] / 20``. + min_length : int, optional + Minimum length a ridge line needs to be acceptable. + Default is ``cwt.shape[0] / 4``, ie 1/4-th the number of widths. + min_snr : float, optional + Minimum SNR ratio. Default 1. The signal is the value of + the cwt matrix at the shortest length scale (``cwt[0, loc]``), the + noise is the `noise_perc`\\ th percentile of datapoints contained within a + window of `window_size` around ``cwt[0, loc]``. + noise_perc : float, optional + When calculating the noise floor, percentile of data points + examined below which to consider noise. Calculated using + scipy.stats.scoreatpercentile. + + References + ---------- + .. [1] Bioinformatics (2006) 22 (17): 2059-2065. + :doi:`10.1093/bioinformatics/btl355` + + """ + num_points = cwt.shape[1] + if min_length is None: + min_length = np.ceil(cwt.shape[0] / 4) + if window_size is None: + window_size = np.ceil(num_points / 20) + + window_size = int(window_size) + hf_window, odd = divmod(window_size, 2) + + # Filter based on SNR + row_one = cwt[0, :] + noises = np.empty_like(row_one) + for ind, val in enumerate(row_one): + window_start = max(ind - hf_window, 0) + window_end = min(ind + hf_window + odd, num_points) + noises[ind] = scoreatpercentile(row_one[window_start:window_end], + per=noise_perc) + + def filt_func(line): + if len(line[0]) < min_length: + return False + snr = abs(cwt[line[0][0], line[1][0]] / noises[line[1][0]]) + if snr < min_snr: + return False + return True + + return list(filter(filt_func, ridge_lines)) + + +def find_peaks_cwt(vector, widths, wavelet=None, max_distances=None, + gap_thresh=None, min_length=None, + min_snr=1, noise_perc=10, window_size=None): + """ + Find peaks in a 1-D array with wavelet transformation. + + The general approach is to smooth `vector` by convolving it with + `wavelet(width)` for each width in `widths`. Relative maxima which + appear at enough length scales, and with sufficiently high SNR, are + accepted. + + Parameters + ---------- + vector : ndarray + 1-D array in which to find the peaks. + widths : float or sequence + Single width or 1-D array-like of widths to use for calculating + the CWT matrix. In general, + this range should cover the expected width of peaks of interest. + wavelet : callable, optional + Should take two parameters and return a 1-D array to convolve + with `vector`. The first parameter determines the number of points + of the returned wavelet array, the second parameter is the scale + (`width`) of the wavelet. Should be normalized and symmetric. + Default is the ricker wavelet. + max_distances : ndarray, optional + At each row, a ridge line is only connected if the relative max at + row[n] is within ``max_distances[n]`` from the relative max at + ``row[n+1]``. Default value is ``widths/4``. + gap_thresh : float, optional + If a relative maximum is not found within `max_distances`, + there will be a gap. A ridge line is discontinued if there are more + than `gap_thresh` points without connecting a new relative maximum. + Default is the first value of the widths array i.e. widths[0]. + min_length : int, optional + Minimum length a ridge line needs to be acceptable. + Default is ``cwt.shape[0] / 4``, ie 1/4-th the number of widths. + min_snr : float, optional + Minimum SNR ratio. Default 1. The signal is the maximum CWT coefficient + on the largest ridge line. The noise is `noise_perc` th percentile of + datapoints contained within the same ridge line. + noise_perc : float, optional + When calculating the noise floor, percentile of data points + examined below which to consider noise. Calculated using + `stats.scoreatpercentile`. Default is 10. + window_size : int, optional + Size of window to use to calculate noise floor. + Default is ``cwt.shape[1] / 20``. + + Returns + ------- + peaks_indices : ndarray + Indices of the locations in the `vector` where peaks were found. + The list is sorted. + + See Also + -------- + find_peaks + Find peaks inside a signal based on peak properties. + + Notes + ----- + This approach was designed for finding sharp peaks among noisy data, + however with proper parameter selection it should function well for + different peak shapes. + + The algorithm is as follows: + 1. Perform a continuous wavelet transform on `vector`, for the supplied + `widths`. This is a convolution of `vector` with `wavelet(width)` for + each width in `widths`. See `cwt`. + 2. Identify "ridge lines" in the cwt matrix. These are relative maxima + at each row, connected across adjacent rows. See identify_ridge_lines + 3. Filter the ridge_lines using filter_ridge_lines. + + .. versionadded:: 0.11.0 + + References + ---------- + .. [1] Bioinformatics (2006) 22 (17): 2059-2065. + :doi:`10.1093/bioinformatics/btl355` + + Examples + -------- + >>> import numpy as np + >>> from scipy import signal + >>> xs = np.arange(0, np.pi, 0.05) + >>> data = np.sin(xs) + >>> peakind = signal.find_peaks_cwt(data, np.arange(1,10)) + >>> peakind, xs[peakind], data[peakind] + ([32], array([ 1.6]), array([ 0.9995736])) + + """ + widths = np.atleast_1d(np.asarray(widths)) + + if gap_thresh is None: + gap_thresh = np.ceil(widths[0]) + if max_distances is None: + max_distances = widths / 4.0 + if wavelet is None: + wavelet = _ricker + + cwt_dat = _cwt(vector, wavelet, widths) + ridge_lines = _identify_ridge_lines(cwt_dat, max_distances, gap_thresh) + filtered = _filter_ridge_lines(cwt_dat, ridge_lines, min_length=min_length, + window_size=window_size, min_snr=min_snr, + noise_perc=noise_perc) + max_locs = np.asarray([x[1][0] for x in filtered]) + max_locs.sort() + + return max_locs diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_savitzky_golay.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_savitzky_golay.py new file mode 100644 index 0000000000000000000000000000000000000000..addcbe6951f8df093461c47848f8027dfdd406f2 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_savitzky_golay.py @@ -0,0 +1,357 @@ +import numpy as np +from scipy.linalg import lstsq +from scipy._lib._util import float_factorial +from scipy.ndimage import convolve1d # type: ignore[attr-defined] +from ._arraytools import axis_slice + + +def savgol_coeffs(window_length, polyorder, deriv=0, delta=1.0, pos=None, + use="conv"): + """Compute the coefficients for a 1-D Savitzky-Golay FIR filter. + + Parameters + ---------- + window_length : int + The length of the filter window (i.e., the number of coefficients). + polyorder : int + The order of the polynomial used to fit the samples. + `polyorder` must be less than `window_length`. + deriv : int, optional + The order of the derivative to compute. This must be a + nonnegative integer. The default is 0, which means to filter + the data without differentiating. + delta : float, optional + The spacing of the samples to which the filter will be applied. + This is only used if deriv > 0. + pos : int or None, optional + If pos is not None, it specifies evaluation position within the + window. The default is the middle of the window. + use : str, optional + Either 'conv' or 'dot'. This argument chooses the order of the + coefficients. The default is 'conv', which means that the + coefficients are ordered to be used in a convolution. With + use='dot', the order is reversed, so the filter is applied by + dotting the coefficients with the data set. + + Returns + ------- + coeffs : 1-D ndarray + The filter coefficients. + + See Also + -------- + savgol_filter + + Notes + ----- + .. versionadded:: 0.14.0 + + References + ---------- + A. Savitzky, M. J. E. Golay, Smoothing and Differentiation of Data by + Simplified Least Squares Procedures. Analytical Chemistry, 1964, 36 (8), + pp 1627-1639. + Jianwen Luo, Kui Ying, and Jing Bai. 2005. Savitzky-Golay smoothing and + differentiation filter for even number data. Signal Process. + 85, 7 (July 2005), 1429-1434. + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal import savgol_coeffs + >>> savgol_coeffs(5, 2) + array([-0.08571429, 0.34285714, 0.48571429, 0.34285714, -0.08571429]) + >>> savgol_coeffs(5, 2, deriv=1) + array([ 2.00000000e-01, 1.00000000e-01, 2.07548111e-16, -1.00000000e-01, + -2.00000000e-01]) + + Note that use='dot' simply reverses the coefficients. + + >>> savgol_coeffs(5, 2, pos=3) + array([ 0.25714286, 0.37142857, 0.34285714, 0.17142857, -0.14285714]) + >>> savgol_coeffs(5, 2, pos=3, use='dot') + array([-0.14285714, 0.17142857, 0.34285714, 0.37142857, 0.25714286]) + >>> savgol_coeffs(4, 2, pos=3, deriv=1, use='dot') + array([0.45, -0.85, -0.65, 1.05]) + + `x` contains data from the parabola x = t**2, sampled at + t = -1, 0, 1, 2, 3. `c` holds the coefficients that will compute the + derivative at the last position. When dotted with `x` the result should + be 6. + + >>> x = np.array([1, 0, 1, 4, 9]) + >>> c = savgol_coeffs(5, 2, pos=4, deriv=1, use='dot') + >>> c.dot(x) + 6.0 + """ + + # An alternative method for finding the coefficients when deriv=0 is + # t = np.arange(window_length) + # unit = (t == pos).astype(int) + # coeffs = np.polyval(np.polyfit(t, unit, polyorder), t) + # The method implemented here is faster. + + # To recreate the table of sample coefficients shown in the chapter on + # the Savitzy-Golay filter in the Numerical Recipes book, use + # window_length = nL + nR + 1 + # pos = nL + 1 + # c = savgol_coeffs(window_length, M, pos=pos, use='dot') + + if polyorder >= window_length: + raise ValueError("polyorder must be less than window_length.") + + halflen, rem = divmod(window_length, 2) + + if pos is None: + if rem == 0: + pos = halflen - 0.5 + else: + pos = halflen + + if not (0 <= pos < window_length): + raise ValueError("pos must be nonnegative and less than " + "window_length.") + + if use not in ['conv', 'dot']: + raise ValueError("`use` must be 'conv' or 'dot'") + + if deriv > polyorder: + coeffs = np.zeros(window_length) + return coeffs + + # Form the design matrix A. The columns of A are powers of the integers + # from -pos to window_length - pos - 1. The powers (i.e., rows) range + # from 0 to polyorder. (That is, A is a vandermonde matrix, but not + # necessarily square.) + x = np.arange(-pos, window_length - pos, dtype=float) + + if use == "conv": + # Reverse so that result can be used in a convolution. + x = x[::-1] + + order = np.arange(polyorder + 1).reshape(-1, 1) + A = x ** order + + # y determines which order derivative is returned. + y = np.zeros(polyorder + 1) + # The coefficient assigned to y[deriv] scales the result to take into + # account the order of the derivative and the sample spacing. + y[deriv] = float_factorial(deriv) / (delta ** deriv) + + # Find the least-squares solution of A*c = y + coeffs, _, _, _ = lstsq(A, y) + + return coeffs + + +def _polyder(p, m): + """Differentiate polynomials represented with coefficients. + + p must be a 1-D or 2-D array. In the 2-D case, each column gives + the coefficients of a polynomial; the first row holds the coefficients + associated with the highest power. m must be a nonnegative integer. + (numpy.polyder doesn't handle the 2-D case.) + """ + + if m == 0: + result = p + else: + n = len(p) + if n <= m: + result = np.zeros_like(p[:1, ...]) + else: + dp = p[:-m].copy() + for k in range(m): + rng = np.arange(n - k - 1, m - k - 1, -1) + dp *= rng.reshape((n - m,) + (1,) * (p.ndim - 1)) + result = dp + return result + + +def _fit_edge(x, window_start, window_stop, interp_start, interp_stop, + axis, polyorder, deriv, delta, y): + """ + Given an N-d array `x` and the specification of a slice of `x` from + `window_start` to `window_stop` along `axis`, create an interpolating + polynomial of each 1-D slice, and evaluate that polynomial in the slice + from `interp_start` to `interp_stop`. Put the result into the + corresponding slice of `y`. + """ + + # Get the edge into a (window_length, -1) array. + x_edge = axis_slice(x, start=window_start, stop=window_stop, axis=axis) + if axis == 0 or axis == -x.ndim: + xx_edge = x_edge + swapped = False + else: + xx_edge = x_edge.swapaxes(axis, 0) + swapped = True + xx_edge = xx_edge.reshape(xx_edge.shape[0], -1) + + # Fit the edges. poly_coeffs has shape (polyorder + 1, -1), + # where '-1' is the same as in xx_edge. + poly_coeffs = np.polyfit(np.arange(0, window_stop - window_start), + xx_edge, polyorder) + + if deriv > 0: + poly_coeffs = _polyder(poly_coeffs, deriv) + + # Compute the interpolated values for the edge. + i = np.arange(interp_start - window_start, interp_stop - window_start) + values = np.polyval(poly_coeffs, i.reshape(-1, 1)) / (delta ** deriv) + + # Now put the values into the appropriate slice of y. + # First reshape values to match y. + shp = list(y.shape) + shp[0], shp[axis] = shp[axis], shp[0] + values = values.reshape(interp_stop - interp_start, *shp[1:]) + if swapped: + values = values.swapaxes(0, axis) + # Get a view of the data to be replaced by values. + y_edge = axis_slice(y, start=interp_start, stop=interp_stop, axis=axis) + y_edge[...] = values + + +def _fit_edges_polyfit(x, window_length, polyorder, deriv, delta, axis, y): + """ + Use polynomial interpolation of x at the low and high ends of the axis + to fill in the halflen values in y. + + This function just calls _fit_edge twice, once for each end of the axis. + """ + halflen = window_length // 2 + _fit_edge(x, 0, window_length, 0, halflen, axis, + polyorder, deriv, delta, y) + n = x.shape[axis] + _fit_edge(x, n - window_length, n, n - halflen, n, axis, + polyorder, deriv, delta, y) + + +def savgol_filter(x, window_length, polyorder, deriv=0, delta=1.0, + axis=-1, mode='interp', cval=0.0): + """ Apply a Savitzky-Golay filter to an array. + + This is a 1-D filter. If `x` has dimension greater than 1, `axis` + determines the axis along which the filter is applied. + + Parameters + ---------- + x : array_like + The data to be filtered. If `x` is not a single or double precision + floating point array, it will be converted to type ``numpy.float64`` + before filtering. + window_length : int + The length of the filter window (i.e., the number of coefficients). + If `mode` is 'interp', `window_length` must be less than or equal + to the size of `x`. + polyorder : int + The order of the polynomial used to fit the samples. + `polyorder` must be less than `window_length`. + deriv : int, optional + The order of the derivative to compute. This must be a + nonnegative integer. The default is 0, which means to filter + the data without differentiating. + delta : float, optional + The spacing of the samples to which the filter will be applied. + This is only used if deriv > 0. Default is 1.0. + axis : int, optional + The axis of the array `x` along which the filter is to be applied. + Default is -1. + mode : str, optional + Must be 'mirror', 'constant', 'nearest', 'wrap' or 'interp'. This + determines the type of extension to use for the padded signal to + which the filter is applied. When `mode` is 'constant', the padding + value is given by `cval`. See the Notes for more details on 'mirror', + 'constant', 'wrap', and 'nearest'. + When the 'interp' mode is selected (the default), no extension + is used. Instead, a degree `polyorder` polynomial is fit to the + last `window_length` values of the edges, and this polynomial is + used to evaluate the last `window_length // 2` output values. + cval : scalar, optional + Value to fill past the edges of the input if `mode` is 'constant'. + Default is 0.0. + + Returns + ------- + y : ndarray, same shape as `x` + The filtered data. + + See Also + -------- + savgol_coeffs + + Notes + ----- + Details on the `mode` options: + + 'mirror': + Repeats the values at the edges in reverse order. The value + closest to the edge is not included. + 'nearest': + The extension contains the nearest input value. + 'constant': + The extension contains the value given by the `cval` argument. + 'wrap': + The extension contains the values from the other end of the array. + + For example, if the input is [1, 2, 3, 4, 5, 6, 7, 8], and + `window_length` is 7, the following shows the extended data for + the various `mode` options (assuming `cval` is 0):: + + mode | Ext | Input | Ext + -----------+---------+------------------------+--------- + 'mirror' | 4 3 2 | 1 2 3 4 5 6 7 8 | 7 6 5 + 'nearest' | 1 1 1 | 1 2 3 4 5 6 7 8 | 8 8 8 + 'constant' | 0 0 0 | 1 2 3 4 5 6 7 8 | 0 0 0 + 'wrap' | 6 7 8 | 1 2 3 4 5 6 7 8 | 1 2 3 + + .. versionadded:: 0.14.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal import savgol_filter + >>> np.set_printoptions(precision=2) # For compact display. + >>> x = np.array([2, 2, 5, 2, 1, 0, 1, 4, 9]) + + Filter with a window length of 5 and a degree 2 polynomial. Use + the defaults for all other parameters. + + >>> savgol_filter(x, 5, 2) + array([1.66, 3.17, 3.54, 2.86, 0.66, 0.17, 1. , 4. , 9. ]) + + Note that the last five values in x are samples of a parabola, so + when mode='interp' (the default) is used with polyorder=2, the last + three values are unchanged. Compare that to, for example, + `mode='nearest'`: + + >>> savgol_filter(x, 5, 2, mode='nearest') + array([1.74, 3.03, 3.54, 2.86, 0.66, 0.17, 1. , 4.6 , 7.97]) + + """ + if mode not in ["mirror", "constant", "nearest", "interp", "wrap"]: + raise ValueError("mode must be 'mirror', 'constant', 'nearest' " + "'wrap' or 'interp'.") + + x = np.asarray(x) + # Ensure that x is either single or double precision floating point. + if x.dtype != np.float64 and x.dtype != np.float32: + x = x.astype(np.float64) + + coeffs = savgol_coeffs(window_length, polyorder, deriv=deriv, delta=delta) + + if mode == "interp": + if window_length > x.shape[axis]: + raise ValueError("If mode is 'interp', window_length must be less " + "than or equal to the size of x.") + + # Do not pad. Instead, for the elements within `window_length // 2` + # of the ends of the sequence, use the polynomial that is fitted to + # the last `window_length` elements. + y = convolve1d(x, coeffs, axis=axis, mode="constant") + _fit_edges_polyfit(x, window_length, polyorder, deriv, delta, axis, y) + else: + # Any mode other than 'interp' is passed on to ndimage.convolve1d. + y = convolve1d(x, coeffs, axis=axis, mode=mode, cval=cval) + + return y diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_short_time_fft.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_short_time_fft.py new file mode 100644 index 0000000000000000000000000000000000000000..6c87718dea8b777d23c77d6147b4ca6368204637 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_short_time_fft.py @@ -0,0 +1,1738 @@ +"""Implementation of an FFT-based Short-time Fourier Transform. """ + +# Implementation Notes for this file (as of 2023-07) +# -------------------------------------------------- +# * MyPy version 1.1.1 does not seem to support decorated property methods +# properly. Hence, applying ``@property`` to methods decorated with `@cache`` +# (as tried with the ``lower_border_end`` method) causes a mypy error when +# accessing it as an index (e.g., ``SFT.lower_border_end[0]``). +# * Since the method `stft` and `istft` have identical names as the legacy +# functions in the signal module, referencing them as HTML link in the +# docstrings has to be done by an explicit `~ShortTimeFFT.stft` instead of an +# ambiguous `stft` (The ``~`` hides the class / module name). +# * The HTML documentation currently renders each method/property on a separate +# page without reference to the parent class. Thus, a link to `ShortTimeFFT` +# was added to the "See Also" section of each method/property. These links +# can be removed, when SciPy updates ``pydata-sphinx-theme`` to >= 0.13.3 +# (currently 0.9). Consult Issue 18512 and PR 16660 for further details. +# + +# Provides typing union operator ``|`` in Python 3.9: +# Linter does not allow to import ``Generator`` from ``typing`` module: +from collections.abc import Generator, Callable +from functools import cache, lru_cache, partial +from typing import get_args, Literal + +import numpy as np + +import scipy.fft as fft_lib +from scipy.signal import detrend +from scipy.signal.windows import get_window + +__all__ = ['ShortTimeFFT'] + + +#: Allowed values for parameter `padding` of method `ShortTimeFFT.stft()`: +PAD_TYPE = Literal['zeros', 'edge', 'even', 'odd'] + +#: Allowed values for property `ShortTimeFFT.fft_mode`: +FFT_MODE_TYPE = Literal['twosided', 'centered', 'onesided', 'onesided2X'] + + +def _calc_dual_canonical_window(win: np.ndarray, hop: int) -> np.ndarray: + """Calculate canonical dual window for 1d window `win` and a time step + of `hop` samples. + + A ``ValueError`` is raised, if the inversion fails. + + This is a separate function not a method, since it is also used in the + class method ``ShortTimeFFT.from_dual()``. + """ + if hop > len(win): + raise ValueError(f"{hop=} is larger than window length of {len(win)}" + + " => STFT not invertible!") + if issubclass(win.dtype.type, np.integer): + raise ValueError("Parameter 'win' cannot be of integer type, but " + + f"{win.dtype=} => STFT not invertible!") + # The calculation of `relative_resolution` does not work for ints. + # Furthermore, `win / DD` casts the integers away, thus an implicit + # cast is avoided, which can always cause confusion when using 32-Bit + # floats. + + w2 = win.real**2 + win.imag**2 # win*win.conj() does not ensure w2 is real + DD = w2.copy() + for k_ in range(hop, len(win), hop): + DD[k_:] += w2[:-k_] + DD[:-k_] += w2[k_:] + + # check DD > 0: + relative_resolution = np.finfo(win.dtype).resolution * max(DD) + if not np.all(DD >= relative_resolution): + raise ValueError("Short-time Fourier Transform not invertible!") + + return win / DD + + +# noinspection PyShadowingNames +class ShortTimeFFT: + r"""Provide a parametrized discrete Short-time Fourier transform (stft) + and its inverse (istft). + + .. currentmodule:: scipy.signal.ShortTimeFFT + + The `~ShortTimeFFT.stft` calculates sequential FFTs by sliding a + window (`win`) over an input signal by `hop` increments. It can be used to + quantify the change of the spectrum over time. + + The `~ShortTimeFFT.stft` is represented by a complex-valued matrix S[q,p] + where the p-th column represents an FFT with the window centered at the + time t[p] = p * `delta_t` = p * `hop` * `T` where `T` is the sampling + interval of the input signal. The q-th row represents the values at the + frequency f[q] = q * `delta_f` with `delta_f` = 1 / (`mfft` * `T`) being + the bin width of the FFT. + + The inverse STFT `~ShortTimeFFT.istft` is calculated by reversing the steps + of the STFT: Take the IFFT of the p-th slice of S[q,p] and multiply the + result with the so-called dual window (see `dual_win`). Shift the result by + p * `delta_t` and add the result to previous shifted results to reconstruct + the signal. If only the dual window is known and the STFT is invertible, + `from_dual` can be used to instantiate this class. + + Due to the convention of time t = 0 being at the first sample of the input + signal, the STFT values typically have negative time slots. Hence, + negative indexes like `p_min` or `k_min` do not indicate counting + backwards from an array's end like in standard Python indexing but being + left of t = 0. + + More detailed information can be found in the :ref:`tutorial_stft` section + of the :ref:`user_guide`. + + Note that all parameters of the initializer, except `scale_to` (which uses + `scaling`) have identical named attributes. + + Parameters + ---------- + win : np.ndarray + The window must be a real- or complex-valued 1d array. + hop : int + The increment in samples, by which the window is shifted in each step. + fs : float + Sampling frequency of input signal and window. Its relation to the + sampling interval `T` is ``T = 1 / fs``. + fft_mode : 'twosided', 'centered', 'onesided', 'onesided2X' + Mode of FFT to be used (default 'onesided'). + See property `fft_mode` for details. + mfft: int | None + Length of the FFT used, if a zero padded FFT is desired. + If ``None`` (default), the length of the window `win` is used. + dual_win : np.ndarray | None + The dual window of `win`. If set to ``None``, it is calculated if + needed. + scale_to : 'magnitude', 'psd' | None + If not ``None`` (default) the window function is scaled, so each STFT + column represents either a 'magnitude' or a power spectral density + ('psd') spectrum. This parameter sets the property `scaling` to the + same value. See method `scale_to` for details. + phase_shift : int | None + If set, add a linear phase `phase_shift` / `mfft` * `f` to each + frequency `f`. The default value 0 ensures that there is no phase shift + on the zeroth slice (in which t=0 is centered). See property + `phase_shift` for more details. + + Examples + -------- + The following example shows the magnitude of the STFT of a sine with + varying frequency :math:`f_i(t)` (marked by a red dashed line in the plot): + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.signal import ShortTimeFFT + >>> from scipy.signal.windows import gaussian + ... + >>> T_x, N = 1 / 20, 1000 # 20 Hz sampling rate for 50 s signal + >>> t_x = np.arange(N) * T_x # time indexes for signal + >>> f_i = 1 * np.arctan((t_x - t_x[N // 2]) / 2) + 5 # varying frequency + >>> x = np.sin(2*np.pi*np.cumsum(f_i)*T_x) # the signal + + The utilized Gaussian window is 50 samples or 2.5 s long. The parameter + ``mfft=200`` in `ShortTimeFFT` causes the spectrum to be oversampled + by a factor of 4: + + >>> g_std = 8 # standard deviation for Gaussian window in samples + >>> w = gaussian(50, std=g_std, sym=True) # symmetric Gaussian window + >>> SFT = ShortTimeFFT(w, hop=10, fs=1/T_x, mfft=200, scale_to='magnitude') + >>> Sx = SFT.stft(x) # perform the STFT + + In the plot, the time extent of the signal `x` is marked by vertical dashed + lines. Note that the SFT produces values outside the time range of `x`. The + shaded areas on the left and the right indicate border effects caused + by the window slices in that area not fully being inside time range of + `x`: + + >>> fig1, ax1 = plt.subplots(figsize=(6., 4.)) # enlarge plot a bit + >>> t_lo, t_hi = SFT.extent(N)[:2] # time range of plot + >>> ax1.set_title(rf"STFT ({SFT.m_num*SFT.T:g}$\,s$ Gaussian window, " + + ... rf"$\sigma_t={g_std*SFT.T}\,$s)") + >>> ax1.set(xlabel=f"Time $t$ in seconds ({SFT.p_num(N)} slices, " + + ... rf"$\Delta t = {SFT.delta_t:g}\,$s)", + ... ylabel=f"Freq. $f$ in Hz ({SFT.f_pts} bins, " + + ... rf"$\Delta f = {SFT.delta_f:g}\,$Hz)", + ... xlim=(t_lo, t_hi)) + ... + >>> im1 = ax1.imshow(abs(Sx), origin='lower', aspect='auto', + ... extent=SFT.extent(N), cmap='viridis') + >>> ax1.plot(t_x, f_i, 'r--', alpha=.5, label='$f_i(t)$') + >>> fig1.colorbar(im1, label="Magnitude $|S_x(t, f)|$") + ... + >>> # Shade areas where window slices stick out to the side: + >>> for t0_, t1_ in [(t_lo, SFT.lower_border_end[0] * SFT.T), + ... (SFT.upper_border_begin(N)[0] * SFT.T, t_hi)]: + ... ax1.axvspan(t0_, t1_, color='w', linewidth=0, alpha=.2) + >>> for t_ in [0, N * SFT.T]: # mark signal borders with vertical line: + ... ax1.axvline(t_, color='y', linestyle='--', alpha=0.5) + >>> ax1.legend() + >>> fig1.tight_layout() + >>> plt.show() + + Reconstructing the signal with the `~ShortTimeFFT.istft` is + straightforward, but note that the length of `x1` should be specified, + since the SFT length increases in `hop` steps: + + >>> SFT.invertible # check if invertible + True + >>> x1 = SFT.istft(Sx, k1=N) + >>> np.allclose(x, x1) + True + + It is possible to calculate the SFT of signal parts: + + >>> N2 = SFT.nearest_k_p(N // 2) + >>> Sx0 = SFT.stft(x[:N2]) + >>> Sx1 = SFT.stft(x[N2:]) + + When assembling sequential STFT parts together, the overlap needs to be + considered: + + >>> p0_ub = SFT.upper_border_begin(N2)[1] - SFT.p_min + >>> p1_le = SFT.lower_border_end[1] - SFT.p_min + >>> Sx01 = np.hstack((Sx0[:, :p0_ub], + ... Sx0[:, p0_ub:] + Sx1[:, :p1_le], + ... Sx1[:, p1_le:])) + >>> np.allclose(Sx01, Sx) # Compare with SFT of complete signal + True + + It is also possible to calculate the `itsft` for signal parts: + + >>> y_p = SFT.istft(Sx, N//3, N//2) + >>> np.allclose(y_p, x[N//3:N//2]) + True + + """ + # immutable attributes (only have getters but no setters): + _win: np.ndarray # window + _dual_win: np.ndarray | None = None # canonical dual window + _hop: int # Step of STFT in number of samples + + # mutable attributes: + _fs: float # sampling frequency of input signal and window + _fft_mode: FFT_MODE_TYPE = 'onesided' # Mode of FFT to use + _mfft: int # length of FFT used - defaults to len(win) + _scaling: Literal['magnitude', 'psd'] | None = None # Scaling of _win + _phase_shift: int | None # amount to shift phase of FFT in samples + + # attributes for caching calculated values: + _fac_mag: float | None = None + _fac_psd: float | None = None + _lower_border_end: tuple[int, int] | None = None + + def __init__(self, win: np.ndarray, hop: int, fs: float, *, + fft_mode: FFT_MODE_TYPE = 'onesided', + mfft: int | None = None, + dual_win: np.ndarray | None = None, + scale_to: Literal['magnitude', 'psd'] | None = None, + phase_shift: int | None = 0): + if not (win.ndim == 1 and win.size > 0): + raise ValueError(f"Parameter win must be 1d, but {win.shape=}!") + if not all(np.isfinite(win)): + raise ValueError("Parameter win must have finite entries!") + if not (hop >= 1 and isinstance(hop, int)): + raise ValueError(f"Parameter {hop=} is not an integer >= 1!") + self._win, self._hop, self.fs = win, hop, fs + + self.mfft = len(win) if mfft is None else mfft + + if dual_win is not None: + if dual_win.shape != win.shape: + raise ValueError(f"{dual_win.shape=} must equal {win.shape=}!") + if not all(np.isfinite(dual_win)): + raise ValueError("Parameter dual_win must be a finite array!") + self._dual_win = dual_win # needs to be set before scaling + + if scale_to is not None: # needs to be set before fft_mode + self.scale_to(scale_to) + + self.fft_mode, self.phase_shift = fft_mode, phase_shift + + @classmethod + def from_dual(cls, dual_win: np.ndarray, hop: int, fs: float, *, + fft_mode: FFT_MODE_TYPE = 'onesided', + mfft: int | None = None, + scale_to: Literal['magnitude', 'psd'] | None = None, + phase_shift: int | None = 0): + r"""Instantiate a `ShortTimeFFT` by only providing a dual window. + + If an STFT is invertible, it is possible to calculate the window `win` + from a given dual window `dual_win`. All other parameters have the + same meaning as in the initializer of `ShortTimeFFT`. + + As explained in the :ref:`tutorial_stft` section of the + :ref:`user_guide`, an invertible STFT can be interpreted as series + expansion of time-shifted and frequency modulated dual windows. E.g., + the series coefficient S[q,p] belongs to the term, which shifted + `dual_win` by p * `delta_t` and multiplied it by + exp( 2 * j * pi * t * q * `delta_f`). + + + Examples + -------- + The following example discusses decomposing a signal into time- and + frequency-shifted Gaussians. A Gaussian with standard deviation of + one made up of 51 samples will be used: + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.signal import ShortTimeFFT + >>> from scipy.signal.windows import gaussian + ... + >>> T, N = 0.1, 51 + >>> d_win = gaussian(N, std=1/T, sym=True) # symmetric Gaussian window + >>> t = T * (np.arange(N) - N//2) + ... + >>> fg1, ax1 = plt.subplots() + >>> ax1.set_title(r"Dual Window: Gaussian with $\sigma_t=1$") + >>> ax1.set(xlabel=f"Time $t$ in seconds ({N} samples, $T={T}$ s)", + ... xlim=(t[0], t[-1]), ylim=(0, 1.1*max(d_win))) + >>> ax1.plot(t, d_win, 'C0-') + + The following plot with the overlap of 41, 11 and 2 samples show how + the `hop` interval affects the shape of the window `win`: + + >>> fig2, axx = plt.subplots(3, 1, sharex='all') + ... + >>> axx[0].set_title(r"Windows for hop$\in\{10, 40, 49\}$") + >>> for c_, h_ in enumerate([10, 40, 49]): + ... SFT = ShortTimeFFT.from_dual(d_win, h_, 1/T) + ... axx[c_].plot(t + h_ * T, SFT.win, 'k--', alpha=.3, label=None) + ... axx[c_].plot(t - h_ * T, SFT.win, 'k:', alpha=.3, label=None) + ... axx[c_].plot(t, SFT.win, f'C{c_+1}', + ... label=r"$\Delta t=%0.1f\,$s" % SFT.delta_t) + ... axx[c_].set_ylim(0, 1.1*max(SFT.win)) + ... axx[c_].legend(loc='center') + >>> axx[-1].set(xlabel=f"Time $t$ in seconds ({N} samples, $T={T}$ s)", + ... xlim=(t[0], t[-1])) + >>> plt.show() + + Beside the window `win` centered at t = 0 the previous (t = -`delta_t`) + and following window (t = `delta_t`) are depicted. It can be seen that + for small `hop` intervals, the window is compact and smooth, having a + good time-frequency concentration in the STFT. For the large `hop` + interval of 4.9 s, the window has small values around t = 0, which are + not covered by the overlap of the adjacent windows, which could lead to + numeric inaccuracies. Furthermore, the peaky shape at the beginning and + the end of the window points to a higher bandwidth, resulting in a + poorer time-frequency resolution of the STFT. + Hence, the choice of the `hop` interval will be a compromise between + a time-frequency resolution and memory requirements demanded by small + `hop` sizes. + + See Also + -------- + from_window: Create instance by wrapping `get_window`. + ShortTimeFFT: Create instance using standard initializer. + """ + win = _calc_dual_canonical_window(dual_win, hop) + return cls(win=win, hop=hop, fs=fs, fft_mode=fft_mode, mfft=mfft, + dual_win=dual_win, scale_to=scale_to, + phase_shift=phase_shift) + + @classmethod + def from_window(cls, win_param: str | tuple | float, + fs: float, nperseg: int, noverlap: int, *, + symmetric_win: bool = False, + fft_mode: FFT_MODE_TYPE = 'onesided', + mfft: int | None = None, + scale_to: Literal['magnitude', 'psd'] | None = None, + phase_shift: int | None = 0): + """Instantiate `ShortTimeFFT` by using `get_window`. + + The method `get_window` is used to create a window of length + `nperseg`. The parameter names `noverlap`, and `nperseg` are used here, + since they more inline with other classical STFT libraries. + + Parameters + ---------- + win_param: Union[str, tuple, float], + Parameters passed to `get_window`. For windows with no parameters, + it may be a string (e.g., ``'hann'``), for parametrized windows a + tuple, (e.g., ``('gaussian', 2.)``) or a single float specifying + the shape parameter of a kaiser window (i.e. ``4.`` and + ``('kaiser', 4.)`` are equal. See `get_window` for more details. + fs : float + Sampling frequency of input signal. Its relation to the + sampling interval `T` is ``T = 1 / fs``. + nperseg: int + Window length in samples, which corresponds to the `m_num`. + noverlap: int + Window overlap in samples. It relates to the `hop` increment by + ``hop = npsereg - noverlap``. + symmetric_win: bool + If ``True`` then a symmetric window is generated, else a periodic + window is generated (default). Though symmetric windows seem for + most applications to be more sensible, the default of a periodic + windows was chosen to correspond to the default of `get_window`. + fft_mode : 'twosided', 'centered', 'onesided', 'onesided2X' + Mode of FFT to be used (default 'onesided'). + See property `fft_mode` for details. + mfft: int | None + Length of the FFT used, if a zero padded FFT is desired. + If ``None`` (default), the length of the window `win` is used. + scale_to : 'magnitude', 'psd' | None + If not ``None`` (default) the window function is scaled, so each + STFT column represents either a 'magnitude' or a power spectral + density ('psd') spectrum. This parameter sets the property + `scaling` to the same value. See method `scale_to` for details. + phase_shift : int | None + If set, add a linear phase `phase_shift` / `mfft` * `f` to each + frequency `f`. The default value 0 ensures that there is no phase + shift on the zeroth slice (in which t=0 is centered). See property + `phase_shift` for more details. + + Examples + -------- + The following instances ``SFT0`` and ``SFT1`` are equivalent: + + >>> from scipy.signal import ShortTimeFFT, get_window + >>> nperseg = 9 # window length + >>> w = get_window(('gaussian', 2.), nperseg) + >>> fs = 128 # sampling frequency + >>> hop = 3 # increment of STFT time slice + >>> SFT0 = ShortTimeFFT(w, hop, fs=fs) + >>> SFT1 = ShortTimeFFT.from_window(('gaussian', 2.), fs, nperseg, + ... noverlap=nperseg-hop) + + See Also + -------- + scipy.signal.get_window: Return a window of a given length and type. + from_dual: Create instance using dual window. + ShortTimeFFT: Create instance using standard initializer. + """ + win = get_window(win_param, nperseg, fftbins=not symmetric_win) + return cls(win, hop=nperseg-noverlap, fs=fs, fft_mode=fft_mode, + mfft=mfft, scale_to=scale_to, phase_shift=phase_shift) + + @property + def win(self) -> np.ndarray: + """Window function as real- or complex-valued 1d array. + + This attribute is read only, since `dual_win` depends on it. + + See Also + -------- + dual_win: Canonical dual window. + m_num: Number of samples in window `win`. + m_num_mid: Center index of window `win`. + mfft: Length of input for the FFT used - may be larger than `m_num`. + hop: ime increment in signal samples for sliding window. + win: Window function as real- or complex-valued 1d array. + ShortTimeFFT: Class this property belongs to. + """ + return self._win + + @property + def hop(self) -> int: + """Time increment in signal samples for sliding window. + + This attribute is read only, since `dual_win` depends on it. + + See Also + -------- + delta_t: Time increment of STFT (``hop*T``) + m_num: Number of samples in window `win`. + m_num_mid: Center index of window `win`. + mfft: Length of input for the FFT used - may be larger than `m_num`. + T: Sampling interval of input signal and of the window. + win: Window function as real- or complex-valued 1d array. + ShortTimeFFT: Class this property belongs to. + """ + return self._hop + + @property + def T(self) -> float: + """Sampling interval of input signal and of the window. + + A ``ValueError`` is raised if it is set to a non-positive value. + + See Also + -------- + delta_t: Time increment of STFT (``hop*T``) + hop: Time increment in signal samples for sliding window. + fs: Sampling frequency (being ``1/T``) + t: Times of STFT for an input signal with `n` samples. + ShortTimeFFT: Class this property belongs to. + """ + return 1 / self._fs + + @T.setter + def T(self, v: float): + """Sampling interval of input signal and of the window. + + A ``ValueError`` is raised if it is set to a non-positive value. + """ + if not (v > 0): + raise ValueError(f"Sampling interval T={v} must be positive!") + self._fs = 1 / v + + @property + def fs(self) -> float: + """Sampling frequency of input signal and of the window. + + The sampling frequency is the inverse of the sampling interval `T`. + A ``ValueError`` is raised if it is set to a non-positive value. + + See Also + -------- + delta_t: Time increment of STFT (``hop*T``) + hop: Time increment in signal samples for sliding window. + T: Sampling interval of input signal and of the window (``1/fs``). + ShortTimeFFT: Class this property belongs to. + """ + return self._fs + + @fs.setter + def fs(self, v: float): + """Sampling frequency of input signal and of the window. + + The sampling frequency is the inverse of the sampling interval `T`. + A ``ValueError`` is raised if it is set to a non-positive value. + """ + if not (v > 0): + raise ValueError(f"Sampling frequency fs={v} must be positive!") + self._fs = v + + @property + def fft_mode(self) -> FFT_MODE_TYPE: + """Mode of utilized FFT ('twosided', 'centered', 'onesided' or + 'onesided2X'). + + It can have the following values: + + 'twosided': + Two-sided FFT, where values for the negative frequencies are in + upper half of the array. Corresponds to :func:`~scipy.fft.fft()`. + 'centered': + Two-sided FFT with the values being ordered along monotonically + increasing frequencies. Corresponds to applying + :func:`~scipy.fft.fftshift()` to :func:`~scipy.fft.fft()`. + 'onesided': + Calculates only values for non-negative frequency values. + Corresponds to :func:`~scipy.fft.rfft()`. + 'onesided2X': + Like `onesided`, but the non-zero frequencies are doubled if + `scaling` is set to 'magnitude' or multiplied by ``sqrt(2)`` if + set to 'psd'. If `scaling` is ``None``, setting `fft_mode` to + `onesided2X` is not allowed. + If the FFT length `mfft` is even, the last FFT value is not paired, + and thus it is not scaled. + + Note that `onesided` and `onesided2X` do not work for complex-valued signals or + complex-valued windows. Furthermore, the frequency values can be obtained by + reading the `f` property, and the number of samples by accessing the `f_pts` + property. + + See Also + -------- + delta_f: Width of the frequency bins of the STFT. + f: Frequencies values of the STFT. + f_pts: Width of the frequency bins of the STFT. + onesided_fft: True if a one-sided FFT is used. + scaling: Normalization applied to the window function + ShortTimeFFT: Class this property belongs to. + """ + return self._fft_mode + + @fft_mode.setter + def fft_mode(self, t: FFT_MODE_TYPE): + """Set mode of FFT. + + Allowed values are 'twosided', 'centered', 'onesided', 'onesided2X'. + See the property `fft_mode` for more details. + """ + if t not in (fft_mode_types := get_args(FFT_MODE_TYPE)): + raise ValueError(f"fft_mode='{t}' not in {fft_mode_types}!") + + if t in {'onesided', 'onesided2X'} and np.iscomplexobj(self.win): + raise ValueError(f"One-sided spectra, i.e., fft_mode='{t}', " + + "are not allowed for complex-valued windows!") + + if t == 'onesided2X' and self.scaling is None: + raise ValueError(f"For scaling is None, fft_mode='{t}' is invalid!" + "Do scale_to('psd') or scale_to('magnitude')!") + self._fft_mode = t + + @property + def mfft(self) -> int: + """Length of input for the FFT used - may be larger than window + length `m_num`. + + If not set, `mfft` defaults to the window length `m_num`. + + See Also + -------- + f_pts: Number of points along the frequency axis. + f: Frequencies values of the STFT. + m_num: Number of samples in window `win`. + ShortTimeFFT: Class this property belongs to. + """ + return self._mfft + + @mfft.setter + def mfft(self, n_: int): + """Setter for the length of FFT utilized. + + See the property `mfft` for further details. + """ + if not (n_ >= self.m_num): + raise ValueError(f"Attribute mfft={n_} needs to be at least the " + + f"window length m_num={self.m_num}!") + self._mfft = n_ + + @property + def scaling(self) -> Literal['magnitude', 'psd'] | None: + """Normalization applied to the window function + ('magnitude', 'psd' or ``None``). + + If not ``None``, the FFTs can be either interpreted as a magnitude or + a power spectral density spectrum. + + The window function can be scaled by calling the `scale_to` method, + or it is set by the initializer parameter ``scale_to``. + + See Also + -------- + fac_magnitude: Scaling factor for to a magnitude spectrum. + fac_psd: Scaling factor for to a power spectral density spectrum. + fft_mode: Mode of utilized FFT + scale_to: Scale window to obtain 'magnitude' or 'psd' scaling. + ShortTimeFFT: Class this property belongs to. + """ + return self._scaling + + def scale_to(self, scaling: Literal['magnitude', 'psd']): + """Scale window to obtain 'magnitude' or 'psd' scaling for the STFT. + + The window of a 'magnitude' spectrum has an integral of one, i.e., unit + area for non-negative windows. This ensures that absolute the values of + spectrum does not change if the length of the window changes (given + the input signal is stationary). + + To represent the power spectral density ('psd') for varying length + windows the area of the absolute square of the window needs to be + unity. + + The `scaling` property shows the current scaling. The properties + `fac_magnitude` and `fac_psd` show the scaling factors required to + scale the STFT values to a magnitude or a psd spectrum. + + This method is called, if the initializer parameter `scale_to` is set. + + See Also + -------- + fac_magnitude: Scaling factor for to a magnitude spectrum. + fac_psd: Scaling factor for to a power spectral density spectrum. + fft_mode: Mode of utilized FFT + scaling: Normalization applied to the window function. + ShortTimeFFT: Class this method belongs to. + """ + if scaling not in (scaling_values := {'magnitude', 'psd'}): + raise ValueError(f"{scaling=} not in {scaling_values}!") + if self._scaling == scaling: # do nothing + return + + s_fac = self.fac_psd if scaling == 'psd' else self.fac_magnitude + self._win = self._win * s_fac + if self._dual_win is not None: + self._dual_win = self._dual_win / s_fac + self._fac_mag, self._fac_psd = None, None # reset scaling factors + self._scaling = scaling + + @property + def phase_shift(self) -> int | None: + """If set, add linear phase `phase_shift` / `mfft` * `f` to each FFT + slice of frequency `f`. + + Shifting (more precisely `rolling`) an `mfft`-point FFT input by + `phase_shift` samples results in a multiplication of the output by + ``np.exp(2j*np.pi*q*phase_shift/mfft)`` at the frequency q * `delta_f`. + + The default value 0 ensures that there is no phase shift on the + zeroth slice (in which t=0 is centered). + No phase shift (``phase_shift is None``) is equivalent to + ``phase_shift = -mfft//2``. In this case slices are not shifted + before calculating the FFT. + + The absolute value of `phase_shift` is limited to be less than `mfft`. + + See Also + -------- + delta_f: Width of the frequency bins of the STFT. + f: Frequencies values of the STFT. + mfft: Length of input for the FFT used + ShortTimeFFT: Class this property belongs to. + """ + return self._phase_shift + + @phase_shift.setter + def phase_shift(self, v: int | None): + """The absolute value of the phase shift needs to be less than mfft + samples. + + See the `phase_shift` getter method for more details. + """ + if v is None: + self._phase_shift = v + return + if not isinstance(v, int): + raise ValueError(f"phase_shift={v} has the unit samples. Hence " + + "it needs to be an int or it may be None!") + if not (-self.mfft < v < self.mfft): + raise ValueError("-mfft < phase_shift < mfft does not hold " + + f"for mfft={self.mfft}, phase_shift={v}!") + self._phase_shift = v + + def _x_slices(self, x: np.ndarray, k_off: int, p0: int, p1: int, + padding: PAD_TYPE) -> Generator[np.ndarray, None, None]: + """Generate signal slices along last axis of `x`. + + This method is only used by `stft_detrend`. The parameters are + described in `~ShortTimeFFT.stft`. + """ + if padding not in (padding_types := get_args(PAD_TYPE)): + raise ValueError(f"Parameter {padding=} not in {padding_types}!") + pad_kws: dict[str, dict] = { # possible keywords to pass to np.pad: + 'zeros': dict(mode='constant', constant_values=(0, 0)), + 'edge': dict(mode='edge'), + 'even': dict(mode='reflect', reflect_type='even'), + 'odd': dict(mode='reflect', reflect_type='odd'), + } # typing of pad_kws is needed to make mypy happy + + n, n1 = x.shape[-1], (p1 - p0) * self.hop + k0 = p0 * self.hop - self.m_num_mid + k_off # start sample + k1 = k0 + n1 + self.m_num # end sample + + i0, i1 = max(k0, 0), min(k1, n) # indexes to shorten x + # dimensions for padding x: + pad_width = [(0, 0)] * (x.ndim-1) + [(-min(k0, 0), max(k1 - n, 0))] + + x1 = np.pad(x[..., i0:i1], pad_width, **pad_kws[padding]) + for k_ in range(0, n1, self.hop): + yield x1[..., k_:k_ + self.m_num] + + def stft(self, x: np.ndarray, p0: int | None = None, + p1: int | None = None, *, k_offset: int = 0, + padding: PAD_TYPE = 'zeros', axis: int = -1) \ + -> np.ndarray: + """Perform the short-time Fourier transform. + + A two-dimensional matrix with ``p1-p0`` columns is calculated. + The `f_pts` rows represent value at the frequencies `f`. The q-th + column of the windowed FFT with the window `win` is centered at t[q]. + The columns represent the values at the frequencies `f`. + + Parameters + ---------- + x + The input signal as real or complex valued array. For complex values, the + property `fft_mode` must be set to 'twosided' or 'centered'. + p0 + The first element of the range of slices to calculate. If ``None`` + then it is set to :attr:`p_min`, which is the smallest possible + slice. + p1 + The end of the array. If ``None`` then `p_max(n)` is used. + k_offset + Index of first sample (t = 0) in `x`. + padding + Kind of values which are added, when the sliding window sticks out + on either the lower or upper end of the input `x`. Zeros are added + if the default 'zeros' is set. For 'edge' either the first or the + last value of `x` is used. 'even' pads by reflecting the + signal on the first or last sample and 'odd' additionally + multiplies it with -1. + axis + The axis of `x` over which to compute the STFT. + If not given, the last axis is used. + + Returns + ------- + S + A complex array is returned with the dimension always being larger + by one than of `x`. The last axis always represent the time slices + of the STFT. `axis` defines the frequency axis (default second to + last). E.g., for a one-dimensional `x`, a complex 2d array is + returned, with axis 0 representing frequency and axis 1 the time + slices. + + See Also + -------- + delta_f: Width of the frequency bins of the STFT. + delta_t: Time increment of STFT + f: Frequencies values of the STFT. + invertible: Check if STFT is invertible. + :meth:`~ShortTimeFFT.istft`: Inverse short-time Fourier transform. + p_range: Determine and validate slice index range. + stft_detrend: STFT with detrended segments. + t: Times of STFT for an input signal with `n` samples. + :class:`scipy.signal.ShortTimeFFT`: Class this method belongs to. + """ + return self.stft_detrend(x, None, p0, p1, k_offset=k_offset, + padding=padding, axis=axis) + + def stft_detrend(self, x: np.ndarray, + detr: Callable[[np.ndarray], np.ndarray] | Literal['linear', 'constant'] | None, # noqa: E501 + p0: int | None = None, p1: int | None = None, *, + k_offset: int = 0, padding: PAD_TYPE = 'zeros', + axis: int = -1) \ + -> np.ndarray: + """Short-time Fourier transform with a trend being subtracted from each + segment beforehand. + + If `detr` is set to 'constant', the mean is subtracted, if set to + "linear", the linear trend is removed. This is achieved by calling + :func:`scipy.signal.detrend`. If `detr` is a function, `detr` is + applied to each segment. + All other parameters have the same meaning as in `~ShortTimeFFT.stft`. + + Note that due to the detrending, the original signal cannot be + reconstructed by the `~ShortTimeFFT.istft`. + + See Also + -------- + invertible: Check if STFT is invertible. + :meth:`~ShortTimeFFT.istft`: Inverse short-time Fourier transform. + :meth:`~ShortTimeFFT.stft`: Short-time Fourier transform + (without detrending). + :class:`scipy.signal.ShortTimeFFT`: Class this method belongs to. + """ + if self.onesided_fft and np.iscomplexobj(x): + raise ValueError(f"Complex-valued `x` not allowed for {self.fft_mode=}'! " + "Set property `fft_mode` to 'twosided' or 'centered'.") + if isinstance(detr, str): + detr = partial(detrend, type=detr) + elif not (detr is None or callable(detr)): + raise ValueError(f"Parameter {detr=} is not a str, function or " + + "None!") + n = x.shape[axis] + if not (n >= (m2p := self.m_num-self.m_num_mid)): + e_str = f'{len(x)=}' if x.ndim == 1 else f'of {axis=} of {x.shape}' + raise ValueError(f"{e_str} must be >= ceil(m_num/2) = {m2p}!") + + if x.ndim > 1: # motivated by the NumPy broadcasting mechanisms: + x = np.moveaxis(x, axis, -1) + # determine slice index range: + p0, p1 = self.p_range(n, p0, p1) + S_shape_1d = (self.f_pts, p1 - p0) + S_shape = x.shape[:-1] + S_shape_1d if x.ndim > 1 else S_shape_1d + S = np.zeros(S_shape, dtype=complex) + for p_, x_ in enumerate(self._x_slices(x, k_offset, p0, p1, padding)): + if detr is not None: + x_ = detr(x_) + S[..., :, p_] = self._fft_func(x_ * self.win.conj()) + if x.ndim > 1: + return np.moveaxis(S, -2, axis if axis >= 0 else axis-1) + return S + + def spectrogram(self, x: np.ndarray, y: np.ndarray | None = None, + detr: Callable[[np.ndarray], np.ndarray] | Literal['linear', 'constant'] | None = None, # noqa: E501 + *, + p0: int | None = None, p1: int | None = None, + k_offset: int = 0, padding: PAD_TYPE = 'zeros', + axis: int = -1) \ + -> np.ndarray: + r"""Calculate spectrogram or cross-spectrogram. + + The spectrogram is the absolute square of the STFT, i.e., it is + ``abs(S[q,p])**2`` for given ``S[q,p]`` and thus is always + non-negative. + For two STFTs ``Sx[q,p], Sy[q,p]``, the cross-spectrogram is defined + as ``Sx[q,p] * np.conj(Sy[q,p])`` and is complex-valued. + This is a convenience function for calling `~ShortTimeFFT.stft` / + `stft_detrend`, hence all parameters are discussed there. If `y` is not + ``None`` it needs to have the same shape as `x`. + + Examples + -------- + The following example shows the spectrogram of a square wave with + varying frequency :math:`f_i(t)` (marked by a green dashed line in the + plot) sampled with 20 Hz: + + >>> import matplotlib.pyplot as plt + >>> import numpy as np + >>> from scipy.signal import square, ShortTimeFFT + >>> from scipy.signal.windows import gaussian + ... + >>> T_x, N = 1 / 20, 1000 # 20 Hz sampling rate for 50 s signal + >>> t_x = np.arange(N) * T_x # time indexes for signal + >>> f_i = 5e-3*(t_x - t_x[N // 3])**2 + 1 # varying frequency + >>> x = square(2*np.pi*np.cumsum(f_i)*T_x) # the signal + + The utilized Gaussian window is 50 samples or 2.5 s long. The + parameter ``mfft=800`` (oversampling factor 16) and the `hop` interval + of 2 in `ShortTimeFFT` was chosen to produce a sufficient number of + points: + + >>> g_std = 12 # standard deviation for Gaussian window in samples + >>> win = gaussian(50, std=g_std, sym=True) # symmetric Gaussian wind. + >>> SFT = ShortTimeFFT(win, hop=2, fs=1/T_x, mfft=800, scale_to='psd') + >>> Sx2 = SFT.spectrogram(x) # calculate absolute square of STFT + + The plot's colormap is logarithmically scaled as the power spectral + density is in dB. The time extent of the signal `x` is marked by + vertical dashed lines and the shaded areas mark the presence of border + effects: + + >>> fig1, ax1 = plt.subplots(figsize=(6., 4.)) # enlarge plot a bit + >>> t_lo, t_hi = SFT.extent(N)[:2] # time range of plot + >>> ax1.set_title(rf"Spectrogram ({SFT.m_num*SFT.T:g}$\,s$ Gaussian " + + ... rf"window, $\sigma_t={g_std*SFT.T:g}\,$s)") + >>> ax1.set(xlabel=f"Time $t$ in seconds ({SFT.p_num(N)} slices, " + + ... rf"$\Delta t = {SFT.delta_t:g}\,$s)", + ... ylabel=f"Freq. $f$ in Hz ({SFT.f_pts} bins, " + + ... rf"$\Delta f = {SFT.delta_f:g}\,$Hz)", + ... xlim=(t_lo, t_hi)) + >>> Sx_dB = 10 * np.log10(np.fmax(Sx2, 1e-4)) # limit range to -40 dB + >>> im1 = ax1.imshow(Sx_dB, origin='lower', aspect='auto', + ... extent=SFT.extent(N), cmap='magma') + >>> ax1.plot(t_x, f_i, 'g--', alpha=.5, label='$f_i(t)$') + >>> fig1.colorbar(im1, label='Power Spectral Density ' + + ... r"$20\,\log_{10}|S_x(t, f)|$ in dB") + ... + >>> # Shade areas where window slices stick out to the side: + >>> for t0_, t1_ in [(t_lo, SFT.lower_border_end[0] * SFT.T), + ... (SFT.upper_border_begin(N)[0] * SFT.T, t_hi)]: + ... ax1.axvspan(t0_, t1_, color='w', linewidth=0, alpha=.3) + >>> for t_ in [0, N * SFT.T]: # mark signal borders with vertical line + ... ax1.axvline(t_, color='c', linestyle='--', alpha=0.5) + >>> ax1.legend() + >>> fig1.tight_layout() + >>> plt.show() + + The logarithmic scaling reveals the odd harmonics of the square wave, + which are reflected at the Nyquist frequency of 10 Hz. This aliasing + is also the main source of the noise artifacts in the plot. + + + See Also + -------- + :meth:`~ShortTimeFFT.stft`: Perform the short-time Fourier transform. + stft_detrend: STFT with a trend subtracted from each segment. + :class:`scipy.signal.ShortTimeFFT`: Class this method belongs to. + """ + Sx = self.stft_detrend(x, detr, p0, p1, k_offset=k_offset, + padding=padding, axis=axis) + if y is None or y is x: # do spectrogram: + return Sx.real**2 + Sx.imag**2 + # Cross-spectrogram: + Sy = self.stft_detrend(y, detr, p0, p1, k_offset=k_offset, + padding=padding, axis=axis) + return Sx * Sy.conj() + + @property + def dual_win(self) -> np.ndarray: + """Canonical dual window. + + A STFT can be interpreted as the input signal being expressed as a + weighted sum of modulated and time-shifted dual windows. Note that for + a given window there exist many dual windows. The canonical window is + the one with the minimal energy (i.e., :math:`L_2` norm). + + `dual_win` has same length as `win`, namely `m_num` samples. + + If the dual window cannot be calculated a ``ValueError`` is raised. + This attribute is read only and calculated lazily. + + See Also + -------- + dual_win: Canonical dual window. + m_num: Number of samples in window `win`. + win: Window function as real- or complex-valued 1d array. + ShortTimeFFT: Class this property belongs to. + """ + if self._dual_win is None: + self._dual_win = _calc_dual_canonical_window(self.win, self.hop) + return self._dual_win + + @property + def invertible(self) -> bool: + """Check if STFT is invertible. + + This is achieved by trying to calculate the canonical dual window. + + See Also + -------- + :meth:`~ShortTimeFFT.istft`: Inverse short-time Fourier transform. + m_num: Number of samples in window `win` and `dual_win`. + dual_win: Canonical dual window. + win: Window for STFT. + ShortTimeFFT: Class this property belongs to. + """ + try: + return len(self.dual_win) > 0 # call self.dual_win() + except ValueError: + return False + + def istft(self, S: np.ndarray, k0: int = 0, k1: int | None = None, *, + f_axis: int = -2, t_axis: int = -1) \ + -> np.ndarray: + """Inverse short-time Fourier transform. + + It returns an array of dimension ``S.ndim - 1`` which is real + if `onesided_fft` is set, else complex. If the STFT is not + `invertible`, or the parameters are out of bounds a ``ValueError`` is + raised. + + Parameters + ---------- + S + A complex valued array where `f_axis` denotes the frequency + values and the `t-axis` dimension the temporal values of the + STFT values. + k0, k1 + The start and the end index of the reconstructed signal. The + default (``k0 = 0``, ``k1 = None``) assumes that the maximum length + signal should be reconstructed. + f_axis, t_axis + The axes in `S` denoting the frequency and the time dimension. + + Notes + ----- + It is required that `S` has `f_pts` entries along the `f_axis`. For + the `t_axis` it is assumed that the first entry corresponds to + `p_min` * `delta_t` (being <= 0). The length of `t_axis` needs to be + compatible with `k1`. I.e., ``S.shape[t_axis] >= self.p_max(k1)`` must + hold, if `k1` is not ``None``. Else `k1` is set to `k_max` with:: + + q_max = S.shape[t_range] + self.p_min + k_max = (q_max - 1) * self.hop + self.m_num - self.m_num_mid + + The :ref:`tutorial_stft` section of the :ref:`user_guide` discussed the + slicing behavior by means of an example. + + See Also + -------- + invertible: Check if STFT is invertible. + :meth:`~ShortTimeFFT.stft`: Perform Short-time Fourier transform. + :class:`scipy.signal.ShortTimeFFT`: Class this method belongs to. + """ + if f_axis == t_axis: + raise ValueError(f"{f_axis=} may not be equal to {t_axis=}!") + if S.shape[f_axis] != self.f_pts: + raise ValueError(f"{S.shape[f_axis]=} must be equal to " + + f"{self.f_pts=} ({S.shape=})!") + n_min = self.m_num-self.m_num_mid # minimum signal length + if not (S.shape[t_axis] >= (q_num := self.p_num(n_min))): + raise ValueError(f"{S.shape[t_axis]=} needs to have at least " + + f"{q_num} slices ({S.shape=})!") + if t_axis != S.ndim - 1 or f_axis != S.ndim - 2: + t_axis = S.ndim + t_axis if t_axis < 0 else t_axis + f_axis = S.ndim + f_axis if f_axis < 0 else f_axis + S = np.moveaxis(S, (f_axis, t_axis), (-2, -1)) + + q_max = S.shape[-1] + self.p_min + k_max = (q_max - 1) * self.hop + self.m_num - self.m_num_mid + + k1 = k_max if k1 is None else k1 + if not (self.k_min <= k0 < k1 <= k_max): + raise ValueError(f"({self.k_min=}) <= ({k0=}) < ({k1=}) <= " + + f"({k_max=}) is false!") + if not (num_pts := k1 - k0) >= n_min: + raise ValueError(f"({k1=}) - ({k0=}) = {num_pts} has to be at " + + f"least the half the window length {n_min}!") + + q0 = (k0 // self.hop + self.p_min if k0 >= 0 else # p_min always <= 0 + k0 // self.hop) + q1 = min(self.p_max(k1), q_max) + k_q0, k_q1 = self.nearest_k_p(k0), self.nearest_k_p(k1, left=False) + n_pts = k_q1 - k_q0 + self.m_num - self.m_num_mid + x = np.zeros(S.shape[:-2] + (n_pts,), + dtype=float if self.onesided_fft else complex) + for q_ in range(q0, q1): + xs = self._ifft_func(S[..., :, q_ - self.p_min]) * self.dual_win + i0 = q_ * self.hop - self.m_num_mid + i1 = min(i0 + self.m_num, n_pts+k0) + j0, j1 = 0, i1 - i0 + if i0 < k0: # xs sticks out to the left on x: + j0 += k0 - i0 + i0 = k0 + x[..., i0-k0:i1-k0] += xs[..., j0:j1] + x = x[..., :k1-k0] + if x.ndim > 1: + x = np.moveaxis(x, -1, f_axis if f_axis < x.ndim else t_axis) + return x + + @property + def fac_magnitude(self) -> float: + """Factor to multiply the STFT values by to scale each frequency slice + to a magnitude spectrum. + + It is 1 if attribute ``scaling == 'magnitude'``. + The window can be scaled to a magnitude spectrum by using the method + `scale_to`. + + See Also + -------- + fac_psd: Scaling factor for to a power spectral density spectrum. + scale_to: Scale window to obtain 'magnitude' or 'psd' scaling. + scaling: Normalization applied to the window function. + ShortTimeFFT: Class this property belongs to. + """ + if self.scaling == 'magnitude': + return 1 + if self._fac_mag is None: + self._fac_mag = 1 / abs(sum(self.win)) + return self._fac_mag + + @property + def fac_psd(self) -> float: + """Factor to multiply the STFT values by to scale each frequency slice + to a power spectral density (PSD). + + It is 1 if attribute ``scaling == 'psd'``. + The window can be scaled to a psd spectrum by using the method + `scale_to`. + + See Also + -------- + fac_magnitude: Scaling factor for to a magnitude spectrum. + scale_to: Scale window to obtain 'magnitude' or 'psd' scaling. + scaling: Normalization applied to the window function. + ShortTimeFFT: Class this property belongs to. + """ + if self.scaling == 'psd': + return 1 + if self._fac_psd is None: + self._fac_psd = 1 / np.sqrt( + sum(self.win.real**2+self.win.imag**2) / self.T) + return self._fac_psd + + @property + def m_num(self) -> int: + """Number of samples in window `win`. + + Note that the FFT can be oversampled by zero-padding. This is achieved + by setting the `mfft` property. + + See Also + -------- + m_num_mid: Center index of window `win`. + mfft: Length of input for the FFT used - may be larger than `m_num`. + hop: Time increment in signal samples for sliding window. + win: Window function as real- or complex-valued 1d array. + ShortTimeFFT: Class this property belongs to. + """ + return len(self.win) + + @property + def m_num_mid(self) -> int: + """Center index of window `win`. + + For odd `m_num`, ``(m_num - 1) / 2`` is returned and + for even `m_num` (per definition) ``m_num / 2`` is returned. + + See Also + -------- + m_num: Number of samples in window `win`. + mfft: Length of input for the FFT used - may be larger than `m_num`. + hop: ime increment in signal samples for sliding window. + win: Window function as real- or complex-valued 1d array. + ShortTimeFFT: Class this property belongs to. + """ + return self.m_num // 2 + + @cache + def _pre_padding(self) -> tuple[int, int]: + """Smallest signal index and slice index due to padding. + + Since, per convention, for time t=0, n,q is zero, the returned values + are negative or zero. + """ + w2 = self.win.real**2 + self.win.imag**2 + # move window to the left until the overlap with t >= 0 vanishes: + n0 = -self.m_num_mid + for q_, n_ in enumerate(range(n0, n0-self.m_num-1, -self.hop)): + n_next = n_ - self.hop + if n_next + self.m_num <= 0 or all(w2[n_next:] == 0): + return n_, -q_ + raise RuntimeError("This is code line should not have been reached!") + # If this case is reached, it probably means the first slice should be + # returned, i.e.: return n0, 0 + + @property + def k_min(self) -> int: + """The smallest possible signal index of the STFT. + + `k_min` is the index of the left-most non-zero value of the lowest + slice `p_min`. Since the zeroth slice is centered over the zeroth + sample of the input signal, `k_min` is never positive. + A detailed example is provided in the :ref:`tutorial_stft_sliding_win` + section of the :ref:`user_guide`. + + See Also + -------- + k_max: First sample index after signal end not touched by a time slice. + lower_border_end: Where pre-padding effects end. + p_min: The smallest possible slice index. + p_max: Index of first non-overlapping upper time slice. + p_num: Number of time slices, i.e., `p_max` - `p_min`. + p_range: Determine and validate slice index range. + upper_border_begin: Where post-padding effects start. + ShortTimeFFT: Class this property belongs to. + """ + return self._pre_padding()[0] + + @property + def p_min(self) -> int: + """The smallest possible slice index. + + `p_min` is the index of the left-most slice, where the window still + sticks into the signal, i.e., has non-zero part for t >= 0. + `k_min` is the smallest index where the window function of the slice + `p_min` is non-zero. + + Since, per convention the zeroth slice is centered at t=0, + `p_min` <= 0 always holds. + A detailed example is provided in the :ref:`tutorial_stft_sliding_win` + section of the :ref:`user_guide`. + + See Also + -------- + k_min: The smallest possible signal index. + k_max: First sample index after signal end not touched by a time slice. + p_max: Index of first non-overlapping upper time slice. + p_num: Number of time slices, i.e., `p_max` - `p_min`. + p_range: Determine and validate slice index range. + ShortTimeFFT: Class this property belongs to. + """ + return self._pre_padding()[1] + + @lru_cache(maxsize=256) + def _post_padding(self, n: int) -> tuple[int, int]: + """Largest signal index and slice index due to padding. + + Parameters + ---------- + n : int + Number of samples of input signal (must be ≥ half of the window length). + """ + if not (n >= (m2p := self.m_num - self.m_num_mid)): + raise ValueError(f"Parameter n must be >= ceil(m_num/2) = {m2p}!") + w2 = self.win.real**2 + self.win.imag**2 + # move window to the right until the overlap for t < t[n] vanishes: + q1 = n // self.hop # last slice index with t[p1] <= t[n] + k1 = q1 * self.hop - self.m_num_mid + for q_, k_ in enumerate(range(k1, n+self.m_num, self.hop), start=q1): + n_next = k_ + self.hop + if n_next >= n or all(w2[:n-n_next] == 0): + return k_ + self.m_num, q_ + 1 + raise RuntimeError("This is code line should not have been reached!") + # If this case is reached, it probably means the last slice should be + # returned, i.e.: return k1 + self.m_num - self.m_num_mid, q1 + 1 + + def k_max(self, n: int) -> int: + """First sample index after signal end not touched by a time slice. + + `k_max` - 1 is the largest sample index of the slice `p_max` for a + given input signal of `n` samples. + A detailed example is provided in the :ref:`tutorial_stft_sliding_win` + section of the :ref:`user_guide`. + + Parameters + ---------- + n : int + Number of samples of input signal (must be ≥ half of the window length). + + See Also + -------- + k_min: The smallest possible signal index. + p_min: The smallest possible slice index. + p_max: Index of first non-overlapping upper time slice. + p_num: Number of time slices, i.e., `p_max` - `p_min`. + p_range: Determine and validate slice index range. + ShortTimeFFT: Class this method belongs to. + """ + return self._post_padding(n)[0] + + def p_max(self, n: int) -> int: + """Index of first non-overlapping upper time slice for `n` sample + input. + + Note that center point t[p_max] = (p_max(n)-1) * `delta_t` is typically + larger than last time index t[n-1] == (`n`-1) * `T`. The upper border + of samples indexes covered by the window slices is given by `k_max`. + Furthermore, `p_max` does not denote the number of slices `p_num` since + `p_min` is typically less than zero. + A detailed example is provided in the :ref:`tutorial_stft_sliding_win` + section of the :ref:`user_guide`. + + See Also + -------- + k_min: The smallest possible signal index. + k_max: First sample index after signal end not touched by a time slice. + p_min: The smallest possible slice index. + p_num: Number of time slices, i.e., `p_max` - `p_min`. + p_range: Determine and validate slice index range. + ShortTimeFFT: Class this method belongs to. + """ + return self._post_padding(n)[1] + + def p_num(self, n: int) -> int: + """Number of time slices for an input signal with `n` samples. + + It is given by `p_num` = `p_max` - `p_min` with `p_min` typically + being negative. + A detailed example is provided in the :ref:`tutorial_stft_sliding_win` + section of the :ref:`user_guide`. + + See Also + -------- + k_min: The smallest possible signal index. + k_max: First sample index after signal end not touched by a time slice. + lower_border_end: Where pre-padding effects end. + p_min: The smallest possible slice index. + p_max: Index of first non-overlapping upper time slice. + p_range: Determine and validate slice index range. + upper_border_begin: Where post-padding effects start. + ShortTimeFFT: Class this method belongs to. + """ + return self.p_max(n) - self.p_min + + @property + def lower_border_end(self) -> tuple[int, int]: + """First signal index and first slice index unaffected by pre-padding. + + Describes the point where the window does not stick out to the left + of the signal domain. + A detailed example is provided in the :ref:`tutorial_stft_sliding_win` + section of the :ref:`user_guide`. + + See Also + -------- + k_min: The smallest possible signal index. + k_max: First sample index after signal end not touched by a time slice. + lower_border_end: Where pre-padding effects end. + p_min: The smallest possible slice index. + p_max: Index of first non-overlapping upper time slice. + p_num: Number of time slices, i.e., `p_max` - `p_min`. + p_range: Determine and validate slice index range. + upper_border_begin: Where post-padding effects start. + ShortTimeFFT: Class this property belongs to. + """ + # not using @cache decorator due to MyPy limitations + if self._lower_border_end is not None: + return self._lower_border_end + + # first non-zero element in self.win: + m0 = np.flatnonzero(self.win.real**2 + self.win.imag**2)[0] + + # move window to the right until does not stick out to the left: + k0 = -self.m_num_mid + m0 + for q_, k_ in enumerate(range(k0, self.hop + 1, self.hop)): + if k_ + self.hop >= 0: # next entry does not stick out anymore + self._lower_border_end = (k_ + self.m_num, q_ + 1) + return self._lower_border_end + self._lower_border_end = (0, max(self.p_min, 0)) # ends at first slice + return self._lower_border_end + + @lru_cache(maxsize=256) + def upper_border_begin(self, n: int) -> tuple[int, int]: + """First signal index and first slice index affected by post-padding. + + Describes the point where the window does begin stick out to the right + of the signal domain. + A detailed example is given :ref:`tutorial_stft_sliding_win` section + of the :ref:`user_guide`. + + Parameters + ---------- + n : int + Number of samples of input signal (must be ≥ half of the window length). + + Returns + ------- + k_ub : int + Lowest signal index, where a touching time slice sticks out past the + signal end. + p_ub : int + Lowest index of time slice of which the end sticks out past the signal end. + + See Also + -------- + k_min: The smallest possible signal index. + k_max: First sample index after signal end not touched by a time slice. + lower_border_end: Where pre-padding effects end. + p_min: The smallest possible slice index. + p_max: Index of first non-overlapping upper time slice. + p_num: Number of time slices, i.e., `p_max` - `p_min`. + p_range: Determine and validate slice index range. + ShortTimeFFT: Class this method belongs to. + """ + if not (n >= (m2p := self.m_num - self.m_num_mid)): + raise ValueError(f"Parameter n must be >= ceil(m_num/2) = {m2p}!") + w2 = self.win.real**2 + self.win.imag**2 + q2 = n // self.hop + 1 # first t[q] >= t[n] + q1 = max((n-self.m_num) // self.hop - 1, -1) + # move window left until does not stick out to the right: + for q_ in range(q2, q1, -1): + k_ = q_ * self.hop + (self.m_num - self.m_num_mid) + if k_ <= n or all(w2[n-k_:] == 0): + return (q_ + 1) * self.hop - self.m_num_mid, q_ + 1 + return 0, 0 # border starts at first slice + + @property + def delta_t(self) -> float: + """Time increment of STFT. + + The time increment `delta_t` = `T` * `hop` represents the sample + increment `hop` converted to time based on the sampling interval `T`. + + See Also + -------- + delta_f: Width of the frequency bins of the STFT. + hop: Hop size in signal samples for sliding window. + t: Times of STFT for an input signal with `n` samples. + T: Sampling interval of input signal and window `win`. + ShortTimeFFT: Class this property belongs to + """ + return self.T * self.hop + + def p_range(self, n: int, p0: int | None = None, + p1: int | None = None) -> tuple[int, int]: + """Determine and validate slice index range. + + Parameters + ---------- + n : int + Number of samples of input signal, assuming t[0] = 0. + p0 : int | None + First slice index. If 0 then the first slice is centered at t = 0. + If ``None`` then `p_min` is used. Note that p0 may be < 0 if + slices are left of t = 0. + p1 : int | None + End of interval (last value is p1-1). + If ``None`` then `p_max(n)` is used. + + + Returns + ------- + p0_ : int + The fist slice index + p1_ : int + End of interval (last value is p1-1). + + Notes + ----- + A ``ValueError`` is raised if ``p_min <= p0 < p1 <= p_max(n)`` does not + hold. + + See Also + -------- + k_min: The smallest possible signal index. + k_max: First sample index after signal end not touched by a time slice. + lower_border_end: Where pre-padding effects end. + p_min: The smallest possible slice index. + p_max: Index of first non-overlapping upper time slice. + p_num: Number of time slices, i.e., `p_max` - `p_min`. + upper_border_begin: Where post-padding effects start. + ShortTimeFFT: Class this property belongs to. + """ + p_max = self.p_max(n) # shorthand + p0_ = self.p_min if p0 is None else p0 + p1_ = p_max if p1 is None else p1 + if not (self.p_min <= p0_ < p1_ <= p_max): + raise ValueError(f"Invalid Parameter {p0=}, {p1=}, i.e., " + + f"{self.p_min=} <= p0 < p1 <= {p_max=} " + + f"does not hold for signal length {n=}!") + return p0_, p1_ + + @lru_cache(maxsize=1) + def t(self, n: int, p0: int | None = None, p1: int | None = None, + k_offset: int = 0) -> np.ndarray: + """Times of STFT for an input signal with `n` samples. + + Returns a 1d array with times of the `~ShortTimeFFT.stft` values with + the same parametrization. Note that the slices are + ``delta_t = hop * T`` time units apart. + + Parameters + ---------- + n + Number of sample of the input signal. + p0 + The first element of the range of slices to calculate. If ``None`` + then it is set to :attr:`p_min`, which is the smallest possible + slice. + p1 + The end of the array. If ``None`` then `p_max(n)` is used. + k_offset + Index of first sample (t = 0) in `x`. + + + See Also + -------- + delta_t: Time increment of STFT (``hop*T``) + hop: Time increment in signal samples for sliding window. + nearest_k_p: Nearest sample index k_p for which t[k_p] == t[p] holds. + T: Sampling interval of input signal and of the window (``1/fs``). + fs: Sampling frequency (being ``1/T``) + ShortTimeFFT: Class this method belongs to. + """ + p0, p1 = self.p_range(n, p0, p1) + return np.arange(p0, p1) * self.delta_t + k_offset * self.T + + def nearest_k_p(self, k: int, left: bool = True) -> int: + """Return nearest sample index k_p for which t[k_p] == t[p] holds. + + The nearest next smaller time sample p (where t[p] is the center + position of the window of the p-th slice) is p_k = k // `hop`. + If `hop` is a divisor of `k` than `k` is returned. + If `left` is set than p_k * `hop` is returned else (p_k+1) * `hop`. + + This method can be used to slice an input signal into chunks for + calculating the STFT and iSTFT incrementally. + + See Also + -------- + delta_t: Time increment of STFT (``hop*T``) + hop: Time increment in signal samples for sliding window. + T: Sampling interval of input signal and of the window (``1/fs``). + fs: Sampling frequency (being ``1/T``) + t: Times of STFT for an input signal with `n` samples. + ShortTimeFFT: Class this method belongs to. + """ + p_q, remainder = divmod(k, self.hop) + if remainder == 0: + return k + return p_q * self.hop if left else (p_q + 1) * self.hop + + @property + def delta_f(self) -> float: + """Width of the frequency bins of the STFT. + + Return the frequency interval `delta_f` = 1 / (`mfft` * `T`). + + See Also + -------- + delta_t: Time increment of STFT. + f_pts: Number of points along the frequency axis. + f: Frequencies values of the STFT. + mfft: Length of the input for FFT used. + T: Sampling interval. + t: Times of STFT for an input signal with `n` samples. + ShortTimeFFT: Class this property belongs to. + """ + return 1 / (self.mfft * self.T) + + @property + def f_pts(self) -> int: + """Number of points along the frequency axis. + + See Also + -------- + delta_f: Width of the frequency bins of the STFT. + f: Frequencies values of the STFT. + mfft: Length of the input for FFT used. + ShortTimeFFT: Class this property belongs to. + """ + return self.mfft // 2 + 1 if self.onesided_fft else self.mfft + + @property + def onesided_fft(self) -> bool: + """Return True if a one-sided FFT is used. + + Returns ``True`` if `fft_mode` is either 'onesided' or 'onesided2X'. + + See Also + -------- + fft_mode: Utilized FFT ('twosided', 'centered', 'onesided' or + 'onesided2X') + ShortTimeFFT: Class this property belongs to. + """ + return self.fft_mode in {'onesided', 'onesided2X'} + + @property + def f(self) -> np.ndarray: + """Frequencies values of the STFT. + + A 1d array of length `f_pts` with `delta_f` spaced entries is returned. + + See Also + -------- + delta_f: Width of the frequency bins of the STFT. + f_pts: Number of points along the frequency axis. + mfft: Length of the input for FFT used. + ShortTimeFFT: Class this property belongs to. + """ + if self.fft_mode in {'onesided', 'onesided2X'}: + return fft_lib.rfftfreq(self.mfft, self.T) + elif self.fft_mode == 'twosided': + return fft_lib.fftfreq(self.mfft, self.T) + elif self.fft_mode == 'centered': + return fft_lib.fftshift(fft_lib.fftfreq(self.mfft, self.T)) + # This should never happen but makes the Linters happy: + fft_modes = get_args(FFT_MODE_TYPE) + raise RuntimeError(f"{self.fft_mode=} not in {fft_modes}!") + + def _fft_func(self, x: np.ndarray) -> np.ndarray: + """FFT based on the `fft_mode`, `mfft`, `scaling` and `phase_shift` + attributes. + + For multidimensional arrays the transformation is carried out on the + last axis. + """ + if self.phase_shift is not None: + if x.shape[-1] < self.mfft: # zero pad if needed + z_shape = list(x.shape) + z_shape[-1] = self.mfft - x.shape[-1] + x = np.hstack((x, np.zeros(z_shape, dtype=x.dtype))) + p_s = (self.phase_shift + self.m_num_mid) % self.m_num + x = np.roll(x, -p_s, axis=-1) + + if self.fft_mode == 'twosided': + return fft_lib.fft(x, n=self.mfft, axis=-1) + if self.fft_mode == 'centered': + return fft_lib.fftshift(fft_lib.fft(x, self.mfft, axis=-1), axes=-1) + if self.fft_mode == 'onesided': + return fft_lib.rfft(x, n=self.mfft, axis=-1) + if self.fft_mode == 'onesided2X': + X = fft_lib.rfft(x, n=self.mfft, axis=-1) + # Either squared magnitude (psd) or magnitude is doubled: + fac = np.sqrt(2) if self.scaling == 'psd' else 2 + # For even input length, the last entry is unpaired: + X[..., 1: -1 if self.mfft % 2 == 0 else None] *= fac + return X + # This should never happen but makes the Linter happy: + fft_modes = get_args(FFT_MODE_TYPE) + raise RuntimeError(f"{self.fft_mode=} not in {fft_modes}!") + + def _ifft_func(self, X: np.ndarray) -> np.ndarray: + """Inverse to `_fft_func`. + + Returned is an array of length `m_num`. If the FFT is `onesided` + then a float array is returned else a complex array is returned. + For multidimensional arrays the transformation is carried out on the + last axis. + """ + if self.fft_mode == 'twosided': + x = fft_lib.ifft(X, n=self.mfft, axis=-1) + elif self.fft_mode == 'centered': + x = fft_lib.ifft(fft_lib.ifftshift(X, axes=-1), n=self.mfft, axis=-1) + elif self.fft_mode == 'onesided': + x = fft_lib.irfft(X, n=self.mfft, axis=-1) + elif self.fft_mode == 'onesided2X': + Xc = X.copy() # we do not want to modify function parameters + fac = np.sqrt(2) if self.scaling == 'psd' else 2 + # For even length X the last value is not paired with a negative + # value on the two-sided FFT: + q1 = -1 if self.mfft % 2 == 0 else None + Xc[..., 1:q1] /= fac + x = fft_lib.irfft(Xc, n=self.mfft, axis=-1) + else: # This should never happen but makes the Linter happy: + error_str = f"{self.fft_mode=} not in {get_args(FFT_MODE_TYPE)}!" + raise RuntimeError(error_str) + + if self.phase_shift is None: + return x[..., :self.m_num] + p_s = (self.phase_shift + self.m_num_mid) % self.m_num + return np.roll(x, p_s, axis=-1)[..., :self.m_num] + + def extent(self, n: int, axes_seq: Literal['tf', 'ft'] = 'tf', + center_bins: bool = False) -> tuple[float, float, float, float]: + """Return minimum and maximum values time-frequency values. + + A tuple with four floats ``(t0, t1, f0, f1)`` for 'tf' and + ``(f0, f1, t0, t1)`` for 'ft' is returned describing the corners + of the time-frequency domain of the `~ShortTimeFFT.stft`. + That tuple can be passed to `matplotlib.pyplot.imshow` as a parameter + with the same name. + + Parameters + ---------- + n : int + Number of samples in input signal. + axes_seq : {'tf', 'ft'} + Return time extent first and then frequency extent or vice-versa. + center_bins: bool + If set (default ``False``), the values of the time slots and + frequency bins are moved from the side the middle. This is useful, + when plotting the `~ShortTimeFFT.stft` values as step functions, + i.e., with no interpolation. + + See Also + -------- + :func:`matplotlib.pyplot.imshow`: Display data as an image. + :class:`scipy.signal.ShortTimeFFT`: Class this method belongs to. + + Examples + -------- + The following two plots illustrate the effect of the parameter `center_bins`: + The grid lines represent the three time and the four frequency values of the + STFT. + The left plot, where ``(t0, t1, f0, f1) = (0, 3, 0, 4)`` is passed as parameter + ``extent`` to `~matplotlib.pyplot.imshow`, shows the standard behavior of the + time and frequency values being at the lower edge of the corrsponding bin. + The right plot, with ``(t0, t1, f0, f1) = (-0.5, 2.5, -0.5, 3.5)``, shows that + the bins are centered over the respective values when passing + ``center_bins=True``. + + >>> import matplotlib.pyplot as plt + >>> import numpy as np + >>> from scipy.signal import ShortTimeFFT + ... + >>> n, m = 12, 6 + >>> SFT = ShortTimeFFT.from_window('hann', fs=m, nperseg=m, noverlap=0) + >>> Sxx = SFT.stft(np.cos(np.arange(n))) # produces a colorful plot + ... + >>> fig, axx = plt.subplots(1, 2, tight_layout=True, figsize=(6., 4.)) + >>> for ax_, center_bins in zip(axx, (False, True)): + ... ax_.imshow(abs(Sxx), origin='lower', interpolation=None, aspect='equal', + ... cmap='viridis', extent=SFT.extent(n, 'tf', center_bins)) + ... ax_.set_title(f"{center_bins=}") + ... ax_.set_xlabel(f"Time ({SFT.p_num(n)} points, Δt={SFT.delta_t})") + ... ax_.set_ylabel(f"Frequency ({SFT.f_pts} points, Δf={SFT.delta_f})") + ... ax_.set_xticks(SFT.t(n)) # vertical grid line are timestamps + ... ax_.set_yticks(SFT.f) # horizontal grid line are frequency values + ... ax_.grid(True) + >>> plt.show() + + Note that the step-like behavior with the constant colors is caused by passing + ``interpolation=None`` to `~matplotlib.pyplot.imshow`. + """ + if axes_seq not in ('tf', 'ft'): + raise ValueError(f"Parameter {axes_seq=} not in ['tf', 'ft']!") + + if self.onesided_fft: + q0, q1 = 0, self.f_pts + elif self.fft_mode == 'centered': + q0 = -(self.mfft // 2) + q1 = self.mfft // 2 if self.mfft % 2 == 0 else self.mfft // 2 + 1 + else: + raise ValueError(f"Attribute fft_mode={self.fft_mode} must be " + + "in ['centered', 'onesided', 'onesided2X']") + + p0, p1 = self.p_min, self.p_max(n) # shorthand + if center_bins: + t0, t1 = self.delta_t * (p0 - 0.5), self.delta_t * (p1 - 0.5) + f0, f1 = self.delta_f * (q0 - 0.5), self.delta_f * (q1 - 0.5) + else: + t0, t1 = self.delta_t * p0, self.delta_t * p1 + f0, f1 = self.delta_f * q0, self.delta_f * q1 + return (t0, t1, f0, f1) if axes_seq == 'tf' else (f0, f1, t0, t1) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_signaltools.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_signaltools.py new file mode 100644 index 0000000000000000000000000000000000000000..340e227760ecd0a4bbf7bf5a135b92acb123a4d3 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_signaltools.py @@ -0,0 +1,4989 @@ +# Author: Travis Oliphant +# 1999 -- 2002 + +from __future__ import annotations # Provides typing union operator `|` in Python 3.9 +import operator +import math +from math import prod as _prod +import timeit +import warnings +from typing import Literal + +from numpy._typing import ArrayLike + +from scipy.spatial import cKDTree +from . import _sigtools +from ._ltisys import dlti +from ._upfirdn import upfirdn, _output_len, _upfirdn_modes +from scipy import linalg, fft as sp_fft +from scipy import ndimage +from scipy.fft._helper import _init_nd_shape_and_axes +import numpy as np +from scipy.special import lambertw +from .windows import get_window +from ._arraytools import axis_slice, axis_reverse, odd_ext, even_ext, const_ext +from ._filter_design import cheby1, _validate_sos, zpk2sos +from ._fir_filter_design import firwin +from ._sosfilt import _sosfilt + + +__all__ = ['correlate', 'correlation_lags', 'correlate2d', + 'convolve', 'convolve2d', 'fftconvolve', 'oaconvolve', + 'order_filter', 'medfilt', 'medfilt2d', 'wiener', 'lfilter', + 'lfiltic', 'sosfilt', 'deconvolve', 'hilbert', 'hilbert2', 'envelope', + 'unique_roots', 'invres', 'invresz', 'residue', + 'residuez', 'resample', 'resample_poly', 'detrend', + 'lfilter_zi', 'sosfilt_zi', 'sosfiltfilt', 'choose_conv_method', + 'filtfilt', 'decimate', 'vectorstrength'] + + +_modedict = {'valid': 0, 'same': 1, 'full': 2} + +_boundarydict = {'fill': 0, 'pad': 0, 'wrap': 2, 'circular': 2, 'symm': 1, + 'symmetric': 1, 'reflect': 4} + + +def _valfrommode(mode): + try: + return _modedict[mode] + except KeyError as e: + raise ValueError("Acceptable mode flags are 'valid'," + " 'same', or 'full'.") from e + + +def _bvalfromboundary(boundary): + try: + return _boundarydict[boundary] << 2 + except KeyError as e: + raise ValueError("Acceptable boundary flags are 'fill', 'circular' " + "(or 'wrap'), and 'symmetric' (or 'symm').") from e + + +def _inputs_swap_needed(mode, shape1, shape2, axes=None): + """Determine if inputs arrays need to be swapped in `"valid"` mode. + + If in `"valid"` mode, returns whether or not the input arrays need to be + swapped depending on whether `shape1` is at least as large as `shape2` in + every calculated dimension. + + This is important for some of the correlation and convolution + implementations in this module, where the larger array input needs to come + before the smaller array input when operating in this mode. + + Note that if the mode provided is not 'valid', False is immediately + returned. + + """ + if mode != 'valid': + return False + + if not shape1: + return False + + if axes is None: + axes = range(len(shape1)) + + ok1 = all(shape1[i] >= shape2[i] for i in axes) + ok2 = all(shape2[i] >= shape1[i] for i in axes) + + if not (ok1 or ok2): + raise ValueError("For 'valid' mode, one must be at least " + "as large as the other in every dimension") + + return not ok1 + + +def _reject_objects(arr, name): + """Warn if arr.dtype is object or longdouble. + """ + dt = np.asarray(arr).dtype + if not (np.issubdtype(dt, np.integer) + or dt in [np.bool_, np.float16, np.float32, np.float64, + np.complex64, np.complex128] + ): + msg = ( + f"dtype={dt} is not supported by {name} and will raise an error in " + f"SciPy 1.17.0. Supported dtypes are: boolean, integer, `np.float16`," + f"`np.float32`, `np.float64`, `np.complex64`, `np.complex128`." + ) + warnings.warn(msg, category=DeprecationWarning, stacklevel=3) + + +def correlate(in1, in2, mode='full', method='auto'): + r""" + Cross-correlate two N-dimensional arrays. + + Cross-correlate `in1` and `in2`, with the output size determined by the + `mode` argument. + + Parameters + ---------- + in1 : array_like + First input. + in2 : array_like + Second input. Should have the same number of dimensions as `in1`. + mode : str {'full', 'valid', 'same'}, optional + A string indicating the size of the output: + + ``full`` + The output is the full discrete linear cross-correlation + of the inputs. (Default) + ``valid`` + The output consists only of those elements that do not + rely on the zero-padding. In 'valid' mode, either `in1` or `in2` + must be at least as large as the other in every dimension. + ``same`` + The output is the same size as `in1`, centered + with respect to the 'full' output. + method : str {'auto', 'direct', 'fft'}, optional + A string indicating which method to use to calculate the correlation. + + ``direct`` + The correlation is determined directly from sums, the definition of + correlation. + ``fft`` + The Fast Fourier Transform is used to perform the correlation more + quickly (only available for numerical arrays.) + ``auto`` + Automatically chooses direct or Fourier method based on an estimate + of which is faster (default). See `convolve` Notes for more detail. + + .. versionadded:: 0.19.0 + + Returns + ------- + correlate : array + An N-dimensional array containing a subset of the discrete linear + cross-correlation of `in1` with `in2`. + + See Also + -------- + choose_conv_method : contains more documentation on `method`. + correlation_lags : calculates the lag / displacement indices array for 1D + cross-correlation. + + Notes + ----- + The correlation z of two d-dimensional arrays x and y is defined as:: + + z[...,k,...] = sum[..., i_l, ...] x[..., i_l,...] * conj(y[..., i_l - k,...]) + + This way, if x and y are 1-D arrays and ``z = correlate(x, y, 'full')`` + then + + .. math:: + + z[k] = (x * y)(k - N + 1) + = \sum_{l=0}^{||x||-1}x_l y_{l-k+N-1}^{*} + + for :math:`k = 0, 1, ..., ||x|| + ||y|| - 2` + + where :math:`||x||` is the length of ``x``, :math:`N = \max(||x||,||y||)`, + and :math:`y_m` is 0 when m is outside the range of y. + + ``method='fft'`` only works for numerical arrays as it relies on + `fftconvolve`. In certain cases (i.e., arrays of objects or when + rounding integers can lose precision), ``method='direct'`` is always used. + + When using "same" mode with even-length inputs, the outputs of `correlate` + and `correlate2d` differ: There is a 1-index offset between them. + + Examples + -------- + Implement a matched filter using cross-correlation, to recover a signal + that has passed through a noisy channel. + + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> rng = np.random.default_rng() + + >>> sig = np.repeat([0., 1., 1., 0., 1., 0., 0., 1.], 128) + >>> sig_noise = sig + rng.standard_normal(len(sig)) + >>> corr = signal.correlate(sig_noise, np.ones(128), mode='same') / 128 + + >>> clock = np.arange(64, len(sig), 128) + >>> fig, (ax_orig, ax_noise, ax_corr) = plt.subplots(3, 1, sharex=True) + >>> ax_orig.plot(sig) + >>> ax_orig.plot(clock, sig[clock], 'ro') + >>> ax_orig.set_title('Original signal') + >>> ax_noise.plot(sig_noise) + >>> ax_noise.set_title('Signal with noise') + >>> ax_corr.plot(corr) + >>> ax_corr.plot(clock, corr[clock], 'ro') + >>> ax_corr.axhline(0.5, ls=':') + >>> ax_corr.set_title('Cross-correlated with rectangular pulse') + >>> ax_orig.margins(0, 0.1) + >>> fig.tight_layout() + >>> plt.show() + + Compute the cross-correlation of a noisy signal with the original signal. + + >>> x = np.arange(128) / 128 + >>> sig = np.sin(2 * np.pi * x) + >>> sig_noise = sig + rng.standard_normal(len(sig)) + >>> corr = signal.correlate(sig_noise, sig) + >>> lags = signal.correlation_lags(len(sig), len(sig_noise)) + >>> corr /= np.max(corr) + + >>> fig, (ax_orig, ax_noise, ax_corr) = plt.subplots(3, 1, figsize=(4.8, 4.8)) + >>> ax_orig.plot(sig) + >>> ax_orig.set_title('Original signal') + >>> ax_orig.set_xlabel('Sample Number') + >>> ax_noise.plot(sig_noise) + >>> ax_noise.set_title('Signal with noise') + >>> ax_noise.set_xlabel('Sample Number') + >>> ax_corr.plot(lags, corr) + >>> ax_corr.set_title('Cross-correlated signal') + >>> ax_corr.set_xlabel('Lag') + >>> ax_orig.margins(0, 0.1) + >>> ax_noise.margins(0, 0.1) + >>> ax_corr.margins(0, 0.1) + >>> fig.tight_layout() + >>> plt.show() + + """ + in1 = np.asarray(in1) + in2 = np.asarray(in2) + _reject_objects(in1, 'correlate') + _reject_objects(in2, 'correlate') + + if in1.ndim == in2.ndim == 0: + return in1 * in2.conj() + elif in1.ndim != in2.ndim: + raise ValueError("in1 and in2 should have the same dimensionality") + + # Don't use _valfrommode, since correlate should not accept numeric modes + try: + val = _modedict[mode] + except KeyError as e: + raise ValueError("Acceptable mode flags are 'valid'," + " 'same', or 'full'.") from e + + # this either calls fftconvolve or this function with method=='direct' + if method in ('fft', 'auto'): + return convolve(in1, _reverse_and_conj(in2), mode, method) + + elif method == 'direct': + # fastpath to faster numpy.correlate for 1d inputs when possible + if _np_conv_ok(in1, in2, mode): + return np.correlate(in1, in2, mode) + + # _correlateND is far slower when in2.size > in1.size, so swap them + # and then undo the effect afterward if mode == 'full'. Also, it fails + # with 'valid' mode if in2 is larger than in1, so swap those, too. + # Don't swap inputs for 'same' mode, since shape of in1 matters. + swapped_inputs = ((mode == 'full') and (in2.size > in1.size) or + _inputs_swap_needed(mode, in1.shape, in2.shape)) + + if swapped_inputs: + in1, in2 = in2, in1 + + if mode == 'valid': + ps = [i - j + 1 for i, j in zip(in1.shape, in2.shape)] + out = np.empty(ps, in1.dtype) + + z = _sigtools._correlateND(in1, in2, out, val) + + else: + ps = [i + j - 1 for i, j in zip(in1.shape, in2.shape)] + + # zero pad input + in1zpadded = np.zeros(ps, in1.dtype) + sc = tuple(slice(0, i) for i in in1.shape) + in1zpadded[sc] = in1.copy() + + if mode == 'full': + out = np.empty(ps, in1.dtype) + elif mode == 'same': + out = np.empty(in1.shape, in1.dtype) + + z = _sigtools._correlateND(in1zpadded, in2, out, val) + + if swapped_inputs: + # Reverse and conjugate to undo the effect of swapping inputs + z = _reverse_and_conj(z) + + return z + + else: + raise ValueError("Acceptable method flags are 'auto'," + " 'direct', or 'fft'.") + + +def correlation_lags(in1_len, in2_len, mode='full'): + r""" + Calculates the lag / displacement indices array for 1D cross-correlation. + + Parameters + ---------- + in1_len : int + First input size. + in2_len : int + Second input size. + mode : str {'full', 'valid', 'same'}, optional + A string indicating the size of the output. + See the documentation `correlate` for more information. + + Returns + ------- + lags : array + Returns an array containing cross-correlation lag/displacement indices. + Indices can be indexed with the np.argmax of the correlation to return + the lag/displacement. + + See Also + -------- + correlate : Compute the N-dimensional cross-correlation. + + Notes + ----- + Cross-correlation for continuous functions :math:`f` and :math:`g` is + defined as: + + .. math:: + + \left ( f\star g \right )\left ( \tau \right ) + \triangleq \int_{t_0}^{t_0 +T} + \overline{f\left ( t \right )}g\left ( t+\tau \right )dt + + Where :math:`\tau` is defined as the displacement, also known as the lag. + + Cross correlation for discrete functions :math:`f` and :math:`g` is + defined as: + + .. math:: + \left ( f\star g \right )\left [ n \right ] + \triangleq \sum_{-\infty}^{\infty} + \overline{f\left [ m \right ]}g\left [ m+n \right ] + + Where :math:`n` is the lag. + + Examples + -------- + Cross-correlation of a signal with its time-delayed self. + + >>> import numpy as np + >>> from scipy import signal + >>> rng = np.random.default_rng() + >>> x = rng.standard_normal(1000) + >>> y = np.concatenate([rng.standard_normal(100), x]) + >>> correlation = signal.correlate(x, y, mode="full") + >>> lags = signal.correlation_lags(x.size, y.size, mode="full") + >>> lag = lags[np.argmax(correlation)] + """ + + # calculate lag ranges in different modes of operation + if mode == "full": + # the output is the full discrete linear convolution + # of the inputs. (Default) + lags = np.arange(-in2_len + 1, in1_len) + elif mode == "same": + # the output is the same size as `in1`, centered + # with respect to the 'full' output. + # calculate the full output + lags = np.arange(-in2_len + 1, in1_len) + # determine the midpoint in the full output + mid = lags.size // 2 + # determine lag_bound to be used with respect + # to the midpoint + lag_bound = in1_len // 2 + # calculate lag ranges for even and odd scenarios + if in1_len % 2 == 0: + lags = lags[(mid-lag_bound):(mid+lag_bound)] + else: + lags = lags[(mid-lag_bound):(mid+lag_bound)+1] + elif mode == "valid": + # the output consists only of those elements that do not + # rely on the zero-padding. In 'valid' mode, either `in1` or `in2` + # must be at least as large as the other in every dimension. + + # the lag_bound will be either negative or positive + # this let's us infer how to present the lag range + lag_bound = in1_len - in2_len + if lag_bound >= 0: + lags = np.arange(lag_bound + 1) + else: + lags = np.arange(lag_bound, 1) + else: + raise ValueError(f"Mode {mode} is invalid") + return lags + + +def _centered(arr, newshape): + # Return the center newshape portion of the array. + newshape = np.asarray(newshape) + currshape = np.array(arr.shape) + startind = (currshape - newshape) // 2 + endind = startind + newshape + myslice = [slice(startind[k], endind[k]) for k in range(len(endind))] + return arr[tuple(myslice)] + + +def _init_freq_conv_axes(in1, in2, mode, axes, sorted_axes=False): + """Handle the axes argument for frequency-domain convolution. + + Returns the inputs and axes in a standard form, eliminating redundant axes, + swapping the inputs if necessary, and checking for various potential + errors. + + Parameters + ---------- + in1 : array + First input. + in2 : array + Second input. + mode : str {'full', 'valid', 'same'}, optional + A string indicating the size of the output. + See the documentation `fftconvolve` for more information. + axes : list of ints + Axes over which to compute the FFTs. + sorted_axes : bool, optional + If `True`, sort the axes. + Default is `False`, do not sort. + + Returns + ------- + in1 : array + The first input, possible swapped with the second input. + in2 : array + The second input, possible swapped with the first input. + axes : list of ints + Axes over which to compute the FFTs. + + """ + s1 = in1.shape + s2 = in2.shape + noaxes = axes is None + + _, axes = _init_nd_shape_and_axes(in1, shape=None, axes=axes) + + if not noaxes and not len(axes): + raise ValueError("when provided, axes cannot be empty") + + # Axes of length 1 can rely on broadcasting rules for multiply, + # no fft needed. + axes = [a for a in axes if s1[a] != 1 and s2[a] != 1] + + if sorted_axes: + axes.sort() + + if not all(s1[a] == s2[a] or s1[a] == 1 or s2[a] == 1 + for a in range(in1.ndim) if a not in axes): + raise ValueError("incompatible shapes for in1 and in2:" + f" {s1} and {s2}") + + # Check that input sizes are compatible with 'valid' mode. + if _inputs_swap_needed(mode, s1, s2, axes=axes): + # Convolution is commutative; order doesn't have any effect on output. + in1, in2 = in2, in1 + + return in1, in2, axes + + +def _freq_domain_conv(in1, in2, axes, shape, calc_fast_len=False): + """Convolve two arrays in the frequency domain. + + This function implements only base the FFT-related operations. + Specifically, it converts the signals to the frequency domain, multiplies + them, then converts them back to the time domain. Calculations of axes, + shapes, convolution mode, etc. are implemented in higher level-functions, + such as `fftconvolve` and `oaconvolve`. Those functions should be used + instead of this one. + + Parameters + ---------- + in1 : array_like + First input. + in2 : array_like + Second input. Should have the same number of dimensions as `in1`. + axes : array_like of ints + Axes over which to compute the FFTs. + shape : array_like of ints + The sizes of the FFTs. + calc_fast_len : bool, optional + If `True`, set each value of `shape` to the next fast FFT length. + Default is `False`, use `axes` as-is. + + Returns + ------- + out : array + An N-dimensional array containing the discrete linear convolution of + `in1` with `in2`. + + """ + if not len(axes): + return in1 * in2 + + complex_result = (in1.dtype.kind == 'c' or in2.dtype.kind == 'c') + + if calc_fast_len: + # Speed up FFT by padding to optimal size. + fshape = [ + sp_fft.next_fast_len(shape[a], not complex_result) for a in axes] + else: + fshape = shape + + if not complex_result: + fft, ifft = sp_fft.rfftn, sp_fft.irfftn + else: + fft, ifft = sp_fft.fftn, sp_fft.ifftn + + sp1 = fft(in1, fshape, axes=axes) + sp2 = fft(in2, fshape, axes=axes) + + ret = ifft(sp1 * sp2, fshape, axes=axes) + + if calc_fast_len: + fslice = tuple([slice(sz) for sz in shape]) + ret = ret[fslice] + + return ret + + +def _apply_conv_mode(ret, s1, s2, mode, axes): + """Calculate the convolution result shape based on the `mode` argument. + + Returns the result sliced to the correct size for the given mode. + + Parameters + ---------- + ret : array + The result array, with the appropriate shape for the 'full' mode. + s1 : list of int + The shape of the first input. + s2 : list of int + The shape of the second input. + mode : str {'full', 'valid', 'same'} + A string indicating the size of the output. + See the documentation `fftconvolve` for more information. + axes : list of ints + Axes over which to compute the convolution. + + Returns + ------- + ret : array + A copy of `res`, sliced to the correct size for the given `mode`. + + """ + if mode == "full": + return ret.copy() + elif mode == "same": + return _centered(ret, s1).copy() + elif mode == "valid": + shape_valid = [ret.shape[a] if a not in axes else s1[a] - s2[a] + 1 + for a in range(ret.ndim)] + return _centered(ret, shape_valid).copy() + else: + raise ValueError("acceptable mode flags are 'valid'," + " 'same', or 'full'") + + +def fftconvolve(in1, in2, mode="full", axes=None): + """Convolve two N-dimensional arrays using FFT. + + Convolve `in1` and `in2` using the fast Fourier transform method, with + the output size determined by the `mode` argument. + + This is generally much faster than `convolve` for large arrays (n > ~500), + but can be slower when only a few output values are needed, and can only + output float arrays (int or object array inputs will be cast to float). + + As of v0.19, `convolve` automatically chooses this method or the direct + method based on an estimation of which is faster. + + Parameters + ---------- + in1 : array_like + First input. + in2 : array_like + Second input. Should have the same number of dimensions as `in1`. + mode : str {'full', 'valid', 'same'}, optional + A string indicating the size of the output: + + ``full`` + The output is the full discrete linear convolution + of the inputs. (Default) + ``valid`` + The output consists only of those elements that do not + rely on the zero-padding. In 'valid' mode, either `in1` or `in2` + must be at least as large as the other in every dimension. + ``same`` + The output is the same size as `in1`, centered + with respect to the 'full' output. + axes : int or array_like of ints or None, optional + Axes over which to compute the convolution. + The default is over all axes. + + Returns + ------- + out : array + An N-dimensional array containing a subset of the discrete linear + convolution of `in1` with `in2`. + + See Also + -------- + convolve : Uses the direct convolution or FFT convolution algorithm + depending on which is faster. + oaconvolve : Uses the overlap-add method to do convolution, which is + generally faster when the input arrays are large and + significantly different in size. + + Examples + -------- + Autocorrelation of white noise is an impulse. + + >>> import numpy as np + >>> from scipy import signal + >>> rng = np.random.default_rng() + >>> sig = rng.standard_normal(1000) + >>> autocorr = signal.fftconvolve(sig, sig[::-1], mode='full') + + >>> import matplotlib.pyplot as plt + >>> fig, (ax_orig, ax_mag) = plt.subplots(2, 1) + >>> ax_orig.plot(sig) + >>> ax_orig.set_title('White noise') + >>> ax_mag.plot(np.arange(-len(sig)+1,len(sig)), autocorr) + >>> ax_mag.set_title('Autocorrelation') + >>> fig.tight_layout() + >>> fig.show() + + Gaussian blur implemented using FFT convolution. Notice the dark borders + around the image, due to the zero-padding beyond its boundaries. + The `convolve2d` function allows for other types of image boundaries, + but is far slower. + + >>> from scipy import datasets + >>> face = datasets.face(gray=True) + >>> kernel = np.outer(signal.windows.gaussian(70, 8), + ... signal.windows.gaussian(70, 8)) + >>> blurred = signal.fftconvolve(face, kernel, mode='same') + + >>> fig, (ax_orig, ax_kernel, ax_blurred) = plt.subplots(3, 1, + ... figsize=(6, 15)) + >>> ax_orig.imshow(face, cmap='gray') + >>> ax_orig.set_title('Original') + >>> ax_orig.set_axis_off() + >>> ax_kernel.imshow(kernel, cmap='gray') + >>> ax_kernel.set_title('Gaussian kernel') + >>> ax_kernel.set_axis_off() + >>> ax_blurred.imshow(blurred, cmap='gray') + >>> ax_blurred.set_title('Blurred') + >>> ax_blurred.set_axis_off() + >>> fig.show() + + """ + in1 = np.asarray(in1) + in2 = np.asarray(in2) + + if in1.ndim == in2.ndim == 0: # scalar inputs + return in1 * in2 + elif in1.ndim != in2.ndim: + raise ValueError("in1 and in2 should have the same dimensionality") + elif in1.size == 0 or in2.size == 0: # empty arrays + return np.array([]) + + in1, in2, axes = _init_freq_conv_axes(in1, in2, mode, axes, + sorted_axes=False) + + s1 = in1.shape + s2 = in2.shape + + shape = [max((s1[i], s2[i])) if i not in axes else s1[i] + s2[i] - 1 + for i in range(in1.ndim)] + + ret = _freq_domain_conv(in1, in2, axes, shape, calc_fast_len=True) + + return _apply_conv_mode(ret, s1, s2, mode, axes) + + +def _calc_oa_lens(s1, s2): + """Calculate the optimal FFT lengths for overlap-add convolution. + + The calculation is done for a single dimension. + + Parameters + ---------- + s1 : int + Size of the dimension for the first array. + s2 : int + Size of the dimension for the second array. + + Returns + ------- + block_size : int + The size of the FFT blocks. + overlap : int + The amount of overlap between two blocks. + in1_step : int + The size of each step for the first array. + in2_step : int + The size of each step for the first array. + + """ + # Set up the arguments for the conventional FFT approach. + fallback = (s1+s2-1, None, s1, s2) + + # Use conventional FFT convolve if sizes are same. + if s1 == s2 or s1 == 1 or s2 == 1: + return fallback + + if s2 > s1: + s1, s2 = s2, s1 + swapped = True + else: + swapped = False + + # There cannot be a useful block size if s2 is more than half of s1. + if s2 >= s1/2: + return fallback + + # Derivation of optimal block length + # For original formula see: + # https://en.wikipedia.org/wiki/Overlap-add_method + # + # Formula: + # K = overlap = s2-1 + # N = block_size + # C = complexity + # e = exponential, exp(1) + # + # C = (N*(log2(N)+1))/(N-K) + # C = (N*log2(2N))/(N-K) + # C = N/(N-K) * log2(2N) + # C1 = N/(N-K) + # C2 = log2(2N) = ln(2N)/ln(2) + # + # dC1/dN = (1*(N-K)-N)/(N-K)^2 = -K/(N-K)^2 + # dC2/dN = 2/(2*N*ln(2)) = 1/(N*ln(2)) + # + # dC/dN = dC1/dN*C2 + dC2/dN*C1 + # dC/dN = -K*ln(2N)/(ln(2)*(N-K)^2) + N/(N*ln(2)*(N-K)) + # dC/dN = -K*ln(2N)/(ln(2)*(N-K)^2) + 1/(ln(2)*(N-K)) + # dC/dN = -K*ln(2N)/(ln(2)*(N-K)^2) + (N-K)/(ln(2)*(N-K)^2) + # dC/dN = (-K*ln(2N) + (N-K)/(ln(2)*(N-K)^2) + # dC/dN = (N - K*ln(2N) - K)/(ln(2)*(N-K)^2) + # + # Solve for minimum, where dC/dN = 0 + # 0 = (N - K*ln(2N) - K)/(ln(2)*(N-K)^2) + # 0 * ln(2)*(N-K)^2 = N - K*ln(2N) - K + # 0 = N - K*ln(2N) - K + # 0 = N - K*(ln(2N) + 1) + # 0 = N - K*ln(2Ne) + # N = K*ln(2Ne) + # N/K = ln(2Ne) + # + # e^(N/K) = e^ln(2Ne) + # e^(N/K) = 2Ne + # 1/e^(N/K) = 1/(2*N*e) + # e^(N/-K) = 1/(2*N*e) + # e^(N/-K) = K/N*1/(2*K*e) + # N/K*e^(N/-K) = 1/(2*e*K) + # N/-K*e^(N/-K) = -1/(2*e*K) + # + # Using Lambert W function + # https://en.wikipedia.org/wiki/Lambert_W_function + # x = W(y) It is the solution to y = x*e^x + # x = N/-K + # y = -1/(2*e*K) + # + # N/-K = W(-1/(2*e*K)) + # + # N = -K*W(-1/(2*e*K)) + overlap = s2-1 + opt_size = -overlap*lambertw(-1/(2*math.e*overlap), k=-1).real + block_size = sp_fft.next_fast_len(math.ceil(opt_size)) + + # Use conventional FFT convolve if there is only going to be one block. + if block_size >= s1: + return fallback + + if not swapped: + in1_step = block_size-s2+1 + in2_step = s2 + else: + in1_step = s2 + in2_step = block_size-s2+1 + + return block_size, overlap, in1_step, in2_step + + +def oaconvolve(in1, in2, mode="full", axes=None): + """Convolve two N-dimensional arrays using the overlap-add method. + + Convolve `in1` and `in2` using the overlap-add method, with + the output size determined by the `mode` argument. + + This is generally much faster than `convolve` for large arrays (n > ~500), + and generally much faster than `fftconvolve` when one array is much + larger than the other, but can be slower when only a few output values are + needed or when the arrays are very similar in shape, and can only + output float arrays (int or object array inputs will be cast to float). + + Parameters + ---------- + in1 : array_like + First input. + in2 : array_like + Second input. Should have the same number of dimensions as `in1`. + mode : str {'full', 'valid', 'same'}, optional + A string indicating the size of the output: + + ``full`` + The output is the full discrete linear convolution + of the inputs. (Default) + ``valid`` + The output consists only of those elements that do not + rely on the zero-padding. In 'valid' mode, either `in1` or `in2` + must be at least as large as the other in every dimension. + ``same`` + The output is the same size as `in1`, centered + with respect to the 'full' output. + axes : int or array_like of ints or None, optional + Axes over which to compute the convolution. + The default is over all axes. + + Returns + ------- + out : array + An N-dimensional array containing a subset of the discrete linear + convolution of `in1` with `in2`. + + See Also + -------- + convolve : Uses the direct convolution or FFT convolution algorithm + depending on which is faster. + fftconvolve : An implementation of convolution using FFT. + + Notes + ----- + .. versionadded:: 1.4.0 + + References + ---------- + .. [1] Wikipedia, "Overlap-add_method". + https://en.wikipedia.org/wiki/Overlap-add_method + .. [2] Richard G. Lyons. Understanding Digital Signal Processing, + Third Edition, 2011. Chapter 13.10. + ISBN 13: 978-0137-02741-5 + + Examples + -------- + Convolve a 100,000 sample signal with a 512-sample filter. + + >>> import numpy as np + >>> from scipy import signal + >>> rng = np.random.default_rng() + >>> sig = rng.standard_normal(100000) + >>> filt = signal.firwin(512, 0.01) + >>> fsig = signal.oaconvolve(sig, filt) + + >>> import matplotlib.pyplot as plt + >>> fig, (ax_orig, ax_mag) = plt.subplots(2, 1) + >>> ax_orig.plot(sig) + >>> ax_orig.set_title('White noise') + >>> ax_mag.plot(fsig) + >>> ax_mag.set_title('Filtered noise') + >>> fig.tight_layout() + >>> fig.show() + + """ + in1 = np.asarray(in1) + in2 = np.asarray(in2) + + if in1.ndim == in2.ndim == 0: # scalar inputs + return in1 * in2 + elif in1.ndim != in2.ndim: + raise ValueError("in1 and in2 should have the same dimensionality") + elif in1.size == 0 or in2.size == 0: # empty arrays + return np.array([]) + elif in1.shape == in2.shape: # Equivalent to fftconvolve + return fftconvolve(in1, in2, mode=mode, axes=axes) + + in1, in2, axes = _init_freq_conv_axes(in1, in2, mode, axes, + sorted_axes=True) + + s1 = in1.shape + s2 = in2.shape + + if not axes: + ret = in1 * in2 + return _apply_conv_mode(ret, s1, s2, mode, axes) + + # Calculate this now since in1 is changed later + shape_final = [None if i not in axes else + s1[i] + s2[i] - 1 for i in range(in1.ndim)] + + # Calculate the block sizes for the output, steps, first and second inputs. + # It is simpler to calculate them all together than doing them in separate + # loops due to all the special cases that need to be handled. + optimal_sizes = ((-1, -1, s1[i], s2[i]) if i not in axes else + _calc_oa_lens(s1[i], s2[i]) for i in range(in1.ndim)) + block_size, overlaps, \ + in1_step, in2_step = zip(*optimal_sizes) + + # Fall back to fftconvolve if there is only one block in every dimension. + if in1_step == s1 and in2_step == s2: + return fftconvolve(in1, in2, mode=mode, axes=axes) + + # Figure out the number of steps and padding. + # This would get too complicated in a list comprehension. + nsteps1 = [] + nsteps2 = [] + pad_size1 = [] + pad_size2 = [] + for i in range(in1.ndim): + if i not in axes: + pad_size1 += [(0, 0)] + pad_size2 += [(0, 0)] + continue + + if s1[i] > in1_step[i]: + curnstep1 = math.ceil((s1[i]+1)/in1_step[i]) + if (block_size[i] - overlaps[i])*curnstep1 < shape_final[i]: + curnstep1 += 1 + + curpad1 = curnstep1*in1_step[i] - s1[i] + else: + curnstep1 = 1 + curpad1 = 0 + + if s2[i] > in2_step[i]: + curnstep2 = math.ceil((s2[i]+1)/in2_step[i]) + if (block_size[i] - overlaps[i])*curnstep2 < shape_final[i]: + curnstep2 += 1 + + curpad2 = curnstep2*in2_step[i] - s2[i] + else: + curnstep2 = 1 + curpad2 = 0 + + nsteps1 += [curnstep1] + nsteps2 += [curnstep2] + pad_size1 += [(0, curpad1)] + pad_size2 += [(0, curpad2)] + + # Pad the array to a size that can be reshaped to the desired shape + # if necessary. + if not all(curpad == (0, 0) for curpad in pad_size1): + in1 = np.pad(in1, pad_size1, mode='constant', constant_values=0) + + if not all(curpad == (0, 0) for curpad in pad_size2): + in2 = np.pad(in2, pad_size2, mode='constant', constant_values=0) + + # Reshape the overlap-add parts to input block sizes. + split_axes = [iax+i for i, iax in enumerate(axes)] + fft_axes = [iax+1 for iax in split_axes] + + # We need to put each new dimension before the corresponding dimension + # being reshaped in order to get the data in the right layout at the end. + reshape_size1 = list(in1_step) + reshape_size2 = list(in2_step) + for i, iax in enumerate(split_axes): + reshape_size1.insert(iax, nsteps1[i]) + reshape_size2.insert(iax, nsteps2[i]) + + in1 = in1.reshape(*reshape_size1) + in2 = in2.reshape(*reshape_size2) + + # Do the convolution. + fft_shape = [block_size[i] for i in axes] + ret = _freq_domain_conv(in1, in2, fft_axes, fft_shape, calc_fast_len=False) + + # Do the overlap-add. + for ax, ax_fft, ax_split in zip(axes, fft_axes, split_axes): + overlap = overlaps[ax] + if overlap is None: + continue + + ret, overpart = np.split(ret, [-overlap], ax_fft) + overpart = np.split(overpart, [-1], ax_split)[0] + + ret_overpart = np.split(ret, [overlap], ax_fft)[0] + ret_overpart = np.split(ret_overpart, [1], ax_split)[1] + ret_overpart += overpart + + # Reshape back to the correct dimensionality. + shape_ret = [ret.shape[i] if i not in fft_axes else + ret.shape[i]*ret.shape[i-1] + for i in range(ret.ndim) if i not in split_axes] + ret = ret.reshape(*shape_ret) + + # Slice to the correct size. + slice_final = tuple([slice(islice) for islice in shape_final]) + ret = ret[slice_final] + + return _apply_conv_mode(ret, s1, s2, mode, axes) + + +def _numeric_arrays(arrays, kinds='buifc'): + """ + See if a list of arrays are all numeric. + + Parameters + ---------- + arrays : array or list of arrays + arrays to check if numeric. + kinds : string-like + The dtypes of the arrays to be checked. If the dtype.kind of + the ndarrays are not in this string the function returns False and + otherwise returns True. + """ + if isinstance(arrays, np.ndarray): + return arrays.dtype.kind in kinds + for array_ in arrays: + if array_.dtype.kind not in kinds: + return False + return True + + +def _conv_ops(x_shape, h_shape, mode): + """ + Find the number of operations required for direct/fft methods of + convolution. The direct operations were recorded by making a dummy class to + record the number of operations by overriding ``__mul__`` and ``__add__``. + The FFT operations rely on the (well-known) computational complexity of the + FFT (and the implementation of ``_freq_domain_conv``). + + """ + if mode == "full": + out_shape = [n + k - 1 for n, k in zip(x_shape, h_shape)] + elif mode == "valid": + out_shape = [abs(n - k) + 1 for n, k in zip(x_shape, h_shape)] + elif mode == "same": + out_shape = x_shape + else: + raise ValueError("Acceptable mode flags are 'valid'," + f" 'same', or 'full', not mode={mode}") + + s1, s2 = x_shape, h_shape + if len(x_shape) == 1: + s1, s2 = s1[0], s2[0] + if mode == "full": + direct_ops = s1 * s2 + elif mode == "valid": + direct_ops = (s2 - s1 + 1) * s1 if s2 >= s1 else (s1 - s2 + 1) * s2 + elif mode == "same": + direct_ops = (s1 * s2 if s1 < s2 else + s1 * s2 - (s2 // 2) * ((s2 + 1) // 2)) + else: + if mode == "full": + direct_ops = min(_prod(s1), _prod(s2)) * _prod(out_shape) + elif mode == "valid": + direct_ops = min(_prod(s1), _prod(s2)) * _prod(out_shape) + elif mode == "same": + direct_ops = _prod(s1) * _prod(s2) + + full_out_shape = [n + k - 1 for n, k in zip(x_shape, h_shape)] + N = _prod(full_out_shape) + fft_ops = 3 * N * np.log(N) # 3 separate FFTs of size full_out_shape + return fft_ops, direct_ops + + +def _fftconv_faster(x, h, mode): + """ + See if using fftconvolve or convolve is faster. + + Parameters + ---------- + x : np.ndarray + Signal + h : np.ndarray + Kernel + mode : str + Mode passed to convolve + + Returns + ------- + fft_faster : bool + + Notes + ----- + See docstring of `choose_conv_method` for details on tuning hardware. + + See pull request 11031 for more detail: + https://github.com/scipy/scipy/pull/11031. + + """ + fft_ops, direct_ops = _conv_ops(x.shape, h.shape, mode) + offset = -1e-3 if x.ndim == 1 else -1e-4 + constants = { + "valid": (1.89095737e-9, 2.1364985e-10, offset), + "full": (1.7649070e-9, 2.1414831e-10, offset), + "same": (3.2646654e-9, 2.8478277e-10, offset) + if h.size <= x.size + else (3.21635404e-9, 1.1773253e-8, -1e-5), + } if x.ndim == 1 else { + "valid": (1.85927e-9, 2.11242e-8, offset), + "full": (1.99817e-9, 1.66174e-8, offset), + "same": (2.04735e-9, 1.55367e-8, offset), + } + O_fft, O_direct, O_offset = constants[mode] + return O_fft * fft_ops < O_direct * direct_ops + O_offset + + +def _reverse_and_conj(x): + """ + Reverse array `x` in all dimensions and perform the complex conjugate + """ + reverse = (slice(None, None, -1),) * x.ndim + return x[reverse].conj() + + +def _np_conv_ok(volume, kernel, mode): + """ + See if numpy supports convolution of `volume` and `kernel` (i.e. both are + 1D ndarrays and of the appropriate shape). NumPy's 'same' mode uses the + size of the larger input, while SciPy's uses the size of the first input. + + Invalid mode strings will return False and be caught by the calling func. + """ + if volume.ndim == kernel.ndim == 1: + if mode in ('full', 'valid'): + return True + elif mode == 'same': + return volume.size >= kernel.size + else: + return False + + +def _timeit_fast(stmt="pass", setup="pass", repeat=3): + """ + Returns the time the statement/function took, in seconds. + + Faster, less precise version of IPython's timeit. `stmt` can be a statement + written as a string or a callable. + + Will do only 1 loop (like IPython's timeit) with no repetitions + (unlike IPython) for very slow functions. For fast functions, only does + enough loops to take 5 ms, which seems to produce similar results (on + Windows at least), and avoids doing an extraneous cycle that isn't + measured. + + """ + timer = timeit.Timer(stmt, setup) + + # determine number of calls per rep so total time for 1 rep >= 5 ms + x = 0 + for p in range(0, 10): + number = 10**p + x = timer.timeit(number) # seconds + if x >= 5e-3 / 10: # 5 ms for final test, 1/10th that for this one + break + if x > 1: # second + # If it's macroscopic, don't bother with repetitions + best = x + else: + number *= 10 + r = timer.repeat(repeat, number) + best = min(r) + + sec = best / number + return sec + + +def choose_conv_method(in1, in2, mode='full', measure=False): + """ + Find the fastest convolution/correlation method. + + This primarily exists to be called during the ``method='auto'`` option in + `convolve` and `correlate`. It can also be used to determine the value of + ``method`` for many different convolutions of the same dtype/shape. + In addition, it supports timing the convolution to adapt the value of + ``method`` to a particular set of inputs and/or hardware. + + Parameters + ---------- + in1 : array_like + The first argument passed into the convolution function. + in2 : array_like + The second argument passed into the convolution function. + mode : str {'full', 'valid', 'same'}, optional + A string indicating the size of the output: + + ``full`` + The output is the full discrete linear convolution + of the inputs. (Default) + ``valid`` + The output consists only of those elements that do not + rely on the zero-padding. + ``same`` + The output is the same size as `in1`, centered + with respect to the 'full' output. + measure : bool, optional + If True, run and time the convolution of `in1` and `in2` with both + methods and return the fastest. If False (default), predict the fastest + method using precomputed values. + + Returns + ------- + method : str + A string indicating which convolution method is fastest, either + 'direct' or 'fft' + times : dict, optional + A dictionary containing the times (in seconds) needed for each method. + This value is only returned if ``measure=True``. + + See Also + -------- + convolve + correlate + + Notes + ----- + Generally, this method is 99% accurate for 2D signals and 85% accurate + for 1D signals for randomly chosen input sizes. For precision, use + ``measure=True`` to find the fastest method by timing the convolution. + This can be used to avoid the minimal overhead of finding the fastest + ``method`` later, or to adapt the value of ``method`` to a particular set + of inputs. + + Experiments were run on an Amazon EC2 r5a.2xlarge machine to test this + function. These experiments measured the ratio between the time required + when using ``method='auto'`` and the time required for the fastest method + (i.e., ``ratio = time_auto / min(time_fft, time_direct)``). In these + experiments, we found: + + * There is a 95% chance of this ratio being less than 1.5 for 1D signals + and a 99% chance of being less than 2.5 for 2D signals. + * The ratio was always less than 2.5/5 for 1D/2D signals respectively. + * This function is most inaccurate for 1D convolutions that take between 1 + and 10 milliseconds with ``method='direct'``. A good proxy for this + (at least in our experiments) is ``1e6 <= in1.size * in2.size <= 1e7``. + + The 2D results almost certainly generalize to 3D/4D/etc because the + implementation is the same (the 1D implementation is different). + + All the numbers above are specific to the EC2 machine. However, we did find + that this function generalizes fairly decently across hardware. The speed + tests were of similar quality (and even slightly better) than the same + tests performed on the machine to tune this function's numbers (a mid-2014 + 15-inch MacBook Pro with 16GB RAM and a 2.5GHz Intel i7 processor). + + There are cases when `fftconvolve` supports the inputs but this function + returns `direct` (e.g., to protect against floating point integer + precision). + + .. versionadded:: 0.19 + + Examples + -------- + Estimate the fastest method for a given input: + + >>> import numpy as np + >>> from scipy import signal + >>> rng = np.random.default_rng() + >>> img = rng.random((32, 32)) + >>> filter = rng.random((8, 8)) + >>> method = signal.choose_conv_method(img, filter, mode='same') + >>> method + 'fft' + + This can then be applied to other arrays of the same dtype and shape: + + >>> img2 = rng.random((32, 32)) + >>> filter2 = rng.random((8, 8)) + >>> corr2 = signal.correlate(img2, filter2, mode='same', method=method) + >>> conv2 = signal.convolve(img2, filter2, mode='same', method=method) + + The output of this function (``method``) works with `correlate` and + `convolve`. + + """ + volume = np.asarray(in1) + kernel = np.asarray(in2) + + _reject_objects(volume, 'choose_conv_method') + _reject_objects(kernel, 'choose_conv_method') + + if measure: + times = {} + for method in ['fft', 'direct']: + times[method] = _timeit_fast(lambda: convolve(volume, kernel, + mode=mode, method=method)) + + chosen_method = 'fft' if times['fft'] < times['direct'] else 'direct' + return chosen_method, times + + # for integer input, + # catch when more precision required than float provides (representing an + # integer as float can lose precision in fftconvolve if larger than 2**52) + if any([_numeric_arrays([x], kinds='ui') for x in [volume, kernel]]): + max_value = int(np.abs(volume).max()) * int(np.abs(kernel).max()) + max_value *= int(min(volume.size, kernel.size)) + if max_value > 2**np.finfo('float').nmant - 1: + return 'direct' + + if _numeric_arrays([volume, kernel], kinds='b'): + return 'direct' + + if _numeric_arrays([volume, kernel]): + if _fftconv_faster(volume, kernel, mode): + return 'fft' + + return 'direct' + + +def convolve(in1, in2, mode='full', method='auto'): + """ + Convolve two N-dimensional arrays. + + Convolve `in1` and `in2`, with the output size determined by the + `mode` argument. + + Parameters + ---------- + in1 : array_like + First input. + in2 : array_like + Second input. Should have the same number of dimensions as `in1`. + mode : str {'full', 'valid', 'same'}, optional + A string indicating the size of the output: + + ``full`` + The output is the full discrete linear convolution + of the inputs. (Default) + ``valid`` + The output consists only of those elements that do not + rely on the zero-padding. In 'valid' mode, either `in1` or `in2` + must be at least as large as the other in every dimension. + ``same`` + The output is the same size as `in1`, centered + with respect to the 'full' output. + method : str {'auto', 'direct', 'fft'}, optional + A string indicating which method to use to calculate the convolution. + + ``direct`` + The convolution is determined directly from sums, the definition of + convolution. + ``fft`` + The Fourier Transform is used to perform the convolution by calling + `fftconvolve`. + ``auto`` + Automatically chooses direct or Fourier method based on an estimate + of which is faster (default). See Notes for more detail. + + .. versionadded:: 0.19.0 + + Returns + ------- + convolve : array + An N-dimensional array containing a subset of the discrete linear + convolution of `in1` with `in2`. + + Warns + ----- + RuntimeWarning + Use of the FFT convolution on input containing NAN or INF will lead + to the entire output being NAN or INF. Use method='direct' when your + input contains NAN or INF values. + + See Also + -------- + numpy.polymul : performs polynomial multiplication (same operation, but + also accepts poly1d objects) + choose_conv_method : chooses the fastest appropriate convolution method + fftconvolve : Always uses the FFT method. + oaconvolve : Uses the overlap-add method to do convolution, which is + generally faster when the input arrays are large and + significantly different in size. + + Notes + ----- + By default, `convolve` and `correlate` use ``method='auto'``, which calls + `choose_conv_method` to choose the fastest method using pre-computed + values (`choose_conv_method` can also measure real-world timing with a + keyword argument). Because `fftconvolve` relies on floating point numbers, + there are certain constraints that may force ``method='direct'`` (more detail + in `choose_conv_method` docstring). + + Examples + -------- + Smooth a square pulse using a Hann window: + + >>> import numpy as np + >>> from scipy import signal + >>> sig = np.repeat([0., 1., 0.], 100) + >>> win = signal.windows.hann(50) + >>> filtered = signal.convolve(sig, win, mode='same') / sum(win) + + >>> import matplotlib.pyplot as plt + >>> fig, (ax_orig, ax_win, ax_filt) = plt.subplots(3, 1, sharex=True) + >>> ax_orig.plot(sig) + >>> ax_orig.set_title('Original pulse') + >>> ax_orig.margins(0, 0.1) + >>> ax_win.plot(win) + >>> ax_win.set_title('Filter impulse response') + >>> ax_win.margins(0, 0.1) + >>> ax_filt.plot(filtered) + >>> ax_filt.set_title('Filtered signal') + >>> ax_filt.margins(0, 0.1) + >>> fig.tight_layout() + >>> fig.show() + + """ + volume = np.asarray(in1) + kernel = np.asarray(in2) + + _reject_objects(volume, 'correlate') + _reject_objects(kernel, 'correlate') + + if volume.ndim == kernel.ndim == 0: + return volume * kernel + elif volume.ndim != kernel.ndim: + raise ValueError("volume and kernel should have the same " + "dimensionality") + + if _inputs_swap_needed(mode, volume.shape, kernel.shape): + # Convolution is commutative; order doesn't have any effect on output + volume, kernel = kernel, volume + + if method == 'auto': + method = choose_conv_method(volume, kernel, mode=mode) + + if method == 'fft': + out = fftconvolve(volume, kernel, mode=mode) + result_type = np.result_type(volume, kernel) + if result_type.kind in {'u', 'i'}: + out = np.around(out) + + if np.isnan(out.flat[0]) or np.isinf(out.flat[0]): + warnings.warn("Use of fft convolution on input with NAN or inf" + " results in NAN or inf output. Consider using" + " method='direct' instead.", + category=RuntimeWarning, stacklevel=2) + + return out.astype(result_type) + elif method == 'direct': + # fastpath to faster numpy.convolve for 1d inputs when possible + if _np_conv_ok(volume, kernel, mode): + return np.convolve(volume, kernel, mode) + + return correlate(volume, _reverse_and_conj(kernel), mode, 'direct') + else: + raise ValueError("Acceptable method flags are 'auto'," + " 'direct', or 'fft'.") + + +def order_filter(a, domain, rank): + """ + Perform an order filter on an N-D array. + + Perform an order filter on the array in. The domain argument acts as a + mask centered over each pixel. The non-zero elements of domain are + used to select elements surrounding each input pixel which are placed + in a list. The list is sorted, and the output for that pixel is the + element corresponding to rank in the sorted list. + + Parameters + ---------- + a : ndarray + The N-dimensional input array. + domain : array_like + A mask array with the same number of dimensions as `a`. + Each dimension should have an odd number of elements. + rank : int + A non-negative integer which selects the element from the + sorted list (0 corresponds to the smallest element, 1 is the + next smallest element, etc.). + + Returns + ------- + out : ndarray + The results of the order filter in an array with the same + shape as `a`. + + Examples + -------- + >>> import numpy as np + >>> from scipy import signal + >>> x = np.arange(25).reshape(5, 5) + >>> domain = np.identity(3) + >>> x + array([[ 0, 1, 2, 3, 4], + [ 5, 6, 7, 8, 9], + [10, 11, 12, 13, 14], + [15, 16, 17, 18, 19], + [20, 21, 22, 23, 24]]) + >>> signal.order_filter(x, domain, 0) + array([[ 0, 0, 0, 0, 0], + [ 0, 0, 1, 2, 0], + [ 0, 5, 6, 7, 0], + [ 0, 10, 11, 12, 0], + [ 0, 0, 0, 0, 0]]) + >>> signal.order_filter(x, domain, 2) + array([[ 6, 7, 8, 9, 4], + [ 11, 12, 13, 14, 9], + [ 16, 17, 18, 19, 14], + [ 21, 22, 23, 24, 19], + [ 20, 21, 22, 23, 24]]) + + """ + domain = np.asarray(domain) + for dimsize in domain.shape: + if (dimsize % 2) != 1: + raise ValueError("Each dimension of domain argument " + "should have an odd number of elements.") + + a = np.asarray(a) + if not (np.issubdtype(a.dtype, np.integer) + or a.dtype in [np.float32, np.float64]): + raise ValueError(f"dtype={a.dtype} is not supported by order_filter") + + result = ndimage.rank_filter(a, rank, footprint=domain, mode='constant') + return result + + +def medfilt(volume, kernel_size=None): + """ + Perform a median filter on an N-dimensional array. + + Apply a median filter to the input array using a local window-size + given by `kernel_size`. The array will automatically be zero-padded. + + Parameters + ---------- + volume : array_like + An N-dimensional input array. + kernel_size : array_like, optional + A scalar or an N-length list giving the size of the median filter + window in each dimension. Elements of `kernel_size` should be odd. + If `kernel_size` is a scalar, then this scalar is used as the size in + each dimension. Default size is 3 for each dimension. + + Returns + ------- + out : ndarray + An array the same size as input containing the median filtered + result. + + Warns + ----- + UserWarning + If array size is smaller than kernel size along any dimension + + See Also + -------- + scipy.ndimage.median_filter + scipy.signal.medfilt2d + + Notes + ----- + The more general function `scipy.ndimage.median_filter` has a more + efficient implementation of a median filter and therefore runs much faster. + + For 2-dimensional images with ``uint8``, ``float32`` or ``float64`` dtypes, + the specialised function `scipy.signal.medfilt2d` may be faster. + + """ + volume = np.atleast_1d(volume) + if not (np.issubdtype(volume.dtype, np.integer) + or volume.dtype in [np.float32, np.float64]): + raise ValueError(f"dtype={volume.dtype} is not supported by medfilt") + + if kernel_size is None: + kernel_size = [3] * volume.ndim + kernel_size = np.asarray(kernel_size) + if kernel_size.shape == (): + kernel_size = np.repeat(kernel_size.item(), volume.ndim) + + for k in range(volume.ndim): + if (kernel_size[k] % 2) != 1: + raise ValueError("Each element of kernel_size should be odd.") + if any(k > s for k, s in zip(kernel_size, volume.shape)): + warnings.warn('kernel_size exceeds volume extent: the volume will be ' + 'zero-padded.', + stacklevel=2) + + size = math.prod(kernel_size) + result = ndimage.rank_filter(volume, size // 2, size=kernel_size, + mode='constant') + + return result + + +def wiener(im, mysize=None, noise=None): + """ + Perform a Wiener filter on an N-dimensional array. + + Apply a Wiener filter to the N-dimensional array `im`. + + Parameters + ---------- + im : ndarray + An N-dimensional array. + mysize : int or array_like, optional + A scalar or an N-length list giving the size of the Wiener filter + window in each dimension. Elements of mysize should be odd. + If mysize is a scalar, then this scalar is used as the size + in each dimension. + noise : float, optional + The noise-power to use. If None, then noise is estimated as the + average of the local variance of the input. + + Returns + ------- + out : ndarray + Wiener filtered result with the same shape as `im`. + + Notes + ----- + This implementation is similar to wiener2 in Matlab/Octave. + For more details see [1]_ + + References + ---------- + .. [1] Lim, Jae S., Two-Dimensional Signal and Image Processing, + Englewood Cliffs, NJ, Prentice Hall, 1990, p. 548. + + Examples + -------- + >>> from scipy.datasets import face + >>> from scipy.signal import wiener + >>> import matplotlib.pyplot as plt + >>> import numpy as np + >>> rng = np.random.default_rng() + >>> img = rng.random((40, 40)) #Create a random image + >>> filtered_img = wiener(img, (5, 5)) #Filter the image + >>> f, (plot1, plot2) = plt.subplots(1, 2) + >>> plot1.imshow(img) + >>> plot2.imshow(filtered_img) + >>> plt.show() + + """ + im = np.asarray(im) + if mysize is None: + mysize = [3] * im.ndim + mysize = np.asarray(mysize) + if mysize.shape == (): + mysize = np.repeat(mysize.item(), im.ndim) + + # Estimate the local mean + size = math.prod(mysize) + lMean = correlate(im, np.ones(mysize), 'same') / size + + # Estimate the local variance + lVar = (correlate(im ** 2, np.ones(mysize), 'same') / size - lMean ** 2) + + # Estimate the noise power if needed. + if noise is None: + noise = np.mean(np.ravel(lVar), axis=0) + + res = (im - lMean) + res *= (1 - noise / lVar) + res += lMean + out = np.where(lVar < noise, lMean, res) + + return out + + +def convolve2d(in1, in2, mode='full', boundary='fill', fillvalue=0): + """ + Convolve two 2-dimensional arrays. + + Convolve `in1` and `in2` with output size determined by `mode`, and + boundary conditions determined by `boundary` and `fillvalue`. + + Parameters + ---------- + in1 : array_like + First input. + in2 : array_like + Second input. Should have the same number of dimensions as `in1`. + mode : str {'full', 'valid', 'same'}, optional + A string indicating the size of the output: + + ``full`` + The output is the full discrete linear convolution + of the inputs. (Default) + ``valid`` + The output consists only of those elements that do not + rely on the zero-padding. In 'valid' mode, either `in1` or `in2` + must be at least as large as the other in every dimension. + ``same`` + The output is the same size as `in1`, centered + with respect to the 'full' output. + boundary : str {'fill', 'wrap', 'symm'}, optional + A flag indicating how to handle boundaries: + + ``fill`` + pad input arrays with fillvalue. (default) + ``wrap`` + circular boundary conditions. + ``symm`` + symmetrical boundary conditions. + + fillvalue : scalar, optional + Value to fill pad input arrays with. Default is 0. + + Returns + ------- + out : ndarray + A 2-dimensional array containing a subset of the discrete linear + convolution of `in1` with `in2`. + + Examples + -------- + Compute the gradient of an image by 2D convolution with a complex Scharr + operator. (Horizontal operator is real, vertical is imaginary.) Use + symmetric boundary condition to avoid creating edges at the image + boundaries. + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy import datasets + >>> ascent = datasets.ascent() + >>> scharr = np.array([[ -3-3j, 0-10j, +3 -3j], + ... [-10+0j, 0+ 0j, +10 +0j], + ... [ -3+3j, 0+10j, +3 +3j]]) # Gx + j*Gy + >>> grad = signal.convolve2d(ascent, scharr, boundary='symm', mode='same') + + >>> import matplotlib.pyplot as plt + >>> fig, (ax_orig, ax_mag, ax_ang) = plt.subplots(3, 1, figsize=(6, 15)) + >>> ax_orig.imshow(ascent, cmap='gray') + >>> ax_orig.set_title('Original') + >>> ax_orig.set_axis_off() + >>> ax_mag.imshow(np.absolute(grad), cmap='gray') + >>> ax_mag.set_title('Gradient magnitude') + >>> ax_mag.set_axis_off() + >>> ax_ang.imshow(np.angle(grad), cmap='hsv') # hsv is cyclic, like angles + >>> ax_ang.set_title('Gradient orientation') + >>> ax_ang.set_axis_off() + >>> fig.show() + + """ + in1 = np.asarray(in1) + in2 = np.asarray(in2) + + if not in1.ndim == in2.ndim == 2: + raise ValueError('convolve2d inputs must both be 2-D arrays') + + if _inputs_swap_needed(mode, in1.shape, in2.shape): + in1, in2 = in2, in1 + + val = _valfrommode(mode) + bval = _bvalfromboundary(boundary) + out = _sigtools._convolve2d(in1, in2, 1, val, bval, fillvalue) + return out + + +def correlate2d(in1, in2, mode='full', boundary='fill', fillvalue=0): + """ + Cross-correlate two 2-dimensional arrays. + + Cross correlate `in1` and `in2` with output size determined by `mode`, and + boundary conditions determined by `boundary` and `fillvalue`. + + Parameters + ---------- + in1 : array_like + First input. + in2 : array_like + Second input. Should have the same number of dimensions as `in1`. + mode : str {'full', 'valid', 'same'}, optional + A string indicating the size of the output: + + ``full`` + The output is the full discrete linear cross-correlation + of the inputs. (Default) + ``valid`` + The output consists only of those elements that do not + rely on the zero-padding. In 'valid' mode, either `in1` or `in2` + must be at least as large as the other in every dimension. + ``same`` + The output is the same size as `in1`, centered + with respect to the 'full' output. + boundary : str {'fill', 'wrap', 'symm'}, optional + A flag indicating how to handle boundaries: + + ``fill`` + pad input arrays with fillvalue. (default) + ``wrap`` + circular boundary conditions. + ``symm`` + symmetrical boundary conditions. + + fillvalue : scalar, optional + Value to fill pad input arrays with. Default is 0. + + Returns + ------- + correlate2d : ndarray + A 2-dimensional array containing a subset of the discrete linear + cross-correlation of `in1` with `in2`. + + Notes + ----- + When using "same" mode with even-length inputs, the outputs of `correlate` + and `correlate2d` differ: There is a 1-index offset between them. + + Examples + -------- + Use 2D cross-correlation to find the location of a template in a noisy + image: + + >>> import numpy as np + >>> from scipy import signal, datasets, ndimage + >>> rng = np.random.default_rng() + >>> face = datasets.face(gray=True) - datasets.face(gray=True).mean() + >>> face = ndimage.zoom(face[30:500, 400:950], 0.5) # extract the face + >>> template = np.copy(face[135:165, 140:175]) # right eye + >>> template -= template.mean() + >>> face = face + rng.standard_normal(face.shape) * 50 # add noise + >>> corr = signal.correlate2d(face, template, boundary='symm', mode='same') + >>> y, x = np.unravel_index(np.argmax(corr), corr.shape) # find the match + + >>> import matplotlib.pyplot as plt + >>> fig, (ax_orig, ax_template, ax_corr) = plt.subplots(3, 1, + ... figsize=(6, 15)) + >>> ax_orig.imshow(face, cmap='gray') + >>> ax_orig.set_title('Original') + >>> ax_orig.set_axis_off() + >>> ax_template.imshow(template, cmap='gray') + >>> ax_template.set_title('Template') + >>> ax_template.set_axis_off() + >>> ax_corr.imshow(corr, cmap='gray') + >>> ax_corr.set_title('Cross-correlation') + >>> ax_corr.set_axis_off() + >>> ax_orig.plot(x, y, 'ro') + >>> fig.show() + + """ + in1 = np.asarray(in1) + in2 = np.asarray(in2) + + if not in1.ndim == in2.ndim == 2: + raise ValueError('correlate2d inputs must both be 2-D arrays') + + swapped_inputs = _inputs_swap_needed(mode, in1.shape, in2.shape) + if swapped_inputs: + in1, in2 = in2, in1 + + val = _valfrommode(mode) + bval = _bvalfromboundary(boundary) + out = _sigtools._convolve2d(in1, in2.conj(), 0, val, bval, fillvalue) + + if swapped_inputs: + out = out[::-1, ::-1] + + return out + + +def medfilt2d(input, kernel_size=3): + """ + Median filter a 2-dimensional array. + + Apply a median filter to the `input` array using a local window-size + given by `kernel_size` (must be odd). The array is zero-padded + automatically. + + Parameters + ---------- + input : array_like + A 2-dimensional input array. + kernel_size : array_like, optional + A scalar or a list of length 2, giving the size of the + median filter window in each dimension. Elements of + `kernel_size` should be odd. If `kernel_size` is a scalar, + then this scalar is used as the size in each dimension. + Default is a kernel of size (3, 3). + + Returns + ------- + out : ndarray + An array the same size as input containing the median filtered + result. + + See Also + -------- + scipy.ndimage.median_filter + + Notes + ----- + This is faster than `medfilt` when the input dtype is ``uint8``, + ``float32``, or ``float64``; for other types, this falls back to + `medfilt`. In some situations, `scipy.ndimage.median_filter` may be + faster than this function. + + Examples + -------- + >>> import numpy as np + >>> from scipy import signal + >>> x = np.arange(25).reshape(5, 5) + >>> x + array([[ 0, 1, 2, 3, 4], + [ 5, 6, 7, 8, 9], + [10, 11, 12, 13, 14], + [15, 16, 17, 18, 19], + [20, 21, 22, 23, 24]]) + + # Replaces i,j with the median out of 5*5 window + + >>> signal.medfilt2d(x, kernel_size=5) + array([[ 0, 0, 2, 0, 0], + [ 0, 3, 7, 4, 0], + [ 2, 8, 12, 9, 4], + [ 0, 8, 12, 9, 0], + [ 0, 0, 12, 0, 0]]) + + # Replaces i,j with the median out of default 3*3 window + + >>> signal.medfilt2d(x) + array([[ 0, 1, 2, 3, 0], + [ 1, 6, 7, 8, 4], + [ 6, 11, 12, 13, 9], + [11, 16, 17, 18, 14], + [ 0, 16, 17, 18, 0]]) + + # Replaces i,j with the median out of default 5*3 window + + >>> signal.medfilt2d(x, kernel_size=[5,3]) + array([[ 0, 1, 2, 3, 0], + [ 0, 6, 7, 8, 3], + [ 5, 11, 12, 13, 8], + [ 5, 11, 12, 13, 8], + [ 0, 11, 12, 13, 0]]) + + # Replaces i,j with the median out of default 3*5 window + + >>> signal.medfilt2d(x, kernel_size=[3,5]) + array([[ 0, 0, 2, 1, 0], + [ 1, 5, 7, 6, 3], + [ 6, 10, 12, 11, 8], + [11, 15, 17, 16, 13], + [ 0, 15, 17, 16, 0]]) + + # As seen in the examples, + # kernel numbers must be odd and not exceed original array dim + + """ + image = np.asarray(input) + + # checking dtype.type, rather than just dtype, is necessary for + # excluding np.longdouble with MS Visual C. + if image.dtype.type not in (np.ubyte, np.float32, np.float64): + return medfilt(image, kernel_size) + + if kernel_size is None: + kernel_size = [3] * 2 + kernel_size = np.asarray(kernel_size) + if kernel_size.shape == (): + kernel_size = np.repeat(kernel_size.item(), 2) + + for size in kernel_size: + if (size % 2) != 1: + raise ValueError("Each element of kernel_size should be odd.") + + return _sigtools._medfilt2d(image, kernel_size) + + +def lfilter(b, a, x, axis=-1, zi=None): + """ + Filter data along one-dimension with an IIR or FIR filter. + + Filter a data sequence, `x`, using a digital filter. This works for many + fundamental data types (including Object type). The filter is a direct + form II transposed implementation of the standard difference equation + (see Notes). + + The function `sosfilt` (and filter design using ``output='sos'``) should be + preferred over `lfilter` for most filtering tasks, as second-order sections + have fewer numerical problems. + + Parameters + ---------- + b : array_like + The numerator coefficient vector in a 1-D sequence. + a : array_like + The denominator coefficient vector in a 1-D sequence. If ``a[0]`` + is not 1, then both `a` and `b` are normalized by ``a[0]``. + x : array_like + An N-dimensional input array. + axis : int, optional + The axis of the input data array along which to apply the + linear filter. The filter is applied to each subarray along + this axis. Default is -1. + zi : array_like, optional + Initial conditions for the filter delays. It is a vector + (or array of vectors for an N-dimensional input) of length + ``max(len(a), len(b)) - 1``. If `zi` is None or is not given then + initial rest is assumed. See `lfiltic` for more information. + + Returns + ------- + y : array + The output of the digital filter. + zf : array, optional + If `zi` is None, this is not returned, otherwise, `zf` holds the + final filter delay values. + + See Also + -------- + lfiltic : Construct initial conditions for `lfilter`. + lfilter_zi : Compute initial state (steady state of step response) for + `lfilter`. + filtfilt : A forward-backward filter, to obtain a filter with zero phase. + savgol_filter : A Savitzky-Golay filter. + sosfilt: Filter data using cascaded second-order sections. + sosfiltfilt: A forward-backward filter using second-order sections. + + Notes + ----- + The filter function is implemented as a direct II transposed structure. + This means that the filter implements:: + + a[0]*y[n] = b[0]*x[n] + b[1]*x[n-1] + ... + b[M]*x[n-M] + - a[1]*y[n-1] - ... - a[N]*y[n-N] + + where `M` is the degree of the numerator, `N` is the degree of the + denominator, and `n` is the sample number. It is implemented using + the following difference equations (assuming M = N):: + + a[0]*y[n] = b[0] * x[n] + d[0][n-1] + d[0][n] = b[1] * x[n] - a[1] * y[n] + d[1][n-1] + d[1][n] = b[2] * x[n] - a[2] * y[n] + d[2][n-1] + ... + d[N-2][n] = b[N-1]*x[n] - a[N-1]*y[n] + d[N-1][n-1] + d[N-1][n] = b[N] * x[n] - a[N] * y[n] + + where `d` are the state variables. + + The rational transfer function describing this filter in the + z-transform domain is:: + + -1 -M + b[0] + b[1]z + ... + b[M] z + Y(z) = -------------------------------- X(z) + -1 -N + a[0] + a[1]z + ... + a[N] z + + Examples + -------- + Generate a noisy signal to be filtered: + + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> rng = np.random.default_rng() + >>> t = np.linspace(-1, 1, 201) + >>> x = (np.sin(2*np.pi*0.75*t*(1-t) + 2.1) + + ... 0.1*np.sin(2*np.pi*1.25*t + 1) + + ... 0.18*np.cos(2*np.pi*3.85*t)) + >>> xn = x + rng.standard_normal(len(t)) * 0.08 + + Create an order 3 lowpass butterworth filter: + + >>> b, a = signal.butter(3, 0.05) + + Apply the filter to xn. Use lfilter_zi to choose the initial condition of + the filter: + + >>> zi = signal.lfilter_zi(b, a) + >>> z, _ = signal.lfilter(b, a, xn, zi=zi*xn[0]) + + Apply the filter again, to have a result filtered at an order the same as + filtfilt: + + >>> z2, _ = signal.lfilter(b, a, z, zi=zi*z[0]) + + Use filtfilt to apply the filter: + + >>> y = signal.filtfilt(b, a, xn) + + Plot the original signal and the various filtered versions: + + >>> plt.figure + >>> plt.plot(t, xn, 'b', alpha=0.75) + >>> plt.plot(t, z, 'r--', t, z2, 'r', t, y, 'k') + >>> plt.legend(('noisy signal', 'lfilter, once', 'lfilter, twice', + ... 'filtfilt'), loc='best') + >>> plt.grid(True) + >>> plt.show() + + """ + b = np.atleast_1d(b) + a = np.atleast_1d(a) + + _reject_objects(x, 'lfilter') + _reject_objects(a, 'lfilter') + _reject_objects(b, 'lfilter') + + if len(a) == 1: + # This path only supports types fdgFDGO to mirror _linear_filter below. + # Any of b, a, x, or zi can set the dtype, but there is no default + # casting of other types; instead a NotImplementedError is raised. + b = np.asarray(b) + a = np.asarray(a) + if b.ndim != 1 and a.ndim != 1: + raise ValueError('object of too small depth for desired array') + x = _validate_x(x) + inputs = [b, a, x] + if zi is not None: + # _linear_filter does not broadcast zi, but does do expansion of + # singleton dims. + zi = np.asarray(zi) + if zi.ndim != x.ndim: + raise ValueError('object of too small depth for desired array') + expected_shape = list(x.shape) + expected_shape[axis] = b.shape[0] - 1 + expected_shape = tuple(expected_shape) + # check the trivial case where zi is the right shape first + if zi.shape != expected_shape: + strides = zi.ndim * [None] + if axis < 0: + axis += zi.ndim + for k in range(zi.ndim): + if k == axis and zi.shape[k] == expected_shape[k]: + strides[k] = zi.strides[k] + elif k != axis and zi.shape[k] == expected_shape[k]: + strides[k] = zi.strides[k] + elif k != axis and zi.shape[k] == 1: + strides[k] = 0 + else: + raise ValueError('Unexpected shape for zi: expected ' + f'{expected_shape}, found {zi.shape}.') + zi = np.lib.stride_tricks.as_strided(zi, expected_shape, + strides) + inputs.append(zi) + dtype = np.result_type(*inputs) + + if dtype.char not in 'fdgFDGO': + raise NotImplementedError(f"input type '{dtype}' not supported") + + b = np.array(b, dtype=dtype) + a = np.asarray(a, dtype=dtype) + b /= a[0] + x = np.asarray(x, dtype=dtype) + + out_full = np.apply_along_axis(lambda y: np.convolve(b, y), axis, x) + ind = out_full.ndim * [slice(None)] + if zi is not None: + ind[axis] = slice(zi.shape[axis]) + out_full[tuple(ind)] += zi + + ind[axis] = slice(out_full.shape[axis] - len(b) + 1) + out = out_full[tuple(ind)] + + if zi is None: + return out + else: + ind[axis] = slice(out_full.shape[axis] - len(b) + 1, None) + zf = out_full[tuple(ind)] + return out, zf + else: + if zi is None: + return _sigtools._linear_filter(b, a, x, axis) + else: + return _sigtools._linear_filter(b, a, x, axis, zi) + + +def lfiltic(b, a, y, x=None): + """ + Construct initial conditions for lfilter given input and output vectors. + + Given a linear filter (b, a) and initial conditions on the output `y` + and the input `x`, return the initial conditions on the state vector zi + which is used by `lfilter` to generate the output given the input. + + Parameters + ---------- + b : array_like + Linear filter term. + a : array_like + Linear filter term. + y : array_like + Initial conditions. + + If ``N = len(a) - 1``, then ``y = {y[-1], y[-2], ..., y[-N]}``. + + If `y` is too short, it is padded with zeros. + x : array_like, optional + Initial conditions. + + If ``M = len(b) - 1``, then ``x = {x[-1], x[-2], ..., x[-M]}``. + + If `x` is not given, its initial conditions are assumed zero. + + If `x` is too short, it is padded with zeros. + + Returns + ------- + zi : ndarray + The state vector ``zi = {z_0[-1], z_1[-1], ..., z_K-1[-1]}``, + where ``K = max(M, N)``. + + See Also + -------- + lfilter, lfilter_zi + + """ + N = np.size(a) - 1 + M = np.size(b) - 1 + K = max(M, N) + y = np.asarray(y) + + if x is None: + result_type = np.result_type(np.asarray(b), np.asarray(a), y) + if result_type.kind in 'bui': + result_type = np.float64 + x = np.zeros(M, dtype=result_type) + else: + x = np.asarray(x) + + result_type = np.result_type(np.asarray(b), np.asarray(a), y, x) + if result_type.kind in 'bui': + result_type = np.float64 + x = x.astype(result_type) + + L = np.size(x) + if L < M: + x = np.r_[x, np.zeros(M - L)] + + y = y.astype(result_type) + zi = np.zeros(K, result_type) + + L = np.size(y) + if L < N: + y = np.r_[y, np.zeros(N - L)] + + for m in range(M): + zi[m] = np.sum(b[m + 1:] * x[:M - m], axis=0) + + for m in range(N): + zi[m] -= np.sum(a[m + 1:] * y[:N - m], axis=0) + + return zi + + +def deconvolve(signal, divisor): + """Deconvolves ``divisor`` out of ``signal`` using inverse filtering. + + Returns the quotient and remainder such that + ``signal = convolve(divisor, quotient) + remainder`` + + Parameters + ---------- + signal : (N,) array_like + Signal data, typically a recorded signal + divisor : (N,) array_like + Divisor data, typically an impulse response or filter that was + applied to the original signal + + Returns + ------- + quotient : ndarray + Quotient, typically the recovered original signal + remainder : ndarray + Remainder + + See Also + -------- + numpy.polydiv : performs polynomial division (same operation, but + also accepts poly1d objects) + + Examples + -------- + Deconvolve a signal that's been filtered: + + >>> from scipy import signal + >>> original = [0, 1, 0, 0, 1, 1, 0, 0] + >>> impulse_response = [2, 1] + >>> recorded = signal.convolve(impulse_response, original) + >>> recorded + array([0, 2, 1, 0, 2, 3, 1, 0, 0]) + >>> recovered, remainder = signal.deconvolve(recorded, impulse_response) + >>> recovered + array([ 0., 1., 0., 0., 1., 1., 0., 0.]) + + """ + num = np.atleast_1d(signal) + den = np.atleast_1d(divisor) + if num.ndim > 1: + raise ValueError("signal must be 1-D.") + if den.ndim > 1: + raise ValueError("divisor must be 1-D.") + N = len(num) + D = len(den) + if D > N: + quot = [] + rem = num + else: + input = np.zeros(N - D + 1, float) + input[0] = 1 + quot = lfilter(num, den, input) + rem = num - convolve(den, quot, mode='full') + return quot, rem + + +def hilbert(x, N=None, axis=-1): + r"""FFT-based computation of the analytic signal. + + The analytic signal is calculated by filtering out the negative frequencies and + doubling the amplitudes of the positive frequencies in the FFT domain. + The imaginary part of the result is the hilbert transform of the real-valued input + signal. + + The transformation is done along the last axis by default. + + Parameters + ---------- + x : array_like + Signal data. Must be real. + N : int, optional + Number of Fourier components. Default: ``x.shape[axis]`` + axis : int, optional + Axis along which to do the transformation. Default: -1. + + Returns + ------- + xa : ndarray + Analytic signal of `x`, of each 1-D array along `axis` + + Notes + ----- + The analytic signal ``x_a(t)`` of a real-valued signal ``x(t)`` + can be expressed as [1]_ + + .. math:: x_a = F^{-1}(F(x) 2U) = x + i y\ , + + where `F` is the Fourier transform, `U` the unit step function, + and `y` the Hilbert transform of `x`. [2]_ + + In other words, the negative half of the frequency spectrum is zeroed + out, turning the real-valued signal into a complex-valued signal. The Hilbert + transformed signal can be obtained from ``np.imag(hilbert(x))``, and the + original signal from ``np.real(hilbert(x))``. + + References + ---------- + .. [1] Wikipedia, "Analytic signal". + https://en.wikipedia.org/wiki/Analytic_signal + .. [2] Wikipedia, "Hilbert Transform". + https://en.wikipedia.org/wiki/Hilbert_transform + .. [3] Leon Cohen, "Time-Frequency Analysis", 1995. Chapter 2. + .. [4] Alan V. Oppenheim, Ronald W. Schafer. Discrete-Time Signal + Processing, Third Edition, 2009. Chapter 12. + ISBN 13: 978-1292-02572-8 + + See Also + -------- + envelope: Compute envelope of a real- or complex-valued signal. + + Examples + -------- + In this example we use the Hilbert transform to determine the amplitude + envelope and instantaneous frequency of an amplitude-modulated signal. + + Let's create a chirp of which the frequency increases from 20 Hz to 100 Hz and + apply an amplitude modulation: + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.signal import hilbert, chirp + ... + >>> duration, fs = 1, 400 # 1 s signal with sampling frequency of 400 Hz + >>> t = np.arange(int(fs*duration)) / fs # timestamps of samples + >>> signal = chirp(t, 20.0, t[-1], 100.0) + >>> signal *= (1.0 + 0.5 * np.sin(2.0*np.pi*3.0*t) ) + + The amplitude envelope is given by the magnitude of the analytic signal. The + instantaneous frequency can be obtained by differentiating the + instantaneous phase in respect to time. The instantaneous phase corresponds + to the phase angle of the analytic signal. + + >>> analytic_signal = hilbert(signal) + >>> amplitude_envelope = np.abs(analytic_signal) + >>> instantaneous_phase = np.unwrap(np.angle(analytic_signal)) + >>> instantaneous_frequency = np.diff(instantaneous_phase) / (2.0*np.pi) * fs + ... + >>> fig, (ax0, ax1) = plt.subplots(nrows=2, sharex='all', tight_layout=True) + >>> ax0.set_title("Amplitude-modulated Chirp Signal") + >>> ax0.set_ylabel("Amplitude") + >>> ax0.plot(t, signal, label='Signal') + >>> ax0.plot(t, amplitude_envelope, label='Envelope') + >>> ax0.legend() + >>> ax1.set(xlabel="Time in seconds", ylabel="Phase in rad", ylim=(0, 120)) + >>> ax1.plot(t[1:], instantaneous_frequency, 'C2-', label='Instantaneous Phase') + >>> ax1.legend() + >>> plt.show() + + """ + x = np.asarray(x) + if np.iscomplexobj(x): + raise ValueError("x must be real.") + if N is None: + N = x.shape[axis] + if N <= 0: + raise ValueError("N must be positive.") + + Xf = sp_fft.fft(x, N, axis=axis) + h = np.zeros(N, dtype=Xf.dtype) + if N % 2 == 0: + h[0] = h[N // 2] = 1 + h[1:N // 2] = 2 + else: + h[0] = 1 + h[1:(N + 1) // 2] = 2 + + if x.ndim > 1: + ind = [np.newaxis] * x.ndim + ind[axis] = slice(None) + h = h[tuple(ind)] + x = sp_fft.ifft(Xf * h, axis=axis) + return x + + +def hilbert2(x, N=None): + """ + Compute the '2-D' analytic signal of `x` + + Parameters + ---------- + x : array_like + 2-D signal data. + N : int or tuple of two ints, optional + Number of Fourier components. Default is ``x.shape`` + + Returns + ------- + xa : ndarray + Analytic signal of `x` taken along axes (0,1). + + References + ---------- + .. [1] Wikipedia, "Analytic signal", + https://en.wikipedia.org/wiki/Analytic_signal + + """ + x = np.atleast_2d(x) + if x.ndim > 2: + raise ValueError("x must be 2-D.") + if np.iscomplexobj(x): + raise ValueError("x must be real.") + if N is None: + N = x.shape + elif isinstance(N, int): + if N <= 0: + raise ValueError("N must be positive.") + N = (N, N) + elif len(N) != 2 or np.any(np.asarray(N) <= 0): + raise ValueError("When given as a tuple, N must hold exactly " + "two positive integers") + + Xf = sp_fft.fft2(x, N, axes=(0, 1)) + h1 = np.zeros(N[0], dtype=Xf.dtype) + h2 = np.zeros(N[1], dtype=Xf.dtype) + for h in (h1, h2): + N1 = h.shape[0] + if N1 % 2 == 0: + h[0] = h[N1 // 2] = 1 + h[1:N1 // 2] = 2 + else: + h[0] = 1 + h[1:(N1 + 1) // 2] = 2 + + h = h1[:, np.newaxis] * h2[np.newaxis, :] + k = x.ndim + while k > 2: + h = h[:, np.newaxis] + k -= 1 + x = sp_fft.ifft2(Xf * h, axes=(0, 1)) + return x + + +def envelope(z: np.ndarray, bp_in: tuple[int | None, int | None] = (1, None), *, + n_out: int | None = None, squared: bool = False, + residual: Literal['lowpass', 'all', None] = 'lowpass', + axis: int = -1) -> np.ndarray: + r"""Compute the envelope of a real- or complex-valued signal. + + Parameters + ---------- + z : ndarray + Real- or complex-valued input signal, which is assumed to be made up of ``n`` + samples and having sampling interval ``T``. `z` may also be a multidimensional + array with the time axis being defined by `axis`. + bp_in : tuple[int | None, int | None], optional + 2-tuple defining the frequency band ``bp_in[0]:bp_in[1]`` of the input filter. + The corner frequencies are specified as integer multiples of ``1/(n*T)`` with + ``-n//2 <= bp_in[0] < bp_in[1] <= (n+1)//2`` being the allowed frequency range. + ``None`` entries are replaced with ``-n//2`` or ``(n+1)//2`` respectively. The + default of ``(1, None)`` removes the mean value as well as the negative + frequency components. + n_out : int | None, optional + If not ``None`` the output will be resampled to `n_out` samples. The default + of ``None`` sets the output to the same length as the input `z`. + squared : bool, optional + If set, the square of the envelope is returned. The bandwidth of the squared + envelope is often smaller than the non-squared envelope bandwidth due to the + nonlinear nature of the utilized absolute value function. I.e., the embedded + square root function typically produces addiational harmonics. + The default is ``False``. + residual : Literal['lowpass', 'all', None], optional + This option determines what kind of residual, i.e., the signal part which the + input bandpass filter removes, is returned. ``'all'`` returns everything except + the contents of the frequency band ``bp_in[0]:bp_in[1]``, ``'lowpass'`` + returns the contents of the frequency band ``< bp_in[0]``. If ``None`` then + only the envelope is returned. Default: ``'lowpass'``. + axis : int, optional + Axis of `z` over which to compute the envelope. Default is last the axis. + + Returns + ------- + ndarray + If parameter `residual` is ``None`` then an array ``z_env`` with the same shape + as the input `z` is returned, containing its envelope. Otherwise, an array with + shape ``(2, *z.shape)``, containing the arrays ``z_env`` and ``z_res``, stacked + along the first axis, is returned. + It allows unpacking, i.e., ``z_env, z_res = envelope(z, residual='all')``. + The residual ``z_res`` contains the signal part which the input bandpass filter + removed, depending on the parameter `residual`. Note that for real-valued + signals, a real-valued residual is returned. Hence, the negative frequency + components of `bp_in` are ignored. + + Notes + ----- + Any complex-valued signal :math:`z(t)` can be described by a real-valued + instantaneous amplitude :math:`a(t)` and a real-valued instantaneous phase + :math:`\phi(t)`, i.e., :math:`z(t) = a(t) \exp\!\big(j \phi(t)\big)`. The + envelope is defined as the absolute value of the amplitude :math:`|a(t)| = |z(t)|`, + which is at the same time the absolute value of the signal. Hence, :math:`|a(t)|` + "envelopes" the class of all signals with amplitude :math:`a(t)` and arbitrary + phase :math:`\phi(t)`. + For real-valued signals, :math:`x(t) = a(t) \cos\!\big(\phi(t)\big)` is the + analogous formulation. Hence, :math:`|a(t)|` can be determined by converting + :math:`x(t)` into an analytic signal :math:`z_a(t)` by means of a Hilbert + transform, i.e., + :math:`z_a(t) = a(t) \cos\!\big(\phi(t)\big) + j a(t) \sin\!\big(\phi(t) \big)`, + which produces a complex-valued signal with the same envelope :math:`|a(t)|`. + + The implementation is based on computing the FFT of the input signal and then + performing the necessary operations in Fourier space. Hence, the typical FFT + caveats need to be taken into account: + + * The signal is assumed to be periodic. Discontinuities between signal start and + end can lead to unwanted results due to Gibbs phenomenon. + * The FFT is slow if the signal length is prime or very long. Also, the memory + demands are typically higher than a comparable FIR/IIR filter based + implementation. + * The frequency spacing ``1 / (n*T)`` for corner frequencies of the bandpass filter + corresponds to the frequencies produced by ``scipy.fft.fftfreq(len(z), T)``. + + If the envelope of a complex-valued signal `z` with no bandpass filtering is + desired, i.e., ``bp_in=(None, None)``, then the envelope corresponds to the + absolute value. Hence, it is more efficient to use ``np.abs(z)`` instead of this + function. + + Although computing the envelope based on the analytic signal [1]_ is the natural + method for real-valued signals, other methods are also frequently used. The most + popular alternative is probably the so-called "square-law" envelope detector and + its relatives [2]_. They do not always compute the correct result for all kinds of + signals, but are usually correct and typically computationally more efficient for + most kinds of narrowband signals. The definition for an envelope presented here is + common where instantaneous amplitude and phase are of interest (e.g., as described + in [3]_). There exist also other concepts, which rely on the general mathematical + idea of an envelope [4]_: A pragmatic approach is to determine all upper and lower + signal peaks and use a spline interpolation to determine the curves [5]_. + + + References + ---------- + .. [1] "Analytic Signal", Wikipedia, + https://en.wikipedia.org/wiki/Analytic_signal + .. [2] Lyons, Richard, "Digital envelope detection: The good, the bad, and the + ugly", IEEE Signal Processing Magazine 34.4 (2017): 183-187. + `PDF `__ + .. [3] T.G. Kincaid, "The complex representation of signals.", + TIS R67# MH5, General Electric Co. (1966). + `PDF `__ + .. [4] "Envelope (mathematics)", Wikipedia, + https://en.wikipedia.org/wiki/Envelope_(mathematics) + .. [5] Yang, Yanli. "A signal theoretic approach for envelope analysis of + real-valued signals." IEEE Access 5 (2017): 5623-5630. + `PDF `__ + + + See Also + -------- + hilbert: Compute analytic signal by means of Hilbert transform. + + + Examples + -------- + The following plot illustrates the envelope of a signal with variable frequency and + a low-frequency drift. To separate the drift from the envelope, a 4 Hz highpass + filter is used. The low-pass residuum of the input bandpass filter is utilized to + determine an asymmetric upper and lower bound to enclose the signal. Due to the + smoothness of the resulting envelope, it is down-sampled from 500 to 40 samples. + Note that the instantaneous amplitude ``a_x`` and the computed envelope ``x_env`` + are not perfectly identical. This is due to the signal not being perfectly periodic + as well as the existence of some spectral overlapping of ``x_carrier`` and + ``x_drift``. Hence, they cannot be completely separated by a bandpass filter. + + >>> import matplotlib.pyplot as plt + >>> import numpy as np + >>> from scipy.signal.windows import gaussian + >>> from scipy.signal import envelope + ... + >>> n, n_out = 500, 40 # number of signal samples and envelope samples + >>> T = 2 / n # sampling interval for 2 s duration + >>> t = np.arange(n) * T # time stamps + >>> a_x = gaussian(len(t), 0.4/T) # instantaneous amplitude + >>> phi_x = 30*np.pi*t + 35*np.cos(2*np.pi*0.25*t) # instantaneous phase + >>> x_carrier = a_x * np.cos(phi_x) + >>> x_drift = 0.3 * gaussian(len(t), 0.4/T) # drift + >>> x = x_carrier + x_drift + ... + >>> bp_in = (int(4 * (n*T)), None) # 4 Hz highpass input filter + >>> x_env, x_res = envelope(x, bp_in, n_out=n_out) + >>> t_out = np.arange(n_out) * (n / n_out) * T + ... + >>> fg0, ax0 = plt.subplots(1, 1, tight_layout=True) + >>> ax0.set_title(r"$4\,$Hz Highpass Envelope of Drifting Signal") + >>> ax0.set(xlabel="Time in seconds", xlim=(0, n*T), ylabel="Amplitude") + >>> ax0.plot(t, x, 'C0-', alpha=0.5, label="Signal") + >>> ax0.plot(t, x_drift, 'C2--', alpha=0.25, label="Drift") + >>> ax0.plot(t_out, x_res+x_env, 'C1.-', alpha=0.5, label="Envelope") + >>> ax0.plot(t_out, x_res-x_env, 'C1.-', alpha=0.5, label=None) + >>> ax0.grid(True) + >>> ax0.legend() + >>> plt.show() + + The second example provides a geometric envelope interpretation of complex-valued + signals: The following two plots show the complex-valued signal as a blue + 3d-trajectory and the envelope as an orange round tube with varying diameter, i.e., + as :math:`|a(t)| \exp(j\rho(t))`, with :math:`\rho(t)\in[-\pi,\pi]`. Also, the + projection into the 2d real and imaginary coordinate planes of trajectory and tube + is depicted. Every point of the complex-valued signal touches the tube's surface. + + The left plot shows an analytic signal, i.e, the phase difference between + imaginary and real part is always 90 degrees, resulting in a spiraling trajectory. + It can be seen that in this case the real part has also the expected envelope, + i.e., representing the absolute value of the instantaneous amplitude. + + The right plot shows the real part of that analytic signal being interpreted + as a complex-vauled signal, i.e., having zero imaginary part. There the resulting + envelope is not as smooth as in the analytic case and the instantaneous amplitude + in the real plane is not recovered. If ``z_re`` had been passed as a real-valued + signal, i.e., as ``z_re = z.real`` instead of ``z_re = z.real + 0j``, the result + would have been identical to the left plot. The reason for this is that real-valued + signals are interpreted as being the real part of a complex-valued analytic signal. + + >>> import matplotlib.pyplot as plt + >>> import numpy as np + >>> from scipy.signal.windows import gaussian + >>> from scipy.signal import envelope + ... + >>> n, T = 1000, 1/1000 # number of samples and sampling interval + >>> t = np.arange(n) * T # time stamps for 1 s duration + >>> f_c = 3 # Carrier frequency for signal + >>> z = gaussian(len(t), 0.3/T) * np.exp(2j*np.pi*f_c*t) # analytic signal + >>> z_re = z.real + 0j # complex signal with zero imaginary part + ... + >>> e_a, e_r = (envelope(z_, (None, None), residual=None) for z_ in (z, z_re)) + ... + >>> # Generate grids to visualize envelopes as 2d and 3d surfaces: + >>> E2d_t, E2_amp = np.meshgrid(t, [-1, 1]) + >>> E2d_1 = np.ones_like(E2_amp) + >>> E3d_t, E3d_phi = np.meshgrid(t, np.linspace(-np.pi, np.pi, 300)) + >>> ma = 1.8 # maximum axis values in real and imaginary direction + ... + >>> fg0 = plt.figure(figsize=(6.2, 4.)) + >>> ax00 = fg0.add_subplot(1, 2, 1, projection='3d') + >>> ax01 = fg0.add_subplot(1, 2, 2, projection='3d', sharex=ax00, + ... sharey=ax00, sharez=ax00) + >>> ax00.set_title("Analytic Signal") + >>> ax00.set(xlim=(0, 1), ylim=(-ma, ma), zlim=(-ma, ma)) + >>> ax01.set_title("Real-valued Signal") + >>> for z_, e_, ax_ in zip((z, z.real), (e_a, e_r), (ax00, ax01)): + ... ax_.set(xlabel="Time $t$", ylabel="Real Amp. $x(t)$", + ... zlabel="Imag. Amp. $y(t)$") + ... ax_.plot(t, z_.real, 'C0-', zs=-ma, zdir='z', alpha=0.5, label="Real") + ... ax_.plot_surface(E2d_t, e_*E2_amp, -ma*E2d_1, color='C1', alpha=0.25) + ... ax_.plot(t, z_.imag, 'C0-', zs=+ma, zdir='y', alpha=0.5, label="Imag.") + ... ax_.plot_surface(E2d_t, ma*E2d_1, e_*E2_amp, color='C1', alpha=0.25) + ... ax_.plot(t, z_.real, z_.imag, 'C0-', label="Signal") + ... ax_.plot_surface(E3d_t, e_*np.cos(E3d_phi), e_*np.sin(E3d_phi), + ... color='C1', alpha=0.5, shade=True, label="Envelope") + ... ax_.view_init(elev=22.7, azim=-114.3) + >>> fg0.subplots_adjust(left=0.08, right=0.97, wspace=0.15) + >>> plt.show() + """ + if not (-z.ndim <= axis < z.ndim): + raise ValueError(f"Invalid parameter {axis=} for {z.shape=}!") + if not (z.shape[axis] > 0): + raise ValueError(f"z.shape[axis] not > 0 for {z.shape=}, {axis=}!") + if len(bp_in) != 2 or not all((isinstance(b_, int) or b_ is None) for b_ in bp_in): + raise ValueError(f"{bp_in=} isn't a 2-tuple of type (int | None, int | None)!") + if not ((isinstance(n_out, int) and 0 < n_out) or n_out is None): + raise ValueError(f"{n_out=} is not a positive integer or None!") + if residual not in ('lowpass', 'all', None): + raise ValueError(f"{residual=} not in ['lowpass', 'all', None]!") + + n = z.shape[axis] # number of time samples of input + n_out = n if n_out is None else n_out + fak = n_out / n # scaling factor for resampling + + bp = slice(bp_in[0] if bp_in[0] is not None else -(n//2), + bp_in[1] if bp_in[1] is not None else (n+1)//2) + if not (-n//2 <= bp.start < bp.stop <= (n+1)//2): + raise ValueError("`-n//2 <= bp_in[0] < bp_in[1] <= (n+1)//2` does not hold " + + f"for n={z.shape[axis]=} and {bp_in=}!") + + # moving active axis to end allows to use `...` for indexing: + z = np.moveaxis(z, axis, -1) + + if np.iscomplexobj(z): + Z = sp_fft.fft(z) + else: # avoid calculating negative frequency bins for real signals: + Z = np.zeros_like(z, dtype=sp_fft.rfft(z.flat[:1]).dtype) + Z[..., :n//2 + 1] = sp_fft.rfft(z) + if bp.start > 0: # make signal analytic within bp_in band: + Z[..., bp] *= 2 + elif bp.stop > 0: + Z[..., 1:bp.stop] *= 2 + if not (bp.start <= 0 < bp.stop): # envelope is invariant to freq. shifts. + z_bb = sp_fft.ifft(Z[..., bp], n=n_out) * fak # baseband signal + else: + bp_shift = slice(bp.start + n//2, bp.stop + n//2) + z_bb = sp_fft.ifft(sp_fft.fftshift(Z, axes=-1)[..., bp_shift], n=n_out) * fak + + z_env = np.abs(z_bb) if not squared else z_bb.real ** 2 + z_bb.imag ** 2 + z_env = np.moveaxis(z_env, -1, axis) + + # Calculate the residual from the input bandpass filter: + if residual is None: + return z_env + if not (bp.start <= 0 < bp.stop): + Z[..., bp] = 0 + else: + Z[..., :bp.stop], Z[..., bp.start:] = 0, 0 + if residual == 'lowpass': + if bp.stop > 0: + Z[..., bp.stop:(n+1) // 2] = 0 + else: + Z[..., bp.start:], Z[..., 0:(n + 1) // 2] = 0, 0 + + z_res = fak * (sp_fft.ifft(Z, n=n_out) if np.iscomplexobj(z) else + sp_fft.irfft(Z, n=n_out)) + return np.stack((z_env, np.moveaxis(z_res, -1, axis)), axis=0) + +def _cmplx_sort(p): + """Sort roots based on magnitude. + + Parameters + ---------- + p : array_like + The roots to sort, as a 1-D array. + + Returns + ------- + p_sorted : ndarray + Sorted roots. + indx : ndarray + Array of indices needed to sort the input `p`. + + Examples + -------- + >>> from scipy import signal + >>> vals = [1, 4, 1+1.j, 3] + >>> p_sorted, indx = signal.cmplx_sort(vals) + >>> p_sorted + array([1.+0.j, 1.+1.j, 3.+0.j, 4.+0.j]) + >>> indx + array([0, 2, 3, 1]) + """ + p = np.asarray(p) + indx = np.argsort(abs(p)) + return np.take(p, indx, 0), indx + + +def unique_roots(p, tol=1e-3, rtype='min'): + """Determine unique roots and their multiplicities from a list of roots. + + Parameters + ---------- + p : array_like + The list of roots. + tol : float, optional + The tolerance for two roots to be considered equal in terms of + the distance between them. Default is 1e-3. Refer to Notes about + the details on roots grouping. + rtype : {'max', 'maximum', 'min', 'minimum', 'avg', 'mean'}, optional + How to determine the returned root if multiple roots are within + `tol` of each other. + + - 'max', 'maximum': pick the maximum of those roots + - 'min', 'minimum': pick the minimum of those roots + - 'avg', 'mean': take the average of those roots + + When finding minimum or maximum among complex roots they are compared + first by the real part and then by the imaginary part. + + Returns + ------- + unique : ndarray + The list of unique roots. + multiplicity : ndarray + The multiplicity of each root. + + Notes + ----- + If we have 3 roots ``a``, ``b`` and ``c``, such that ``a`` is close to + ``b`` and ``b`` is close to ``c`` (distance is less than `tol`), then it + doesn't necessarily mean that ``a`` is close to ``c``. It means that roots + grouping is not unique. In this function we use "greedy" grouping going + through the roots in the order they are given in the input `p`. + + This utility function is not specific to roots but can be used for any + sequence of values for which uniqueness and multiplicity has to be + determined. For a more general routine, see `numpy.unique`. + + Examples + -------- + >>> from scipy import signal + >>> vals = [0, 1.3, 1.31, 2.8, 1.25, 2.2, 10.3] + >>> uniq, mult = signal.unique_roots(vals, tol=2e-2, rtype='avg') + + Check which roots have multiplicity larger than 1: + + >>> uniq[mult > 1] + array([ 1.305]) + """ + if rtype in ['max', 'maximum']: + reduce = np.max + elif rtype in ['min', 'minimum']: + reduce = np.min + elif rtype in ['avg', 'mean']: + reduce = np.mean + else: + raise ValueError("`rtype` must be one of " + "{'max', 'maximum', 'min', 'minimum', 'avg', 'mean'}") + + p = np.asarray(p) + + points = np.empty((len(p), 2)) + points[:, 0] = np.real(p) + points[:, 1] = np.imag(p) + tree = cKDTree(points) + + p_unique = [] + p_multiplicity = [] + used = np.zeros(len(p), dtype=bool) + for i in range(len(p)): + if used[i]: + continue + + group = tree.query_ball_point(points[i], tol) + group = [x for x in group if not used[x]] + + p_unique.append(reduce(p[group])) + p_multiplicity.append(len(group)) + + used[group] = True + + return np.asarray(p_unique), np.asarray(p_multiplicity) + + +def invres(r, p, k, tol=1e-3, rtype='avg'): + """Compute b(s) and a(s) from partial fraction expansion. + + If `M` is the degree of numerator `b` and `N` the degree of denominator + `a`:: + + b(s) b[0] s**(M) + b[1] s**(M-1) + ... + b[M] + H(s) = ------ = ------------------------------------------ + a(s) a[0] s**(N) + a[1] s**(N-1) + ... + a[N] + + then the partial-fraction expansion H(s) is defined as:: + + r[0] r[1] r[-1] + = -------- + -------- + ... + --------- + k(s) + (s-p[0]) (s-p[1]) (s-p[-1]) + + If there are any repeated roots (closer together than `tol`), then H(s) + has terms like:: + + r[i] r[i+1] r[i+n-1] + -------- + ----------- + ... + ----------- + (s-p[i]) (s-p[i])**2 (s-p[i])**n + + This function is used for polynomials in positive powers of s or z, + such as analog filters or digital filters in controls engineering. For + negative powers of z (typical for digital filters in DSP), use `invresz`. + + Parameters + ---------- + r : array_like + Residues corresponding to the poles. For repeated poles, the residues + must be ordered to correspond to ascending by power fractions. + p : array_like + Poles. Equal poles must be adjacent. + k : array_like + Coefficients of the direct polynomial term. + tol : float, optional + The tolerance for two roots to be considered equal in terms of + the distance between them. Default is 1e-3. See `unique_roots` + for further details. + rtype : {'avg', 'min', 'max'}, optional + Method for computing a root to represent a group of identical roots. + Default is 'avg'. See `unique_roots` for further details. + + Returns + ------- + b : ndarray + Numerator polynomial coefficients. + a : ndarray + Denominator polynomial coefficients. + + See Also + -------- + residue, invresz, unique_roots + + """ + r = np.atleast_1d(r) + p = np.atleast_1d(p) + k = np.trim_zeros(np.atleast_1d(k), 'f') + + unique_poles, multiplicity = _group_poles(p, tol, rtype) + factors, denominator = _compute_factors(unique_poles, multiplicity, + include_powers=True) + + if len(k) == 0: + numerator = 0 + else: + numerator = np.polymul(k, denominator) + + for residue, factor in zip(r, factors): + numerator = np.polyadd(numerator, residue * factor) + + return numerator, denominator + + +def _compute_factors(roots, multiplicity, include_powers=False): + """Compute the total polynomial divided by factors for each root.""" + current = np.array([1]) + suffixes = [current] + for pole, mult in zip(roots[-1:0:-1], multiplicity[-1:0:-1]): + monomial = np.array([1, -pole]) + for _ in range(mult): + current = np.polymul(current, monomial) + suffixes.append(current) + suffixes = suffixes[::-1] + + factors = [] + current = np.array([1]) + for pole, mult, suffix in zip(roots, multiplicity, suffixes): + monomial = np.array([1, -pole]) + block = [] + for i in range(mult): + if i == 0 or include_powers: + block.append(np.polymul(current, suffix)) + current = np.polymul(current, monomial) + factors.extend(reversed(block)) + + return factors, current + + +def _compute_residues(poles, multiplicity, numerator): + denominator_factors, _ = _compute_factors(poles, multiplicity) + numerator = numerator.astype(poles.dtype) + + residues = [] + for pole, mult, factor in zip(poles, multiplicity, + denominator_factors): + if mult == 1: + residues.append(np.polyval(numerator, pole) / + np.polyval(factor, pole)) + else: + numer = numerator.copy() + monomial = np.array([1, -pole]) + factor, d = np.polydiv(factor, monomial) + + block = [] + for _ in range(mult): + numer, n = np.polydiv(numer, monomial) + r = n[0] / d[0] + numer = np.polysub(numer, r * factor) + block.append(r) + + residues.extend(reversed(block)) + + return np.asarray(residues) + + +def residue(b, a, tol=1e-3, rtype='avg'): + """Compute partial-fraction expansion of b(s) / a(s). + + If `M` is the degree of numerator `b` and `N` the degree of denominator + `a`:: + + b(s) b[0] s**(M) + b[1] s**(M-1) + ... + b[M] + H(s) = ------ = ------------------------------------------ + a(s) a[0] s**(N) + a[1] s**(N-1) + ... + a[N] + + then the partial-fraction expansion H(s) is defined as:: + + r[0] r[1] r[-1] + = -------- + -------- + ... + --------- + k(s) + (s-p[0]) (s-p[1]) (s-p[-1]) + + If there are any repeated roots (closer together than `tol`), then H(s) + has terms like:: + + r[i] r[i+1] r[i+n-1] + -------- + ----------- + ... + ----------- + (s-p[i]) (s-p[i])**2 (s-p[i])**n + + This function is used for polynomials in positive powers of s or z, + such as analog filters or digital filters in controls engineering. For + negative powers of z (typical for digital filters in DSP), use `residuez`. + + See Notes for details about the algorithm. + + Parameters + ---------- + b : array_like + Numerator polynomial coefficients. + a : array_like + Denominator polynomial coefficients. + tol : float, optional + The tolerance for two roots to be considered equal in terms of + the distance between them. Default is 1e-3. See `unique_roots` + for further details. + rtype : {'avg', 'min', 'max'}, optional + Method for computing a root to represent a group of identical roots. + Default is 'avg'. See `unique_roots` for further details. + + Returns + ------- + r : ndarray + Residues corresponding to the poles. For repeated poles, the residues + are ordered to correspond to ascending by power fractions. + p : ndarray + Poles ordered by magnitude in ascending order. + k : ndarray + Coefficients of the direct polynomial term. + + See Also + -------- + invres, residuez, numpy.poly, unique_roots + + Notes + ----- + The "deflation through subtraction" algorithm is used for + computations --- method 6 in [1]_. + + The form of partial fraction expansion depends on poles multiplicity in + the exact mathematical sense. However there is no way to exactly + determine multiplicity of roots of a polynomial in numerical computing. + Thus you should think of the result of `residue` with given `tol` as + partial fraction expansion computed for the denominator composed of the + computed poles with empirically determined multiplicity. The choice of + `tol` can drastically change the result if there are close poles. + + References + ---------- + .. [1] J. F. Mahoney, B. D. Sivazlian, "Partial fractions expansion: a + review of computational methodology and efficiency", Journal of + Computational and Applied Mathematics, Vol. 9, 1983. + """ + b = np.asarray(b) + a = np.asarray(a) + if (np.issubdtype(b.dtype, np.complexfloating) + or np.issubdtype(a.dtype, np.complexfloating)): + b = b.astype(complex) + a = a.astype(complex) + else: + b = b.astype(float) + a = a.astype(float) + + b = np.trim_zeros(np.atleast_1d(b), 'f') + a = np.trim_zeros(np.atleast_1d(a), 'f') + + if a.size == 0: + raise ValueError("Denominator `a` is zero.") + + poles = np.roots(a) + if b.size == 0: + return np.zeros(poles.shape), _cmplx_sort(poles)[0], np.array([]) + + if len(b) < len(a): + k = np.empty(0) + else: + k, b = np.polydiv(b, a) + + unique_poles, multiplicity = unique_roots(poles, tol=tol, rtype=rtype) + unique_poles, order = _cmplx_sort(unique_poles) + multiplicity = multiplicity[order] + + residues = _compute_residues(unique_poles, multiplicity, b) + + index = 0 + for pole, mult in zip(unique_poles, multiplicity): + poles[index:index + mult] = pole + index += mult + + return residues / a[0], poles, k + + +def residuez(b, a, tol=1e-3, rtype='avg'): + """Compute partial-fraction expansion of b(z) / a(z). + + If `M` is the degree of numerator `b` and `N` the degree of denominator + `a`:: + + b(z) b[0] + b[1] z**(-1) + ... + b[M] z**(-M) + H(z) = ------ = ------------------------------------------ + a(z) a[0] + a[1] z**(-1) + ... + a[N] z**(-N) + + then the partial-fraction expansion H(z) is defined as:: + + r[0] r[-1] + = --------------- + ... + ---------------- + k[0] + k[1]z**(-1) ... + (1-p[0]z**(-1)) (1-p[-1]z**(-1)) + + If there are any repeated roots (closer than `tol`), then the partial + fraction expansion has terms like:: + + r[i] r[i+1] r[i+n-1] + -------------- + ------------------ + ... + ------------------ + (1-p[i]z**(-1)) (1-p[i]z**(-1))**2 (1-p[i]z**(-1))**n + + This function is used for polynomials in negative powers of z, + such as digital filters in DSP. For positive powers, use `residue`. + + See Notes of `residue` for details about the algorithm. + + Parameters + ---------- + b : array_like + Numerator polynomial coefficients. + a : array_like + Denominator polynomial coefficients. + tol : float, optional + The tolerance for two roots to be considered equal in terms of + the distance between them. Default is 1e-3. See `unique_roots` + for further details. + rtype : {'avg', 'min', 'max'}, optional + Method for computing a root to represent a group of identical roots. + Default is 'avg'. See `unique_roots` for further details. + + Returns + ------- + r : ndarray + Residues corresponding to the poles. For repeated poles, the residues + are ordered to correspond to ascending by power fractions. + p : ndarray + Poles ordered by magnitude in ascending order. + k : ndarray + Coefficients of the direct polynomial term. + + See Also + -------- + invresz, residue, unique_roots + """ + b = np.asarray(b) + a = np.asarray(a) + if (np.issubdtype(b.dtype, np.complexfloating) + or np.issubdtype(a.dtype, np.complexfloating)): + b = b.astype(complex) + a = a.astype(complex) + else: + b = b.astype(float) + a = a.astype(float) + + b = np.trim_zeros(np.atleast_1d(b), 'b') + a = np.trim_zeros(np.atleast_1d(a), 'b') + + if a.size == 0: + raise ValueError("Denominator `a` is zero.") + elif a[0] == 0: + raise ValueError("First coefficient of determinant `a` must be " + "non-zero.") + + poles = np.roots(a) + if b.size == 0: + return np.zeros(poles.shape), _cmplx_sort(poles)[0], np.array([]) + + b_rev = b[::-1] + a_rev = a[::-1] + + if len(b_rev) < len(a_rev): + k_rev = np.empty(0) + else: + k_rev, b_rev = np.polydiv(b_rev, a_rev) + + unique_poles, multiplicity = unique_roots(poles, tol=tol, rtype=rtype) + unique_poles, order = _cmplx_sort(unique_poles) + multiplicity = multiplicity[order] + + residues = _compute_residues(1 / unique_poles, multiplicity, b_rev) + + index = 0 + powers = np.empty(len(residues), dtype=int) + for pole, mult in zip(unique_poles, multiplicity): + poles[index:index + mult] = pole + powers[index:index + mult] = 1 + np.arange(mult) + index += mult + + residues *= (-poles) ** powers / a_rev[0] + + return residues, poles, k_rev[::-1] + + +def _group_poles(poles, tol, rtype): + if rtype in ['max', 'maximum']: + reduce = np.max + elif rtype in ['min', 'minimum']: + reduce = np.min + elif rtype in ['avg', 'mean']: + reduce = np.mean + else: + raise ValueError("`rtype` must be one of " + "{'max', 'maximum', 'min', 'minimum', 'avg', 'mean'}") + + unique = [] + multiplicity = [] + + pole = poles[0] + block = [pole] + for i in range(1, len(poles)): + if abs(poles[i] - pole) <= tol: + block.append(pole) + else: + unique.append(reduce(block)) + multiplicity.append(len(block)) + pole = poles[i] + block = [pole] + + unique.append(reduce(block)) + multiplicity.append(len(block)) + + return np.asarray(unique), np.asarray(multiplicity) + + +def invresz(r, p, k, tol=1e-3, rtype='avg'): + """Compute b(z) and a(z) from partial fraction expansion. + + If `M` is the degree of numerator `b` and `N` the degree of denominator + `a`:: + + b(z) b[0] + b[1] z**(-1) + ... + b[M] z**(-M) + H(z) = ------ = ------------------------------------------ + a(z) a[0] + a[1] z**(-1) + ... + a[N] z**(-N) + + then the partial-fraction expansion H(z) is defined as:: + + r[0] r[-1] + = --------------- + ... + ---------------- + k[0] + k[1]z**(-1) ... + (1-p[0]z**(-1)) (1-p[-1]z**(-1)) + + If there are any repeated roots (closer than `tol`), then the partial + fraction expansion has terms like:: + + r[i] r[i+1] r[i+n-1] + -------------- + ------------------ + ... + ------------------ + (1-p[i]z**(-1)) (1-p[i]z**(-1))**2 (1-p[i]z**(-1))**n + + This function is used for polynomials in negative powers of z, + such as digital filters in DSP. For positive powers, use `invres`. + + Parameters + ---------- + r : array_like + Residues corresponding to the poles. For repeated poles, the residues + must be ordered to correspond to ascending by power fractions. + p : array_like + Poles. Equal poles must be adjacent. + k : array_like + Coefficients of the direct polynomial term. + tol : float, optional + The tolerance for two roots to be considered equal in terms of + the distance between them. Default is 1e-3. See `unique_roots` + for further details. + rtype : {'avg', 'min', 'max'}, optional + Method for computing a root to represent a group of identical roots. + Default is 'avg'. See `unique_roots` for further details. + + Returns + ------- + b : ndarray + Numerator polynomial coefficients. + a : ndarray + Denominator polynomial coefficients. + + See Also + -------- + residuez, unique_roots, invres + + """ + r = np.atleast_1d(r) + p = np.atleast_1d(p) + k = np.trim_zeros(np.atleast_1d(k), 'b') + + unique_poles, multiplicity = _group_poles(p, tol, rtype) + factors, denominator = _compute_factors(unique_poles, multiplicity, + include_powers=True) + + if len(k) == 0: + numerator = 0 + else: + numerator = np.polymul(k[::-1], denominator[::-1]) + + for residue, factor in zip(r, factors): + numerator = np.polyadd(numerator, residue * factor[::-1]) + + return numerator[::-1], denominator + + +def resample(x, num, t=None, axis=0, window=None, domain='time'): + """ + Resample `x` to `num` samples using Fourier method along the given axis. + + The resampled signal starts at the same value as `x` but is sampled + with a spacing of ``len(x) / num * (spacing of x)``. Because a + Fourier method is used, the signal is assumed to be periodic. + + Parameters + ---------- + x : array_like + The data to be resampled. + num : int + The number of samples in the resampled signal. + t : array_like, optional + If `t` is given, it is assumed to be the equally spaced sample + positions associated with the signal data in `x`. + axis : int, optional + The axis of `x` that is resampled. Default is 0. + window : array_like, callable, string, float, or tuple, optional + Specifies the window applied to the signal in the Fourier + domain. See below for details. + domain : string, optional + A string indicating the domain of the input `x`: + ``time`` Consider the input `x` as time-domain (Default), + ``freq`` Consider the input `x` as frequency-domain. + + Returns + ------- + resampled_x or (resampled_x, resampled_t) + Either the resampled array, or, if `t` was given, a tuple + containing the resampled array and the corresponding resampled + positions. + + See Also + -------- + decimate : Downsample the signal after applying an FIR or IIR filter. + resample_poly : Resample using polyphase filtering and an FIR filter. + + Notes + ----- + The argument `window` controls a Fourier-domain window that tapers + the Fourier spectrum before zero-padding to alleviate ringing in + the resampled values for sampled signals you didn't intend to be + interpreted as band-limited. + + If `window` is a function, then it is called with a vector of inputs + indicating the frequency bins (i.e. fftfreq(x.shape[axis]) ). + + If `window` is an array of the same length as `x.shape[axis]` it is + assumed to be the window to be applied directly in the Fourier + domain (with dc and low-frequency first). + + For any other type of `window`, the function `scipy.signal.get_window` + is called to generate the window. + + The first sample of the returned vector is the same as the first + sample of the input vector. The spacing between samples is changed + from ``dx`` to ``dx * len(x) / num``. + + If `t` is not None, then it is used solely to calculate the resampled + positions `resampled_t` + + As noted, `resample` uses FFT transformations, which can be very + slow if the number of input or output samples is large and prime; + see :func:`~scipy.fft.fft`. In such cases, it can be faster to first downsample + a signal of length ``n`` with :func:`~scipy.signal.resample_poly` by a factor of + ``n//num`` before using `resample`. Note that this approach changes the + characteristics of the antialiasing filter. + + Examples + -------- + Note that the end of the resampled data rises to meet the first + sample of the next cycle: + + >>> import numpy as np + >>> from scipy import signal + + >>> x = np.linspace(0, 10, 20, endpoint=False) + >>> y = np.cos(-x**2/6.0) + >>> f = signal.resample(y, 100) + >>> xnew = np.linspace(0, 10, 100, endpoint=False) + + >>> import matplotlib.pyplot as plt + >>> plt.plot(x, y, 'go-', xnew, f, '.-', 10, y[0], 'ro') + >>> plt.legend(['data', 'resampled'], loc='best') + >>> plt.show() + + Consider the following signal ``y`` where ``len(y)`` is a large prime number: + + >>> N = 55949 + >>> freq = 100 + >>> x = np.linspace(0, 1, N) + >>> y = np.cos(2 * np.pi * freq * x) + + Due to ``N`` being prime, + + >>> num = 5000 + >>> f = signal.resample(signal.resample_poly(y, 1, N // num), num) + + runs significantly faster than + + >>> f = signal.resample(y, num) + """ + + if domain not in ('time', 'freq'): + raise ValueError("Acceptable domain flags are 'time' or" + f" 'freq', not domain={domain}") + + x = np.asarray(x) + Nx = x.shape[axis] + + # Check if we can use faster real FFT + real_input = np.isrealobj(x) + + if domain == 'time': + # Forward transform + if real_input: + X = sp_fft.rfft(x, axis=axis) + else: # Full complex FFT + X = sp_fft.fft(x, axis=axis) + else: # domain == 'freq' + X = x + + # Apply window to spectrum + if window is not None: + if callable(window): + W = window(sp_fft.fftfreq(Nx)) + elif isinstance(window, np.ndarray): + if window.shape != (Nx,): + raise ValueError('window must have the same length as data') + W = window + else: + W = sp_fft.ifftshift(get_window(window, Nx)) + + newshape_W = [1] * x.ndim + newshape_W[axis] = X.shape[axis] + if real_input: + # Fold the window back on itself to mimic complex behavior + W_real = W.copy() + W_real[1:] += W_real[-1:0:-1] + W_real[1:] *= 0.5 + X *= W_real[:newshape_W[axis]].reshape(newshape_W) + else: + X *= W.reshape(newshape_W) + + # Copy each half of the original spectrum to the output spectrum, either + # truncating high frequencies (downsampling) or zero-padding them + # (upsampling) + + # Placeholder array for output spectrum + newshape = list(x.shape) + if real_input: + newshape[axis] = num // 2 + 1 + else: + newshape[axis] = num + Y = np.zeros(newshape, X.dtype) + + # Copy positive frequency components (and Nyquist, if present) + N = min(num, Nx) + nyq = N // 2 + 1 # Slice index that includes Nyquist if present + sl = [slice(None)] * x.ndim + sl[axis] = slice(0, nyq) + Y[tuple(sl)] = X[tuple(sl)] + if not real_input: + # Copy negative frequency components + if N > 2: # (slice expression doesn't collapse to empty array) + sl[axis] = slice(nyq - N, None) + Y[tuple(sl)] = X[tuple(sl)] + + # Split/join Nyquist component(s) if present + # So far we have set Y[+N/2]=X[+N/2] + if N % 2 == 0: + if num < Nx: # downsampling + if real_input: + sl[axis] = slice(N//2, N//2 + 1) + Y[tuple(sl)] *= 2. + else: + # select the component of Y at frequency +N/2, + # add the component of X at -N/2 + sl[axis] = slice(-N//2, -N//2 + 1) + Y[tuple(sl)] += X[tuple(sl)] + elif Nx < num: # upsampling + # select the component at frequency +N/2 and halve it + sl[axis] = slice(N//2, N//2 + 1) + Y[tuple(sl)] *= 0.5 + if not real_input: + temp = Y[tuple(sl)] + # set the component at -N/2 equal to the component at +N/2 + sl[axis] = slice(num-N//2, num-N//2 + 1) + Y[tuple(sl)] = temp + + # Inverse transform + if real_input: + y = sp_fft.irfft(Y, num, axis=axis) + else: + y = sp_fft.ifft(Y, axis=axis, overwrite_x=True) + + y *= (float(num) / float(Nx)) + + if t is None: + return y + else: + new_t = np.arange(0, num) * (t[1] - t[0]) * Nx / float(num) + t[0] + return y, new_t + + +def resample_poly(x, up, down, axis=0, window=('kaiser', 5.0), + padtype='constant', cval=None): + """ + Resample `x` along the given axis using polyphase filtering. + + The signal `x` is upsampled by the factor `up`, a zero-phase low-pass + FIR filter is applied, and then it is downsampled by the factor `down`. + The resulting sample rate is ``up / down`` times the original sample + rate. By default, values beyond the boundary of the signal are assumed + to be zero during the filtering step. + + Parameters + ---------- + x : array_like + The data to be resampled. + up : int + The upsampling factor. + down : int + The downsampling factor. + axis : int, optional + The axis of `x` that is resampled. Default is 0. + window : string, tuple, or array_like, optional + Desired window to use to design the low-pass filter, or the FIR filter + coefficients to employ. See below for details. + padtype : string, optional + `constant`, `line`, `mean`, `median`, `maximum`, `minimum` or any of + the other signal extension modes supported by `scipy.signal.upfirdn`. + Changes assumptions on values beyond the boundary. If `constant`, + assumed to be `cval` (default zero). If `line` assumed to continue a + linear trend defined by the first and last points. `mean`, `median`, + `maximum` and `minimum` work as in `np.pad` and assume that the values + beyond the boundary are the mean, median, maximum or minimum + respectively of the array along the axis. + + .. versionadded:: 1.4.0 + cval : float, optional + Value to use if `padtype='constant'`. Default is zero. + + .. versionadded:: 1.4.0 + + Returns + ------- + resampled_x : array + The resampled array. + + See Also + -------- + decimate : Downsample the signal after applying an FIR or IIR filter. + resample : Resample up or down using the FFT method. + + Notes + ----- + This polyphase method will likely be faster than the Fourier method + in `scipy.signal.resample` when the number of samples is large and + prime, or when the number of samples is large and `up` and `down` + share a large greatest common denominator. The length of the FIR + filter used will depend on ``max(up, down) // gcd(up, down)``, and + the number of operations during polyphase filtering will depend on + the filter length and `down` (see `scipy.signal.upfirdn` for details). + + The argument `window` specifies the FIR low-pass filter design. + + If `window` is an array_like it is assumed to be the FIR filter + coefficients. Note that the FIR filter is applied after the upsampling + step, so it should be designed to operate on a signal at a sampling + frequency higher than the original by a factor of `up//gcd(up, down)`. + This function's output will be centered with respect to this array, so it + is best to pass a symmetric filter with an odd number of samples if, as + is usually the case, a zero-phase filter is desired. + + For any other type of `window`, the functions `scipy.signal.get_window` + and `scipy.signal.firwin` are called to generate the appropriate filter + coefficients. + + The first sample of the returned vector is the same as the first + sample of the input vector. The spacing between samples is changed + from ``dx`` to ``dx * down / float(up)``. + + Examples + -------- + By default, the end of the resampled data rises to meet the first + sample of the next cycle for the FFT method, and gets closer to zero + for the polyphase method: + + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + + >>> x = np.linspace(0, 10, 20, endpoint=False) + >>> y = np.cos(-x**2/6.0) + >>> f_fft = signal.resample(y, 100) + >>> f_poly = signal.resample_poly(y, 100, 20) + >>> xnew = np.linspace(0, 10, 100, endpoint=False) + + >>> plt.plot(xnew, f_fft, 'b.-', xnew, f_poly, 'r.-') + >>> plt.plot(x, y, 'ko-') + >>> plt.plot(10, y[0], 'bo', 10, 0., 'ro') # boundaries + >>> plt.legend(['resample', 'resamp_poly', 'data'], loc='best') + >>> plt.show() + + This default behaviour can be changed by using the padtype option: + + >>> N = 5 + >>> x = np.linspace(0, 1, N, endpoint=False) + >>> y = 2 + x**2 - 1.7*np.sin(x) + .2*np.cos(11*x) + >>> y2 = 1 + x**3 + 0.1*np.sin(x) + .1*np.cos(11*x) + >>> Y = np.stack([y, y2], axis=-1) + >>> up = 4 + >>> xr = np.linspace(0, 1, N*up, endpoint=False) + + >>> y2 = signal.resample_poly(Y, up, 1, padtype='constant') + >>> y3 = signal.resample_poly(Y, up, 1, padtype='mean') + >>> y4 = signal.resample_poly(Y, up, 1, padtype='line') + + >>> for i in [0,1]: + ... plt.figure() + ... plt.plot(xr, y4[:,i], 'g.', label='line') + ... plt.plot(xr, y3[:,i], 'y.', label='mean') + ... plt.plot(xr, y2[:,i], 'r.', label='constant') + ... plt.plot(x, Y[:,i], 'k-') + ... plt.legend() + >>> plt.show() + + """ + x = np.asarray(x) + if up != int(up): + raise ValueError("up must be an integer") + if down != int(down): + raise ValueError("down must be an integer") + up = int(up) + down = int(down) + if up < 1 or down < 1: + raise ValueError('up and down must be >= 1') + if cval is not None and padtype != 'constant': + raise ValueError('cval has no effect when padtype is ', padtype) + + # Determine our up and down factors + # Use a rational approximation to save computation time on really long + # signals + g_ = math.gcd(up, down) + up //= g_ + down //= g_ + if up == down == 1: + return x.copy() + n_in = x.shape[axis] + n_out = n_in * up + n_out = n_out // down + bool(n_out % down) + + if isinstance(window, (list | np.ndarray)): + window = np.array(window) # use array to force a copy (we modify it) + if window.ndim > 1: + raise ValueError('window must be 1-D') + half_len = (window.size - 1) // 2 + h = window + else: + # Design a linear-phase low-pass FIR filter + max_rate = max(up, down) + f_c = 1. / max_rate # cutoff of FIR filter (rel. to Nyquist) + half_len = 10 * max_rate # reasonable cutoff for sinc-like function + if np.issubdtype(x.dtype, np.complexfloating): + h = firwin(2 * half_len + 1, f_c, + window=window).astype(x.dtype) # match dtype of x + elif np.issubdtype(x.dtype, np.floating): + h = firwin(2 * half_len + 1, f_c, + window=window).astype(x.dtype) # match dtype of x + else: + h = firwin(2 * half_len + 1, f_c, + window=window) + h *= up + + # Zero-pad our filter to put the output samples at the center + n_pre_pad = (down - half_len % down) + n_post_pad = 0 + n_pre_remove = (half_len + n_pre_pad) // down + # We should rarely need to do this given our filter lengths... + while _output_len(len(h) + n_pre_pad + n_post_pad, n_in, + up, down) < n_out + n_pre_remove: + n_post_pad += 1 + h = np.concatenate((np.zeros(n_pre_pad, dtype=h.dtype), h, + np.zeros(n_post_pad, dtype=h.dtype))) + n_pre_remove_end = n_pre_remove + n_out + + # Remove background depending on the padtype option + funcs = {'mean': np.mean, 'median': np.median, + 'minimum': np.amin, 'maximum': np.amax} + upfirdn_kwargs = {'mode': 'constant', 'cval': 0} + if padtype in funcs: + background_values = funcs[padtype](x, axis=axis, keepdims=True) + elif padtype in _upfirdn_modes: + upfirdn_kwargs = {'mode': padtype} + if padtype == 'constant': + if cval is None: + cval = 0 + upfirdn_kwargs['cval'] = cval + else: + raise ValueError( + 'padtype must be one of: maximum, mean, median, minimum, ' + + ', '.join(_upfirdn_modes)) + + if padtype in funcs: + x = x - background_values + + # filter then remove excess + y = upfirdn(h, x, up, down, axis=axis, **upfirdn_kwargs) + keep = [slice(None), ]*x.ndim + keep[axis] = slice(n_pre_remove, n_pre_remove_end) + y_keep = y[tuple(keep)] + + # Add background back + if padtype in funcs: + y_keep += background_values + + return y_keep + + +def vectorstrength(events, period): + ''' + Determine the vector strength of the events corresponding to the given + period. + + The vector strength is a measure of phase synchrony, how well the + timing of the events is synchronized to a single period of a periodic + signal. + + If multiple periods are used, calculate the vector strength of each. + This is called the "resonating vector strength". + + Parameters + ---------- + events : 1D array_like + An array of time points containing the timing of the events. + period : float or array_like + The period of the signal that the events should synchronize to. + The period is in the same units as `events`. It can also be an array + of periods, in which case the outputs are arrays of the same length. + + Returns + ------- + strength : float or 1D array + The strength of the synchronization. 1.0 is perfect synchronization + and 0.0 is no synchronization. If `period` is an array, this is also + an array with each element containing the vector strength at the + corresponding period. + phase : float or array + The phase that the events are most strongly synchronized to in radians. + If `period` is an array, this is also an array with each element + containing the phase for the corresponding period. + + References + ---------- + van Hemmen, JL, Longtin, A, and Vollmayr, AN. Testing resonating vector + strength: Auditory system, electric fish, and noise. + Chaos 21, 047508 (2011); + :doi:`10.1063/1.3670512`. + van Hemmen, JL. Vector strength after Goldberg, Brown, and von Mises: + biological and mathematical perspectives. Biol Cybern. + 2013 Aug;107(4):385-96. :doi:`10.1007/s00422-013-0561-7`. + van Hemmen, JL and Vollmayr, AN. Resonating vector strength: what happens + when we vary the "probing" frequency while keeping the spike times + fixed. Biol Cybern. 2013 Aug;107(4):491-94. + :doi:`10.1007/s00422-013-0560-8`. + ''' + events = np.asarray(events) + period = np.asarray(period) + if events.ndim > 1: + raise ValueError('events cannot have dimensions more than 1') + if period.ndim > 1: + raise ValueError('period cannot have dimensions more than 1') + + # we need to know later if period was originally a scalar + scalarperiod = not period.ndim + + events = np.atleast_2d(events) + period = np.atleast_2d(period) + if (period <= 0).any(): + raise ValueError('periods must be positive') + + # this converts the times to vectors + vectors = np.exp(np.dot(2j*np.pi/period.T, events)) + + # the vector strength is just the magnitude of the mean of the vectors + # the vector phase is the angle of the mean of the vectors + vectormean = np.mean(vectors, axis=1) + strength = abs(vectormean) + phase = np.angle(vectormean) + + # if the original period was a scalar, return scalars + if scalarperiod: + strength = strength[0] + phase = phase[0] + return strength, phase + + +def detrend(data: np.ndarray, axis: int = -1, + type: Literal['linear', 'constant'] = 'linear', + bp: ArrayLike | int = 0, overwrite_data: bool = False) -> np.ndarray: + r"""Remove linear or constant trend along axis from data. + + Parameters + ---------- + data : array_like + The input data. + axis : int, optional + The axis along which to detrend the data. By default this is the + last axis (-1). + type : {'linear', 'constant'}, optional + The type of detrending. If ``type == 'linear'`` (default), + the result of a linear least-squares fit to `data` is subtracted + from `data`. + If ``type == 'constant'``, only the mean of `data` is subtracted. + bp : array_like of ints, optional + A sequence of break points. If given, an individual linear fit is + performed for each part of `data` between two break points. + Break points are specified as indices into `data`. This parameter + only has an effect when ``type == 'linear'``. + overwrite_data : bool, optional + If True, perform in place detrending and avoid a copy. Default is False + + Returns + ------- + ret : ndarray + The detrended input data. + + Notes + ----- + Detrending can be interpreted as subtracting a least squares fit polynomial: + Setting the parameter `type` to 'constant' corresponds to fitting a zeroth degree + polynomial, 'linear' to a first degree polynomial. Consult the example below. + + See Also + -------- + numpy.polynomial.polynomial.Polynomial.fit: Create least squares fit polynomial. + + + Examples + -------- + The following example detrends the function :math:`x(t) = \sin(\pi t) + 1/4`: + + >>> import matplotlib.pyplot as plt + >>> import numpy as np + >>> from scipy.signal import detrend + ... + >>> t = np.linspace(-0.5, 0.5, 21) + >>> x = np.sin(np.pi*t) + 1/4 + ... + >>> x_d_const = detrend(x, type='constant') + >>> x_d_linear = detrend(x, type='linear') + ... + >>> fig1, ax1 = plt.subplots() + >>> ax1.set_title(r"Detrending $x(t)=\sin(\pi t) + 1/4$") + >>> ax1.set(xlabel="t", ylabel="$x(t)$", xlim=(t[0], t[-1])) + >>> ax1.axhline(y=0, color='black', linewidth=.5) + >>> ax1.axvline(x=0, color='black', linewidth=.5) + >>> ax1.plot(t, x, 'C0.-', label="No detrending") + >>> ax1.plot(t, x_d_const, 'C1x-', label="type='constant'") + >>> ax1.plot(t, x_d_linear, 'C2+-', label="type='linear'") + >>> ax1.legend() + >>> plt.show() + + Alternatively, NumPy's `~numpy.polynomial.polynomial.Polynomial` can be used for + detrending as well: + + >>> pp0 = np.polynomial.Polynomial.fit(t, x, deg=0) # fit degree 0 polynomial + >>> np.allclose(x_d_const, x - pp0(t)) # compare with constant detrend + True + >>> pp1 = np.polynomial.Polynomial.fit(t, x, deg=1) # fit degree 1 polynomial + >>> np.allclose(x_d_linear, x - pp1(t)) # compare with linear detrend + True + + Note that `~numpy.polynomial.polynomial.Polynomial` also allows fitting higher + degree polynomials. Consult its documentation on how to extract the polynomial + coefficients. + """ + if type not in ['linear', 'l', 'constant', 'c']: + raise ValueError("Trend type must be 'linear' or 'constant'.") + data = np.asarray(data) + dtype = data.dtype.char + if dtype not in 'dfDF': + dtype = 'd' + if type in ['constant', 'c']: + ret = data - np.mean(data, axis, keepdims=True) + return ret + else: + dshape = data.shape + N = dshape[axis] + bp = np.sort(np.unique(np.concatenate(np.atleast_1d(0, bp, N)))) + if np.any(bp > N): + raise ValueError("Breakpoints must be less than length " + "of data along given axis.") + + # Restructure data so that axis is along first dimension and + # all other dimensions are collapsed into second dimension + rnk = len(dshape) + if axis < 0: + axis = axis + rnk + newdata = np.moveaxis(data, axis, 0) + newdata_shape = newdata.shape + newdata = newdata.reshape(N, -1) + + if not overwrite_data: + newdata = newdata.copy() # make sure we have a copy + if newdata.dtype.char not in 'dfDF': + newdata = newdata.astype(dtype) + +# Nreg = len(bp) - 1 + # Find leastsq fit and remove it for each piece + for m in range(len(bp) - 1): + Npts = bp[m + 1] - bp[m] + A = np.ones((Npts, 2), dtype) + A[:, 0] = np.arange(1, Npts + 1, dtype=dtype) / Npts + sl = slice(bp[m], bp[m + 1]) + coef, resids, rank, s = linalg.lstsq(A, newdata[sl]) + newdata[sl] = newdata[sl] - A @ coef + + # Put data back in original shape. + newdata = newdata.reshape(newdata_shape) + ret = np.moveaxis(newdata, 0, axis) + return ret + + +def lfilter_zi(b, a): + """ + Construct initial conditions for lfilter for step response steady-state. + + Compute an initial state `zi` for the `lfilter` function that corresponds + to the steady state of the step response. + + A typical use of this function is to set the initial state so that the + output of the filter starts at the same value as the first element of + the signal to be filtered. + + Parameters + ---------- + b, a : array_like (1-D) + The IIR filter coefficients. See `lfilter` for more + information. + + Returns + ------- + zi : 1-D ndarray + The initial state for the filter. + + See Also + -------- + lfilter, lfiltic, filtfilt + + Notes + ----- + A linear filter with order m has a state space representation (A, B, C, D), + for which the output y of the filter can be expressed as:: + + z(n+1) = A*z(n) + B*x(n) + y(n) = C*z(n) + D*x(n) + + where z(n) is a vector of length m, A has shape (m, m), B has shape + (m, 1), C has shape (1, m) and D has shape (1, 1) (assuming x(n) is + a scalar). lfilter_zi solves:: + + zi = A*zi + B + + In other words, it finds the initial condition for which the response + to an input of all ones is a constant. + + Given the filter coefficients `a` and `b`, the state space matrices + for the transposed direct form II implementation of the linear filter, + which is the implementation used by scipy.signal.lfilter, are:: + + A = scipy.linalg.companion(a).T + B = b[1:] - a[1:]*b[0] + + assuming ``a[0]`` is 1.0; if ``a[0]`` is not 1, `a` and `b` are first + divided by a[0]. + + Examples + -------- + The following code creates a lowpass Butterworth filter. Then it + applies that filter to an array whose values are all 1.0; the + output is also all 1.0, as expected for a lowpass filter. If the + `zi` argument of `lfilter` had not been given, the output would have + shown the transient signal. + + >>> from numpy import array, ones + >>> from scipy.signal import lfilter, lfilter_zi, butter + >>> b, a = butter(5, 0.25) + >>> zi = lfilter_zi(b, a) + >>> y, zo = lfilter(b, a, ones(10), zi=zi) + >>> y + array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]) + + Another example: + + >>> x = array([0.5, 0.5, 0.5, 0.0, 0.0, 0.0, 0.0]) + >>> y, zf = lfilter(b, a, x, zi=zi*x[0]) + >>> y + array([ 0.5 , 0.5 , 0.5 , 0.49836039, 0.48610528, + 0.44399389, 0.35505241]) + + Note that the `zi` argument to `lfilter` was computed using + `lfilter_zi` and scaled by ``x[0]``. Then the output `y` has no + transient until the input drops from 0.5 to 0.0. + + """ + + # FIXME: Can this function be replaced with an appropriate + # use of lfiltic? For example, when b,a = butter(N,Wn), + # lfiltic(b, a, y=numpy.ones_like(a), x=numpy.ones_like(b)). + # + + # We could use scipy.signal.normalize, but it uses warnings in + # cases where a ValueError is more appropriate, and it allows + # b to be 2D. + b = np.atleast_1d(b) + if b.ndim != 1: + raise ValueError("Numerator b must be 1-D.") + a = np.atleast_1d(a) + if a.ndim != 1: + raise ValueError("Denominator a must be 1-D.") + + while len(a) > 1 and a[0] == 0.0: + a = a[1:] + if a.size < 1: + raise ValueError("There must be at least one nonzero `a` coefficient.") + + if a[0] != 1.0: + # Normalize the coefficients so a[0] == 1. + b = b / a[0] + a = a / a[0] + + n = max(len(a), len(b)) + + # Pad a or b with zeros so they are the same length. + if len(a) < n: + a = np.r_[a, np.zeros(n - len(a), dtype=a.dtype)] + elif len(b) < n: + b = np.r_[b, np.zeros(n - len(b), dtype=b.dtype)] + + IminusA = np.eye(n - 1, dtype=np.result_type(a, b)) - linalg.companion(a).T + B = b[1:] - a[1:] * b[0] + # Solve zi = A*zi + B + zi = np.linalg.solve(IminusA, B) + + # For future reference: we could also use the following + # explicit formulas to solve the linear system: + # + # zi = np.zeros(n - 1) + # zi[0] = B.sum() / IminusA[:,0].sum() + # asum = 1.0 + # csum = 0.0 + # for k in range(1,n-1): + # asum += a[k] + # csum += b[k] - a[k]*b[0] + # zi[k] = asum*zi[0] - csum + + return zi + + +def sosfilt_zi(sos): + """ + Construct initial conditions for sosfilt for step response steady-state. + + Compute an initial state `zi` for the `sosfilt` function that corresponds + to the steady state of the step response. + + A typical use of this function is to set the initial state so that the + output of the filter starts at the same value as the first element of + the signal to be filtered. + + Parameters + ---------- + sos : array_like + Array of second-order filter coefficients, must have shape + ``(n_sections, 6)``. See `sosfilt` for the SOS filter format + specification. + + Returns + ------- + zi : ndarray + Initial conditions suitable for use with ``sosfilt``, shape + ``(n_sections, 2)``. + + See Also + -------- + sosfilt, zpk2sos + + Notes + ----- + .. versionadded:: 0.16.0 + + Examples + -------- + Filter a rectangular pulse that begins at time 0, with and without + the use of the `zi` argument of `scipy.signal.sosfilt`. + + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + + >>> sos = signal.butter(9, 0.125, output='sos') + >>> zi = signal.sosfilt_zi(sos) + >>> x = (np.arange(250) < 100).astype(int) + >>> f1 = signal.sosfilt(sos, x) + >>> f2, zo = signal.sosfilt(sos, x, zi=zi) + + >>> plt.plot(x, 'k--', label='x') + >>> plt.plot(f1, 'b', alpha=0.5, linewidth=2, label='filtered') + >>> plt.plot(f2, 'g', alpha=0.25, linewidth=4, label='filtered with zi') + >>> plt.legend(loc='best') + >>> plt.show() + + """ + sos = np.asarray(sos) + if sos.ndim != 2 or sos.shape[1] != 6: + raise ValueError('sos must be shape (n_sections, 6)') + + if sos.dtype.kind in 'bui': + sos = sos.astype(np.float64) + + n_sections = sos.shape[0] + zi = np.empty((n_sections, 2), dtype=sos.dtype) + scale = 1.0 + for section in range(n_sections): + b = sos[section, :3] + a = sos[section, 3:] + zi[section] = scale * lfilter_zi(b, a) + # If H(z) = B(z)/A(z) is this section's transfer function, then + # b.sum()/a.sum() is H(1), the gain at omega=0. That's the steady + # state value of this section's step response. + scale *= b.sum() / a.sum() + + return zi + + +def _filtfilt_gust(b, a, x, axis=-1, irlen=None): + """Forward-backward IIR filter that uses Gustafsson's method. + + Apply the IIR filter defined by ``(b,a)`` to `x` twice, first forward + then backward, using Gustafsson's initial conditions [1]_. + + Let ``y_fb`` be the result of filtering first forward and then backward, + and let ``y_bf`` be the result of filtering first backward then forward. + Gustafsson's method is to compute initial conditions for the forward + pass and the backward pass such that ``y_fb == y_bf``. + + Parameters + ---------- + b : scalar or 1-D ndarray + Numerator coefficients of the filter. + a : scalar or 1-D ndarray + Denominator coefficients of the filter. + x : ndarray + Data to be filtered. + axis : int, optional + Axis of `x` to be filtered. Default is -1. + irlen : int or None, optional + The length of the nonnegligible part of the impulse response. + If `irlen` is None, or if the length of the signal is less than + ``2 * irlen``, then no part of the impulse response is ignored. + + Returns + ------- + y : ndarray + The filtered data. + x0 : ndarray + Initial condition for the forward filter. + x1 : ndarray + Initial condition for the backward filter. + + Notes + ----- + Typically the return values `x0` and `x1` are not needed by the + caller. The intended use of these return values is in unit tests. + + References + ---------- + .. [1] F. Gustaffson. Determining the initial states in forward-backward + filtering. Transactions on Signal Processing, 46(4):988-992, 1996. + + """ + # In the comments, "Gustafsson's paper" and [1] refer to the + # paper referenced in the docstring. + + b = np.atleast_1d(b) + a = np.atleast_1d(a) + + order = max(len(b), len(a)) - 1 + if order == 0: + # The filter is just scalar multiplication, with no state. + scale = (b[0] / a[0])**2 + y = scale * x + return y, np.array([]), np.array([]) + + if axis != -1 or axis != x.ndim - 1: + # Move the axis containing the data to the end. + x = np.swapaxes(x, axis, x.ndim - 1) + + # n is the number of samples in the data to be filtered. + n = x.shape[-1] + + if irlen is None or n <= 2*irlen: + m = n + else: + m = irlen + + # Create Obs, the observability matrix (called O in the paper). + # This matrix can be interpreted as the operator that propagates + # an arbitrary initial state to the output, assuming the input is + # zero. + # In Gustafsson's paper, the forward and backward filters are not + # necessarily the same, so he has both O_f and O_b. We use the same + # filter in both directions, so we only need O. The same comment + # applies to S below. + Obs = np.zeros((m, order)) + zi = np.zeros(order) + zi[0] = 1 + Obs[:, 0] = lfilter(b, a, np.zeros(m), zi=zi)[0] + for k in range(1, order): + Obs[k:, k] = Obs[:-k, 0] + + # Obsr is O^R (Gustafsson's notation for row-reversed O) + Obsr = Obs[::-1] + + # Create S. S is the matrix that applies the filter to the reversed + # propagated initial conditions. That is, + # out = S.dot(zi) + # is the same as + # tmp, _ = lfilter(b, a, zeros(), zi=zi) # Propagate ICs. + # out = lfilter(b, a, tmp[::-1]) # Reverse and filter. + + # Equations (5) & (6) of [1] + S = lfilter(b, a, Obs[::-1], axis=0) + + # Sr is S^R (row-reversed S) + Sr = S[::-1] + + # M is [(S^R - O), (O^R - S)] + if m == n: + M = np.hstack((Sr - Obs, Obsr - S)) + else: + # Matrix described in section IV of [1]. + M = np.zeros((2*m, 2*order)) + M[:m, :order] = Sr - Obs + M[m:, order:] = Obsr - S + + # Naive forward-backward and backward-forward filters. + # These have large transients because the filters use zero initial + # conditions. + y_f = lfilter(b, a, x) + y_fb = lfilter(b, a, y_f[..., ::-1])[..., ::-1] + + y_b = lfilter(b, a, x[..., ::-1])[..., ::-1] + y_bf = lfilter(b, a, y_b) + + delta_y_bf_fb = y_bf - y_fb + if m == n: + delta = delta_y_bf_fb + else: + start_m = delta_y_bf_fb[..., :m] + end_m = delta_y_bf_fb[..., -m:] + delta = np.concatenate((start_m, end_m), axis=-1) + + # ic_opt holds the "optimal" initial conditions. + # The following code computes the result shown in the formula + # of the paper between equations (6) and (7). + if delta.ndim == 1: + ic_opt = linalg.lstsq(M, delta)[0] + else: + # Reshape delta so it can be used as an array of multiple + # right-hand-sides in linalg.lstsq. + delta2d = delta.reshape(-1, delta.shape[-1]).T + ic_opt0 = linalg.lstsq(M, delta2d)[0].T + ic_opt = ic_opt0.reshape(delta.shape[:-1] + (M.shape[-1],)) + + # Now compute the filtered signal using equation (7) of [1]. + # First, form [S^R, O^R] and call it W. + if m == n: + W = np.hstack((Sr, Obsr)) + else: + W = np.zeros((2*m, 2*order)) + W[:m, :order] = Sr + W[m:, order:] = Obsr + + # Equation (7) of [1] says + # Y_fb^opt = Y_fb^0 + W * [x_0^opt; x_{N-1}^opt] + # `wic` is (almost) the product on the right. + # W has shape (m, 2*order), and ic_opt has shape (..., 2*order), + # so we can't use W.dot(ic_opt). Instead, we dot ic_opt with W.T, + # so wic has shape (..., m). + wic = ic_opt.dot(W.T) + + # `wic` is "almost" the product of W and the optimal ICs in equation + # (7)--if we're using a truncated impulse response (m < n), `wic` + # contains only the adjustments required for the ends of the signal. + # Here we form y_opt, taking this into account if necessary. + y_opt = y_fb + if m == n: + y_opt += wic + else: + y_opt[..., :m] += wic[..., :m] + y_opt[..., -m:] += wic[..., -m:] + + x0 = ic_opt[..., :order] + x1 = ic_opt[..., -order:] + if axis != -1 or axis != x.ndim - 1: + # Restore the data axis to its original position. + x0 = np.swapaxes(x0, axis, x.ndim - 1) + x1 = np.swapaxes(x1, axis, x.ndim - 1) + y_opt = np.swapaxes(y_opt, axis, x.ndim - 1) + + return y_opt, x0, x1 + + +def filtfilt(b, a, x, axis=-1, padtype='odd', padlen=None, method='pad', + irlen=None): + """ + Apply a digital filter forward and backward to a signal. + + This function applies a linear digital filter twice, once forward and + once backwards. The combined filter has zero phase and a filter order + twice that of the original. + + The function provides options for handling the edges of the signal. + + The function `sosfiltfilt` (and filter design using ``output='sos'``) + should be preferred over `filtfilt` for most filtering tasks, as + second-order sections have fewer numerical problems. + + Parameters + ---------- + b : (N,) array_like + The numerator coefficient vector of the filter. + a : (N,) array_like + The denominator coefficient vector of the filter. If ``a[0]`` + is not 1, then both `a` and `b` are normalized by ``a[0]``. + x : array_like + The array of data to be filtered. + axis : int, optional + The axis of `x` to which the filter is applied. + Default is -1. + padtype : str or None, optional + Must be 'odd', 'even', 'constant', or None. This determines the + type of extension to use for the padded signal to which the filter + is applied. If `padtype` is None, no padding is used. The default + is 'odd'. + padlen : int or None, optional + The number of elements by which to extend `x` at both ends of + `axis` before applying the filter. This value must be less than + ``x.shape[axis] - 1``. ``padlen=0`` implies no padding. + The default value is ``3 * max(len(a), len(b))``. + method : str, optional + Determines the method for handling the edges of the signal, either + "pad" or "gust". When `method` is "pad", the signal is padded; the + type of padding is determined by `padtype` and `padlen`, and `irlen` + is ignored. When `method` is "gust", Gustafsson's method is used, + and `padtype` and `padlen` are ignored. + irlen : int or None, optional + When `method` is "gust", `irlen` specifies the length of the + impulse response of the filter. If `irlen` is None, no part + of the impulse response is ignored. For a long signal, specifying + `irlen` can significantly improve the performance of the filter. + + Returns + ------- + y : ndarray + The filtered output with the same shape as `x`. + + See Also + -------- + sosfiltfilt, lfilter_zi, lfilter, lfiltic, savgol_filter, sosfilt + + Notes + ----- + When `method` is "pad", the function pads the data along the given axis + in one of three ways: odd, even or constant. The odd and even extensions + have the corresponding symmetry about the end point of the data. The + constant extension extends the data with the values at the end points. On + both the forward and backward passes, the initial condition of the + filter is found by using `lfilter_zi` and scaling it by the end point of + the extended data. + + When `method` is "gust", Gustafsson's method [1]_ is used. Initial + conditions are chosen for the forward and backward passes so that the + forward-backward filter gives the same result as the backward-forward + filter. + + The option to use Gustaffson's method was added in scipy version 0.16.0. + + References + ---------- + .. [1] F. Gustaffson, "Determining the initial states in forward-backward + filtering", Transactions on Signal Processing, Vol. 46, pp. 988-992, + 1996. + + Examples + -------- + The examples will use several functions from `scipy.signal`. + + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + + First we create a one second signal that is the sum of two pure sine + waves, with frequencies 5 Hz and 250 Hz, sampled at 2000 Hz. + + >>> t = np.linspace(0, 1.0, 2001) + >>> xlow = np.sin(2 * np.pi * 5 * t) + >>> xhigh = np.sin(2 * np.pi * 250 * t) + >>> x = xlow + xhigh + + Now create a lowpass Butterworth filter with a cutoff of 0.125 times + the Nyquist frequency, or 125 Hz, and apply it to ``x`` with `filtfilt`. + The result should be approximately ``xlow``, with no phase shift. + + >>> b, a = signal.butter(8, 0.125) + >>> y = signal.filtfilt(b, a, x, padlen=150) + >>> np.abs(y - xlow).max() + 9.1086182074789912e-06 + + We get a fairly clean result for this artificial example because + the odd extension is exact, and with the moderately long padding, + the filter's transients have dissipated by the time the actual data + is reached. In general, transient effects at the edges are + unavoidable. + + The following example demonstrates the option ``method="gust"``. + + First, create a filter. + + >>> b, a = signal.ellip(4, 0.01, 120, 0.125) # Filter to be applied. + + `sig` is a random input signal to be filtered. + + >>> rng = np.random.default_rng() + >>> n = 60 + >>> sig = rng.standard_normal(n)**3 + 3*rng.standard_normal(n).cumsum() + + Apply `filtfilt` to `sig`, once using the Gustafsson method, and + once using padding, and plot the results for comparison. + + >>> fgust = signal.filtfilt(b, a, sig, method="gust") + >>> fpad = signal.filtfilt(b, a, sig, padlen=50) + >>> plt.plot(sig, 'k-', label='input') + >>> plt.plot(fgust, 'b-', linewidth=4, label='gust') + >>> plt.plot(fpad, 'c-', linewidth=1.5, label='pad') + >>> plt.legend(loc='best') + >>> plt.show() + + The `irlen` argument can be used to improve the performance + of Gustafsson's method. + + Estimate the impulse response length of the filter. + + >>> z, p, k = signal.tf2zpk(b, a) + >>> eps = 1e-9 + >>> r = np.max(np.abs(p)) + >>> approx_impulse_len = int(np.ceil(np.log(eps) / np.log(r))) + >>> approx_impulse_len + 137 + + Apply the filter to a longer signal, with and without the `irlen` + argument. The difference between `y1` and `y2` is small. For long + signals, using `irlen` gives a significant performance improvement. + + >>> x = rng.standard_normal(4000) + >>> y1 = signal.filtfilt(b, a, x, method='gust') + >>> y2 = signal.filtfilt(b, a, x, method='gust', irlen=approx_impulse_len) + >>> print(np.max(np.abs(y1 - y2))) + 2.875334415008979e-10 + + """ + b = np.atleast_1d(b) + a = np.atleast_1d(a) + x = np.asarray(x) + + if method not in ["pad", "gust"]: + raise ValueError("method must be 'pad' or 'gust'.") + + if method == "gust": + y, z1, z2 = _filtfilt_gust(b, a, x, axis=axis, irlen=irlen) + return y + + # method == "pad" + edge, ext = _validate_pad(padtype, padlen, x, axis, + ntaps=max(len(a), len(b))) + + # Get the steady state of the filter's step response. + zi = lfilter_zi(b, a) + + # Reshape zi and create x0 so that zi*x0 broadcasts + # to the correct value for the 'zi' keyword argument + # to lfilter. + zi_shape = [1] * x.ndim + zi_shape[axis] = zi.size + zi = np.reshape(zi, zi_shape) + x0 = axis_slice(ext, stop=1, axis=axis) + + # Forward filter. + (y, zf) = lfilter(b, a, ext, axis=axis, zi=zi * x0) + + # Backward filter. + # Create y0 so zi*y0 broadcasts appropriately. + y0 = axis_slice(y, start=-1, axis=axis) + (y, zf) = lfilter(b, a, axis_reverse(y, axis=axis), axis=axis, zi=zi * y0) + + # Reverse y. + y = axis_reverse(y, axis=axis) + + if edge > 0: + # Slice the actual signal from the extended signal. + y = axis_slice(y, start=edge, stop=-edge, axis=axis) + + return y + + +def _validate_pad(padtype, padlen, x, axis, ntaps): + """Helper to validate padding for filtfilt""" + if padtype not in ['even', 'odd', 'constant', None]: + raise ValueError(f"Unknown value '{padtype}' given to padtype. " + "padtype must be 'even', 'odd', 'constant', or None.") + + if padtype is None: + padlen = 0 + + if padlen is None: + # Original padding; preserved for backwards compatibility. + edge = ntaps * 3 + else: + edge = padlen + + # x's 'axis' dimension must be bigger than edge. + if x.shape[axis] <= edge: + raise ValueError("The length of the input vector x must be greater " + "than padlen, which is %d." % edge) + + if padtype is not None and edge > 0: + # Make an extension of length `edge` at each + # end of the input array. + if padtype == 'even': + ext = even_ext(x, edge, axis=axis) + elif padtype == 'odd': + ext = odd_ext(x, edge, axis=axis) + else: + ext = const_ext(x, edge, axis=axis) + else: + ext = x + return edge, ext + + +def _validate_x(x): + x = np.asarray(x) + if x.ndim == 0: + raise ValueError('x must be at least 1-D') + return x + + +def sosfilt(sos, x, axis=-1, zi=None): + """ + Filter data along one dimension using cascaded second-order sections. + + Filter a data sequence, `x`, using a digital IIR filter defined by + `sos`. + + Parameters + ---------- + sos : array_like + Array of second-order filter coefficients, must have shape + ``(n_sections, 6)``. Each row corresponds to a second-order + section, with the first three columns providing the numerator + coefficients and the last three providing the denominator + coefficients. + x : array_like + An N-dimensional input array. + axis : int, optional + The axis of the input data array along which to apply the + linear filter. The filter is applied to each subarray along + this axis. Default is -1. + zi : array_like, optional + Initial conditions for the cascaded filter delays. It is a (at + least 2D) vector of shape ``(n_sections, ..., 2, ...)``, where + ``..., 2, ...`` denotes the shape of `x`, but with ``x.shape[axis]`` + replaced by 2. If `zi` is None or is not given then initial rest + (i.e. all zeros) is assumed. + Note that these initial conditions are *not* the same as the initial + conditions given by `lfiltic` or `lfilter_zi`. + + Returns + ------- + y : ndarray + The output of the digital filter. + zf : ndarray, optional + If `zi` is None, this is not returned, otherwise, `zf` holds the + final filter delay values. + + See Also + -------- + zpk2sos, sos2zpk, sosfilt_zi, sosfiltfilt, freqz_sos + + Notes + ----- + The filter function is implemented as a series of second-order filters + with direct-form II transposed structure. It is designed to minimize + numerical precision errors for high-order filters. + + .. versionadded:: 0.16.0 + + Examples + -------- + Plot a 13th-order filter's impulse response using both `lfilter` and + `sosfilt`, showing the instability that results from trying to do a + 13th-order filter in a single stage (the numerical error pushes some poles + outside of the unit circle): + + >>> import matplotlib.pyplot as plt + >>> from scipy import signal + >>> b, a = signal.ellip(13, 0.009, 80, 0.05, output='ba') + >>> sos = signal.ellip(13, 0.009, 80, 0.05, output='sos') + >>> x = signal.unit_impulse(700) + >>> y_tf = signal.lfilter(b, a, x) + >>> y_sos = signal.sosfilt(sos, x) + >>> plt.plot(y_tf, 'r', label='TF') + >>> plt.plot(y_sos, 'k', label='SOS') + >>> plt.legend(loc='best') + >>> plt.show() + + """ + _reject_objects(sos, 'sosfilt') + _reject_objects(x, 'sosfilt') + if zi is not None: + _reject_objects(zi, 'sosfilt') + + x = _validate_x(x) + sos, n_sections = _validate_sos(sos) + x_zi_shape = list(x.shape) + x_zi_shape[axis] = 2 + x_zi_shape = tuple([n_sections] + x_zi_shape) + inputs = [sos, x] + if zi is not None: + inputs.append(np.asarray(zi)) + dtype = np.result_type(*inputs) + if dtype.char not in 'fdgFDGO': + raise NotImplementedError(f"input type '{dtype}' not supported") + if zi is not None: + zi = np.array(zi, dtype) # make a copy so that we can operate in place + if zi.shape != x_zi_shape: + raise ValueError('Invalid zi shape. With axis=%r, an input with ' + 'shape %r, and an sos array with %d sections, zi ' + 'must have shape %r, got %r.' % + (axis, x.shape, n_sections, x_zi_shape, zi.shape)) + return_zi = True + else: + zi = np.zeros(x_zi_shape, dtype=dtype) + return_zi = False + axis = axis % x.ndim # make positive + x = np.moveaxis(x, axis, -1) + zi = np.moveaxis(zi, [0, axis + 1], [-2, -1]) + x_shape, zi_shape = x.shape, zi.shape + x = np.reshape(x, (-1, x.shape[-1])) + x = np.array(x, dtype, order='C') # make a copy, can modify in place + zi = np.ascontiguousarray(np.reshape(zi, (-1, n_sections, 2))) + sos = sos.astype(dtype, copy=False) + _sosfilt(sos, x, zi) + x.shape = x_shape + x = np.moveaxis(x, -1, axis) + if return_zi: + zi.shape = zi_shape + zi = np.moveaxis(zi, [-2, -1], [0, axis + 1]) + out = (x, zi) + else: + out = x + return out + + +def sosfiltfilt(sos, x, axis=-1, padtype='odd', padlen=None): + """ + A forward-backward digital filter using cascaded second-order sections. + + See `filtfilt` for more complete information about this method. + + Parameters + ---------- + sos : array_like + Array of second-order filter coefficients, must have shape + ``(n_sections, 6)``. Each row corresponds to a second-order + section, with the first three columns providing the numerator + coefficients and the last three providing the denominator + coefficients. + x : array_like + The array of data to be filtered. + axis : int, optional + The axis of `x` to which the filter is applied. + Default is -1. + padtype : str or None, optional + Must be 'odd', 'even', 'constant', or None. This determines the + type of extension to use for the padded signal to which the filter + is applied. If `padtype` is None, no padding is used. The default + is 'odd'. + padlen : int or None, optional + The number of elements by which to extend `x` at both ends of + `axis` before applying the filter. This value must be less than + ``x.shape[axis] - 1``. ``padlen=0`` implies no padding. + The default value is:: + + 3 * (2 * len(sos) + 1 - min((sos[:, 2] == 0).sum(), + (sos[:, 5] == 0).sum())) + + The extra subtraction at the end attempts to compensate for poles + and zeros at the origin (e.g. for odd-order filters) to yield + equivalent estimates of `padlen` to those of `filtfilt` for + second-order section filters built with `scipy.signal` functions. + + Returns + ------- + y : ndarray + The filtered output with the same shape as `x`. + + See Also + -------- + filtfilt, sosfilt, sosfilt_zi, freqz_sos + + Notes + ----- + .. versionadded:: 0.18.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal import sosfiltfilt, butter + >>> import matplotlib.pyplot as plt + >>> rng = np.random.default_rng() + + Create an interesting signal to filter. + + >>> n = 201 + >>> t = np.linspace(0, 1, n) + >>> x = 1 + (t < 0.5) - 0.25*t**2 + 0.05*rng.standard_normal(n) + + Create a lowpass Butterworth filter, and use it to filter `x`. + + >>> sos = butter(4, 0.125, output='sos') + >>> y = sosfiltfilt(sos, x) + + For comparison, apply an 8th order filter using `sosfilt`. The filter + is initialized using the mean of the first four values of `x`. + + >>> from scipy.signal import sosfilt, sosfilt_zi + >>> sos8 = butter(8, 0.125, output='sos') + >>> zi = x[:4].mean() * sosfilt_zi(sos8) + >>> y2, zo = sosfilt(sos8, x, zi=zi) + + Plot the results. Note that the phase of `y` matches the input, while + `y2` has a significant phase delay. + + >>> plt.plot(t, x, alpha=0.5, label='x(t)') + >>> plt.plot(t, y, label='y(t)') + >>> plt.plot(t, y2, label='y2(t)') + >>> plt.legend(framealpha=1, shadow=True) + >>> plt.grid(alpha=0.25) + >>> plt.xlabel('t') + >>> plt.show() + + """ + sos, n_sections = _validate_sos(sos) + x = _validate_x(x) + + # `method` is "pad"... + ntaps = 2 * n_sections + 1 + ntaps -= min((sos[:, 2] == 0).sum(), (sos[:, 5] == 0).sum()) + edge, ext = _validate_pad(padtype, padlen, x, axis, + ntaps=ntaps) + + # These steps follow the same form as filtfilt with modifications + zi = sosfilt_zi(sos) # shape (n_sections, 2) --> (n_sections, ..., 2, ...) + zi_shape = [1] * x.ndim + zi_shape[axis] = 2 + zi.shape = [n_sections] + zi_shape + x_0 = axis_slice(ext, stop=1, axis=axis) + (y, zf) = sosfilt(sos, ext, axis=axis, zi=zi * x_0) + y_0 = axis_slice(y, start=-1, axis=axis) + (y, zf) = sosfilt(sos, axis_reverse(y, axis=axis), axis=axis, zi=zi * y_0) + y = axis_reverse(y, axis=axis) + if edge > 0: + y = axis_slice(y, start=edge, stop=-edge, axis=axis) + return y + + +def decimate(x, q, n=None, ftype='iir', axis=-1, zero_phase=True): + """ + Downsample the signal after applying an anti-aliasing filter. + + By default, an order 8 Chebyshev type I filter is used. A 30 point FIR + filter with Hamming window is used if `ftype` is 'fir'. + + Parameters + ---------- + x : array_like + The signal to be downsampled, as an N-dimensional array. + q : int + The downsampling factor. When using IIR downsampling, it is recommended + to call `decimate` multiple times for downsampling factors higher than + 13. + n : int, optional + The order of the filter (1 less than the length for 'fir'). Defaults to + 8 for 'iir' and 20 times the downsampling factor for 'fir'. + ftype : str {'iir', 'fir'} or ``dlti`` instance, optional + If 'iir' or 'fir', specifies the type of lowpass filter. If an instance + of an `dlti` object, uses that object to filter before downsampling. + axis : int, optional + The axis along which to decimate. + zero_phase : bool, optional + Prevent phase shift by filtering with `filtfilt` instead of `lfilter` + when using an IIR filter, and shifting the outputs back by the filter's + group delay when using an FIR filter. The default value of ``True`` is + recommended, since a phase shift is generally not desired. + + .. versionadded:: 0.18.0 + + Returns + ------- + y : ndarray + The down-sampled signal. + + See Also + -------- + resample : Resample up or down using the FFT method. + resample_poly : Resample using polyphase filtering and an FIR filter. + + Notes + ----- + The ``zero_phase`` keyword was added in 0.18.0. + The possibility to use instances of ``dlti`` as ``ftype`` was added in + 0.18.0. + + Examples + -------- + + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + + Define wave parameters. + + >>> wave_duration = 3 + >>> sample_rate = 100 + >>> freq = 2 + >>> q = 5 + + Calculate number of samples. + + >>> samples = wave_duration*sample_rate + >>> samples_decimated = int(samples/q) + + Create cosine wave. + + >>> x = np.linspace(0, wave_duration, samples, endpoint=False) + >>> y = np.cos(x*np.pi*freq*2) + + Decimate cosine wave. + + >>> ydem = signal.decimate(y, q) + >>> xnew = np.linspace(0, wave_duration, samples_decimated, endpoint=False) + + Plot original and decimated waves. + + >>> plt.plot(x, y, '.-', xnew, ydem, 'o-') + >>> plt.xlabel('Time, Seconds') + >>> plt.legend(['data', 'decimated'], loc='best') + >>> plt.show() + + """ + + x = np.asarray(x) + q = operator.index(q) + + if n is not None: + n = operator.index(n) + + result_type = x.dtype + if not np.issubdtype(result_type, np.inexact) \ + or result_type.type == np.float16: + # upcast integers and float16 to float64 + result_type = np.float64 + + if ftype == 'fir': + if n is None: + half_len = 10 * q # reasonable cutoff for our sinc-like function + n = 2 * half_len + b, a = firwin(n+1, 1. / q, window='hamming'), 1. + b = np.asarray(b, dtype=result_type) + a = np.asarray(a, dtype=result_type) + elif ftype == 'iir': + iir_use_sos = True + if n is None: + n = 8 + sos = cheby1(n, 0.05, 0.8 / q, output='sos') + sos = np.asarray(sos, dtype=result_type) + elif isinstance(ftype, dlti): + system = ftype._as_zpk() + if system.poles.shape[0] == 0: + # FIR + system = ftype._as_tf() + b, a = system.num, system.den + ftype = 'fir' + elif (any(np.iscomplex(system.poles)) + or any(np.iscomplex(system.poles)) + or np.iscomplex(system.gain)): + # sosfilt & sosfiltfilt don't handle complex coeffs + iir_use_sos = False + system = ftype._as_tf() + b, a = system.num, system.den + else: + iir_use_sos = True + sos = zpk2sos(system.zeros, system.poles, system.gain) + sos = np.asarray(sos, dtype=result_type) + else: + raise ValueError('invalid ftype') + + sl = [slice(None)] * x.ndim + + if ftype == 'fir': + b = b / a + if zero_phase: + y = resample_poly(x, 1, q, axis=axis, window=b) + else: + # upfirdn is generally faster than lfilter by a factor equal to the + # downsampling factor, since it only calculates the needed outputs + n_out = x.shape[axis] // q + bool(x.shape[axis] % q) + y = upfirdn(b, x, up=1, down=q, axis=axis) + sl[axis] = slice(None, n_out, None) + + else: # IIR case + if zero_phase: + if iir_use_sos: + y = sosfiltfilt(sos, x, axis=axis) + else: + y = filtfilt(b, a, x, axis=axis) + else: + if iir_use_sos: + y = sosfilt(sos, x, axis=axis) + else: + y = lfilter(b, a, x, axis=axis) + + sl[axis] = slice(None, None, q) + + return y[tuple(sl)] diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_sigtools.cpython-310-x86_64-linux-gnu.so b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_sigtools.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..9697a8a7dda74e71dadf9522d0ba943d2946a581 Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_sigtools.cpython-310-x86_64-linux-gnu.so differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_spectral_py.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_spectral_py.py new file mode 100644 index 0000000000000000000000000000000000000000..5151b2b335172a485b5d13408d35290812cadc43 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_spectral_py.py @@ -0,0 +1,2291 @@ +"""Tools for spectral analysis. +""" +import numpy as np +import numpy.typing as npt +from scipy import fft as sp_fft +from . import _signaltools +from .windows import get_window +from ._arraytools import const_ext, even_ext, odd_ext, zero_ext +import warnings +from typing import Literal + + +__all__ = ['periodogram', 'welch', 'lombscargle', 'csd', 'coherence', + 'spectrogram', 'stft', 'istft', 'check_COLA', 'check_NOLA'] + + +def lombscargle( + x: npt.ArrayLike, + y: npt.ArrayLike, + freqs: npt.ArrayLike, + precenter: bool = False, + normalize: bool | Literal["power", "normalize", "amplitude"] = False, + *, + weights: npt.NDArray | None = None, + floating_mean: bool = False, +) -> npt.NDArray: + """ + Compute the generalized Lomb-Scargle periodogram. + + The Lomb-Scargle periodogram was developed by Lomb [1]_ and further + extended by Scargle [2]_ to find, and test the significance of weak + periodic signals with uneven temporal sampling. The algorithm used + here is based on a weighted least-squares fit of the form + ``y(ω) = a*cos(ω*x) + b*sin(ω*x) + c``, where the fit is calculated for + each frequency independently. This algorithm was developed by Zechmeister + and Kürster which improves the Lomb-Scargle periodogram by enabling + the weighting of individual samples and calculating an unknown y offset + (also called a "floating-mean" model) [3]_. For more details, and practical + considerations, see the excellent reference on the Lomb-Scargle periodogram [4]_. + + When *normalize* is False (or "power") (default) the computed periodogram + is unnormalized, it takes the value ``(A**2) * N/4`` for a harmonic + signal with amplitude A for sufficiently large N. Where N is the length of x or y. + + When *normalize* is True (or "normalize") the computed periodogram is normalized + by the residuals of the data around a constant reference model (at zero). + + When *normalize* is "amplitude" the computed periodogram is the complex + representation of the amplitude and phase. + + Input arrays should be 1-D of a real floating data type, which are converted into + float64 arrays before processing. + + Parameters + ---------- + x : array_like + Sample times. + y : array_like + Measurement values. Values are assumed to have a baseline of ``y = 0``. If + there is a possibility of a y offset, it is recommended to set `floating_mean` + to True. + freqs : array_like + Angular frequencies (e.g., having unit rad/s=2π/s for `x` having unit s) for + output periodogram. Frequencies are normally >= 0, as any peak at ``-freq`` will + also exist at ``+freq``. + precenter : bool, optional + Pre-center measurement values by subtracting the mean, if True. This is + a legacy parameter and unnecessary if `floating_mean` is True. + normalize : bool | str, optional + Compute normalized or complex (amplitude + phase) periodogram. + Valid options are: ``False``/``"power"``, ``True``/``"normalize"``, or + ``"amplitude"``. + weights : array_like, optional + Weights for each sample. Weights must be nonnegative. + floating_mean : bool, optional + Determines a y offset for each frequency independently, if True. + Else the y offset is assumed to be `0`. + + Returns + ------- + pgram : array_like + Lomb-Scargle periodogram. + + Raises + ------ + ValueError + If any of the input arrays x, y, freqs, or weights are not 1D, or if any are + zero length. Or, if the input arrays x, y, and weights do not have the same + shape as each other. + ValueError + If any weight is < 0, or the sum of the weights is <= 0. + ValueError + If the normalize parameter is not one of the allowed options. + + See Also + -------- + periodogram: Power spectral density using a periodogram + welch: Power spectral density by Welch's method + csd: Cross spectral density by Welch's method + + Notes + ----- + The algorithm used will not automatically account for any unknown y offset, unless + floating_mean is True. Therefore, for most use cases, if there is a possibility of + a y offset, it is recommended to set floating_mean to True. If precenter is True, + it performs the operation ``y -= y.mean()``. However, precenter is a legacy + parameter, and unnecessary when floating_mean is True. Furthermore, the mean + removed by precenter does not account for sample weights, nor will it correct for + any bias due to consistently missing observations at peaks and/or troughs. When the + normalize parameter is "amplitude", for any frequency in freqs that is below + ``(2*pi)/(x.max() - x.min())``, the predicted amplitude will tend towards infinity. + The concept of a "Nyquist frequency" limit (see Nyquist-Shannon sampling theorem) + is not generally applicable to unevenly sampled data. Therefore, with unevenly + sampled data, valid frequencies in freqs can often be much higher than expected. + + References + ---------- + .. [1] N.R. Lomb "Least-squares frequency analysis of unequally spaced + data", Astrophysics and Space Science, vol 39, pp. 447-462, 1976 + :doi:`10.1007/bf00648343` + + .. [2] J.D. Scargle "Studies in astronomical time series analysis. II - + Statistical aspects of spectral analysis of unevenly spaced data", + The Astrophysical Journal, vol 263, pp. 835-853, 1982 + :doi:`10.1086/160554` + + .. [3] M. Zechmeister and M. Kürster, "The generalised Lomb-Scargle periodogram. + A new formalism for the floating-mean and Keplerian periodograms," + Astronomy and Astrophysics, vol. 496, pp. 577-584, 2009 + :doi:`10.1051/0004-6361:200811296` + + .. [4] J.T. VanderPlas, "Understanding the Lomb-Scargle Periodogram," + The Astrophysical Journal Supplement Series, vol. 236, no. 1, p. 16, + May 2018 + :doi:`10.3847/1538-4365/aab766` + + + Examples + -------- + >>> import numpy as np + >>> rng = np.random.default_rng() + + First define some input parameters for the signal: + + >>> A = 2. # amplitude + >>> c = 2. # offset + >>> w0 = 1. # rad/sec + >>> nin = 150 + >>> nout = 1002 + + Randomly generate sample times: + + >>> x = rng.uniform(0, 10*np.pi, nin) + + Plot a sine wave for the selected times: + + >>> y = A * np.cos(w0*x) + c + + Define the array of frequencies for which to compute the periodogram: + + >>> w = np.linspace(0.25, 10, nout) + + Calculate Lomb-Scargle periodogram for each of the normalize options: + + >>> from scipy.signal import lombscargle + >>> pgram_power = lombscargle(x, y, w, normalize=False) + >>> pgram_norm = lombscargle(x, y, w, normalize=True) + >>> pgram_amp = lombscargle(x, y, w, normalize='amplitude') + ... + >>> pgram_power_f = lombscargle(x, y, w, normalize=False, floating_mean=True) + >>> pgram_norm_f = lombscargle(x, y, w, normalize=True, floating_mean=True) + >>> pgram_amp_f = lombscargle(x, y, w, normalize='amplitude', floating_mean=True) + + Now make a plot of the input data: + + >>> import matplotlib.pyplot as plt + >>> fig, (ax_t, ax_p, ax_n, ax_a) = plt.subplots(4, 1, figsize=(5, 6)) + >>> ax_t.plot(x, y, 'b+') + >>> ax_t.set_xlabel('Time [s]') + >>> ax_t.set_ylabel('Amplitude') + + Then plot the periodogram for each of the normalize options, as well as with and + without floating_mean=True: + + >>> ax_p.plot(w, pgram_power, label='default') + >>> ax_p.plot(w, pgram_power_f, label='floating_mean=True') + >>> ax_p.set_xlabel('Angular frequency [rad/s]') + >>> ax_p.set_ylabel('Power') + >>> ax_p.legend(prop={'size': 7}) + ... + >>> ax_n.plot(w, pgram_norm, label='default') + >>> ax_n.plot(w, pgram_norm_f, label='floating_mean=True') + >>> ax_n.set_xlabel('Angular frequency [rad/s]') + >>> ax_n.set_ylabel('Normalized') + >>> ax_n.legend(prop={'size': 7}) + ... + >>> ax_a.plot(w, np.abs(pgram_amp), label='default') + >>> ax_a.plot(w, np.abs(pgram_amp_f), label='floating_mean=True') + >>> ax_a.set_xlabel('Angular frequency [rad/s]') + >>> ax_a.set_ylabel('Amplitude') + >>> ax_a.legend(prop={'size': 7}) + ... + >>> plt.tight_layout() + >>> plt.show() + + """ + + # if no weights are provided, assume all data points are equally important + if weights is None: + weights = np.ones_like(y, dtype=np.float64) + else: + # if provided, make sure weights is an array and cast to float64 + weights = np.asarray(weights, dtype=np.float64) + + # make sure other inputs are arrays and cast to float64 + # done before validation, in case they were not arrays + x = np.asarray(x, dtype=np.float64) + y = np.asarray(y, dtype=np.float64) + freqs = np.asarray(freqs, dtype=np.float64) + + # validate input shapes + if not (x.ndim == 1 and x.size > 0 and x.shape == y.shape == weights.shape): + raise ValueError("Parameters x, y, weights must be 1-D arrays of " + "equal non-zero length!") + if not (freqs.ndim == 1 and freqs.size > 0): + raise ValueError("Parameter freqs must be a 1-D array of non-zero length!") + + # validate weights + if not (np.all(weights >= 0) and np.sum(weights) > 0): + raise ValueError("Parameter weights must have only non-negative entries " + "which sum to a positive value!") + + # validate normalize parameter + if isinstance(normalize, bool): + # if bool, convert to str literal + normalize = "normalize" if normalize else "power" + + if normalize not in ["power", "normalize", "amplitude"]: + raise ValueError( + "Normalize must be: False (or 'power'), True (or 'normalize'), " + "or 'amplitude'." + ) + + # weight vector must sum to 1 + weights *= 1.0 / weights.sum() + + # if requested, perform precenter + if precenter: + y -= y.mean() + + # transform arrays + # row vector + freqs = freqs.reshape(1, -1) + # column vectors + x = x.reshape(-1, 1) + y = y.reshape(-1, 1) + weights = weights.reshape(-1, 1) + + # store frequent intermediates + weights_y = weights * y + freqst = freqs * x + coswt = np.cos(freqst) + sinwt = np.sin(freqst) + + Y = np.dot(weights.T, y) # Eq. 7 + CC = np.dot(weights.T, coswt * coswt) # Eq. 13 + SS = 1.0 - CC # trig identity: S^2 = 1 - C^2 Eq.14 + CS = np.dot(weights.T, coswt * sinwt) # Eq. 15 + + if floating_mean: + C = np.dot(weights.T, coswt) # Eq. 8 + S = np.dot(weights.T, sinwt) # Eq. 9 + CC -= C * C # Eq. 13 + SS -= S * S # Eq. 14 + CS -= C * S # Eq. 15 + + # calculate tau (phase offset to eliminate CS variable) + tau = 0.5 * np.arctan2(2.0 * CS, CC - SS) # Eq. 19 + freqst_tau = freqst - tau + + # coswt and sinwt are now offset by tau, which eliminates CS + coswt_tau = np.cos(freqst_tau) + sinwt_tau = np.sin(freqst_tau) + + YC = np.dot(weights_y.T, coswt_tau) # Eq. 11 + YS = np.dot(weights_y.T, sinwt_tau) # Eq. 12 + CC = np.dot(weights.T, coswt_tau * coswt_tau) # Eq. 13, CC range is [0.5, 1.0] + SS = 1.0 - CC # trig identity: S^2 = 1 - C^2 Eq. 14, SS range is [0.0, 0.5] + + if floating_mean: + C = np.dot(weights.T, coswt_tau) # Eq. 8 + S = np.dot(weights.T, sinwt_tau) # Eq. 9 + YC -= Y * C # Eq. 11 + YS -= Y * S # Eq. 12 + CC -= C * C # Eq. 13, CC range is now [0.0, 1.0] + SS -= S * S # Eq. 14, SS range is now [0.0, 0.5] + + # to prevent division by zero errors with a and b, as well as correcting for + # numerical precision errors that lead to CC or SS being approximately -0.0, + # make sure CC and SS are both > 0 + epsneg = np.finfo(dtype=y.dtype).epsneg + CC[CC < epsneg] = epsneg + SS[SS < epsneg] = epsneg + + # calculate a and b + # where: y(w) = a*cos(w) + b*sin(w) + c + a = YC / CC # Eq. A.4 and 6, eliminating CS + b = YS / SS # Eq. A.4 and 6, eliminating CS + # c = Y - a * C - b * S + + # store final value as power in A^2 (i.e., (y units)^2) + pgram = 2.0 * (a * YC + b * YS) + + # squeeze back to a vector + pgram = np.squeeze(pgram) + + if normalize == "power": # (default) + # return the legacy power units ((A**2) * N/4) + + pgram *= float(x.shape[0]) / 4.0 + + elif normalize == "normalize": + # return the normalized power (power at current frequency wrt the entire signal) + # range will be [0, 1] + + YY = np.dot(weights_y.T, y) # Eq. 10 + if floating_mean: + YY -= Y * Y # Eq. 10 + + pgram *= 0.5 / np.squeeze(YY) # Eq. 20 + + else: # normalize == "amplitude": + # return the complex representation of the best-fit amplitude and phase + + # squeeze back to vectors + a = np.squeeze(a) + b = np.squeeze(b) + tau = np.squeeze(tau) + + # calculate the complex representation, and correct for tau rotation + pgram = (a + 1j * b) * np.exp(1j * tau) + + return pgram + + +def periodogram(x, fs=1.0, window='boxcar', nfft=None, detrend='constant', + return_onesided=True, scaling='density', axis=-1): + """ + Estimate power spectral density using a periodogram. + + Parameters + ---------- + x : array_like + Time series of measurement values + fs : float, optional + Sampling frequency of the `x` time series. Defaults to 1.0. + window : str or tuple or array_like, optional + Desired window to use. If `window` is a string or tuple, it is + passed to `get_window` to generate the window values, which are + DFT-even by default. See `get_window` for a list of windows and + required parameters. If `window` is array_like it will be used + directly as the window and its length must be equal to the length + of the axis over which the periodogram is computed. Defaults + to 'boxcar'. + nfft : int, optional + Length of the FFT used. If `None` the length of `x` will be + used. + detrend : str or function or `False`, optional + Specifies how to detrend each segment. If `detrend` is a + string, it is passed as the `type` argument to the `detrend` + function. If it is a function, it takes a segment and returns a + detrended segment. If `detrend` is `False`, no detrending is + done. Defaults to 'constant'. + return_onesided : bool, optional + If `True`, return a one-sided spectrum for real data. If + `False` return a two-sided spectrum. Defaults to `True`, but for + complex data, a two-sided spectrum is always returned. + scaling : { 'density', 'spectrum' }, optional + Selects between computing the power spectral density ('density') + where `Pxx` has units of V**2/Hz and computing the squared magnitude + spectrum ('spectrum') where `Pxx` has units of V**2, if `x` + is measured in V and `fs` is measured in Hz. Defaults to + 'density' + axis : int, optional + Axis along which the periodogram is computed; the default is + over the last axis (i.e. ``axis=-1``). + + Returns + ------- + f : ndarray + Array of sample frequencies. + Pxx : ndarray + Power spectral density or power spectrum of `x`. + + See Also + -------- + welch: Estimate power spectral density using Welch's method + lombscargle: Lomb-Scargle periodogram for unevenly sampled data + + Notes + ----- + Consult the :ref:`tutorial_SpectralAnalysis` section of the :ref:`user_guide` + for a discussion of the scalings of the power spectral density and + the magnitude (squared) spectrum. + + .. versionadded:: 0.12.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> rng = np.random.default_rng() + + Generate a test signal, a 2 Vrms sine wave at 1234 Hz, corrupted by + 0.001 V**2/Hz of white noise sampled at 10 kHz. + + >>> fs = 10e3 + >>> N = 1e5 + >>> amp = 2*np.sqrt(2) + >>> freq = 1234.0 + >>> noise_power = 0.001 * fs / 2 + >>> time = np.arange(N) / fs + >>> x = amp*np.sin(2*np.pi*freq*time) + >>> x += rng.normal(scale=np.sqrt(noise_power), size=time.shape) + + Compute and plot the power spectral density. + + >>> f, Pxx_den = signal.periodogram(x, fs) + >>> plt.semilogy(f, Pxx_den) + >>> plt.ylim([1e-7, 1e2]) + >>> plt.xlabel('frequency [Hz]') + >>> plt.ylabel('PSD [V**2/Hz]') + >>> plt.show() + + If we average the last half of the spectral density, to exclude the + peak, we can recover the noise power on the signal. + + >>> np.mean(Pxx_den[25000:]) + 0.000985320699252543 + + Now compute and plot the power spectrum. + + >>> f, Pxx_spec = signal.periodogram(x, fs, 'flattop', scaling='spectrum') + >>> plt.figure() + >>> plt.semilogy(f, np.sqrt(Pxx_spec)) + >>> plt.ylim([1e-4, 1e1]) + >>> plt.xlabel('frequency [Hz]') + >>> plt.ylabel('Linear spectrum [V RMS]') + >>> plt.show() + + The peak height in the power spectrum is an estimate of the RMS + amplitude. + + >>> np.sqrt(Pxx_spec.max()) + 2.0077340678640727 + + """ + x = np.asarray(x) + + if x.size == 0: + return np.empty(x.shape), np.empty(x.shape) + + if window is None: + window = 'boxcar' + + if nfft is None: + nperseg = x.shape[axis] + elif nfft == x.shape[axis]: + nperseg = nfft + elif nfft > x.shape[axis]: + nperseg = x.shape[axis] + elif nfft < x.shape[axis]: + s = [np.s_[:]]*len(x.shape) + s[axis] = np.s_[:nfft] + x = x[tuple(s)] + nperseg = nfft + nfft = None + + if hasattr(window, 'size'): + if window.size != nperseg: + raise ValueError('the size of the window must be the same size ' + 'of the input on the specified axis') + + return welch(x, fs=fs, window=window, nperseg=nperseg, noverlap=0, + nfft=nfft, detrend=detrend, return_onesided=return_onesided, + scaling=scaling, axis=axis) + + +def welch(x, fs=1.0, window='hann', nperseg=None, noverlap=None, nfft=None, + detrend='constant', return_onesided=True, scaling='density', + axis=-1, average='mean'): + r""" + Estimate power spectral density using Welch's method. + + Welch's method [1]_ computes an estimate of the power spectral + density by dividing the data into overlapping segments, computing a + modified periodogram for each segment and averaging the + periodograms. + + Parameters + ---------- + x : array_like + Time series of measurement values + fs : float, optional + Sampling frequency of the `x` time series. Defaults to 1.0. + window : str or tuple or array_like, optional + Desired window to use. If `window` is a string or tuple, it is + passed to `get_window` to generate the window values, which are + DFT-even by default. See `get_window` for a list of windows and + required parameters. If `window` is array_like it will be used + directly as the window and its length must be nperseg. Defaults + to a Hann window. + nperseg : int, optional + Length of each segment. Defaults to None, but if window is str or + tuple, is set to 256, and if window is array_like, is set to the + length of the window. + noverlap : int, optional + Number of points to overlap between segments. If `None`, + ``noverlap = nperseg // 2``. Defaults to `None`. + nfft : int, optional + Length of the FFT used, if a zero padded FFT is desired. If + `None`, the FFT length is `nperseg`. Defaults to `None`. + detrend : str or function or `False`, optional + Specifies how to detrend each segment. If `detrend` is a + string, it is passed as the `type` argument to the `detrend` + function. If it is a function, it takes a segment and returns a + detrended segment. If `detrend` is `False`, no detrending is + done. Defaults to 'constant'. + return_onesided : bool, optional + If `True`, return a one-sided spectrum for real data. If + `False` return a two-sided spectrum. Defaults to `True`, but for + complex data, a two-sided spectrum is always returned. + scaling : { 'density', 'spectrum' }, optional + Selects between computing the power spectral density ('density') + where `Pxx` has units of V**2/Hz and computing the squared magnitude + spectrum ('spectrum') where `Pxx` has units of V**2, if `x` + is measured in V and `fs` is measured in Hz. Defaults to + 'density' + axis : int, optional + Axis along which the periodogram is computed; the default is + over the last axis (i.e. ``axis=-1``). + average : { 'mean', 'median' }, optional + Method to use when averaging periodograms. Defaults to 'mean'. + + .. versionadded:: 1.2.0 + + Returns + ------- + f : ndarray + Array of sample frequencies. + Pxx : ndarray + Power spectral density or power spectrum of x. + + See Also + -------- + periodogram: Simple, optionally modified periodogram + lombscargle: Lomb-Scargle periodogram for unevenly sampled data + + Notes + ----- + An appropriate amount of overlap will depend on the choice of window + and on your requirements. For the default Hann window an overlap of + 50% is a reasonable trade off between accurately estimating the + signal power, while not over counting any of the data. Narrower + windows may require a larger overlap. + + If `noverlap` is 0, this method is equivalent to Bartlett's method + [2]_. + + Consult the :ref:`tutorial_SpectralAnalysis` section of the :ref:`user_guide` + for a discussion of the scalings of the power spectral density and + the (squared) magnitude spectrum. + + .. versionadded:: 0.12.0 + + References + ---------- + .. [1] P. Welch, "The use of the fast Fourier transform for the + estimation of power spectra: A method based on time averaging + over short, modified periodograms", IEEE Trans. Audio + Electroacoust. vol. 15, pp. 70-73, 1967. + .. [2] M.S. Bartlett, "Periodogram Analysis and Continuous Spectra", + Biometrika, vol. 37, pp. 1-16, 1950. + + Examples + -------- + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> rng = np.random.default_rng() + + Generate a test signal, a 2 Vrms sine wave at 1234 Hz, corrupted by + 0.001 V**2/Hz of white noise sampled at 10 kHz. + + >>> fs = 10e3 + >>> N = 1e5 + >>> amp = 2*np.sqrt(2) + >>> freq = 1234.0 + >>> noise_power = 0.001 * fs / 2 + >>> time = np.arange(N) / fs + >>> x = amp*np.sin(2*np.pi*freq*time) + >>> x += rng.normal(scale=np.sqrt(noise_power), size=time.shape) + + Compute and plot the power spectral density. + + >>> f, Pxx_den = signal.welch(x, fs, nperseg=1024) + >>> plt.semilogy(f, Pxx_den) + >>> plt.ylim([0.5e-3, 1]) + >>> plt.xlabel('frequency [Hz]') + >>> plt.ylabel('PSD [V**2/Hz]') + >>> plt.show() + + If we average the last half of the spectral density, to exclude the + peak, we can recover the noise power on the signal. + + >>> np.mean(Pxx_den[256:]) + 0.0009924865443739191 + + Now compute and plot the power spectrum. + + >>> f, Pxx_spec = signal.welch(x, fs, 'flattop', 1024, scaling='spectrum') + >>> plt.figure() + >>> plt.semilogy(f, np.sqrt(Pxx_spec)) + >>> plt.xlabel('frequency [Hz]') + >>> plt.ylabel('Linear spectrum [V RMS]') + >>> plt.show() + + The peak height in the power spectrum is an estimate of the RMS + amplitude. + + >>> np.sqrt(Pxx_spec.max()) + 2.0077340678640727 + + If we now introduce a discontinuity in the signal, by increasing the + amplitude of a small portion of the signal by 50, we can see the + corruption of the mean average power spectral density, but using a + median average better estimates the normal behaviour. + + >>> x[int(N//2):int(N//2)+10] *= 50. + >>> f, Pxx_den = signal.welch(x, fs, nperseg=1024) + >>> f_med, Pxx_den_med = signal.welch(x, fs, nperseg=1024, average='median') + >>> plt.semilogy(f, Pxx_den, label='mean') + >>> plt.semilogy(f_med, Pxx_den_med, label='median') + >>> plt.ylim([0.5e-3, 1]) + >>> plt.xlabel('frequency [Hz]') + >>> plt.ylabel('PSD [V**2/Hz]') + >>> plt.legend() + >>> plt.show() + + """ + freqs, Pxx = csd(x, x, fs=fs, window=window, nperseg=nperseg, + noverlap=noverlap, nfft=nfft, detrend=detrend, + return_onesided=return_onesided, scaling=scaling, + axis=axis, average=average) + + return freqs, Pxx.real + + +def csd(x, y, fs=1.0, window='hann', nperseg=None, noverlap=None, nfft=None, + detrend='constant', return_onesided=True, scaling='density', + axis=-1, average='mean'): + r""" + Estimate the cross power spectral density, Pxy, using Welch's method. + + Parameters + ---------- + x : array_like + Time series of measurement values + y : array_like + Time series of measurement values + fs : float, optional + Sampling frequency of the `x` and `y` time series. Defaults + to 1.0. + window : str or tuple or array_like, optional + Desired window to use. If `window` is a string or tuple, it is + passed to `get_window` to generate the window values, which are + DFT-even by default. See `get_window` for a list of windows and + required parameters. If `window` is array_like it will be used + directly as the window and its length must be nperseg. Defaults + to a Hann window. + nperseg : int, optional + Length of each segment. Defaults to None, but if window is str or + tuple, is set to 256, and if window is array_like, is set to the + length of the window. + noverlap: int, optional + Number of points to overlap between segments. If `None`, + ``noverlap = nperseg // 2``. Defaults to `None`. + nfft : int, optional + Length of the FFT used, if a zero padded FFT is desired. If + `None`, the FFT length is `nperseg`. Defaults to `None`. + detrend : str or function or `False`, optional + Specifies how to detrend each segment. If `detrend` is a + string, it is passed as the `type` argument to the `detrend` + function. If it is a function, it takes a segment and returns a + detrended segment. If `detrend` is `False`, no detrending is + done. Defaults to 'constant'. + return_onesided : bool, optional + If `True`, return a one-sided spectrum for real data. If + `False` return a two-sided spectrum. Defaults to `True`, but for + complex data, a two-sided spectrum is always returned. + scaling : { 'density', 'spectrum' }, optional + Selects between computing the cross spectral density ('density') + where `Pxy` has units of V**2/Hz and computing the cross spectrum + ('spectrum') where `Pxy` has units of V**2, if `x` and `y` are + measured in V and `fs` is measured in Hz. Defaults to 'density' + axis : int, optional + Axis along which the CSD is computed for both inputs; the + default is over the last axis (i.e. ``axis=-1``). + average : { 'mean', 'median' }, optional + Method to use when averaging periodograms. If the spectrum is + complex, the average is computed separately for the real and + imaginary parts. Defaults to 'mean'. + + .. versionadded:: 1.2.0 + + Returns + ------- + f : ndarray + Array of sample frequencies. + Pxy : ndarray + Cross spectral density or cross power spectrum of x,y. + + See Also + -------- + periodogram: Simple, optionally modified periodogram + lombscargle: Lomb-Scargle periodogram for unevenly sampled data + welch: Power spectral density by Welch's method. [Equivalent to + csd(x,x)] + coherence: Magnitude squared coherence by Welch's method. + + Notes + ----- + By convention, Pxy is computed with the conjugate FFT of X + multiplied by the FFT of Y. + + If the input series differ in length, the shorter series will be + zero-padded to match. + + An appropriate amount of overlap will depend on the choice of window + and on your requirements. For the default Hann window an overlap of + 50% is a reasonable trade off between accurately estimating the + signal power, while not over counting any of the data. Narrower + windows may require a larger overlap. + + Consult the :ref:`tutorial_SpectralAnalysis` section of the :ref:`user_guide` + for a discussion of the scalings of a spectral density and an (amplitude) spectrum. + + .. versionadded:: 0.16.0 + + References + ---------- + .. [1] P. Welch, "The use of the fast Fourier transform for the + estimation of power spectra: A method based on time averaging + over short, modified periodograms", IEEE Trans. Audio + Electroacoust. vol. 15, pp. 70-73, 1967. + .. [2] Rabiner, Lawrence R., and B. Gold. "Theory and Application of + Digital Signal Processing" Prentice-Hall, pp. 414-419, 1975 + + Examples + -------- + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> rng = np.random.default_rng() + + Generate two test signals with some common features. + + >>> fs = 10e3 + >>> N = 1e5 + >>> amp = 20 + >>> freq = 1234.0 + >>> noise_power = 0.001 * fs / 2 + >>> time = np.arange(N) / fs + >>> b, a = signal.butter(2, 0.25, 'low') + >>> x = rng.normal(scale=np.sqrt(noise_power), size=time.shape) + >>> y = signal.lfilter(b, a, x) + >>> x += amp*np.sin(2*np.pi*freq*time) + >>> y += rng.normal(scale=0.1*np.sqrt(noise_power), size=time.shape) + + Compute and plot the magnitude of the cross spectral density. + + >>> f, Pxy = signal.csd(x, y, fs, nperseg=1024) + >>> plt.semilogy(f, np.abs(Pxy)) + >>> plt.xlabel('frequency [Hz]') + >>> plt.ylabel('CSD [V**2/Hz]') + >>> plt.show() + + """ + freqs, _, Pxy = _spectral_helper(x, y, fs, window, nperseg, noverlap, + nfft, detrend, return_onesided, scaling, + axis, mode='psd') + + # Average over windows. + if len(Pxy.shape) >= 2 and Pxy.size > 0: + if Pxy.shape[-1] > 1: + if average == 'median': + # np.median must be passed real arrays for the desired result + bias = _median_bias(Pxy.shape[-1]) + if np.iscomplexobj(Pxy): + Pxy = (np.median(np.real(Pxy), axis=-1) + + 1j * np.median(np.imag(Pxy), axis=-1)) + else: + Pxy = np.median(Pxy, axis=-1) + Pxy /= bias + elif average == 'mean': + Pxy = Pxy.mean(axis=-1) + else: + raise ValueError(f'average must be "median" or "mean", got {average}') + else: + Pxy = np.reshape(Pxy, Pxy.shape[:-1]) + + return freqs, Pxy + + +def spectrogram(x, fs=1.0, window=('tukey', .25), nperseg=None, noverlap=None, + nfft=None, detrend='constant', return_onesided=True, + scaling='density', axis=-1, mode='psd'): + """Compute a spectrogram with consecutive Fourier transforms (legacy function). + + Spectrograms can be used as a way of visualizing the change of a + nonstationary signal's frequency content over time. + + .. legacy:: function + + :class:`ShortTimeFFT` is a newer STFT / ISTFT implementation with more + features also including a :meth:`~ShortTimeFFT.spectrogram` method. + A :ref:`comparison ` between the + implementations can be found in the :ref:`tutorial_stft` section of + the :ref:`user_guide`. + + Parameters + ---------- + x : array_like + Time series of measurement values + fs : float, optional + Sampling frequency of the `x` time series. Defaults to 1.0. + window : str or tuple or array_like, optional + Desired window to use. If `window` is a string or tuple, it is + passed to `get_window` to generate the window values, which are + DFT-even by default. See `get_window` for a list of windows and + required parameters. If `window` is array_like it will be used + directly as the window and its length must be nperseg. + Defaults to a Tukey window with shape parameter of 0.25. + nperseg : int, optional + Length of each segment. Defaults to None, but if window is str or + tuple, is set to 256, and if window is array_like, is set to the + length of the window. + noverlap : int, optional + Number of points to overlap between segments. If `None`, + ``noverlap = nperseg // 8``. Defaults to `None`. + nfft : int, optional + Length of the FFT used, if a zero padded FFT is desired. If + `None`, the FFT length is `nperseg`. Defaults to `None`. + detrend : str or function or `False`, optional + Specifies how to detrend each segment. If `detrend` is a + string, it is passed as the `type` argument to the `detrend` + function. If it is a function, it takes a segment and returns a + detrended segment. If `detrend` is `False`, no detrending is + done. Defaults to 'constant'. + return_onesided : bool, optional + If `True`, return a one-sided spectrum for real data. If + `False` return a two-sided spectrum. Defaults to `True`, but for + complex data, a two-sided spectrum is always returned. + scaling : { 'density', 'spectrum' }, optional + Selects between computing the power spectral density ('density') + where `Sxx` has units of V**2/Hz and computing the power + spectrum ('spectrum') where `Sxx` has units of V**2, if `x` + is measured in V and `fs` is measured in Hz. Defaults to + 'density'. + axis : int, optional + Axis along which the spectrogram is computed; the default is over + the last axis (i.e. ``axis=-1``). + mode : str, optional + Defines what kind of return values are expected. Options are + ['psd', 'complex', 'magnitude', 'angle', 'phase']. 'complex' is + equivalent to the output of `stft` with no padding or boundary + extension. 'magnitude' returns the absolute magnitude of the + STFT. 'angle' and 'phase' return the complex angle of the STFT, + with and without unwrapping, respectively. + + Returns + ------- + f : ndarray + Array of sample frequencies. + t : ndarray + Array of segment times. + Sxx : ndarray + Spectrogram of x. By default, the last axis of Sxx corresponds + to the segment times. + + See Also + -------- + periodogram: Simple, optionally modified periodogram + lombscargle: Lomb-Scargle periodogram for unevenly sampled data + welch: Power spectral density by Welch's method. + csd: Cross spectral density by Welch's method. + ShortTimeFFT: Newer STFT/ISTFT implementation providing more features, + which also includes a :meth:`~ShortTimeFFT.spectrogram` + method. + + Notes + ----- + An appropriate amount of overlap will depend on the choice of window + and on your requirements. In contrast to welch's method, where the + entire data stream is averaged over, one may wish to use a smaller + overlap (or perhaps none at all) when computing a spectrogram, to + maintain some statistical independence between individual segments. + It is for this reason that the default window is a Tukey window with + 1/8th of a window's length overlap at each end. + + + .. versionadded:: 0.16.0 + + References + ---------- + .. [1] Oppenheim, Alan V., Ronald W. Schafer, John R. Buck + "Discrete-Time Signal Processing", Prentice Hall, 1999. + + Examples + -------- + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fftshift + >>> import matplotlib.pyplot as plt + >>> rng = np.random.default_rng() + + Generate a test signal, a 2 Vrms sine wave whose frequency is slowly + modulated around 3kHz, corrupted by white noise of exponentially + decreasing magnitude sampled at 10 kHz. + + >>> fs = 10e3 + >>> N = 1e5 + >>> amp = 2 * np.sqrt(2) + >>> noise_power = 0.01 * fs / 2 + >>> time = np.arange(N) / float(fs) + >>> mod = 500*np.cos(2*np.pi*0.25*time) + >>> carrier = amp * np.sin(2*np.pi*3e3*time + mod) + >>> noise = rng.normal(scale=np.sqrt(noise_power), size=time.shape) + >>> noise *= np.exp(-time/5) + >>> x = carrier + noise + + Compute and plot the spectrogram. + + >>> f, t, Sxx = signal.spectrogram(x, fs) + >>> plt.pcolormesh(t, f, Sxx, shading='gouraud') + >>> plt.ylabel('Frequency [Hz]') + >>> plt.xlabel('Time [sec]') + >>> plt.show() + + Note, if using output that is not one sided, then use the following: + + >>> f, t, Sxx = signal.spectrogram(x, fs, return_onesided=False) + >>> plt.pcolormesh(t, fftshift(f), fftshift(Sxx, axes=0), shading='gouraud') + >>> plt.ylabel('Frequency [Hz]') + >>> plt.xlabel('Time [sec]') + >>> plt.show() + + """ + modelist = ['psd', 'complex', 'magnitude', 'angle', 'phase'] + if mode not in modelist: + raise ValueError(f'unknown value for mode {mode}, must be one of {modelist}') + + # need to set default for nperseg before setting default for noverlap below + window, nperseg = _triage_segments(window, nperseg, + input_length=x.shape[axis]) + + # Less overlap than welch, so samples are more statistically independent + if noverlap is None: + noverlap = nperseg // 8 + + if mode == 'psd': + freqs, time, Sxx = _spectral_helper(x, x, fs, window, nperseg, + noverlap, nfft, detrend, + return_onesided, scaling, axis, + mode='psd') + + else: + freqs, time, Sxx = _spectral_helper(x, x, fs, window, nperseg, + noverlap, nfft, detrend, + return_onesided, scaling, axis, + mode='stft') + + if mode == 'magnitude': + Sxx = np.abs(Sxx) + elif mode in ['angle', 'phase']: + Sxx = np.angle(Sxx) + if mode == 'phase': + # Sxx has one additional dimension for time strides + if axis < 0: + axis -= 1 + Sxx = np.unwrap(Sxx, axis=axis) + + # mode =='complex' is same as `stft`, doesn't need modification + + return freqs, time, Sxx + + +def check_COLA(window, nperseg, noverlap, tol=1e-10): + r"""Check whether the Constant OverLap Add (COLA) constraint is met. + + Parameters + ---------- + window : str or tuple or array_like + Desired window to use. If `window` is a string or tuple, it is + passed to `get_window` to generate the window values, which are + DFT-even by default. See `get_window` for a list of windows and + required parameters. If `window` is array_like it will be used + directly as the window and its length must be nperseg. + nperseg : int + Length of each segment. + noverlap : int + Number of points to overlap between segments. + tol : float, optional + The allowed variance of a bin's weighted sum from the median bin + sum. + + Returns + ------- + verdict : bool + `True` if chosen combination satisfies COLA within `tol`, + `False` otherwise + + See Also + -------- + check_NOLA: Check whether the Nonzero Overlap Add (NOLA) constraint is met + stft: Short Time Fourier Transform + istft: Inverse Short Time Fourier Transform + + Notes + ----- + In order to enable inversion of an STFT via the inverse STFT in + `istft`, it is sufficient that the signal windowing obeys the constraint of + "Constant OverLap Add" (COLA). This ensures that every point in the input + data is equally weighted, thereby avoiding aliasing and allowing full + reconstruction. + + Some examples of windows that satisfy COLA: + - Rectangular window at overlap of 0, 1/2, 2/3, 3/4, ... + - Bartlett window at overlap of 1/2, 3/4, 5/6, ... + - Hann window at 1/2, 2/3, 3/4, ... + - Any Blackman family window at 2/3 overlap + - Any window with ``noverlap = nperseg-1`` + + A very comprehensive list of other windows may be found in [2]_, + wherein the COLA condition is satisfied when the "Amplitude + Flatness" is unity. + + .. versionadded:: 0.19.0 + + References + ---------- + .. [1] Julius O. Smith III, "Spectral Audio Signal Processing", W3K + Publishing, 2011,ISBN 978-0-9745607-3-1. + .. [2] G. Heinzel, A. Ruediger and R. Schilling, "Spectrum and + spectral density estimation by the Discrete Fourier transform + (DFT), including a comprehensive list of window functions and + some new at-top windows", 2002, + http://hdl.handle.net/11858/00-001M-0000-0013-557A-5 + + Examples + -------- + >>> from scipy import signal + + Confirm COLA condition for rectangular window of 75% (3/4) overlap: + + >>> signal.check_COLA(signal.windows.boxcar(100), 100, 75) + True + + COLA is not true for 25% (1/4) overlap, though: + + >>> signal.check_COLA(signal.windows.boxcar(100), 100, 25) + False + + "Symmetrical" Hann window (for filter design) is not COLA: + + >>> signal.check_COLA(signal.windows.hann(120, sym=True), 120, 60) + False + + "Periodic" or "DFT-even" Hann window (for FFT analysis) is COLA for + overlap of 1/2, 2/3, 3/4, etc.: + + >>> signal.check_COLA(signal.windows.hann(120, sym=False), 120, 60) + True + + >>> signal.check_COLA(signal.windows.hann(120, sym=False), 120, 80) + True + + >>> signal.check_COLA(signal.windows.hann(120, sym=False), 120, 90) + True + + """ + nperseg = int(nperseg) + + if nperseg < 1: + raise ValueError('nperseg must be a positive integer') + + if noverlap >= nperseg: + raise ValueError('noverlap must be less than nperseg.') + noverlap = int(noverlap) + + if isinstance(window, str) or type(window) is tuple: + win = get_window(window, nperseg) + else: + win = np.asarray(window) + if len(win.shape) != 1: + raise ValueError('window must be 1-D') + if win.shape[0] != nperseg: + raise ValueError('window must have length of nperseg') + + step = nperseg - noverlap + binsums = sum(win[ii*step:(ii+1)*step] for ii in range(nperseg//step)) + + if nperseg % step != 0: + binsums[:nperseg % step] += win[-(nperseg % step):] + + deviation = binsums - np.median(binsums) + return np.max(np.abs(deviation)) < tol + + +def check_NOLA(window, nperseg, noverlap, tol=1e-10): + r"""Check whether the Nonzero Overlap Add (NOLA) constraint is met. + + Parameters + ---------- + window : str or tuple or array_like + Desired window to use. If `window` is a string or tuple, it is + passed to `get_window` to generate the window values, which are + DFT-even by default. See `get_window` for a list of windows and + required parameters. If `window` is array_like it will be used + directly as the window and its length must be nperseg. + nperseg : int + Length of each segment. + noverlap : int + Number of points to overlap between segments. + tol : float, optional + The allowed variance of a bin's weighted sum from the median bin + sum. + + Returns + ------- + verdict : bool + `True` if chosen combination satisfies the NOLA constraint within + `tol`, `False` otherwise + + See Also + -------- + check_COLA: Check whether the Constant OverLap Add (COLA) constraint is met + stft: Short Time Fourier Transform + istft: Inverse Short Time Fourier Transform + + Notes + ----- + In order to enable inversion of an STFT via the inverse STFT in + `istft`, the signal windowing must obey the constraint of "nonzero + overlap add" (NOLA): + + .. math:: \sum_{t}w^{2}[n-tH] \ne 0 + + for all :math:`n`, where :math:`w` is the window function, :math:`t` is the + frame index, and :math:`H` is the hop size (:math:`H` = `nperseg` - + `noverlap`). + + This ensures that the normalization factors in the denominator of the + overlap-add inversion equation are not zero. Only very pathological windows + will fail the NOLA constraint. + + .. versionadded:: 1.2.0 + + References + ---------- + .. [1] Julius O. Smith III, "Spectral Audio Signal Processing", W3K + Publishing, 2011,ISBN 978-0-9745607-3-1. + .. [2] G. Heinzel, A. Ruediger and R. Schilling, "Spectrum and + spectral density estimation by the Discrete Fourier transform + (DFT), including a comprehensive list of window functions and + some new at-top windows", 2002, + http://hdl.handle.net/11858/00-001M-0000-0013-557A-5 + + Examples + -------- + >>> import numpy as np + >>> from scipy import signal + + Confirm NOLA condition for rectangular window of 75% (3/4) overlap: + + >>> signal.check_NOLA(signal.windows.boxcar(100), 100, 75) + True + + NOLA is also true for 25% (1/4) overlap: + + >>> signal.check_NOLA(signal.windows.boxcar(100), 100, 25) + True + + "Symmetrical" Hann window (for filter design) is also NOLA: + + >>> signal.check_NOLA(signal.windows.hann(120, sym=True), 120, 60) + True + + As long as there is overlap, it takes quite a pathological window to fail + NOLA: + + >>> w = np.ones(64, dtype="float") + >>> w[::2] = 0 + >>> signal.check_NOLA(w, 64, 32) + False + + If there is not enough overlap, a window with zeros at the ends will not + work: + + >>> signal.check_NOLA(signal.windows.hann(64), 64, 0) + False + >>> signal.check_NOLA(signal.windows.hann(64), 64, 1) + False + >>> signal.check_NOLA(signal.windows.hann(64), 64, 2) + True + + """ + nperseg = int(nperseg) + + if nperseg < 1: + raise ValueError('nperseg must be a positive integer') + + if noverlap >= nperseg: + raise ValueError('noverlap must be less than nperseg') + if noverlap < 0: + raise ValueError('noverlap must be a nonnegative integer') + noverlap = int(noverlap) + + if isinstance(window, str) or type(window) is tuple: + win = get_window(window, nperseg) + else: + win = np.asarray(window) + if len(win.shape) != 1: + raise ValueError('window must be 1-D') + if win.shape[0] != nperseg: + raise ValueError('window must have length of nperseg') + + step = nperseg - noverlap + binsums = sum(win[ii*step:(ii+1)*step]**2 for ii in range(nperseg//step)) + + if nperseg % step != 0: + binsums[:nperseg % step] += win[-(nperseg % step):]**2 + + return np.min(binsums) > tol + + +def stft(x, fs=1.0, window='hann', nperseg=256, noverlap=None, nfft=None, + detrend=False, return_onesided=True, boundary='zeros', padded=True, + axis=-1, scaling='spectrum'): + r"""Compute the Short Time Fourier Transform (legacy function). + + STFTs can be used as a way of quantifying the change of a + nonstationary signal's frequency and phase content over time. + + .. legacy:: function + + `ShortTimeFFT` is a newer STFT / ISTFT implementation with more + features. A :ref:`comparison ` between the + implementations can be found in the :ref:`tutorial_stft` section of the + :ref:`user_guide`. + + Parameters + ---------- + x : array_like + Time series of measurement values + fs : float, optional + Sampling frequency of the `x` time series. Defaults to 1.0. + window : str or tuple or array_like, optional + Desired window to use. If `window` is a string or tuple, it is + passed to `get_window` to generate the window values, which are + DFT-even by default. See `get_window` for a list of windows and + required parameters. If `window` is array_like it will be used + directly as the window and its length must be nperseg. Defaults + to a Hann window. + nperseg : int, optional + Length of each segment. Defaults to 256. + noverlap : int, optional + Number of points to overlap between segments. If `None`, + ``noverlap = nperseg // 2``. Defaults to `None`. When + specified, the COLA constraint must be met (see Notes below). + nfft : int, optional + Length of the FFT used, if a zero padded FFT is desired. If + `None`, the FFT length is `nperseg`. Defaults to `None`. + detrend : str or function or `False`, optional + Specifies how to detrend each segment. If `detrend` is a + string, it is passed as the `type` argument to the `detrend` + function. If it is a function, it takes a segment and returns a + detrended segment. If `detrend` is `False`, no detrending is + done. Defaults to `False`. + return_onesided : bool, optional + If `True`, return a one-sided spectrum for real data. If + `False` return a two-sided spectrum. Defaults to `True`, but for + complex data, a two-sided spectrum is always returned. + boundary : str or None, optional + Specifies whether the input signal is extended at both ends, and + how to generate the new values, in order to center the first + windowed segment on the first input point. This has the benefit + of enabling reconstruction of the first input point when the + employed window function starts at zero. Valid options are + ``['even', 'odd', 'constant', 'zeros', None]``. Defaults to + 'zeros', for zero padding extension. I.e. ``[1, 2, 3, 4]`` is + extended to ``[0, 1, 2, 3, 4, 0]`` for ``nperseg=3``. + padded : bool, optional + Specifies whether the input signal is zero-padded at the end to + make the signal fit exactly into an integer number of window + segments, so that all of the signal is included in the output. + Defaults to `True`. Padding occurs after boundary extension, if + `boundary` is not `None`, and `padded` is `True`, as is the + default. + axis : int, optional + Axis along which the STFT is computed; the default is over the + last axis (i.e. ``axis=-1``). + scaling: {'spectrum', 'psd'} + The default 'spectrum' scaling allows each frequency line of `Zxx` to + be interpreted as a magnitude spectrum. The 'psd' option scales each + line to a power spectral density - it allows to calculate the signal's + energy by numerically integrating over ``abs(Zxx)**2``. + + .. versionadded:: 1.9.0 + + Returns + ------- + f : ndarray + Array of sample frequencies. + t : ndarray + Array of segment times. + Zxx : ndarray + STFT of `x`. By default, the last axis of `Zxx` corresponds + to the segment times. + + See Also + -------- + istft: Inverse Short Time Fourier Transform + ShortTimeFFT: Newer STFT/ISTFT implementation providing more features. + check_COLA: Check whether the Constant OverLap Add (COLA) constraint + is met + check_NOLA: Check whether the Nonzero Overlap Add (NOLA) constraint is met + welch: Power spectral density by Welch's method. + spectrogram: Spectrogram by Welch's method. + csd: Cross spectral density by Welch's method. + lombscargle: Lomb-Scargle periodogram for unevenly sampled data + + Notes + ----- + In order to enable inversion of an STFT via the inverse STFT in + `istft`, the signal windowing must obey the constraint of "Nonzero + OverLap Add" (NOLA), and the input signal must have complete + windowing coverage (i.e. ``(x.shape[axis] - nperseg) % + (nperseg-noverlap) == 0``). The `padded` argument may be used to + accomplish this. + + Given a time-domain signal :math:`x[n]`, a window :math:`w[n]`, and a hop + size :math:`H` = `nperseg - noverlap`, the windowed frame at time index + :math:`t` is given by + + .. math:: x_{t}[n]=x[n]w[n-tH] + + The overlap-add (OLA) reconstruction equation is given by + + .. math:: x[n]=\frac{\sum_{t}x_{t}[n]w[n-tH]}{\sum_{t}w^{2}[n-tH]} + + The NOLA constraint ensures that every normalization term that appears + in the denominator of the OLA reconstruction equation is nonzero. Whether a + choice of `window`, `nperseg`, and `noverlap` satisfy this constraint can + be tested with `check_NOLA`. + + + .. versionadded:: 0.19.0 + + References + ---------- + .. [1] Oppenheim, Alan V., Ronald W. Schafer, John R. Buck + "Discrete-Time Signal Processing", Prentice Hall, 1999. + .. [2] Daniel W. Griffin, Jae S. Lim "Signal Estimation from + Modified Short-Time Fourier Transform", IEEE 1984, + 10.1109/TASSP.1984.1164317 + + Examples + -------- + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> rng = np.random.default_rng() + + Generate a test signal, a 2 Vrms sine wave whose frequency is slowly + modulated around 3kHz, corrupted by white noise of exponentially + decreasing magnitude sampled at 10 kHz. + + >>> fs = 10e3 + >>> N = 1e5 + >>> amp = 2 * np.sqrt(2) + >>> noise_power = 0.01 * fs / 2 + >>> time = np.arange(N) / float(fs) + >>> mod = 500*np.cos(2*np.pi*0.25*time) + >>> carrier = amp * np.sin(2*np.pi*3e3*time + mod) + >>> noise = rng.normal(scale=np.sqrt(noise_power), + ... size=time.shape) + >>> noise *= np.exp(-time/5) + >>> x = carrier + noise + + Compute and plot the STFT's magnitude. + + >>> f, t, Zxx = signal.stft(x, fs, nperseg=1000) + >>> plt.pcolormesh(t, f, np.abs(Zxx), vmin=0, vmax=amp, shading='gouraud') + >>> plt.title('STFT Magnitude') + >>> plt.ylabel('Frequency [Hz]') + >>> plt.xlabel('Time [sec]') + >>> plt.show() + + Compare the energy of the signal `x` with the energy of its STFT: + + >>> E_x = sum(x**2) / fs # Energy of x + >>> # Calculate a two-sided STFT with PSD scaling: + >>> f, t, Zxx = signal.stft(x, fs, nperseg=1000, return_onesided=False, + ... scaling='psd') + >>> # Integrate numerically over abs(Zxx)**2: + >>> df, dt = f[1] - f[0], t[1] - t[0] + >>> E_Zxx = sum(np.sum(Zxx.real**2 + Zxx.imag**2, axis=0) * df) * dt + >>> # The energy is the same, but the numerical errors are quite large: + >>> np.isclose(E_x, E_Zxx, rtol=1e-2) + True + + """ + if scaling == 'psd': + scaling = 'density' + elif scaling != 'spectrum': + raise ValueError(f"Parameter {scaling=} not in ['spectrum', 'psd']!") + + freqs, time, Zxx = _spectral_helper(x, x, fs, window, nperseg, noverlap, + nfft, detrend, return_onesided, + scaling=scaling, axis=axis, + mode='stft', boundary=boundary, + padded=padded) + + return freqs, time, Zxx + + +def istft(Zxx, fs=1.0, window='hann', nperseg=None, noverlap=None, nfft=None, + input_onesided=True, boundary=True, time_axis=-1, freq_axis=-2, + scaling='spectrum'): + r"""Perform the inverse Short Time Fourier transform (legacy function). + + .. legacy:: function + + `ShortTimeFFT` is a newer STFT / ISTFT implementation with more + features. A :ref:`comparison ` between the + implementations can be found in the :ref:`tutorial_stft` section of the + :ref:`user_guide`. + + Parameters + ---------- + Zxx : array_like + STFT of the signal to be reconstructed. If a purely real array + is passed, it will be cast to a complex data type. + fs : float, optional + Sampling frequency of the time series. Defaults to 1.0. + window : str or tuple or array_like, optional + Desired window to use. If `window` is a string or tuple, it is + passed to `get_window` to generate the window values, which are + DFT-even by default. See `get_window` for a list of windows and + required parameters. If `window` is array_like it will be used + directly as the window and its length must be nperseg. Defaults + to a Hann window. Must match the window used to generate the + STFT for faithful inversion. + nperseg : int, optional + Number of data points corresponding to each STFT segment. This + parameter must be specified if the number of data points per + segment is odd, or if the STFT was padded via ``nfft > + nperseg``. If `None`, the value depends on the shape of + `Zxx` and `input_onesided`. If `input_onesided` is `True`, + ``nperseg=2*(Zxx.shape[freq_axis] - 1)``. Otherwise, + ``nperseg=Zxx.shape[freq_axis]``. Defaults to `None`. + noverlap : int, optional + Number of points to overlap between segments. If `None`, half + of the segment length. Defaults to `None`. When specified, the + COLA constraint must be met (see Notes below), and should match + the parameter used to generate the STFT. Defaults to `None`. + nfft : int, optional + Number of FFT points corresponding to each STFT segment. This + parameter must be specified if the STFT was padded via ``nfft > + nperseg``. If `None`, the default values are the same as for + `nperseg`, detailed above, with one exception: if + `input_onesided` is True and + ``nperseg==2*Zxx.shape[freq_axis] - 1``, `nfft` also takes on + that value. This case allows the proper inversion of an + odd-length unpadded STFT using ``nfft=None``. Defaults to + `None`. + input_onesided : bool, optional + If `True`, interpret the input array as one-sided FFTs, such + as is returned by `stft` with ``return_onesided=True`` and + `numpy.fft.rfft`. If `False`, interpret the input as a a + two-sided FFT. Defaults to `True`. + boundary : bool, optional + Specifies whether the input signal was extended at its + boundaries by supplying a non-`None` ``boundary`` argument to + `stft`. Defaults to `True`. + time_axis : int, optional + Where the time segments of the STFT is located; the default is + the last axis (i.e. ``axis=-1``). + freq_axis : int, optional + Where the frequency axis of the STFT is located; the default is + the penultimate axis (i.e. ``axis=-2``). + scaling: {'spectrum', 'psd'} + The default 'spectrum' scaling allows each frequency line of `Zxx` to + be interpreted as a magnitude spectrum. The 'psd' option scales each + line to a power spectral density - it allows to calculate the signal's + energy by numerically integrating over ``abs(Zxx)**2``. + + Returns + ------- + t : ndarray + Array of output data times. + x : ndarray + iSTFT of `Zxx`. + + See Also + -------- + stft: Short Time Fourier Transform + ShortTimeFFT: Newer STFT/ISTFT implementation providing more features. + check_COLA: Check whether the Constant OverLap Add (COLA) constraint + is met + check_NOLA: Check whether the Nonzero Overlap Add (NOLA) constraint is met + + Notes + ----- + In order to enable inversion of an STFT via the inverse STFT with + `istft`, the signal windowing must obey the constraint of "nonzero + overlap add" (NOLA): + + .. math:: \sum_{t}w^{2}[n-tH] \ne 0 + + This ensures that the normalization factors that appear in the denominator + of the overlap-add reconstruction equation + + .. math:: x[n]=\frac{\sum_{t}x_{t}[n]w[n-tH]}{\sum_{t}w^{2}[n-tH]} + + are not zero. The NOLA constraint can be checked with the `check_NOLA` + function. + + An STFT which has been modified (via masking or otherwise) is not + guaranteed to correspond to a exactly realizible signal. This + function implements the iSTFT via the least-squares estimation + algorithm detailed in [2]_, which produces a signal that minimizes + the mean squared error between the STFT of the returned signal and + the modified STFT. + + + .. versionadded:: 0.19.0 + + References + ---------- + .. [1] Oppenheim, Alan V., Ronald W. Schafer, John R. Buck + "Discrete-Time Signal Processing", Prentice Hall, 1999. + .. [2] Daniel W. Griffin, Jae S. Lim "Signal Estimation from + Modified Short-Time Fourier Transform", IEEE 1984, + 10.1109/TASSP.1984.1164317 + + Examples + -------- + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> rng = np.random.default_rng() + + Generate a test signal, a 2 Vrms sine wave at 50Hz corrupted by + 0.001 V**2/Hz of white noise sampled at 1024 Hz. + + >>> fs = 1024 + >>> N = 10*fs + >>> nperseg = 512 + >>> amp = 2 * np.sqrt(2) + >>> noise_power = 0.001 * fs / 2 + >>> time = np.arange(N) / float(fs) + >>> carrier = amp * np.sin(2*np.pi*50*time) + >>> noise = rng.normal(scale=np.sqrt(noise_power), + ... size=time.shape) + >>> x = carrier + noise + + Compute the STFT, and plot its magnitude + + >>> f, t, Zxx = signal.stft(x, fs=fs, nperseg=nperseg) + >>> plt.figure() + >>> plt.pcolormesh(t, f, np.abs(Zxx), vmin=0, vmax=amp, shading='gouraud') + >>> plt.ylim([f[1], f[-1]]) + >>> plt.title('STFT Magnitude') + >>> plt.ylabel('Frequency [Hz]') + >>> plt.xlabel('Time [sec]') + >>> plt.yscale('log') + >>> plt.show() + + Zero the components that are 10% or less of the carrier magnitude, + then convert back to a time series via inverse STFT + + >>> Zxx = np.where(np.abs(Zxx) >= amp/10, Zxx, 0) + >>> _, xrec = signal.istft(Zxx, fs) + + Compare the cleaned signal with the original and true carrier signals. + + >>> plt.figure() + >>> plt.plot(time, x, time, xrec, time, carrier) + >>> plt.xlim([2, 2.1]) + >>> plt.xlabel('Time [sec]') + >>> plt.ylabel('Signal') + >>> plt.legend(['Carrier + Noise', 'Filtered via STFT', 'True Carrier']) + >>> plt.show() + + Note that the cleaned signal does not start as abruptly as the original, + since some of the coefficients of the transient were also removed: + + >>> plt.figure() + >>> plt.plot(time, x, time, xrec, time, carrier) + >>> plt.xlim([0, 0.1]) + >>> plt.xlabel('Time [sec]') + >>> plt.ylabel('Signal') + >>> plt.legend(['Carrier + Noise', 'Filtered via STFT', 'True Carrier']) + >>> plt.show() + + """ + # Make sure input is an ndarray of appropriate complex dtype + Zxx = np.asarray(Zxx) + 0j + freq_axis = int(freq_axis) + time_axis = int(time_axis) + + if Zxx.ndim < 2: + raise ValueError('Input stft must be at least 2d!') + + if freq_axis == time_axis: + raise ValueError('Must specify differing time and frequency axes!') + + nseg = Zxx.shape[time_axis] + + if input_onesided: + # Assume even segment length + n_default = 2*(Zxx.shape[freq_axis] - 1) + else: + n_default = Zxx.shape[freq_axis] + + # Check windowing parameters + if nperseg is None: + nperseg = n_default + else: + nperseg = int(nperseg) + if nperseg < 1: + raise ValueError('nperseg must be a positive integer') + + if nfft is None: + if (input_onesided) and (nperseg == n_default + 1): + # Odd nperseg, no FFT padding + nfft = nperseg + else: + nfft = n_default + elif nfft < nperseg: + raise ValueError('nfft must be greater than or equal to nperseg.') + else: + nfft = int(nfft) + + if noverlap is None: + noverlap = nperseg//2 + else: + noverlap = int(noverlap) + if noverlap >= nperseg: + raise ValueError('noverlap must be less than nperseg.') + nstep = nperseg - noverlap + + # Rearrange axes if necessary + if time_axis != Zxx.ndim-1 or freq_axis != Zxx.ndim-2: + # Turn negative indices to positive for the call to transpose + if freq_axis < 0: + freq_axis = Zxx.ndim + freq_axis + if time_axis < 0: + time_axis = Zxx.ndim + time_axis + zouter = list(range(Zxx.ndim)) + for ax in sorted([time_axis, freq_axis], reverse=True): + zouter.pop(ax) + Zxx = np.transpose(Zxx, zouter+[freq_axis, time_axis]) + + # Get window as array + if isinstance(window, str) or type(window) is tuple: + win = get_window(window, nperseg) + else: + win = np.asarray(window) + if len(win.shape) != 1: + raise ValueError('window must be 1-D') + if win.shape[0] != nperseg: + raise ValueError(f'window must have length of {nperseg}') + + ifunc = sp_fft.irfft if input_onesided else sp_fft.ifft + xsubs = ifunc(Zxx, axis=-2, n=nfft)[..., :nperseg, :] + + # Initialize output and normalization arrays + outputlength = nperseg + (nseg-1)*nstep + x = np.zeros(list(Zxx.shape[:-2])+[outputlength], dtype=xsubs.dtype) + norm = np.zeros(outputlength, dtype=xsubs.dtype) + + if np.result_type(win, xsubs) != xsubs.dtype: + win = win.astype(xsubs.dtype) + + if scaling == 'spectrum': + xsubs *= win.sum() + elif scaling == 'psd': + xsubs *= np.sqrt(fs * sum(win**2)) + else: + raise ValueError(f"Parameter {scaling=} not in ['spectrum', 'psd']!") + + # Construct the output from the ifft segments + # This loop could perhaps be vectorized/strided somehow... + for ii in range(nseg): + # Window the ifft + x[..., ii*nstep:ii*nstep+nperseg] += xsubs[..., ii] * win + norm[..., ii*nstep:ii*nstep+nperseg] += win**2 + + # Remove extension points + if boundary: + x = x[..., nperseg//2:-(nperseg//2)] + norm = norm[..., nperseg//2:-(nperseg//2)] + + # Divide out normalization where non-tiny + if np.sum(norm > 1e-10) != len(norm): + warnings.warn( + "NOLA condition failed, STFT may not be invertible." + + (" Possibly due to missing boundary" if not boundary else ""), + stacklevel=2 + ) + x /= np.where(norm > 1e-10, norm, 1.0) + + if input_onesided: + x = x.real + + # Put axes back + if x.ndim > 1: + if time_axis != Zxx.ndim-1: + if freq_axis < time_axis: + time_axis -= 1 + x = np.moveaxis(x, -1, time_axis) + + time = np.arange(x.shape[0])/float(fs) + return time, x + + +def coherence(x, y, fs=1.0, window='hann', nperseg=None, noverlap=None, + nfft=None, detrend='constant', axis=-1): + r""" + Estimate the magnitude squared coherence estimate, Cxy, of + discrete-time signals X and Y using Welch's method. + + ``Cxy = abs(Pxy)**2/(Pxx*Pyy)``, where `Pxx` and `Pyy` are power + spectral density estimates of X and Y, and `Pxy` is the cross + spectral density estimate of X and Y. + + Parameters + ---------- + x : array_like + Time series of measurement values + y : array_like + Time series of measurement values + fs : float, optional + Sampling frequency of the `x` and `y` time series. Defaults + to 1.0. + window : str or tuple or array_like, optional + Desired window to use. If `window` is a string or tuple, it is + passed to `get_window` to generate the window values, which are + DFT-even by default. See `get_window` for a list of windows and + required parameters. If `window` is array_like it will be used + directly as the window and its length must be nperseg. Defaults + to a Hann window. + nperseg : int, optional + Length of each segment. Defaults to None, but if window is str or + tuple, is set to 256, and if window is array_like, is set to the + length of the window. + noverlap: int, optional + Number of points to overlap between segments. If `None`, + ``noverlap = nperseg // 2``. Defaults to `None`. + nfft : int, optional + Length of the FFT used, if a zero padded FFT is desired. If + `None`, the FFT length is `nperseg`. Defaults to `None`. + detrend : str or function or `False`, optional + Specifies how to detrend each segment. If `detrend` is a + string, it is passed as the `type` argument to the `detrend` + function. If it is a function, it takes a segment and returns a + detrended segment. If `detrend` is `False`, no detrending is + done. Defaults to 'constant'. + axis : int, optional + Axis along which the coherence is computed for both inputs; the + default is over the last axis (i.e. ``axis=-1``). + + Returns + ------- + f : ndarray + Array of sample frequencies. + Cxy : ndarray + Magnitude squared coherence of x and y. + + See Also + -------- + periodogram: Simple, optionally modified periodogram + lombscargle: Lomb-Scargle periodogram for unevenly sampled data + welch: Power spectral density by Welch's method. + csd: Cross spectral density by Welch's method. + + Notes + ----- + An appropriate amount of overlap will depend on the choice of window + and on your requirements. For the default Hann window an overlap of + 50% is a reasonable trade off between accurately estimating the + signal power, while not over counting any of the data. Narrower + windows may require a larger overlap. + + .. versionadded:: 0.16.0 + + References + ---------- + .. [1] P. Welch, "The use of the fast Fourier transform for the + estimation of power spectra: A method based on time averaging + over short, modified periodograms", IEEE Trans. Audio + Electroacoust. vol. 15, pp. 70-73, 1967. + .. [2] Stoica, Petre, and Randolph Moses, "Spectral Analysis of + Signals" Prentice Hall, 2005 + + Examples + -------- + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> rng = np.random.default_rng() + + Generate two test signals with some common features. + + >>> fs = 10e3 + >>> N = 1e5 + >>> amp = 20 + >>> freq = 1234.0 + >>> noise_power = 0.001 * fs / 2 + >>> time = np.arange(N) / fs + >>> b, a = signal.butter(2, 0.25, 'low') + >>> x = rng.normal(scale=np.sqrt(noise_power), size=time.shape) + >>> y = signal.lfilter(b, a, x) + >>> x += amp*np.sin(2*np.pi*freq*time) + >>> y += rng.normal(scale=0.1*np.sqrt(noise_power), size=time.shape) + + Compute and plot the coherence. + + >>> f, Cxy = signal.coherence(x, y, fs, nperseg=1024) + >>> plt.semilogy(f, Cxy) + >>> plt.xlabel('frequency [Hz]') + >>> plt.ylabel('Coherence') + >>> plt.show() + + """ + freqs, Pxx = welch(x, fs=fs, window=window, nperseg=nperseg, + noverlap=noverlap, nfft=nfft, detrend=detrend, + axis=axis) + _, Pyy = welch(y, fs=fs, window=window, nperseg=nperseg, noverlap=noverlap, + nfft=nfft, detrend=detrend, axis=axis) + _, Pxy = csd(x, y, fs=fs, window=window, nperseg=nperseg, + noverlap=noverlap, nfft=nfft, detrend=detrend, axis=axis) + + Cxy = np.abs(Pxy)**2 / Pxx / Pyy + + return freqs, Cxy + + +def _spectral_helper(x, y, fs=1.0, window='hann', nperseg=None, noverlap=None, + nfft=None, detrend='constant', return_onesided=True, + scaling='density', axis=-1, mode='psd', boundary=None, + padded=False): + """Calculate various forms of windowed FFTs for PSD, CSD, etc. + + This is a helper function that implements the commonality between + the stft, psd, csd, and spectrogram functions. It is not designed to + be called externally. The windows are not averaged over; the result + from each window is returned. + + Parameters + ---------- + x : array_like + Array or sequence containing the data to be analyzed. + y : array_like + Array or sequence containing the data to be analyzed. If this is + the same object in memory as `x` (i.e. ``_spectral_helper(x, + x, ...)``), the extra computations are spared. + fs : float, optional + Sampling frequency of the time series. Defaults to 1.0. + window : str or tuple or array_like, optional + Desired window to use. If `window` is a string or tuple, it is + passed to `get_window` to generate the window values, which are + DFT-even by default. See `get_window` for a list of windows and + required parameters. If `window` is array_like it will be used + directly as the window and its length must be nperseg. Defaults + to a Hann window. + nperseg : int, optional + Length of each segment. Defaults to None, but if window is str or + tuple, is set to 256, and if window is array_like, is set to the + length of the window. + noverlap : int, optional + Number of points to overlap between segments. If `None`, + ``noverlap = nperseg // 2``. Defaults to `None`. + nfft : int, optional + Length of the FFT used, if a zero padded FFT is desired. If + `None`, the FFT length is `nperseg`. Defaults to `None`. + detrend : str or function or `False`, optional + Specifies how to detrend each segment. If `detrend` is a + string, it is passed as the `type` argument to the `detrend` + function. If it is a function, it takes a segment and returns a + detrended segment. If `detrend` is `False`, no detrending is + done. Defaults to 'constant'. + return_onesided : bool, optional + If `True`, return a one-sided spectrum for real data. If + `False` return a two-sided spectrum. Defaults to `True`, but for + complex data, a two-sided spectrum is always returned. + scaling : { 'density', 'spectrum' }, optional + Selects between computing the cross spectral density ('density') + where `Pxy` has units of V**2/Hz and computing the cross + spectrum ('spectrum') where `Pxy` has units of V**2, if `x` + and `y` are measured in V and `fs` is measured in Hz. + Defaults to 'density' + axis : int, optional + Axis along which the FFTs are computed; the default is over the + last axis (i.e. ``axis=-1``). + mode: str {'psd', 'stft'}, optional + Defines what kind of return values are expected. Defaults to + 'psd'. + boundary : str or None, optional + Specifies whether the input signal is extended at both ends, and + how to generate the new values, in order to center the first + windowed segment on the first input point. This has the benefit + of enabling reconstruction of the first input point when the + employed window function starts at zero. Valid options are + ``['even', 'odd', 'constant', 'zeros', None]``. Defaults to + `None`. + padded : bool, optional + Specifies whether the input signal is zero-padded at the end to + make the signal fit exactly into an integer number of window + segments, so that all of the signal is included in the output. + Defaults to `False`. Padding occurs after boundary extension, if + `boundary` is not `None`, and `padded` is `True`. + + Returns + ------- + freqs : ndarray + Array of sample frequencies. + t : ndarray + Array of times corresponding to each data segment + result : ndarray + Array of output data, contents dependent on *mode* kwarg. + + Notes + ----- + Adapted from matplotlib.mlab + + .. versionadded:: 0.16.0 + """ + if mode not in ['psd', 'stft']: + raise ValueError(f"Unknown value for mode {mode}, must be one of: " + "{'psd', 'stft'}") + + boundary_funcs = {'even': even_ext, + 'odd': odd_ext, + 'constant': const_ext, + 'zeros': zero_ext, + None: None} + + if boundary not in boundary_funcs: + raise ValueError(f"Unknown boundary option '{boundary}', " + f"must be one of: {list(boundary_funcs.keys())}") + + # If x and y are the same object we can save ourselves some computation. + same_data = y is x + + if not same_data and mode != 'psd': + raise ValueError("x and y must be equal if mode is 'stft'") + + axis = int(axis) + + # Ensure we have np.arrays, get outdtype + x = np.asarray(x) + if not same_data: + y = np.asarray(y) + outdtype = np.result_type(x, y, np.complex64) + else: + outdtype = np.result_type(x, np.complex64) + + if not same_data: + # Check if we can broadcast the outer axes together + xouter = list(x.shape) + youter = list(y.shape) + xouter.pop(axis) + youter.pop(axis) + try: + outershape = np.broadcast(np.empty(xouter), np.empty(youter)).shape + except ValueError as e: + raise ValueError('x and y cannot be broadcast together.') from e + + if same_data: + if x.size == 0: + return np.empty(x.shape), np.empty(x.shape), np.empty(x.shape) + else: + if x.size == 0 or y.size == 0: + outshape = outershape + (min([x.shape[axis], y.shape[axis]]),) + emptyout = np.moveaxis(np.empty(outshape), -1, axis) + return emptyout, emptyout, emptyout + + if x.ndim > 1: + if axis != -1: + x = np.moveaxis(x, axis, -1) + if not same_data and y.ndim > 1: + y = np.moveaxis(y, axis, -1) + + # Check if x and y are the same length, zero-pad if necessary + if not same_data: + if x.shape[-1] != y.shape[-1]: + if x.shape[-1] < y.shape[-1]: + pad_shape = list(x.shape) + pad_shape[-1] = y.shape[-1] - x.shape[-1] + x = np.concatenate((x, np.zeros(pad_shape)), -1) + else: + pad_shape = list(y.shape) + pad_shape[-1] = x.shape[-1] - y.shape[-1] + y = np.concatenate((y, np.zeros(pad_shape)), -1) + + if nperseg is not None: # if specified by user + nperseg = int(nperseg) + if nperseg < 1: + raise ValueError('nperseg must be a positive integer') + + # parse window; if array like, then set nperseg = win.shape + win, nperseg = _triage_segments(window, nperseg, input_length=x.shape[-1]) + + if nfft is None: + nfft = nperseg + elif nfft < nperseg: + raise ValueError('nfft must be greater than or equal to nperseg.') + else: + nfft = int(nfft) + + if noverlap is None: + noverlap = nperseg//2 + else: + noverlap = int(noverlap) + if noverlap >= nperseg: + raise ValueError('noverlap must be less than nperseg.') + nstep = nperseg - noverlap + + # Padding occurs after boundary extension, so that the extended signal ends + # in zeros, instead of introducing an impulse at the end. + # I.e. if x = [..., 3, 2] + # extend then pad -> [..., 3, 2, 2, 3, 0, 0, 0] + # pad then extend -> [..., 3, 2, 0, 0, 0, 2, 3] + + if boundary is not None: + ext_func = boundary_funcs[boundary] + x = ext_func(x, nperseg//2, axis=-1) + if not same_data: + y = ext_func(y, nperseg//2, axis=-1) + + if padded: + # Pad to integer number of windowed segments + # I.e. make x.shape[-1] = nperseg + (nseg-1)*nstep, with integer nseg + nadd = (-(x.shape[-1]-nperseg) % nstep) % nperseg + zeros_shape = list(x.shape[:-1]) + [nadd] + x = np.concatenate((x, np.zeros(zeros_shape)), axis=-1) + if not same_data: + zeros_shape = list(y.shape[:-1]) + [nadd] + y = np.concatenate((y, np.zeros(zeros_shape)), axis=-1) + + # Handle detrending and window functions + if not detrend: + def detrend_func(d): + return d + elif not hasattr(detrend, '__call__'): + def detrend_func(d): + return _signaltools.detrend(d, type=detrend, axis=-1) + elif axis != -1: + # Wrap this function so that it receives a shape that it could + # reasonably expect to receive. + def detrend_func(d): + d = np.moveaxis(d, -1, axis) + d = detrend(d) + return np.moveaxis(d, axis, -1) + else: + detrend_func = detrend + + if np.result_type(win, np.complex64) != outdtype: + win = win.astype(outdtype) + + if scaling == 'density': + scale = 1.0 / (fs * (win*win).sum()) + elif scaling == 'spectrum': + scale = 1.0 / win.sum()**2 + else: + raise ValueError(f'Unknown scaling: {scaling!r}') + + if mode == 'stft': + scale = np.sqrt(scale) + + if return_onesided: + if np.iscomplexobj(x): + sides = 'twosided' + warnings.warn('Input data is complex, switching to return_onesided=False', + stacklevel=3) + else: + sides = 'onesided' + if not same_data: + if np.iscomplexobj(y): + sides = 'twosided' + warnings.warn('Input data is complex, switching to ' + 'return_onesided=False', + stacklevel=3) + else: + sides = 'twosided' + + if sides == 'twosided': + freqs = sp_fft.fftfreq(nfft, 1/fs) + elif sides == 'onesided': + freqs = sp_fft.rfftfreq(nfft, 1/fs) + + # Perform the windowed FFTs + result = _fft_helper(x, win, detrend_func, nperseg, noverlap, nfft, sides) + + if not same_data: + # All the same operations on the y data + result_y = _fft_helper(y, win, detrend_func, nperseg, noverlap, nfft, + sides) + result = np.conjugate(result) * result_y + elif mode == 'psd': + result = np.conjugate(result) * result + + result *= scale + if sides == 'onesided' and mode == 'psd': + if nfft % 2: + result[..., 1:] *= 2 + else: + # Last point is unpaired Nyquist freq point, don't double + result[..., 1:-1] *= 2 + + time = np.arange(nperseg/2, x.shape[-1] - nperseg/2 + 1, + nperseg - noverlap)/float(fs) + if boundary is not None: + time -= (nperseg/2) / fs + + result = result.astype(outdtype) + + # All imaginary parts are zero anyways + if same_data and mode != 'stft': + result = result.real + + # Output is going to have new last axis for time/window index, so a + # negative axis index shifts down one + if axis < 0: + axis -= 1 + + # Roll frequency axis back to axis where the data came from + result = np.moveaxis(result, -1, axis) + + return freqs, time, result + + +def _fft_helper(x, win, detrend_func, nperseg, noverlap, nfft, sides): + """ + Calculate windowed FFT, for internal use by + `scipy.signal._spectral_helper`. + + This is a helper function that does the main FFT calculation for + `_spectral helper`. All input validation is performed there, and the + data axis is assumed to be the last axis of x. It is not designed to + be called externally. The windows are not averaged over; the result + from each window is returned. + + Returns + ------- + result : ndarray + Array of FFT data + + Notes + ----- + Adapted from matplotlib.mlab + + .. versionadded:: 0.16.0 + """ + # Created sliding window view of array + if nperseg == 1 and noverlap == 0: + result = x[..., np.newaxis] + else: + step = nperseg - noverlap + result = np.lib.stride_tricks.sliding_window_view( + x, window_shape=nperseg, axis=-1, writeable=True + ) + result = result[..., 0::step, :] + + # Detrend each data segment individually + result = detrend_func(result) + + # Apply window by multiplication + result = win * result + + # Perform the fft. Acts on last axis by default. Zero-pads automatically + if sides == 'twosided': + func = sp_fft.fft + else: + result = result.real + func = sp_fft.rfft + result = func(result, n=nfft) + + return result + + +def _triage_segments(window, nperseg, input_length): + """ + Parses window and nperseg arguments for spectrogram and _spectral_helper. + This is a helper function, not meant to be called externally. + + Parameters + ---------- + window : string, tuple, or ndarray + If window is specified by a string or tuple and nperseg is not + specified, nperseg is set to the default of 256 and returns a window of + that length. + If instead the window is array_like and nperseg is not specified, then + nperseg is set to the length of the window. A ValueError is raised if + the user supplies both an array_like window and a value for nperseg but + nperseg does not equal the length of the window. + + nperseg : int + Length of each segment + + input_length: int + Length of input signal, i.e. x.shape[-1]. Used to test for errors. + + Returns + ------- + win : ndarray + window. If function was called with string or tuple than this will hold + the actual array used as a window. + + nperseg : int + Length of each segment. If window is str or tuple, nperseg is set to + 256. If window is array_like, nperseg is set to the length of the + window. + """ + # parse window; if array like, then set nperseg = win.shape + if isinstance(window, str) or isinstance(window, tuple): + # if nperseg not specified + if nperseg is None: + nperseg = 256 # then change to default + if nperseg > input_length: + warnings.warn(f'nperseg = {nperseg:d} is greater than input length ' + f' = {input_length:d}, using nperseg = {input_length:d}', + stacklevel=3) + nperseg = input_length + win = get_window(window, nperseg) + else: + win = np.asarray(window) + if len(win.shape) != 1: + raise ValueError('window must be 1-D') + if input_length < win.shape[-1]: + raise ValueError('window is longer than input signal') + if nperseg is None: + nperseg = win.shape[0] + elif nperseg is not None: + if nperseg != win.shape[0]: + raise ValueError("value specified for nperseg is different" + " from length of window") + return win, nperseg + + +def _median_bias(n): + """ + Returns the bias of the median of a set of periodograms relative to + the mean. + + See Appendix B from [1]_ for details. + + Parameters + ---------- + n : int + Numbers of periodograms being averaged. + + Returns + ------- + bias : float + Calculated bias. + + References + ---------- + .. [1] B. Allen, W.G. Anderson, P.R. Brady, D.A. Brown, J.D.E. Creighton. + "FINDCHIRP: an algorithm for detection of gravitational waves from + inspiraling compact binaries", Physical Review D 85, 2012, + :arxiv:`gr-qc/0509116` + """ + ii_2 = 2 * np.arange(1., (n-1) // 2 + 1) + return 1 + np.sum(1. / (ii_2 + 1) - 1. / ii_2) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_spline.cpython-310-x86_64-linux-gnu.so b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_spline.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..c776c84deedabf62573fdee3f6b0bea1089d0092 Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_spline.cpython-310-x86_64-linux-gnu.so differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_spline.pyi b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_spline.pyi new file mode 100644 index 0000000000000000000000000000000000000000..c4225577db7ea188a2add225ecec1fbec855de06 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_spline.pyi @@ -0,0 +1,34 @@ + +import numpy as np +from numpy.typing import NDArray + +FloatingArray = NDArray[np.float32] | NDArray[np.float64] +ComplexArray = NDArray[np.complex64] | NDArray[np.complex128] +FloatingComplexArray = FloatingArray | ComplexArray + + +def symiirorder1_ic(signal: FloatingComplexArray, + c0: float, + z1: float, + precision: float) -> FloatingComplexArray: + ... + + +def symiirorder2_ic_fwd(signal: FloatingArray, + r: float, + omega: float, + precision: float) -> FloatingArray: + ... + + +def symiirorder2_ic_bwd(signal: FloatingArray, + r: float, + omega: float, + precision: float) -> FloatingArray: + ... + + +def sepfir2d(input: FloatingComplexArray, + hrow: FloatingComplexArray, + hcol: FloatingComplexArray) -> FloatingComplexArray: + ... diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_spline_filters.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_spline_filters.py new file mode 100644 index 0000000000000000000000000000000000000000..eb7884c5cc5544e9fc6d37476016e7a2d0e81d57 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_spline_filters.py @@ -0,0 +1,808 @@ +from numpy import (asarray, pi, zeros_like, + array, arctan2, tan, ones, arange, floor, + r_, atleast_1d, sqrt, exp, greater, cos, add, sin, + moveaxis, abs, arctan, complex64, float32) +import numpy as np + +from scipy._lib._util import normalize_axis_index + +# From splinemodule.c +from ._spline import sepfir2d, symiirorder1_ic, symiirorder2_ic_fwd, symiirorder2_ic_bwd +from ._signaltools import lfilter, sosfilt, lfiltic +from ._arraytools import axis_slice, axis_reverse + +from scipy.interpolate import BSpline + + +__all__ = ['spline_filter', 'gauss_spline', + 'cspline1d', 'qspline1d', 'qspline2d', 'cspline2d', + 'cspline1d_eval', 'qspline1d_eval', 'symiirorder1', 'symiirorder2'] + + +def spline_filter(Iin, lmbda=5.0): + """Smoothing spline (cubic) filtering of a rank-2 array. + + Filter an input data set, `Iin`, using a (cubic) smoothing spline of + fall-off `lmbda`. + + Parameters + ---------- + Iin : array_like + input data set + lmbda : float, optional + spline smoothing fall-off value, default is `5.0`. + + Returns + ------- + res : ndarray + filtered input data + + Examples + -------- + We can filter an multi dimensional signal (ex: 2D image) using cubic + B-spline filter: + + >>> import numpy as np + >>> from scipy.signal import spline_filter + >>> import matplotlib.pyplot as plt + >>> orig_img = np.eye(20) # create an image + >>> orig_img[10, :] = 1.0 + >>> sp_filter = spline_filter(orig_img, lmbda=0.1) + >>> f, ax = plt.subplots(1, 2, sharex=True) + >>> for ind, data in enumerate([[orig_img, "original image"], + ... [sp_filter, "spline filter"]]): + ... ax[ind].imshow(data[0], cmap='gray_r') + ... ax[ind].set_title(data[1]) + >>> plt.tight_layout() + >>> plt.show() + + """ + if Iin.dtype not in [np.float32, np.float64, np.complex64, np.complex128]: + raise TypeError(f"Invalid data type for Iin: {Iin.dtype = }") + + # XXX: note that complex-valued computations are done in single precision + # this is historic, and the root reason is unclear, + # see https://github.com/scipy/scipy/issues/9209 + # Attempting to work in complex double precision leads to symiirorder1 + # failing to converge for the boundary conditions. + intype = Iin.dtype + hcol = array([1.0, 4.0, 1.0], np.float32) / 6.0 + if intype == np.complex128: + Iin = Iin.astype(np.complex64) + + ck = cspline2d(Iin, lmbda) + out = sepfir2d(ck, hcol, hcol) + out = out.astype(intype) + return out + + +_splinefunc_cache = {} + + +def gauss_spline(x, n): + r"""Gaussian approximation to B-spline basis function of order n. + + Parameters + ---------- + x : array_like + a knot vector + n : int + The order of the spline. Must be non-negative, i.e., n >= 0 + + Returns + ------- + res : ndarray + B-spline basis function values approximated by a zero-mean Gaussian + function. + + Notes + ----- + The B-spline basis function can be approximated well by a zero-mean + Gaussian function with standard-deviation equal to :math:`\sigma=(n+1)/12` + for large `n` : + + .. math:: \frac{1}{\sqrt {2\pi\sigma^2}}exp(-\frac{x^2}{2\sigma}) + + References + ---------- + .. [1] Bouma H., Vilanova A., Bescos J.O., ter Haar Romeny B.M., Gerritsen + F.A. (2007) Fast and Accurate Gaussian Derivatives Based on B-Splines. In: + Sgallari F., Murli A., Paragios N. (eds) Scale Space and Variational + Methods in Computer Vision. SSVM 2007. Lecture Notes in Computer + Science, vol 4485. Springer, Berlin, Heidelberg + .. [2] http://folk.uio.no/inf3330/scripting/doc/python/SciPy/tutorial/old/node24.html + + Examples + -------- + We can calculate B-Spline basis functions approximated by a gaussian + distribution: + + >>> import numpy as np + >>> from scipy.signal import gauss_spline + >>> knots = np.array([-1.0, 0.0, -1.0]) + >>> gauss_spline(knots, 3) + array([0.15418033, 0.6909883, 0.15418033]) # may vary + + """ + x = asarray(x) + signsq = (n + 1) / 12.0 + return 1 / sqrt(2 * pi * signsq) * exp(-x ** 2 / 2 / signsq) + + +def _cubic(x): + x = asarray(x, dtype=float) + b = BSpline.basis_element([-2, -1, 0, 1, 2], extrapolate=False) + out = b(x) + out[(x < -2) | (x > 2)] = 0 + return out + + +def _quadratic(x): + x = abs(asarray(x, dtype=float)) + b = BSpline.basis_element([-1.5, -0.5, 0.5, 1.5], extrapolate=False) + out = b(x) + out[(x < -1.5) | (x > 1.5)] = 0 + return out + + +def _coeff_smooth(lam): + xi = 1 - 96 * lam + 24 * lam * sqrt(3 + 144 * lam) + omeg = arctan2(sqrt(144 * lam - 1), sqrt(xi)) + rho = (24 * lam - 1 - sqrt(xi)) / (24 * lam) + rho = rho * sqrt((48 * lam + 24 * lam * sqrt(3 + 144 * lam)) / xi) + return rho, omeg + + +def _hc(k, cs, rho, omega): + return (cs / sin(omega) * (rho ** k) * sin(omega * (k + 1)) * + greater(k, -1)) + + +def _hs(k, cs, rho, omega): + c0 = (cs * cs * (1 + rho * rho) / (1 - rho * rho) / + (1 - 2 * rho * rho * cos(2 * omega) + rho ** 4)) + gamma = (1 - rho * rho) / (1 + rho * rho) / tan(omega) + ak = abs(k) + return c0 * rho ** ak * (cos(omega * ak) + gamma * sin(omega * ak)) + + +def _cubic_smooth_coeff(signal, lamb): + rho, omega = _coeff_smooth(lamb) + cs = 1 - 2 * rho * cos(omega) + rho * rho + K = len(signal) + k = arange(K) + + zi_2 = (_hc(0, cs, rho, omega) * signal[0] + + add.reduce(_hc(k + 1, cs, rho, omega) * signal)) + zi_1 = (_hc(0, cs, rho, omega) * signal[0] + + _hc(1, cs, rho, omega) * signal[1] + + add.reduce(_hc(k + 2, cs, rho, omega) * signal)) + + # Forward filter: + # for n in range(2, K): + # yp[n] = (cs * signal[n] + 2 * rho * cos(omega) * yp[n - 1] - + # rho * rho * yp[n - 2]) + zi = lfiltic(cs, r_[1, -2 * rho * cos(omega), rho * rho], r_[zi_1, zi_2]) + zi = zi.reshape(1, -1) + + sos = r_[cs, 0, 0, 1, -2 * rho * cos(omega), rho * rho] + sos = sos.reshape(1, -1) + + yp, _ = sosfilt(sos, signal[2:], zi=zi) + yp = r_[zi_2, zi_1, yp] + + # Reverse filter: + # for n in range(K - 3, -1, -1): + # y[n] = (cs * yp[n] + 2 * rho * cos(omega) * y[n + 1] - + # rho * rho * y[n + 2]) + + zi_2 = add.reduce((_hs(k, cs, rho, omega) + + _hs(k + 1, cs, rho, omega)) * signal[::-1]) + zi_1 = add.reduce((_hs(k - 1, cs, rho, omega) + + _hs(k + 2, cs, rho, omega)) * signal[::-1]) + + zi = lfiltic(cs, r_[1, -2 * rho * cos(omega), rho * rho], r_[zi_1, zi_2]) + zi = zi.reshape(1, -1) + y, _ = sosfilt(sos, yp[-3::-1], zi=zi) + y = r_[y[::-1], zi_1, zi_2] + return y + + +def _cubic_coeff(signal): + zi = -2 + sqrt(3) + K = len(signal) + powers = zi ** arange(K) + + if K == 1: + yplus = signal[0] + zi * add.reduce(powers * signal) + output = zi / (zi - 1) * yplus + return atleast_1d(output) + + # Forward filter: + # yplus[0] = signal[0] + zi * add.reduce(powers * signal) + # for k in range(1, K): + # yplus[k] = signal[k] + zi * yplus[k - 1] + + state = lfiltic(1, r_[1, -zi], atleast_1d(add.reduce(powers * signal))) + + b = ones(1) + a = r_[1, -zi] + yplus, _ = lfilter(b, a, signal, zi=state) + + # Reverse filter: + # output[K - 1] = zi / (zi - 1) * yplus[K - 1] + # for k in range(K - 2, -1, -1): + # output[k] = zi * (output[k + 1] - yplus[k]) + out_last = zi / (zi - 1) * yplus[K - 1] + state = lfiltic(-zi, r_[1, -zi], atleast_1d(out_last)) + + b = asarray([-zi]) + output, _ = lfilter(b, a, yplus[-2::-1], zi=state) + output = r_[output[::-1], out_last] + return output * 6.0 + + +def _quadratic_coeff(signal): + zi = -3 + 2 * sqrt(2.0) + K = len(signal) + powers = zi ** arange(K) + + if K == 1: + yplus = signal[0] + zi * add.reduce(powers * signal) + output = zi / (zi - 1) * yplus + return atleast_1d(output) + + # Forward filter: + # yplus[0] = signal[0] + zi * add.reduce(powers * signal) + # for k in range(1, K): + # yplus[k] = signal[k] + zi * yplus[k - 1] + + state = lfiltic(1, r_[1, -zi], atleast_1d(add.reduce(powers * signal))) + + b = ones(1) + a = r_[1, -zi] + yplus, _ = lfilter(b, a, signal, zi=state) + + # Reverse filter: + # output[K - 1] = zi / (zi - 1) * yplus[K - 1] + # for k in range(K - 2, -1, -1): + # output[k] = zi * (output[k + 1] - yplus[k]) + out_last = zi / (zi - 1) * yplus[K - 1] + state = lfiltic(-zi, r_[1, -zi], atleast_1d(out_last)) + + b = asarray([-zi]) + output, _ = lfilter(b, a, yplus[-2::-1], zi=state) + output = r_[output[::-1], out_last] + return output * 8.0 + + +def compute_root_from_lambda(lamb): + tmp = sqrt(3 + 144 * lamb) + xi = 1 - 96 * lamb + 24 * lamb * tmp + omega = arctan(sqrt((144 * lamb - 1.0) / xi)) + tmp2 = sqrt(xi) + r = ((24 * lamb - 1 - tmp2) / (24 * lamb) * + sqrt(48*lamb + 24 * lamb * tmp) / tmp2) + return r, omega + + +def cspline1d(signal, lamb=0.0): + """ + Compute cubic spline coefficients for rank-1 array. + + Find the cubic spline coefficients for a 1-D signal assuming + mirror-symmetric boundary conditions. To obtain the signal back from the + spline representation mirror-symmetric-convolve these coefficients with a + length 3 FIR window [1.0, 4.0, 1.0]/ 6.0 . + + Parameters + ---------- + signal : ndarray + A rank-1 array representing samples of a signal. + lamb : float, optional + Smoothing coefficient, default is 0.0. + + Returns + ------- + c : ndarray + Cubic spline coefficients. + + See Also + -------- + cspline1d_eval : Evaluate a cubic spline at the new set of points. + + Examples + -------- + We can filter a signal to reduce and smooth out high-frequency noise with + a cubic spline: + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.signal import cspline1d, cspline1d_eval + >>> rng = np.random.default_rng() + >>> sig = np.repeat([0., 1., 0.], 100) + >>> sig += rng.standard_normal(len(sig))*0.05 # add noise + >>> time = np.linspace(0, len(sig)) + >>> filtered = cspline1d_eval(cspline1d(sig), time) + >>> plt.plot(sig, label="signal") + >>> plt.plot(time, filtered, label="filtered") + >>> plt.legend() + >>> plt.show() + + """ + if lamb != 0.0: + return _cubic_smooth_coeff(signal, lamb) + else: + return _cubic_coeff(signal) + + +def qspline1d(signal, lamb=0.0): + """Compute quadratic spline coefficients for rank-1 array. + + Parameters + ---------- + signal : ndarray + A rank-1 array representing samples of a signal. + lamb : float, optional + Smoothing coefficient (must be zero for now). + + Returns + ------- + c : ndarray + Quadratic spline coefficients. + + See Also + -------- + qspline1d_eval : Evaluate a quadratic spline at the new set of points. + + Notes + ----- + Find the quadratic spline coefficients for a 1-D signal assuming + mirror-symmetric boundary conditions. To obtain the signal back from the + spline representation mirror-symmetric-convolve these coefficients with a + length 3 FIR window [1.0, 6.0, 1.0]/ 8.0 . + + Examples + -------- + We can filter a signal to reduce and smooth out high-frequency noise with + a quadratic spline: + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.signal import qspline1d, qspline1d_eval + >>> rng = np.random.default_rng() + >>> sig = np.repeat([0., 1., 0.], 100) + >>> sig += rng.standard_normal(len(sig))*0.05 # add noise + >>> time = np.linspace(0, len(sig)) + >>> filtered = qspline1d_eval(qspline1d(sig), time) + >>> plt.plot(sig, label="signal") + >>> plt.plot(time, filtered, label="filtered") + >>> plt.legend() + >>> plt.show() + + """ + if lamb != 0.0: + raise ValueError("Smoothing quadratic splines not supported yet.") + else: + return _quadratic_coeff(signal) + + +def collapse_2d(x, axis): + x = moveaxis(x, axis, -1) + x_shape = x.shape + x = x.reshape(-1, x.shape[-1]) + if not x.flags.c_contiguous: + x = x.copy() + return x, x_shape + + +def symiirorder_nd(func, input, *args, axis=-1, **kwargs): + axis = normalize_axis_index(axis, input.ndim) + input_shape = input.shape + input_ndim = input.ndim + if input.ndim > 1: + input, input_shape = collapse_2d(input, axis) + + out = func(input, *args, **kwargs) + + if input_ndim > 1: + out = out.reshape(input_shape) + out = moveaxis(out, -1, axis) + if not out.flags.c_contiguous: + out = out.copy() + return out + + +def qspline2d(signal, lamb=0.0, precision=-1.0): + """ + Coefficients for 2-D quadratic (2nd order) B-spline. + + Return the second-order B-spline coefficients over a regularly spaced + input grid for the two-dimensional input image. + + Parameters + ---------- + input : ndarray + The input signal. + lamb : float + Specifies the amount of smoothing in the transfer function. + precision : float + Specifies the precision for computing the infinite sum needed to apply + mirror-symmetric boundary conditions. + + Returns + ------- + output : ndarray + The filtered signal. + """ + if precision < 0.0 or precision >= 1.0: + if signal.dtype in [float32, complex64]: + precision = 1e-3 + else: + precision = 1e-6 + + if lamb > 0: + raise ValueError('lambda must be negative or zero') + + # normal quadratic spline + r = -3 + 2 * sqrt(2.0) + c0 = -r * 8.0 + z1 = r + + out = symiirorder_nd(symiirorder1, signal, c0, z1, precision, axis=-1) + out = symiirorder_nd(symiirorder1, out, c0, z1, precision, axis=0) + return out + + +def cspline2d(signal, lamb=0.0, precision=-1.0): + """ + Coefficients for 2-D cubic (3rd order) B-spline. + + Return the third-order B-spline coefficients over a regularly spaced + input grid for the two-dimensional input image. + + Parameters + ---------- + input : ndarray + The input signal. + lamb : float + Specifies the amount of smoothing in the transfer function. + precision : float + Specifies the precision for computing the infinite sum needed to apply + mirror-symmetric boundary conditions. + + Returns + ------- + output : ndarray + The filtered signal. + """ + if precision < 0.0 or precision >= 1.0: + if signal.dtype in [float32, complex64]: + precision = 1e-3 + else: + precision = 1e-6 + + if lamb <= 1 / 144.0: + # Normal cubic spline + r = -2 + sqrt(3.0) + out = symiirorder_nd( + symiirorder1, signal, -r * 6.0, r, precision=precision, axis=-1) + out = symiirorder_nd( + symiirorder1, out, -r * 6.0, r, precision=precision, axis=0) + return out + + r, omega = compute_root_from_lambda(lamb) + out = symiirorder_nd(symiirorder2, signal, r, omega, + precision=precision, axis=-1) + out = symiirorder_nd(symiirorder2, out, r, omega, + precision=precision, axis=0) + return out + + +def cspline1d_eval(cj, newx, dx=1.0, x0=0): + """Evaluate a cubic spline at the new set of points. + + `dx` is the old sample-spacing while `x0` was the old origin. In + other-words the old-sample points (knot-points) for which the `cj` + represent spline coefficients were at equally-spaced points of: + + oldx = x0 + j*dx j=0...N-1, with N=len(cj) + + Edges are handled using mirror-symmetric boundary conditions. + + Parameters + ---------- + cj : ndarray + cublic spline coefficients + newx : ndarray + New set of points. + dx : float, optional + Old sample-spacing, the default value is 1.0. + x0 : int, optional + Old origin, the default value is 0. + + Returns + ------- + res : ndarray + Evaluated a cubic spline points. + + See Also + -------- + cspline1d : Compute cubic spline coefficients for rank-1 array. + + Examples + -------- + We can filter a signal to reduce and smooth out high-frequency noise with + a cubic spline: + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.signal import cspline1d, cspline1d_eval + >>> rng = np.random.default_rng() + >>> sig = np.repeat([0., 1., 0.], 100) + >>> sig += rng.standard_normal(len(sig))*0.05 # add noise + >>> time = np.linspace(0, len(sig)) + >>> filtered = cspline1d_eval(cspline1d(sig), time) + >>> plt.plot(sig, label="signal") + >>> plt.plot(time, filtered, label="filtered") + >>> plt.legend() + >>> plt.show() + + """ + newx = (asarray(newx) - x0) / float(dx) + res = zeros_like(newx, dtype=cj.dtype) + if res.size == 0: + return res + N = len(cj) + cond1 = newx < 0 + cond2 = newx > (N - 1) + cond3 = ~(cond1 | cond2) + # handle general mirror-symmetry + res[cond1] = cspline1d_eval(cj, -newx[cond1]) + res[cond2] = cspline1d_eval(cj, 2 * (N - 1) - newx[cond2]) + newx = newx[cond3] + if newx.size == 0: + return res + result = zeros_like(newx, dtype=cj.dtype) + jlower = floor(newx - 2).astype(int) + 1 + for i in range(4): + thisj = jlower + i + indj = thisj.clip(0, N - 1) # handle edge cases + result += cj[indj] * _cubic(newx - thisj) + res[cond3] = result + return res + + +def qspline1d_eval(cj, newx, dx=1.0, x0=0): + """Evaluate a quadratic spline at the new set of points. + + Parameters + ---------- + cj : ndarray + Quadratic spline coefficients + newx : ndarray + New set of points. + dx : float, optional + Old sample-spacing, the default value is 1.0. + x0 : int, optional + Old origin, the default value is 0. + + Returns + ------- + res : ndarray + Evaluated a quadratic spline points. + + See Also + -------- + qspline1d : Compute quadratic spline coefficients for rank-1 array. + + Notes + ----- + `dx` is the old sample-spacing while `x0` was the old origin. In + other-words the old-sample points (knot-points) for which the `cj` + represent spline coefficients were at equally-spaced points of:: + + oldx = x0 + j*dx j=0...N-1, with N=len(cj) + + Edges are handled using mirror-symmetric boundary conditions. + + Examples + -------- + We can filter a signal to reduce and smooth out high-frequency noise with + a quadratic spline: + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.signal import qspline1d, qspline1d_eval + >>> rng = np.random.default_rng() + >>> sig = np.repeat([0., 1., 0.], 100) + >>> sig += rng.standard_normal(len(sig))*0.05 # add noise + >>> time = np.linspace(0, len(sig)) + >>> filtered = qspline1d_eval(qspline1d(sig), time) + >>> plt.plot(sig, label="signal") + >>> plt.plot(time, filtered, label="filtered") + >>> plt.legend() + >>> plt.show() + + """ + newx = (asarray(newx) - x0) / dx + res = zeros_like(newx) + if res.size == 0: + return res + N = len(cj) + cond1 = newx < 0 + cond2 = newx > (N - 1) + cond3 = ~(cond1 | cond2) + # handle general mirror-symmetry + res[cond1] = qspline1d_eval(cj, -newx[cond1]) + res[cond2] = qspline1d_eval(cj, 2 * (N - 1) - newx[cond2]) + newx = newx[cond3] + if newx.size == 0: + return res + result = zeros_like(newx) + jlower = floor(newx - 1.5).astype(int) + 1 + for i in range(3): + thisj = jlower + i + indj = thisj.clip(0, N - 1) # handle edge cases + result += cj[indj] * _quadratic(newx - thisj) + res[cond3] = result + return res + + +def symiirorder1(signal, c0, z1, precision=-1.0): + """ + Implement a smoothing IIR filter with mirror-symmetric boundary conditions + using a cascade of first-order sections. + + The second section uses a reversed sequence. This implements a system with + the following transfer function and mirror-symmetric boundary conditions:: + + c0 + H(z) = --------------------- + (1-z1/z) (1 - z1 z) + + The resulting signal will have mirror symmetric boundary conditions + as well. + + Parameters + ---------- + signal : ndarray + The input signal. If 2D, then the filter will be applied in a batched + fashion across the last axis. + c0, z1 : scalar + Parameters in the transfer function. + precision : + Specifies the precision for calculating initial conditions + of the recursive filter based on mirror-symmetric input. + + Returns + ------- + output : ndarray + The filtered signal. + """ + if np.abs(z1) >= 1: + raise ValueError('|z1| must be less than 1.0') + + if signal.ndim > 2: + raise ValueError('Input must be 1D or 2D') + + squeeze_dim = False + if signal.ndim == 1: + signal = signal[None, :] + squeeze_dim = True + + if np.issubdtype(signal.dtype, np.integer): + signal = signal.astype(np.promote_types(signal.dtype, np.float32)) + + y0 = symiirorder1_ic(signal, z1, precision) + + # Apply first the system 1 / (1 - z1 * z^-1) + b = np.ones(1, dtype=signal.dtype) + a = np.r_[1, -z1] + a = a.astype(signal.dtype) + + # Compute the initial state for lfilter. + zii = y0 * z1 + + y1, _ = lfilter(b, a, axis_slice(signal, 1), zi=zii) + y1 = np.c_[y0, y1] + + # Compute backward symmetric condition and apply the system + # c0 / (1 - z1 * z) + b = np.asarray([c0], dtype=signal.dtype) + out_last = -c0 / (z1 - 1.0) * axis_slice(y1, -1) + + # Compute the initial state for lfilter. + zii = out_last * z1 + + # Apply the system c0 / (1 - z1 * z) by reversing the output of the previous stage + out, _ = lfilter(b, a, axis_slice(y1, -2, step=-1), zi=zii) + out = np.c_[axis_reverse(out), out_last] + + if squeeze_dim: + out = out[0] + + return out + + +def symiirorder2(input, r, omega, precision=-1.0): + """ + Implement a smoothing IIR filter with mirror-symmetric boundary conditions + using a cascade of second-order sections. + + The second section uses a reversed sequence. This implements the following + transfer function:: + + cs^2 + H(z) = --------------------------------------- + (1 - a2/z - a3/z^2) (1 - a2 z - a3 z^2 ) + + where:: + + a2 = 2 * r * cos(omega) + a3 = - r ** 2 + cs = 1 - 2 * r * cos(omega) + r ** 2 + + Parameters + ---------- + input : ndarray + The input signal. + r, omega : float + Parameters in the transfer function. + precision : float + Specifies the precision for calculating initial conditions + of the recursive filter based on mirror-symmetric input. + + Returns + ------- + output : ndarray + The filtered signal. + """ + if r >= 1.0: + raise ValueError('r must be less than 1.0') + + if input.ndim > 2: + raise ValueError('Input must be 1D or 2D') + + if not input.flags.c_contiguous: + input = input.copy() + + squeeze_dim = False + if input.ndim == 1: + input = input[None, :] + squeeze_dim = True + + if np.issubdtype(input.dtype, np.integer): + input = input.astype(np.promote_types(input.dtype, np.float32)) + + rsq = r * r + a2 = 2 * r * np.cos(omega) + a3 = -rsq + cs = np.atleast_1d(1 - 2 * r * np.cos(omega) + rsq) + sos = np.atleast_2d(np.r_[cs, 0, 0, 1, -a2, -a3]).astype(input.dtype) + + # Find the starting (forward) conditions. + ic_fwd = symiirorder2_ic_fwd(input, r, omega, precision) + + # Apply first the system cs / (1 - a2 * z^-1 - a3 * z^-2) + # Compute the initial conditions in the form expected by sosfilt + # coef = np.asarray([[a3, a2], [0, a3]], dtype=input.dtype) + coef = np.r_[a3, a2, 0, a3].reshape(2, 2).astype(input.dtype) + zi = np.matmul(coef, ic_fwd[:, :, None])[:, :, 0] + + y_fwd, _ = sosfilt(sos, axis_slice(input, 2), zi=zi[None]) + y_fwd = np.c_[ic_fwd, y_fwd] + + # Then compute the symmetric backward starting conditions + ic_bwd = symiirorder2_ic_bwd(input, r, omega, precision) + + # Apply the system cs / (1 - a2 * z^1 - a3 * z^2) + # Compute the initial conditions in the form expected by sosfilt + zi = np.matmul(coef, ic_bwd[:, :, None])[:, :, 0] + y, _ = sosfilt(sos, axis_slice(y_fwd, -3, step=-1), zi=zi[None]) + out = np.c_[axis_reverse(y), axis_reverse(ic_bwd)] + + if squeeze_dim: + out = out[0] + + return out diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_upfirdn.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_upfirdn.py new file mode 100644 index 0000000000000000000000000000000000000000..d64cc142ff194b1404e380507289ddbaffab3359 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_upfirdn.py @@ -0,0 +1,216 @@ +# Code adapted from "upfirdn" python library with permission: +# +# Copyright (c) 2009, Motorola, Inc +# +# All Rights Reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# * Neither the name of Motorola nor the names of its contributors may be +# used to endorse or promote products derived from this software without +# specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import numpy as np + +from ._upfirdn_apply import _output_len, _apply, mode_enum + +__all__ = ['upfirdn', '_output_len'] + +_upfirdn_modes = [ + 'constant', 'wrap', 'edge', 'smooth', 'symmetric', 'reflect', + 'antisymmetric', 'antireflect', 'line', +] + + +def _pad_h(h, up): + """Store coefficients in a transposed, flipped arrangement. + + For example, suppose upRate is 3, and the + input number of coefficients is 10, represented as h[0], ..., h[9]. + + Then the internal buffer will look like this:: + + h[9], h[6], h[3], h[0], // flipped phase 0 coefs + 0, h[7], h[4], h[1], // flipped phase 1 coefs (zero-padded) + 0, h[8], h[5], h[2], // flipped phase 2 coefs (zero-padded) + + """ + h_padlen = len(h) + (-len(h) % up) + h_full = np.zeros(h_padlen, h.dtype) + h_full[:len(h)] = h + h_full = h_full.reshape(-1, up).T[:, ::-1].ravel() + return h_full + + +def _check_mode(mode): + mode = mode.lower() + enum = mode_enum(mode) + return enum + + +class _UpFIRDn: + """Helper for resampling.""" + + def __init__(self, h, x_dtype, up, down): + h = np.asarray(h) + if h.ndim != 1 or h.size == 0: + raise ValueError('h must be 1-D with non-zero length') + self._output_type = np.result_type(h.dtype, x_dtype, np.float32) + h = np.asarray(h, self._output_type) + self._up = int(up) + self._down = int(down) + if self._up < 1 or self._down < 1: + raise ValueError('Both up and down must be >= 1') + # This both transposes, and "flips" each phase for filtering + self._h_trans_flip = _pad_h(h, self._up) + self._h_trans_flip = np.ascontiguousarray(self._h_trans_flip) + self._h_len_orig = len(h) + + def apply_filter(self, x, axis=-1, mode='constant', cval=0): + """Apply the prepared filter to the specified axis of N-D signal x.""" + output_len = _output_len(self._h_len_orig, x.shape[axis], + self._up, self._down) + # Explicit use of np.int64 for output_shape dtype avoids OverflowError + # when allocating large array on platforms where intp is 32 bits. + output_shape = np.asarray(x.shape, dtype=np.int64) + output_shape[axis] = output_len + out = np.zeros(output_shape, dtype=self._output_type, order='C') + axis = axis % x.ndim + mode = _check_mode(mode) + _apply(np.asarray(x, self._output_type), + self._h_trans_flip, out, + self._up, self._down, axis, mode, cval) + return out + + +def upfirdn(h, x, up=1, down=1, axis=-1, mode='constant', cval=0): + """Upsample, FIR filter, and downsample. + + Parameters + ---------- + h : array_like + 1-D FIR (finite-impulse response) filter coefficients. + x : array_like + Input signal array. + up : int, optional + Upsampling rate. Default is 1. + down : int, optional + Downsampling rate. Default is 1. + axis : int, optional + The axis of the input data array along which to apply the + linear filter. The filter is applied to each subarray along + this axis. Default is -1. + mode : str, optional + The signal extension mode to use. The set + ``{"constant", "symmetric", "reflect", "edge", "wrap"}`` correspond to + modes provided by `numpy.pad`. ``"smooth"`` implements a smooth + extension by extending based on the slope of the last 2 points at each + end of the array. ``"antireflect"`` and ``"antisymmetric"`` are + anti-symmetric versions of ``"reflect"`` and ``"symmetric"``. The mode + `"line"` extends the signal based on a linear trend defined by the + first and last points along the ``axis``. + + .. versionadded:: 1.4.0 + cval : float, optional + The constant value to use when ``mode == "constant"``. + + .. versionadded:: 1.4.0 + + Returns + ------- + y : ndarray + The output signal array. Dimensions will be the same as `x` except + for along `axis`, which will change size according to the `h`, + `up`, and `down` parameters. + + Notes + ----- + The algorithm is an implementation of the block diagram shown on page 129 + of the Vaidyanathan text [1]_ (Figure 4.3-8d). + + The direct approach of upsampling by factor of P with zero insertion, + FIR filtering of length ``N``, and downsampling by factor of Q is + O(N*Q) per output sample. The polyphase implementation used here is + O(N/P). + + .. versionadded:: 0.18 + + References + ---------- + .. [1] P. P. Vaidyanathan, Multirate Systems and Filter Banks, + Prentice Hall, 1993. + + Examples + -------- + Simple operations: + + >>> import numpy as np + >>> from scipy.signal import upfirdn + >>> upfirdn([1, 1, 1], [1, 1, 1]) # FIR filter + array([ 1., 2., 3., 2., 1.]) + >>> upfirdn([1], [1, 2, 3], 3) # upsampling with zeros insertion + array([ 1., 0., 0., 2., 0., 0., 3.]) + >>> upfirdn([1, 1, 1], [1, 2, 3], 3) # upsampling with sample-and-hold + array([ 1., 1., 1., 2., 2., 2., 3., 3., 3.]) + >>> upfirdn([.5, 1, .5], [1, 1, 1], 2) # linear interpolation + array([ 0.5, 1. , 1. , 1. , 1. , 1. , 0.5]) + >>> upfirdn([1], np.arange(10), 1, 3) # decimation by 3 + array([ 0., 3., 6., 9.]) + >>> upfirdn([.5, 1, .5], np.arange(10), 2, 3) # linear interp, rate 2/3 + array([ 0. , 1. , 2.5, 4. , 5.5, 7. , 8.5]) + + Apply a single filter to multiple signals: + + >>> x = np.reshape(np.arange(8), (4, 2)) + >>> x + array([[0, 1], + [2, 3], + [4, 5], + [6, 7]]) + + Apply along the last dimension of ``x``: + + >>> h = [1, 1] + >>> upfirdn(h, x, 2) + array([[ 0., 0., 1., 1.], + [ 2., 2., 3., 3.], + [ 4., 4., 5., 5.], + [ 6., 6., 7., 7.]]) + + Apply along the 0th dimension of ``x``: + + >>> upfirdn(h, x, 2, axis=0) + array([[ 0., 1.], + [ 0., 1.], + [ 2., 3.], + [ 2., 3.], + [ 4., 5.], + [ 4., 5.], + [ 6., 7.], + [ 6., 7.]]) + """ + x = np.asarray(x) + ufd = _UpFIRDn(h, x.dtype, up, down) + # This is equivalent to (but faster than) using np.apply_along_axis + return ufd.apply_filter(x, axis, mode, cval) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_waveforms.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_waveforms.py new file mode 100644 index 0000000000000000000000000000000000000000..a6be46cfd38674ee8c3ae89c9762461440c1e620 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_waveforms.py @@ -0,0 +1,696 @@ +# Author: Travis Oliphant +# 2003 +# +# Feb. 2010: Updated by Warren Weckesser: +# Rewrote much of chirp() +# Added sweep_poly() +import numpy as np +from numpy import asarray, zeros, place, nan, mod, pi, extract, log, sqrt, \ + exp, cos, sin, polyval, polyint + + +__all__ = ['sawtooth', 'square', 'gausspulse', 'chirp', 'sweep_poly', + 'unit_impulse'] + + +def sawtooth(t, width=1): + """ + Return a periodic sawtooth or triangle waveform. + + The sawtooth waveform has a period ``2*pi``, rises from -1 to 1 on the + interval 0 to ``width*2*pi``, then drops from 1 to -1 on the interval + ``width*2*pi`` to ``2*pi``. `width` must be in the interval [0, 1]. + + Note that this is not band-limited. It produces an infinite number + of harmonics, which are aliased back and forth across the frequency + spectrum. + + Parameters + ---------- + t : array_like + Time. + width : array_like, optional + Width of the rising ramp as a proportion of the total cycle. + Default is 1, producing a rising ramp, while 0 produces a falling + ramp. `width` = 0.5 produces a triangle wave. + If an array, causes wave shape to change over time, and must be the + same length as t. + + Returns + ------- + y : ndarray + Output array containing the sawtooth waveform. + + Examples + -------- + A 5 Hz waveform sampled at 500 Hz for 1 second: + + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> t = np.linspace(0, 1, 500) + >>> plt.plot(t, signal.sawtooth(2 * np.pi * 5 * t)) + + """ + t, w = asarray(t), asarray(width) + w = asarray(w + (t - t)) + t = asarray(t + (w - w)) + if t.dtype.char in ['fFdD']: + ytype = t.dtype.char + else: + ytype = 'd' + y = zeros(t.shape, ytype) + + # width must be between 0 and 1 inclusive + mask1 = (w > 1) | (w < 0) + place(y, mask1, nan) + + # take t modulo 2*pi + tmod = mod(t, 2 * pi) + + # on the interval 0 to width*2*pi function is + # tmod / (pi*w) - 1 + mask2 = (1 - mask1) & (tmod < w * 2 * pi) + tsub = extract(mask2, tmod) + wsub = extract(mask2, w) + place(y, mask2, tsub / (pi * wsub) - 1) + + # on the interval width*2*pi to 2*pi function is + # (pi*(w+1)-tmod) / (pi*(1-w)) + + mask3 = (1 - mask1) & (1 - mask2) + tsub = extract(mask3, tmod) + wsub = extract(mask3, w) + place(y, mask3, (pi * (wsub + 1) - tsub) / (pi * (1 - wsub))) + return y + + +def square(t, duty=0.5): + """ + Return a periodic square-wave waveform. + + The square wave has a period ``2*pi``, has value +1 from 0 to + ``2*pi*duty`` and -1 from ``2*pi*duty`` to ``2*pi``. `duty` must be in + the interval [0,1]. + + Note that this is not band-limited. It produces an infinite number + of harmonics, which are aliased back and forth across the frequency + spectrum. + + Parameters + ---------- + t : array_like + The input time array. + duty : array_like, optional + Duty cycle. Default is 0.5 (50% duty cycle). + If an array, causes wave shape to change over time, and must be the + same length as t. + + Returns + ------- + y : ndarray + Output array containing the square waveform. + + Examples + -------- + A 5 Hz waveform sampled at 500 Hz for 1 second: + + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> t = np.linspace(0, 1, 500, endpoint=False) + >>> plt.plot(t, signal.square(2 * np.pi * 5 * t)) + >>> plt.ylim(-2, 2) + + A pulse-width modulated sine wave: + + >>> plt.figure() + >>> sig = np.sin(2 * np.pi * t) + >>> pwm = signal.square(2 * np.pi * 30 * t, duty=(sig + 1)/2) + >>> plt.subplot(2, 1, 1) + >>> plt.plot(t, sig) + >>> plt.subplot(2, 1, 2) + >>> plt.plot(t, pwm) + >>> plt.ylim(-1.5, 1.5) + + """ + t, w = asarray(t), asarray(duty) + w = asarray(w + (t - t)) + t = asarray(t + (w - w)) + if t.dtype.char in ['fFdD']: + ytype = t.dtype.char + else: + ytype = 'd' + + y = zeros(t.shape, ytype) + + # width must be between 0 and 1 inclusive + mask1 = (w > 1) | (w < 0) + place(y, mask1, nan) + + # on the interval 0 to duty*2*pi function is 1 + tmod = mod(t, 2 * pi) + mask2 = (1 - mask1) & (tmod < w * 2 * pi) + place(y, mask2, 1) + + # on the interval duty*2*pi to 2*pi function is + # (pi*(w+1)-tmod) / (pi*(1-w)) + mask3 = (1 - mask1) & (1 - mask2) + place(y, mask3, -1) + return y + + +def gausspulse(t, fc=1000, bw=0.5, bwr=-6, tpr=-60, retquad=False, + retenv=False): + """ + Return a Gaussian modulated sinusoid: + + ``exp(-a t^2) exp(1j*2*pi*fc*t).`` + + If `retquad` is True, then return the real and imaginary parts + (in-phase and quadrature). + If `retenv` is True, then return the envelope (unmodulated signal). + Otherwise, return the real part of the modulated sinusoid. + + Parameters + ---------- + t : ndarray or the string 'cutoff' + Input array. + fc : float, optional + Center frequency (e.g. Hz). Default is 1000. + bw : float, optional + Fractional bandwidth in frequency domain of pulse (e.g. Hz). + Default is 0.5. + bwr : float, optional + Reference level at which fractional bandwidth is calculated (dB). + Default is -6. + tpr : float, optional + If `t` is 'cutoff', then the function returns the cutoff + time for when the pulse amplitude falls below `tpr` (in dB). + Default is -60. + retquad : bool, optional + If True, return the quadrature (imaginary) as well as the real part + of the signal. Default is False. + retenv : bool, optional + If True, return the envelope of the signal. Default is False. + + Returns + ------- + yI : ndarray + Real part of signal. Always returned. + yQ : ndarray + Imaginary part of signal. Only returned if `retquad` is True. + yenv : ndarray + Envelope of signal. Only returned if `retenv` is True. + + Examples + -------- + Plot real component, imaginary component, and envelope for a 5 Hz pulse, + sampled at 100 Hz for 2 seconds: + + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> t = np.linspace(-1, 1, 2 * 100, endpoint=False) + >>> i, q, e = signal.gausspulse(t, fc=5, retquad=True, retenv=True) + >>> plt.plot(t, i, t, q, t, e, '--') + + """ + if fc < 0: + raise ValueError(f"Center frequency (fc={fc:.2f}) must be >=0.") + if bw <= 0: + raise ValueError(f"Fractional bandwidth (bw={bw:.2f}) must be > 0.") + if bwr >= 0: + raise ValueError(f"Reference level for bandwidth (bwr={bwr:.2f}) " + "must be < 0 dB") + + # exp(-a t^2) <-> sqrt(pi/a) exp(-pi^2/a * f^2) = g(f) + + ref = pow(10.0, bwr / 20.0) + # fdel = fc*bw/2: g(fdel) = ref --- solve this for a + # + # pi^2/a * fc^2 * bw^2 /4=-log(ref) + a = -(pi * fc * bw) ** 2 / (4.0 * log(ref)) + + if isinstance(t, str): + if t == 'cutoff': # compute cut_off point + # Solve exp(-a tc**2) = tref for tc + # tc = sqrt(-log(tref) / a) where tref = 10^(tpr/20) + if tpr >= 0: + raise ValueError("Reference level for time cutoff must " + "be < 0 dB") + tref = pow(10.0, tpr / 20.0) + return sqrt(-log(tref) / a) + else: + raise ValueError("If `t` is a string, it must be 'cutoff'") + + yenv = exp(-a * t * t) + yI = yenv * cos(2 * pi * fc * t) + yQ = yenv * sin(2 * pi * fc * t) + if not retquad and not retenv: + return yI + if not retquad and retenv: + return yI, yenv + if retquad and not retenv: + return yI, yQ + if retquad and retenv: + return yI, yQ, yenv + + +def chirp(t, f0, t1, f1, method='linear', phi=0, vertex_zero=True, *, + complex=False): + r"""Frequency-swept cosine generator. + + In the following, 'Hz' should be interpreted as 'cycles per unit'; + there is no requirement here that the unit is one second. The + important distinction is that the units of rotation are cycles, not + radians. Likewise, `t` could be a measurement of space instead of time. + + Parameters + ---------- + t : array_like + Times at which to evaluate the waveform. + f0 : float + Frequency (e.g. Hz) at time t=0. + t1 : float + Time at which `f1` is specified. + f1 : float + Frequency (e.g. Hz) of the waveform at time `t1`. + method : {'linear', 'quadratic', 'logarithmic', 'hyperbolic'}, optional + Kind of frequency sweep. If not given, `linear` is assumed. See + Notes below for more details. + phi : float, optional + Phase offset, in degrees. Default is 0. + vertex_zero : bool, optional + This parameter is only used when `method` is 'quadratic'. + It determines whether the vertex of the parabola that is the graph + of the frequency is at t=0 or t=t1. + complex : bool, optional + This parameter creates a complex-valued analytic signal instead of a + real-valued signal. It allows the use of complex baseband (in communications + domain). Default is False. + + .. versionadded:: 1.15.0 + + Returns + ------- + y : ndarray + A numpy array containing the signal evaluated at `t` with the requested + time-varying frequency. More precisely, the function returns + ``exp(1j*phase + 1j*(pi/180)*phi) if complex else cos(phase + (pi/180)*phi)`` + where `phase` is the integral (from 0 to `t`) of ``2*pi*f(t)``. + The instantaneous frequency ``f(t)`` is defined below. + + See Also + -------- + sweep_poly + + Notes + ----- + There are four possible options for the parameter `method`, which have a (long) + standard form and some allowed abbreviations. The formulas for the instantaneous + frequency :math:`f(t)` of the generated signal are as follows: + + 1. Parameter `method` in ``('linear', 'lin', 'li')``: + + .. math:: + f(t) = f_0 + \beta\, t \quad\text{with}\quad + \beta = \frac{f_1 - f_0}{t_1} + + Frequency :math:`f(t)` varies linearly over time with a constant rate + :math:`\beta`. + + 2. Parameter `method` in ``('quadratic', 'quad', 'q')``: + + .. math:: + f(t) = + \begin{cases} + f_0 + \beta\, t^2 & \text{if vertex_zero is True,}\\ + f_1 + \beta\, (t_1 - t)^2 & \text{otherwise,} + \end{cases} + \quad\text{with}\quad + \beta = \frac{f_1 - f_0}{t_1^2} + + The graph of the frequency f(t) is a parabola through :math:`(0, f_0)` and + :math:`(t_1, f_1)`. By default, the vertex of the parabola is at + :math:`(0, f_0)`. If `vertex_zero` is ``False``, then the vertex is at + :math:`(t_1, f_1)`. + To use a more general quadratic function, or an arbitrary + polynomial, use the function `scipy.signal.sweep_poly`. + + 3. Parameter `method` in ``('logarithmic', 'log', 'lo')``: + + .. math:: + f(t) = f_0 \left(\frac{f_1}{f_0}\right)^{t/t_1} + + :math:`f_0` and :math:`f_1` must be nonzero and have the same sign. + This signal is also known as a geometric or exponential chirp. + + 4. Parameter `method` in ``('hyperbolic', 'hyp')``: + + .. math:: + f(t) = \frac{\alpha}{\beta\, t + \gamma} \quad\text{with}\quad + \alpha = f_0 f_1 t_1, \ \beta = f_0 - f_1, \ \gamma = f_1 t_1 + + :math:`f_0` and :math:`f_1` must be nonzero. + + + Examples + -------- + For the first example, a linear chirp ranging from 6 Hz to 1 Hz over 10 seconds is + plotted: + + >>> import numpy as np + >>> from matplotlib.pyplot import tight_layout + >>> from scipy.signal import chirp, square, ShortTimeFFT + >>> from scipy.signal.windows import gaussian + >>> import matplotlib.pyplot as plt + ... + >>> N, T = 1000, 0.01 # number of samples and sampling interval for 10 s signal + >>> t = np.arange(N) * T # timestamps + ... + >>> x_lin = chirp(t, f0=6, f1=1, t1=10, method='linear') + ... + >>> fg0, ax0 = plt.subplots() + >>> ax0.set_title(r"Linear Chirp from $f(0)=6\,$Hz to $f(10)=1\,$Hz") + >>> ax0.set(xlabel="Time $t$ in Seconds", ylabel=r"Amplitude $x_\text{lin}(t)$") + >>> ax0.plot(t, x_lin) + >>> plt.show() + + The following four plots each show the short-time Fourier transform of a chirp + ranging from 45 Hz to 5 Hz with different values for the parameter `method` + (and `vertex_zero`): + + >>> x_qu0 = chirp(t, f0=45, f1=5, t1=N*T, method='quadratic', vertex_zero=True) + >>> x_qu1 = chirp(t, f0=45, f1=5, t1=N*T, method='quadratic', vertex_zero=False) + >>> x_log = chirp(t, f0=45, f1=5, t1=N*T, method='logarithmic') + >>> x_hyp = chirp(t, f0=45, f1=5, t1=N*T, method='hyperbolic') + ... + >>> win = gaussian(50, std=12, sym=True) + >>> SFT = ShortTimeFFT(win, hop=2, fs=1/T, mfft=800, scale_to='magnitude') + >>> ts = ("'quadratic', vertex_zero=True", "'quadratic', vertex_zero=False", + ... "'logarithmic'", "'hyperbolic'") + >>> fg1, ax1s = plt.subplots(2, 2, sharex='all', sharey='all', + ... figsize=(6, 5), layout="constrained") + >>> for x_, ax_, t_ in zip([x_qu0, x_qu1, x_log, x_hyp], ax1s.ravel(), ts): + ... aSx = abs(SFT.stft(x_)) + ... im_ = ax_.imshow(aSx, origin='lower', aspect='auto', extent=SFT.extent(N), + ... cmap='plasma') + ... ax_.set_title(t_) + ... if t_ == "'hyperbolic'": + ... fg1.colorbar(im_, ax=ax1s, label='Magnitude $|S_z(t,f)|$') + >>> _ = fg1.supxlabel("Time $t$ in Seconds") # `_ =` is needed to pass doctests + >>> _ = fg1.supylabel("Frequency $f$ in Hertz") + >>> plt.show() + + Finally, the short-time Fourier transform of a complex-valued linear chirp + ranging from -30 Hz to 30 Hz is depicted: + + >>> z_lin = chirp(t, f0=-30, f1=30, t1=N*T, method="linear", complex=True) + >>> SFT.fft_mode = 'centered' # needed to work with complex signals + >>> aSz = abs(SFT.stft(z_lin)) + ... + >>> fg2, ax2 = plt.subplots() + >>> ax2.set_title(r"Linear Chirp from $-30\,$Hz to $30\,$Hz") + >>> ax2.set(xlabel="Time $t$ in Seconds", ylabel="Frequency $f$ in Hertz") + >>> im2 = ax2.imshow(aSz, origin='lower', aspect='auto', + ... extent=SFT.extent(N), cmap='viridis') + >>> fg2.colorbar(im2, label='Magnitude $|S_z(t,f)|$') + >>> plt.show() + + Note that using negative frequencies makes only sense with complex-valued signals. + Furthermore, the magnitude of the complex exponential function is one whereas the + magnitude of the real-valued cosine function is only 1/2. + """ + # 'phase' is computed in _chirp_phase, to make testing easier. + phase = _chirp_phase(t, f0, t1, f1, method, vertex_zero) + np.deg2rad(phi) + return np.exp(1j*phase) if complex else np.cos(phase) + + +def _chirp_phase(t, f0, t1, f1, method='linear', vertex_zero=True): + """ + Calculate the phase used by `chirp` to generate its output. + + See `chirp` for a description of the arguments. + + """ + t = asarray(t) + f0 = float(f0) + t1 = float(t1) + f1 = float(f1) + if method in ['linear', 'lin', 'li']: + beta = (f1 - f0) / t1 + phase = 2 * pi * (f0 * t + 0.5 * beta * t * t) + + elif method in ['quadratic', 'quad', 'q']: + beta = (f1 - f0) / (t1 ** 2) + if vertex_zero: + phase = 2 * pi * (f0 * t + beta * t ** 3 / 3) + else: + phase = 2 * pi * (f1 * t + beta * ((t1 - t) ** 3 - t1 ** 3) / 3) + + elif method in ['logarithmic', 'log', 'lo']: + if f0 * f1 <= 0.0: + raise ValueError("For a logarithmic chirp, f0 and f1 must be " + "nonzero and have the same sign.") + if f0 == f1: + phase = 2 * pi * f0 * t + else: + beta = t1 / log(f1 / f0) + phase = 2 * pi * beta * f0 * (pow(f1 / f0, t / t1) - 1.0) + + elif method in ['hyperbolic', 'hyp']: + if f0 == 0 or f1 == 0: + raise ValueError("For a hyperbolic chirp, f0 and f1 must be " + "nonzero.") + if f0 == f1: + # Degenerate case: constant frequency. + phase = 2 * pi * f0 * t + else: + # Singular point: the instantaneous frequency blows up + # when t == sing. + sing = -f1 * t1 / (f0 - f1) + phase = 2 * pi * (-sing * f0) * log(np.abs(1 - t/sing)) + + else: + raise ValueError("method must be 'linear', 'quadratic', 'logarithmic', " + f"or 'hyperbolic', but a value of {method!r} was given.") + + return phase + + +def sweep_poly(t, poly, phi=0): + """ + Frequency-swept cosine generator, with a time-dependent frequency. + + This function generates a sinusoidal function whose instantaneous + frequency varies with time. The frequency at time `t` is given by + the polynomial `poly`. + + Parameters + ---------- + t : ndarray + Times at which to evaluate the waveform. + poly : 1-D array_like or instance of numpy.poly1d + The desired frequency expressed as a polynomial. If `poly` is + a list or ndarray of length n, then the elements of `poly` are + the coefficients of the polynomial, and the instantaneous + frequency is + + ``f(t) = poly[0]*t**(n-1) + poly[1]*t**(n-2) + ... + poly[n-1]`` + + If `poly` is an instance of numpy.poly1d, then the + instantaneous frequency is + + ``f(t) = poly(t)`` + + phi : float, optional + Phase offset, in degrees, Default: 0. + + Returns + ------- + sweep_poly : ndarray + A numpy array containing the signal evaluated at `t` with the + requested time-varying frequency. More precisely, the function + returns ``cos(phase + (pi/180)*phi)``, where `phase` is the integral + (from 0 to t) of ``2 * pi * f(t)``; ``f(t)`` is defined above. + + See Also + -------- + chirp + + Notes + ----- + .. versionadded:: 0.8.0 + + If `poly` is a list or ndarray of length `n`, then the elements of + `poly` are the coefficients of the polynomial, and the instantaneous + frequency is: + + ``f(t) = poly[0]*t**(n-1) + poly[1]*t**(n-2) + ... + poly[n-1]`` + + If `poly` is an instance of `numpy.poly1d`, then the instantaneous + frequency is: + + ``f(t) = poly(t)`` + + Finally, the output `s` is: + + ``cos(phase + (pi/180)*phi)`` + + where `phase` is the integral from 0 to `t` of ``2 * pi * f(t)``, + ``f(t)`` as defined above. + + Examples + -------- + Compute the waveform with instantaneous frequency:: + + f(t) = 0.025*t**3 - 0.36*t**2 + 1.25*t + 2 + + over the interval 0 <= t <= 10. + + >>> import numpy as np + >>> from scipy.signal import sweep_poly + >>> p = np.poly1d([0.025, -0.36, 1.25, 2.0]) + >>> t = np.linspace(0, 10, 5001) + >>> w = sweep_poly(t, p) + + Plot it: + + >>> import matplotlib.pyplot as plt + >>> plt.subplot(2, 1, 1) + >>> plt.plot(t, w) + >>> plt.title("Sweep Poly\\nwith frequency " + + ... "$f(t) = 0.025t^3 - 0.36t^2 + 1.25t + 2$") + >>> plt.subplot(2, 1, 2) + >>> plt.plot(t, p(t), 'r', label='f(t)') + >>> plt.legend() + >>> plt.xlabel('t') + >>> plt.tight_layout() + >>> plt.show() + + """ + # 'phase' is computed in _sweep_poly_phase, to make testing easier. + phase = _sweep_poly_phase(t, poly) + # Convert to radians. + phi *= pi / 180 + return cos(phase + phi) + + +def _sweep_poly_phase(t, poly): + """ + Calculate the phase used by sweep_poly to generate its output. + + See `sweep_poly` for a description of the arguments. + + """ + # polyint handles lists, ndarrays and instances of poly1d automatically. + intpoly = polyint(poly) + phase = 2 * pi * polyval(intpoly, t) + return phase + + +def unit_impulse(shape, idx=None, dtype=float): + r""" + Unit impulse signal (discrete delta function) or unit basis vector. + + Parameters + ---------- + shape : int or tuple of int + Number of samples in the output (1-D), or a tuple that represents the + shape of the output (N-D). + idx : None or int or tuple of int or 'mid', optional + Index at which the value is 1. If None, defaults to the 0th element. + If ``idx='mid'``, the impulse will be centered at ``shape // 2`` in + all dimensions. If an int, the impulse will be at `idx` in all + dimensions. + dtype : data-type, optional + The desired data-type for the array, e.g., ``numpy.int8``. Default is + ``numpy.float64``. + + Returns + ------- + y : ndarray + Output array containing an impulse signal. + + Notes + ----- + In digital signal processing literature the unit impulse signal is often + represented by the Kronecker delta. [1]_ I.e., a signal :math:`u_k[n]`, + which is zero everywhere except being one at the :math:`k`-th sample, + can be expressed as + + .. math:: + + u_k[n] = \delta[n-k] \equiv \delta_{n,k}\ . + + Furthermore, the unit impulse is frequently interpreted as the discrete-time + version of the continuous-time Dirac distribution. [2]_ + + References + ---------- + .. [1] "Kronecker delta", *Wikipedia*, + https://en.wikipedia.org/wiki/Kronecker_delta#Digital_signal_processing + .. [2] "Dirac delta function" *Wikipedia*, + https://en.wikipedia.org/wiki/Dirac_delta_function#Relationship_to_the_Kronecker_delta + + .. versionadded:: 0.19.0 + + Examples + -------- + An impulse at the 0th element (:math:`\\delta[n]`): + + >>> from scipy import signal + >>> signal.unit_impulse(8) + array([ 1., 0., 0., 0., 0., 0., 0., 0.]) + + Impulse offset by 2 samples (:math:`\\delta[n-2]`): + + >>> signal.unit_impulse(7, 2) + array([ 0., 0., 1., 0., 0., 0., 0.]) + + 2-dimensional impulse, centered: + + >>> signal.unit_impulse((3, 3), 'mid') + array([[ 0., 0., 0.], + [ 0., 1., 0.], + [ 0., 0., 0.]]) + + Impulse at (2, 2), using broadcasting: + + >>> signal.unit_impulse((4, 4), 2) + array([[ 0., 0., 0., 0.], + [ 0., 0., 0., 0.], + [ 0., 0., 1., 0.], + [ 0., 0., 0., 0.]]) + + Plot the impulse response of a 4th-order Butterworth lowpass filter: + + >>> imp = signal.unit_impulse(100, 'mid') + >>> b, a = signal.butter(4, 0.2) + >>> response = signal.lfilter(b, a, imp) + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> plt.plot(np.arange(-50, 50), imp) + >>> plt.plot(np.arange(-50, 50), response) + >>> plt.margins(0.1, 0.1) + >>> plt.xlabel('Time [samples]') + >>> plt.ylabel('Amplitude') + >>> plt.grid(True) + >>> plt.show() + + """ + out = zeros(shape, dtype) + + shape = np.atleast_1d(shape) + + if idx is None: + idx = (0,) * len(shape) + elif idx == 'mid': + idx = tuple(shape // 2) + elif not hasattr(idx, "__iter__"): + idx = (idx,) * len(shape) + + out[idx] = 1 + return out diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_wavelets.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_wavelets.py new file mode 100644 index 0000000000000000000000000000000000000000..2b9f8fa32672e3f252f0f4ec4e387e0d474dc21e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/_wavelets.py @@ -0,0 +1,29 @@ +import numpy as np +from scipy.signal import convolve + + +def _ricker(points, a): + A = 2 / (np.sqrt(3 * a) * (np.pi**0.25)) + wsq = a**2 + vec = np.arange(0, points) - (points - 1.0) / 2 + xsq = vec**2 + mod = (1 - xsq / wsq) + gauss = np.exp(-xsq / (2 * wsq)) + total = A * mod * gauss + return total + + +def _cwt(data, wavelet, widths, dtype=None, **kwargs): + # Determine output type + if dtype is None: + if np.asarray(wavelet(1, widths[0], **kwargs)).dtype.char in 'FDG': + dtype = np.complex128 + else: + dtype = np.float64 + + output = np.empty((len(widths), len(data)), dtype=dtype) + for ind, width in enumerate(widths): + N = np.min([10 * width, len(data)]) + wavelet_data = np.conj(wavelet(N, width, **kwargs)[::-1]) + output[ind] = convolve(data, wavelet_data, mode='same') + return output diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/bsplines.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/bsplines.py new file mode 100644 index 0000000000000000000000000000000000000000..0328d45c107bda78cbdbd374148237ca09ac411d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/bsplines.py @@ -0,0 +1,21 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.signal` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__ = [ # noqa: F822 + 'spline_filter', 'gauss_spline', + 'cspline1d', 'qspline1d', 'cspline1d_eval', 'qspline1d_eval', + 'cspline2d', 'sepfir2d' +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="signal", module="bsplines", + private_modules=["_spline_filters"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/filter_design.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/filter_design.py new file mode 100644 index 0000000000000000000000000000000000000000..41dc230a7f24a7ac3209f821d8d0f9417130afbd --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/filter_design.py @@ -0,0 +1,28 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.signal` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__ = [ # noqa: F822 + 'findfreqs', 'freqs', 'freqz', 'tf2zpk', 'zpk2tf', 'normalize', + 'lp2lp', 'lp2hp', 'lp2bp', 'lp2bs', 'bilinear', 'iirdesign', + 'iirfilter', 'butter', 'cheby1', 'cheby2', 'ellip', 'bessel', + 'band_stop_obj', 'buttord', 'cheb1ord', 'cheb2ord', 'ellipord', + 'buttap', 'cheb1ap', 'cheb2ap', 'ellipap', 'besselap', + 'BadCoefficients', 'freqs_zpk', 'freqz_zpk', + 'tf2sos', 'sos2tf', 'zpk2sos', 'sos2zpk', 'group_delay', + 'sosfreqz', 'freqz_sos', 'iirnotch', 'iirpeak', 'bilinear_zpk', + 'lp2lp_zpk', 'lp2hp_zpk', 'lp2bp_zpk', 'lp2bs_zpk', + 'gammatone', 'iircomb', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="signal", module="filter_design", + private_modules=["_filter_design"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/fir_filter_design.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/fir_filter_design.py new file mode 100644 index 0000000000000000000000000000000000000000..2214b82998bdefd2c6d6171cc952adf827269736 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/fir_filter_design.py @@ -0,0 +1,20 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.signal` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__ = [ # noqa: F822 + 'kaiser_beta', 'kaiser_atten', 'kaiserord', + 'firwin', 'firwin2', 'remez', 'firls', 'minimum_phase', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="signal", module="fir_filter_design", + private_modules=["_fir_filter_design"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/lti_conversion.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/lti_conversion.py new file mode 100644 index 0000000000000000000000000000000000000000..7080990afc9e23e51e8a45aaa146b64c58dda3cf --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/lti_conversion.py @@ -0,0 +1,20 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.signal` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__ = [ # noqa: F822 + 'tf2ss', 'abcd_normalize', 'ss2tf', 'zpk2ss', 'ss2zpk', + 'cont2discrete', 'tf2zpk', 'zpk2tf', 'normalize' +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="signal", module="lti_conversion", + private_modules=["_lti_conversion"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/ltisys.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/ltisys.py new file mode 100644 index 0000000000000000000000000000000000000000..5123068de559f124bf444c12ef9824c3d14de64f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/ltisys.py @@ -0,0 +1,25 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.signal` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__ = [ # noqa: F822 + 'lti', 'dlti', 'TransferFunction', 'ZerosPolesGain', 'StateSpace', + 'lsim', 'impulse', 'step', 'bode', + 'freqresp', 'place_poles', 'dlsim', 'dstep', 'dimpulse', + 'dfreqresp', 'dbode', + 'tf2zpk', 'zpk2tf', 'normalize', 'freqs', + 'freqz', 'freqs_zpk', 'freqz_zpk', 'tf2ss', 'abcd_normalize', + 'ss2tf', 'zpk2ss', 'ss2zpk', 'cont2discrete', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="signal", module="ltisys", + private_modules=["_ltisys"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/signaltools.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/signaltools.py new file mode 100644 index 0000000000000000000000000000000000000000..85d426f5fb2605c639fc6dbd1b4d0284a3f11e1b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/signaltools.py @@ -0,0 +1,27 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.signal` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__ = [ # noqa: F822 + 'correlate', 'correlation_lags', 'correlate2d', + 'convolve', 'convolve2d', 'fftconvolve', 'oaconvolve', + 'order_filter', 'medfilt', 'medfilt2d', 'wiener', 'lfilter', + 'lfiltic', 'sosfilt', 'deconvolve', 'hilbert', 'hilbert2', + 'unique_roots', 'invres', 'invresz', 'residue', + 'residuez', 'resample', 'resample_poly', 'detrend', + 'lfilter_zi', 'sosfilt_zi', 'sosfiltfilt', 'choose_conv_method', + 'filtfilt', 'decimate', 'vectorstrength', + 'dlti', 'upfirdn', 'get_window', 'cheby1', 'firwin' +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="signal", module="signaltools", + private_modules=["_signaltools"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/spectral.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/spectral.py new file mode 100644 index 0000000000000000000000000000000000000000..299ebed781b00a1f1f35e96c54f4c20d9bd9d0fc --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/spectral.py @@ -0,0 +1,21 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.signal` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__ = [ # noqa: F822 + 'periodogram', 'welch', 'lombscargle', 'csd', 'coherence', + 'spectrogram', 'stft', 'istft', 'check_COLA', 'check_NOLA', + 'get_window', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="signal", module="spectral", + private_modules=["_spectral_py"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/spline.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/spline.py new file mode 100644 index 0000000000000000000000000000000000000000..7afd0d0a14beecd5bc4522050eaf3b195f1a3601 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/spline.py @@ -0,0 +1,25 @@ +# This file is not meant for public use and will be removed in the future +# versions of SciPy. Use the `scipy.signal` namespace for importing the +# functions included below. + +import warnings + +from . import _spline + +__all__ = ['sepfir2d'] # noqa: F822 + + +def __dir__(): + return __all__ + + +def __getattr__(name): + if name not in __all__: + raise AttributeError( + f"scipy.signal.spline is deprecated and has no attribute {name}. " + "Try looking in scipy.signal instead.") + + warnings.warn(f"Please use `{name}` from the `scipy.signal` namespace, " + "the `scipy.signal.spline` namespace is deprecated.", + category=DeprecationWarning, stacklevel=2) + return getattr(_spline, name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/_scipy_spectral_test_shim.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/_scipy_spectral_test_shim.py new file mode 100644 index 0000000000000000000000000000000000000000..42d3d830d0e39797832472b9e039259111cfccc8 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/_scipy_spectral_test_shim.py @@ -0,0 +1,480 @@ +"""Helpers to utilize existing stft / istft tests for testing `ShortTimeFFT`. + +This module provides the functions stft_compare() and istft_compare(), which, +compares the output between the existing (i)stft() and the shortTimeFFT based +_(i)stft_wrapper() implementations in this module. + +For testing add the following imports to the file ``tests/test_spectral.py``:: + + from ._scipy_spectral_test_shim import stft_compare as stft + from ._scipy_spectral_test_shim import istft_compare as istft + +and remove the existing imports of stft and istft. + +The idea of these wrappers is not to provide a backward-compatible interface +but to demonstrate that the ShortTimeFFT implementation is at least as capable +as the existing one and delivers comparable results. Furthermore, the +wrappers highlight the different philosophies of the implementations, +especially in the border handling. +""" +import platform +from typing import cast, Literal + +import numpy as np +from numpy.testing import assert_allclose + +from scipy.signal import ShortTimeFFT +from scipy.signal import csd, get_window, stft, istft +from scipy.signal._arraytools import const_ext, even_ext, odd_ext, zero_ext +from scipy.signal._short_time_fft import FFT_MODE_TYPE +from scipy.signal._spectral_py import _spectral_helper, _triage_segments, \ + _median_bias + + +def _stft_wrapper(x, fs=1.0, window='hann', nperseg=256, noverlap=None, + nfft=None, detrend=False, return_onesided=True, + boundary='zeros', padded=True, axis=-1, scaling='spectrum'): + """Wrapper for the SciPy `stft()` function based on `ShortTimeFFT` for + unit testing. + + Handling the boundary and padding is where `ShortTimeFFT` and `stft()` + differ in behavior. Parts of `_spectral_helper()` were copied to mimic + the` stft()` behavior. + + This function is meant to be solely used by `stft_compare()`. + """ + if scaling not in ('psd', 'spectrum'): # same errors as in original stft: + raise ValueError(f"Parameter {scaling=} not in ['spectrum', 'psd']!") + + # The following lines are taken from the original _spectral_helper(): + boundary_funcs = {'even': even_ext, + 'odd': odd_ext, + 'constant': const_ext, + 'zeros': zero_ext, + None: None} + + if boundary not in boundary_funcs: + raise ValueError(f"Unknown boundary option '{boundary}', must be one" + + f" of: {list(boundary_funcs.keys())}") + if x.size == 0: + return np.empty(x.shape), np.empty(x.shape), np.empty(x.shape) + + if nperseg is not None: # if specified by user + nperseg = int(nperseg) + if nperseg < 1: + raise ValueError('nperseg must be a positive integer') + + # parse window; if array like, then set nperseg = win.shape + win, nperseg = _triage_segments(window, nperseg, + input_length=x.shape[axis]) + + if nfft is None: + nfft = nperseg + elif nfft < nperseg: + raise ValueError('nfft must be greater than or equal to nperseg.') + else: + nfft = int(nfft) + + if noverlap is None: + noverlap = nperseg//2 + else: + noverlap = int(noverlap) + if noverlap >= nperseg: + raise ValueError('noverlap must be less than nperseg.') + nstep = nperseg - noverlap + n = x.shape[axis] + + # Padding occurs after boundary extension, so that the extended signal ends + # in zeros, instead of introducing an impulse at the end. + # I.e. if x = [..., 3, 2] + # extend then pad -> [..., 3, 2, 2, 3, 0, 0, 0] + # pad then extend -> [..., 3, 2, 0, 0, 0, 2, 3] + + if boundary is not None: + ext_func = boundary_funcs[boundary] + # Extend by nperseg//2 in front and back: + x = ext_func(x, nperseg//2, axis=axis) + + if padded: + # Pad to integer number of windowed segments + # I.e make x.shape[-1] = nperseg + (nseg-1)*nstep, with integer nseg + x = np.moveaxis(x, axis, -1) + + # This is an edge case where shortTimeFFT returns one more time slice + # than the Scipy stft() shorten to remove last time slice: + if n % 2 == 1 and nperseg % 2 == 1 and noverlap % 2 == 1: + x = x[..., : -1] + + nadd = (-(x.shape[-1]-nperseg) % nstep) % nperseg + zeros_shape = list(x.shape[:-1]) + [nadd] + x = np.concatenate((x, np.zeros(zeros_shape)), axis=-1) + x = np.moveaxis(x, -1, axis) + + # ... end original _spectral_helper() code. + scale_to = {'spectrum': 'magnitude', 'psd': 'psd'}[scaling] + + if np.iscomplexobj(x) and return_onesided: + return_onesided = False + # using cast() to make mypy happy: + fft_mode = cast(FFT_MODE_TYPE, 'onesided' if return_onesided else 'twosided') + + ST = ShortTimeFFT(win, nstep, fs, fft_mode=fft_mode, mfft=nfft, + scale_to=scale_to, phase_shift=None) + + k_off = nperseg // 2 + p0 = 0 # ST.lower_border_end[1] + 1 + nn = x.shape[axis] if padded else n+k_off+1 + # number of frames akin to legacy stft computation + p1 = (x.shape[axis] - nperseg) // nstep + 1 + + detr = None if detrend is False else detrend + Sxx = ST.stft_detrend(x, detr, p0, p1, k_offset=k_off, axis=axis) + t = ST.t(nn, 0, p1 - p0, k_offset=0 if boundary is not None else k_off) + if x.dtype in (np.float32, np.complex64): + Sxx = Sxx.astype(np.complex64) + + return ST.f, t, Sxx + + +def _istft_wrapper(Zxx, fs=1.0, window='hann', nperseg=None, noverlap=None, + nfft=None, input_onesided=True, boundary=True, time_axis=-1, + freq_axis=-2, scaling='spectrum') -> \ + tuple[np.ndarray, np.ndarray, tuple[int, int]]: + """Wrapper for the SciPy `istft()` function based on `ShortTimeFFT` for + unit testing. + + Note that only option handling is implemented as far as to handle the unit + tests. E.g., the case ``nperseg=None`` is not handled. + + This function is meant to be solely used by `istft_compare()`. + """ + # *** Lines are taken from _spectral_py.istft() ***: + if Zxx.ndim < 2: + raise ValueError('Input stft must be at least 2d!') + + if freq_axis == time_axis: + raise ValueError('Must specify differing time and frequency axes!') + + nseg = Zxx.shape[time_axis] + + if input_onesided: + # Assume even segment length + n_default = 2*(Zxx.shape[freq_axis] - 1) + else: + n_default = Zxx.shape[freq_axis] + + # Check windowing parameters + if nperseg is None: + nperseg = n_default + else: + nperseg = int(nperseg) + if nperseg < 1: + raise ValueError('nperseg must be a positive integer') + + if nfft is None: + if input_onesided and (nperseg == n_default + 1): + # Odd nperseg, no FFT padding + nfft = nperseg + else: + nfft = n_default + elif nfft < nperseg: + raise ValueError('nfft must be greater than or equal to nperseg.') + else: + nfft = int(nfft) + + if noverlap is None: + noverlap = nperseg//2 + else: + noverlap = int(noverlap) + if noverlap >= nperseg: + raise ValueError('noverlap must be less than nperseg.') + nstep = nperseg - noverlap + + # Get window as array + if isinstance(window, str) or type(window) is tuple: + win = get_window(window, nperseg) + else: + win = np.asarray(window) + if len(win.shape) != 1: + raise ValueError('window must be 1-D') + if win.shape[0] != nperseg: + raise ValueError(f'window must have length of {nperseg}') + + outputlength = nperseg + (nseg-1)*nstep + # *** End block of: Taken from _spectral_py.istft() *** + + # Using cast() to make mypy happy: + fft_mode = cast(FFT_MODE_TYPE, 'onesided' if input_onesided else 'twosided') + scale_to = cast(Literal['magnitude', 'psd'], + {'spectrum': 'magnitude', 'psd': 'psd'}[scaling]) + + ST = ShortTimeFFT(win, nstep, fs, fft_mode=fft_mode, mfft=nfft, + scale_to=scale_to, phase_shift=None) + + if boundary: + j = nperseg if nperseg % 2 == 0 else nperseg - 1 + k0 = ST.k_min + nperseg // 2 + k1 = outputlength - j + k0 + else: + raise NotImplementedError("boundary=False does not make sense with" + + "ShortTimeFFT.istft()!") + + x = ST.istft(Zxx, k0=k0, k1=k1, f_axis=freq_axis, t_axis=time_axis) + t = np.arange(k1 - k0) * ST.T + k_hi = ST.upper_border_begin(k1 - k0)[0] + # using cast() to make mypy happy: + return t, x, (ST.lower_border_end[0], k_hi) + + +def _csd_wrapper(x, y, fs=1.0, window='hann', nperseg=None, noverlap=None, + nfft=None, detrend='constant', return_onesided=True, + scaling='density', axis=-1, average='mean'): + """Wrapper for the `csd()` function based on `ShortTimeFFT` for + unit testing. + """ + freqs, _, Pxy = _csd_test_shim(x, y, fs, window, nperseg, noverlap, nfft, + detrend, return_onesided, scaling, axis) + + # The following code is taken from csd(): + if len(Pxy.shape) >= 2 and Pxy.size > 0: + if Pxy.shape[-1] > 1: + if average == 'median': + # np.median must be passed real arrays for the desired result + bias = _median_bias(Pxy.shape[-1]) + if np.iscomplexobj(Pxy): + Pxy = (np.median(np.real(Pxy), axis=-1) + + 1j * np.median(np.imag(Pxy), axis=-1)) + else: + Pxy = np.median(Pxy, axis=-1) + Pxy /= bias + elif average == 'mean': + Pxy = Pxy.mean(axis=-1) + else: + raise ValueError(f'average must be "median" or "mean", got {average}') + else: + Pxy = np.reshape(Pxy, Pxy.shape[:-1]) + + return freqs, Pxy + + +def _csd_test_shim(x, y, fs=1.0, window='hann', nperseg=None, noverlap=None, + nfft=None, detrend='constant', return_onesided=True, + scaling='density', axis=-1): + """Compare output of _spectral_helper() and ShortTimeFFT, more + precisely _spect_helper_csd() for used in csd_wrapper(). + + The motivation of this function is to test if the ShortTimeFFT-based + wrapper `_spect_helper_csd()` returns the same values as `_spectral_helper`. + This function should only be usd by csd() in (unit) testing. + """ + freqs, t, Pxy = _spectral_helper(x, y, fs, window, nperseg, noverlap, nfft, + detrend, return_onesided, scaling, axis, + mode='psd') + freqs1, Pxy1 = _spect_helper_csd(x, y, fs, window, nperseg, noverlap, nfft, + detrend, return_onesided, scaling, axis) + + np.testing.assert_allclose(freqs1, freqs) + amax_Pxy = max(np.abs(Pxy).max(), 1) if Pxy.size else 1 + atol = np.finfo(Pxy.dtype).resolution * amax_Pxy # needed for large Pxy + # for c_ in range(Pxy.shape[-1]): + # np.testing.assert_allclose(Pxy1[:, c_], Pxy[:, c_], atol=atol) + np.testing.assert_allclose(Pxy1, Pxy, atol=atol) + return freqs, t, Pxy + + +def _spect_helper_csd(x, y, fs=1.0, window='hann', nperseg=None, noverlap=None, + nfft=None, detrend='constant', return_onesided=True, + scaling='density', axis=-1): + """Wrapper for replacing _spectral_helper() by using the ShortTimeFFT + for use by csd(). + + This function should be only used by _csd_test_shim() and is only useful + for testing the ShortTimeFFT implementation. + """ + + # The following lines are taken from the original _spectral_helper(): + same_data = y is x + axis = int(axis) + + # Ensure we have np.arrays, get outdtype + x = np.asarray(x) + if not same_data: + y = np.asarray(y) + # outdtype = np.result_type(x, y, np.complex64) + # else: + # outdtype = np.result_type(x, np.complex64) + + if not same_data: + # Check if we can broadcast the outer axes together + xouter = list(x.shape) + youter = list(y.shape) + xouter.pop(axis) + youter.pop(axis) + try: + outershape = np.broadcast(np.empty(xouter), np.empty(youter)).shape + except ValueError as e: + raise ValueError('x and y cannot be broadcast together.') from e + + if same_data: + if x.size == 0: + return np.empty(x.shape), np.empty(x.shape) + else: + if x.size == 0 or y.size == 0: + outshape = outershape + (min([x.shape[axis], y.shape[axis]]),) + emptyout = np.moveaxis(np.empty(outshape), -1, axis) + return emptyout, emptyout + + if nperseg is not None: # if specified by user + nperseg = int(nperseg) + if nperseg < 1: + raise ValueError('nperseg must be a positive integer') + + # parse window; if array like, then set nperseg = win.shape + n = x.shape[axis] if same_data else max(x.shape[axis], y.shape[axis]) + win, nperseg = _triage_segments(window, nperseg, input_length=n) + + if nfft is None: + nfft = nperseg + elif nfft < nperseg: + raise ValueError('nfft must be greater than or equal to nperseg.') + else: + nfft = int(nfft) + + if noverlap is None: + noverlap = nperseg // 2 + else: + noverlap = int(noverlap) + if noverlap >= nperseg: + raise ValueError('noverlap must be less than nperseg.') + nstep = nperseg - noverlap + + if np.iscomplexobj(x) and return_onesided: + return_onesided = False + + # using cast() to make mypy happy: + fft_mode = cast(FFT_MODE_TYPE, 'onesided' if return_onesided + else 'twosided') + scale = {'spectrum': 'magnitude', 'density': 'psd'}[scaling] + SFT = ShortTimeFFT(win, nstep, fs, fft_mode=fft_mode, mfft=nfft, + scale_to=scale, phase_shift=None) + + # _spectral_helper() calculates X.conj()*Y instead of X*Y.conj(): + Pxy = SFT.spectrogram(y, x, detr=None if detrend is False else detrend, + p0=0, p1=(n-noverlap)//SFT.hop, k_offset=nperseg//2, + axis=axis).conj() + # Note: + # 'onesided2X' scaling of ShortTimeFFT conflicts with the + # scaling='spectrum' parameter, since it doubles the squared magnitude, + # which in the view of the ShortTimeFFT implementation does not make sense. + # Hence, the doubling of the square is implemented here: + if return_onesided: + f_axis = Pxy.ndim - 1 + axis if axis < 0 else axis + Pxy = np.moveaxis(Pxy, f_axis, -1) + Pxy[..., 1:-1 if SFT.mfft % 2 == 0 else None] *= 2 + Pxy = np.moveaxis(Pxy, -1, f_axis) + + return SFT.f, Pxy + + +def stft_compare(x, fs=1.0, window='hann', nperseg=256, noverlap=None, + nfft=None, detrend=False, return_onesided=True, + boundary='zeros', padded=True, axis=-1, scaling='spectrum'): + """Assert that the results from the existing `stft()` and `_stft_wrapper()` + are close to each other. + + For comparing the STFT values an absolute tolerance of the floating point + resolution was added to circumvent problems with the following tests: + * For float32 the tolerances are much higher in + TestSTFT.test_roundtrip_float32()). + * The TestSTFT.test_roundtrip_scaling() has a high relative deviation. + Interestingly this did not appear in Scipy 1.9.1 but only in the current + development version. + """ + kw = dict(x=x, fs=fs, window=window, nperseg=nperseg, noverlap=noverlap, + nfft=nfft, detrend=detrend, return_onesided=return_onesided, + boundary=boundary, padded=padded, axis=axis, scaling=scaling) + f, t, Zxx = stft(**kw) + f_wrapper, t_wrapper, Zxx_wrapper = _stft_wrapper(**kw) + + e_msg_part = " of `stft_wrapper()` differ from `stft()`." + assert_allclose(f_wrapper, f, err_msg=f"Frequencies {e_msg_part}") + assert_allclose(t_wrapper, t, err_msg=f"Time slices {e_msg_part}") + + # Adapted tolerances to account for: + atol = np.finfo(Zxx.dtype).resolution * 2 + assert_allclose(Zxx_wrapper, Zxx, atol=atol, + err_msg=f"STFT values {e_msg_part}") + return f, t, Zxx + + +def istft_compare(Zxx, fs=1.0, window='hann', nperseg=None, noverlap=None, + nfft=None, input_onesided=True, boundary=True, time_axis=-1, + freq_axis=-2, scaling='spectrum'): + """Assert that the results from the existing `istft()` and + `_istft_wrapper()` are close to each other. + + Quirks: + * If ``boundary=False`` the comparison is skipped, since it does not + make sense with ShortTimeFFT.istft(). Only used in test + TestSTFT.test_roundtrip_boundary_extension(). + * If ShortTimeFFT.istft() decides the STFT is not invertible, the + comparison is skipped, since istft() only emits a warning and does not + return a correct result. Only used in + ShortTimeFFT.test_roundtrip_not_nola(). + * For comparing the signals an absolute tolerance of the floating point + resolution was added to account for the low accuracy of float32 (Occurs + only in TestSTFT.test_roundtrip_float32()). + """ + kw = dict(Zxx=Zxx, fs=fs, window=window, nperseg=nperseg, + noverlap=noverlap, nfft=nfft, input_onesided=input_onesided, + boundary=boundary, time_axis=time_axis, freq_axis=freq_axis, + scaling=scaling) + + t, x = istft(**kw) + if not boundary: # skip test_roundtrip_boundary_extension(): + return t, x # _istft_wrapper does() not implement this case + try: # if inversion fails, istft() only emits a warning: + t_wrapper, x_wrapper, (k_lo, k_hi) = _istft_wrapper(**kw) + except ValueError as v: # Do nothing if inversion fails: + if v.args[0] == "Short-time Fourier Transform not invertible!": + return t, x + raise v + + e_msg_part = " of `istft_wrapper()` differ from `istft()`" + assert_allclose(t, t_wrapper, err_msg=f"Sample times {e_msg_part}") + + # Adapted tolerances to account for resolution loss: + atol = np.finfo(x.dtype).resolution*2 # instead of default atol = 0 + rtol = 1e-7 # default for np.allclose() + + # Relax atol on 32-Bit platforms a bit to pass CI tests. + # - Not clear why there are discrepancies (in the FFT maybe?) + # - Not sure what changed on 'i686' since earlier on those test passed + if x.dtype == np.float32 and platform.machine() == 'i686': + # float32 gets only used by TestSTFT.test_roundtrip_float32() so + # we are using the tolerances from there to circumvent CI problems + atol, rtol = 1e-4, 1e-5 + elif platform.machine() in ('aarch64', 'i386', 'i686'): + atol = max(atol, 1e-12) # 2e-15 seems too tight for 32-Bit platforms + + assert_allclose(x_wrapper[k_lo:k_hi], x[k_lo:k_hi], atol=atol, rtol=rtol, + err_msg=f"Signal values {e_msg_part}") + return t, x + + +def csd_compare(x, y, fs=1.0, window='hann', nperseg=None, noverlap=None, + nfft=None, detrend='constant', return_onesided=True, + scaling='density', axis=-1, average='mean'): + """Assert that the results from the existing `csd()` and `_csd_wrapper()` + are close to each other. """ + kw = dict(x=x, y=y, fs=fs, window=window, nperseg=nperseg, + noverlap=noverlap, nfft=nfft, detrend=detrend, + return_onesided=return_onesided, scaling=scaling, axis=axis, + average=average) + freqs0, Pxy0 = csd(**kw) + freqs1, Pxy1 = _csd_wrapper(**kw) + + assert_allclose(freqs1, freqs0) + assert_allclose(Pxy1, Pxy0) + assert_allclose(freqs1, freqs0) + return freqs0, Pxy0 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/mpsig.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/mpsig.py new file mode 100644 index 0000000000000000000000000000000000000000..d129de74e5df00c22bc0b82c7d3f7b52483941f9 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/mpsig.py @@ -0,0 +1,122 @@ +""" +Some signal functions implemented using mpmath. +""" + +try: + import mpmath +except ImportError: + mpmath = None + + +def _prod(seq): + """Returns the product of the elements in the sequence `seq`.""" + p = 1 + for elem in seq: + p *= elem + return p + + +def _relative_degree(z, p): + """ + Return relative degree of transfer function from zeros and poles. + + This is simply len(p) - len(z), which must be nonnegative. + A ValueError is raised if len(p) < len(z). + """ + degree = len(p) - len(z) + if degree < 0: + raise ValueError("Improper transfer function. " + "Must have at least as many poles as zeros.") + return degree + + +def _zpkbilinear(z, p, k, fs): + """Bilinear transformation to convert a filter from analog to digital.""" + + degree = _relative_degree(z, p) + + fs2 = 2*fs + + # Bilinear transform the poles and zeros + z_z = [(fs2 + z1) / (fs2 - z1) for z1 in z] + p_z = [(fs2 + p1) / (fs2 - p1) for p1 in p] + + # Any zeros that were at infinity get moved to the Nyquist frequency + z_z.extend([-1] * degree) + + # Compensate for gain change + numer = _prod(fs2 - z1 for z1 in z) + denom = _prod(fs2 - p1 for p1 in p) + k_z = k * numer / denom + + return z_z, p_z, k_z.real + + +def _zpklp2lp(z, p, k, wo=1): + """Transform a lowpass filter to a different cutoff frequency.""" + + degree = _relative_degree(z, p) + + # Scale all points radially from origin to shift cutoff frequency + z_lp = [wo * z1 for z1 in z] + p_lp = [wo * p1 for p1 in p] + + # Each shifted pole decreases gain by wo, each shifted zero increases it. + # Cancel out the net change to keep overall gain the same + k_lp = k * wo**degree + + return z_lp, p_lp, k_lp + + +def _butter_analog_poles(n): + """ + Poles of an analog Butterworth lowpass filter. + + This is the same calculation as scipy.signal.buttap(n) or + scipy.signal.butter(n, 1, analog=True, output='zpk'), but mpmath is used, + and only the poles are returned. + """ + poles = [-mpmath.exp(1j*mpmath.pi*k/(2*n)) for k in range(-n+1, n, 2)] + return poles + + +def butter_lp(n, Wn): + """ + Lowpass Butterworth digital filter design. + + This computes the same result as scipy.signal.butter(n, Wn, output='zpk'), + but it uses mpmath, and the results are returned in lists instead of NumPy + arrays. + """ + zeros = [] + poles = _butter_analog_poles(n) + k = 1 + fs = 2 + warped = 2 * fs * mpmath.tan(mpmath.pi * Wn / fs) + z, p, k = _zpklp2lp(zeros, poles, k, wo=warped) + z, p, k = _zpkbilinear(z, p, k, fs=fs) + return z, p, k + + +def zpkfreqz(z, p, k, worN=None): + """ + Frequency response of a filter in zpk format, using mpmath. + + This is the same calculation as scipy.signal.freqz, but the input is in + zpk format, the calculation is performed using mpath, and the results are + returned in lists instead of NumPy arrays. + """ + if worN is None or isinstance(worN, int): + N = worN or 512 + ws = [mpmath.pi * mpmath.mpf(j) / N for j in range(N)] + else: + ws = worN + + h = [] + for wk in ws: + zm1 = mpmath.exp(1j * wk) + numer = _prod([zm1 - t for t in z]) + denom = _prod([zm1 - t for t in p]) + hk = k * numer / denom + h.append(hk) + return ws, h diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_array_tools.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_array_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..4bda9716e0bc4b6ad3ed0c3954147043b74c421a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_array_tools.py @@ -0,0 +1,111 @@ +import numpy as np + +from scipy._lib._array_api import xp_assert_equal +from pytest import raises as assert_raises + +from scipy.signal._arraytools import (axis_slice, axis_reverse, + odd_ext, even_ext, const_ext, zero_ext) + + +class TestArrayTools: + + def test_axis_slice(self): + a = np.arange(12).reshape(3, 4) + + s = axis_slice(a, start=0, stop=1, axis=0) + xp_assert_equal(s, a[0:1, :]) + + s = axis_slice(a, start=-1, axis=0) + xp_assert_equal(s, a[-1:, :]) + + s = axis_slice(a, start=0, stop=1, axis=1) + xp_assert_equal(s, a[:, 0:1]) + + s = axis_slice(a, start=-1, axis=1) + xp_assert_equal(s, a[:, -1:]) + + s = axis_slice(a, start=0, step=2, axis=0) + xp_assert_equal(s, a[::2, :]) + + s = axis_slice(a, start=0, step=2, axis=1) + xp_assert_equal(s, a[:, ::2]) + + def test_axis_reverse(self): + a = np.arange(12).reshape(3, 4) + + r = axis_reverse(a, axis=0) + xp_assert_equal(r, a[::-1, :]) + + r = axis_reverse(a, axis=1) + xp_assert_equal(r, a[:, ::-1]) + + def test_odd_ext(self): + a = np.array([[1, 2, 3, 4, 5], + [9, 8, 7, 6, 5]]) + + odd = odd_ext(a, 2, axis=1) + expected = np.array([[-1, 0, 1, 2, 3, 4, 5, 6, 7], + [11, 10, 9, 8, 7, 6, 5, 4, 3]]) + xp_assert_equal(odd, expected) + + odd = odd_ext(a, 1, axis=0) + expected = np.array([[-7, -4, -1, 2, 5], + [1, 2, 3, 4, 5], + [9, 8, 7, 6, 5], + [17, 14, 11, 8, 5]]) + xp_assert_equal(odd, expected) + + assert_raises(ValueError, odd_ext, a, 2, axis=0) + assert_raises(ValueError, odd_ext, a, 5, axis=1) + + def test_even_ext(self): + a = np.array([[1, 2, 3, 4, 5], + [9, 8, 7, 6, 5]]) + + even = even_ext(a, 2, axis=1) + expected = np.array([[3, 2, 1, 2, 3, 4, 5, 4, 3], + [7, 8, 9, 8, 7, 6, 5, 6, 7]]) + xp_assert_equal(even, expected) + + even = even_ext(a, 1, axis=0) + expected = np.array([[9, 8, 7, 6, 5], + [1, 2, 3, 4, 5], + [9, 8, 7, 6, 5], + [1, 2, 3, 4, 5]]) + xp_assert_equal(even, expected) + + assert_raises(ValueError, even_ext, a, 2, axis=0) + assert_raises(ValueError, even_ext, a, 5, axis=1) + + def test_const_ext(self): + a = np.array([[1, 2, 3, 4, 5], + [9, 8, 7, 6, 5]]) + + const = const_ext(a, 2, axis=1) + expected = np.array([[1, 1, 1, 2, 3, 4, 5, 5, 5], + [9, 9, 9, 8, 7, 6, 5, 5, 5]]) + xp_assert_equal(const, expected) + + const = const_ext(a, 1, axis=0) + expected = np.array([[1, 2, 3, 4, 5], + [1, 2, 3, 4, 5], + [9, 8, 7, 6, 5], + [9, 8, 7, 6, 5]]) + xp_assert_equal(const, expected) + + def test_zero_ext(self): + a = np.array([[1, 2, 3, 4, 5], + [9, 8, 7, 6, 5]]) + + zero = zero_ext(a, 2, axis=1) + expected = np.array([[0, 0, 1, 2, 3, 4, 5, 0, 0], + [0, 0, 9, 8, 7, 6, 5, 0, 0]]) + xp_assert_equal(zero, expected) + + zero = zero_ext(a, 1, axis=0) + expected = np.array([[0, 0, 0, 0, 0], + [1, 2, 3, 4, 5], + [9, 8, 7, 6, 5], + [0, 0, 0, 0, 0]]) + xp_assert_equal(zero, expected) + diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_bsplines.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_bsplines.py new file mode 100644 index 0000000000000000000000000000000000000000..9c7baf2d8d9f2f9a84452965c35b5262ca20105d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_bsplines.py @@ -0,0 +1,330 @@ +# pylint: disable=missing-docstring +import numpy as np + +from scipy._lib._array_api import ( + assert_almost_equal, xp_assert_close, xp_assert_equal +) +import pytest +from pytest import raises + +import scipy.signal._spline_filters as bsp +from scipy import signal + + +class TestBSplines: + """Test behaviors of B-splines. Some of the values tested against were + returned as of SciPy 1.1.0 and are included for regression testing + purposes. Others (at integer points) are compared to theoretical + expressions (cf. Unser, Aldroubi, Eden, IEEE TSP 1993, Table 1).""" + + def test_spline_filter(self): + rng = np.random.RandomState(12457) + # Test the type-error branch + raises(TypeError, bsp.spline_filter, np.asarray([0]), 0) + # Test the real branch + data_array_real = rng.rand(12, 12) + # make the magnitude exceed 1, and make some negative + data_array_real = 10*(1-2*data_array_real) + result_array_real = np.asarray( + [[-.463312621, 8.33391222, .697290949, 5.28390836, + 5.92066474, 6.59452137, 9.84406950, -8.78324188, + 7.20675750, -8.17222994, -4.38633345, 9.89917069], + [2.67755154, 6.24192170, -3.15730578, 9.87658581, + -9.96930425, 3.17194115, -4.50919947, 5.75423446, + 9.65979824, -8.29066885, .971416087, -2.38331897], + [-7.08868346, 4.89887705, -1.37062289, 7.70705838, + 2.51526461, 3.65885497, 5.16786604, -8.77715342e-03, + 4.10533325, 9.04761993, -.577960351, 9.86382519], + [-4.71444301, -1.68038985, 2.84695116, 1.14315938, + -3.17127091, 1.91830461, 7.13779687, -5.35737482, + -9.66586425, -9.87717456, 9.93160672, 4.71948144], + [9.49551194, -1.92958436, 6.25427993, -9.05582911, + 3.97562282, 7.68232426, -1.04514824, -5.86021443, + -8.43007451, 5.47528997, 2.06330736, -8.65968112], + [-8.91720100, 8.87065356, 3.76879937, 2.56222894, + -.828387146, 8.72288903, 6.42474741, -6.84576083, + 9.94724115, 6.90665380, -6.61084494, -9.44907391], + [9.25196790, -.774032030, 7.05371046, -2.73505725, + 2.53953305, -1.82889155, 2.95454824, -1.66362046, + 5.72478916, -3.10287679, 1.54017123, -7.87759020], + [-3.98464539, -2.44316992, -1.12708657, 1.01725672, + -8.89294671, -5.42145629, -6.16370321, 2.91775492, + 9.64132208, .702499998, -2.02622392, 1.56308431], + [-2.22050773, 7.89951554, 5.98970713, -7.35861835, + 5.45459283, -7.76427957, 3.67280490, -4.05521315, + 4.51967507, -3.22738749, -3.65080177, 3.05630155], + [-6.21240584, -.296796126, -8.34800163, 9.21564563, + -3.61958784, -4.77120006, -3.99454057, 1.05021988e-03, + -6.95982829, 6.04380797, 8.43181250, -2.71653339], + [1.19638037, 6.99718842e-02, 6.72020394, -2.13963198, + 3.75309875, -5.70076744, 5.92143551, -7.22150575, + -3.77114594, -1.11903194, -5.39151466, 3.06620093], + [9.86326886, 1.05134482, -7.75950607, -3.64429655, + 7.81848957, -9.02270373, 3.73399754, -4.71962549, + -7.71144306, 3.78263161, 6.46034818, -4.43444731]]) + xp_assert_close(bsp.spline_filter(data_array_real, 0), + result_array_real) + + def test_spline_filter_complex(self): + rng = np.random.RandomState(12457) + data_array_complex = rng.rand(7, 7) + rng.rand(7, 7)*1j + # make the magnitude exceed 1, and make some negative + data_array_complex = 10*(1+1j-2*data_array_complex) + result_array_complex = np.asarray( + [[-4.61489230e-01-1.92994022j, 8.33332443+6.25519943j, + 6.96300745e-01-9.05576038j, 5.28294849+3.97541356j, + 5.92165565+7.68240595j, 6.59493160-1.04542804j, + 9.84503460-5.85946894j], + [-8.78262329-8.4295969j, 7.20675516+5.47528982j, + -8.17223072+2.06330729j, -4.38633347-8.65968037j, + 9.89916801-8.91720295j, 2.67755103+8.8706522j, + 6.24192142+3.76879835j], + [-3.15627527+2.56303072j, 9.87658501-0.82838702j, + -9.96930313+8.72288895j, 3.17193985+6.42474651j, + -4.50919819-6.84576082j, 5.75423431+9.94723988j, + 9.65979767+6.90665293j], + [-8.28993416-6.61064005j, 9.71416473e-01-9.44907284j, + -2.38331890+9.25196648j, -7.08868170-0.77403212j, + 4.89887714+7.05371094j, -1.37062311-2.73505688j, + 7.70705748+2.5395329j], + [2.51528406-1.82964492j, 3.65885472+2.95454836j, + 5.16786575-1.66362023j, -8.77737999e-03+5.72478867j, + 4.10533333-3.10287571j, 9.04761887+1.54017115j, + -5.77960968e-01-7.87758923j], + [9.86398506-3.98528528j, -4.71444130-2.44316983j, + -1.68038976-1.12708664j, 2.84695053+1.01725709j, + 1.14315915-8.89294529j, -3.17127085-5.42145538j, + 1.91830420-6.16370344j], + [7.13875294+2.91851187j, -5.35737514+9.64132309j, + -9.66586399+0.70250005j, -9.87717438-2.0262239j, + 9.93160629+1.5630846j, 4.71948051-2.22050714j, + 9.49550819+7.8995142j]]) + # FIXME: for complex types, the computations are done in + # single precision (reason unclear). When this is changed, + # this test needs updating. + xp_assert_close(bsp.spline_filter(data_array_complex, 0), + result_array_complex, rtol=1e-6) + + def test_gauss_spline(self): + np.random.seed(12459) + assert_almost_equal(bsp.gauss_spline(0, 0), 1.381976597885342) + xp_assert_close(bsp.gauss_spline(np.asarray([1.]), 1), + np.asarray([0.04865217]), atol=1e-9 + ) + + def test_gauss_spline_list(self): + # regression test for gh-12152 (accept array_like) + knots = [-1.0, 0.0, -1.0] + assert_almost_equal(bsp.gauss_spline(knots, 3), + np.asarray([0.15418033, 0.6909883, 0.15418033]) + ) + + def test_cspline1d(self): + np.random.seed(12462) + xp_assert_equal(bsp.cspline1d(np.asarray([0])), [0.]) + c1d = np.asarray([1.21037185, 1.86293902, 2.98834059, 4.11660378, + 4.78893826]) + # test lamda != 0 + xp_assert_close(bsp.cspline1d(np.asarray([1., 2, 3, 4, 5]), 1), c1d) + c1d0 = np.asarray([0.78683946, 2.05333735, 2.99981113, 3.94741812, + 5.21051638]) + xp_assert_close(bsp.cspline1d(np.asarray([1., 2, 3, 4, 5])), c1d0) + + def test_qspline1d(self): + np.random.seed(12463) + xp_assert_equal(bsp.qspline1d(np.asarray([0])), [0.]) + # test lamda != 0 + raises(ValueError, bsp.qspline1d, np.asarray([1., 2, 3, 4, 5]), 1.) + raises(ValueError, bsp.qspline1d, np.asarray([1., 2, 3, 4, 5]), -1.) + q1d0 = np.asarray([0.85350007, 2.02441743, 2.99999534, 3.97561055, + 5.14634135]) + xp_assert_close(bsp.qspline1d(np.asarray([1., 2, 3, 4, 5])), q1d0) + + def test_cspline1d_eval(self): + np.random.seed(12464) + xp_assert_close(bsp.cspline1d_eval(np.asarray([0., 0]), [0.]), + np.asarray([0.]) + ) + xp_assert_equal(bsp.cspline1d_eval(np.asarray([1., 0, 1]), []), + np.asarray([]) + ) + x = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6] + dx = x[1] - x[0] + newx = [-6., -5.5, -5., -4.5, -4., -3.5, -3., -2.5, -2., -1.5, -1., + -0.5, 0., 0.5, 1., 1.5, 2., 2.5, 3., 3.5, 4., 4.5, 5., 5.5, 6., + 6.5, 7., 7.5, 8., 8.5, 9., 9.5, 10., 10.5, 11., 11.5, 12., + 12.5] + y = np.asarray([4.216, 6.864, 3.514, 6.203, 6.759, 7.433, 7.874, 5.879, + 1.396, 4.094]) + cj = bsp.cspline1d(y) + newy = np.asarray([6.203, 4.41570658, 3.514, 5.16924703, 6.864, 6.04643068, + 4.21600281, 6.04643068, 6.864, 5.16924703, 3.514, + 4.41570658, 6.203, 6.80717667, 6.759, 6.98971173, 7.433, + 7.79560142, 7.874, 7.41525761, 5.879, 3.18686814, 1.396, + 2.24889482, 4.094, 2.24889482, 1.396, 3.18686814, 5.879, + 7.41525761, 7.874, 7.79560142, 7.433, 6.98971173, 6.759, + 6.80717667, 6.203, 4.41570658]) + xp_assert_close(bsp.cspline1d_eval(cj, newx, dx=dx, x0=x[0]), newy) + + def test_qspline1d_eval(self): + np.random.seed(12465) + xp_assert_close(bsp.qspline1d_eval(np.asarray([0., 0]), [0.]), + np.asarray([0.]) + ) + xp_assert_equal(bsp.qspline1d_eval(np.asarray([1., 0, 1]), []), + np.asarray([]) + ) + x = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6] + dx = x[1]-x[0] + newx = [-6., -5.5, -5., -4.5, -4., -3.5, -3., -2.5, -2., -1.5, -1., + -0.5, 0., 0.5, 1., 1.5, 2., 2.5, 3., 3.5, 4., 4.5, 5., 5.5, 6., + 6.5, 7., 7.5, 8., 8.5, 9., 9.5, 10., 10.5, 11., 11.5, 12., + 12.5] + y = np.asarray([4.216, 6.864, 3.514, 6.203, 6.759, 7.433, 7.874, 5.879, + 1.396, 4.094]) + cj = bsp.qspline1d(y) + newy = np.asarray([6.203, 4.49418159, 3.514, 5.18390821, 6.864, 5.91436915, + 4.21600002, 5.91436915, 6.864, 5.18390821, 3.514, + 4.49418159, 6.203, 6.71900226, 6.759, 7.03980488, 7.433, + 7.81016848, 7.874, 7.32718426, 5.879, 3.23872593, 1.396, + 2.34046013, 4.094, 2.34046013, 1.396, 3.23872593, 5.879, + 7.32718426, 7.874, 7.81016848, 7.433, 7.03980488, 6.759, + 6.71900226, 6.203, 4.49418159]) + xp_assert_close(bsp.qspline1d_eval(cj, newx, dx=dx, x0=x[0]), newy) + + +# i/o dtypes with scipy 1.9.1, likely fixed by backwards compat +sepfir_dtype_map = {np.uint8: np.float32, int: np.float64, + np.float32: np.float32, float: float, + np.complex64: np.complex64, complex: complex} + +class TestSepfir2d: + def test_sepfir2d_invalid_filter(self): + filt = np.array([1.0, 2.0, 4.0, 2.0, 1.0]) + image = np.random.rand(7, 9) + # No error for odd lengths + signal.sepfir2d(image, filt, filt[2:]) + + # Row or column filter must be odd + with pytest.raises(ValueError, match="odd length"): + signal.sepfir2d(image, filt, filt[1:]) + with pytest.raises(ValueError, match="odd length"): + signal.sepfir2d(image, filt[1:], filt) + + # Filters must be 1-dimensional + with pytest.raises(ValueError, match="object too deep"): + signal.sepfir2d(image, filt.reshape(1, -1), filt) + with pytest.raises(ValueError, match="object too deep"): + signal.sepfir2d(image, filt, filt.reshape(1, -1)) + + def test_sepfir2d_invalid_image(self): + filt = np.array([1.0, 2.0, 4.0, 2.0, 1.0]) + image = np.random.rand(8, 8) + + # Image must be 2 dimensional + with pytest.raises(ValueError, match="object too deep"): + signal.sepfir2d(image.reshape(4, 4, 4), filt, filt) + + with pytest.raises(ValueError, match="object of too small depth"): + signal.sepfir2d(image[0], filt, filt) + + @pytest.mark.parametrize('dtyp', + [np.uint8, int, np.float32, float, np.complex64, complex] + ) + def test_simple(self, dtyp): + # test values on a paper-and-pencil example + a = np.array([[1, 2, 3, 3, 2, 1], + [1, 2, 3, 3, 2, 1], + [1, 2, 3, 3, 2, 1], + [1, 2, 3, 3, 2, 1]], dtype=dtyp) + h1 = [0.5, 1, 0.5] + h2 = [1] + result = signal.sepfir2d(a, h1, h2) + dt = sepfir_dtype_map[dtyp] + expected = np.asarray([[2.5, 4. , 5.5, 5.5, 4. , 2.5], + [2.5, 4. , 5.5, 5.5, 4. , 2.5], + [2.5, 4. , 5.5, 5.5, 4. , 2.5], + [2.5, 4. , 5.5, 5.5, 4. , 2.5]], dtype=dt) + xp_assert_close(result, expected, atol=1e-16) + + result = signal.sepfir2d(a, h2, h1) + expected = np.asarray([[2., 4., 6., 6., 4., 2.], + [2., 4., 6., 6., 4., 2.], + [2., 4., 6., 6., 4., 2.], + [2., 4., 6., 6., 4., 2.]], dtype=dt) + xp_assert_close(result, expected, atol=1e-16) + + @pytest.mark.parametrize('dtyp', + [np.uint8, int, np.float32, float, np.complex64, complex] + ) + def test_strided(self, dtyp): + a = np.array([[1, 2, 3, 3, 2, 1, 1, 2, 3], + [1, 2, 3, 3, 2, 1, 1, 2, 3], + [1, 2, 3, 3, 2, 1, 1, 2, 3], + [1, 2, 3, 3, 2, 1, 1, 2, 3]]) + h1, h2 = [0.5, 1, 0.5], [1] + result_strided = signal.sepfir2d(a[:, ::2], h1, h2) + result_contig = signal.sepfir2d(a[:, ::2].copy(), h1, h2) + xp_assert_close(result_strided, result_contig, atol=1e-15) + assert result_strided.dtype == result_contig.dtype + + @pytest.mark.xfail(reason="XXX: filt.size > image.shape: flaky") + def test_sepfir2d_strided_2(self): + # XXX: this test is flaky: fails on some reruns, with + # result[0, 1] and result[1, 1] being ~1e+224. + np.random.seed(1234) + filt = np.array([1.0, 2.0, 4.0, 2.0, 1.0, 3.0, 2.0]) + image = np.random.rand(4, 4) + + expected = np.asarray([[36.018162, 30.239061, 38.71187 , 43.878183], + [38.180999, 35.824583, 43.525247, 43.874945], + [43.269533, 40.834018, 46.757772, 44.276423], + [49.120928, 39.681844, 43.596067, 45.085854]]) + xp_assert_close(signal.sepfir2d(image, filt, filt[::3]), expected) + + @pytest.mark.xfail(reason="XXX: flaky. pointers OOB on some platforms") + @pytest.mark.parametrize('dtyp', + [np.uint8, int, np.float32, float, np.complex64, complex] + ) + def test_sepfir2d_strided_3(self, dtyp): + # NB: 'image' and 'filt' dtypes match here. Otherwise we can run into + # unsafe casting errors for many combinations. Historically, dtype handling + # in `sepfir2d` is a tad baroque; fixing it is an enhancement. + filt = np.array([1, 2, 4, 2, 1, 3, 2], dtype=dtyp) + image = np.asarray([[0, 3, 0, 1, 2], + [2, 2, 3, 3, 3], + [0, 1, 3, 0, 3], + [2, 3, 0, 1, 3], + [3, 3, 2, 1, 2]], dtype=dtyp) + + expected = [[123., 101., 91., 136., 127.], + [133., 125., 126., 152., 160.], + [136., 137., 150., 162., 177.], + [133., 124., 132., 148., 147.], + [173., 158., 152., 164., 141.]] + expected = np.asarray(expected) + result = signal.sepfir2d(image, filt, filt[::3]) + xp_assert_close(result, expected, atol=1e-15) + assert result.dtype == sepfir_dtype_map[dtyp] + + expected = [[22., 35., 41., 31., 47.], + [27., 39., 48., 47., 55.], + [33., 42., 49., 53., 59.], + [39., 44., 41., 36., 48.], + [67., 62., 47., 34., 46.]] + expected = np.asarray(expected) + result = signal.sepfir2d(image, filt[::3], filt[::3]) + xp_assert_close(result, expected, atol=1e-15) + assert result.dtype == sepfir_dtype_map[dtyp] + + +def test_cspline2d(): + np.random.seed(181819142) + image = np.random.rand(71, 73) + signal.cspline2d(image, 8.0) + + +def test_qspline2d(): + np.random.seed(181819143) + image = np.random.rand(71, 73) + signal.qspline2d(image) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_cont2discrete.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_cont2discrete.py new file mode 100644 index 0000000000000000000000000000000000000000..0b4008afd4728acb5b63a6626440b214f2d90f6f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_cont2discrete.py @@ -0,0 +1,417 @@ +import numpy as np +from scipy._lib._array_api import ( + assert_array_almost_equal, assert_almost_equal, xp_assert_close +) + +import pytest +from scipy.signal import cont2discrete as c2d +from scipy.signal import dlsim, ss2tf, ss2zpk, lsim, lti +from scipy.signal import tf2ss, impulse, dimpulse, step, dstep + +# Author: Jeffrey Armstrong +# March 29, 2011 + + +class TestC2D: + @pytest.mark.thread_unsafe # due to Cython fused types, see cython#6506 + def test_zoh(self): + ac = np.eye(2, dtype=np.float64) + bc = np.full((2, 1), 0.5, dtype=np.float64) + cc = np.array([[0.75, 1.0], [1.0, 1.0], [1.0, 0.25]]) + dc = np.array([[0.0], [0.0], [-0.33]]) + + ad_truth = 1.648721270700128 * np.eye(2) + bd_truth = np.full((2, 1), 0.324360635350064) + # c and d in discrete should be equal to their continuous counterparts + dt_requested = 0.5 + + ad, bd, cd, dd, dt = c2d((ac, bc, cc, dc), dt_requested, method='zoh') + + assert_array_almost_equal(ad_truth, ad) + assert_array_almost_equal(bd_truth, bd) + assert_array_almost_equal(cc, cd) + assert_array_almost_equal(dc, dd) + assert_almost_equal(dt_requested, dt) + + def test_foh(self): + ac = np.eye(2) + bc = np.full((2, 1), 0.5) + cc = np.array([[0.75, 1.0], [1.0, 1.0], [1.0, 0.25]]) + dc = np.array([[0.0], [0.0], [-0.33]]) + + # True values are verified with Matlab + ad_truth = 1.648721270700128 * np.eye(2) + bd_truth = np.full((2, 1), 0.420839287058789) + cd_truth = cc + dd_truth = np.array([[0.260262223725224], + [0.297442541400256], + [-0.144098411624840]]) + dt_requested = 0.5 + + ad, bd, cd, dd, dt = c2d((ac, bc, cc, dc), dt_requested, method='foh') + + assert_array_almost_equal(ad_truth, ad) + assert_array_almost_equal(bd_truth, bd) + assert_array_almost_equal(cd_truth, cd) + assert_array_almost_equal(dd_truth, dd) + assert_almost_equal(dt_requested, dt) + + def test_impulse(self): + ac = np.eye(2) + bc = np.full((2, 1), 0.5) + cc = np.array([[0.75, 1.0], [1.0, 1.0], [1.0, 0.25]]) + dc = np.array([[0.0], [0.0], [0.0]]) + + # True values are verified with Matlab + ad_truth = 1.648721270700128 * np.eye(2) + bd_truth = np.full((2, 1), 0.412180317675032) + cd_truth = cc + dd_truth = np.array([[0.4375], [0.5], [0.3125]]) + dt_requested = 0.5 + + ad, bd, cd, dd, dt = c2d((ac, bc, cc, dc), dt_requested, + method='impulse') + + assert_array_almost_equal(ad_truth, ad) + assert_array_almost_equal(bd_truth, bd) + assert_array_almost_equal(cd_truth, cd) + assert_array_almost_equal(dd_truth, dd) + assert_almost_equal(dt_requested, dt) + + def test_gbt(self): + ac = np.eye(2) + bc = np.full((2, 1), 0.5) + cc = np.array([[0.75, 1.0], [1.0, 1.0], [1.0, 0.25]]) + dc = np.array([[0.0], [0.0], [-0.33]]) + + dt_requested = 0.5 + alpha = 1.0 / 3.0 + + ad_truth = 1.6 * np.eye(2) + bd_truth = np.full((2, 1), 0.3) + cd_truth = np.array([[0.9, 1.2], + [1.2, 1.2], + [1.2, 0.3]]) + dd_truth = np.array([[0.175], + [0.2], + [-0.205]]) + + ad, bd, cd, dd, dt = c2d((ac, bc, cc, dc), dt_requested, + method='gbt', alpha=alpha) + + assert_array_almost_equal(ad_truth, ad) + assert_array_almost_equal(bd_truth, bd) + assert_array_almost_equal(cd_truth, cd) + assert_array_almost_equal(dd_truth, dd) + + def test_euler(self): + ac = np.eye(2) + bc = np.full((2, 1), 0.5) + cc = np.array([[0.75, 1.0], [1.0, 1.0], [1.0, 0.25]]) + dc = np.array([[0.0], [0.0], [-0.33]]) + + dt_requested = 0.5 + + ad_truth = 1.5 * np.eye(2) + bd_truth = np.full((2, 1), 0.25) + cd_truth = np.array([[0.75, 1.0], + [1.0, 1.0], + [1.0, 0.25]]) + dd_truth = dc + + ad, bd, cd, dd, dt = c2d((ac, bc, cc, dc), dt_requested, + method='euler') + + assert_array_almost_equal(ad_truth, ad) + assert_array_almost_equal(bd_truth, bd) + assert_array_almost_equal(cd_truth, cd) + assert_array_almost_equal(dd_truth, dd) + assert_almost_equal(dt_requested, dt) + + def test_backward_diff(self): + ac = np.eye(2) + bc = np.full((2, 1), 0.5) + cc = np.array([[0.75, 1.0], [1.0, 1.0], [1.0, 0.25]]) + dc = np.array([[0.0], [0.0], [-0.33]]) + + dt_requested = 0.5 + + ad_truth = 2.0 * np.eye(2) + bd_truth = np.full((2, 1), 0.5) + cd_truth = np.array([[1.5, 2.0], + [2.0, 2.0], + [2.0, 0.5]]) + dd_truth = np.array([[0.875], + [1.0], + [0.295]]) + + ad, bd, cd, dd, dt = c2d((ac, bc, cc, dc), dt_requested, + method='backward_diff') + + assert_array_almost_equal(ad_truth, ad) + assert_array_almost_equal(bd_truth, bd) + assert_array_almost_equal(cd_truth, cd) + assert_array_almost_equal(dd_truth, dd) + + def test_bilinear(self): + ac = np.eye(2) + bc = np.full((2, 1), 0.5) + cc = np.array([[0.75, 1.0], [1.0, 1.0], [1.0, 0.25]]) + dc = np.array([[0.0], [0.0], [-0.33]]) + + dt_requested = 0.5 + + ad_truth = (5.0 / 3.0) * np.eye(2) + bd_truth = np.full((2, 1), 1.0 / 3.0) + cd_truth = np.array([[1.0, 4.0 / 3.0], + [4.0 / 3.0, 4.0 / 3.0], + [4.0 / 3.0, 1.0 / 3.0]]) + dd_truth = np.array([[0.291666666666667], + [1.0 / 3.0], + [-0.121666666666667]]) + + ad, bd, cd, dd, dt = c2d((ac, bc, cc, dc), dt_requested, + method='bilinear') + + assert_array_almost_equal(ad_truth, ad) + assert_array_almost_equal(bd_truth, bd) + assert_array_almost_equal(cd_truth, cd) + assert_array_almost_equal(dd_truth, dd) + assert_almost_equal(dt_requested, dt) + + # Same continuous system again, but change sampling rate + + ad_truth = 1.4 * np.eye(2) + bd_truth = np.full((2, 1), 0.2) + cd_truth = np.array([[0.9, 1.2], [1.2, 1.2], [1.2, 0.3]]) + dd_truth = np.array([[0.175], [0.2], [-0.205]]) + + dt_requested = 1.0 / 3.0 + + ad, bd, cd, dd, dt = c2d((ac, bc, cc, dc), dt_requested, + method='bilinear') + + assert_array_almost_equal(ad_truth, ad) + assert_array_almost_equal(bd_truth, bd) + assert_array_almost_equal(cd_truth, cd) + assert_array_almost_equal(dd_truth, dd) + assert_almost_equal(dt_requested, dt) + + def test_transferfunction(self): + numc = np.array([0.25, 0.25, 0.5]) + denc = np.array([0.75, 0.75, 1.0]) + + numd = np.array([[1.0 / 3.0, -0.427419169438754, 0.221654141101125]]) + dend = np.array([1.0, -1.351394049721225, 0.606530659712634]) + + dt_requested = 0.5 + + num, den, dt = c2d((numc, denc), dt_requested, method='zoh') + + assert_array_almost_equal(numd, num) + assert_array_almost_equal(dend, den) + assert_almost_equal(dt_requested, dt) + + def test_zerospolesgain(self): + zeros_c = np.array([0.5, -0.5]) + poles_c = np.array([1.j / np.sqrt(2), -1.j / np.sqrt(2)]) + k_c = 1.0 + + zeros_d = [1.23371727305860, 0.735356894461267] + polls_d = [0.938148335039729 + 0.346233593780536j, + 0.938148335039729 - 0.346233593780536j] + k_d = 1.0 + + dt_requested = 0.5 + + zeros, poles, k, dt = c2d((zeros_c, poles_c, k_c), dt_requested, + method='zoh') + + assert_array_almost_equal(zeros_d, zeros) + assert_array_almost_equal(polls_d, poles) + assert_almost_equal(k_d, k) + assert_almost_equal(dt_requested, dt) + + def test_gbt_with_sio_tf_and_zpk(self): + """Test method='gbt' with alpha=0.25 for tf and zpk cases.""" + # State space coefficients for the continuous SIO system. + A = -1.0 + B = 1.0 + C = 1.0 + D = 0.5 + + # The continuous transfer function coefficients. + cnum, cden = ss2tf(A, B, C, D) + + # Continuous zpk representation + cz, cp, ck = ss2zpk(A, B, C, D) + + h = 1.0 + alpha = 0.25 + + # Explicit formulas, in the scalar case. + Ad = (1 + (1 - alpha) * h * A) / (1 - alpha * h * A) + Bd = h * B / (1 - alpha * h * A) + Cd = C / (1 - alpha * h * A) + Dd = D + alpha * C * Bd + + # Convert the explicit solution to tf + dnum, dden = ss2tf(Ad, Bd, Cd, Dd) + + # Compute the discrete tf using cont2discrete. + c2dnum, c2dden, dt = c2d((cnum, cden), h, method='gbt', alpha=alpha) + + xp_assert_close(dnum, c2dnum) + xp_assert_close(dden, c2dden) + + # Convert explicit solution to zpk. + dz, dp, dk = ss2zpk(Ad, Bd, Cd, Dd) + + # Compute the discrete zpk using cont2discrete. + c2dz, c2dp, c2dk, dt = c2d((cz, cp, ck), h, method='gbt', alpha=alpha) + + xp_assert_close(dz, c2dz) + xp_assert_close(dp, c2dp) + xp_assert_close(dk, c2dk) + + def test_discrete_approx(self): + """ + Test that the solution to the discrete approximation of a continuous + system actually approximates the solution to the continuous system. + This is an indirect test of the correctness of the implementation + of cont2discrete. + """ + + def u(t): + return np.sin(2.5 * t) + + a = np.array([[-0.01]]) + b = np.array([[1.0]]) + c = np.array([[1.0]]) + d = np.array([[0.2]]) + x0 = 1.0 + + t = np.linspace(0, 10.0, 101) + dt = t[1] - t[0] + u1 = u(t) + + # Use lsim to compute the solution to the continuous system. + t, yout, xout = lsim((a, b, c, d), T=t, U=u1, X0=x0) + + # Convert the continuous system to a discrete approximation. + dsys = c2d((a, b, c, d), dt, method='bilinear') + + # Use dlsim with the pairwise averaged input to compute the output + # of the discrete system. + u2 = 0.5 * (u1[:-1] + u1[1:]) + t2 = t[:-1] + td2, yd2, xd2 = dlsim(dsys, u=u2.reshape(-1, 1), t=t2, x0=x0) + + # ymid is the average of consecutive terms of the "exact" output + # computed by lsim2. This is what the discrete approximation + # actually approximates. + ymid = 0.5 * (yout[:-1] + yout[1:]) + + xp_assert_close(yd2.ravel(), ymid, rtol=1e-4) + + def test_simo_tf(self): + # See gh-5753 + tf = ([[1, 0], [1, 1]], [1, 1]) + num, den, dt = c2d(tf, 0.01) + + assert dt == 0.01 # sanity check + xp_assert_close(den, [1, -0.990404983], rtol=1e-3) + xp_assert_close(num, [[1, -1], [1, -0.99004983]], rtol=1e-3) + + def test_multioutput(self): + ts = 0.01 # time step + + tf = ([[1, -3], [1, 5]], [1, 1]) + num, den, dt = c2d(tf, ts) + + tf1 = (tf[0][0], tf[1]) + num1, den1, dt1 = c2d(tf1, ts) + + tf2 = (tf[0][1], tf[1]) + num2, den2, dt2 = c2d(tf2, ts) + + # Sanity checks + assert dt == dt1 + assert dt == dt2 + + # Check that we get the same results + xp_assert_close(num, np.vstack((num1, num2)), rtol=1e-13) + + # Single input, so the denominator should + # not be multidimensional like the numerator + xp_assert_close(den, den1, rtol=1e-13) + xp_assert_close(den, den2, rtol=1e-13) + +class TestC2dLti: + def test_c2d_ss(self): + # StateSpace + A = np.array([[-0.3, 0.1], [0.2, -0.7]]) + B = np.array([[0], [1]]) + C = np.array([[1, 0]]) + D = 0 + + A_res = np.array([[0.985136404135682, 0.004876671474795], + [0.009753342949590, 0.965629718236502]]) + B_res = np.array([[0.000122937599964], [0.049135527547844]]) + + sys_ssc = lti(A, B, C, D) + sys_ssd = sys_ssc.to_discrete(0.05) + + xp_assert_close(sys_ssd.A, A_res) + xp_assert_close(sys_ssd.B, B_res) + xp_assert_close(sys_ssd.C, C) + xp_assert_close(sys_ssd.D, np.zeros_like(sys_ssd.D)) + + def test_c2d_tf(self): + + sys = lti([0.5, 0.3], [1.0, 0.4]) + sys = sys.to_discrete(0.005) + + # Matlab results + num_res = np.array([0.5, -0.485149004980066]) + den_res = np.array([1.0, -0.980198673306755]) + + # Somehow a lot of numerical errors + xp_assert_close(sys.den, den_res, atol=0.02) + xp_assert_close(sys.num, num_res, atol=0.02) + + +class TestC2dInvariants: + # Some test cases for checking the invariances. + # Array of triplets: (system, sample time, number of samples) + cases = [ + (tf2ss([1, 1], [1, 1.5, 1]), 0.25, 10), + (tf2ss([1, 2], [1, 1.5, 3, 1]), 0.5, 10), + (tf2ss(0.1, [1, 1, 2, 1]), 0.5, 10), + ] + + # Check that systems discretized with the impulse-invariant + # method really hold the invariant + @pytest.mark.parametrize("sys,sample_time,samples_number", cases) + def test_impulse_invariant(self, sys, sample_time, samples_number): + time = np.arange(samples_number) * sample_time + _, yout_cont = impulse(sys, T=time) + _, yout_disc = dimpulse(c2d(sys, sample_time, method='impulse'), + n=len(time)) + xp_assert_close(sample_time * yout_cont.ravel(), yout_disc[0].ravel()) + + # Step invariant should hold for ZOH discretized systems + @pytest.mark.parametrize("sys,sample_time,samples_number", cases) + def test_step_invariant(self, sys, sample_time, samples_number): + time = np.arange(samples_number) * sample_time + _, yout_cont = step(sys, T=time) + _, yout_disc = dstep(c2d(sys, sample_time, method='zoh'), n=len(time)) + xp_assert_close(yout_cont.ravel(), yout_disc[0].ravel()) + + # Linear invariant should hold for FOH discretized systems + @pytest.mark.parametrize("sys,sample_time,samples_number", cases) + def test_linear_invariant(self, sys, sample_time, samples_number): + time = np.arange(samples_number) * sample_time + _, yout_cont, _ = lsim(sys, T=time, U=time) + _, yout_disc, _ = dlsim(c2d(sys, sample_time, method='foh'), u=time) + xp_assert_close(yout_cont.ravel(), yout_disc.ravel()) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_czt.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_czt.py new file mode 100644 index 0000000000000000000000000000000000000000..35087d99fec5057131f0735d43e0faa33a74ef82 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_czt.py @@ -0,0 +1,221 @@ +# This program is public domain +# Authors: Paul Kienzle, Nadav Horesh +''' +A unit test module for czt.py +''' +import pytest +from scipy._lib._array_api import xp_assert_close +from scipy.fft import fft +from scipy.signal import (czt, zoom_fft, czt_points, CZT, ZoomFFT) +import numpy as np + + +def check_czt(x): + # Check that czt is the equivalent of normal fft + y = fft(x) + y1 = czt(x) + xp_assert_close(y1, y, rtol=1e-13) + + # Check that interpolated czt is the equivalent of normal fft + y = fft(x, 100*len(x)) + y1 = czt(x, 100*len(x)) + xp_assert_close(y1, y, rtol=1e-12) + + +def check_zoom_fft(x): + # Check that zoom_fft is the equivalent of normal fft + y = fft(x) + y1 = zoom_fft(x, [0, 2-2./len(y)], endpoint=True) + xp_assert_close(y1, y, rtol=1e-11, atol=1e-14) + y1 = zoom_fft(x, [0, 2]) + xp_assert_close(y1, y, rtol=1e-11, atol=1e-14) + + # Test fn scalar + y1 = zoom_fft(x, 2-2./len(y), endpoint=True) + xp_assert_close(y1, y, rtol=1e-11, atol=1e-14) + y1 = zoom_fft(x, 2) + xp_assert_close(y1, y, rtol=1e-11, atol=1e-14) + + # Check that zoom_fft with oversampling is equivalent to zero padding + over = 10 + yover = fft(x, over*len(x)) + y2 = zoom_fft(x, [0, 2-2./len(yover)], m=len(yover), endpoint=True) + xp_assert_close(y2, yover, rtol=1e-12, atol=1e-10) + y2 = zoom_fft(x, [0, 2], m=len(yover)) + xp_assert_close(y2, yover, rtol=1e-12, atol=1e-10) + + # Check that zoom_fft works on a subrange + w = np.linspace(0, 2-2./len(x), len(x)) + f1, f2 = w[3], w[6] + y3 = zoom_fft(x, [f1, f2], m=3*over+1, endpoint=True) + idx3 = slice(3*over, 6*over+1) + xp_assert_close(y3, yover[idx3], rtol=1e-13) + + +def test_1D(): + # Test of 1D version of the transforms + + rng = np.random.RandomState(0) # Deterministic randomness + + # Random signals + lengths = rng.randint(8, 200, 20) + np.append(lengths, 1) + for length in lengths: + x = rng.random(length) + check_zoom_fft(x) + check_czt(x) + + # Gauss + t = np.linspace(-2, 2, 128) + x = np.exp(-t**2/0.01) + check_zoom_fft(x) + + # Linear + x = [1, 2, 3, 4, 5, 6, 7] + check_zoom_fft(x) + + # Check near powers of two + check_zoom_fft(range(126-31)) + check_zoom_fft(range(127-31)) + check_zoom_fft(range(128-31)) + check_zoom_fft(range(129-31)) + check_zoom_fft(range(130-31)) + + # Check transform on n-D array input + x = np.reshape(np.arange(3*2*28), (3, 2, 28)) + y1 = zoom_fft(x, [0, 2-2./28]) + y2 = zoom_fft(x[2, 0, :], [0, 2-2./28]) + xp_assert_close(y1[2, 0], y2, rtol=1e-13, atol=1e-12) + + y1 = zoom_fft(x, [0, 2], endpoint=False) + y2 = zoom_fft(x[2, 0, :], [0, 2], endpoint=False) + xp_assert_close(y1[2, 0], y2, rtol=1e-13, atol=1e-12) + + # Random (not a test condition) + x = rng.rand(101) + check_zoom_fft(x) + + # Spikes + t = np.linspace(0, 1, 128) + x = np.sin(2*np.pi*t*5)+np.sin(2*np.pi*t*13) + check_zoom_fft(x) + + # Sines + x = np.zeros(100, dtype=complex) + x[[1, 5, 21]] = 1 + check_zoom_fft(x) + + # Sines plus complex component + x += 1j*np.linspace(0, 0.5, x.shape[0]) + check_zoom_fft(x) + + +def test_large_prime_lengths(): + rng = np.random.RandomState(0) # Deterministic randomness + for N in (101, 1009, 10007): + x = rng.rand(N) + y = fft(x) + y1 = czt(x) + xp_assert_close(y, y1, rtol=1e-12) + + +@pytest.mark.slow +def test_czt_vs_fft(): + rng = np.random.RandomState(123) # Deterministic randomness + random_lengths = rng.exponential(100000, size=10).astype('int') + for n in random_lengths: + a = rng.randn(n) + xp_assert_close(czt(a), fft(a), rtol=1e-11) + + +def test_empty_input(): + with pytest.raises(ValueError, match='Invalid number of CZT'): + czt([]) + with pytest.raises(ValueError, match='Invalid number of CZT'): + zoom_fft([], 0.5) + + +def test_0_rank_input(): + with pytest.raises(IndexError, match='tuple index out of range'): + czt(5) + with pytest.raises(IndexError, match='tuple index out of range'): + zoom_fft(5, 0.5) + + +@pytest.mark.parametrize('impulse', ([0, 0, 1], [0, 0, 1, 0, 0], + np.concatenate((np.array([0, 0, 1]), + np.zeros(100))))) +@pytest.mark.parametrize('m', (1, 3, 5, 8, 101, 1021)) +@pytest.mark.parametrize('a', (1, 2, 0.5, 1.1)) +# Step that tests away from the unit circle, but not so far it explodes from +# numerical error +@pytest.mark.parametrize('w', (None, 0.98534 + 0.17055j)) +def test_czt_math(impulse, m, w, a): + # z-transform of an impulse is 1 everywhere + xp_assert_close(czt(impulse[2:], m=m, w=w, a=a), + np.ones(m, dtype=np.complex128), rtol=1e-10) + + # z-transform of a delayed impulse is z**-1 + xp_assert_close(czt(impulse[1:], m=m, w=w, a=a), + czt_points(m=m, w=w, a=a)**-1, rtol=1e-10) + + # z-transform of a 2-delayed impulse is z**-2 + xp_assert_close(czt(impulse, m=m, w=w, a=a), + czt_points(m=m, w=w, a=a)**-2, rtol=1e-10) + + +def test_int_args(): + # Integer argument `a` was producing all 0s + xp_assert_close(abs(czt([0, 1], m=10, a=2)), 0.5*np.ones(10), rtol=1e-15) + xp_assert_close(czt_points(11, w=2), + 1/(2**np.arange(11, dtype=np.complex128)), rtol=1e-30) + + +def test_czt_points(): + for N in (1, 2, 3, 8, 11, 100, 101, 10007): + xp_assert_close(czt_points(N), np.exp(2j*np.pi*np.arange(N)/N), + rtol=1e-30) + + xp_assert_close(czt_points(7, w=1), np.ones(7, dtype=np.complex128), rtol=1e-30) + xp_assert_close(czt_points(11, w=2.), + 1/(2**np.arange(11, dtype=np.complex128)), rtol=1e-30) + + func = CZT(12, m=11, w=2., a=1) + xp_assert_close(func.points(), 1/(2**np.arange(11)), rtol=1e-30) + + +@pytest.mark.parametrize('cls, args', [(CZT, (100,)), (ZoomFFT, (100, 0.2))]) +def test_CZT_size_mismatch(cls, args): + # Data size doesn't match function's expected size + myfunc = cls(*args) + with pytest.raises(ValueError, match='CZT defined for'): + myfunc(np.arange(5)) + + +def test_invalid_range(): + with pytest.raises(ValueError, match='2-length sequence'): + ZoomFFT(100, [1, 2, 3]) + + +@pytest.mark.parametrize('m', [0, -11, 5.5, 4.0]) +def test_czt_points_errors(m): + # Invalid number of points + with pytest.raises(ValueError, match='Invalid number of CZT'): + czt_points(m) + + +@pytest.mark.parametrize('size', [0, -5, 3.5, 4.0]) +def test_nonsense_size(size): + # Numpy and Scipy fft() give ValueError for 0 output size, so we do, too + with pytest.raises(ValueError, match='Invalid number of CZT'): + CZT(size, 3) + with pytest.raises(ValueError, match='Invalid number of CZT'): + ZoomFFT(size, 0.2, 3) + with pytest.raises(ValueError, match='Invalid number of CZT'): + CZT(3, size) + with pytest.raises(ValueError, match='Invalid number of CZT'): + ZoomFFT(3, 0.2, size) + with pytest.raises(ValueError, match='Invalid number of CZT'): + czt([1, 2, 3], size) + with pytest.raises(ValueError, match='Invalid number of CZT'): + zoom_fft([1, 2, 3], 0.2, size) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_dltisys.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_dltisys.py new file mode 100644 index 0000000000000000000000000000000000000000..872541543ba485f3e8a17735bee471875f92fd05 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_dltisys.py @@ -0,0 +1,599 @@ +# Author: Jeffrey Armstrong +# April 4, 2011 + +import numpy as np +from numpy.testing import suppress_warnings +from pytest import raises as assert_raises +from scipy._lib._array_api import ( + assert_array_almost_equal, assert_almost_equal, xp_assert_close, xp_assert_equal, +) + +from scipy.signal import (dlsim, dstep, dimpulse, tf2zpk, lti, dlti, + StateSpace, TransferFunction, ZerosPolesGain, + dfreqresp, dbode, BadCoefficients) + + +class TestDLTI: + + def test_dlsim(self): + + a = np.asarray([[0.9, 0.1], [-0.2, 0.9]]) + b = np.asarray([[0.4, 0.1, -0.1], [0.0, 0.05, 0.0]]) + c = np.asarray([[0.1, 0.3]]) + d = np.asarray([[0.0, -0.1, 0.0]]) + dt = 0.5 + + # Create an input matrix with inputs down the columns (3 cols) and its + # respective time input vector + u = np.hstack((np.linspace(0, 4.0, num=5)[:, np.newaxis], + np.full((5, 1), 0.01), + np.full((5, 1), -0.002))) + t_in = np.linspace(0, 2.0, num=5) + + # Define the known result + yout_truth = np.array([[-0.001, + -0.00073, + 0.039446, + 0.0915387, + 0.13195948]]).T + xout_truth = np.asarray([[0, 0], + [0.0012, 0.0005], + [0.40233, 0.00071], + [1.163368, -0.079327], + [2.2402985, -0.3035679]]) + + tout, yout, xout = dlsim((a, b, c, d, dt), u, t_in) + + assert_array_almost_equal(yout_truth, yout) + assert_array_almost_equal(xout_truth, xout) + assert_array_almost_equal(t_in, tout) + + # Make sure input with single-dimension doesn't raise error + dlsim((1, 2, 3), 4) + + # Interpolated control - inputs should have different time steps + # than the discrete model uses internally + u_sparse = u[[0, 4], :] + t_sparse = np.asarray([0.0, 2.0]) + + tout, yout, xout = dlsim((a, b, c, d, dt), u_sparse, t_sparse) + + assert_array_almost_equal(yout_truth, yout) + assert_array_almost_equal(xout_truth, xout) + assert len(tout) == len(yout) + + # Transfer functions (assume dt = 0.5) + num = np.asarray([1.0, -0.1]) + den = np.asarray([0.3, 1.0, 0.2]) + yout_truth = np.array([[0.0, + 0.0, + 3.33333333333333, + -4.77777777777778, + 23.0370370370370]]).T + + # Assume use of the first column of the control input built earlier + tout, yout = dlsim((num, den, 0.5), u[:, 0], t_in) + + assert_array_almost_equal(yout, yout_truth) + assert_array_almost_equal(t_in, tout) + + # Retest the same with a 1-D input vector + uflat = np.asarray(u[:, 0]) + uflat = uflat.reshape((5,)) + tout, yout = dlsim((num, den, 0.5), uflat, t_in) + + assert_array_almost_equal(yout, yout_truth) + assert_array_almost_equal(t_in, tout) + + # zeros-poles-gain representation + zd = np.array([0.5, -0.5]) + pd = np.array([1.j / np.sqrt(2), -1.j / np.sqrt(2)]) + k = 1.0 + yout_truth = np.array([[0.0, 1.0, 2.0, 2.25, 2.5]]).T + + tout, yout = dlsim((zd, pd, k, 0.5), u[:, 0], t_in) + + assert_array_almost_equal(yout, yout_truth) + assert_array_almost_equal(t_in, tout) + + # Raise an error for continuous-time systems + system = lti([1], [1, 1]) + assert_raises(AttributeError, dlsim, system, u) + + def test_dstep(self): + + a = np.asarray([[0.9, 0.1], [-0.2, 0.9]]) + b = np.asarray([[0.4, 0.1, -0.1], [0.0, 0.05, 0.0]]) + c = np.asarray([[0.1, 0.3]]) + d = np.asarray([[0.0, -0.1, 0.0]]) + dt = 0.5 + + # Because b.shape[1] == 3, dstep should result in a tuple of three + # result vectors + yout_step_truth = (np.asarray([0.0, 0.04, 0.052, 0.0404, 0.00956, + -0.036324, -0.093318, -0.15782348, + -0.226628324, -0.2969374948]), + np.asarray([-0.1, -0.075, -0.058, -0.04815, + -0.04453, -0.0461895, -0.0521812, + -0.061588875, -0.073549579, + -0.08727047595]), + np.asarray([0.0, -0.01, -0.013, -0.0101, -0.00239, + 0.009081, 0.0233295, 0.03945587, + 0.056657081, 0.0742343737])) + + tout, yout = dstep((a, b, c, d, dt), n=10) + + assert len(yout) == 3 + + for i in range(0, len(yout)): + assert yout[i].shape[0] == 10 + assert_array_almost_equal(yout[i].flatten(), yout_step_truth[i]) + + # Check that the other two inputs (tf, zpk) will work as well + tfin = ([1.0], [1.0, 1.0], 0.5) + yout_tfstep = np.asarray([0.0, 1.0, 0.0]) + tout, yout = dstep(tfin, n=3) + assert len(yout) == 1 + assert_array_almost_equal(yout[0].flatten(), yout_tfstep) + + zpkin = tf2zpk(tfin[0], tfin[1]) + (0.5,) + tout, yout = dstep(zpkin, n=3) + assert len(yout) == 1 + assert_array_almost_equal(yout[0].flatten(), yout_tfstep) + + # Raise an error for continuous-time systems + system = lti([1], [1, 1]) + assert_raises(AttributeError, dstep, system) + + def test_dimpulse(self): + + a = np.asarray([[0.9, 0.1], [-0.2, 0.9]]) + b = np.asarray([[0.4, 0.1, -0.1], [0.0, 0.05, 0.0]]) + c = np.asarray([[0.1, 0.3]]) + d = np.asarray([[0.0, -0.1, 0.0]]) + dt = 0.5 + + # Because b.shape[1] == 3, dimpulse should result in a tuple of three + # result vectors + yout_imp_truth = (np.asarray([0.0, 0.04, 0.012, -0.0116, -0.03084, + -0.045884, -0.056994, -0.06450548, + -0.068804844, -0.0703091708]), + np.asarray([-0.1, 0.025, 0.017, 0.00985, 0.00362, + -0.0016595, -0.0059917, -0.009407675, + -0.011960704, -0.01372089695]), + np.asarray([0.0, -0.01, -0.003, 0.0029, 0.00771, + 0.011471, 0.0142485, 0.01612637, + 0.017201211, 0.0175772927])) + + tout, yout = dimpulse((a, b, c, d, dt), n=10) + + assert len(yout) == 3 + + for i in range(0, len(yout)): + assert yout[i].shape[0] == 10 + assert_array_almost_equal(yout[i].flatten(), yout_imp_truth[i]) + + # Check that the other two inputs (tf, zpk) will work as well + tfin = ([1.0], [1.0, 1.0], 0.5) + yout_tfimpulse = np.asarray([0.0, 1.0, -1.0]) + tout, yout = dimpulse(tfin, n=3) + assert len(yout) == 1 + assert_array_almost_equal(yout[0].flatten(), yout_tfimpulse) + + zpkin = tf2zpk(tfin[0], tfin[1]) + (0.5,) + tout, yout = dimpulse(zpkin, n=3) + assert len(yout) == 1 + assert_array_almost_equal(yout[0].flatten(), yout_tfimpulse) + + # Raise an error for continuous-time systems + system = lti([1], [1, 1]) + assert_raises(AttributeError, dimpulse, system) + + def test_dlsim_trivial(self): + a = np.array([[0.0]]) + b = np.array([[0.0]]) + c = np.array([[0.0]]) + d = np.array([[0.0]]) + n = 5 + u = np.zeros(n).reshape(-1, 1) + tout, yout, xout = dlsim((a, b, c, d, 1), u) + xp_assert_equal(tout, np.arange(float(n))) + xp_assert_equal(yout, np.zeros((n, 1))) + xp_assert_equal(xout, np.zeros((n, 1))) + + def test_dlsim_simple1d(self): + a = np.array([[0.5]]) + b = np.array([[0.0]]) + c = np.array([[1.0]]) + d = np.array([[0.0]]) + n = 5 + u = np.zeros(n).reshape(-1, 1) + tout, yout, xout = dlsim((a, b, c, d, 1), u, x0=1) + xp_assert_equal(tout, np.arange(float(n))) + expected = (0.5 ** np.arange(float(n))).reshape(-1, 1) + xp_assert_equal(yout, expected) + xp_assert_equal(xout, expected) + + def test_dlsim_simple2d(self): + lambda1 = 0.5 + lambda2 = 0.25 + a = np.array([[lambda1, 0.0], + [0.0, lambda2]]) + b = np.array([[0.0], + [0.0]]) + c = np.array([[1.0, 0.0], + [0.0, 1.0]]) + d = np.array([[0.0], + [0.0]]) + n = 5 + u = np.zeros(n).reshape(-1, 1) + tout, yout, xout = dlsim((a, b, c, d, 1), u, x0=1) + xp_assert_equal(tout, np.arange(float(n))) + # The analytical solution: + expected = (np.array([lambda1, lambda2]) ** + np.arange(float(n)).reshape(-1, 1)) + xp_assert_equal(yout, expected) + xp_assert_equal(xout, expected) + + def test_more_step_and_impulse(self): + lambda1 = 0.5 + lambda2 = 0.75 + a = np.array([[lambda1, 0.0], + [0.0, lambda2]]) + b = np.array([[1.0, 0.0], + [0.0, 1.0]]) + c = np.array([[1.0, 1.0]]) + d = np.array([[0.0, 0.0]]) + + n = 10 + + # Check a step response. + ts, ys = dstep((a, b, c, d, 1), n=n) + + # Create the exact step response. + stp0 = (1.0 / (1 - lambda1)) * (1.0 - lambda1 ** np.arange(n)) + stp1 = (1.0 / (1 - lambda2)) * (1.0 - lambda2 ** np.arange(n)) + + xp_assert_close(ys[0][:, 0], stp0) + xp_assert_close(ys[1][:, 0], stp1) + + # Check an impulse response with an initial condition. + x0 = np.array([1.0, 1.0]) + ti, yi = dimpulse((a, b, c, d, 1), n=n, x0=x0) + + # Create the exact impulse response. + imp = (np.array([lambda1, lambda2]) ** + np.arange(-1, n + 1).reshape(-1, 1)) + imp[0, :] = 0.0 + # Analytical solution to impulse response + y0 = imp[:n, 0] + np.dot(imp[1:n + 1, :], x0) + y1 = imp[:n, 1] + np.dot(imp[1:n + 1, :], x0) + + xp_assert_close(yi[0][:, 0], y0) + xp_assert_close(yi[1][:, 0], y1) + + # Check that dt=0.1, n=3 gives 3 time values. + system = ([1.0], [1.0, -0.5], 0.1) + t, (y,) = dstep(system, n=3) + xp_assert_close(t, [0, 0.1, 0.2]) + xp_assert_equal(y.T, [[0, 1.0, 1.5]]) + t, (y,) = dimpulse(system, n=3) + xp_assert_close(t, [0, 0.1, 0.2]) + xp_assert_equal(y.T, [[0, 1, 0.5]]) + + +class TestDlti: + def test_dlti_instantiation(self): + # Test that lti can be instantiated. + + dt = 0.05 + # TransferFunction + s = dlti([1], [-1], dt=dt) + assert isinstance(s, TransferFunction) + assert isinstance(s, dlti) + assert not isinstance(s, lti) + assert s.dt == dt + + # ZerosPolesGain + s = dlti(np.array([]), np.array([-1]), 1, dt=dt) + assert isinstance(s, ZerosPolesGain) + assert isinstance(s, dlti) + assert not isinstance(s, lti) + assert s.dt == dt + + # StateSpace + s = dlti([1], [-1], 1, 3, dt=dt) + assert isinstance(s, StateSpace) + assert isinstance(s, dlti) + assert not isinstance(s, lti) + assert s.dt == dt + + # Number of inputs + assert_raises(ValueError, dlti, 1) + assert_raises(ValueError, dlti, 1, 1, 1, 1, 1) + + +class TestStateSpaceDisc: + def test_initialization(self): + # Check that all initializations work + dt = 0.05 + StateSpace(1, 1, 1, 1, dt=dt) + StateSpace([1], [2], [3], [4], dt=dt) + StateSpace(np.array([[1, 2], [3, 4]]), np.array([[1], [2]]), + np.array([[1, 0]]), np.array([[0]]), dt=dt) + StateSpace(1, 1, 1, 1, dt=True) + + def test_conversion(self): + # Check the conversion functions + s = StateSpace(1, 2, 3, 4, dt=0.05) + assert isinstance(s.to_ss(), StateSpace) + assert isinstance(s.to_tf(), TransferFunction) + assert isinstance(s.to_zpk(), ZerosPolesGain) + + # Make sure copies work + assert StateSpace(s) is not s + assert s.to_ss() is not s + + def test_properties(self): + # Test setters/getters for cross class properties. + # This implicitly tests to_tf() and to_zpk() + + # Getters + s = StateSpace(1, 1, 1, 1, dt=0.05) + xp_assert_equal(s.poles, [1.]) + xp_assert_equal(s.zeros, [0.]) + + +class TestTransferFunction: + def test_initialization(self): + # Check that all initializations work + dt = 0.05 + TransferFunction(1, 1, dt=dt) + TransferFunction([1], [2], dt=dt) + TransferFunction(np.array([1]), np.array([2]), dt=dt) + TransferFunction(1, 1, dt=True) + + def test_conversion(self): + # Check the conversion functions + s = TransferFunction([1, 0], [1, -1], dt=0.05) + assert isinstance(s.to_ss(), StateSpace) + assert isinstance(s.to_tf(), TransferFunction) + assert isinstance(s.to_zpk(), ZerosPolesGain) + + # Make sure copies work + assert TransferFunction(s) is not s + assert s.to_tf() is not s + + def test_properties(self): + # Test setters/getters for cross class properties. + # This implicitly tests to_ss() and to_zpk() + + # Getters + s = TransferFunction([1, 0], [1, -1], dt=0.05) + xp_assert_equal(s.poles, [1.]) + xp_assert_equal(s.zeros, [0.]) + + +class TestZerosPolesGain: + def test_initialization(self): + # Check that all initializations work + dt = 0.05 + ZerosPolesGain(1, 1, 1, dt=dt) + ZerosPolesGain([1], [2], 1, dt=dt) + ZerosPolesGain(np.array([1]), np.array([2]), 1, dt=dt) + ZerosPolesGain(1, 1, 1, dt=True) + + def test_conversion(self): + # Check the conversion functions + s = ZerosPolesGain(1, 2, 3, dt=0.05) + assert isinstance(s.to_ss(), StateSpace) + assert isinstance(s.to_tf(), TransferFunction) + assert isinstance(s.to_zpk(), ZerosPolesGain) + + # Make sure copies work + assert ZerosPolesGain(s) is not s + assert s.to_zpk() is not s + + +class Test_dfreqresp: + + def test_manual(self): + # Test dfreqresp() real part calculation (manual sanity check). + # 1st order low-pass filter: H(z) = 1 / (z - 0.2), + system = TransferFunction(1, [1, -0.2], dt=0.1) + w = [0.1, 1, 10] + w, H = dfreqresp(system, w=w) + + # test real + expected_re = [1.2383, 0.4130, -0.7553] + assert_almost_equal(H.real, expected_re, decimal=4) + + # test imag + expected_im = [-0.1555, -1.0214, 0.3955] + assert_almost_equal(H.imag, expected_im, decimal=4) + + def test_auto(self): + # Test dfreqresp() real part calculation. + # 1st order low-pass filter: H(z) = 1 / (z - 0.2), + system = TransferFunction(1, [1, -0.2], dt=0.1) + w = [0.1, 1, 10, 100] + w, H = dfreqresp(system, w=w) + jw = np.exp(w * 1j) + y = np.polyval(system.num, jw) / np.polyval(system.den, jw) + + # test real + expected_re = y.real + assert_almost_equal(H.real, expected_re) + + # test imag + expected_im = y.imag + assert_almost_equal(H.imag, expected_im) + + def test_freq_range(self): + # Test that freqresp() finds a reasonable frequency range. + # 1st order low-pass filter: H(z) = 1 / (z - 0.2), + # Expected range is from 0.01 to 10. + system = TransferFunction(1, [1, -0.2], dt=0.1) + n = 10 + expected_w = np.linspace(0, np.pi, 10, endpoint=False) + w, H = dfreqresp(system, n=n) + assert_almost_equal(w, expected_w) + + def test_pole_one(self): + # Test that freqresp() doesn't fail on a system with a pole at 0. + # integrator, pole at zero: H(s) = 1 / s + system = TransferFunction([1], [1, -1], dt=0.1) + + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, message="divide by zero") + sup.filter(RuntimeWarning, message="invalid value encountered") + w, H = dfreqresp(system, n=2) + assert w[0] == 0. # a fail would give not-a-number + + def test_error(self): + # Raise an error for continuous-time systems + system = lti([1], [1, 1]) + assert_raises(AttributeError, dfreqresp, system) + + def test_from_state_space(self): + # H(z) = 2 / z^3 - 0.5 * z^2 + + system_TF = dlti([2], [1, -0.5, 0, 0]) + + A = np.array([[0.5, 0, 0], + [1, 0, 0], + [0, 1, 0]]) + B = np.array([[1, 0, 0]]).T + C = np.array([[0, 0, 2]]) + D = 0 + + system_SS = dlti(A, B, C, D) + w = 10.0**np.arange(-3,0,.5) + with suppress_warnings() as sup: + sup.filter(BadCoefficients) + w1, H1 = dfreqresp(system_TF, w=w) + w2, H2 = dfreqresp(system_SS, w=w) + + assert_almost_equal(H1, H2) + + def test_from_zpk(self): + # 1st order low-pass filter: H(s) = 0.3 / (z - 0.2), + system_ZPK = dlti([],[0.2],0.3) + system_TF = dlti(0.3, [1, -0.2]) + w = [0.1, 1, 10, 100] + w1, H1 = dfreqresp(system_ZPK, w=w) + w2, H2 = dfreqresp(system_TF, w=w) + assert_almost_equal(H1, H2) + + +class Test_bode: + + def test_manual(self): + # Test bode() magnitude calculation (manual sanity check). + # 1st order low-pass filter: H(s) = 0.3 / (z - 0.2), + dt = 0.1 + system = TransferFunction(0.3, [1, -0.2], dt=dt) + w = [0.1, 0.5, 1, np.pi] + w2, mag, phase = dbode(system, w=w) + + # Test mag + expected_mag = [-8.5329, -8.8396, -9.6162, -12.0412] + assert_almost_equal(mag, expected_mag, decimal=4) + + # Test phase + expected_phase = [-7.1575, -35.2814, -67.9809, -180.0000] + assert_almost_equal(phase, expected_phase, decimal=4) + + # Test frequency + xp_assert_equal(np.array(w) / dt, w2) + + def test_auto(self): + # Test bode() magnitude calculation. + # 1st order low-pass filter: H(s) = 0.3 / (z - 0.2), + system = TransferFunction(0.3, [1, -0.2], dt=0.1) + w = np.array([0.1, 0.5, 1, np.pi]) + w2, mag, phase = dbode(system, w=w) + jw = np.exp(w * 1j) + y = np.polyval(system.num, jw) / np.polyval(system.den, jw) + + # Test mag + expected_mag = 20.0 * np.log10(abs(y)) + assert_almost_equal(mag, expected_mag) + + # Test phase + expected_phase = np.rad2deg(np.angle(y)) + assert_almost_equal(phase, expected_phase) + + def test_range(self): + # Test that bode() finds a reasonable frequency range. + # 1st order low-pass filter: H(s) = 0.3 / (z - 0.2), + dt = 0.1 + system = TransferFunction(0.3, [1, -0.2], dt=0.1) + n = 10 + # Expected range is from 0.01 to 10. + expected_w = np.linspace(0, np.pi, n, endpoint=False) / dt + w, mag, phase = dbode(system, n=n) + assert_almost_equal(w, expected_w) + + def test_pole_one(self): + # Test that freqresp() doesn't fail on a system with a pole at 0. + # integrator, pole at zero: H(s) = 1 / s + system = TransferFunction([1], [1, -1], dt=0.1) + + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, message="divide by zero") + sup.filter(RuntimeWarning, message="invalid value encountered") + w, mag, phase = dbode(system, n=2) + assert w[0] == 0. # a fail would give not-a-number + + def test_imaginary(self): + # bode() should not fail on a system with pure imaginary poles. + # The test passes if bode doesn't raise an exception. + system = TransferFunction([1], [1, 0, 100], dt=0.1) + dbode(system, n=2) + + def test_error(self): + # Raise an error for continuous-time systems + system = lti([1], [1, 1]) + assert_raises(AttributeError, dbode, system) + + +class TestTransferFunctionZConversion: + """Test private conversions between 'z' and 'z**-1' polynomials.""" + + def test_full(self): + # Numerator and denominator same order + num = np.asarray([2.0, 3, 4]) + den = np.asarray([5.0, 6, 7]) + num2, den2 = TransferFunction._z_to_zinv(num, den) + xp_assert_equal(num, num2) + xp_assert_equal(den, den2) + + num2, den2 = TransferFunction._zinv_to_z(num, den) + xp_assert_equal(num, num2) + xp_assert_equal(den, den2) + + def test_numerator(self): + # Numerator lower order than denominator + num = np.asarray([2.0, 3]) + den = np.asarray([50, 6, 7]) + num2, den2 = TransferFunction._z_to_zinv(num, den) + xp_assert_equal([0.0, 2, 3], num2) + xp_assert_equal(den, den2) + + num2, den2 = TransferFunction._zinv_to_z(num, den) + xp_assert_equal([2.0, 3, 0], num2) + xp_assert_equal(den, den2) + + def test_denominator(self): + # Numerator higher order than denominator + num = np.asarray([2., 3, 4]) + den = np.asarray([5.0, 6]) + num2, den2 = TransferFunction._z_to_zinv(num, den) + xp_assert_equal(num, num2) + xp_assert_equal([0.0, 5, 6], den2) + + num2, den2 = TransferFunction._zinv_to_z(num, den) + xp_assert_equal(num, num2) + xp_assert_equal([5.0, 6, 0], den2) + diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_filter_design.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_filter_design.py new file mode 100644 index 0000000000000000000000000000000000000000..62613b5bb64ec2980dc8a306e7a2a997b5713d2c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_filter_design.py @@ -0,0 +1,4485 @@ +import warnings + +from scipy._lib import _pep440 +import numpy as np +from numpy.testing import ( + assert_array_almost_equal_nulp, assert_warns, suppress_warnings +) +import pytest +from pytest import raises as assert_raises +from scipy._lib._array_api import ( + xp_assert_close, xp_assert_equal, + assert_array_almost_equal, +) + +from numpy import array, spacing, sin, pi, sort, sqrt +from scipy.signal import (argrelextrema, BadCoefficients, bessel, besselap, bilinear, + buttap, butter, buttord, cheb1ap, cheb1ord, cheb2ap, + cheb2ord, cheby1, cheby2, ellip, ellipap, ellipord, + firwin, freqs_zpk, freqs, freqz, freqz_zpk, + gammatone, group_delay, iircomb, iirdesign, iirfilter, + iirnotch, iirpeak, lp2bp, lp2bs, lp2hp, lp2lp, normalize, + medfilt, order_filter, + sos2tf, sos2zpk, sosfreqz, freqz_sos, tf2sos, tf2zpk, zpk2sos, + zpk2tf, bilinear_zpk, lp2lp_zpk, lp2hp_zpk, lp2bp_zpk, + lp2bs_zpk) +from scipy.signal._filter_design import (_cplxreal, _cplxpair, _norm_factor, + _bessel_poly, _bessel_zeros) + +try: + import mpmath +except ImportError: + mpmath = None + + +def mpmath_check(min_ver): + return pytest.mark.skipif( + mpmath is None + or _pep440.parse(mpmath.__version__) < _pep440.Version(min_ver), + reason=f"mpmath version >= {min_ver} required", + ) + + +class TestCplxPair: + + def test_trivial_input(self): + assert _cplxpair([]).size == 0 + assert _cplxpair(1) == 1 + + def test_output_order(self): + xp_assert_close(_cplxpair([1+1j, 1-1j]), [1-1j, 1+1j]) + + a = [1+1j, 1+1j, 1, 1-1j, 1-1j, 2] + b = [1-1j, 1+1j, 1-1j, 1+1j, 1, 2] + xp_assert_close(_cplxpair(a), b) + + # points spaced around the unit circle + z = np.exp(2j*pi*array([4, 3, 5, 2, 6, 1, 0])/7) + z1 = np.copy(z) + np.random.shuffle(z) + xp_assert_close(_cplxpair(z), z1) + np.random.shuffle(z) + xp_assert_close(_cplxpair(z), z1) + np.random.shuffle(z) + xp_assert_close(_cplxpair(z), z1) + + # Should be able to pair up all the conjugates + x = np.random.rand(10000) + 1j * np.random.rand(10000) + y = x.conj() + z = np.random.rand(10000) + x = np.concatenate((x, y, z)) + np.random.shuffle(x) + c = _cplxpair(x) + + # Every other element of head should be conjugates: + xp_assert_close(c[0:20000:2], np.conj(c[1:20000:2])) + # Real parts of head should be in sorted order: + xp_assert_close(c[0:20000:2].real, np.sort(c[0:20000:2].real)) + # Tail should be sorted real numbers: + xp_assert_close(c[20000:], np.sort(c[20000:])) + + def test_real_integer_input(self): + xp_assert_equal(_cplxpair([2, 0, 1]), [0, 1, 2]) + + def test_tolerances(self): + eps = spacing(1) + xp_assert_close(_cplxpair([1j, -1j, 1+1j*eps], tol=2*eps), + [-1j, 1j, 1+1j*eps]) + + # sorting close to 0 + xp_assert_close(_cplxpair([-eps+1j, +eps-1j]), [-1j, +1j]) + xp_assert_close(_cplxpair([+eps+1j, -eps-1j]), [-1j, +1j]) + xp_assert_close(_cplxpair([+1j, -1j]), [-1j, +1j]) + + def test_unmatched_conjugates(self): + # 1+2j is unmatched + assert_raises(ValueError, _cplxpair, [1+3j, 1-3j, 1+2j]) + + # 1+2j and 1-3j are unmatched + assert_raises(ValueError, _cplxpair, [1+3j, 1-3j, 1+2j, 1-3j]) + + # 1+3j is unmatched + assert_raises(ValueError, _cplxpair, [1+3j, 1-3j, 1+3j]) + + # Not conjugates + assert_raises(ValueError, _cplxpair, [4+5j, 4+5j]) + assert_raises(ValueError, _cplxpair, [1-7j, 1-7j]) + + # No pairs + assert_raises(ValueError, _cplxpair, [1+3j]) + assert_raises(ValueError, _cplxpair, [1-3j]) + + +class TestCplxReal: + + def test_trivial_input(self): + assert all(x.size == 0 for x in _cplxreal([])) + + x = _cplxreal(1) + assert x[0].size == 0 + xp_assert_equal(x[1], np.asarray([1])) + + + def test_output_order(self): + zc, zr = _cplxreal(np.roots(array([1, 0, 0, 1]))) + xp_assert_close(np.append(zc, zr), [1/2 + 1j*sin(pi/3), -1]) + + eps = spacing(1) + + a = [0+1j, 0-1j, eps + 1j, eps - 1j, -eps + 1j, -eps - 1j, + 1, 4, 2, 3, 0, 0, + 2+3j, 2-3j, + 1-eps + 1j, 1+2j, 1-2j, 1+eps - 1j, # sorts out of order + 3+1j, 3+1j, 3+1j, 3-1j, 3-1j, 3-1j, + 2-3j, 2+3j] + zc, zr = _cplxreal(a) + xp_assert_close(zc, [1j, 1j, 1j, 1+1j, 1+2j, 2+3j, 2+3j, 3+1j, 3+1j, + 3+1j]) + xp_assert_close(zr, [0.0, 0, 1, 2, 3, 4]) + + z = array([1-eps + 1j, 1+2j, 1-2j, 1+eps - 1j, 1+eps+3j, 1-2*eps-3j, + 0+1j, 0-1j, 2+4j, 2-4j, 2+3j, 2-3j, 3+7j, 3-7j, 4-eps+1j, + 4+eps-2j, 4-1j, 4-eps+2j]) + + zc, zr = _cplxreal(z) + xp_assert_close(zc, [1j, 1+1j, 1+2j, 1+3j, 2+3j, 2+4j, 3+7j, 4+1j, + 4+2j]) + xp_assert_equal(zr, np.asarray([])) + + def test_unmatched_conjugates(self): + # 1+2j is unmatched + assert_raises(ValueError, _cplxreal, [1+3j, 1-3j, 1+2j]) + + # 1+2j and 1-3j are unmatched + assert_raises(ValueError, _cplxreal, [1+3j, 1-3j, 1+2j, 1-3j]) + + # 1+3j is unmatched + assert_raises(ValueError, _cplxreal, [1+3j, 1-3j, 1+3j]) + + # No pairs + assert_raises(ValueError, _cplxreal, [1+3j]) + assert_raises(ValueError, _cplxreal, [1-3j]) + + def test_real_integer_input(self): + zc, zr = _cplxreal([2, 0, 1, 4]) + xp_assert_equal(zc, []) + xp_assert_equal(zr, [0, 1, 2, 4]) + + +class TestTf2zpk: + + @pytest.mark.parametrize('dt', (np.float64, np.complex128)) + def test_simple(self, dt): + z_r = np.array([0.5, -0.5]) + p_r = np.array([1.j / np.sqrt(2), -1.j / np.sqrt(2)]) + # Sort the zeros/poles so that we don't fail the test if the order + # changes + z_r.sort() + p_r.sort() + b = np.poly(z_r).astype(dt) + a = np.poly(p_r).astype(dt) + + z, p, k = tf2zpk(b, a) + z.sort() + # The real part of `p` is ~0.0, so sort by imaginary part + p = p[np.argsort(p.imag)] + + assert_array_almost_equal(z, z_r) + assert_array_almost_equal(p, p_r) + assert_array_almost_equal(k, 1.) + assert k.dtype == dt + + def test_bad_filter(self): + # Regression test for #651: better handling of badly conditioned + # filter coefficients. + with suppress_warnings(): + warnings.simplefilter("error", BadCoefficients) + assert_raises(BadCoefficients, tf2zpk, [1e-15], [1.0, 1.0]) + + +class TestZpk2Tf: + + def test_identity(self): + """Test the identity transfer function.""" + z = [] + p = [] + k = 1. + b, a = zpk2tf(z, p, k) + b_r = np.array([1.]) # desired result + a_r = np.array([1.]) # desired result + # The test for the *type* of the return values is a regression + # test for ticket #1095. In the case p=[], zpk2tf used to + # return the scalar 1.0 instead of array([1.0]). + xp_assert_equal(b, b_r) + assert isinstance(b, np.ndarray) + xp_assert_equal(a, a_r) + assert isinstance(a, np.ndarray) + + +class TestSos2Zpk: + + def test_basic(self): + sos = [[1, 0, 1, 1, 0, -0.81], + [1, 0, 0, 1, 0, +0.49]] + z, p, k = sos2zpk(sos) + z2 = [1j, -1j, 0, 0] + p2 = [0.9, -0.9, 0.7j, -0.7j] + k2 = 1 + assert_array_almost_equal(sort(z), sort(z2), decimal=4) + assert_array_almost_equal(sort(p), sort(p2), decimal=4) + assert_array_almost_equal(k, k2) + + sos = [[1.00000, +0.61803, 1.0000, 1.00000, +0.60515, 0.95873], + [1.00000, -1.61803, 1.0000, 1.00000, -1.58430, 0.95873], + [1.00000, +1.00000, 0.0000, 1.00000, +0.97915, 0.00000]] + z, p, k = sos2zpk(sos) + z2 = [-0.3090 + 0.9511j, -0.3090 - 0.9511j, 0.8090 + 0.5878j, + 0.8090 - 0.5878j, -1.0000 + 0.0000j, 0] + p2 = [-0.3026 + 0.9312j, -0.3026 - 0.9312j, 0.7922 + 0.5755j, + 0.7922 - 0.5755j, -0.9791 + 0.0000j, 0] + k2 = 1 + assert_array_almost_equal(sort(z), sort(z2), decimal=4) + assert_array_almost_equal(sort(p), sort(p2), decimal=4) + + sos = array([[1, 2, 3, 1, 0.2, 0.3], + [4, 5, 6, 1, 0.4, 0.5]]) + z = array([-1 - 1.41421356237310j, -1 + 1.41421356237310j, + -0.625 - 1.05326872164704j, -0.625 + 1.05326872164704j]) + p = array([-0.2 - 0.678232998312527j, -0.2 + 0.678232998312527j, + -0.1 - 0.538516480713450j, -0.1 + 0.538516480713450j]) + k = 4 + z2, p2, k2 = sos2zpk(sos) + xp_assert_close(_cplxpair(z2), z) + xp_assert_close(_cplxpair(p2), p) + assert k2 == k + + @pytest.mark.thread_unsafe + def test_fewer_zeros(self): + """Test not the expected number of p/z (effectively at origin).""" + sos = butter(3, 0.1, output='sos') + z, p, k = sos2zpk(sos) + assert len(z) == 4 + assert len(p) == 4 + + sos = butter(12, [5., 30.], 'bandpass', fs=1200., analog=False, + output='sos') + with pytest.warns(BadCoefficients, match='Badly conditioned'): + z, p, k = sos2zpk(sos) + assert len(z) == 24 + assert len(p) == 24 + + +class TestSos2Tf: + + def test_basic(self): + sos = [[1, 1, 1, 1, 0, -1], + [-2, 3, 1, 1, 10, 1]] + b, a = sos2tf(sos) + assert_array_almost_equal(b, [-2, 1, 2, 4, 1]) + assert_array_almost_equal(a, [1, 10, 0, -10, -1]) + + +class TestTf2Sos: + + def test_basic(self): + num = [2, 16, 44, 56, 32] + den = [3, 3, -15, 18, -12] + sos = tf2sos(num, den) + sos2 = [[0.6667, 4.0000, 5.3333, 1.0000, +2.0000, -4.0000], + [1.0000, 2.0000, 2.0000, 1.0000, -1.0000, +1.0000]] + assert_array_almost_equal(sos, sos2, decimal=4) + + b = [1, -3, 11, -27, 18] + a = [16, 12, 2, -4, -1] + sos = tf2sos(b, a) + sos2 = [[0.0625, -0.1875, 0.1250, 1.0000, -0.2500, -0.1250], + [1.0000, +0.0000, 9.0000, 1.0000, +1.0000, +0.5000]] + # assert_array_almost_equal(sos, sos2, decimal=4) + + @pytest.mark.parametrize('b, a, analog, sos', + [([1], [1], False, [[1., 0., 0., 1., 0., 0.]]), + ([1], [1], True, [[0., 0., 1., 0., 0., 1.]]), + ([1], [1., 0., -1.01, 0, 0.01], False, + [[1., 0., 0., 1., 0., -0.01], + [1., 0., 0., 1., 0., -1]]), + ([1], [1., 0., -1.01, 0, 0.01], True, + [[0., 0., 1., 1., 0., -1], + [0., 0., 1., 1., 0., -0.01]])]) + def test_analog(self, b, a, analog, sos): + sos2 = tf2sos(b, a, analog=analog) + assert_array_almost_equal(sos, sos2, decimal=4) + + +class TestZpk2Sos: + + @pytest.mark.parametrize('dt', 'fdgFDG') + @pytest.mark.parametrize('pairing, analog', + [('nearest', False), + ('keep_odd', False), + ('minimal', False), + ('minimal', True)]) + def test_dtypes(self, dt, pairing, analog): + z = np.array([-1, -1]).astype(dt) + ct = dt.upper() # the poles have to be complex + p = np.array([0.57149 + 0.29360j, 0.57149 - 0.29360j]).astype(ct) + k = np.array(1).astype(dt) + sos = zpk2sos(z, p, k, pairing=pairing, analog=analog) + sos2 = [[1, 2, 1, 1, -1.14298, 0.41280]] # octave & MATLAB + assert_array_almost_equal(sos, sos2, decimal=4) + + def test_basic(self): + for pairing in ('nearest', 'keep_odd'): + # + # Cases that match octave + # + + z = [-1, -1] + p = [0.57149 + 0.29360j, 0.57149 - 0.29360j] + k = 1 + sos = zpk2sos(z, p, k, pairing=pairing) + sos2 = [[1, 2, 1, 1, -1.14298, 0.41280]] # octave & MATLAB + assert_array_almost_equal(sos, sos2, decimal=4) + + z = [1j, -1j] + p = [0.9, -0.9, 0.7j, -0.7j] + k = 1 + sos = zpk2sos(z, p, k, pairing=pairing) + sos2 = [[1, 0, 1, 1, 0, +0.49], + [1, 0, 0, 1, 0, -0.81]] # octave + # sos2 = [[0, 0, 1, 1, -0.9, 0], + # [1, 0, 1, 1, 0.9, 0]] # MATLAB + assert_array_almost_equal(sos, sos2, decimal=4) + + z = [] + p = [0.8, -0.5+0.25j, -0.5-0.25j] + k = 1. + sos = zpk2sos(z, p, k, pairing=pairing) + sos2 = [[1., 0., 0., 1., 1., 0.3125], + [1., 0., 0., 1., -0.8, 0.]] # octave, MATLAB fails + assert_array_almost_equal(sos, sos2, decimal=4) + + z = [1., 1., 0.9j, -0.9j] + p = [0.99+0.01j, 0.99-0.01j, 0.1+0.9j, 0.1-0.9j] + k = 1 + sos = zpk2sos(z, p, k, pairing=pairing) + sos2 = [[1, 0, 0.81, 1, -0.2, 0.82], + [1, -2, 1, 1, -1.98, 0.9802]] # octave + # sos2 = [[1, -2, 1, 1, -0.2, 0.82], + # [1, 0, 0.81, 1, -1.98, 0.9802]] # MATLAB + assert_array_almost_equal(sos, sos2, decimal=4) + + z = [0.9+0.1j, 0.9-0.1j, -0.9] + p = [0.75+0.25j, 0.75-0.25j, 0.9] + k = 1 + sos = zpk2sos(z, p, k, pairing=pairing) + if pairing == 'keep_odd': + sos2 = [[1, -1.8, 0.82, 1, -1.5, 0.625], + [1, 0.9, 0, 1, -0.9, 0]] # octave; MATLAB fails + assert_array_almost_equal(sos, sos2, decimal=4) + else: # pairing == 'nearest' + sos2 = [[1, 0.9, 0, 1, -1.5, 0.625], + [1, -1.8, 0.82, 1, -0.9, 0]] # our algorithm + assert_array_almost_equal(sos, sos2, decimal=4) + + # + # Cases that differ from octave: + # + + z = [-0.3090 + 0.9511j, -0.3090 - 0.9511j, 0.8090 + 0.5878j, + +0.8090 - 0.5878j, -1.0000 + 0.0000j] + p = [-0.3026 + 0.9312j, -0.3026 - 0.9312j, 0.7922 + 0.5755j, + +0.7922 - 0.5755j, -0.9791 + 0.0000j] + k = 1 + sos = zpk2sos(z, p, k, pairing=pairing) + # sos2 = [[1, 0.618, 1, 1, 0.6052, 0.95870], + # [1, -1.618, 1, 1, -1.5844, 0.95878], + # [1, 1, 0, 1, 0.9791, 0]] # octave, MATLAB fails + sos2 = [[1, 1, 0, 1, +0.97915, 0], + [1, 0.61803, 1, 1, +0.60515, 0.95873], + [1, -1.61803, 1, 1, -1.58430, 0.95873]] + assert_array_almost_equal(sos, sos2, decimal=4) + + z = [-1 - 1.4142j, -1 + 1.4142j, + -0.625 - 1.0533j, -0.625 + 1.0533j] + p = [-0.2 - 0.6782j, -0.2 + 0.6782j, + -0.1 - 0.5385j, -0.1 + 0.5385j] + k = 4 + sos = zpk2sos(z, p, k, pairing=pairing) + sos2 = [[4, 8, 12, 1, 0.2, 0.3], + [1, 1.25, 1.5, 1, 0.4, 0.5]] # MATLAB + # sos2 = [[4, 8, 12, 1, 0.4, 0.5], + # [1, 1.25, 1.5, 1, 0.2, 0.3]] # octave + xp_assert_close(sos, sos2, rtol=1e-4, atol=1e-4) + + z = [] + p = [0.2, -0.5+0.25j, -0.5-0.25j] + k = 1. + sos = zpk2sos(z, p, k, pairing=pairing) + sos2 = [[1., 0., 0., 1., -0.2, 0.], + [1., 0., 0., 1., 1., 0.3125]] + # sos2 = [[1., 0., 0., 1., 1., 0.3125], + # [1., 0., 0., 1., -0.2, 0]] # octave, MATLAB fails + assert_array_almost_equal(sos, sos2, decimal=4) + + # The next two examples are adapted from Leland B. Jackson, + # "Digital Filters and Signal Processing (1995) p.400: + # http://books.google.com/books?id=VZ8uabI1pNMC&lpg=PA400&ots=gRD9pi8Jua&dq=Pole%2Fzero%20pairing%20for%20minimum%20roundoff%20noise%20in%20BSF.&pg=PA400#v=onepage&q=Pole%2Fzero%20pairing%20for%20minimum%20roundoff%20noise%20in%20BSF.&f=false + + deg2rad = np.pi / 180. + k = 1. + + # first example + thetas = [22.5, 45, 77.5] + mags = [0.8, 0.6, 0.9] + z = np.array([np.exp(theta * deg2rad * 1j) for theta in thetas]) + z = np.concatenate((z, np.conj(z))) + p = np.array([mag * np.exp(theta * deg2rad * 1j) + for theta, mag in zip(thetas, mags)]) + p = np.concatenate((p, np.conj(p))) + sos = zpk2sos(z, p, k) + # sos2 = [[1, -0.43288, 1, 1, -0.38959, 0.81], # octave, + # [1, -1.41421, 1, 1, -0.84853, 0.36], # MATLAB fails + # [1, -1.84776, 1, 1, -1.47821, 0.64]] + # Note that pole-zero pairing matches, but ordering is different + sos2 = [[1, -1.41421, 1, 1, -0.84853, 0.36], + [1, -1.84776, 1, 1, -1.47821, 0.64], + [1, -0.43288, 1, 1, -0.38959, 0.81]] + assert_array_almost_equal(sos, sos2, decimal=4) + + # second example + z = np.array([np.exp(theta * deg2rad * 1j) + for theta in (85., 10.)]) + z = np.concatenate((z, np.conj(z), [1, -1])) + sos = zpk2sos(z, p, k) + + # sos2 = [[1, -0.17431, 1, 1, -0.38959, 0.81], # octave "wrong", + # [1, -1.96962, 1, 1, -0.84853, 0.36], # MATLAB fails + # [1, 0, -1, 1, -1.47821, 0.64000]] + # Our pole-zero pairing matches the text, Octave does not + sos2 = [[1, 0, -1, 1, -0.84853, 0.36], + [1, -1.96962, 1, 1, -1.47821, 0.64], + [1, -0.17431, 1, 1, -0.38959, 0.81]] + assert_array_almost_equal(sos, sos2, decimal=4) + + # these examples are taken from the doc string, and show the + # effect of the 'pairing' argument + @pytest.mark.parametrize('pairing, sos', + [('nearest', + np.array([[1., 1., 0.5, 1., -0.75, 0.], + [1., 1., 0., 1., -1.6, 0.65]])), + ('keep_odd', + np.array([[1., 1., 0, 1., -0.75, 0.], + [1., 1., 0.5, 1., -1.6, 0.65]])), + ('minimal', + np.array([[0., 1., 1., 0., 1., -0.75], + [1., 1., 0.5, 1., -1.6, 0.65]]))]) + def test_pairing(self, pairing, sos): + z1 = np.array([-1, -0.5-0.5j, -0.5+0.5j]) + p1 = np.array([0.75, 0.8+0.1j, 0.8-0.1j]) + sos2 = zpk2sos(z1, p1, 1, pairing=pairing) + assert_array_almost_equal(sos, sos2, decimal=4) + + @pytest.mark.parametrize('p, sos_dt', + [([-1, 1, -0.1, 0.1], + [[0., 0., 1., 1., 0., -0.01], + [0., 0., 1., 1., 0., -1]]), + ([-0.7071+0.7071j, -0.7071-0.7071j, -0.1j, 0.1j], + [[0., 0., 1., 1., 0., 0.01], + [0., 0., 1., 1., 1.4142, 1.]])]) + def test_analog(self, p, sos_dt): + # test `analog` argument + # for discrete time, poles closest to unit circle should appear last + # for cont. time, poles closest to imaginary axis should appear last + sos2_dt = zpk2sos([], p, 1, pairing='minimal', analog=False) + sos2_ct = zpk2sos([], p, 1, pairing='minimal', analog=True) + assert_array_almost_equal(sos_dt, sos2_dt, decimal=4) + assert_array_almost_equal(sos_dt[::-1], sos2_ct, decimal=4) + + def test_bad_args(self): + with pytest.raises(ValueError, match=r'pairing must be one of'): + zpk2sos([1], [2], 1, pairing='no_such_pairing') + + with pytest.raises(ValueError, match=r'.*pairing must be "minimal"'): + zpk2sos([1], [2], 1, pairing='keep_odd', analog=True) + + with pytest.raises(ValueError, + match=r'.*must have len\(p\)>=len\(z\)'): + zpk2sos([1, 1], [2], 1, analog=True) + + with pytest.raises(ValueError, match=r'k must be real'): + zpk2sos([1], [2], k=1j) + + +class TestFreqs: + + def test_basic(self): + _, h = freqs([1.0], [1.0], worN=8) + assert_array_almost_equal(h, np.ones(8)) + + def test_output(self): + # 1st order low-pass filter: H(s) = 1 / (s + 1) + w = [0.1, 1, 10, 100] + num = [1] + den = [1, 1] + w, H = freqs(num, den, worN=w) + s = w * 1j + expected = 1 / (s + 1) + assert_array_almost_equal(H.real, expected.real) + assert_array_almost_equal(H.imag, expected.imag) + + def test_freq_range(self): + # Test that freqresp() finds a reasonable frequency range. + # 1st order low-pass filter: H(s) = 1 / (s + 1) + # Expected range is from 0.01 to 10. + num = [1] + den = [1, 1] + n = 10 + expected_w = np.logspace(-2, 1, n) + w, H = freqs(num, den, worN=n) + assert_array_almost_equal(w, expected_w) + + def test_plot(self): + + def plot(w, h): + assert_array_almost_equal(h, np.ones(8)) + + assert_raises(ZeroDivisionError, freqs, [1.0], [1.0], worN=8, + plot=lambda w, h: 1 / 0) + freqs([1.0], [1.0], worN=8, plot=plot) + + def test_backward_compat(self): + # For backward compatibility, test if None act as a wrapper for default + w1, h1 = freqs([1.0], [1.0]) + w2, h2 = freqs([1.0], [1.0], None) + assert_array_almost_equal(w1, w2) + assert_array_almost_equal(h1, h2) + + def test_w_or_N_types(self): + # Measure at 8 equally-spaced points + for N in (8, np.int8(8), np.int16(8), np.int32(8), np.int64(8), + np.array(8)): + w, h = freqs([1.0], [1.0], worN=N) + assert len(w) == 8 + assert_array_almost_equal(h, np.ones(8)) + + # Measure at frequency 8 rad/sec + for w in (8.0, 8.0+0j): + w_out, h = freqs([1.0], [1.0], worN=w) + assert_array_almost_equal(w_out, [8]) + assert_array_almost_equal(h, [1]) + + +class TestFreqs_zpk: + + def test_basic(self): + _, h = freqs_zpk([1.0], [1.0], [1.0], worN=8) + assert_array_almost_equal(h, np.ones(8)) + + def test_output(self): + # 1st order low-pass filter: H(s) = 1 / (s + 1) + w = [0.1, 1, 10, 100] + z = [] + p = [-1] + k = 1 + w, H = freqs_zpk(z, p, k, worN=w) + s = w * 1j + expected = 1 / (s + 1) + assert_array_almost_equal(H.real, expected.real) + assert_array_almost_equal(H.imag, expected.imag) + + def test_freq_range(self): + # Test that freqresp() finds a reasonable frequency range. + # 1st order low-pass filter: H(s) = 1 / (s + 1) + # Expected range is from 0.01 to 10. + z = [] + p = [-1] + k = 1 + n = 10 + expected_w = np.logspace(-2, 1, n) + w, H = freqs_zpk(z, p, k, worN=n) + assert_array_almost_equal(w, expected_w) + + def test_vs_freqs(self): + b, a = cheby1(4, 5, 100, analog=True, output='ba') + z, p, k = cheby1(4, 5, 100, analog=True, output='zpk') + + w1, h1 = freqs(b, a) + w2, h2 = freqs_zpk(z, p, k) + xp_assert_close(w1, w2) + xp_assert_close(h1, h2, rtol=1e-6) + + def test_backward_compat(self): + # For backward compatibility, test if None act as a wrapper for default + w1, h1 = freqs_zpk([1.0], [1.0], [1.0]) + w2, h2 = freqs_zpk([1.0], [1.0], [1.0], None) + assert_array_almost_equal(w1, w2) + assert_array_almost_equal(h1, h2) + + def test_w_or_N_types(self): + # Measure at 8 equally-spaced points + for N in (8, np.int8(8), np.int16(8), np.int32(8), np.int64(8), + np.array(8)): + w, h = freqs_zpk([], [], 1, worN=N) + assert len(w) == 8 + assert_array_almost_equal(h, np.ones(8)) + + # Measure at frequency 8 rad/sec + for w in (8.0, 8.0+0j): + w_out, h = freqs_zpk([], [], 1, worN=w) + assert_array_almost_equal(w_out, [8]) + assert_array_almost_equal(h, [1]) + + +class TestFreqz: + + def test_ticket1441(self): + """Regression test for ticket 1441.""" + # Because freqz previously used arange instead of linspace, + # when N was large, it would return one more point than + # requested. + N = 100000 + w, h = freqz([1.0], worN=N) + assert w.shape == (N,) + + def test_basic(self): + w, h = freqz([1.0], worN=8) + assert_array_almost_equal(w, np.pi * np.arange(8) / 8.) + assert_array_almost_equal(h, np.ones(8)) + w, h = freqz([1.0], worN=9) + assert_array_almost_equal(w, np.pi * np.arange(9) / 9.) + assert_array_almost_equal(h, np.ones(9)) + + for a in [1, np.ones(2)]: + w, h = freqz(np.ones(2), a, worN=0) + assert w.shape == (0,) + assert h.shape == (0,) + assert h.dtype == np.dtype('complex128') + + t = np.linspace(0, 1, 4, endpoint=False) + for b, a, h_whole in zip( + ([1., 0, 0, 0], np.sin(2 * np.pi * t)), + ([1., 0, 0, 0], [0.5, 0, 0, 0]), + ([1., 1., 1., 1.], [0, -4j, 0, 4j])): + w, h = freqz(b, a, worN=4, whole=True) + expected_w = np.linspace(0, 2 * np.pi, 4, endpoint=False) + assert_array_almost_equal(w, expected_w) + assert_array_almost_equal(h, h_whole) + # simultaneously check int-like support + w, h = freqz(b, a, worN=np.int32(4), whole=True) + assert_array_almost_equal(w, expected_w) + assert_array_almost_equal(h, h_whole) + w, h = freqz(b, a, worN=w, whole=True) + assert_array_almost_equal(w, expected_w) + assert_array_almost_equal(h, h_whole) + + def test_basic_whole(self): + w, h = freqz([1.0], worN=8, whole=True) + assert_array_almost_equal(w, 2 * np.pi * np.arange(8.0) / 8) + assert_array_almost_equal(h, np.ones(8)) + + def test_plot(self): + + def plot(w, h): + assert_array_almost_equal(w, np.pi * np.arange(8.0) / 8) + assert_array_almost_equal(h, np.ones(8)) + + assert_raises(ZeroDivisionError, freqz, [1.0], worN=8, + plot=lambda w, h: 1 / 0) + freqz([1.0], worN=8, plot=plot) + + def test_fft_wrapping(self): + # Some simple real FIR filters + bs = list() # filters + as_ = list() + hs_whole = list() + hs_half = list() + # 3 taps + t = np.linspace(0, 1, 3, endpoint=False) + bs.append(np.sin(2 * np.pi * t)) + as_.append(3.) + hs_whole.append([0, -0.5j, 0.5j]) + hs_half.append([0, np.sqrt(1./12.), -0.5j]) + # 4 taps + t = np.linspace(0, 1, 4, endpoint=False) + bs.append(np.sin(2 * np.pi * t)) + as_.append(0.5) + hs_whole.append([0, -4j, 0, 4j]) + hs_half.append([0, np.sqrt(8), -4j, -np.sqrt(8)]) + del t + for ii, b in enumerate(bs): + # whole + a = as_[ii] + expected_w = np.linspace(0, 2 * np.pi, len(b), endpoint=False) + w, h = freqz(b, a, worN=expected_w, whole=True) # polyval + err_msg = f'b = {b}, a={a}' + assert_array_almost_equal(w, expected_w, err_msg=err_msg) + assert_array_almost_equal(h, hs_whole[ii], err_msg=err_msg) + w, h = freqz(b, a, worN=len(b), whole=True) # FFT + assert_array_almost_equal(w, expected_w, err_msg=err_msg) + assert_array_almost_equal(h, hs_whole[ii], err_msg=err_msg) + # non-whole + expected_w = np.linspace(0, np.pi, len(b), endpoint=False) + w, h = freqz(b, a, worN=expected_w, whole=False) # polyval + assert_array_almost_equal(w, expected_w, err_msg=err_msg) + assert_array_almost_equal(h, hs_half[ii], err_msg=err_msg) + w, h = freqz(b, a, worN=len(b), whole=False) # FFT + assert_array_almost_equal(w, expected_w, err_msg=err_msg) + assert_array_almost_equal(h, hs_half[ii], err_msg=err_msg) + + # some random FIR filters (real + complex) + # assume polyval is accurate + rng = np.random.RandomState(0) + for ii in range(2, 10): # number of taps + b = rng.randn(ii) + for kk in range(2): + a = rng.randn(1) if kk == 0 else rng.randn(3) + for jj in range(2): + if jj == 1: + b = b + rng.randn(ii) * 1j + # whole + expected_w = np.linspace(0, 2 * np.pi, ii, endpoint=False) + w, expected_h = freqz(b, a, worN=expected_w, whole=True) + assert_array_almost_equal(w, expected_w) + w, h = freqz(b, a, worN=ii, whole=True) + assert_array_almost_equal(w, expected_w) + assert_array_almost_equal(h, expected_h) + # half + expected_w = np.linspace(0, np.pi, ii, endpoint=False) + w, expected_h = freqz(b, a, worN=expected_w, whole=False) + assert_array_almost_equal(w, expected_w) + w, h = freqz(b, a, worN=ii, whole=False) + assert_array_almost_equal(w, expected_w) + assert_array_almost_equal(h, expected_h) + + def test_broadcasting1(self): + # Test broadcasting with worN an integer or a 1-D array, + # b and a are n-dimensional arrays. + np.random.seed(123) + b = np.random.rand(3, 5, 1) + a = np.random.rand(2, 1) + for whole in [False, True]: + # Test with worN being integers (one fast for FFT and one not), + # a 1-D array, and an empty array. + for worN in [16, 17, np.linspace(0, 1, 10), np.array([])]: + w, h = freqz(b, a, worN=worN, whole=whole) + for k in range(b.shape[1]): + bk = b[:, k, 0] + ak = a[:, 0] + ww, hh = freqz(bk, ak, worN=worN, whole=whole) + xp_assert_close(ww, w) + xp_assert_close(hh, h[k]) + + def test_broadcasting2(self): + # Test broadcasting with worN an integer or a 1-D array, + # b is an n-dimensional array, and a is left at the default value. + np.random.seed(123) + b = np.random.rand(3, 5, 1) + for whole in [False, True]: + for worN in [16, 17, np.linspace(0, 1, 10)]: + w, h = freqz(b, worN=worN, whole=whole) + for k in range(b.shape[1]): + bk = b[:, k, 0] + ww, hh = freqz(bk, worN=worN, whole=whole) + xp_assert_close(ww, w) + xp_assert_close(hh, h[k]) + + def test_broadcasting3(self): + # Test broadcasting where b.shape[-1] is the same length + # as worN, and a is left at the default value. + np.random.seed(123) + N = 16 + b = np.random.rand(3, N) + for whole in [False, True]: + for worN in [N, np.linspace(0, 1, N)]: + w, h = freqz(b, worN=worN, whole=whole) + assert w.size == N + for k in range(N): + bk = b[:, k] + ww, hh = freqz(bk, worN=w[k], whole=whole) + xp_assert_close(ww, np.asarray(w[k])[None]) + xp_assert_close(hh, np.asarray(h[k])[None]) + + def test_broadcasting4(self): + # Test broadcasting with worN a 2-D array. + np.random.seed(123) + b = np.random.rand(4, 2, 1, 1) + a = np.random.rand(5, 2, 1, 1) + for whole in [False, True]: + for worN in [np.random.rand(6, 7), np.empty((6, 0))]: + w, h = freqz(b, a, worN=worN, whole=whole) + xp_assert_close(w, worN, rtol=1e-14) + assert h.shape == (2,) + worN.shape + for k in range(2): + ww, hh = freqz(b[:, k, 0, 0], a[:, k, 0, 0], + worN=worN.ravel(), + whole=whole) + xp_assert_close(ww, worN.ravel(), rtol=1e-14) + xp_assert_close(hh, h[k, :, :].ravel()) + + def test_backward_compat(self): + # For backward compatibility, test if None act as a wrapper for default + w1, h1 = freqz([1.0], 1) + w2, h2 = freqz([1.0], 1, None) + assert_array_almost_equal(w1, w2) + assert_array_almost_equal(h1, h2) + + def test_fs_param(self): + fs = 900 + b = [0.039479155677484369, 0.11843746703245311, 0.11843746703245311, + 0.039479155677484369] + a = [1.0, -1.3199152021838287, 0.80341991081938424, + -0.16767146321568049] + + # N = None, whole=False + w1, h1 = freqz(b, a, fs=fs) + w2, h2 = freqz(b, a) + xp_assert_close(h1, h2) + xp_assert_close(w1, np.linspace(0, fs/2, 512, endpoint=False)) + + # N = None, whole=True + w1, h1 = freqz(b, a, whole=True, fs=fs) + w2, h2 = freqz(b, a, whole=True) + xp_assert_close(h1, h2) + xp_assert_close(w1, np.linspace(0, fs, 512, endpoint=False)) + + # N = 5, whole=False + w1, h1 = freqz(b, a, 5, fs=fs) + w2, h2 = freqz(b, a, 5) + xp_assert_close(h1, h2) + xp_assert_close(w1, np.linspace(0, fs/2, 5, endpoint=False)) + + # N = 5, whole=True + w1, h1 = freqz(b, a, 5, whole=True, fs=fs) + w2, h2 = freqz(b, a, 5, whole=True) + xp_assert_close(h1, h2) + xp_assert_close(w1, np.linspace(0, fs, 5, endpoint=False)) + + # w is an array_like + for w in ([123], (123,), np.array([123]), (50, 123, 230), + np.array([50, 123, 230])): + w1, h1 = freqz(b, a, w, fs=fs) + w2, h2 = freqz(b, a, 2*pi*np.array(w)/fs) + xp_assert_close(h1, h2) + xp_assert_close(w, w1, check_dtype=False) + + def test_w_or_N_types(self): + # Measure at 7 (polyval) or 8 (fft) equally-spaced points + for N in (7, np.int8(7), np.int16(7), np.int32(7), np.int64(7), + np.array(7), + 8, np.int8(8), np.int16(8), np.int32(8), np.int64(8), + np.array(8)): + + w, h = freqz([1.0], worN=N) + assert_array_almost_equal(w, np.pi * np.arange(N) / N) + assert_array_almost_equal(h, np.ones(N)) + + w, h = freqz([1.0], worN=N, fs=100) + assert_array_almost_equal(w, np.linspace(0, 50, N, endpoint=False)) + assert_array_almost_equal(h, np.ones(N)) + + # Measure at frequency 8 Hz + for w in (8.0, 8.0+0j): + # Only makes sense when fs is specified + w_out, h = freqz([1.0], worN=w, fs=100) + assert_array_almost_equal(w_out, [8]) + assert_array_almost_equal(h, [1]) + + def test_nyquist(self): + w, h = freqz([1.0], worN=8, include_nyquist=True) + assert_array_almost_equal(w, np.pi * np.arange(8) / 7.) + assert_array_almost_equal(h, np.ones(8)) + w, h = freqz([1.0], worN=9, include_nyquist=True) + assert_array_almost_equal(w, np.pi * np.arange(9) / 8.) + assert_array_almost_equal(h, np.ones(9)) + + for a in [1, np.ones(2)]: + w, h = freqz(np.ones(2), a, worN=0, include_nyquist=True) + assert w.shape == (0,) + assert h.shape == (0,) + assert h.dtype == np.dtype('complex128') + + w1, h1 = freqz([1.0], worN=8, whole = True, include_nyquist=True) + w2, h2 = freqz([1.0], worN=8, whole = True, include_nyquist=False) + assert_array_almost_equal(w1, w2) + assert_array_almost_equal(h1, h2) + + # https://github.com/scipy/scipy/issues/17289 + # https://github.com/scipy/scipy/issues/15273 + @pytest.mark.parametrize('whole,nyquist,worN', + [(False, False, 32), + (False, True, 32), + (True, False, 32), + (True, True, 32), + (False, False, 257), + (False, True, 257), + (True, False, 257), + (True, True, 257)]) + def test_17289(self, whole, nyquist, worN): + d = [0, 1] + w, Drfft = freqz(d, worN=32, whole=whole, include_nyquist=nyquist) + _, Dpoly = freqz(d, worN=w) + xp_assert_close(Drfft, Dpoly) + + def test_fs_validation(self): + with pytest.raises(ValueError, match="Sampling.*single scalar"): + freqz([1.0], fs=np.array([10, 20])) + + with pytest.raises(ValueError, match="Sampling.*be none."): + freqz([1.0], fs=None) + + +class Testfreqz_sos: + + def test_freqz_sos_basic(self): + # Compare the results of freqz and freqz_sos for a low order + # Butterworth filter. + + N = 500 + + b, a = butter(4, 0.2) + sos = butter(4, 0.2, output='sos') + w, h = freqz(b, a, worN=N) + w2, h2 = freqz_sos(sos, worN=N) + xp_assert_equal(w2, w) + xp_assert_close(h2, h, rtol=1e-10, atol=1e-14) + + b, a = ellip(3, 1, 30, (0.2, 0.3), btype='bandpass') + sos = ellip(3, 1, 30, (0.2, 0.3), btype='bandpass', output='sos') + w, h = freqz(b, a, worN=N) + w2, h2 = freqz_sos(sos, worN=N) + xp_assert_equal(w2, w) + xp_assert_close(h2, h, rtol=1e-10, atol=1e-14) + # must have at least one section + assert_raises(ValueError, freqz_sos, sos[:0]) + + def test_backward_compat(self): + # For backward compatibility, test if None act as a wrapper for default + N = 500 + + sos = butter(4, 0.2, output='sos') + w1, h1 = freqz_sos(sos, worN=N) + w2, h2 = sosfreqz(sos, worN=N) + assert_array_almost_equal(w1, w2) + assert_array_almost_equal(h1, h2) + + def test_freqz_sos_design(self): + # Compare freqz_sos output against expected values for different + # filter types + + # from cheb2ord + N, Wn = cheb2ord([0.1, 0.6], [0.2, 0.5], 3, 60) + sos = cheby2(N, 60, Wn, 'stop', output='sos') + w, h = freqz_sos(sos) + h = np.abs(h) + w /= np.pi + xp_assert_close(20 * np.log10(h[w <= 0.1]), np.asarray(0.), atol=3.01, + check_shape=False) + xp_assert_close(20 * np.log10(h[w >= 0.6]), np.asarray(0.), atol=3.01, + check_shape=False) + xp_assert_close(h[(w >= 0.2) & (w <= 0.5)], + np.asarray(0.), atol=1e-3, + check_shape=False) # <= -60 dB + + N, Wn = cheb2ord([0.1, 0.6], [0.2, 0.5], 3, 150) + sos = cheby2(N, 150, Wn, 'stop', output='sos') + w, h = freqz_sos(sos) + dB = 20*np.log10(np.abs(h)) + w /= np.pi + xp_assert_close(dB[w <= 0.1], np.asarray(0.0), atol=3.01, check_shape=False) + xp_assert_close(dB[w >= 0.6], np.asarray(0.0), atol=3.01, check_shape=False) + assert np.all(dB[(w >= 0.2) & (w <= 0.5)] < -149.9) + + # from cheb1ord + N, Wn = cheb1ord(0.2, 0.3, 3, 40) + sos = cheby1(N, 3, Wn, 'low', output='sos') + w, h = freqz_sos(sos) + h = np.abs(h) + w /= np.pi + xp_assert_close(20 * np.log10(h[w <= 0.2]), np.asarray(0.0), atol=3.01, + check_shape=False) + xp_assert_close(h[w >= 0.3], np.asarray(0.0), atol=1e-2, + check_shape=False) # <= -40 dB + + N, Wn = cheb1ord(0.2, 0.3, 1, 150) + sos = cheby1(N, 1, Wn, 'low', output='sos') + w, h = freqz_sos(sos) + dB = 20*np.log10(np.abs(h)) + w /= np.pi + xp_assert_close(dB[w <= 0.2], np.asarray(0.0), atol=1.01, + check_shape=False) + assert np.all(dB[w >= 0.3] < -149.9) + + # adapted from ellipord + N, Wn = ellipord(0.3, 0.2, 3, 60) + sos = ellip(N, 0.3, 60, Wn, 'high', output='sos') + w, h = freqz_sos(sos) + h = np.abs(h) + w /= np.pi + xp_assert_close(20 * np.log10(h[w >= 0.3]), np.asarray(0.0), atol=3.01, + check_shape=False) + xp_assert_close(h[w <= 0.1], np.asarray(0.0), atol=1.5e-3, + check_shape=False) # <= -60 dB (approx) + + # adapted from buttord + N, Wn = buttord([0.2, 0.5], [0.14, 0.6], 3, 40) + sos = butter(N, Wn, 'band', output='sos') + w, h = freqz_sos(sos) + h = np.abs(h) + w /= np.pi + + h014 = h[w <= 0.14] + xp_assert_close(h014, np.zeros_like(h014), atol=1e-2) # <= -40 dB + h06 = h[w >= 0.6] + xp_assert_close(h06, np.zeros_like(h06), atol=1e-2) # <= -40 dB + h0205 = 20 * np.log10(h[(w >= 0.2) & (w <= 0.5)]) + xp_assert_close(h0205, np.zeros_like(h0205), atol=3.01) + + N, Wn = buttord([0.2, 0.5], [0.14, 0.6], 3, 100) + sos = butter(N, Wn, 'band', output='sos') + w, h = freqz_sos(sos) + dB = 20*np.log10(np.maximum(np.abs(h), 1e-10)) + w /= np.pi + + assert np.all(dB[(w > 0) & (w <= 0.14)] < -99.9) + assert np.all(dB[w >= 0.6] < -99.9) + db0205 = dB[(w >= 0.2) & (w <= 0.5)] + xp_assert_close(db0205, np.zeros_like(db0205), atol=3.01) + + def test_freqz_sos_design_ellip(self): + N, Wn = ellipord(0.3, 0.1, 3, 60) + sos = ellip(N, 0.3, 60, Wn, 'high', output='sos') + w, h = freqz_sos(sos) + h = np.abs(h) + w /= np.pi + + h03 = 20 * np.log10(h[w >= 0.3]) + xp_assert_close(h03, np.zeros_like(h03), atol=3.01) + h01 = h[w <= 0.1] + xp_assert_close(h01, np.zeros_like(h01), atol=1.5e-3) # <= -60 dB (approx) + + N, Wn = ellipord(0.3, 0.2, .5, 150) + sos = ellip(N, .5, 150, Wn, 'high', output='sos') + w, h = freqz_sos(sos) + dB = 20*np.log10(np.maximum(np.abs(h), 1e-10)) + w /= np.pi + + db03 = dB[w >= 0.3] + xp_assert_close(db03, np.zeros_like(db03), atol=.55) + # Allow some numerical slop in the upper bound -150, so this is + # a check that dB[w <= 0.2] is less than or almost equal to -150. + assert dB[w <= 0.2].max() < -150*(1 - 1e-12) + + @mpmath_check("0.10") + def test_freqz_sos_against_mp(self): + # Compare the result of freqz_sos applied to a high order Butterworth + # filter against the result computed using mpmath. (signal.freqz fails + # miserably with such high order filters.) + from . import mpsig + N = 500 + order = 25 + Wn = 0.15 + with mpmath.workdps(80): + z_mp, p_mp, k_mp = mpsig.butter_lp(order, Wn) + w_mp, h_mp = mpsig.zpkfreqz(z_mp, p_mp, k_mp, N) + w_mp = np.array([float(x) for x in w_mp]) + h_mp = np.array([complex(x) for x in h_mp]) + + sos = butter(order, Wn, output='sos') + w, h = freqz_sos(sos, worN=N) + xp_assert_close(w, w_mp, rtol=1e-12, atol=1e-14) + xp_assert_close(h, h_mp, rtol=1e-12, atol=1e-14) + + def test_fs_param(self): + fs = 900 + sos = [[0.03934683014103762, 0.07869366028207524, 0.03934683014103762, + 1.0, -0.37256600288916636, 0.0], + [1.0, 1.0, 0.0, 1.0, -0.9495739996946778, 0.45125966317124144]] + + # N = None, whole=False + w1, h1 = freqz_sos(sos, fs=fs) + w2, h2 = freqz_sos(sos) + xp_assert_close(h1, h2) + xp_assert_close(w1, np.linspace(0, fs/2, 512, endpoint=False)) + + # N = None, whole=True + w1, h1 = freqz_sos(sos, whole=True, fs=fs) + w2, h2 = freqz_sos(sos, whole=True) + xp_assert_close(h1, h2, atol=1e-27) + xp_assert_close(w1, np.linspace(0, fs, 512, endpoint=False)) + + # N = 5, whole=False + w1, h1 = freqz_sos(sos, 5, fs=fs) + w2, h2 = freqz_sos(sos, 5) + xp_assert_close(h1, h2) + xp_assert_close(w1, np.linspace(0, fs/2, 5, endpoint=False)) + + # N = 5, whole=True + w1, h1 = freqz_sos(sos, 5, whole=True, fs=fs) + w2, h2 = freqz_sos(sos, 5, whole=True) + xp_assert_close(h1, h2) + xp_assert_close(w1, np.linspace(0, fs, 5, endpoint=False)) + + # w is an array_like + for w in ([123], (123,), np.array([123]), (50, 123, 230), + np.array([50, 123, 230])): + w1, h1 = freqz_sos(sos, w, fs=fs) + w2, h2 = freqz_sos(sos, 2*pi*np.array(w)/fs) + xp_assert_close(h1, h2) + xp_assert_close(w, w1, check_dtype=False) + + def test_w_or_N_types(self): + # Measure at 7 (polyval) or 8 (fft) equally-spaced points + for N in (7, np.int8(7), np.int16(7), np.int32(7), np.int64(7), + np.array(7), + 8, np.int8(8), np.int16(8), np.int32(8), np.int64(8), + np.array(8)): + + w, h = freqz_sos([1, 0, 0, 1, 0, 0], worN=N) + assert_array_almost_equal(w, np.pi * np.arange(N) / N) + assert_array_almost_equal(h, np.ones(N)) + + w, h = freqz_sos([1, 0, 0, 1, 0, 0], worN=N, fs=100) + assert_array_almost_equal(w, np.linspace(0, 50, N, endpoint=False)) + assert_array_almost_equal(h, np.ones(N)) + + # Measure at frequency 8 Hz + for w in (8.0, 8.0+0j): + # Only makes sense when fs is specified + w_out, h = freqz_sos([1, 0, 0, 1, 0, 0], worN=w, fs=100) + assert_array_almost_equal(w_out, [8]) + assert_array_almost_equal(h, [1]) + + def test_fs_validation(self): + sos = butter(4, 0.2, output='sos') + with pytest.raises(ValueError, match="Sampling.*single scalar"): + freqz_sos(sos, fs=np.array([10, 20])) + + +class TestFreqz_zpk: + + def test_ticket1441(self): + """Regression test for ticket 1441.""" + # Because freqz previously used arange instead of linspace, + # when N was large, it would return one more point than + # requested. + N = 100000 + w, h = freqz_zpk([0.5], [0.5], 1.0, worN=N) + assert w.shape == (N,) + + def test_basic(self): + w, h = freqz_zpk([0.5], [0.5], 1.0, worN=8) + assert_array_almost_equal(w, np.pi * np.arange(8.0) / 8) + assert_array_almost_equal(h, np.ones(8)) + + def test_basic_whole(self): + w, h = freqz_zpk([0.5], [0.5], 1.0, worN=8, whole=True) + assert_array_almost_equal(w, 2 * np.pi * np.arange(8.0) / 8) + assert_array_almost_equal(h, np.ones(8)) + + def test_vs_freqz(self): + b, a = cheby1(4, 5, 0.5, analog=False, output='ba') + z, p, k = cheby1(4, 5, 0.5, analog=False, output='zpk') + + w1, h1 = freqz(b, a) + w2, h2 = freqz_zpk(z, p, k) + xp_assert_close(w1, w2) + xp_assert_close(h1, h2, rtol=1e-6) + + def test_backward_compat(self): + # For backward compatibility, test if None act as a wrapper for default + w1, h1 = freqz_zpk([0.5], [0.5], 1.0) + w2, h2 = freqz_zpk([0.5], [0.5], 1.0, None) + assert_array_almost_equal(w1, w2) + assert_array_almost_equal(h1, h2) + + def test_fs_param(self): + fs = 900 + z = [-1, -1, -1] + p = [0.4747869998473389+0.4752230717749344j, 0.37256600288916636, + 0.4747869998473389-0.4752230717749344j] + k = 0.03934683014103762 + + # N = None, whole=False + w1, h1 = freqz_zpk(z, p, k, whole=False, fs=fs) + w2, h2 = freqz_zpk(z, p, k, whole=False) + xp_assert_close(h1, h2) + xp_assert_close(w1, np.linspace(0, fs/2, 512, endpoint=False)) + + # N = None, whole=True + w1, h1 = freqz_zpk(z, p, k, whole=True, fs=fs) + w2, h2 = freqz_zpk(z, p, k, whole=True) + xp_assert_close(h1, h2) + xp_assert_close(w1, np.linspace(0, fs, 512, endpoint=False)) + + # N = 5, whole=False + w1, h1 = freqz_zpk(z, p, k, 5, fs=fs) + w2, h2 = freqz_zpk(z, p, k, 5) + xp_assert_close(h1, h2) + xp_assert_close(w1, np.linspace(0, fs/2, 5, endpoint=False)) + + # N = 5, whole=True + w1, h1 = freqz_zpk(z, p, k, 5, whole=True, fs=fs) + w2, h2 = freqz_zpk(z, p, k, 5, whole=True) + xp_assert_close(h1, h2) + xp_assert_close(w1, np.linspace(0, fs, 5, endpoint=False)) + + # w is an array_like + for w in ([123], (123,), np.array([123]), (50, 123, 230), + np.array([50, 123, 230])): + w1, h1 = freqz_zpk(z, p, k, w, fs=fs) + w2, h2 = freqz_zpk(z, p, k, 2*pi*np.array(w)/fs) + xp_assert_close(h1, h2) + xp_assert_close(w, w1, check_dtype=False) + + def test_w_or_N_types(self): + # Measure at 8 equally-spaced points + for N in (8, np.int8(8), np.int16(8), np.int32(8), np.int64(8), + np.array(8)): + + w, h = freqz_zpk([], [], 1, worN=N) + assert_array_almost_equal(w, np.pi * np.arange(8) / 8.) + assert_array_almost_equal(h, np.ones(8)) + + w, h = freqz_zpk([], [], 1, worN=N, fs=100) + assert_array_almost_equal(w, np.linspace(0, 50, 8, endpoint=False)) + assert_array_almost_equal(h, np.ones(8)) + + # Measure at frequency 8 Hz + for w in (8.0, 8.0+0j): + # Only makes sense when fs is specified + w_out, h = freqz_zpk([], [], 1, worN=w, fs=100) + assert_array_almost_equal(w_out, [8]) + assert_array_almost_equal(h, [1]) + + def test_fs_validation(self): + with pytest.raises(ValueError, match="Sampling.*single scalar"): + freqz_zpk([1.0], [1.0], [1.0], fs=np.array([10, 20])) + + with pytest.raises(ValueError, match="Sampling.*be none."): + freqz_zpk([1.0], [1.0], [1.0], fs=None) + + +class TestNormalize: + + def test_allclose(self): + """Test for false positive on allclose in normalize() in + filter_design.py""" + # Test to make sure the allclose call within signal.normalize does not + # choose false positives. Then check against a known output from MATLAB + # to make sure the fix doesn't break anything. + + # These are the coefficients returned from + # `[b,a] = cheby1(8, 0.5, 0.048)' + # in MATLAB. There are at least 15 significant figures in each + # coefficient, so it makes sense to test for errors on the order of + # 1e-13 (this can always be relaxed if different platforms have + # different rounding errors) + b_matlab = np.array([2.150733144728282e-11, 1.720586515782626e-10, + 6.022052805239190e-10, 1.204410561047838e-09, + 1.505513201309798e-09, 1.204410561047838e-09, + 6.022052805239190e-10, 1.720586515782626e-10, + 2.150733144728282e-11]) + a_matlab = np.array([1.000000000000000e+00, -7.782402035027959e+00, + 2.654354569747454e+01, -5.182182531666387e+01, + 6.334127355102684e+01, -4.963358186631157e+01, + 2.434862182949389e+01, -6.836925348604676e+00, + 8.412934944449140e-01]) + + # This is the input to signal.normalize after passing through the + # equivalent steps in signal.iirfilter as was done for MATLAB + b_norm_in = np.array([1.5543135865293012e-06, 1.2434508692234413e-05, + 4.3520780422820447e-05, 8.7041560845640893e-05, + 1.0880195105705122e-04, 8.7041560845640975e-05, + 4.3520780422820447e-05, 1.2434508692234413e-05, + 1.5543135865293012e-06]) + a_norm_in = np.array([7.2269025909127173e+04, -5.6242661430467968e+05, + 1.9182761917308895e+06, -3.7451128364682454e+06, + 4.5776121393762771e+06, -3.5869706138592605e+06, + 1.7596511818472347e+06, -4.9409793515707983e+05, + 6.0799461347219651e+04]) + + b_output, a_output = normalize(b_norm_in, a_norm_in) + + # The test on b works for decimal=14 but the one for a does not. For + # the sake of consistency, both of these are decimal=13. If something + # breaks on another platform, it is probably fine to relax this lower. + assert_array_almost_equal(b_matlab, b_output, decimal=13) + assert_array_almost_equal(a_matlab, a_output, decimal=13) + + def test_errors(self): + """Test the error cases.""" + # all zero denominator + assert_raises(ValueError, normalize, [1, 2], 0) + + # denominator not 1 dimensional + assert_raises(ValueError, normalize, [1, 2], [[1]]) + + # numerator too many dimensions + assert_raises(ValueError, normalize, [[[1, 2]]], 1) + + +class TestLp2lp: + + def test_basic(self): + b = [1] + a = [1, np.sqrt(2), 1] + b_lp, a_lp = lp2lp(b, a, 0.38574256627112119) + assert_array_almost_equal(b_lp, [0.1488], decimal=4) + assert_array_almost_equal(a_lp, [1, 0.5455, 0.1488], decimal=4) + + +class TestLp2hp: + + def test_basic(self): + b = [0.25059432325190018] + a = [1, 0.59724041654134863, 0.92834805757524175, 0.25059432325190018] + b_hp, a_hp = lp2hp(b, a, 2*np.pi*5000) + xp_assert_close(b_hp, [1.0, 0, 0, 0]) + xp_assert_close(a_hp, [1, 1.1638e5, 2.3522e9, 1.2373e14], rtol=1e-4) + + +class TestLp2bp: + + def test_basic(self): + b = [1] + a = [1, 2, 2, 1] + b_bp, a_bp = lp2bp(b, a, 2*np.pi*4000, 2*np.pi*2000) + xp_assert_close(b_bp, [1.9844e12, 0, 0, 0], rtol=1e-6) + xp_assert_close(a_bp, [1, 2.5133e4, 2.2108e9, 3.3735e13, + 1.3965e18, 1.0028e22, 2.5202e26], rtol=1e-4) + + +class TestLp2bs: + + def test_basic(self): + b = [1] + a = [1, 1] + b_bs, a_bs = lp2bs(b, a, 0.41722257286366754, 0.18460575326152251) + assert_array_almost_equal(b_bs, [1, 0, 0.17407], decimal=5) + assert_array_almost_equal(a_bs, [1, 0.18461, 0.17407], decimal=5) + + +class TestBilinear: + + def test_basic(self): + b = [0.14879732743343033] + a = [1, 0.54552236880522209, 0.14879732743343033] + b_z, a_z = bilinear(b, a, 0.5) + assert_array_almost_equal(b_z, [0.087821, 0.17564, 0.087821], + decimal=5) + assert_array_almost_equal(a_z, [1, -1.0048, 0.35606], decimal=4) + + b = [1, 0, 0.17407467530697837] + a = [1, 0.18460575326152251, 0.17407467530697837] + b_z, a_z = bilinear(b, a, 0.5) + assert_array_almost_equal(b_z, [0.86413, -1.2158, 0.86413], + decimal=4) + assert_array_almost_equal(a_z, [1, -1.2158, 0.72826], + decimal=4) + + def test_fs_validation(self): + b = [0.14879732743343033] + a = [1, 0.54552236880522209, 0.14879732743343033] + with pytest.raises(ValueError, match="Sampling.*single scalar"): + bilinear(b, a, fs=np.array([10, 20])) + + with pytest.raises(ValueError, match="Sampling.*be none"): + bilinear(b, a, fs=None) + + +class TestLp2lp_zpk: + + def test_basic(self): + z = [] + p = [(-1+1j)/np.sqrt(2), (-1-1j)/np.sqrt(2)] + k = 1 + z_lp, p_lp, k_lp = lp2lp_zpk(z, p, k, 5) + xp_assert_equal(z_lp, []) + xp_assert_close(sort(p_lp), sort(p)*5) + xp_assert_close(k_lp, 25.) + + # Pseudo-Chebyshev with both poles and zeros + z = [-2j, +2j] + p = [-0.75, -0.5-0.5j, -0.5+0.5j] + k = 3 + z_lp, p_lp, k_lp = lp2lp_zpk(z, p, k, 20) + xp_assert_close(sort(z_lp), sort([-40j, +40j])) + xp_assert_close(sort(p_lp), sort([-15, -10-10j, -10+10j])) + xp_assert_close(k_lp, 60.) + + def test_fs_validation(self): + z = [-2j, +2j] + p = [-0.75, -0.5 - 0.5j, -0.5 + 0.5j] + k = 3 + + with pytest.raises(ValueError, match="Sampling.*single scalar"): + bilinear_zpk(z, p, k, fs=np.array([10, 20])) + + with pytest.raises(ValueError, match="Sampling.*be none"): + bilinear_zpk(z, p, k, fs=None) + + +class TestLp2hp_zpk: + + def test_basic(self): + z = [] + p = [(-1+1j)/np.sqrt(2), (-1-1j)/np.sqrt(2)] + k = 1 + + z_hp, p_hp, k_hp = lp2hp_zpk(z, p, k, 5) + xp_assert_equal(z_hp, np.asarray([0.0, 0.0])) + xp_assert_close(sort(p_hp), sort(p)*5) + xp_assert_close(k_hp, 1.0) + + z = [-2j, +2j] + p = [-0.75, -0.5-0.5j, -0.5+0.5j] + k = 3 + z_hp, p_hp, k_hp = lp2hp_zpk(z, p, k, 6) + xp_assert_close(sort(z_hp), sort([-3j, 0, +3j])) + xp_assert_close(sort(p_hp), sort([-8, -6-6j, -6+6j])) + xp_assert_close(k_hp, 32.0) + + +class TestLp2bp_zpk: + + def test_basic(self): + z = [-2j, +2j] + p = [-0.75, -0.5-0.5j, -0.5+0.5j] + k = 3 + z_bp, p_bp, k_bp = lp2bp_zpk(z, p, k, 15, 8) + xp_assert_close(sort(z_bp), sort([-25j, -9j, 0, +9j, +25j])) + xp_assert_close(sort(p_bp), sort([-3 + 6j*sqrt(6), + -3 - 6j*sqrt(6), + +2j+sqrt(-8j-225)-2, + -2j+sqrt(+8j-225)-2, + +2j-sqrt(-8j-225)-2, + -2j-sqrt(+8j-225)-2, ])) + xp_assert_close(k_bp, 24.0) + + +class TestLp2bs_zpk: + + def test_basic(self): + z = [-2j, +2j] + p = [-0.75, -0.5-0.5j, -0.5+0.5j] + k = 3 + + z_bs, p_bs, k_bs = lp2bs_zpk(z, p, k, 35, 12) + + xp_assert_close(sort(z_bs), sort([+35j, -35j, + +3j+sqrt(1234)*1j, + -3j+sqrt(1234)*1j, + +3j-sqrt(1234)*1j, + -3j-sqrt(1234)*1j])) + xp_assert_close(sort(p_bs), sort([+3j*sqrt(129) - 8, + -3j*sqrt(129) - 8, + (-6 + 6j) - sqrt(-1225 - 72j), + (-6 - 6j) - sqrt(-1225 + 72j), + (-6 + 6j) + sqrt(-1225 - 72j), + (-6 - 6j) + sqrt(-1225 + 72j), ])) + xp_assert_close(k_bs, 32.0) + + +class TestBilinear_zpk: + + def test_basic(self): + z = [-2j, +2j] + p = [-0.75, -0.5-0.5j, -0.5+0.5j] + k = 3 + + z_d, p_d, k_d = bilinear_zpk(z, p, k, 10) + + xp_assert_close(sort(z_d), sort([(20-2j)/(20+2j), (20+2j)/(20-2j), + -1])) + xp_assert_close(sort(p_d), sort([77/83, + (1j/2 + 39/2) / (41/2 - 1j/2), + (39/2 - 1j/2) / (1j/2 + 41/2), ])) + xp_assert_close(k_d, 9696/69803) + + +class TestPrototypeType: + + def test_output_type(self): + # Prototypes should consistently output arrays, not lists + # https://github.com/scipy/scipy/pull/441 + for func in (buttap, + besselap, + lambda N: cheb1ap(N, 1), + lambda N: cheb2ap(N, 20), + lambda N: ellipap(N, 1, 20)): + for N in range(7): + z, p, k = func(N) + assert isinstance(z, np.ndarray) + assert isinstance(p, np.ndarray) + + +def dB(x): + # Return magnitude in decibels, avoiding divide-by-zero warnings + # (and deal with some "not less-ordered" errors when -inf shows up) + return 20 * np.log10(np.maximum(np.abs(x), np.finfo(np.float64).tiny)) + + +class TestButtord: + + def test_lowpass(self): + wp = 0.2 + ws = 0.3 + rp = 3 + rs = 60 + N, Wn = buttord(wp, ws, rp, rs, False) + b, a = butter(N, Wn, 'lowpass', False) + w, h = freqz(b, a) + w /= np.pi + assert np.all(-rp < dB(h[w <= wp])) + assert np.all(dB(h[ws <= w]) < -rs) + + assert N == 16 + xp_assert_close(Wn, + 2.0002776782743284e-01, rtol=1e-15) + + def test_highpass(self): + wp = 0.3 + ws = 0.2 + rp = 3 + rs = 70 + N, Wn = buttord(wp, ws, rp, rs, False) + b, a = butter(N, Wn, 'highpass', False) + w, h = freqz(b, a) + w /= np.pi + assert np.all(-rp < dB(h[wp <= w])) + assert np.all(dB(h[w <= ws]) < -rs) + + assert N == 18 + xp_assert_close(Wn, + 2.9996603079132672e-01, rtol=1e-15) + + def test_bandpass(self): + wp = [0.2, 0.5] + ws = [0.1, 0.6] + rp = 3 + rs = 80 + N, Wn = buttord(wp, ws, rp, rs, False) + b, a = butter(N, Wn, 'bandpass', False) + w, h = freqz(b, a) + w /= np.pi + + assert np.all((-rp - 0.1) < dB(h[np.logical_and(wp[0] <= w, w <= wp[1])])) + + assert np.all(dB(h[np.logical_or(w <= ws[0], ws[1] <= w)]) < (-rs + 0.1)) + + assert N == 18 + xp_assert_close(Wn, [1.9998742411409134e-01, 5.0002139595676276e-01], + rtol=1e-15) + + def test_bandstop(self): + wp = [0.1, 0.6] + ws = [0.2, 0.5] + rp = 3 + rs = 90 + N, Wn = buttord(wp, ws, rp, rs, False) + b, a = butter(N, Wn, 'bandstop', False) + w, h = freqz(b, a) + w /= np.pi + + assert np.all(-rp < dB(h[np.logical_or(w <= wp[0], wp[1] <= w)])) + assert np.all(dB(h[np.logical_and(ws[0] <= w, w <= ws[1])]) < -rs) + + assert N == 20 + xp_assert_close(Wn, [1.4759432329294042e-01, 5.9997365985276407e-01], + rtol=1e-6) + + def test_analog(self): + wp = 200 + ws = 600 + rp = 3 + rs = 60 + N, Wn = buttord(wp, ws, rp, rs, True) + b, a = butter(N, Wn, 'lowpass', True) + w, h = freqs(b, a) + assert np.all(-rp < dB(h[w <= wp])) + assert np.all(dB(h[ws <= w]) < -rs) + + assert N == 7 + xp_assert_close(Wn, 2.0006785355671877e+02, rtol=1e-15) + + n, Wn = buttord(1, 550/450, 1, 26, analog=True) + assert n == 19 + xp_assert_close(Wn, 1.0361980524629517, rtol=1e-15) + + xp_assert_equal(buttord(1, 1.2, 1, 80, analog=True)[0], 55) + + def test_fs_param(self): + wp = [4410, 11025] + ws = [2205, 13230] + rp = 3 + rs = 80 + fs = 44100 + N, Wn = buttord(wp, ws, rp, rs, False, fs=fs) + b, a = butter(N, Wn, 'bandpass', False, fs=fs) + w, h = freqz(b, a, fs=fs) + assert np.all(-rp - 0.1 < dB(h[np.logical_and(wp[0] <= w, w <= wp[1])])) + assert np.all(dB(h[np.logical_or(w <= ws[0], ws[1] <= w)]) < -rs + 0.1) + + assert N == 18 + xp_assert_close(Wn, [4409.722701715714, 11025.47178084662], + rtol=1e-15) + + def test_invalid_input(self): + with pytest.raises(ValueError) as exc_info: + buttord([20, 50], [14, 60], 3, 2) + assert "gpass should be smaller than gstop" in str(exc_info.value) + + with pytest.raises(ValueError) as exc_info: + buttord([20, 50], [14, 60], -1, 2) + assert "gpass should be larger than 0.0" in str(exc_info.value) + + with pytest.raises(ValueError) as exc_info: + buttord([20, 50], [14, 60], 1, -2) + assert "gstop should be larger than 0.0" in str(exc_info.value) + + @pytest.mark.thread_unsafe + def test_runtime_warnings(self): + msg = "Order is zero.*|divide by zero encountered" + with pytest.warns(RuntimeWarning, match=msg): + buttord(0.0, 1.0, 3, 60) + + def test_ellip_butter(self): + # The purpose of the test is to compare to some known output from past + # scipy versions. The values to compare to are generated with scipy + # 1.9.1 (there is nothing special about this particular version though) + n, wn = buttord([0.1, 0.6], [0.2, 0.5], 3, 60) + assert n == 14 + + def test_fs_validation(self): + wp = 0.2 + ws = 0.3 + rp = 3 + rs = 60 + + with pytest.raises(ValueError, match="Sampling.*single scalar"): + buttord(wp, ws, rp, rs, False, fs=np.array([10, 20])) + + +class TestCheb1ord: + + def test_lowpass(self): + wp = 0.2 + ws = 0.3 + rp = 3 + rs = 60 + N, Wn = cheb1ord(wp, ws, rp, rs, False) + b, a = cheby1(N, rp, Wn, 'low', False) + w, h = freqz(b, a) + w /= np.pi + assert np.all(-rp - 0.1 < dB(h[w <= wp])) + assert np.all(dB(h[ws <= w]) < -rs + 0.1) + + assert N == 8 + xp_assert_close(Wn, 0.2, rtol=1e-15) + + def test_highpass(self): + wp = 0.3 + ws = 0.2 + rp = 3 + rs = 70 + N, Wn = cheb1ord(wp, ws, rp, rs, False) + b, a = cheby1(N, rp, Wn, 'high', False) + w, h = freqz(b, a) + w /= np.pi + assert np.all(-rp - 0.1 < dB(h[wp <= w])) + assert np.all(dB(h[w <= ws]) < -rs + 0.1) + + assert N == 9 + xp_assert_close(Wn, 0.3, rtol=1e-15) + + def test_bandpass(self): + wp = [0.2, 0.5] + ws = [0.1, 0.6] + rp = 3 + rs = 80 + N, Wn = cheb1ord(wp, ws, rp, rs, False) + b, a = cheby1(N, rp, Wn, 'band', False) + w, h = freqz(b, a) + w /= np.pi + assert np.all(-rp - 0.1 < dB(h[np.logical_and(wp[0] <= w, w <= wp[1])])) + assert np.all(dB(h[np.logical_or(w <= ws[0], ws[1] <= w)]) < -rs + 0.1) + + assert N == 9 + xp_assert_close(Wn, [0.2, 0.5], rtol=1e-15) + + def test_bandstop(self): + wp = [0.1, 0.6] + ws = [0.2, 0.5] + rp = 3 + rs = 90 + N, Wn = cheb1ord(wp, ws, rp, rs, False) + b, a = cheby1(N, rp, Wn, 'stop', False) + w, h = freqz(b, a) + w /= np.pi + assert np.all(-rp - 0.1 < dB(h[np.logical_or(w <= wp[0], wp[1] <= w)])) + assert np.all(dB(h[np.logical_and(ws[0] <= w, w <= ws[1])]) < -rs + 0.1) + + assert N == 10 + xp_assert_close(Wn, [0.14758232569947785, 0.6], rtol=1e-5) + + def test_analog(self): + wp = 700 + ws = 100 + rp = 3 + rs = 70 + N, Wn = cheb1ord(wp, ws, rp, rs, True) + b, a = cheby1(N, rp, Wn, 'high', True) + w, h = freqs(b, a) + assert np.all(-rp - 0.1 < dB(h[wp <= w])) + assert np.all(dB(h[w <= ws]) < -rs + 0.1) + + assert N == 4 + xp_assert_close(Wn, 700.0, rtol=1e-15) + + xp_assert_equal(cheb1ord(1, 1.2, 1, 80, analog=True)[0], 17) + + def test_fs_param(self): + wp = 4800 + ws = 7200 + rp = 3 + rs = 60 + fs = 48000 + N, Wn = cheb1ord(wp, ws, rp, rs, False, fs=fs) + b, a = cheby1(N, rp, Wn, 'low', False, fs=fs) + w, h = freqz(b, a, fs=fs) + assert np.all(-rp - 0.1 < dB(h[w <= wp])) + assert np.all(dB(h[ws <= w]) < -rs + 0.1) + + assert N == 8 + xp_assert_close(Wn, 4800.0, rtol=1e-15) + + def test_invalid_input(self): + with pytest.raises(ValueError) as exc_info: + cheb1ord(0.2, 0.3, 3, 2) + assert "gpass should be smaller than gstop" in str(exc_info.value) + + with pytest.raises(ValueError) as exc_info: + cheb1ord(0.2, 0.3, -1, 2) + assert "gpass should be larger than 0.0" in str(exc_info.value) + + with pytest.raises(ValueError) as exc_info: + cheb1ord(0.2, 0.3, 1, -2) + assert "gstop should be larger than 0.0" in str(exc_info.value) + + def test_ellip_cheb1(self): + # The purpose of the test is to compare to some known output from past + # scipy versions. The values to compare to are generated with scipy + # 1.9.1 (there is nothing special about this particular version though) + n, wn = cheb1ord([0.1, 0.6], [0.2, 0.5], 3, 60) + assert n == 7 + + n2, w2 = cheb2ord([0.1, 0.6], [0.2, 0.5], 3, 60) + assert not (wn == w2).all() + + def test_fs_validation(self): + wp = 0.2 + ws = 0.3 + rp = 3 + rs = 60 + + with pytest.raises(ValueError, match="Sampling.*single scalar"): + cheb1ord(wp, ws, rp, rs, False, fs=np.array([10, 20])) + + +class TestCheb2ord: + + def test_lowpass(self): + wp = 0.2 + ws = 0.3 + rp = 3 + rs = 60 + N, Wn = cheb2ord(wp, ws, rp, rs, False) + b, a = cheby2(N, rs, Wn, 'lp', False) + w, h = freqz(b, a) + w /= np.pi + assert np.all(-rp - 0.1 < dB(h[w <= wp])) + assert np.all(dB(h[ws <= w]) < -rs + 0.1) + + assert N == 8 + xp_assert_close(Wn, 0.28647639976553163, rtol=1e-15) + + def test_highpass(self): + wp = 0.3 + ws = 0.2 + rp = 3 + rs = 70 + N, Wn = cheb2ord(wp, ws, rp, rs, False) + b, a = cheby2(N, rs, Wn, 'hp', False) + w, h = freqz(b, a) + w /= np.pi + assert np.all(-rp - 0.1 < dB(h[wp <= w])) + assert np.all(dB(h[w <= ws]) < -rs + 0.1) + + assert N == 9 + xp_assert_close(Wn, 0.20697492182903282, rtol=1e-15) + + def test_bandpass(self): + wp = [0.2, 0.5] + ws = [0.1, 0.6] + rp = 3 + rs = 80 + N, Wn = cheb2ord(wp, ws, rp, rs, False) + b, a = cheby2(N, rs, Wn, 'bp', False) + w, h = freqz(b, a) + w /= np.pi + assert np.all(-rp - 0.1 < dB(h[np.logical_and(wp[0] <= w, w <= wp[1])])) + assert np.all(dB(h[np.logical_or(w <= ws[0], ws[1] <= w)]) < -rs + 0.1) + + assert N == 9 + xp_assert_close(Wn, [0.14876937565923479, 0.59748447842351482], + rtol=1e-15) + + def test_bandstop(self): + wp = [0.1, 0.6] + ws = [0.2, 0.5] + rp = 3 + rs = 90 + N, Wn = cheb2ord(wp, ws, rp, rs, False) + b, a = cheby2(N, rs, Wn, 'bs', False) + w, h = freqz(b, a) + w /= np.pi + assert np.all(-rp - 0.1 < dB(h[np.logical_or(w <= wp[0], wp[1] <= w)])) + assert np.all(dB(h[np.logical_and(ws[0] <= w, w <= ws[1])]) < -rs + 0.1) + + assert N == 10 + xp_assert_close(Wn, [0.19926249974781743, 0.50125246585567362], + rtol=1e-6) + + def test_analog(self): + wp = [20, 50] + ws = [10, 60] + rp = 3 + rs = 80 + N, Wn = cheb2ord(wp, ws, rp, rs, True) + b, a = cheby2(N, rs, Wn, 'bp', True) + w, h = freqs(b, a) + assert np.all(-rp - 0.1 < dB(h[np.logical_and(wp[0] <= w, w <= wp[1])])) + assert np.all(dB(h[np.logical_or(w <= ws[0], ws[1] <= w)]) < -rs + 0.1) + + assert N == 11 + xp_assert_close(Wn, [1.673740595370124e+01, 5.974641487254268e+01], + rtol=1e-15) + + def test_fs_param(self): + wp = 150 + ws = 100 + rp = 3 + rs = 70 + fs = 1000 + N, Wn = cheb2ord(wp, ws, rp, rs, False, fs=fs) + b, a = cheby2(N, rs, Wn, 'hp', False, fs=fs) + w, h = freqz(b, a, fs=fs) + assert np.all(-rp - 0.1 < dB(h[wp <= w])) + assert np.all(dB(h[w <= ws]) < -rs + 0.1) + + assert N == 9 + xp_assert_close(Wn, 103.4874609145164, rtol=1e-15) + + def test_invalid_input(self): + with pytest.raises(ValueError) as exc_info: + cheb2ord([0.1, 0.6], [0.2, 0.5], 3, 2) + assert "gpass should be smaller than gstop" in str(exc_info.value) + + with pytest.raises(ValueError) as exc_info: + cheb2ord([0.1, 0.6], [0.2, 0.5], -1, 2) + assert "gpass should be larger than 0.0" in str(exc_info.value) + + with pytest.raises(ValueError) as exc_info: + cheb2ord([0.1, 0.6], [0.2, 0.5], 1, -2) + assert "gstop should be larger than 0.0" in str(exc_info.value) + + def test_ellip_cheb2(self): + # The purpose of the test is to compare to some known output from past + # scipy versions. The values to compare to are generated with scipy + # 1.9.1 (there is nothing special about this particular version though) + n, wn = cheb2ord([0.1, 0.6], [0.2, 0.5], 3, 60) + assert n == 7 + + n1, w1 = cheb1ord([0.1, 0.6], [0.2, 0.5], 3, 60) + assert not (wn == w1).all() + + def test_fs_validation(self): + wp = 0.2 + ws = 0.3 + rp = 3 + rs = 60 + + with pytest.raises(ValueError, match="Sampling.*single scalar"): + cheb2ord(wp, ws, rp, rs, False, fs=np.array([10, 20])) + + +class TestEllipord: + + def test_lowpass(self): + wp = 0.2 + ws = 0.3 + rp = 3 + rs = 60 + N, Wn = ellipord(wp, ws, rp, rs, False) + b, a = ellip(N, rp, rs, Wn, 'lp', False) + w, h = freqz(b, a) + w /= np.pi + assert np.all(-rp - 0.1 < dB(h[w <= wp])) + assert np.all(dB(h[ws <= w]) < -rs + 0.1) + + assert N == 5 + xp_assert_close(Wn, 0.2, rtol=1e-15) + + def test_lowpass_1000dB(self): + # failed when ellipkm1 wasn't used in ellipord and ellipap + wp = 0.2 + ws = 0.3 + rp = 3 + rs = 1000 + N, Wn = ellipord(wp, ws, rp, rs, False) + sos = ellip(N, rp, rs, Wn, 'lp', False, output='sos') + w, h = freqz_sos(sos) + w /= np.pi + assert np.all(-rp - 0.1 < dB(h[w <= wp])) + assert np.all(dB(h[ws <= w]) < -rs + 0.1) + + def test_highpass(self): + wp = 0.3 + ws = 0.2 + rp = 3 + rs = 70 + N, Wn = ellipord(wp, ws, rp, rs, False) + b, a = ellip(N, rp, rs, Wn, 'hp', False) + w, h = freqz(b, a) + w /= np.pi + assert np.all(-rp - 0.1 < dB(h[wp <= w])) + assert np.all(dB(h[w <= ws]) < -rs + 0.1) + + assert N == 6 + xp_assert_close(Wn, 0.3, rtol=1e-15) + + def test_bandpass(self): + wp = [0.2, 0.5] + ws = [0.1, 0.6] + rp = 3 + rs = 80 + N, Wn = ellipord(wp, ws, rp, rs, False) + b, a = ellip(N, rp, rs, Wn, 'bp', False) + w, h = freqz(b, a) + w /= np.pi + assert np.all(-rp - 0.1 < dB(h[np.logical_and(wp[0] <= w, w <= wp[1])])) + assert np.all(dB(h[np.logical_or(w <= ws[0], ws[1] <= w)]) < -rs + 0.1) + + assert N == 6 + xp_assert_close(Wn, [0.2, 0.5], rtol=1e-15) + + def test_bandstop(self): + wp = [0.1, 0.6] + ws = [0.2, 0.5] + rp = 3 + rs = 90 + N, Wn = ellipord(wp, ws, rp, rs, False) + b, a = ellip(N, rp, rs, Wn, 'bs', False) + w, h = freqz(b, a) + w /= np.pi + assert np.all(-rp - 0.1 < dB(h[np.logical_or(w <= wp[0], wp[1] <= w)])) + assert np.all(dB(h[np.logical_and(ws[0] <= w, w <= ws[1])]) < -rs + 0.1) + + assert N == 7 + xp_assert_close(Wn, [0.14758232794342988, 0.6], rtol=1e-5) + + def test_analog(self): + wp = [1000, 6000] + ws = [2000, 5000] + rp = 3 + rs = 90 + N, Wn = ellipord(wp, ws, rp, rs, True) + b, a = ellip(N, rp, rs, Wn, 'bs', True) + w, h = freqs(b, a) + assert np.all(-rp - 0.1 < dB(h[np.logical_or(w <= wp[0], wp[1] <= w)])) + assert np.all(dB(h[np.logical_and(ws[0] <= w, w <= ws[1])]) < -rs + 0.1) + + assert N == 8 + xp_assert_close(Wn, [1666.6666, 6000]) + + assert ellipord(1, 1.2, 1, 80, analog=True)[0] == 9 + + def test_fs_param(self): + wp = [400, 2400] + ws = [800, 2000] + rp = 3 + rs = 90 + fs = 8000 + N, Wn = ellipord(wp, ws, rp, rs, False, fs=fs) + b, a = ellip(N, rp, rs, Wn, 'bs', False, fs=fs) + w, h = freqz(b, a, fs=fs) + assert np.all(-rp - 0.1 < dB(h[np.logical_or(w <= wp[0], wp[1] <= w)])) + assert np.all(dB(h[np.logical_and(ws[0] <= w, w <= ws[1])]) < -rs + 0.1) + + assert N == 7 + xp_assert_close(Wn, [590.3293117737195, 2400], rtol=1e-5) + + def test_invalid_input(self): + with pytest.raises(ValueError) as exc_info: + ellipord(0.2, 0.5, 3, 2) + assert "gpass should be smaller than gstop" in str(exc_info.value) + + with pytest.raises(ValueError) as exc_info: + ellipord(0.2, 0.5, -1, 2) + assert "gpass should be larger than 0.0" in str(exc_info.value) + + with pytest.raises(ValueError) as exc_info: + ellipord(0.2, 0.5, 1, -2) + assert "gstop should be larger than 0.0" in str(exc_info.value) + + def test_ellip_butter(self): + # The purpose of the test is to compare to some known output from past + # scipy versions. The values to compare to are generated with scipy + # 1.9.1 (there is nothing special about this particular version though) + n, wn = ellipord([0.1, 0.6], [0.2, 0.5], 3, 60) + assert n == 5 + + def test_fs_validation(self): + wp = 0.2 + ws = 0.3 + rp = 3 + rs = 60 + + with pytest.raises(ValueError, match="Sampling.*single scalar"): + ellipord(wp, ws, rp, rs, False, fs=np.array([10, 20])) + + +class TestBessel: + + def test_degenerate(self): + for norm in ('delay', 'phase', 'mag'): + # 0-order filter is just a passthrough + b, a = bessel(0, 1, analog=True, norm=norm) + xp_assert_equal(b, np.asarray([1.0])) + xp_assert_equal(a, np.asarray([1.0])) + + # 1-order filter is same for all types + b, a = bessel(1, 1, analog=True, norm=norm) + xp_assert_close(b, np.asarray([1.0]), rtol=1e-15) + xp_assert_close(a, np.asarray([1.0, 1]), rtol=1e-15) + + z, p, k = bessel(1, 0.3, analog=True, output='zpk', norm=norm) + xp_assert_equal(z, np.asarray([])) + xp_assert_close(p, np.asarray([-0.3+0j]), rtol=1e-14) + xp_assert_close(k, 0.3, rtol=1e-14) + + def test_high_order(self): + # high even order, 'phase' + z, p, k = bessel(24, 100, analog=True, output='zpk') + z2 = [] + p2 = [ + -9.055312334014323e+01 + 4.844005815403969e+00j, + -8.983105162681878e+01 + 1.454056170018573e+01j, + -8.837357994162065e+01 + 2.426335240122282e+01j, + -8.615278316179575e+01 + 3.403202098404543e+01j, + -8.312326467067703e+01 + 4.386985940217900e+01j, + -7.921695461084202e+01 + 5.380628489700191e+01j, + -7.433392285433246e+01 + 6.388084216250878e+01j, + -6.832565803501586e+01 + 7.415032695116071e+01j, + -6.096221567378025e+01 + 8.470292433074425e+01j, + -5.185914574820616e+01 + 9.569048385258847e+01j, + -4.027853855197555e+01 + 1.074195196518679e+02j, + -2.433481337524861e+01 + 1.207298683731973e+02j, + ] + k2 = 9.999999999999989e+47 + xp_assert_equal(z, z2) + xp_assert_close(sorted(p, key=np.imag), + sorted(np.union1d(p2, np.conj(p2)), key=np.imag)) + xp_assert_close(k, k2, rtol=1e-14) + + # high odd order, 'phase' + z, p, k = bessel(23, 1000, analog=True, output='zpk') + z2 = [] + p2 = [ + -2.497697202208956e+02 + 1.202813187870698e+03j, + -4.126986617510172e+02 + 1.065328794475509e+03j, + -5.304922463809596e+02 + 9.439760364018479e+02j, + -9.027564978975828e+02 + 1.010534334242318e+02j, + -8.909283244406079e+02 + 2.023024699647598e+02j, + -8.709469394347836e+02 + 3.039581994804637e+02j, + -8.423805948131370e+02 + 4.062657947488952e+02j, + -8.045561642249877e+02 + 5.095305912401127e+02j, + -7.564660146766259e+02 + 6.141594859516342e+02j, + -6.965966033906477e+02 + 7.207341374730186e+02j, + -6.225903228776276e+02 + 8.301558302815096e+02j, + -9.066732476324988e+02] + k2 = 9.999999999999983e+68 + xp_assert_equal(z, z2) + xp_assert_close(sorted(p, key=np.imag), + sorted(np.union1d(p2, np.conj(p2)), key=np.imag)) + xp_assert_close(k, k2, rtol=1e-14) + + # high even order, 'delay' (Orchard 1965 "The Roots of the + # Maximally Flat-Delay Polynomials" Table 1) + z, p, k = bessel(31, 1, analog=True, output='zpk', norm='delay') + p2 = [-20.876706, + -20.826543 + 1.735732j, + -20.675502 + 3.473320j, + -20.421895 + 5.214702j, + -20.062802 + 6.961982j, + -19.593895 + 8.717546j, + -19.009148 + 10.484195j, + -18.300400 + 12.265351j, + -17.456663 + 14.065350j, + -16.463032 + 15.889910j, + -15.298849 + 17.746914j, + -13.934466 + 19.647827j, + -12.324914 + 21.610519j, + -10.395893 + 23.665701j, + - 8.005600 + 25.875019j, + - 4.792045 + 28.406037j, + ] + xp_assert_close(sorted(p, key=np.imag), + sorted(np.union1d(p2, np.conj(p2)), key=np.imag)) + + # high odd order, 'delay' + z, p, k = bessel(30, 1, analog=True, output='zpk', norm='delay') + p2 = [-20.201029 + 0.867750j, + -20.097257 + 2.604235j, + -19.888485 + 4.343721j, + -19.572188 + 6.088363j, + -19.144380 + 7.840570j, + -18.599342 + 9.603147j, + -17.929195 + 11.379494j, + -17.123228 + 13.173901j, + -16.166808 + 14.992008j, + -15.039580 + 16.841580j, + -13.712245 + 18.733902j, + -12.140295 + 20.686563j, + -10.250119 + 22.729808j, + - 7.901170 + 24.924391j, + - 4.734679 + 27.435615j, + ] + xp_assert_close(sorted(p, key=np.imag), + sorted(np.union1d(p2, np.conj(p2)), key=np.imag)) + + def test_refs(self): + # Compare to http://www.crbond.com/papers/bsf2.pdf + # "Delay Normalized Bessel Polynomial Coefficients" + bond_b = np.asarray([10395.0]) + bond_a = np.asarray([1.0, 21, 210, 1260, 4725, 10395, 10395]) + b, a = bessel(6, 1, norm='delay', analog=True) + xp_assert_close(b, bond_b) + xp_assert_close(a, bond_a) + + # "Delay Normalized Bessel Pole Locations" + bond_poles = { + 1: [-1.0000000000], + 2: [-1.5000000000 + 0.8660254038j], + 3: [-1.8389073227 + 1.7543809598j, -2.3221853546], + 4: [-2.1037893972 + 2.6574180419j, -2.8962106028 + 0.8672341289j], + 5: [-2.3246743032 + 3.5710229203j, -3.3519563992 + 1.7426614162j, + -3.6467385953], + 6: [-2.5159322478 + 4.4926729537j, -3.7357083563 + 2.6262723114j, + -4.2483593959 + 0.8675096732j], + 7: [-2.6856768789 + 5.4206941307j, -4.0701391636 + 3.5171740477j, + -4.7582905282 + 1.7392860611j, -4.9717868585], + 8: [-2.8389839489 + 6.3539112986j, -4.3682892172 + 4.4144425005j, + -5.2048407906 + 2.6161751526j, -5.5878860433 + 0.8676144454j], + 9: [-2.9792607982 + 7.2914636883j, -4.6384398872 + 5.3172716754j, + -5.6044218195 + 3.4981569179j, -6.1293679043 + 1.7378483835j, + -6.2970191817], + 10: [-3.1089162336 + 8.2326994591j, -4.8862195669 + 6.2249854825j, + -5.9675283286 + 4.3849471889j, -6.6152909655 + 2.6115679208j, + -6.9220449054 + 0.8676651955j] + } + + for N in range(1, 11): + p1 = np.sort(bond_poles[N]) + p2 = np.sort(np.concatenate(_cplxreal(besselap(N, 'delay')[1]))) + assert_array_almost_equal(p1, p2, decimal=10) + + # "Frequency Normalized Bessel Pole Locations" + bond_poles = { + 1: [-1.0000000000], + 2: [-1.1016013306 + 0.6360098248j], + 3: [-1.0474091610 + 0.9992644363j, -1.3226757999], + 4: [-0.9952087644 + 1.2571057395j, -1.3700678306 + 0.4102497175j], + 5: [-0.9576765486 + 1.4711243207j, -1.3808773259 + 0.7179095876j, + -1.5023162714], + 6: [-0.9306565229 + 1.6618632689j, -1.3818580976 + 0.9714718907j, + -1.5714904036 + 0.3208963742j], + 7: [-0.9098677806 + 1.8364513530j, -1.3789032168 + 1.1915667778j, + -1.6120387662 + 0.5892445069j, -1.6843681793], + 8: [-0.8928697188 + 1.9983258436j, -1.3738412176 + 1.3883565759j, + -1.6369394181 + 0.8227956251j, -1.7574084004 + 0.2728675751j], + 9: [-0.8783992762 + 2.1498005243j, -1.3675883098 + 1.5677337122j, + -1.6523964846 + 1.0313895670j, -1.8071705350 + 0.5123837306j, + -1.8566005012], + 10: [-0.8657569017 + 2.2926048310j, -1.3606922784 + 1.7335057427j, + -1.6618102414 + 1.2211002186j, -1.8421962445 + 0.7272575978j, + -1.9276196914 + 0.2416234710j] + } + + for N in range(1, 11): + p1 = np.sort(bond_poles[N]) + p2 = np.sort(np.concatenate(_cplxreal(besselap(N, 'mag')[1]))) + assert_array_almost_equal(p1, p2, decimal=10) + + # Compare to https://www.ranecommercial.com/legacy/note147.html + # "Table 1 - Bessel Crossovers of Second, Third, and Fourth-Order" + a = np.asarray([1, 1, 1/3]) + b2, a2 = bessel(2, 1, norm='delay', analog=True) + xp_assert_close(a[::-1], a2/b2) + + a = np.asarray([1, 1, 2/5, 1/15]) + b2, a2 = bessel(3, 1, norm='delay', analog=True) + xp_assert_close(a[::-1], a2/b2) + + a = np.asarray([1, 1, 9/21, 2/21, 1/105]) + b2, a2 = bessel(4, 1, norm='delay', analog=True) + xp_assert_close(a[::-1], a2/b2) + + a = np.asarray([1, np.sqrt(3), 1]) + b2, a2 = bessel(2, 1, norm='phase', analog=True) + xp_assert_close(a[::-1], a2/b2) + + # TODO: Why so inaccurate? Is reference flawed? + a = np.asarray([1, 2.481, 2.463, 1.018]) + b2, a2 = bessel(3, 1, norm='phase', analog=True) + assert_array_almost_equal(a[::-1], a2/b2, decimal=1) + + # TODO: Why so inaccurate? Is reference flawed? + a = np.asarray([1, 3.240, 4.5, 3.240, 1.050]) + b2, a2 = bessel(4, 1, norm='phase', analog=True) + assert_array_almost_equal(a[::-1], a2/b2, decimal=1) + + # Table of -3 dB factors: + N, scale = 2, np.asarray([1.272, 1.272], dtype=np.complex128) + scale2 = besselap(N, 'mag')[1] / besselap(N, 'phase')[1] + assert_array_almost_equal(scale2, scale, decimal=3) + + # TODO: Why so inaccurate? Is reference flawed? + N, scale = 3, np.asarray([1.413, 1.413, 1.413], dtype=np.complex128) + scale2 = besselap(N, 'mag')[1] / besselap(N, 'phase')[1] + assert_array_almost_equal(scale2, scale, decimal=2) + + # TODO: Why so inaccurate? Is reference flawed? + N, scale = 4, np.asarray([1.533]*4, dtype=np.complex128) + scale2 = besselap(N, 'mag')[1] / besselap(N, 'phase')[1] + assert_array_almost_equal(scale, scale2, decimal=1) + + def test_hardcoded(self): + # Compare to values from original hardcoded implementation + originals = { + 0: [], + 1: [-1], + 2: [-.8660254037844386467637229 + .4999999999999999999999996j], + 3: [-.9416000265332067855971980, + -.7456403858480766441810907 + .7113666249728352680992154j], + 4: [-.6572111716718829545787788 + .8301614350048733772399715j, + -.9047587967882449459642624 + .2709187330038746636700926j], + 5: [-.9264420773877602247196260, + -.8515536193688395541722677 + .4427174639443327209850002j, + -.5905759446119191779319432 + .9072067564574549539291747j], + 6: [-.9093906830472271808050953 + .1856964396793046769246397j, + -.7996541858328288520243325 + .5621717346937317988594118j, + -.5385526816693109683073792 + .9616876881954277199245657j], + 7: [-.9194871556490290014311619, + -.8800029341523374639772340 + .3216652762307739398381830j, + -.7527355434093214462291616 + .6504696305522550699212995j, + -.4966917256672316755024763 + 1.002508508454420401230220j], + 8: [-.9096831546652910216327629 + .1412437976671422927888150j, + -.8473250802359334320103023 + .4259017538272934994996429j, + -.7111381808485399250796172 + .7186517314108401705762571j, + -.4621740412532122027072175 + 1.034388681126901058116589j], + 9: [-.9154957797499037686769223, + -.8911217017079759323183848 + .2526580934582164192308115j, + -.8148021112269012975514135 + .5085815689631499483745341j, + -.6743622686854761980403401 + .7730546212691183706919682j, + -.4331415561553618854685942 + 1.060073670135929666774323j], + 10: [-.9091347320900502436826431 + .1139583137335511169927714j, + -.8688459641284764527921864 + .3430008233766309973110589j, + -.7837694413101441082655890 + .5759147538499947070009852j, + -.6417513866988316136190854 + .8175836167191017226233947j, + -.4083220732868861566219785 + 1.081274842819124562037210j], + 11: [-.9129067244518981934637318, + -.8963656705721166099815744 + .2080480375071031919692341j, + -.8453044014712962954184557 + .4178696917801248292797448j, + -.7546938934722303128102142 + .6319150050721846494520941j, + -.6126871554915194054182909 + .8547813893314764631518509j, + -.3868149510055090879155425 + 1.099117466763120928733632j], + 12: [-.9084478234140682638817772 + 95506365213450398415258360e-27j, + -.8802534342016826507901575 + .2871779503524226723615457j, + -.8217296939939077285792834 + .4810212115100676440620548j, + -.7276681615395159454547013 + .6792961178764694160048987j, + -.5866369321861477207528215 + .8863772751320727026622149j, + -.3679640085526312839425808 + 1.114373575641546257595657j], + 13: [-.9110914665984182781070663, + -.8991314665475196220910718 + .1768342956161043620980863j, + -.8625094198260548711573628 + .3547413731172988997754038j, + -.7987460692470972510394686 + .5350752120696801938272504j, + -.7026234675721275653944062 + .7199611890171304131266374j, + -.5631559842430199266325818 + .9135900338325109684927731j, + -.3512792323389821669401925 + 1.127591548317705678613239j], + 14: [-.9077932138396487614720659 + 82196399419401501888968130e-27j, + -.8869506674916445312089167 + .2470079178765333183201435j, + -.8441199160909851197897667 + .4131653825102692595237260j, + -.7766591387063623897344648 + .5819170677377608590492434j, + -.6794256425119233117869491 + .7552857305042033418417492j, + -.5418766775112297376541293 + .9373043683516919569183099j, + -.3363868224902037330610040 + 1.139172297839859991370924j], + 15: [-.9097482363849064167228581, + -.9006981694176978324932918 + .1537681197278439351298882j, + -.8731264620834984978337843 + .3082352470564267657715883j, + -.8256631452587146506294553 + .4642348752734325631275134j, + -.7556027168970728127850416 + .6229396358758267198938604j, + -.6579196593110998676999362 + .7862895503722515897065645j, + -.5224954069658330616875186 + .9581787261092526478889345j, + -.3229963059766444287113517 + 1.149416154583629539665297j], + 16: [-.9072099595087001356491337 + 72142113041117326028823950e-27j, + -.8911723070323647674780132 + .2167089659900576449410059j, + -.8584264231521330481755780 + .3621697271802065647661080j, + -.8074790293236003885306146 + .5092933751171800179676218j, + -.7356166304713115980927279 + .6591950877860393745845254j, + -.6379502514039066715773828 + .8137453537108761895522580j, + -.5047606444424766743309967 + .9767137477799090692947061j, + -.3108782755645387813283867 + 1.158552841199330479412225j], + 17: [-.9087141161336397432860029, + -.9016273850787285964692844 + .1360267995173024591237303j, + -.8801100704438627158492165 + .2725347156478803885651973j, + -.8433414495836129204455491 + .4100759282910021624185986j, + -.7897644147799708220288138 + .5493724405281088674296232j, + -.7166893842372349049842743 + .6914936286393609433305754j, + -.6193710717342144521602448 + .8382497252826992979368621j, + -.4884629337672704194973683 + .9932971956316781632345466j, + -.2998489459990082015466971 + 1.166761272925668786676672j], + 18: [-.9067004324162775554189031 + 64279241063930693839360680e-27j, + -.8939764278132455733032155 + .1930374640894758606940586j, + -.8681095503628830078317207 + .3224204925163257604931634j, + -.8281885016242836608829018 + .4529385697815916950149364j, + -.7726285030739558780127746 + .5852778162086640620016316j, + -.6987821445005273020051878 + .7204696509726630531663123j, + -.6020482668090644386627299 + .8602708961893664447167418j, + -.4734268069916151511140032 + 1.008234300314801077034158j, + -.2897592029880489845789953 + 1.174183010600059128532230j], + 19: [-.9078934217899404528985092, + -.9021937639390660668922536 + .1219568381872026517578164j, + -.8849290585034385274001112 + .2442590757549818229026280j, + -.8555768765618421591093993 + .3672925896399872304734923j, + -.8131725551578197705476160 + .4915365035562459055630005j, + -.7561260971541629355231897 + .6176483917970178919174173j, + -.6818424412912442033411634 + .7466272357947761283262338j, + -.5858613321217832644813602 + .8801817131014566284786759j, + -.4595043449730988600785456 + 1.021768776912671221830298j, + -.2804866851439370027628724 + 1.180931628453291873626003j], + 20: [-.9062570115576771146523497 + 57961780277849516990208850e-27j, + -.8959150941925768608568248 + .1740317175918705058595844j, + -.8749560316673332850673214 + .2905559296567908031706902j, + -.8427907479956670633544106 + .4078917326291934082132821j, + -.7984251191290606875799876 + .5264942388817132427317659j, + -.7402780309646768991232610 + .6469975237605228320268752j, + -.6658120544829934193890626 + .7703721701100763015154510j, + -.5707026806915714094398061 + .8982829066468255593407161j, + -.4465700698205149555701841 + 1.034097702560842962315411j, + -.2719299580251652601727704 + 1.187099379810885886139638j], + 21: [-.9072262653142957028884077, + -.9025428073192696303995083 + .1105252572789856480992275j, + -.8883808106664449854431605 + .2213069215084350419975358j, + -.8643915813643204553970169 + .3326258512522187083009453j, + -.8299435470674444100273463 + .4448177739407956609694059j, + -.7840287980408341576100581 + .5583186348022854707564856j, + -.7250839687106612822281339 + .6737426063024382240549898j, + -.6506315378609463397807996 + .7920349342629491368548074j, + -.5564766488918562465935297 + .9148198405846724121600860j, + -.4345168906815271799687308 + 1.045382255856986531461592j, + -.2640041595834031147954813 + 1.192762031948052470183960j], + 22: [-.9058702269930872551848625 + 52774908289999045189007100e-27j, + -.8972983138153530955952835 + .1584351912289865608659759j, + -.8799661455640176154025352 + .2644363039201535049656450j, + -.8534754036851687233084587 + .3710389319482319823405321j, + -.8171682088462720394344996 + .4785619492202780899653575j, + -.7700332930556816872932937 + .5874255426351153211965601j, + -.7105305456418785989070935 + .6982266265924524000098548j, + -.6362427683267827226840153 + .8118875040246347267248508j, + -.5430983056306302779658129 + .9299947824439872998916657j, + -.4232528745642628461715044 + 1.055755605227545931204656j, + -.2566376987939318038016012 + 1.197982433555213008346532j], + 23: [-.9066732476324988168207439, + -.9027564979912504609412993 + .1010534335314045013252480j, + -.8909283242471251458653994 + .2023024699381223418195228j, + -.8709469395587416239596874 + .3039581993950041588888925j, + -.8423805948021127057054288 + .4062657948237602726779246j, + -.8045561642053176205623187 + .5095305912227258268309528j, + -.7564660146829880581478138 + .6141594859476032127216463j, + -.6965966033912705387505040 + .7207341374753046970247055j, + -.6225903228771341778273152 + .8301558302812980678845563j, + -.5304922463810191698502226 + .9439760364018300083750242j, + -.4126986617510148836149955 + 1.065328794475513585531053j, + -.2497697202208956030229911 + 1.202813187870697831365338j], + 24: [-.9055312363372773709269407 + 48440066540478700874836350e-27j, + -.8983105104397872954053307 + .1454056133873610120105857j, + -.8837358034555706623131950 + .2426335234401383076544239j, + -.8615278304016353651120610 + .3403202112618624773397257j, + -.8312326466813240652679563 + .4386985933597305434577492j, + -.7921695462343492518845446 + .5380628490968016700338001j, + -.7433392285088529449175873 + .6388084216222567930378296j, + -.6832565803536521302816011 + .7415032695091650806797753j, + -.6096221567378335562589532 + .8470292433077202380020454j, + -.5185914574820317343536707 + .9569048385259054576937721j, + -.4027853855197518014786978 + 1.074195196518674765143729j, + -.2433481337524869675825448 + 1.207298683731972524975429j], + 25: [-.9062073871811708652496104, + -.9028833390228020537142561 + 93077131185102967450643820e-27j, + -.8928551459883548836774529 + .1863068969804300712287138j, + -.8759497989677857803656239 + .2798521321771408719327250j, + -.8518616886554019782346493 + .3738977875907595009446142j, + -.8201226043936880253962552 + .4686668574656966589020580j, + -.7800496278186497225905443 + .5644441210349710332887354j, + -.7306549271849967721596735 + .6616149647357748681460822j, + -.6704827128029559528610523 + .7607348858167839877987008j, + -.5972898661335557242320528 + .8626676330388028512598538j, + -.5073362861078468845461362 + .9689006305344868494672405j, + -.3934529878191079606023847 + 1.082433927173831581956863j, + -.2373280669322028974199184 + 1.211476658382565356579418j], + } + for N in originals: + p1 = sorted(np.union1d(originals[N], + np.conj(originals[N])), key=np.imag) + p2 = sorted(besselap(N)[1], key=np.imag) + xp_assert_close(p1, + p2, rtol=1e-14, check_dtype=False) + + def test_norm_phase(self): + # Test some orders and frequencies and see that they have the right + # phase at w0 + for N in (1, 2, 3, 4, 5, 51, 72): + for w0 in (1, 100): + b, a = bessel(N, w0, analog=True, norm='phase') + w = np.linspace(0, w0, 100) + w, h = freqs(b, a, w) + phase = np.unwrap(np.angle(h)) + xp_assert_close(phase[[0, -1]], (0, -N*pi/4), rtol=1e-1) + + def test_norm_mag(self): + # Test some orders and frequencies and see that they have the right + # mag at w0 + for N in (1, 2, 3, 4, 5, 51, 72): + for w0 in (1, 100): + b, a = bessel(N, w0, analog=True, norm='mag') + w = (0, w0) + w, h = freqs(b, a, w) + mag = abs(h) + xp_assert_close(mag, (1, 1/np.sqrt(2))) + + def test_norm_delay(self): + # Test some orders and frequencies and see that they have the right + # delay at DC + for N in (1, 2, 3, 4, 5, 51, 72): + for w0 in (1, 100): + b, a = bessel(N, w0, analog=True, norm='delay') + w = np.linspace(0, 10*w0, 1000) + w, h = freqs(b, a, w) + delay = -np.diff(np.unwrap(np.angle(h)))/np.diff(w) + xp_assert_close(delay[0], 1/w0, rtol=1e-4) + + def test_norm_factor(self): + mpmath_values = { + 1: 1.0, 2: 1.361654128716130520, 3: 1.755672368681210649, + 4: 2.113917674904215843, 5: 2.427410702152628137, + 6: 2.703395061202921876, 7: 2.951722147038722771, + 8: 3.179617237510651330, 9: 3.391693138911660101, + 10: 3.590980594569163482, 11: 3.779607416439620092, + 12: 3.959150821144285315, 13: 4.130825499383535980, + 14: 4.295593409533637564, 15: 4.454233021624377494, + 16: 4.607385465472647917, 17: 4.755586548961147727, + 18: 4.899289677284488007, 19: 5.038882681488207605, + 20: 5.174700441742707423, 21: 5.307034531360917274, + 22: 5.436140703250035999, 23: 5.562244783787878196, + 24: 5.685547371295963521, 25: 5.806227623775418541, + 50: 8.268963160013226298, 51: 8.352374541546012058, + } + for N in mpmath_values: + z, p, k = besselap(N, 'delay') + xp_assert_close(mpmath_values[N], _norm_factor(p, k), rtol=1e-13) + + def test_bessel_poly(self): + xp_assert_equal(_bessel_poly(5), [945, 945, 420, 105, 15, 1]) + xp_assert_equal(_bessel_poly(4, True), [1, 10, 45, 105, 105]) + + def test_bessel_zeros(self): + xp_assert_equal(_bessel_zeros(0), []) + + def test_invalid(self): + assert_raises(ValueError, besselap, 5, 'nonsense') + assert_raises(ValueError, besselap, -5) + assert_raises(ValueError, besselap, 3.2) + assert_raises(ValueError, _bessel_poly, -3) + assert_raises(ValueError, _bessel_poly, 3.3) + + @pytest.mark.fail_slow(10) + def test_fs_param(self): + for norm in ('phase', 'mag', 'delay'): + for fs in (900, 900.1, 1234.567): + for N in (0, 1, 2, 3, 10): + for fc in (100, 100.1, 432.12345): + for btype in ('lp', 'hp'): + ba1 = bessel(N, fc, btype, norm=norm, fs=fs) + ba2 = bessel(N, fc/(fs/2), btype, norm=norm) + for ba1_, ba2_ in zip(ba1, ba2): + xp_assert_close(ba1_, ba2_) + for fc in ((100, 200), (100.1, 200.2), (321.123, 432.123)): + for btype in ('bp', 'bs'): + ba1 = bessel(N, fc, btype, norm=norm, fs=fs) + for seq in (list, tuple, array): + fcnorm = seq([f/(fs/2) for f in fc]) + ba2 = bessel(N, fcnorm, btype, norm=norm) + for ba1_, ba2_ in zip(ba1, ba2): + xp_assert_close(ba1_, ba2_) + + +class TestButter: + + def test_degenerate(self): + # 0-order filter is just a passthrough + b, a = butter(0, 1, analog=True) + xp_assert_equal(b, np.asarray([1.0])) + xp_assert_equal(a, np.asarray([1.0])) + + # 1-order filter is same for all types + b, a = butter(1, 1, analog=True) + assert_array_almost_equal(b, [1]) + assert_array_almost_equal(a, [1, 1]) + + z, p, k = butter(1, 0.3, output='zpk') + xp_assert_equal(z, np.asarray([-1.0])) + xp_assert_close(p, [3.249196962329063e-01 + 0j], rtol=1e-14) + xp_assert_close(k, 3.375401518835469e-01, rtol=1e-14) + + def test_basic(self): + # analog s-plane + for N in range(25): + wn = 0.01 + z, p, k = butter(N, wn, 'low', analog=True, output='zpk') + assert_array_almost_equal([], z) + assert len(p) == N + # All poles should be at distance wn from origin + assert_array_almost_equal(abs(p), np.asarray(wn)) + assert all(np.real(p) <= 0) # No poles in right half of S-plane + assert_array_almost_equal(wn**N, k) + + # digital z-plane + for N in range(25): + wn = 0.01 + z, p, k = butter(N, wn, 'high', analog=False, output='zpk') + xp_assert_equal(np.ones(N), z) # All zeros exactly at DC + assert all(np.abs(p) <= 1) # No poles outside unit circle + + b1, a1 = butter(2, 1, analog=True) + assert_array_almost_equal(b1, [1]) + assert_array_almost_equal(a1, [1, np.sqrt(2), 1]) + + b2, a2 = butter(5, 1, analog=True) + assert_array_almost_equal(b2, [1]) + assert_array_almost_equal(a2, [1, 3.2361, 5.2361, + 5.2361, 3.2361, 1], decimal=4) + + b3, a3 = butter(10, 1, analog=True) + assert_array_almost_equal(b3, [1]) + assert_array_almost_equal(a3, [1, 6.3925, 20.4317, 42.8021, 64.8824, + 74.2334, 64.8824, 42.8021, 20.4317, + 6.3925, 1], decimal=4) + + b2, a2 = butter(19, 1.0441379169150726, analog=True) + assert_array_almost_equal(b2, [2.2720], decimal=4) + assert_array_almost_equal(a2, 1.0e+004 * np.array([ + 0.0001, 0.0013, 0.0080, 0.0335, 0.1045, 0.2570, + 0.5164, 0.8669, 1.2338, 1.5010, 1.5672, 1.4044, + 1.0759, 0.6986, 0.3791, 0.1681, 0.0588, 0.0153, + 0.0026, 0.0002]), decimal=0) + + b, a = butter(5, 0.4) + assert_array_almost_equal(b, [0.0219, 0.1097, 0.2194, + 0.2194, 0.1097, 0.0219], decimal=4) + assert_array_almost_equal(a, [1.0000, -0.9853, 0.9738, + -0.3864, 0.1112, -0.0113], decimal=4) + + def test_highpass(self): + # highpass, high even order + z, p, k = butter(28, 0.43, 'high', output='zpk') + z2 = np.ones(28) + p2 = [ + 2.068257195514592e-01 + 9.238294351481734e-01j, + 2.068257195514592e-01 - 9.238294351481734e-01j, + 1.874933103892023e-01 + 8.269455076775277e-01j, + 1.874933103892023e-01 - 8.269455076775277e-01j, + 1.717435567330153e-01 + 7.383078571194629e-01j, + 1.717435567330153e-01 - 7.383078571194629e-01j, + 1.588266870755982e-01 + 6.564623730651094e-01j, + 1.588266870755982e-01 - 6.564623730651094e-01j, + 1.481881532502603e-01 + 5.802343458081779e-01j, + 1.481881532502603e-01 - 5.802343458081779e-01j, + 1.394122576319697e-01 + 5.086609000582009e-01j, + 1.394122576319697e-01 - 5.086609000582009e-01j, + 1.321840881809715e-01 + 4.409411734716436e-01j, + 1.321840881809715e-01 - 4.409411734716436e-01j, + 1.262633413354405e-01 + 3.763990035551881e-01j, + 1.262633413354405e-01 - 3.763990035551881e-01j, + 1.214660449478046e-01 + 3.144545234797277e-01j, + 1.214660449478046e-01 - 3.144545234797277e-01j, + 1.104868766650320e-01 + 2.771505404367791e-02j, + 1.104868766650320e-01 - 2.771505404367791e-02j, + 1.111768629525075e-01 + 8.331369153155753e-02j, + 1.111768629525075e-01 - 8.331369153155753e-02j, + 1.125740630842972e-01 + 1.394219509611784e-01j, + 1.125740630842972e-01 - 1.394219509611784e-01j, + 1.147138487992747e-01 + 1.963932363793666e-01j, + 1.147138487992747e-01 - 1.963932363793666e-01j, + 1.176516491045901e-01 + 2.546021573417188e-01j, + 1.176516491045901e-01 - 2.546021573417188e-01j, + ] + k2 = 1.446671081817286e-06 + xp_assert_equal(z, z2) + xp_assert_close(sorted(p, key=np.imag), + sorted(p2, key=np.imag), rtol=1e-7) + xp_assert_close(k, k2, rtol=1e-10) + + # highpass, high odd order + z, p, k = butter(27, 0.56, 'high', output='zpk') + z2 = np.ones(27) + p2 = [ + -1.772572785680147e-01 + 9.276431102995948e-01j, + -1.772572785680147e-01 - 9.276431102995948e-01j, + -1.600766565322114e-01 + 8.264026279893268e-01j, + -1.600766565322114e-01 - 8.264026279893268e-01j, + -1.461948419016121e-01 + 7.341841939120078e-01j, + -1.461948419016121e-01 - 7.341841939120078e-01j, + -1.348975284762046e-01 + 6.493235066053785e-01j, + -1.348975284762046e-01 - 6.493235066053785e-01j, + -1.256628210712206e-01 + 5.704921366889227e-01j, + -1.256628210712206e-01 - 5.704921366889227e-01j, + -1.181038235962314e-01 + 4.966120551231630e-01j, + -1.181038235962314e-01 - 4.966120551231630e-01j, + -1.119304913239356e-01 + 4.267938916403775e-01j, + -1.119304913239356e-01 - 4.267938916403775e-01j, + -1.069237739782691e-01 + 3.602914879527338e-01j, + -1.069237739782691e-01 - 3.602914879527338e-01j, + -1.029178030691416e-01 + 2.964677964142126e-01j, + -1.029178030691416e-01 - 2.964677964142126e-01j, + -9.978747500816100e-02 + 2.347687643085738e-01j, + -9.978747500816100e-02 - 2.347687643085738e-01j, + -9.743974496324025e-02 + 1.747028739092479e-01j, + -9.743974496324025e-02 - 1.747028739092479e-01j, + -9.580754551625957e-02 + 1.158246860771989e-01j, + -9.580754551625957e-02 - 1.158246860771989e-01j, + -9.484562207782568e-02 + 5.772118357151691e-02j, + -9.484562207782568e-02 - 5.772118357151691e-02j, + -9.452783117928215e-02 + ] + k2 = 9.585686688851069e-09 + xp_assert_equal(z, z2) + xp_assert_close(sorted(p, key=np.imag), + sorted(p2, key=np.imag), rtol=1e-8) + xp_assert_close(k, k2) + + def test_bandpass(self): + z, p, k = butter(8, [0.25, 0.33], 'band', output='zpk') + z2 = [1, 1, 1, 1, 1, 1, 1, 1, + -1, -1, -1, -1, -1, -1, -1, -1] + p2 = [ + 4.979909925436156e-01 + 8.367609424799387e-01j, + 4.979909925436156e-01 - 8.367609424799387e-01j, + 4.913338722555539e-01 + 7.866774509868817e-01j, + 4.913338722555539e-01 - 7.866774509868817e-01j, + 5.035229361778706e-01 + 7.401147376726750e-01j, + 5.035229361778706e-01 - 7.401147376726750e-01j, + 5.307617160406101e-01 + 7.029184459442954e-01j, + 5.307617160406101e-01 - 7.029184459442954e-01j, + 5.680556159453138e-01 + 6.788228792952775e-01j, + 5.680556159453138e-01 - 6.788228792952775e-01j, + 6.100962560818854e-01 + 6.693849403338664e-01j, + 6.100962560818854e-01 - 6.693849403338664e-01j, + 6.904694312740631e-01 + 6.930501690145245e-01j, + 6.904694312740631e-01 - 6.930501690145245e-01j, + 6.521767004237027e-01 + 6.744414640183752e-01j, + 6.521767004237027e-01 - 6.744414640183752e-01j, + ] + k2 = 3.398854055800844e-08 + xp_assert_equal(z, z2, check_dtype=False) + xp_assert_close(sorted(p, key=np.imag), + sorted(p2, key=np.imag), rtol=1e-13) + xp_assert_close(k, k2, rtol=1e-13) + + # bandpass analog + z, p, k = butter(4, [90.5, 110.5], 'bp', analog=True, output='zpk') + z2 = np.zeros(4, dtype=z.dtype) + p2 = [ + -4.179137760733086e+00 + 1.095935899082837e+02j, + -4.179137760733086e+00 - 1.095935899082837e+02j, + -9.593598668443835e+00 + 1.034745398029734e+02j, + -9.593598668443835e+00 - 1.034745398029734e+02j, + -8.883991981781929e+00 + 9.582087115567160e+01j, + -8.883991981781929e+00 - 9.582087115567160e+01j, + -3.474530886568715e+00 + 9.111599925805801e+01j, + -3.474530886568715e+00 - 9.111599925805801e+01j, + ] + k2 = 1.600000000000001e+05 + xp_assert_equal(z, z2) + xp_assert_close(sorted(p, key=np.imag), + sorted(p2, key=np.imag)) + xp_assert_close(k, k2, rtol=1e-15) + + def test_bandstop(self): + z, p, k = butter(7, [0.45, 0.56], 'stop', output='zpk') + z2 = [-1.594474531383421e-02 + 9.998728744679880e-01j, + -1.594474531383421e-02 - 9.998728744679880e-01j, + -1.594474531383421e-02 + 9.998728744679880e-01j, + -1.594474531383421e-02 - 9.998728744679880e-01j, + -1.594474531383421e-02 + 9.998728744679880e-01j, + -1.594474531383421e-02 - 9.998728744679880e-01j, + -1.594474531383421e-02 + 9.998728744679880e-01j, + -1.594474531383421e-02 - 9.998728744679880e-01j, + -1.594474531383421e-02 + 9.998728744679880e-01j, + -1.594474531383421e-02 - 9.998728744679880e-01j, + -1.594474531383421e-02 + 9.998728744679880e-01j, + -1.594474531383421e-02 - 9.998728744679880e-01j, + -1.594474531383421e-02 + 9.998728744679880e-01j, + -1.594474531383421e-02 - 9.998728744679880e-01j] + p2 = [-1.766850742887729e-01 + 9.466951258673900e-01j, + -1.766850742887729e-01 - 9.466951258673900e-01j, + 1.467897662432886e-01 + 9.515917126462422e-01j, + 1.467897662432886e-01 - 9.515917126462422e-01j, + -1.370083529426906e-01 + 8.880376681273993e-01j, + -1.370083529426906e-01 - 8.880376681273993e-01j, + 1.086774544701390e-01 + 8.915240810704319e-01j, + 1.086774544701390e-01 - 8.915240810704319e-01j, + -7.982704457700891e-02 + 8.506056315273435e-01j, + -7.982704457700891e-02 - 8.506056315273435e-01j, + 5.238812787110331e-02 + 8.524011102699969e-01j, + 5.238812787110331e-02 - 8.524011102699969e-01j, + -1.357545000491310e-02 + 8.382287744986582e-01j, + -1.357545000491310e-02 - 8.382287744986582e-01j] + k2 = 4.577122512960063e-01 + xp_assert_close(sorted(z, key=np.imag), + sorted(z2, key=np.imag)) + xp_assert_close(sorted(p, key=np.imag), + sorted(p2, key=np.imag)) + xp_assert_close(k, k2, rtol=1e-14) + + def test_ba_output(self): + b, a = butter(4, [100, 300], 'bandpass', analog=True) + b2 = [1.6e+09, 0, 0, 0, 0] + a2 = [1.000000000000000e+00, 5.226251859505511e+02, + 2.565685424949238e+05, 6.794127417357160e+07, + 1.519411254969542e+10, 2.038238225207147e+12, + 2.309116882454312e+14, 1.411088002066486e+16, + 8.099999999999991e+17] + xp_assert_close(b, b2, rtol=1e-14) + xp_assert_close(a, a2, rtol=1e-14) + + def test_fs_param(self): + for fs in (900, 900.1, 1234.567): + for N in (0, 1, 2, 3, 10): + for fc in (100, 100.1, 432.12345): + for btype in ('lp', 'hp'): + ba1 = butter(N, fc, btype, fs=fs) + ba2 = butter(N, fc/(fs/2), btype) + for ba1_, ba2_ in zip(ba1, ba2): + xp_assert_close(ba1_, ba2_) + for fc in ((100, 200), (100.1, 200.2), (321.123, 432.123)): + for btype in ('bp', 'bs'): + ba1 = butter(N, fc, btype, fs=fs) + for seq in (list, tuple, array): + fcnorm = seq([f/(fs/2) for f in fc]) + ba2 = butter(N, fcnorm, btype) + for ba1_, ba2_ in zip(ba1, ba2): + xp_assert_close(ba1_, ba2_) + + +class TestCheby1: + + def test_degenerate(self): + # 0-order filter is just a passthrough + # Even-order filters have DC gain of -rp dB + b, a = cheby1(0, 10*np.log10(2), 1, analog=True) + assert_array_almost_equal(b, [1/np.sqrt(2)]) + xp_assert_equal(a, np.asarray([1.0])) + + # 1-order filter is same for all types + b, a = cheby1(1, 10*np.log10(2), 1, analog=True) + assert_array_almost_equal(b, [1]) + assert_array_almost_equal(a, [1, 1]) + + z, p, k = cheby1(1, 0.1, 0.3, output='zpk') + xp_assert_equal(z, np.asarray([-1.0])) + xp_assert_close(p, [-5.390126972799615e-01 + 0j], rtol=1e-14) + xp_assert_close(k, 7.695063486399808e-01, rtol=1e-14) + + def test_basic(self): + for N in range(25): + wn = 0.01 + z, p, k = cheby1(N, 1, wn, 'low', analog=True, output='zpk') + assert_array_almost_equal([], z) + assert len(p) == N + assert all(np.real(p) <= 0) # No poles in right half of S-plane + + for N in range(25): + wn = 0.01 + z, p, k = cheby1(N, 1, wn, 'high', analog=False, output='zpk') + xp_assert_equal(np.ones(N), z) # All zeros exactly at DC + assert all(np.abs(p) <= 1) # No poles outside unit circle + + # Same test as TestNormalize + b, a = cheby1(8, 0.5, 0.048) + assert_array_almost_equal(b, [ + 2.150733144728282e-11, 1.720586515782626e-10, + 6.022052805239190e-10, 1.204410561047838e-09, + 1.505513201309798e-09, 1.204410561047838e-09, + 6.022052805239190e-10, 1.720586515782626e-10, + 2.150733144728282e-11], decimal=14) + assert_array_almost_equal(a, [ + 1.000000000000000e+00, -7.782402035027959e+00, + 2.654354569747454e+01, -5.182182531666387e+01, + 6.334127355102684e+01, -4.963358186631157e+01, + 2.434862182949389e+01, -6.836925348604676e+00, + 8.412934944449140e-01], decimal=14) + + b, a = cheby1(4, 1, [0.4, 0.7], btype='band') + assert_array_almost_equal(b, [0.0084, 0, -0.0335, 0, 0.0502, 0, + -0.0335, 0, 0.0084], decimal=4) + assert_array_almost_equal(a, [1.0, 1.1191, 2.862, 2.2986, 3.4137, + 1.8653, 1.8982, 0.5676, 0.4103], + decimal=4) + + b2, a2 = cheby1(5, 3, 1, analog=True) + assert_array_almost_equal(b2, [0.0626], decimal=4) + assert_array_almost_equal(a2, [1, 0.5745, 1.4150, 0.5489, 0.4080, + 0.0626], decimal=4) + + b, a = cheby1(8, 0.5, 0.1) + assert_array_almost_equal(b, 1.0e-006 * np.array([ + 0.00703924326028, 0.05631394608227, 0.19709881128793, + 0.39419762257586, 0.49274702821983, 0.39419762257586, + 0.19709881128793, 0.05631394608227, 0.00703924326028]), + decimal=13) + assert_array_almost_equal(a, [ + 1.00000000000000, -7.44912258934158, 24.46749067762108, + -46.27560200466141, 55.11160187999928, -42.31640010161038, + 20.45543300484147, -5.69110270561444, 0.69770374759022], + decimal=13) + + b, a = cheby1(8, 0.5, 0.25) + assert_array_almost_equal(b, 1.0e-003 * np.array([ + 0.00895261138923, 0.07162089111382, 0.25067311889837, + 0.50134623779673, 0.62668279724591, 0.50134623779673, + 0.25067311889837, 0.07162089111382, 0.00895261138923]), + decimal=13) + assert_array_almost_equal(a, [1.00000000000000, -5.97529229188545, + 16.58122329202101, -27.71423273542923, + 30.39509758355313, -22.34729670426879, + 10.74509800434910, -3.08924633697497, + 0.40707685889802], decimal=13) + + def test_highpass(self): + # high even order + z, p, k = cheby1(24, 0.7, 0.2, 'high', output='zpk') + z2 = np.ones(24) + p2 = [-6.136558509657073e-01 + 2.700091504942893e-01j, + -6.136558509657073e-01 - 2.700091504942893e-01j, + -3.303348340927516e-01 + 6.659400861114254e-01j, + -3.303348340927516e-01 - 6.659400861114254e-01j, + 8.779713780557169e-03 + 8.223108447483040e-01j, + 8.779713780557169e-03 - 8.223108447483040e-01j, + 2.742361123006911e-01 + 8.356666951611864e-01j, + 2.742361123006911e-01 - 8.356666951611864e-01j, + 4.562984557158206e-01 + 7.954276912303594e-01j, + 4.562984557158206e-01 - 7.954276912303594e-01j, + 5.777335494123628e-01 + 7.435821817961783e-01j, + 5.777335494123628e-01 - 7.435821817961783e-01j, + 6.593260977749194e-01 + 6.955390907990932e-01j, + 6.593260977749194e-01 - 6.955390907990932e-01j, + 7.149590948466562e-01 + 6.559437858502012e-01j, + 7.149590948466562e-01 - 6.559437858502012e-01j, + 7.532432388188739e-01 + 6.256158042292060e-01j, + 7.532432388188739e-01 - 6.256158042292060e-01j, + 7.794365244268271e-01 + 6.042099234813333e-01j, + 7.794365244268271e-01 - 6.042099234813333e-01j, + 7.967253874772997e-01 + 5.911966597313203e-01j, + 7.967253874772997e-01 - 5.911966597313203e-01j, + 8.069756417293870e-01 + 5.862214589217275e-01j, + 8.069756417293870e-01 - 5.862214589217275e-01j] + k2 = 6.190427617192018e-04 + xp_assert_equal(z, z2) + xp_assert_close(sorted(p, key=np.imag), + sorted(p2, key=np.imag), rtol=1e-10) + xp_assert_close(k, k2, rtol=1e-10) + + # high odd order + z, p, k = cheby1(23, 0.8, 0.3, 'high', output='zpk') + z2 = np.ones(23) + p2 = [-7.676400532011010e-01, + -6.754621070166477e-01 + 3.970502605619561e-01j, + -6.754621070166477e-01 - 3.970502605619561e-01j, + -4.528880018446727e-01 + 6.844061483786332e-01j, + -4.528880018446727e-01 - 6.844061483786332e-01j, + -1.986009130216447e-01 + 8.382285942941594e-01j, + -1.986009130216447e-01 - 8.382285942941594e-01j, + 2.504673931532608e-02 + 8.958137635794080e-01j, + 2.504673931532608e-02 - 8.958137635794080e-01j, + 2.001089429976469e-01 + 9.010678290791480e-01j, + 2.001089429976469e-01 - 9.010678290791480e-01j, + 3.302410157191755e-01 + 8.835444665962544e-01j, + 3.302410157191755e-01 - 8.835444665962544e-01j, + 4.246662537333661e-01 + 8.594054226449009e-01j, + 4.246662537333661e-01 - 8.594054226449009e-01j, + 4.919620928120296e-01 + 8.366772762965786e-01j, + 4.919620928120296e-01 - 8.366772762965786e-01j, + 5.385746917494749e-01 + 8.191616180796720e-01j, + 5.385746917494749e-01 - 8.191616180796720e-01j, + 5.855636993537203e-01 + 8.060680937701062e-01j, + 5.855636993537203e-01 - 8.060680937701062e-01j, + 5.688812849391721e-01 + 8.086497795114683e-01j, + 5.688812849391721e-01 - 8.086497795114683e-01j] + k2 = 1.941697029206324e-05 + xp_assert_equal(z, z2) + xp_assert_close(sorted(p, key=np.imag), + sorted(p2, key=np.imag), rtol=1e-10) + xp_assert_close(k, k2, rtol=1e-10) + + z, p, k = cheby1(10, 1, 1000, 'high', analog=True, output='zpk') + z2 = np.zeros(10) + p2 = [-3.144743169501551e+03 + 3.511680029092744e+03j, + -3.144743169501551e+03 - 3.511680029092744e+03j, + -5.633065604514602e+02 + 2.023615191183945e+03j, + -5.633065604514602e+02 - 2.023615191183945e+03j, + -1.946412183352025e+02 + 1.372309454274755e+03j, + -1.946412183352025e+02 - 1.372309454274755e+03j, + -7.987162953085479e+01 + 1.105207708045358e+03j, + -7.987162953085479e+01 - 1.105207708045358e+03j, + -2.250315039031946e+01 + 1.001723931471477e+03j, + -2.250315039031946e+01 - 1.001723931471477e+03j] + k2 = 8.912509381337453e-01 + xp_assert_equal(z, z2) + xp_assert_close(sorted(p, key=np.imag), + sorted(p2, key=np.imag), rtol=1e-13) + xp_assert_close(k, k2, rtol=1e-15) + + def test_bandpass(self): + z, p, k = cheby1(8, 1, [0.3, 0.4], 'bp', output='zpk') + z2 = [1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1] + p2 = [3.077784854851463e-01 + 9.453307017592942e-01j, + 3.077784854851463e-01 - 9.453307017592942e-01j, + 3.280567400654425e-01 + 9.272377218689016e-01j, + 3.280567400654425e-01 - 9.272377218689016e-01j, + 3.677912763284301e-01 + 9.038008865279966e-01j, + 3.677912763284301e-01 - 9.038008865279966e-01j, + 4.194425632520948e-01 + 8.769407159656157e-01j, + 4.194425632520948e-01 - 8.769407159656157e-01j, + 4.740921994669189e-01 + 8.496508528630974e-01j, + 4.740921994669189e-01 - 8.496508528630974e-01j, + 5.234866481897429e-01 + 8.259608422808477e-01j, + 5.234866481897429e-01 - 8.259608422808477e-01j, + 5.844717632289875e-01 + 8.052901363500210e-01j, + 5.844717632289875e-01 - 8.052901363500210e-01j, + 5.615189063336070e-01 + 8.100667803850766e-01j, + 5.615189063336070e-01 - 8.100667803850766e-01j] + k2 = 5.007028718074307e-09 + xp_assert_equal(z, z2, check_dtype=False) + xp_assert_close(sorted(p, key=np.imag), + sorted(p2, key=np.imag), rtol=1e-13) + xp_assert_close(k, k2, rtol=1e-13) + + def test_bandstop(self): + z, p, k = cheby1(7, 1, [0.5, 0.6], 'stop', output='zpk') + z2 = [-1.583844403245361e-01 + 9.873775210440450e-01j, + -1.583844403245361e-01 - 9.873775210440450e-01j, + -1.583844403245361e-01 + 9.873775210440450e-01j, + -1.583844403245361e-01 - 9.873775210440450e-01j, + -1.583844403245361e-01 + 9.873775210440450e-01j, + -1.583844403245361e-01 - 9.873775210440450e-01j, + -1.583844403245361e-01 + 9.873775210440450e-01j, + -1.583844403245361e-01 - 9.873775210440450e-01j, + -1.583844403245361e-01 + 9.873775210440450e-01j, + -1.583844403245361e-01 - 9.873775210440450e-01j, + -1.583844403245361e-01 + 9.873775210440450e-01j, + -1.583844403245361e-01 - 9.873775210440450e-01j, + -1.583844403245361e-01 + 9.873775210440450e-01j, + -1.583844403245361e-01 - 9.873775210440450e-01j] + p2 = [-8.942974551472813e-02 + 3.482480481185926e-01j, + -8.942974551472813e-02 - 3.482480481185926e-01j, + 1.293775154041798e-01 + 8.753499858081858e-01j, + 1.293775154041798e-01 - 8.753499858081858e-01j, + 3.399741945062013e-02 + 9.690316022705607e-01j, + 3.399741945062013e-02 - 9.690316022705607e-01j, + 4.167225522796539e-04 + 9.927338161087488e-01j, + 4.167225522796539e-04 - 9.927338161087488e-01j, + -3.912966549550960e-01 + 8.046122859255742e-01j, + -3.912966549550960e-01 - 8.046122859255742e-01j, + -3.307805547127368e-01 + 9.133455018206508e-01j, + -3.307805547127368e-01 - 9.133455018206508e-01j, + -3.072658345097743e-01 + 9.443589759799366e-01j, + -3.072658345097743e-01 - 9.443589759799366e-01j] + k2 = 3.619438310405028e-01 + xp_assert_close(sorted(z, key=np.imag), + sorted(z2, key=np.imag), rtol=1e-13) + xp_assert_close(sorted(p, key=np.imag), + sorted(p2, key=np.imag), rtol=1e-13) + xp_assert_close(k, k2, rtol=0, atol=5e-16) + + def test_ba_output(self): + # with transfer function conversion, without digital conversion + b, a = cheby1(5, 0.9, [210, 310], 'stop', analog=True) + b2 = [1.000000000000006e+00, 0, + 3.255000000000020e+05, 0, + 4.238010000000026e+10, 0, + 2.758944510000017e+15, 0, + 8.980364380050052e+19, 0, + 1.169243442282517e+24 + ] + a2 = [1.000000000000000e+00, 4.630555945694342e+02, + 4.039266454794788e+05, 1.338060988610237e+08, + 5.844333551294591e+10, 1.357346371637638e+13, + 3.804661141892782e+15, 5.670715850340080e+17, + 1.114411200988328e+20, 8.316815934908471e+21, + 1.169243442282517e+24 + ] + xp_assert_close(b, b2, rtol=1e-14) + xp_assert_close(a, a2, rtol=1e-14) + + def test_fs_param(self): + for fs in (900, 900.1, 1234.567): + for N in (0, 1, 2, 3, 10): + for fc in (100, 100.1, 432.12345): + for btype in ('lp', 'hp'): + ba1 = cheby1(N, 1, fc, btype, fs=fs) + ba2 = cheby1(N, 1, fc/(fs/2), btype) + for ba1_, ba2_ in zip(ba1, ba2): + xp_assert_close(ba1_, ba2_) + for fc in ((100, 200), (100.1, 200.2), (321.123, 432.123)): + for btype in ('bp', 'bs'): + ba1 = cheby1(N, 1, fc, btype, fs=fs) + for seq in (list, tuple, array): + fcnorm = seq([f/(fs/2) for f in fc]) + ba2 = cheby1(N, 1, fcnorm, btype) + for ba1_, ba2_ in zip(ba1, ba2): + xp_assert_close(ba1_, ba2_) + +class TestCheby2: + + def test_degenerate(self): + # 0-order filter is just a passthrough + # Stopband ripple factor doesn't matter + b, a = cheby2(0, 123.456, 1, analog=True) + xp_assert_equal(b, np.asarray([1.0])) + xp_assert_equal(a, np.asarray([1.0])) + + # 1-order filter is same for all types + b, a = cheby2(1, 10*np.log10(2), 1, analog=True) + assert_array_almost_equal(b, [1]) + assert_array_almost_equal(a, [1, 1]) + + z, p, k = cheby2(1, 50, 0.3, output='zpk') + xp_assert_equal(z, np.asarray([-1], dtype=np.complex128)) + xp_assert_close(p, [9.967826460175649e-01 + 0j], rtol=1e-14) + xp_assert_close(k, 1.608676991217512e-03, rtol=1e-14) + + def test_basic(self): + for N in range(25): + wn = 0.01 + z, p, k = cheby2(N, 40, wn, 'low', analog=True, output='zpk') + assert len(p) == N + assert all(np.real(p) <= 0) # No poles in right half of S-plane + + for N in range(25): + wn = 0.01 + z, p, k = cheby2(N, 40, wn, 'high', analog=False, output='zpk') + assert all(np.abs(p) <= 1) # No poles outside unit circle + + B, A = cheby2(18, 100, 0.5) + assert_array_almost_equal(B, [ + 0.00167583914216, 0.01249479541868, 0.05282702120282, + 0.15939804265706, 0.37690207631117, 0.73227013789108, + 1.20191856962356, 1.69522872823393, 2.07598674519837, + 2.21972389625291, 2.07598674519838, 1.69522872823395, + 1.20191856962359, 0.73227013789110, 0.37690207631118, + 0.15939804265707, 0.05282702120282, 0.01249479541868, + 0.00167583914216], decimal=13) + assert_array_almost_equal(A, [ + 1.00000000000000, -0.27631970006174, 3.19751214254060, + -0.15685969461355, 4.13926117356269, 0.60689917820044, + 2.95082770636540, 0.89016501910416, 1.32135245849798, + 0.51502467236824, 0.38906643866660, 0.15367372690642, + 0.07255803834919, 0.02422454070134, 0.00756108751837, + 0.00179848550988, 0.00033713574499, 0.00004258794833, + 0.00000281030149], decimal=13) + + def test_highpass(self): + # high even order + z, p, k = cheby2(26, 60, 0.3, 'high', output='zpk') + z2 = [9.981088955489852e-01 + 6.147058341984388e-02j, + 9.981088955489852e-01 - 6.147058341984388e-02j, + 9.832702870387426e-01 + 1.821525257215483e-01j, + 9.832702870387426e-01 - 1.821525257215483e-01j, + 9.550760158089112e-01 + 2.963609353922882e-01j, + 9.550760158089112e-01 - 2.963609353922882e-01j, + 9.162054748821922e-01 + 4.007087817803773e-01j, + 9.162054748821922e-01 - 4.007087817803773e-01j, + 8.700619897368064e-01 + 4.929423232136168e-01j, + 8.700619897368064e-01 - 4.929423232136168e-01j, + 5.889791753434985e-01 + 8.081482110427953e-01j, + 5.889791753434985e-01 - 8.081482110427953e-01j, + 5.984900456570295e-01 + 8.011302423760501e-01j, + 5.984900456570295e-01 - 8.011302423760501e-01j, + 6.172880888914629e-01 + 7.867371958365343e-01j, + 6.172880888914629e-01 - 7.867371958365343e-01j, + 6.448899971038180e-01 + 7.642754030030161e-01j, + 6.448899971038180e-01 - 7.642754030030161e-01j, + 6.804845629637927e-01 + 7.327624168637228e-01j, + 6.804845629637927e-01 - 7.327624168637228e-01j, + 8.202619107108660e-01 + 5.719881098737678e-01j, + 8.202619107108660e-01 - 5.719881098737678e-01j, + 7.228410452536148e-01 + 6.910143437705678e-01j, + 7.228410452536148e-01 - 6.910143437705678e-01j, + 7.702121399578629e-01 + 6.377877856007792e-01j, + 7.702121399578629e-01 - 6.377877856007792e-01j] + p2 = [7.365546198286450e-01 + 4.842085129329526e-02j, + 7.365546198286450e-01 - 4.842085129329526e-02j, + 7.292038510962885e-01 + 1.442201672097581e-01j, + 7.292038510962885e-01 - 1.442201672097581e-01j, + 7.151293788040354e-01 + 2.369925800458584e-01j, + 7.151293788040354e-01 - 2.369925800458584e-01j, + 6.955051820787286e-01 + 3.250341363856910e-01j, + 6.955051820787286e-01 - 3.250341363856910e-01j, + 6.719122956045220e-01 + 4.070475750638047e-01j, + 6.719122956045220e-01 - 4.070475750638047e-01j, + 6.461722130611300e-01 + 4.821965916689270e-01j, + 6.461722130611300e-01 - 4.821965916689270e-01j, + 5.528045062872224e-01 + 8.162920513838372e-01j, + 5.528045062872224e-01 - 8.162920513838372e-01j, + 5.464847782492791e-01 + 7.869899955967304e-01j, + 5.464847782492791e-01 - 7.869899955967304e-01j, + 5.488033111260949e-01 + 7.520442354055579e-01j, + 5.488033111260949e-01 - 7.520442354055579e-01j, + 6.201874719022955e-01 + 5.500894392527353e-01j, + 6.201874719022955e-01 - 5.500894392527353e-01j, + 5.586478152536709e-01 + 7.112676877332921e-01j, + 5.586478152536709e-01 - 7.112676877332921e-01j, + 5.958145844148228e-01 + 6.107074340842115e-01j, + 5.958145844148228e-01 - 6.107074340842115e-01j, + 5.747812938519067e-01 + 6.643001536914696e-01j, + 5.747812938519067e-01 - 6.643001536914696e-01j] + k2 = 9.932997786497189e-02 + xp_assert_close(sorted(z, key=np.angle), + sorted(z2, key=np.angle), rtol=1e-13) + xp_assert_close(sorted(p, key=np.angle), + sorted(p2, key=np.angle), rtol=1e-12) + xp_assert_close(k, k2, rtol=1e-11) + + # high odd order + z, p, k = cheby2(25, 80, 0.5, 'high', output='zpk') + z2 = [9.690690376586687e-01 + 2.467897896011971e-01j, + 9.690690376586687e-01 - 2.467897896011971e-01j, + 9.999999999999492e-01, + 8.835111277191199e-01 + 4.684101698261429e-01j, + 8.835111277191199e-01 - 4.684101698261429e-01j, + 7.613142857900539e-01 + 6.483830335935022e-01j, + 7.613142857900539e-01 - 6.483830335935022e-01j, + 6.232625173626231e-01 + 7.820126817709752e-01j, + 6.232625173626231e-01 - 7.820126817709752e-01j, + 4.864456563413621e-01 + 8.737108351316745e-01j, + 4.864456563413621e-01 - 8.737108351316745e-01j, + 3.618368136816749e-01 + 9.322414495530347e-01j, + 3.618368136816749e-01 - 9.322414495530347e-01j, + 2.549486883466794e-01 + 9.669545833752675e-01j, + 2.549486883466794e-01 - 9.669545833752675e-01j, + 1.676175432109457e-01 + 9.858520980390212e-01j, + 1.676175432109457e-01 - 9.858520980390212e-01j, + 1.975218468277521e-03 + 9.999980492540941e-01j, + 1.975218468277521e-03 - 9.999980492540941e-01j, + 1.786959496651858e-02 + 9.998403260399917e-01j, + 1.786959496651858e-02 - 9.998403260399917e-01j, + 9.967933660557139e-02 + 9.950196127985684e-01j, + 9.967933660557139e-02 - 9.950196127985684e-01j, + 5.013970951219547e-02 + 9.987422137518890e-01j, + 5.013970951219547e-02 - 9.987422137518890e-01j] + p2 = [4.218866331906864e-01, + 4.120110200127552e-01 + 1.361290593621978e-01j, + 4.120110200127552e-01 - 1.361290593621978e-01j, + 3.835890113632530e-01 + 2.664910809911026e-01j, + 3.835890113632530e-01 - 2.664910809911026e-01j, + 3.399195570456499e-01 + 3.863983538639875e-01j, + 3.399195570456499e-01 - 3.863983538639875e-01j, + 2.855977834508353e-01 + 4.929444399540688e-01j, + 2.855977834508353e-01 - 4.929444399540688e-01j, + 2.255765441339322e-01 + 5.851631870205766e-01j, + 2.255765441339322e-01 - 5.851631870205766e-01j, + 1.644087535815792e-01 + 6.637356937277153e-01j, + 1.644087535815792e-01 - 6.637356937277153e-01j, + -7.293633845273095e-02 + 9.739218252516307e-01j, + -7.293633845273095e-02 - 9.739218252516307e-01j, + 1.058259206358626e-01 + 7.304739464862978e-01j, + 1.058259206358626e-01 - 7.304739464862978e-01j, + -5.703971947785402e-02 + 9.291057542169088e-01j, + -5.703971947785402e-02 - 9.291057542169088e-01j, + 5.263875132656864e-02 + 7.877974334424453e-01j, + 5.263875132656864e-02 - 7.877974334424453e-01j, + -3.007943405982616e-02 + 8.846331716180016e-01j, + -3.007943405982616e-02 - 8.846331716180016e-01j, + 6.857277464483946e-03 + 8.383275456264492e-01j, + 6.857277464483946e-03 - 8.383275456264492e-01j] + k2 = 6.507068761705037e-03 + xp_assert_close(sorted(z, key=np.angle), + sorted(z2, key=np.angle), rtol=1e-13) + xp_assert_close(sorted(p, key=np.angle), + sorted(p2, key=np.angle), rtol=1e-12) + xp_assert_close(k, k2, rtol=1e-11) + + def test_bandpass(self): + z, p, k = cheby2(9, 40, [0.07, 0.2], 'pass', output='zpk') + z2 = [-9.999999999999999e-01, + 3.676588029658514e-01 + 9.299607543341383e-01j, + 3.676588029658514e-01 - 9.299607543341383e-01j, + 7.009689684982283e-01 + 7.131917730894889e-01j, + 7.009689684982283e-01 - 7.131917730894889e-01j, + 7.815697973765858e-01 + 6.238178033919218e-01j, + 7.815697973765858e-01 - 6.238178033919218e-01j, + 8.063793628819866e-01 + 5.913986160941200e-01j, + 8.063793628819866e-01 - 5.913986160941200e-01j, + 1.000000000000001e+00, + 9.944493019920448e-01 + 1.052168511576739e-01j, + 9.944493019920448e-01 - 1.052168511576739e-01j, + 9.854674703367308e-01 + 1.698642543566085e-01j, + 9.854674703367308e-01 - 1.698642543566085e-01j, + 9.762751735919308e-01 + 2.165335665157851e-01j, + 9.762751735919308e-01 - 2.165335665157851e-01j, + 9.792277171575134e-01 + 2.027636011479496e-01j, + 9.792277171575134e-01 - 2.027636011479496e-01j] + p2 = [8.143803410489621e-01 + 5.411056063397541e-01j, + 8.143803410489621e-01 - 5.411056063397541e-01j, + 7.650769827887418e-01 + 5.195412242095543e-01j, + 7.650769827887418e-01 - 5.195412242095543e-01j, + 6.096241204063443e-01 + 3.568440484659796e-01j, + 6.096241204063443e-01 - 3.568440484659796e-01j, + 6.918192770246239e-01 + 4.770463577106911e-01j, + 6.918192770246239e-01 - 4.770463577106911e-01j, + 6.986241085779207e-01 + 1.146512226180060e-01j, + 6.986241085779207e-01 - 1.146512226180060e-01j, + 8.654645923909734e-01 + 1.604208797063147e-01j, + 8.654645923909734e-01 - 1.604208797063147e-01j, + 9.164831670444591e-01 + 1.969181049384918e-01j, + 9.164831670444591e-01 - 1.969181049384918e-01j, + 9.630425777594550e-01 + 2.317513360702271e-01j, + 9.630425777594550e-01 - 2.317513360702271e-01j, + 9.438104703725529e-01 + 2.193509900269860e-01j, + 9.438104703725529e-01 - 2.193509900269860e-01j] + k2 = 9.345352824659604e-03 + xp_assert_close(sorted(z, key=np.angle), + sorted(z2, key=np.angle), rtol=1e-13) + xp_assert_close(sorted(p, key=np.angle), + sorted(p2, key=np.angle), rtol=1e-13) + xp_assert_close(k, k2, rtol=1e-11) + + def test_bandstop(self): + z, p, k = cheby2(6, 55, [0.1, 0.9], 'stop', output='zpk') + z2 = [6.230544895101009e-01 + 7.821784343111114e-01j, + 6.230544895101009e-01 - 7.821784343111114e-01j, + 9.086608545660115e-01 + 4.175349702471991e-01j, + 9.086608545660115e-01 - 4.175349702471991e-01j, + 9.478129721465802e-01 + 3.188268649763867e-01j, + 9.478129721465802e-01 - 3.188268649763867e-01j, + -6.230544895100982e-01 + 7.821784343111109e-01j, + -6.230544895100982e-01 - 7.821784343111109e-01j, + -9.086608545660116e-01 + 4.175349702472088e-01j, + -9.086608545660116e-01 - 4.175349702472088e-01j, + -9.478129721465784e-01 + 3.188268649763897e-01j, + -9.478129721465784e-01 - 3.188268649763897e-01j] + p2 = [-9.464094036167638e-01 + 1.720048695084344e-01j, + -9.464094036167638e-01 - 1.720048695084344e-01j, + -8.715844103386737e-01 + 1.370665039509297e-01j, + -8.715844103386737e-01 - 1.370665039509297e-01j, + -8.078751204586425e-01 + 5.729329866682983e-02j, + -8.078751204586425e-01 - 5.729329866682983e-02j, + 9.464094036167665e-01 + 1.720048695084332e-01j, + 9.464094036167665e-01 - 1.720048695084332e-01j, + 8.078751204586447e-01 + 5.729329866683007e-02j, + 8.078751204586447e-01 - 5.729329866683007e-02j, + 8.715844103386721e-01 + 1.370665039509331e-01j, + 8.715844103386721e-01 - 1.370665039509331e-01j] + k2 = 2.917823332763358e-03 + xp_assert_close(sorted(z, key=np.angle), + sorted(z2, key=np.angle), rtol=1e-13) + xp_assert_close(sorted(p, key=np.angle), + sorted(p2, key=np.angle), rtol=1e-13) + xp_assert_close(k, k2, rtol=1e-11) + + def test_ba_output(self): + # with transfer function conversion, without digital conversion + b, a = cheby2(5, 20, [2010, 2100], 'stop', True) + b2 = [1.000000000000000e+00, 0, # Matlab: 6.683253076978249e-12, + 2.111512500000000e+07, 0, # Matlab: 1.134325604589552e-04, + 1.782966433781250e+14, 0, # Matlab: 7.216787944356781e+02, + 7.525901316990656e+20, 0, # Matlab: 2.039829265789886e+09, + 1.587960565565748e+27, 0, # Matlab: 2.161236218626134e+15, + 1.339913493808585e+33] + a2 = [1.000000000000000e+00, 1.849550755473371e+02, + 2.113222918998538e+07, 3.125114149732283e+09, + 1.785133457155609e+14, 1.979158697776348e+16, + 7.535048322653831e+20, 5.567966191263037e+22, + 1.589246884221346e+27, 5.871210648525566e+28, + 1.339913493808590e+33] + xp_assert_close(b, b2, rtol=1e-14) + xp_assert_close(a, a2, rtol=1e-14) + + def test_fs_param(self): + for fs in (900, 900.1, 1234.567): + for N in (0, 1, 2, 3, 10): + for fc in (100, 100.1, 432.12345): + for btype in ('lp', 'hp'): + ba1 = cheby2(N, 20, fc, btype, fs=fs) + ba2 = cheby2(N, 20, fc/(fs/2), btype) + for ba1_, ba2_ in zip(ba1, ba2): + xp_assert_close(ba1_, ba2_) + for fc in ((100, 200), (100.1, 200.2), (321.123, 432.123)): + for btype in ('bp', 'bs'): + ba1 = cheby2(N, 20, fc, btype, fs=fs) + for seq in (list, tuple, array): + fcnorm = seq([f/(fs/2) for f in fc]) + ba2 = cheby2(N, 20, fcnorm, btype) + for ba1_, ba2_ in zip(ba1, ba2): + xp_assert_close(ba1_, ba2_) + +class TestEllip: + + def test_degenerate(self): + # 0-order filter is just a passthrough + # Even-order filters have DC gain of -rp dB + # Stopband ripple factor doesn't matter + b, a = ellip(0, 10*np.log10(2), 123.456, 1, analog=True) + assert_array_almost_equal(b, [1/np.sqrt(2)]) + xp_assert_equal(a, np.asarray([1.0])) + + # 1-order filter is same for all types + b, a = ellip(1, 10*np.log10(2), 1, 1, analog=True) + assert_array_almost_equal(b, [1]) + assert_array_almost_equal(a, [1, 1]) + + z, p, k = ellip(1, 1, 55, 0.3, output='zpk') + xp_assert_close(z, [-9.999999999999998e-01], rtol=1e-14) + xp_assert_close(p, [-6.660721153525525e-04], rtol=1e-10) + xp_assert_close(k, 5.003330360576763e-01, rtol=1e-14) + + def test_basic(self): + for N in range(25): + wn = 0.01 + z, p, k = ellip(N, 1, 40, wn, 'low', analog=True, output='zpk') + assert len(p) == N + assert all(np.real(p) <= 0) # No poles in right half of S-plane + + for N in range(25): + wn = 0.01 + z, p, k = ellip(N, 1, 40, wn, 'high', analog=False, output='zpk') + assert all(np.abs(p) <= 1) # No poles outside unit circle + + b3, a3 = ellip(5, 3, 26, 1, analog=True) + assert_array_almost_equal(b3, [0.1420, 0, 0.3764, 0, + 0.2409], decimal=4) + assert_array_almost_equal(a3, [1, 0.5686, 1.8061, 0.8017, 0.8012, + 0.2409], decimal=4) + + b, a = ellip(3, 1, 60, [0.4, 0.7], 'stop') + assert_array_almost_equal(b, [0.3310, 0.3469, 1.1042, 0.7044, 1.1042, + 0.3469, 0.3310], decimal=4) + assert_array_almost_equal(a, [1.0000, 0.6973, 1.1441, 0.5878, 0.7323, + 0.1131, -0.0060], decimal=4) + + def test_highpass(self): + # high even order + z, p, k = ellip(24, 1, 80, 0.3, 'high', output='zpk') + z2 = [9.761875332501075e-01 + 2.169283290099910e-01j, + 9.761875332501075e-01 - 2.169283290099910e-01j, + 8.413503353963494e-01 + 5.404901600661900e-01j, + 8.413503353963494e-01 - 5.404901600661900e-01j, + 7.160082576305009e-01 + 6.980918098681732e-01j, + 7.160082576305009e-01 - 6.980918098681732e-01j, + 6.456533638965329e-01 + 7.636306264739803e-01j, + 6.456533638965329e-01 - 7.636306264739803e-01j, + 6.127321820971366e-01 + 7.902906256703928e-01j, + 6.127321820971366e-01 - 7.902906256703928e-01j, + 5.983607817490196e-01 + 8.012267936512676e-01j, + 5.983607817490196e-01 - 8.012267936512676e-01j, + 5.922577552594799e-01 + 8.057485658286990e-01j, + 5.922577552594799e-01 - 8.057485658286990e-01j, + 5.896952092563588e-01 + 8.076258788449631e-01j, + 5.896952092563588e-01 - 8.076258788449631e-01j, + 5.886248765538837e-01 + 8.084063054565607e-01j, + 5.886248765538837e-01 - 8.084063054565607e-01j, + 5.881802711123132e-01 + 8.087298490066037e-01j, + 5.881802711123132e-01 - 8.087298490066037e-01j, + 5.879995719101164e-01 + 8.088612386766461e-01j, + 5.879995719101164e-01 - 8.088612386766461e-01j, + 5.879354086709576e-01 + 8.089078780868164e-01j, + 5.879354086709576e-01 - 8.089078780868164e-01j] + p2 = [-3.184805259081650e-01 + 4.206951906775851e-01j, + -3.184805259081650e-01 - 4.206951906775851e-01j, + 1.417279173459985e-01 + 7.903955262836452e-01j, + 1.417279173459985e-01 - 7.903955262836452e-01j, + 4.042881216964651e-01 + 8.309042239116594e-01j, + 4.042881216964651e-01 - 8.309042239116594e-01j, + 5.128964442789670e-01 + 8.229563236799665e-01j, + 5.128964442789670e-01 - 8.229563236799665e-01j, + 5.569614712822724e-01 + 8.155957702908510e-01j, + 5.569614712822724e-01 - 8.155957702908510e-01j, + 5.750478870161392e-01 + 8.118633973883931e-01j, + 5.750478870161392e-01 - 8.118633973883931e-01j, + 5.825314018170804e-01 + 8.101960910679270e-01j, + 5.825314018170804e-01 - 8.101960910679270e-01j, + 5.856397379751872e-01 + 8.094825218722543e-01j, + 5.856397379751872e-01 - 8.094825218722543e-01j, + 5.869326035251949e-01 + 8.091827531557583e-01j, + 5.869326035251949e-01 - 8.091827531557583e-01j, + 5.874697218855733e-01 + 8.090593298213502e-01j, + 5.874697218855733e-01 - 8.090593298213502e-01j, + 5.876904783532237e-01 + 8.090127161018823e-01j, + 5.876904783532237e-01 - 8.090127161018823e-01j, + 5.877753105317594e-01 + 8.090050577978136e-01j, + 5.877753105317594e-01 - 8.090050577978136e-01j] + k2 = 4.918081266957108e-02 + xp_assert_close(sorted(z, key=np.angle), + sorted(z2, key=np.angle), rtol=1e-4) + xp_assert_close(sorted(p, key=np.angle), + sorted(p2, key=np.angle), rtol=1e-4) + xp_assert_close(k, k2, rtol=1e-3) + + # high odd order + z, p, k = ellip(23, 1, 70, 0.5, 'high', output='zpk') + z2 = [9.999999999998661e-01, + 6.603717261750994e-01 + 7.509388678638675e-01j, + 6.603717261750994e-01 - 7.509388678638675e-01j, + 2.788635267510325e-01 + 9.603307416968041e-01j, + 2.788635267510325e-01 - 9.603307416968041e-01j, + 1.070215532544218e-01 + 9.942567008268131e-01j, + 1.070215532544218e-01 - 9.942567008268131e-01j, + 4.049427369978163e-02 + 9.991797705105507e-01j, + 4.049427369978163e-02 - 9.991797705105507e-01j, + 1.531059368627931e-02 + 9.998827859909265e-01j, + 1.531059368627931e-02 - 9.998827859909265e-01j, + 5.808061438534933e-03 + 9.999831330689181e-01j, + 5.808061438534933e-03 - 9.999831330689181e-01j, + 2.224277847754599e-03 + 9.999975262909676e-01j, + 2.224277847754599e-03 - 9.999975262909676e-01j, + 8.731857107534554e-04 + 9.999996187732845e-01j, + 8.731857107534554e-04 - 9.999996187732845e-01j, + 3.649057346914968e-04 + 9.999999334218996e-01j, + 3.649057346914968e-04 - 9.999999334218996e-01j, + 1.765538109802615e-04 + 9.999999844143768e-01j, + 1.765538109802615e-04 - 9.999999844143768e-01j, + 1.143655290967426e-04 + 9.999999934602630e-01j, + 1.143655290967426e-04 - 9.999999934602630e-01j] + p2 = [-6.322017026545028e-01, + -4.648423756662754e-01 + 5.852407464440732e-01j, + -4.648423756662754e-01 - 5.852407464440732e-01j, + -2.249233374627773e-01 + 8.577853017985717e-01j, + -2.249233374627773e-01 - 8.577853017985717e-01j, + -9.234137570557621e-02 + 9.506548198678851e-01j, + -9.234137570557621e-02 - 9.506548198678851e-01j, + -3.585663561241373e-02 + 9.821494736043981e-01j, + -3.585663561241373e-02 - 9.821494736043981e-01j, + -1.363917242312723e-02 + 9.933844128330656e-01j, + -1.363917242312723e-02 - 9.933844128330656e-01j, + -5.131505238923029e-03 + 9.975221173308673e-01j, + -5.131505238923029e-03 - 9.975221173308673e-01j, + -1.904937999259502e-03 + 9.990680819857982e-01j, + -1.904937999259502e-03 - 9.990680819857982e-01j, + -6.859439885466834e-04 + 9.996492201426826e-01j, + -6.859439885466834e-04 - 9.996492201426826e-01j, + -2.269936267937089e-04 + 9.998686250679161e-01j, + -2.269936267937089e-04 - 9.998686250679161e-01j, + -5.687071588789117e-05 + 9.999527573294513e-01j, + -5.687071588789117e-05 - 9.999527573294513e-01j, + -6.948417068525226e-07 + 9.999882737700173e-01j, + -6.948417068525226e-07 - 9.999882737700173e-01j] + k2 = 1.220910020289434e-02 + xp_assert_close(sorted(z, key=np.angle), + sorted(z2, key=np.angle), rtol=1e-4) + xp_assert_close(sorted(p, key=np.angle), + sorted(p2, key=np.angle), rtol=1e-4) + xp_assert_close(k, k2, rtol=1e-3) + + def test_bandpass(self): + z, p, k = ellip(7, 1, 40, [0.07, 0.2], 'pass', output='zpk') + z2 = [-9.999999999999991e-01, + 6.856610961780020e-01 + 7.279209168501619e-01j, + 6.856610961780020e-01 - 7.279209168501619e-01j, + 7.850346167691289e-01 + 6.194518952058737e-01j, + 7.850346167691289e-01 - 6.194518952058737e-01j, + 7.999038743173071e-01 + 6.001281461922627e-01j, + 7.999038743173071e-01 - 6.001281461922627e-01j, + 9.999999999999999e-01, + 9.862938983554124e-01 + 1.649980183725925e-01j, + 9.862938983554124e-01 - 1.649980183725925e-01j, + 9.788558330548762e-01 + 2.045513580850601e-01j, + 9.788558330548762e-01 - 2.045513580850601e-01j, + 9.771155231720003e-01 + 2.127093189691258e-01j, + 9.771155231720003e-01 - 2.127093189691258e-01j] + p2 = [8.063992755498643e-01 + 5.858071374778874e-01j, + 8.063992755498643e-01 - 5.858071374778874e-01j, + 8.050395347071724e-01 + 5.639097428109795e-01j, + 8.050395347071724e-01 - 5.639097428109795e-01j, + 8.113124936559144e-01 + 4.855241143973142e-01j, + 8.113124936559144e-01 - 4.855241143973142e-01j, + 8.665595314082394e-01 + 3.334049560919331e-01j, + 8.665595314082394e-01 - 3.334049560919331e-01j, + 9.412369011968871e-01 + 2.457616651325908e-01j, + 9.412369011968871e-01 - 2.457616651325908e-01j, + 9.679465190411238e-01 + 2.228772501848216e-01j, + 9.679465190411238e-01 - 2.228772501848216e-01j, + 9.747235066273385e-01 + 2.178937926146544e-01j, + 9.747235066273385e-01 - 2.178937926146544e-01j] + k2 = 8.354782670263239e-03 + xp_assert_close(sorted(z, key=np.angle), + sorted(z2, key=np.angle), rtol=1e-4) + xp_assert_close(sorted(p, key=np.angle), + sorted(p2, key=np.angle), rtol=1e-4) + xp_assert_close(k, k2, rtol=1e-3) + + z, p, k = ellip(5, 1, 75, [90.5, 110.5], 'pass', True, 'zpk') + z2 = [-5.583607317695175e-14 + 1.433755965989225e+02j, + -5.583607317695175e-14 - 1.433755965989225e+02j, + 5.740106416459296e-14 + 1.261678754570291e+02j, + 5.740106416459296e-14 - 1.261678754570291e+02j, + -2.199676239638652e-14 + 6.974861996895196e+01j, + -2.199676239638652e-14 - 6.974861996895196e+01j, + -3.372595657044283e-14 + 7.926145989044531e+01j, + -3.372595657044283e-14 - 7.926145989044531e+01j, + 0] + p2 = [-8.814960004852743e-01 + 1.104124501436066e+02j, + -8.814960004852743e-01 - 1.104124501436066e+02j, + -2.477372459140184e+00 + 1.065638954516534e+02j, + -2.477372459140184e+00 - 1.065638954516534e+02j, + -3.072156842945799e+00 + 9.995404870405324e+01j, + -3.072156842945799e+00 - 9.995404870405324e+01j, + -2.180456023925693e+00 + 9.379206865455268e+01j, + -2.180456023925693e+00 - 9.379206865455268e+01j, + -7.230484977485752e-01 + 9.056598800801140e+01j, + -7.230484977485752e-01 - 9.056598800801140e+01j] + k2 = 3.774571622827070e-02 + xp_assert_close(sorted(z, key=np.imag), + sorted(z2, key=np.imag), rtol=1e-4) + xp_assert_close(sorted(p, key=np.imag), + sorted(p2, key=np.imag), rtol=1e-6) + xp_assert_close(k, k2, rtol=1e-3) + + def test_bandstop(self): + z, p, k = ellip(8, 1, 65, [0.2, 0.4], 'stop', output='zpk') + z2 = [3.528578094286510e-01 + 9.356769561794296e-01j, + 3.528578094286510e-01 - 9.356769561794296e-01j, + 3.769716042264783e-01 + 9.262248159096587e-01j, + 3.769716042264783e-01 - 9.262248159096587e-01j, + 4.406101783111199e-01 + 8.976985411420985e-01j, + 4.406101783111199e-01 - 8.976985411420985e-01j, + 5.539386470258847e-01 + 8.325574907062760e-01j, + 5.539386470258847e-01 - 8.325574907062760e-01j, + 6.748464963023645e-01 + 7.379581332490555e-01j, + 6.748464963023645e-01 - 7.379581332490555e-01j, + 7.489887970285254e-01 + 6.625826604475596e-01j, + 7.489887970285254e-01 - 6.625826604475596e-01j, + 7.913118471618432e-01 + 6.114127579150699e-01j, + 7.913118471618432e-01 - 6.114127579150699e-01j, + 7.806804740916381e-01 + 6.249303940216475e-01j, + 7.806804740916381e-01 - 6.249303940216475e-01j] + + p2 = [-1.025299146693730e-01 + 5.662682444754943e-01j, + -1.025299146693730e-01 - 5.662682444754943e-01j, + 1.698463595163031e-01 + 8.926678667070186e-01j, + 1.698463595163031e-01 - 8.926678667070186e-01j, + 2.750532687820631e-01 + 9.351020170094005e-01j, + 2.750532687820631e-01 - 9.351020170094005e-01j, + 3.070095178909486e-01 + 9.457373499553291e-01j, + 3.070095178909486e-01 - 9.457373499553291e-01j, + 7.695332312152288e-01 + 2.792567212705257e-01j, + 7.695332312152288e-01 - 2.792567212705257e-01j, + 8.083818999225620e-01 + 4.990723496863960e-01j, + 8.083818999225620e-01 - 4.990723496863960e-01j, + 8.066158014414928e-01 + 5.649811440393374e-01j, + 8.066158014414928e-01 - 5.649811440393374e-01j, + 8.062787978834571e-01 + 5.855780880424964e-01j, + 8.062787978834571e-01 - 5.855780880424964e-01j] + k2 = 2.068622545291259e-01 + xp_assert_close(sorted(z, key=np.angle), + sorted(z2, key=np.angle), rtol=1e-6) + xp_assert_close(sorted(p, key=np.angle), + sorted(p2, key=np.angle), rtol=1e-5) + xp_assert_close(k, k2, rtol=1e-5) + + def test_ba_output(self): + # with transfer function conversion, without digital conversion + b, a = ellip(5, 1, 40, [201, 240], 'stop', True) + b2 = [ + 1.000000000000000e+00, 0, # Matlab: 1.743506051190569e-13, + 2.426561778314366e+05, 0, # Matlab: 3.459426536825722e-08, + 2.348218683400168e+10, 0, # Matlab: 2.559179747299313e-03, + 1.132780692872241e+15, 0, # Matlab: 8.363229375535731e+01, + 2.724038554089566e+19, 0, # Matlab: 1.018700994113120e+06, + 2.612380874940186e+23 + ] + a2 = [ + 1.000000000000000e+00, 1.337266601804649e+02, + 2.486725353510667e+05, 2.628059713728125e+07, + 2.436169536928770e+10, 1.913554568577315e+12, + 1.175208184614438e+15, 6.115751452473410e+16, + 2.791577695211466e+19, 7.241811142725384e+20, + 2.612380874940182e+23 + ] + xp_assert_close(b, b2, rtol=1e-6) + xp_assert_close(a, a2, rtol=1e-4) + + def test_fs_param(self): + for fs in (900, 900.1, 1234.567): + for N in (0, 1, 2, 3, 10): + for fc in (100, 100.1, 432.12345): + for btype in ('lp', 'hp'): + ba1 = ellip(N, 1, 20, fc, btype, fs=fs) + ba2 = ellip(N, 1, 20, fc/(fs/2), btype) + for ba1_, ba2_ in zip(ba1, ba2): + xp_assert_close(ba1_, ba2_) + for fc in ((100, 200), (100.1, 200.2), (321.123, 432.123)): + for btype in ('bp', 'bs'): + ba1 = ellip(N, 1, 20, fc, btype, fs=fs) + for seq in (list, tuple, array): + fcnorm = seq([f/(fs/2) for f in fc]) + ba2 = ellip(N, 1, 20, fcnorm, btype) + for ba1_, ba2_ in zip(ba1, ba2): + xp_assert_close(ba1_, ba2_) + + def test_fs_validation(self): + with pytest.raises(ValueError, match="Sampling.*single scalar"): + iirnotch(0.06, 30, fs=np.array([10, 20])) + + with pytest.raises(ValueError, match="Sampling.*be none"): + iirnotch(0.06, 30, fs=None) + + +def test_sos_consistency(): + # Consistency checks of output='sos' for the specialized IIR filter + # design functions. + design_funcs = [(bessel, (0.1,)), + (butter, (0.1,)), + (cheby1, (45.0, 0.1)), + (cheby2, (0.087, 0.1)), + (ellip, (0.087, 45, 0.1))] + for func, args in design_funcs: + name = func.__name__ + + b, a = func(2, *args, output='ba') + sos = func(2, *args, output='sos') + xp_assert_close(sos, [np.hstack((b, a))], err_msg=f"{name}(2,...)") + + zpk = func(3, *args, output='zpk') + sos = func(3, *args, output='sos') + xp_assert_close(sos, zpk2sos(*zpk), err_msg=f"{name}(3,...)") + + zpk = func(4, *args, output='zpk') + sos = func(4, *args, output='sos') + xp_assert_close(sos, zpk2sos(*zpk), err_msg=f"{name}(4,...)") + + +class TestIIRNotch: + + def test_ba_output(self): + # Compare coefficients with Matlab ones + # for the equivalent input: + b, a = iirnotch(0.06, 30) + b2 = [ + 9.9686824e-01, -1.9584219e+00, + 9.9686824e-01 + ] + a2 = [ + 1.0000000e+00, -1.9584219e+00, + 9.9373647e-01 + ] + + xp_assert_close(b, b2, rtol=1e-8) + xp_assert_close(a, a2, rtol=1e-8) + + def test_frequency_response(self): + # Get filter coefficients + b, a = iirnotch(0.3, 30) + + # Get frequency response + w, h = freqz(b, a, 1000) + + # Pick 5 point + p = [200, # w0 = 0.200 + 295, # w0 = 0.295 + 300, # w0 = 0.300 + 305, # w0 = 0.305 + 400] # w0 = 0.400 + + # Get frequency response correspondent to each of those points + hp = h[p] + + # Check if the frequency response fulfill the specifications: + # hp[0] and hp[4] correspond to frequencies distant from + # w0 = 0.3 and should be close to 1 + xp_assert_close(abs(hp[0]), np.asarray(1.), rtol=1e-2, check_0d=False) + xp_assert_close(abs(hp[4]), np.asarray(1.), rtol=1e-2, check_0d=False) + + # hp[1] and hp[3] correspond to frequencies approximately + # on the edges of the passband and should be close to -3dB + xp_assert_close(abs(hp[1]), 1/np.sqrt(2), rtol=1e-2) + xp_assert_close(abs(hp[3]), 1/np.sqrt(2), rtol=1e-2) + + # hp[2] correspond to the frequency that should be removed + # the frequency response should be very close to 0 + xp_assert_close(abs(hp[2]), np.asarray(0.0), atol=1e-10, check_0d=False) + + def test_errors(self): + # Exception should be raised if w0 > 1 or w0 <0 + assert_raises(ValueError, iirnotch, w0=2, Q=30) + assert_raises(ValueError, iirnotch, w0=-1, Q=30) + + # Exception should be raised if any of the parameters + # are not float (or cannot be converted to one) + assert_raises(ValueError, iirnotch, w0="blabla", Q=30) + assert_raises(TypeError, iirnotch, w0=-1, Q=[1, 2, 3]) + + def test_fs_param(self): + # Get filter coefficients + b, a = iirnotch(1500, 30, fs=10000) + + # Get frequency response + w, h = freqz(b, a, 1000, fs=10000) + + # Pick 5 point + p = [200, # w0 = 1000 + 295, # w0 = 1475 + 300, # w0 = 1500 + 305, # w0 = 1525 + 400] # w0 = 2000 + + # Get frequency response correspondent to each of those points + hp = h[p] + + # Check if the frequency response fulfill the specifications: + # hp[0] and hp[4] correspond to frequencies distant from + # w0 = 1500 and should be close to 1 + xp_assert_close(abs(hp[0]), np.ones_like(abs(hp[0])), rtol=1e-2, + check_0d=False) + xp_assert_close(abs(hp[4]), np.ones_like(abs(hp[4])), rtol=1e-2, + check_0d=False) + + # hp[1] and hp[3] correspond to frequencies approximately + # on the edges of the passband and should be close to -3dB + xp_assert_close(abs(hp[1]), 1/np.sqrt(2), rtol=1e-2) + xp_assert_close(abs(hp[3]), 1/np.sqrt(2), rtol=1e-2) + + # hp[2] correspond to the frequency that should be removed + # the frequency response should be very close to 0 + xp_assert_close(abs(hp[2]), np.asarray(0.0), atol=1e-10, check_0d=False) + + +class TestIIRPeak: + + def test_ba_output(self): + # Compare coefficients with Matlab ones + # for the equivalent input: + b, a = iirpeak(0.06, 30) + b2 = [ + 3.131764229e-03, 0, + -3.131764229e-03 + ] + a2 = [ + 1.0000000e+00, -1.958421917e+00, + 9.9373647e-01 + ] + xp_assert_close(b, b2, rtol=1e-8) + xp_assert_close(a, a2, rtol=1e-8) + + def test_frequency_response(self): + # Get filter coefficients + b, a = iirpeak(0.3, 30) + + # Get frequency response + w, h = freqz(b, a, 1000) + + # Pick 5 point + p = [30, # w0 = 0.030 + 295, # w0 = 0.295 + 300, # w0 = 0.300 + 305, # w0 = 0.305 + 800] # w0 = 0.800 + + # Get frequency response correspondent to each of those points + hp = h[p] + + # Check if the frequency response fulfill the specifications: + # hp[0] and hp[4] correspond to frequencies distant from + # w0 = 0.3 and should be close to 0 + xp_assert_close(abs(hp[0]), + np.zeros_like(abs(hp[0])), atol=1e-2, check_0d=False) + xp_assert_close(abs(hp[4]), + np.zeros_like(abs(hp[4])), atol=1e-2, check_0d=False) + + # hp[1] and hp[3] correspond to frequencies approximately + # on the edges of the passband and should be close to 10**(-3/20) + xp_assert_close(abs(hp[1]), 1/np.sqrt(2), rtol=1e-2) + xp_assert_close(abs(hp[3]), 1/np.sqrt(2), rtol=1e-2) + + # hp[2] correspond to the frequency that should be retained and + # the frequency response should be very close to 1 + xp_assert_close(abs(hp[2]), np.asarray(1.0), rtol=1e-10, check_0d=False) + + def test_errors(self): + # Exception should be raised if w0 > 1 or w0 <0 + assert_raises(ValueError, iirpeak, w0=2, Q=30) + assert_raises(ValueError, iirpeak, w0=-1, Q=30) + + # Exception should be raised if any of the parameters + # are not float (or cannot be converted to one) + assert_raises(ValueError, iirpeak, w0="blabla", Q=30) + assert_raises(TypeError, iirpeak, w0=-1, Q=[1, 2, 3]) + + def test_fs_param(self): + # Get filter coefficients + b, a = iirpeak(1200, 30, fs=8000) + + # Get frequency response + w, h = freqz(b, a, 1000, fs=8000) + + # Pick 5 point + p = [30, # w0 = 120 + 295, # w0 = 1180 + 300, # w0 = 1200 + 305, # w0 = 1220 + 800] # w0 = 3200 + + # Get frequency response correspondent to each of those points + hp = h[p] + + # Check if the frequency response fulfill the specifications: + # hp[0] and hp[4] correspond to frequencies distant from + # w0 = 1200 and should be close to 0 + xp_assert_close(abs(hp[0]), + np.zeros_like(abs(hp[0])), atol=1e-2, check_0d=False) + xp_assert_close(abs(hp[4]), + np.zeros_like(abs(hp[4])), atol=1e-2, check_0d=False) + + # hp[1] and hp[3] correspond to frequencies approximately + # on the edges of the passband and should be close to 10**(-3/20) + xp_assert_close(abs(hp[1]), 1/np.sqrt(2), rtol=1e-2) + xp_assert_close(abs(hp[3]), 1/np.sqrt(2), rtol=1e-2) + + # hp[2] correspond to the frequency that should be retained and + # the frequency response should be very close to 1 + xp_assert_close(abs(hp[2]), + np.ones_like(abs(hp[2])), rtol=1e-10, check_0d=False) + + +class TestIIRComb: + # Test erroneous input cases + def test_invalid_input(self): + # w0 is <= 0 or >= fs / 2 + fs = 1000 + for args in [(-fs, 30), (0, 35), (fs / 2, 40), (fs, 35)]: + with pytest.raises(ValueError, match='w0 must be between '): + iircomb(*args, fs=fs) + + # fs is not divisible by w0 + for args in [(120, 30), (157, 35)]: + with pytest.raises(ValueError, match='fs must be divisible '): + iircomb(*args, fs=fs) + + # https://github.com/scipy/scipy/issues/14043#issuecomment-1107349140 + # Previously, fs=44100, w0=49.999 was rejected, but fs=2, + # w0=49.999/int(44100/2) was accepted. Now it is rejected, too. + with pytest.raises(ValueError, match='fs must be divisible '): + iircomb(w0=49.999/int(44100/2), Q=30) + + with pytest.raises(ValueError, match='fs must be divisible '): + iircomb(w0=49.999, Q=30, fs=44100) + + # Filter type is not notch or peak + for args in [(0.2, 30, 'natch'), (0.5, 35, 'comb')]: + with pytest.raises(ValueError, match='ftype must be '): + iircomb(*args) + + # Verify that the filter's frequency response contains a + # notch at the cutoff frequency + @pytest.mark.parametrize('ftype', ('notch', 'peak')) + def test_frequency_response(self, ftype): + # Create a notching or peaking comb filter at 1000 Hz + b, a = iircomb(1000, 30, ftype=ftype, fs=10000) + + # Compute the frequency response + freqs, response = freqz(b, a, 1000, fs=10000) + + # Find the notch using argrelextrema + comb_points = argrelextrema(abs(response), np.less)[0] + + # Verify that the first notch sits at 1000 Hz + comb1 = comb_points[0] + xp_assert_close(freqs[comb1], np.asarray(1000.), check_0d=False) + + # Verify pass_zero parameter + @pytest.mark.parametrize('ftype,pass_zero,peak,notch', + [('peak', True, 123.45, 61.725), + ('peak', False, 61.725, 123.45), + ('peak', None, 61.725, 123.45), + ('notch', None, 61.725, 123.45), + ('notch', True, 123.45, 61.725), + ('notch', False, 61.725, 123.45)]) + def test_pass_zero(self, ftype, pass_zero, peak, notch): + # Create a notching or peaking comb filter + b, a = iircomb(123.45, 30, ftype=ftype, fs=1234.5, pass_zero=pass_zero) + + # Compute the frequency response + freqs, response = freqz(b, a, [peak, notch], fs=1234.5) + + # Verify that expected notches are notches and peaks are peaks + assert abs(response[0]) > 0.99 + assert abs(response[1]) < 1e-10 + + # All built-in IIR filters are real, so should have perfectly + # symmetrical poles and zeros. Then ba representation (using + # numpy.poly) will be purely real instead of having negligible + # imaginary parts. + def test_iir_symmetry(self): + b, a = iircomb(400, 30, fs=24000) + z, p, k = tf2zpk(b, a) + xp_assert_equal(sorted(z), sorted(z.conj())) + xp_assert_equal(sorted(p), sorted(p.conj())) + xp_assert_equal(k, np.real(k)) + + assert issubclass(b.dtype.type, np.floating) + assert issubclass(a.dtype.type, np.floating) + + # Verify filter coefficients with MATLAB's iircomb function + def test_ba_output(self): + b_notch, a_notch = iircomb(60, 35, ftype='notch', fs=600) + b_notch2 = [0.957020174408697, 0.0, 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, -0.957020174408697] + a_notch2 = [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, -0.914040348817395] + xp_assert_close(b_notch, b_notch2) + xp_assert_close(a_notch, a_notch2) + + b_peak, a_peak = iircomb(60, 35, ftype='peak', fs=600) + b_peak2 = [0.0429798255913026, 0.0, 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, -0.0429798255913026] + a_peak2 = [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, 0.914040348817395] + xp_assert_close(b_peak, b_peak2) + xp_assert_close(a_peak, a_peak2) + + # Verify that https://github.com/scipy/scipy/issues/14043 is fixed + def test_nearest_divisor(self): + # Create a notching comb filter + b, a = iircomb(50/int(44100/2), 50.0, ftype='notch') + + # Compute the frequency response at an upper harmonic of 50 + freqs, response = freqz(b, a, [22000], fs=44100) + + # Before bug fix, this would produce N = 881, so that 22 kHz was ~0 dB. + # Now N = 882 correctly and 22 kHz should be a notch <-220 dB + assert abs(response[0]) < 1e-10 + + def test_fs_validation(self): + with pytest.raises(ValueError, match="Sampling.*single scalar"): + iircomb(1000, 30, fs=np.array([10, 20])) + + with pytest.raises(ValueError, match="Sampling.*be none"): + iircomb(1000, 30, fs=None) + + +class TestIIRDesign: + + def test_exceptions(self): + with pytest.raises(ValueError, match="the same shape"): + iirdesign(0.2, [0.1, 0.3], 1, 40) + with pytest.raises(ValueError, match="the same shape"): + iirdesign(np.array([[0.3, 0.6], [0.3, 0.6]]), + np.array([[0.4, 0.5], [0.4, 0.5]]), 1, 40) + + # discrete filter with non-positive frequency + with pytest.raises(ValueError, match="must be greater than 0"): + iirdesign(0, 0.5, 1, 40) + with pytest.raises(ValueError, match="must be greater than 0"): + iirdesign(-0.1, 0.5, 1, 40) + with pytest.raises(ValueError, match="must be greater than 0"): + iirdesign(0.1, 0, 1, 40) + with pytest.raises(ValueError, match="must be greater than 0"): + iirdesign(0.1, -0.5, 1, 40) + with pytest.raises(ValueError, match="must be greater than 0"): + iirdesign([0, 0.3], [0.1, 0.5], 1, 40) + with pytest.raises(ValueError, match="must be greater than 0"): + iirdesign([-0.1, 0.3], [0.1, 0.5], 1, 40) + with pytest.raises(ValueError, match="must be greater than 0"): + iirdesign([0.1, 0], [0.1, 0.5], 1, 40) + with pytest.raises(ValueError, match="must be greater than 0"): + iirdesign([0.1, -0.3], [0.1, 0.5], 1, 40) + with pytest.raises(ValueError, match="must be greater than 0"): + iirdesign([0.1, 0.3], [0, 0.5], 1, 40) + with pytest.raises(ValueError, match="must be greater than 0"): + iirdesign([0.1, 0.3], [-0.1, 0.5], 1, 40) + with pytest.raises(ValueError, match="must be greater than 0"): + iirdesign([0.1, 0.3], [0.1, 0], 1, 40) + with pytest.raises(ValueError, match="must be greater than 0"): + iirdesign([0.1, 0.3], [0.1, -0.5], 1, 40) + + # analog filter with negative frequency + with pytest.raises(ValueError, match="must be greater than 0"): + iirdesign(-0.1, 0.5, 1, 40, analog=True) + with pytest.raises(ValueError, match="must be greater than 0"): + iirdesign(0.1, -0.5, 1, 40, analog=True) + with pytest.raises(ValueError, match="must be greater than 0"): + iirdesign([-0.1, 0.3], [0.1, 0.5], 1, 40, analog=True) + with pytest.raises(ValueError, match="must be greater than 0"): + iirdesign([0.1, -0.3], [0.1, 0.5], 1, 40, analog=True) + with pytest.raises(ValueError, match="must be greater than 0"): + iirdesign([0.1, 0.3], [-0.1, 0.5], 1, 40, analog=True) + with pytest.raises(ValueError, match="must be greater than 0"): + iirdesign([0.1, 0.3], [0.1, -0.5], 1, 40, analog=True) + + # discrete filter with fs=None, freq > 1 + with pytest.raises(ValueError, match="must be less than 1"): + iirdesign(1, 0.5, 1, 40) + with pytest.raises(ValueError, match="must be less than 1"): + iirdesign(1.1, 0.5, 1, 40) + with pytest.raises(ValueError, match="must be less than 1"): + iirdesign(0.1, 1, 1, 40) + with pytest.raises(ValueError, match="must be less than 1"): + iirdesign(0.1, 1.5, 1, 40) + with pytest.raises(ValueError, match="must be less than 1"): + iirdesign([1, 0.3], [0.1, 0.5], 1, 40) + with pytest.raises(ValueError, match="must be less than 1"): + iirdesign([1.1, 0.3], [0.1, 0.5], 1, 40) + with pytest.raises(ValueError, match="must be less than 1"): + iirdesign([0.1, 1], [0.1, 0.5], 1, 40) + with pytest.raises(ValueError, match="must be less than 1"): + iirdesign([0.1, 1.1], [0.1, 0.5], 1, 40) + with pytest.raises(ValueError, match="must be less than 1"): + iirdesign([0.1, 0.3], [1, 0.5], 1, 40) + with pytest.raises(ValueError, match="must be less than 1"): + iirdesign([0.1, 0.3], [1.1, 0.5], 1, 40) + with pytest.raises(ValueError, match="must be less than 1"): + iirdesign([0.1, 0.3], [0.1, 1], 1, 40) + with pytest.raises(ValueError, match="must be less than 1"): + iirdesign([0.1, 0.3], [0.1, 1.5], 1, 40) + + # discrete filter with fs>2, wp, ws < fs/2 must pass + iirdesign(100, 500, 1, 40, fs=2000) + iirdesign(500, 100, 1, 40, fs=2000) + iirdesign([200, 400], [100, 500], 1, 40, fs=2000) + iirdesign([100, 500], [200, 400], 1, 40, fs=2000) + + # discrete filter with fs>2, freq > fs/2: this must raise + with pytest.raises(ValueError, match="must be less than fs/2"): + iirdesign(1000, 400, 1, 40, fs=2000) + with pytest.raises(ValueError, match="must be less than fs/2"): + iirdesign(1100, 500, 1, 40, fs=2000) + with pytest.raises(ValueError, match="must be less than fs/2"): + iirdesign(100, 1000, 1, 40, fs=2000) + with pytest.raises(ValueError, match="must be less than fs/2"): + iirdesign(100, 1100, 1, 40, fs=2000) + with pytest.raises(ValueError, match="must be less than fs/2"): + iirdesign([1000, 400], [100, 500], 1, 40, fs=2000) + with pytest.raises(ValueError, match="must be less than fs/2"): + iirdesign([1100, 400], [100, 500], 1, 40, fs=2000) + with pytest.raises(ValueError, match="must be less than fs/2"): + iirdesign([200, 1000], [100, 500], 1, 40, fs=2000) + with pytest.raises(ValueError, match="must be less than fs/2"): + iirdesign([200, 1100], [100, 500], 1, 40, fs=2000) + with pytest.raises(ValueError, match="must be less than fs/2"): + iirdesign([200, 400], [1000, 500], 1, 40, fs=2000) + with pytest.raises(ValueError, match="must be less than fs/2"): + iirdesign([200, 400], [1100, 500], 1, 40, fs=2000) + with pytest.raises(ValueError, match="must be less than fs/2"): + iirdesign([200, 400], [100, 1000], 1, 40, fs=2000) + with pytest.raises(ValueError, match="must be less than fs/2"): + iirdesign([200, 400], [100, 1100], 1, 40, fs=2000) + + with pytest.raises(ValueError, match="strictly inside stopband"): + iirdesign([0.1, 0.4], [0.5, 0.6], 1, 40) + with pytest.raises(ValueError, match="strictly inside stopband"): + iirdesign([0.5, 0.6], [0.1, 0.4], 1, 40) + with pytest.raises(ValueError, match="strictly inside stopband"): + iirdesign([0.3, 0.6], [0.4, 0.7], 1, 40) + with pytest.raises(ValueError, match="strictly inside stopband"): + iirdesign([0.4, 0.7], [0.3, 0.6], 1, 40) + + def test_fs_validation(self): + with pytest.raises(ValueError, match="Sampling.*single scalar"): + iirfilter(1, 1, btype="low", fs=np.array([10, 20])) + + +class TestIIRFilter: + + def test_symmetry(self): + # All built-in IIR filters are real, so should have perfectly + # symmetrical poles and zeros. Then ba representation (using + # numpy.poly) will be purely real instead of having negligible + # imaginary parts. + for N in np.arange(1, 26): + for ftype in ('butter', 'bessel', 'cheby1', 'cheby2', 'ellip'): + z, p, k = iirfilter(N, 1.1, 1, 20, 'low', analog=True, + ftype=ftype, output='zpk') + xp_assert_equal(sorted(z), + sorted(z.conj())) + xp_assert_equal(sorted(p), + sorted(p.conj())) + xp_assert_equal(k, np.real(k)) + + b, a = iirfilter(N, 1.1, 1, 20, 'low', analog=True, + ftype=ftype, output='ba') + assert issubclass(b.dtype.type, np.floating) + assert issubclass(a.dtype.type, np.floating) + + def test_int_inputs(self): + # Using integer frequency arguments and large N should not produce + # numpy integers that wraparound to negative numbers + k = iirfilter(24, 100, btype='low', analog=True, ftype='bessel', + output='zpk')[2] + k2 = 9.999999999999989e+47 + xp_assert_close(np.asarray(k), np.asarray(k2)) + # if fs is specified then the normalization of Wn to have + # 0 <= Wn <= 1 should not cause an integer overflow + # the following line should not raise an exception + iirfilter(20, [1000000000, 1100000000], btype='bp', + analog=False, fs=6250000000) + + def test_invalid_wn_size(self): + # low and high have 1 Wn, band and stop have 2 Wn + assert_raises(ValueError, iirfilter, 1, [0.1, 0.9], btype='low') + assert_raises(ValueError, iirfilter, 1, [0.2, 0.5], btype='high') + assert_raises(ValueError, iirfilter, 1, 0.2, btype='bp') + assert_raises(ValueError, iirfilter, 1, 400, btype='bs', analog=True) + + def test_invalid_wn_range(self): + # For digital filters, 0 <= Wn <= 1 + assert_raises(ValueError, iirfilter, 1, 2, btype='low') + assert_raises(ValueError, iirfilter, 1, [0.5, 1], btype='band') + assert_raises(ValueError, iirfilter, 1, [0., 0.5], btype='band') + assert_raises(ValueError, iirfilter, 1, -1, btype='high') + assert_raises(ValueError, iirfilter, 1, [1, 2], btype='band') + assert_raises(ValueError, iirfilter, 1, [10, 20], btype='stop') + + # analog=True with non-positive critical frequencies + with pytest.raises(ValueError, match="must be greater than 0"): + iirfilter(2, 0, btype='low', analog=True) + with pytest.raises(ValueError, match="must be greater than 0"): + iirfilter(2, -1, btype='low', analog=True) + with pytest.raises(ValueError, match="must be greater than 0"): + iirfilter(2, [0, 100], analog=True) + with pytest.raises(ValueError, match="must be greater than 0"): + iirfilter(2, [-1, 100], analog=True) + with pytest.raises(ValueError, match="must be greater than 0"): + iirfilter(2, [10, 0], analog=True) + with pytest.raises(ValueError, match="must be greater than 0"): + iirfilter(2, [10, -1], analog=True) + + def test_analog_sos(self): + # first order Butterworth filter with Wn = 1 has tf 1/(s+1) + sos = [[0., 0., 1., 0., 1., 1.]] + sos2 = iirfilter(N=1, Wn=1, btype='low', analog=True, output='sos') + assert_array_almost_equal(sos, sos2) + + def test_wn1_ge_wn0(self): + # gh-15773: should raise error if Wn[0] >= Wn[1] + with pytest.raises(ValueError, + match=r"Wn\[0\] must be less than Wn\[1\]"): + iirfilter(2, [0.5, 0.5]) + with pytest.raises(ValueError, + match=r"Wn\[0\] must be less than Wn\[1\]"): + iirfilter(2, [0.6, 0.5]) + + +class TestGroupDelay: + def test_identity_filter(self): + w, gd = group_delay((1, 1)) + assert_array_almost_equal(w, pi * np.arange(512) / 512) + assert_array_almost_equal(gd, np.zeros(512)) + w, gd = group_delay((1, 1), whole=True) + assert_array_almost_equal(w, 2 * pi * np.arange(512) / 512) + assert_array_almost_equal(gd, np.zeros(512)) + + def test_fir(self): + # Let's design linear phase FIR and check that the group delay + # is constant. + N = 100 + b = firwin(N + 1, 0.1) + w, gd = group_delay((b, 1)) + xp_assert_close(gd, np.ones_like(gd)*(0.5 * N)) + + def test_iir(self): + # Let's design Butterworth filter and test the group delay at + # some points against MATLAB answer. + b, a = butter(4, 0.1) + w = np.linspace(0, pi, num=10, endpoint=False) + w, gd = group_delay((b, a), w=w) + matlab_gd = np.array([8.249313898506037, 11.958947880907104, + 2.452325615326005, 1.048918665702008, + 0.611382575635897, 0.418293269460578, + 0.317932917836572, 0.261371844762525, + 0.229038045801298, 0.212185774208521]) + assert_array_almost_equal(gd, matlab_gd) + + @pytest.mark.thread_unsafe + def test_singular(self): + # Let's create a filter with zeros and poles on the unit circle and + # check if warnings are raised at those frequencies. + z1 = np.exp(1j * 0.1 * pi) + z2 = np.exp(1j * 0.25 * pi) + p1 = np.exp(1j * 0.5 * pi) + p2 = np.exp(1j * 0.8 * pi) + b = np.convolve([1, -z1], [1, -z2]) + a = np.convolve([1, -p1], [1, -p2]) + w = np.array([0.1 * pi, 0.25 * pi, -0.5 * pi, -0.8 * pi]) + + w, gd = assert_warns(UserWarning, group_delay, (b, a), w=w) + + def test_backward_compat(self): + # For backward compatibility, test if None act as a wrapper for default + w1, gd1 = group_delay((1, 1)) + w2, gd2 = group_delay((1, 1), None) + assert_array_almost_equal(w1, w2) + assert_array_almost_equal(gd1, gd2) + + def test_fs_param(self): + # Let's design Butterworth filter and test the group delay at + # some points against the normalized frequency answer. + b, a = butter(4, 4800, fs=96000) + w = np.linspace(0, 96000/2, num=10, endpoint=False) + w, gd = group_delay((b, a), w=w, fs=96000) + norm_gd = np.array([8.249313898506037, 11.958947880907104, + 2.452325615326005, 1.048918665702008, + 0.611382575635897, 0.418293269460578, + 0.317932917836572, 0.261371844762525, + 0.229038045801298, 0.212185774208521]) + assert_array_almost_equal(gd, norm_gd) + + def test_w_or_N_types(self): + # Measure at 8 equally-spaced points + for N in (8, np.int8(8), np.int16(8), np.int32(8), np.int64(8), + np.array(8)): + w, gd = group_delay((1, 1), N) + assert_array_almost_equal(w, pi * np.arange(8) / 8) + assert_array_almost_equal(gd, np.zeros(8)) + + # Measure at frequency 8 rad/sec + for w in (8.0, 8.0+0j): + w_out, gd = group_delay((1, 1), w) + assert_array_almost_equal(w_out, [8]) + assert_array_almost_equal(gd, [0]) + + def test_complex_coef(self): + # gh-19586: handle complex coef TFs + # + # for g(z) = (alpha*z+1)/(1+conjugate(alpha)), group delay is + # given by function below. + # + # def gd_expr(w, alpha): + # num = 1j*(abs(alpha)**2-1)*np.exp(1j*w) + # den = (alpha*np.exp(1j*w)+1)*(np.exp(1j*w)+np.conj(alpha)) + # return -np.imag(num/den) + + # arbitrary non-real alpha + alpha = -0.6143077933232609+0.3355978770229421j + # 8 points from from -pi to pi + wref = np.array([-3.141592653589793 , + -2.356194490192345 , + -1.5707963267948966, + -0.7853981633974483, + 0. , + 0.7853981633974483, + 1.5707963267948966, + 2.356194490192345 ]) + gdref = array([0.18759548150354619, + 0.17999770352712252, + 0.23598047471879877, + 0.46539443069907194, + 1.9511492420564165 , + 3.478129975138865 , + 0.6228594960517333 , + 0.27067831839471224]) + b = [alpha,1] + a = [1, np.conjugate(alpha)] + gdtest = group_delay((b,a), wref)[1] + # need nulp=14 for macOS arm64 wheel builds; added 2 for some + # robustness on other platforms. + assert_array_almost_equal_nulp(gdtest, gdref, nulp=16) + + def test_fs_validation(self): + with pytest.raises(ValueError, match="Sampling.*single scalar"): + group_delay((1, 1), fs=np.array([10, 20])) + + with pytest.raises(ValueError, match="Sampling.*be none"): + group_delay((1, 1), fs=None) + + +class TestGammatone: + # Test erroneous input cases. + def test_invalid_input(self): + # Cutoff frequency is <= 0 or >= fs / 2. + fs = 16000 + for args in [(-fs, 'iir'), (0, 'fir'), (fs / 2, 'iir'), (fs, 'fir')]: + with pytest.raises(ValueError, match='The frequency must be ' + 'between '): + gammatone(*args, fs=fs) + + # Filter type is not fir or iir + for args in [(440, 'fie'), (220, 'it')]: + with pytest.raises(ValueError, match='ftype must be '): + gammatone(*args, fs=fs) + + # Order is <= 0 or > 24 for FIR filter. + for args in [(440, 'fir', -50), (220, 'fir', 0), (110, 'fir', 25), + (55, 'fir', 50)]: + with pytest.raises(ValueError, match='Invalid order: '): + gammatone(*args, numtaps=None, fs=fs) + + # Verify that the filter's frequency response is approximately + # 1 at the cutoff frequency. + def test_frequency_response(self): + fs = 16000 + ftypes = ['fir', 'iir'] + for ftype in ftypes: + # Create a gammatone filter centered at 1000 Hz. + b, a = gammatone(1000, ftype, fs=fs) + + # Calculate the frequency response. + freqs, response = freqz(b, a) + + # Determine peak magnitude of the response + # and corresponding frequency. + response_max = np.max(np.abs(response)) + freq_hz = freqs[np.argmax(np.abs(response))] / ((2 * np.pi) / fs) + + # Check that the peak magnitude is 1 and the frequency is 1000 Hz. + xp_assert_close(response_max, + np.ones_like(response_max), rtol=1e-2, check_0d=False) + xp_assert_close(freq_hz, + 1000*np.ones_like(freq_hz), rtol=1e-2, check_0d=False) + + # All built-in IIR filters are real, so should have perfectly + # symmetrical poles and zeros. Then ba representation (using + # numpy.poly) will be purely real instead of having negligible + # imaginary parts. + def test_iir_symmetry(self): + b, a = gammatone(440, 'iir', fs=24000) + z, p, k = tf2zpk(b, a) + xp_assert_equal(sorted(z), sorted(z.conj())) + xp_assert_equal(sorted(p), sorted(p.conj())) + xp_assert_equal(k, np.real(k)) + + assert issubclass(b.dtype.type, np.floating) + assert issubclass(a.dtype.type, np.floating) + + # Verify FIR filter coefficients with the paper's + # Mathematica implementation + def test_fir_ba_output(self): + b, _ = gammatone(15, 'fir', fs=1000) + b2 = [0.0, 2.2608075649884e-04, + 1.5077903981357e-03, 4.2033687753998e-03, + 8.1508962726503e-03, 1.2890059089154e-02, + 1.7833890391666e-02, 2.2392613558564e-02, + 2.6055195863104e-02, 2.8435872863284e-02, + 2.9293319149544e-02, 2.852976858014e-02, + 2.6176557156294e-02, 2.2371510270395e-02, + 1.7332485267759e-02] + xp_assert_close(b, b2) + + # Verify IIR filter coefficients with the paper's MATLAB implementation + def test_iir_ba_output(self): + b, a = gammatone(440, 'iir', fs=16000) + b2 = [1.31494461367464e-06, -5.03391196645395e-06, + 7.00649426000897e-06, -4.18951968419854e-06, + 9.02614910412011e-07] + a2 = [1.0, -7.65646235454218, + 25.7584699322366, -49.7319214483238, + 60.2667361289181, -46.9399590980486, + 22.9474798808461, -6.43799381299034, + 0.793651554625368] + xp_assert_close(b, b2) + xp_assert_close(a, a2) + + def test_fs_validation(self): + with pytest.raises(ValueError, match="Sampling.*single scalar"): + gammatone(440, 'iir', fs=np.array([10, 20])) + + +class TestOrderFilter: + def test_doc_example(self): + x = np.arange(25).reshape(5, 5) + domain = np.identity(3) + + # minimum of elements 1,3,9 (zero-padded) on phone pad + # 7,5,3 on numpad + expected = np.array( + [[0., 0., 0., 0., 0.], + [0., 0., 1., 2., 0.], + [0., 5., 6., 7., 0.], + [0., 10., 11., 12., 0.], + [0., 0., 0., 0., 0.]], + ) + xp_assert_close(order_filter(x, domain, 0), expected, check_dtype=False) + + # maximum of elements 1,3,9 (zero-padded) on phone pad + # 7,5,3 on numpad + expected = np.array( + [[6., 7., 8., 9., 4.], + [11., 12., 13., 14., 9.], + [16., 17., 18., 19., 14.], + [21., 22., 23., 24., 19.], + [20., 21., 22., 23., 24.]], + ) + xp_assert_close(order_filter(x, domain, 2), expected, check_dtype=False) + + # and, just to complete the set, median of zero-padded elements + expected = np.array( + [[0, 1, 2, 3, 0], + [5, 6, 7, 8, 3], + [10, 11, 12, 13, 8], + [15, 16, 17, 18, 13], + [0, 15, 16, 17, 18]], + ) + xp_assert_close(order_filter(x, domain, 1), expected) + + def test_medfilt_order_filter(self): + x = np.arange(25).reshape(5, 5) + + # median of zero-padded elements 1,5,9 on phone pad + # 7,5,3 on numpad + expected = np.array( + [[0, 1, 2, 3, 0], + [1, 6, 7, 8, 4], + [6, 11, 12, 13, 9], + [11, 16, 17, 18, 14], + [0, 16, 17, 18, 0]], + ) + xp_assert_close(medfilt(x, 3), expected) + + xp_assert_close( + order_filter(x, np.ones((3, 3)), 4), + expected + ) + + def test_order_filter_asymmetric(self): + x = np.arange(25).reshape(5, 5) + domain = np.array( + [[1, 1, 0], + [0, 1, 0], + [0, 0, 0]], + ) + + expected = np.array( + [[0, 0, 0, 0, 0], + [0, 0, 1, 2, 3], + [0, 5, 6, 7, 8], + [0, 10, 11, 12, 13], + [0, 15, 16, 17, 18]] + ) + xp_assert_close(order_filter(x, domain, 0), expected) + + expected = np.array( + [[0, 0, 0, 0, 0], + [0, 1, 2, 3, 4], + [5, 6, 7, 8, 9], + [10, 11, 12, 13, 14], + [15, 16, 17, 18, 19]] + ) + xp_assert_close(order_filter(x, domain, 1), expected) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_fir_filter_design.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_fir_filter_design.py new file mode 100644 index 0000000000000000000000000000000000000000..cd2b60e63cdcb36e39c6775fa99394d123c2956b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_fir_filter_design.py @@ -0,0 +1,654 @@ +import numpy as np +from numpy.testing import assert_warns +from scipy._lib._array_api import ( + xp_assert_close, xp_assert_equal, + assert_almost_equal, assert_array_almost_equal, +) +from pytest import raises as assert_raises +import pytest + +from scipy.fft import fft +from scipy.special import sinc +from scipy.signal import (kaiser_beta, kaiser_atten, kaiserord, + firwin, firwin2, freqz, remez, firls, minimum_phase +) + + +def test_kaiser_beta(): + b = kaiser_beta(58.7) + assert_almost_equal(b, 0.1102 * 50.0) + b = kaiser_beta(22.0) + assert_almost_equal(b, 0.5842 + 0.07886) + b = kaiser_beta(21.0) + assert b == 0.0 + b = kaiser_beta(10.0) + assert b == 0.0 + + +def test_kaiser_atten(): + a = kaiser_atten(1, 1.0) + assert a == 7.95 + a = kaiser_atten(2, 1/np.pi) + assert a == 2.285 + 7.95 + + +def test_kaiserord(): + assert_raises(ValueError, kaiserord, 1.0, 1.0) + numtaps, beta = kaiserord(2.285 + 7.95 - 0.001, 1/np.pi) + assert (numtaps, beta) == (2, 0.0) + + +class TestFirwin: + + def check_response(self, h, expected_response, tol=.05): + N = len(h) + alpha = 0.5 * (N-1) + m = np.arange(0,N) - alpha # time indices of taps + for freq, expected in expected_response: + actual = abs(np.sum(h*np.exp(-1.j*np.pi*m*freq))) + mse = abs(actual-expected)**2 + assert mse < tol, f'response not as expected, mse={mse:g} > {tol:g}' + + def test_response(self): + N = 51 + f = .5 + # increase length just to try even/odd + h = firwin(N, f) # low-pass from 0 to f + self.check_response(h, [(.25,1), (.75,0)]) + + h = firwin(N+1, f, window='nuttall') # specific window + self.check_response(h, [(.25,1), (.75,0)]) + + h = firwin(N+2, f, pass_zero=False) # stop from 0 to f --> high-pass + self.check_response(h, [(.25,0), (.75,1)]) + + f1, f2, f3, f4 = .2, .4, .6, .8 + h = firwin(N+3, [f1, f2], pass_zero=False) # band-pass filter + self.check_response(h, [(.1,0), (.3,1), (.5,0)]) + + h = firwin(N+4, [f1, f2]) # band-stop filter + self.check_response(h, [(.1,1), (.3,0), (.5,1)]) + + h = firwin(N+5, [f1, f2, f3, f4], pass_zero=False, scale=False) + self.check_response(h, [(.1,0), (.3,1), (.5,0), (.7,1), (.9,0)]) + + h = firwin(N+6, [f1, f2, f3, f4]) # multiband filter + self.check_response(h, [(.1,1), (.3,0), (.5,1), (.7,0), (.9,1)]) + + h = firwin(N+7, 0.1, width=.03) # low-pass + self.check_response(h, [(.05,1), (.75,0)]) + + h = firwin(N+8, 0.1, pass_zero=False) # high-pass + self.check_response(h, [(.05,0), (.75,1)]) + + def mse(self, h, bands): + """Compute mean squared error versus ideal response across frequency + band. + h -- coefficients + bands -- list of (left, right) tuples relative to 1==Nyquist of + passbands + """ + w, H = freqz(h, worN=1024) + f = w/np.pi + passIndicator = np.zeros(len(w), bool) + for left, right in bands: + passIndicator |= (f >= left) & (f < right) + Hideal = np.where(passIndicator, 1, 0) + mse = np.mean(abs(abs(H)-Hideal)**2) + return mse + + def test_scaling(self): + """ + For one lowpass, bandpass, and highpass example filter, this test + checks two things: + - the mean squared error over the frequency domain of the unscaled + filter is smaller than the scaled filter (true for rectangular + window) + - the response of the scaled filter is exactly unity at the center + of the first passband + """ + N = 11 + cases = [ + ([.5], True, (0, 1)), + ([0.2, .6], False, (.4, 1)), + ([.5], False, (1, 1)), + ] + for cutoff, pass_zero, expected_response in cases: + h = firwin(N, cutoff, scale=False, pass_zero=pass_zero, window='ones') + hs = firwin(N, cutoff, scale=True, pass_zero=pass_zero, window='ones') + if len(cutoff) == 1: + if pass_zero: + cutoff = [0] + cutoff + else: + cutoff = cutoff + [1] + msg = 'least squares violation' + assert self.mse(h, [cutoff]) < self.mse(hs, [cutoff]), msg + self.check_response(hs, [expected_response], 1e-12) + + def test_fs_validation(self): + with pytest.raises(ValueError, match="Sampling.*single scalar"): + firwin(51, .5, fs=np.array([10, 20])) + + +class TestFirWinMore: + """Different author, different style, different tests...""" + + def test_lowpass(self): + width = 0.04 + ntaps, beta = kaiserord(120, width) + kwargs = dict(cutoff=0.5, window=('kaiser', beta), scale=False) + taps = firwin(ntaps, **kwargs) + + # Check the symmetry of taps. + assert_array_almost_equal(taps[:ntaps//2], taps[ntaps:ntaps-ntaps//2-1:-1]) + + # Check the gain at a few samples where + # we know it should be approximately 0 or 1. + freq_samples = np.array([0.0, 0.25, 0.5-width/2, 0.5+width/2, 0.75, 1.0]) + freqs, response = freqz(taps, worN=np.pi*freq_samples) + assert_array_almost_equal(np.abs(response), + [1.0, 1.0, 1.0, 0.0, 0.0, 0.0], decimal=5) + + taps_str = firwin(ntaps, pass_zero='lowpass', **kwargs) + xp_assert_close(taps, taps_str) + + def test_highpass(self): + width = 0.04 + ntaps, beta = kaiserord(120, width) + + # Ensure that ntaps is odd. + ntaps |= 1 + + kwargs = dict(cutoff=0.5, window=('kaiser', beta), scale=False) + taps = firwin(ntaps, pass_zero=False, **kwargs) + + # Check the symmetry of taps. + assert_array_almost_equal(taps[:ntaps//2], taps[ntaps:ntaps-ntaps//2-1:-1]) + + # Check the gain at a few samples where + # we know it should be approximately 0 or 1. + freq_samples = np.array([0.0, 0.25, 0.5-width/2, 0.5+width/2, 0.75, 1.0]) + freqs, response = freqz(taps, worN=np.pi*freq_samples) + assert_array_almost_equal(np.abs(response), + [0.0, 0.0, 0.0, 1.0, 1.0, 1.0], decimal=5) + + taps_str = firwin(ntaps, pass_zero='highpass', **kwargs) + xp_assert_close(taps, taps_str) + + def test_bandpass(self): + width = 0.04 + ntaps, beta = kaiserord(120, width) + kwargs = dict(cutoff=[0.3, 0.7], window=('kaiser', beta), scale=False) + taps = firwin(ntaps, pass_zero=False, **kwargs) + + # Check the symmetry of taps. + assert_array_almost_equal(taps[:ntaps//2], taps[ntaps:ntaps-ntaps//2-1:-1]) + + # Check the gain at a few samples where + # we know it should be approximately 0 or 1. + freq_samples = np.array([0.0, 0.2, 0.3-width/2, 0.3+width/2, 0.5, + 0.7-width/2, 0.7+width/2, 0.8, 1.0]) + freqs, response = freqz(taps, worN=np.pi*freq_samples) + assert_array_almost_equal(np.abs(response), + [0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0], decimal=5) + + taps_str = firwin(ntaps, pass_zero='bandpass', **kwargs) + xp_assert_close(taps, taps_str) + + def test_bandstop_multi(self): + width = 0.04 + ntaps, beta = kaiserord(120, width) + kwargs = dict(cutoff=[0.2, 0.5, 0.8], window=('kaiser', beta), + scale=False) + taps = firwin(ntaps, **kwargs) + + # Check the symmetry of taps. + assert_array_almost_equal(taps[:ntaps//2], taps[ntaps:ntaps-ntaps//2-1:-1]) + + # Check the gain at a few samples where + # we know it should be approximately 0 or 1. + freq_samples = np.array([0.0, 0.1, 0.2-width/2, 0.2+width/2, 0.35, + 0.5-width/2, 0.5+width/2, 0.65, + 0.8-width/2, 0.8+width/2, 0.9, 1.0]) + freqs, response = freqz(taps, worN=np.pi*freq_samples) + assert_array_almost_equal(np.abs(response), + [1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0], + decimal=5) + + taps_str = firwin(ntaps, pass_zero='bandstop', **kwargs) + xp_assert_close(taps, taps_str) + + def test_fs_nyq(self): + """Test the fs and nyq keywords.""" + nyquist = 1000 + width = 40.0 + relative_width = width/nyquist + ntaps, beta = kaiserord(120, relative_width) + taps = firwin(ntaps, cutoff=[300, 700], window=('kaiser', beta), + pass_zero=False, scale=False, fs=2*nyquist) + + # Check the symmetry of taps. + assert_array_almost_equal(taps[:ntaps//2], taps[ntaps:ntaps-ntaps//2-1:-1]) + + # Check the gain at a few samples where + # we know it should be approximately 0 or 1. + freq_samples = np.array([0.0, 200, 300-width/2, 300+width/2, 500, + 700-width/2, 700+width/2, 800, 1000]) + freqs, response = freqz(taps, worN=np.pi*freq_samples/nyquist) + assert_array_almost_equal(np.abs(response), + [0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0], decimal=5) + + def test_bad_cutoff(self): + """Test that invalid cutoff argument raises ValueError.""" + # cutoff values must be greater than 0 and less than 1. + assert_raises(ValueError, firwin, 99, -0.5) + assert_raises(ValueError, firwin, 99, 1.5) + # Don't allow 0 or 1 in cutoff. + assert_raises(ValueError, firwin, 99, [0, 0.5]) + assert_raises(ValueError, firwin, 99, [0.5, 1]) + # cutoff values must be strictly increasing. + assert_raises(ValueError, firwin, 99, [0.1, 0.5, 0.2]) + assert_raises(ValueError, firwin, 99, [0.1, 0.5, 0.5]) + # Must have at least one cutoff value. + assert_raises(ValueError, firwin, 99, []) + # 2D array not allowed. + assert_raises(ValueError, firwin, 99, [[0.1, 0.2],[0.3, 0.4]]) + # cutoff values must be less than nyq. + assert_raises(ValueError, firwin, 99, 50.0, fs=80) + assert_raises(ValueError, firwin, 99, [10, 20, 30], fs=50) + + def test_even_highpass_raises_value_error(self): + """Test that attempt to create a highpass filter with an even number + of taps raises a ValueError exception.""" + assert_raises(ValueError, firwin, 40, 0.5, pass_zero=False) + assert_raises(ValueError, firwin, 40, [.25, 0.5]) + + def test_bad_pass_zero(self): + """Test degenerate pass_zero cases.""" + with assert_raises(ValueError, match='pass_zero must be'): + firwin(41, 0.5, pass_zero='foo') + with assert_raises(TypeError, match='cannot be interpreted'): + firwin(41, 0.5, pass_zero=1.) + for pass_zero in ('lowpass', 'highpass'): + with assert_raises(ValueError, match='cutoff must have one'): + firwin(41, [0.5, 0.6], pass_zero=pass_zero) + for pass_zero in ('bandpass', 'bandstop'): + with assert_raises(ValueError, match='must have at least two'): + firwin(41, [0.5], pass_zero=pass_zero) + + def test_fs_validation(self): + with pytest.raises(ValueError, match="Sampling.*single scalar"): + firwin2(51, .5, 1, fs=np.array([10, 20])) + + +class TestFirwin2: + + def test_invalid_args(self): + # `freq` and `gain` have different lengths. + with assert_raises(ValueError, match='must be of same length'): + firwin2(50, [0, 0.5, 1], [0.0, 1.0]) + # `nfreqs` is less than `ntaps`. + with assert_raises(ValueError, match='ntaps must be less than nfreqs'): + firwin2(50, [0, 0.5, 1], [0.0, 1.0, 1.0], nfreqs=33) + # Decreasing value in `freq` + with assert_raises(ValueError, match='must be nondecreasing'): + firwin2(50, [0, 0.5, 0.4, 1.0], [0, .25, .5, 1.0]) + # Value in `freq` repeated more than once. + with assert_raises(ValueError, match='must not occur more than twice'): + firwin2(50, [0, .1, .1, .1, 1.0], [0.0, 0.5, 0.75, 1.0, 1.0]) + # `freq` does not start at 0.0. + with assert_raises(ValueError, match='start with 0'): + firwin2(50, [0.5, 1.0], [0.0, 1.0]) + # `freq` does not end at fs/2. + with assert_raises(ValueError, match='end with fs/2'): + firwin2(50, [0.0, 0.5], [0.0, 1.0]) + # Value 0 is repeated in `freq` + with assert_raises(ValueError, match='0 must not be repeated'): + firwin2(50, [0.0, 0.0, 0.5, 1.0], [1.0, 1.0, 0.0, 0.0]) + # Value fs/2 is repeated in `freq` + with assert_raises(ValueError, match='fs/2 must not be repeated'): + firwin2(50, [0.0, 0.5, 1.0, 1.0], [1.0, 1.0, 0.0, 0.0]) + # Value in `freq` that is too close to a repeated number + with assert_raises(ValueError, match='cannot contain numbers ' + 'that are too close'): + firwin2(50, [0.0, 0.5 - np.finfo(float).eps * 0.5, 0.5, 0.5, 1.0], + [1.0, 1.0, 1.0, 0.0, 0.0]) + + # Type II filter, but the gain at nyquist frequency is not zero. + with assert_raises(ValueError, match='Type II filter'): + firwin2(16, [0.0, 0.5, 1.0], [0.0, 1.0, 1.0]) + + # Type III filter, but the gains at nyquist and zero rate are not zero. + with assert_raises(ValueError, match='Type III filter'): + firwin2(17, [0.0, 0.5, 1.0], [0.0, 1.0, 1.0], antisymmetric=True) + with assert_raises(ValueError, match='Type III filter'): + firwin2(17, [0.0, 0.5, 1.0], [1.0, 1.0, 0.0], antisymmetric=True) + with assert_raises(ValueError, match='Type III filter'): + firwin2(17, [0.0, 0.5, 1.0], [1.0, 1.0, 1.0], antisymmetric=True) + + # Type IV filter, but the gain at zero rate is not zero. + with assert_raises(ValueError, match='Type IV filter'): + firwin2(16, [0.0, 0.5, 1.0], [1.0, 1.0, 0.0], antisymmetric=True) + + def test01(self): + width = 0.04 + beta = 12.0 + ntaps = 400 + # Filter is 1 from w=0 to w=0.5, then decreases linearly from 1 to 0 as w + # increases from w=0.5 to w=1 (w=1 is the Nyquist frequency). + freq = [0.0, 0.5, 1.0] + gain = [1.0, 1.0, 0.0] + taps = firwin2(ntaps, freq, gain, window=('kaiser', beta)) + freq_samples = np.array([0.0, 0.25, 0.5-width/2, 0.5+width/2, + 0.75, 1.0-width/2]) + freqs, response = freqz(taps, worN=np.pi*freq_samples) + assert_array_almost_equal(np.abs(response), + [1.0, 1.0, 1.0, 1.0-width, 0.5, width], decimal=5) + + def test02(self): + width = 0.04 + beta = 12.0 + # ntaps must be odd for positive gain at Nyquist. + ntaps = 401 + # An ideal highpass filter. + freq = [0.0, 0.5, 0.5, 1.0] + gain = [0.0, 0.0, 1.0, 1.0] + taps = firwin2(ntaps, freq, gain, window=('kaiser', beta)) + freq_samples = np.array([0.0, 0.25, 0.5-width, 0.5+width, 0.75, 1.0]) + freqs, response = freqz(taps, worN=np.pi*freq_samples) + assert_array_almost_equal(np.abs(response), + [0.0, 0.0, 0.0, 1.0, 1.0, 1.0], decimal=5) + + def test03(self): + width = 0.02 + ntaps, beta = kaiserord(120, width) + # ntaps must be odd for positive gain at Nyquist. + ntaps = int(ntaps) | 1 + freq = [0.0, 0.4, 0.4, 0.5, 0.5, 1.0] + gain = [1.0, 1.0, 0.0, 0.0, 1.0, 1.0] + taps = firwin2(ntaps, freq, gain, window=('kaiser', beta)) + freq_samples = np.array([0.0, 0.4-width, 0.4+width, 0.45, + 0.5-width, 0.5+width, 0.75, 1.0]) + freqs, response = freqz(taps, worN=np.pi*freq_samples) + assert_array_almost_equal(np.abs(response), + [1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0], decimal=5) + + def test04(self): + """Test firwin2 when window=None.""" + ntaps = 5 + # Ideal lowpass: gain is 1 on [0,0.5], and 0 on [0.5, 1.0] + freq = [0.0, 0.5, 0.5, 1.0] + gain = [1.0, 1.0, 0.0, 0.0] + taps = firwin2(ntaps, freq, gain, window=None, nfreqs=8193) + alpha = 0.5 * (ntaps - 1) + m = np.arange(0, ntaps) - alpha + h = 0.5 * sinc(0.5 * m) + assert_array_almost_equal(h, taps) + + def test05(self): + """Test firwin2 for calculating Type IV filters""" + ntaps = 1500 + + freq = [0.0, 1.0] + gain = [0.0, 1.0] + taps = firwin2(ntaps, freq, gain, window=None, antisymmetric=True) + assert_array_almost_equal(taps[: ntaps // 2], -taps[ntaps // 2:][::-1]) + + freqs, response = freqz(taps, worN=2048) + assert_array_almost_equal(abs(response), freqs / np.pi, decimal=4) + + def test06(self): + """Test firwin2 for calculating Type III filters""" + ntaps = 1501 + + freq = [0.0, 0.5, 0.55, 1.0] + gain = [0.0, 0.5, 0.0, 0.0] + taps = firwin2(ntaps, freq, gain, window=None, antisymmetric=True) + assert taps[ntaps // 2] == 0.0 + assert_array_almost_equal(taps[: ntaps // 2], -taps[ntaps // 2 + 1:][::-1]) + + freqs, response1 = freqz(taps, worN=2048) + response2 = np.interp(freqs / np.pi, freq, gain) + assert_array_almost_equal(abs(response1), response2, decimal=3) + + def test_fs_nyq(self): + taps1 = firwin2(80, [0.0, 0.5, 1.0], [1.0, 1.0, 0.0]) + taps2 = firwin2(80, [0.0, 30.0, 60.0], [1.0, 1.0, 0.0], fs=120.0) + assert_array_almost_equal(taps1, taps2) + + def test_tuple(self): + taps1 = firwin2(150, (0.0, 0.5, 0.5, 1.0), (1.0, 1.0, 0.0, 0.0)) + taps2 = firwin2(150, [0.0, 0.5, 0.5, 1.0], [1.0, 1.0, 0.0, 0.0]) + assert_array_almost_equal(taps1, taps2) + + def test_input_modyfication(self): + freq1 = np.array([0.0, 0.5, 0.5, 1.0]) + freq2 = np.array(freq1) + firwin2(80, freq1, [1.0, 1.0, 0.0, 0.0]) + xp_assert_equal(freq1, freq2) + + +class TestRemez: + + def test_bad_args(self): + assert_raises(ValueError, remez, 11, [0.1, 0.4], [1], type='pooka') + + def test_hilbert(self): + N = 11 # number of taps in the filter + a = 0.1 # width of the transition band + + # design an unity gain hilbert bandpass filter from w to 0.5-w + h = remez(11, [a, 0.5-a], [1], type='hilbert') + + # make sure the filter has correct # of taps + assert len(h) == N, "Number of Taps" + + # make sure it is type III (anti-symmetric tap coefficients) + assert_array_almost_equal(h[:(N-1)//2], -h[:-(N-1)//2-1:-1]) + + # Since the requested response is symmetric, all even coefficients + # should be zero (or in this case really small) + assert (abs(h[1::2]) < 1e-15).all(), "Even Coefficients Equal Zero" + + # now check the frequency response + w, H = freqz(h, 1) + f = w/2/np.pi + Hmag = abs(H) + + # should have a zero at 0 and pi (in this case close to zero) + assert (Hmag[[0, -1]] < 0.02).all(), "Zero at zero and pi" + + # check that the pass band is close to unity + idx = np.logical_and(f > a, f < 0.5-a) + assert (abs(Hmag[idx] - 1) < 0.015).all(), "Pass Band Close To Unity" + + def test_compare(self): + # test comparison to MATLAB + k = [0.024590270518440, -0.041314581814658, -0.075943803756711, + -0.003530911231040, 0.193140296954975, 0.373400753484939, + 0.373400753484939, 0.193140296954975, -0.003530911231040, + -0.075943803756711, -0.041314581814658, 0.024590270518440] + h = remez(12, [0, 0.3, 0.5, 1], [1, 0], fs=2.) + xp_assert_close(h, k) + + h = [-0.038976016082299, 0.018704846485491, -0.014644062687875, + 0.002879152556419, 0.016849978528150, -0.043276706138248, + 0.073641298245579, -0.103908158578635, 0.129770906801075, + -0.147163447297124, 0.153302248456347, -0.147163447297124, + 0.129770906801075, -0.103908158578635, 0.073641298245579, + -0.043276706138248, 0.016849978528150, 0.002879152556419, + -0.014644062687875, 0.018704846485491, -0.038976016082299] + xp_assert_close(remez(21, [0, 0.8, 0.9, 1], [0, 1], fs=2.), h) + + def test_fs_validation(self): + with pytest.raises(ValueError, match="Sampling.*single scalar"): + remez(11, .1, 1, fs=np.array([10, 20])) + +class TestFirls: + + def test_bad_args(self): + # even numtaps + assert_raises(ValueError, firls, 10, [0.1, 0.2], [0, 0]) + # odd bands + assert_raises(ValueError, firls, 11, [0.1, 0.2, 0.4], [0, 0, 0]) + # len(bands) != len(desired) + assert_raises(ValueError, firls, 11, [0.1, 0.2, 0.3, 0.4], [0, 0, 0]) + # non-monotonic bands + assert_raises(ValueError, firls, 11, [0.2, 0.1], [0, 0]) + assert_raises(ValueError, firls, 11, [0.1, 0.2, 0.3, 0.3], [0] * 4) + assert_raises(ValueError, firls, 11, [0.3, 0.4, 0.1, 0.2], [0] * 4) + assert_raises(ValueError, firls, 11, [0.1, 0.3, 0.2, 0.4], [0] * 4) + # negative desired + assert_raises(ValueError, firls, 11, [0.1, 0.2], [-1, 1]) + # len(weight) != len(pairs) + assert_raises(ValueError, firls, 11, [0.1, 0.2], [0, 0], weight=[1, 2]) + # negative weight + assert_raises(ValueError, firls, 11, [0.1, 0.2], [0, 0], weight=[-1]) + + def test_firls(self): + N = 11 # number of taps in the filter + a = 0.1 # width of the transition band + + # design a halfband symmetric low-pass filter + h = firls(11, [0, a, 0.5-a, 0.5], [1, 1, 0, 0], fs=1.0) + + # make sure the filter has correct # of taps + assert h.shape[0] == N + + # make sure it is symmetric + midx = (N-1) // 2 + assert_array_almost_equal(h[:midx], h[:-midx-1:-1]) + + # make sure the center tap is 0.5 + assert_almost_equal(h[midx], 0.5) + + # For halfband symmetric, odd coefficients (except the center) + # should be zero (really small) + hodd = np.hstack((h[1:midx:2], h[-midx+1::2])) + assert_array_almost_equal(hodd, np.zeros_like(hodd)) + + # now check the frequency response + w, H = freqz(h, 1) + f = w/2/np.pi + Hmag = np.abs(H) + + # check that the pass band is close to unity + idx = np.logical_and(f > 0, f < a) + assert_array_almost_equal(Hmag[idx], np.ones_like(Hmag[idx]), decimal=3) + + # check that the stop band is close to zero + idx = np.logical_and(f > 0.5-a, f < 0.5) + assert_array_almost_equal(Hmag[idx], np.zeros_like(Hmag[idx]), decimal=3) + + def test_compare(self): + # compare to OCTAVE output + taps = firls(9, [0, 0.5, 0.55, 1], [1, 1, 0, 0], weight=[1, 2]) + # >> taps = firls(8, [0 0.5 0.55 1], [1 1 0 0], [1, 2]); + known_taps = [-6.26930101730182e-04, -1.03354450635036e-01, + -9.81576747564301e-03, 3.17271686090449e-01, + 5.11409425599933e-01, 3.17271686090449e-01, + -9.81576747564301e-03, -1.03354450635036e-01, + -6.26930101730182e-04] + xp_assert_close(taps, known_taps) + + # compare to MATLAB output + taps = firls(11, [0, 0.5, 0.5, 1], [1, 1, 0, 0], weight=[1, 2]) + # >> taps = firls(10, [0 0.5 0.5 1], [1 1 0 0], [1, 2]); + known_taps = [ + 0.058545300496815, -0.014233383714318, -0.104688258464392, + 0.012403323025279, 0.317930861136062, 0.488047220029700, + 0.317930861136062, 0.012403323025279, -0.104688258464392, + -0.014233383714318, 0.058545300496815] + xp_assert_close(taps, known_taps) + + # With linear changes: + taps = firls(7, (0, 1, 2, 3, 4, 5), [1, 0, 0, 1, 1, 0], fs=20) + # >> taps = firls(6, [0, 0.1, 0.2, 0.3, 0.4, 0.5], [1, 0, 0, 1, 1, 0]) + known_taps = [ + 1.156090832768218, -4.1385894727395849, 7.5288619164321826, + -8.5530572592947856, 7.5288619164321826, -4.1385894727395849, + 1.156090832768218] + xp_assert_close(taps, known_taps) + + def test_rank_deficient(self): + # solve() runs but warns (only sometimes, so here we don't use match) + x = firls(21, [0, 0.1, 0.9, 1], [1, 1, 0, 0]) + w, h = freqz(x, fs=2.) + absh2 = np.abs(h[:2]) + xp_assert_close(absh2, np.ones_like(absh2), atol=1e-5) + absh2 = np.abs(h[-2:]) + xp_assert_close(absh2, np.zeros_like(absh2), atol=1e-6, rtol=1e-7) + # switch to pinvh (tolerances could be higher with longer + # filters, but using shorter ones is faster computationally and + # the idea is the same) + x = firls(101, [0, 0.01, 0.99, 1], [1, 1, 0, 0]) + w, h = freqz(x, fs=2.) + mask = w < 0.01 + assert mask.sum() > 3 + habs = np.abs(h[mask]) + xp_assert_close(habs, np.ones_like(habs), atol=1e-4) + mask = w > 0.99 + assert mask.sum() > 3 + habs = np.abs(h[mask]) + xp_assert_close(habs, np.zeros_like(habs), atol=1e-4) + + def test_fs_validation(self): + with pytest.raises(ValueError, match="Sampling.*single scalar"): + firls(11, .1, 1, fs=np.array([10, 20])) + +class TestMinimumPhase: + @pytest.mark.thread_unsafe + def test_bad_args(self): + # not enough taps + assert_raises(ValueError, minimum_phase, [1.]) + assert_raises(ValueError, minimum_phase, [1., 1.]) + assert_raises(ValueError, minimum_phase, np.full(10, 1j)) + assert_raises(ValueError, minimum_phase, 'foo') + assert_raises(ValueError, minimum_phase, np.ones(10), n_fft=8) + assert_raises(ValueError, minimum_phase, np.ones(10), method='foo') + assert_warns(RuntimeWarning, minimum_phase, np.arange(3)) + with pytest.raises(ValueError, match="is only supported when"): + minimum_phase(np.ones(3), method='hilbert', half=False) + + def test_homomorphic(self): + # check that it can recover frequency responses of arbitrary + # linear-phase filters + + # for some cases we can get the actual filter back + h = [1, -1] + h_new = minimum_phase(np.convolve(h, h[::-1])) + xp_assert_close(h_new, np.asarray(h, dtype=np.float64), rtol=0.05) + + # but in general we only guarantee we get the magnitude back + rng = np.random.RandomState(0) + for n in (2, 3, 10, 11, 15, 16, 17, 20, 21, 100, 101): + h = rng.randn(n) + h_linear = np.convolve(h, h[::-1]) + h_new = minimum_phase(h_linear) + xp_assert_close(np.abs(fft(h_new)), np.abs(fft(h)), rtol=1e-4) + h_new = minimum_phase(h_linear, half=False) + assert len(h_linear) == len(h_new) + xp_assert_close(np.abs(fft(h_new)), np.abs(fft(h_linear)), rtol=1e-4) + + def test_hilbert(self): + # compare to MATLAB output of reference implementation + + # f=[0 0.3 0.5 1]; + # a=[1 1 0 0]; + # h=remez(11,f,a); + h = remez(12, [0, 0.3, 0.5, 1], [1, 0], fs=2.) + k = [0.349585548646686, 0.373552164395447, 0.326082685363438, + 0.077152207480935, -0.129943946349364, -0.059355880509749] + m = minimum_phase(h, 'hilbert') + xp_assert_close(m, k, rtol=5e-3) + + # f=[0 0.8 0.9 1]; + # a=[0 0 1 1]; + # h=remez(20,f,a); + h = remez(21, [0, 0.8, 0.9, 1], [0, 1], fs=2.) + k = [0.232486803906329, -0.133551833687071, 0.151871456867244, + -0.157957283165866, 0.151739294892963, -0.129293146705090, + 0.100787844523204, -0.065832656741252, 0.035361328741024, + -0.014977068692269, -0.158416139047557] + m = minimum_phase(h, 'hilbert', n_fft=2**19) + xp_assert_close(m, k, rtol=2e-3) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_ltisys.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_ltisys.py new file mode 100644 index 0000000000000000000000000000000000000000..826b39cb0e066b3a6198bbcf1a293f6e0497076b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_ltisys.py @@ -0,0 +1,1225 @@ +import warnings + +import numpy as np +from numpy.testing import suppress_warnings +import pytest +from pytest import raises as assert_raises +from scipy._lib._array_api import( + assert_almost_equal, xp_assert_equal, xp_assert_close +) + +from scipy.signal import (ss2tf, tf2ss, lti, + dlti, bode, freqresp, lsim, impulse, step, + abcd_normalize, place_poles, + TransferFunction, StateSpace, ZerosPolesGain) +from scipy.signal._filter_design import BadCoefficients +import scipy.linalg as linalg + + +def _assert_poles_close(P1,P2, rtol=1e-8, atol=1e-8): + """ + Check each pole in P1 is close to a pole in P2 with a 1e-8 + relative tolerance or 1e-8 absolute tolerance (useful for zero poles). + These tolerances are very strict but the systems tested are known to + accept these poles so we should not be far from what is requested. + """ + P2 = P2.copy() + for p1 in P1: + found = False + for p2_idx in range(P2.shape[0]): + if np.allclose([np.real(p1), np.imag(p1)], + [np.real(P2[p2_idx]), np.imag(P2[p2_idx])], + rtol, atol): + found = True + np.delete(P2, p2_idx) + break + if not found: + raise ValueError("Can't find pole " + str(p1) + " in " + str(P2)) + + +class TestPlacePoles: + + def _check(self, A, B, P, **kwargs): + """ + Perform the most common tests on the poles computed by place_poles + and return the Bunch object for further specific tests + """ + fsf = place_poles(A, B, P, **kwargs) + expected, _ = np.linalg.eig(A - np.dot(B, fsf.gain_matrix)) + _assert_poles_close(expected, fsf.requested_poles) + _assert_poles_close(expected, fsf.computed_poles) + _assert_poles_close(P,fsf.requested_poles) + return fsf + + def test_real(self): + # Test real pole placement using KNV and YT0 algorithm and example 1 in + # section 4 of the reference publication (see place_poles docstring) + A = np.array([1.380, -0.2077, 6.715, -5.676, -0.5814, -4.290, 0, + 0.6750, 1.067, 4.273, -6.654, 5.893, 0.0480, 4.273, + 1.343, -2.104]).reshape(4, 4) + B = np.array([0, 5.679, 1.136, 1.136, 0, 0, -3.146,0]).reshape(4, 2) + P = np.array([-0.2, -0.5, -5.0566, -8.6659]) + + # Check that both KNV and YT compute correct K matrix + self._check(A, B, P, method='KNV0') + self._check(A, B, P, method='YT') + + # Try to reach the specific case in _YT_real where two singular + # values are almost equal. This is to improve code coverage but I + # have no way to be sure this code is really reached + + # on some architectures this can lead to a RuntimeWarning invalid + # value in divide (see gh-7590), so suppress it for now + with np.errstate(invalid='ignore'): + self._check(A, B, (2,2,3,3)) + + def test_complex(self): + # Test complex pole placement on a linearized car model, taken from L. + # Jaulin, Automatique pour la robotique, Cours et Exercices, iSTE + # editions p 184/185 + A = np.array([[0, 7, 0, 0], + [0, 0, 0, 7/3.], + [0, 0, 0, 0], + [0, 0, 0, 0]]) + B = np.array([[0, 0], + [0, 0], + [1, 0], + [0, 1]]) + # Test complex poles on YT + P = np.array([-3, -1, -2-1j, -2+1j]) + # on macOS arm64 this can lead to a RuntimeWarning invalid + # value in divide, so suppress it for now + with np.errstate(divide='ignore', invalid='ignore'): + self._check(A, B, P) + + # Try to reach the specific case in _YT_complex where two singular + # values are almost equal. This is to improve code coverage but I + # have no way to be sure this code is really reached + + P = [0-1e-6j,0+1e-6j,-10,10] + with np.errstate(divide='ignore', invalid='ignore'): + self._check(A, B, P, maxiter=1000) + + # Try to reach the specific case in _YT_complex where the rank two + # update yields two null vectors. This test was found via Monte Carlo. + + A = np.array( + [-2148,-2902, -2267, -598, -1722, -1829, -165, -283, -2546, + -167, -754, -2285, -543, -1700, -584, -2978, -925, -1300, + -1583, -984, -386, -2650, -764, -897, -517, -1598, 2, -1709, + -291, -338, -153, -1804, -1106, -1168, -867, -2297] + ).reshape(6,6) + + B = np.array( + [-108, -374, -524, -1285, -1232, -161, -1204, -672, -637, + -15, -483, -23, -931, -780, -1245, -1129, -1290, -1502, + -952, -1374, -62, -964, -930, -939, -792, -756, -1437, + -491, -1543, -686] + ).reshape(6,5) + P = [-25.-29.j, -25.+29.j, 31.-42.j, 31.+42.j, 33.-41.j, 33.+41.j] + self._check(A, B, P) + + # Use a lot of poles to go through all cases for update_order + # in _YT_loop + + big_A = np.ones((11,11))-np.eye(11) + big_B = np.ones((11,10))-np.diag([1]*10,1)[:,1:] + big_A[:6,:6] = A + big_B[:6,:5] = B + + P = [-10,-20,-30,40,50,60,70,-20-5j,-20+5j,5+3j,5-3j] + with np.errstate(divide='ignore', invalid='ignore'): + self._check(big_A, big_B, P) + + #check with only complex poles and only real poles + P = [-10,-20,-30,-40,-50,-60,-70,-80,-90,-100] + self._check(big_A[:-1,:-1], big_B[:-1,:-1], P) + P = [-10+10j,-20+20j,-30+30j,-40+40j,-50+50j, + -10-10j,-20-20j,-30-30j,-40-40j,-50-50j] + self._check(big_A[:-1,:-1], big_B[:-1,:-1], P) + + # need a 5x5 array to ensure YT handles properly when there + # is only one real pole and several complex + A = np.array([0,7,0,0,0,0,0,7/3.,0,0,0,0,0,0,0,0, + 0,0,0,5,0,0,0,0,9]).reshape(5,5) + B = np.array([0,0,0,0,1,0,0,1,2,3]).reshape(5,2) + P = np.array([-2, -3+1j, -3-1j, -1+1j, -1-1j]) + with np.errstate(divide='ignore', invalid='ignore'): + place_poles(A, B, P) + + # same test with an odd number of real poles > 1 + # this is another specific case of YT + P = np.array([-2, -3, -4, -1+1j, -1-1j]) + with np.errstate(divide='ignore', invalid='ignore'): + self._check(A, B, P) + + def test_tricky_B(self): + # check we handle as we should the 1 column B matrices and + # n column B matrices (with n such as shape(A)=(n, n)) + A = np.array([1.380, -0.2077, 6.715, -5.676, -0.5814, -4.290, 0, + 0.6750, 1.067, 4.273, -6.654, 5.893, 0.0480, 4.273, + 1.343, -2.104]).reshape(4, 4) + B = np.array([0, 5.679, 1.136, 1.136, 0, 0, -3.146, 0, 1, 2, 3, 4, + 5, 6, 7, 8]).reshape(4, 4) + + # KNV or YT are not called here, it's a specific case with only + # one unique solution + P = np.array([-0.2, -0.5, -5.0566, -8.6659]) + fsf = self._check(A, B, P) + # rtol and nb_iter should be set to np.nan as the identity can be + # used as transfer matrix + assert np.isnan(fsf.rtol) + assert np.isnan(fsf.nb_iter) + + # check with complex poles too as they trigger a specific case in + # the specific case :-) + P = np.array((-2+1j,-2-1j,-3,-2)) + fsf = self._check(A, B, P) + assert np.isnan(fsf.rtol) + assert np.isnan(fsf.nb_iter) + + #now test with a B matrix with only one column (no optimisation) + B = B[:,0].reshape(4,1) + P = np.array((-2+1j,-2-1j,-3,-2)) + fsf = self._check(A, B, P) + + # we can't optimize anything, check they are set to 0 as expected + assert fsf.rtol == 0 + assert fsf.nb_iter == 0 + + @pytest.mark.thread_unsafe + def test_errors(self): + # Test input mistakes from user + A = np.array([0,7,0,0,0,0,0,7/3.,0,0,0,0,0,0,0,0]).reshape(4,4) + B = np.array([0,0,0,0,1,0,0,1]).reshape(4,2) + + #should fail as the method keyword is invalid + assert_raises(ValueError, place_poles, A, B, (-2.1,-2.2,-2.3,-2.4), + method="foo") + + #should fail as poles are not 1D array + assert_raises(ValueError, place_poles, A, B, + np.array((-2.1,-2.2,-2.3,-2.4)).reshape(4,1)) + + #should fail as A is not a 2D array + assert_raises(ValueError, place_poles, A[:,:,np.newaxis], B, + (-2.1,-2.2,-2.3,-2.4)) + + #should fail as B is not a 2D array + assert_raises(ValueError, place_poles, A, B[:,:,np.newaxis], + (-2.1,-2.2,-2.3,-2.4)) + + #should fail as there are too many poles + assert_raises(ValueError, place_poles, A, B, (-2.1,-2.2,-2.3,-2.4,-3)) + + #should fail as there are not enough poles + assert_raises(ValueError, place_poles, A, B, (-2.1,-2.2,-2.3)) + + #should fail as the rtol is greater than 1 + assert_raises(ValueError, place_poles, A, B, (-2.1,-2.2,-2.3,-2.4), + rtol=42) + + #should fail as maxiter is smaller than 1 + assert_raises(ValueError, place_poles, A, B, (-2.1,-2.2,-2.3,-2.4), + maxiter=-42) + + # should fail as ndim(B) is two + assert_raises(ValueError, place_poles, A, B, (-2,-2,-2,-2)) + + # uncontrollable system + assert_raises(ValueError, place_poles, np.ones((4,4)), + np.ones((4,2)), (1,2,3,4)) + + # Should not raise ValueError as the poles can be placed but should + # raise a warning as the convergence is not reached + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + fsf = place_poles(A, B, (-1,-2,-3,-4), rtol=1e-16, maxiter=42) + assert len(w) == 1 + assert issubclass(w[-1].category, UserWarning) + assert ("Convergence was not reached after maxiter iterations" + in str(w[-1].message)) + assert fsf.nb_iter == 42 + + # should fail as a complex misses its conjugate + assert_raises(ValueError, place_poles, A, B, (-2+1j,-2-1j,-2+3j,-2)) + + # should fail as A is not square + assert_raises(ValueError, place_poles, A[:,:3], B, (-2,-3,-4,-5)) + + # should fail as B has not the same number of lines as A + assert_raises(ValueError, place_poles, A, B[:3,:], (-2,-3,-4,-5)) + + # should fail as KNV0 does not support complex poles + assert_raises(ValueError, place_poles, A, B, + (-2+1j,-2-1j,-2+3j,-2-3j), method="KNV0") + + +class TestSS2TF: + + def check_matrix_shapes(self, p, q, r): + ss2tf(np.zeros((p, p)), + np.zeros((p, q)), + np.zeros((r, p)), + np.zeros((r, q)), 0) + + def test_shapes(self): + # Each tuple holds: + # number of states, number of inputs, number of outputs + for p, q, r in [(3, 3, 3), (1, 3, 3), (1, 1, 1)]: + self.check_matrix_shapes(p, q, r) + + def test_basic(self): + # Test a round trip through tf2ss and ss2tf. + b = np.array([1.0, 3.0, 5.0]) + a = np.array([1.0, 2.0, 3.0]) + + A, B, C, D = tf2ss(b, a) + xp_assert_close(A, [[-2., -3], [1, 0]], rtol=1e-13) + xp_assert_close(B, [[1.], [0]], rtol=1e-13) + xp_assert_close(C, [[1., 2]], rtol=1e-13) + xp_assert_close(D, [[1.]], rtol=1e-14) + + bb, aa = ss2tf(A, B, C, D) + xp_assert_close(bb[0], b, rtol=1e-13) + xp_assert_close(aa, a, rtol=1e-13) + + def test_zero_order_round_trip(self): + # See gh-5760 + tf = (2, 1) + A, B, C, D = tf2ss(*tf) + xp_assert_close(A, [[0.]], rtol=1e-13) + xp_assert_close(B, [[0.]], rtol=1e-13) + xp_assert_close(C, [[0.]], rtol=1e-13) + xp_assert_close(D, [[2.]], rtol=1e-13) + + num, den = ss2tf(A, B, C, D) + xp_assert_close(num, [[2., 0]], rtol=1e-13) + xp_assert_close(den, [1., 0], rtol=1e-13) + + tf = ([[5], [2]], 1) + A, B, C, D = tf2ss(*tf) + xp_assert_close(A, [[0.]], rtol=1e-13) + xp_assert_close(B, [[0.]], rtol=1e-13) + xp_assert_close(C, [[0.], [0]], rtol=1e-13) + xp_assert_close(D, [[5.], [2]], rtol=1e-13) + + num, den = ss2tf(A, B, C, D) + xp_assert_close(num, [[5., 0], [2, 0]], rtol=1e-13) + xp_assert_close(den, [1., 0], rtol=1e-13) + + def test_simo_round_trip(self): + # See gh-5753 + tf = ([[1, 2], [1, 1]], [1, 2]) + A, B, C, D = tf2ss(*tf) + xp_assert_close(A, [[-2.]], rtol=1e-13) + xp_assert_close(B, [[1.]], rtol=1e-13) + xp_assert_close(C, [[0.], [-1.]], rtol=1e-13) + xp_assert_close(D, [[1.], [1.]], rtol=1e-13) + + num, den = ss2tf(A, B, C, D) + xp_assert_close(num, [[1., 2.], [1., 1.]], rtol=1e-13) + xp_assert_close(den, [1., 2.], rtol=1e-13) + + tf = ([[1, 0, 1], [1, 1, 1]], [1, 1, 1]) + A, B, C, D = tf2ss(*tf) + xp_assert_close(A, [[-1., -1.], [1., 0.]], rtol=1e-13) + xp_assert_close(B, [[1.], [0.]], rtol=1e-13) + xp_assert_close(C, [[-1., 0.], [0., 0.]], rtol=1e-13) + xp_assert_close(D, [[1.], [1.]], rtol=1e-13) + + num, den = ss2tf(A, B, C, D) + xp_assert_close(num, [[1., 0., 1.], [1., 1., 1.]], rtol=1e-13) + xp_assert_close(den, [1., 1., 1.], rtol=1e-13) + + tf = ([[1, 2, 3], [1, 2, 3]], [1, 2, 3, 4]) + A, B, C, D = tf2ss(*tf) + xp_assert_close(A, [[-2., -3, -4], [1, 0, 0], [0, 1, 0]], rtol=1e-13) + xp_assert_close(B, [[1.], [0], [0]], rtol=1e-13) + xp_assert_close(C, [[1., 2, 3], [1, 2, 3]], rtol=1e-13) + xp_assert_close(D, [[0.], [0]], rtol=1e-13) + + num, den = ss2tf(A, B, C, D) + xp_assert_close(num, [[0., 1, 2, 3], [0, 1, 2, 3]], rtol=1e-13) + xp_assert_close(den, [1., 2, 3, 4], rtol=1e-13) + + tf = (np.array([1, [2, 3]], dtype=object), [1, 6]) + A, B, C, D = tf2ss(*tf) + xp_assert_close(A, [[-6.]], rtol=1e-31) + xp_assert_close(B, [[1.]], rtol=1e-31) + xp_assert_close(C, [[1.], [-9]], rtol=1e-31) + xp_assert_close(D, [[0.], [2]], rtol=1e-31) + + num, den = ss2tf(A, B, C, D) + xp_assert_close(num, [[0., 1], [2, 3]], rtol=1e-13) + xp_assert_close(den, [1., 6], rtol=1e-13) + + tf = (np.array([[1, -3], [1, 2, 3]], dtype=object), [1, 6, 5]) + A, B, C, D = tf2ss(*tf) + xp_assert_close(A, [[-6., -5], [1, 0]], rtol=1e-13) + xp_assert_close(B, [[1.], [0]], rtol=1e-13) + xp_assert_close(C, [[1., -3], [-4, -2]], rtol=1e-13) + xp_assert_close(D, [[0.], [1]], rtol=1e-13) + + num, den = ss2tf(A, B, C, D) + xp_assert_close(num, [[0., 1, -3], [1, 2, 3]], rtol=1e-13) + xp_assert_close(den, [1., 6, 5], rtol=1e-13) + + def test_all_int_arrays(self): + A = [[0, 1, 0], [0, 0, 1], [-3, -4, -2]] + B = [[0], [0], [1]] + C = [[5, 1, 0]] + D = [[0]] + num, den = ss2tf(A, B, C, D) + xp_assert_close(num, [[0.0, 0.0, 1.0, 5.0]], rtol=1e-13, atol=1e-14) + xp_assert_close(den, [1.0, 2.0, 4.0, 3.0], rtol=1e-13) + + def test_multioutput(self): + # Regression test for gh-2669. + + # 4 states + A = np.array([[-1.0, 0.0, 1.0, 0.0], + [-1.0, 0.0, 2.0, 0.0], + [-4.0, 0.0, 3.0, 0.0], + [-8.0, 8.0, 0.0, 4.0]]) + + # 1 input + B = np.array([[0.3], + [0.0], + [7.0], + [0.0]]) + + # 3 outputs + C = np.array([[0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + [8.0, 8.0, 0.0, 0.0]]) + + D = np.array([[0.0], + [0.0], + [1.0]]) + + # Get the transfer functions for all the outputs in one call. + b_all, a = ss2tf(A, B, C, D) + + # Get the transfer functions for each output separately. + b0, a0 = ss2tf(A, B, C[0], D[0]) + b1, a1 = ss2tf(A, B, C[1], D[1]) + b2, a2 = ss2tf(A, B, C[2], D[2]) + + # Check that we got the same results. + xp_assert_close(a0, a, rtol=1e-13) + xp_assert_close(a1, a, rtol=1e-13) + xp_assert_close(a2, a, rtol=1e-13) + xp_assert_close(b_all, np.vstack((b0, b1, b2)), rtol=1e-13, atol=1e-14) + + +class TestLsim: + digits_accuracy = 7 + + def lti_nowarn(self, *args): + with suppress_warnings() as sup: + sup.filter(BadCoefficients) + system = lti(*args) + return system + + def test_first_order(self): + # y' = -y + # exact solution is y(t) = exp(-t) + system = self.lti_nowarn(-1.,1.,1.,0.) + t = np.linspace(0,5) + u = np.zeros_like(t) + tout, y, x = lsim(system, u, t, X0=[1.0]) + expected_x = np.exp(-tout) + assert_almost_equal(x, expected_x) + assert_almost_equal(y, expected_x) + + def test_second_order(self): + t = np.linspace(0, 10, 1001) + u = np.zeros_like(t) + # Second order system with a repeated root: x''(t) + 2*x(t) + x(t) = 0. + # With initial conditions x(0)=1.0 and x'(t)=0.0, the exact solution + # is (1-t)*exp(-t). + system = self.lti_nowarn([1.0], [1.0, 2.0, 1.0]) + tout, y, x = lsim(system, u, t, X0=[1.0, 0.0]) + expected_x = (1.0 - tout) * np.exp(-tout) + assert_almost_equal(x[:, 0], expected_x) + + def test_integrator(self): + # integrator: y' = u + system = self.lti_nowarn(0., 1., 1., 0.) + t = np.linspace(0,5) + u = t + tout, y, x = lsim(system, u, t) + expected_x = 0.5 * tout**2 + assert_almost_equal(x, expected_x, decimal=self.digits_accuracy) + assert_almost_equal(y, expected_x, decimal=self.digits_accuracy) + + def test_two_states(self): + # A system with two state variables, two inputs, and one output. + A = np.array([[-1.0, 0.0], [0.0, -2.0]]) + B = np.array([[1.0, 0.0], [0.0, 1.0]]) + C = np.array([1.0, 0.0]) + D = np.zeros((1, 2)) + + system = self.lti_nowarn(A, B, C, D) + + t = np.linspace(0, 10.0, 21) + u = np.zeros((len(t), 2)) + tout, y, x = lsim(system, U=u, T=t, X0=[1.0, 1.0]) + expected_y = np.exp(-tout) + expected_x0 = np.exp(-tout) + expected_x1 = np.exp(-2.0 * tout) + assert_almost_equal(y, expected_y) + assert_almost_equal(x[:, 0], expected_x0) + assert_almost_equal(x[:, 1], expected_x1) + + def test_double_integrator(self): + # double integrator: y'' = 2u + A = np.array([[0., 1.], [0., 0.]]) + B = np.array([[0.], [1.]]) + C = np.array([[2., 0.]]) + system = self.lti_nowarn(A, B, C, 0.) + t = np.linspace(0,5) + u = np.ones_like(t) + tout, y, x = lsim(system, u, t) + expected_x = np.transpose(np.array([0.5 * tout**2, tout])) + expected_y = tout**2 + assert_almost_equal(x, expected_x, decimal=self.digits_accuracy) + assert_almost_equal(y, expected_y, decimal=self.digits_accuracy) + + def test_jordan_block(self): + # Non-diagonalizable A matrix + # x1' + x1 = x2 + # x2' + x2 = u + # y = x1 + # Exact solution with u = 0 is y(t) = t exp(-t) + A = np.array([[-1., 1.], [0., -1.]]) + B = np.array([[0.], [1.]]) + C = np.array([[1., 0.]]) + system = self.lti_nowarn(A, B, C, 0.) + t = np.linspace(0,5) + u = np.zeros_like(t) + tout, y, x = lsim(system, u, t, X0=[0.0, 1.0]) + expected_y = tout * np.exp(-tout) + assert_almost_equal(y, expected_y) + + def test_miso(self): + # A system with two state variables, two inputs, and one output. + A = np.array([[-1.0, 0.0], [0.0, -2.0]]) + B = np.array([[1.0, 0.0], [0.0, 1.0]]) + C = np.array([1.0, 0.0]) + D = np.zeros((1,2)) + system = self.lti_nowarn(A, B, C, D) + + t = np.linspace(0, 5.0, 101) + u = np.zeros((len(t), 2)) + tout, y, x = lsim(system, u, t, X0=[1.0, 1.0]) + expected_y = np.exp(-tout) + expected_x0 = np.exp(-tout) + expected_x1 = np.exp(-2.0*tout) + assert_almost_equal(y, expected_y) + assert_almost_equal(x[:,0], expected_x0) + assert_almost_equal(x[:,1], expected_x1) + + def test_nonzero_initial_time(self): + system = self.lti_nowarn(-1.,1.,1.,0.) + t = np.linspace(1,2) + u = np.zeros_like(t) + tout, y, x = lsim(system, u, t, X0=[1.0]) + expected_y = np.exp(-tout) + assert_almost_equal(y, expected_y) + + def test_nonequal_timesteps(self): + t = np.array([0.0, 1.0, 1.0, 3.0]) + u = np.array([0.0, 0.0, 1.0, 1.0]) + # Simple integrator: x'(t) = u(t) + system = ([1.0], [1.0, 0.0]) + with assert_raises(ValueError, + match="Time steps are not equally spaced."): + tout, y, x = lsim(system, u, t, X0=[1.0]) + + +class TestImpulse: + def test_first_order(self): + # First order system: x'(t) + x(t) = u(t) + # Exact impulse response is x(t) = exp(-t). + system = ([1.0], [1.0,1.0]) + tout, y = impulse(system) + expected_y = np.exp(-tout) + assert_almost_equal(y, expected_y) + + def test_first_order_fixed_time(self): + # Specify the desired time values for the output. + + # First order system: x'(t) + x(t) = u(t) + # Exact impulse response is x(t) = exp(-t). + system = ([1.0], [1.0,1.0]) + n = 21 + t = np.linspace(0, 2.0, n) + tout, y = impulse(system, T=t) + assert tout.shape == (n,) + assert_almost_equal(tout, t) + expected_y = np.exp(-t) + assert_almost_equal(y, expected_y) + + def test_first_order_initial(self): + # Specify an initial condition as a scalar. + + # First order system: x'(t) + x(t) = u(t), x(0)=3.0 + # Exact impulse response is x(t) = 4*exp(-t). + system = ([1.0], [1.0,1.0]) + tout, y = impulse(system, X0=3.0) + expected_y = 4.0 * np.exp(-tout) + assert_almost_equal(y, expected_y) + + def test_first_order_initial_list(self): + # Specify an initial condition as a list. + + # First order system: x'(t) + x(t) = u(t), x(0)=3.0 + # Exact impulse response is x(t) = 4*exp(-t). + system = ([1.0], [1.0,1.0]) + tout, y = impulse(system, X0=[3.0]) + expected_y = 4.0 * np.exp(-tout) + assert_almost_equal(y, expected_y) + + def test_integrator(self): + # Simple integrator: x'(t) = u(t) + system = ([1.0], [1.0,0.0]) + tout, y = impulse(system) + expected_y = np.ones_like(tout) + assert_almost_equal(y, expected_y) + + def test_second_order(self): + # Second order system with a repeated root: + # x''(t) + 2*x(t) + x(t) = u(t) + # The exact impulse response is t*exp(-t). + system = ([1.0], [1.0, 2.0, 1.0]) + tout, y = impulse(system) + expected_y = tout * np.exp(-tout) + assert_almost_equal(y, expected_y) + + def test_array_like(self): + # Test that function can accept sequences, scalars. + system = ([1.0], [1.0, 2.0, 1.0]) + # TODO: add meaningful test where X0 is a list + tout, y = impulse(system, X0=[3], T=[5, 6]) + tout, y = impulse(system, X0=[3], T=[5]) + + def test_array_like2(self): + system = ([1.0], [1.0, 2.0, 1.0]) + tout, y = impulse(system, X0=3, T=5) + + +class TestStep: + def test_first_order(self): + # First order system: x'(t) + x(t) = u(t) + # Exact step response is x(t) = 1 - exp(-t). + system = ([1.0], [1.0,1.0]) + tout, y = step(system) + expected_y = 1.0 - np.exp(-tout) + assert_almost_equal(y, expected_y) + + def test_first_order_fixed_time(self): + # Specify the desired time values for the output. + + # First order system: x'(t) + x(t) = u(t) + # Exact step response is x(t) = 1 - exp(-t). + system = ([1.0], [1.0,1.0]) + n = 21 + t = np.linspace(0, 2.0, n) + tout, y = step(system, T=t) + assert tout.shape == (n,) + assert_almost_equal(tout, t) + expected_y = 1 - np.exp(-t) + assert_almost_equal(y, expected_y) + + def test_first_order_initial(self): + # Specify an initial condition as a scalar. + + # First order system: x'(t) + x(t) = u(t), x(0)=3.0 + # Exact step response is x(t) = 1 + 2*exp(-t). + system = ([1.0], [1.0,1.0]) + tout, y = step(system, X0=3.0) + expected_y = 1 + 2.0*np.exp(-tout) + assert_almost_equal(y, expected_y) + + def test_first_order_initial_list(self): + # Specify an initial condition as a list. + + # First order system: x'(t) + x(t) = u(t), x(0)=3.0 + # Exact step response is x(t) = 1 + 2*exp(-t). + system = ([1.0], [1.0,1.0]) + tout, y = step(system, X0=[3.0]) + expected_y = 1 + 2.0*np.exp(-tout) + assert_almost_equal(y, expected_y) + + def test_integrator(self): + # Simple integrator: x'(t) = u(t) + # Exact step response is x(t) = t. + system = ([1.0],[1.0,0.0]) + tout, y = step(system) + expected_y = tout + assert_almost_equal(y, expected_y) + + def test_second_order(self): + # Second order system with a repeated root: + # x''(t) + 2*x(t) + x(t) = u(t) + # The exact step response is 1 - (1 + t)*exp(-t). + system = ([1.0], [1.0, 2.0, 1.0]) + tout, y = step(system) + expected_y = 1 - (1 + tout) * np.exp(-tout) + assert_almost_equal(y, expected_y) + + def test_array_like(self): + # Test that function can accept sequences, scalars. + system = ([1.0], [1.0, 2.0, 1.0]) + # TODO: add meaningful test where X0 is a list + tout, y = step(system, T=[5, 6]) + + def test_complex_input(self): + # Test that complex input doesn't raise an error. + # `step` doesn't seem to have been designed for complex input, but this + # works and may be used, so add regression test. See gh-2654. + step(([], [-1], 1+0j)) + + +class TestLti: + def test_lti_instantiation(self): + # Test that lti can be instantiated with sequences, scalars. + # See PR-225. + + # TransferFunction + s = lti([1], [-1]) + assert isinstance(s, TransferFunction) + assert isinstance(s, lti) + assert not isinstance(s, dlti) + assert s.dt is None + + # ZerosPolesGain + s = lti(np.array([]), np.array([-1]), 1) + assert isinstance(s, ZerosPolesGain) + assert isinstance(s, lti) + assert not isinstance(s, dlti) + assert s.dt is None + + # StateSpace + s = lti([], [-1], 1) + s = lti([1], [-1], 1, 3) + assert isinstance(s, StateSpace) + assert isinstance(s, lti) + assert not isinstance(s, dlti) + assert s.dt is None + + +class TestStateSpace: + def test_initialization(self): + # Check that all initializations work + StateSpace(1, 1, 1, 1) + StateSpace([1], [2], [3], [4]) + StateSpace(np.array([[1, 2], [3, 4]]), np.array([[1], [2]]), + np.array([[1, 0]]), np.array([[0]])) + + def test_conversion(self): + # Check the conversion functions + s = StateSpace(1, 2, 3, 4) + assert isinstance(s.to_ss(), StateSpace) + assert isinstance(s.to_tf(), TransferFunction) + assert isinstance(s.to_zpk(), ZerosPolesGain) + + # Make sure copies work + assert StateSpace(s) is not s + assert s.to_ss() is not s + + def test_properties(self): + # Test setters/getters for cross class properties. + # This implicitly tests to_tf() and to_zpk() + + # Getters + s = StateSpace(1, 1, 1, 1) + xp_assert_equal(s.poles, [1.]) + xp_assert_equal(s.zeros, [0.]) + assert s.dt is None + + def test_operators(self): + # Test +/-/* operators on systems + + class BadType: + pass + + s1 = StateSpace(np.array([[-0.5, 0.7], [0.3, -0.8]]), + np.array([[1], [0]]), + np.array([[1, 0]]), + np.array([[0]]), + ) + + s2 = StateSpace(np.array([[-0.2, -0.1], [0.4, -0.1]]), + np.array([[1], [0]]), + np.array([[1, 0]]), + np.array([[0]]) + ) + + s_discrete = s1.to_discrete(0.1) + s2_discrete = s2.to_discrete(0.2) + s3_discrete = s2.to_discrete(0.1) + + # Impulse response + t = np.linspace(0, 1, 100) + u = np.zeros_like(t) + u[0] = 1 + + # Test multiplication + for typ in (int, float, complex, np.float32, np.complex128, np.array): + xp_assert_close(lsim(typ(2) * s1, U=u, T=t)[1], + typ(2) * lsim(s1, U=u, T=t)[1]) + + xp_assert_close(lsim(s1 * typ(2), U=u, T=t)[1], + lsim(s1, U=u, T=t)[1] * typ(2)) + + xp_assert_close(lsim(s1 / typ(2), U=u, T=t)[1], + lsim(s1, U=u, T=t)[1] / typ(2)) + + with assert_raises(TypeError): + typ(2) / s1 + + xp_assert_close(lsim(s1 * 2, U=u, T=t)[1], + lsim(s1, U=2 * u, T=t)[1]) + + xp_assert_close(lsim(s1 * s2, U=u, T=t)[1], + lsim(s1, U=lsim(s2, U=u, T=t)[1], T=t)[1], + atol=1e-5) + + with assert_raises(TypeError): + s1 / s1 + + with assert_raises(TypeError): + s1 * s_discrete + + with assert_raises(TypeError): + # Check different discretization constants + s_discrete * s2_discrete + + with assert_raises(TypeError): + s1 * BadType() + + with assert_raises(TypeError): + BadType() * s1 + + with assert_raises(TypeError): + s1 / BadType() + + with assert_raises(TypeError): + BadType() / s1 + + # Test addition + xp_assert_close(lsim(s1 + 2, U=u, T=t)[1], + 2 * u + lsim(s1, U=u, T=t)[1]) + + # Check for dimension mismatch + with assert_raises(ValueError): + s1 + np.array([1, 2]) + + with assert_raises(ValueError): + np.array([1, 2]) + s1 + + with assert_raises(TypeError): + s1 + s_discrete + + with assert_raises(ValueError): + s1 / np.array([[1, 2], [3, 4]]) + + with assert_raises(TypeError): + # Check different discretization constants + s_discrete + s2_discrete + + with assert_raises(TypeError): + s1 + BadType() + + with assert_raises(TypeError): + BadType() + s1 + + xp_assert_close(lsim(s1 + s2, U=u, T=t)[1], + lsim(s1, U=u, T=t)[1] + lsim(s2, U=u, T=t)[1]) + + # Test subtraction + xp_assert_close(lsim(s1 - 2, U=u, T=t)[1], + -2 * u + lsim(s1, U=u, T=t)[1]) + + xp_assert_close(lsim(2 - s1, U=u, T=t)[1], + 2 * u + lsim(-s1, U=u, T=t)[1]) + + xp_assert_close(lsim(s1 - s2, U=u, T=t)[1], + lsim(s1, U=u, T=t)[1] - lsim(s2, U=u, T=t)[1]) + + with assert_raises(TypeError): + s1 - BadType() + + with assert_raises(TypeError): + BadType() - s1 + + s = s_discrete + s3_discrete + assert s.dt == 0.1 + + s = s_discrete * s3_discrete + assert s.dt == 0.1 + + s = 3 * s_discrete + assert s.dt == 0.1 + + s = -s_discrete + assert s.dt == 0.1 + +class TestTransferFunction: + def test_initialization(self): + # Check that all initializations work + TransferFunction(1, 1) + TransferFunction([1], [2]) + TransferFunction(np.array([1]), np.array([2])) + + def test_conversion(self): + # Check the conversion functions + s = TransferFunction([1, 0], [1, -1]) + assert isinstance(s.to_ss(), StateSpace) + assert isinstance(s.to_tf(), TransferFunction) + assert isinstance(s.to_zpk(), ZerosPolesGain) + + # Make sure copies work + assert TransferFunction(s) is not s + assert s.to_tf() is not s + + def test_properties(self): + # Test setters/getters for cross class properties. + # This implicitly tests to_ss() and to_zpk() + + # Getters + s = TransferFunction([1, 0], [1, -1]) + xp_assert_equal(s.poles, [1.]) + xp_assert_equal(s.zeros, [0.]) + + +class TestZerosPolesGain: + def test_initialization(self): + # Check that all initializations work + ZerosPolesGain(1, 1, 1) + ZerosPolesGain([1], [2], 1) + ZerosPolesGain(np.array([1]), np.array([2]), 1) + + def test_conversion(self): + #Check the conversion functions + s = ZerosPolesGain(1, 2, 3) + assert isinstance(s.to_ss(), StateSpace) + assert isinstance(s.to_tf(), TransferFunction) + assert isinstance(s.to_zpk(), ZerosPolesGain) + + # Make sure copies work + assert ZerosPolesGain(s) is not s + assert s.to_zpk() is not s + + +class Test_abcd_normalize: + def setup_method(self): + self.A = np.array([[1.0, 2.0], [3.0, 4.0]]) + self.B = np.array([[-1.0], [5.0]]) + self.C = np.array([[4.0, 5.0]]) + self.D = np.array([[2.5]]) + + def test_no_matrix_fails(self): + assert_raises(ValueError, abcd_normalize) + + def test_A_nosquare_fails(self): + assert_raises(ValueError, abcd_normalize, [1, -1], + self.B, self.C, self.D) + + def test_AB_mismatch_fails(self): + assert_raises(ValueError, abcd_normalize, self.A, [-1, 5], + self.C, self.D) + + def test_AC_mismatch_fails(self): + assert_raises(ValueError, abcd_normalize, self.A, self.B, + [[4.0], [5.0]], self.D) + + def test_CD_mismatch_fails(self): + assert_raises(ValueError, abcd_normalize, self.A, self.B, + self.C, [2.5, 0]) + + def test_BD_mismatch_fails(self): + assert_raises(ValueError, abcd_normalize, self.A, [-1, 5], + self.C, self.D) + + def test_normalized_matrices_unchanged(self): + A, B, C, D = abcd_normalize(self.A, self.B, self.C, self.D) + xp_assert_equal(A, self.A) + xp_assert_equal(B, self.B) + xp_assert_equal(C, self.C) + xp_assert_equal(D, self.D) + + def test_shapes(self): + A, B, C, D = abcd_normalize(self.A, self.B, [1, 0], 0) + xp_assert_equal(A.shape[0], A.shape[1]) + xp_assert_equal(A.shape[0], B.shape[0]) + xp_assert_equal(A.shape[0], C.shape[1]) + xp_assert_equal(C.shape[0], D.shape[0]) + xp_assert_equal(B.shape[1], D.shape[1]) + + def test_zero_dimension_is_not_none1(self): + B_ = np.zeros((2, 0)) + D_ = np.zeros((0, 0)) + A, B, C, D = abcd_normalize(A=self.A, B=B_, D=D_) + xp_assert_equal(A, self.A) + xp_assert_equal(B, B_) + xp_assert_equal(D, D_) + assert C.shape[0] == D_.shape[0] + assert C.shape[1] == self.A.shape[0] + + def test_zero_dimension_is_not_none2(self): + B_ = np.zeros((2, 0)) + C_ = np.zeros((0, 2)) + A, B, C, D = abcd_normalize(A=self.A, B=B_, C=C_) + xp_assert_equal(A, self.A) + xp_assert_equal(B, B_) + xp_assert_equal(C, C_) + assert D.shape[0] == C_.shape[0] + assert D.shape[1] == B_.shape[1] + + def test_missing_A(self): + A, B, C, D = abcd_normalize(B=self.B, C=self.C, D=self.D) + assert A.shape[0] == A.shape[1] + assert A.shape[0] == B.shape[0] + assert A.shape == (self.B.shape[0], self.B.shape[0]) + + def test_missing_B(self): + A, B, C, D = abcd_normalize(A=self.A, C=self.C, D=self.D) + assert B.shape[0] == A.shape[0] + assert B.shape[1] == D.shape[1] + assert B.shape == (self.A.shape[0], self.D.shape[1]) + + def test_missing_C(self): + A, B, C, D = abcd_normalize(A=self.A, B=self.B, D=self.D) + assert C.shape[0] == D.shape[0] + assert C.shape[1] == A.shape[0] + assert C.shape == (self.D.shape[0], self.A.shape[0]) + + def test_missing_D(self): + A, B, C, D = abcd_normalize(A=self.A, B=self.B, C=self.C) + assert D.shape[0] == C.shape[0] + assert D.shape[1] == B.shape[1] + assert D.shape == (self.C.shape[0], self.B.shape[1]) + + def test_missing_AB(self): + A, B, C, D = abcd_normalize(C=self.C, D=self.D) + assert A.shape[0] == A.shape[1] + assert A.shape[0] == B.shape[0] + assert B.shape[1] == D.shape[1] + assert A.shape == (self.C.shape[1], self.C.shape[1]) + assert B.shape == (self.C.shape[1], self.D.shape[1]) + + def test_missing_AC(self): + A, B, C, D = abcd_normalize(B=self.B, D=self.D) + assert A.shape[0] == A.shape[1] + assert A.shape[0] == B.shape[0] + assert C.shape[0] == D.shape[0] + assert C.shape[1] == A.shape[0] + assert A.shape == (self.B.shape[0], self.B.shape[0]) + assert C.shape == (self.D.shape[0], self.B.shape[0]) + + def test_missing_AD(self): + A, B, C, D = abcd_normalize(B=self.B, C=self.C) + assert A.shape[0] == A.shape[1] + assert A.shape[0] == B.shape[0] + assert D.shape[0] == C.shape[0] + assert D.shape[1] == B.shape[1] + assert A.shape == (self.B.shape[0], self.B.shape[0]) + assert D.shape == (self.C.shape[0], self.B.shape[1]) + + def test_missing_BC(self): + A, B, C, D = abcd_normalize(A=self.A, D=self.D) + assert B.shape[0] == A.shape[0] + assert B.shape[1] == D.shape[1] + assert C.shape[0] == D.shape[0] + assert C.shape[1], A.shape[0] + assert B.shape == (self.A.shape[0], self.D.shape[1]) + assert C.shape == (self.D.shape[0], self.A.shape[0]) + + def test_missing_ABC_fails(self): + assert_raises(ValueError, abcd_normalize, D=self.D) + + def test_missing_BD_fails(self): + assert_raises(ValueError, abcd_normalize, A=self.A, C=self.C) + + def test_missing_CD_fails(self): + assert_raises(ValueError, abcd_normalize, A=self.A, B=self.B) + + +class Test_bode: + + def test_01(self): + # Test bode() magnitude calculation (manual sanity check). + # 1st order low-pass filter: H(s) = 1 / (s + 1), + # cutoff: 1 rad/s, slope: -20 dB/decade + # H(s=0.1) ~= 0 dB + # H(s=1) ~= -3 dB + # H(s=10) ~= -20 dB + # H(s=100) ~= -40 dB + system = lti([1], [1, 1]) + w = [0.1, 1, 10, 100] + w, mag, phase = bode(system, w=w) + expected_mag = [0, -3, -20, -40] + assert_almost_equal(mag, expected_mag, decimal=1) + + def test_02(self): + # Test bode() phase calculation (manual sanity check). + # 1st order low-pass filter: H(s) = 1 / (s + 1), + # angle(H(s=0.1)) ~= -5.7 deg + # angle(H(s=1)) ~= -45 deg + # angle(H(s=10)) ~= -84.3 deg + system = lti([1], [1, 1]) + w = [0.1, 1, 10] + w, mag, phase = bode(system, w=w) + expected_phase = [-5.7, -45, -84.3] + assert_almost_equal(phase, expected_phase, decimal=1) + + def test_03(self): + # Test bode() magnitude calculation. + # 1st order low-pass filter: H(s) = 1 / (s + 1) + system = lti([1], [1, 1]) + w = [0.1, 1, 10, 100] + w, mag, phase = bode(system, w=w) + jw = w * 1j + y = np.polyval(system.num, jw) / np.polyval(system.den, jw) + expected_mag = 20.0 * np.log10(abs(y)) + assert_almost_equal(mag, expected_mag) + + def test_04(self): + # Test bode() phase calculation. + # 1st order low-pass filter: H(s) = 1 / (s + 1) + system = lti([1], [1, 1]) + w = [0.1, 1, 10, 100] + w, mag, phase = bode(system, w=w) + jw = w * 1j + y = np.polyval(system.num, jw) / np.polyval(system.den, jw) + expected_phase = np.arctan2(y.imag, y.real) * 180.0 / np.pi + assert_almost_equal(phase, expected_phase) + + def test_05(self): + # Test that bode() finds a reasonable frequency range. + # 1st order low-pass filter: H(s) = 1 / (s + 1) + system = lti([1], [1, 1]) + n = 10 + # Expected range is from 0.01 to 10. + expected_w = np.logspace(-2, 1, n) + w, mag, phase = bode(system, n=n) + assert_almost_equal(w, expected_w) + + def test_06(self): + # Test that bode() doesn't fail on a system with a pole at 0. + # integrator, pole at zero: H(s) = 1 / s + system = lti([1], [1, 0]) + w, mag, phase = bode(system, n=2) + assert w[0] == 0.01 # a fail would give not-a-number + + def test_07(self): + # bode() should not fail on a system with pure imaginary poles. + # The test passes if bode doesn't raise an exception. + system = lti([1], [1, 0, 100]) + w, mag, phase = bode(system, n=2) + + def test_08(self): + # Test that bode() return continuous phase, issues/2331. + system = lti([], [-10, -30, -40, -60, -70], 1) + w, mag, phase = system.bode(w=np.logspace(-3, 40, 100)) + assert_almost_equal(min(phase), -450, decimal=15) + + def test_from_state_space(self): + # Ensure that bode works with a system that was created from the + # state space representation matrices A, B, C, D. In this case, + # system.num will be a 2-D array with shape (1, n+1), where (n,n) + # is the shape of A. + # A Butterworth lowpass filter is used, so we know the exact + # frequency response. + a = np.array([1.0, 2.0, 2.0, 1.0]) + A = linalg.companion(a).T + B = np.array([[0.0], [0.0], [1.0]]) + C = np.array([[1.0, 0.0, 0.0]]) + D = np.array([[0.0]]) + with suppress_warnings() as sup: + sup.filter(BadCoefficients) + system = lti(A, B, C, D) + w, mag, phase = bode(system, n=100) + + expected_magnitude = 20 * np.log10(np.sqrt(1.0 / (1.0 + w**6))) + assert_almost_equal(mag, expected_magnitude) + + +class Test_freqresp: + + def test_output_manual(self): + # Test freqresp() output calculation (manual sanity check). + # 1st order low-pass filter: H(s) = 1 / (s + 1), + # re(H(s=0.1)) ~= 0.99 + # re(H(s=1)) ~= 0.5 + # re(H(s=10)) ~= 0.0099 + system = lti([1], [1, 1]) + w = [0.1, 1, 10] + w, H = freqresp(system, w=w) + expected_re = [0.99, 0.5, 0.0099] + expected_im = [-0.099, -0.5, -0.099] + assert_almost_equal(H.real, expected_re, decimal=1) + assert_almost_equal(H.imag, expected_im, decimal=1) + + def test_output(self): + # Test freqresp() output calculation. + # 1st order low-pass filter: H(s) = 1 / (s + 1) + system = lti([1], [1, 1]) + w = [0.1, 1, 10, 100] + w, H = freqresp(system, w=w) + s = w * 1j + expected = np.polyval(system.num, s) / np.polyval(system.den, s) + assert_almost_equal(H.real, expected.real) + assert_almost_equal(H.imag, expected.imag) + + def test_freq_range(self): + # Test that freqresp() finds a reasonable frequency range. + # 1st order low-pass filter: H(s) = 1 / (s + 1) + # Expected range is from 0.01 to 10. + system = lti([1], [1, 1]) + n = 10 + expected_w = np.logspace(-2, 1, n) + w, H = freqresp(system, n=n) + assert_almost_equal(w, expected_w) + + def test_pole_zero(self): + # Test that freqresp() doesn't fail on a system with a pole at 0. + # integrator, pole at zero: H(s) = 1 / s + system = lti([1], [1, 0]) + w, H = freqresp(system, n=2) + assert w[0] == 0.01 # a fail would give not-a-number + + def test_from_state_space(self): + # Ensure that freqresp works with a system that was created from the + # state space representation matrices A, B, C, D. In this case, + # system.num will be a 2-D array with shape (1, n+1), where (n,n) is + # the shape of A. + # A Butterworth lowpass filter is used, so we know the exact + # frequency response. + a = np.array([1.0, 2.0, 2.0, 1.0]) + A = linalg.companion(a).T + B = np.array([[0.0],[0.0],[1.0]]) + C = np.array([[1.0, 0.0, 0.0]]) + D = np.array([[0.0]]) + with suppress_warnings() as sup: + sup.filter(BadCoefficients) + system = lti(A, B, C, D) + w, H = freqresp(system, n=100) + s = w * 1j + expected = (1.0 / (1.0 + 2*s + 2*s**2 + s**3)) + assert_almost_equal(H.real, expected.real) + assert_almost_equal(H.imag, expected.imag) + + def test_from_zpk(self): + # 4th order low-pass filter: H(s) = 1 / (s + 1) + system = lti([],[-1]*4,[1]) + w = [0.1, 1, 10, 100] + w, H = freqresp(system, w=w) + s = w * 1j + expected = 1 / (s + 1)**4 + assert_almost_equal(H.real, expected.real) + assert_almost_equal(H.imag, expected.imag) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_max_len_seq.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_max_len_seq.py new file mode 100644 index 0000000000000000000000000000000000000000..7610b3f898571d10d75a64f00d900168c7142fbe --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_max_len_seq.py @@ -0,0 +1,71 @@ +import numpy as np +from pytest import raises as assert_raises +from scipy._lib._array_api import xp_assert_close, xp_assert_equal + +from numpy.fft import fft, ifft + +from scipy.signal import max_len_seq + + +class TestMLS: + + def test_mls_inputs(self): + # can't all be zero state + assert_raises(ValueError, max_len_seq, + 10, state=np.zeros(10)) + # wrong size state + assert_raises(ValueError, max_len_seq, 10, + state=np.ones(3)) + # wrong length + assert_raises(ValueError, max_len_seq, 10, length=-1) + xp_assert_equal(max_len_seq(10, length=0)[0], + np.asarray([], dtype=np.int8) + ) + # unknown taps + assert_raises(ValueError, max_len_seq, 64) + # bad taps + assert_raises(ValueError, max_len_seq, 10, taps=[-1, 1]) + + def test_mls_output(self): + # define some alternate working taps + alt_taps = {2: [1], 3: [2], 4: [3], 5: [4, 3, 2], 6: [5, 4, 1], 7: [4], + 8: [7, 5, 3]} + # assume the other bit levels work, too slow to test higher orders... + for nbits in range(2, 8): + for state in [None, np.round(np.random.rand(nbits))]: + for taps in [None, alt_taps[nbits]]: + if state is not None and np.all(state == 0): + state[0] = 1 # they can't all be zero + orig_m = max_len_seq(nbits, state=state, + taps=taps)[0] + m = 2. * orig_m - 1. # convert to +/- 1 representation + # First, make sure we got all 1's or -1 + err_msg = "mls had non binary terms" + xp_assert_equal(np.abs(m), np.ones_like(m), + err_msg=err_msg) + # Test via circular cross-correlation, which is just mult. + # in the frequency domain with one signal conjugated + tester = np.real(ifft(fft(m) * np.conj(fft(m)))) + out_len = 2**nbits - 1 + # impulse amplitude == test_len + err_msg = "mls impulse has incorrect value" + xp_assert_close(tester[0], + float(out_len), + err_msg=err_msg + ) + # steady-state is -1 + err_msg = "mls steady-state has incorrect value" + xp_assert_close(tester[1:], + np.full(out_len - 1, -1, dtype=tester.dtype), + err_msg=err_msg) + # let's do the split thing using a couple options + for n in (1, 2**(nbits - 1)): + m1, s1 = max_len_seq(nbits, state=state, taps=taps, + length=n) + m2, s2 = max_len_seq(nbits, state=s1, taps=taps, + length=1) + m3, s3 = max_len_seq(nbits, state=s2, taps=taps, + length=out_len - n - 1) + new_m = np.concatenate((m1, m2, m3)) + xp_assert_equal(orig_m, new_m) + diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_peak_finding.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_peak_finding.py new file mode 100644 index 0000000000000000000000000000000000000000..8de5a2379c2d43c0a10b5b3facd0b33be0778a36 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_peak_finding.py @@ -0,0 +1,915 @@ +import copy + +import numpy as np +import pytest +from pytest import raises, warns +from scipy._lib._array_api import xp_assert_close, xp_assert_equal + +from scipy.signal._peak_finding import ( + argrelmax, + argrelmin, + peak_prominences, + peak_widths, + _unpack_condition_args, + find_peaks, + find_peaks_cwt, + _identify_ridge_lines +) +from scipy.signal.windows import gaussian +from scipy.signal._peak_finding_utils import _local_maxima_1d, PeakPropertyWarning + + +def _gen_gaussians(center_locs, sigmas, total_length): + xdata = np.arange(0, total_length).astype(float) + out_data = np.zeros(total_length, dtype=float) + for ind, sigma in enumerate(sigmas): + tmp = (xdata - center_locs[ind]) / sigma + out_data += np.exp(-(tmp**2)) + return out_data + + +def _gen_gaussians_even(sigmas, total_length): + num_peaks = len(sigmas) + delta = total_length / (num_peaks + 1) + center_locs = np.linspace(delta, total_length - delta, num=num_peaks).astype(int) + out_data = _gen_gaussians(center_locs, sigmas, total_length) + return out_data, center_locs + + +def _gen_ridge_line(start_locs, max_locs, length, distances, gaps): + """ + Generate coordinates for a ridge line. + + Will be a series of coordinates, starting a start_loc (length 2). + The maximum distance between any adjacent columns will be + `max_distance`, the max distance between adjacent rows + will be `map_gap'. + + `max_locs` should be the size of the intended matrix. The + ending coordinates are guaranteed to be less than `max_locs`, + although they may not approach `max_locs` at all. + """ + + def keep_bounds(num, max_val): + out = max(num, 0) + out = min(out, max_val) + return out + + gaps = copy.deepcopy(gaps) + distances = copy.deepcopy(distances) + + locs = np.zeros([length, 2], dtype=int) + locs[0, :] = start_locs + total_length = max_locs[0] - start_locs[0] - sum(gaps) + if total_length < length: + raise ValueError('Cannot generate ridge line according to constraints') + dist_int = length / len(distances) - 1 + gap_int = length / len(gaps) - 1 + for ind in range(1, length): + nextcol = locs[ind - 1, 1] + nextrow = locs[ind - 1, 0] + 1 + if (ind % dist_int == 0) and (len(distances) > 0): + nextcol += ((-1)**ind)*distances.pop() + if (ind % gap_int == 0) and (len(gaps) > 0): + nextrow += gaps.pop() + nextrow = keep_bounds(nextrow, max_locs[0]) + nextcol = keep_bounds(nextcol, max_locs[1]) + locs[ind, :] = [nextrow, nextcol] + + return [locs[:, 0], locs[:, 1]] + + +class TestLocalMaxima1d: + + def test_empty(self): + """Test with empty signal.""" + x = np.array([], dtype=np.float64) + for array in _local_maxima_1d(x): + xp_assert_equal(array, np.array([]), check_dtype=False) + assert array.base is None + + def test_linear(self): + """Test with linear signal.""" + x = np.linspace(0, 100) + for array in _local_maxima_1d(x): + xp_assert_equal(array, np.array([], dtype=np.intp)) + assert array.base is None + + def test_simple(self): + """Test with simple signal.""" + x = np.linspace(-10, 10, 50) + x[2::3] += 1 + expected = np.arange(2, 50, 3, dtype=np.intp) + for array in _local_maxima_1d(x): + # For plateaus of size 1, the edges are identical with the + # midpoints + xp_assert_equal(array, expected, check_dtype=False) + assert array.base is None + + def test_flat_maxima(self): + """Test if flat maxima are detected correctly.""" + x = np.array([-1.3, 0, 1, 0, 2, 2, 0, 3, 3, 3, 2.99, 4, 4, 4, 4, -10, + -5, -5, -5, -5, -5, -10]) + midpoints, left_edges, right_edges = _local_maxima_1d(x) + xp_assert_equal(midpoints, np.array([2, 4, 8, 12, 18]), check_dtype=False) + xp_assert_equal(left_edges, np.array([2, 4, 7, 11, 16]), check_dtype=False) + xp_assert_equal(right_edges, np.array([2, 5, 9, 14, 20]), check_dtype=False) + + @pytest.mark.parametrize('x', [ + np.array([1., 0, 2]), + np.array([3., 3, 0, 4, 4]), + np.array([5., 5, 5, 0, 6, 6, 6]), + ]) + def test_signal_edges(self, x): + """Test if behavior on signal edges is correct.""" + for array in _local_maxima_1d(x): + xp_assert_equal(array, np.array([], dtype=np.intp)) + assert array.base is None + + def test_exceptions(self): + """Test input validation and raised exceptions.""" + with raises(ValueError, match="wrong number of dimensions"): + _local_maxima_1d(np.ones((1, 1))) + with raises(ValueError, match="expected 'const float64_t'"): + _local_maxima_1d(np.ones(1, dtype=int)) + with raises(TypeError, match="list"): + _local_maxima_1d([1., 2.]) + with raises(TypeError, match="'x' must not be None"): + _local_maxima_1d(None) + + +class TestRidgeLines: + + def test_empty(self): + test_matr = np.zeros([20, 100]) + lines = _identify_ridge_lines(test_matr, np.full(20, 2), 1) + assert len(lines) == 0 + + def test_minimal(self): + test_matr = np.zeros([20, 100]) + test_matr[0, 10] = 1 + lines = _identify_ridge_lines(test_matr, np.full(20, 2), 1) + assert len(lines) == 1 + + test_matr = np.zeros([20, 100]) + test_matr[0:2, 10] = 1 + lines = _identify_ridge_lines(test_matr, np.full(20, 2), 1) + assert len(lines) == 1 + + def test_single_pass(self): + distances = [0, 1, 2, 5] + gaps = [0, 1, 2, 0, 1] + test_matr = np.zeros([20, 50]) + 1e-12 + length = 12 + line = _gen_ridge_line([0, 25], test_matr.shape, length, distances, gaps) + test_matr[line[0], line[1]] = 1 + max_distances = np.full(20, max(distances)) + identified_lines = _identify_ridge_lines(test_matr, + max_distances, + max(gaps) + 1) + assert len(identified_lines) == 1 + for iline_, line_ in zip(identified_lines[0], line): + xp_assert_equal(iline_, line_, check_dtype=False) + + def test_single_bigdist(self): + distances = [0, 1, 2, 5] + gaps = [0, 1, 2, 4] + test_matr = np.zeros([20, 50]) + length = 12 + line = _gen_ridge_line([0, 25], test_matr.shape, length, distances, gaps) + test_matr[line[0], line[1]] = 1 + max_dist = 3 + max_distances = np.full(20, max_dist) + #This should get 2 lines, since the distance is too large + identified_lines = _identify_ridge_lines(test_matr, + max_distances, + max(gaps) + 1) + assert len(identified_lines) == 2 + + for iline in identified_lines: + adists = np.diff(iline[1]) + np.testing.assert_array_less(np.abs(adists), max_dist) + + agaps = np.diff(iline[0]) + np.testing.assert_array_less(np.abs(agaps), max(gaps) + 0.1) + + def test_single_biggap(self): + distances = [0, 1, 2, 5] + max_gap = 3 + gaps = [0, 4, 2, 1] + test_matr = np.zeros([20, 50]) + length = 12 + line = _gen_ridge_line([0, 25], test_matr.shape, length, distances, gaps) + test_matr[line[0], line[1]] = 1 + max_dist = 6 + max_distances = np.full(20, max_dist) + #This should get 2 lines, since the gap is too large + identified_lines = _identify_ridge_lines(test_matr, max_distances, max_gap) + assert len(identified_lines) == 2 + + for iline in identified_lines: + adists = np.diff(iline[1]) + np.testing.assert_array_less(np.abs(adists), max_dist) + + agaps = np.diff(iline[0]) + np.testing.assert_array_less(np.abs(agaps), max(gaps) + 0.1) + + def test_single_biggaps(self): + distances = [0] + max_gap = 1 + gaps = [3, 6] + test_matr = np.zeros([50, 50]) + length = 30 + line = _gen_ridge_line([0, 25], test_matr.shape, length, distances, gaps) + test_matr[line[0], line[1]] = 1 + max_dist = 1 + max_distances = np.full(50, max_dist) + #This should get 3 lines, since the gaps are too large + identified_lines = _identify_ridge_lines(test_matr, max_distances, max_gap) + assert len(identified_lines) == 3 + + for iline in identified_lines: + adists = np.diff(iline[1]) + np.testing.assert_array_less(np.abs(adists), max_dist) + + agaps = np.diff(iline[0]) + np.testing.assert_array_less(np.abs(agaps), max(gaps) + 0.1) + + +class TestArgrel: + + def test_empty(self): + # Regression test for gh-2832. + # When there are no relative extrema, make sure that + # the number of empty arrays returned matches the + # dimension of the input. + + empty_array = np.array([], dtype=int) + + z1 = np.zeros(5) + + i = argrelmin(z1) + xp_assert_equal(len(i), 1) + xp_assert_equal(i[0], empty_array, check_dtype=False) + + z2 = np.zeros((3, 5)) + + row, col = argrelmin(z2, axis=0) + xp_assert_equal(row, empty_array, check_dtype=False) + xp_assert_equal(col, empty_array, check_dtype=False) + + row, col = argrelmin(z2, axis=1) + xp_assert_equal(row, empty_array, check_dtype=False) + xp_assert_equal(col, empty_array, check_dtype=False) + + def test_basic(self): + # Note: the docstrings for the argrel{min,max,extrema} functions + # do not give a guarantee of the order of the indices, so we'll + # sort them before testing. + + x = np.array([[1, 2, 2, 3, 2], + [2, 1, 2, 2, 3], + [3, 2, 1, 2, 2], + [2, 3, 2, 1, 2], + [1, 2, 3, 2, 1]]) + + row, col = argrelmax(x, axis=0) + order = np.argsort(row) + xp_assert_equal(row[order], [1, 2, 3], check_dtype=False) + xp_assert_equal(col[order], [4, 0, 1], check_dtype=False) + + row, col = argrelmax(x, axis=1) + order = np.argsort(row) + xp_assert_equal(row[order], [0, 3, 4], check_dtype=False) + xp_assert_equal(col[order], [3, 1, 2], check_dtype=False) + + row, col = argrelmin(x, axis=0) + order = np.argsort(row) + xp_assert_equal(row[order], [1, 2, 3], check_dtype=False) + xp_assert_equal(col[order], [1, 2, 3], check_dtype=False) + + row, col = argrelmin(x, axis=1) + order = np.argsort(row) + xp_assert_equal(row[order], [1, 2, 3], check_dtype=False) + xp_assert_equal(col[order], [1, 2, 3], check_dtype=False) + + def test_highorder(self): + order = 2 + sigmas = [1.0, 2.0, 10.0, 5.0, 15.0] + test_data, act_locs = _gen_gaussians_even(sigmas, 500) + test_data[act_locs + order] = test_data[act_locs]*0.99999 + test_data[act_locs - order] = test_data[act_locs]*0.99999 + rel_max_locs = argrelmax(test_data, order=order, mode='clip')[0] + + assert len(rel_max_locs) == len(act_locs) + assert (rel_max_locs == act_locs).all() + + def test_2d_gaussians(self): + sigmas = [1.0, 2.0, 10.0] + test_data, act_locs = _gen_gaussians_even(sigmas, 100) + rot_factor = 20 + rot_range = np.arange(0, len(test_data)) - rot_factor + test_data_2 = np.vstack([test_data, test_data[rot_range]]) + rel_max_rows, rel_max_cols = argrelmax(test_data_2, axis=1, order=1) + + for rw in range(0, test_data_2.shape[0]): + inds = (rel_max_rows == rw) + + assert len(rel_max_cols[inds]) == len(act_locs) + assert (act_locs == (rel_max_cols[inds] - rot_factor*rw)).all() + + +class TestPeakProminences: + + def test_empty(self): + """ + Test if an empty array is returned if no peaks are provided. + """ + out = peak_prominences([1, 2, 3], []) + for arr, dtype in zip(out, [np.float64, np.intp, np.intp]): + assert arr.size == 0 + assert arr.dtype == dtype + + out = peak_prominences([], []) + for arr, dtype in zip(out, [np.float64, np.intp, np.intp]): + assert arr.size == 0 + assert arr.dtype == dtype + + def test_basic(self): + """ + Test if height of prominences is correctly calculated in signal with + rising baseline (peak widths are 1 sample). + """ + # Prepare basic signal + x = np.array([-1, 1.2, 1.2, 1, 3.2, 1.3, 2.88, 2.1]) + peaks = np.array([1, 2, 4, 6]) + lbases = np.array([0, 0, 0, 5]) + rbases = np.array([3, 3, 5, 7]) + proms = x[peaks] - np.max([x[lbases], x[rbases]], axis=0) + # Test if calculation matches handcrafted result + out = peak_prominences(x, peaks) + xp_assert_equal(out[0], proms, check_dtype=False) + xp_assert_equal(out[1], lbases, check_dtype=False) + xp_assert_equal(out[2], rbases, check_dtype=False) + + def test_edge_cases(self): + """ + Test edge cases. + """ + # Peaks have same height, prominence and bases + x = [0, 2, 1, 2, 1, 2, 0] + peaks = [1, 3, 5] + proms, lbases, rbases = peak_prominences(x, peaks) + xp_assert_equal(proms, np.asarray([2.0, 2, 2]), check_dtype=False) + xp_assert_equal(lbases, [0, 0, 0], check_dtype=False) + xp_assert_equal(rbases, [6, 6, 6], check_dtype=False) + + # Peaks have same height & prominence but different bases + x = [0, 1, 0, 1, 0, 1, 0] + peaks = np.array([1, 3, 5]) + proms, lbases, rbases = peak_prominences(x, peaks) + xp_assert_equal(proms, np.asarray([1.0, 1, 1])) + xp_assert_equal(lbases, peaks - 1, check_dtype=False) + xp_assert_equal(rbases, peaks + 1, check_dtype=False) + + def test_non_contiguous(self): + """ + Test with non-C-contiguous input arrays. + """ + x = np.repeat([-9, 9, 9, 0, 3, 1], 2) + peaks = np.repeat([1, 2, 4], 2) + proms, lbases, rbases = peak_prominences(x[::2], peaks[::2]) + xp_assert_equal(proms, np.asarray([9.0, 9, 2])) + xp_assert_equal(lbases, [0, 0, 3], check_dtype=False) + xp_assert_equal(rbases, [3, 3, 5], check_dtype=False) + + def test_wlen(self): + """ + Test if wlen actually shrinks the evaluation range correctly. + """ + x = [0, 1, 2, 3, 1, 0, -1] + peak = [3] + # Test rounding behavior of wlen + proms = peak_prominences(x, peak) + for prom, val in zip(proms, [3.0, 0, 6]): + assert prom == val + + for wlen, i in [(8, 0), (7, 0), (6, 0), (5, 1), (3.2, 1), (3, 2), (1.1, 2)]: + proms = peak_prominences(x, peak, wlen) + for prom, val in zip(proms, [3. - i, 0 + i, 6 - i]): + assert prom == val + + def test_exceptions(self): + """ + Verify that exceptions and warnings are raised. + """ + # x with dimension > 1 + with raises(ValueError, match='1-D array'): + peak_prominences([[0, 1, 1, 0]], [1, 2]) + # peaks with dimension > 1 + with raises(ValueError, match='1-D array'): + peak_prominences([0, 1, 1, 0], [[1, 2]]) + # x with dimension < 1 + with raises(ValueError, match='1-D array'): + peak_prominences(3, [0,]) + + # empty x with supplied + with raises(ValueError, match='not a valid index'): + peak_prominences([], [0]) + # invalid indices with non-empty x + for p in [-100, -1, 3, 1000]: + with raises(ValueError, match='not a valid index'): + peak_prominences([1, 0, 2], [p]) + + # peaks is not cast-able to np.intp + with raises(TypeError, match='cannot safely cast'): + peak_prominences([0, 1, 1, 0], [1.1, 2.3]) + + # wlen < 3 + with raises(ValueError, match='wlen'): + peak_prominences(np.arange(10), [3, 5], wlen=1) + + @pytest.mark.thread_unsafe + def test_warnings(self): + """ + Verify that appropriate warnings are raised. + """ + msg = "some peaks have a prominence of 0" + for p in [0, 1, 2]: + with warns(PeakPropertyWarning, match=msg): + peak_prominences([1, 0, 2], [p,]) + with warns(PeakPropertyWarning, match=msg): + peak_prominences([0, 1, 1, 1, 0], [2], wlen=2) + + +class TestPeakWidths: + + def test_empty(self): + """ + Test if an empty array is returned if no peaks are provided. + """ + widths = peak_widths([], [])[0] + assert isinstance(widths, np.ndarray) + assert widths.size == 0 + widths = peak_widths([1, 2, 3], [])[0] + assert isinstance(widths, np.ndarray) + assert widths.size == 0 + out = peak_widths([], []) + for arr in out: + assert isinstance(arr, np.ndarray) + assert arr.size == 0 + + @pytest.mark.filterwarnings("ignore:some peaks have a width of 0") + def test_basic(self): + """ + Test a simple use case with easy to verify results at different relative + heights. + """ + x = np.array([1, 0, 1, 2, 1, 0, -1]) + prominence = 2 + for rel_height, width_true, lip_true, rip_true in [ + (0., 0., 3., 3.), # raises warning + (0.25, 1., 2.5, 3.5), + (0.5, 2., 2., 4.), + (0.75, 3., 1.5, 4.5), + (1., 4., 1., 5.), + (2., 5., 1., 6.), + (3., 5., 1., 6.) + ]: + width_calc, height, lip_calc, rip_calc = peak_widths( + x, [3], rel_height) + xp_assert_close(width_calc, np.asarray([width_true])) + xp_assert_close(height, np.asarray([2 - rel_height * prominence])) + xp_assert_close(lip_calc, np.asarray([lip_true])) + xp_assert_close(rip_calc, np.asarray([rip_true])) + + def test_non_contiguous(self): + """ + Test with non-C-contiguous input arrays. + """ + x = np.repeat([0, 100, 50], 4) + peaks = np.repeat([1], 3) + result = peak_widths(x[::4], peaks[::3]) + xp_assert_equal(result, + np.asarray([[0.75], [75], [0.75], [1.5]]) + ) + + def test_exceptions(self): + """ + Verify that argument validation works as intended. + """ + with raises(ValueError, match='1-D array'): + # x with dimension > 1 + peak_widths(np.zeros((3, 4)), np.ones(3)) + with raises(ValueError, match='1-D array'): + # x with dimension < 1 + peak_widths(3, [0]) + with raises(ValueError, match='1-D array'): + # peaks with dimension > 1 + peak_widths(np.arange(10), np.ones((3, 2), dtype=np.intp)) + with raises(ValueError, match='1-D array'): + # peaks with dimension < 1 + peak_widths(np.arange(10), 3) + with raises(ValueError, match='not a valid index'): + # peak pos exceeds x.size + peak_widths(np.arange(10), [8, 11]) + with raises(ValueError, match='not a valid index'): + # empty x with peaks supplied + peak_widths([], [1, 2]) + with raises(TypeError, match='cannot safely cast'): + # peak cannot be safely cast to intp + peak_widths(np.arange(10), [1.1, 2.3]) + with raises(ValueError, match='rel_height'): + # rel_height is < 0 + peak_widths([0, 1, 0, 1, 0], [1, 3], rel_height=-1) + with raises(TypeError, match='None'): + # prominence data contains None + peak_widths([1, 2, 1], [1], prominence_data=(None, None, None)) + + @pytest.mark.thread_unsafe + def test_warnings(self): + """ + Verify that appropriate warnings are raised. + """ + msg = "some peaks have a width of 0" + with warns(PeakPropertyWarning, match=msg): + # Case: rel_height is 0 + peak_widths([0, 1, 0], [1], rel_height=0) + with warns(PeakPropertyWarning, match=msg): + # Case: prominence is 0 and bases are identical + peak_widths( + [0, 1, 1, 1, 0], [2], + prominence_data=(np.array([0.], np.float64), + np.array([2], np.intp), + np.array([2], np.intp)) + ) + + def test_mismatching_prominence_data(self): + """Test with mismatching peak and / or prominence data.""" + x = [0, 1, 0] + peak = [1] + for i, (prominences, left_bases, right_bases) in enumerate([ + ((1.,), (-1,), (2,)), # left base not in x + ((1.,), (0,), (3,)), # right base not in x + ((1.,), (2,), (0,)), # swapped bases same as peak + ((1., 1.), (0, 0), (2, 2)), # array shapes don't match peaks + ((1., 1.), (0,), (2,)), # arrays with different shapes + ((1.,), (0, 0), (2,)), # arrays with different shapes + ((1.,), (0,), (2, 2)) # arrays with different shapes + ]): + # Make sure input is matches output of signal.peak_prominences + prominence_data = (np.array(prominences, dtype=np.float64), + np.array(left_bases, dtype=np.intp), + np.array(right_bases, dtype=np.intp)) + # Test for correct exception + if i < 3: + match = "prominence data is invalid for peak" + else: + match = "arrays in `prominence_data` must have the same shape" + with raises(ValueError, match=match): + peak_widths(x, peak, prominence_data=prominence_data) + + @pytest.mark.filterwarnings("ignore:some peaks have a width of 0") + def test_intersection_rules(self): + """Test if x == eval_height counts as an intersection.""" + # Flatt peak with two possible intersection points if evaluated at 1 + x = [0, 1, 2, 1, 3, 3, 3, 1, 2, 1, 0] + # relative height is 0 -> width is 0 as well, raises warning + xp_assert_close(peak_widths(x, peaks=[5], rel_height=0), + [(0.,), (3.,), (5.,), (5.,)]) + # width_height == x counts as intersection -> nearest 1 is chosen + xp_assert_close(peak_widths(x, peaks=[5], rel_height=2/3), + [(4.,), (1.,), (3.,), (7.,)]) + + +def test_unpack_condition_args(): + """ + Verify parsing of condition arguments for `scipy.signal.find_peaks` function. + """ + x = np.arange(10) + amin_true = x + amax_true = amin_true + 10 + peaks = amin_true[1::2] + + # Test unpacking with None or interval + assert (None, None) == _unpack_condition_args((None, None), x, peaks) + assert (1, None) == _unpack_condition_args(1, x, peaks) + assert (1, None) == _unpack_condition_args((1, None), x, peaks) + assert (None, 2) == _unpack_condition_args((None, 2), x, peaks) + assert (3., 4.5) == _unpack_condition_args((3., 4.5), x, peaks) + + # Test if borders are correctly reduced with `peaks` + amin_calc, amax_calc = _unpack_condition_args((amin_true, amax_true), x, peaks) + xp_assert_equal(amin_calc, amin_true[peaks]) + xp_assert_equal(amax_calc, amax_true[peaks]) + + # Test raises if array borders don't match x + with raises(ValueError, match="array size of lower"): + _unpack_condition_args(amin_true, np.arange(11), peaks) + with raises(ValueError, match="array size of upper"): + _unpack_condition_args((None, amin_true), np.arange(11), peaks) + + +class TestFindPeaks: + + # Keys of optionally returned properties + property_keys = {'peak_heights', 'left_thresholds', 'right_thresholds', + 'prominences', 'left_bases', 'right_bases', 'widths', + 'width_heights', 'left_ips', 'right_ips'} + + def test_constant(self): + """ + Test behavior for signal without local maxima. + """ + open_interval = (None, None) + peaks, props = find_peaks(np.ones(10), + height=open_interval, threshold=open_interval, + prominence=open_interval, width=open_interval) + assert peaks.size == 0 + for key in self.property_keys: + assert props[key].size == 0 + + def test_plateau_size(self): + """ + Test plateau size condition for peaks. + """ + # Prepare signal with peaks with peak_height == plateau_size + plateau_sizes = np.array([1, 2, 3, 4, 8, 20, 111]) + x = np.zeros(plateau_sizes.size * 2 + 1) + x[1::2] = plateau_sizes + repeats = np.ones(x.size, dtype=int) + repeats[1::2] = x[1::2] + x = np.repeat(x, repeats) + + # Test full output + peaks, props = find_peaks(x, plateau_size=(None, None)) + xp_assert_equal(peaks, [1, 3, 7, 11, 18, 33, 100], check_dtype=False) + xp_assert_equal(props["plateau_sizes"], plateau_sizes, check_dtype=False) + xp_assert_equal(props["left_edges"], peaks - (plateau_sizes - 1) // 2, + check_dtype=False) + xp_assert_equal(props["right_edges"], peaks + plateau_sizes // 2, + check_dtype=False) + + # Test conditions + xp_assert_equal(find_peaks(x, plateau_size=4)[0], [11, 18, 33, 100], + check_dtype=False) + xp_assert_equal(find_peaks(x, plateau_size=(None, 3.5))[0], [1, 3, 7], + check_dtype=False) + xp_assert_equal(find_peaks(x, plateau_size=(5, 50))[0], [18, 33], + check_dtype=False) + + def test_height_condition(self): + """ + Test height condition for peaks. + """ + x = (0., 1/3, 0., 2.5, 0, 4., 0) + peaks, props = find_peaks(x, height=(None, None)) + xp_assert_equal(peaks, np.array([1, 3, 5]), check_dtype=False) + xp_assert_equal(props['peak_heights'], np.array([1/3, 2.5, 4.]), + check_dtype=False) + xp_assert_equal(find_peaks(x, height=0.5)[0], np.array([3, 5]), + check_dtype=False) + xp_assert_equal(find_peaks(x, height=(None, 3))[0], np.array([1, 3]), + check_dtype=False) + xp_assert_equal(find_peaks(x, height=(2, 3))[0], np.array([3]), + check_dtype=False) + + def test_threshold_condition(self): + """ + Test threshold condition for peaks. + """ + x = (0, 2, 1, 4, -1) + peaks, props = find_peaks(x, threshold=(None, None)) + xp_assert_equal(peaks, np.array([1, 3]), check_dtype=False) + xp_assert_equal(props['left_thresholds'], np.array([2.0, 3.0])) + xp_assert_equal(props['right_thresholds'], np.array([1.0, 5.0])) + xp_assert_equal(find_peaks(x, threshold=2)[0], np.array([3]), + check_dtype=False) + xp_assert_equal(find_peaks(x, threshold=3.5)[0], np.array([], dtype=int), + check_dtype=False) + xp_assert_equal(find_peaks(x, threshold=(None, 5))[0], np.array([1, 3]), + check_dtype=False) + xp_assert_equal(find_peaks(x, threshold=(None, 4))[0], np.array([1]), + check_dtype=False) + xp_assert_equal(find_peaks(x, threshold=(2, 4))[0], np.array([], dtype=int), + check_dtype=False) + + def test_distance_condition(self): + """ + Test distance condition for peaks. + """ + # Peaks of different height with constant distance 3 + peaks_all = np.arange(1, 21, 3) + x = np.zeros(21) + x[peaks_all] += np.linspace(1, 2, peaks_all.size) + + # Test if peaks with "minimal" distance are still selected (distance = 3) + xp_assert_equal(find_peaks(x, distance=3)[0], peaks_all, check_dtype=False) + + # Select every second peak (distance > 3) + peaks_subset = find_peaks(x, distance=3.0001)[0] + # Test if peaks_subset is subset of peaks_all + assert np.setdiff1d(peaks_subset, peaks_all, assume_unique=True).size == 0 + + # Test if every second peak was removed + dfs = np.diff(peaks_subset) + xp_assert_equal(dfs, 6*np.ones_like(dfs)) + + # Test priority of peak removal + x = [-2, 1, -1, 0, -3] + peaks_subset = find_peaks(x, distance=10)[0] # use distance > x size + assert peaks_subset.size == 1 and peaks_subset[0] == 1 + + def test_prominence_condition(self): + """ + Test prominence condition for peaks. + """ + x = np.linspace(0, 10, 100) + peaks_true = np.arange(1, 99, 2) + offset = np.linspace(1, 10, peaks_true.size) + x[peaks_true] += offset + prominences = x[peaks_true] - x[peaks_true + 1] + interval = (3, 9) + keep = np.nonzero( + (interval[0] <= prominences) & (prominences <= interval[1])) + + peaks_calc, properties = find_peaks(x, prominence=interval) + xp_assert_equal(peaks_calc, peaks_true[keep], check_dtype=False) + xp_assert_equal(properties['prominences'], prominences[keep], check_dtype=False) + xp_assert_equal(properties['left_bases'], + np.zeros_like(properties['left_bases'])) + xp_assert_equal(properties['right_bases'], peaks_true[keep] + 1, + check_dtype=False) + + def test_width_condition(self): + """ + Test width condition for peaks. + """ + x = np.array([1, 0, 1, 2, 1, 0, -1, 4, 0]) + peaks, props = find_peaks(x, width=(None, 2), rel_height=0.75) + assert peaks.size == 1 + xp_assert_equal(peaks, 7*np.ones_like(peaks)) + xp_assert_close(props['widths'], np.asarray([1.35])) + xp_assert_close(props['width_heights'], np.asarray([1.])) + xp_assert_close(props['left_ips'], np.asarray([6.4])) + xp_assert_close(props['right_ips'], np.asarray([7.75])) + + def test_properties(self): + """ + Test returned properties. + """ + open_interval = (None, None) + x = [0, 1, 0, 2, 1.5, 0, 3, 0, 5, 9] + peaks, props = find_peaks(x, + height=open_interval, threshold=open_interval, + prominence=open_interval, width=open_interval) + assert len(props) == len(self.property_keys) + for key in self.property_keys: + assert peaks.size == props[key].size + + def test_raises(self): + """ + Test exceptions raised by function. + """ + with raises(ValueError, match="1-D array"): + find_peaks(np.array(1)) + with raises(ValueError, match="1-D array"): + find_peaks(np.ones((2, 2))) + with raises(ValueError, match="distance"): + find_peaks(np.arange(10), distance=-1) + + @pytest.mark.filterwarnings("ignore:some peaks have a prominence of 0", + "ignore:some peaks have a width of 0") + def test_wlen_smaller_plateau(self): + """ + Test behavior of prominence and width calculation if the given window + length is smaller than a peak's plateau size. + + Regression test for gh-9110. + """ + peaks, props = find_peaks([0, 1, 1, 1, 0], prominence=(None, None), + width=(None, None), wlen=2) + xp_assert_equal(peaks, 2 * np.ones_like(peaks)) + xp_assert_equal(props["prominences"], np.zeros_like(props["prominences"])) + xp_assert_equal(props["widths"], np.zeros_like(props["widths"])) + xp_assert_equal(props["width_heights"], np.ones_like(props["width_heights"])) + for key in ("left_bases", "right_bases", "left_ips", "right_ips"): + xp_assert_equal(props[key], peaks, check_dtype=False) + + @pytest.mark.parametrize("kwargs", [ + {}, + {"distance": 3.0}, + {"prominence": (None, None)}, + {"width": (None, 2)}, + + ]) + def test_readonly_array(self, kwargs): + """ + Test readonly arrays are accepted. + """ + x = np.linspace(0, 10, 15) + x_readonly = x.copy() + x_readonly.flags.writeable = False + + peaks, _ = find_peaks(x) + peaks_readonly, _ = find_peaks(x_readonly, **kwargs) + + xp_assert_close(peaks, peaks_readonly) + + +class TestFindPeaksCwt: + + def test_find_peaks_exact(self): + """ + Generate a series of gaussians and attempt to find the peak locations. + """ + sigmas = [5.0, 3.0, 10.0, 20.0, 10.0, 50.0] + num_points = 500 + test_data, act_locs = _gen_gaussians_even(sigmas, num_points) + widths = np.arange(0.1, max(sigmas)) + found_locs = find_peaks_cwt(test_data, widths, gap_thresh=2, min_snr=0, + min_length=None) + xp_assert_equal(found_locs, act_locs, + check_dtype=False, + err_msg="Found maximum locations did not equal those expected" + ) + + def test_find_peaks_withnoise(self): + """ + Verify that peak locations are (approximately) found + for a series of gaussians with added noise. + """ + sigmas = [5.0, 3.0, 10.0, 20.0, 10.0, 50.0] + num_points = 500 + test_data, act_locs = _gen_gaussians_even(sigmas, num_points) + widths = np.arange(0.1, max(sigmas)) + noise_amp = 0.07 + np.random.seed(18181911) + test_data += (np.random.rand(num_points) - 0.5)*(2*noise_amp) + found_locs = find_peaks_cwt(test_data, widths, min_length=15, + gap_thresh=1, min_snr=noise_amp / 5) + + err_msg ='Different number of peaks found than expected' + assert len(found_locs) == len(act_locs), err_msg + diffs = np.abs(found_locs - act_locs) + max_diffs = np.array(sigmas) / 5 + np.testing.assert_array_less(diffs, max_diffs, 'Maximum location differed' + + f'by more than {max_diffs}') + + def test_find_peaks_nopeak(self): + """ + Verify that no peak is found in + data that's just noise. + """ + noise_amp = 1.0 + num_points = 100 + rng = np.random.RandomState(181819141) + test_data = (rng.rand(num_points) - 0.5)*(2*noise_amp) + widths = np.arange(10, 50) + found_locs = find_peaks_cwt(test_data, widths, min_snr=5, noise_perc=30) + assert len(found_locs) == 0 + + def test_find_peaks_with_non_default_wavelets(self): + x = gaussian(200, 2) + widths = np.array([1, 2, 3, 4]) + a = find_peaks_cwt(x, widths, wavelet=gaussian) + + xp_assert_equal(a, np.asarray([100]), check_dtype=False) + + def test_find_peaks_window_size(self): + """ + Verify that window_size is passed correctly to private function and + affects the result. + """ + sigmas = [2.0, 2.0] + num_points = 1000 + test_data, act_locs = _gen_gaussians_even(sigmas, num_points) + widths = np.arange(0.1, max(sigmas), 0.2) + noise_amp = 0.05 + rng = np.random.RandomState(18181911) + test_data += (rng.rand(num_points) - 0.5)*(2*noise_amp) + + # Possibly contrived negative region to throw off peak finding + # when window_size is too large + test_data[250:320] -= 1 + + found_locs = find_peaks_cwt(test_data, widths, gap_thresh=2, min_snr=3, + min_length=None, window_size=None) + with pytest.raises(AssertionError): + assert found_locs.size == act_locs.size + + found_locs = find_peaks_cwt(test_data, widths, gap_thresh=2, min_snr=3, + min_length=None, window_size=20) + assert found_locs.size == act_locs.size + + def test_find_peaks_with_one_width(self): + """ + Verify that the `width` argument + in `find_peaks_cwt` can be a float + """ + xs = np.arange(0, np.pi, 0.05) + test_data = np.sin(xs) + widths = 1 + found_locs = find_peaks_cwt(test_data, widths) + + np.testing.assert_equal(found_locs, 32) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_result_type.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_result_type.py new file mode 100644 index 0000000000000000000000000000000000000000..a2cadd325a7e36c877df8532ba957712831c2dad --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_result_type.py @@ -0,0 +1,51 @@ +# Regressions tests on result types of some signal functions + +import numpy as np + +from scipy.signal import (decimate, + lfilter_zi, + lfiltic, + sos2tf, + sosfilt_zi) + + +def test_decimate(): + ones_f32 = np.ones(32, dtype=np.float32) + assert decimate(ones_f32, 2).dtype == np.float32 + + ones_i64 = np.ones(32, dtype=np.int64) + assert decimate(ones_i64, 2).dtype == np.float64 + + +def test_lfilter_zi(): + b_f32 = np.array([1, 2, 3], dtype=np.float32) + a_f32 = np.array([4, 5, 6], dtype=np.float32) + assert lfilter_zi(b_f32, a_f32).dtype == np.float32 + + +def test_lfiltic(): + # this would return f32 when given a mix of f32 / f64 args + b_f32 = np.array([1, 2, 3], dtype=np.float32) + a_f32 = np.array([4, 5, 6], dtype=np.float32) + x_f32 = np.ones(32, dtype=np.float32) + + b_f64 = b_f32.astype(np.float64) + a_f64 = a_f32.astype(np.float64) + x_f64 = x_f32.astype(np.float64) + + assert lfiltic(b_f64, a_f32, x_f32).dtype == np.float64 + assert lfiltic(b_f32, a_f64, x_f32).dtype == np.float64 + assert lfiltic(b_f32, a_f32, x_f64).dtype == np.float64 + assert lfiltic(b_f32, a_f32, x_f32, x_f64).dtype == np.float64 + + +def test_sos2tf(): + sos_f32 = np.array([[4, 5, 6, 1, 2, 3]], dtype=np.float32) + b, a = sos2tf(sos_f32) + assert b.dtype == np.float32 + assert a.dtype == np.float32 + + +def test_sosfilt_zi(): + sos_f32 = np.array([[4, 5, 6, 1, 2, 3]], dtype=np.float32) + assert sosfilt_zi(sos_f32).dtype == np.float32 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_savitzky_golay.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_savitzky_golay.py new file mode 100644 index 0000000000000000000000000000000000000000..61d958e35d91b7d537e0bd3551b6cec3f45a4983 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_savitzky_golay.py @@ -0,0 +1,362 @@ +import pytest +import numpy as np +from numpy.testing import (assert_equal, + assert_array_equal, +) + +from scipy._lib._array_api import ( + assert_almost_equal, assert_array_almost_equal, xp_assert_close +) + +from scipy.ndimage import convolve1d # type: ignore[attr-defined] + +from scipy.signal import savgol_coeffs, savgol_filter +from scipy.signal._savitzky_golay import _polyder + + +def check_polyder(p, m, expected): + dp = _polyder(p, m) + assert_array_equal(dp, expected) + + +def test_polyder(): + cases = [ + ([5], 0, [5]), + ([5], 1, [0]), + ([3, 2, 1], 0, [3, 2, 1]), + ([3, 2, 1], 1, [6, 2]), + ([3, 2, 1], 2, [6]), + ([3, 2, 1], 3, [0]), + ([[3, 2, 1], [5, 6, 7]], 0, [[3, 2, 1], [5, 6, 7]]), + ([[3, 2, 1], [5, 6, 7]], 1, [[6, 2], [10, 6]]), + ([[3, 2, 1], [5, 6, 7]], 2, [[6], [10]]), + ([[3, 2, 1], [5, 6, 7]], 3, [[0], [0]]), + ] + for p, m, expected in cases: + check_polyder(np.array(p).T, m, np.array(expected).T) + + +#-------------------------------------------------------------------- +# savgol_coeffs tests +#-------------------------------------------------------------------- + +def alt_sg_coeffs(window_length, polyorder, pos): + """This is an alternative implementation of the SG coefficients. + + It uses numpy.polyfit and numpy.polyval. The results should be + equivalent to those of savgol_coeffs(), but this implementation + is slower. + + window_length should be odd. + + """ + if pos is None: + pos = window_length // 2 + t = np.arange(window_length) + unit = (t == pos).astype(int) + h = np.polyval(np.polyfit(t, unit, polyorder), t) + return h + + +def test_sg_coeffs_trivial(): + # Test a trivial case of savgol_coeffs: polyorder = window_length - 1 + h = savgol_coeffs(1, 0) + xp_assert_close(h, [1.0]) + + h = savgol_coeffs(3, 2) + xp_assert_close(h, [0.0, 1, 0], atol=1e-10) + + h = savgol_coeffs(5, 4) + xp_assert_close(h, [0.0, 0, 1, 0, 0], atol=1e-10) + + h = savgol_coeffs(5, 4, pos=1) + xp_assert_close(h, [0.0, 0, 0, 1, 0], atol=1e-10) + + h = savgol_coeffs(5, 4, pos=1, use='dot') + xp_assert_close(h, [0.0, 1, 0, 0, 0], atol=1e-10) + + +def compare_coeffs_to_alt(window_length, order): + # For the given window_length and order, compare the results + # of savgol_coeffs and alt_sg_coeffs for pos from 0 to window_length - 1. + # Also include pos=None. + for pos in [None] + list(range(window_length)): + h1 = savgol_coeffs(window_length, order, pos=pos, use='dot') + h2 = alt_sg_coeffs(window_length, order, pos=pos) + xp_assert_close(h1, h2, atol=1e-10, + err_msg=("window_length = %d, order = %d, pos = %s" % + (window_length, order, pos))) + + +def test_sg_coeffs_compare(): + # Compare savgol_coeffs() to alt_sg_coeffs(). + for window_length in range(1, 8, 2): + for order in range(window_length): + compare_coeffs_to_alt(window_length, order) + + +def test_sg_coeffs_exact(): + polyorder = 4 + window_length = 9 + halflen = window_length // 2 + + x = np.linspace(0, 21, 43) + delta = x[1] - x[0] + + # The data is a cubic polynomial. We'll use an order 4 + # SG filter, so the filtered values should equal the input data + # (except within half window_length of the edges). + y = 0.5 * x ** 3 - x + h = savgol_coeffs(window_length, polyorder) + y0 = convolve1d(y, h) + xp_assert_close(y0[halflen:-halflen], y[halflen:-halflen]) + + # Check the same input, but use deriv=1. dy is the exact result. + dy = 1.5 * x ** 2 - 1 + h = savgol_coeffs(window_length, polyorder, deriv=1, delta=delta) + y1 = convolve1d(y, h) + xp_assert_close(y1[halflen:-halflen], dy[halflen:-halflen]) + + # Check the same input, but use deriv=2. d2y is the exact result. + d2y = 3.0 * x + h = savgol_coeffs(window_length, polyorder, deriv=2, delta=delta) + y2 = convolve1d(y, h) + xp_assert_close(y2[halflen:-halflen], d2y[halflen:-halflen]) + + +def test_sg_coeffs_deriv(): + # The data in `x` is a sampled parabola, so using savgol_coeffs with an + # order 2 or higher polynomial should give exact results. + i = np.array([-2.0, 0.0, 2.0, 4.0, 6.0]) + x = i ** 2 / 4 + dx = i / 2 + d2x = np.full_like(i, 0.5) + for pos in range(x.size): + coeffs0 = savgol_coeffs(5, 3, pos=pos, delta=2.0, use='dot') + xp_assert_close(coeffs0.dot(x), x[pos], atol=1e-10) + coeffs1 = savgol_coeffs(5, 3, pos=pos, delta=2.0, use='dot', deriv=1) + xp_assert_close(coeffs1.dot(x), dx[pos], atol=1e-10) + coeffs2 = savgol_coeffs(5, 3, pos=pos, delta=2.0, use='dot', deriv=2) + xp_assert_close(coeffs2.dot(x), d2x[pos], atol=1e-10) + + +def test_sg_coeffs_deriv_gt_polyorder(): + """ + If deriv > polyorder, the coefficients should be all 0. + This is a regression test for a bug where, e.g., + savgol_coeffs(5, polyorder=1, deriv=2) + raised an error. + """ + coeffs = savgol_coeffs(5, polyorder=1, deriv=2) + assert_array_equal(coeffs, np.zeros(5)) + coeffs = savgol_coeffs(7, polyorder=4, deriv=6) + assert_array_equal(coeffs, np.zeros(7)) + + +def test_sg_coeffs_large(): + # Test that for large values of window_length and polyorder the array of + # coefficients returned is symmetric. The aim is to ensure that + # no potential numeric overflow occurs. + coeffs0 = savgol_coeffs(31, 9) + assert_array_almost_equal(coeffs0, coeffs0[::-1]) + coeffs1 = savgol_coeffs(31, 9, deriv=1) + assert_array_almost_equal(coeffs1, -coeffs1[::-1]) + +# -------------------------------------------------------------------- +# savgol_coeffs tests for even window length +# -------------------------------------------------------------------- + + +def test_sg_coeffs_even_window_length(): + # Simple case - deriv=0, polyorder=0, 1 + window_lengths = [4, 6, 8, 10, 12, 14, 16] + for length in window_lengths: + h_p_d = savgol_coeffs(length, 0, 0) + xp_assert_close(h_p_d, np.ones_like(h_p_d) / length) + + # Verify with closed forms + # deriv=1, polyorder=1, 2 + def h_p_d_closed_form_1(k, m): + return 6*(k - 0.5)/((2*m + 1)*m*(2*m - 1)) + + # deriv=2, polyorder=2 + def h_p_d_closed_form_2(k, m): + numer = 15*(-4*m**2 + 1 + 12*(k - 0.5)**2) + denom = 4*(2*m + 1)*(m + 1)*m*(m - 1)*(2*m - 1) + return numer/denom + + for length in window_lengths: + m = length//2 + expected_output = [h_p_d_closed_form_1(k, m) + for k in range(-m + 1, m + 1)][::-1] + actual_output = savgol_coeffs(length, 1, 1) + xp_assert_close(expected_output, actual_output) + actual_output = savgol_coeffs(length, 2, 1) + xp_assert_close(expected_output, actual_output) + + expected_output = [h_p_d_closed_form_2(k, m) + for k in range(-m + 1, m + 1)][::-1] + actual_output = savgol_coeffs(length, 2, 2) + xp_assert_close(expected_output, actual_output) + actual_output = savgol_coeffs(length, 3, 2) + xp_assert_close(expected_output, actual_output) + +#-------------------------------------------------------------------- +# savgol_filter tests +#-------------------------------------------------------------------- + + +def test_sg_filter_trivial(): + """ Test some trivial edge cases for savgol_filter().""" + x = np.array([1.0]) + y = savgol_filter(x, 1, 0) + assert_equal(y, [1.0]) + + # Input is a single value. With a window length of 3 and polyorder 1, + # the value in y is from the straight-line fit of (-1,0), (0,3) and + # (1, 0) at 0. This is just the average of the three values, hence 1.0. + x = np.array([3.0]) + y = savgol_filter(x, 3, 1, mode='constant') + assert_almost_equal(y, [1.0], decimal=15) + + x = np.array([3.0]) + y = savgol_filter(x, 3, 1, mode='nearest') + assert_almost_equal(y, [3.0], decimal=15) + + x = np.array([1.0] * 3) + y = savgol_filter(x, 3, 1, mode='wrap') + assert_almost_equal(y, [1.0, 1.0, 1.0], decimal=15) + + +def test_sg_filter_basic(): + # Some basic test cases for savgol_filter(). + x = np.array([1.0, 2.0, 1.0]) + y = savgol_filter(x, 3, 1, mode='constant') + xp_assert_close(y, [1.0, 4.0 / 3, 1.0]) + + y = savgol_filter(x, 3, 1, mode='mirror') + xp_assert_close(y, [5.0 / 3, 4.0 / 3, 5.0 / 3]) + + y = savgol_filter(x, 3, 1, mode='wrap') + xp_assert_close(y, [4.0 / 3, 4.0 / 3, 4.0 / 3]) + + +def test_sg_filter_2d(): + x = np.array([[1.0, 2.0, 1.0], + [2.0, 4.0, 2.0]]) + expected = np.array([[1.0, 4.0 / 3, 1.0], + [2.0, 8.0 / 3, 2.0]]) + y = savgol_filter(x, 3, 1, mode='constant') + xp_assert_close(y, expected) + + y = savgol_filter(x.T, 3, 1, mode='constant', axis=0) + xp_assert_close(y, expected.T) + + +def test_sg_filter_interp_edges(): + # Another test with low degree polynomial data, for which we can easily + # give the exact results. In this test, we use mode='interp', so + # savgol_filter should match the exact solution for the entire data set, + # including the edges. + t = np.linspace(-5, 5, 21) + delta = t[1] - t[0] + # Polynomial test data. + x = np.array([t, + 3 * t ** 2, + t ** 3 - t]) + dx = np.array([np.ones_like(t), + 6 * t, + 3 * t ** 2 - 1.0]) + d2x = np.array([np.zeros_like(t), + np.full_like(t, 6), + 6 * t]) + + window_length = 7 + + y = savgol_filter(x, window_length, 3, axis=-1, mode='interp') + xp_assert_close(y, x, atol=1e-12) + + y1 = savgol_filter(x, window_length, 3, axis=-1, mode='interp', + deriv=1, delta=delta) + xp_assert_close(y1, dx, atol=1e-12) + + y2 = savgol_filter(x, window_length, 3, axis=-1, mode='interp', + deriv=2, delta=delta) + xp_assert_close(y2, d2x, atol=1e-12) + + # Transpose everything, and test again with axis=0. + + x = x.T + dx = dx.T + d2x = d2x.T + + y = savgol_filter(x, window_length, 3, axis=0, mode='interp') + xp_assert_close(y, x, atol=1e-12) + + y1 = savgol_filter(x, window_length, 3, axis=0, mode='interp', + deriv=1, delta=delta) + xp_assert_close(y1, dx, atol=1e-12) + + y2 = savgol_filter(x, window_length, 3, axis=0, mode='interp', + deriv=2, delta=delta) + xp_assert_close(y2, d2x, atol=1e-12) + + +def test_sg_filter_interp_edges_3d(): + # Test mode='interp' with a 3-D array. + t = np.linspace(-5, 5, 21) + delta = t[1] - t[0] + x1 = np.array([t, -t]) + x2 = np.array([t ** 2, 3 * t ** 2 + 5]) + x3 = np.array([t ** 3, 2 * t ** 3 + t ** 2 - 0.5 * t]) + dx1 = np.array([np.ones_like(t), -np.ones_like(t)]) + dx2 = np.array([2 * t, 6 * t]) + dx3 = np.array([3 * t ** 2, 6 * t ** 2 + 2 * t - 0.5]) + + # z has shape (3, 2, 21) + z = np.array([x1, x2, x3]) + dz = np.array([dx1, dx2, dx3]) + + y = savgol_filter(z, 7, 3, axis=-1, mode='interp', delta=delta) + xp_assert_close(y, z, atol=1e-10) + + dy = savgol_filter(z, 7, 3, axis=-1, mode='interp', deriv=1, delta=delta) + xp_assert_close(dy, dz, atol=1e-10) + + # z has shape (3, 21, 2) + z = np.array([x1.T, x2.T, x3.T]) + dz = np.array([dx1.T, dx2.T, dx3.T]) + + y = savgol_filter(z, 7, 3, axis=1, mode='interp', delta=delta) + xp_assert_close(y, z, atol=1e-10) + + dy = savgol_filter(z, 7, 3, axis=1, mode='interp', deriv=1, delta=delta) + xp_assert_close(dy, dz, atol=1e-10) + + # z has shape (21, 3, 2) + z = z.swapaxes(0, 1).copy() + dz = dz.swapaxes(0, 1).copy() + + y = savgol_filter(z, 7, 3, axis=0, mode='interp', delta=delta) + xp_assert_close(y, z, atol=1e-10) + + dy = savgol_filter(z, 7, 3, axis=0, mode='interp', deriv=1, delta=delta) + xp_assert_close(dy, dz, atol=1e-10) + + +def test_sg_filter_valid_window_length_3d(): + """Tests that the window_length check is using the correct axis.""" + + x = np.ones((10, 20, 30)) + + savgol_filter(x, window_length=29, polyorder=3, mode='interp') + + with pytest.raises(ValueError, match='window_length must be less than'): + # window_length is more than x.shape[-1]. + savgol_filter(x, window_length=31, polyorder=3, mode='interp') + + savgol_filter(x, window_length=9, polyorder=3, axis=0, mode='interp') + + with pytest.raises(ValueError, match='window_length must be less than'): + # window_length is more than x.shape[0]. + savgol_filter(x, window_length=11, polyorder=3, axis=0, mode='interp') diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_short_time_fft.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_short_time_fft.py new file mode 100644 index 0000000000000000000000000000000000000000..df1ccc639f2041cfc8a6aec50190b34f72d25c84 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_short_time_fft.py @@ -0,0 +1,880 @@ +"""Unit tests for module `_short_time_fft`. + +This file's structure loosely groups the tests into the following sequential +categories: + +1. Test function `_calc_dual_canonical_window`. +2. Test for invalid parameters and exceptions in `ShortTimeFFT` (until the + `test_from_window` function). +3. Test algorithmic properties of STFT/ISTFT. Some tests were ported from + ``test_spectral.py``. + +Notes +----- +* Mypy 0.990 does interpret the line:: + + from scipy.stats import norm as normal_distribution + + incorrectly (but the code works), hence a ``type: ignore`` was appended. +""" +import math +from itertools import product +from typing import cast, get_args, Literal + +import numpy as np +import pytest +from scipy._lib._array_api import xp_assert_close, xp_assert_equal +from scipy.fft import fftshift +from scipy.stats import norm as normal_distribution # type: ignore +from scipy.signal import get_window, welch, stft, istft, spectrogram + +from scipy.signal._short_time_fft import FFT_MODE_TYPE, \ + _calc_dual_canonical_window, ShortTimeFFT, PAD_TYPE +from scipy.signal.windows import gaussian + + +def test__calc_dual_canonical_window_roundtrip(): + """Test dual window calculation with a round trip to verify duality. + + Note that this works only for canonical window pairs (having minimal + energy) like a Gaussian. + + The window is the same as in the example of `from ShortTimeFFT.from_dual`. + """ + win = gaussian(51, std=10, sym=True) + d_win = _calc_dual_canonical_window(win, 10) + win2 = _calc_dual_canonical_window(d_win, 10) + xp_assert_close(win2, win) + + +def test__calc_dual_canonical_window_exceptions(): + """Raise all exceptions in `_calc_dual_canonical_window`.""" + # Verify that calculation can fail: + with pytest.raises(ValueError, match="hop=5 is larger than window len.*"): + _calc_dual_canonical_window(np.ones(4), 5) + with pytest.raises(ValueError, match=".* Transform not invertible!"): + _calc_dual_canonical_window(np.array([.1, .2, .3, 0]), 4) + + # Verify that parameter `win` may not be integers: + with pytest.raises(ValueError, match="Parameter 'win' cannot be of int.*"): + _calc_dual_canonical_window(np.ones(4, dtype=int), 1) + + +def test_invalid_initializer_parameters(): + """Verify that exceptions get raised on invalid parameters when + instantiating ShortTimeFFT. """ + with pytest.raises(ValueError, match=r"Parameter win must be 1d, " + + r"but win.shape=\(2, 2\)!"): + ShortTimeFFT(np.ones((2, 2)), hop=4, fs=1) + with pytest.raises(ValueError, match="Parameter win must have " + + "finite entries"): + ShortTimeFFT(np.array([1, np.inf, 2, 3]), hop=4, fs=1) + with pytest.raises(ValueError, match="Parameter hop=0 is not " + + "an integer >= 1!"): + ShortTimeFFT(np.ones(4), hop=0, fs=1) + with pytest.raises(ValueError, match="Parameter hop=2.0 is not " + + "an integer >= 1!"): + # noinspection PyTypeChecker + ShortTimeFFT(np.ones(4), hop=2.0, fs=1) + with pytest.raises(ValueError, match=r"dual_win.shape=\(5,\) must equal " + + r"win.shape=\(4,\)!"): + ShortTimeFFT(np.ones(4), hop=2, fs=1, dual_win=np.ones(5)) + with pytest.raises(ValueError, match="Parameter dual_win must be " + + "a finite array!"): + ShortTimeFFT(np.ones(3), hop=2, fs=1, + dual_win=np.array([np.nan, 2, 3])) + + +def test_exceptions_properties_methods(): + """Verify that exceptions get raised when setting properties or calling + method of ShortTimeFFT to/with invalid values.""" + SFT = ShortTimeFFT(np.ones(8), hop=4, fs=1) + with pytest.raises(ValueError, match="Sampling interval T=-1 must be " + + "positive!"): + SFT.T = -1 + with pytest.raises(ValueError, match="Sampling frequency fs=-1 must be " + + "positive!"): + SFT.fs = -1 + with pytest.raises(ValueError, match="fft_mode='invalid_typ' not in " + + r"\('twosided', 'centered', " + + r"'onesided', 'onesided2X'\)!"): + SFT.fft_mode = 'invalid_typ' + with pytest.raises(ValueError, match="For scaling is None, " + + "fft_mode='onesided2X' is invalid.*"): + SFT.fft_mode = 'onesided2X' + with pytest.raises(ValueError, match="Attribute mfft=7 needs to be " + + "at least the window length.*"): + SFT.mfft = 7 + with pytest.raises(ValueError, match="scaling='invalid' not in.*"): + # noinspection PyTypeChecker + SFT.scale_to('invalid') + with pytest.raises(ValueError, match="phase_shift=3.0 has the unit .*"): + SFT.phase_shift = 3.0 + with pytest.raises(ValueError, match="-mfft < phase_shift < mfft " + + "does not hold.*"): + SFT.phase_shift = 2*SFT.mfft + with pytest.raises(ValueError, match="Parameter padding='invalid' not.*"): + # noinspection PyTypeChecker + g = SFT._x_slices(np.zeros(16), k_off=0, p0=0, p1=1, padding='invalid') + next(g) # execute generator + with pytest.raises(ValueError, match="Trend type must be 'linear' " + + "or 'constant'"): + # noinspection PyTypeChecker + SFT.stft_detrend(np.zeros(16), detr='invalid') + with pytest.raises(ValueError, match="Parameter detr=nan is not a str, " + + "function or None!"): + # noinspection PyTypeChecker + SFT.stft_detrend(np.zeros(16), detr=np.nan) + with pytest.raises(ValueError, match="Invalid Parameter p0=0, p1=200.*"): + SFT.p_range(100, 0, 200) + + with pytest.raises(ValueError, match="f_axis=0 may not be equal to " + + "t_axis=0!"): + SFT.istft(np.zeros((SFT.f_pts, 2)), t_axis=0, f_axis=0) + with pytest.raises(ValueError, match=r"S.shape\[f_axis\]=2 must be equal" + + " to self.f_pts=5.*"): + SFT.istft(np.zeros((2, 2))) + with pytest.raises(ValueError, match=r"S.shape\[t_axis\]=1 needs to have" + + " at least 2 slices.*"): + SFT.istft(np.zeros((SFT.f_pts, 1))) + with pytest.raises(ValueError, match=r".*\(k1=100\) <= \(k_max=12\) " + + "is false!$"): + SFT.istft(np.zeros((SFT.f_pts, 3)), k1=100) + with pytest.raises(ValueError, match=r"\(k1=1\) - \(k0=0\) = 1 has to " + + "be at least.* length 4!"): + SFT.istft(np.zeros((SFT.f_pts, 3)), k0=0, k1=1) + + with pytest.raises(ValueError, match=r"Parameter axes_seq='invalid' " + + r"not in \['tf', 'ft'\]!"): + # noinspection PyTypeChecker + SFT.extent(n=100, axes_seq='invalid') + with pytest.raises(ValueError, match="Attribute fft_mode=twosided must.*"): + SFT.fft_mode = 'twosided' + SFT.extent(n=100) + + +@pytest.mark.parametrize('m', ('onesided', 'onesided2X')) +def test_exceptions_fft_mode_complex_win(m: FFT_MODE_TYPE): + """Verify that one-sided spectra are not allowed with complex-valued + windows or with complex-valued signals. + + The reason being, the `rfft` function only accepts real-valued input. + """ + with pytest.raises(ValueError, + match=f"One-sided spectra, i.e., fft_mode='{m}'.*"): + ShortTimeFFT(np.ones(8)*1j, hop=4, fs=1, fft_mode=m) + + SFT = ShortTimeFFT(np.ones(8)*1j, hop=4, fs=1, fft_mode='twosided') + with pytest.raises(ValueError, + match=f"One-sided spectra, i.e., fft_mode='{m}'.*"): + SFT.fft_mode = m + + SFT = ShortTimeFFT(np.ones(8), hop=4, fs=1, scale_to='psd', fft_mode='onesided') + with pytest.raises(ValueError, match="Complex-valued `x` not allowed for self.*"): + SFT.stft(np.ones(8)*1j) + SFT.fft_mode = 'onesided2X' + with pytest.raises(ValueError, match="Complex-valued `x` not allowed for self.*"): + SFT.stft(np.ones(8)*1j) + + +def test_invalid_fft_mode_RuntimeError(): + """Ensure exception gets raised when property `fft_mode` is invalid. """ + SFT = ShortTimeFFT(np.ones(8), hop=4, fs=1) + SFT._fft_mode = 'invalid_typ' + + with pytest.raises(RuntimeError): + _ = SFT.f + with pytest.raises(RuntimeError): + SFT._fft_func(np.ones(8)) + with pytest.raises(RuntimeError): + SFT._ifft_func(np.ones(8)) + + +@pytest.mark.parametrize('win_params, Nx', [(('gaussian', 2.), 9), # in docstr + ('triang', 7), + (('kaiser', 4.0), 9), + (('exponential', None, 1.), 9), + (4.0, 9)]) +def test_from_window(win_params, Nx: int): + """Verify that `from_window()` handles parameters correctly. + + The window parameterizations are documented in the `get_window` docstring. + """ + w_sym, fs = get_window(win_params, Nx, fftbins=False), 16. + w_per = get_window(win_params, Nx, fftbins=True) + SFT0 = ShortTimeFFT(w_sym, hop=3, fs=fs, fft_mode='twosided', + scale_to='psd', phase_shift=1) + nperseg = len(w_sym) + noverlap = nperseg - SFT0.hop + SFT1 = ShortTimeFFT.from_window(win_params, fs, nperseg, noverlap, + symmetric_win=True, fft_mode='twosided', + scale_to='psd', phase_shift=1) + # periodic window: + SFT2 = ShortTimeFFT.from_window(win_params, fs, nperseg, noverlap, + symmetric_win=False, fft_mode='twosided', + scale_to='psd', phase_shift=1) + # Be informative when comparing instances: + xp_assert_equal(SFT1.win, SFT0.win) + xp_assert_close(SFT2.win, w_per / np.sqrt(sum(w_per**2) * fs)) + for n_ in ('hop', 'T', 'fft_mode', 'mfft', 'scaling', 'phase_shift'): + v0, v1, v2 = (getattr(SFT_, n_) for SFT_ in (SFT0, SFT1, SFT2)) + assert v1 == v0, f"SFT1.{n_}={v1} does not equal SFT0.{n_}={v0}" + assert v2 == v0, f"SFT2.{n_}={v2} does not equal SFT0.{n_}={v0}" + + +def test_dual_win_roundtrip(): + """Verify the duality of `win` and `dual_win`. + + Note that this test does not work for arbitrary windows, since dual windows + are not unique. It always works for invertible STFTs if the windows do not + overlap. + """ + # Non-standard values for keyword arguments (except for `scale_to`): + kw = dict(hop=4, fs=1, fft_mode='twosided', mfft=8, scale_to=None, + phase_shift=2) + SFT0 = ShortTimeFFT(np.ones(4), **kw) + SFT1 = ShortTimeFFT.from_dual(SFT0.dual_win, **kw) + xp_assert_close(SFT1.dual_win, SFT0.win) + + +@pytest.mark.parametrize('scale_to, fac_psd, fac_mag', + [(None, 0.25, 0.125), + ('magnitude', 2.0, 1), + ('psd', 1, 0.5)]) +def test_scaling(scale_to: Literal['magnitude', 'psd'], fac_psd, fac_mag): + """Verify scaling calculations. + + * Verify passing `scale_to`parameter to ``__init__(). + * Roundtrip while changing scaling factor. + """ + SFT = ShortTimeFFT(np.ones(4) * 2, hop=4, fs=1, scale_to=scale_to) + assert SFT.fac_psd == fac_psd + assert SFT.fac_magnitude == fac_mag + # increase coverage by accessing properties twice: + assert SFT.fac_psd == fac_psd + assert SFT.fac_magnitude == fac_mag + + x = np.fft.irfft([0, 0, 7, 0, 0, 0, 0]) # periodic signal + Sx = SFT.stft(x) + Sx_mag, Sx_psd = Sx * SFT.fac_magnitude, Sx * SFT.fac_psd + + SFT.scale_to('magnitude') + x_mag = SFT.istft(Sx_mag, k1=len(x)) + xp_assert_close(x_mag, x) + + SFT.scale_to('psd') + x_psd = SFT.istft(Sx_psd, k1=len(x)) + xp_assert_close(x_psd, x) + + +def test_scale_to(): + """Verify `scale_to()` method.""" + SFT = ShortTimeFFT(np.ones(4) * 2, hop=4, fs=1, scale_to=None) + + SFT.scale_to('magnitude') + assert SFT.scaling == 'magnitude' + assert SFT.fac_psd == 2.0 + assert SFT.fac_magnitude == 1 + + SFT.scale_to('psd') + assert SFT.scaling == 'psd' + assert SFT.fac_psd == 1 + assert SFT.fac_magnitude == 0.5 + + SFT.scale_to('psd') # needed for coverage + + for scale, s_fac in zip(('magnitude', 'psd'), (8, 4)): + SFT = ShortTimeFFT(np.ones(4) * 2, hop=4, fs=1, scale_to=None) + dual_win = SFT.dual_win.copy() + + SFT.scale_to(cast(Literal['magnitude', 'psd'], scale)) + xp_assert_close(SFT.dual_win, dual_win * s_fac) + + +def test_x_slices_padding(): + """Verify padding. + + The reference arrays were taken from the docstrings of `zero_ext`, + `const_ext`, `odd_ext()`, and `even_ext()` from the _array_tools module. + """ + SFT = ShortTimeFFT(np.ones(5), hop=4, fs=1) + x = np.array([[1, 2, 3, 4, 5], [0, 1, 4, 9, 16]], dtype=float) + d = {'zeros': [[[0, 0, 1, 2, 3], [0, 0, 0, 1, 4]], + [[3, 4, 5, 0, 0], [4, 9, 16, 0, 0]]], + 'edge': [[[1, 1, 1, 2, 3], [0, 0, 0, 1, 4]], + [[3, 4, 5, 5, 5], [4, 9, 16, 16, 16]]], + 'even': [[[3, 2, 1, 2, 3], [4, 1, 0, 1, 4]], + [[3, 4, 5, 4, 3], [4, 9, 16, 9, 4]]], + 'odd': [[[-1, 0, 1, 2, 3], [-4, -1, 0, 1, 4]], + [[3, 4, 5, 6, 7], [4, 9, 16, 23, 28]]]} + for p_, xx in d.items(): + gen = SFT._x_slices(np.array(x), 0, 0, 2, padding=cast(PAD_TYPE, p_)) + yy = np.array([y_.copy() for y_ in gen]) # due to inplace copying + xx = np.asarray(xx, dtype=np.float64) + xp_assert_equal(yy, xx, err_msg=f"Failed '{p_}' padding.") + + +def test_invertible(): + """Verify `invertible` property. """ + SFT = ShortTimeFFT(np.ones(8), hop=4, fs=1) + assert SFT.invertible + SFT = ShortTimeFFT(np.ones(8), hop=9, fs=1) + assert not SFT.invertible + + +def test_border_values(): + """Ensure that minimum and maximum values of slices are correct.""" + SFT = ShortTimeFFT(np.ones(8), hop=4, fs=1) + assert SFT.p_min == 0 + assert SFT.k_min == -4 + assert SFT.lower_border_end == (4, 1) + assert SFT.lower_border_end == (4, 1) # needed to test caching + assert SFT.p_max(10) == 4 + assert SFT.k_max(10) == 16 + assert SFT.upper_border_begin(10) == (4, 2) + # Raise exceptions: + with pytest.raises(ValueError, match="^Parameter n must be"): + SFT.upper_border_begin(3) + with pytest.raises(ValueError, match="^Parameter n must be"): + SFT._post_padding(3) + +def test_border_values_exotic(): + """Ensure that the border calculations are correct for windows with + zeros. """ + w = np.array([0, 0, 0, 0, 0, 0, 0, 1.]) + SFT = ShortTimeFFT(w, hop=1, fs=1) + assert SFT.lower_border_end == (0, 0) + + SFT = ShortTimeFFT(np.flip(w), hop=20, fs=1) + assert SFT.upper_border_begin(4) == (16, 1) + assert SFT.upper_border_begin(5) == (16, 1) + assert SFT.upper_border_begin(23) == (36, 2) + assert SFT.upper_border_begin(24) == (36, 2) + assert SFT.upper_border_begin(25) == (36, 2) + + SFT._hop = -1 # provoke unreachable line + with pytest.raises(RuntimeError): + _ = SFT.k_max(4) + with pytest.raises(RuntimeError): + _ = SFT.k_min + + +def test_t(): + """Verify that the times of the slices are correct. """ + SFT = ShortTimeFFT(np.ones(8), hop=4, fs=2) + assert SFT.T == 1/2 + assert SFT.fs == 2. + assert SFT.delta_t == 4 * 1/2 + t_stft = np.arange(0, SFT.p_max(10)) * SFT.delta_t + xp_assert_equal(SFT.t(10), t_stft) + xp_assert_equal(SFT.t(10, 1, 3), t_stft[1:3]) + SFT.T = 1/4 + assert SFT.T == 1/4 + assert SFT.fs == 4 + SFT.fs = 1/8 + assert SFT.fs == 1/8 + assert SFT.T == 8 + + +@pytest.mark.parametrize('fft_mode, f', + [('onesided', [0., 1., 2.]), + ('onesided2X', [0., 1., 2.]), + ('twosided', [0., 1., 2., -2., -1.]), + ('centered', [-2., -1., 0., 1., 2.])]) +def test_f(fft_mode: FFT_MODE_TYPE, f): + """Verify the frequency values property `f`.""" + SFT = ShortTimeFFT(np.ones(5), hop=4, fs=5, fft_mode=fft_mode, + scale_to='psd') + xp_assert_equal(SFT.f, f) + + +@pytest.mark.parametrize('n', [20, 21]) +@pytest.mark.parametrize('m', [5, 6]) +@pytest.mark.parametrize('fft_mode', ['onesided', 'centered']) +def test_extent(n, m, fft_mode: FFT_MODE_TYPE): + """Ensure that the `extent()` method is correct. """ + SFT = ShortTimeFFT(np.ones(m), hop=m, fs=m, fft_mode=fft_mode) + + t0 = SFT.t(n)[0] # first timestamp + t1 = SFT.t(n)[-1] + SFT.delta_t # last timestamp + 1 + t0c, t1c = t0 - SFT.delta_t / 2, t1 - SFT.delta_t / 2 # centered timestamps + + f0 = SFT.f[0] # first frequency + f1 = SFT.f[-1] + SFT.delta_f # last frequency + 1 + f0c, f1c = f0 - SFT.delta_f / 2, f1 - SFT.delta_f / 2 # centered frequencies + + assert SFT.extent(n, 'tf', False) == (t0, t1, f0, f1) + assert SFT.extent(n, 'ft', False) == (f0, f1, t0, t1) + assert SFT.extent(n, 'tf', True) == (t0c, t1c, f0c, f1c) + assert SFT.extent(n, 'ft', True) == (f0c, f1c, t0c, t1c) + + +def test_spectrogram(): + """Verify spectrogram and cross-spectrogram methods. """ + SFT = ShortTimeFFT(np.ones(8), hop=4, fs=1) + x, y = np.ones(10), np.arange(10) + X, Y = SFT.stft(x), SFT.stft(y) + xp_assert_close(SFT.spectrogram(x), X.real**2+X.imag**2) + xp_assert_close(SFT.spectrogram(x, y), X * Y.conj()) + + +@pytest.mark.parametrize('n', [8, 9]) +def test_fft_func_roundtrip(n: int): + """Test roundtrip `ifft_func(fft_func(x)) == x` for all permutations of + relevant parameters. """ + np.random.seed(2394795) + x0 = np.random.rand(n) + w, h_n = np.ones(n), 4 + + pp = dict( + fft_mode=get_args(FFT_MODE_TYPE), + mfft=[None, n, n+1, n+2], + scaling=[None, 'magnitude', 'psd'], + phase_shift=[None, -n+1, 0, n // 2, n-1]) + for f_typ, mfft, scaling, phase_shift in product(*pp.values()): + if f_typ == 'onesided2X' and scaling is None: + continue # this combination is forbidden + SFT = ShortTimeFFT(w, h_n, fs=n, fft_mode=f_typ, mfft=mfft, + scale_to=scaling, phase_shift=phase_shift) + X0 = SFT._fft_func(x0) + x1 = SFT._ifft_func(X0) + xp_assert_close(x0.astype(x1.dtype), x1, + err_msg="_fft_func() roundtrip failed for " + + f"{f_typ=}, {mfft=}, {scaling=}, {phase_shift=}") + + SFT = ShortTimeFFT(w, h_n, fs=1) + SFT._fft_mode = 'invalid_fft' # type: ignore + with pytest.raises(RuntimeError): + SFT._fft_func(x0) + with pytest.raises(RuntimeError): + SFT._ifft_func(x0) + + +@pytest.mark.parametrize('i', range(19)) +def test_impulse_roundtrip(i): + """Roundtrip for an impulse being at different positions `i`.""" + n = 19 + w, h_n = np.ones(8), 3 + x = np.zeros(n) + x[i] = 1 + + SFT = ShortTimeFFT(w, hop=h_n, fs=1, scale_to=None, phase_shift=None) + Sx = SFT.stft(x) + # test slicing the input signal into two parts: + n_q = SFT.nearest_k_p(n // 2) + Sx0 = SFT.stft(x[:n_q], padding='zeros') + Sx1 = SFT.stft(x[n_q:], padding='zeros') + q0_ub = SFT.upper_border_begin(n_q)[1] - SFT.p_min + q1_le = SFT.lower_border_end[1] - SFT.p_min + xp_assert_close(Sx0[:, :q0_ub], Sx[:, :q0_ub], err_msg=f"{i=}") + xp_assert_close(Sx1[:, q1_le:], Sx[:, q1_le-Sx1.shape[1]:], + err_msg=f"{i=}") + + Sx01 = np.hstack((Sx0[:, :q0_ub], + Sx0[:, q0_ub:] + Sx1[:, :q1_le], + Sx1[:, q1_le:])) + xp_assert_close(Sx, Sx01, atol=1e-8, err_msg=f"{i=}") + + y = SFT.istft(Sx, 0, n) + xp_assert_close(y, x, atol=1e-8, err_msg=f"{i=}") + y0 = SFT.istft(Sx, 0, n//2) + xp_assert_close(x[:n//2], y0, atol=1e-8, err_msg=f"{i=}") + y1 = SFT.istft(Sx, n // 2, n) + xp_assert_close(x[n // 2:], y1, atol=1e-8, err_msg=f"{i=}") + + +@pytest.mark.parametrize('hop', [1, 7, 8]) +def test_asymmetric_window_roundtrip(hop: int): + """An asymmetric window could uncover indexing problems. """ + np.random.seed(23371) + + w = np.arange(16) / 8 # must be of type float + w[len(w)//2:] = 1 + SFT = ShortTimeFFT(w, hop, fs=1) + + x = 10 * np.random.randn(64) + Sx = SFT.stft(x) + x1 = SFT.istft(Sx, k1=len(x)) + xp_assert_close(x1, x1, err_msg="Roundtrip for asymmetric window with " + + f" {hop=} failed!") + + +@pytest.mark.parametrize('m_num', [6, 7]) +def test_minimal_length_signal(m_num): + """Verify that the shortest allowed signal works. """ + SFT = ShortTimeFFT(np.ones(m_num), m_num//2, fs=1) + n = math.ceil(m_num/2) + x = np.ones(n) + Sx = SFT.stft(x) + x1 = SFT.istft(Sx, k1=n) + xp_assert_close(x1, x, err_msg=f"Roundtrip minimal length signal ({n=})" + + f" for {m_num} sample window failed!") + with pytest.raises(ValueError, match=rf"len\(x\)={n-1} must be >= ceil.*"): + SFT.stft(x[:-1]) + with pytest.raises(ValueError, match=rf"S.shape\[t_axis\]={Sx.shape[1]-1}" + f" needs to have at least {Sx.shape[1]} slices"): + SFT.istft(Sx[:, :-1], k1=n) + + +def test_tutorial_stft_sliding_win(): + """Verify example in "Sliding Windows" subsection from the "User Guide". + + In :ref:`tutorial_stft_sliding_win` (file ``signal.rst``) of the + :ref:`user_guide` the behavior the border behavior of + ``ShortTimeFFT(np.ones(6), 2, fs=1)`` with a 50 sample signal is discussed. + This test verifies the presented indexes. + """ + SFT = ShortTimeFFT(np.ones(6), 2, fs=1) + + # Lower border: + assert SFT.m_num_mid == 3, f"Slice middle is not 3 but {SFT.m_num_mid=}" + assert SFT.p_min == -1, f"Lowest slice {SFT.p_min=} is not -1" + assert SFT.k_min == -5, f"Lowest slice sample {SFT.p_min=} is not -5" + k_lb, p_lb = SFT.lower_border_end + assert p_lb == 2, f"First unaffected slice {p_lb=} is not 2" + assert k_lb == 5, f"First unaffected sample {k_lb=} is not 5" + + n = 50 # upper signal border + assert (p_max := SFT.p_max(n)) == 27, f"Last slice {p_max=} must be 27" + assert (k_max := SFT.k_max(n)) == 55, f"Last sample {k_max=} must be 55" + k_ub, p_ub = SFT.upper_border_begin(n) + assert p_ub == 24, f"First upper border slice {p_ub=} must be 24" + assert k_ub == 45, f"First upper border slice {k_ub=} must be 45" + + +def test_tutorial_stft_legacy_stft(): + """Verify STFT example in "Comparison with Legacy Implementation" from the + "User Guide". + + In :ref:`tutorial_stft_legacy_stft` (file ``signal.rst``) of the + :ref:`user_guide` the legacy and the new implementation are compared. + """ + fs, N = 200, 1001 # # 200 Hz sampling rate for 5 s signal + t_z = np.arange(N) / fs # time indexes for signal + z = np.exp(2j*np.pi * 70 * (t_z - 0.2 * t_z ** 2)) # complex-valued chirp + + nperseg, noverlap = 50, 40 + win = ('gaussian', 1e-2 * fs) # Gaussian with 0.01 s standard deviation + + # Legacy STFT: + f0_u, t0, Sz0_u = stft(z, fs, win, nperseg, noverlap, + return_onesided=False, scaling='spectrum') + Sz0 = fftshift(Sz0_u, axes=0) + + # New STFT: + SFT = ShortTimeFFT.from_window(win, fs, nperseg, noverlap, + fft_mode='centered', + scale_to='magnitude', phase_shift=None) + Sz1 = SFT.stft(z) + + xp_assert_close(Sz0, Sz1[:, 2:-1]) + + xp_assert_close((abs(Sz1[:, 1]).min(), abs(Sz1[:, 1]).max()), + (6.925060911593139e-07, 8.00271269218721e-07)) + + t0_r, z0_r = istft(Sz0_u, fs, win, nperseg, noverlap, input_onesided=False, + scaling='spectrum') + z1_r = SFT.istft(Sz1, k1=N) + assert len(z0_r) == N + 9 + xp_assert_close(z0_r[:N], z) + xp_assert_close(z1_r, z) + + # Spectrogram is just the absolute square of th STFT: + xp_assert_close(SFT.spectrogram(z), abs(Sz1) ** 2) + + +def test_tutorial_stft_legacy_spectrogram(): + """Verify spectrogram example in "Comparison with Legacy Implementation" + from the "User Guide". + + In :ref:`tutorial_stft_legacy_stft` (file ``signal.rst``) of the + :ref:`user_guide` the legacy and the new implementation are compared. + """ + fs, N = 200, 1001 # 200 Hz sampling rate for almost 5 s signal + t_z = np.arange(N) / fs # time indexes for signal + z = np.exp(2j*np.pi*70 * (t_z - 0.2*t_z**2)) # complex-valued sweep + + nperseg, noverlap = 50, 40 + win = ('gaussian', 1e-2 * fs) # Gaussian with 0.01 s standard dev. + + # Legacy spectrogram: + f2_u, t2, Sz2_u = spectrogram(z, fs, win, nperseg, noverlap, detrend=None, + return_onesided=False, scaling='spectrum', + mode='complex') + + f2, Sz2 = fftshift(f2_u), fftshift(Sz2_u, axes=0) + + # New STFT: + SFT = ShortTimeFFT.from_window(win, fs, nperseg, noverlap, + fft_mode='centered', scale_to='magnitude', + phase_shift=None) + Sz3 = SFT.stft(z, p0=0, p1=(N-noverlap) // SFT.hop, k_offset=nperseg // 2) + t3 = SFT.t(N, p0=0, p1=(N-noverlap) // SFT.hop, k_offset=nperseg // 2) + + xp_assert_close(t2, t3) + xp_assert_close(f2, SFT.f) + xp_assert_close(Sz2, Sz3) + + +def test_permute_axes(): + """Verify correctness of four-dimensional signal by permuting its + shape. """ + n = 25 + SFT = ShortTimeFFT(np.ones(8)/8, hop=3, fs=n) + x0 = np.arange(n, dtype=np.float64) + Sx0 = SFT.stft(x0) + Sx0 = Sx0.reshape((Sx0.shape[0], 1, 1, 1, Sx0.shape[-1])) + SxT = np.moveaxis(Sx0, (0, -1), (-1, 0)) + + atol = 2 * np.finfo(SFT.win.dtype).resolution + for i in range(4): + y = np.reshape(x0, np.roll((n, 1, 1, 1), i)) + Sy = SFT.stft(y, axis=i) + xp_assert_close(Sy, np.moveaxis(Sx0, 0, i)) + + yb0 = SFT.istft(Sy, k1=n, f_axis=i) + xp_assert_close(yb0, y, atol=atol) + # explicit t-axis parameter (for coverage): + yb1 = SFT.istft(Sy, k1=n, f_axis=i, t_axis=Sy.ndim-1) + xp_assert_close(yb1, y, atol=atol) + + SyT = np.moveaxis(Sy, (i, -1), (-1, i)) + xp_assert_close(SyT, np.moveaxis(SxT, 0, i)) + + ybT = SFT.istft(SyT, k1=n, t_axis=i, f_axis=-1) + xp_assert_close(ybT, y, atol=atol) + + +@pytest.mark.parametrize("fft_mode", + ('twosided', 'centered', 'onesided', 'onesided2X')) +def test_roundtrip_multidimensional(fft_mode: FFT_MODE_TYPE): + """Test roundtrip of a multidimensional input signal versus its components. + + This test can uncover potential problems with `fftshift()`. + """ + n = 9 + x = np.arange(4*n*2, dtype=np.float64).reshape(4, n, 2) + SFT = ShortTimeFFT(get_window('hann', 4), hop=2, fs=1, + scale_to='magnitude', fft_mode=fft_mode) + Sx = SFT.stft(x, axis=1) + y = SFT.istft(Sx, k1=n, f_axis=1, t_axis=-1) + xp_assert_close(y, x.astype(y.dtype), err_msg='Multidim. roundtrip failed!') + + for i, j in product(range(x.shape[0]), range(x.shape[2])): + y_ = SFT.istft(Sx[i, :, j, :], k1=n) + xp_assert_close(y_, x[i, :, j].astype(y_.dtype), + err_msg="Multidim. roundtrip for component " + + f"x[{i}, :, {j}] and {fft_mode=} failed!") + +@pytest.mark.parametrize("phase_shift", (0, 4, None)) +def test_roundtrip_two_dimensional(phase_shift: int|None): + """Test roundtrip of a 2 channel input signal with `mfft` set with different + values for `phase_shift` + + Tests for Issue https://github.com/scipy/scipy/issues/21671 + """ + n = 21 + SFT = ShortTimeFFT.from_window('hann', fs=1, nperseg=13, noverlap=7, + mfft=16, phase_shift=phase_shift) + x = np.arange(2*n, dtype=float).reshape(2, n) + Sx = SFT.stft(x) + y = SFT.istft(Sx, k1=n) + xp_assert_close(y, x, atol=2 * np.finfo(SFT.win.dtype).resolution, + err_msg='2-dim. roundtrip failed!') + + +@pytest.mark.parametrize('window, n, nperseg, noverlap', + [('boxcar', 100, 10, 0), # Test no overlap + ('boxcar', 100, 10, 9), # Test high overlap + ('bartlett', 101, 51, 26), # Test odd nperseg + ('hann', 1024, 256, 128), # Test defaults + (('tukey', 0.5), 1152, 256, 64), # Test Tukey + ('hann', 1024, 256, 255), # Test overlapped hann + ('boxcar', 100, 10, 3), # NOLA True, COLA False + ('bartlett', 101, 51, 37), # NOLA True, COLA False + ('hann', 1024, 256, 127), # NOLA True, COLA False + # NOLA True, COLA False: + (('tukey', 0.5), 1152, 256, 14), + ('hann', 1024, 256, 5)]) # NOLA True, COLA False +def test_roundtrip_windows(window, n: int, nperseg: int, noverlap: int): + """Roundtrip test adapted from `test_spectral.TestSTFT`. + + The parameters are taken from the methods test_roundtrip_real(), + test_roundtrip_nola_not_cola(), test_roundtrip_float32(), + test_roundtrip_complex(). + """ + np.random.seed(2394655) + + w = get_window(window, nperseg) + SFT = ShortTimeFFT(w, nperseg - noverlap, fs=1, fft_mode='twosided', + phase_shift=None) + + z = 10 * np.random.randn(n) + 10j * np.random.randn(n) + Sz = SFT.stft(z) + z1 = SFT.istft(Sz, k1=len(z)) + xp_assert_close(z, z1, err_msg="Roundtrip for complex values failed") + + x = 10 * np.random.randn(n) + Sx = SFT.stft(x) + x1 = SFT.istft(Sx, k1=len(z)) + xp_assert_close(x.astype(np.complex128), x1, + err_msg="Roundtrip for float values failed") + + x32 = x.astype(np.float32) + Sx32 = SFT.stft(x32) + x32_1 = SFT.istft(Sx32, k1=len(x32)) + x32_1_r = x32_1.real + xp_assert_close(x32, x32_1_r.astype(np.float32), + err_msg="Roundtrip for 32 Bit float values failed") + xp_assert_close(x32.imag, np.zeros_like(x32.imag), + err_msg="Roundtrip for 32 Bit float values failed") + + +@pytest.mark.parametrize('signal_type', ('real', 'complex')) +def test_roundtrip_complex_window(signal_type): + """Test roundtrip for complex-valued window function + + The purpose of this test is to check if the dual window is calculated + correctly for complex-valued windows. + """ + np.random.seed(1354654) + win = np.exp(2j*np.linspace(0, np.pi, 8)) + SFT = ShortTimeFFT(win, 3, fs=1, fft_mode='twosided') + + z = 10 * np.random.randn(11) + if signal_type == 'complex': + z = z + 2j * z + Sz = SFT.stft(z) + z1 = SFT.istft(Sz, k1=len(z)) + xp_assert_close(z.astype(np.complex128), z1, + err_msg="Roundtrip for complex-valued window failed") + + +def test_average_all_segments(): + """Compare `welch` function with stft mean. + + Ported from `TestSpectrogram.test_average_all_segments` from file + ``test__spectral.py``. + """ + x = np.random.randn(1024) + + fs = 1.0 + window = ('tukey', 0.25) + nperseg, noverlap = 16, 2 + fw, Pw = welch(x, fs, window, nperseg, noverlap) + SFT = ShortTimeFFT.from_window(window, fs, nperseg, noverlap, + fft_mode='onesided2X', scale_to='psd', + phase_shift=None) + # `welch` positions the window differently than the STFT: + P = SFT.spectrogram(x, detr='constant', p0=0, + p1=(len(x)-noverlap)//SFT.hop, k_offset=nperseg//2) + + xp_assert_close(SFT.f, fw) + xp_assert_close(np.mean(P, axis=-1), Pw) + + +@pytest.mark.parametrize('window, N, nperseg, noverlap, mfft', + # from test_roundtrip_padded_FFT: + [('hann', 1024, 256, 128, 512), + ('hann', 1024, 256, 128, 501), + ('boxcar', 100, 10, 0, 33), + (('tukey', 0.5), 1152, 256, 64, 1024), + # from test_roundtrip_padded_signal: + ('boxcar', 101, 10, 0, None), + ('hann', 1000, 256, 128, None), + # from test_roundtrip_boundary_extension: + ('boxcar', 100, 10, 0, None), + ('boxcar', 100, 10, 9, None)]) +@pytest.mark.parametrize('padding', get_args(PAD_TYPE)) +def test_stft_padding_roundtrip(window, N: int, nperseg: int, noverlap: int, + mfft: int, padding): + """Test the parameter 'padding' of `stft` with roundtrips. + + The STFT parametrizations were taken from the methods + `test_roundtrip_padded_FFT`, `test_roundtrip_padded_signal` and + `test_roundtrip_boundary_extension` from class `TestSTFT` in file + ``test_spectral.py``. Note that the ShortTimeFFT does not need the + concept of "boundary extension". + """ + x = normal_distribution.rvs(size=N, random_state=2909) # real signal + z = x * np.exp(1j * np.pi / 4) # complex signal + + SFT = ShortTimeFFT.from_window(window, 1, nperseg, noverlap, + fft_mode='twosided', mfft=mfft) + Sx = SFT.stft(x, padding=padding) + x1 = SFT.istft(Sx, k1=N) + xp_assert_close(x1, x.astype(np.complex128), + err_msg=f"Failed real roundtrip with '{padding}' padding") + + Sz = SFT.stft(z, padding=padding) + z1 = SFT.istft(Sz, k1=N) + xp_assert_close(z1, z, err_msg="Failed complex roundtrip with " + + f" '{padding}' padding") + + +@pytest.mark.parametrize('N_x', (128, 129, 255, 256, 1337)) # signal length +@pytest.mark.parametrize('w_size', (128, 256)) # window length +@pytest.mark.parametrize('t_step', (4, 64)) # SFT time hop +@pytest.mark.parametrize('f_c', (7., 23.)) # frequency of input sine +def test_energy_conservation(N_x: int, w_size: int, t_step: int, f_c: float): + """Test if a `psd`-scaled STFT conserves the L2 norm. + + This test is adapted from MNE-Python [1]_. Besides being battle-tested, + this test has the benefit of using non-standard window including + non-positive values and a 2d input signal. + + Since `ShortTimeFFT` requires the signal length `N_x` to be at least the + window length `w_size`, the parameter `N_x` was changed from + ``(127, 128, 255, 256, 1337)`` to ``(128, 129, 255, 256, 1337)`` to be + more useful. + + .. [1] File ``test_stft.py`` of MNE-Python + https://github.com/mne-tools/mne-python/blob/main/mne/time_frequency/tests/test_stft.py + """ + window = np.sin(np.arange(.5, w_size + .5) / w_size * np.pi) + SFT = ShortTimeFFT(window, t_step, fs=1000, fft_mode='onesided2X', + scale_to='psd') + atol = 2*np.finfo(window.dtype).resolution + N_x = max(N_x, w_size) # minimal sing + # Test with low frequency signal + t = np.arange(N_x).astype(np.float64) + x = np.sin(2 * np.pi * f_c * t * SFT.T) + x = np.array([x, x + 1.]) + X = SFT.stft(x) + xp = SFT.istft(X, k1=N_x) + + max_freq = SFT.f[np.argmax(np.sum(np.abs(X[0]) ** 2, axis=1))] + + assert X.shape[1] == SFT.f_pts + assert np.all(SFT.f >= 0.) + assert np.abs(max_freq - f_c) < 1. + xp_assert_close(x, xp, atol=atol) + + # check L2-norm squared (i.e., energy) conservation: + E_x = np.sum(x**2, axis=-1) * SFT.T # numerical integration + aX2 = X.real**2 + X.imag.real**2 + E_X = np.sum(np.sum(aX2, axis=-1) * SFT.delta_t, axis=-1) * SFT.delta_f + xp_assert_close(E_X, E_x, atol=atol) + + # Test with random signal + np.random.seed(2392795) + x = np.random.randn(2, N_x) + X = SFT.stft(x) + xp = SFT.istft(X, k1=N_x) + + assert X.shape[1] == SFT.f_pts + assert np.all(SFT.f >= 0.) + assert np.abs(max_freq - f_c) < 1. + xp_assert_close(x, xp, atol=atol) + + # check L2-norm squared (i.e., energy) conservation: + E_x = np.sum(x**2, axis=-1) * SFT.T # numeric integration + aX2 = X.real ** 2 + X.imag.real ** 2 + E_X = np.sum(np.sum(aX2, axis=-1) * SFT.delta_t, axis=-1) * SFT.delta_f + xp_assert_close(E_X, E_x, atol=atol) + + # Try with empty array + x = np.zeros((0, N_x)) + X = SFT.stft(x) + xp = SFT.istft(X, k1=N_x) + assert xp.shape == x.shape diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_signaltools.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_signaltools.py new file mode 100644 index 0000000000000000000000000000000000000000..7953fcb5ff7634f1c01d96920c1dd069cacf0c0c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_signaltools.py @@ -0,0 +1,3933 @@ +import sys + +from concurrent.futures import ThreadPoolExecutor, as_completed +from decimal import Decimal +from itertools import product +from math import gcd + +import pytest +from pytest import raises as assert_raises +from numpy.testing import ( + assert_equal, + assert_almost_equal, assert_array_equal, assert_array_almost_equal, + assert_allclose, assert_, assert_array_less, + suppress_warnings) +from numpy import array, arange +import numpy as np + +from scipy import fft as sp_fft +from scipy.ndimage import correlate1d +from scipy.optimize import fmin, linear_sum_assignment +from scipy import signal +from scipy.signal import ( + correlate, correlate2d, correlation_lags, convolve, convolve2d, + fftconvolve, oaconvolve, choose_conv_method, envelope, + hilbert, hilbert2, lfilter, lfilter_zi, filtfilt, butter, zpk2tf, zpk2sos, + invres, invresz, vectorstrength, lfiltic, tf2sos, sosfilt, sosfiltfilt, + sosfilt_zi, tf2zpk, BadCoefficients, detrend, unique_roots, residue, + residuez) +from scipy.signal.windows import hann +from scipy.signal._signaltools import (_filtfilt_gust, _compute_factors, + _group_poles) +from scipy.signal._upfirdn import _upfirdn_modes +from scipy._lib import _testutils +from scipy._lib._array_api import xp_assert_close +from scipy._lib._util import ComplexWarning, np_long, np_ulong + + +class _TestConvolve: + + def test_basic(self): + a = [3, 4, 5, 6, 5, 4] + b = [1, 2, 3] + c = convolve(a, b) + assert_array_equal(c, array([3, 10, 22, 28, 32, 32, 23, 12])) + + def test_same(self): + a = [3, 4, 5] + b = [1, 2, 3, 4] + c = convolve(a, b, mode="same") + assert_array_equal(c, array([10, 22, 34])) + + def test_same_eq(self): + a = [3, 4, 5] + b = [1, 2, 3] + c = convolve(a, b, mode="same") + assert_array_equal(c, array([10, 22, 22])) + + def test_complex(self): + x = array([1 + 1j, 2 + 1j, 3 + 1j]) + y = array([1 + 1j, 2 + 1j]) + z = convolve(x, y) + assert_array_equal(z, array([2j, 2 + 6j, 5 + 8j, 5 + 5j])) + + def test_zero_rank(self): + a = 1289 + b = 4567 + c = convolve(a, b) + assert_equal(c, a * b) + + def test_broadcastable(self): + a = np.arange(27).reshape(3, 3, 3) + b = np.arange(3) + for i in range(3): + b_shape = [1]*3 + b_shape[i] = 3 + x = convolve(a, b.reshape(b_shape), method='direct') + y = convolve(a, b.reshape(b_shape), method='fft') + assert_allclose(x, y) + + def test_single_element(self): + a = array([4967]) + b = array([3920]) + c = convolve(a, b) + assert_equal(c, a * b) + + def test_2d_arrays(self): + a = [[1, 2, 3], [3, 4, 5]] + b = [[2, 3, 4], [4, 5, 6]] + c = convolve(a, b) + d = array([[2, 7, 16, 17, 12], + [10, 30, 62, 58, 38], + [12, 31, 58, 49, 30]]) + assert_array_equal(c, d) + + def test_input_swapping(self): + small = arange(8).reshape(2, 2, 2) + big = 1j * arange(27).reshape(3, 3, 3) + big += arange(27)[::-1].reshape(3, 3, 3) + + out_array = array( + [[[0 + 0j, 26 + 0j, 25 + 1j, 24 + 2j], + [52 + 0j, 151 + 5j, 145 + 11j, 93 + 11j], + [46 + 6j, 133 + 23j, 127 + 29j, 81 + 23j], + [40 + 12j, 98 + 32j, 93 + 37j, 54 + 24j]], + + [[104 + 0j, 247 + 13j, 237 + 23j, 135 + 21j], + [282 + 30j, 632 + 96j, 604 + 124j, 330 + 86j], + [246 + 66j, 548 + 180j, 520 + 208j, 282 + 134j], + [142 + 66j, 307 + 161j, 289 + 179j, 153 + 107j]], + + [[68 + 36j, 157 + 103j, 147 + 113j, 81 + 75j], + [174 + 138j, 380 + 348j, 352 + 376j, 186 + 230j], + [138 + 174j, 296 + 432j, 268 + 460j, 138 + 278j], + [70 + 138j, 145 + 323j, 127 + 341j, 63 + 197j]], + + [[32 + 72j, 68 + 166j, 59 + 175j, 30 + 100j], + [68 + 192j, 139 + 433j, 117 + 455j, 57 + 255j], + [38 + 222j, 73 + 499j, 51 + 521j, 21 + 291j], + [12 + 144j, 20 + 318j, 7 + 331j, 0 + 182j]]]) + + assert_array_equal(convolve(small, big, 'full'), out_array) + assert_array_equal(convolve(big, small, 'full'), out_array) + assert_array_equal(convolve(small, big, 'same'), + out_array[1:3, 1:3, 1:3]) + assert_array_equal(convolve(big, small, 'same'), + out_array[0:3, 0:3, 0:3]) + assert_array_equal(convolve(small, big, 'valid'), + out_array[1:3, 1:3, 1:3]) + assert_array_equal(convolve(big, small, 'valid'), + out_array[1:3, 1:3, 1:3]) + + def test_invalid_params(self): + a = [3, 4, 5] + b = [1, 2, 3] + assert_raises(ValueError, convolve, a, b, mode='spam') + assert_raises(ValueError, convolve, a, b, mode='eggs', method='fft') + assert_raises(ValueError, convolve, a, b, mode='ham', method='direct') + assert_raises(ValueError, convolve, a, b, mode='full', method='bacon') + assert_raises(ValueError, convolve, a, b, mode='same', method='bacon') + + +class TestConvolve(_TestConvolve): + + def test_valid_mode2(self): + # See gh-5897 + a = [1, 2, 3, 6, 5, 3] + b = [2, 3, 4, 5, 3, 4, 2, 2, 1] + expected = [70, 78, 73, 65] + + out = convolve(a, b, 'valid') + assert_array_equal(out, expected) + + out = convolve(b, a, 'valid') + assert_array_equal(out, expected) + + a = [1 + 5j, 2 - 1j, 3 + 0j] + b = [2 - 3j, 1 + 0j] + expected = [2 - 3j, 8 - 10j] + + out = convolve(a, b, 'valid') + assert_array_equal(out, expected) + + out = convolve(b, a, 'valid') + assert_array_equal(out, expected) + + def test_same_mode(self): + a = [1, 2, 3, 3, 1, 2] + b = [1, 4, 3, 4, 5, 6, 7, 4, 3, 2, 1, 1, 3] + c = convolve(a, b, 'same') + d = array([57, 61, 63, 57, 45, 36]) + assert_array_equal(c, d) + + def test_invalid_shapes(self): + # By "invalid," we mean that no one + # array has dimensions that are all at + # least as large as the corresponding + # dimensions of the other array. This + # setup should throw a ValueError. + a = np.arange(1, 7).reshape((2, 3)) + b = np.arange(-6, 0).reshape((3, 2)) + + assert_raises(ValueError, convolve, *(a, b), **{'mode': 'valid'}) + assert_raises(ValueError, convolve, *(b, a), **{'mode': 'valid'}) + + def test_convolve_method(self, n=100): + # this types data structure was manually encoded instead of + # using custom filters on the soon-to-be-removed np.sctypes + types = {'uint16', 'uint64', 'int64', 'int32', + 'complex128', 'float64', 'float16', + 'complex64', 'float32', 'int16', + 'uint8', 'uint32', 'int8', 'bool'} + args = [(t1, t2, mode) for t1 in types for t2 in types + for mode in ['valid', 'full', 'same']] + + # These are random arrays, which means test is much stronger than + # convolving testing by convolving two np.ones arrays + rng = np.random.RandomState(42) + array_types = {'i': rng.choice([0, 1], size=n), + 'f': rng.randn(n)} + array_types['b'] = array_types['u'] = array_types['i'] + array_types['c'] = array_types['f'] + 0.5j*array_types['f'] + + for t1, t2, mode in args: + x1 = array_types[np.dtype(t1).kind].astype(t1) + x2 = array_types[np.dtype(t2).kind].astype(t2) + + results = {key: convolve(x1, x2, method=key, mode=mode) + for key in ['fft', 'direct']} + + assert_equal(results['fft'].dtype, results['direct'].dtype) + + if 'bool' in t1 and 'bool' in t2: + assert_equal(choose_conv_method(x1, x2), 'direct') + continue + + # Found by experiment. Found approx smallest value for (rtol, atol) + # threshold to have tests pass. + if any([t in {'complex64', 'float32'} for t in [t1, t2]]): + kwargs = {'rtol': 1.0e-4, 'atol': 1e-6} + elif 'float16' in [t1, t2]: + # atol is default for np.allclose + kwargs = {'rtol': 1e-3, 'atol': 1e-3} + else: + # defaults for np.allclose (different from assert_allclose) + kwargs = {'rtol': 1e-5, 'atol': 1e-8} + + assert_allclose(results['fft'], results['direct'], **kwargs) + + def test_convolve_method_large_input(self): + # This is really a test that convolving two large integers goes to the + # direct method even if they're in the fft method. + for n in [10, 20, 50, 51, 52, 53, 54, 60, 62]: + z = np.array([2**n], dtype=np.int64) + fft = convolve(z, z, method='fft') + direct = convolve(z, z, method='direct') + + # this is the case when integer precision gets to us + # issue #6076 has more detail, hopefully more tests after resolved + if n < 50: + assert_equal(fft, direct) + assert_equal(fft, 2**(2*n)) + assert_equal(direct, 2**(2*n)) + + def test_mismatched_dims(self): + # Input arrays should have the same number of dimensions + assert_raises(ValueError, convolve, [1], 2, method='direct') + assert_raises(ValueError, convolve, 1, [2], method='direct') + assert_raises(ValueError, convolve, [1], 2, method='fft') + assert_raises(ValueError, convolve, 1, [2], method='fft') + assert_raises(ValueError, convolve, [1], [[2]]) + assert_raises(ValueError, convolve, [3], 2) + + @pytest.mark.thread_unsafe + def test_dtype_deprecation(self): + # gh-21211 + a = np.asarray([1, 2, 3, 6, 5, 3], dtype=object) + b = np.asarray([2, 3, 4, 5, 3, 4, 2, 2, 1], dtype=object) + with pytest.deprecated_call(match="dtype=object is not supported"): + convolve(a, b) + + +class _TestConvolve2d: + + def test_2d_arrays(self): + a = [[1, 2, 3], [3, 4, 5]] + b = [[2, 3, 4], [4, 5, 6]] + d = array([[2, 7, 16, 17, 12], + [10, 30, 62, 58, 38], + [12, 31, 58, 49, 30]]) + e = convolve2d(a, b) + assert_array_equal(e, d) + + def test_valid_mode(self): + e = [[2, 3, 4, 5, 6, 7, 8], [4, 5, 6, 7, 8, 9, 10]] + f = [[1, 2, 3], [3, 4, 5]] + h = array([[62, 80, 98, 116, 134]]) + + g = convolve2d(e, f, 'valid') + assert_array_equal(g, h) + + # See gh-5897 + g = convolve2d(f, e, 'valid') + assert_array_equal(g, h) + + def test_valid_mode_complx(self): + e = [[2, 3, 4, 5, 6, 7, 8], [4, 5, 6, 7, 8, 9, 10]] + f = np.array([[1, 2, 3], [3, 4, 5]], dtype=complex) + 1j + h = array([[62.+24.j, 80.+30.j, 98.+36.j, 116.+42.j, 134.+48.j]]) + + g = convolve2d(e, f, 'valid') + assert_array_almost_equal(g, h) + + # See gh-5897 + g = convolve2d(f, e, 'valid') + assert_array_equal(g, h) + + def test_fillvalue(self): + a = [[1, 2, 3], [3, 4, 5]] + b = [[2, 3, 4], [4, 5, 6]] + fillval = 1 + c = convolve2d(a, b, 'full', 'fill', fillval) + d = array([[24, 26, 31, 34, 32], + [28, 40, 62, 64, 52], + [32, 46, 67, 62, 48]]) + assert_array_equal(c, d) + + def test_fillvalue_errors(self): + msg = "could not cast `fillvalue` directly to the output " + with np.testing.suppress_warnings() as sup: + sup.filter(ComplexWarning, "Casting complex values") + with assert_raises(ValueError, match=msg): + convolve2d([[1]], [[1, 2]], fillvalue=1j) + + msg = "`fillvalue` must be scalar or an array with " + with assert_raises(ValueError, match=msg): + convolve2d([[1]], [[1, 2]], fillvalue=[1, 2]) + + def test_fillvalue_empty(self): + # Check that fillvalue being empty raises an error: + assert_raises(ValueError, convolve2d, [[1]], [[1, 2]], + fillvalue=[]) + + def test_wrap_boundary(self): + a = [[1, 2, 3], [3, 4, 5]] + b = [[2, 3, 4], [4, 5, 6]] + c = convolve2d(a, b, 'full', 'wrap') + d = array([[80, 80, 74, 80, 80], + [68, 68, 62, 68, 68], + [80, 80, 74, 80, 80]]) + assert_array_equal(c, d) + + def test_sym_boundary(self): + a = [[1, 2, 3], [3, 4, 5]] + b = [[2, 3, 4], [4, 5, 6]] + c = convolve2d(a, b, 'full', 'symm') + d = array([[34, 30, 44, 62, 66], + [52, 48, 62, 80, 84], + [82, 78, 92, 110, 114]]) + assert_array_equal(c, d) + + @pytest.mark.parametrize('func', [convolve2d, correlate2d]) + @pytest.mark.parametrize('boundary, expected', + [('symm', [[37.0, 42.0, 44.0, 45.0]]), + ('wrap', [[43.0, 44.0, 42.0, 39.0]])]) + def test_same_with_boundary(self, func, boundary, expected): + # Test boundary='symm' and boundary='wrap' with a "long" kernel. + # The size of the kernel requires that the values in the "image" + # be extended more than once to handle the requested boundary method. + # This is a regression test for gh-8684 and gh-8814. + image = np.array([[2.0, -1.0, 3.0, 4.0]]) + kernel = np.ones((1, 21)) + result = func(image, kernel, mode='same', boundary=boundary) + # The expected results were calculated "by hand". Because the + # kernel is all ones, the same result is expected for convolve2d + # and correlate2d. + assert_array_equal(result, expected) + + def test_boundary_extension_same(self): + # Regression test for gh-12686. + # Use ndimage.convolve with appropriate arguments to create the + # expected result. + import scipy.ndimage as ndi + a = np.arange(1, 10*3+1, dtype=float).reshape(10, 3) + b = np.arange(1, 10*10+1, dtype=float).reshape(10, 10) + c = convolve2d(a, b, mode='same', boundary='wrap') + assert_array_equal(c, ndi.convolve(a, b, mode='wrap', origin=(-1, -1))) + + def test_boundary_extension_full(self): + # Regression test for gh-12686. + # Use ndimage.convolve with appropriate arguments to create the + # expected result. + import scipy.ndimage as ndi + a = np.arange(1, 3*3+1, dtype=float).reshape(3, 3) + b = np.arange(1, 6*6+1, dtype=float).reshape(6, 6) + c = convolve2d(a, b, mode='full', boundary='wrap') + apad = np.pad(a, ((3, 3), (3, 3)), 'wrap') + assert_array_equal(c, ndi.convolve(apad, b, mode='wrap')[:-1, :-1]) + + def test_invalid_shapes(self): + # By "invalid," we mean that no one + # array has dimensions that are all at + # least as large as the corresponding + # dimensions of the other array. This + # setup should throw a ValueError. + a = np.arange(1, 7).reshape((2, 3)) + b = np.arange(-6, 0).reshape((3, 2)) + + assert_raises(ValueError, convolve2d, *(a, b), **{'mode': 'valid'}) + assert_raises(ValueError, convolve2d, *(b, a), **{'mode': 'valid'}) + + +class TestConvolve2d(_TestConvolve2d): + + def test_same_mode(self): + e = [[1, 2, 3], [3, 4, 5]] + f = [[2, 3, 4, 5, 6, 7, 8], [4, 5, 6, 7, 8, 9, 10]] + g = convolve2d(e, f, 'same') + h = array([[22, 28, 34], + [80, 98, 116]]) + assert_array_equal(g, h) + + def test_valid_mode2(self): + # See gh-5897 + e = [[1, 2, 3], [3, 4, 5]] + f = [[2, 3, 4, 5, 6, 7, 8], [4, 5, 6, 7, 8, 9, 10]] + expected = [[62, 80, 98, 116, 134]] + + out = convolve2d(e, f, 'valid') + assert_array_equal(out, expected) + + out = convolve2d(f, e, 'valid') + assert_array_equal(out, expected) + + e = [[1 + 1j, 2 - 3j], [3 + 1j, 4 + 0j]] + f = [[2 - 1j, 3 + 2j, 4 + 0j], [4 - 0j, 5 + 1j, 6 - 3j]] + expected = [[27 - 1j, 46. + 2j]] + + out = convolve2d(e, f, 'valid') + assert_array_equal(out, expected) + + # See gh-5897 + out = convolve2d(f, e, 'valid') + assert_array_equal(out, expected) + + def test_consistency_convolve_funcs(self): + # Compare np.convolve, signal.convolve, signal.convolve2d + a = np.arange(5) + b = np.array([3.2, 1.4, 3]) + for mode in ['full', 'valid', 'same']: + assert_almost_equal(np.convolve(a, b, mode=mode), + signal.convolve(a, b, mode=mode)) + assert_almost_equal(np.squeeze( + signal.convolve2d([a], [b], mode=mode)), + signal.convolve(a, b, mode=mode)) + + def test_invalid_dims(self): + assert_raises(ValueError, convolve2d, 3, 4) + assert_raises(ValueError, convolve2d, [3], [4]) + assert_raises(ValueError, convolve2d, [[[3]]], [[[4]]]) + + @pytest.mark.slow + @pytest.mark.xfail_on_32bit("Can't create large array for test") + def test_large_array(self): + # Test indexing doesn't overflow an int (gh-10761) + n = 2**31 // (1000 * np.int64().itemsize) + _testutils.check_free_memory(2 * n * 1001 * np.int64().itemsize / 1e6) + + # Create a chequered pattern of 1s and 0s + a = np.zeros(1001 * n, dtype=np.int64) + a[::2] = 1 + a = np.lib.stride_tricks.as_strided(a, shape=(n, 1000), strides=(8008, 8)) + + count = signal.convolve2d(a, [[1, 1]]) + fails = np.where(count > 1) + assert fails[0].size == 0 + + +class TestFFTConvolve: + + @pytest.mark.parametrize('axes', ['', None, 0, [0], -1, [-1]]) + def test_real(self, axes): + a = array([1, 2, 3]) + expected = array([1, 4, 10, 12, 9.]) + + if axes == '': + out = fftconvolve(a, a) + else: + out = fftconvolve(a, a, axes=axes) + + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('axes', [1, [1], -1, [-1]]) + def test_real_axes(self, axes): + a = array([1, 2, 3]) + expected = array([1, 4, 10, 12, 9.]) + + a = np.tile(a, [2, 1]) + expected = np.tile(expected, [2, 1]) + + out = fftconvolve(a, a, axes=axes) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('axes', ['', None, 0, [0], -1, [-1]]) + def test_complex(self, axes): + a = array([1 + 1j, 2 + 2j, 3 + 3j]) + expected = array([0 + 2j, 0 + 8j, 0 + 20j, 0 + 24j, 0 + 18j]) + + if axes == '': + out = fftconvolve(a, a) + else: + out = fftconvolve(a, a, axes=axes) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('axes', [1, [1], -1, [-1]]) + def test_complex_axes(self, axes): + a = array([1 + 1j, 2 + 2j, 3 + 3j]) + expected = array([0 + 2j, 0 + 8j, 0 + 20j, 0 + 24j, 0 + 18j]) + + a = np.tile(a, [2, 1]) + expected = np.tile(expected, [2, 1]) + + out = fftconvolve(a, a, axes=axes) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('axes', ['', + None, + [0, 1], + [1, 0], + [0, -1], + [-1, 0], + [-2, 1], + [1, -2], + [-2, -1], + [-1, -2]]) + def test_2d_real_same(self, axes): + a = array([[1, 2, 3], + [4, 5, 6]]) + expected = array([[1, 4, 10, 12, 9], + [8, 26, 56, 54, 36], + [16, 40, 73, 60, 36]]) + + if axes == '': + out = fftconvolve(a, a) + else: + out = fftconvolve(a, a, axes=axes) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('axes', [[1, 2], + [2, 1], + [1, -1], + [-1, 1], + [-2, 2], + [2, -2], + [-2, -1], + [-1, -2]]) + def test_2d_real_same_axes(self, axes): + a = array([[1, 2, 3], + [4, 5, 6]]) + expected = array([[1, 4, 10, 12, 9], + [8, 26, 56, 54, 36], + [16, 40, 73, 60, 36]]) + + a = np.tile(a, [2, 1, 1]) + expected = np.tile(expected, [2, 1, 1]) + + out = fftconvolve(a, a, axes=axes) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('axes', ['', + None, + [0, 1], + [1, 0], + [0, -1], + [-1, 0], + [-2, 1], + [1, -2], + [-2, -1], + [-1, -2]]) + def test_2d_complex_same(self, axes): + a = array([[1 + 2j, 3 + 4j, 5 + 6j], + [2 + 1j, 4 + 3j, 6 + 5j]]) + expected = array([ + [-3 + 4j, -10 + 20j, -21 + 56j, -18 + 76j, -11 + 60j], + [10j, 44j, 118j, 156j, 122j], + [3 + 4j, 10 + 20j, 21 + 56j, 18 + 76j, 11 + 60j] + ]) + + if axes == '': + out = fftconvolve(a, a) + else: + out = fftconvolve(a, a, axes=axes) + + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('axes', [[1, 2], + [2, 1], + [1, -1], + [-1, 1], + [-2, 2], + [2, -2], + [-2, -1], + [-1, -2]]) + def test_2d_complex_same_axes(self, axes): + a = array([[1 + 2j, 3 + 4j, 5 + 6j], + [2 + 1j, 4 + 3j, 6 + 5j]]) + expected = array([ + [-3 + 4j, -10 + 20j, -21 + 56j, -18 + 76j, -11 + 60j], + [10j, 44j, 118j, 156j, 122j], + [3 + 4j, 10 + 20j, 21 + 56j, 18 + 76j, 11 + 60j] + ]) + + a = np.tile(a, [2, 1, 1]) + expected = np.tile(expected, [2, 1, 1]) + + out = fftconvolve(a, a, axes=axes) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('axes', ['', None, 0, [0], -1, [-1]]) + def test_real_same_mode(self, axes): + a = array([1, 2, 3]) + b = array([3, 3, 5, 6, 8, 7, 9, 0, 1]) + expected_1 = array([35., 41., 47.]) + expected_2 = array([9., 20., 25., 35., 41., 47., 39., 28., 2.]) + + if axes == '': + out = fftconvolve(a, b, 'same') + else: + out = fftconvolve(a, b, 'same', axes=axes) + assert_array_almost_equal(out, expected_1) + + if axes == '': + out = fftconvolve(b, a, 'same') + else: + out = fftconvolve(b, a, 'same', axes=axes) + assert_array_almost_equal(out, expected_2) + + @pytest.mark.parametrize('axes', [1, -1, [1], [-1]]) + def test_real_same_mode_axes(self, axes): + a = array([1, 2, 3]) + b = array([3, 3, 5, 6, 8, 7, 9, 0, 1]) + expected_1 = array([35., 41., 47.]) + expected_2 = array([9., 20., 25., 35., 41., 47., 39., 28., 2.]) + + a = np.tile(a, [2, 1]) + b = np.tile(b, [2, 1]) + expected_1 = np.tile(expected_1, [2, 1]) + expected_2 = np.tile(expected_2, [2, 1]) + + out = fftconvolve(a, b, 'same', axes=axes) + assert_array_almost_equal(out, expected_1) + + out = fftconvolve(b, a, 'same', axes=axes) + assert_array_almost_equal(out, expected_2) + + @pytest.mark.parametrize('axes', ['', None, 0, [0], -1, [-1]]) + def test_valid_mode_real(self, axes): + # See gh-5897 + a = array([3, 2, 1]) + b = array([3, 3, 5, 6, 8, 7, 9, 0, 1]) + expected = array([24., 31., 41., 43., 49., 25., 12.]) + + if axes == '': + out = fftconvolve(a, b, 'valid') + else: + out = fftconvolve(a, b, 'valid', axes=axes) + assert_array_almost_equal(out, expected) + + if axes == '': + out = fftconvolve(b, a, 'valid') + else: + out = fftconvolve(b, a, 'valid', axes=axes) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('axes', [1, [1]]) + def test_valid_mode_real_axes(self, axes): + # See gh-5897 + a = array([3, 2, 1]) + b = array([3, 3, 5, 6, 8, 7, 9, 0, 1]) + expected = array([24., 31., 41., 43., 49., 25., 12.]) + + a = np.tile(a, [2, 1]) + b = np.tile(b, [2, 1]) + expected = np.tile(expected, [2, 1]) + + out = fftconvolve(a, b, 'valid', axes=axes) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('axes', ['', None, 0, [0], -1, [-1]]) + def test_valid_mode_complex(self, axes): + a = array([3 - 1j, 2 + 7j, 1 + 0j]) + b = array([3 + 2j, 3 - 3j, 5 + 0j, 6 - 1j, 8 + 0j]) + expected = array([45. + 12.j, 30. + 23.j, 48 + 32.j]) + + if axes == '': + out = fftconvolve(a, b, 'valid') + else: + out = fftconvolve(a, b, 'valid', axes=axes) + assert_array_almost_equal(out, expected) + + if axes == '': + out = fftconvolve(b, a, 'valid') + else: + out = fftconvolve(b, a, 'valid', axes=axes) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('axes', [1, [1], -1, [-1]]) + def test_valid_mode_complex_axes(self, axes): + a = array([3 - 1j, 2 + 7j, 1 + 0j]) + b = array([3 + 2j, 3 - 3j, 5 + 0j, 6 - 1j, 8 + 0j]) + expected = array([45. + 12.j, 30. + 23.j, 48 + 32.j]) + + a = np.tile(a, [2, 1]) + b = np.tile(b, [2, 1]) + expected = np.tile(expected, [2, 1]) + + out = fftconvolve(a, b, 'valid', axes=axes) + assert_array_almost_equal(out, expected) + + out = fftconvolve(b, a, 'valid', axes=axes) + assert_array_almost_equal(out, expected) + + def test_valid_mode_ignore_nonaxes(self): + # See gh-5897 + a = array([3, 2, 1]) + b = array([3, 3, 5, 6, 8, 7, 9, 0, 1]) + expected = array([24., 31., 41., 43., 49., 25., 12.]) + + a = np.tile(a, [2, 1]) + b = np.tile(b, [1, 1]) + expected = np.tile(expected, [2, 1]) + + out = fftconvolve(a, b, 'valid', axes=1) + assert_array_almost_equal(out, expected) + + def test_empty(self): + # Regression test for #1745: crashes with 0-length input. + assert_(fftconvolve([], []).size == 0) + assert_(fftconvolve([5, 6], []).size == 0) + assert_(fftconvolve([], [7]).size == 0) + + def test_zero_rank(self): + a = array(4967) + b = array(3920) + out = fftconvolve(a, b) + assert_equal(out, a * b) + + def test_single_element(self): + a = array([4967]) + b = array([3920]) + out = fftconvolve(a, b) + assert_equal(out, a * b) + + @pytest.mark.parametrize('axes', ['', None, 0, [0], -1, [-1]]) + def test_random_data(self, axes): + np.random.seed(1234) + a = np.random.rand(1233) + 1j * np.random.rand(1233) + b = np.random.rand(1321) + 1j * np.random.rand(1321) + expected = np.convolve(a, b, 'full') + + if axes == '': + out = fftconvolve(a, b, 'full') + else: + out = fftconvolve(a, b, 'full', axes=axes) + assert_(np.allclose(out, expected, rtol=1e-10)) + + @pytest.mark.parametrize('axes', [1, [1], -1, [-1]]) + def test_random_data_axes(self, axes): + np.random.seed(1234) + a = np.random.rand(1233) + 1j * np.random.rand(1233) + b = np.random.rand(1321) + 1j * np.random.rand(1321) + expected = np.convolve(a, b, 'full') + + a = np.tile(a, [2, 1]) + b = np.tile(b, [2, 1]) + expected = np.tile(expected, [2, 1]) + + out = fftconvolve(a, b, 'full', axes=axes) + assert_(np.allclose(out, expected, rtol=1e-10)) + + @pytest.mark.parametrize('axes', [[1, 4], + [4, 1], + [1, -1], + [-1, 1], + [-4, 4], + [4, -4], + [-4, -1], + [-1, -4]]) + def test_random_data_multidim_axes(self, axes): + a_shape, b_shape = (123, 22), (132, 11) + np.random.seed(1234) + a = np.random.rand(*a_shape) + 1j * np.random.rand(*a_shape) + b = np.random.rand(*b_shape) + 1j * np.random.rand(*b_shape) + expected = convolve2d(a, b, 'full') + + a = a[:, :, None, None, None] + b = b[:, :, None, None, None] + expected = expected[:, :, None, None, None] + + a = np.moveaxis(a.swapaxes(0, 2), 1, 4) + b = np.moveaxis(b.swapaxes(0, 2), 1, 4) + expected = np.moveaxis(expected.swapaxes(0, 2), 1, 4) + + # use 1 for dimension 2 in a and 3 in b to test broadcasting + a = np.tile(a, [2, 1, 3, 1, 1]) + b = np.tile(b, [2, 1, 1, 4, 1]) + expected = np.tile(expected, [2, 1, 3, 4, 1]) + + out = fftconvolve(a, b, 'full', axes=axes) + assert_allclose(out, expected, rtol=1e-10, atol=1e-10) + + @pytest.mark.slow + @pytest.mark.parametrize( + 'n', + list(range(1, 100)) + + list(range(1000, 1500)) + + np.random.RandomState(1234).randint(1001, 10000, 5).tolist()) + def test_many_sizes(self, n): + a = np.random.rand(n) + 1j * np.random.rand(n) + b = np.random.rand(n) + 1j * np.random.rand(n) + expected = np.convolve(a, b, 'full') + + out = fftconvolve(a, b, 'full') + assert_allclose(out, expected, atol=1e-10) + + out = fftconvolve(a, b, 'full', axes=[0]) + assert_allclose(out, expected, atol=1e-10) + + @pytest.mark.thread_unsafe + def test_fft_nan(self): + n = 1000 + rng = np.random.default_rng(43876432987) + sig_nan = rng.standard_normal(n) + + for val in [np.nan, np.inf]: + sig_nan[100] = val + coeffs = signal.firwin(200, 0.2) + + msg = "Use of fft convolution.*|invalid value encountered.*" + with pytest.warns(RuntimeWarning, match=msg): + signal.convolve(sig_nan, coeffs, mode='same', method='fft') + +def fftconvolve_err(*args, **kwargs): + raise RuntimeError('Fell back to fftconvolve') + + +def gen_oa_shapes(sizes): + return [(a, b) for a, b in product(sizes, repeat=2) + if abs(a - b) > 3] + + +def gen_oa_shapes_2d(sizes): + shapes0 = gen_oa_shapes(sizes) + shapes1 = gen_oa_shapes(sizes) + shapes = [ishapes0+ishapes1 for ishapes0, ishapes1 in + zip(shapes0, shapes1)] + + modes = ['full', 'valid', 'same'] + return [ishapes+(imode,) for ishapes, imode in product(shapes, modes) + if imode != 'valid' or + (ishapes[0] > ishapes[1] and ishapes[2] > ishapes[3]) or + (ishapes[0] < ishapes[1] and ishapes[2] < ishapes[3])] + + +def gen_oa_shapes_eq(sizes): + return [(a, b) for a, b in product(sizes, repeat=2) + if a >= b] + + +class TestOAConvolve: + @pytest.mark.slow() + @pytest.mark.parametrize('shape_a_0, shape_b_0', + gen_oa_shapes_eq(list(range(100)) + + list(range(100, 1000, 23))) + ) + def test_real_manylens(self, shape_a_0, shape_b_0): + a = np.random.rand(shape_a_0) + b = np.random.rand(shape_b_0) + + expected = fftconvolve(a, b) + out = oaconvolve(a, b) + + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('shape_a_0, shape_b_0', + gen_oa_shapes([50, 47, 6, 4, 1])) + @pytest.mark.parametrize('is_complex', [True, False]) + @pytest.mark.parametrize('mode', ['full', 'valid', 'same']) + def test_1d_noaxes(self, shape_a_0, shape_b_0, + is_complex, mode, monkeypatch): + a = np.random.rand(shape_a_0) + b = np.random.rand(shape_b_0) + if is_complex: + a = a + 1j*np.random.rand(shape_a_0) + b = b + 1j*np.random.rand(shape_b_0) + + expected = fftconvolve(a, b, mode=mode) + + monkeypatch.setattr(signal._signaltools, 'fftconvolve', + fftconvolve_err) + out = oaconvolve(a, b, mode=mode) + + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('axes', [0, 1]) + @pytest.mark.parametrize('shape_a_0, shape_b_0', + gen_oa_shapes([50, 47, 6, 4])) + @pytest.mark.parametrize('shape_a_extra', [1, 3]) + @pytest.mark.parametrize('shape_b_extra', [1, 3]) + @pytest.mark.parametrize('is_complex', [True, False]) + @pytest.mark.parametrize('mode', ['full', 'valid', 'same']) + def test_1d_axes(self, axes, shape_a_0, shape_b_0, + shape_a_extra, shape_b_extra, + is_complex, mode, monkeypatch): + ax_a = [shape_a_extra]*2 + ax_b = [shape_b_extra]*2 + ax_a[axes] = shape_a_0 + ax_b[axes] = shape_b_0 + + a = np.random.rand(*ax_a) + b = np.random.rand(*ax_b) + if is_complex: + a = a + 1j*np.random.rand(*ax_a) + b = b + 1j*np.random.rand(*ax_b) + + expected = fftconvolve(a, b, mode=mode, axes=axes) + + monkeypatch.setattr(signal._signaltools, 'fftconvolve', + fftconvolve_err) + out = oaconvolve(a, b, mode=mode, axes=axes) + + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('shape_a_0, shape_b_0, ' + 'shape_a_1, shape_b_1, mode', + gen_oa_shapes_2d([50, 47, 6, 4])) + @pytest.mark.parametrize('is_complex', [True, False]) + def test_2d_noaxes(self, shape_a_0, shape_b_0, + shape_a_1, shape_b_1, mode, + is_complex, monkeypatch): + a = np.random.rand(shape_a_0, shape_a_1) + b = np.random.rand(shape_b_0, shape_b_1) + if is_complex: + a = a + 1j*np.random.rand(shape_a_0, shape_a_1) + b = b + 1j*np.random.rand(shape_b_0, shape_b_1) + + expected = fftconvolve(a, b, mode=mode) + + monkeypatch.setattr(signal._signaltools, 'fftconvolve', + fftconvolve_err) + out = oaconvolve(a, b, mode=mode) + + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('axes', [[0, 1], [0, 2], [1, 2]]) + @pytest.mark.parametrize('shape_a_0, shape_b_0, ' + 'shape_a_1, shape_b_1, mode', + gen_oa_shapes_2d([50, 47, 6, 4])) + @pytest.mark.parametrize('shape_a_extra', [1, 3]) + @pytest.mark.parametrize('shape_b_extra', [1, 3]) + @pytest.mark.parametrize('is_complex', [True, False]) + def test_2d_axes(self, axes, shape_a_0, shape_b_0, + shape_a_1, shape_b_1, mode, + shape_a_extra, shape_b_extra, + is_complex, monkeypatch): + ax_a = [shape_a_extra]*3 + ax_b = [shape_b_extra]*3 + ax_a[axes[0]] = shape_a_0 + ax_b[axes[0]] = shape_b_0 + ax_a[axes[1]] = shape_a_1 + ax_b[axes[1]] = shape_b_1 + + a = np.random.rand(*ax_a) + b = np.random.rand(*ax_b) + if is_complex: + a = a + 1j*np.random.rand(*ax_a) + b = b + 1j*np.random.rand(*ax_b) + + expected = fftconvolve(a, b, mode=mode, axes=axes) + + monkeypatch.setattr(signal._signaltools, 'fftconvolve', + fftconvolve_err) + out = oaconvolve(a, b, mode=mode, axes=axes) + + assert_array_almost_equal(out, expected) + + def test_empty(self): + # Regression test for #1745: crashes with 0-length input. + assert_(oaconvolve([], []).size == 0) + assert_(oaconvolve([5, 6], []).size == 0) + assert_(oaconvolve([], [7]).size == 0) + + def test_zero_rank(self): + a = array(4967) + b = array(3920) + out = oaconvolve(a, b) + assert_equal(out, a * b) + + def test_single_element(self): + a = array([4967]) + b = array([3920]) + out = oaconvolve(a, b) + assert_equal(out, a * b) + + +class TestAllFreqConvolves: + + @pytest.mark.parametrize('convapproach', + [fftconvolve, oaconvolve]) + def test_invalid_shapes(self, convapproach): + a = np.arange(1, 7).reshape((2, 3)) + b = np.arange(-6, 0).reshape((3, 2)) + with assert_raises(ValueError, + match="For 'valid' mode, one must be at least " + "as large as the other in every dimension"): + convapproach(a, b, mode='valid') + + @pytest.mark.parametrize('convapproach', + [fftconvolve, oaconvolve]) + def test_invalid_shapes_axes(self, convapproach): + a = np.zeros([5, 6, 2, 1]) + b = np.zeros([5, 6, 3, 1]) + with assert_raises(ValueError, + match=r"incompatible shapes for in1 and in2:" + r" \(5L?, 6L?, 2L?, 1L?\) and" + r" \(5L?, 6L?, 3L?, 1L?\)"): + convapproach(a, b, axes=[0, 1]) + + @pytest.mark.parametrize('a,b', + [([1], 2), + (1, [2]), + ([3], [[2]])]) + @pytest.mark.parametrize('convapproach', + [fftconvolve, oaconvolve]) + def test_mismatched_dims(self, a, b, convapproach): + with assert_raises(ValueError, + match="in1 and in2 should have the same" + " dimensionality"): + convapproach(a, b) + + @pytest.mark.parametrize('convapproach', + [fftconvolve, oaconvolve]) + def test_invalid_flags(self, convapproach): + with assert_raises(ValueError, + match="acceptable mode flags are 'valid'," + " 'same', or 'full'"): + convapproach([1], [2], mode='chips') + + with assert_raises(ValueError, + match="when provided, axes cannot be empty"): + convapproach([1], [2], axes=[]) + + with assert_raises(ValueError, match="axes must be a scalar or " + "iterable of integers"): + convapproach([1], [2], axes=[[1, 2], [3, 4]]) + + with assert_raises(ValueError, match="axes must be a scalar or " + "iterable of integers"): + convapproach([1], [2], axes=[1., 2., 3., 4.]) + + with assert_raises(ValueError, + match="axes exceeds dimensionality of input"): + convapproach([1], [2], axes=[1]) + + with assert_raises(ValueError, + match="axes exceeds dimensionality of input"): + convapproach([1], [2], axes=[-2]) + + with assert_raises(ValueError, + match="all axes must be unique"): + convapproach([1], [2], axes=[0, 0]) + + @pytest.mark.filterwarnings('ignore::DeprecationWarning') + @pytest.mark.parametrize('dtype', [np.longdouble, np.clongdouble]) + def test_longdtype_input(self, dtype): + x = np.random.random((27, 27)).astype(dtype) + y = np.random.random((4, 4)).astype(dtype) + if np.iscomplexobj(dtype()): + x += .1j + y -= .1j + + res = fftconvolve(x, y) + assert_allclose(res, convolve(x, y, method='direct')) + assert res.dtype == dtype + + +class TestMedFilt: + + IN = [[50, 50, 50, 50, 50, 92, 18, 27, 65, 46], + [50, 50, 50, 50, 50, 0, 72, 77, 68, 66], + [50, 50, 50, 50, 50, 46, 47, 19, 64, 77], + [50, 50, 50, 50, 50, 42, 15, 29, 95, 35], + [50, 50, 50, 50, 50, 46, 34, 9, 21, 66], + [70, 97, 28, 68, 78, 77, 61, 58, 71, 42], + [64, 53, 44, 29, 68, 32, 19, 68, 24, 84], + [3, 33, 53, 67, 1, 78, 74, 55, 12, 83], + [7, 11, 46, 70, 60, 47, 24, 43, 61, 26], + [32, 61, 88, 7, 39, 4, 92, 64, 45, 61]] + + OUT = [[0, 50, 50, 50, 42, 15, 15, 18, 27, 0], + [0, 50, 50, 50, 50, 42, 19, 21, 29, 0], + [50, 50, 50, 50, 50, 47, 34, 34, 46, 35], + [50, 50, 50, 50, 50, 50, 42, 47, 64, 42], + [50, 50, 50, 50, 50, 50, 46, 55, 64, 35], + [33, 50, 50, 50, 50, 47, 46, 43, 55, 26], + [32, 50, 50, 50, 50, 47, 46, 45, 55, 26], + [7, 46, 50, 50, 47, 46, 46, 43, 45, 21], + [0, 32, 33, 39, 32, 32, 43, 43, 43, 0], + [0, 7, 11, 7, 4, 4, 19, 19, 24, 0]] + + KERNEL_SIZE = [7,3] + + def test_basic(self): + d = signal.medfilt(self.IN, self.KERNEL_SIZE) + e = signal.medfilt2d(np.array(self.IN, float), self.KERNEL_SIZE) + assert_array_equal(d, self.OUT) + assert_array_equal(d, e) + + @pytest.mark.parametrize('dtype', [np.ubyte, np.byte, np.ushort, np.short, + np_ulong, np_long, np.ulonglong, np.ulonglong, + np.float32, np.float64]) + def test_types(self, dtype): + # volume input and output types match + in_typed = np.array(self.IN, dtype=dtype) + assert_equal(signal.medfilt(in_typed).dtype, dtype) + assert_equal(signal.medfilt2d(in_typed).dtype, dtype) + + @pytest.mark.parametrize('dtype', [np.bool_, np.complex64, np.complex128, + np.clongdouble, np.float16, np.object_, + "float96", "float128"]) + def test_invalid_dtypes(self, dtype): + # We can only test this on platforms that support a native type of float96 or + # float128; comparing to np.longdouble allows us to filter out non-native types + if (dtype in ["float96", "float128"] + and np.finfo(np.longdouble).dtype != dtype): + pytest.skip(f"Platform does not support {dtype}") + + in_typed = np.array(self.IN, dtype=dtype) + with pytest.raises(ValueError, match="not supported"): + signal.medfilt(in_typed) + + with pytest.raises(ValueError, match="not supported"): + signal.medfilt2d(in_typed) + + def test_none(self): + # gh-1651, trac #1124. Ensure this does not segfault. + msg = "dtype=object is not supported by medfilt" + with assert_raises(ValueError, match=msg): + signal.medfilt(None) + + def test_odd_strides(self): + # Avoid a regression with possible contiguous + # numpy arrays that have odd strides. The stride value below gets + # us into wrong memory if used (but it does not need to be used) + dummy = np.arange(10, dtype=np.float64) + a = dummy[5:6] + a.strides = 16 + assert_(signal.medfilt(a, 1) == 5.) + + @pytest.mark.parametrize("dtype", [np.ubyte, np.float32, np.float64]) + def test_medfilt2d_parallel(self, dtype): + in_typed = np.array(self.IN, dtype=dtype) + expected = np.array(self.OUT, dtype=dtype) + + # This is used to simplify the indexing calculations. + assert in_typed.shape == expected.shape + + # We'll do the calculation in four chunks. M1 and N1 are the dimensions + # of the first output chunk. We have to extend the input by half the + # kernel size to be able to calculate the full output chunk. + M1 = expected.shape[0] // 2 + N1 = expected.shape[1] // 2 + offM = self.KERNEL_SIZE[0] // 2 + 1 + offN = self.KERNEL_SIZE[1] // 2 + 1 + + def apply(chunk): + # in = slice of in_typed to use. + # sel = slice of output to crop it to the correct region. + # out = slice of output array to store in. + M, N = chunk + if M == 0: + Min = slice(0, M1 + offM) + Msel = slice(0, -offM) + Mout = slice(0, M1) + else: + Min = slice(M1 - offM, None) + Msel = slice(offM, None) + Mout = slice(M1, None) + if N == 0: + Nin = slice(0, N1 + offN) + Nsel = slice(0, -offN) + Nout = slice(0, N1) + else: + Nin = slice(N1 - offN, None) + Nsel = slice(offN, None) + Nout = slice(N1, None) + + # Do the calculation, but do not write to the output in the threads. + chunk_data = in_typed[Min, Nin] + med = signal.medfilt2d(chunk_data, self.KERNEL_SIZE) + return med[Msel, Nsel], Mout, Nout + + # Give each chunk to a different thread. + output = np.zeros_like(expected) + with ThreadPoolExecutor(max_workers=4) as pool: + chunks = {(0, 0), (0, 1), (1, 0), (1, 1)} + futures = {pool.submit(apply, chunk) for chunk in chunks} + + # Store each result in the output as it arrives. + for future in as_completed(futures): + data, Mslice, Nslice = future.result() + output[Mslice, Nslice] = data + + assert_array_equal(output, expected) + + +class TestWiener: + + def test_basic(self): + g = array([[5, 6, 4, 3], + [3, 5, 6, 2], + [2, 3, 5, 6], + [1, 6, 9, 7]], 'd') + h = array([[2.16374269, 3.2222222222, 2.8888888889, 1.6666666667], + [2.666666667, 4.33333333333, 4.44444444444, 2.8888888888], + [2.222222222, 4.4444444444, 5.4444444444, 4.801066874837], + [1.33333333333, 3.92735042735, 6.0712560386, 5.0404040404]]) + assert_array_almost_equal(signal.wiener(g), h, decimal=6) + assert_array_almost_equal(signal.wiener(g, mysize=3), h, decimal=6) + + +padtype_options = ["mean", "median", "minimum", "maximum", "line"] +padtype_options += _upfirdn_modes + + +class TestResample: + def test_basic(self): + # Some basic tests + + # Regression test for issue #3603. + # window.shape must equal to sig.shape[0] + sig = np.arange(128) + num = 256 + win = signal.get_window(('kaiser', 8.0), 160) + assert_raises(ValueError, signal.resample, sig, num, window=win) + + # Other degenerate conditions + assert_raises(ValueError, signal.resample_poly, sig, 'yo', 1) + assert_raises(ValueError, signal.resample_poly, sig, 1, 0) + assert_raises(ValueError, signal.resample_poly, sig, 2, 1, padtype='') + assert_raises(ValueError, signal.resample_poly, sig, 2, 1, + padtype='mean', cval=10) + + # test for issue #6505 - should not modify window.shape when axis ≠ 0 + sig2 = np.tile(np.arange(160), (2, 1)) + signal.resample(sig2, num, axis=-1, window=win) + assert_(win.shape == (160,)) + + @pytest.mark.parametrize('window', (None, 'hamming')) + @pytest.mark.parametrize('N', (20, 19)) + @pytest.mark.parametrize('num', (100, 101, 10, 11)) + def test_rfft(self, N, num, window): + # Make sure the speed up using rfft gives the same result as the normal + # way using fft + x = np.linspace(0, 10, N, endpoint=False) + y = np.cos(-x**2/6.0) + assert_allclose(signal.resample(y, num, window=window), + signal.resample(y + 0j, num, window=window).real) + + y = np.array([np.cos(-x**2/6.0), np.sin(-x**2/6.0)]) + y_complex = y + 0j + assert_allclose( + signal.resample(y, num, axis=1, window=window), + signal.resample(y_complex, num, axis=1, window=window).real, + atol=1e-9) + + def test_input_domain(self): + # Test if both input domain modes produce the same results. + tsig = np.arange(256) + 0j + fsig = sp_fft.fft(tsig) + num = 256 + assert_allclose( + signal.resample(fsig, num, domain='freq'), + signal.resample(tsig, num, domain='time'), + atol=1e-9) + + @pytest.mark.parametrize('nx', (1, 2, 3, 5, 8)) + @pytest.mark.parametrize('ny', (1, 2, 3, 5, 8)) + @pytest.mark.parametrize('dtype', ('float', 'complex')) + def test_dc(self, nx, ny, dtype): + x = np.array([1] * nx, dtype) + y = signal.resample(x, ny) + assert_allclose(y, [1] * ny) + + @pytest.mark.thread_unsafe # due to Cython fused types, see cython#6506 + @pytest.mark.parametrize('padtype', padtype_options) + def test_mutable_window(self, padtype): + # Test that a mutable window is not modified + impulse = np.zeros(3) + window = np.random.RandomState(0).randn(2) + window_orig = window.copy() + signal.resample_poly(impulse, 5, 1, window=window, padtype=padtype) + assert_array_equal(window, window_orig) + + @pytest.mark.parametrize('padtype', padtype_options) + def test_output_float32(self, padtype): + # Test that float32 inputs yield a float32 output + x = np.arange(10, dtype=np.float32) + h = np.array([1, 1, 1], dtype=np.float32) + y = signal.resample_poly(x, 1, 2, window=h, padtype=padtype) + assert y.dtype == np.float32 + + @pytest.mark.parametrize('padtype', padtype_options) + @pytest.mark.parametrize('dtype', [np.float32, np.float64]) + def test_output_match_dtype(self, padtype, dtype): + # Test that the dtype of x is preserved per issue #14733 + x = np.arange(10, dtype=dtype) + y = signal.resample_poly(x, 1, 2, padtype=padtype) + assert y.dtype == x.dtype + + @pytest.mark.parametrize( + "method, ext, padtype", + [("fft", False, None)] + + list( + product( + ["polyphase"], [False, True], padtype_options, + ) + ), + ) + def test_resample_methods(self, method, ext, padtype): + # Test resampling of sinusoids and random noise (1-sec) + rate = 100 + rates_to = [49, 50, 51, 99, 100, 101, 199, 200, 201] + + # Sinusoids, windowed to avoid edge artifacts + t = np.arange(rate) / float(rate) + freqs = np.array((1., 10., 40.))[:, np.newaxis] + x = np.sin(2 * np.pi * freqs * t) * hann(rate) + + for rate_to in rates_to: + t_to = np.arange(rate_to) / float(rate_to) + y_tos = np.sin(2 * np.pi * freqs * t_to) * hann(rate_to) + if method == 'fft': + y_resamps = signal.resample(x, rate_to, axis=-1) + else: + if ext and rate_to != rate: + # Match default window design + g = gcd(rate_to, rate) + up = rate_to // g + down = rate // g + max_rate = max(up, down) + f_c = 1. / max_rate + half_len = 10 * max_rate + window = signal.firwin(2 * half_len + 1, f_c, + window=('kaiser', 5.0)) + polyargs = {'window': window, 'padtype': padtype} + else: + polyargs = {'padtype': padtype} + + y_resamps = signal.resample_poly(x, rate_to, rate, axis=-1, + **polyargs) + + for y_to, y_resamp, freq in zip(y_tos, y_resamps, freqs): + if freq >= 0.5 * rate_to: + y_to.fill(0.) # mostly low-passed away + if padtype in ['minimum', 'maximum']: + assert_allclose(y_resamp, y_to, atol=3e-1) + else: + assert_allclose(y_resamp, y_to, atol=1e-3) + else: + assert_array_equal(y_to.shape, y_resamp.shape) + corr = np.corrcoef(y_to, y_resamp)[0, 1] + assert_(corr > 0.99, msg=(corr, rate, rate_to)) + + # Random data + rng = np.random.RandomState(0) + x = hann(rate) * np.cumsum(rng.randn(rate)) # low-pass, wind + for rate_to in rates_to: + # random data + t_to = np.arange(rate_to) / float(rate_to) + y_to = np.interp(t_to, t, x) + if method == 'fft': + y_resamp = signal.resample(x, rate_to) + else: + y_resamp = signal.resample_poly(x, rate_to, rate, + padtype=padtype) + assert_array_equal(y_to.shape, y_resamp.shape) + corr = np.corrcoef(y_to, y_resamp)[0, 1] + assert_(corr > 0.99, msg=corr) + + # More tests of fft method (Master 0.18.1 fails these) + if method == 'fft': + x1 = np.array([1.+0.j, 0.+0.j]) + y1_test = signal.resample(x1, 4) + # upsampling a complex array + y1_true = np.array([1.+0.j, 0.5+0.j, 0.+0.j, 0.5+0.j]) + assert_allclose(y1_test, y1_true, atol=1e-12) + x2 = np.array([1., 0.5, 0., 0.5]) + y2_test = signal.resample(x2, 2) # downsampling a real array + y2_true = np.array([1., 0.]) + assert_allclose(y2_test, y2_true, atol=1e-12) + + def test_poly_vs_filtfilt(self): + # Check that up=1.0 gives same answer as filtfilt + slicing + random_state = np.random.RandomState(17) + try_types = (int, np.float32, np.complex64, float, complex) + size = 10000 + down_factors = [2, 11, 79] + + for dtype in try_types: + x = random_state.randn(size).astype(dtype) + if dtype in (np.complex64, np.complex128): + x += 1j * random_state.randn(size) + + # resample_poly assumes zeros outside of signl, whereas filtfilt + # can only constant-pad. Make them equivalent: + x[0] = 0 + x[-1] = 0 + + for down in down_factors: + h = signal.firwin(31, 1. / down, window='hamming') + yf = filtfilt(h, 1.0, x, padtype='constant')[::down] + + # Need to pass convolved version of filter to resample_poly, + # since filtfilt does forward and backward, but resample_poly + # only goes forward + hc = convolve(h, h[::-1]) + y = signal.resample_poly(x, 1, down, window=hc) + assert_allclose(yf, y, atol=1e-7, rtol=1e-7) + + def test_correlate1d(self): + for down in [2, 4]: + for nx in range(1, 40, down): + for nweights in (32, 33): + x = np.random.random((nx,)) + weights = np.random.random((nweights,)) + y_g = correlate1d(x, weights[::-1], mode='constant') + y_s = signal.resample_poly( + x, up=1, down=down, window=weights) + assert_allclose(y_g[::down], y_s) + + @pytest.mark.parametrize('dtype', [np.int32, np.float32]) + def test_gh_15620(self, dtype): + data = np.array([0, 1, 2, 3, 2, 1, 0], dtype=dtype) + actual = signal.resample_poly(data, + up=2, + down=1, + padtype='smooth') + assert np.count_nonzero(actual) > 0 + + +class TestCSpline1DEval: + + def test_basic(self): + y = array([1, 2, 3, 4, 3, 2, 1, 2, 3.0]) + x = arange(len(y)) + dx = x[1] - x[0] + cj = signal.cspline1d(y) + + x2 = arange(len(y) * 10.0) / 10.0 + y2 = signal.cspline1d_eval(cj, x2, dx=dx, x0=x[0]) + + # make sure interpolated values are on knot points + assert_array_almost_equal(y2[::10], y, decimal=5) + + def test_complex(self): + # create some smoothly varying complex signal to interpolate + x = np.arange(2) + y = np.zeros(x.shape, dtype=np.complex64) + T = 10.0 + f = 1.0 / T + y = np.exp(2.0J * np.pi * f * x) + + # get the cspline transform + cy = signal.cspline1d(y) + + # determine new test x value and interpolate + xnew = np.array([0.5]) + ynew = signal.cspline1d_eval(cy, xnew) + + assert_equal(ynew.dtype, y.dtype) + +class TestOrderFilt: + + def test_basic(self): + assert_array_equal(signal.order_filter([1, 2, 3], [1, 0, 1], 1), + [2, 3, 2]) + + +class _TestLinearFilter: + + def generate(self, shape): + x = np.linspace(0, np.prod(shape) - 1, np.prod(shape)).reshape(shape) + return self.convert_dtype(x) + + def convert_dtype(self, arr): + if self.dtype == np.dtype('O'): + arr = np.asarray(arr) + out = np.empty(arr.shape, self.dtype) + iter = np.nditer([arr, out], ['refs_ok','zerosize_ok'], + [['readonly'],['writeonly']]) + for x, y in iter: + y[...] = self.type(x[()]) + return out + else: + return np.asarray(arr, dtype=self.dtype) + + def test_rank_1_IIR(self): + x = self.generate((6,)) + b = self.convert_dtype([1, -1]) + a = self.convert_dtype([0.5, -0.5]) + y_r = self.convert_dtype([0, 2, 4, 6, 8, 10.]) + assert_array_almost_equal(lfilter(b, a, x), y_r) + + def test_rank_1_FIR(self): + x = self.generate((6,)) + b = self.convert_dtype([1, 1]) + a = self.convert_dtype([1]) + y_r = self.convert_dtype([0, 1, 3, 5, 7, 9.]) + assert_array_almost_equal(lfilter(b, a, x), y_r) + + def test_rank_1_IIR_init_cond(self): + x = self.generate((6,)) + b = self.convert_dtype([1, 0, -1]) + a = self.convert_dtype([0.5, -0.5]) + zi = self.convert_dtype([1, 2]) + y_r = self.convert_dtype([1, 5, 9, 13, 17, 21]) + zf_r = self.convert_dtype([13, -10]) + y, zf = lfilter(b, a, x, zi=zi) + assert_array_almost_equal(y, y_r) + assert_array_almost_equal(zf, zf_r) + + def test_rank_1_FIR_init_cond(self): + x = self.generate((6,)) + b = self.convert_dtype([1, 1, 1]) + a = self.convert_dtype([1]) + zi = self.convert_dtype([1, 1]) + y_r = self.convert_dtype([1, 2, 3, 6, 9, 12.]) + zf_r = self.convert_dtype([9, 5]) + y, zf = lfilter(b, a, x, zi=zi) + assert_array_almost_equal(y, y_r) + assert_array_almost_equal(zf, zf_r) + + def test_rank_2_IIR_axis_0(self): + x = self.generate((4, 3)) + b = self.convert_dtype([1, -1]) + a = self.convert_dtype([0.5, 0.5]) + y_r2_a0 = self.convert_dtype([[0, 2, 4], [6, 4, 2], [0, 2, 4], + [6, 4, 2]]) + y = lfilter(b, a, x, axis=0) + assert_array_almost_equal(y_r2_a0, y) + + def test_rank_2_IIR_axis_1(self): + x = self.generate((4, 3)) + b = self.convert_dtype([1, -1]) + a = self.convert_dtype([0.5, 0.5]) + y_r2_a1 = self.convert_dtype([[0, 2, 0], [6, -4, 6], [12, -10, 12], + [18, -16, 18]]) + y = lfilter(b, a, x, axis=1) + assert_array_almost_equal(y_r2_a1, y) + + def test_rank_2_IIR_axis_0_init_cond(self): + x = self.generate((4, 3)) + b = self.convert_dtype([1, -1]) + a = self.convert_dtype([0.5, 0.5]) + zi = self.convert_dtype(np.ones((4,1))) + + y_r2_a0_1 = self.convert_dtype([[1, 1, 1], [7, -5, 7], [13, -11, 13], + [19, -17, 19]]) + zf_r = self.convert_dtype([-5, -17, -29, -41])[:, np.newaxis] + y, zf = lfilter(b, a, x, axis=1, zi=zi) + assert_array_almost_equal(y_r2_a0_1, y) + assert_array_almost_equal(zf, zf_r) + + def test_rank_2_IIR_axis_1_init_cond(self): + x = self.generate((4,3)) + b = self.convert_dtype([1, -1]) + a = self.convert_dtype([0.5, 0.5]) + zi = self.convert_dtype(np.ones((1,3))) + + y_r2_a0_0 = self.convert_dtype([[1, 3, 5], [5, 3, 1], + [1, 3, 5], [5, 3, 1]]) + zf_r = self.convert_dtype([[-23, -23, -23]]) + y, zf = lfilter(b, a, x, axis=0, zi=zi) + assert_array_almost_equal(y_r2_a0_0, y) + assert_array_almost_equal(zf, zf_r) + + def test_rank_3_IIR(self): + x = self.generate((4, 3, 2)) + b = self.convert_dtype([1, -1]) + a = self.convert_dtype([0.5, 0.5]) + + for axis in range(x.ndim): + y = lfilter(b, a, x, axis) + y_r = np.apply_along_axis(lambda w: lfilter(b, a, w), axis, x) + assert_array_almost_equal(y, y_r) + + def test_rank_3_IIR_init_cond(self): + x = self.generate((4, 3, 2)) + b = self.convert_dtype([1, -1]) + a = self.convert_dtype([0.5, 0.5]) + + for axis in range(x.ndim): + zi_shape = list(x.shape) + zi_shape[axis] = 1 + zi = self.convert_dtype(np.ones(zi_shape)) + zi1 = self.convert_dtype([1]) + y, zf = lfilter(b, a, x, axis, zi) + def lf0(w): + return lfilter(b, a, w, zi=zi1)[0] + def lf1(w): + return lfilter(b, a, w, zi=zi1)[1] + y_r = np.apply_along_axis(lf0, axis, x) + zf_r = np.apply_along_axis(lf1, axis, x) + assert_array_almost_equal(y, y_r) + assert_array_almost_equal(zf, zf_r) + + def test_rank_3_FIR(self): + x = self.generate((4, 3, 2)) + b = self.convert_dtype([1, 0, -1]) + a = self.convert_dtype([1]) + + for axis in range(x.ndim): + y = lfilter(b, a, x, axis) + y_r = np.apply_along_axis(lambda w: lfilter(b, a, w), axis, x) + assert_array_almost_equal(y, y_r) + + def test_rank_3_FIR_init_cond(self): + x = self.generate((4, 3, 2)) + b = self.convert_dtype([1, 0, -1]) + a = self.convert_dtype([1]) + + for axis in range(x.ndim): + zi_shape = list(x.shape) + zi_shape[axis] = 2 + zi = self.convert_dtype(np.ones(zi_shape)) + zi1 = self.convert_dtype([1, 1]) + y, zf = lfilter(b, a, x, axis, zi) + def lf0(w): + return lfilter(b, a, w, zi=zi1)[0] + def lf1(w): + return lfilter(b, a, w, zi=zi1)[1] + y_r = np.apply_along_axis(lf0, axis, x) + zf_r = np.apply_along_axis(lf1, axis, x) + assert_array_almost_equal(y, y_r) + assert_array_almost_equal(zf, zf_r) + + def test_zi_pseudobroadcast(self): + x = self.generate((4, 5, 20)) + b,a = signal.butter(8, 0.2, output='ba') + b = self.convert_dtype(b) + a = self.convert_dtype(a) + zi_size = b.shape[0] - 1 + + # lfilter requires x.ndim == zi.ndim exactly. However, zi can have + # length 1 dimensions. + zi_full = self.convert_dtype(np.ones((4, 5, zi_size))) + zi_sing = self.convert_dtype(np.ones((1, 1, zi_size))) + + y_full, zf_full = lfilter(b, a, x, zi=zi_full) + y_sing, zf_sing = lfilter(b, a, x, zi=zi_sing) + + assert_array_almost_equal(y_sing, y_full) + assert_array_almost_equal(zf_full, zf_sing) + + # lfilter does not prepend ones + assert_raises(ValueError, lfilter, b, a, x, -1, np.ones(zi_size)) + + def test_scalar_a(self): + # a can be a scalar. + x = self.generate(6) + b = self.convert_dtype([1, 0, -1]) + a = self.convert_dtype([1]) + y_r = self.convert_dtype([0, 1, 2, 2, 2, 2]) + + y = lfilter(b, a[0], x) + assert_array_almost_equal(y, y_r) + + def test_zi_some_singleton_dims(self): + # lfilter doesn't really broadcast (no prepending of 1's). But does + # do singleton expansion if x and zi have the same ndim. This was + # broken only if a subset of the axes were singletons (gh-4681). + x = self.convert_dtype(np.zeros((3,2,5), 'l')) + b = self.convert_dtype(np.ones(5, 'l')) + a = self.convert_dtype(np.array([1,0,0])) + zi = np.ones((3,1,4), 'l') + zi[1,:,:] *= 2 + zi[2,:,:] *= 3 + zi = self.convert_dtype(zi) + + zf_expected = self.convert_dtype(np.zeros((3,2,4), 'l')) + y_expected = np.zeros((3,2,5), 'l') + y_expected[:,:,:4] = [[[1]], [[2]], [[3]]] + y_expected = self.convert_dtype(y_expected) + + # IIR + y_iir, zf_iir = lfilter(b, a, x, -1, zi) + assert_array_almost_equal(y_iir, y_expected) + assert_array_almost_equal(zf_iir, zf_expected) + + # FIR + y_fir, zf_fir = lfilter(b, a[0], x, -1, zi) + assert_array_almost_equal(y_fir, y_expected) + assert_array_almost_equal(zf_fir, zf_expected) + + def base_bad_size_zi(self, b, a, x, axis, zi): + b = self.convert_dtype(b) + a = self.convert_dtype(a) + x = self.convert_dtype(x) + zi = self.convert_dtype(zi) + assert_raises(ValueError, lfilter, b, a, x, axis, zi) + + def test_bad_size_zi(self): + # rank 1 + x1 = np.arange(6) + self.base_bad_size_zi([1], [1], x1, -1, [1]) + self.base_bad_size_zi([1, 1], [1], x1, -1, [0, 1]) + self.base_bad_size_zi([1, 1], [1], x1, -1, [[0]]) + self.base_bad_size_zi([1, 1], [1], x1, -1, [0, 1, 2]) + self.base_bad_size_zi([1, 1, 1], [1], x1, -1, [[0]]) + self.base_bad_size_zi([1, 1, 1], [1], x1, -1, [0, 1, 2]) + self.base_bad_size_zi([1], [1, 1], x1, -1, [0, 1]) + self.base_bad_size_zi([1], [1, 1], x1, -1, [[0]]) + self.base_bad_size_zi([1], [1, 1], x1, -1, [0, 1, 2]) + self.base_bad_size_zi([1, 1, 1], [1, 1], x1, -1, [0]) + self.base_bad_size_zi([1, 1, 1], [1, 1], x1, -1, [[0], [1]]) + self.base_bad_size_zi([1, 1, 1], [1, 1], x1, -1, [0, 1, 2]) + self.base_bad_size_zi([1, 1, 1], [1, 1], x1, -1, [0, 1, 2, 3]) + self.base_bad_size_zi([1, 1], [1, 1, 1], x1, -1, [0]) + self.base_bad_size_zi([1, 1], [1, 1, 1], x1, -1, [[0], [1]]) + self.base_bad_size_zi([1, 1], [1, 1, 1], x1, -1, [0, 1, 2]) + self.base_bad_size_zi([1, 1], [1, 1, 1], x1, -1, [0, 1, 2, 3]) + + # rank 2 + x2 = np.arange(12).reshape((4,3)) + # for axis=0 zi.shape should == (max(len(a),len(b))-1, 3) + self.base_bad_size_zi([1], [1], x2, 0, [0]) + + # for each of these there are 5 cases tested (in this order): + # 1. not deep enough, right # elements + # 2. too deep, right # elements + # 3. right depth, right # elements, transposed + # 4. right depth, too few elements + # 5. right depth, too many elements + + self.base_bad_size_zi([1, 1], [1], x2, 0, [0,1,2]) + self.base_bad_size_zi([1, 1], [1], x2, 0, [[[0,1,2]]]) + self.base_bad_size_zi([1, 1], [1], x2, 0, [[0], [1], [2]]) + self.base_bad_size_zi([1, 1], [1], x2, 0, [[0,1]]) + self.base_bad_size_zi([1, 1], [1], x2, 0, [[0,1,2,3]]) + + self.base_bad_size_zi([1, 1, 1], [1], x2, 0, [0,1,2,3,4,5]) + self.base_bad_size_zi([1, 1, 1], [1], x2, 0, [[[0,1,2],[3,4,5]]]) + self.base_bad_size_zi([1, 1, 1], [1], x2, 0, [[0,1],[2,3],[4,5]]) + self.base_bad_size_zi([1, 1, 1], [1], x2, 0, [[0,1],[2,3]]) + self.base_bad_size_zi([1, 1, 1], [1], x2, 0, [[0,1,2,3],[4,5,6,7]]) + + self.base_bad_size_zi([1], [1, 1], x2, 0, [0,1,2]) + self.base_bad_size_zi([1], [1, 1], x2, 0, [[[0,1,2]]]) + self.base_bad_size_zi([1], [1, 1], x2, 0, [[0], [1], [2]]) + self.base_bad_size_zi([1], [1, 1], x2, 0, [[0,1]]) + self.base_bad_size_zi([1], [1, 1], x2, 0, [[0,1,2,3]]) + + self.base_bad_size_zi([1], [1, 1, 1], x2, 0, [0,1,2,3,4,5]) + self.base_bad_size_zi([1], [1, 1, 1], x2, 0, [[[0,1,2],[3,4,5]]]) + self.base_bad_size_zi([1], [1, 1, 1], x2, 0, [[0,1],[2,3],[4,5]]) + self.base_bad_size_zi([1], [1, 1, 1], x2, 0, [[0,1],[2,3]]) + self.base_bad_size_zi([1], [1, 1, 1], x2, 0, [[0,1,2,3],[4,5,6,7]]) + + self.base_bad_size_zi([1, 1, 1], [1, 1], x2, 0, [0,1,2,3,4,5]) + self.base_bad_size_zi([1, 1, 1], [1, 1], x2, 0, [[[0,1,2],[3,4,5]]]) + self.base_bad_size_zi([1, 1, 1], [1, 1], x2, 0, [[0,1],[2,3],[4,5]]) + self.base_bad_size_zi([1, 1, 1], [1, 1], x2, 0, [[0,1],[2,3]]) + self.base_bad_size_zi([1, 1, 1], [1, 1], x2, 0, [[0,1,2,3],[4,5,6,7]]) + + # for axis=1 zi.shape should == (4, max(len(a),len(b))-1) + self.base_bad_size_zi([1], [1], x2, 1, [0]) + + self.base_bad_size_zi([1, 1], [1], x2, 1, [0,1,2,3]) + self.base_bad_size_zi([1, 1], [1], x2, 1, [[[0],[1],[2],[3]]]) + self.base_bad_size_zi([1, 1], [1], x2, 1, [[0, 1, 2, 3]]) + self.base_bad_size_zi([1, 1], [1], x2, 1, [[0],[1],[2]]) + self.base_bad_size_zi([1, 1], [1], x2, 1, [[0],[1],[2],[3],[4]]) + + self.base_bad_size_zi([1, 1, 1], [1], x2, 1, [0,1,2,3,4,5,6,7]) + self.base_bad_size_zi([1, 1, 1], [1], x2, 1, [[[0,1],[2,3],[4,5],[6,7]]]) + self.base_bad_size_zi([1, 1, 1], [1], x2, 1, [[0,1,2,3],[4,5,6,7]]) + self.base_bad_size_zi([1, 1, 1], [1], x2, 1, [[0,1],[2,3],[4,5]]) + self.base_bad_size_zi([1, 1, 1], [1], x2, 1, [[0,1],[2,3],[4,5],[6,7],[8,9]]) + + self.base_bad_size_zi([1], [1, 1], x2, 1, [0,1,2,3]) + self.base_bad_size_zi([1], [1, 1], x2, 1, [[[0],[1],[2],[3]]]) + self.base_bad_size_zi([1], [1, 1], x2, 1, [[0, 1, 2, 3]]) + self.base_bad_size_zi([1], [1, 1], x2, 1, [[0],[1],[2]]) + self.base_bad_size_zi([1], [1, 1], x2, 1, [[0],[1],[2],[3],[4]]) + + self.base_bad_size_zi([1], [1, 1, 1], x2, 1, [0,1,2,3,4,5,6,7]) + self.base_bad_size_zi([1], [1, 1, 1], x2, 1, [[[0,1],[2,3],[4,5],[6,7]]]) + self.base_bad_size_zi([1], [1, 1, 1], x2, 1, [[0,1,2,3],[4,5,6,7]]) + self.base_bad_size_zi([1], [1, 1, 1], x2, 1, [[0,1],[2,3],[4,5]]) + self.base_bad_size_zi([1], [1, 1, 1], x2, 1, [[0,1],[2,3],[4,5],[6,7],[8,9]]) + + self.base_bad_size_zi([1, 1, 1], [1, 1], x2, 1, [0,1,2,3,4,5,6,7]) + self.base_bad_size_zi([1, 1, 1], [1, 1], x2, 1, [[[0,1],[2,3],[4,5],[6,7]]]) + self.base_bad_size_zi([1, 1, 1], [1, 1], x2, 1, [[0,1,2,3],[4,5,6,7]]) + self.base_bad_size_zi([1, 1, 1], [1, 1], x2, 1, [[0,1],[2,3],[4,5]]) + self.base_bad_size_zi([1, 1, 1], [1, 1], x2, 1, [[0,1],[2,3],[4,5],[6,7],[8,9]]) + + def test_empty_zi(self): + # Regression test for #880: empty array for zi crashes. + x = self.generate((5,)) + a = self.convert_dtype([1]) + b = self.convert_dtype([1]) + zi = self.convert_dtype([]) + y, zf = lfilter(b, a, x, zi=zi) + assert_array_almost_equal(y, x) + assert_equal(zf.dtype, self.dtype) + assert_equal(zf.size, 0) + + def test_lfiltic_bad_zi(self): + # Regression test for #3699: bad initial conditions + a = self.convert_dtype([1]) + b = self.convert_dtype([1]) + # "y" sets the datatype of zi, so it truncates if int + zi = lfiltic(b, a, [1., 0]) + zi_1 = lfiltic(b, a, [1, 0]) + zi_2 = lfiltic(b, a, [True, False]) + assert_array_equal(zi, zi_1) + assert_array_equal(zi, zi_2) + + def test_short_x_FIR(self): + # regression test for #5116 + # x shorter than b, with non None zi fails + a = self.convert_dtype([1]) + b = self.convert_dtype([1, 0, -1]) + zi = self.convert_dtype([2, 7]) + x = self.convert_dtype([72]) + ye = self.convert_dtype([74]) + zfe = self.convert_dtype([7, -72]) + y, zf = lfilter(b, a, x, zi=zi) + assert_array_almost_equal(y, ye) + assert_array_almost_equal(zf, zfe) + + def test_short_x_IIR(self): + # regression test for #5116 + # x shorter than b, with non None zi fails + a = self.convert_dtype([1, 1]) + b = self.convert_dtype([1, 0, -1]) + zi = self.convert_dtype([2, 7]) + x = self.convert_dtype([72]) + ye = self.convert_dtype([74]) + zfe = self.convert_dtype([-67, -72]) + y, zf = lfilter(b, a, x, zi=zi) + assert_array_almost_equal(y, ye) + assert_array_almost_equal(zf, zfe) + + def test_do_not_modify_a_b_IIR(self): + x = self.generate((6,)) + b = self.convert_dtype([1, -1]) + b0 = b.copy() + a = self.convert_dtype([0.5, -0.5]) + a0 = a.copy() + y_r = self.convert_dtype([0, 2, 4, 6, 8, 10.]) + y_f = lfilter(b, a, x) + assert_array_almost_equal(y_f, y_r) + assert_equal(b, b0) + assert_equal(a, a0) + + def test_do_not_modify_a_b_FIR(self): + x = self.generate((6,)) + b = self.convert_dtype([1, 0, 1]) + b0 = b.copy() + a = self.convert_dtype([2]) + a0 = a.copy() + y_r = self.convert_dtype([0, 0.5, 1, 2, 3, 4.]) + y_f = lfilter(b, a, x) + assert_array_almost_equal(y_f, y_r) + assert_equal(b, b0) + assert_equal(a, a0) + + @pytest.mark.parametrize("a", [1.0, [1.0], np.array(1.0)]) + @pytest.mark.parametrize("b", [1.0, [1.0], np.array(1.0)]) + def test_scalar_input(self, a, b): + data = np.random.randn(10) + assert_allclose( + lfilter(np.array([1.0]), np.array([1.0]), data), + lfilter(b, a, data)) + + @pytest.mark.thread_unsafe + def test_dtype_deprecation(self): + # gh-21211 + a = np.asarray([1, 2, 3, 6, 5, 3], dtype=object) + b = np.asarray([2, 3, 4, 5, 3, 4, 2, 2, 1], dtype=object) + with pytest.deprecated_call(match="dtype=object is not supported"): + lfilter(a, b, [1, 2, 3, 4]) + + +class TestLinearFilterFloat32(_TestLinearFilter): + dtype = np.dtype('f') + + +class TestLinearFilterFloat64(_TestLinearFilter): + dtype = np.dtype('d') + + +@pytest.mark.filterwarnings('ignore::DeprecationWarning') +class TestLinearFilterFloatExtended(_TestLinearFilter): + dtype = np.dtype('g') + + +class TestLinearFilterComplex64(_TestLinearFilter): + dtype = np.dtype('F') + + +class TestLinearFilterComplex128(_TestLinearFilter): + dtype = np.dtype('D') + + +@pytest.mark.filterwarnings('ignore::DeprecationWarning') +class TestLinearFilterComplexExtended(_TestLinearFilter): + dtype = np.dtype('G') + + +@pytest.mark.filterwarnings('ignore::DeprecationWarning') +class TestLinearFilterDecimal(_TestLinearFilter): + dtype = np.dtype('O') + + def type(self, x): + return Decimal(str(x)) + + +@pytest.mark.filterwarnings('ignore::DeprecationWarning') +class TestLinearFilterObject(_TestLinearFilter): + dtype = np.dtype('O') + type = float + + +@pytest.mark.filterwarnings('ignore::DeprecationWarning') +def test_lfilter_bad_object(): + # lfilter: object arrays with non-numeric objects raise TypeError. + # Regression test for ticket #1452. + if hasattr(sys, 'abiflags') and 'd' in sys.abiflags: + pytest.skip('test is flaky when run with python3-dbg') + assert_raises(TypeError, lfilter, [1.0], [1.0], [1.0, None, 2.0]) + assert_raises(TypeError, lfilter, [1.0], [None], [1.0, 2.0, 3.0]) + assert_raises(TypeError, lfilter, [None], [1.0], [1.0, 2.0, 3.0]) + + +_pmf = pytest.mark.filterwarnings('ignore::DeprecationWarning') + +def test_lfilter_notimplemented_input(): + # Should not crash, gh-7991 + assert_raises(NotImplementedError, lfilter, [2,3], [4,5], [1,2,3,4,5]) + + +@pytest.mark.parametrize('dt', [np.ubyte, np.byte, np.ushort, np.short, + np_ulong, np_long, np.ulonglong, np.ulonglong, + np.float32, np.float64, + pytest.param(np.longdouble, marks=_pmf), + pytest.param(Decimal, marks=_pmf)] +) +class TestCorrelateReal: + def _setup_rank1(self, dt): + a = np.linspace(0, 3, 4).astype(dt) + b = np.linspace(1, 2, 2).astype(dt) + + y_r = np.array([0, 2, 5, 8, 3]).astype(dt) + return a, b, y_r + + def equal_tolerance(self, res_dt): + # default value of keyword + decimal = 6 + try: + dt_info = np.finfo(res_dt) + if hasattr(dt_info, 'resolution'): + decimal = int(-0.5*np.log10(dt_info.resolution)) + except Exception: + pass + return decimal + + def equal_tolerance_fft(self, res_dt): + # FFT implementations convert longdouble arguments down to + # double so don't expect better precision, see gh-9520 + if res_dt == np.longdouble: + return self.equal_tolerance(np.float64) + else: + return self.equal_tolerance(res_dt) + + def test_method(self, dt): + if dt == Decimal: + method = choose_conv_method([Decimal(4)], [Decimal(3)]) + assert_equal(method, 'direct') + else: + a, b, y_r = self._setup_rank3(dt) + y_fft = correlate(a, b, method='fft') + y_direct = correlate(a, b, method='direct') + + assert_array_almost_equal(y_r, + y_fft, + decimal=self.equal_tolerance_fft(y_fft.dtype),) + assert_array_almost_equal(y_r, + y_direct, + decimal=self.equal_tolerance(y_direct.dtype),) + assert_equal(y_fft.dtype, dt) + assert_equal(y_direct.dtype, dt) + + def test_rank1_valid(self, dt): + a, b, y_r = self._setup_rank1(dt) + y = correlate(a, b, 'valid') + assert_array_almost_equal(y, y_r[1:4]) + assert_equal(y.dtype, dt) + + # See gh-5897 + y = correlate(b, a, 'valid') + assert_array_almost_equal(y, y_r[1:4][::-1]) + assert_equal(y.dtype, dt) + + def test_rank1_same(self, dt): + a, b, y_r = self._setup_rank1(dt) + y = correlate(a, b, 'same') + assert_array_almost_equal(y, y_r[:-1]) + assert_equal(y.dtype, dt) + + def test_rank1_full(self, dt): + a, b, y_r = self._setup_rank1(dt) + y = correlate(a, b, 'full') + assert_array_almost_equal(y, y_r) + assert_equal(y.dtype, dt) + + def _setup_rank3(self, dt): + a = np.linspace(0, 39, 40).reshape((2, 4, 5), order='F').astype( + dt) + b = np.linspace(0, 23, 24).reshape((2, 3, 4), order='F').astype( + dt) + + y_r = array([[[0., 184., 504., 912., 1360., 888., 472., 160.], + [46., 432., 1062., 1840., 2672., 1698., 864., 266.], + [134., 736., 1662., 2768., 3920., 2418., 1168., 314.], + [260., 952., 1932., 3056., 4208., 2580., 1240., 332.], + [202., 664., 1290., 1984., 2688., 1590., 712., 150.], + [114., 344., 642., 960., 1280., 726., 296., 38.]], + + [[23., 400., 1035., 1832., 2696., 1737., 904., 293.], + [134., 920., 2166., 3680., 5280., 3306., 1640., 474.], + [325., 1544., 3369., 5512., 7720., 4683., 2192., 535.], + [571., 1964., 3891., 6064., 8272., 4989., 2324., 565.], + [434., 1360., 2586., 3920., 5264., 3054., 1312., 230.], + [241., 700., 1281., 1888., 2496., 1383., 532., 39.]], + + [[22., 214., 528., 916., 1332., 846., 430., 132.], + [86., 484., 1098., 1832., 2600., 1602., 772., 206.], + [188., 802., 1698., 2732., 3788., 2256., 1018., 218.], + [308., 1006., 1950., 2996., 4052., 2400., 1078., 230.], + [230., 692., 1290., 1928., 2568., 1458., 596., 78.], + [126., 354., 636., 924., 1212., 654., 234., 0.]]], + dtype=np.float64).astype(dt) + + return a, b, y_r + + def test_rank3_valid(self, dt): + a, b, y_r = self._setup_rank3(dt) + y = correlate(a, b, "valid") + assert_array_almost_equal(y, y_r[1:2, 2:4, 3:5]) + assert_equal(y.dtype, dt) + + # See gh-5897 + y = correlate(b, a, "valid") + assert_array_almost_equal(y, y_r[1:2, 2:4, 3:5][::-1, ::-1, ::-1]) + assert_equal(y.dtype, dt) + + def test_rank3_same(self, dt): + a, b, y_r = self._setup_rank3(dt) + y = correlate(a, b, "same") + assert_array_almost_equal(y, y_r[0:-1, 1:-1, 1:-2]) + assert_equal(y.dtype, dt) + + def test_rank3_all(self, dt): + a, b, y_r = self._setup_rank3(dt) + y = correlate(a, b) + assert_array_almost_equal(y, y_r) + assert_equal(y.dtype, dt) + + +class TestCorrelate: + # Tests that don't depend on dtype + + def test_invalid_shapes(self): + # By "invalid," we mean that no one + # array has dimensions that are all at + # least as large as the corresponding + # dimensions of the other array. This + # setup should throw a ValueError. + a = np.arange(1, 7).reshape((2, 3)) + b = np.arange(-6, 0).reshape((3, 2)) + + assert_raises(ValueError, correlate, *(a, b), **{'mode': 'valid'}) + assert_raises(ValueError, correlate, *(b, a), **{'mode': 'valid'}) + + def test_invalid_params(self): + a = [3, 4, 5] + b = [1, 2, 3] + assert_raises(ValueError, correlate, a, b, mode='spam') + assert_raises(ValueError, correlate, a, b, mode='eggs', method='fft') + assert_raises(ValueError, correlate, a, b, mode='ham', method='direct') + assert_raises(ValueError, correlate, a, b, mode='full', method='bacon') + assert_raises(ValueError, correlate, a, b, mode='same', method='bacon') + + def test_mismatched_dims(self): + # Input arrays should have the same number of dimensions + assert_raises(ValueError, correlate, [1], 2, method='direct') + assert_raises(ValueError, correlate, 1, [2], method='direct') + assert_raises(ValueError, correlate, [1], 2, method='fft') + assert_raises(ValueError, correlate, 1, [2], method='fft') + assert_raises(ValueError, correlate, [1], [[2]]) + assert_raises(ValueError, correlate, [3], 2) + + def test_numpy_fastpath(self): + a = [1, 2, 3] + b = [4, 5] + assert_allclose(correlate(a, b, mode='same'), [5, 14, 23]) + + a = [1, 2, 3] + b = [4, 5, 6] + assert_allclose(correlate(a, b, mode='same'), [17, 32, 23]) + assert_allclose(correlate(a, b, mode='full'), [6, 17, 32, 23, 12]) + assert_allclose(correlate(a, b, mode='valid'), [32]) + + @pytest.mark.thread_unsafe + def test_dtype_deprecation(self): + # gh-21211 + a = np.asarray([1, 2, 3, 6, 5, 3], dtype=object) + b = np.asarray([2, 3, 4, 5, 3, 4, 2, 2, 1], dtype=object) + with pytest.deprecated_call(match="dtype=object is not supported"): + correlate(a, b) + + +@pytest.mark.parametrize("mode", ["valid", "same", "full"]) +@pytest.mark.parametrize("behind", [True, False]) +@pytest.mark.parametrize("input_size", [100, 101, 1000, 1001, 10000, 10001]) +def test_correlation_lags(mode, behind, input_size): + # generate random data + rng = np.random.RandomState(0) + in1 = rng.standard_normal(input_size) + offset = int(input_size/10) + # generate offset version of array to correlate with + if behind: + # y is behind x + in2 = np.concatenate([rng.standard_normal(offset), in1]) + expected = -offset + else: + # y is ahead of x + in2 = in1[offset:] + expected = offset + # cross correlate, returning lag information + correlation = correlate(in1, in2, mode=mode) + lags = correlation_lags(in1.size, in2.size, mode=mode) + # identify the peak + lag_index = np.argmax(correlation) + # Check as expected + assert_equal(lags[lag_index], expected) + # Correlation and lags shape should match + assert_equal(lags.shape, correlation.shape) + + +def test_correlation_lags_invalid_mode(): + with pytest.raises(ValueError, match="Mode asdfgh is invalid"): + correlation_lags(100, 100, mode="asdfgh") + + +@pytest.mark.parametrize('dt', [np.csingle, np.cdouble, + pytest.param(np.clongdouble, marks=_pmf)]) +class TestCorrelateComplex: + # The decimal precision to be used for comparing results. + # This value will be passed as the 'decimal' keyword argument of + # assert_array_almost_equal(). + # Since correlate may chose to use FFT method which converts + # longdoubles to doubles internally don't expect better precision + # for longdouble than for double (see gh-9520). + + def decimal(self, dt): + if dt == np.clongdouble: + dt = np.cdouble + return int(2 * np.finfo(dt).precision / 3) + + def _setup_rank1(self, dt, mode): + np.random.seed(9) + a = np.random.randn(10).astype(dt) + a += 1j * np.random.randn(10).astype(dt) + b = np.random.randn(8).astype(dt) + b += 1j * np.random.randn(8).astype(dt) + + y_r = (correlate(a.real, b.real, mode=mode) + + correlate(a.imag, b.imag, mode=mode)).astype(dt) + y_r += 1j * (-correlate(a.real, b.imag, mode=mode) + + correlate(a.imag, b.real, mode=mode)) + return a, b, y_r + + def test_rank1_valid(self, dt): + a, b, y_r = self._setup_rank1(dt, 'valid') + y = correlate(a, b, 'valid') + assert_array_almost_equal(y, y_r, decimal=self.decimal(dt)) + assert_equal(y.dtype, dt) + + # See gh-5897 + y = correlate(b, a, 'valid') + assert_array_almost_equal(y, y_r[::-1].conj(), decimal=self.decimal(dt)) + assert_equal(y.dtype, dt) + + def test_rank1_same(self, dt): + a, b, y_r = self._setup_rank1(dt, 'same') + y = correlate(a, b, 'same') + assert_array_almost_equal(y, y_r, decimal=self.decimal(dt)) + assert_equal(y.dtype, dt) + + def test_rank1_full(self, dt): + a, b, y_r = self._setup_rank1(dt, 'full') + y = correlate(a, b, 'full') + assert_array_almost_equal(y, y_r, decimal=self.decimal(dt)) + assert_equal(y.dtype, dt) + + def test_swap_full(self, dt): + d = np.array([0.+0.j, 1.+1.j, 2.+2.j], dtype=dt) + k = np.array([1.+3.j, 2.+4.j, 3.+5.j, 4.+6.j], dtype=dt) + y = correlate(d, k) + assert_equal(y, [0.+0.j, 10.-2.j, 28.-6.j, 22.-6.j, 16.-6.j, 8.-4.j]) + + def test_swap_same(self, dt): + d = [0.+0.j, 1.+1.j, 2.+2.j] + k = [1.+3.j, 2.+4.j, 3.+5.j, 4.+6.j] + y = correlate(d, k, mode="same") + assert_equal(y, [10.-2.j, 28.-6.j, 22.-6.j]) + + def test_rank3(self, dt): + a = np.random.randn(10, 8, 6).astype(dt) + a += 1j * np.random.randn(10, 8, 6).astype(dt) + b = np.random.randn(8, 6, 4).astype(dt) + b += 1j * np.random.randn(8, 6, 4).astype(dt) + + y_r = (correlate(a.real, b.real) + + correlate(a.imag, b.imag)).astype(dt) + y_r += 1j * (-correlate(a.real, b.imag) + correlate(a.imag, b.real)) + + y = correlate(a, b, 'full') + assert_array_almost_equal(y, y_r, decimal=self.decimal(dt) - 1) + assert_equal(y.dtype, dt) + + def test_rank0(self, dt): + a = np.array(np.random.randn()).astype(dt) + a += 1j * np.array(np.random.randn()).astype(dt) + b = np.array(np.random.randn()).astype(dt) + b += 1j * np.array(np.random.randn()).astype(dt) + + y_r = (correlate(a.real, b.real) + + correlate(a.imag, b.imag)).astype(dt) + y_r += 1j * np.array(-correlate(a.real, b.imag) + + correlate(a.imag, b.real)) + + y = correlate(a, b, 'full') + assert_array_almost_equal(y, y_r, decimal=self.decimal(dt) - 1) + assert_equal(y.dtype, dt) + + assert_equal(correlate([1], [2j]), correlate(1, 2j)) + assert_equal(correlate([2j], [3j]), correlate(2j, 3j)) + assert_equal(correlate([3j], [4]), correlate(3j, 4)) + + +class TestCorrelate2d: + + def test_consistency_correlate_funcs(self): + # Compare np.correlate, signal.correlate, signal.correlate2d + a = np.arange(5) + b = np.array([3.2, 1.4, 3]) + for mode in ['full', 'valid', 'same']: + assert_almost_equal(np.correlate(a, b, mode=mode), + signal.correlate(a, b, mode=mode)) + assert_almost_equal(np.squeeze(signal.correlate2d([a], [b], + mode=mode)), + signal.correlate(a, b, mode=mode)) + + # See gh-5897 + if mode == 'valid': + assert_almost_equal(np.correlate(b, a, mode=mode), + signal.correlate(b, a, mode=mode)) + assert_almost_equal(np.squeeze(signal.correlate2d([b], [a], + mode=mode)), + signal.correlate(b, a, mode=mode)) + + def test_invalid_shapes(self): + # By "invalid," we mean that no one + # array has dimensions that are all at + # least as large as the corresponding + # dimensions of the other array. This + # setup should throw a ValueError. + a = np.arange(1, 7).reshape((2, 3)) + b = np.arange(-6, 0).reshape((3, 2)) + + assert_raises(ValueError, signal.correlate2d, *(a, b), **{'mode': 'valid'}) + assert_raises(ValueError, signal.correlate2d, *(b, a), **{'mode': 'valid'}) + + def test_complex_input(self): + assert_equal(signal.correlate2d([[1]], [[2j]]), -2j) + assert_equal(signal.correlate2d([[2j]], [[3j]]), 6) + assert_equal(signal.correlate2d([[3j]], [[4]]), 12j) + + +class TestLFilterZI: + + def test_basic(self): + a = np.array([1.0, -1.0, 0.5]) + b = np.array([1.0, 0.0, 2.0]) + zi_expected = np.array([5.0, -1.0]) + zi = lfilter_zi(b, a) + assert_array_almost_equal(zi, zi_expected) + + def test_scale_invariance(self): + # Regression test. There was a bug in which b was not correctly + # rescaled when a[0] was nonzero. + b = np.array([2, 8, 5]) + a = np.array([1, 1, 8]) + zi1 = lfilter_zi(b, a) + zi2 = lfilter_zi(2*b, 2*a) + assert_allclose(zi2, zi1, rtol=1e-12) + + @pytest.mark.parametrize('dtype', [np.float32, np.float64]) + def test_types(self, dtype): + b = np.zeros((8), dtype=dtype) + a = np.array([1], dtype=dtype) + assert_equal(np.real(signal.lfilter_zi(b, a)).dtype, dtype) + + +class TestFiltFilt: + filtfilt_kind = 'tf' + + def filtfilt(self, zpk, x, axis=-1, padtype='odd', padlen=None, + method='pad', irlen=None): + if self.filtfilt_kind == 'tf': + b, a = zpk2tf(*zpk) + return filtfilt(b, a, x, axis, padtype, padlen, method, irlen) + elif self.filtfilt_kind == 'sos': + sos = zpk2sos(*zpk) + return sosfiltfilt(sos, x, axis, padtype, padlen) + + def test_basic(self): + zpk = tf2zpk([1, 2, 3], [1, 2, 3]) + out = self.filtfilt(zpk, np.arange(12)) + assert_allclose(out, arange(12), atol=5.28e-11) + + def test_sine(self): + rate = 2000 + t = np.linspace(0, 1.0, rate + 1) + # A signal with low frequency and a high frequency. + xlow = np.sin(5 * 2 * np.pi * t) + xhigh = np.sin(250 * 2 * np.pi * t) + x = xlow + xhigh + + zpk = butter(8, 0.125, output='zpk') + # r is the magnitude of the largest pole. + r = np.abs(zpk[1]).max() + eps = 1e-5 + # n estimates the number of steps for the + # transient to decay by a factor of eps. + n = int(np.ceil(np.log(eps) / np.log(r))) + + # High order lowpass filter... + y = self.filtfilt(zpk, x, padlen=n) + # Result should be just xlow. + err = np.abs(y - xlow).max() + assert_(err < 1e-4) + + # A 2D case. + x2d = np.vstack([xlow, xlow + xhigh]) + y2d = self.filtfilt(zpk, x2d, padlen=n, axis=1) + assert_equal(y2d.shape, x2d.shape) + err = np.abs(y2d - xlow).max() + assert_(err < 1e-4) + + # Use the previous result to check the use of the axis keyword. + # (Regression test for ticket #1620) + y2dt = self.filtfilt(zpk, x2d.T, padlen=n, axis=0) + assert_equal(y2d, y2dt.T) + + def test_axis(self): + # Test the 'axis' keyword on a 3D array. + x = np.arange(10.0 * 11.0 * 12.0).reshape(10, 11, 12) + zpk = butter(3, 0.125, output='zpk') + y0 = self.filtfilt(zpk, x, padlen=0, axis=0) + y1 = self.filtfilt(zpk, np.swapaxes(x, 0, 1), padlen=0, axis=1) + assert_array_equal(y0, np.swapaxes(y1, 0, 1)) + y2 = self.filtfilt(zpk, np.swapaxes(x, 0, 2), padlen=0, axis=2) + assert_array_equal(y0, np.swapaxes(y2, 0, 2)) + + def test_acoeff(self): + if self.filtfilt_kind != 'tf': + return # only necessary for TF + # test for 'a' coefficient as single number + out = signal.filtfilt([.5, .5], 1, np.arange(10)) + assert_allclose(out, np.arange(10), rtol=1e-14, atol=1e-14) + + def test_gust_simple(self): + if self.filtfilt_kind != 'tf': + pytest.skip('gust only implemented for TF systems') + # The input array has length 2. The exact solution for this case + # was computed "by hand". + x = np.array([1.0, 2.0]) + b = np.array([0.5]) + a = np.array([1.0, -0.5]) + y, z1, z2 = _filtfilt_gust(b, a, x) + assert_allclose([z1[0], z2[0]], + [0.3*x[0] + 0.2*x[1], 0.2*x[0] + 0.3*x[1]]) + assert_allclose(y, [z1[0] + 0.25*z2[0] + 0.25*x[0] + 0.125*x[1], + 0.25*z1[0] + z2[0] + 0.125*x[0] + 0.25*x[1]]) + + def test_gust_scalars(self): + if self.filtfilt_kind != 'tf': + pytest.skip('gust only implemented for TF systems') + # The filter coefficients are both scalars, so the filter simply + # multiplies its input by b/a. When it is used in filtfilt, the + # factor is (b/a)**2. + x = np.arange(12) + b = 3.0 + a = 2.0 + y = filtfilt(b, a, x, method="gust") + expected = (b/a)**2 * x + assert_allclose(y, expected) + + +class TestSOSFiltFilt(TestFiltFilt): + filtfilt_kind = 'sos' + + def test_equivalence(self): + """Test equivalence between sosfiltfilt and filtfilt""" + x = np.random.RandomState(0).randn(1000) + for order in range(1, 6): + zpk = signal.butter(order, 0.35, output='zpk') + b, a = zpk2tf(*zpk) + sos = zpk2sos(*zpk) + y = filtfilt(b, a, x) + y_sos = sosfiltfilt(sos, x) + assert_allclose(y, y_sos, atol=1e-12, err_msg=f'order={order}') + + +def filtfilt_gust_opt(b, a, x): + """ + An alternative implementation of filtfilt with Gustafsson edges. + + This function computes the same result as + `scipy.signal._signaltools._filtfilt_gust`, but only 1-d arrays + are accepted. The problem is solved using `fmin` from `scipy.optimize`. + `_filtfilt_gust` is significantly faster than this implementation. + """ + def filtfilt_gust_opt_func(ics, b, a, x): + """Objective function used in filtfilt_gust_opt.""" + m = max(len(a), len(b)) - 1 + z0f = ics[:m] + z0b = ics[m:] + y_f = lfilter(b, a, x, zi=z0f)[0] + y_fb = lfilter(b, a, y_f[::-1], zi=z0b)[0][::-1] + + y_b = lfilter(b, a, x[::-1], zi=z0b)[0][::-1] + y_bf = lfilter(b, a, y_b, zi=z0f)[0] + value = np.sum((y_fb - y_bf)**2) + return value + + m = max(len(a), len(b)) - 1 + zi = lfilter_zi(b, a) + ics = np.concatenate((x[:m].mean()*zi, x[-m:].mean()*zi)) + result = fmin(filtfilt_gust_opt_func, ics, args=(b, a, x), + xtol=1e-10, ftol=1e-12, + maxfun=10000, maxiter=10000, + full_output=True, disp=False) + opt, fopt, niter, funcalls, warnflag = result + if warnflag > 0: + raise RuntimeError("minimization failed in filtfilt_gust_opt: " + "warnflag=%d" % warnflag) + z0f = opt[:m] + z0b = opt[m:] + + # Apply the forward-backward filter using the computed initial + # conditions. + y_b = lfilter(b, a, x[::-1], zi=z0b)[0][::-1] + y = lfilter(b, a, y_b, zi=z0f)[0] + + return y, z0f, z0b + + +def check_filtfilt_gust(b, a, shape, axis, irlen=None): + # Generate x, the data to be filtered. + np.random.seed(123) + x = np.random.randn(*shape) + + # Apply filtfilt to x. This is the main calculation to be checked. + y = filtfilt(b, a, x, axis=axis, method="gust", irlen=irlen) + + # Also call the private function so we can test the ICs. + yg, zg1, zg2 = _filtfilt_gust(b, a, x, axis=axis, irlen=irlen) + + # filtfilt_gust_opt is an independent implementation that gives the + # expected result, but it only handles 1-D arrays, so use some looping + # and reshaping shenanigans to create the expected output arrays. + xx = np.swapaxes(x, axis, -1) + out_shape = xx.shape[:-1] + yo = np.empty_like(xx) + m = max(len(a), len(b)) - 1 + zo1 = np.empty(out_shape + (m,)) + zo2 = np.empty(out_shape + (m,)) + for indx in product(*[range(d) for d in out_shape]): + yo[indx], zo1[indx], zo2[indx] = filtfilt_gust_opt(b, a, xx[indx]) + yo = np.swapaxes(yo, -1, axis) + zo1 = np.swapaxes(zo1, -1, axis) + zo2 = np.swapaxes(zo2, -1, axis) + + assert_allclose(y, yo, rtol=1e-8, atol=1e-9) + assert_allclose(yg, yo, rtol=1e-8, atol=1e-9) + assert_allclose(zg1, zo1, rtol=1e-8, atol=1e-9) + assert_allclose(zg2, zo2, rtol=1e-8, atol=1e-9) + + +@pytest.mark.fail_slow(10) +def test_choose_conv_method(): + for mode in ['valid', 'same', 'full']: + for ndim in [1, 2]: + n, k, true_method = 8, 6, 'direct' + x = np.random.randn(*((n,) * ndim)) + h = np.random.randn(*((k,) * ndim)) + + method = choose_conv_method(x, h, mode=mode) + assert_equal(method, true_method) + + method_try, times = choose_conv_method(x, h, mode=mode, measure=True) + assert_(method_try in {'fft', 'direct'}) + assert_(isinstance(times, dict)) + assert_('fft' in times.keys() and 'direct' in times.keys()) + + x = np.array([2**51], dtype=np.int64) + h = x.copy() + assert_equal(choose_conv_method(x, h, mode=mode), 'direct') + + +@pytest.mark.thread_unsafe +def test_choose_conv_dtype_deprecation(): + # gh-21211 + a = np.asarray([1, 2, 3, 6, 5, 3], dtype=object) + b = np.asarray([2, 3, 4, 5, 3, 4, 2, 2, 1], dtype=object) + with pytest.deprecated_call(match="dtype=object is not supported"): + choose_conv_method(a, b) + + +@pytest.mark.filterwarnings('ignore::DeprecationWarning') +def test_choose_conv_method_2(): + for mode in ['valid', 'same', 'full']: + x = [Decimal(3), Decimal(2)] + h = [Decimal(1), Decimal(4)] + assert_equal(choose_conv_method(x, h, mode=mode), 'direct') + + n = 10 + for not_fft_conv_supp in ["complex256", "complex192"]: + if hasattr(np, not_fft_conv_supp): + x = np.ones(n, dtype=not_fft_conv_supp) + h = x.copy() + assert_equal(choose_conv_method(x, h, mode=mode), 'direct') + + +@pytest.mark.fail_slow(10) +def test_filtfilt_gust(): + # Design a filter. + z, p, k = signal.ellip(3, 0.01, 120, 0.0875, output='zpk') + + # Find the approximate impulse response length of the filter. + eps = 1e-10 + r = np.max(np.abs(p)) + approx_impulse_len = int(np.ceil(np.log(eps) / np.log(r))) + + np.random.seed(123) + + b, a = zpk2tf(z, p, k) + for irlen in [None, approx_impulse_len]: + signal_len = 5 * approx_impulse_len + + # 1-d test case + check_filtfilt_gust(b, a, (signal_len,), 0, irlen) + + # 3-d test case; test each axis. + for axis in range(3): + shape = [2, 2, 2] + shape[axis] = signal_len + check_filtfilt_gust(b, a, shape, axis, irlen) + + # Test case with length less than 2*approx_impulse_len. + # In this case, `filtfilt_gust` should behave the same as if + # `irlen=None` was given. + length = 2*approx_impulse_len - 50 + check_filtfilt_gust(b, a, (length,), 0, approx_impulse_len) + + +class TestDecimate: + def test_bad_args(self): + x = np.arange(12) + assert_raises(TypeError, signal.decimate, x, q=0.5, n=1) + assert_raises(TypeError, signal.decimate, x, q=2, n=0.5) + + def test_basic_IIR(self): + x = np.arange(12) + y = signal.decimate(x, 2, n=1, ftype='iir', zero_phase=False).round() + assert_array_equal(y, x[::2]) + + def test_basic_FIR(self): + x = np.arange(12) + y = signal.decimate(x, 2, n=1, ftype='fir', zero_phase=False).round() + assert_array_equal(y, x[::2]) + + def test_shape(self): + # Regression test for ticket #1480. + z = np.zeros((30, 30)) + d0 = signal.decimate(z, 2, axis=0, zero_phase=False) + assert_equal(d0.shape, (15, 30)) + d1 = signal.decimate(z, 2, axis=1, zero_phase=False) + assert_equal(d1.shape, (30, 15)) + + def test_phaseshift_FIR(self): + with suppress_warnings() as sup: + sup.filter(BadCoefficients, "Badly conditioned filter") + self._test_phaseshift(method='fir', zero_phase=False) + + def test_zero_phase_FIR(self): + with suppress_warnings() as sup: + sup.filter(BadCoefficients, "Badly conditioned filter") + self._test_phaseshift(method='fir', zero_phase=True) + + def test_phaseshift_IIR(self): + self._test_phaseshift(method='iir', zero_phase=False) + + def test_zero_phase_IIR(self): + self._test_phaseshift(method='iir', zero_phase=True) + + def _test_phaseshift(self, method, zero_phase): + rate = 120 + rates_to = [15, 20, 30, 40] # q = 8, 6, 4, 3 + + t_tot = 100 # Need to let antialiasing filters settle + t = np.arange(rate*t_tot+1) / float(rate) + + # Sinusoids at 0.8*nyquist, windowed to avoid edge artifacts + freqs = np.array(rates_to) * 0.8 / 2 + d = (np.exp(1j * 2 * np.pi * freqs[:, np.newaxis] * t) + * signal.windows.tukey(t.size, 0.1)) + + for rate_to in rates_to: + q = rate // rate_to + t_to = np.arange(rate_to*t_tot+1) / float(rate_to) + d_tos = (np.exp(1j * 2 * np.pi * freqs[:, np.newaxis] * t_to) + * signal.windows.tukey(t_to.size, 0.1)) + + # Set up downsampling filters, match v0.17 defaults + if method == 'fir': + n = 30 + system = signal.dlti(signal.firwin(n + 1, 1. / q, + window='hamming'), 1.) + elif method == 'iir': + n = 8 + wc = 0.8*np.pi/q + system = signal.dlti(*signal.cheby1(n, 0.05, wc/np.pi)) + + # Calculate expected phase response, as unit complex vector + if zero_phase is False: + _, h_resps = signal.freqz(system.num, system.den, + freqs/rate*2*np.pi) + h_resps /= np.abs(h_resps) + else: + h_resps = np.ones_like(freqs) + + y_resamps = signal.decimate(d.real, q, n, ftype=system, + zero_phase=zero_phase) + + # Get phase from complex inner product, like CSD + h_resamps = np.sum(d_tos.conj() * y_resamps, axis=-1) + h_resamps /= np.abs(h_resamps) + subnyq = freqs < 0.5*rate_to + + # Complex vectors should be aligned, only compare below nyquist + assert_allclose(np.angle(h_resps.conj()*h_resamps)[subnyq], 0, + atol=1e-3, rtol=1e-3) + + def test_auto_n(self): + # Test that our value of n is a reasonable choice (depends on + # the downsampling factor) + sfreq = 100. + n = 1000 + t = np.arange(n) / sfreq + # will alias for decimations (>= 15) + x = np.sqrt(2. / n) * np.sin(2 * np.pi * (sfreq / 30.) * t) + assert_allclose(np.linalg.norm(x), 1., rtol=1e-3) + x_out = signal.decimate(x, 30, ftype='fir') + assert_array_less(np.linalg.norm(x_out), 0.01) + + def test_long_float32(self): + # regression: gh-15072. With 32-bit float and either lfilter + # or filtfilt, this is numerically unstable + x = signal.decimate(np.ones(10_000, dtype=np.float32), 10) + assert not any(np.isnan(x)) + + def test_float16_upcast(self): + # float16 must be upcast to float64 + x = signal.decimate(np.ones(100, dtype=np.float16), 10) + assert x.dtype.type == np.float64 + + def test_complex_iir_dlti(self): + # regression: gh-17845 + # centre frequency for filter [Hz] + fcentre = 50 + # filter passband width [Hz] + fwidth = 5 + # sample rate [Hz] + fs = 1e3 + + z, p, k = signal.butter(2, 2*np.pi*fwidth/2, output='zpk', fs=fs) + z = z.astype(complex) * np.exp(2j * np.pi * fcentre/fs) + p = p.astype(complex) * np.exp(2j * np.pi * fcentre/fs) + system = signal.dlti(z, p, k) + + t = np.arange(200) / fs + + # input + u = (np.exp(2j * np.pi * fcentre * t) + + 0.5 * np.exp(-2j * np.pi * fcentre * t)) + + ynzp = signal.decimate(u, 2, ftype=system, zero_phase=False) + ynzpref = signal.lfilter(*signal.zpk2tf(z, p, k), + u)[::2] + + assert_equal(ynzp, ynzpref) + + yzp = signal.decimate(u, 2, ftype=system, zero_phase=True) + yzpref = signal.filtfilt(*signal.zpk2tf(z, p, k), + u)[::2] + + assert_allclose(yzp, yzpref, rtol=1e-10, atol=1e-13) + + def test_complex_fir_dlti(self): + # centre frequency for filter [Hz] + fcentre = 50 + # filter passband width [Hz] + fwidth = 5 + # sample rate [Hz] + fs = 1e3 + numtaps = 20 + + # FIR filter about 0Hz + bbase = signal.firwin(numtaps, fwidth/2, fs=fs) + + # rotate these to desired frequency + zbase = np.roots(bbase) + zrot = zbase * np.exp(2j * np.pi * fcentre/fs) + # FIR filter about 50Hz, maintaining passband gain of 0dB + bz = bbase[0] * np.poly(zrot) + + system = signal.dlti(bz, 1) + + t = np.arange(200) / fs + + # input + u = (np.exp(2j * np.pi * fcentre * t) + + 0.5 * np.exp(-2j * np.pi * fcentre * t)) + + ynzp = signal.decimate(u, 2, ftype=system, zero_phase=False) + ynzpref = signal.upfirdn(bz, u, up=1, down=2)[:100] + + assert_equal(ynzp, ynzpref) + + yzp = signal.decimate(u, 2, ftype=system, zero_phase=True) + yzpref = signal.resample_poly(u, 1, 2, window=bz) + + assert_equal(yzp, yzpref) + + +class TestHilbert: + + def test_bad_args(self): + x = np.array([1.0 + 0.0j]) + assert_raises(ValueError, hilbert, x) + x = np.arange(8.0) + assert_raises(ValueError, hilbert, x, N=0) + + def test_hilbert_theoretical(self): + # test cases by Ariel Rokem + decimal = 14 + + pi = np.pi + t = np.arange(0, 2 * pi, pi / 256) + a0 = np.sin(t) + a1 = np.cos(t) + a2 = np.sin(2 * t) + a3 = np.cos(2 * t) + a = np.vstack([a0, a1, a2, a3]) + + h = hilbert(a) + h_abs = np.abs(h) + h_angle = np.angle(h) + h_real = np.real(h) + + # The real part should be equal to the original signals: + assert_almost_equal(h_real, a, decimal) + # The absolute value should be one everywhere, for this input: + assert_almost_equal(h_abs, np.ones(a.shape), decimal) + # For the 'slow' sine - the phase should go from -pi/2 to pi/2 in + # the first 256 bins: + assert_almost_equal(h_angle[0, :256], + np.arange(-pi / 2, pi / 2, pi / 256), + decimal) + # For the 'slow' cosine - the phase should go from 0 to pi in the + # same interval: + assert_almost_equal( + h_angle[1, :256], np.arange(0, pi, pi / 256), decimal) + # The 'fast' sine should make this phase transition in half the time: + assert_almost_equal(h_angle[2, :128], + np.arange(-pi / 2, pi / 2, pi / 128), + decimal) + # Ditto for the 'fast' cosine: + assert_almost_equal( + h_angle[3, :128], np.arange(0, pi, pi / 128), decimal) + + # The imaginary part of hilbert(cos(t)) = sin(t) Wikipedia + assert_almost_equal(h[1].imag, a0, decimal) + + def test_hilbert_axisN(self): + # tests for axis and N arguments + a = np.arange(18).reshape(3, 6) + # test axis + aa = hilbert(a, axis=-1) + assert_equal(hilbert(a.T, axis=0), aa.T) + # test 1d + assert_almost_equal(hilbert(a[0]), aa[0], 14) + + # test N + aan = hilbert(a, N=20, axis=-1) + assert_equal(aan.shape, [3, 20]) + assert_equal(hilbert(a.T, N=20, axis=0).shape, [20, 3]) + # the next test is just a regression test, + # no idea whether numbers make sense + a0hilb = np.array([0.000000000000000e+00 - 1.72015830311905j, + 1.000000000000000e+00 - 2.047794505137069j, + 1.999999999999999e+00 - 2.244055555687583j, + 3.000000000000000e+00 - 1.262750302935009j, + 4.000000000000000e+00 - 1.066489252384493j, + 5.000000000000000e+00 + 2.918022706971047j, + 8.881784197001253e-17 + 3.845658908989067j, + -9.444121133484362e-17 + 0.985044202202061j, + -1.776356839400251e-16 + 1.332257797702019j, + -3.996802888650564e-16 + 0.501905089898885j, + 1.332267629550188e-16 + 0.668696078880782j, + -1.192678053963799e-16 + 0.235487067862679j, + -1.776356839400251e-16 + 0.286439612812121j, + 3.108624468950438e-16 + 0.031676888064907j, + 1.332267629550188e-16 - 0.019275656884536j, + -2.360035624836702e-16 - 0.1652588660287j, + 0.000000000000000e+00 - 0.332049855010597j, + 3.552713678800501e-16 - 0.403810179797771j, + 8.881784197001253e-17 - 0.751023775297729j, + 9.444121133484362e-17 - 0.79252210110103j]) + assert_almost_equal(aan[0], a0hilb, 14, 'N regression') + + @pytest.mark.parametrize('dtype', [np.float32, np.float64]) + def test_hilbert_types(self, dtype): + in_typed = np.zeros(8, dtype=dtype) + assert_equal(np.real(signal.hilbert(in_typed)).dtype, dtype) + + +class TestHilbert2: + + def test_bad_args(self): + # x must be real. + x = np.array([[1.0 + 0.0j]]) + assert_raises(ValueError, hilbert2, x) + + # x must be rank 2. + x = np.arange(24).reshape(2, 3, 4) + assert_raises(ValueError, hilbert2, x) + + # Bad value for N. + x = np.arange(16).reshape(4, 4) + assert_raises(ValueError, hilbert2, x, N=0) + assert_raises(ValueError, hilbert2, x, N=(2, 0)) + assert_raises(ValueError, hilbert2, x, N=(2,)) + + @pytest.mark.parametrize('dtype', [np.float32, np.float64]) + def test_hilbert2_types(self, dtype): + in_typed = np.zeros((2, 32), dtype=dtype) + assert_equal(np.real(signal.hilbert2(in_typed)).dtype, dtype) + + +class TestEnvelope: + """Unit tests for function `._signaltools.envelope()`. """ + + @staticmethod + def assert_close(actual, desired, msg): + """Little helper to compare to arrays with proper tolerances""" + xp_assert_close(actual, desired, atol=1e-12, rtol=1e-12, err_msg=msg) + + def test_envelope_invalid_parameters(self): + """For `envelope()` Raise all exceptions that are used to verify function + parameters. """ + with pytest.raises(ValueError, + match=r"Invalid parameter axis=2 for z.shape=.*"): + envelope(np.ones(3), axis=2) + with pytest.raises(ValueError, + match=r"z.shape\[axis\] not > 0 for z.shape=.*"): + envelope(np.ones((3, 0)), axis=1) + for bp_in in [(0, 1, 2), (0, 2.), (None, 2.)]: + ts = ', '.join(map(str, bp_in)) + with pytest.raises(ValueError, + match=rf"bp_in=\({ts}\) isn't a 2-tuple of.*"): + # noinspection PyTypeChecker + envelope(np.ones(4), bp_in=bp_in) + with pytest.raises(ValueError, + match="n_out=10.0 is not a positive integer or.*"): + # noinspection PyTypeChecker + envelope(np.ones(4), n_out=10.) + for bp_in in [(-1, 3), (1, 1), (0, 10)]: + with pytest.raises(ValueError, + match=r"`-n//2 <= bp_in\[0\] < bp_in\[1\] <=.*"): + envelope(np.ones(4), bp_in=bp_in) + with pytest.raises(ValueError, match="residual='undefined' not in .*"): + # noinspection PyTypeChecker + envelope(np.ones(4), residual='undefined') + + def test_envelope_verify_parameters(self): + """Ensure that the various parametrizations produce compatible results. """ + Z, Zr_a = [4, 2, 2, 3, 0], [4, 0, 0, 6, 0, 0, 0, 0] + z = sp_fft.irfft(Z) + n = len(z) + + # the reference envelope: + ze2_0, zr_0 = envelope(z, (1, 3), residual='all', squared=True) + self.assert_close(sp_fft.rfft(ze2_0), np.array([4, 2, 0, 0, 0]).astype(complex), + msg="Envelope calculation error") + self.assert_close(sp_fft.rfft(zr_0), np.array([4, 0, 0, 3, 0]).astype(complex), + msg="Residual calculation error") + + ze_1, zr_1 = envelope(z, (1, 3), residual='all', squared=False) + self.assert_close(ze_1**2, ze2_0, + msg="Unsquared versus Squared envelope calculation error") + self.assert_close(zr_1, zr_0, + msg="Unsquared versus Squared residual calculation error") + + ze2_2, zr_2 = envelope(z, (1, 3), residual='all', squared=True, n_out=3*n) + self.assert_close(ze2_2[::3], ze2_0, + msg="3x up-sampled envelope calculation error") + self.assert_close(zr_2[::3], zr_0, + msg="3x up-sampled residual calculation error") + + ze2_3, zr_3 = envelope(z, (1, 3), residual='lowpass', squared=True) + self.assert_close(ze2_3, ze2_0, + msg="`residual='lowpass'` envelope calculation error") + self.assert_close(sp_fft.rfft(zr_3), np.array([4, 0, 0, 0, 0]).astype(complex), + msg="`residual='lowpass'` residual calculation error") + + ze2_4 = envelope(z, (1, 3), residual=None, squared=True) + self.assert_close(ze2_4, ze2_0, + msg="`residual=None` envelope calculation error") + + # compare complex analytic signal to real version + Z_a = np.copy(Z) + Z_a[1:] *= 2 + z_a = sp_fft.ifft(Z_a, n=n) # analytic signal of Z + self.assert_close(z_a.real, z, + msg="Reference analytic signal error") + ze2_a, zr_a = envelope(z_a, (1, 3), residual='all', squared=True) + self.assert_close(ze2_a, ze2_0.astype(complex), # dtypes must match + msg="Complex envelope calculation error") + self.assert_close(sp_fft.fft(zr_a), np.array(Zr_a).astype(complex), + msg="Complex residual calculation error") + + @pytest.mark.parametrize( + " Z, bp_in, Ze2_desired, Zr_desired", + [([1, 0, 2, 2, 0], (1, None), [4, 2, 0, 0, 0], [1, 0, 0, 0, 0]), + ([4, 0, 2, 0, 0], (0, None), [4, 0, 2, 0, 0], [0, 0, 0, 0, 0]), + ([4, 0, 0, 2, 0], (None, None), [4, 0, 0, 2, 0], [0, 0, 0, 0, 0]), + ([0, 0, 2, 2, 0], (1, 3), [2, 0, 0, 0, 0], [0, 0, 0, 2, 0]), + ([4, 0, 2, 2, 0], (-3, 3), [4, 0, 2, 0, 0], [0, 0, 0, 2, 0]), + ([4, 0, 3, 4, 0], (None, 1), [2, 0, 0, 0, 0], [0, 0, 3, 4, 0]), + ([4, 0, 3, 4, 0], (None, 0), [0, 0, 0, 0, 0], [4, 0, 3, 4, 0])]) + def test_envelope_real_signals(self, Z, bp_in, Ze2_desired, Zr_desired): + """Test envelope calculation with real-valued test signals. + + The comparisons are performed in the Fourier space, since it makes evaluating + the bandpass filter behavior straightforward. Note that also the squared + envelope can be easily calculated by hand, if one recalls that coefficients of + a complex-valued Fourier series representing the signal can be directly + determined by an FFT and that the absolute square of a Fourier series is again + a Fourier series. + """ + z = sp_fft.irfft(Z) + ze2, zr = envelope(z, bp_in, residual='all', squared=True) + ze2_lp, zr_lp = envelope(z, bp_in, residual='lowpass', squared=True) + Ze2, Zr, Ze2_lp, Zr_lp = (sp_fft.rfft(z_) for z_ in (ze2, zr, ze2_lp, zr_lp)) + + Ze2_desired = np.array(Ze2_desired).astype(complex) + Zr_desired = np.array(Zr_desired).astype(complex) + self.assert_close(Ze2, Ze2_desired, + msg="Envelope calculation error (residual='all')") + self.assert_close(Zr, Zr_desired, + msg="Residual calculation error (residual='all')") + + if bp_in[1] is not None: + Zr_desired[bp_in[1]:] = 0 + self.assert_close(Ze2_lp, Ze2_desired, + msg="Envelope calculation error (residual='lowpass')") + self.assert_close(Zr_lp, Zr_desired, + msg="Residual calculation error (residual='lowpass')") + + @pytest.mark.parametrize( + " Z, bp_in, Ze2_desired, Zr_desired", + [([0, 5, 0, 5, 0], (None, None), [5, 0, 10, 0, 5], [0, 0, 0, 0, 0]), + ([1, 5, 0, 5, 2], (-1, 2), [5, 0, 10, 0, 5], [1, 0, 0, 0, 2]), + ([1, 2, 6, 0, 6, 3], (-1, 2), [0, 6, 0, 12, 0, 6], [1, 2, 0, 0, 0, 3]) + ]) + def test_envelope_complex_signals(self, Z, bp_in, Ze2_desired, Zr_desired): + """Test envelope calculation with complex-valued test signals. + + We only need to test for the complex envelope here, since the ``Nones``s in the + bandpass filter were already tested in the previous test. + """ + z = sp_fft.ifft(sp_fft.ifftshift(Z)) + ze2, zr = envelope(z, bp_in, residual='all', squared=True) + Ze2, Zr = (sp_fft.fftshift(sp_fft.fft(z_)) for z_ in (ze2, zr)) + + self.assert_close(Ze2, np.array(Ze2_desired).astype(complex), + msg="Envelope calculation error") + self.assert_close(Zr, np.array(Zr_desired).astype(complex), + msg="Residual calculation error") + + def test_envelope_verify_axis_parameter(self): + """Test for multi-channel envelope calculations. """ + z = sp_fft.irfft([[1, 0, 2, 2, 0], [7, 0, 4, 4, 0]]) + Ze2_desired = np.array([[4, 2, 0, 0, 0], [16, 8, 0, 0, 0]], + dtype=complex) + Zr_desired = np.array([[1, 0, 0, 0, 0], [7, 0, 0, 0, 0]], dtype=complex) + + ze2, zr = envelope(z, squared=True, axis=1) + ye2T, yrT = envelope(z.T, squared=True, axis=0) + Ze2, Ye2, Zr, Yr = (sp_fft.rfft(z_) for z_ in (ze2, ye2T.T, zr, yrT.T)) + + self.assert_close(Ze2, Ze2_desired, msg="2d envelope calculation error") + self.assert_close(Zr, Zr_desired, msg="2d residual calculation error") + self.assert_close(Ye2, Ze2_desired, msg="Transposed 2d envelope calc. error") + self.assert_close(Yr, Zr_desired, msg="Transposed 2d residual calc. error") + + def test_envelope_verify_axis_parameter_complex(self): + """Test for multi-channel envelope calculations with complex values. """ + z = sp_fft.ifft(sp_fft.ifftshift([[1, 5, 0, 5, 2], [1, 10, 0, 10, 2]], axes=1)) + Ze2_des = np.array([[5, 0, 10, 0, 5], [20, 0, 40, 0, 20],], + dtype=complex) + Zr_des = np.array([[1, 0, 0, 0, 2], [1, 0, 0, 0, 2]], dtype=complex) + + kw = dict(bp_in=(-1, 2), residual='all', squared=True) + ze2, zr = envelope(z, axis=1, **kw) + ye2T, yrT = envelope(z.T, axis=0, **kw) + Ze2, Ye2, Zr, Yr = (sp_fft.fftshift(sp_fft.fft(z_), axes=1) + for z_ in (ze2, ye2T.T, zr, yrT.T)) + + self.assert_close(Ze2, Ze2_des, msg="2d envelope calculation error") + self.assert_close(Zr, Zr_des, msg="2d residual calculation error") + self.assert_close(Ye2, Ze2_des, msg="Transposed 2d envelope calc. error") + self.assert_close(Yr, Zr_des, msg="Transposed 2d residual calc. error") + + @pytest.mark.parametrize('X', [[4, 0, 0, 1, 2], [4, 0, 0, 2, 1, 2]]) + def test_compare_envelope_hilbert(self, X): + """Compare output of `envelope()` and `hilbert()`. """ + x = sp_fft.irfft(X) + e_hil = np.abs(hilbert(x)) + e_env = envelope(x, (None, None), residual=None) + self.assert_close(e_hil, e_env, msg="Hilbert-Envelope comparison error") + + +class TestPartialFractionExpansion: + @staticmethod + def assert_rp_almost_equal(r, p, r_true, p_true, decimal=7): + r_true = np.asarray(r_true) + p_true = np.asarray(p_true) + + distance = np.hypot(abs(p[:, None] - p_true), + abs(r[:, None] - r_true)) + + rows, cols = linear_sum_assignment(distance) + assert_almost_equal(p[rows], p_true[cols], decimal=decimal) + assert_almost_equal(r[rows], r_true[cols], decimal=decimal) + + def test_compute_factors(self): + factors, poly = _compute_factors([1, 2, 3], [3, 2, 1]) + assert_equal(len(factors), 3) + assert_almost_equal(factors[0], np.poly([2, 2, 3])) + assert_almost_equal(factors[1], np.poly([1, 1, 1, 3])) + assert_almost_equal(factors[2], np.poly([1, 1, 1, 2, 2])) + assert_almost_equal(poly, np.poly([1, 1, 1, 2, 2, 3])) + + factors, poly = _compute_factors([1, 2, 3], [3, 2, 1], + include_powers=True) + assert_equal(len(factors), 6) + assert_almost_equal(factors[0], np.poly([1, 1, 2, 2, 3])) + assert_almost_equal(factors[1], np.poly([1, 2, 2, 3])) + assert_almost_equal(factors[2], np.poly([2, 2, 3])) + assert_almost_equal(factors[3], np.poly([1, 1, 1, 2, 3])) + assert_almost_equal(factors[4], np.poly([1, 1, 1, 3])) + assert_almost_equal(factors[5], np.poly([1, 1, 1, 2, 2])) + assert_almost_equal(poly, np.poly([1, 1, 1, 2, 2, 3])) + + def test_group_poles(self): + unique, multiplicity = _group_poles( + [1.0, 1.001, 1.003, 2.0, 2.003, 3.0], 0.1, 'min') + assert_equal(unique, [1.0, 2.0, 3.0]) + assert_equal(multiplicity, [3, 2, 1]) + + def test_residue_general(self): + # Test are taken from issue #4464, note that poles in scipy are + # in increasing by absolute value order, opposite to MATLAB. + r, p, k = residue([5, 3, -2, 7], [-4, 0, 8, 3]) + assert_almost_equal(r, [1.3320, -0.6653, -1.4167], decimal=4) + assert_almost_equal(p, [-0.4093, -1.1644, 1.5737], decimal=4) + assert_almost_equal(k, [-1.2500], decimal=4) + + r, p, k = residue([-4, 8], [1, 6, 8]) + assert_almost_equal(r, [8, -12]) + assert_almost_equal(p, [-2, -4]) + assert_equal(k.size, 0) + + r, p, k = residue([4, 1], [1, -1, -2]) + assert_almost_equal(r, [1, 3]) + assert_almost_equal(p, [-1, 2]) + assert_equal(k.size, 0) + + r, p, k = residue([4, 3], [2, -3.4, 1.98, -0.406]) + self.assert_rp_almost_equal( + r, p, [-18.125 - 13.125j, -18.125 + 13.125j, 36.25], + [0.5 - 0.2j, 0.5 + 0.2j, 0.7]) + assert_equal(k.size, 0) + + r, p, k = residue([2, 1], [1, 5, 8, 4]) + self.assert_rp_almost_equal(r, p, [-1, 1, 3], [-1, -2, -2]) + assert_equal(k.size, 0) + + r, p, k = residue([3, -1.1, 0.88, -2.396, 1.348], + [1, -0.7, -0.14, 0.048]) + assert_almost_equal(r, [-3, 4, 1]) + assert_almost_equal(p, [0.2, -0.3, 0.8]) + assert_almost_equal(k, [3, 1]) + + r, p, k = residue([1], [1, 2, -3]) + assert_almost_equal(r, [0.25, -0.25]) + assert_almost_equal(p, [1, -3]) + assert_equal(k.size, 0) + + r, p, k = residue([1, 0, -5], [1, 0, 0, 0, -1]) + self.assert_rp_almost_equal(r, p, + [1, 1.5j, -1.5j, -1], [-1, -1j, 1j, 1]) + assert_equal(k.size, 0) + + r, p, k = residue([3, 8, 6], [1, 3, 3, 1]) + self.assert_rp_almost_equal(r, p, [1, 2, 3], [-1, -1, -1]) + assert_equal(k.size, 0) + + r, p, k = residue([3, -1], [1, -3, 2]) + assert_almost_equal(r, [-2, 5]) + assert_almost_equal(p, [1, 2]) + assert_equal(k.size, 0) + + r, p, k = residue([2, 3, -1], [1, -3, 2]) + assert_almost_equal(r, [-4, 13]) + assert_almost_equal(p, [1, 2]) + assert_almost_equal(k, [2]) + + r, p, k = residue([7, 2, 3, -1], [1, -3, 2]) + assert_almost_equal(r, [-11, 69]) + assert_almost_equal(p, [1, 2]) + assert_almost_equal(k, [7, 23]) + + r, p, k = residue([2, 3, -1], [1, -3, 4, -2]) + self.assert_rp_almost_equal(r, p, [4, -1 + 3.5j, -1 - 3.5j], + [1, 1 - 1j, 1 + 1j]) + assert_almost_equal(k.size, 0) + + def test_residue_leading_zeros(self): + # Leading zeros in numerator or denominator must not affect the answer. + r0, p0, k0 = residue([5, 3, -2, 7], [-4, 0, 8, 3]) + r1, p1, k1 = residue([0, 5, 3, -2, 7], [-4, 0, 8, 3]) + r2, p2, k2 = residue([5, 3, -2, 7], [0, -4, 0, 8, 3]) + r3, p3, k3 = residue([0, 0, 5, 3, -2, 7], [0, 0, 0, -4, 0, 8, 3]) + assert_almost_equal(r0, r1) + assert_almost_equal(r0, r2) + assert_almost_equal(r0, r3) + assert_almost_equal(p0, p1) + assert_almost_equal(p0, p2) + assert_almost_equal(p0, p3) + assert_almost_equal(k0, k1) + assert_almost_equal(k0, k2) + assert_almost_equal(k0, k3) + + def test_resiude_degenerate(self): + # Several tests for zero numerator and denominator. + r, p, k = residue([0, 0], [1, 6, 8]) + assert_almost_equal(r, [0, 0]) + assert_almost_equal(p, [-2, -4]) + assert_equal(k.size, 0) + + r, p, k = residue(0, 1) + assert_equal(r.size, 0) + assert_equal(p.size, 0) + assert_equal(k.size, 0) + + with pytest.raises(ValueError, match="Denominator `a` is zero."): + residue(1, 0) + + def test_residuez_general(self): + r, p, k = residuez([1, 6, 6, 2], [1, -(2 + 1j), (1 + 2j), -1j]) + self.assert_rp_almost_equal(r, p, [-2+2.5j, 7.5+7.5j, -4.5-12j], + [1j, 1, 1]) + assert_almost_equal(k, [2j]) + + r, p, k = residuez([1, 2, 1], [1, -1, 0.3561]) + self.assert_rp_almost_equal(r, p, + [-0.9041 - 5.9928j, -0.9041 + 5.9928j], + [0.5 + 0.3257j, 0.5 - 0.3257j], + decimal=4) + assert_almost_equal(k, [2.8082], decimal=4) + + r, p, k = residuez([1, -1], [1, -5, 6]) + assert_almost_equal(r, [-1, 2]) + assert_almost_equal(p, [2, 3]) + assert_equal(k.size, 0) + + r, p, k = residuez([2, 3, 4], [1, 3, 3, 1]) + self.assert_rp_almost_equal(r, p, [4, -5, 3], [-1, -1, -1]) + assert_equal(k.size, 0) + + r, p, k = residuez([1, -10, -4, 4], [2, -2, -4]) + assert_almost_equal(r, [0.5, -1.5]) + assert_almost_equal(p, [-1, 2]) + assert_almost_equal(k, [1.5, -1]) + + r, p, k = residuez([18], [18, 3, -4, -1]) + self.assert_rp_almost_equal(r, p, + [0.36, 0.24, 0.4], [0.5, -1/3, -1/3]) + assert_equal(k.size, 0) + + r, p, k = residuez([2, 3], np.polymul([1, -1/2], [1, 1/4])) + assert_almost_equal(r, [-10/3, 16/3]) + assert_almost_equal(p, [-0.25, 0.5]) + assert_equal(k.size, 0) + + r, p, k = residuez([1, -2, 1], [1, -1]) + assert_almost_equal(r, [0]) + assert_almost_equal(p, [1]) + assert_almost_equal(k, [1, -1]) + + r, p, k = residuez(1, [1, -1j]) + assert_almost_equal(r, [1]) + assert_almost_equal(p, [1j]) + assert_equal(k.size, 0) + + r, p, k = residuez(1, [1, -1, 0.25]) + assert_almost_equal(r, [0, 1]) + assert_almost_equal(p, [0.5, 0.5]) + assert_equal(k.size, 0) + + r, p, k = residuez(1, [1, -0.75, .125]) + assert_almost_equal(r, [-1, 2]) + assert_almost_equal(p, [0.25, 0.5]) + assert_equal(k.size, 0) + + r, p, k = residuez([1, 6, 2], [1, -2, 1]) + assert_almost_equal(r, [-10, 9]) + assert_almost_equal(p, [1, 1]) + assert_almost_equal(k, [2]) + + r, p, k = residuez([6, 2], [1, -2, 1]) + assert_almost_equal(r, [-2, 8]) + assert_almost_equal(p, [1, 1]) + assert_equal(k.size, 0) + + r, p, k = residuez([1, 6, 6, 2], [1, -2, 1]) + assert_almost_equal(r, [-24, 15]) + assert_almost_equal(p, [1, 1]) + assert_almost_equal(k, [10, 2]) + + r, p, k = residuez([1, 0, 1], [1, 0, 0, 0, 0, -1]) + self.assert_rp_almost_equal(r, p, + [0.2618 + 0.1902j, 0.2618 - 0.1902j, + 0.4, 0.0382 - 0.1176j, 0.0382 + 0.1176j], + [-0.8090 + 0.5878j, -0.8090 - 0.5878j, + 1.0, 0.3090 + 0.9511j, 0.3090 - 0.9511j], + decimal=4) + assert_equal(k.size, 0) + + def test_residuez_trailing_zeros(self): + # Trailing zeros in numerator or denominator must not affect the + # answer. + r0, p0, k0 = residuez([5, 3, -2, 7], [-4, 0, 8, 3]) + r1, p1, k1 = residuez([5, 3, -2, 7, 0], [-4, 0, 8, 3]) + r2, p2, k2 = residuez([5, 3, -2, 7], [-4, 0, 8, 3, 0]) + r3, p3, k3 = residuez([5, 3, -2, 7, 0, 0], [-4, 0, 8, 3, 0, 0, 0]) + assert_almost_equal(r0, r1) + assert_almost_equal(r0, r2) + assert_almost_equal(r0, r3) + assert_almost_equal(p0, p1) + assert_almost_equal(p0, p2) + assert_almost_equal(p0, p3) + assert_almost_equal(k0, k1) + assert_almost_equal(k0, k2) + assert_almost_equal(k0, k3) + + def test_residuez_degenerate(self): + r, p, k = residuez([0, 0], [1, 6, 8]) + assert_almost_equal(r, [0, 0]) + assert_almost_equal(p, [-2, -4]) + assert_equal(k.size, 0) + + r, p, k = residuez(0, 1) + assert_equal(r.size, 0) + assert_equal(p.size, 0) + assert_equal(k.size, 0) + + with pytest.raises(ValueError, match="Denominator `a` is zero."): + residuez(1, 0) + + with pytest.raises(ValueError, + match="First coefficient of determinant `a` must " + "be non-zero."): + residuez(1, [0, 1, 2, 3]) + + def test_inverse_unique_roots_different_rtypes(self): + # This test was inspired by GitHub issue 2496. + r = [3 / 10, -1 / 6, -2 / 15] + p = [0, -2, -5] + k = [] + b_expected = [0, 1, 3] + a_expected = [1, 7, 10, 0] + + # With the default tolerance, the rtype does not matter + # for this example. + for rtype in ('avg', 'mean', 'min', 'minimum', 'max', 'maximum'): + b, a = invres(r, p, k, rtype=rtype) + assert_allclose(b, b_expected) + assert_allclose(a, a_expected) + + b, a = invresz(r, p, k, rtype=rtype) + assert_allclose(b, b_expected) + assert_allclose(a, a_expected) + + def test_inverse_repeated_roots_different_rtypes(self): + r = [3 / 20, -7 / 36, -1 / 6, 2 / 45] + p = [0, -2, -2, -5] + k = [] + b_expected = [0, 0, 1, 3] + b_expected_z = [-1/6, -2/3, 11/6, 3] + a_expected = [1, 9, 24, 20, 0] + + for rtype in ('avg', 'mean', 'min', 'minimum', 'max', 'maximum'): + b, a = invres(r, p, k, rtype=rtype) + assert_allclose(b, b_expected, atol=1e-14) + assert_allclose(a, a_expected) + + b, a = invresz(r, p, k, rtype=rtype) + assert_allclose(b, b_expected_z, atol=1e-14) + assert_allclose(a, a_expected) + + def test_inverse_bad_rtype(self): + r = [3 / 20, -7 / 36, -1 / 6, 2 / 45] + p = [0, -2, -2, -5] + k = [] + with pytest.raises(ValueError, match="`rtype` must be one of"): + invres(r, p, k, rtype='median') + with pytest.raises(ValueError, match="`rtype` must be one of"): + invresz(r, p, k, rtype='median') + + def test_invresz_one_coefficient_bug(self): + # Regression test for issue in gh-4646. + r = [1] + p = [2] + k = [0] + b, a = invresz(r, p, k) + assert_allclose(b, [1.0]) + assert_allclose(a, [1.0, -2.0]) + + def test_invres(self): + b, a = invres([1], [1], []) + assert_almost_equal(b, [1]) + assert_almost_equal(a, [1, -1]) + + b, a = invres([1 - 1j, 2, 0.5 - 3j], [1, 0.5j, 1 + 1j], []) + assert_almost_equal(b, [3.5 - 4j, -8.5 + 0.25j, 3.5 + 3.25j]) + assert_almost_equal(a, [1, -2 - 1.5j, 0.5 + 2j, 0.5 - 0.5j]) + + b, a = invres([0.5, 1], [1 - 1j, 2 + 2j], [1, 2, 3]) + assert_almost_equal(b, [1, -1 - 1j, 1 - 2j, 0.5 - 3j, 10]) + assert_almost_equal(a, [1, -3 - 1j, 4]) + + b, a = invres([-1, 2, 1j, 3 - 1j, 4, -2], + [-1, 2 - 1j, 2 - 1j, 3, 3, 3], []) + assert_almost_equal(b, [4 - 1j, -28 + 16j, 40 - 62j, 100 + 24j, + -292 + 219j, 192 - 268j]) + assert_almost_equal(a, [1, -12 + 2j, 53 - 20j, -96 + 68j, 27 - 72j, + 108 - 54j, -81 + 108j]) + + b, a = invres([-1, 1j], [1, 1], [1, 2]) + assert_almost_equal(b, [1, 0, -4, 3 + 1j]) + assert_almost_equal(a, [1, -2, 1]) + + def test_invresz(self): + b, a = invresz([1], [1], []) + assert_almost_equal(b, [1]) + assert_almost_equal(a, [1, -1]) + + b, a = invresz([1 - 1j, 2, 0.5 - 3j], [1, 0.5j, 1 + 1j], []) + assert_almost_equal(b, [3.5 - 4j, -8.5 + 0.25j, 3.5 + 3.25j]) + assert_almost_equal(a, [1, -2 - 1.5j, 0.5 + 2j, 0.5 - 0.5j]) + + b, a = invresz([0.5, 1], [1 - 1j, 2 + 2j], [1, 2, 3]) + assert_almost_equal(b, [2.5, -3 - 1j, 1 - 2j, -1 - 3j, 12]) + assert_almost_equal(a, [1, -3 - 1j, 4]) + + b, a = invresz([-1, 2, 1j, 3 - 1j, 4, -2], + [-1, 2 - 1j, 2 - 1j, 3, 3, 3], []) + assert_almost_equal(b, [6, -50 + 11j, 100 - 72j, 80 + 58j, + -354 + 228j, 234 - 297j]) + assert_almost_equal(a, [1, -12 + 2j, 53 - 20j, -96 + 68j, 27 - 72j, + 108 - 54j, -81 + 108j]) + + b, a = invresz([-1, 1j], [1, 1], [1, 2]) + assert_almost_equal(b, [1j, 1, -3, 2]) + assert_almost_equal(a, [1, -2, 1]) + + def test_inverse_scalar_arguments(self): + b, a = invres(1, 1, 1) + assert_almost_equal(b, [1, 0]) + assert_almost_equal(a, [1, -1]) + + b, a = invresz(1, 1, 1) + assert_almost_equal(b, [2, -1]) + assert_almost_equal(a, [1, -1]) + + +class TestVectorstrength: + + def test_single_1dperiod(self): + events = np.array([.5]) + period = 5. + targ_strength = 1. + targ_phase = .1 + + strength, phase = vectorstrength(events, period) + + assert_equal(strength.ndim, 0) + assert_equal(phase.ndim, 0) + assert_almost_equal(strength, targ_strength) + assert_almost_equal(phase, 2 * np.pi * targ_phase) + + def test_single_2dperiod(self): + events = np.array([.5]) + period = [1, 2, 5.] + targ_strength = [1.] * 3 + targ_phase = np.array([.5, .25, .1]) + + strength, phase = vectorstrength(events, period) + + assert_equal(strength.ndim, 1) + assert_equal(phase.ndim, 1) + assert_array_almost_equal(strength, targ_strength) + assert_almost_equal(phase, 2 * np.pi * targ_phase) + + def test_equal_1dperiod(self): + events = np.array([.25, .25, .25, .25, .25, .25]) + period = 2 + targ_strength = 1. + targ_phase = .125 + + strength, phase = vectorstrength(events, period) + + assert_equal(strength.ndim, 0) + assert_equal(phase.ndim, 0) + assert_almost_equal(strength, targ_strength) + assert_almost_equal(phase, 2 * np.pi * targ_phase) + + def test_equal_2dperiod(self): + events = np.array([.25, .25, .25, .25, .25, .25]) + period = [1, 2, ] + targ_strength = [1.] * 2 + targ_phase = np.array([.25, .125]) + + strength, phase = vectorstrength(events, period) + + assert_equal(strength.ndim, 1) + assert_equal(phase.ndim, 1) + assert_almost_equal(strength, targ_strength) + assert_almost_equal(phase, 2 * np.pi * targ_phase) + + def test_spaced_1dperiod(self): + events = np.array([.1, 1.1, 2.1, 4.1, 10.1]) + period = 1 + targ_strength = 1. + targ_phase = .1 + + strength, phase = vectorstrength(events, period) + + assert_equal(strength.ndim, 0) + assert_equal(phase.ndim, 0) + assert_almost_equal(strength, targ_strength) + assert_almost_equal(phase, 2 * np.pi * targ_phase) + + def test_spaced_2dperiod(self): + events = np.array([.1, 1.1, 2.1, 4.1, 10.1]) + period = [1, .5] + targ_strength = [1.] * 2 + targ_phase = np.array([.1, .2]) + + strength, phase = vectorstrength(events, period) + + assert_equal(strength.ndim, 1) + assert_equal(phase.ndim, 1) + assert_almost_equal(strength, targ_strength) + assert_almost_equal(phase, 2 * np.pi * targ_phase) + + def test_partial_1dperiod(self): + events = np.array([.25, .5, .75]) + period = 1 + targ_strength = 1. / 3. + targ_phase = .5 + + strength, phase = vectorstrength(events, period) + + assert_equal(strength.ndim, 0) + assert_equal(phase.ndim, 0) + assert_almost_equal(strength, targ_strength) + assert_almost_equal(phase, 2 * np.pi * targ_phase) + + def test_partial_2dperiod(self): + events = np.array([.25, .5, .75]) + period = [1., 1., 1., 1.] + targ_strength = [1. / 3.] * 4 + targ_phase = np.array([.5, .5, .5, .5]) + + strength, phase = vectorstrength(events, period) + + assert_equal(strength.ndim, 1) + assert_equal(phase.ndim, 1) + assert_almost_equal(strength, targ_strength) + assert_almost_equal(phase, 2 * np.pi * targ_phase) + + def test_opposite_1dperiod(self): + events = np.array([0, .25, .5, .75]) + period = 1. + targ_strength = 0 + + strength, phase = vectorstrength(events, period) + + assert_equal(strength.ndim, 0) + assert_equal(phase.ndim, 0) + assert_almost_equal(strength, targ_strength) + + def test_opposite_2dperiod(self): + events = np.array([0, .25, .5, .75]) + period = [1.] * 10 + targ_strength = [0.] * 10 + + strength, phase = vectorstrength(events, period) + + assert_equal(strength.ndim, 1) + assert_equal(phase.ndim, 1) + assert_almost_equal(strength, targ_strength) + + def test_2d_events_ValueError(self): + events = np.array([[1, 2]]) + period = 1. + assert_raises(ValueError, vectorstrength, events, period) + + def test_2d_period_ValueError(self): + events = 1. + period = np.array([[1]]) + assert_raises(ValueError, vectorstrength, events, period) + + def test_zero_period_ValueError(self): + events = 1. + period = 0 + assert_raises(ValueError, vectorstrength, events, period) + + def test_negative_period_ValueError(self): + events = 1. + period = -1 + assert_raises(ValueError, vectorstrength, events, period) + + +def assert_allclose_cast(actual, desired, rtol=1e-7, atol=0): + """Wrap assert_allclose while casting object arrays.""" + if actual.dtype.kind == 'O': + dtype = np.array(actual.flat[0]).dtype + actual, desired = actual.astype(dtype), desired.astype(dtype) + assert_allclose(actual, desired, rtol, atol) + + +@pytest.mark.filterwarnings('ignore::DeprecationWarning') +@pytest.mark.parametrize('func', (sosfilt, lfilter)) +def test_nonnumeric_dtypes(func): + x = [Decimal(1), Decimal(2), Decimal(3)] + b = [Decimal(1), Decimal(2), Decimal(3)] + a = [Decimal(1), Decimal(2), Decimal(3)] + x = np.array(x) + assert x.dtype.kind == 'O' + desired = lfilter(np.array(b, float), np.array(a, float), x.astype(float)) + if func is sosfilt: + actual = sosfilt([b + a], x) + else: + actual = lfilter(b, a, x) + assert all(isinstance(x, Decimal) for x in actual) + assert_allclose(actual.astype(float), desired.astype(float)) + # Degenerate cases + if func is lfilter: + args = [1., 1.] + else: + args = [tf2sos(1., 1.)] + + with pytest.raises(ValueError, match='must be at least 1-D'): + func(*args, x=1.) + + +@pytest.mark.parametrize('dt', 'fdFD') +class TestSOSFilt: + + # The test_rank* tests are pulled from _TestLinearFilter + def test_rank1(self, dt): + x = np.linspace(0, 5, 6).astype(dt) + b = np.array([1, -1]).astype(dt) + a = np.array([0.5, -0.5]).astype(dt) + + # Test simple IIR + y_r = np.array([0, 2, 4, 6, 8, 10.]).astype(dt) + sos = tf2sos(b, a) + assert_array_almost_equal(sosfilt(tf2sos(b, a), x), y_r) + + # Test simple FIR + b = np.array([1, 1]).astype(dt) + # NOTE: This was changed (rel. to TestLinear...) to add a pole @zero: + a = np.array([1, 0]).astype(dt) + y_r = np.array([0, 1, 3, 5, 7, 9.]).astype(dt) + assert_array_almost_equal(sosfilt(tf2sos(b, a), x), y_r) + + b = [1, 1, 0] + a = [1, 0, 0] + x = np.ones(8) + sos = np.concatenate((b, a)) + sos.shape = (1, 6) + y = sosfilt(sos, x) + assert_allclose(y, [1, 2, 2, 2, 2, 2, 2, 2]) + + def test_rank2(self, dt): + shape = (4, 3) + x = np.linspace(0, np.prod(shape) - 1, np.prod(shape)).reshape(shape) + x = x.astype(dt) + + b = np.array([1, -1]).astype(dt) + a = np.array([0.5, 0.5]).astype(dt) + + y_r2_a0 = np.array([[0, 2, 4], [6, 4, 2], [0, 2, 4], [6, 4, 2]], + dtype=dt) + + y_r2_a1 = np.array([[0, 2, 0], [6, -4, 6], [12, -10, 12], + [18, -16, 18]], dtype=dt) + + y = sosfilt(tf2sos(b, a), x, axis=0) + assert_array_almost_equal(y_r2_a0, y) + + y = sosfilt(tf2sos(b, a), x, axis=1) + assert_array_almost_equal(y_r2_a1, y) + + def test_rank3(self, dt): + shape = (4, 3, 2) + x = np.linspace(0, np.prod(shape) - 1, np.prod(shape)).reshape(shape) + + b = np.array([1, -1]).astype(dt) + a = np.array([0.5, 0.5]).astype(dt) + + # Test last axis + y = sosfilt(tf2sos(b, a), x) + for i in range(x.shape[0]): + for j in range(x.shape[1]): + assert_array_almost_equal(y[i, j], lfilter(b, a, x[i, j])) + + def test_initial_conditions(self, dt): + b1, a1 = signal.butter(2, 0.25, 'low') + b2, a2 = signal.butter(2, 0.75, 'low') + b3, a3 = signal.butter(2, 0.75, 'low') + b = np.convolve(np.convolve(b1, b2), b3) + a = np.convolve(np.convolve(a1, a2), a3) + sos = np.array((np.r_[b1, a1], np.r_[b2, a2], np.r_[b3, a3])) + + x = np.random.rand(50).astype(dt) + + # Stopping filtering and continuing + y_true, zi = lfilter(b, a, x[:20], zi=np.zeros(6)) + y_true = np.r_[y_true, lfilter(b, a, x[20:], zi=zi)[0]] + assert_allclose_cast(y_true, lfilter(b, a, x)) + + y_sos, zi = sosfilt(sos, x[:20], zi=np.zeros((3, 2))) + y_sos = np.r_[y_sos, sosfilt(sos, x[20:], zi=zi)[0]] + assert_allclose_cast(y_true, y_sos) + + # Use a step function + zi = sosfilt_zi(sos) + x = np.ones(8, dt) + y, zf = sosfilt(sos, x, zi=zi) + + assert_allclose_cast(y, np.ones(8)) + assert_allclose_cast(zf, zi) + + # Initial condition shape matching + x.shape = (1, 1) + x.shape # 3D + assert_raises(ValueError, sosfilt, sos, x, zi=zi) + zi_nd = zi.copy() + zi_nd.shape = (zi.shape[0], 1, 1, zi.shape[-1]) + assert_raises(ValueError, sosfilt, sos, x, + zi=zi_nd[:, :, :, [0, 1, 1]]) + y, zf = sosfilt(sos, x, zi=zi_nd) + assert_allclose_cast(y[0, 0], np.ones(8)) + assert_allclose_cast(zf[:, 0, 0, :], zi) + + def test_initial_conditions_3d_axis1(self, dt): + # Test the use of zi when sosfilt is applied to axis 1 of a 3-d input. + + # Input array is x. + x = np.random.RandomState(159).randint(0, 5, size=(2, 15, 3)) + x = x.astype(dt) + + # Design a filter in ZPK format and convert to SOS + zpk = signal.butter(6, 0.35, output='zpk') + sos = zpk2sos(*zpk) + nsections = sos.shape[0] + + # Filter along this axis. + axis = 1 + + # Initial conditions, all zeros. + shp = list(x.shape) + shp[axis] = 2 + shp = [nsections] + shp + z0 = np.zeros(shp) + + # Apply the filter to x. + yf, zf = sosfilt(sos, x, axis=axis, zi=z0) + + # Apply the filter to x in two stages. + y1, z1 = sosfilt(sos, x[:, :5, :], axis=axis, zi=z0) + y2, z2 = sosfilt(sos, x[:, 5:, :], axis=axis, zi=z1) + + # y should equal yf, and z2 should equal zf. + y = np.concatenate((y1, y2), axis=axis) + assert_allclose_cast(y, yf, rtol=1e-10, atol=1e-13) + assert_allclose_cast(z2, zf, rtol=1e-10, atol=1e-13) + + # let's try the "step" initial condition + zi = sosfilt_zi(sos) + zi.shape = [nsections, 1, 2, 1] + zi = zi * x[:, 0:1, :] + y = sosfilt(sos, x, axis=axis, zi=zi)[0] + # check it against the TF form + b, a = zpk2tf(*zpk) + zi = lfilter_zi(b, a) + zi.shape = [1, zi.size, 1] + zi = zi * x[:, 0:1, :] + y_tf = lfilter(b, a, x, axis=axis, zi=zi)[0] + assert_allclose_cast(y, y_tf, rtol=1e-10, atol=1e-13) + + def test_bad_zi_shape(self, dt): + # The shape of zi is checked before using any values in the + # arguments, so np.empty is fine for creating the arguments. + x = np.empty((3, 15, 3), dt) + sos = np.zeros((4, 6)) + zi = np.empty((4, 3, 3, 2)) # Correct shape is (4, 3, 2, 3) + with pytest.raises(ValueError, match='should be all ones'): + sosfilt(sos, x, zi=zi, axis=1) + sos[:, 3] = 1. + with pytest.raises(ValueError, match='Invalid zi shape'): + sosfilt(sos, x, zi=zi, axis=1) + + def test_sosfilt_zi(self, dt): + sos = signal.butter(6, 0.2, output='sos') + zi = sosfilt_zi(sos) + + y, zf = sosfilt(sos, np.ones(40, dt), zi=zi) + assert_allclose_cast(zf, zi, rtol=1e-13) + + # Expected steady state value of the step response of this filter: + ss = np.prod(sos[:, :3].sum(axis=-1) / sos[:, 3:].sum(axis=-1)) + assert_allclose_cast(y, ss, rtol=1e-13) + + # zi as array-like + _, zf = sosfilt(sos, np.ones(40, dt), zi=zi.tolist()) + assert_allclose_cast(zf, zi, rtol=1e-13) + + @pytest.mark.thread_unsafe + def test_dtype_deprecation(self, dt): + # gh-21211 + sos = np.asarray([1, 2, 3, 1, 5, 3], dtype=object).reshape(1, 6) + x = np.asarray([2, 3, 4, 5, 3, 4, 2, 2, 1], dtype=object) + with pytest.deprecated_call(match="dtype=object is not supported"): + sosfilt(sos, x) + + +class TestDeconvolve: + + def test_basic(self): + # From docstring example + original = [0, 1, 0, 0, 1, 1, 0, 0] + impulse_response = [2, 1] + recorded = [0, 2, 1, 0, 2, 3, 1, 0, 0] + recovered, remainder = signal.deconvolve(recorded, impulse_response) + assert_allclose(recovered, original) + + def test_n_dimensional_signal(self): + recorded = [[0, 0], [0, 0]] + impulse_response = [0, 0] + with pytest.raises(ValueError, match="signal must be 1-D."): + quotient, remainder = signal.deconvolve(recorded, impulse_response) + + def test_n_dimensional_divisor(self): + recorded = [0, 0] + impulse_response = [[0, 0], [0, 0]] + with pytest.raises(ValueError, match="divisor must be 1-D."): + quotient, remainder = signal.deconvolve(recorded, impulse_response) + + +class TestDetrend: + + def test_basic(self): + detrended = detrend(array([1, 2, 3])) + detrended_exact = array([0, 0, 0]) + assert_array_almost_equal(detrended, detrended_exact) + + def test_copy(self): + x = array([1, 1.2, 1.5, 1.6, 2.4]) + copy_array = detrend(x, overwrite_data=False) + inplace = detrend(x, overwrite_data=True) + assert_array_almost_equal(copy_array, inplace) + + @pytest.mark.parametrize('kind', ['linear', 'constant']) + @pytest.mark.parametrize('axis', [0, 1, 2]) + def test_axis(self, axis, kind): + data = np.arange(5*6*7).reshape(5, 6, 7) + detrended = detrend(data, type=kind, axis=axis) + assert detrended.shape == data.shape + + def test_bp(self): + data = [0, 1, 2] + [5, 0, -5, -10] + detrended = detrend(data, type='linear', bp=3) + assert_allclose(detrended, 0, atol=1e-14) + + # repeat with ndim > 1 and axis + data = np.asarray(data)[None, :, None] + + detrended = detrend(data, type="linear", bp=3, axis=1) + assert_allclose(detrended, 0, atol=1e-14) + + # breakpoint index > shape[axis]: raises + with assert_raises(ValueError): + detrend(data, type="linear", bp=3) + + @pytest.mark.parametrize('bp', [np.array([0, 2]), [0, 2]]) + def test_detrend_array_bp(self, bp): + # regression test for https://github.com/scipy/scipy/issues/18675 + rng = np.random.RandomState(12345) + x = rng.rand(10) + # bp = np.array([0, 2]) + + res = detrend(x, bp=bp) + res_scipy_191 = np.array([-4.44089210e-16, -2.22044605e-16, + -1.11128506e-01, -1.69470553e-01, 1.14710683e-01, 6.35468419e-02, + 3.53533144e-01, -3.67877935e-02, -2.00417675e-02, -1.94362049e-01]) + + assert_allclose(res, res_scipy_191, atol=1e-14) + + +class TestUniqueRoots: + def test_real_no_repeat(self): + p = [-1.0, -0.5, 0.3, 1.2, 10.0] + unique, multiplicity = unique_roots(p) + assert_almost_equal(unique, p, decimal=15) + assert_equal(multiplicity, np.ones(len(p))) + + def test_real_repeat(self): + p = [-1.0, -0.95, -0.89, -0.8, 0.5, 1.0, 1.05] + + unique, multiplicity = unique_roots(p, tol=1e-1, rtype='min') + assert_almost_equal(unique, [-1.0, -0.89, 0.5, 1.0], decimal=15) + assert_equal(multiplicity, [2, 2, 1, 2]) + + unique, multiplicity = unique_roots(p, tol=1e-1, rtype='max') + assert_almost_equal(unique, [-0.95, -0.8, 0.5, 1.05], decimal=15) + assert_equal(multiplicity, [2, 2, 1, 2]) + + unique, multiplicity = unique_roots(p, tol=1e-1, rtype='avg') + assert_almost_equal(unique, [-0.975, -0.845, 0.5, 1.025], decimal=15) + assert_equal(multiplicity, [2, 2, 1, 2]) + + def test_complex_no_repeat(self): + p = [-1.0, 1.0j, 0.5 + 0.5j, -1.0 - 1.0j, 3.0 + 2.0j] + unique, multiplicity = unique_roots(p) + assert_almost_equal(unique, p, decimal=15) + assert_equal(multiplicity, np.ones(len(p))) + + def test_complex_repeat(self): + p = [-1.0, -1.0 + 0.05j, -0.95 + 0.15j, -0.90 + 0.15j, 0.0, + 0.5 + 0.5j, 0.45 + 0.55j] + + unique, multiplicity = unique_roots(p, tol=1e-1, rtype='min') + assert_almost_equal(unique, [-1.0, -0.95 + 0.15j, 0.0, 0.45 + 0.55j], + decimal=15) + assert_equal(multiplicity, [2, 2, 1, 2]) + + unique, multiplicity = unique_roots(p, tol=1e-1, rtype='max') + assert_almost_equal(unique, + [-1.0 + 0.05j, -0.90 + 0.15j, 0.0, 0.5 + 0.5j], + decimal=15) + assert_equal(multiplicity, [2, 2, 1, 2]) + + unique, multiplicity = unique_roots(p, tol=1e-1, rtype='avg') + assert_almost_equal( + unique, [-1.0 + 0.025j, -0.925 + 0.15j, 0.0, 0.475 + 0.525j], + decimal=15) + assert_equal(multiplicity, [2, 2, 1, 2]) + + def test_gh_4915(self): + p = np.roots(np.convolve(np.ones(5), np.ones(5))) + true_roots = [-(-1)**(1/5), (-1)**(4/5), -(-1)**(3/5), (-1)**(2/5)] + + unique, multiplicity = unique_roots(p) + unique = np.sort(unique) + + assert_almost_equal(np.sort(unique), true_roots, decimal=7) + assert_equal(multiplicity, [2, 2, 2, 2]) + + def test_complex_roots_extra(self): + unique, multiplicity = unique_roots([1.0, 1.0j, 1.0]) + assert_almost_equal(unique, [1.0, 1.0j], decimal=15) + assert_equal(multiplicity, [2, 1]) + + unique, multiplicity = unique_roots([1, 1 + 2e-9, 1e-9 + 1j], tol=0.1) + assert_almost_equal(unique, [1.0, 1e-9 + 1.0j], decimal=15) + assert_equal(multiplicity, [2, 1]) + + def test_single_unique_root(self): + p = np.random.rand(100) + 1j * np.random.rand(100) + unique, multiplicity = unique_roots(p, 2) + assert_almost_equal(unique, [np.min(p)], decimal=15) + assert_equal(multiplicity, [100]) + + +def test_gh_22684(): + actual = signal.resample_poly(np.arange(2000, dtype=np.complex64), 6, 4) + assert actual.dtype == np.complex64 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_spectral.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_spectral.py new file mode 100644 index 0000000000000000000000000000000000000000..12dac6300b9ef4b2eac0475f0b53517ab4867416 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_spectral.py @@ -0,0 +1,2059 @@ +import sys + +import numpy as np +from numpy.testing import (assert_, + assert_allclose, assert_array_equal, assert_equal, + assert_array_almost_equal_nulp, suppress_warnings) +import pytest +from pytest import raises as assert_raises + +from scipy import signal +from scipy.fft import fftfreq, rfftfreq, fft, irfft +from scipy.integrate import trapezoid +from scipy.signal import (periodogram, welch, lombscargle, coherence, + spectrogram, check_COLA, check_NOLA) +from scipy.signal.windows import hann +from scipy.signal._spectral_py import _spectral_helper + +# Compare ShortTimeFFT.stft() / ShortTimeFFT.istft() with stft() / istft(): +from scipy.signal.tests._scipy_spectral_test_shim import stft_compare as stft +from scipy.signal.tests._scipy_spectral_test_shim import istft_compare as istft +from scipy.signal.tests._scipy_spectral_test_shim import csd_compare as csd + + +class TestPeriodogram: + def test_real_onesided_even(self): + x = np.zeros(16) + x[0] = 1 + f, p = periodogram(x) + assert_allclose(f, np.linspace(0, 0.5, 9)) + q = np.ones(9) + q[0] = 0 + q[-1] /= 2.0 + q /= 8 + assert_allclose(p, q) + + def test_real_onesided_odd(self): + x = np.zeros(15) + x[0] = 1 + f, p = periodogram(x) + assert_allclose(f, np.arange(8.0)/15.0) + q = np.ones(8) + q[0] = 0 + q *= 2.0/15.0 + assert_allclose(p, q, atol=1e-15) + + def test_real_twosided(self): + x = np.zeros(16) + x[0] = 1 + f, p = periodogram(x, return_onesided=False) + assert_allclose(f, fftfreq(16, 1.0)) + q = np.full(16, 1/16.0) + q[0] = 0 + assert_allclose(p, q) + + def test_real_spectrum(self): + x = np.zeros(16) + x[0] = 1 + f, p = periodogram(x, scaling='spectrum') + g, q = periodogram(x, scaling='density') + assert_allclose(f, np.linspace(0, 0.5, 9)) + assert_allclose(p, q/16.0) + + def test_integer_even(self): + x = np.zeros(16, dtype=int) + x[0] = 1 + f, p = periodogram(x) + assert_allclose(f, np.linspace(0, 0.5, 9)) + q = np.ones(9) + q[0] = 0 + q[-1] /= 2.0 + q /= 8 + assert_allclose(p, q) + + def test_integer_odd(self): + x = np.zeros(15, dtype=int) + x[0] = 1 + f, p = periodogram(x) + assert_allclose(f, np.arange(8.0)/15.0) + q = np.ones(8) + q[0] = 0 + q *= 2.0/15.0 + assert_allclose(p, q, atol=1e-15) + + def test_integer_twosided(self): + x = np.zeros(16, dtype=int) + x[0] = 1 + f, p = periodogram(x, return_onesided=False) + assert_allclose(f, fftfreq(16, 1.0)) + q = np.full(16, 1/16.0) + q[0] = 0 + assert_allclose(p, q) + + def test_complex(self): + x = np.zeros(16, np.complex128) + x[0] = 1.0 + 2.0j + f, p = periodogram(x, return_onesided=False) + assert_allclose(f, fftfreq(16, 1.0)) + q = np.full(16, 5.0/16.0) + q[0] = 0 + assert_allclose(p, q) + + def test_unk_scaling(self): + assert_raises(ValueError, periodogram, np.zeros(4, np.complex128), + scaling='foo') + + @pytest.mark.skipif( + sys.maxsize <= 2**32, + reason="On some 32-bit tolerance issue" + ) + def test_nd_axis_m1(self): + x = np.zeros(20, dtype=np.float64) + x = x.reshape((2,1,10)) + x[:,:,0] = 1.0 + f, p = periodogram(x) + assert_array_equal(p.shape, (2, 1, 6)) + assert_array_almost_equal_nulp(p[0,0,:], p[1,0,:], 60) + f0, p0 = periodogram(x[0,0,:]) + assert_array_almost_equal_nulp(p0[np.newaxis,:], p[1,:], 60) + + @pytest.mark.skipif( + sys.maxsize <= 2**32, + reason="On some 32-bit tolerance issue" + ) + def test_nd_axis_0(self): + x = np.zeros(20, dtype=np.float64) + x = x.reshape((10,2,1)) + x[0,:,:] = 1.0 + f, p = periodogram(x, axis=0) + assert_array_equal(p.shape, (6,2,1)) + assert_array_almost_equal_nulp(p[:,0,0], p[:,1,0], 60) + f0, p0 = periodogram(x[:,0,0]) + assert_array_almost_equal_nulp(p0, p[:,1,0]) + + def test_window_external(self): + x = np.zeros(16) + x[0] = 1 + f, p = periodogram(x, 10, 'hann') + win = signal.get_window('hann', 16) + fe, pe = periodogram(x, 10, win) + assert_array_almost_equal_nulp(p, pe) + assert_array_almost_equal_nulp(f, fe) + win_err = signal.get_window('hann', 32) + assert_raises(ValueError, periodogram, x, + 10, win_err) # win longer than signal + + def test_padded_fft(self): + x = np.zeros(16) + x[0] = 1 + f, p = periodogram(x) + fp, pp = periodogram(x, nfft=32) + assert_allclose(f, fp[::2]) + assert_allclose(p, pp[::2]) + assert_array_equal(pp.shape, (17,)) + + def test_empty_input(self): + f, p = periodogram([]) + assert_array_equal(f.shape, (0,)) + assert_array_equal(p.shape, (0,)) + for shape in [(0,), (3,0), (0,5,2)]: + f, p = periodogram(np.empty(shape)) + assert_array_equal(f.shape, shape) + assert_array_equal(p.shape, shape) + + def test_empty_input_other_axis(self): + for shape in [(3,0), (0,5,2)]: + f, p = periodogram(np.empty(shape), axis=1) + assert_array_equal(f.shape, shape) + assert_array_equal(p.shape, shape) + + def test_short_nfft(self): + x = np.zeros(18) + x[0] = 1 + f, p = periodogram(x, nfft=16) + assert_allclose(f, np.linspace(0, 0.5, 9)) + q = np.ones(9) + q[0] = 0 + q[-1] /= 2.0 + q /= 8 + assert_allclose(p, q) + + def test_nfft_is_xshape(self): + x = np.zeros(16) + x[0] = 1 + f, p = periodogram(x, nfft=16) + assert_allclose(f, np.linspace(0, 0.5, 9)) + q = np.ones(9) + q[0] = 0 + q[-1] /= 2.0 + q /= 8 + assert_allclose(p, q) + + def test_real_onesided_even_32(self): + x = np.zeros(16, 'f') + x[0] = 1 + f, p = periodogram(x) + assert_allclose(f, np.linspace(0, 0.5, 9)) + q = np.ones(9, 'f') + q[0] = 0 + q[-1] /= 2.0 + q /= 8 + assert_allclose(p, q) + assert_(p.dtype == q.dtype) + + def test_real_onesided_odd_32(self): + x = np.zeros(15, 'f') + x[0] = 1 + f, p = periodogram(x) + assert_allclose(f, np.arange(8.0)/15.0) + q = np.ones(8, 'f') + q[0] = 0 + q *= 2.0/15.0 + assert_allclose(p, q, atol=1e-7) + assert_(p.dtype == q.dtype) + + def test_real_twosided_32(self): + x = np.zeros(16, 'f') + x[0] = 1 + f, p = periodogram(x, return_onesided=False) + assert_allclose(f, fftfreq(16, 1.0)) + q = np.full(16, 1/16.0, 'f') + q[0] = 0 + assert_allclose(p, q) + assert_(p.dtype == q.dtype) + + def test_complex_32(self): + x = np.zeros(16, 'F') + x[0] = 1.0 + 2.0j + f, p = periodogram(x, return_onesided=False) + assert_allclose(f, fftfreq(16, 1.0)) + q = np.full(16, 5.0/16.0, 'f') + q[0] = 0 + assert_allclose(p, q) + assert_(p.dtype == q.dtype) + + def test_shorter_window_error(self): + x = np.zeros(16) + x[0] = 1 + win = signal.get_window('hann', 10) + expected_msg = ('the size of the window must be the same size ' + 'of the input on the specified axis') + with assert_raises(ValueError, match=expected_msg): + periodogram(x, window=win) + + +class TestWelch: + def test_real_onesided_even(self): + x = np.zeros(16) + x[0] = 1 + x[8] = 1 + f, p = welch(x, nperseg=8) + assert_allclose(f, np.linspace(0, 0.5, 5)) + q = np.array([0.08333333, 0.15277778, 0.22222222, 0.22222222, + 0.11111111]) + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + + def test_real_onesided_odd(self): + x = np.zeros(16) + x[0] = 1 + x[8] = 1 + f, p = welch(x, nperseg=9) + assert_allclose(f, np.arange(5.0)/9.0) + q = np.array([0.12477455, 0.23430933, 0.17072113, 0.17072113, + 0.17072113]) + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + + def test_real_twosided(self): + x = np.zeros(16) + x[0] = 1 + x[8] = 1 + f, p = welch(x, nperseg=8, return_onesided=False) + assert_allclose(f, fftfreq(8, 1.0)) + q = np.array([0.08333333, 0.07638889, 0.11111111, 0.11111111, + 0.11111111, 0.11111111, 0.11111111, 0.07638889]) + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + + def test_real_spectrum(self): + x = np.zeros(16) + x[0] = 1 + x[8] = 1 + f, p = welch(x, nperseg=8, scaling='spectrum') + assert_allclose(f, np.linspace(0, 0.5, 5)) + q = np.array([0.015625, 0.02864583, 0.04166667, 0.04166667, + 0.02083333]) + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + + def test_integer_onesided_even(self): + x = np.zeros(16, dtype=int) + x[0] = 1 + x[8] = 1 + f, p = welch(x, nperseg=8) + assert_allclose(f, np.linspace(0, 0.5, 5)) + q = np.array([0.08333333, 0.15277778, 0.22222222, 0.22222222, + 0.11111111]) + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + + def test_integer_onesided_odd(self): + x = np.zeros(16, dtype=int) + x[0] = 1 + x[8] = 1 + f, p = welch(x, nperseg=9) + assert_allclose(f, np.arange(5.0)/9.0) + q = np.array([0.12477455, 0.23430933, 0.17072113, 0.17072113, + 0.17072113]) + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + + def test_integer_twosided(self): + x = np.zeros(16, dtype=int) + x[0] = 1 + x[8] = 1 + f, p = welch(x, nperseg=8, return_onesided=False) + assert_allclose(f, fftfreq(8, 1.0)) + q = np.array([0.08333333, 0.07638889, 0.11111111, 0.11111111, + 0.11111111, 0.11111111, 0.11111111, 0.07638889]) + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + + def test_complex(self): + x = np.zeros(16, np.complex128) + x[0] = 1.0 + 2.0j + x[8] = 1.0 + 2.0j + f, p = welch(x, nperseg=8, return_onesided=False) + assert_allclose(f, fftfreq(8, 1.0)) + q = np.array([0.41666667, 0.38194444, 0.55555556, 0.55555556, + 0.55555556, 0.55555556, 0.55555556, 0.38194444]) + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + + def test_unk_scaling(self): + assert_raises(ValueError, welch, np.zeros(4, np.complex128), + scaling='foo', nperseg=4) + + def test_detrend_linear(self): + x = np.arange(10, dtype=np.float64) + 0.04 + f, p = welch(x, nperseg=10, detrend='linear') + assert_allclose(p, np.zeros_like(p), atol=1e-15) + + def test_no_detrending(self): + x = np.arange(10, dtype=np.float64) + 0.04 + f1, p1 = welch(x, nperseg=10, detrend=False) + f2, p2 = welch(x, nperseg=10, detrend=lambda x: x) + assert_allclose(f1, f2, atol=1e-15) + assert_allclose(p1, p2, atol=1e-15) + + def test_detrend_external(self): + x = np.arange(10, dtype=np.float64) + 0.04 + f, p = welch(x, nperseg=10, + detrend=lambda seg: signal.detrend(seg, type='l')) + assert_allclose(p, np.zeros_like(p), atol=1e-15) + + def test_detrend_external_nd_m1(self): + x = np.arange(40, dtype=np.float64) + 0.04 + x = x.reshape((2,2,10)) + f, p = welch(x, nperseg=10, + detrend=lambda seg: signal.detrend(seg, type='l')) + assert_allclose(p, np.zeros_like(p), atol=1e-15) + + def test_detrend_external_nd_0(self): + x = np.arange(20, dtype=np.float64) + 0.04 + x = x.reshape((2,1,10)) + x = np.moveaxis(x, 2, 0) + f, p = welch(x, nperseg=10, axis=0, + detrend=lambda seg: signal.detrend(seg, axis=0, type='l')) + assert_allclose(p, np.zeros_like(p), atol=1e-15) + + def test_nd_axis_m1(self): + x = np.arange(20, dtype=np.float64) + 0.04 + x = x.reshape((2,1,10)) + f, p = welch(x, nperseg=10) + assert_array_equal(p.shape, (2, 1, 6)) + assert_allclose(p[0,0,:], p[1,0,:], atol=1e-13, rtol=1e-13) + f0, p0 = welch(x[0,0,:], nperseg=10) + assert_allclose(p0[np.newaxis,:], p[1,:], atol=1e-13, rtol=1e-13) + + def test_nd_axis_0(self): + x = np.arange(20, dtype=np.float64) + 0.04 + x = x.reshape((10,2,1)) + f, p = welch(x, nperseg=10, axis=0) + assert_array_equal(p.shape, (6,2,1)) + assert_allclose(p[:,0,0], p[:,1,0], atol=1e-13, rtol=1e-13) + f0, p0 = welch(x[:,0,0], nperseg=10) + assert_allclose(p0, p[:,1,0], atol=1e-13, rtol=1e-13) + + def test_window_external(self): + x = np.zeros(16) + x[0] = 1 + x[8] = 1 + f, p = welch(x, 10, 'hann', nperseg=8) + win = signal.get_window('hann', 8) + fe, pe = welch(x, 10, win, nperseg=None) + assert_array_almost_equal_nulp(p, pe) + assert_array_almost_equal_nulp(f, fe) + assert_array_equal(fe.shape, (5,)) # because win length used as nperseg + assert_array_equal(pe.shape, (5,)) + assert_raises(ValueError, welch, x, + 10, win, nperseg=4) # because nperseg != win.shape[-1] + win_err = signal.get_window('hann', 32) + assert_raises(ValueError, welch, x, + 10, win_err, nperseg=None) # win longer than signal + + def test_empty_input(self): + f, p = welch([]) + assert_array_equal(f.shape, (0,)) + assert_array_equal(p.shape, (0,)) + for shape in [(0,), (3,0), (0,5,2)]: + f, p = welch(np.empty(shape)) + assert_array_equal(f.shape, shape) + assert_array_equal(p.shape, shape) + + def test_empty_input_other_axis(self): + for shape in [(3,0), (0,5,2)]: + f, p = welch(np.empty(shape), axis=1) + assert_array_equal(f.shape, shape) + assert_array_equal(p.shape, shape) + + def test_short_data(self): + x = np.zeros(8) + x[0] = 1 + #for string-like window, input signal length < nperseg value gives + #UserWarning, sets nperseg to x.shape[-1] + with suppress_warnings() as sup: + msg = "nperseg = 256 is greater than input length = 8, using nperseg = 8" + sup.filter(UserWarning, msg) + f, p = welch(x,window='hann') # default nperseg + f1, p1 = welch(x,window='hann', nperseg=256) # user-specified nperseg + f2, p2 = welch(x, nperseg=8) # valid nperseg, doesn't give warning + assert_allclose(f, f2) + assert_allclose(p, p2) + assert_allclose(f1, f2) + assert_allclose(p1, p2) + + def test_window_long_or_nd(self): + assert_raises(ValueError, welch, np.zeros(4), 1, np.array([1,1,1,1,1])) + assert_raises(ValueError, welch, np.zeros(4), 1, + np.arange(6).reshape((2,3))) + + def test_nondefault_noverlap(self): + x = np.zeros(64) + x[::8] = 1 + f, p = welch(x, nperseg=16, noverlap=4) + q = np.array([0, 1./12., 1./3., 1./5., 1./3., 1./5., 1./3., 1./5., + 1./6.]) + assert_allclose(p, q, atol=1e-12) + + def test_bad_noverlap(self): + assert_raises(ValueError, welch, np.zeros(4), 1, 'hann', 2, 7) + + def test_nfft_too_short(self): + assert_raises(ValueError, welch, np.ones(12), nfft=3, nperseg=4) + + def test_real_onesided_even_32(self): + x = np.zeros(16, 'f') + x[0] = 1 + x[8] = 1 + f, p = welch(x, nperseg=8) + assert_allclose(f, np.linspace(0, 0.5, 5)) + q = np.array([0.08333333, 0.15277778, 0.22222222, 0.22222222, + 0.11111111], 'f') + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + assert_(p.dtype == q.dtype) + + def test_real_onesided_odd_32(self): + x = np.zeros(16, 'f') + x[0] = 1 + x[8] = 1 + f, p = welch(x, nperseg=9) + assert_allclose(f, np.arange(5.0)/9.0) + q = np.array([0.12477458, 0.23430935, 0.17072113, 0.17072116, + 0.17072113], 'f') + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + assert_(p.dtype == q.dtype) + + def test_real_twosided_32(self): + x = np.zeros(16, 'f') + x[0] = 1 + x[8] = 1 + f, p = welch(x, nperseg=8, return_onesided=False) + assert_allclose(f, fftfreq(8, 1.0)) + q = np.array([0.08333333, 0.07638889, 0.11111111, + 0.11111111, 0.11111111, 0.11111111, 0.11111111, + 0.07638889], 'f') + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + assert_(p.dtype == q.dtype) + + def test_complex_32(self): + x = np.zeros(16, 'F') + x[0] = 1.0 + 2.0j + x[8] = 1.0 + 2.0j + f, p = welch(x, nperseg=8, return_onesided=False) + assert_allclose(f, fftfreq(8, 1.0)) + q = np.array([0.41666666, 0.38194442, 0.55555552, 0.55555552, + 0.55555558, 0.55555552, 0.55555552, 0.38194442], 'f') + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + assert_(p.dtype == q.dtype, + f'dtype mismatch, {p.dtype}, {q.dtype}') + + def test_padded_freqs(self): + x = np.zeros(12) + + nfft = 24 + f = fftfreq(nfft, 1.0)[:nfft//2+1] + f[-1] *= -1 + fodd, _ = welch(x, nperseg=5, nfft=nfft) + feven, _ = welch(x, nperseg=6, nfft=nfft) + assert_allclose(f, fodd) + assert_allclose(f, feven) + + nfft = 25 + f = fftfreq(nfft, 1.0)[:(nfft + 1)//2] + fodd, _ = welch(x, nperseg=5, nfft=nfft) + feven, _ = welch(x, nperseg=6, nfft=nfft) + assert_allclose(f, fodd) + assert_allclose(f, feven) + + def test_window_correction(self): + A = 20 + fs = 1e4 + nperseg = int(fs//10) + fsig = 300 + ii = int(fsig*nperseg//fs) # Freq index of fsig + + tt = np.arange(fs)/fs + x = A*np.sin(2*np.pi*fsig*tt) + + for window in ['hann', 'bartlett', ('tukey', 0.1), 'flattop']: + _, p_spec = welch(x, fs=fs, nperseg=nperseg, window=window, + scaling='spectrum') + freq, p_dens = welch(x, fs=fs, nperseg=nperseg, window=window, + scaling='density') + + # Check peak height at signal frequency for 'spectrum' + assert_allclose(p_spec[ii], A**2/2.0) + # Check integrated spectrum RMS for 'density' + assert_allclose(np.sqrt(trapezoid(p_dens, freq)), A*np.sqrt(2)/2, + rtol=1e-3) + + def test_axis_rolling(self): + np.random.seed(1234) + + x_flat = np.random.randn(1024) + _, p_flat = welch(x_flat) + + for a in range(3): + newshape = [1,]*3 + newshape[a] = -1 + x = x_flat.reshape(newshape) + + _, p_plus = welch(x, axis=a) # Positive axis index + _, p_minus = welch(x, axis=a-x.ndim) # Negative axis index + + assert_equal(p_flat, p_plus.squeeze(), err_msg=a) + assert_equal(p_flat, p_minus.squeeze(), err_msg=a-x.ndim) + + def test_average(self): + x = np.zeros(16) + x[0] = 1 + x[8] = 1 + f, p = welch(x, nperseg=8, average='median') + assert_allclose(f, np.linspace(0, 0.5, 5)) + q = np.array([.1, .05, 0., 1.54074396e-33, 0.]) + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + + assert_raises(ValueError, welch, x, nperseg=8, + average='unrecognised-average') + + +class TestCSD: + def test_pad_shorter_x(self): + x = np.zeros(8) + y = np.zeros(12) + + f = np.linspace(0, 0.5, 7) + c = np.zeros(7,dtype=np.complex128) + f1, c1 = csd(x, y, nperseg=12) + + assert_allclose(f, f1) + assert_allclose(c, c1) + + def test_pad_shorter_y(self): + x = np.zeros(12) + y = np.zeros(8) + + f = np.linspace(0, 0.5, 7) + c = np.zeros(7,dtype=np.complex128) + f1, c1 = csd(x, y, nperseg=12) + + assert_allclose(f, f1) + assert_allclose(c, c1) + + def test_real_onesided_even(self): + x = np.zeros(16) + x[0] = 1 + x[8] = 1 + f, p = csd(x, x, nperseg=8) + assert_allclose(f, np.linspace(0, 0.5, 5)) + q = np.array([0.08333333, 0.15277778, 0.22222222, 0.22222222, + 0.11111111]) + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + + def test_real_onesided_odd(self): + x = np.zeros(16) + x[0] = 1 + x[8] = 1 + f, p = csd(x, x, nperseg=9) + assert_allclose(f, np.arange(5.0)/9.0) + q = np.array([0.12477455, 0.23430933, 0.17072113, 0.17072113, + 0.17072113]) + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + + def test_real_twosided(self): + x = np.zeros(16) + x[0] = 1 + x[8] = 1 + f, p = csd(x, x, nperseg=8, return_onesided=False) + assert_allclose(f, fftfreq(8, 1.0)) + q = np.array([0.08333333, 0.07638889, 0.11111111, 0.11111111, + 0.11111111, 0.11111111, 0.11111111, 0.07638889]) + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + + def test_real_spectrum(self): + x = np.zeros(16) + x[0] = 1 + x[8] = 1 + f, p = csd(x, x, nperseg=8, scaling='spectrum') + assert_allclose(f, np.linspace(0, 0.5, 5)) + q = np.array([0.015625, 0.02864583, 0.04166667, 0.04166667, + 0.02083333]) + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + + def test_integer_onesided_even(self): + x = np.zeros(16, dtype=int) + x[0] = 1 + x[8] = 1 + f, p = csd(x, x, nperseg=8) + assert_allclose(f, np.linspace(0, 0.5, 5)) + q = np.array([0.08333333, 0.15277778, 0.22222222, 0.22222222, + 0.11111111]) + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + + def test_integer_onesided_odd(self): + x = np.zeros(16, dtype=int) + x[0] = 1 + x[8] = 1 + f, p = csd(x, x, nperseg=9) + assert_allclose(f, np.arange(5.0)/9.0) + q = np.array([0.12477455, 0.23430933, 0.17072113, 0.17072113, + 0.17072113]) + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + + def test_integer_twosided(self): + x = np.zeros(16, dtype=int) + x[0] = 1 + x[8] = 1 + f, p = csd(x, x, nperseg=8, return_onesided=False) + assert_allclose(f, fftfreq(8, 1.0)) + q = np.array([0.08333333, 0.07638889, 0.11111111, 0.11111111, + 0.11111111, 0.11111111, 0.11111111, 0.07638889]) + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + + def test_complex(self): + x = np.zeros(16, np.complex128) + x[0] = 1.0 + 2.0j + x[8] = 1.0 + 2.0j + f, p = csd(x, x, nperseg=8, return_onesided=False) + assert_allclose(f, fftfreq(8, 1.0)) + q = np.array([0.41666667, 0.38194444, 0.55555556, 0.55555556, + 0.55555556, 0.55555556, 0.55555556, 0.38194444]) + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + + def test_unk_scaling(self): + assert_raises(ValueError, csd, np.zeros(4, np.complex128), + np.ones(4, np.complex128), scaling='foo', nperseg=4) + + def test_detrend_linear(self): + x = np.arange(10, dtype=np.float64) + 0.04 + f, p = csd(x, x, nperseg=10, detrend='linear') + assert_allclose(p, np.zeros_like(p), atol=1e-15) + + def test_no_detrending(self): + x = np.arange(10, dtype=np.float64) + 0.04 + f1, p1 = csd(x, x, nperseg=10, detrend=False) + f2, p2 = csd(x, x, nperseg=10, detrend=lambda x: x) + assert_allclose(f1, f2, atol=1e-15) + assert_allclose(p1, p2, atol=1e-15) + + def test_detrend_external(self): + x = np.arange(10, dtype=np.float64) + 0.04 + f, p = csd(x, x, nperseg=10, + detrend=lambda seg: signal.detrend(seg, type='l')) + assert_allclose(p, np.zeros_like(p), atol=1e-15) + + def test_detrend_external_nd_m1(self): + x = np.arange(40, dtype=np.float64) + 0.04 + x = x.reshape((2,2,10)) + f, p = csd(x, x, nperseg=10, + detrend=lambda seg: signal.detrend(seg, type='l')) + assert_allclose(p, np.zeros_like(p), atol=1e-15) + + def test_detrend_external_nd_0(self): + x = np.arange(20, dtype=np.float64) + 0.04 + x = x.reshape((2,1,10)) + x = np.moveaxis(x, 2, 0) + f, p = csd(x, x, nperseg=10, axis=0, + detrend=lambda seg: signal.detrend(seg, axis=0, type='l')) + assert_allclose(p, np.zeros_like(p), atol=1e-15) + + def test_nd_axis_m1(self): + x = np.arange(20, dtype=np.float64) + 0.04 + x = x.reshape((2,1,10)) + f, p = csd(x, x, nperseg=10) + assert_array_equal(p.shape, (2, 1, 6)) + assert_allclose(p[0,0,:], p[1,0,:], atol=1e-13, rtol=1e-13) + f0, p0 = csd(x[0,0,:], x[0,0,:], nperseg=10) + assert_allclose(p0[np.newaxis,:], p[1,:], atol=1e-13, rtol=1e-13) + + def test_nd_axis_0(self): + x = np.arange(20, dtype=np.float64) + 0.04 + x = x.reshape((10,2,1)) + f, p = csd(x, x, nperseg=10, axis=0) + assert_array_equal(p.shape, (6,2,1)) + assert_allclose(p[:,0,0], p[:,1,0], atol=1e-13, rtol=1e-13) + f0, p0 = csd(x[:,0,0], x[:,0,0], nperseg=10) + assert_allclose(p0, p[:,1,0], atol=1e-13, rtol=1e-13) + + def test_window_external(self): + x = np.zeros(16) + x[0] = 1 + x[8] = 1 + f, p = csd(x, x, 10, 'hann', 8) + win = signal.get_window('hann', 8) + fe, pe = csd(x, x, 10, win, nperseg=None) + assert_array_almost_equal_nulp(p, pe) + assert_array_almost_equal_nulp(f, fe) + assert_array_equal(fe.shape, (5,)) # because win length used as nperseg + assert_array_equal(pe.shape, (5,)) + assert_raises(ValueError, csd, x, x, + 10, win, nperseg=256) # because nperseg != win.shape[-1] + win_err = signal.get_window('hann', 32) + assert_raises(ValueError, csd, x, x, + 10, win_err, nperseg=None) # because win longer than signal + + def test_empty_input(self): + f, p = csd([],np.zeros(10)) + assert_array_equal(f.shape, (0,)) + assert_array_equal(p.shape, (0,)) + + f, p = csd(np.zeros(10),[]) + assert_array_equal(f.shape, (0,)) + assert_array_equal(p.shape, (0,)) + + for shape in [(0,), (3,0), (0,5,2)]: + f, p = csd(np.empty(shape), np.empty(shape)) + assert_array_equal(f.shape, shape) + assert_array_equal(p.shape, shape) + + f, p = csd(np.ones(10), np.empty((5,0))) + assert_array_equal(f.shape, (5,0)) + assert_array_equal(p.shape, (5,0)) + + f, p = csd(np.empty((5,0)), np.ones(10)) + assert_array_equal(f.shape, (5,0)) + assert_array_equal(p.shape, (5,0)) + + def test_empty_input_other_axis(self): + for shape in [(3,0), (0,5,2)]: + f, p = csd(np.empty(shape), np.empty(shape), axis=1) + assert_array_equal(f.shape, shape) + assert_array_equal(p.shape, shape) + + f, p = csd(np.empty((10,10,3)), np.zeros((10,0,1)), axis=1) + assert_array_equal(f.shape, (10,0,3)) + assert_array_equal(p.shape, (10,0,3)) + + f, p = csd(np.empty((10,0,1)), np.zeros((10,10,3)), axis=1) + assert_array_equal(f.shape, (10,0,3)) + assert_array_equal(p.shape, (10,0,3)) + + def test_short_data(self): + x = np.zeros(8) + x[0] = 1 + + #for string-like window, input signal length < nperseg value gives + #UserWarning, sets nperseg to x.shape[-1] + with suppress_warnings() as sup: + msg = "nperseg = 256 is greater than input length = 8, using nperseg = 8" + sup.filter(UserWarning, msg) + f, p = csd(x, x, window='hann') # default nperseg + f1, p1 = csd(x, x, window='hann', nperseg=256) # user-specified nperseg + f2, p2 = csd(x, x, nperseg=8) # valid nperseg, doesn't give warning + assert_allclose(f, f2) + assert_allclose(p, p2) + assert_allclose(f1, f2) + assert_allclose(p1, p2) + + def test_window_long_or_nd(self): + assert_raises(ValueError, csd, np.zeros(4), np.ones(4), 1, + np.array([1,1,1,1,1])) + assert_raises(ValueError, csd, np.zeros(4), np.ones(4), 1, + np.arange(6).reshape((2,3))) + + def test_nondefault_noverlap(self): + x = np.zeros(64) + x[::8] = 1 + f, p = csd(x, x, nperseg=16, noverlap=4) + q = np.array([0, 1./12., 1./3., 1./5., 1./3., 1./5., 1./3., 1./5., + 1./6.]) + assert_allclose(p, q, atol=1e-12) + + def test_bad_noverlap(self): + assert_raises(ValueError, csd, np.zeros(4), np.ones(4), 1, 'hann', + 2, 7) + + def test_nfft_too_short(self): + assert_raises(ValueError, csd, np.ones(12), np.zeros(12), nfft=3, + nperseg=4) + + def test_real_onesided_even_32(self): + x = np.zeros(16, 'f') + x[0] = 1 + x[8] = 1 + f, p = csd(x, x, nperseg=8) + assert_allclose(f, np.linspace(0, 0.5, 5)) + q = np.array([0.08333333, 0.15277778, 0.22222222, 0.22222222, + 0.11111111], 'f') + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + assert_(p.dtype == q.dtype) + + def test_real_onesided_odd_32(self): + x = np.zeros(16, 'f') + x[0] = 1 + x[8] = 1 + f, p = csd(x, x, nperseg=9) + assert_allclose(f, np.arange(5.0)/9.0) + q = np.array([0.12477458, 0.23430935, 0.17072113, 0.17072116, + 0.17072113], 'f') + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + assert_(p.dtype == q.dtype) + + def test_real_twosided_32(self): + x = np.zeros(16, 'f') + x[0] = 1 + x[8] = 1 + f, p = csd(x, x, nperseg=8, return_onesided=False) + assert_allclose(f, fftfreq(8, 1.0)) + q = np.array([0.08333333, 0.07638889, 0.11111111, + 0.11111111, 0.11111111, 0.11111111, 0.11111111, + 0.07638889], 'f') + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + assert_(p.dtype == q.dtype) + + def test_complex_32(self): + x = np.zeros(16, 'F') + x[0] = 1.0 + 2.0j + x[8] = 1.0 + 2.0j + f, p = csd(x, x, nperseg=8, return_onesided=False) + assert_allclose(f, fftfreq(8, 1.0)) + q = np.array([0.41666666, 0.38194442, 0.55555552, 0.55555552, + 0.55555558, 0.55555552, 0.55555552, 0.38194442], 'f') + assert_allclose(p, q, atol=1e-7, rtol=1e-7) + assert_(p.dtype == q.dtype, + f'dtype mismatch, {p.dtype}, {q.dtype}') + + def test_padded_freqs(self): + x = np.zeros(12) + y = np.ones(12) + + nfft = 24 + f = fftfreq(nfft, 1.0)[:nfft//2+1] + f[-1] *= -1 + fodd, _ = csd(x, y, nperseg=5, nfft=nfft) + feven, _ = csd(x, y, nperseg=6, nfft=nfft) + assert_allclose(f, fodd) + assert_allclose(f, feven) + + nfft = 25 + f = fftfreq(nfft, 1.0)[:(nfft + 1)//2] + fodd, _ = csd(x, y, nperseg=5, nfft=nfft) + feven, _ = csd(x, y, nperseg=6, nfft=nfft) + assert_allclose(f, fodd) + assert_allclose(f, feven) + + def test_copied_data(self): + x = np.random.randn(64) + y = x.copy() + + _, p_same = csd(x, x, nperseg=8, average='mean', + return_onesided=False) + _, p_copied = csd(x, y, nperseg=8, average='mean', + return_onesided=False) + assert_allclose(p_same, p_copied) + + _, p_same = csd(x, x, nperseg=8, average='median', + return_onesided=False) + _, p_copied = csd(x, y, nperseg=8, average='median', + return_onesided=False) + assert_allclose(p_same, p_copied) + + +class TestCoherence: + def test_identical_input(self): + x = np.random.randn(20) + y = np.copy(x) # So `y is x` -> False + + f = np.linspace(0, 0.5, 6) + C = np.ones(6) + f1, C1 = coherence(x, y, nperseg=10) + + assert_allclose(f, f1) + assert_allclose(C, C1) + + def test_phase_shifted_input(self): + x = np.random.randn(20) + y = -x + + f = np.linspace(0, 0.5, 6) + C = np.ones(6) + f1, C1 = coherence(x, y, nperseg=10) + + assert_allclose(f, f1) + assert_allclose(C, C1) + + +class TestSpectrogram: + def test_average_all_segments(self): + x = np.random.randn(1024) + + fs = 1.0 + window = ('tukey', 0.25) + nperseg = 16 + noverlap = 2 + + f, _, P = spectrogram(x, fs, window, nperseg, noverlap) + fw, Pw = welch(x, fs, window, nperseg, noverlap) + assert_allclose(f, fw) + assert_allclose(np.mean(P, axis=-1), Pw) + + def test_window_external(self): + x = np.random.randn(1024) + + fs = 1.0 + window = ('tukey', 0.25) + nperseg = 16 + noverlap = 2 + f, _, P = spectrogram(x, fs, window, nperseg, noverlap) + + win = signal.get_window(('tukey', 0.25), 16) + fe, _, Pe = spectrogram(x, fs, win, nperseg=None, noverlap=2) + assert_array_equal(fe.shape, (9,)) # because win length used as nperseg + assert_array_equal(Pe.shape, (9,73)) + assert_raises(ValueError, spectrogram, x, + fs, win, nperseg=8) # because nperseg != win.shape[-1] + win_err = signal.get_window(('tukey', 0.25), 2048) + assert_raises(ValueError, spectrogram, x, + fs, win_err, nperseg=None) # win longer than signal + + def test_short_data(self): + x = np.random.randn(1024) + fs = 1.0 + + #for string-like window, input signal length < nperseg value gives + #UserWarning, sets nperseg to x.shape[-1] + f, _, p = spectrogram(x, fs, window=('tukey',0.25)) # default nperseg + with suppress_warnings() as sup: + sup.filter(UserWarning, + "nperseg = 1025 is greater than input length = 1024, " + "using nperseg = 1024",) + f1, _, p1 = spectrogram(x, fs, window=('tukey',0.25), + nperseg=1025) # user-specified nperseg + f2, _, p2 = spectrogram(x, fs, nperseg=256) # to compare w/default + f3, _, p3 = spectrogram(x, fs, nperseg=1024) # compare w/user-spec'd + assert_allclose(f, f2) + assert_allclose(p, p2) + assert_allclose(f1, f3) + assert_allclose(p1, p3) + +class TestLombscargle: + def test_frequency(self): + """Test if frequency location of peak corresponds to frequency of + generated input signal. + """ + + # Input parameters + ampl = 2. + w = 1. + phi = 0.5 * np.pi + nin = 100 + nout = 1000 + p = 0.7 # Fraction of points to select + + # Randomly select a fraction of an array with timesteps + rng = np.random.RandomState(2353425) + r = rng.rand(nin) + t = np.linspace(0.01*np.pi, 10.*np.pi, nin)[r >= p] + + # Plot a sine wave for the selected times + y = ampl * np.sin(w*t + phi) + + # Define the array of frequencies for which to compute the periodogram + f = np.linspace(0.01, 10., nout) + + # Calculate Lomb-Scargle periodogram + P = lombscargle(t, y, f) + + # Check if difference between found frequency maximum and input + # frequency is less than accuracy + delta = f[1] - f[0] + assert(w - f[np.argmax(P)] < (delta/2.)) + + # also, check that it works with weights + P = lombscargle(t, y, f, weights=np.ones_like(t, dtype=f.dtype)) + + # Check if difference between found frequency maximum and input + # frequency is less than accuracy + delta = f[1] - f[0] + assert(w - f[np.argmax(P)] < (delta/2.)) + + + def test_amplitude(self): + # Test if height of peak in unnormalized Lomb-Scargle periodogram + # corresponds to amplitude of the generated input signal. + + # Input parameters + ampl = 2. + w = 1. + phi = 0.5 * np.pi + nin = 1000 + nout = 1000 + p = 0.7 # Fraction of points to select + + # Randomly select a fraction of an array with timesteps + rng = np.random.RandomState(2353425) + r = rng.rand(nin) + t = np.linspace(0.01*np.pi, 10.*np.pi, nin)[r >= p] + + # Plot a sine wave for the selected times + y = ampl * np.sin(w*t + phi) + + # Define the array of frequencies for which to compute the periodogram + f = np.linspace(0.01, 10., nout) + + # Calculate Lomb-Scargle periodogram + pgram = lombscargle(t, y, f) + + # convert to the amplitude + pgram = np.sqrt(4.0 * pgram / t.shape[0]) + + # Check if amplitude is correct (this will not exactly match, due to + # numerical differences when data is removed) + assert_allclose(pgram[f==w], ampl, rtol=5e-2) + + def test_precenter(self): + # Test if precenter gives the same result as manually precentering + # (for a very simple offset) + + # Input parameters + ampl = 2. + w = 1. + phi = 0.5 * np.pi + nin = 100 + nout = 1000 + p = 0.7 # Fraction of points to select + offset = 0.15 # Offset to be subtracted in pre-centering + + # Randomly select a fraction of an array with timesteps + rng = np.random.RandomState(2353425) + r = rng.rand(nin) + t = np.linspace(0.01*np.pi, 10.*np.pi, nin)[r >= p] + + # Plot a sine wave for the selected times + y = ampl * np.sin(w*t + phi) + offset + + # Define the array of frequencies for which to compute the periodogram + f = np.linspace(0.01, 10., nout) + + # Calculate Lomb-Scargle periodogram + pgram = lombscargle(t, y, f, precenter=True) + pgram2 = lombscargle(t, y - y.mean(), f, precenter=False) + + # check if centering worked + assert_allclose(pgram, pgram2) + + # do this again, but with floating_mean=True + + # Calculate Lomb-Scargle periodogram + pgram = lombscargle(t, y, f, precenter=True, floating_mean=True) + pgram2 = lombscargle(t, y - y.mean(), f, precenter=False, floating_mean=True) + + # check if centering worked + assert_allclose(pgram, pgram2) + + def test_normalize(self): + # Test normalize option of Lomb-Scarge. + + # Input parameters + ampl = 2. + w = 1. + phi = 0.5 * np.pi + nin = 100 + nout = 1000 + p = 0.7 # Fraction of points to select + + # Randomly select a fraction of an array with timesteps + rng = np.random.RandomState(2353425) + r = rng.rand(nin) + t = np.linspace(0.01*np.pi, 10.*np.pi, nin)[r >= p] + + # Plot a sine wave for the selected times + y = ampl * np.sin(w*t + phi) + + # Define the array of frequencies for which to compute the periodogram + f = np.linspace(0.01, 10., nout) + + # Calculate Lomb-Scargle periodogram + pgram = lombscargle(t, y, f) + pgram2 = lombscargle(t, y, f, normalize=True) + + # Calculate the scale to convert from unnormalized to normalized + weights = np.ones_like(t)/float(t.shape[0]) + YY_hat = (weights * y * y).sum() + YY = YY_hat # correct formula for floating_mean=False + scale_to_use = 2/(YY*t.shape[0]) + + # check if normalization works as expected + assert_allclose(pgram * scale_to_use, pgram2) + assert_allclose(np.max(pgram2), 1.0) + + def test_wrong_shape(self): + + # different length t and y + t = np.linspace(0, 1, 1) + y = np.linspace(0, 1, 2) + f = np.linspace(0, 1, 3) + 0.1 + assert_raises(ValueError, lombscargle, t, y, f) + + # t is 2D, with both axes length > 1 + t = np.repeat(np.expand_dims(np.linspace(0, 1, 2), 1), 2, axis=1) + y = np.linspace(0, 1, 2) + f = np.linspace(0, 1, 3) + 0.1 + assert_raises(ValueError, lombscargle, t, y, f) + + # y is 2D, with both axes length > 1 + t = np.linspace(0, 1, 2) + y = np.repeat(np.expand_dims(np.linspace(0, 1, 2), 1), 2, axis=1) + f = np.linspace(0, 1, 3) + 0.1 + assert_raises(ValueError, lombscargle, t, y, f) + + # f is 2D, with both axes length > 1 + t = np.linspace(0, 1, 2) + y = np.linspace(0, 1, 2) + f = np.repeat(np.expand_dims(np.linspace(0, 1, 3), 1) + 0.1, 2, axis=1) + assert_raises(ValueError, lombscargle, t, y, f) + + # weights is 2D, with both axes length > 1 + t = np.linspace(0, 1, 2) + y = np.linspace(0, 1, 2) + f = np.linspace(0, 1, 3) + 0.1 + weights = np.repeat(np.expand_dims(np.linspace(0, 1, 2), 1), 2, axis=1) + assert_raises(ValueError, lombscargle, t, y, f, weights=weights) + + def test_lombscargle_atan_vs_atan2(self): + # https://github.com/scipy/scipy/issues/3787 + # This raised a ZeroDivisionError. + t = np.linspace(0, 10, 1000, endpoint=False) + y = np.sin(4*t) + f = np.linspace(0, 50, 500, endpoint=False) + 0.1 + lombscargle(t, y, f*2*np.pi) + + def test_wrong_shape_weights(self): + # Weights must be the same shape as t + + t = np.linspace(0, 1, 1) + y = np.linspace(0, 1, 1) + f = np.linspace(0, 1, 3) + 0.1 + weights = np.linspace(1, 2, 2) + assert_raises(ValueError, lombscargle, t, y, f, weights=weights) + + def test_zero_division_weights(self): + # Weights cannot sum to 0 + + t = np.zeros(1) + y = np.zeros(1) + f = np.ones(1) + weights = np.zeros(1) + assert_raises(ValueError, lombscargle, t, y, f, weights=weights) + + def test_normalize_parameter(self): + # Test the validity of the normalize parameter input + + # Input parameters + ampl = 2. + w = 1. + phi = 0 + nin = 100 + nout = 1000 + p = 0.7 # Fraction of points to select + + # Randomly select a fraction of an array with timesteps + rng = np.random.RandomState(2353425) + r = rng.rand(nin) + t = np.linspace(0.01*np.pi, 10.*np.pi, nin)[r >= p] + + # Plot a sine wave for the selected times + y = ampl * np.sin(w*t + phi) + + # Define the array of frequencies for which to compute the periodogram + f = np.linspace(0.01, 10., nout) + + # check each of the valid inputs + pgram_false = lombscargle(t, y, f, normalize=False) + pgram_true = lombscargle(t, y, f, normalize=True) + pgram_power = lombscargle(t, y, f, normalize='power') + pgram_norm = lombscargle(t, y, f, normalize='normalize') + pgram_amp = lombscargle(t, y, f, normalize='amplitude') + + # validate the results that should be the same + assert_allclose(pgram_false, pgram_power) + assert_allclose(pgram_true, pgram_norm) + + # validate that the power and norm outputs are proper wrt each other + weights = np.ones_like(y)/float(y.shape[0]) + YY_hat = (weights * y * y).sum() + YY = YY_hat # correct formula for floating_mean=False + assert_allclose(pgram_power * 2.0 / (float(t.shape[0]) * YY), pgram_norm) + + # validate that the amp output is correct for the given input + f_i = np.where(f==w)[0][0] + assert_allclose(np.abs(pgram_amp[f_i]), ampl) + + # check invalid inputs + # 1) a string that is not allowed + assert_raises(ValueError, lombscargle, t, y, f, normalize='lomb') + # 2) something besides a bool or str + assert_raises(ValueError, lombscargle, t, y, f, normalize=2) + + def test_offset_removal(self): + # Verify that the amplitude is the same, even with an offset + # must use floating_mean=True, otherwise it will not remove an offset + + # Input parameters + ampl = 2. + w = 1. + phi = 0.5 * np.pi + nin = 100 + nout = 1000 + p = 0.7 # Fraction of points to select + offset = 2.15 # Large offset + + # Randomly select a fraction of an array with timesteps + rng = np.random.RandomState(2353425) + r = rng.rand(nin) + t = np.linspace(0.01*np.pi, 10.*np.pi, nin)[r >= p] + + # Plot a sine wave for the selected times + y = ampl * np.sin(w*t + phi) + + # Define the array of frequencies for which to compute the periodogram + f = np.linspace(0.01, 10., nout) + + # Calculate Lomb-Scargle periodogram + pgram = lombscargle(t, y, f, floating_mean=True) + pgram_offset = lombscargle(t, y + offset, f, floating_mean=True) + + # check if offset removal works as expected + assert_allclose(pgram, pgram_offset) + + def test_floating_mean_false(self): + # Verify that when disabling the floating_mean, the calculations are correct + + # Input parameters + ampl = 2. + w = 1. + phi = 0 + nin = 1000 + nout = 1000 + p = 0.7 # Fraction of points to select + offset = 2 # Large offset + + # Randomly select a fraction of an array with timesteps + rng = np.random.RandomState(2353425) + r = rng.rand(nin) + t = np.linspace(0.01*np.pi, 10.*np.pi, nin)[r >= p] + + # Plot a cos wave for the selected times + y = ampl * np.cos(w*t + phi) + + # Define the array of frequencies for which to compute the periodogram + f = np.linspace(0.01, 10., nout) + + # Calculate Lomb-Scargle periodogram + pgram = lombscargle(t, y, f, normalize=True, floating_mean=False) + pgram_offset = lombscargle(t, y + offset, f, normalize=True, + floating_mean=False) + + # check if disabling floating_mean works as expected + # nearly-zero for no offset, exact value will change based on seed + assert(pgram[0] < 0.01) + # significant value with offset, exact value will change based on seed + assert(pgram_offset[0] > 0.5) + + def test_amplitude_is_correct(self): + # Verify that the amplitude is correct (when normalize='amplitude') + + # Input parameters + ampl = 2. + w = 1. + phi = 0.12 + nin = 100 + nout = 1000 + p = 0.7 # Fraction of points to select + offset = 2.15 # Large offset + + # Randomly select a fraction of an array with timesteps + rng = np.random.RandomState(2353425) + r = rng.rand(nin) + t = np.linspace(0.01*np.pi, 10.*np.pi, nin)[r >= p] + + # Plot a sine wave for the selected times + y = ampl * np.cos(w*t + phi) + offset + + # Define the array of frequencies for which to compute the periodogram + f = np.linspace(0.01, 10., nout) + + # Get the index of where the exact result should be + f_indx = np.where(f==w)[0][0] + + # Calculate Lomb-Scargle periodogram (amplitude + phase) + pgram = lombscargle(t, y, f, normalize='amplitude', floating_mean=True) + + # Check if amplitude is correct + assert_allclose(np.abs(pgram[f_indx]), ampl) + + # Check if phase is correct + # (phase angle is the negative of the phase offset) + assert_allclose(-np.angle(pgram[f_indx]), phi) + + def test_negative_weight(self): + # Test that a negative weight produces an error + + t = np.zeros(1) + y = np.zeros(1) + f = np.ones(1) + weights = -np.ones(1) + assert_raises(ValueError, lombscargle, t, y, f, weights=weights) + + def test_list_input(self): + # Test that input can be passsed in as lists and with a numerical issue + # https://github.com/scipy/scipy/issues/8787 + + t = [1.98201652e+09, 1.98201752e+09, 1.98201852e+09, 1.98201952e+09, + 1.98202052e+09, 1.98202152e+09, 1.98202252e+09, 1.98202352e+09, + 1.98202452e+09, 1.98202552e+09, 1.98202652e+09, 1.98202752e+09, + 1.98202852e+09, 1.98202952e+09, 1.98203052e+09, 1.98203152e+09, + 1.98203252e+09, 1.98203352e+09, 1.98203452e+09, 1.98203552e+09, + 1.98205452e+09, 1.98205552e+09, 1.98205652e+09, 1.98205752e+09, + 1.98205852e+09, 1.98205952e+09, 1.98206052e+09, 1.98206152e+09, + 1.98206252e+09, 1.98206352e+09, 1.98206452e+09, 1.98206552e+09, + 1.98206652e+09, 1.98206752e+09, 1.98206852e+09, 1.98206952e+09, + 1.98207052e+09, 1.98207152e+09, 1.98207252e+09, 1.98207352e+09, + 1.98209652e+09, 1.98209752e+09, 1.98209852e+09, 1.98209952e+09, + 1.98210052e+09, 1.98210152e+09, 1.98210252e+09, 1.98210352e+09, + 1.98210452e+09, 1.98210552e+09, 1.98210652e+09, 1.98210752e+09, + 1.98210852e+09, 1.98210952e+09, 1.98211052e+09, 1.98211152e+09, + 1.98211252e+09, 1.98211352e+09, 1.98211452e+09, 1.98211552e+09, + 1.98217252e+09, 1.98217352e+09, 1.98217452e+09, 1.98217552e+09, + 1.98217652e+09, 1.98217752e+09, 1.98217852e+09, 1.98217952e+09, + 1.98218052e+09, 1.98218152e+09, 1.98218252e+09, 1.98218352e+09, + 1.98218452e+09, 1.98218552e+09, 1.98218652e+09, 1.98218752e+09, + 1.98218852e+09, 1.98218952e+09, 1.98219052e+09, 1.98219152e+09, + 1.98219352e+09, 1.98219452e+09, 1.98219552e+09, 1.98219652e+09, + 1.98219752e+09, 1.98219852e+09, 1.98219952e+09, 1.98220052e+09, + 1.98220152e+09, 1.98220252e+09, 1.98220352e+09, 1.98220452e+09, + 1.98220552e+09, 1.98220652e+09, 1.98220752e+09, 1.98220852e+09, + 1.98220952e+09, 1.98221052e+09, 1.98221152e+09, 1.98221252e+09, + 1.98222752e+09, 1.98222852e+09, 1.98222952e+09, 1.98223052e+09, + 1.98223152e+09, 1.98223252e+09, 1.98223352e+09, 1.98223452e+09, + 1.98223552e+09, 1.98223652e+09, 1.98223752e+09, 1.98223852e+09, + 1.98223952e+09, 1.98224052e+09, 1.98224152e+09, 1.98224252e+09, + 1.98224352e+09, 1.98224452e+09, 1.98224552e+09, 1.98224652e+09, + 1.98224752e+09] + y = [2.97600000e+03, 3.18200000e+03, 3.74900000e+03, 4.53500000e+03, + 5.43300000e+03, 6.38000000e+03, 7.34000000e+03, 8.29200000e+03, + 9.21900000e+03, 1.01120000e+04, 1.09620000e+04, 1.17600000e+04, + 1.25010000e+04, 1.31790000e+04, 1.37900000e+04, 1.43290000e+04, + 1.47940000e+04, 1.51800000e+04, 1.54870000e+04, 1.57110000e+04, + 5.74200000e+03, 4.82300000e+03, 3.99100000e+03, 3.33600000e+03, + 2.99600000e+03, 3.08400000e+03, 3.56700000e+03, 4.30700000e+03, + 5.18200000e+03, 6.11900000e+03, 7.07900000e+03, 8.03400000e+03, + 8.97000000e+03, 9.87300000e+03, 1.07350000e+04, 1.15480000e+04, + 1.23050000e+04, 1.30010000e+04, 1.36300000e+04, 1.41890000e+04, + 6.00000000e+03, 5.06800000e+03, 4.20500000e+03, 3.49000000e+03, + 3.04900000e+03, 3.01600000e+03, 3.40400000e+03, 4.08800000e+03, + 4.93500000e+03, 5.86000000e+03, 6.81700000e+03, 7.77500000e+03, + 8.71800000e+03, 9.63100000e+03, 1.05050000e+04, 1.13320000e+04, + 1.21050000e+04, 1.28170000e+04, 1.34660000e+04, 1.40440000e+04, + 1.32730000e+04, 1.26040000e+04, 1.18720000e+04, 1.10820000e+04, + 1.02400000e+04, 9.35300000e+03, 8.43000000e+03, 7.48100000e+03, + 6.52100000e+03, 5.57000000e+03, 4.66200000e+03, 3.85400000e+03, + 3.24600000e+03, 2.97900000e+03, 3.14700000e+03, 3.68800000e+03, + 4.45900000e+03, 5.35000000e+03, 6.29400000e+03, 7.25400000e+03, + 9.13800000e+03, 1.00340000e+04, 1.08880000e+04, 1.16910000e+04, + 1.24370000e+04, 1.31210000e+04, 1.37380000e+04, 1.42840000e+04, + 1.47550000e+04, 1.51490000e+04, 1.54630000e+04, 1.56950000e+04, + 1.58430000e+04, 1.59070000e+04, 1.58860000e+04, 1.57800000e+04, + 1.55910000e+04, 1.53190000e+04, 1.49650000e+04, 1.45330000e+04, + 3.01000000e+03, 3.05900000e+03, 3.51200000e+03, 4.23400000e+03, + 5.10000000e+03, 6.03400000e+03, 6.99300000e+03, 7.95000000e+03, + 8.88800000e+03, 9.79400000e+03, 1.06600000e+04, 1.14770000e+04, + 1.22400000e+04, 1.29410000e+04, 1.35770000e+04, 1.41430000e+04, + 1.46350000e+04, 1.50500000e+04, 1.53850000e+04, 1.56400000e+04, + 1.58110000e+04] + + periods = np.linspace(400, 120, 1000) + angular_freq = 2 * np.pi / periods + + lombscargle(t, y, angular_freq, precenter=True, normalize=True) + + def test_zero_freq(self): + # Verify that function works when freqs includes 0 + # The value at f=0 will depend on the seed + + # Input parameters + ampl = 2. + w = 1. + phi = 0.12 + nin = 100 + nout = 1001 + p = 0.7 # Fraction of points to select + offset = 0 + + # Randomly select a fraction of an array with timesteps + rng = np.random.RandomState(2353425) + r = rng.rand(nin) + t = np.linspace(0.01*np.pi, 10.*np.pi, nin)[r >= p] + + # Plot a sine wave for the selected times + y = ampl * np.cos(w*t + phi) + offset + + # Define the array of frequencies for which to compute the periodogram + f = np.linspace(0, 10., nout) + + # Calculate Lomb-Scargle periodogram + pgram = lombscargle(t, y, f, normalize=True, floating_mean=True) + + # exact value will change based on seed + # testing to make sure it is very small + assert(pgram[0] < 1e-4) + + def test_simple_div_zero(self): + # these are bare-minimum examples that would, without the eps adjustments, + # cause division-by-zero errors + + # first, test with example that will cause first SS sum to be 0.0 + t = [t + 1 for t in range(0, 32)] + y = np.ones(len(t)) + freqs = [2.0*np.pi] * 2 # must have 2+ elements + lombscargle(t, y, freqs) + + # second, test with example that will cause first CC sum to be 0.0 + t = [t*4 + 1 for t in range(0, 32)] + y = np.ones(len(t)) + freqs = [np.pi/2.0] * 2 # must have 2+ elements + + lombscargle(t, y, freqs) + + +class TestSTFT: + @pytest.mark.thread_unsafe + def test_input_validation(self): + + def chk_VE(match): + """Assert for a ValueError matching regexp `match`. + + This little wrapper allows a more concise code layout. + """ + return pytest.raises(ValueError, match=match) + + # Checks for check_COLA(): + with chk_VE('nperseg must be a positive integer'): + check_COLA('hann', -10, 0) + with chk_VE('noverlap must be less than nperseg.'): + check_COLA('hann', 10, 20) + with chk_VE('window must be 1-D'): + check_COLA(np.ones((2, 2)), 10, 0) + with chk_VE('window must have length of nperseg'): + check_COLA(np.ones(20), 10, 0) + + # Checks for check_NOLA(): + with chk_VE('nperseg must be a positive integer'): + check_NOLA('hann', -10, 0) + with chk_VE('noverlap must be less than nperseg'): + check_NOLA('hann', 10, 20) + with chk_VE('window must be 1-D'): + check_NOLA(np.ones((2, 2)), 10, 0) + with chk_VE('window must have length of nperseg'): + check_NOLA(np.ones(20), 10, 0) + with chk_VE('noverlap must be a nonnegative integer'): + check_NOLA('hann', 64, -32) + + x = np.zeros(1024) + z = stft(x)[2] + + # Checks for stft(): + with chk_VE('window must be 1-D'): + stft(x, window=np.ones((2, 2))) + with chk_VE('value specified for nperseg is different ' + + 'from length of window'): + stft(x, window=np.ones(10), nperseg=256) + with chk_VE('nperseg must be a positive integer'): + stft(x, nperseg=-256) + with chk_VE('noverlap must be less than nperseg.'): + stft(x, nperseg=256, noverlap=1024) + with chk_VE('nfft must be greater than or equal to nperseg.'): + stft(x, nperseg=256, nfft=8) + + # Checks for istft(): + with chk_VE('Input stft must be at least 2d!'): + istft(x) + with chk_VE('window must be 1-D'): + istft(z, window=np.ones((2, 2))) + with chk_VE('window must have length of 256'): + istft(z, window=np.ones(10), nperseg=256) + with chk_VE('nperseg must be a positive integer'): + istft(z, nperseg=-256) + with chk_VE('noverlap must be less than nperseg.'): + istft(z, nperseg=256, noverlap=1024) + with chk_VE('nfft must be greater than or equal to nperseg.'): + istft(z, nperseg=256, nfft=8) + with pytest.warns(UserWarning, match="NOLA condition failed, " + + "STFT may not be invertible"): + istft(z, nperseg=256, noverlap=0, window='hann') + with chk_VE('Must specify differing time and frequency axes!'): + istft(z, time_axis=0, freq_axis=0) + + # Checks for _spectral_helper(): + with chk_VE("Unknown value for mode foo, must be one of: " + + r"\{'psd', 'stft'\}"): + _spectral_helper(x, x, mode='foo') + with chk_VE("x and y must be equal if mode is 'stft'"): + _spectral_helper(x[:512], x[512:], mode='stft') + with chk_VE("Unknown boundary option 'foo', must be one of: " + + r"\['even', 'odd', 'constant', 'zeros', None\]"): + _spectral_helper(x, x, boundary='foo') + + scaling = "not_valid" + with chk_VE(fr"Parameter {scaling=} not in \['spectrum', 'psd'\]!"): + stft(x, scaling=scaling) + with chk_VE(fr"Parameter {scaling=} not in \['spectrum', 'psd'\]!"): + istft(z, scaling=scaling) + + def test_check_COLA(self): + settings = [ + ('boxcar', 10, 0), + ('boxcar', 10, 9), + ('bartlett', 51, 26), + ('hann', 256, 128), + ('hann', 256, 192), + ('blackman', 300, 200), + (('tukey', 0.5), 256, 64), + ('hann', 256, 255), + ] + + for setting in settings: + msg = '{}, {}, {}'.format(*setting) + assert_equal(True, check_COLA(*setting), err_msg=msg) + + def test_check_NOLA(self): + settings_pass = [ + ('boxcar', 10, 0), + ('boxcar', 10, 9), + ('boxcar', 10, 7), + ('bartlett', 51, 26), + ('bartlett', 51, 10), + ('hann', 256, 128), + ('hann', 256, 192), + ('hann', 256, 37), + ('blackman', 300, 200), + ('blackman', 300, 123), + (('tukey', 0.5), 256, 64), + (('tukey', 0.5), 256, 38), + ('hann', 256, 255), + ('hann', 256, 39), + ] + for setting in settings_pass: + msg = '{}, {}, {}'.format(*setting) + assert_equal(True, check_NOLA(*setting), err_msg=msg) + + w_fail = np.ones(16) + w_fail[::2] = 0 + settings_fail = [ + (w_fail, len(w_fail), len(w_fail) // 2), + ('hann', 64, 0), + ] + for setting in settings_fail: + msg = '{}, {}, {}'.format(*setting) + assert_equal(False, check_NOLA(*setting), err_msg=msg) + + def test_average_all_segments(self): + rng = np.random.RandomState(1234) + x = rng.randn(1024) + + fs = 1.0 + window = 'hann' + nperseg = 16 + noverlap = 8 + + # Compare twosided, because onesided welch doubles non-DC terms to + # account for power at negative frequencies. stft doesn't do this, + # because it breaks invertibility. + f, _, Z = stft(x, fs, window, nperseg, noverlap, padded=False, + return_onesided=False, boundary=None) + fw, Pw = welch(x, fs, window, nperseg, noverlap, return_onesided=False, + scaling='spectrum', detrend=False) + + assert_allclose(f, fw) + assert_allclose(np.mean(np.abs(Z)**2, axis=-1), Pw) + + def test_permute_axes(self): + rng = np.random.RandomState(1234) + x = rng.randn(1024) + + fs = 1.0 + window = 'hann' + nperseg = 16 + noverlap = 8 + + f1, t1, Z1 = stft(x, fs, window, nperseg, noverlap) + f2, t2, Z2 = stft(x.reshape((-1, 1, 1)), fs, window, nperseg, noverlap, + axis=0) + + t3, x1 = istft(Z1, fs, window, nperseg, noverlap) + t4, x2 = istft(Z2.T, fs, window, nperseg, noverlap, time_axis=0, + freq_axis=-1) + + assert_allclose(f1, f2) + assert_allclose(t1, t2) + assert_allclose(t3, t4) + assert_allclose(Z1, Z2[:, 0, 0, :]) + assert_allclose(x1, x2[:, 0, 0]) + + @pytest.mark.parametrize('scaling', ['spectrum', 'psd']) + def test_roundtrip_real(self, scaling): + rng = np.random.RandomState(1234) + + settings = [ + ('boxcar', 100, 10, 0), # Test no overlap + ('boxcar', 100, 10, 9), # Test high overlap + ('bartlett', 101, 51, 26), # Test odd nperseg + ('hann', 1024, 256, 128), # Test defaults + (('tukey', 0.5), 1152, 256, 64), # Test Tukey + ('hann', 1024, 256, 255), # Test overlapped hann + ] + + for window, N, nperseg, noverlap in settings: + t = np.arange(N) + x = 10*rng.randn(t.size) + + _, _, zz = stft(x, nperseg=nperseg, noverlap=noverlap, + window=window, detrend=None, padded=False, + scaling=scaling) + + tr, xr = istft(zz, nperseg=nperseg, noverlap=noverlap, + window=window, scaling=scaling) + + msg = f'{window}, {noverlap}' + assert_allclose(t, tr, err_msg=msg) + assert_allclose(x, xr, err_msg=msg) + + @pytest.mark.thread_unsafe + def test_roundtrip_not_nola(self): + rng = np.random.RandomState(1234) + + w_fail = np.ones(16) + w_fail[::2] = 0 + settings = [ + (w_fail, 256, len(w_fail), len(w_fail) // 2), + ('hann', 256, 64, 0), + ] + + for window, N, nperseg, noverlap in settings: + msg = f'{window}, {N}, {nperseg}, {noverlap}' + assert not check_NOLA(window, nperseg, noverlap), msg + + t = np.arange(N) + x = 10 * rng.randn(t.size) + + _, _, zz = stft(x, nperseg=nperseg, noverlap=noverlap, + window=window, detrend=None, padded=True, + boundary='zeros') + with pytest.warns(UserWarning, match='NOLA'): + tr, xr = istft(zz, nperseg=nperseg, noverlap=noverlap, + window=window, boundary=True) + + assert np.allclose(t, tr[:len(t)]), msg + assert not np.allclose(x, xr[:len(x)]), msg + + def test_roundtrip_nola_not_cola(self): + rng = np.random.RandomState(1234) + + settings = [ + ('boxcar', 100, 10, 3), # NOLA True, COLA False + ('bartlett', 101, 51, 37), # NOLA True, COLA False + ('hann', 1024, 256, 127), # NOLA True, COLA False + (('tukey', 0.5), 1152, 256, 14), # NOLA True, COLA False + ('hann', 1024, 256, 5), # NOLA True, COLA False + ] + + for window, N, nperseg, noverlap in settings: + msg = f'{window}, {nperseg}, {noverlap}' + assert check_NOLA(window, nperseg, noverlap), msg + assert not check_COLA(window, nperseg, noverlap), msg + + t = np.arange(N) + x = 10 * rng.randn(t.size) + + _, _, zz = stft(x, nperseg=nperseg, noverlap=noverlap, + window=window, detrend=None, padded=True, + boundary='zeros') + + tr, xr = istft(zz, nperseg=nperseg, noverlap=noverlap, + window=window, boundary=True) + + msg = f'{window}, {noverlap}' + assert_allclose(t, tr[:len(t)], err_msg=msg) + assert_allclose(x, xr[:len(x)], err_msg=msg) + + def test_roundtrip_float32(self): + rng = np.random.RandomState(1234) + + settings = [('hann', 1024, 256, 128)] + + for window, N, nperseg, noverlap in settings: + t = np.arange(N) + x = 10*rng.randn(t.size) + x = x.astype(np.float32) + + _, _, zz = stft(x, nperseg=nperseg, noverlap=noverlap, + window=window, detrend=None, padded=False) + + tr, xr = istft(zz, nperseg=nperseg, noverlap=noverlap, + window=window) + + msg = f'{window}, {noverlap}' + assert_allclose(t, t, err_msg=msg) + assert_allclose(x, xr, err_msg=msg, rtol=1e-4, atol=1e-5) + assert_(x.dtype == xr.dtype) + + @pytest.mark.thread_unsafe + @pytest.mark.parametrize('scaling', ['spectrum', 'psd']) + def test_roundtrip_complex(self, scaling): + rng = np.random.RandomState(1234) + + settings = [ + ('boxcar', 100, 10, 0), # Test no overlap + ('boxcar', 100, 10, 9), # Test high overlap + ('bartlett', 101, 51, 26), # Test odd nperseg + ('hann', 1024, 256, 128), # Test defaults + (('tukey', 0.5), 1152, 256, 64), # Test Tukey + ('hann', 1024, 256, 255), # Test overlapped hann + ] + + for window, N, nperseg, noverlap in settings: + t = np.arange(N) + x = 10*rng.randn(t.size) + 10j*rng.randn(t.size) + + _, _, zz = stft(x, nperseg=nperseg, noverlap=noverlap, + window=window, detrend=None, padded=False, + return_onesided=False, scaling=scaling) + + tr, xr = istft(zz, nperseg=nperseg, noverlap=noverlap, + window=window, input_onesided=False, + scaling=scaling) + + msg = f'{window}, {nperseg}, {noverlap}' + assert_allclose(t, tr, err_msg=msg) + assert_allclose(x, xr, err_msg=msg) + + # Check that asking for onesided switches to twosided + with suppress_warnings() as sup: + sup.filter(UserWarning, + "Input data is complex, switching to return_onesided=False") + _, _, zz = stft(x, nperseg=nperseg, noverlap=noverlap, + window=window, detrend=None, padded=False, + return_onesided=True, scaling=scaling) + + tr, xr = istft(zz, nperseg=nperseg, noverlap=noverlap, + window=window, input_onesided=False, scaling=scaling) + + msg = f'{window}, {nperseg}, {noverlap}' + assert_allclose(t, tr, err_msg=msg) + assert_allclose(x, xr, err_msg=msg) + + def test_roundtrip_boundary_extension(self): + rng = np.random.RandomState(1234) + + # Test against boxcar, since window is all ones, and thus can be fully + # recovered with no boundary extension + + settings = [ + ('boxcar', 100, 10, 0), # Test no overlap + ('boxcar', 100, 10, 9), # Test high overlap + ] + + for window, N, nperseg, noverlap in settings: + t = np.arange(N) + x = 10*rng.randn(t.size) + + _, _, zz = stft(x, nperseg=nperseg, noverlap=noverlap, + window=window, detrend=None, padded=True, + boundary=None) + + _, xr = istft(zz, noverlap=noverlap, window=window, boundary=False) + + for boundary in ['even', 'odd', 'constant', 'zeros']: + _, _, zz_ext = stft(x, nperseg=nperseg, noverlap=noverlap, + window=window, detrend=None, padded=True, + boundary=boundary) + + _, xr_ext = istft(zz_ext, noverlap=noverlap, window=window, + boundary=True) + + msg = f'{window}, {noverlap}, {boundary}' + assert_allclose(x, xr, err_msg=msg) + assert_allclose(x, xr_ext, err_msg=msg) + + def test_roundtrip_padded_signal(self): + rng = np.random.RandomState(1234) + + settings = [ + ('boxcar', 101, 10, 0), + ('hann', 1000, 256, 128), + ] + + for window, N, nperseg, noverlap in settings: + t = np.arange(N) + x = 10*rng.randn(t.size) + + _, _, zz = stft(x, nperseg=nperseg, noverlap=noverlap, + window=window, detrend=None, padded=True) + + tr, xr = istft(zz, noverlap=noverlap, window=window) + + msg = f'{window}, {noverlap}' + # Account for possible zero-padding at the end + assert_allclose(t, tr[:t.size], err_msg=msg) + assert_allclose(x, xr[:x.size], err_msg=msg) + + def test_roundtrip_padded_FFT(self): + rng = np.random.RandomState(1234) + + settings = [ + ('hann', 1024, 256, 128, 512), + ('hann', 1024, 256, 128, 501), + ('boxcar', 100, 10, 0, 33), + (('tukey', 0.5), 1152, 256, 64, 1024), + ] + + for window, N, nperseg, noverlap, nfft in settings: + t = np.arange(N) + x = 10*rng.randn(t.size) + xc = x*np.exp(1j*np.pi/4) + + # real signal + _, _, z = stft(x, nperseg=nperseg, noverlap=noverlap, nfft=nfft, + window=window, detrend=None, padded=True) + + # complex signal + _, _, zc = stft(xc, nperseg=nperseg, noverlap=noverlap, nfft=nfft, + window=window, detrend=None, padded=True, + return_onesided=False) + + tr, xr = istft(z, nperseg=nperseg, noverlap=noverlap, nfft=nfft, + window=window) + + tr, xcr = istft(zc, nperseg=nperseg, noverlap=noverlap, nfft=nfft, + window=window, input_onesided=False) + + msg = f'{window}, {noverlap}' + assert_allclose(t, tr, err_msg=msg) + assert_allclose(x, xr, err_msg=msg) + assert_allclose(xc, xcr, err_msg=msg) + + def test_axis_rolling(self): + rng = np.random.RandomState(1234) + + x_flat = rng.randn(1024) + _, _, z_flat = stft(x_flat) + + for a in range(3): + newshape = [1,]*3 + newshape[a] = -1 + x = x_flat.reshape(newshape) + + _, _, z_plus = stft(x, axis=a) # Positive axis index + _, _, z_minus = stft(x, axis=a-x.ndim) # Negative axis index + + assert_equal(z_flat, z_plus.squeeze(), err_msg=a) + assert_equal(z_flat, z_minus.squeeze(), err_msg=a-x.ndim) + + # z_flat has shape [n_freq, n_time] + + # Test vs. transpose + _, x_transpose_m = istft(z_flat.T, time_axis=-2, freq_axis=-1) + _, x_transpose_p = istft(z_flat.T, time_axis=0, freq_axis=1) + + assert_allclose(x_flat, x_transpose_m, err_msg='istft transpose minus') + assert_allclose(x_flat, x_transpose_p, err_msg='istft transpose plus') + + def test_roundtrip_scaling(self): + """Verify behavior of scaling parameter. """ + # Create 1024 sample cosine signal with amplitude 2: + X = np.zeros(513, dtype=complex) + X[256] = 1024 + x = np.fft.irfft(X) + power_x = sum(x**2) / len(x) # power of signal x is 2 + + # Calculate magnitude-scaled STFT: + Zs = stft(x, boundary='even', scaling='spectrum')[2] + + # Test round trip: + x1 = istft(Zs, boundary=True, scaling='spectrum')[1] + assert_allclose(x1, x) + + # For a Hann-windowed 256 sample length FFT, we expect a peak at + # frequency 64 (since it is 1/4 the length of X) with a height of 1 + # (half the amplitude). A Hann window of a perfectly centered sine has + # the magnitude [..., 0, 0, 0.5, 1, 0.5, 0, 0, ...]. + # Note that in this case the 'even' padding works for the beginning + # but not for the end of the STFT. + assert_allclose(abs(Zs[63, :-1]), 0.5) + assert_allclose(abs(Zs[64, :-1]), 1) + assert_allclose(abs(Zs[65, :-1]), 0.5) + # All other values should be zero: + Zs[63:66, :-1] = 0 + # Note since 'rtol' does not have influence here, atol needs to be set: + assert_allclose(Zs[:, :-1], 0, atol=np.finfo(Zs.dtype).resolution) + + # Calculate two-sided psd-scaled STFT: + # - using 'even' padding since signal is axis symmetric - this ensures + # stationary behavior on the boundaries + # - using the two-sided transform allows determining the spectral + # power by `sum(abs(Zp[:, k])**2) / len(f)` for the k-th time slot. + Zp = stft(x, return_onesided=False, boundary='even', scaling='psd')[2] + + # Calculate spectral power of Zd by summing over the frequency axis: + psd_Zp = np.sum(Zp.real**2 + Zp.imag**2, axis=0) / Zp.shape[0] + # Spectral power of Zp should be equal to the signal's power: + assert_allclose(psd_Zp, power_x) + + # Test round trip: + x1 = istft(Zp, input_onesided=False, boundary=True, scaling='psd')[1] + assert_allclose(x1, x) + + # The power of the one-sided psd-scaled STFT can be determined + # analogously (note that the two sides are not of equal shape): + Zp0 = stft(x, return_onesided=True, boundary='even', scaling='psd')[2] + + # Since x is real, its Fourier transform is conjugate symmetric, i.e., + # the missing 'second side' can be expressed through the 'first side': + Zp1 = np.conj(Zp0[-2:0:-1, :]) # 'second side' is conjugate reversed + assert_allclose(Zp[:129, :], Zp0) + assert_allclose(Zp[129:, :], Zp1) + + # Calculate the spectral power: + s2 = (np.sum(Zp0.real ** 2 + Zp0.imag ** 2, axis=0) + + np.sum(Zp1.real ** 2 + Zp1.imag ** 2, axis=0)) + psd_Zp01 = s2 / (Zp0.shape[0] + Zp1.shape[0]) + assert_allclose(psd_Zp01, power_x) + + # Test round trip: + x1 = istft(Zp0, input_onesided=True, boundary=True, scaling='psd')[1] + assert_allclose(x1, x) + + +class TestSampledSpectralRepresentations: + """Check energy/power relations from `Spectral Analysis` section in the user guide. + + A 32 sample cosine signal is used to compare the numerical to the expected results + stated in :ref:`tutorial_SpectralAnalysis` in + file ``doc/source/tutorial/signal.rst`` + """ + n: int = 32 #: number of samples + T: float = 1/16 #: sampling interval + a_ref: float = 3 #: amplitude of reference + l_a: int = 3 #: index in fft for defining frequency of test signal + + x_ref: np.ndarray #: reference signal + X_ref: np.ndarray #: two-sided FFT of x_ref + E_ref: float #: energy of signal + P_ref: float #: power of signal + + def setup_method(self): + """Create Cosine signal with amplitude a from spectrum. """ + f = rfftfreq(self.n, self.T) + X_ref = np.zeros_like(f) + self.l_a = 3 + X_ref[self.l_a] = self.a_ref/2 * self.n # set amplitude + self.x_ref = irfft(X_ref) + self.X_ref = fft(self.x_ref) + + # Closed form expression for continuous-time signal: + self.E_ref = self.tau * self.a_ref**2 / 2 # energy of signal + self.P_ref = self.a_ref**2 / 2 # power of signal + + @property + def tau(self) -> float: + """Duration of signal. """ + return self.n * self.T + + @property + def delta_f(self) -> float: + """Bin width """ + return 1 / (self.n * self.T) + + def test_reference_signal(self): + """Test energy and power formulas. """ + # Verify that amplitude is a: + assert_allclose(2*self.a_ref, np.ptp(self.x_ref), rtol=0.1) + # Verify that energy expression for sampled signal: + assert_allclose(self.T * sum(self.x_ref ** 2), self.E_ref) + + # Verify that spectral energy and power formulas are correct: + sum_X_ref_squared = sum(self.X_ref.real**2 + self.X_ref.imag**2) + assert_allclose(self.T/self.n * sum_X_ref_squared, self.E_ref) + assert_allclose(1/self.n**2 * sum_X_ref_squared, self.P_ref) + + def test_windowed_DFT(self): + """Verify spectral representations of windowed DFT. + + Furthermore, the scalings of `periodogram` and `welch` are verified. + """ + w = hann(self.n, sym=False) + c_amp, c_rms = abs(sum(w)), np.sqrt(sum(w.real**2 + w.imag**2)) + Xw = fft(self.x_ref*w) # unnormalized windowed DFT + + # Verify that the *spectrum* peak is consistent: + assert_allclose(self.tau * Xw[self.l_a] / c_amp, self.a_ref * self.tau / 2) + # Verify that the *amplitude spectrum* peak is consistent: + assert_allclose(Xw[self.l_a] / c_amp, self.a_ref/2) + + # Verify spectral power/energy equals signal's power/energy: + X_ESD = self.tau * self.T * abs(Xw / c_rms)**2 # Energy Spectral Density + X_PSD = self.T * abs(Xw / c_rms)**2 # Power Spectral Density + assert_allclose(self.delta_f * sum(X_ESD), self.E_ref) + assert_allclose(self.delta_f * sum(X_PSD), self.P_ref) + + # Verify scalings of periodogram: + kw = dict(fs=1/self.T, window=w, detrend=False, return_onesided=False) + _, P_mag = periodogram(self.x_ref, scaling='spectrum', **kw) + _, P_psd = periodogram(self.x_ref, scaling='density', **kw) + + # Verify that periodogram calculates a squared magnitude spectrum: + float_res = np.finfo(P_mag.dtype).resolution + assert_allclose(P_mag, abs(Xw/c_amp)**2, atol=float_res*max(P_mag)) + # Verify that periodogram calculates a PSD: + assert_allclose(P_psd, X_PSD, atol=float_res*max(P_psd)) + + # Ensure that scaling of welch is the same as of periodogram: + kw = dict(nperseg=len(self.x_ref), noverlap=0, **kw) + assert_allclose(welch(self.x_ref, scaling='spectrum', **kw)[1], P_mag, + atol=float_res*max(P_mag)) + assert_allclose(welch(self.x_ref, scaling='density', **kw)[1], P_psd, + atol=float_res*max(P_psd)) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_splines.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_splines.py new file mode 100644 index 0000000000000000000000000000000000000000..e1be4083436f457582c7d8229198fd63ff0f9584 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_splines.py @@ -0,0 +1,362 @@ +# pylint: disable=missing-docstring +import numpy as np +import pytest +from scipy._lib._array_api import xp_assert_close + +from scipy.signal._spline import ( + symiirorder1_ic, symiirorder2_ic_fwd, symiirorder2_ic_bwd) +from scipy.signal import symiirorder1, symiirorder2 + + +def _compute_symiirorder2_bwd_hs(k, cs, rsq, omega): + cssq = cs * cs + k = np.abs(k) + rsupk = np.power(rsq, k / 2.0) + + c0 = (cssq * (1.0 + rsq) / (1.0 - rsq) / + (1 - 2 * rsq * np.cos(2 * omega) + rsq * rsq)) + gamma = (1.0 - rsq) / (1.0 + rsq) / np.tan(omega) + return c0 * rsupk * (np.cos(omega * k) + gamma * np.sin(omega * k)) + + +class TestSymIIR: + @pytest.mark.parametrize( + 'dtype', [np.float32, np.float64, np.complex64, np.complex128]) + @pytest.mark.parametrize('precision', [-1.0, 0.7, 0.5, 0.25, 0.0075]) + def test_symiir1_ic(self, dtype, precision): + c_precision = precision + if precision <= 0.0 or precision > 1.0: + if dtype in {np.float32, np.complex64}: + c_precision = 1e-6 + else: + c_precision = 1e-11 + + # Symmetrical initial conditions for a IIR filter of order 1 are: + # x[0] + z1 * \sum{k = 0}^{n - 1} x[k] * z1^k + + # Check the initial condition for a low-pass filter + # with coefficient b = 0.85 on a step signal. The initial condition is + # a geometric series: 1 + b * \sum_{k = 0}^{n - 1} u[k] b^k. + + # Finding the initial condition corresponds to + # 1. Computing the index n such that b**n < precision, which + # corresponds to ceil(log(precision) / log(b)) + # 2. Computing the geometric series until n, this can be computed + # using the partial sum formula: (1 - b**n) / (1 - b) + # This holds due to the input being a step signal. + b = 0.85 + n_exp = int(np.ceil(np.log(c_precision) / np.log(b))) + expected = np.asarray([[(1 - b ** n_exp) / (1 - b)]], dtype=dtype) + expected = 1 + b * expected + + # Create a step signal of size n + 1 + x = np.ones(n_exp + 1, dtype=dtype) + xp_assert_close(symiirorder1_ic(x, b, precision), expected, + atol=2e-6, rtol=2e-7) + + # Check the conditions for a exponential decreasing signal with base 2. + # Same conditions hold, as the product of 0.5^n * 0.85^n is + # still a geometric series + b_d = np.asarray(b, dtype=dtype) + expected = np.asarray( + [[(1 - (0.5 * b_d) ** n_exp) / (1 - (0.5 * b_d))]], dtype=dtype) + expected = 1 + b_d * expected + + # Create an exponential decreasing signal of size n + 1 + x = 2 ** -np.arange(n_exp + 1, dtype=dtype) + xp_assert_close(symiirorder1_ic(x, b, precision), expected, + atol=2e-6, rtol=2e-7) + + def test_symiir1_ic_fails(self): + # Test that symiirorder1_ic fails whenever \sum_{n = 1}^{n} b^n > eps + b = 0.85 + # Create a step signal of size 100 + x = np.ones(100, dtype=np.float64) + + # Compute the closed form for the geometrical series + precision = 1 / (1 - b) + pytest.raises(ValueError, symiirorder1_ic, x, b, precision) + + # Test that symiirorder1_ic fails when |z1| >= 1 + pytest.raises(ValueError, symiirorder1_ic, x, 1.0, -1) + pytest.raises(ValueError, symiirorder1_ic, x, 2.0, -1) + + @pytest.mark.parametrize( + 'dtype', [np.float32, np.float64, np.complex64, np.complex128]) + @pytest.mark.parametrize('precision', [-1.0, 0.7, 0.5, 0.25, 0.0075]) + def test_symiir1(self, dtype, precision): + c_precision = precision + if precision <= 0.0 or precision > 1.0: + if dtype in {np.float32, np.complex64}: + c_precision = 1e-6 + else: + c_precision = 1e-11 + + # Test for a low-pass filter with c0 = 0.15 and z1 = 0.85 + # using an unit step over 200 samples. + c0 = 0.15 + z1 = 0.85 + n = 200 + signal = np.ones(n, dtype=dtype) + + # Find the initial condition. See test_symiir1_ic for a detailed + # explanation + n_exp = int(np.ceil(np.log(c_precision) / np.log(z1))) + initial = np.asarray((1 - z1 ** n_exp) / (1 - z1), dtype=dtype) + initial = 1 + z1 * initial + + # Forward pass + # The transfer function for the system 1 / (1 - z1 * z^-1) when + # applied to an unit step with initial conditions y0 is + # 1 / (1 - z1 * z^-1) * (z^-1 / (1 - z^-1) + y0) + + # Solving the inverse Z-transform for the given expression yields: + # y[n] = y0 * z1**n * u[n] + + # -z1 / (1 - z1) * z1**(k - 1) * u[k - 1] + + # 1 / (1 - z1) * u[k - 1] + # d is the Kronecker delta function, and u is the unit step + + # y0 * z1**n * u[n] + pos = np.arange(n, dtype=dtype) + comp1 = initial * z1**pos + + # -z1 / (1 - z1) * z1**(k - 1) * u[k - 1] + comp2 = np.zeros(n, dtype=dtype) + comp2[1:] = -z1 / (1 - z1) * z1**pos[:-1] + + # 1 / (1 - z1) * u[k - 1] + comp3 = np.zeros(n, dtype=dtype) + comp3[1:] = 1 / (1 - z1) + + expected_fwd = comp1 + comp2 + comp3 + + # Reverse condition + sym_cond = -c0 / (z1 - 1.0) * expected_fwd[-1] + + # Backward pass + # The transfer function for the forward result is equivalent to + # the forward system times c0 / (1 - z1 * z). + + # Computing a closed form for the complete expression is difficult + # The result will be computed iteratively from the difference equation + exp_out = np.zeros(n, dtype=dtype) + exp_out[0] = sym_cond + + for i in range(1, n): + exp_out[i] = c0 * expected_fwd[n - 1 - i] + z1 * exp_out[i - 1] + + exp_out = exp_out[::-1] + + out = symiirorder1(signal, c0, z1, precision) + xp_assert_close(out, exp_out, atol=4e-6, rtol=6e-7) + + @pytest.mark.parametrize('dtype', ['float32', 'float64']) + def test_symiir1_values(self, dtype): + rng = np.random.RandomState(1234) + dtype = getattr(np, dtype) + s = rng.uniform(size=16).astype(dtype) + res = symiirorder1(s, 0.5, 0.1) + + # values from scipy 1.9.1 + exp_res = np.array([0.14387447, 0.35166047, 0.29735238, 0.46295986, 0.45174927, + 0.19982875, 0.20355805, 0.47378628, 0.57232247, 0.51597393, + 0.25935107, 0.31438554, 0.41096728, 0.4190693 , 0.25812255, + 0.33671467], dtype=res.dtype) + assert res.dtype == dtype + atol = {np.float64: 1e-15, np.float32: 1e-7}[dtype] + xp_assert_close(res, exp_res, atol=atol) + + s = s + 1j*s + res = symiirorder1(s, 0.5, 0.1) + assert res.dtype == np.complex64 if dtype == np.float32 else np.complex128 + xp_assert_close(res, exp_res + 1j*exp_res, atol=atol) + + @pytest.mark.parametrize( + 'dtype', ['float32', 'float64']) + @pytest.mark.parametrize('precision', [-1.0, 0.7, 0.5, 0.25, 0.0075]) + def test_symiir2_initial_fwd(self, dtype, precision): + dtype = getattr(np, dtype) + c_precision = precision + if precision <= 0.0 or precision > 1.0: + if dtype in {np.float32, np.complex64}: + c_precision = 1e-6 + else: + c_precision = 1e-11 + + # Compute the initial conditions for a order-two symmetrical low-pass + # filter with r = 0.5 and omega = pi / 3 for an unit step input. + r = np.asarray(0.5, dtype=dtype) + omega = np.asarray(np.pi / 3.0, dtype=dtype) + cs = 1 - 2 * r * np.cos(omega) + r**2 + + # The index n for the initial condition is bound from 0 to the + # first position where sin(omega * (n + 2)) = 0 => omega * (n + 2) = pi + # For omega = pi / 3, the maximum initial condition occurs when + # sqrt(3) / 2 * r**n < precision. + # => n = log(2 * sqrt(3) / 3 * precision) / log(r) + ub = np.ceil(np.log(c_precision / np.sin(omega)) / np.log(c_precision)) + lb = np.ceil(np.pi / omega) - 2 + n_exp = min(ub, lb) + + # The forward initial condition for a filter of order two is: + # \frac{cs}{\sin(\omega)} \sum_{n = 0}^{N - 1} { + # r^(n + 1) \sin{\omega(n + 2)}} + cs + # The closed expression for this sum is: + # s[n] = 2 * r * np.cos(omega) - + # r**2 - r**(n + 2) * np.sin(omega * (n + 3)) / np.sin(omega) + + # r**(n + 3) * np.sin(omega * (n + 2)) / np.sin(omega) + cs + fwd_initial_1 = ( + cs + + 2 * r * np.cos(omega) - + r**2 - + r**(n_exp + 2) * np.sin(omega * (n_exp + 3)) / np.sin(omega) + + r**(n_exp + 3) * np.sin(omega * (n_exp + 2)) / np.sin(omega)) + + # The second initial condition is given by + # s[n] = 1 / np.sin(omega) * ( + # r**2 * np.sin(3 * omega) - + # r**3 * np.sin(2 * omega) - + # r**(n + 3) * np.sin(omega * (n + 4)) + + # r**(n + 4) * np.sin(omega * (n + 3))) + ub = np.ceil(np.log(c_precision / np.sin(omega)) / np.log(c_precision)) + lb = np.ceil(np.pi / omega) - 3 + n_exp = min(ub, lb) + + fwd_initial_2 = ( + cs + cs * 2 * r * np.cos(omega) + + (r**2 * np.sin(3 * omega) - + r**3 * np.sin(2 * omega) - + r**(n_exp + 3) * np.sin(omega * (n_exp + 4)) + + r**(n_exp + 4) * np.sin(omega * (n_exp + 3))) / np.sin(omega)) + + expected = np.r_[fwd_initial_1, fwd_initial_2][None, :] + expected = expected.astype(dtype) + + n = 100 + signal = np.ones(n, dtype=dtype) + + out = symiirorder2_ic_fwd(signal, r, omega, precision) + xp_assert_close(out, expected, atol=4e-6, rtol=6e-7) + + @pytest.mark.parametrize( + 'dtype', [np.float32, np.float64]) + @pytest.mark.parametrize('precision', [-1.0, 0.7, 0.5, 0.25, 0.0075]) + def test_symiir2_initial_bwd(self, dtype, precision): + c_precision = precision + if precision <= 0.0 or precision > 1.0: + if dtype in {np.float32, np.complex64}: + c_precision = 1e-6 + else: + c_precision = 1e-11 + + r = np.asarray(0.5, dtype=dtype) + omega = np.asarray(np.pi / 3.0, dtype=dtype) + cs = 1 - 2 * r * np.cos(omega) + r * r + a2 = 2 * r * np.cos(omega) + a3 = -r * r + + n = 100 + signal = np.ones(n, dtype=dtype) + + # Compute initial forward conditions + ic = symiirorder2_ic_fwd(signal, r, omega, precision) + out = np.zeros(n + 2, dtype=dtype) + out[:2] = ic[0] + + # Apply the forward system cs / (1 - a2 * z^-1 - a3 * z^-2)) + for i in range(2, n + 2): + out[i] = cs * signal[i - 2] + a2 * out[i - 1] + a3 * out[i - 2] + + # Find the backward initial conditions + ic2 = np.zeros(2, dtype=dtype) + idx = np.arange(n) + + diff = (_compute_symiirorder2_bwd_hs(idx, cs, r * r, omega) + + _compute_symiirorder2_bwd_hs(idx + 1, cs, r * r, omega)) + ic2_0_all = np.cumsum(diff * out[:1:-1]) + pos = np.where(diff ** 2 < c_precision)[0] + ic2[0] = ic2_0_all[pos[0]] + + diff = (_compute_symiirorder2_bwd_hs(idx - 1, cs, r * r, omega) + + _compute_symiirorder2_bwd_hs(idx + 2, cs, r * r, omega)) + ic2_1_all = np.cumsum(diff * out[:1:-1]) + pos = np.where(diff ** 2 < c_precision)[0] + ic2[1] = ic2_1_all[pos[0]] + + out_ic = symiirorder2_ic_bwd(out, r, omega, precision)[0] + xp_assert_close(out_ic, ic2, atol=4e-6, rtol=6e-7) + + @pytest.mark.parametrize( + 'dtype', [np.float32, np.float64]) + @pytest.mark.parametrize('precision', [-1.0, 0.7, 0.5, 0.25, 0.0075]) + def test_symiir2(self, dtype, precision): + r = np.asarray(0.5, dtype=dtype) + omega = np.asarray(np.pi / 3.0, dtype=dtype) + cs = 1 - 2 * r * np.cos(omega) + r * r + a2 = 2 * r * np.cos(omega) + a3 = -r * r + + n = 100 + signal = np.ones(n, dtype=dtype) + + # Compute initial forward conditions + ic = symiirorder2_ic_fwd(signal, r, omega, precision) + out1 = np.zeros(n + 2, dtype=dtype) + out1[:2] = ic[0] + + # Apply the forward system cs / (1 - a2 * z^-1 - a3 * z^-2)) + for i in range(2, n + 2): + out1[i] = cs * signal[i - 2] + a2 * out1[i - 1] + a3 * out1[i - 2] + + # Find the backward initial conditions + ic2 = symiirorder2_ic_bwd(out1, r, omega, precision)[0] + + # Apply the system cs / (1 - a2 * z - a3 * z^2)) in backwards + exp = np.empty(n, dtype=dtype) + exp[-2:] = ic2[::-1] + + for i in range(n - 3, -1, -1): + exp[i] = cs * out1[i] + a2 * exp[i + 1] + a3 * exp[i + 2] + + out = symiirorder2(signal, r, omega, precision) + xp_assert_close(out, exp, atol=4e-6, rtol=6e-7) + + @pytest.mark.parametrize('dtyp', ['float32', 'float64']) + def test_symiir2_values(self, dtyp): + dtyp = getattr(np, dtyp) + rng = np.random.RandomState(1234) + s = rng.uniform(size=16).astype(dtyp) + res = symiirorder2(s, 0.1, 0.1, precision=1e-10) + + # values from scipy 1.9.1 + exp_res = np.array([0.26572609, 0.53408018, 0.51032696, 0.72115829, 0.69486885, + 0.3649055 , 0.37349478, 0.74165032, 0.89718521, 0.80582483, + 0.46758053, 0.51898709, 0.65025605, 0.65394321, 0.45273595, + 0.53539183], dtype=dtyp) + + assert res.dtype == dtyp + # The values in SciPy 1.14 agree with those in SciPy 1.9.1 to this + # accuracy only. Implementation differences are twofold: + # 1. boundary conditions are computed differently + # 2. the filter itself uses sosfilt instead of a hardcoded iteration + # The boundary conditions seem are tested separately (see + # test_symiir2_initial_{fwd,bwd} above, so the difference is likely + # due to a different way roundoff errors accumulate in the filter. + # In that respect, sosfilt is likely doing a better job. + xp_assert_close(res, exp_res, atol=2e-6) + + s = s + 1j*s + with pytest.raises(TypeError): + res = symiirorder2(s, 0.5, 0.1) + + def test_symiir1_integer_input(self): + s = np.where(np.arange(100) % 2, -1, 1) + expected = symiirorder1(s.astype(float), 0.5, 0.5) + out = symiirorder1(s, 0.5, 0.5) + xp_assert_close(out, expected) + + def test_symiir2_integer_input(self): + s = np.where(np.arange(100) % 2, -1, 1) + expected = symiirorder2(s.astype(float), 0.5, np.pi / 3.0) + out = symiirorder2(s, 0.5, np.pi / 3.0) + xp_assert_close(out, expected) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_upfirdn.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_upfirdn.py new file mode 100644 index 0000000000000000000000000000000000000000..0aaec38f06ba72a8bcd984d91b596e98eb3bbc54 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_upfirdn.py @@ -0,0 +1,288 @@ +# Code adapted from "upfirdn" python library with permission: +# +# Copyright (c) 2009, Motorola, Inc +# +# All Rights Reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# * Neither the name of Motorola nor the names of its contributors may be +# used to endorse or promote products derived from this software without +# specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +import numpy as np +from itertools import product + +from scipy._lib._array_api import xp_assert_close +from pytest import raises as assert_raises +import pytest + +from scipy.signal import upfirdn, firwin +from scipy.signal._upfirdn import _output_len, _upfirdn_modes +from scipy.signal._upfirdn_apply import _pad_test + + +def upfirdn_naive(x, h, up=1, down=1): + """Naive upfirdn processing in Python. + + Note: arg order (x, h) differs to facilitate apply_along_axis use. + """ + h = np.asarray(h) + out = np.zeros(len(x) * up, x.dtype) + out[::up] = x + out = np.convolve(h, out)[::down][:_output_len(len(h), len(x), up, down)] + return out + + +class UpFIRDnCase: + """Test _UpFIRDn object""" + def __init__(self, up, down, h, x_dtype): + self.up = up + self.down = down + self.h = np.atleast_1d(h) + self.x_dtype = x_dtype + self.rng = np.random.RandomState(17) + + def __call__(self): + # tiny signal + self.scrub(np.ones(1, self.x_dtype)) + # ones + self.scrub(np.ones(10, self.x_dtype)) # ones + # randn + x = self.rng.randn(10).astype(self.x_dtype) + if self.x_dtype in (np.complex64, np.complex128): + x += 1j * self.rng.randn(10) + self.scrub(x) + # ramp + self.scrub(np.arange(10).astype(self.x_dtype)) + # 3D, random + size = (2, 3, 5) + x = self.rng.randn(*size).astype(self.x_dtype) + if self.x_dtype in (np.complex64, np.complex128): + x += 1j * self.rng.randn(*size) + for axis in range(len(size)): + self.scrub(x, axis=axis) + x = x[:, ::2, 1::3].T + for axis in range(len(size)): + self.scrub(x, axis=axis) + + def scrub(self, x, axis=-1): + yr = np.apply_along_axis(upfirdn_naive, axis, x, + self.h, self.up, self.down) + want_len = _output_len(len(self.h), x.shape[axis], self.up, self.down) + assert yr.shape[axis] == want_len + y = upfirdn(self.h, x, self.up, self.down, axis=axis) + assert y.shape[axis] == want_len + assert y.shape == yr.shape + dtypes = (self.h.dtype, x.dtype) + if all(d == np.complex64 for d in dtypes): + assert y.dtype == np.complex64 + elif np.complex64 in dtypes and np.float32 in dtypes: + assert y.dtype == np.complex64 + elif all(d == np.float32 for d in dtypes): + assert y.dtype == np.float32 + elif np.complex128 in dtypes or np.complex64 in dtypes: + assert y.dtype == np.complex128 + else: + assert y.dtype == np.float64 + xp_assert_close(yr.astype(y.dtype), y) + + +_UPFIRDN_TYPES = (int, np.float32, np.complex64, float, complex) + + +class TestUpfirdn: + + def test_valid_input(self): + assert_raises(ValueError, upfirdn, [1], [1], 1, 0) # up or down < 1 + assert_raises(ValueError, upfirdn, [], [1], 1, 1) # h.ndim != 1 + assert_raises(ValueError, upfirdn, [[1]], [1], 1, 1) + + @pytest.mark.parametrize('len_h', [1, 2, 3, 4, 5]) + @pytest.mark.parametrize('len_x', [1, 2, 3, 4, 5]) + def test_singleton(self, len_h, len_x): + # gh-9844: lengths producing expected outputs + h = np.zeros(len_h) + h[len_h // 2] = 1. # make h a delta + x = np.ones(len_x) + y = upfirdn(h, x, 1, 1) + want = np.pad(x, (len_h // 2, (len_h - 1) // 2), 'constant') + xp_assert_close(y, want) + + def test_shift_x(self): + # gh-9844: shifted x can change values? + y = upfirdn([1, 1], [1.], 1, 1) + xp_assert_close(y, np.asarray([1.0, 1.0])) # was [0, 1] in the issue + y = upfirdn([1, 1], [0., 1.], 1, 1) + xp_assert_close(y, np.asarray([0.0, 1.0, 1.0])) + + # A bunch of lengths/factors chosen because they exposed differences + # between the "old way" and new way of computing length, and then + # got `expected` from MATLAB + @pytest.mark.parametrize('len_h, len_x, up, down, expected', [ + (2, 2, 5, 2, [1, 0, 0, 0]), + (2, 3, 6, 3, [1, 0, 1, 0, 1]), + (2, 4, 4, 3, [1, 0, 0, 0, 1]), + (3, 2, 6, 2, [1, 0, 0, 1, 0]), + (4, 11, 3, 5, [1, 0, 0, 1, 0, 0, 1]), + ]) + def test_length_factors(self, len_h, len_x, up, down, expected): + # gh-9844: weird factors + h = np.zeros(len_h) + h[0] = 1. + x = np.ones(len_x) + y = upfirdn(h, x, up, down) + expected = np.asarray(expected, dtype=np.float64) + xp_assert_close(y, expected) + + @pytest.mark.parametrize('down, want_len', [ # lengths from MATLAB + (2, 5015), + (11, 912), + (79, 127), + ]) + def test_vs_convolve(self, down, want_len): + # Check that up=1.0 gives same answer as convolve + slicing + random_state = np.random.RandomState(17) + try_types = (int, np.float32, np.complex64, float, complex) + size = 10000 + + for dtype in try_types: + x = random_state.randn(size).astype(dtype) + if dtype in (np.complex64, np.complex128): + x += 1j * random_state.randn(size) + + h = firwin(31, 1. / down, window='hamming') + yl = upfirdn_naive(x, h, 1, down) + y = upfirdn(h, x, up=1, down=down) + assert y.shape == (want_len,) + assert yl.shape[0] == y.shape[0] + xp_assert_close(yl, y, atol=1e-7, rtol=1e-7) + + @pytest.mark.parametrize('x_dtype', _UPFIRDN_TYPES) + @pytest.mark.parametrize('h', (1., 1j)) + @pytest.mark.parametrize('up, down', [(1, 1), (2, 2), (3, 2), (2, 3)]) + def test_vs_naive_delta(self, x_dtype, h, up, down): + UpFIRDnCase(up, down, h, x_dtype)() + + @pytest.mark.parametrize('x_dtype', _UPFIRDN_TYPES) + @pytest.mark.parametrize('h_dtype', _UPFIRDN_TYPES) + @pytest.mark.parametrize('p_max, q_max', + list(product((10, 100), (10, 100)))) + def test_vs_naive(self, x_dtype, h_dtype, p_max, q_max): + tests = self._random_factors(p_max, q_max, h_dtype, x_dtype) + for test in tests: + test() + + def _random_factors(self, p_max, q_max, h_dtype, x_dtype): + n_rep = 3 + longest_h = 25 + random_state = np.random.RandomState(17) + tests = [] + + for _ in range(n_rep): + # Randomize the up/down factors somewhat + p_add = q_max if p_max > q_max else 1 + q_add = p_max if q_max > p_max else 1 + p = random_state.randint(p_max) + p_add + q = random_state.randint(q_max) + q_add + + # Generate random FIR coefficients + len_h = random_state.randint(longest_h) + 1 + h = np.atleast_1d(random_state.randint(len_h)) + h = h.astype(h_dtype) + if h_dtype is complex: + h += 1j * random_state.randint(len_h) + + tests.append(UpFIRDnCase(p, q, h, x_dtype)) + + return tests + + @pytest.mark.parametrize('mode', _upfirdn_modes) + def test_extensions(self, mode): + """Test vs. manually computed results for modes not in numpy's pad.""" + x = np.array([1, 2, 3, 1], dtype=float) + npre, npost = 6, 6 + y = _pad_test(x, npre=npre, npost=npost, mode=mode) + if mode == 'antisymmetric': + y_expected = np.asarray( + [3.0, 1, -1, -3, -2, -1, 1, 2, 3, 1, -1, -3, -2, -1, 1, 2]) + elif mode == 'antireflect': + y_expected = np.asarray( + [1.0, 2, 3, 1, -1, 0, 1, 2, 3, 1, -1, 0, 1, 2, 3, 1]) + elif mode == 'smooth': + y_expected = np.asarray( + [-5.0, -4, -3, -2, -1, 0, 1, 2, 3, 1, -1, -3, -5, -7, -9, -11]) + elif mode == "line": + lin_slope = (x[-1] - x[0]) / (len(x) - 1) + left = x[0] + np.arange(-npre, 0, 1) * lin_slope + right = x[-1] + np.arange(1, npost + 1) * lin_slope + y_expected = np.concatenate((left, x, right)) + else: + y_expected = np.pad(x, (npre, npost), mode=mode) + xp_assert_close(y, y_expected) + + @pytest.mark.parametrize( + 'size, h_len, mode, dtype', + product( + [8], + [4, 5, 26], # include cases with h_len > 2*size + _upfirdn_modes, + [np.float32, np.float64, np.complex64, np.complex128], + ) + ) + def test_modes(self, size, h_len, mode, dtype): + random_state = np.random.RandomState(5) + x = random_state.randn(size).astype(dtype) + if dtype in (np.complex64, np.complex128): + x += 1j * random_state.randn(size) + h = np.arange(1, 1 + h_len, dtype=x.real.dtype) + + y = upfirdn(h, x, up=1, down=1, mode=mode) + # expected result: pad the input, filter with zero padding, then crop + npad = h_len - 1 + if mode in ['antisymmetric', 'antireflect', 'smooth', 'line']: + # use _pad_test test function for modes not supported by np.pad. + xpad = _pad_test(x, npre=npad, npost=npad, mode=mode) + else: + xpad = np.pad(x, npad, mode=mode) + ypad = upfirdn(h, xpad, up=1, down=1, mode='constant') + y_expected = ypad[npad:-npad] + + atol = rtol = np.finfo(dtype).eps * 1e2 + xp_assert_close(y, y_expected, atol=atol, rtol=rtol) + + +def test_output_len_long_input(): + # Regression test for gh-17375. On Windows, a large enough input + # that should have been well within the capabilities of 64 bit integers + # would result in a 32 bit overflow because of a bug in Cython 0.29.32. + len_h = 1001 + in_len = 10**8 + up = 320 + down = 441 + out_len = _output_len(len_h, in_len, up, down) + # The expected value was computed "by hand" from the formula + # (((in_len - 1) * up + len_h) - 1) // down + 1 + assert out_len == 72562360 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_waveforms.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_waveforms.py new file mode 100644 index 0000000000000000000000000000000000000000..b30f7b9ceba80822f05ecfcabaad76fb87d5f335 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_waveforms.py @@ -0,0 +1,380 @@ +import numpy as np +from pytest import raises as assert_raises +from scipy._lib._array_api import ( + assert_almost_equal, xp_assert_equal, xp_assert_close +) + +import scipy.signal._waveforms as waveforms + + +# These chirp_* functions are the instantaneous frequencies of the signals +# returned by chirp(). + +def chirp_linear(t, f0, f1, t1): + f = f0 + (f1 - f0) * t / t1 + return f + + +def chirp_quadratic(t, f0, f1, t1, vertex_zero=True): + if vertex_zero: + f = f0 + (f1 - f0) * t**2 / t1**2 + else: + f = f1 - (f1 - f0) * (t1 - t)**2 / t1**2 + return f + + +def chirp_geometric(t, f0, f1, t1): + f = f0 * (f1/f0)**(t/t1) + return f + + +def chirp_hyperbolic(t, f0, f1, t1): + f = f0*f1*t1 / ((f0 - f1)*t + f1*t1) + return f + + +def compute_frequency(t, theta): + """ + Compute theta'(t)/(2*pi), where theta'(t) is the derivative of theta(t). + """ + # Assume theta and t are 1-D NumPy arrays. + # Assume that t is uniformly spaced. + dt = t[1] - t[0] + f = np.diff(theta)/(2*np.pi) / dt + tf = 0.5*(t[1:] + t[:-1]) + return tf, f + + +class TestChirp: + + def test_linear_at_zero(self): + w = waveforms.chirp(t=0, f0=1.0, f1=2.0, t1=1.0, method='linear') + assert_almost_equal(w, 1.0) + + def test_linear_freq_01(self): + method = 'linear' + f0 = 1.0 + f1 = 2.0 + t1 = 1.0 + t = np.linspace(0, t1, 100) + phase = waveforms._chirp_phase(t, f0, t1, f1, method) + tf, f = compute_frequency(t, phase) + abserr = np.max(np.abs(f - chirp_linear(tf, f0, f1, t1))) + assert abserr < 1e-6 + + def test_linear_freq_02(self): + method = 'linear' + f0 = 200.0 + f1 = 100.0 + t1 = 10.0 + t = np.linspace(0, t1, 100) + phase = waveforms._chirp_phase(t, f0, t1, f1, method) + tf, f = compute_frequency(t, phase) + abserr = np.max(np.abs(f - chirp_linear(tf, f0, f1, t1))) + assert abserr < 1e-6 + + def test_linear_complex_power(self): + method = 'linear' + f0 = 1.0 + f1 = 2.0 + t1 = 1.0 + t = np.linspace(0, t1, 100) + w_real = waveforms.chirp(t, f0, t1, f1, method, complex=False) + w_complex = waveforms.chirp(t, f0, t1, f1, method, complex=True) + w_pwr_r = np.var(w_real) + w_pwr_c = np.var(w_complex) + + # Making sure that power of the real part is not affected with + # complex conversion operation + err = w_pwr_r - np.real(w_pwr_c) + + assert(err < 1e-6) + + def test_linear_complex_at_zero(self): + w = waveforms.chirp(t=0, f0=-10.0, f1=1.0, t1=1.0, method='linear', + complex=True) + xp_assert_close(w, 1.0+0.0j) # dtype must match + + def test_quadratic_at_zero(self): + w = waveforms.chirp(t=0, f0=1.0, f1=2.0, t1=1.0, method='quadratic') + assert_almost_equal(w, 1.0) + + def test_quadratic_at_zero2(self): + w = waveforms.chirp(t=0, f0=1.0, f1=2.0, t1=1.0, method='quadratic', + vertex_zero=False) + assert_almost_equal(w, 1.0) + + def test_quadratic_complex_at_zero(self): + w = waveforms.chirp(t=0, f0=-1.0, f1=2.0, t1=1.0, method='quadratic', + complex=True) + xp_assert_close(w, 1.0+0j) + + def test_quadratic_freq_01(self): + method = 'quadratic' + f0 = 1.0 + f1 = 2.0 + t1 = 1.0 + t = np.linspace(0, t1, 2000) + phase = waveforms._chirp_phase(t, f0, t1, f1, method) + tf, f = compute_frequency(t, phase) + abserr = np.max(np.abs(f - chirp_quadratic(tf, f0, f1, t1))) + assert abserr < 1e-6 + + def test_quadratic_freq_02(self): + method = 'quadratic' + f0 = 20.0 + f1 = 10.0 + t1 = 10.0 + t = np.linspace(0, t1, 2000) + phase = waveforms._chirp_phase(t, f0, t1, f1, method) + tf, f = compute_frequency(t, phase) + abserr = np.max(np.abs(f - chirp_quadratic(tf, f0, f1, t1))) + assert abserr < 1e-6 + + def test_logarithmic_at_zero(self): + w = waveforms.chirp(t=0, f0=1.0, f1=2.0, t1=1.0, method='logarithmic') + assert_almost_equal(w, 1.0) + + def test_logarithmic_freq_01(self): + method = 'logarithmic' + f0 = 1.0 + f1 = 2.0 + t1 = 1.0 + t = np.linspace(0, t1, 10000) + phase = waveforms._chirp_phase(t, f0, t1, f1, method) + tf, f = compute_frequency(t, phase) + abserr = np.max(np.abs(f - chirp_geometric(tf, f0, f1, t1))) + assert abserr < 1e-6 + + def test_logarithmic_freq_02(self): + method = 'logarithmic' + f0 = 200.0 + f1 = 100.0 + t1 = 10.0 + t = np.linspace(0, t1, 10000) + phase = waveforms._chirp_phase(t, f0, t1, f1, method) + tf, f = compute_frequency(t, phase) + abserr = np.max(np.abs(f - chirp_geometric(tf, f0, f1, t1))) + assert abserr < 1e-6 + + def test_logarithmic_freq_03(self): + method = 'logarithmic' + f0 = 100.0 + f1 = 100.0 + t1 = 10.0 + t = np.linspace(0, t1, 10000) + phase = waveforms._chirp_phase(t, f0, t1, f1, method) + tf, f = compute_frequency(t, phase) + abserr = np.max(np.abs(f - chirp_geometric(tf, f0, f1, t1))) + assert abserr < 1e-6 + + def test_hyperbolic_at_zero(self): + w = waveforms.chirp(t=0, f0=10.0, f1=1.0, t1=1.0, method='hyperbolic') + assert_almost_equal(w, 1.0) + + def test_hyperbolic_freq_01(self): + method = 'hyperbolic' + t1 = 1.0 + t = np.linspace(0, t1, 10000) + # f0 f1 + cases = [[10.0, 1.0], + [1.0, 10.0], + [-10.0, -1.0], + [-1.0, -10.0]] + for f0, f1 in cases: + phase = waveforms._chirp_phase(t, f0, t1, f1, method) + tf, f = compute_frequency(t, phase) + expected = chirp_hyperbolic(tf, f0, f1, t1) + xp_assert_close(f, expected, atol=1e-7) + + def test_hyperbolic_zero_freq(self): + # f0=0 or f1=0 must raise a ValueError. + method = 'hyperbolic' + t1 = 1.0 + t = np.linspace(0, t1, 5) + assert_raises(ValueError, waveforms.chirp, t, 0, t1, 1, method) + assert_raises(ValueError, waveforms.chirp, t, 1, t1, 0, method) + + def test_unknown_method(self): + method = "foo" + f0 = 10.0 + f1 = 20.0 + t1 = 1.0 + t = np.linspace(0, t1, 10) + assert_raises(ValueError, waveforms.chirp, t, f0, t1, f1, method) + + def test_integer_t1(self): + f0 = 10.0 + f1 = 20.0 + t = np.linspace(-1, 1, 11) + t1 = 3.0 + float_result = waveforms.chirp(t, f0, t1, f1) + t1 = 3 + int_result = waveforms.chirp(t, f0, t1, f1) + err_msg = "Integer input 't1=3' gives wrong result" + xp_assert_equal(int_result, float_result, err_msg=err_msg) + + def test_integer_f0(self): + f1 = 20.0 + t1 = 3.0 + t = np.linspace(-1, 1, 11) + f0 = 10.0 + float_result = waveforms.chirp(t, f0, t1, f1) + f0 = 10 + int_result = waveforms.chirp(t, f0, t1, f1) + err_msg = "Integer input 'f0=10' gives wrong result" + xp_assert_equal(int_result, float_result, err_msg=err_msg) + + def test_integer_f1(self): + f0 = 10.0 + t1 = 3.0 + t = np.linspace(-1, 1, 11) + f1 = 20.0 + float_result = waveforms.chirp(t, f0, t1, f1) + f1 = 20 + int_result = waveforms.chirp(t, f0, t1, f1) + err_msg = "Integer input 'f1=20' gives wrong result" + xp_assert_equal(int_result, float_result, err_msg=err_msg) + + def test_integer_all(self): + f0 = 10 + t1 = 3 + f1 = 20 + t = np.linspace(-1, 1, 11) + float_result = waveforms.chirp(t, float(f0), float(t1), float(f1)) + int_result = waveforms.chirp(t, f0, t1, f1) + err_msg = "Integer input 'f0=10, t1=3, f1=20' gives wrong result" + xp_assert_equal(int_result, float_result, err_msg=err_msg) + + +class TestSweepPoly: + + def test_sweep_poly_quad1(self): + p = np.poly1d([1.0, 0.0, 1.0]) + t = np.linspace(0, 3.0, 10000) + phase = waveforms._sweep_poly_phase(t, p) + tf, f = compute_frequency(t, phase) + expected = p(tf) + abserr = np.max(np.abs(f - expected)) + assert abserr < 1e-6 + + def test_sweep_poly_const(self): + p = np.poly1d(2.0) + t = np.linspace(0, 3.0, 10000) + phase = waveforms._sweep_poly_phase(t, p) + tf, f = compute_frequency(t, phase) + expected = p(tf) + abserr = np.max(np.abs(f - expected)) + assert abserr < 1e-6 + + def test_sweep_poly_linear(self): + p = np.poly1d([-1.0, 10.0]) + t = np.linspace(0, 3.0, 10000) + phase = waveforms._sweep_poly_phase(t, p) + tf, f = compute_frequency(t, phase) + expected = p(tf) + abserr = np.max(np.abs(f - expected)) + assert abserr < 1e-6 + + def test_sweep_poly_quad2(self): + p = np.poly1d([1.0, 0.0, -2.0]) + t = np.linspace(0, 3.0, 10000) + phase = waveforms._sweep_poly_phase(t, p) + tf, f = compute_frequency(t, phase) + expected = p(tf) + abserr = np.max(np.abs(f - expected)) + assert abserr < 1e-6 + + def test_sweep_poly_cubic(self): + p = np.poly1d([2.0, 1.0, 0.0, -2.0]) + t = np.linspace(0, 2.0, 10000) + phase = waveforms._sweep_poly_phase(t, p) + tf, f = compute_frequency(t, phase) + expected = p(tf) + abserr = np.max(np.abs(f - expected)) + assert abserr < 1e-6 + + def test_sweep_poly_cubic2(self): + """Use an array of coefficients instead of a poly1d.""" + p = np.array([2.0, 1.0, 0.0, -2.0]) + t = np.linspace(0, 2.0, 10000) + phase = waveforms._sweep_poly_phase(t, p) + tf, f = compute_frequency(t, phase) + expected = np.poly1d(p)(tf) + abserr = np.max(np.abs(f - expected)) + assert abserr < 1e-6 + + def test_sweep_poly_cubic3(self): + """Use a list of coefficients instead of a poly1d.""" + p = [2.0, 1.0, 0.0, -2.0] + t = np.linspace(0, 2.0, 10000) + phase = waveforms._sweep_poly_phase(t, p) + tf, f = compute_frequency(t, phase) + expected = np.poly1d(p)(tf) + abserr = np.max(np.abs(f - expected)) + assert abserr < 1e-6 + + +class TestGaussPulse: + + def test_integer_fc(self): + float_result = waveforms.gausspulse('cutoff', fc=1000.0) + int_result = waveforms.gausspulse('cutoff', fc=1000) + err_msg = "Integer input 'fc=1000' gives wrong result" + xp_assert_equal(int_result, float_result, err_msg=err_msg) + + def test_integer_bw(self): + float_result = waveforms.gausspulse('cutoff', bw=1.0) + int_result = waveforms.gausspulse('cutoff', bw=1) + err_msg = "Integer input 'bw=1' gives wrong result" + xp_assert_equal(int_result, float_result, err_msg=err_msg) + + def test_integer_bwr(self): + float_result = waveforms.gausspulse('cutoff', bwr=-6.0) + int_result = waveforms.gausspulse('cutoff', bwr=-6) + err_msg = "Integer input 'bwr=-6' gives wrong result" + xp_assert_equal(int_result, float_result, err_msg=err_msg) + + def test_integer_tpr(self): + float_result = waveforms.gausspulse('cutoff', tpr=-60.0) + int_result = waveforms.gausspulse('cutoff', tpr=-60) + err_msg = "Integer input 'tpr=-60' gives wrong result" + xp_assert_equal(int_result, float_result, err_msg=err_msg) + + +class TestUnitImpulse: + + def test_no_index(self): + xp_assert_equal(waveforms.unit_impulse(7), + np.asarray([1.0, 0, 0, 0, 0, 0, 0])) + xp_assert_equal(waveforms.unit_impulse((3, 3)), + np.asarray([[1.0, 0, 0], [0, 0, 0], [0, 0, 0]])) + + def test_index(self): + xp_assert_equal(waveforms.unit_impulse(10, 3), + np.asarray([0.0, 0, 0, 1, 0, 0, 0, 0, 0, 0])) + xp_assert_equal(waveforms.unit_impulse((3, 3), (1, 1)), + np.asarray([[0.0, 0, 0], [0, 1, 0], [0, 0, 0]])) + + # Broadcasting + imp = waveforms.unit_impulse((4, 4), 2) + xp_assert_equal(imp, np.asarray([[0.0, 0, 0, 0], + [0.0, 0, 0, 0], + [0.0, 0, 1, 0], + [0.0, 0, 0, 0]])) + + def test_mid(self): + xp_assert_equal(waveforms.unit_impulse((3, 3), 'mid'), + np.asarray([[0.0, 0, 0], [0, 1, 0], [0, 0, 0]])) + xp_assert_equal(waveforms.unit_impulse(9, 'mid'), + np.asarray([0.0, 0, 0, 0, 1, 0, 0, 0, 0])) + + def test_dtype(self): + imp = waveforms.unit_impulse(7) + assert np.issubdtype(imp.dtype, np.floating) + + imp = waveforms.unit_impulse(5, 3, dtype=int) + assert np.issubdtype(imp.dtype, np.integer) + + imp = waveforms.unit_impulse((5, 2), (3, 1), dtype=complex) + assert np.issubdtype(imp.dtype, np.complexfloating) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_wavelets.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_wavelets.py new file mode 100644 index 0000000000000000000000000000000000000000..7a357d2eaf4a530930d612358b8ca69a18b5248e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_wavelets.py @@ -0,0 +1,59 @@ +import numpy as np +from numpy.testing import assert_array_equal, assert_array_almost_equal + +import scipy.signal._wavelets as wavelets + + +class TestWavelets: + def test_ricker(self): + w = wavelets._ricker(1.0, 1) + expected = 2 / (np.sqrt(3 * 1.0) * (np.pi ** 0.25)) + assert_array_equal(w, expected) + + lengths = [5, 11, 15, 51, 101] + for length in lengths: + w = wavelets._ricker(length, 1.0) + assert len(w) == length + max_loc = np.argmax(w) + assert max_loc == (length // 2) + + points = 100 + w = wavelets._ricker(points, 2.0) + half_vec = np.arange(0, points // 2) + # Wavelet should be symmetric + assert_array_almost_equal(w[half_vec], w[-(half_vec + 1)]) + + # Check zeros + aas = [5, 10, 15, 20, 30] + points = 99 + for a in aas: + w = wavelets._ricker(points, a) + vec = np.arange(0, points) - (points - 1.0) / 2 + exp_zero1 = np.argmin(np.abs(vec - a)) + exp_zero2 = np.argmin(np.abs(vec + a)) + assert_array_almost_equal(w[exp_zero1], 0) + assert_array_almost_equal(w[exp_zero2], 0) + + def test_cwt(self): + widths = [1.0] + def delta_wavelet(s, t): + return np.array([1]) + len_data = 100 + test_data = np.sin(np.pi * np.arange(0, len_data) / 10.0) + + # Test delta function input gives same data as output + cwt_dat = wavelets._cwt(test_data, delta_wavelet, widths) + assert cwt_dat.shape == (len(widths), len_data) + assert_array_almost_equal(test_data, cwt_dat.flatten()) + + # Check proper shape on output + widths = [1, 3, 4, 5, 10] + cwt_dat = wavelets._cwt(test_data, wavelets._ricker, widths) + assert cwt_dat.shape == (len(widths), len_data) + + widths = [len_data * 10] + # Note: this wavelet isn't defined quite right, but is fine for this test + def flat_wavelet(l, w): + return np.full(w, 1 / w) + cwt_dat = wavelets._cwt(test_data, flat_wavelet, widths) + assert_array_almost_equal(cwt_dat, np.mean(test_data)) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_windows.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_windows.py new file mode 100644 index 0000000000000000000000000000000000000000..75c4da5327f0c1a806f72865687927bc7a380c6d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/tests/test_windows.py @@ -0,0 +1,846 @@ +import numpy as np +from numpy import array +from numpy.testing import (assert_array_almost_equal, assert_array_equal, + assert_allclose, + assert_equal, assert_, assert_array_less, + suppress_warnings) +from pytest import raises as assert_raises + +from scipy.fft import fft +from scipy.signal import windows, get_window, resample + + +window_funcs = [ + ('boxcar', ()), + ('triang', ()), + ('parzen', ()), + ('bohman', ()), + ('blackman', ()), + ('nuttall', ()), + ('blackmanharris', ()), + ('flattop', ()), + ('bartlett', ()), + ('barthann', ()), + ('hamming', ()), + ('kaiser', (1,)), + ('dpss', (2,)), + ('gaussian', (0.5,)), + ('general_gaussian', (1.5, 2)), + ('chebwin', (1,)), + ('cosine', ()), + ('hann', ()), + ('exponential', ()), + ('taylor', ()), + ('tukey', (0.5,)), + ('lanczos', ()), + ] + + +class TestBartHann: + + def test_basic(self): + assert_allclose(windows.barthann(6, sym=True), + [0, 0.35857354213752, 0.8794264578624801, + 0.8794264578624801, 0.3585735421375199, 0], + rtol=1e-15, atol=1e-15) + assert_allclose(windows.barthann(7), + [0, 0.27, 0.73, 1.0, 0.73, 0.27, 0], + rtol=1e-15, atol=1e-15) + assert_allclose(windows.barthann(6, False), + [0, 0.27, 0.73, 1.0, 0.73, 0.27], + rtol=1e-15, atol=1e-15) + + +class TestBartlett: + + def test_basic(self): + assert_allclose(windows.bartlett(6), [0, 0.4, 0.8, 0.8, 0.4, 0]) + assert_allclose(windows.bartlett(7), [0, 1/3, 2/3, 1.0, 2/3, 1/3, 0]) + assert_allclose(windows.bartlett(6, False), + [0, 1/3, 2/3, 1.0, 2/3, 1/3]) + + +class TestBlackman: + + def test_basic(self): + assert_allclose(windows.blackman(6, sym=False), + [0, 0.13, 0.63, 1.0, 0.63, 0.13], atol=1e-14) + assert_allclose(windows.blackman(7, sym=False), + [0, 0.09045342435412804, 0.4591829575459636, + 0.9203636180999081, 0.9203636180999081, + 0.4591829575459636, 0.09045342435412804], atol=1e-8) + assert_allclose(windows.blackman(6), + [0, 0.2007701432625305, 0.8492298567374694, + 0.8492298567374694, 0.2007701432625305, 0], + atol=1e-14) + assert_allclose(windows.blackman(7, True), + [0, 0.13, 0.63, 1.0, 0.63, 0.13, 0], atol=1e-14) + + +class TestBlackmanHarris: + + def test_basic(self): + assert_allclose(windows.blackmanharris(6, False), + [6.0e-05, 0.055645, 0.520575, 1.0, 0.520575, 0.055645]) + assert_allclose(windows.blackmanharris(7, sym=False), + [6.0e-05, 0.03339172347815117, 0.332833504298565, + 0.8893697722232837, 0.8893697722232838, + 0.3328335042985652, 0.03339172347815122]) + assert_allclose(windows.blackmanharris(6), + [6.0e-05, 0.1030114893456638, 0.7938335106543362, + 0.7938335106543364, 0.1030114893456638, 6.0e-05]) + assert_allclose(windows.blackmanharris(7, sym=True), + [6.0e-05, 0.055645, 0.520575, 1.0, 0.520575, 0.055645, + 6.0e-05]) + + +class TestTaylor: + + def test_normalized(self): + """Tests windows of small length that are normalized to 1. See the + documentation for the Taylor window for more information on + normalization. + """ + assert_allclose(windows.taylor(1, 2, 15), 1.0) + assert_allclose( + windows.taylor(5, 2, 15), + np.array([0.75803341, 0.90757699, 1.0, 0.90757699, 0.75803341]) + ) + assert_allclose( + windows.taylor(6, 2, 15), + np.array([ + 0.7504082, 0.86624416, 0.98208011, 0.98208011, 0.86624416, + 0.7504082 + ]) + ) + + def test_non_normalized(self): + """Test windows of small length that are not normalized to 1. See + the documentation for the Taylor window for more information on + normalization. + """ + assert_allclose( + windows.taylor(5, 2, 15, norm=False), + np.array([ + 0.87508054, 1.04771499, 1.15440894, 1.04771499, 0.87508054 + ]) + ) + assert_allclose( + windows.taylor(6, 2, 15, norm=False), + np.array([ + 0.86627793, 1.0, 1.13372207, 1.13372207, 1.0, 0.86627793 + ]) + ) + + def test_correctness(self): + """This test ensures the correctness of the implemented Taylor + Windowing function. A Taylor Window of 1024 points is created, its FFT + is taken, and the Peak Sidelobe Level (PSLL) and 3dB and 18dB bandwidth + are found and checked. + + A publication from Sandia National Laboratories was used as reference + for the correctness values [1]_. + + References + ----- + .. [1] Armin Doerry, "Catalog of Window Taper Functions for + Sidelobe Control", 2017. + https://www.researchgate.net/profile/Armin_Doerry/publication/316281181_Catalog_of_Window_Taper_Functions_for_Sidelobe_Control/links/58f92cb2a6fdccb121c9d54d/Catalog-of-Window-Taper-Functions-for-Sidelobe-Control.pdf + """ + M_win = 1024 + N_fft = 131072 + # Set norm=False for correctness as the values obtained from the + # scientific publication do not normalize the values. Normalizing + # changes the sidelobe level from the desired value. + w = windows.taylor(M_win, nbar=4, sll=35, norm=False, sym=False) + f = fft(w, N_fft) + spec = 20 * np.log10(np.abs(f / np.amax(f))) + + first_zero = np.argmax(np.diff(spec) > 0) + + PSLL = np.amax(spec[first_zero:-first_zero]) + + BW_3dB = 2*np.argmax(spec <= -3.0102999566398121) / N_fft * M_win + BW_18dB = 2*np.argmax(spec <= -18.061799739838872) / N_fft * M_win + + assert_allclose(PSLL, -35.1672, atol=1) + assert_allclose(BW_3dB, 1.1822, atol=0.1) + assert_allclose(BW_18dB, 2.6112, atol=0.1) + + +class TestBohman: + + def test_basic(self): + assert_allclose(windows.bohman(6), + [0, 0.1791238937062839, 0.8343114522576858, + 0.8343114522576858, 0.1791238937062838, 0]) + assert_allclose(windows.bohman(7, sym=True), + [0, 0.1089977810442293, 0.6089977810442293, 1.0, + 0.6089977810442295, 0.1089977810442293, 0]) + assert_allclose(windows.bohman(6, False), + [0, 0.1089977810442293, 0.6089977810442293, 1.0, + 0.6089977810442295, 0.1089977810442293]) + + +class TestBoxcar: + + def test_basic(self): + assert_allclose(windows.boxcar(6), [1, 1, 1, 1, 1, 1]) + assert_allclose(windows.boxcar(7), [1, 1, 1, 1, 1, 1, 1]) + assert_allclose(windows.boxcar(6, False), [1, 1, 1, 1, 1, 1]) + + +cheb_odd_true = array([0.200938, 0.107729, 0.134941, 0.165348, + 0.198891, 0.235450, 0.274846, 0.316836, + 0.361119, 0.407338, 0.455079, 0.503883, + 0.553248, 0.602637, 0.651489, 0.699227, + 0.745266, 0.789028, 0.829947, 0.867485, + 0.901138, 0.930448, 0.955010, 0.974482, + 0.988591, 0.997138, 1.000000, 0.997138, + 0.988591, 0.974482, 0.955010, 0.930448, + 0.901138, 0.867485, 0.829947, 0.789028, + 0.745266, 0.699227, 0.651489, 0.602637, + 0.553248, 0.503883, 0.455079, 0.407338, + 0.361119, 0.316836, 0.274846, 0.235450, + 0.198891, 0.165348, 0.134941, 0.107729, + 0.200938]) + +cheb_even_true = array([0.203894, 0.107279, 0.133904, + 0.163608, 0.196338, 0.231986, + 0.270385, 0.311313, 0.354493, + 0.399594, 0.446233, 0.493983, + 0.542378, 0.590916, 0.639071, + 0.686302, 0.732055, 0.775783, + 0.816944, 0.855021, 0.889525, + 0.920006, 0.946060, 0.967339, + 0.983557, 0.994494, 1.000000, + 1.000000, 0.994494, 0.983557, + 0.967339, 0.946060, 0.920006, + 0.889525, 0.855021, 0.816944, + 0.775783, 0.732055, 0.686302, + 0.639071, 0.590916, 0.542378, + 0.493983, 0.446233, 0.399594, + 0.354493, 0.311313, 0.270385, + 0.231986, 0.196338, 0.163608, + 0.133904, 0.107279, 0.203894]) + + +class TestChebWin: + + def test_basic(self): + with suppress_warnings() as sup: + sup.filter(UserWarning, "This window is not suitable") + assert_allclose(windows.chebwin(6, 100), + [0.1046401879356917, 0.5075781475823447, 1.0, 1.0, + 0.5075781475823447, 0.1046401879356917]) + assert_allclose(windows.chebwin(7, 100), + [0.05650405062850233, 0.316608530648474, + 0.7601208123539079, 1.0, 0.7601208123539079, + 0.316608530648474, 0.05650405062850233]) + assert_allclose(windows.chebwin(6, 10), + [1.0, 0.6071201674458373, 0.6808391469897297, + 0.6808391469897297, 0.6071201674458373, 1.0]) + assert_allclose(windows.chebwin(7, 10), + [1.0, 0.5190521247588651, 0.5864059018130382, + 0.6101519801307441, 0.5864059018130382, + 0.5190521247588651, 1.0]) + assert_allclose(windows.chebwin(6, 10, False), + [1.0, 0.5190521247588651, 0.5864059018130382, + 0.6101519801307441, 0.5864059018130382, + 0.5190521247588651]) + + def test_cheb_odd_high_attenuation(self): + with suppress_warnings() as sup: + sup.filter(UserWarning, "This window is not suitable") + cheb_odd = windows.chebwin(53, at=-40) + assert_array_almost_equal(cheb_odd, cheb_odd_true, decimal=4) + + def test_cheb_even_high_attenuation(self): + with suppress_warnings() as sup: + sup.filter(UserWarning, "This window is not suitable") + cheb_even = windows.chebwin(54, at=40) + assert_array_almost_equal(cheb_even, cheb_even_true, decimal=4) + + def test_cheb_odd_low_attenuation(self): + cheb_odd_low_at_true = array([1.000000, 0.519052, 0.586405, + 0.610151, 0.586405, 0.519052, + 1.000000]) + with suppress_warnings() as sup: + sup.filter(UserWarning, "This window is not suitable") + cheb_odd = windows.chebwin(7, at=10) + assert_array_almost_equal(cheb_odd, cheb_odd_low_at_true, decimal=4) + + def test_cheb_even_low_attenuation(self): + cheb_even_low_at_true = array([1.000000, 0.451924, 0.51027, + 0.541338, 0.541338, 0.51027, + 0.451924, 1.000000]) + with suppress_warnings() as sup: + sup.filter(UserWarning, "This window is not suitable") + cheb_even = windows.chebwin(8, at=-10) + assert_array_almost_equal(cheb_even, cheb_even_low_at_true, decimal=4) + + +exponential_data = { + (4, None, 0.2, False): + array([4.53999297624848542e-05, + 6.73794699908546700e-03, 1.00000000000000000e+00, + 6.73794699908546700e-03]), + (4, None, 0.2, True): array([0.00055308437014783, 0.0820849986238988, + 0.0820849986238988, 0.00055308437014783]), + (4, None, 1.0, False): array([0.1353352832366127, 0.36787944117144233, 1., + 0.36787944117144233]), + (4, None, 1.0, True): array([0.22313016014842982, 0.60653065971263342, + 0.60653065971263342, 0.22313016014842982]), + (4, 2, 0.2, False): + array([4.53999297624848542e-05, 6.73794699908546700e-03, + 1.00000000000000000e+00, 6.73794699908546700e-03]), + (4, 2, 0.2, True): None, + (4, 2, 1.0, False): array([0.1353352832366127, 0.36787944117144233, 1., + 0.36787944117144233]), + (4, 2, 1.0, True): None, + (5, None, 0.2, True): + array([4.53999297624848542e-05, + 6.73794699908546700e-03, 1.00000000000000000e+00, + 6.73794699908546700e-03, 4.53999297624848542e-05]), + (5, None, 1.0, True): array([0.1353352832366127, 0.36787944117144233, 1., + 0.36787944117144233, 0.1353352832366127]), + (5, 2, 0.2, True): None, + (5, 2, 1.0, True): None +} + + +def test_exponential(): + for k, v in exponential_data.items(): + if v is None: + assert_raises(ValueError, windows.exponential, *k) + else: + win = windows.exponential(*k) + assert_allclose(win, v, rtol=1e-14) + + +class TestFlatTop: + + def test_basic(self): + assert_allclose(windows.flattop(6, sym=False), + [-0.000421051, -0.051263156, 0.19821053, 1.0, + 0.19821053, -0.051263156]) + assert_allclose(windows.flattop(7, sym=False), + [-0.000421051, -0.03684078115492348, + 0.01070371671615342, 0.7808739149387698, + 0.7808739149387698, 0.01070371671615342, + -0.03684078115492348]) + assert_allclose(windows.flattop(6), + [-0.000421051, -0.0677142520762119, 0.6068721525762117, + 0.6068721525762117, -0.0677142520762119, + -0.000421051]) + assert_allclose(windows.flattop(7, True), + [-0.000421051, -0.051263156, 0.19821053, 1.0, + 0.19821053, -0.051263156, -0.000421051]) + + +class TestGaussian: + + def test_basic(self): + assert_allclose(windows.gaussian(6, 1.0), + [0.04393693362340742, 0.3246524673583497, + 0.8824969025845955, 0.8824969025845955, + 0.3246524673583497, 0.04393693362340742]) + assert_allclose(windows.gaussian(7, 1.2), + [0.04393693362340742, 0.2493522087772962, + 0.7066482778577162, 1.0, 0.7066482778577162, + 0.2493522087772962, 0.04393693362340742]) + assert_allclose(windows.gaussian(7, 3), + [0.6065306597126334, 0.8007374029168081, + 0.9459594689067654, 1.0, 0.9459594689067654, + 0.8007374029168081, 0.6065306597126334]) + assert_allclose(windows.gaussian(6, 3, False), + [0.6065306597126334, 0.8007374029168081, + 0.9459594689067654, 1.0, 0.9459594689067654, + 0.8007374029168081]) + + +class TestGeneralCosine: + + def test_basic(self): + assert_allclose(windows.general_cosine(5, [0.5, 0.3, 0.2]), + [0.4, 0.3, 1, 0.3, 0.4]) + assert_allclose(windows.general_cosine(4, [0.5, 0.3, 0.2], sym=False), + [0.4, 0.3, 1, 0.3]) + + +class TestGeneralHamming: + + def test_basic(self): + assert_allclose(windows.general_hamming(5, 0.7), + [0.4, 0.7, 1.0, 0.7, 0.4]) + assert_allclose(windows.general_hamming(5, 0.75, sym=False), + [0.5, 0.6727457514, 0.9522542486, + 0.9522542486, 0.6727457514]) + assert_allclose(windows.general_hamming(6, 0.75, sym=True), + [0.5, 0.6727457514, 0.9522542486, + 0.9522542486, 0.6727457514, 0.5]) + + +class TestHamming: + + def test_basic(self): + assert_allclose(windows.hamming(6, False), + [0.08, 0.31, 0.77, 1.0, 0.77, 0.31]) + assert_allclose(windows.hamming(7, sym=False), + [0.08, 0.2531946911449826, 0.6423596296199047, + 0.9544456792351128, 0.9544456792351128, + 0.6423596296199047, 0.2531946911449826]) + assert_allclose(windows.hamming(6), + [0.08, 0.3978521825875242, 0.9121478174124757, + 0.9121478174124757, 0.3978521825875242, 0.08]) + assert_allclose(windows.hamming(7, sym=True), + [0.08, 0.31, 0.77, 1.0, 0.77, 0.31, 0.08]) + + +class TestHann: + + def test_basic(self): + assert_allclose(windows.hann(6, sym=False), + [0, 0.25, 0.75, 1.0, 0.75, 0.25], + rtol=1e-15, atol=1e-15) + assert_allclose(windows.hann(7, sym=False), + [0, 0.1882550990706332, 0.6112604669781572, + 0.9504844339512095, 0.9504844339512095, + 0.6112604669781572, 0.1882550990706332], + rtol=1e-15, atol=1e-15) + assert_allclose(windows.hann(6, True), + [0, 0.3454915028125263, 0.9045084971874737, + 0.9045084971874737, 0.3454915028125263, 0], + rtol=1e-15, atol=1e-15) + assert_allclose(windows.hann(7), + [0, 0.25, 0.75, 1.0, 0.75, 0.25, 0], + rtol=1e-15, atol=1e-15) + + +class TestKaiser: + + def test_basic(self): + assert_allclose(windows.kaiser(6, 0.5), + [0.9403061933191572, 0.9782962393705389, + 0.9975765035372042, 0.9975765035372042, + 0.9782962393705389, 0.9403061933191572]) + assert_allclose(windows.kaiser(7, 0.5), + [0.9403061933191572, 0.9732402256999829, + 0.9932754654413773, 1.0, 0.9932754654413773, + 0.9732402256999829, 0.9403061933191572]) + assert_allclose(windows.kaiser(6, 2.7), + [0.2603047507678832, 0.6648106293528054, + 0.9582099802511439, 0.9582099802511439, + 0.6648106293528054, 0.2603047507678832]) + assert_allclose(windows.kaiser(7, 2.7), + [0.2603047507678832, 0.5985765418119844, + 0.8868495172060835, 1.0, 0.8868495172060835, + 0.5985765418119844, 0.2603047507678832]) + assert_allclose(windows.kaiser(6, 2.7, False), + [0.2603047507678832, 0.5985765418119844, + 0.8868495172060835, 1.0, 0.8868495172060835, + 0.5985765418119844]) + + +class TestKaiserBesselDerived: + + def test_basic(self): + M = 100 + w = windows.kaiser_bessel_derived(M, beta=4.0) + w2 = windows.get_window(('kaiser bessel derived', 4.0), + M, fftbins=False) + assert_allclose(w, w2) + + # Test for Princen-Bradley condition + assert_allclose(w[:M // 2] ** 2 + w[-M // 2:] ** 2, 1.) + + # Test actual values from other implementations + # M = 2: sqrt(2) / 2 + # M = 4: 0.518562710536, 0.855039598640 + # M = 6: 0.436168993154, 0.707106781187, 0.899864772847 + # Ref:https://github.com/scipy/scipy/pull/4747#issuecomment-172849418 + assert_allclose(windows.kaiser_bessel_derived(2, beta=np.pi / 2)[:1], + np.sqrt(2) / 2) + + assert_allclose(windows.kaiser_bessel_derived(4, beta=np.pi / 2)[:2], + [0.518562710536, 0.855039598640]) + + assert_allclose(windows.kaiser_bessel_derived(6, beta=np.pi / 2)[:3], + [0.436168993154, 0.707106781187, 0.899864772847]) + + def test_exceptions(self): + M = 100 + # Assert ValueError for odd window length + msg = ("Kaiser-Bessel Derived windows are only defined for even " + "number of points") + with assert_raises(ValueError, match=msg): + windows.kaiser_bessel_derived(M + 1, beta=4.) + + # Assert ValueError for non-symmetric setting + msg = ("Kaiser-Bessel Derived windows are only defined for " + "symmetric shapes") + with assert_raises(ValueError, match=msg): + windows.kaiser_bessel_derived(M + 1, beta=4., sym=False) + + +class TestNuttall: + + def test_basic(self): + assert_allclose(windows.nuttall(6, sym=False), + [0.0003628, 0.0613345, 0.5292298, 1.0, 0.5292298, + 0.0613345]) + assert_allclose(windows.nuttall(7, sym=False), + [0.0003628, 0.03777576895352025, 0.3427276199688195, + 0.8918518610776603, 0.8918518610776603, + 0.3427276199688196, 0.0377757689535203]) + assert_allclose(windows.nuttall(6), + [0.0003628, 0.1105152530498718, 0.7982580969501282, + 0.7982580969501283, 0.1105152530498719, 0.0003628]) + assert_allclose(windows.nuttall(7, True), + [0.0003628, 0.0613345, 0.5292298, 1.0, 0.5292298, + 0.0613345, 0.0003628]) + + +class TestParzen: + + def test_basic(self): + assert_allclose(windows.parzen(6), + [0.009259259259259254, 0.25, 0.8611111111111112, + 0.8611111111111112, 0.25, 0.009259259259259254]) + assert_allclose(windows.parzen(7, sym=True), + [0.00583090379008747, 0.1574344023323616, + 0.6501457725947521, 1.0, 0.6501457725947521, + 0.1574344023323616, 0.00583090379008747]) + assert_allclose(windows.parzen(6, False), + [0.00583090379008747, 0.1574344023323616, + 0.6501457725947521, 1.0, 0.6501457725947521, + 0.1574344023323616]) + + +class TestTriang: + + def test_basic(self): + + assert_allclose(windows.triang(6, True), + [1/6, 1/2, 5/6, 5/6, 1/2, 1/6]) + assert_allclose(windows.triang(7), + [1/4, 1/2, 3/4, 1, 3/4, 1/2, 1/4]) + assert_allclose(windows.triang(6, sym=False), + [1/4, 1/2, 3/4, 1, 3/4, 1/2]) + + +tukey_data = { + (4, 0.5, True): array([0.0, 1.0, 1.0, 0.0]), + (4, 0.9, True): array([0.0, 0.84312081893436686, + 0.84312081893436686, 0.0]), + (4, 1.0, True): array([0.0, 0.75, 0.75, 0.0]), + (4, 0.5, False): array([0.0, 1.0, 1.0, 1.0]), + (4, 0.9, False): array([0.0, 0.58682408883346526, + 1.0, 0.58682408883346526]), + (4, 1.0, False): array([0.0, 0.5, 1.0, 0.5]), + (5, 0.0, True): array([1.0, 1.0, 1.0, 1.0, 1.0]), + (5, 0.8, True): array([0.0, 0.69134171618254492, + 1.0, 0.69134171618254492, 0.0]), + (5, 1.0, True): array([0.0, 0.5, 1.0, 0.5, 0.0]), + + (6, 0): [1, 1, 1, 1, 1, 1], + (7, 0): [1, 1, 1, 1, 1, 1, 1], + (6, .25): [0, 1, 1, 1, 1, 0], + (7, .25): [0, 1, 1, 1, 1, 1, 0], + (6,): [0, 0.9045084971874737, 1.0, 1.0, 0.9045084971874735, 0], + (7,): [0, 0.75, 1.0, 1.0, 1.0, 0.75, 0], + (6, .75): [0, 0.5522642316338269, 1.0, 1.0, 0.5522642316338267, 0], + (7, .75): [0, 0.4131759111665348, 0.9698463103929542, 1.0, + 0.9698463103929542, 0.4131759111665347, 0], + (6, 1): [0, 0.3454915028125263, 0.9045084971874737, 0.9045084971874737, + 0.3454915028125263, 0], + (7, 1): [0, 0.25, 0.75, 1.0, 0.75, 0.25, 0], +} + + +class TestTukey: + + def test_basic(self): + # Test against hardcoded data + for k, v in tukey_data.items(): + if v is None: + assert_raises(ValueError, windows.tukey, *k) + else: + win = windows.tukey(*k) + assert_allclose(win, v, rtol=1e-15, atol=1e-15) + + def test_extremes(self): + # Test extremes of alpha correspond to boxcar and hann + tuk0 = windows.tukey(100, 0) + box0 = windows.boxcar(100) + assert_array_almost_equal(tuk0, box0) + + tuk1 = windows.tukey(100, 1) + han1 = windows.hann(100) + assert_array_almost_equal(tuk1, han1) + + +dpss_data = { + # All values from MATLAB: + # * taper[1] of (3, 1.4, 3) sign-flipped + # * taper[3] of (5, 1.5, 5) sign-flipped + (4, 0.1, 2): ([[0.497943898, 0.502047681, 0.502047681, 0.497943898], [0.670487993, 0.224601537, -0.224601537, -0.670487993]], [0.197961815, 0.002035474]), # noqa: E501 + (3, 1.4, 3): ([[0.410233151, 0.814504464, 0.410233151], [0.707106781, 0.0, -0.707106781], [0.575941629, -0.580157287, 0.575941629]], [0.999998093, 0.998067480, 0.801934426]), # noqa: E501 + (5, 1.5, 5): ([[0.1745071052, 0.4956749177, 0.669109327, 0.495674917, 0.174507105], [0.4399493348, 0.553574369, 0.0, -0.553574369, -0.439949334], [0.631452756, 0.073280238, -0.437943884, 0.073280238, 0.631452756], [0.553574369, -0.439949334, 0.0, 0.439949334, -0.553574369], [0.266110290, -0.498935248, 0.600414741, -0.498935248, 0.266110290147157]], [0.999728571, 0.983706916, 0.768457889, 0.234159338, 0.013947282907567]), # noqa: E501 + (100, 2, 4): ([[0.0030914414, 0.0041266922, 0.005315076, 0.006665149, 0.008184854, 0.0098814158, 0.011761239, 0.013829809, 0.016091597, 0.018549973, 0.02120712, 0.02406396, 0.027120092, 0.030373728, 0.033821651, 0.037459181, 0.041280145, 0.045276872, 0.049440192, 0.053759447, 0.058222524, 0.062815894, 0.067524661, 0.072332638, 0.077222418, 0.082175473, 0.087172252, 0.092192299, 0.097214376, 0.1022166, 0.10717657, 0.11207154, 0.11687856, 0.12157463, 0.12613686, 0.13054266, 0.13476986, 0.13879691, 0.14260302, 0.14616832, 0.14947401, 0.1525025, 0.15523755, 0.15766438, 0.15976981, 0.16154233, 0.16297223, 0.16405162, 0.16477455, 0.16513702, 0.16513702, 0.16477455, 0.16405162, 0.16297223, 0.16154233, 0.15976981, 0.15766438, 0.15523755, 0.1525025, 0.14947401, 0.14616832, 0.14260302, 0.13879691, 0.13476986, 0.13054266, 0.12613686, 0.12157463, 0.11687856, 0.11207154, 0.10717657, 0.1022166, 0.097214376, 0.092192299, 0.087172252, 0.082175473, 0.077222418, 0.072332638, 0.067524661, 0.062815894, 0.058222524, 0.053759447, 0.049440192, 0.045276872, 0.041280145, 0.037459181, 0.033821651, 0.030373728, 0.027120092, 0.02406396, 0.02120712, 0.018549973, 0.016091597, 0.013829809, 0.011761239, 0.0098814158, 0.008184854, 0.006665149, 0.005315076, 0.0041266922, 0.0030914414], [0.018064449, 0.022040342, 0.026325013, 0.030905288, 0.035764398, 0.040881982, 0.046234148, 0.051793558, 0.057529559, 0.063408356, 0.069393216, 0.075444716, 0.081521022, 0.087578202, 0.093570567, 0.099451049, 0.10517159, 0.11068356, 0.11593818, 0.12088699, 0.12548227, 0.12967752, 0.1334279, 0.13669069, 0.13942569, 0.1415957, 0.14316686, 0.14410905, 0.14439626, 0.14400686, 0.14292389, 0.1411353, 0.13863416, 0.13541876, 0.13149274, 0.12686516, 0.12155045, 0.1155684, 0.10894403, 0.10170748, 0.093893752, 0.08554251, 0.076697768, 0.067407559, 0.057723559, 0.04770068, 0.037396627, 0.026871428, 0.016186944, 0.0054063557, -0.0054063557, -0.016186944, -0.026871428, -0.037396627, -0.04770068, -0.057723559, -0.067407559, -0.076697768, -0.08554251, -0.093893752, -0.10170748, -0.10894403, -0.1155684, -0.12155045, -0.12686516, -0.13149274, -0.13541876, -0.13863416, -0.1411353, -0.14292389, -0.14400686, -0.14439626, -0.14410905, -0.14316686, -0.1415957, -0.13942569, -0.13669069, -0.1334279, -0.12967752, -0.12548227, -0.12088699, -0.11593818, -0.11068356, -0.10517159, -0.099451049, -0.093570567, -0.087578202, -0.081521022, -0.075444716, -0.069393216, -0.063408356, -0.057529559, -0.051793558, -0.046234148, -0.040881982, -0.035764398, -0.030905288, -0.026325013, -0.022040342, -0.018064449], [0.064817553, 0.072567801, 0.080292992, 0.087918235, 0.095367076, 0.10256232, 0.10942687, 0.1158846, 0.12186124, 0.12728523, 0.13208858, 0.13620771, 0.13958427, 0.14216587, 0.14390678, 0.14476863, 0.1447209, 0.14374148, 0.14181704, 0.13894336, 0.13512554, 0.13037812, 0.1247251, 0.11819984, 0.11084487, 0.10271159, 0.093859853, 0.084357497, 0.074279719, 0.063708406, 0.052731374, 0.041441525, 0.029935953, 0.018314987, 0.0066811877, -0.0048616765, -0.016209689, -0.027259848, -0.037911124, -0.048065512, -0.05762905, -0.066512804, -0.0746338, -0.081915903, -0.088290621, -0.09369783, -0.098086416, -0.10141482, -0.10365146, -0.10477512, -0.10477512, -0.10365146, -0.10141482, -0.098086416, -0.09369783, -0.088290621, -0.081915903, -0.0746338, -0.066512804, -0.05762905, -0.048065512, -0.037911124, -0.027259848, -0.016209689, -0.0048616765, 0.0066811877, 0.018314987, 0.029935953, 0.041441525, 0.052731374, 0.063708406, 0.074279719, 0.084357497, 0.093859853, 0.10271159, 0.11084487, 0.11819984, 0.1247251, 0.13037812, 0.13512554, 0.13894336, 0.14181704, 0.14374148, 0.1447209, 0.14476863, 0.14390678, 0.14216587, 0.13958427, 0.13620771, 0.13208858, 0.12728523, 0.12186124, 0.1158846, 0.10942687, 0.10256232, 0.095367076, 0.087918235, 0.080292992, 0.072567801, 0.064817553], [0.14985551, 0.15512305, 0.15931467, 0.16236806, 0.16423291, 0.16487165, 0.16426009, 0.1623879, 0.1592589, 0.15489114, 0.14931693, 0.14258255, 0.13474785, 0.1258857, 0.11608124, 0.10543095, 0.094041635, 0.082029213, 0.069517411, 0.056636348, 0.043521028, 0.030309756, 0.017142511, 0.0041592774, -0.0085016282, -0.020705223, -0.032321494, -0.043226982, -0.053306291, -0.062453515, -0.070573544, -0.077583253, -0.083412547, -0.088005244, -0.091319802, -0.093329861, -0.094024602, -0.093408915, -0.091503383, -0.08834406, -0.08398207, -0.078483012, -0.071926192, -0.064403681, -0.056019215, -0.046886954, -0.037130106, -0.026879442, -0.016271713, -0.005448, 0.005448, 0.016271713, 0.026879442, 0.037130106, 0.046886954, 0.056019215, 0.064403681, 0.071926192, 0.078483012, 0.08398207, 0.08834406, 0.091503383, 0.093408915, 0.094024602, 0.093329861, 0.091319802, 0.088005244, 0.083412547, 0.077583253, 0.070573544, 0.062453515, 0.053306291, 0.043226982, 0.032321494, 0.020705223, 0.0085016282, -0.0041592774, -0.017142511, -0.030309756, -0.043521028, -0.056636348, -0.069517411, -0.082029213, -0.094041635, -0.10543095, -0.11608124, -0.1258857, -0.13474785, -0.14258255, -0.14931693, -0.15489114, -0.1592589, -0.1623879, -0.16426009, -0.16487165, -0.16423291, -0.16236806, -0.15931467, -0.15512305, -0.14985551]], [0.999943140, 0.997571533, 0.959465463, 0.721862496]), # noqa: E501 +} + + +class TestDPSS: + + def test_basic(self): + # Test against hardcoded data + for k, v in dpss_data.items(): + win, ratios = windows.dpss(*k, return_ratios=True) + assert_allclose(win, v[0], atol=1e-7, err_msg=k) + assert_allclose(ratios, v[1], rtol=1e-5, atol=1e-7, err_msg=k) + + def test_unity(self): + # Test unity value handling (gh-2221) + for M in range(1, 21): + # corrected w/approximation (default) + win = windows.dpss(M, M / 2.1) + expected = M % 2 # one for odd, none for even + assert_equal(np.isclose(win, 1.).sum(), expected, + err_msg=f'{win}') + # corrected w/subsample delay (slower) + win_sub = windows.dpss(M, M / 2.1, norm='subsample') + if M > 2: + # @M=2 the subsample doesn't do anything + assert_equal(np.isclose(win_sub, 1.).sum(), expected, + err_msg=f'{win_sub}') + assert_allclose(win, win_sub, rtol=0.03) # within 3% + # not the same, l2-norm + win_2 = windows.dpss(M, M / 2.1, norm=2) + expected = 1 if M == 1 else 0 + assert_equal(np.isclose(win_2, 1.).sum(), expected, + err_msg=f'{win_2}') + + def test_extremes(self): + # Test extremes of alpha + lam = windows.dpss(31, 6, 4, return_ratios=True)[1] + assert_array_almost_equal(lam, 1.) + lam = windows.dpss(31, 7, 4, return_ratios=True)[1] + assert_array_almost_equal(lam, 1.) + lam = windows.dpss(31, 8, 4, return_ratios=True)[1] + assert_array_almost_equal(lam, 1.) + + def test_degenerate(self): + # Test failures + assert_raises(ValueError, windows.dpss, 4, 1.5, -1) # Bad Kmax + assert_raises(ValueError, windows.dpss, 4, 1.5, -5) + assert_raises(TypeError, windows.dpss, 4, 1.5, 1.1) + assert_raises(ValueError, windows.dpss, 3, 1.5, 3) # NW must be < N/2. + assert_raises(ValueError, windows.dpss, 3, -1, 3) # NW must be pos + assert_raises(ValueError, windows.dpss, 3, 0, 3) + assert_raises(ValueError, windows.dpss, -1, 1, 3) # negative M + + +class TestLanczos: + + def test_basic(self): + # Analytical results: + # sinc(x) = sinc(-x) + # sinc(pi) = 0, sinc(0) = 1 + # Hand computation on WolframAlpha: + # sinc(2 pi / 3) = 0.413496672 + # sinc(pi / 3) = 0.826993343 + # sinc(3 pi / 5) = 0.504551152 + # sinc(pi / 5) = 0.935489284 + assert_allclose(windows.lanczos(6, sym=False), + [0., 0.413496672, + 0.826993343, 1., 0.826993343, + 0.413496672], + atol=1e-9) + assert_allclose(windows.lanczos(6), + [0., 0.504551152, + 0.935489284, 0.935489284, + 0.504551152, 0.], + atol=1e-9) + assert_allclose(windows.lanczos(7, sym=True), + [0., 0.413496672, + 0.826993343, 1., 0.826993343, + 0.413496672, 0.], + atol=1e-9) + + def test_array_size(self): + for n in [0, 10, 11]: + assert_equal(len(windows.lanczos(n, sym=False)), n) + assert_equal(len(windows.lanczos(n, sym=True)), n) + + +class TestGetWindow: + + def test_boxcar(self): + w = windows.get_window('boxcar', 12) + assert_array_equal(w, np.ones_like(w)) + + # window is a tuple of len 1 + w = windows.get_window(('boxcar',), 16) + assert_array_equal(w, np.ones_like(w)) + + def test_cheb_odd(self): + with suppress_warnings() as sup: + sup.filter(UserWarning, "This window is not suitable") + w = windows.get_window(('chebwin', -40), 53, fftbins=False) + assert_array_almost_equal(w, cheb_odd_true, decimal=4) + + def test_cheb_even(self): + with suppress_warnings() as sup: + sup.filter(UserWarning, "This window is not suitable") + w = windows.get_window(('chebwin', 40), 54, fftbins=False) + assert_array_almost_equal(w, cheb_even_true, decimal=4) + + def test_dpss(self): + win1 = windows.get_window(('dpss', 3), 64, fftbins=False) + win2 = windows.dpss(64, 3) + assert_array_almost_equal(win1, win2, decimal=4) + + def test_kaiser_float(self): + win1 = windows.get_window(7.2, 64) + win2 = windows.kaiser(64, 7.2, False) + assert_allclose(win1, win2) + + def test_invalid_inputs(self): + # Window is not a float, tuple, or string + assert_raises(ValueError, windows.get_window, set('hann'), 8) + + # Unknown window type error + assert_raises(ValueError, windows.get_window, 'broken', 4) + + def test_array_as_window(self): + # GitHub issue 3603 + osfactor = 128 + sig = np.arange(128) + + win = windows.get_window(('kaiser', 8.0), osfactor // 2) + with assert_raises(ValueError, match='must have the same length'): + resample(sig, len(sig) * osfactor, window=win) + + def test_general_cosine(self): + assert_allclose(get_window(('general_cosine', [0.5, 0.3, 0.2]), 4), + [0.4, 0.3, 1, 0.3]) + assert_allclose(get_window(('general_cosine', [0.5, 0.3, 0.2]), 4, + fftbins=False), + [0.4, 0.55, 0.55, 0.4]) + + def test_general_hamming(self): + assert_allclose(get_window(('general_hamming', 0.7), 5), + [0.4, 0.6072949, 0.9427051, 0.9427051, 0.6072949]) + assert_allclose(get_window(('general_hamming', 0.7), 5, fftbins=False), + [0.4, 0.7, 1.0, 0.7, 0.4]) + + def test_lanczos(self): + assert_allclose(get_window('lanczos', 6), + [0., 0.413496672, 0.826993343, 1., 0.826993343, + 0.413496672], atol=1e-9) + assert_allclose(get_window('lanczos', 6, fftbins=False), + [0., 0.504551152, 0.935489284, 0.935489284, + 0.504551152, 0.], atol=1e-9) + assert_allclose(get_window('lanczos', 6), get_window('sinc', 6)) + + +def test_windowfunc_basics(): + for window_name, params in window_funcs: + window = getattr(windows, window_name) + with suppress_warnings() as sup: + sup.filter(UserWarning, "This window is not suitable") + # Check symmetry for odd and even lengths + w1 = window(8, *params, sym=True) + w2 = window(7, *params, sym=False) + assert_array_almost_equal(w1[:-1], w2) + + w1 = window(9, *params, sym=True) + w2 = window(8, *params, sym=False) + assert_array_almost_equal(w1[:-1], w2) + + # Check that functions run and output lengths are correct + assert_equal(len(window(6, *params, sym=True)), 6) + assert_equal(len(window(6, *params, sym=False)), 6) + assert_equal(len(window(7, *params, sym=True)), 7) + assert_equal(len(window(7, *params, sym=False)), 7) + + # Check invalid lengths + assert_raises(ValueError, window, 5.5, *params) + assert_raises(ValueError, window, -7, *params) + + # Check degenerate cases + assert_array_equal(window(0, *params, sym=True), []) + assert_array_equal(window(0, *params, sym=False), []) + assert_array_equal(window(1, *params, sym=True), [1]) + assert_array_equal(window(1, *params, sym=False), [1]) + + # Check dtype + assert_(window(0, *params, sym=True).dtype == 'float') + assert_(window(0, *params, sym=False).dtype == 'float') + assert_(window(1, *params, sym=True).dtype == 'float') + assert_(window(1, *params, sym=False).dtype == 'float') + assert_(window(6, *params, sym=True).dtype == 'float') + assert_(window(6, *params, sym=False).dtype == 'float') + + # Check normalization + assert_array_less(window(10, *params, sym=True), 1.01) + assert_array_less(window(10, *params, sym=False), 1.01) + assert_array_less(window(9, *params, sym=True), 1.01) + assert_array_less(window(9, *params, sym=False), 1.01) + + # Check that DFT-even spectrum is purely real for odd and even + assert_allclose(fft(window(10, *params, sym=False)).imag, + 0, atol=1e-14) + assert_allclose(fft(window(11, *params, sym=False)).imag, + 0, atol=1e-14) + + +def test_needs_params(): + for winstr in ['kaiser', 'ksr', 'kaiser_bessel_derived', 'kbd', + 'gaussian', 'gauss', 'gss', + 'general gaussian', 'general_gaussian', + 'general gauss', 'general_gauss', 'ggs', + 'dss', 'dpss', 'general cosine', 'general_cosine', + 'chebwin', 'cheb', 'general hamming', 'general_hamming', + ]: + assert_raises(ValueError, get_window, winstr, 7) + + +def test_not_needs_params(): + for winstr in ['barthann', + 'bartlett', + 'blackman', + 'blackmanharris', + 'bohman', + 'boxcar', + 'cosine', + 'flattop', + 'hamming', + 'nuttall', + 'parzen', + 'taylor', + 'exponential', + 'poisson', + 'tukey', + 'tuk', + 'triangle', + 'lanczos', + 'sinc', + ]: + win = get_window(winstr, 7) + assert_equal(len(win), 7) + + +def test_symmetric(): + + for win in [windows.lanczos]: + # Even sampling points + w = win(4096) + error = np.max(np.abs(w-np.flip(w))) + assert_equal(error, 0.0) + + # Odd sampling points + w = win(4097) + error = np.max(np.abs(w-np.flip(w))) + assert_equal(error, 0.0) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/waveforms.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/waveforms.py new file mode 100644 index 0000000000000000000000000000000000000000..30e71348d04276a66470a4053d97cefc60f7136e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/waveforms.py @@ -0,0 +1,20 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.signal` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__ = [ # noqa: F822 + 'sawtooth', 'square', 'gausspulse', 'chirp', 'sweep_poly', + 'unit_impulse', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="signal", module="waveforms", + private_modules=["_waveforms"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/wavelets.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/wavelets.py new file mode 100644 index 0000000000000000000000000000000000000000..fc897a2483536df7e995faaa29af621e25fe38c7 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/wavelets.py @@ -0,0 +1,17 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.signal` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__: list[str] = [] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="signal", module="wavelets", + private_modules=["_wavelets"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/windows/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/windows/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..967a7c758f69c1c8002d886d78832904c402d2b3 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/windows/__init__.py @@ -0,0 +1,52 @@ +""" +Window functions (:mod:`scipy.signal.windows`) +============================================== + +The suite of window functions for filtering and spectral estimation. + +.. currentmodule:: scipy.signal.windows + +.. autosummary:: + :toctree: generated/ + + get_window -- Return a window of a given length and type. + + barthann -- Bartlett-Hann window + bartlett -- Bartlett window + blackman -- Blackman window + blackmanharris -- Minimum 4-term Blackman-Harris window + bohman -- Bohman window + boxcar -- Boxcar window + chebwin -- Dolph-Chebyshev window + cosine -- Cosine window + dpss -- Discrete prolate spheroidal sequences + exponential -- Exponential window + flattop -- Flat top window + gaussian -- Gaussian window + general_cosine -- Generalized Cosine window + general_gaussian -- Generalized Gaussian window + general_hamming -- Generalized Hamming window + hamming -- Hamming window + hann -- Hann window + kaiser -- Kaiser window + kaiser_bessel_derived -- Kaiser-Bessel derived window + lanczos -- Lanczos window also known as a sinc window + nuttall -- Nuttall's minimum 4-term Blackman-Harris window + parzen -- Parzen window + taylor -- Taylor window + triang -- Triangular window + tukey -- Tukey window + +""" + +from ._windows import * + +# Deprecated namespaces, to be removed in v2.0.0 +from . import windows + +__all__ = ['boxcar', 'triang', 'parzen', 'bohman', 'blackman', 'nuttall', + 'blackmanharris', 'flattop', 'bartlett', 'barthann', + 'hamming', 'kaiser', 'kaiser_bessel_derived', 'gaussian', + 'general_gaussian', 'general_cosine', 'general_hamming', + 'chebwin', 'cosine', 'hann', 'exponential', 'tukey', 'taylor', + 'get_window', 'dpss', 'lanczos'] diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/windows/_windows.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/windows/_windows.py new file mode 100644 index 0000000000000000000000000000000000000000..e89c1aee6aba661f11a86cb2213904964d870782 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/windows/_windows.py @@ -0,0 +1,2374 @@ +"""The suite of window functions.""" + +import operator +import warnings + +import numpy as np +from scipy import linalg, special, fft as sp_fft + +__all__ = ['boxcar', 'triang', 'parzen', 'bohman', 'blackman', 'nuttall', + 'blackmanharris', 'flattop', 'bartlett', 'barthann', + 'hamming', 'kaiser', 'kaiser_bessel_derived', 'gaussian', + 'general_cosine', 'general_gaussian', 'general_hamming', + 'chebwin', 'cosine', 'hann', 'exponential', 'tukey', 'taylor', + 'dpss', 'get_window', 'lanczos'] + + +def _len_guards(M): + """Handle small or incorrect window lengths""" + if int(M) != M or M < 0: + raise ValueError('Window length M must be a non-negative integer') + return M <= 1 + + +def _extend(M, sym): + """Extend window by 1 sample if needed for DFT-even symmetry""" + if not sym: + return M + 1, True + else: + return M, False + + +def _truncate(w, needed): + """Truncate window by 1 sample if needed for DFT-even symmetry""" + if needed: + return w[:-1] + else: + return w + + +def general_cosine(M, a, sym=True): + r""" + Generic weighted sum of cosine terms window + + Parameters + ---------- + M : int + Number of points in the output window + a : array_like + Sequence of weighting coefficients. This uses the convention of being + centered on the origin, so these will typically all be positive + numbers, not alternating sign. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The array of window values. + + References + ---------- + .. [1] A. Nuttall, "Some windows with very good sidelobe behavior," IEEE + Transactions on Acoustics, Speech, and Signal Processing, vol. 29, + no. 1, pp. 84-91, Feb 1981. :doi:`10.1109/TASSP.1981.1163506`. + .. [2] Heinzel G. et al., "Spectrum and spectral density estimation by the + Discrete Fourier transform (DFT), including a comprehensive list of + window functions and some new flat-top windows", February 15, 2002 + https://holometer.fnal.gov/GH_FFT.pdf + + Examples + -------- + Heinzel describes a flat-top window named "HFT90D" with formula: [2]_ + + .. math:: w_j = 1 - 1.942604 \cos(z) + 1.340318 \cos(2z) + - 0.440811 \cos(3z) + 0.043097 \cos(4z) + + where + + .. math:: z = \frac{2 \pi j}{N}, j = 0...N - 1 + + Since this uses the convention of starting at the origin, to reproduce the + window, we need to convert every other coefficient to a positive number: + + >>> HFT90D = [1, 1.942604, 1.340318, 0.440811, 0.043097] + + The paper states that the highest sidelobe is at -90.2 dB. Reproduce + Figure 42 by plotting the window and its frequency response, and confirm + the sidelobe level in red: + + >>> import numpy as np + >>> from scipy.signal.windows import general_cosine + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> window = general_cosine(1000, HFT90D, sym=False) + >>> plt.plot(window) + >>> plt.title("HFT90D window") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + + >>> plt.figure() + >>> A = fft(window, 10000) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = np.abs(fftshift(A / abs(A).max())) + >>> response = 20 * np.log10(np.maximum(response, 1e-10)) + >>> plt.plot(freq, response) + >>> plt.axis([-50/1000, 50/1000, -140, 0]) + >>> plt.title("Frequency response of the HFT90D window") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + >>> plt.axhline(-90.2, color='red') + >>> plt.show() + """ + if _len_guards(M): + return np.ones(M) + M, needs_trunc = _extend(M, sym) + + fac = np.linspace(-np.pi, np.pi, M) + w = np.zeros(M) + for k in range(len(a)): + w += a[k] * np.cos(k * fac) + + return _truncate(w, needs_trunc) + + +def boxcar(M, sym=True): + """Return a boxcar or rectangular window. + + Also known as a rectangular window or Dirichlet window, this is equivalent + to no window at all. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + sym : bool, optional + Whether the window is symmetric. (Has no effect for boxcar.) + + Returns + ------- + w : ndarray + The window, with the maximum value normalized to 1. + + Examples + -------- + Plot the window and its frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> window = signal.windows.boxcar(51) + >>> plt.plot(window) + >>> plt.title("Boxcar window") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + + >>> plt.figure() + >>> A = fft(window, 2048) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) + >>> plt.plot(freq, response) + >>> plt.axis([-0.5, 0.5, -120, 0]) + >>> plt.title("Frequency response of the boxcar window") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + + """ + if _len_guards(M): + return np.ones(M) + M, needs_trunc = _extend(M, sym) + + w = np.ones(M, float) + + return _truncate(w, needs_trunc) + + +def triang(M, sym=True): + """Return a triangular window. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The window, with the maximum value normalized to 1 (though the value 1 + does not appear if `M` is even and `sym` is True). + + See Also + -------- + bartlett : A triangular window that touches zero + + Examples + -------- + Plot the window and its frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> window = signal.windows.triang(51) + >>> plt.plot(window) + >>> plt.title("Triangular window") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + + >>> plt.figure() + >>> A = fft(window, 2048) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = np.abs(fftshift(A / abs(A).max())) + >>> response = 20 * np.log10(np.maximum(response, 1e-10)) + >>> plt.plot(freq, response) + >>> plt.axis([-0.5, 0.5, -120, 0]) + >>> plt.title("Frequency response of the triangular window") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + + """ + if _len_guards(M): + return np.ones(M) + M, needs_trunc = _extend(M, sym) + + n = np.arange(1, (M + 1) // 2 + 1) + if M % 2 == 0: + w = (2 * n - 1.0) / M + w = np.r_[w, w[::-1]] + else: + w = 2 * n / (M + 1.0) + w = np.r_[w, w[-2::-1]] + + return _truncate(w, needs_trunc) + + +def parzen(M, sym=True): + """Return a Parzen window. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The window, with the maximum value normalized to 1 (though the value 1 + does not appear if `M` is even and `sym` is True). + + References + ---------- + .. [1] E. Parzen, "Mathematical Considerations in the Estimation of + Spectra", Technometrics, Vol. 3, No. 2 (May, 1961), pp. 167-190 + + Examples + -------- + Plot the window and its frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> window = signal.windows.parzen(51) + >>> plt.plot(window) + >>> plt.title("Parzen window") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + + >>> plt.figure() + >>> A = fft(window, 2048) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) + >>> plt.plot(freq, response) + >>> plt.axis([-0.5, 0.5, -120, 0]) + >>> plt.title("Frequency response of the Parzen window") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + + """ + if _len_guards(M): + return np.ones(M) + M, needs_trunc = _extend(M, sym) + + n = np.arange(-(M - 1) / 2.0, (M - 1) / 2.0 + 0.5, 1.0) + na = np.extract(n < -(M - 1) / 4.0, n) + nb = np.extract(abs(n) <= (M - 1) / 4.0, n) + wa = 2 * (1 - np.abs(na) / (M / 2.0)) ** 3.0 + wb = (1 - 6 * (np.abs(nb) / (M / 2.0)) ** 2.0 + + 6 * (np.abs(nb) / (M / 2.0)) ** 3.0) + w = np.r_[wa, wb, wa[::-1]] + + return _truncate(w, needs_trunc) + + +def bohman(M, sym=True): + """Return a Bohman window. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The window, with the maximum value normalized to 1 (though the value 1 + does not appear if `M` is even and `sym` is True). + + Examples + -------- + Plot the window and its frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> window = signal.windows.bohman(51) + >>> plt.plot(window) + >>> plt.title("Bohman window") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + + >>> plt.figure() + >>> A = fft(window, 2047) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) + >>> plt.plot(freq, response) + >>> plt.axis([-0.5, 0.5, -120, 0]) + >>> plt.title("Frequency response of the Bohman window") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + + """ + if _len_guards(M): + return np.ones(M) + M, needs_trunc = _extend(M, sym) + + fac = np.abs(np.linspace(-1, 1, M)[1:-1]) + w = (1 - fac) * np.cos(np.pi * fac) + 1.0 / np.pi * np.sin(np.pi * fac) + w = np.r_[0, w, 0] + + return _truncate(w, needs_trunc) + + +def blackman(M, sym=True): + r""" + Return a Blackman window. + + The Blackman window is a taper formed by using the first three terms of + a summation of cosines. It was designed to have close to the minimal + leakage possible. It is close to optimal, only slightly worse than a + Kaiser window. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The window, with the maximum value normalized to 1 (though the value 1 + does not appear if `M` is even and `sym` is True). + + Notes + ----- + The Blackman window is defined as + + .. math:: w(n) = 0.42 - 0.5 \cos(2\pi n/M) + 0.08 \cos(4\pi n/M) + + The "exact Blackman" window was designed to null out the third and fourth + sidelobes, but has discontinuities at the boundaries, resulting in a + 6 dB/oct fall-off. This window is an approximation of the "exact" window, + which does not null the sidelobes as well, but is smooth at the edges, + improving the fall-off rate to 18 dB/oct. [3]_ + + Most references to the Blackman window come from the signal processing + literature, where it is used as one of many windowing functions for + smoothing values. It is also known as an apodization (which means + "removing the foot", i.e. smoothing discontinuities at the beginning + and end of the sampled signal) or tapering function. It is known as a + "near optimal" tapering function, almost as good (by some measures) + as the Kaiser window. + + References + ---------- + .. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power + spectra, Dover Publications, New York. + .. [2] Oppenheim, A.V., and R.W. Schafer. Discrete-Time Signal Processing. + Upper Saddle River, NJ: Prentice-Hall, 1999, pp. 468-471. + .. [3] Harris, Fredric J. (Jan 1978). "On the use of Windows for Harmonic + Analysis with the Discrete Fourier Transform". Proceedings of the + IEEE 66 (1): 51-83. :doi:`10.1109/PROC.1978.10837`. + + Examples + -------- + Plot the window and its frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> window = signal.windows.blackman(51) + >>> plt.plot(window) + >>> plt.title("Blackman window") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + + >>> plt.figure() + >>> A = fft(window, 2048) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = np.abs(fftshift(A / abs(A).max())) + >>> response = 20 * np.log10(np.maximum(response, 1e-10)) + >>> plt.plot(freq, response) + >>> plt.axis([-0.5, 0.5, -120, 0]) + >>> plt.title("Frequency response of the Blackman window") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + + """ + # Docstring adapted from NumPy's blackman function + return general_cosine(M, [0.42, 0.50, 0.08], sym) + + +def nuttall(M, sym=True): + """Return a minimum 4-term Blackman-Harris window according to Nuttall. + + This variation is called "Nuttall4c" by Heinzel. [2]_ + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The window, with the maximum value normalized to 1 (though the value 1 + does not appear if `M` is even and `sym` is True). + + References + ---------- + .. [1] A. Nuttall, "Some windows with very good sidelobe behavior," IEEE + Transactions on Acoustics, Speech, and Signal Processing, vol. 29, + no. 1, pp. 84-91, Feb 1981. :doi:`10.1109/TASSP.1981.1163506`. + .. [2] Heinzel G. et al., "Spectrum and spectral density estimation by the + Discrete Fourier transform (DFT), including a comprehensive list of + window functions and some new flat-top windows", February 15, 2002 + https://holometer.fnal.gov/GH_FFT.pdf + + Examples + -------- + Plot the window and its frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> window = signal.windows.nuttall(51) + >>> plt.plot(window) + >>> plt.title("Nuttall window") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + + >>> plt.figure() + >>> A = fft(window, 2048) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) + >>> plt.plot(freq, response) + >>> plt.axis([-0.5, 0.5, -120, 0]) + >>> plt.title("Frequency response of the Nuttall window") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + + """ + return general_cosine(M, [0.3635819, 0.4891775, 0.1365995, 0.0106411], sym) + + +def blackmanharris(M, sym=True): + """Return a minimum 4-term Blackman-Harris window. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The window, with the maximum value normalized to 1 (though the value 1 + does not appear if `M` is even and `sym` is True). + + Examples + -------- + Plot the window and its frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> window = signal.windows.blackmanharris(51) + >>> plt.plot(window) + >>> plt.title("Blackman-Harris window") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + + >>> plt.figure() + >>> A = fft(window, 2048) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) + >>> plt.plot(freq, response) + >>> plt.axis([-0.5, 0.5, -120, 0]) + >>> plt.title("Frequency response of the Blackman-Harris window") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + + """ + return general_cosine(M, [0.35875, 0.48829, 0.14128, 0.01168], sym) + + +def flattop(M, sym=True): + """Return a flat top window. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The window, with the maximum value normalized to 1 (though the value 1 + does not appear if `M` is even and `sym` is True). + + Notes + ----- + Flat top windows are used for taking accurate measurements of signal + amplitude in the frequency domain, with minimal scalloping error from the + center of a frequency bin to its edges, compared to others. This is a + 5th-order cosine window, with the 5 terms optimized to make the main lobe + maximally flat. [1]_ + + References + ---------- + .. [1] D'Antona, Gabriele, and A. Ferrero, "Digital Signal Processing for + Measurement Systems", Springer Media, 2006, p. 70 + :doi:`10.1007/0-387-28666-7`. + + Examples + -------- + Plot the window and its frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> window = signal.windows.flattop(51) + >>> plt.plot(window) + >>> plt.title("Flat top window") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + + >>> plt.figure() + >>> A = fft(window, 2048) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) + >>> plt.plot(freq, response) + >>> plt.axis([-0.5, 0.5, -120, 0]) + >>> plt.title("Frequency response of the flat top window") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + + """ + a = [0.21557895, 0.41663158, 0.277263158, 0.083578947, 0.006947368] + return general_cosine(M, a, sym) + + +def bartlett(M, sym=True): + r""" + Return a Bartlett window. + + The Bartlett window is very similar to a triangular window, except + that the end points are at zero. It is often used in signal + processing for tapering a signal, without generating too much + ripple in the frequency domain. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The triangular window, with the first and last samples equal to zero + and the maximum value normalized to 1 (though the value 1 does not + appear if `M` is even and `sym` is True). + + See Also + -------- + triang : A triangular window that does not touch zero at the ends + + Notes + ----- + The Bartlett window is defined as + + .. math:: w(n) = \frac{2}{M-1} \left( + \frac{M-1}{2} - \left|n - \frac{M-1}{2}\right| + \right) + + Most references to the Bartlett window come from the signal + processing literature, where it is used as one of many windowing + functions for smoothing values. Note that convolution with this + window produces linear interpolation. It is also known as an + apodization (which means"removing the foot", i.e. smoothing + discontinuities at the beginning and end of the sampled signal) or + tapering function. The Fourier transform of the Bartlett is the product + of two sinc functions. + Note the excellent discussion in Kanasewich. [2]_ + + References + ---------- + .. [1] M.S. Bartlett, "Periodogram Analysis and Continuous Spectra", + Biometrika 37, 1-16, 1950. + .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", + The University of Alberta Press, 1975, pp. 109-110. + .. [3] A.V. Oppenheim and R.W. Schafer, "Discrete-Time Signal + Processing", Prentice-Hall, 1999, pp. 468-471. + .. [4] Wikipedia, "Window function", + https://en.wikipedia.org/wiki/Window_function + .. [5] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling, + "Numerical Recipes", Cambridge University Press, 1986, page 429. + + Examples + -------- + Plot the window and its frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> window = signal.windows.bartlett(51) + >>> plt.plot(window) + >>> plt.title("Bartlett window") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + + >>> plt.figure() + >>> A = fft(window, 2048) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) + >>> plt.plot(freq, response) + >>> plt.axis([-0.5, 0.5, -120, 0]) + >>> plt.title("Frequency response of the Bartlett window") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + + """ + # Docstring adapted from NumPy's bartlett function + if _len_guards(M): + return np.ones(M) + M, needs_trunc = _extend(M, sym) + + n = np.arange(0, M) + w = np.where(np.less_equal(n, (M - 1) / 2.0), + 2.0 * n / (M - 1), 2.0 - 2.0 * n / (M - 1)) + + return _truncate(w, needs_trunc) + + +def hann(M, sym=True): + r""" + Return a Hann window. + + The Hann window is a taper formed by using a raised cosine or sine-squared + with ends that touch zero. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The window, with the maximum value normalized to 1 (though the value 1 + does not appear if `M` is even and `sym` is True). + + Notes + ----- + The Hann window is defined as + + .. math:: w(n) = 0.5 - 0.5 \cos\left(\frac{2\pi{n}}{M-1}\right) + \qquad 0 \leq n \leq M-1 + + The window was named for Julius von Hann, an Austrian meteorologist. It is + also known as the Cosine Bell. It is sometimes erroneously referred to as + the "Hanning" window, from the use of "hann" as a verb in the original + paper and confusion with the very similar Hamming window. + + Most references to the Hann window come from the signal processing + literature, where it is used as one of many windowing functions for + smoothing values. It is also known as an apodization (which means + "removing the foot", i.e. smoothing discontinuities at the beginning + and end of the sampled signal) or tapering function. + + References + ---------- + .. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power + spectra, Dover Publications, New York. + .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", + The University of Alberta Press, 1975, pp. 106-108. + .. [3] Wikipedia, "Window function", + https://en.wikipedia.org/wiki/Window_function + .. [4] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling, + "Numerical Recipes", Cambridge University Press, 1986, page 425. + + Examples + -------- + Plot the window and its frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> window = signal.windows.hann(51) + >>> plt.plot(window) + >>> plt.title("Hann window") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + + >>> plt.figure() + >>> A = fft(window, 2048) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = np.abs(fftshift(A / abs(A).max())) + >>> response = 20 * np.log10(np.maximum(response, 1e-10)) + >>> plt.plot(freq, response) + >>> plt.axis([-0.5, 0.5, -120, 0]) + >>> plt.title("Frequency response of the Hann window") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + + """ + # Docstring adapted from NumPy's hanning function + return general_hamming(M, 0.5, sym) + + +def tukey(M, alpha=0.5, sym=True): + r"""Return a Tukey window, also known as a tapered cosine window. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + alpha : float, optional + Shape parameter of the Tukey window, representing the fraction of the + window inside the cosine tapered region. + If zero, the Tukey window is equivalent to a rectangular window. + If one, the Tukey window is equivalent to a Hann window. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The window, with the maximum value normalized to 1 (though the value 1 + does not appear if `M` is even and `sym` is True). + + References + ---------- + .. [1] Harris, Fredric J. (Jan 1978). "On the use of Windows for Harmonic + Analysis with the Discrete Fourier Transform". Proceedings of the + IEEE 66 (1): 51-83. :doi:`10.1109/PROC.1978.10837` + .. [2] Wikipedia, "Window function", + https://en.wikipedia.org/wiki/Window_function#Tukey_window + + Examples + -------- + Plot the window and its frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> window = signal.windows.tukey(51) + >>> plt.plot(window) + >>> plt.title("Tukey window") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + >>> plt.ylim([0, 1.1]) + + >>> plt.figure() + >>> A = fft(window, 2048) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) + >>> plt.plot(freq, response) + >>> plt.axis([-0.5, 0.5, -120, 0]) + >>> plt.title("Frequency response of the Tukey window") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + + """ + if _len_guards(M): + return np.ones(M) + + if alpha <= 0: + return np.ones(M, 'd') + elif alpha >= 1.0: + return hann(M, sym=sym) + + M, needs_trunc = _extend(M, sym) + + n = np.arange(0, M) + width = int(np.floor(alpha*(M-1)/2.0)) + n1 = n[0:width+1] + n2 = n[width+1:M-width-1] + n3 = n[M-width-1:] + + w1 = 0.5 * (1 + np.cos(np.pi * (-1 + 2.0*n1/alpha/(M-1)))) + w2 = np.ones(n2.shape) + w3 = 0.5 * (1 + np.cos(np.pi * (-2.0/alpha + 1 + 2.0*n3/alpha/(M-1)))) + + w = np.concatenate((w1, w2, w3)) + + return _truncate(w, needs_trunc) + + +def barthann(M, sym=True): + """Return a modified Bartlett-Hann window. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The window, with the maximum value normalized to 1 (though the value 1 + does not appear if `M` is even and `sym` is True). + + Examples + -------- + Plot the window and its frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> window = signal.windows.barthann(51) + >>> plt.plot(window) + >>> plt.title("Bartlett-Hann window") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + + >>> plt.figure() + >>> A = fft(window, 2048) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) + >>> plt.plot(freq, response) + >>> plt.axis([-0.5, 0.5, -120, 0]) + >>> plt.title("Frequency response of the Bartlett-Hann window") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + + """ + if _len_guards(M): + return np.ones(M) + M, needs_trunc = _extend(M, sym) + + n = np.arange(0, M) + fac = np.abs(n / (M - 1.0) - 0.5) + w = 0.62 - 0.48 * fac + 0.38 * np.cos(2 * np.pi * fac) + + return _truncate(w, needs_trunc) + + +def general_hamming(M, alpha, sym=True): + r"""Return a generalized Hamming window. + + The generalized Hamming window is constructed by multiplying a rectangular + window by one period of a cosine function [1]_. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + alpha : float + The window coefficient, :math:`\alpha` + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The window, with the maximum value normalized to 1 (though the value 1 + does not appear if `M` is even and `sym` is True). + + See Also + -------- + hamming, hann + + Notes + ----- + The generalized Hamming window is defined as + + .. math:: w(n) = \alpha - \left(1 - \alpha\right) + \cos\left(\frac{2\pi{n}}{M-1}\right) \qquad 0 \leq n \leq M-1 + + Both the common Hamming window and Hann window are special cases of the + generalized Hamming window with :math:`\alpha` = 0.54 and :math:`\alpha` = + 0.5, respectively [2]_. + + References + ---------- + .. [1] DSPRelated, "Generalized Hamming Window Family", + https://www.dsprelated.com/freebooks/sasp/Generalized_Hamming_Window_Family.html + .. [2] Wikipedia, "Window function", + https://en.wikipedia.org/wiki/Window_function + .. [3] Riccardo Piantanida ESA, "Sentinel-1 Level 1 Detailed Algorithm + Definition", + https://sentinel.esa.int/documents/247904/1877131/Sentinel-1-Level-1-Detailed-Algorithm-Definition + .. [4] Matthieu Bourbigot ESA, "Sentinel-1 Product Definition", + https://sentinel.esa.int/documents/247904/1877131/Sentinel-1-Product-Definition + + Examples + -------- + The Sentinel-1A/B Instrument Processing Facility uses generalized Hamming + windows in the processing of spaceborne Synthetic Aperture Radar (SAR) + data [3]_. The facility uses various values for the :math:`\alpha` + parameter based on operating mode of the SAR instrument. Some common + :math:`\alpha` values include 0.75, 0.7 and 0.52 [4]_. As an example, we + plot these different windows. + + >>> import numpy as np + >>> from scipy.signal.windows import general_hamming + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> fig1, spatial_plot = plt.subplots() + >>> spatial_plot.set_title("Generalized Hamming Windows") + >>> spatial_plot.set_ylabel("Amplitude") + >>> spatial_plot.set_xlabel("Sample") + + >>> fig2, freq_plot = plt.subplots() + >>> freq_plot.set_title("Frequency Responses") + >>> freq_plot.set_ylabel("Normalized magnitude [dB]") + >>> freq_plot.set_xlabel("Normalized frequency [cycles per sample]") + + >>> for alpha in [0.75, 0.7, 0.52]: + ... window = general_hamming(41, alpha) + ... spatial_plot.plot(window, label="{:.2f}".format(alpha)) + ... A = fft(window, 2048) / (len(window)/2.0) + ... freq = np.linspace(-0.5, 0.5, len(A)) + ... response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) + ... freq_plot.plot(freq, response, label="{:.2f}".format(alpha)) + >>> freq_plot.legend(loc="upper right") + >>> spatial_plot.legend(loc="upper right") + + """ + return general_cosine(M, [alpha, 1. - alpha], sym) + + +def hamming(M, sym=True): + r"""Return a Hamming window. + + The Hamming window is a taper formed by using a raised cosine with + non-zero endpoints, optimized to minimize the nearest side lobe. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The window, with the maximum value normalized to 1 (though the value 1 + does not appear if `M` is even and `sym` is True). + + Notes + ----- + The Hamming window is defined as + + .. math:: w(n) = 0.54 - 0.46 \cos\left(\frac{2\pi{n}}{M-1}\right) + \qquad 0 \leq n \leq M-1 + + The Hamming was named for R. W. Hamming, an associate of J. W. Tukey and + is described in Blackman and Tukey. It was recommended for smoothing the + truncated autocovariance function in the time domain. + Most references to the Hamming window come from the signal processing + literature, where it is used as one of many windowing functions for + smoothing values. It is also known as an apodization (which means + "removing the foot", i.e. smoothing discontinuities at the beginning + and end of the sampled signal) or tapering function. + + References + ---------- + .. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power + spectra, Dover Publications, New York. + .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The + University of Alberta Press, 1975, pp. 109-110. + .. [3] Wikipedia, "Window function", + https://en.wikipedia.org/wiki/Window_function + .. [4] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling, + "Numerical Recipes", Cambridge University Press, 1986, page 425. + + Examples + -------- + Plot the window and its frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> window = signal.windows.hamming(51) + >>> plt.plot(window) + >>> plt.title("Hamming window") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + + >>> plt.figure() + >>> A = fft(window, 2048) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) + >>> plt.plot(freq, response) + >>> plt.axis([-0.5, 0.5, -120, 0]) + >>> plt.title("Frequency response of the Hamming window") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + + """ + # Docstring adapted from NumPy's hamming function + return general_hamming(M, 0.54, sym) + + +def kaiser(M, beta, sym=True): + r"""Return a Kaiser window. + + The Kaiser window is a taper formed by using a Bessel function. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + beta : float + Shape parameter, determines trade-off between main-lobe width and + side lobe level. As beta gets large, the window narrows. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The window, with the maximum value normalized to 1 (though the value 1 + does not appear if `M` is even and `sym` is True). + + Notes + ----- + The Kaiser window is defined as + + .. math:: w(n) = I_0\left( \beta \sqrt{1-\frac{4n^2}{(M-1)^2}} + \right)/I_0(\beta) + + with + + .. math:: \quad -\frac{M-1}{2} \leq n \leq \frac{M-1}{2}, + + where :math:`I_0` is the modified zeroth-order Bessel function. + + The Kaiser was named for Jim Kaiser, who discovered a simple approximation + to the DPSS window based on Bessel functions. + The Kaiser window is a very good approximation to the discrete prolate + spheroidal sequence, or Slepian window, which is the transform which + maximizes the energy in the main lobe of the window relative to total + energy. + + The Kaiser can approximate other windows by varying the beta parameter. + (Some literature uses alpha = beta/pi.) [4]_ + + ==== ======================= + beta Window shape + ==== ======================= + 0 Rectangular + 5 Similar to a Hamming + 6 Similar to a Hann + 8.6 Similar to a Blackman + ==== ======================= + + A beta value of 14 is probably a good starting point. Note that as beta + gets large, the window narrows, and so the number of samples needs to be + large enough to sample the increasingly narrow spike, otherwise NaNs will + be returned. + + Most references to the Kaiser window come from the signal processing + literature, where it is used as one of many windowing functions for + smoothing values. It is also known as an apodization (which means + "removing the foot", i.e. smoothing discontinuities at the beginning + and end of the sampled signal) or tapering function. + + References + ---------- + .. [1] J. F. Kaiser, "Digital Filters" - Ch 7 in "Systems analysis by + digital computer", Editors: F.F. Kuo and J.F. Kaiser, p 218-285. + John Wiley and Sons, New York, (1966). + .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The + University of Alberta Press, 1975, pp. 177-178. + .. [3] Wikipedia, "Window function", + https://en.wikipedia.org/wiki/Window_function + .. [4] F. J. Harris, "On the use of windows for harmonic analysis with the + discrete Fourier transform," Proceedings of the IEEE, vol. 66, + no. 1, pp. 51-83, Jan. 1978. :doi:`10.1109/PROC.1978.10837`. + + Examples + -------- + Plot the window and its frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> window = signal.windows.kaiser(51, beta=14) + >>> plt.plot(window) + >>> plt.title(r"Kaiser window ($\beta$=14)") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + + >>> plt.figure() + >>> A = fft(window, 2048) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) + >>> plt.plot(freq, response) + >>> plt.axis([-0.5, 0.5, -120, 0]) + >>> plt.title(r"Frequency response of the Kaiser window ($\beta$=14)") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + + """ + # Docstring adapted from NumPy's kaiser function + if _len_guards(M): + return np.ones(M) + M, needs_trunc = _extend(M, sym) + + n = np.arange(0, M) + alpha = (M - 1) / 2.0 + w = (special.i0(beta * np.sqrt(1 - ((n - alpha) / alpha) ** 2.0)) / + special.i0(beta)) + + return _truncate(w, needs_trunc) + + +def kaiser_bessel_derived(M, beta, *, sym=True): + """Return a Kaiser-Bessel derived window. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + Note that this window is only defined for an even + number of points. + beta : float + Kaiser window shape parameter. + sym : bool, optional + This parameter only exists to comply with the interface offered by + the other window functions and to be callable by `get_window`. + When True (default), generates a symmetric window, for use in filter + design. + + Returns + ------- + w : ndarray + The window, normalized to fulfil the Princen-Bradley condition. + + See Also + -------- + kaiser + + Notes + ----- + It is designed to be suitable for use with the modified discrete cosine + transform (MDCT) and is mainly used in audio signal processing and + audio coding. + + .. versionadded:: 1.9.0 + + References + ---------- + .. [1] Bosi, Marina, and Richard E. Goldberg. Introduction to Digital + Audio Coding and Standards. Dordrecht: Kluwer, 2003. + .. [2] Wikipedia, "Kaiser window", + https://en.wikipedia.org/wiki/Kaiser_window + + Examples + -------- + Plot the Kaiser-Bessel derived window based on the wikipedia + reference [2]_: + + >>> import numpy as np + >>> from scipy import signal + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots() + >>> N = 50 + >>> for alpha in [0.64, 2.55, 7.64, 31.83]: + ... ax.plot(signal.windows.kaiser_bessel_derived(2*N, np.pi*alpha), + ... label=f"{alpha=}") + >>> ax.grid(True) + >>> ax.set_title("Kaiser-Bessel derived window") + >>> ax.set_ylabel("Amplitude") + >>> ax.set_xlabel("Sample") + >>> ax.set_xticks([0, N, 2*N-1]) + >>> ax.set_xticklabels(["0", "N", "2N+1"]) # doctest: +SKIP + >>> ax.set_yticks([0.0, 0.2, 0.4, 0.6, 0.707, 0.8, 1.0]) + >>> fig.legend(loc="center") + >>> fig.tight_layout() + >>> fig.show() + """ + if not sym: + raise ValueError( + "Kaiser-Bessel Derived windows are only defined for symmetric " + "shapes" + ) + elif M < 1: + return np.array([]) + elif M % 2: + raise ValueError( + "Kaiser-Bessel Derived windows are only defined for even number " + "of points" + ) + + kaiser_window = kaiser(M // 2 + 1, beta) + csum = np.cumsum(kaiser_window) + half_window = np.sqrt(csum[:-1] / csum[-1]) + w = np.concatenate((half_window, half_window[::-1]), axis=0) + return w + + +def gaussian(M, std, sym=True): + r"""Return a Gaussian window. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + std : float + The standard deviation, sigma. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The window, with the maximum value normalized to 1 (though the value 1 + does not appear if `M` is even and `sym` is True). + + Notes + ----- + The Gaussian window is defined as + + .. math:: w(n) = e^{ -\frac{1}{2}\left(\frac{n}{\sigma}\right)^2 } + + Examples + -------- + Plot the window and its frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> window = signal.windows.gaussian(51, std=7) + >>> plt.plot(window) + >>> plt.title(r"Gaussian window ($\sigma$=7)") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + + >>> plt.figure() + >>> A = fft(window, 2048) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) + >>> plt.plot(freq, response) + >>> plt.axis([-0.5, 0.5, -120, 0]) + >>> plt.title(r"Frequency response of the Gaussian window ($\sigma$=7)") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + + """ + if _len_guards(M): + return np.ones(M) + M, needs_trunc = _extend(M, sym) + + n = np.arange(0, M) - (M - 1.0) / 2.0 + sig2 = 2 * std * std + w = np.exp(-n ** 2 / sig2) + + return _truncate(w, needs_trunc) + + +def general_gaussian(M, p, sig, sym=True): + r"""Return a window with a generalized Gaussian shape. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + p : float + Shape parameter. p = 1 is identical to `gaussian`, p = 0.5 is + the same shape as the Laplace distribution. + sig : float + The standard deviation, sigma. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The window, with the maximum value normalized to 1 (though the value 1 + does not appear if `M` is even and `sym` is True). + + Notes + ----- + The generalized Gaussian window is defined as + + .. math:: w(n) = e^{ -\frac{1}{2}\left|\frac{n}{\sigma}\right|^{2p} } + + the half-power point is at + + .. math:: (2 \log(2))^{1/(2 p)} \sigma + + Examples + -------- + Plot the window and its frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> window = signal.windows.general_gaussian(51, p=1.5, sig=7) + >>> plt.plot(window) + >>> plt.title(r"Generalized Gaussian window (p=1.5, $\sigma$=7)") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + + >>> plt.figure() + >>> A = fft(window, 2048) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) + >>> plt.plot(freq, response) + >>> plt.axis([-0.5, 0.5, -120, 0]) + >>> plt.title(r"Freq. resp. of the gen. Gaussian " + ... r"window (p=1.5, $\sigma$=7)") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + + """ + if _len_guards(M): + return np.ones(M) + M, needs_trunc = _extend(M, sym) + + n = np.arange(0, M) - (M - 1.0) / 2.0 + w = np.exp(-0.5 * np.abs(n / sig) ** (2 * p)) + + return _truncate(w, needs_trunc) + + +# `chebwin` contributed by Kumar Appaiah. +def chebwin(M, at, sym=True): + r"""Return a Dolph-Chebyshev window. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + at : float + Attenuation (in dB). + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The window, with the maximum value always normalized to 1 + + Notes + ----- + This window optimizes for the narrowest main lobe width for a given order + `M` and sidelobe equiripple attenuation `at`, using Chebyshev + polynomials. It was originally developed by Dolph to optimize the + directionality of radio antenna arrays. + + Unlike most windows, the Dolph-Chebyshev is defined in terms of its + frequency response: + + .. math:: W(k) = \frac + {\cos\{M \cos^{-1}[\beta \cos(\frac{\pi k}{M})]\}} + {\cosh[M \cosh^{-1}(\beta)]} + + where + + .. math:: \beta = \cosh \left [\frac{1}{M} + \cosh^{-1}(10^\frac{A}{20}) \right ] + + and 0 <= abs(k) <= M-1. A is the attenuation in decibels (`at`). + + The time domain window is then generated using the IFFT, so + power-of-two `M` are the fastest to generate, and prime number `M` are + the slowest. + + The equiripple condition in the frequency domain creates impulses in the + time domain, which appear at the ends of the window. + + References + ---------- + .. [1] C. Dolph, "A current distribution for broadside arrays which + optimizes the relationship between beam width and side-lobe level", + Proceedings of the IEEE, Vol. 34, Issue 6 + .. [2] Peter Lynch, "The Dolph-Chebyshev Window: A Simple Optimal Filter", + American Meteorological Society (April 1997) + http://mathsci.ucd.ie/~plynch/Publications/Dolph.pdf + .. [3] F. J. Harris, "On the use of windows for harmonic analysis with the + discrete Fourier transforms", Proceedings of the IEEE, Vol. 66, + No. 1, January 1978 + + Examples + -------- + Plot the window and its frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> window = signal.windows.chebwin(51, at=100) + >>> plt.plot(window) + >>> plt.title("Dolph-Chebyshev window (100 dB)") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + + >>> plt.figure() + >>> A = fft(window, 2048) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) + >>> plt.plot(freq, response) + >>> plt.axis([-0.5, 0.5, -120, 0]) + >>> plt.title("Frequency response of the Dolph-Chebyshev window (100 dB)") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + + """ + if np.abs(at) < 45: + warnings.warn("This window is not suitable for spectral analysis " + "for attenuation values lower than about 45dB because " + "the equivalent noise bandwidth of a Chebyshev window " + "does not grow monotonically with increasing sidelobe " + "attenuation when the attenuation is smaller than " + "about 45 dB.", + stacklevel=2) + if _len_guards(M): + return np.ones(M) + M, needs_trunc = _extend(M, sym) + + # compute the parameter beta + order = M - 1.0 + beta = np.cosh(1.0 / order * np.arccosh(10 ** (np.abs(at) / 20.))) + k = np.r_[0:M] * 1.0 + x = beta * np.cos(np.pi * k / M) + # Find the window's DFT coefficients + # Use analytic definition of Chebyshev polynomial instead of expansion + # from scipy.special. Using the expansion in scipy.special leads to errors. + p = np.zeros(x.shape) + p[x > 1] = np.cosh(order * np.arccosh(x[x > 1])) + p[x < -1] = (2 * (M % 2) - 1) * np.cosh(order * np.arccosh(-x[x < -1])) + p[np.abs(x) <= 1] = np.cos(order * np.arccos(x[np.abs(x) <= 1])) + + # Appropriate IDFT and filling up + # depending on even/odd M + if M % 2: + w = np.real(sp_fft.fft(p)) + n = (M + 1) // 2 + w = w[:n] + w = np.concatenate((w[n - 1:0:-1], w)) + else: + p = p * np.exp(1.j * np.pi / M * np.r_[0:M]) + w = np.real(sp_fft.fft(p)) + n = M // 2 + 1 + w = np.concatenate((w[n - 1:0:-1], w[1:n])) + w = w / max(w) + + return _truncate(w, needs_trunc) + + +def cosine(M, sym=True): + """Return a window with a simple cosine shape. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The window, with the maximum value normalized to 1 (though the value 1 + does not appear if `M` is even and `sym` is True). + + Notes + ----- + + .. versionadded:: 0.13.0 + + Examples + -------- + Plot the window and its frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> window = signal.windows.cosine(51) + >>> plt.plot(window) + >>> plt.title("Cosine window") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + + >>> plt.figure() + >>> A = fft(window, 2047) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) + >>> plt.plot(freq, response) + >>> plt.axis([-0.5, 0.5, -120, 0]) + >>> plt.title("Frequency response of the cosine window") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + >>> plt.show() + + """ + if _len_guards(M): + return np.ones(M) + M, needs_trunc = _extend(M, sym) + + w = np.sin(np.pi / M * (np.arange(0, M) + .5)) + + return _truncate(w, needs_trunc) + + +def exponential(M, center=None, tau=1., sym=True): + r"""Return an exponential (or Poisson) window. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + center : float, optional + Parameter defining the center location of the window function. + The default value if not given is ``center = (M-1) / 2``. This + parameter must take its default value for symmetric windows. + tau : float, optional + Parameter defining the decay. For ``center = 0`` use + ``tau = -(M-1) / ln(x)`` if ``x`` is the fraction of the window + remaining at the end. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The window, with the maximum value normalized to 1 (though the value 1 + does not appear if `M` is even and `sym` is True). + + Notes + ----- + The Exponential window is defined as + + .. math:: w(n) = e^{-|n-center| / \tau} + + References + ---------- + .. [1] S. Gade and H. Herlufsen, "Windows to FFT analysis (Part I)", + Technical Review 3, Bruel & Kjaer, 1987. + + Examples + -------- + Plot the symmetric window and its frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> M = 51 + >>> tau = 3.0 + >>> window = signal.windows.exponential(M, tau=tau) + >>> plt.plot(window) + >>> plt.title("Exponential Window (tau=3.0)") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + + >>> plt.figure() + >>> A = fft(window, 2048) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) + >>> plt.plot(freq, response) + >>> plt.axis([-0.5, 0.5, -35, 0]) + >>> plt.title("Frequency response of the Exponential window (tau=3.0)") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + + This function can also generate non-symmetric windows: + + >>> tau2 = -(M-1) / np.log(0.01) + >>> window2 = signal.windows.exponential(M, 0, tau2, False) + >>> plt.figure() + >>> plt.plot(window2) + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + """ + if sym and center is not None: + raise ValueError("If sym==True, center must be None.") + if _len_guards(M): + return np.ones(M) + M, needs_trunc = _extend(M, sym) + + if center is None: + center = (M-1) / 2 + + n = np.arange(0, M) + w = np.exp(-np.abs(n-center) / tau) + + return _truncate(w, needs_trunc) + + +def taylor(M, nbar=4, sll=30, norm=True, sym=True): + """ + Return a Taylor window. + + The Taylor window taper function approximates the Dolph-Chebyshev window's + constant sidelobe level for a parameterized number of near-in sidelobes, + but then allows a taper beyond [2]_. + + The SAR (synthetic aperture radar) community commonly uses Taylor + weighting for image formation processing because it provides strong, + selectable sidelobe suppression with minimum broadening of the + mainlobe [1]_. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + nbar : int, optional + Number of nearly constant level sidelobes adjacent to the mainlobe. + sll : float, optional + Desired suppression of sidelobe level in decibels (dB) relative to the + DC gain of the mainlobe. This should be a positive number. + norm : bool, optional + When True (default), divides the window by the largest (middle) value + for odd-length windows or the value that would occur between the two + repeated middle values for even-length windows such that all values + are less than or equal to 1. When False the DC gain will remain at 1 + (0 dB) and the sidelobes will be `sll` dB down. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + out : array + The window. When `norm` is True (default), the maximum value is + normalized to 1 (though the value 1 does not appear if `M` is + even and `sym` is True). + + See Also + -------- + chebwin, kaiser, bartlett, blackman, hamming, hann + + References + ---------- + .. [1] W. Carrara, R. Goodman, and R. Majewski, "Spotlight Synthetic + Aperture Radar: Signal Processing Algorithms" Pages 512-513, + July 1995. + .. [2] Armin Doerry, "Catalog of Window Taper Functions for + Sidelobe Control", 2017. + https://www.researchgate.net/profile/Armin_Doerry/publication/316281181_Catalog_of_Window_Taper_Functions_for_Sidelobe_Control/links/58f92cb2a6fdccb121c9d54d/Catalog-of-Window-Taper-Functions-for-Sidelobe-Control.pdf + + Examples + -------- + Plot the window and its frequency response: + + >>> import numpy as np + >>> from scipy import signal + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + + >>> window = signal.windows.taylor(51, nbar=20, sll=100, norm=False) + >>> plt.plot(window) + >>> plt.title("Taylor window (100 dB)") + >>> plt.ylabel("Amplitude") + >>> plt.xlabel("Sample") + + >>> plt.figure() + >>> A = fft(window, 2048) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) + >>> plt.plot(freq, response) + >>> plt.axis([-0.5, 0.5, -120, 0]) + >>> plt.title("Frequency response of the Taylor window (100 dB)") + >>> plt.ylabel("Normalized magnitude [dB]") + >>> plt.xlabel("Normalized frequency [cycles per sample]") + + """ # noqa: E501 + if _len_guards(M): + return np.ones(M) + M, needs_trunc = _extend(M, sym) + + # Original text uses a negative sidelobe level parameter and then negates + # it in the calculation of B. To keep consistent with other methods we + # assume the sidelobe level parameter to be positive. + B = 10**(sll / 20) + A = np.arccosh(B) / np.pi + s2 = nbar**2 / (A**2 + (nbar - 0.5)**2) + ma = np.arange(1, nbar) + + Fm = np.empty(nbar-1) + signs = np.empty_like(ma) + signs[::2] = 1 + signs[1::2] = -1 + m2 = ma*ma + for mi, m in enumerate(ma): + numer = signs[mi] * np.prod(1 - m2[mi]/s2/(A**2 + (ma - 0.5)**2)) + denom = 2 * np.prod(1 - m2[mi]/m2[:mi]) * np.prod(1 - m2[mi]/m2[mi+1:]) + Fm[mi] = numer / denom + + def W(n): + return 1 + 2*np.dot(Fm, np.cos( + 2*np.pi*ma[:, np.newaxis]*(n-M/2.+0.5)/M)) + + w = W(np.arange(M)) + + # normalize (Note that this is not described in the original text [1]) + if norm: + scale = 1.0 / W((M - 1) / 2) + w *= scale + + return _truncate(w, needs_trunc) + + +def dpss(M, NW, Kmax=None, sym=True, norm=None, return_ratios=False): + """ + Compute the Discrete Prolate Spheroidal Sequences (DPSS). + + DPSS (or Slepian sequences) are often used in multitaper power spectral + density estimation (see [1]_). The first window in the sequence can be + used to maximize the energy concentration in the main lobe, and is also + called the Slepian window. + + Parameters + ---------- + M : int + Window length. + NW : float + Standardized half bandwidth corresponding to ``2*NW = BW/f0 = BW*M*dt`` + where ``dt`` is taken as 1. + Kmax : int | None, optional + Number of DPSS windows to return (orders ``0`` through ``Kmax-1``). + If None (default), return only a single window of shape ``(M,)`` + instead of an array of windows of shape ``(Kmax, M)``. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + norm : {2, 'approximate', 'subsample'} | None, optional + If 'approximate' or 'subsample', then the windows are normalized by the + maximum, and a correction scale-factor for even-length windows + is applied either using ``M**2/(M**2+NW)`` ("approximate") or + a FFT-based subsample shift ("subsample"), see Notes for details. + If None, then "approximate" is used when ``Kmax=None`` and 2 otherwise + (which uses the l2 norm). + return_ratios : bool, optional + If True, also return the concentration ratios in addition to the + windows. + + Returns + ------- + v : ndarray, shape (Kmax, M) or (M,) + The DPSS windows. Will be 1D if `Kmax` is None. + r : ndarray, shape (Kmax,) or float, optional + The concentration ratios for the windows. Only returned if + `return_ratios` evaluates to True. Will be 0D if `Kmax` is None. + + Notes + ----- + This computation uses the tridiagonal eigenvector formulation given + in [2]_. + + The default normalization for ``Kmax=None``, i.e. window-generation mode, + simply using the l-infinity norm would create a window with two unity + values, which creates slight normalization differences between even and odd + orders. The approximate correction of ``M**2/float(M**2+NW)`` for even + sample numbers is used to counteract this effect (see Examples below). + + For very long signals (e.g., 1e6 elements), it can be useful to compute + windows orders of magnitude shorter and use interpolation (e.g., + `scipy.interpolate.interp1d`) to obtain tapers of length `M`, + but this in general will not preserve orthogonality between the tapers. + + .. versionadded:: 1.1 + + References + ---------- + .. [1] Percival DB, Walden WT. Spectral Analysis for Physical Applications: + Multitaper and Conventional Univariate Techniques. + Cambridge University Press; 1993. + .. [2] Slepian, D. Prolate spheroidal wave functions, Fourier analysis, and + uncertainty V: The discrete case. Bell System Technical Journal, + Volume 57 (1978), 1371430. + .. [3] Kaiser, JF, Schafer RW. On the Use of the I0-Sinh Window for + Spectrum Analysis. IEEE Transactions on Acoustics, Speech and + Signal Processing. ASSP-28 (1): 105-107; 1980. + + Examples + -------- + We can compare the window to `kaiser`, which was invented as an alternative + that was easier to calculate [3]_ (example adapted from + `here `_): + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.signal import windows, freqz + >>> M = 51 + >>> fig, axes = plt.subplots(3, 2, figsize=(5, 7)) + >>> for ai, alpha in enumerate((1, 3, 5)): + ... win_dpss = windows.dpss(M, alpha) + ... beta = alpha*np.pi + ... win_kaiser = windows.kaiser(M, beta) + ... for win, c in ((win_dpss, 'k'), (win_kaiser, 'r')): + ... win /= win.sum() + ... axes[ai, 0].plot(win, color=c, lw=1.) + ... axes[ai, 0].set(xlim=[0, M-1], title=r'$\\alpha$ = %s' % alpha, + ... ylabel='Amplitude') + ... w, h = freqz(win) + ... axes[ai, 1].plot(w, 20 * np.log10(np.abs(h)), color=c, lw=1.) + ... axes[ai, 1].set(xlim=[0, np.pi], + ... title=r'$\\beta$ = %0.2f' % beta, + ... ylabel='Magnitude (dB)') + >>> for ax in axes.ravel(): + ... ax.grid(True) + >>> axes[2, 1].legend(['DPSS', 'Kaiser']) + >>> fig.tight_layout() + >>> plt.show() + + And here are examples of the first four windows, along with their + concentration ratios: + + >>> M = 512 + >>> NW = 2.5 + >>> win, eigvals = windows.dpss(M, NW, 4, return_ratios=True) + >>> fig, ax = plt.subplots(1) + >>> ax.plot(win.T, linewidth=1.) + >>> ax.set(xlim=[0, M-1], ylim=[-0.1, 0.1], xlabel='Samples', + ... title='DPSS, M=%d, NW=%0.1f' % (M, NW)) + >>> ax.legend(['win[%d] (%0.4f)' % (ii, ratio) + ... for ii, ratio in enumerate(eigvals)]) + >>> fig.tight_layout() + >>> plt.show() + + Using a standard :math:`l_{\\infty}` norm would produce two unity values + for even `M`, but only one unity value for odd `M`. This produces uneven + window power that can be counteracted by the approximate correction + ``M**2/float(M**2+NW)``, which can be selected by using + ``norm='approximate'`` (which is the same as ``norm=None`` when + ``Kmax=None``, as is the case here). Alternatively, the slower + ``norm='subsample'`` can be used, which uses subsample shifting in the + frequency domain (FFT) to compute the correction: + + >>> Ms = np.arange(1, 41) + >>> factors = (50, 20, 10, 5, 2.0001) + >>> energy = np.empty((3, len(Ms), len(factors))) + >>> for mi, M in enumerate(Ms): + ... for fi, factor in enumerate(factors): + ... NW = M / float(factor) + ... # Corrected using empirical approximation (default) + ... win = windows.dpss(M, NW) + ... energy[0, mi, fi] = np.sum(win ** 2) / np.sqrt(M) + ... # Corrected using subsample shifting + ... win = windows.dpss(M, NW, norm='subsample') + ... energy[1, mi, fi] = np.sum(win ** 2) / np.sqrt(M) + ... # Uncorrected (using l-infinity norm) + ... win /= win.max() + ... energy[2, mi, fi] = np.sum(win ** 2) / np.sqrt(M) + >>> fig, ax = plt.subplots(1) + >>> hs = ax.plot(Ms, energy[2], '-o', markersize=4, + ... markeredgecolor='none') + >>> leg = [hs[-1]] + >>> for hi, hh in enumerate(hs): + ... h1 = ax.plot(Ms, energy[0, :, hi], '-o', markersize=4, + ... color=hh.get_color(), markeredgecolor='none', + ... alpha=0.66) + ... h2 = ax.plot(Ms, energy[1, :, hi], '-o', markersize=4, + ... color=hh.get_color(), markeredgecolor='none', + ... alpha=0.33) + ... if hi == len(hs) - 1: + ... leg.insert(0, h1[0]) + ... leg.insert(0, h2[0]) + >>> ax.set(xlabel='M (samples)', ylabel=r'Power / $\\sqrt{M}$') + >>> ax.legend(leg, ['Uncorrected', r'Corrected: $\\frac{M^2}{M^2+NW}$', + ... 'Corrected (subsample)']) + >>> fig.tight_layout() + + """ + if _len_guards(M): + return np.ones(M) + if norm is None: + norm = 'approximate' if Kmax is None else 2 + known_norms = (2, 'approximate', 'subsample') + if norm not in known_norms: + raise ValueError(f'norm must be one of {known_norms}, got {norm}') + if Kmax is None: + singleton = True + Kmax = 1 + else: + singleton = False + Kmax = operator.index(Kmax) + if not 0 < Kmax <= M: + raise ValueError('Kmax must be greater than 0 and less than M') + if NW >= M/2.: + raise ValueError('NW must be less than M/2.') + if NW <= 0: + raise ValueError('NW must be positive') + M, needs_trunc = _extend(M, sym) + W = float(NW) / M + nidx = np.arange(M) + + # Here we want to set up an optimization problem to find a sequence + # whose energy is maximally concentrated within band [-W,W]. + # Thus, the measure lambda(T,W) is the ratio between the energy within + # that band, and the total energy. This leads to the eigen-system + # (A - (l1)I)v = 0, where the eigenvector corresponding to the largest + # eigenvalue is the sequence with maximally concentrated energy. The + # collection of eigenvectors of this system are called Slepian + # sequences, or discrete prolate spheroidal sequences (DPSS). Only the + # first K, K = 2NW/dt orders of DPSS will exhibit good spectral + # concentration + # [see https://en.wikipedia.org/wiki/Spectral_concentration_problem] + + # Here we set up an alternative symmetric tri-diagonal eigenvalue + # problem such that + # (B - (l2)I)v = 0, and v are our DPSS (but eigenvalues l2 != l1) + # the main diagonal = ([M-1-2*t]/2)**2 cos(2PIW), t=[0,1,2,...,M-1] + # and the first off-diagonal = t(M-t)/2, t=[1,2,...,M-1] + # [see Percival and Walden, 1993] + d = ((M - 1 - 2 * nidx) / 2.) ** 2 * np.cos(2 * np.pi * W) + e = nidx[1:] * (M - nidx[1:]) / 2. + + # only calculate the highest Kmax eigenvalues + w, windows = linalg.eigh_tridiagonal( + d, e, select='i', select_range=(M - Kmax, M - 1)) + w = w[::-1] + windows = windows[:, ::-1].T + + # By convention (Percival and Walden, 1993 pg 379) + # * symmetric tapers (k=0,2,4,...) should have a positive average. + fix_even = (windows[::2].sum(axis=1) < 0) + for i, f in enumerate(fix_even): + if f: + windows[2 * i] *= -1 + # * antisymmetric tapers should begin with a positive lobe + # (this depends on the definition of "lobe", here we'll take the first + # point above the numerical noise, which should be good enough for + # sufficiently smooth functions, and more robust than relying on an + # algorithm that uses max(abs(w)), which is susceptible to numerical + # noise problems) + thresh = max(1e-7, 1. / M) + for i, w in enumerate(windows[1::2]): + if w[w * w > thresh][0] < 0: + windows[2 * i + 1] *= -1 + + # Now find the eigenvalues of the original spectral concentration problem + # Use the autocorr sequence technique from Percival and Walden, 1993 pg 390 + if return_ratios: + dpss_rxx = _fftautocorr(windows) + r = 4 * W * np.sinc(2 * W * nidx) + r[0] = 2 * W + ratios = np.dot(dpss_rxx, r) + if singleton: + ratios = ratios[0] + # Deal with sym and Kmax=None + if norm != 2: + windows /= windows.max() + if M % 2 == 0: + if norm == 'approximate': + correction = M**2 / float(M**2 + NW) + else: + s = sp_fft.rfft(windows[0]) + shift = -(1 - 1./M) * np.arange(1, M//2 + 1) + s[1:] *= 2 * np.exp(-1j * np.pi * shift) + correction = M / s.real.sum() + windows *= correction + # else we're already l2 normed, so do nothing + if needs_trunc: + windows = windows[:, :-1] + if singleton: + windows = windows[0] + return (windows, ratios) if return_ratios else windows + + +def lanczos(M, *, sym=True): + r"""Return a Lanczos window also known as a sinc window. + + Parameters + ---------- + M : int + Number of points in the output window. If zero, an empty array + is returned. An exception is thrown when it is negative. + sym : bool, optional + When True (default), generates a symmetric window, for use in filter + design. + When False, generates a periodic window, for use in spectral analysis. + + Returns + ------- + w : ndarray + The window, with the maximum value normalized to 1 (though the value 1 + does not appear if `M` is even and `sym` is True). + + Notes + ----- + The Lanczos window is defined as + + .. math:: w(n) = sinc \left( \frac{2n}{M - 1} - 1 \right) + + where + + .. math:: sinc(x) = \frac{\sin(\pi x)}{\pi x} + + The Lanczos window has reduced Gibbs oscillations and is widely used for + filtering climate timeseries with good properties in the physical and + spectral domains. + + .. versionadded:: 1.10 + + References + ---------- + .. [1] Lanczos, C., and Teichmann, T. (1957). Applied analysis. + Physics Today, 10, 44. + .. [2] Duchon C. E. (1979) Lanczos Filtering in One and Two Dimensions. + Journal of Applied Meteorology, Vol 18, pp 1016-1022. + .. [3] Thomson, R. E. and Emery, W. J. (2014) Data Analysis Methods in + Physical Oceanography (Third Edition), Elsevier, pp 593-637. + .. [4] Wikipedia, "Window function", + http://en.wikipedia.org/wiki/Window_function + + Examples + -------- + Plot the window + + >>> import numpy as np + >>> from scipy.signal.windows import lanczos + >>> from scipy.fft import fft, fftshift + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots(1) + >>> window = lanczos(51) + >>> ax.plot(window) + >>> ax.set_title("Lanczos window") + >>> ax.set_ylabel("Amplitude") + >>> ax.set_xlabel("Sample") + >>> fig.tight_layout() + >>> plt.show() + + and its frequency response: + + >>> fig, ax = plt.subplots(1) + >>> A = fft(window, 2048) / (len(window)/2.0) + >>> freq = np.linspace(-0.5, 0.5, len(A)) + >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) + >>> ax.plot(freq, response) + >>> ax.set_xlim(-0.5, 0.5) + >>> ax.set_ylim(-120, 0) + >>> ax.set_title("Frequency response of the lanczos window") + >>> ax.set_ylabel("Normalized magnitude [dB]") + >>> ax.set_xlabel("Normalized frequency [cycles per sample]") + >>> fig.tight_layout() + >>> plt.show() + """ + if _len_guards(M): + return np.ones(M) + M, needs_trunc = _extend(M, sym) + + # To make sure that the window is symmetric, we concatenate the right hand + # half of the window and the flipped one which is the left hand half of + # the window. + def _calc_right_side_lanczos(n, m): + return np.sinc(2. * np.arange(n, m) / (m - 1) - 1.0) + + if M % 2 == 0: + wh = _calc_right_side_lanczos(M/2, M) + w = np.r_[np.flip(wh), wh] + else: + wh = _calc_right_side_lanczos((M+1)/2, M) + w = np.r_[np.flip(wh), 1.0, wh] + + return _truncate(w, needs_trunc) + + +def _fftautocorr(x): + """Compute the autocorrelation of a real array and crop the result.""" + N = x.shape[-1] + use_N = sp_fft.next_fast_len(2*N-1) + x_fft = sp_fft.rfft(x, use_N, axis=-1) + cxy = sp_fft.irfft(x_fft * x_fft.conj(), n=use_N)[:, :N] + # Or equivalently (but in most cases slower): + # cxy = np.array([np.convolve(xx, yy[::-1], mode='full') + # for xx, yy in zip(x, x)])[:, N-1:2*N-1] + return cxy + + +_win_equiv_raw = { + ('barthann', 'brthan', 'bth'): (barthann, False), + ('bartlett', 'bart', 'brt'): (bartlett, False), + ('blackman', 'black', 'blk'): (blackman, False), + ('blackmanharris', 'blackharr', 'bkh'): (blackmanharris, False), + ('bohman', 'bman', 'bmn'): (bohman, False), + ('boxcar', 'box', 'ones', + 'rect', 'rectangular'): (boxcar, False), + ('chebwin', 'cheb'): (chebwin, True), + ('cosine', 'halfcosine'): (cosine, False), + ('dpss',): (dpss, True), + ('exponential', 'poisson'): (exponential, False), + ('flattop', 'flat', 'flt'): (flattop, False), + ('gaussian', 'gauss', 'gss'): (gaussian, True), + ('general cosine', 'general_cosine'): (general_cosine, True), + ('general gaussian', 'general_gaussian', + 'general gauss', 'general_gauss', 'ggs'): (general_gaussian, True), + ('general hamming', 'general_hamming'): (general_hamming, True), + ('hamming', 'hamm', 'ham'): (hamming, False), + ('hann', 'han'): (hann, False), + ('kaiser', 'ksr'): (kaiser, True), + ('kaiser bessel derived', 'kbd'): (kaiser_bessel_derived, True), + ('lanczos', 'sinc'): (lanczos, False), + ('nuttall', 'nutl', 'nut'): (nuttall, False), + ('parzen', 'parz', 'par'): (parzen, False), + ('taylor', 'taylorwin'): (taylor, False), + ('triangle', 'triang', 'tri'): (triang, False), + ('tukey', 'tuk'): (tukey, False), +} + +# Fill dict with all valid window name strings +_win_equiv = {} +for k, v in _win_equiv_raw.items(): + for key in k: + _win_equiv[key] = v[0] + +# Keep track of which windows need additional parameters +_needs_param = set() +for k, v in _win_equiv_raw.items(): + if v[1]: + _needs_param.update(k) + + +def get_window(window, Nx, fftbins=True): + """ + Return a window of a given length and type. + + Parameters + ---------- + window : string, float, or tuple + The type of window to create. See below for more details. + Nx : int + The number of samples in the window. + fftbins : bool, optional + If True (default), create a "periodic" window, ready to use with + `ifftshift` and be multiplied by the result of an FFT (see also + :func:`~scipy.fft.fftfreq`). + If False, create a "symmetric" window, for use in filter design. + + Returns + ------- + get_window : ndarray + Returns a window of length `Nx` and type `window` + + Notes + ----- + Window types: + + - `~scipy.signal.windows.boxcar` + - `~scipy.signal.windows.triang` + - `~scipy.signal.windows.blackman` + - `~scipy.signal.windows.hamming` + - `~scipy.signal.windows.hann` + - `~scipy.signal.windows.bartlett` + - `~scipy.signal.windows.flattop` + - `~scipy.signal.windows.parzen` + - `~scipy.signal.windows.bohman` + - `~scipy.signal.windows.blackmanharris` + - `~scipy.signal.windows.nuttall` + - `~scipy.signal.windows.barthann` + - `~scipy.signal.windows.cosine` + - `~scipy.signal.windows.exponential` + - `~scipy.signal.windows.tukey` + - `~scipy.signal.windows.taylor` + - `~scipy.signal.windows.lanczos` + - `~scipy.signal.windows.kaiser` (needs beta) + - `~scipy.signal.windows.kaiser_bessel_derived` (needs beta) + - `~scipy.signal.windows.gaussian` (needs standard deviation) + - `~scipy.signal.windows.general_cosine` (needs weighting coefficients) + - `~scipy.signal.windows.general_gaussian` (needs power, width) + - `~scipy.signal.windows.general_hamming` (needs window coefficient) + - `~scipy.signal.windows.dpss` (needs normalized half-bandwidth) + - `~scipy.signal.windows.chebwin` (needs attenuation) + + + If the window requires no parameters, then `window` can be a string. + + If the window requires parameters, then `window` must be a tuple + with the first argument the string name of the window, and the next + arguments the needed parameters. + + If `window` is a floating point number, it is interpreted as the beta + parameter of the `~scipy.signal.windows.kaiser` window. + + Each of the window types listed above is also the name of + a function that can be called directly to create a window of + that type. + + Examples + -------- + >>> from scipy import signal + >>> signal.get_window('triang', 7) + array([ 0.125, 0.375, 0.625, 0.875, 0.875, 0.625, 0.375]) + >>> signal.get_window(('kaiser', 4.0), 9) + array([ 0.08848053, 0.29425961, 0.56437221, 0.82160913, 0.97885093, + 0.97885093, 0.82160913, 0.56437221, 0.29425961]) + >>> signal.get_window(('exponential', None, 1.), 9) + array([ 0.011109 , 0.03019738, 0.082085 , 0.22313016, 0.60653066, + 0.60653066, 0.22313016, 0.082085 , 0.03019738]) + >>> signal.get_window(4.0, 9) + array([ 0.08848053, 0.29425961, 0.56437221, 0.82160913, 0.97885093, + 0.97885093, 0.82160913, 0.56437221, 0.29425961]) + + """ + sym = not fftbins + try: + beta = float(window) + except (TypeError, ValueError) as e: + args = () + if isinstance(window, tuple): + winstr = window[0] + if len(window) > 1: + args = window[1:] + elif isinstance(window, str): + if window in _needs_param: + raise ValueError("The '" + window + "' window needs one or " + "more parameters -- pass a tuple.") from e + else: + winstr = window + else: + raise ValueError( + f"{str(type(window))} as window type is not supported.") from e + + try: + winfunc = _win_equiv[winstr] + except KeyError as e: + raise ValueError("Unknown window type.") from e + + if winfunc is dpss: + params = (Nx,) + args + (None,) + else: + params = (Nx,) + args + else: + winfunc = kaiser + params = (Nx, beta) + + return winfunc(*params, sym=sym) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/windows/windows.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/windows/windows.py new file mode 100644 index 0000000000000000000000000000000000000000..6858f71aceeb29ca6110864d01fb250e8c8ce403 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/signal/windows/windows.py @@ -0,0 +1,23 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.signal.windows` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__ = [ # noqa: F822 + 'boxcar', 'triang', 'parzen', 'bohman', 'blackman', 'nuttall', + 'blackmanharris', 'flattop', 'bartlett', 'barthann', + 'hamming', 'kaiser', 'gaussian', 'general_cosine', + 'general_gaussian', 'general_hamming', 'chebwin', 'cosine', + 'hann', 'exponential', 'tukey', 'taylor', 'dpss', 'get_window', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="signal.windows", module="windows", + private_modules=["_windows"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..18fe7e011db102f57a8263d1db343818715aeeee --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/__init__.py @@ -0,0 +1,331 @@ +""" +=================================== +Sparse arrays (:mod:`scipy.sparse`) +=================================== + +.. currentmodule:: scipy.sparse + +.. toctree:: + :hidden: + + sparse.csgraph + sparse.linalg + sparse.migration_to_sparray + +SciPy 2-D sparse array package for numeric data. + +.. note:: + + This package is switching to an array interface, compatible with + NumPy arrays, from the older matrix interface. We recommend that + you use the array objects (`bsr_array`, `coo_array`, etc.) for + all new work. + + When using the array interface, please note that: + + - ``x * y`` no longer performs matrix multiplication, but + element-wise multiplication (just like with NumPy arrays). To + make code work with both arrays and matrices, use ``x @ y`` for + matrix multiplication. + - Operations such as ``sum``, that used to produce dense matrices, now + produce arrays, whose multiplication behavior differs similarly. + - Sparse arrays use array style *slicing* operations, returning scalars, + 1D, or 2D sparse arrays. If you need 2D results, use an appropriate index. + E.g. ``A[:, i, None]`` or ``A[:, [i]]``. + + The construction utilities (`eye`, `kron`, `random`, `diags`, etc.) + have appropriate replacements (see :ref:`sparse-construction-functions`). + + For more information see + :ref:`Migration from spmatrix to sparray `. + + +Submodules +========== + +.. autosummary:: + + csgraph - Compressed sparse graph routines + linalg - Sparse linear algebra routines + + +Sparse array classes +==================== + +.. autosummary:: + :toctree: generated/ + + bsr_array - Block Sparse Row array + coo_array - A sparse array in COOrdinate format + csc_array - Compressed Sparse Column array + csr_array - Compressed Sparse Row array + dia_array - Sparse array with DIAgonal storage + dok_array - Dictionary Of Keys based sparse array + lil_array - Row-based list of lists sparse array + sparray - Sparse array base class + +.. _sparse-construction-functions: + +Building sparse arrays +---------------------- + +.. autosummary:: + :toctree: generated/ + + diags_array - Return a sparse array from diagonals + eye_array - Sparse MxN array whose k-th diagonal is all ones + random_array - Random values in a given shape array + block_array - Build a sparse array from sub-blocks + +.. _combining-arrays: + +Combining arrays +---------------- + +.. autosummary:: + :toctree: generated/ + + kron - Kronecker product of two sparse arrays + kronsum - Kronecker sum of sparse arrays + block_diag - Build a block diagonal sparse array + tril - Lower triangular portion of a sparse array + triu - Upper triangular portion of a sparse array + hstack - Stack sparse arrays horizontally (column wise) + vstack - Stack sparse arrays vertically (row wise) + +Sparse tools +------------ + +.. autosummary:: + :toctree: generated/ + + save_npz - Save a sparse array to a file using ``.npz`` format. + load_npz - Load a sparse array from a file using ``.npz`` format. + find - Return the indices and values of the nonzero elements + get_index_dtype - determine a good dtype for index arrays. + safely_cast_index_arrays - cast index array dtype or raise if shape too big + +Identifying sparse arrays +------------------------- + +.. autosummary:: + :toctree: generated/ + + issparse - Check if the argument is a sparse object (array or matrix). + + +Sparse matrix classes +===================== + +.. autosummary:: + :toctree: generated/ + + bsr_matrix - Block Sparse Row matrix + coo_matrix - A sparse matrix in COOrdinate format + csc_matrix - Compressed Sparse Column matrix + csr_matrix - Compressed Sparse Row matrix + dia_matrix - Sparse matrix with DIAgonal storage + dok_matrix - Dictionary Of Keys based sparse matrix + lil_matrix - Row-based list of lists sparse matrix + spmatrix - Sparse matrix base class + +Building sparse matrices +------------------------ + +.. autosummary:: + :toctree: generated/ + + eye - Sparse MxN matrix whose k-th diagonal is all ones + identity - Identity matrix in sparse matrix format + diags - Return a sparse matrix from diagonals + spdiags - Return a sparse matrix from diagonals + bmat - Build a sparse matrix from sparse sub-blocks + random - Random values in a given shape matrix + rand - Random values in a given shape matrix (old interface) + +**Combining matrices use the same functions as for** :ref:`combining-arrays`. + +Identifying sparse matrices +--------------------------- + +.. autosummary:: + :toctree: generated/ + + issparse + isspmatrix + isspmatrix_csc + isspmatrix_csr + isspmatrix_bsr + isspmatrix_lil + isspmatrix_dok + isspmatrix_coo + isspmatrix_dia + + +Warnings +======== + +.. autosummary:: + :toctree: generated/ + + SparseEfficiencyWarning + SparseWarning + + +Usage information +================= + +There are seven available sparse array types: + + 1. csc_array: Compressed Sparse Column format + 2. csr_array: Compressed Sparse Row format + 3. bsr_array: Block Sparse Row format + 4. lil_array: List of Lists format + 5. dok_array: Dictionary of Keys format + 6. coo_array: COOrdinate format (aka IJV, triplet format) + 7. dia_array: DIAgonal format + +To construct an array efficiently, use any of `coo_array`, +`dok_array` or `lil_array`. `dok_array` and `lil_array` +support basic slicing and fancy indexing with a similar syntax +to NumPy arrays. The COO format does not support indexing (yet) +but can also be used to efficiently construct arrays using coord +and value info. + +Despite their similarity to NumPy arrays, it is **strongly discouraged** +to use NumPy functions directly on these arrays because NumPy typically +treats them as generic Python objects rather than arrays, leading to +unexpected (and incorrect) results. If you do want to apply a NumPy +function to these arrays, first check if SciPy has its own implementation +for the given sparse array class, or **convert the sparse array to +a NumPy array** (e.g., using the `toarray` method of the class) +before applying the method. + +All conversions among the CSR, CSC, and COO formats are efficient, +linear-time operations. + +To perform manipulations such as multiplication or inversion, first +convert the array to either CSC or CSR format. The `lil_array` +format is row-based, so conversion to CSR is efficient, whereas +conversion to CSC is less so. + +Matrix vector product +--------------------- + +To do a vector product between a 2D sparse array and a vector use +the matmul operator (i.e., ``@``) which performs a dot product (like the +``dot`` method): + +>>> import numpy as np +>>> from scipy.sparse import csr_array +>>> A = csr_array([[1, 2, 0], [0, 0, 3], [4, 0, 5]]) +>>> v = np.array([1, 0, -1]) +>>> A @ v +array([ 1, -3, -1], dtype=int64) + +The CSR format is especially suitable for fast matrix vector products. + +Example 1 +--------- + +Construct a 1000x1000 `lil_array` and add some values to it: + +>>> from scipy.sparse import lil_array +>>> from scipy.sparse.linalg import spsolve +>>> from numpy.linalg import solve, norm +>>> from numpy.random import rand + +>>> A = lil_array((1000, 1000)) +>>> A[0, :100] = rand(100) +>>> A.setdiag(rand(1000)) + +Now convert it to CSR format and solve A x = b for x: + +>>> A = A.tocsr() +>>> b = rand(1000) +>>> x = spsolve(A, b) + +Convert it to a dense array and solve, and check that the result +is the same: + +>>> x_ = solve(A.toarray(), b) + +Now we can compute norm of the error with: + +>>> err = norm(x-x_) +>>> err < 1e-10 +True + +It should be small :) + + +Example 2 +--------- + +Construct an array in COO format: + +>>> from scipy import sparse +>>> from numpy import array +>>> I = array([0,3,1,0]) +>>> J = array([0,3,1,2]) +>>> V = array([4,5,7,9]) +>>> A = sparse.coo_array((V,(I,J)),shape=(4,4)) + +Notice that the indices do not need to be sorted. + +Duplicate (i,j) entries are summed when converting to CSR or CSC. + +>>> I = array([0,0,1,3,1,0,0]) +>>> J = array([0,2,1,3,1,0,0]) +>>> V = array([1,1,1,1,1,1,1]) +>>> B = sparse.coo_array((V,(I,J)),shape=(4,4)).tocsr() + +This is useful for constructing finite-element stiffness and mass matrices. + +Further details +--------------- + +CSR column indices are not necessarily sorted. Likewise for CSC row +indices. Use the ``.sorted_indices()`` and ``.sort_indices()`` methods when +sorted indices are required (e.g., when passing data to other libraries). + +""" + +# Original code by Travis Oliphant. +# Modified and extended by Ed Schofield, Robert Cimrman, +# Nathan Bell, and Jake Vanderplas. + +import warnings as _warnings + +from ._base import * +from ._csr import * +from ._csc import * +from ._lil import * +from ._dok import * +from ._coo import * +from ._dia import * +from ._bsr import * +from ._construct import * +from ._extract import * +from ._matrix import spmatrix +from ._matrix_io import * +from ._sputils import get_index_dtype, safely_cast_index_arrays + +# For backward compatibility with v0.19. +from . import csgraph + +# Deprecated namespaces, to be removed in v2.0.0 +from . import ( + base, bsr, compressed, construct, coo, csc, csr, data, dia, dok, extract, + lil, sparsetools, sputils +) + +__all__ = [s for s in dir() if not s.startswith('_')] + +# Filter PendingDeprecationWarning for np.matrix introduced with numpy 1.15 +msg = 'the matrix subclass is not the recommended way' +_warnings.filterwarnings('ignore', message=msg) + +from scipy._lib._testutils import PytestTester +test = PytestTester(__name__) +del PytestTester diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_base.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_base.py new file mode 100644 index 0000000000000000000000000000000000000000..926e191013c7cacebab7a8e025a017358ba82f50 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_base.py @@ -0,0 +1,1448 @@ +"""Base class for sparse matrices""" + +import numpy as np + +from ._sputils import (asmatrix, check_reshape_kwargs, check_shape, + get_sum_dtype, isdense, isscalarlike, + matrix, validateaxis, getdtype) + +from ._matrix import spmatrix + +__all__ = ['isspmatrix', 'issparse', 'sparray', + 'SparseWarning', 'SparseEfficiencyWarning'] + + +class SparseWarning(Warning): + pass + + +class SparseFormatWarning(SparseWarning): + pass + + +class SparseEfficiencyWarning(SparseWarning): + pass + + +# The formats that we might potentially understand. +_formats = {'csc': [0, "Compressed Sparse Column"], + 'csr': [1, "Compressed Sparse Row"], + 'dok': [2, "Dictionary Of Keys"], + 'lil': [3, "List of Lists"], + 'dod': [4, "Dictionary of Dictionaries"], + 'sss': [5, "Symmetric Sparse Skyline"], + 'coo': [6, "COOrdinate"], + 'lba': [7, "Linpack BAnded"], + 'egd': [8, "Ellpack-itpack Generalized Diagonal"], + 'dia': [9, "DIAgonal"], + 'bsr': [10, "Block Sparse Row"], + 'msr': [11, "Modified compressed Sparse Row"], + 'bsc': [12, "Block Sparse Column"], + 'msc': [13, "Modified compressed Sparse Column"], + 'ssk': [14, "Symmetric SKyline"], + 'nsk': [15, "Nonsymmetric SKyline"], + 'jad': [16, "JAgged Diagonal"], + 'uss': [17, "Unsymmetric Sparse Skyline"], + 'vbr': [18, "Variable Block Row"], + 'und': [19, "Undefined"] + } + + +# These univariate ufuncs preserve zeros. +_ufuncs_with_fixed_point_at_zero = frozenset([ + np.sin, np.tan, np.arcsin, np.arctan, np.sinh, np.tanh, np.arcsinh, + np.arctanh, np.rint, np.sign, np.expm1, np.log1p, np.deg2rad, + np.rad2deg, np.floor, np.ceil, np.trunc, np.sqrt]) + + +MAXPRINT = 50 + + +class _spbase: + """ This class provides a base class for all sparse arrays. It + cannot be instantiated. Most of the work is provided by subclasses. + """ + + __array_priority__ = 10.1 + _format = 'und' # undefined + _allow_nd = (2,) + + @property + def ndim(self) -> int: + return len(self._shape) + + @property + def _shape_as_2d(self): + s = self._shape + return (1, s[-1]) if len(s) == 1 else s + + @property + def _bsr_container(self): + from ._bsr import bsr_array + return bsr_array + + @property + def _coo_container(self): + from ._coo import coo_array + return coo_array + + @property + def _csc_container(self): + from ._csc import csc_array + return csc_array + + @property + def _csr_container(self): + from ._csr import csr_array + return csr_array + + @property + def _dia_container(self): + from ._dia import dia_array + return dia_array + + @property + def _dok_container(self): + from ._dok import dok_array + return dok_array + + @property + def _lil_container(self): + from ._lil import lil_array + return lil_array + + def __init__(self, arg1, *, maxprint=None): + self._shape = None + if self.__class__.__name__ == '_spbase': + raise ValueError("This class is not intended" + " to be instantiated directly.") + if isinstance(self, sparray) and np.isscalar(arg1): + raise ValueError( + "scipy sparse array classes do not support instantiation from a scalar" + ) + self.maxprint = MAXPRINT if maxprint is None else maxprint + + @property + def shape(self): + return self._shape + + def reshape(self, *args, **kwargs): + """reshape(self, shape, order='C', copy=False) + + Gives a new shape to a sparse array/matrix without changing its data. + + Parameters + ---------- + shape : length-2 tuple of ints + The new shape should be compatible with the original shape. + order : {'C', 'F'}, optional + Read the elements using this index order. 'C' means to read and + write the elements using C-like index order; e.g., read entire first + row, then second row, etc. 'F' means to read and write the elements + using Fortran-like index order; e.g., read entire first column, then + second column, etc. + copy : bool, optional + Indicates whether or not attributes of self should be copied + whenever possible. The degree to which attributes are copied varies + depending on the type of sparse array being used. + + Returns + ------- + reshaped : sparse array/matrix + A sparse array/matrix with the given `shape`, not necessarily of the same + format as the current object. + + See Also + -------- + numpy.reshape : NumPy's implementation of 'reshape' for ndarrays + """ + # If the shape already matches, don't bother doing an actual reshape + # Otherwise, the default is to convert to COO and use its reshape + # Don't restrict ndim on this first call. That happens in constructor + shape = check_shape(args, self.shape, allow_nd=range(1, 65)) + order, copy = check_reshape_kwargs(kwargs) + if shape == self.shape: + if copy: + return self.copy() + else: + return self + + return self.tocoo(copy=copy).reshape(shape, order=order, copy=False) + + def resize(self, shape): + """Resize the array/matrix in-place to dimensions given by ``shape`` + + Any elements that lie within the new shape will remain at the same + indices, while non-zero elements lying outside the new shape are + removed. + + Parameters + ---------- + shape : (int, int) + number of rows and columns in the new array/matrix + + Notes + ----- + The semantics are not identical to `numpy.ndarray.resize` or + `numpy.resize`. Here, the same data will be maintained at each index + before and after reshape, if that index is within the new bounds. In + numpy, resizing maintains contiguity of the array, moving elements + around in the logical array but not within a flattened representation. + + We give no guarantees about whether the underlying data attributes + (arrays, etc.) will be modified in place or replaced with new objects. + """ + # As an inplace operation, this requires implementation in each format. + raise NotImplementedError( + f'{type(self).__name__}.resize is not implemented') + + def astype(self, dtype, casting='unsafe', copy=True): + """Cast the array/matrix elements to a specified type. + + Parameters + ---------- + dtype : string or numpy dtype + Typecode or data-type to which to cast the data. + casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional + Controls what kind of data casting may occur. + Defaults to 'unsafe' for backwards compatibility. + 'no' means the data types should not be cast at all. + 'equiv' means only byte-order changes are allowed. + 'safe' means only casts which can preserve values are allowed. + 'same_kind' means only safe casts or casts within a kind, + like float64 to float32, are allowed. + 'unsafe' means any data conversions may be done. + copy : bool, optional + If `copy` is `False`, the result might share some memory with this + array/matrix. If `copy` is `True`, it is guaranteed that the result and + this array/matrix do not share any memory. + """ + + dtype = getdtype(dtype) + if self.dtype != dtype: + return self.tocsr().astype( + dtype, casting=casting, copy=copy).asformat(self.format) + elif copy: + return self.copy() + else: + return self + + @classmethod + def _ascontainer(cls, X, **kwargs): + if issubclass(cls, sparray): + return np.asarray(X, **kwargs) + else: + return asmatrix(X, **kwargs) + + @classmethod + def _container(cls, X, **kwargs): + if issubclass(cls, sparray): + return np.array(X, **kwargs) + else: + return matrix(X, **kwargs) + + def _asfptype(self): + """Upcast array to a floating point format (if necessary)""" + + fp_types = ['f', 'd', 'F', 'D'] + + if self.dtype.char in fp_types: + return self + else: + for fp_type in fp_types: + if self.dtype <= np.dtype(fp_type): + return self.astype(fp_type) + + raise TypeError( + f'cannot upcast [{self.dtype.name}] to a floating point format' + ) + + def __iter__(self): + for r in range(self.shape[0]): + yield self[r] + + def _getmaxprint(self): + """Maximum number of elements to display when printed.""" + return self.maxprint + + def count_nonzero(self, axis=None): + """Number of non-zero entries, equivalent to + + np.count_nonzero(a.toarray(), axis=axis) + + Unlike the nnz property, which return the number of stored + entries (the length of the data attribute), this method counts the + actual number of non-zero entries in data. + + Duplicate entries are summed before counting. + + Parameters + ---------- + axis : {-2, -1, 0, 1, None} optional + Count nonzeros for the whole array, or along a specified axis. + + .. versionadded:: 1.15.0 + + Returns + ------- + numpy array + A reduced array (no axis `axis`) holding the number of nonzero values + for each of the indices of the nonaxis dimensions. + + Notes + ----- + If you want to count nonzero and explicit zero stored values (e.g. nnz) + along an axis, two fast idioms are provided by `numpy` functions for the + common CSR, CSC, COO formats. + + For the major axis in CSR (rows) and CSC (cols) use `np.diff`: + + >>> import numpy as np + >>> import scipy as sp + >>> A = sp.sparse.csr_array([[4, 5, 0], [7, 0, 0]]) + >>> major_axis_stored_values = np.diff(A.indptr) # -> np.array([2, 1]) + + For the minor axis in CSR (cols) and CSC (rows) use `numpy.bincount` with + minlength ``A.shape[1]`` for CSR and ``A.shape[0]`` for CSC: + + >>> csr_minor_stored_values = np.bincount(A.indices, minlength=A.shape[1]) + + For COO, use the minor axis approach for either `axis`: + + >>> A = A.tocoo() + >>> coo_axis0_stored_values = np.bincount(A.coords[0], minlength=A.shape[1]) + >>> coo_axis1_stored_values = np.bincount(A.coords[1], minlength=A.shape[0]) + + Examples + -------- + + >>> A = sp.sparse.csr_array([[4, 5, 0], [7, 0, 0]]) + >>> A.count_nonzero(axis=0) + array([2, 1, 0]) + """ + clsname = self.__class__.__name__ + raise NotImplementedError(f"count_nonzero not implemented for {clsname}.") + + def _getnnz(self, axis=None): + """Number of stored values, including explicit zeros. + + Parameters + ---------- + axis : {-2, -1, 0, 1, None} optional + Report stored values for the whole array, or along a specified axis. + + See also + -------- + count_nonzero : Number of non-zero entries + """ + clsname = self.__class__.__name__ + raise NotImplementedError(f"getnnz not implemented for {clsname}.") + + @property + def nnz(self) -> int: + """Number of stored values, including explicit zeros. + + See also + -------- + count_nonzero : Number of non-zero entries + """ + return self._getnnz() + + @property + def size(self) -> int: + """Number of stored values. + + See also + -------- + count_nonzero : Number of non-zero values. + """ + return self._getnnz() + + @property + def format(self) -> str: + """Format string for matrix.""" + return self._format + + @property + def T(self): + """Transpose.""" + return self.transpose() + + @property + def real(self): + return self._real() + + @property + def imag(self): + return self._imag() + + def __repr__(self): + _, format_name = _formats[self.format] + sparse_cls = 'array' if isinstance(self, sparray) else 'matrix' + return ( + f"<{format_name} sparse {sparse_cls} of dtype '{self.dtype}'\n" + f"\twith {self.nnz} stored elements and shape {self.shape}>" + ) + + def __str__(self): + maxprint = self._getmaxprint() + + A = self.tocoo() + + # helper function, outputs "(i,j) v" + def tostr(coords, data): + pairs = zip(zip(*(c.tolist() for c in coords)), data) + return '\n'.join(f' {idx}\t{val}' for idx, val in pairs) + + out = repr(self) + if self.nnz == 0: + return out + + out += '\n Coords\tValues\n' + if self.nnz > maxprint: + half = maxprint // 2 + out += tostr(tuple(c[:half] for c in A.coords), A.data[:half]) + out += "\n :\t:\n" + half = maxprint - half + out += tostr(tuple(c[-half:] for c in A.coords), A.data[-half:]) + else: + out += tostr(A.coords, A.data) + + return out + + def __bool__(self): # Simple -- other ideas? + if self.shape == (1, 1): + return self.nnz != 0 + else: + raise ValueError("The truth value of an array with more than one " + "element is ambiguous. Use a.any() or a.all().") + __nonzero__ = __bool__ + + # What should len(sparse) return? For consistency with dense matrices, + # perhaps it should be the number of rows? But for some uses the number of + # non-zeros is more important. For now, raise an exception! + def __len__(self): + raise TypeError("sparse array length is ambiguous; use getnnz()" + " or shape[0]") + + def asformat(self, format, copy=False): + """Return this array/matrix in the passed format. + + Parameters + ---------- + format : {str, None} + The desired sparse format ("csr", "csc", "lil", "dok", "array", ...) + or None for no conversion. + copy : bool, optional + If True, the result is guaranteed to not share data with self. + + Returns + ------- + A : This array/matrix in the passed format. + """ + if format is None or format == self.format: + if copy: + return self.copy() + else: + return self + else: + try: + convert_method = getattr(self, 'to' + format) + except AttributeError as e: + raise ValueError(f'Format {format} is unknown.') from e + + # Forward the copy kwarg, if it's accepted. + try: + return convert_method(copy=copy) + except TypeError: + return convert_method() + + ################################################################### + # NOTE: All arithmetic operations use csr_matrix by default. + # Therefore a new sparse array format just needs to define a + # .tocsr() method to provide arithmetic support. Any of these + # methods can be overridden for efficiency. + #################################################################### + + def multiply(self, other): + """Point-wise multiplication by another array/matrix.""" + if isscalarlike(other): + return self._mul_scalar(other) + return self.tocsr().multiply(other) + + def maximum(self, other): + """Element-wise maximum between this and another array/matrix.""" + return self.tocsr().maximum(other) + + def minimum(self, other): + """Element-wise minimum between this and another array/matrix.""" + return self.tocsr().minimum(other) + + def dot(self, other): + """Ordinary dot product + + Examples + -------- + >>> import numpy as np + >>> from scipy.sparse import csr_array + >>> A = csr_array([[1, 2, 0], [0, 0, 3], [4, 0, 5]]) + >>> v = np.array([1, 0, -1]) + >>> A.dot(v) + array([ 1, -3, -1], dtype=int64) + + """ + if np.isscalar(other): + return self * other + else: + return self @ other + + def power(self, n, dtype=None): + """Element-wise power.""" + return self.tocsr().power(n, dtype=dtype) + + def _broadcast_to(self, shape, copy=False): + if self.shape == shape: + return self.copy() if copy else self + else: + return self.tocsr()._broadcast_to(shape, copy) + + def __eq__(self, other): + return self.tocsr().__eq__(other) + + def __ne__(self, other): + return self.tocsr().__ne__(other) + + def __lt__(self, other): + return self.tocsr().__lt__(other) + + def __gt__(self, other): + return self.tocsr().__gt__(other) + + def __le__(self, other): + return self.tocsr().__le__(other) + + def __ge__(self, other): + return self.tocsr().__ge__(other) + + def __abs__(self): + return abs(self.tocsr()) + + def __round__(self, ndigits=0): + return round(self.tocsr(), ndigits=ndigits) + + def _add_sparse(self, other): + return self.tocsr()._add_sparse(other) + + def _add_dense(self, other): + return self.tocoo()._add_dense(other) + + def _sub_sparse(self, other): + return self.tocsr()._sub_sparse(other) + + def _sub_dense(self, other): + return self.todense() - other + + def _rsub_dense(self, other): + # note: this can't be replaced by other + (-self) for unsigned types + return other - self.todense() + + def __add__(self, other): # self + other + if isscalarlike(other): + if other == 0: + return self.copy() + # Now we would add this scalar to every element. + raise NotImplementedError('adding a nonzero scalar to a ' + 'sparse array is not supported') + elif issparse(other): + if other.shape != self.shape: + raise ValueError("inconsistent shapes") + return self._add_sparse(other) + elif isdense(other): + other = np.broadcast_to(other, self.shape) + return self._add_dense(other) + else: + return NotImplemented + + def __radd__(self,other): # other + self + return self.__add__(other) + + def __sub__(self, other): # self - other + if isscalarlike(other): + if other == 0: + return self.copy() + raise NotImplementedError('subtracting a nonzero scalar from a ' + 'sparse array is not supported') + elif issparse(other): + if other.shape != self.shape: + raise ValueError("inconsistent shapes") + return self._sub_sparse(other) + elif isdense(other): + other = np.broadcast_to(other, self.shape) + return self._sub_dense(other) + else: + return NotImplemented + + def __rsub__(self,other): # other - self + if isscalarlike(other): + if other == 0: + return -self.copy() + raise NotImplementedError('subtracting a sparse array from a ' + 'nonzero scalar is not supported') + elif isdense(other): + other = np.broadcast_to(other, self.shape) + return self._rsub_dense(other) + else: + return NotImplemented + + def _matmul_dispatch(self, other): + """np.array-like matmul & `np.matrix`-like mul, i.e. `dot` or `NotImplemented` + + interpret other and call one of the following + self._mul_scalar() + self._matmul_vector() + self._matmul_multivector() + self._matmul_sparse() + """ + # This method has to be different from `__matmul__` because it is also + # called by sparse matrix classes. + + # Currently matrix multiplication is only supported + # for 2D arrays. Hence we unpacked and use only the + # two last axes' lengths. + M, N = self._shape_as_2d + + if other.__class__ is np.ndarray: + # Fast path for the most common case + if other.shape == (N,): + return self._matmul_vector(other) + elif other.shape == (N, 1): + result = self._matmul_vector(other.ravel()) + if self.ndim == 1: + return result.reshape(1) + return result.reshape(M, 1) + elif other.ndim == 2 and other.shape[0] == N: + return self._matmul_multivector(other) + + if isscalarlike(other): + # scalar value + return self._mul_scalar(other) + + err_prefix = "matmul: dimension mismatch with signature" + if issparse(other): + if N != other.shape[0]: + raise ValueError( + f"{err_prefix} (n,k={N}),(k={other.shape[0]},m)->(n,m)" + ) + return self._matmul_sparse(other) + + # If it's a list or whatever, treat it like an array + other_a = np.asanyarray(other) + + if other_a.ndim == 0 and other_a.dtype == np.object_: + # Not interpretable as an array; return NotImplemented so that + # other's __rmatmul__ can kick in if that's implemented. + return NotImplemented + + try: + other.shape + except AttributeError: + other = other_a + + if other.ndim == 1 or other.ndim == 2 and other.shape[1] == 1: + # dense row or column vector + if other.shape[0] != N: + raise ValueError( + f"{err_prefix} (n,k={N}),(k={other.shape[0]},1?)->(n,1?)" + ) + + result = self._matmul_vector(np.ravel(other)) + + if isinstance(other, np.matrix): + result = self._ascontainer(result) + + if other.ndim == 2 and other.shape[1] == 1: + # If 'other' was an (nx1) column vector, reshape the result + if self.ndim == 1: + result = result.reshape(1) + else: + result = result.reshape(-1, 1) + + return result + + elif other.ndim == 2: + ## + # dense 2D array or matrix ("multivector") + + if other.shape[0] != N: + raise ValueError( + f"{err_prefix} (n,k={N}),(k={other.shape[0]},m)->(n,m)" + ) + + result = self._matmul_multivector(np.asarray(other)) + + if isinstance(other, np.matrix): + result = self._ascontainer(result) + + return result + + else: + raise ValueError('could not interpret dimensions') + + def __mul__(self, other): + return self.multiply(other) + + def __rmul__(self, other): # other * self + return self.multiply(other) + + # by default, use CSR for __mul__ handlers + def _mul_scalar(self, other): + return self.tocsr()._mul_scalar(other) + + def _matmul_vector(self, other): + return self.tocsr()._matmul_vector(other) + + def _matmul_multivector(self, other): + return self.tocsr()._matmul_multivector(other) + + def _matmul_sparse(self, other): + return self.tocsr()._matmul_sparse(other) + + def _rmatmul_dispatch(self, other): + if isscalarlike(other): + return self._mul_scalar(other) + else: + # Don't use asarray unless we have to + try: + tr = other.transpose() + except AttributeError: + tr = np.asarray(other).transpose() + ret = self.transpose()._matmul_dispatch(tr) + if ret is NotImplemented: + return NotImplemented + return ret.transpose() + + ####################### + # matmul (@) operator # + ####################### + + def __matmul__(self, other): + if isscalarlike(other): + raise ValueError("Scalar operands are not allowed, " + "use '*' instead") + return self._matmul_dispatch(other) + + def __rmatmul__(self, other): + if isscalarlike(other): + raise ValueError("Scalar operands are not allowed, " + "use '*' instead") + return self._rmatmul_dispatch(other) + + #################### + # Other Arithmetic # + #################### + + def _divide(self, other, true_divide=False, rdivide=False): + if isscalarlike(other): + if rdivide: + if true_divide: + return np.true_divide(other, self.todense()) + else: + return np.divide(other, self.todense()) + + if true_divide and np.can_cast(self.dtype, np.float64): + return self.astype(np.float64)._mul_scalar(1./other) + else: + r = self._mul_scalar(1./other) + + scalar_dtype = np.asarray(other).dtype + if (np.issubdtype(self.dtype, np.integer) and + np.issubdtype(scalar_dtype, np.integer)): + return r.astype(self.dtype) + else: + return r + + elif isdense(other): + if not rdivide: + if true_divide: + recip = np.true_divide(1., other) + else: + recip = np.divide(1., other) + return self.multiply(recip) + else: + if true_divide: + return np.true_divide(other, self.todense()) + else: + return np.divide(other, self.todense()) + elif issparse(other): + if rdivide: + return other._divide(self, true_divide, rdivide=False) + + self_csr = self.tocsr() + if true_divide and np.can_cast(self.dtype, np.float64): + return self_csr.astype(np.float64)._divide_sparse(other) + else: + return self_csr._divide_sparse(other) + else: + return NotImplemented + + def __truediv__(self, other): + return self._divide(other, true_divide=True) + + def __div__(self, other): + # Always do true division + return self._divide(other, true_divide=True) + + def __rtruediv__(self, other): + # Implementing this as the inverse would be too magical -- bail out + return NotImplemented + + def __rdiv__(self, other): + # Implementing this as the inverse would be too magical -- bail out + return NotImplemented + + def __neg__(self): + return -self.tocsr() + + def __iadd__(self, other): + return NotImplemented + + def __isub__(self, other): + return NotImplemented + + def __imul__(self, other): + return NotImplemented + + def __idiv__(self, other): + return self.__itruediv__(other) + + def __itruediv__(self, other): + return NotImplemented + + def __pow__(self, *args, **kwargs): + return self.power(*args, **kwargs) + + def transpose(self, axes=None, copy=False): + """ + Reverses the dimensions of the sparse array/matrix. + + Parameters + ---------- + axes : None, optional + This argument is in the signature *solely* for NumPy + compatibility reasons. Do not pass in anything except + for the default value. + copy : bool, optional + Indicates whether or not attributes of `self` should be + copied whenever possible. The degree to which attributes + are copied varies depending on the type of sparse array/matrix + being used. + + Returns + ------- + p : `self` with the dimensions reversed. + + Notes + ----- + If `self` is a `csr_array` or a `csc_array`, then this will return a + `csc_array` or a `csr_array`, respectively. + + See Also + -------- + numpy.transpose : NumPy's implementation of 'transpose' for ndarrays + """ + return self.tocsr(copy=copy).transpose(axes=axes, copy=False) + + def conjugate(self, copy=True): + """Element-wise complex conjugation. + + If the array/matrix is of non-complex data type and `copy` is False, + this method does nothing and the data is not copied. + + Parameters + ---------- + copy : bool, optional + If True, the result is guaranteed to not share data with self. + + Returns + ------- + A : The element-wise complex conjugate. + + """ + if np.issubdtype(self.dtype, np.complexfloating): + return self.tocsr(copy=copy).conjugate(copy=False) + elif copy: + return self.copy() + else: + return self + + def conj(self, copy=True): + return self.conjugate(copy=copy) + + conj.__doc__ = conjugate.__doc__ + + def _real(self): + return self.tocsr()._real() + + def _imag(self): + return self.tocsr()._imag() + + def nonzero(self): + """Nonzero indices of the array/matrix. + + Returns a tuple of arrays (row,col) containing the indices + of the non-zero elements of the array. + + Examples + -------- + >>> from scipy.sparse import csr_array + >>> A = csr_array([[1, 2, 0], [0, 0, 3], [4, 0, 5]]) + >>> A.nonzero() + (array([0, 0, 1, 2, 2], dtype=int32), array([0, 1, 2, 0, 2], dtype=int32)) + + """ + + # convert to COOrdinate format + A = self.tocoo() + nz_mask = A.data != 0 + return tuple(idx[nz_mask] for idx in A.coords) + + def _getcol(self, j): + """Returns a copy of column j of the array, as an (m x 1) sparse + array (column vector). + """ + if self.ndim == 1: + raise ValueError("getcol not provided for 1d arrays. Use indexing A[j]") + # Subclasses should override this method for efficiency. + # Post-multiply by a (n x 1) column vector 'a' containing all zeros + # except for a_j = 1 + N = self.shape[-1] + if j < 0: + j += N + if j < 0 or j >= N: + raise IndexError("index out of bounds") + col_selector = self._csc_container(([1], [[j], [0]]), + shape=(N, 1), dtype=self.dtype) + result = self @ col_selector + return result + + def _getrow(self, i): + """Returns a copy of row i of the array, as a (1 x n) sparse + array (row vector). + """ + if self.ndim == 1: + raise ValueError("getrow not meaningful for a 1d array") + # Subclasses should override this method for efficiency. + # Pre-multiply by a (1 x m) row vector 'a' containing all zeros + # except for a_i = 1 + M = self.shape[0] + if i < 0: + i += M + if i < 0 or i >= M: + raise IndexError("index out of bounds") + row_selector = self._csr_container(([1], [[0], [i]]), + shape=(1, M), dtype=self.dtype) + return row_selector @ self + + # The following dunder methods cannot be implemented. + # + # def __array__(self): + # # Sparse matrices rely on NumPy wrapping them in object arrays under + # # the hood to make unary ufuncs work on them. So we cannot raise + # # TypeError here - which would be handy to not give users object + # # arrays they probably don't want (they're looking for `.toarray()`). + # # + # # Conversion with `toarray()` would also break things because of the + # # behavior discussed above, plus we want to avoid densification by + # # accident because that can too easily blow up memory. + # + # def __array_ufunc__(self): + # # We cannot implement __array_ufunc__ due to mismatching semantics. + # # See gh-7707 and gh-7349 for details. + # + # def __array_function__(self): + # # We cannot implement __array_function__ due to mismatching semantics. + # # See gh-10362 for details. + + def todense(self, order=None, out=None): + """ + Return a dense representation of this sparse array. + + Parameters + ---------- + order : {'C', 'F'}, optional + Whether to store multi-dimensional data in C (row-major) + or Fortran (column-major) order in memory. The default + is 'None', which provides no ordering guarantees. + Cannot be specified in conjunction with the `out` + argument. + + out : ndarray, 2-D, optional + If specified, uses this array as the output buffer + instead of allocating a new array to return. The + provided array must have the same shape and dtype as + the sparse array on which you are calling the method. + + Returns + ------- + arr : ndarray, 2-D + An array with the same shape and containing the same + data represented by the sparse array, with the requested + memory order. If `out` was passed, the same object is + returned after being modified in-place to contain the + appropriate values. + """ + return self._ascontainer(self.toarray(order=order, out=out)) + + def toarray(self, order=None, out=None): + """ + Return a dense ndarray representation of this sparse array/matrix. + + Parameters + ---------- + order : {'C', 'F'}, optional + Whether to store multidimensional data in C (row-major) + or Fortran (column-major) order in memory. The default + is 'None', which provides no ordering guarantees. + Cannot be specified in conjunction with the `out` + argument. + + out : ndarray, 2-D, optional + If specified, uses this array as the output buffer + instead of allocating a new array to return. The provided + array must have the same shape and dtype as the sparse + array/matrix on which you are calling the method. For most + sparse types, `out` is required to be memory contiguous + (either C or Fortran ordered). + + Returns + ------- + arr : ndarray, 2-D + An array with the same shape and containing the same + data represented by the sparse array/matrix, with the requested + memory order. If `out` was passed, the same object is + returned after being modified in-place to contain the + appropriate values. + """ + return self.tocoo(copy=False).toarray(order=order, out=out) + + # Any sparse array format deriving from _spbase must define one of + # tocsr or tocoo. The other conversion methods may be implemented for + # efficiency, but are not required. + def tocsr(self, copy=False): + """Convert this array/matrix to Compressed Sparse Row format. + + With copy=False, the data/indices may be shared between this array/matrix and + the resultant csr_array/matrix. + """ + return self.tocoo(copy=copy).tocsr(copy=False) + + def todok(self, copy=False): + """Convert this array/matrix to Dictionary Of Keys format. + + With copy=False, the data/indices may be shared between this array/matrix and + the resultant dok_array/matrix. + """ + return self.tocoo(copy=copy).todok(copy=False) + + def tocoo(self, copy=False): + """Convert this array/matrix to COOrdinate format. + + With copy=False, the data/indices may be shared between this array/matrix and + the resultant coo_array/matrix. + """ + return self.tocsr(copy=False).tocoo(copy=copy) + + def tolil(self, copy=False): + """Convert this array/matrix to List of Lists format. + + With copy=False, the data/indices may be shared between this array/matrix and + the resultant lil_array/matrix. + """ + return self.tocsr(copy=False).tolil(copy=copy) + + def todia(self, copy=False): + """Convert this array/matrix to sparse DIAgonal format. + + With copy=False, the data/indices may be shared between this array/matrix and + the resultant dia_array/matrix. + """ + return self.tocoo(copy=copy).todia(copy=False) + + def tobsr(self, blocksize=None, copy=False): + """Convert this array/matrix to Block Sparse Row format. + + With copy=False, the data/indices may be shared between this array/matrix and + the resultant bsr_array/matrix. + + When blocksize=(R, C) is provided, it will be used for construction of + the bsr_array/matrix. + """ + return self.tocsr(copy=False).tobsr(blocksize=blocksize, copy=copy) + + def tocsc(self, copy=False): + """Convert this array/matrix to Compressed Sparse Column format. + + With copy=False, the data/indices may be shared between this array/matrix and + the resultant csc_array/matrix. + """ + return self.tocsr(copy=copy).tocsc(copy=False) + + def copy(self): + """Returns a copy of this array/matrix. + + No data/indices will be shared between the returned value and current + array/matrix. + """ + return self.__class__(self, copy=True) + + def sum(self, axis=None, dtype=None, out=None): + """ + Sum the array/matrix elements over a given axis. + + Parameters + ---------- + axis : {-2, -1, 0, 1, None} optional + Axis along which the sum is computed. The default is to + compute the sum of all the array/matrix elements, returning a scalar + (i.e., `axis` = `None`). + dtype : dtype, optional + The type of the returned array/matrix and of the accumulator in which + the elements are summed. The dtype of `a` is used by default + unless `a` has an integer dtype of less precision than the default + platform integer. In that case, if `a` is signed then the platform + integer is used while if `a` is unsigned then an unsigned integer + of the same precision as the platform integer is used. + + .. versionadded:: 0.18.0 + + out : np.matrix, optional + Alternative output matrix in which to place the result. It must + have the same shape as the expected output, but the type of the + output values will be cast if necessary. + + .. versionadded:: 0.18.0 + + Returns + ------- + sum_along_axis : np.matrix + A matrix with the same shape as `self`, with the specified + axis removed. + + See Also + -------- + numpy.matrix.sum : NumPy's implementation of 'sum' for matrices + + """ + validateaxis(axis) + + # Mimic numpy's casting. + res_dtype = get_sum_dtype(self.dtype) + + if self.ndim == 1: + if axis not in (None, -1, 0): + raise ValueError("axis must be None, -1 or 0") + res = self @ np.ones(self.shape, dtype=res_dtype) + return res.sum(dtype=dtype, out=out) + + # We use multiplication by a matrix of ones to achieve this. + # For some sparse array formats more efficient methods are + # possible -- these should override this function. + M, N = self.shape + + if axis is None: + # sum over rows and columns + return ( + self @ self._ascontainer(np.ones((N, 1), dtype=res_dtype)) + ).sum(dtype=dtype, out=out) + + if axis < 0: + axis += 2 + + # axis = 0 or 1 now + if axis == 0: + # sum over columns + ret = self._ascontainer( + np.ones((1, M), dtype=res_dtype) + ) @ self + else: + # sum over rows + ret = self @ self._ascontainer( + np.ones((N, 1), dtype=res_dtype) + ) + + return ret.sum(axis=axis, dtype=dtype, out=out) + + def mean(self, axis=None, dtype=None, out=None): + """ + Compute the arithmetic mean along the specified axis. + + Returns the average of the array/matrix elements. The average is taken + over all elements in the array/matrix by default, otherwise over the + specified axis. `float64` intermediate and return values are used + for integer inputs. + + Parameters + ---------- + axis : {-2, -1, 0, 1, None} optional + Axis along which the mean is computed. The default is to compute + the mean of all elements in the array/matrix (i.e., `axis` = `None`). + dtype : data-type, optional + Type to use in computing the mean. For integer inputs, the default + is `float64`; for floating point inputs, it is the same as the + input dtype. + + .. versionadded:: 0.18.0 + + out : np.matrix, optional + Alternative output matrix in which to place the result. It must + have the same shape as the expected output, but the type of the + output values will be cast if necessary. + + .. versionadded:: 0.18.0 + + Returns + ------- + m : np.matrix + + See Also + -------- + numpy.matrix.mean : NumPy's implementation of 'mean' for matrices + + """ + validateaxis(axis) + + res_dtype = self.dtype.type + integral = (np.issubdtype(self.dtype, np.integer) or + np.issubdtype(self.dtype, np.bool_)) + + # output dtype + if dtype is None: + if integral: + res_dtype = np.float64 + else: + res_dtype = np.dtype(dtype).type + + # intermediate dtype for summation + inter_dtype = np.float64 if integral else res_dtype + inter_self = self.astype(inter_dtype) + + if self.ndim == 1: + if axis not in (None, -1, 0): + raise ValueError("axis must be None, -1 or 0") + res = inter_self / self.shape[-1] + return res.sum(dtype=res_dtype, out=out) + + if axis is None: + return (inter_self / (self.shape[0] * self.shape[1]))\ + .sum(dtype=res_dtype, out=out) + + if axis < 0: + axis += 2 + + # axis = 0 or 1 now + if axis == 0: + return (inter_self * (1.0 / self.shape[0])).sum( + axis=0, dtype=res_dtype, out=out) + else: + return (inter_self * (1.0 / self.shape[1])).sum( + axis=1, dtype=res_dtype, out=out) + + def diagonal(self, k=0): + """Returns the kth diagonal of the array/matrix. + + Parameters + ---------- + k : int, optional + Which diagonal to get, corresponding to elements a[i, i+k]. + Default: 0 (the main diagonal). + + .. versionadded:: 1.0 + + See also + -------- + numpy.diagonal : Equivalent numpy function. + + Examples + -------- + >>> from scipy.sparse import csr_array + >>> A = csr_array([[1, 2, 0], [0, 0, 3], [4, 0, 5]]) + >>> A.diagonal() + array([1, 0, 5]) + >>> A.diagonal(k=1) + array([2, 3]) + """ + return self.tocsr().diagonal(k=k) + + def trace(self, offset=0): + """Returns the sum along diagonals of the sparse array/matrix. + + Parameters + ---------- + offset : int, optional + Which diagonal to get, corresponding to elements a[i, i+offset]. + Default: 0 (the main diagonal). + + """ + return self.diagonal(k=offset).sum() + + def setdiag(self, values, k=0): + """ + Set diagonal or off-diagonal elements of the array/matrix. + + Parameters + ---------- + values : array_like + New values of the diagonal elements. + + Values may have any length. If the diagonal is longer than values, + then the remaining diagonal entries will not be set. If values are + longer than the diagonal, then the remaining values are ignored. + + If a scalar value is given, all of the diagonal is set to it. + + k : int, optional + Which off-diagonal to set, corresponding to elements a[i,i+k]. + Default: 0 (the main diagonal). + + """ + M, N = self.shape + if (k > 0 and k >= N) or (k < 0 and -k >= M): + raise ValueError("k exceeds array dimensions") + self._setdiag(np.asarray(values), k) + + def _setdiag(self, values, k): + """This part of the implementation gets overridden by the + different formats. + """ + M, N = self.shape + if k < 0: + if values.ndim == 0: + # broadcast + max_index = min(M+k, N) + for i in range(max_index): + self[i - k, i] = values + else: + max_index = min(M+k, N, len(values)) + if max_index <= 0: + return + for i, v in enumerate(values[:max_index]): + self[i - k, i] = v + else: + if values.ndim == 0: + # broadcast + max_index = min(M, N-k) + for i in range(max_index): + self[i, i + k] = values + else: + max_index = min(M, N-k, len(values)) + if max_index <= 0: + return + for i, v in enumerate(values[:max_index]): + self[i, i + k] = v + + def _process_toarray_args(self, order, out): + if out is not None: + if order is not None: + raise ValueError('order cannot be specified if out ' + 'is not None') + if out.shape != self.shape or out.dtype != self.dtype: + raise ValueError('out array must be same dtype and shape as ' + 'sparse array') + out[...] = 0. + return out + else: + return np.zeros(self.shape, dtype=self.dtype, order=order) + + def _get_index_dtype(self, arrays=(), maxval=None, check_contents=False): + """ + Determine index dtype for array. + + This wraps _sputils.get_index_dtype, providing compatibility for both + array and matrix API sparse matrices. Matrix API sparse matrices would + attempt to downcast the indices - which can be computationally + expensive and undesirable for users. The array API changes this + behaviour. + + See discussion: https://github.com/scipy/scipy/issues/16774 + + The get_index_dtype import is due to implementation details of the test + suite. It allows the decorator ``with_64bit_maxval_limit`` to mock a + lower int32 max value for checks on the matrix API's downcasting + behaviour. + """ + from ._sputils import get_index_dtype + + # Don't check contents for array API + return get_index_dtype(arrays, + maxval, + (check_contents and not isinstance(self, sparray))) + + +class sparray: + """A namespace class to separate sparray from spmatrix""" + + +sparray.__doc__ = _spbase.__doc__ + + +def issparse(x): + """Is `x` of a sparse array or sparse matrix type? + + Parameters + ---------- + x + object to check for being a sparse array or sparse matrix + + Returns + ------- + bool + True if `x` is a sparse array or a sparse matrix, False otherwise + + Notes + ----- + Use `isinstance(x, sp.sparse.sparray)` to check between an array or matrix. + Use `a.format` to check the sparse format, e.g. `a.format == 'csr'`. + + Examples + -------- + >>> import numpy as np + >>> from scipy.sparse import csr_array, csr_matrix, issparse + >>> issparse(csr_matrix([[5]])) + True + >>> issparse(csr_array([[5]])) + True + >>> issparse(np.array([[5]])) + False + >>> issparse(5) + False + """ + return isinstance(x, _spbase) + + +def isspmatrix(x): + """Is `x` of a sparse matrix type? + + Parameters + ---------- + x + object to check for being a sparse matrix + + Returns + ------- + bool + True if `x` is a sparse matrix, False otherwise + + Examples + -------- + >>> import numpy as np + >>> from scipy.sparse import csr_array, csr_matrix, isspmatrix + >>> isspmatrix(csr_matrix([[5]])) + True + >>> isspmatrix(csr_array([[5]])) + False + >>> isspmatrix(np.array([[5]])) + False + >>> isspmatrix(5) + False + """ + return isinstance(x, spmatrix) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_bsr.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_bsr.py new file mode 100644 index 0000000000000000000000000000000000000000..14cf85f8ccf8d7d2b4c63d19938b215e54a9736b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_bsr.py @@ -0,0 +1,877 @@ +"""Compressed Block Sparse Row format""" + +__docformat__ = "restructuredtext en" + +__all__ = ['bsr_array', 'bsr_matrix', 'isspmatrix_bsr'] + +from warnings import warn + +import numpy as np + +from scipy._lib._util import copy_if_needed +from ._matrix import spmatrix +from ._data import _data_matrix, _minmax_mixin +from ._compressed import _cs_matrix +from ._base import issparse, _formats, _spbase, sparray +from ._sputils import (isshape, getdtype, getdata, to_native, upcast, + check_shape) +from . import _sparsetools +from ._sparsetools import (bsr_matvec, bsr_matvecs, csr_matmat_maxnnz, + bsr_matmat, bsr_transpose, bsr_sort_indices, + bsr_tocsr) + + +class _bsr_base(_cs_matrix, _minmax_mixin): + _format = 'bsr' + + def __init__(self, arg1, shape=None, dtype=None, copy=False, + blocksize=None, *, maxprint=None): + _data_matrix.__init__(self, arg1, maxprint=maxprint) + + if issparse(arg1): + if arg1.format == self.format and copy: + arg1 = arg1.copy() + else: + arg1 = arg1.tobsr(blocksize=blocksize) + self.indptr, self.indices, self.data, self._shape = ( + arg1.indptr, arg1.indices, arg1.data, arg1._shape + ) + + elif isinstance(arg1,tuple): + if isshape(arg1): + # it's a tuple of matrix dimensions (M,N) + self._shape = check_shape(arg1) + M,N = self.shape + # process blocksize + if blocksize is None: + blocksize = (1,1) + else: + if not isshape(blocksize): + raise ValueError(f'invalid blocksize={blocksize}') + blocksize = tuple(blocksize) + self.data = np.zeros((0,) + blocksize, getdtype(dtype, default=float)) + + R,C = blocksize + if (M % R) != 0 or (N % C) != 0: + raise ValueError('shape must be multiple of blocksize') + + # Select index dtype large enough to pass array and + # scalar parameters to sparsetools + idx_dtype = self._get_index_dtype(maxval=max(M//R, N//C, R, C)) + self.indices = np.zeros(0, dtype=idx_dtype) + self.indptr = np.zeros(M//R + 1, dtype=idx_dtype) + + elif len(arg1) == 2: + # (data,(row,col)) format + coo = self._coo_container(arg1, dtype=dtype, shape=shape) + bsr = coo.tobsr(blocksize=blocksize) + self.indptr, self.indices, self.data, self._shape = ( + bsr.indptr, bsr.indices, bsr.data, bsr._shape + ) + + elif len(arg1) == 3: + # (data,indices,indptr) format + (data, indices, indptr) = arg1 + + # Select index dtype large enough to pass array and + # scalar parameters to sparsetools + maxval = 1 + if shape is not None: + maxval = max(shape) + if blocksize is not None: + maxval = max(maxval, max(blocksize)) + idx_dtype = self._get_index_dtype((indices, indptr), maxval=maxval, + check_contents=True) + if not copy: + copy = copy_if_needed + self.indices = np.array(indices, copy=copy, dtype=idx_dtype) + self.indptr = np.array(indptr, copy=copy, dtype=idx_dtype) + self.data = getdata(data, copy=copy, dtype=dtype) + if self.data.ndim != 3: + raise ValueError( + f'BSR data must be 3-dimensional, got shape={self.data.shape}' + ) + if blocksize is not None: + if not isshape(blocksize): + raise ValueError(f'invalid blocksize={blocksize}') + if tuple(blocksize) != self.data.shape[1:]: + raise ValueError( + f'mismatching blocksize={blocksize}' + f' vs {self.data.shape[1:]}' + ) + else: + raise ValueError('unrecognized bsr_array constructor usage') + else: + # must be dense + try: + arg1 = np.asarray(arg1) + except Exception as e: + raise ValueError("unrecognized form for " + f"{self.format}_matrix constructor") from e + if isinstance(self, sparray) and arg1.ndim != 2: + raise ValueError(f"BSR arrays don't support {arg1.ndim}D input. Use 2D") + arg1 = self._coo_container(arg1, dtype=dtype).tobsr(blocksize=blocksize) + self.indptr, self.indices, self.data, self._shape = ( + arg1.indptr, arg1.indices, arg1.data, arg1._shape + ) + + if shape is not None: + self._shape = check_shape(shape) + else: + if self.shape is None: + # shape not already set, try to infer dimensions + try: + M = len(self.indptr) - 1 + N = self.indices.max() + 1 + except Exception as e: + raise ValueError('unable to infer matrix dimensions') from e + else: + R,C = self.blocksize + self._shape = check_shape((M*R,N*C)) + + if self.shape is None: + if shape is None: + # TODO infer shape here + raise ValueError('need to infer shape') + else: + self._shape = check_shape(shape) + + if dtype is not None: + self.data = self.data.astype(getdtype(dtype, self.data), copy=False) + + self.check_format(full_check=False) + + def check_format(self, full_check=True): + """Check whether the array/matrix respects the BSR format. + + Parameters + ---------- + full_check : bool, optional + If `True`, run rigorous check, scanning arrays for valid values. + Note that activating those check might copy arrays for casting, + modifying indices and index pointers' inplace. + If `False`, run basic checks on attributes. O(1) operations. + Default is `True`. + """ + M,N = self.shape + R,C = self.blocksize + + # index arrays should have integer data types + if self.indptr.dtype.kind != 'i': + warn(f"indptr array has non-integer dtype ({self.indptr.dtype.name})", + stacklevel=2) + if self.indices.dtype.kind != 'i': + warn(f"indices array has non-integer dtype ({self.indices.dtype.name})", + stacklevel=2) + + # check array shapes + if self.indices.ndim != 1 or self.indptr.ndim != 1: + raise ValueError("indices, and indptr should be 1-D") + if self.data.ndim != 3: + raise ValueError("data should be 3-D") + + # check index pointer + if (len(self.indptr) != M//R + 1): + raise ValueError("index pointer size (%d) should be (%d)" % + (len(self.indptr), M//R + 1)) + if (self.indptr[0] != 0): + raise ValueError("index pointer should start with 0") + + # check index and data arrays + if (len(self.indices) != len(self.data)): + raise ValueError("indices and data should have the same size") + if (self.indptr[-1] > len(self.indices)): + raise ValueError("Last value of index pointer should be less than " + "the size of index and data arrays") + + self.prune() + + if full_check: + # check format validity (more expensive) + if self.nnz > 0: + if self.indices.max() >= N//C: + raise ValueError("column index values must be < %d (now max %d)" + % (N//C, self.indices.max())) + if self.indices.min() < 0: + raise ValueError("column index values must be >= 0") + if np.diff(self.indptr).min() < 0: + raise ValueError("index pointer values must form a " + "non-decreasing sequence") + + idx_dtype = self._get_index_dtype((self.indices, self.indptr)) + self.indptr = np.asarray(self.indptr, dtype=idx_dtype) + self.indices = np.asarray(self.indices, dtype=idx_dtype) + self.data = to_native(self.data) + # if not self.has_sorted_indices(): + # warn('Indices were not in sorted order. Sorting indices.') + # self.sort_indices(check_first=False) + + @property + def blocksize(self) -> tuple: + """Block size of the matrix.""" + return self.data.shape[1:] + + def _getnnz(self, axis=None): + if axis is not None: + raise NotImplementedError("_getnnz over an axis is not implemented " + "for BSR format") + R, C = self.blocksize + return int(self.indptr[-1]) * R * C + + _getnnz.__doc__ = _spbase._getnnz.__doc__ + + def count_nonzero(self, axis=None): + if axis is not None: + raise NotImplementedError( + "count_nonzero over axis is not implemented for BSR format." + ) + return np.count_nonzero(self._deduped_data()) + + count_nonzero.__doc__ = _spbase.count_nonzero.__doc__ + + def __repr__(self): + _, fmt = _formats[self.format] + sparse_cls = 'array' if isinstance(self, sparray) else 'matrix' + b = 'x'.join(str(x) for x in self.blocksize) + return ( + f"<{fmt} sparse {sparse_cls} of dtype '{self.dtype}'\n" + f"\twith {self.nnz} stored elements (blocksize={b}) and shape {self.shape}>" + ) + + def diagonal(self, k=0): + rows, cols = self.shape + if k <= -rows or k >= cols: + return np.empty(0, dtype=self.data.dtype) + R, C = self.blocksize + y = np.zeros(min(rows + min(k, 0), cols - max(k, 0)), + dtype=upcast(self.dtype)) + _sparsetools.bsr_diagonal(k, rows // R, cols // C, R, C, + self.indptr, self.indices, + np.ravel(self.data), y) + return y + + diagonal.__doc__ = _spbase.diagonal.__doc__ + + ########################## + # NotImplemented methods # + ########################## + + def __getitem__(self,key): + raise NotImplementedError + + def __setitem__(self,key,val): + raise NotImplementedError + + ###################### + # Arithmetic methods # + ###################### + + def _add_dense(self, other): + return self.tocoo(copy=False)._add_dense(other) + + def _matmul_vector(self, other): + M,N = self.shape + R,C = self.blocksize + + result = np.zeros(self.shape[0], dtype=upcast(self.dtype, other.dtype)) + + bsr_matvec(M//R, N//C, R, C, + self.indptr, self.indices, self.data.ravel(), + other, result) + + return result + + def _matmul_multivector(self,other): + R,C = self.blocksize + M,N = self.shape + n_vecs = other.shape[1] # number of column vectors + + result = np.zeros((M,n_vecs), dtype=upcast(self.dtype,other.dtype)) + + bsr_matvecs(M//R, N//C, n_vecs, R, C, + self.indptr, self.indices, self.data.ravel(), + other.ravel(), result.ravel()) + + return result + + def _matmul_sparse(self, other): + M, K1 = self.shape + K2, N = other.shape + + R,n = self.blocksize + + # convert to this format + if other.format == "bsr": + C = other.blocksize[1] + else: + C = 1 + + if other.format == "csr" and n == 1: + other = other.tobsr(blocksize=(n,C), copy=False) # lightweight conversion + else: + other = other.tobsr(blocksize=(n,C)) + + idx_dtype = self._get_index_dtype((self.indptr, self.indices, + other.indptr, other.indices)) + + bnnz = csr_matmat_maxnnz(M//R, N//C, + self.indptr.astype(idx_dtype), + self.indices.astype(idx_dtype), + other.indptr.astype(idx_dtype), + other.indices.astype(idx_dtype)) + + idx_dtype = self._get_index_dtype((self.indptr, self.indices, + other.indptr, other.indices), + maxval=bnnz) + indptr = np.empty(self.indptr.shape, dtype=idx_dtype) + indices = np.empty(bnnz, dtype=idx_dtype) + data = np.empty(R*C*bnnz, dtype=upcast(self.dtype,other.dtype)) + + bsr_matmat(bnnz, M//R, N//C, R, C, n, + self.indptr.astype(idx_dtype), + self.indices.astype(idx_dtype), + np.ravel(self.data), + other.indptr.astype(idx_dtype), + other.indices.astype(idx_dtype), + np.ravel(other.data), + indptr, + indices, + data) + + data = data.reshape(-1,R,C) + + # TODO eliminate zeros + + return self._bsr_container( + (data, indices, indptr), shape=(M, N), blocksize=(R, C) + ) + + ###################### + # Conversion methods # + ###################### + + def tobsr(self, blocksize=None, copy=False): + """Convert this array/matrix into Block Sparse Row Format. + + With copy=False, the data/indices may be shared between this + array/matrix and the resultant bsr_array/bsr_matrix. + + If blocksize=(R, C) is provided, it will be used for determining + block size of the bsr_array/bsr_matrix. + """ + if blocksize not in [None, self.blocksize]: + return self.tocsr().tobsr(blocksize=blocksize) + if copy: + return self.copy() + else: + return self + + def tocsr(self, copy=False): + M, N = self.shape + R, C = self.blocksize + nnz = self.nnz + idx_dtype = self._get_index_dtype((self.indptr, self.indices), + maxval=max(nnz, N)) + indptr = np.empty(M + 1, dtype=idx_dtype) + indices = np.empty(nnz, dtype=idx_dtype) + data = np.empty(nnz, dtype=upcast(self.dtype)) + + bsr_tocsr(M // R, # n_brow + N // C, # n_bcol + R, C, + self.indptr.astype(idx_dtype, copy=False), + self.indices.astype(idx_dtype, copy=False), + self.data, + indptr, + indices, + data) + return self._csr_container((data, indices, indptr), shape=self.shape) + + tocsr.__doc__ = _spbase.tocsr.__doc__ + + def tocsc(self, copy=False): + return self.tocsr(copy=False).tocsc(copy=copy) + + tocsc.__doc__ = _spbase.tocsc.__doc__ + + def tocoo(self, copy=True): + """Convert this array/matrix to COOrdinate format. + + When copy=False the data array will be shared between + this array/matrix and the resultant coo_array/coo_matrix. + """ + + M,N = self.shape + R,C = self.blocksize + + indptr_diff = np.diff(self.indptr) + if indptr_diff.dtype.itemsize > np.dtype(np.intp).itemsize: + # Check for potential overflow + indptr_diff_limited = indptr_diff.astype(np.intp) + if np.any(indptr_diff_limited != indptr_diff): + raise ValueError("Matrix too big to convert") + indptr_diff = indptr_diff_limited + + idx_dtype = self._get_index_dtype(maxval=max(M, N)) + row = (R * np.arange(M//R, dtype=idx_dtype)).repeat(indptr_diff) + row = row.repeat(R*C).reshape(-1,R,C) + row += np.tile(np.arange(R, dtype=idx_dtype).reshape(-1,1), (1,C)) + row = row.reshape(-1) + + col = ((C * self.indices).astype(idx_dtype, copy=False) + .repeat(R*C).reshape(-1,R,C)) + col += np.tile(np.arange(C, dtype=idx_dtype), (R,1)) + col = col.reshape(-1) + + data = self.data.reshape(-1) + + if copy: + data = data.copy() + + return self._coo_container( + (data, (row, col)), shape=self.shape + ) + + def toarray(self, order=None, out=None): + return self.tocoo(copy=False).toarray(order=order, out=out) + + toarray.__doc__ = _spbase.toarray.__doc__ + + def transpose(self, axes=None, copy=False): + if axes is not None and axes != (1, 0): + raise ValueError("Sparse matrices do not support " + "an 'axes' parameter because swapping " + "dimensions is the only logical permutation.") + + R, C = self.blocksize + M, N = self.shape + NBLK = self.nnz//(R*C) + + if self.nnz == 0: + return self._bsr_container((N, M), blocksize=(C, R), + dtype=self.dtype, copy=copy) + + indptr = np.empty(N//C + 1, dtype=self.indptr.dtype) + indices = np.empty(NBLK, dtype=self.indices.dtype) + data = np.empty((NBLK, C, R), dtype=self.data.dtype) + + bsr_transpose(M//R, N//C, R, C, + self.indptr, self.indices, self.data.ravel(), + indptr, indices, data.ravel()) + + return self._bsr_container((data, indices, indptr), + shape=(N, M), copy=copy) + + transpose.__doc__ = _spbase.transpose.__doc__ + + ############################################################## + # methods that examine or modify the internal data structure # + ############################################################## + + def eliminate_zeros(self): + """Remove zero elements in-place.""" + + if not self.nnz: + return # nothing to do + + R,C = self.blocksize + M,N = self.shape + + mask = (self.data != 0).reshape(-1,R*C).sum(axis=1) # nonzero blocks + + nonzero_blocks = mask.nonzero()[0] + + self.data[:len(nonzero_blocks)] = self.data[nonzero_blocks] + + # modifies self.indptr and self.indices *in place* + _sparsetools.csr_eliminate_zeros(M//R, N//C, self.indptr, + self.indices, mask) + self.prune() + + def sum_duplicates(self): + """Eliminate duplicate array/matrix entries by adding them together + + The is an *in place* operation + """ + if self.has_canonical_format: + return + self.sort_indices() + R, C = self.blocksize + M, N = self.shape + + # port of _sparsetools.csr_sum_duplicates + n_row = M // R + nnz = 0 + row_end = 0 + for i in range(n_row): + jj = row_end + row_end = self.indptr[i+1] + while jj < row_end: + j = self.indices[jj] + x = self.data[jj] + jj += 1 + while jj < row_end and self.indices[jj] == j: + x += self.data[jj] + jj += 1 + self.indices[nnz] = j + self.data[nnz] = x + nnz += 1 + self.indptr[i+1] = nnz + + self.prune() # nnz may have changed + self.has_canonical_format = True + + def sort_indices(self): + """Sort the indices of this array/matrix *in place* + """ + if self.has_sorted_indices: + return + + R,C = self.blocksize + M,N = self.shape + + bsr_sort_indices(M//R, N//C, R, C, self.indptr, self.indices, self.data.ravel()) + + self.has_sorted_indices = True + + def prune(self): + """Remove empty space after all non-zero elements. + """ + + R,C = self.blocksize + M,N = self.shape + + if len(self.indptr) != M//R + 1: + raise ValueError("index pointer has invalid length") + + bnnz = self.indptr[-1] + + if len(self.indices) < bnnz: + raise ValueError("indices array has too few elements") + if len(self.data) < bnnz: + raise ValueError("data array has too few elements") + + self.data = self.data[:bnnz] + self.indices = self.indices[:bnnz] + + # utility functions + def _binopt(self, other, op, in_shape=None, out_shape=None): + """Apply the binary operation fn to two sparse matrices.""" + + # Ideally we'd take the GCDs of the blocksize dimensions + # and explode self and other to match. + other = self.__class__(other, blocksize=self.blocksize) + + # e.g. bsr_plus_bsr, etc. + fn = getattr(_sparsetools, self.format + op + self.format) + + R,C = self.blocksize + + max_bnnz = len(self.data) + len(other.data) + idx_dtype = self._get_index_dtype((self.indptr, self.indices, + other.indptr, other.indices), + maxval=max_bnnz) + indptr = np.empty(self.indptr.shape, dtype=idx_dtype) + indices = np.empty(max_bnnz, dtype=idx_dtype) + + bool_ops = ['_ne_', '_lt_', '_gt_', '_le_', '_ge_'] + if op in bool_ops: + data = np.empty(R*C*max_bnnz, dtype=np.bool_) + else: + data = np.empty(R*C*max_bnnz, dtype=upcast(self.dtype,other.dtype)) + + fn(self.shape[0]//R, self.shape[1]//C, R, C, + self.indptr.astype(idx_dtype), + self.indices.astype(idx_dtype), + self.data, + other.indptr.astype(idx_dtype), + other.indices.astype(idx_dtype), + np.ravel(other.data), + indptr, + indices, + data) + + actual_bnnz = indptr[-1] + indices = indices[:actual_bnnz] + data = data[:R*C*actual_bnnz] + + if actual_bnnz < max_bnnz/2: + indices = indices.copy() + data = data.copy() + + data = data.reshape(-1,R,C) + + return self.__class__((data, indices, indptr), shape=self.shape) + + # needed by _data_matrix + def _with_data(self,data,copy=True): + """Returns a matrix with the same sparsity structure as self, + but with different data. By default the structure arrays + (i.e. .indptr and .indices) are copied. + """ + if copy: + return self.__class__((data,self.indices.copy(),self.indptr.copy()), + shape=self.shape,dtype=data.dtype) + else: + return self.__class__((data,self.indices,self.indptr), + shape=self.shape,dtype=data.dtype) + +# # these functions are used by the parent class +# # to remove redundancy between bsc_matrix and bsr_matrix +# def _swap(self,x): +# """swap the members of x if this is a column-oriented matrix +# """ +# return (x[0],x[1]) + + def _broadcast_to(self, shape, copy=False): + return _spbase._broadcast_to(self, shape, copy) + + +def isspmatrix_bsr(x): + """Is `x` of a bsr_matrix type? + + Parameters + ---------- + x + object to check for being a bsr matrix + + Returns + ------- + bool + True if `x` is a bsr matrix, False otherwise + + Examples + -------- + >>> from scipy.sparse import bsr_array, bsr_matrix, csr_matrix, isspmatrix_bsr + >>> isspmatrix_bsr(bsr_matrix([[5]])) + True + >>> isspmatrix_bsr(bsr_array([[5]])) + False + >>> isspmatrix_bsr(csr_matrix([[5]])) + False + """ + return isinstance(x, bsr_matrix) + + +# This namespace class separates array from matrix with isinstance +class bsr_array(_bsr_base, sparray): + """ + Block Sparse Row format sparse array. + + This can be instantiated in several ways: + bsr_array(D, [blocksize=(R,C)]) + where D is a 2-D ndarray. + + bsr_array(S, [blocksize=(R,C)]) + with another sparse array or matrix S (equivalent to S.tobsr()) + + bsr_array((M, N), [blocksize=(R,C), dtype]) + to construct an empty sparse array with shape (M, N) + dtype is optional, defaulting to dtype='d'. + + bsr_array((data, ij), [blocksize=(R,C), shape=(M, N)]) + where ``data`` and ``ij`` satisfy ``a[ij[0, k], ij[1, k]] = data[k]`` + + bsr_array((data, indices, indptr), [shape=(M, N)]) + is the standard BSR representation where the block column + indices for row i are stored in ``indices[indptr[i]:indptr[i+1]]`` + and their corresponding block values are stored in + ``data[ indptr[i]: indptr[i+1] ]``. If the shape parameter is not + supplied, the array dimensions are inferred from the index arrays. + + Attributes + ---------- + dtype : dtype + Data type of the array + shape : 2-tuple + Shape of the array + ndim : int + Number of dimensions (this is always 2) + nnz + size + data + BSR format data array of the array + indices + BSR format index array of the array + indptr + BSR format index pointer array of the array + blocksize + Block size + has_sorted_indices : bool + Whether indices are sorted + has_canonical_format : bool + T + + Notes + ----- + Sparse arrays can be used in arithmetic operations: they support + addition, subtraction, multiplication, division, and matrix power. + + **Summary of BSR format** + + The Block Sparse Row (BSR) format is very similar to the Compressed + Sparse Row (CSR) format. BSR is appropriate for sparse matrices with dense + sub matrices like the last example below. Such sparse block matrices often + arise in vector-valued finite element discretizations. In such cases, BSR is + considerably more efficient than CSR and CSC for many sparse arithmetic + operations. + + **Blocksize** + + The blocksize (R,C) must evenly divide the shape of the sparse array (M,N). + That is, R and C must satisfy the relationship ``M % R = 0`` and + ``N % C = 0``. + + If no blocksize is specified, a simple heuristic is applied to determine + an appropriate blocksize. + + **Canonical Format** + + In canonical format, there are no duplicate blocks and indices are sorted + per row. + + **Limitations** + + Block Sparse Row format sparse arrays do not support slicing. + + Examples + -------- + >>> import numpy as np + >>> from scipy.sparse import bsr_array + >>> bsr_array((3, 4), dtype=np.int8).toarray() + array([[0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0]], dtype=int8) + + >>> row = np.array([0, 0, 1, 2, 2, 2]) + >>> col = np.array([0, 2, 2, 0, 1, 2]) + >>> data = np.array([1, 2, 3 ,4, 5, 6]) + >>> bsr_array((data, (row, col)), shape=(3, 3)).toarray() + array([[1, 0, 2], + [0, 0, 3], + [4, 5, 6]]) + + >>> indptr = np.array([0, 2, 3, 6]) + >>> indices = np.array([0, 2, 2, 0, 1, 2]) + >>> data = np.array([1, 2, 3, 4, 5, 6]).repeat(4).reshape(6, 2, 2) + >>> bsr_array((data,indices,indptr), shape=(6, 6)).toarray() + array([[1, 1, 0, 0, 2, 2], + [1, 1, 0, 0, 2, 2], + [0, 0, 0, 0, 3, 3], + [0, 0, 0, 0, 3, 3], + [4, 4, 5, 5, 6, 6], + [4, 4, 5, 5, 6, 6]]) + + """ + + +class bsr_matrix(spmatrix, _bsr_base): + """ + Block Sparse Row format sparse matrix. + + This can be instantiated in several ways: + bsr_matrix(D, [blocksize=(R,C)]) + where D is a 2-D ndarray. + + bsr_matrix(S, [blocksize=(R,C)]) + with another sparse array or matrix S (equivalent to S.tobsr()) + + bsr_matrix((M, N), [blocksize=(R,C), dtype]) + to construct an empty sparse matrix with shape (M, N) + dtype is optional, defaulting to dtype='d'. + + bsr_matrix((data, ij), [blocksize=(R,C), shape=(M, N)]) + where ``data`` and ``ij`` satisfy ``a[ij[0, k], ij[1, k]] = data[k]`` + + bsr_matrix((data, indices, indptr), [shape=(M, N)]) + is the standard BSR representation where the block column + indices for row i are stored in ``indices[indptr[i]:indptr[i+1]]`` + and their corresponding block values are stored in + ``data[ indptr[i]: indptr[i+1] ]``. If the shape parameter is not + supplied, the matrix dimensions are inferred from the index arrays. + + Attributes + ---------- + dtype : dtype + Data type of the matrix + shape : 2-tuple + Shape of the matrix + ndim : int + Number of dimensions (this is always 2) + nnz + size + data + BSR format data array of the matrix + indices + BSR format index array of the matrix + indptr + BSR format index pointer array of the matrix + blocksize + Block size + has_sorted_indices : bool + Whether indices are sorted + has_canonical_format : bool + T + + Notes + ----- + Sparse matrices can be used in arithmetic operations: they support + addition, subtraction, multiplication, division, and matrix power. + + **Summary of BSR format** + + The Block Sparse Row (BSR) format is very similar to the Compressed + Sparse Row (CSR) format. BSR is appropriate for sparse matrices with dense + sub matrices like the last example below. Such sparse block matrices often + arise in vector-valued finite element discretizations. In such cases, BSR is + considerably more efficient than CSR and CSC for many sparse arithmetic + operations. + + **Blocksize** + + The blocksize (R,C) must evenly divide the shape of the sparse matrix (M,N). + That is, R and C must satisfy the relationship ``M % R = 0`` and + ``N % C = 0``. + + If no blocksize is specified, a simple heuristic is applied to determine + an appropriate blocksize. + + **Canonical Format** + + In canonical format, there are no duplicate blocks and indices are sorted + per row. + + **Limitations** + + Block Sparse Row format sparse matrices do not support slicing. + + Examples + -------- + >>> import numpy as np + >>> from scipy.sparse import bsr_matrix + >>> bsr_matrix((3, 4), dtype=np.int8).toarray() + array([[0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0]], dtype=int8) + + >>> row = np.array([0, 0, 1, 2, 2, 2]) + >>> col = np.array([0, 2, 2, 0, 1, 2]) + >>> data = np.array([1, 2, 3 ,4, 5, 6]) + >>> bsr_matrix((data, (row, col)), shape=(3, 3)).toarray() + array([[1, 0, 2], + [0, 0, 3], + [4, 5, 6]]) + + >>> indptr = np.array([0, 2, 3, 6]) + >>> indices = np.array([0, 2, 2, 0, 1, 2]) + >>> data = np.array([1, 2, 3, 4, 5, 6]).repeat(4).reshape(6, 2, 2) + >>> bsr_matrix((data,indices,indptr), shape=(6, 6)).toarray() + array([[1, 1, 0, 0, 2, 2], + [1, 1, 0, 0, 2, 2], + [0, 0, 0, 0, 3, 3], + [0, 0, 0, 0, 3, 3], + [4, 4, 5, 5, 6, 6], + [4, 4, 5, 5, 6, 6]]) + + """ + diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_compressed.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_compressed.py new file mode 100644 index 0000000000000000000000000000000000000000..e5f43c16bd924ac6bd70cfd4634dc3afcd298391 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_compressed.py @@ -0,0 +1,1500 @@ +"""Base class for sparse matrix formats using compressed storage.""" +__all__ = [] + +from warnings import warn +import itertools +import operator + +import numpy as np +from scipy._lib._util import _prune_array, copy_if_needed + +from ._base import _spbase, issparse, sparray, SparseEfficiencyWarning +from ._data import _data_matrix, _minmax_mixin +from . import _sparsetools +from ._sparsetools import (get_csr_submatrix, csr_sample_offsets, csr_todense, + csr_sample_values, csr_row_index, csr_row_slice, + csr_column_index1, csr_column_index2) +from ._index import IndexMixin +from ._sputils import (upcast, upcast_char, to_native, isdense, isshape, + getdtype, isscalarlike, isintlike, downcast_intp_index, + get_sum_dtype, check_shape, get_index_dtype, broadcast_shapes, + is_pydata_spmatrix) + + +class _cs_matrix(_data_matrix, _minmax_mixin, IndexMixin): + """ + base array/matrix class for compressed row- and column-oriented arrays/matrices + """ + + def __init__(self, arg1, shape=None, dtype=None, copy=False, *, maxprint=None): + _data_matrix.__init__(self, arg1, maxprint=maxprint) + + if issparse(arg1): + if arg1.format == self.format and copy: + arg1 = arg1.copy() + else: + arg1 = arg1.asformat(self.format) + self.indptr, self.indices, self.data, self._shape = ( + arg1.indptr, arg1.indices, arg1.data, arg1._shape + ) + + elif isinstance(arg1, tuple): + if isshape(arg1, allow_nd=self._allow_nd): + # It's a tuple of matrix dimensions (M, N) + # create empty matrix + self._shape = check_shape(arg1, allow_nd=self._allow_nd) + M, N = self._swap(self._shape_as_2d) + # Select index dtype large enough to pass array and + # scalar parameters to sparsetools + idx_dtype = self._get_index_dtype(maxval=max(self.shape)) + self.data = np.zeros(0, getdtype(dtype, default=float)) + self.indices = np.zeros(0, idx_dtype) + self.indptr = np.zeros(M + 1, dtype=idx_dtype) + else: + if len(arg1) == 2: + # (data, ij) format + coo = self._coo_container(arg1, shape=shape, dtype=dtype) + arrays = coo._coo_to_compressed(self._swap) + self.indptr, self.indices, self.data, self._shape = arrays + self.sum_duplicates() + elif len(arg1) == 3: + # (data, indices, indptr) format + (data, indices, indptr) = arg1 + + # Select index dtype large enough to pass array and + # scalar parameters to sparsetools + maxval = None + if shape is not None and 0 not in shape: + maxval = max(shape) + idx_dtype = self._get_index_dtype((indices, indptr), + maxval=maxval, + check_contents=True) + + if not copy: + copy = copy_if_needed + self.indices = np.array(indices, copy=copy, dtype=idx_dtype) + self.indptr = np.array(indptr, copy=copy, dtype=idx_dtype) + self.data = np.array(data, copy=copy, dtype=dtype) + else: + raise ValueError(f"unrecognized {self.__class__.__name__} " + f"constructor input: {arg1}") + + else: + # must be dense + try: + arg1 = np.asarray(arg1) + except Exception as e: + raise ValueError(f"unrecognized {self.__class__.__name__} " + f"constructor input: {arg1}") from e + if isinstance(self, sparray) and arg1.ndim != 2 and self.format == "csc": + raise ValueError(f"CSC arrays don't support {arg1.ndim}D input. Use 2D") + if arg1.ndim > 2: + raise ValueError(f"CSR arrays don't yet support {arg1.ndim}D.") + + coo = self._coo_container(arg1, dtype=dtype) + arrays = coo._coo_to_compressed(self._swap) + self.indptr, self.indices, self.data, self._shape = arrays + + # Read matrix dimensions given, if any + if shape is not None: + self._shape = check_shape(shape, allow_nd=self._allow_nd) + elif self.shape is None: + # shape not already set, try to infer dimensions + try: + M = len(self.indptr) - 1 + N = self.indices.max() + 1 + except Exception as e: + raise ValueError('unable to infer matrix dimensions') from e + + self._shape = check_shape(self._swap((M, N)), allow_nd=self._allow_nd) + + if dtype is not None: + newdtype = getdtype(dtype) + self.data = self.data.astype(newdtype, copy=False) + + self.check_format(full_check=False) + + def _getnnz(self, axis=None): + if axis is None: + return int(self.indptr[-1]) + elif self.ndim == 1: + if axis in (0, -1): + return int(self.indptr[-1]) + raise ValueError('axis out of bounds') + else: + if axis < 0: + axis += 2 + axis, _ = self._swap((axis, 1 - axis)) + _, N = self._swap(self.shape) + if axis == 0: + return np.bincount(downcast_intp_index(self.indices), minlength=N) + elif axis == 1: + return np.diff(self.indptr) + raise ValueError('axis out of bounds') + + _getnnz.__doc__ = _spbase._getnnz.__doc__ + + def count_nonzero(self, axis=None): + self.sum_duplicates() + if axis is None: + return np.count_nonzero(self.data) + + if self.ndim == 1: + if axis not in (0, -1): + raise ValueError('axis out of bounds') + return np.count_nonzero(self.data) + + if axis < 0: + axis += 2 + axis, _ = self._swap((axis, 1 - axis)) + if axis == 0: + _, N = self._swap(self.shape) + mask = self.data != 0 + idx = self.indices if mask.all() else self.indices[mask] + return np.bincount(downcast_intp_index(idx), minlength=N) + elif axis == 1: + if self.data.all(): + return np.diff(self.indptr) + pairs = itertools.pairwise(self.indptr) + return np.array([np.count_nonzero(self.data[i:j]) for i, j in pairs]) + else: + raise ValueError('axis out of bounds') + + count_nonzero.__doc__ = _spbase.count_nonzero.__doc__ + + def check_format(self, full_check=True): + """Check whether the array/matrix respects the CSR or CSC format. + + Parameters + ---------- + full_check : bool, optional + If `True`, run rigorous check, scanning arrays for valid values. + Note that activating those check might copy arrays for casting, + modifying indices and index pointers' inplace. + If `False`, run basic checks on attributes. O(1) operations. + Default is `True`. + """ + # index arrays should have integer data types + if self.indptr.dtype.kind != 'i': + warn(f"indptr array has non-integer dtype ({self.indptr.dtype.name})", + stacklevel=3) + if self.indices.dtype.kind != 'i': + warn(f"indices array has non-integer dtype ({self.indices.dtype.name})", + stacklevel=3) + + # check array shapes + for x in [self.data.ndim, self.indices.ndim, self.indptr.ndim]: + if x != 1: + raise ValueError('data, indices, and indptr should be 1-D') + + # check index pointer. Use _swap to determine proper bounds + M, N = self._swap(self._shape_as_2d) + + if (len(self.indptr) != M + 1): + raise ValueError(f"index pointer size {len(self.indptr)} should be {M + 1}") + if (self.indptr[0] != 0): + raise ValueError("index pointer should start with 0") + + # check index and data arrays + if (len(self.indices) != len(self.data)): + raise ValueError("indices and data should have the same size") + if (self.indptr[-1] > len(self.indices)): + raise ValueError("Last value of index pointer should be less than " + "the size of index and data arrays") + + self.prune() + + if full_check: + # check format validity (more expensive) + if self.nnz > 0: + if self.indices.max() >= N: + raise ValueError(f"indices must be < {N}") + if self.indices.min() < 0: + raise ValueError("indices must be >= 0") + if np.diff(self.indptr).min() < 0: + raise ValueError("indptr must be a non-decreasing sequence") + + idx_dtype = self._get_index_dtype((self.indptr, self.indices)) + self.indptr = np.asarray(self.indptr, dtype=idx_dtype) + self.indices = np.asarray(self.indices, dtype=idx_dtype) + self.data = to_native(self.data) + + # if not self.has_sorted_indices(): + # warn('Indices were not in sorted order. Sorting indices.') + # self.sort_indices() + # assert(self.has_sorted_indices()) + # TODO check for duplicates? + + ####################### + # Boolean comparisons # + ####################### + + def _scalar_binopt(self, other, op): + """Scalar version of self._binopt, for cases in which no new nonzeros + are added. Produces a new sparse array in canonical form. + """ + self.sum_duplicates() + res = self._with_data(op(self.data, other), copy=True) + res.eliminate_zeros() + return res + + def __eq__(self, other): + # Scalar other. + if isscalarlike(other): + if np.isnan(other): + return self.__class__(self.shape, dtype=np.bool_) + + if other == 0: + warn("Comparing a sparse matrix with 0 using == is inefficient" + ", try using != instead.", SparseEfficiencyWarning, + stacklevel=3) + all_true = self.__class__(np.ones(self.shape, dtype=np.bool_)) + inv = self._scalar_binopt(other, operator.ne) + return all_true - inv + else: + return self._scalar_binopt(other, operator.eq) + # Dense other. + elif isdense(other): + return self.todense() == other + # Pydata sparse other. + elif is_pydata_spmatrix(other): + return NotImplemented + # Sparse other. + elif issparse(other): + warn("Comparing sparse matrices using == is inefficient, try using" + " != instead.", SparseEfficiencyWarning, stacklevel=3) + # TODO sparse broadcasting + if self.shape != other.shape: + return False + elif self.format != other.format: + other = other.asformat(self.format) + res = self._binopt(other, '_ne_') + all_true = self.__class__(np.ones(self.shape, dtype=np.bool_)) + return all_true - res + else: + return NotImplemented + + def __ne__(self, other): + # Scalar other. + if isscalarlike(other): + if np.isnan(other): + warn("Comparing a sparse matrix with nan using != is" + " inefficient", SparseEfficiencyWarning, stacklevel=3) + all_true = self.__class__(np.ones(self.shape, dtype=np.bool_)) + return all_true + elif other != 0: + warn("Comparing a sparse matrix with a nonzero scalar using !=" + " is inefficient, try using == instead.", + SparseEfficiencyWarning, stacklevel=3) + all_true = self.__class__(np.ones(self.shape), dtype=np.bool_) + inv = self._scalar_binopt(other, operator.eq) + return all_true - inv + else: + return self._scalar_binopt(other, operator.ne) + # Dense other. + elif isdense(other): + return self.todense() != other + # Pydata sparse other. + elif is_pydata_spmatrix(other): + return NotImplemented + # Sparse other. + elif issparse(other): + # TODO sparse broadcasting + if self.shape != other.shape: + return True + elif self.format != other.format: + other = other.asformat(self.format) + return self._binopt(other, '_ne_') + else: + return NotImplemented + + def _inequality(self, other, op, op_name, bad_scalar_msg): + # Scalar other. + if isscalarlike(other): + if 0 == other and op_name in ('_le_', '_ge_'): + raise NotImplementedError(" >= and <= don't work with 0.") + elif op(0, other): + warn(bad_scalar_msg, SparseEfficiencyWarning, stacklevel=3) + other_arr = np.empty(self.shape, dtype=np.result_type(other)) + other_arr.fill(other) + other_arr = self.__class__(other_arr) + return self._binopt(other_arr, op_name) + else: + return self._scalar_binopt(other, op) + # Dense other. + elif isdense(other): + return op(self.todense(), other) + # Sparse other. + elif issparse(other): + # TODO sparse broadcasting + if self.shape != other.shape: + raise ValueError("inconsistent shapes") + elif self.format != other.format: + other = other.asformat(self.format) + if op_name not in ('_ge_', '_le_'): + return self._binopt(other, op_name) + + warn("Comparing sparse matrices using >= and <= is inefficient, " + "using <, >, or !=, instead.", + SparseEfficiencyWarning, stacklevel=3) + all_true = self.__class__(np.ones(self.shape, dtype=np.bool_)) + res = self._binopt(other, '_gt_' if op_name == '_le_' else '_lt_') + return all_true - res + else: + return NotImplemented + + def __lt__(self, other): + return self._inequality(other, operator.lt, '_lt_', + "Comparing a sparse matrix with a scalar " + "greater than zero using < is inefficient, " + "try using >= instead.") + + def __gt__(self, other): + return self._inequality(other, operator.gt, '_gt_', + "Comparing a sparse matrix with a scalar " + "less than zero using > is inefficient, " + "try using <= instead.") + + def __le__(self, other): + return self._inequality(other, operator.le, '_le_', + "Comparing a sparse matrix with a scalar " + "greater than zero using <= is inefficient, " + "try using > instead.") + + def __ge__(self, other): + return self._inequality(other, operator.ge, '_ge_', + "Comparing a sparse matrix with a scalar " + "less than zero using >= is inefficient, " + "try using < instead.") + + ################################# + # Arithmetic operator overrides # + ################################# + + def _add_dense(self, other): + if other.shape != self.shape: + raise ValueError(f'Incompatible shapes ({self.shape} and {other.shape})') + dtype = upcast_char(self.dtype.char, other.dtype.char) + order = self._swap('CF')[0] + result = np.array(other, dtype=dtype, order=order, copy=True) + y = result if result.flags.c_contiguous else result.T + M, N = self._swap(self._shape_as_2d) + csr_todense(M, N, self.indptr, self.indices, self.data, y) + return self._container(result, copy=False) + + def _add_sparse(self, other): + return self._binopt(other, '_plus_') + + def _sub_sparse(self, other): + return self._binopt(other, '_minus_') + + def multiply(self, other): + """Point-wise multiplication by array/matrix, vector, or scalar.""" + # Scalar multiplication. + if isscalarlike(other): + return self._mul_scalar(other) + # Sparse matrix or vector. + if issparse(other): + if self.shape == other.shape: + other = self.__class__(other) + return self._binopt(other, '_elmul_') + # Single element. + if other.shape == (1, 1): + result = self._mul_scalar(other.toarray()[0, 0]) + if self.ndim == 1: + return result.reshape((1, self.shape[0])) + return result + if other.shape == (1,): + return self._mul_scalar(other.toarray()[0]) + if self.shape in ((1,), (1, 1)): + return other._mul_scalar(self.data.sum()) + + # broadcast. treat 1d like a row + sM, sN = self._shape_as_2d + oM, oN = other._shape_as_2d + # A row times a column. + if sM == 1 and oN == 1: + return other._matmul_sparse(self.reshape(sM, sN).tocsc()) + if sN == 1 and oM == 1: + return self._matmul_sparse(other.reshape(oM, oN).tocsc()) + + is_array = isinstance(self, sparray) + # Other is a row. + if oM == 1 and sN == oN: + new_other = _make_diagonal_csr(other.toarray().ravel(), is_array) + result = self._matmul_sparse(new_other) + return result if self.ndim == 2 else result.reshape((1, oN)) + # self is a row. + if sM == 1 and sN == oN: + copy = _make_diagonal_csr(self.toarray().ravel(), is_array) + return other._matmul_sparse(copy) + + # Other is a column. + if oN == 1 and sM == oM: + new_other = _make_diagonal_csr(other.toarray().ravel(), is_array) + return new_other._matmul_sparse(self) + # self is a column. + if sN == 1 and sM == oM: + new_self = _make_diagonal_csr(self.toarray().ravel(), is_array) + return new_self._matmul_sparse(other) + raise ValueError("inconsistent shapes") + + # Assume other is a dense matrix/array, which produces a single-item + # object array if other isn't convertible to ndarray. + other = np.asanyarray(other) + + if other.ndim > 2: + return np.multiply(self.toarray(), other) + # Single element / wrapped object. + if other.size == 1: + if other.dtype == np.object_: + # 'other' not convertible to ndarray. + return NotImplemented + bshape = broadcast_shapes(self.shape, other.shape) + return self._mul_scalar(other.flat[0]).reshape(bshape) + # Fast case for trivial sparse matrix. + if self.shape in ((1,), (1, 1)): + bshape = broadcast_shapes(self.shape, other.shape) + return np.multiply(self.data.sum(), other).reshape(bshape) + + ret = self.tocoo() + # Matching shapes. + if self.shape == other.shape: + data = np.multiply(ret.data, other[ret.coords]) + ret.data = data.view(np.ndarray).ravel() + return ret + + # convert other to 2d + other2d = np.atleast_2d(other) + # Sparse row vector times... + if self.shape[0] == 1 or self.ndim == 1: + if other2d.shape[1] == 1: # Dense column vector. + data = np.multiply(ret.data, other2d) + elif other2d.shape[1] == self.shape[-1]: # Dense 2d matrix. + data = np.multiply(ret.data, other2d[:, ret.col]) + else: + raise ValueError("inconsistent shapes") + idx_dtype = self._get_index_dtype(ret.col, + maxval=ret.nnz * other2d.shape[0]) + row = np.repeat(np.arange(other2d.shape[0], dtype=idx_dtype), ret.nnz) + col = np.tile(ret.col.astype(idx_dtype, copy=False), other2d.shape[0]) + return self._coo_container( + (data.view(np.ndarray).ravel(), (row, col)), + shape=(other2d.shape[0], self.shape[-1]), + copy=False + ) + # Sparse column vector times... + if self.shape[1] == 1: + if other2d.shape[0] == 1: # Dense row vector. + data = np.multiply(ret.data[:, None], other2d) + elif other2d.shape[0] == self.shape[0]: # Dense 2d array. + data = np.multiply(ret.data[:, None], other2d[ret.row]) + else: + raise ValueError("inconsistent shapes") + idx_dtype = self._get_index_dtype(ret.row, + maxval=ret.nnz * other2d.shape[1]) + row = np.repeat(ret.row.astype(idx_dtype, copy=False), other2d.shape[1]) + col = np.tile(np.arange(other2d.shape[1], dtype=idx_dtype), ret.nnz) + return self._coo_container( + (data.view(np.ndarray).ravel(), (row, col)), + shape=(self.shape[0], other2d.shape[1]), + copy=False + ) + # Sparse matrix times dense row vector. + if other2d.shape[0] == 1 and self.shape[1] == other2d.shape[1]: + data = np.multiply(ret.data, other2d[:, ret.col].ravel()) + # Sparse matrix times dense column vector. + elif other2d.shape[1] == 1 and self.shape[0] == other2d.shape[0]: + data = np.multiply(ret.data, other2d[ret.row].ravel()) + else: + raise ValueError("inconsistent shapes") + ret.data = data.view(np.ndarray).ravel() + return ret + + ########################### + # Multiplication handlers # + ########################### + + def _matmul_vector(self, other): + M, N = self._shape_as_2d + + # output array + result = np.zeros(M, dtype=upcast_char(self.dtype.char, other.dtype.char)) + + # csr_matvec or csc_matvec + fn = getattr(_sparsetools, self.format + '_matvec') + fn(M, N, self.indptr, self.indices, self.data, other, result) + + return result[0] if self.ndim == 1 else result + + def _matmul_multivector(self, other): + M, N = self._shape_as_2d + n_vecs = other.shape[-1] # number of column vectors + + result = np.zeros((M, n_vecs), + dtype=upcast_char(self.dtype.char, other.dtype.char)) + + # csr_matvecs or csc_matvecs + fn = getattr(_sparsetools, self.format + '_matvecs') + fn(M, N, n_vecs, self.indptr, self.indices, self.data, + other.ravel(), result.ravel()) + + if self.ndim == 1: + return result.reshape((n_vecs,)) + return result + + def _matmul_sparse(self, other): + M, K1 = self._shape_as_2d + # if other is 1d, treat as a **column** + o_ndim = other.ndim + if o_ndim == 1: + # convert 1d array to a 2d column when on the right of @ + other = other.reshape((1, other.shape[0])).T # Note: converts to CSC + K2, N = other._shape if other.ndim == 2 else (other.shape[0], 1) + + # find new_shape: (M, N), (M,), (N,) or () + new_shape = () + if self.ndim == 2: + new_shape += (M,) + if o_ndim == 2: + new_shape += (N,) + faux_shape = (M if self.ndim == 2 else 1, N if o_ndim == 2 else 1) + + major_dim = self._swap((M, N))[0] + other = self.__class__(other) # convert to this format + + idx_dtype = self._get_index_dtype((self.indptr, self.indices, + other.indptr, other.indices)) + + fn = getattr(_sparsetools, self.format + '_matmat_maxnnz') + nnz = fn(M, N, + np.asarray(self.indptr, dtype=idx_dtype), + np.asarray(self.indices, dtype=idx_dtype), + np.asarray(other.indptr, dtype=idx_dtype), + np.asarray(other.indices, dtype=idx_dtype)) + if nnz == 0: + if new_shape == (): + return np.array(0, dtype=upcast(self.dtype, other.dtype)) + return self.__class__(new_shape, dtype=upcast(self.dtype, other.dtype)) + + idx_dtype = self._get_index_dtype((self.indptr, self.indices, + other.indptr, other.indices), + maxval=nnz) + + indptr = np.empty(major_dim + 1, dtype=idx_dtype) + indices = np.empty(nnz, dtype=idx_dtype) + data = np.empty(nnz, dtype=upcast(self.dtype, other.dtype)) + + fn = getattr(_sparsetools, self.format + '_matmat') + fn(M, N, np.asarray(self.indptr, dtype=idx_dtype), + np.asarray(self.indices, dtype=idx_dtype), + self.data, + np.asarray(other.indptr, dtype=idx_dtype), + np.asarray(other.indices, dtype=idx_dtype), + other.data, + indptr, indices, data) + + if new_shape == (): + return np.array(data[0]) + res = self.__class__((data, indices, indptr), shape=faux_shape) + if faux_shape != new_shape: + if res.format != 'csr': + res = res.tocsr() + res = res.reshape(new_shape) + return res + + def diagonal(self, k=0): + rows, cols = self.shape + if k <= -rows or k >= cols: + return np.empty(0, dtype=self.data.dtype) + fn = getattr(_sparsetools, self.format + "_diagonal") + y = np.empty(min(rows + min(k, 0), cols - max(k, 0)), + dtype=upcast(self.dtype)) + fn(k, self.shape[0], self.shape[1], self.indptr, self.indices, + self.data, y) + return y + + diagonal.__doc__ = _spbase.diagonal.__doc__ + + ##################### + # Other binary ops # + ##################### + + def _maximum_minimum(self, other, npop, op_name, dense_check): + if isscalarlike(other): + if dense_check(other): + warn("Taking maximum (minimum) with > 0 (< 0) number results" + " to a dense matrix.", SparseEfficiencyWarning, + stacklevel=3) + other_arr = np.empty(self.shape, dtype=np.asarray(other).dtype) + other_arr.fill(other) + other_arr = self.__class__(other_arr) + return self._binopt(other_arr, op_name) + else: + self.sum_duplicates() + new_data = npop(self.data, np.asarray(other)) + mat = self.__class__((new_data, self.indices, self.indptr), + dtype=new_data.dtype, shape=self.shape) + return mat + elif isdense(other): + return npop(self.todense(), other) + elif issparse(other): + return self._binopt(other, op_name) + else: + raise ValueError("Operands not compatible.") + + def maximum(self, other): + return self._maximum_minimum(other, np.maximum, + '_maximum_', lambda x: np.asarray(x) > 0) + + maximum.__doc__ = _spbase.maximum.__doc__ + + def minimum(self, other): + return self._maximum_minimum(other, np.minimum, + '_minimum_', lambda x: np.asarray(x) < 0) + + minimum.__doc__ = _spbase.minimum.__doc__ + + ##################### + # Reduce operations # + ##################### + + def sum(self, axis=None, dtype=None, out=None): + """Sum the array/matrix over the given axis. If the axis is None, sum + over both rows and columns, returning a scalar. + """ + # The _spbase base class already does axis=0 and axis=1 efficiently + # so we only do the case axis=None here + if (self.ndim == 2 and not hasattr(self, 'blocksize') and + axis in self._swap(((1, -1), (0, -2)))[0]): + # faster than multiplication for large minor axis in CSC/CSR + res_dtype = get_sum_dtype(self.dtype) + ret = np.zeros(len(self.indptr) - 1, dtype=res_dtype) + + major_index, value = self._minor_reduce(np.add) + ret[major_index] = value + ret = self._ascontainer(ret) + if axis % 2 == 1: + ret = ret.T + + return ret.sum(axis=(), dtype=dtype, out=out) + else: + # _spbase handles the situations when axis is in {None, -2, -1, 0, 1} + return _spbase.sum(self, axis=axis, dtype=dtype, out=out) + + sum.__doc__ = _spbase.sum.__doc__ + + def _minor_reduce(self, ufunc, data=None): + """Reduce nonzeros with a ufunc over the minor axis when non-empty + + Can be applied to a function of self.data by supplying data parameter. + + Warning: this does not call sum_duplicates() + + Returns + ------- + major_index : array of ints + Major indices where nonzero + + value : array of self.dtype + Reduce result for nonzeros in each major_index + """ + if data is None: + data = self.data + major_index = np.flatnonzero(np.diff(self.indptr)) + value = ufunc.reduceat(data, + downcast_intp_index(self.indptr[major_index])) + return major_index, value + + ####################### + # Getting and Setting # + ####################### + + def _get_intXint(self, row, col): + M, N = self._swap(self.shape) + major, minor = self._swap((row, col)) + indptr, indices, data = get_csr_submatrix( + M, N, self.indptr, self.indices, self.data, + major, major + 1, minor, minor + 1) + return data.sum(dtype=self.dtype) + + def _get_sliceXslice(self, row, col): + major, minor = self._swap((row, col)) + if major.step in (1, None) and minor.step in (1, None): + return self._get_submatrix(major, minor, copy=True) + return self._major_slice(major)._minor_slice(minor) + + def _get_arrayXarray(self, row, col): + # inner indexing + idx_dtype = self.indices.dtype + M, N = self._swap(self.shape) + major, minor = self._swap((row, col)) + major = np.asarray(major, dtype=idx_dtype) + minor = np.asarray(minor, dtype=idx_dtype) + + val = np.empty(major.size, dtype=self.dtype) + csr_sample_values(M, N, self.indptr, self.indices, self.data, + major.size, major.ravel(), minor.ravel(), val) + if major.ndim == 1: + return self._ascontainer(val) + return self.__class__(val.reshape(major.shape)) + + def _get_columnXarray(self, row, col): + # outer indexing + major, minor = self._swap((row, col)) + return self._major_index_fancy(major)._minor_index_fancy(minor) + + def _major_index_fancy(self, idx): + """Index along the major axis where idx is an array of ints. + """ + idx_dtype = self._get_index_dtype((self.indptr, self.indices)) + indices = np.asarray(idx, dtype=idx_dtype).ravel() + + N = self._swap(self._shape_as_2d)[1] + M = len(indices) + new_shape = self._swap((M, N)) if self.ndim == 2 else (M,) + if M == 0: + return self.__class__(new_shape, dtype=self.dtype) + + row_nnz = (self.indptr[indices + 1] - self.indptr[indices]).astype(idx_dtype) + res_indptr = np.zeros(M + 1, dtype=idx_dtype) + np.cumsum(row_nnz, out=res_indptr[1:]) + + nnz = res_indptr[-1] + res_indices = np.empty(nnz, dtype=idx_dtype) + res_data = np.empty(nnz, dtype=self.dtype) + csr_row_index( + M, + indices, + self.indptr.astype(idx_dtype, copy=False), + self.indices.astype(idx_dtype, copy=False), + self.data, + res_indices, + res_data + ) + + return self.__class__((res_data, res_indices, res_indptr), + shape=new_shape, copy=False) + + def _major_slice(self, idx, copy=False): + """Index along the major axis where idx is a slice object. + """ + if idx == slice(None): + return self.copy() if copy else self + + M, N = self._swap(self._shape_as_2d) + start, stop, step = idx.indices(M) + M = len(range(start, stop, step)) + new_shape = self._swap((M, N)) if self.ndim == 2 else (M,) + if M == 0: + return self.__class__(new_shape, dtype=self.dtype) + + # Work out what slices are needed for `row_nnz` + # start,stop can be -1, only if step is negative + start0, stop0 = start, stop + if stop == -1 and start >= 0: + stop0 = None + start1, stop1 = start + 1, stop + 1 + + row_nnz = self.indptr[start1:stop1:step] - \ + self.indptr[start0:stop0:step] + idx_dtype = self.indices.dtype + res_indptr = np.zeros(M+1, dtype=idx_dtype) + np.cumsum(row_nnz, out=res_indptr[1:]) + + if step == 1: + all_idx = slice(self.indptr[start], self.indptr[stop]) + res_indices = np.array(self.indices[all_idx], copy=copy) + res_data = np.array(self.data[all_idx], copy=copy) + else: + nnz = res_indptr[-1] + res_indices = np.empty(nnz, dtype=idx_dtype) + res_data = np.empty(nnz, dtype=self.dtype) + csr_row_slice(start, stop, step, self.indptr, self.indices, + self.data, res_indices, res_data) + + return self.__class__((res_data, res_indices, res_indptr), + shape=new_shape, copy=False) + + def _minor_index_fancy(self, idx): + """Index along the minor axis where idx is an array of ints. + """ + idx_dtype = self._get_index_dtype((self.indices, self.indptr)) + indices = self.indices.astype(idx_dtype, copy=False) + indptr = self.indptr.astype(idx_dtype, copy=False) + + idx = np.asarray(idx, dtype=idx_dtype).ravel() + + M, N = self._swap(self._shape_as_2d) + k = len(idx) + new_shape = self._swap((M, k)) if self.ndim == 2 else (k,) + if k == 0: + return self.__class__(new_shape, dtype=self.dtype) + + # pass 1: count idx entries and compute new indptr + col_offsets = np.zeros(N, dtype=idx_dtype) + res_indptr = np.empty_like(self.indptr, dtype=idx_dtype) + csr_column_index1( + k, + idx, + M, + N, + indptr, + indices, + col_offsets, + res_indptr, + ) + + # pass 2: copy indices/data for selected idxs + col_order = np.argsort(idx).astype(idx_dtype, copy=False) + nnz = res_indptr[-1] + res_indices = np.empty(nnz, dtype=idx_dtype) + res_data = np.empty(nnz, dtype=self.dtype) + csr_column_index2(col_order, col_offsets, len(self.indices), + indices, self.data, res_indices, res_data) + return self.__class__((res_data, res_indices, res_indptr), + shape=new_shape, copy=False) + + def _minor_slice(self, idx, copy=False): + """Index along the minor axis where idx is a slice object. + """ + if idx == slice(None): + return self.copy() if copy else self + + M, N = self._swap(self._shape_as_2d) + start, stop, step = idx.indices(N) + N = len(range(start, stop, step)) + if N == 0: + return self.__class__(self._swap((M, N)), dtype=self.dtype) + if step == 1: + return self._get_submatrix(minor=idx, copy=copy) + # TODO: don't fall back to fancy indexing here + return self._minor_index_fancy(np.arange(start, stop, step)) + + def _get_submatrix(self, major=None, minor=None, copy=False): + """Return a submatrix of this matrix. + + major, minor: None, int, or slice with step 1 + """ + M, N = self._swap(self._shape_as_2d) + i0, i1 = _process_slice(major, M) + j0, j1 = _process_slice(minor, N) + + if i0 == 0 and j0 == 0 and i1 == M and j1 == N: + return self.copy() if copy else self + + indptr, indices, data = get_csr_submatrix( + M, N, self.indptr, self.indices, self.data, i0, i1, j0, j1) + + shape = self._swap((i1 - i0, j1 - j0)) + if self.ndim == 1: + shape = (shape[1],) + return self.__class__((data, indices, indptr), shape=shape, + dtype=self.dtype, copy=False) + + def _set_intXint(self, row, col, x): + i, j = self._swap((row, col)) + self._set_many(i, j, x) + + def _set_arrayXarray(self, row, col, x): + i, j = self._swap((row, col)) + self._set_many(i, j, x) + + def _set_arrayXarray_sparse(self, row, col, x): + # clear entries that will be overwritten + self._zero_many(*self._swap((row, col))) + + M, N = row.shape # matches col.shape + broadcast_row = M != 1 and x.shape[0] == 1 + broadcast_col = N != 1 and x.shape[1] == 1 + r, c = x.row, x.col + + x = np.asarray(x.data, dtype=self.dtype) + if x.size == 0: + return + + if broadcast_row: + r = np.repeat(np.arange(M), len(r)) + c = np.tile(c, M) + x = np.tile(x, M) + if broadcast_col: + r = np.repeat(r, N) + c = np.tile(np.arange(N), len(c)) + x = np.repeat(x, N) + # only assign entries in the new sparsity structure + i, j = self._swap((row[r, c], col[r, c])) + self._set_many(i, j, x) + + def _setdiag(self, values, k): + if 0 in self.shape: + return + if self.ndim == 1: + raise NotImplementedError('diagonals cant be set in 1d arrays') + + M, N = self.shape + broadcast = (values.ndim == 0) + + if k < 0: + if broadcast: + max_index = min(M + k, N) + else: + max_index = min(M + k, N, len(values)) + i = np.arange(-k, max_index - k, dtype=self.indices.dtype) + j = np.arange(max_index, dtype=self.indices.dtype) + + else: + if broadcast: + max_index = min(M, N - k) + else: + max_index = min(M, N - k, len(values)) + i = np.arange(max_index, dtype=self.indices.dtype) + j = np.arange(k, k + max_index, dtype=self.indices.dtype) + + if not broadcast: + values = values[:len(i)] + + x = np.atleast_1d(np.asarray(values, dtype=self.dtype)).ravel() + if x.squeeze().shape != i.squeeze().shape: + x = np.broadcast_to(x, i.shape) + if x.size == 0: + return + + M, N = self._swap((M, N)) + i, j = self._swap((i, j)) + n_samples = x.size + offsets = np.empty(n_samples, dtype=self.indices.dtype) + ret = csr_sample_offsets(M, N, self.indptr, self.indices, n_samples, + i, j, offsets) + if ret == 1: + # rinse and repeat + self.sum_duplicates() + csr_sample_offsets(M, N, self.indptr, self.indices, n_samples, + i, j, offsets) + if -1 not in offsets: + # only affects existing non-zero cells + self.data[offsets] = x + return + + mask = (offsets >= 0) + # Boundary between csc and convert to coo + # The value 0.001 is justified in gh-19962#issuecomment-1920499678 + if self.nnz - mask.sum() < self.nnz * 0.001: + # replace existing entries + self.data[offsets[mask]] = x[mask] + # create new entries + mask = ~mask + i = i[mask] + j = j[mask] + self._insert_many(i, j, x[mask]) + else: + # convert to coo for _set_diag + coo = self.tocoo() + coo._setdiag(values, k) + arrays = coo._coo_to_compressed(self._swap) + self.indptr, self.indices, self.data, _ = arrays + + def _prepare_indices(self, i, j): + M, N = self._swap(self._shape_as_2d) + + def check_bounds(indices, bound): + idx = indices.max() + if idx >= bound: + raise IndexError(f'index ({idx}) out of range (>= {bound})') + idx = indices.min() + if idx < -bound: + raise IndexError(f'index ({idx}) out of range (< -{bound})') + + i = np.atleast_1d(np.asarray(i, dtype=self.indices.dtype)).ravel() + j = np.atleast_1d(np.asarray(j, dtype=self.indices.dtype)).ravel() + check_bounds(i, M) + check_bounds(j, N) + return i, j, M, N + + def _set_many(self, i, j, x): + """Sets value at each (i, j) to x + + Here (i,j) index major and minor respectively, and must not contain + duplicate entries. + """ + i, j, M, N = self._prepare_indices(i, j) + x = np.atleast_1d(np.asarray(x, dtype=self.dtype)).ravel() + + n_samples = x.size + offsets = np.empty(n_samples, dtype=self.indices.dtype) + ret = csr_sample_offsets(M, N, self.indptr, self.indices, n_samples, + i, j, offsets) + if ret == 1: + # rinse and repeat + self.sum_duplicates() + csr_sample_offsets(M, N, self.indptr, self.indices, n_samples, + i, j, offsets) + + if -1 not in offsets: + # only affects existing non-zero cells + self.data[offsets] = x + return + + else: + warn(f"Changing the sparsity structure of a {self.__class__.__name__} is" + " expensive. lil and dok are more efficient.", + SparseEfficiencyWarning, stacklevel=3) + # replace where possible + mask = offsets > -1 + self.data[offsets[mask]] = x[mask] + # only insertions remain + mask = ~mask + i = i[mask] + i[i < 0] += M + j = j[mask] + j[j < 0] += N + self._insert_many(i, j, x[mask]) + + def _zero_many(self, i, j): + """Sets value at each (i, j) to zero, preserving sparsity structure. + + Here (i,j) index major and minor respectively. + """ + i, j, M, N = self._prepare_indices(i, j) + + n_samples = len(i) + offsets = np.empty(n_samples, dtype=self.indices.dtype) + ret = csr_sample_offsets(M, N, self.indptr, self.indices, n_samples, + i, j, offsets) + if ret == 1: + # rinse and repeat + self.sum_duplicates() + csr_sample_offsets(M, N, self.indptr, self.indices, n_samples, + i, j, offsets) + + # only assign zeros to the existing sparsity structure + self.data[offsets[offsets > -1]] = 0 + + def _insert_many(self, i, j, x): + """Inserts new nonzero at each (i, j) with value x + + Here (i,j) index major and minor respectively. + i, j and x must be non-empty, 1d arrays. + Inserts each major group (e.g. all entries per row) at a time. + Maintains has_sorted_indices property. + Modifies i, j, x in place. + """ + order = np.argsort(i, kind='mergesort') # stable for duplicates + i = i.take(order, mode='clip') + j = j.take(order, mode='clip') + x = x.take(order, mode='clip') + + do_sort = self.has_sorted_indices + + # Update index data type + idx_dtype = self._get_index_dtype((self.indices, self.indptr), + maxval=(self.indptr[-1] + x.size)) + self.indptr = np.asarray(self.indptr, dtype=idx_dtype) + self.indices = np.asarray(self.indices, dtype=idx_dtype) + i = np.asarray(i, dtype=idx_dtype) + j = np.asarray(j, dtype=idx_dtype) + + # Collate old and new in chunks by major index + indices_parts = [] + data_parts = [] + ui, ui_indptr = np.unique(i, return_index=True) + ui_indptr = np.append(ui_indptr, len(j)) + new_nnzs = np.diff(ui_indptr) + prev = 0 + for c, (ii, js, je) in enumerate(zip(ui, ui_indptr, ui_indptr[1:])): + # old entries + start = self.indptr[prev] + stop = self.indptr[ii] + indices_parts.append(self.indices[start:stop]) + data_parts.append(self.data[start:stop]) + + # handle duplicate j: keep last setting + uj, uj_indptr = np.unique(j[js:je][::-1], return_index=True) + if len(uj) == je - js: + indices_parts.append(j[js:je]) + data_parts.append(x[js:je]) + else: + indices_parts.append(j[js:je][::-1][uj_indptr]) + data_parts.append(x[js:je][::-1][uj_indptr]) + new_nnzs[c] = len(uj) + + prev = ii + + # remaining old entries + start = self.indptr[ii] + indices_parts.append(self.indices[start:]) + data_parts.append(self.data[start:]) + + # update attributes + self.indices = np.concatenate(indices_parts) + self.data = np.concatenate(data_parts) + nnzs = np.empty(self.indptr.shape, dtype=idx_dtype) + nnzs[0] = idx_dtype(0) + indptr_diff = np.diff(self.indptr) + indptr_diff[ui] += new_nnzs + nnzs[1:] = indptr_diff + self.indptr = np.cumsum(nnzs, out=nnzs) + + if do_sort: + # TODO: only sort where necessary + self.has_sorted_indices = False + self.sort_indices() + + self.check_format(full_check=False) + + ###################### + # Conversion methods # + ###################### + + def tocoo(self, copy=True): + if self.ndim == 1: + csr = self.tocsr() + return self._coo_container((csr.data, (csr.indices,)), csr.shape, copy=copy) + major_dim, minor_dim = self._swap(self.shape) + minor_indices = self.indices + major_indices = np.empty(len(minor_indices), dtype=self.indices.dtype) + _sparsetools.expandptr(major_dim, self.indptr, major_indices) + coords = self._swap((major_indices, minor_indices)) + + return self._coo_container( + (self.data, coords), self.shape, copy=copy, dtype=self.dtype + ) + + tocoo.__doc__ = _spbase.tocoo.__doc__ + + def toarray(self, order=None, out=None): + if out is None and order is None: + order = self._swap('cf')[0] + out = self._process_toarray_args(order, out) + if not (out.flags.c_contiguous or out.flags.f_contiguous): + raise ValueError('Output array must be C or F contiguous') + # align ideal order with output array order + if out.flags.c_contiguous: + x = self.tocsr() + y = out + else: + x = self.tocsc() + y = out.T + M, N = x._swap(x._shape_as_2d) + csr_todense(M, N, x.indptr, x.indices, x.data, y) + return out + + toarray.__doc__ = _spbase.toarray.__doc__ + + ############################################################## + # methods that examine or modify the internal data structure # + ############################################################## + + def eliminate_zeros(self): + """Remove zero entries from the array/matrix + + This is an *in place* operation. + """ + M, N = self._swap(self._shape_as_2d) + _sparsetools.csr_eliminate_zeros(M, N, self.indptr, self.indices, self.data) + self.prune() # nnz may have changed + + @property + def has_canonical_format(self) -> bool: + """Whether the array/matrix has sorted indices and no duplicates + + Returns + - True: if the above applies + - False: otherwise + + has_canonical_format implies has_sorted_indices, so if the latter flag + is False, so will the former be; if the former is found True, the + latter flag is also set. + """ + # first check to see if result was cached + if not getattr(self, '_has_sorted_indices', True): + # not sorted => not canonical + self._has_canonical_format = False + elif not hasattr(self, '_has_canonical_format'): + self.has_canonical_format = bool( + _sparsetools.csr_has_canonical_format( + len(self.indptr) - 1, self.indptr, self.indices) + ) + return self._has_canonical_format + + @has_canonical_format.setter + def has_canonical_format(self, val: bool): + self._has_canonical_format = bool(val) + if val: + self.has_sorted_indices = True + + def sum_duplicates(self): + """Eliminate duplicate entries by adding them together + + This is an *in place* operation. + """ + if self.has_canonical_format: + return + self.sort_indices() + + M, N = self._swap(self._shape_as_2d) + _sparsetools.csr_sum_duplicates(M, N, self.indptr, self.indices, self.data) + + self.prune() # nnz may have changed + self.has_canonical_format = True + + @property + def has_sorted_indices(self) -> bool: + """Whether the indices are sorted + + Returns + - True: if the indices of the array/matrix are in sorted order + - False: otherwise + """ + # first check to see if result was cached + if not hasattr(self, '_has_sorted_indices'): + self._has_sorted_indices = bool( + _sparsetools.csr_has_sorted_indices( + len(self.indptr) - 1, self.indptr, self.indices) + ) + return self._has_sorted_indices + + @has_sorted_indices.setter + def has_sorted_indices(self, val: bool): + self._has_sorted_indices = bool(val) + + + def sorted_indices(self): + """Return a copy of this array/matrix with sorted indices + """ + A = self.copy() + A.sort_indices() + return A + + # an alternative that has linear complexity is the following + # although the previous option is typically faster + # return self.toother().toother() + + def sort_indices(self): + """Sort the indices of this array/matrix *in place* + """ + + if not self.has_sorted_indices: + _sparsetools.csr_sort_indices(len(self.indptr) - 1, self.indptr, + self.indices, self.data) + self.has_sorted_indices = True + + def prune(self): + """Remove empty space after all non-zero elements. + """ + major_dim = self._swap(self._shape_as_2d)[0] + + if len(self.indptr) != major_dim + 1: + raise ValueError('index pointer has invalid length') + if len(self.indices) < self.nnz: + raise ValueError('indices array has fewer than nnz elements') + if len(self.data) < self.nnz: + raise ValueError('data array has fewer than nnz elements') + + self.indices = _prune_array(self.indices[:self.nnz]) + self.data = _prune_array(self.data[:self.nnz]) + + def resize(self, *shape): + shape = check_shape(shape, allow_nd=self._allow_nd) + + if hasattr(self, 'blocksize'): + bm, bn = self.blocksize + new_M, rm = divmod(shape[0], bm) + new_N, rn = divmod(shape[1], bn) + if rm or rn: + raise ValueError(f"shape must be divisible into {self.blocksize}" + f" blocks. Got {shape}") + M, N = self.shape[0] // bm, self.shape[1] // bn + else: + new_M, new_N = self._swap(shape if len(shape)>1 else (1, shape[0])) + M, N = self._swap(self._shape_as_2d) + + if new_M < M: + self.indices = self.indices[:self.indptr[new_M]] + self.data = self.data[:self.indptr[new_M]] + self.indptr = self.indptr[:new_M + 1] + elif new_M > M: + self.indptr = np.resize(self.indptr, new_M + 1) + self.indptr[M + 1:].fill(self.indptr[M]) + + if new_N < N: + mask = self.indices < new_N + if not np.all(mask): + self.indices = self.indices[mask] + self.data = self.data[mask] + major_index, val = self._minor_reduce(np.add, mask) + self.indptr.fill(0) + self.indptr[1:][major_index] = val + np.cumsum(self.indptr, out=self.indptr) + + self._shape = shape + + resize.__doc__ = _spbase.resize.__doc__ + + ################### + # utility methods # + ################### + + # needed by _data_matrix + def _with_data(self, data, copy=True): + """Returns a matrix with the same sparsity structure as self, + but with different data. By default the structure arrays + (i.e. .indptr and .indices) are copied. + """ + if copy: + return self.__class__((data, self.indices.copy(), + self.indptr.copy()), + shape=self.shape, + dtype=data.dtype) + else: + return self.__class__((data, self.indices, self.indptr), + shape=self.shape, dtype=data.dtype) + + def _binopt(self, other, op): + """apply the binary operation fn to two sparse matrices.""" + other = self.__class__(other) + + # e.g. csr_plus_csr, csr_minus_csr, etc. + fn = getattr(_sparsetools, self.format + op + self.format) + + maxnnz = self.nnz + other.nnz + idx_dtype = self._get_index_dtype((self.indptr, self.indices, + other.indptr, other.indices), + maxval=maxnnz) + indptr = np.empty(self.indptr.shape, dtype=idx_dtype) + indices = np.empty(maxnnz, dtype=idx_dtype) + + bool_ops = ['_ne_', '_lt_', '_gt_', '_le_', '_ge_'] + if op in bool_ops: + data = np.empty(maxnnz, dtype=np.bool_) + else: + data = np.empty(maxnnz, dtype=upcast(self.dtype, other.dtype)) + + M, N = self._shape_as_2d + fn(M, N, + np.asarray(self.indptr, dtype=idx_dtype), + np.asarray(self.indices, dtype=idx_dtype), + self.data, + np.asarray(other.indptr, dtype=idx_dtype), + np.asarray(other.indices, dtype=idx_dtype), + other.data, + indptr, indices, data) + + A = self.__class__((data, indices, indptr), shape=self.shape) + A.prune() + + return A + + def _divide_sparse(self, other): + """ + Divide this matrix by a second sparse matrix. + """ + if other.shape != self.shape: + raise ValueError('inconsistent shapes') + + r = self._binopt(other, '_eldiv_') + + if np.issubdtype(r.dtype, np.inexact): + # Eldiv leaves entries outside the combined sparsity + # pattern empty, so they must be filled manually. + # Everything outside of other's sparsity is NaN, and everything + # inside it is either zero or defined by eldiv. + out = np.empty(self.shape, dtype=self.dtype) + out.fill(np.nan) + coords = other.nonzero() + if self.ndim == 1: + coords = (coords[-1],) + out[coords] = 0 + r = r.tocoo() + out[r.coords] = r.data + return self._container(out) + else: + # integers types go with nan <-> 0 + out = r + return out + + def _broadcast_to(self, shape, copy=False): + if self.shape == shape: + return self.copy() if copy else self + + shape = check_shape(shape, allow_nd=(self._allow_nd)) + + if broadcast_shapes(self.shape, shape) != shape: + raise ValueError("cannot be broadcast") + + if len(self.shape) == 1 and len(shape) == 1: + self.sum_duplicates() + if self.nnz == 0: # array has no non zero elements + return self.__class__(shape, dtype=self.dtype, copy=False) + + N = shape[0] + data = np.full(N, self.data[0]) + indices = np.arange(0,N) + indptr = np.array([0, N]) + return self._csr_container((data, indices, indptr), shape=shape, copy=False) + + # treat 1D as a 2D row + old_shape = self._shape_as_2d + + if len(shape) != 2: + ndim = len(shape) + raise ValueError(f'CSR/CSC broadcast_to cannot have shape >2D. Got {ndim}D') + + if self.nnz == 0: # array has no non zero elements + return self.__class__(shape, dtype=self.dtype, copy=False) + + self.sum_duplicates() + M, N = self._swap(shape) + oM, oN = self._swap(old_shape) + if all(s == 1 for s in old_shape): + # Broadcast a single element to the entire shape + data = np.full(M * N, self.data[0]) + indices = np.tile(np.arange(N), M) + indptr = np.arange(0, len(data) + 1, N) + elif oM == 1 and oN == N: + # Broadcast row-wise (columns for CSC) + data = np.tile(self.data, M) + indices = np.tile(self.indices, M) + indptr = np.arange(0, len(data) + 1, len(self.data)) + elif oN == 1 and oM == M: + # Broadcast column-wise (rows for CSC) + data = np.repeat(self.data, N) + indices = np.tile(np.arange(N), len(self.data)) + indptr = self.indptr * N + return self.__class__((data, indices, indptr), shape=shape, copy=False) + + +def _make_diagonal_csr(data, is_array=False): + """build diagonal csc_array/csr_array => self._csr_container + + Parameter `data` should be a raveled numpy array holding the + values on the diagonal of the resulting sparse matrix. + """ + from ._csr import csr_array, csr_matrix + csr_array = csr_array if is_array else csr_matrix + + N = len(data) + idx_dtype = get_index_dtype(maxval=N) + indptr = np.arange(N + 1, dtype=idx_dtype) + indices = indptr[:-1] + + return csr_array((data, indices, indptr), shape=(N, N)) + + +def _process_slice(sl, num): + if sl is None: + i0, i1 = 0, num + elif isinstance(sl, slice): + i0, i1, stride = sl.indices(num) + if stride != 1: + raise ValueError('slicing with step != 1 not supported') + i0 = min(i0, i1) # give an empty slice when i0 > i1 + elif isintlike(sl): + if sl < 0: + sl += num + i0, i1 = sl, sl + 1 + if i0 < 0 or i1 > num: + raise IndexError(f'index out of bounds: 0 <= {i0} < {i1} <= {num}') + else: + raise TypeError('expected slice or scalar') + + return i0, i1 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_construct.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_construct.py new file mode 100644 index 0000000000000000000000000000000000000000..f483976badb771d777c9dba0eecfbeb94d2e76fd --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_construct.py @@ -0,0 +1,1402 @@ +"""Functions to construct sparse matrices and arrays +""" + +__docformat__ = "restructuredtext en" + +__all__ = ['spdiags', 'eye', 'identity', 'kron', 'kronsum', + 'hstack', 'vstack', 'bmat', 'rand', 'random', 'diags', 'block_diag', + 'diags_array', 'block_array', 'eye_array', 'random_array'] + +import numbers +import math +import numpy as np + +from scipy._lib._util import check_random_state, rng_integers, _transition_to_rng +from ._sputils import upcast, get_index_dtype, isscalarlike + +from ._sparsetools import csr_hstack +from ._bsr import bsr_matrix, bsr_array +from ._coo import coo_matrix, coo_array +from ._csc import csc_matrix, csc_array +from ._csr import csr_matrix, csr_array +from ._dia import dia_matrix, dia_array + +from ._base import issparse, sparray + + +def spdiags(data, diags, m=None, n=None, format=None): + """ + Return a sparse matrix from diagonals. + + Parameters + ---------- + data : array_like + Matrix diagonals stored row-wise + diags : sequence of int or an int + Diagonals to set: + + * k = 0 the main diagonal + * k > 0 the kth upper diagonal + * k < 0 the kth lower diagonal + m, n : int, tuple, optional + Shape of the result. If `n` is None and `m` is a given tuple, + the shape is this tuple. If omitted, the matrix is square and + its shape is len(data[0]). + format : str, optional + Format of the result. By default (format=None) an appropriate sparse + matrix format is returned. This choice is subject to change. + + .. warning:: + + This function returns a sparse matrix -- not a sparse array. + You are encouraged to use ``dia_array`` to take advantage + of the sparse array functionality. + + Notes + ----- + This function can be replaced by an equivalent call to ``dia_matrix`` + as:: + + dia_matrix((data, diags), shape=(m, n)).asformat(format) + + See Also + -------- + diags_array : more convenient form of this function + diags : matrix version of diags_array + dia_matrix : the sparse DIAgonal format. + + Examples + -------- + >>> import numpy as np + >>> from scipy.sparse import spdiags + >>> data = np.array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]) + >>> diags = np.array([0, -1, 2]) + >>> spdiags(data, diags, 4, 4).toarray() + array([[1, 0, 3, 0], + [1, 2, 0, 4], + [0, 2, 3, 0], + [0, 0, 3, 4]]) + + """ + if m is None and n is None: + m = n = len(data[0]) + elif n is None: + m, n = m + return dia_matrix((data, diags), shape=(m, n)).asformat(format) + + +def diags_array(diagonals, /, *, offsets=0, shape=None, format=None, dtype=None): + """ + Construct a sparse array from diagonals. + + Parameters + ---------- + diagonals : sequence of array_like + Sequence of arrays containing the array diagonals, + corresponding to `offsets`. + offsets : sequence of int or an int, optional + Diagonals to set (repeated offsets are not allowed): + - k = 0 the main diagonal (default) + - k > 0 the kth upper diagonal + - k < 0 the kth lower diagonal + shape : tuple of int, optional + Shape of the result. If omitted, a square array large enough + to contain the diagonals is returned. + format : {"dia", "csr", "csc", "lil", ...}, optional + Matrix format of the result. By default (format=None) an + appropriate sparse array format is returned. This choice is + subject to change. + dtype : dtype, optional + Data type of the array. + + Notes + ----- + Repeated diagonal offsets are disallowed. + + The result from `diags_array` is the sparse equivalent of:: + + np.diag(diagonals[0], offsets[0]) + + ... + + np.diag(diagonals[k], offsets[k]) + + ``diags_array`` differs from `dia_array` in the way it handles off-diagonals. + Specifically, `dia_array` assumes the data input includes padding + (ignored values) at the start/end of the rows for positive/negative + offset, while ``diags_array` assumes the input data has no padding. + Each value in the input ``diagonals`` is used. + + .. versionadded:: 1.11 + + Examples + -------- + >>> from scipy.sparse import diags_array + >>> diagonals = [[1, 2, 3, 4], [1, 2, 3], [1, 2]] + >>> diags_array(diagonals, offsets=[0, -1, 2]).toarray() + array([[1., 0., 1., 0.], + [1., 2., 0., 2.], + [0., 2., 3., 0.], + [0., 0., 3., 4.]]) + + Broadcasting of scalars is supported (but shape needs to be + specified): + + >>> diags_array([1, -2, 1], offsets=[-1, 0, 1], shape=(4, 4)).toarray() + array([[-2., 1., 0., 0.], + [ 1., -2., 1., 0.], + [ 0., 1., -2., 1.], + [ 0., 0., 1., -2.]]) + + + If only one diagonal is wanted (as in `numpy.diag`), the following + works as well: + + >>> diags_array([1, 2, 3], offsets=1).toarray() + array([[ 0., 1., 0., 0.], + [ 0., 0., 2., 0.], + [ 0., 0., 0., 3.], + [ 0., 0., 0., 0.]]) + + """ + # if offsets is not a sequence, assume that there's only one diagonal + if isscalarlike(offsets): + # now check that there's actually only one diagonal + if len(diagonals) == 0 or isscalarlike(diagonals[0]): + diagonals = [np.atleast_1d(diagonals)] + else: + raise ValueError("Different number of diagonals and offsets.") + else: + diagonals = list(map(np.atleast_1d, diagonals)) + + offsets = np.atleast_1d(offsets) + + # Basic check + if len(diagonals) != len(offsets): + raise ValueError("Different number of diagonals and offsets.") + + # Determine shape, if omitted + if shape is None: + m = len(diagonals[0]) + abs(int(offsets[0])) + shape = (m, m) + + # Determine data type, if omitted + if dtype is None: + dtype = np.common_type(*diagonals) + + # Construct data array + m, n = shape + + M = max([min(m + offset, n - offset) + max(0, offset) + for offset in offsets]) + M = max(0, M) + data_arr = np.zeros((len(offsets), M), dtype=dtype) + + K = min(m, n) + + for j, diagonal in enumerate(diagonals): + offset = offsets[j] + k = max(0, offset) + length = min(m + offset, n - offset, K) + if length < 0: + raise ValueError(f"Offset {offset} (index {j}) out of bounds") + try: + data_arr[j, k:k+length] = diagonal[...,:length] + except ValueError as e: + if len(diagonal) != length and len(diagonal) != 1: + raise ValueError( + f"Diagonal length (index {j}: {len(diagonal)} at" + f" offset {offset}) does not agree with array size ({m}, {n})." + ) from e + raise + + return dia_array((data_arr, offsets), shape=(m, n)).asformat(format) + + +def diags(diagonals, offsets=0, shape=None, format=None, dtype=None): + """ + Construct a sparse matrix from diagonals. + + .. warning:: + + This function returns a sparse matrix -- not a sparse array. + You are encouraged to use ``diags_array`` to take advantage + of the sparse array functionality. + + Parameters + ---------- + diagonals : sequence of array_like + Sequence of arrays containing the matrix diagonals, + corresponding to `offsets`. + offsets : sequence of int or an int, optional + Diagonals to set (repeated offsets are not allowed): + - k = 0 the main diagonal (default) + - k > 0 the kth upper diagonal + - k < 0 the kth lower diagonal + shape : tuple of int, optional + Shape of the result. If omitted, a square matrix large enough + to contain the diagonals is returned. + format : {"dia", "csr", "csc", "lil", ...}, optional + Matrix format of the result. By default (format=None) an + appropriate sparse matrix format is returned. This choice is + subject to change. + dtype : dtype, optional + Data type of the matrix. + + See Also + -------- + spdiags : construct matrix from diagonals + diags_array : construct sparse array instead of sparse matrix + + Notes + ----- + Repeated diagonal offsets are disallowed. + + The result from `diags` is the sparse equivalent of:: + + np.diag(diagonals[0], offsets[0]) + + ... + + np.diag(diagonals[k], offsets[k]) + + ``diags`` differs from ``dia_matrix`` in the way it handles off-diagonals. + Specifically, `dia_matrix` assumes the data input includes padding + (ignored values) at the start/end of the rows for positive/negative + offset, while ``diags` assumes the input data has no padding. + Each value in the input ``diagonals`` is used. + + .. versionadded:: 0.11 + + Examples + -------- + >>> from scipy.sparse import diags + >>> diagonals = [[1, 2, 3, 4], [1, 2, 3], [1, 2]] + >>> diags(diagonals, [0, -1, 2]).toarray() + array([[1., 0., 1., 0.], + [1., 2., 0., 2.], + [0., 2., 3., 0.], + [0., 0., 3., 4.]]) + + Broadcasting of scalars is supported (but shape needs to be + specified): + + >>> diags([1, -2, 1], [-1, 0, 1], shape=(4, 4)).toarray() + array([[-2., 1., 0., 0.], + [ 1., -2., 1., 0.], + [ 0., 1., -2., 1.], + [ 0., 0., 1., -2.]]) + + + If only one diagonal is wanted (as in `numpy.diag`), the following + works as well: + + >>> diags([1, 2, 3], 1).toarray() + array([[ 0., 1., 0., 0.], + [ 0., 0., 2., 0.], + [ 0., 0., 0., 3.], + [ 0., 0., 0., 0.]]) + + """ + A = diags_array(diagonals, offsets=offsets, shape=shape, dtype=dtype) + return dia_matrix(A).asformat(format) + + +def identity(n, dtype='d', format=None): + """Identity matrix in sparse format + + Returns an identity matrix with shape (n,n) using a given + sparse format and dtype. This differs from `eye_array` in + that it has a square shape with ones only on the main diagonal. + It is thus the multiplicative identity. `eye_array` allows + rectangular shapes and the diagonal can be offset from the main one. + + .. warning:: + + This function returns a sparse matrix -- not a sparse array. + You are encouraged to use ``eye_array`` to take advantage + of the sparse array functionality. + + Parameters + ---------- + n : int + Shape of the identity matrix. + dtype : dtype, optional + Data type of the matrix + format : str, optional + Sparse format of the result, e.g., format="csr", etc. + + Examples + -------- + >>> import scipy as sp + >>> sp.sparse.identity(3).toarray() + array([[ 1., 0., 0.], + [ 0., 1., 0.], + [ 0., 0., 1.]]) + >>> sp.sparse.identity(3, dtype='int8', format='dia') + + >>> sp.sparse.eye_array(3, dtype='int8', format='dia') + + + """ + return eye(n, n, dtype=dtype, format=format) + + +def eye_array(m, n=None, *, k=0, dtype=float, format=None): + """Identity matrix in sparse array format + + Return a sparse array with ones on diagonal. + Specifically a sparse array (m x n) where the kth diagonal + is all ones and everything else is zeros. + + Parameters + ---------- + m : int + Number of rows requested. + n : int, optional + Number of columns. Default: `m`. + k : int, optional + Diagonal to place ones on. Default: 0 (main diagonal). + dtype : dtype, optional + Data type of the array + format : str, optional (default: "dia") + Sparse format of the result, e.g., format="csr", etc. + + Examples + -------- + >>> import numpy as np + >>> import scipy as sp + >>> sp.sparse.eye_array(3).toarray() + array([[ 1., 0., 0.], + [ 0., 1., 0.], + [ 0., 0., 1.]]) + >>> sp.sparse.eye_array(3, dtype=np.int8) + + + """ + # TODO: delete next 15 lines [combine with _eye()] once spmatrix removed + return _eye(m, n, k, dtype, format) + + +def _eye(m, n, k, dtype, format, as_sparray=True): + if as_sparray: + csr_sparse = csr_array + csc_sparse = csc_array + coo_sparse = coo_array + diags_sparse = diags_array + else: + csr_sparse = csr_matrix + csc_sparse = csc_matrix + coo_sparse = coo_matrix + diags_sparse = diags + + if n is None: + n = m + m, n = int(m), int(n) + + if m == n and k == 0: + # fast branch for special formats + if format in ['csr', 'csc']: + idx_dtype = get_index_dtype(maxval=n) + indptr = np.arange(n+1, dtype=idx_dtype) + indices = np.arange(n, dtype=idx_dtype) + data = np.ones(n, dtype=dtype) + cls = {'csr': csr_sparse, 'csc': csc_sparse}[format] + return cls((data, indices, indptr), (n, n)) + + elif format == 'coo': + idx_dtype = get_index_dtype(maxval=n) + row = np.arange(n, dtype=idx_dtype) + col = np.arange(n, dtype=idx_dtype) + data = np.ones(n, dtype=dtype) + return coo_sparse((data, (row, col)), (n, n)) + + data = np.ones((1, max(0, min(m + k, n))), dtype=dtype) + return diags_sparse(data, offsets=[k], shape=(m, n), dtype=dtype).asformat(format) + + +def eye(m, n=None, k=0, dtype=float, format=None): + """Sparse matrix with ones on diagonal + + Returns a sparse matrix (m x n) where the kth diagonal + is all ones and everything else is zeros. + + Parameters + ---------- + m : int + Number of rows in the matrix. + n : int, optional + Number of columns. Default: `m`. + k : int, optional + Diagonal to place ones on. Default: 0 (main diagonal). + dtype : dtype, optional + Data type of the matrix. + format : str, optional + Sparse format of the result, e.g., format="csr", etc. + + .. warning:: + + This function returns a sparse matrix -- not a sparse array. + You are encouraged to use ``eye_array`` to take advantage + of the sparse array functionality. + + Examples + -------- + >>> import numpy as np + >>> import scipy as sp + >>> sp.sparse.eye(3).toarray() + array([[ 1., 0., 0.], + [ 0., 1., 0.], + [ 0., 0., 1.]]) + >>> sp.sparse.eye(3, dtype=np.int8) + + + """ + return _eye(m, n, k, dtype, format, False) + + +def kron(A, B, format=None): + """kronecker product of sparse matrices A and B + + Parameters + ---------- + A : sparse or dense matrix + first matrix of the product + B : sparse or dense matrix + second matrix of the product + format : str, optional (default: 'bsr' or 'coo') + format of the result (e.g. "csr") + If None, choose 'bsr' for relatively dense array and 'coo' for others + + Returns + ------- + kronecker product in a sparse format. + Returns a sparse matrix unless either A or B is a + sparse array in which case returns a sparse array. + + Examples + -------- + >>> import numpy as np + >>> import scipy as sp + >>> A = sp.sparse.csr_array(np.array([[0, 2], [5, 0]])) + >>> B = sp.sparse.csr_array(np.array([[1, 2], [3, 4]])) + >>> sp.sparse.kron(A, B).toarray() + array([[ 0, 0, 2, 4], + [ 0, 0, 6, 8], + [ 5, 10, 0, 0], + [15, 20, 0, 0]]) + + >>> sp.sparse.kron(A, [[1, 2], [3, 4]]).toarray() + array([[ 0, 0, 2, 4], + [ 0, 0, 6, 8], + [ 5, 10, 0, 0], + [15, 20, 0, 0]]) + + """ + # TODO: delete next 10 lines and replace _sparse with _array when spmatrix removed + if isinstance(A, sparray) or isinstance(B, sparray): + # convert to local variables + bsr_sparse = bsr_array + csr_sparse = csr_array + coo_sparse = coo_array + else: # use spmatrix + bsr_sparse = bsr_matrix + csr_sparse = csr_matrix + coo_sparse = coo_matrix + + B = coo_sparse(B) + if B.ndim != 2: + raise ValueError(f"kron requires 2D input arrays. `B` is {B.ndim}D.") + + # B is fairly dense, use BSR + if (format is None or format == "bsr") and 2*B.nnz >= B.shape[0] * B.shape[1]: + A = csr_sparse(A,copy=True) + if A.ndim != 2: + raise ValueError(f"kron requires 2D input arrays. `A` is {A.ndim}D.") + output_shape = (A.shape[0]*B.shape[0], A.shape[1]*B.shape[1]) + + if A.nnz == 0 or B.nnz == 0: + # kronecker product is the zero matrix + return coo_sparse(output_shape).asformat(format) + + B = B.toarray() + data = A.data.repeat(B.size).reshape(-1,B.shape[0],B.shape[1]) + data = data * B + + return bsr_sparse((data,A.indices,A.indptr), shape=output_shape) + else: + # use COO + A = coo_sparse(A) + if A.ndim != 2: + raise ValueError(f"kron requires 2D input arrays. `A` is {A.ndim}D.") + output_shape = (A.shape[0]*B.shape[0], A.shape[1]*B.shape[1]) + + if A.nnz == 0 or B.nnz == 0: + # kronecker product is the zero matrix + return coo_sparse(output_shape).asformat(format) + + # expand entries of a into blocks + idx_dtype = get_index_dtype(A.coords, maxval=max(output_shape)) + row = np.asarray(A.row, dtype=idx_dtype).repeat(B.nnz) + col = np.asarray(A.col, dtype=idx_dtype).repeat(B.nnz) + data = A.data.repeat(B.nnz) + + row *= B.shape[0] + col *= B.shape[1] + + # increment block indices + row,col = row.reshape(-1,B.nnz),col.reshape(-1,B.nnz) + row += B.row + col += B.col + row,col = row.reshape(-1),col.reshape(-1) + + # compute block entries + data = data.reshape(-1,B.nnz) * B.data + data = data.reshape(-1) + + return coo_sparse((data,(row,col)), shape=output_shape).asformat(format) + + +def kronsum(A, B, format=None): + """kronecker sum of square sparse matrices A and B + + Kronecker sum of two sparse matrices is a sum of two Kronecker + products kron(I_n,A) + kron(B,I_m) where A has shape (m,m) + and B has shape (n,n) and I_m and I_n are identity matrices + of shape (m,m) and (n,n), respectively. + + Parameters + ---------- + A + square matrix + B + square matrix + format : str + format of the result (e.g. "csr") + + Returns + ------- + kronecker sum in a sparse matrix format + + """ + # TODO: delete next 8 lines and replace _sparse with _array when spmatrix removed + if isinstance(A, sparray) or isinstance(B, sparray): + # convert to local variables + coo_sparse = coo_array + identity_sparse = eye_array + else: + coo_sparse = coo_matrix + identity_sparse = identity + + A = coo_sparse(A) + B = coo_sparse(B) + + if A.ndim != 2: + raise ValueError(f"kronsum requires 2D inputs. `A` is {A.ndim}D.") + if B.ndim != 2: + raise ValueError(f"kronsum requires 2D inputs. `B` is {B.ndim}D.") + if A.shape[0] != A.shape[1]: + raise ValueError('A is not square') + if B.shape[0] != B.shape[1]: + raise ValueError('B is not square') + + dtype = upcast(A.dtype, B.dtype) + + I_n = identity_sparse(A.shape[0], dtype=dtype) + I_m = identity_sparse(B.shape[0], dtype=dtype) + L = kron(I_m, A, format='coo') + R = kron(B, I_n, format='coo') + + return (L + R).asformat(format) + + +def _compressed_sparse_stack(blocks, axis, return_spmatrix): + """ + Stacking fast path for CSR/CSC matrices or arrays + (i) vstack for CSR, (ii) hstack for CSC. + """ + other_axis = 1 if axis == 0 else 0 + data = np.concatenate([b.data for b in blocks]) + constant_dim = blocks[0]._shape_as_2d[other_axis] + idx_dtype = get_index_dtype(arrays=[b.indptr for b in blocks], + maxval=max(data.size, constant_dim)) + indices = np.empty(data.size, dtype=idx_dtype) + indptr = np.empty(sum(b._shape_as_2d[axis] for b in blocks) + 1, dtype=idx_dtype) + last_indptr = idx_dtype(0) + sum_dim = 0 + sum_indices = 0 + for b in blocks: + if b._shape_as_2d[other_axis] != constant_dim: + raise ValueError(f'incompatible dimensions for axis {other_axis}') + indices[sum_indices:sum_indices+b.indices.size] = b.indices + sum_indices += b.indices.size + idxs = slice(sum_dim, sum_dim + b._shape_as_2d[axis]) + indptr[idxs] = b.indptr[:-1] + indptr[idxs] += last_indptr + sum_dim += b._shape_as_2d[axis] + last_indptr += b.indptr[-1] + indptr[-1] = last_indptr + # TODO remove this if-structure when sparse matrices removed + if return_spmatrix: + if axis == 0: + return csr_matrix((data, indices, indptr), + shape=(sum_dim, constant_dim)) + else: + return csc_matrix((data, indices, indptr), + shape=(constant_dim, sum_dim)) + + if axis == 0: + return csr_array((data, indices, indptr), + shape=(sum_dim, constant_dim)) + else: + return csc_array((data, indices, indptr), + shape=(constant_dim, sum_dim)) + + +def _stack_along_minor_axis(blocks, axis): + """ + Stacking fast path for CSR/CSC matrices along the minor axis + (i) hstack for CSR, (ii) vstack for CSC. + """ + n_blocks = len(blocks) + if n_blocks == 0: + raise ValueError('Missing block matrices') + + if n_blocks == 1: + return blocks[0] + + # check for incompatible dimensions + other_axis = 1 if axis == 0 else 0 + other_axis_dims = {b._shape_as_2d[other_axis] for b in blocks} + if len(other_axis_dims) > 1: + raise ValueError(f'Mismatching dimensions along axis {other_axis}: ' + f'{other_axis_dims}') + constant_dim, = other_axis_dims + + # Do the stacking + indptr_list = [b.indptr for b in blocks] + data_cat = np.concatenate([b.data for b in blocks]) + + # Need to check if any indices/indptr, would be too large post- + # concatenation for np.int32: + # - The max value of indices is the output array's stacking-axis length - 1 + # - The max value in indptr is the number of non-zero entries. This is + # exceedingly unlikely to require int64, but is checked out of an + # abundance of caution. + sum_dim = sum(b._shape_as_2d[axis] for b in blocks) + nnz = sum(len(b.indices) for b in blocks) + idx_dtype = get_index_dtype(indptr_list, maxval=max(sum_dim - 1, nnz)) + stack_dim_cat = np.array([b._shape_as_2d[axis] for b in blocks], dtype=idx_dtype) + if data_cat.size > 0: + indptr_cat = np.concatenate(indptr_list, dtype=idx_dtype) + indices_cat = np.concatenate([b.indices for b in blocks], dtype=idx_dtype) + indptr = np.empty(constant_dim + 1, dtype=idx_dtype) + indices = np.empty_like(indices_cat) + data = np.empty_like(data_cat) + csr_hstack(n_blocks, constant_dim, stack_dim_cat, + indptr_cat, indices_cat, data_cat, + indptr, indices, data) + else: + indptr = np.zeros(constant_dim + 1, dtype=idx_dtype) + indices = np.empty(0, dtype=idx_dtype) + data = np.empty(0, dtype=data_cat.dtype) + + if axis == 0: + return blocks[0]._csc_container((data, indices, indptr), + shape=(sum_dim, constant_dim)) + else: + return blocks[0]._csr_container((data, indices, indptr), + shape=(constant_dim, sum_dim)) + + +def hstack(blocks, format=None, dtype=None): + """ + Stack sparse matrices horizontally (column wise) + + Parameters + ---------- + blocks + sequence of sparse matrices with compatible shapes + format : str + sparse format of the result (e.g., "csr") + by default an appropriate sparse matrix format is returned. + This choice is subject to change. + dtype : dtype, optional + The data-type of the output matrix. If not given, the dtype is + determined from that of `blocks`. + + Returns + ------- + new_array : sparse matrix or array + If any block in blocks is a sparse array, return a sparse array. + Otherwise return a sparse matrix. + + If you want a sparse array built from blocks that are not sparse + arrays, use ``block(hstack(blocks))`` or convert one block + e.g. ``blocks[0] = csr_array(blocks[0])``. + + See Also + -------- + vstack : stack sparse matrices vertically (row wise) + + Examples + -------- + >>> from scipy.sparse import coo_matrix, hstack + >>> A = coo_matrix([[1, 2], [3, 4]]) + >>> B = coo_matrix([[5], [6]]) + >>> hstack([A,B]).toarray() + array([[1, 2, 5], + [3, 4, 6]]) + + """ + blocks = np.asarray(blocks, dtype='object') + if any(isinstance(b, sparray) for b in blocks.flat): + return _block([blocks], format, dtype) + else: + return _block([blocks], format, dtype, return_spmatrix=True) + + +def vstack(blocks, format=None, dtype=None): + """ + Stack sparse arrays vertically (row wise) + + Parameters + ---------- + blocks + sequence of sparse arrays with compatible shapes + format : str, optional + sparse format of the result (e.g., "csr") + by default an appropriate sparse array format is returned. + This choice is subject to change. + dtype : dtype, optional + The data-type of the output array. If not given, the dtype is + determined from that of `blocks`. + + Returns + ------- + new_array : sparse matrix or array + If any block in blocks is a sparse array, return a sparse array. + Otherwise return a sparse matrix. + + If you want a sparse array built from blocks that are not sparse + arrays, use ``block(vstack(blocks))`` or convert one block + e.g. `blocks[0] = csr_array(blocks[0])`. + + See Also + -------- + hstack : stack sparse matrices horizontally (column wise) + + Examples + -------- + >>> from scipy.sparse import coo_array, vstack + >>> A = coo_array([[1, 2], [3, 4]]) + >>> B = coo_array([[5, 6]]) + >>> vstack([A, B]).toarray() + array([[1, 2], + [3, 4], + [5, 6]]) + + """ + blocks = np.asarray(blocks, dtype='object') + if any(isinstance(b, sparray) for b in blocks.flat): + return _block([[b] for b in blocks], format, dtype) + else: + return _block([[b] for b in blocks], format, dtype, return_spmatrix=True) + + +def bmat(blocks, format=None, dtype=None): + """ + Build a sparse array or matrix from sparse sub-blocks + + Note: `block_array` is preferred over `bmat`. They are the same function + except that `bmat` can return a deprecated sparse matrix. + `bmat` returns a coo_matrix if none of the inputs are a sparse array. + + .. warning:: + + This function returns a sparse matrix -- not a sparse array. + You are encouraged to use ``block_array`` to take advantage + of the sparse array functionality. + + Parameters + ---------- + blocks : array_like + Grid of sparse matrices with compatible shapes. + An entry of None implies an all-zero matrix. + format : {'bsr', 'coo', 'csc', 'csr', 'dia', 'dok', 'lil'}, optional + The sparse format of the result (e.g. "csr"). By default an + appropriate sparse matrix format is returned. + This choice is subject to change. + dtype : dtype, optional + The data-type of the output matrix. If not given, the dtype is + determined from that of `blocks`. + + Returns + ------- + bmat : sparse matrix or array + If any block in blocks is a sparse array, return a sparse array. + Otherwise return a sparse matrix. + + If you want a sparse array built from blocks that are not sparse + arrays, use ``block_array()``. + + See Also + -------- + block_array + + Examples + -------- + >>> from scipy.sparse import coo_array, bmat + >>> A = coo_array([[1, 2], [3, 4]]) + >>> B = coo_array([[5], [6]]) + >>> C = coo_array([[7]]) + >>> bmat([[A, B], [None, C]]).toarray() + array([[1, 2, 5], + [3, 4, 6], + [0, 0, 7]]) + + >>> bmat([[A, None], [None, C]]).toarray() + array([[1, 2, 0], + [3, 4, 0], + [0, 0, 7]]) + + """ + blocks = np.asarray(blocks, dtype='object') + if any(isinstance(b, sparray) for b in blocks.flat): + return _block(blocks, format, dtype) + else: + return _block(blocks, format, dtype, return_spmatrix=True) + + +def block_array(blocks, *, format=None, dtype=None): + """ + Build a sparse array from sparse sub-blocks + + Parameters + ---------- + blocks : array_like + Grid of sparse arrays with compatible shapes. + An entry of None implies an all-zero array. + format : {'bsr', 'coo', 'csc', 'csr', 'dia', 'dok', 'lil'}, optional + The sparse format of the result (e.g. "csr"). By default an + appropriate sparse array format is returned. + This choice is subject to change. + dtype : dtype, optional + The data-type of the output array. If not given, the dtype is + determined from that of `blocks`. + + Returns + ------- + block : sparse array + + See Also + -------- + block_diag : specify blocks along the main diagonals + diags : specify (possibly offset) diagonals + + Examples + -------- + >>> from scipy.sparse import coo_array, block_array + >>> A = coo_array([[1, 2], [3, 4]]) + >>> B = coo_array([[5], [6]]) + >>> C = coo_array([[7]]) + >>> block_array([[A, B], [None, C]]).toarray() + array([[1, 2, 5], + [3, 4, 6], + [0, 0, 7]]) + + >>> block_array([[A, None], [None, C]]).toarray() + array([[1, 2, 0], + [3, 4, 0], + [0, 0, 7]]) + + """ + return _block(blocks, format, dtype) + + +def _block(blocks, format, dtype, return_spmatrix=False): + blocks = np.asarray(blocks, dtype='object') + + if blocks.ndim != 2: + raise ValueError('blocks must be 2-D') + + M,N = blocks.shape + + # check for fast path cases + if (format in (None, 'csr') and + all(issparse(b) and b.format == 'csr' for b in blocks.flat) + ): + if N > 1: + # stack along columns (axis 1): must have shape (M, 1) + blocks = [[_stack_along_minor_axis(blocks[b, :], 1)] for b in range(M)] + blocks = np.asarray(blocks, dtype='object') + + # stack along rows (axis 0): + A = _compressed_sparse_stack(blocks[:, 0], 0, return_spmatrix) + if dtype is not None: + A = A.astype(dtype, copy=False) + return A + elif (format in (None, 'csc') and + all(issparse(b) and b.format == 'csc' for b in blocks.flat) + ): + if M > 1: + # stack along rows (axis 0): must have shape (1, N) + blocks = [[_stack_along_minor_axis(blocks[:, b], 0) for b in range(N)]] + blocks = np.asarray(blocks, dtype='object') + + # stack along columns (axis 1): + A = _compressed_sparse_stack(blocks[0, :], 1, return_spmatrix) + if dtype is not None: + A = A.astype(dtype, copy=False) + return A + + block_mask = np.zeros(blocks.shape, dtype=bool) + brow_lengths = np.zeros(M, dtype=np.int64) + bcol_lengths = np.zeros(N, dtype=np.int64) + + # convert everything to COO format + for i in range(M): + for j in range(N): + if blocks[i,j] is not None: + A = coo_array(blocks[i,j]) + blocks[i,j] = A + block_mask[i,j] = True + + if brow_lengths[i] == 0: + brow_lengths[i] = A._shape_as_2d[0] + elif brow_lengths[i] != A._shape_as_2d[0]: + msg = (f'blocks[{i},:] has incompatible row dimensions. ' + f'Got blocks[{i},{j}].shape[0] == {A._shape_as_2d[0]}, ' + f'expected {brow_lengths[i]}.') + raise ValueError(msg) + + if bcol_lengths[j] == 0: + bcol_lengths[j] = A._shape_as_2d[1] + elif bcol_lengths[j] != A._shape_as_2d[1]: + msg = (f'blocks[:,{j}] has incompatible column ' + f'dimensions. ' + f'Got blocks[{i},{j}].shape[1] == {A._shape_as_2d[1]}, ' + f'expected {bcol_lengths[j]}.') + raise ValueError(msg) + + nnz = sum(block.nnz for block in blocks[block_mask]) + if dtype is None: + all_dtypes = [blk.dtype for blk in blocks[block_mask]] + dtype = upcast(*all_dtypes) if all_dtypes else None + + row_offsets = np.append(0, np.cumsum(brow_lengths)) + col_offsets = np.append(0, np.cumsum(bcol_lengths)) + + shape = (row_offsets[-1], col_offsets[-1]) + + data = np.empty(nnz, dtype=dtype) + idx_dtype = get_index_dtype([b.coords[0] for b in blocks[block_mask]], + maxval=max(shape)) + row = np.empty(nnz, dtype=idx_dtype) + col = np.empty(nnz, dtype=idx_dtype) + + nnz = 0 + ii, jj = np.nonzero(block_mask) + for i, j in zip(ii, jj): + B = blocks[i, j] + idx = slice(nnz, nnz + B.nnz) + data[idx] = B.data + np.add(B.row, row_offsets[i], out=row[idx], dtype=idx_dtype) + np.add(B.col, col_offsets[j], out=col[idx], dtype=idx_dtype) + nnz += B.nnz + + if return_spmatrix: + return coo_matrix((data, (row, col)), shape=shape).asformat(format) + return coo_array((data, (row, col)), shape=shape).asformat(format) + + +def block_diag(mats, format=None, dtype=None): + """ + Build a block diagonal sparse matrix or array from provided matrices. + + Parameters + ---------- + mats : sequence of matrices or arrays + Input matrices or arrays. + format : str, optional + The sparse format of the result (e.g., "csr"). If not given, the result + is returned in "coo" format. + dtype : dtype specifier, optional + The data-type of the output. If not given, the dtype is + determined from that of `blocks`. + + Returns + ------- + res : sparse matrix or array + If at least one input is a sparse array, the output is a sparse array. + Otherwise the output is a sparse matrix. + + Notes + ----- + + .. versionadded:: 0.11.0 + + See Also + -------- + block_array + diags_array + + Examples + -------- + >>> from scipy.sparse import coo_array, block_diag + >>> A = coo_array([[1, 2], [3, 4]]) + >>> B = coo_array([[5], [6]]) + >>> C = coo_array([[7]]) + >>> block_diag((A, B, C)).toarray() + array([[1, 2, 0, 0], + [3, 4, 0, 0], + [0, 0, 5, 0], + [0, 0, 6, 0], + [0, 0, 0, 7]]) + + """ + if any(isinstance(a, sparray) for a in mats): + container = coo_array + else: + container = coo_matrix + + row = [] + col = [] + data = [] + idx_arrays = [] # track idx_dtype of incoming sparse arrays + r_idx = 0 + c_idx = 0 + for a in mats: + if isinstance(a, (list | numbers.Number)): + a = coo_array(np.atleast_2d(a)) + if issparse(a): + a = a.tocoo() + if not idx_arrays and a.coords[0].dtype == np.int64: + idx_arrays.append(a.coords[0]) + nrows, ncols = a._shape_as_2d + row.append(a.row + r_idx) + col.append(a.col + c_idx) + data.append(a.data) + else: + nrows, ncols = a.shape + a_row, a_col = np.divmod(np.arange(nrows*ncols), ncols) + row.append(a_row + r_idx) + col.append(a_col + c_idx) + data.append(a.ravel()) + r_idx += nrows + c_idx += ncols + idx_dtype = get_index_dtype(idx_arrays, maxval=max(r_idx, c_idx)) + row = np.concatenate(row, dtype=idx_dtype) + col = np.concatenate(col, dtype=idx_dtype) + data = np.concatenate(data) + new_shape = (r_idx, c_idx) + + return container((data, (row, col)), shape=new_shape, dtype=dtype).asformat(format) + + +@_transition_to_rng("random_state") +def random_array(shape, *, density=0.01, format='coo', dtype=None, + rng=None, data_sampler=None): + """Return a sparse array of uniformly random numbers in [0, 1) + + Returns a sparse array with the given shape and density + where values are generated uniformly randomly in the range [0, 1). + + Parameters + ---------- + shape : int or tuple of ints + shape of the array + density : real, optional (default: 0.01) + density of the generated matrix: density equal to one means a full + matrix, density of 0 means a matrix with no non-zero items. + format : str, optional (default: 'coo') + sparse matrix format. + dtype : dtype, optional (default: np.float64) + type of the returned matrix values. + rng : `numpy.random.Generator`, optional + Pseudorandom number generator state. When `rng` is None, a new + `numpy.random.Generator` is created using entropy from the + operating system. Types other than `numpy.random.Generator` are + passed to `numpy.random.default_rng` to instantiate a ``Generator``. + + This random state will be used for sampling `indices` (the sparsity + structure), and by default for the data values too (see `data_sampler`). + data_sampler : callable, optional (default depends on dtype) + Sampler of random data values with keyword arg `size`. + This function should take a single keyword argument `size` specifying + the length of its returned ndarray. It is used to generate the nonzero + values in the matrix after the locations of those values are chosen. + By default, uniform [0, 1) random values are used unless `dtype` is + an integer (default uniform integers from that dtype) or + complex (default uniform over the unit square in the complex plane). + For these, the `rng` is used e.g. ``rng.uniform(size=size)``. + + Returns + ------- + res : sparse array + + Examples + -------- + + Passing a ``np.random.Generator`` instance for better performance: + + >>> import numpy as np + >>> import scipy as sp + >>> rng = np.random.default_rng() + + Default sampling uniformly from [0, 1): + + >>> S = sp.sparse.random_array((3, 4), density=0.25, rng=rng) + + Providing a sampler for the values: + + >>> rvs = sp.stats.poisson(25, loc=10).rvs + >>> S = sp.sparse.random_array((3, 4), density=0.25, + ... rng=rng, data_sampler=rvs) + >>> S.toarray() + array([[ 36., 0., 33., 0.], # random + [ 0., 0., 0., 0.], + [ 0., 0., 36., 0.]]) + + Building a custom distribution. + This example builds a squared normal from np.random: + + >>> def np_normal_squared(size=None, rng=rng): + ... return rng.standard_normal(size) ** 2 + >>> S = sp.sparse.random_array((3, 4), density=0.25, rng=rng, + ... data_sampler=np_normal_squared) + + Or we can build it from sp.stats style rvs functions: + + >>> def sp_stats_normal_squared(size=None, rng=rng): + ... std_normal = sp.stats.distributions.norm_gen().rvs + ... return std_normal(size=size, random_state=rng) ** 2 + >>> S = sp.sparse.random_array((3, 4), density=0.25, rng=rng, + ... data_sampler=sp_stats_normal_squared) + + Or we can subclass sp.stats rv_continuous or rv_discrete: + + >>> class NormalSquared(sp.stats.rv_continuous): + ... def _rvs(self, size=None, random_state=rng): + ... return rng.standard_normal(size) ** 2 + >>> X = NormalSquared() + >>> Y = X().rvs + >>> S = sp.sparse.random_array((3, 4), density=0.25, + ... rng=rng, data_sampler=Y) + """ + data, ind = _random(shape, density, format, dtype, rng, data_sampler) + + # downcast, if safe, before calling coo_constructor + idx_dtype = get_index_dtype(maxval=max(shape)) + ind = tuple(np.asarray(co, dtype=idx_dtype) for co in ind) + return coo_array((data, ind), shape=shape).asformat(format) + + +def _random(shape, density=0.01, format=None, dtype=None, + rng=None, data_sampler=None): + if density < 0 or density > 1: + raise ValueError("density expected to be 0 <= density <= 1") + + tot_prod = math.prod(shape) # use `math` for when prod is >= 2**64 + + # Number of non zero values + size = int(round(density * tot_prod)) + + rng = check_random_state(rng) + + if data_sampler is None: + if np.issubdtype(dtype, np.integer): + def data_sampler(size): + return rng_integers(rng, + np.iinfo(dtype).min, + np.iinfo(dtype).max, + size, + dtype=dtype) + elif np.issubdtype(dtype, np.complexfloating): + def data_sampler(size): + return (rng.uniform(size=size) + + rng.uniform(size=size) * 1j) + else: + data_sampler = rng.uniform + + idx_dtype = get_index_dtype(maxval=max(shape)) + # rng.choice uses int64 if first arg is an int + if tot_prod <= np.iinfo(np.int64).max: + raveled_ind = rng.choice(tot_prod, size=size, replace=False) + ind = np.unravel_index(raveled_ind, shape=shape, order='F') + ind = tuple(np.asarray(co, idx_dtype) for co in ind) + else: + # for ravel indices bigger than dtype max, use sets to remove duplicates + ndim = len(shape) + seen = set() + while len(seen) < size: + dsize = size - len(seen) + seen.update(map(tuple, rng_integers(rng, shape, size=(dsize, ndim)))) + ind = tuple(np.array(list(seen), dtype=idx_dtype).T) + + # size kwarg allows eg data_sampler=partial(np.random.poisson, lam=5) + vals = data_sampler(size=size).astype(dtype, copy=False) + return vals, ind + + +@_transition_to_rng("random_state", position_num=5) +def random(m, n, density=0.01, format='coo', dtype=None, + rng=None, data_rvs=None): + """Generate a sparse matrix of the given shape and density with randomly + distributed values. + + .. warning:: + + This function returns a sparse matrix -- not a sparse array. + You are encouraged to use ``random_array`` to take advantage of the + sparse array functionality. + + Parameters + ---------- + m, n : int + shape of the matrix + density : real, optional + density of the generated matrix: density equal to one means a full + matrix, density of 0 means a matrix with no non-zero items. + format : str, optional + sparse matrix format. + dtype : dtype, optional + type of the returned matrix values. + rng : `numpy.random.Generator`, optional + Pseudorandom number generator state. When `rng` is None, a new + `numpy.random.Generator` is created using entropy from the + operating system. Types other than `numpy.random.Generator` are + passed to `numpy.random.default_rng` to instantiate a ``Generator``. + + This random state will be used for sampling the sparsity structure, but + not necessarily for sampling the values of the structurally nonzero + entries of the matrix. + data_rvs : callable, optional + Samples a requested number of random values. + This function should take a single argument specifying the length + of the ndarray that it will return. The structurally nonzero entries + of the sparse random matrix will be taken from the array sampled + by this function. By default, uniform [0, 1) random values will be + sampled using the same random state as is used for sampling + the sparsity structure. + + Returns + ------- + res : sparse matrix + + See Also + -------- + random_array : constructs sparse arrays instead of sparse matrices + + Examples + -------- + + Passing a ``np.random.Generator`` instance for better performance: + + >>> import scipy as sp + >>> import numpy as np + >>> rng = np.random.default_rng() + >>> S = sp.sparse.random(3, 4, density=0.25, rng=rng) + + Providing a sampler for the values: + + >>> rvs = sp.stats.poisson(25, loc=10).rvs + >>> S = sp.sparse.random(3, 4, density=0.25, rng=rng, data_rvs=rvs) + >>> S.toarray() + array([[ 36., 0., 33., 0.], # random + [ 0., 0., 0., 0.], + [ 0., 0., 36., 0.]]) + + Building a custom distribution. + This example builds a squared normal from np.random: + + >>> def np_normal_squared(size=None, rng=rng): + ... return rng.standard_normal(size) ** 2 + >>> S = sp.sparse.random(3, 4, density=0.25, rng=rng, + ... data_rvs=np_normal_squared) + + Or we can build it from sp.stats style rvs functions: + + >>> def sp_stats_normal_squared(size=None, rng=rng): + ... std_normal = sp.stats.distributions.norm_gen().rvs + ... return std_normal(size=size, random_state=rng) ** 2 + >>> S = sp.sparse.random(3, 4, density=0.25, rng=rng, + ... data_rvs=sp_stats_normal_squared) + + Or we can subclass sp.stats rv_continuous or rv_discrete: + + >>> class NormalSquared(sp.stats.rv_continuous): + ... def _rvs(self, size=None, random_state=rng): + ... return rng.standard_normal(size) ** 2 + >>> X = NormalSquared() + >>> Y = X() # get a frozen version of the distribution + >>> S = sp.sparse.random(3, 4, density=0.25, rng=rng, data_rvs=Y.rvs) + """ + if n is None: + n = m + m, n = int(m), int(n) + # make keyword syntax work for data_rvs e.g. data_rvs(size=7) + if data_rvs is not None: + def data_rvs_kw(size): + return data_rvs(size) + else: + data_rvs_kw = None + vals, ind = _random((m, n), density, format, dtype, rng, data_rvs_kw) + return coo_matrix((vals, ind), shape=(m, n)).asformat(format) + + +@_transition_to_rng("random_state", position_num=5) +def rand(m, n, density=0.01, format="coo", dtype=None, rng=None): + """Generate a sparse matrix of the given shape and density with uniformly + distributed values. + + .. warning:: + + This function returns a sparse matrix -- not a sparse array. + You are encouraged to use ``random_array`` to take advantage + of the sparse array functionality. + + Parameters + ---------- + m, n : int + shape of the matrix + density : real, optional + density of the generated matrix: density equal to one means a full + matrix, density of 0 means a matrix with no non-zero items. + format : str, optional + sparse matrix format. + dtype : dtype, optional + type of the returned matrix values. + rng : `numpy.random.Generator`, optional + Pseudorandom number generator state. When `rng` is None, a new + `numpy.random.Generator` is created using entropy from the + operating system. Types other than `numpy.random.Generator` are + passed to `numpy.random.default_rng` to instantiate a ``Generator``. + + Returns + ------- + res : sparse matrix + + Notes + ----- + Only float types are supported for now. + + See Also + -------- + random : Similar function allowing a custom random data sampler + random_array : Similar to random() but returns a sparse array + + Examples + -------- + >>> from scipy.sparse import rand + >>> matrix = rand(3, 4, density=0.25, format="csr", rng=42) + >>> matrix + + >>> matrix.toarray() + array([[0.05641158, 0. , 0. , 0.65088847], # random + [0. , 0. , 0. , 0.14286682], + [0. , 0. , 0. , 0. ]]) + + """ + return random(m, n, density, format, dtype, rng) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_coo.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_coo.py new file mode 100644 index 0000000000000000000000000000000000000000..3b1d577f90e5cf4d585aede3f30c6caf5b8ae059 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_coo.py @@ -0,0 +1,1647 @@ +""" A sparse matrix in COOrdinate or 'triplet' format""" + +__docformat__ = "restructuredtext en" + +__all__ = ['coo_array', 'coo_matrix', 'isspmatrix_coo'] + +import math +from warnings import warn + +import numpy as np + +from .._lib._util import copy_if_needed +from ._matrix import spmatrix +from ._sparsetools import (coo_tocsr, coo_todense, coo_todense_nd, + coo_matvec, coo_matvec_nd, coo_matmat_dense, + coo_matmat_dense_nd) +from ._base import issparse, SparseEfficiencyWarning, _spbase, sparray +from ._data import _data_matrix, _minmax_mixin +from ._sputils import (upcast_char, to_native, isshape, getdtype, + getdata, downcast_intp_index, get_index_dtype, + check_shape, check_reshape_kwargs, isscalarlike, isdense) + +import operator + + +class _coo_base(_data_matrix, _minmax_mixin): + _format = 'coo' + _allow_nd = range(1, 65) + + def __init__(self, arg1, shape=None, dtype=None, copy=False, *, maxprint=None): + _data_matrix.__init__(self, arg1, maxprint=maxprint) + if not copy: + copy = copy_if_needed + + if isinstance(arg1, tuple): + if isshape(arg1, allow_nd=self._allow_nd): + self._shape = check_shape(arg1, allow_nd=self._allow_nd) + idx_dtype = self._get_index_dtype(maxval=max(self._shape)) + data_dtype = getdtype(dtype, default=float) + self.coords = tuple(np.array([], dtype=idx_dtype) + for _ in range(len(self._shape))) + self.data = np.array([], dtype=data_dtype) + self.has_canonical_format = True + else: + try: + obj, coords = arg1 + except (TypeError, ValueError) as e: + raise TypeError('invalid input format') from e + + if shape is None: + if any(len(idx) == 0 for idx in coords): + raise ValueError('cannot infer dimensions from zero ' + 'sized index arrays') + shape = tuple(operator.index(np.max(idx)) + 1 + for idx in coords) + self._shape = check_shape(shape, allow_nd=self._allow_nd) + idx_dtype = self._get_index_dtype(coords, + maxval=max(self.shape), + check_contents=True) + self.coords = tuple(np.array(idx, copy=copy, dtype=idx_dtype) + for idx in coords) + self.data = getdata(obj, copy=copy, dtype=dtype) + self.has_canonical_format = False + else: + if issparse(arg1): + if arg1.format == self.format and copy: + self.coords = tuple(idx.copy() for idx in arg1.coords) + self.data = arg1.data.astype(getdtype(dtype, arg1)) # copy=True + self._shape = check_shape(arg1.shape, allow_nd=self._allow_nd) + self.has_canonical_format = arg1.has_canonical_format + else: + coo = arg1.tocoo() + self.coords = tuple(coo.coords) + self.data = coo.data.astype(getdtype(dtype, coo), copy=False) + self._shape = check_shape(coo.shape, allow_nd=self._allow_nd) + self.has_canonical_format = False + else: + # dense argument + M = np.asarray(arg1) + if not isinstance(self, sparray): + M = np.atleast_2d(M) + if M.ndim != 2: + raise TypeError(f'expected 2D array or matrix, not {M.ndim}D') + + self._shape = check_shape(M.shape, allow_nd=self._allow_nd) + if shape is not None: + if check_shape(shape, allow_nd=self._allow_nd) != self._shape: + message = f'inconsistent shapes: {shape} != {self._shape}' + raise ValueError(message) + + index_dtype = self._get_index_dtype(maxval=max(self._shape)) + coords = M.nonzero() + self.coords = tuple(idx.astype(index_dtype, copy=False) + for idx in coords) + self.data = getdata(M[coords], copy=copy, dtype=dtype) + self.has_canonical_format = True + + if len(self._shape) > 2: + self.coords = tuple(idx.astype(np.int64, copy=False) for idx in self.coords) + + self._check() + + @property + def row(self): + if self.ndim > 1: + return self.coords[-2] + result = np.zeros_like(self.col) + result.setflags(write=False) + return result + + + @row.setter + def row(self, new_row): + if self.ndim < 2: + raise ValueError('cannot set row attribute of a 1-dimensional sparse array') + new_row = np.asarray(new_row, dtype=self.coords[-2].dtype) + self.coords = self.coords[:-2] + (new_row,) + self.coords[-1:] + + @property + def col(self): + return self.coords[-1] + + @col.setter + def col(self, new_col): + new_col = np.asarray(new_col, dtype=self.coords[-1].dtype) + self.coords = self.coords[:-1] + (new_col,) + + def reshape(self, *args, **kwargs): + shape = check_shape(args, self.shape, allow_nd=self._allow_nd) + order, copy = check_reshape_kwargs(kwargs) + + # Return early if reshape is not required + if shape == self.shape: + if copy: + return self.copy() + else: + return self + + # When reducing the number of dimensions, we need to be careful about + # index overflow. This is why we can't simply call + # `np.ravel_multi_index()` followed by `np.unravel_index()` here. + flat_coords = _ravel_coords(self.coords, self.shape, order=order) + if len(shape) == 2: + if order == 'C': + new_coords = divmod(flat_coords, shape[1]) + else: + new_coords = divmod(flat_coords, shape[0])[::-1] + else: + new_coords = np.unravel_index(flat_coords, shape, order=order) + + idx_dtype = self._get_index_dtype(self.coords, maxval=max(shape)) + new_coords = tuple(np.asarray(co, dtype=idx_dtype) for co in new_coords) + + # Handle copy here rather than passing on to the constructor so that no + # copy will be made of `new_coords` regardless. + if copy: + new_data = self.data.copy() + else: + new_data = self.data + + return self.__class__((new_data, new_coords), shape=shape, copy=False) + + reshape.__doc__ = _spbase.reshape.__doc__ + + def _getnnz(self, axis=None): + if axis is None or (axis == 0 and self.ndim == 1): + nnz = len(self.data) + if any(len(idx) != nnz for idx in self.coords): + raise ValueError('all index and data arrays must have the ' + 'same length') + + if self.data.ndim != 1 or any(idx.ndim != 1 for idx in self.coords): + raise ValueError('coordinates and data arrays must be 1-D') + + return int(nnz) + + if axis < 0: + axis += self.ndim + if axis >= self.ndim: + raise ValueError('axis out of bounds') + + return np.bincount(downcast_intp_index(self.coords[1 - axis]), + minlength=self.shape[1 - axis]) + + _getnnz.__doc__ = _spbase._getnnz.__doc__ + + def count_nonzero(self, axis=None): + self.sum_duplicates() + if axis is None: + return np.count_nonzero(self.data) + + if axis < 0: + axis += self.ndim + if axis < 0 or axis >= self.ndim: + raise ValueError('axis out of bounds') + mask = self.data != 0 + coord = self.coords[1 - axis][mask] + return np.bincount(downcast_intp_index(coord), minlength=self.shape[1 - axis]) + + count_nonzero.__doc__ = _spbase.count_nonzero.__doc__ + + def _check(self): + """ Checks data structure for consistency """ + if self.ndim != len(self.coords): + raise ValueError('mismatching number of index arrays for shape; ' + f'got {len(self.coords)}, expected {self.ndim}') + + # index arrays should have integer data types + for i, idx in enumerate(self.coords): + if idx.dtype.kind != 'i': + warn(f'index array {i} has non-integer dtype ({idx.dtype.name})', + stacklevel=3) + + idx_dtype = self._get_index_dtype(self.coords, maxval=max(self.shape)) + self.coords = tuple(np.asarray(idx, dtype=idx_dtype) + for idx in self.coords) + self.data = to_native(self.data) + + if self.nnz > 0: + for i, idx in enumerate(self.coords): + if idx.max() >= self.shape[i]: + raise ValueError(f'axis {i} index {idx.max()} exceeds ' + f'matrix dimension {self.shape[i]}') + if idx.min() < 0: + raise ValueError(f'negative axis {i} index: {idx.min()}') + + def transpose(self, axes=None, copy=False): + if axes is None: + axes = range(self.ndim)[::-1] + elif isinstance(self, sparray): + if not hasattr(axes, "__len__") or len(axes) != self.ndim: + raise ValueError("axes don't match matrix dimensions") + if len(set(axes)) != self.ndim: + raise ValueError("repeated axis in transpose") + elif axes != (1, 0): + raise ValueError("Sparse matrices do not support an 'axes' " + "parameter because swapping dimensions is the " + "only logical permutation.") + + permuted_shape = tuple(self._shape[i] for i in axes) + permuted_coords = tuple(self.coords[i] for i in axes) + return self.__class__((self.data, permuted_coords), + shape=permuted_shape, copy=copy) + + transpose.__doc__ = _spbase.transpose.__doc__ + + def resize(self, *shape) -> None: + shape = check_shape(shape, allow_nd=self._allow_nd) + if self.ndim > 2: + raise ValueError("only 1-D or 2-D input accepted") + if len(shape) > 2: + raise ValueError("shape argument must be 1-D or 2-D") + # Check for added dimensions. + if len(shape) > self.ndim: + flat_coords = _ravel_coords(self.coords, self.shape) + max_size = math.prod(shape) + self.coords = np.unravel_index(flat_coords[:max_size], shape) + self.data = self.data[:max_size] + self._shape = shape + return + + # Check for removed dimensions. + if len(shape) < self.ndim: + tmp_shape = ( + self._shape[:len(shape) - 1] # Original shape without last axis + + (-1,) # Last axis is used to flatten the array + + (1,) * (self.ndim - len(shape)) # Pad with ones + ) + tmp = self.reshape(tmp_shape) + self.coords = tmp.coords[:len(shape)] + self._shape = tmp.shape[:len(shape)] + + # Handle truncation of existing dimensions. + is_truncating = any(old > new for old, new in zip(self.shape, shape)) + if is_truncating: + mask = np.logical_and.reduce([ + idx < size for idx, size in zip(self.coords, shape) + ]) + if not mask.all(): + self.coords = tuple(idx[mask] for idx in self.coords) + self.data = self.data[mask] + + self._shape = shape + + resize.__doc__ = _spbase.resize.__doc__ + + def toarray(self, order=None, out=None): + B = self._process_toarray_args(order, out) + fortran = int(B.flags.f_contiguous) + if not fortran and not B.flags.c_contiguous: + raise ValueError("Output array must be C or F contiguous") + # This handles both 0D and 1D cases correctly regardless of the + # original shape. + if self.ndim == 1: + coo_todense_nd(np.array([1]), self.nnz, self.ndim, + self.coords[0], self.data, B.ravel('A'), fortran) + elif self.ndim == 2: + M, N = self.shape + coo_todense(M, N, self.nnz, self.row, self.col, self.data, + B.ravel('A'), fortran) + else: + if fortran: + strides = np.append(1, np.cumprod(self.shape[:-1])) + else: + strides = np.append(np.cumprod(self.shape[1:][::-1])[::-1], 1) + coords = np.concatenate(self.coords) + coo_todense_nd(strides, self.nnz, self.ndim, + coords, self.data, B.ravel('A'), fortran) + # Note: reshape() doesn't copy here, but does return a new array (view). + return B.reshape(self.shape) + + toarray.__doc__ = _spbase.toarray.__doc__ + + def tocsc(self, copy=False): + """Convert this array/matrix to Compressed Sparse Column format + + Duplicate entries will be summed together. + + Examples + -------- + >>> from numpy import array + >>> from scipy.sparse import coo_array + >>> row = array([0, 0, 1, 3, 1, 0, 0]) + >>> col = array([0, 2, 1, 3, 1, 0, 0]) + >>> data = array([1, 1, 1, 1, 1, 1, 1]) + >>> A = coo_array((data, (row, col)), shape=(4, 4)).tocsc() + >>> A.toarray() + array([[3, 0, 1, 0], + [0, 2, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 1]]) + + """ + if self.ndim != 2: + raise ValueError(f'Cannot convert. CSC format must be 2D. Got {self.ndim}D') + if self.nnz == 0: + return self._csc_container(self.shape, dtype=self.dtype) + else: + from ._csc import csc_array + indptr, indices, data, shape = self._coo_to_compressed(csc_array._swap) + + x = self._csc_container((data, indices, indptr), shape=shape) + if not self.has_canonical_format: + x.sum_duplicates() + return x + + def tocsr(self, copy=False): + """Convert this array/matrix to Compressed Sparse Row format + + Duplicate entries will be summed together. + + Examples + -------- + >>> from numpy import array + >>> from scipy.sparse import coo_array + >>> row = array([0, 0, 1, 3, 1, 0, 0]) + >>> col = array([0, 2, 1, 3, 1, 0, 0]) + >>> data = array([1, 1, 1, 1, 1, 1, 1]) + >>> A = coo_array((data, (row, col)), shape=(4, 4)).tocsr() + >>> A.toarray() + array([[3, 0, 1, 0], + [0, 2, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 1]]) + + """ + if self.ndim > 2: + raise ValueError(f'Cannot convert. CSR must be 1D or 2D. Got {self.ndim}D') + if self.nnz == 0: + return self._csr_container(self.shape, dtype=self.dtype) + else: + from ._csr import csr_array + arrays = self._coo_to_compressed(csr_array._swap, copy=copy) + indptr, indices, data, shape = arrays + + x = self._csr_container((data, indices, indptr), shape=self.shape) + if not self.has_canonical_format: + x.sum_duplicates() + return x + + def _coo_to_compressed(self, swap, copy=False): + """convert (shape, coords, data) to (indptr, indices, data, shape)""" + M, N = swap(self._shape_as_2d) + # convert idx_dtype intc to int32 for pythran. + # tested in scipy/optimize/tests/test__numdiff.py::test_group_columns + idx_dtype = self._get_index_dtype(self.coords, maxval=max(self.nnz, N)) + + if self.ndim == 1: + indices = self.coords[0].copy() if copy else self.coords[0] + nnz = len(indices) + indptr = np.array([0, nnz], dtype=idx_dtype) + data = self.data.copy() if copy else self.data + return indptr, indices, data, self.shape + + # ndim == 2 + major, minor = swap(self.coords) + nnz = len(major) + major = major.astype(idx_dtype, copy=False) + minor = minor.astype(idx_dtype, copy=False) + + indptr = np.empty(M + 1, dtype=idx_dtype) + indices = np.empty_like(minor, dtype=idx_dtype) + data = np.empty_like(self.data, dtype=self.dtype) + + coo_tocsr(M, N, nnz, major, minor, self.data, indptr, indices, data) + return indptr, indices, data, self.shape + + def tocoo(self, copy=False): + if copy: + return self.copy() + else: + return self + + tocoo.__doc__ = _spbase.tocoo.__doc__ + + def todia(self, copy=False): + if self.ndim != 2: + raise ValueError(f'Cannot convert. DIA format must be 2D. Got {self.ndim}D') + self.sum_duplicates() + ks = self.col - self.row # the diagonal for each nonzero + diags, diag_idx = np.unique(ks, return_inverse=True) + + if len(diags) > 100: + # probably undesired, should todia() have a maxdiags parameter? + warn(f"Constructing a DIA matrix with {len(diags)} diagonals " + "is inefficient", + SparseEfficiencyWarning, stacklevel=2) + + #initialize and fill in data array + if self.data.size == 0: + data = np.zeros((0, 0), dtype=self.dtype) + else: + data = np.zeros((len(diags), self.col.max()+1), dtype=self.dtype) + data[diag_idx, self.col] = self.data + + return self._dia_container((data, diags), shape=self.shape) + + todia.__doc__ = _spbase.todia.__doc__ + + def todok(self, copy=False): + if self.ndim > 2: + raise ValueError(f'Cannot convert. DOK must be 1D or 2D. Got {self.ndim}D') + self.sum_duplicates() + dok = self._dok_container(self.shape, dtype=self.dtype) + # ensure that 1d coordinates are not tuples + if self.ndim == 1: + coords = self.coords[0] + else: + coords = zip(*self.coords) + + dok._dict = dict(zip(coords, self.data)) + return dok + + todok.__doc__ = _spbase.todok.__doc__ + + def diagonal(self, k=0): + if self.ndim != 2: + raise ValueError("diagonal requires two dimensions") + rows, cols = self.shape + if k <= -rows or k >= cols: + return np.empty(0, dtype=self.data.dtype) + diag = np.zeros(min(rows + min(k, 0), cols - max(k, 0)), + dtype=self.dtype) + diag_mask = (self.row + k) == self.col + + if self.has_canonical_format: + row = self.row[diag_mask] + data = self.data[diag_mask] + else: + inds = tuple(idx[diag_mask] for idx in self.coords) + (row, _), data = self._sum_duplicates(inds, self.data[diag_mask]) + diag[row + min(k, 0)] = data + + return diag + + diagonal.__doc__ = _data_matrix.diagonal.__doc__ + + def _setdiag(self, values, k): + if self.ndim != 2: + raise ValueError("setting a diagonal requires two dimensions") + M, N = self.shape + if values.ndim and not len(values): + return + idx_dtype = self.row.dtype + + # Determine which triples to keep and where to put the new ones. + full_keep = self.col - self.row != k + if k < 0: + max_index = min(M+k, N) + if values.ndim: + max_index = min(max_index, len(values)) + keep = np.logical_or(full_keep, self.col >= max_index) + new_row = np.arange(-k, -k + max_index, dtype=idx_dtype) + new_col = np.arange(max_index, dtype=idx_dtype) + else: + max_index = min(M, N-k) + if values.ndim: + max_index = min(max_index, len(values)) + keep = np.logical_or(full_keep, self.row >= max_index) + new_row = np.arange(max_index, dtype=idx_dtype) + new_col = np.arange(k, k + max_index, dtype=idx_dtype) + + # Define the array of data consisting of the entries to be added. + if values.ndim: + new_data = values[:max_index] + else: + new_data = np.empty(max_index, dtype=self.dtype) + new_data[:] = values + + # Update the internal structure. + self.coords = (np.concatenate((self.row[keep], new_row)), + np.concatenate((self.col[keep], new_col))) + self.data = np.concatenate((self.data[keep], new_data)) + self.has_canonical_format = False + + # needed by _data_matrix + def _with_data(self, data, copy=True): + """Returns a matrix with the same sparsity structure as self, + but with different data. By default the index arrays are copied. + """ + if copy: + coords = tuple(idx.copy() for idx in self.coords) + else: + coords = self.coords + return self.__class__((data, coords), shape=self.shape, dtype=data.dtype) + + def sum_duplicates(self) -> None: + """Eliminate duplicate entries by adding them together + + This is an *in place* operation + """ + if self.has_canonical_format: + return + summed = self._sum_duplicates(self.coords, self.data) + self.coords, self.data = summed + self.has_canonical_format = True + + def _sum_duplicates(self, coords, data): + # Assumes coords not in canonical format. + if len(data) == 0: + return coords, data + # Sort coords w.r.t. rows, then cols. This corresponds to C-order, + # which we rely on for argmin/argmax to return the first index in the + # same way that numpy does (in the case of ties). + order = np.lexsort(coords[::-1]) + coords = tuple(idx[order] for idx in coords) + data = data[order] + unique_mask = np.logical_or.reduce([ + idx[1:] != idx[:-1] for idx in coords + ]) + unique_mask = np.append(True, unique_mask) + coords = tuple(idx[unique_mask] for idx in coords) + unique_inds, = np.nonzero(unique_mask) + data = np.add.reduceat(data, downcast_intp_index(unique_inds), dtype=self.dtype) + return coords, data + + def eliminate_zeros(self): + """Remove zero entries from the array/matrix + + This is an *in place* operation + """ + mask = self.data != 0 + self.data = self.data[mask] + self.coords = tuple(idx[mask] for idx in self.coords) + + ####################### + # Arithmetic handlers # + ####################### + + def _add_dense(self, other): + if other.shape != self.shape: + raise ValueError(f'Incompatible shapes ({self.shape} and {other.shape})') + dtype = upcast_char(self.dtype.char, other.dtype.char) + result = np.array(other, dtype=dtype, copy=True) + fortran = int(result.flags.f_contiguous) + if self.ndim == 1: + coo_todense_nd(np.array([1]), self.nnz, self.ndim, + self.coords[0], self.data, result.ravel('A'), fortran) + elif self.ndim == 2: + M, N = self._shape_as_2d + coo_todense(M, N, self.nnz, self.row, self.col, self.data, + result.ravel('A'), fortran) + else: + if fortran: + strides = np.append(1, np.cumprod(self.shape[:-1])) + else: + strides = np.append(np.cumprod(self.shape[1:][::-1])[::-1], 1) + coords = np.concatenate(self.coords) + coo_todense_nd(strides, self.nnz, self.ndim, + coords, self.data, result.ravel('A'), fortran) + return self._container(result, copy=False) + + + def _add_sparse(self, other): + if self.ndim < 3: + return self.tocsr()._add_sparse(other) + + if other.shape != self.shape: + raise ValueError(f'Incompatible shapes ({self.shape} and {other.shape})') + other = self.__class__(other) + new_data = np.concatenate((self.data, other.data)) + new_coords = tuple(np.concatenate((self.coords, other.coords), axis=1)) + A = self.__class__((new_data, new_coords), shape=self.shape) + return A + + + def _sub_sparse(self, other): + if self.ndim < 3: + return self.tocsr()._sub_sparse(other) + + if other.shape != self.shape: + raise ValueError(f'Incompatible shapes ({self.shape} and {other.shape})') + other = self.__class__(other) + new_data = np.concatenate((self.data, -other.data)) + new_coords = tuple(np.concatenate((self.coords, other.coords), axis=1)) + A = coo_array((new_data, new_coords), shape=self.shape) + return A + + + def _matmul_vector(self, other): + if self.ndim > 2: + result = np.zeros(math.prod(self.shape[:-1]), + dtype=upcast_char(self.dtype.char, other.dtype.char)) + shape = np.array(self.shape) + strides = np.append(np.cumprod(shape[:-1][::-1])[::-1][1:], 1) + coords = np.concatenate(self.coords) + coo_matvec_nd(self.nnz, len(self.shape), strides, coords, self.data, + other, result) + + result = result.reshape(self.shape[:-1]) + return result + + # self.ndim <= 2 + result_shape = self.shape[0] if self.ndim > 1 else 1 + result = np.zeros(result_shape, + dtype=upcast_char(self.dtype.char, other.dtype.char)) + if self.ndim == 2: + col = self.col + row = self.row + elif self.ndim == 1: + col = self.coords[0] + row = np.zeros_like(col) + else: + raise NotImplementedError( + f"coo_matvec not implemented for ndim={self.ndim}") + + coo_matvec(self.nnz, row, col, self.data, other, result) + # Array semantics return a scalar here, not a single-element array. + if isinstance(self, sparray) and result_shape == 1: + return result[0] + return result + + + def _rmatmul_dispatch(self, other): + if isscalarlike(other): + return self._mul_scalar(other) + else: + # Don't use asarray unless we have to + try: + o_ndim = other.ndim + except AttributeError: + other = np.asarray(other) + o_ndim = other.ndim + perm = tuple(range(o_ndim)[:-2]) + tuple(range(o_ndim)[-2:][::-1]) + tr = other.transpose(perm) + + s_ndim = self.ndim + perm = tuple(range(s_ndim)[:-2]) + tuple(range(s_ndim)[-2:][::-1]) + ret = self.transpose(perm)._matmul_dispatch(tr) + if ret is NotImplemented: + return NotImplemented + + if s_ndim == 1 or o_ndim == 1: + perm = range(ret.ndim) + else: + perm = tuple(range(ret.ndim)[:-2]) + tuple(range(ret.ndim)[-2:][::-1]) + return ret.transpose(perm) + + + def _matmul_dispatch(self, other): + if isscalarlike(other): + return self.multiply(other) + + if not (issparse(other) or isdense(other)): + # If it's a list or whatever, treat it like an array + other_a = np.asanyarray(other) + + if other_a.ndim == 0 and other_a.dtype == np.object_: + # Not interpretable as an array; return NotImplemented so that + # other's __rmatmul__ can kick in if that's implemented. + return NotImplemented + + try: + other.shape + except AttributeError: + other = other_a + + if self.ndim < 3 and other.ndim < 3: + return _spbase._matmul_dispatch(self, other) + + N = self.shape[-1] + err_prefix = "matmul: dimension mismatch with signature" + if other.__class__ is np.ndarray: + if other.shape == (N,): + return self._matmul_vector(other) + if other.shape == (N, 1): + result = self._matmul_vector(other.ravel()) + return result.reshape(*self.shape[:-1], 1) + if other.ndim == 1: + msg = f"{err_prefix} (n,k={N}),(k={other.shape[0]},)->(n,)" + raise ValueError(msg) + if other.shape[-2] == N: + # check for batch dimensions compatibility + batch_shape_A = self.shape[:-2] + batch_shape_B = other.shape[:-2] + if batch_shape_A != batch_shape_B: + try: + # This will raise an error if the shapes are not broadcastable + np.broadcast_shapes(batch_shape_A, batch_shape_B) + except ValueError: + raise ValueError("Batch dimensions are not broadcastable") + + return self._matmul_multivector(other) + else: + raise ValueError( + f"{err_prefix} (n,..,k={N}),(k={other.shape[-2]},..,m)->(n,..,m)" + ) + + + if isscalarlike(other): + # scalar value + return self._mul_scalar(other) + + if issparse(other): + self_is_1d = self.ndim == 1 + other_is_1d = other.ndim == 1 + + # reshape to 2-D if self or other is 1-D + if self_is_1d: + self = self.reshape(self._shape_as_2d) # prepend 1 to shape + + if other_is_1d: + other = other.reshape((other.shape[0], 1)) # append 1 to shape + + # Check if the inner dimensions match for matrix multiplication + if N != other.shape[-2]: + raise ValueError( + f"{err_prefix} (n,..,k={N}),(k={other.shape[-2]},..,m)->(n,..,m)" + ) + + # If A or B has more than 2 dimensions, check for + # batch dimensions compatibility + if self.ndim > 2 or other.ndim > 2: + batch_shape_A = self.shape[:-2] + batch_shape_B = other.shape[:-2] + if batch_shape_A != batch_shape_B: + try: + # This will raise an error if the shapes are not broadcastable + np.broadcast_shapes(batch_shape_A, batch_shape_B) + except ValueError: + raise ValueError("Batch dimensions are not broadcastable") + + result = self._matmul_sparse(other) + + # reshape back if a or b were originally 1-D + if self_is_1d: + # if self was originally 1-D, reshape result accordingly + result = result.reshape(tuple(result.shape[:-2]) + + tuple(result.shape[-1:])) + if other_is_1d: + result = result.reshape(result.shape[:-1]) + return result + + + def _matmul_multivector(self, other): + result_dtype = upcast_char(self.dtype.char, other.dtype.char) + if self.ndim >= 3 or other.ndim >= 3: + # if self has shape (N,), reshape to (1,N) + if self.ndim == 1: + result = self.reshape(1, self.shape[0])._matmul_multivector(other) + return result.reshape(tuple(other.shape[:-2]) + tuple(other.shape[-1:])) + + broadcast_shape = np.broadcast_shapes(self.shape[:-2], other.shape[:-2]) + self_shape = broadcast_shape + self.shape[-2:] + other_shape = broadcast_shape + other.shape[-2:] + + self = self._broadcast_to(self_shape) + other = np.broadcast_to(other, other_shape) + result_shape = broadcast_shape + self.shape[-2:-1] + other.shape[-1:] + result = np.zeros(result_shape, dtype=result_dtype) + coo_matmat_dense_nd(self.nnz, len(self.shape), other.shape[-1], + np.array(other_shape), np.array(result_shape), + np.concatenate(self.coords), + self.data, other.ravel('C'), result) + return result + + if self.ndim == 2: + result_shape = (self.shape[0], other.shape[1]) + col = self.col + row = self.row + elif self.ndim == 1: + result_shape = (other.shape[1],) + col = self.coords[0] + row = np.zeros_like(col) + result = np.zeros(result_shape, dtype=result_dtype) + coo_matmat_dense(self.nnz, other.shape[-1], row, col, + self.data, other.ravel('C'), result) + return result.view(type=type(other)) + + + def dot(self, other): + """Return the dot product of two arrays. + + Strictly speaking a dot product involves two vectors. + But in the sense that an array with ndim >= 1 is a collection + of vectors, the function computes the collection of dot products + between each vector in the first array with each vector in the + second array. The axis upon which the sum of products is performed + is the last axis of the first array and the second to last axis of + the second array. If the second array is 1-D, the last axis is used. + + Thus, if both arrays are 1-D, the inner product is returned. + If both are 2-D, we have matrix multiplication. If `other` is 1-D, + the sum product is taken along the last axis of each array. If + `other` is N-D for N>=2, the sum product is over the last axis of + the first array and the second-to-last axis of the second array. + + Parameters + ---------- + other : array_like (dense or sparse) + Second array + + Returns + ------- + output : array (sparse or dense) + The dot product of this array with `other`. + It will be dense/sparse if `other` is dense/sparse. + + Examples + -------- + + >>> import numpy as np + >>> from scipy.sparse import coo_array + >>> A = coo_array([[1, 2, 0], [0, 0, 3], [4, 0, 5]]) + >>> v = np.array([1, 0, -1]) + >>> A.dot(v) + array([ 1, -3, -1], dtype=int64) + + For 2-D arrays it is the matrix product: + + >>> A = coo_array([[1, 0], [0, 1]]) + >>> B = coo_array([[4, 1], [2, 2]]) + >>> A.dot(B).toarray() + array([[4, 1], + [2, 2]]) + + For 3-D arrays the shape extends unused axes by other unused axes. + + >>> A = coo_array(np.arange(3*4*5*6)).reshape((3,4,5,6)) + >>> B = coo_array(np.arange(3*4*5*6)).reshape((5,4,6,3)) + >>> A.dot(B).shape + (3, 4, 5, 5, 4, 3) + """ + if not (issparse(other) or isdense(other) or isscalarlike(other)): + # If it's a list or whatever, treat it like an array + o_array = np.asanyarray(other) + + if o_array.ndim == 0 and o_array.dtype == np.object_: + raise TypeError(f"dot argument not supported type: '{type(other)}'") + try: + other.shape + except AttributeError: + other = o_array + + if self.ndim < 3 and (np.isscalar(other) or other.ndim<3): + return _spbase.dot(self, other) + # Handle scalar multiplication + if np.isscalar(other): + return self * other + if isdense(other): + return self._dense_dot(other) + elif other.format != "coo": + raise TypeError("input must be a COO matrix/array") + elif self.ndim == 1 and other.ndim == 1: + # Handle inner product of vectors (1-D arrays) + if self.shape[0] != other.shape[0]: + raise ValueError(f"shapes {self.shape} and {other.shape}" + " are not aligned for inner product") + return self @ other + elif self.ndim == 2 and other.ndim == 2: + # Handle matrix multiplication (2-D arrays) + if self.shape[1] != other.shape[0]: + raise ValueError(f"shapes {self.shape} and {other.shape}" + " are not aligned for matmul") + return self @ other + else: + return self._sparse_dot(other) + + + def _sparse_dot(self, other): + self_is_1d = self.ndim == 1 + other_is_1d = other.ndim == 1 + + # reshape to 2-D if self or other is 1-D + if self_is_1d: + self = self.reshape(self._shape_as_2d) # prepend 1 to shape + if other_is_1d: + other = other.reshape((other.shape[0], 1)) # append 1 to shape + + if self.shape[-1] != other.shape[-2]: + raise ValueError(f"shapes {self.shape} and {other.shape}" + " are not aligned for n-D dot") + + # Prepare the tensors for dot operation + # Ravel non-reduced axes coordinates + self_raveled_coords = _ravel_non_reduced_axes(self.coords, + self.shape, [self.ndim-1]) + other_raveled_coords = _ravel_non_reduced_axes(other.coords, + other.shape, [other.ndim-2]) + + # Get the shape of the non-reduced axes + self_nonreduced_shape = self.shape[:-1] + other_nonreduced_shape = other.shape[:-2] + other.shape[-1:] + + # Create 2D coords arrays + ravel_coords_shape_self = (math.prod(self_nonreduced_shape), self.shape[-1]) + ravel_coords_shape_other = (other.shape[-2], math.prod(other_nonreduced_shape)) + + self_2d_coords = (self_raveled_coords, self.coords[-1]) + other_2d_coords = (other.coords[-2], other_raveled_coords) + + self_2d = coo_array((self.data, self_2d_coords), ravel_coords_shape_self) + other_2d = coo_array((other.data, other_2d_coords), ravel_coords_shape_other) + + prod = (self_2d @ other_2d).tocoo() # routes via 2-D CSR + + # Combine the shapes of the non-reduced axes + combined_shape = self_nonreduced_shape + other_nonreduced_shape + + # Unravel the 2D coordinates to get multi-dimensional coordinates + shapes = (self_nonreduced_shape, other_nonreduced_shape) + prod_coords = [] + for c, s in zip(prod.coords, shapes): + prod_coords.extend(np.unravel_index(c, s)) + + prod_arr = coo_array((prod.data, prod_coords), combined_shape) + + # reshape back if a or b were originally 1-D + # TODO: Move this logic before computation of prod_coords for efficiency + if self_is_1d: + prod_arr = prod_arr.reshape(combined_shape[1:]) + if other_is_1d: + prod_arr = prod_arr.reshape(combined_shape[:-1]) + + return prod_arr + + def _dense_dot(self, other): + self_is_1d = self.ndim == 1 + other_is_1d = other.ndim == 1 + + # reshape to 2-D if self or other is 1-D + if self_is_1d: + self = self.reshape(self._shape_as_2d) # prepend 1 to shape + if other_is_1d: + other = other.reshape((other.shape[0], 1)) # append 1 to shape + + if self.shape[-1] != other.shape[-2]: + raise ValueError(f"shapes {self.shape} and {other.shape}" + " are not aligned for n-D dot") + + new_shape_self = ( + self.shape[:-1] + (1,) * (len(other.shape) - 1) + self.shape[-1:] + ) + new_shape_other = (1,) * (len(self.shape) - 1) + other.shape + + result_shape = self.shape[:-1] + other.shape[:-2] + other.shape[-1:] + result = self.reshape(new_shape_self) @ other.reshape(new_shape_other) + prod_arr = result.reshape(result_shape) + + # reshape back if a or b were originally 1-D + if self_is_1d: + prod_arr = prod_arr.reshape(result_shape[1:]) + if other_is_1d: + prod_arr = prod_arr.reshape(result_shape[:-1]) + + return prod_arr + + def tensordot(self, other, axes=2): + """Return the tensordot product with another array along the given axes. + + The tensordot differs from dot and matmul in that any axis can be + chosen for each of the first and second array and the sum of the + products is computed just like for matrix multiplication, only not + just for the rows of the first times the columns of the second. It + takes the dot product of the collection of vectors along the specified + axes. Here we can even take the sum of the products along two or even + more axes if desired. So, tensordot is a dot product computation + applied to arrays of any dimension >= 1. It is like matmul but over + arbitrary axes for each matrix. + + Given two tensors, `a` and `b`, and the desired axes specified as a + 2-tuple/list/array containing two sequences of axis numbers, + ``(a_axes, b_axes)``, sum the products of `a`'s and `b`'s elements + (components) over the axes specified by ``a_axes`` and ``b_axes``. + The `axes` input can be a single non-negative integer, ``N``; + if it is, then the last ``N`` dimensions of `a` and the first + ``N`` dimensions of `b` are summed over. + + Parameters + ---------- + a, b : array_like + Tensors to "dot". + + axes : int or (2,) array_like + * integer_like + If an int N, sum over the last N axes of `a` and the first N axes + of `b` in order. The sizes of the corresponding axes must match. + * (2,) array_like + A 2-tuple of sequences of axes to be summed over, the first applying + to `a`, the second to `b`. The sequences must be the same length. + The shape of the corresponding axes must match between `a` and `b`. + + Returns + ------- + output : coo_array + The tensor dot product of this array with `other`. + It will be dense/sparse if `other` is dense/sparse. + + See Also + -------- + dot + + Examples + -------- + >>> import numpy as np + >>> import scipy.sparse + >>> A = scipy.sparse.coo_array([[[2, 3], [0, 0]], [[0, 1], [0, 5]]]) + >>> A.shape + (2, 2, 2) + + Integer axes N are shorthand for (range(-N, 0), range(0, N)): + + >>> A.tensordot(A, axes=1).toarray() + array([[[[ 4, 9], + [ 0, 15]], + + [[ 0, 0], + [ 0, 0]]], + + + [[[ 0, 1], + [ 0, 5]], + + [[ 0, 5], + [ 0, 25]]]]) + >>> A.tensordot(A, axes=2).toarray() + array([[ 4, 6], + [ 0, 25]]) + >>> A.tensordot(A, axes=3) + array(39) + + Using tuple for axes: + + >>> a = scipy.sparse.coo_array(np.arange(60).reshape(3,4,5)) + >>> b = np.arange(24).reshape(4,3,2) + >>> c = a.tensordot(b, axes=([1,0],[0,1])) + >>> c.shape + (5, 2) + >>> c + array([[4400, 4730], + [4532, 4874], + [4664, 5018], + [4796, 5162], + [4928, 5306]]) + + """ + if not isdense(other) and not issparse(other): + # If it's a list or whatever, treat it like an array + other_array = np.asanyarray(other) + + if other_array.ndim == 0 and other_array.dtype == np.object_: + raise TypeError(f"tensordot arg not supported type: '{type(other)}'") + try: + other.shape + except AttributeError: + other = other_array + + axes_self, axes_other = _process_axes(self.ndim, other.ndim, axes) + + # Check for shape compatibility along specified axes + if any(self.shape[ax] != other.shape[bx] + for ax, bx in zip(axes_self, axes_other)): + raise ValueError("sizes of the corresponding axes must match") + + if isdense(other): + return self._dense_tensordot(other, axes_self, axes_other) + else: + return self._sparse_tensordot(other, axes_self, axes_other) + + + def _sparse_tensordot(self, other, axes_self, axes_other): + ndim_self = len(self.shape) + ndim_other = len(other.shape) + + # Prepare the tensors for tensordot operation + # Ravel non-reduced axes coordinates + self_non_red_coords = _ravel_non_reduced_axes(self.coords, self.shape, + axes_self) + self_reduced_coords = np.ravel_multi_index( + [self.coords[ax] for ax in axes_self], [self.shape[ax] for ax in axes_self]) + other_non_red_coords = _ravel_non_reduced_axes(other.coords, other.shape, + axes_other) + other_reduced_coords = np.ravel_multi_index( + [other.coords[a] for a in axes_other], [other.shape[a] for a in axes_other] + ) + # Get the shape of the non-reduced axes + self_nonreduced_shape = tuple(self.shape[ax] for ax in range(ndim_self) + if ax not in axes_self) + other_nonreduced_shape = tuple(other.shape[ax] for ax in range(ndim_other) + if ax not in axes_other) + + # Create 2D coords arrays + ravel_coords_shape_self = (math.prod(self_nonreduced_shape), + math.prod([self.shape[ax] for ax in axes_self])) + ravel_coords_shape_other = (math.prod([other.shape[ax] for ax in axes_other]), + math.prod(other_nonreduced_shape)) + + self_2d_coords = (self_non_red_coords, self_reduced_coords) + other_2d_coords = (other_reduced_coords, other_non_red_coords) + + self_2d = coo_array((self.data, self_2d_coords), ravel_coords_shape_self) + other_2d = coo_array((other.data, other_2d_coords), ravel_coords_shape_other) + + # Perform matrix multiplication (routed via 2-D CSR) + prod = (self_2d @ other_2d).tocoo() + + # Combine the shapes of the non-contracted axes + combined_shape = self_nonreduced_shape + other_nonreduced_shape + + # Unravel the 2D coordinates to get multi-dimensional coordinates + coords = [] + for c, s in zip(prod.coords, (self_nonreduced_shape, other_nonreduced_shape)): + if s: + coords.extend(np.unravel_index(c, s)) + + if coords == []: # if result is scalar + return sum(prod.data) + + # Construct the resulting COO array with combined coordinates and shape + return coo_array((prod.data, coords), shape=combined_shape) + + + def _dense_tensordot(self, other, axes_self, axes_other): + ndim_self = len(self.shape) + ndim_other = len(other.shape) + + non_reduced_axes_self = [ax for ax in range(ndim_self) if ax not in axes_self] + reduced_shape_self = [self.shape[s] for s in axes_self] + non_reduced_shape_self = [self.shape[s] for s in non_reduced_axes_self] + + non_reduced_axes_other = [ax for ax in range(ndim_other) + if ax not in axes_other] + reduced_shape_other = [other.shape[s] for s in axes_other] + non_reduced_shape_other = [other.shape[s] for s in non_reduced_axes_other] + + permute_self = non_reduced_axes_self + axes_self + permute_other = ( + non_reduced_axes_other[:-1] + axes_other + non_reduced_axes_other[-1:] + ) + self = self.transpose(permute_self) + other = np.transpose(other, permute_other) + + reshape_self = (*non_reduced_shape_self, math.prod(reduced_shape_self)) + reshape_other = (*non_reduced_shape_other[:-1], math.prod(reduced_shape_other), + *non_reduced_shape_other[-1:]) + + return self.reshape(reshape_self).dot(other.reshape(reshape_other)) + + + def _matmul_sparse(self, other): + """ + Perform sparse-sparse matrix multiplication for two n-D COO arrays. + The method converts input n-D arrays to 2-D block array format, + uses csr_matmat to multiply them, and then converts the + result back to n-D COO array. + + Parameters: + self (COO): The first n-D sparse array in COO format. + other (COO): The second n-D sparse array in COO format. + + Returns: + prod (COO): The resulting n-D sparse array after multiplication. + """ + if self.ndim < 3 and other.ndim < 3: + return _spbase._matmul_sparse(self, other) + + # Get the shapes of self and other + self_shape = self.shape + other_shape = other.shape + + # Determine the new shape to broadcast self and other + broadcast_shape = np.broadcast_shapes(self_shape[:-2], other_shape[:-2]) + self_new_shape = tuple(broadcast_shape) + self_shape[-2:] + other_new_shape = tuple(broadcast_shape) + other_shape[-2:] + + self_broadcasted = self._broadcast_to(self_new_shape) + other_broadcasted = other._broadcast_to(other_new_shape) + + # Convert n-D COO arrays to 2-D block diagonal arrays + self_block_diag = _block_diag(self_broadcasted) + other_block_diag = _block_diag(other_broadcasted) + + # Use csr_matmat to perform sparse matrix multiplication + prod_block_diag = (self_block_diag @ other_block_diag).tocoo() + + # Convert the 2-D block diagonal array back to n-D + return _extract_block_diag( + prod_block_diag, + shape=(*broadcast_shape, self.shape[-2], other.shape[-1]), + ) + + + def _broadcast_to(self, new_shape, copy=False): + if self.shape == new_shape: + return self.copy() if copy else self + + old_shape = self.shape + + # Check if the new shape is compatible for broadcasting + if len(new_shape) < len(old_shape): + raise ValueError("New shape must have at least as many dimensions" + " as the current shape") + + # Add leading ones to shape to ensure same length as `new_shape` + shape = (1,) * (len(new_shape) - len(old_shape)) + tuple(old_shape) + + # Ensure the old shape can be broadcast to the new shape + if any((o != 1 and o != n) for o, n in zip(shape, new_shape)): + raise ValueError(f"current shape {old_shape} cannot be " + "broadcast to new shape {new_shape}") + + # Reshape the COO array to match the new dimensions + self = self.reshape(shape) + + idx_dtype = get_index_dtype(self.coords, maxval=max(new_shape)) + coords = self.coords + new_data = self.data + new_coords = coords[-1:] # Copy last coordinate to start + cum_repeat = 1 # Cumulative repeat factor for broadcasting + + if shape[-1] != new_shape[-1]: # broadcasting the n-th (col) dimension + repeat_count = new_shape[-1] + cum_repeat *= repeat_count + new_data = np.tile(new_data, repeat_count) + new_dim = np.repeat(np.arange(0, repeat_count, dtype=idx_dtype), self.nnz) + new_coords = (new_dim,) + + for i in range(-2, -(len(shape)+1), -1): + if shape[i] != new_shape[i]: + repeat_count = new_shape[i] # number of times to repeat data, coords + cum_repeat *= repeat_count # update cumulative repeat factor + nnz = len(new_data) # Number of non-zero elements so far + + # Tile data and coordinates to match the new repeat count + new_data = np.tile(new_data, repeat_count) + new_coords = tuple(np.tile(new_coords[i+1:], repeat_count)) + + # Create new dimensions and stack them + new_dim = np.repeat(np.arange(0, repeat_count, dtype=idx_dtype), nnz) + new_coords = (new_dim,) + new_coords + else: + # If no broadcasting needed, tile the coordinates + new_dim = np.tile(coords[i], cum_repeat) + new_coords = (new_dim,) + new_coords + + return coo_array((new_data, new_coords), new_shape) + + +def _block_diag(self): + """ + Converts an N-D COO array into a 2-D COO array in block diagonal form. + + Parameters: + self (coo_array): An N-Dimensional COO sparse array. + + Returns: + coo_array: A 2-Dimensional COO sparse array in block diagonal form. + """ + if self.ndim<2: + raise ValueError("array must have atleast dim=2") + num_blocks = math.prod(self.shape[:-2]) + n_col = self.shape[-1] + n_row = self.shape[-2] + res_arr = self.reshape((num_blocks, n_row, n_col)) + new_coords = ( + res_arr.coords[1] + res_arr.coords[0] * res_arr.shape[1], + res_arr.coords[2] + res_arr.coords[0] * res_arr.shape[2], + ) + + new_shape = (num_blocks * n_row, num_blocks * n_col) + return coo_array((self.data, tuple(new_coords)), shape=new_shape) + + +def _extract_block_diag(self, shape): + n_row, n_col = shape[-2], shape[-1] + + # Extract data and coordinates from the block diagonal COO array + data = self.data + row, col = self.row, self.col + + # Initialize new coordinates array + new_coords = np.empty((len(shape), self.nnz), dtype=int) + + # Calculate within-block indices + new_coords[-2] = row % n_row + new_coords[-1] = col % n_col + + # Calculate coordinates for higher dimensions + temp_block_idx = row // n_row + for i in range(len(shape) - 3, -1, -1): + size = shape[i] + new_coords[i] = temp_block_idx % size + temp_block_idx = temp_block_idx // size + + # Create the new COO array with the original n-D shape + return coo_array((data, tuple(new_coords)), shape=shape) + + +def _process_axes(ndim_a, ndim_b, axes): + if isinstance(axes, int): + if axes < 1 or axes > min(ndim_a, ndim_b): + raise ValueError("axes integer is out of bounds for input arrays") + axes_a = list(range(ndim_a - axes, ndim_a)) + axes_b = list(range(axes)) + elif isinstance(axes, (tuple, list)): + if len(axes) != 2: + raise ValueError("axes must be a tuple/list of length 2") + axes_a, axes_b = axes + if len(axes_a) != len(axes_b): + raise ValueError("axes lists/tuples must be of the same length") + if any(ax >= ndim_a or ax < -ndim_a for ax in axes_a) or \ + any(bx >= ndim_b or bx < -ndim_b for bx in axes_b): + raise ValueError("axes indices are out of bounds for input arrays") + else: + raise TypeError("axes must be an integer or a tuple/list of integers") + + axes_a = [axis + ndim_a if axis < 0 else axis for axis in axes_a] + axes_b = [axis + ndim_b if axis < 0 else axis for axis in axes_b] + return axes_a, axes_b + + +def _ravel_non_reduced_axes(coords, shape, axes): + ndim = len(shape) + non_reduced_axes = [ax for ax in range(ndim) if ax not in axes] + + if not non_reduced_axes: + # Return an array with one row + return np.zeros_like(coords[0]) + + # Extract the shape of the non-reduced axes + non_reduced_shape = [shape[ax] for ax in non_reduced_axes] + + # Extract the coordinates of the non-reduced axes + non_reduced_coords = tuple(coords[idx] for idx in non_reduced_axes) + + # Ravel the coordinates into 1D + return np.ravel_multi_index(non_reduced_coords, non_reduced_shape) + + +def _ravel_coords(coords, shape, order='C'): + """Like np.ravel_multi_index, but avoids some overflow issues.""" + if len(coords) == 1: + return coords[0] + # Handle overflow as in https://github.com/scipy/scipy/pull/9132 + if len(coords) == 2: + nrows, ncols = shape + row, col = coords + if order == 'C': + maxval = (ncols * max(0, nrows - 1) + max(0, ncols - 1)) + idx_dtype = get_index_dtype(maxval=maxval) + return np.multiply(ncols, row, dtype=idx_dtype) + col + elif order == 'F': + maxval = (nrows * max(0, ncols - 1) + max(0, nrows - 1)) + idx_dtype = get_index_dtype(maxval=maxval) + return np.multiply(nrows, col, dtype=idx_dtype) + row + else: + raise ValueError("'order' must be 'C' or 'F'") + return np.ravel_multi_index(coords, shape, order=order) + + +def isspmatrix_coo(x): + """Is `x` of coo_matrix type? + + Parameters + ---------- + x + object to check for being a coo matrix + + Returns + ------- + bool + True if `x` is a coo matrix, False otherwise + + Examples + -------- + >>> from scipy.sparse import coo_array, coo_matrix, csr_matrix, isspmatrix_coo + >>> isspmatrix_coo(coo_matrix([[5]])) + True + >>> isspmatrix_coo(coo_array([[5]])) + False + >>> isspmatrix_coo(csr_matrix([[5]])) + False + """ + return isinstance(x, coo_matrix) + + +# This namespace class separates array from matrix with isinstance +class coo_array(_coo_base, sparray): + """ + A sparse array in COOrdinate format. + + Also known as the 'ijv' or 'triplet' format. + + This can be instantiated in several ways: + coo_array(D) + where D is an ndarray + + coo_array(S) + with another sparse array or matrix S (equivalent to S.tocoo()) + + coo_array(shape, [dtype]) + to construct an empty sparse array with shape `shape` + dtype is optional, defaulting to dtype='d'. + + coo_array((data, coords), [shape]) + to construct from existing data and index arrays: + 1. data[:] the entries of the sparse array, in any order + 2. coords[i][:] the axis-i coordinates of the data entries + + Where ``A[coords] = data``, and coords is a tuple of index arrays. + When shape is not specified, it is inferred from the index arrays. + + Attributes + ---------- + dtype : dtype + Data type of the sparse array + shape : tuple of integers + Shape of the sparse array + ndim : int + Number of dimensions of the sparse array + nnz + size + data + COO format data array of the sparse array + coords + COO format tuple of index arrays + has_canonical_format : bool + Whether the matrix has sorted coordinates and no duplicates + format + T + + Notes + ----- + + Sparse arrays can be used in arithmetic operations: they support + addition, subtraction, multiplication, division, and matrix power. + + Advantages of the COO format + - facilitates fast conversion among sparse formats + - permits duplicate entries (see example) + - very fast conversion to and from CSR/CSC formats + + Disadvantages of the COO format + - does not directly support: + + arithmetic operations + + slicing + + Intended Usage + - COO is a fast format for constructing sparse arrays + - Once a COO array has been constructed, convert to CSR or + CSC format for fast arithmetic and matrix vector operations + - By default when converting to CSR or CSC format, duplicate (i,j) + entries will be summed together. This facilitates efficient + construction of finite element matrices and the like. (see example) + + Canonical format + - Entries and coordinates sorted by row, then column. + - There are no duplicate entries (i.e. duplicate (i,j) locations) + - Data arrays MAY have explicit zeros. + + Examples + -------- + + >>> # Constructing an empty sparse array + >>> import numpy as np + >>> from scipy.sparse import coo_array + >>> coo_array((3, 4), dtype=np.int8).toarray() + array([[0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0]], dtype=int8) + + >>> # Constructing a sparse array using ijv format + >>> row = np.array([0, 3, 1, 0]) + >>> col = np.array([0, 3, 1, 2]) + >>> data = np.array([4, 5, 7, 9]) + >>> coo_array((data, (row, col)), shape=(4, 4)).toarray() + array([[4, 0, 9, 0], + [0, 7, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 5]]) + + >>> # Constructing a sparse array with duplicate coordinates + >>> row = np.array([0, 0, 1, 3, 1, 0, 0]) + >>> col = np.array([0, 2, 1, 3, 1, 0, 0]) + >>> data = np.array([1, 1, 1, 1, 1, 1, 1]) + >>> coo = coo_array((data, (row, col)), shape=(4, 4)) + >>> # Duplicate coordinates are maintained until implicitly or explicitly summed + >>> np.max(coo.data) + 1 + >>> coo.toarray() + array([[3, 0, 1, 0], + [0, 2, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 1]]) + + """ + + +class coo_matrix(spmatrix, _coo_base): + """ + A sparse matrix in COOrdinate format. + + Also known as the 'ijv' or 'triplet' format. + + This can be instantiated in several ways: + coo_matrix(D) + where D is a 2-D ndarray + + coo_matrix(S) + with another sparse array or matrix S (equivalent to S.tocoo()) + + coo_matrix((M, N), [dtype]) + to construct an empty matrix with shape (M, N) + dtype is optional, defaulting to dtype='d'. + + coo_matrix((data, (i, j)), [shape=(M, N)]) + to construct from three arrays: + 1. data[:] the entries of the matrix, in any order + 2. i[:] the row indices of the matrix entries + 3. j[:] the column indices of the matrix entries + + Where ``A[i[k], j[k]] = data[k]``. When shape is not + specified, it is inferred from the index arrays + + Attributes + ---------- + dtype : dtype + Data type of the matrix + shape : 2-tuple + Shape of the matrix + ndim : int + Number of dimensions (this is always 2) + nnz + size + data + COO format data array of the matrix + row + COO format row index array of the matrix + col + COO format column index array of the matrix + has_canonical_format : bool + Whether the matrix has sorted indices and no duplicates + format + T + + Notes + ----- + + Sparse matrices can be used in arithmetic operations: they support + addition, subtraction, multiplication, division, and matrix power. + + Advantages of the COO format + - facilitates fast conversion among sparse formats + - permits duplicate entries (see example) + - very fast conversion to and from CSR/CSC formats + + Disadvantages of the COO format + - does not directly support: + + arithmetic operations + + slicing + + Intended Usage + - COO is a fast format for constructing sparse matrices + - Once a COO matrix has been constructed, convert to CSR or + CSC format for fast arithmetic and matrix vector operations + - By default when converting to CSR or CSC format, duplicate (i,j) + entries will be summed together. This facilitates efficient + construction of finite element matrices and the like. (see example) + + Canonical format + - Entries and coordinates sorted by row, then column. + - There are no duplicate entries (i.e. duplicate (i,j) locations) + - Data arrays MAY have explicit zeros. + + Examples + -------- + + >>> # Constructing an empty matrix + >>> import numpy as np + >>> from scipy.sparse import coo_matrix + >>> coo_matrix((3, 4), dtype=np.int8).toarray() + array([[0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0]], dtype=int8) + + >>> # Constructing a matrix using ijv format + >>> row = np.array([0, 3, 1, 0]) + >>> col = np.array([0, 3, 1, 2]) + >>> data = np.array([4, 5, 7, 9]) + >>> coo_matrix((data, (row, col)), shape=(4, 4)).toarray() + array([[4, 0, 9, 0], + [0, 7, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 5]]) + + >>> # Constructing a matrix with duplicate coordinates + >>> row = np.array([0, 0, 1, 3, 1, 0, 0]) + >>> col = np.array([0, 2, 1, 3, 1, 0, 0]) + >>> data = np.array([1, 1, 1, 1, 1, 1, 1]) + >>> coo = coo_matrix((data, (row, col)), shape=(4, 4)) + >>> # Duplicate coordinates are maintained until implicitly or explicitly summed + >>> np.max(coo.data) + 1 + >>> coo.toarray() + array([[3, 0, 1, 0], + [0, 2, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 1]]) + + """ + + def __setstate__(self, state): + if 'coords' not in state: + # For retro-compatibility with the previous attributes + # storing nnz coordinates for 2D COO matrix. + state['coords'] = (state.pop('row'), state.pop('col')) + self.__dict__.update(state) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_csc.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_csc.py new file mode 100644 index 0000000000000000000000000000000000000000..9a03f50f6a29c71a838e6a9c93d61c20114bb432 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_csc.py @@ -0,0 +1,367 @@ +"""Compressed Sparse Column matrix format""" +__docformat__ = "restructuredtext en" + +__all__ = ['csc_array', 'csc_matrix', 'isspmatrix_csc'] + + +import numpy as np + +from ._matrix import spmatrix +from ._base import _spbase, sparray +from ._sparsetools import csc_tocsr, expandptr +from ._sputils import upcast + +from ._compressed import _cs_matrix + + +class _csc_base(_cs_matrix): + _format = 'csc' + + def transpose(self, axes=None, copy=False): + if axes is not None and axes != (1, 0): + raise ValueError("Sparse arrays/matrices do not support " + "an 'axes' parameter because swapping " + "dimensions is the only logical permutation.") + + M, N = self.shape + + return self._csr_container((self.data, self.indices, + self.indptr), (N, M), copy=copy) + + transpose.__doc__ = _spbase.transpose.__doc__ + + def __iter__(self): + yield from self.tocsr() + + def tocsc(self, copy=False): + if copy: + return self.copy() + else: + return self + + tocsc.__doc__ = _spbase.tocsc.__doc__ + + def tocsr(self, copy=False): + M,N = self.shape + idx_dtype = self._get_index_dtype((self.indptr, self.indices), + maxval=max(self.nnz, N)) + indptr = np.empty(M + 1, dtype=idx_dtype) + indices = np.empty(self.nnz, dtype=idx_dtype) + data = np.empty(self.nnz, dtype=upcast(self.dtype)) + + csc_tocsr(M, N, + self.indptr.astype(idx_dtype), + self.indices.astype(idx_dtype), + self.data, + indptr, + indices, + data) + + A = self._csr_container( + (data, indices, indptr), + shape=self.shape, copy=False + ) + A.has_sorted_indices = True + return A + + tocsr.__doc__ = _spbase.tocsr.__doc__ + + def nonzero(self): + # CSC can't use _cs_matrix's .nonzero method because it + # returns the indices sorted for self transposed. + + # Get row and col indices, from _cs_matrix.tocoo + major_dim, minor_dim = self._swap(self.shape) + minor_indices = self.indices + major_indices = np.empty(len(minor_indices), dtype=self.indices.dtype) + expandptr(major_dim, self.indptr, major_indices) + row, col = self._swap((major_indices, minor_indices)) + + # Remove explicit zeros + nz_mask = self.data != 0 + row = row[nz_mask] + col = col[nz_mask] + + # Sort them to be in C-style order + ind = np.argsort(row, kind='mergesort') + row = row[ind] + col = col[ind] + + return row, col + + nonzero.__doc__ = _cs_matrix.nonzero.__doc__ + + def _getrow(self, i): + """Returns a copy of row i of the matrix, as a (1 x n) + CSR matrix (row vector). + """ + M, N = self.shape + i = int(i) + if i < 0: + i += M + if i < 0 or i >= M: + raise IndexError('index (%d) out of range' % i) + return self._get_submatrix(minor=i).tocsr() + + def _getcol(self, i): + """Returns a copy of column i of the matrix, as a (m x 1) + CSC matrix (column vector). + """ + M, N = self.shape + i = int(i) + if i < 0: + i += N + if i < 0 or i >= N: + raise IndexError('index (%d) out of range' % i) + return self._get_submatrix(major=i, copy=True) + + def _get_intXarray(self, row, col): + return self._major_index_fancy(col)._get_submatrix(minor=row) + + def _get_intXslice(self, row, col): + if col.step in (1, None): + return self._get_submatrix(major=col, minor=row, copy=True) + return self._major_slice(col)._get_submatrix(minor=row) + + def _get_sliceXint(self, row, col): + if row.step in (1, None): + return self._get_submatrix(major=col, minor=row, copy=True) + return self._get_submatrix(major=col)._minor_slice(row) + + def _get_sliceXarray(self, row, col): + return self._major_index_fancy(col)._minor_slice(row) + + def _get_arrayXint(self, row, col): + res = self._get_submatrix(major=col)._minor_index_fancy(row) + if row.ndim > 1: + return res.reshape(row.shape) + return res + + def _get_arrayXslice(self, row, col): + return self._major_slice(col)._minor_index_fancy(row) + + # these functions are used by the parent class (_cs_matrix) + # to remove redundancy between csc_array and csr_matrix + @staticmethod + def _swap(x): + """swap the members of x if this is a column-oriented matrix + """ + return x[1], x[0] + + +def isspmatrix_csc(x): + """Is `x` of csc_matrix type? + + Parameters + ---------- + x + object to check for being a csc matrix + + Returns + ------- + bool + True if `x` is a csc matrix, False otherwise + + Examples + -------- + >>> from scipy.sparse import csc_array, csc_matrix, coo_matrix, isspmatrix_csc + >>> isspmatrix_csc(csc_matrix([[5]])) + True + >>> isspmatrix_csc(csc_array([[5]])) + False + >>> isspmatrix_csc(coo_matrix([[5]])) + False + """ + return isinstance(x, csc_matrix) + + +# This namespace class separates array from matrix with isinstance +class csc_array(_csc_base, sparray): + """ + Compressed Sparse Column array. + + This can be instantiated in several ways: + csc_array(D) + where D is a 2-D ndarray + + csc_array(S) + with another sparse array or matrix S (equivalent to S.tocsc()) + + csc_array((M, N), [dtype]) + to construct an empty array with shape (M, N) + dtype is optional, defaulting to dtype='d'. + + csc_array((data, (row_ind, col_ind)), [shape=(M, N)]) + where ``data``, ``row_ind`` and ``col_ind`` satisfy the + relationship ``a[row_ind[k], col_ind[k]] = data[k]``. + + csc_array((data, indices, indptr), [shape=(M, N)]) + is the standard CSC representation where the row indices for + column i are stored in ``indices[indptr[i]:indptr[i+1]]`` + and their corresponding values are stored in + ``data[indptr[i]:indptr[i+1]]``. If the shape parameter is + not supplied, the array dimensions are inferred from + the index arrays. + + Attributes + ---------- + dtype : dtype + Data type of the array + shape : 2-tuple + Shape of the array + ndim : int + Number of dimensions (this is always 2) + nnz + size + data + CSC format data array of the array + indices + CSC format index array of the array + indptr + CSC format index pointer array of the array + has_sorted_indices + has_canonical_format + T + + Notes + ----- + + Sparse arrays can be used in arithmetic operations: they support + addition, subtraction, multiplication, division, and matrix power. + + Advantages of the CSC format + - efficient arithmetic operations CSC + CSC, CSC * CSC, etc. + - efficient column slicing + - fast matrix vector products (CSR, BSR may be faster) + + Disadvantages of the CSC format + - slow row slicing operations (consider CSR) + - changes to the sparsity structure are expensive (consider LIL or DOK) + + Canonical format + - Within each column, indices are sorted by row. + - There are no duplicate entries. + + Examples + -------- + + >>> import numpy as np + >>> from scipy.sparse import csc_array + >>> csc_array((3, 4), dtype=np.int8).toarray() + array([[0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0]], dtype=int8) + + >>> row = np.array([0, 2, 2, 0, 1, 2]) + >>> col = np.array([0, 0, 1, 2, 2, 2]) + >>> data = np.array([1, 2, 3, 4, 5, 6]) + >>> csc_array((data, (row, col)), shape=(3, 3)).toarray() + array([[1, 0, 4], + [0, 0, 5], + [2, 3, 6]]) + + >>> indptr = np.array([0, 2, 3, 6]) + >>> indices = np.array([0, 2, 2, 0, 1, 2]) + >>> data = np.array([1, 2, 3, 4, 5, 6]) + >>> csc_array((data, indices, indptr), shape=(3, 3)).toarray() + array([[1, 0, 4], + [0, 0, 5], + [2, 3, 6]]) + + """ + + +class csc_matrix(spmatrix, _csc_base): + """ + Compressed Sparse Column matrix. + + This can be instantiated in several ways: + csc_matrix(D) + where D is a 2-D ndarray + + csc_matrix(S) + with another sparse array or matrix S (equivalent to S.tocsc()) + + csc_matrix((M, N), [dtype]) + to construct an empty matrix with shape (M, N) + dtype is optional, defaulting to dtype='d'. + + csc_matrix((data, (row_ind, col_ind)), [shape=(M, N)]) + where ``data``, ``row_ind`` and ``col_ind`` satisfy the + relationship ``a[row_ind[k], col_ind[k]] = data[k]``. + + csc_matrix((data, indices, indptr), [shape=(M, N)]) + is the standard CSC representation where the row indices for + column i are stored in ``indices[indptr[i]:indptr[i+1]]`` + and their corresponding values are stored in + ``data[indptr[i]:indptr[i+1]]``. If the shape parameter is + not supplied, the matrix dimensions are inferred from + the index arrays. + + Attributes + ---------- + dtype : dtype + Data type of the matrix + shape : 2-tuple + Shape of the matrix + ndim : int + Number of dimensions (this is always 2) + nnz + size + data + CSC format data array of the matrix + indices + CSC format index array of the matrix + indptr + CSC format index pointer array of the matrix + has_sorted_indices + has_canonical_format + T + + Notes + ----- + + Sparse matrices can be used in arithmetic operations: they support + addition, subtraction, multiplication, division, and matrix power. + + Advantages of the CSC format + - efficient arithmetic operations CSC + CSC, CSC * CSC, etc. + - efficient column slicing + - fast matrix vector products (CSR, BSR may be faster) + + Disadvantages of the CSC format + - slow row slicing operations (consider CSR) + - changes to the sparsity structure are expensive (consider LIL or DOK) + + Canonical format + - Within each column, indices are sorted by row. + - There are no duplicate entries. + + Examples + -------- + + >>> import numpy as np + >>> from scipy.sparse import csc_matrix + >>> csc_matrix((3, 4), dtype=np.int8).toarray() + array([[0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0]], dtype=int8) + + >>> row = np.array([0, 2, 2, 0, 1, 2]) + >>> col = np.array([0, 0, 1, 2, 2, 2]) + >>> data = np.array([1, 2, 3, 4, 5, 6]) + >>> csc_matrix((data, (row, col)), shape=(3, 3)).toarray() + array([[1, 0, 4], + [0, 0, 5], + [2, 3, 6]]) + + >>> indptr = np.array([0, 2, 3, 6]) + >>> indices = np.array([0, 2, 2, 0, 1, 2]) + >>> data = np.array([1, 2, 3, 4, 5, 6]) + >>> csc_matrix((data, indices, indptr), shape=(3, 3)).toarray() + array([[1, 0, 4], + [0, 0, 5], + [2, 3, 6]]) + + """ + diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_csr.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_csr.py new file mode 100644 index 0000000000000000000000000000000000000000..52ce35cdb1fbf75c26a08b4e13b93d236566ab0b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_csr.py @@ -0,0 +1,558 @@ +"""Compressed Sparse Row matrix format""" + +__docformat__ = "restructuredtext en" + +__all__ = ['csr_array', 'csr_matrix', 'isspmatrix_csr'] + +import numpy as np + +from ._matrix import spmatrix +from ._base import _spbase, sparray +from ._sparsetools import (csr_tocsc, csr_tobsr, csr_count_blocks, + get_csr_submatrix, csr_sample_values) +from ._sputils import upcast + +from ._compressed import _cs_matrix + + +class _csr_base(_cs_matrix): + _format = 'csr' + _allow_nd = (1, 2) + + def transpose(self, axes=None, copy=False): + if axes is not None and axes != (1, 0): + raise ValueError("Sparse arrays/matrices do not support " + "an 'axes' parameter because swapping " + "dimensions is the only logical permutation.") + + if self.ndim == 1: + return self.copy() if copy else self + M, N = self.shape + return self._csc_container((self.data, self.indices, + self.indptr), shape=(N, M), copy=copy) + + transpose.__doc__ = _spbase.transpose.__doc__ + + def tolil(self, copy=False): + if self.ndim != 2: + raise ValueError("Cannot convert a 1d sparse array to lil format") + lil = self._lil_container(self.shape, dtype=self.dtype) + + self.sum_duplicates() + ptr,ind,dat = self.indptr,self.indices,self.data + rows, data = lil.rows, lil.data + + for n in range(self.shape[0]): + start = ptr[n] + end = ptr[n+1] + rows[n] = ind[start:end].tolist() + data[n] = dat[start:end].tolist() + + return lil + + tolil.__doc__ = _spbase.tolil.__doc__ + + def tocsr(self, copy=False): + if copy: + return self.copy() + else: + return self + + tocsr.__doc__ = _spbase.tocsr.__doc__ + + def tocsc(self, copy=False): + if self.ndim != 2: + raise ValueError("Cannot convert a 1d sparse array to csc format") + M, N = self.shape + idx_dtype = self._get_index_dtype((self.indptr, self.indices), + maxval=max(self.nnz, M)) + indptr = np.empty(N + 1, dtype=idx_dtype) + indices = np.empty(self.nnz, dtype=idx_dtype) + data = np.empty(self.nnz, dtype=upcast(self.dtype)) + + csr_tocsc(M, N, + self.indptr.astype(idx_dtype), + self.indices.astype(idx_dtype), + self.data, + indptr, + indices, + data) + + A = self._csc_container((data, indices, indptr), shape=self.shape) + A.has_sorted_indices = True + return A + + tocsc.__doc__ = _spbase.tocsc.__doc__ + + def tobsr(self, blocksize=None, copy=True): + if self.ndim != 2: + raise ValueError("Cannot convert a 1d sparse array to bsr format") + if blocksize is None: + from ._spfuncs import estimate_blocksize + return self.tobsr(blocksize=estimate_blocksize(self)) + + elif blocksize == (1,1): + arg1 = (self.data.reshape(-1,1,1),self.indices,self.indptr) + return self._bsr_container(arg1, shape=self.shape, copy=copy) + + else: + R,C = blocksize + M,N = self.shape + + if R < 1 or C < 1 or M % R != 0 or N % C != 0: + raise ValueError(f'invalid blocksize {blocksize}') + + blks = csr_count_blocks(M,N,R,C,self.indptr,self.indices) + + idx_dtype = self._get_index_dtype((self.indptr, self.indices), + maxval=max(N//C, blks)) + indptr = np.empty(M//R+1, dtype=idx_dtype) + indices = np.empty(blks, dtype=idx_dtype) + data = np.zeros((blks,R,C), dtype=self.dtype) + + csr_tobsr(M, N, R, C, + self.indptr.astype(idx_dtype), + self.indices.astype(idx_dtype), + self.data, + indptr, indices, data.ravel()) + + return self._bsr_container( + (data, indices, indptr), shape=self.shape + ) + + tobsr.__doc__ = _spbase.tobsr.__doc__ + + # these functions are used by the parent class (_cs_matrix) + # to remove redundancy between csc_matrix and csr_array + @staticmethod + def _swap(x): + """swap the members of x if this is a column-oriented matrix + """ + return x + + def __iter__(self): + if self.ndim == 1: + zero = self.dtype.type(0) + u = 0 + for v, d in zip(self.indices, self.data): + for _ in range(v - u): + yield zero + yield d + u = v + 1 + for _ in range(self.shape[0] - u): + yield zero + return + + indptr = np.zeros(2, dtype=self.indptr.dtype) + # return 1d (sparray) or 2drow (spmatrix) + shape = self.shape[1:] if isinstance(self, sparray) else (1, self.shape[1]) + i0 = 0 + for i1 in self.indptr[1:]: + indptr[1] = i1 - i0 + indices = self.indices[i0:i1] + data = self.data[i0:i1] + yield self.__class__((data, indices, indptr), shape=shape, copy=True) + i0 = i1 + + def _getrow(self, i): + """Returns a copy of row i of the matrix, as a (1 x n) + CSR matrix (row vector). + """ + if self.ndim == 1: + if i not in (0, -1): + raise IndexError(f'index ({i}) out of range') + return self.reshape((1, self.shape[0]), copy=True) + + M, N = self.shape + i = int(i) + if i < 0: + i += M + if i < 0 or i >= M: + raise IndexError('index (%d) out of range' % i) + indptr, indices, data = get_csr_submatrix( + M, N, self.indptr, self.indices, self.data, i, i + 1, 0, N) + return self.__class__((data, indices, indptr), shape=(1, N), + dtype=self.dtype, copy=False) + + def _getcol(self, i): + """Returns a copy of column i. A (m x 1) sparse array (column vector). + """ + if self.ndim == 1: + raise ValueError("getcol not provided for 1d arrays. Use indexing A[j]") + M, N = self.shape + i = int(i) + if i < 0: + i += N + if i < 0 or i >= N: + raise IndexError('index (%d) out of range' % i) + indptr, indices, data = get_csr_submatrix( + M, N, self.indptr, self.indices, self.data, 0, M, i, i + 1) + return self.__class__((data, indices, indptr), shape=(M, 1), + dtype=self.dtype, copy=False) + + def _get_int(self, idx): + spot = np.flatnonzero(self.indices == idx) + if spot.size: + return self.data[spot[0]] + return self.data.dtype.type(0) + + def _get_slice(self, idx): + if idx == slice(None): + return self.copy() + if idx.step in (1, None): + ret = self._get_submatrix(0, idx, copy=True) + return ret.reshape(ret.shape[-1]) + return self._minor_slice(idx) + + def _get_array(self, idx): + idx_dtype = self._get_index_dtype(self.indices) + idx = np.asarray(idx, dtype=idx_dtype) + if idx.size == 0: + return self.__class__([], dtype=self.dtype) + + M, N = 1, self.shape[0] + row = np.zeros_like(idx, dtype=idx_dtype) + col = np.asarray(idx, dtype=idx_dtype) + val = np.empty(row.size, dtype=self.dtype) + csr_sample_values(M, N, self.indptr, self.indices, self.data, + row.size, row, col, val) + + new_shape = col.shape if col.shape[0] > 1 else (col.shape[0],) + return self.__class__(val.reshape(new_shape)) + + def _get_intXarray(self, row, col): + return self._getrow(row)._minor_index_fancy(col) + + def _get_intXslice(self, row, col): + if col.step in (1, None): + return self._get_submatrix(row, col, copy=True) + # TODO: uncomment this once it's faster: + # return self._getrow(row)._minor_slice(col) + + M, N = self.shape + start, stop, stride = col.indices(N) + + ii, jj = self.indptr[row:row+2] + row_indices = self.indices[ii:jj] + row_data = self.data[ii:jj] + + if stride > 0: + ind = (row_indices >= start) & (row_indices < stop) + else: + ind = (row_indices <= start) & (row_indices > stop) + + if abs(stride) > 1: + ind &= (row_indices - start) % stride == 0 + + row_indices = (row_indices[ind] - start) // stride + row_data = row_data[ind] + row_indptr = np.array([0, len(row_indices)]) + + if stride < 0: + row_data = row_data[::-1] + row_indices = abs(row_indices[::-1]) + + shape = (1, max(0, int(np.ceil(float(stop - start) / stride)))) + return self.__class__((row_data, row_indices, row_indptr), shape=shape, + dtype=self.dtype, copy=False) + + def _get_sliceXint(self, row, col): + if row.step in (1, None): + return self._get_submatrix(row, col, copy=True) + return self._major_slice(row)._get_submatrix(minor=col) + + def _get_sliceXarray(self, row, col): + return self._major_slice(row)._minor_index_fancy(col) + + def _get_arrayXint(self, row, col): + res = self._major_index_fancy(row)._get_submatrix(minor=col) + if row.ndim > 1: + return res.reshape(row.shape) + return res + + def _get_arrayXslice(self, row, col): + if col.step not in (1, None): + col = np.arange(*col.indices(self.shape[1])) + return self._get_arrayXarray(row, col) + return self._major_index_fancy(row)._get_submatrix(minor=col) + + def _set_int(self, idx, x): + self._set_many(0, idx, x) + + def _set_array(self, idx, x): + x = np.broadcast_to(x, idx.shape) + self._set_many(np.zeros_like(idx), idx, x) + + +def isspmatrix_csr(x): + """Is `x` of csr_matrix type? + + Parameters + ---------- + x + object to check for being a csr matrix + + Returns + ------- + bool + True if `x` is a csr matrix, False otherwise + + Examples + -------- + >>> from scipy.sparse import csr_array, csr_matrix, coo_matrix, isspmatrix_csr + >>> isspmatrix_csr(csr_matrix([[5]])) + True + >>> isspmatrix_csr(csr_array([[5]])) + False + >>> isspmatrix_csr(coo_matrix([[5]])) + False + """ + return isinstance(x, csr_matrix) + + +# This namespace class separates array from matrix with isinstance +class csr_array(_csr_base, sparray): + """ + Compressed Sparse Row array. + + This can be instantiated in several ways: + csr_array(D) + where D is a 2-D ndarray + + csr_array(S) + with another sparse array or matrix S (equivalent to S.tocsr()) + + csr_array((M, N), [dtype]) + to construct an empty array with shape (M, N) + dtype is optional, defaulting to dtype='d'. + + csr_array((data, (row_ind, col_ind)), [shape=(M, N)]) + where ``data``, ``row_ind`` and ``col_ind`` satisfy the + relationship ``a[row_ind[k], col_ind[k]] = data[k]``. + + csr_array((data, indices, indptr), [shape=(M, N)]) + is the standard CSR representation where the column indices for + row i are stored in ``indices[indptr[i]:indptr[i+1]]`` and their + corresponding values are stored in ``data[indptr[i]:indptr[i+1]]``. + If the shape parameter is not supplied, the array dimensions + are inferred from the index arrays. + + Attributes + ---------- + dtype : dtype + Data type of the array + shape : 2-tuple + Shape of the array + ndim : int + Number of dimensions (this is always 2) + nnz + size + data + CSR format data array of the array + indices + CSR format index array of the array + indptr + CSR format index pointer array of the array + has_sorted_indices + has_canonical_format + T + + Notes + ----- + + Sparse arrays can be used in arithmetic operations: they support + addition, subtraction, multiplication, division, and matrix power. + + Advantages of the CSR format + - efficient arithmetic operations CSR + CSR, CSR * CSR, etc. + - efficient row slicing + - fast matrix vector products + + Disadvantages of the CSR format + - slow column slicing operations (consider CSC) + - changes to the sparsity structure are expensive (consider LIL or DOK) + + Canonical Format + - Within each row, indices are sorted by column. + - There are no duplicate entries. + + Examples + -------- + + >>> import numpy as np + >>> from scipy.sparse import csr_array + >>> csr_array((3, 4), dtype=np.int8).toarray() + array([[0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0]], dtype=int8) + + >>> row = np.array([0, 0, 1, 2, 2, 2]) + >>> col = np.array([0, 2, 2, 0, 1, 2]) + >>> data = np.array([1, 2, 3, 4, 5, 6]) + >>> csr_array((data, (row, col)), shape=(3, 3)).toarray() + array([[1, 0, 2], + [0, 0, 3], + [4, 5, 6]]) + + >>> indptr = np.array([0, 2, 3, 6]) + >>> indices = np.array([0, 2, 2, 0, 1, 2]) + >>> data = np.array([1, 2, 3, 4, 5, 6]) + >>> csr_array((data, indices, indptr), shape=(3, 3)).toarray() + array([[1, 0, 2], + [0, 0, 3], + [4, 5, 6]]) + + Duplicate entries are summed together: + + >>> row = np.array([0, 1, 2, 0]) + >>> col = np.array([0, 1, 1, 0]) + >>> data = np.array([1, 2, 4, 8]) + >>> csr_array((data, (row, col)), shape=(3, 3)).toarray() + array([[9, 0, 0], + [0, 2, 0], + [0, 4, 0]]) + + As an example of how to construct a CSR array incrementally, + the following snippet builds a term-document array from texts: + + >>> docs = [["hello", "world", "hello"], ["goodbye", "cruel", "world"]] + >>> indptr = [0] + >>> indices = [] + >>> data = [] + >>> vocabulary = {} + >>> for d in docs: + ... for term in d: + ... index = vocabulary.setdefault(term, len(vocabulary)) + ... indices.append(index) + ... data.append(1) + ... indptr.append(len(indices)) + ... + >>> csr_array((data, indices, indptr), dtype=int).toarray() + array([[2, 1, 0, 0], + [0, 1, 1, 1]]) + + """ + + +class csr_matrix(spmatrix, _csr_base): + """ + Compressed Sparse Row matrix. + + This can be instantiated in several ways: + csr_matrix(D) + where D is a 2-D ndarray + + csr_matrix(S) + with another sparse array or matrix S (equivalent to S.tocsr()) + + csr_matrix((M, N), [dtype]) + to construct an empty matrix with shape (M, N) + dtype is optional, defaulting to dtype='d'. + + csr_matrix((data, (row_ind, col_ind)), [shape=(M, N)]) + where ``data``, ``row_ind`` and ``col_ind`` satisfy the + relationship ``a[row_ind[k], col_ind[k]] = data[k]``. + + csr_matrix((data, indices, indptr), [shape=(M, N)]) + is the standard CSR representation where the column indices for + row i are stored in ``indices[indptr[i]:indptr[i+1]]`` and their + corresponding values are stored in ``data[indptr[i]:indptr[i+1]]``. + If the shape parameter is not supplied, the matrix dimensions + are inferred from the index arrays. + + Attributes + ---------- + dtype : dtype + Data type of the matrix + shape : 2-tuple + Shape of the matrix + ndim : int + Number of dimensions (this is always 2) + nnz + size + data + CSR format data array of the matrix + indices + CSR format index array of the matrix + indptr + CSR format index pointer array of the matrix + has_sorted_indices + has_canonical_format + T + + Notes + ----- + + Sparse matrices can be used in arithmetic operations: they support + addition, subtraction, multiplication, division, and matrix power. + + Advantages of the CSR format + - efficient arithmetic operations CSR + CSR, CSR * CSR, etc. + - efficient row slicing + - fast matrix vector products + + Disadvantages of the CSR format + - slow column slicing operations (consider CSC) + - changes to the sparsity structure are expensive (consider LIL or DOK) + + Canonical Format + - Within each row, indices are sorted by column. + - There are no duplicate entries. + + Examples + -------- + + >>> import numpy as np + >>> from scipy.sparse import csr_matrix + >>> csr_matrix((3, 4), dtype=np.int8).toarray() + array([[0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0]], dtype=int8) + + >>> row = np.array([0, 0, 1, 2, 2, 2]) + >>> col = np.array([0, 2, 2, 0, 1, 2]) + >>> data = np.array([1, 2, 3, 4, 5, 6]) + >>> csr_matrix((data, (row, col)), shape=(3, 3)).toarray() + array([[1, 0, 2], + [0, 0, 3], + [4, 5, 6]]) + + >>> indptr = np.array([0, 2, 3, 6]) + >>> indices = np.array([0, 2, 2, 0, 1, 2]) + >>> data = np.array([1, 2, 3, 4, 5, 6]) + >>> csr_matrix((data, indices, indptr), shape=(3, 3)).toarray() + array([[1, 0, 2], + [0, 0, 3], + [4, 5, 6]]) + + Duplicate entries are summed together: + + >>> row = np.array([0, 1, 2, 0]) + >>> col = np.array([0, 1, 1, 0]) + >>> data = np.array([1, 2, 4, 8]) + >>> csr_matrix((data, (row, col)), shape=(3, 3)).toarray() + array([[9, 0, 0], + [0, 2, 0], + [0, 4, 0]]) + + As an example of how to construct a CSR matrix incrementally, + the following snippet builds a term-document matrix from texts: + + >>> docs = [["hello", "world", "hello"], ["goodbye", "cruel", "world"]] + >>> indptr = [0] + >>> indices = [] + >>> data = [] + >>> vocabulary = {} + >>> for d in docs: + ... for term in d: + ... index = vocabulary.setdefault(term, len(vocabulary)) + ... indices.append(index) + ... data.append(1) + ... indptr.append(len(indices)) + ... + >>> csr_matrix((data, indices, indptr), dtype=int).toarray() + array([[2, 1, 0, 0], + [0, 1, 1, 1]]) + + """ + diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_data.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_data.py new file mode 100644 index 0000000000000000000000000000000000000000..585820b10a65271b52b81d140e82130eb4177979 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_data.py @@ -0,0 +1,569 @@ +"""Base class for sparse matrice with a .data attribute + + subclasses must provide a _with_data() method that + creates a new matrix with the same sparsity pattern + as self but with a different data array + +""" + +import math +import numpy as np + +from ._base import _spbase, sparray, _ufuncs_with_fixed_point_at_zero +from ._sputils import isscalarlike, validateaxis + +__all__ = [] + + +# TODO implement all relevant operations +# use .data.__methods__() instead of /=, *=, etc. +class _data_matrix(_spbase): + def __init__(self, arg1, *, maxprint=None): + _spbase.__init__(self, arg1, maxprint=maxprint) + + @property + def dtype(self): + return self.data.dtype + + @dtype.setter + def dtype(self, newtype): + self.data.dtype = newtype + + def _deduped_data(self): + if hasattr(self, 'sum_duplicates'): + self.sum_duplicates() + return self.data + + def __abs__(self): + return self._with_data(abs(self._deduped_data())) + + def __round__(self, ndigits=0): + return self._with_data(np.around(self._deduped_data(), decimals=ndigits)) + + def _real(self): + return self._with_data(self.data.real) + + def _imag(self): + return self._with_data(self.data.imag) + + def __neg__(self): + if self.dtype.kind == 'b': + raise NotImplementedError('negating a boolean sparse array is not ' + 'supported') + return self._with_data(-self.data) + + def __imul__(self, other): # self *= other + if isscalarlike(other): + self.data *= other + return self + return NotImplemented + + def __itruediv__(self, other): # self /= other + if isscalarlike(other): + recip = 1.0 / other + self.data *= recip + return self + else: + return NotImplemented + + def astype(self, dtype, casting='unsafe', copy=True): + dtype = np.dtype(dtype) + if self.dtype != dtype: + matrix = self._with_data( + self.data.astype(dtype, casting=casting, copy=True), + copy=True + ) + return matrix._with_data(matrix._deduped_data(), copy=False) + elif copy: + return self.copy() + else: + return self + + astype.__doc__ = _spbase.astype.__doc__ + + def conjugate(self, copy=True): + if np.issubdtype(self.dtype, np.complexfloating): + return self._with_data(self.data.conjugate(), copy=copy) + elif copy: + return self.copy() + else: + return self + + conjugate.__doc__ = _spbase.conjugate.__doc__ + + def copy(self): + return self._with_data(self.data.copy(), copy=True) + + copy.__doc__ = _spbase.copy.__doc__ + + def power(self, n, dtype=None): + """ + This function performs element-wise power. + + Parameters + ---------- + n : scalar + n is a non-zero scalar (nonzero avoids dense ones creation) + If zero power is desired, special case it to use `np.ones` + + dtype : If dtype is not specified, the current dtype will be preserved. + + Raises + ------ + NotImplementedError : if n is a zero scalar + If zero power is desired, special case it to use + ``np.ones(A.shape, dtype=A.dtype)`` + """ + if not isscalarlike(n): + raise NotImplementedError("input is not scalar") + if not n: + raise NotImplementedError( + "zero power is not supported as it would densify the matrix.\n" + "Use `np.ones(A.shape, dtype=A.dtype)` for this case." + ) + + data = self._deduped_data() + if dtype is not None: + data = data.astype(dtype) + return self._with_data(data ** n) + + ########################### + # Multiplication handlers # + ########################### + + def _mul_scalar(self, other): + return self._with_data(self.data * other) + + +# Add the numpy unary ufuncs for which func(0) = 0 to _data_matrix. +for npfunc in _ufuncs_with_fixed_point_at_zero: + name = npfunc.__name__ + + def _create_method(op): + def method(self): + result = op(self._deduped_data()) + return self._with_data(result, copy=True) + + method.__doc__ = (f"Element-wise {name}.\n\n" + f"See `numpy.{name}` for more information.") + method.__name__ = name + + return method + + setattr(_data_matrix, name, _create_method(npfunc)) + + +def _find_missing_index(ind, n): + for k, a in enumerate(ind): + if k != a: + return k + + k += 1 + if k < n: + return k + else: + return -1 + + +class _minmax_mixin: + """Mixin for min and max methods. + + These are not implemented for dia_matrix, hence the separate class. + """ + + def _min_or_max_axis(self, axis, min_or_max, explicit): + N = self.shape[axis] + if N == 0: + raise ValueError("zero-size array to reduction operation") + M = self.shape[1 - axis] + idx_dtype = self._get_index_dtype(maxval=M) + + mat = self.tocsc() if axis == 0 else self.tocsr() + mat.sum_duplicates() + + major_index, value = mat._minor_reduce(min_or_max) + if not explicit: + not_full = np.diff(mat.indptr)[major_index] < N + value[not_full] = min_or_max(value[not_full], 0) + + mask = value != 0 + major_index = np.compress(mask, major_index).astype(idx_dtype, copy=False) + value = np.compress(mask, value) + + if isinstance(self, sparray): + coords = (major_index,) + shape = (M,) + return self._coo_container((value, coords), shape=shape, dtype=self.dtype) + + if axis == 0: + return self._coo_container( + (value, (np.zeros(len(value), dtype=idx_dtype), major_index)), + dtype=self.dtype, shape=(1, M) + ) + else: + return self._coo_container( + (value, (major_index, np.zeros(len(value), dtype=idx_dtype))), + dtype=self.dtype, shape=(M, 1) + ) + + def _min_or_max(self, axis, out, min_or_max, explicit): + if out is not None: + raise ValueError("Sparse arrays do not support an 'out' parameter.") + + validateaxis(axis) + if self.ndim == 1: + if axis not in (None, 0, -1): + raise ValueError("axis out of range") + axis = None # avoid calling special axis case. no impact on 1d + + if axis is None: + if 0 in self.shape: + raise ValueError("zero-size array to reduction operation") + + zero = self.dtype.type(0) + if self.nnz == 0: + return zero + m = min_or_max.reduce(self._deduped_data().ravel()) + if self.nnz != math.prod(self.shape) and not explicit: + m = min_or_max(zero, m) + return m + + if axis < 0: + axis += 2 + + if (axis == 0) or (axis == 1): + return self._min_or_max_axis(axis, min_or_max, explicit) + else: + raise ValueError("axis out of range") + + def _arg_min_or_max_axis(self, axis, argmin_or_argmax, compare, explicit): + if self.shape[axis] == 0: + raise ValueError("Cannot apply the operation along a zero-sized dimension.") + + if axis < 0: + axis += 2 + + zero = self.dtype.type(0) + + mat = self.tocsc() if axis == 0 else self.tocsr() + mat.sum_duplicates() + + ret_size, line_size = mat._swap(mat.shape) + ret = np.zeros(ret_size, dtype=int) + + nz_lines, = np.nonzero(np.diff(mat.indptr)) + for i in nz_lines: + p, q = mat.indptr[i:i + 2] + data = mat.data[p:q] + indices = mat.indices[p:q] + extreme_index = argmin_or_argmax(data) + extreme_value = data[extreme_index] + if explicit: + if q - p > 0: + ret[i] = indices[extreme_index] + else: + if compare(extreme_value, zero) or q - p == line_size: + ret[i] = indices[extreme_index] + else: + zero_ind = _find_missing_index(indices, line_size) + if extreme_value == zero: + ret[i] = min(extreme_index, zero_ind) + else: + ret[i] = zero_ind + + if isinstance(self, sparray): + return ret + + if axis == 1: + ret = ret.reshape(-1, 1) + + return self._ascontainer(ret) + + def _arg_min_or_max(self, axis, out, argmin_or_argmax, compare, explicit): + if out is not None: + raise ValueError("Sparse types do not support an 'out' parameter.") + + validateaxis(axis) + + if self.ndim == 1: + if axis not in (None, 0, -1): + raise ValueError("axis out of range") + axis = None # avoid calling special axis case. no impact on 1d + + if axis is not None: + return self._arg_min_or_max_axis(axis, argmin_or_argmax, compare, explicit) + + if 0 in self.shape: + raise ValueError("Cannot apply the operation to an empty matrix.") + + if self.nnz == 0: + if explicit: + raise ValueError("Cannot apply the operation to zero matrix " + "when explicit=True.") + return 0 + + zero = self.dtype.type(0) + mat = self.tocoo() + # Convert to canonical form: no duplicates, sorted indices. + mat.sum_duplicates() + extreme_index = argmin_or_argmax(mat.data) + if explicit: + return extreme_index + extreme_value = mat.data[extreme_index] + num_col = mat.shape[-1] + + # If the min value is less than zero, or max is greater than zero, + # then we do not need to worry about implicit zeros. + if compare(extreme_value, zero): + # cast to Python int to avoid overflow and RuntimeError + return int(mat.row[extreme_index]) * num_col + int(mat.col[extreme_index]) + + # Cheap test for the rare case where we have no implicit zeros. + size = math.prod(self.shape) + if size == mat.nnz: + return int(mat.row[extreme_index]) * num_col + int(mat.col[extreme_index]) + + # At this stage, any implicit zero could be the min or max value. + # After sum_duplicates(), the `row` and `col` arrays are guaranteed to + # be sorted in C-order, which means the linearized indices are sorted. + linear_indices = mat.row * num_col + mat.col + first_implicit_zero_index = _find_missing_index(linear_indices, size) + if extreme_value == zero: + return min(first_implicit_zero_index, extreme_index) + return first_implicit_zero_index + + def max(self, axis=None, out=None, *, explicit=False): + """Return the maximum of the array/matrix or maximum along an axis. + + By default, all elements are taken into account, not just the non-zero ones. + But with `explicit` set, only the stored elements are considered. + + Parameters + ---------- + axis : {-2, -1, 0, 1, None} optional + Axis along which the sum is computed. The default is to + compute the maximum over all elements, returning + a scalar (i.e., `axis` = `None`). + + out : None, optional + This argument is in the signature *solely* for NumPy + compatibility reasons. Do not pass in anything except + for the default value, as this argument is not used. + + explicit : {False, True} optional (default: False) + When set to True, only the stored elements will be considered. + If a row/column is empty, the sparse.coo_array returned + has no stored element (i.e. an implicit zero) for that row/column. + + .. versionadded:: 1.15.0 + + Returns + ------- + amax : coo_array or scalar + Maximum of `a`. If `axis` is None, the result is a scalar value. + If `axis` is given, the result is a sparse.coo_array of dimension + ``a.ndim - 1``. + + See Also + -------- + min : The minimum value of a sparse array/matrix along a given axis. + numpy.max : NumPy's implementation of 'max' + + """ + return self._min_or_max(axis, out, np.maximum, explicit) + + def min(self, axis=None, out=None, *, explicit=False): + """Return the minimum of the array/matrix or maximum along an axis. + + By default, all elements are taken into account, not just the non-zero ones. + But with `explicit` set, only the stored elements are considered. + + Parameters + ---------- + axis : {-2, -1, 0, 1, None} optional + Axis along which the sum is computed. The default is to + compute the minimum over all elements, returning + a scalar (i.e., `axis` = `None`). + + out : None, optional + This argument is in the signature *solely* for NumPy + compatibility reasons. Do not pass in anything except for + the default value, as this argument is not used. + + explicit : {False, True} optional (default: False) + When set to True, only the stored elements will be considered. + If a row/column is empty, the sparse.coo_array returned + has no stored element (i.e. an implicit zero) for that row/column. + + .. versionadded:: 1.15.0 + + Returns + ------- + amin : coo_matrix or scalar + Minimum of `a`. If `axis` is None, the result is a scalar value. + If `axis` is given, the result is a sparse.coo_array of dimension + ``a.ndim - 1``. + + See Also + -------- + max : The maximum value of a sparse array/matrix along a given axis. + numpy.min : NumPy's implementation of 'min' + + """ + return self._min_or_max(axis, out, np.minimum, explicit) + + def nanmax(self, axis=None, out=None, *, explicit=False): + """Return the maximum, ignoring any Nans, along an axis. + + Return the maximum, ignoring any Nans, of the array/matrix along an axis. + By default this takes all elements into account, but with `explicit` set, + only stored elements are considered. + + .. versionadded:: 1.11.0 + + Parameters + ---------- + axis : {-2, -1, 0, 1, None} optional + Axis along which the maximum is computed. The default is to + compute the maximum over all elements, returning + a scalar (i.e., `axis` = `None`). + + out : None, optional + This argument is in the signature *solely* for NumPy + compatibility reasons. Do not pass in anything except + for the default value, as this argument is not used. + + explicit : {False, True} optional (default: False) + When set to True, only the stored elements will be considered. + If a row/column is empty, the sparse.coo_array returned + has no stored element (i.e. an implicit zero) for that row/column. + + .. versionadded:: 1.15.0 + + Returns + ------- + amax : coo_array or scalar + Maximum of `a`. If `axis` is None, the result is a scalar value. + If `axis` is given, the result is a sparse.coo_array of dimension + ``a.ndim - 1``. + + See Also + -------- + nanmin : The minimum value of a sparse array/matrix along a given axis, + ignoring NaNs. + max : The maximum value of a sparse array/matrix along a given axis, + propagating NaNs. + numpy.nanmax : NumPy's implementation of 'nanmax'. + + """ + return self._min_or_max(axis, out, np.fmax, explicit) + + def nanmin(self, axis=None, out=None, *, explicit=False): + """Return the minimum, ignoring any Nans, along an axis. + + Return the minimum, ignoring any Nans, of the array/matrix along an axis. + By default this takes all elements into account, but with `explicit` set, + only stored elements are considered. + + .. versionadded:: 1.11.0 + + Parameters + ---------- + axis : {-2, -1, 0, 1, None} optional + Axis along which the minimum is computed. The default is to + compute the minimum over all elements, returning + a scalar (i.e., `axis` = `None`). + + out : None, optional + This argument is in the signature *solely* for NumPy + compatibility reasons. Do not pass in anything except for + the default value, as this argument is not used. + + explicit : {False, True} optional (default: False) + When set to True, only the stored elements will be considered. + If a row/column is empty, the sparse.coo_array returned + has no stored element (i.e. an implicit zero) for that row/column. + + .. versionadded:: 1.15.0 + + Returns + ------- + amin : coo_array or scalar + Minimum of `a`. If `axis` is None, the result is a scalar value. + If `axis` is given, the result is a sparse.coo_array of dimension + ``a.ndim - 1``. + + See Also + -------- + nanmax : The maximum value of a sparse array/matrix along a given axis, + ignoring NaNs. + min : The minimum value of a sparse array/matrix along a given axis, + propagating NaNs. + numpy.nanmin : NumPy's implementation of 'nanmin'. + + """ + return self._min_or_max(axis, out, np.fmin, explicit) + + def argmax(self, axis=None, out=None, *, explicit=False): + """Return indices of maximum elements along an axis. + + By default, implicit zero elements are taken into account. If there are + several minimum values, the index of the first occurrence is returned. + If `explicit` is set, only explicitly stored elements will be considered. + + Parameters + ---------- + axis : {-2, -1, 0, 1, None}, optional + Axis along which the argmax is computed. If None (default), index + of the maximum element in the flatten data is returned. + + out : None, optional + This argument is in the signature *solely* for NumPy + compatibility reasons. Do not pass in anything except for + the default value, as this argument is not used. + + explicit : {False, True} optional (default: False) + When set to True, only explicitly stored elements will be considered. + If axis is not None and a row/column has no stored elements, argmax + is undefined, so the index ``0`` is returned for that row/column. + + .. versionadded:: 1.15.0 + + Returns + ------- + ind : numpy.matrix or int + Indices of maximum elements. If matrix, its size along `axis` is 1. + """ + return self._arg_min_or_max(axis, out, np.argmax, np.greater, explicit) + + def argmin(self, axis=None, out=None, *, explicit=False): + """Return indices of minimum elements along an axis. + + By default, implicit zero elements are taken into account. If there are + several minimum values, the index of the first occurrence is returned. + If `explicit` is set, only explicitly stored elements will be considered. + + Parameters + ---------- + axis : {-2, -1, 0, 1, None}, optional + Axis along which the argmin is computed. If None (default), index + of the minimum element in the flatten data is returned. + + out : None, optional + This argument is in the signature *solely* for NumPy + compatibility reasons. Do not pass in anything except for + the default value, as this argument is not used. + + explicit : {False, True} optional (default: False) + When set to True, only explicitly stored elements will be considered. + If axis is not None and a row/column has no stored elements, argmin + is undefined, so the index ``0`` is returned for that row/column. + + .. versionadded:: 1.15.0 + + Returns + ------- + ind : numpy.matrix or int + Indices of minimum elements. If matrix, its size along `axis` is 1. + """ + return self._arg_min_or_max(axis, out, np.argmin, np.less, explicit) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_dia.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_dia.py new file mode 100644 index 0000000000000000000000000000000000000000..c2944e080b6abc1705d3f597dda7478335b2bcf3 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_dia.py @@ -0,0 +1,590 @@ +"""Sparse DIAgonal format""" + +__docformat__ = "restructuredtext en" + +__all__ = ['dia_array', 'dia_matrix', 'isspmatrix_dia'] + +import numpy as np + +from .._lib._util import copy_if_needed +from ._matrix import spmatrix +from ._base import issparse, _formats, _spbase, sparray +from ._data import _data_matrix +from ._sputils import ( + isshape, upcast_char, getdtype, get_sum_dtype, validateaxis, check_shape +) +from ._sparsetools import dia_matvec + + +class _dia_base(_data_matrix): + _format = 'dia' + + def __init__(self, arg1, shape=None, dtype=None, copy=False, *, maxprint=None): + _data_matrix.__init__(self, arg1, maxprint=maxprint) + + if issparse(arg1): + if arg1.format == "dia": + if copy: + arg1 = arg1.copy() + self.data = arg1.data + self.offsets = arg1.offsets + self._shape = check_shape(arg1.shape) + else: + if arg1.format == self.format and copy: + A = arg1.copy() + else: + A = arg1.todia() + self.data = A.data + self.offsets = A.offsets + self._shape = check_shape(A.shape) + elif isinstance(arg1, tuple): + if isshape(arg1): + # It's a tuple of matrix dimensions (M, N) + # create empty matrix + self._shape = check_shape(arg1) + self.data = np.zeros((0,0), getdtype(dtype, default=float)) + idx_dtype = self._get_index_dtype(maxval=max(self.shape)) + self.offsets = np.zeros((0), dtype=idx_dtype) + else: + try: + # Try interpreting it as (data, offsets) + data, offsets = arg1 + except Exception as e: + message = 'unrecognized form for dia_array constructor' + raise ValueError(message) from e + else: + if shape is None: + raise ValueError('expected a shape argument') + if not copy: + copy = copy_if_needed + self.data = np.atleast_2d(np.array(arg1[0], dtype=dtype, copy=copy)) + offsets = np.array(arg1[1], + dtype=self._get_index_dtype(maxval=max(shape)), + copy=copy) + self.offsets = np.atleast_1d(offsets) + self._shape = check_shape(shape) + else: + # must be dense, convert to COO first, then to DIA + try: + arg1 = np.asarray(arg1) + except Exception as e: + raise ValueError("unrecognized form for " + f"{self.format}_matrix constructor") from e + if isinstance(self, sparray) and arg1.ndim != 2: + raise ValueError(f"DIA arrays don't support {arg1.ndim}D input. Use 2D") + A = self._coo_container(arg1, dtype=dtype, shape=shape).todia() + self.data = A.data + self.offsets = A.offsets + self._shape = check_shape(A.shape) + + if dtype is not None: + newdtype = getdtype(dtype) + self.data = self.data.astype(newdtype) + + # check format + if self.offsets.ndim != 1: + raise ValueError('offsets array must have rank 1') + + if self.data.ndim != 2: + raise ValueError('data array must have rank 2') + + if self.data.shape[0] != len(self.offsets): + raise ValueError('number of diagonals (%d) ' + 'does not match the number of offsets (%d)' + % (self.data.shape[0], len(self.offsets))) + + if len(np.unique(self.offsets)) != len(self.offsets): + raise ValueError('offset array contains duplicate values') + + def __repr__(self): + _, fmt = _formats[self.format] + sparse_cls = 'array' if isinstance(self, sparray) else 'matrix' + d = self.data.shape[0] + return ( + f"<{fmt} sparse {sparse_cls} of dtype '{self.dtype}'\n" + f"\twith {self.nnz} stored elements ({d} diagonals) and shape {self.shape}>" + ) + + def _data_mask(self): + """Returns a mask of the same shape as self.data, where + mask[i,j] is True when data[i,j] corresponds to a stored element.""" + num_rows, num_cols = self.shape + offset_inds = np.arange(self.data.shape[1]) + row = offset_inds - self.offsets[:,None] + mask = (row >= 0) + mask &= (row < num_rows) + mask &= (offset_inds < num_cols) + return mask + + def count_nonzero(self, axis=None): + if axis is not None: + raise NotImplementedError( + "count_nonzero over an axis is not implemented for DIA format" + ) + mask = self._data_mask() + return np.count_nonzero(self.data[mask]) + + count_nonzero.__doc__ = _spbase.count_nonzero.__doc__ + + def _getnnz(self, axis=None): + if axis is not None: + raise NotImplementedError("_getnnz over an axis is not implemented " + "for DIA format") + M,N = self.shape + nnz = 0 + for k in self.offsets: + if k > 0: + nnz += min(M,N-k) + else: + nnz += min(M+k,N) + return int(nnz) + + _getnnz.__doc__ = _spbase._getnnz.__doc__ + + def sum(self, axis=None, dtype=None, out=None): + validateaxis(axis) + + if axis is not None and axis < 0: + axis += 2 + + res_dtype = get_sum_dtype(self.dtype) + num_rows, num_cols = self.shape + ret = None + + if axis == 0: + mask = self._data_mask() + x = (self.data * mask).sum(axis=0) + if x.shape[0] == num_cols: + res = x + else: + res = np.zeros(num_cols, dtype=x.dtype) + res[:x.shape[0]] = x + ret = self._ascontainer(res, dtype=res_dtype) + + else: + row_sums = np.zeros((num_rows, 1), dtype=res_dtype) + one = np.ones(num_cols, dtype=res_dtype) + dia_matvec(num_rows, num_cols, len(self.offsets), + self.data.shape[1], self.offsets, self.data, one, row_sums) + + row_sums = self._ascontainer(row_sums) + + if axis is None: + return row_sums.sum(dtype=dtype, out=out) + + ret = self._ascontainer(row_sums.sum(axis=axis)) + + return ret.sum(axis=(), dtype=dtype, out=out) + + sum.__doc__ = _spbase.sum.__doc__ + + def _add_sparse(self, other): + # If other is not DIA format, let them handle us instead. + if not isinstance(other, _dia_base): + return other._add_sparse(self) + + # Fast path for exact equality of the sparsity structure. + if np.array_equal(self.offsets, other.offsets): + return self._with_data(self.data + other.data) + + # Find the union of the offsets (which will be sorted and unique). + new_offsets = np.union1d(self.offsets, other.offsets) + self_idx = np.searchsorted(new_offsets, self.offsets) + other_idx = np.searchsorted(new_offsets, other.offsets) + + self_d = self.data.shape[1] + other_d = other.data.shape[1] + # Fast path for a sparsity structure where the final offsets are a + # permutation of the existing offsets and the diagonal lengths match. + if self_d == other_d and len(new_offsets) == len(self.offsets): + new_data = self.data[_invert_index(self_idx)] + new_data[other_idx, :] += other.data + elif self_d == other_d and len(new_offsets) == len(other.offsets): + new_data = other.data[_invert_index(other_idx)] + new_data[self_idx, :] += self.data + else: + # Maximum diagonal length of the result. + d = min(self.shape[0] + new_offsets[-1], self.shape[1]) + + # Add all diagonals to a freshly-allocated data array. + new_data = np.zeros( + (len(new_offsets), d), + dtype=np.result_type(self.data, other.data), + ) + new_data[self_idx, :self_d] += self.data[:, :d] + new_data[other_idx, :other_d] += other.data[:, :d] + return self._dia_container((new_data, new_offsets), shape=self.shape) + + def _mul_scalar(self, other): + return self._with_data(self.data * other) + + def _matmul_vector(self, other): + x = other + + y = np.zeros(self.shape[0], dtype=upcast_char(self.dtype.char, + x.dtype.char)) + + L = self.data.shape[1] + + M,N = self.shape + + dia_matvec(M,N, len(self.offsets), L, self.offsets, self.data, + x.ravel(), y.ravel()) + + return y + + def _setdiag(self, values, k=0): + M, N = self.shape + + if values.ndim == 0: + # broadcast + values_n = np.inf + else: + values_n = len(values) + + if k < 0: + n = min(M + k, N, values_n) + min_index = 0 + max_index = n + else: + n = min(M, N - k, values_n) + min_index = k + max_index = k + n + + if values.ndim != 0: + # allow also longer sequences + values = values[:n] + + data_rows, data_cols = self.data.shape + if k in self.offsets: + if max_index > data_cols: + data = np.zeros((data_rows, max_index), dtype=self.data.dtype) + data[:, :data_cols] = self.data + self.data = data + self.data[self.offsets == k, min_index:max_index] = values + else: + self.offsets = np.append(self.offsets, self.offsets.dtype.type(k)) + m = max(max_index, data_cols) + data = np.zeros((data_rows + 1, m), dtype=self.data.dtype) + data[:-1, :data_cols] = self.data + data[-1, min_index:max_index] = values + self.data = data + + def todia(self, copy=False): + if copy: + return self.copy() + else: + return self + + todia.__doc__ = _spbase.todia.__doc__ + + def transpose(self, axes=None, copy=False): + if axes is not None and axes != (1, 0): + raise ValueError("Sparse arrays/matrices do not support " + "an 'axes' parameter because swapping " + "dimensions is the only logical permutation.") + + num_rows, num_cols = self.shape + max_dim = max(self.shape) + + # flip diagonal offsets + offsets = -self.offsets + + # re-align the data matrix + r = np.arange(len(offsets), dtype=np.intc)[:, None] + c = np.arange(num_rows, dtype=np.intc) - (offsets % max_dim)[:, None] + pad_amount = max(0, max_dim-self.data.shape[1]) + data = np.hstack((self.data, np.zeros((self.data.shape[0], pad_amount), + dtype=self.data.dtype))) + data = data[r, c] + return self._dia_container((data, offsets), shape=( + num_cols, num_rows), copy=copy) + + transpose.__doc__ = _spbase.transpose.__doc__ + + def diagonal(self, k=0): + rows, cols = self.shape + if k <= -rows or k >= cols: + return np.empty(0, dtype=self.data.dtype) + idx, = np.nonzero(self.offsets == k) + first_col = max(0, k) + last_col = min(rows + k, cols) + result_size = last_col - first_col + if idx.size == 0: + return np.zeros(result_size, dtype=self.data.dtype) + result = self.data[idx[0], first_col:last_col] + padding = result_size - len(result) + if padding > 0: + result = np.pad(result, (0, padding), mode='constant') + return result + + diagonal.__doc__ = _spbase.diagonal.__doc__ + + def tocsc(self, copy=False): + if self.nnz == 0: + return self._csc_container(self.shape, dtype=self.dtype) + + num_rows, num_cols = self.shape + num_offsets, offset_len = self.data.shape + offset_inds = np.arange(offset_len) + + row = offset_inds - self.offsets[:,None] + mask = (row >= 0) + mask &= (row < num_rows) + mask &= (offset_inds < num_cols) + mask &= (self.data != 0) + + idx_dtype = self._get_index_dtype(maxval=max(self.shape)) + indptr = np.zeros(num_cols + 1, dtype=idx_dtype) + indptr[1:offset_len+1] = np.cumsum(mask.sum(axis=0)[:num_cols]) + if offset_len < num_cols: + indptr[offset_len+1:] = indptr[offset_len] + indices = row.T[mask.T].astype(idx_dtype, copy=False) + data = self.data.T[mask.T] + return self._csc_container((data, indices, indptr), shape=self.shape, + dtype=self.dtype) + + tocsc.__doc__ = _spbase.tocsc.__doc__ + + def tocoo(self, copy=False): + num_rows, num_cols = self.shape + num_offsets, offset_len = self.data.shape + offset_inds = np.arange(offset_len) + + row = offset_inds - self.offsets[:,None] + mask = (row >= 0) + mask &= (row < num_rows) + mask &= (offset_inds < num_cols) + mask &= (self.data != 0) + row = row[mask] + col = np.tile(offset_inds, num_offsets)[mask.ravel()] + idx_dtype = self._get_index_dtype( + arrays=(self.offsets,), maxval=max(self.shape) + ) + row = row.astype(idx_dtype, copy=False) + col = col.astype(idx_dtype, copy=False) + data = self.data[mask] + # Note: this cannot set has_canonical_format=True, because despite the + # lack of duplicates, we do not generate sorted indices. + return self._coo_container( + (data, (row, col)), shape=self.shape, dtype=self.dtype, copy=False + ) + + tocoo.__doc__ = _spbase.tocoo.__doc__ + + # needed by _data_matrix + def _with_data(self, data, copy=True): + """Returns a matrix with the same sparsity structure as self, + but with different data. By default the structure arrays are copied. + """ + if copy: + return self._dia_container( + (data, self.offsets.copy()), shape=self.shape + ) + else: + return self._dia_container( + (data, self.offsets), shape=self.shape + ) + + def resize(self, *shape): + shape = check_shape(shape) + M, N = shape + # we do not need to handle the case of expanding N + self.data = self.data[:, :N] + + if (M > self.shape[0] and + np.any(self.offsets + self.shape[0] < self.data.shape[1])): + # explicitly clear values that were previously hidden + mask = (self.offsets[:, None] + self.shape[0] <= + np.arange(self.data.shape[1])) + self.data[mask] = 0 + + self._shape = shape + + resize.__doc__ = _spbase.resize.__doc__ + + +def _invert_index(idx): + """Helper function to invert an index array.""" + inv = np.zeros_like(idx) + inv[idx] = np.arange(len(idx)) + return inv + + +def isspmatrix_dia(x): + """Is `x` of dia_matrix type? + + Parameters + ---------- + x + object to check for being a dia matrix + + Returns + ------- + bool + True if `x` is a dia matrix, False otherwise + + Examples + -------- + >>> from scipy.sparse import dia_array, dia_matrix, coo_matrix, isspmatrix_dia + >>> isspmatrix_dia(dia_matrix([[5]])) + True + >>> isspmatrix_dia(dia_array([[5]])) + False + >>> isspmatrix_dia(coo_matrix([[5]])) + False + """ + return isinstance(x, dia_matrix) + + +# This namespace class separates array from matrix with isinstance +class dia_array(_dia_base, sparray): + """ + Sparse array with DIAgonal storage. + + This can be instantiated in several ways: + dia_array(D) + where D is a 2-D ndarray + + dia_array(S) + with another sparse array or matrix S (equivalent to S.todia()) + + dia_array((M, N), [dtype]) + to construct an empty array with shape (M, N), + dtype is optional, defaulting to dtype='d'. + + dia_array((data, offsets), shape=(M, N)) + where the ``data[k,:]`` stores the diagonal entries for + diagonal ``offsets[k]`` (See example below) + + Attributes + ---------- + dtype : dtype + Data type of the array + shape : 2-tuple + Shape of the array + ndim : int + Number of dimensions (this is always 2) + nnz + size + data + DIA format data array of the array + offsets + DIA format offset array of the array + T + + Notes + ----- + + Sparse arrays can be used in arithmetic operations: they support + addition, subtraction, multiplication, division, and matrix power. + Sparse arrays with DIAgonal storage do not support slicing. + + Examples + -------- + + >>> import numpy as np + >>> from scipy.sparse import dia_array + >>> dia_array((3, 4), dtype=np.int8).toarray() + array([[0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0]], dtype=int8) + + >>> data = np.array([[1, 2, 3, 4]]).repeat(3, axis=0) + >>> offsets = np.array([0, -1, 2]) + >>> dia_array((data, offsets), shape=(4, 4)).toarray() + array([[1, 0, 3, 0], + [1, 2, 0, 4], + [0, 2, 3, 0], + [0, 0, 3, 4]]) + + >>> from scipy.sparse import dia_array + >>> n = 10 + >>> ex = np.ones(n) + >>> data = np.array([ex, 2 * ex, ex]) + >>> offsets = np.array([-1, 0, 1]) + >>> dia_array((data, offsets), shape=(n, n)).toarray() + array([[2., 1., 0., ..., 0., 0., 0.], + [1., 2., 1., ..., 0., 0., 0.], + [0., 1., 2., ..., 0., 0., 0.], + ..., + [0., 0., 0., ..., 2., 1., 0.], + [0., 0., 0., ..., 1., 2., 1.], + [0., 0., 0., ..., 0., 1., 2.]]) + """ + + +class dia_matrix(spmatrix, _dia_base): + """ + Sparse matrix with DIAgonal storage. + + This can be instantiated in several ways: + dia_matrix(D) + where D is a 2-D ndarray + + dia_matrix(S) + with another sparse array or matrix S (equivalent to S.todia()) + + dia_matrix((M, N), [dtype]) + to construct an empty matrix with shape (M, N), + dtype is optional, defaulting to dtype='d'. + + dia_matrix((data, offsets), shape=(M, N)) + where the ``data[k,:]`` stores the diagonal entries for + diagonal ``offsets[k]`` (See example below) + + Attributes + ---------- + dtype : dtype + Data type of the matrix + shape : 2-tuple + Shape of the matrix + ndim : int + Number of dimensions (this is always 2) + nnz + size + data + DIA format data array of the matrix + offsets + DIA format offset array of the matrix + T + + Notes + ----- + + Sparse matrices can be used in arithmetic operations: they support + addition, subtraction, multiplication, division, and matrix power. + Sparse matrices with DIAgonal storage do not support slicing. + + Examples + -------- + + >>> import numpy as np + >>> from scipy.sparse import dia_matrix + >>> dia_matrix((3, 4), dtype=np.int8).toarray() + array([[0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0]], dtype=int8) + + >>> data = np.array([[1, 2, 3, 4]]).repeat(3, axis=0) + >>> offsets = np.array([0, -1, 2]) + >>> dia_matrix((data, offsets), shape=(4, 4)).toarray() + array([[1, 0, 3, 0], + [1, 2, 0, 4], + [0, 2, 3, 0], + [0, 0, 3, 4]]) + + >>> from scipy.sparse import dia_matrix + >>> n = 10 + >>> ex = np.ones(n) + >>> data = np.array([ex, 2 * ex, ex]) + >>> offsets = np.array([-1, 0, 1]) + >>> dia_matrix((data, offsets), shape=(n, n)).toarray() + array([[2., 1., 0., ..., 0., 0., 0.], + [1., 2., 1., ..., 0., 0., 0.], + [0., 1., 2., ..., 0., 0., 0.], + ..., + [0., 0., 0., ..., 2., 1., 0.], + [0., 0., 0., ..., 1., 2., 1.], + [0., 0., 0., ..., 0., 1., 2.]]) + """ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_dok.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_dok.py new file mode 100644 index 0000000000000000000000000000000000000000..c9814a9e8d0b2d5a67185faae9311f4216cc7d13 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_dok.py @@ -0,0 +1,692 @@ +"""Dictionary Of Keys based matrix""" + +__docformat__ = "restructuredtext en" + +__all__ = ['dok_array', 'dok_matrix', 'isspmatrix_dok'] + +import itertools +from warnings import warn +import numpy as np + +from ._matrix import spmatrix +from ._base import _spbase, sparray, issparse +from ._index import IndexMixin +from ._sputils import (isdense, getdtype, isshape, isintlike, isscalarlike, + upcast, upcast_scalar, check_shape) + + +class _dok_base(_spbase, IndexMixin, dict): + _format = 'dok' + _allow_nd = (1, 2) + + def __init__(self, arg1, shape=None, dtype=None, copy=False, *, maxprint=None): + _spbase.__init__(self, arg1, maxprint=maxprint) + + if isinstance(arg1, tuple) and isshape(arg1, allow_nd=self._allow_nd): + self._shape = check_shape(arg1, allow_nd=self._allow_nd) + self._dict = {} + self.dtype = getdtype(dtype, default=float) + elif issparse(arg1): # Sparse ctor + if arg1.format == self.format: + arg1 = arg1.copy() if copy else arg1 + else: + arg1 = arg1.todok() + + if dtype is not None: + arg1 = arg1.astype(dtype, copy=False) + + self._dict = arg1._dict + self._shape = check_shape(arg1.shape, allow_nd=self._allow_nd) + self.dtype = getdtype(arg1.dtype) + else: # Dense ctor + try: + arg1 = np.asarray(arg1) + except Exception as e: + raise TypeError('Invalid input format.') from e + + if arg1.ndim > 2: + raise ValueError(f"DOK arrays don't yet support {arg1.ndim}D input.") + + if arg1.ndim == 1: + if dtype is not None: + arg1 = arg1.astype(dtype) + self._dict = {i: v for i, v in enumerate(arg1) if v != 0} + self.dtype = getdtype(arg1.dtype) + else: + d = self._coo_container(arg1, shape=shape, dtype=dtype).todok() + self._dict = d._dict + self.dtype = getdtype(d.dtype) + self._shape = check_shape(arg1.shape, allow_nd=self._allow_nd) + + def update(self, val): + # Prevent direct usage of update + raise NotImplementedError("Direct update to DOK sparse format is not allowed.") + + def _getnnz(self, axis=None): + if axis is not None: + raise NotImplementedError( + "_getnnz over an axis is not implemented for DOK format." + ) + return len(self._dict) + + def count_nonzero(self, axis=None): + if axis is not None: + raise NotImplementedError( + "count_nonzero over an axis is not implemented for DOK format." + ) + return sum(x != 0 for x in self.values()) + + _getnnz.__doc__ = _spbase._getnnz.__doc__ + count_nonzero.__doc__ = _spbase.count_nonzero.__doc__ + + def __len__(self): + return len(self._dict) + + def __contains__(self, key): + return key in self._dict + + def setdefault(self, key, default=None, /): + return self._dict.setdefault(key, default) + + def __delitem__(self, key, /): + del self._dict[key] + + def clear(self): + return self._dict.clear() + + def pop(self, /, *args): + return self._dict.pop(*args) + + def __reversed__(self): + raise TypeError("reversed is not defined for dok_array type") + + def __or__(self, other): + type_names = f"{type(self).__name__} and {type(other).__name__}" + raise TypeError(f"unsupported operand type for |: {type_names}") + + def __ror__(self, other): + type_names = f"{type(self).__name__} and {type(other).__name__}" + raise TypeError(f"unsupported operand type for |: {type_names}") + + def __ior__(self, other): + type_names = f"{type(self).__name__} and {type(other).__name__}" + raise TypeError(f"unsupported operand type for |: {type_names}") + + def popitem(self): + return self._dict.popitem() + + def items(self): + return self._dict.items() + + def keys(self): + return self._dict.keys() + + def values(self): + return self._dict.values() + + def get(self, key, default=0.0): + """This provides dict.get method functionality with type checking""" + if key in self._dict: + return self._dict[key] + if isintlike(key) and self.ndim == 1: + key = (key,) + if self.ndim != len(key): + raise IndexError(f'Index {key} length needs to match self.shape') + try: + for i in key: + assert isintlike(i) + except (AssertionError, TypeError, ValueError) as e: + raise IndexError('Index must be or consist of integers.') from e + key = tuple(i + M if i < 0 else i for i, M in zip(key, self.shape)) + if any(i < 0 or i >= M for i, M in zip(key, self.shape)): + raise IndexError('Index out of bounds.') + if self.ndim == 1: + key = key[0] + return self._dict.get(key, default) + + # 1D get methods + def _get_int(self, idx): + return self._dict.get(idx, self.dtype.type(0)) + + def _get_slice(self, idx): + i_range = range(*idx.indices(self.shape[0])) + return self._get_array(list(i_range)) + + def _get_array(self, idx): + idx = np.asarray(idx) + if idx.ndim == 0: + val = self._dict.get(int(idx), self.dtype.type(0)) + return np.array(val, stype=self.dtype) + new_dok = self._dok_container(idx.shape, dtype=self.dtype) + dok_vals = [self._dict.get(i, 0) for i in idx.ravel()] + if dok_vals: + if len(idx.shape) == 1: + for i, v in enumerate(dok_vals): + if v: + new_dok._dict[i] = v + else: + new_idx = np.unravel_index(np.arange(len(dok_vals)), idx.shape) + new_idx = new_idx[0] if len(new_idx) == 1 else zip(*new_idx) + for i, v in zip(new_idx, dok_vals, strict=True): + if v: + new_dok._dict[i] = v + return new_dok + + # 2D get methods + def _get_intXint(self, row, col): + return self._dict.get((row, col), self.dtype.type(0)) + + def _get_intXslice(self, row, col): + return self._get_sliceXslice(slice(row, row + 1), col) + + def _get_sliceXint(self, row, col): + return self._get_sliceXslice(row, slice(col, col + 1)) + + def _get_sliceXslice(self, row, col): + row_start, row_stop, row_step = row.indices(self.shape[0]) + col_start, col_stop, col_step = col.indices(self.shape[1]) + row_range = range(row_start, row_stop, row_step) + col_range = range(col_start, col_stop, col_step) + shape = (len(row_range), len(col_range)) + # Switch paths only when advantageous + # (count the iterations in the loops, adjust for complexity) + if len(self) >= 2 * shape[0] * shape[1]: + # O(nr*nc) path: loop over + return self._get_columnXarray(row_range, col_range) + # O(nnz) path: loop over entries of self + newdok = self._dok_container(shape, dtype=self.dtype) + for key in self.keys(): + i, ri = divmod(int(key[0]) - row_start, row_step) + if ri != 0 or i < 0 or i >= shape[0]: + continue + j, rj = divmod(int(key[1]) - col_start, col_step) + if rj != 0 or j < 0 or j >= shape[1]: + continue + newdok._dict[i, j] = self._dict[key] + return newdok + + def _get_intXarray(self, row, col): + return self._get_columnXarray([row], col.ravel()) + + def _get_arrayXint(self, row, col): + res = self._get_columnXarray(row.ravel(), [col]) + if row.ndim > 1: + return res.reshape(row.shape) + return res + + def _get_sliceXarray(self, row, col): + row = list(range(*row.indices(self.shape[0]))) + return self._get_columnXarray(row, col) + + def _get_arrayXslice(self, row, col): + col = list(range(*col.indices(self.shape[1]))) + return self._get_columnXarray(row, col) + + def _get_columnXarray(self, row, col): + # outer indexing + newdok = self._dok_container((len(row), len(col)), dtype=self.dtype) + + for i, r in enumerate(row): + for j, c in enumerate(col): + v = self._dict.get((r, c), 0) + if v: + newdok._dict[i, j] = v + return newdok + + def _get_arrayXarray(self, row, col): + # inner indexing + i, j = map(np.atleast_2d, np.broadcast_arrays(row, col)) + newdok = self._dok_container(i.shape, dtype=self.dtype) + + for key in itertools.product(range(i.shape[0]), range(i.shape[1])): + v = self._dict.get((i[key], j[key]), 0) + if v: + newdok._dict[key] = v + return newdok + + # 1D set methods + def _set_int(self, idx, x): + if x: + self._dict[idx] = x + elif idx in self._dict: + del self._dict[idx] + + def _set_array(self, idx, x): + idx_set = idx.ravel() + x_set = x.ravel() + if len(idx_set) != len(x_set): + if len(x_set) == 1: + x_set = np.full(len(idx_set), x_set[0], dtype=self.dtype) + else: + raise ValueError("Need len(index)==len(data) or len(data)==1") + for i, v in zip(idx_set, x_set): + if v: + self._dict[i] = v + elif i in self._dict: + del self._dict[i] + + # 2D set methods + def _set_intXint(self, row, col, x): + key = (row, col) + if x: + self._dict[key] = x + elif key in self._dict: + del self._dict[key] + + def _set_arrayXarray(self, row, col, x): + row = list(map(int, row.ravel())) + col = list(map(int, col.ravel())) + x = x.ravel() + self._dict.update(zip(zip(row, col), x)) + + for i in np.nonzero(x == 0)[0]: + key = (row[i], col[i]) + if self._dict[key] == 0: + # may have been superseded by later update + del self._dict[key] + + def __add__(self, other): + if isscalarlike(other): + res_dtype = upcast_scalar(self.dtype, other) + new = self._dok_container(self.shape, dtype=res_dtype) + # Add this scalar to each element. + for key in itertools.product(*[range(d) for d in self.shape]): + aij = self._dict.get(key, 0) + other + if aij: + new[key] = aij + elif issparse(other): + if other.shape != self.shape: + raise ValueError("Matrix dimensions are not equal.") + res_dtype = upcast(self.dtype, other.dtype) + new = self._dok_container(self.shape, dtype=res_dtype) + new._dict = self._dict.copy() + if other.format == "dok": + o_items = other.items() + else: + other = other.tocoo() + if self.ndim == 1: + o_items = zip(other.coords[0], other.data) + else: + o_items = zip(zip(*other.coords), other.data) + with np.errstate(over='ignore'): + new._dict.update((k, new[k] + v) for k, v in o_items) + elif isdense(other): + new = self.todense() + other + else: + return NotImplemented + return new + + def __radd__(self, other): + return self + other # addition is commutative + + def __neg__(self): + if self.dtype.kind == 'b': + raise NotImplementedError( + 'Negating a sparse boolean matrix is not supported.' + ) + new = self._dok_container(self.shape, dtype=self.dtype) + new._dict.update((k, -v) for k, v in self.items()) + return new + + def _mul_scalar(self, other): + res_dtype = upcast_scalar(self.dtype, other) + # Multiply this scalar by every element. + new = self._dok_container(self.shape, dtype=res_dtype) + new._dict.update(((k, v * other) for k, v in self.items())) + return new + + def _matmul_vector(self, other): + res_dtype = upcast(self.dtype, other.dtype) + + # vector @ vector + if self.ndim == 1: + if issparse(other): + if other.format == "dok": + keys = self.keys() & other.keys() + else: + keys = self.keys() & other.tocoo().coords[0] + return res_dtype(sum(self._dict[k] * other._dict[k] for k in keys)) + elif isdense(other): + return res_dtype(sum(other[k] * v for k, v in self.items())) + else: + return NotImplemented + + # matrix @ vector + result = np.zeros(self.shape[0], dtype=res_dtype) + for (i, j), v in self.items(): + result[i] += v * other[j] + return result + + def _matmul_multivector(self, other): + result_dtype = upcast(self.dtype, other.dtype) + # vector @ multivector + if self.ndim == 1: + # works for other 1d or 2d + return sum(v * other[j] for j, v in self._dict.items()) + + # matrix @ multivector + M = self.shape[0] + new_shape = (M,) if other.ndim == 1 else (M, other.shape[1]) + result = np.zeros(new_shape, dtype=result_dtype) + for (i, j), v in self.items(): + result[i] += v * other[j] + return result + + def __imul__(self, other): + if isscalarlike(other): + self._dict.update((k, v * other) for k, v in self.items()) + return self + return NotImplemented + + def __truediv__(self, other): + if isscalarlike(other): + res_dtype = upcast_scalar(self.dtype, other) + new = self._dok_container(self.shape, dtype=res_dtype) + new._dict.update(((k, v / other) for k, v in self.items())) + return new + return self.tocsr() / other + + def __itruediv__(self, other): + if isscalarlike(other): + self._dict.update((k, v / other) for k, v in self.items()) + return self + return NotImplemented + + def __reduce__(self): + # this approach is necessary because __setstate__ is called after + # __setitem__ upon unpickling and since __init__ is not called there + # is no shape attribute hence it is not possible to unpickle it. + return dict.__reduce__(self) + + def diagonal(self, k=0): + if self.ndim == 2: + return super().diagonal(k) + raise ValueError("diagonal requires two dimensions") + + def transpose(self, axes=None, copy=False): + if self.ndim == 1: + return self.copy() + + if axes is not None and axes != (1, 0): + raise ValueError( + "Sparse arrays/matrices do not support " + "an 'axes' parameter because swapping " + "dimensions is the only logical permutation." + ) + + M, N = self.shape + new = self._dok_container((N, M), dtype=self.dtype, copy=copy) + new._dict.update((((right, left), val) for (left, right), val in self.items())) + return new + + transpose.__doc__ = _spbase.transpose.__doc__ + + def conjtransp(self): + """DEPRECATED: Return the conjugate transpose. + + .. deprecated:: 1.14.0 + + `conjtransp` is deprecated and will be removed in v1.16.0. + Use ``.T.conj()`` instead. + """ + msg = ("`conjtransp` is deprecated and will be removed in v1.16.0. " + "Use `.T.conj()` instead.") + warn(msg, DeprecationWarning, stacklevel=2) + + if self.ndim == 1: + new = self.tocoo() + new.data = new.data.conjugate() + return new + + M, N = self.shape + new = self._dok_container((N, M), dtype=self.dtype) + new._dict = {(right, left): np.conj(val) for (left, right), val in self.items()} + return new + + def copy(self): + new = self._dok_container(self.shape, dtype=self.dtype) + new._dict.update(self._dict) + return new + + copy.__doc__ = _spbase.copy.__doc__ + + @classmethod + def fromkeys(cls, iterable, value=1, /): + tmp = dict.fromkeys(iterable, value) + if isinstance(next(iter(tmp)), tuple): + shape = tuple(max(idx) + 1 for idx in zip(*tmp)) + else: + shape = (max(tmp) + 1,) + result = cls(shape, dtype=type(value)) + result._dict = tmp + return result + + def tocoo(self, copy=False): + nnz = self.nnz + if nnz == 0: + return self._coo_container(self.shape, dtype=self.dtype) + + idx_dtype = self._get_index_dtype(maxval=max(self.shape)) + data = np.fromiter(self.values(), dtype=self.dtype, count=nnz) + # handle 1d keys specially b/c not a tuple + inds = zip(*self.keys()) if self.ndim > 1 else (self.keys(),) + coords = tuple(np.fromiter(ix, dtype=idx_dtype, count=nnz) for ix in inds) + A = self._coo_container((data, coords), shape=self.shape, dtype=self.dtype) + A.has_canonical_format = True + return A + + tocoo.__doc__ = _spbase.tocoo.__doc__ + + def todok(self, copy=False): + if copy: + return self.copy() + return self + + todok.__doc__ = _spbase.todok.__doc__ + + def tocsc(self, copy=False): + if self.ndim == 1: + raise NotImplementedError("tocsr() not valid for 1d sparse array") + return self.tocoo(copy=False).tocsc(copy=copy) + + tocsc.__doc__ = _spbase.tocsc.__doc__ + + def resize(self, *shape): + shape = check_shape(shape, allow_nd=self._allow_nd) + if len(shape) != len(self.shape): + # TODO implement resize across dimensions + raise NotImplementedError + + if self.ndim == 1: + newN = shape[-1] + for i in list(self._dict): + if i >= newN: + del self._dict[i] + self._shape = shape + return + + newM, newN = shape + M, N = self.shape + if newM < M or newN < N: + # Remove all elements outside new dimensions + for i, j in list(self.keys()): + if i >= newM or j >= newN: + del self._dict[i, j] + self._shape = shape + + resize.__doc__ = _spbase.resize.__doc__ + + # Added for 1d to avoid `tocsr` from _base.py + def astype(self, dtype, casting='unsafe', copy=True): + dtype = np.dtype(dtype) + if self.dtype != dtype: + result = self._dok_container(self.shape, dtype=dtype) + data = np.array(list(self._dict.values()), dtype=dtype) + result._dict = dict(zip(self._dict, data)) + return result + elif copy: + return self.copy() + return self + + +def isspmatrix_dok(x): + """Is `x` of dok_array type? + + Parameters + ---------- + x + object to check for being a dok matrix + + Returns + ------- + bool + True if `x` is a dok matrix, False otherwise + + Examples + -------- + >>> from scipy.sparse import dok_array, dok_matrix, coo_matrix, isspmatrix_dok + >>> isspmatrix_dok(dok_matrix([[5]])) + True + >>> isspmatrix_dok(dok_array([[5]])) + False + >>> isspmatrix_dok(coo_matrix([[5]])) + False + """ + return isinstance(x, dok_matrix) + + +# This namespace class separates array from matrix with isinstance +class dok_array(_dok_base, sparray): + """ + Dictionary Of Keys based sparse array. + + This is an efficient structure for constructing sparse + arrays incrementally. + + This can be instantiated in several ways: + dok_array(D) + where D is a 2-D ndarray + + dok_array(S) + with another sparse array or matrix S (equivalent to S.todok()) + + dok_array((M,N), [dtype]) + create the array with initial shape (M,N) + dtype is optional, defaulting to dtype='d' + + Attributes + ---------- + dtype : dtype + Data type of the array + shape : 2-tuple + Shape of the array + ndim : int + Number of dimensions (this is always 2) + nnz + Number of nonzero elements + size + T + + Notes + ----- + + Sparse arrays can be used in arithmetic operations: they support + addition, subtraction, multiplication, division, and matrix power. + + - Allows for efficient O(1) access of individual elements. + - Duplicates are not allowed. + - Can be efficiently converted to a coo_array once constructed. + + Examples + -------- + >>> import numpy as np + >>> from scipy.sparse import dok_array + >>> S = dok_array((5, 5), dtype=np.float32) + >>> for i in range(5): + ... for j in range(5): + ... S[i, j] = i + j # Update element + + """ + + +class dok_matrix(spmatrix, _dok_base): + """ + Dictionary Of Keys based sparse matrix. + + This is an efficient structure for constructing sparse + matrices incrementally. + + This can be instantiated in several ways: + dok_matrix(D) + where D is a 2-D ndarray + + dok_matrix(S) + with another sparse array or matrix S (equivalent to S.todok()) + + dok_matrix((M,N), [dtype]) + create the matrix with initial shape (M,N) + dtype is optional, defaulting to dtype='d' + + Attributes + ---------- + dtype : dtype + Data type of the matrix + shape : 2-tuple + Shape of the matrix + ndim : int + Number of dimensions (this is always 2) + nnz + Number of nonzero elements + size + T + + Notes + ----- + + Sparse matrices can be used in arithmetic operations: they support + addition, subtraction, multiplication, division, and matrix power. + + - Allows for efficient O(1) access of individual elements. + - Duplicates are not allowed. + - Can be efficiently converted to a coo_matrix once constructed. + + Examples + -------- + >>> import numpy as np + >>> from scipy.sparse import dok_matrix + >>> S = dok_matrix((5, 5), dtype=np.float32) + >>> for i in range(5): + ... for j in range(5): + ... S[i, j] = i + j # Update element + + """ + + def set_shape(self, shape): + new_matrix = self.reshape(shape, copy=False).asformat(self.format) + self.__dict__ = new_matrix.__dict__ + + def get_shape(self): + """Get shape of a sparse matrix.""" + return self._shape + + shape = property(fget=get_shape, fset=set_shape) + + def __reversed__(self): + return self._dict.__reversed__() + + def __or__(self, other): + if isinstance(other, _dok_base): + return self._dict | other._dict + return self._dict | other + + def __ror__(self, other): + if isinstance(other, _dok_base): + return self._dict | other._dict + return self._dict | other + + def __ior__(self, other): + if isinstance(other, _dok_base): + self._dict |= other._dict + else: + self._dict |= other + return self diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_extract.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_extract.py new file mode 100644 index 0000000000000000000000000000000000000000..0ee1a88575926efa1d5a921edbd3d88696157dc2 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_extract.py @@ -0,0 +1,178 @@ +"""Functions to extract parts of sparse matrices +""" + +__docformat__ = "restructuredtext en" + +__all__ = ['find', 'tril', 'triu'] + + +from ._coo import coo_matrix, coo_array +from ._base import sparray + + +def find(A): + """Return the indices and values of the nonzero elements of a matrix + + Parameters + ---------- + A : dense or sparse array or matrix + Matrix whose nonzero elements are desired. + + Returns + ------- + (I,J,V) : tuple of arrays + I,J, and V contain the row indices, column indices, and values + of the nonzero entries. + + + Examples + -------- + >>> from scipy.sparse import csr_array, find + >>> A = csr_array([[7.0, 8.0, 0],[0, 0, 9.0]]) + >>> find(A) + (array([0, 0, 1], dtype=int32), + array([0, 1, 2], dtype=int32), + array([ 7., 8., 9.])) + + """ + + A = coo_array(A, copy=True) + A.sum_duplicates() + # remove explicit zeros + nz_mask = A.data != 0 + return A.row[nz_mask], A.col[nz_mask], A.data[nz_mask] + + +def tril(A, k=0, format=None): + """Return the lower triangular portion of a sparse array or matrix + + Returns the elements on or below the k-th diagonal of A. + - k = 0 corresponds to the main diagonal + - k > 0 is above the main diagonal + - k < 0 is below the main diagonal + + Parameters + ---------- + A : dense or sparse array or matrix + Matrix whose lower trianglar portion is desired. + k : integer : optional + The top-most diagonal of the lower triangle. + format : string + Sparse format of the result, e.g. format="csr", etc. + + Returns + ------- + L : sparse matrix + Lower triangular portion of A in sparse format. + + See Also + -------- + triu : upper triangle in sparse format + + Examples + -------- + >>> from scipy.sparse import csr_array, tril + >>> A = csr_array([[1, 2, 0, 0, 3], [4, 5, 0, 6, 7], [0, 0, 8, 9, 0]], + ... dtype='int32') + >>> A.toarray() + array([[1, 2, 0, 0, 3], + [4, 5, 0, 6, 7], + [0, 0, 8, 9, 0]], dtype=int32) + >>> tril(A).toarray() + array([[1, 0, 0, 0, 0], + [4, 5, 0, 0, 0], + [0, 0, 8, 0, 0]], dtype=int32) + >>> tril(A).nnz + 4 + >>> tril(A, k=1).toarray() + array([[1, 2, 0, 0, 0], + [4, 5, 0, 0, 0], + [0, 0, 8, 9, 0]], dtype=int32) + >>> tril(A, k=-1).toarray() + array([[0, 0, 0, 0, 0], + [4, 0, 0, 0, 0], + [0, 0, 0, 0, 0]], dtype=int32) + >>> tril(A, format='csc') + + + """ + coo_sparse = coo_array if isinstance(A, sparray) else coo_matrix + + # convert to COOrdinate format where things are easy + A = coo_sparse(A, copy=False) + mask = A.row + k >= A.col + + row = A.row[mask] + col = A.col[mask] + data = A.data[mask] + new_coo = coo_sparse((data, (row, col)), shape=A.shape, dtype=A.dtype) + return new_coo.asformat(format) + + +def triu(A, k=0, format=None): + """Return the upper triangular portion of a sparse array or matrix + + Returns the elements on or above the k-th diagonal of A. + - k = 0 corresponds to the main diagonal + - k > 0 is above the main diagonal + - k < 0 is below the main diagonal + + Parameters + ---------- + A : dense or sparse array or matrix + Matrix whose upper trianglar portion is desired. + k : integer : optional + The bottom-most diagonal of the upper triangle. + format : string + Sparse format of the result, e.g. format="csr", etc. + + Returns + ------- + L : sparse array or matrix + Upper triangular portion of A in sparse format. + Sparse array if A is a sparse array, otherwise matrix. + + See Also + -------- + tril : lower triangle in sparse format + + Examples + -------- + >>> from scipy.sparse import csr_array, triu + >>> A = csr_array([[1, 2, 0, 0, 3], [4, 5, 0, 6, 7], [0, 0, 8, 9, 0]], + ... dtype='int32') + >>> A.toarray() + array([[1, 2, 0, 0, 3], + [4, 5, 0, 6, 7], + [0, 0, 8, 9, 0]], dtype=int32) + >>> triu(A).toarray() + array([[1, 2, 0, 0, 3], + [0, 5, 0, 6, 7], + [0, 0, 8, 9, 0]], dtype=int32) + >>> triu(A).nnz + 8 + >>> triu(A, k=1).toarray() + array([[0, 2, 0, 0, 3], + [0, 0, 0, 6, 7], + [0, 0, 0, 9, 0]], dtype=int32) + >>> triu(A, k=-1).toarray() + array([[1, 2, 0, 0, 3], + [4, 5, 0, 6, 7], + [0, 0, 8, 9, 0]], dtype=int32) + >>> triu(A, format='csc') + + + """ + coo_sparse = coo_array if isinstance(A, sparray) else coo_matrix + + # convert to COOrdinate format where things are easy + A = coo_sparse(A, copy=False) + mask = A.row + k <= A.col + + row = A.row[mask] + col = A.col[mask] + data = A.data[mask] + new_coo = coo_sparse((data, (row, col)), shape=A.shape, dtype=A.dtype) + return new_coo.asformat(format) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_index.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_index.py new file mode 100644 index 0000000000000000000000000000000000000000..451df8b242c73b35036878feaf1f7ad302dc1f91 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_index.py @@ -0,0 +1,444 @@ +"""Indexing mixin for sparse array/matrix classes. +""" +import numpy as np +from ._sputils import isintlike +from ._base import sparray, issparse + +INT_TYPES = (int, np.integer) + + +def _broadcast_arrays(a, b): + """ + Same as np.broadcast_arrays(a, b) but old writeability rules. + + NumPy >= 1.17.0 transitions broadcast_arrays to return + read-only arrays. Set writeability explicitly to avoid warnings. + Retain the old writeability rules, as our Cython code assumes + the old behavior. + """ + x, y = np.broadcast_arrays(a, b) + x.flags.writeable = a.flags.writeable + y.flags.writeable = b.flags.writeable + return x, y + + +class IndexMixin: + """ + This class provides common dispatching and validation logic for indexing. + """ + def __getitem__(self, key): + index, new_shape = self._validate_indices(key) + + # 1D array + if len(index) == 1: + idx = index[0] + if isinstance(idx, np.ndarray): + if idx.shape == (): + idx = idx.item() + if isinstance(idx, INT_TYPES): + res = self._get_int(idx) + elif isinstance(idx, slice): + res = self._get_slice(idx) + else: # assume array idx + res = self._get_array(idx) + + # package the result and return + if not isinstance(self, sparray): + return res + # handle np.newaxis in idx when result would otherwise be a scalar + if res.shape == () and new_shape != (): + if len(new_shape) == 1: + return self.__class__([res], shape=new_shape, dtype=self.dtype) + if len(new_shape) == 2: + return self.__class__([[res]], shape=new_shape, dtype=self.dtype) + return res.reshape(new_shape) + + # 2D array + row, col = index + + # Dispatch to specialized methods. + if isinstance(row, INT_TYPES): + if isinstance(col, INT_TYPES): + res = self._get_intXint(row, col) + elif isinstance(col, slice): + res = self._get_intXslice(row, col) + elif col.ndim == 1: + res = self._get_intXarray(row, col) + elif col.ndim == 2: + res = self._get_intXarray(row, col) + else: + raise IndexError('index results in >2 dimensions') + elif isinstance(row, slice): + if isinstance(col, INT_TYPES): + res = self._get_sliceXint(row, col) + elif isinstance(col, slice): + if row == slice(None) and row == col: + res = self.copy() + else: + res = self._get_sliceXslice(row, col) + elif col.ndim == 1: + res = self._get_sliceXarray(row, col) + else: + raise IndexError('index results in >2 dimensions') + else: + if isinstance(col, INT_TYPES): + res = self._get_arrayXint(row, col) + elif isinstance(col, slice): + res = self._get_arrayXslice(row, col) + # arrayXarray preprocess + elif (row.ndim == 2 and row.shape[1] == 1 + and (col.ndim == 1 or col.shape[0] == 1)): + # outer indexing + res = self._get_columnXarray(row[:, 0], col.ravel()) + else: + # inner indexing + row, col = _broadcast_arrays(row, col) + if row.shape != col.shape: + raise IndexError('number of row and column indices differ') + if row.size == 0: + res = self.__class__(np.atleast_2d(row).shape, dtype=self.dtype) + else: + res = self._get_arrayXarray(row, col) + + # handle spmatrix (must be 2d, dont let 1d new_shape start reshape) + if not isinstance(self, sparray): + if new_shape == () or (len(new_shape) == 1 and res.ndim != 0): + # res handles cases not inflated by None + return res + if len(new_shape) == 1: + # shape inflated to 1D by None in index. Make 2D + new_shape = (1,) + new_shape + # reshape if needed (when None changes shape, e.g. A[1,:,None]) + return res if new_shape == res.shape else res.reshape(new_shape) + + # package the result and return + if res.shape != new_shape: + # handle formats that support indexing but not 1D (lil for now) + if self.format == "lil" and len(new_shape) != 2: + if res.shape == (): + return self._coo_container([res], shape = new_shape) + return res.tocoo().reshape(new_shape) + return res.reshape(new_shape) + return res + + def __setitem__(self, key, x): + index, _ = self._validate_indices(key) + + # 1D array + if len(index) == 1: + idx = index[0] + + if issparse(x): + x = x.toarray() + else: + x = np.asarray(x, dtype=self.dtype) + + if isinstance(idx, INT_TYPES): + if x.size != 1: + raise ValueError('Trying to assign a sequence to an item') + self._set_int(idx, x.flat[0]) + return + + if isinstance(idx, slice): + # check for simple case of slice that gives 1 item + # Note: Python `range` does not use lots of memory + idx_range = range(*idx.indices(self.shape[0])) + N = len(idx_range) + if N == 1 and x.size == 1: + self._set_int(idx_range[0], x.flat[0]) + return + idx = np.arange(*idx.indices(self.shape[0])) + idx_shape = idx.shape + else: + idx_shape = idx.squeeze().shape + # broadcast scalar to full 1d + if x.squeeze().shape != idx_shape: + x = np.broadcast_to(x, idx.shape) + if x.size != 0: + self._set_array(idx, x) + return + + # 2D array + row, col = index + + if isinstance(row, INT_TYPES) and isinstance(col, INT_TYPES): + x = np.asarray(x, dtype=self.dtype) + if x.size != 1: + raise ValueError('Trying to assign a sequence to an item') + self._set_intXint(row, col, x.flat[0]) + return + + if isinstance(row, slice): + row = np.arange(*row.indices(self.shape[0]))[:, None] + else: + row = np.atleast_1d(row) + + if isinstance(col, slice): + col = np.arange(*col.indices(self.shape[1]))[None, :] + if row.ndim == 1: + row = row[:, None] + else: + col = np.atleast_1d(col) + + i, j = _broadcast_arrays(row, col) + if i.shape != j.shape: + raise IndexError('number of row and column indices differ') + + if issparse(x): + if 0 in x.shape: + return + if i.ndim == 1: + # Inner indexing, so treat them like row vectors. + i = i[None] + j = j[None] + x = x.tocoo(copy=False).reshape(x._shape_as_2d, copy=True) + broadcast_row = x.shape[0] == 1 and i.shape[0] != 1 + broadcast_col = x.shape[1] == 1 and i.shape[1] != 1 + if not ((broadcast_row or x.shape[0] == i.shape[0]) and + (broadcast_col or x.shape[1] == i.shape[1])): + raise ValueError('shape mismatch in assignment') + x.sum_duplicates() + self._set_arrayXarray_sparse(i, j, x) + else: + # Make x and i into the same shape + x = np.asarray(x, dtype=self.dtype) + if x.squeeze().shape != i.squeeze().shape: + x = np.broadcast_to(x, i.shape) + if x.size == 0: + return + x = x.reshape(i.shape) + self._set_arrayXarray(i, j, x) + + def _validate_indices(self, key): + """Returns two tuples: (index tuple, requested shape tuple)""" + # single ellipsis + if key is Ellipsis: + return (slice(None),) * self.ndim, self.shape + + if not isinstance(key, tuple): + key = [key] + + ellps_pos = None + index_1st = [] + prelim_ndim = 0 + for i, idx in enumerate(key): + if idx is Ellipsis: + if ellps_pos is not None: + raise IndexError('an index can only have a single ellipsis') + ellps_pos = i + elif idx is None: + index_1st.append(idx) + elif isinstance(idx, slice) or isintlike(idx): + index_1st.append(idx) + prelim_ndim += 1 + elif (ix := _compatible_boolean_index(idx, self.ndim)) is not None: + index_1st.append(ix) + prelim_ndim += ix.ndim + elif issparse(idx): + # TODO: make sparse matrix indexing work for sparray + raise IndexError( + 'Indexing with sparse matrices is not supported ' + 'except boolean indexing where matrix and index ' + 'are equal shapes.') + else: # dense array + index_1st.append(np.asarray(idx)) + prelim_ndim += 1 + ellip_slices = (self.ndim - prelim_ndim) * [slice(None)] + if ellip_slices: + if ellps_pos is None: + index_1st.extend(ellip_slices) + else: + index_1st = index_1st[:ellps_pos] + ellip_slices + index_1st[ellps_pos:] + + # second pass (have processed ellipsis and preprocessed arrays) + idx_shape = [] + index_ndim = 0 + index = [] + array_indices = [] + for i, idx in enumerate(index_1st): + if idx is None: + idx_shape.append(1) + elif isinstance(idx, slice): + index.append(idx) + Ms = self._shape[index_ndim] + len_slice = len(range(*idx.indices(Ms))) + idx_shape.append(len_slice) + index_ndim += 1 + elif isintlike(idx): + N = self._shape[index_ndim] + if not (-N <= idx < N): + raise IndexError(f'index ({idx}) out of range') + idx = int(idx + N if idx < 0 else idx) + index.append(idx) + index_ndim += 1 + # bool array (checked in first pass) + elif idx.dtype.kind == 'b': + ix = idx + tmp_ndim = index_ndim + ix.ndim + mid_shape = self._shape[index_ndim:tmp_ndim] + if ix.shape != mid_shape: + raise IndexError( + f"bool index {i} has shape {mid_shape} instead of {ix.shape}" + ) + index.extend(ix.nonzero()) + array_indices.extend(range(index_ndim, tmp_ndim)) + index_ndim = tmp_ndim + else: # dense array + N = self._shape[index_ndim] + idx = self._asindices(idx, N) + index.append(idx) + array_indices.append(index_ndim) + index_ndim += 1 + if index_ndim > self.ndim: + raise IndexError( + f'invalid index ndim. Array is {self.ndim}D. Index needs {index_ndim}D' + ) + if len(array_indices) > 1: + idx_arrays = _broadcast_arrays(*(index[i] for i in array_indices)) + if any(idx_arrays[0].shape != ix.shape for ix in idx_arrays[1:]): + shapes = " ".join(str(ix.shape) for ix in idx_arrays) + msg = (f'shape mismatch: indexing arrays could not be broadcast ' + f'together with shapes {shapes}') + raise IndexError(msg) + # TODO: handle this for nD (adjacent arrays stay, separated move to start) + idx_shape = list(idx_arrays[0].shape) + idx_shape + elif len(array_indices) == 1: + arr_index = array_indices[0] + arr_shape = list(index[arr_index].shape) + idx_shape = idx_shape[:arr_index] + arr_shape + idx_shape[arr_index:] + if (ndim := len(idx_shape)) > 2: + raise IndexError(f'Only 1D or 2D arrays allowed. Index makes {ndim}D') + return tuple(index), tuple(idx_shape) + + def _asindices(self, idx, length): + """Convert `idx` to a valid index for an axis with a given length. + + Subclasses that need special validation can override this method. + """ + try: + x = np.asarray(idx) + except (ValueError, TypeError, MemoryError) as e: + raise IndexError('invalid index') from e + + if x.ndim not in (1, 2): + raise IndexError('Index dimension must be 1 or 2') + + if x.size == 0: + return x + + # Check bounds + max_indx = x.max() + if max_indx >= length: + raise IndexError('index (%d) out of range' % max_indx) + + min_indx = x.min() + if min_indx < 0: + if min_indx < -length: + raise IndexError('index (%d) out of range' % min_indx) + if x is idx or not x.flags.owndata: + x = x.copy() + x[x < 0] += length + return x + + def _getrow(self, i): + """Return a copy of row i of the matrix, as a (1 x n) row vector. + """ + M, N = self.shape + i = int(i) + if i < -M or i >= M: + raise IndexError('index (%d) out of range' % i) + if i < 0: + i += M + return self._get_intXslice(i, slice(None)) + + def _getcol(self, i): + """Return a copy of column i of the matrix, as a (m x 1) column vector. + """ + M, N = self.shape + i = int(i) + if i < -N or i >= N: + raise IndexError('index (%d) out of range' % i) + if i < 0: + i += N + return self._get_sliceXint(slice(None), i) + + def _get_int(self, idx): + raise NotImplementedError() + + def _get_slice(self, idx): + raise NotImplementedError() + + def _get_array(self, idx): + raise NotImplementedError() + + def _get_intXint(self, row, col): + raise NotImplementedError() + + def _get_intXarray(self, row, col): + raise NotImplementedError() + + def _get_intXslice(self, row, col): + raise NotImplementedError() + + def _get_sliceXint(self, row, col): + raise NotImplementedError() + + def _get_sliceXslice(self, row, col): + raise NotImplementedError() + + def _get_sliceXarray(self, row, col): + raise NotImplementedError() + + def _get_arrayXint(self, row, col): + raise NotImplementedError() + + def _get_arrayXslice(self, row, col): + raise NotImplementedError() + + def _get_columnXarray(self, row, col): + raise NotImplementedError() + + def _get_arrayXarray(self, row, col): + raise NotImplementedError() + + def _set_int(self, idx, x): + raise NotImplementedError() + + def _set_array(self, idx, x): + raise NotImplementedError() + + def _set_intXint(self, row, col, x): + raise NotImplementedError() + + def _set_arrayXarray(self, row, col, x): + raise NotImplementedError() + + def _set_arrayXarray_sparse(self, row, col, x): + # Fall back to densifying x + x = np.asarray(x.toarray(), dtype=self.dtype) + x, _ = _broadcast_arrays(x, row) + self._set_arrayXarray(row, col, x) + + +def _compatible_boolean_index(idx, desired_ndim): + """Check for boolean array or array-like. peek before asarray for array-like""" + # use attribute ndim to indicate a compatible array and check dtype + # if not, look at 1st element as quick rejection of bool, else slower asanyarray + if not hasattr(idx, 'ndim'): + # is first element boolean? + try: + ix = next(iter(idx), None) + for _ in range(desired_ndim): + if isinstance(ix, bool): + break + ix = next(iter(ix), None) + else: + return None + except TypeError: + return None + # since first is boolean, construct array and check all elements + idx = np.asanyarray(idx) + + if idx.dtype.kind == 'b': + return idx + return None diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_lil.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_lil.py new file mode 100644 index 0000000000000000000000000000000000000000..479472445cd8bdc36374b3d8bc18e6f9df123306 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_lil.py @@ -0,0 +1,632 @@ +"""List of Lists sparse matrix class +""" + +__docformat__ = "restructuredtext en" + +__all__ = ['lil_array', 'lil_matrix', 'isspmatrix_lil'] + +from bisect import bisect_left + +import numpy as np + +from ._matrix import spmatrix +from ._base import _spbase, sparray, issparse +from ._index import IndexMixin, INT_TYPES, _broadcast_arrays +from ._sputils import (getdtype, isshape, isscalarlike, upcast_scalar, + check_shape, check_reshape_kwargs) +from . import _csparsetools + + +class _lil_base(_spbase, IndexMixin): + _format = 'lil' + + def __init__(self, arg1, shape=None, dtype=None, copy=False, *, maxprint=None): + _spbase.__init__(self, arg1, maxprint=maxprint) + self.dtype = getdtype(dtype, arg1, default=float) + + # First get the shape + if issparse(arg1): + if arg1.format == "lil" and copy: + A = arg1.copy() + else: + A = arg1.tolil() + + if dtype is not None: + newdtype = getdtype(dtype) + A = A.astype(newdtype, copy=False) + + self._shape = check_shape(A.shape) + self.dtype = A.dtype + self.rows = A.rows + self.data = A.data + elif isinstance(arg1,tuple): + if isshape(arg1): + if shape is not None: + raise ValueError('invalid use of shape parameter') + M, N = arg1 + self._shape = check_shape((M, N)) + self.rows = np.empty((M,), dtype=object) + self.data = np.empty((M,), dtype=object) + for i in range(M): + self.rows[i] = [] + self.data[i] = [] + else: + raise TypeError('unrecognized lil_array constructor usage') + else: + # assume A is dense + try: + A = self._ascontainer(arg1) + except TypeError as e: + raise TypeError('unsupported matrix type') from e + if isinstance(self, sparray) and A.ndim != 2: + raise ValueError(f"LIL arrays don't support {A.ndim}D input. Use 2D") + A = self._csr_container(A, dtype=dtype).tolil() + + self._shape = check_shape(A.shape) + self.dtype = getdtype(A.dtype) + self.rows = A.rows + self.data = A.data + + def __iadd__(self,other): + self[:,:] = self + other + return self + + def __isub__(self,other): + self[:,:] = self - other + return self + + def __imul__(self,other): + if isscalarlike(other): + self[:,:] = self * other + return self + else: + return NotImplemented + + def __itruediv__(self,other): + if isscalarlike(other): + self[:,:] = self / other + return self + else: + return NotImplemented + + # Whenever the dimensions change, empty lists should be created for each + # row + + def _getnnz(self, axis=None): + if axis is None: + return sum([len(rowvals) for rowvals in self.data]) + if axis < 0: + axis += 2 + if axis == 0: + out = np.zeros(self.shape[1], dtype=np.intp) + for row in self.rows: + out[row] += 1 + return out + elif axis == 1: + return np.array([len(rowvals) for rowvals in self.data], dtype=np.intp) + else: + raise ValueError('axis out of bounds') + + _getnnz.__doc__ = _spbase._getnnz.__doc__ + + def count_nonzero(self, axis=None): + if axis is None: + return sum(np.count_nonzero(rowvals) for rowvals in self.data) + + if axis < 0: + axis += 2 + if axis == 0: + out = np.zeros(self.shape[1], dtype=np.intp) + for row, data in zip(self.rows, self.data): + mask = [c for c, d in zip(row, data) if d != 0] + out[mask] += 1 + return out + elif axis == 1: + return np.array( + [np.count_nonzero(rowvals) for rowvals in self.data], dtype=np.intp, + ) + else: + raise ValueError('axis out of bounds') + + count_nonzero.__doc__ = _spbase.count_nonzero.__doc__ + + def getrowview(self, i): + """Returns a view of the 'i'th row (without copying). + """ + new = self._lil_container((1, self.shape[1]), dtype=self.dtype) + new.rows[0] = self.rows[i] + new.data[0] = self.data[i] + return new + + def getrow(self, i): + """Returns a copy of the 'i'th row. + """ + M, N = self.shape + if i < 0: + i += M + if i < 0 or i >= M: + raise IndexError('row index out of bounds') + new = self._lil_container((1, N), dtype=self.dtype) + new.rows[0] = self.rows[i][:] + new.data[0] = self.data[i][:] + return new + + def __getitem__(self, key): + # Fast path for simple (int, int) indexing. + if (isinstance(key, tuple) and len(key) == 2 and + isinstance(key[0], INT_TYPES) and + isinstance(key[1], INT_TYPES)): + # lil_get1 handles validation for us. + return self._get_intXint(*key) + # Everything else takes the normal path. + return IndexMixin.__getitem__(self, key) + + def _asindices(self, idx, N): + # LIL routines handle bounds-checking for us, so don't do it here. + try: + x = np.asarray(idx) + except (ValueError, TypeError, MemoryError) as e: + raise IndexError('invalid index') from e + if x.ndim not in (1, 2): + raise IndexError('Index dimension must be <= 2') + return x + + def _get_intXint(self, row, col): + v = _csparsetools.lil_get1(self.shape[0], self.shape[1], self.rows, + self.data, row, col) + return self.dtype.type(v) + + def _get_sliceXint(self, row, col): + row = range(*row.indices(self.shape[0])) + return self._get_row_ranges(row, slice(col, col+1)) + + def _get_arrayXint(self, row, col): + res = self._get_row_ranges(row.ravel(), slice(col, col+1)) + if row.ndim > 1: + return res.reshape(row.shape) + return res + + def _get_intXslice(self, row, col): + return self._get_row_ranges((row,), col) + + def _get_sliceXslice(self, row, col): + row = range(*row.indices(self.shape[0])) + return self._get_row_ranges(row, col) + + def _get_arrayXslice(self, row, col): + return self._get_row_ranges(row, col) + + def _get_intXarray(self, row, col): + row = np.array(row, dtype=col.dtype, ndmin=1) + return self._get_columnXarray(row, col) + + def _get_sliceXarray(self, row, col): + row = np.arange(*row.indices(self.shape[0])) + return self._get_columnXarray(row, col) + + def _get_columnXarray(self, row, col): + # outer indexing + row, col = _broadcast_arrays(row[:,None], col) + return self._get_arrayXarray(row, col) + + def _get_arrayXarray(self, row, col): + # inner indexing + i, j = map(np.atleast_2d, _prepare_index_for_memoryview(row, col)) + new = self._lil_container(i.shape, dtype=self.dtype) + _csparsetools.lil_fancy_get(self.shape[0], self.shape[1], + self.rows, self.data, + new.rows, new.data, + i, j) + return new + + def _get_row_ranges(self, rows, col_slice): + """ + Fast path for indexing in the case where column index is slice. + + This gains performance improvement over brute force by more + efficient skipping of zeros, by accessing the elements + column-wise in order. + + Parameters + ---------- + rows : sequence or range + Rows indexed. If range, must be within valid bounds. + col_slice : slice + Columns indexed + + """ + j_start, j_stop, j_stride = col_slice.indices(self.shape[1]) + col_range = range(j_start, j_stop, j_stride) + nj = len(col_range) + new = self._lil_container((len(rows), nj), dtype=self.dtype) + + _csparsetools.lil_get_row_ranges(self.shape[0], self.shape[1], + self.rows, self.data, + new.rows, new.data, + rows, + j_start, j_stop, j_stride, nj) + + return new + + def _set_intXint(self, row, col, x): + _csparsetools.lil_insert(self.shape[0], self.shape[1], self.rows, + self.data, row, col, x) + + def _set_arrayXarray(self, row, col, x): + i, j, x = map(np.atleast_2d, _prepare_index_for_memoryview(row, col, x)) + _csparsetools.lil_fancy_set(self.shape[0], self.shape[1], + self.rows, self.data, + i, j, x) + + def _set_arrayXarray_sparse(self, row, col, x): + # Fall back to densifying x + x = np.asarray(x.toarray(), dtype=self.dtype) + x, _ = _broadcast_arrays(x, row) + self._set_arrayXarray(row, col, x) + + def __setitem__(self, key, x): + if isinstance(key, tuple) and len(key) == 2: + row, col = key + # Fast path for simple (int, int) indexing. + if isinstance(row, INT_TYPES) and isinstance(col, INT_TYPES): + x = self.dtype.type(x) + if x.size > 1: + raise ValueError("Trying to assign a sequence to an item") + return self._set_intXint(row, col, x) + # Fast path for full-matrix sparse assignment. + if (isinstance(row, slice) and isinstance(col, slice) and + row == slice(None) and col == slice(None) and + issparse(x) and x.shape == self.shape): + x = self._lil_container(x, dtype=self.dtype) + self.rows = x.rows + self.data = x.data + return + # Everything else takes the normal path. + IndexMixin.__setitem__(self, key, x) + + def _mul_scalar(self, other): + if other == 0: + # Multiply by zero: return the zero matrix + new = self._lil_container(self.shape, dtype=self.dtype) + else: + res_dtype = upcast_scalar(self.dtype, other) + + new = self.copy() + new = new.astype(res_dtype) + # Multiply this scalar by every element. + for j, rowvals in enumerate(new.data): + new.data[j] = [val*other for val in rowvals] + return new + + def __truediv__(self, other): # self / other + if isscalarlike(other): + new = self.copy() + new.dtype = np.result_type(self, other) + # Divide every element by this scalar + for j, rowvals in enumerate(new.data): + new.data[j] = [val/other for val in rowvals] + return new + else: + return self.tocsr() / other + + def copy(self): + M, N = self.shape + new = self._lil_container(self.shape, dtype=self.dtype) + # This is ~14x faster than calling deepcopy() on rows and data. + _csparsetools.lil_get_row_ranges(M, N, self.rows, self.data, + new.rows, new.data, range(M), + 0, N, 1, N) + return new + + copy.__doc__ = _spbase.copy.__doc__ + + def reshape(self, *args, **kwargs): + shape = check_shape(args, self.shape) + order, copy = check_reshape_kwargs(kwargs) + + # Return early if reshape is not required + if shape == self.shape: + if copy: + return self.copy() + else: + return self + + new = self._lil_container(shape, dtype=self.dtype) + + if order == 'C': + ncols = self.shape[1] + for i, row in enumerate(self.rows): + for col, j in enumerate(row): + new_r, new_c = np.unravel_index(i * ncols + j, shape) + new[new_r, new_c] = self[i, j] + elif order == 'F': + nrows = self.shape[0] + for i, row in enumerate(self.rows): + for col, j in enumerate(row): + new_r, new_c = np.unravel_index(i + j * nrows, shape, order) + new[new_r, new_c] = self[i, j] + else: + raise ValueError("'order' must be 'C' or 'F'") + + return new + + reshape.__doc__ = _spbase.reshape.__doc__ + + def resize(self, *shape): + shape = check_shape(shape) + new_M, new_N = shape + M, N = self.shape + + if new_M < M: + self.rows = self.rows[:new_M] + self.data = self.data[:new_M] + elif new_M > M: + self.rows = np.resize(self.rows, new_M) + self.data = np.resize(self.data, new_M) + for i in range(M, new_M): + self.rows[i] = [] + self.data[i] = [] + + if new_N < N: + for row, data in zip(self.rows, self.data): + trunc = bisect_left(row, new_N) + del row[trunc:] + del data[trunc:] + + self._shape = shape + + resize.__doc__ = _spbase.resize.__doc__ + + def toarray(self, order=None, out=None): + d = self._process_toarray_args(order, out) + for i, row in enumerate(self.rows): + for pos, j in enumerate(row): + d[i, j] = self.data[i][pos] + return d + + toarray.__doc__ = _spbase.toarray.__doc__ + + def transpose(self, axes=None, copy=False): + return self.tocsr(copy=copy).transpose(axes=axes, copy=False).tolil(copy=False) + + transpose.__doc__ = _spbase.transpose.__doc__ + + def tolil(self, copy=False): + if copy: + return self.copy() + else: + return self + + tolil.__doc__ = _spbase.tolil.__doc__ + + def tocsr(self, copy=False): + M, N = self.shape + if M == 0 or N == 0: + return self._csr_container((M, N), dtype=self.dtype) + + # construct indptr array + if M*N <= np.iinfo(np.int32).max: + # fast path: it is known that 64-bit indexing will not be needed. + idx_dtype = np.int32 + indptr = np.empty(M + 1, dtype=idx_dtype) + indptr[0] = 0 + _csparsetools.lil_get_lengths(self.rows, indptr[1:]) + np.cumsum(indptr, out=indptr) + nnz = indptr[-1] + else: + idx_dtype = self._get_index_dtype(maxval=N) + lengths = np.empty(M, dtype=idx_dtype) + _csparsetools.lil_get_lengths(self.rows, lengths) + nnz = lengths.sum(dtype=np.int64) + idx_dtype = self._get_index_dtype(maxval=max(N, nnz)) + indptr = np.empty(M + 1, dtype=idx_dtype) + indptr[0] = 0 + np.cumsum(lengths, dtype=idx_dtype, out=indptr[1:]) + + indices = np.empty(nnz, dtype=idx_dtype) + data = np.empty(nnz, dtype=self.dtype) + _csparsetools.lil_flatten_to_array(self.rows, indices) + _csparsetools.lil_flatten_to_array(self.data, data) + + # init csr matrix + return self._csr_container((data, indices, indptr), shape=self.shape) + + tocsr.__doc__ = _spbase.tocsr.__doc__ + + +def _prepare_index_for_memoryview(i, j, x=None): + """ + Convert index and data arrays to form suitable for passing to the + Cython fancy getset routines. + + The conversions are necessary since to (i) ensure the integer + index arrays are in one of the accepted types, and (ii) to ensure + the arrays are writable so that Cython memoryview support doesn't + choke on them. + + Parameters + ---------- + i, j + Index arrays + x : optional + Data arrays + + Returns + ------- + i, j, x + Re-formatted arrays (x is omitted, if input was None) + + """ + if i.dtype > j.dtype: + j = j.astype(i.dtype) + elif i.dtype < j.dtype: + i = i.astype(j.dtype) + + if not i.flags.writeable or i.dtype not in (np.int32, np.int64): + i = i.astype(np.intp) + if not j.flags.writeable or j.dtype not in (np.int32, np.int64): + j = j.astype(np.intp) + + if x is not None: + if not x.flags.writeable: + x = x.copy() + return i, j, x + else: + return i, j + + +def isspmatrix_lil(x): + """Is `x` of lil_matrix type? + + Parameters + ---------- + x + object to check for being a lil matrix + + Returns + ------- + bool + True if `x` is a lil matrix, False otherwise + + Examples + -------- + >>> from scipy.sparse import lil_array, lil_matrix, coo_matrix, isspmatrix_lil + >>> isspmatrix_lil(lil_matrix([[5]])) + True + >>> isspmatrix_lil(lil_array([[5]])) + False + >>> isspmatrix_lil(coo_matrix([[5]])) + False + """ + return isinstance(x, lil_matrix) + + +# This namespace class separates array from matrix with isinstance +class lil_array(_lil_base, sparray): + """ + Row-based LIst of Lists sparse array. + + This is a structure for constructing sparse arrays incrementally. + Note that inserting a single item can take linear time in the worst case; + to construct the array efficiently, make sure the items are pre-sorted by + index, per row. + + This can be instantiated in several ways: + lil_array(D) + where D is a 2-D ndarray + + lil_array(S) + with another sparse array or matrix S (equivalent to S.tolil()) + + lil_array((M, N), [dtype]) + to construct an empty array with shape (M, N) + dtype is optional, defaulting to dtype='d'. + + Attributes + ---------- + dtype : dtype + Data type of the array + shape : 2-tuple + Shape of the array + ndim : int + Number of dimensions (this is always 2) + nnz + size + data + LIL format data array of the array + rows + LIL format row index array of the array + T + + Notes + ----- + Sparse arrays can be used in arithmetic operations: they support + addition, subtraction, multiplication, division, and matrix power. + + Advantages of the LIL format + - supports flexible slicing + - changes to the array sparsity structure are efficient + + Disadvantages of the LIL format + - arithmetic operations LIL + LIL are slow (consider CSR or CSC) + - slow column slicing (consider CSC) + - slow matrix vector products (consider CSR or CSC) + + Intended Usage + - LIL is a convenient format for constructing sparse arrays + - once an array has been constructed, convert to CSR or + CSC format for fast arithmetic and matrix vector operations + - consider using the COO format when constructing large arrays + + Data Structure + - An array (``self.rows``) of rows, each of which is a sorted + list of column indices of non-zero elements. + - The corresponding nonzero values are stored in similar + fashion in ``self.data``. + + """ + + +class lil_matrix(spmatrix, _lil_base): + """ + Row-based LIst of Lists sparse matrix. + + This is a structure for constructing sparse matrices incrementally. + Note that inserting a single item can take linear time in the worst case; + to construct the matrix efficiently, make sure the items are pre-sorted by + index, per row. + + This can be instantiated in several ways: + lil_matrix(D) + where D is a 2-D ndarray + + lil_matrix(S) + with another sparse array or matrix S (equivalent to S.tolil()) + + lil_matrix((M, N), [dtype]) + to construct an empty matrix with shape (M, N) + dtype is optional, defaulting to dtype='d'. + + Attributes + ---------- + dtype : dtype + Data type of the matrix + shape : 2-tuple + Shape of the matrix + ndim : int + Number of dimensions (this is always 2) + nnz + size + data + LIL format data array of the matrix + rows + LIL format row index array of the matrix + T + + Notes + ----- + Sparse matrices can be used in arithmetic operations: they support + addition, subtraction, multiplication, division, and matrix power. + + Advantages of the LIL format + - supports flexible slicing + - changes to the matrix sparsity structure are efficient + + Disadvantages of the LIL format + - arithmetic operations LIL + LIL are slow (consider CSR or CSC) + - slow column slicing (consider CSC) + - slow matrix vector products (consider CSR or CSC) + + Intended Usage + - LIL is a convenient format for constructing sparse matrices + - once a matrix has been constructed, convert to CSR or + CSC format for fast arithmetic and matrix vector operations + - consider using the COO format when constructing large matrices + + Data Structure + - An array (``self.rows``) of rows, each of which is a sorted + list of column indices of non-zero elements. + - The corresponding nonzero values are stored in similar + fashion in ``self.data``. + + """ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_matrix.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..351660ba389ea7f2adf2576e350e840783d894fa --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_matrix.py @@ -0,0 +1,146 @@ +class spmatrix: + """This class provides a base class for all sparse matrix classes. + + It cannot be instantiated. Most of the work is provided by subclasses. + """ + _allow_nd = (2,) + + @property + def _bsr_container(self): + from ._bsr import bsr_matrix + return bsr_matrix + + @property + def _coo_container(self): + from ._coo import coo_matrix + return coo_matrix + + @property + def _csc_container(self): + from ._csc import csc_matrix + return csc_matrix + + @property + def _csr_container(self): + from ._csr import csr_matrix + return csr_matrix + + @property + def _dia_container(self): + from ._dia import dia_matrix + return dia_matrix + + @property + def _dok_container(self): + from ._dok import dok_matrix + return dok_matrix + + @property + def _lil_container(self): + from ._lil import lil_matrix + return lil_matrix + + # Restore matrix multiplication + def __mul__(self, other): + return self._matmul_dispatch(other) + + def __rmul__(self, other): + return self._rmatmul_dispatch(other) + + # Restore matrix power + def __pow__(self, power): + from .linalg import matrix_power + + return matrix_power(self, power) + + ## Backward compatibility + + def set_shape(self, shape): + """Set the shape of the matrix in-place""" + # Make sure copy is False since this is in place + # Make sure format is unchanged because we are doing a __dict__ swap + new_self = self.reshape(shape, copy=False).asformat(self.format) + self.__dict__ = new_self.__dict__ + + def get_shape(self): + """Get the shape of the matrix""" + return self._shape + + shape = property(fget=get_shape, fset=set_shape, + doc="Shape of the matrix") + + def asfptype(self): + """Upcast matrix to a floating point format (if necessary)""" + return self._asfptype() + + def getmaxprint(self): + """Maximum number of elements to display when printed.""" + return self._getmaxprint() + + def getformat(self): + """Matrix storage format""" + return self.format + + def getnnz(self, axis=None): + """Number of stored values, including explicit zeros. + + Parameters + ---------- + axis : None, 0, or 1 + Select between the number of values across the whole array, in + each column, or in each row. + """ + return self._getnnz(axis=axis) + + def getH(self): + """Return the Hermitian transpose of this matrix. + + See Also + -------- + numpy.matrix.getH : NumPy's implementation of `getH` for matrices + """ + return self.conjugate().transpose() + + def getcol(self, j): + """Returns a copy of column j of the matrix, as an (m x 1) sparse + matrix (column vector). + """ + return self._getcol(j) + + def getrow(self, i): + """Returns a copy of row i of the matrix, as a (1 x n) sparse + matrix (row vector). + """ + return self._getrow(i) + + def todense(self, order=None, out=None): + """ + Return a dense representation of this sparse matrix. + + Parameters + ---------- + order : {'C', 'F'}, optional + Whether to store multi-dimensional data in C (row-major) + or Fortran (column-major) order in memory. The default + is 'None', which provides no ordering guarantees. + Cannot be specified in conjunction with the `out` + argument. + + out : ndarray, 2-D, optional + If specified, uses this array (or `numpy.matrix`) as the + output buffer instead of allocating a new array to + return. The provided array must have the same shape and + dtype as the sparse matrix on which you are calling the + method. + + Returns + ------- + arr : numpy.matrix, 2-D + A NumPy matrix object with the same shape and containing + the same data represented by the sparse matrix, with the + requested memory order. If `out` was passed and was an + array (rather than a `numpy.matrix`), it will be filled + with the appropriate values and returned wrapped in a + `numpy.matrix` object that shares the same memory. + """ + return super().todense(order, out) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_matrix_io.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_matrix_io.py new file mode 100644 index 0000000000000000000000000000000000000000..5b7f533926fd415a379cb08420b4a65a14baeb43 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_matrix_io.py @@ -0,0 +1,167 @@ +import numpy as np +import scipy as sp + +__all__ = ['save_npz', 'load_npz'] + + +# Make loading safe vs. malicious input +PICKLE_KWARGS = dict(allow_pickle=False) + + +def save_npz(file, matrix, compressed=True): + """ Save a sparse matrix or array to a file using ``.npz`` format. + + Parameters + ---------- + file : str or file-like object + Either the file name (string) or an open file (file-like object) + where the data will be saved. If file is a string, the ``.npz`` + extension will be appended to the file name if it is not already + there. + matrix: spmatrix or sparray + The sparse matrix or array to save. + Supported formats: ``csc``, ``csr``, ``bsr``, ``dia`` or ``coo``. + compressed : bool, optional + Allow compressing the file. Default: True + + See Also + -------- + scipy.sparse.load_npz: Load a sparse matrix from a file using ``.npz`` format. + numpy.savez: Save several arrays into a ``.npz`` archive. + numpy.savez_compressed : Save several arrays into a compressed ``.npz`` archive. + + Examples + -------- + Store sparse matrix to disk, and load it again: + + >>> import numpy as np + >>> import scipy as sp + >>> sparse_matrix = sp.sparse.csc_matrix([[0, 0, 3], [4, 0, 0]]) + >>> sparse_matrix + + >>> sparse_matrix.toarray() + array([[0, 0, 3], + [4, 0, 0]], dtype=int64) + + >>> sp.sparse.save_npz('/tmp/sparse_matrix.npz', sparse_matrix) + >>> sparse_matrix = sp.sparse.load_npz('/tmp/sparse_matrix.npz') + + >>> sparse_matrix + + >>> sparse_matrix.toarray() + array([[0, 0, 3], + [4, 0, 0]], dtype=int64) + """ + arrays_dict = {} + if matrix.format in ('csc', 'csr', 'bsr'): + arrays_dict.update(indices=matrix.indices, indptr=matrix.indptr) + elif matrix.format == 'dia': + arrays_dict.update(offsets=matrix.offsets) + elif matrix.format == 'coo': + arrays_dict.update(row=matrix.row, col=matrix.col) + else: + msg = f'Save is not implemented for sparse matrix of format {matrix.format}.' + raise NotImplementedError(msg) + arrays_dict.update( + format=matrix.format.encode('ascii'), + shape=matrix.shape, + data=matrix.data + ) + if isinstance(matrix, sp.sparse.sparray): + arrays_dict.update(_is_array=True) + if compressed: + np.savez_compressed(file, **arrays_dict) + else: + np.savez(file, **arrays_dict) + + +def load_npz(file): + """ Load a sparse array/matrix from a file using ``.npz`` format. + + Parameters + ---------- + file : str or file-like object + Either the file name (string) or an open file (file-like object) + where the data will be loaded. + + Returns + ------- + result : csc_array, csr_array, bsr_array, dia_array or coo_array + A sparse array/matrix containing the loaded data. + + Raises + ------ + OSError + If the input file does not exist or cannot be read. + + See Also + -------- + scipy.sparse.save_npz: Save a sparse array/matrix to a file using ``.npz`` format. + numpy.load: Load several arrays from a ``.npz`` archive. + + Examples + -------- + Store sparse array/matrix to disk, and load it again: + + >>> import numpy as np + >>> import scipy as sp + >>> sparse_array = sp.sparse.csc_array([[0, 0, 3], [4, 0, 0]]) + >>> sparse_array + + >>> sparse_array.toarray() + array([[0, 0, 3], + [4, 0, 0]], dtype=int64) + + >>> sp.sparse.save_npz('/tmp/sparse_array.npz', sparse_array) + >>> sparse_array = sp.sparse.load_npz('/tmp/sparse_array.npz') + + >>> sparse_array + + >>> sparse_array.toarray() + array([[0, 0, 3], + [4, 0, 0]], dtype=int64) + + In this example we force the result to be csr_array from csr_matrix + >>> sparse_matrix = sp.sparse.csc_matrix([[0, 0, 3], [4, 0, 0]]) + >>> sp.sparse.save_npz('/tmp/sparse_matrix.npz', sparse_matrix) + >>> tmp = sp.sparse.load_npz('/tmp/sparse_matrix.npz') + >>> sparse_array = sp.sparse.csr_array(tmp) + """ + with np.load(file, **PICKLE_KWARGS) as loaded: + sparse_format = loaded.get('format') + if sparse_format is None: + raise ValueError(f'The file {file} does not contain ' + f'a sparse array or matrix.') + sparse_format = sparse_format.item() + + if not isinstance(sparse_format, str): + # Play safe with Python 2 vs 3 backward compatibility; + # files saved with SciPy < 1.0.0 may contain unicode or bytes. + sparse_format = sparse_format.decode('ascii') + + if loaded.get('_is_array'): + sparse_type = sparse_format + '_array' + else: + sparse_type = sparse_format + '_matrix' + + try: + cls = getattr(sp.sparse, f'{sparse_type}') + except AttributeError as e: + raise ValueError(f'Unknown format "{sparse_type}"') from e + + if sparse_format in ('csc', 'csr', 'bsr'): + return cls((loaded['data'], loaded['indices'], loaded['indptr']), + shape=loaded['shape']) + elif sparse_format == 'dia': + return cls((loaded['data'], loaded['offsets']), + shape=loaded['shape']) + elif sparse_format == 'coo': + return cls((loaded['data'], (loaded['row'], loaded['col'])), + shape=loaded['shape']) + else: + raise NotImplementedError(f'Load is not implemented for ' + f'sparse matrix of format {sparse_format}.') diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_spfuncs.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_spfuncs.py new file mode 100644 index 0000000000000000000000000000000000000000..8e9b0abcede6387e74538baf839a303c6cc1b6be --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_spfuncs.py @@ -0,0 +1,76 @@ +""" Functions that operate on sparse matrices +""" + +__all__ = ['count_blocks','estimate_blocksize'] + +from ._base import issparse +from ._csr import csr_array +from ._sparsetools import csr_count_blocks + + +def estimate_blocksize(A,efficiency=0.7): + """Attempt to determine the blocksize of a sparse matrix + + Returns a blocksize=(r,c) such that + - A.nnz / A.tobsr( (r,c) ).nnz > efficiency + """ + if not (issparse(A) and A.format in ("csc", "csr")): + A = csr_array(A) + + if A.nnz == 0: + return (1,1) + + if not 0 < efficiency < 1.0: + raise ValueError('efficiency must satisfy 0.0 < efficiency < 1.0') + + high_efficiency = (1.0 + efficiency) / 2.0 + nnz = float(A.nnz) + M,N = A.shape + + if M % 2 == 0 and N % 2 == 0: + e22 = nnz / (4 * count_blocks(A,(2,2))) + else: + e22 = 0.0 + + if M % 3 == 0 and N % 3 == 0: + e33 = nnz / (9 * count_blocks(A,(3,3))) + else: + e33 = 0.0 + + if e22 > high_efficiency and e33 > high_efficiency: + e66 = nnz / (36 * count_blocks(A,(6,6))) + if e66 > efficiency: + return (6,6) + else: + return (3,3) + else: + if M % 4 == 0 and N % 4 == 0: + e44 = nnz / (16 * count_blocks(A,(4,4))) + else: + e44 = 0.0 + + if e44 > efficiency: + return (4,4) + elif e33 > efficiency: + return (3,3) + elif e22 > efficiency: + return (2,2) + else: + return (1,1) + + +def count_blocks(A,blocksize): + """For a given blocksize=(r,c) count the number of occupied + blocks in a sparse matrix A + """ + r,c = blocksize + if r < 1 or c < 1: + raise ValueError('r and c must be positive') + + if issparse(A): + if A.format == "csr": + M,N = A.shape + return csr_count_blocks(M,N,r,c,A.indptr,A.indices) + elif A.format == "csc": + return count_blocks(A.T,(c,r)) + return count_blocks(csr_array(A),blocksize) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_sputils.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_sputils.py new file mode 100644 index 0000000000000000000000000000000000000000..4fb5b5fc6c2e37d0c61dd3a3aa0aa382c7486a03 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/_sputils.py @@ -0,0 +1,617 @@ +""" Utility functions for sparse matrix module +""" + +import sys +from typing import Any, Literal, Union +import operator +import numpy as np +from math import prod +import scipy.sparse as sp +from scipy._lib._util import np_long, np_ulong + + +__all__ = ['upcast', 'getdtype', 'getdata', 'isscalarlike', 'isintlike', + 'isshape', 'issequence', 'isdense', 'ismatrix', 'get_sum_dtype', + 'broadcast_shapes'] + +supported_dtypes = [np.bool_, np.byte, np.ubyte, np.short, np.ushort, np.intc, + np.uintc, np_long, np_ulong, np.longlong, np.ulonglong, + np.float32, np.float64, np.longdouble, + np.complex64, np.complex128, np.clongdouble] + +_upcast_memo = {} + + +def upcast(*args): + """Returns the nearest supported sparse dtype for the + combination of one or more types. + + upcast(t0, t1, ..., tn) -> T where T is a supported dtype + + Examples + -------- + >>> from scipy.sparse._sputils import upcast + >>> upcast('int32') + + >>> upcast('bool') + + >>> upcast('int32','float32') + + >>> upcast('bool',complex,float) + + + """ + + t = _upcast_memo.get(hash(args)) + if t is not None: + return t + + upcast = np.result_type(*args) + + for t in supported_dtypes: + if np.can_cast(upcast, t): + _upcast_memo[hash(args)] = t + return t + + raise TypeError(f'no supported conversion for types: {args!r}') + + +def upcast_char(*args): + """Same as `upcast` but taking dtype.char as input (faster).""" + t = _upcast_memo.get(args) + if t is not None: + return t + t = upcast(*map(np.dtype, args)) + _upcast_memo[args] = t + return t + + +def upcast_scalar(dtype, scalar): + """Determine data type for binary operation between an array of + type `dtype` and a scalar. + """ + return (np.array([0], dtype=dtype) * scalar).dtype + + +def downcast_intp_index(arr): + """ + Down-cast index array to np.intp dtype if it is of a larger dtype. + + Raise an error if the array contains a value that is too large for + intp. + """ + if arr.dtype.itemsize > np.dtype(np.intp).itemsize: + if arr.size == 0: + return arr.astype(np.intp) + maxval = arr.max() + minval = arr.min() + if maxval > np.iinfo(np.intp).max or minval < np.iinfo(np.intp).min: + raise ValueError("Cannot deal with arrays with indices larger " + "than the machine maximum address size " + "(e.g. 64-bit indices on 32-bit machine).") + return arr.astype(np.intp) + return arr + + +def to_native(A): + """ + Ensure that the data type of the NumPy array `A` has native byte order. + + `A` must be a NumPy array. If the data type of `A` does not have native + byte order, a copy of `A` with a native byte order is returned. Otherwise + `A` is returned. + """ + dt = A.dtype + if dt.isnative: + # Don't call `asarray()` if A is already native, to avoid unnecessarily + # creating a view of the input array. + return A + return np.asarray(A, dtype=dt.newbyteorder('native')) + + +def getdtype(dtype, a=None, default=None): + """Form a supported numpy dtype based on input arguments. + + Returns a valid ``numpy.dtype`` from `dtype` if not None, + or else ``a.dtype`` if possible, or else the given `default` + if not None, or else raise a ``TypeError``. + + The resulting ``dtype`` must be in ``supported_dtypes``: + bool_, int8, uint8, int16, uint16, int32, uint32, + int64, uint64, longlong, ulonglong, float32, float64, + longdouble, complex64, complex128, clongdouble + """ + if dtype is None: + try: + newdtype = a.dtype + except AttributeError as e: + if default is not None: + newdtype = np.dtype(default) + else: + raise TypeError("could not interpret data type") from e + else: + newdtype = np.dtype(dtype) + + if newdtype not in supported_dtypes: + supported_dtypes_fmt = ", ".join(t.__name__ for t in supported_dtypes) + raise ValueError(f"scipy.sparse does not support dtype {newdtype.name}. " + f"The only supported types are: {supported_dtypes_fmt}.") + return newdtype + + +def getdata(obj, dtype=None, copy=False) -> np.ndarray: + """ + This is a wrapper of `np.array(obj, dtype=dtype, copy=copy)` + that will generate a warning if the result is an object array. + """ + data = np.array(obj, dtype=dtype, copy=copy) + # Defer to getdtype for checking that the dtype is OK. + # This is called for the validation only; we don't need the return value. + getdtype(data.dtype) + return data + + +def safely_cast_index_arrays(A, idx_dtype=np.int32, msg=""): + """Safely cast sparse array indices to `idx_dtype`. + + Check the shape of `A` to determine if it is safe to cast its index + arrays to dtype `idx_dtype`. If any dimension in shape is larger than + fits in the dtype, casting is unsafe so raise ``ValueError``. + If safe, cast the index arrays to `idx_dtype` and return the result + without changing the input `A`. The caller can assign results to `A` + attributes if desired or use the recast index arrays directly. + + Unless downcasting is needed, the original index arrays are returned. + You can test e.g. ``A.indptr is new_indptr`` to see if downcasting occurred. + + .. versionadded:: 1.15.0 + + Parameters + ---------- + A : sparse array or matrix + The array for which index arrays should be downcast. + idx_dtype : dtype + Desired dtype. Should be an integer dtype (default: ``np.int32``). + Most of scipy.sparse uses either int64 or int32. + msg : string, optional + A string to be added to the end of the ValueError message + if the array shape is too big to fit in `idx_dtype`. + The error message is ``f" values too large for {msg}"`` + It should indicate why the downcasting is needed, e.g. "SuperLU", + and defaults to f"dtype {idx_dtype}". + + Returns + ------- + idx_arrays : ndarray or tuple of ndarrays + Based on ``A.format``, index arrays are returned after casting to `idx_dtype`. + For CSC/CSR, returns ``(indices, indptr)``. + For COO, returns ``coords``. + For DIA, returns ``offsets``. + For BSR, returns ``(indices, indptr)``. + + Raises + ------ + ValueError + If the array has shape that would not fit in the new dtype, or if + the sparse format does not use index arrays. + + Examples + -------- + >>> import numpy as np + >>> from scipy import sparse + >>> data = [3] + >>> coords = (np.array([3]), np.array([1])) # Note: int64 arrays + >>> A = sparse.coo_array((data, coords)) + >>> A.coords[0].dtype + dtype('int64') + + >>> # rescast after construction, raising exception if shape too big + >>> coords = sparse.safely_cast_index_arrays(A, np.int32) + >>> A.coords[0] is coords[0] # False if casting is needed + False + >>> A.coords = coords # set the index dtype of A + >>> A.coords[0].dtype + dtype('int32') + """ + if not msg: + msg = f"dtype {idx_dtype}" + # check for safe downcasting + max_value = np.iinfo(idx_dtype).max + + if A.format in ("csc", "csr"): + # indptr[-1] is max b/c indptr always sorted + if A.indptr[-1] > max_value: + raise ValueError(f"indptr values too large for {msg}") + + # check shape vs dtype + if max(*A.shape) > max_value: + if (A.indices > max_value).any(): + raise ValueError(f"indices values too large for {msg}") + + indices = A.indices.astype(idx_dtype, copy=False) + indptr = A.indptr.astype(idx_dtype, copy=False) + return indices, indptr + + elif A.format == "coo": + if max(*A.shape) > max_value: + if any((co > max_value).any() for co in A.coords): + raise ValueError(f"coords values too large for {msg}") + return tuple(co.astype(idx_dtype, copy=False) for co in A.coords) + + elif A.format == "dia": + if max(*A.shape) > max_value: + if (A.offsets > max_value).any(): + raise ValueError(f"offsets values too large for {msg}") + offsets = A.offsets.astype(idx_dtype, copy=False) + return offsets + + elif A.format == 'bsr': + R, C = A.blocksize + if A.indptr[-1] * R > max_value: + raise ValueError("indptr values too large for {msg}") + if max(*A.shape) > max_value: + if (A.indices * C > max_value).any(): + raise ValueError(f"indices values too large for {msg}") + indices = A.indices.astype(idx_dtype, copy=False) + indptr = A.indptr.astype(idx_dtype, copy=False) + return indices, indptr + + else: + raise TypeError(f'Format {A.format} is not associated with index arrays. ' + 'DOK and LIL have dict and list, not array.') + + +def get_index_dtype(arrays=(), maxval=None, check_contents=False): + """ + Based on input (integer) arrays `a`, determine a suitable index data + type that can hold the data in the arrays. + + Parameters + ---------- + arrays : tuple of array_like + Input arrays whose types/contents to check + maxval : float, optional + Maximum value needed + check_contents : bool, optional + Whether to check the values in the arrays and not just their types. + Default: False (check only the types) + + Returns + ------- + dtype : dtype + Suitable index data type (int32 or int64) + + Examples + -------- + >>> import numpy as np + >>> from scipy import sparse + >>> # select index dtype based on shape + >>> shape = (3, 3) + >>> idx_dtype = sparse.get_index_dtype(maxval=max(shape)) + >>> data = [1.1, 3.0, 1.5] + >>> indices = np.array([0, 1, 0], dtype=idx_dtype) + >>> indptr = np.array([0, 2, 3, 3], dtype=idx_dtype) + >>> A = sparse.csr_array((data, indices, indptr), shape=shape) + >>> A.indptr.dtype + dtype('int32') + + >>> # select based on larger of existing arrays and shape + >>> shape = (3, 3) + >>> idx_dtype = sparse.get_index_dtype(A.indptr, maxval=max(shape)) + >>> idx_dtype + + """ + # not using intc directly due to misinteractions with pythran + if np.intc().itemsize != 4: + return np.int64 + + int32min = np.int32(np.iinfo(np.int32).min) + int32max = np.int32(np.iinfo(np.int32).max) + + if maxval is not None: + maxval = np.int64(maxval) + if maxval > int32max: + return np.int64 + + if isinstance(arrays, np.ndarray): + arrays = (arrays,) + + for arr in arrays: + arr = np.asarray(arr) + if not np.can_cast(arr.dtype, np.int32): + if check_contents: + if arr.size == 0: + # a bigger type not needed + continue + elif np.issubdtype(arr.dtype, np.integer): + maxval = arr.max() + minval = arr.min() + if minval >= int32min and maxval <= int32max: + # a bigger type not needed + continue + return np.int64 + return np.int32 + + +def get_sum_dtype(dtype: np.dtype) -> np.dtype: + """Mimic numpy's casting for np.sum""" + if dtype.kind == 'u' and np.can_cast(dtype, np.uint): + return np.uint + if np.can_cast(dtype, np.int_): + return np.int_ + return dtype + + +def isscalarlike(x) -> bool: + """Is x either a scalar, an array scalar, or a 0-dim array?""" + return np.isscalar(x) or (isdense(x) and x.ndim == 0) + + +def isintlike(x) -> bool: + """Is x appropriate as an index into a sparse matrix? Returns True + if it can be cast safely to a machine int. + """ + # Fast-path check to eliminate non-scalar values. operator.index would + # catch this case too, but the exception catching is slow. + if np.ndim(x) != 0: + return False + try: + operator.index(x) + except (TypeError, ValueError): + try: + loose_int = bool(int(x) == x) + except (TypeError, ValueError): + return False + if loose_int: + msg = "Inexact indices into sparse matrices are not allowed" + raise ValueError(msg) + return loose_int + return True + + +def isshape(x, nonneg=False, *, allow_nd=(2,)) -> bool: + """Is x a valid tuple of dimensions? + + If nonneg, also checks that the dimensions are non-negative. + Shapes of length in the tuple allow_nd are allowed. + """ + ndim = len(x) + if ndim not in allow_nd: + return False + + for d in x: + if not isintlike(d): + return False + if nonneg and d < 0: + return False + return True + + +def issequence(t) -> bool: + return ((isinstance(t, list | tuple) and + (len(t) == 0 or np.isscalar(t[0]))) or + (isinstance(t, np.ndarray) and (t.ndim == 1))) + + +def ismatrix(t) -> bool: + return ((isinstance(t, list | tuple) and + len(t) > 0 and issequence(t[0])) or + (isinstance(t, np.ndarray) and t.ndim == 2)) + + +def isdense(x) -> bool: + return isinstance(x, np.ndarray) + + +def validateaxis(axis) -> None: + if axis is None: + return + axis_type = type(axis) + + # In NumPy, you can pass in tuples for 'axis', but they are + # not very useful for sparse matrices given their limited + # dimensions, so let's make it explicit that they are not + # allowed to be passed in + if isinstance(axis, tuple): + raise TypeError("Tuples are not accepted for the 'axis' parameter. " + "Please pass in one of the following: " + "{-2, -1, 0, 1, None}.") + + # If not a tuple, check that the provided axis is actually + # an integer and raise a TypeError similar to NumPy's + if not np.issubdtype(np.dtype(axis_type), np.integer): + raise TypeError(f"axis must be an integer, not {axis_type.__name__}") + + if not (-2 <= axis <= 1): + raise ValueError("axis out of range") + + +def check_shape(args, current_shape=None, *, allow_nd=(2,)) -> tuple[int, ...]: + """Imitate numpy.matrix handling of shape arguments + + Parameters + ---------- + args : array_like + Data structures providing information about the shape of the sparse array. + current_shape : tuple, optional + The current shape of the sparse array or matrix. + If None (default), the current shape will be inferred from args. + allow_nd : tuple of ints, optional default: (2,) + If shape does not have a length in the tuple allow_nd an error is raised. + + Returns + ------- + new_shape: tuple + The new shape after validation. + """ + if len(args) == 0: + raise TypeError("function missing 1 required positional argument: 'shape'") + if len(args) == 1: + try: + shape_iter = iter(args[0]) + except TypeError: + new_shape = (operator.index(args[0]), ) + else: + new_shape = tuple(operator.index(arg) for arg in shape_iter) + else: + new_shape = tuple(operator.index(arg) for arg in args) + + if current_shape is None: + if len(new_shape) not in allow_nd: + raise ValueError(f'shape must have length in {allow_nd}. Got {new_shape=}') + if any(d < 0 for d in new_shape): + raise ValueError("'shape' elements cannot be negative") + else: + # Check the current size only if needed + current_size = prod(current_shape) + + # Check for negatives + negative_indexes = [i for i, x in enumerate(new_shape) if x < 0] + if not negative_indexes: + new_size = prod(new_shape) + if new_size != current_size: + raise ValueError(f'cannot reshape array of size {current_size}' + f' into shape {new_shape}') + elif len(negative_indexes) == 1: + skip = negative_indexes[0] + specified = prod(new_shape[:skip] + new_shape[skip+1:]) + unspecified, remainder = divmod(current_size, specified) + if remainder != 0: + err_shape = tuple('newshape' if x < 0 else x for x in new_shape) + raise ValueError(f'cannot reshape array of size {current_size}' + f' into shape {err_shape}') + new_shape = new_shape[:skip] + (unspecified,) + new_shape[skip+1:] + else: + raise ValueError('can only specify one unknown dimension') + + if len(new_shape) not in allow_nd: + raise ValueError(f'shape must have length in {allow_nd}. Got {new_shape=}') + + return new_shape + + +def broadcast_shapes(*shapes): + """Check if shapes can be broadcast and return resulting shape + + This is similar to the NumPy ``broadcast_shapes`` function but + does not check memory consequences of the resulting dense matrix. + + Parameters + ---------- + *shapes : tuple of shape tuples + The tuple of shapes to be considered for broadcasting. + Shapes should be tuples of non-negative integers. + + Returns + ------- + new_shape : tuple of integers + The shape that results from broadcasting th input shapes. + """ + if not shapes: + return () + shapes = [shp if isinstance(shp, (tuple, list)) else (shp,) for shp in shapes] + big_shp = max(shapes, key=len) + out = list(big_shp) + for shp in shapes: + if shp is big_shp: + continue + for i, x in enumerate(shp, start=-len(shp)): + if x != 1 and x != out[i]: + if out[i] != 1: + raise ValueError("shapes cannot be broadcast to a single shape.") + out[i] = x + return (*out,) + + +def check_reshape_kwargs(kwargs): + """Unpack keyword arguments for reshape function. + + This is useful because keyword arguments after star arguments are not + allowed in Python 2, but star keyword arguments are. This function unpacks + 'order' and 'copy' from the star keyword arguments (with defaults) and + throws an error for any remaining. + """ + + order = kwargs.pop('order', 'C') + copy = kwargs.pop('copy', False) + if kwargs: # Some unused kwargs remain + raise TypeError("reshape() got unexpected keywords arguments: " + f"{', '.join(kwargs.keys())}") + return order, copy + + +def is_pydata_spmatrix(m) -> bool: + """ + Check whether object is pydata/sparse matrix, avoiding importing the module. + """ + base_cls = getattr(sys.modules.get('sparse'), 'SparseArray', None) + return base_cls is not None and isinstance(m, base_cls) + + +def convert_pydata_sparse_to_scipy( + arg: Any, + target_format: None | Literal["csc", "csr"] = None, + accept_fv: Any = None, +) -> Union[Any, "sp.spmatrix"]: + """ + Convert a pydata/sparse array to scipy sparse matrix, + pass through anything else. + """ + if is_pydata_spmatrix(arg): + # The `accept_fv` keyword is new in PyData Sparse 0.15.4 (May 2024), + # remove the `except` once the minimum supported version is >=0.15.4 + try: + arg = arg.to_scipy_sparse(accept_fv=accept_fv) + except TypeError: + arg = arg.to_scipy_sparse() + if target_format is not None: + arg = arg.asformat(target_format) + elif arg.format not in ("csc", "csr"): + arg = arg.tocsc() + return arg + + +############################################################################### +# Wrappers for NumPy types that are deprecated + +# Numpy versions of these functions raise deprecation warnings, the +# ones below do not. + +def matrix(*args, **kwargs): + return np.array(*args, **kwargs).view(np.matrix) + + +def asmatrix(data, dtype=None): + if isinstance(data, np.matrix) and (dtype is None or data.dtype == dtype): + return data + return np.asarray(data, dtype=dtype).view(np.matrix) + +############################################################################### + + +def _todata(s) -> np.ndarray: + """Access nonzero values, possibly after summing duplicates. + + Parameters + ---------- + s : sparse array + Input sparse array. + + Returns + ------- + data: ndarray + Nonzero values of the array, with shape (s.nnz,) + + """ + if isinstance(s, sp._data._data_matrix): + return s._deduped_data() + + if isinstance(s, sp.dok_array): + return np.fromiter(s.values(), dtype=s.dtype, count=s.nnz) + + if isinstance(s, sp.lil_array): + data = np.empty(s.nnz, dtype=s.dtype) + sp._csparsetools.lil_flatten_to_array(s.data, data) + return data + + return s.tocoo()._deduped_data() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/base.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/base.py new file mode 100644 index 0000000000000000000000000000000000000000..d0a427e4570e07cc71e9e45bf98c7cf61798125b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/base.py @@ -0,0 +1,33 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.sparse` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'MAXPRINT', + 'SparseEfficiencyWarning', + 'SparseFormatWarning', + 'SparseWarning', + 'asmatrix', + 'check_reshape_kwargs', + 'check_shape', + 'get_sum_dtype', + 'isdense', + 'isscalarlike', + 'issparse', + 'isspmatrix', + 'spmatrix', + 'validateaxis', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="sparse", module="base", + private_modules=["_base"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/bsr.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/bsr.py new file mode 100644 index 0000000000000000000000000000000000000000..c686301a78fc3e2221600eb06035a5cb12898cdb --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/bsr.py @@ -0,0 +1,36 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.sparse` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'bsr_matmat', + 'bsr_matrix', + 'bsr_matvec', + 'bsr_matvecs', + 'bsr_sort_indices', + 'bsr_tocsr', + 'bsr_transpose', + 'check_shape', + 'csr_matmat_maxnnz', + 'getdata', + 'getdtype', + 'isshape', + 'isspmatrix_bsr', + 'spmatrix', + 'to_native', + 'upcast', + 'warn', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="sparse", module="bsr", + private_modules=["_bsr"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/compressed.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/compressed.py new file mode 100644 index 0000000000000000000000000000000000000000..e6dc8a73e5ab527cfe0b73d558dae25047cfb98b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/compressed.py @@ -0,0 +1,43 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.sparse` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'IndexMixin', + 'SparseEfficiencyWarning', + 'check_shape', + 'csr_column_index1', + 'csr_column_index2', + 'csr_row_index', + 'csr_row_slice', + 'csr_sample_offsets', + 'csr_sample_values', + 'csr_todense', + 'downcast_intp_index', + 'get_csr_submatrix', + 'get_sum_dtype', + 'getdtype', + 'is_pydata_spmatrix', + 'isdense', + 'isintlike', + 'isscalarlike', + 'isshape', + 'operator', + 'to_native', + 'upcast', + 'upcast_char', + 'warn', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="sparse", module="compressed", + private_modules=["_compressed"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/construct.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/construct.py new file mode 100644 index 0000000000000000000000000000000000000000..c3d34d2fd38887877980727bceaaa215129bf283 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/construct.py @@ -0,0 +1,44 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.sparse` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'block_diag', + 'bmat', + 'bsr_matrix', + 'check_random_state', + 'coo_matrix', + 'csc_matrix', + 'csr_hstack', + 'csr_matrix', + 'dia_matrix', + 'diags', + 'eye', + 'get_index_dtype', + 'hstack', + 'identity', + 'isscalarlike', + 'issparse', + 'kron', + 'kronsum', + 'numbers', + 'rand', + 'random', + 'rng_integers', + 'spdiags', + 'upcast', + 'vstack', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="sparse", module="construct", + private_modules=["_construct"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/coo.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/coo.py new file mode 100644 index 0000000000000000000000000000000000000000..bda2da3d09a676ab79739331a21ba26102bb90ae --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/coo.py @@ -0,0 +1,37 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.sparse` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'SparseEfficiencyWarning', + 'check_reshape_kwargs', + 'check_shape', + 'coo_matrix', + 'coo_matvec', + 'coo_tocsr', + 'coo_todense', + 'downcast_intp_index', + 'getdata', + 'getdtype', + 'isshape', + 'isspmatrix_coo', + 'operator', + 'spmatrix', + 'to_native', + 'upcast', + 'upcast_char', + 'warn', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="sparse", module="coo", + private_modules=["_coo"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csc.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csc.py new file mode 100644 index 0000000000000000000000000000000000000000..d140b841e0724155f8602a4215836e2c8a7fad72 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csc.py @@ -0,0 +1,25 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.sparse` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'csc_matrix', + 'csc_tocsr', + 'expandptr', + 'isspmatrix_csc', + 'spmatrix', + 'upcast', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="sparse", module="csc", + private_modules=["_csc"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csgraph/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csgraph/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..00ab19af4748147d748fccb51a3710d5c711f4b4 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csgraph/__init__.py @@ -0,0 +1,210 @@ +r""" +Compressed sparse graph routines (:mod:`scipy.sparse.csgraph`) +============================================================== + +.. currentmodule:: scipy.sparse.csgraph + +Fast graph algorithms based on sparse matrix representations. + +Contents +-------- + +.. autosummary:: + :toctree: generated/ + + connected_components -- determine connected components of a graph + laplacian -- compute the laplacian of a graph + shortest_path -- compute the shortest path between points on a positive graph + dijkstra -- use Dijkstra's algorithm for shortest path + floyd_warshall -- use the Floyd-Warshall algorithm for shortest path + bellman_ford -- use the Bellman-Ford algorithm for shortest path + johnson -- use Johnson's algorithm for shortest path + yen -- use Yen's algorithm for K-shortest paths between to nodes. + breadth_first_order -- compute a breadth-first order of nodes + depth_first_order -- compute a depth-first order of nodes + breadth_first_tree -- construct the breadth-first tree from a given node + depth_first_tree -- construct a depth-first tree from a given node + minimum_spanning_tree -- construct the minimum spanning tree of a graph + reverse_cuthill_mckee -- compute permutation for reverse Cuthill-McKee ordering + maximum_flow -- solve the maximum flow problem for a graph + maximum_bipartite_matching -- compute a maximum matching of a bipartite graph + min_weight_full_bipartite_matching - compute a minimum weight full matching of a bipartite graph + structural_rank -- compute the structural rank of a graph + NegativeCycleError + +.. autosummary:: + :toctree: generated/ + + construct_dist_matrix + csgraph_from_dense + csgraph_from_masked + csgraph_masked_from_dense + csgraph_to_dense + csgraph_to_masked + reconstruct_path + +Graph Representations +--------------------- +This module uses graphs which are stored in a matrix format. A +graph with N nodes can be represented by an (N x N) adjacency matrix G. +If there is a connection from node i to node j, then G[i, j] = w, where +w is the weight of the connection. For nodes i and j which are +not connected, the value depends on the representation: + +- for dense array representations, non-edges are represented by + G[i, j] = 0, infinity, or NaN. + +- for dense masked representations (of type np.ma.MaskedArray), non-edges + are represented by masked values. This can be useful when graphs with + zero-weight edges are desired. + +- for sparse array representations, non-edges are represented by + non-entries in the matrix. This sort of sparse representation also + allows for edges with zero weights. + +As a concrete example, imagine that you would like to represent the following +undirected graph:: + + G + + (0) + / \ + 1 2 + / \ + (2) (1) + +This graph has three nodes, where node 0 and 1 are connected by an edge of +weight 2, and nodes 0 and 2 are connected by an edge of weight 1. +We can construct the dense, masked, and sparse representations as follows, +keeping in mind that an undirected graph is represented by a symmetric matrix:: + + >>> import numpy as np + >>> G_dense = np.array([[0, 2, 1], + ... [2, 0, 0], + ... [1, 0, 0]]) + >>> G_masked = np.ma.masked_values(G_dense, 0) + >>> from scipy.sparse import csr_array + >>> G_sparse = csr_array(G_dense) + +This becomes more difficult when zero edges are significant. For example, +consider the situation when we slightly modify the above graph:: + + G2 + + (0) + / \ + 0 2 + / \ + (2) (1) + +This is identical to the previous graph, except nodes 0 and 2 are connected +by an edge of zero weight. In this case, the dense representation above +leads to ambiguities: how can non-edges be represented if zero is a meaningful +value? In this case, either a masked or sparse representation must be used +to eliminate the ambiguity:: + + >>> import numpy as np + >>> G2_data = np.array([[np.inf, 2, 0 ], + ... [2, np.inf, np.inf], + ... [0, np.inf, np.inf]]) + >>> G2_masked = np.ma.masked_invalid(G2_data) + >>> from scipy.sparse.csgraph import csgraph_from_dense + >>> # G2_sparse = csr_array(G2_data) would give the wrong result + >>> G2_sparse = csgraph_from_dense(G2_data, null_value=np.inf) + >>> G2_sparse.data + array([ 2., 0., 2., 0.]) + +Here we have used a utility routine from the csgraph submodule in order to +convert the dense representation to a sparse representation which can be +understood by the algorithms in submodule. By viewing the data array, we +can see that the zero values are explicitly encoded in the graph. + +Directed vs. undirected +^^^^^^^^^^^^^^^^^^^^^^^ +Matrices may represent either directed or undirected graphs. This is +specified throughout the csgraph module by a boolean keyword. Graphs are +assumed to be directed by default. In a directed graph, traversal from node +i to node j can be accomplished over the edge G[i, j], but not the edge +G[j, i]. Consider the following dense graph:: + + >>> import numpy as np + >>> G_dense = np.array([[0, 1, 0], + ... [2, 0, 3], + ... [0, 4, 0]]) + +When ``directed=True`` we get the graph:: + + ---1--> ---3--> + (0) (1) (2) + <--2--- <--4--- + +In a non-directed graph, traversal from node i to node j can be +accomplished over either G[i, j] or G[j, i]. If both edges are not null, +and the two have unequal weights, then the smaller of the two is used. + +So for the same graph, when ``directed=False`` we get the graph:: + + (0)--1--(1)--3--(2) + +Note that a symmetric matrix will represent an undirected graph, regardless +of whether the 'directed' keyword is set to True or False. In this case, +using ``directed=True`` generally leads to more efficient computation. + +The routines in this module accept as input either scipy.sparse representations +(csr, csc, or lil format), masked representations, or dense representations +with non-edges indicated by zeros, infinities, and NaN entries. +""" # noqa: E501 + +__docformat__ = "restructuredtext en" + +__all__ = ['connected_components', + 'laplacian', + 'shortest_path', + 'floyd_warshall', + 'dijkstra', + 'bellman_ford', + 'johnson', + 'yen', + 'breadth_first_order', + 'depth_first_order', + 'breadth_first_tree', + 'depth_first_tree', + 'minimum_spanning_tree', + 'reverse_cuthill_mckee', + 'maximum_flow', + 'maximum_bipartite_matching', + 'min_weight_full_bipartite_matching', + 'structural_rank', + 'construct_dist_matrix', + 'reconstruct_path', + 'csgraph_masked_from_dense', + 'csgraph_from_dense', + 'csgraph_from_masked', + 'csgraph_to_dense', + 'csgraph_to_masked', + 'NegativeCycleError'] + +from ._laplacian import laplacian +from ._shortest_path import ( + shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson, yen, + NegativeCycleError +) +from ._traversal import ( + breadth_first_order, depth_first_order, breadth_first_tree, + depth_first_tree, connected_components +) +from ._min_spanning_tree import minimum_spanning_tree +from ._flow import maximum_flow +from ._matching import ( + maximum_bipartite_matching, min_weight_full_bipartite_matching +) +from ._reordering import reverse_cuthill_mckee, structural_rank +from ._tools import ( + construct_dist_matrix, reconstruct_path, csgraph_from_dense, + csgraph_to_dense, csgraph_masked_from_dense, csgraph_from_masked, + csgraph_to_masked +) + +from scipy._lib._testutils import PytestTester +test = PytestTester(__name__) +del PytestTester diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csgraph/_laplacian.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csgraph/_laplacian.py new file mode 100644 index 0000000000000000000000000000000000000000..e5529a0662a3f9db006bc5411664908f10d8fe23 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csgraph/_laplacian.py @@ -0,0 +1,563 @@ +""" +Laplacian of a compressed-sparse graph +""" + +import numpy as np +from scipy.sparse import issparse +from scipy.sparse.linalg import LinearOperator +from scipy.sparse._sputils import convert_pydata_sparse_to_scipy, is_pydata_spmatrix + + +############################################################################### +# Graph laplacian +def laplacian( + csgraph, + normed=False, + return_diag=False, + use_out_degree=False, + *, + copy=True, + form="array", + dtype=None, + symmetrized=False, +): + """ + Return the Laplacian of a directed graph. + + Parameters + ---------- + csgraph : array_like or sparse array or matrix, 2 dimensions + compressed-sparse graph, with shape (N, N). + normed : bool, optional + If True, then compute symmetrically normalized Laplacian. + Default: False. + return_diag : bool, optional + If True, then also return an array related to vertex degrees. + Default: False. + use_out_degree : bool, optional + If True, then use out-degree instead of in-degree. + This distinction matters only if the graph is asymmetric. + Default: False. + copy: bool, optional + If False, then change `csgraph` in place if possible, + avoiding doubling the memory use. + Default: True, for backward compatibility. + form: 'array', or 'function', or 'lo' + Determines the format of the output Laplacian: + + * 'array' is a numpy array; + * 'function' is a pointer to evaluating the Laplacian-vector + or Laplacian-matrix product; + * 'lo' results in the format of the `LinearOperator`. + + Choosing 'function' or 'lo' always avoids doubling + the memory use, ignoring `copy` value. + Default: 'array', for backward compatibility. + dtype: None or one of numeric numpy dtypes, optional + The dtype of the output. If ``dtype=None``, the dtype of the + output matches the dtype of the input csgraph, except for + the case ``normed=True`` and integer-like csgraph, where + the output dtype is 'float' allowing accurate normalization, + but dramatically increasing the memory use. + Default: None, for backward compatibility. + symmetrized: bool, optional + If True, then the output Laplacian is symmetric/Hermitian. + The symmetrization is done by ``csgraph + csgraph.T.conj`` + without dividing by 2 to preserve integer dtypes if possible + prior to the construction of the Laplacian. + The symmetrization will increase the memory footprint of + sparse matrices unless the sparsity pattern is symmetric or + `form` is 'function' or 'lo'. + Default: False, for backward compatibility. + + Returns + ------- + lap : ndarray, or sparse array or matrix, or `LinearOperator` + The N x N Laplacian of csgraph. It will be a NumPy array (dense) + if the input was dense, or a sparse array otherwise, or + the format of a function or `LinearOperator` if + `form` equals 'function' or 'lo', respectively. + diag : ndarray, optional + The length-N main diagonal of the Laplacian matrix. + For the normalized Laplacian, this is the array of square roots + of vertex degrees or 1 if the degree is zero. + + Notes + ----- + The Laplacian matrix of a graph is sometimes referred to as the + "Kirchhoff matrix" or just the "Laplacian", and is useful in many + parts of spectral graph theory. + In particular, the eigen-decomposition of the Laplacian can give + insight into many properties of the graph, e.g., + is commonly used for spectral data embedding and clustering. + + The constructed Laplacian doubles the memory use if ``copy=True`` and + ``form="array"`` which is the default. + Choosing ``copy=False`` has no effect unless ``form="array"`` + or the matrix is sparse in the ``coo`` format, or dense array, except + for the integer input with ``normed=True`` that forces the float output. + + Sparse input is reformatted into ``coo`` if ``form="array"``, + which is the default. + + If the input adjacency matrix is not symmetric, the Laplacian is + also non-symmetric unless ``symmetrized=True`` is used. + + Diagonal entries of the input adjacency matrix are ignored and + replaced with zeros for the purpose of normalization where ``normed=True``. + The normalization uses the inverse square roots of row-sums of the input + adjacency matrix, and thus may fail if the row-sums contain + negative or complex with a non-zero imaginary part values. + + The normalization is symmetric, making the normalized Laplacian also + symmetric if the input csgraph was symmetric. + + References + ---------- + .. [1] Laplacian matrix. https://en.wikipedia.org/wiki/Laplacian_matrix + + Examples + -------- + >>> import numpy as np + >>> from scipy.sparse import csgraph + + Our first illustration is the symmetric graph + + >>> G = np.arange(4) * np.arange(4)[:, np.newaxis] + >>> G + array([[0, 0, 0, 0], + [0, 1, 2, 3], + [0, 2, 4, 6], + [0, 3, 6, 9]]) + + and its symmetric Laplacian matrix + + >>> csgraph.laplacian(G) + array([[ 0, 0, 0, 0], + [ 0, 5, -2, -3], + [ 0, -2, 8, -6], + [ 0, -3, -6, 9]]) + + The non-symmetric graph + + >>> G = np.arange(9).reshape(3, 3) + >>> G + array([[0, 1, 2], + [3, 4, 5], + [6, 7, 8]]) + + has different row- and column sums, resulting in two varieties + of the Laplacian matrix, using an in-degree, which is the default + + >>> L_in_degree = csgraph.laplacian(G) + >>> L_in_degree + array([[ 9, -1, -2], + [-3, 8, -5], + [-6, -7, 7]]) + + or alternatively an out-degree + + >>> L_out_degree = csgraph.laplacian(G, use_out_degree=True) + >>> L_out_degree + array([[ 3, -1, -2], + [-3, 8, -5], + [-6, -7, 13]]) + + Constructing a symmetric Laplacian matrix, one can add the two as + + >>> L_in_degree + L_out_degree.T + array([[ 12, -4, -8], + [ -4, 16, -12], + [ -8, -12, 20]]) + + or use the ``symmetrized=True`` option + + >>> csgraph.laplacian(G, symmetrized=True) + array([[ 12, -4, -8], + [ -4, 16, -12], + [ -8, -12, 20]]) + + that is equivalent to symmetrizing the original graph + + >>> csgraph.laplacian(G + G.T) + array([[ 12, -4, -8], + [ -4, 16, -12], + [ -8, -12, 20]]) + + The goal of normalization is to make the non-zero diagonal entries + of the Laplacian matrix to be all unit, also scaling off-diagonal + entries correspondingly. The normalization can be done manually, e.g., + + >>> G = np.array([[0, 1, 1], [1, 0, 1], [1, 1, 0]]) + >>> L, d = csgraph.laplacian(G, return_diag=True) + >>> L + array([[ 2, -1, -1], + [-1, 2, -1], + [-1, -1, 2]]) + >>> d + array([2, 2, 2]) + >>> scaling = np.sqrt(d) + >>> scaling + array([1.41421356, 1.41421356, 1.41421356]) + >>> (1/scaling)*L*(1/scaling) + array([[ 1. , -0.5, -0.5], + [-0.5, 1. , -0.5], + [-0.5, -0.5, 1. ]]) + + Or using ``normed=True`` option + + >>> L, d = csgraph.laplacian(G, return_diag=True, normed=True) + >>> L + array([[ 1. , -0.5, -0.5], + [-0.5, 1. , -0.5], + [-0.5, -0.5, 1. ]]) + + which now instead of the diagonal returns the scaling coefficients + + >>> d + array([1.41421356, 1.41421356, 1.41421356]) + + Zero scaling coefficients are substituted with 1s, where scaling + has thus no effect, e.g., + + >>> G = np.array([[0, 0, 0], [0, 0, 1], [0, 1, 0]]) + >>> G + array([[0, 0, 0], + [0, 0, 1], + [0, 1, 0]]) + >>> L, d = csgraph.laplacian(G, return_diag=True, normed=True) + >>> L + array([[ 0., -0., -0.], + [-0., 1., -1.], + [-0., -1., 1.]]) + >>> d + array([1., 1., 1.]) + + Only the symmetric normalization is implemented, resulting + in a symmetric Laplacian matrix if and only if its graph is symmetric + and has all non-negative degrees, like in the examples above. + + The output Laplacian matrix is by default a dense array or a sparse + array or matrix inferring its class, shape, format, and dtype from + the input graph matrix: + + >>> G = np.array([[0, 1, 1], [1, 0, 1], [1, 1, 0]]).astype(np.float32) + >>> G + array([[0., 1., 1.], + [1., 0., 1.], + [1., 1., 0.]], dtype=float32) + >>> csgraph.laplacian(G) + array([[ 2., -1., -1.], + [-1., 2., -1.], + [-1., -1., 2.]], dtype=float32) + + but can alternatively be generated matrix-free as a LinearOperator: + + >>> L = csgraph.laplacian(G, form="lo") + >>> L + <3x3 _CustomLinearOperator with dtype=float32> + >>> L(np.eye(3)) + array([[ 2., -1., -1.], + [-1., 2., -1.], + [-1., -1., 2.]]) + + or as a lambda-function: + + >>> L = csgraph.laplacian(G, form="function") + >>> L + . at 0x0000012AE6F5A598> + >>> L(np.eye(3)) + array([[ 2., -1., -1.], + [-1., 2., -1.], + [-1., -1., 2.]]) + + The Laplacian matrix is used for + spectral data clustering and embedding + as well as for spectral graph partitioning. + Our final example illustrates the latter + for a noisy directed linear graph. + + >>> from scipy.sparse import diags_array, random_array + >>> from scipy.sparse.linalg import lobpcg + + Create a directed linear graph with ``N=35`` vertices + using a sparse adjacency matrix ``G``: + + >>> N = 35 + >>> G = diags_array(np.ones(N - 1), offsets=1, format="csr") + + Fix a random seed ``rng`` and add a random sparse noise to the graph ``G``: + + >>> rng = np.random.default_rng() + >>> G += 1e-2 * random_array((N, N), density=0.1, rng=rng) + + Set initial approximations for eigenvectors: + + >>> X = rng.random((N, 2)) + + The constant vector of ones is always a trivial eigenvector + of the non-normalized Laplacian to be filtered out: + + >>> Y = np.ones((N, 1)) + + Alternating (1) the sign of the graph weights allows determining + labels for spectral max- and min- cuts in a single loop. + Since the graph is undirected, the option ``symmetrized=True`` + must be used in the construction of the Laplacian. + The option ``normed=True`` cannot be used in (2) for the negative weights + here as the symmetric normalization evaluates square roots. + The option ``form="lo"`` in (2) is matrix-free, i.e., guarantees + a fixed memory footprint and read-only access to the graph. + Calling the eigenvalue solver ``lobpcg`` (3) computes the Fiedler vector + that determines the labels as the signs of its components in (5). + Since the sign in an eigenvector is not deterministic and can flip, + we fix the sign of the first component to be always +1 in (4). + + >>> for cut in ["max", "min"]: + ... G = -G # 1. + ... L = csgraph.laplacian(G, symmetrized=True, form="lo") # 2. + ... _, eves = lobpcg(L, X, Y=Y, largest=False, tol=1e-2) # 3. + ... eves *= np.sign(eves[0, 0]) # 4. + ... print(cut + "-cut labels:\\n", 1 * (eves[:, 0]>0)) # 5. + max-cut labels: + [1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1] + min-cut labels: + [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] + + As anticipated for a (slightly noisy) linear graph, + the max-cut strips all the edges of the graph coloring all + odd vertices into one color and all even vertices into another one, + while the balanced min-cut partitions the graph + in the middle by deleting a single edge. + Both determined partitions are optimal. + """ + is_pydata_sparse = is_pydata_spmatrix(csgraph) + if is_pydata_sparse: + pydata_sparse_cls = csgraph.__class__ + csgraph = convert_pydata_sparse_to_scipy(csgraph) + if csgraph.ndim != 2 or csgraph.shape[0] != csgraph.shape[1]: + raise ValueError('csgraph must be a square matrix or array') + + if normed and ( + np.issubdtype(csgraph.dtype, np.signedinteger) + or np.issubdtype(csgraph.dtype, np.uint) + ): + csgraph = csgraph.astype(np.float64) + + if form == "array": + create_lap = ( + _laplacian_sparse if issparse(csgraph) else _laplacian_dense + ) + else: + create_lap = ( + _laplacian_sparse_flo + if issparse(csgraph) + else _laplacian_dense_flo + ) + + degree_axis = 1 if use_out_degree else 0 + + lap, d = create_lap( + csgraph, + normed=normed, + axis=degree_axis, + copy=copy, + form=form, + dtype=dtype, + symmetrized=symmetrized, + ) + if is_pydata_sparse: + lap = pydata_sparse_cls.from_scipy_sparse(lap) + if return_diag: + return lap, d + return lap + + +def _setdiag_dense(m, d): + step = len(d) + 1 + m.flat[::step] = d + + +def _laplace(m, d): + return lambda v: v * d[:, np.newaxis] - m @ v + + +def _laplace_normed(m, d, nd): + laplace = _laplace(m, d) + return lambda v: nd[:, np.newaxis] * laplace(v * nd[:, np.newaxis]) + + +def _laplace_sym(m, d): + return ( + lambda v: v * d[:, np.newaxis] + - m @ v + - np.transpose(np.conjugate(np.transpose(np.conjugate(v)) @ m)) + ) + + +def _laplace_normed_sym(m, d, nd): + laplace_sym = _laplace_sym(m, d) + return lambda v: nd[:, np.newaxis] * laplace_sym(v * nd[:, np.newaxis]) + + +def _linearoperator(mv, shape, dtype): + return LinearOperator(matvec=mv, matmat=mv, shape=shape, dtype=dtype) + + +def _laplacian_sparse_flo(graph, normed, axis, copy, form, dtype, symmetrized): + # The keyword argument `copy` is unused and has no effect here. + del copy + + if dtype is None: + dtype = graph.dtype + + graph_sum = np.asarray(graph.sum(axis=axis)).ravel() + graph_diagonal = graph.diagonal() + diag = graph_sum - graph_diagonal + if symmetrized: + graph_sum += np.asarray(graph.sum(axis=1 - axis)).ravel() + diag = graph_sum - graph_diagonal - graph_diagonal + + if normed: + isolated_node_mask = diag == 0 + w = np.where(isolated_node_mask, 1, np.sqrt(diag)) + if symmetrized: + md = _laplace_normed_sym(graph, graph_sum, 1.0 / w) + else: + md = _laplace_normed(graph, graph_sum, 1.0 / w) + if form == "function": + return md, w.astype(dtype, copy=False) + elif form == "lo": + m = _linearoperator(md, shape=graph.shape, dtype=dtype) + return m, w.astype(dtype, copy=False) + else: + raise ValueError(f"Invalid form: {form!r}") + else: + if symmetrized: + md = _laplace_sym(graph, graph_sum) + else: + md = _laplace(graph, graph_sum) + if form == "function": + return md, diag.astype(dtype, copy=False) + elif form == "lo": + m = _linearoperator(md, shape=graph.shape, dtype=dtype) + return m, diag.astype(dtype, copy=False) + else: + raise ValueError(f"Invalid form: {form!r}") + + +def _laplacian_sparse(graph, normed, axis, copy, form, dtype, symmetrized): + # The keyword argument `form` is unused and has no effect here. + del form + + if dtype is None: + dtype = graph.dtype + + needs_copy = False + if graph.format in ('lil', 'dok'): + m = graph.tocoo() + else: + m = graph + if copy: + needs_copy = True + + if symmetrized: + m += m.T.conj() + + w = np.asarray(m.sum(axis=axis)).ravel() - m.diagonal() + if normed: + m = m.tocoo(copy=needs_copy) + isolated_node_mask = (w == 0) + w = np.where(isolated_node_mask, 1, np.sqrt(w)) + m.data /= w[m.row] + m.data /= w[m.col] + m.data *= -1 + m.setdiag(1 - isolated_node_mask) + else: + if m.format == 'dia': + m = m.copy() + else: + m = m.tocoo(copy=needs_copy) + m.data *= -1 + m.setdiag(w) + + return m.astype(dtype, copy=False), w.astype(dtype) + + +def _laplacian_dense_flo(graph, normed, axis, copy, form, dtype, symmetrized): + + if copy: + m = np.array(graph) + else: + m = np.asarray(graph) + + if dtype is None: + dtype = m.dtype + + graph_sum = m.sum(axis=axis) + graph_diagonal = m.diagonal() + diag = graph_sum - graph_diagonal + if symmetrized: + graph_sum += m.sum(axis=1 - axis) + diag = graph_sum - graph_diagonal - graph_diagonal + + if normed: + isolated_node_mask = diag == 0 + w = np.where(isolated_node_mask, 1, np.sqrt(diag)) + if symmetrized: + md = _laplace_normed_sym(m, graph_sum, 1.0 / w) + else: + md = _laplace_normed(m, graph_sum, 1.0 / w) + if form == "function": + return md, w.astype(dtype, copy=False) + elif form == "lo": + m = _linearoperator(md, shape=graph.shape, dtype=dtype) + return m, w.astype(dtype, copy=False) + else: + raise ValueError(f"Invalid form: {form!r}") + else: + if symmetrized: + md = _laplace_sym(m, graph_sum) + else: + md = _laplace(m, graph_sum) + if form == "function": + return md, diag.astype(dtype, copy=False) + elif form == "lo": + m = _linearoperator(md, shape=graph.shape, dtype=dtype) + return m, diag.astype(dtype, copy=False) + else: + raise ValueError(f"Invalid form: {form!r}") + + +def _laplacian_dense(graph, normed, axis, copy, form, dtype, symmetrized): + + if form != "array": + raise ValueError(f'{form!r} must be "array"') + + if dtype is None: + dtype = graph.dtype + + if copy: + m = np.array(graph) + else: + m = np.asarray(graph) + + if dtype is None: + dtype = m.dtype + + if symmetrized: + m += m.T.conj() + np.fill_diagonal(m, 0) + w = m.sum(axis=axis) + if normed: + isolated_node_mask = (w == 0) + w = np.where(isolated_node_mask, 1, np.sqrt(w)) + m /= w + m /= w[:, np.newaxis] + m *= -1 + _setdiag_dense(m, 1 - isolated_node_mask) + else: + m *= -1 + _setdiag_dense(m, w) + + return m.astype(dtype, copy=False), w.astype(dtype, copy=False) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csgraph/_validation.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csgraph/_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..6eb9ce811b73e751ebb1cd6b226b73f7bcfe7ceb --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csgraph/_validation.py @@ -0,0 +1,66 @@ +import numpy as np +from scipy.sparse import issparse +from scipy.sparse._sputils import convert_pydata_sparse_to_scipy +from scipy.sparse.csgraph._tools import ( + csgraph_to_dense, csgraph_from_dense, + csgraph_masked_from_dense, csgraph_from_masked +) + +DTYPE = np.float64 + + +def validate_graph(csgraph, directed, dtype=DTYPE, + csr_output=True, dense_output=True, + copy_if_dense=False, copy_if_sparse=False, + null_value_in=0, null_value_out=np.inf, + infinity_null=True, nan_null=True): + """Routine for validation and conversion of csgraph inputs""" + if not (csr_output or dense_output): + raise ValueError("Internal: dense or csr output must be true") + + accept_fv = [null_value_in] + if infinity_null: + accept_fv.append(np.inf) + if nan_null: + accept_fv.append(np.nan) + csgraph = convert_pydata_sparse_to_scipy(csgraph, accept_fv=accept_fv) + + # if undirected and csc storage, then transposing in-place + # is quicker than later converting to csr. + if (not directed) and issparse(csgraph) and csgraph.format == "csc": + csgraph = csgraph.T + + if issparse(csgraph): + if csr_output: + csgraph = csgraph.tocsr(copy=copy_if_sparse).astype(DTYPE, copy=False) + else: + csgraph = csgraph_to_dense(csgraph, null_value=null_value_out) + elif np.ma.isMaskedArray(csgraph): + if dense_output: + mask = csgraph.mask + csgraph = np.array(csgraph.data, dtype=DTYPE, copy=copy_if_dense) + csgraph[mask] = null_value_out + else: + csgraph = csgraph_from_masked(csgraph) + else: + if dense_output: + csgraph = csgraph_masked_from_dense(csgraph, + copy=copy_if_dense, + null_value=null_value_in, + nan_null=nan_null, + infinity_null=infinity_null) + mask = csgraph.mask + csgraph = np.asarray(csgraph.data, dtype=DTYPE) + csgraph[mask] = null_value_out + else: + csgraph = csgraph_from_dense(csgraph, null_value=null_value_in, + infinity_null=infinity_null, + nan_null=nan_null) + + if csgraph.ndim != 2: + raise ValueError("compressed-sparse graph must be 2-D") + + if csgraph.shape[0] != csgraph.shape[1]: + raise ValueError("compressed-sparse graph must be shape (N, N)") + + return csgraph diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_connected_components.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_connected_components.py new file mode 100644 index 0000000000000000000000000000000000000000..0b190a24deb9f2818893a120f8ea376fbfb8d6fe --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_connected_components.py @@ -0,0 +1,119 @@ +import numpy as np +from numpy.testing import assert_equal, assert_array_almost_equal +from scipy.sparse import csgraph, csr_array + + +def test_weak_connections(): + Xde = np.array([[0, 1, 0], + [0, 0, 0], + [0, 0, 0]]) + + Xsp = csgraph.csgraph_from_dense(Xde, null_value=0) + + for X in Xsp, Xde: + n_components, labels =\ + csgraph.connected_components(X, directed=True, + connection='weak') + + assert_equal(n_components, 2) + assert_array_almost_equal(labels, [0, 0, 1]) + + +def test_strong_connections(): + X1de = np.array([[0, 1, 0], + [0, 0, 0], + [0, 0, 0]]) + X2de = X1de + X1de.T + + X1sp = csgraph.csgraph_from_dense(X1de, null_value=0) + X2sp = csgraph.csgraph_from_dense(X2de, null_value=0) + + for X in X1sp, X1de: + n_components, labels =\ + csgraph.connected_components(X, directed=True, + connection='strong') + + assert_equal(n_components, 3) + labels.sort() + assert_array_almost_equal(labels, [0, 1, 2]) + + for X in X2sp, X2de: + n_components, labels =\ + csgraph.connected_components(X, directed=True, + connection='strong') + + assert_equal(n_components, 2) + labels.sort() + assert_array_almost_equal(labels, [0, 0, 1]) + + +def test_strong_connections2(): + X = np.array([[0, 0, 0, 0, 0, 0], + [1, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0], + [0, 0, 1, 0, 1, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0]]) + n_components, labels =\ + csgraph.connected_components(X, directed=True, + connection='strong') + assert_equal(n_components, 5) + labels.sort() + assert_array_almost_equal(labels, [0, 1, 2, 2, 3, 4]) + + +def test_weak_connections2(): + X = np.array([[0, 0, 0, 0, 0, 0], + [1, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0], + [0, 0, 1, 0, 1, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0]]) + n_components, labels =\ + csgraph.connected_components(X, directed=True, + connection='weak') + assert_equal(n_components, 2) + labels.sort() + assert_array_almost_equal(labels, [0, 0, 1, 1, 1, 1]) + + +def test_ticket1876(): + # Regression test: this failed in the original implementation + # There should be two strongly-connected components; previously gave one + g = np.array([[0, 1, 1, 0], + [1, 0, 0, 1], + [0, 0, 0, 1], + [0, 0, 1, 0]]) + n_components, labels = csgraph.connected_components(g, connection='strong') + + assert_equal(n_components, 2) + assert_equal(labels[0], labels[1]) + assert_equal(labels[2], labels[3]) + + +def test_fully_connected_graph(): + # Fully connected dense matrices raised an exception. + # https://github.com/scipy/scipy/issues/3818 + g = np.ones((4, 4)) + n_components, labels = csgraph.connected_components(g) + assert_equal(n_components, 1) + + +def test_int64_indices_undirected(): + # See https://github.com/scipy/scipy/issues/18716 + g = csr_array(([1], np.array([[0], [1]], dtype=np.int64)), shape=(2, 2)) + assert g.indices.dtype == np.int64 + n, labels = csgraph.connected_components(g, directed=False) + assert n == 1 + assert_array_almost_equal(labels, [0, 0]) + + +def test_int64_indices_directed(): + # See https://github.com/scipy/scipy/issues/18716 + g = csr_array(([1], np.array([[0], [1]], dtype=np.int64)), shape=(2, 2)) + assert g.indices.dtype == np.int64 + n, labels = csgraph.connected_components(g, directed=True, + connection='strong') + assert n == 2 + assert_array_almost_equal(labels, [1, 0]) + diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_conversions.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_conversions.py new file mode 100644 index 0000000000000000000000000000000000000000..65f141e5b371367018a6e9985f8325850d8972da --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_conversions.py @@ -0,0 +1,61 @@ +import numpy as np +from numpy.testing import assert_array_almost_equal +from scipy.sparse import csr_array +from scipy.sparse.csgraph import csgraph_from_dense, csgraph_to_dense + + +def test_csgraph_from_dense(): + np.random.seed(1234) + G = np.random.random((10, 10)) + some_nulls = (G < 0.4) + all_nulls = (G < 0.8) + + for null_value in [0, np.nan, np.inf]: + G[all_nulls] = null_value + with np.errstate(invalid="ignore"): + G_csr = csgraph_from_dense(G, null_value=0) + + G[all_nulls] = 0 + assert_array_almost_equal(G, G_csr.toarray()) + + for null_value in [np.nan, np.inf]: + G[all_nulls] = 0 + G[some_nulls] = null_value + with np.errstate(invalid="ignore"): + G_csr = csgraph_from_dense(G, null_value=0) + + G[all_nulls] = 0 + assert_array_almost_equal(G, G_csr.toarray()) + + +def test_csgraph_to_dense(): + np.random.seed(1234) + G = np.random.random((10, 10)) + nulls = (G < 0.8) + G[nulls] = np.inf + + G_csr = csgraph_from_dense(G) + + for null_value in [0, 10, -np.inf, np.inf]: + G[nulls] = null_value + assert_array_almost_equal(G, csgraph_to_dense(G_csr, null_value)) + + +def test_multiple_edges(): + # create a random square matrix with an even number of elements + np.random.seed(1234) + X = np.random.random((10, 10)) + Xcsr = csr_array(X) + + # now double-up every other column + Xcsr.indices[::2] = Xcsr.indices[1::2] + + # normal sparse toarray() will sum the duplicated edges + Xdense = Xcsr.toarray() + assert_array_almost_equal(Xdense[:, 1::2], + X[:, ::2] + X[:, 1::2]) + + # csgraph_to_dense chooses the minimum of each duplicated edge + Xdense = csgraph_to_dense(Xcsr) + assert_array_almost_equal(Xdense[:, 1::2], + np.minimum(X[:, ::2], X[:, 1::2])) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_flow.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_flow.py new file mode 100644 index 0000000000000000000000000000000000000000..c92eb985a1145c4b7c1777f0449bb423402f6d66 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_flow.py @@ -0,0 +1,209 @@ +import numpy as np +from numpy.testing import assert_array_equal +import pytest + +from scipy.sparse import csr_array, csc_array, csr_matrix +from scipy.sparse.csgraph import maximum_flow +from scipy.sparse.csgraph._flow import ( + _add_reverse_edges, _make_edge_pointers, _make_tails +) + +methods = ['edmonds_karp', 'dinic'] + +def test_raises_on_dense_input(): + with pytest.raises(TypeError): + graph = np.array([[0, 1], [0, 0]]) + maximum_flow(graph, 0, 1) + maximum_flow(graph, 0, 1, method='edmonds_karp') + + +def test_raises_on_csc_input(): + with pytest.raises(TypeError): + graph = csc_array([[0, 1], [0, 0]]) + maximum_flow(graph, 0, 1) + maximum_flow(graph, 0, 1, method='edmonds_karp') + + +def test_raises_on_floating_point_input(): + with pytest.raises(ValueError): + graph = csr_array([[0, 1.5], [0, 0]], dtype=np.float64) + maximum_flow(graph, 0, 1) + maximum_flow(graph, 0, 1, method='edmonds_karp') + + +def test_raises_on_non_square_input(): + with pytest.raises(ValueError): + graph = csr_array([[0, 1, 2], [2, 1, 0]]) + maximum_flow(graph, 0, 1) + + +def test_raises_when_source_is_sink(): + with pytest.raises(ValueError): + graph = csr_array([[0, 1], [0, 0]]) + maximum_flow(graph, 0, 0) + maximum_flow(graph, 0, 0, method='edmonds_karp') + + +@pytest.mark.parametrize('method', methods) +@pytest.mark.parametrize('source', [-1, 2, 3]) +def test_raises_when_source_is_out_of_bounds(source, method): + with pytest.raises(ValueError): + graph = csr_array([[0, 1], [0, 0]]) + maximum_flow(graph, source, 1, method=method) + + +@pytest.mark.parametrize('method', methods) +@pytest.mark.parametrize('sink', [-1, 2, 3]) +def test_raises_when_sink_is_out_of_bounds(sink, method): + with pytest.raises(ValueError): + graph = csr_array([[0, 1], [0, 0]]) + maximum_flow(graph, 0, sink, method=method) + + +@pytest.mark.parametrize('method', methods) +def test_simple_graph(method): + # This graph looks as follows: + # (0) --5--> (1) + graph = csr_array([[0, 5], [0, 0]]) + res = maximum_flow(graph, 0, 1, method=method) + assert res.flow_value == 5 + expected_flow = np.array([[0, 5], [-5, 0]]) + assert_array_equal(res.flow.toarray(), expected_flow) + + +@pytest.mark.parametrize('method', methods) +def test_return_type(method): + graph = csr_array([[0, 5], [0, 0]]) + assert isinstance(maximum_flow(graph, 0, 1, method=method).flow, csr_array) + graph = csr_matrix([[0, 5], [0, 0]]) + assert isinstance(maximum_flow(graph, 0, 1, method=method).flow, csr_matrix) + + +@pytest.mark.parametrize('method', methods) +def test_bottle_neck_graph(method): + # This graph cannot use the full capacity between 0 and 1: + # (0) --5--> (1) --3--> (2) + graph = csr_array([[0, 5, 0], [0, 0, 3], [0, 0, 0]]) + res = maximum_flow(graph, 0, 2, method=method) + assert res.flow_value == 3 + expected_flow = np.array([[0, 3, 0], [-3, 0, 3], [0, -3, 0]]) + assert_array_equal(res.flow.toarray(), expected_flow) + + +@pytest.mark.parametrize('method', methods) +def test_backwards_flow(method): + # This example causes backwards flow between vertices 3 and 4, + # and so this test ensures that we handle that accordingly. See + # https://stackoverflow.com/q/38843963/5085211 + # for more information. + graph = csr_array([[0, 10, 0, 0, 10, 0, 0, 0], + [0, 0, 10, 0, 0, 0, 0, 0], + [0, 0, 0, 10, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 10], + [0, 0, 0, 10, 0, 10, 0, 0], + [0, 0, 0, 0, 0, 0, 10, 0], + [0, 0, 0, 0, 0, 0, 0, 10], + [0, 0, 0, 0, 0, 0, 0, 0]]) + res = maximum_flow(graph, 0, 7, method=method) + assert res.flow_value == 20 + expected_flow = np.array([[0, 10, 0, 0, 10, 0, 0, 0], + [-10, 0, 10, 0, 0, 0, 0, 0], + [0, -10, 0, 10, 0, 0, 0, 0], + [0, 0, -10, 0, 0, 0, 0, 10], + [-10, 0, 0, 0, 0, 10, 0, 0], + [0, 0, 0, 0, -10, 0, 10, 0], + [0, 0, 0, 0, 0, -10, 0, 10], + [0, 0, 0, -10, 0, 0, -10, 0]]) + assert_array_equal(res.flow.toarray(), expected_flow) + + +@pytest.mark.parametrize('method', methods) +def test_example_from_clrs_chapter_26_1(method): + # See page 659 in CLRS second edition, but note that the maximum flow + # we find is slightly different than the one in CLRS; we push a flow of + # 12 to v_1 instead of v_2. + graph = csr_array([[0, 16, 13, 0, 0, 0], + [0, 0, 10, 12, 0, 0], + [0, 4, 0, 0, 14, 0], + [0, 0, 9, 0, 0, 20], + [0, 0, 0, 7, 0, 4], + [0, 0, 0, 0, 0, 0]]) + res = maximum_flow(graph, 0, 5, method=method) + assert res.flow_value == 23 + expected_flow = np.array([[0, 12, 11, 0, 0, 0], + [-12, 0, 0, 12, 0, 0], + [-11, 0, 0, 0, 11, 0], + [0, -12, 0, 0, -7, 19], + [0, 0, -11, 7, 0, 4], + [0, 0, 0, -19, -4, 0]]) + assert_array_equal(res.flow.toarray(), expected_flow) + + +@pytest.mark.parametrize('method', methods) +def test_disconnected_graph(method): + # This tests the following disconnected graph: + # (0) --5--> (1) (2) --3--> (3) + graph = csr_array([[0, 5, 0, 0], + [0, 0, 0, 0], + [0, 0, 9, 3], + [0, 0, 0, 0]]) + res = maximum_flow(graph, 0, 3, method=method) + assert res.flow_value == 0 + expected_flow = np.zeros((4, 4), dtype=np.int32) + assert_array_equal(res.flow.toarray(), expected_flow) + + +@pytest.mark.parametrize('method', methods) +def test_add_reverse_edges_large_graph(method): + # Regression test for https://github.com/scipy/scipy/issues/14385 + n = 100_000 + indices = np.arange(1, n) + indptr = np.array(list(range(n)) + [n - 1]) + data = np.ones(n - 1, dtype=np.int32) + graph = csr_array((data, indices, indptr), shape=(n, n)) + res = maximum_flow(graph, 0, n - 1, method=method) + assert res.flow_value == 1 + expected_flow = graph - graph.transpose() + assert_array_equal(res.flow.data, expected_flow.data) + assert_array_equal(res.flow.indices, expected_flow.indices) + assert_array_equal(res.flow.indptr, expected_flow.indptr) + + +@pytest.mark.parametrize("a,b_data_expected", [ + ([[]], []), + ([[0], [0]], []), + ([[1, 0, 2], [0, 0, 0], [0, 3, 0]], [1, 2, 0, 0, 3]), + ([[9, 8, 7], [4, 5, 6], [0, 0, 0]], [9, 8, 7, 4, 5, 6, 0, 0])]) +def test_add_reverse_edges(a, b_data_expected): + """Test that the reversal of the edges of the input graph works + as expected. + """ + a = csr_array(a, dtype=np.int32, shape=(len(a), len(a))) + b = _add_reverse_edges(a) + assert_array_equal(b.data, b_data_expected) + + +@pytest.mark.parametrize("a,expected", [ + ([[]], []), + ([[0]], []), + ([[1]], [0]), + ([[0, 1], [10, 0]], [1, 0]), + ([[1, 0, 2], [0, 0, 3], [4, 5, 0]], [0, 3, 4, 1, 2]) +]) +def test_make_edge_pointers(a, expected): + a = csr_array(a, dtype=np.int32) + rev_edge_ptr = _make_edge_pointers(a) + assert_array_equal(rev_edge_ptr, expected) + + +@pytest.mark.parametrize("a,expected", [ + ([[]], []), + ([[0]], []), + ([[1]], [0]), + ([[0, 1], [10, 0]], [0, 1]), + ([[1, 0, 2], [0, 0, 3], [4, 5, 0]], [0, 0, 1, 2, 2]) +]) +def test_make_tails(a, expected): + a = csr_array(a, dtype=np.int32) + tails = _make_tails(a) + assert_array_equal(tails, expected) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_graph_laplacian.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_graph_laplacian.py new file mode 100644 index 0000000000000000000000000000000000000000..0ed5e2edf92ef0cacc819fcbd06bc6d4e195cb44 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_graph_laplacian.py @@ -0,0 +1,368 @@ +import pytest +import numpy as np +from numpy.testing import assert_allclose +from pytest import raises as assert_raises +from scipy import sparse + +from scipy.sparse import csgraph +from scipy._lib._util import np_long, np_ulong + + +def check_int_type(mat): + return np.issubdtype(mat.dtype, np.signedinteger) or np.issubdtype( + mat.dtype, np_ulong + ) + + +def test_laplacian_value_error(): + for t in int, float, complex: + for m in ([1, 1], + [[[1]]], + [[1, 2, 3], [4, 5, 6]], + [[1, 2], [3, 4], [5, 5]]): + A = np.array(m, dtype=t) + assert_raises(ValueError, csgraph.laplacian, A) + + +def _explicit_laplacian(x, normed=False): + if sparse.issparse(x): + x = x.toarray() + x = np.asarray(x) + y = -1.0 * x + for j in range(y.shape[0]): + y[j,j] = x[j,j+1:].sum() + x[j,:j].sum() + if normed: + d = np.diag(y).copy() + d[d == 0] = 1.0 + y /= d[:,None]**.5 + y /= d[None,:]**.5 + return y + + +def _check_symmetric_graph_laplacian(mat, normed, copy=True): + if not hasattr(mat, 'shape'): + mat = eval(mat, dict(np=np, sparse=sparse)) + + if sparse.issparse(mat): + sp_mat = mat + mat = sp_mat.toarray() + else: + sp_mat = sparse.csr_array(mat) + + mat_copy = np.copy(mat) + sp_mat_copy = sparse.csr_array(sp_mat, copy=True) + + n_nodes = mat.shape[0] + explicit_laplacian = _explicit_laplacian(mat, normed=normed) + laplacian = csgraph.laplacian(mat, normed=normed, copy=copy) + sp_laplacian = csgraph.laplacian(sp_mat, normed=normed, + copy=copy) + + if copy: + assert_allclose(mat, mat_copy) + _assert_allclose_sparse(sp_mat, sp_mat_copy) + else: + if not (normed and check_int_type(mat)): + assert_allclose(laplacian, mat) + if sp_mat.format == 'coo': + _assert_allclose_sparse(sp_laplacian, sp_mat) + + assert_allclose(laplacian, sp_laplacian.toarray()) + + for tested in [laplacian, sp_laplacian.toarray()]: + if not normed: + assert_allclose(tested.sum(axis=0), np.zeros(n_nodes)) + assert_allclose(tested.T, tested) + assert_allclose(tested, explicit_laplacian) + + +def test_symmetric_graph_laplacian(): + symmetric_mats = ( + 'np.arange(10) * np.arange(10)[:, np.newaxis]', + 'np.ones((7, 7))', + 'np.eye(19)', + 'sparse.diags([1, 1], [-1, 1], shape=(4, 4))', + 'sparse.diags([1, 1], [-1, 1], shape=(4, 4)).toarray()', + 'sparse.diags([1, 1], [-1, 1], shape=(4, 4)).todense()', + 'np.vander(np.arange(4)) + np.vander(np.arange(4)).T' + ) + for mat in symmetric_mats: + for normed in True, False: + for copy in True, False: + _check_symmetric_graph_laplacian(mat, normed, copy) + + +def _assert_allclose_sparse(a, b, **kwargs): + # helper function that can deal with sparse matrices + if sparse.issparse(a): + a = a.toarray() + if sparse.issparse(b): + b = b.toarray() + assert_allclose(a, b, **kwargs) + + +def _check_laplacian_dtype_none( + A, desired_L, desired_d, normed, use_out_degree, copy, dtype, arr_type +): + mat = arr_type(A, dtype=dtype) + L, d = csgraph.laplacian( + mat, + normed=normed, + return_diag=True, + use_out_degree=use_out_degree, + copy=copy, + dtype=None, + ) + if normed and check_int_type(mat): + assert L.dtype == np.float64 + assert d.dtype == np.float64 + _assert_allclose_sparse(L, desired_L, atol=1e-12) + _assert_allclose_sparse(d, desired_d, atol=1e-12) + else: + assert L.dtype == dtype + assert d.dtype == dtype + desired_L = np.asarray(desired_L).astype(dtype) + desired_d = np.asarray(desired_d).astype(dtype) + _assert_allclose_sparse(L, desired_L, atol=1e-12) + _assert_allclose_sparse(d, desired_d, atol=1e-12) + + if not copy: + if not (normed and check_int_type(mat)): + if type(mat) is np.ndarray: + assert_allclose(L, mat) + elif mat.format == "coo": + _assert_allclose_sparse(L, mat) + + +def _check_laplacian_dtype( + A, desired_L, desired_d, normed, use_out_degree, copy, dtype, arr_type +): + mat = arr_type(A, dtype=dtype) + L, d = csgraph.laplacian( + mat, + normed=normed, + return_diag=True, + use_out_degree=use_out_degree, + copy=copy, + dtype=dtype, + ) + assert L.dtype == dtype + assert d.dtype == dtype + desired_L = np.asarray(desired_L).astype(dtype) + desired_d = np.asarray(desired_d).astype(dtype) + _assert_allclose_sparse(L, desired_L, atol=1e-12) + _assert_allclose_sparse(d, desired_d, atol=1e-12) + + if not copy: + if not (normed and check_int_type(mat)): + if type(mat) is np.ndarray: + assert_allclose(L, mat) + elif mat.format == 'coo': + _assert_allclose_sparse(L, mat) + + +INT_DTYPES = (np.intc, np_long, np.longlong) +REAL_DTYPES = (np.float32, np.float64, np.longdouble) +COMPLEX_DTYPES = (np.complex64, np.complex128, np.clongdouble) +DTYPES = INT_DTYPES + REAL_DTYPES + COMPLEX_DTYPES + + +@pytest.mark.parametrize("dtype", DTYPES) +@pytest.mark.parametrize("arr_type", [np.array, + sparse.csr_matrix, + sparse.coo_matrix, + sparse.csr_array, + sparse.coo_array]) +@pytest.mark.parametrize("copy", [True, False]) +@pytest.mark.parametrize("normed", [True, False]) +@pytest.mark.parametrize("use_out_degree", [True, False]) +def test_asymmetric_laplacian(use_out_degree, normed, + copy, dtype, arr_type): + # adjacency matrix + A = [[0, 1, 0], + [4, 2, 0], + [0, 0, 0]] + A = arr_type(np.array(A), dtype=dtype) + A_copy = A.copy() + + if not normed and use_out_degree: + # Laplacian matrix using out-degree + L = [[1, -1, 0], + [-4, 4, 0], + [0, 0, 0]] + d = [1, 4, 0] + + if normed and use_out_degree: + # normalized Laplacian matrix using out-degree + L = [[1, -0.5, 0], + [-2, 1, 0], + [0, 0, 0]] + d = [1, 2, 1] + + if not normed and not use_out_degree: + # Laplacian matrix using in-degree + L = [[4, -1, 0], + [-4, 1, 0], + [0, 0, 0]] + d = [4, 1, 0] + + if normed and not use_out_degree: + # normalized Laplacian matrix using in-degree + L = [[1, -0.5, 0], + [-2, 1, 0], + [0, 0, 0]] + d = [2, 1, 1] + + _check_laplacian_dtype_none( + A, + L, + d, + normed=normed, + use_out_degree=use_out_degree, + copy=copy, + dtype=dtype, + arr_type=arr_type, + ) + + _check_laplacian_dtype( + A_copy, + L, + d, + normed=normed, + use_out_degree=use_out_degree, + copy=copy, + dtype=dtype, + arr_type=arr_type, + ) + + +@pytest.mark.parametrize("fmt", ['csr', 'csc', 'coo', 'lil', + 'dok', 'dia', 'bsr']) +@pytest.mark.parametrize("normed", [True, False]) +@pytest.mark.parametrize("copy", [True, False]) +def test_sparse_formats(fmt, normed, copy): + mat = sparse.diags_array([1, 1], offsets=[-1, 1], shape=(4, 4), format=fmt) + _check_symmetric_graph_laplacian(mat, normed, copy) + + +@pytest.mark.parametrize( + "arr_type", [np.asarray, + sparse.csr_matrix, + sparse.coo_matrix, + sparse.csr_array, + sparse.coo_array] +) +@pytest.mark.parametrize("form", ["array", "function", "lo"]) +def test_laplacian_symmetrized(arr_type, form): + # adjacency matrix + n = 3 + mat = arr_type(np.arange(n * n).reshape(n, n)) + L_in, d_in = csgraph.laplacian( + mat, + return_diag=True, + form=form, + ) + L_out, d_out = csgraph.laplacian( + mat, + return_diag=True, + use_out_degree=True, + form=form, + ) + Ls, ds = csgraph.laplacian( + mat, + return_diag=True, + symmetrized=True, + form=form, + ) + Ls_normed, ds_normed = csgraph.laplacian( + mat, + return_diag=True, + symmetrized=True, + normed=True, + form=form, + ) + mat += mat.T + Lss, dss = csgraph.laplacian(mat, return_diag=True, form=form) + Lss_normed, dss_normed = csgraph.laplacian( + mat, + return_diag=True, + normed=True, + form=form, + ) + + assert_allclose(ds, d_in + d_out) + assert_allclose(ds, dss) + assert_allclose(ds_normed, dss_normed) + + d = {} + for L in ["L_in", "L_out", "Ls", "Ls_normed", "Lss", "Lss_normed"]: + if form == "array": + d[L] = eval(L) + else: + d[L] = eval(L)(np.eye(n, dtype=mat.dtype)) + + _assert_allclose_sparse(d["Ls"], d["L_in"] + d["L_out"].T) + _assert_allclose_sparse(d["Ls"], d["Lss"]) + _assert_allclose_sparse(d["Ls_normed"], d["Lss_normed"]) + + +@pytest.mark.parametrize( + "arr_type", [np.asarray, + sparse.csr_matrix, + sparse.coo_matrix, + sparse.csr_array, + sparse.coo_array] +) +@pytest.mark.parametrize("dtype", DTYPES) +@pytest.mark.parametrize("normed", [True, False]) +@pytest.mark.parametrize("symmetrized", [True, False]) +@pytest.mark.parametrize("use_out_degree", [True, False]) +@pytest.mark.parametrize("form", ["function", "lo"]) +def test_format(dtype, arr_type, normed, symmetrized, use_out_degree, form): + n = 3 + mat = [[0, 1, 0], [4, 2, 0], [0, 0, 0]] + mat = arr_type(np.array(mat), dtype=dtype) + Lo, do = csgraph.laplacian( + mat, + return_diag=True, + normed=normed, + symmetrized=symmetrized, + use_out_degree=use_out_degree, + dtype=dtype, + ) + La, da = csgraph.laplacian( + mat, + return_diag=True, + normed=normed, + symmetrized=symmetrized, + use_out_degree=use_out_degree, + dtype=dtype, + form="array", + ) + assert_allclose(do, da) + _assert_allclose_sparse(Lo, La) + + L, d = csgraph.laplacian( + mat, + return_diag=True, + normed=normed, + symmetrized=symmetrized, + use_out_degree=use_out_degree, + dtype=dtype, + form=form, + ) + assert_allclose(d, do) + assert d.dtype == dtype + Lm = L(np.eye(n, dtype=mat.dtype)).astype(dtype) + _assert_allclose_sparse(Lm, Lo, rtol=2e-7, atol=2e-7) + x = np.arange(6).reshape(3, 2) + if not (normed and dtype in INT_DTYPES): + assert_allclose(L(x), Lo @ x) + else: + # Normalized Lo is casted to integer, but L() is not + pass + + +def test_format_error_message(): + with pytest.raises(ValueError, match="Invalid form: 'toto'"): + _ = csgraph.laplacian(np.eye(1), form='toto') diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_matching.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_matching.py new file mode 100644 index 0000000000000000000000000000000000000000..8477861d3e563c43379c615ec0913f47a4349abd --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_matching.py @@ -0,0 +1,295 @@ +from itertools import product + +import numpy as np +from numpy.testing import assert_array_equal, assert_equal +import pytest + +from scipy.sparse import csr_array, diags_array +from scipy.sparse.csgraph import ( + maximum_bipartite_matching, min_weight_full_bipartite_matching +) + + +def test_maximum_bipartite_matching_raises_on_dense_input(): + with pytest.raises(TypeError): + graph = np.array([[0, 1], [0, 0]]) + maximum_bipartite_matching(graph) + + +def test_maximum_bipartite_matching_empty_graph(): + graph = csr_array((0, 0)) + x = maximum_bipartite_matching(graph, perm_type='row') + y = maximum_bipartite_matching(graph, perm_type='column') + expected_matching = np.array([]) + assert_array_equal(expected_matching, x) + assert_array_equal(expected_matching, y) + + +def test_maximum_bipartite_matching_empty_left_partition(): + graph = csr_array((2, 0)) + x = maximum_bipartite_matching(graph, perm_type='row') + y = maximum_bipartite_matching(graph, perm_type='column') + assert_array_equal(np.array([]), x) + assert_array_equal(np.array([-1, -1]), y) + + +def test_maximum_bipartite_matching_empty_right_partition(): + graph = csr_array((0, 3)) + x = maximum_bipartite_matching(graph, perm_type='row') + y = maximum_bipartite_matching(graph, perm_type='column') + assert_array_equal(np.array([-1, -1, -1]), x) + assert_array_equal(np.array([]), y) + + +def test_maximum_bipartite_matching_graph_with_no_edges(): + graph = csr_array((2, 2)) + x = maximum_bipartite_matching(graph, perm_type='row') + y = maximum_bipartite_matching(graph, perm_type='column') + assert_array_equal(np.array([-1, -1]), x) + assert_array_equal(np.array([-1, -1]), y) + + +def test_maximum_bipartite_matching_graph_that_causes_augmentation(): + # In this graph, column 1 is initially assigned to row 1, but it should be + # reassigned to make room for row 2. + graph = csr_array([[1, 1], [1, 0]]) + x = maximum_bipartite_matching(graph, perm_type='column') + y = maximum_bipartite_matching(graph, perm_type='row') + expected_matching = np.array([1, 0]) + assert_array_equal(expected_matching, x) + assert_array_equal(expected_matching, y) + + +def test_maximum_bipartite_matching_graph_with_more_rows_than_columns(): + graph = csr_array([[1, 1], [1, 0], [0, 1]]) + x = maximum_bipartite_matching(graph, perm_type='column') + y = maximum_bipartite_matching(graph, perm_type='row') + assert_array_equal(np.array([0, -1, 1]), x) + assert_array_equal(np.array([0, 2]), y) + + +def test_maximum_bipartite_matching_graph_with_more_columns_than_rows(): + graph = csr_array([[1, 1, 0], [0, 0, 1]]) + x = maximum_bipartite_matching(graph, perm_type='column') + y = maximum_bipartite_matching(graph, perm_type='row') + assert_array_equal(np.array([0, 2]), x) + assert_array_equal(np.array([0, -1, 1]), y) + + +def test_maximum_bipartite_matching_explicit_zeros_count_as_edges(): + data = [0, 0] + indices = [1, 0] + indptr = [0, 1, 2] + graph = csr_array((data, indices, indptr), shape=(2, 2)) + x = maximum_bipartite_matching(graph, perm_type='row') + y = maximum_bipartite_matching(graph, perm_type='column') + expected_matching = np.array([1, 0]) + assert_array_equal(expected_matching, x) + assert_array_equal(expected_matching, y) + + +def test_maximum_bipartite_matching_feasibility_of_result(): + # This is a regression test for GitHub issue #11458 + data = np.ones(50, dtype=int) + indices = [11, 12, 19, 22, 23, 5, 22, 3, 8, 10, 5, 6, 11, 12, 13, 5, 13, + 14, 20, 22, 3, 15, 3, 13, 14, 11, 12, 19, 22, 23, 5, 22, 3, 8, + 10, 5, 6, 11, 12, 13, 5, 13, 14, 20, 22, 3, 15, 3, 13, 14] + indptr = [0, 5, 7, 10, 10, 15, 20, 22, 22, 23, 25, 30, 32, 35, 35, 40, 45, + 47, 47, 48, 50] + graph = csr_array((data, indices, indptr), shape=(20, 25)) + x = maximum_bipartite_matching(graph, perm_type='row') + y = maximum_bipartite_matching(graph, perm_type='column') + assert (x != -1).sum() == 13 + assert (y != -1).sum() == 13 + # Ensure that each element of the matching is in fact an edge in the graph. + for u, v in zip(range(graph.shape[0]), y): + if v != -1: + assert graph[u, v] + for u, v in zip(x, range(graph.shape[1])): + if u != -1: + assert graph[u, v] + + +def test_matching_large_random_graph_with_one_edge_incident_to_each_vertex(): + np.random.seed(42) + A = diags_array(np.ones(25), offsets=0, format='csr') + rand_perm = np.random.permutation(25) + rand_perm2 = np.random.permutation(25) + + Rrow = np.arange(25) + Rcol = rand_perm + Rdata = np.ones(25, dtype=int) + Rmat = csr_array((Rdata, (Rrow, Rcol))) + + Crow = rand_perm2 + Ccol = np.arange(25) + Cdata = np.ones(25, dtype=int) + Cmat = csr_array((Cdata, (Crow, Ccol))) + # Randomly permute identity matrix + B = Rmat @ A @ Cmat + + # Row permute + perm = maximum_bipartite_matching(B, perm_type='row') + Rrow = np.arange(25) + Rcol = perm + Rdata = np.ones(25, dtype=int) + Rmat = csr_array((Rdata, (Rrow, Rcol))) + C1 = Rmat @ B + + # Column permute + perm2 = maximum_bipartite_matching(B, perm_type='column') + Crow = perm2 + Ccol = np.arange(25) + Cdata = np.ones(25, dtype=int) + Cmat = csr_array((Cdata, (Crow, Ccol))) + C2 = B @ Cmat + + # Should get identity matrix back + assert_equal(any(C1.diagonal() == 0), False) + assert_equal(any(C2.diagonal() == 0), False) + + +@pytest.mark.parametrize('num_rows,num_cols', [(0, 0), (2, 0), (0, 3)]) +def test_min_weight_full_matching_trivial_graph(num_rows, num_cols): + biadjacency = csr_array((num_cols, num_rows)) + row_ind, col_ind = min_weight_full_bipartite_matching(biadjacency) + assert len(row_ind) == 0 + assert len(col_ind) == 0 + + +@pytest.mark.parametrize('biadjacency', + [ + [[1, 1, 1], [1, 0, 0], [1, 0, 0]], + [[1, 1, 1], [0, 0, 1], [0, 0, 1]], + [[1, 0, 0, 1], [1, 1, 0, 1], [0, 0, 0, 0]], + [[1, 0, 0], [2, 0, 0]], + [[0, 1, 0], [0, 2, 0]], + [[1, 0], [2, 0], [5, 0]] + ]) +def test_min_weight_full_matching_infeasible_problems(biadjacency): + with pytest.raises(ValueError): + min_weight_full_bipartite_matching(csr_array(biadjacency)) + + +def test_min_weight_full_matching_large_infeasible(): + # Regression test for GitHub issue #17269 + a = np.asarray([ + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.001, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.001, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, 0.001, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, 0.0, 0.001, 0.0, 0.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.001, 0.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.001, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.001, 0.0, 0.0], + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.001, 0.0], + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.001], + [0.0, 0.11687445, 0.0, 0.0, 0.01319788, 0.07509257, 0.0, + 0.0, 0.0, 0.74228317, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 0.81087935, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 0.0, 0.8408466, 0.0, 0.0, 0.0, 0.0, 0.01194389, + 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [0.0, 0.82994211, 0.0, 0.0, 0.0, 0.11468516, 0.0, 0.0, 0.0, + 0.11173505, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0], + [0.18796507, 0.0, 0.04002318, 0.0, 0.0, 0.0, 0.0, 0.0, 0.75883335, + 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.71545464, 0.0, 0.0, 0.0, 0.0, 0.0, 0.02748488, + 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [0.78470564, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.14829198, + 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [0.0, 0.10870609, 0.0, 0.0, 0.0, 0.8918677, 0.0, 0.0, 0.0, 0.06306644, + 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, + 0.63844085, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.7442354, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.09850549, 0.0, 0.0, 0.18638258, + 0.2769244, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.73182464, 0.0, 0.0, 0.46443561, + 0.38589284, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [0.29510278, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.09666032, 0.0, + 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] + ]) + with pytest.raises(ValueError, match='no full matching exists'): + min_weight_full_bipartite_matching(csr_array(a)) + + +@pytest.mark.thread_unsafe +def test_explicit_zero_causes_warning(): + with pytest.warns(UserWarning): + biadjacency = csr_array(((2, 0, 3), (0, 1, 1), (0, 2, 3))) + min_weight_full_bipartite_matching(biadjacency) + + +# General test for linear sum assignment solvers to make it possible to rely +# on the same tests for scipy.optimize.linear_sum_assignment. +def linear_sum_assignment_assertions( + solver, array_type, sign, test_case +): + cost_matrix, expected_cost = test_case + maximize = sign == -1 + cost_matrix = sign * array_type(cost_matrix) + expected_cost = sign * np.array(expected_cost) + + row_ind, col_ind = solver(cost_matrix, maximize=maximize) + assert_array_equal(row_ind, np.sort(row_ind)) + assert_array_equal(expected_cost, + np.array(cost_matrix[row_ind, col_ind]).flatten()) + + cost_matrix = cost_matrix.T + row_ind, col_ind = solver(cost_matrix, maximize=maximize) + assert_array_equal(row_ind, np.sort(row_ind)) + assert_array_equal(np.sort(expected_cost), + np.sort(np.array( + cost_matrix[row_ind, col_ind])).flatten()) + + +linear_sum_assignment_test_cases = product( + [-1, 1], + [ + # Square + ([[400, 150, 400], + [400, 450, 600], + [300, 225, 300]], + [150, 400, 300]), + + # Rectangular variant + ([[400, 150, 400, 1], + [400, 450, 600, 2], + [300, 225, 300, 3]], + [150, 2, 300]), + + ([[10, 10, 8], + [9, 8, 1], + [9, 7, 4]], + [10, 1, 7]), + + # Square + ([[10, 10, 8, 11], + [9, 8, 1, 1], + [9, 7, 4, 10]], + [10, 1, 4]), + + # Rectangular variant + ([[10, float("inf"), float("inf")], + [float("inf"), float("inf"), 1], + [float("inf"), 7, float("inf")]], + [10, 1, 7]) + ]) + + +@pytest.mark.parametrize('sign,test_case', linear_sum_assignment_test_cases) +def test_min_weight_full_matching_small_inputs(sign, test_case): + linear_sum_assignment_assertions( + min_weight_full_bipartite_matching, csr_array, sign, test_case) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_pydata_sparse.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_pydata_sparse.py new file mode 100644 index 0000000000000000000000000000000000000000..1476c29a3ba97869c6c38be4d717641a494c1183 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_pydata_sparse.py @@ -0,0 +1,194 @@ +import pytest + +import numpy as np +import scipy.sparse as sp +import scipy.sparse.csgraph as spgraph +from scipy._lib import _pep440 + +from numpy.testing import assert_equal + +try: + import sparse +except Exception: + sparse = None + +pytestmark = pytest.mark.skipif(sparse is None, + reason="pydata/sparse not installed") + + +msg = "pydata/sparse (0.15.1) does not implement necessary operations" + + +sparse_params = (pytest.param("COO"), + pytest.param("DOK", marks=[pytest.mark.xfail(reason=msg)])) + + +def check_sparse_version(min_ver): + if sparse is None: + return pytest.mark.skip(reason="sparse is not installed") + return pytest.mark.skipif( + _pep440.parse(sparse.__version__) < _pep440.Version(min_ver), + reason=f"sparse version >= {min_ver} required" + ) + + +@pytest.fixture(params=sparse_params) +def sparse_cls(request): + return getattr(sparse, request.param) + + +@pytest.fixture +def graphs(sparse_cls): + graph = [ + [0, 1, 1, 0, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 1], + [0, 0, 0, 0, 0], + ] + A_dense = np.array(graph) + A_sparse = sparse_cls(A_dense) + return A_dense, A_sparse + + +@pytest.mark.parametrize( + "func", + [ + spgraph.shortest_path, + spgraph.dijkstra, + spgraph.floyd_warshall, + spgraph.bellman_ford, + spgraph.johnson, + spgraph.reverse_cuthill_mckee, + spgraph.maximum_bipartite_matching, + spgraph.structural_rank, + ] +) +def test_csgraph_equiv(func, graphs): + A_dense, A_sparse = graphs + actual = func(A_sparse) + desired = func(sp.csc_array(A_dense)) + assert_equal(actual, desired) + + +def test_connected_components(graphs): + A_dense, A_sparse = graphs + func = spgraph.connected_components + + actual_comp, actual_labels = func(A_sparse) + desired_comp, desired_labels, = func(sp.csc_array(A_dense)) + + assert actual_comp == desired_comp + assert_equal(actual_labels, desired_labels) + + +def test_laplacian(graphs): + A_dense, A_sparse = graphs + sparse_cls = type(A_sparse) + func = spgraph.laplacian + + actual = func(A_sparse) + desired = func(sp.csc_array(A_dense)) + + assert isinstance(actual, sparse_cls) + + assert_equal(actual.todense(), desired.todense()) + + +@pytest.mark.parametrize( + "func", [spgraph.breadth_first_order, spgraph.depth_first_order] +) +def test_order_search(graphs, func): + A_dense, A_sparse = graphs + + actual = func(A_sparse, 0) + desired = func(sp.csc_array(A_dense), 0) + + assert_equal(actual, desired) + + +@pytest.mark.parametrize( + "func", [spgraph.breadth_first_tree, spgraph.depth_first_tree] +) +def test_tree_search(graphs, func): + A_dense, A_sparse = graphs + sparse_cls = type(A_sparse) + + actual = func(A_sparse, 0) + desired = func(sp.csc_array(A_dense), 0) + + assert isinstance(actual, sparse_cls) + + assert_equal(actual.todense(), desired.todense()) + + +def test_minimum_spanning_tree(graphs): + A_dense, A_sparse = graphs + sparse_cls = type(A_sparse) + func = spgraph.minimum_spanning_tree + + actual = func(A_sparse) + desired = func(sp.csc_array(A_dense)) + + assert isinstance(actual, sparse_cls) + + assert_equal(actual.todense(), desired.todense()) + + +def test_maximum_flow(graphs): + A_dense, A_sparse = graphs + sparse_cls = type(A_sparse) + func = spgraph.maximum_flow + + actual = func(A_sparse, 0, 2) + desired = func(sp.csr_array(A_dense), 0, 2) + + assert actual.flow_value == desired.flow_value + assert isinstance(actual.flow, sparse_cls) + + assert_equal(actual.flow.todense(), desired.flow.todense()) + + +def test_min_weight_full_bipartite_matching(graphs): + A_dense, A_sparse = graphs + func = spgraph.min_weight_full_bipartite_matching + + actual = func(A_sparse[0:2, 1:3]) + desired = func(sp.csc_array(A_dense)[0:2, 1:3]) + + assert_equal(actual, desired) + + +@check_sparse_version("0.15.4") +@pytest.mark.parametrize( + "func", + [ + spgraph.shortest_path, + spgraph.dijkstra, + spgraph.floyd_warshall, + spgraph.bellman_ford, + spgraph.johnson, + spgraph.minimum_spanning_tree, + ] +) +@pytest.mark.parametrize( + "fill_value, comp_func", + [(np.inf, np.isposinf), (np.nan, np.isnan)], +) +def test_nonzero_fill_value(graphs, func, fill_value, comp_func): + A_dense, A_sparse = graphs + A_sparse = A_sparse.astype(float) + A_sparse.fill_value = fill_value + sparse_cls = type(A_sparse) + + actual = func(A_sparse) + desired = func(sp.csc_array(A_dense)) + + if func == spgraph.minimum_spanning_tree: + assert isinstance(actual, sparse_cls) + assert comp_func(actual.fill_value) + actual = actual.todense() + actual[comp_func(actual)] = 0.0 + assert_equal(actual, desired.todense()) + else: + assert_equal(actual, desired) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_reordering.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_reordering.py new file mode 100644 index 0000000000000000000000000000000000000000..add76cdc29c39c079f386a6ca73075bb90b0a6e8 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_reordering.py @@ -0,0 +1,70 @@ +import numpy as np +from numpy.testing import assert_equal +from scipy.sparse.csgraph import reverse_cuthill_mckee, structural_rank +from scipy.sparse import csc_array, csr_array, coo_array + + +def test_graph_reverse_cuthill_mckee(): + A = np.array([[1, 0, 0, 0, 1, 0, 0, 0], + [0, 1, 1, 0, 0, 1, 0, 1], + [0, 1, 1, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 1, 0], + [1, 0, 1, 0, 1, 0, 0, 0], + [0, 1, 0, 0, 0, 1, 0, 1], + [0, 0, 0, 1, 0, 0, 1, 0], + [0, 1, 0, 0, 0, 1, 0, 1]], dtype=int) + + graph = csr_array(A) + perm = reverse_cuthill_mckee(graph) + correct_perm = np.array([6, 3, 7, 5, 1, 2, 4, 0]) + assert_equal(perm, correct_perm) + + # Test int64 indices input + graph.indices = graph.indices.astype('int64') + graph.indptr = graph.indptr.astype('int64') + perm = reverse_cuthill_mckee(graph, True) + assert_equal(perm, correct_perm) + + +def test_graph_reverse_cuthill_mckee_ordering(): + data = np.ones(63,dtype=int) + rows = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, + 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, + 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, + 9, 10, 10, 10, 10, 10, 11, 11, 11, 11, + 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, + 14, 15, 15, 15, 15, 15]) + cols = np.array([0, 2, 5, 8, 10, 1, 3, 9, 11, 0, 2, + 7, 10, 1, 3, 11, 4, 6, 12, 14, 0, 7, 13, + 15, 4, 6, 14, 2, 5, 7, 15, 0, 8, 10, 13, + 1, 9, 11, 0, 2, 8, 10, 15, 1, 3, 9, 11, + 4, 12, 14, 5, 8, 13, 15, 4, 6, 12, 14, + 5, 7, 10, 13, 15]) + graph = csr_array((data, (rows,cols))) + perm = reverse_cuthill_mckee(graph) + correct_perm = np.array([12, 14, 4, 6, 10, 8, 2, 15, + 0, 13, 7, 5, 9, 11, 1, 3]) + assert_equal(perm, correct_perm) + + +def test_graph_structural_rank(): + # Test square matrix #1 + A = csc_array([[1, 1, 0], + [1, 0, 1], + [0, 1, 0]]) + assert_equal(structural_rank(A), 3) + + # Test square matrix #2 + rows = np.array([0,0,0,0,0,1,1,2,2,3,3,3,3,3,3,4,4,5,5,6,6,7,7]) + cols = np.array([0,1,2,3,4,2,5,2,6,0,1,3,5,6,7,4,5,5,6,2,6,2,4]) + data = np.ones_like(rows) + B = coo_array((data,(rows,cols)), shape=(8,8)) + assert_equal(structural_rank(B), 6) + + #Test non-square matrix + C = csc_array([[1, 0, 2, 0], + [2, 0, 4, 0]]) + assert_equal(structural_rank(C), 2) + + #Test tall matrix + assert_equal(structural_rank(C.T), 2) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_shortest_path.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_shortest_path.py new file mode 100644 index 0000000000000000000000000000000000000000..ba50f760e750ce1dbdec3624c2ab985fca1af7d1 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_shortest_path.py @@ -0,0 +1,484 @@ +from io import StringIO +import warnings +import numpy as np +from numpy.testing import assert_array_almost_equal, assert_array_equal, assert_allclose +from pytest import raises as assert_raises +from scipy.sparse.csgraph import (shortest_path, dijkstra, johnson, + bellman_ford, construct_dist_matrix, yen, + NegativeCycleError) +import scipy.sparse +from scipy.io import mmread +import pytest + +directed_G = np.array([[0, 3, 3, 0, 0], + [0, 0, 0, 2, 4], + [0, 0, 0, 0, 0], + [1, 0, 0, 0, 0], + [2, 0, 0, 2, 0]], dtype=float) + +undirected_G = np.array([[0, 3, 3, 1, 2], + [3, 0, 0, 2, 4], + [3, 0, 0, 0, 0], + [1, 2, 0, 0, 2], + [2, 4, 0, 2, 0]], dtype=float) + +unweighted_G = (directed_G > 0).astype(float) + +directed_SP = [[0, 3, 3, 5, 7], + [3, 0, 6, 2, 4], + [np.inf, np.inf, 0, np.inf, np.inf], + [1, 4, 4, 0, 8], + [2, 5, 5, 2, 0]] + +directed_2SP_0_to_3 = [[-9999, 0, -9999, 1, -9999], + [-9999, 0, -9999, 4, 1]] + +directed_sparse_zero_G = scipy.sparse.csr_array( + ( + [0, 1, 2, 3, 1], + ([0, 1, 2, 3, 4], [1, 2, 0, 4, 3]), + ), + shape=(5, 5), +) + +directed_sparse_zero_SP = [[0, 0, 1, np.inf, np.inf], + [3, 0, 1, np.inf, np.inf], + [2, 2, 0, np.inf, np.inf], + [np.inf, np.inf, np.inf, 0, 3], + [np.inf, np.inf, np.inf, 1, 0]] + +undirected_sparse_zero_G = scipy.sparse.csr_array( + ( + [0, 0, 1, 1, 2, 2, 1, 1], + ([0, 1, 1, 2, 2, 0, 3, 4], [1, 0, 2, 1, 0, 2, 4, 3]) + ), + shape=(5, 5), +) + +undirected_sparse_zero_SP = [[0, 0, 1, np.inf, np.inf], + [0, 0, 1, np.inf, np.inf], + [1, 1, 0, np.inf, np.inf], + [np.inf, np.inf, np.inf, 0, 1], + [np.inf, np.inf, np.inf, 1, 0]] + +directed_pred = np.array([[-9999, 0, 0, 1, 1], + [3, -9999, 0, 1, 1], + [-9999, -9999, -9999, -9999, -9999], + [3, 0, 0, -9999, 1], + [4, 0, 0, 4, -9999]], dtype=float) + +undirected_SP = np.array([[0, 3, 3, 1, 2], + [3, 0, 6, 2, 4], + [3, 6, 0, 4, 5], + [1, 2, 4, 0, 2], + [2, 4, 5, 2, 0]], dtype=float) + +undirected_SP_limit_2 = np.array([[0, np.inf, np.inf, 1, 2], + [np.inf, 0, np.inf, 2, np.inf], + [np.inf, np.inf, 0, np.inf, np.inf], + [1, 2, np.inf, 0, 2], + [2, np.inf, np.inf, 2, 0]], dtype=float) + +undirected_SP_limit_0 = np.ones((5, 5), dtype=float) - np.eye(5) +undirected_SP_limit_0[undirected_SP_limit_0 > 0] = np.inf + +undirected_pred = np.array([[-9999, 0, 0, 0, 0], + [1, -9999, 0, 1, 1], + [2, 0, -9999, 0, 0], + [3, 3, 0, -9999, 3], + [4, 4, 0, 4, -9999]], dtype=float) + +directed_negative_weighted_G = np.array([[0, 0, 0], + [-1, 0, 0], + [0, -1, 0]], dtype=float) + +directed_negative_weighted_SP = np.array([[0, np.inf, np.inf], + [-1, 0, np.inf], + [-2, -1, 0]], dtype=float) + +methods = ['auto', 'FW', 'D', 'BF', 'J'] + + +def test_dijkstra_limit(): + limits = [0, 2, np.inf] + results = [undirected_SP_limit_0, + undirected_SP_limit_2, + undirected_SP] + + def check(limit, result): + SP = dijkstra(undirected_G, directed=False, limit=limit) + assert_array_almost_equal(SP, result) + + for limit, result in zip(limits, results): + check(limit, result) + + +def test_directed(): + def check(method): + SP = shortest_path(directed_G, method=method, directed=True, + overwrite=False) + assert_array_almost_equal(SP, directed_SP) + + for method in methods: + check(method) + + +def test_undirected(): + def check(method, directed_in): + if directed_in: + SP1 = shortest_path(directed_G, method=method, directed=False, + overwrite=False) + assert_array_almost_equal(SP1, undirected_SP) + else: + SP2 = shortest_path(undirected_G, method=method, directed=True, + overwrite=False) + assert_array_almost_equal(SP2, undirected_SP) + + for method in methods: + for directed_in in (True, False): + check(method, directed_in) + + +def test_directed_sparse_zero(): + # test directed sparse graph with zero-weight edge and two connected components + def check(method): + SP = shortest_path(directed_sparse_zero_G, method=method, directed=True, + overwrite=False) + assert_array_almost_equal(SP, directed_sparse_zero_SP) + + for method in methods: + check(method) + + +def test_undirected_sparse_zero(): + def check(method, directed_in): + if directed_in: + SP1 = shortest_path(directed_sparse_zero_G, method=method, directed=False, + overwrite=False) + assert_array_almost_equal(SP1, undirected_sparse_zero_SP) + else: + SP2 = shortest_path(undirected_sparse_zero_G, method=method, directed=True, + overwrite=False) + assert_array_almost_equal(SP2, undirected_sparse_zero_SP) + + for method in methods: + for directed_in in (True, False): + check(method, directed_in) + + +@pytest.mark.parametrize('directed, SP_ans', + ((True, directed_SP), + (False, undirected_SP))) +@pytest.mark.parametrize('indices', ([0, 2, 4], [0, 4], [3, 4], [0, 0])) +def test_dijkstra_indices_min_only(directed, SP_ans, indices): + SP_ans = np.array(SP_ans) + indices = np.array(indices, dtype=np.int64) + min_ind_ans = indices[np.argmin(SP_ans[indices, :], axis=0)] + min_d_ans = np.zeros(SP_ans.shape[0], SP_ans.dtype) + for k in range(SP_ans.shape[0]): + min_d_ans[k] = SP_ans[min_ind_ans[k], k] + min_ind_ans[np.isinf(min_d_ans)] = -9999 + + SP, pred, sources = dijkstra(directed_G, + directed=directed, + indices=indices, + min_only=True, + return_predecessors=True) + assert_array_almost_equal(SP, min_d_ans) + assert_array_equal(min_ind_ans, sources) + SP = dijkstra(directed_G, + directed=directed, + indices=indices, + min_only=True, + return_predecessors=False) + assert_array_almost_equal(SP, min_d_ans) + + +@pytest.mark.parametrize('n', (10, 100, 1000)) +def test_dijkstra_min_only_random(n): + rng = np.random.default_rng(7345782358920239234) + data = scipy.sparse.random_array((n, n), density=0.5, format='lil', + rng=rng, dtype=np.float64) + data.setdiag(np.zeros(n, dtype=np.bool_)) + # choose some random vertices + v = np.arange(n) + rng.shuffle(v) + indices = v[:int(n*.1)] + ds, pred, sources = dijkstra(data, + directed=True, + indices=indices, + min_only=True, + return_predecessors=True) + for k in range(n): + p = pred[k] + s = sources[k] + while p != -9999: + assert sources[p] == s + p = pred[p] + + +def test_dijkstra_random(): + # reproduces the hang observed in gh-17782 + n = 10 + indices = [0, 4, 4, 5, 7, 9, 0, 6, 2, 3, 7, 9, 1, 2, 9, 2, 5, 6] + indptr = [0, 0, 2, 5, 6, 7, 8, 12, 15, 18, 18] + data = [0.33629, 0.40458, 0.47493, 0.42757, 0.11497, 0.91653, 0.69084, + 0.64979, 0.62555, 0.743, 0.01724, 0.99945, 0.31095, 0.15557, + 0.02439, 0.65814, 0.23478, 0.24072] + graph = scipy.sparse.csr_array((data, indices, indptr), shape=(n, n)) + dijkstra(graph, directed=True, return_predecessors=True) + + +def test_gh_17782_segfault(): + text = """%%MatrixMarket matrix coordinate real general + 84 84 22 + 2 1 4.699999809265137e+00 + 6 14 1.199999973177910e-01 + 9 6 1.199999973177910e-01 + 10 16 2.012000083923340e+01 + 11 10 1.422000026702881e+01 + 12 1 9.645999908447266e+01 + 13 18 2.012000083923340e+01 + 14 13 4.679999828338623e+00 + 15 11 1.199999973177910e-01 + 16 12 1.199999973177910e-01 + 18 15 1.199999973177910e-01 + 32 2 2.299999952316284e+00 + 33 20 6.000000000000000e+00 + 33 32 5.000000000000000e+00 + 36 9 3.720000028610229e+00 + 36 37 3.720000028610229e+00 + 36 38 3.720000028610229e+00 + 37 44 8.159999847412109e+00 + 38 32 7.903999328613281e+01 + 43 20 2.400000000000000e+01 + 43 33 4.000000000000000e+00 + 44 43 6.028000259399414e+01 + """ + data = mmread(StringIO(text), spmatrix=False) + dijkstra(data, directed=True, return_predecessors=True) + + +def test_shortest_path_indices(): + indices = np.arange(4) + + def check(func, indshape): + outshape = indshape + (5,) + SP = func(directed_G, directed=False, + indices=indices.reshape(indshape)) + assert_array_almost_equal(SP, undirected_SP[indices].reshape(outshape)) + + for indshape in [(4,), (4, 1), (2, 2)]: + for func in (dijkstra, bellman_ford, johnson, shortest_path): + check(func, indshape) + + assert_raises(ValueError, shortest_path, directed_G, method='FW', + indices=indices) + + +def test_predecessors(): + SP_res = {True: directed_SP, + False: undirected_SP} + pred_res = {True: directed_pred, + False: undirected_pred} + + def check(method, directed): + SP, pred = shortest_path(directed_G, method, directed=directed, + overwrite=False, + return_predecessors=True) + assert_array_almost_equal(SP, SP_res[directed]) + assert_array_almost_equal(pred, pred_res[directed]) + + for method in methods: + for directed in (True, False): + check(method, directed) + + +def test_construct_shortest_path(): + def check(method, directed): + SP1, pred = shortest_path(directed_G, + directed=directed, + overwrite=False, + return_predecessors=True) + SP2 = construct_dist_matrix(directed_G, pred, directed=directed) + assert_array_almost_equal(SP1, SP2) + + for method in methods: + for directed in (True, False): + check(method, directed) + + +def test_unweighted_path(): + def check(method, directed): + SP1 = shortest_path(directed_G, + directed=directed, + overwrite=False, + unweighted=True) + SP2 = shortest_path(unweighted_G, + directed=directed, + overwrite=False, + unweighted=False) + assert_array_almost_equal(SP1, SP2) + + for method in methods: + for directed in (True, False): + check(method, directed) + + +def test_negative_cycles(): + # create a small graph with a negative cycle + graph = np.ones([5, 5]) + graph.flat[::6] = 0 + graph[1, 2] = -2 + + def check(method, directed): + assert_raises(NegativeCycleError, shortest_path, graph, method, + directed) + + for directed in (True, False): + for method in ['FW', 'J', 'BF']: + check(method, directed) + + assert_raises(NegativeCycleError, yen, graph, 0, 1, 1, + directed=directed) + + +@pytest.mark.parametrize("method", ['FW', 'J', 'BF']) +def test_negative_weights(method): + SP = shortest_path(directed_negative_weighted_G, method, directed=True) + assert_allclose(SP, directed_negative_weighted_SP, atol=1e-10) + + +def test_masked_input(): + np.ma.masked_equal(directed_G, 0) + + def check(method): + SP = shortest_path(directed_G, method=method, directed=True, + overwrite=False) + assert_array_almost_equal(SP, directed_SP) + + for method in methods: + check(method) + + +def test_overwrite(): + G = np.array([[0, 3, 3, 1, 2], + [3, 0, 0, 2, 4], + [3, 0, 0, 0, 0], + [1, 2, 0, 0, 2], + [2, 4, 0, 2, 0]], dtype=float) + foo = G.copy() + shortest_path(foo, overwrite=False) + assert_array_equal(foo, G) + + +@pytest.mark.parametrize('method', methods) +def test_buffer(method): + # Smoke test that sparse matrices with read-only buffers (e.g., those from + # joblib workers) do not cause:: + # + # ValueError: buffer source array is read-only + # + G = scipy.sparse.csr_array([[1.]]) + G.data.flags['WRITEABLE'] = False + shortest_path(G, method=method) + + +def test_NaN_warnings(): + with warnings.catch_warnings(record=True) as record: + shortest_path(np.array([[0, 1], [np.nan, 0]])) + for r in record: + assert r.category is not RuntimeWarning + + +def test_sparse_matrices(): + # Test that using lil,csr and csc sparse matrix do not cause error + G_dense = np.array([[0, 3, 0, 0, 0], + [0, 0, -1, 0, 0], + [0, 0, 0, 2, 0], + [0, 0, 0, 0, 4], + [0, 0, 0, 0, 0]], dtype=float) + SP = shortest_path(G_dense) + G_csr = scipy.sparse.csr_array(G_dense) + G_csc = scipy.sparse.csc_array(G_dense) + G_lil = scipy.sparse.lil_array(G_dense) + assert_array_almost_equal(SP, shortest_path(G_csr)) + assert_array_almost_equal(SP, shortest_path(G_csc)) + assert_array_almost_equal(SP, shortest_path(G_lil)) + + +def test_yen_directed(): + distances, predecessors = yen( + directed_G, + source=0, + sink=3, + K=2, + return_predecessors=True + ) + assert_allclose(distances, [5., 9.]) + assert_allclose(predecessors, directed_2SP_0_to_3) + + +def test_yen_undirected(): + distances = yen( + undirected_G, + source=0, + sink=3, + K=4, + ) + assert_allclose(distances, [1., 4., 5., 8.]) + +def test_yen_unweighted(): + # Ask for more paths than there are, verify only the available paths are returned + distances, predecessors = yen( + directed_G, + source=0, + sink=3, + K=4, + unweighted=True, + return_predecessors=True, + ) + assert_allclose(distances, [2., 3.]) + assert_allclose(predecessors, directed_2SP_0_to_3) + +def test_yen_no_paths(): + distances = yen( + directed_G, + source=2, + sink=3, + K=1, + ) + assert distances.size == 0 + +def test_yen_negative_weights(): + distances = yen( + directed_negative_weighted_G, + source=2, + sink=0, + K=1, + ) + assert_allclose(distances, [-2.]) + + +@pytest.mark.parametrize("min_only", (True, False)) +@pytest.mark.parametrize("directed", (True, False)) +@pytest.mark.parametrize("return_predecessors", (True, False)) +@pytest.mark.parametrize("index_dtype", (np.int32, np.int64)) +@pytest.mark.parametrize("indices", (None, [1])) +def test_20904(min_only, directed, return_predecessors, index_dtype, indices): + """Test two failures from gh-20904: int32 and indices-as-None.""" + adj_mat = scipy.sparse.eye_array(4, format="csr") + adj_mat = scipy.sparse.csr_array( + ( + adj_mat.data, + adj_mat.indices.astype(index_dtype), + adj_mat.indptr.astype(index_dtype), + ), + ) + dijkstra( + adj_mat, + directed, + indices=indices, + min_only=min_only, + return_predecessors=return_predecessors, + ) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csr.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csr.py new file mode 100644 index 0000000000000000000000000000000000000000..86bb1e072ebe4480e9dcb01f2d36f7387872b898 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csr.py @@ -0,0 +1,27 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.sparse` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'csr_count_blocks', + 'csr_matrix', + 'csr_tobsr', + 'csr_tocsc', + 'get_csr_submatrix', + 'isspmatrix_csr', + 'spmatrix', + 'upcast', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="sparse", module="csr", + private_modules=["_csr"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/data.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/data.py new file mode 100644 index 0000000000000000000000000000000000000000..a9958bcda6dd35ac0779514d79b7f1c494c1b01a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/data.py @@ -0,0 +1,23 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.sparse` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'isscalarlike', + 'name', + 'npfunc', + 'validateaxis', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="sparse", module="data", + private_modules=["_data"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/dia.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/dia.py new file mode 100644 index 0000000000000000000000000000000000000000..f79abd39f114b23df8ceb6eafb7fcc1c07218dcb --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/dia.py @@ -0,0 +1,29 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.sparse` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'check_shape', + 'dia_matrix', + 'dia_matvec', + 'get_sum_dtype', + 'getdtype', + 'isshape', + 'isspmatrix_dia', + 'spmatrix', + 'upcast_char', + 'validateaxis', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="sparse", module="dia", + private_modules=["_dia"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/dok.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/dok.py new file mode 100644 index 0000000000000000000000000000000000000000..847824456eaa3145d5ecb078e30251875168775b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/dok.py @@ -0,0 +1,32 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.sparse` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'IndexMixin', + 'check_shape', + 'dok_matrix', + 'getdtype', + 'isdense', + 'isintlike', + 'isscalarlike', + 'isshape', + 'isspmatrix_dok', + 'itertools', + 'spmatrix', + 'upcast', + 'upcast_scalar', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="sparse", module="dok", + private_modules=["_dok"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/extract.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/extract.py new file mode 100644 index 0000000000000000000000000000000000000000..be5e161b6f99e57e2b2a6b3d4f1ef6427c07658d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/extract.py @@ -0,0 +1,23 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.sparse` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'coo_matrix', + 'find', + 'tril', + 'triu', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="sparse", module="extract", + private_modules=["_extract"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/lil.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/lil.py new file mode 100644 index 0000000000000000000000000000000000000000..5f7bf8eb03bb36a1b2fa77c5fc0840e532ab64fd --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/lil.py @@ -0,0 +1,22 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.sparse` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'isspmatrix_lil', + 'lil_array', + 'lil_matrix', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="sparse", module="lil", + private_modules=["_lil"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/sparsetools.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/sparsetools.py new file mode 100644 index 0000000000000000000000000000000000000000..404e431d89d479520d2198ae73b9eab7b23a80f7 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/sparsetools.py @@ -0,0 +1,17 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.sparse` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__: list[str] = [] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="sparse", module="sparsetools", + private_modules=["_sparsetools"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/spfuncs.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/spfuncs.py new file mode 100644 index 0000000000000000000000000000000000000000..911969e414d4a1d3888900ad8392b5fc2177c850 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/spfuncs.py @@ -0,0 +1,17 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.sparse` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__: list[str] = [] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="sparse", module="spfuncs", + private_modules=["_spfuncs"], all=__all__, + attribute=name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/sputils.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/sputils.py new file mode 100644 index 0000000000000000000000000000000000000000..4ddd27a43889609b0642bd7579e13c8e3c460a8b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/sputils.py @@ -0,0 +1,17 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.sparse` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__: list[str] = [] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="sparse", module="sputils", + private_modules=["_sputils"], all=__all__, + attribute=name)