jasonfan commited on
Commit
5c1ef06
·
verified ·
1 Parent(s): f723ecc

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_spanning_tree.py +66 -0
  2. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_traversal.py +148 -0
  3. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/__init__.py +148 -0
  4. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_dsolve/__init__.py +71 -0
  5. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_dsolve/_add_newdocs.py +147 -0
  6. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_dsolve/linsolve.py +873 -0
  7. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_dsolve/tests/__init__.py +0 -0
  8. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_dsolve/tests/test_linsolve.py +921 -0
  9. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/__init__.py +22 -0
  10. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/_svds.py +540 -0
  11. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/_svds_doc.py +382 -0
  12. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/arpack/COPYING +45 -0
  13. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/arpack/__init__.py +20 -0
  14. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/arpack/arpack.py +1700 -0
  15. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/arpack/tests/__init__.py +0 -0
  16. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/arpack/tests/test_arpack.py +717 -0
  17. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/lobpcg/__init__.py +16 -0
  18. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/lobpcg/lobpcg.py +1110 -0
  19. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/lobpcg/tests/__init__.py +0 -0
  20. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/lobpcg/tests/test_lobpcg.py +725 -0
  21. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/tests/__init__.py +0 -0
  22. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/tests/test_svds.py +886 -0
  23. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_expm_multiply.py +816 -0
  24. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_interface.py +921 -0
  25. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__init__.py +20 -0
  26. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/_gcrotmk.py +503 -0
  27. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/iterative.py +1045 -0
  28. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/lgmres.py +230 -0
  29. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/lsmr.py +486 -0
  30. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/lsqr.py +589 -0
  31. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/minres.py +372 -0
  32. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/__init__.py +0 -0
  33. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_gcrotmk.py +183 -0
  34. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_iterative.py +809 -0
  35. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_lgmres.py +225 -0
  36. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_lsmr.py +185 -0
  37. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_lsqr.py +120 -0
  38. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_minres.py +97 -0
  39. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_utils.py +9 -0
  40. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tfqmr.py +179 -0
  41. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/utils.py +127 -0
  42. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_matfuncs.py +940 -0
  43. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_norm.py +195 -0
  44. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_onenormest.py +467 -0
  45. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_special_sparse_arrays.py +948 -0
  46. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_svdp.py +309 -0
  47. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/dsolve.py +22 -0
  48. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/eigen.py +21 -0
  49. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/interface.py +20 -0
  50. miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/isolve.py +22 -0
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_spanning_tree.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Test the minimum spanning tree function"""
2
+ import numpy as np
3
+ from numpy.testing import assert_
4
+ import numpy.testing as npt
5
+ from scipy.sparse import csr_array
6
+ from scipy.sparse.csgraph import minimum_spanning_tree
7
+
8
+
9
+ def test_minimum_spanning_tree():
10
+
11
+ # Create a graph with two connected components.
12
+ graph = [[0,1,0,0,0],
13
+ [1,0,0,0,0],
14
+ [0,0,0,8,5],
15
+ [0,0,8,0,1],
16
+ [0,0,5,1,0]]
17
+ graph = np.asarray(graph)
18
+
19
+ # Create the expected spanning tree.
20
+ expected = [[0,1,0,0,0],
21
+ [0,0,0,0,0],
22
+ [0,0,0,0,5],
23
+ [0,0,0,0,1],
24
+ [0,0,0,0,0]]
25
+ expected = np.asarray(expected)
26
+
27
+ # Ensure minimum spanning tree code gives this expected output.
28
+ csgraph = csr_array(graph)
29
+ mintree = minimum_spanning_tree(csgraph)
30
+ mintree_array = mintree.toarray()
31
+ npt.assert_array_equal(mintree_array, expected,
32
+ 'Incorrect spanning tree found.')
33
+
34
+ # Ensure that the original graph was not modified.
35
+ npt.assert_array_equal(csgraph.toarray(), graph,
36
+ 'Original graph was modified.')
37
+
38
+ # Now let the algorithm modify the csgraph in place.
39
+ mintree = minimum_spanning_tree(csgraph, overwrite=True)
40
+ npt.assert_array_equal(mintree.toarray(), expected,
41
+ 'Graph was not properly modified to contain MST.')
42
+
43
+ np.random.seed(1234)
44
+ for N in (5, 10, 15, 20):
45
+
46
+ # Create a random graph.
47
+ graph = 3 + np.random.random((N, N))
48
+ csgraph = csr_array(graph)
49
+
50
+ # The spanning tree has at most N - 1 edges.
51
+ mintree = minimum_spanning_tree(csgraph)
52
+ assert_(mintree.nnz < N)
53
+
54
+ # Set the sub diagonal to 1 to create a known spanning tree.
55
+ idx = np.arange(N-1)
56
+ graph[idx,idx+1] = 1
57
+ csgraph = csr_array(graph)
58
+ mintree = minimum_spanning_tree(csgraph)
59
+
60
+ # We expect to see this pattern in the spanning tree and otherwise
61
+ # have this zero.
62
+ expected = np.zeros((N, N))
63
+ expected[idx, idx+1] = 1
64
+
65
+ npt.assert_array_equal(mintree.toarray(), expected,
66
+ 'Incorrect spanning tree found.')
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_traversal.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+ from numpy.testing import assert_array_almost_equal
4
+ from scipy.sparse import csr_array, csr_matrix, coo_array, coo_matrix
5
+ from scipy.sparse.csgraph import (breadth_first_tree, depth_first_tree,
6
+ csgraph_to_dense, csgraph_from_dense, csgraph_masked_from_dense)
7
+
8
+
9
+ def test_graph_breadth_first():
10
+ csgraph = np.array([[0, 1, 2, 0, 0],
11
+ [1, 0, 0, 0, 3],
12
+ [2, 0, 0, 7, 0],
13
+ [0, 0, 7, 0, 1],
14
+ [0, 3, 0, 1, 0]])
15
+ csgraph = csgraph_from_dense(csgraph, null_value=0)
16
+
17
+ bfirst = np.array([[0, 1, 2, 0, 0],
18
+ [0, 0, 0, 0, 3],
19
+ [0, 0, 0, 7, 0],
20
+ [0, 0, 0, 0, 0],
21
+ [0, 0, 0, 0, 0]])
22
+
23
+ for directed in [True, False]:
24
+ bfirst_test = breadth_first_tree(csgraph, 0, directed)
25
+ assert_array_almost_equal(csgraph_to_dense(bfirst_test),
26
+ bfirst)
27
+
28
+
29
+ def test_graph_depth_first():
30
+ csgraph = np.array([[0, 1, 2, 0, 0],
31
+ [1, 0, 0, 0, 3],
32
+ [2, 0, 0, 7, 0],
33
+ [0, 0, 7, 0, 1],
34
+ [0, 3, 0, 1, 0]])
35
+ csgraph = csgraph_from_dense(csgraph, null_value=0)
36
+
37
+ dfirst = np.array([[0, 1, 0, 0, 0],
38
+ [0, 0, 0, 0, 3],
39
+ [0, 0, 0, 0, 0],
40
+ [0, 0, 7, 0, 0],
41
+ [0, 0, 0, 1, 0]])
42
+
43
+ for directed in [True, False]:
44
+ dfirst_test = depth_first_tree(csgraph, 0, directed)
45
+ assert_array_almost_equal(csgraph_to_dense(dfirst_test), dfirst)
46
+
47
+
48
+ def test_return_type():
49
+ from .._laplacian import laplacian
50
+ from .._min_spanning_tree import minimum_spanning_tree
51
+
52
+ np_csgraph = np.array([[0, 1, 2, 0, 0],
53
+ [1, 0, 0, 0, 3],
54
+ [2, 0, 0, 7, 0],
55
+ [0, 0, 7, 0, 1],
56
+ [0, 3, 0, 1, 0]])
57
+ csgraph = csr_array(np_csgraph)
58
+ assert isinstance(laplacian(csgraph), coo_array)
59
+ assert isinstance(minimum_spanning_tree(csgraph), csr_array)
60
+ for directed in [True, False]:
61
+ assert isinstance(depth_first_tree(csgraph, 0, directed), csr_array)
62
+ assert isinstance(breadth_first_tree(csgraph, 0, directed), csr_array)
63
+
64
+ csgraph = csgraph_from_dense(np_csgraph, null_value=0)
65
+ assert isinstance(csgraph, csr_array)
66
+ assert isinstance(laplacian(csgraph), coo_array)
67
+ assert isinstance(minimum_spanning_tree(csgraph), csr_array)
68
+ for directed in [True, False]:
69
+ assert isinstance(depth_first_tree(csgraph, 0, directed), csr_array)
70
+ assert isinstance(breadth_first_tree(csgraph, 0, directed), csr_array)
71
+
72
+ csgraph = csgraph_masked_from_dense(np_csgraph, null_value=0)
73
+ assert isinstance(csgraph, np.ma.MaskedArray)
74
+ assert csgraph._baseclass is np.ndarray
75
+ # laplacian doesnt work with masked arrays so not here
76
+ assert isinstance(minimum_spanning_tree(csgraph), csr_array)
77
+ for directed in [True, False]:
78
+ assert isinstance(depth_first_tree(csgraph, 0, directed), csr_array)
79
+ assert isinstance(breadth_first_tree(csgraph, 0, directed), csr_array)
80
+
81
+ # start of testing with matrix/spmatrix types
82
+ with np.testing.suppress_warnings() as sup:
83
+ sup.filter(DeprecationWarning, "the matrix subclass.*")
84
+ sup.filter(PendingDeprecationWarning, "the matrix subclass.*")
85
+
86
+ nm_csgraph = np.matrix([[0, 1, 2, 0, 0],
87
+ [1, 0, 0, 0, 3],
88
+ [2, 0, 0, 7, 0],
89
+ [0, 0, 7, 0, 1],
90
+ [0, 3, 0, 1, 0]])
91
+
92
+ csgraph = csr_matrix(nm_csgraph)
93
+ assert isinstance(laplacian(csgraph), coo_matrix)
94
+ assert isinstance(minimum_spanning_tree(csgraph), csr_matrix)
95
+ for directed in [True, False]:
96
+ assert isinstance(depth_first_tree(csgraph, 0, directed), csr_matrix)
97
+ assert isinstance(breadth_first_tree(csgraph, 0, directed), csr_matrix)
98
+
99
+ csgraph = csgraph_from_dense(nm_csgraph, null_value=0)
100
+ assert isinstance(csgraph, csr_matrix)
101
+ assert isinstance(laplacian(csgraph), coo_matrix)
102
+ assert isinstance(minimum_spanning_tree(csgraph), csr_matrix)
103
+ for directed in [True, False]:
104
+ assert isinstance(depth_first_tree(csgraph, 0, directed), csr_matrix)
105
+ assert isinstance(breadth_first_tree(csgraph, 0, directed), csr_matrix)
106
+
107
+ mm_csgraph = csgraph_masked_from_dense(nm_csgraph, null_value=0)
108
+ assert isinstance(mm_csgraph, np.ma.MaskedArray)
109
+ # laplacian doesnt work with masked arrays so not here
110
+ assert isinstance(minimum_spanning_tree(csgraph), csr_matrix)
111
+ for directed in [True, False]:
112
+ assert isinstance(depth_first_tree(csgraph, 0, directed), csr_matrix)
113
+ assert isinstance(breadth_first_tree(csgraph, 0, directed), csr_matrix)
114
+ # end of testing with matrix/spmatrix types
115
+
116
+
117
+ def test_graph_breadth_first_trivial_graph():
118
+ csgraph = np.array([[0]])
119
+ csgraph = csgraph_from_dense(csgraph, null_value=0)
120
+
121
+ bfirst = np.array([[0]])
122
+
123
+ for directed in [True, False]:
124
+ bfirst_test = breadth_first_tree(csgraph, 0, directed)
125
+ assert_array_almost_equal(csgraph_to_dense(bfirst_test), bfirst)
126
+
127
+
128
+ def test_graph_depth_first_trivial_graph():
129
+ csgraph = np.array([[0]])
130
+ csgraph = csgraph_from_dense(csgraph, null_value=0)
131
+
132
+ bfirst = np.array([[0]])
133
+
134
+ for directed in [True, False]:
135
+ bfirst_test = depth_first_tree(csgraph, 0, directed)
136
+ assert_array_almost_equal(csgraph_to_dense(bfirst_test),
137
+ bfirst)
138
+
139
+
140
+ @pytest.mark.parametrize('directed', [True, False])
141
+ @pytest.mark.parametrize('tree_func', [breadth_first_tree, depth_first_tree])
142
+ def test_int64_indices(tree_func, directed):
143
+ # See https://github.com/scipy/scipy/issues/18716
144
+ g = csr_array(([1], np.array([[0], [1]], dtype=np.int64)), shape=(2, 2))
145
+ assert g.indices.dtype == np.int64
146
+ tree = tree_func(g, 0, directed=directed)
147
+ assert_array_almost_equal(csgraph_to_dense(tree), [[0, 1], [0, 0]])
148
+
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/__init__.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Sparse linear algebra (:mod:`scipy.sparse.linalg`)
3
+ ==================================================
4
+
5
+ .. currentmodule:: scipy.sparse.linalg
6
+
7
+ Abstract linear operators
8
+ -------------------------
9
+
10
+ .. autosummary::
11
+ :toctree: generated/
12
+
13
+ LinearOperator -- abstract representation of a linear operator
14
+ aslinearoperator -- convert an object to an abstract linear operator
15
+
16
+ Matrix Operations
17
+ -----------------
18
+
19
+ .. autosummary::
20
+ :toctree: generated/
21
+
22
+ inv -- compute the sparse matrix inverse
23
+ expm -- compute the sparse matrix exponential
24
+ expm_multiply -- compute the product of a matrix exponential and a matrix
25
+ matrix_power -- compute the matrix power by raising a matrix to an exponent
26
+
27
+ Matrix norms
28
+ ------------
29
+
30
+ .. autosummary::
31
+ :toctree: generated/
32
+
33
+ norm -- Norm of a sparse matrix
34
+ onenormest -- Estimate the 1-norm of a sparse matrix
35
+
36
+ Solving linear problems
37
+ -----------------------
38
+
39
+ Direct methods for linear equation systems:
40
+
41
+ .. autosummary::
42
+ :toctree: generated/
43
+
44
+ spsolve -- Solve the sparse linear system Ax=b
45
+ spsolve_triangular -- Solve sparse linear system Ax=b for a triangular A.
46
+ is_sptriangular -- Check if sparse A is triangular.
47
+ spbandwidth -- Find the bandwidth of a sparse matrix.
48
+ factorized -- Pre-factorize matrix to a function solving a linear system
49
+ MatrixRankWarning -- Warning on exactly singular matrices
50
+ use_solver -- Select direct solver to use
51
+
52
+ Iterative methods for linear equation systems:
53
+
54
+ .. autosummary::
55
+ :toctree: generated/
56
+
57
+ bicg -- Use BIConjugate Gradient iteration to solve Ax = b
58
+ bicgstab -- Use BIConjugate Gradient STABilized iteration to solve Ax = b
59
+ cg -- Use Conjugate Gradient iteration to solve Ax = b
60
+ cgs -- Use Conjugate Gradient Squared iteration to solve Ax = b
61
+ gmres -- Use Generalized Minimal RESidual iteration to solve Ax = b
62
+ lgmres -- Solve a matrix equation using the LGMRES algorithm
63
+ minres -- Use MINimum RESidual iteration to solve Ax = b
64
+ qmr -- Use Quasi-Minimal Residual iteration to solve Ax = b
65
+ gcrotmk -- Solve a matrix equation using the GCROT(m,k) algorithm
66
+ tfqmr -- Use Transpose-Free Quasi-Minimal Residual iteration to solve Ax = b
67
+
68
+ Iterative methods for least-squares problems:
69
+
70
+ .. autosummary::
71
+ :toctree: generated/
72
+
73
+ lsqr -- Find the least-squares solution to a sparse linear equation system
74
+ lsmr -- Find the least-squares solution to a sparse linear equation system
75
+
76
+ Matrix factorizations
77
+ ---------------------
78
+
79
+ Eigenvalue problems:
80
+
81
+ .. autosummary::
82
+ :toctree: generated/
83
+
84
+ eigs -- Find k eigenvalues and eigenvectors of the square matrix A
85
+ eigsh -- Find k eigenvalues and eigenvectors of a symmetric matrix
86
+ lobpcg -- Solve symmetric partial eigenproblems with optional preconditioning
87
+
88
+ Singular values problems:
89
+
90
+ .. autosummary::
91
+ :toctree: generated/
92
+
93
+ svds -- Compute k singular values/vectors for a sparse matrix
94
+
95
+ The `svds` function supports the following solvers:
96
+
97
+ .. toctree::
98
+
99
+ sparse.linalg.svds-arpack
100
+ sparse.linalg.svds-lobpcg
101
+ sparse.linalg.svds-propack
102
+
103
+ Complete or incomplete LU factorizations
104
+
105
+ .. autosummary::
106
+ :toctree: generated/
107
+
108
+ splu -- Compute a LU decomposition for a sparse matrix
109
+ spilu -- Compute an incomplete LU decomposition for a sparse matrix
110
+ SuperLU -- Object representing an LU factorization
111
+
112
+ Sparse arrays with structure
113
+ ----------------------------
114
+
115
+ .. autosummary::
116
+ :toctree: generated/
117
+
118
+ LaplacianNd -- Laplacian on a uniform rectangular grid in ``N`` dimensions
119
+
120
+ Exceptions
121
+ ----------
122
+
123
+ .. autosummary::
124
+ :toctree: generated/
125
+
126
+ ArpackNoConvergence
127
+ ArpackError
128
+
129
+ """
130
+
131
+ from ._isolve import *
132
+ from ._dsolve import *
133
+ from ._interface import *
134
+ from ._eigen import *
135
+ from ._matfuncs import *
136
+ from ._onenormest import *
137
+ from ._norm import *
138
+ from ._expm_multiply import *
139
+ from ._special_sparse_arrays import *
140
+
141
+ # Deprecated namespaces, to be removed in v2.0.0
142
+ from . import isolve, dsolve, interface, eigen, matfuncs
143
+
144
+ __all__ = [s for s in dir() if not s.startswith('_')]
145
+
146
+ from scipy._lib._testutils import PytestTester
147
+ test = PytestTester(__name__)
148
+ del PytestTester
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_dsolve/__init__.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Linear Solvers
3
+ ==============
4
+
5
+ The default solver is SuperLU (included in the scipy distribution),
6
+ which can solve real or complex linear systems in both single and
7
+ double precisions. It is automatically replaced by UMFPACK, if
8
+ available. Note that UMFPACK works in double precision only, so
9
+ switch it off by::
10
+
11
+ >>> from scipy.sparse.linalg import spsolve, use_solver
12
+ >>> use_solver(useUmfpack=False)
13
+
14
+ to solve in the single precision. See also use_solver documentation.
15
+
16
+ Example session::
17
+
18
+ >>> from scipy.sparse import csc_array, dia_array
19
+ >>> from numpy import array
20
+ >>>
21
+ >>> print("Inverting a sparse linear system:")
22
+ >>> print("The sparse matrix (constructed from diagonals):")
23
+ >>> a = dia_array(([[1, 2, 3, 4, 5], [6, 5, 8, 9, 10]], [0, 1]), shape=(5, 5))
24
+ >>> b = array([1, 2, 3, 4, 5])
25
+ >>> print("Solve: single precision complex:")
26
+ >>> use_solver( useUmfpack = False )
27
+ >>> a = a.astype('F')
28
+ >>> x = spsolve(a, b)
29
+ >>> print(x)
30
+ >>> print("Error: ", a@x-b)
31
+ >>>
32
+ >>> print("Solve: double precision complex:")
33
+ >>> use_solver( useUmfpack = True )
34
+ >>> a = a.astype('D')
35
+ >>> x = spsolve(a, b)
36
+ >>> print(x)
37
+ >>> print("Error: ", a@x-b)
38
+ >>>
39
+ >>> print("Solve: double precision:")
40
+ >>> a = a.astype('d')
41
+ >>> x = spsolve(a, b)
42
+ >>> print(x)
43
+ >>> print("Error: ", a@x-b)
44
+ >>>
45
+ >>> print("Solve: single precision:")
46
+ >>> use_solver( useUmfpack = False )
47
+ >>> a = a.astype('f')
48
+ >>> x = spsolve(a, b.astype('f'))
49
+ >>> print(x)
50
+ >>> print("Error: ", a@x-b)
51
+
52
+ """
53
+
54
+ #import umfpack
55
+ #__doc__ = '\n\n'.join( (__doc__, umfpack.__doc__) )
56
+ #del umfpack
57
+
58
+ from .linsolve import *
59
+ from ._superlu import SuperLU
60
+ from . import _add_newdocs
61
+ from . import linsolve
62
+
63
+ __all__ = [
64
+ 'MatrixRankWarning', 'SuperLU', 'factorized',
65
+ 'spilu', 'splu', 'spsolve', 'is_sptriangular',
66
+ 'spsolve_triangular', 'use_solver', 'spbandwidth',
67
+ ]
68
+
69
+ from scipy._lib._testutils import PytestTester
70
+ test = PytestTester(__name__)
71
+ del PytestTester
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_dsolve/_add_newdocs.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from numpy.lib import add_newdoc
2
+
3
+ add_newdoc('scipy.sparse.linalg._dsolve._superlu', 'SuperLU',
4
+ """
5
+ LU factorization of a sparse matrix.
6
+
7
+ Factorization is represented as::
8
+
9
+ Pr @ A @ Pc = L @ U
10
+
11
+ To construct these `SuperLU` objects, call the `splu` and `spilu`
12
+ functions.
13
+
14
+ Attributes
15
+ ----------
16
+ shape
17
+ nnz
18
+ perm_c
19
+ perm_r
20
+ L
21
+ U
22
+
23
+ Methods
24
+ -------
25
+ solve
26
+
27
+ Notes
28
+ -----
29
+
30
+ .. versionadded:: 0.14.0
31
+
32
+ Examples
33
+ --------
34
+ The LU decomposition can be used to solve matrix equations. Consider:
35
+
36
+ >>> import numpy as np
37
+ >>> from scipy.sparse import csc_array
38
+ >>> from scipy.sparse.linalg import splu
39
+ >>> A = csc_array([[1,2,0,4], [1,0,0,1], [1,0,2,1], [2,2,1,0.]])
40
+
41
+ This can be solved for a given right-hand side:
42
+
43
+ >>> lu = splu(A)
44
+ >>> b = np.array([1, 2, 3, 4])
45
+ >>> x = lu.solve(b)
46
+ >>> A.dot(x)
47
+ array([ 1., 2., 3., 4.])
48
+
49
+ The ``lu`` object also contains an explicit representation of the
50
+ decomposition. The permutations are represented as mappings of
51
+ indices:
52
+
53
+ >>> lu.perm_r
54
+ array([2, 1, 3, 0], dtype=int32) # may vary
55
+ >>> lu.perm_c
56
+ array([0, 1, 3, 2], dtype=int32) # may vary
57
+
58
+ The L and U factors are sparse matrices in CSC format:
59
+
60
+ >>> lu.L.toarray()
61
+ array([[ 1. , 0. , 0. , 0. ], # may vary
62
+ [ 0.5, 1. , 0. , 0. ],
63
+ [ 0.5, -1. , 1. , 0. ],
64
+ [ 0.5, 1. , 0. , 1. ]])
65
+ >>> lu.U.toarray()
66
+ array([[ 2. , 2. , 0. , 1. ], # may vary
67
+ [ 0. , -1. , 1. , -0.5],
68
+ [ 0. , 0. , 5. , -1. ],
69
+ [ 0. , 0. , 0. , 2. ]])
70
+
71
+ The permutation matrices can be constructed:
72
+
73
+ >>> Pr = csc_array((np.ones(4), (lu.perm_r, np.arange(4))))
74
+ >>> Pc = csc_array((np.ones(4), (np.arange(4), lu.perm_c)))
75
+
76
+ We can reassemble the original matrix:
77
+
78
+ >>> (Pr.T @ (lu.L @ lu.U) @ Pc.T).toarray()
79
+ array([[ 1., 2., 0., 4.],
80
+ [ 1., 0., 0., 1.],
81
+ [ 1., 0., 2., 1.],
82
+ [ 2., 2., 1., 0.]])
83
+ """)
84
+
85
+ add_newdoc('scipy.sparse.linalg._dsolve._superlu', 'SuperLU', ('solve',
86
+ """
87
+ solve(rhs[, trans])
88
+
89
+ Solves linear system of equations with one or several right-hand sides.
90
+
91
+ Parameters
92
+ ----------
93
+ rhs : ndarray, shape (n,) or (n, k)
94
+ Right hand side(s) of equation
95
+ trans : {'N', 'T', 'H'}, optional
96
+ Type of system to solve::
97
+
98
+ 'N': A @ x == rhs (default)
99
+ 'T': A^T @ x == rhs
100
+ 'H': A^H @ x == rhs
101
+
102
+ i.e., normal, transposed, and hermitian conjugate.
103
+
104
+ Returns
105
+ -------
106
+ x : ndarray, shape ``rhs.shape``
107
+ Solution vector(s)
108
+ """))
109
+
110
+ add_newdoc('scipy.sparse.linalg._dsolve._superlu', 'SuperLU', ('L',
111
+ """
112
+ Lower triangular factor with unit diagonal as a
113
+ `scipy.sparse.csc_array`.
114
+
115
+ .. versionadded:: 0.14.0
116
+ """))
117
+
118
+ add_newdoc('scipy.sparse.linalg._dsolve._superlu', 'SuperLU', ('U',
119
+ """
120
+ Upper triangular factor as a `scipy.sparse.csc_array`.
121
+
122
+ .. versionadded:: 0.14.0
123
+ """))
124
+
125
+ add_newdoc('scipy.sparse.linalg._dsolve._superlu', 'SuperLU', ('shape',
126
+ """
127
+ Shape of the original matrix as a tuple of ints.
128
+ """))
129
+
130
+ add_newdoc('scipy.sparse.linalg._dsolve._superlu', 'SuperLU', ('nnz',
131
+ """
132
+ Number of nonzero elements in the matrix.
133
+ """))
134
+
135
+ add_newdoc('scipy.sparse.linalg._dsolve._superlu', 'SuperLU', ('perm_c',
136
+ """
137
+ Permutation Pc represented as an array of indices.
138
+
139
+ See the `SuperLU` docstring for details.
140
+ """))
141
+
142
+ add_newdoc('scipy.sparse.linalg._dsolve._superlu', 'SuperLU', ('perm_r',
143
+ """
144
+ Permutation Pr represented as an array of indices.
145
+
146
+ See the `SuperLU` docstring for details.
147
+ """))
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_dsolve/linsolve.py ADDED
@@ -0,0 +1,873 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from warnings import warn, catch_warnings, simplefilter
2
+
3
+ import numpy as np
4
+ from numpy import asarray
5
+ from scipy.sparse import (issparse, SparseEfficiencyWarning,
6
+ csr_array, csc_array, eye_array, diags_array)
7
+ from scipy.sparse._sputils import (is_pydata_spmatrix, convert_pydata_sparse_to_scipy,
8
+ get_index_dtype, safely_cast_index_arrays)
9
+ from scipy.linalg import LinAlgError
10
+ import copy
11
+ import threading
12
+
13
+ from . import _superlu
14
+
15
+ noScikit = False
16
+ try:
17
+ import scikits.umfpack as umfpack
18
+ except ImportError:
19
+ noScikit = True
20
+
21
+ useUmfpack = threading.local()
22
+
23
+
24
+ __all__ = ['use_solver', 'spsolve', 'splu', 'spilu', 'factorized',
25
+ 'MatrixRankWarning', 'spsolve_triangular', 'is_sptriangular', 'spbandwidth']
26
+
27
+
28
+ class MatrixRankWarning(UserWarning):
29
+ pass
30
+
31
+
32
+ def use_solver(**kwargs):
33
+ """
34
+ Select default sparse direct solver to be used.
35
+
36
+ Parameters
37
+ ----------
38
+ useUmfpack : bool, optional
39
+ Use UMFPACK [1]_, [2]_, [3]_, [4]_. over SuperLU. Has effect only
40
+ if ``scikits.umfpack`` is installed. Default: True
41
+ assumeSortedIndices : bool, optional
42
+ Allow UMFPACK to skip the step of sorting indices for a CSR/CSC matrix.
43
+ Has effect only if useUmfpack is True and ``scikits.umfpack`` is
44
+ installed. Default: False
45
+
46
+ Notes
47
+ -----
48
+ The default sparse solver is UMFPACK when available
49
+ (``scikits.umfpack`` is installed). This can be changed by passing
50
+ useUmfpack = False, which then causes the always present SuperLU
51
+ based solver to be used.
52
+
53
+ UMFPACK requires a CSR/CSC matrix to have sorted column/row indices. If
54
+ sure that the matrix fulfills this, pass ``assumeSortedIndices=True``
55
+ to gain some speed.
56
+
57
+ References
58
+ ----------
59
+ .. [1] T. A. Davis, Algorithm 832: UMFPACK - an unsymmetric-pattern
60
+ multifrontal method with a column pre-ordering strategy, ACM
61
+ Trans. on Mathematical Software, 30(2), 2004, pp. 196--199.
62
+ https://dl.acm.org/doi/abs/10.1145/992200.992206
63
+
64
+ .. [2] T. A. Davis, A column pre-ordering strategy for the
65
+ unsymmetric-pattern multifrontal method, ACM Trans.
66
+ on Mathematical Software, 30(2), 2004, pp. 165--195.
67
+ https://dl.acm.org/doi/abs/10.1145/992200.992205
68
+
69
+ .. [3] T. A. Davis and I. S. Duff, A combined unifrontal/multifrontal
70
+ method for unsymmetric sparse matrices, ACM Trans. on
71
+ Mathematical Software, 25(1), 1999, pp. 1--19.
72
+ https://doi.org/10.1145/305658.287640
73
+
74
+ .. [4] T. A. Davis and I. S. Duff, An unsymmetric-pattern multifrontal
75
+ method for sparse LU factorization, SIAM J. Matrix Analysis and
76
+ Computations, 18(1), 1997, pp. 140--158.
77
+ https://doi.org/10.1137/S0895479894246905T.
78
+
79
+ Examples
80
+ --------
81
+ >>> import numpy as np
82
+ >>> from scipy.sparse.linalg import use_solver, spsolve
83
+ >>> from scipy.sparse import csc_array
84
+ >>> R = np.random.randn(5, 5)
85
+ >>> A = csc_array(R)
86
+ >>> b = np.random.randn(5)
87
+ >>> use_solver(useUmfpack=False) # enforce superLU over UMFPACK
88
+ >>> x = spsolve(A, b)
89
+ >>> np.allclose(A.dot(x), b)
90
+ True
91
+ >>> use_solver(useUmfpack=True) # reset umfPack usage to default
92
+ """
93
+ global useUmfpack
94
+ if 'useUmfpack' in kwargs:
95
+ useUmfpack.u = kwargs['useUmfpack']
96
+ if useUmfpack.u and 'assumeSortedIndices' in kwargs:
97
+ umfpack.configure(assumeSortedIndices=kwargs['assumeSortedIndices'])
98
+
99
+ def _get_umf_family(A):
100
+ """Get umfpack family string given the sparse matrix dtype."""
101
+ _families = {
102
+ (np.float64, np.int32): 'di',
103
+ (np.complex128, np.int32): 'zi',
104
+ (np.float64, np.int64): 'dl',
105
+ (np.complex128, np.int64): 'zl'
106
+ }
107
+
108
+ # A.dtype.name can only be "float64" or
109
+ # "complex128" in control flow
110
+ f_type = getattr(np, A.dtype.name)
111
+ # control flow may allow for more index
112
+ # types to get through here
113
+ i_type = getattr(np, A.indices.dtype.name)
114
+
115
+ try:
116
+ family = _families[(f_type, i_type)]
117
+
118
+ except KeyError as e:
119
+ msg = ('only float64 or complex128 matrices with int32 or int64 '
120
+ f'indices are supported! (got: matrix: {f_type}, indices: {i_type})')
121
+ raise ValueError(msg) from e
122
+
123
+ # See gh-8278. Considered converting only if
124
+ # A.shape[0]*A.shape[1] > np.iinfo(np.int32).max,
125
+ # but that didn't always fix the issue.
126
+ family = family[0] + "l"
127
+ A_new = copy.copy(A)
128
+ A_new.indptr = np.asarray(A.indptr, dtype=np.int64)
129
+ A_new.indices = np.asarray(A.indices, dtype=np.int64)
130
+
131
+ return family, A_new
132
+
133
+ def spsolve(A, b, permc_spec=None, use_umfpack=True):
134
+ """Solve the sparse linear system Ax=b, where b may be a vector or a matrix.
135
+
136
+ Parameters
137
+ ----------
138
+ A : ndarray or sparse array or matrix
139
+ The square matrix A will be converted into CSC or CSR form
140
+ b : ndarray or sparse array or matrix
141
+ The matrix or vector representing the right hand side of the equation.
142
+ If a vector, b.shape must be (n,) or (n, 1).
143
+ permc_spec : str, optional
144
+ How to permute the columns of the matrix for sparsity preservation.
145
+ (default: 'COLAMD')
146
+
147
+ - ``NATURAL``: natural ordering.
148
+ - ``MMD_ATA``: minimum degree ordering on the structure of A^T A.
149
+ - ``MMD_AT_PLUS_A``: minimum degree ordering on the structure of A^T+A.
150
+ - ``COLAMD``: approximate minimum degree column ordering [1]_, [2]_.
151
+
152
+ use_umfpack : bool, optional
153
+ if True (default) then use UMFPACK for the solution [3]_, [4]_, [5]_,
154
+ [6]_ . This is only referenced if b is a vector and
155
+ ``scikits.umfpack`` is installed.
156
+
157
+ Returns
158
+ -------
159
+ x : ndarray or sparse array or matrix
160
+ the solution of the sparse linear equation.
161
+ If b is a vector, then x is a vector of size A.shape[1]
162
+ If b is a matrix, then x is a matrix of size (A.shape[1], b.shape[1])
163
+
164
+ Notes
165
+ -----
166
+ For solving the matrix expression AX = B, this solver assumes the resulting
167
+ matrix X is sparse, as is often the case for very sparse inputs. If the
168
+ resulting X is dense, the construction of this sparse result will be
169
+ relatively expensive. In that case, consider converting A to a dense
170
+ matrix and using scipy.linalg.solve or its variants.
171
+
172
+ References
173
+ ----------
174
+ .. [1] T. A. Davis, J. R. Gilbert, S. Larimore, E. Ng, Algorithm 836:
175
+ COLAMD, an approximate column minimum degree ordering algorithm,
176
+ ACM Trans. on Mathematical Software, 30(3), 2004, pp. 377--380.
177
+ :doi:`10.1145/1024074.1024080`
178
+
179
+ .. [2] T. A. Davis, J. R. Gilbert, S. Larimore, E. Ng, A column approximate
180
+ minimum degree ordering algorithm, ACM Trans. on Mathematical
181
+ Software, 30(3), 2004, pp. 353--376. :doi:`10.1145/1024074.1024079`
182
+
183
+ .. [3] T. A. Davis, Algorithm 832: UMFPACK - an unsymmetric-pattern
184
+ multifrontal method with a column pre-ordering strategy, ACM
185
+ Trans. on Mathematical Software, 30(2), 2004, pp. 196--199.
186
+ https://dl.acm.org/doi/abs/10.1145/992200.992206
187
+
188
+ .. [4] T. A. Davis, A column pre-ordering strategy for the
189
+ unsymmetric-pattern multifrontal method, ACM Trans.
190
+ on Mathematical Software, 30(2), 2004, pp. 165--195.
191
+ https://dl.acm.org/doi/abs/10.1145/992200.992205
192
+
193
+ .. [5] T. A. Davis and I. S. Duff, A combined unifrontal/multifrontal
194
+ method for unsymmetric sparse matrices, ACM Trans. on
195
+ Mathematical Software, 25(1), 1999, pp. 1--19.
196
+ https://doi.org/10.1145/305658.287640
197
+
198
+ .. [6] T. A. Davis and I. S. Duff, An unsymmetric-pattern multifrontal
199
+ method for sparse LU factorization, SIAM J. Matrix Analysis and
200
+ Computations, 18(1), 1997, pp. 140--158.
201
+ https://doi.org/10.1137/S0895479894246905T.
202
+
203
+
204
+ Examples
205
+ --------
206
+ >>> import numpy as np
207
+ >>> from scipy.sparse import csc_array
208
+ >>> from scipy.sparse.linalg import spsolve
209
+ >>> A = csc_array([[3, 2, 0], [1, -1, 0], [0, 5, 1]], dtype=float)
210
+ >>> B = csc_array([[2, 0], [-1, 0], [2, 0]], dtype=float)
211
+ >>> x = spsolve(A, B)
212
+ >>> np.allclose(A.dot(x).toarray(), B.toarray())
213
+ True
214
+ """
215
+ is_pydata_sparse = is_pydata_spmatrix(b)
216
+ pydata_sparse_cls = b.__class__ if is_pydata_sparse else None
217
+ A = convert_pydata_sparse_to_scipy(A)
218
+ b = convert_pydata_sparse_to_scipy(b)
219
+
220
+ if not (issparse(A) and A.format in ("csc", "csr")):
221
+ A = csc_array(A)
222
+ warn('spsolve requires A be CSC or CSR matrix format',
223
+ SparseEfficiencyWarning, stacklevel=2)
224
+
225
+ # b is a vector only if b have shape (n,) or (n, 1)
226
+ b_is_sparse = issparse(b)
227
+ if not b_is_sparse:
228
+ b = asarray(b)
229
+ b_is_vector = ((b.ndim == 1) or (b.ndim == 2 and b.shape[1] == 1))
230
+
231
+ # sum duplicates for non-canonical format
232
+ A.sum_duplicates()
233
+ A = A._asfptype() # upcast to a floating point format
234
+ result_dtype = np.promote_types(A.dtype, b.dtype)
235
+ if A.dtype != result_dtype:
236
+ A = A.astype(result_dtype)
237
+ if b.dtype != result_dtype:
238
+ b = b.astype(result_dtype)
239
+
240
+ # validate input shapes
241
+ M, N = A.shape
242
+ if (M != N):
243
+ raise ValueError(f"matrix must be square (has shape {(M, N)})")
244
+
245
+ if M != b.shape[0]:
246
+ raise ValueError(f"matrix - rhs dimension mismatch ({A.shape} - {b.shape[0]})")
247
+
248
+ if not hasattr(useUmfpack, 'u'):
249
+ useUmfpack.u = not noScikit
250
+
251
+ use_umfpack = use_umfpack and useUmfpack.u
252
+
253
+ if b_is_vector and use_umfpack:
254
+ if b_is_sparse:
255
+ b_vec = b.toarray()
256
+ else:
257
+ b_vec = b
258
+ b_vec = asarray(b_vec, dtype=A.dtype).ravel()
259
+
260
+ if noScikit:
261
+ raise RuntimeError('Scikits.umfpack not installed.')
262
+
263
+ if A.dtype.char not in 'dD':
264
+ raise ValueError("convert matrix data to double, please, using"
265
+ " .astype(), or set linsolve.useUmfpack.u = False")
266
+
267
+ umf_family, A = _get_umf_family(A)
268
+ umf = umfpack.UmfpackContext(umf_family)
269
+ x = umf.linsolve(umfpack.UMFPACK_A, A, b_vec,
270
+ autoTranspose=True)
271
+ else:
272
+ if b_is_vector and b_is_sparse:
273
+ b = b.toarray()
274
+ b_is_sparse = False
275
+
276
+ if not b_is_sparse:
277
+ if A.format == "csc":
278
+ flag = 1 # CSC format
279
+ else:
280
+ flag = 0 # CSR format
281
+
282
+ indices = A.indices.astype(np.intc, copy=False)
283
+ indptr = A.indptr.astype(np.intc, copy=False)
284
+ options = dict(ColPerm=permc_spec)
285
+ x, info = _superlu.gssv(N, A.nnz, A.data, indices, indptr,
286
+ b, flag, options=options)
287
+ if info != 0:
288
+ warn("Matrix is exactly singular", MatrixRankWarning, stacklevel=2)
289
+ x.fill(np.nan)
290
+ if b_is_vector:
291
+ x = x.ravel()
292
+ else:
293
+ # b is sparse
294
+ Afactsolve = factorized(A)
295
+
296
+ if not (b.format == "csc" or is_pydata_spmatrix(b)):
297
+ warn('spsolve is more efficient when sparse b '
298
+ 'is in the CSC matrix format',
299
+ SparseEfficiencyWarning, stacklevel=2)
300
+ b = csc_array(b)
301
+
302
+ # Create a sparse output matrix by repeatedly applying
303
+ # the sparse factorization to solve columns of b.
304
+ data_segs = []
305
+ row_segs = []
306
+ col_segs = []
307
+ for j in range(b.shape[1]):
308
+ bj = b[:, j].toarray().ravel()
309
+ xj = Afactsolve(bj)
310
+ w = np.flatnonzero(xj)
311
+ segment_length = w.shape[0]
312
+ row_segs.append(w)
313
+ col_segs.append(np.full(segment_length, j, dtype=int))
314
+ data_segs.append(np.asarray(xj[w], dtype=A.dtype))
315
+ sparse_data = np.concatenate(data_segs)
316
+ idx_dtype = get_index_dtype(maxval=max(b.shape))
317
+ sparse_row = np.concatenate(row_segs, dtype=idx_dtype)
318
+ sparse_col = np.concatenate(col_segs, dtype=idx_dtype)
319
+ x = A.__class__((sparse_data, (sparse_row, sparse_col)),
320
+ shape=b.shape, dtype=A.dtype)
321
+
322
+ if is_pydata_sparse:
323
+ x = pydata_sparse_cls.from_scipy_sparse(x)
324
+
325
+ return x
326
+
327
+
328
+ def splu(A, permc_spec=None, diag_pivot_thresh=None,
329
+ relax=None, panel_size=None, options=None):
330
+ """
331
+ Compute the LU decomposition of a sparse, square matrix.
332
+
333
+ Parameters
334
+ ----------
335
+ A : sparse array or matrix
336
+ Sparse array to factorize. Most efficient when provided in CSC
337
+ format. Other formats will be converted to CSC before factorization.
338
+ permc_spec : str, optional
339
+ How to permute the columns of the matrix for sparsity preservation.
340
+ (default: 'COLAMD')
341
+
342
+ - ``NATURAL``: natural ordering.
343
+ - ``MMD_ATA``: minimum degree ordering on the structure of A^T A.
344
+ - ``MMD_AT_PLUS_A``: minimum degree ordering on the structure of A^T+A.
345
+ - ``COLAMD``: approximate minimum degree column ordering
346
+
347
+ diag_pivot_thresh : float, optional
348
+ Threshold used for a diagonal entry to be an acceptable pivot.
349
+ See SuperLU user's guide for details [1]_
350
+ relax : int, optional
351
+ Expert option for customizing the degree of relaxing supernodes.
352
+ See SuperLU user's guide for details [1]_
353
+ panel_size : int, optional
354
+ Expert option for customizing the panel size.
355
+ See SuperLU user's guide for details [1]_
356
+ options : dict, optional
357
+ Dictionary containing additional expert options to SuperLU.
358
+ See SuperLU user guide [1]_ (section 2.4 on the 'Options' argument)
359
+ for more details. For example, you can specify
360
+ ``options=dict(Equil=False, IterRefine='SINGLE'))``
361
+ to turn equilibration off and perform a single iterative refinement.
362
+
363
+ Returns
364
+ -------
365
+ invA : scipy.sparse.linalg.SuperLU
366
+ Object, which has a ``solve`` method.
367
+
368
+ See also
369
+ --------
370
+ spilu : incomplete LU decomposition
371
+
372
+ Notes
373
+ -----
374
+ This function uses the SuperLU library.
375
+
376
+ References
377
+ ----------
378
+ .. [1] SuperLU https://portal.nersc.gov/project/sparse/superlu/
379
+
380
+ Examples
381
+ --------
382
+ >>> import numpy as np
383
+ >>> from scipy.sparse import csc_array
384
+ >>> from scipy.sparse.linalg import splu
385
+ >>> A = csc_array([[1., 0., 0.], [5., 0., 2.], [0., -1., 0.]], dtype=float)
386
+ >>> B = splu(A)
387
+ >>> x = np.array([1., 2., 3.], dtype=float)
388
+ >>> B.solve(x)
389
+ array([ 1. , -3. , -1.5])
390
+ >>> A.dot(B.solve(x))
391
+ array([ 1., 2., 3.])
392
+ >>> B.solve(A.dot(x))
393
+ array([ 1., 2., 3.])
394
+ """
395
+
396
+ if is_pydata_spmatrix(A):
397
+ A_cls = type(A)
398
+ def csc_construct_func(*a, cls=A_cls):
399
+ return cls.from_scipy_sparse(csc_array(*a))
400
+ A = A.to_scipy_sparse().tocsc()
401
+ else:
402
+ csc_construct_func = csc_array
403
+
404
+ if not (issparse(A) and A.format == "csc"):
405
+ A = csc_array(A)
406
+ warn('splu converted its input to CSC format',
407
+ SparseEfficiencyWarning, stacklevel=2)
408
+
409
+ # sum duplicates for non-canonical format
410
+ A.sum_duplicates()
411
+ A = A._asfptype() # upcast to a floating point format
412
+
413
+ M, N = A.shape
414
+ if (M != N):
415
+ raise ValueError("can only factor square matrices") # is this true?
416
+
417
+ indices, indptr = safely_cast_index_arrays(A, np.intc, "SuperLU")
418
+
419
+ _options = dict(DiagPivotThresh=diag_pivot_thresh, ColPerm=permc_spec,
420
+ PanelSize=panel_size, Relax=relax)
421
+ if options is not None:
422
+ _options.update(options)
423
+
424
+ # Ensure that no column permutations are applied
425
+ if (_options["ColPerm"] == "NATURAL"):
426
+ _options["SymmetricMode"] = True
427
+
428
+ return _superlu.gstrf(N, A.nnz, A.data, indices, indptr,
429
+ csc_construct_func=csc_construct_func,
430
+ ilu=False, options=_options)
431
+
432
+
433
+ def spilu(A, drop_tol=None, fill_factor=None, drop_rule=None, permc_spec=None,
434
+ diag_pivot_thresh=None, relax=None, panel_size=None, options=None):
435
+ """
436
+ Compute an incomplete LU decomposition for a sparse, square matrix.
437
+
438
+ The resulting object is an approximation to the inverse of `A`.
439
+
440
+ Parameters
441
+ ----------
442
+ A : (N, N) array_like
443
+ Sparse array to factorize. Most efficient when provided in CSC format.
444
+ Other formats will be converted to CSC before factorization.
445
+ drop_tol : float, optional
446
+ Drop tolerance (0 <= tol <= 1) for an incomplete LU decomposition.
447
+ (default: 1e-4)
448
+ fill_factor : float, optional
449
+ Specifies the fill ratio upper bound (>= 1.0) for ILU. (default: 10)
450
+ drop_rule : str, optional
451
+ Comma-separated string of drop rules to use.
452
+ Available rules: ``basic``, ``prows``, ``column``, ``area``,
453
+ ``secondary``, ``dynamic``, ``interp``. (Default: ``basic,area``)
454
+
455
+ See SuperLU documentation for details.
456
+
457
+ Remaining other options
458
+ Same as for `splu`
459
+
460
+ Returns
461
+ -------
462
+ invA_approx : scipy.sparse.linalg.SuperLU
463
+ Object, which has a ``solve`` method.
464
+
465
+ See also
466
+ --------
467
+ splu : complete LU decomposition
468
+
469
+ Notes
470
+ -----
471
+ To improve the better approximation to the inverse, you may need to
472
+ increase `fill_factor` AND decrease `drop_tol`.
473
+
474
+ This function uses the SuperLU library.
475
+
476
+ Examples
477
+ --------
478
+ >>> import numpy as np
479
+ >>> from scipy.sparse import csc_array
480
+ >>> from scipy.sparse.linalg import spilu
481
+ >>> A = csc_array([[1., 0., 0.], [5., 0., 2.], [0., -1., 0.]], dtype=float)
482
+ >>> B = spilu(A)
483
+ >>> x = np.array([1., 2., 3.], dtype=float)
484
+ >>> B.solve(x)
485
+ array([ 1. , -3. , -1.5])
486
+ >>> A.dot(B.solve(x))
487
+ array([ 1., 2., 3.])
488
+ >>> B.solve(A.dot(x))
489
+ array([ 1., 2., 3.])
490
+ """
491
+
492
+ if is_pydata_spmatrix(A):
493
+ A_cls = type(A)
494
+ def csc_construct_func(*a, cls=A_cls):
495
+ return cls.from_scipy_sparse(csc_array(*a))
496
+ A = A.to_scipy_sparse().tocsc()
497
+ else:
498
+ csc_construct_func = csc_array
499
+
500
+ if not (issparse(A) and A.format == "csc"):
501
+ A = csc_array(A)
502
+ warn('spilu converted its input to CSC format',
503
+ SparseEfficiencyWarning, stacklevel=2)
504
+
505
+ # sum duplicates for non-canonical format
506
+ A.sum_duplicates()
507
+ A = A._asfptype() # upcast to a floating point format
508
+
509
+ M, N = A.shape
510
+ if (M != N):
511
+ raise ValueError("can only factor square matrices") # is this true?
512
+
513
+ indices, indptr = safely_cast_index_arrays(A, np.intc, "SuperLU")
514
+
515
+ _options = dict(ILU_DropRule=drop_rule, ILU_DropTol=drop_tol,
516
+ ILU_FillFactor=fill_factor,
517
+ DiagPivotThresh=diag_pivot_thresh, ColPerm=permc_spec,
518
+ PanelSize=panel_size, Relax=relax)
519
+ if options is not None:
520
+ _options.update(options)
521
+
522
+ # Ensure that no column permutations are applied
523
+ if (_options["ColPerm"] == "NATURAL"):
524
+ _options["SymmetricMode"] = True
525
+
526
+ return _superlu.gstrf(N, A.nnz, A.data, indices, indptr,
527
+ csc_construct_func=csc_construct_func,
528
+ ilu=True, options=_options)
529
+
530
+
531
+ def factorized(A):
532
+ """
533
+ Return a function for solving a sparse linear system, with A pre-factorized.
534
+
535
+ Parameters
536
+ ----------
537
+ A : (N, N) array_like
538
+ Input. A in CSC format is most efficient. A CSR format matrix will
539
+ be converted to CSC before factorization.
540
+
541
+ Returns
542
+ -------
543
+ solve : callable
544
+ To solve the linear system of equations given in `A`, the `solve`
545
+ callable should be passed an ndarray of shape (N,).
546
+
547
+ Examples
548
+ --------
549
+ >>> import numpy as np
550
+ >>> from scipy.sparse.linalg import factorized
551
+ >>> from scipy.sparse import csc_array
552
+ >>> A = np.array([[ 3. , 2. , -1. ],
553
+ ... [ 2. , -2. , 4. ],
554
+ ... [-1. , 0.5, -1. ]])
555
+ >>> solve = factorized(csc_array(A)) # Makes LU decomposition.
556
+ >>> rhs1 = np.array([1, -2, 0])
557
+ >>> solve(rhs1) # Uses the LU factors.
558
+ array([ 1., -2., -2.])
559
+
560
+ """
561
+ if is_pydata_spmatrix(A):
562
+ A = A.to_scipy_sparse().tocsc()
563
+
564
+ if not hasattr(useUmfpack, 'u'):
565
+ useUmfpack.u = not noScikit
566
+
567
+ if useUmfpack.u:
568
+ if noScikit:
569
+ raise RuntimeError('Scikits.umfpack not installed.')
570
+
571
+ if not (issparse(A) and A.format == "csc"):
572
+ A = csc_array(A)
573
+ warn('splu converted its input to CSC format',
574
+ SparseEfficiencyWarning, stacklevel=2)
575
+
576
+ A = A._asfptype() # upcast to a floating point format
577
+
578
+ if A.dtype.char not in 'dD':
579
+ raise ValueError("convert matrix data to double, please, using"
580
+ " .astype(), or set linsolve.useUmfpack.u = False")
581
+
582
+ umf_family, A = _get_umf_family(A)
583
+ umf = umfpack.UmfpackContext(umf_family)
584
+
585
+ # Make LU decomposition.
586
+ umf.numeric(A)
587
+
588
+ def solve(b):
589
+ with np.errstate(divide="ignore", invalid="ignore"):
590
+ # Ignoring warnings with numpy >= 1.23.0, see gh-16523
591
+ result = umf.solve(umfpack.UMFPACK_A, A, b, autoTranspose=True)
592
+
593
+ return result
594
+
595
+ return solve
596
+ else:
597
+ return splu(A).solve
598
+
599
+
600
+ def spsolve_triangular(A, b, lower=True, overwrite_A=False, overwrite_b=False,
601
+ unit_diagonal=False):
602
+ """
603
+ Solve the equation ``A x = b`` for `x`, assuming A is a triangular matrix.
604
+
605
+ Parameters
606
+ ----------
607
+ A : (M, M) sparse array or matrix
608
+ A sparse square triangular matrix. Should be in CSR or CSC format.
609
+ b : (M,) or (M, N) array_like
610
+ Right-hand side matrix in ``A x = b``
611
+ lower : bool, optional
612
+ Whether `A` is a lower or upper triangular matrix.
613
+ Default is lower triangular matrix.
614
+ overwrite_A : bool, optional
615
+ Allow changing `A`.
616
+ Enabling gives a performance gain. Default is False.
617
+ overwrite_b : bool, optional
618
+ Allow overwriting data in `b`.
619
+ Enabling gives a performance gain. Default is False.
620
+ If `overwrite_b` is True, it should be ensured that
621
+ `b` has an appropriate dtype to be able to store the result.
622
+ unit_diagonal : bool, optional
623
+ If True, diagonal elements of `a` are assumed to be 1.
624
+
625
+ .. versionadded:: 1.4.0
626
+
627
+ Returns
628
+ -------
629
+ x : (M,) or (M, N) ndarray
630
+ Solution to the system ``A x = b``. Shape of return matches shape
631
+ of `b`.
632
+
633
+ Raises
634
+ ------
635
+ LinAlgError
636
+ If `A` is singular or not triangular.
637
+ ValueError
638
+ If shape of `A` or shape of `b` do not match the requirements.
639
+
640
+ Notes
641
+ -----
642
+ .. versionadded:: 0.19.0
643
+
644
+ Examples
645
+ --------
646
+ >>> import numpy as np
647
+ >>> from scipy.sparse import csc_array
648
+ >>> from scipy.sparse.linalg import spsolve_triangular
649
+ >>> A = csc_array([[3, 0, 0], [1, -1, 0], [2, 0, 1]], dtype=float)
650
+ >>> B = np.array([[2, 0], [-1, 0], [2, 0]], dtype=float)
651
+ >>> x = spsolve_triangular(A, B)
652
+ >>> np.allclose(A.dot(x), B)
653
+ True
654
+ """
655
+
656
+ if is_pydata_spmatrix(A):
657
+ A = A.to_scipy_sparse().tocsc()
658
+
659
+ trans = "N"
660
+ if issparse(A) and A.format == "csr":
661
+ A = A.T
662
+ trans = "T"
663
+ lower = not lower
664
+
665
+ if not (issparse(A) and A.format == "csc"):
666
+ warn('CSC or CSR matrix format is required. Converting to CSC matrix.',
667
+ SparseEfficiencyWarning, stacklevel=2)
668
+ A = csc_array(A)
669
+ elif not overwrite_A:
670
+ A = A.copy()
671
+
672
+
673
+ M, N = A.shape
674
+ if M != N:
675
+ raise ValueError(
676
+ f'A must be a square matrix but its shape is {A.shape}.')
677
+
678
+ if unit_diagonal:
679
+ with catch_warnings():
680
+ simplefilter('ignore', SparseEfficiencyWarning)
681
+ A.setdiag(1)
682
+ else:
683
+ diag = A.diagonal()
684
+ if np.any(diag == 0):
685
+ raise LinAlgError(
686
+ 'A is singular: zero entry on diagonal.')
687
+ invdiag = 1/diag
688
+ if trans == "N":
689
+ A = A @ diags_array(invdiag)
690
+ else:
691
+ A = (A.T @ diags_array(invdiag)).T
692
+
693
+ # sum duplicates for non-canonical format
694
+ A.sum_duplicates()
695
+
696
+ b = np.asanyarray(b)
697
+
698
+ if b.ndim not in [1, 2]:
699
+ raise ValueError(
700
+ f'b must have 1 or 2 dims but its shape is {b.shape}.')
701
+ if M != b.shape[0]:
702
+ raise ValueError(
703
+ 'The size of the dimensions of A must be equal to '
704
+ 'the size of the first dimension of b but the shape of A is '
705
+ f'{A.shape} and the shape of b is {b.shape}.'
706
+ )
707
+
708
+ result_dtype = np.promote_types(np.promote_types(A.dtype, np.float32), b.dtype)
709
+ if A.dtype != result_dtype:
710
+ A = A.astype(result_dtype)
711
+ if b.dtype != result_dtype:
712
+ b = b.astype(result_dtype)
713
+ elif not overwrite_b:
714
+ b = b.copy()
715
+
716
+ if lower:
717
+ L = A
718
+ U = csc_array((N, N), dtype=result_dtype)
719
+ else:
720
+ L = eye_array(N, dtype=result_dtype, format='csc')
721
+ U = A
722
+ U.setdiag(0)
723
+
724
+ x, info = _superlu.gstrs(trans,
725
+ N, L.nnz, L.data, L.indices, L.indptr,
726
+ N, U.nnz, U.data, U.indices, U.indptr,
727
+ b)
728
+ if info:
729
+ raise LinAlgError('A is singular.')
730
+
731
+ if not unit_diagonal:
732
+ invdiag = invdiag.reshape(-1, *([1] * (len(x.shape) - 1)))
733
+ x = x * invdiag
734
+
735
+ return x
736
+
737
+
738
+ def is_sptriangular(A):
739
+ """Returns 2-tuple indicating lower/upper triangular structure for sparse ``A``
740
+
741
+ Checks for triangular structure in ``A``. The result is summarized in
742
+ two boolean values ``lower`` and ``upper`` to designate whether ``A`` is
743
+ lower triangular or upper triangular respectively. Diagonal ``A`` will
744
+ result in both being True. Non-triangular structure results in False for both.
745
+
746
+ Only the sparse structure is used here. Values are not checked for zeros.
747
+
748
+ This function will convert a copy of ``A`` to CSC format if it is not already
749
+ CSR or CSC format. So it may be more efficient to convert it yourself if you
750
+ have other uses for the CSR/CSC version.
751
+
752
+ If ``A`` is not square, the portions outside the upper left square of the
753
+ matrix do not affect its triangular structure. You probably want to work
754
+ with the square portion of the matrix, though it is not requred here.
755
+
756
+ Parameters
757
+ ----------
758
+ A : SciPy sparse array or matrix
759
+ A sparse matrix preferrably in CSR or CSC format.
760
+
761
+ Returns
762
+ -------
763
+ lower, upper : 2-tuple of bool
764
+
765
+ .. versionadded:: 1.15.0
766
+
767
+ Examples
768
+ --------
769
+ >>> import numpy as np
770
+ >>> from scipy.sparse import csc_array, eye_array
771
+ >>> from scipy.sparse.linalg import is_sptriangular
772
+ >>> A = csc_array([[3, 0, 0], [1, -1, 0], [2, 0, 1]], dtype=float)
773
+ >>> is_sptriangular(A)
774
+ (True, False)
775
+ >>> D = eye_array(3, format='csr')
776
+ >>> is_sptriangular(D)
777
+ (True, True)
778
+ """
779
+ if not (issparse(A) and A.format in ("csc", "csr", "coo", "dia", "dok", "lil")):
780
+ warn('is_sptriangular needs sparse and not BSR format. Converting to CSR.',
781
+ SparseEfficiencyWarning, stacklevel=2)
782
+ A = csr_array(A)
783
+
784
+ # bsr is better off converting to csr
785
+ if A.format == "dia":
786
+ return A.offsets.max() <= 0, A.offsets.min() >= 0
787
+ elif A.format == "coo":
788
+ rows, cols = A.coords
789
+ return (cols <= rows).all(), (cols >= rows).all()
790
+ elif A.format == "dok":
791
+ return all(c <= r for r, c in A.keys()), all(c >= r for r, c in A.keys())
792
+ elif A.format == "lil":
793
+ lower = all(col <= row for row, cols in enumerate(A.rows) for col in cols)
794
+ upper = all(col >= row for row, cols in enumerate(A.rows) for col in cols)
795
+ return lower, upper
796
+ # format in ("csc", "csr")
797
+ indptr, indices = A.indptr, A.indices
798
+ N = len(indptr) - 1
799
+
800
+ lower, upper = True, True
801
+ # check middle, 1st, last col (treat as CSC and switch at end if CSR)
802
+ for col in [N // 2, 0, -1]:
803
+ rows = indices[indptr[col]:indptr[col + 1]]
804
+ upper = upper and (col >= rows).all()
805
+ lower = lower and (col <= rows).all()
806
+ if not upper and not lower:
807
+ return False, False
808
+ # check all cols
809
+ cols = np.repeat(np.arange(N), np.diff(indptr))
810
+ rows = indices
811
+ upper = upper and (cols >= rows).all()
812
+ lower = lower and (cols <= rows).all()
813
+ if A.format == 'csr':
814
+ return upper, lower
815
+ return lower, upper
816
+
817
+
818
+ def spbandwidth(A):
819
+ """Return the lower and upper bandwidth of a 2D numeric array.
820
+
821
+ Computes the lower and upper limits on the bandwidth of the
822
+ sparse 2D array ``A``. The result is summarized as a 2-tuple
823
+ of positive integers ``(lo, hi)``. A zero denotes no sub/super
824
+ diagonal entries on that side (tringular). The maximum value
825
+ for ``lo``(``hi``) is one less than the number of rows(cols).
826
+
827
+ Only the sparse structure is used here. Values are not checked for zeros.
828
+
829
+ Parameters
830
+ ----------
831
+ A : SciPy sparse array or matrix
832
+ A sparse matrix preferrably in CSR or CSC format.
833
+
834
+ Returns
835
+ -------
836
+ below, above : 2-tuple of int
837
+ The distance to the farthest non-zero diagonal below/above the
838
+ main diagonal.
839
+
840
+ .. versionadded:: 1.15.0
841
+
842
+ Examples
843
+ --------
844
+ >>> import numpy as np
845
+ >>> from scipy.sparse.linalg import spbandwidth
846
+ >>> from scipy.sparse import csc_array, eye_array
847
+ >>> A = csc_array([[3, 0, 0], [1, -1, 0], [2, 0, 1]], dtype=float)
848
+ >>> spbandwidth(A)
849
+ (2, 0)
850
+ >>> D = eye_array(3, format='csr')
851
+ >>> spbandwidth(D)
852
+ (0, 0)
853
+ """
854
+ if not (issparse(A) and A.format in ("csc", "csr", "coo", "dia", "dok")):
855
+ warn('spbandwidth needs sparse format not LIL and BSR. Converting to CSR.',
856
+ SparseEfficiencyWarning, stacklevel=2)
857
+ A = csr_array(A)
858
+
859
+ # bsr and lil are better off converting to csr
860
+ if A.format == "dia":
861
+ return max(0, -A.offsets.min().item()), max(0, A.offsets.max().item())
862
+ if A.format in ("csc", "csr"):
863
+ indptr, indices = A.indptr, A.indices
864
+ N = len(indptr) - 1
865
+ gap = np.repeat(np.arange(N), np.diff(indptr)) - indices
866
+ if A.format == 'csr':
867
+ gap = -gap
868
+ elif A.format == "coo":
869
+ gap = A.coords[1] - A.coords[0]
870
+ elif A.format == "dok":
871
+ gap = [(c - r) for r, c in A.keys()] + [0]
872
+ return -min(gap), max(gap)
873
+ return max(-np.min(gap).item(), 0), max(np.max(gap).item(), 0)
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_dsolve/tests/__init__.py ADDED
File without changes
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_dsolve/tests/test_linsolve.py ADDED
@@ -0,0 +1,921 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import threading
3
+
4
+ import numpy as np
5
+ from numpy import array, finfo, arange, eye, all, unique, ones, dot
6
+ import numpy.random as random
7
+ from numpy.testing import (
8
+ assert_array_almost_equal, assert_almost_equal,
9
+ assert_equal, assert_array_equal, assert_, assert_allclose,
10
+ assert_warns, suppress_warnings)
11
+ import pytest
12
+ from pytest import raises as assert_raises
13
+
14
+ import scipy.linalg
15
+ from scipy.linalg import norm, inv
16
+ from scipy.sparse import (dia_array, SparseEfficiencyWarning, csc_array,
17
+ csr_array, eye_array, issparse, dok_array, lil_array, bsr_array, kron)
18
+ from scipy.sparse.linalg import SuperLU
19
+ from scipy.sparse.linalg._dsolve import (spsolve, use_solver, splu, spilu,
20
+ MatrixRankWarning, _superlu, spsolve_triangular, factorized,
21
+ is_sptriangular, spbandwidth)
22
+ import scipy.sparse
23
+
24
+ from scipy._lib._testutils import check_free_memory
25
+ from scipy._lib._util import ComplexWarning
26
+
27
+
28
+ sup_sparse_efficiency = suppress_warnings()
29
+ sup_sparse_efficiency.filter(SparseEfficiencyWarning)
30
+
31
+ # scikits.umfpack is not a SciPy dependency but it is optionally used in
32
+ # dsolve, so check whether it's available
33
+ try:
34
+ import scikits.umfpack as umfpack
35
+ has_umfpack = True
36
+ except ImportError:
37
+ has_umfpack = False
38
+
39
+ def toarray(a):
40
+ if issparse(a):
41
+ return a.toarray()
42
+ else:
43
+ return a
44
+
45
+
46
+ def setup_bug_8278():
47
+ N = 2 ** 6
48
+ h = 1/N
49
+ Ah1D = dia_array(([-1, 2, -1], [-1, 0, 1]), shape=(N-1, N-1))/(h**2)
50
+ eyeN = eye_array(N - 1)
51
+ A = (kron(eyeN, kron(eyeN, Ah1D))
52
+ + kron(eyeN, kron(Ah1D, eyeN))
53
+ + kron(Ah1D, kron(eyeN, eyeN)))
54
+ b = np.random.rand((N-1)**3)
55
+ return A, b
56
+
57
+
58
+ class TestFactorized:
59
+ def setup_method(self):
60
+ n = 5
61
+ d = arange(n) + 1
62
+ self.n = n
63
+ self.A = dia_array(((d, 2*d, d[::-1]), (-3, 0, 5)), shape=(n,n)).tocsc()
64
+ random.seed(1234)
65
+
66
+ def _check_singular(self):
67
+ A = csc_array((5,5), dtype='d')
68
+ b = ones(5)
69
+ assert_array_almost_equal(0. * b, factorized(A)(b))
70
+
71
+ def _check_non_singular(self):
72
+ # Make a diagonal dominant, to make sure it is not singular
73
+ n = 5
74
+ a = csc_array(random.rand(n, n))
75
+ b = ones(n)
76
+
77
+ expected = splu(a).solve(b)
78
+ assert_array_almost_equal(factorized(a)(b), expected)
79
+
80
+ def test_singular_without_umfpack(self):
81
+ use_solver(useUmfpack=False)
82
+ with assert_raises(RuntimeError, match="Factor is exactly singular"):
83
+ self._check_singular()
84
+
85
+ @pytest.mark.skipif(not has_umfpack, reason="umfpack not available")
86
+ def test_singular_with_umfpack(self):
87
+ use_solver(useUmfpack=True)
88
+ with suppress_warnings() as sup:
89
+ sup.filter(RuntimeWarning, "divide by zero encountered in double_scalars")
90
+ assert_warns(umfpack.UmfpackWarning, self._check_singular)
91
+
92
+ def test_non_singular_without_umfpack(self):
93
+ use_solver(useUmfpack=False)
94
+ self._check_non_singular()
95
+
96
+ @pytest.mark.skipif(not has_umfpack, reason="umfpack not available")
97
+ def test_non_singular_with_umfpack(self):
98
+ use_solver(useUmfpack=True)
99
+ self._check_non_singular()
100
+
101
+ def test_cannot_factorize_nonsquare_matrix_without_umfpack(self):
102
+ use_solver(useUmfpack=False)
103
+ msg = "can only factor square matrices"
104
+ with assert_raises(ValueError, match=msg):
105
+ factorized(self.A[:, :4])
106
+
107
+ @pytest.mark.skipif(not has_umfpack, reason="umfpack not available")
108
+ def test_factorizes_nonsquare_matrix_with_umfpack(self):
109
+ use_solver(useUmfpack=True)
110
+ # does not raise
111
+ factorized(self.A[:,:4])
112
+
113
+ def test_call_with_incorrectly_sized_matrix_without_umfpack(self):
114
+ use_solver(useUmfpack=False)
115
+ solve = factorized(self.A)
116
+ b = random.rand(4)
117
+ B = random.rand(4, 3)
118
+ BB = random.rand(self.n, 3, 9)
119
+
120
+ with assert_raises(ValueError, match="is of incompatible size"):
121
+ solve(b)
122
+ with assert_raises(ValueError, match="is of incompatible size"):
123
+ solve(B)
124
+ with assert_raises(ValueError,
125
+ match="object too deep for desired array"):
126
+ solve(BB)
127
+
128
+ @pytest.mark.skipif(not has_umfpack, reason="umfpack not available")
129
+ def test_call_with_incorrectly_sized_matrix_with_umfpack(self):
130
+ use_solver(useUmfpack=True)
131
+ solve = factorized(self.A)
132
+ b = random.rand(4)
133
+ B = random.rand(4, 3)
134
+ BB = random.rand(self.n, 3, 9)
135
+
136
+ # does not raise
137
+ solve(b)
138
+ msg = "object too deep for desired array"
139
+ with assert_raises(ValueError, match=msg):
140
+ solve(B)
141
+ with assert_raises(ValueError, match=msg):
142
+ solve(BB)
143
+
144
+ def test_call_with_cast_to_complex_without_umfpack(self):
145
+ use_solver(useUmfpack=False)
146
+ solve = factorized(self.A)
147
+ b = random.rand(4)
148
+ for t in [np.complex64, np.complex128]:
149
+ with assert_raises(TypeError, match="Cannot cast array data"):
150
+ solve(b.astype(t))
151
+
152
+ @pytest.mark.skipif(not has_umfpack, reason="umfpack not available")
153
+ def test_call_with_cast_to_complex_with_umfpack(self):
154
+ use_solver(useUmfpack=True)
155
+ solve = factorized(self.A)
156
+ b = random.rand(4)
157
+ for t in [np.complex64, np.complex128]:
158
+ assert_warns(ComplexWarning, solve, b.astype(t))
159
+
160
+ @pytest.mark.skipif(not has_umfpack, reason="umfpack not available")
161
+ def test_assume_sorted_indices_flag(self):
162
+ # a sparse matrix with unsorted indices
163
+ unsorted_inds = np.array([2, 0, 1, 0])
164
+ data = np.array([10, 16, 5, 0.4])
165
+ indptr = np.array([0, 1, 2, 4])
166
+ A = csc_array((data, unsorted_inds, indptr), (3, 3))
167
+ b = ones(3)
168
+
169
+ # should raise when incorrectly assuming indices are sorted
170
+ use_solver(useUmfpack=True, assumeSortedIndices=True)
171
+ with assert_raises(RuntimeError,
172
+ match="UMFPACK_ERROR_invalid_matrix"):
173
+ factorized(A)
174
+
175
+ # should sort indices and succeed when not assuming indices are sorted
176
+ use_solver(useUmfpack=True, assumeSortedIndices=False)
177
+ expected = splu(A.copy()).solve(b)
178
+
179
+ assert_equal(A.has_sorted_indices, 0)
180
+ assert_array_almost_equal(factorized(A)(b), expected)
181
+
182
+ @pytest.mark.slow
183
+ @pytest.mark.skipif(not has_umfpack, reason="umfpack not available")
184
+ def test_bug_8278(self):
185
+ check_free_memory(8000)
186
+ use_solver(useUmfpack=True)
187
+ A, b = setup_bug_8278()
188
+ A = A.tocsc()
189
+ f = factorized(A)
190
+ x = f(b)
191
+ assert_array_almost_equal(A @ x, b)
192
+
193
+
194
+ class TestLinsolve:
195
+ def setup_method(self):
196
+ use_solver(useUmfpack=False)
197
+
198
+ def test_singular(self):
199
+ A = csc_array((5,5), dtype='d')
200
+ b = array([1, 2, 3, 4, 5],dtype='d')
201
+ with suppress_warnings() as sup:
202
+ sup.filter(MatrixRankWarning, "Matrix is exactly singular")
203
+ x = spsolve(A, b)
204
+ assert_(not np.isfinite(x).any())
205
+
206
+ def test_singular_gh_3312(self):
207
+ # "Bad" test case that leads SuperLU to call LAPACK with invalid
208
+ # arguments. Check that it fails moderately gracefully.
209
+ ij = np.array([(17, 0), (17, 6), (17, 12), (10, 13)], dtype=np.int32)
210
+ v = np.array([0.284213, 0.94933781, 0.15767017, 0.38797296])
211
+ A = csc_array((v, ij.T), shape=(20, 20))
212
+ b = np.arange(20)
213
+
214
+ try:
215
+ # should either raise a runtime error or return value
216
+ # appropriate for singular input (which yields the warning)
217
+ with suppress_warnings() as sup:
218
+ sup.filter(MatrixRankWarning, "Matrix is exactly singular")
219
+ x = spsolve(A, b)
220
+ assert not np.isfinite(x).any()
221
+ except RuntimeError:
222
+ pass
223
+
224
+ @pytest.mark.parametrize('format', ['csc', 'csr'])
225
+ @pytest.mark.parametrize('idx_dtype', [np.int32, np.int64])
226
+ def test_twodiags(self, format: str, idx_dtype: np.dtype):
227
+ A = dia_array(([[1, 2, 3, 4, 5], [6, 5, 8, 9, 10]], [0, 1]),
228
+ shape=(5, 5)).asformat(format)
229
+ b = array([1, 2, 3, 4, 5])
230
+
231
+ # condition number of A
232
+ cond_A = norm(A.toarray(), 2) * norm(inv(A.toarray()), 2)
233
+
234
+ for t in ['f','d','F','D']:
235
+ eps = finfo(t).eps # floating point epsilon
236
+ b = b.astype(t)
237
+ Asp = A.astype(t)
238
+ Asp.indices = Asp.indices.astype(idx_dtype, copy=False)
239
+ Asp.indptr = Asp.indptr.astype(idx_dtype, copy=False)
240
+
241
+ x = spsolve(Asp, b)
242
+ assert_(norm(b - Asp@x) < 10 * cond_A * eps)
243
+
244
+ def test_bvector_smoketest(self):
245
+ Adense = array([[0., 1., 1.],
246
+ [1., 0., 1.],
247
+ [0., 0., 1.]])
248
+ As = csc_array(Adense)
249
+ random.seed(1234)
250
+ x = random.randn(3)
251
+ b = As@x
252
+ x2 = spsolve(As, b)
253
+
254
+ assert_array_almost_equal(x, x2)
255
+
256
+ def test_bmatrix_smoketest(self):
257
+ Adense = array([[0., 1., 1.],
258
+ [1., 0., 1.],
259
+ [0., 0., 1.]])
260
+ As = csc_array(Adense)
261
+ random.seed(1234)
262
+ x = random.randn(3, 4)
263
+ Bdense = As.dot(x)
264
+ Bs = csc_array(Bdense)
265
+ x2 = spsolve(As, Bs)
266
+ assert_array_almost_equal(x, x2.toarray())
267
+
268
+ @pytest.mark.thread_unsafe
269
+ @sup_sparse_efficiency
270
+ def test_non_square(self):
271
+ # A is not square.
272
+ A = ones((3, 4))
273
+ b = ones((4, 1))
274
+ assert_raises(ValueError, spsolve, A, b)
275
+ # A2 and b2 have incompatible shapes.
276
+ A2 = csc_array(eye(3))
277
+ b2 = array([1.0, 2.0])
278
+ assert_raises(ValueError, spsolve, A2, b2)
279
+
280
+ @pytest.mark.thread_unsafe
281
+ @sup_sparse_efficiency
282
+ def test_example_comparison(self):
283
+ row = array([0,0,1,2,2,2])
284
+ col = array([0,2,2,0,1,2])
285
+ data = array([1,2,3,-4,5,6])
286
+ sM = csr_array((data,(row,col)), shape=(3,3), dtype=float)
287
+ M = sM.toarray()
288
+
289
+ row = array([0,0,1,1,0,0])
290
+ col = array([0,2,1,1,0,0])
291
+ data = array([1,1,1,1,1,1])
292
+ sN = csr_array((data, (row,col)), shape=(3,3), dtype=float)
293
+ N = sN.toarray()
294
+
295
+ sX = spsolve(sM, sN)
296
+ X = scipy.linalg.solve(M, N)
297
+
298
+ assert_array_almost_equal(X, sX.toarray())
299
+
300
+ @pytest.mark.thread_unsafe
301
+ @sup_sparse_efficiency
302
+ @pytest.mark.skipif(not has_umfpack, reason="umfpack not available")
303
+ def test_shape_compatibility(self):
304
+ use_solver(useUmfpack=True)
305
+ A = csc_array([[1., 0], [0, 2]])
306
+ bs = [
307
+ [1, 6],
308
+ array([1, 6]),
309
+ [[1], [6]],
310
+ array([[1], [6]]),
311
+ csc_array([[1], [6]]),
312
+ csr_array([[1], [6]]),
313
+ dok_array([[1], [6]]),
314
+ bsr_array([[1], [6]]),
315
+ array([[1., 2., 3.], [6., 8., 10.]]),
316
+ csc_array([[1., 2., 3.], [6., 8., 10.]]),
317
+ csr_array([[1., 2., 3.], [6., 8., 10.]]),
318
+ dok_array([[1., 2., 3.], [6., 8., 10.]]),
319
+ bsr_array([[1., 2., 3.], [6., 8., 10.]]),
320
+ ]
321
+
322
+ for b in bs:
323
+ x = np.linalg.solve(A.toarray(), toarray(b))
324
+ for spmattype in [csc_array, csr_array, dok_array, lil_array]:
325
+ x1 = spsolve(spmattype(A), b, use_umfpack=True)
326
+ x2 = spsolve(spmattype(A), b, use_umfpack=False)
327
+
328
+ # check solution
329
+ if x.ndim == 2 and x.shape[1] == 1:
330
+ # interprets also these as "vectors"
331
+ x = x.ravel()
332
+
333
+ assert_array_almost_equal(toarray(x1), x,
334
+ err_msg=repr((b, spmattype, 1)))
335
+ assert_array_almost_equal(toarray(x2), x,
336
+ err_msg=repr((b, spmattype, 2)))
337
+
338
+ # dense vs. sparse output ("vectors" are always dense)
339
+ if issparse(b) and x.ndim > 1:
340
+ assert_(issparse(x1), repr((b, spmattype, 1)))
341
+ assert_(issparse(x2), repr((b, spmattype, 2)))
342
+ else:
343
+ assert_(isinstance(x1, np.ndarray), repr((b, spmattype, 1)))
344
+ assert_(isinstance(x2, np.ndarray), repr((b, spmattype, 2)))
345
+
346
+ # check output shape
347
+ if x.ndim == 1:
348
+ # "vector"
349
+ assert_equal(x1.shape, (A.shape[1],))
350
+ assert_equal(x2.shape, (A.shape[1],))
351
+ else:
352
+ # "matrix"
353
+ assert_equal(x1.shape, x.shape)
354
+ assert_equal(x2.shape, x.shape)
355
+
356
+ A = csc_array((3, 3))
357
+ b = csc_array((1, 3))
358
+ assert_raises(ValueError, spsolve, A, b)
359
+
360
+ @pytest.mark.thread_unsafe
361
+ @sup_sparse_efficiency
362
+ def test_ndarray_support(self):
363
+ A = array([[1., 2.], [2., 0.]])
364
+ x = array([[1., 1.], [0.5, -0.5]])
365
+ b = array([[2., 0.], [2., 2.]])
366
+
367
+ assert_array_almost_equal(x, spsolve(A, b))
368
+
369
+ def test_gssv_badinput(self):
370
+ N = 10
371
+ d = arange(N) + 1.0
372
+ A = dia_array(((d, 2*d, d[::-1]), (-3, 0, 5)), shape=(N, N))
373
+
374
+ for container in (csc_array, csr_array):
375
+ A = container(A)
376
+ b = np.arange(N)
377
+
378
+ def not_c_contig(x):
379
+ return x.repeat(2)[::2]
380
+
381
+ def not_1dim(x):
382
+ return x[:,None]
383
+
384
+ def bad_type(x):
385
+ return x.astype(bool)
386
+
387
+ def too_short(x):
388
+ return x[:-1]
389
+
390
+ badops = [not_c_contig, not_1dim, bad_type, too_short]
391
+
392
+ for badop in badops:
393
+ msg = f"{container!r} {badop!r}"
394
+ # Not C-contiguous
395
+ assert_raises((ValueError, TypeError), _superlu.gssv,
396
+ N, A.nnz, badop(A.data), A.indices, A.indptr,
397
+ b, int(A.format == 'csc'), err_msg=msg)
398
+ assert_raises((ValueError, TypeError), _superlu.gssv,
399
+ N, A.nnz, A.data, badop(A.indices), A.indptr,
400
+ b, int(A.format == 'csc'), err_msg=msg)
401
+ assert_raises((ValueError, TypeError), _superlu.gssv,
402
+ N, A.nnz, A.data, A.indices, badop(A.indptr),
403
+ b, int(A.format == 'csc'), err_msg=msg)
404
+
405
+ def test_sparsity_preservation(self):
406
+ ident = csc_array([
407
+ [1, 0, 0],
408
+ [0, 1, 0],
409
+ [0, 0, 1]])
410
+ b = csc_array([
411
+ [0, 1],
412
+ [1, 0],
413
+ [0, 0]])
414
+ x = spsolve(ident, b)
415
+ assert_equal(ident.nnz, 3)
416
+ assert_equal(b.nnz, 2)
417
+ assert_equal(x.nnz, 2)
418
+ assert_allclose(x.toarray(), b.toarray(), atol=1e-12, rtol=1e-12)
419
+
420
+ def test_dtype_cast(self):
421
+ A_real = scipy.sparse.csr_array([[1, 2, 0],
422
+ [0, 0, 3],
423
+ [4, 0, 5]])
424
+ A_complex = scipy.sparse.csr_array([[1, 2, 0],
425
+ [0, 0, 3],
426
+ [4, 0, 5 + 1j]])
427
+ b_real = np.array([1,1,1])
428
+ b_complex = np.array([1,1,1]) + 1j*np.array([1,1,1])
429
+ x = spsolve(A_real, b_real)
430
+ assert_(np.issubdtype(x.dtype, np.floating))
431
+ x = spsolve(A_real, b_complex)
432
+ assert_(np.issubdtype(x.dtype, np.complexfloating))
433
+ x = spsolve(A_complex, b_real)
434
+ assert_(np.issubdtype(x.dtype, np.complexfloating))
435
+ x = spsolve(A_complex, b_complex)
436
+ assert_(np.issubdtype(x.dtype, np.complexfloating))
437
+
438
+ @pytest.mark.slow
439
+ @pytest.mark.skipif(not has_umfpack, reason="umfpack not available")
440
+ def test_bug_8278(self):
441
+ check_free_memory(8000)
442
+ use_solver(useUmfpack=True)
443
+ A, b = setup_bug_8278()
444
+ x = spsolve(A, b)
445
+ assert_array_almost_equal(A @ x, b)
446
+
447
+
448
+ class TestSplu:
449
+ def setup_method(self):
450
+ use_solver(useUmfpack=False)
451
+ n = 40
452
+ d = arange(n) + 1
453
+ self.n = n
454
+ self.A = dia_array(((d, 2*d, d[::-1]), (-3, 0, 5)), shape=(n, n)).tocsc()
455
+ random.seed(1234)
456
+
457
+ def _smoketest(self, spxlu, check, dtype, idx_dtype):
458
+ if np.issubdtype(dtype, np.complexfloating):
459
+ A = self.A + 1j*self.A.T
460
+ else:
461
+ A = self.A
462
+
463
+ A = A.astype(dtype)
464
+ A.indices = A.indices.astype(idx_dtype, copy=False)
465
+ A.indptr = A.indptr.astype(idx_dtype, copy=False)
466
+ lu = spxlu(A)
467
+
468
+ rng = random.RandomState(1234)
469
+
470
+ # Input shapes
471
+ for k in [None, 1, 2, self.n, self.n+2]:
472
+ msg = f"k={k!r}"
473
+
474
+ if k is None:
475
+ b = rng.rand(self.n)
476
+ else:
477
+ b = rng.rand(self.n, k)
478
+
479
+ if np.issubdtype(dtype, np.complexfloating):
480
+ b = b + 1j*rng.rand(*b.shape)
481
+ b = b.astype(dtype)
482
+
483
+ x = lu.solve(b)
484
+ check(A, b, x, msg)
485
+
486
+ x = lu.solve(b, 'T')
487
+ check(A.T, b, x, msg)
488
+
489
+ x = lu.solve(b, 'H')
490
+ check(A.T.conj(), b, x, msg)
491
+
492
+ @pytest.mark.thread_unsafe
493
+ @sup_sparse_efficiency
494
+ def test_splu_smoketest(self):
495
+ self._internal_test_splu_smoketest()
496
+
497
+ def _internal_test_splu_smoketest(self):
498
+ # Check that splu works at all
499
+ def check(A, b, x, msg=""):
500
+ eps = np.finfo(A.dtype).eps
501
+ r = A @ x
502
+ assert_(abs(r - b).max() < 1e3*eps, msg)
503
+
504
+ for dtype in [np.float32, np.float64, np.complex64, np.complex128]:
505
+ for idx_dtype in [np.int32, np.int64]:
506
+ self._smoketest(splu, check, dtype, idx_dtype)
507
+
508
+ @pytest.mark.thread_unsafe
509
+ @sup_sparse_efficiency
510
+ def test_spilu_smoketest(self):
511
+ self._internal_test_spilu_smoketest()
512
+
513
+ def _internal_test_spilu_smoketest(self):
514
+ errors = []
515
+
516
+ def check(A, b, x, msg=""):
517
+ r = A @ x
518
+ err = abs(r - b).max()
519
+ assert_(err < 1e-2, msg)
520
+ if b.dtype in (np.float64, np.complex128):
521
+ errors.append(err)
522
+
523
+ for dtype in [np.float32, np.float64, np.complex64, np.complex128]:
524
+ for idx_dtype in [np.int32, np.int64]:
525
+ self._smoketest(spilu, check, dtype, idx_dtype)
526
+
527
+ assert_(max(errors) > 1e-5)
528
+
529
+ @pytest.mark.thread_unsafe
530
+ @sup_sparse_efficiency
531
+ def test_spilu_drop_rule(self):
532
+ # Test passing in the drop_rule argument to spilu.
533
+ A = eye_array(2)
534
+
535
+ rules = [
536
+ b'basic,area'.decode('ascii'), # unicode
537
+ b'basic,area', # ascii
538
+ [b'basic', b'area'.decode('ascii')]
539
+ ]
540
+ for rule in rules:
541
+ # Argument should be accepted
542
+ assert_(isinstance(spilu(A, drop_rule=rule), SuperLU))
543
+
544
+ def test_splu_nnz0(self):
545
+ A = csc_array((5,5), dtype='d')
546
+ assert_raises(RuntimeError, splu, A)
547
+
548
+ def test_spilu_nnz0(self):
549
+ A = csc_array((5,5), dtype='d')
550
+ assert_raises(RuntimeError, spilu, A)
551
+
552
+ def test_splu_basic(self):
553
+ # Test basic splu functionality.
554
+ n = 30
555
+ rng = random.RandomState(12)
556
+ a = rng.rand(n, n)
557
+ a[a < 0.95] = 0
558
+ # First test with a singular matrix
559
+ a[:, 0] = 0
560
+ a_ = csc_array(a)
561
+ # Matrix is exactly singular
562
+ assert_raises(RuntimeError, splu, a_)
563
+
564
+ # Make a diagonal dominant, to make sure it is not singular
565
+ a += 4*eye(n)
566
+ a_ = csc_array(a)
567
+ lu = splu(a_)
568
+ b = ones(n)
569
+ x = lu.solve(b)
570
+ assert_almost_equal(dot(a, x), b)
571
+
572
+ def test_splu_perm(self):
573
+ # Test the permutation vectors exposed by splu.
574
+ n = 30
575
+ a = random.random((n, n))
576
+ a[a < 0.95] = 0
577
+ # Make a diagonal dominant, to make sure it is not singular
578
+ a += 4*eye(n)
579
+ a_ = csc_array(a)
580
+ lu = splu(a_)
581
+ # Check that the permutation indices do belong to [0, n-1].
582
+ for perm in (lu.perm_r, lu.perm_c):
583
+ assert_(all(perm > -1))
584
+ assert_(all(perm < n))
585
+ assert_equal(len(unique(perm)), len(perm))
586
+
587
+ # Now make a symmetric, and test that the two permutation vectors are
588
+ # the same
589
+ # Note: a += a.T relies on undefined behavior.
590
+ a = a + a.T
591
+ a_ = csc_array(a)
592
+ lu = splu(a_)
593
+ assert_array_equal(lu.perm_r, lu.perm_c)
594
+
595
+ @pytest.mark.parametrize("splu_fun, rtol", [(splu, 1e-7), (spilu, 1e-1)])
596
+ def test_natural_permc(self, splu_fun, rtol):
597
+ # Test that the "NATURAL" permc_spec does not permute the matrix
598
+ rng = np.random.RandomState(42)
599
+ n = 500
600
+ p = 0.01
601
+ A = scipy.sparse.random(n, n, p, random_state=rng)
602
+ x = rng.rand(n)
603
+ # Make A diagonal dominant to make sure it is not singular
604
+ A += (n+1)*scipy.sparse.eye_array(n)
605
+ A_ = csc_array(A)
606
+ b = A_ @ x
607
+
608
+ # without permc_spec, permutation is not identity
609
+ lu = splu_fun(A_)
610
+ assert_(np.any(lu.perm_c != np.arange(n)))
611
+
612
+ # with permc_spec="NATURAL", permutation is identity
613
+ lu = splu_fun(A_, permc_spec="NATURAL")
614
+ assert_array_equal(lu.perm_c, np.arange(n))
615
+
616
+ # Also, lu decomposition is valid
617
+ x2 = lu.solve(b)
618
+ assert_allclose(x, x2, rtol=rtol)
619
+
620
+ @pytest.mark.skipif(not hasattr(sys, 'getrefcount'), reason="no sys.getrefcount")
621
+ def test_lu_refcount(self):
622
+ # Test that we are keeping track of the reference count with splu.
623
+ n = 30
624
+ a = random.random((n, n))
625
+ a[a < 0.95] = 0
626
+ # Make a diagonal dominant, to make sure it is not singular
627
+ a += 4*eye(n)
628
+ a_ = csc_array(a)
629
+ lu = splu(a_)
630
+
631
+ # And now test that we don't have a refcount bug
632
+ rc = sys.getrefcount(lu)
633
+ for attr in ('perm_r', 'perm_c'):
634
+ perm = getattr(lu, attr)
635
+ assert_equal(sys.getrefcount(lu), rc + 1)
636
+ del perm
637
+ assert_equal(sys.getrefcount(lu), rc)
638
+
639
+ def test_bad_inputs(self):
640
+ A = self.A.tocsc()
641
+
642
+ assert_raises(ValueError, splu, A[:,:4])
643
+ assert_raises(ValueError, spilu, A[:,:4])
644
+
645
+ for lu in [splu(A), spilu(A)]:
646
+ b = random.rand(42)
647
+ B = random.rand(42, 3)
648
+ BB = random.rand(self.n, 3, 9)
649
+ assert_raises(ValueError, lu.solve, b)
650
+ assert_raises(ValueError, lu.solve, B)
651
+ assert_raises(ValueError, lu.solve, BB)
652
+ assert_raises(TypeError, lu.solve,
653
+ b.astype(np.complex64))
654
+ assert_raises(TypeError, lu.solve,
655
+ b.astype(np.complex128))
656
+
657
+ @pytest.mark.thread_unsafe
658
+ @sup_sparse_efficiency
659
+ def test_superlu_dlamch_i386_nan(self):
660
+ # SuperLU 4.3 calls some functions returning floats without
661
+ # declaring them. On i386@linux call convention, this fails to
662
+ # clear floating point registers after call. As a result, NaN
663
+ # can appear in the next floating point operation made.
664
+ #
665
+ # Here's a test case that triggered the issue.
666
+ n = 8
667
+ d = np.arange(n) + 1
668
+ A = dia_array(((d, 2*d, d[::-1]), (-3, 0, 5)), shape=(n, n))
669
+ A = A.astype(np.float32)
670
+ spilu(A)
671
+ A = A + 1j*A
672
+ B = A.toarray()
673
+ assert_(not np.isnan(B).any())
674
+
675
+ @pytest.mark.thread_unsafe
676
+ @sup_sparse_efficiency
677
+ def test_lu_attr(self):
678
+
679
+ def check(dtype, complex_2=False):
680
+ A = self.A.astype(dtype)
681
+
682
+ if complex_2:
683
+ A = A + 1j*A.T
684
+
685
+ n = A.shape[0]
686
+ lu = splu(A)
687
+
688
+ # Check that the decomposition is as advertised
689
+
690
+ Pc = np.zeros((n, n))
691
+ Pc[np.arange(n), lu.perm_c] = 1
692
+
693
+ Pr = np.zeros((n, n))
694
+ Pr[lu.perm_r, np.arange(n)] = 1
695
+
696
+ Ad = A.toarray()
697
+ lhs = Pr.dot(Ad).dot(Pc)
698
+ rhs = (lu.L @ lu.U).toarray()
699
+
700
+ eps = np.finfo(dtype).eps
701
+
702
+ assert_allclose(lhs, rhs, atol=100*eps)
703
+
704
+ check(np.float32)
705
+ check(np.float64)
706
+ check(np.complex64)
707
+ check(np.complex128)
708
+ check(np.complex64, True)
709
+ check(np.complex128, True)
710
+
711
+ @pytest.mark.thread_unsafe
712
+ @pytest.mark.slow
713
+ @sup_sparse_efficiency
714
+ def test_threads_parallel(self):
715
+ oks = []
716
+
717
+ def worker():
718
+ try:
719
+ self.test_splu_basic()
720
+ self._internal_test_splu_smoketest()
721
+ self._internal_test_spilu_smoketest()
722
+ oks.append(True)
723
+ except Exception:
724
+ pass
725
+
726
+ threads = [threading.Thread(target=worker)
727
+ for k in range(20)]
728
+ for t in threads:
729
+ t.start()
730
+ for t in threads:
731
+ t.join()
732
+
733
+ assert_equal(len(oks), 20)
734
+
735
+ @pytest.mark.thread_unsafe
736
+ def test_singular_matrix(self):
737
+ # Test that SuperLU does not print to stdout when a singular matrix is
738
+ # passed. See gh-20993.
739
+ A = eye_array(10, format='csr')
740
+ A[-1, -1] = 0
741
+ b = np.zeros(10)
742
+ with pytest.warns(MatrixRankWarning):
743
+ res = spsolve(A, b)
744
+ assert np.isnan(res).all()
745
+
746
+
747
+ class TestGstrsErrors:
748
+ def setup_method(self):
749
+ self.A = array([[1.0,2.0,3.0],[4.0,5.0,6.0],[7.0,8.0,9.0]], dtype=np.float64)
750
+ self.b = np.array([[1.0],[2.0],[3.0]], dtype=np.float64)
751
+
752
+ def test_trans(self):
753
+ L = scipy.sparse.tril(self.A, format='csc')
754
+ U = scipy.sparse.triu(self.A, k=1, format='csc')
755
+ with assert_raises(ValueError, match="trans must be N, T, or H"):
756
+ _superlu.gstrs('X', L.shape[0], L.nnz, L.data, L.indices, L.indptr,
757
+ U.shape[0], U.nnz, U.data, U.indices, U.indptr, self.b)
758
+
759
+ def test_shape_LU(self):
760
+ L = scipy.sparse.tril(self.A[0:2,0:2], format='csc')
761
+ U = scipy.sparse.triu(self.A, k=1, format='csc')
762
+ with assert_raises(ValueError, match="L and U must have the same dimension"):
763
+ _superlu.gstrs('N', L.shape[0], L.nnz, L.data, L.indices, L.indptr,
764
+ U.shape[0], U.nnz, U.data, U.indices, U.indptr, self.b)
765
+
766
+ def test_shape_b(self):
767
+ L = scipy.sparse.tril(self.A, format='csc')
768
+ U = scipy.sparse.triu(self.A, k=1, format='csc')
769
+ with assert_raises(ValueError, match="right hand side array has invalid shape"):
770
+ _superlu.gstrs('N', L.shape[0], L.nnz, L.data, L.indices, L.indptr,
771
+ U.shape[0], U.nnz, U.data, U.indices, U.indptr,
772
+ self.b[0:2])
773
+
774
+ def test_types_differ(self):
775
+ L = scipy.sparse.tril(self.A.astype(np.float32), format='csc')
776
+ U = scipy.sparse.triu(self.A, k=1, format='csc')
777
+ with assert_raises(TypeError, match="nzvals types of L and U differ"):
778
+ _superlu.gstrs('N', L.shape[0], L.nnz, L.data, L.indices, L.indptr,
779
+ U.shape[0], U.nnz, U.data, U.indices, U.indptr, self.b)
780
+
781
+ def test_types_unsupported(self):
782
+ L = scipy.sparse.tril(self.A.astype(np.uint8), format='csc')
783
+ U = scipy.sparse.triu(self.A.astype(np.uint8), k=1, format='csc')
784
+ with assert_raises(TypeError, match="nzvals is not of a type supported"):
785
+ _superlu.gstrs('N', L.shape[0], L.nnz, L.data, L.indices, L.indptr,
786
+ U.shape[0], U.nnz, U.data, U.indices, U.indptr,
787
+ self.b.astype(np.uint8))
788
+
789
+ class TestSpsolveTriangular:
790
+ def setup_method(self):
791
+ use_solver(useUmfpack=False)
792
+
793
+ @pytest.mark.parametrize("fmt",["csr","csc"])
794
+ def test_zero_diagonal(self,fmt):
795
+ n = 5
796
+ rng = np.random.default_rng(43876432987)
797
+ A = rng.standard_normal((n, n))
798
+ b = np.arange(n)
799
+ A = scipy.sparse.tril(A, k=0, format=fmt)
800
+
801
+ x = spsolve_triangular(A, b, unit_diagonal=True, lower=True)
802
+
803
+ A.setdiag(1)
804
+ assert_allclose(A.dot(x), b)
805
+
806
+ # Regression test from gh-15199
807
+ A = np.array([[0, 0, 0], [1, 0, 0], [1, 1, 0]], dtype=np.float64)
808
+ b = np.array([1., 2., 3.])
809
+ with suppress_warnings() as sup:
810
+ sup.filter(SparseEfficiencyWarning, "CSC or CSR matrix format is")
811
+ spsolve_triangular(A, b, unit_diagonal=True)
812
+
813
+ @pytest.mark.parametrize("fmt",["csr","csc"])
814
+ def test_singular(self,fmt):
815
+ n = 5
816
+ if fmt == "csr":
817
+ A = csr_array((n, n))
818
+ else:
819
+ A = csc_array((n, n))
820
+ b = np.arange(n)
821
+ for lower in (True, False):
822
+ assert_raises(scipy.linalg.LinAlgError,
823
+ spsolve_triangular, A, b, lower=lower)
824
+
825
+ @pytest.mark.thread_unsafe
826
+ @sup_sparse_efficiency
827
+ def test_bad_shape(self):
828
+ # A is not square.
829
+ A = np.zeros((3, 4))
830
+ b = ones((4, 1))
831
+ assert_raises(ValueError, spsolve_triangular, A, b)
832
+ # A2 and b2 have incompatible shapes.
833
+ A2 = csr_array(eye(3))
834
+ b2 = array([1.0, 2.0])
835
+ assert_raises(ValueError, spsolve_triangular, A2, b2)
836
+
837
+ @pytest.mark.thread_unsafe
838
+ @sup_sparse_efficiency
839
+ def test_input_types(self):
840
+ A = array([[1., 0.], [1., 2.]])
841
+ b = array([[2., 0.], [2., 2.]])
842
+ for matrix_type in (array, csc_array, csr_array):
843
+ x = spsolve_triangular(matrix_type(A), b, lower=True)
844
+ assert_array_almost_equal(A.dot(x), b)
845
+
846
+ @pytest.mark.thread_unsafe
847
+ @pytest.mark.slow
848
+ @sup_sparse_efficiency
849
+ @pytest.mark.parametrize("n", [10, 10**2, 10**3])
850
+ @pytest.mark.parametrize("m", [1, 10])
851
+ @pytest.mark.parametrize("lower", [True, False])
852
+ @pytest.mark.parametrize("format", ["csr", "csc"])
853
+ @pytest.mark.parametrize("unit_diagonal", [False, True])
854
+ @pytest.mark.parametrize("choice_of_A", ["real", "complex"])
855
+ @pytest.mark.parametrize("choice_of_b", ["floats", "ints", "complexints"])
856
+ def test_random(self, n, m, lower, format, unit_diagonal, choice_of_A, choice_of_b):
857
+ def random_triangle_matrix(n, lower=True, format="csr", choice_of_A="real"):
858
+ if choice_of_A == "real":
859
+ dtype = np.float64
860
+ elif choice_of_A == "complex":
861
+ dtype = np.complex128
862
+ else:
863
+ raise ValueError("choice_of_A must be 'real' or 'complex'.")
864
+ rng = np.random.default_rng(789002319)
865
+ rvs = rng.random
866
+ A = scipy.sparse.random(n, n, density=0.1, format='lil', dtype=dtype,
867
+ random_state=rng, data_rvs=rvs)
868
+ if lower:
869
+ A = scipy.sparse.tril(A, format="lil")
870
+ else:
871
+ A = scipy.sparse.triu(A, format="lil")
872
+ for i in range(n):
873
+ A[i, i] = np.random.rand() + 1
874
+ if format == "csc":
875
+ A = A.tocsc(copy=False)
876
+ else:
877
+ A = A.tocsr(copy=False)
878
+ return A
879
+
880
+ np.random.seed(1234)
881
+ A = random_triangle_matrix(n, lower=lower)
882
+ if choice_of_b == "floats":
883
+ b = np.random.rand(n, m)
884
+ elif choice_of_b == "ints":
885
+ b = np.random.randint(-9, 9, (n, m))
886
+ elif choice_of_b == "complexints":
887
+ b = np.random.randint(-9, 9, (n, m)) + np.random.randint(-9, 9, (n, m)) * 1j
888
+ else:
889
+ raise ValueError(
890
+ "choice_of_b must be 'floats', 'ints', or 'complexints'.")
891
+ x = spsolve_triangular(A, b, lower=lower, unit_diagonal=unit_diagonal)
892
+ if unit_diagonal:
893
+ A.setdiag(1)
894
+ assert_allclose(A.dot(x), b, atol=1.5e-6)
895
+
896
+
897
+ @pytest.mark.thread_unsafe
898
+ @sup_sparse_efficiency
899
+ @pytest.mark.parametrize("nnz", [10, 10**2, 10**3])
900
+ @pytest.mark.parametrize("fmt", ["csr", "csc", "coo", "dia", "dok", "lil"])
901
+ def test_is_sptriangular_and_spbandwidth(nnz, fmt):
902
+ rng = np.random.default_rng(42)
903
+
904
+ N = nnz // 2
905
+ dens = 0.1
906
+ A = scipy.sparse.random_array((N, N), density=dens, format="csr", rng=rng)
907
+ A[1, 3] = A[3, 1] = 22 # ensure not upper or lower
908
+ A = A.asformat(fmt)
909
+ AU = scipy.sparse.triu(A, format=fmt)
910
+ AL = scipy.sparse.tril(A, format=fmt)
911
+ D = 0.1 * scipy.sparse.eye_array(N, format=fmt)
912
+
913
+ assert is_sptriangular(A) == (False, False)
914
+ assert is_sptriangular(AL) == (True, False)
915
+ assert is_sptriangular(AU) == (False, True)
916
+ assert is_sptriangular(D) == (True, True)
917
+
918
+ assert spbandwidth(A) == scipy.linalg.bandwidth(A.toarray())
919
+ assert spbandwidth(AU) == scipy.linalg.bandwidth(AU.toarray())
920
+ assert spbandwidth(AL) == scipy.linalg.bandwidth(AL.toarray())
921
+ assert spbandwidth(D) == scipy.linalg.bandwidth(D.toarray())
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/__init__.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Sparse Eigenvalue Solvers
3
+ -------------------------
4
+
5
+ The submodules of sparse.linalg._eigen:
6
+ 1. lobpcg: Locally Optimal Block Preconditioned Conjugate Gradient Method
7
+
8
+ """
9
+ from .arpack import *
10
+ from .lobpcg import *
11
+ from ._svds import svds
12
+
13
+ from . import arpack
14
+
15
+ __all__ = [
16
+ 'ArpackError', 'ArpackNoConvergence',
17
+ 'eigs', 'eigsh', 'lobpcg', 'svds'
18
+ ]
19
+
20
+ from scipy._lib._testutils import PytestTester
21
+ test = PytestTester(__name__)
22
+ del PytestTester
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/_svds.py ADDED
@@ -0,0 +1,540 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import numpy as np
3
+
4
+ from .arpack import _arpack # type: ignore[attr-defined]
5
+ from . import eigsh
6
+
7
+ from scipy._lib._util import check_random_state, _transition_to_rng
8
+ from scipy.sparse.linalg._interface import LinearOperator, aslinearoperator
9
+ from scipy.sparse.linalg._eigen.lobpcg import lobpcg # type: ignore[no-redef]
10
+ from scipy.sparse.linalg._svdp import _svdp
11
+ from scipy.linalg import svd
12
+
13
+ arpack_int = _arpack.timing.nbx.dtype
14
+ __all__ = ['svds']
15
+
16
+
17
+ def _herm(x):
18
+ return x.T.conj()
19
+
20
+
21
+ def _iv(A, k, ncv, tol, which, v0, maxiter,
22
+ return_singular, solver, rng):
23
+
24
+ # input validation/standardization for `solver`
25
+ # out of order because it's needed for other parameters
26
+ solver = str(solver).lower()
27
+ solvers = {"arpack", "lobpcg", "propack"}
28
+ if solver not in solvers:
29
+ raise ValueError(f"solver must be one of {solvers}.")
30
+
31
+ # input validation/standardization for `A`
32
+ A = aslinearoperator(A) # this takes care of some input validation
33
+ if not np.issubdtype(A.dtype, np.number):
34
+ message = "`A` must be of numeric data type."
35
+ raise ValueError(message)
36
+ if math.prod(A.shape) == 0:
37
+ message = "`A` must not be empty."
38
+ raise ValueError(message)
39
+
40
+ # input validation/standardization for `k`
41
+ kmax = min(A.shape) if solver == 'propack' else min(A.shape) - 1
42
+ if int(k) != k or not (0 < k <= kmax):
43
+ message = "`k` must be an integer satisfying `0 < k < min(A.shape)`."
44
+ raise ValueError(message)
45
+ k = int(k)
46
+
47
+ # input validation/standardization for `ncv`
48
+ if solver == "arpack" and ncv is not None:
49
+ if int(ncv) != ncv or not (k < ncv < min(A.shape)):
50
+ message = ("`ncv` must be an integer satisfying "
51
+ "`k < ncv < min(A.shape)`.")
52
+ raise ValueError(message)
53
+ ncv = int(ncv)
54
+
55
+ # input validation/standardization for `tol`
56
+ if tol < 0 or not np.isfinite(tol):
57
+ message = "`tol` must be a non-negative floating point value."
58
+ raise ValueError(message)
59
+ tol = float(tol)
60
+
61
+ # input validation/standardization for `which`
62
+ which = str(which).upper()
63
+ whichs = {'LM', 'SM'}
64
+ if which not in whichs:
65
+ raise ValueError(f"`which` must be in {whichs}.")
66
+
67
+ # input validation/standardization for `v0`
68
+ if v0 is not None:
69
+ v0 = np.atleast_1d(v0)
70
+ if not (np.issubdtype(v0.dtype, np.complexfloating)
71
+ or np.issubdtype(v0.dtype, np.floating)):
72
+ message = ("`v0` must be of floating or complex floating "
73
+ "data type.")
74
+ raise ValueError(message)
75
+
76
+ shape = (A.shape[0],) if solver == 'propack' else (min(A.shape),)
77
+ if v0.shape != shape:
78
+ message = f"`v0` must have shape {shape}."
79
+ raise ValueError(message)
80
+
81
+ # input validation/standardization for `maxiter`
82
+ if maxiter is not None and (int(maxiter) != maxiter or maxiter <= 0):
83
+ message = "`maxiter` must be a positive integer."
84
+ raise ValueError(message)
85
+ maxiter = int(maxiter) if maxiter is not None else maxiter
86
+
87
+ # input validation/standardization for `return_singular_vectors`
88
+ # not going to be flexible with this; too complicated for little gain
89
+ rs_options = {True, False, "vh", "u"}
90
+ if return_singular not in rs_options:
91
+ raise ValueError(f"`return_singular_vectors` must be in {rs_options}.")
92
+
93
+ rng = check_random_state(rng)
94
+
95
+ return (A, k, ncv, tol, which, v0, maxiter,
96
+ return_singular, solver, rng)
97
+
98
+
99
+ @_transition_to_rng("random_state", position_num=9)
100
+ def svds(A, k=6, ncv=None, tol=0, which='LM', v0=None,
101
+ maxiter=None, return_singular_vectors=True,
102
+ solver='arpack', rng=None, options=None):
103
+ """
104
+ Partial singular value decomposition of a sparse matrix.
105
+
106
+ Compute the largest or smallest `k` singular values and corresponding
107
+ singular vectors of a sparse matrix `A`. The order in which the singular
108
+ values are returned is not guaranteed.
109
+
110
+ In the descriptions below, let ``M, N = A.shape``.
111
+
112
+ Parameters
113
+ ----------
114
+ A : ndarray, sparse matrix, or LinearOperator
115
+ Matrix to decompose of a floating point numeric dtype.
116
+ k : int, default: 6
117
+ Number of singular values and singular vectors to compute.
118
+ Must satisfy ``1 <= k <= kmax``, where ``kmax=min(M, N)`` for
119
+ ``solver='propack'`` and ``kmax=min(M, N) - 1`` otherwise.
120
+ ncv : int, optional
121
+ When ``solver='arpack'``, this is the number of Lanczos vectors
122
+ generated. See :ref:`'arpack' <sparse.linalg.svds-arpack>` for details.
123
+ When ``solver='lobpcg'`` or ``solver='propack'``, this parameter is
124
+ ignored.
125
+ tol : float, optional
126
+ Tolerance for singular values. Zero (default) means machine precision.
127
+ which : {'LM', 'SM'}
128
+ Which `k` singular values to find: either the largest magnitude ('LM')
129
+ or smallest magnitude ('SM') singular values.
130
+ v0 : ndarray, optional
131
+ The starting vector for iteration; see method-specific
132
+ documentation (:ref:`'arpack' <sparse.linalg.svds-arpack>`,
133
+ :ref:`'lobpcg' <sparse.linalg.svds-lobpcg>`), or
134
+ :ref:`'propack' <sparse.linalg.svds-propack>` for details.
135
+ maxiter : int, optional
136
+ Maximum number of iterations; see method-specific
137
+ documentation (:ref:`'arpack' <sparse.linalg.svds-arpack>`,
138
+ :ref:`'lobpcg' <sparse.linalg.svds-lobpcg>`), or
139
+ :ref:`'propack' <sparse.linalg.svds-propack>` for details.
140
+ return_singular_vectors : {True, False, "u", "vh"}
141
+ Singular values are always computed and returned; this parameter
142
+ controls the computation and return of singular vectors.
143
+
144
+ - ``True``: return singular vectors.
145
+ - ``False``: do not return singular vectors.
146
+ - ``"u"``: if ``M <= N``, compute only the left singular vectors and
147
+ return ``None`` for the right singular vectors. Otherwise, compute
148
+ all singular vectors.
149
+ - ``"vh"``: if ``M > N``, compute only the right singular vectors and
150
+ return ``None`` for the left singular vectors. Otherwise, compute
151
+ all singular vectors.
152
+
153
+ If ``solver='propack'``, the option is respected regardless of the
154
+ matrix shape.
155
+
156
+ solver : {'arpack', 'propack', 'lobpcg'}, optional
157
+ The solver used.
158
+ :ref:`'arpack' <sparse.linalg.svds-arpack>`,
159
+ :ref:`'lobpcg' <sparse.linalg.svds-lobpcg>`, and
160
+ :ref:`'propack' <sparse.linalg.svds-propack>` are supported.
161
+ Default: `'arpack'`.
162
+ rng : `numpy.random.Generator`, optional
163
+ Pseudorandom number generator state. When `rng` is None, a new
164
+ `numpy.random.Generator` is created using entropy from the
165
+ operating system. Types other than `numpy.random.Generator` are
166
+ passed to `numpy.random.default_rng` to instantiate a ``Generator``.
167
+ options : dict, optional
168
+ A dictionary of solver-specific options. No solver-specific options
169
+ are currently supported; this parameter is reserved for future use.
170
+
171
+ Returns
172
+ -------
173
+ u : ndarray, shape=(M, k)
174
+ Unitary matrix having left singular vectors as columns.
175
+ s : ndarray, shape=(k,)
176
+ The singular values.
177
+ vh : ndarray, shape=(k, N)
178
+ Unitary matrix having right singular vectors as rows.
179
+
180
+ Notes
181
+ -----
182
+ This is a naive implementation using ARPACK or LOBPCG as an eigensolver
183
+ on the matrix ``A.conj().T @ A`` or ``A @ A.conj().T``, depending on
184
+ which one is smaller size, followed by the Rayleigh-Ritz method
185
+ as postprocessing; see
186
+ Using the normal matrix, in Rayleigh-Ritz method, (2022, Nov. 19),
187
+ Wikipedia, https://w.wiki/4zms.
188
+
189
+ Alternatively, the PROPACK solver can be called.
190
+
191
+ Choices of the input matrix `A` numeric dtype may be limited.
192
+ Only ``solver="lobpcg"`` supports all floating point dtypes
193
+ real: 'np.float32', 'np.float64', 'np.longdouble' and
194
+ complex: 'np.complex64', 'np.complex128', 'np.clongdouble'.
195
+ The ``solver="arpack"`` supports only
196
+ 'np.float32', 'np.float64', and 'np.complex128'.
197
+
198
+ Examples
199
+ --------
200
+ Construct a matrix `A` from singular values and vectors.
201
+
202
+ >>> import numpy as np
203
+ >>> from scipy import sparse, linalg, stats
204
+ >>> from scipy.sparse.linalg import svds, aslinearoperator, LinearOperator
205
+
206
+ Construct a dense matrix `A` from singular values and vectors.
207
+
208
+ >>> rng = np.random.default_rng(258265244568965474821194062361901728911)
209
+ >>> orthogonal = stats.ortho_group.rvs(10, random_state=rng)
210
+ >>> s = [1e-3, 1, 2, 3, 4] # non-zero singular values
211
+ >>> u = orthogonal[:, :5] # left singular vectors
212
+ >>> vT = orthogonal[:, 5:].T # right singular vectors
213
+ >>> A = u @ np.diag(s) @ vT
214
+
215
+ With only four singular values/vectors, the SVD approximates the original
216
+ matrix.
217
+
218
+ >>> u4, s4, vT4 = svds(A, k=4)
219
+ >>> A4 = u4 @ np.diag(s4) @ vT4
220
+ >>> np.allclose(A4, A, atol=1e-3)
221
+ True
222
+
223
+ With all five non-zero singular values/vectors, we can reproduce
224
+ the original matrix more accurately.
225
+
226
+ >>> u5, s5, vT5 = svds(A, k=5)
227
+ >>> A5 = u5 @ np.diag(s5) @ vT5
228
+ >>> np.allclose(A5, A)
229
+ True
230
+
231
+ The singular values match the expected singular values.
232
+
233
+ >>> np.allclose(s5, s)
234
+ True
235
+
236
+ Since the singular values are not close to each other in this example,
237
+ every singular vector matches as expected up to a difference in sign.
238
+
239
+ >>> (np.allclose(np.abs(u5), np.abs(u)) and
240
+ ... np.allclose(np.abs(vT5), np.abs(vT)))
241
+ True
242
+
243
+ The singular vectors are also orthogonal.
244
+
245
+ >>> (np.allclose(u5.T @ u5, np.eye(5)) and
246
+ ... np.allclose(vT5 @ vT5.T, np.eye(5)))
247
+ True
248
+
249
+ If there are (nearly) multiple singular values, the corresponding
250
+ individual singular vectors may be unstable, but the whole invariant
251
+ subspace containing all such singular vectors is computed accurately
252
+ as can be measured by angles between subspaces via 'subspace_angles'.
253
+
254
+ >>> rng = np.random.default_rng(178686584221410808734965903901790843963)
255
+ >>> s = [1, 1 + 1e-6] # non-zero singular values
256
+ >>> u, _ = np.linalg.qr(rng.standard_normal((99, 2)))
257
+ >>> v, _ = np.linalg.qr(rng.standard_normal((99, 2)))
258
+ >>> vT = v.T
259
+ >>> A = u @ np.diag(s) @ vT
260
+ >>> A = A.astype(np.float32)
261
+ >>> u2, s2, vT2 = svds(A, k=2, rng=rng)
262
+ >>> np.allclose(s2, s)
263
+ True
264
+
265
+ The angles between the individual exact and computed singular vectors
266
+ may not be so small. To check use:
267
+
268
+ >>> (linalg.subspace_angles(u2[:, :1], u[:, :1]) +
269
+ ... linalg.subspace_angles(u2[:, 1:], u[:, 1:]))
270
+ array([0.06562513]) # may vary
271
+ >>> (linalg.subspace_angles(vT2[:1, :].T, vT[:1, :].T) +
272
+ ... linalg.subspace_angles(vT2[1:, :].T, vT[1:, :].T))
273
+ array([0.06562507]) # may vary
274
+
275
+ As opposed to the angles between the 2-dimensional invariant subspaces
276
+ that these vectors span, which are small for rights singular vectors
277
+
278
+ >>> linalg.subspace_angles(u2, u).sum() < 1e-6
279
+ True
280
+
281
+ as well as for left singular vectors.
282
+
283
+ >>> linalg.subspace_angles(vT2.T, vT.T).sum() < 1e-6
284
+ True
285
+
286
+ The next example follows that of 'sklearn.decomposition.TruncatedSVD'.
287
+
288
+ >>> rng = np.random.default_rng(0)
289
+ >>> X_dense = rng.random(size=(100, 100))
290
+ >>> X_dense[:, 2 * np.arange(50)] = 0
291
+ >>> X = sparse.csr_array(X_dense)
292
+ >>> _, singular_values, _ = svds(X, k=5, rng=rng)
293
+ >>> print(singular_values)
294
+ [ 4.3221... 4.4043... 4.4907... 4.5858... 35.4549...]
295
+
296
+ The function can be called without the transpose of the input matrix
297
+ ever explicitly constructed.
298
+
299
+ >>> rng = np.random.default_rng(102524723947864966825913730119128190974)
300
+ >>> G = sparse.random_array((8, 9), density=0.5, rng=rng)
301
+ >>> Glo = aslinearoperator(G)
302
+ >>> _, singular_values_svds, _ = svds(Glo, k=5, rng=rng)
303
+ >>> _, singular_values_svd, _ = linalg.svd(G.toarray())
304
+ >>> np.allclose(singular_values_svds, singular_values_svd[-4::-1])
305
+ True
306
+
307
+ The most memory efficient scenario is where neither
308
+ the original matrix, nor its transpose, is explicitly constructed.
309
+ Our example computes the smallest singular values and vectors
310
+ of 'LinearOperator' constructed from the numpy function 'np.diff' used
311
+ column-wise to be consistent with 'LinearOperator' operating on columns.
312
+
313
+ >>> diff0 = lambda a: np.diff(a, axis=0)
314
+
315
+ Let us create the matrix from 'diff0' to be used for validation only.
316
+
317
+ >>> n = 5 # The dimension of the space.
318
+ >>> M_from_diff0 = diff0(np.eye(n))
319
+ >>> print(M_from_diff0.astype(int))
320
+ [[-1 1 0 0 0]
321
+ [ 0 -1 1 0 0]
322
+ [ 0 0 -1 1 0]
323
+ [ 0 0 0 -1 1]]
324
+
325
+ The matrix 'M_from_diff0' is bi-diagonal and could be alternatively
326
+ created directly by
327
+
328
+ >>> M = - np.eye(n - 1, n, dtype=int)
329
+ >>> np.fill_diagonal(M[:,1:], 1)
330
+ >>> np.allclose(M, M_from_diff0)
331
+ True
332
+
333
+ Its transpose
334
+
335
+ >>> print(M.T)
336
+ [[-1 0 0 0]
337
+ [ 1 -1 0 0]
338
+ [ 0 1 -1 0]
339
+ [ 0 0 1 -1]
340
+ [ 0 0 0 1]]
341
+
342
+ can be viewed as the incidence matrix; see
343
+ Incidence matrix, (2022, Nov. 19), Wikipedia, https://w.wiki/5YXU,
344
+ of a linear graph with 5 vertices and 4 edges. The 5x5 normal matrix
345
+ ``M.T @ M`` thus is
346
+
347
+ >>> print(M.T @ M)
348
+ [[ 1 -1 0 0 0]
349
+ [-1 2 -1 0 0]
350
+ [ 0 -1 2 -1 0]
351
+ [ 0 0 -1 2 -1]
352
+ [ 0 0 0 -1 1]]
353
+
354
+ the graph Laplacian, while the actually used in 'svds' smaller size
355
+ 4x4 normal matrix ``M @ M.T``
356
+
357
+ >>> print(M @ M.T)
358
+ [[ 2 -1 0 0]
359
+ [-1 2 -1 0]
360
+ [ 0 -1 2 -1]
361
+ [ 0 0 -1 2]]
362
+
363
+ is the so-called edge-based Laplacian; see
364
+ Symmetric Laplacian via the incidence matrix, in Laplacian matrix,
365
+ (2022, Nov. 19), Wikipedia, https://w.wiki/5YXW.
366
+
367
+ The 'LinearOperator' setup needs the options 'rmatvec' and 'rmatmat'
368
+ of multiplication by the matrix transpose ``M.T``, but we want to be
369
+ matrix-free to save memory, so knowing how ``M.T`` looks like, we
370
+ manually construct the following function to be
371
+ used in ``rmatmat=diff0t``.
372
+
373
+ >>> def diff0t(a):
374
+ ... if a.ndim == 1:
375
+ ... a = a[:,np.newaxis] # Turn 1D into 2D array
376
+ ... d = np.zeros((a.shape[0] + 1, a.shape[1]), dtype=a.dtype)
377
+ ... d[0, :] = - a[0, :]
378
+ ... d[1:-1, :] = a[0:-1, :] - a[1:, :]
379
+ ... d[-1, :] = a[-1, :]
380
+ ... return d
381
+
382
+ We check that our function 'diff0t' for the matrix transpose is valid.
383
+
384
+ >>> np.allclose(M.T, diff0t(np.eye(n-1)))
385
+ True
386
+
387
+ Now we setup our matrix-free 'LinearOperator' called 'diff0_func_aslo'
388
+ and for validation the matrix-based 'diff0_matrix_aslo'.
389
+
390
+ >>> def diff0_func_aslo_def(n):
391
+ ... return LinearOperator(matvec=diff0,
392
+ ... matmat=diff0,
393
+ ... rmatvec=diff0t,
394
+ ... rmatmat=diff0t,
395
+ ... shape=(n - 1, n))
396
+ >>> diff0_func_aslo = diff0_func_aslo_def(n)
397
+ >>> diff0_matrix_aslo = aslinearoperator(M_from_diff0)
398
+
399
+ And validate both the matrix and its transpose in 'LinearOperator'.
400
+
401
+ >>> np.allclose(diff0_func_aslo(np.eye(n)),
402
+ ... diff0_matrix_aslo(np.eye(n)))
403
+ True
404
+ >>> np.allclose(diff0_func_aslo.T(np.eye(n-1)),
405
+ ... diff0_matrix_aslo.T(np.eye(n-1)))
406
+ True
407
+
408
+ Having the 'LinearOperator' setup validated, we run the solver.
409
+
410
+ >>> n = 100
411
+ >>> diff0_func_aslo = diff0_func_aslo_def(n)
412
+ >>> u, s, vT = svds(diff0_func_aslo, k=3, which='SM')
413
+
414
+ The singular values squared and the singular vectors are known
415
+ explicitly; see
416
+ Pure Dirichlet boundary conditions, in
417
+ Eigenvalues and eigenvectors of the second derivative,
418
+ (2022, Nov. 19), Wikipedia, https://w.wiki/5YX6,
419
+ since 'diff' corresponds to first
420
+ derivative, and its smaller size n-1 x n-1 normal matrix
421
+ ``M @ M.T`` represent the discrete second derivative with the Dirichlet
422
+ boundary conditions. We use these analytic expressions for validation.
423
+
424
+ >>> se = 2. * np.sin(np.pi * np.arange(1, 4) / (2. * n))
425
+ >>> ue = np.sqrt(2 / n) * np.sin(np.pi * np.outer(np.arange(1, n),
426
+ ... np.arange(1, 4)) / n)
427
+ >>> np.allclose(s, se, atol=1e-3)
428
+ True
429
+ >>> np.allclose(np.abs(u), np.abs(ue), atol=1e-6)
430
+ True
431
+
432
+ """
433
+ args = _iv(A, k, ncv, tol, which, v0, maxiter, return_singular_vectors,
434
+ solver, rng)
435
+ (A, k, ncv, tol, which, v0, maxiter,
436
+ return_singular_vectors, solver, rng) = args
437
+
438
+ largest = (which == 'LM')
439
+ n, m = A.shape
440
+
441
+ if n >= m:
442
+ X_dot = A.matvec
443
+ X_matmat = A.matmat
444
+ XH_dot = A.rmatvec
445
+ XH_mat = A.rmatmat
446
+ transpose = False
447
+ else:
448
+ X_dot = A.rmatvec
449
+ X_matmat = A.rmatmat
450
+ XH_dot = A.matvec
451
+ XH_mat = A.matmat
452
+ transpose = True
453
+
454
+ dtype = getattr(A, 'dtype', None)
455
+ if dtype is None:
456
+ dtype = A.dot(np.zeros([m, 1])).dtype
457
+
458
+ def matvec_XH_X(x):
459
+ return XH_dot(X_dot(x))
460
+
461
+ def matmat_XH_X(x):
462
+ return XH_mat(X_matmat(x))
463
+
464
+ XH_X = LinearOperator(matvec=matvec_XH_X, dtype=A.dtype,
465
+ matmat=matmat_XH_X,
466
+ shape=(min(A.shape), min(A.shape)))
467
+
468
+ # Get a low rank approximation of the implicitly defined gramian matrix.
469
+ # This is not a stable way to approach the problem.
470
+ if solver == 'lobpcg':
471
+
472
+ if k == 1 and v0 is not None:
473
+ X = np.reshape(v0, (-1, 1))
474
+ else:
475
+ X = rng.standard_normal(size=(min(A.shape), k))
476
+
477
+ _, eigvec = lobpcg(XH_X, X, tol=tol ** 2, maxiter=maxiter,
478
+ largest=largest)
479
+
480
+ elif solver == 'propack':
481
+ jobu = return_singular_vectors in {True, 'u'}
482
+ jobv = return_singular_vectors in {True, 'vh'}
483
+ irl_mode = (which == 'SM')
484
+ res = _svdp(A, k=k, tol=tol**2, which=which, maxiter=None,
485
+ compute_u=jobu, compute_v=jobv, irl_mode=irl_mode,
486
+ kmax=maxiter, v0=v0, rng=rng)
487
+
488
+ u, s, vh, _ = res # but we'll ignore bnd, the last output
489
+
490
+ # PROPACK order appears to be largest first. `svds` output order is not
491
+ # guaranteed, according to documentation, but for ARPACK and LOBPCG
492
+ # they actually are ordered smallest to largest, so reverse for
493
+ # consistency.
494
+ s = s[::-1]
495
+ u = u[:, ::-1]
496
+ vh = vh[::-1]
497
+
498
+ u = u if jobu else None
499
+ vh = vh if jobv else None
500
+
501
+ if return_singular_vectors:
502
+ return u, s, vh
503
+ else:
504
+ return s
505
+
506
+ elif solver == 'arpack' or solver is None:
507
+ if v0 is None:
508
+ v0 = rng.standard_normal(size=(min(A.shape),))
509
+ _, eigvec = eigsh(XH_X, k=k, tol=tol ** 2, maxiter=maxiter,
510
+ ncv=ncv, which=which, v0=v0)
511
+ # arpack do not guarantee exactly orthonormal eigenvectors
512
+ # for clustered eigenvalues, especially in complex arithmetic
513
+ eigvec, _ = np.linalg.qr(eigvec)
514
+
515
+ # the eigenvectors eigvec must be orthonomal here; see gh-16712
516
+ Av = X_matmat(eigvec)
517
+ if not return_singular_vectors:
518
+ s = svd(Av, compute_uv=False, overwrite_a=True)
519
+ return s[::-1]
520
+
521
+ # compute the left singular vectors of X and update the right ones
522
+ # accordingly
523
+ u, s, vh = svd(Av, full_matrices=False, overwrite_a=True)
524
+ u = u[:, ::-1]
525
+ s = s[::-1]
526
+ vh = vh[::-1]
527
+
528
+ jobu = return_singular_vectors in {True, 'u'}
529
+ jobv = return_singular_vectors in {True, 'vh'}
530
+
531
+ if transpose:
532
+ u_tmp = eigvec @ _herm(vh) if jobu else None
533
+ vh = _herm(u) if jobv else None
534
+ u = u_tmp
535
+ else:
536
+ if not jobu:
537
+ u = None
538
+ vh = vh @ _herm(eigvec) if jobv else None
539
+
540
+ return u, s, vh
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/_svds_doc.py ADDED
@@ -0,0 +1,382 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def _svds_arpack_doc(A, k=6, ncv=None, tol=0, which='LM', v0=None,
2
+ maxiter=None, return_singular_vectors=True,
3
+ solver='arpack', rng=None):
4
+ """
5
+ Partial singular value decomposition of a sparse matrix using ARPACK.
6
+
7
+ Compute the largest or smallest `k` singular values and corresponding
8
+ singular vectors of a sparse matrix `A`. The order in which the singular
9
+ values are returned is not guaranteed.
10
+
11
+ In the descriptions below, let ``M, N = A.shape``.
12
+
13
+ Parameters
14
+ ----------
15
+ A : sparse matrix or LinearOperator
16
+ Matrix to decompose.
17
+ k : int, optional
18
+ Number of singular values and singular vectors to compute.
19
+ Must satisfy ``1 <= k <= min(M, N) - 1``.
20
+ Default is 6.
21
+ ncv : int, optional
22
+ The number of Lanczos vectors generated.
23
+ The default is ``min(n, max(2*k + 1, 20))``.
24
+ If specified, must satisfy ``k + 1 < ncv < min(M, N)``; ``ncv > 2*k``
25
+ is recommended.
26
+ tol : float, optional
27
+ Tolerance for singular values. Zero (default) means machine precision.
28
+ which : {'LM', 'SM'}
29
+ Which `k` singular values to find: either the largest magnitude ('LM')
30
+ or smallest magnitude ('SM') singular values.
31
+ v0 : ndarray, optional
32
+ The starting vector for iteration:
33
+ an (approximate) left singular vector if ``N > M`` and a right singular
34
+ vector otherwise. Must be of length ``min(M, N)``.
35
+ Default: random
36
+ maxiter : int, optional
37
+ Maximum number of Arnoldi update iterations allowed;
38
+ default is ``min(M, N) * 10``.
39
+ return_singular_vectors : {True, False, "u", "vh"}
40
+ Singular values are always computed and returned; this parameter
41
+ controls the computation and return of singular vectors.
42
+
43
+ - ``True``: return singular vectors.
44
+ - ``False``: do not return singular vectors.
45
+ - ``"u"``: if ``M <= N``, compute only the left singular vectors and
46
+ return ``None`` for the right singular vectors. Otherwise, compute
47
+ all singular vectors.
48
+ - ``"vh"``: if ``M > N``, compute only the right singular vectors and
49
+ return ``None`` for the left singular vectors. Otherwise, compute
50
+ all singular vectors.
51
+
52
+ solver : {'arpack', 'propack', 'lobpcg'}, optional
53
+ This is the solver-specific documentation for ``solver='arpack'``.
54
+ :ref:`'lobpcg' <sparse.linalg.svds-lobpcg>` and
55
+ :ref:`'propack' <sparse.linalg.svds-propack>`
56
+ are also supported.
57
+ rng : `numpy.random.Generator`, optional
58
+ Pseudorandom number generator state. When `rng` is None, a new
59
+ `numpy.random.Generator` is created using entropy from the
60
+ operating system. Types other than `numpy.random.Generator` are
61
+ passed to `numpy.random.default_rng` to instantiate a ``Generator``.
62
+ options : dict, optional
63
+ A dictionary of solver-specific options. No solver-specific options
64
+ are currently supported; this parameter is reserved for future use.
65
+
66
+ Returns
67
+ -------
68
+ u : ndarray, shape=(M, k)
69
+ Unitary matrix having left singular vectors as columns.
70
+ s : ndarray, shape=(k,)
71
+ The singular values.
72
+ vh : ndarray, shape=(k, N)
73
+ Unitary matrix having right singular vectors as rows.
74
+
75
+ Notes
76
+ -----
77
+ This is a naive implementation using ARPACK as an eigensolver
78
+ on ``A.conj().T @ A`` or ``A @ A.conj().T``, depending on which one is more
79
+ efficient.
80
+
81
+ Examples
82
+ --------
83
+ Construct a matrix ``A`` from singular values and vectors.
84
+
85
+ >>> import numpy as np
86
+ >>> from scipy.stats import ortho_group
87
+ >>> from scipy.sparse import csc_array, diags_array
88
+ >>> from scipy.sparse.linalg import svds
89
+ >>> rng = np.random.default_rng()
90
+ >>> orthogonal = csc_array(ortho_group.rvs(10, random_state=rng))
91
+ >>> s = [0.0001, 0.001, 3, 4, 5] # singular values
92
+ >>> u = orthogonal[:, :5] # left singular vectors
93
+ >>> vT = orthogonal[:, 5:].T # right singular vectors
94
+ >>> A = u @ diags_array(s) @ vT
95
+
96
+ With only three singular values/vectors, the SVD approximates the original
97
+ matrix.
98
+
99
+ >>> u2, s2, vT2 = svds(A, k=3, solver='arpack')
100
+ >>> A2 = u2 @ np.diag(s2) @ vT2
101
+ >>> np.allclose(A2, A.toarray(), atol=1e-3)
102
+ True
103
+
104
+ With all five singular values/vectors, we can reproduce the original
105
+ matrix.
106
+
107
+ >>> u3, s3, vT3 = svds(A, k=5, solver='arpack')
108
+ >>> A3 = u3 @ np.diag(s3) @ vT3
109
+ >>> np.allclose(A3, A.toarray())
110
+ True
111
+
112
+ The singular values match the expected singular values, and the singular
113
+ vectors are as expected up to a difference in sign.
114
+
115
+ >>> (np.allclose(s3, s) and
116
+ ... np.allclose(np.abs(u3), np.abs(u.toarray())) and
117
+ ... np.allclose(np.abs(vT3), np.abs(vT.toarray())))
118
+ True
119
+
120
+ The singular vectors are also orthogonal.
121
+
122
+ >>> (np.allclose(u3.T @ u3, np.eye(5)) and
123
+ ... np.allclose(vT3 @ vT3.T, np.eye(5)))
124
+ True
125
+ """
126
+ pass
127
+
128
+
129
+ def _svds_lobpcg_doc(A, k=6, ncv=None, tol=0, which='LM', v0=None,
130
+ maxiter=None, return_singular_vectors=True,
131
+ solver='lobpcg', rng=None):
132
+ """
133
+ Partial singular value decomposition of a sparse matrix using LOBPCG.
134
+
135
+ Compute the largest or smallest `k` singular values and corresponding
136
+ singular vectors of a sparse matrix `A`. The order in which the singular
137
+ values are returned is not guaranteed.
138
+
139
+ In the descriptions below, let ``M, N = A.shape``.
140
+
141
+ Parameters
142
+ ----------
143
+ A : sparse matrix or LinearOperator
144
+ Matrix to decompose.
145
+ k : int, default: 6
146
+ Number of singular values and singular vectors to compute.
147
+ Must satisfy ``1 <= k <= min(M, N) - 1``.
148
+ ncv : int, optional
149
+ Ignored.
150
+ tol : float, optional
151
+ Tolerance for singular values. Zero (default) means machine precision.
152
+ which : {'LM', 'SM'}
153
+ Which `k` singular values to find: either the largest magnitude ('LM')
154
+ or smallest magnitude ('SM') singular values.
155
+ v0 : ndarray, optional
156
+ If `k` is 1, the starting vector for iteration:
157
+ an (approximate) left singular vector if ``N > M`` and a right singular
158
+ vector otherwise. Must be of length ``min(M, N)``.
159
+ Ignored otherwise.
160
+ Default: random
161
+ maxiter : int, default: 20
162
+ Maximum number of iterations.
163
+ return_singular_vectors : {True, False, "u", "vh"}
164
+ Singular values are always computed and returned; this parameter
165
+ controls the computation and return of singular vectors.
166
+
167
+ - ``True``: return singular vectors.
168
+ - ``False``: do not return singular vectors.
169
+ - ``"u"``: if ``M <= N``, compute only the left singular vectors and
170
+ return ``None`` for the right singular vectors. Otherwise, compute
171
+ all singular vectors.
172
+ - ``"vh"``: if ``M > N``, compute only the right singular vectors and
173
+ return ``None`` for the left singular vectors. Otherwise, compute
174
+ all singular vectors.
175
+
176
+ solver : {'arpack', 'propack', 'lobpcg'}, optional
177
+ This is the solver-specific documentation for ``solver='lobpcg'``.
178
+ :ref:`'arpack' <sparse.linalg.svds-arpack>` and
179
+ :ref:`'propack' <sparse.linalg.svds-propack>`
180
+ are also supported.
181
+ rng : `numpy.random.Generator`, optional
182
+ Pseudorandom number generator state. When `rng` is None, a new
183
+ `numpy.random.Generator` is created using entropy from the
184
+ operating system. Types other than `numpy.random.Generator` are
185
+ passed to `numpy.random.default_rng` to instantiate a ``Generator``.
186
+ options : dict, optional
187
+ A dictionary of solver-specific options. No solver-specific options
188
+ are currently supported; this parameter is reserved for future use.
189
+
190
+ Returns
191
+ -------
192
+ u : ndarray, shape=(M, k)
193
+ Unitary matrix having left singular vectors as columns.
194
+ s : ndarray, shape=(k,)
195
+ The singular values.
196
+ vh : ndarray, shape=(k, N)
197
+ Unitary matrix having right singular vectors as rows.
198
+
199
+ Notes
200
+ -----
201
+ This is a naive implementation using LOBPCG as an eigensolver
202
+ on ``A.conj().T @ A`` or ``A @ A.conj().T``, depending on which one is more
203
+ efficient.
204
+
205
+ Examples
206
+ --------
207
+ Construct a matrix ``A`` from singular values and vectors.
208
+
209
+ >>> import numpy as np
210
+ >>> from scipy.stats import ortho_group
211
+ >>> from scipy.sparse import csc_array, diags_array
212
+ >>> from scipy.sparse.linalg import svds
213
+ >>> rng = np.random.default_rng()
214
+ >>> orthogonal = csc_array(ortho_group.rvs(10, random_state=rng))
215
+ >>> s = [0.0001, 0.001, 3, 4, 5] # singular values
216
+ >>> u = orthogonal[:, :5] # left singular vectors
217
+ >>> vT = orthogonal[:, 5:].T # right singular vectors
218
+ >>> A = u @ diags_array(s) @ vT
219
+
220
+ With only three singular values/vectors, the SVD approximates the original
221
+ matrix.
222
+
223
+ >>> u2, s2, vT2 = svds(A, k=3, solver='lobpcg')
224
+ >>> A2 = u2 @ np.diag(s2) @ vT2
225
+ >>> np.allclose(A2, A.toarray(), atol=1e-3)
226
+ True
227
+
228
+ With all five singular values/vectors, we can reproduce the original
229
+ matrix.
230
+
231
+ >>> u3, s3, vT3 = svds(A, k=5, solver='lobpcg')
232
+ >>> A3 = u3 @ np.diag(s3) @ vT3
233
+ >>> np.allclose(A3, A.toarray())
234
+ True
235
+
236
+ The singular values match the expected singular values, and the singular
237
+ vectors are as expected up to a difference in sign.
238
+
239
+ >>> (np.allclose(s3, s) and
240
+ ... np.allclose(np.abs(u3), np.abs(u.todense())) and
241
+ ... np.allclose(np.abs(vT3), np.abs(vT.todense())))
242
+ True
243
+
244
+ The singular vectors are also orthogonal.
245
+
246
+ >>> (np.allclose(u3.T @ u3, np.eye(5)) and
247
+ ... np.allclose(vT3 @ vT3.T, np.eye(5)))
248
+ True
249
+
250
+ """
251
+ pass
252
+
253
+
254
+ def _svds_propack_doc(A, k=6, ncv=None, tol=0, which='LM', v0=None,
255
+ maxiter=None, return_singular_vectors=True,
256
+ solver='propack', rng=None):
257
+ """
258
+ Partial singular value decomposition of a sparse matrix using PROPACK.
259
+
260
+ Compute the largest or smallest `k` singular values and corresponding
261
+ singular vectors of a sparse matrix `A`. The order in which the singular
262
+ values are returned is not guaranteed.
263
+
264
+ In the descriptions below, let ``M, N = A.shape``.
265
+
266
+ Parameters
267
+ ----------
268
+ A : sparse matrix or LinearOperator
269
+ Matrix to decompose. If `A` is a ``LinearOperator``
270
+ object, it must define both ``matvec`` and ``rmatvec`` methods.
271
+ k : int, default: 6
272
+ Number of singular values and singular vectors to compute.
273
+ Must satisfy ``1 <= k <= min(M, N)``.
274
+ ncv : int, optional
275
+ Ignored.
276
+ tol : float, optional
277
+ The desired relative accuracy for computed singular values.
278
+ Zero (default) means machine precision.
279
+ which : {'LM', 'SM'}
280
+ Which `k` singular values to find: either the largest magnitude ('LM')
281
+ or smallest magnitude ('SM') singular values. Note that choosing
282
+ ``which='SM'`` will force the ``irl`` option to be set ``True``.
283
+ v0 : ndarray, optional
284
+ Starting vector for iterations: must be of length ``A.shape[0]``.
285
+ If not specified, PROPACK will generate a starting vector.
286
+ maxiter : int, optional
287
+ Maximum number of iterations / maximal dimension of the Krylov
288
+ subspace. Default is ``10 * k``.
289
+ return_singular_vectors : {True, False, "u", "vh"}
290
+ Singular values are always computed and returned; this parameter
291
+ controls the computation and return of singular vectors.
292
+
293
+ - ``True``: return singular vectors.
294
+ - ``False``: do not return singular vectors.
295
+ - ``"u"``: compute only the left singular vectors; return ``None`` for
296
+ the right singular vectors.
297
+ - ``"vh"``: compute only the right singular vectors; return ``None``
298
+ for the left singular vectors.
299
+
300
+ solver : {'arpack', 'propack', 'lobpcg'}, optional
301
+ This is the solver-specific documentation for ``solver='propack'``.
302
+ :ref:`'arpack' <sparse.linalg.svds-arpack>` and
303
+ :ref:`'lobpcg' <sparse.linalg.svds-lobpcg>`
304
+ are also supported.
305
+ rng : `numpy.random.Generator`, optional
306
+ Pseudorandom number generator state. When `rng` is None, a new
307
+ `numpy.random.Generator` is created using entropy from the
308
+ operating system. Types other than `numpy.random.Generator` are
309
+ passed to `numpy.random.default_rng` to instantiate a ``Generator``.
310
+ options : dict, optional
311
+ A dictionary of solver-specific options. No solver-specific options
312
+ are currently supported; this parameter is reserved for future use.
313
+
314
+ Returns
315
+ -------
316
+ u : ndarray, shape=(M, k)
317
+ Unitary matrix having left singular vectors as columns.
318
+ s : ndarray, shape=(k,)
319
+ The singular values.
320
+ vh : ndarray, shape=(k, N)
321
+ Unitary matrix having right singular vectors as rows.
322
+
323
+ Notes
324
+ -----
325
+ This is an interface to the Fortran library PROPACK [1]_.
326
+ The current default is to run with IRL mode disabled unless seeking the
327
+ smallest singular values/vectors (``which='SM'``).
328
+
329
+ References
330
+ ----------
331
+
332
+ .. [1] Larsen, Rasmus Munk. "PROPACK-Software for large and sparse SVD
333
+ calculations." Available online. URL
334
+ http://sun.stanford.edu/~rmunk/PROPACK (2004): 2008-2009.
335
+
336
+ Examples
337
+ --------
338
+ Construct a matrix ``A`` from singular values and vectors.
339
+
340
+ >>> import numpy as np
341
+ >>> from scipy.stats import ortho_group
342
+ >>> from scipy.sparse import csc_array, diags_array
343
+ >>> from scipy.sparse.linalg import svds
344
+ >>> rng = np.random.default_rng()
345
+ >>> orthogonal = csc_array(ortho_group.rvs(10, random_state=rng))
346
+ >>> s = [0.0001, 0.001, 3, 4, 5] # singular values
347
+ >>> u = orthogonal[:, :5] # left singular vectors
348
+ >>> vT = orthogonal[:, 5:].T # right singular vectors
349
+ >>> A = u @ diags_array(s) @ vT
350
+
351
+ With only three singular values/vectors, the SVD approximates the original
352
+ matrix.
353
+
354
+ >>> u2, s2, vT2 = svds(A, k=3, solver='propack')
355
+ >>> A2 = u2 @ np.diag(s2) @ vT2
356
+ >>> np.allclose(A2, A.todense(), atol=1e-3)
357
+ True
358
+
359
+ With all five singular values/vectors, we can reproduce the original
360
+ matrix.
361
+
362
+ >>> u3, s3, vT3 = svds(A, k=5, solver='propack')
363
+ >>> A3 = u3 @ np.diag(s3) @ vT3
364
+ >>> np.allclose(A3, A.todense())
365
+ True
366
+
367
+ The singular values match the expected singular values, and the singular
368
+ vectors are as expected up to a difference in sign.
369
+
370
+ >>> (np.allclose(s3, s) and
371
+ ... np.allclose(np.abs(u3), np.abs(u.toarray())) and
372
+ ... np.allclose(np.abs(vT3), np.abs(vT.toarray())))
373
+ True
374
+
375
+ The singular vectors are also orthogonal.
376
+
377
+ >>> (np.allclose(u3.T @ u3, np.eye(5)) and
378
+ ... np.allclose(vT3 @ vT3.T, np.eye(5)))
379
+ True
380
+
381
+ """
382
+ pass
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/arpack/COPYING ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ BSD Software License
3
+
4
+ Pertains to ARPACK and P_ARPACK
5
+
6
+ Copyright (c) 1996-2008 Rice University.
7
+ Developed by D.C. Sorensen, R.B. Lehoucq, C. Yang, and K. Maschhoff.
8
+ All rights reserved.
9
+
10
+ Arpack has been renamed to arpack-ng.
11
+
12
+ Copyright (c) 2001-2011 - Scilab Enterprises
13
+ Updated by Allan Cornet, Sylvestre Ledru.
14
+
15
+ Copyright (c) 2010 - Jordi Gutiérrez Hermoso (Octave patch)
16
+
17
+ Copyright (c) 2007 - Sébastien Fabbro (gentoo patch)
18
+
19
+ Redistribution and use in source and binary forms, with or without
20
+ modification, are permitted provided that the following conditions are
21
+ met:
22
+
23
+ - Redistributions of source code must retain the above copyright
24
+ notice, this list of conditions and the following disclaimer.
25
+
26
+ - Redistributions in binary form must reproduce the above copyright
27
+ notice, this list of conditions and the following disclaimer listed
28
+ in this license in the documentation and/or other materials
29
+ provided with the distribution.
30
+
31
+ - Neither the name of the copyright holders nor the names of its
32
+ contributors may be used to endorse or promote products derived from
33
+ this software without specific prior written permission.
34
+
35
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
36
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
37
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
38
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
39
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
42
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
43
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
44
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
45
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/arpack/__init__.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Eigenvalue solver using iterative methods.
3
+
4
+ Find k eigenvectors and eigenvalues of a matrix A using the
5
+ Arnoldi/Lanczos iterative methods from ARPACK [1]_,[2]_.
6
+
7
+ These methods are most useful for large sparse matrices.
8
+
9
+ - eigs(A,k)
10
+ - eigsh(A,k)
11
+
12
+ References
13
+ ----------
14
+ .. [1] ARPACK Software, http://www.caam.rice.edu/software/ARPACK/
15
+ .. [2] R. B. Lehoucq, D. C. Sorensen, and C. Yang, ARPACK USERS GUIDE:
16
+ Solution of Large Scale Eigenvalue Problems by Implicitly Restarted
17
+ Arnoldi Methods. SIAM, Philadelphia, PA, 1998.
18
+
19
+ """
20
+ from .arpack import *
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/arpack/arpack.py ADDED
@@ -0,0 +1,1700 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Find a few eigenvectors and eigenvalues of a matrix.
3
+
4
+
5
+ Uses ARPACK: https://github.com/opencollab/arpack-ng
6
+
7
+ """
8
+ # Wrapper implementation notes
9
+ #
10
+ # ARPACK Entry Points
11
+ # -------------------
12
+ # The entry points to ARPACK are
13
+ # - (s,d)seupd : single and double precision symmetric matrix
14
+ # - (s,d,c,z)neupd: single,double,complex,double complex general matrix
15
+ # This wrapper puts the *neupd (general matrix) interfaces in eigs()
16
+ # and the *seupd (symmetric matrix) in eigsh().
17
+ # There is no specialized interface for complex Hermitian matrices.
18
+ # To find eigenvalues of a complex Hermitian matrix you
19
+ # may use eigsh(), but eigsh() will simply call eigs()
20
+ # and return the real part of the eigenvalues thus obtained.
21
+
22
+ # Number of eigenvalues returned and complex eigenvalues
23
+ # ------------------------------------------------------
24
+ # The ARPACK nonsymmetric real and double interface (s,d)naupd return
25
+ # eigenvalues and eigenvectors in real (float,double) arrays.
26
+ # Since the eigenvalues and eigenvectors are, in general, complex
27
+ # ARPACK puts the real and imaginary parts in consecutive entries
28
+ # in real-valued arrays. This wrapper puts the real entries
29
+ # into complex data types and attempts to return the requested eigenvalues
30
+ # and eigenvectors.
31
+
32
+
33
+ # Solver modes
34
+ # ------------
35
+ # ARPACK and handle shifted and shift-inverse computations
36
+ # for eigenvalues by providing a shift (sigma) and a solver.
37
+
38
+ import numpy as np
39
+ import warnings
40
+ from scipy.sparse.linalg._interface import aslinearoperator, LinearOperator
41
+ from scipy.sparse import eye, issparse
42
+ from scipy.linalg import eig, eigh, lu_factor, lu_solve
43
+ from scipy.sparse._sputils import (
44
+ convert_pydata_sparse_to_scipy, isdense, is_pydata_spmatrix,
45
+ )
46
+ from scipy.sparse.linalg import gmres, splu
47
+ from scipy._lib._util import _aligned_zeros
48
+ from scipy._lib._threadsafety import ReentrancyLock
49
+ from . import _arpack
50
+ arpack_int = _arpack.timing.nbx.dtype
51
+
52
+ __docformat__ = "restructuredtext en"
53
+
54
+ __all__ = ['eigs', 'eigsh', 'ArpackError', 'ArpackNoConvergence']
55
+
56
+
57
+ _type_conv = {'f': 's', 'd': 'd', 'F': 'c', 'D': 'z'}
58
+ _ndigits = {'f': 5, 'd': 12, 'F': 5, 'D': 12}
59
+
60
+ DNAUPD_ERRORS = {
61
+ 0: "Normal exit.",
62
+ 1: "Maximum number of iterations taken. "
63
+ "All possible eigenvalues of OP has been found. IPARAM(5) "
64
+ "returns the number of wanted converged Ritz values.",
65
+ 2: "No longer an informational error. Deprecated starting "
66
+ "with release 2 of ARPACK.",
67
+ 3: "No shifts could be applied during a cycle of the "
68
+ "Implicitly restarted Arnoldi iteration. One possibility "
69
+ "is to increase the size of NCV relative to NEV. ",
70
+ -1: "N must be positive.",
71
+ -2: "NEV must be positive.",
72
+ -3: "NCV-NEV >= 2 and less than or equal to N.",
73
+ -4: "The maximum number of Arnoldi update iterations allowed "
74
+ "must be greater than zero.",
75
+ -5: " WHICH must be one of 'LM', 'SM', 'LR', 'SR', 'LI', 'SI'",
76
+ -6: "BMAT must be one of 'I' or 'G'.",
77
+ -7: "Length of private work array WORKL is not sufficient.",
78
+ -8: "Error return from LAPACK eigenvalue calculation;",
79
+ -9: "Starting vector is zero.",
80
+ -10: "IPARAM(7) must be 1,2,3,4.",
81
+ -11: "IPARAM(7) = 1 and BMAT = 'G' are incompatible.",
82
+ -12: "IPARAM(1) must be equal to 0 or 1.",
83
+ -13: "NEV and WHICH = 'BE' are incompatible.",
84
+ -9999: "Could not build an Arnoldi factorization. "
85
+ "IPARAM(5) returns the size of the current Arnoldi "
86
+ "factorization. The user is advised to check that "
87
+ "enough workspace and array storage has been allocated."
88
+ }
89
+
90
+ SNAUPD_ERRORS = DNAUPD_ERRORS
91
+
92
+ ZNAUPD_ERRORS = DNAUPD_ERRORS.copy()
93
+ ZNAUPD_ERRORS[-10] = "IPARAM(7) must be 1,2,3."
94
+
95
+ CNAUPD_ERRORS = ZNAUPD_ERRORS
96
+
97
+ DSAUPD_ERRORS = {
98
+ 0: "Normal exit.",
99
+ 1: "Maximum number of iterations taken. "
100
+ "All possible eigenvalues of OP has been found.",
101
+ 2: "No longer an informational error. Deprecated starting with "
102
+ "release 2 of ARPACK.",
103
+ 3: "No shifts could be applied during a cycle of the Implicitly "
104
+ "restarted Arnoldi iteration. One possibility is to increase "
105
+ "the size of NCV relative to NEV. ",
106
+ -1: "N must be positive.",
107
+ -2: "NEV must be positive.",
108
+ -3: "NCV must be greater than NEV and less than or equal to N.",
109
+ -4: "The maximum number of Arnoldi update iterations allowed "
110
+ "must be greater than zero.",
111
+ -5: "WHICH must be one of 'LM', 'SM', 'LA', 'SA' or 'BE'.",
112
+ -6: "BMAT must be one of 'I' or 'G'.",
113
+ -7: "Length of private work array WORKL is not sufficient.",
114
+ -8: "Error return from trid. eigenvalue calculation; "
115
+ "Informational error from LAPACK routine dsteqr .",
116
+ -9: "Starting vector is zero.",
117
+ -10: "IPARAM(7) must be 1,2,3,4,5.",
118
+ -11: "IPARAM(7) = 1 and BMAT = 'G' are incompatible.",
119
+ -12: "IPARAM(1) must be equal to 0 or 1.",
120
+ -13: "NEV and WHICH = 'BE' are incompatible. ",
121
+ -9999: "Could not build an Arnoldi factorization. "
122
+ "IPARAM(5) returns the size of the current Arnoldi "
123
+ "factorization. The user is advised to check that "
124
+ "enough workspace and array storage has been allocated.",
125
+ }
126
+
127
+ SSAUPD_ERRORS = DSAUPD_ERRORS
128
+
129
+ DNEUPD_ERRORS = {
130
+ 0: "Normal exit.",
131
+ 1: "The Schur form computed by LAPACK routine dlahqr "
132
+ "could not be reordered by LAPACK routine dtrsen. "
133
+ "Re-enter subroutine dneupd with IPARAM(5)NCV and "
134
+ "increase the size of the arrays DR and DI to have "
135
+ "dimension at least dimension NCV and allocate at least NCV "
136
+ "columns for Z. NOTE: Not necessary if Z and V share "
137
+ "the same space. Please notify the authors if this error"
138
+ "occurs.",
139
+ -1: "N must be positive.",
140
+ -2: "NEV must be positive.",
141
+ -3: "NCV-NEV >= 2 and less than or equal to N.",
142
+ -5: "WHICH must be one of 'LM', 'SM', 'LR', 'SR', 'LI', 'SI'",
143
+ -6: "BMAT must be one of 'I' or 'G'.",
144
+ -7: "Length of private work WORKL array is not sufficient.",
145
+ -8: "Error return from calculation of a real Schur form. "
146
+ "Informational error from LAPACK routine dlahqr .",
147
+ -9: "Error return from calculation of eigenvectors. "
148
+ "Informational error from LAPACK routine dtrevc.",
149
+ -10: "IPARAM(7) must be 1,2,3,4.",
150
+ -11: "IPARAM(7) = 1 and BMAT = 'G' are incompatible.",
151
+ -12: "HOWMNY = 'S' not yet implemented",
152
+ -13: "HOWMNY must be one of 'A' or 'P' if RVEC = .true.",
153
+ -14: "DNAUPD did not find any eigenvalues to sufficient "
154
+ "accuracy.",
155
+ -15: "DNEUPD got a different count of the number of converged "
156
+ "Ritz values than DNAUPD got. This indicates the user "
157
+ "probably made an error in passing data from DNAUPD to "
158
+ "DNEUPD or that the data was modified before entering "
159
+ "DNEUPD",
160
+ }
161
+
162
+ SNEUPD_ERRORS = DNEUPD_ERRORS.copy()
163
+ SNEUPD_ERRORS[1] = ("The Schur form computed by LAPACK routine slahqr "
164
+ "could not be reordered by LAPACK routine strsen . "
165
+ "Re-enter subroutine dneupd with IPARAM(5)=NCV and "
166
+ "increase the size of the arrays DR and DI to have "
167
+ "dimension at least dimension NCV and allocate at least "
168
+ "NCV columns for Z. NOTE: Not necessary if Z and V share "
169
+ "the same space. Please notify the authors if this error "
170
+ "occurs.")
171
+ SNEUPD_ERRORS[-14] = ("SNAUPD did not find any eigenvalues to sufficient "
172
+ "accuracy.")
173
+ SNEUPD_ERRORS[-15] = ("SNEUPD got a different count of the number of "
174
+ "converged Ritz values than SNAUPD got. This indicates "
175
+ "the user probably made an error in passing data from "
176
+ "SNAUPD to SNEUPD or that the data was modified before "
177
+ "entering SNEUPD")
178
+
179
+ ZNEUPD_ERRORS = {0: "Normal exit.",
180
+ 1: "The Schur form computed by LAPACK routine csheqr "
181
+ "could not be reordered by LAPACK routine ztrsen. "
182
+ "Re-enter subroutine zneupd with IPARAM(5)=NCV and "
183
+ "increase the size of the array D to have "
184
+ "dimension at least dimension NCV and allocate at least "
185
+ "NCV columns for Z. NOTE: Not necessary if Z and V share "
186
+ "the same space. Please notify the authors if this error "
187
+ "occurs.",
188
+ -1: "N must be positive.",
189
+ -2: "NEV must be positive.",
190
+ -3: "NCV-NEV >= 1 and less than or equal to N.",
191
+ -5: "WHICH must be one of 'LM', 'SM', 'LR', 'SR', 'LI', 'SI'",
192
+ -6: "BMAT must be one of 'I' or 'G'.",
193
+ -7: "Length of private work WORKL array is not sufficient.",
194
+ -8: "Error return from LAPACK eigenvalue calculation. "
195
+ "This should never happened.",
196
+ -9: "Error return from calculation of eigenvectors. "
197
+ "Informational error from LAPACK routine ztrevc.",
198
+ -10: "IPARAM(7) must be 1,2,3",
199
+ -11: "IPARAM(7) = 1 and BMAT = 'G' are incompatible.",
200
+ -12: "HOWMNY = 'S' not yet implemented",
201
+ -13: "HOWMNY must be one of 'A' or 'P' if RVEC = .true.",
202
+ -14: "ZNAUPD did not find any eigenvalues to sufficient "
203
+ "accuracy.",
204
+ -15: "ZNEUPD got a different count of the number of "
205
+ "converged Ritz values than ZNAUPD got. This "
206
+ "indicates the user probably made an error in passing "
207
+ "data from ZNAUPD to ZNEUPD or that the data was "
208
+ "modified before entering ZNEUPD"
209
+ }
210
+
211
+ CNEUPD_ERRORS = ZNEUPD_ERRORS.copy()
212
+ CNEUPD_ERRORS[-14] = ("CNAUPD did not find any eigenvalues to sufficient "
213
+ "accuracy.")
214
+ CNEUPD_ERRORS[-15] = ("CNEUPD got a different count of the number of "
215
+ "converged Ritz values than CNAUPD got. This indicates "
216
+ "the user probably made an error in passing data from "
217
+ "CNAUPD to CNEUPD or that the data was modified before "
218
+ "entering CNEUPD")
219
+
220
+ DSEUPD_ERRORS = {
221
+ 0: "Normal exit.",
222
+ -1: "N must be positive.",
223
+ -2: "NEV must be positive.",
224
+ -3: "NCV must be greater than NEV and less than or equal to N.",
225
+ -5: "WHICH must be one of 'LM', 'SM', 'LA', 'SA' or 'BE'.",
226
+ -6: "BMAT must be one of 'I' or 'G'.",
227
+ -7: "Length of private work WORKL array is not sufficient.",
228
+ -8: ("Error return from trid. eigenvalue calculation; "
229
+ "Information error from LAPACK routine dsteqr."),
230
+ -9: "Starting vector is zero.",
231
+ -10: "IPARAM(7) must be 1,2,3,4,5.",
232
+ -11: "IPARAM(7) = 1 and BMAT = 'G' are incompatible.",
233
+ -12: "NEV and WHICH = 'BE' are incompatible.",
234
+ -14: "DSAUPD did not find any eigenvalues to sufficient accuracy.",
235
+ -15: "HOWMNY must be one of 'A' or 'S' if RVEC = .true.",
236
+ -16: "HOWMNY = 'S' not yet implemented",
237
+ -17: ("DSEUPD got a different count of the number of converged "
238
+ "Ritz values than DSAUPD got. This indicates the user "
239
+ "probably made an error in passing data from DSAUPD to "
240
+ "DSEUPD or that the data was modified before entering "
241
+ "DSEUPD.")
242
+ }
243
+
244
+ SSEUPD_ERRORS = DSEUPD_ERRORS.copy()
245
+ SSEUPD_ERRORS[-14] = ("SSAUPD did not find any eigenvalues "
246
+ "to sufficient accuracy.")
247
+ SSEUPD_ERRORS[-17] = ("SSEUPD got a different count of the number of "
248
+ "converged "
249
+ "Ritz values than SSAUPD got. This indicates the user "
250
+ "probably made an error in passing data from SSAUPD to "
251
+ "SSEUPD or that the data was modified before entering "
252
+ "SSEUPD.")
253
+
254
+ _SAUPD_ERRORS = {'d': DSAUPD_ERRORS,
255
+ 's': SSAUPD_ERRORS}
256
+ _NAUPD_ERRORS = {'d': DNAUPD_ERRORS,
257
+ 's': SNAUPD_ERRORS,
258
+ 'z': ZNAUPD_ERRORS,
259
+ 'c': CNAUPD_ERRORS}
260
+ _SEUPD_ERRORS = {'d': DSEUPD_ERRORS,
261
+ 's': SSEUPD_ERRORS}
262
+ _NEUPD_ERRORS = {'d': DNEUPD_ERRORS,
263
+ 's': SNEUPD_ERRORS,
264
+ 'z': ZNEUPD_ERRORS,
265
+ 'c': CNEUPD_ERRORS}
266
+
267
+ # accepted values of parameter WHICH in _SEUPD
268
+ _SEUPD_WHICH = ['LM', 'SM', 'LA', 'SA', 'BE']
269
+
270
+ # accepted values of parameter WHICH in _NAUPD
271
+ _NEUPD_WHICH = ['LM', 'SM', 'LR', 'SR', 'LI', 'SI']
272
+
273
+
274
+ class ArpackError(RuntimeError):
275
+ """
276
+ ARPACK error
277
+ """
278
+
279
+ def __init__(self, info, infodict=None):
280
+ if infodict is None:
281
+ infodict = _NAUPD_ERRORS
282
+
283
+ msg = infodict.get(info, "Unknown error")
284
+ super().__init__(f"ARPACK error {info}: {msg}")
285
+
286
+
287
+ class ArpackNoConvergence(ArpackError):
288
+ """
289
+ ARPACK iteration did not converge
290
+
291
+ Attributes
292
+ ----------
293
+ eigenvalues : ndarray
294
+ Partial result. Converged eigenvalues.
295
+ eigenvectors : ndarray
296
+ Partial result. Converged eigenvectors.
297
+
298
+ """
299
+
300
+ def __init__(self, msg, eigenvalues, eigenvectors):
301
+ ArpackError.__init__(self, -1, {-1: msg})
302
+ self.eigenvalues = eigenvalues
303
+ self.eigenvectors = eigenvectors
304
+
305
+
306
+ def choose_ncv(k):
307
+ """
308
+ Choose number of lanczos vectors based on target number
309
+ of singular/eigen values and vectors to compute, k.
310
+ """
311
+ return max(2 * k + 1, 20)
312
+
313
+
314
+ class _ArpackParams:
315
+ def __init__(self, n, k, tp, mode=1, sigma=None,
316
+ ncv=None, v0=None, maxiter=None, which="LM", tol=0):
317
+ if k <= 0:
318
+ raise ValueError("k must be positive, k=%d" % k)
319
+
320
+ if maxiter is None:
321
+ maxiter = n * 10
322
+ if maxiter <= 0:
323
+ raise ValueError("maxiter must be positive, maxiter=%d" % maxiter)
324
+
325
+ if tp not in 'fdFD':
326
+ # Use `float64` libraries from integer dtypes.
327
+ if np.can_cast(tp, 'd'):
328
+ tp = 'd'
329
+ else:
330
+ raise ValueError("matrix type must be 'f', 'd', 'F', or 'D'")
331
+
332
+ if v0 is not None:
333
+ # ARPACK overwrites its initial resid, make a copy
334
+ self.resid = np.array(v0, copy=True)
335
+ info = 1
336
+ else:
337
+ # ARPACK will use a random initial vector.
338
+ self.resid = np.zeros(n, tp)
339
+ info = 0
340
+
341
+ if sigma is None:
342
+ #sigma not used
343
+ self.sigma = 0
344
+ else:
345
+ self.sigma = sigma
346
+
347
+ if ncv is None:
348
+ ncv = choose_ncv(k)
349
+ ncv = min(ncv, n)
350
+
351
+ self.v = np.zeros((n, ncv), tp) # holds Ritz vectors
352
+ self.iparam = np.zeros(11, arpack_int)
353
+
354
+ # set solver mode and parameters
355
+ ishfts = 1
356
+ self.mode = mode
357
+ self.iparam[0] = ishfts
358
+ self.iparam[2] = maxiter
359
+ self.iparam[3] = 1
360
+ self.iparam[6] = mode
361
+
362
+ self.n = n
363
+ self.tol = tol
364
+ self.k = k
365
+ self.maxiter = maxiter
366
+ self.ncv = ncv
367
+ self.which = which
368
+ self.tp = tp
369
+ self.info = info
370
+
371
+ self.converged = False
372
+ self.ido = 0
373
+
374
+ def _raise_no_convergence(self):
375
+ msg = "No convergence (%d iterations, %d/%d eigenvectors converged)"
376
+ k_ok = self.iparam[4]
377
+ num_iter = self.iparam[2]
378
+ try:
379
+ ev, vec = self.extract(True)
380
+ except ArpackError as err:
381
+ msg = f"{msg} [{err}]"
382
+ ev = np.zeros((0,))
383
+ vec = np.zeros((self.n, 0))
384
+ k_ok = 0
385
+ raise ArpackNoConvergence(msg % (num_iter, k_ok, self.k), ev, vec)
386
+
387
+
388
+ class _SymmetricArpackParams(_ArpackParams):
389
+ def __init__(self, n, k, tp, matvec, mode=1, M_matvec=None,
390
+ Minv_matvec=None, sigma=None,
391
+ ncv=None, v0=None, maxiter=None, which="LM", tol=0):
392
+ # The following modes are supported:
393
+ # mode = 1:
394
+ # Solve the standard eigenvalue problem:
395
+ # A*x = lambda*x :
396
+ # A - symmetric
397
+ # Arguments should be
398
+ # matvec = left multiplication by A
399
+ # M_matvec = None [not used]
400
+ # Minv_matvec = None [not used]
401
+ #
402
+ # mode = 2:
403
+ # Solve the general eigenvalue problem:
404
+ # A*x = lambda*M*x
405
+ # A - symmetric
406
+ # M - symmetric positive definite
407
+ # Arguments should be
408
+ # matvec = left multiplication by A
409
+ # M_matvec = left multiplication by M
410
+ # Minv_matvec = left multiplication by M^-1
411
+ #
412
+ # mode = 3:
413
+ # Solve the general eigenvalue problem in shift-invert mode:
414
+ # A*x = lambda*M*x
415
+ # A - symmetric
416
+ # M - symmetric positive semi-definite
417
+ # Arguments should be
418
+ # matvec = None [not used]
419
+ # M_matvec = left multiplication by M
420
+ # or None, if M is the identity
421
+ # Minv_matvec = left multiplication by [A-sigma*M]^-1
422
+ #
423
+ # mode = 4:
424
+ # Solve the general eigenvalue problem in Buckling mode:
425
+ # A*x = lambda*AG*x
426
+ # A - symmetric positive semi-definite
427
+ # AG - symmetric indefinite
428
+ # Arguments should be
429
+ # matvec = left multiplication by A
430
+ # M_matvec = None [not used]
431
+ # Minv_matvec = left multiplication by [A-sigma*AG]^-1
432
+ #
433
+ # mode = 5:
434
+ # Solve the general eigenvalue problem in Cayley-transformed mode:
435
+ # A*x = lambda*M*x
436
+ # A - symmetric
437
+ # M - symmetric positive semi-definite
438
+ # Arguments should be
439
+ # matvec = left multiplication by A
440
+ # M_matvec = left multiplication by M
441
+ # or None, if M is the identity
442
+ # Minv_matvec = left multiplication by [A-sigma*M]^-1
443
+ if mode == 1:
444
+ if matvec is None:
445
+ raise ValueError("matvec must be specified for mode=1")
446
+ if M_matvec is not None:
447
+ raise ValueError("M_matvec cannot be specified for mode=1")
448
+ if Minv_matvec is not None:
449
+ raise ValueError("Minv_matvec cannot be specified for mode=1")
450
+
451
+ self.OP = matvec
452
+ self.B = lambda x: x
453
+ self.bmat = 'I'
454
+ elif mode == 2:
455
+ if matvec is None:
456
+ raise ValueError("matvec must be specified for mode=2")
457
+ if M_matvec is None:
458
+ raise ValueError("M_matvec must be specified for mode=2")
459
+ if Minv_matvec is None:
460
+ raise ValueError("Minv_matvec must be specified for mode=2")
461
+
462
+ self.OP = lambda x: Minv_matvec(matvec(x))
463
+ self.OPa = Minv_matvec
464
+ self.OPb = matvec
465
+ self.B = M_matvec
466
+ self.bmat = 'G'
467
+ elif mode == 3:
468
+ if matvec is not None:
469
+ raise ValueError("matvec must not be specified for mode=3")
470
+ if Minv_matvec is None:
471
+ raise ValueError("Minv_matvec must be specified for mode=3")
472
+
473
+ if M_matvec is None:
474
+ self.OP = Minv_matvec
475
+ self.OPa = Minv_matvec
476
+ self.B = lambda x: x
477
+ self.bmat = 'I'
478
+ else:
479
+ self.OP = lambda x: Minv_matvec(M_matvec(x))
480
+ self.OPa = Minv_matvec
481
+ self.B = M_matvec
482
+ self.bmat = 'G'
483
+ elif mode == 4:
484
+ if matvec is None:
485
+ raise ValueError("matvec must be specified for mode=4")
486
+ if M_matvec is not None:
487
+ raise ValueError("M_matvec must not be specified for mode=4")
488
+ if Minv_matvec is None:
489
+ raise ValueError("Minv_matvec must be specified for mode=4")
490
+ self.OPa = Minv_matvec
491
+ self.OP = lambda x: self.OPa(matvec(x))
492
+ self.B = matvec
493
+ self.bmat = 'G'
494
+ elif mode == 5:
495
+ if matvec is None:
496
+ raise ValueError("matvec must be specified for mode=5")
497
+ if Minv_matvec is None:
498
+ raise ValueError("Minv_matvec must be specified for mode=5")
499
+
500
+ self.OPa = Minv_matvec
501
+ self.A_matvec = matvec
502
+
503
+ if M_matvec is None:
504
+ self.OP = lambda x: Minv_matvec(matvec(x) + sigma * x)
505
+ self.B = lambda x: x
506
+ self.bmat = 'I'
507
+ else:
508
+ self.OP = lambda x: Minv_matvec(matvec(x)
509
+ + sigma * M_matvec(x))
510
+ self.B = M_matvec
511
+ self.bmat = 'G'
512
+ else:
513
+ raise ValueError("mode=%i not implemented" % mode)
514
+
515
+ if which not in _SEUPD_WHICH:
516
+ raise ValueError(f"which must be one of {' '.join(_SEUPD_WHICH)}")
517
+ if k >= n:
518
+ raise ValueError("k must be less than ndim(A), k=%d" % k)
519
+
520
+ _ArpackParams.__init__(self, n, k, tp, mode, sigma,
521
+ ncv, v0, maxiter, which, tol)
522
+
523
+ if self.ncv > n or self.ncv <= k:
524
+ raise ValueError(f"ncv must be k<ncv<=n, ncv={self.ncv}")
525
+
526
+ # Use _aligned_zeros to work around a f2py bug in Numpy 1.9.1
527
+ self.workd = _aligned_zeros(3 * n, self.tp)
528
+ self.workl = _aligned_zeros(self.ncv * (self.ncv + 8), self.tp)
529
+
530
+ ltr = _type_conv[self.tp]
531
+ if ltr not in ["s", "d"]:
532
+ raise ValueError("Input matrix is not real-valued.")
533
+
534
+ self._arpack_solver = _arpack.__dict__[ltr + 'saupd']
535
+ self._arpack_extract = _arpack.__dict__[ltr + 'seupd']
536
+
537
+ self.iterate_infodict = _SAUPD_ERRORS[ltr]
538
+ self.extract_infodict = _SEUPD_ERRORS[ltr]
539
+
540
+ self.ipntr = np.zeros(11, arpack_int)
541
+
542
+ def iterate(self):
543
+ self.ido, self.tol, self.resid, self.v, self.iparam, self.ipntr, self.info = \
544
+ self._arpack_solver(self.ido, self.bmat, self.which, self.k,
545
+ self.tol, self.resid, self.v, self.iparam,
546
+ self.ipntr, self.workd, self.workl, self.info)
547
+
548
+ xslice = slice(self.ipntr[0] - 1, self.ipntr[0] - 1 + self.n)
549
+ yslice = slice(self.ipntr[1] - 1, self.ipntr[1] - 1 + self.n)
550
+ if self.ido == -1:
551
+ # initialization
552
+ self.workd[yslice] = self.OP(self.workd[xslice])
553
+ elif self.ido == 1:
554
+ # compute y = Op*x
555
+ if self.mode == 1:
556
+ self.workd[yslice] = self.OP(self.workd[xslice])
557
+ elif self.mode == 2:
558
+ self.workd[xslice] = self.OPb(self.workd[xslice])
559
+ self.workd[yslice] = self.OPa(self.workd[xslice])
560
+ elif self.mode == 5:
561
+ Bxslice = slice(self.ipntr[2] - 1, self.ipntr[2] - 1 + self.n)
562
+ Ax = self.A_matvec(self.workd[xslice])
563
+ self.workd[yslice] = self.OPa(Ax + (self.sigma *
564
+ self.workd[Bxslice]))
565
+ else:
566
+ Bxslice = slice(self.ipntr[2] - 1, self.ipntr[2] - 1 + self.n)
567
+ self.workd[yslice] = self.OPa(self.workd[Bxslice])
568
+ elif self.ido == 2:
569
+ self.workd[yslice] = self.B(self.workd[xslice])
570
+ elif self.ido == 3:
571
+ raise ValueError("ARPACK requested user shifts. Assure ISHIFT==0")
572
+ else:
573
+ self.converged = True
574
+
575
+ if self.info == 0:
576
+ pass
577
+ elif self.info == 1:
578
+ self._raise_no_convergence()
579
+ else:
580
+ raise ArpackError(self.info, infodict=self.iterate_infodict)
581
+
582
+ def extract(self, return_eigenvectors):
583
+ rvec = return_eigenvectors
584
+ ierr = 0
585
+ howmny = 'A' # return all eigenvectors
586
+ sselect = np.zeros(self.ncv, 'int') # unused
587
+ d, z, ierr = self._arpack_extract(rvec, howmny, sselect, self.sigma,
588
+ self.bmat, self.which, self.k,
589
+ self.tol, self.resid, self.v,
590
+ self.iparam[0:7], self.ipntr,
591
+ self.workd[0:2 * self.n],
592
+ self.workl, ierr)
593
+ if ierr != 0:
594
+ raise ArpackError(ierr, infodict=self.extract_infodict)
595
+ k_ok = self.iparam[4]
596
+ d = d[:k_ok]
597
+ z = z[:, :k_ok]
598
+
599
+ if return_eigenvectors:
600
+ return d, z
601
+ else:
602
+ return d
603
+
604
+
605
+ class _UnsymmetricArpackParams(_ArpackParams):
606
+ def __init__(self, n, k, tp, matvec, mode=1, M_matvec=None,
607
+ Minv_matvec=None, sigma=None,
608
+ ncv=None, v0=None, maxiter=None, which="LM", tol=0):
609
+ # The following modes are supported:
610
+ # mode = 1:
611
+ # Solve the standard eigenvalue problem:
612
+ # A*x = lambda*x
613
+ # A - square matrix
614
+ # Arguments should be
615
+ # matvec = left multiplication by A
616
+ # M_matvec = None [not used]
617
+ # Minv_matvec = None [not used]
618
+ #
619
+ # mode = 2:
620
+ # Solve the generalized eigenvalue problem:
621
+ # A*x = lambda*M*x
622
+ # A - square matrix
623
+ # M - symmetric, positive semi-definite
624
+ # Arguments should be
625
+ # matvec = left multiplication by A
626
+ # M_matvec = left multiplication by M
627
+ # Minv_matvec = left multiplication by M^-1
628
+ #
629
+ # mode = 3,4:
630
+ # Solve the general eigenvalue problem in shift-invert mode:
631
+ # A*x = lambda*M*x
632
+ # A - square matrix
633
+ # M - symmetric, positive semi-definite
634
+ # Arguments should be
635
+ # matvec = None [not used]
636
+ # M_matvec = left multiplication by M
637
+ # or None, if M is the identity
638
+ # Minv_matvec = left multiplication by [A-sigma*M]^-1
639
+ # if A is real and mode==3, use the real part of Minv_matvec
640
+ # if A is real and mode==4, use the imag part of Minv_matvec
641
+ # if A is complex and mode==3,
642
+ # use real and imag parts of Minv_matvec
643
+ if mode == 1:
644
+ if matvec is None:
645
+ raise ValueError("matvec must be specified for mode=1")
646
+ if M_matvec is not None:
647
+ raise ValueError("M_matvec cannot be specified for mode=1")
648
+ if Minv_matvec is not None:
649
+ raise ValueError("Minv_matvec cannot be specified for mode=1")
650
+
651
+ self.OP = matvec
652
+ self.B = lambda x: x
653
+ self.bmat = 'I'
654
+ elif mode == 2:
655
+ if matvec is None:
656
+ raise ValueError("matvec must be specified for mode=2")
657
+ if M_matvec is None:
658
+ raise ValueError("M_matvec must be specified for mode=2")
659
+ if Minv_matvec is None:
660
+ raise ValueError("Minv_matvec must be specified for mode=2")
661
+
662
+ self.OP = lambda x: Minv_matvec(matvec(x))
663
+ self.OPa = Minv_matvec
664
+ self.OPb = matvec
665
+ self.B = M_matvec
666
+ self.bmat = 'G'
667
+ elif mode in (3, 4):
668
+ if matvec is None:
669
+ raise ValueError("matvec must be specified "
670
+ "for mode in (3,4)")
671
+ if Minv_matvec is None:
672
+ raise ValueError("Minv_matvec must be specified "
673
+ "for mode in (3,4)")
674
+
675
+ self.matvec = matvec
676
+ if tp in 'DF': # complex type
677
+ if mode == 3:
678
+ self.OPa = Minv_matvec
679
+ else:
680
+ raise ValueError("mode=4 invalid for complex A")
681
+ else: # real type
682
+ if mode == 3:
683
+ self.OPa = lambda x: np.real(Minv_matvec(x))
684
+ else:
685
+ self.OPa = lambda x: np.imag(Minv_matvec(x))
686
+ if M_matvec is None:
687
+ self.B = lambda x: x
688
+ self.bmat = 'I'
689
+ self.OP = self.OPa
690
+ else:
691
+ self.B = M_matvec
692
+ self.bmat = 'G'
693
+ self.OP = lambda x: self.OPa(M_matvec(x))
694
+ else:
695
+ raise ValueError("mode=%i not implemented" % mode)
696
+
697
+ if which not in _NEUPD_WHICH:
698
+ raise ValueError(f"Parameter which must be one of {' '.join(_NEUPD_WHICH)}")
699
+ if k >= n - 1:
700
+ raise ValueError("k must be less than ndim(A)-1, k=%d" % k)
701
+
702
+ _ArpackParams.__init__(self, n, k, tp, mode, sigma,
703
+ ncv, v0, maxiter, which, tol)
704
+
705
+ if self.ncv > n or self.ncv <= k + 1:
706
+ raise ValueError(f"ncv must be k+1<ncv<=n, ncv={self.ncv}")
707
+
708
+ # Use _aligned_zeros to work around a f2py bug in Numpy 1.9.1
709
+ self.workd = _aligned_zeros(3 * n, self.tp)
710
+ self.workl = _aligned_zeros(3 * self.ncv * (self.ncv + 2), self.tp)
711
+
712
+ ltr = _type_conv[self.tp]
713
+ self._arpack_solver = _arpack.__dict__[ltr + 'naupd']
714
+ self._arpack_extract = _arpack.__dict__[ltr + 'neupd']
715
+
716
+ self.iterate_infodict = _NAUPD_ERRORS[ltr]
717
+ self.extract_infodict = _NEUPD_ERRORS[ltr]
718
+
719
+ self.ipntr = np.zeros(14, arpack_int)
720
+
721
+ if self.tp in 'FD':
722
+ # Use _aligned_zeros to work around a f2py bug in Numpy 1.9.1
723
+ self.rwork = _aligned_zeros(self.ncv, self.tp.lower())
724
+ else:
725
+ self.rwork = None
726
+
727
+ def iterate(self):
728
+ if self.tp in 'fd':
729
+ results = self._arpack_solver(self.ido, self.bmat, self.which, self.k,
730
+ self.tol, self.resid, self.v, self.iparam,
731
+ self.ipntr, self.workd, self.workl, self.info)
732
+ self.ido, self.tol, self.resid, self.v, \
733
+ self.iparam, self.ipntr, self.info = results
734
+
735
+ else:
736
+ results = self._arpack_solver(self.ido, self.bmat, self.which, self.k,
737
+ self.tol, self.resid, self.v, self.iparam,
738
+ self.ipntr, self.workd, self.workl,
739
+ self.rwork, self.info)
740
+ self.ido, self.tol, self.resid, self.v, \
741
+ self.iparam, self.ipntr, self.info = results
742
+
743
+
744
+ xslice = slice(self.ipntr[0] - 1, self.ipntr[0] - 1 + self.n)
745
+ yslice = slice(self.ipntr[1] - 1, self.ipntr[1] - 1 + self.n)
746
+ if self.ido == -1:
747
+ # initialization
748
+ self.workd[yslice] = self.OP(self.workd[xslice])
749
+ elif self.ido == 1:
750
+ # compute y = Op*x
751
+ if self.mode in (1, 2):
752
+ self.workd[yslice] = self.OP(self.workd[xslice])
753
+ else:
754
+ Bxslice = slice(self.ipntr[2] - 1, self.ipntr[2] - 1 + self.n)
755
+ self.workd[yslice] = self.OPa(self.workd[Bxslice])
756
+ elif self.ido == 2:
757
+ self.workd[yslice] = self.B(self.workd[xslice])
758
+ elif self.ido == 3:
759
+ raise ValueError("ARPACK requested user shifts. Assure ISHIFT==0")
760
+ else:
761
+ self.converged = True
762
+
763
+ if self.info == 0:
764
+ pass
765
+ elif self.info == 1:
766
+ self._raise_no_convergence()
767
+ else:
768
+ raise ArpackError(self.info, infodict=self.iterate_infodict)
769
+
770
+ def extract(self, return_eigenvectors):
771
+ k, n = self.k, self.n
772
+
773
+ ierr = 0
774
+ howmny = 'A' # return all eigenvectors
775
+ sselect = np.zeros(self.ncv, 'int') # unused
776
+ sigmar = np.real(self.sigma)
777
+ sigmai = np.imag(self.sigma)
778
+ workev = np.zeros(3 * self.ncv, self.tp)
779
+
780
+ if self.tp in 'fd':
781
+ dr = np.zeros(k + 1, self.tp)
782
+ di = np.zeros(k + 1, self.tp)
783
+ zr = np.zeros((n, k + 1), self.tp)
784
+ dr, di, zr, ierr = \
785
+ self._arpack_extract(return_eigenvectors,
786
+ howmny, sselect, sigmar, sigmai, workev,
787
+ self.bmat, self.which, k, self.tol, self.resid,
788
+ self.v, self.iparam, self.ipntr,
789
+ self.workd, self.workl, self.info)
790
+ if ierr != 0:
791
+ raise ArpackError(ierr, infodict=self.extract_infodict)
792
+ nreturned = self.iparam[4] # number of good eigenvalues returned
793
+
794
+ # Build complex eigenvalues from real and imaginary parts
795
+ d = dr + 1.0j * di
796
+
797
+ # Arrange the eigenvectors: complex eigenvectors are stored as
798
+ # real,imaginary in consecutive columns
799
+ z = zr.astype(self.tp.upper())
800
+
801
+ # The ARPACK nonsymmetric real and double interface (s,d)naupd
802
+ # return eigenvalues and eigenvectors in real (float,double)
803
+ # arrays.
804
+
805
+ # Efficiency: this should check that return_eigenvectors == True
806
+ # before going through this construction.
807
+ if sigmai == 0:
808
+ i = 0
809
+ while i <= k:
810
+ # check if complex
811
+ if abs(d[i].imag) != 0:
812
+ # this is a complex conjugate pair with eigenvalues
813
+ # in consecutive columns
814
+ if i < k:
815
+ z[:, i] = zr[:, i] + 1.0j * zr[:, i + 1]
816
+ z[:, i + 1] = z[:, i].conjugate()
817
+ i += 1
818
+ else:
819
+ #last eigenvalue is complex: the imaginary part of
820
+ # the eigenvector has not been returned
821
+ #this can only happen if nreturned > k, so we'll
822
+ # throw out this case.
823
+ nreturned -= 1
824
+ i += 1
825
+
826
+ else:
827
+ # real matrix, mode 3 or 4, imag(sigma) is nonzero:
828
+ # see remark 3 in <s,d>neupd.f
829
+ # Build complex eigenvalues from real and imaginary parts
830
+ i = 0
831
+ while i <= k:
832
+ if abs(d[i].imag) == 0:
833
+ d[i] = np.dot(zr[:, i], self.matvec(zr[:, i]))
834
+ else:
835
+ if i < k:
836
+ z[:, i] = zr[:, i] + 1.0j * zr[:, i + 1]
837
+ z[:, i + 1] = z[:, i].conjugate()
838
+ d[i] = ((np.dot(zr[:, i],
839
+ self.matvec(zr[:, i]))
840
+ + np.dot(zr[:, i + 1],
841
+ self.matvec(zr[:, i + 1])))
842
+ + 1j * (np.dot(zr[:, i],
843
+ self.matvec(zr[:, i + 1]))
844
+ - np.dot(zr[:, i + 1],
845
+ self.matvec(zr[:, i]))))
846
+ d[i + 1] = d[i].conj()
847
+ i += 1
848
+ else:
849
+ #last eigenvalue is complex: the imaginary part of
850
+ # the eigenvector has not been returned
851
+ #this can only happen if nreturned > k, so we'll
852
+ # throw out this case.
853
+ nreturned -= 1
854
+ i += 1
855
+
856
+ # Now we have k+1 possible eigenvalues and eigenvectors
857
+ # Return the ones specified by the keyword "which"
858
+
859
+ if nreturned <= k:
860
+ # we got less or equal as many eigenvalues we wanted
861
+ d = d[:nreturned]
862
+ z = z[:, :nreturned]
863
+ else:
864
+ # we got one extra eigenvalue (likely a cc pair, but which?)
865
+ if self.mode in (1, 2):
866
+ rd = d
867
+ elif self.mode in (3, 4):
868
+ rd = 1 / (d - self.sigma)
869
+
870
+ if self.which in ['LR', 'SR']:
871
+ ind = np.argsort(rd.real)
872
+ elif self.which in ['LI', 'SI']:
873
+ # for LI,SI ARPACK returns largest,smallest
874
+ # abs(imaginary) (complex pairs come together)
875
+ ind = np.argsort(abs(rd.imag))
876
+ else:
877
+ ind = np.argsort(abs(rd))
878
+
879
+ if self.which in ['LR', 'LM', 'LI']:
880
+ ind = ind[-k:][::-1]
881
+ elif self.which in ['SR', 'SM', 'SI']:
882
+ ind = ind[:k]
883
+
884
+ d = d[ind]
885
+ z = z[:, ind]
886
+ else:
887
+ # complex is so much simpler...
888
+ d, z, ierr =\
889
+ self._arpack_extract(return_eigenvectors,
890
+ howmny, sselect, self.sigma, workev,
891
+ self.bmat, self.which, k, self.tol, self.resid,
892
+ self.v, self.iparam, self.ipntr,
893
+ self.workd, self.workl, self.rwork, ierr)
894
+
895
+ if ierr != 0:
896
+ raise ArpackError(ierr, infodict=self.extract_infodict)
897
+
898
+ k_ok = self.iparam[4]
899
+ d = d[:k_ok]
900
+ z = z[:, :k_ok]
901
+
902
+ if return_eigenvectors:
903
+ return d, z
904
+ else:
905
+ return d
906
+
907
+ class SpLuInv(LinearOperator):
908
+ """
909
+ SpLuInv:
910
+ helper class to repeatedly solve M*x=b
911
+ using a sparse LU-decomposition of M
912
+ """
913
+
914
+ def __init__(self, M):
915
+ self.M_lu = splu(M)
916
+ self.shape = M.shape
917
+ self.dtype = M.dtype
918
+ self.isreal = not np.issubdtype(self.dtype, np.complexfloating)
919
+
920
+ def _matvec(self, x):
921
+ # careful here: splu.solve will throw away imaginary
922
+ # part of x if M is real
923
+ x = np.asarray(x)
924
+ if self.isreal and np.issubdtype(x.dtype, np.complexfloating):
925
+ return (self.M_lu.solve(np.real(x).astype(self.dtype))
926
+ + 1j * self.M_lu.solve(np.imag(x).astype(self.dtype)))
927
+ else:
928
+ return self.M_lu.solve(x.astype(self.dtype))
929
+
930
+
931
+ class LuInv(LinearOperator):
932
+ """
933
+ LuInv:
934
+ helper class to repeatedly solve M*x=b
935
+ using an LU-decomposition of M
936
+ """
937
+
938
+ def __init__(self, M):
939
+ self.M_lu = lu_factor(M)
940
+ self.shape = M.shape
941
+ self.dtype = M.dtype
942
+
943
+ def _matvec(self, x):
944
+ return lu_solve(self.M_lu, x)
945
+
946
+
947
+ def gmres_loose(A, b, tol):
948
+ """
949
+ gmres with looser termination condition.
950
+ """
951
+ b = np.asarray(b)
952
+ min_tol = 1000 * np.sqrt(b.size) * np.finfo(b.dtype).eps
953
+ return gmres(A, b, rtol=max(tol, min_tol), atol=0)
954
+
955
+
956
+ class IterInv(LinearOperator):
957
+ """
958
+ IterInv:
959
+ helper class to repeatedly solve M*x=b
960
+ using an iterative method.
961
+ """
962
+
963
+ def __init__(self, M, ifunc=gmres_loose, tol=0):
964
+ self.M = M
965
+ if hasattr(M, 'dtype'):
966
+ self.dtype = M.dtype
967
+ else:
968
+ x = np.zeros(M.shape[1])
969
+ self.dtype = (M * x).dtype
970
+ self.shape = M.shape
971
+
972
+ if tol <= 0:
973
+ # when tol=0, ARPACK uses machine tolerance as calculated
974
+ # by LAPACK's _LAMCH function. We should match this
975
+ tol = 2 * np.finfo(self.dtype).eps
976
+ self.ifunc = ifunc
977
+ self.tol = tol
978
+
979
+ def _matvec(self, x):
980
+ b, info = self.ifunc(self.M, x, tol=self.tol)
981
+ if info != 0:
982
+ raise ValueError("Error in inverting M: function "
983
+ "%s did not converge (info = %i)."
984
+ % (self.ifunc.__name__, info))
985
+ return b
986
+
987
+
988
+ class IterOpInv(LinearOperator):
989
+ """
990
+ IterOpInv:
991
+ helper class to repeatedly solve [A-sigma*M]*x = b
992
+ using an iterative method
993
+ """
994
+
995
+ def __init__(self, A, M, sigma, ifunc=gmres_loose, tol=0):
996
+ self.A = A
997
+ self.M = M
998
+ self.sigma = sigma
999
+
1000
+ def mult_func(x):
1001
+ return A.matvec(x) - sigma * M.matvec(x)
1002
+
1003
+ def mult_func_M_None(x):
1004
+ return A.matvec(x) - sigma * x
1005
+
1006
+ x = np.zeros(A.shape[1])
1007
+ if M is None:
1008
+ dtype = mult_func_M_None(x).dtype
1009
+ self.OP = LinearOperator(self.A.shape,
1010
+ mult_func_M_None,
1011
+ dtype=dtype)
1012
+ else:
1013
+ dtype = mult_func(x).dtype
1014
+ self.OP = LinearOperator(self.A.shape,
1015
+ mult_func,
1016
+ dtype=dtype)
1017
+ self.shape = A.shape
1018
+
1019
+ if tol <= 0:
1020
+ # when tol=0, ARPACK uses machine tolerance as calculated
1021
+ # by LAPACK's _LAMCH function. We should match this
1022
+ tol = 2 * np.finfo(self.OP.dtype).eps
1023
+ self.ifunc = ifunc
1024
+ self.tol = tol
1025
+
1026
+ def _matvec(self, x):
1027
+ b, info = self.ifunc(self.OP, x, tol=self.tol)
1028
+ if info != 0:
1029
+ raise ValueError("Error in inverting [A-sigma*M]: function "
1030
+ "%s did not converge (info = %i)."
1031
+ % (self.ifunc.__name__, info))
1032
+ return b
1033
+
1034
+ @property
1035
+ def dtype(self):
1036
+ return self.OP.dtype
1037
+
1038
+
1039
+ def _fast_spmatrix_to_csc(A, hermitian=False):
1040
+ """Convert sparse matrix to CSC (by transposing, if possible)"""
1041
+ if (A.format == "csr" and hermitian
1042
+ and not np.issubdtype(A.dtype, np.complexfloating)):
1043
+ return A.T
1044
+ elif is_pydata_spmatrix(A):
1045
+ # No need to convert
1046
+ return A
1047
+ else:
1048
+ return A.tocsc()
1049
+
1050
+
1051
+ def get_inv_matvec(M, hermitian=False, tol=0):
1052
+ if isdense(M):
1053
+ return LuInv(M).matvec
1054
+ elif issparse(M) or is_pydata_spmatrix(M):
1055
+ M = _fast_spmatrix_to_csc(M, hermitian=hermitian)
1056
+ return SpLuInv(M).matvec
1057
+ else:
1058
+ return IterInv(M, tol=tol).matvec
1059
+
1060
+
1061
+ def get_OPinv_matvec(A, M, sigma, hermitian=False, tol=0):
1062
+ if sigma == 0:
1063
+ return get_inv_matvec(A, hermitian=hermitian, tol=tol)
1064
+
1065
+ if M is None:
1066
+ #M is the identity matrix
1067
+ if isdense(A):
1068
+ if (np.issubdtype(A.dtype, np.complexfloating)
1069
+ or np.imag(sigma) == 0):
1070
+ A = np.copy(A)
1071
+ else:
1072
+ A = A + 0j
1073
+ A.flat[::A.shape[1] + 1] -= sigma
1074
+ return LuInv(A).matvec
1075
+ elif issparse(A) or is_pydata_spmatrix(A):
1076
+ A = A - sigma * eye(A.shape[0])
1077
+ A = _fast_spmatrix_to_csc(A, hermitian=hermitian)
1078
+ return SpLuInv(A).matvec
1079
+ else:
1080
+ return IterOpInv(aslinearoperator(A),
1081
+ M, sigma, tol=tol).matvec
1082
+ else:
1083
+ if ((not isdense(A) and not issparse(A) and not is_pydata_spmatrix(A)) or
1084
+ (not isdense(M) and not issparse(M) and not is_pydata_spmatrix(A))):
1085
+ return IterOpInv(aslinearoperator(A),
1086
+ aslinearoperator(M),
1087
+ sigma, tol=tol).matvec
1088
+ elif isdense(A) or isdense(M):
1089
+ return LuInv(A - sigma * M).matvec
1090
+ else:
1091
+ OP = A - sigma * M
1092
+ OP = _fast_spmatrix_to_csc(OP, hermitian=hermitian)
1093
+ return SpLuInv(OP).matvec
1094
+
1095
+
1096
+ # ARPACK is not threadsafe or reentrant (SAVE variables), so we need a
1097
+ # lock and a re-entering check.
1098
+ _ARPACK_LOCK = ReentrancyLock("Nested calls to eigs/eighs not allowed: "
1099
+ "ARPACK is not re-entrant")
1100
+
1101
+
1102
+ def eigs(A, k=6, M=None, sigma=None, which='LM', v0=None,
1103
+ ncv=None, maxiter=None, tol=0, return_eigenvectors=True,
1104
+ Minv=None, OPinv=None, OPpart=None):
1105
+ """
1106
+ Find k eigenvalues and eigenvectors of the square matrix A.
1107
+
1108
+ Solves ``A @ x[i] = w[i] * x[i]``, the standard eigenvalue problem
1109
+ for w[i] eigenvalues with corresponding eigenvectors x[i].
1110
+
1111
+ If M is specified, solves ``A @ x[i] = w[i] * M @ x[i]``, the
1112
+ generalized eigenvalue problem for w[i] eigenvalues
1113
+ with corresponding eigenvectors x[i]
1114
+
1115
+ Parameters
1116
+ ----------
1117
+ A : ndarray, sparse matrix or LinearOperator
1118
+ An array, sparse matrix, or LinearOperator representing
1119
+ the operation ``A @ x``, where A is a real or complex square matrix.
1120
+ k : int, optional
1121
+ The number of eigenvalues and eigenvectors desired.
1122
+ `k` must be smaller than N-1. It is not possible to compute all
1123
+ eigenvectors of a matrix.
1124
+ M : ndarray, sparse matrix or LinearOperator, optional
1125
+ An array, sparse matrix, or LinearOperator representing
1126
+ the operation M@x for the generalized eigenvalue problem
1127
+
1128
+ A @ x = w * M @ x.
1129
+
1130
+ M must represent a real symmetric matrix if A is real, and must
1131
+ represent a complex Hermitian matrix if A is complex. For best
1132
+ results, the data type of M should be the same as that of A.
1133
+ Additionally:
1134
+
1135
+ If `sigma` is None, M is positive definite
1136
+
1137
+ If sigma is specified, M is positive semi-definite
1138
+
1139
+ If sigma is None, eigs requires an operator to compute the solution
1140
+ of the linear equation ``M @ x = b``. This is done internally via a
1141
+ (sparse) LU decomposition for an explicit matrix M, or via an
1142
+ iterative solver for a general linear operator. Alternatively,
1143
+ the user can supply the matrix or operator Minv, which gives
1144
+ ``x = Minv @ b = M^-1 @ b``.
1145
+ sigma : real or complex, optional
1146
+ Find eigenvalues near sigma using shift-invert mode. This requires
1147
+ an operator to compute the solution of the linear system
1148
+ ``[A - sigma * M] @ x = b``, where M is the identity matrix if
1149
+ unspecified. This is computed internally via a (sparse) LU
1150
+ decomposition for explicit matrices A & M, or via an iterative
1151
+ solver if either A or M is a general linear operator.
1152
+ Alternatively, the user can supply the matrix or operator OPinv,
1153
+ which gives ``x = OPinv @ b = [A - sigma * M]^-1 @ b``.
1154
+ For a real matrix A, shift-invert can either be done in imaginary
1155
+ mode or real mode, specified by the parameter OPpart ('r' or 'i').
1156
+ Note that when sigma is specified, the keyword 'which' (below)
1157
+ refers to the shifted eigenvalues ``w'[i]`` where:
1158
+
1159
+ If A is real and OPpart == 'r' (default),
1160
+ ``w'[i] = 1/2 * [1/(w[i]-sigma) + 1/(w[i]-conj(sigma))]``.
1161
+
1162
+ If A is real and OPpart == 'i',
1163
+ ``w'[i] = 1/2i * [1/(w[i]-sigma) - 1/(w[i]-conj(sigma))]``.
1164
+
1165
+ If A is complex, ``w'[i] = 1/(w[i]-sigma)``.
1166
+
1167
+ v0 : ndarray, optional
1168
+ Starting vector for iteration.
1169
+ Default: random
1170
+ ncv : int, optional
1171
+ The number of Lanczos vectors generated
1172
+ `ncv` must be greater than `k`; it is recommended that ``ncv > 2*k``.
1173
+ Default: ``min(n, max(2*k + 1, 20))``
1174
+ which : str, ['LM' | 'SM' | 'LR' | 'SR' | 'LI' | 'SI'], optional
1175
+ Which `k` eigenvectors and eigenvalues to find:
1176
+
1177
+ 'LM' : largest magnitude
1178
+
1179
+ 'SM' : smallest magnitude
1180
+
1181
+ 'LR' : largest real part
1182
+
1183
+ 'SR' : smallest real part
1184
+
1185
+ 'LI' : largest imaginary part
1186
+
1187
+ 'SI' : smallest imaginary part
1188
+
1189
+ When sigma != None, 'which' refers to the shifted eigenvalues w'[i]
1190
+ (see discussion in 'sigma', above). ARPACK is generally better
1191
+ at finding large values than small values. If small eigenvalues are
1192
+ desired, consider using shift-invert mode for better performance.
1193
+ maxiter : int, optional
1194
+ Maximum number of Arnoldi update iterations allowed
1195
+ Default: ``n*10``
1196
+ tol : float, optional
1197
+ Relative accuracy for eigenvalues (stopping criterion)
1198
+ The default value of 0 implies machine precision.
1199
+ return_eigenvectors : bool, optional
1200
+ Return eigenvectors (True) in addition to eigenvalues
1201
+ Minv : ndarray, sparse matrix or LinearOperator, optional
1202
+ See notes in M, above.
1203
+ OPinv : ndarray, sparse matrix or LinearOperator, optional
1204
+ See notes in sigma, above.
1205
+ OPpart : {'r' or 'i'}, optional
1206
+ See notes in sigma, above
1207
+
1208
+ Returns
1209
+ -------
1210
+ w : ndarray
1211
+ Array of k eigenvalues.
1212
+ v : ndarray
1213
+ An array of `k` eigenvectors.
1214
+ ``v[:, i]`` is the eigenvector corresponding to the eigenvalue w[i].
1215
+
1216
+ Raises
1217
+ ------
1218
+ ArpackNoConvergence
1219
+ When the requested convergence is not obtained.
1220
+ The currently converged eigenvalues and eigenvectors can be found
1221
+ as ``eigenvalues`` and ``eigenvectors`` attributes of the exception
1222
+ object.
1223
+
1224
+ See Also
1225
+ --------
1226
+ eigsh : eigenvalues and eigenvectors for symmetric matrix A
1227
+ svds : singular value decomposition for a matrix A
1228
+
1229
+ Notes
1230
+ -----
1231
+ This function is a wrapper to the ARPACK [1]_ SNEUPD, DNEUPD, CNEUPD,
1232
+ ZNEUPD, functions which use the Implicitly Restarted Arnoldi Method to
1233
+ find the eigenvalues and eigenvectors [2]_.
1234
+
1235
+ References
1236
+ ----------
1237
+ .. [1] ARPACK Software, https://github.com/opencollab/arpack-ng
1238
+ .. [2] R. B. Lehoucq, D. C. Sorensen, and C. Yang, ARPACK USERS GUIDE:
1239
+ Solution of Large Scale Eigenvalue Problems by Implicitly Restarted
1240
+ Arnoldi Methods. SIAM, Philadelphia, PA, 1998.
1241
+
1242
+ Examples
1243
+ --------
1244
+ Find 6 eigenvectors of the identity matrix:
1245
+
1246
+ >>> import numpy as np
1247
+ >>> from scipy.sparse.linalg import eigs
1248
+ >>> id = np.eye(13)
1249
+ >>> vals, vecs = eigs(id, k=6)
1250
+ >>> vals
1251
+ array([ 1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j])
1252
+ >>> vecs.shape
1253
+ (13, 6)
1254
+
1255
+ """
1256
+ A = convert_pydata_sparse_to_scipy(A)
1257
+ M = convert_pydata_sparse_to_scipy(M)
1258
+ if A.shape[0] != A.shape[1]:
1259
+ raise ValueError(f'expected square matrix (shape={A.shape})')
1260
+ if M is not None:
1261
+ if M.shape != A.shape:
1262
+ raise ValueError(f'wrong M dimensions {M.shape}, should be {A.shape}')
1263
+ if np.dtype(M.dtype).char.lower() != np.dtype(A.dtype).char.lower():
1264
+ warnings.warn('M does not have the same type precision as A. '
1265
+ 'This may adversely affect ARPACK convergence',
1266
+ stacklevel=2)
1267
+
1268
+ n = A.shape[0]
1269
+
1270
+ if k <= 0:
1271
+ raise ValueError("k=%d must be greater than 0." % k)
1272
+
1273
+ if k >= n - 1:
1274
+ warnings.warn("k >= N - 1 for N * N square matrix. "
1275
+ "Attempting to use scipy.linalg.eig instead.",
1276
+ RuntimeWarning, stacklevel=2)
1277
+
1278
+ if issparse(A):
1279
+ raise TypeError("Cannot use scipy.linalg.eig for sparse A with "
1280
+ "k >= N - 1. Use scipy.linalg.eig(A.toarray()) or"
1281
+ " reduce k.")
1282
+ if isinstance(A, LinearOperator):
1283
+ raise TypeError("Cannot use scipy.linalg.eig for LinearOperator "
1284
+ "A with k >= N - 1.")
1285
+ if isinstance(M, LinearOperator):
1286
+ raise TypeError("Cannot use scipy.linalg.eig for LinearOperator "
1287
+ "M with k >= N - 1.")
1288
+
1289
+ return eig(A, b=M, right=return_eigenvectors)
1290
+
1291
+ if sigma is None:
1292
+ matvec = aslinearoperator(A).matvec
1293
+
1294
+ if OPinv is not None:
1295
+ raise ValueError("OPinv should not be specified "
1296
+ "with sigma = None.")
1297
+ if OPpart is not None:
1298
+ raise ValueError("OPpart should not be specified with "
1299
+ "sigma = None or complex A")
1300
+
1301
+ if M is None:
1302
+ #standard eigenvalue problem
1303
+ mode = 1
1304
+ M_matvec = None
1305
+ Minv_matvec = None
1306
+ if Minv is not None:
1307
+ raise ValueError("Minv should not be "
1308
+ "specified with M = None.")
1309
+ else:
1310
+ #general eigenvalue problem
1311
+ mode = 2
1312
+ if Minv is None:
1313
+ Minv_matvec = get_inv_matvec(M, hermitian=True, tol=tol)
1314
+ else:
1315
+ Minv = aslinearoperator(Minv)
1316
+ Minv_matvec = Minv.matvec
1317
+ M_matvec = aslinearoperator(M).matvec
1318
+ else:
1319
+ #sigma is not None: shift-invert mode
1320
+ if np.issubdtype(A.dtype, np.complexfloating):
1321
+ if OPpart is not None:
1322
+ raise ValueError("OPpart should not be specified "
1323
+ "with sigma=None or complex A")
1324
+ mode = 3
1325
+ elif OPpart is None or OPpart.lower() == 'r':
1326
+ mode = 3
1327
+ elif OPpart.lower() == 'i':
1328
+ if np.imag(sigma) == 0:
1329
+ raise ValueError("OPpart cannot be 'i' if sigma is real")
1330
+ mode = 4
1331
+ else:
1332
+ raise ValueError("OPpart must be one of ('r','i')")
1333
+
1334
+ matvec = aslinearoperator(A).matvec
1335
+ if Minv is not None:
1336
+ raise ValueError("Minv should not be specified when sigma is")
1337
+ if OPinv is None:
1338
+ Minv_matvec = get_OPinv_matvec(A, M, sigma,
1339
+ hermitian=False, tol=tol)
1340
+ else:
1341
+ OPinv = aslinearoperator(OPinv)
1342
+ Minv_matvec = OPinv.matvec
1343
+ if M is None:
1344
+ M_matvec = None
1345
+ else:
1346
+ M_matvec = aslinearoperator(M).matvec
1347
+
1348
+ params = _UnsymmetricArpackParams(n, k, A.dtype.char, matvec, mode,
1349
+ M_matvec, Minv_matvec, sigma,
1350
+ ncv, v0, maxiter, which, tol)
1351
+
1352
+ with _ARPACK_LOCK:
1353
+ while not params.converged:
1354
+ params.iterate()
1355
+
1356
+ return params.extract(return_eigenvectors)
1357
+
1358
+
1359
+ def eigsh(A, k=6, M=None, sigma=None, which='LM', v0=None,
1360
+ ncv=None, maxiter=None, tol=0, return_eigenvectors=True,
1361
+ Minv=None, OPinv=None, mode='normal'):
1362
+ """
1363
+ Find k eigenvalues and eigenvectors of the real symmetric square matrix
1364
+ or complex Hermitian matrix A.
1365
+
1366
+ Solves ``A @ x[i] = w[i] * x[i]``, the standard eigenvalue problem for
1367
+ w[i] eigenvalues with corresponding eigenvectors x[i].
1368
+
1369
+ If M is specified, solves ``A @ x[i] = w[i] * M @ x[i]``, the
1370
+ generalized eigenvalue problem for w[i] eigenvalues
1371
+ with corresponding eigenvectors x[i].
1372
+
1373
+ Note that there is no specialized routine for the case when A is a complex
1374
+ Hermitian matrix. In this case, ``eigsh()`` will call ``eigs()`` and return the
1375
+ real parts of the eigenvalues thus obtained.
1376
+
1377
+ Parameters
1378
+ ----------
1379
+ A : ndarray, sparse matrix or LinearOperator
1380
+ A square operator representing the operation ``A @ x``, where ``A`` is
1381
+ real symmetric or complex Hermitian. For buckling mode (see below)
1382
+ ``A`` must additionally be positive-definite.
1383
+ k : int, optional
1384
+ The number of eigenvalues and eigenvectors desired.
1385
+ `k` must be smaller than N. It is not possible to compute all
1386
+ eigenvectors of a matrix.
1387
+
1388
+ Returns
1389
+ -------
1390
+ w : array
1391
+ Array of k eigenvalues.
1392
+ v : array
1393
+ An array representing the `k` eigenvectors. The column ``v[:, i]`` is
1394
+ the eigenvector corresponding to the eigenvalue ``w[i]``.
1395
+
1396
+ Other Parameters
1397
+ ----------------
1398
+ M : An N x N matrix, array, sparse matrix, or linear operator representing
1399
+ the operation ``M @ x`` for the generalized eigenvalue problem
1400
+
1401
+ A @ x = w * M @ x.
1402
+
1403
+ M must represent a real symmetric matrix if A is real, and must
1404
+ represent a complex Hermitian matrix if A is complex. For best
1405
+ results, the data type of M should be the same as that of A.
1406
+ Additionally:
1407
+
1408
+ If sigma is None, M is symmetric positive definite.
1409
+
1410
+ If sigma is specified, M is symmetric positive semi-definite.
1411
+
1412
+ In buckling mode, M is symmetric indefinite.
1413
+
1414
+ If sigma is None, eigsh requires an operator to compute the solution
1415
+ of the linear equation ``M @ x = b``. This is done internally via a
1416
+ (sparse) LU decomposition for an explicit matrix M, or via an
1417
+ iterative solver for a general linear operator. Alternatively,
1418
+ the user can supply the matrix or operator Minv, which gives
1419
+ ``x = Minv @ b = M^-1 @ b``.
1420
+ sigma : real
1421
+ Find eigenvalues near sigma using shift-invert mode. This requires
1422
+ an operator to compute the solution of the linear system
1423
+ ``[A - sigma * M] x = b``, where M is the identity matrix if
1424
+ unspecified. This is computed internally via a (sparse) LU
1425
+ decomposition for explicit matrices A & M, or via an iterative
1426
+ solver if either A or M is a general linear operator.
1427
+ Alternatively, the user can supply the matrix or operator OPinv,
1428
+ which gives ``x = OPinv @ b = [A - sigma * M]^-1 @ b``.
1429
+ Note that when sigma is specified, the keyword 'which' refers to
1430
+ the shifted eigenvalues ``w'[i]`` where:
1431
+
1432
+ if mode == 'normal', ``w'[i] = 1 / (w[i] - sigma)``.
1433
+
1434
+ if mode == 'cayley', ``w'[i] = (w[i] + sigma) / (w[i] - sigma)``.
1435
+
1436
+ if mode == 'buckling', ``w'[i] = w[i] / (w[i] - sigma)``.
1437
+
1438
+ (see further discussion in 'mode' below)
1439
+ v0 : ndarray, optional
1440
+ Starting vector for iteration.
1441
+ Default: random
1442
+ ncv : int, optional
1443
+ The number of Lanczos vectors generated ncv must be greater than k and
1444
+ smaller than n; it is recommended that ``ncv > 2*k``.
1445
+ Default: ``min(n, max(2*k + 1, 20))``
1446
+ which : str ['LM' | 'SM' | 'LA' | 'SA' | 'BE']
1447
+ If A is a complex Hermitian matrix, 'BE' is invalid.
1448
+ Which `k` eigenvectors and eigenvalues to find:
1449
+
1450
+ 'LM' : Largest (in magnitude) eigenvalues.
1451
+
1452
+ 'SM' : Smallest (in magnitude) eigenvalues.
1453
+
1454
+ 'LA' : Largest (algebraic) eigenvalues.
1455
+
1456
+ 'SA' : Smallest (algebraic) eigenvalues.
1457
+
1458
+ 'BE' : Half (k/2) from each end of the spectrum.
1459
+
1460
+ When k is odd, return one more (k/2+1) from the high end.
1461
+ When sigma != None, 'which' refers to the shifted eigenvalues ``w'[i]``
1462
+ (see discussion in 'sigma', above). ARPACK is generally better
1463
+ at finding large values than small values. If small eigenvalues are
1464
+ desired, consider using shift-invert mode for better performance.
1465
+ maxiter : int, optional
1466
+ Maximum number of Arnoldi update iterations allowed.
1467
+ Default: ``n*10``
1468
+ tol : float
1469
+ Relative accuracy for eigenvalues (stopping criterion).
1470
+ The default value of 0 implies machine precision.
1471
+ Minv : N x N matrix, array, sparse matrix, or LinearOperator
1472
+ See notes in M, above.
1473
+ OPinv : N x N matrix, array, sparse matrix, or LinearOperator
1474
+ See notes in sigma, above.
1475
+ return_eigenvectors : bool
1476
+ Return eigenvectors (True) in addition to eigenvalues.
1477
+ This value determines the order in which eigenvalues are sorted.
1478
+ The sort order is also dependent on the `which` variable.
1479
+
1480
+ For which = 'LM' or 'SA':
1481
+ If `return_eigenvectors` is True, eigenvalues are sorted by
1482
+ algebraic value.
1483
+
1484
+ If `return_eigenvectors` is False, eigenvalues are sorted by
1485
+ absolute value.
1486
+
1487
+ For which = 'BE' or 'LA':
1488
+ eigenvalues are always sorted by algebraic value.
1489
+
1490
+ For which = 'SM':
1491
+ If `return_eigenvectors` is True, eigenvalues are sorted by
1492
+ algebraic value.
1493
+
1494
+ If `return_eigenvectors` is False, eigenvalues are sorted by
1495
+ decreasing absolute value.
1496
+
1497
+ mode : string ['normal' | 'buckling' | 'cayley']
1498
+ Specify strategy to use for shift-invert mode. This argument applies
1499
+ only for real-valued A and sigma != None. For shift-invert mode,
1500
+ ARPACK internally solves the eigenvalue problem
1501
+ ``OP @ x'[i] = w'[i] * B @ x'[i]``
1502
+ and transforms the resulting Ritz vectors x'[i] and Ritz values w'[i]
1503
+ into the desired eigenvectors and eigenvalues of the problem
1504
+ ``A @ x[i] = w[i] * M @ x[i]``.
1505
+ The modes are as follows:
1506
+
1507
+ 'normal' :
1508
+ OP = [A - sigma * M]^-1 @ M,
1509
+ B = M,
1510
+ w'[i] = 1 / (w[i] - sigma)
1511
+
1512
+ 'buckling' :
1513
+ OP = [A - sigma * M]^-1 @ A,
1514
+ B = A,
1515
+ w'[i] = w[i] / (w[i] - sigma)
1516
+
1517
+ 'cayley' :
1518
+ OP = [A - sigma * M]^-1 @ [A + sigma * M],
1519
+ B = M,
1520
+ w'[i] = (w[i] + sigma) / (w[i] - sigma)
1521
+
1522
+ The choice of mode will affect which eigenvalues are selected by
1523
+ the keyword 'which', and can also impact the stability of
1524
+ convergence (see [2] for a discussion).
1525
+
1526
+ Raises
1527
+ ------
1528
+ ArpackNoConvergence
1529
+ When the requested convergence is not obtained.
1530
+
1531
+ The currently converged eigenvalues and eigenvectors can be found
1532
+ as ``eigenvalues`` and ``eigenvectors`` attributes of the exception
1533
+ object.
1534
+
1535
+ See Also
1536
+ --------
1537
+ eigs : eigenvalues and eigenvectors for a general (nonsymmetric) matrix A
1538
+ svds : singular value decomposition for a matrix A
1539
+
1540
+ Notes
1541
+ -----
1542
+ This function is a wrapper to the ARPACK [1]_ SSEUPD and DSEUPD
1543
+ functions which use the Implicitly Restarted Lanczos Method to
1544
+ find the eigenvalues and eigenvectors [2]_.
1545
+
1546
+ References
1547
+ ----------
1548
+ .. [1] ARPACK Software, https://github.com/opencollab/arpack-ng
1549
+ .. [2] R. B. Lehoucq, D. C. Sorensen, and C. Yang, ARPACK USERS GUIDE:
1550
+ Solution of Large Scale Eigenvalue Problems by Implicitly Restarted
1551
+ Arnoldi Methods. SIAM, Philadelphia, PA, 1998.
1552
+
1553
+ Examples
1554
+ --------
1555
+ >>> import numpy as np
1556
+ >>> from scipy.sparse.linalg import eigsh
1557
+ >>> identity = np.eye(13)
1558
+ >>> eigenvalues, eigenvectors = eigsh(identity, k=6)
1559
+ >>> eigenvalues
1560
+ array([1., 1., 1., 1., 1., 1.])
1561
+ >>> eigenvectors.shape
1562
+ (13, 6)
1563
+
1564
+ """
1565
+ # complex Hermitian matrices should be solved with eigs
1566
+ if np.issubdtype(A.dtype, np.complexfloating):
1567
+ if mode != 'normal':
1568
+ raise ValueError(f"mode={mode} cannot be used with complex matrix A")
1569
+ if which == 'BE':
1570
+ raise ValueError("which='BE' cannot be used with complex matrix A")
1571
+ elif which == 'LA':
1572
+ which = 'LR'
1573
+ elif which == 'SA':
1574
+ which = 'SR'
1575
+ ret = eigs(A, k, M=M, sigma=sigma, which=which, v0=v0,
1576
+ ncv=ncv, maxiter=maxiter, tol=tol,
1577
+ return_eigenvectors=return_eigenvectors, Minv=Minv,
1578
+ OPinv=OPinv)
1579
+
1580
+ if return_eigenvectors:
1581
+ return ret[0].real, ret[1]
1582
+ else:
1583
+ return ret.real
1584
+
1585
+ if A.shape[0] != A.shape[1]:
1586
+ raise ValueError(f'expected square matrix (shape={A.shape})')
1587
+ if M is not None:
1588
+ if M.shape != A.shape:
1589
+ raise ValueError(f'wrong M dimensions {M.shape}, should be {A.shape}')
1590
+ if np.dtype(M.dtype).char.lower() != np.dtype(A.dtype).char.lower():
1591
+ warnings.warn('M does not have the same type precision as A. '
1592
+ 'This may adversely affect ARPACK convergence',
1593
+ stacklevel=2)
1594
+
1595
+ n = A.shape[0]
1596
+
1597
+ if k <= 0:
1598
+ raise ValueError("k must be greater than 0.")
1599
+
1600
+ if k >= n:
1601
+ warnings.warn("k >= N for N * N square matrix. "
1602
+ "Attempting to use scipy.linalg.eigh instead.",
1603
+ RuntimeWarning, stacklevel=2)
1604
+
1605
+ if issparse(A):
1606
+ raise TypeError("Cannot use scipy.linalg.eigh for sparse A with "
1607
+ "k >= N. Use scipy.linalg.eigh(A.toarray()) or"
1608
+ " reduce k.")
1609
+ if isinstance(A, LinearOperator):
1610
+ raise TypeError("Cannot use scipy.linalg.eigh for LinearOperator "
1611
+ "A with k >= N.")
1612
+ if isinstance(M, LinearOperator):
1613
+ raise TypeError("Cannot use scipy.linalg.eigh for LinearOperator "
1614
+ "M with k >= N.")
1615
+
1616
+ return eigh(A, b=M, eigvals_only=not return_eigenvectors)
1617
+
1618
+ if sigma is None:
1619
+ A = aslinearoperator(A)
1620
+ matvec = A.matvec
1621
+
1622
+ if OPinv is not None:
1623
+ raise ValueError("OPinv should not be specified "
1624
+ "with sigma = None.")
1625
+ if M is None:
1626
+ #standard eigenvalue problem
1627
+ mode = 1
1628
+ M_matvec = None
1629
+ Minv_matvec = None
1630
+ if Minv is not None:
1631
+ raise ValueError("Minv should not be "
1632
+ "specified with M = None.")
1633
+ else:
1634
+ #general eigenvalue problem
1635
+ mode = 2
1636
+ if Minv is None:
1637
+ Minv_matvec = get_inv_matvec(M, hermitian=True, tol=tol)
1638
+ else:
1639
+ Minv = aslinearoperator(Minv)
1640
+ Minv_matvec = Minv.matvec
1641
+ M_matvec = aslinearoperator(M).matvec
1642
+ else:
1643
+ # sigma is not None: shift-invert mode
1644
+ if Minv is not None:
1645
+ raise ValueError("Minv should not be specified when sigma is")
1646
+
1647
+ # normal mode
1648
+ if mode == 'normal':
1649
+ mode = 3
1650
+ matvec = None
1651
+ if OPinv is None:
1652
+ Minv_matvec = get_OPinv_matvec(A, M, sigma,
1653
+ hermitian=True, tol=tol)
1654
+ else:
1655
+ OPinv = aslinearoperator(OPinv)
1656
+ Minv_matvec = OPinv.matvec
1657
+ if M is None:
1658
+ M_matvec = None
1659
+ else:
1660
+ M = aslinearoperator(M)
1661
+ M_matvec = M.matvec
1662
+
1663
+ # buckling mode
1664
+ elif mode == 'buckling':
1665
+ mode = 4
1666
+ if OPinv is None:
1667
+ Minv_matvec = get_OPinv_matvec(A, M, sigma,
1668
+ hermitian=True, tol=tol)
1669
+ else:
1670
+ Minv_matvec = aslinearoperator(OPinv).matvec
1671
+ matvec = aslinearoperator(A).matvec
1672
+ M_matvec = None
1673
+
1674
+ # cayley-transform mode
1675
+ elif mode == 'cayley':
1676
+ mode = 5
1677
+ matvec = aslinearoperator(A).matvec
1678
+ if OPinv is None:
1679
+ Minv_matvec = get_OPinv_matvec(A, M, sigma,
1680
+ hermitian=True, tol=tol)
1681
+ else:
1682
+ Minv_matvec = aslinearoperator(OPinv).matvec
1683
+ if M is None:
1684
+ M_matvec = None
1685
+ else:
1686
+ M_matvec = aslinearoperator(M).matvec
1687
+
1688
+ # unrecognized mode
1689
+ else:
1690
+ raise ValueError(f"unrecognized mode '{mode}'")
1691
+
1692
+ params = _SymmetricArpackParams(n, k, A.dtype.char, matvec, mode,
1693
+ M_matvec, Minv_matvec, sigma,
1694
+ ncv, v0, maxiter, which, tol)
1695
+
1696
+ with _ARPACK_LOCK:
1697
+ while not params.converged:
1698
+ params.iterate()
1699
+
1700
+ return params.extract(return_eigenvectors)
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/arpack/tests/__init__.py ADDED
File without changes
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/arpack/tests/test_arpack.py ADDED
@@ -0,0 +1,717 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __usage__ = """
2
+ To run tests locally:
3
+ python tests/test_arpack.py [-l<int>] [-v<int>]
4
+
5
+ """
6
+
7
+ import threading
8
+ import itertools
9
+
10
+ import numpy as np
11
+
12
+ from numpy.testing import assert_allclose, assert_equal, suppress_warnings
13
+ from pytest import raises as assert_raises
14
+ import pytest
15
+
16
+ from numpy import dot, conj, random
17
+ from scipy.linalg import eig, eigh
18
+ from scipy.sparse import csc_array, csr_array, diags_array, random_array
19
+ from scipy.sparse.linalg import LinearOperator, aslinearoperator
20
+ from scipy.sparse.linalg._eigen.arpack import (eigs, eigsh, arpack,
21
+ ArpackNoConvergence)
22
+
23
+
24
+ from scipy._lib._gcutils import assert_deallocated, IS_PYPY
25
+
26
+
27
+ # precision for tests
28
+ _ndigits = {'f': 3, 'd': 11, 'F': 3, 'D': 11}
29
+
30
+
31
+ def _get_test_tolerance(type_char, mattype=None, D_type=None, which=None):
32
+ """
33
+ Return tolerance values suitable for a given test:
34
+
35
+ Parameters
36
+ ----------
37
+ type_char : {'f', 'd', 'F', 'D'}
38
+ Data type in ARPACK eigenvalue problem
39
+ mattype : {csr_array, aslinearoperator, asarray}, optional
40
+ Linear operator type
41
+
42
+ Returns
43
+ -------
44
+ tol
45
+ Tolerance to pass to the ARPACK routine
46
+ rtol
47
+ Relative tolerance for outputs
48
+ atol
49
+ Absolute tolerance for outputs
50
+
51
+ """
52
+
53
+ rtol = {'f': 3000 * np.finfo(np.float32).eps,
54
+ 'F': 3000 * np.finfo(np.float32).eps,
55
+ 'd': 2000 * np.finfo(np.float64).eps,
56
+ 'D': 2000 * np.finfo(np.float64).eps}[type_char]
57
+ atol = rtol
58
+ tol = 0
59
+
60
+ if mattype is aslinearoperator and type_char in ('f', 'F'):
61
+ # iterative methods in single precision: worse errors
62
+ # also: bump ARPACK tolerance so that the iterative method converges
63
+ tol = 30 * np.finfo(np.float32).eps
64
+ rtol *= 5
65
+
66
+ if (
67
+ isinstance(mattype, type) and issubclass(mattype, csr_array)
68
+ and type_char in ('f', 'F')
69
+ ):
70
+ # sparse in single precision: worse errors
71
+ rtol *= 5
72
+
73
+ if (
74
+ which in ('LM', 'SM', 'LA')
75
+ and D_type.name == "gen-hermitian-Mc"
76
+ ):
77
+ if type_char == 'F':
78
+ # missing case 1, 2, and more, from PR 14798
79
+ rtol *= 5
80
+
81
+ if type_char == 'D':
82
+ # missing more cases, from PR 14798
83
+ rtol *= 10
84
+ atol *= 10
85
+
86
+ return tol, rtol, atol
87
+
88
+
89
+ def generate_matrix(N, complex_=False, hermitian=False,
90
+ pos_definite=False, sparse=False, rng=None):
91
+ M = rng.random((N, N))
92
+ if complex_:
93
+ M = M + 1j * rng.random((N, N))
94
+
95
+ if hermitian:
96
+ if pos_definite:
97
+ if sparse:
98
+ i = np.arange(N)
99
+ j = rng.randint(N, size=N-2)
100
+ i, j = np.meshgrid(i, j)
101
+ M[i, j] = 0
102
+ M = np.dot(M.conj(), M.T)
103
+ else:
104
+ M = np.dot(M.conj(), M.T)
105
+ if sparse:
106
+ i = rng.randint(N, size=N * N // 4)
107
+ j = rng.randint(N, size=N * N // 4)
108
+ ind = np.nonzero(i == j)
109
+ j[ind] = (j[ind] + 1) % N
110
+ M[i, j] = 0
111
+ M[j, i] = 0
112
+ else:
113
+ if sparse:
114
+ i = rng.randint(N, size=N * N // 2)
115
+ j = rng.randint(N, size=N * N // 2)
116
+ M[i, j] = 0
117
+ return M
118
+
119
+
120
+ def generate_matrix_symmetric(N, pos_definite=False, sparse=False, rng=None):
121
+ M = rng.random((N, N))
122
+
123
+ M = 0.5 * (M + M.T) # Make M symmetric
124
+
125
+ if pos_definite:
126
+ Id = N * np.eye(N)
127
+ if sparse:
128
+ M = csr_array(M)
129
+ M += Id
130
+ else:
131
+ if sparse:
132
+ M = csr_array(M)
133
+
134
+ return M
135
+
136
+
137
+ def assert_allclose_cc(actual, desired, **kw):
138
+ """Almost equal or complex conjugates almost equal"""
139
+ try:
140
+ assert_allclose(actual, desired, **kw)
141
+ except AssertionError:
142
+ assert_allclose(actual, conj(desired), **kw)
143
+
144
+
145
+ def argsort_which(eigenvalues, typ, k, which,
146
+ sigma=None, OPpart=None, mode=None):
147
+ """Return sorted indices of eigenvalues using the "which" keyword
148
+ from eigs and eigsh"""
149
+ if sigma is None:
150
+ reval = np.round(eigenvalues, decimals=_ndigits[typ])
151
+ else:
152
+ if mode is None or mode == 'normal':
153
+ if OPpart is None:
154
+ reval = 1. / (eigenvalues - sigma)
155
+ elif OPpart == 'r':
156
+ reval = 0.5 * (1. / (eigenvalues - sigma)
157
+ + 1. / (eigenvalues - np.conj(sigma)))
158
+ elif OPpart == 'i':
159
+ reval = -0.5j * (1. / (eigenvalues - sigma)
160
+ - 1. / (eigenvalues - np.conj(sigma)))
161
+ elif mode == 'cayley':
162
+ reval = (eigenvalues + sigma) / (eigenvalues - sigma)
163
+ elif mode == 'buckling':
164
+ reval = eigenvalues / (eigenvalues - sigma)
165
+ else:
166
+ raise ValueError(f"mode='{mode}' not recognized")
167
+
168
+ reval = np.round(reval, decimals=_ndigits[typ])
169
+
170
+ if which in ['LM', 'SM']:
171
+ ind = np.argsort(abs(reval))
172
+ elif which in ['LR', 'SR', 'LA', 'SA', 'BE']:
173
+ ind = np.argsort(np.real(reval))
174
+ elif which in ['LI', 'SI']:
175
+ # for LI,SI ARPACK returns largest,smallest abs(imaginary) why?
176
+ if typ.islower():
177
+ ind = np.argsort(abs(np.imag(reval)))
178
+ else:
179
+ ind = np.argsort(np.imag(reval))
180
+ else:
181
+ raise ValueError(f"which='{which}' is unrecognized")
182
+
183
+ if which in ['LM', 'LA', 'LR', 'LI']:
184
+ return ind[-k:]
185
+ elif which in ['SM', 'SA', 'SR', 'SI']:
186
+ return ind[:k]
187
+ elif which == 'BE':
188
+ return np.concatenate((ind[:k//2], ind[k//2-k:]))
189
+
190
+
191
+ def eval_evec(symmetric, d, typ, k, which, v0=None, sigma=None,
192
+ mattype=np.asarray, OPpart=None, mode='normal'):
193
+ general = ('bmat' in d)
194
+
195
+ if symmetric:
196
+ eigs_func = eigsh
197
+ else:
198
+ eigs_func = eigs
199
+
200
+ if general:
201
+ err = (f"error for {eigs_func.__name__}:general, typ={typ}, which={which}, "
202
+ f"sigma={sigma}, mattype={mattype.__name__},"
203
+ f" OPpart={OPpart}, mode={mode}")
204
+ else:
205
+ err = (f"error for {eigs_func.__name__}:standard, typ={typ}, which={which}, "
206
+ f"sigma={sigma}, mattype={mattype.__name__}, "
207
+ f"OPpart={OPpart}, mode={mode}")
208
+
209
+ a = d['mat'].astype(typ)
210
+ ac = mattype(a)
211
+
212
+ if general:
213
+ b = d['bmat'].astype(typ)
214
+ bc = mattype(b)
215
+
216
+ # get exact eigenvalues
217
+ exact_eval = d['eval'].astype(typ.upper())
218
+ ind = argsort_which(exact_eval, typ, k, which,
219
+ sigma, OPpart, mode)
220
+ exact_eval = exact_eval[ind]
221
+
222
+ # compute arpack eigenvalues
223
+ kwargs = dict(which=which, v0=v0, sigma=sigma)
224
+ if eigs_func is eigsh:
225
+ kwargs['mode'] = mode
226
+ else:
227
+ kwargs['OPpart'] = OPpart
228
+
229
+ # compute suitable tolerances
230
+ kwargs['tol'], rtol, atol = _get_test_tolerance(typ, mattype, d, which)
231
+ # on rare occasions, ARPACK routines return results that are proper
232
+ # eigenvalues and -vectors, but not necessarily the ones requested in
233
+ # the parameter which. This is inherent to the Krylov methods, and
234
+ # should not be treated as a failure. If such a rare situation
235
+ # occurs, the calculation is tried again (but at most a few times).
236
+ ntries = 0
237
+ while ntries < 5:
238
+ # solve
239
+ if general:
240
+ try:
241
+ eigenvalues, evec = eigs_func(ac, k, bc, **kwargs)
242
+ except ArpackNoConvergence:
243
+ kwargs['maxiter'] = 20*a.shape[0]
244
+ eigenvalues, evec = eigs_func(ac, k, bc, **kwargs)
245
+ else:
246
+ try:
247
+ eigenvalues, evec = eigs_func(ac, k, **kwargs)
248
+ except ArpackNoConvergence:
249
+ kwargs['maxiter'] = 20*a.shape[0]
250
+ eigenvalues, evec = eigs_func(ac, k, **kwargs)
251
+
252
+ ind = argsort_which(eigenvalues, typ, k, which,
253
+ sigma, OPpart, mode)
254
+ eigenvalues = eigenvalues[ind]
255
+ evec = evec[:, ind]
256
+
257
+ try:
258
+ # check eigenvalues
259
+ assert_allclose_cc(eigenvalues, exact_eval, rtol=rtol, atol=atol,
260
+ err_msg=err)
261
+ check_evecs = True
262
+ except AssertionError:
263
+ check_evecs = False
264
+ ntries += 1
265
+
266
+ if check_evecs:
267
+ # check eigenvectors
268
+ LHS = np.dot(a, evec)
269
+ if general:
270
+ RHS = eigenvalues * np.dot(b, evec)
271
+ else:
272
+ RHS = eigenvalues * evec
273
+
274
+ assert_allclose(LHS, RHS, rtol=rtol, atol=atol, err_msg=err)
275
+ break
276
+
277
+ # check eigenvalues
278
+ assert_allclose_cc(eigenvalues, exact_eval, rtol=rtol, atol=atol, err_msg=err)
279
+
280
+
281
+ class DictWithRepr(dict):
282
+ def __init__(self, name):
283
+ self.name = name
284
+
285
+ def __repr__(self):
286
+ return f"<{self.name}>"
287
+
288
+
289
+ class SymmetricParams:
290
+ def __init__(self):
291
+ self.eigs = eigsh
292
+ self.which = ['LM', 'SM', 'LA', 'SA', 'BE']
293
+ self.mattypes = [csr_array, aslinearoperator, np.asarray]
294
+ self.sigmas_modes = {None: ['normal'],
295
+ 0.5: ['normal', 'buckling', 'cayley']}
296
+
297
+ # generate matrices
298
+ # these should all be float32 so that the eigenvalues
299
+ # are the same in float32 and float64
300
+ N = 6
301
+ rng = np.random.RandomState(2300)
302
+ Ar = generate_matrix(N, hermitian=True,
303
+ pos_definite=True,
304
+ rng=rng).astype('f').astype('d')
305
+ M = generate_matrix(N, hermitian=True,
306
+ pos_definite=True,
307
+ rng=rng).astype('f').astype('d')
308
+ Ac = generate_matrix(N, hermitian=True, pos_definite=True,
309
+ complex_=True, rng=rng).astype('F').astype('D')
310
+ Mc = generate_matrix(N, hermitian=True, pos_definite=True,
311
+ complex_=True, rng=rng).astype('F').astype('D')
312
+ v0 = rng.random(N)
313
+
314
+ # standard symmetric problem
315
+ SS = DictWithRepr("std-symmetric")
316
+ SS['mat'] = Ar
317
+ SS['v0'] = v0
318
+ SS['eval'] = eigh(SS['mat'], eigvals_only=True)
319
+
320
+ # general symmetric problem
321
+ GS = DictWithRepr("gen-symmetric")
322
+ GS['mat'] = Ar
323
+ GS['bmat'] = M
324
+ GS['v0'] = v0
325
+ GS['eval'] = eigh(GS['mat'], GS['bmat'], eigvals_only=True)
326
+
327
+ # standard hermitian problem
328
+ SH = DictWithRepr("std-hermitian")
329
+ SH['mat'] = Ac
330
+ SH['v0'] = v0
331
+ SH['eval'] = eigh(SH['mat'], eigvals_only=True)
332
+
333
+ # general hermitian problem
334
+ GH = DictWithRepr("gen-hermitian")
335
+ GH['mat'] = Ac
336
+ GH['bmat'] = M
337
+ GH['v0'] = v0
338
+ GH['eval'] = eigh(GH['mat'], GH['bmat'], eigvals_only=True)
339
+
340
+ # general hermitian problem with hermitian M
341
+ GHc = DictWithRepr("gen-hermitian-Mc")
342
+ GHc['mat'] = Ac
343
+ GHc['bmat'] = Mc
344
+ GHc['v0'] = v0
345
+ GHc['eval'] = eigh(GHc['mat'], GHc['bmat'], eigvals_only=True)
346
+
347
+ self.real_test_cases = [SS, GS]
348
+ self.complex_test_cases = [SH, GH, GHc]
349
+
350
+
351
+ class NonSymmetricParams:
352
+ def __init__(self):
353
+ self.eigs = eigs
354
+ self.which = ['LM', 'LR', 'LI'] # , 'SM', 'LR', 'SR', 'LI', 'SI']
355
+ self.mattypes = [csr_array, aslinearoperator, np.asarray]
356
+ self.sigmas_OPparts = {None: [None],
357
+ 0.1: ['r'],
358
+ 0.1 + 0.1j: ['r', 'i']}
359
+
360
+ # generate matrices
361
+ # these should all be float32 so that the eigenvalues
362
+ # are the same in float32 and float64
363
+ N = 6
364
+ rng = np.random.RandomState(2300)
365
+ Ar = generate_matrix(N, rng=rng).astype('f').astype('d')
366
+ M = generate_matrix(N, hermitian=True,
367
+ pos_definite=True, rng=rng).astype('f').astype('d')
368
+ Ac = generate_matrix(N, complex_=True, rng=rng).astype('F').astype('D')
369
+ v0 = rng.random(N)
370
+
371
+ # standard real nonsymmetric problem
372
+ SNR = DictWithRepr("std-real-nonsym")
373
+ SNR['mat'] = Ar
374
+ SNR['v0'] = v0
375
+ SNR['eval'] = eig(SNR['mat'], left=False, right=False)
376
+
377
+ # general real nonsymmetric problem
378
+ GNR = DictWithRepr("gen-real-nonsym")
379
+ GNR['mat'] = Ar
380
+ GNR['bmat'] = M
381
+ GNR['v0'] = v0
382
+ GNR['eval'] = eig(GNR['mat'], GNR['bmat'], left=False, right=False)
383
+
384
+ # standard complex nonsymmetric problem
385
+ SNC = DictWithRepr("std-cmplx-nonsym")
386
+ SNC['mat'] = Ac
387
+ SNC['v0'] = v0
388
+ SNC['eval'] = eig(SNC['mat'], left=False, right=False)
389
+
390
+ # general complex nonsymmetric problem
391
+ GNC = DictWithRepr("gen-cmplx-nonsym")
392
+ GNC['mat'] = Ac
393
+ GNC['bmat'] = M
394
+ GNC['v0'] = v0
395
+ GNC['eval'] = eig(GNC['mat'], GNC['bmat'], left=False, right=False)
396
+
397
+ self.real_test_cases = [SNR, GNR]
398
+ self.complex_test_cases = [SNC, GNC]
399
+
400
+
401
+ @pytest.mark.iterations(1)
402
+ @pytest.mark.thread_unsafe
403
+ def test_symmetric_modes(num_parallel_threads):
404
+ assert num_parallel_threads == 1
405
+ params = SymmetricParams()
406
+ k = 2
407
+ symmetric = True
408
+ for D in params.real_test_cases:
409
+ for typ in 'fd':
410
+ for which in params.which:
411
+ for mattype in params.mattypes:
412
+ for (sigma, modes) in params.sigmas_modes.items():
413
+ for mode in modes:
414
+ eval_evec(symmetric, D, typ, k, which,
415
+ None, sigma, mattype, None, mode)
416
+
417
+
418
+ def test_hermitian_modes():
419
+ params = SymmetricParams()
420
+ k = 2
421
+ symmetric = True
422
+ for D in params.complex_test_cases:
423
+ for typ in 'FD':
424
+ for which in params.which:
425
+ if which == 'BE':
426
+ continue # BE invalid for complex
427
+ for mattype in params.mattypes:
428
+ for sigma in params.sigmas_modes:
429
+ eval_evec(symmetric, D, typ, k, which,
430
+ None, sigma, mattype)
431
+
432
+
433
+ def test_symmetric_starting_vector():
434
+ params = SymmetricParams()
435
+ symmetric = True
436
+ for k in [1, 2, 3, 4, 5]:
437
+ for D in params.real_test_cases:
438
+ for typ in 'fd':
439
+ v0 = random.rand(len(D['v0'])).astype(typ)
440
+ eval_evec(symmetric, D, typ, k, 'LM', v0)
441
+
442
+
443
+ def test_symmetric_no_convergence():
444
+ rng = np.random.RandomState(1234)
445
+ m = generate_matrix(30, hermitian=True, pos_definite=True, rng=rng)
446
+ tol, rtol, atol = _get_test_tolerance('d')
447
+ try:
448
+ w, v = eigsh(m, 4, which='LM', v0=m[:, 0], maxiter=5, tol=tol, ncv=9)
449
+ raise AssertionError("Spurious no-error exit")
450
+ except ArpackNoConvergence as err:
451
+ k = len(err.eigenvalues)
452
+ if k <= 0:
453
+ raise AssertionError("Spurious no-eigenvalues-found case") from err
454
+ w, v = err.eigenvalues, err.eigenvectors
455
+ assert_allclose(dot(m, v), w * v, rtol=rtol, atol=atol)
456
+
457
+
458
+ def test_real_nonsymmetric_modes():
459
+ params = NonSymmetricParams()
460
+ k = 2
461
+ symmetric = False
462
+ for D in params.real_test_cases:
463
+ for typ in 'fd':
464
+ for which in params.which:
465
+ for mattype in params.mattypes:
466
+ for sigma, OPparts in params.sigmas_OPparts.items():
467
+ for OPpart in OPparts:
468
+ eval_evec(symmetric, D, typ, k, which,
469
+ None, sigma, mattype, OPpart)
470
+
471
+
472
+ def test_complex_nonsymmetric_modes():
473
+ params = NonSymmetricParams()
474
+ k = 2
475
+ symmetric = False
476
+ for D in params.complex_test_cases:
477
+ for typ in 'DF':
478
+ for which in params.which:
479
+ for mattype in params.mattypes:
480
+ for sigma in params.sigmas_OPparts:
481
+ eval_evec(symmetric, D, typ, k, which,
482
+ None, sigma, mattype)
483
+
484
+
485
+ def test_standard_nonsymmetric_starting_vector():
486
+ params = NonSymmetricParams()
487
+ sigma = None
488
+ symmetric = False
489
+ for k in [1, 2, 3, 4]:
490
+ for d in params.complex_test_cases:
491
+ for typ in 'FD':
492
+ A = d['mat']
493
+ n = A.shape[0]
494
+ v0 = random.rand(n).astype(typ)
495
+ eval_evec(symmetric, d, typ, k, "LM", v0, sigma)
496
+
497
+
498
+ def test_general_nonsymmetric_starting_vector():
499
+ params = NonSymmetricParams()
500
+ sigma = None
501
+ symmetric = False
502
+ for k in [1, 2, 3, 4]:
503
+ for d in params.complex_test_cases:
504
+ for typ in 'FD':
505
+ A = d['mat']
506
+ n = A.shape[0]
507
+ v0 = random.rand(n).astype(typ)
508
+ eval_evec(symmetric, d, typ, k, "LM", v0, sigma)
509
+
510
+
511
+ def test_standard_nonsymmetric_no_convergence():
512
+ rng = np.random.RandomState(1234)
513
+ m = generate_matrix(30, complex_=True, rng=rng)
514
+ tol, rtol, atol = _get_test_tolerance('d')
515
+ try:
516
+ w, v = eigs(m, 4, which='LM', v0=m[:, 0], maxiter=5, tol=tol)
517
+ raise AssertionError("Spurious no-error exit")
518
+ except ArpackNoConvergence as err:
519
+ k = len(err.eigenvalues)
520
+ if k <= 0:
521
+ raise AssertionError("Spurious no-eigenvalues-found case") from err
522
+ w, v = err.eigenvalues, err.eigenvectors
523
+ for ww, vv in zip(w, v.T):
524
+ assert_allclose(dot(m, vv), ww * vv, rtol=rtol, atol=atol)
525
+
526
+
527
+ def test_eigen_bad_shapes():
528
+ # A is not square.
529
+ A = csc_array(np.zeros((2, 3)))
530
+ assert_raises(ValueError, eigs, A)
531
+
532
+
533
+ def test_eigen_bad_kwargs():
534
+ # Test eigen on wrong keyword argument
535
+ A = csc_array(np.zeros((8, 8)))
536
+ assert_raises(ValueError, eigs, A, which='XX')
537
+
538
+
539
+ def test_ticket_1459_arpack_crash():
540
+ for dtype in [np.float32, np.float64]:
541
+ # This test does not seem to catch the issue for float32,
542
+ # but we made the same fix there, just to be sure
543
+
544
+ N = 6
545
+ k = 2
546
+
547
+ np.random.seed(2301)
548
+ A = np.random.random((N, N)).astype(dtype)
549
+ v0 = np.array([-0.71063568258907849895, -0.83185111795729227424,
550
+ -0.34365925382227402451, 0.46122533684552280420,
551
+ -0.58001341115969040629, -0.78844877570084292984e-01],
552
+ dtype=dtype)
553
+
554
+ # Should not crash:
555
+ evals, evecs = eigs(A, k, v0=v0)
556
+
557
+
558
+ @pytest.mark.skipif(IS_PYPY, reason="Test not meaningful on PyPy")
559
+ def test_linearoperator_deallocation():
560
+ # Check that the linear operators used by the Arpack wrappers are
561
+ # deallocatable by reference counting -- they are big objects, so
562
+ # Python's cyclic GC may not collect them fast enough before
563
+ # running out of memory if eigs/eigsh are called in a tight loop.
564
+
565
+ M_d = np.eye(10)
566
+ M_s = csc_array(M_d)
567
+ M_o = aslinearoperator(M_d)
568
+
569
+ with assert_deallocated(lambda: arpack.SpLuInv(M_s)):
570
+ pass
571
+ with assert_deallocated(lambda: arpack.LuInv(M_d)):
572
+ pass
573
+ with assert_deallocated(lambda: arpack.IterInv(M_s)):
574
+ pass
575
+ with assert_deallocated(lambda: arpack.IterOpInv(M_o, None, 0.3)):
576
+ pass
577
+ with assert_deallocated(lambda: arpack.IterOpInv(M_o, M_o, 0.3)):
578
+ pass
579
+
580
+
581
+ @pytest.mark.thread_unsafe
582
+ def test_parallel_threads():
583
+ results = []
584
+ v0 = np.random.rand(50)
585
+
586
+ def worker():
587
+ x = diags_array([1, -2, 1], offsets=[-1, 0, 1], shape=(50, 50))
588
+ w, v = eigs(x, k=3, v0=v0)
589
+ results.append(w)
590
+
591
+ w, v = eigsh(x, k=3, v0=v0)
592
+ results.append(w)
593
+
594
+ threads = [threading.Thread(target=worker) for k in range(10)]
595
+ for t in threads:
596
+ t.start()
597
+ for t in threads:
598
+ t.join()
599
+
600
+ worker()
601
+
602
+ for r in results:
603
+ assert_allclose(r, results[-1])
604
+
605
+
606
+ def test_reentering():
607
+ # Just some linear operator that calls eigs recursively
608
+ def A_matvec(x):
609
+ x = diags_array([1, -2, 1], offsets=[-1, 0, 1], shape=(50, 50))
610
+ w, v = eigs(x, k=1)
611
+ return v / w[0]
612
+ A = LinearOperator(matvec=A_matvec, dtype=float, shape=(50, 50))
613
+
614
+ # The Fortran code is not reentrant, so this fails (gracefully, not crashing)
615
+ assert_raises(RuntimeError, eigs, A, k=1)
616
+ assert_raises(RuntimeError, eigsh, A, k=1)
617
+
618
+
619
+ def test_regression_arpackng_1315():
620
+ # Check that issue arpack-ng/#1315 is not present.
621
+ # Adapted from arpack-ng/TESTS/bug_1315_single.c
622
+ # If this fails, then the installed ARPACK library is faulty.
623
+
624
+ for dtype in [np.float32, np.float64]:
625
+ np.random.seed(1234)
626
+
627
+ w0 = np.arange(1, 1000+1).astype(dtype)
628
+ A = diags_array([w0], offsets=[0], shape=(1000, 1000))
629
+
630
+ v0 = np.random.rand(1000).astype(dtype)
631
+ w, v = eigs(A, k=9, ncv=2*9+1, which="LM", v0=v0)
632
+
633
+ assert_allclose(np.sort(w), np.sort(w0[-9:]),
634
+ rtol=1e-4)
635
+
636
+
637
+ def test_eigs_for_k_greater():
638
+ # Test eigs() for k beyond limits.
639
+ rng = np.random.RandomState(1234)
640
+ A_sparse = diags_array([1, -2, 1], offsets=[-1, 0, 1], shape=(4, 4)) # sparse
641
+ A = generate_matrix(4, sparse=False, rng=rng)
642
+ M_dense = rng.random((4, 4))
643
+ M_sparse = generate_matrix(4, sparse=True, rng=rng)
644
+ M_linop = aslinearoperator(M_dense)
645
+ eig_tuple1 = eig(A, b=M_dense)
646
+ eig_tuple2 = eig(A, b=M_sparse)
647
+
648
+ with suppress_warnings() as sup:
649
+ sup.filter(RuntimeWarning)
650
+
651
+ assert_equal(eigs(A, M=M_dense, k=3), eig_tuple1)
652
+ assert_equal(eigs(A, M=M_dense, k=4), eig_tuple1)
653
+ assert_equal(eigs(A, M=M_dense, k=5), eig_tuple1)
654
+ assert_equal(eigs(A, M=M_sparse, k=5), eig_tuple2)
655
+
656
+ # M as LinearOperator
657
+ assert_raises(TypeError, eigs, A, M=M_linop, k=3)
658
+
659
+ # Test 'A' for different types
660
+ assert_raises(TypeError, eigs, aslinearoperator(A), k=3)
661
+ assert_raises(TypeError, eigs, A_sparse, k=3)
662
+
663
+
664
+ def test_eigsh_for_k_greater():
665
+ # Test eigsh() for k beyond limits.
666
+ rng = np.random.RandomState(1234)
667
+ A_sparse = diags_array([1, -2, 1], offsets=[-1, 0, 1], shape=(4, 4)) # sparse
668
+ A = generate_matrix(4, sparse=False, rng=rng)
669
+ M_dense = generate_matrix_symmetric(4, pos_definite=True, rng=rng)
670
+ M_sparse = generate_matrix_symmetric(
671
+ 4, pos_definite=True, sparse=True, rng=rng)
672
+ M_linop = aslinearoperator(M_dense)
673
+ eig_tuple1 = eigh(A, b=M_dense)
674
+ eig_tuple2 = eigh(A, b=M_sparse)
675
+
676
+ with suppress_warnings() as sup:
677
+ sup.filter(RuntimeWarning)
678
+
679
+ assert_equal(eigsh(A, M=M_dense, k=4), eig_tuple1)
680
+ assert_equal(eigsh(A, M=M_dense, k=5), eig_tuple1)
681
+ assert_equal(eigsh(A, M=M_sparse, k=5), eig_tuple2)
682
+
683
+ # M as LinearOperator
684
+ assert_raises(TypeError, eigsh, A, M=M_linop, k=4)
685
+
686
+ # Test 'A' for different types
687
+ assert_raises(TypeError, eigsh, aslinearoperator(A), k=4)
688
+ assert_raises(TypeError, eigsh, A_sparse, M=M_dense, k=4)
689
+
690
+
691
+ def test_real_eigs_real_k_subset():
692
+ rng = np.random.default_rng(2)
693
+
694
+ n = 10
695
+ A = random_array(shape=(n, n), density=0.5, rng=rng)
696
+ A.data *= 2
697
+ A.data -= 1
698
+ A += A.T # make symmetric to test real eigenvalues
699
+
700
+ v0 = np.ones(n)
701
+
702
+ whichs = ['LM', 'SM', 'LR', 'SR', 'LI', 'SI']
703
+ dtypes = [np.float32, np.float64]
704
+
705
+ for which, sigma, dtype in itertools.product(whichs, [None, 0, 5], dtypes):
706
+ prev_w = np.array([], dtype=dtype)
707
+ eps = np.finfo(dtype).eps
708
+ for k in range(1, 9):
709
+ w, z = eigs(A.astype(dtype), k=k, which=which, sigma=sigma,
710
+ v0=v0.astype(dtype), tol=0)
711
+ assert_allclose(np.linalg.norm(A.dot(z) - z * w), 0, atol=np.sqrt(eps))
712
+
713
+ # Check that the set of eigenvalues for `k` is a subset of that for `k+1`
714
+ dist = abs(prev_w[:,None] - w).min(axis=1)
715
+ assert_allclose(dist, 0, atol=np.sqrt(eps))
716
+
717
+ prev_w = w
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/lobpcg/__init__.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Locally Optimal Block Preconditioned Conjugate Gradient Method (LOBPCG)
3
+
4
+ LOBPCG is a preconditioned eigensolver for large symmetric positive definite
5
+ (SPD) generalized eigenproblems.
6
+
7
+ Call the function lobpcg - see help for lobpcg.lobpcg.
8
+
9
+ """
10
+ from .lobpcg import *
11
+
12
+ __all__ = [s for s in dir() if not s.startswith('_')]
13
+
14
+ from scipy._lib._testutils import PytestTester
15
+ test = PytestTester(__name__)
16
+ del PytestTester
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/lobpcg/lobpcg.py ADDED
@@ -0,0 +1,1110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Locally Optimal Block Preconditioned Conjugate Gradient Method (LOBPCG).
3
+
4
+ References
5
+ ----------
6
+ .. [1] A. V. Knyazev (2001),
7
+ Toward the Optimal Preconditioned Eigensolver: Locally Optimal
8
+ Block Preconditioned Conjugate Gradient Method.
9
+ SIAM Journal on Scientific Computing 23, no. 2,
10
+ pp. 517-541. :doi:`10.1137/S1064827500366124`
11
+
12
+ .. [2] A. V. Knyazev, I. Lashuk, M. E. Argentati, and E. Ovchinnikov (2007),
13
+ Block Locally Optimal Preconditioned Eigenvalue Xolvers (BLOPEX)
14
+ in hypre and PETSc. :arxiv:`0705.2626`
15
+
16
+ .. [3] A. V. Knyazev's C and MATLAB implementations:
17
+ https://github.com/lobpcg/blopex
18
+ """
19
+
20
+ import warnings
21
+ import numpy as np
22
+ from scipy.linalg import (inv, eigh, cho_factor, cho_solve,
23
+ cholesky, LinAlgError)
24
+ from scipy.sparse.linalg import LinearOperator
25
+ from scipy.sparse import issparse
26
+
27
+ __all__ = ["lobpcg"]
28
+
29
+
30
+ def _report_nonhermitian(M, name):
31
+ """
32
+ Report if `M` is not a Hermitian matrix given its type.
33
+ """
34
+ from scipy.linalg import norm
35
+
36
+ md = M - M.T.conj()
37
+ nmd = norm(md, 1)
38
+ tol = 10 * np.finfo(M.dtype).eps
39
+ tol = max(tol, tol * norm(M, 1))
40
+ if nmd > tol:
41
+ warnings.warn(
42
+ f"Matrix {name} of the type {M.dtype} is not Hermitian: "
43
+ f"condition: {nmd} < {tol} fails.",
44
+ UserWarning, stacklevel=4
45
+ )
46
+
47
+ def _as2d(ar):
48
+ """
49
+ If the input array is 2D return it, if it is 1D, append a dimension,
50
+ making it a column vector.
51
+ """
52
+ if ar.ndim == 2:
53
+ return ar
54
+ else: # Assume 1!
55
+ aux = np.asarray(ar)
56
+ aux.shape = (ar.shape[0], 1)
57
+ return aux
58
+
59
+
60
+ def _makeMatMat(m):
61
+ if m is None:
62
+ return None
63
+ elif callable(m):
64
+ return lambda v: m(v)
65
+ else:
66
+ return lambda v: m @ v
67
+
68
+
69
+ def _matmul_inplace(x, y, verbosityLevel=0):
70
+ """Perform 'np.matmul' in-place if possible.
71
+
72
+ If some sufficient conditions for inplace matmul are met, do so.
73
+ Otherwise try inplace update and fall back to overwrite if that fails.
74
+ """
75
+ if x.flags["CARRAY"] and x.shape[1] == y.shape[1] and x.dtype == y.dtype:
76
+ # conditions where we can guarantee that inplace updates will work;
77
+ # i.e. x is not a view/slice, x & y have compatible dtypes, and the
78
+ # shape of the result of x @ y matches the shape of x.
79
+ np.matmul(x, y, out=x)
80
+ else:
81
+ # ideally, we'd have an exhaustive list of conditions above when
82
+ # inplace updates are possible; since we don't, we opportunistically
83
+ # try if it works, and fall back to overwriting if necessary
84
+ try:
85
+ np.matmul(x, y, out=x)
86
+ except Exception:
87
+ if verbosityLevel:
88
+ warnings.warn(
89
+ "Inplace update of x = x @ y failed, "
90
+ "x needs to be overwritten.",
91
+ UserWarning, stacklevel=3
92
+ )
93
+ x = x @ y
94
+ return x
95
+
96
+
97
+ def _applyConstraints(blockVectorV, factYBY, blockVectorBY, blockVectorY):
98
+ """Changes blockVectorV in-place."""
99
+ YBV = blockVectorBY.T.conj() @ blockVectorV
100
+ tmp = cho_solve(factYBY, YBV)
101
+ blockVectorV -= blockVectorY @ tmp
102
+
103
+
104
+ def _b_orthonormalize(B, blockVectorV, blockVectorBV=None,
105
+ verbosityLevel=0):
106
+ """in-place B-orthonormalize the given block vector using Cholesky."""
107
+ if blockVectorBV is None:
108
+ if B is None:
109
+ blockVectorBV = blockVectorV
110
+ else:
111
+ try:
112
+ blockVectorBV = B(blockVectorV)
113
+ except Exception as e:
114
+ if verbosityLevel:
115
+ warnings.warn(
116
+ f"Secondary MatMul call failed with error\n"
117
+ f"{e}\n",
118
+ UserWarning, stacklevel=3
119
+ )
120
+ return None, None, None
121
+ if blockVectorBV.shape != blockVectorV.shape:
122
+ raise ValueError(
123
+ f"The shape {blockVectorV.shape} "
124
+ f"of the orthogonalized matrix not preserved\n"
125
+ f"and changed to {blockVectorBV.shape} "
126
+ f"after multiplying by the secondary matrix.\n"
127
+ )
128
+
129
+ VBV = blockVectorV.T.conj() @ blockVectorBV
130
+ try:
131
+ # VBV is a Cholesky factor from now on...
132
+ VBV = cholesky(VBV, overwrite_a=True)
133
+ VBV = inv(VBV, overwrite_a=True)
134
+ blockVectorV = _matmul_inplace(
135
+ blockVectorV, VBV,
136
+ verbosityLevel=verbosityLevel
137
+ )
138
+ if B is not None:
139
+ blockVectorBV = _matmul_inplace(
140
+ blockVectorBV, VBV,
141
+ verbosityLevel=verbosityLevel
142
+ )
143
+ return blockVectorV, blockVectorBV, VBV
144
+ except LinAlgError:
145
+ if verbosityLevel:
146
+ warnings.warn(
147
+ "Cholesky has failed.",
148
+ UserWarning, stacklevel=3
149
+ )
150
+ return None, None, None
151
+
152
+
153
+ def _get_indx(_lambda, num, largest):
154
+ """Get `num` indices into `_lambda` depending on `largest` option."""
155
+ ii = np.argsort(_lambda)
156
+ if largest:
157
+ ii = ii[:-num - 1:-1]
158
+ else:
159
+ ii = ii[:num]
160
+
161
+ return ii
162
+
163
+
164
+ def _handle_gramA_gramB_verbosity(gramA, gramB, verbosityLevel):
165
+ if verbosityLevel:
166
+ _report_nonhermitian(gramA, "gramA")
167
+ _report_nonhermitian(gramB, "gramB")
168
+
169
+
170
+ def lobpcg(
171
+ A,
172
+ X,
173
+ B=None,
174
+ M=None,
175
+ Y=None,
176
+ tol=None,
177
+ maxiter=None,
178
+ largest=True,
179
+ verbosityLevel=0,
180
+ retLambdaHistory=False,
181
+ retResidualNormsHistory=False,
182
+ restartControl=20,
183
+ ):
184
+ """Locally Optimal Block Preconditioned Conjugate Gradient Method (LOBPCG).
185
+
186
+ LOBPCG is a preconditioned eigensolver for large real symmetric and complex
187
+ Hermitian definite generalized eigenproblems.
188
+
189
+ Parameters
190
+ ----------
191
+ A : {sparse matrix, ndarray, LinearOperator, callable object}
192
+ The Hermitian linear operator of the problem, usually given by a
193
+ sparse matrix. Often called the "stiffness matrix".
194
+ X : ndarray, float32 or float64
195
+ Initial approximation to the ``k`` eigenvectors (non-sparse).
196
+ If `A` has ``shape=(n,n)`` then `X` must have ``shape=(n,k)``.
197
+ B : {sparse matrix, ndarray, LinearOperator, callable object}
198
+ Optional. By default ``B = None``, which is equivalent to identity.
199
+ The right hand side operator in a generalized eigenproblem if present.
200
+ Often called the "mass matrix". Must be Hermitian positive definite.
201
+ M : {sparse matrix, ndarray, LinearOperator, callable object}
202
+ Optional. By default ``M = None``, which is equivalent to identity.
203
+ Preconditioner aiming to accelerate convergence.
204
+ Y : ndarray, float32 or float64, default: None
205
+ An ``n-by-sizeY`` ndarray of constraints with ``sizeY < n``.
206
+ The iterations will be performed in the ``B``-orthogonal complement
207
+ of the column-space of `Y`. `Y` must be full rank if present.
208
+ tol : scalar, optional
209
+ The default is ``tol=n*sqrt(eps)``.
210
+ Solver tolerance for the stopping criterion.
211
+ maxiter : int, default: 20
212
+ Maximum number of iterations.
213
+ largest : bool, default: True
214
+ When True, solve for the largest eigenvalues, otherwise the smallest.
215
+ verbosityLevel : int, optional
216
+ By default ``verbosityLevel=0`` no output.
217
+ Controls the solver standard/screen output.
218
+ retLambdaHistory : bool, default: False
219
+ Whether to return iterative eigenvalue history.
220
+ retResidualNormsHistory : bool, default: False
221
+ Whether to return iterative history of residual norms.
222
+ restartControl : int, optional.
223
+ Iterations restart if the residuals jump ``2**restartControl`` times
224
+ compared to the smallest recorded in ``retResidualNormsHistory``.
225
+ The default is ``restartControl=20``, making the restarts rare for
226
+ backward compatibility.
227
+
228
+ Returns
229
+ -------
230
+ lambda : ndarray of the shape ``(k, )``.
231
+ Array of ``k`` approximate eigenvalues.
232
+ v : ndarray of the same shape as ``X.shape``.
233
+ An array of ``k`` approximate eigenvectors.
234
+ lambdaHistory : ndarray, optional.
235
+ The eigenvalue history, if `retLambdaHistory` is ``True``.
236
+ ResidualNormsHistory : ndarray, optional.
237
+ The history of residual norms, if `retResidualNormsHistory`
238
+ is ``True``.
239
+
240
+ Notes
241
+ -----
242
+ The iterative loop runs ``maxit=maxiter`` (20 if ``maxit=None``)
243
+ iterations at most and finishes earlier if the tolerance is met.
244
+ Breaking backward compatibility with the previous version, LOBPCG
245
+ now returns the block of iterative vectors with the best accuracy rather
246
+ than the last one iterated, as a cure for possible divergence.
247
+
248
+ If ``X.dtype == np.float32`` and user-provided operations/multiplications
249
+ by `A`, `B`, and `M` all preserve the ``np.float32`` data type,
250
+ all the calculations and the output are in ``np.float32``.
251
+
252
+ The size of the iteration history output equals to the number of the best
253
+ (limited by `maxit`) iterations plus 3: initial, final, and postprocessing.
254
+
255
+ If both `retLambdaHistory` and `retResidualNormsHistory` are ``True``,
256
+ the return tuple has the following format
257
+ ``(lambda, V, lambda history, residual norms history)``.
258
+
259
+ In the following ``n`` denotes the matrix size and ``k`` the number
260
+ of required eigenvalues (smallest or largest).
261
+
262
+ The LOBPCG code internally solves eigenproblems of the size ``3k`` on every
263
+ iteration by calling the dense eigensolver `eigh`, so if ``k`` is not
264
+ small enough compared to ``n``, it makes no sense to call the LOBPCG code.
265
+ Moreover, if one calls the LOBPCG algorithm for ``5k > n``, it would likely
266
+ break internally, so the code calls the standard function `eigh` instead.
267
+ It is not that ``n`` should be large for the LOBPCG to work, but rather the
268
+ ratio ``n / k`` should be large. It you call LOBPCG with ``k=1``
269
+ and ``n=10``, it works though ``n`` is small. The method is intended
270
+ for extremely large ``n / k``.
271
+
272
+ The convergence speed depends basically on three factors:
273
+
274
+ 1. Quality of the initial approximations `X` to the seeking eigenvectors.
275
+ Randomly distributed around the origin vectors work well if no better
276
+ choice is known.
277
+
278
+ 2. Relative separation of the desired eigenvalues from the rest
279
+ of the eigenvalues. One can vary ``k`` to improve the separation.
280
+
281
+ 3. Proper preconditioning to shrink the spectral spread.
282
+ For example, a rod vibration test problem (under tests
283
+ directory) is ill-conditioned for large ``n``, so convergence will be
284
+ slow, unless efficient preconditioning is used. For this specific
285
+ problem, a good simple preconditioner function would be a linear solve
286
+ for `A`, which is easy to code since `A` is tridiagonal.
287
+
288
+ References
289
+ ----------
290
+ .. [1] A. V. Knyazev (2001),
291
+ Toward the Optimal Preconditioned Eigensolver: Locally Optimal
292
+ Block Preconditioned Conjugate Gradient Method.
293
+ SIAM Journal on Scientific Computing 23, no. 2,
294
+ pp. 517-541. :doi:`10.1137/S1064827500366124`
295
+
296
+ .. [2] A. V. Knyazev, I. Lashuk, M. E. Argentati, and E. Ovchinnikov
297
+ (2007), Block Locally Optimal Preconditioned Eigenvalue Xolvers
298
+ (BLOPEX) in hypre and PETSc. :arxiv:`0705.2626`
299
+
300
+ .. [3] A. V. Knyazev's C and MATLAB implementations:
301
+ https://github.com/lobpcg/blopex
302
+
303
+ Examples
304
+ --------
305
+ Our first example is minimalistic - find the largest eigenvalue of
306
+ a diagonal matrix by solving the non-generalized eigenvalue problem
307
+ ``A x = lambda x`` without constraints or preconditioning.
308
+
309
+ >>> import numpy as np
310
+ >>> from scipy.sparse import spdiags
311
+ >>> from scipy.sparse.linalg import LinearOperator, aslinearoperator
312
+ >>> from scipy.sparse.linalg import lobpcg
313
+
314
+ The square matrix size is
315
+
316
+ >>> n = 100
317
+
318
+ and its diagonal entries are 1, ..., 100 defined by
319
+
320
+ >>> vals = np.arange(1, n + 1).astype(np.int16)
321
+
322
+ The first mandatory input parameter in this test is
323
+ the sparse diagonal matrix `A`
324
+ of the eigenvalue problem ``A x = lambda x`` to solve.
325
+
326
+ >>> A = spdiags(vals, 0, n, n)
327
+ >>> A = A.astype(np.int16)
328
+ >>> A.toarray()
329
+ array([[ 1, 0, 0, ..., 0, 0, 0],
330
+ [ 0, 2, 0, ..., 0, 0, 0],
331
+ [ 0, 0, 3, ..., 0, 0, 0],
332
+ ...,
333
+ [ 0, 0, 0, ..., 98, 0, 0],
334
+ [ 0, 0, 0, ..., 0, 99, 0],
335
+ [ 0, 0, 0, ..., 0, 0, 100]], shape=(100, 100), dtype=int16)
336
+
337
+ The second mandatory input parameter `X` is a 2D array with the
338
+ row dimension determining the number of requested eigenvalues.
339
+ `X` is an initial guess for targeted eigenvectors.
340
+ `X` must have linearly independent columns.
341
+ If no initial approximations available, randomly oriented vectors
342
+ commonly work best, e.g., with components normally distributed
343
+ around zero or uniformly distributed on the interval [-1 1].
344
+ Setting the initial approximations to dtype ``np.float32``
345
+ forces all iterative values to dtype ``np.float32`` speeding up
346
+ the run while still allowing accurate eigenvalue computations.
347
+
348
+ >>> k = 1
349
+ >>> rng = np.random.default_rng()
350
+ >>> X = rng.normal(size=(n, k))
351
+ >>> X = X.astype(np.float32)
352
+
353
+ >>> eigenvalues, _ = lobpcg(A, X, maxiter=60)
354
+ >>> eigenvalues
355
+ array([100.], dtype=float32)
356
+
357
+ `lobpcg` needs only access the matrix product with `A` rather
358
+ then the matrix itself. Since the matrix `A` is diagonal in
359
+ this example, one can write a function of the matrix product
360
+ ``A @ X`` using the diagonal values ``vals`` only, e.g., by
361
+ element-wise multiplication with broadcasting in the lambda-function
362
+
363
+ >>> A_lambda = lambda X: vals[:, np.newaxis] * X
364
+
365
+ or the regular function
366
+
367
+ >>> def A_matmat(X):
368
+ ... return vals[:, np.newaxis] * X
369
+
370
+ and use the handle to one of these callables as an input
371
+
372
+ >>> eigenvalues, _ = lobpcg(A_lambda, X, maxiter=60)
373
+ >>> eigenvalues
374
+ array([100.], dtype=float32)
375
+ >>> eigenvalues, _ = lobpcg(A_matmat, X, maxiter=60)
376
+ >>> eigenvalues
377
+ array([100.], dtype=float32)
378
+
379
+ The traditional callable `LinearOperator` is no longer
380
+ necessary but still supported as the input to `lobpcg`.
381
+ Specifying ``matmat=A_matmat`` explicitly improves performance.
382
+
383
+ >>> A_lo = LinearOperator((n, n), matvec=A_matmat, matmat=A_matmat, dtype=np.int16)
384
+ >>> eigenvalues, _ = lobpcg(A_lo, X, maxiter=80)
385
+ >>> eigenvalues
386
+ array([100.], dtype=float32)
387
+
388
+ The least efficient callable option is `aslinearoperator`:
389
+
390
+ >>> eigenvalues, _ = lobpcg(aslinearoperator(A), X, maxiter=80)
391
+ >>> eigenvalues
392
+ array([100.], dtype=float32)
393
+
394
+ We now switch to computing the three smallest eigenvalues specifying
395
+
396
+ >>> k = 3
397
+ >>> X = np.random.default_rng().normal(size=(n, k))
398
+
399
+ and ``largest=False`` parameter
400
+
401
+ >>> eigenvalues, _ = lobpcg(A, X, largest=False, maxiter=90)
402
+ >>> print(eigenvalues)
403
+ [1. 2. 3.]
404
+
405
+ The next example illustrates computing 3 smallest eigenvalues of
406
+ the same matrix `A` given by the function handle ``A_matmat`` but
407
+ with constraints and preconditioning.
408
+
409
+ Constraints - an optional input parameter is a 2D array comprising
410
+ of column vectors that the eigenvectors must be orthogonal to
411
+
412
+ >>> Y = np.eye(n, 3)
413
+
414
+ The preconditioner acts as the inverse of `A` in this example, but
415
+ in the reduced precision ``np.float32`` even though the initial `X`
416
+ and thus all iterates and the output are in full ``np.float64``.
417
+
418
+ >>> inv_vals = 1./vals
419
+ >>> inv_vals = inv_vals.astype(np.float32)
420
+ >>> M = lambda X: inv_vals[:, np.newaxis] * X
421
+
422
+ Let us now solve the eigenvalue problem for the matrix `A` first
423
+ without preconditioning requesting 80 iterations
424
+
425
+ >>> eigenvalues, _ = lobpcg(A_matmat, X, Y=Y, largest=False, maxiter=80)
426
+ >>> eigenvalues
427
+ array([4., 5., 6.])
428
+ >>> eigenvalues.dtype
429
+ dtype('float64')
430
+
431
+ With preconditioning we need only 20 iterations from the same `X`
432
+
433
+ >>> eigenvalues, _ = lobpcg(A_matmat, X, Y=Y, M=M, largest=False, maxiter=20)
434
+ >>> eigenvalues
435
+ array([4., 5., 6.])
436
+
437
+ Note that the vectors passed in `Y` are the eigenvectors of the 3
438
+ smallest eigenvalues. The results returned above are orthogonal to those.
439
+
440
+ The primary matrix `A` may be indefinite, e.g., after shifting
441
+ ``vals`` by 50 from 1, ..., 100 to -49, ..., 50, we still can compute
442
+ the 3 smallest or largest eigenvalues.
443
+
444
+ >>> vals = vals - 50
445
+ >>> X = rng.normal(size=(n, k))
446
+ >>> eigenvalues, _ = lobpcg(A_matmat, X, largest=False, maxiter=99)
447
+ >>> eigenvalues
448
+ array([-49., -48., -47.])
449
+ >>> eigenvalues, _ = lobpcg(A_matmat, X, largest=True, maxiter=99)
450
+ >>> eigenvalues
451
+ array([50., 49., 48.])
452
+
453
+ """
454
+ blockVectorX = X
455
+ bestblockVectorX = blockVectorX
456
+ blockVectorY = Y
457
+ residualTolerance = tol
458
+ if maxiter is None:
459
+ maxiter = 20
460
+
461
+ bestIterationNumber = maxiter
462
+
463
+ sizeY = 0
464
+ if blockVectorY is not None:
465
+ if len(blockVectorY.shape) != 2:
466
+ warnings.warn(
467
+ f"Expected rank-2 array for argument Y, instead got "
468
+ f"{len(blockVectorY.shape)}, "
469
+ f"so ignore it and use no constraints.",
470
+ UserWarning, stacklevel=2
471
+ )
472
+ blockVectorY = None
473
+ else:
474
+ sizeY = blockVectorY.shape[1]
475
+
476
+ # Block size.
477
+ if blockVectorX is None:
478
+ raise ValueError("The mandatory initial matrix X cannot be None")
479
+ if len(blockVectorX.shape) != 2:
480
+ raise ValueError("expected rank-2 array for argument X")
481
+
482
+ n, sizeX = blockVectorX.shape
483
+
484
+ # Data type of iterates, determined by X, must be inexact
485
+ if not np.issubdtype(blockVectorX.dtype, np.inexact):
486
+ warnings.warn(
487
+ f"Data type for argument X is {blockVectorX.dtype}, "
488
+ f"which is not inexact, so casted to np.float32.",
489
+ UserWarning, stacklevel=2
490
+ )
491
+ blockVectorX = np.asarray(blockVectorX, dtype=np.float32)
492
+
493
+ if retLambdaHistory:
494
+ lambdaHistory = np.zeros((maxiter + 3, sizeX),
495
+ dtype=blockVectorX.dtype)
496
+ if retResidualNormsHistory:
497
+ residualNormsHistory = np.zeros((maxiter + 3, sizeX),
498
+ dtype=blockVectorX.dtype)
499
+
500
+ if verbosityLevel:
501
+ aux = "Solving "
502
+ if B is None:
503
+ aux += "standard"
504
+ else:
505
+ aux += "generalized"
506
+ aux += " eigenvalue problem with"
507
+ if M is None:
508
+ aux += "out"
509
+ aux += " preconditioning\n\n"
510
+ aux += "matrix size %d\n" % n
511
+ aux += "block size %d\n\n" % sizeX
512
+ if blockVectorY is None:
513
+ aux += "No constraints\n\n"
514
+ else:
515
+ if sizeY > 1:
516
+ aux += "%d constraints\n\n" % sizeY
517
+ else:
518
+ aux += "%d constraint\n\n" % sizeY
519
+ print(aux)
520
+
521
+ if (n - sizeY) < (5 * sizeX):
522
+ warnings.warn(
523
+ f"The problem size {n} minus the constraints size {sizeY} "
524
+ f"is too small relative to the block size {sizeX}. "
525
+ f"Using a dense eigensolver instead of LOBPCG iterations."
526
+ f"No output of the history of the iterations.",
527
+ UserWarning, stacklevel=2
528
+ )
529
+
530
+ sizeX = min(sizeX, n)
531
+
532
+ if blockVectorY is not None:
533
+ raise NotImplementedError(
534
+ "The dense eigensolver does not support constraints."
535
+ )
536
+
537
+ # Define the closed range of indices of eigenvalues to return.
538
+ if largest:
539
+ eigvals = (n - sizeX, n - 1)
540
+ else:
541
+ eigvals = (0, sizeX - 1)
542
+
543
+ try:
544
+ if isinstance(A, LinearOperator):
545
+ A = A(np.eye(n, dtype=int))
546
+ elif callable(A):
547
+ A = A(np.eye(n, dtype=int))
548
+ if A.shape != (n, n):
549
+ raise ValueError(
550
+ f"The shape {A.shape} of the primary matrix\n"
551
+ f"defined by a callable object is wrong.\n"
552
+ )
553
+ elif issparse(A):
554
+ A = A.toarray()
555
+ else:
556
+ A = np.asarray(A)
557
+ except Exception as e:
558
+ raise Exception(
559
+ f"Primary MatMul call failed with error\n"
560
+ f"{e}\n")
561
+
562
+ if B is not None:
563
+ try:
564
+ if isinstance(B, LinearOperator):
565
+ B = B(np.eye(n, dtype=int))
566
+ elif callable(B):
567
+ B = B(np.eye(n, dtype=int))
568
+ if B.shape != (n, n):
569
+ raise ValueError(
570
+ f"The shape {B.shape} of the secondary matrix\n"
571
+ f"defined by a callable object is wrong.\n"
572
+ )
573
+ elif issparse(B):
574
+ B = B.toarray()
575
+ else:
576
+ B = np.asarray(B)
577
+ except Exception as e:
578
+ raise Exception(
579
+ f"Secondary MatMul call failed with error\n"
580
+ f"{e}\n")
581
+
582
+ try:
583
+ vals, vecs = eigh(A,
584
+ B,
585
+ subset_by_index=eigvals,
586
+ check_finite=False)
587
+ if largest:
588
+ # Reverse order to be compatible with eigs() in 'LM' mode.
589
+ vals = vals[::-1]
590
+ vecs = vecs[:, ::-1]
591
+
592
+ return vals, vecs
593
+ except Exception as e:
594
+ raise Exception(
595
+ f"Dense eigensolver failed with error\n"
596
+ f"{e}\n"
597
+ )
598
+
599
+ if (residualTolerance is None) or (residualTolerance <= 0.0):
600
+ residualTolerance = np.sqrt(np.finfo(blockVectorX.dtype).eps) * n
601
+
602
+ A = _makeMatMat(A)
603
+ B = _makeMatMat(B)
604
+ M = _makeMatMat(M)
605
+
606
+ # Apply constraints to X.
607
+ if blockVectorY is not None:
608
+
609
+ if B is not None:
610
+ blockVectorBY = B(blockVectorY)
611
+ if blockVectorBY.shape != blockVectorY.shape:
612
+ raise ValueError(
613
+ f"The shape {blockVectorY.shape} "
614
+ f"of the constraint not preserved\n"
615
+ f"and changed to {blockVectorBY.shape} "
616
+ f"after multiplying by the secondary matrix.\n"
617
+ )
618
+ else:
619
+ blockVectorBY = blockVectorY
620
+
621
+ # gramYBY is a dense array.
622
+ gramYBY = blockVectorY.T.conj() @ blockVectorBY
623
+ try:
624
+ # gramYBY is a Cholesky factor from now on...
625
+ gramYBY = cho_factor(gramYBY, overwrite_a=True)
626
+ except LinAlgError as e:
627
+ raise ValueError("Linearly dependent constraints") from e
628
+
629
+ _applyConstraints(blockVectorX, gramYBY, blockVectorBY, blockVectorY)
630
+
631
+ ##
632
+ # B-orthonormalize X.
633
+ blockVectorX, blockVectorBX, _ = _b_orthonormalize(
634
+ B, blockVectorX, verbosityLevel=verbosityLevel)
635
+ if blockVectorX is None:
636
+ raise ValueError("Linearly dependent initial approximations")
637
+
638
+ ##
639
+ # Compute the initial Ritz vectors: solve the eigenproblem.
640
+ blockVectorAX = A(blockVectorX)
641
+ if blockVectorAX.shape != blockVectorX.shape:
642
+ raise ValueError(
643
+ f"The shape {blockVectorX.shape} "
644
+ f"of the initial approximations not preserved\n"
645
+ f"and changed to {blockVectorAX.shape} "
646
+ f"after multiplying by the primary matrix.\n"
647
+ )
648
+
649
+ gramXAX = blockVectorX.T.conj() @ blockVectorAX
650
+
651
+ _lambda, eigBlockVector = eigh(gramXAX, check_finite=False)
652
+ ii = _get_indx(_lambda, sizeX, largest)
653
+ _lambda = _lambda[ii]
654
+ if retLambdaHistory:
655
+ lambdaHistory[0, :] = _lambda
656
+
657
+ eigBlockVector = np.asarray(eigBlockVector[:, ii])
658
+ blockVectorX = _matmul_inplace(
659
+ blockVectorX, eigBlockVector,
660
+ verbosityLevel=verbosityLevel
661
+ )
662
+ blockVectorAX = _matmul_inplace(
663
+ blockVectorAX, eigBlockVector,
664
+ verbosityLevel=verbosityLevel
665
+ )
666
+ if B is not None:
667
+ blockVectorBX = _matmul_inplace(
668
+ blockVectorBX, eigBlockVector,
669
+ verbosityLevel=verbosityLevel
670
+ )
671
+
672
+ ##
673
+ # Active index set.
674
+ activeMask = np.ones((sizeX,), dtype=bool)
675
+
676
+ ##
677
+ # Main iteration loop.
678
+
679
+ blockVectorP = None # set during iteration
680
+ blockVectorAP = None
681
+ blockVectorBP = None
682
+
683
+ smallestResidualNorm = np.abs(np.finfo(blockVectorX.dtype).max)
684
+
685
+ iterationNumber = -1
686
+ restart = True
687
+ forcedRestart = False
688
+ explicitGramFlag = False
689
+ while iterationNumber < maxiter:
690
+ iterationNumber += 1
691
+
692
+ if B is not None:
693
+ aux = blockVectorBX * _lambda[np.newaxis, :]
694
+ else:
695
+ aux = blockVectorX * _lambda[np.newaxis, :]
696
+
697
+ blockVectorR = blockVectorAX - aux
698
+
699
+ aux = np.sum(blockVectorR.conj() * blockVectorR, 0)
700
+ residualNorms = np.sqrt(np.abs(aux))
701
+ if retResidualNormsHistory:
702
+ residualNormsHistory[iterationNumber, :] = residualNorms
703
+ residualNorm = np.sum(np.abs(residualNorms)) / sizeX
704
+
705
+ if residualNorm < smallestResidualNorm:
706
+ smallestResidualNorm = residualNorm
707
+ bestIterationNumber = iterationNumber
708
+ bestblockVectorX = blockVectorX
709
+ elif residualNorm > 2**restartControl * smallestResidualNorm:
710
+ forcedRestart = True
711
+ blockVectorAX = A(blockVectorX)
712
+ if blockVectorAX.shape != blockVectorX.shape:
713
+ raise ValueError(
714
+ f"The shape {blockVectorX.shape} "
715
+ f"of the restarted iterate not preserved\n"
716
+ f"and changed to {blockVectorAX.shape} "
717
+ f"after multiplying by the primary matrix.\n"
718
+ )
719
+ if B is not None:
720
+ blockVectorBX = B(blockVectorX)
721
+ if blockVectorBX.shape != blockVectorX.shape:
722
+ raise ValueError(
723
+ f"The shape {blockVectorX.shape} "
724
+ f"of the restarted iterate not preserved\n"
725
+ f"and changed to {blockVectorBX.shape} "
726
+ f"after multiplying by the secondary matrix.\n"
727
+ )
728
+
729
+ ii = np.where(residualNorms > residualTolerance, True, False)
730
+ activeMask = activeMask & ii
731
+ currentBlockSize = activeMask.sum()
732
+
733
+ if verbosityLevel:
734
+ print(f"iteration {iterationNumber}")
735
+ print(f"current block size: {currentBlockSize}")
736
+ print(f"eigenvalue(s):\n{_lambda}")
737
+ print(f"residual norm(s):\n{residualNorms}")
738
+
739
+ if currentBlockSize == 0:
740
+ break
741
+
742
+ activeBlockVectorR = _as2d(blockVectorR[:, activeMask])
743
+
744
+ if iterationNumber > 0:
745
+ activeBlockVectorP = _as2d(blockVectorP[:, activeMask])
746
+ activeBlockVectorAP = _as2d(blockVectorAP[:, activeMask])
747
+ if B is not None:
748
+ activeBlockVectorBP = _as2d(blockVectorBP[:, activeMask])
749
+
750
+ if M is not None:
751
+ # Apply preconditioner T to the active residuals.
752
+ activeBlockVectorR = M(activeBlockVectorR)
753
+
754
+ ##
755
+ # Apply constraints to the preconditioned residuals.
756
+ if blockVectorY is not None:
757
+ _applyConstraints(activeBlockVectorR,
758
+ gramYBY,
759
+ blockVectorBY,
760
+ blockVectorY)
761
+
762
+ ##
763
+ # B-orthogonalize the preconditioned residuals to X.
764
+ if B is not None:
765
+ activeBlockVectorR = activeBlockVectorR - (
766
+ blockVectorX @
767
+ (blockVectorBX.T.conj() @ activeBlockVectorR)
768
+ )
769
+ else:
770
+ activeBlockVectorR = activeBlockVectorR - (
771
+ blockVectorX @
772
+ (blockVectorX.T.conj() @ activeBlockVectorR)
773
+ )
774
+
775
+ ##
776
+ # B-orthonormalize the preconditioned residuals.
777
+ aux = _b_orthonormalize(
778
+ B, activeBlockVectorR, verbosityLevel=verbosityLevel)
779
+ activeBlockVectorR, activeBlockVectorBR, _ = aux
780
+
781
+ if activeBlockVectorR is None:
782
+ warnings.warn(
783
+ f"Failed at iteration {iterationNumber} with accuracies "
784
+ f"{residualNorms}\n not reaching the requested "
785
+ f"tolerance {residualTolerance}.",
786
+ UserWarning, stacklevel=2
787
+ )
788
+ break
789
+ activeBlockVectorAR = A(activeBlockVectorR)
790
+
791
+ if iterationNumber > 0:
792
+ if B is not None:
793
+ aux = _b_orthonormalize(
794
+ B, activeBlockVectorP, activeBlockVectorBP,
795
+ verbosityLevel=verbosityLevel
796
+ )
797
+ activeBlockVectorP, activeBlockVectorBP, invR = aux
798
+ else:
799
+ aux = _b_orthonormalize(B, activeBlockVectorP,
800
+ verbosityLevel=verbosityLevel)
801
+ activeBlockVectorP, _, invR = aux
802
+ # Function _b_orthonormalize returns None if Cholesky fails
803
+ if activeBlockVectorP is not None:
804
+ activeBlockVectorAP = _matmul_inplace(
805
+ activeBlockVectorAP, invR,
806
+ verbosityLevel=verbosityLevel
807
+ )
808
+ restart = forcedRestart
809
+ else:
810
+ restart = True
811
+
812
+ ##
813
+ # Perform the Rayleigh Ritz Procedure:
814
+ # Compute symmetric Gram matrices:
815
+
816
+ if activeBlockVectorAR.dtype == "float32":
817
+ myeps = 1
818
+ else:
819
+ myeps = np.sqrt(np.finfo(activeBlockVectorR.dtype).eps)
820
+
821
+ if residualNorms.max() > myeps and not explicitGramFlag:
822
+ explicitGramFlag = False
823
+ else:
824
+ # Once explicitGramFlag, forever explicitGramFlag.
825
+ explicitGramFlag = True
826
+
827
+ # Shared memory assignments to simplify the code
828
+ if B is None:
829
+ blockVectorBX = blockVectorX
830
+ activeBlockVectorBR = activeBlockVectorR
831
+ if not restart:
832
+ activeBlockVectorBP = activeBlockVectorP
833
+
834
+ # Common submatrices:
835
+ gramXAR = np.dot(blockVectorX.T.conj(), activeBlockVectorAR)
836
+ gramRAR = np.dot(activeBlockVectorR.T.conj(), activeBlockVectorAR)
837
+
838
+ gramDtype = activeBlockVectorAR.dtype
839
+ if explicitGramFlag:
840
+ gramRAR = (gramRAR + gramRAR.T.conj()) / 2
841
+ gramXAX = np.dot(blockVectorX.T.conj(), blockVectorAX)
842
+ gramXAX = (gramXAX + gramXAX.T.conj()) / 2
843
+ gramXBX = np.dot(blockVectorX.T.conj(), blockVectorBX)
844
+ gramRBR = np.dot(activeBlockVectorR.T.conj(), activeBlockVectorBR)
845
+ gramXBR = np.dot(blockVectorX.T.conj(), activeBlockVectorBR)
846
+ else:
847
+ gramXAX = np.diag(_lambda).astype(gramDtype)
848
+ gramXBX = np.eye(sizeX, dtype=gramDtype)
849
+ gramRBR = np.eye(currentBlockSize, dtype=gramDtype)
850
+ gramXBR = np.zeros((sizeX, currentBlockSize), dtype=gramDtype)
851
+
852
+ if not restart:
853
+ gramXAP = np.dot(blockVectorX.T.conj(), activeBlockVectorAP)
854
+ gramRAP = np.dot(activeBlockVectorR.T.conj(), activeBlockVectorAP)
855
+ gramPAP = np.dot(activeBlockVectorP.T.conj(), activeBlockVectorAP)
856
+ gramXBP = np.dot(blockVectorX.T.conj(), activeBlockVectorBP)
857
+ gramRBP = np.dot(activeBlockVectorR.T.conj(), activeBlockVectorBP)
858
+ if explicitGramFlag:
859
+ gramPAP = (gramPAP + gramPAP.T.conj()) / 2
860
+ gramPBP = np.dot(activeBlockVectorP.T.conj(),
861
+ activeBlockVectorBP)
862
+ else:
863
+ gramPBP = np.eye(currentBlockSize, dtype=gramDtype)
864
+
865
+ gramA = np.block(
866
+ [
867
+ [gramXAX, gramXAR, gramXAP],
868
+ [gramXAR.T.conj(), gramRAR, gramRAP],
869
+ [gramXAP.T.conj(), gramRAP.T.conj(), gramPAP],
870
+ ]
871
+ )
872
+ gramB = np.block(
873
+ [
874
+ [gramXBX, gramXBR, gramXBP],
875
+ [gramXBR.T.conj(), gramRBR, gramRBP],
876
+ [gramXBP.T.conj(), gramRBP.T.conj(), gramPBP],
877
+ ]
878
+ )
879
+
880
+ _handle_gramA_gramB_verbosity(gramA, gramB, verbosityLevel)
881
+
882
+ try:
883
+ _lambda, eigBlockVector = eigh(gramA,
884
+ gramB,
885
+ check_finite=False)
886
+ except LinAlgError as e:
887
+ # raise ValueError("eigh failed in lobpcg iterations") from e
888
+ if verbosityLevel:
889
+ warnings.warn(
890
+ f"eigh failed at iteration {iterationNumber} \n"
891
+ f"with error {e} causing a restart.\n",
892
+ UserWarning, stacklevel=2
893
+ )
894
+ # try again after dropping the direction vectors P from RR
895
+ restart = True
896
+
897
+ if restart:
898
+ gramA = np.block([[gramXAX, gramXAR], [gramXAR.T.conj(), gramRAR]])
899
+ gramB = np.block([[gramXBX, gramXBR], [gramXBR.T.conj(), gramRBR]])
900
+
901
+ _handle_gramA_gramB_verbosity(gramA, gramB, verbosityLevel)
902
+
903
+ try:
904
+ _lambda, eigBlockVector = eigh(gramA,
905
+ gramB,
906
+ check_finite=False)
907
+ except LinAlgError as e:
908
+ # raise ValueError("eigh failed in lobpcg iterations") from e
909
+ warnings.warn(
910
+ f"eigh failed at iteration {iterationNumber} with error\n"
911
+ f"{e}\n",
912
+ UserWarning, stacklevel=2
913
+ )
914
+ break
915
+
916
+ ii = _get_indx(_lambda, sizeX, largest)
917
+ _lambda = _lambda[ii]
918
+ eigBlockVector = eigBlockVector[:, ii]
919
+ if retLambdaHistory:
920
+ lambdaHistory[iterationNumber + 1, :] = _lambda
921
+
922
+ # Compute Ritz vectors.
923
+ if B is not None:
924
+ if not restart:
925
+ eigBlockVectorX = eigBlockVector[:sizeX]
926
+ eigBlockVectorR = eigBlockVector[sizeX:
927
+ sizeX + currentBlockSize]
928
+ eigBlockVectorP = eigBlockVector[sizeX + currentBlockSize:]
929
+
930
+ pp = np.dot(activeBlockVectorR, eigBlockVectorR)
931
+ pp += np.dot(activeBlockVectorP, eigBlockVectorP)
932
+
933
+ app = np.dot(activeBlockVectorAR, eigBlockVectorR)
934
+ app += np.dot(activeBlockVectorAP, eigBlockVectorP)
935
+
936
+ bpp = np.dot(activeBlockVectorBR, eigBlockVectorR)
937
+ bpp += np.dot(activeBlockVectorBP, eigBlockVectorP)
938
+ else:
939
+ eigBlockVectorX = eigBlockVector[:sizeX]
940
+ eigBlockVectorR = eigBlockVector[sizeX:]
941
+
942
+ pp = np.dot(activeBlockVectorR, eigBlockVectorR)
943
+ app = np.dot(activeBlockVectorAR, eigBlockVectorR)
944
+ bpp = np.dot(activeBlockVectorBR, eigBlockVectorR)
945
+
946
+ blockVectorX = np.dot(blockVectorX, eigBlockVectorX) + pp
947
+ blockVectorAX = np.dot(blockVectorAX, eigBlockVectorX) + app
948
+ blockVectorBX = np.dot(blockVectorBX, eigBlockVectorX) + bpp
949
+
950
+ blockVectorP, blockVectorAP, blockVectorBP = pp, app, bpp
951
+
952
+ else:
953
+ if not restart:
954
+ eigBlockVectorX = eigBlockVector[:sizeX]
955
+ eigBlockVectorR = eigBlockVector[sizeX:
956
+ sizeX + currentBlockSize]
957
+ eigBlockVectorP = eigBlockVector[sizeX + currentBlockSize:]
958
+
959
+ pp = np.dot(activeBlockVectorR, eigBlockVectorR)
960
+ pp += np.dot(activeBlockVectorP, eigBlockVectorP)
961
+
962
+ app = np.dot(activeBlockVectorAR, eigBlockVectorR)
963
+ app += np.dot(activeBlockVectorAP, eigBlockVectorP)
964
+ else:
965
+ eigBlockVectorX = eigBlockVector[:sizeX]
966
+ eigBlockVectorR = eigBlockVector[sizeX:]
967
+
968
+ pp = np.dot(activeBlockVectorR, eigBlockVectorR)
969
+ app = np.dot(activeBlockVectorAR, eigBlockVectorR)
970
+
971
+ blockVectorX = np.dot(blockVectorX, eigBlockVectorX) + pp
972
+ blockVectorAX = np.dot(blockVectorAX, eigBlockVectorX) + app
973
+
974
+ blockVectorP, blockVectorAP = pp, app
975
+
976
+ if B is not None:
977
+ aux = blockVectorBX * _lambda[np.newaxis, :]
978
+ else:
979
+ aux = blockVectorX * _lambda[np.newaxis, :]
980
+
981
+ blockVectorR = blockVectorAX - aux
982
+
983
+ aux = np.sum(blockVectorR.conj() * blockVectorR, 0)
984
+ residualNorms = np.sqrt(np.abs(aux))
985
+ # Use old lambda in case of early loop exit.
986
+ if retLambdaHistory:
987
+ lambdaHistory[iterationNumber + 1, :] = _lambda
988
+ if retResidualNormsHistory:
989
+ residualNormsHistory[iterationNumber + 1, :] = residualNorms
990
+ residualNorm = np.sum(np.abs(residualNorms)) / sizeX
991
+ if residualNorm < smallestResidualNorm:
992
+ smallestResidualNorm = residualNorm
993
+ bestIterationNumber = iterationNumber + 1
994
+ bestblockVectorX = blockVectorX
995
+
996
+ if np.max(np.abs(residualNorms)) > residualTolerance:
997
+ warnings.warn(
998
+ f"Exited at iteration {iterationNumber} with accuracies \n"
999
+ f"{residualNorms}\n"
1000
+ f"not reaching the requested tolerance {residualTolerance}.\n"
1001
+ f"Use iteration {bestIterationNumber} instead with accuracy \n"
1002
+ f"{smallestResidualNorm}.\n",
1003
+ UserWarning, stacklevel=2
1004
+ )
1005
+
1006
+ if verbosityLevel:
1007
+ print(f"Final iterative eigenvalue(s):\n{_lambda}")
1008
+ print(f"Final iterative residual norm(s):\n{residualNorms}")
1009
+
1010
+ blockVectorX = bestblockVectorX
1011
+ # Making eigenvectors "exactly" satisfy the blockVectorY constrains
1012
+ if blockVectorY is not None:
1013
+ _applyConstraints(blockVectorX,
1014
+ gramYBY,
1015
+ blockVectorBY,
1016
+ blockVectorY)
1017
+
1018
+ # Making eigenvectors "exactly" othonormalized by final "exact" RR
1019
+ blockVectorAX = A(blockVectorX)
1020
+ if blockVectorAX.shape != blockVectorX.shape:
1021
+ raise ValueError(
1022
+ f"The shape {blockVectorX.shape} "
1023
+ f"of the postprocessing iterate not preserved\n"
1024
+ f"and changed to {blockVectorAX.shape} "
1025
+ f"after multiplying by the primary matrix.\n"
1026
+ )
1027
+ gramXAX = np.dot(blockVectorX.T.conj(), blockVectorAX)
1028
+
1029
+ blockVectorBX = blockVectorX
1030
+ if B is not None:
1031
+ blockVectorBX = B(blockVectorX)
1032
+ if blockVectorBX.shape != blockVectorX.shape:
1033
+ raise ValueError(
1034
+ f"The shape {blockVectorX.shape} "
1035
+ f"of the postprocessing iterate not preserved\n"
1036
+ f"and changed to {blockVectorBX.shape} "
1037
+ f"after multiplying by the secondary matrix.\n"
1038
+ )
1039
+
1040
+ gramXBX = np.dot(blockVectorX.T.conj(), blockVectorBX)
1041
+ _handle_gramA_gramB_verbosity(gramXAX, gramXBX, verbosityLevel)
1042
+ gramXAX = (gramXAX + gramXAX.T.conj()) / 2
1043
+ gramXBX = (gramXBX + gramXBX.T.conj()) / 2
1044
+ try:
1045
+ _lambda, eigBlockVector = eigh(gramXAX,
1046
+ gramXBX,
1047
+ check_finite=False)
1048
+ except LinAlgError as e:
1049
+ raise ValueError("eigh has failed in lobpcg postprocessing") from e
1050
+
1051
+ ii = _get_indx(_lambda, sizeX, largest)
1052
+ _lambda = _lambda[ii]
1053
+ eigBlockVector = np.asarray(eigBlockVector[:, ii])
1054
+
1055
+ blockVectorX = np.dot(blockVectorX, eigBlockVector)
1056
+ blockVectorAX = np.dot(blockVectorAX, eigBlockVector)
1057
+
1058
+ if B is not None:
1059
+ blockVectorBX = np.dot(blockVectorBX, eigBlockVector)
1060
+ aux = blockVectorBX * _lambda[np.newaxis, :]
1061
+ else:
1062
+ aux = blockVectorX * _lambda[np.newaxis, :]
1063
+
1064
+ blockVectorR = blockVectorAX - aux
1065
+
1066
+ aux = np.sum(blockVectorR.conj() * blockVectorR, 0)
1067
+ residualNorms = np.sqrt(np.abs(aux))
1068
+
1069
+ if retLambdaHistory:
1070
+ lambdaHistory[bestIterationNumber + 1, :] = _lambda
1071
+ if retResidualNormsHistory:
1072
+ residualNormsHistory[bestIterationNumber + 1, :] = residualNorms
1073
+
1074
+ if retLambdaHistory:
1075
+ lambdaHistory = lambdaHistory[
1076
+ : bestIterationNumber + 2, :]
1077
+ if retResidualNormsHistory:
1078
+ residualNormsHistory = residualNormsHistory[
1079
+ : bestIterationNumber + 2, :]
1080
+
1081
+ if np.max(np.abs(residualNorms)) > residualTolerance:
1082
+ warnings.warn(
1083
+ f"Exited postprocessing with accuracies \n"
1084
+ f"{residualNorms}\n"
1085
+ f"not reaching the requested tolerance {residualTolerance}.",
1086
+ UserWarning, stacklevel=2
1087
+ )
1088
+
1089
+ if verbosityLevel:
1090
+ print(f"Final postprocessing eigenvalue(s):\n{_lambda}")
1091
+ print(f"Final residual norm(s):\n{residualNorms}")
1092
+
1093
+ if retLambdaHistory:
1094
+ lambdaHistory = np.vsplit(lambdaHistory, np.shape(lambdaHistory)[0])
1095
+ lambdaHistory = [np.squeeze(i) for i in lambdaHistory]
1096
+ if retResidualNormsHistory:
1097
+ residualNormsHistory = np.vsplit(residualNormsHistory,
1098
+ np.shape(residualNormsHistory)[0])
1099
+ residualNormsHistory = [np.squeeze(i) for i in residualNormsHistory]
1100
+
1101
+ if retLambdaHistory:
1102
+ if retResidualNormsHistory:
1103
+ return _lambda, blockVectorX, lambdaHistory, residualNormsHistory
1104
+ else:
1105
+ return _lambda, blockVectorX, lambdaHistory
1106
+ else:
1107
+ if retResidualNormsHistory:
1108
+ return _lambda, blockVectorX, residualNormsHistory
1109
+ else:
1110
+ return _lambda, blockVectorX
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/lobpcg/tests/__init__.py ADDED
File without changes
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/lobpcg/tests/test_lobpcg.py ADDED
@@ -0,0 +1,725 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Test functions for the sparse.linalg._eigen.lobpcg module
2
+ """
3
+
4
+ import itertools
5
+ import platform
6
+ import sys
7
+ import pytest
8
+ import numpy as np
9
+ from numpy import ones, r_, diag
10
+ from numpy.testing import (assert_almost_equal, assert_equal,
11
+ assert_allclose, assert_array_less)
12
+
13
+ from scipy import sparse
14
+ from scipy.linalg import (eigh, toeplitz,
15
+ cholesky_banded, cho_solve_banded)
16
+ from scipy.sparse import dia_array, eye_array, csr_array
17
+ from scipy.sparse.linalg import eigsh, LinearOperator
18
+ from scipy.sparse.linalg._eigen.lobpcg import lobpcg
19
+ from scipy.sparse.linalg._eigen.lobpcg.lobpcg import _b_orthonormalize
20
+ from scipy._lib._util import np_long, np_ulong
21
+ from scipy.sparse.linalg._special_sparse_arrays import (Sakurai,
22
+ MikotaPair)
23
+
24
+ _IS_32BIT = (sys.maxsize < 2**32)
25
+
26
+ INT_DTYPES = (np.intc, np_long, np.longlong, np.uintc, np_ulong, np.ulonglong)
27
+ # np.half is unsupported on many test systems so excluded
28
+ REAL_DTYPES = (np.float32, np.float64, np.longdouble)
29
+ COMPLEX_DTYPES = (np.complex64, np.complex128, np.clongdouble)
30
+ INEXACTDTYPES = REAL_DTYPES + COMPLEX_DTYPES
31
+ ALLDTYPES = INT_DTYPES + INEXACTDTYPES
32
+
33
+
34
+ def sign_align(A, B):
35
+ """Align signs of columns of A match those of B: column-wise remove
36
+ sign of A by multiplying with its sign then multiply in sign of B.
37
+ """
38
+ return np.array([col_A * np.sign(col_A[0]) * np.sign(col_B[0])
39
+ for col_A, col_B in zip(A.T, B.T)]).T
40
+
41
+ def ElasticRod(n):
42
+ """Build the matrices for the generalized eigenvalue problem of the
43
+ fixed-free elastic rod vibration model.
44
+ """
45
+ L = 1.0
46
+ le = L/n
47
+ rho = 7.85e3
48
+ S = 1.e-4
49
+ E = 2.1e11
50
+ mass = rho*S*le/6.
51
+ k = E*S/le
52
+ A = k*(diag(r_[2.*ones(n-1), 1])-diag(ones(n-1), 1)-diag(ones(n-1), -1))
53
+ B = mass*(diag(r_[4.*ones(n-1), 2])+diag(ones(n-1), 1)+diag(ones(n-1), -1))
54
+ return A, B
55
+
56
+
57
+ @pytest.mark.filterwarnings("ignore:The problem size")
58
+ @pytest.mark.parametrize("n", [10, 20])
59
+ @pytest.mark.filterwarnings("ignore:Exited at iteration")
60
+ @pytest.mark.filterwarnings("ignore:Exited postprocessing")
61
+ def test_ElasticRod(n):
62
+ """Check eigh vs. lobpcg consistency for elastic rod model.
63
+ """
64
+ A, B = ElasticRod(n)
65
+ m = 2
66
+ rnd = np.random.RandomState(0)
67
+ X = rnd.standard_normal((n, m))
68
+ eigvals, _ = lobpcg(A, X, B=B, tol=1e-2, maxiter=50, largest=False)
69
+ eigvals.sort()
70
+ w, _ = eigh(A, b=B)
71
+ w.sort()
72
+ assert_almost_equal(w[:int(m/2)], eigvals[:int(m/2)], decimal=2)
73
+
74
+
75
+ @pytest.mark.parametrize("n", [50])
76
+ @pytest.mark.parametrize("m", [1, 2, 10])
77
+ @pytest.mark.filterwarnings("ignore:Casting complex values to real")
78
+ @pytest.mark.parametrize("Vdtype", INEXACTDTYPES)
79
+ @pytest.mark.parametrize("Bdtype", ALLDTYPES)
80
+ @pytest.mark.parametrize("BVdtype", INEXACTDTYPES)
81
+ def test_b_orthonormalize(n, m, Vdtype, Bdtype, BVdtype):
82
+ """Test B-orthonormalization by Cholesky with callable 'B'.
83
+ The function '_b_orthonormalize' is key in LOBPCG but may
84
+ lead to numerical instabilities. The input vectors are often
85
+ badly scaled, so the function needs scale-invariant Cholesky;
86
+ see https://netlib.org/lapack/lawnspdf/lawn14.pdf.
87
+ """
88
+ rnd = np.random.RandomState(0)
89
+ X = rnd.standard_normal((n, m)).astype(Vdtype)
90
+ Xcopy = np.copy(X)
91
+ vals = np.arange(1, n+1, dtype=float)
92
+ B = dia_array(([vals], [0]), shape=(n, n)).astype(Bdtype)
93
+ BX = B @ X
94
+ BX = BX.astype(BVdtype)
95
+ is_all_complex = (np.issubdtype(Vdtype, np.complexfloating) and
96
+ np.issubdtype(BVdtype, np.complexfloating))
97
+ is_all_notcomplex = (not np.issubdtype(Vdtype, np.complexfloating) and
98
+ not np.issubdtype(Bdtype, np.complexfloating) and
99
+ not np.issubdtype(BVdtype, np.complexfloating))
100
+
101
+ # All complex or all not complex can calculate in-place
102
+ check_inplace = is_all_complex or is_all_notcomplex
103
+ # np.longdouble tol cannot be achieved on most systems
104
+ atol = m * n * max(np.finfo(Vdtype).eps,
105
+ np.finfo(BVdtype).eps,
106
+ np.finfo(np.float64).eps)
107
+
108
+ Xo, BXo, _ = _b_orthonormalize(lambda v: B @ v, X, BX)
109
+ if check_inplace:
110
+ # Check in-place
111
+ assert_equal(X, Xo)
112
+ assert_equal(id(X), id(Xo))
113
+ assert_equal(BX, BXo)
114
+ assert_equal(id(BX), id(BXo))
115
+ # Check BXo
116
+ assert_allclose(B @ Xo, BXo, atol=atol, rtol=atol)
117
+ # Check B-orthonormality
118
+ assert_allclose(Xo.T.conj() @ B @ Xo, np.identity(m),
119
+ atol=atol, rtol=atol)
120
+ # Repeat without BX in outputs
121
+ X = np.copy(Xcopy)
122
+ Xo1, BXo1, _ = _b_orthonormalize(lambda v: B @ v, X)
123
+ assert_allclose(Xo, Xo1, atol=atol, rtol=atol)
124
+ assert_allclose(BXo, BXo1, atol=atol, rtol=atol)
125
+ if check_inplace:
126
+ # Check in-place.
127
+ assert_equal(X, Xo1)
128
+ assert_equal(id(X), id(Xo1))
129
+ # Check BXo1
130
+ assert_allclose(B @ Xo1, BXo1, atol=atol, rtol=atol)
131
+
132
+ # Introduce column-scaling in X
133
+ scaling = 1.0 / np.geomspace(10, 1e10, num=m)
134
+ X = Xcopy * scaling
135
+ X = X.astype(Vdtype)
136
+ BX = B @ X
137
+ BX = BX.astype(BVdtype)
138
+ # Check scaling-invariance of Cholesky-based orthonormalization
139
+ Xo1, BXo1, _ = _b_orthonormalize(lambda v: B @ v, X, BX)
140
+ # The output should be the same, up the signs of the columns
141
+ Xo1 = sign_align(Xo1, Xo)
142
+ assert_allclose(Xo, Xo1, atol=atol, rtol=atol)
143
+ BXo1 = sign_align(BXo1, BXo)
144
+ assert_allclose(BXo, BXo1, atol=atol, rtol=atol)
145
+
146
+
147
+ @pytest.mark.thread_unsafe
148
+ @pytest.mark.filterwarnings("ignore:Exited at iteration 0")
149
+ @pytest.mark.filterwarnings("ignore:Exited postprocessing")
150
+ def test_nonhermitian_warning(capsys):
151
+ """Check the warning of a Ritz matrix being not Hermitian
152
+ by feeding a non-Hermitian input matrix.
153
+ Also check stdout since verbosityLevel=1 and lack of stderr.
154
+ """
155
+ n = 10
156
+ X = np.arange(n * 2).reshape(n, 2).astype(np.float32)
157
+ A = np.arange(n * n).reshape(n, n).astype(np.float32)
158
+ with pytest.warns(UserWarning, match="Matrix gramA"):
159
+ _, _ = lobpcg(A, X, verbosityLevel=1, maxiter=0)
160
+ out, err = capsys.readouterr() # Capture output
161
+ assert out.startswith("Solving standard eigenvalue") # Test stdout
162
+ assert err == '' # Test empty stderr
163
+ # Make the matrix symmetric and the UserWarning disappears.
164
+ A += A.T
165
+ _, _ = lobpcg(A, X, verbosityLevel=1, maxiter=0)
166
+ out, err = capsys.readouterr() # Capture output
167
+ assert out.startswith("Solving standard eigenvalue") # Test stdout
168
+ assert err == '' # Test empty stderr
169
+
170
+
171
+ def test_regression():
172
+ """Check the eigenvalue of the identity matrix is one.
173
+ """
174
+ # https://mail.python.org/pipermail/scipy-user/2010-October/026944.html
175
+ n = 10
176
+ X = np.ones((n, 1))
177
+ A = np.identity(n)
178
+ w, _ = lobpcg(A, X)
179
+ assert_allclose(w, [1])
180
+
181
+
182
+ @pytest.mark.filterwarnings("ignore:The problem size")
183
+ @pytest.mark.parametrize('n, m, m_excluded', [(30, 4, 3), (4, 2, 0)])
184
+ def test_diagonal(n, m, m_excluded):
185
+ """Test ``m - m_excluded`` eigenvalues and eigenvectors of
186
+ diagonal matrices of the size ``n`` varying matrix formats:
187
+ dense array, spare matrix, and ``LinearOperator`` for both
188
+ matrixes in the generalized eigenvalue problem ``Av = cBv``
189
+ and for the preconditioner.
190
+ """
191
+ rnd = np.random.RandomState(0)
192
+
193
+ # Define the generalized eigenvalue problem Av = cBv
194
+ # where (c, v) is a generalized eigenpair,
195
+ # A is the diagonal matrix whose entries are 1,...n,
196
+ # B is the identity matrix.
197
+ vals = np.arange(1, n+1, dtype=float)
198
+ A_s = dia_array(([vals], [0]), shape=(n, n))
199
+ A_a = A_s.toarray()
200
+
201
+ def A_f(x):
202
+ return A_s @ x
203
+
204
+ A_lo = LinearOperator(matvec=A_f,
205
+ matmat=A_f,
206
+ shape=(n, n), dtype=float)
207
+
208
+ B_a = eye_array(n)
209
+ B_s = csr_array(B_a)
210
+
211
+ def B_f(x):
212
+ return B_a @ x
213
+
214
+ B_lo = LinearOperator(matvec=B_f,
215
+ matmat=B_f,
216
+ shape=(n, n), dtype=float)
217
+
218
+ # Let the preconditioner M be the inverse of A.
219
+ M_s = dia_array(([1./vals], [0]), shape=(n, n))
220
+ M_a = M_s.toarray()
221
+
222
+ def M_f(x):
223
+ return M_s @ x
224
+
225
+ M_lo = LinearOperator(matvec=M_f,
226
+ matmat=M_f,
227
+ shape=(n, n), dtype=float)
228
+
229
+ # Pick random initial vectors.
230
+ X = rnd.normal(size=(n, m))
231
+
232
+ # Require that the returned eigenvectors be in the orthogonal complement
233
+ # of the first few standard basis vectors.
234
+ if m_excluded > 0:
235
+ Y = np.eye(n, m_excluded)
236
+ else:
237
+ Y = None
238
+
239
+ for A in [A_a, A_s, A_lo]:
240
+ for B in [B_a, B_s, B_lo]:
241
+ for M in [M_a, M_s, M_lo]:
242
+ eigvals, vecs = lobpcg(A, X, B, M=M, Y=Y,
243
+ maxiter=40, largest=False)
244
+
245
+ assert_allclose(eigvals, np.arange(1+m_excluded,
246
+ 1+m_excluded+m))
247
+ _check_eigen(A, eigvals, vecs, rtol=1e-3, atol=1e-3)
248
+
249
+
250
+ def _check_eigen(M, w, V, rtol=1e-8, atol=1e-14):
251
+ """Check if the eigenvalue residual is small.
252
+ """
253
+ mult_wV = np.multiply(w, V)
254
+ dot_MV = M.dot(V)
255
+ assert_allclose(mult_wV, dot_MV, rtol=rtol, atol=atol)
256
+
257
+
258
+ def _check_fiedler(n, p):
259
+ """Check the Fiedler vector computation.
260
+ """
261
+ # This is not necessarily the recommended way to find the Fiedler vector.
262
+ col = np.zeros(n)
263
+ col[1] = 1
264
+ A = toeplitz(col)
265
+ D = np.diag(A.sum(axis=1))
266
+ L = D - A
267
+ # Compute the full eigendecomposition using tricks, e.g.
268
+ # http://www.cs.yale.edu/homes/spielman/561/2009/lect02-09.pdf
269
+ tmp = np.pi * np.arange(n) / n
270
+ analytic_w = 2 * (1 - np.cos(tmp))
271
+ analytic_V = np.cos(np.outer(np.arange(n) + 1/2, tmp))
272
+ _check_eigen(L, analytic_w, analytic_V)
273
+ # Compute the full eigendecomposition using eigh.
274
+ eigh_w, eigh_V = eigh(L)
275
+ _check_eigen(L, eigh_w, eigh_V)
276
+ # Check that the first eigenvalue is near zero and that the rest agree.
277
+ assert_array_less(np.abs([eigh_w[0], analytic_w[0]]), 1e-14)
278
+ assert_allclose(eigh_w[1:], analytic_w[1:])
279
+
280
+ # Check small lobpcg eigenvalues.
281
+ X = analytic_V[:, :p]
282
+ lobpcg_w, lobpcg_V = lobpcg(L, X, largest=False)
283
+ assert_equal(lobpcg_w.shape, (p,))
284
+ assert_equal(lobpcg_V.shape, (n, p))
285
+ _check_eigen(L, lobpcg_w, lobpcg_V)
286
+ assert_array_less(np.abs(np.min(lobpcg_w)), 1e-14)
287
+ assert_allclose(np.sort(lobpcg_w)[1:], analytic_w[1:p])
288
+
289
+ # Check large lobpcg eigenvalues.
290
+ X = analytic_V[:, -p:]
291
+ lobpcg_w, lobpcg_V = lobpcg(L, X, largest=True)
292
+ assert_equal(lobpcg_w.shape, (p,))
293
+ assert_equal(lobpcg_V.shape, (n, p))
294
+ _check_eigen(L, lobpcg_w, lobpcg_V)
295
+ assert_allclose(np.sort(lobpcg_w), analytic_w[-p:])
296
+
297
+ # Look for the Fiedler vector using good but not exactly correct guesses.
298
+ fiedler_guess = np.concatenate((np.ones(n//2), -np.ones(n-n//2)))
299
+ X = np.vstack((np.ones(n), fiedler_guess)).T
300
+ lobpcg_w, _ = lobpcg(L, X, largest=False)
301
+ # Mathematically, the smaller eigenvalue should be zero
302
+ # and the larger should be the algebraic connectivity.
303
+ lobpcg_w = np.sort(lobpcg_w)
304
+ assert_allclose(lobpcg_w, analytic_w[:2], atol=1e-14)
305
+
306
+
307
+ @pytest.mark.thread_unsafe
308
+ def test_fiedler_small_8():
309
+ """Check the dense workaround path for small matrices.
310
+ """
311
+ # This triggers the dense path because 8 < 2*5.
312
+ with pytest.warns(UserWarning, match="The problem size"):
313
+ _check_fiedler(8, 2)
314
+
315
+
316
+ def test_fiedler_large_12():
317
+ """Check the dense workaround path avoided for non-small matrices.
318
+ """
319
+ # This does not trigger the dense path, because 2*5 <= 12.
320
+ _check_fiedler(12, 2)
321
+
322
+
323
+ @pytest.mark.filterwarnings("ignore:Failed at iteration")
324
+ @pytest.mark.filterwarnings("ignore:Exited at iteration")
325
+ @pytest.mark.filterwarnings("ignore:Exited postprocessing")
326
+ def test_failure_to_run_iterations():
327
+ """Check that the code exits gracefully without breaking. Issue #10974.
328
+ The code may or not issue a warning, filtered out. Issue #15935, #17954.
329
+ """
330
+ rnd = np.random.RandomState(0)
331
+ X = rnd.standard_normal((100, 10))
332
+ A = X @ X.T
333
+ Q = rnd.standard_normal((X.shape[0], 4))
334
+ eigenvalues, _ = lobpcg(A, Q, maxiter=40, tol=1e-12)
335
+ assert np.max(eigenvalues) > 0
336
+
337
+
338
+ @pytest.mark.thread_unsafe
339
+ def test_failure_to_run_iterations_nonsymmetric():
340
+ """Check that the code exists gracefully without breaking
341
+ if the matrix in not symmetric.
342
+ """
343
+ A = np.zeros((10, 10))
344
+ A[0, 1] = 1
345
+ Q = np.ones((10, 1))
346
+ msg = "Exited at iteration 2|Exited postprocessing with accuracies.*"
347
+ with pytest.warns(UserWarning, match=msg):
348
+ eigenvalues, _ = lobpcg(A, Q, maxiter=20)
349
+ assert np.max(eigenvalues) > 0
350
+
351
+
352
+ @pytest.mark.filterwarnings("ignore:The problem size")
353
+ def test_hermitian():
354
+ """Check complex-value Hermitian cases.
355
+ """
356
+ rnd = np.random.RandomState(0)
357
+
358
+ sizes = [3, 12]
359
+ ks = [1, 2]
360
+ gens = [True, False]
361
+
362
+ for s, k, gen, dh, dx, db in (
363
+ itertools.product(sizes, ks, gens, gens, gens, gens)
364
+ ):
365
+ H = rnd.random((s, s)) + 1.j * rnd.random((s, s))
366
+ H = 10 * np.eye(s) + H + H.T.conj()
367
+ H = H.astype(np.complex128) if dh else H.astype(np.complex64)
368
+
369
+ X = rnd.standard_normal((s, k))
370
+ X = X + 1.j * rnd.standard_normal((s, k))
371
+ X = X.astype(np.complex128) if dx else X.astype(np.complex64)
372
+
373
+ if not gen:
374
+ B = np.eye(s)
375
+ w, v = lobpcg(H, X, maxiter=99, verbosityLevel=0)
376
+ # Also test mixing complex H with real B.
377
+ wb, _ = lobpcg(H, X, B, maxiter=99, verbosityLevel=0)
378
+ assert_allclose(w, wb, rtol=1e-6)
379
+ w0, _ = eigh(H)
380
+ else:
381
+ B = rnd.random((s, s)) + 1.j * rnd.random((s, s))
382
+ B = 10 * np.eye(s) + B.dot(B.T.conj())
383
+ B = B.astype(np.complex128) if db else B.astype(np.complex64)
384
+ w, v = lobpcg(H, X, B, maxiter=99, verbosityLevel=0)
385
+ w0, _ = eigh(H, B)
386
+
387
+ for wx, vx in zip(w, v.T):
388
+ # Check eigenvector
389
+ assert_allclose(np.linalg.norm(H.dot(vx) - B.dot(vx) * wx)
390
+ / np.linalg.norm(H.dot(vx)),
391
+ 0, atol=5e-2, rtol=0)
392
+
393
+ # Compare eigenvalues
394
+ j = np.argmin(abs(w0 - wx))
395
+ assert_allclose(wx, w0[j], rtol=1e-4)
396
+
397
+
398
+ # The n=5 case tests the alternative small matrix code path that uses eigh().
399
+ @pytest.mark.filterwarnings("ignore:The problem size")
400
+ @pytest.mark.parametrize('n, atol', [(20, 1e-3), (5, 1e-8)])
401
+ def test_eigsh_consistency(n, atol):
402
+ """Check eigsh vs. lobpcg consistency.
403
+ """
404
+ vals = np.arange(1, n+1, dtype=np.float64)
405
+ A = dia_array((vals, 0), shape=(n, n))
406
+ rnd = np.random.RandomState(0)
407
+ X = rnd.standard_normal((n, 2))
408
+ lvals, lvecs = lobpcg(A, X, largest=True, maxiter=100)
409
+ vals, _ = eigsh(A, k=2)
410
+
411
+ _check_eigen(A, lvals, lvecs, atol=atol, rtol=0)
412
+ assert_allclose(np.sort(vals), np.sort(lvals), atol=1e-14)
413
+
414
+
415
+ @pytest.mark.thread_unsafe
416
+ def test_verbosity():
417
+ """Check that nonzero verbosity level code runs.
418
+ """
419
+ rnd = np.random.RandomState(0)
420
+ X = rnd.standard_normal((10, 10))
421
+ A = X @ X.T
422
+ Q = rnd.standard_normal((X.shape[0], 1))
423
+ msg = "Exited at iteration.*|Exited postprocessing with accuracies.*"
424
+ with pytest.warns(UserWarning, match=msg):
425
+ _, _ = lobpcg(A, Q, maxiter=3, verbosityLevel=9)
426
+
427
+
428
+ @pytest.mark.xfail(_IS_32BIT and sys.platform == 'win32',
429
+ reason="tolerance violation on windows")
430
+ @pytest.mark.xfail(platform.machine() == 'ppc64le',
431
+ reason="fails on ppc64le")
432
+ @pytest.mark.filterwarnings("ignore:Exited postprocessing")
433
+ def test_tolerance_float32():
434
+ """Check lobpcg for attainable tolerance in float32.
435
+ """
436
+ rnd = np.random.RandomState(0)
437
+ n = 50
438
+ m = 3
439
+ vals = -np.arange(1, n + 1)
440
+ A = dia_array(([vals], [0]), shape=(n, n))
441
+ A = A.astype(np.float32)
442
+ X = rnd.standard_normal((n, m))
443
+ X = X.astype(np.float32)
444
+ eigvals, _ = lobpcg(A, X, tol=1.25e-5, maxiter=50, verbosityLevel=0)
445
+ assert_allclose(eigvals, -np.arange(1, 1 + m), atol=2e-5, rtol=1e-5)
446
+
447
+
448
+ @pytest.mark.parametrize("vdtype", INEXACTDTYPES)
449
+ @pytest.mark.parametrize("mdtype", ALLDTYPES)
450
+ @pytest.mark.parametrize("arr_type", [np.array,
451
+ sparse.csr_array,
452
+ sparse.coo_array])
453
+ def test_dtypes(vdtype, mdtype, arr_type):
454
+ """Test lobpcg in various dtypes.
455
+ """
456
+ rnd = np.random.RandomState(0)
457
+ n = 12
458
+ m = 2
459
+ A = arr_type(np.diag(np.arange(1, n + 1)).astype(mdtype))
460
+ X = rnd.random((n, m))
461
+ X = X.astype(vdtype)
462
+ eigvals, eigvecs = lobpcg(A, X, tol=1e-2, largest=False)
463
+ assert_allclose(eigvals, np.arange(1, 1 + m), atol=1e-1)
464
+ # eigenvectors must be nearly real in any case
465
+ assert_allclose(np.sum(np.abs(eigvecs - eigvecs.conj())), 0, atol=1e-2)
466
+
467
+
468
+ @pytest.mark.thread_unsafe
469
+ @pytest.mark.filterwarnings("ignore:Exited at iteration")
470
+ @pytest.mark.filterwarnings("ignore:Exited postprocessing")
471
+ def test_inplace_warning():
472
+ """Check lobpcg gives a warning in '_b_orthonormalize'
473
+ that in-place orthogonalization is impossible due to dtype mismatch.
474
+ """
475
+ rnd = np.random.RandomState(0)
476
+ n = 6
477
+ m = 1
478
+ vals = -np.arange(1, n + 1)
479
+ A = dia_array(([vals], [0]), shape=(n, n))
480
+ A = A.astype(np.cdouble)
481
+ X = rnd.standard_normal((n, m))
482
+ with pytest.warns(UserWarning, match="Inplace update"):
483
+ eigvals, _ = lobpcg(A, X, maxiter=2, verbosityLevel=1)
484
+
485
+
486
+ @pytest.mark.thread_unsafe
487
+ def test_maxit():
488
+ """Check lobpcg if maxit=maxiter runs maxiter iterations and
489
+ if maxit=None runs 20 iterations (the default)
490
+ by checking the size of the iteration history output, which should
491
+ be the number of iterations plus 3 (initial, final, and postprocessing)
492
+ typically when maxiter is small and the choice of the best is passive.
493
+ """
494
+ rnd = np.random.RandomState(0)
495
+ n = 50
496
+ m = 4
497
+ vals = -np.arange(1, n + 1)
498
+ A = dia_array(([vals], [0]), shape=(n, n))
499
+ A = A.astype(np.float32)
500
+ X = rnd.standard_normal((n, m))
501
+ X = X.astype(np.float64)
502
+ msg = "Exited at iteration.*|Exited postprocessing with accuracies.*"
503
+ for maxiter in range(1, 4):
504
+ with pytest.warns(UserWarning, match=msg):
505
+ _, _, l_h, r_h = lobpcg(A, X, tol=1e-8, maxiter=maxiter,
506
+ retLambdaHistory=True,
507
+ retResidualNormsHistory=True)
508
+ assert_allclose(np.shape(l_h)[0], maxiter+3)
509
+ assert_allclose(np.shape(r_h)[0], maxiter+3)
510
+ with pytest.warns(UserWarning, match=msg):
511
+ l, _, l_h, r_h = lobpcg(A, X, tol=1e-8,
512
+ retLambdaHistory=True,
513
+ retResidualNormsHistory=True)
514
+ assert_allclose(np.shape(l_h)[0], 20+3)
515
+ assert_allclose(np.shape(r_h)[0], 20+3)
516
+ # Check that eigenvalue output is the last one in history
517
+ assert_allclose(l, l_h[-1])
518
+ # Make sure that both history outputs are lists
519
+ assert isinstance(l_h, list)
520
+ assert isinstance(r_h, list)
521
+ # Make sure that both history lists are arrays-like
522
+ assert_allclose(np.shape(l_h), np.shape(np.asarray(l_h)))
523
+ assert_allclose(np.shape(r_h), np.shape(np.asarray(r_h)))
524
+
525
+
526
+ @pytest.mark.xslow
527
+ @pytest.mark.filterwarnings("ignore:Exited at iteration")
528
+ @pytest.mark.filterwarnings("ignore:Exited postprocessing")
529
+ def test_sakurai():
530
+ """Check lobpcg and eighs accuracy for the Sakurai example
531
+ already used in `benchmarks/benchmarks/sparse_linalg_lobpcg.py`.
532
+ """
533
+ n = 50
534
+ tol = 100 * n * n * n* np.finfo(float).eps
535
+ sakurai_obj = Sakurai(n, dtype='int')
536
+ A = sakurai_obj
537
+ m = 3
538
+ ee = sakurai_obj.eigenvalues(3)
539
+ rng = np.random.default_rng(0)
540
+ X = rng.normal(size=(n, m))
541
+ el, _ = lobpcg(A, X, tol=1e-9, maxiter=5000, largest=False)
542
+ accuracy = max(abs(ee - el) / ee)
543
+ assert_allclose(accuracy, 0., atol=tol)
544
+ a_l = LinearOperator((n, n), matvec=A, matmat=A, dtype='float64')
545
+ ea, _ = eigsh(a_l, k=m, which='SA', tol=1e-9, maxiter=15000,
546
+ v0 = rng.normal(size=(n, 1)))
547
+ accuracy = max(abs(ee - ea) / ee)
548
+ assert_allclose(accuracy, 0., atol=tol)
549
+
550
+
551
+ @pytest.mark.parametrize("n", [500, 1000])
552
+ @pytest.mark.filterwarnings("ignore:Exited at iteration")
553
+ @pytest.mark.filterwarnings("ignore:Exited postprocessing")
554
+ def test_sakurai_inverse(n):
555
+ """Check lobpcg and eighs accuracy for the sakurai_inverse example
556
+ already used in `benchmarks/benchmarks/sparse_linalg_lobpcg.py`.
557
+ """
558
+ def a(x):
559
+ return cho_solve_banded((c, False), x)
560
+ tol = 100 * n * n * n* np.finfo(float).eps
561
+ sakurai_obj = Sakurai(n)
562
+ A = sakurai_obj.tobanded().astype(np.float64)
563
+ m = 3
564
+ ee = sakurai_obj.eigenvalues(3)
565
+ rng = np.random.default_rng(0)
566
+ X = rng.normal(size=(n, m))
567
+ c = cholesky_banded(A)
568
+ el, _ = lobpcg(a, X, tol=1e-9, maxiter=8)
569
+ accuracy = max(abs(ee - 1. / el) / ee)
570
+ assert_allclose(accuracy, 0., atol=tol)
571
+ a_l = LinearOperator((n, n), matvec=a, matmat=a, dtype='float64')
572
+ ea, _ = eigsh(a_l, k=m, which='LA', tol=1e-9, maxiter=8,
573
+ v0 = rng.normal(size=(n, 1)))
574
+ accuracy = max(abs(ee - np.sort(1. / ea)) / ee)
575
+ assert_allclose(accuracy, 0., atol=tol)
576
+
577
+
578
+ @pytest.mark.filterwarnings("ignore:The problem size")
579
+ @pytest.mark.parametrize("n", [10, 20, 128, 256, 512, 1024, 2048])
580
+ @pytest.mark.filterwarnings("ignore:Exited at iteration")
581
+ @pytest.mark.filterwarnings("ignore:Exited postprocessing")
582
+ def test_MikotaPair(n):
583
+ """Check lobpcg and eighs accuracy for the Mikota example
584
+ already used in `benchmarks/benchmarks/sparse_linalg_lobpcg.py`.
585
+ """
586
+ def a(x):
587
+ return cho_solve_banded((c, False), x)
588
+ mik = MikotaPair(n)
589
+ mik_k = mik.k
590
+ mik_m = mik.m
591
+ Ac = mik_k
592
+ Bc = mik_m
593
+ Ab = mik_k.tobanded()
594
+ eigenvalues = mik.eigenvalues
595
+ if n == 10:
596
+ m = 3 # lobpcg calls eigh
597
+ elif n == 20:
598
+ m = 2
599
+ else:
600
+ m = 10
601
+ ee = eigenvalues(m)
602
+ tol = 100 * m * n * n * np.finfo(float).eps
603
+ rng = np.random.default_rng(0)
604
+ X = rng.normal(size=(n, m))
605
+ c = cholesky_banded(Ab.astype(np.float32))
606
+ el, _ = lobpcg(Ac, X, Bc, M=a, tol=1e-4,
607
+ maxiter=40, largest=False)
608
+ accuracy = max(abs(ee - el) / ee)
609
+ assert_allclose(accuracy, 0., atol=tol)
610
+ B = LinearOperator((n, n), matvec=Bc, matmat=Bc, dtype='float64')
611
+ A = LinearOperator((n, n), matvec=Ac, matmat=Ac, dtype='float64')
612
+ c = cholesky_banded(Ab)
613
+ a_l = LinearOperator((n, n), matvec=a, matmat=a, dtype='float64')
614
+ ea, _ = eigsh(B, k=m, M=A, Minv=a_l, which='LA', tol=1e-4, maxiter=50,
615
+ v0 = rng.normal(size=(n, 1)))
616
+ accuracy = max(abs(ee - np.sort(1./ea)) / ee)
617
+ assert_allclose(accuracy, 0., atol=tol)
618
+
619
+
620
+ @pytest.mark.slow
621
+ @pytest.mark.parametrize("n", [15])
622
+ @pytest.mark.parametrize("m", [1, 2])
623
+ @pytest.mark.filterwarnings("ignore:Exited at iteration")
624
+ @pytest.mark.filterwarnings("ignore:Exited postprocessing")
625
+ def test_diagonal_data_types(n, m):
626
+ """Check lobpcg for diagonal matrices for all matrix types.
627
+ Constraints are imposed, so a dense eigensolver eig cannot run.
628
+ """
629
+ rnd = np.random.RandomState(0)
630
+ # Define the generalized eigenvalue problem Av = cBv
631
+ # where (c, v) is a generalized eigenpair,
632
+ # and where we choose A and B to be diagonal.
633
+ vals = np.arange(1, n + 1)
634
+
635
+ list_sparse_format = ['bsr', 'coo', 'csc', 'csr', 'dia', 'dok', 'lil']
636
+ for s_f_i, s_f in enumerate(list_sparse_format):
637
+
638
+ As64 = dia_array(([vals * vals], [0]), shape=(n, n)).asformat(s_f)
639
+ As32 = As64.astype(np.float32)
640
+ Af64 = As64.toarray()
641
+ Af32 = Af64.astype(np.float32)
642
+
643
+ def As32f(x):
644
+ return As32 @ x
645
+ As32LO = LinearOperator(matvec=As32f,
646
+ matmat=As32f,
647
+ shape=(n, n),
648
+ dtype=As32.dtype)
649
+
650
+ listA = [Af64, As64, Af32, As32, As32f, As32LO, lambda v: As32 @ v]
651
+
652
+ Bs64 = dia_array(([vals], [0]), shape=(n, n)).asformat(s_f)
653
+ Bf64 = Bs64.toarray()
654
+ Bs32 = Bs64.astype(np.float32)
655
+
656
+ def Bs32f(x):
657
+ return Bs32 @ x
658
+ Bs32LO = LinearOperator(matvec=Bs32f,
659
+ matmat=Bs32f,
660
+ shape=(n, n),
661
+ dtype=Bs32.dtype)
662
+ listB = [Bf64, Bs64, Bs32, Bs32f, Bs32LO, lambda v: Bs32 @ v]
663
+
664
+ # Define the preconditioner function as LinearOperator.
665
+ Ms64 = dia_array(([1./vals], [0]), shape=(n, n)).asformat(s_f)
666
+
667
+ def Ms64precond(x):
668
+ return Ms64 @ x
669
+ Ms64precondLO = LinearOperator(matvec=Ms64precond,
670
+ matmat=Ms64precond,
671
+ shape=(n, n),
672
+ dtype=Ms64.dtype)
673
+ Mf64 = Ms64.toarray()
674
+
675
+ def Mf64precond(x):
676
+ return Mf64 @ x
677
+ Mf64precondLO = LinearOperator(matvec=Mf64precond,
678
+ matmat=Mf64precond,
679
+ shape=(n, n),
680
+ dtype=Mf64.dtype)
681
+ Ms32 = Ms64.astype(np.float32)
682
+
683
+ def Ms32precond(x):
684
+ return Ms32 @ x
685
+ Ms32precondLO = LinearOperator(matvec=Ms32precond,
686
+ matmat=Ms32precond,
687
+ shape=(n, n),
688
+ dtype=Ms32.dtype)
689
+ Mf32 = Ms32.toarray()
690
+
691
+ def Mf32precond(x):
692
+ return Mf32 @ x
693
+ Mf32precondLO = LinearOperator(matvec=Mf32precond,
694
+ matmat=Mf32precond,
695
+ shape=(n, n),
696
+ dtype=Mf32.dtype)
697
+ listM = [None, Ms64, Ms64precondLO, Mf64precondLO, Ms64precond,
698
+ Ms32, Ms32precondLO, Mf32precondLO, Ms32precond]
699
+
700
+ # Setup matrix of the initial approximation to the eigenvectors
701
+ # (cannot be sparse array).
702
+ Xf64 = rnd.random((n, m))
703
+ Xf32 = Xf64.astype(np.float32)
704
+ listX = [Xf64, Xf32]
705
+
706
+ # Require that the returned eigenvectors be in the orthogonal complement
707
+ # of the first few standard basis vectors (cannot be sparse array).
708
+ m_excluded = 3
709
+ Yf64 = np.eye(n, m_excluded, dtype=float)
710
+ Yf32 = np.eye(n, m_excluded, dtype=np.float32)
711
+ listY = [Yf64, Yf32]
712
+
713
+ tests = list(itertools.product(listA, listB, listM, listX, listY))
714
+
715
+ for A, B, M, X, Y in tests:
716
+ # This is one of the slower tests because there are >1,000 configs
717
+ # to test here. Flip a biased coin to decide whether to run each
718
+ # test to get decent coverage in less time.
719
+ if rnd.random() < 0.98:
720
+ continue # too many tests
721
+ eigvals, _ = lobpcg(A, X, B=B, M=M, Y=Y, tol=1e-4,
722
+ maxiter=100, largest=False)
723
+ assert_allclose(eigvals,
724
+ np.arange(1 + m_excluded, 1 + m_excluded + m),
725
+ atol=1e-5)
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/tests/__init__.py ADDED
File without changes
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/tests/test_svds.py ADDED
@@ -0,0 +1,886 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import copy
3
+ import numpy as np
4
+
5
+ from numpy.testing import assert_allclose, assert_equal, assert_array_equal
6
+ import pytest
7
+
8
+ from scipy.linalg import svd, null_space
9
+ from scipy.sparse import csc_array, issparse, dia_array, random_array
10
+ from scipy.sparse.linalg import LinearOperator, aslinearoperator
11
+ from scipy.sparse.linalg import svds
12
+ from scipy.sparse.linalg._eigen.arpack import ArpackNoConvergence
13
+
14
+
15
+ # --- Helper Functions / Classes ---
16
+
17
+
18
+ def sorted_svd(m, k, which='LM'):
19
+ # Compute svd of a dense matrix m, and return singular vectors/values
20
+ # sorted.
21
+ if issparse(m):
22
+ m = m.toarray()
23
+ u, s, vh = svd(m)
24
+ if which == 'LM':
25
+ ii = np.argsort(s)[-k:]
26
+ elif which == 'SM':
27
+ ii = np.argsort(s)[:k]
28
+ else:
29
+ raise ValueError(f"unknown which={which!r}")
30
+
31
+ return u[:, ii], s[ii], vh[ii]
32
+
33
+
34
+ def _check_svds(A, k, u, s, vh, which="LM", check_usvh_A=False,
35
+ check_svd=True, atol=1e-10, rtol=1e-7):
36
+ n, m = A.shape
37
+
38
+ # Check shapes.
39
+ assert_equal(u.shape, (n, k))
40
+ assert_equal(s.shape, (k,))
41
+ assert_equal(vh.shape, (k, m))
42
+
43
+ # Check that the original matrix can be reconstituted.
44
+ A_rebuilt = (u*s).dot(vh)
45
+ assert_equal(A_rebuilt.shape, A.shape)
46
+ if check_usvh_A:
47
+ assert_allclose(A_rebuilt, A, atol=atol, rtol=rtol)
48
+
49
+ # Check that u is a semi-orthogonal matrix.
50
+ uh_u = np.dot(u.T.conj(), u)
51
+ assert_equal(uh_u.shape, (k, k))
52
+ assert_allclose(uh_u, np.identity(k), atol=atol, rtol=rtol)
53
+
54
+ # Check that vh is a semi-orthogonal matrix.
55
+ vh_v = np.dot(vh, vh.T.conj())
56
+ assert_equal(vh_v.shape, (k, k))
57
+ assert_allclose(vh_v, np.identity(k), atol=atol, rtol=rtol)
58
+
59
+ # Check that scipy.sparse.linalg.svds ~ scipy.linalg.svd
60
+ if check_svd:
61
+ u2, s2, vh2 = sorted_svd(A, k, which)
62
+ assert_allclose(np.abs(u), np.abs(u2), atol=atol, rtol=rtol)
63
+ assert_allclose(s, s2, atol=atol, rtol=rtol)
64
+ assert_allclose(np.abs(vh), np.abs(vh2), atol=atol, rtol=rtol)
65
+
66
+
67
+ def _check_svds_n(A, k, u, s, vh, which="LM", check_res=True,
68
+ check_svd=True, atol=1e-10, rtol=1e-7):
69
+ n, m = A.shape
70
+
71
+ # Check shapes.
72
+ assert_equal(u.shape, (n, k))
73
+ assert_equal(s.shape, (k,))
74
+ assert_equal(vh.shape, (k, m))
75
+
76
+ # Check that u is a semi-orthogonal matrix.
77
+ uh_u = np.dot(u.T.conj(), u)
78
+ assert_equal(uh_u.shape, (k, k))
79
+ error = np.sum(np.abs(uh_u - np.identity(k))) / (k * k)
80
+ assert_allclose(error, 0.0, atol=atol, rtol=rtol)
81
+
82
+ # Check that vh is a semi-orthogonal matrix.
83
+ vh_v = np.dot(vh, vh.T.conj())
84
+ assert_equal(vh_v.shape, (k, k))
85
+ error = np.sum(np.abs(vh_v - np.identity(k))) / (k * k)
86
+ assert_allclose(error, 0.0, atol=atol, rtol=rtol)
87
+
88
+ # Check residuals
89
+ if check_res:
90
+ ru = A.T.conj() @ u - vh.T.conj() * s
91
+ rus = np.sum(np.abs(ru)) / (n * k)
92
+ rvh = A @ vh.T.conj() - u * s
93
+ rvhs = np.sum(np.abs(rvh)) / (m * k)
94
+ assert_allclose(rus, 0.0, atol=atol, rtol=rtol)
95
+ assert_allclose(rvhs, 0.0, atol=atol, rtol=rtol)
96
+
97
+ # Check that scipy.sparse.linalg.svds ~ scipy.linalg.svd
98
+ if check_svd:
99
+ u2, s2, vh2 = sorted_svd(A, k, which)
100
+ assert_allclose(s, s2, atol=atol, rtol=rtol)
101
+ A_rebuilt_svd = (u2*s2).dot(vh2)
102
+ A_rebuilt = (u*s).dot(vh)
103
+ assert_equal(A_rebuilt.shape, A.shape)
104
+ error = np.sum(np.abs(A_rebuilt_svd - A_rebuilt)) / (k * k)
105
+ assert_allclose(error, 0.0, atol=atol, rtol=rtol)
106
+
107
+
108
+ class CheckingLinearOperator(LinearOperator):
109
+ def __init__(self, A):
110
+ self.A = A
111
+ self.dtype = A.dtype
112
+ self.shape = A.shape
113
+
114
+ def _matvec(self, x):
115
+ assert_equal(max(x.shape), np.size(x))
116
+ return self.A.dot(x)
117
+
118
+ def _rmatvec(self, x):
119
+ assert_equal(max(x.shape), np.size(x))
120
+ return self.A.T.conjugate().dot(x)
121
+
122
+
123
+ # --- Test Input Validation ---
124
+ # Tests input validation on parameters `k` and `which`.
125
+ # Needs better input validation checks for all other parameters.
126
+
127
+ class SVDSCommonTests:
128
+
129
+ solver = None
130
+
131
+ # some of these IV tests could run only once, say with solver=None
132
+
133
+ _A_empty_msg = "`A` must not be empty."
134
+ _A_dtype_msg = "`A` must be of numeric data type"
135
+ _A_type_msg = "type not understood"
136
+ _A_ndim_msg = "array must have ndim <= 2"
137
+ _A_validation_inputs = [
138
+ (np.asarray([[]]), ValueError, _A_empty_msg),
139
+ (np.array([['a', 'b'], ['c', 'd']], dtype='object'), ValueError, _A_dtype_msg),
140
+ ("hi", TypeError, _A_type_msg),
141
+ (np.asarray([[[1., 2.], [3., 4.]]]), ValueError, _A_ndim_msg)]
142
+
143
+ @pytest.mark.parametrize("args", _A_validation_inputs)
144
+ def test_svds_input_validation_A(self, args):
145
+ A, error_type, message = args
146
+ with pytest.raises(error_type, match=message):
147
+ svds(A, k=1, solver=self.solver, rng=0)
148
+
149
+ @pytest.mark.parametrize("which", ["LM", "SM"])
150
+ def test_svds_int_A(self, which):
151
+ A = np.asarray([[1, 2], [3, 4]])
152
+ if self.solver == 'lobpcg':
153
+ with pytest.warns(UserWarning, match="The problem size"):
154
+ res = svds(A, k=1, which=which, solver=self.solver, rng=0)
155
+ else:
156
+ res = svds(A, k=1, which=which, solver=self.solver, rng=0)
157
+ _check_svds(A, 1, *res, which=which, atol=8e-10)
158
+
159
+ def test_svds_diff0_docstring_example(self):
160
+ def diff0(a):
161
+ return np.diff(a, axis=0)
162
+ def diff0t(a):
163
+ if a.ndim == 1:
164
+ a = a[:,np.newaxis] # Turn 1D into 2D array
165
+ d = np.zeros((a.shape[0] + 1, a.shape[1]), dtype=a.dtype)
166
+ d[0, :] = - a[0, :]
167
+ d[1:-1, :] = a[0:-1, :] - a[1:, :]
168
+ d[-1, :] = a[-1, :]
169
+ return d
170
+ def diff0_func_aslo_def(n):
171
+ return LinearOperator(matvec=diff0,
172
+ matmat=diff0,
173
+ rmatvec=diff0t,
174
+ rmatmat=diff0t,
175
+ shape=(n - 1, n))
176
+ n = 100
177
+ diff0_func_aslo = diff0_func_aslo_def(n)
178
+ # preserve a use of legacy keyword `random_state` during SPEC 7 transition
179
+ u, s, _ = svds(diff0_func_aslo, k=3, which='SM', random_state=0)
180
+ se = 2. * np.sin(np.pi * np.arange(1, 4) / (2. * n))
181
+ ue = np.sqrt(2 / n) * np.sin(np.pi * np.outer(np.arange(1, n),
182
+ np.arange(1, 4)) / n)
183
+ assert_allclose(s, se, atol=1e-3)
184
+ assert_allclose(np.abs(u), np.abs(ue), atol=1e-6)
185
+
186
+ @pytest.mark.parametrize("k", [-1, 0, 3, 4, 5, 1.5, "1"])
187
+ def test_svds_input_validation_k_1(self, k):
188
+ rng = np.random.default_rng(0)
189
+ A = rng.random((4, 3))
190
+
191
+ # propack can do complete SVD
192
+ if self.solver == 'propack' and k == 3:
193
+ res = svds(A, k=k, solver=self.solver, rng=0)
194
+ _check_svds(A, k, *res, check_usvh_A=True, check_svd=True)
195
+ return
196
+
197
+ message = ("`k` must be an integer satisfying")
198
+ with pytest.raises(ValueError, match=message):
199
+ svds(A, k=k, solver=self.solver, rng=0)
200
+
201
+ def test_svds_input_validation_k_2(self):
202
+ # I think the stack trace is reasonable when `k` can't be converted
203
+ # to an int.
204
+ message = "int() argument must be a"
205
+ with pytest.raises(TypeError, match=re.escape(message)):
206
+ svds(np.eye(10), k=[], solver=self.solver, rng=0)
207
+
208
+ message = "invalid literal for int()"
209
+ with pytest.raises(ValueError, match=message):
210
+ svds(np.eye(10), k="hi", solver=self.solver, rng=0)
211
+
212
+ @pytest.mark.parametrize("tol", (-1, np.inf, np.nan))
213
+ def test_svds_input_validation_tol_1(self, tol):
214
+ message = "`tol` must be a non-negative floating point value."
215
+ with pytest.raises(ValueError, match=message):
216
+ svds(np.eye(10), tol=tol, solver=self.solver, rng=0)
217
+
218
+ @pytest.mark.parametrize("tol", ([], 'hi'))
219
+ def test_svds_input_validation_tol_2(self, tol):
220
+ # I think the stack trace is reasonable here
221
+ message = "'<' not supported between instances"
222
+ with pytest.raises(TypeError, match=message):
223
+ svds(np.eye(10), tol=tol, solver=self.solver, rng=0)
224
+
225
+ @pytest.mark.parametrize("which", ('LA', 'SA', 'ekki', 0))
226
+ def test_svds_input_validation_which(self, which):
227
+ # Regression test for a github issue.
228
+ # https://github.com/scipy/scipy/issues/4590
229
+ # Function was not checking for eigenvalue type and unintended
230
+ # values could be returned.
231
+ with pytest.raises(ValueError, match="`which` must be in"):
232
+ svds(np.eye(10), which=which, solver=self.solver, rng=0)
233
+
234
+ @pytest.mark.parametrize("transpose", (True, False))
235
+ @pytest.mark.parametrize("n", range(4, 9))
236
+ def test_svds_input_validation_v0_1(self, transpose, n):
237
+ rng = np.random.default_rng(0)
238
+ A = rng.random((5, 7))
239
+ v0 = rng.random(n)
240
+ if transpose:
241
+ A = A.T
242
+ k = 2
243
+ message = "`v0` must have shape"
244
+
245
+ required_length = (A.shape[0] if self.solver == 'propack'
246
+ else min(A.shape))
247
+ if n != required_length:
248
+ with pytest.raises(ValueError, match=message):
249
+ svds(A, k=k, v0=v0, solver=self.solver, rng=0)
250
+
251
+ def test_svds_input_validation_v0_2(self):
252
+ A = np.ones((10, 10))
253
+ v0 = np.ones((1, 10))
254
+ message = "`v0` must have shape"
255
+ with pytest.raises(ValueError, match=message):
256
+ svds(A, k=1, v0=v0, solver=self.solver, rng=0)
257
+
258
+ @pytest.mark.parametrize("v0", ("hi", 1, np.ones(10, dtype=int)))
259
+ def test_svds_input_validation_v0_3(self, v0):
260
+ A = np.ones((10, 10))
261
+ message = "`v0` must be of floating or complex floating data type."
262
+ with pytest.raises(ValueError, match=message):
263
+ svds(A, k=1, v0=v0, solver=self.solver, rng=0)
264
+
265
+ @pytest.mark.parametrize("maxiter", (-1, 0, 5.5))
266
+ def test_svds_input_validation_maxiter_1(self, maxiter):
267
+ message = ("`maxiter` must be a positive integer.")
268
+ with pytest.raises(ValueError, match=message):
269
+ svds(np.eye(10), maxiter=maxiter, solver=self.solver, rng=0)
270
+
271
+ def test_svds_input_validation_maxiter_2(self):
272
+ # I think the stack trace is reasonable when `k` can't be converted
273
+ # to an int.
274
+ message = "int() argument must be a"
275
+ with pytest.raises(TypeError, match=re.escape(message)):
276
+ svds(np.eye(10), maxiter=[], solver=self.solver, rng=0)
277
+
278
+ message = "invalid literal for int()"
279
+ with pytest.raises(ValueError, match=message):
280
+ svds(np.eye(10), maxiter="hi", solver=self.solver, rng=0)
281
+
282
+ @pytest.mark.parametrize("rsv", ('ekki', 10))
283
+ def test_svds_input_validation_return_singular_vectors(self, rsv):
284
+ message = "`return_singular_vectors` must be in"
285
+ with pytest.raises(ValueError, match=message):
286
+ svds(np.eye(10), return_singular_vectors=rsv, solver=self.solver, rng=0)
287
+
288
+ # --- Test Parameters ---
289
+ @pytest.mark.thread_unsafe
290
+ @pytest.mark.parametrize("k", [3, 5])
291
+ @pytest.mark.parametrize("which", ["LM", "SM"])
292
+ def test_svds_parameter_k_which(self, k, which):
293
+ # check that the `k` parameter sets the number of eigenvalues/
294
+ # eigenvectors returned.
295
+ # Also check that the `which` parameter sets whether the largest or
296
+ # smallest eigenvalues are returned
297
+ rng = np.random.default_rng(0)
298
+ A = rng.random((10, 10))
299
+ if self.solver == 'lobpcg':
300
+ with pytest.warns(UserWarning, match="The problem size"):
301
+ res = svds(A, k=k, which=which, solver=self.solver, rng=0)
302
+ else:
303
+ res = svds(A, k=k, which=which, solver=self.solver, rng=0)
304
+ _check_svds(A, k, *res, which=which, atol=1e-9, rtol=2e-13)
305
+
306
+ @pytest.mark.filterwarnings("ignore:Exited",
307
+ reason="Ignore LOBPCG early exit.")
308
+ # loop instead of parametrize for simplicity
309
+ def test_svds_parameter_tol(self):
310
+ # check the effect of the `tol` parameter on solver accuracy by solving
311
+ # the same problem with varying `tol` and comparing the eigenvalues
312
+ # against ground truth computed
313
+ n = 100 # matrix size
314
+ k = 3 # number of eigenvalues to check
315
+
316
+ # generate a random, sparse-ish matrix
317
+ # effect isn't apparent for matrices that are too small
318
+ rng = np.random.default_rng(0)
319
+ A = rng.random((n, n))
320
+ A[A > .1] = 0
321
+ A = A @ A.T
322
+
323
+ _, s, _ = svd(A) # calculate ground truth
324
+
325
+ # calculate the error as a function of `tol`
326
+ A = csc_array(A)
327
+
328
+ def err(tol):
329
+ _, s2, _ = svds(A, k=k, v0=np.ones(n), maxiter=1000,
330
+ solver=self.solver, tol=tol, rng=0)
331
+ return np.linalg.norm((s2 - s[k-1::-1])/s[k-1::-1])
332
+
333
+ tols = [1e-4, 1e-2, 1e0] # tolerance levels to check
334
+ # for 'arpack' and 'propack', accuracies make discrete steps
335
+ accuracies = {'propack': [1e-12, 1e-6, 1e-4],
336
+ 'arpack': [2.5e-15, 1e-10, 1e-10],
337
+ 'lobpcg': [2e-12, 4e-2, 2]}
338
+
339
+ for tol, accuracy in zip(tols, accuracies[self.solver]):
340
+ error = err(tol)
341
+ assert error < accuracy
342
+
343
+ def test_svd_v0(self):
344
+ # check that the `v0` parameter affects the solution
345
+ n = 100
346
+ k = 1
347
+ # If k != 1, LOBPCG needs more initial vectors, which are generated
348
+ # with rng, so it does not pass w/ k >= 2.
349
+ # For some other values of `n`, the AssertionErrors are not raised
350
+ # with different v0s, which is reasonable.
351
+
352
+ rng = np.random.default_rng(0)
353
+ A = rng.random((n, n))
354
+
355
+ # with the same v0, solutions are the same, and they are accurate
356
+ # v0 takes precedence over rng
357
+ v0a = rng.random(n)
358
+ res1a = svds(A, k, v0=v0a, solver=self.solver, rng=0)
359
+ res2a = svds(A, k, v0=v0a, solver=self.solver, rng=1)
360
+ for idx in range(3):
361
+ assert_allclose(res1a[idx], res2a[idx], rtol=1e-15, atol=2e-16)
362
+ _check_svds(A, k, *res1a)
363
+
364
+ # with the same v0, solutions are the same, and they are accurate
365
+ v0b = rng.random(n)
366
+ res1b = svds(A, k, v0=v0b, solver=self.solver, rng=2)
367
+ res2b = svds(A, k, v0=v0b, solver=self.solver, rng=3)
368
+ for idx in range(3):
369
+ assert_allclose(res1b[idx], res2b[idx], rtol=1e-15, atol=2e-16)
370
+ _check_svds(A, k, *res1b)
371
+
372
+ # with different v0, solutions can be numerically different
373
+ message = "Arrays are not equal"
374
+ with pytest.raises(AssertionError, match=message):
375
+ assert_equal(res1a, res1b)
376
+
377
+ def test_svd_rng(self):
378
+ # check that the `rng` parameter affects the solution
379
+ # Admittedly, `n` and `k` are chosen so that all solver pass all
380
+ # these checks. That's a tall order, since LOBPCG doesn't want to
381
+ # achieve the desired accuracy and ARPACK often returns the same
382
+ # singular values/vectors for different v0.
383
+ n = 100
384
+ k = 1
385
+
386
+ rng = np.random.default_rng(0)
387
+ A = rng.random((n, n))
388
+
389
+ # with the same rng, solutions are the same and accurate
390
+ res1a = svds(A, k, solver=self.solver, rng=0)
391
+ res2a = svds(A, k, solver=self.solver, rng=0)
392
+ for idx in range(3):
393
+ assert_allclose(res1a[idx], res2a[idx], rtol=1e-15, atol=2e-16)
394
+ _check_svds(A, k, *res1a)
395
+
396
+ # with the same rng, solutions are the same and accurate
397
+ res1b = svds(A, k, solver=self.solver, rng=1)
398
+ res2b = svds(A, k, solver=self.solver, rng=1)
399
+ for idx in range(3):
400
+ assert_allclose(res1b[idx], res2b[idx], rtol=1e-15, atol=2e-16)
401
+ _check_svds(A, k, *res1b)
402
+
403
+ # with different rng, solutions can be numerically different
404
+ message = "Arrays are not equal"
405
+ with pytest.raises(AssertionError, match=message):
406
+ assert_equal(res1a, res1b)
407
+
408
+ def test_svd_rng_2(self):
409
+ n = 100
410
+ k = 1
411
+
412
+ rng = np.random.default_rng(234981)
413
+ A = rng.random((n, n))
414
+ rng_2 = copy.deepcopy(rng)
415
+
416
+ # with the same rng, solutions are the same and accurate
417
+ res1a = svds(A, k, solver=self.solver, rng=rng)
418
+ res2a = svds(A, k, solver=self.solver, rng=rng_2)
419
+ for idx in range(3):
420
+ assert_allclose(res1a[idx], res2a[idx], rtol=1e-15, atol=2e-16)
421
+ _check_svds(A, k, *res1a)
422
+
423
+ @pytest.mark.filterwarnings("ignore:Exited",
424
+ reason="Ignore LOBPCG early exit.")
425
+ def test_svd_rng_3(self):
426
+ n = 100
427
+ k = 5
428
+
429
+ rng1 = np.random.default_rng(0)
430
+ rng2 = np.random.default_rng(234832)
431
+ A = rng1.random((n, n))
432
+
433
+ # rng in different state produces accurate - but not
434
+ # not necessarily identical - results
435
+ res1a = svds(A, k, solver=self.solver, rng=rng1, maxiter=1000)
436
+ res2a = svds(A, k, solver=self.solver, rng=rng2, maxiter=1000)
437
+ _check_svds(A, k, *res1a, atol=2e-7)
438
+ _check_svds(A, k, *res2a, atol=2e-7)
439
+
440
+ message = "Arrays are not equal"
441
+ with pytest.raises(AssertionError, match=message):
442
+ assert_equal(res1a, res2a)
443
+
444
+ @pytest.mark.thread_unsafe
445
+ @pytest.mark.filterwarnings("ignore:Exited postprocessing")
446
+ def test_svd_maxiter(self):
447
+ # check that maxiter works as expected: should not return accurate
448
+ # solution after 1 iteration, but should with default `maxiter`
449
+ A = np.diag(np.arange(9)).astype(np.float64)
450
+ k = 1
451
+ u, s, vh = sorted_svd(A, k)
452
+ # Use default maxiter by default
453
+ maxiter = None
454
+
455
+ if self.solver == 'arpack':
456
+ message = "ARPACK error -1: No convergence"
457
+ with pytest.raises(ArpackNoConvergence, match=message):
458
+ svds(A, k, ncv=3, maxiter=1, solver=self.solver, rng=0)
459
+ elif self.solver == 'lobpcg':
460
+ # Set maxiter higher so test passes without changing
461
+ # default and breaking backward compatibility (gh-20221)
462
+ maxiter = 30
463
+ with pytest.warns(UserWarning, match="Exited at iteration"):
464
+ svds(A, k, maxiter=1, solver=self.solver, rng=0)
465
+ elif self.solver == 'propack':
466
+ message = "k=1 singular triplets did not converge within"
467
+ with pytest.raises(np.linalg.LinAlgError, match=message):
468
+ svds(A, k, maxiter=1, solver=self.solver, rng=0)
469
+
470
+ ud, sd, vhd = svds(A, k, solver=self.solver, maxiter=maxiter, rng=0)
471
+ _check_svds(A, k, ud, sd, vhd, atol=1e-8)
472
+ assert_allclose(np.abs(ud), np.abs(u), atol=1e-8)
473
+ assert_allclose(np.abs(vhd), np.abs(vh), atol=1e-8)
474
+ assert_allclose(np.abs(sd), np.abs(s), atol=1e-9)
475
+
476
+ @pytest.mark.thread_unsafe
477
+ @pytest.mark.parametrize("rsv", (True, False, 'u', 'vh'))
478
+ @pytest.mark.parametrize("shape", ((5, 7), (6, 6), (7, 5)))
479
+ def test_svd_return_singular_vectors(self, rsv, shape):
480
+ # check that the return_singular_vectors parameter works as expected
481
+ rng = np.random.default_rng(0)
482
+ A = rng.random(shape)
483
+ k = 2
484
+ M, N = shape
485
+ u, s, vh = sorted_svd(A, k)
486
+
487
+ respect_u = True if self.solver == 'propack' else M <= N
488
+ respect_vh = True if self.solver == 'propack' else M > N
489
+
490
+ if self.solver == 'lobpcg':
491
+ with pytest.warns(UserWarning, match="The problem size"):
492
+ if rsv is False:
493
+ s2 = svds(A, k, return_singular_vectors=rsv,
494
+ solver=self.solver, rng=rng)
495
+ assert_allclose(s2, s)
496
+ elif rsv == 'u' and respect_u:
497
+ u2, s2, vh2 = svds(A, k, return_singular_vectors=rsv,
498
+ solver=self.solver, rng=rng)
499
+ assert_allclose(np.abs(u2), np.abs(u))
500
+ assert_allclose(s2, s)
501
+ assert vh2 is None
502
+ elif rsv == 'vh' and respect_vh:
503
+ u2, s2, vh2 = svds(A, k, return_singular_vectors=rsv,
504
+ solver=self.solver, rng=rng)
505
+ assert u2 is None
506
+ assert_allclose(s2, s)
507
+ assert_allclose(np.abs(vh2), np.abs(vh))
508
+ else:
509
+ u2, s2, vh2 = svds(A, k, return_singular_vectors=rsv,
510
+ solver=self.solver, rng=rng)
511
+ if u2 is not None:
512
+ assert_allclose(np.abs(u2), np.abs(u))
513
+ assert_allclose(s2, s)
514
+ if vh2 is not None:
515
+ assert_allclose(np.abs(vh2), np.abs(vh))
516
+ else:
517
+ if rsv is False:
518
+ s2 = svds(A, k, return_singular_vectors=rsv,
519
+ solver=self.solver, rng=rng)
520
+ assert_allclose(s2, s)
521
+ elif rsv == 'u' and respect_u:
522
+ u2, s2, vh2 = svds(A, k, return_singular_vectors=rsv,
523
+ solver=self.solver, rng=rng)
524
+ assert_allclose(np.abs(u2), np.abs(u))
525
+ assert_allclose(s2, s)
526
+ assert vh2 is None
527
+ elif rsv == 'vh' and respect_vh:
528
+ u2, s2, vh2 = svds(A, k, return_singular_vectors=rsv,
529
+ solver=self.solver, rng=rng)
530
+ assert u2 is None
531
+ assert_allclose(s2, s)
532
+ assert_allclose(np.abs(vh2), np.abs(vh))
533
+ else:
534
+ u2, s2, vh2 = svds(A, k, return_singular_vectors=rsv,
535
+ solver=self.solver, rng=rng)
536
+ if u2 is not None:
537
+ assert_allclose(np.abs(u2), np.abs(u))
538
+ assert_allclose(s2, s)
539
+ if vh2 is not None:
540
+ assert_allclose(np.abs(vh2), np.abs(vh))
541
+
542
+ # --- Test Basic Functionality ---
543
+ # Tests the accuracy of each solver for real and complex matrices provided
544
+ # as list, dense array, sparse matrix, and LinearOperator.
545
+
546
+ A1 = [[1, 2, 3], [3, 4, 3], [1 + 1j, 0, 2], [0, 0, 1]]
547
+ A2 = [[1, 2, 3, 8 + 5j], [3 - 2j, 4, 3, 5], [1, 0, 2, 3], [0, 0, 1, 0]]
548
+
549
+ @pytest.mark.thread_unsafe
550
+ @pytest.mark.filterwarnings("ignore:k >= N - 1",
551
+ reason="needed to demonstrate #16725")
552
+ @pytest.mark.parametrize('A', (A1, A2))
553
+ @pytest.mark.parametrize('k', range(1, 5))
554
+ # PROPACK fails a lot if @pytest.mark.parametrize('which', ("SM", "LM"))
555
+ @pytest.mark.parametrize('real', (True, False))
556
+ @pytest.mark.parametrize('transpose', (False, True))
557
+ # In gh-14299, it was suggested the `svds` should _not_ work with lists
558
+ @pytest.mark.parametrize('lo_type', (np.asarray, csc_array,
559
+ aslinearoperator))
560
+ def test_svd_simple(self, A, k, real, transpose, lo_type):
561
+
562
+ A = np.asarray(A)
563
+ A = np.real(A) if real else A
564
+ A = A.T if transpose else A
565
+ A2 = lo_type(A)
566
+
567
+ # could check for the appropriate errors, but that is tested above
568
+ if k > min(A.shape):
569
+ pytest.skip("`k` cannot be greater than `min(A.shape)`")
570
+ if self.solver != 'propack' and k >= min(A.shape):
571
+ pytest.skip("Only PROPACK supports complete SVD")
572
+ if self.solver == 'arpack' and not real and k == min(A.shape) - 1:
573
+ pytest.skip("#16725")
574
+
575
+ atol = 3e-10
576
+ if self.solver == 'propack':
577
+ atol = 3e-9 # otherwise test fails on Linux aarch64 (see gh-19855)
578
+
579
+ if self.solver == 'lobpcg':
580
+ with pytest.warns(UserWarning, match="The problem size"):
581
+ u, s, vh = svds(A2, k, solver=self.solver, rng=0)
582
+ else:
583
+ u, s, vh = svds(A2, k, solver=self.solver, rng=0)
584
+ _check_svds(A, k, u, s, vh, atol=atol)
585
+
586
+ @pytest.mark.thread_unsafe
587
+ def test_svd_linop(self):
588
+ solver = self.solver
589
+
590
+ nmks = [(6, 7, 3),
591
+ (9, 5, 4),
592
+ (10, 8, 5)]
593
+
594
+ def reorder(args):
595
+ U, s, VH = args
596
+ j = np.argsort(s)
597
+ return U[:, j], s[j], VH[j, :]
598
+
599
+ for n, m, k in nmks:
600
+ # Test svds on a LinearOperator.
601
+ A = np.random.RandomState(52).randn(n, m)
602
+ L = CheckingLinearOperator(A)
603
+
604
+ if solver == 'propack':
605
+ v0 = np.ones(n)
606
+ else:
607
+ v0 = np.ones(min(A.shape))
608
+ if solver == 'lobpcg':
609
+ with pytest.warns(UserWarning, match="The problem size"):
610
+ U1, s1, VH1 = reorder(svds(A, k, v0=v0, solver=solver, rng=0))
611
+ U2, s2, VH2 = reorder(svds(L, k, v0=v0, solver=solver, rng=0))
612
+ else:
613
+ U1, s1, VH1 = reorder(svds(A, k, v0=v0, solver=solver, rng=0))
614
+ U2, s2, VH2 = reorder(svds(L, k, v0=v0, solver=solver, rng=0))
615
+
616
+ assert_allclose(np.abs(U1), np.abs(U2))
617
+ assert_allclose(s1, s2)
618
+ assert_allclose(np.abs(VH1), np.abs(VH2))
619
+ assert_allclose(np.dot(U1, np.dot(np.diag(s1), VH1)),
620
+ np.dot(U2, np.dot(np.diag(s2), VH2)))
621
+
622
+ # Try again with which="SM".
623
+ A = np.random.RandomState(1909).randn(n, m)
624
+ L = CheckingLinearOperator(A)
625
+
626
+ # TODO: arpack crashes when v0=v0, which="SM"
627
+ kwargs = {'v0': v0} if solver not in {None, 'arpack'} else {}
628
+ if self.solver == 'lobpcg':
629
+ with pytest.warns(UserWarning, match="The problem size"):
630
+ U1, s1, VH1 = reorder(svds(A, k, which="SM", solver=solver,
631
+ rng=0, **kwargs))
632
+ U2, s2, VH2 = reorder(svds(L, k, which="SM", solver=solver,
633
+ rng=0, **kwargs))
634
+ else:
635
+ U1, s1, VH1 = reorder(svds(A, k, which="SM", solver=solver,
636
+ rng=0, **kwargs))
637
+ U2, s2, VH2 = reorder(svds(L, k, which="SM", solver=solver,
638
+ rng=0, **kwargs))
639
+
640
+ assert_allclose(np.abs(U1), np.abs(U2))
641
+ assert_allclose(s1 + 1, s2 + 1)
642
+ assert_allclose(np.abs(VH1), np.abs(VH2))
643
+ assert_allclose(np.dot(U1, np.dot(np.diag(s1), VH1)),
644
+ np.dot(U2, np.dot(np.diag(s2), VH2)))
645
+
646
+ if k < min(n, m) - 1:
647
+ # Complex input and explicit which="LM".
648
+ for (dt, eps) in [(complex, 1e-7), (np.complex64, 3e-3)]:
649
+ rng = np.random.RandomState(1648)
650
+ A = (rng.randn(n, m) + 1j * rng.randn(n, m)).astype(dt)
651
+ L = CheckingLinearOperator(A)
652
+
653
+ if self.solver == 'lobpcg':
654
+ with pytest.warns(UserWarning,
655
+ match="The problem size"):
656
+ U1, s1, VH1 = reorder(svds(A, k, which="LM",
657
+ solver=solver, rng=0))
658
+ U2, s2, VH2 = reorder(svds(L, k, which="LM",
659
+ solver=solver, rng=0))
660
+ else:
661
+ U1, s1, VH1 = reorder(svds(A, k, which="LM",
662
+ solver=solver, rng=0))
663
+ U2, s2, VH2 = reorder(svds(L, k, which="LM",
664
+ solver=solver, rng=0))
665
+
666
+ assert_allclose(np.abs(U1), np.abs(U2), rtol=eps)
667
+ assert_allclose(s1, s2, rtol=eps)
668
+ assert_allclose(np.abs(VH1), np.abs(VH2), rtol=eps)
669
+ assert_allclose(np.dot(U1, np.dot(np.diag(s1), VH1)),
670
+ np.dot(U2, np.dot(np.diag(s2), VH2)),
671
+ rtol=eps)
672
+
673
+ SHAPES = ((100, 100), (100, 101), (101, 100))
674
+
675
+ @pytest.mark.filterwarnings("ignore:Exited at iteration")
676
+ @pytest.mark.filterwarnings("ignore:Exited postprocessing")
677
+ @pytest.mark.parametrize("shape", SHAPES)
678
+ # ARPACK supports only dtype float, complex, or np.float32
679
+ @pytest.mark.parametrize("dtype", (float, complex, np.float32))
680
+ def test_small_sigma_sparse(self, shape, dtype):
681
+ # https://github.com/scipy/scipy/pull/11829
682
+ solver = self.solver
683
+ # 2do: PROPACK fails orthogonality of singular vectors
684
+ # if dtype == complex and self.solver == 'propack':
685
+ # pytest.skip("PROPACK unsupported for complex dtype")
686
+ rng = np.random.default_rng(0)
687
+ k = 5
688
+ (m, n) = shape
689
+ S = random_array(shape=(m, n), density=0.1, rng=rng)
690
+ if dtype is complex:
691
+ S = + 1j * random_array(shape=(m, n), density=0.1, rng=rng)
692
+ e = np.ones(m)
693
+ e[0:5] *= 1e1 ** np.arange(-5, 0, 1)
694
+ S = dia_array((e, 0), shape=(m, m)) @ S
695
+ S = S.astype(dtype)
696
+ u, s, vh = svds(S, k, which='SM', solver=solver, maxiter=1000, rng=0)
697
+ c_svd = False # partial SVD can be different from full SVD
698
+ _check_svds_n(S, k, u, s, vh, which="SM", check_svd=c_svd, atol=2e-1)
699
+
700
+ # --- Test Edge Cases ---
701
+ # Checks a few edge cases.
702
+ @pytest.mark.thread_unsafe
703
+ @pytest.mark.parametrize("shape", ((6, 5), (5, 5), (5, 6)))
704
+ @pytest.mark.parametrize("dtype", (float, complex))
705
+ def test_svd_LM_ones_matrix(self, shape, dtype):
706
+ # Check that svds can deal with matrix_rank less than k in LM mode.
707
+ k = 3
708
+ n, m = shape
709
+ A = np.ones((n, m), dtype=dtype)
710
+
711
+ if self.solver == 'lobpcg':
712
+ with pytest.warns(UserWarning, match="The problem size"):
713
+ U, s, VH = svds(A, k, solver=self.solver, rng=0)
714
+ else:
715
+ U, s, VH = svds(A, k, solver=self.solver, rng=0)
716
+
717
+ _check_svds(A, k, U, s, VH, check_usvh_A=True, check_svd=False)
718
+
719
+ # Check that the largest singular value is near sqrt(n*m)
720
+ # and the other singular values have been forced to zero.
721
+ assert_allclose(np.max(s), np.sqrt(n*m))
722
+ s = np.array(sorted(s)[:-1]) + 1
723
+ z = np.ones_like(s)
724
+ assert_allclose(s, z)
725
+
726
+ @pytest.mark.thread_unsafe
727
+ @pytest.mark.filterwarnings("ignore:k >= N - 1",
728
+ reason="needed to demonstrate #16725")
729
+ @pytest.mark.parametrize("shape", ((3, 4), (4, 4), (4, 3), (4, 2)))
730
+ @pytest.mark.parametrize("dtype", (float, complex))
731
+ def test_zero_matrix(self, shape, dtype):
732
+ # Check that svds can deal with matrices containing only zeros;
733
+ # see https://github.com/scipy/scipy/issues/3452/
734
+ # shape = (4, 2) is included because it is the particular case
735
+ # reported in the issue
736
+ k = 1
737
+ n, m = shape
738
+ A = np.zeros((n, m), dtype=dtype)
739
+
740
+ if (self.solver == 'arpack'):
741
+ pytest.skip('See gh-21110.')
742
+
743
+ if (self.solver == 'arpack' and dtype is complex
744
+ and k == min(A.shape) - 1):
745
+ pytest.skip("#16725")
746
+
747
+ if self.solver == 'propack':
748
+ pytest.skip("PROPACK failures unrelated to PR #16712")
749
+
750
+ if self.solver == 'lobpcg':
751
+ with pytest.warns(UserWarning, match="The problem size"):
752
+ U, s, VH = svds(A, k, solver=self.solver, rng=0)
753
+ else:
754
+ U, s, VH = svds(A, k, solver=self.solver, rng=0)
755
+
756
+ # Check some generic properties of svd.
757
+ _check_svds(A, k, U, s, VH, check_usvh_A=True, check_svd=False)
758
+
759
+ # Check that the singular values are zero.
760
+ assert_array_equal(s, 0)
761
+
762
+ @pytest.mark.parametrize("shape", ((20, 20), (20, 21), (21, 20)))
763
+ # ARPACK supports only dtype float, complex, or np.float32
764
+ @pytest.mark.parametrize("dtype", (float, complex, np.float32))
765
+ @pytest.mark.filterwarnings("ignore:Exited",
766
+ reason="Ignore LOBPCG early exit.")
767
+ def test_small_sigma(self, shape, dtype):
768
+ rng = np.random.default_rng(179847540)
769
+ A = rng.random(shape).astype(dtype)
770
+ u, _, vh = svd(A, full_matrices=False)
771
+ if dtype == np.float32:
772
+ e = 10.0
773
+ else:
774
+ e = 100.0
775
+ t = e**(-np.arange(len(vh))).astype(dtype)
776
+ A = (u*t).dot(vh)
777
+ k = 4
778
+ u, s, vh = svds(A, k, solver=self.solver, maxiter=100, rng=0)
779
+ t = np.sum(s > 0)
780
+ assert_equal(t, k)
781
+ # LOBPCG needs larger atol and rtol to pass
782
+ _check_svds_n(A, k, u, s, vh, atol=1e-3, rtol=1e0, check_svd=False)
783
+
784
+ # ARPACK supports only dtype float, complex, or np.float32
785
+ @pytest.mark.filterwarnings("ignore:The problem size")
786
+ @pytest.mark.parametrize("dtype", (float, complex, np.float32))
787
+ def test_small_sigma2(self, dtype):
788
+ rng = np.random.default_rng(179847540)
789
+ # create a 10x10 singular matrix with a 4-dim null space
790
+ dim = 4
791
+ size = 10
792
+ x = rng.random((size, size-dim))
793
+ y = x[:, :dim] * rng.random(dim)
794
+ mat = np.hstack((x, y))
795
+ mat = mat.astype(dtype)
796
+
797
+ nz = null_space(mat)
798
+ assert_equal(nz.shape[1], dim)
799
+
800
+ # Tolerances atol and rtol adjusted to pass np.float32
801
+ # Use non-sparse svd
802
+ u, s, vh = svd(mat)
803
+ # Singular values are 0:
804
+ assert_allclose(s[-dim:], 0, atol=1e-6, rtol=1e0)
805
+ # Smallest right singular vectors in null space:
806
+ assert_allclose(mat @ vh[-dim:, :].T, 0, atol=1e-6, rtol=1e0)
807
+
808
+ # Smallest singular values should be 0
809
+ sp_mat = csc_array(mat)
810
+ su, ss, svh = svds(sp_mat, k=dim, which='SM', solver=self.solver, rng=0)
811
+ # Smallest dim singular values are 0:
812
+ assert_allclose(ss, 0, atol=1e-5, rtol=1e0)
813
+ # Smallest singular vectors via svds in null space:
814
+ n, m = mat.shape
815
+ if n < m: # else the assert fails with some libraries unclear why
816
+ assert_allclose(sp_mat.transpose() @ su, 0, atol=1e-5, rtol=1e0)
817
+ assert_allclose(sp_mat @ svh.T, 0, atol=1e-5, rtol=1e0)
818
+
819
+ # --- Perform tests with each solver ---
820
+
821
+
822
+ class Test_SVDS_once:
823
+ @pytest.mark.parametrize("solver", ['ekki', object])
824
+ def test_svds_input_validation_solver(self, solver):
825
+ message = "solver must be one of"
826
+ with pytest.raises(ValueError, match=message):
827
+ svds(np.ones((3, 4)), k=2, solver=solver, rng=0)
828
+
829
+
830
+ class Test_SVDS_ARPACK(SVDSCommonTests):
831
+
832
+ def setup_method(self):
833
+ self.solver = 'arpack'
834
+
835
+ @pytest.mark.parametrize("ncv", list(range(-1, 8)) + [4.5, "5"])
836
+ def test_svds_input_validation_ncv_1(self, ncv):
837
+ rng = np.random.default_rng(0)
838
+ A = rng.random((6, 7))
839
+ k = 3
840
+ if ncv in {4, 5}:
841
+ u, s, vh = svds(A, k=k, ncv=ncv, solver=self.solver, rng=0)
842
+ # partial decomposition, so don't check that u@diag(s)@vh=A;
843
+ # do check that scipy.sparse.linalg.svds ~ scipy.linalg.svd
844
+ _check_svds(A, k, u, s, vh)
845
+ else:
846
+ message = ("`ncv` must be an integer satisfying")
847
+ with pytest.raises(ValueError, match=message):
848
+ svds(A, k=k, ncv=ncv, solver=self.solver, rng=0)
849
+
850
+ def test_svds_input_validation_ncv_2(self):
851
+ # I think the stack trace is reasonable when `ncv` can't be converted
852
+ # to an int.
853
+ message = "int() argument must be a"
854
+ with pytest.raises(TypeError, match=re.escape(message)):
855
+ svds(np.eye(10), ncv=[], solver=self.solver, rng=0)
856
+
857
+ message = "invalid literal for int()"
858
+ with pytest.raises(ValueError, match=message):
859
+ svds(np.eye(10), ncv="hi", solver=self.solver, rng=0)
860
+
861
+ # I can't see a robust relationship between `ncv` and relevant outputs
862
+ # (e.g. accuracy, time), so no test of the parameter.
863
+
864
+
865
+ class Test_SVDS_LOBPCG(SVDSCommonTests):
866
+
867
+ def setup_method(self):
868
+ self.solver = 'lobpcg'
869
+
870
+
871
+ class Test_SVDS_PROPACK(SVDSCommonTests):
872
+
873
+ def setup_method(self):
874
+ self.solver = 'propack'
875
+
876
+ def test_svd_LM_ones_matrix(self):
877
+ message = ("PROPACK does not return orthonormal singular vectors "
878
+ "associated with zero singular values.")
879
+ # There are some other issues with this matrix of all ones, e.g.
880
+ # `which='sm'` and `k=1` returns the largest singular value
881
+ pytest.xfail(message)
882
+
883
+ def test_svd_LM_zeros_matrix(self):
884
+ message = ("PROPACK does not return orthonormal singular vectors "
885
+ "associated with zero singular values.")
886
+ pytest.xfail(message)
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_expm_multiply.py ADDED
@@ -0,0 +1,816 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compute the action of the matrix exponential."""
2
+ from warnings import warn
3
+
4
+ import numpy as np
5
+
6
+ import scipy.linalg
7
+ import scipy.sparse.linalg
8
+ from scipy.linalg._decomp_qr import qr
9
+ from scipy.sparse._sputils import is_pydata_spmatrix
10
+ from scipy.sparse.linalg import aslinearoperator
11
+ from scipy.sparse.linalg._interface import IdentityOperator
12
+ from scipy.sparse.linalg._onenormest import onenormest
13
+
14
+ __all__ = ['expm_multiply']
15
+
16
+
17
+ def _exact_inf_norm(A):
18
+ # A compatibility function which should eventually disappear.
19
+ if scipy.sparse.issparse(A):
20
+ return max(abs(A).sum(axis=1).flat)
21
+ elif is_pydata_spmatrix(A):
22
+ return max(abs(A).sum(axis=1))
23
+ else:
24
+ return np.linalg.norm(A, np.inf)
25
+
26
+
27
+ def _exact_1_norm(A):
28
+ # A compatibility function which should eventually disappear.
29
+ if scipy.sparse.issparse(A):
30
+ return max(abs(A).sum(axis=0).flat)
31
+ elif is_pydata_spmatrix(A):
32
+ return max(abs(A).sum(axis=0))
33
+ else:
34
+ return np.linalg.norm(A, 1)
35
+
36
+
37
+ def _trace(A):
38
+ # A compatibility function which should eventually disappear.
39
+ if is_pydata_spmatrix(A):
40
+ return A.to_scipy_sparse().trace()
41
+ else:
42
+ return A.trace()
43
+
44
+
45
+ def traceest(A, m3, seed=None):
46
+ """Estimate `np.trace(A)` using `3*m3` matrix-vector products.
47
+
48
+ The result is not deterministic.
49
+
50
+ Parameters
51
+ ----------
52
+ A : LinearOperator
53
+ Linear operator whose trace will be estimated. Has to be square.
54
+ m3 : int
55
+ Number of matrix-vector products divided by 3 used to estimate the
56
+ trace.
57
+ seed : optional
58
+ Seed for `numpy.random.default_rng`.
59
+ Can be provided to obtain deterministic results.
60
+
61
+ Returns
62
+ -------
63
+ trace : LinearOperator.dtype
64
+ Estimate of the trace
65
+
66
+ Notes
67
+ -----
68
+ This is the Hutch++ algorithm given in [1]_.
69
+
70
+ References
71
+ ----------
72
+ .. [1] Meyer, Raphael A., Cameron Musco, Christopher Musco, and David P.
73
+ Woodruff. "Hutch++: Optimal Stochastic Trace Estimation." In Symposium
74
+ on Simplicity in Algorithms (SOSA), pp. 142-155. Society for Industrial
75
+ and Applied Mathematics, 2021
76
+ https://doi.org/10.1137/1.9781611976496.16
77
+
78
+ """
79
+ rng = np.random.default_rng(seed)
80
+ if len(A.shape) != 2 or A.shape[-1] != A.shape[-2]:
81
+ raise ValueError("Expected A to be like a square matrix.")
82
+ n = A.shape[-1]
83
+ S = rng.choice([-1.0, +1.0], [n, m3])
84
+ Q, _ = qr(A.matmat(S), overwrite_a=True, mode='economic')
85
+ trQAQ = np.trace(Q.conj().T @ A.matmat(Q))
86
+ G = rng.choice([-1, +1], [n, m3])
87
+ right = G - Q@(Q.conj().T @ G)
88
+ trGAG = np.trace(right.conj().T @ A.matmat(right))
89
+ return trQAQ + trGAG/m3
90
+
91
+
92
+ def _ident_like(A):
93
+ # A compatibility function which should eventually disappear.
94
+ if scipy.sparse.issparse(A):
95
+ # Creates a sparse matrix in dia format
96
+ out = scipy.sparse.eye(A.shape[0], A.shape[1], dtype=A.dtype)
97
+ if scipy.sparse.issparse(A):
98
+ return out.asformat(A.format)
99
+ return scipy.sparse.dia_array(out).asformat(A.format)
100
+ elif is_pydata_spmatrix(A):
101
+ import sparse
102
+ return sparse.eye(A.shape[0], A.shape[1], dtype=A.dtype)
103
+ elif isinstance(A, scipy.sparse.linalg.LinearOperator):
104
+ return IdentityOperator(A.shape, dtype=A.dtype)
105
+ else:
106
+ return np.eye(A.shape[0], A.shape[1], dtype=A.dtype)
107
+
108
+
109
+ def expm_multiply(A, B, start=None, stop=None, num=None,
110
+ endpoint=None, traceA=None):
111
+ """
112
+ Compute the action of the matrix exponential of A on B.
113
+
114
+ Parameters
115
+ ----------
116
+ A : transposable linear operator
117
+ The operator whose exponential is of interest.
118
+ B : ndarray, sparse array
119
+ The matrix or vector to be multiplied by the matrix exponential of A.
120
+ start : scalar, optional
121
+ The starting time point of the sequence.
122
+ stop : scalar, optional
123
+ The end time point of the sequence, unless `endpoint` is set to False.
124
+ In that case, the sequence consists of all but the last of ``num + 1``
125
+ evenly spaced time points, so that `stop` is excluded.
126
+ Note that the step size changes when `endpoint` is False.
127
+ num : int, optional
128
+ Number of time points to use.
129
+ endpoint : bool, optional
130
+ If True, `stop` is the last time point. Otherwise, it is not included.
131
+ traceA : scalar, optional
132
+ Trace of `A`. If not given the trace is estimated for linear operators,
133
+ or calculated exactly for sparse matrices. It is used to precondition
134
+ `A`, thus an approximate trace is acceptable.
135
+ For linear operators, `traceA` should be provided to ensure performance
136
+ as the estimation is not guaranteed to be reliable for all cases.
137
+
138
+ .. versionadded:: 1.9.0
139
+
140
+ Returns
141
+ -------
142
+ expm_A_B : ndarray
143
+ The result of the action :math:`e^{t_k A} B`.
144
+
145
+ Warns
146
+ -----
147
+ UserWarning
148
+ If `A` is a linear operator and ``traceA=None`` (default).
149
+
150
+ Notes
151
+ -----
152
+ The optional arguments defining the sequence of evenly spaced time points
153
+ are compatible with the arguments of `numpy.linspace`.
154
+
155
+ The output ndarray shape is somewhat complicated so I explain it here.
156
+ The ndim of the output could be either 1, 2, or 3.
157
+ It would be 1 if you are computing the expm action on a single vector
158
+ at a single time point.
159
+ It would be 2 if you are computing the expm action on a vector
160
+ at multiple time points, or if you are computing the expm action
161
+ on a matrix at a single time point.
162
+ It would be 3 if you want the action on a matrix with multiple
163
+ columns at multiple time points.
164
+ If multiple time points are requested, expm_A_B[0] will always
165
+ be the action of the expm at the first time point,
166
+ regardless of whether the action is on a vector or a matrix.
167
+
168
+ References
169
+ ----------
170
+ .. [1] Awad H. Al-Mohy and Nicholas J. Higham (2011)
171
+ "Computing the Action of the Matrix Exponential,
172
+ with an Application to Exponential Integrators."
173
+ SIAM Journal on Scientific Computing,
174
+ 33 (2). pp. 488-511. ISSN 1064-8275
175
+ http://eprints.ma.man.ac.uk/1591/
176
+
177
+ .. [2] Nicholas J. Higham and Awad H. Al-Mohy (2010)
178
+ "Computing Matrix Functions."
179
+ Acta Numerica,
180
+ 19. 159-208. ISSN 0962-4929
181
+ http://eprints.ma.man.ac.uk/1451/
182
+
183
+ Examples
184
+ --------
185
+ >>> import numpy as np
186
+ >>> from scipy.sparse import csc_array
187
+ >>> from scipy.sparse.linalg import expm, expm_multiply
188
+ >>> A = csc_array([[1, 0], [0, 1]])
189
+ >>> A.toarray()
190
+ array([[1, 0],
191
+ [0, 1]], dtype=int64)
192
+ >>> B = np.array([np.exp(-1.), np.exp(-2.)])
193
+ >>> B
194
+ array([ 0.36787944, 0.13533528])
195
+ >>> expm_multiply(A, B, start=1, stop=2, num=3, endpoint=True)
196
+ array([[ 1. , 0.36787944],
197
+ [ 1.64872127, 0.60653066],
198
+ [ 2.71828183, 1. ]])
199
+ >>> expm(A).dot(B) # Verify 1st timestep
200
+ array([ 1. , 0.36787944])
201
+ >>> expm(1.5*A).dot(B) # Verify 2nd timestep
202
+ array([ 1.64872127, 0.60653066])
203
+ >>> expm(2*A).dot(B) # Verify 3rd timestep
204
+ array([ 2.71828183, 1. ])
205
+ """
206
+ if all(arg is None for arg in (start, stop, num, endpoint)):
207
+ X = _expm_multiply_simple(A, B, traceA=traceA)
208
+ else:
209
+ X, status = _expm_multiply_interval(A, B, start, stop, num,
210
+ endpoint, traceA=traceA)
211
+ return X
212
+
213
+
214
+ def _expm_multiply_simple(A, B, t=1.0, traceA=None, balance=False):
215
+ """
216
+ Compute the action of the matrix exponential at a single time point.
217
+
218
+ Parameters
219
+ ----------
220
+ A : transposable linear operator
221
+ The operator whose exponential is of interest.
222
+ B : ndarray
223
+ The matrix to be multiplied by the matrix exponential of A.
224
+ t : float
225
+ A time point.
226
+ traceA : scalar, optional
227
+ Trace of `A`. If not given the trace is estimated for linear operators,
228
+ or calculated exactly for sparse matrices. It is used to precondition
229
+ `A`, thus an approximate trace is acceptable
230
+ balance : bool
231
+ Indicates whether or not to apply balancing.
232
+
233
+ Returns
234
+ -------
235
+ F : ndarray
236
+ :math:`e^{t A} B`
237
+
238
+ Notes
239
+ -----
240
+ This is algorithm (3.2) in Al-Mohy and Higham (2011).
241
+
242
+ """
243
+ if balance:
244
+ raise NotImplementedError
245
+ if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
246
+ raise ValueError('expected A to be like a square matrix')
247
+ if A.shape[1] != B.shape[0]:
248
+ raise ValueError(f'shapes of matrices A {A.shape} and B {B.shape}'
249
+ ' are incompatible')
250
+ ident = _ident_like(A)
251
+ is_linear_operator = isinstance(A, scipy.sparse.linalg.LinearOperator)
252
+ n = A.shape[0]
253
+ if len(B.shape) == 1:
254
+ n0 = 1
255
+ elif len(B.shape) == 2:
256
+ n0 = B.shape[1]
257
+ else:
258
+ raise ValueError('expected B to be like a matrix or a vector')
259
+ u_d = 2**-53
260
+ tol = u_d
261
+ if traceA is None:
262
+ if is_linear_operator:
263
+ warn("Trace of LinearOperator not available, it will be estimated."
264
+ " Provide `traceA` to ensure performance.", stacklevel=3)
265
+ # m3=1 is bit arbitrary choice, a more accurate trace (larger m3) might
266
+ # speed up exponential calculation, but trace estimation is more costly
267
+ traceA = traceest(A, m3=1) if is_linear_operator else _trace(A)
268
+ mu = traceA / float(n)
269
+ A = A - mu * ident
270
+ A_1_norm = onenormest(A) if is_linear_operator else _exact_1_norm(A)
271
+ if t*A_1_norm == 0:
272
+ m_star, s = 0, 1
273
+ else:
274
+ ell = 2
275
+ norm_info = LazyOperatorNormInfo(t*A, A_1_norm=t*A_1_norm, ell=ell)
276
+ m_star, s = _fragment_3_1(norm_info, n0, tol, ell=ell)
277
+ return _expm_multiply_simple_core(A, B, t, mu, m_star, s, tol, balance)
278
+
279
+
280
+ def _expm_multiply_simple_core(A, B, t, mu, m_star, s, tol=None, balance=False):
281
+ """
282
+ A helper function.
283
+ """
284
+ if balance:
285
+ raise NotImplementedError
286
+ if tol is None:
287
+ u_d = 2 ** -53
288
+ tol = u_d
289
+ F = B
290
+ eta = np.exp(t*mu / float(s))
291
+ for i in range(s):
292
+ c1 = _exact_inf_norm(B)
293
+ for j in range(m_star):
294
+ coeff = t / float(s*(j+1))
295
+ B = coeff * A.dot(B)
296
+ c2 = _exact_inf_norm(B)
297
+ F = F + B
298
+ if c1 + c2 <= tol * _exact_inf_norm(F):
299
+ break
300
+ c1 = c2
301
+ F = eta * F
302
+ B = F
303
+ return F
304
+
305
+
306
+ # This table helps to compute bounds.
307
+ # They seem to have been difficult to calculate, involving symbolic
308
+ # manipulation of equations, followed by numerical root finding.
309
+ _theta = {
310
+ # The first 30 values are from table A.3 of Computing Matrix Functions.
311
+ 1: 2.29e-16,
312
+ 2: 2.58e-8,
313
+ 3: 1.39e-5,
314
+ 4: 3.40e-4,
315
+ 5: 2.40e-3,
316
+ 6: 9.07e-3,
317
+ 7: 2.38e-2,
318
+ 8: 5.00e-2,
319
+ 9: 8.96e-2,
320
+ 10: 1.44e-1,
321
+ # 11
322
+ 11: 2.14e-1,
323
+ 12: 3.00e-1,
324
+ 13: 4.00e-1,
325
+ 14: 5.14e-1,
326
+ 15: 6.41e-1,
327
+ 16: 7.81e-1,
328
+ 17: 9.31e-1,
329
+ 18: 1.09,
330
+ 19: 1.26,
331
+ 20: 1.44,
332
+ # 21
333
+ 21: 1.62,
334
+ 22: 1.82,
335
+ 23: 2.01,
336
+ 24: 2.22,
337
+ 25: 2.43,
338
+ 26: 2.64,
339
+ 27: 2.86,
340
+ 28: 3.08,
341
+ 29: 3.31,
342
+ 30: 3.54,
343
+ # The rest are from table 3.1 of
344
+ # Computing the Action of the Matrix Exponential.
345
+ 35: 4.7,
346
+ 40: 6.0,
347
+ 45: 7.2,
348
+ 50: 8.5,
349
+ 55: 9.9,
350
+ }
351
+
352
+
353
+ def _onenormest_matrix_power(A, p,
354
+ t=2, itmax=5, compute_v=False, compute_w=False):
355
+ """
356
+ Efficiently estimate the 1-norm of A^p.
357
+
358
+ Parameters
359
+ ----------
360
+ A : ndarray
361
+ Matrix whose 1-norm of a power is to be computed.
362
+ p : int
363
+ Non-negative integer power.
364
+ t : int, optional
365
+ A positive parameter controlling the tradeoff between
366
+ accuracy versus time and memory usage.
367
+ Larger values take longer and use more memory
368
+ but give more accurate output.
369
+ itmax : int, optional
370
+ Use at most this many iterations.
371
+ compute_v : bool, optional
372
+ Request a norm-maximizing linear operator input vector if True.
373
+ compute_w : bool, optional
374
+ Request a norm-maximizing linear operator output vector if True.
375
+
376
+ Returns
377
+ -------
378
+ est : float
379
+ An underestimate of the 1-norm of the sparse matrix.
380
+ v : ndarray, optional
381
+ The vector such that ||Av||_1 == est*||v||_1.
382
+ It can be thought of as an input to the linear operator
383
+ that gives an output with particularly large norm.
384
+ w : ndarray, optional
385
+ The vector Av which has relatively large 1-norm.
386
+ It can be thought of as an output of the linear operator
387
+ that is relatively large in norm compared to the input.
388
+
389
+ """
390
+ #XXX Eventually turn this into an API function in the _onenormest module,
391
+ #XXX and remove its underscore,
392
+ #XXX but wait until expm_multiply goes into scipy.
393
+ from scipy.sparse.linalg._onenormest import onenormest
394
+ return onenormest(aslinearoperator(A) ** p)
395
+
396
+ class LazyOperatorNormInfo:
397
+ """
398
+ Information about an operator is lazily computed.
399
+
400
+ The information includes the exact 1-norm of the operator,
401
+ in addition to estimates of 1-norms of powers of the operator.
402
+ This uses the notation of Computing the Action (2011).
403
+ This class is specialized enough to probably not be of general interest
404
+ outside of this module.
405
+
406
+ """
407
+
408
+ def __init__(self, A, A_1_norm=None, ell=2, scale=1):
409
+ """
410
+ Provide the operator and some norm-related information.
411
+
412
+ Parameters
413
+ ----------
414
+ A : linear operator
415
+ The operator of interest.
416
+ A_1_norm : float, optional
417
+ The exact 1-norm of A.
418
+ ell : int, optional
419
+ A technical parameter controlling norm estimation quality.
420
+ scale : int, optional
421
+ If specified, return the norms of scale*A instead of A.
422
+
423
+ """
424
+ self._A = A
425
+ self._A_1_norm = A_1_norm
426
+ self._ell = ell
427
+ self._d = {}
428
+ self._scale = scale
429
+
430
+ def set_scale(self,scale):
431
+ """
432
+ Set the scale parameter.
433
+ """
434
+ self._scale = scale
435
+
436
+ def onenorm(self):
437
+ """
438
+ Compute the exact 1-norm.
439
+ """
440
+ if self._A_1_norm is None:
441
+ self._A_1_norm = _exact_1_norm(self._A)
442
+ return self._scale*self._A_1_norm
443
+
444
+ def d(self, p):
445
+ """
446
+ Lazily estimate :math:`d_p(A) ~= || A^p ||^(1/p)`
447
+ where :math:`||.||` is the 1-norm.
448
+ """
449
+ if p not in self._d:
450
+ est = _onenormest_matrix_power(self._A, p, self._ell)
451
+ self._d[p] = est ** (1.0 / p)
452
+ return self._scale*self._d[p]
453
+
454
+ def alpha(self, p):
455
+ """
456
+ Lazily compute max(d(p), d(p+1)).
457
+ """
458
+ return max(self.d(p), self.d(p+1))
459
+
460
+ def _compute_cost_div_m(m, p, norm_info):
461
+ """
462
+ A helper function for computing bounds.
463
+
464
+ This is equation (3.10).
465
+ It measures cost in terms of the number of required matrix products.
466
+
467
+ Parameters
468
+ ----------
469
+ m : int
470
+ A valid key of _theta.
471
+ p : int
472
+ A matrix power.
473
+ norm_info : LazyOperatorNormInfo
474
+ Information about 1-norms of related operators.
475
+
476
+ Returns
477
+ -------
478
+ cost_div_m : int
479
+ Required number of matrix products divided by m.
480
+
481
+ """
482
+ return int(np.ceil(norm_info.alpha(p) / _theta[m]))
483
+
484
+
485
+ def _compute_p_max(m_max):
486
+ """
487
+ Compute the largest positive integer p such that p*(p-1) <= m_max + 1.
488
+
489
+ Do this in a slightly dumb way, but safe and not too slow.
490
+
491
+ Parameters
492
+ ----------
493
+ m_max : int
494
+ A count related to bounds.
495
+
496
+ """
497
+ sqrt_m_max = np.sqrt(m_max)
498
+ p_low = int(np.floor(sqrt_m_max))
499
+ p_high = int(np.ceil(sqrt_m_max + 1))
500
+ return max(p for p in range(p_low, p_high+1) if p*(p-1) <= m_max + 1)
501
+
502
+
503
+ def _fragment_3_1(norm_info, n0, tol, m_max=55, ell=2):
504
+ """
505
+ A helper function for the _expm_multiply_* functions.
506
+
507
+ Parameters
508
+ ----------
509
+ norm_info : LazyOperatorNormInfo
510
+ Information about norms of certain linear operators of interest.
511
+ n0 : int
512
+ Number of columns in the _expm_multiply_* B matrix.
513
+ tol : float
514
+ Expected to be
515
+ :math:`2^{-24}` for single precision or
516
+ :math:`2^{-53}` for double precision.
517
+ m_max : int
518
+ A value related to a bound.
519
+ ell : int
520
+ The number of columns used in the 1-norm approximation.
521
+ This is usually taken to be small, maybe between 1 and 5.
522
+
523
+ Returns
524
+ -------
525
+ best_m : int
526
+ Related to bounds for error control.
527
+ best_s : int
528
+ Amount of scaling.
529
+
530
+ Notes
531
+ -----
532
+ This is code fragment (3.1) in Al-Mohy and Higham (2011).
533
+ The discussion of default values for m_max and ell
534
+ is given between the definitions of equation (3.11)
535
+ and the definition of equation (3.12).
536
+
537
+ """
538
+ if ell < 1:
539
+ raise ValueError('expected ell to be a positive integer')
540
+ best_m = None
541
+ best_s = None
542
+ if _condition_3_13(norm_info.onenorm(), n0, m_max, ell):
543
+ for m, theta in _theta.items():
544
+ s = int(np.ceil(norm_info.onenorm() / theta))
545
+ if best_m is None or m * s < best_m * best_s:
546
+ best_m = m
547
+ best_s = s
548
+ else:
549
+ # Equation (3.11).
550
+ for p in range(2, _compute_p_max(m_max) + 1):
551
+ for m in range(p*(p-1)-1, m_max+1):
552
+ if m in _theta:
553
+ s = _compute_cost_div_m(m, p, norm_info)
554
+ if best_m is None or m * s < best_m * best_s:
555
+ best_m = m
556
+ best_s = s
557
+ best_s = max(best_s, 1)
558
+ return best_m, best_s
559
+
560
+
561
+ def _condition_3_13(A_1_norm, n0, m_max, ell):
562
+ """
563
+ A helper function for the _expm_multiply_* functions.
564
+
565
+ Parameters
566
+ ----------
567
+ A_1_norm : float
568
+ The precomputed 1-norm of A.
569
+ n0 : int
570
+ Number of columns in the _expm_multiply_* B matrix.
571
+ m_max : int
572
+ A value related to a bound.
573
+ ell : int
574
+ The number of columns used in the 1-norm approximation.
575
+ This is usually taken to be small, maybe between 1 and 5.
576
+
577
+ Returns
578
+ -------
579
+ value : bool
580
+ Indicates whether or not the condition has been met.
581
+
582
+ Notes
583
+ -----
584
+ This is condition (3.13) in Al-Mohy and Higham (2011).
585
+
586
+ """
587
+
588
+ # This is the rhs of equation (3.12).
589
+ p_max = _compute_p_max(m_max)
590
+ a = 2 * ell * p_max * (p_max + 3)
591
+
592
+ # Evaluate the condition (3.13).
593
+ b = _theta[m_max] / float(n0 * m_max)
594
+ return A_1_norm <= a * b
595
+
596
+
597
+ def _expm_multiply_interval(A, B, start=None, stop=None, num=None,
598
+ endpoint=None, traceA=None, balance=False,
599
+ status_only=False):
600
+ """
601
+ Compute the action of the matrix exponential at multiple time points.
602
+
603
+ Parameters
604
+ ----------
605
+ A : transposable linear operator
606
+ The operator whose exponential is of interest.
607
+ B : ndarray
608
+ The matrix to be multiplied by the matrix exponential of A.
609
+ start : scalar, optional
610
+ The starting time point of the sequence.
611
+ stop : scalar, optional
612
+ The end time point of the sequence, unless `endpoint` is set to False.
613
+ In that case, the sequence consists of all but the last of ``num + 1``
614
+ evenly spaced time points, so that `stop` is excluded.
615
+ Note that the step size changes when `endpoint` is False.
616
+ num : int, optional
617
+ Number of time points to use.
618
+ traceA : scalar, optional
619
+ Trace of `A`. If not given the trace is estimated for linear operators,
620
+ or calculated exactly for sparse matrices. It is used to precondition
621
+ `A`, thus an approximate trace is acceptable
622
+ endpoint : bool, optional
623
+ If True, `stop` is the last time point. Otherwise, it is not included.
624
+ balance : bool
625
+ Indicates whether or not to apply balancing.
626
+ status_only : bool
627
+ A flag that is set to True for some debugging and testing operations.
628
+
629
+ Returns
630
+ -------
631
+ F : ndarray
632
+ :math:`e^{t_k A} B`
633
+ status : int
634
+ An integer status for testing and debugging.
635
+
636
+ Notes
637
+ -----
638
+ This is algorithm (5.2) in Al-Mohy and Higham (2011).
639
+
640
+ There seems to be a typo, where line 15 of the algorithm should be
641
+ moved to line 6.5 (between lines 6 and 7).
642
+
643
+ """
644
+ if balance:
645
+ raise NotImplementedError
646
+ if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
647
+ raise ValueError('expected A to be like a square matrix')
648
+ if A.shape[1] != B.shape[0]:
649
+ raise ValueError(f'shapes of matrices A {A.shape} and B {B.shape}'
650
+ ' are incompatible')
651
+ ident = _ident_like(A)
652
+ is_linear_operator = isinstance(A, scipy.sparse.linalg.LinearOperator)
653
+ n = A.shape[0]
654
+ if len(B.shape) == 1:
655
+ n0 = 1
656
+ elif len(B.shape) == 2:
657
+ n0 = B.shape[1]
658
+ else:
659
+ raise ValueError('expected B to be like a matrix or a vector')
660
+ u_d = 2**-53
661
+ tol = u_d
662
+ if traceA is None:
663
+ if is_linear_operator:
664
+ warn("Trace of LinearOperator not available, it will be estimated."
665
+ " Provide `traceA` to ensure performance.", stacklevel=3)
666
+ # m3=5 is bit arbitrary choice, a more accurate trace (larger m3) might
667
+ # speed up exponential calculation, but trace estimation is also costly
668
+ # an educated guess would need to consider the number of time points
669
+ traceA = traceest(A, m3=5) if is_linear_operator else _trace(A)
670
+ mu = traceA / float(n)
671
+
672
+ # Get the linspace samples, attempting to preserve the linspace defaults.
673
+ linspace_kwargs = {'retstep': True}
674
+ if num is not None:
675
+ linspace_kwargs['num'] = num
676
+ if endpoint is not None:
677
+ linspace_kwargs['endpoint'] = endpoint
678
+ samples, step = np.linspace(start, stop, **linspace_kwargs)
679
+
680
+ # Convert the linspace output to the notation used by the publication.
681
+ nsamples = len(samples)
682
+ if nsamples < 2:
683
+ raise ValueError('at least two time points are required')
684
+ q = nsamples - 1
685
+ h = step
686
+ t_0 = samples[0]
687
+ t_q = samples[q]
688
+
689
+ # Define the output ndarray.
690
+ # Use an ndim=3 shape, such that the last two indices
691
+ # are the ones that may be involved in level 3 BLAS operations.
692
+ X_shape = (nsamples,) + B.shape
693
+ X = np.empty(X_shape, dtype=np.result_type(A.dtype, B.dtype, float))
694
+ t = t_q - t_0
695
+ A = A - mu * ident
696
+ A_1_norm = onenormest(A) if is_linear_operator else _exact_1_norm(A)
697
+ ell = 2
698
+ norm_info = LazyOperatorNormInfo(t*A, A_1_norm=t*A_1_norm, ell=ell)
699
+ if t*A_1_norm == 0:
700
+ m_star, s = 0, 1
701
+ else:
702
+ m_star, s = _fragment_3_1(norm_info, n0, tol, ell=ell)
703
+
704
+ # Compute the expm action up to the initial time point.
705
+ action_t0 = _expm_multiply_simple_core(A, B, t_0, mu, m_star, s)
706
+ if scipy.sparse.issparse(action_t0):
707
+ action_t0 = action_t0.toarray()
708
+ elif is_pydata_spmatrix(action_t0):
709
+ action_t0 = action_t0.todense()
710
+ X[0] = action_t0
711
+
712
+ # Compute the expm action at the rest of the time points.
713
+ if q <= s:
714
+ if status_only:
715
+ return 0
716
+ else:
717
+ return _expm_multiply_interval_core_0(A, X,
718
+ h, mu, q, norm_info, tol, ell,n0)
719
+ elif not (q % s):
720
+ if status_only:
721
+ return 1
722
+ else:
723
+ return _expm_multiply_interval_core_1(A, X,
724
+ h, mu, m_star, s, q, tol)
725
+ elif (q % s):
726
+ if status_only:
727
+ return 2
728
+ else:
729
+ return _expm_multiply_interval_core_2(A, X,
730
+ h, mu, m_star, s, q, tol)
731
+ else:
732
+ raise Exception('internal error')
733
+
734
+
735
+ def _expm_multiply_interval_core_0(A, X, h, mu, q, norm_info, tol, ell, n0):
736
+ """
737
+ A helper function, for the case q <= s.
738
+ """
739
+
740
+ # Compute the new values of m_star and s which should be applied
741
+ # over intervals of size t/q
742
+ if norm_info.onenorm() == 0:
743
+ m_star, s = 0, 1
744
+ else:
745
+ norm_info.set_scale(1./q)
746
+ m_star, s = _fragment_3_1(norm_info, n0, tol, ell=ell)
747
+ norm_info.set_scale(1)
748
+
749
+ for k in range(q):
750
+ X[k+1] = _expm_multiply_simple_core(A, X[k], h, mu, m_star, s)
751
+ return X, 0
752
+
753
+
754
+ def _expm_multiply_interval_core_1(A, X, h, mu, m_star, s, q, tol):
755
+ """
756
+ A helper function, for the case q > s and q % s == 0.
757
+ """
758
+ d = q // s
759
+ input_shape = X.shape[1:]
760
+ K_shape = (m_star + 1, ) + input_shape
761
+ K = np.empty(K_shape, dtype=X.dtype)
762
+ for i in range(s):
763
+ Z = X[i*d]
764
+ K[0] = Z
765
+ high_p = 0
766
+ for k in range(1, d+1):
767
+ F = K[0]
768
+ c1 = _exact_inf_norm(F)
769
+ for p in range(1, m_star+1):
770
+ if p > high_p:
771
+ K[p] = h * A.dot(K[p-1]) / float(p)
772
+ coeff = float(pow(k, p))
773
+ F = F + coeff * K[p]
774
+ inf_norm_K_p_1 = _exact_inf_norm(K[p])
775
+ c2 = coeff * inf_norm_K_p_1
776
+ if c1 + c2 <= tol * _exact_inf_norm(F):
777
+ break
778
+ c1 = c2
779
+ X[k + i*d] = np.exp(k*h*mu) * F
780
+ return X, 1
781
+
782
+
783
+ def _expm_multiply_interval_core_2(A, X, h, mu, m_star, s, q, tol):
784
+ """
785
+ A helper function, for the case q > s and q % s > 0.
786
+ """
787
+ d = q // s
788
+ j = q // d
789
+ r = q - d * j
790
+ input_shape = X.shape[1:]
791
+ K_shape = (m_star + 1, ) + input_shape
792
+ K = np.empty(K_shape, dtype=X.dtype)
793
+ for i in range(j + 1):
794
+ Z = X[i*d]
795
+ K[0] = Z
796
+ high_p = 0
797
+ if i < j:
798
+ effective_d = d
799
+ else:
800
+ effective_d = r
801
+ for k in range(1, effective_d+1):
802
+ F = K[0]
803
+ c1 = _exact_inf_norm(F)
804
+ for p in range(1, m_star+1):
805
+ if p == high_p + 1:
806
+ K[p] = h * A.dot(K[p-1]) / float(p)
807
+ high_p = p
808
+ coeff = float(pow(k, p))
809
+ F = F + coeff * K[p]
810
+ inf_norm_K_p_1 = _exact_inf_norm(K[p])
811
+ c2 = coeff * inf_norm_K_p_1
812
+ if c1 + c2 <= tol * _exact_inf_norm(F):
813
+ break
814
+ c1 = c2
815
+ X[k + i*d] = np.exp(k*h*mu) * F
816
+ return X, 2
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_interface.py ADDED
@@ -0,0 +1,921 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Abstract linear algebra library.
2
+
3
+ This module defines a class hierarchy that implements a kind of "lazy"
4
+ matrix representation, called the ``LinearOperator``. It can be used to do
5
+ linear algebra with extremely large sparse or structured matrices, without
6
+ representing those explicitly in memory. Such matrices can be added,
7
+ multiplied, transposed, etc.
8
+
9
+ As a motivating example, suppose you want have a matrix where almost all of
10
+ the elements have the value one. The standard sparse matrix representation
11
+ skips the storage of zeros, but not ones. By contrast, a LinearOperator is
12
+ able to represent such matrices efficiently. First, we need a compact way to
13
+ represent an all-ones matrix::
14
+
15
+ >>> import numpy as np
16
+ >>> from scipy.sparse.linalg._interface import LinearOperator
17
+ >>> class Ones(LinearOperator):
18
+ ... def __init__(self, shape):
19
+ ... super().__init__(dtype=None, shape=shape)
20
+ ... def _matvec(self, x):
21
+ ... return np.repeat(x.sum(), self.shape[0])
22
+
23
+ Instances of this class emulate ``np.ones(shape)``, but using a constant
24
+ amount of storage, independent of ``shape``. The ``_matvec`` method specifies
25
+ how this linear operator multiplies with (operates on) a vector. We can now
26
+ add this operator to a sparse matrix that stores only offsets from one::
27
+
28
+ >>> from scipy.sparse.linalg._interface import aslinearoperator
29
+ >>> from scipy.sparse import csr_array
30
+ >>> offsets = csr_array([[1, 0, 2], [0, -1, 0], [0, 0, 3]])
31
+ >>> A = aslinearoperator(offsets) + Ones(offsets.shape)
32
+ >>> A.dot([1, 2, 3])
33
+ array([13, 4, 15])
34
+
35
+ The result is the same as that given by its dense, explicitly-stored
36
+ counterpart::
37
+
38
+ >>> (np.ones(A.shape, A.dtype) + offsets.toarray()).dot([1, 2, 3])
39
+ array([13, 4, 15])
40
+
41
+ Several algorithms in the ``scipy.sparse`` library are able to operate on
42
+ ``LinearOperator`` instances.
43
+ """
44
+
45
+ import warnings
46
+
47
+ import numpy as np
48
+
49
+ from scipy.sparse import issparse
50
+ from scipy.sparse._sputils import isshape, isintlike, asmatrix, is_pydata_spmatrix
51
+
52
+ __all__ = ['LinearOperator', 'aslinearoperator']
53
+
54
+
55
+ class LinearOperator:
56
+ """Common interface for performing matrix vector products
57
+
58
+ Many iterative methods (e.g. cg, gmres) do not need to know the
59
+ individual entries of a matrix to solve a linear system A@x=b.
60
+ Such solvers only require the computation of matrix vector
61
+ products, A@v where v is a dense vector. This class serves as
62
+ an abstract interface between iterative solvers and matrix-like
63
+ objects.
64
+
65
+ To construct a concrete LinearOperator, either pass appropriate
66
+ callables to the constructor of this class, or subclass it.
67
+
68
+ A subclass must implement either one of the methods ``_matvec``
69
+ and ``_matmat``, and the attributes/properties ``shape`` (pair of
70
+ integers) and ``dtype`` (may be None). It may call the ``__init__``
71
+ on this class to have these attributes validated. Implementing
72
+ ``_matvec`` automatically implements ``_matmat`` (using a naive
73
+ algorithm) and vice-versa.
74
+
75
+ Optionally, a subclass may implement ``_rmatvec`` or ``_adjoint``
76
+ to implement the Hermitian adjoint (conjugate transpose). As with
77
+ ``_matvec`` and ``_matmat``, implementing either ``_rmatvec`` or
78
+ ``_adjoint`` implements the other automatically. Implementing
79
+ ``_adjoint`` is preferable; ``_rmatvec`` is mostly there for
80
+ backwards compatibility.
81
+
82
+ Parameters
83
+ ----------
84
+ shape : tuple
85
+ Matrix dimensions (M, N).
86
+ matvec : callable f(v)
87
+ Returns returns A @ v.
88
+ rmatvec : callable f(v)
89
+ Returns A^H @ v, where A^H is the conjugate transpose of A.
90
+ matmat : callable f(V)
91
+ Returns A @ V, where V is a dense matrix with dimensions (N, K).
92
+ dtype : dtype
93
+ Data type of the matrix.
94
+ rmatmat : callable f(V)
95
+ Returns A^H @ V, where V is a dense matrix with dimensions (M, K).
96
+
97
+ Attributes
98
+ ----------
99
+ args : tuple
100
+ For linear operators describing products etc. of other linear
101
+ operators, the operands of the binary operation.
102
+ ndim : int
103
+ Number of dimensions (this is always 2)
104
+
105
+ See Also
106
+ --------
107
+ aslinearoperator : Construct LinearOperators
108
+
109
+ Notes
110
+ -----
111
+ The user-defined matvec() function must properly handle the case
112
+ where v has shape (N,) as well as the (N,1) case. The shape of
113
+ the return type is handled internally by LinearOperator.
114
+
115
+ It is highly recommended to explicitly specify the `dtype`, otherwise
116
+ it is determined automatically at the cost of a single matvec application
117
+ on `int8` zero vector using the promoted `dtype` of the output.
118
+ Python `int` could be difficult to automatically cast to numpy integers
119
+ in the definition of the `matvec` so the determination may be inaccurate.
120
+ It is assumed that `matmat`, `rmatvec`, and `rmatmat` would result in
121
+ the same dtype of the output given an `int8` input as `matvec`.
122
+
123
+ LinearOperator instances can also be multiplied, added with each
124
+ other and exponentiated, all lazily: the result of these operations
125
+ is always a new, composite LinearOperator, that defers linear
126
+ operations to the original operators and combines the results.
127
+
128
+ More details regarding how to subclass a LinearOperator and several
129
+ examples of concrete LinearOperator instances can be found in the
130
+ external project `PyLops <https://pylops.readthedocs.io>`_.
131
+
132
+
133
+ Examples
134
+ --------
135
+ >>> import numpy as np
136
+ >>> from scipy.sparse.linalg import LinearOperator
137
+ >>> def mv(v):
138
+ ... return np.array([2*v[0], 3*v[1]])
139
+ ...
140
+ >>> A = LinearOperator((2,2), matvec=mv)
141
+ >>> A
142
+ <2x2 _CustomLinearOperator with dtype=int8>
143
+ >>> A.matvec(np.ones(2))
144
+ array([ 2., 3.])
145
+ >>> A @ np.ones(2)
146
+ array([ 2., 3.])
147
+
148
+ """
149
+
150
+ ndim = 2
151
+ # Necessary for right matmul with numpy arrays.
152
+ __array_ufunc__ = None
153
+
154
+ def __new__(cls, *args, **kwargs):
155
+ if cls is LinearOperator:
156
+ # Operate as _CustomLinearOperator factory.
157
+ return super().__new__(_CustomLinearOperator)
158
+ else:
159
+ obj = super().__new__(cls)
160
+
161
+ if (type(obj)._matvec == LinearOperator._matvec
162
+ and type(obj)._matmat == LinearOperator._matmat):
163
+ warnings.warn("LinearOperator subclass should implement"
164
+ " at least one of _matvec and _matmat.",
165
+ category=RuntimeWarning, stacklevel=2)
166
+
167
+ return obj
168
+
169
+ def __init__(self, dtype, shape):
170
+ """Initialize this LinearOperator.
171
+
172
+ To be called by subclasses. ``dtype`` may be None; ``shape`` should
173
+ be convertible to a length-2 tuple.
174
+ """
175
+ if dtype is not None:
176
+ dtype = np.dtype(dtype)
177
+
178
+ shape = tuple(shape)
179
+ if not isshape(shape):
180
+ raise ValueError(f"invalid shape {shape!r} (must be 2-d)")
181
+
182
+ self.dtype = dtype
183
+ self.shape = shape
184
+
185
+ def _init_dtype(self):
186
+ """Determine the dtype by executing `matvec` on an `int8` test vector.
187
+
188
+ In `np.promote_types` hierarchy, the type `int8` is the smallest,
189
+ so we call `matvec` on `int8` and use the promoted dtype of the output
190
+ to set the default `dtype` of the `LinearOperator`.
191
+ We assume that `matmat`, `rmatvec`, and `rmatmat` would result in
192
+ the same dtype of the output given an `int8` input as `matvec`.
193
+
194
+ Called from subclasses at the end of the __init__ routine.
195
+ """
196
+ if self.dtype is None:
197
+ v = np.zeros(self.shape[-1], dtype=np.int8)
198
+ try:
199
+ matvec_v = np.asarray(self.matvec(v))
200
+ except OverflowError:
201
+ # Python large `int` promoted to `np.int64`or `np.int32`
202
+ self.dtype = np.dtype(int)
203
+ else:
204
+ self.dtype = matvec_v.dtype
205
+
206
+ def _matmat(self, X):
207
+ """Default matrix-matrix multiplication handler.
208
+
209
+ Falls back on the user-defined _matvec method, so defining that will
210
+ define matrix multiplication (though in a very suboptimal way).
211
+ """
212
+
213
+ return np.hstack([self.matvec(col.reshape(-1,1)) for col in X.T])
214
+
215
+ def _matvec(self, x):
216
+ """Default matrix-vector multiplication handler.
217
+
218
+ If self is a linear operator of shape (M, N), then this method will
219
+ be called on a shape (N,) or (N, 1) ndarray, and should return a
220
+ shape (M,) or (M, 1) ndarray.
221
+
222
+ This default implementation falls back on _matmat, so defining that
223
+ will define matrix-vector multiplication as well.
224
+ """
225
+ return self.matmat(x.reshape(-1, 1))
226
+
227
+ def matvec(self, x):
228
+ """Matrix-vector multiplication.
229
+
230
+ Performs the operation y=A@x where A is an MxN linear
231
+ operator and x is a column vector or 1-d array.
232
+
233
+ Parameters
234
+ ----------
235
+ x : {matrix, ndarray}
236
+ An array with shape (N,) or (N,1).
237
+
238
+ Returns
239
+ -------
240
+ y : {matrix, ndarray}
241
+ A matrix or ndarray with shape (M,) or (M,1) depending
242
+ on the type and shape of the x argument.
243
+
244
+ Notes
245
+ -----
246
+ This matvec wraps the user-specified matvec routine or overridden
247
+ _matvec method to ensure that y has the correct shape and type.
248
+
249
+ """
250
+
251
+ x = np.asanyarray(x)
252
+
253
+ M,N = self.shape
254
+
255
+ if x.shape != (N,) and x.shape != (N,1):
256
+ raise ValueError('dimension mismatch')
257
+
258
+ y = self._matvec(x)
259
+
260
+ if isinstance(x, np.matrix):
261
+ y = asmatrix(y)
262
+ else:
263
+ y = np.asarray(y)
264
+
265
+ if x.ndim == 1:
266
+ y = y.reshape(M)
267
+ elif x.ndim == 2:
268
+ y = y.reshape(M,1)
269
+ else:
270
+ raise ValueError('invalid shape returned by user-defined matvec()')
271
+
272
+ return y
273
+
274
+ def rmatvec(self, x):
275
+ """Adjoint matrix-vector multiplication.
276
+
277
+ Performs the operation y = A^H @ x where A is an MxN linear
278
+ operator and x is a column vector or 1-d array.
279
+
280
+ Parameters
281
+ ----------
282
+ x : {matrix, ndarray}
283
+ An array with shape (M,) or (M,1).
284
+
285
+ Returns
286
+ -------
287
+ y : {matrix, ndarray}
288
+ A matrix or ndarray with shape (N,) or (N,1) depending
289
+ on the type and shape of the x argument.
290
+
291
+ Notes
292
+ -----
293
+ This rmatvec wraps the user-specified rmatvec routine or overridden
294
+ _rmatvec method to ensure that y has the correct shape and type.
295
+
296
+ """
297
+
298
+ x = np.asanyarray(x)
299
+
300
+ M,N = self.shape
301
+
302
+ if x.shape != (M,) and x.shape != (M,1):
303
+ raise ValueError('dimension mismatch')
304
+
305
+ y = self._rmatvec(x)
306
+
307
+ if isinstance(x, np.matrix):
308
+ y = asmatrix(y)
309
+ else:
310
+ y = np.asarray(y)
311
+
312
+ if x.ndim == 1:
313
+ y = y.reshape(N)
314
+ elif x.ndim == 2:
315
+ y = y.reshape(N,1)
316
+ else:
317
+ raise ValueError('invalid shape returned by user-defined rmatvec()')
318
+
319
+ return y
320
+
321
+ def _rmatvec(self, x):
322
+ """Default implementation of _rmatvec; defers to adjoint."""
323
+ if type(self)._adjoint == LinearOperator._adjoint:
324
+ # _adjoint not overridden, prevent infinite recursion
325
+ if (hasattr(self, "_rmatmat")
326
+ and type(self)._rmatmat != LinearOperator._rmatmat):
327
+ # Try to use _rmatmat as a fallback
328
+ return self._rmatmat(x.reshape(-1, 1)).reshape(-1)
329
+ raise NotImplementedError
330
+ else:
331
+ return self.H.matvec(x)
332
+
333
+ def matmat(self, X):
334
+ """Matrix-matrix multiplication.
335
+
336
+ Performs the operation y=A@X where A is an MxN linear
337
+ operator and X dense N*K matrix or ndarray.
338
+
339
+ Parameters
340
+ ----------
341
+ X : {matrix, ndarray}
342
+ An array with shape (N,K).
343
+
344
+ Returns
345
+ -------
346
+ Y : {matrix, ndarray}
347
+ A matrix or ndarray with shape (M,K) depending on
348
+ the type of the X argument.
349
+
350
+ Notes
351
+ -----
352
+ This matmat wraps any user-specified matmat routine or overridden
353
+ _matmat method to ensure that y has the correct type.
354
+
355
+ """
356
+ if not (issparse(X) or is_pydata_spmatrix(X)):
357
+ X = np.asanyarray(X)
358
+
359
+ if X.ndim != 2:
360
+ raise ValueError(f'expected 2-d ndarray or matrix, not {X.ndim}-d')
361
+
362
+ if X.shape[0] != self.shape[1]:
363
+ raise ValueError(f'dimension mismatch: {self.shape}, {X.shape}')
364
+
365
+ try:
366
+ Y = self._matmat(X)
367
+ except Exception as e:
368
+ if issparse(X) or is_pydata_spmatrix(X):
369
+ raise TypeError(
370
+ "Unable to multiply a LinearOperator with a sparse matrix."
371
+ " Wrap the matrix in aslinearoperator first."
372
+ ) from e
373
+ raise
374
+
375
+ if isinstance(Y, np.matrix):
376
+ Y = asmatrix(Y)
377
+
378
+ return Y
379
+
380
+ def rmatmat(self, X):
381
+ """Adjoint matrix-matrix multiplication.
382
+
383
+ Performs the operation y = A^H @ x where A is an MxN linear
384
+ operator and x is a column vector or 1-d array, or 2-d array.
385
+ The default implementation defers to the adjoint.
386
+
387
+ Parameters
388
+ ----------
389
+ X : {matrix, ndarray}
390
+ A matrix or 2D array.
391
+
392
+ Returns
393
+ -------
394
+ Y : {matrix, ndarray}
395
+ A matrix or 2D array depending on the type of the input.
396
+
397
+ Notes
398
+ -----
399
+ This rmatmat wraps the user-specified rmatmat routine.
400
+
401
+ """
402
+ if not (issparse(X) or is_pydata_spmatrix(X)):
403
+ X = np.asanyarray(X)
404
+
405
+ if X.ndim != 2:
406
+ raise ValueError('expected 2-d ndarray or matrix, not %d-d'
407
+ % X.ndim)
408
+
409
+ if X.shape[0] != self.shape[0]:
410
+ raise ValueError(f'dimension mismatch: {self.shape}, {X.shape}')
411
+
412
+ try:
413
+ Y = self._rmatmat(X)
414
+ except Exception as e:
415
+ if issparse(X) or is_pydata_spmatrix(X):
416
+ raise TypeError(
417
+ "Unable to multiply a LinearOperator with a sparse matrix."
418
+ " Wrap the matrix in aslinearoperator() first."
419
+ ) from e
420
+ raise
421
+
422
+ if isinstance(Y, np.matrix):
423
+ Y = asmatrix(Y)
424
+ return Y
425
+
426
+ def _rmatmat(self, X):
427
+ """Default implementation of _rmatmat defers to rmatvec or adjoint."""
428
+ if type(self)._adjoint == LinearOperator._adjoint:
429
+ return np.hstack([self.rmatvec(col.reshape(-1, 1)) for col in X.T])
430
+ else:
431
+ return self.H.matmat(X)
432
+
433
+ def __call__(self, x):
434
+ return self@x
435
+
436
+ def __mul__(self, x):
437
+ return self.dot(x)
438
+
439
+ def __truediv__(self, other):
440
+ if not np.isscalar(other):
441
+ raise ValueError("Can only divide a linear operator by a scalar.")
442
+
443
+ return _ScaledLinearOperator(self, 1.0/other)
444
+
445
+ def dot(self, x):
446
+ """Matrix-matrix or matrix-vector multiplication.
447
+
448
+ Parameters
449
+ ----------
450
+ x : array_like
451
+ 1-d or 2-d array, representing a vector or matrix.
452
+
453
+ Returns
454
+ -------
455
+ Ax : array
456
+ 1-d or 2-d array (depending on the shape of x) that represents
457
+ the result of applying this linear operator on x.
458
+
459
+ """
460
+ if isinstance(x, LinearOperator):
461
+ return _ProductLinearOperator(self, x)
462
+ elif np.isscalar(x):
463
+ return _ScaledLinearOperator(self, x)
464
+ else:
465
+ if not issparse(x) and not is_pydata_spmatrix(x):
466
+ # Sparse matrices shouldn't be converted to numpy arrays.
467
+ x = np.asarray(x)
468
+
469
+ if x.ndim == 1 or x.ndim == 2 and x.shape[1] == 1:
470
+ return self.matvec(x)
471
+ elif x.ndim == 2:
472
+ return self.matmat(x)
473
+ else:
474
+ raise ValueError(f'expected 1-d or 2-d array or matrix, got {x!r}')
475
+
476
+ def __matmul__(self, other):
477
+ if np.isscalar(other):
478
+ raise ValueError("Scalar operands are not allowed, "
479
+ "use '*' instead")
480
+ return self.__mul__(other)
481
+
482
+ def __rmatmul__(self, other):
483
+ if np.isscalar(other):
484
+ raise ValueError("Scalar operands are not allowed, "
485
+ "use '*' instead")
486
+ return self.__rmul__(other)
487
+
488
+ def __rmul__(self, x):
489
+ if np.isscalar(x):
490
+ return _ScaledLinearOperator(self, x)
491
+ else:
492
+ return self._rdot(x)
493
+
494
+ def _rdot(self, x):
495
+ """Matrix-matrix or matrix-vector multiplication from the right.
496
+
497
+ Parameters
498
+ ----------
499
+ x : array_like
500
+ 1-d or 2-d array, representing a vector or matrix.
501
+
502
+ Returns
503
+ -------
504
+ xA : array
505
+ 1-d or 2-d array (depending on the shape of x) that represents
506
+ the result of applying this linear operator on x from the right.
507
+
508
+ Notes
509
+ -----
510
+ This is copied from dot to implement right multiplication.
511
+ """
512
+ if isinstance(x, LinearOperator):
513
+ return _ProductLinearOperator(x, self)
514
+ elif np.isscalar(x):
515
+ return _ScaledLinearOperator(self, x)
516
+ else:
517
+ if not issparse(x) and not is_pydata_spmatrix(x):
518
+ # Sparse matrices shouldn't be converted to numpy arrays.
519
+ x = np.asarray(x)
520
+
521
+ # We use transpose instead of rmatvec/rmatmat to avoid
522
+ # unnecessary complex conjugation if possible.
523
+ if x.ndim == 1 or x.ndim == 2 and x.shape[0] == 1:
524
+ return self.T.matvec(x.T).T
525
+ elif x.ndim == 2:
526
+ return self.T.matmat(x.T).T
527
+ else:
528
+ raise ValueError(f'expected 1-d or 2-d array or matrix, got {x!r}')
529
+
530
+ def __pow__(self, p):
531
+ if np.isscalar(p):
532
+ return _PowerLinearOperator(self, p)
533
+ else:
534
+ return NotImplemented
535
+
536
+ def __add__(self, x):
537
+ if isinstance(x, LinearOperator):
538
+ return _SumLinearOperator(self, x)
539
+ else:
540
+ return NotImplemented
541
+
542
+ def __neg__(self):
543
+ return _ScaledLinearOperator(self, -1)
544
+
545
+ def __sub__(self, x):
546
+ return self.__add__(-x)
547
+
548
+ def __repr__(self):
549
+ M,N = self.shape
550
+ if self.dtype is None:
551
+ dt = 'unspecified dtype'
552
+ else:
553
+ dt = 'dtype=' + str(self.dtype)
554
+
555
+ return '<%dx%d %s with %s>' % (M, N, self.__class__.__name__, dt)
556
+
557
+ def adjoint(self):
558
+ """Hermitian adjoint.
559
+
560
+ Returns the Hermitian adjoint of self, aka the Hermitian
561
+ conjugate or Hermitian transpose. For a complex matrix, the
562
+ Hermitian adjoint is equal to the conjugate transpose.
563
+
564
+ Can be abbreviated self.H instead of self.adjoint().
565
+
566
+ Returns
567
+ -------
568
+ A_H : LinearOperator
569
+ Hermitian adjoint of self.
570
+ """
571
+ return self._adjoint()
572
+
573
+ H = property(adjoint)
574
+
575
+ def transpose(self):
576
+ """Transpose this linear operator.
577
+
578
+ Returns a LinearOperator that represents the transpose of this one.
579
+ Can be abbreviated self.T instead of self.transpose().
580
+ """
581
+ return self._transpose()
582
+
583
+ T = property(transpose)
584
+
585
+ def _adjoint(self):
586
+ """Default implementation of _adjoint; defers to rmatvec."""
587
+ return _AdjointLinearOperator(self)
588
+
589
+ def _transpose(self):
590
+ """ Default implementation of _transpose; defers to rmatvec + conj"""
591
+ return _TransposedLinearOperator(self)
592
+
593
+
594
+ class _CustomLinearOperator(LinearOperator):
595
+ """Linear operator defined in terms of user-specified operations."""
596
+
597
+ def __init__(self, shape, matvec, rmatvec=None, matmat=None,
598
+ dtype=None, rmatmat=None):
599
+ super().__init__(dtype, shape)
600
+
601
+ self.args = ()
602
+
603
+ self.__matvec_impl = matvec
604
+ self.__rmatvec_impl = rmatvec
605
+ self.__rmatmat_impl = rmatmat
606
+ self.__matmat_impl = matmat
607
+
608
+ self._init_dtype()
609
+
610
+ def _matmat(self, X):
611
+ if self.__matmat_impl is not None:
612
+ return self.__matmat_impl(X)
613
+ else:
614
+ return super()._matmat(X)
615
+
616
+ def _matvec(self, x):
617
+ return self.__matvec_impl(x)
618
+
619
+ def _rmatvec(self, x):
620
+ func = self.__rmatvec_impl
621
+ if func is None:
622
+ raise NotImplementedError("rmatvec is not defined")
623
+ return self.__rmatvec_impl(x)
624
+
625
+ def _rmatmat(self, X):
626
+ if self.__rmatmat_impl is not None:
627
+ return self.__rmatmat_impl(X)
628
+ else:
629
+ return super()._rmatmat(X)
630
+
631
+ def _adjoint(self):
632
+ return _CustomLinearOperator(shape=(self.shape[1], self.shape[0]),
633
+ matvec=self.__rmatvec_impl,
634
+ rmatvec=self.__matvec_impl,
635
+ matmat=self.__rmatmat_impl,
636
+ rmatmat=self.__matmat_impl,
637
+ dtype=self.dtype)
638
+
639
+
640
+ class _AdjointLinearOperator(LinearOperator):
641
+ """Adjoint of arbitrary Linear Operator"""
642
+
643
+ def __init__(self, A):
644
+ shape = (A.shape[1], A.shape[0])
645
+ super().__init__(dtype=A.dtype, shape=shape)
646
+ self.A = A
647
+ self.args = (A,)
648
+
649
+ def _matvec(self, x):
650
+ return self.A._rmatvec(x)
651
+
652
+ def _rmatvec(self, x):
653
+ return self.A._matvec(x)
654
+
655
+ def _matmat(self, x):
656
+ return self.A._rmatmat(x)
657
+
658
+ def _rmatmat(self, x):
659
+ return self.A._matmat(x)
660
+
661
+ class _TransposedLinearOperator(LinearOperator):
662
+ """Transposition of arbitrary Linear Operator"""
663
+
664
+ def __init__(self, A):
665
+ shape = (A.shape[1], A.shape[0])
666
+ super().__init__(dtype=A.dtype, shape=shape)
667
+ self.A = A
668
+ self.args = (A,)
669
+
670
+ def _matvec(self, x):
671
+ # NB. np.conj works also on sparse matrices
672
+ return np.conj(self.A._rmatvec(np.conj(x)))
673
+
674
+ def _rmatvec(self, x):
675
+ return np.conj(self.A._matvec(np.conj(x)))
676
+
677
+ def _matmat(self, x):
678
+ # NB. np.conj works also on sparse matrices
679
+ return np.conj(self.A._rmatmat(np.conj(x)))
680
+
681
+ def _rmatmat(self, x):
682
+ return np.conj(self.A._matmat(np.conj(x)))
683
+
684
+ def _get_dtype(operators, dtypes=None):
685
+ if dtypes is None:
686
+ dtypes = []
687
+ for obj in operators:
688
+ if obj is not None and hasattr(obj, 'dtype'):
689
+ dtypes.append(obj.dtype)
690
+ return np.result_type(*dtypes)
691
+
692
+
693
+ class _SumLinearOperator(LinearOperator):
694
+ def __init__(self, A, B):
695
+ if not isinstance(A, LinearOperator) or \
696
+ not isinstance(B, LinearOperator):
697
+ raise ValueError('both operands have to be a LinearOperator')
698
+ if A.shape != B.shape:
699
+ raise ValueError(f'cannot add {A} and {B}: shape mismatch')
700
+ self.args = (A, B)
701
+ super().__init__(_get_dtype([A, B]), A.shape)
702
+
703
+ def _matvec(self, x):
704
+ return self.args[0].matvec(x) + self.args[1].matvec(x)
705
+
706
+ def _rmatvec(self, x):
707
+ return self.args[0].rmatvec(x) + self.args[1].rmatvec(x)
708
+
709
+ def _rmatmat(self, x):
710
+ return self.args[0].rmatmat(x) + self.args[1].rmatmat(x)
711
+
712
+ def _matmat(self, x):
713
+ return self.args[0].matmat(x) + self.args[1].matmat(x)
714
+
715
+ def _adjoint(self):
716
+ A, B = self.args
717
+ return A.H + B.H
718
+
719
+
720
+ class _ProductLinearOperator(LinearOperator):
721
+ def __init__(self, A, B):
722
+ if not isinstance(A, LinearOperator) or \
723
+ not isinstance(B, LinearOperator):
724
+ raise ValueError('both operands have to be a LinearOperator')
725
+ if A.shape[1] != B.shape[0]:
726
+ raise ValueError(f'cannot multiply {A} and {B}: shape mismatch')
727
+ super().__init__(_get_dtype([A, B]),
728
+ (A.shape[0], B.shape[1]))
729
+ self.args = (A, B)
730
+
731
+ def _matvec(self, x):
732
+ return self.args[0].matvec(self.args[1].matvec(x))
733
+
734
+ def _rmatvec(self, x):
735
+ return self.args[1].rmatvec(self.args[0].rmatvec(x))
736
+
737
+ def _rmatmat(self, x):
738
+ return self.args[1].rmatmat(self.args[0].rmatmat(x))
739
+
740
+ def _matmat(self, x):
741
+ return self.args[0].matmat(self.args[1].matmat(x))
742
+
743
+ def _adjoint(self):
744
+ A, B = self.args
745
+ return B.H @ A.H
746
+
747
+
748
+ class _ScaledLinearOperator(LinearOperator):
749
+ def __init__(self, A, alpha):
750
+ if not isinstance(A, LinearOperator):
751
+ raise ValueError('LinearOperator expected as A')
752
+ if not np.isscalar(alpha):
753
+ raise ValueError('scalar expected as alpha')
754
+ if isinstance(A, _ScaledLinearOperator):
755
+ A, alpha_original = A.args
756
+ # Avoid in-place multiplication so that we don't accidentally mutate
757
+ # the original prefactor.
758
+ alpha = alpha * alpha_original
759
+
760
+ dtype = _get_dtype([A], [type(alpha)])
761
+ super().__init__(dtype, A.shape)
762
+ self.args = (A, alpha)
763
+ # Note: args[1] is alpha (a scalar), so use `*` below, not `@`
764
+
765
+ def _matvec(self, x):
766
+ return self.args[1] * self.args[0].matvec(x)
767
+
768
+ def _rmatvec(self, x):
769
+ return np.conj(self.args[1]) * self.args[0].rmatvec(x)
770
+
771
+ def _rmatmat(self, x):
772
+ return np.conj(self.args[1]) * self.args[0].rmatmat(x)
773
+
774
+ def _matmat(self, x):
775
+ return self.args[1] * self.args[0].matmat(x)
776
+
777
+ def _adjoint(self):
778
+ A, alpha = self.args
779
+ return A.H * np.conj(alpha)
780
+
781
+
782
+ class _PowerLinearOperator(LinearOperator):
783
+ def __init__(self, A, p):
784
+ if not isinstance(A, LinearOperator):
785
+ raise ValueError('LinearOperator expected as A')
786
+ if A.shape[0] != A.shape[1]:
787
+ raise ValueError(f'square LinearOperator expected, got {A!r}')
788
+ if not isintlike(p) or p < 0:
789
+ raise ValueError('non-negative integer expected as p')
790
+
791
+ super().__init__(_get_dtype([A]), A.shape)
792
+ self.args = (A, p)
793
+
794
+ def _power(self, fun, x):
795
+ res = np.array(x, copy=True)
796
+ for i in range(self.args[1]):
797
+ res = fun(res)
798
+ return res
799
+
800
+ def _matvec(self, x):
801
+ return self._power(self.args[0].matvec, x)
802
+
803
+ def _rmatvec(self, x):
804
+ return self._power(self.args[0].rmatvec, x)
805
+
806
+ def _rmatmat(self, x):
807
+ return self._power(self.args[0].rmatmat, x)
808
+
809
+ def _matmat(self, x):
810
+ return self._power(self.args[0].matmat, x)
811
+
812
+ def _adjoint(self):
813
+ A, p = self.args
814
+ return A.H ** p
815
+
816
+
817
+ class MatrixLinearOperator(LinearOperator):
818
+ def __init__(self, A):
819
+ super().__init__(A.dtype, A.shape)
820
+ self.A = A
821
+ self.__adj = None
822
+ self.args = (A,)
823
+
824
+ def _matmat(self, X):
825
+ return self.A.dot(X)
826
+
827
+ def _adjoint(self):
828
+ if self.__adj is None:
829
+ self.__adj = _AdjointMatrixOperator(self.A)
830
+ return self.__adj
831
+
832
+
833
+ class _AdjointMatrixOperator(MatrixLinearOperator):
834
+ def __init__(self, adjoint_array):
835
+ self.A = adjoint_array.T.conj()
836
+ self.args = (adjoint_array,)
837
+ self.shape = adjoint_array.shape[1], adjoint_array.shape[0]
838
+
839
+ @property
840
+ def dtype(self):
841
+ return self.args[0].dtype
842
+
843
+ def _adjoint(self):
844
+ return MatrixLinearOperator(self.args[0])
845
+
846
+
847
+ class IdentityOperator(LinearOperator):
848
+ def __init__(self, shape, dtype=None):
849
+ super().__init__(dtype, shape)
850
+
851
+ def _matvec(self, x):
852
+ return x
853
+
854
+ def _rmatvec(self, x):
855
+ return x
856
+
857
+ def _rmatmat(self, x):
858
+ return x
859
+
860
+ def _matmat(self, x):
861
+ return x
862
+
863
+ def _adjoint(self):
864
+ return self
865
+
866
+
867
+ def aslinearoperator(A):
868
+ """Return A as a LinearOperator.
869
+
870
+ 'A' may be any of the following types:
871
+ - ndarray
872
+ - matrix
873
+ - sparse array (e.g. csr_array, lil_array, etc.)
874
+ - LinearOperator
875
+ - An object with .shape and .matvec attributes
876
+
877
+ See the LinearOperator documentation for additional information.
878
+
879
+ Notes
880
+ -----
881
+ If 'A' has no .dtype attribute, the data type is determined by calling
882
+ :func:`LinearOperator.matvec()` - set the .dtype attribute to prevent this
883
+ call upon the linear operator creation.
884
+
885
+ Examples
886
+ --------
887
+ >>> import numpy as np
888
+ >>> from scipy.sparse.linalg import aslinearoperator
889
+ >>> M = np.array([[1,2,3],[4,5,6]], dtype=np.int32)
890
+ >>> aslinearoperator(M)
891
+ <2x3 MatrixLinearOperator with dtype=int32>
892
+ """
893
+ if isinstance(A, LinearOperator):
894
+ return A
895
+
896
+ elif isinstance(A, np.ndarray) or isinstance(A, np.matrix):
897
+ if A.ndim > 2:
898
+ raise ValueError('array must have ndim <= 2')
899
+ A = np.atleast_2d(np.asarray(A))
900
+ return MatrixLinearOperator(A)
901
+
902
+ elif issparse(A) or is_pydata_spmatrix(A):
903
+ return MatrixLinearOperator(A)
904
+
905
+ else:
906
+ if hasattr(A, 'shape') and hasattr(A, 'matvec'):
907
+ rmatvec = None
908
+ rmatmat = None
909
+ dtype = None
910
+
911
+ if hasattr(A, 'rmatvec'):
912
+ rmatvec = A.rmatvec
913
+ if hasattr(A, 'rmatmat'):
914
+ rmatmat = A.rmatmat
915
+ if hasattr(A, 'dtype'):
916
+ dtype = A.dtype
917
+ return LinearOperator(A.shape, A.matvec, rmatvec=rmatvec,
918
+ rmatmat=rmatmat, dtype=dtype)
919
+
920
+ else:
921
+ raise TypeError('type not understood')
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__init__.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "Iterative Solvers for Sparse Linear Systems"
2
+
3
+ #from info import __doc__
4
+ from .iterative import *
5
+ from .minres import minres
6
+ from .lgmres import lgmres
7
+ from .lsqr import lsqr
8
+ from .lsmr import lsmr
9
+ from ._gcrotmk import gcrotmk
10
+ from .tfqmr import tfqmr
11
+
12
+ __all__ = [
13
+ 'bicg', 'bicgstab', 'cg', 'cgs', 'gcrotmk', 'gmres',
14
+ 'lgmres', 'lsmr', 'lsqr',
15
+ 'minres', 'qmr', 'tfqmr'
16
+ ]
17
+
18
+ from scipy._lib._testutils import PytestTester
19
+ test = PytestTester(__name__)
20
+ del PytestTester
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/_gcrotmk.py ADDED
@@ -0,0 +1,503 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) 2015, Pauli Virtanen <pav@iki.fi>
2
+ # Distributed under the same license as SciPy.
3
+
4
+ import numpy as np
5
+ from numpy.linalg import LinAlgError
6
+ from scipy.linalg import (get_blas_funcs, qr, solve, svd, qr_insert, lstsq)
7
+ from .iterative import _get_atol_rtol
8
+ from scipy.sparse.linalg._isolve.utils import make_system
9
+
10
+
11
+ __all__ = ['gcrotmk']
12
+
13
+
14
+ def _fgmres(matvec, v0, m, atol, lpsolve=None, rpsolve=None, cs=(), outer_v=(),
15
+ prepend_outer_v=False):
16
+ """
17
+ FGMRES Arnoldi process, with optional projection or augmentation
18
+
19
+ Parameters
20
+ ----------
21
+ matvec : callable
22
+ Operation A*x
23
+ v0 : ndarray
24
+ Initial vector, normalized to nrm2(v0) == 1
25
+ m : int
26
+ Number of GMRES rounds
27
+ atol : float
28
+ Absolute tolerance for early exit
29
+ lpsolve : callable
30
+ Left preconditioner L
31
+ rpsolve : callable
32
+ Right preconditioner R
33
+ cs : list of (ndarray, ndarray)
34
+ Columns of matrices C and U in GCROT
35
+ outer_v : list of ndarrays
36
+ Augmentation vectors in LGMRES
37
+ prepend_outer_v : bool, optional
38
+ Whether augmentation vectors come before or after
39
+ Krylov iterates
40
+
41
+ Raises
42
+ ------
43
+ LinAlgError
44
+ If nans encountered
45
+
46
+ Returns
47
+ -------
48
+ Q, R : ndarray
49
+ QR decomposition of the upper Hessenberg H=QR
50
+ B : ndarray
51
+ Projections corresponding to matrix C
52
+ vs : list of ndarray
53
+ Columns of matrix V
54
+ zs : list of ndarray
55
+ Columns of matrix Z
56
+ y : ndarray
57
+ Solution to ||H y - e_1||_2 = min!
58
+ res : float
59
+ The final (preconditioned) residual norm
60
+
61
+ """
62
+
63
+ if lpsolve is None:
64
+ def lpsolve(x):
65
+ return x
66
+ if rpsolve is None:
67
+ def rpsolve(x):
68
+ return x
69
+
70
+ axpy, dot, scal, nrm2 = get_blas_funcs(['axpy', 'dot', 'scal', 'nrm2'], (v0,))
71
+
72
+ vs = [v0]
73
+ zs = []
74
+ y = None
75
+ res = np.nan
76
+
77
+ m = m + len(outer_v)
78
+
79
+ # Orthogonal projection coefficients
80
+ B = np.zeros((len(cs), m), dtype=v0.dtype)
81
+
82
+ # H is stored in QR factorized form
83
+ Q = np.ones((1, 1), dtype=v0.dtype)
84
+ R = np.zeros((1, 0), dtype=v0.dtype)
85
+
86
+ eps = np.finfo(v0.dtype).eps
87
+
88
+ breakdown = False
89
+
90
+ # FGMRES Arnoldi process
91
+ for j in range(m):
92
+ # L A Z = C B + V H
93
+
94
+ if prepend_outer_v and j < len(outer_v):
95
+ z, w = outer_v[j]
96
+ elif prepend_outer_v and j == len(outer_v):
97
+ z = rpsolve(v0)
98
+ w = None
99
+ elif not prepend_outer_v and j >= m - len(outer_v):
100
+ z, w = outer_v[j - (m - len(outer_v))]
101
+ else:
102
+ z = rpsolve(vs[-1])
103
+ w = None
104
+
105
+ if w is None:
106
+ w = lpsolve(matvec(z))
107
+ else:
108
+ # w is clobbered below
109
+ w = w.copy()
110
+
111
+ w_norm = nrm2(w)
112
+
113
+ # GCROT projection: L A -> (1 - C C^H) L A
114
+ # i.e. orthogonalize against C
115
+ for i, c in enumerate(cs):
116
+ alpha = dot(c, w)
117
+ B[i,j] = alpha
118
+ w = axpy(c, w, c.shape[0], -alpha) # w -= alpha*c
119
+
120
+ # Orthogonalize against V
121
+ hcur = np.zeros(j+2, dtype=Q.dtype)
122
+ for i, v in enumerate(vs):
123
+ alpha = dot(v, w)
124
+ hcur[i] = alpha
125
+ w = axpy(v, w, v.shape[0], -alpha) # w -= alpha*v
126
+ hcur[i+1] = nrm2(w)
127
+
128
+ with np.errstate(over='ignore', divide='ignore'):
129
+ # Careful with denormals
130
+ alpha = 1/hcur[-1]
131
+
132
+ if np.isfinite(alpha):
133
+ w = scal(alpha, w)
134
+
135
+ if not (hcur[-1] > eps * w_norm):
136
+ # w essentially in the span of previous vectors,
137
+ # or we have nans. Bail out after updating the QR
138
+ # solution.
139
+ breakdown = True
140
+
141
+ vs.append(w)
142
+ zs.append(z)
143
+
144
+ # Arnoldi LSQ problem
145
+
146
+ # Add new column to H=Q@R, padding other columns with zeros
147
+ Q2 = np.zeros((j+2, j+2), dtype=Q.dtype, order='F')
148
+ Q2[:j+1,:j+1] = Q
149
+ Q2[j+1,j+1] = 1
150
+
151
+ R2 = np.zeros((j+2, j), dtype=R.dtype, order='F')
152
+ R2[:j+1,:] = R
153
+
154
+ Q, R = qr_insert(Q2, R2, hcur, j, which='col',
155
+ overwrite_qru=True, check_finite=False)
156
+
157
+ # Transformed least squares problem
158
+ # || Q R y - inner_res_0 * e_1 ||_2 = min!
159
+ # Since R = [R'; 0], solution is y = inner_res_0 (R')^{-1} (Q^H)[:j,0]
160
+
161
+ # Residual is immediately known
162
+ res = abs(Q[0,-1])
163
+
164
+ # Check for termination
165
+ if res < atol or breakdown:
166
+ break
167
+
168
+ if not np.isfinite(R[j,j]):
169
+ # nans encountered, bail out
170
+ raise LinAlgError()
171
+
172
+ # -- Get the LSQ problem solution
173
+
174
+ # The problem is triangular, but the condition number may be
175
+ # bad (or in case of breakdown the last diagonal entry may be
176
+ # zero), so use lstsq instead of trtrs.
177
+ y, _, _, _, = lstsq(R[:j+1,:j+1], Q[0,:j+1].conj())
178
+
179
+ B = B[:,:j+1]
180
+
181
+ return Q, R, B, vs, zs, y, res
182
+
183
+
184
+ def gcrotmk(A, b, x0=None, *, rtol=1e-5, atol=0., maxiter=1000, M=None, callback=None,
185
+ m=20, k=None, CU=None, discard_C=False, truncate='oldest'):
186
+ """
187
+ Solve a matrix equation using flexible GCROT(m,k) algorithm.
188
+
189
+ Parameters
190
+ ----------
191
+ A : {sparse array, ndarray, LinearOperator}
192
+ The real or complex N-by-N matrix of the linear system.
193
+ Alternatively, `A` can be a linear operator which can
194
+ produce ``Ax`` using, e.g.,
195
+ `LinearOperator`.
196
+ b : ndarray
197
+ Right hand side of the linear system. Has shape (N,) or (N,1).
198
+ x0 : ndarray
199
+ Starting guess for the solution.
200
+ rtol, atol : float, optional
201
+ Parameters for the convergence test. For convergence,
202
+ ``norm(b - A @ x) <= max(rtol*norm(b), atol)`` should be satisfied.
203
+ The default is ``rtol=1e-5`` and ``atol=0.0``.
204
+ maxiter : int, optional
205
+ Maximum number of iterations. Iteration will stop after maxiter
206
+ steps even if the specified tolerance has not been achieved. The
207
+ default is ``1000``.
208
+ M : {sparse array, ndarray, LinearOperator}, optional
209
+ Preconditioner for `A`. The preconditioner should approximate the
210
+ inverse of `A`. gcrotmk is a 'flexible' algorithm and the preconditioner
211
+ can vary from iteration to iteration. Effective preconditioning
212
+ dramatically improves the rate of convergence, which implies that
213
+ fewer iterations are needed to reach a given error tolerance.
214
+ callback : function, optional
215
+ User-supplied function to call after each iteration. It is called
216
+ as ``callback(xk)``, where ``xk`` is the current solution vector.
217
+ m : int, optional
218
+ Number of inner FGMRES iterations per each outer iteration.
219
+ Default: 20
220
+ k : int, optional
221
+ Number of vectors to carry between inner FGMRES iterations.
222
+ According to [2]_, good values are around `m`.
223
+ Default: `m`
224
+ CU : list of tuples, optional
225
+ List of tuples ``(c, u)`` which contain the columns of the matrices
226
+ C and U in the GCROT(m,k) algorithm. For details, see [2]_.
227
+ The list given and vectors contained in it are modified in-place.
228
+ If not given, start from empty matrices. The ``c`` elements in the
229
+ tuples can be ``None``, in which case the vectors are recomputed
230
+ via ``c = A u`` on start and orthogonalized as described in [3]_.
231
+ discard_C : bool, optional
232
+ Discard the C-vectors at the end. Useful if recycling Krylov subspaces
233
+ for different linear systems.
234
+ truncate : {'oldest', 'smallest'}, optional
235
+ Truncation scheme to use. Drop: oldest vectors, or vectors with
236
+ smallest singular values using the scheme discussed in [1,2].
237
+ See [2]_ for detailed comparison.
238
+ Default: 'oldest'
239
+
240
+ Returns
241
+ -------
242
+ x : ndarray
243
+ The solution found.
244
+ info : int
245
+ Provides convergence information:
246
+
247
+ * 0 : successful exit
248
+ * >0 : convergence to tolerance not achieved, number of iterations
249
+
250
+ References
251
+ ----------
252
+ .. [1] E. de Sturler, ''Truncation strategies for optimal Krylov subspace
253
+ methods'', SIAM J. Numer. Anal. 36, 864 (1999).
254
+ .. [2] J.E. Hicken and D.W. Zingg, ''A simplified and flexible variant
255
+ of GCROT for solving nonsymmetric linear systems'',
256
+ SIAM J. Sci. Comput. 32, 172 (2010).
257
+ .. [3] M.L. Parks, E. de Sturler, G. Mackey, D.D. Johnson, S. Maiti,
258
+ ''Recycling Krylov subspaces for sequences of linear systems'',
259
+ SIAM J. Sci. Comput. 28, 1651 (2006).
260
+
261
+ Examples
262
+ --------
263
+ >>> import numpy as np
264
+ >>> from scipy.sparse import csc_array
265
+ >>> from scipy.sparse.linalg import gcrotmk
266
+ >>> R = np.random.randn(5, 5)
267
+ >>> A = csc_array(R)
268
+ >>> b = np.random.randn(5)
269
+ >>> x, exit_code = gcrotmk(A, b, atol=1e-5)
270
+ >>> print(exit_code)
271
+ 0
272
+ >>> np.allclose(A.dot(x), b)
273
+ True
274
+
275
+ """
276
+ A,M,x,b,postprocess = make_system(A,M,x0,b)
277
+
278
+ if not np.isfinite(b).all():
279
+ raise ValueError("RHS must contain only finite numbers")
280
+
281
+ if truncate not in ('oldest', 'smallest'):
282
+ raise ValueError(f"Invalid value for 'truncate': {truncate!r}")
283
+
284
+ matvec = A.matvec
285
+ psolve = M.matvec
286
+
287
+ if CU is None:
288
+ CU = []
289
+
290
+ if k is None:
291
+ k = m
292
+
293
+ axpy, dot, scal = None, None, None
294
+
295
+ if x0 is None:
296
+ r = b.copy()
297
+ else:
298
+ r = b - matvec(x)
299
+
300
+ axpy, dot, scal, nrm2 = get_blas_funcs(['axpy', 'dot', 'scal', 'nrm2'], (x, r))
301
+
302
+ b_norm = nrm2(b)
303
+
304
+ # we call this to get the right atol/rtol and raise errors as necessary
305
+ atol, rtol = _get_atol_rtol('gcrotmk', b_norm, atol, rtol)
306
+
307
+ if b_norm == 0:
308
+ x = b
309
+ return (postprocess(x), 0)
310
+
311
+ if discard_C:
312
+ CU[:] = [(None, u) for c, u in CU]
313
+
314
+ # Reorthogonalize old vectors
315
+ if CU:
316
+ # Sort already existing vectors to the front
317
+ CU.sort(key=lambda cu: cu[0] is not None)
318
+
319
+ # Fill-in missing ones
320
+ C = np.empty((A.shape[0], len(CU)), dtype=r.dtype, order='F')
321
+ us = []
322
+ j = 0
323
+ while CU:
324
+ # More memory-efficient: throw away old vectors as we go
325
+ c, u = CU.pop(0)
326
+ if c is None:
327
+ c = matvec(u)
328
+ C[:,j] = c
329
+ j += 1
330
+ us.append(u)
331
+
332
+ # Orthogonalize
333
+ Q, R, P = qr(C, overwrite_a=True, mode='economic', pivoting=True)
334
+ del C
335
+
336
+ # C := Q
337
+ cs = list(Q.T)
338
+
339
+ # U := U P R^-1, back-substitution
340
+ new_us = []
341
+ for j in range(len(cs)):
342
+ u = us[P[j]]
343
+ for i in range(j):
344
+ u = axpy(us[P[i]], u, u.shape[0], -R[i,j])
345
+ if abs(R[j,j]) < 1e-12 * abs(R[0,0]):
346
+ # discard rest of the vectors
347
+ break
348
+ u = scal(1.0/R[j,j], u)
349
+ new_us.append(u)
350
+
351
+ # Form the new CU lists
352
+ CU[:] = list(zip(cs, new_us))[::-1]
353
+
354
+ if CU:
355
+ axpy, dot = get_blas_funcs(['axpy', 'dot'], (r,))
356
+
357
+ # Solve first the projection operation with respect to the CU
358
+ # vectors. This corresponds to modifying the initial guess to
359
+ # be
360
+ #
361
+ # x' = x + U y
362
+ # y = argmin_y || b - A (x + U y) ||^2
363
+ #
364
+ # The solution is y = C^H (b - A x)
365
+ for c, u in CU:
366
+ yc = dot(c, r)
367
+ x = axpy(u, x, x.shape[0], yc)
368
+ r = axpy(c, r, r.shape[0], -yc)
369
+
370
+ # GCROT main iteration
371
+ for j_outer in range(maxiter):
372
+ # -- callback
373
+ if callback is not None:
374
+ callback(x)
375
+
376
+ beta = nrm2(r)
377
+
378
+ # -- check stopping condition
379
+ beta_tol = max(atol, rtol * b_norm)
380
+
381
+ if beta <= beta_tol and (j_outer > 0 or CU):
382
+ # recompute residual to avoid rounding error
383
+ r = b - matvec(x)
384
+ beta = nrm2(r)
385
+
386
+ if beta <= beta_tol:
387
+ j_outer = -1
388
+ break
389
+
390
+ ml = m + max(k - len(CU), 0)
391
+
392
+ cs = [c for c, u in CU]
393
+
394
+ try:
395
+ Q, R, B, vs, zs, y, pres = _fgmres(matvec,
396
+ r/beta,
397
+ ml,
398
+ rpsolve=psolve,
399
+ atol=max(atol, rtol*b_norm)/beta,
400
+ cs=cs)
401
+ y *= beta
402
+ except LinAlgError:
403
+ # Floating point over/underflow, non-finite result from
404
+ # matmul etc. -- report failure.
405
+ break
406
+
407
+ #
408
+ # At this point,
409
+ #
410
+ # [A U, A Z] = [C, V] G; G = [ I B ]
411
+ # [ 0 H ]
412
+ #
413
+ # where [C, V] has orthonormal columns, and r = beta v_0. Moreover,
414
+ #
415
+ # || b - A (x + Z y + U q) ||_2 = || r - C B y - V H y - C q ||_2 = min!
416
+ #
417
+ # from which y = argmin_y || beta e_1 - H y ||_2, and q = -B y
418
+ #
419
+
420
+ #
421
+ # GCROT(m,k) update
422
+ #
423
+
424
+ # Define new outer vectors
425
+
426
+ # ux := (Z - U B) y
427
+ ux = zs[0]*y[0]
428
+ for z, yc in zip(zs[1:], y[1:]):
429
+ ux = axpy(z, ux, ux.shape[0], yc) # ux += z*yc
430
+ by = B.dot(y)
431
+ for cu, byc in zip(CU, by):
432
+ c, u = cu
433
+ ux = axpy(u, ux, ux.shape[0], -byc) # ux -= u*byc
434
+
435
+ # cx := V H y
436
+ with np.errstate(invalid="ignore"):
437
+ hy = Q.dot(R.dot(y))
438
+ cx = vs[0] * hy[0]
439
+ for v, hyc in zip(vs[1:], hy[1:]):
440
+ cx = axpy(v, cx, cx.shape[0], hyc) # cx += v*hyc
441
+
442
+ # Normalize cx, maintaining cx = A ux
443
+ # This new cx is orthogonal to the previous C, by construction
444
+ try:
445
+ alpha = 1/nrm2(cx)
446
+ if not np.isfinite(alpha):
447
+ raise FloatingPointError()
448
+ except (FloatingPointError, ZeroDivisionError):
449
+ # Cannot update, so skip it
450
+ continue
451
+
452
+ cx = scal(alpha, cx)
453
+ ux = scal(alpha, ux)
454
+
455
+ # Update residual and solution
456
+ gamma = dot(cx, r)
457
+ r = axpy(cx, r, r.shape[0], -gamma) # r -= gamma*cx
458
+ x = axpy(ux, x, x.shape[0], gamma) # x += gamma*ux
459
+
460
+ # Truncate CU
461
+ if truncate == 'oldest':
462
+ while len(CU) >= k and CU:
463
+ del CU[0]
464
+ elif truncate == 'smallest':
465
+ if len(CU) >= k and CU:
466
+ # cf. [1,2]
467
+ D = solve(R[:-1,:].T, B.T).T
468
+ W, sigma, V = svd(D)
469
+
470
+ # C := C W[:,:k-1], U := U W[:,:k-1]
471
+ new_CU = []
472
+ for j, w in enumerate(W[:,:k-1].T):
473
+ c, u = CU[0]
474
+ c = c * w[0]
475
+ u = u * w[0]
476
+ for cup, wp in zip(CU[1:], w[1:]):
477
+ cp, up = cup
478
+ c = axpy(cp, c, c.shape[0], wp)
479
+ u = axpy(up, u, u.shape[0], wp)
480
+
481
+ # Reorthogonalize at the same time; not necessary
482
+ # in exact arithmetic, but floating point error
483
+ # tends to accumulate here
484
+ for cp, up in new_CU:
485
+ alpha = dot(cp, c)
486
+ c = axpy(cp, c, c.shape[0], -alpha)
487
+ u = axpy(up, u, u.shape[0], -alpha)
488
+ alpha = nrm2(c)
489
+ c = scal(1.0/alpha, c)
490
+ u = scal(1.0/alpha, u)
491
+
492
+ new_CU.append((c, u))
493
+ CU[:] = new_CU
494
+
495
+ # Add new vector to CU
496
+ CU.append((cx, ux))
497
+
498
+ # Include the solution vector to the span
499
+ CU.append((None, x.copy()))
500
+ if discard_C:
501
+ CU[:] = [(None, uz) for cz, uz in CU]
502
+
503
+ return postprocess(x), j_outer + 1
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/iterative.py ADDED
@@ -0,0 +1,1045 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+ import numpy as np
3
+ from scipy.sparse.linalg._interface import LinearOperator
4
+ from .utils import make_system
5
+ from scipy.linalg import get_lapack_funcs
6
+
7
+ __all__ = ['bicg', 'bicgstab', 'cg', 'cgs', 'gmres', 'qmr']
8
+
9
+
10
+ def _get_atol_rtol(name, b_norm, atol=0., rtol=1e-5):
11
+ """
12
+ A helper function to handle tolerance normalization
13
+ """
14
+ if atol == 'legacy' or atol is None or atol < 0:
15
+ msg = (f"'scipy.sparse.linalg.{name}' called with invalid `atol`={atol}; "
16
+ "if set, `atol` must be a real, non-negative number.")
17
+ raise ValueError(msg)
18
+
19
+ atol = max(float(atol), float(rtol) * float(b_norm))
20
+
21
+ return atol, rtol
22
+
23
+
24
+ def bicg(A, b, x0=None, *, rtol=1e-5, atol=0., maxiter=None, M=None, callback=None):
25
+ """Use BIConjugate Gradient iteration to solve ``Ax = b``.
26
+
27
+ Parameters
28
+ ----------
29
+ A : {sparse array, ndarray, LinearOperator}
30
+ The real or complex N-by-N matrix of the linear system.
31
+ Alternatively, `A` can be a linear operator which can
32
+ produce ``Ax`` and ``A^T x`` using, e.g.,
33
+ ``scipy.sparse.linalg.LinearOperator``.
34
+ b : ndarray
35
+ Right hand side of the linear system. Has shape (N,) or (N,1).
36
+ x0 : ndarray
37
+ Starting guess for the solution.
38
+ rtol, atol : float, optional
39
+ Parameters for the convergence test. For convergence,
40
+ ``norm(b - A @ x) <= max(rtol*norm(b), atol)`` should be satisfied.
41
+ The default is ``atol=0.`` and ``rtol=1e-5``.
42
+ maxiter : integer
43
+ Maximum number of iterations. Iteration will stop after maxiter
44
+ steps even if the specified tolerance has not been achieved.
45
+ M : {sparse array, ndarray, LinearOperator}
46
+ Preconditioner for `A`. It should approximate the
47
+ inverse of `A` (see Notes). Effective preconditioning dramatically improves the
48
+ rate of convergence, which implies that fewer iterations are needed
49
+ to reach a given error tolerance.
50
+ callback : function
51
+ User-supplied function to call after each iteration. It is called
52
+ as ``callback(xk)``, where ``xk`` is the current solution vector.
53
+
54
+ Returns
55
+ -------
56
+ x : ndarray
57
+ The converged solution.
58
+ info : integer
59
+ Provides convergence information:
60
+ 0 : successful exit
61
+ >0 : convergence to tolerance not achieved, number of iterations
62
+ <0 : parameter breakdown
63
+
64
+ Notes
65
+ -----
66
+ The preconditioner `M` should be a matrix such that ``M @ A`` has a smaller
67
+ condition number than `A`, see [1]_ .
68
+
69
+ References
70
+ ----------
71
+ .. [1] "Preconditioner", Wikipedia,
72
+ https://en.wikipedia.org/wiki/Preconditioner
73
+ .. [2] "Biconjugate gradient method", Wikipedia,
74
+ https://en.wikipedia.org/wiki/Biconjugate_gradient_method
75
+
76
+ Examples
77
+ --------
78
+ >>> import numpy as np
79
+ >>> from scipy.sparse import csc_array
80
+ >>> from scipy.sparse.linalg import bicg
81
+ >>> A = csc_array([[3, 2, 0], [1, -1, 0], [0, 5, 1.]])
82
+ >>> b = np.array([2., 4., -1.])
83
+ >>> x, exitCode = bicg(A, b, atol=1e-5)
84
+ >>> print(exitCode) # 0 indicates successful convergence
85
+ 0
86
+ >>> np.allclose(A.dot(x), b)
87
+ True
88
+ """
89
+ A, M, x, b, postprocess = make_system(A, M, x0, b)
90
+ bnrm2 = np.linalg.norm(b)
91
+
92
+ atol, _ = _get_atol_rtol('bicg', bnrm2, atol, rtol)
93
+
94
+ if bnrm2 == 0:
95
+ return postprocess(b), 0
96
+
97
+ n = len(b)
98
+ dotprod = np.vdot if np.iscomplexobj(x) else np.dot
99
+
100
+ if maxiter is None:
101
+ maxiter = n*10
102
+
103
+ matvec, rmatvec = A.matvec, A.rmatvec
104
+ psolve, rpsolve = M.matvec, M.rmatvec
105
+
106
+ rhotol = np.finfo(x.dtype.char).eps**2
107
+
108
+ # Dummy values to initialize vars, silence linter warnings
109
+ rho_prev, p, ptilde = None, None, None
110
+
111
+ r = b - matvec(x) if x.any() else b.copy()
112
+ rtilde = r.copy()
113
+
114
+ for iteration in range(maxiter):
115
+ if np.linalg.norm(r) < atol: # Are we done?
116
+ return postprocess(x), 0
117
+
118
+ z = psolve(r)
119
+ ztilde = rpsolve(rtilde)
120
+ # order matters in this dot product
121
+ rho_cur = dotprod(rtilde, z)
122
+
123
+ if np.abs(rho_cur) < rhotol: # Breakdown case
124
+ return postprocess, -10
125
+
126
+ if iteration > 0:
127
+ beta = rho_cur / rho_prev
128
+ p *= beta
129
+ p += z
130
+ ptilde *= beta.conj()
131
+ ptilde += ztilde
132
+ else: # First spin
133
+ p = z.copy()
134
+ ptilde = ztilde.copy()
135
+
136
+ q = matvec(p)
137
+ qtilde = rmatvec(ptilde)
138
+ rv = dotprod(ptilde, q)
139
+
140
+ if rv == 0:
141
+ return postprocess(x), -11
142
+
143
+ alpha = rho_cur / rv
144
+ x += alpha*p
145
+ r -= alpha*q
146
+ rtilde -= alpha.conj()*qtilde
147
+ rho_prev = rho_cur
148
+
149
+ if callback:
150
+ callback(x)
151
+
152
+ else: # for loop exhausted
153
+ # Return incomplete progress
154
+ return postprocess(x), maxiter
155
+
156
+
157
+ def bicgstab(A, b, x0=None, *, rtol=1e-5, atol=0., maxiter=None, M=None,
158
+ callback=None):
159
+ """Use BIConjugate Gradient STABilized iteration to solve ``Ax = b``.
160
+
161
+ Parameters
162
+ ----------
163
+ A : {sparse array, ndarray, LinearOperator}
164
+ The real or complex N-by-N matrix of the linear system.
165
+ Alternatively, `A` can be a linear operator which can
166
+ produce ``Ax`` and ``A^T x`` using, e.g.,
167
+ ``scipy.sparse.linalg.LinearOperator``.
168
+ b : ndarray
169
+ Right hand side of the linear system. Has shape (N,) or (N,1).
170
+ x0 : ndarray
171
+ Starting guess for the solution.
172
+ rtol, atol : float, optional
173
+ Parameters for the convergence test. For convergence,
174
+ ``norm(b - A @ x) <= max(rtol*norm(b), atol)`` should be satisfied.
175
+ The default is ``atol=0.`` and ``rtol=1e-5``.
176
+ maxiter : integer
177
+ Maximum number of iterations. Iteration will stop after maxiter
178
+ steps even if the specified tolerance has not been achieved.
179
+ M : {sparse array, ndarray, LinearOperator}
180
+ Preconditioner for `A`. It should approximate the
181
+ inverse of `A` (see Notes). Effective preconditioning dramatically improves the
182
+ rate of convergence, which implies that fewer iterations are needed
183
+ to reach a given error tolerance.
184
+ callback : function
185
+ User-supplied function to call after each iteration. It is called
186
+ as ``callback(xk)``, where ``xk`` is the current solution vector.
187
+
188
+ Returns
189
+ -------
190
+ x : ndarray
191
+ The converged solution.
192
+ info : integer
193
+ Provides convergence information:
194
+ 0 : successful exit
195
+ >0 : convergence to tolerance not achieved, number of iterations
196
+ <0 : parameter breakdown
197
+
198
+ Notes
199
+ -----
200
+ The preconditioner `M` should be a matrix such that ``M @ A`` has a smaller
201
+ condition number than `A`, see [1]_ .
202
+
203
+ References
204
+ ----------
205
+ .. [1] "Preconditioner", Wikipedia,
206
+ https://en.wikipedia.org/wiki/Preconditioner
207
+ .. [2] "Biconjugate gradient stabilized method",
208
+ Wikipedia, https://en.wikipedia.org/wiki/Biconjugate_gradient_stabilized_method
209
+
210
+ Examples
211
+ --------
212
+ >>> import numpy as np
213
+ >>> from scipy.sparse import csc_array
214
+ >>> from scipy.sparse.linalg import bicgstab
215
+ >>> R = np.array([[4, 2, 0, 1],
216
+ ... [3, 0, 0, 2],
217
+ ... [0, 1, 1, 1],
218
+ ... [0, 2, 1, 0]])
219
+ >>> A = csc_array(R)
220
+ >>> b = np.array([-1, -0.5, -1, 2])
221
+ >>> x, exit_code = bicgstab(A, b, atol=1e-5)
222
+ >>> print(exit_code) # 0 indicates successful convergence
223
+ 0
224
+ >>> np.allclose(A.dot(x), b)
225
+ True
226
+ """
227
+ A, M, x, b, postprocess = make_system(A, M, x0, b)
228
+ bnrm2 = np.linalg.norm(b)
229
+
230
+ atol, _ = _get_atol_rtol('bicgstab', bnrm2, atol, rtol)
231
+
232
+ if bnrm2 == 0:
233
+ return postprocess(b), 0
234
+
235
+ n = len(b)
236
+
237
+ dotprod = np.vdot if np.iscomplexobj(x) else np.dot
238
+
239
+ if maxiter is None:
240
+ maxiter = n*10
241
+
242
+ matvec = A.matvec
243
+ psolve = M.matvec
244
+
245
+ # These values make no sense but coming from original Fortran code
246
+ # sqrt might have been meant instead.
247
+ rhotol = np.finfo(x.dtype.char).eps**2
248
+ omegatol = rhotol
249
+
250
+ # Dummy values to initialize vars, silence linter warnings
251
+ rho_prev, omega, alpha, p, v = None, None, None, None, None
252
+
253
+ r = b - matvec(x) if x.any() else b.copy()
254
+ rtilde = r.copy()
255
+
256
+ for iteration in range(maxiter):
257
+ if np.linalg.norm(r) < atol: # Are we done?
258
+ return postprocess(x), 0
259
+
260
+ rho = dotprod(rtilde, r)
261
+ if np.abs(rho) < rhotol: # rho breakdown
262
+ return postprocess(x), -10
263
+
264
+ if iteration > 0:
265
+ if np.abs(omega) < omegatol: # omega breakdown
266
+ return postprocess(x), -11
267
+
268
+ beta = (rho / rho_prev) * (alpha / omega)
269
+ p -= omega*v
270
+ p *= beta
271
+ p += r
272
+ else: # First spin
273
+ s = np.empty_like(r)
274
+ p = r.copy()
275
+
276
+ phat = psolve(p)
277
+ v = matvec(phat)
278
+ rv = dotprod(rtilde, v)
279
+ if rv == 0:
280
+ return postprocess(x), -11
281
+ alpha = rho / rv
282
+ r -= alpha*v
283
+ s[:] = r[:]
284
+
285
+ if np.linalg.norm(s) < atol:
286
+ x += alpha*phat
287
+ return postprocess(x), 0
288
+
289
+ shat = psolve(s)
290
+ t = matvec(shat)
291
+ omega = dotprod(t, s) / dotprod(t, t)
292
+ x += alpha*phat
293
+ x += omega*shat
294
+ r -= omega*t
295
+ rho_prev = rho
296
+
297
+ if callback:
298
+ callback(x)
299
+
300
+ else: # for loop exhausted
301
+ # Return incomplete progress
302
+ return postprocess(x), maxiter
303
+
304
+
305
+ def cg(A, b, x0=None, *, rtol=1e-5, atol=0., maxiter=None, M=None, callback=None):
306
+ """Use Conjugate Gradient iteration to solve ``Ax = b``.
307
+
308
+ Parameters
309
+ ----------
310
+ A : {sparse array, ndarray, LinearOperator}
311
+ The real or complex N-by-N matrix of the linear system.
312
+ `A` must represent a hermitian, positive definite matrix.
313
+ Alternatively, `A` can be a linear operator which can
314
+ produce ``Ax`` using, e.g.,
315
+ ``scipy.sparse.linalg.LinearOperator``.
316
+ b : ndarray
317
+ Right hand side of the linear system. Has shape (N,) or (N,1).
318
+ x0 : ndarray
319
+ Starting guess for the solution.
320
+ rtol, atol : float, optional
321
+ Parameters for the convergence test. For convergence,
322
+ ``norm(b - A @ x) <= max(rtol*norm(b), atol)`` should be satisfied.
323
+ The default is ``atol=0.`` and ``rtol=1e-5``.
324
+ maxiter : integer
325
+ Maximum number of iterations. Iteration will stop after maxiter
326
+ steps even if the specified tolerance has not been achieved.
327
+ M : {sparse array, ndarray, LinearOperator}
328
+ Preconditioner for `A`. `M` must represent a hermitian, positive definite
329
+ matrix. It should approximate the inverse of `A` (see Notes).
330
+ Effective preconditioning dramatically improves the
331
+ rate of convergence, which implies that fewer iterations are needed
332
+ to reach a given error tolerance.
333
+ callback : function
334
+ User-supplied function to call after each iteration. It is called
335
+ as ``callback(xk)``, where ``xk`` is the current solution vector.
336
+
337
+ Returns
338
+ -------
339
+ x : ndarray
340
+ The converged solution.
341
+ info : integer
342
+ Provides convergence information:
343
+ 0 : successful exit
344
+ >0 : convergence to tolerance not achieved, number of iterations
345
+
346
+ Notes
347
+ -----
348
+ The preconditioner `M` should be a matrix such that ``M @ A`` has a smaller
349
+ condition number than `A`, see [2]_.
350
+
351
+ References
352
+ ----------
353
+ .. [1] "Conjugate Gradient Method, Wikipedia,
354
+ https://en.wikipedia.org/wiki/Conjugate_gradient_method
355
+ .. [2] "Preconditioner",
356
+ Wikipedia, https://en.wikipedia.org/wiki/Preconditioner
357
+
358
+ Examples
359
+ --------
360
+ >>> import numpy as np
361
+ >>> from scipy.sparse import csc_array
362
+ >>> from scipy.sparse.linalg import cg
363
+ >>> P = np.array([[4, 0, 1, 0],
364
+ ... [0, 5, 0, 0],
365
+ ... [1, 0, 3, 2],
366
+ ... [0, 0, 2, 4]])
367
+ >>> A = csc_array(P)
368
+ >>> b = np.array([-1, -0.5, -1, 2])
369
+ >>> x, exit_code = cg(A, b, atol=1e-5)
370
+ >>> print(exit_code) # 0 indicates successful convergence
371
+ 0
372
+ >>> np.allclose(A.dot(x), b)
373
+ True
374
+ """
375
+ A, M, x, b, postprocess = make_system(A, M, x0, b)
376
+ bnrm2 = np.linalg.norm(b)
377
+
378
+ atol, _ = _get_atol_rtol('cg', bnrm2, atol, rtol)
379
+
380
+ if bnrm2 == 0:
381
+ return postprocess(b), 0
382
+
383
+ n = len(b)
384
+
385
+ if maxiter is None:
386
+ maxiter = n*10
387
+
388
+ dotprod = np.vdot if np.iscomplexobj(x) else np.dot
389
+
390
+ matvec = A.matvec
391
+ psolve = M.matvec
392
+ r = b - matvec(x) if x.any() else b.copy()
393
+
394
+ # Dummy value to initialize var, silences warnings
395
+ rho_prev, p = None, None
396
+
397
+ for iteration in range(maxiter):
398
+ if np.linalg.norm(r) < atol: # Are we done?
399
+ return postprocess(x), 0
400
+
401
+ z = psolve(r)
402
+ rho_cur = dotprod(r, z)
403
+ if iteration > 0:
404
+ beta = rho_cur / rho_prev
405
+ p *= beta
406
+ p += z
407
+ else: # First spin
408
+ p = np.empty_like(r)
409
+ p[:] = z[:]
410
+
411
+ q = matvec(p)
412
+ alpha = rho_cur / dotprod(p, q)
413
+ x += alpha*p
414
+ r -= alpha*q
415
+ rho_prev = rho_cur
416
+
417
+ if callback:
418
+ callback(x)
419
+
420
+ else: # for loop exhausted
421
+ # Return incomplete progress
422
+ return postprocess(x), maxiter
423
+
424
+
425
+ def cgs(A, b, x0=None, *, rtol=1e-5, atol=0., maxiter=None, M=None, callback=None):
426
+ """Use Conjugate Gradient Squared iteration to solve ``Ax = b``.
427
+
428
+ Parameters
429
+ ----------
430
+ A : {sparse array, ndarray, LinearOperator}
431
+ The real-valued N-by-N matrix of the linear system.
432
+ Alternatively, `A` can be a linear operator which can
433
+ produce ``Ax`` using, e.g.,
434
+ ``scipy.sparse.linalg.LinearOperator``.
435
+ b : ndarray
436
+ Right hand side of the linear system. Has shape (N,) or (N,1).
437
+ x0 : ndarray
438
+ Starting guess for the solution.
439
+ rtol, atol : float, optional
440
+ Parameters for the convergence test. For convergence,
441
+ ``norm(b - A @ x) <= max(rtol*norm(b), atol)`` should be satisfied.
442
+ The default is ``atol=0.`` and ``rtol=1e-5``.
443
+ maxiter : integer
444
+ Maximum number of iterations. Iteration will stop after maxiter
445
+ steps even if the specified tolerance has not been achieved.
446
+ M : {sparse array, ndarray, LinearOperator}
447
+ Preconditioner for ``A``. It should approximate the
448
+ inverse of `A` (see Notes). Effective preconditioning dramatically improves the
449
+ rate of convergence, which implies that fewer iterations are needed
450
+ to reach a given error tolerance.
451
+ callback : function
452
+ User-supplied function to call after each iteration. It is called
453
+ as ``callback(xk)``, where ``xk`` is the current solution vector.
454
+
455
+ Returns
456
+ -------
457
+ x : ndarray
458
+ The converged solution.
459
+ info : integer
460
+ Provides convergence information:
461
+ 0 : successful exit
462
+ >0 : convergence to tolerance not achieved, number of iterations
463
+ <0 : parameter breakdown
464
+
465
+ Notes
466
+ -----
467
+ The preconditioner `M` should be a matrix such that ``M @ A`` has a smaller
468
+ condition number than `A`, see [1]_.
469
+
470
+ References
471
+ ----------
472
+ .. [1] "Preconditioner", Wikipedia,
473
+ https://en.wikipedia.org/wiki/Preconditioner
474
+ .. [2] "Conjugate gradient squared", Wikipedia,
475
+ https://en.wikipedia.org/wiki/Conjugate_gradient_squared_method
476
+
477
+ Examples
478
+ --------
479
+ >>> import numpy as np
480
+ >>> from scipy.sparse import csc_array
481
+ >>> from scipy.sparse.linalg import cgs
482
+ >>> R = np.array([[4, 2, 0, 1],
483
+ ... [3, 0, 0, 2],
484
+ ... [0, 1, 1, 1],
485
+ ... [0, 2, 1, 0]])
486
+ >>> A = csc_array(R)
487
+ >>> b = np.array([-1, -0.5, -1, 2])
488
+ >>> x, exit_code = cgs(A, b)
489
+ >>> print(exit_code) # 0 indicates successful convergence
490
+ 0
491
+ >>> np.allclose(A.dot(x), b)
492
+ True
493
+ """
494
+ A, M, x, b, postprocess = make_system(A, M, x0, b)
495
+ bnrm2 = np.linalg.norm(b)
496
+
497
+ atol, _ = _get_atol_rtol('cgs', bnrm2, atol, rtol)
498
+
499
+ if bnrm2 == 0:
500
+ return postprocess(b), 0
501
+
502
+ n = len(b)
503
+
504
+ dotprod = np.vdot if np.iscomplexobj(x) else np.dot
505
+
506
+ if maxiter is None:
507
+ maxiter = n*10
508
+
509
+ matvec = A.matvec
510
+ psolve = M.matvec
511
+
512
+ rhotol = np.finfo(x.dtype.char).eps**2
513
+
514
+ r = b - matvec(x) if x.any() else b.copy()
515
+
516
+ rtilde = r.copy()
517
+ bnorm = np.linalg.norm(b)
518
+ if bnorm == 0:
519
+ bnorm = 1
520
+
521
+ # Dummy values to initialize vars, silence linter warnings
522
+ rho_prev, p, u, q = None, None, None, None
523
+
524
+ for iteration in range(maxiter):
525
+ rnorm = np.linalg.norm(r)
526
+ if rnorm < atol: # Are we done?
527
+ return postprocess(x), 0
528
+
529
+ rho_cur = dotprod(rtilde, r)
530
+ if np.abs(rho_cur) < rhotol: # Breakdown case
531
+ return postprocess, -10
532
+
533
+ if iteration > 0:
534
+ beta = rho_cur / rho_prev
535
+
536
+ # u = r + beta * q
537
+ # p = u + beta * (q + beta * p);
538
+ u[:] = r[:]
539
+ u += beta*q
540
+
541
+ p *= beta
542
+ p += q
543
+ p *= beta
544
+ p += u
545
+
546
+ else: # First spin
547
+ p = r.copy()
548
+ u = r.copy()
549
+ q = np.empty_like(r)
550
+
551
+ phat = psolve(p)
552
+ vhat = matvec(phat)
553
+ rv = dotprod(rtilde, vhat)
554
+
555
+ if rv == 0: # Dot product breakdown
556
+ return postprocess(x), -11
557
+
558
+ alpha = rho_cur / rv
559
+ q[:] = u[:]
560
+ q -= alpha*vhat
561
+ uhat = psolve(u + q)
562
+ x += alpha*uhat
563
+
564
+ # Due to numerical error build-up the actual residual is computed
565
+ # instead of the following two lines that were in the original
566
+ # FORTRAN templates, still using a single matvec.
567
+
568
+ # qhat = matvec(uhat)
569
+ # r -= alpha*qhat
570
+ r = b - matvec(x)
571
+
572
+ rho_prev = rho_cur
573
+
574
+ if callback:
575
+ callback(x)
576
+
577
+ else: # for loop exhausted
578
+ # Return incomplete progress
579
+ return postprocess(x), maxiter
580
+
581
+
582
+ def gmres(A, b, x0=None, *, rtol=1e-5, atol=0., restart=None, maxiter=None, M=None,
583
+ callback=None, callback_type=None):
584
+ """
585
+ Use Generalized Minimal RESidual iteration to solve ``Ax = b``.
586
+
587
+ Parameters
588
+ ----------
589
+ A : {sparse array, ndarray, LinearOperator}
590
+ The real or complex N-by-N matrix of the linear system.
591
+ Alternatively, `A` can be a linear operator which can
592
+ produce ``Ax`` using, e.g.,
593
+ ``scipy.sparse.linalg.LinearOperator``.
594
+ b : ndarray
595
+ Right hand side of the linear system. Has shape (N,) or (N,1).
596
+ x0 : ndarray
597
+ Starting guess for the solution (a vector of zeros by default).
598
+ atol, rtol : float
599
+ Parameters for the convergence test. For convergence,
600
+ ``norm(b - A @ x) <= max(rtol*norm(b), atol)`` should be satisfied.
601
+ The default is ``atol=0.`` and ``rtol=1e-5``.
602
+ restart : int, optional
603
+ Number of iterations between restarts. Larger values increase
604
+ iteration cost, but may be necessary for convergence.
605
+ If omitted, ``min(20, n)`` is used.
606
+ maxiter : int, optional
607
+ Maximum number of iterations (restart cycles). Iteration will stop
608
+ after maxiter steps even if the specified tolerance has not been
609
+ achieved. See `callback_type`.
610
+ M : {sparse array, ndarray, LinearOperator}
611
+ Inverse of the preconditioner of `A`. `M` should approximate the
612
+ inverse of `A` and be easy to solve for (see Notes). Effective
613
+ preconditioning dramatically improves the rate of convergence,
614
+ which implies that fewer iterations are needed to reach a given
615
+ error tolerance. By default, no preconditioner is used.
616
+ In this implementation, left preconditioning is used,
617
+ and the preconditioned residual is minimized. However, the final
618
+ convergence is tested with respect to the ``b - A @ x`` residual.
619
+ callback : function
620
+ User-supplied function to call after each iteration. It is called
621
+ as ``callback(args)``, where ``args`` are selected by `callback_type`.
622
+ callback_type : {'x', 'pr_norm', 'legacy'}, optional
623
+ Callback function argument requested:
624
+ - ``x``: current iterate (ndarray), called on every restart
625
+ - ``pr_norm``: relative (preconditioned) residual norm (float),
626
+ called on every inner iteration
627
+ - ``legacy`` (default): same as ``pr_norm``, but also changes the
628
+ meaning of `maxiter` to count inner iterations instead of restart
629
+ cycles.
630
+
631
+ This keyword has no effect if `callback` is not set.
632
+
633
+ Returns
634
+ -------
635
+ x : ndarray
636
+ The converged solution.
637
+ info : int
638
+ Provides convergence information:
639
+ 0 : successful exit
640
+ >0 : convergence to tolerance not achieved, number of iterations
641
+
642
+ See Also
643
+ --------
644
+ LinearOperator
645
+
646
+ Notes
647
+ -----
648
+ A preconditioner, P, is chosen such that P is close to A but easy to solve
649
+ for. The preconditioner parameter required by this routine is
650
+ ``M = P^-1``. The inverse should preferably not be calculated
651
+ explicitly. Rather, use the following template to produce M::
652
+
653
+ # Construct a linear operator that computes P^-1 @ x.
654
+ import scipy.sparse.linalg as spla
655
+ M_x = lambda x: spla.spsolve(P, x)
656
+ M = spla.LinearOperator((n, n), M_x)
657
+
658
+ Examples
659
+ --------
660
+ >>> import numpy as np
661
+ >>> from scipy.sparse import csc_array
662
+ >>> from scipy.sparse.linalg import gmres
663
+ >>> A = csc_array([[3, 2, 0], [1, -1, 0], [0, 5, 1]], dtype=float)
664
+ >>> b = np.array([2, 4, -1], dtype=float)
665
+ >>> x, exitCode = gmres(A, b, atol=1e-5)
666
+ >>> print(exitCode) # 0 indicates successful convergence
667
+ 0
668
+ >>> np.allclose(A.dot(x), b)
669
+ True
670
+ """
671
+ if callback is not None and callback_type is None:
672
+ # Warn about 'callback_type' semantic changes.
673
+ # Probably should be removed only in far future, Scipy 2.0 or so.
674
+ msg = ("scipy.sparse.linalg.gmres called without specifying "
675
+ "`callback_type`. The default value will be changed in"
676
+ " a future release. For compatibility, specify a value "
677
+ "for `callback_type` explicitly, e.g., "
678
+ "``gmres(..., callback_type='pr_norm')``, or to retain the "
679
+ "old behavior ``gmres(..., callback_type='legacy')``"
680
+ )
681
+ warnings.warn(msg, category=DeprecationWarning, stacklevel=3)
682
+
683
+ if callback_type is None:
684
+ callback_type = 'legacy'
685
+
686
+ if callback_type not in ('x', 'pr_norm', 'legacy'):
687
+ raise ValueError(f"Unknown callback_type: {callback_type!r}")
688
+
689
+ if callback is None:
690
+ callback_type = None
691
+
692
+ A, M, x, b, postprocess = make_system(A, M, x0, b)
693
+ matvec = A.matvec
694
+ psolve = M.matvec
695
+ n = len(b)
696
+ bnrm2 = np.linalg.norm(b)
697
+
698
+ atol, _ = _get_atol_rtol('gmres', bnrm2, atol, rtol)
699
+
700
+ if bnrm2 == 0:
701
+ return postprocess(b), 0
702
+
703
+ eps = np.finfo(x.dtype.char).eps
704
+
705
+ dotprod = np.vdot if np.iscomplexobj(x) else np.dot
706
+
707
+ if maxiter is None:
708
+ maxiter = n*10
709
+
710
+ if restart is None:
711
+ restart = 20
712
+ restart = min(restart, n)
713
+
714
+ Mb_nrm2 = np.linalg.norm(psolve(b))
715
+
716
+ # ====================================================
717
+ # =========== Tolerance control from gh-8400 =========
718
+ # ====================================================
719
+ # Tolerance passed to GMRESREVCOM applies to the inner
720
+ # iteration and deals with the left-preconditioned
721
+ # residual.
722
+ ptol_max_factor = 1.
723
+ ptol = Mb_nrm2 * min(ptol_max_factor, atol / bnrm2)
724
+ presid = 0.
725
+ # ====================================================
726
+ lartg = get_lapack_funcs('lartg', dtype=x.dtype)
727
+
728
+ # allocate internal variables
729
+ v = np.empty([restart+1, n], dtype=x.dtype)
730
+ h = np.zeros([restart, restart+1], dtype=x.dtype)
731
+ givens = np.zeros([restart, 2], dtype=x.dtype)
732
+
733
+ # legacy iteration count
734
+ inner_iter = 0
735
+
736
+ for iteration in range(maxiter):
737
+ if iteration == 0:
738
+ r = b - matvec(x) if x.any() else b.copy()
739
+ if np.linalg.norm(r) < atol: # Are we done?
740
+ return postprocess(x), 0
741
+
742
+ v[0, :] = psolve(r)
743
+ tmp = np.linalg.norm(v[0, :])
744
+ v[0, :] *= (1 / tmp)
745
+ # RHS of the Hessenberg problem
746
+ S = np.zeros(restart+1, dtype=x.dtype)
747
+ S[0] = tmp
748
+
749
+ breakdown = False
750
+ for col in range(restart):
751
+ av = matvec(v[col, :])
752
+ w = psolve(av)
753
+
754
+ # Modified Gram-Schmidt
755
+ h0 = np.linalg.norm(w)
756
+ for k in range(col+1):
757
+ tmp = dotprod(v[k, :], w)
758
+ h[col, k] = tmp
759
+ w -= tmp*v[k, :]
760
+
761
+ h1 = np.linalg.norm(w)
762
+ h[col, col + 1] = h1
763
+ v[col + 1, :] = w[:]
764
+
765
+ # Exact solution indicator
766
+ if h1 <= eps*h0:
767
+ h[col, col + 1] = 0
768
+ breakdown = True
769
+ else:
770
+ v[col + 1, :] *= (1 / h1)
771
+
772
+ # apply past Givens rotations to current h column
773
+ for k in range(col):
774
+ c, s = givens[k, 0], givens[k, 1]
775
+ n0, n1 = h[col, [k, k+1]]
776
+ h[col, [k, k + 1]] = [c*n0 + s*n1, -s.conj()*n0 + c*n1]
777
+
778
+ # get and apply current rotation to h and S
779
+ c, s, mag = lartg(h[col, col], h[col, col+1])
780
+ givens[col, :] = [c, s]
781
+ h[col, [col, col+1]] = mag, 0
782
+
783
+ # S[col+1] component is always 0
784
+ tmp = -np.conjugate(s)*S[col]
785
+ S[[col, col + 1]] = [c*S[col], tmp]
786
+ presid = np.abs(tmp)
787
+ inner_iter += 1
788
+
789
+ if callback_type in ('legacy', 'pr_norm'):
790
+ callback(presid / bnrm2)
791
+ # Legacy behavior
792
+ if callback_type == 'legacy' and inner_iter == maxiter:
793
+ break
794
+ if presid <= ptol or breakdown:
795
+ break
796
+
797
+ # Solve h(col, col) upper triangular system and allow pseudo-solve
798
+ # singular cases as in (but without the f2py copies):
799
+ # y = trsv(h[:col+1, :col+1].T, S[:col+1])
800
+
801
+ if h[col, col] == 0:
802
+ S[col] = 0
803
+
804
+ y = np.zeros([col+1], dtype=x.dtype)
805
+ y[:] = S[:col+1]
806
+ for k in range(col, 0, -1):
807
+ if y[k] != 0:
808
+ y[k] /= h[k, k]
809
+ tmp = y[k]
810
+ y[:k] -= tmp*h[k, :k]
811
+ if y[0] != 0:
812
+ y[0] /= h[0, 0]
813
+
814
+ x += y @ v[:col+1, :]
815
+
816
+ r = b - matvec(x)
817
+ rnorm = np.linalg.norm(r)
818
+
819
+ # Legacy exit
820
+ if callback_type == 'legacy' and inner_iter == maxiter:
821
+ return postprocess(x), 0 if rnorm <= atol else maxiter
822
+
823
+ if callback_type == 'x':
824
+ callback(x)
825
+
826
+ if rnorm <= atol:
827
+ break
828
+ elif breakdown:
829
+ # Reached breakdown (= exact solution), but the external
830
+ # tolerance check failed. Bail out with failure.
831
+ break
832
+ elif presid <= ptol:
833
+ # Inner loop passed but outer didn't
834
+ ptol_max_factor = max(eps, 0.25 * ptol_max_factor)
835
+ else:
836
+ ptol_max_factor = min(1.0, 1.5 * ptol_max_factor)
837
+
838
+ ptol = presid * min(ptol_max_factor, atol / rnorm)
839
+
840
+ info = 0 if (rnorm <= atol) else maxiter
841
+ return postprocess(x), info
842
+
843
+
844
+ def qmr(A, b, x0=None, *, rtol=1e-5, atol=0., maxiter=None, M1=None, M2=None,
845
+ callback=None):
846
+ """Use Quasi-Minimal Residual iteration to solve ``Ax = b``.
847
+
848
+ Parameters
849
+ ----------
850
+ A : {sparse array, ndarray, LinearOperator}
851
+ The real-valued N-by-N matrix of the linear system.
852
+ Alternatively, ``A`` can be a linear operator which can
853
+ produce ``Ax`` and ``A^T x`` using, e.g.,
854
+ ``scipy.sparse.linalg.LinearOperator``.
855
+ b : ndarray
856
+ Right hand side of the linear system. Has shape (N,) or (N,1).
857
+ x0 : ndarray
858
+ Starting guess for the solution.
859
+ atol, rtol : float, optional
860
+ Parameters for the convergence test. For convergence,
861
+ ``norm(b - A @ x) <= max(rtol*norm(b), atol)`` should be satisfied.
862
+ The default is ``atol=0.`` and ``rtol=1e-5``.
863
+ maxiter : integer
864
+ Maximum number of iterations. Iteration will stop after maxiter
865
+ steps even if the specified tolerance has not been achieved.
866
+ M1 : {sparse array, ndarray, LinearOperator}
867
+ Left preconditioner for A.
868
+ M2 : {sparse array, ndarray, LinearOperator}
869
+ Right preconditioner for A. Used together with the left
870
+ preconditioner M1. The matrix M1@A@M2 should have better
871
+ conditioned than A alone.
872
+ callback : function
873
+ User-supplied function to call after each iteration. It is called
874
+ as callback(xk), where xk is the current solution vector.
875
+
876
+ Returns
877
+ -------
878
+ x : ndarray
879
+ The converged solution.
880
+ info : integer
881
+ Provides convergence information:
882
+ 0 : successful exit
883
+ >0 : convergence to tolerance not achieved, number of iterations
884
+ <0 : parameter breakdown
885
+
886
+ See Also
887
+ --------
888
+ LinearOperator
889
+
890
+ Examples
891
+ --------
892
+ >>> import numpy as np
893
+ >>> from scipy.sparse import csc_array
894
+ >>> from scipy.sparse.linalg import qmr
895
+ >>> A = csc_array([[3., 2., 0.], [1., -1., 0.], [0., 5., 1.]])
896
+ >>> b = np.array([2., 4., -1.])
897
+ >>> x, exitCode = qmr(A, b, atol=1e-5)
898
+ >>> print(exitCode) # 0 indicates successful convergence
899
+ 0
900
+ >>> np.allclose(A.dot(x), b)
901
+ True
902
+ """
903
+ A_ = A
904
+ A, M, x, b, postprocess = make_system(A, None, x0, b)
905
+ bnrm2 = np.linalg.norm(b)
906
+
907
+ atol, _ = _get_atol_rtol('qmr', bnrm2, atol, rtol)
908
+
909
+ if bnrm2 == 0:
910
+ return postprocess(b), 0
911
+
912
+ if M1 is None and M2 is None:
913
+ if hasattr(A_, 'psolve'):
914
+ def left_psolve(b):
915
+ return A_.psolve(b, 'left')
916
+
917
+ def right_psolve(b):
918
+ return A_.psolve(b, 'right')
919
+
920
+ def left_rpsolve(b):
921
+ return A_.rpsolve(b, 'left')
922
+
923
+ def right_rpsolve(b):
924
+ return A_.rpsolve(b, 'right')
925
+ M1 = LinearOperator(A.shape,
926
+ matvec=left_psolve,
927
+ rmatvec=left_rpsolve)
928
+ M2 = LinearOperator(A.shape,
929
+ matvec=right_psolve,
930
+ rmatvec=right_rpsolve)
931
+ else:
932
+ def id(b):
933
+ return b
934
+ M1 = LinearOperator(A.shape, matvec=id, rmatvec=id)
935
+ M2 = LinearOperator(A.shape, matvec=id, rmatvec=id)
936
+
937
+ n = len(b)
938
+ if maxiter is None:
939
+ maxiter = n*10
940
+
941
+ dotprod = np.vdot if np.iscomplexobj(x) else np.dot
942
+
943
+ rhotol = np.finfo(x.dtype.char).eps
944
+ betatol = rhotol
945
+ gammatol = rhotol
946
+ deltatol = rhotol
947
+ epsilontol = rhotol
948
+ xitol = rhotol
949
+
950
+ r = b - A.matvec(x) if x.any() else b.copy()
951
+
952
+ vtilde = r.copy()
953
+ y = M1.matvec(vtilde)
954
+ rho = np.linalg.norm(y)
955
+ wtilde = r.copy()
956
+ z = M2.rmatvec(wtilde)
957
+ xi = np.linalg.norm(z)
958
+ gamma, eta, theta = 1, -1, 0
959
+ v = np.empty_like(vtilde)
960
+ w = np.empty_like(wtilde)
961
+
962
+ # Dummy values to initialize vars, silence linter warnings
963
+ epsilon, q, d, p, s = None, None, None, None, None
964
+
965
+ for iteration in range(maxiter):
966
+ if np.linalg.norm(r) < atol: # Are we done?
967
+ return postprocess(x), 0
968
+ if np.abs(rho) < rhotol: # rho breakdown
969
+ return postprocess(x), -10
970
+ if np.abs(xi) < xitol: # xi breakdown
971
+ return postprocess(x), -15
972
+
973
+ v[:] = vtilde[:]
974
+ v *= (1 / rho)
975
+ y *= (1 / rho)
976
+ w[:] = wtilde[:]
977
+ w *= (1 / xi)
978
+ z *= (1 / xi)
979
+ delta = dotprod(z, y)
980
+
981
+ if np.abs(delta) < deltatol: # delta breakdown
982
+ return postprocess(x), -13
983
+
984
+ ytilde = M2.matvec(y)
985
+ ztilde = M1.rmatvec(z)
986
+
987
+ if iteration > 0:
988
+ ytilde -= (xi * delta / epsilon) * p
989
+ p[:] = ytilde[:]
990
+ ztilde -= (rho * (delta / epsilon).conj()) * q
991
+ q[:] = ztilde[:]
992
+ else: # First spin
993
+ p = ytilde.copy()
994
+ q = ztilde.copy()
995
+
996
+ ptilde = A.matvec(p)
997
+ epsilon = dotprod(q, ptilde)
998
+ if np.abs(epsilon) < epsilontol: # epsilon breakdown
999
+ return postprocess(x), -14
1000
+
1001
+ beta = epsilon / delta
1002
+ if np.abs(beta) < betatol: # beta breakdown
1003
+ return postprocess(x), -11
1004
+
1005
+ vtilde[:] = ptilde[:]
1006
+ vtilde -= beta*v
1007
+ y = M1.matvec(vtilde)
1008
+
1009
+ rho_prev = rho
1010
+ rho = np.linalg.norm(y)
1011
+ wtilde[:] = w[:]
1012
+ wtilde *= - beta.conj()
1013
+ wtilde += A.rmatvec(q)
1014
+ z = M2.rmatvec(wtilde)
1015
+ xi = np.linalg.norm(z)
1016
+ gamma_prev = gamma
1017
+ theta_prev = theta
1018
+ theta = rho / (gamma_prev * np.abs(beta))
1019
+ gamma = 1 / np.sqrt(1 + theta**2)
1020
+
1021
+ if np.abs(gamma) < gammatol: # gamma breakdown
1022
+ return postprocess(x), -12
1023
+
1024
+ eta *= -(rho_prev / beta) * (gamma / gamma_prev)**2
1025
+
1026
+ if iteration > 0:
1027
+ d *= (theta_prev * gamma) ** 2
1028
+ d += eta*p
1029
+ s *= (theta_prev * gamma) ** 2
1030
+ s += eta*ptilde
1031
+ else:
1032
+ d = p.copy()
1033
+ d *= eta
1034
+ s = ptilde.copy()
1035
+ s *= eta
1036
+
1037
+ x += d
1038
+ r -= s
1039
+
1040
+ if callback:
1041
+ callback(x)
1042
+
1043
+ else: # for loop exhausted
1044
+ # Return incomplete progress
1045
+ return postprocess(x), maxiter
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/lgmres.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) 2009, Pauli Virtanen <pav@iki.fi>
2
+ # Distributed under the same license as SciPy.
3
+
4
+ import numpy as np
5
+ from numpy.linalg import LinAlgError
6
+ from scipy.linalg import get_blas_funcs
7
+ from .iterative import _get_atol_rtol
8
+ from .utils import make_system
9
+
10
+ from ._gcrotmk import _fgmres
11
+
12
+ __all__ = ['lgmres']
13
+
14
+
15
+ def lgmres(A, b, x0=None, *, rtol=1e-5, atol=0., maxiter=1000, M=None, callback=None,
16
+ inner_m=30, outer_k=3, outer_v=None, store_outer_Av=True,
17
+ prepend_outer_v=False):
18
+ """
19
+ Solve a matrix equation using the LGMRES algorithm.
20
+
21
+ The LGMRES algorithm [1]_ [2]_ is designed to avoid some problems
22
+ in the convergence in restarted GMRES, and often converges in fewer
23
+ iterations.
24
+
25
+ Parameters
26
+ ----------
27
+ A : {sparse array, ndarray, LinearOperator}
28
+ The real or complex N-by-N matrix of the linear system.
29
+ Alternatively, ``A`` can be a linear operator which can
30
+ produce ``Ax`` using, e.g.,
31
+ ``scipy.sparse.linalg.LinearOperator``.
32
+ b : ndarray
33
+ Right hand side of the linear system. Has shape (N,) or (N,1).
34
+ x0 : ndarray
35
+ Starting guess for the solution.
36
+ rtol, atol : float, optional
37
+ Parameters for the convergence test. For convergence,
38
+ ``norm(b - A @ x) <= max(rtol*norm(b), atol)`` should be satisfied.
39
+ The default is ``rtol=1e-5``, the default for ``atol`` is ``0.0``.
40
+ maxiter : int, optional
41
+ Maximum number of iterations. Iteration will stop after maxiter
42
+ steps even if the specified tolerance has not been achieved.
43
+ M : {sparse array, ndarray, LinearOperator}, optional
44
+ Preconditioner for A. The preconditioner should approximate the
45
+ inverse of A. Effective preconditioning dramatically improves the
46
+ rate of convergence, which implies that fewer iterations are needed
47
+ to reach a given error tolerance.
48
+ callback : function, optional
49
+ User-supplied function to call after each iteration. It is called
50
+ as callback(xk), where xk is the current solution vector.
51
+ inner_m : int, optional
52
+ Number of inner GMRES iterations per each outer iteration.
53
+ outer_k : int, optional
54
+ Number of vectors to carry between inner GMRES iterations.
55
+ According to [1]_, good values are in the range of 1...3.
56
+ However, note that if you want to use the additional vectors to
57
+ accelerate solving multiple similar problems, larger values may
58
+ be beneficial.
59
+ outer_v : list of tuples, optional
60
+ List containing tuples ``(v, Av)`` of vectors and corresponding
61
+ matrix-vector products, used to augment the Krylov subspace, and
62
+ carried between inner GMRES iterations. The element ``Av`` can
63
+ be `None` if the matrix-vector product should be re-evaluated.
64
+ This parameter is modified in-place by `lgmres`, and can be used
65
+ to pass "guess" vectors in and out of the algorithm when solving
66
+ similar problems.
67
+ store_outer_Av : bool, optional
68
+ Whether LGMRES should store also A@v in addition to vectors `v`
69
+ in the `outer_v` list. Default is True.
70
+ prepend_outer_v : bool, optional
71
+ Whether to put outer_v augmentation vectors before Krylov iterates.
72
+ In standard LGMRES, prepend_outer_v=False.
73
+
74
+ Returns
75
+ -------
76
+ x : ndarray
77
+ The converged solution.
78
+ info : int
79
+ Provides convergence information:
80
+
81
+ - 0 : successful exit
82
+ - >0 : convergence to tolerance not achieved, number of iterations
83
+ - <0 : illegal input or breakdown
84
+
85
+ Notes
86
+ -----
87
+ The LGMRES algorithm [1]_ [2]_ is designed to avoid the
88
+ slowing of convergence in restarted GMRES, due to alternating
89
+ residual vectors. Typically, it often outperforms GMRES(m) of
90
+ comparable memory requirements by some measure, or at least is not
91
+ much worse.
92
+
93
+ Another advantage in this algorithm is that you can supply it with
94
+ 'guess' vectors in the `outer_v` argument that augment the Krylov
95
+ subspace. If the solution lies close to the span of these vectors,
96
+ the algorithm converges faster. This can be useful if several very
97
+ similar matrices need to be inverted one after another, such as in
98
+ Newton-Krylov iteration where the Jacobian matrix often changes
99
+ little in the nonlinear steps.
100
+
101
+ References
102
+ ----------
103
+ .. [1] A.H. Baker and E.R. Jessup and T. Manteuffel, "A Technique for
104
+ Accelerating the Convergence of Restarted GMRES", SIAM J. Matrix
105
+ Anal. Appl. 26, 962 (2005).
106
+ .. [2] A.H. Baker, "On Improving the Performance of the Linear Solver
107
+ restarted GMRES", PhD thesis, University of Colorado (2003).
108
+
109
+ Examples
110
+ --------
111
+ >>> import numpy as np
112
+ >>> from scipy.sparse import csc_array
113
+ >>> from scipy.sparse.linalg import lgmres
114
+ >>> A = csc_array([[3, 2, 0], [1, -1, 0], [0, 5, 1]], dtype=float)
115
+ >>> b = np.array([2, 4, -1], dtype=float)
116
+ >>> x, exitCode = lgmres(A, b, atol=1e-5)
117
+ >>> print(exitCode) # 0 indicates successful convergence
118
+ 0
119
+ >>> np.allclose(A.dot(x), b)
120
+ True
121
+ """
122
+ A,M,x,b,postprocess = make_system(A,M,x0,b)
123
+
124
+ if not np.isfinite(b).all():
125
+ raise ValueError("RHS must contain only finite numbers")
126
+
127
+ matvec = A.matvec
128
+ psolve = M.matvec
129
+
130
+ if outer_v is None:
131
+ outer_v = []
132
+
133
+ axpy, dot, scal = None, None, None
134
+ nrm2 = get_blas_funcs('nrm2', [b])
135
+
136
+ b_norm = nrm2(b)
137
+
138
+ # we call this to get the right atol/rtol and raise errors as necessary
139
+ atol, rtol = _get_atol_rtol('lgmres', b_norm, atol, rtol)
140
+
141
+ if b_norm == 0:
142
+ x = b
143
+ return (postprocess(x), 0)
144
+
145
+ ptol_max_factor = 1.0
146
+
147
+ for k_outer in range(maxiter):
148
+ r_outer = matvec(x) - b
149
+
150
+ # -- callback
151
+ if callback is not None:
152
+ callback(x)
153
+
154
+ # -- determine input type routines
155
+ if axpy is None:
156
+ if np.iscomplexobj(r_outer) and not np.iscomplexobj(x):
157
+ x = x.astype(r_outer.dtype)
158
+ axpy, dot, scal, nrm2 = get_blas_funcs(['axpy', 'dot', 'scal', 'nrm2'],
159
+ (x, r_outer))
160
+
161
+ # -- check stopping condition
162
+ r_norm = nrm2(r_outer)
163
+ if r_norm <= max(atol, rtol * b_norm):
164
+ break
165
+
166
+ # -- inner LGMRES iteration
167
+ v0 = -psolve(r_outer)
168
+ inner_res_0 = nrm2(v0)
169
+
170
+ if inner_res_0 == 0:
171
+ rnorm = nrm2(r_outer)
172
+ raise RuntimeError("Preconditioner returned a zero vector; "
173
+ f"|v| ~ {rnorm:.1g}, |M v| = 0")
174
+
175
+ v0 = scal(1.0/inner_res_0, v0)
176
+
177
+ ptol = min(ptol_max_factor, max(atol, rtol*b_norm)/r_norm)
178
+
179
+ try:
180
+ Q, R, B, vs, zs, y, pres = _fgmres(matvec,
181
+ v0,
182
+ inner_m,
183
+ lpsolve=psolve,
184
+ atol=ptol,
185
+ outer_v=outer_v,
186
+ prepend_outer_v=prepend_outer_v)
187
+ y *= inner_res_0
188
+ if not np.isfinite(y).all():
189
+ # Overflow etc. in computation. There's no way to
190
+ # recover from this, so we have to bail out.
191
+ raise LinAlgError()
192
+ except LinAlgError:
193
+ # Floating point over/underflow, non-finite result from
194
+ # matmul etc. -- report failure.
195
+ return postprocess(x), k_outer + 1
196
+
197
+ # Inner loop tolerance control
198
+ if pres > ptol:
199
+ ptol_max_factor = min(1.0, 1.5 * ptol_max_factor)
200
+ else:
201
+ ptol_max_factor = max(1e-16, 0.25 * ptol_max_factor)
202
+
203
+ # -- GMRES terminated: eval solution
204
+ dx = zs[0]*y[0]
205
+ for w, yc in zip(zs[1:], y[1:]):
206
+ dx = axpy(w, dx, dx.shape[0], yc) # dx += w*yc
207
+
208
+ # -- Store LGMRES augmentation vectors
209
+ nx = nrm2(dx)
210
+ if nx > 0:
211
+ if store_outer_Av:
212
+ q = Q.dot(R.dot(y))
213
+ ax = vs[0]*q[0]
214
+ for v, qc in zip(vs[1:], q[1:]):
215
+ ax = axpy(v, ax, ax.shape[0], qc)
216
+ outer_v.append((dx/nx, ax/nx))
217
+ else:
218
+ outer_v.append((dx/nx, None))
219
+
220
+ # -- Retain only a finite number of augmentation vectors
221
+ while len(outer_v) > outer_k:
222
+ del outer_v[0]
223
+
224
+ # -- Apply step
225
+ x += dx
226
+ else:
227
+ # didn't converge ...
228
+ return postprocess(x), maxiter
229
+
230
+ return postprocess(x), 0
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/lsmr.py ADDED
@@ -0,0 +1,486 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copyright (C) 2010 David Fong and Michael Saunders
3
+
4
+ LSMR uses an iterative method.
5
+
6
+ 07 Jun 2010: Documentation updated
7
+ 03 Jun 2010: First release version in Python
8
+
9
+ David Chin-lung Fong clfong@stanford.edu
10
+ Institute for Computational and Mathematical Engineering
11
+ Stanford University
12
+
13
+ Michael Saunders saunders@stanford.edu
14
+ Systems Optimization Laboratory
15
+ Dept of MS&E, Stanford University.
16
+
17
+ """
18
+
19
+ __all__ = ['lsmr']
20
+
21
+ from numpy import zeros, inf, atleast_1d, result_type
22
+ from numpy.linalg import norm
23
+ from math import sqrt
24
+ from scipy.sparse.linalg._interface import aslinearoperator
25
+
26
+ from scipy.sparse.linalg._isolve.lsqr import _sym_ortho
27
+
28
+
29
+ def lsmr(A, b, damp=0.0, atol=1e-6, btol=1e-6, conlim=1e8,
30
+ maxiter=None, show=False, x0=None):
31
+ """Iterative solver for least-squares problems.
32
+
33
+ lsmr solves the system of linear equations ``Ax = b``. If the system
34
+ is inconsistent, it solves the least-squares problem ``min ||b - Ax||_2``.
35
+ ``A`` is a rectangular matrix of dimension m-by-n, where all cases are
36
+ allowed: m = n, m > n, or m < n. ``b`` is a vector of length m.
37
+ The matrix A may be dense or sparse (usually sparse).
38
+
39
+ Parameters
40
+ ----------
41
+ A : {sparse array, ndarray, LinearOperator}
42
+ Matrix A in the linear system.
43
+ Alternatively, ``A`` can be a linear operator which can
44
+ produce ``Ax`` and ``A^H x`` using, e.g.,
45
+ ``scipy.sparse.linalg.LinearOperator``.
46
+ b : array_like, shape (m,)
47
+ Vector ``b`` in the linear system.
48
+ damp : float
49
+ Damping factor for regularized least-squares. `lsmr` solves
50
+ the regularized least-squares problem::
51
+
52
+ min ||(b) - ( A )x||
53
+ ||(0) (damp*I) ||_2
54
+
55
+ where damp is a scalar. If damp is None or 0, the system
56
+ is solved without regularization. Default is 0.
57
+ atol, btol : float, optional
58
+ Stopping tolerances. `lsmr` continues iterations until a
59
+ certain backward error estimate is smaller than some quantity
60
+ depending on atol and btol. Let ``r = b - Ax`` be the
61
+ residual vector for the current approximate solution ``x``.
62
+ If ``Ax = b`` seems to be consistent, `lsmr` terminates
63
+ when ``norm(r) <= atol * norm(A) * norm(x) + btol * norm(b)``.
64
+ Otherwise, `lsmr` terminates when ``norm(A^H r) <=
65
+ atol * norm(A) * norm(r)``. If both tolerances are 1.0e-6 (default),
66
+ the final ``norm(r)`` should be accurate to about 6
67
+ digits. (The final ``x`` will usually have fewer correct digits,
68
+ depending on ``cond(A)`` and the size of LAMBDA.) If `atol`
69
+ or `btol` is None, a default value of 1.0e-6 will be used.
70
+ Ideally, they should be estimates of the relative error in the
71
+ entries of ``A`` and ``b`` respectively. For example, if the entries
72
+ of ``A`` have 7 correct digits, set ``atol = 1e-7``. This prevents
73
+ the algorithm from doing unnecessary work beyond the
74
+ uncertainty of the input data.
75
+ conlim : float, optional
76
+ `lsmr` terminates if an estimate of ``cond(A)`` exceeds
77
+ `conlim`. For compatible systems ``Ax = b``, conlim could be
78
+ as large as 1.0e+12 (say). For least-squares problems,
79
+ `conlim` should be less than 1.0e+8. If `conlim` is None, the
80
+ default value is 1e+8. Maximum precision can be obtained by
81
+ setting ``atol = btol = conlim = 0``, but the number of
82
+ iterations may then be excessive. Default is 1e8.
83
+ maxiter : int, optional
84
+ `lsmr` terminates if the number of iterations reaches
85
+ `maxiter`. The default is ``maxiter = min(m, n)``. For
86
+ ill-conditioned systems, a larger value of `maxiter` may be
87
+ needed. Default is False.
88
+ show : bool, optional
89
+ Print iterations logs if ``show=True``. Default is False.
90
+ x0 : array_like, shape (n,), optional
91
+ Initial guess of ``x``, if None zeros are used. Default is None.
92
+
93
+ .. versionadded:: 1.0.0
94
+
95
+ Returns
96
+ -------
97
+ x : ndarray of float
98
+ Least-square solution returned.
99
+ istop : int
100
+ istop gives the reason for stopping::
101
+
102
+ istop = 0 means x=0 is a solution. If x0 was given, then x=x0 is a
103
+ solution.
104
+ = 1 means x is an approximate solution to A@x = B,
105
+ according to atol and btol.
106
+ = 2 means x approximately solves the least-squares problem
107
+ according to atol.
108
+ = 3 means COND(A) seems to be greater than CONLIM.
109
+ = 4 is the same as 1 with atol = btol = eps (machine
110
+ precision)
111
+ = 5 is the same as 2 with atol = eps.
112
+ = 6 is the same as 3 with CONLIM = 1/eps.
113
+ = 7 means ITN reached maxiter before the other stopping
114
+ conditions were satisfied.
115
+
116
+ itn : int
117
+ Number of iterations used.
118
+ normr : float
119
+ ``norm(b-Ax)``
120
+ normar : float
121
+ ``norm(A^H (b - Ax))``
122
+ norma : float
123
+ ``norm(A)``
124
+ conda : float
125
+ Condition number of A.
126
+ normx : float
127
+ ``norm(x)``
128
+
129
+ Notes
130
+ -----
131
+
132
+ .. versionadded:: 0.11.0
133
+
134
+ References
135
+ ----------
136
+ .. [1] D. C.-L. Fong and M. A. Saunders,
137
+ "LSMR: An iterative algorithm for sparse least-squares problems",
138
+ SIAM J. Sci. Comput., vol. 33, pp. 2950-2971, 2011.
139
+ :arxiv:`1006.0758`
140
+ .. [2] LSMR Software, https://web.stanford.edu/group/SOL/software/lsmr/
141
+
142
+ Examples
143
+ --------
144
+ >>> import numpy as np
145
+ >>> from scipy.sparse import csc_array
146
+ >>> from scipy.sparse.linalg import lsmr
147
+ >>> A = csc_array([[1., 0.], [1., 1.], [0., 1.]], dtype=float)
148
+
149
+ The first example has the trivial solution ``[0, 0]``
150
+
151
+ >>> b = np.array([0., 0., 0.], dtype=float)
152
+ >>> x, istop, itn, normr = lsmr(A, b)[:4]
153
+ >>> istop
154
+ 0
155
+ >>> x
156
+ array([0., 0.])
157
+
158
+ The stopping code ``istop=0`` returned indicates that a vector of zeros was
159
+ found as a solution. The returned solution `x` indeed contains
160
+ ``[0., 0.]``. The next example has a non-trivial solution:
161
+
162
+ >>> b = np.array([1., 0., -1.], dtype=float)
163
+ >>> x, istop, itn, normr = lsmr(A, b)[:4]
164
+ >>> istop
165
+ 1
166
+ >>> x
167
+ array([ 1., -1.])
168
+ >>> itn
169
+ 1
170
+ >>> normr
171
+ 4.440892098500627e-16
172
+
173
+ As indicated by ``istop=1``, `lsmr` found a solution obeying the tolerance
174
+ limits. The given solution ``[1., -1.]`` obviously solves the equation. The
175
+ remaining return values include information about the number of iterations
176
+ (`itn=1`) and the remaining difference of left and right side of the solved
177
+ equation.
178
+ The final example demonstrates the behavior in the case where there is no
179
+ solution for the equation:
180
+
181
+ >>> b = np.array([1., 0.01, -1.], dtype=float)
182
+ >>> x, istop, itn, normr = lsmr(A, b)[:4]
183
+ >>> istop
184
+ 2
185
+ >>> x
186
+ array([ 1.00333333, -0.99666667])
187
+ >>> A.dot(x)-b
188
+ array([ 0.00333333, -0.00333333, 0.00333333])
189
+ >>> normr
190
+ 0.005773502691896255
191
+
192
+ `istop` indicates that the system is inconsistent and thus `x` is rather an
193
+ approximate solution to the corresponding least-squares problem. `normr`
194
+ contains the minimal distance that was found.
195
+ """
196
+
197
+ A = aslinearoperator(A)
198
+ b = atleast_1d(b)
199
+ if b.ndim > 1:
200
+ b = b.squeeze()
201
+
202
+ msg = ('The exact solution is x = 0, or x = x0, if x0 was given ',
203
+ 'Ax - b is small enough, given atol, btol ',
204
+ 'The least-squares solution is good enough, given atol ',
205
+ 'The estimate of cond(Abar) has exceeded conlim ',
206
+ 'Ax - b is small enough for this machine ',
207
+ 'The least-squares solution is good enough for this machine',
208
+ 'Cond(Abar) seems to be too large for this machine ',
209
+ 'The iteration limit has been reached ')
210
+
211
+ hdg1 = ' itn x(1) norm r norm Ar'
212
+ hdg2 = ' compatible LS norm A cond A'
213
+ pfreq = 20 # print frequency (for repeating the heading)
214
+ pcount = 0 # print counter
215
+
216
+ m, n = A.shape
217
+
218
+ # stores the num of singular values
219
+ minDim = min([m, n])
220
+
221
+ if maxiter is None:
222
+ maxiter = minDim
223
+
224
+ if x0 is None:
225
+ dtype = result_type(A, b, float)
226
+ else:
227
+ dtype = result_type(A, b, x0, float)
228
+
229
+ if show:
230
+ print(' ')
231
+ print('LSMR Least-squares solution of Ax = b\n')
232
+ print(f'The matrix A has {m} rows and {n} columns')
233
+ print(f'damp = {damp:20.14e}\n')
234
+ print(f'atol = {atol:8.2e} conlim = {conlim:8.2e}\n')
235
+ print(f'btol = {btol:8.2e} maxiter = {maxiter:8g}\n')
236
+
237
+ u = b
238
+ normb = norm(b)
239
+ if x0 is None:
240
+ x = zeros(n, dtype)
241
+ beta = normb.copy()
242
+ else:
243
+ x = atleast_1d(x0.copy())
244
+ u = u - A.matvec(x)
245
+ beta = norm(u)
246
+
247
+ if beta > 0:
248
+ u = (1 / beta) * u
249
+ v = A.rmatvec(u)
250
+ alpha = norm(v)
251
+ else:
252
+ v = zeros(n, dtype)
253
+ alpha = 0
254
+
255
+ if alpha > 0:
256
+ v = (1 / alpha) * v
257
+
258
+ # Initialize variables for 1st iteration.
259
+
260
+ itn = 0
261
+ zetabar = alpha * beta
262
+ alphabar = alpha
263
+ rho = 1
264
+ rhobar = 1
265
+ cbar = 1
266
+ sbar = 0
267
+
268
+ h = v.copy()
269
+ hbar = zeros(n, dtype)
270
+
271
+ # Initialize variables for estimation of ||r||.
272
+
273
+ betadd = beta
274
+ betad = 0
275
+ rhodold = 1
276
+ tautildeold = 0
277
+ thetatilde = 0
278
+ zeta = 0
279
+ d = 0
280
+
281
+ # Initialize variables for estimation of ||A|| and cond(A)
282
+
283
+ normA2 = alpha * alpha
284
+ maxrbar = 0
285
+ minrbar = 1e+100
286
+ normA = sqrt(normA2)
287
+ condA = 1
288
+ normx = 0
289
+
290
+ # Items for use in stopping rules, normb set earlier
291
+ istop = 0
292
+ ctol = 0
293
+ if conlim > 0:
294
+ ctol = 1 / conlim
295
+ normr = beta
296
+
297
+ # Reverse the order here from the original matlab code because
298
+ # there was an error on return when arnorm==0
299
+ normar = alpha * beta
300
+ if normar == 0:
301
+ if show:
302
+ print(msg[0])
303
+ return x, istop, itn, normr, normar, normA, condA, normx
304
+
305
+ if normb == 0:
306
+ x[()] = 0
307
+ return x, istop, itn, normr, normar, normA, condA, normx
308
+
309
+ if show:
310
+ print(' ')
311
+ print(hdg1, hdg2)
312
+ test1 = 1
313
+ test2 = alpha / beta
314
+ str1 = f'{itn:6g} {x[0]:12.5e}'
315
+ str2 = f' {normr:10.3e} {normar:10.3e}'
316
+ str3 = f' {test1:8.1e} {test2:8.1e}'
317
+ print(''.join([str1, str2, str3]))
318
+
319
+ # Main iteration loop.
320
+ while itn < maxiter:
321
+ itn = itn + 1
322
+
323
+ # Perform the next step of the bidiagonalization to obtain the
324
+ # next beta, u, alpha, v. These satisfy the relations
325
+ # beta*u = A@v - alpha*u,
326
+ # alpha*v = A'@u - beta*v.
327
+
328
+ u *= -alpha
329
+ u += A.matvec(v)
330
+ beta = norm(u)
331
+
332
+ if beta > 0:
333
+ u *= (1 / beta)
334
+ v *= -beta
335
+ v += A.rmatvec(u)
336
+ alpha = norm(v)
337
+ if alpha > 0:
338
+ v *= (1 / alpha)
339
+
340
+ # At this point, beta = beta_{k+1}, alpha = alpha_{k+1}.
341
+
342
+ # Construct rotation Qhat_{k,2k+1}.
343
+
344
+ chat, shat, alphahat = _sym_ortho(alphabar, damp)
345
+
346
+ # Use a plane rotation (Q_i) to turn B_i to R_i
347
+
348
+ rhoold = rho
349
+ c, s, rho = _sym_ortho(alphahat, beta)
350
+ thetanew = s*alpha
351
+ alphabar = c*alpha
352
+
353
+ # Use a plane rotation (Qbar_i) to turn R_i^T to R_i^bar
354
+
355
+ rhobarold = rhobar
356
+ zetaold = zeta
357
+ thetabar = sbar * rho
358
+ rhotemp = cbar * rho
359
+ cbar, sbar, rhobar = _sym_ortho(cbar * rho, thetanew)
360
+ zeta = cbar * zetabar
361
+ zetabar = - sbar * zetabar
362
+
363
+ # Update h, h_hat, x.
364
+
365
+ hbar *= - (thetabar * rho / (rhoold * rhobarold))
366
+ hbar += h
367
+ x += (zeta / (rho * rhobar)) * hbar
368
+ h *= - (thetanew / rho)
369
+ h += v
370
+
371
+ # Estimate of ||r||.
372
+
373
+ # Apply rotation Qhat_{k,2k+1}.
374
+ betaacute = chat * betadd
375
+ betacheck = -shat * betadd
376
+
377
+ # Apply rotation Q_{k,k+1}.
378
+ betahat = c * betaacute
379
+ betadd = -s * betaacute
380
+
381
+ # Apply rotation Qtilde_{k-1}.
382
+ # betad = betad_{k-1} here.
383
+
384
+ thetatildeold = thetatilde
385
+ ctildeold, stildeold, rhotildeold = _sym_ortho(rhodold, thetabar)
386
+ thetatilde = stildeold * rhobar
387
+ rhodold = ctildeold * rhobar
388
+ betad = - stildeold * betad + ctildeold * betahat
389
+
390
+ # betad = betad_k here.
391
+ # rhodold = rhod_k here.
392
+
393
+ tautildeold = (zetaold - thetatildeold * tautildeold) / rhotildeold
394
+ taud = (zeta - thetatilde * tautildeold) / rhodold
395
+ d = d + betacheck * betacheck
396
+ normr = sqrt(d + (betad - taud)**2 + betadd * betadd)
397
+
398
+ # Estimate ||A||.
399
+ normA2 = normA2 + beta * beta
400
+ normA = sqrt(normA2)
401
+ normA2 = normA2 + alpha * alpha
402
+
403
+ # Estimate cond(A).
404
+ maxrbar = max(maxrbar, rhobarold)
405
+ if itn > 1:
406
+ minrbar = min(minrbar, rhobarold)
407
+ condA = max(maxrbar, rhotemp) / min(minrbar, rhotemp)
408
+
409
+ # Test for convergence.
410
+
411
+ # Compute norms for convergence testing.
412
+ normar = abs(zetabar)
413
+ normx = norm(x)
414
+
415
+ # Now use these norms to estimate certain other quantities,
416
+ # some of which will be small near a solution.
417
+
418
+ test1 = normr / normb
419
+ if (normA * normr) != 0:
420
+ test2 = normar / (normA * normr)
421
+ else:
422
+ test2 = inf
423
+ test3 = 1 / condA
424
+ t1 = test1 / (1 + normA * normx / normb)
425
+ rtol = btol + atol * normA * normx / normb
426
+
427
+ # The following tests guard against extremely small values of
428
+ # atol, btol or ctol. (The user may have set any or all of
429
+ # the parameters atol, btol, conlim to 0.)
430
+ # The effect is equivalent to the normAl tests using
431
+ # atol = eps, btol = eps, conlim = 1/eps.
432
+
433
+ if itn >= maxiter:
434
+ istop = 7
435
+ if 1 + test3 <= 1:
436
+ istop = 6
437
+ if 1 + test2 <= 1:
438
+ istop = 5
439
+ if 1 + t1 <= 1:
440
+ istop = 4
441
+
442
+ # Allow for tolerances set by the user.
443
+
444
+ if test3 <= ctol:
445
+ istop = 3
446
+ if test2 <= atol:
447
+ istop = 2
448
+ if test1 <= rtol:
449
+ istop = 1
450
+
451
+ # See if it is time to print something.
452
+
453
+ if show:
454
+ if (n <= 40) or (itn <= 10) or (itn >= maxiter - 10) or \
455
+ (itn % 10 == 0) or (test3 <= 1.1 * ctol) or \
456
+ (test2 <= 1.1 * atol) or (test1 <= 1.1 * rtol) or \
457
+ (istop != 0):
458
+
459
+ if pcount >= pfreq:
460
+ pcount = 0
461
+ print(' ')
462
+ print(hdg1, hdg2)
463
+ pcount = pcount + 1
464
+ str1 = f'{itn:6g} {x[0]:12.5e}'
465
+ str2 = f' {normr:10.3e} {normar:10.3e}'
466
+ str3 = f' {test1:8.1e} {test2:8.1e}'
467
+ str4 = f' {normA:8.1e} {condA:8.1e}'
468
+ print(''.join([str1, str2, str3, str4]))
469
+
470
+ if istop > 0:
471
+ break
472
+
473
+ # Print the stopping condition.
474
+
475
+ if show:
476
+ print(' ')
477
+ print('LSMR finished')
478
+ print(msg[istop])
479
+ print(f'istop ={istop:8g} normr ={normr:8.1e}')
480
+ print(f' normA ={normA:8.1e} normAr ={normar:8.1e}')
481
+ print(f'itn ={itn:8g} condA ={condA:8.1e}')
482
+ print(f' normx ={normx:8.1e}')
483
+ print(str1, str2)
484
+ print(str3, str4)
485
+
486
+ return x, istop, itn, normr, normar, normA, condA, normx
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/lsqr.py ADDED
@@ -0,0 +1,589 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Sparse Equations and Least Squares.
2
+
3
+ The original Fortran code was written by C. C. Paige and M. A. Saunders as
4
+ described in
5
+
6
+ C. C. Paige and M. A. Saunders, LSQR: An algorithm for sparse linear
7
+ equations and sparse least squares, TOMS 8(1), 43--71 (1982).
8
+
9
+ C. C. Paige and M. A. Saunders, Algorithm 583; LSQR: Sparse linear
10
+ equations and least-squares problems, TOMS 8(2), 195--209 (1982).
11
+
12
+ It is licensed under the following BSD license:
13
+
14
+ Copyright (c) 2006, Systems Optimization Laboratory
15
+ All rights reserved.
16
+
17
+ Redistribution and use in source and binary forms, with or without
18
+ modification, are permitted provided that the following conditions are
19
+ met:
20
+
21
+ * Redistributions of source code must retain the above copyright
22
+ notice, this list of conditions and the following disclaimer.
23
+
24
+ * Redistributions in binary form must reproduce the above
25
+ copyright notice, this list of conditions and the following
26
+ disclaimer in the documentation and/or other materials provided
27
+ with the distribution.
28
+
29
+ * Neither the name of Stanford University nor the names of its
30
+ contributors may be used to endorse or promote products derived
31
+ from this software without specific prior written permission.
32
+
33
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
34
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
35
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
36
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
37
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
38
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
39
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
40
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
41
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
42
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
43
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44
+
45
+ The Fortran code was translated to Python for use in CVXOPT by Jeffery
46
+ Kline with contributions by Mridul Aanjaneya and Bob Myhill.
47
+
48
+ Adapted for SciPy by Stefan van der Walt.
49
+
50
+ """
51
+
52
+ __all__ = ['lsqr']
53
+
54
+ import numpy as np
55
+ from math import sqrt
56
+ from scipy.sparse.linalg._interface import aslinearoperator
57
+ from scipy.sparse._sputils import convert_pydata_sparse_to_scipy
58
+
59
+ eps = np.finfo(np.float64).eps
60
+
61
+
62
+ def _sym_ortho(a, b):
63
+ """
64
+ Stable implementation of Givens rotation.
65
+
66
+ Notes
67
+ -----
68
+ The routine 'SymOrtho' was added for numerical stability. This is
69
+ recommended by S.-C. Choi in [1]_. It removes the unpleasant potential of
70
+ ``1/eps`` in some important places (see, for example text following
71
+ "Compute the next plane rotation Qk" in minres.py).
72
+
73
+ References
74
+ ----------
75
+ .. [1] S.-C. Choi, "Iterative Methods for Singular Linear Equations
76
+ and Least-Squares Problems", Dissertation,
77
+ http://www.stanford.edu/group/SOL/dissertations/sou-cheng-choi-thesis.pdf
78
+
79
+ """
80
+ if b == 0:
81
+ return np.sign(a), 0, abs(a)
82
+ elif a == 0:
83
+ return 0, np.sign(b), abs(b)
84
+ elif abs(b) > abs(a):
85
+ tau = a / b
86
+ s = np.sign(b) / sqrt(1 + tau * tau)
87
+ c = s * tau
88
+ r = b / s
89
+ else:
90
+ tau = b / a
91
+ c = np.sign(a) / sqrt(1+tau*tau)
92
+ s = c * tau
93
+ r = a / c
94
+ return c, s, r
95
+
96
+
97
+ def lsqr(A, b, damp=0.0, atol=1e-6, btol=1e-6, conlim=1e8,
98
+ iter_lim=None, show=False, calc_var=False, x0=None):
99
+ """Find the least-squares solution to a large, sparse, linear system
100
+ of equations.
101
+
102
+ The function solves ``Ax = b`` or ``min ||Ax - b||^2`` or
103
+ ``min ||Ax - b||^2 + d^2 ||x - x0||^2``.
104
+
105
+ The matrix A may be square or rectangular (over-determined or
106
+ under-determined), and may have any rank.
107
+
108
+ ::
109
+
110
+ 1. Unsymmetric equations -- solve Ax = b
111
+
112
+ 2. Linear least squares -- solve Ax = b
113
+ in the least-squares sense
114
+
115
+ 3. Damped least squares -- solve ( A )*x = ( b )
116
+ ( damp*I ) ( damp*x0 )
117
+ in the least-squares sense
118
+
119
+ Parameters
120
+ ----------
121
+ A : {sparse array, ndarray, LinearOperator}
122
+ Representation of an m-by-n matrix.
123
+ Alternatively, ``A`` can be a linear operator which can
124
+ produce ``Ax`` and ``A^T x`` using, e.g.,
125
+ ``scipy.sparse.linalg.LinearOperator``.
126
+ b : array_like, shape (m,)
127
+ Right-hand side vector ``b``.
128
+ damp : float
129
+ Damping coefficient. Default is 0.
130
+ atol, btol : float, optional
131
+ Stopping tolerances. `lsqr` continues iterations until a
132
+ certain backward error estimate is smaller than some quantity
133
+ depending on atol and btol. Let ``r = b - Ax`` be the
134
+ residual vector for the current approximate solution ``x``.
135
+ If ``Ax = b`` seems to be consistent, `lsqr` terminates
136
+ when ``norm(r) <= atol * norm(A) * norm(x) + btol * norm(b)``.
137
+ Otherwise, `lsqr` terminates when ``norm(A^H r) <=
138
+ atol * norm(A) * norm(r)``. If both tolerances are 1.0e-6 (default),
139
+ the final ``norm(r)`` should be accurate to about 6
140
+ digits. (The final ``x`` will usually have fewer correct digits,
141
+ depending on ``cond(A)`` and the size of LAMBDA.) If `atol`
142
+ or `btol` is None, a default value of 1.0e-6 will be used.
143
+ Ideally, they should be estimates of the relative error in the
144
+ entries of ``A`` and ``b`` respectively. For example, if the entries
145
+ of ``A`` have 7 correct digits, set ``atol = 1e-7``. This prevents
146
+ the algorithm from doing unnecessary work beyond the
147
+ uncertainty of the input data.
148
+ conlim : float, optional
149
+ Another stopping tolerance. lsqr terminates if an estimate of
150
+ ``cond(A)`` exceeds `conlim`. For compatible systems ``Ax =
151
+ b``, `conlim` could be as large as 1.0e+12 (say). For
152
+ least-squares problems, conlim should be less than 1.0e+8.
153
+ Maximum precision can be obtained by setting ``atol = btol =
154
+ conlim = zero``, but the number of iterations may then be
155
+ excessive. Default is 1e8.
156
+ iter_lim : int, optional
157
+ Explicit limitation on number of iterations (for safety).
158
+ show : bool, optional
159
+ Display an iteration log. Default is False.
160
+ calc_var : bool, optional
161
+ Whether to estimate diagonals of ``(A'A + damp^2*I)^{-1}``.
162
+ x0 : array_like, shape (n,), optional
163
+ Initial guess of x, if None zeros are used. Default is None.
164
+
165
+ .. versionadded:: 1.0.0
166
+
167
+ Returns
168
+ -------
169
+ x : ndarray of float
170
+ The final solution.
171
+ istop : int
172
+ Gives the reason for termination.
173
+ 1 means x is an approximate solution to Ax = b.
174
+ 2 means x approximately solves the least-squares problem.
175
+ itn : int
176
+ Iteration number upon termination.
177
+ r1norm : float
178
+ ``norm(r)``, where ``r = b - Ax``.
179
+ r2norm : float
180
+ ``sqrt( norm(r)^2 + damp^2 * norm(x - x0)^2 )``. Equal to `r1norm`
181
+ if ``damp == 0``.
182
+ anorm : float
183
+ Estimate of Frobenius norm of ``Abar = [[A]; [damp*I]]``.
184
+ acond : float
185
+ Estimate of ``cond(Abar)``.
186
+ arnorm : float
187
+ Estimate of ``norm(A'@r - damp^2*(x - x0))``.
188
+ xnorm : float
189
+ ``norm(x)``
190
+ var : ndarray of float
191
+ If ``calc_var`` is True, estimates all diagonals of
192
+ ``(A'A)^{-1}`` (if ``damp == 0``) or more generally ``(A'A +
193
+ damp^2*I)^{-1}``. This is well defined if A has full column
194
+ rank or ``damp > 0``. (Not sure what var means if ``rank(A)
195
+ < n`` and ``damp = 0.``)
196
+
197
+ Notes
198
+ -----
199
+ LSQR uses an iterative method to approximate the solution. The
200
+ number of iterations required to reach a certain accuracy depends
201
+ strongly on the scaling of the problem. Poor scaling of the rows
202
+ or columns of A should therefore be avoided where possible.
203
+
204
+ For example, in problem 1 the solution is unaltered by
205
+ row-scaling. If a row of A is very small or large compared to
206
+ the other rows of A, the corresponding row of ( A b ) should be
207
+ scaled up or down.
208
+
209
+ In problems 1 and 2, the solution x is easily recovered
210
+ following column-scaling. Unless better information is known,
211
+ the nonzero columns of A should be scaled so that they all have
212
+ the same Euclidean norm (e.g., 1.0).
213
+
214
+ In problem 3, there is no freedom to re-scale if damp is
215
+ nonzero. However, the value of damp should be assigned only
216
+ after attention has been paid to the scaling of A.
217
+
218
+ The parameter damp is intended to help regularize
219
+ ill-conditioned systems, by preventing the true solution from
220
+ being very large. Another aid to regularization is provided by
221
+ the parameter acond, which may be used to terminate iterations
222
+ before the computed solution becomes very large.
223
+
224
+ If some initial estimate ``x0`` is known and if ``damp == 0``,
225
+ one could proceed as follows:
226
+
227
+ 1. Compute a residual vector ``r0 = b - A@x0``.
228
+ 2. Use LSQR to solve the system ``A@dx = r0``.
229
+ 3. Add the correction dx to obtain a final solution ``x = x0 + dx``.
230
+
231
+ This requires that ``x0`` be available before and after the call
232
+ to LSQR. To judge the benefits, suppose LSQR takes k1 iterations
233
+ to solve A@x = b and k2 iterations to solve A@dx = r0.
234
+ If x0 is "good", norm(r0) will be smaller than norm(b).
235
+ If the same stopping tolerances atol and btol are used for each
236
+ system, k1 and k2 will be similar, but the final solution x0 + dx
237
+ should be more accurate. The only way to reduce the total work
238
+ is to use a larger stopping tolerance for the second system.
239
+ If some value btol is suitable for A@x = b, the larger value
240
+ btol*norm(b)/norm(r0) should be suitable for A@dx = r0.
241
+
242
+ Preconditioning is another way to reduce the number of iterations.
243
+ If it is possible to solve a related system ``M@x = b``
244
+ efficiently, where M approximates A in some helpful way (e.g. M -
245
+ A has low rank or its elements are small relative to those of A),
246
+ LSQR may converge more rapidly on the system ``A@M(inverse)@z =
247
+ b``, after which x can be recovered by solving M@x = z.
248
+
249
+ If A is symmetric, LSQR should not be used!
250
+
251
+ Alternatives are the symmetric conjugate-gradient method (cg)
252
+ and/or SYMMLQ. SYMMLQ is an implementation of symmetric cg that
253
+ applies to any symmetric A and will converge more rapidly than
254
+ LSQR. If A is positive definite, there are other implementations
255
+ of symmetric cg that require slightly less work per iteration than
256
+ SYMMLQ (but will take the same number of iterations).
257
+
258
+ References
259
+ ----------
260
+ .. [1] C. C. Paige and M. A. Saunders (1982a).
261
+ "LSQR: An algorithm for sparse linear equations and
262
+ sparse least squares", ACM TOMS 8(1), 43-71.
263
+ .. [2] C. C. Paige and M. A. Saunders (1982b).
264
+ "Algorithm 583. LSQR: Sparse linear equations and least
265
+ squares problems", ACM TOMS 8(2), 195-209.
266
+ .. [3] M. A. Saunders (1995). "Solution of sparse rectangular
267
+ systems using LSQR and CRAIG", BIT 35, 588-604.
268
+
269
+ Examples
270
+ --------
271
+ >>> import numpy as np
272
+ >>> from scipy.sparse import csc_array
273
+ >>> from scipy.sparse.linalg import lsqr
274
+ >>> A = csc_array([[1., 0.], [1., 1.], [0., 1.]], dtype=float)
275
+
276
+ The first example has the trivial solution ``[0, 0]``
277
+
278
+ >>> b = np.array([0., 0., 0.], dtype=float)
279
+ >>> x, istop, itn, normr = lsqr(A, b)[:4]
280
+ >>> istop
281
+ 0
282
+ >>> x
283
+ array([ 0., 0.])
284
+
285
+ The stopping code ``istop=0`` returned indicates that a vector of zeros was
286
+ found as a solution. The returned solution `x` indeed contains
287
+ ``[0., 0.]``. The next example has a non-trivial solution:
288
+
289
+ >>> b = np.array([1., 0., -1.], dtype=float)
290
+ >>> x, istop, itn, r1norm = lsqr(A, b)[:4]
291
+ >>> istop
292
+ 1
293
+ >>> x
294
+ array([ 1., -1.])
295
+ >>> itn
296
+ 1
297
+ >>> r1norm
298
+ 4.440892098500627e-16
299
+
300
+ As indicated by ``istop=1``, `lsqr` found a solution obeying the tolerance
301
+ limits. The given solution ``[1., -1.]`` obviously solves the equation. The
302
+ remaining return values include information about the number of iterations
303
+ (`itn=1`) and the remaining difference of left and right side of the solved
304
+ equation.
305
+ The final example demonstrates the behavior in the case where there is no
306
+ solution for the equation:
307
+
308
+ >>> b = np.array([1., 0.01, -1.], dtype=float)
309
+ >>> x, istop, itn, r1norm = lsqr(A, b)[:4]
310
+ >>> istop
311
+ 2
312
+ >>> x
313
+ array([ 1.00333333, -0.99666667])
314
+ >>> A.dot(x)-b
315
+ array([ 0.00333333, -0.00333333, 0.00333333])
316
+ >>> r1norm
317
+ 0.005773502691896255
318
+
319
+ `istop` indicates that the system is inconsistent and thus `x` is rather an
320
+ approximate solution to the corresponding least-squares problem. `r1norm`
321
+ contains the norm of the minimal residual that was found.
322
+ """
323
+ A = convert_pydata_sparse_to_scipy(A)
324
+ A = aslinearoperator(A)
325
+ b = np.atleast_1d(b)
326
+ if b.ndim > 1:
327
+ b = b.squeeze()
328
+
329
+ m, n = A.shape
330
+ if iter_lim is None:
331
+ iter_lim = 2 * n
332
+ var = np.zeros(n)
333
+
334
+ msg = ('The exact solution is x = 0 ',
335
+ 'Ax - b is small enough, given atol, btol ',
336
+ 'The least-squares solution is good enough, given atol ',
337
+ 'The estimate of cond(Abar) has exceeded conlim ',
338
+ 'Ax - b is small enough for this machine ',
339
+ 'The least-squares solution is good enough for this machine',
340
+ 'Cond(Abar) seems to be too large for this machine ',
341
+ 'The iteration limit has been reached ')
342
+
343
+ if show:
344
+ print(' ')
345
+ print('LSQR Least-squares solution of Ax = b')
346
+ str1 = f'The matrix A has {m} rows and {n} columns'
347
+ str2 = f'damp = {damp:20.14e} calc_var = {calc_var:8g}'
348
+ str3 = f'atol = {atol:8.2e} conlim = {conlim:8.2e}'
349
+ str4 = f'btol = {btol:8.2e} iter_lim = {iter_lim:8g}'
350
+ print(str1)
351
+ print(str2)
352
+ print(str3)
353
+ print(str4)
354
+
355
+ itn = 0
356
+ istop = 0
357
+ ctol = 0
358
+ if conlim > 0:
359
+ ctol = 1/conlim
360
+ anorm = 0
361
+ acond = 0
362
+ dampsq = damp**2
363
+ ddnorm = 0
364
+ res2 = 0
365
+ xnorm = 0
366
+ xxnorm = 0
367
+ z = 0
368
+ cs2 = -1
369
+ sn2 = 0
370
+
371
+ # Set up the first vectors u and v for the bidiagonalization.
372
+ # These satisfy beta*u = b - A@x, alfa*v = A'@u.
373
+ u = b
374
+ bnorm = np.linalg.norm(b)
375
+
376
+ if x0 is None:
377
+ x = np.zeros(n)
378
+ beta = bnorm.copy()
379
+ else:
380
+ x = np.asarray(x0)
381
+ u = u - A.matvec(x)
382
+ beta = np.linalg.norm(u)
383
+
384
+ if beta > 0:
385
+ u = (1/beta) * u
386
+ v = A.rmatvec(u)
387
+ alfa = np.linalg.norm(v)
388
+ else:
389
+ v = x.copy()
390
+ alfa = 0
391
+
392
+ if alfa > 0:
393
+ v = (1/alfa) * v
394
+ w = v.copy()
395
+
396
+ rhobar = alfa
397
+ phibar = beta
398
+ rnorm = beta
399
+ r1norm = rnorm
400
+ r2norm = rnorm
401
+
402
+ # Reverse the order here from the original matlab code because
403
+ # there was an error on return when arnorm==0
404
+ arnorm = alfa * beta
405
+ if arnorm == 0:
406
+ if show:
407
+ print(msg[0])
408
+ return x, istop, itn, r1norm, r2norm, anorm, acond, arnorm, xnorm, var
409
+
410
+ head1 = ' Itn x[0] r1norm r2norm '
411
+ head2 = ' Compatible LS Norm A Cond A'
412
+
413
+ if show:
414
+ print(' ')
415
+ print(head1, head2)
416
+ test1 = 1
417
+ test2 = alfa / beta
418
+ str1 = f'{itn:6g} {x[0]:12.5e}'
419
+ str2 = f' {r1norm:10.3e} {r2norm:10.3e}'
420
+ str3 = f' {test1:8.1e} {test2:8.1e}'
421
+ print(str1, str2, str3)
422
+
423
+ # Main iteration loop.
424
+ while itn < iter_lim:
425
+ itn = itn + 1
426
+ # Perform the next step of the bidiagonalization to obtain the
427
+ # next beta, u, alfa, v. These satisfy the relations
428
+ # beta*u = a@v - alfa*u,
429
+ # alfa*v = A'@u - beta*v.
430
+ u = A.matvec(v) - alfa * u
431
+ beta = np.linalg.norm(u)
432
+
433
+ if beta > 0:
434
+ u = (1/beta) * u
435
+ anorm = sqrt(anorm**2 + alfa**2 + beta**2 + dampsq)
436
+ v = A.rmatvec(u) - beta * v
437
+ alfa = np.linalg.norm(v)
438
+ if alfa > 0:
439
+ v = (1 / alfa) * v
440
+
441
+ # Use a plane rotation to eliminate the damping parameter.
442
+ # This alters the diagonal (rhobar) of the lower-bidiagonal matrix.
443
+ if damp > 0:
444
+ rhobar1 = sqrt(rhobar**2 + dampsq)
445
+ cs1 = rhobar / rhobar1
446
+ sn1 = damp / rhobar1
447
+ psi = sn1 * phibar
448
+ phibar = cs1 * phibar
449
+ else:
450
+ # cs1 = 1 and sn1 = 0
451
+ rhobar1 = rhobar
452
+ psi = 0.
453
+
454
+ # Use a plane rotation to eliminate the subdiagonal element (beta)
455
+ # of the lower-bidiagonal matrix, giving an upper-bidiagonal matrix.
456
+ cs, sn, rho = _sym_ortho(rhobar1, beta)
457
+
458
+ theta = sn * alfa
459
+ rhobar = -cs * alfa
460
+ phi = cs * phibar
461
+ phibar = sn * phibar
462
+ tau = sn * phi
463
+
464
+ # Update x and w.
465
+ t1 = phi / rho
466
+ t2 = -theta / rho
467
+ dk = (1 / rho) * w
468
+
469
+ x = x + t1 * w
470
+ w = v + t2 * w
471
+ ddnorm = ddnorm + np.linalg.norm(dk)**2
472
+
473
+ if calc_var:
474
+ var = var + dk**2
475
+
476
+ # Use a plane rotation on the right to eliminate the
477
+ # super-diagonal element (theta) of the upper-bidiagonal matrix.
478
+ # Then use the result to estimate norm(x).
479
+ delta = sn2 * rho
480
+ gambar = -cs2 * rho
481
+ rhs = phi - delta * z
482
+ zbar = rhs / gambar
483
+ xnorm = sqrt(xxnorm + zbar**2)
484
+ gamma = sqrt(gambar**2 + theta**2)
485
+ cs2 = gambar / gamma
486
+ sn2 = theta / gamma
487
+ z = rhs / gamma
488
+ xxnorm = xxnorm + z**2
489
+
490
+ # Test for convergence.
491
+ # First, estimate the condition of the matrix Abar,
492
+ # and the norms of rbar and Abar'rbar.
493
+ acond = anorm * sqrt(ddnorm)
494
+ res1 = phibar**2
495
+ res2 = res2 + psi**2
496
+ rnorm = sqrt(res1 + res2)
497
+ arnorm = alfa * abs(tau)
498
+
499
+ # Distinguish between
500
+ # r1norm = ||b - Ax|| and
501
+ # r2norm = rnorm in current code
502
+ # = sqrt(r1norm^2 + damp^2*||x - x0||^2).
503
+ # Estimate r1norm from
504
+ # r1norm = sqrt(r2norm^2 - damp^2*||x - x0||^2).
505
+ # Although there is cancellation, it might be accurate enough.
506
+ if damp > 0:
507
+ r1sq = rnorm**2 - dampsq * xxnorm
508
+ r1norm = sqrt(abs(r1sq))
509
+ if r1sq < 0:
510
+ r1norm = -r1norm
511
+ else:
512
+ r1norm = rnorm
513
+ r2norm = rnorm
514
+
515
+ # Now use these norms to estimate certain other quantities,
516
+ # some of which will be small near a solution.
517
+ test1 = rnorm / bnorm
518
+ test2 = arnorm / (anorm * rnorm + eps)
519
+ test3 = 1 / (acond + eps)
520
+ t1 = test1 / (1 + anorm * xnorm / bnorm)
521
+ rtol = btol + atol * anorm * xnorm / bnorm
522
+
523
+ # The following tests guard against extremely small values of
524
+ # atol, btol or ctol. (The user may have set any or all of
525
+ # the parameters atol, btol, conlim to 0.)
526
+ # The effect is equivalent to the normal tests using
527
+ # atol = eps, btol = eps, conlim = 1/eps.
528
+ if itn >= iter_lim:
529
+ istop = 7
530
+ if 1 + test3 <= 1:
531
+ istop = 6
532
+ if 1 + test2 <= 1:
533
+ istop = 5
534
+ if 1 + t1 <= 1:
535
+ istop = 4
536
+
537
+ # Allow for tolerances set by the user.
538
+ if test3 <= ctol:
539
+ istop = 3
540
+ if test2 <= atol:
541
+ istop = 2
542
+ if test1 <= rtol:
543
+ istop = 1
544
+
545
+ if show:
546
+ # See if it is time to print something.
547
+ prnt = False
548
+ if n <= 40:
549
+ prnt = True
550
+ if itn <= 10:
551
+ prnt = True
552
+ if itn >= iter_lim-10:
553
+ prnt = True
554
+ # if itn%10 == 0: prnt = True
555
+ if test3 <= 2*ctol:
556
+ prnt = True
557
+ if test2 <= 10*atol:
558
+ prnt = True
559
+ if test1 <= 10*rtol:
560
+ prnt = True
561
+ if istop != 0:
562
+ prnt = True
563
+
564
+ if prnt:
565
+ str1 = f'{itn:6g} {x[0]:12.5e}'
566
+ str2 = f' {r1norm:10.3e} {r2norm:10.3e}'
567
+ str3 = f' {test1:8.1e} {test2:8.1e}'
568
+ str4 = f' {anorm:8.1e} {acond:8.1e}'
569
+ print(str1, str2, str3, str4)
570
+
571
+ if istop != 0:
572
+ break
573
+
574
+ # End of iteration loop.
575
+ # Print the stopping condition.
576
+ if show:
577
+ print(' ')
578
+ print('LSQR finished')
579
+ print(msg[istop])
580
+ print(' ')
581
+ str1 = f'istop ={istop:8g} r1norm ={r1norm:8.1e}'
582
+ str2 = f'anorm ={anorm:8.1e} arnorm ={arnorm:8.1e}'
583
+ str3 = f'itn ={itn:8g} r2norm ={r2norm:8.1e}'
584
+ str4 = f'acond ={acond:8.1e} xnorm ={xnorm:8.1e}'
585
+ print(str1 + ' ' + str2)
586
+ print(str3 + ' ' + str4)
587
+ print(' ')
588
+
589
+ return x, istop, itn, r1norm, r2norm, anorm, acond, arnorm, xnorm, var
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/minres.py ADDED
@@ -0,0 +1,372 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from numpy import inner, zeros, inf, finfo
2
+ from numpy.linalg import norm
3
+ from math import sqrt
4
+
5
+ from .utils import make_system
6
+
7
+ __all__ = ['minres']
8
+
9
+
10
+ def minres(A, b, x0=None, *, rtol=1e-5, shift=0.0, maxiter=None,
11
+ M=None, callback=None, show=False, check=False):
12
+ """
13
+ Use MINimum RESidual iteration to solve Ax=b
14
+
15
+ MINRES minimizes norm(Ax - b) for a real symmetric matrix A. Unlike
16
+ the Conjugate Gradient method, A can be indefinite or singular.
17
+
18
+ If shift != 0 then the method solves (A - shift*I)x = b
19
+
20
+ Parameters
21
+ ----------
22
+ A : {sparse array, ndarray, LinearOperator}
23
+ The real symmetric N-by-N matrix of the linear system
24
+ Alternatively, ``A`` can be a linear operator which can
25
+ produce ``Ax`` using, e.g.,
26
+ ``scipy.sparse.linalg.LinearOperator``.
27
+ b : ndarray
28
+ Right hand side of the linear system. Has shape (N,) or (N,1).
29
+
30
+ Returns
31
+ -------
32
+ x : ndarray
33
+ The converged solution.
34
+ info : integer
35
+ Provides convergence information:
36
+ 0 : successful exit
37
+ >0 : convergence to tolerance not achieved, number of iterations
38
+ <0 : illegal input or breakdown
39
+
40
+ Other Parameters
41
+ ----------------
42
+ x0 : ndarray
43
+ Starting guess for the solution.
44
+ shift : float
45
+ Value to apply to the system ``(A - shift * I)x = b``. Default is 0.
46
+ rtol : float
47
+ Tolerance to achieve. The algorithm terminates when the relative
48
+ residual is below ``rtol``.
49
+ maxiter : integer
50
+ Maximum number of iterations. Iteration will stop after maxiter
51
+ steps even if the specified tolerance has not been achieved.
52
+ M : {sparse array, ndarray, LinearOperator}
53
+ Preconditioner for A. The preconditioner should approximate the
54
+ inverse of A. Effective preconditioning dramatically improves the
55
+ rate of convergence, which implies that fewer iterations are needed
56
+ to reach a given error tolerance.
57
+ callback : function
58
+ User-supplied function to call after each iteration. It is called
59
+ as callback(xk), where xk is the current solution vector.
60
+ show : bool
61
+ If ``True``, print out a summary and metrics related to the solution
62
+ during iterations. Default is ``False``.
63
+ check : bool
64
+ If ``True``, run additional input validation to check that `A` and
65
+ `M` (if specified) are symmetric. Default is ``False``.
66
+
67
+ Examples
68
+ --------
69
+ >>> import numpy as np
70
+ >>> from scipy.sparse import csc_array
71
+ >>> from scipy.sparse.linalg import minres
72
+ >>> A = csc_array([[3, 2, 0], [1, -1, 0], [0, 5, 1]], dtype=float)
73
+ >>> A = A + A.T
74
+ >>> b = np.array([2, 4, -1], dtype=float)
75
+ >>> x, exitCode = minres(A, b)
76
+ >>> print(exitCode) # 0 indicates successful convergence
77
+ 0
78
+ >>> np.allclose(A.dot(x), b)
79
+ True
80
+
81
+ References
82
+ ----------
83
+ Solution of sparse indefinite systems of linear equations,
84
+ C. C. Paige and M. A. Saunders (1975),
85
+ SIAM J. Numer. Anal. 12(4), pp. 617-629.
86
+ https://web.stanford.edu/group/SOL/software/minres/
87
+
88
+ This file is a translation of the following MATLAB implementation:
89
+ https://web.stanford.edu/group/SOL/software/minres/minres-matlab.zip
90
+
91
+ """
92
+ A, M, x, b, postprocess = make_system(A, M, x0, b)
93
+
94
+ matvec = A.matvec
95
+ psolve = M.matvec
96
+
97
+ first = 'Enter minres. '
98
+ last = 'Exit minres. '
99
+
100
+ n = A.shape[0]
101
+
102
+ if maxiter is None:
103
+ maxiter = 5 * n
104
+
105
+ msg = [' beta2 = 0. If M = I, b and x are eigenvectors ', # -1
106
+ ' beta1 = 0. The exact solution is x0 ', # 0
107
+ ' A solution to Ax = b was found, given rtol ', # 1
108
+ ' A least-squares solution was found, given rtol ', # 2
109
+ ' Reasonable accuracy achieved, given eps ', # 3
110
+ ' x has converged to an eigenvector ', # 4
111
+ ' acond has exceeded 0.1/eps ', # 5
112
+ ' The iteration limit was reached ', # 6
113
+ ' A does not define a symmetric matrix ', # 7
114
+ ' M does not define a symmetric matrix ', # 8
115
+ ' M does not define a pos-def preconditioner '] # 9
116
+
117
+ if show:
118
+ print(first + 'Solution of symmetric Ax = b')
119
+ print(first + f'n = {n:3g} shift = {shift:23.14e}')
120
+ print(first + f'itnlim = {maxiter:3g} rtol = {rtol:11.2e}')
121
+ print()
122
+
123
+ istop = 0
124
+ itn = 0
125
+ Anorm = 0
126
+ Acond = 0
127
+ rnorm = 0
128
+ ynorm = 0
129
+
130
+ xtype = x.dtype
131
+
132
+ eps = finfo(xtype).eps
133
+
134
+ # Set up y and v for the first Lanczos vector v1.
135
+ # y = beta1 P' v1, where P = C**(-1).
136
+ # v is really P' v1.
137
+
138
+ if x0 is None:
139
+ r1 = b.copy()
140
+ else:
141
+ r1 = b - A@x
142
+ y = psolve(r1)
143
+
144
+ beta1 = inner(r1, y)
145
+
146
+ if beta1 < 0:
147
+ raise ValueError('indefinite preconditioner')
148
+ elif beta1 == 0:
149
+ return (postprocess(x), 0)
150
+
151
+ bnorm = norm(b)
152
+ if bnorm == 0:
153
+ x = b
154
+ return (postprocess(x), 0)
155
+
156
+ beta1 = sqrt(beta1)
157
+
158
+ if check:
159
+ # are these too strict?
160
+
161
+ # see if A is symmetric
162
+ w = matvec(y)
163
+ r2 = matvec(w)
164
+ s = inner(w,w)
165
+ t = inner(y,r2)
166
+ z = abs(s - t)
167
+ epsa = (s + eps) * eps**(1.0/3.0)
168
+ if z > epsa:
169
+ raise ValueError('non-symmetric matrix')
170
+
171
+ # see if M is symmetric
172
+ r2 = psolve(y)
173
+ s = inner(y,y)
174
+ t = inner(r1,r2)
175
+ z = abs(s - t)
176
+ epsa = (s + eps) * eps**(1.0/3.0)
177
+ if z > epsa:
178
+ raise ValueError('non-symmetric preconditioner')
179
+
180
+ # Initialize other quantities
181
+ oldb = 0
182
+ beta = beta1
183
+ dbar = 0
184
+ epsln = 0
185
+ qrnorm = beta1
186
+ phibar = beta1
187
+ rhs1 = beta1
188
+ rhs2 = 0
189
+ tnorm2 = 0
190
+ gmax = 0
191
+ gmin = finfo(xtype).max
192
+ cs = -1
193
+ sn = 0
194
+ w = zeros(n, dtype=xtype)
195
+ w2 = zeros(n, dtype=xtype)
196
+ r2 = r1
197
+
198
+ if show:
199
+ print()
200
+ print()
201
+ print(' Itn x(1) Compatible LS norm(A) cond(A) gbar/|A|')
202
+
203
+ while itn < maxiter:
204
+ itn += 1
205
+
206
+ s = 1.0/beta
207
+ v = s*y
208
+
209
+ y = matvec(v)
210
+ y = y - shift * v
211
+
212
+ if itn >= 2:
213
+ y = y - (beta/oldb)*r1
214
+
215
+ alfa = inner(v,y)
216
+ y = y - (alfa/beta)*r2
217
+ r1 = r2
218
+ r2 = y
219
+ y = psolve(r2)
220
+ oldb = beta
221
+ beta = inner(r2,y)
222
+ if beta < 0:
223
+ raise ValueError('non-symmetric matrix')
224
+ beta = sqrt(beta)
225
+ tnorm2 += alfa**2 + oldb**2 + beta**2
226
+
227
+ if itn == 1:
228
+ if beta/beta1 <= 10*eps:
229
+ istop = -1 # Terminate later
230
+
231
+ # Apply previous rotation Qk-1 to get
232
+ # [deltak epslnk+1] = [cs sn][dbark 0 ]
233
+ # [gbar k dbar k+1] [sn -cs][alfak betak+1].
234
+
235
+ oldeps = epsln
236
+ delta = cs * dbar + sn * alfa # delta1 = 0 deltak
237
+ gbar = sn * dbar - cs * alfa # gbar 1 = alfa1 gbar k
238
+ epsln = sn * beta # epsln2 = 0 epslnk+1
239
+ dbar = - cs * beta # dbar 2 = beta2 dbar k+1
240
+ root = norm([gbar, dbar])
241
+ Arnorm = phibar * root
242
+
243
+ # Compute the next plane rotation Qk
244
+
245
+ gamma = norm([gbar, beta]) # gammak
246
+ gamma = max(gamma, eps)
247
+ cs = gbar / gamma # ck
248
+ sn = beta / gamma # sk
249
+ phi = cs * phibar # phik
250
+ phibar = sn * phibar # phibark+1
251
+
252
+ # Update x.
253
+
254
+ denom = 1.0/gamma
255
+ w1 = w2
256
+ w2 = w
257
+ w = (v - oldeps*w1 - delta*w2) * denom
258
+ x = x + phi*w
259
+
260
+ # Go round again.
261
+
262
+ gmax = max(gmax, gamma)
263
+ gmin = min(gmin, gamma)
264
+ z = rhs1 / gamma
265
+ rhs1 = rhs2 - delta*z
266
+ rhs2 = - epsln*z
267
+
268
+ # Estimate various norms and test for convergence.
269
+
270
+ Anorm = sqrt(tnorm2)
271
+ ynorm = norm(x)
272
+ epsa = Anorm * eps
273
+ epsx = Anorm * ynorm * eps
274
+ epsr = Anorm * ynorm * rtol
275
+ diag = gbar
276
+
277
+ if diag == 0:
278
+ diag = epsa
279
+
280
+ qrnorm = phibar
281
+ rnorm = qrnorm
282
+ if ynorm == 0 or Anorm == 0:
283
+ test1 = inf
284
+ else:
285
+ test1 = rnorm / (Anorm*ynorm) # ||r|| / (||A|| ||x||)
286
+ if Anorm == 0:
287
+ test2 = inf
288
+ else:
289
+ test2 = root / Anorm # ||Ar|| / (||A|| ||r||)
290
+
291
+ # Estimate cond(A).
292
+ # In this version we look at the diagonals of R in the
293
+ # factorization of the lower Hessenberg matrix, Q @ H = R,
294
+ # where H is the tridiagonal matrix from Lanczos with one
295
+ # extra row, beta(k+1) e_k^T.
296
+
297
+ Acond = gmax/gmin
298
+
299
+ # See if any of the stopping criteria are satisfied.
300
+ # In rare cases, istop is already -1 from above (Abar = const*I).
301
+
302
+ if istop == 0:
303
+ t1 = 1 + test1 # These tests work if rtol < eps
304
+ t2 = 1 + test2
305
+ if t2 <= 1:
306
+ istop = 2
307
+ if t1 <= 1:
308
+ istop = 1
309
+
310
+ if itn >= maxiter:
311
+ istop = 6
312
+ if Acond >= 0.1/eps:
313
+ istop = 4
314
+ if epsx >= beta1:
315
+ istop = 3
316
+ # if rnorm <= epsx : istop = 2
317
+ # if rnorm <= epsr : istop = 1
318
+ if test2 <= rtol:
319
+ istop = 2
320
+ if test1 <= rtol:
321
+ istop = 1
322
+
323
+ # See if it is time to print something.
324
+
325
+ prnt = False
326
+ if n <= 40:
327
+ prnt = True
328
+ if itn <= 10:
329
+ prnt = True
330
+ if itn >= maxiter-10:
331
+ prnt = True
332
+ if itn % 10 == 0:
333
+ prnt = True
334
+ if qrnorm <= 10*epsx:
335
+ prnt = True
336
+ if qrnorm <= 10*epsr:
337
+ prnt = True
338
+ if Acond <= 1e-2/eps:
339
+ prnt = True
340
+ if istop != 0:
341
+ prnt = True
342
+
343
+ if show and prnt:
344
+ str1 = f'{itn:6g} {x[0]:12.5e} {test1:10.3e}'
345
+ str2 = f' {test2:10.3e}'
346
+ str3 = f' {Anorm:8.1e} {Acond:8.1e} {gbar/Anorm:8.1e}'
347
+
348
+ print(str1 + str2 + str3)
349
+
350
+ if itn % 10 == 0:
351
+ print()
352
+
353
+ if callback is not None:
354
+ callback(x)
355
+
356
+ if istop != 0:
357
+ break # TODO check this
358
+
359
+ if show:
360
+ print()
361
+ print(last + f' istop = {istop:3g} itn ={itn:5g}')
362
+ print(last + f' Anorm = {Anorm:12.4e} Acond = {Acond:12.4e}')
363
+ print(last + f' rnorm = {rnorm:12.4e} ynorm = {ynorm:12.4e}')
364
+ print(last + f' Arnorm = {Arnorm:12.4e}')
365
+ print(last + msg[istop+1])
366
+
367
+ if istop == 6:
368
+ info = maxiter
369
+ else:
370
+ info = 0
371
+
372
+ return (postprocess(x),info)
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/__init__.py ADDED
File without changes
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_gcrotmk.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Tests for the linalg._isolve.gcrotmk module
3
+ """
4
+
5
+ import threading
6
+ from numpy.testing import (assert_, assert_allclose, assert_equal,
7
+ suppress_warnings)
8
+
9
+ import numpy as np
10
+ from numpy import zeros, array, allclose
11
+ from scipy.linalg import norm
12
+ from scipy.sparse import csr_array, eye_array, random_array
13
+
14
+ from scipy.sparse.linalg._interface import LinearOperator
15
+ from scipy.sparse.linalg import splu
16
+ from scipy.sparse.linalg._isolve import gcrotmk, gmres
17
+
18
+
19
+ Am = csr_array(array([[-2,1,0,0,0,9],
20
+ [1,-2,1,0,5,0],
21
+ [0,1,-2,1,0,0],
22
+ [0,0,1,-2,1,0],
23
+ [0,3,0,1,-2,1],
24
+ [1,0,0,0,1,-2]]))
25
+ b = array([1,2,3,4,5,6])
26
+ count = threading.local() # [0]
27
+ niter = threading.local() # [0]
28
+
29
+
30
+ def matvec(v):
31
+ if not hasattr(count, 'c'):
32
+ count.c = [0]
33
+ count.c[0] += 1
34
+ return Am@v
35
+
36
+
37
+ def cb(v):
38
+ if not hasattr(niter, 'n'):
39
+ niter.n = [0]
40
+ niter.n[0] += 1
41
+
42
+
43
+ A = LinearOperator(matvec=matvec, shape=Am.shape, dtype=Am.dtype)
44
+
45
+
46
+ def do_solve(**kw):
47
+ if not hasattr(niter, 'n'):
48
+ niter.n = [0]
49
+
50
+ if not hasattr(count, 'c'):
51
+ count.c = [0]
52
+
53
+ count.c[0] = 0
54
+ with suppress_warnings() as sup:
55
+ sup.filter(DeprecationWarning, ".*called without specifying.*")
56
+ x0, flag = gcrotmk(A, b, x0=zeros(A.shape[0]), rtol=1e-14, **kw)
57
+ count_0 = count.c[0]
58
+ assert_(allclose(A@x0, b, rtol=1e-12, atol=1e-12), norm(A@x0-b))
59
+ return x0, count_0
60
+
61
+
62
+ class TestGCROTMK:
63
+ def test_preconditioner(self):
64
+ # Check that preconditioning works
65
+ pc = splu(Am.tocsc())
66
+ M = LinearOperator(matvec=pc.solve, shape=A.shape, dtype=A.dtype)
67
+
68
+ x0, count_0 = do_solve()
69
+ niter.n[0] = 0
70
+ x1, count_1 = do_solve(M=M, callback=cb)
71
+
72
+ assert_equal(count_1, 3)
73
+ assert count_1 < count_0/2
74
+ assert allclose(x1, x0, rtol=1e-14)
75
+ assert niter.n[0] < 3
76
+
77
+ def test_arnoldi(self):
78
+ rng = np.random.default_rng(1)
79
+
80
+ A = eye_array(2000) + random_array((2000, 2000), density=5e-4, rng=rng)
81
+ b = rng.random(2000)
82
+
83
+ # The inner arnoldi should be equivalent to gmres
84
+ with suppress_warnings() as sup:
85
+ sup.filter(DeprecationWarning, ".*called without specifying.*")
86
+ x0, flag0 = gcrotmk(A, b, x0=zeros(A.shape[0]), m=10, k=0, maxiter=1)
87
+ x1, flag1 = gmres(A, b, x0=zeros(A.shape[0]), restart=10, maxiter=1)
88
+
89
+ assert_equal(flag0, 1)
90
+ assert_equal(flag1, 1)
91
+ assert np.linalg.norm(A.dot(x0) - b) > 1e-4
92
+
93
+ assert_allclose(x0, x1)
94
+
95
+ def test_cornercase(self):
96
+ np.random.seed(1234)
97
+
98
+ # Rounding error may prevent convergence with tol=0 --- ensure
99
+ # that the return values in this case are correct, and no
100
+ # exceptions are raised
101
+
102
+ for n in [3, 5, 10, 100]:
103
+ A = 2*eye_array(n)
104
+
105
+ with suppress_warnings() as sup:
106
+ sup.filter(DeprecationWarning, ".*called without specifying.*")
107
+ b = np.ones(n)
108
+ x, info = gcrotmk(A, b, maxiter=10)
109
+ assert_equal(info, 0)
110
+ assert_allclose(A.dot(x) - b, 0, atol=1e-14)
111
+
112
+ x, info = gcrotmk(A, b, rtol=0, maxiter=10)
113
+ if info == 0:
114
+ assert_allclose(A.dot(x) - b, 0, atol=1e-14)
115
+
116
+ b = np.random.rand(n)
117
+ x, info = gcrotmk(A, b, maxiter=10)
118
+ assert_equal(info, 0)
119
+ assert_allclose(A.dot(x) - b, 0, atol=1e-14)
120
+
121
+ x, info = gcrotmk(A, b, rtol=0, maxiter=10)
122
+ if info == 0:
123
+ assert_allclose(A.dot(x) - b, 0, atol=1e-14)
124
+
125
+ def test_nans(self):
126
+ A = eye_array(3, format='lil')
127
+ A[1,1] = np.nan
128
+ b = np.ones(3)
129
+
130
+ with suppress_warnings() as sup:
131
+ sup.filter(DeprecationWarning, ".*called without specifying.*")
132
+ x, info = gcrotmk(A, b, rtol=0, maxiter=10)
133
+ assert_equal(info, 1)
134
+
135
+ def test_truncate(self):
136
+ np.random.seed(1234)
137
+ A = np.random.rand(30, 30) + np.eye(30)
138
+ b = np.random.rand(30)
139
+
140
+ for truncate in ['oldest', 'smallest']:
141
+ with suppress_warnings() as sup:
142
+ sup.filter(DeprecationWarning, ".*called without specifying.*")
143
+ x, info = gcrotmk(A, b, m=10, k=10, truncate=truncate,
144
+ rtol=1e-4, maxiter=200)
145
+ assert_equal(info, 0)
146
+ assert_allclose(A.dot(x) - b, 0, atol=1e-3)
147
+
148
+ def test_CU(self):
149
+ for discard_C in (True, False):
150
+ # Check that C,U behave as expected
151
+ CU = []
152
+ x0, count_0 = do_solve(CU=CU, discard_C=discard_C)
153
+ assert_(len(CU) > 0)
154
+ assert_(len(CU) <= 6)
155
+
156
+ if discard_C:
157
+ for c, u in CU:
158
+ assert_(c is None)
159
+
160
+ # should converge immediately
161
+ x1, count_1 = do_solve(CU=CU, discard_C=discard_C)
162
+ if discard_C:
163
+ assert_equal(count_1, 2 + len(CU))
164
+ else:
165
+ assert_equal(count_1, 3)
166
+ assert_(count_1 <= count_0/2)
167
+ assert_allclose(x1, x0, atol=1e-14)
168
+
169
+ def test_denormals(self):
170
+ # Check that no warnings are emitted if the matrix contains
171
+ # numbers for which 1/x has no float representation, and that
172
+ # the solver behaves properly.
173
+ A = np.array([[1, 2], [3, 4]], dtype=float)
174
+ A *= 100 * np.nextafter(0, 1)
175
+
176
+ b = np.array([1, 1])
177
+
178
+ with suppress_warnings() as sup:
179
+ sup.filter(DeprecationWarning, ".*called without specifying.*")
180
+ xp, info = gcrotmk(A, b)
181
+
182
+ if info == 0:
183
+ assert_allclose(A.dot(xp), b)
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_iterative.py ADDED
@@ -0,0 +1,809 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Test functions for the sparse.linalg._isolve module
2
+ """
3
+
4
+ import itertools
5
+ import platform
6
+ import pytest
7
+
8
+ import numpy as np
9
+ from numpy.testing import assert_array_equal, assert_allclose
10
+ from numpy import zeros, arange, array, ones, eye, iscomplexobj
11
+ from numpy.linalg import norm
12
+
13
+ from scipy.sparse import dia_array, csr_array, kronsum
14
+
15
+ from scipy.sparse.linalg import LinearOperator, aslinearoperator
16
+ from scipy.sparse.linalg._isolve import (bicg, bicgstab, cg, cgs,
17
+ gcrotmk, gmres, lgmres,
18
+ minres, qmr, tfqmr)
19
+
20
+ # TODO check that method preserve shape and type
21
+ # TODO test both preconditioner methods
22
+
23
+
24
+ # list of all solvers under test
25
+ _SOLVERS = [bicg, bicgstab, cg, cgs, gcrotmk, gmres, lgmres,
26
+ minres, qmr, tfqmr]
27
+
28
+ CB_TYPE_FILTER = ".*called without specifying `callback_type`.*"
29
+
30
+
31
+ # create parametrized fixture for easy reuse in tests
32
+ @pytest.fixture(params=_SOLVERS, scope="session")
33
+ def solver(request):
34
+ """
35
+ Fixture for all solvers in scipy.sparse.linalg._isolve
36
+ """
37
+ return request.param
38
+
39
+
40
+ class Case:
41
+ def __init__(self, name, A, b=None, skip=None, nonconvergence=None):
42
+ self.name = name
43
+ self.A = A
44
+ if b is None:
45
+ self.b = arange(A.shape[0], dtype=float)
46
+ else:
47
+ self.b = b
48
+ if skip is None:
49
+ self.skip = []
50
+ else:
51
+ self.skip = skip
52
+ if nonconvergence is None:
53
+ self.nonconvergence = []
54
+ else:
55
+ self.nonconvergence = nonconvergence
56
+
57
+
58
+ class SingleTest:
59
+ def __init__(self, A, b, solver, casename, convergence=True):
60
+ self.A = A
61
+ self.b = b
62
+ self.solver = solver
63
+ self.name = casename + '-' + solver.__name__
64
+ self.convergence = convergence
65
+
66
+ def __repr__(self):
67
+ return f"<{self.name}>"
68
+
69
+
70
+ class IterativeParams:
71
+ def __init__(self):
72
+ sym_solvers = [minres, cg]
73
+ posdef_solvers = [cg]
74
+ real_solvers = [minres]
75
+
76
+ # list of Cases
77
+ self.cases = []
78
+
79
+ # Symmetric and Positive Definite
80
+ N = 40
81
+ data = ones((3, N))
82
+ data[0, :] = 2
83
+ data[1, :] = -1
84
+ data[2, :] = -1
85
+ Poisson1D = dia_array((data, [0, -1, 1]), shape=(N, N)).tocsr()
86
+ self.cases.append(Case("poisson1d", Poisson1D))
87
+ # note: minres fails for single precision
88
+ self.cases.append(Case("poisson1d-F", Poisson1D.astype('f'),
89
+ skip=[minres]))
90
+
91
+ # Symmetric and Negative Definite
92
+ self.cases.append(Case("neg-poisson1d", -Poisson1D,
93
+ skip=posdef_solvers))
94
+ # note: minres fails for single precision
95
+ self.cases.append(Case("neg-poisson1d-F", (-Poisson1D).astype('f'),
96
+ skip=posdef_solvers + [minres]))
97
+
98
+ # 2-dimensional Poisson equations
99
+ Poisson2D = kronsum(Poisson1D, Poisson1D)
100
+ # note: minres fails for 2-d poisson problem,
101
+ # it will be fixed in the future PR
102
+ self.cases.append(Case("poisson2d", Poisson2D, skip=[minres]))
103
+ # note: minres fails for single precision
104
+ self.cases.append(Case("poisson2d-F", Poisson2D.astype('f'),
105
+ skip=[minres]))
106
+
107
+ # Symmetric and Indefinite
108
+ data = array([[6, -5, 2, 7, -1, 10, 4, -3, -8, 9]], dtype='d')
109
+ RandDiag = dia_array((data, [0]), shape=(10, 10)).tocsr()
110
+ self.cases.append(Case("rand-diag", RandDiag, skip=posdef_solvers))
111
+ self.cases.append(Case("rand-diag-F", RandDiag.astype('f'),
112
+ skip=posdef_solvers))
113
+
114
+ # Random real-valued
115
+ rng = np.random.RandomState(1234)
116
+ data = rng.rand(4, 4)
117
+ self.cases.append(Case("rand", data,
118
+ skip=posdef_solvers + sym_solvers))
119
+ self.cases.append(Case("rand-F", data.astype('f'),
120
+ skip=posdef_solvers + sym_solvers))
121
+
122
+ # Random symmetric real-valued
123
+ rng = np.random.RandomState(1234)
124
+ data = rng.rand(4, 4)
125
+ data = data + data.T
126
+ self.cases.append(Case("rand-sym", data, skip=posdef_solvers))
127
+ self.cases.append(Case("rand-sym-F", data.astype('f'),
128
+ skip=posdef_solvers))
129
+
130
+ # Random pos-def symmetric real
131
+ np.random.seed(1234)
132
+ data = np.random.rand(9, 9)
133
+ data = np.dot(data.conj(), data.T)
134
+ self.cases.append(Case("rand-sym-pd", data))
135
+ # note: minres fails for single precision
136
+ self.cases.append(Case("rand-sym-pd-F", data.astype('f'),
137
+ skip=[minres]))
138
+
139
+ # Random complex-valued
140
+ rng = np.random.RandomState(1234)
141
+ data = rng.rand(4, 4) + 1j * rng.rand(4, 4)
142
+ skip_cmplx = posdef_solvers + sym_solvers + real_solvers
143
+ self.cases.append(Case("rand-cmplx", data, skip=skip_cmplx))
144
+ self.cases.append(Case("rand-cmplx-F", data.astype('F'),
145
+ skip=skip_cmplx))
146
+
147
+ # Random hermitian complex-valued
148
+ rng = np.random.RandomState(1234)
149
+ data = rng.rand(4, 4) + 1j * rng.rand(4, 4)
150
+ data = data + data.T.conj()
151
+ self.cases.append(Case("rand-cmplx-herm", data,
152
+ skip=posdef_solvers + real_solvers))
153
+ self.cases.append(Case("rand-cmplx-herm-F", data.astype('F'),
154
+ skip=posdef_solvers + real_solvers))
155
+
156
+ # Random pos-def hermitian complex-valued
157
+ rng = np.random.RandomState(1234)
158
+ data = rng.rand(9, 9) + 1j * rng.rand(9, 9)
159
+ data = np.dot(data.conj(), data.T)
160
+ self.cases.append(Case("rand-cmplx-sym-pd", data, skip=real_solvers))
161
+ self.cases.append(Case("rand-cmplx-sym-pd-F", data.astype('F'),
162
+ skip=real_solvers))
163
+
164
+ # Non-symmetric and Positive Definite
165
+ #
166
+ # cgs, qmr, bicg and tfqmr fail to converge on this one
167
+ # -- algorithmic limitation apparently
168
+ data = ones((2, 10))
169
+ data[0, :] = 2
170
+ data[1, :] = -1
171
+ A = dia_array((data, [0, -1]), shape=(10, 10)).tocsr()
172
+ self.cases.append(Case("nonsymposdef", A,
173
+ skip=sym_solvers + [cgs, qmr, bicg, tfqmr]))
174
+ self.cases.append(Case("nonsymposdef-F", A.astype('F'),
175
+ skip=sym_solvers + [cgs, qmr, bicg, tfqmr]))
176
+
177
+ # Symmetric, non-pd, hitting cgs/bicg/bicgstab/qmr/tfqmr breakdown
178
+ A = np.array([[0, 0, 0, 0, 0, 1, -1, -0, -0, -0, -0],
179
+ [0, 0, 0, 0, 0, 2, -0, -1, -0, -0, -0],
180
+ [0, 0, 0, 0, 0, 2, -0, -0, -1, -0, -0],
181
+ [0, 0, 0, 0, 0, 2, -0, -0, -0, -1, -0],
182
+ [0, 0, 0, 0, 0, 1, -0, -0, -0, -0, -1],
183
+ [1, 2, 2, 2, 1, 0, -0, -0, -0, -0, -0],
184
+ [-1, 0, 0, 0, 0, 0, -1, -0, -0, -0, -0],
185
+ [0, -1, 0, 0, 0, 0, -0, -1, -0, -0, -0],
186
+ [0, 0, -1, 0, 0, 0, -0, -0, -1, -0, -0],
187
+ [0, 0, 0, -1, 0, 0, -0, -0, -0, -1, -0],
188
+ [0, 0, 0, 0, -1, 0, -0, -0, -0, -0, -1]], dtype=float)
189
+ b = np.array([0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], dtype=float)
190
+ assert (A == A.T).all()
191
+ self.cases.append(Case("sym-nonpd", A, b,
192
+ skip=posdef_solvers,
193
+ nonconvergence=[cgs, bicg, bicgstab, qmr, tfqmr]
194
+ )
195
+ )
196
+
197
+ def generate_tests(self):
198
+ # generate test cases with skips applied
199
+ tests = []
200
+ for case in self.cases:
201
+ for solver in _SOLVERS:
202
+ if (solver in case.skip):
203
+ continue
204
+ if solver in case.nonconvergence:
205
+ tests += [SingleTest(case.A, case.b, solver, case.name,
206
+ convergence=False)]
207
+ else:
208
+ tests += [SingleTest(case.A, case.b, solver, case.name)]
209
+ return tests
210
+
211
+
212
+ cases = IterativeParams().generate_tests()
213
+
214
+
215
+ @pytest.fixture(params=cases, ids=[x.name for x in cases], scope="module")
216
+ def case(request):
217
+ """
218
+ Fixture for all cases in IterativeParams
219
+ """
220
+ return request.param
221
+
222
+ @pytest.mark.thread_unsafe
223
+ def test_maxiter(case):
224
+ if not case.convergence:
225
+ pytest.skip("Solver - Breakdown case, see gh-8829")
226
+ A = case.A
227
+ rtol = 1e-12
228
+
229
+ b = case.b
230
+ x0 = 0 * b
231
+
232
+ residuals = []
233
+
234
+ def callback(x):
235
+ if x.ndim == 0:
236
+ residuals.append(norm(b - case.A * x))
237
+ else:
238
+ residuals.append(norm(b - case.A @ x))
239
+
240
+ if case.solver == gmres:
241
+ with pytest.warns(DeprecationWarning, match=CB_TYPE_FILTER):
242
+ x, info = case.solver(A, b, x0=x0, rtol=rtol, maxiter=1, callback=callback)
243
+ else:
244
+ x, info = case.solver(A, b, x0=x0, rtol=rtol, maxiter=1, callback=callback)
245
+
246
+ assert len(residuals) == 1
247
+ assert info == 1
248
+
249
+
250
+ def test_convergence(case):
251
+ A = case.A
252
+
253
+ if A.dtype.char in "dD":
254
+ rtol = 1e-8
255
+ else:
256
+ rtol = 1e-2
257
+
258
+ b = case.b
259
+ x0 = 0 * b
260
+
261
+ x, info = case.solver(A, b, x0=x0, rtol=rtol)
262
+
263
+ assert_array_equal(x0, 0 * b) # ensure that x0 is not overwritten
264
+ if case.convergence:
265
+ assert info == 0
266
+ assert norm(A @ x - b) <= norm(b) * rtol
267
+ else:
268
+ assert info != 0
269
+ assert norm(A @ x - b) <= norm(b)
270
+
271
+
272
+ def test_precond_dummy(case):
273
+ if not case.convergence:
274
+ pytest.skip("Solver - Breakdown case, see gh-8829")
275
+
276
+ rtol = 1e-8
277
+
278
+ def identity(b, which=None):
279
+ """trivial preconditioner"""
280
+ return b
281
+
282
+ A = case.A
283
+
284
+ M, N = A.shape
285
+ # Ensure the diagonal elements of A are non-zero before calculating
286
+ # 1.0/A.diagonal()
287
+ diagOfA = A.diagonal()
288
+ if np.count_nonzero(diagOfA) == len(diagOfA):
289
+ dia_array(([1.0 / diagOfA], [0]), shape=(M, N))
290
+
291
+ b = case.b
292
+ x0 = 0 * b
293
+
294
+ precond = LinearOperator(A.shape, identity, rmatvec=identity)
295
+
296
+ if case.solver is qmr:
297
+ x, info = case.solver(A, b, M1=precond, M2=precond, x0=x0, rtol=rtol)
298
+ else:
299
+ x, info = case.solver(A, b, M=precond, x0=x0, rtol=rtol)
300
+ assert info == 0
301
+ assert norm(A @ x - b) <= norm(b) * rtol
302
+
303
+ A = aslinearoperator(A)
304
+ A.psolve = identity
305
+ A.rpsolve = identity
306
+
307
+ x, info = case.solver(A, b, x0=x0, rtol=rtol)
308
+ assert info == 0
309
+ assert norm(A @ x - b) <= norm(b) * rtol
310
+
311
+
312
+ # Specific test for poisson1d and poisson2d cases
313
+ @pytest.mark.fail_slow(10)
314
+ @pytest.mark.parametrize('case', [x for x in IterativeParams().cases
315
+ if x.name in ('poisson1d', 'poisson2d')],
316
+ ids=['poisson1d', 'poisson2d'])
317
+ def test_precond_inverse(case):
318
+ for solver in _SOLVERS:
319
+ if solver in case.skip or solver is qmr:
320
+ continue
321
+
322
+ rtol = 1e-8
323
+
324
+ def inverse(b, which=None):
325
+ """inverse preconditioner"""
326
+ A = case.A
327
+ if not isinstance(A, np.ndarray):
328
+ A = A.toarray()
329
+ return np.linalg.solve(A, b)
330
+
331
+ def rinverse(b, which=None):
332
+ """inverse preconditioner"""
333
+ A = case.A
334
+ if not isinstance(A, np.ndarray):
335
+ A = A.toarray()
336
+ return np.linalg.solve(A.T, b)
337
+
338
+ matvec_count = [0]
339
+
340
+ def matvec(b):
341
+ matvec_count[0] += 1
342
+ return case.A @ b
343
+
344
+ def rmatvec(b):
345
+ matvec_count[0] += 1
346
+ return case.A.T @ b
347
+
348
+ b = case.b
349
+ x0 = 0 * b
350
+
351
+ A = LinearOperator(case.A.shape, matvec, rmatvec=rmatvec)
352
+ precond = LinearOperator(case.A.shape, inverse, rmatvec=rinverse)
353
+
354
+ # Solve with preconditioner
355
+ matvec_count = [0]
356
+ x, info = solver(A, b, M=precond, x0=x0, rtol=rtol)
357
+
358
+ assert info == 0
359
+ assert norm(case.A @ x - b) <= norm(b) * rtol
360
+
361
+ # Solution should be nearly instant
362
+ assert matvec_count[0] <= 3
363
+
364
+
365
+ def test_atol(solver):
366
+ # TODO: minres / tfqmr. It didn't historically use absolute tolerances, so
367
+ # fixing it is less urgent.
368
+ if solver in (minres, tfqmr):
369
+ pytest.skip("TODO: Add atol to minres/tfqmr")
370
+
371
+ # Historically this is tested as below, all pass but for some reason
372
+ # gcrotmk is over-sensitive to difference between random.seed/rng.random
373
+ # Hence tol lower bound is changed from -10 to -9
374
+ # np.random.seed(1234)
375
+ # A = np.random.rand(10, 10)
376
+ # A = A @ A.T + 10 * np.eye(10)
377
+ # b = 1e3*np.random.rand(10)
378
+
379
+ rng = np.random.default_rng(168441431005389)
380
+ A = rng.uniform(size=[10, 10])
381
+ A = A @ A.T + 10*np.eye(10)
382
+ b = 1e3 * rng.uniform(size=10)
383
+
384
+ b_norm = np.linalg.norm(b)
385
+
386
+ tols = np.r_[0, np.logspace(-9, 2, 7), np.inf]
387
+
388
+ # Check effect of badly scaled preconditioners
389
+ M0 = rng.standard_normal(size=(10, 10))
390
+ M0 = M0 @ M0.T
391
+ Ms = [None, 1e-6 * M0, 1e6 * M0]
392
+
393
+ for M, rtol, atol in itertools.product(Ms, tols, tols):
394
+ if rtol == 0 and atol == 0:
395
+ continue
396
+
397
+ if solver is qmr:
398
+ if M is not None:
399
+ M = aslinearoperator(M)
400
+ M2 = aslinearoperator(np.eye(10))
401
+ else:
402
+ M2 = None
403
+ x, info = solver(A, b, M1=M, M2=M2, rtol=rtol, atol=atol)
404
+ else:
405
+ x, info = solver(A, b, M=M, rtol=rtol, atol=atol)
406
+
407
+ assert info == 0
408
+ residual = A @ x - b
409
+ err = np.linalg.norm(residual)
410
+ atol2 = rtol * b_norm
411
+ # Added 1.00025 fudge factor because of `err` exceeding `atol` just
412
+ # very slightly on s390x (see gh-17839)
413
+ assert err <= 1.00025 * max(atol, atol2)
414
+
415
+
416
+ def test_zero_rhs(solver):
417
+ rng = np.random.default_rng(1684414984100503)
418
+ A = rng.random(size=[10, 10])
419
+ A = A @ A.T + 10 * np.eye(10)
420
+
421
+ b = np.zeros(10)
422
+ tols = np.r_[np.logspace(-10, 2, 7)]
423
+
424
+ for tol in tols:
425
+ x, info = solver(A, b, rtol=tol)
426
+ assert info == 0
427
+ assert_allclose(x, 0., atol=1e-15)
428
+
429
+ x, info = solver(A, b, rtol=tol, x0=ones(10))
430
+ assert info == 0
431
+ assert_allclose(x, 0., atol=tol)
432
+
433
+ if solver is not minres:
434
+ x, info = solver(A, b, rtol=tol, atol=0, x0=ones(10))
435
+ if info == 0:
436
+ assert_allclose(x, 0)
437
+
438
+ x, info = solver(A, b, rtol=tol, atol=tol)
439
+ assert info == 0
440
+ assert_allclose(x, 0, atol=1e-300)
441
+
442
+ x, info = solver(A, b, rtol=tol, atol=0)
443
+ assert info == 0
444
+ assert_allclose(x, 0, atol=1e-300)
445
+
446
+
447
+ @pytest.mark.xfail(reason="see gh-18697")
448
+ def test_maxiter_worsening(solver):
449
+ if solver not in (gmres, lgmres, qmr):
450
+ # these were skipped from the very beginning, see gh-9201; gh-14160
451
+ pytest.skip("Solver breakdown case")
452
+ # Check error does not grow (boundlessly) with increasing maxiter.
453
+ # This can occur due to the solvers hitting close to breakdown,
454
+ # which they should detect and halt as necessary.
455
+ # cf. gh-9100
456
+ if (solver is lgmres and
457
+ platform.machine() not in ['x86_64' 'x86', 'aarch64', 'arm64']):
458
+ # see gh-17839
459
+ pytest.xfail(reason="fails on at least ppc64le, ppc64 and riscv64")
460
+
461
+ # Singular matrix, rhs numerically not in range
462
+ A = np.array([[-0.1112795288033378, 0, 0, 0.16127952880333685],
463
+ [0, -0.13627952880333782 + 6.283185307179586j, 0, 0],
464
+ [0, 0, -0.13627952880333782 - 6.283185307179586j, 0],
465
+ [0.1112795288033368, 0j, 0j, -0.16127952880333785]])
466
+ v = np.ones(4)
467
+ best_error = np.inf
468
+
469
+ # Unable to match the Fortran code tolerance levels with this example
470
+ # Original tolerance values
471
+
472
+ # slack_tol = 7 if platform.machine() == 'aarch64' else 5
473
+ slack_tol = 9
474
+
475
+ for maxiter in range(1, 20):
476
+ x, info = solver(A, v, maxiter=maxiter, rtol=1e-8, atol=0)
477
+
478
+ if info == 0:
479
+ assert norm(A @ x - v) <= 1e-8 * norm(v)
480
+
481
+ error = np.linalg.norm(A @ x - v)
482
+ best_error = min(best_error, error)
483
+
484
+ # Check with slack
485
+ assert error <= slack_tol * best_error
486
+
487
+
488
+ def test_x0_working(solver):
489
+ # Easy problem
490
+ rng = np.random.default_rng(1685363802304750)
491
+ n = 10
492
+ A = rng.random(size=[n, n])
493
+ A = A @ A.T
494
+ b = rng.random(n)
495
+ x0 = rng.random(n)
496
+
497
+ if solver is minres:
498
+ kw = dict(rtol=1e-6)
499
+ else:
500
+ kw = dict(atol=0, rtol=1e-6)
501
+
502
+ x, info = solver(A, b, **kw)
503
+ assert info == 0
504
+ assert norm(A @ x - b) <= 1e-6 * norm(b)
505
+
506
+ x, info = solver(A, b, x0=x0, **kw)
507
+ assert info == 0
508
+ assert norm(A @ x - b) <= 4.5e-6*norm(b)
509
+
510
+
511
+ def test_x0_equals_Mb(case):
512
+ if (case.solver is bicgstab) and (case.name == 'nonsymposdef-bicgstab'):
513
+ pytest.skip("Solver fails due to numerical noise "
514
+ "on some architectures (see gh-15533).")
515
+ if case.solver is tfqmr:
516
+ pytest.skip("Solver does not support x0='Mb'")
517
+
518
+ A = case.A
519
+ b = case.b
520
+ x0 = 'Mb'
521
+ rtol = 1e-8
522
+ x, info = case.solver(A, b, x0=x0, rtol=rtol)
523
+
524
+ assert_array_equal(x0, 'Mb') # ensure that x0 is not overwritten
525
+ assert info == 0
526
+ assert norm(A @ x - b) <= rtol * norm(b)
527
+
528
+
529
+ @pytest.mark.parametrize('solver', _SOLVERS)
530
+ def test_x0_solves_problem_exactly(solver):
531
+ # See gh-19948
532
+ mat = np.eye(2)
533
+ rhs = np.array([-1., -1.])
534
+
535
+ sol, info = solver(mat, rhs, x0=rhs)
536
+ assert_allclose(sol, rhs)
537
+ assert info == 0
538
+
539
+
540
+ # Specific tfqmr test
541
+ @pytest.mark.thread_unsafe
542
+ @pytest.mark.parametrize('case', IterativeParams().cases)
543
+ def test_show(case, capsys):
544
+ def cb(x):
545
+ pass
546
+
547
+ x, info = tfqmr(case.A, case.b, callback=cb, show=True)
548
+ out, err = capsys.readouterr()
549
+
550
+ if case.name == "sym-nonpd":
551
+ # no logs for some reason
552
+ exp = ""
553
+ elif case.name in ("nonsymposdef", "nonsymposdef-F"):
554
+ # Asymmetric and Positive Definite
555
+ exp = "TFQMR: Linear solve not converged due to reach MAXIT iterations"
556
+ else: # all other cases
557
+ exp = "TFQMR: Linear solve converged due to reach TOL iterations"
558
+
559
+ assert out.startswith(exp)
560
+ assert err == ""
561
+
562
+
563
+ def test_positional_error(solver):
564
+ # from test_x0_working
565
+ rng = np.random.default_rng(1685363802304750)
566
+ n = 10
567
+ A = rng.random(size=[n, n])
568
+ A = A @ A.T
569
+ b = rng.random(n)
570
+ x0 = rng.random(n)
571
+ with pytest.raises(TypeError):
572
+ solver(A, b, x0, 1e-5)
573
+
574
+
575
+ @pytest.mark.parametrize("atol", ["legacy", None, -1])
576
+ def test_invalid_atol(solver, atol):
577
+ if solver == minres:
578
+ pytest.skip("minres has no `atol` argument")
579
+ # from test_x0_working
580
+ rng = np.random.default_rng(1685363802304750)
581
+ n = 10
582
+ A = rng.random(size=[n, n])
583
+ A = A @ A.T
584
+ b = rng.random(n)
585
+ x0 = rng.random(n)
586
+ with pytest.raises(ValueError):
587
+ solver(A, b, x0, atol=atol)
588
+
589
+
590
+ class TestQMR:
591
+ @pytest.mark.filterwarnings('ignore::scipy.sparse.SparseEfficiencyWarning')
592
+ def test_leftright_precond(self):
593
+ """Check that QMR works with left and right preconditioners"""
594
+
595
+ from scipy.sparse.linalg._dsolve import splu
596
+ from scipy.sparse.linalg._interface import LinearOperator
597
+
598
+ n = 100
599
+
600
+ dat = ones(n)
601
+ A = dia_array(([-2 * dat, 4 * dat, -dat], [-1, 0, 1]), shape=(n, n))
602
+ b = arange(n, dtype='d')
603
+
604
+ L = dia_array(([-dat / 2, dat], [-1, 0]), shape=(n, n))
605
+ U = dia_array(([4 * dat, -dat], [0, 1]), shape=(n, n))
606
+ L_solver = splu(L)
607
+ U_solver = splu(U)
608
+
609
+ def L_solve(b):
610
+ return L_solver.solve(b)
611
+
612
+ def U_solve(b):
613
+ return U_solver.solve(b)
614
+
615
+ def LT_solve(b):
616
+ return L_solver.solve(b, 'T')
617
+
618
+ def UT_solve(b):
619
+ return U_solver.solve(b, 'T')
620
+
621
+ M1 = LinearOperator((n, n), matvec=L_solve, rmatvec=LT_solve)
622
+ M2 = LinearOperator((n, n), matvec=U_solve, rmatvec=UT_solve)
623
+
624
+ rtol = 1e-8
625
+ x, info = qmr(A, b, rtol=rtol, maxiter=15, M1=M1, M2=M2)
626
+
627
+ assert info == 0
628
+ assert norm(A @ x - b) <= rtol * norm(b)
629
+
630
+
631
+ class TestGMRES:
632
+ def test_basic(self):
633
+ A = np.vander(np.arange(10) + 1)[:, ::-1]
634
+ b = np.zeros(10)
635
+ b[0] = 1
636
+
637
+ x_gm, err = gmres(A, b, restart=5, maxiter=1)
638
+
639
+ assert_allclose(x_gm[0], 0.359, rtol=1e-2)
640
+
641
+ @pytest.mark.filterwarnings(f"ignore:{CB_TYPE_FILTER}:DeprecationWarning")
642
+ def test_callback(self):
643
+
644
+ def store_residual(r, rvec):
645
+ rvec[rvec.nonzero()[0].max() + 1] = r
646
+
647
+ # Define, A,b
648
+ A = csr_array(array([[-2, 1, 0, 0, 0, 0],
649
+ [1, -2, 1, 0, 0, 0],
650
+ [0, 1, -2, 1, 0, 0],
651
+ [0, 0, 1, -2, 1, 0],
652
+ [0, 0, 0, 1, -2, 1],
653
+ [0, 0, 0, 0, 1, -2]]))
654
+ b = ones((A.shape[0],))
655
+ maxiter = 1
656
+ rvec = zeros(maxiter + 1)
657
+ rvec[0] = 1.0
658
+
659
+ def callback(r):
660
+ return store_residual(r, rvec)
661
+
662
+ x, flag = gmres(A, b, x0=zeros(A.shape[0]), rtol=1e-16,
663
+ maxiter=maxiter, callback=callback)
664
+
665
+ # Expected output from SciPy 1.0.0
666
+ assert_allclose(rvec, array([1.0, 0.81649658092772603]), rtol=1e-10)
667
+
668
+ # Test preconditioned callback
669
+ M = 1e-3 * np.eye(A.shape[0])
670
+ rvec = zeros(maxiter + 1)
671
+ rvec[0] = 1.0
672
+ x, flag = gmres(A, b, M=M, rtol=1e-16, maxiter=maxiter,
673
+ callback=callback)
674
+
675
+ # Expected output from SciPy 1.0.0
676
+ # (callback has preconditioned residual!)
677
+ assert_allclose(rvec, array([1.0, 1e-3 * 0.81649658092772603]),
678
+ rtol=1e-10)
679
+
680
+ def test_abi(self):
681
+ # Check we don't segfault on gmres with complex argument
682
+ A = eye(2)
683
+ b = ones(2)
684
+ r_x, r_info = gmres(A, b)
685
+ r_x = r_x.astype(complex)
686
+ x, info = gmres(A.astype(complex), b.astype(complex))
687
+
688
+ assert iscomplexobj(x)
689
+ assert_allclose(r_x, x)
690
+ assert r_info == info
691
+
692
+ @pytest.mark.fail_slow(10)
693
+ def test_atol_legacy(self):
694
+
695
+ A = eye(2)
696
+ b = ones(2)
697
+ x, info = gmres(A, b, rtol=1e-5)
698
+ assert np.linalg.norm(A @ x - b) <= 1e-5 * np.linalg.norm(b)
699
+ assert_allclose(x, b, atol=0, rtol=1e-8)
700
+
701
+ rndm = np.random.RandomState(12345)
702
+ A = rndm.rand(30, 30)
703
+ b = 1e-6 * ones(30)
704
+ x, info = gmres(A, b, rtol=1e-7, restart=20)
705
+ assert np.linalg.norm(A @ x - b) > 1e-7
706
+
707
+ A = eye(2)
708
+ b = 1e-10 * ones(2)
709
+ x, info = gmres(A, b, rtol=1e-8, atol=0)
710
+ assert np.linalg.norm(A @ x - b) <= 1e-8 * np.linalg.norm(b)
711
+
712
+ def test_defective_precond_breakdown(self):
713
+ # Breakdown due to defective preconditioner
714
+ M = np.eye(3)
715
+ M[2, 2] = 0
716
+
717
+ b = np.array([0, 1, 1])
718
+ x = np.array([1, 0, 0])
719
+ A = np.diag([2, 3, 4])
720
+
721
+ x, info = gmres(A, b, x0=x, M=M, rtol=1e-15, atol=0)
722
+
723
+ # Should not return nans, nor terminate with false success
724
+ assert not np.isnan(x).any()
725
+ if info == 0:
726
+ assert np.linalg.norm(A @ x - b) <= 1e-15 * np.linalg.norm(b)
727
+
728
+ # The solution should be OK outside null space of M
729
+ assert_allclose(M @ (A @ x), M @ b)
730
+
731
+ def test_defective_matrix_breakdown(self):
732
+ # Breakdown due to defective matrix
733
+ A = np.array([[0, 1, 0], [1, 0, 0], [0, 0, 0]])
734
+ b = np.array([1, 0, 1])
735
+ rtol = 1e-8
736
+ x, info = gmres(A, b, rtol=rtol, atol=0)
737
+
738
+ # Should not return nans, nor terminate with false success
739
+ assert not np.isnan(x).any()
740
+ if info == 0:
741
+ assert np.linalg.norm(A @ x - b) <= rtol * np.linalg.norm(b)
742
+
743
+ # The solution should be OK outside null space of A
744
+ assert_allclose(A @ (A @ x), A @ b)
745
+
746
+ @pytest.mark.filterwarnings(f"ignore:{CB_TYPE_FILTER}:DeprecationWarning")
747
+ def test_callback_type(self):
748
+ # The legacy callback type changes meaning of 'maxiter'
749
+ np.random.seed(1)
750
+ A = np.random.rand(20, 20)
751
+ b = np.random.rand(20)
752
+
753
+ cb_count = [0]
754
+
755
+ def pr_norm_cb(r):
756
+ cb_count[0] += 1
757
+ assert isinstance(r, float)
758
+
759
+ def x_cb(x):
760
+ cb_count[0] += 1
761
+ assert isinstance(x, np.ndarray)
762
+
763
+ # 2 iterations is not enough to solve the problem
764
+ cb_count = [0]
765
+ x, info = gmres(A, b, rtol=1e-6, atol=0, callback=pr_norm_cb,
766
+ maxiter=2, restart=50)
767
+ assert info == 2
768
+ assert cb_count[0] == 2
769
+
770
+ # With `callback_type` specified, no warning should be raised
771
+ cb_count = [0]
772
+ x, info = gmres(A, b, rtol=1e-6, atol=0, callback=pr_norm_cb,
773
+ maxiter=2, restart=50, callback_type='legacy')
774
+ assert info == 2
775
+ assert cb_count[0] == 2
776
+
777
+ # 2 restart cycles is enough to solve the problem
778
+ cb_count = [0]
779
+ x, info = gmres(A, b, rtol=1e-6, atol=0, callback=pr_norm_cb,
780
+ maxiter=2, restart=50, callback_type='pr_norm')
781
+ assert info == 0
782
+ assert cb_count[0] > 2
783
+
784
+ # 2 restart cycles is enough to solve the problem
785
+ cb_count = [0]
786
+ x, info = gmres(A, b, rtol=1e-6, atol=0, callback=x_cb, maxiter=2,
787
+ restart=50, callback_type='x')
788
+ assert info == 0
789
+ assert cb_count[0] == 1
790
+
791
+ def test_callback_x_monotonic(self):
792
+ # Check that callback_type='x' gives monotonic norm decrease
793
+ rng = np.random.RandomState(1)
794
+ A = rng.rand(20, 20) + np.eye(20)
795
+ b = rng.rand(20)
796
+
797
+ prev_r = [np.inf]
798
+ count = [0]
799
+
800
+ def x_cb(x):
801
+ r = np.linalg.norm(A @ x - b)
802
+ assert r <= prev_r[0]
803
+ prev_r[0] = r
804
+ count[0] += 1
805
+
806
+ x, info = gmres(A, b, rtol=1e-6, atol=0, callback=x_cb, maxiter=20,
807
+ restart=10, callback_type='x')
808
+ assert info == 20
809
+ assert count[0] == 20
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_lgmres.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for the linalg._isolve.lgmres module
2
+ """
3
+
4
+ import threading
5
+ from numpy.testing import (assert_, assert_allclose, assert_equal,
6
+ suppress_warnings)
7
+
8
+ import pytest
9
+ from platform import python_implementation
10
+
11
+ import numpy as np
12
+ from numpy import zeros, array, allclose
13
+ from scipy.linalg import norm
14
+ from scipy.sparse import csr_array, eye_array, random_array
15
+
16
+ from scipy.sparse.linalg._interface import LinearOperator
17
+ from scipy.sparse.linalg import splu
18
+ from scipy.sparse.linalg._isolve import lgmres, gmres
19
+
20
+
21
+ Am = csr_array(array([[-2, 1, 0, 0, 0, 9],
22
+ [1, -2, 1, 0, 5, 0],
23
+ [0, 1, -2, 1, 0, 0],
24
+ [0, 0, 1, -2, 1, 0],
25
+ [0, 3, 0, 1, -2, 1],
26
+ [1, 0, 0, 0, 1, -2]]))
27
+ b = array([1, 2, 3, 4, 5, 6])
28
+ count = threading.local() # [0]
29
+ niter = threading.local() # [0]
30
+
31
+
32
+ def matvec(v):
33
+ if not hasattr(count, 'c'):
34
+ count.c = [0]
35
+ count.c[0] += 1
36
+ return Am@v
37
+
38
+
39
+ def cb(v):
40
+ if not hasattr(niter, 'n'):
41
+ niter.n = [0]
42
+ niter.n[0] += 1
43
+
44
+
45
+ A = LinearOperator(matvec=matvec, shape=Am.shape, dtype=Am.dtype)
46
+
47
+
48
+ def do_solve(**kw):
49
+ if not hasattr(niter, 'n'):
50
+ niter.n = [0]
51
+ if not hasattr(count, 'c'):
52
+ count.c = [0]
53
+ count.c[0] = 0
54
+ with suppress_warnings() as sup:
55
+ sup.filter(DeprecationWarning, ".*called without specifying.*")
56
+ x0, flag = lgmres(A, b, x0=zeros(A.shape[0]),
57
+ inner_m=6, rtol=1e-14, **kw)
58
+ count_0 = count.c[0]
59
+ assert_(allclose(A@x0, b, rtol=1e-12, atol=1e-12), norm(A@x0-b))
60
+ return x0, count_0
61
+
62
+
63
+ class TestLGMRES:
64
+ def test_preconditioner(self):
65
+ # Check that preconditioning works
66
+ pc = splu(Am.tocsc())
67
+ M = LinearOperator(matvec=pc.solve, shape=A.shape, dtype=A.dtype)
68
+
69
+ x0, count_0 = do_solve()
70
+ niter.n[0] = 0
71
+ x1, count_1 = do_solve(M=M, callback=cb)
72
+
73
+ assert count_1 == 3
74
+ assert count_1 < count_0/2
75
+ assert allclose(x1, x0, rtol=1e-14)
76
+ assert niter.n[0] < 3
77
+
78
+ def test_outer_v(self):
79
+ # Check that the augmentation vectors behave as expected
80
+
81
+ outer_v = []
82
+ x0, count_0 = do_solve(outer_k=6, outer_v=outer_v)
83
+ assert_(len(outer_v) > 0)
84
+ assert_(len(outer_v) <= 6)
85
+
86
+ x1, count_1 = do_solve(outer_k=6, outer_v=outer_v,
87
+ prepend_outer_v=True)
88
+ assert_(count_1 == 2, count_1)
89
+ assert_(count_1 < count_0/2)
90
+ assert_(allclose(x1, x0, rtol=1e-14))
91
+
92
+ # ---
93
+
94
+ outer_v = []
95
+ x0, count_0 = do_solve(outer_k=6, outer_v=outer_v,
96
+ store_outer_Av=False)
97
+ assert_(array([v[1] is None for v in outer_v]).all())
98
+ assert_(len(outer_v) > 0)
99
+ assert_(len(outer_v) <= 6)
100
+
101
+ x1, count_1 = do_solve(outer_k=6, outer_v=outer_v,
102
+ prepend_outer_v=True)
103
+ assert_(count_1 == 3, count_1)
104
+ assert_(count_1 < count_0/2)
105
+ assert_(allclose(x1, x0, rtol=1e-14))
106
+
107
+ @pytest.mark.skipif(python_implementation() == 'PyPy',
108
+ reason="Fails on PyPy CI runs. See #9507")
109
+ def test_arnoldi(self):
110
+ rng = np.random.default_rng(123)
111
+
112
+ A = eye_array(2000) + random_array((2000, 2000), density=5e-4, rng=rng)
113
+ b = rng.random(2000)
114
+
115
+ # The inner arnoldi should be equivalent to gmres
116
+ with suppress_warnings() as sup:
117
+ sup.filter(DeprecationWarning, ".*called without specifying.*")
118
+ x0, flag0 = lgmres(A, b, x0=zeros(A.shape[0]), inner_m=10, maxiter=1)
119
+ x1, flag1 = gmres(A, b, x0=zeros(A.shape[0]), restart=10, maxiter=1)
120
+
121
+ assert_equal(flag0, 1)
122
+ assert_equal(flag1, 1)
123
+ norm = np.linalg.norm(A.dot(x0) - b)
124
+ assert_(norm > 1e-4)
125
+ assert_allclose(x0, x1)
126
+
127
+ def test_cornercase(self):
128
+ rng = np.random.RandomState(1234)
129
+
130
+ # Rounding error may prevent convergence with tol=0 --- ensure
131
+ # that the return values in this case are correct, and no
132
+ # exceptions are raised
133
+
134
+ for n in [3, 5, 10, 100]:
135
+ A = 2*eye_array(n)
136
+
137
+ with suppress_warnings() as sup:
138
+ sup.filter(DeprecationWarning, ".*called without specifying.*")
139
+
140
+ b = np.ones(n)
141
+ x, info = lgmres(A, b, maxiter=10)
142
+ assert_equal(info, 0)
143
+ assert_allclose(A.dot(x) - b, 0, atol=1e-14)
144
+
145
+ x, info = lgmres(A, b, rtol=0, maxiter=10)
146
+ if info == 0:
147
+ assert_allclose(A.dot(x) - b, 0, atol=1e-14)
148
+
149
+ b = rng.rand(n)
150
+ x, info = lgmres(A, b, maxiter=10)
151
+ assert_equal(info, 0)
152
+ assert_allclose(A.dot(x) - b, 0, atol=1e-14)
153
+
154
+ x, info = lgmres(A, b, rtol=0, maxiter=10)
155
+ if info == 0:
156
+ assert_allclose(A.dot(x) - b, 0, atol=1e-14)
157
+
158
+ def test_nans(self):
159
+ A = eye_array(3, format='lil')
160
+ A[1, 1] = np.nan
161
+ b = np.ones(3)
162
+
163
+ with suppress_warnings() as sup:
164
+ sup.filter(DeprecationWarning, ".*called without specifying.*")
165
+ x, info = lgmres(A, b, rtol=0, maxiter=10)
166
+ assert_equal(info, 1)
167
+
168
+ def test_breakdown_with_outer_v(self):
169
+ A = np.array([[1, 2], [3, 4]], dtype=float)
170
+ b = np.array([1, 2])
171
+
172
+ x = np.linalg.solve(A, b)
173
+ v0 = np.array([1, 0])
174
+
175
+ # The inner iteration should converge to the correct solution,
176
+ # since it's in the outer vector list
177
+ with suppress_warnings() as sup:
178
+ sup.filter(DeprecationWarning, ".*called without specifying.*")
179
+ xp, info = lgmres(A, b, outer_v=[(v0, None), (x, None)], maxiter=1)
180
+
181
+ assert_allclose(xp, x, atol=1e-12)
182
+
183
+ def test_breakdown_underdetermined(self):
184
+ # Should find LSQ solution in the Krylov span in one inner
185
+ # iteration, despite solver breakdown from nilpotent A.
186
+ A = np.array([[0, 1, 1, 1],
187
+ [0, 0, 1, 1],
188
+ [0, 0, 0, 1],
189
+ [0, 0, 0, 0]], dtype=float)
190
+
191
+ bs = [
192
+ np.array([1, 1, 1, 1]),
193
+ np.array([1, 1, 1, 0]),
194
+ np.array([1, 1, 0, 0]),
195
+ np.array([1, 0, 0, 0]),
196
+ ]
197
+
198
+ for b in bs:
199
+ with suppress_warnings() as sup:
200
+ sup.filter(DeprecationWarning, ".*called without specifying.*")
201
+ xp, info = lgmres(A, b, maxiter=1)
202
+ resp = np.linalg.norm(A.dot(xp) - b)
203
+
204
+ K = np.c_[b, A.dot(b), A.dot(A.dot(b)), A.dot(A.dot(A.dot(b)))]
205
+ y, _, _, _ = np.linalg.lstsq(A.dot(K), b, rcond=-1)
206
+ x = K.dot(y)
207
+ res = np.linalg.norm(A.dot(x) - b)
208
+
209
+ assert_allclose(resp, res, err_msg=repr(b))
210
+
211
+ def test_denormals(self):
212
+ # Check that no warnings are emitted if the matrix contains
213
+ # numbers for which 1/x has no float representation, and that
214
+ # the solver behaves properly.
215
+ A = np.array([[1, 2], [3, 4]], dtype=float)
216
+ A *= 100 * np.nextafter(0, 1)
217
+
218
+ b = np.array([1, 1])
219
+
220
+ with suppress_warnings() as sup:
221
+ sup.filter(DeprecationWarning, ".*called without specifying.*")
222
+ xp, info = lgmres(A, b)
223
+
224
+ if info == 0:
225
+ assert_allclose(A.dot(xp), b)
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_lsmr.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copyright (C) 2010 David Fong and Michael Saunders
3
+ Distributed under the same license as SciPy
4
+
5
+ Testing Code for LSMR.
6
+
7
+ 03 Jun 2010: First version release with lsmr.py
8
+
9
+ David Chin-lung Fong clfong@stanford.edu
10
+ Institute for Computational and Mathematical Engineering
11
+ Stanford University
12
+
13
+ Michael Saunders saunders@stanford.edu
14
+ Systems Optimization Laboratory
15
+ Dept of MS&E, Stanford University.
16
+
17
+ """
18
+
19
+ from numpy import array, arange, eye, zeros, ones, transpose, hstack
20
+ from numpy.linalg import norm
21
+ from numpy.testing import assert_allclose
22
+ import pytest
23
+ from scipy.sparse import coo_array
24
+ from scipy.sparse.linalg._interface import aslinearoperator
25
+ from scipy.sparse.linalg import lsmr
26
+ from .test_lsqr import G, b
27
+
28
+
29
+ class TestLSMR:
30
+ def setup_method(self):
31
+ self.n = 10
32
+ self.m = 10
33
+
34
+ def assertCompatibleSystem(self, A, xtrue):
35
+ Afun = aslinearoperator(A)
36
+ b = Afun.matvec(xtrue)
37
+ x = lsmr(A, b)[0]
38
+ assert norm(x - xtrue) == pytest.approx(0, abs=1e-5)
39
+
40
+ def testIdentityACase1(self):
41
+ A = eye(self.n)
42
+ xtrue = zeros((self.n, 1))
43
+ self.assertCompatibleSystem(A, xtrue)
44
+
45
+ def testIdentityACase2(self):
46
+ A = eye(self.n)
47
+ xtrue = ones((self.n,1))
48
+ self.assertCompatibleSystem(A, xtrue)
49
+
50
+ def testIdentityACase3(self):
51
+ A = eye(self.n)
52
+ xtrue = transpose(arange(self.n,0,-1))
53
+ self.assertCompatibleSystem(A, xtrue)
54
+
55
+ def testBidiagonalA(self):
56
+ A = lowerBidiagonalMatrix(20,self.n)
57
+ xtrue = transpose(arange(self.n,0,-1))
58
+ self.assertCompatibleSystem(A,xtrue)
59
+
60
+ def testScalarB(self):
61
+ A = array([[1.0, 2.0]])
62
+ b = 3.0
63
+ x = lsmr(A, b)[0]
64
+ assert norm(A.dot(x) - b) == pytest.approx(0)
65
+
66
+ def testComplexX(self):
67
+ A = eye(self.n)
68
+ xtrue = transpose(arange(self.n, 0, -1) * (1 + 1j))
69
+ self.assertCompatibleSystem(A, xtrue)
70
+
71
+ def testComplexX0(self):
72
+ A = 4 * eye(self.n) + ones((self.n, self.n))
73
+ xtrue = transpose(arange(self.n, 0, -1))
74
+ b = aslinearoperator(A).matvec(xtrue)
75
+ x0 = zeros(self.n, dtype=complex)
76
+ x = lsmr(A, b, x0=x0)[0]
77
+ assert norm(x - xtrue) == pytest.approx(0, abs=1e-5)
78
+
79
+ def testComplexA(self):
80
+ A = 4 * eye(self.n) + 1j * ones((self.n, self.n))
81
+ xtrue = transpose(arange(self.n, 0, -1).astype(complex))
82
+ self.assertCompatibleSystem(A, xtrue)
83
+
84
+ def testComplexB(self):
85
+ A = 4 * eye(self.n) + ones((self.n, self.n))
86
+ xtrue = transpose(arange(self.n, 0, -1) * (1 + 1j))
87
+ b = aslinearoperator(A).matvec(xtrue)
88
+ x = lsmr(A, b)[0]
89
+ assert norm(x - xtrue) == pytest.approx(0, abs=1e-5)
90
+
91
+ def testColumnB(self):
92
+ A = eye(self.n)
93
+ b = ones((self.n, 1))
94
+ x = lsmr(A, b)[0]
95
+ assert norm(A.dot(x) - b.ravel()) == pytest.approx(0)
96
+
97
+ def testInitialization(self):
98
+ # Test that the default setting is not modified
99
+ x_ref, _, itn_ref, normr_ref, *_ = lsmr(G, b)
100
+ assert_allclose(norm(b - G@x_ref), normr_ref, atol=1e-6)
101
+
102
+ # Test passing zeros yields similar result
103
+ x0 = zeros(b.shape)
104
+ x = lsmr(G, b, x0=x0)[0]
105
+ assert_allclose(x, x_ref)
106
+
107
+ # Test warm-start with single iteration
108
+ x0 = lsmr(G, b, maxiter=1)[0]
109
+
110
+ x, _, itn, normr, *_ = lsmr(G, b, x0=x0)
111
+ assert_allclose(norm(b - G@x), normr, atol=1e-6)
112
+
113
+ # NOTE(gh-12139): This doesn't always converge to the same value as
114
+ # ref because error estimates will be slightly different when calculated
115
+ # from zeros vs x0 as a result only compare norm and itn (not x).
116
+
117
+ # x generally converges 1 iteration faster because it started at x0.
118
+ # itn == itn_ref means that lsmr(x0) took an extra iteration see above.
119
+ # -1 is technically possible but is rare (1 in 100000) so it's more
120
+ # likely to be an error elsewhere.
121
+ assert itn - itn_ref in (0, 1)
122
+
123
+ # If an extra iteration is performed normr may be 0, while normr_ref
124
+ # may be much larger.
125
+ assert normr < normr_ref * (1 + 1e-6)
126
+
127
+
128
+ class TestLSMRReturns:
129
+ def setup_method(self):
130
+ self.n = 10
131
+ self.A = lowerBidiagonalMatrix(20, self.n)
132
+ self.xtrue = transpose(arange(self.n, 0, -1))
133
+ self.Afun = aslinearoperator(self.A)
134
+ self.b = self.Afun.matvec(self.xtrue)
135
+ self.x0 = ones(self.n)
136
+ self.x00 = self.x0.copy()
137
+ self.returnValues = lsmr(self.A, self.b)
138
+ self.returnValuesX0 = lsmr(self.A, self.b, x0=self.x0)
139
+
140
+ def test_unchanged_x0(self):
141
+ x, istop, itn, normr, normar, normA, condA, normx = self.returnValuesX0
142
+ assert_allclose(self.x00, self.x0)
143
+
144
+ def testNormr(self):
145
+ x, istop, itn, normr, normar, normA, condA, normx = self.returnValues
146
+ assert norm(self.b - self.Afun.matvec(x)) == pytest.approx(normr)
147
+
148
+ def testNormar(self):
149
+ x, istop, itn, normr, normar, normA, condA, normx = self.returnValues
150
+ assert (norm(self.Afun.rmatvec(self.b - self.Afun.matvec(x)))
151
+ == pytest.approx(normar))
152
+
153
+ def testNormx(self):
154
+ x, istop, itn, normr, normar, normA, condA, normx = self.returnValues
155
+ assert norm(x) == pytest.approx(normx)
156
+
157
+
158
+ def lowerBidiagonalMatrix(m, n):
159
+ # This is a simple example for testing LSMR.
160
+ # It uses the leading m*n submatrix from
161
+ # A = [ 1
162
+ # 1 2
163
+ # 2 3
164
+ # 3 4
165
+ # ...
166
+ # n ]
167
+ # suitably padded by zeros.
168
+ #
169
+ # 04 Jun 2010: First version for distribution with lsmr.py
170
+ if m <= n:
171
+ row = hstack((arange(m, dtype=int),
172
+ arange(1, m, dtype=int)))
173
+ col = hstack((arange(m, dtype=int),
174
+ arange(m-1, dtype=int)))
175
+ data = hstack((arange(1, m+1, dtype=float),
176
+ arange(1,m, dtype=float)))
177
+ return coo_array((data, (row, col)), shape=(m,n))
178
+ else:
179
+ row = hstack((arange(n, dtype=int),
180
+ arange(1, n+1, dtype=int)))
181
+ col = hstack((arange(n, dtype=int),
182
+ arange(n, dtype=int)))
183
+ data = hstack((arange(1, n+1, dtype=float),
184
+ arange(1,n+1, dtype=float)))
185
+ return coo_array((data,(row, col)), shape=(m,n))
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_lsqr.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from numpy.testing import assert_allclose, assert_array_equal, assert_equal
3
+ import pytest
4
+ import scipy.sparse
5
+ import scipy.sparse.linalg
6
+ from scipy.sparse.linalg import lsqr
7
+
8
+ # Set up a test problem
9
+ n = 35
10
+ G = np.eye(n)
11
+ normal = np.random.normal
12
+ norm = np.linalg.norm
13
+
14
+ for jj in range(5):
15
+ gg = normal(size=n)
16
+ hh = gg * gg.T
17
+ G += (hh + hh.T) * 0.5
18
+ G += normal(size=n) * normal(size=n)
19
+
20
+ b = normal(size=n)
21
+
22
+ # tolerance for atol/btol keywords of lsqr()
23
+ tol = 2e-10
24
+ # tolerances for testing the results of the lsqr() call with assert_allclose
25
+ # These tolerances are a bit fragile - see discussion in gh-15301.
26
+ atol_test = 4e-10
27
+ rtol_test = 2e-8
28
+ show = False
29
+ maxit = None
30
+
31
+
32
+ def test_lsqr_basic():
33
+ b_copy = b.copy()
34
+ xo, *_ = lsqr(G, b, show=show, atol=tol, btol=tol, iter_lim=maxit)
35
+ assert_array_equal(b_copy, b)
36
+
37
+ svx = np.linalg.solve(G, b)
38
+ assert_allclose(xo, svx, atol=atol_test, rtol=rtol_test)
39
+
40
+ # Now the same but with damp > 0.
41
+ # This is equivalent to solving the extended system:
42
+ # ( G ) @ x = ( b )
43
+ # ( damp*I ) ( 0 )
44
+ damp = 1.5
45
+ xo, *_ = lsqr(
46
+ G, b, damp=damp, show=show, atol=tol, btol=tol, iter_lim=maxit)
47
+
48
+ Gext = np.r_[G, damp * np.eye(G.shape[1])]
49
+ bext = np.r_[b, np.zeros(G.shape[1])]
50
+ svx, *_ = np.linalg.lstsq(Gext, bext, rcond=None)
51
+ assert_allclose(xo, svx, atol=atol_test, rtol=rtol_test)
52
+
53
+
54
+ def test_gh_2466():
55
+ row = np.array([0, 0])
56
+ col = np.array([0, 1])
57
+ val = np.array([1, -1])
58
+ A = scipy.sparse.coo_array((val, (row, col)), shape=(1, 2))
59
+ b = np.asarray([4])
60
+ lsqr(A, b)
61
+
62
+
63
+ def test_well_conditioned_problems():
64
+ # Test that sparse the lsqr solver returns the right solution
65
+ # on various problems with different random seeds.
66
+ # This is a non-regression test for a potential ZeroDivisionError
67
+ # raised when computing the `test2` & `test3` convergence conditions.
68
+ n = 10
69
+ A_sparse = scipy.sparse.eye_array(n, n)
70
+ A_dense = A_sparse.toarray()
71
+
72
+ with np.errstate(invalid='raise'):
73
+ for seed in range(30):
74
+ rng = np.random.RandomState(seed + 10)
75
+ beta = rng.rand(n)
76
+ beta[beta == 0] = 0.00001 # ensure that all the betas are not null
77
+ b = A_sparse @ beta[:, np.newaxis]
78
+ output = lsqr(A_sparse, b, show=show)
79
+
80
+ # Check that the termination condition corresponds to an approximate
81
+ # solution to Ax = b
82
+ assert_equal(output[1], 1)
83
+ solution = output[0]
84
+
85
+ # Check that we recover the ground truth solution
86
+ assert_allclose(solution, beta)
87
+
88
+ # Sanity check: compare to the dense array solver
89
+ reference_solution = np.linalg.solve(A_dense, b).ravel()
90
+ assert_allclose(solution, reference_solution)
91
+
92
+
93
+ def test_b_shapes():
94
+ # Test b being a scalar.
95
+ A = np.array([[1.0, 2.0]])
96
+ b = 3.0
97
+ x = lsqr(A, b)[0]
98
+ assert norm(A.dot(x) - b) == pytest.approx(0)
99
+
100
+ # Test b being a column vector.
101
+ A = np.eye(10)
102
+ b = np.ones((10, 1))
103
+ x = lsqr(A, b)[0]
104
+ assert norm(A.dot(x) - b.ravel()) == pytest.approx(0)
105
+
106
+
107
+ def test_initialization():
108
+ # Test the default setting is the same as zeros
109
+ b_copy = b.copy()
110
+ x_ref = lsqr(G, b, show=show, atol=tol, btol=tol, iter_lim=maxit)
111
+ x0 = np.zeros(x_ref[0].shape)
112
+ x = lsqr(G, b, show=show, atol=tol, btol=tol, iter_lim=maxit, x0=x0)
113
+ assert_array_equal(b_copy, b)
114
+ assert_allclose(x_ref[0], x[0])
115
+
116
+ # Test warm-start with single iteration
117
+ x0 = lsqr(G, b, show=show, atol=tol, btol=tol, iter_lim=1)[0]
118
+ x = lsqr(G, b, show=show, atol=tol, btol=tol, iter_lim=maxit, x0=x0)
119
+ assert_allclose(x_ref[0], x[0])
120
+ assert_array_equal(b_copy, b)
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_minres.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from numpy.linalg import norm
3
+ from numpy.testing import assert_equal, assert_allclose, assert_
4
+ from scipy.sparse.linalg._isolve import minres
5
+
6
+ from pytest import raises as assert_raises
7
+
8
+
9
+ def get_sample_problem():
10
+ # A random 10 x 10 symmetric matrix
11
+ rng = np.random.RandomState(1234)
12
+ matrix = rng.rand(10, 10)
13
+ matrix = matrix + matrix.T
14
+ # A random vector of length 10
15
+ vector = rng.rand(10)
16
+ return matrix, vector
17
+
18
+
19
+ def test_singular():
20
+ A, b = get_sample_problem()
21
+ A[0, ] = 0
22
+ b[0] = 0
23
+ xp, info = minres(A, b)
24
+ assert_equal(info, 0)
25
+ assert norm(A @ xp - b) <= 1e-5 * norm(b)
26
+
27
+
28
+ def test_x0_is_used_by():
29
+ A, b = get_sample_problem()
30
+ # Random x0 to feed minres
31
+ rng = np.random.RandomState(12345)
32
+ x0 = rng.rand(10)
33
+ trace = []
34
+
35
+ def trace_iterates(xk):
36
+ trace.append(xk)
37
+ minres(A, b, x0=x0, callback=trace_iterates)
38
+ trace_with_x0 = trace
39
+
40
+ trace = []
41
+ minres(A, b, callback=trace_iterates)
42
+ assert_(not np.array_equal(trace_with_x0[0], trace[0]))
43
+
44
+
45
+ def test_shift():
46
+ A, b = get_sample_problem()
47
+ shift = 0.5
48
+ shifted_A = A - shift * np.eye(10)
49
+ x1, info1 = minres(A, b, shift=shift)
50
+ x2, info2 = minres(shifted_A, b)
51
+ assert_equal(info1, 0)
52
+ assert_allclose(x1, x2, rtol=1e-5)
53
+
54
+
55
+ def test_asymmetric_fail():
56
+ """Asymmetric matrix should raise `ValueError` when check=True"""
57
+ A, b = get_sample_problem()
58
+ A[1, 2] = 1
59
+ A[2, 1] = 2
60
+ with assert_raises(ValueError):
61
+ xp, info = minres(A, b, check=True)
62
+
63
+
64
+ def test_minres_non_default_x0():
65
+ rng = np.random.RandomState(1234)
66
+ rtol = 1e-6
67
+ a = rng.randn(5, 5)
68
+ a = np.dot(a, a.T)
69
+ b = rng.randn(5)
70
+ c = rng.randn(5)
71
+ x = minres(a, b, x0=c, rtol=rtol)[0]
72
+ assert norm(a @ x - b) <= rtol * norm(b)
73
+
74
+
75
+ def test_minres_precond_non_default_x0():
76
+ rng = np.random.RandomState(12345)
77
+ rtol = 1e-6
78
+ a = rng.randn(5, 5)
79
+ a = np.dot(a, a.T)
80
+ b = rng.randn(5)
81
+ c = rng.randn(5)
82
+ m = rng.randn(5, 5)
83
+ m = np.dot(m, m.T)
84
+ x = minres(a, b, M=m, x0=c, rtol=rtol)[0]
85
+ assert norm(a @ x - b) <= rtol * norm(b)
86
+
87
+
88
+ def test_minres_precond_exact_x0():
89
+ rng = np.random.RandomState(1234)
90
+ rtol = 1e-6
91
+ a = np.eye(10)
92
+ b = np.ones(10)
93
+ c = np.ones(10)
94
+ m = rng.randn(10, 10)
95
+ m = np.dot(m, m.T)
96
+ x = minres(a, b, M=m, x0=c, rtol=rtol)[0]
97
+ assert norm(a @ x - b) <= rtol * norm(b)
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_utils.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from pytest import raises as assert_raises
3
+
4
+ import scipy.sparse.linalg._isolve.utils as utils
5
+
6
+
7
+ def test_make_system_bad_shape():
8
+ assert_raises(ValueError,
9
+ utils.make_system, np.zeros((5,3)), None, np.zeros(4), np.zeros(4))
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tfqmr.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from .iterative import _get_atol_rtol
3
+ from .utils import make_system
4
+
5
+
6
+ __all__ = ['tfqmr']
7
+
8
+
9
+ def tfqmr(A, b, x0=None, *, rtol=1e-5, atol=0., maxiter=None, M=None,
10
+ callback=None, show=False):
11
+ """
12
+ Use Transpose-Free Quasi-Minimal Residual iteration to solve ``Ax = b``.
13
+
14
+ Parameters
15
+ ----------
16
+ A : {sparse array, ndarray, LinearOperator}
17
+ The real or complex N-by-N matrix of the linear system.
18
+ Alternatively, `A` can be a linear operator which can
19
+ produce ``Ax`` using, e.g.,
20
+ `scipy.sparse.linalg.LinearOperator`.
21
+ b : {ndarray}
22
+ Right hand side of the linear system. Has shape (N,) or (N,1).
23
+ x0 : {ndarray}
24
+ Starting guess for the solution.
25
+ rtol, atol : float, optional
26
+ Parameters for the convergence test. For convergence,
27
+ ``norm(b - A @ x) <= max(rtol*norm(b), atol)`` should be satisfied.
28
+ The default is ``rtol=1e-5``, the default for ``atol`` is ``0.0``.
29
+ maxiter : int, optional
30
+ Maximum number of iterations. Iteration will stop after maxiter
31
+ steps even if the specified tolerance has not been achieved.
32
+ Default is ``min(10000, ndofs * 10)``, where ``ndofs = A.shape[0]``.
33
+ M : {sparse array, ndarray, LinearOperator}
34
+ Inverse of the preconditioner of A. M should approximate the
35
+ inverse of A and be easy to solve for (see Notes). Effective
36
+ preconditioning dramatically improves the rate of convergence,
37
+ which implies that fewer iterations are needed to reach a given
38
+ error tolerance. By default, no preconditioner is used.
39
+ callback : function, optional
40
+ User-supplied function to call after each iteration. It is called
41
+ as ``callback(xk)``, where ``xk`` is the current solution vector.
42
+ show : bool, optional
43
+ Specify ``show = True`` to show the convergence, ``show = False`` is
44
+ to close the output of the convergence.
45
+ Default is `False`.
46
+
47
+ Returns
48
+ -------
49
+ x : ndarray
50
+ The converged solution.
51
+ info : int
52
+ Provides convergence information:
53
+
54
+ - 0 : successful exit
55
+ - >0 : convergence to tolerance not achieved, number of iterations
56
+ - <0 : illegal input or breakdown
57
+
58
+ Notes
59
+ -----
60
+ The Transpose-Free QMR algorithm is derived from the CGS algorithm.
61
+ However, unlike CGS, the convergence curves for the TFQMR method is
62
+ smoothed by computing a quasi minimization of the residual norm. The
63
+ implementation supports left preconditioner, and the "residual norm"
64
+ to compute in convergence criterion is actually an upper bound on the
65
+ actual residual norm ``||b - Axk||``.
66
+
67
+ References
68
+ ----------
69
+ .. [1] R. W. Freund, A Transpose-Free Quasi-Minimal Residual Algorithm for
70
+ Non-Hermitian Linear Systems, SIAM J. Sci. Comput., 14(2), 470-482,
71
+ 1993.
72
+ .. [2] Y. Saad, Iterative Methods for Sparse Linear Systems, 2nd edition,
73
+ SIAM, Philadelphia, 2003.
74
+ .. [3] C. T. Kelley, Iterative Methods for Linear and Nonlinear Equations,
75
+ number 16 in Frontiers in Applied Mathematics, SIAM, Philadelphia,
76
+ 1995.
77
+
78
+ Examples
79
+ --------
80
+ >>> import numpy as np
81
+ >>> from scipy.sparse import csc_array
82
+ >>> from scipy.sparse.linalg import tfqmr
83
+ >>> A = csc_array([[3, 2, 0], [1, -1, 0], [0, 5, 1]], dtype=float)
84
+ >>> b = np.array([2, 4, -1], dtype=float)
85
+ >>> x, exitCode = tfqmr(A, b, atol=0.0)
86
+ >>> print(exitCode) # 0 indicates successful convergence
87
+ 0
88
+ >>> np.allclose(A.dot(x), b)
89
+ True
90
+ """
91
+
92
+ # Check data type
93
+ dtype = A.dtype
94
+ if np.issubdtype(dtype, np.int64):
95
+ dtype = float
96
+ A = A.astype(dtype)
97
+ if np.issubdtype(b.dtype, np.int64):
98
+ b = b.astype(dtype)
99
+
100
+ A, M, x, b, postprocess = make_system(A, M, x0, b)
101
+
102
+ # Check if the R.H.S is a zero vector
103
+ if np.linalg.norm(b) == 0.:
104
+ x = b.copy()
105
+ return (postprocess(x), 0)
106
+
107
+ ndofs = A.shape[0]
108
+ if maxiter is None:
109
+ maxiter = min(10000, ndofs * 10)
110
+
111
+ if x0 is None:
112
+ r = b.copy()
113
+ else:
114
+ r = b - A.matvec(x)
115
+ u = r
116
+ w = r.copy()
117
+ # Take rstar as b - Ax0, that is rstar := r = b - Ax0 mathematically
118
+ rstar = r
119
+ v = M.matvec(A.matvec(r))
120
+ uhat = v
121
+ d = theta = eta = 0.
122
+ # at this point we know rstar == r, so rho is always real
123
+ rho = np.inner(rstar.conjugate(), r).real
124
+ rhoLast = rho
125
+ r0norm = np.sqrt(rho)
126
+ tau = r0norm
127
+ if r0norm == 0:
128
+ return (postprocess(x), 0)
129
+
130
+ # we call this to get the right atol and raise errors as necessary
131
+ atol, _ = _get_atol_rtol('tfqmr', r0norm, atol, rtol)
132
+
133
+ for iter in range(maxiter):
134
+ even = iter % 2 == 0
135
+ if (even):
136
+ vtrstar = np.inner(rstar.conjugate(), v)
137
+ # Check breakdown
138
+ if vtrstar == 0.:
139
+ return (postprocess(x), -1)
140
+ alpha = rho / vtrstar
141
+ uNext = u - alpha * v # [1]-(5.6)
142
+ w -= alpha * uhat # [1]-(5.8)
143
+ d = u + (theta**2 / alpha) * eta * d # [1]-(5.5)
144
+ # [1]-(5.2)
145
+ theta = np.linalg.norm(w) / tau
146
+ c = np.sqrt(1. / (1 + theta**2))
147
+ tau *= theta * c
148
+ # Calculate step and direction [1]-(5.4)
149
+ eta = (c**2) * alpha
150
+ z = M.matvec(d)
151
+ x += eta * z
152
+
153
+ if callback is not None:
154
+ callback(x)
155
+
156
+ # Convergence criterion
157
+ if tau * np.sqrt(iter+1) < atol:
158
+ if (show):
159
+ print("TFQMR: Linear solve converged due to reach TOL "
160
+ f"iterations {iter+1}")
161
+ return (postprocess(x), 0)
162
+
163
+ if (not even):
164
+ # [1]-(5.7)
165
+ rho = np.inner(rstar.conjugate(), w)
166
+ beta = rho / rhoLast
167
+ u = w + beta * u
168
+ v = beta * uhat + (beta**2) * v
169
+ uhat = M.matvec(A.matvec(u))
170
+ v += uhat
171
+ else:
172
+ uhat = M.matvec(A.matvec(uNext))
173
+ u = uNext
174
+ rhoLast = rho
175
+
176
+ if (show):
177
+ print("TFQMR: Linear solve not converged due to reach MAXIT "
178
+ f"iterations {iter+1}")
179
+ return (postprocess(x), maxiter)
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/utils.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __docformat__ = "restructuredtext en"
2
+
3
+ __all__ = []
4
+
5
+
6
+ from numpy import asanyarray, asarray, array, zeros
7
+
8
+ from scipy.sparse.linalg._interface import aslinearoperator, LinearOperator, \
9
+ IdentityOperator
10
+
11
+ _coerce_rules = {('f','f'):'f', ('f','d'):'d', ('f','F'):'F',
12
+ ('f','D'):'D', ('d','f'):'d', ('d','d'):'d',
13
+ ('d','F'):'D', ('d','D'):'D', ('F','f'):'F',
14
+ ('F','d'):'D', ('F','F'):'F', ('F','D'):'D',
15
+ ('D','f'):'D', ('D','d'):'D', ('D','F'):'D',
16
+ ('D','D'):'D'}
17
+
18
+
19
+ def coerce(x,y):
20
+ if x not in 'fdFD':
21
+ x = 'd'
22
+ if y not in 'fdFD':
23
+ y = 'd'
24
+ return _coerce_rules[x,y]
25
+
26
+
27
+ def id(x):
28
+ return x
29
+
30
+
31
+ def make_system(A, M, x0, b):
32
+ """Make a linear system Ax=b
33
+
34
+ Parameters
35
+ ----------
36
+ A : LinearOperator
37
+ sparse or dense matrix (or any valid input to aslinearoperator)
38
+ M : {LinearOperator, Nones}
39
+ preconditioner
40
+ sparse or dense matrix (or any valid input to aslinearoperator)
41
+ x0 : {array_like, str, None}
42
+ initial guess to iterative method.
43
+ ``x0 = 'Mb'`` means using the nonzero initial guess ``M @ b``.
44
+ Default is `None`, which means using the zero initial guess.
45
+ b : array_like
46
+ right hand side
47
+
48
+ Returns
49
+ -------
50
+ (A, M, x, b, postprocess)
51
+ A : LinearOperator
52
+ matrix of the linear system
53
+ M : LinearOperator
54
+ preconditioner
55
+ x : rank 1 ndarray
56
+ initial guess
57
+ b : rank 1 ndarray
58
+ right hand side
59
+ postprocess : function
60
+ converts the solution vector to the appropriate
61
+ type and dimensions (e.g. (N,1) matrix)
62
+
63
+ """
64
+ A_ = A
65
+ A = aslinearoperator(A)
66
+
67
+ if A.shape[0] != A.shape[1]:
68
+ raise ValueError(f'expected square matrix, but got shape={(A.shape,)}')
69
+
70
+ N = A.shape[0]
71
+
72
+ b = asanyarray(b)
73
+
74
+ if not (b.shape == (N,1) or b.shape == (N,)):
75
+ raise ValueError(f'shapes of A {A.shape} and b {b.shape} are '
76
+ 'incompatible')
77
+
78
+ if b.dtype.char not in 'fdFD':
79
+ b = b.astype('d') # upcast non-FP types to double
80
+
81
+ def postprocess(x):
82
+ return x
83
+
84
+ if hasattr(A,'dtype'):
85
+ xtype = A.dtype.char
86
+ else:
87
+ xtype = A.matvec(b).dtype.char
88
+ xtype = coerce(xtype, b.dtype.char)
89
+
90
+ b = asarray(b,dtype=xtype) # make b the same type as x
91
+ b = b.ravel()
92
+
93
+ # process preconditioner
94
+ if M is None:
95
+ if hasattr(A_,'psolve'):
96
+ psolve = A_.psolve
97
+ else:
98
+ psolve = id
99
+ if hasattr(A_,'rpsolve'):
100
+ rpsolve = A_.rpsolve
101
+ else:
102
+ rpsolve = id
103
+ if psolve is id and rpsolve is id:
104
+ M = IdentityOperator(shape=A.shape, dtype=A.dtype)
105
+ else:
106
+ M = LinearOperator(A.shape, matvec=psolve, rmatvec=rpsolve,
107
+ dtype=A.dtype)
108
+ else:
109
+ M = aslinearoperator(M)
110
+ if A.shape != M.shape:
111
+ raise ValueError('matrix and preconditioner have different shapes')
112
+
113
+ # set initial guess
114
+ if x0 is None:
115
+ x = zeros(N, dtype=xtype)
116
+ elif isinstance(x0, str):
117
+ if x0 == 'Mb': # use nonzero initial guess ``M @ b``
118
+ bCopy = b.copy()
119
+ x = M.matvec(bCopy)
120
+ else:
121
+ x = array(x0, dtype=xtype)
122
+ if not (x.shape == (N, 1) or x.shape == (N,)):
123
+ raise ValueError(f'shapes of A {A.shape} and '
124
+ f'x0 {x.shape} are incompatible')
125
+ x = x.ravel()
126
+
127
+ return A, M, x, b, postprocess
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_matfuncs.py ADDED
@@ -0,0 +1,940 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Sparse matrix functions
3
+ """
4
+
5
+ #
6
+ # Authors: Travis Oliphant, March 2002
7
+ # Anthony Scopatz, August 2012 (Sparse Updates)
8
+ # Jake Vanderplas, August 2012 (Sparse Updates)
9
+ #
10
+
11
+ __all__ = ['expm', 'inv', 'matrix_power']
12
+
13
+ import numpy as np
14
+ from scipy.linalg._basic import solve, solve_triangular
15
+
16
+ from scipy.sparse._base import issparse
17
+ from scipy.sparse.linalg import spsolve
18
+ from scipy.sparse._sputils import is_pydata_spmatrix, isintlike
19
+
20
+ import scipy.sparse
21
+ import scipy.sparse.linalg
22
+ from scipy.sparse.linalg._interface import LinearOperator
23
+ from scipy.sparse._construct import eye_array
24
+
25
+ from ._expm_multiply import _ident_like, _exact_1_norm as _onenorm
26
+
27
+
28
+ UPPER_TRIANGULAR = 'upper_triangular'
29
+
30
+
31
+ def inv(A):
32
+ """
33
+ Compute the inverse of a sparse arrays
34
+
35
+ Parameters
36
+ ----------
37
+ A : (M, M) sparse arrays
38
+ square matrix to be inverted
39
+
40
+ Returns
41
+ -------
42
+ Ainv : (M, M) sparse arrays
43
+ inverse of `A`
44
+
45
+ Notes
46
+ -----
47
+ This computes the sparse inverse of `A`. If the inverse of `A` is expected
48
+ to be non-sparse, it will likely be faster to convert `A` to dense and use
49
+ `scipy.linalg.inv`.
50
+
51
+ Examples
52
+ --------
53
+ >>> from scipy.sparse import csc_array
54
+ >>> from scipy.sparse.linalg import inv
55
+ >>> A = csc_array([[1., 0.], [1., 2.]])
56
+ >>> Ainv = inv(A)
57
+ >>> Ainv
58
+ <Compressed Sparse Column sparse array of dtype 'float64'
59
+ with 3 stored elements and shape (2, 2)>
60
+ >>> A.dot(Ainv)
61
+ <Compressed Sparse Column sparse array of dtype 'float64'
62
+ with 2 stored elements and shape (2, 2)>
63
+ >>> A.dot(Ainv).toarray()
64
+ array([[ 1., 0.],
65
+ [ 0., 1.]])
66
+
67
+ .. versionadded:: 0.12.0
68
+
69
+ """
70
+ # Check input
71
+ if not (issparse(A) or is_pydata_spmatrix(A)):
72
+ raise TypeError('Input must be a sparse arrays')
73
+
74
+ # Use sparse direct solver to solve "AX = I" accurately
75
+ I = _ident_like(A)
76
+ Ainv = spsolve(A, I)
77
+ return Ainv
78
+
79
+
80
+ def _onenorm_matrix_power_nnm(A, p):
81
+ """
82
+ Compute the 1-norm of a non-negative integer power of a non-negative matrix.
83
+
84
+ Parameters
85
+ ----------
86
+ A : a square ndarray or matrix or sparse arrays
87
+ Input matrix with non-negative entries.
88
+ p : non-negative integer
89
+ The power to which the matrix is to be raised.
90
+
91
+ Returns
92
+ -------
93
+ out : float
94
+ The 1-norm of the matrix power p of A.
95
+
96
+ """
97
+ # Check input
98
+ if int(p) != p or p < 0:
99
+ raise ValueError('expected non-negative integer p')
100
+ p = int(p)
101
+ if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
102
+ raise ValueError('expected A to be like a square matrix')
103
+
104
+ # Explicitly make a column vector so that this works when A is a
105
+ # numpy matrix (in addition to ndarray and sparse arrays).
106
+ v = np.ones((A.shape[0], 1), dtype=float)
107
+ M = A.T
108
+ for i in range(p):
109
+ v = M.dot(v)
110
+ return np.max(v)
111
+
112
+
113
+ def _is_upper_triangular(A):
114
+ # This function could possibly be of wider interest.
115
+ if issparse(A):
116
+ lower_part = scipy.sparse.tril(A, -1)
117
+ # Check structural upper triangularity,
118
+ # then coincidental upper triangularity if needed.
119
+ return lower_part.nnz == 0 or lower_part.count_nonzero() == 0
120
+ elif is_pydata_spmatrix(A):
121
+ import sparse
122
+ lower_part = sparse.tril(A, -1)
123
+ return lower_part.nnz == 0
124
+ else:
125
+ return not np.tril(A, -1).any()
126
+
127
+
128
+ def _smart_matrix_product(A, B, alpha=None, structure=None):
129
+ """
130
+ A matrix product that knows about sparse and structured matrices.
131
+
132
+ Parameters
133
+ ----------
134
+ A : 2d ndarray
135
+ First matrix.
136
+ B : 2d ndarray
137
+ Second matrix.
138
+ alpha : float
139
+ The matrix product will be scaled by this constant.
140
+ structure : str, optional
141
+ A string describing the structure of both matrices `A` and `B`.
142
+ Only `upper_triangular` is currently supported.
143
+
144
+ Returns
145
+ -------
146
+ M : 2d ndarray
147
+ Matrix product of A and B.
148
+
149
+ """
150
+ if len(A.shape) != 2:
151
+ raise ValueError('expected A to be a rectangular matrix')
152
+ if len(B.shape) != 2:
153
+ raise ValueError('expected B to be a rectangular matrix')
154
+ f = None
155
+ if structure == UPPER_TRIANGULAR:
156
+ if (not issparse(A) and not issparse(B)
157
+ and not is_pydata_spmatrix(A) and not is_pydata_spmatrix(B)):
158
+ f, = scipy.linalg.get_blas_funcs(('trmm',), (A, B))
159
+ if f is not None:
160
+ if alpha is None:
161
+ alpha = 1.
162
+ out = f(alpha, A, B)
163
+ else:
164
+ if alpha is None:
165
+ out = A.dot(B)
166
+ else:
167
+ out = alpha * A.dot(B)
168
+ return out
169
+
170
+
171
+ class MatrixPowerOperator(LinearOperator):
172
+
173
+ def __init__(self, A, p, structure=None):
174
+ if A.ndim != 2 or A.shape[0] != A.shape[1]:
175
+ raise ValueError('expected A to be like a square matrix')
176
+ if p < 0:
177
+ raise ValueError('expected p to be a non-negative integer')
178
+ self._A = A
179
+ self._p = p
180
+ self._structure = structure
181
+ self.dtype = A.dtype
182
+ self.ndim = A.ndim
183
+ self.shape = A.shape
184
+
185
+ def _matvec(self, x):
186
+ for i in range(self._p):
187
+ x = self._A.dot(x)
188
+ return x
189
+
190
+ def _rmatvec(self, x):
191
+ A_T = self._A.T
192
+ x = x.ravel()
193
+ for i in range(self._p):
194
+ x = A_T.dot(x)
195
+ return x
196
+
197
+ def _matmat(self, X):
198
+ for i in range(self._p):
199
+ X = _smart_matrix_product(self._A, X, structure=self._structure)
200
+ return X
201
+
202
+ @property
203
+ def T(self):
204
+ return MatrixPowerOperator(self._A.T, self._p)
205
+
206
+
207
+ class ProductOperator(LinearOperator):
208
+ """
209
+ For now, this is limited to products of multiple square matrices.
210
+ """
211
+
212
+ def __init__(self, *args, **kwargs):
213
+ self._structure = kwargs.get('structure', None)
214
+ for A in args:
215
+ if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
216
+ raise ValueError(
217
+ 'For now, the ProductOperator implementation is '
218
+ 'limited to the product of multiple square matrices.')
219
+ if args:
220
+ n = args[0].shape[0]
221
+ for A in args:
222
+ for d in A.shape:
223
+ if d != n:
224
+ raise ValueError(
225
+ 'The square matrices of the ProductOperator '
226
+ 'must all have the same shape.')
227
+ self.shape = (n, n)
228
+ self.ndim = len(self.shape)
229
+ self.dtype = np.result_type(*[x.dtype for x in args])
230
+ self._operator_sequence = args
231
+
232
+ def _matvec(self, x):
233
+ for A in reversed(self._operator_sequence):
234
+ x = A.dot(x)
235
+ return x
236
+
237
+ def _rmatvec(self, x):
238
+ x = x.ravel()
239
+ for A in self._operator_sequence:
240
+ x = A.T.dot(x)
241
+ return x
242
+
243
+ def _matmat(self, X):
244
+ for A in reversed(self._operator_sequence):
245
+ X = _smart_matrix_product(A, X, structure=self._structure)
246
+ return X
247
+
248
+ @property
249
+ def T(self):
250
+ T_args = [A.T for A in reversed(self._operator_sequence)]
251
+ return ProductOperator(*T_args)
252
+
253
+
254
+ def _onenormest_matrix_power(A, p,
255
+ t=2, itmax=5, compute_v=False, compute_w=False, structure=None):
256
+ """
257
+ Efficiently estimate the 1-norm of A^p.
258
+
259
+ Parameters
260
+ ----------
261
+ A : ndarray
262
+ Matrix whose 1-norm of a power is to be computed.
263
+ p : int
264
+ Non-negative integer power.
265
+ t : int, optional
266
+ A positive parameter controlling the tradeoff between
267
+ accuracy versus time and memory usage.
268
+ Larger values take longer and use more memory
269
+ but give more accurate output.
270
+ itmax : int, optional
271
+ Use at most this many iterations.
272
+ compute_v : bool, optional
273
+ Request a norm-maximizing linear operator input vector if True.
274
+ compute_w : bool, optional
275
+ Request a norm-maximizing linear operator output vector if True.
276
+
277
+ Returns
278
+ -------
279
+ est : float
280
+ An underestimate of the 1-norm of the sparse arrays.
281
+ v : ndarray, optional
282
+ The vector such that ||Av||_1 == est*||v||_1.
283
+ It can be thought of as an input to the linear operator
284
+ that gives an output with particularly large norm.
285
+ w : ndarray, optional
286
+ The vector Av which has relatively large 1-norm.
287
+ It can be thought of as an output of the linear operator
288
+ that is relatively large in norm compared to the input.
289
+
290
+ """
291
+ return scipy.sparse.linalg.onenormest(
292
+ MatrixPowerOperator(A, p, structure=structure))
293
+
294
+
295
+ def _onenormest_product(operator_seq,
296
+ t=2, itmax=5, compute_v=False, compute_w=False, structure=None):
297
+ """
298
+ Efficiently estimate the 1-norm of the matrix product of the args.
299
+
300
+ Parameters
301
+ ----------
302
+ operator_seq : linear operator sequence
303
+ Matrices whose 1-norm of product is to be computed.
304
+ t : int, optional
305
+ A positive parameter controlling the tradeoff between
306
+ accuracy versus time and memory usage.
307
+ Larger values take longer and use more memory
308
+ but give more accurate output.
309
+ itmax : int, optional
310
+ Use at most this many iterations.
311
+ compute_v : bool, optional
312
+ Request a norm-maximizing linear operator input vector if True.
313
+ compute_w : bool, optional
314
+ Request a norm-maximizing linear operator output vector if True.
315
+ structure : str, optional
316
+ A string describing the structure of all operators.
317
+ Only `upper_triangular` is currently supported.
318
+
319
+ Returns
320
+ -------
321
+ est : float
322
+ An underestimate of the 1-norm of the sparse arrays.
323
+ v : ndarray, optional
324
+ The vector such that ||Av||_1 == est*||v||_1.
325
+ It can be thought of as an input to the linear operator
326
+ that gives an output with particularly large norm.
327
+ w : ndarray, optional
328
+ The vector Av which has relatively large 1-norm.
329
+ It can be thought of as an output of the linear operator
330
+ that is relatively large in norm compared to the input.
331
+
332
+ """
333
+ return scipy.sparse.linalg.onenormest(
334
+ ProductOperator(*operator_seq, structure=structure))
335
+
336
+
337
+ class _ExpmPadeHelper:
338
+ """
339
+ Help lazily evaluate a matrix exponential.
340
+
341
+ The idea is to not do more work than we need for high expm precision,
342
+ so we lazily compute matrix powers and store or precompute
343
+ other properties of the matrix.
344
+
345
+ """
346
+
347
+ def __init__(self, A, structure=None, use_exact_onenorm=False):
348
+ """
349
+ Initialize the object.
350
+
351
+ Parameters
352
+ ----------
353
+ A : a dense or sparse square numpy matrix or ndarray
354
+ The matrix to be exponentiated.
355
+ structure : str, optional
356
+ A string describing the structure of matrix `A`.
357
+ Only `upper_triangular` is currently supported.
358
+ use_exact_onenorm : bool, optional
359
+ If True then only the exact one-norm of matrix powers and products
360
+ will be used. Otherwise, the one-norm of powers and products
361
+ may initially be estimated.
362
+ """
363
+ self.A = A
364
+ self._A2 = None
365
+ self._A4 = None
366
+ self._A6 = None
367
+ self._A8 = None
368
+ self._A10 = None
369
+ self._d4_exact = None
370
+ self._d6_exact = None
371
+ self._d8_exact = None
372
+ self._d10_exact = None
373
+ self._d4_approx = None
374
+ self._d6_approx = None
375
+ self._d8_approx = None
376
+ self._d10_approx = None
377
+ self.ident = _ident_like(A)
378
+ self.structure = structure
379
+ self.use_exact_onenorm = use_exact_onenorm
380
+
381
+ @property
382
+ def A2(self):
383
+ if self._A2 is None:
384
+ self._A2 = _smart_matrix_product(
385
+ self.A, self.A, structure=self.structure)
386
+ return self._A2
387
+
388
+ @property
389
+ def A4(self):
390
+ if self._A4 is None:
391
+ self._A4 = _smart_matrix_product(
392
+ self.A2, self.A2, structure=self.structure)
393
+ return self._A4
394
+
395
+ @property
396
+ def A6(self):
397
+ if self._A6 is None:
398
+ self._A6 = _smart_matrix_product(
399
+ self.A4, self.A2, structure=self.structure)
400
+ return self._A6
401
+
402
+ @property
403
+ def A8(self):
404
+ if self._A8 is None:
405
+ self._A8 = _smart_matrix_product(
406
+ self.A6, self.A2, structure=self.structure)
407
+ return self._A8
408
+
409
+ @property
410
+ def A10(self):
411
+ if self._A10 is None:
412
+ self._A10 = _smart_matrix_product(
413
+ self.A4, self.A6, structure=self.structure)
414
+ return self._A10
415
+
416
+ @property
417
+ def d4_tight(self):
418
+ if self._d4_exact is None:
419
+ self._d4_exact = _onenorm(self.A4)**(1/4.)
420
+ return self._d4_exact
421
+
422
+ @property
423
+ def d6_tight(self):
424
+ if self._d6_exact is None:
425
+ self._d6_exact = _onenorm(self.A6)**(1/6.)
426
+ return self._d6_exact
427
+
428
+ @property
429
+ def d8_tight(self):
430
+ if self._d8_exact is None:
431
+ self._d8_exact = _onenorm(self.A8)**(1/8.)
432
+ return self._d8_exact
433
+
434
+ @property
435
+ def d10_tight(self):
436
+ if self._d10_exact is None:
437
+ self._d10_exact = _onenorm(self.A10)**(1/10.)
438
+ return self._d10_exact
439
+
440
+ @property
441
+ def d4_loose(self):
442
+ if self.use_exact_onenorm:
443
+ return self.d4_tight
444
+ if self._d4_exact is not None:
445
+ return self._d4_exact
446
+ else:
447
+ if self._d4_approx is None:
448
+ self._d4_approx = _onenormest_matrix_power(self.A2, 2,
449
+ structure=self.structure)**(1/4.)
450
+ return self._d4_approx
451
+
452
+ @property
453
+ def d6_loose(self):
454
+ if self.use_exact_onenorm:
455
+ return self.d6_tight
456
+ if self._d6_exact is not None:
457
+ return self._d6_exact
458
+ else:
459
+ if self._d6_approx is None:
460
+ self._d6_approx = _onenormest_matrix_power(self.A2, 3,
461
+ structure=self.structure)**(1/6.)
462
+ return self._d6_approx
463
+
464
+ @property
465
+ def d8_loose(self):
466
+ if self.use_exact_onenorm:
467
+ return self.d8_tight
468
+ if self._d8_exact is not None:
469
+ return self._d8_exact
470
+ else:
471
+ if self._d8_approx is None:
472
+ self._d8_approx = _onenormest_matrix_power(self.A4, 2,
473
+ structure=self.structure)**(1/8.)
474
+ return self._d8_approx
475
+
476
+ @property
477
+ def d10_loose(self):
478
+ if self.use_exact_onenorm:
479
+ return self.d10_tight
480
+ if self._d10_exact is not None:
481
+ return self._d10_exact
482
+ else:
483
+ if self._d10_approx is None:
484
+ self._d10_approx = _onenormest_product((self.A4, self.A6),
485
+ structure=self.structure)**(1/10.)
486
+ return self._d10_approx
487
+
488
+ def pade3(self):
489
+ b = (120., 60., 12., 1.)
490
+ U = _smart_matrix_product(self.A,
491
+ b[3]*self.A2 + b[1]*self.ident,
492
+ structure=self.structure)
493
+ V = b[2]*self.A2 + b[0]*self.ident
494
+ return U, V
495
+
496
+ def pade5(self):
497
+ b = (30240., 15120., 3360., 420., 30., 1.)
498
+ U = _smart_matrix_product(self.A,
499
+ b[5]*self.A4 + b[3]*self.A2 + b[1]*self.ident,
500
+ structure=self.structure)
501
+ V = b[4]*self.A4 + b[2]*self.A2 + b[0]*self.ident
502
+ return U, V
503
+
504
+ def pade7(self):
505
+ b = (17297280., 8648640., 1995840., 277200., 25200., 1512., 56., 1.)
506
+ U = _smart_matrix_product(self.A,
507
+ b[7]*self.A6 + b[5]*self.A4 + b[3]*self.A2 + b[1]*self.ident,
508
+ structure=self.structure)
509
+ V = b[6]*self.A6 + b[4]*self.A4 + b[2]*self.A2 + b[0]*self.ident
510
+ return U, V
511
+
512
+ def pade9(self):
513
+ b = (17643225600., 8821612800., 2075673600., 302702400., 30270240.,
514
+ 2162160., 110880., 3960., 90., 1.)
515
+ U = _smart_matrix_product(self.A,
516
+ (b[9]*self.A8 + b[7]*self.A6 + b[5]*self.A4 +
517
+ b[3]*self.A2 + b[1]*self.ident),
518
+ structure=self.structure)
519
+ V = (b[8]*self.A8 + b[6]*self.A6 + b[4]*self.A4 +
520
+ b[2]*self.A2 + b[0]*self.ident)
521
+ return U, V
522
+
523
+ def pade13_scaled(self, s):
524
+ b = (64764752532480000., 32382376266240000., 7771770303897600.,
525
+ 1187353796428800., 129060195264000., 10559470521600.,
526
+ 670442572800., 33522128640., 1323241920., 40840800., 960960.,
527
+ 16380., 182., 1.)
528
+ B = self.A * 2**-s
529
+ B2 = self.A2 * 2**(-2*s)
530
+ B4 = self.A4 * 2**(-4*s)
531
+ B6 = self.A6 * 2**(-6*s)
532
+ U2 = _smart_matrix_product(B6,
533
+ b[13]*B6 + b[11]*B4 + b[9]*B2,
534
+ structure=self.structure)
535
+ U = _smart_matrix_product(B,
536
+ (U2 + b[7]*B6 + b[5]*B4 +
537
+ b[3]*B2 + b[1]*self.ident),
538
+ structure=self.structure)
539
+ V2 = _smart_matrix_product(B6,
540
+ b[12]*B6 + b[10]*B4 + b[8]*B2,
541
+ structure=self.structure)
542
+ V = V2 + b[6]*B6 + b[4]*B4 + b[2]*B2 + b[0]*self.ident
543
+ return U, V
544
+
545
+
546
+ def expm(A):
547
+ """
548
+ Compute the matrix exponential using Pade approximation.
549
+
550
+ Parameters
551
+ ----------
552
+ A : (M,M) array_like or sparse array
553
+ 2D Array or Matrix (sparse or dense) to be exponentiated
554
+
555
+ Returns
556
+ -------
557
+ expA : (M,M) ndarray
558
+ Matrix exponential of `A`
559
+
560
+ Notes
561
+ -----
562
+ This is algorithm (6.1) which is a simplification of algorithm (5.1).
563
+
564
+ .. versionadded:: 0.12.0
565
+
566
+ References
567
+ ----------
568
+ .. [1] Awad H. Al-Mohy and Nicholas J. Higham (2009)
569
+ "A New Scaling and Squaring Algorithm for the Matrix Exponential."
570
+ SIAM Journal on Matrix Analysis and Applications.
571
+ 31 (3). pp. 970-989. ISSN 1095-7162
572
+
573
+ Examples
574
+ --------
575
+ >>> from scipy.sparse import csc_array
576
+ >>> from scipy.sparse.linalg import expm
577
+ >>> A = csc_array([[1, 0, 0], [0, 2, 0], [0, 0, 3]])
578
+ >>> A.toarray()
579
+ array([[1, 0, 0],
580
+ [0, 2, 0],
581
+ [0, 0, 3]], dtype=int64)
582
+ >>> Aexp = expm(A)
583
+ >>> Aexp
584
+ <Compressed Sparse Column sparse array of dtype 'float64'
585
+ with 3 stored elements and shape (3, 3)>
586
+ >>> Aexp.toarray()
587
+ array([[ 2.71828183, 0. , 0. ],
588
+ [ 0. , 7.3890561 , 0. ],
589
+ [ 0. , 0. , 20.08553692]])
590
+ """
591
+ return _expm(A, use_exact_onenorm='auto')
592
+
593
+
594
+ def _expm(A, use_exact_onenorm):
595
+ # Core of expm, separated to allow testing exact and approximate
596
+ # algorithms.
597
+
598
+ # Avoid indiscriminate asarray() to allow sparse or other strange arrays.
599
+ if isinstance(A, (list, tuple, np.matrix)):
600
+ A = np.asarray(A)
601
+ if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
602
+ raise ValueError('expected a square matrix')
603
+
604
+ # gracefully handle size-0 input,
605
+ # carefully handling sparse scenario
606
+ if A.shape == (0, 0):
607
+ out = np.zeros([0, 0], dtype=A.dtype)
608
+ if issparse(A) or is_pydata_spmatrix(A):
609
+ return A.__class__(out)
610
+ return out
611
+
612
+ # Trivial case
613
+ if A.shape == (1, 1):
614
+ out = [[np.exp(A[0, 0])]]
615
+
616
+ # Avoid indiscriminate casting to ndarray to
617
+ # allow for sparse or other strange arrays
618
+ if issparse(A) or is_pydata_spmatrix(A):
619
+ return A.__class__(out)
620
+
621
+ return np.array(out)
622
+
623
+ # Ensure input is of float type, to avoid integer overflows etc.
624
+ if ((isinstance(A, np.ndarray) or issparse(A) or is_pydata_spmatrix(A))
625
+ and not np.issubdtype(A.dtype, np.inexact)):
626
+ A = A.astype(float)
627
+
628
+ # Detect upper triangularity.
629
+ structure = UPPER_TRIANGULAR if _is_upper_triangular(A) else None
630
+
631
+ if use_exact_onenorm == "auto":
632
+ # Hardcode a matrix order threshold for exact vs. estimated one-norms.
633
+ use_exact_onenorm = A.shape[0] < 200
634
+
635
+ # Track functions of A to help compute the matrix exponential.
636
+ h = _ExpmPadeHelper(
637
+ A, structure=structure, use_exact_onenorm=use_exact_onenorm)
638
+
639
+ # Try Pade order 3.
640
+ eta_1 = max(h.d4_loose, h.d6_loose)
641
+ if eta_1 < 1.495585217958292e-002 and _ell(h.A, 3) == 0:
642
+ U, V = h.pade3()
643
+ return _solve_P_Q(U, V, structure=structure)
644
+
645
+ # Try Pade order 5.
646
+ eta_2 = max(h.d4_tight, h.d6_loose)
647
+ if eta_2 < 2.539398330063230e-001 and _ell(h.A, 5) == 0:
648
+ U, V = h.pade5()
649
+ return _solve_P_Q(U, V, structure=structure)
650
+
651
+ # Try Pade orders 7 and 9.
652
+ eta_3 = max(h.d6_tight, h.d8_loose)
653
+ if eta_3 < 9.504178996162932e-001 and _ell(h.A, 7) == 0:
654
+ U, V = h.pade7()
655
+ return _solve_P_Q(U, V, structure=structure)
656
+ if eta_3 < 2.097847961257068e+000 and _ell(h.A, 9) == 0:
657
+ U, V = h.pade9()
658
+ return _solve_P_Q(U, V, structure=structure)
659
+
660
+ # Use Pade order 13.
661
+ eta_4 = max(h.d8_loose, h.d10_loose)
662
+ eta_5 = min(eta_3, eta_4)
663
+ theta_13 = 4.25
664
+
665
+ # Choose smallest s>=0 such that 2**(-s) eta_5 <= theta_13
666
+ if eta_5 == 0:
667
+ # Nilpotent special case
668
+ s = 0
669
+ else:
670
+ s = max(int(np.ceil(np.log2(eta_5 / theta_13))), 0)
671
+ s = s + _ell(2**-s * h.A, 13)
672
+ U, V = h.pade13_scaled(s)
673
+ X = _solve_P_Q(U, V, structure=structure)
674
+ if structure == UPPER_TRIANGULAR:
675
+ # Invoke Code Fragment 2.1.
676
+ X = _fragment_2_1(X, h.A, s)
677
+ else:
678
+ # X = r_13(A)^(2^s) by repeated squaring.
679
+ for i in range(s):
680
+ X = X.dot(X)
681
+ return X
682
+
683
+
684
+ def _solve_P_Q(U, V, structure=None):
685
+ """
686
+ A helper function for expm_2009.
687
+
688
+ Parameters
689
+ ----------
690
+ U : ndarray
691
+ Pade numerator.
692
+ V : ndarray
693
+ Pade denominator.
694
+ structure : str, optional
695
+ A string describing the structure of both matrices `U` and `V`.
696
+ Only `upper_triangular` is currently supported.
697
+
698
+ Notes
699
+ -----
700
+ The `structure` argument is inspired by similar args
701
+ for theano and cvxopt functions.
702
+
703
+ """
704
+ P = U + V
705
+ Q = -U + V
706
+ if issparse(U) or is_pydata_spmatrix(U):
707
+ return spsolve(Q, P)
708
+ elif structure is None:
709
+ return solve(Q, P)
710
+ elif structure == UPPER_TRIANGULAR:
711
+ return solve_triangular(Q, P)
712
+ else:
713
+ raise ValueError('unsupported matrix structure: ' + str(structure))
714
+
715
+
716
+ def _exp_sinch(a, x):
717
+ """
718
+ Stably evaluate exp(a)*sinh(x)/x
719
+
720
+ Notes
721
+ -----
722
+ The strategy of falling back to a sixth order Taylor expansion
723
+ was suggested by the Spallation Neutron Source docs
724
+ which was found on the internet by google search.
725
+ http://www.ornl.gov/~t6p/resources/xal/javadoc/gov/sns/tools/math/ElementaryFunction.html
726
+ The details of the cutoff point and the Horner-like evaluation
727
+ was picked without reference to anything in particular.
728
+
729
+ Note that sinch is not currently implemented in scipy.special,
730
+ whereas the "engineer's" definition of sinc is implemented.
731
+ The implementation of sinc involves a scaling factor of pi
732
+ that distinguishes it from the "mathematician's" version of sinc.
733
+
734
+ """
735
+
736
+ # If x is small then use sixth order Taylor expansion.
737
+ # How small is small? I am using the point where the relative error
738
+ # of the approximation is less than 1e-14.
739
+ # If x is large then directly evaluate sinh(x) / x.
740
+ if abs(x) < 0.0135:
741
+ x2 = x*x
742
+ return np.exp(a) * (1 + (x2/6.)*(1 + (x2/20.)*(1 + (x2/42.))))
743
+ else:
744
+ return (np.exp(a + x) - np.exp(a - x)) / (2*x)
745
+
746
+
747
+ def _eq_10_42(lam_1, lam_2, t_12):
748
+ """
749
+ Equation (10.42) of Functions of Matrices: Theory and Computation.
750
+
751
+ Notes
752
+ -----
753
+ This is a helper function for _fragment_2_1 of expm_2009.
754
+ Equation (10.42) is on page 251 in the section on Schur algorithms.
755
+ In particular, section 10.4.3 explains the Schur-Parlett algorithm.
756
+ expm([[lam_1, t_12], [0, lam_1])
757
+ =
758
+ [[exp(lam_1), t_12*exp((lam_1 + lam_2)/2)*sinch((lam_1 - lam_2)/2)],
759
+ [0, exp(lam_2)]
760
+ """
761
+
762
+ # The plain formula t_12 * (exp(lam_2) - exp(lam_2)) / (lam_2 - lam_1)
763
+ # apparently suffers from cancellation, according to Higham's textbook.
764
+ # A nice implementation of sinch, defined as sinh(x)/x,
765
+ # will apparently work around the cancellation.
766
+ a = 0.5 * (lam_1 + lam_2)
767
+ b = 0.5 * (lam_1 - lam_2)
768
+ return t_12 * _exp_sinch(a, b)
769
+
770
+
771
+ def _fragment_2_1(X, T, s):
772
+ """
773
+ A helper function for expm_2009.
774
+
775
+ Notes
776
+ -----
777
+ The argument X is modified in-place, but this modification is not the same
778
+ as the returned value of the function.
779
+ This function also takes pains to do things in ways that are compatible
780
+ with sparse arrays, for example by avoiding fancy indexing
781
+ and by using methods of the matrices whenever possible instead of
782
+ using functions of the numpy or scipy libraries themselves.
783
+
784
+ """
785
+ # Form X = r_m(2^-s T)
786
+ # Replace diag(X) by exp(2^-s diag(T)).
787
+ n = X.shape[0]
788
+ diag_T = np.ravel(T.diagonal().copy())
789
+
790
+ # Replace diag(X) by exp(2^-s diag(T)).
791
+ scale = 2 ** -s
792
+ exp_diag = np.exp(scale * diag_T)
793
+ for k in range(n):
794
+ X[k, k] = exp_diag[k]
795
+
796
+ for i in range(s-1, -1, -1):
797
+ X = X.dot(X)
798
+
799
+ # Replace diag(X) by exp(2^-i diag(T)).
800
+ scale = 2 ** -i
801
+ exp_diag = np.exp(scale * diag_T)
802
+ for k in range(n):
803
+ X[k, k] = exp_diag[k]
804
+
805
+ # Replace (first) superdiagonal of X by explicit formula
806
+ # for superdiagonal of exp(2^-i T) from Eq (10.42) of
807
+ # the author's 2008 textbook
808
+ # Functions of Matrices: Theory and Computation.
809
+ for k in range(n-1):
810
+ lam_1 = scale * diag_T[k]
811
+ lam_2 = scale * diag_T[k+1]
812
+ t_12 = scale * T[k, k+1]
813
+ value = _eq_10_42(lam_1, lam_2, t_12)
814
+ X[k, k+1] = value
815
+
816
+ # Return the updated X matrix.
817
+ return X
818
+
819
+
820
+ def _ell(A, m):
821
+ """
822
+ A helper function for expm_2009.
823
+
824
+ Parameters
825
+ ----------
826
+ A : linear operator
827
+ A linear operator whose norm of power we care about.
828
+ m : int
829
+ The power of the linear operator
830
+
831
+ Returns
832
+ -------
833
+ value : int
834
+ A value related to a bound.
835
+
836
+ """
837
+ if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
838
+ raise ValueError('expected A to be like a square matrix')
839
+
840
+ # The c_i are explained in (2.2) and (2.6) of the 2005 expm paper.
841
+ # They are coefficients of terms of a generating function series expansion.
842
+ c_i = {3: 100800.,
843
+ 5: 10059033600.,
844
+ 7: 4487938430976000.,
845
+ 9: 5914384781877411840000.,
846
+ 13: 113250775606021113483283660800000000.
847
+ }
848
+ abs_c_recip = c_i[m]
849
+
850
+ # This is explained after Eq. (1.2) of the 2009 expm paper.
851
+ # It is the "unit roundoff" of IEEE double precision arithmetic.
852
+ u = 2**-53
853
+
854
+ # Compute the one-norm of matrix power p of abs(A).
855
+ A_abs_onenorm = _onenorm_matrix_power_nnm(abs(A), 2*m + 1)
856
+
857
+ # Treat zero norm as a special case.
858
+ if not A_abs_onenorm:
859
+ return 0
860
+
861
+ alpha = A_abs_onenorm / (_onenorm(A) * abs_c_recip)
862
+ log2_alpha_div_u = np.log2(alpha/u)
863
+ value = int(np.ceil(log2_alpha_div_u / (2 * m)))
864
+ return max(value, 0)
865
+
866
+ def matrix_power(A, power):
867
+ """
868
+ Raise a square matrix to the integer power, `power`.
869
+
870
+ For non-negative integers, ``A**power`` is computed using repeated
871
+ matrix multiplications. Negative integers are not supported.
872
+
873
+ Parameters
874
+ ----------
875
+ A : (M, M) square sparse array or matrix
876
+ sparse array that will be raised to power `power`
877
+ power : int
878
+ Exponent used to raise sparse array `A`
879
+
880
+ Returns
881
+ -------
882
+ A**power : (M, M) sparse array or matrix
883
+ The output matrix will be the same shape as A, and will preserve
884
+ the class of A, but the format of the output may be changed.
885
+
886
+ Notes
887
+ -----
888
+ This uses a recursive implementation of the matrix power. For computing
889
+ the matrix power using a reasonably large `power`, this may be less efficient
890
+ than computing the product directly, using A @ A @ ... @ A.
891
+ This is contingent upon the number of nonzero entries in the matrix.
892
+
893
+ .. versionadded:: 1.12.0
894
+
895
+ Examples
896
+ --------
897
+ >>> from scipy import sparse
898
+ >>> A = sparse.csc_array([[0,1,0],[1,0,1],[0,1,0]])
899
+ >>> A.todense()
900
+ array([[0, 1, 0],
901
+ [1, 0, 1],
902
+ [0, 1, 0]])
903
+ >>> (A @ A).todense()
904
+ array([[1, 0, 1],
905
+ [0, 2, 0],
906
+ [1, 0, 1]])
907
+ >>> A2 = sparse.linalg.matrix_power(A, 2)
908
+ >>> A2.todense()
909
+ array([[1, 0, 1],
910
+ [0, 2, 0],
911
+ [1, 0, 1]])
912
+ >>> A4 = sparse.linalg.matrix_power(A, 4)
913
+ >>> A4.todense()
914
+ array([[2, 0, 2],
915
+ [0, 4, 0],
916
+ [2, 0, 2]])
917
+
918
+ """
919
+ M, N = A.shape
920
+ if M != N:
921
+ raise TypeError('sparse matrix is not square')
922
+
923
+ if isintlike(power):
924
+ power = int(power)
925
+ if power < 0:
926
+ raise ValueError('exponent must be >= 0')
927
+
928
+ if power == 0:
929
+ return eye_array(M, dtype=A.dtype)
930
+
931
+ if power == 1:
932
+ return A.copy()
933
+
934
+ tmp = matrix_power(A, power // 2)
935
+ if power % 2:
936
+ return A @ tmp @ tmp
937
+ else:
938
+ return tmp @ tmp
939
+ else:
940
+ raise ValueError("exponent must be an integer")
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_norm.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Sparse matrix norms.
2
+
3
+ """
4
+ import numpy as np
5
+ from scipy.sparse import issparse
6
+ from scipy.sparse.linalg import svds
7
+ from scipy.sparse._sputils import convert_pydata_sparse_to_scipy
8
+ import scipy.sparse as sp
9
+
10
+ from numpy import sqrt, abs
11
+
12
+ __all__ = ['norm']
13
+
14
+
15
+ def _sparse_frobenius_norm(x):
16
+ data = sp._sputils._todata(x)
17
+ return np.linalg.norm(data)
18
+
19
+
20
+ def norm(x, ord=None, axis=None):
21
+ """
22
+ Norm of a sparse matrix
23
+
24
+ This function is able to return one of seven different matrix norms,
25
+ depending on the value of the ``ord`` parameter.
26
+
27
+ Parameters
28
+ ----------
29
+ x : a sparse array
30
+ Input sparse array.
31
+ ord : {non-zero int, inf, -inf, 'fro'}, optional
32
+ Order of the norm (see table under ``Notes``). inf means numpy's
33
+ `inf` object.
34
+ axis : {int, 2-tuple of ints, None}, optional
35
+ If `axis` is an integer, it specifies the axis of `x` along which to
36
+ compute the vector norms. If `axis` is a 2-tuple, it specifies the
37
+ axes that hold 2-D matrices, and the matrix norms of these matrices
38
+ are computed. If `axis` is None then either a vector norm (when `x`
39
+ is 1-D) or a matrix norm (when `x` is 2-D) is returned.
40
+
41
+ Returns
42
+ -------
43
+ n : float or ndarray
44
+
45
+ Notes
46
+ -----
47
+ Some of the ord are not implemented because some associated functions like,
48
+ _multi_svd_norm, are not yet available for sparse array.
49
+
50
+ This docstring is modified based on numpy.linalg.norm.
51
+ https://github.com/numpy/numpy/blob/main/numpy/linalg/linalg.py
52
+
53
+ The following norms can be calculated:
54
+
55
+ ===== ============================
56
+ ord norm for sparse arrays
57
+ ===== ============================
58
+ None Frobenius norm
59
+ 'fro' Frobenius norm
60
+ inf max(sum(abs(x), axis=1))
61
+ -inf min(sum(abs(x), axis=1))
62
+ 0 abs(x).sum(axis=axis)
63
+ 1 max(sum(abs(x), axis=0))
64
+ -1 min(sum(abs(x), axis=0))
65
+ 2 Spectral norm (the largest singular value)
66
+ -2 Not implemented
67
+ other Not implemented
68
+ ===== ============================
69
+
70
+ The Frobenius norm is given by [1]_:
71
+
72
+ :math:`||A||_F = [\\sum_{i,j} abs(a_{i,j})^2]^{1/2}`
73
+
74
+ References
75
+ ----------
76
+ .. [1] G. H. Golub and C. F. Van Loan, *Matrix Computations*,
77
+ Baltimore, MD, Johns Hopkins University Press, 1985, pg. 15
78
+
79
+ Examples
80
+ --------
81
+ >>> from scipy.sparse import csr_array, diags_array
82
+ >>> import numpy as np
83
+ >>> from scipy.sparse.linalg import norm
84
+ >>> a = np.arange(9) - 4
85
+ >>> a
86
+ array([-4, -3, -2, -1, 0, 1, 2, 3, 4])
87
+ >>> b = a.reshape((3, 3))
88
+ >>> b
89
+ array([[-4, -3, -2],
90
+ [-1, 0, 1],
91
+ [ 2, 3, 4]])
92
+
93
+ >>> b = csr_array(b)
94
+ >>> norm(b)
95
+ 7.745966692414834
96
+ >>> norm(b, 'fro')
97
+ 7.745966692414834
98
+ >>> norm(b, np.inf)
99
+ 9
100
+ >>> norm(b, -np.inf)
101
+ 2
102
+ >>> norm(b, 1)
103
+ 7
104
+ >>> norm(b, -1)
105
+ 6
106
+
107
+ The matrix 2-norm or the spectral norm is the largest singular
108
+ value, computed approximately and with limitations.
109
+
110
+ >>> b = diags_array([-1, 1], [0, 1], shape=(9, 10))
111
+ >>> norm(b, 2)
112
+ 1.9753...
113
+ """
114
+ x = convert_pydata_sparse_to_scipy(x, target_format="csr")
115
+ if not issparse(x):
116
+ raise TypeError("input is not sparse. use numpy.linalg.norm")
117
+
118
+ # Check the default case first and handle it immediately.
119
+ if axis is None and ord in (None, 'fro', 'f'):
120
+ return _sparse_frobenius_norm(x)
121
+
122
+ # Some norms require functions that are not implemented for all types.
123
+ x = x.tocsr()
124
+
125
+ if axis is None:
126
+ axis = tuple(range(x.ndim))
127
+ elif not isinstance(axis, tuple):
128
+ msg = "'axis' must be None, an integer or a tuple of integers"
129
+ try:
130
+ int_axis = int(axis)
131
+ except TypeError as e:
132
+ raise TypeError(msg) from e
133
+ if axis != int_axis:
134
+ raise TypeError(msg)
135
+ axis = (int_axis,)
136
+
137
+ nd = x.ndim
138
+ if len(axis) == 2:
139
+ row_axis, col_axis = axis
140
+ if not (-nd <= row_axis < nd and -nd <= col_axis < nd):
141
+ message = f'Invalid axis {axis!r} for an array with shape {x.shape!r}'
142
+ raise ValueError(message)
143
+ if row_axis % nd == col_axis % nd:
144
+ raise ValueError('Duplicate axes given.')
145
+ if ord == 2:
146
+ # Only solver="lobpcg" supports all numpy dtypes
147
+ _, s, _ = svds(x, k=1, solver="lobpcg")
148
+ return s[0]
149
+ elif ord == -2:
150
+ raise NotImplementedError
151
+ #return _multi_svd_norm(x, row_axis, col_axis, amin)
152
+ elif ord == 1:
153
+ return abs(x).sum(axis=row_axis).max()
154
+ elif ord == np.inf:
155
+ return abs(x).sum(axis=col_axis).max()
156
+ elif ord == -1:
157
+ return abs(x).sum(axis=row_axis).min()
158
+ elif ord == -np.inf:
159
+ return abs(x).sum(axis=col_axis).min()
160
+ elif ord in (None, 'f', 'fro'):
161
+ # The axis order does not matter for this norm.
162
+ return _sparse_frobenius_norm(x)
163
+ else:
164
+ raise ValueError("Invalid norm order for matrices.")
165
+ elif len(axis) == 1:
166
+ a, = axis
167
+ if not (-nd <= a < nd):
168
+ message = f'Invalid axis {axis!r} for an array with shape {x.shape!r}'
169
+ raise ValueError(message)
170
+ if ord == np.inf:
171
+ M = abs(x).max(axis=a)
172
+ elif ord == -np.inf:
173
+ M = abs(x).min(axis=a)
174
+ elif ord == 0:
175
+ # Zero norm
176
+ M = (x != 0).sum(axis=a)
177
+ elif ord == 1:
178
+ # special case for speedup
179
+ M = abs(x).sum(axis=a)
180
+ elif ord in (2, None):
181
+ M = sqrt(abs(x).power(2).sum(axis=a))
182
+ else:
183
+ try:
184
+ ord + 1
185
+ except TypeError as e:
186
+ raise ValueError('Invalid norm order for vectors.') from e
187
+ M = np.power(abs(x).power(ord).sum(axis=a), 1 / ord)
188
+ if hasattr(M, 'toarray'):
189
+ return M.toarray().ravel()
190
+ elif hasattr(M, 'A'):
191
+ return M.A.ravel()
192
+ else:
193
+ return M.ravel()
194
+ else:
195
+ raise ValueError("Improper number of dimensions to norm.")
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_onenormest.py ADDED
@@ -0,0 +1,467 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Sparse block 1-norm estimator.
2
+ """
3
+
4
+ import numpy as np
5
+ from scipy.sparse.linalg import aslinearoperator
6
+
7
+
8
+ __all__ = ['onenormest']
9
+
10
+
11
+ def onenormest(A, t=2, itmax=5, compute_v=False, compute_w=False):
12
+ """
13
+ Compute a lower bound of the 1-norm of a sparse array.
14
+
15
+ Parameters
16
+ ----------
17
+ A : ndarray or other linear operator
18
+ A linear operator that can be transposed and that can
19
+ produce matrix products.
20
+ t : int, optional
21
+ A positive parameter controlling the tradeoff between
22
+ accuracy versus time and memory usage.
23
+ Larger values take longer and use more memory
24
+ but give more accurate output.
25
+ itmax : int, optional
26
+ Use at most this many iterations.
27
+ compute_v : bool, optional
28
+ Request a norm-maximizing linear operator input vector if True.
29
+ compute_w : bool, optional
30
+ Request a norm-maximizing linear operator output vector if True.
31
+
32
+ Returns
33
+ -------
34
+ est : float
35
+ An underestimate of the 1-norm of the sparse array.
36
+ v : ndarray, optional
37
+ The vector such that ||Av||_1 == est*||v||_1.
38
+ It can be thought of as an input to the linear operator
39
+ that gives an output with particularly large norm.
40
+ w : ndarray, optional
41
+ The vector Av which has relatively large 1-norm.
42
+ It can be thought of as an output of the linear operator
43
+ that is relatively large in norm compared to the input.
44
+
45
+ Notes
46
+ -----
47
+ This is algorithm 2.4 of [1].
48
+
49
+ In [2] it is described as follows.
50
+ "This algorithm typically requires the evaluation of
51
+ about 4t matrix-vector products and almost invariably
52
+ produces a norm estimate (which is, in fact, a lower
53
+ bound on the norm) correct to within a factor 3."
54
+
55
+ .. versionadded:: 0.13.0
56
+
57
+ References
58
+ ----------
59
+ .. [1] Nicholas J. Higham and Francoise Tisseur (2000),
60
+ "A Block Algorithm for Matrix 1-Norm Estimation,
61
+ with an Application to 1-Norm Pseudospectra."
62
+ SIAM J. Matrix Anal. Appl. Vol. 21, No. 4, pp. 1185-1201.
63
+
64
+ .. [2] Awad H. Al-Mohy and Nicholas J. Higham (2009),
65
+ "A new scaling and squaring algorithm for the matrix exponential."
66
+ SIAM J. Matrix Anal. Appl. Vol. 31, No. 3, pp. 970-989.
67
+
68
+ Examples
69
+ --------
70
+ >>> import numpy as np
71
+ >>> from scipy.sparse import csc_array
72
+ >>> from scipy.sparse.linalg import onenormest
73
+ >>> A = csc_array([[1., 0., 0.], [5., 8., 2.], [0., -1., 0.]], dtype=float)
74
+ >>> A.toarray()
75
+ array([[ 1., 0., 0.],
76
+ [ 5., 8., 2.],
77
+ [ 0., -1., 0.]])
78
+ >>> onenormest(A)
79
+ 9.0
80
+ >>> np.linalg.norm(A.toarray(), ord=1)
81
+ 9.0
82
+ """
83
+
84
+ # Check the input.
85
+ A = aslinearoperator(A)
86
+ if A.shape[0] != A.shape[1]:
87
+ raise ValueError('expected the operator to act like a square matrix')
88
+
89
+ # If the operator size is small compared to t,
90
+ # then it is easier to compute the exact norm.
91
+ # Otherwise estimate the norm.
92
+ n = A.shape[1]
93
+ if t >= n:
94
+ A_explicit = np.asarray(aslinearoperator(A).matmat(np.identity(n)))
95
+ if A_explicit.shape != (n, n):
96
+ raise Exception('internal error: ',
97
+ 'unexpected shape ' + str(A_explicit.shape))
98
+ col_abs_sums = abs(A_explicit).sum(axis=0)
99
+ if col_abs_sums.shape != (n, ):
100
+ raise Exception('internal error: ',
101
+ 'unexpected shape ' + str(col_abs_sums.shape))
102
+ argmax_j = np.argmax(col_abs_sums)
103
+ v = elementary_vector(n, argmax_j)
104
+ w = A_explicit[:, argmax_j]
105
+ est = col_abs_sums[argmax_j]
106
+ else:
107
+ est, v, w, nmults, nresamples = _onenormest_core(A, A.H, t, itmax)
108
+
109
+ # Report the norm estimate along with some certificates of the estimate.
110
+ if compute_v or compute_w:
111
+ result = (est,)
112
+ if compute_v:
113
+ result += (v,)
114
+ if compute_w:
115
+ result += (w,)
116
+ return result
117
+ else:
118
+ return est
119
+
120
+
121
+ def _blocked_elementwise(func):
122
+ """
123
+ Decorator for an elementwise function, to apply it blockwise along
124
+ first dimension, to avoid excessive memory usage in temporaries.
125
+ """
126
+ block_size = 2**20
127
+
128
+ def wrapper(x):
129
+ if x.shape[0] < block_size:
130
+ return func(x)
131
+ else:
132
+ y0 = func(x[:block_size])
133
+ y = np.zeros((x.shape[0],) + y0.shape[1:], dtype=y0.dtype)
134
+ y[:block_size] = y0
135
+ del y0
136
+ for j in range(block_size, x.shape[0], block_size):
137
+ y[j:j+block_size] = func(x[j:j+block_size])
138
+ return y
139
+ return wrapper
140
+
141
+
142
+ @_blocked_elementwise
143
+ def sign_round_up(X):
144
+ """
145
+ This should do the right thing for both real and complex matrices.
146
+
147
+ From Higham and Tisseur:
148
+ "Everything in this section remains valid for complex matrices
149
+ provided that sign(A) is redefined as the matrix (aij / |aij|)
150
+ (and sign(0) = 1) transposes are replaced by conjugate transposes."
151
+
152
+ """
153
+ Y = X.copy()
154
+ Y[Y == 0] = 1
155
+ Y /= np.abs(Y)
156
+ return Y
157
+
158
+
159
+ @_blocked_elementwise
160
+ def _max_abs_axis1(X):
161
+ return np.max(np.abs(X), axis=1)
162
+
163
+
164
+ def _sum_abs_axis0(X):
165
+ block_size = 2**20
166
+ r = None
167
+ for j in range(0, X.shape[0], block_size):
168
+ y = np.sum(np.abs(X[j:j+block_size]), axis=0)
169
+ if r is None:
170
+ r = y
171
+ else:
172
+ r += y
173
+ return r
174
+
175
+
176
+ def elementary_vector(n, i):
177
+ v = np.zeros(n, dtype=float)
178
+ v[i] = 1
179
+ return v
180
+
181
+
182
+ def vectors_are_parallel(v, w):
183
+ # Columns are considered parallel when they are equal or negative.
184
+ # Entries are required to be in {-1, 1},
185
+ # which guarantees that the magnitudes of the vectors are identical.
186
+ if v.ndim != 1 or v.shape != w.shape:
187
+ raise ValueError('expected conformant vectors with entries in {-1,1}')
188
+ n = v.shape[0]
189
+ return np.dot(v, w) == n
190
+
191
+
192
+ def every_col_of_X_is_parallel_to_a_col_of_Y(X, Y):
193
+ for v in X.T:
194
+ if not any(vectors_are_parallel(v, w) for w in Y.T):
195
+ return False
196
+ return True
197
+
198
+
199
+ def column_needs_resampling(i, X, Y=None):
200
+ # column i of X needs resampling if either
201
+ # it is parallel to a previous column of X or
202
+ # it is parallel to a column of Y
203
+ n, t = X.shape
204
+ v = X[:, i]
205
+ if any(vectors_are_parallel(v, X[:, j]) for j in range(i)):
206
+ return True
207
+ if Y is not None:
208
+ if any(vectors_are_parallel(v, w) for w in Y.T):
209
+ return True
210
+ return False
211
+
212
+
213
+ def resample_column(i, X):
214
+ X[:, i] = np.random.randint(0, 2, size=X.shape[0])*2 - 1
215
+
216
+
217
+ def less_than_or_close(a, b):
218
+ return np.allclose(a, b) or (a < b)
219
+
220
+
221
+ def _algorithm_2_2(A, AT, t):
222
+ """
223
+ This is Algorithm 2.2.
224
+
225
+ Parameters
226
+ ----------
227
+ A : ndarray or other linear operator
228
+ A linear operator that can produce matrix products.
229
+ AT : ndarray or other linear operator
230
+ The transpose of A.
231
+ t : int, optional
232
+ A positive parameter controlling the tradeoff between
233
+ accuracy versus time and memory usage.
234
+
235
+ Returns
236
+ -------
237
+ g : sequence
238
+ A non-negative decreasing vector
239
+ such that g[j] is a lower bound for the 1-norm
240
+ of the column of A of jth largest 1-norm.
241
+ The first entry of this vector is therefore a lower bound
242
+ on the 1-norm of the linear operator A.
243
+ This sequence has length t.
244
+ ind : sequence
245
+ The ith entry of ind is the index of the column A whose 1-norm
246
+ is given by g[i].
247
+ This sequence of indices has length t, and its entries are
248
+ chosen from range(n), possibly with repetition,
249
+ where n is the order of the operator A.
250
+
251
+ Notes
252
+ -----
253
+ This algorithm is mainly for testing.
254
+ It uses the 'ind' array in a way that is similar to
255
+ its usage in algorithm 2.4. This algorithm 2.2 may be easier to test,
256
+ so it gives a chance of uncovering bugs related to indexing
257
+ which could have propagated less noticeably to algorithm 2.4.
258
+
259
+ """
260
+ A_linear_operator = aslinearoperator(A)
261
+ AT_linear_operator = aslinearoperator(AT)
262
+ n = A_linear_operator.shape[0]
263
+
264
+ # Initialize the X block with columns of unit 1-norm.
265
+ X = np.ones((n, t))
266
+ if t > 1:
267
+ X[:, 1:] = np.random.randint(0, 2, size=(n, t-1))*2 - 1
268
+ X /= float(n)
269
+
270
+ # Iteratively improve the lower bounds.
271
+ # Track extra things, to assert invariants for debugging.
272
+ g_prev = None
273
+ h_prev = None
274
+ k = 1
275
+ ind = range(t)
276
+ while True:
277
+ Y = np.asarray(A_linear_operator.matmat(X))
278
+ g = _sum_abs_axis0(Y)
279
+ best_j = np.argmax(g)
280
+ g.sort()
281
+ g = g[::-1]
282
+ S = sign_round_up(Y)
283
+ Z = np.asarray(AT_linear_operator.matmat(S))
284
+ h = _max_abs_axis1(Z)
285
+
286
+ # If this algorithm runs for fewer than two iterations,
287
+ # then its return values do not have the properties indicated
288
+ # in the description of the algorithm.
289
+ # In particular, the entries of g are not 1-norms of any
290
+ # column of A until the second iteration.
291
+ # Therefore we will require the algorithm to run for at least
292
+ # two iterations, even though this requirement is not stated
293
+ # in the description of the algorithm.
294
+ if k >= 2:
295
+ if less_than_or_close(max(h), np.dot(Z[:, best_j], X[:, best_j])):
296
+ break
297
+ ind = np.argsort(h)[::-1][:t]
298
+ h = h[ind]
299
+ for j in range(t):
300
+ X[:, j] = elementary_vector(n, ind[j])
301
+
302
+ # Check invariant (2.2).
303
+ if k >= 2:
304
+ if not less_than_or_close(g_prev[0], h_prev[0]):
305
+ raise Exception('invariant (2.2) is violated')
306
+ if not less_than_or_close(h_prev[0], g[0]):
307
+ raise Exception('invariant (2.2) is violated')
308
+
309
+ # Check invariant (2.3).
310
+ if k >= 3:
311
+ for j in range(t):
312
+ if not less_than_or_close(g[j], g_prev[j]):
313
+ raise Exception('invariant (2.3) is violated')
314
+
315
+ # Update for the next iteration.
316
+ g_prev = g
317
+ h_prev = h
318
+ k += 1
319
+
320
+ # Return the lower bounds and the corresponding column indices.
321
+ return g, ind
322
+
323
+
324
+ def _onenormest_core(A, AT, t, itmax):
325
+ """
326
+ Compute a lower bound of the 1-norm of a sparse array.
327
+
328
+ Parameters
329
+ ----------
330
+ A : ndarray or other linear operator
331
+ A linear operator that can produce matrix products.
332
+ AT : ndarray or other linear operator
333
+ The transpose of A.
334
+ t : int, optional
335
+ A positive parameter controlling the tradeoff between
336
+ accuracy versus time and memory usage.
337
+ itmax : int, optional
338
+ Use at most this many iterations.
339
+
340
+ Returns
341
+ -------
342
+ est : float
343
+ An underestimate of the 1-norm of the sparse array.
344
+ v : ndarray, optional
345
+ The vector such that ||Av||_1 == est*||v||_1.
346
+ It can be thought of as an input to the linear operator
347
+ that gives an output with particularly large norm.
348
+ w : ndarray, optional
349
+ The vector Av which has relatively large 1-norm.
350
+ It can be thought of as an output of the linear operator
351
+ that is relatively large in norm compared to the input.
352
+ nmults : int, optional
353
+ The number of matrix products that were computed.
354
+ nresamples : int, optional
355
+ The number of times a parallel column was observed,
356
+ necessitating a re-randomization of the column.
357
+
358
+ Notes
359
+ -----
360
+ This is algorithm 2.4.
361
+
362
+ """
363
+ # This function is a more or less direct translation
364
+ # of Algorithm 2.4 from the Higham and Tisseur (2000) paper.
365
+ A_linear_operator = aslinearoperator(A)
366
+ AT_linear_operator = aslinearoperator(AT)
367
+ if itmax < 2:
368
+ raise ValueError('at least two iterations are required')
369
+ if t < 1:
370
+ raise ValueError('at least one column is required')
371
+ n = A.shape[0]
372
+ if t >= n:
373
+ raise ValueError('t should be smaller than the order of A')
374
+ # Track the number of big*small matrix multiplications
375
+ # and the number of resamplings.
376
+ nmults = 0
377
+ nresamples = 0
378
+ # "We now explain our choice of starting matrix. We take the first
379
+ # column of X to be the vector of 1s [...] This has the advantage that
380
+ # for a matrix with nonnegative elements the algorithm converges
381
+ # with an exact estimate on the second iteration, and such matrices
382
+ # arise in applications [...]"
383
+ X = np.ones((n, t), dtype=float)
384
+ # "The remaining columns are chosen as rand{-1,1},
385
+ # with a check for and correction of parallel columns,
386
+ # exactly as for S in the body of the algorithm."
387
+ if t > 1:
388
+ for i in range(1, t):
389
+ # These are technically initial samples, not resamples,
390
+ # so the resampling count is not incremented.
391
+ resample_column(i, X)
392
+ for i in range(t):
393
+ while column_needs_resampling(i, X):
394
+ resample_column(i, X)
395
+ nresamples += 1
396
+ # "Choose starting matrix X with columns of unit 1-norm."
397
+ X /= float(n)
398
+ # "indices of used unit vectors e_j"
399
+ ind_hist = np.zeros(0, dtype=np.intp)
400
+ est_old = 0
401
+ S = np.zeros((n, t), dtype=float)
402
+ k = 1
403
+ ind = None
404
+ while True:
405
+ Y = np.asarray(A_linear_operator.matmat(X))
406
+ nmults += 1
407
+ mags = _sum_abs_axis0(Y)
408
+ est = np.max(mags)
409
+ best_j = np.argmax(mags)
410
+ if est > est_old or k == 2:
411
+ if k >= 2:
412
+ ind_best = ind[best_j]
413
+ w = Y[:, best_j]
414
+ # (1)
415
+ if k >= 2 and est <= est_old:
416
+ est = est_old
417
+ break
418
+ est_old = est
419
+ S_old = S
420
+ if k > itmax:
421
+ break
422
+ S = sign_round_up(Y)
423
+ del Y
424
+ # (2)
425
+ if every_col_of_X_is_parallel_to_a_col_of_Y(S, S_old):
426
+ break
427
+ if t > 1:
428
+ # "Ensure that no column of S is parallel to another column of S
429
+ # or to a column of S_old by replacing columns of S by rand{-1,1}."
430
+ for i in range(t):
431
+ while column_needs_resampling(i, S, S_old):
432
+ resample_column(i, S)
433
+ nresamples += 1
434
+ del S_old
435
+ # (3)
436
+ Z = np.asarray(AT_linear_operator.matmat(S))
437
+ nmults += 1
438
+ h = _max_abs_axis1(Z)
439
+ del Z
440
+ # (4)
441
+ if k >= 2 and max(h) == h[ind_best]:
442
+ break
443
+ # "Sort h so that h_first >= ... >= h_last
444
+ # and re-order ind correspondingly."
445
+ #
446
+ # Later on, we will need at most t+len(ind_hist) largest
447
+ # entries, so drop the rest
448
+ ind = np.argsort(h)[::-1][:t+len(ind_hist)].copy()
449
+ del h
450
+ if t > 1:
451
+ # (5)
452
+ # Break if the most promising t vectors have been visited already.
453
+ if np.isin(ind[:t], ind_hist).all():
454
+ break
455
+ # Put the most promising unvisited vectors at the front of the list
456
+ # and put the visited vectors at the end of the list.
457
+ # Preserve the order of the indices induced by the ordering of h.
458
+ seen = np.isin(ind, ind_hist)
459
+ ind = np.concatenate((ind[~seen], ind[seen]))
460
+ for j in range(t):
461
+ X[:, j] = elementary_vector(n, ind[j])
462
+
463
+ new_ind = ind[:t][~np.isin(ind[:t], ind_hist)]
464
+ ind_hist = np.concatenate((ind_hist, new_ind))
465
+ k += 1
466
+ v = elementary_vector(n, ind_best)
467
+ return est, v, w, nmults, nresamples
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_special_sparse_arrays.py ADDED
@@ -0,0 +1,948 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from scipy.sparse.linalg import LinearOperator
3
+ from scipy.sparse import kron, eye, dia_array
4
+
5
+ __all__ = ['LaplacianNd']
6
+ # Sakurai and Mikota classes are intended for tests and benchmarks
7
+ # and explicitly not included in the public API of this module.
8
+
9
+
10
+ class LaplacianNd(LinearOperator):
11
+ """
12
+ The grid Laplacian in ``N`` dimensions and its eigenvalues/eigenvectors.
13
+
14
+ Construct Laplacian on a uniform rectangular grid in `N` dimensions
15
+ and output its eigenvalues and eigenvectors.
16
+ The Laplacian ``L`` is square, negative definite, real symmetric array
17
+ with signed integer entries and zeros otherwise.
18
+
19
+ Parameters
20
+ ----------
21
+ grid_shape : tuple
22
+ A tuple of integers of length ``N`` (corresponding to the dimension of
23
+ the Lapacian), where each entry gives the size of that dimension. The
24
+ Laplacian matrix is square of the size ``np.prod(grid_shape)``.
25
+ boundary_conditions : {'neumann', 'dirichlet', 'periodic'}, optional
26
+ The type of the boundary conditions on the boundaries of the grid.
27
+ Valid values are ``'dirichlet'`` or ``'neumann'``(default) or
28
+ ``'periodic'``.
29
+ dtype : dtype
30
+ Numerical type of the array. Default is ``np.int8``.
31
+
32
+ Methods
33
+ -------
34
+ toarray()
35
+ Construct a dense array from Laplacian data
36
+ tosparse()
37
+ Construct a sparse array from Laplacian data
38
+ eigenvalues(m=None)
39
+ Construct a 1D array of `m` largest (smallest in absolute value)
40
+ eigenvalues of the Laplacian matrix in ascending order.
41
+ eigenvectors(m=None):
42
+ Construct the array with columns made of `m` eigenvectors (``float``)
43
+ of the ``Nd`` Laplacian corresponding to the `m` ordered eigenvalues.
44
+
45
+ .. versionadded:: 1.12.0
46
+
47
+ Notes
48
+ -----
49
+ Compared to the MATLAB/Octave implementation [1] of 1-, 2-, and 3-D
50
+ Laplacian, this code allows the arbitrary N-D case and the matrix-free
51
+ callable option, but is currently limited to pure Dirichlet, Neumann or
52
+ Periodic boundary conditions only.
53
+
54
+ The Laplacian matrix of a graph (`scipy.sparse.csgraph.laplacian`) of a
55
+ rectangular grid corresponds to the negative Laplacian with the Neumann
56
+ conditions, i.e., ``boundary_conditions = 'neumann'``.
57
+
58
+ All eigenvalues and eigenvectors of the discrete Laplacian operator for
59
+ an ``N``-dimensional regular grid of shape `grid_shape` with the grid
60
+ step size ``h=1`` are analytically known [2].
61
+
62
+ References
63
+ ----------
64
+ .. [1] https://github.com/lobpcg/blopex/blob/master/blopex_\
65
+ tools/matlab/laplacian/laplacian.m
66
+ .. [2] "Eigenvalues and eigenvectors of the second derivative", Wikipedia
67
+ https://en.wikipedia.org/wiki/Eigenvalues_and_eigenvectors_\
68
+ of_the_second_derivative
69
+
70
+ Examples
71
+ --------
72
+ >>> import numpy as np
73
+ >>> from scipy.sparse.linalg import LaplacianNd
74
+ >>> from scipy.sparse import diags, csgraph
75
+ >>> from scipy.linalg import eigvalsh
76
+
77
+ The one-dimensional Laplacian demonstrated below for pure Neumann boundary
78
+ conditions on a regular grid with ``n=6`` grid points is exactly the
79
+ negative graph Laplacian for the undirected linear graph with ``n``
80
+ vertices using the sparse adjacency matrix ``G`` represented by the
81
+ famous tri-diagonal matrix:
82
+
83
+ >>> n = 6
84
+ >>> G = diags(np.ones(n - 1), 1, format='csr')
85
+ >>> Lf = csgraph.laplacian(G, symmetrized=True, form='function')
86
+ >>> grid_shape = (n, )
87
+ >>> lap = LaplacianNd(grid_shape, boundary_conditions='neumann')
88
+ >>> np.array_equal(lap.matmat(np.eye(n)), -Lf(np.eye(n)))
89
+ True
90
+
91
+ Since all matrix entries of the Laplacian are integers, ``'int8'`` is
92
+ the default dtype for storing matrix representations.
93
+
94
+ >>> lap.tosparse()
95
+ <DIAgonal sparse array of dtype 'int8'
96
+ with 16 stored elements (3 diagonals) and shape (6, 6)>
97
+ >>> lap.toarray()
98
+ array([[-1, 1, 0, 0, 0, 0],
99
+ [ 1, -2, 1, 0, 0, 0],
100
+ [ 0, 1, -2, 1, 0, 0],
101
+ [ 0, 0, 1, -2, 1, 0],
102
+ [ 0, 0, 0, 1, -2, 1],
103
+ [ 0, 0, 0, 0, 1, -1]], dtype=int8)
104
+ >>> np.array_equal(lap.matmat(np.eye(n)), lap.toarray())
105
+ True
106
+ >>> np.array_equal(lap.tosparse().toarray(), lap.toarray())
107
+ True
108
+
109
+ Any number of extreme eigenvalues and/or eigenvectors can be computed.
110
+
111
+ >>> lap = LaplacianNd(grid_shape, boundary_conditions='periodic')
112
+ >>> lap.eigenvalues()
113
+ array([-4., -3., -3., -1., -1., 0.])
114
+ >>> lap.eigenvalues()[-2:]
115
+ array([-1., 0.])
116
+ >>> lap.eigenvalues(2)
117
+ array([-1., 0.])
118
+ >>> lap.eigenvectors(1)
119
+ array([[0.40824829],
120
+ [0.40824829],
121
+ [0.40824829],
122
+ [0.40824829],
123
+ [0.40824829],
124
+ [0.40824829]])
125
+ >>> lap.eigenvectors(2)
126
+ array([[ 0.5 , 0.40824829],
127
+ [ 0. , 0.40824829],
128
+ [-0.5 , 0.40824829],
129
+ [-0.5 , 0.40824829],
130
+ [ 0. , 0.40824829],
131
+ [ 0.5 , 0.40824829]])
132
+ >>> lap.eigenvectors()
133
+ array([[ 0.40824829, 0.28867513, 0.28867513, 0.5 , 0.5 ,
134
+ 0.40824829],
135
+ [-0.40824829, -0.57735027, -0.57735027, 0. , 0. ,
136
+ 0.40824829],
137
+ [ 0.40824829, 0.28867513, 0.28867513, -0.5 , -0.5 ,
138
+ 0.40824829],
139
+ [-0.40824829, 0.28867513, 0.28867513, -0.5 , -0.5 ,
140
+ 0.40824829],
141
+ [ 0.40824829, -0.57735027, -0.57735027, 0. , 0. ,
142
+ 0.40824829],
143
+ [-0.40824829, 0.28867513, 0.28867513, 0.5 , 0.5 ,
144
+ 0.40824829]])
145
+
146
+ The two-dimensional Laplacian is illustrated on a regular grid with
147
+ ``grid_shape = (2, 3)`` points in each dimension.
148
+
149
+ >>> grid_shape = (2, 3)
150
+ >>> n = np.prod(grid_shape)
151
+
152
+ Numeration of grid points is as follows:
153
+
154
+ >>> np.arange(n).reshape(grid_shape + (-1,))
155
+ array([[[0],
156
+ [1],
157
+ [2]],
158
+ <BLANKLINE>
159
+ [[3],
160
+ [4],
161
+ [5]]])
162
+
163
+ Each of the boundary conditions ``'dirichlet'``, ``'periodic'``, and
164
+ ``'neumann'`` is illustrated separately; with ``'dirichlet'``
165
+
166
+ >>> lap = LaplacianNd(grid_shape, boundary_conditions='dirichlet')
167
+ >>> lap.tosparse()
168
+ <Compressed Sparse Row sparse array of dtype 'int8'
169
+ with 20 stored elements and shape (6, 6)>
170
+ >>> lap.toarray()
171
+ array([[-4, 1, 0, 1, 0, 0],
172
+ [ 1, -4, 1, 0, 1, 0],
173
+ [ 0, 1, -4, 0, 0, 1],
174
+ [ 1, 0, 0, -4, 1, 0],
175
+ [ 0, 1, 0, 1, -4, 1],
176
+ [ 0, 0, 1, 0, 1, -4]], dtype=int8)
177
+ >>> np.array_equal(lap.matmat(np.eye(n)), lap.toarray())
178
+ True
179
+ >>> np.array_equal(lap.tosparse().toarray(), lap.toarray())
180
+ True
181
+ >>> lap.eigenvalues()
182
+ array([-6.41421356, -5. , -4.41421356, -3.58578644, -3. ,
183
+ -1.58578644])
184
+ >>> eigvals = eigvalsh(lap.toarray().astype(np.float64))
185
+ >>> np.allclose(lap.eigenvalues(), eigvals)
186
+ True
187
+ >>> np.allclose(lap.toarray() @ lap.eigenvectors(),
188
+ ... lap.eigenvectors() @ np.diag(lap.eigenvalues()))
189
+ True
190
+
191
+ with ``'periodic'``
192
+
193
+ >>> lap = LaplacianNd(grid_shape, boundary_conditions='periodic')
194
+ >>> lap.tosparse()
195
+ <Compressed Sparse Row sparse array of dtype 'int8'
196
+ with 24 stored elements and shape (6, 6)>
197
+ >>> lap.toarray()
198
+ array([[-4, 1, 1, 2, 0, 0],
199
+ [ 1, -4, 1, 0, 2, 0],
200
+ [ 1, 1, -4, 0, 0, 2],
201
+ [ 2, 0, 0, -4, 1, 1],
202
+ [ 0, 2, 0, 1, -4, 1],
203
+ [ 0, 0, 2, 1, 1, -4]], dtype=int8)
204
+ >>> np.array_equal(lap.matmat(np.eye(n)), lap.toarray())
205
+ True
206
+ >>> np.array_equal(lap.tosparse().toarray(), lap.toarray())
207
+ True
208
+ >>> lap.eigenvalues()
209
+ array([-7., -7., -4., -3., -3., 0.])
210
+ >>> eigvals = eigvalsh(lap.toarray().astype(np.float64))
211
+ >>> np.allclose(lap.eigenvalues(), eigvals)
212
+ True
213
+ >>> np.allclose(lap.toarray() @ lap.eigenvectors(),
214
+ ... lap.eigenvectors() @ np.diag(lap.eigenvalues()))
215
+ True
216
+
217
+ and with ``'neumann'``
218
+
219
+ >>> lap = LaplacianNd(grid_shape, boundary_conditions='neumann')
220
+ >>> lap.tosparse()
221
+ <Compressed Sparse Row sparse array of dtype 'int8'
222
+ with 20 stored elements and shape (6, 6)>
223
+ >>> lap.toarray()
224
+ array([[-2, 1, 0, 1, 0, 0],
225
+ [ 1, -3, 1, 0, 1, 0],
226
+ [ 0, 1, -2, 0, 0, 1],
227
+ [ 1, 0, 0, -2, 1, 0],
228
+ [ 0, 1, 0, 1, -3, 1],
229
+ [ 0, 0, 1, 0, 1, -2]], dtype=int8)
230
+ >>> np.array_equal(lap.matmat(np.eye(n)), lap.toarray())
231
+ True
232
+ >>> np.array_equal(lap.tosparse().toarray(), lap.toarray())
233
+ True
234
+ >>> lap.eigenvalues()
235
+ array([-5., -3., -3., -2., -1., 0.])
236
+ >>> eigvals = eigvalsh(lap.toarray().astype(np.float64))
237
+ >>> np.allclose(lap.eigenvalues(), eigvals)
238
+ True
239
+ >>> np.allclose(lap.toarray() @ lap.eigenvectors(),
240
+ ... lap.eigenvectors() @ np.diag(lap.eigenvalues()))
241
+ True
242
+
243
+ """
244
+
245
+ def __init__(self, grid_shape, *,
246
+ boundary_conditions='neumann',
247
+ dtype=np.int8):
248
+
249
+ if boundary_conditions not in ('dirichlet', 'neumann', 'periodic'):
250
+ raise ValueError(
251
+ f"Unknown value {boundary_conditions!r} is given for "
252
+ "'boundary_conditions' parameter. The valid options are "
253
+ "'dirichlet', 'periodic', and 'neumann' (default)."
254
+ )
255
+
256
+ self.grid_shape = grid_shape
257
+ self.boundary_conditions = boundary_conditions
258
+ # LaplacianNd folds all dimensions in `grid_shape` into a single one
259
+ N = np.prod(grid_shape)
260
+ super().__init__(dtype=dtype, shape=(N, N))
261
+
262
+ def _eigenvalue_ordering(self, m):
263
+ """Compute `m` largest eigenvalues in each of the ``N`` directions,
264
+ i.e., up to ``m * N`` total, order them and return `m` largest.
265
+ """
266
+ grid_shape = self.grid_shape
267
+ if m is None:
268
+ indices = np.indices(grid_shape)
269
+ Leig = np.zeros(grid_shape)
270
+ else:
271
+ grid_shape_min = min(grid_shape,
272
+ tuple(np.ones_like(grid_shape) * m))
273
+ indices = np.indices(grid_shape_min)
274
+ Leig = np.zeros(grid_shape_min)
275
+
276
+ for j, n in zip(indices, grid_shape):
277
+ if self.boundary_conditions == 'dirichlet':
278
+ Leig += -4 * np.sin(np.pi * (j + 1) / (2 * (n + 1))) ** 2
279
+ elif self.boundary_conditions == 'neumann':
280
+ Leig += -4 * np.sin(np.pi * j / (2 * n)) ** 2
281
+ else: # boundary_conditions == 'periodic'
282
+ Leig += -4 * np.sin(np.pi * np.floor((j + 1) / 2) / n) ** 2
283
+
284
+ Leig_ravel = Leig.ravel()
285
+ ind = np.argsort(Leig_ravel)
286
+ eigenvalues = Leig_ravel[ind]
287
+ if m is not None:
288
+ eigenvalues = eigenvalues[-m:]
289
+ ind = ind[-m:]
290
+
291
+ return eigenvalues, ind
292
+
293
+ def eigenvalues(self, m=None):
294
+ """Return the requested number of eigenvalues.
295
+
296
+ Parameters
297
+ ----------
298
+ m : int, optional
299
+ The positive number of smallest eigenvalues to return.
300
+ If not provided, then all eigenvalues will be returned.
301
+
302
+ Returns
303
+ -------
304
+ eigenvalues : float array
305
+ The requested `m` smallest or all eigenvalues, in ascending order.
306
+ """
307
+ eigenvalues, _ = self._eigenvalue_ordering(m)
308
+ return eigenvalues
309
+
310
+ def _ev1d(self, j, n):
311
+ """Return 1 eigenvector in 1d with index `j`
312
+ and number of grid points `n` where ``j < n``.
313
+ """
314
+ if self.boundary_conditions == 'dirichlet':
315
+ i = np.pi * (np.arange(n) + 1) / (n + 1)
316
+ ev = np.sqrt(2. / (n + 1.)) * np.sin(i * (j + 1))
317
+ elif self.boundary_conditions == 'neumann':
318
+ i = np.pi * (np.arange(n) + 0.5) / n
319
+ ev = np.sqrt((1. if j == 0 else 2.) / n) * np.cos(i * j)
320
+ else: # boundary_conditions == 'periodic'
321
+ if j == 0:
322
+ ev = np.sqrt(1. / n) * np.ones(n)
323
+ elif j + 1 == n and n % 2 == 0:
324
+ ev = np.sqrt(1. / n) * np.tile([1, -1], n//2)
325
+ else:
326
+ i = 2. * np.pi * (np.arange(n) + 0.5) / n
327
+ ev = np.sqrt(2. / n) * np.cos(i * np.floor((j + 1) / 2))
328
+ # make small values exact zeros correcting round-off errors
329
+ # due to symmetry of eigenvectors the exact 0. is correct
330
+ ev[np.abs(ev) < np.finfo(np.float64).eps] = 0.
331
+ return ev
332
+
333
+ def _one_eve(self, k):
334
+ """Return 1 eigenvector in Nd with multi-index `j`
335
+ as a tensor product of the corresponding 1d eigenvectors.
336
+ """
337
+ phi = [self._ev1d(j, n) for j, n in zip(k, self.grid_shape)]
338
+ result = phi[0]
339
+ for phi in phi[1:]:
340
+ result = np.tensordot(result, phi, axes=0)
341
+ return np.asarray(result).ravel()
342
+
343
+ def eigenvectors(self, m=None):
344
+ """Return the requested number of eigenvectors for ordered eigenvalues.
345
+
346
+ Parameters
347
+ ----------
348
+ m : int, optional
349
+ The positive number of eigenvectors to return. If not provided,
350
+ then all eigenvectors will be returned.
351
+
352
+ Returns
353
+ -------
354
+ eigenvectors : float array
355
+ An array with columns made of the requested `m` or all eigenvectors.
356
+ The columns are ordered according to the `m` ordered eigenvalues.
357
+ """
358
+ _, ind = self._eigenvalue_ordering(m)
359
+ if m is None:
360
+ grid_shape_min = self.grid_shape
361
+ else:
362
+ grid_shape_min = min(self.grid_shape,
363
+ tuple(np.ones_like(self.grid_shape) * m))
364
+
365
+ N_indices = np.unravel_index(ind, grid_shape_min)
366
+ N_indices = [tuple(x) for x in zip(*N_indices)]
367
+ eigenvectors_list = [self._one_eve(k) for k in N_indices]
368
+ return np.column_stack(eigenvectors_list)
369
+
370
+ def toarray(self):
371
+ """
372
+ Converts the Laplacian data to a dense array.
373
+
374
+ Returns
375
+ -------
376
+ L : ndarray
377
+ The shape is ``(N, N)`` where ``N = np.prod(grid_shape)``.
378
+
379
+ """
380
+ grid_shape = self.grid_shape
381
+ n = np.prod(grid_shape)
382
+ L = np.zeros([n, n], dtype=np.int8)
383
+ # Scratch arrays
384
+ L_i = np.empty_like(L)
385
+ Ltemp = np.empty_like(L)
386
+
387
+ for ind, dim in enumerate(grid_shape):
388
+ # Start zeroing out L_i
389
+ L_i[:] = 0
390
+ # Allocate the top left corner with the kernel of L_i
391
+ # Einsum returns writable view of arrays
392
+ np.einsum("ii->i", L_i[:dim, :dim])[:] = -2
393
+ np.einsum("ii->i", L_i[: dim - 1, 1:dim])[:] = 1
394
+ np.einsum("ii->i", L_i[1:dim, : dim - 1])[:] = 1
395
+
396
+ if self.boundary_conditions == 'neumann':
397
+ L_i[0, 0] = -1
398
+ L_i[dim - 1, dim - 1] = -1
399
+ elif self.boundary_conditions == 'periodic':
400
+ if dim > 1:
401
+ L_i[0, dim - 1] += 1
402
+ L_i[dim - 1, 0] += 1
403
+ else:
404
+ L_i[0, 0] += 1
405
+
406
+ # kron is too slow for large matrices hence the next two tricks
407
+ # 1- kron(eye, mat) is block_diag(mat, mat, ...)
408
+ # 2- kron(mat, eye) can be performed by 4d stride trick
409
+
410
+ # 1-
411
+ new_dim = dim
412
+ # for block_diag we tile the top left portion on the diagonal
413
+ if ind > 0:
414
+ tiles = np.prod(grid_shape[:ind])
415
+ for j in range(1, tiles):
416
+ L_i[j*dim:(j+1)*dim, j*dim:(j+1)*dim] = L_i[:dim, :dim]
417
+ new_dim += dim
418
+ # 2-
419
+ # we need the keep L_i, but reset the array
420
+ Ltemp[:new_dim, :new_dim] = L_i[:new_dim, :new_dim]
421
+ tiles = int(np.prod(grid_shape[ind+1:]))
422
+ # Zero out the top left, the rest is already 0
423
+ L_i[:new_dim, :new_dim] = 0
424
+ idx = [x for x in range(tiles)]
425
+ L_i.reshape(
426
+ (new_dim, tiles,
427
+ new_dim, tiles)
428
+ )[:, idx, :, idx] = Ltemp[:new_dim, :new_dim]
429
+
430
+ L += L_i
431
+
432
+ return L.astype(self.dtype)
433
+
434
+ def tosparse(self):
435
+ """
436
+ Constructs a sparse array from the Laplacian data. The returned sparse
437
+ array format is dependent on the selected boundary conditions.
438
+
439
+ Returns
440
+ -------
441
+ L : scipy.sparse.sparray
442
+ The shape is ``(N, N)`` where ``N = np.prod(grid_shape)``.
443
+
444
+ """
445
+ N = len(self.grid_shape)
446
+ p = np.prod(self.grid_shape)
447
+ L = dia_array((p, p), dtype=np.int8)
448
+
449
+ for i in range(N):
450
+ dim = self.grid_shape[i]
451
+ data = np.ones([3, dim], dtype=np.int8)
452
+ data[1, :] *= -2
453
+
454
+ if self.boundary_conditions == 'neumann':
455
+ data[1, 0] = -1
456
+ data[1, -1] = -1
457
+
458
+ L_i = dia_array((data, [-1, 0, 1]), shape=(dim, dim),
459
+ dtype=np.int8
460
+ )
461
+
462
+ if self.boundary_conditions == 'periodic':
463
+ t = dia_array((dim, dim), dtype=np.int8)
464
+ t.setdiag([1], k=-dim+1)
465
+ t.setdiag([1], k=dim-1)
466
+ L_i += t
467
+
468
+ for j in range(i):
469
+ L_i = kron(eye(self.grid_shape[j], dtype=np.int8), L_i)
470
+ for j in range(i + 1, N):
471
+ L_i = kron(L_i, eye(self.grid_shape[j], dtype=np.int8))
472
+ L += L_i
473
+ return L.astype(self.dtype)
474
+
475
+ def _matvec(self, x):
476
+ grid_shape = self.grid_shape
477
+ N = len(grid_shape)
478
+ X = x.reshape(grid_shape + (-1,))
479
+ Y = -2 * N * X
480
+ for i in range(N):
481
+ Y += np.roll(X, 1, axis=i)
482
+ Y += np.roll(X, -1, axis=i)
483
+ if self.boundary_conditions in ('neumann', 'dirichlet'):
484
+ Y[(slice(None),)*i + (0,) + (slice(None),)*(N-i-1)
485
+ ] -= np.roll(X, 1, axis=i)[
486
+ (slice(None),) * i + (0,) + (slice(None),) * (N-i-1)
487
+ ]
488
+ Y[
489
+ (slice(None),) * i + (-1,) + (slice(None),) * (N-i-1)
490
+ ] -= np.roll(X, -1, axis=i)[
491
+ (slice(None),) * i + (-1,) + (slice(None),) * (N-i-1)
492
+ ]
493
+
494
+ if self.boundary_conditions == 'neumann':
495
+ Y[
496
+ (slice(None),) * i + (0,) + (slice(None),) * (N-i-1)
497
+ ] += np.roll(X, 0, axis=i)[
498
+ (slice(None),) * i + (0,) + (slice(None),) * (N-i-1)
499
+ ]
500
+ Y[
501
+ (slice(None),) * i + (-1,) + (slice(None),) * (N-i-1)
502
+ ] += np.roll(X, 0, axis=i)[
503
+ (slice(None),) * i + (-1,) + (slice(None),) * (N-i-1)
504
+ ]
505
+
506
+ return Y.reshape(-1, X.shape[-1])
507
+
508
+ def _matmat(self, x):
509
+ return self._matvec(x)
510
+
511
+ def _adjoint(self):
512
+ return self
513
+
514
+ def _transpose(self):
515
+ return self
516
+
517
+
518
+ class Sakurai(LinearOperator):
519
+ """
520
+ Construct a Sakurai matrix in various formats and its eigenvalues.
521
+
522
+ Constructs the "Sakurai" matrix motivated by reference [1]_:
523
+ square real symmetric positive definite and 5-diagonal
524
+ with the main diagonal ``[5, 6, 6, ..., 6, 6, 5], the ``+1`` and ``-1``
525
+ diagonals filled with ``-4``, and the ``+2`` and ``-2`` diagonals
526
+ made of ``1``. Its eigenvalues are analytically known to be
527
+ ``16. * np.power(np.cos(0.5 * k * np.pi / (n + 1)), 4)``.
528
+ The matrix gets ill-conditioned with its size growing.
529
+ It is useful for testing and benchmarking sparse eigenvalue solvers
530
+ especially those taking advantage of its banded 5-diagonal structure.
531
+ See the notes below for details.
532
+
533
+ Parameters
534
+ ----------
535
+ n : int
536
+ The size of the matrix.
537
+ dtype : dtype
538
+ Numerical type of the array. Default is ``np.int8``.
539
+
540
+ Methods
541
+ -------
542
+ toarray()
543
+ Construct a dense array from Laplacian data
544
+ tosparse()
545
+ Construct a sparse array from Laplacian data
546
+ tobanded()
547
+ The Sakurai matrix in the format for banded symmetric matrices,
548
+ i.e., (3, n) ndarray with 3 upper diagonals
549
+ placing the main diagonal at the bottom.
550
+ eigenvalues
551
+ All eigenvalues of the Sakurai matrix ordered ascending.
552
+
553
+ Notes
554
+ -----
555
+ Reference [1]_ introduces a generalized eigenproblem for the matrix pair
556
+ `A` and `B` where `A` is the identity so we turn it into an eigenproblem
557
+ just for the matrix `B` that this function outputs in various formats
558
+ together with its eigenvalues.
559
+
560
+ .. versionadded:: 1.12.0
561
+
562
+ References
563
+ ----------
564
+ .. [1] T. Sakurai, H. Tadano, Y. Inadomi, and U. Nagashima,
565
+ "A moment-based method for large-scale generalized
566
+ eigenvalue problems",
567
+ Appl. Num. Anal. Comp. Math. Vol. 1 No. 2 (2004).
568
+
569
+ Examples
570
+ --------
571
+ >>> import numpy as np
572
+ >>> from scipy.sparse.linalg._special_sparse_arrays import Sakurai
573
+ >>> from scipy.linalg import eig_banded
574
+ >>> n = 6
575
+ >>> sak = Sakurai(n)
576
+
577
+ Since all matrix entries are small integers, ``'int8'`` is
578
+ the default dtype for storing matrix representations.
579
+
580
+ >>> sak.toarray()
581
+ array([[ 5, -4, 1, 0, 0, 0],
582
+ [-4, 6, -4, 1, 0, 0],
583
+ [ 1, -4, 6, -4, 1, 0],
584
+ [ 0, 1, -4, 6, -4, 1],
585
+ [ 0, 0, 1, -4, 6, -4],
586
+ [ 0, 0, 0, 1, -4, 5]], dtype=int8)
587
+ >>> sak.tobanded()
588
+ array([[ 1, 1, 1, 1, 1, 1],
589
+ [-4, -4, -4, -4, -4, -4],
590
+ [ 5, 6, 6, 6, 6, 5]], dtype=int8)
591
+ >>> sak.tosparse()
592
+ <DIAgonal sparse array of dtype 'int8'
593
+ with 24 stored elements (5 diagonals) and shape (6, 6)>
594
+ >>> np.array_equal(sak.dot(np.eye(n)), sak.tosparse().toarray())
595
+ True
596
+ >>> sak.eigenvalues()
597
+ array([0.03922866, 0.56703972, 2.41789479, 5.97822974,
598
+ 10.54287655, 14.45473055])
599
+ >>> sak.eigenvalues(2)
600
+ array([0.03922866, 0.56703972])
601
+
602
+ The banded form can be used in scipy functions for banded matrices, e.g.,
603
+
604
+ >>> e = eig_banded(sak.tobanded(), eigvals_only=True)
605
+ >>> np.allclose(sak.eigenvalues, e, atol= n * n * n * np.finfo(float).eps)
606
+ True
607
+
608
+ """
609
+ def __init__(self, n, dtype=np.int8):
610
+ self.n = n
611
+ self.dtype = dtype
612
+ shape = (n, n)
613
+ super().__init__(dtype, shape)
614
+
615
+ def eigenvalues(self, m=None):
616
+ """Return the requested number of eigenvalues.
617
+
618
+ Parameters
619
+ ----------
620
+ m : int, optional
621
+ The positive number of smallest eigenvalues to return.
622
+ If not provided, then all eigenvalues will be returned.
623
+
624
+ Returns
625
+ -------
626
+ eigenvalues : `np.float64` array
627
+ The requested `m` smallest or all eigenvalues, in ascending order.
628
+ """
629
+ if m is None:
630
+ m = self.n
631
+ k = np.arange(self.n + 1 -m, self.n + 1)
632
+ return np.flip(16. * np.power(np.cos(0.5 * k * np.pi / (self.n + 1)), 4))
633
+
634
+ def tobanded(self):
635
+ """
636
+ Construct the Sakurai matrix as a banded array.
637
+ """
638
+ d0 = np.r_[5, 6 * np.ones(self.n - 2, dtype=self.dtype), 5]
639
+ d1 = -4 * np.ones(self.n, dtype=self.dtype)
640
+ d2 = np.ones(self.n, dtype=self.dtype)
641
+ return np.array([d2, d1, d0]).astype(self.dtype)
642
+
643
+ def tosparse(self):
644
+ """
645
+ Construct the Sakurai matrix is a sparse format.
646
+ """
647
+ from scipy.sparse import spdiags
648
+ d = self.tobanded()
649
+ # the banded format has the main diagonal at the bottom
650
+ # `spdiags` has no `dtype` parameter so inherits dtype from banded
651
+ return spdiags([d[0], d[1], d[2], d[1], d[0]], [-2, -1, 0, 1, 2],
652
+ self.n, self.n)
653
+
654
+ def toarray(self):
655
+ return self.tosparse().toarray()
656
+
657
+ def _matvec(self, x):
658
+ """
659
+ Construct matrix-free callable banded-matrix-vector multiplication by
660
+ the Sakurai matrix without constructing or storing the matrix itself
661
+ using the knowledge of its entries and the 5-diagonal format.
662
+ """
663
+ x = x.reshape(self.n, -1)
664
+ result_dtype = np.promote_types(x.dtype, self.dtype)
665
+ sx = np.zeros_like(x, dtype=result_dtype)
666
+ sx[0, :] = 5 * x[0, :] - 4 * x[1, :] + x[2, :]
667
+ sx[-1, :] = 5 * x[-1, :] - 4 * x[-2, :] + x[-3, :]
668
+ sx[1: -1, :] = (6 * x[1: -1, :] - 4 * (x[:-2, :] + x[2:, :])
669
+ + np.pad(x[:-3, :], ((1, 0), (0, 0)))
670
+ + np.pad(x[3:, :], ((0, 1), (0, 0))))
671
+ return sx
672
+
673
+ def _matmat(self, x):
674
+ """
675
+ Construct matrix-free callable matrix-matrix multiplication by
676
+ the Sakurai matrix without constructing or storing the matrix itself
677
+ by reusing the ``_matvec(x)`` that supports both 1D and 2D arrays ``x``.
678
+ """
679
+ return self._matvec(x)
680
+
681
+ def _adjoint(self):
682
+ return self
683
+
684
+ def _transpose(self):
685
+ return self
686
+
687
+
688
+ class MikotaM(LinearOperator):
689
+ """
690
+ Construct a mass matrix in various formats of Mikota pair.
691
+
692
+ The mass matrix `M` is square real diagonal
693
+ positive definite with entries that are reciprocal to integers.
694
+
695
+ Parameters
696
+ ----------
697
+ shape : tuple of int
698
+ The shape of the matrix.
699
+ dtype : dtype
700
+ Numerical type of the array. Default is ``np.float64``.
701
+
702
+ Methods
703
+ -------
704
+ toarray()
705
+ Construct a dense array from Mikota data
706
+ tosparse()
707
+ Construct a sparse array from Mikota data
708
+ tobanded()
709
+ The format for banded symmetric matrices,
710
+ i.e., (1, n) ndarray with the main diagonal.
711
+ """
712
+ def __init__(self, shape, dtype=np.float64):
713
+ self.shape = shape
714
+ self.dtype = dtype
715
+ super().__init__(dtype, shape)
716
+
717
+ def _diag(self):
718
+ # The matrix is constructed from its diagonal 1 / [1, ..., N+1];
719
+ # compute in a function to avoid duplicated code & storage footprint
720
+ return (1. / np.arange(1, self.shape[0] + 1)).astype(self.dtype)
721
+
722
+ def tobanded(self):
723
+ return self._diag()
724
+
725
+ def tosparse(self):
726
+ from scipy.sparse import diags
727
+ return diags([self._diag()], [0], shape=self.shape, dtype=self.dtype)
728
+
729
+ def toarray(self):
730
+ return np.diag(self._diag()).astype(self.dtype)
731
+
732
+ def _matvec(self, x):
733
+ """
734
+ Construct matrix-free callable banded-matrix-vector multiplication by
735
+ the Mikota mass matrix without constructing or storing the matrix itself
736
+ using the knowledge of its entries and the diagonal format.
737
+ """
738
+ x = x.reshape(self.shape[0], -1)
739
+ return self._diag()[:, np.newaxis] * x
740
+
741
+ def _matmat(self, x):
742
+ """
743
+ Construct matrix-free callable matrix-matrix multiplication by
744
+ the Mikota mass matrix without constructing or storing the matrix itself
745
+ by reusing the ``_matvec(x)`` that supports both 1D and 2D arrays ``x``.
746
+ """
747
+ return self._matvec(x)
748
+
749
+ def _adjoint(self):
750
+ return self
751
+
752
+ def _transpose(self):
753
+ return self
754
+
755
+
756
+ class MikotaK(LinearOperator):
757
+ """
758
+ Construct a stiffness matrix in various formats of Mikota pair.
759
+
760
+ The stiffness matrix `K` is square real tri-diagonal symmetric
761
+ positive definite with integer entries.
762
+
763
+ Parameters
764
+ ----------
765
+ shape : tuple of int
766
+ The shape of the matrix.
767
+ dtype : dtype
768
+ Numerical type of the array. Default is ``np.int32``.
769
+
770
+ Methods
771
+ -------
772
+ toarray()
773
+ Construct a dense array from Mikota data
774
+ tosparse()
775
+ Construct a sparse array from Mikota data
776
+ tobanded()
777
+ The format for banded symmetric matrices,
778
+ i.e., (2, n) ndarray with 2 upper diagonals
779
+ placing the main diagonal at the bottom.
780
+ """
781
+ def __init__(self, shape, dtype=np.int32):
782
+ self.shape = shape
783
+ self.dtype = dtype
784
+ super().__init__(dtype, shape)
785
+ # The matrix is constructed from its diagonals;
786
+ # we precompute these to avoid duplicating the computation
787
+ n = shape[0]
788
+ self._diag0 = np.arange(2 * n - 1, 0, -2, dtype=self.dtype)
789
+ self._diag1 = - np.arange(n - 1, 0, -1, dtype=self.dtype)
790
+
791
+ def tobanded(self):
792
+ return np.array([np.pad(self._diag1, (1, 0), 'constant'), self._diag0])
793
+
794
+ def tosparse(self):
795
+ from scipy.sparse import diags
796
+ return diags([self._diag1, self._diag0, self._diag1], [-1, 0, 1],
797
+ shape=self.shape, dtype=self.dtype)
798
+
799
+ def toarray(self):
800
+ return self.tosparse().toarray()
801
+
802
+ def _matvec(self, x):
803
+ """
804
+ Construct matrix-free callable banded-matrix-vector multiplication by
805
+ the Mikota stiffness matrix without constructing or storing the matrix
806
+ itself using the knowledge of its entries and the 3-diagonal format.
807
+ """
808
+ x = x.reshape(self.shape[0], -1)
809
+ result_dtype = np.promote_types(x.dtype, self.dtype)
810
+ kx = np.zeros_like(x, dtype=result_dtype)
811
+ d1 = self._diag1
812
+ d0 = self._diag0
813
+ kx[0, :] = d0[0] * x[0, :] + d1[0] * x[1, :]
814
+ kx[-1, :] = d1[-1] * x[-2, :] + d0[-1] * x[-1, :]
815
+ kx[1: -1, :] = (d1[:-1, None] * x[: -2, :]
816
+ + d0[1: -1, None] * x[1: -1, :]
817
+ + d1[1:, None] * x[2:, :])
818
+ return kx
819
+
820
+ def _matmat(self, x):
821
+ """
822
+ Construct matrix-free callable matrix-matrix multiplication by
823
+ the Stiffness mass matrix without constructing or storing the matrix itself
824
+ by reusing the ``_matvec(x)`` that supports both 1D and 2D arrays ``x``.
825
+ """
826
+ return self._matvec(x)
827
+
828
+ def _adjoint(self):
829
+ return self
830
+
831
+ def _transpose(self):
832
+ return self
833
+
834
+
835
+ class MikotaPair:
836
+ """
837
+ Construct the Mikota pair of matrices in various formats and
838
+ eigenvalues of the generalized eigenproblem with them.
839
+
840
+ The Mikota pair of matrices [1, 2]_ models a vibration problem
841
+ of a linear mass-spring system with the ends attached where
842
+ the stiffness of the springs and the masses increase along
843
+ the system length such that vibration frequencies are subsequent
844
+ integers 1, 2, ..., `n` where `n` is the number of the masses. Thus,
845
+ eigenvalues of the generalized eigenvalue problem for
846
+ the matrix pair `K` and `M` where `K` is the system stiffness matrix
847
+ and `M` is the system mass matrix are the squares of the integers,
848
+ i.e., 1, 4, 9, ..., ``n * n``.
849
+
850
+ The stiffness matrix `K` is square real tri-diagonal symmetric
851
+ positive definite. The mass matrix `M` is diagonal with diagonal
852
+ entries 1, 1/2, 1/3, ...., ``1/n``. Both matrices get
853
+ ill-conditioned with `n` growing.
854
+
855
+ Parameters
856
+ ----------
857
+ n : int
858
+ The size of the matrices of the Mikota pair.
859
+ dtype : dtype
860
+ Numerical type of the array. Default is ``np.float64``.
861
+
862
+ Attributes
863
+ ----------
864
+ eigenvalues : 1D ndarray, ``np.uint64``
865
+ All eigenvalues of the Mikota pair ordered ascending.
866
+
867
+ Methods
868
+ -------
869
+ MikotaK()
870
+ A `LinearOperator` custom object for the stiffness matrix.
871
+ MikotaM()
872
+ A `LinearOperator` custom object for the mass matrix.
873
+
874
+ .. versionadded:: 1.12.0
875
+
876
+ References
877
+ ----------
878
+ .. [1] J. Mikota, "Frequency tuning of chain structure multibody oscillators
879
+ to place the natural frequencies at omega1 and N-1 integer multiples
880
+ omega2,..., omegaN", Z. Angew. Math. Mech. 81 (2001), S2, S201-S202.
881
+ Appl. Num. Anal. Comp. Math. Vol. 1 No. 2 (2004).
882
+ .. [2] Peter C. Muller and Metin Gurgoze,
883
+ "Natural frequencies of a multi-degree-of-freedom vibration system",
884
+ Proc. Appl. Math. Mech. 6, 319-320 (2006).
885
+ http://dx.doi.org/10.1002/pamm.200610141.
886
+
887
+ Examples
888
+ --------
889
+ >>> import numpy as np
890
+ >>> from scipy.sparse.linalg._special_sparse_arrays import MikotaPair
891
+ >>> n = 6
892
+ >>> mik = MikotaPair(n)
893
+ >>> mik_k = mik.k
894
+ >>> mik_m = mik.m
895
+ >>> mik_k.toarray()
896
+ array([[11., -5., 0., 0., 0., 0.],
897
+ [-5., 9., -4., 0., 0., 0.],
898
+ [ 0., -4., 7., -3., 0., 0.],
899
+ [ 0., 0., -3., 5., -2., 0.],
900
+ [ 0., 0., 0., -2., 3., -1.],
901
+ [ 0., 0., 0., 0., -1., 1.]])
902
+ >>> mik_k.tobanded()
903
+ array([[ 0., -5., -4., -3., -2., -1.],
904
+ [11., 9., 7., 5., 3., 1.]])
905
+ >>> mik_m.tobanded()
906
+ array([1. , 0.5 , 0.33333333, 0.25 , 0.2 ,
907
+ 0.16666667])
908
+ >>> mik_k.tosparse()
909
+ <DIAgonal sparse array of dtype 'float64'
910
+ with 20 stored elements (3 diagonals) and shape (6, 6)>
911
+ >>> mik_m.tosparse()
912
+ <DIAgonal sparse array of dtype 'float64'
913
+ with 6 stored elements (1 diagonals) and shape (6, 6)>
914
+ >>> np.array_equal(mik_k(np.eye(n)), mik_k.toarray())
915
+ True
916
+ >>> np.array_equal(mik_m(np.eye(n)), mik_m.toarray())
917
+ True
918
+ >>> mik.eigenvalues()
919
+ array([ 1, 4, 9, 16, 25, 36])
920
+ >>> mik.eigenvalues(2)
921
+ array([ 1, 4])
922
+
923
+ """
924
+ def __init__(self, n, dtype=np.float64):
925
+ self.n = n
926
+ self.dtype = dtype
927
+ self.shape = (n, n)
928
+ self.m = MikotaM(self.shape, self.dtype)
929
+ self.k = MikotaK(self.shape, self.dtype)
930
+
931
+ def eigenvalues(self, m=None):
932
+ """Return the requested number of eigenvalues.
933
+
934
+ Parameters
935
+ ----------
936
+ m : int, optional
937
+ The positive number of smallest eigenvalues to return.
938
+ If not provided, then all eigenvalues will be returned.
939
+
940
+ Returns
941
+ -------
942
+ eigenvalues : `np.uint64` array
943
+ The requested `m` smallest or all eigenvalues, in ascending order.
944
+ """
945
+ if m is None:
946
+ m = self.n
947
+ arange_plus1 = np.arange(1, m + 1, dtype=np.uint64)
948
+ return arange_plus1 * arange_plus1
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/_svdp.py ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Python wrapper for PROPACK
3
+ --------------------------
4
+
5
+ PROPACK is a collection of Fortran routines for iterative computation
6
+ of partial SVDs of large matrices or linear operators.
7
+
8
+ Based on BSD licensed pypropack project:
9
+ http://github.com/jakevdp/pypropack
10
+ Author: Jake Vanderplas <vanderplas@astro.washington.edu>
11
+
12
+ PROPACK source is BSD licensed, and available at
13
+ http://soi.stanford.edu/~rmunk/PROPACK/
14
+ """
15
+
16
+ __all__ = ['_svdp']
17
+
18
+ import numpy as np
19
+
20
+ from scipy.sparse.linalg import aslinearoperator
21
+ from scipy.linalg import LinAlgError
22
+
23
+ from ._propack import _spropack # type: ignore[attr-defined]
24
+ from ._propack import _dpropack # type: ignore[attr-defined]
25
+ from ._propack import _cpropack # type: ignore[attr-defined]
26
+ from ._propack import _zpropack # type: ignore[attr-defined]
27
+
28
+
29
+ _lansvd_dict = {
30
+ 'f': _spropack.slansvd,
31
+ 'd': _dpropack.dlansvd,
32
+ 'F': _cpropack.clansvd,
33
+ 'D': _zpropack.zlansvd,
34
+ }
35
+
36
+
37
+ _lansvd_irl_dict = {
38
+ 'f': _spropack.slansvd_irl,
39
+ 'd': _dpropack.dlansvd_irl,
40
+ 'F': _cpropack.clansvd_irl,
41
+ 'D': _zpropack.zlansvd_irl,
42
+ }
43
+
44
+ _which_converter = {
45
+ 'LM': 'L',
46
+ 'SM': 'S',
47
+ }
48
+
49
+
50
+ class _AProd:
51
+ """
52
+ Wrapper class for linear operator
53
+
54
+ The call signature of the __call__ method matches the callback of
55
+ the PROPACK routines.
56
+ """
57
+ def __init__(self, A):
58
+ try:
59
+ self.A = aslinearoperator(A)
60
+ except TypeError:
61
+ self.A = aslinearoperator(np.asarray(A))
62
+
63
+ def __call__(self, transa, m, n, x, y, sparm, iparm):
64
+ if transa == 'n':
65
+ y[:] = self.A.matvec(x)
66
+ else:
67
+ y[:] = self.A.rmatvec(x)
68
+
69
+ @property
70
+ def shape(self):
71
+ return self.A.shape
72
+
73
+ @property
74
+ def dtype(self):
75
+ try:
76
+ return self.A.dtype
77
+ except AttributeError:
78
+ return self.A.matvec(np.zeros(self.A.shape[1])).dtype
79
+
80
+
81
+ def _svdp(A, k, which='LM', irl_mode=True, kmax=None,
82
+ compute_u=True, compute_v=True, v0=None, full_output=False, tol=0,
83
+ delta=None, eta=None, anorm=0, cgs=False, elr=True,
84
+ min_relgap=0.002, shifts=None, maxiter=None, rng=None):
85
+ """
86
+ Compute the singular value decomposition of a linear operator using PROPACK
87
+
88
+ Parameters
89
+ ----------
90
+ A : array_like, sparse matrix, or LinearOperator
91
+ Operator for which SVD will be computed. If `A` is a LinearOperator
92
+ object, it must define both ``matvec`` and ``rmatvec`` methods.
93
+ k : int
94
+ Number of singular values/vectors to compute
95
+ which : {"LM", "SM"}
96
+ Which singular triplets to compute:
97
+ - 'LM': compute triplets corresponding to the `k` largest singular
98
+ values
99
+ - 'SM': compute triplets corresponding to the `k` smallest singular
100
+ values
101
+ `which='SM'` requires `irl_mode=True`. Computes largest singular
102
+ values by default.
103
+ irl_mode : bool, optional
104
+ If `True`, then compute SVD using IRL (implicitly restarted Lanczos)
105
+ mode. Default is `True`.
106
+ kmax : int, optional
107
+ Maximal number of iterations / maximal dimension of the Krylov
108
+ subspace. Default is ``10 * k``.
109
+ compute_u : bool, optional
110
+ If `True` (default) then compute left singular vectors, `u`.
111
+ compute_v : bool, optional
112
+ If `True` (default) then compute right singular vectors, `v`.
113
+ tol : float, optional
114
+ The desired relative accuracy for computed singular values.
115
+ If not specified, it will be set based on machine precision.
116
+ v0 : array_like, optional
117
+ Starting vector for iterations: must be of length ``A.shape[0]``.
118
+ If not specified, PROPACK will generate a starting vector.
119
+ full_output : bool, optional
120
+ If `True`, then return sigma_bound. Default is `False`.
121
+ delta : float, optional
122
+ Level of orthogonality to maintain between Lanczos vectors.
123
+ Default is set based on machine precision.
124
+ eta : float, optional
125
+ Orthogonality cutoff. During reorthogonalization, vectors with
126
+ component larger than `eta` along the Lanczos vector will be purged.
127
+ Default is set based on machine precision.
128
+ anorm : float, optional
129
+ Estimate of ``||A||``. Default is ``0``.
130
+ cgs : bool, optional
131
+ If `True`, reorthogonalization is done using classical Gram-Schmidt.
132
+ If `False` (default), it is done using modified Gram-Schmidt.
133
+ elr : bool, optional
134
+ If `True` (default), then extended local orthogonality is enforced
135
+ when obtaining singular vectors.
136
+ min_relgap : float, optional
137
+ The smallest relative gap allowed between any shift in IRL mode.
138
+ Default is ``0.001``. Accessed only if ``irl_mode=True``.
139
+ shifts : int, optional
140
+ Number of shifts per restart in IRL mode. Default is determined
141
+ to satisfy ``k <= min(kmax-shifts, m, n)``. Must be
142
+ >= 0, but choosing 0 might lead to performance degradation.
143
+ Accessed only if ``irl_mode=True``.
144
+ maxiter : int, optional
145
+ Maximum number of restarts in IRL mode. Default is ``1000``.
146
+ Accessed only if ``irl_mode=True``.
147
+ rng : `numpy.random.Generator`, optional
148
+ Pseudorandom number generator state. When `rng` is None, a new
149
+ `numpy.random.Generator` is created using entropy from the
150
+ operating system. Types other than `numpy.random.Generator` are
151
+ passed to `numpy.random.default_rng` to instantiate a ``Generator``.
152
+
153
+ Returns
154
+ -------
155
+ u : ndarray
156
+ The `k` largest (``which="LM"``) or smallest (``which="SM"``) left
157
+ singular vectors, ``shape == (A.shape[0], 3)``, returned only if
158
+ ``compute_u=True``.
159
+ sigma : ndarray
160
+ The top `k` singular values, ``shape == (k,)``
161
+ vt : ndarray
162
+ The `k` largest (``which="LM"``) or smallest (``which="SM"``) right
163
+ singular vectors, ``shape == (3, A.shape[1])``, returned only if
164
+ ``compute_v=True``.
165
+ sigma_bound : ndarray
166
+ the error bounds on the singular values sigma, returned only if
167
+ ``full_output=True``.
168
+
169
+ """
170
+ if rng is None:
171
+ raise ValueError("`rng` must be a normalized numpy.random.Generator instance")
172
+
173
+ which = which.upper()
174
+ if which not in {'LM', 'SM'}:
175
+ raise ValueError("`which` must be either 'LM' or 'SM'")
176
+ if not irl_mode and which == 'SM':
177
+ raise ValueError("`which`='SM' requires irl_mode=True")
178
+
179
+ aprod = _AProd(A)
180
+ typ = aprod.dtype.char
181
+
182
+ try:
183
+ lansvd_irl = _lansvd_irl_dict[typ]
184
+ lansvd = _lansvd_dict[typ]
185
+ except KeyError:
186
+ # work with non-supported types using native system precision
187
+ if np.iscomplexobj(np.empty(0, dtype=typ)):
188
+ typ = np.dtype(complex).char
189
+ else:
190
+ typ = np.dtype(float).char
191
+ lansvd_irl = _lansvd_irl_dict[typ]
192
+ lansvd = _lansvd_dict[typ]
193
+
194
+ m, n = aprod.shape
195
+ if (k < 1) or (k > min(m, n)):
196
+ raise ValueError("k must be positive and not greater than m or n")
197
+
198
+ if kmax is None:
199
+ kmax = 10*k
200
+ if maxiter is None:
201
+ maxiter = 1000
202
+
203
+ # guard against unnecessarily large kmax
204
+ kmax = min(m + 1, n + 1, kmax)
205
+ if kmax < k:
206
+ raise ValueError(
207
+ "kmax must be greater than or equal to k, "
208
+ f"but kmax ({kmax}) < k ({k})")
209
+
210
+ # convert python args to fortran args
211
+ jobu = 'y' if compute_u else 'n'
212
+ jobv = 'y' if compute_v else 'n'
213
+
214
+ # these will be the output arrays
215
+ u = np.zeros((m, kmax + 1), order='F', dtype=typ)
216
+ v = np.zeros((n, kmax), order='F', dtype=typ)
217
+
218
+ # Specify the starting vector. if v0 is all zero, PROPACK will generate
219
+ # a random starting vector: the random seed cannot be controlled in that
220
+ # case, so we'll instead use numpy to generate a random vector
221
+ if v0 is None:
222
+ u[:, 0] = rng.uniform(size=m)
223
+ if np.iscomplexobj(np.empty(0, dtype=typ)): # complex type
224
+ u[:, 0] += 1j * rng.uniform(size=m)
225
+ else:
226
+ try:
227
+ u[:, 0] = v0
228
+ except ValueError:
229
+ raise ValueError(f"v0 must be of length {m}")
230
+
231
+ # process options for the fit
232
+ if delta is None:
233
+ delta = np.sqrt(np.finfo(typ).eps)
234
+ if eta is None:
235
+ eta = np.finfo(typ).eps ** 0.75
236
+
237
+ if irl_mode:
238
+ doption = np.array((delta, eta, anorm, min_relgap), dtype=typ.lower())
239
+
240
+ # validate or find default shifts
241
+ if shifts is None:
242
+ shifts = kmax - k
243
+ if k > min(kmax - shifts, m, n):
244
+ raise ValueError('shifts must satisfy '
245
+ 'k <= min(kmax-shifts, m, n)!')
246
+ elif shifts < 0:
247
+ raise ValueError('shifts must be >= 0!')
248
+
249
+ else:
250
+ doption = np.array((delta, eta, anorm), dtype=typ.lower())
251
+
252
+ ioption = np.array((int(bool(cgs)), int(bool(elr))), dtype='i')
253
+
254
+ # If computing `u` or `v` (left and right singular vectors,
255
+ # respectively), `blocksize` controls how large a fraction of the
256
+ # work is done via fast BLAS level 3 operations. A larger blocksize
257
+ # may lead to faster computation at the expense of greater memory
258
+ # consumption. `blocksize` must be ``>= 1``. Choosing blocksize
259
+ # of 16, but docs don't specify; it's almost surely a
260
+ # power of 2.
261
+ blocksize = 16
262
+
263
+ # Determine lwork & liwork:
264
+ # the required lengths are specified in the PROPACK documentation
265
+ if compute_u or compute_v:
266
+ lwork = m + n + 9*kmax + 5*kmax*kmax + 4 + max(
267
+ 3*kmax*kmax + 4*kmax + 4,
268
+ blocksize*max(m, n))
269
+ liwork = 8*kmax
270
+ else:
271
+ lwork = m + n + 9*kmax + 2*kmax*kmax + 4 + max(m + n, 4*kmax + 4)
272
+ liwork = 2*kmax + 1
273
+ work = np.empty(lwork, dtype=typ.lower())
274
+ iwork = np.empty(liwork, dtype=np.int32)
275
+
276
+ # dummy arguments: these are passed to aprod, and not used in this wrapper
277
+ dparm = np.empty(1, dtype=typ.lower())
278
+ iparm = np.empty(1, dtype=np.int32)
279
+
280
+ if typ.isupper():
281
+ # PROPACK documentation is unclear on the required length of zwork.
282
+ # Use the same length Julia's wrapper uses
283
+ # see https://github.com/JuliaSmoothOptimizers/PROPACK.jl/
284
+ zwork = np.empty(m + n + 32*m, dtype=typ)
285
+ works = work, zwork, iwork
286
+ else:
287
+ works = work, iwork
288
+
289
+ if irl_mode:
290
+ u, sigma, bnd, v, info = lansvd_irl(_which_converter[which], jobu,
291
+ jobv, m, n, shifts, k, maxiter,
292
+ aprod, u, v, tol, *works, doption,
293
+ ioption, dparm, iparm)
294
+ else:
295
+ u, sigma, bnd, v, info = lansvd(jobu, jobv, m, n, k, aprod, u, v, tol,
296
+ *works, doption, ioption, dparm, iparm)
297
+
298
+ if info > 0:
299
+ raise LinAlgError(
300
+ f"An invariant subspace of dimension {info} was found.")
301
+ elif info < 0:
302
+ raise LinAlgError(
303
+ f"k={k} singular triplets did not converge within "
304
+ f"kmax={kmax} iterations")
305
+
306
+ # info == 0: The K largest (or smallest) singular triplets were computed
307
+ # successfully!
308
+
309
+ return u[:, :k], sigma, v[:, :k].conj().T, bnd
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/dsolve.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+ # Use the `scipy.sparse.linalg` namespace for importing the functions
3
+ # included below.
4
+
5
+ from scipy._lib.deprecation import _sub_module_deprecation
6
+
7
+
8
+ __all__ = [ # noqa: F822
9
+ 'MatrixRankWarning', 'SuperLU', 'factorized',
10
+ 'spilu', 'splu', 'spsolve',
11
+ 'spsolve_triangular', 'use_solver', 'test'
12
+ ]
13
+
14
+
15
+ def __dir__():
16
+ return __all__
17
+
18
+
19
+ def __getattr__(name):
20
+ return _sub_module_deprecation(sub_package="sparse.linalg", module="dsolve",
21
+ private_modules=["_dsolve"], all=__all__,
22
+ attribute=name)
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/eigen.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+ # Use the `scipy.sparse.linalg` namespace for importing the functions
3
+ # included below.
4
+
5
+ from scipy._lib.deprecation import _sub_module_deprecation
6
+
7
+
8
+ __all__ = [ # noqa: F822
9
+ 'ArpackError', 'ArpackNoConvergence', 'ArpackError',
10
+ 'eigs', 'eigsh', 'lobpcg', 'svds', 'test'
11
+ ]
12
+
13
+
14
+ def __dir__():
15
+ return __all__
16
+
17
+
18
+ def __getattr__(name):
19
+ return _sub_module_deprecation(sub_package="sparse.linalg", module="eigen",
20
+ private_modules=["_eigen"], all=__all__,
21
+ attribute=name)
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/interface.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+ # Use the `scipy.sparse.linalg` namespace for importing the functions
3
+ # included below.
4
+
5
+ from scipy._lib.deprecation import _sub_module_deprecation
6
+
7
+
8
+ __all__ = [ # noqa: F822
9
+ 'LinearOperator', 'aslinearoperator',
10
+ ]
11
+
12
+
13
+ def __dir__():
14
+ return __all__
15
+
16
+
17
+ def __getattr__(name):
18
+ return _sub_module_deprecation(sub_package="sparse.linalg", module="interface",
19
+ private_modules=["_interface"], all=__all__,
20
+ attribute=name)
miniconda3/envs/ladir/lib/python3.10/site-packages/scipy/sparse/linalg/isolve.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+ # Use the `scipy.sparse.linalg` namespace for importing the functions
3
+ # included below.
4
+
5
+ from scipy._lib.deprecation import _sub_module_deprecation
6
+
7
+
8
+ __all__ = [ # noqa: F822
9
+ 'bicg', 'bicgstab', 'cg', 'cgs', 'gcrotmk', 'gmres',
10
+ 'lgmres', 'lsmr', 'lsqr',
11
+ 'minres', 'qmr', 'tfqmr', 'test'
12
+ ]
13
+
14
+
15
+ def __dir__():
16
+ return __all__
17
+
18
+
19
+ def __getattr__(name):
20
+ return _sub_module_deprecation(sub_package="sparse.linalg", module="isolve",
21
+ private_modules=["_isolve"], all=__all__,
22
+ attribute=name)