Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- ckpts/universal/global_step40/zero/3.mlp.dense_4h_to_h.weight/exp_avg.pt +3 -0
- ckpts/universal/global_step40/zero/3.mlp.dense_4h_to_h.weight/exp_avg_sq.pt +3 -0
- ckpts/universal/global_step40/zero/3.mlp.dense_4h_to_h.weight/fp32.pt +3 -0
- ckpts/universal/global_step40/zero/7.mlp.dense_h_to_4h_swiglu.weight/exp_avg_sq.pt +3 -0
- ckpts/universal/global_step40/zero/7.mlp.dense_h_to_4h_swiglu.weight/fp32.pt +3 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/_expm_multiply.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/_interface.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/_matfuncs.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/_norm.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/_onenormest.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/_special_sparse_arrays.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/_svdp.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/dsolve.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/eigen.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/interface.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/isolve.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/matfuncs.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/__init__.py +22 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/__pycache__/_svds.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/__pycache__/_svds_doc.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/_svds.py +545 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/_svds_doc.py +400 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__init__.py +20 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/_gcrotmk.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/iterative.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/lgmres.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/lsmr.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/lsqr.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/minres.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/tfqmr.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/utils.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/_gcrotmk.py +514 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/iterative.py +1079 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/lgmres.py +242 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/lsmr.py +486 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/lsqr.py +587 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/minres.py +387 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/__init__.py +0 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/__pycache__/test_gcrotmk.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/__pycache__/test_iterative.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/__pycache__/test_lgmres.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/__pycache__/test_lsmr.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/__pycache__/test_lsqr.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/__pycache__/test_minres.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/__pycache__/test_utils.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_gcrotmk.py +165 -0
- venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_iterative.py +796 -0
ckpts/universal/global_step40/zero/3.mlp.dense_4h_to_h.weight/exp_avg.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:6cf9886c29a60bea162941ed95b811b590fcfe2f3600a80177a568bba80242f9
|
3 |
+
size 33555612
|
ckpts/universal/global_step40/zero/3.mlp.dense_4h_to_h.weight/exp_avg_sq.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:f9b0fc6bb399344b8c1be23e4a5b91e6a5f1740b74edca0c5813101d93aae626
|
3 |
+
size 33555627
|
ckpts/universal/global_step40/zero/3.mlp.dense_4h_to_h.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b065ab03d6cf9b470ca9f83dae3099a901d8ec757d40cd792d5c0b1de059cbc2
|
3 |
+
size 33555533
|
ckpts/universal/global_step40/zero/7.mlp.dense_h_to_4h_swiglu.weight/exp_avg_sq.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:9005b50ac0ede1b142a63ed1f03953c3f1ab09a296512032875222091e1aa798
|
3 |
+
size 33555627
|
ckpts/universal/global_step40/zero/7.mlp.dense_h_to_4h_swiglu.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:2645d5e4c31f303c55f3272c294e521f2a05f4c0ff728cc52fe7638b582f4ec2
|
3 |
+
size 33555533
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (4.27 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/_expm_multiply.cpython-310.pyc
ADDED
Binary file (23.1 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/_interface.cpython-310.pyc
ADDED
Binary file (30 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/_matfuncs.cpython-310.pyc
ADDED
Binary file (25.5 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/_norm.cpython-310.pyc
ADDED
Binary file (5.07 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/_onenormest.cpython-310.pyc
ADDED
Binary file (11.9 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/_special_sparse_arrays.cpython-310.pyc
ADDED
Binary file (33.9 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/_svdp.cpython-310.pyc
ADDED
Binary file (9.19 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/dsolve.cpython-310.pyc
ADDED
Binary file (745 Bytes). View file
|
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/eigen.cpython-310.pyc
ADDED
Binary file (711 Bytes). View file
|
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/interface.cpython-310.pyc
ADDED
Binary file (739 Bytes). View file
|
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/isolve.cpython-310.pyc
ADDED
Binary file (711 Bytes). View file
|
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/matfuncs.cpython-310.pyc
ADDED
Binary file (749 Bytes). View file
|
|
venv/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
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/__pycache__/_svds.cpython-310.pyc
ADDED
Binary file (17.3 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/__pycache__/_svds_doc.cpython-310.pyc
ADDED
Binary file (15.8 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/_svds.py
ADDED
@@ -0,0 +1,545 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
|
3 |
+
from .arpack import _arpack # type: ignore[attr-defined]
|
4 |
+
from . import eigsh
|
5 |
+
|
6 |
+
from scipy._lib._util import check_random_state
|
7 |
+
from scipy.sparse.linalg._interface import LinearOperator, aslinearoperator
|
8 |
+
from scipy.sparse.linalg._eigen.lobpcg import lobpcg # type: ignore[no-redef]
|
9 |
+
from scipy.sparse.linalg._svdp import _svdp
|
10 |
+
from scipy.linalg import svd
|
11 |
+
|
12 |
+
arpack_int = _arpack.timing.nbx.dtype
|
13 |
+
__all__ = ['svds']
|
14 |
+
|
15 |
+
|
16 |
+
def _herm(x):
|
17 |
+
return x.T.conj()
|
18 |
+
|
19 |
+
|
20 |
+
def _iv(A, k, ncv, tol, which, v0, maxiter,
|
21 |
+
return_singular, solver, random_state):
|
22 |
+
|
23 |
+
# input validation/standardization for `solver`
|
24 |
+
# out of order because it's needed for other parameters
|
25 |
+
solver = str(solver).lower()
|
26 |
+
solvers = {"arpack", "lobpcg", "propack"}
|
27 |
+
if solver not in solvers:
|
28 |
+
raise ValueError(f"solver must be one of {solvers}.")
|
29 |
+
|
30 |
+
# input validation/standardization for `A`
|
31 |
+
A = aslinearoperator(A) # this takes care of some input validation
|
32 |
+
if not (np.issubdtype(A.dtype, np.complexfloating)
|
33 |
+
or np.issubdtype(A.dtype, np.floating)):
|
34 |
+
message = "`A` must be of floating or complex floating data type."
|
35 |
+
raise ValueError(message)
|
36 |
+
if np.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 |
+
random_state = check_random_state(random_state)
|
94 |
+
|
95 |
+
return (A, k, ncv, tol, which, v0, maxiter,
|
96 |
+
return_singular, solver, random_state)
|
97 |
+
|
98 |
+
|
99 |
+
def svds(A, k=6, ncv=None, tol=0, which='LM', v0=None,
|
100 |
+
maxiter=None, return_singular_vectors=True,
|
101 |
+
solver='arpack', random_state=None, options=None):
|
102 |
+
"""
|
103 |
+
Partial singular value decomposition of a sparse matrix.
|
104 |
+
|
105 |
+
Compute the largest or smallest `k` singular values and corresponding
|
106 |
+
singular vectors of a sparse matrix `A`. The order in which the singular
|
107 |
+
values are returned is not guaranteed.
|
108 |
+
|
109 |
+
In the descriptions below, let ``M, N = A.shape``.
|
110 |
+
|
111 |
+
Parameters
|
112 |
+
----------
|
113 |
+
A : ndarray, sparse matrix, or LinearOperator
|
114 |
+
Matrix to decompose of a floating point numeric dtype.
|
115 |
+
k : int, default: 6
|
116 |
+
Number of singular values and singular vectors to compute.
|
117 |
+
Must satisfy ``1 <= k <= kmax``, where ``kmax=min(M, N)`` for
|
118 |
+
``solver='propack'`` and ``kmax=min(M, N) - 1`` otherwise.
|
119 |
+
ncv : int, optional
|
120 |
+
When ``solver='arpack'``, this is the number of Lanczos vectors
|
121 |
+
generated. See :ref:`'arpack' <sparse.linalg.svds-arpack>` for details.
|
122 |
+
When ``solver='lobpcg'`` or ``solver='propack'``, this parameter is
|
123 |
+
ignored.
|
124 |
+
tol : float, optional
|
125 |
+
Tolerance for singular values. Zero (default) means machine precision.
|
126 |
+
which : {'LM', 'SM'}
|
127 |
+
Which `k` singular values to find: either the largest magnitude ('LM')
|
128 |
+
or smallest magnitude ('SM') singular values.
|
129 |
+
v0 : ndarray, optional
|
130 |
+
The starting vector for iteration; see method-specific
|
131 |
+
documentation (:ref:`'arpack' <sparse.linalg.svds-arpack>`,
|
132 |
+
:ref:`'lobpcg' <sparse.linalg.svds-lobpcg>`), or
|
133 |
+
:ref:`'propack' <sparse.linalg.svds-propack>` for details.
|
134 |
+
maxiter : int, optional
|
135 |
+
Maximum number of iterations; see method-specific
|
136 |
+
documentation (:ref:`'arpack' <sparse.linalg.svds-arpack>`,
|
137 |
+
:ref:`'lobpcg' <sparse.linalg.svds-lobpcg>`), or
|
138 |
+
:ref:`'propack' <sparse.linalg.svds-propack>` for details.
|
139 |
+
return_singular_vectors : {True, False, "u", "vh"}
|
140 |
+
Singular values are always computed and returned; this parameter
|
141 |
+
controls the computation and return of singular vectors.
|
142 |
+
|
143 |
+
- ``True``: return singular vectors.
|
144 |
+
- ``False``: do not return singular vectors.
|
145 |
+
- ``"u"``: if ``M <= N``, compute only the left singular vectors and
|
146 |
+
return ``None`` for the right singular vectors. Otherwise, compute
|
147 |
+
all singular vectors.
|
148 |
+
- ``"vh"``: if ``M > N``, compute only the right singular vectors and
|
149 |
+
return ``None`` for the left singular vectors. Otherwise, compute
|
150 |
+
all singular vectors.
|
151 |
+
|
152 |
+
If ``solver='propack'``, the option is respected regardless of the
|
153 |
+
matrix shape.
|
154 |
+
|
155 |
+
solver : {'arpack', 'propack', 'lobpcg'}, optional
|
156 |
+
The solver used.
|
157 |
+
:ref:`'arpack' <sparse.linalg.svds-arpack>`,
|
158 |
+
:ref:`'lobpcg' <sparse.linalg.svds-lobpcg>`, and
|
159 |
+
:ref:`'propack' <sparse.linalg.svds-propack>` are supported.
|
160 |
+
Default: `'arpack'`.
|
161 |
+
random_state : {None, int, `numpy.random.Generator`,
|
162 |
+
`numpy.random.RandomState`}, optional
|
163 |
+
|
164 |
+
Pseudorandom number generator state used to generate resamples.
|
165 |
+
|
166 |
+
If `random_state` is ``None`` (or `np.random`), the
|
167 |
+
`numpy.random.RandomState` singleton is used.
|
168 |
+
If `random_state` is an int, a new ``RandomState`` instance is used,
|
169 |
+
seeded with `random_state`.
|
170 |
+
If `random_state` is already a ``Generator`` or ``RandomState``
|
171 |
+
instance then that instance is used.
|
172 |
+
options : dict, optional
|
173 |
+
A dictionary of solver-specific options. No solver-specific options
|
174 |
+
are currently supported; this parameter is reserved for future use.
|
175 |
+
|
176 |
+
Returns
|
177 |
+
-------
|
178 |
+
u : ndarray, shape=(M, k)
|
179 |
+
Unitary matrix having left singular vectors as columns.
|
180 |
+
s : ndarray, shape=(k,)
|
181 |
+
The singular values.
|
182 |
+
vh : ndarray, shape=(k, N)
|
183 |
+
Unitary matrix having right singular vectors as rows.
|
184 |
+
|
185 |
+
Notes
|
186 |
+
-----
|
187 |
+
This is a naive implementation using ARPACK or LOBPCG as an eigensolver
|
188 |
+
on the matrix ``A.conj().T @ A`` or ``A @ A.conj().T``, depending on
|
189 |
+
which one is smaller size, followed by the Rayleigh-Ritz method
|
190 |
+
as postprocessing; see
|
191 |
+
Using the normal matrix, in Rayleigh-Ritz method, (2022, Nov. 19),
|
192 |
+
Wikipedia, https://w.wiki/4zms.
|
193 |
+
|
194 |
+
Alternatively, the PROPACK solver can be called.
|
195 |
+
|
196 |
+
Choices of the input matrix `A` numeric dtype may be limited.
|
197 |
+
Only ``solver="lobpcg"`` supports all floating point dtypes
|
198 |
+
real: 'np.float32', 'np.float64', 'np.longdouble' and
|
199 |
+
complex: 'np.complex64', 'np.complex128', 'np.clongdouble'.
|
200 |
+
The ``solver="arpack"`` supports only
|
201 |
+
'np.float32', 'np.float64', and 'np.complex128'.
|
202 |
+
|
203 |
+
Examples
|
204 |
+
--------
|
205 |
+
Construct a matrix `A` from singular values and vectors.
|
206 |
+
|
207 |
+
>>> import numpy as np
|
208 |
+
>>> from scipy import sparse, linalg, stats
|
209 |
+
>>> from scipy.sparse.linalg import svds, aslinearoperator, LinearOperator
|
210 |
+
|
211 |
+
Construct a dense matrix `A` from singular values and vectors.
|
212 |
+
|
213 |
+
>>> rng = np.random.default_rng(258265244568965474821194062361901728911)
|
214 |
+
>>> orthogonal = stats.ortho_group.rvs(10, random_state=rng)
|
215 |
+
>>> s = [1e-3, 1, 2, 3, 4] # non-zero singular values
|
216 |
+
>>> u = orthogonal[:, :5] # left singular vectors
|
217 |
+
>>> vT = orthogonal[:, 5:].T # right singular vectors
|
218 |
+
>>> A = u @ np.diag(s) @ vT
|
219 |
+
|
220 |
+
With only four singular values/vectors, the SVD approximates the original
|
221 |
+
matrix.
|
222 |
+
|
223 |
+
>>> u4, s4, vT4 = svds(A, k=4)
|
224 |
+
>>> A4 = u4 @ np.diag(s4) @ vT4
|
225 |
+
>>> np.allclose(A4, A, atol=1e-3)
|
226 |
+
True
|
227 |
+
|
228 |
+
With all five non-zero singular values/vectors, we can reproduce
|
229 |
+
the original matrix more accurately.
|
230 |
+
|
231 |
+
>>> u5, s5, vT5 = svds(A, k=5)
|
232 |
+
>>> A5 = u5 @ np.diag(s5) @ vT5
|
233 |
+
>>> np.allclose(A5, A)
|
234 |
+
True
|
235 |
+
|
236 |
+
The singular values match the expected singular values.
|
237 |
+
|
238 |
+
>>> np.allclose(s5, s)
|
239 |
+
True
|
240 |
+
|
241 |
+
Since the singular values are not close to each other in this example,
|
242 |
+
every singular vector matches as expected up to a difference in sign.
|
243 |
+
|
244 |
+
>>> (np.allclose(np.abs(u5), np.abs(u)) and
|
245 |
+
... np.allclose(np.abs(vT5), np.abs(vT)))
|
246 |
+
True
|
247 |
+
|
248 |
+
The singular vectors are also orthogonal.
|
249 |
+
|
250 |
+
>>> (np.allclose(u5.T @ u5, np.eye(5)) and
|
251 |
+
... np.allclose(vT5 @ vT5.T, np.eye(5)))
|
252 |
+
True
|
253 |
+
|
254 |
+
If there are (nearly) multiple singular values, the corresponding
|
255 |
+
individual singular vectors may be unstable, but the whole invariant
|
256 |
+
subspace containing all such singular vectors is computed accurately
|
257 |
+
as can be measured by angles between subspaces via 'subspace_angles'.
|
258 |
+
|
259 |
+
>>> rng = np.random.default_rng(178686584221410808734965903901790843963)
|
260 |
+
>>> s = [1, 1 + 1e-6] # non-zero singular values
|
261 |
+
>>> u, _ = np.linalg.qr(rng.standard_normal((99, 2)))
|
262 |
+
>>> v, _ = np.linalg.qr(rng.standard_normal((99, 2)))
|
263 |
+
>>> vT = v.T
|
264 |
+
>>> A = u @ np.diag(s) @ vT
|
265 |
+
>>> A = A.astype(np.float32)
|
266 |
+
>>> u2, s2, vT2 = svds(A, k=2, random_state=rng)
|
267 |
+
>>> np.allclose(s2, s)
|
268 |
+
True
|
269 |
+
|
270 |
+
The angles between the individual exact and computed singular vectors
|
271 |
+
may not be so small. To check use:
|
272 |
+
|
273 |
+
>>> (linalg.subspace_angles(u2[:, :1], u[:, :1]) +
|
274 |
+
... linalg.subspace_angles(u2[:, 1:], u[:, 1:]))
|
275 |
+
array([0.06562513]) # may vary
|
276 |
+
>>> (linalg.subspace_angles(vT2[:1, :].T, vT[:1, :].T) +
|
277 |
+
... linalg.subspace_angles(vT2[1:, :].T, vT[1:, :].T))
|
278 |
+
array([0.06562507]) # may vary
|
279 |
+
|
280 |
+
As opposed to the angles between the 2-dimensional invariant subspaces
|
281 |
+
that these vectors span, which are small for rights singular vectors
|
282 |
+
|
283 |
+
>>> linalg.subspace_angles(u2, u).sum() < 1e-6
|
284 |
+
True
|
285 |
+
|
286 |
+
as well as for left singular vectors.
|
287 |
+
|
288 |
+
>>> linalg.subspace_angles(vT2.T, vT.T).sum() < 1e-6
|
289 |
+
True
|
290 |
+
|
291 |
+
The next example follows that of 'sklearn.decomposition.TruncatedSVD'.
|
292 |
+
|
293 |
+
>>> rng = np.random.RandomState(0)
|
294 |
+
>>> X_dense = rng.random(size=(100, 100))
|
295 |
+
>>> X_dense[:, 2 * np.arange(50)] = 0
|
296 |
+
>>> X = sparse.csr_matrix(X_dense)
|
297 |
+
>>> _, singular_values, _ = svds(X, k=5, random_state=rng)
|
298 |
+
>>> print(singular_values)
|
299 |
+
[ 4.3293... 4.4491... 4.5420... 4.5987... 35.2410...]
|
300 |
+
|
301 |
+
The function can be called without the transpose of the input matrix
|
302 |
+
ever explicitly constructed.
|
303 |
+
|
304 |
+
>>> rng = np.random.default_rng(102524723947864966825913730119128190974)
|
305 |
+
>>> G = sparse.rand(8, 9, density=0.5, random_state=rng)
|
306 |
+
>>> Glo = aslinearoperator(G)
|
307 |
+
>>> _, singular_values_svds, _ = svds(Glo, k=5, random_state=rng)
|
308 |
+
>>> _, singular_values_svd, _ = linalg.svd(G.toarray())
|
309 |
+
>>> np.allclose(singular_values_svds, singular_values_svd[-4::-1])
|
310 |
+
True
|
311 |
+
|
312 |
+
The most memory efficient scenario is where neither
|
313 |
+
the original matrix, nor its transpose, is explicitly constructed.
|
314 |
+
Our example computes the smallest singular values and vectors
|
315 |
+
of 'LinearOperator' constructed from the numpy function 'np.diff' used
|
316 |
+
column-wise to be consistent with 'LinearOperator' operating on columns.
|
317 |
+
|
318 |
+
>>> diff0 = lambda a: np.diff(a, axis=0)
|
319 |
+
|
320 |
+
Let us create the matrix from 'diff0' to be used for validation only.
|
321 |
+
|
322 |
+
>>> n = 5 # The dimension of the space.
|
323 |
+
>>> M_from_diff0 = diff0(np.eye(n))
|
324 |
+
>>> print(M_from_diff0.astype(int))
|
325 |
+
[[-1 1 0 0 0]
|
326 |
+
[ 0 -1 1 0 0]
|
327 |
+
[ 0 0 -1 1 0]
|
328 |
+
[ 0 0 0 -1 1]]
|
329 |
+
|
330 |
+
The matrix 'M_from_diff0' is bi-diagonal and could be alternatively
|
331 |
+
created directly by
|
332 |
+
|
333 |
+
>>> M = - np.eye(n - 1, n, dtype=int)
|
334 |
+
>>> np.fill_diagonal(M[:,1:], 1)
|
335 |
+
>>> np.allclose(M, M_from_diff0)
|
336 |
+
True
|
337 |
+
|
338 |
+
Its transpose
|
339 |
+
|
340 |
+
>>> print(M.T)
|
341 |
+
[[-1 0 0 0]
|
342 |
+
[ 1 -1 0 0]
|
343 |
+
[ 0 1 -1 0]
|
344 |
+
[ 0 0 1 -1]
|
345 |
+
[ 0 0 0 1]]
|
346 |
+
|
347 |
+
can be viewed as the incidence matrix; see
|
348 |
+
Incidence matrix, (2022, Nov. 19), Wikipedia, https://w.wiki/5YXU,
|
349 |
+
of a linear graph with 5 vertices and 4 edges. The 5x5 normal matrix
|
350 |
+
``M.T @ M`` thus is
|
351 |
+
|
352 |
+
>>> print(M.T @ M)
|
353 |
+
[[ 1 -1 0 0 0]
|
354 |
+
[-1 2 -1 0 0]
|
355 |
+
[ 0 -1 2 -1 0]
|
356 |
+
[ 0 0 -1 2 -1]
|
357 |
+
[ 0 0 0 -1 1]]
|
358 |
+
|
359 |
+
the graph Laplacian, while the actually used in 'svds' smaller size
|
360 |
+
4x4 normal matrix ``M @ M.T``
|
361 |
+
|
362 |
+
>>> print(M @ M.T)
|
363 |
+
[[ 2 -1 0 0]
|
364 |
+
[-1 2 -1 0]
|
365 |
+
[ 0 -1 2 -1]
|
366 |
+
[ 0 0 -1 2]]
|
367 |
+
|
368 |
+
is the so-called edge-based Laplacian; see
|
369 |
+
Symmetric Laplacian via the incidence matrix, in Laplacian matrix,
|
370 |
+
(2022, Nov. 19), Wikipedia, https://w.wiki/5YXW.
|
371 |
+
|
372 |
+
The 'LinearOperator' setup needs the options 'rmatvec' and 'rmatmat'
|
373 |
+
of multiplication by the matrix transpose ``M.T``, but we want to be
|
374 |
+
matrix-free to save memory, so knowing how ``M.T`` looks like, we
|
375 |
+
manually construct the following function to be
|
376 |
+
used in ``rmatmat=diff0t``.
|
377 |
+
|
378 |
+
>>> def diff0t(a):
|
379 |
+
... if a.ndim == 1:
|
380 |
+
... a = a[:,np.newaxis] # Turn 1D into 2D array
|
381 |
+
... d = np.zeros((a.shape[0] + 1, a.shape[1]), dtype=a.dtype)
|
382 |
+
... d[0, :] = - a[0, :]
|
383 |
+
... d[1:-1, :] = a[0:-1, :] - a[1:, :]
|
384 |
+
... d[-1, :] = a[-1, :]
|
385 |
+
... return d
|
386 |
+
|
387 |
+
We check that our function 'diff0t' for the matrix transpose is valid.
|
388 |
+
|
389 |
+
>>> np.allclose(M.T, diff0t(np.eye(n-1)))
|
390 |
+
True
|
391 |
+
|
392 |
+
Now we setup our matrix-free 'LinearOperator' called 'diff0_func_aslo'
|
393 |
+
and for validation the matrix-based 'diff0_matrix_aslo'.
|
394 |
+
|
395 |
+
>>> def diff0_func_aslo_def(n):
|
396 |
+
... return LinearOperator(matvec=diff0,
|
397 |
+
... matmat=diff0,
|
398 |
+
... rmatvec=diff0t,
|
399 |
+
... rmatmat=diff0t,
|
400 |
+
... shape=(n - 1, n))
|
401 |
+
>>> diff0_func_aslo = diff0_func_aslo_def(n)
|
402 |
+
>>> diff0_matrix_aslo = aslinearoperator(M_from_diff0)
|
403 |
+
|
404 |
+
And validate both the matrix and its transpose in 'LinearOperator'.
|
405 |
+
|
406 |
+
>>> np.allclose(diff0_func_aslo(np.eye(n)),
|
407 |
+
... diff0_matrix_aslo(np.eye(n)))
|
408 |
+
True
|
409 |
+
>>> np.allclose(diff0_func_aslo.T(np.eye(n-1)),
|
410 |
+
... diff0_matrix_aslo.T(np.eye(n-1)))
|
411 |
+
True
|
412 |
+
|
413 |
+
Having the 'LinearOperator' setup validated, we run the solver.
|
414 |
+
|
415 |
+
>>> n = 100
|
416 |
+
>>> diff0_func_aslo = diff0_func_aslo_def(n)
|
417 |
+
>>> u, s, vT = svds(diff0_func_aslo, k=3, which='SM')
|
418 |
+
|
419 |
+
The singular values squared and the singular vectors are known
|
420 |
+
explicitly; see
|
421 |
+
Pure Dirichlet boundary conditions, in
|
422 |
+
Eigenvalues and eigenvectors of the second derivative,
|
423 |
+
(2022, Nov. 19), Wikipedia, https://w.wiki/5YX6,
|
424 |
+
since 'diff' corresponds to first
|
425 |
+
derivative, and its smaller size n-1 x n-1 normal matrix
|
426 |
+
``M @ M.T`` represent the discrete second derivative with the Dirichlet
|
427 |
+
boundary conditions. We use these analytic expressions for validation.
|
428 |
+
|
429 |
+
>>> se = 2. * np.sin(np.pi * np.arange(1, 4) / (2. * n))
|
430 |
+
>>> ue = np.sqrt(2 / n) * np.sin(np.pi * np.outer(np.arange(1, n),
|
431 |
+
... np.arange(1, 4)) / n)
|
432 |
+
>>> np.allclose(s, se, atol=1e-3)
|
433 |
+
True
|
434 |
+
>>> print(np.allclose(np.abs(u), np.abs(ue), atol=1e-6))
|
435 |
+
True
|
436 |
+
|
437 |
+
"""
|
438 |
+
args = _iv(A, k, ncv, tol, which, v0, maxiter, return_singular_vectors,
|
439 |
+
solver, random_state)
|
440 |
+
(A, k, ncv, tol, which, v0, maxiter,
|
441 |
+
return_singular_vectors, solver, random_state) = args
|
442 |
+
|
443 |
+
largest = (which == 'LM')
|
444 |
+
n, m = A.shape
|
445 |
+
|
446 |
+
if n >= m:
|
447 |
+
X_dot = A.matvec
|
448 |
+
X_matmat = A.matmat
|
449 |
+
XH_dot = A.rmatvec
|
450 |
+
XH_mat = A.rmatmat
|
451 |
+
transpose = False
|
452 |
+
else:
|
453 |
+
X_dot = A.rmatvec
|
454 |
+
X_matmat = A.rmatmat
|
455 |
+
XH_dot = A.matvec
|
456 |
+
XH_mat = A.matmat
|
457 |
+
transpose = True
|
458 |
+
|
459 |
+
dtype = getattr(A, 'dtype', None)
|
460 |
+
if dtype is None:
|
461 |
+
dtype = A.dot(np.zeros([m, 1])).dtype
|
462 |
+
|
463 |
+
def matvec_XH_X(x):
|
464 |
+
return XH_dot(X_dot(x))
|
465 |
+
|
466 |
+
def matmat_XH_X(x):
|
467 |
+
return XH_mat(X_matmat(x))
|
468 |
+
|
469 |
+
XH_X = LinearOperator(matvec=matvec_XH_X, dtype=A.dtype,
|
470 |
+
matmat=matmat_XH_X,
|
471 |
+
shape=(min(A.shape), min(A.shape)))
|
472 |
+
|
473 |
+
# Get a low rank approximation of the implicitly defined gramian matrix.
|
474 |
+
# This is not a stable way to approach the problem.
|
475 |
+
if solver == 'lobpcg':
|
476 |
+
|
477 |
+
if k == 1 and v0 is not None:
|
478 |
+
X = np.reshape(v0, (-1, 1))
|
479 |
+
else:
|
480 |
+
X = random_state.standard_normal(size=(min(A.shape), k))
|
481 |
+
|
482 |
+
_, eigvec = lobpcg(XH_X, X, tol=tol ** 2, maxiter=maxiter,
|
483 |
+
largest=largest)
|
484 |
+
|
485 |
+
elif solver == 'propack':
|
486 |
+
jobu = return_singular_vectors in {True, 'u'}
|
487 |
+
jobv = return_singular_vectors in {True, 'vh'}
|
488 |
+
irl_mode = (which == 'SM')
|
489 |
+
res = _svdp(A, k=k, tol=tol**2, which=which, maxiter=None,
|
490 |
+
compute_u=jobu, compute_v=jobv, irl_mode=irl_mode,
|
491 |
+
kmax=maxiter, v0=v0, random_state=random_state)
|
492 |
+
|
493 |
+
u, s, vh, _ = res # but we'll ignore bnd, the last output
|
494 |
+
|
495 |
+
# PROPACK order appears to be largest first. `svds` output order is not
|
496 |
+
# guaranteed, according to documentation, but for ARPACK and LOBPCG
|
497 |
+
# they actually are ordered smallest to largest, so reverse for
|
498 |
+
# consistency.
|
499 |
+
s = s[::-1]
|
500 |
+
u = u[:, ::-1]
|
501 |
+
vh = vh[::-1]
|
502 |
+
|
503 |
+
u = u if jobu else None
|
504 |
+
vh = vh if jobv else None
|
505 |
+
|
506 |
+
if return_singular_vectors:
|
507 |
+
return u, s, vh
|
508 |
+
else:
|
509 |
+
return s
|
510 |
+
|
511 |
+
elif solver == 'arpack' or solver is None:
|
512 |
+
if v0 is None:
|
513 |
+
v0 = random_state.standard_normal(size=(min(A.shape),))
|
514 |
+
_, eigvec = eigsh(XH_X, k=k, tol=tol ** 2, maxiter=maxiter,
|
515 |
+
ncv=ncv, which=which, v0=v0)
|
516 |
+
# arpack do not guarantee exactly orthonormal eigenvectors
|
517 |
+
# for clustered eigenvalues, especially in complex arithmetic
|
518 |
+
eigvec, _ = np.linalg.qr(eigvec)
|
519 |
+
|
520 |
+
# the eigenvectors eigvec must be orthonomal here; see gh-16712
|
521 |
+
Av = X_matmat(eigvec)
|
522 |
+
if not return_singular_vectors:
|
523 |
+
s = svd(Av, compute_uv=False, overwrite_a=True)
|
524 |
+
return s[::-1]
|
525 |
+
|
526 |
+
# compute the left singular vectors of X and update the right ones
|
527 |
+
# accordingly
|
528 |
+
u, s, vh = svd(Av, full_matrices=False, overwrite_a=True)
|
529 |
+
u = u[:, ::-1]
|
530 |
+
s = s[::-1]
|
531 |
+
vh = vh[::-1]
|
532 |
+
|
533 |
+
jobu = return_singular_vectors in {True, 'u'}
|
534 |
+
jobv = return_singular_vectors in {True, 'vh'}
|
535 |
+
|
536 |
+
if transpose:
|
537 |
+
u_tmp = eigvec @ _herm(vh) if jobu else None
|
538 |
+
vh = _herm(u) if jobv else None
|
539 |
+
u = u_tmp
|
540 |
+
else:
|
541 |
+
if not jobu:
|
542 |
+
u = None
|
543 |
+
vh = vh @ _herm(eigvec) if jobv else None
|
544 |
+
|
545 |
+
return u, s, vh
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/_svds_doc.py
ADDED
@@ -0,0 +1,400 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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', random_state=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 satistify ``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 |
+
random_state : {None, int, `numpy.random.Generator`,
|
58 |
+
`numpy.random.RandomState`}, optional
|
59 |
+
|
60 |
+
Pseudorandom number generator state used to generate resamples.
|
61 |
+
|
62 |
+
If `random_state` is ``None`` (or `np.random`), the
|
63 |
+
`numpy.random.RandomState` singleton is used.
|
64 |
+
If `random_state` is an int, a new ``RandomState`` instance is used,
|
65 |
+
seeded with `random_state`.
|
66 |
+
If `random_state` is already a ``Generator`` or ``RandomState``
|
67 |
+
instance then that instance is used.
|
68 |
+
options : dict, optional
|
69 |
+
A dictionary of solver-specific options. No solver-specific options
|
70 |
+
are currently supported; this parameter is reserved for future use.
|
71 |
+
|
72 |
+
Returns
|
73 |
+
-------
|
74 |
+
u : ndarray, shape=(M, k)
|
75 |
+
Unitary matrix having left singular vectors as columns.
|
76 |
+
s : ndarray, shape=(k,)
|
77 |
+
The singular values.
|
78 |
+
vh : ndarray, shape=(k, N)
|
79 |
+
Unitary matrix having right singular vectors as rows.
|
80 |
+
|
81 |
+
Notes
|
82 |
+
-----
|
83 |
+
This is a naive implementation using ARPACK as an eigensolver
|
84 |
+
on ``A.conj().T @ A`` or ``A @ A.conj().T``, depending on which one is more
|
85 |
+
efficient.
|
86 |
+
|
87 |
+
Examples
|
88 |
+
--------
|
89 |
+
Construct a matrix ``A`` from singular values and vectors.
|
90 |
+
|
91 |
+
>>> import numpy as np
|
92 |
+
>>> from scipy.stats import ortho_group
|
93 |
+
>>> from scipy.sparse import csc_matrix, diags
|
94 |
+
>>> from scipy.sparse.linalg import svds
|
95 |
+
>>> rng = np.random.default_rng()
|
96 |
+
>>> orthogonal = csc_matrix(ortho_group.rvs(10, random_state=rng))
|
97 |
+
>>> s = [0.0001, 0.001, 3, 4, 5] # singular values
|
98 |
+
>>> u = orthogonal[:, :5] # left singular vectors
|
99 |
+
>>> vT = orthogonal[:, 5:].T # right singular vectors
|
100 |
+
>>> A = u @ diags(s) @ vT
|
101 |
+
|
102 |
+
With only three singular values/vectors, the SVD approximates the original
|
103 |
+
matrix.
|
104 |
+
|
105 |
+
>>> u2, s2, vT2 = svds(A, k=3, solver='arpack')
|
106 |
+
>>> A2 = u2 @ np.diag(s2) @ vT2
|
107 |
+
>>> np.allclose(A2, A.toarray(), atol=1e-3)
|
108 |
+
True
|
109 |
+
|
110 |
+
With all five singular values/vectors, we can reproduce the original
|
111 |
+
matrix.
|
112 |
+
|
113 |
+
>>> u3, s3, vT3 = svds(A, k=5, solver='arpack')
|
114 |
+
>>> A3 = u3 @ np.diag(s3) @ vT3
|
115 |
+
>>> np.allclose(A3, A.toarray())
|
116 |
+
True
|
117 |
+
|
118 |
+
The singular values match the expected singular values, and the singular
|
119 |
+
vectors are as expected up to a difference in sign.
|
120 |
+
|
121 |
+
>>> (np.allclose(s3, s) and
|
122 |
+
... np.allclose(np.abs(u3), np.abs(u.toarray())) and
|
123 |
+
... np.allclose(np.abs(vT3), np.abs(vT.toarray())))
|
124 |
+
True
|
125 |
+
|
126 |
+
The singular vectors are also orthogonal.
|
127 |
+
|
128 |
+
>>> (np.allclose(u3.T @ u3, np.eye(5)) and
|
129 |
+
... np.allclose(vT3 @ vT3.T, np.eye(5)))
|
130 |
+
True
|
131 |
+
"""
|
132 |
+
pass
|
133 |
+
|
134 |
+
|
135 |
+
def _svds_lobpcg_doc(A, k=6, ncv=None, tol=0, which='LM', v0=None,
|
136 |
+
maxiter=None, return_singular_vectors=True,
|
137 |
+
solver='lobpcg', random_state=None):
|
138 |
+
"""
|
139 |
+
Partial singular value decomposition of a sparse matrix using LOBPCG.
|
140 |
+
|
141 |
+
Compute the largest or smallest `k` singular values and corresponding
|
142 |
+
singular vectors of a sparse matrix `A`. The order in which the singular
|
143 |
+
values are returned is not guaranteed.
|
144 |
+
|
145 |
+
In the descriptions below, let ``M, N = A.shape``.
|
146 |
+
|
147 |
+
Parameters
|
148 |
+
----------
|
149 |
+
A : sparse matrix or LinearOperator
|
150 |
+
Matrix to decompose.
|
151 |
+
k : int, default: 6
|
152 |
+
Number of singular values and singular vectors to compute.
|
153 |
+
Must satisfy ``1 <= k <= min(M, N) - 1``.
|
154 |
+
ncv : int, optional
|
155 |
+
Ignored.
|
156 |
+
tol : float, optional
|
157 |
+
Tolerance for singular values. Zero (default) means machine precision.
|
158 |
+
which : {'LM', 'SM'}
|
159 |
+
Which `k` singular values to find: either the largest magnitude ('LM')
|
160 |
+
or smallest magnitude ('SM') singular values.
|
161 |
+
v0 : ndarray, optional
|
162 |
+
If `k` is 1, the starting vector for iteration:
|
163 |
+
an (approximate) left singular vector if ``N > M`` and a right singular
|
164 |
+
vector otherwise. Must be of length ``min(M, N)``.
|
165 |
+
Ignored otherwise.
|
166 |
+
Default: random
|
167 |
+
maxiter : int, default: 20
|
168 |
+
Maximum number of iterations.
|
169 |
+
return_singular_vectors : {True, False, "u", "vh"}
|
170 |
+
Singular values are always computed and returned; this parameter
|
171 |
+
controls the computation and return of singular vectors.
|
172 |
+
|
173 |
+
- ``True``: return singular vectors.
|
174 |
+
- ``False``: do not return singular vectors.
|
175 |
+
- ``"u"``: if ``M <= N``, compute only the left singular vectors and
|
176 |
+
return ``None`` for the right singular vectors. Otherwise, compute
|
177 |
+
all singular vectors.
|
178 |
+
- ``"vh"``: if ``M > N``, compute only the right singular vectors and
|
179 |
+
return ``None`` for the left singular vectors. Otherwise, compute
|
180 |
+
all singular vectors.
|
181 |
+
|
182 |
+
solver : {'arpack', 'propack', 'lobpcg'}, optional
|
183 |
+
This is the solver-specific documentation for ``solver='lobpcg'``.
|
184 |
+
:ref:`'arpack' <sparse.linalg.svds-arpack>` and
|
185 |
+
:ref:`'propack' <sparse.linalg.svds-propack>`
|
186 |
+
are also supported.
|
187 |
+
random_state : {None, int, `numpy.random.Generator`,
|
188 |
+
`numpy.random.RandomState`}, optional
|
189 |
+
|
190 |
+
Pseudorandom number generator state used to generate resamples.
|
191 |
+
|
192 |
+
If `random_state` is ``None`` (or `np.random`), the
|
193 |
+
`numpy.random.RandomState` singleton is used.
|
194 |
+
If `random_state` is an int, a new ``RandomState`` instance is used,
|
195 |
+
seeded with `random_state`.
|
196 |
+
If `random_state` is already a ``Generator`` or ``RandomState``
|
197 |
+
instance then that instance is used.
|
198 |
+
options : dict, optional
|
199 |
+
A dictionary of solver-specific options. No solver-specific options
|
200 |
+
are currently supported; this parameter is reserved for future use.
|
201 |
+
|
202 |
+
Returns
|
203 |
+
-------
|
204 |
+
u : ndarray, shape=(M, k)
|
205 |
+
Unitary matrix having left singular vectors as columns.
|
206 |
+
s : ndarray, shape=(k,)
|
207 |
+
The singular values.
|
208 |
+
vh : ndarray, shape=(k, N)
|
209 |
+
Unitary matrix having right singular vectors as rows.
|
210 |
+
|
211 |
+
Notes
|
212 |
+
-----
|
213 |
+
This is a naive implementation using LOBPCG as an eigensolver
|
214 |
+
on ``A.conj().T @ A`` or ``A @ A.conj().T``, depending on which one is more
|
215 |
+
efficient.
|
216 |
+
|
217 |
+
Examples
|
218 |
+
--------
|
219 |
+
Construct a matrix ``A`` from singular values and vectors.
|
220 |
+
|
221 |
+
>>> import numpy as np
|
222 |
+
>>> from scipy.stats import ortho_group
|
223 |
+
>>> from scipy.sparse import csc_matrix, diags
|
224 |
+
>>> from scipy.sparse.linalg import svds
|
225 |
+
>>> rng = np.random.default_rng()
|
226 |
+
>>> orthogonal = csc_matrix(ortho_group.rvs(10, random_state=rng))
|
227 |
+
>>> s = [0.0001, 0.001, 3, 4, 5] # singular values
|
228 |
+
>>> u = orthogonal[:, :5] # left singular vectors
|
229 |
+
>>> vT = orthogonal[:, 5:].T # right singular vectors
|
230 |
+
>>> A = u @ diags(s) @ vT
|
231 |
+
|
232 |
+
With only three singular values/vectors, the SVD approximates the original
|
233 |
+
matrix.
|
234 |
+
|
235 |
+
>>> u2, s2, vT2 = svds(A, k=3, solver='lobpcg')
|
236 |
+
>>> A2 = u2 @ np.diag(s2) @ vT2
|
237 |
+
>>> np.allclose(A2, A.toarray(), atol=1e-3)
|
238 |
+
True
|
239 |
+
|
240 |
+
With all five singular values/vectors, we can reproduce the original
|
241 |
+
matrix.
|
242 |
+
|
243 |
+
>>> u3, s3, vT3 = svds(A, k=5, solver='lobpcg')
|
244 |
+
>>> A3 = u3 @ np.diag(s3) @ vT3
|
245 |
+
>>> np.allclose(A3, A.toarray())
|
246 |
+
True
|
247 |
+
|
248 |
+
The singular values match the expected singular values, and the singular
|
249 |
+
vectors are as expected up to a difference in sign.
|
250 |
+
|
251 |
+
>>> (np.allclose(s3, s) and
|
252 |
+
... np.allclose(np.abs(u3), np.abs(u.todense())) and
|
253 |
+
... np.allclose(np.abs(vT3), np.abs(vT.todense())))
|
254 |
+
True
|
255 |
+
|
256 |
+
The singular vectors are also orthogonal.
|
257 |
+
|
258 |
+
>>> (np.allclose(u3.T @ u3, np.eye(5)) and
|
259 |
+
... np.allclose(vT3 @ vT3.T, np.eye(5)))
|
260 |
+
True
|
261 |
+
|
262 |
+
"""
|
263 |
+
pass
|
264 |
+
|
265 |
+
|
266 |
+
def _svds_propack_doc(A, k=6, ncv=None, tol=0, which='LM', v0=None,
|
267 |
+
maxiter=None, return_singular_vectors=True,
|
268 |
+
solver='propack', random_state=None):
|
269 |
+
"""
|
270 |
+
Partial singular value decomposition of a sparse matrix using PROPACK.
|
271 |
+
|
272 |
+
Compute the largest or smallest `k` singular values and corresponding
|
273 |
+
singular vectors of a sparse matrix `A`. The order in which the singular
|
274 |
+
values are returned is not guaranteed.
|
275 |
+
|
276 |
+
In the descriptions below, let ``M, N = A.shape``.
|
277 |
+
|
278 |
+
Parameters
|
279 |
+
----------
|
280 |
+
A : sparse matrix or LinearOperator
|
281 |
+
Matrix to decompose. If `A` is a ``LinearOperator``
|
282 |
+
object, it must define both ``matvec`` and ``rmatvec`` methods.
|
283 |
+
k : int, default: 6
|
284 |
+
Number of singular values and singular vectors to compute.
|
285 |
+
Must satisfy ``1 <= k <= min(M, N)``.
|
286 |
+
ncv : int, optional
|
287 |
+
Ignored.
|
288 |
+
tol : float, optional
|
289 |
+
The desired relative accuracy for computed singular values.
|
290 |
+
Zero (default) means machine precision.
|
291 |
+
which : {'LM', 'SM'}
|
292 |
+
Which `k` singular values to find: either the largest magnitude ('LM')
|
293 |
+
or smallest magnitude ('SM') singular values. Note that choosing
|
294 |
+
``which='SM'`` will force the ``irl`` option to be set ``True``.
|
295 |
+
v0 : ndarray, optional
|
296 |
+
Starting vector for iterations: must be of length ``A.shape[0]``.
|
297 |
+
If not specified, PROPACK will generate a starting vector.
|
298 |
+
maxiter : int, optional
|
299 |
+
Maximum number of iterations / maximal dimension of the Krylov
|
300 |
+
subspace. Default is ``10 * k``.
|
301 |
+
return_singular_vectors : {True, False, "u", "vh"}
|
302 |
+
Singular values are always computed and returned; this parameter
|
303 |
+
controls the computation and return of singular vectors.
|
304 |
+
|
305 |
+
- ``True``: return singular vectors.
|
306 |
+
- ``False``: do not return singular vectors.
|
307 |
+
- ``"u"``: compute only the left singular vectors; return ``None`` for
|
308 |
+
the right singular vectors.
|
309 |
+
- ``"vh"``: compute only the right singular vectors; return ``None``
|
310 |
+
for the left singular vectors.
|
311 |
+
|
312 |
+
solver : {'arpack', 'propack', 'lobpcg'}, optional
|
313 |
+
This is the solver-specific documentation for ``solver='propack'``.
|
314 |
+
:ref:`'arpack' <sparse.linalg.svds-arpack>` and
|
315 |
+
:ref:`'lobpcg' <sparse.linalg.svds-lobpcg>`
|
316 |
+
are also supported.
|
317 |
+
random_state : {None, int, `numpy.random.Generator`,
|
318 |
+
`numpy.random.RandomState`}, optional
|
319 |
+
|
320 |
+
Pseudorandom number generator state used to generate resamples.
|
321 |
+
|
322 |
+
If `random_state` is ``None`` (or `np.random`), the
|
323 |
+
`numpy.random.RandomState` singleton is used.
|
324 |
+
If `random_state` is an int, a new ``RandomState`` instance is used,
|
325 |
+
seeded with `random_state`.
|
326 |
+
If `random_state` is already a ``Generator`` or ``RandomState``
|
327 |
+
instance then that instance is used.
|
328 |
+
options : dict, optional
|
329 |
+
A dictionary of solver-specific options. No solver-specific options
|
330 |
+
are currently supported; this parameter is reserved for future use.
|
331 |
+
|
332 |
+
Returns
|
333 |
+
-------
|
334 |
+
u : ndarray, shape=(M, k)
|
335 |
+
Unitary matrix having left singular vectors as columns.
|
336 |
+
s : ndarray, shape=(k,)
|
337 |
+
The singular values.
|
338 |
+
vh : ndarray, shape=(k, N)
|
339 |
+
Unitary matrix having right singular vectors as rows.
|
340 |
+
|
341 |
+
Notes
|
342 |
+
-----
|
343 |
+
This is an interface to the Fortran library PROPACK [1]_.
|
344 |
+
The current default is to run with IRL mode disabled unless seeking the
|
345 |
+
smallest singular values/vectors (``which='SM'``).
|
346 |
+
|
347 |
+
References
|
348 |
+
----------
|
349 |
+
|
350 |
+
.. [1] Larsen, Rasmus Munk. "PROPACK-Software for large and sparse SVD
|
351 |
+
calculations." Available online. URL
|
352 |
+
http://sun.stanford.edu/~rmunk/PROPACK (2004): 2008-2009.
|
353 |
+
|
354 |
+
Examples
|
355 |
+
--------
|
356 |
+
Construct a matrix ``A`` from singular values and vectors.
|
357 |
+
|
358 |
+
>>> import numpy as np
|
359 |
+
>>> from scipy.stats import ortho_group
|
360 |
+
>>> from scipy.sparse import csc_matrix, diags
|
361 |
+
>>> from scipy.sparse.linalg import svds
|
362 |
+
>>> rng = np.random.default_rng()
|
363 |
+
>>> orthogonal = csc_matrix(ortho_group.rvs(10, random_state=rng))
|
364 |
+
>>> s = [0.0001, 0.001, 3, 4, 5] # singular values
|
365 |
+
>>> u = orthogonal[:, :5] # left singular vectors
|
366 |
+
>>> vT = orthogonal[:, 5:].T # right singular vectors
|
367 |
+
>>> A = u @ diags(s) @ vT
|
368 |
+
|
369 |
+
With only three singular values/vectors, the SVD approximates the original
|
370 |
+
matrix.
|
371 |
+
|
372 |
+
>>> u2, s2, vT2 = svds(A, k=3, solver='propack')
|
373 |
+
>>> A2 = u2 @ np.diag(s2) @ vT2
|
374 |
+
>>> np.allclose(A2, A.todense(), atol=1e-3)
|
375 |
+
True
|
376 |
+
|
377 |
+
With all five singular values/vectors, we can reproduce the original
|
378 |
+
matrix.
|
379 |
+
|
380 |
+
>>> u3, s3, vT3 = svds(A, k=5, solver='propack')
|
381 |
+
>>> A3 = u3 @ np.diag(s3) @ vT3
|
382 |
+
>>> np.allclose(A3, A.todense())
|
383 |
+
True
|
384 |
+
|
385 |
+
The singular values match the expected singular values, and the singular
|
386 |
+
vectors are as expected up to a difference in sign.
|
387 |
+
|
388 |
+
>>> (np.allclose(s3, s) and
|
389 |
+
... np.allclose(np.abs(u3), np.abs(u.toarray())) and
|
390 |
+
... np.allclose(np.abs(vT3), np.abs(vT.toarray())))
|
391 |
+
True
|
392 |
+
|
393 |
+
The singular vectors are also orthogonal.
|
394 |
+
|
395 |
+
>>> (np.allclose(u3.T @ u3, np.eye(5)) and
|
396 |
+
... np.allclose(vT3 @ vT3.T, np.eye(5)))
|
397 |
+
True
|
398 |
+
|
399 |
+
"""
|
400 |
+
pass
|
venv/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
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (642 Bytes). View file
|
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/_gcrotmk.cpython-310.pyc
ADDED
Binary file (11.4 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/iterative.cpython-310.pyc
ADDED
Binary file (27.6 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/lgmres.cpython-310.pyc
ADDED
Binary file (7.41 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/lsmr.cpython-310.pyc
ADDED
Binary file (11.6 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/lsqr.cpython-310.pyc
ADDED
Binary file (17 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/minres.cpython-310.pyc
ADDED
Binary file (8.07 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/tfqmr.cpython-310.pyc
ADDED
Binary file (5.73 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/utils.cpython-310.pyc
ADDED
Binary file (3.29 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/_gcrotmk.py
ADDED
@@ -0,0 +1,514 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (C) 2015, Pauli Virtanen <[email protected]>
|
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 |
+
from scipy._lib.deprecation import _NoValue, _deprecate_positional_args
|
10 |
+
|
11 |
+
|
12 |
+
__all__ = ['gcrotmk']
|
13 |
+
|
14 |
+
|
15 |
+
def _fgmres(matvec, v0, m, atol, lpsolve=None, rpsolve=None, cs=(), outer_v=(),
|
16 |
+
prepend_outer_v=False):
|
17 |
+
"""
|
18 |
+
FGMRES Arnoldi process, with optional projection or augmentation
|
19 |
+
|
20 |
+
Parameters
|
21 |
+
----------
|
22 |
+
matvec : callable
|
23 |
+
Operation A*x
|
24 |
+
v0 : ndarray
|
25 |
+
Initial vector, normalized to nrm2(v0) == 1
|
26 |
+
m : int
|
27 |
+
Number of GMRES rounds
|
28 |
+
atol : float
|
29 |
+
Absolute tolerance for early exit
|
30 |
+
lpsolve : callable
|
31 |
+
Left preconditioner L
|
32 |
+
rpsolve : callable
|
33 |
+
Right preconditioner R
|
34 |
+
cs : list of (ndarray, ndarray)
|
35 |
+
Columns of matrices C and U in GCROT
|
36 |
+
outer_v : list of ndarrays
|
37 |
+
Augmentation vectors in LGMRES
|
38 |
+
prepend_outer_v : bool, optional
|
39 |
+
Whether augmentation vectors come before or after
|
40 |
+
Krylov iterates
|
41 |
+
|
42 |
+
Raises
|
43 |
+
------
|
44 |
+
LinAlgError
|
45 |
+
If nans encountered
|
46 |
+
|
47 |
+
Returns
|
48 |
+
-------
|
49 |
+
Q, R : ndarray
|
50 |
+
QR decomposition of the upper Hessenberg H=QR
|
51 |
+
B : ndarray
|
52 |
+
Projections corresponding to matrix C
|
53 |
+
vs : list of ndarray
|
54 |
+
Columns of matrix V
|
55 |
+
zs : list of ndarray
|
56 |
+
Columns of matrix Z
|
57 |
+
y : ndarray
|
58 |
+
Solution to ||H y - e_1||_2 = min!
|
59 |
+
res : float
|
60 |
+
The final (preconditioned) residual norm
|
61 |
+
|
62 |
+
"""
|
63 |
+
|
64 |
+
if lpsolve is None:
|
65 |
+
def lpsolve(x):
|
66 |
+
return x
|
67 |
+
if rpsolve is None:
|
68 |
+
def rpsolve(x):
|
69 |
+
return x
|
70 |
+
|
71 |
+
axpy, dot, scal, nrm2 = get_blas_funcs(['axpy', 'dot', 'scal', 'nrm2'], (v0,))
|
72 |
+
|
73 |
+
vs = [v0]
|
74 |
+
zs = []
|
75 |
+
y = None
|
76 |
+
res = np.nan
|
77 |
+
|
78 |
+
m = m + len(outer_v)
|
79 |
+
|
80 |
+
# Orthogonal projection coefficients
|
81 |
+
B = np.zeros((len(cs), m), dtype=v0.dtype)
|
82 |
+
|
83 |
+
# H is stored in QR factorized form
|
84 |
+
Q = np.ones((1, 1), dtype=v0.dtype)
|
85 |
+
R = np.zeros((1, 0), dtype=v0.dtype)
|
86 |
+
|
87 |
+
eps = np.finfo(v0.dtype).eps
|
88 |
+
|
89 |
+
breakdown = False
|
90 |
+
|
91 |
+
# FGMRES Arnoldi process
|
92 |
+
for j in range(m):
|
93 |
+
# L A Z = C B + V H
|
94 |
+
|
95 |
+
if prepend_outer_v and j < len(outer_v):
|
96 |
+
z, w = outer_v[j]
|
97 |
+
elif prepend_outer_v and j == len(outer_v):
|
98 |
+
z = rpsolve(v0)
|
99 |
+
w = None
|
100 |
+
elif not prepend_outer_v and j >= m - len(outer_v):
|
101 |
+
z, w = outer_v[j - (m - len(outer_v))]
|
102 |
+
else:
|
103 |
+
z = rpsolve(vs[-1])
|
104 |
+
w = None
|
105 |
+
|
106 |
+
if w is None:
|
107 |
+
w = lpsolve(matvec(z))
|
108 |
+
else:
|
109 |
+
# w is clobbered below
|
110 |
+
w = w.copy()
|
111 |
+
|
112 |
+
w_norm = nrm2(w)
|
113 |
+
|
114 |
+
# GCROT projection: L A -> (1 - C C^H) L A
|
115 |
+
# i.e. orthogonalize against C
|
116 |
+
for i, c in enumerate(cs):
|
117 |
+
alpha = dot(c, w)
|
118 |
+
B[i,j] = alpha
|
119 |
+
w = axpy(c, w, c.shape[0], -alpha) # w -= alpha*c
|
120 |
+
|
121 |
+
# Orthogonalize against V
|
122 |
+
hcur = np.zeros(j+2, dtype=Q.dtype)
|
123 |
+
for i, v in enumerate(vs):
|
124 |
+
alpha = dot(v, w)
|
125 |
+
hcur[i] = alpha
|
126 |
+
w = axpy(v, w, v.shape[0], -alpha) # w -= alpha*v
|
127 |
+
hcur[i+1] = nrm2(w)
|
128 |
+
|
129 |
+
with np.errstate(over='ignore', divide='ignore'):
|
130 |
+
# Careful with denormals
|
131 |
+
alpha = 1/hcur[-1]
|
132 |
+
|
133 |
+
if np.isfinite(alpha):
|
134 |
+
w = scal(alpha, w)
|
135 |
+
|
136 |
+
if not (hcur[-1] > eps * w_norm):
|
137 |
+
# w essentially in the span of previous vectors,
|
138 |
+
# or we have nans. Bail out after updating the QR
|
139 |
+
# solution.
|
140 |
+
breakdown = True
|
141 |
+
|
142 |
+
vs.append(w)
|
143 |
+
zs.append(z)
|
144 |
+
|
145 |
+
# Arnoldi LSQ problem
|
146 |
+
|
147 |
+
# Add new column to H=Q@R, padding other columns with zeros
|
148 |
+
Q2 = np.zeros((j+2, j+2), dtype=Q.dtype, order='F')
|
149 |
+
Q2[:j+1,:j+1] = Q
|
150 |
+
Q2[j+1,j+1] = 1
|
151 |
+
|
152 |
+
R2 = np.zeros((j+2, j), dtype=R.dtype, order='F')
|
153 |
+
R2[:j+1,:] = R
|
154 |
+
|
155 |
+
Q, R = qr_insert(Q2, R2, hcur, j, which='col',
|
156 |
+
overwrite_qru=True, check_finite=False)
|
157 |
+
|
158 |
+
# Transformed least squares problem
|
159 |
+
# || Q R y - inner_res_0 * e_1 ||_2 = min!
|
160 |
+
# Since R = [R'; 0], solution is y = inner_res_0 (R')^{-1} (Q^H)[:j,0]
|
161 |
+
|
162 |
+
# Residual is immediately known
|
163 |
+
res = abs(Q[0,-1])
|
164 |
+
|
165 |
+
# Check for termination
|
166 |
+
if res < atol or breakdown:
|
167 |
+
break
|
168 |
+
|
169 |
+
if not np.isfinite(R[j,j]):
|
170 |
+
# nans encountered, bail out
|
171 |
+
raise LinAlgError()
|
172 |
+
|
173 |
+
# -- Get the LSQ problem solution
|
174 |
+
|
175 |
+
# The problem is triangular, but the condition number may be
|
176 |
+
# bad (or in case of breakdown the last diagonal entry may be
|
177 |
+
# zero), so use lstsq instead of trtrs.
|
178 |
+
y, _, _, _, = lstsq(R[:j+1,:j+1], Q[0,:j+1].conj())
|
179 |
+
|
180 |
+
B = B[:,:j+1]
|
181 |
+
|
182 |
+
return Q, R, B, vs, zs, y, res
|
183 |
+
|
184 |
+
|
185 |
+
@_deprecate_positional_args(version="1.14.0")
|
186 |
+
def gcrotmk(A, b, x0=None, *, tol=_NoValue, maxiter=1000, M=None, callback=None,
|
187 |
+
m=20, k=None, CU=None, discard_C=False, truncate='oldest',
|
188 |
+
atol=None, rtol=1e-5):
|
189 |
+
"""
|
190 |
+
Solve a matrix equation using flexible GCROT(m,k) algorithm.
|
191 |
+
|
192 |
+
Parameters
|
193 |
+
----------
|
194 |
+
A : {sparse matrix, ndarray, LinearOperator}
|
195 |
+
The real or complex N-by-N matrix of the linear system.
|
196 |
+
Alternatively, ``A`` can be a linear operator which can
|
197 |
+
produce ``Ax`` using, e.g.,
|
198 |
+
``scipy.sparse.linalg.LinearOperator``.
|
199 |
+
b : ndarray
|
200 |
+
Right hand side of the linear system. Has shape (N,) or (N,1).
|
201 |
+
x0 : ndarray
|
202 |
+
Starting guess for the solution.
|
203 |
+
rtol, atol : float, optional
|
204 |
+
Parameters for the convergence test. For convergence,
|
205 |
+
``norm(b - A @ x) <= max(rtol*norm(b), atol)`` should be satisfied.
|
206 |
+
The default is ``rtol=1e-5``, the default for ``atol`` is ``rtol``.
|
207 |
+
|
208 |
+
.. warning::
|
209 |
+
|
210 |
+
The default value for ``atol`` will be changed to ``0.0`` in
|
211 |
+
SciPy 1.14.0.
|
212 |
+
maxiter : int, optional
|
213 |
+
Maximum number of iterations. Iteration will stop after maxiter
|
214 |
+
steps even if the specified tolerance has not been achieved.
|
215 |
+
M : {sparse matrix, ndarray, LinearOperator}, optional
|
216 |
+
Preconditioner for A. The preconditioner should approximate the
|
217 |
+
inverse of A. gcrotmk is a 'flexible' algorithm and the preconditioner
|
218 |
+
can vary from iteration to iteration. Effective preconditioning
|
219 |
+
dramatically improves the rate of convergence, which implies that
|
220 |
+
fewer iterations are needed to reach a given error tolerance.
|
221 |
+
callback : function, optional
|
222 |
+
User-supplied function to call after each iteration. It is called
|
223 |
+
as callback(xk), where xk is the current solution vector.
|
224 |
+
m : int, optional
|
225 |
+
Number of inner FGMRES iterations per each outer iteration.
|
226 |
+
Default: 20
|
227 |
+
k : int, optional
|
228 |
+
Number of vectors to carry between inner FGMRES iterations.
|
229 |
+
According to [2]_, good values are around m.
|
230 |
+
Default: m
|
231 |
+
CU : list of tuples, optional
|
232 |
+
List of tuples ``(c, u)`` which contain the columns of the matrices
|
233 |
+
C and U in the GCROT(m,k) algorithm. For details, see [2]_.
|
234 |
+
The list given and vectors contained in it are modified in-place.
|
235 |
+
If not given, start from empty matrices. The ``c`` elements in the
|
236 |
+
tuples can be ``None``, in which case the vectors are recomputed
|
237 |
+
via ``c = A u`` on start and orthogonalized as described in [3]_.
|
238 |
+
discard_C : bool, optional
|
239 |
+
Discard the C-vectors at the end. Useful if recycling Krylov subspaces
|
240 |
+
for different linear systems.
|
241 |
+
truncate : {'oldest', 'smallest'}, optional
|
242 |
+
Truncation scheme to use. Drop: oldest vectors, or vectors with
|
243 |
+
smallest singular values using the scheme discussed in [1,2].
|
244 |
+
See [2]_ for detailed comparison.
|
245 |
+
Default: 'oldest'
|
246 |
+
tol : float, optional, deprecated
|
247 |
+
|
248 |
+
.. deprecated:: 1.12.0
|
249 |
+
`gcrotmk` keyword argument ``tol`` is deprecated in favor of
|
250 |
+
``rtol`` and will be removed in SciPy 1.14.0.
|
251 |
+
|
252 |
+
Returns
|
253 |
+
-------
|
254 |
+
x : ndarray
|
255 |
+
The solution found.
|
256 |
+
info : int
|
257 |
+
Provides convergence information:
|
258 |
+
|
259 |
+
* 0 : successful exit
|
260 |
+
* >0 : convergence to tolerance not achieved, number of iterations
|
261 |
+
|
262 |
+
Examples
|
263 |
+
--------
|
264 |
+
>>> import numpy as np
|
265 |
+
>>> from scipy.sparse import csc_matrix
|
266 |
+
>>> from scipy.sparse.linalg import gcrotmk
|
267 |
+
>>> R = np.random.randn(5, 5)
|
268 |
+
>>> A = csc_matrix(R)
|
269 |
+
>>> b = np.random.randn(5)
|
270 |
+
>>> x, exit_code = gcrotmk(A, b, atol=1e-5)
|
271 |
+
>>> print(exit_code)
|
272 |
+
0
|
273 |
+
>>> np.allclose(A.dot(x), b)
|
274 |
+
True
|
275 |
+
|
276 |
+
References
|
277 |
+
----------
|
278 |
+
.. [1] E. de Sturler, ''Truncation strategies for optimal Krylov subspace
|
279 |
+
methods'', SIAM J. Numer. Anal. 36, 864 (1999).
|
280 |
+
.. [2] J.E. Hicken and D.W. Zingg, ''A simplified and flexible variant
|
281 |
+
of GCROT for solving nonsymmetric linear systems'',
|
282 |
+
SIAM J. Sci. Comput. 32, 172 (2010).
|
283 |
+
.. [3] M.L. Parks, E. de Sturler, G. Mackey, D.D. Johnson, S. Maiti,
|
284 |
+
''Recycling Krylov subspaces for sequences of linear systems'',
|
285 |
+
SIAM J. Sci. Comput. 28, 1651 (2006).
|
286 |
+
|
287 |
+
"""
|
288 |
+
A,M,x,b,postprocess = make_system(A,M,x0,b)
|
289 |
+
|
290 |
+
if not np.isfinite(b).all():
|
291 |
+
raise ValueError("RHS must contain only finite numbers")
|
292 |
+
|
293 |
+
if truncate not in ('oldest', 'smallest'):
|
294 |
+
raise ValueError(f"Invalid value for 'truncate': {truncate!r}")
|
295 |
+
|
296 |
+
matvec = A.matvec
|
297 |
+
psolve = M.matvec
|
298 |
+
|
299 |
+
if CU is None:
|
300 |
+
CU = []
|
301 |
+
|
302 |
+
if k is None:
|
303 |
+
k = m
|
304 |
+
|
305 |
+
axpy, dot, scal = None, None, None
|
306 |
+
|
307 |
+
if x0 is None:
|
308 |
+
r = b.copy()
|
309 |
+
else:
|
310 |
+
r = b - matvec(x)
|
311 |
+
|
312 |
+
axpy, dot, scal, nrm2 = get_blas_funcs(['axpy', 'dot', 'scal', 'nrm2'], (x, r))
|
313 |
+
|
314 |
+
b_norm = nrm2(b)
|
315 |
+
|
316 |
+
# we call this to get the right atol/rtol and raise warnings as necessary
|
317 |
+
atol, rtol = _get_atol_rtol('gcrotmk', b_norm, tol, atol, rtol)
|
318 |
+
|
319 |
+
if b_norm == 0:
|
320 |
+
x = b
|
321 |
+
return (postprocess(x), 0)
|
322 |
+
|
323 |
+
if discard_C:
|
324 |
+
CU[:] = [(None, u) for c, u in CU]
|
325 |
+
|
326 |
+
# Reorthogonalize old vectors
|
327 |
+
if CU:
|
328 |
+
# Sort already existing vectors to the front
|
329 |
+
CU.sort(key=lambda cu: cu[0] is not None)
|
330 |
+
|
331 |
+
# Fill-in missing ones
|
332 |
+
C = np.empty((A.shape[0], len(CU)), dtype=r.dtype, order='F')
|
333 |
+
us = []
|
334 |
+
j = 0
|
335 |
+
while CU:
|
336 |
+
# More memory-efficient: throw away old vectors as we go
|
337 |
+
c, u = CU.pop(0)
|
338 |
+
if c is None:
|
339 |
+
c = matvec(u)
|
340 |
+
C[:,j] = c
|
341 |
+
j += 1
|
342 |
+
us.append(u)
|
343 |
+
|
344 |
+
# Orthogonalize
|
345 |
+
Q, R, P = qr(C, overwrite_a=True, mode='economic', pivoting=True)
|
346 |
+
del C
|
347 |
+
|
348 |
+
# C := Q
|
349 |
+
cs = list(Q.T)
|
350 |
+
|
351 |
+
# U := U P R^-1, back-substitution
|
352 |
+
new_us = []
|
353 |
+
for j in range(len(cs)):
|
354 |
+
u = us[P[j]]
|
355 |
+
for i in range(j):
|
356 |
+
u = axpy(us[P[i]], u, u.shape[0], -R[i,j])
|
357 |
+
if abs(R[j,j]) < 1e-12 * abs(R[0,0]):
|
358 |
+
# discard rest of the vectors
|
359 |
+
break
|
360 |
+
u = scal(1.0/R[j,j], u)
|
361 |
+
new_us.append(u)
|
362 |
+
|
363 |
+
# Form the new CU lists
|
364 |
+
CU[:] = list(zip(cs, new_us))[::-1]
|
365 |
+
|
366 |
+
if CU:
|
367 |
+
axpy, dot = get_blas_funcs(['axpy', 'dot'], (r,))
|
368 |
+
|
369 |
+
# Solve first the projection operation with respect to the CU
|
370 |
+
# vectors. This corresponds to modifying the initial guess to
|
371 |
+
# be
|
372 |
+
#
|
373 |
+
# x' = x + U y
|
374 |
+
# y = argmin_y || b - A (x + U y) ||^2
|
375 |
+
#
|
376 |
+
# The solution is y = C^H (b - A x)
|
377 |
+
for c, u in CU:
|
378 |
+
yc = dot(c, r)
|
379 |
+
x = axpy(u, x, x.shape[0], yc)
|
380 |
+
r = axpy(c, r, r.shape[0], -yc)
|
381 |
+
|
382 |
+
# GCROT main iteration
|
383 |
+
for j_outer in range(maxiter):
|
384 |
+
# -- callback
|
385 |
+
if callback is not None:
|
386 |
+
callback(x)
|
387 |
+
|
388 |
+
beta = nrm2(r)
|
389 |
+
|
390 |
+
# -- check stopping condition
|
391 |
+
beta_tol = max(atol, rtol * b_norm)
|
392 |
+
|
393 |
+
if beta <= beta_tol and (j_outer > 0 or CU):
|
394 |
+
# recompute residual to avoid rounding error
|
395 |
+
r = b - matvec(x)
|
396 |
+
beta = nrm2(r)
|
397 |
+
|
398 |
+
if beta <= beta_tol:
|
399 |
+
j_outer = -1
|
400 |
+
break
|
401 |
+
|
402 |
+
ml = m + max(k - len(CU), 0)
|
403 |
+
|
404 |
+
cs = [c for c, u in CU]
|
405 |
+
|
406 |
+
try:
|
407 |
+
Q, R, B, vs, zs, y, pres = _fgmres(matvec,
|
408 |
+
r/beta,
|
409 |
+
ml,
|
410 |
+
rpsolve=psolve,
|
411 |
+
atol=max(atol, rtol*b_norm)/beta,
|
412 |
+
cs=cs)
|
413 |
+
y *= beta
|
414 |
+
except LinAlgError:
|
415 |
+
# Floating point over/underflow, non-finite result from
|
416 |
+
# matmul etc. -- report failure.
|
417 |
+
break
|
418 |
+
|
419 |
+
#
|
420 |
+
# At this point,
|
421 |
+
#
|
422 |
+
# [A U, A Z] = [C, V] G; G = [ I B ]
|
423 |
+
# [ 0 H ]
|
424 |
+
#
|
425 |
+
# where [C, V] has orthonormal columns, and r = beta v_0. Moreover,
|
426 |
+
#
|
427 |
+
# || b - A (x + Z y + U q) ||_2 = || r - C B y - V H y - C q ||_2 = min!
|
428 |
+
#
|
429 |
+
# from which y = argmin_y || beta e_1 - H y ||_2, and q = -B y
|
430 |
+
#
|
431 |
+
|
432 |
+
#
|
433 |
+
# GCROT(m,k) update
|
434 |
+
#
|
435 |
+
|
436 |
+
# Define new outer vectors
|
437 |
+
|
438 |
+
# ux := (Z - U B) y
|
439 |
+
ux = zs[0]*y[0]
|
440 |
+
for z, yc in zip(zs[1:], y[1:]):
|
441 |
+
ux = axpy(z, ux, ux.shape[0], yc) # ux += z*yc
|
442 |
+
by = B.dot(y)
|
443 |
+
for cu, byc in zip(CU, by):
|
444 |
+
c, u = cu
|
445 |
+
ux = axpy(u, ux, ux.shape[0], -byc) # ux -= u*byc
|
446 |
+
|
447 |
+
# cx := V H y
|
448 |
+
hy = Q.dot(R.dot(y))
|
449 |
+
cx = vs[0] * hy[0]
|
450 |
+
for v, hyc in zip(vs[1:], hy[1:]):
|
451 |
+
cx = axpy(v, cx, cx.shape[0], hyc) # cx += v*hyc
|
452 |
+
|
453 |
+
# Normalize cx, maintaining cx = A ux
|
454 |
+
# This new cx is orthogonal to the previous C, by construction
|
455 |
+
try:
|
456 |
+
alpha = 1/nrm2(cx)
|
457 |
+
if not np.isfinite(alpha):
|
458 |
+
raise FloatingPointError()
|
459 |
+
except (FloatingPointError, ZeroDivisionError):
|
460 |
+
# Cannot update, so skip it
|
461 |
+
continue
|
462 |
+
|
463 |
+
cx = scal(alpha, cx)
|
464 |
+
ux = scal(alpha, ux)
|
465 |
+
|
466 |
+
# Update residual and solution
|
467 |
+
gamma = dot(cx, r)
|
468 |
+
r = axpy(cx, r, r.shape[0], -gamma) # r -= gamma*cx
|
469 |
+
x = axpy(ux, x, x.shape[0], gamma) # x += gamma*ux
|
470 |
+
|
471 |
+
# Truncate CU
|
472 |
+
if truncate == 'oldest':
|
473 |
+
while len(CU) >= k and CU:
|
474 |
+
del CU[0]
|
475 |
+
elif truncate == 'smallest':
|
476 |
+
if len(CU) >= k and CU:
|
477 |
+
# cf. [1,2]
|
478 |
+
D = solve(R[:-1,:].T, B.T).T
|
479 |
+
W, sigma, V = svd(D)
|
480 |
+
|
481 |
+
# C := C W[:,:k-1], U := U W[:,:k-1]
|
482 |
+
new_CU = []
|
483 |
+
for j, w in enumerate(W[:,:k-1].T):
|
484 |
+
c, u = CU[0]
|
485 |
+
c = c * w[0]
|
486 |
+
u = u * w[0]
|
487 |
+
for cup, wp in zip(CU[1:], w[1:]):
|
488 |
+
cp, up = cup
|
489 |
+
c = axpy(cp, c, c.shape[0], wp)
|
490 |
+
u = axpy(up, u, u.shape[0], wp)
|
491 |
+
|
492 |
+
# Reorthogonalize at the same time; not necessary
|
493 |
+
# in exact arithmetic, but floating point error
|
494 |
+
# tends to accumulate here
|
495 |
+
for cp, up in new_CU:
|
496 |
+
alpha = dot(cp, c)
|
497 |
+
c = axpy(cp, c, c.shape[0], -alpha)
|
498 |
+
u = axpy(up, u, u.shape[0], -alpha)
|
499 |
+
alpha = nrm2(c)
|
500 |
+
c = scal(1.0/alpha, c)
|
501 |
+
u = scal(1.0/alpha, u)
|
502 |
+
|
503 |
+
new_CU.append((c, u))
|
504 |
+
CU[:] = new_CU
|
505 |
+
|
506 |
+
# Add new vector to CU
|
507 |
+
CU.append((cx, ux))
|
508 |
+
|
509 |
+
# Include the solution vector to the span
|
510 |
+
CU.append((None, x.copy()))
|
511 |
+
if discard_C:
|
512 |
+
CU[:] = [(None, uz) for cz, uz in CU]
|
513 |
+
|
514 |
+
return postprocess(x), j_outer + 1
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/iterative.py
ADDED
@@ -0,0 +1,1079 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
from scipy._lib.deprecation import _NoValue, _deprecate_positional_args
|
7 |
+
|
8 |
+
__all__ = ['bicg', 'bicgstab', 'cg', 'cgs', 'gmres', 'qmr']
|
9 |
+
|
10 |
+
|
11 |
+
def _get_atol_rtol(name, b_norm, tol=_NoValue, atol=0., rtol=1e-5):
|
12 |
+
"""
|
13 |
+
A helper function to handle tolerance deprecations and normalization
|
14 |
+
"""
|
15 |
+
if tol is not _NoValue:
|
16 |
+
msg = (f"'scipy.sparse.linalg.{name}' keyword argument `tol` is "
|
17 |
+
"deprecated in favor of `rtol` and will be removed in SciPy "
|
18 |
+
"v1.14.0. Until then, if set, it will override `rtol`.")
|
19 |
+
warnings.warn(msg, category=DeprecationWarning, stacklevel=4)
|
20 |
+
rtol = float(tol) if tol is not None else rtol
|
21 |
+
|
22 |
+
if atol == 'legacy':
|
23 |
+
msg = (f"'scipy.sparse.linalg.{name}' called with `atol='legacy'`. "
|
24 |
+
"This behavior is deprecated and will result in an error in "
|
25 |
+
"SciPy v1.14.0. To preserve current behaviour, set `atol=0.0`.")
|
26 |
+
warnings.warn(msg, category=DeprecationWarning, stacklevel=4)
|
27 |
+
atol = 0
|
28 |
+
|
29 |
+
# this branch is only hit from gcrotmk/lgmres/tfqmr
|
30 |
+
if atol is None:
|
31 |
+
msg = (f"'scipy.sparse.linalg.{name}' called without specifying "
|
32 |
+
"`atol`. This behavior is deprecated and will result in an "
|
33 |
+
"error in SciPy v1.14.0. To preserve current behaviour, set "
|
34 |
+
"`atol=rtol`, or, to adopt the future default, set `atol=0.0`.")
|
35 |
+
warnings.warn(msg, category=DeprecationWarning, stacklevel=4)
|
36 |
+
atol = rtol
|
37 |
+
|
38 |
+
atol = max(float(atol), float(rtol) * float(b_norm))
|
39 |
+
|
40 |
+
return atol, rtol
|
41 |
+
|
42 |
+
|
43 |
+
@_deprecate_positional_args(version="1.14")
|
44 |
+
def bicg(A, b, x0=None, *, tol=_NoValue, maxiter=None, M=None, callback=None,
|
45 |
+
atol=0., rtol=1e-5):
|
46 |
+
"""Use BIConjugate Gradient iteration to solve ``Ax = b``.
|
47 |
+
|
48 |
+
Parameters
|
49 |
+
----------
|
50 |
+
A : {sparse matrix, ndarray, LinearOperator}
|
51 |
+
The real or complex N-by-N matrix of the linear system.
|
52 |
+
Alternatively, ``A`` can be a linear operator which can
|
53 |
+
produce ``Ax`` and ``A^T x`` using, e.g.,
|
54 |
+
``scipy.sparse.linalg.LinearOperator``.
|
55 |
+
b : ndarray
|
56 |
+
Right hand side of the linear system. Has shape (N,) or (N,1).
|
57 |
+
x0 : ndarray
|
58 |
+
Starting guess for the solution.
|
59 |
+
rtol, atol : float, optional
|
60 |
+
Parameters for the convergence test. For convergence,
|
61 |
+
``norm(b - A @ x) <= max(rtol*norm(b), atol)`` should be satisfied.
|
62 |
+
The default is ``atol=0.`` and ``rtol=1e-5``.
|
63 |
+
maxiter : integer
|
64 |
+
Maximum number of iterations. Iteration will stop after maxiter
|
65 |
+
steps even if the specified tolerance has not been achieved.
|
66 |
+
M : {sparse matrix, ndarray, LinearOperator}
|
67 |
+
Preconditioner for A. The preconditioner should approximate the
|
68 |
+
inverse of A. Effective preconditioning dramatically improves the
|
69 |
+
rate of convergence, which implies that fewer iterations are needed
|
70 |
+
to reach a given error tolerance.
|
71 |
+
callback : function
|
72 |
+
User-supplied function to call after each iteration. It is called
|
73 |
+
as callback(xk), where xk is the current solution vector.
|
74 |
+
tol : float, optional, deprecated
|
75 |
+
|
76 |
+
.. deprecated:: 1.12.0
|
77 |
+
`bicg` keyword argument ``tol`` is deprecated in favor of ``rtol``
|
78 |
+
and will be removed in SciPy 1.14.0.
|
79 |
+
|
80 |
+
Returns
|
81 |
+
-------
|
82 |
+
x : ndarray
|
83 |
+
The converged solution.
|
84 |
+
info : integer
|
85 |
+
Provides convergence information:
|
86 |
+
0 : successful exit
|
87 |
+
>0 : convergence to tolerance not achieved, number of iterations
|
88 |
+
<0 : parameter breakdown
|
89 |
+
|
90 |
+
Examples
|
91 |
+
--------
|
92 |
+
>>> import numpy as np
|
93 |
+
>>> from scipy.sparse import csc_matrix
|
94 |
+
>>> from scipy.sparse.linalg import bicg
|
95 |
+
>>> A = csc_matrix([[3, 2, 0], [1, -1, 0], [0, 5, 1.]])
|
96 |
+
>>> b = np.array([2., 4., -1.])
|
97 |
+
>>> x, exitCode = bicg(A, b, atol=1e-5)
|
98 |
+
>>> print(exitCode) # 0 indicates successful convergence
|
99 |
+
0
|
100 |
+
>>> np.allclose(A.dot(x), b)
|
101 |
+
True
|
102 |
+
|
103 |
+
"""
|
104 |
+
A, M, x, b, postprocess = make_system(A, M, x0, b)
|
105 |
+
bnrm2 = np.linalg.norm(b)
|
106 |
+
|
107 |
+
atol, _ = _get_atol_rtol('bicg', bnrm2, tol, atol, rtol)
|
108 |
+
|
109 |
+
if bnrm2 == 0:
|
110 |
+
return postprocess(b), 0
|
111 |
+
|
112 |
+
n = len(b)
|
113 |
+
dotprod = np.vdot if np.iscomplexobj(x) else np.dot
|
114 |
+
|
115 |
+
if maxiter is None:
|
116 |
+
maxiter = n*10
|
117 |
+
|
118 |
+
matvec, rmatvec = A.matvec, A.rmatvec
|
119 |
+
psolve, rpsolve = M.matvec, M.rmatvec
|
120 |
+
|
121 |
+
rhotol = np.finfo(x.dtype.char).eps**2
|
122 |
+
|
123 |
+
# Dummy values to initialize vars, silence linter warnings
|
124 |
+
rho_prev, p, ptilde = None, None, None
|
125 |
+
|
126 |
+
r = b - matvec(x) if x.any() else b.copy()
|
127 |
+
rtilde = r.copy()
|
128 |
+
|
129 |
+
for iteration in range(maxiter):
|
130 |
+
if np.linalg.norm(r) < atol: # Are we done?
|
131 |
+
return postprocess(x), 0
|
132 |
+
|
133 |
+
z = psolve(r)
|
134 |
+
ztilde = rpsolve(rtilde)
|
135 |
+
# order matters in this dot product
|
136 |
+
rho_cur = dotprod(rtilde, z)
|
137 |
+
|
138 |
+
if np.abs(rho_cur) < rhotol: # Breakdown case
|
139 |
+
return postprocess, -10
|
140 |
+
|
141 |
+
if iteration > 0:
|
142 |
+
beta = rho_cur / rho_prev
|
143 |
+
p *= beta
|
144 |
+
p += z
|
145 |
+
ptilde *= beta.conj()
|
146 |
+
ptilde += ztilde
|
147 |
+
else: # First spin
|
148 |
+
p = z.copy()
|
149 |
+
ptilde = ztilde.copy()
|
150 |
+
|
151 |
+
q = matvec(p)
|
152 |
+
qtilde = rmatvec(ptilde)
|
153 |
+
rv = dotprod(ptilde, q)
|
154 |
+
|
155 |
+
if rv == 0:
|
156 |
+
return postprocess(x), -11
|
157 |
+
|
158 |
+
alpha = rho_cur / rv
|
159 |
+
x += alpha*p
|
160 |
+
r -= alpha*q
|
161 |
+
rtilde -= alpha.conj()*qtilde
|
162 |
+
rho_prev = rho_cur
|
163 |
+
|
164 |
+
if callback:
|
165 |
+
callback(x)
|
166 |
+
|
167 |
+
else: # for loop exhausted
|
168 |
+
# Return incomplete progress
|
169 |
+
return postprocess(x), maxiter
|
170 |
+
|
171 |
+
|
172 |
+
@_deprecate_positional_args(version="1.14")
|
173 |
+
def bicgstab(A, b, *, x0=None, tol=_NoValue, maxiter=None, M=None,
|
174 |
+
callback=None, atol=0., rtol=1e-5):
|
175 |
+
"""Use BIConjugate Gradient STABilized iteration to solve ``Ax = b``.
|
176 |
+
|
177 |
+
Parameters
|
178 |
+
----------
|
179 |
+
A : {sparse matrix, ndarray, LinearOperator}
|
180 |
+
The real or complex N-by-N matrix of the linear system.
|
181 |
+
Alternatively, ``A`` can be a linear operator which can
|
182 |
+
produce ``Ax`` and ``A^T x`` using, e.g.,
|
183 |
+
``scipy.sparse.linalg.LinearOperator``.
|
184 |
+
b : ndarray
|
185 |
+
Right hand side of the linear system. Has shape (N,) or (N,1).
|
186 |
+
x0 : ndarray
|
187 |
+
Starting guess for the solution.
|
188 |
+
rtol, atol : float, optional
|
189 |
+
Parameters for the convergence test. For convergence,
|
190 |
+
``norm(b - A @ x) <= max(rtol*norm(b), atol)`` should be satisfied.
|
191 |
+
The default is ``atol=0.`` and ``rtol=1e-5``.
|
192 |
+
maxiter : integer
|
193 |
+
Maximum number of iterations. Iteration will stop after maxiter
|
194 |
+
steps even if the specified tolerance has not been achieved.
|
195 |
+
M : {sparse matrix, ndarray, LinearOperator}
|
196 |
+
Preconditioner for A. The preconditioner should approximate the
|
197 |
+
inverse of A. Effective preconditioning dramatically improves the
|
198 |
+
rate of convergence, which implies that fewer iterations are needed
|
199 |
+
to reach a given error tolerance.
|
200 |
+
callback : function
|
201 |
+
User-supplied function to call after each iteration. It is called
|
202 |
+
as callback(xk), where xk is the current solution vector.
|
203 |
+
tol : float, optional, deprecated
|
204 |
+
|
205 |
+
.. deprecated:: 1.12.0
|
206 |
+
`bicgstab` keyword argument ``tol`` is deprecated in favor of
|
207 |
+
``rtol`` and will be removed in SciPy 1.14.0.
|
208 |
+
|
209 |
+
Returns
|
210 |
+
-------
|
211 |
+
x : ndarray
|
212 |
+
The converged solution.
|
213 |
+
info : integer
|
214 |
+
Provides convergence information:
|
215 |
+
0 : successful exit
|
216 |
+
>0 : convergence to tolerance not achieved, number of iterations
|
217 |
+
<0 : parameter breakdown
|
218 |
+
|
219 |
+
Examples
|
220 |
+
--------
|
221 |
+
>>> import numpy as np
|
222 |
+
>>> from scipy.sparse import csc_matrix
|
223 |
+
>>> from scipy.sparse.linalg import bicgstab
|
224 |
+
>>> R = np.array([[4, 2, 0, 1],
|
225 |
+
... [3, 0, 0, 2],
|
226 |
+
... [0, 1, 1, 1],
|
227 |
+
... [0, 2, 1, 0]])
|
228 |
+
>>> A = csc_matrix(R)
|
229 |
+
>>> b = np.array([-1, -0.5, -1, 2])
|
230 |
+
>>> x, exit_code = bicgstab(A, b, atol=1e-5)
|
231 |
+
>>> print(exit_code) # 0 indicates successful convergence
|
232 |
+
0
|
233 |
+
>>> np.allclose(A.dot(x), b)
|
234 |
+
True
|
235 |
+
|
236 |
+
"""
|
237 |
+
A, M, x, b, postprocess = make_system(A, M, x0, b)
|
238 |
+
bnrm2 = np.linalg.norm(b)
|
239 |
+
|
240 |
+
atol, _ = _get_atol_rtol('bicgstab', bnrm2, tol, atol, rtol)
|
241 |
+
|
242 |
+
if bnrm2 == 0:
|
243 |
+
return postprocess(b), 0
|
244 |
+
|
245 |
+
n = len(b)
|
246 |
+
|
247 |
+
dotprod = np.vdot if np.iscomplexobj(x) else np.dot
|
248 |
+
|
249 |
+
if maxiter is None:
|
250 |
+
maxiter = n*10
|
251 |
+
|
252 |
+
matvec = A.matvec
|
253 |
+
psolve = M.matvec
|
254 |
+
|
255 |
+
# These values make no sense but coming from original Fortran code
|
256 |
+
# sqrt might have been meant instead.
|
257 |
+
rhotol = np.finfo(x.dtype.char).eps**2
|
258 |
+
omegatol = rhotol
|
259 |
+
|
260 |
+
# Dummy values to initialize vars, silence linter warnings
|
261 |
+
rho_prev, omega, alpha, p, v = None, None, None, None, None
|
262 |
+
|
263 |
+
r = b - matvec(x) if x.any() else b.copy()
|
264 |
+
rtilde = r.copy()
|
265 |
+
|
266 |
+
for iteration in range(maxiter):
|
267 |
+
if np.linalg.norm(r) < atol: # Are we done?
|
268 |
+
return postprocess(x), 0
|
269 |
+
|
270 |
+
rho = dotprod(rtilde, r)
|
271 |
+
if np.abs(rho) < rhotol: # rho breakdown
|
272 |
+
return postprocess(x), -10
|
273 |
+
|
274 |
+
if iteration > 0:
|
275 |
+
if np.abs(omega) < omegatol: # omega breakdown
|
276 |
+
return postprocess(x), -11
|
277 |
+
|
278 |
+
beta = (rho / rho_prev) * (alpha / omega)
|
279 |
+
p -= omega*v
|
280 |
+
p *= beta
|
281 |
+
p += r
|
282 |
+
else: # First spin
|
283 |
+
s = np.empty_like(r)
|
284 |
+
p = r.copy()
|
285 |
+
|
286 |
+
phat = psolve(p)
|
287 |
+
v = matvec(phat)
|
288 |
+
rv = dotprod(rtilde, v)
|
289 |
+
if rv == 0:
|
290 |
+
return postprocess(x), -11
|
291 |
+
alpha = rho / rv
|
292 |
+
r -= alpha*v
|
293 |
+
s[:] = r[:]
|
294 |
+
|
295 |
+
if np.linalg.norm(s) < atol:
|
296 |
+
x += alpha*phat
|
297 |
+
return postprocess(x), 0
|
298 |
+
|
299 |
+
shat = psolve(s)
|
300 |
+
t = matvec(shat)
|
301 |
+
omega = dotprod(t, s) / dotprod(t, t)
|
302 |
+
x += alpha*phat
|
303 |
+
x += omega*shat
|
304 |
+
r -= omega*t
|
305 |
+
rho_prev = rho
|
306 |
+
|
307 |
+
if callback:
|
308 |
+
callback(x)
|
309 |
+
|
310 |
+
else: # for loop exhausted
|
311 |
+
# Return incomplete progress
|
312 |
+
return postprocess(x), maxiter
|
313 |
+
|
314 |
+
|
315 |
+
@_deprecate_positional_args(version="1.14")
|
316 |
+
def cg(A, b, x0=None, *, tol=_NoValue, maxiter=None, M=None, callback=None,
|
317 |
+
atol=0., rtol=1e-5):
|
318 |
+
"""Use Conjugate Gradient iteration to solve ``Ax = b``.
|
319 |
+
|
320 |
+
Parameters
|
321 |
+
----------
|
322 |
+
A : {sparse matrix, ndarray, LinearOperator}
|
323 |
+
The real or complex N-by-N matrix of the linear system.
|
324 |
+
``A`` must represent a hermitian, positive definite matrix.
|
325 |
+
Alternatively, ``A`` can be a linear operator which can
|
326 |
+
produce ``Ax`` using, e.g.,
|
327 |
+
``scipy.sparse.linalg.LinearOperator``.
|
328 |
+
b : ndarray
|
329 |
+
Right hand side of the linear system. Has shape (N,) or (N,1).
|
330 |
+
x0 : ndarray
|
331 |
+
Starting guess for the solution.
|
332 |
+
rtol, atol : float, optional
|
333 |
+
Parameters for the convergence test. For convergence,
|
334 |
+
``norm(b - A @ x) <= max(rtol*norm(b), atol)`` should be satisfied.
|
335 |
+
The default is ``atol=0.`` and ``rtol=1e-5``.
|
336 |
+
maxiter : integer
|
337 |
+
Maximum number of iterations. Iteration will stop after maxiter
|
338 |
+
steps even if the specified tolerance has not been achieved.
|
339 |
+
M : {sparse matrix, ndarray, LinearOperator}
|
340 |
+
Preconditioner for A. The preconditioner should approximate the
|
341 |
+
inverse of A. Effective preconditioning dramatically improves the
|
342 |
+
rate of convergence, which implies that fewer iterations are needed
|
343 |
+
to reach a given error tolerance.
|
344 |
+
callback : function
|
345 |
+
User-supplied function to call after each iteration. It is called
|
346 |
+
as callback(xk), where xk is the current solution vector.
|
347 |
+
tol : float, optional, deprecated
|
348 |
+
|
349 |
+
.. deprecated:: 1.12.0
|
350 |
+
`cg` keyword argument ``tol`` is deprecated in favor of ``rtol`` and
|
351 |
+
will be removed in SciPy 1.14.0.
|
352 |
+
|
353 |
+
Returns
|
354 |
+
-------
|
355 |
+
x : ndarray
|
356 |
+
The converged solution.
|
357 |
+
info : integer
|
358 |
+
Provides convergence information:
|
359 |
+
0 : successful exit
|
360 |
+
>0 : convergence to tolerance not achieved, number of iterations
|
361 |
+
|
362 |
+
Examples
|
363 |
+
--------
|
364 |
+
>>> import numpy as np
|
365 |
+
>>> from scipy.sparse import csc_matrix
|
366 |
+
>>> from scipy.sparse.linalg import cg
|
367 |
+
>>> P = np.array([[4, 0, 1, 0],
|
368 |
+
... [0, 5, 0, 0],
|
369 |
+
... [1, 0, 3, 2],
|
370 |
+
... [0, 0, 2, 4]])
|
371 |
+
>>> A = csc_matrix(P)
|
372 |
+
>>> b = np.array([-1, -0.5, -1, 2])
|
373 |
+
>>> x, exit_code = cg(A, b, atol=1e-5)
|
374 |
+
>>> print(exit_code) # 0 indicates successful convergence
|
375 |
+
0
|
376 |
+
>>> np.allclose(A.dot(x), b)
|
377 |
+
True
|
378 |
+
|
379 |
+
"""
|
380 |
+
A, M, x, b, postprocess = make_system(A, M, x0, b)
|
381 |
+
bnrm2 = np.linalg.norm(b)
|
382 |
+
|
383 |
+
atol, _ = _get_atol_rtol('cg', bnrm2, tol, atol, rtol)
|
384 |
+
|
385 |
+
if bnrm2 == 0:
|
386 |
+
return postprocess(b), 0
|
387 |
+
|
388 |
+
n = len(b)
|
389 |
+
|
390 |
+
if maxiter is None:
|
391 |
+
maxiter = n*10
|
392 |
+
|
393 |
+
dotprod = np.vdot if np.iscomplexobj(x) else np.dot
|
394 |
+
|
395 |
+
matvec = A.matvec
|
396 |
+
psolve = M.matvec
|
397 |
+
r = b - matvec(x) if x.any() else b.copy()
|
398 |
+
|
399 |
+
# Dummy value to initialize var, silences warnings
|
400 |
+
rho_prev, p = None, None
|
401 |
+
|
402 |
+
for iteration in range(maxiter):
|
403 |
+
if np.linalg.norm(r) < atol: # Are we done?
|
404 |
+
return postprocess(x), 0
|
405 |
+
|
406 |
+
z = psolve(r)
|
407 |
+
rho_cur = dotprod(r, z)
|
408 |
+
if iteration > 0:
|
409 |
+
beta = rho_cur / rho_prev
|
410 |
+
p *= beta
|
411 |
+
p += z
|
412 |
+
else: # First spin
|
413 |
+
p = np.empty_like(r)
|
414 |
+
p[:] = z[:]
|
415 |
+
|
416 |
+
q = matvec(p)
|
417 |
+
alpha = rho_cur / dotprod(p, q)
|
418 |
+
x += alpha*p
|
419 |
+
r -= alpha*q
|
420 |
+
rho_prev = rho_cur
|
421 |
+
|
422 |
+
if callback:
|
423 |
+
callback(x)
|
424 |
+
|
425 |
+
else: # for loop exhausted
|
426 |
+
# Return incomplete progress
|
427 |
+
return postprocess(x), maxiter
|
428 |
+
|
429 |
+
|
430 |
+
@_deprecate_positional_args(version="1.14")
|
431 |
+
def cgs(A, b, x0=None, *, tol=_NoValue, maxiter=None, M=None, callback=None,
|
432 |
+
atol=0., rtol=1e-5):
|
433 |
+
"""Use Conjugate Gradient Squared iteration to solve ``Ax = b``.
|
434 |
+
|
435 |
+
Parameters
|
436 |
+
----------
|
437 |
+
A : {sparse matrix, ndarray, LinearOperator}
|
438 |
+
The real-valued N-by-N matrix of the linear system.
|
439 |
+
Alternatively, ``A`` can be a linear operator which can
|
440 |
+
produce ``Ax`` using, e.g.,
|
441 |
+
``scipy.sparse.linalg.LinearOperator``.
|
442 |
+
b : ndarray
|
443 |
+
Right hand side of the linear system. Has shape (N,) or (N,1).
|
444 |
+
x0 : ndarray
|
445 |
+
Starting guess for the solution.
|
446 |
+
rtol, atol : float, optional
|
447 |
+
Parameters for the convergence test. For convergence,
|
448 |
+
``norm(b - A @ x) <= max(rtol*norm(b), atol)`` should be satisfied.
|
449 |
+
The default is ``atol=0.`` and ``rtol=1e-5``.
|
450 |
+
maxiter : integer
|
451 |
+
Maximum number of iterations. Iteration will stop after maxiter
|
452 |
+
steps even if the specified tolerance has not been achieved.
|
453 |
+
M : {sparse matrix, ndarray, LinearOperator}
|
454 |
+
Preconditioner for A. The preconditioner should approximate the
|
455 |
+
inverse of A. Effective preconditioning dramatically improves the
|
456 |
+
rate of convergence, which implies that fewer iterations are needed
|
457 |
+
to reach a given error tolerance.
|
458 |
+
callback : function
|
459 |
+
User-supplied function to call after each iteration. It is called
|
460 |
+
as callback(xk), where xk is the current solution vector.
|
461 |
+
tol : float, optional, deprecated
|
462 |
+
|
463 |
+
.. deprecated:: 1.12.0
|
464 |
+
`cgs` keyword argument ``tol`` is deprecated in favor of ``rtol``
|
465 |
+
and will be removed in SciPy 1.14.0.
|
466 |
+
|
467 |
+
Returns
|
468 |
+
-------
|
469 |
+
x : ndarray
|
470 |
+
The converged solution.
|
471 |
+
info : integer
|
472 |
+
Provides convergence information:
|
473 |
+
0 : successful exit
|
474 |
+
>0 : convergence to tolerance not achieved, number of iterations
|
475 |
+
<0 : parameter breakdown
|
476 |
+
|
477 |
+
Examples
|
478 |
+
--------
|
479 |
+
>>> import numpy as np
|
480 |
+
>>> from scipy.sparse import csc_matrix
|
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_matrix(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 |
+
"""
|
495 |
+
A, M, x, b, postprocess = make_system(A, M, x0, b)
|
496 |
+
bnrm2 = np.linalg.norm(b)
|
497 |
+
|
498 |
+
atol, _ = _get_atol_rtol('cgs', bnrm2, tol, atol, rtol)
|
499 |
+
|
500 |
+
if bnrm2 == 0:
|
501 |
+
return postprocess(b), 0
|
502 |
+
|
503 |
+
n = len(b)
|
504 |
+
|
505 |
+
dotprod = np.vdot if np.iscomplexobj(x) else np.dot
|
506 |
+
|
507 |
+
if maxiter is None:
|
508 |
+
maxiter = n*10
|
509 |
+
|
510 |
+
matvec = A.matvec
|
511 |
+
psolve = M.matvec
|
512 |
+
|
513 |
+
rhotol = np.finfo(x.dtype.char).eps**2
|
514 |
+
|
515 |
+
r = b - matvec(x) if x.any() else b.copy()
|
516 |
+
|
517 |
+
rtilde = r.copy()
|
518 |
+
bnorm = np.linalg.norm(b)
|
519 |
+
if bnorm == 0:
|
520 |
+
bnorm = 1
|
521 |
+
|
522 |
+
# Dummy values to initialize vars, silence linter warnings
|
523 |
+
rho_prev, p, u, q = None, None, None, None
|
524 |
+
|
525 |
+
for iteration in range(maxiter):
|
526 |
+
rnorm = np.linalg.norm(r)
|
527 |
+
if rnorm < atol: # Are we done?
|
528 |
+
return postprocess(x), 0
|
529 |
+
|
530 |
+
rho_cur = dotprod(rtilde, r)
|
531 |
+
if np.abs(rho_cur) < rhotol: # Breakdown case
|
532 |
+
return postprocess, -10
|
533 |
+
|
534 |
+
if iteration > 0:
|
535 |
+
beta = rho_cur / rho_prev
|
536 |
+
|
537 |
+
# u = r + beta * q
|
538 |
+
# p = u + beta * (q + beta * p);
|
539 |
+
u[:] = r[:]
|
540 |
+
u += beta*q
|
541 |
+
|
542 |
+
p *= beta
|
543 |
+
p += q
|
544 |
+
p *= beta
|
545 |
+
p += u
|
546 |
+
|
547 |
+
else: # First spin
|
548 |
+
p = r.copy()
|
549 |
+
u = r.copy()
|
550 |
+
q = np.empty_like(r)
|
551 |
+
|
552 |
+
phat = psolve(p)
|
553 |
+
vhat = matvec(phat)
|
554 |
+
rv = dotprod(rtilde, vhat)
|
555 |
+
|
556 |
+
if rv == 0: # Dot product breakdown
|
557 |
+
return postprocess(x), -11
|
558 |
+
|
559 |
+
alpha = rho_cur / rv
|
560 |
+
q[:] = u[:]
|
561 |
+
q -= alpha*vhat
|
562 |
+
uhat = psolve(u + q)
|
563 |
+
x += alpha*uhat
|
564 |
+
|
565 |
+
# Due to numerical error build-up the actual residual is computed
|
566 |
+
# instead of the following two lines that were in the original
|
567 |
+
# FORTRAN templates, still using a single matvec.
|
568 |
+
|
569 |
+
# qhat = matvec(uhat)
|
570 |
+
# r -= alpha*qhat
|
571 |
+
r = b - matvec(x)
|
572 |
+
|
573 |
+
rho_prev = rho_cur
|
574 |
+
|
575 |
+
if callback:
|
576 |
+
callback(x)
|
577 |
+
|
578 |
+
else: # for loop exhausted
|
579 |
+
# Return incomplete progress
|
580 |
+
return postprocess(x), maxiter
|
581 |
+
|
582 |
+
|
583 |
+
@_deprecate_positional_args(version="1.14")
|
584 |
+
def gmres(A, b, x0=None, *, tol=_NoValue, restart=None, maxiter=None, M=None,
|
585 |
+
callback=None, restrt=_NoValue, atol=0., callback_type=None,
|
586 |
+
rtol=1e-5):
|
587 |
+
"""
|
588 |
+
Use Generalized Minimal RESidual iteration to solve ``Ax = b``.
|
589 |
+
|
590 |
+
Parameters
|
591 |
+
----------
|
592 |
+
A : {sparse matrix, ndarray, LinearOperator}
|
593 |
+
The real or complex N-by-N matrix of the linear system.
|
594 |
+
Alternatively, ``A`` can be a linear operator which can
|
595 |
+
produce ``Ax`` using, e.g.,
|
596 |
+
``scipy.sparse.linalg.LinearOperator``.
|
597 |
+
b : ndarray
|
598 |
+
Right hand side of the linear system. Has shape (N,) or (N,1).
|
599 |
+
x0 : ndarray
|
600 |
+
Starting guess for the solution (a vector of zeros by default).
|
601 |
+
atol, rtol : float
|
602 |
+
Parameters for the convergence test. For convergence,
|
603 |
+
``norm(b - A @ x) <= max(rtol*norm(b), atol)`` should be satisfied.
|
604 |
+
The default is ``atol=0.`` and ``rtol=1e-5``.
|
605 |
+
restart : int, optional
|
606 |
+
Number of iterations between restarts. Larger values increase
|
607 |
+
iteration cost, but may be necessary for convergence.
|
608 |
+
If omitted, ``min(20, n)`` is used.
|
609 |
+
maxiter : int, optional
|
610 |
+
Maximum number of iterations (restart cycles). Iteration will stop
|
611 |
+
after maxiter steps even if the specified tolerance has not been
|
612 |
+
achieved. See `callback_type`.
|
613 |
+
M : {sparse matrix, ndarray, LinearOperator}
|
614 |
+
Inverse of the preconditioner of A. M should approximate the
|
615 |
+
inverse of A and be easy to solve for (see Notes). Effective
|
616 |
+
preconditioning dramatically improves the rate of convergence,
|
617 |
+
which implies that fewer iterations are needed to reach a given
|
618 |
+
error tolerance. By default, no preconditioner is used.
|
619 |
+
In this implementation, left preconditioning is used,
|
620 |
+
and the preconditioned residual is minimized. However, the final
|
621 |
+
convergence is tested with respect to the ``b - A @ x`` residual.
|
622 |
+
callback : function
|
623 |
+
User-supplied function to call after each iteration. It is called
|
624 |
+
as `callback(args)`, where `args` are selected by `callback_type`.
|
625 |
+
callback_type : {'x', 'pr_norm', 'legacy'}, optional
|
626 |
+
Callback function argument requested:
|
627 |
+
- ``x``: current iterate (ndarray), called on every restart
|
628 |
+
- ``pr_norm``: relative (preconditioned) residual norm (float),
|
629 |
+
called on every inner iteration
|
630 |
+
- ``legacy`` (default): same as ``pr_norm``, but also changes the
|
631 |
+
meaning of `maxiter` to count inner iterations instead of restart
|
632 |
+
cycles.
|
633 |
+
|
634 |
+
This keyword has no effect if `callback` is not set.
|
635 |
+
restrt : int, optional, deprecated
|
636 |
+
|
637 |
+
.. deprecated:: 0.11.0
|
638 |
+
`gmres` keyword argument ``restrt`` is deprecated in favor of
|
639 |
+
``restart`` and will be removed in SciPy 1.14.0.
|
640 |
+
tol : float, optional, deprecated
|
641 |
+
|
642 |
+
.. deprecated:: 1.12.0
|
643 |
+
`gmres` keyword argument ``tol`` is deprecated in favor of ``rtol``
|
644 |
+
and will be removed in SciPy 1.14.0
|
645 |
+
|
646 |
+
Returns
|
647 |
+
-------
|
648 |
+
x : ndarray
|
649 |
+
The converged solution.
|
650 |
+
info : int
|
651 |
+
Provides convergence information:
|
652 |
+
0 : successful exit
|
653 |
+
>0 : convergence to tolerance not achieved, number of iterations
|
654 |
+
|
655 |
+
See Also
|
656 |
+
--------
|
657 |
+
LinearOperator
|
658 |
+
|
659 |
+
Notes
|
660 |
+
-----
|
661 |
+
A preconditioner, P, is chosen such that P is close to A but easy to solve
|
662 |
+
for. The preconditioner parameter required by this routine is
|
663 |
+
``M = P^-1``. The inverse should preferably not be calculated
|
664 |
+
explicitly. Rather, use the following template to produce M::
|
665 |
+
|
666 |
+
# Construct a linear operator that computes P^-1 @ x.
|
667 |
+
import scipy.sparse.linalg as spla
|
668 |
+
M_x = lambda x: spla.spsolve(P, x)
|
669 |
+
M = spla.LinearOperator((n, n), M_x)
|
670 |
+
|
671 |
+
Examples
|
672 |
+
--------
|
673 |
+
>>> import numpy as np
|
674 |
+
>>> from scipy.sparse import csc_matrix
|
675 |
+
>>> from scipy.sparse.linalg import gmres
|
676 |
+
>>> A = csc_matrix([[3, 2, 0], [1, -1, 0], [0, 5, 1]], dtype=float)
|
677 |
+
>>> b = np.array([2, 4, -1], dtype=float)
|
678 |
+
>>> x, exitCode = gmres(A, b, atol=1e-5)
|
679 |
+
>>> print(exitCode) # 0 indicates successful convergence
|
680 |
+
0
|
681 |
+
>>> np.allclose(A.dot(x), b)
|
682 |
+
True
|
683 |
+
"""
|
684 |
+
|
685 |
+
# Handle the deprecation frenzy
|
686 |
+
if restrt not in (None, _NoValue) and restart:
|
687 |
+
raise ValueError("Cannot specify both 'restart' and 'restrt'"
|
688 |
+
" keywords. Also 'rstrt' is deprecated."
|
689 |
+
" and will be removed in SciPy 1.14.0. Use "
|
690 |
+
"'restart' instead.")
|
691 |
+
if restrt is not _NoValue:
|
692 |
+
msg = ("'gmres' keyword argument 'restrt' is deprecated "
|
693 |
+
"in favor of 'restart' and will be removed in SciPy"
|
694 |
+
" 1.14.0. Until then, if set, 'rstrt' will override 'restart'."
|
695 |
+
)
|
696 |
+
warnings.warn(msg, DeprecationWarning, stacklevel=3)
|
697 |
+
restart = restrt
|
698 |
+
|
699 |
+
if callback is not None and callback_type is None:
|
700 |
+
# Warn about 'callback_type' semantic changes.
|
701 |
+
# Probably should be removed only in far future, Scipy 2.0 or so.
|
702 |
+
msg = ("scipy.sparse.linalg.gmres called without specifying "
|
703 |
+
"`callback_type`. The default value will be changed in"
|
704 |
+
" a future release. For compatibility, specify a value "
|
705 |
+
"for `callback_type` explicitly, e.g., "
|
706 |
+
"``gmres(..., callback_type='pr_norm')``, or to retain the "
|
707 |
+
"old behavior ``gmres(..., callback_type='legacy')``"
|
708 |
+
)
|
709 |
+
warnings.warn(msg, category=DeprecationWarning, stacklevel=3)
|
710 |
+
|
711 |
+
if callback_type is None:
|
712 |
+
callback_type = 'legacy'
|
713 |
+
|
714 |
+
if callback_type not in ('x', 'pr_norm', 'legacy'):
|
715 |
+
raise ValueError(f"Unknown callback_type: {callback_type!r}")
|
716 |
+
|
717 |
+
if callback is None:
|
718 |
+
callback_type = None
|
719 |
+
|
720 |
+
A, M, x, b, postprocess = make_system(A, M, x0, b)
|
721 |
+
matvec = A.matvec
|
722 |
+
psolve = M.matvec
|
723 |
+
n = len(b)
|
724 |
+
bnrm2 = np.linalg.norm(b)
|
725 |
+
|
726 |
+
atol, _ = _get_atol_rtol('gmres', bnrm2, tol, atol, rtol)
|
727 |
+
|
728 |
+
if bnrm2 == 0:
|
729 |
+
return postprocess(b), 0
|
730 |
+
|
731 |
+
eps = np.finfo(x.dtype.char).eps
|
732 |
+
|
733 |
+
dotprod = np.vdot if np.iscomplexobj(x) else np.dot
|
734 |
+
|
735 |
+
if maxiter is None:
|
736 |
+
maxiter = n*10
|
737 |
+
|
738 |
+
if restart is None:
|
739 |
+
restart = 20
|
740 |
+
restart = min(restart, n)
|
741 |
+
|
742 |
+
Mb_nrm2 = np.linalg.norm(psolve(b))
|
743 |
+
|
744 |
+
# ====================================================
|
745 |
+
# =========== Tolerance control from gh-8400 =========
|
746 |
+
# ====================================================
|
747 |
+
# Tolerance passed to GMRESREVCOM applies to the inner
|
748 |
+
# iteration and deals with the left-preconditioned
|
749 |
+
# residual.
|
750 |
+
ptol_max_factor = 1.
|
751 |
+
ptol = Mb_nrm2 * min(ptol_max_factor, atol / bnrm2)
|
752 |
+
presid = 0.
|
753 |
+
# ====================================================
|
754 |
+
lartg = get_lapack_funcs('lartg', dtype=x.dtype)
|
755 |
+
|
756 |
+
# allocate internal variables
|
757 |
+
v = np.empty([restart+1, n], dtype=x.dtype)
|
758 |
+
h = np.zeros([restart, restart+1], dtype=x.dtype)
|
759 |
+
givens = np.zeros([restart, 2], dtype=x.dtype)
|
760 |
+
|
761 |
+
# legacy iteration count
|
762 |
+
inner_iter = 0
|
763 |
+
|
764 |
+
for iteration in range(maxiter):
|
765 |
+
if iteration == 0:
|
766 |
+
r = b - matvec(x) if x.any() else b.copy()
|
767 |
+
if np.linalg.norm(r) < atol: # Are we done?
|
768 |
+
return postprocess(x), 0
|
769 |
+
|
770 |
+
v[0, :] = psolve(r)
|
771 |
+
tmp = np.linalg.norm(v[0, :])
|
772 |
+
v[0, :] *= (1 / tmp)
|
773 |
+
# RHS of the Hessenberg problem
|
774 |
+
S = np.zeros(restart+1, dtype=x.dtype)
|
775 |
+
S[0] = tmp
|
776 |
+
|
777 |
+
breakdown = False
|
778 |
+
for col in range(restart):
|
779 |
+
av = matvec(v[col, :])
|
780 |
+
w = psolve(av)
|
781 |
+
|
782 |
+
# Modified Gram-Schmidt
|
783 |
+
h0 = np.linalg.norm(w)
|
784 |
+
for k in range(col+1):
|
785 |
+
tmp = dotprod(v[k, :], w)
|
786 |
+
h[col, k] = tmp
|
787 |
+
w -= tmp*v[k, :]
|
788 |
+
|
789 |
+
h1 = np.linalg.norm(w)
|
790 |
+
h[col, col + 1] = h1
|
791 |
+
v[col + 1, :] = w[:]
|
792 |
+
|
793 |
+
# Exact solution indicator
|
794 |
+
if h1 <= eps*h0:
|
795 |
+
h[col, col + 1] = 0
|
796 |
+
breakdown = True
|
797 |
+
else:
|
798 |
+
v[col + 1, :] *= (1 / h1)
|
799 |
+
|
800 |
+
# apply past Givens rotations to current h column
|
801 |
+
for k in range(col):
|
802 |
+
c, s = givens[k, 0], givens[k, 1]
|
803 |
+
n0, n1 = h[col, [k, k+1]]
|
804 |
+
h[col, [k, k + 1]] = [c*n0 + s*n1, -s.conj()*n0 + c*n1]
|
805 |
+
|
806 |
+
# get and apply current rotation to h and S
|
807 |
+
c, s, mag = lartg(h[col, col], h[col, col+1])
|
808 |
+
givens[col, :] = [c, s]
|
809 |
+
h[col, [col, col+1]] = mag, 0
|
810 |
+
|
811 |
+
# S[col+1] component is always 0
|
812 |
+
tmp = -np.conjugate(s)*S[col]
|
813 |
+
S[[col, col + 1]] = [c*S[col], tmp]
|
814 |
+
presid = np.abs(tmp)
|
815 |
+
inner_iter += 1
|
816 |
+
|
817 |
+
if callback_type in ('legacy', 'pr_norm'):
|
818 |
+
callback(presid / bnrm2)
|
819 |
+
# Legacy behavior
|
820 |
+
if callback_type == 'legacy' and inner_iter == maxiter:
|
821 |
+
break
|
822 |
+
if presid <= ptol or breakdown:
|
823 |
+
break
|
824 |
+
|
825 |
+
# Solve h(col, col) upper triangular system and allow pseudo-solve
|
826 |
+
# singular cases as in (but without the f2py copies):
|
827 |
+
# y = trsv(h[:col+1, :col+1].T, S[:col+1])
|
828 |
+
|
829 |
+
if h[col, col] == 0:
|
830 |
+
S[col] = 0
|
831 |
+
|
832 |
+
y = np.zeros([col+1], dtype=x.dtype)
|
833 |
+
y[:] = S[:col+1]
|
834 |
+
for k in range(col, 0, -1):
|
835 |
+
if y[k] != 0:
|
836 |
+
y[k] /= h[k, k]
|
837 |
+
tmp = y[k]
|
838 |
+
y[:k] -= tmp*h[k, :k]
|
839 |
+
if y[0] != 0:
|
840 |
+
y[0] /= h[0, 0]
|
841 |
+
|
842 |
+
x += y @ v[:col+1, :]
|
843 |
+
|
844 |
+
r = b - matvec(x)
|
845 |
+
rnorm = np.linalg.norm(r)
|
846 |
+
|
847 |
+
# Legacy exit
|
848 |
+
if callback_type == 'legacy' and inner_iter == maxiter:
|
849 |
+
return postprocess(x), 0 if rnorm <= atol else maxiter
|
850 |
+
|
851 |
+
if callback_type == 'x':
|
852 |
+
callback(x)
|
853 |
+
|
854 |
+
if rnorm <= atol:
|
855 |
+
break
|
856 |
+
elif breakdown:
|
857 |
+
# Reached breakdown (= exact solution), but the external
|
858 |
+
# tolerance check failed. Bail out with failure.
|
859 |
+
break
|
860 |
+
elif presid <= ptol:
|
861 |
+
# Inner loop passed but outer didn't
|
862 |
+
ptol_max_factor = max(eps, 0.25 * ptol_max_factor)
|
863 |
+
else:
|
864 |
+
ptol_max_factor = min(1.0, 1.5 * ptol_max_factor)
|
865 |
+
|
866 |
+
ptol = presid * min(ptol_max_factor, atol / rnorm)
|
867 |
+
|
868 |
+
info = 0 if (rnorm <= atol) else maxiter
|
869 |
+
return postprocess(x), info
|
870 |
+
|
871 |
+
|
872 |
+
@_deprecate_positional_args(version="1.14")
|
873 |
+
def qmr(A, b, x0=None, *, tol=_NoValue, maxiter=None, M1=None, M2=None,
|
874 |
+
callback=None, atol=0., rtol=1e-5):
|
875 |
+
"""Use Quasi-Minimal Residual iteration to solve ``Ax = b``.
|
876 |
+
|
877 |
+
Parameters
|
878 |
+
----------
|
879 |
+
A : {sparse matrix, ndarray, LinearOperator}
|
880 |
+
The real-valued N-by-N matrix of the linear system.
|
881 |
+
Alternatively, ``A`` can be a linear operator which can
|
882 |
+
produce ``Ax`` and ``A^T x`` using, e.g.,
|
883 |
+
``scipy.sparse.linalg.LinearOperator``.
|
884 |
+
b : ndarray
|
885 |
+
Right hand side of the linear system. Has shape (N,) or (N,1).
|
886 |
+
x0 : ndarray
|
887 |
+
Starting guess for the solution.
|
888 |
+
atol, rtol : float, optional
|
889 |
+
Parameters for the convergence test. For convergence,
|
890 |
+
``norm(b - A @ x) <= max(rtol*norm(b), atol)`` should be satisfied.
|
891 |
+
The default is ``atol=0.`` and ``rtol=1e-5``.
|
892 |
+
maxiter : integer
|
893 |
+
Maximum number of iterations. Iteration will stop after maxiter
|
894 |
+
steps even if the specified tolerance has not been achieved.
|
895 |
+
M1 : {sparse matrix, ndarray, LinearOperator}
|
896 |
+
Left preconditioner for A.
|
897 |
+
M2 : {sparse matrix, ndarray, LinearOperator}
|
898 |
+
Right preconditioner for A. Used together with the left
|
899 |
+
preconditioner M1. The matrix M1@A@M2 should have better
|
900 |
+
conditioned than A alone.
|
901 |
+
callback : function
|
902 |
+
User-supplied function to call after each iteration. It is called
|
903 |
+
as callback(xk), where xk is the current solution vector.
|
904 |
+
tol : float, optional, deprecated
|
905 |
+
|
906 |
+
.. deprecated:: 1.12.0
|
907 |
+
`qmr` keyword argument ``tol`` is deprecated in favor of ``rtol``
|
908 |
+
and will be removed in SciPy 1.14.0.
|
909 |
+
|
910 |
+
Returns
|
911 |
+
-------
|
912 |
+
x : ndarray
|
913 |
+
The converged solution.
|
914 |
+
info : integer
|
915 |
+
Provides convergence information:
|
916 |
+
0 : successful exit
|
917 |
+
>0 : convergence to tolerance not achieved, number of iterations
|
918 |
+
<0 : parameter breakdown
|
919 |
+
|
920 |
+
See Also
|
921 |
+
--------
|
922 |
+
LinearOperator
|
923 |
+
|
924 |
+
Examples
|
925 |
+
--------
|
926 |
+
>>> import numpy as np
|
927 |
+
>>> from scipy.sparse import csc_matrix
|
928 |
+
>>> from scipy.sparse.linalg import qmr
|
929 |
+
>>> A = csc_matrix([[3., 2., 0.], [1., -1., 0.], [0., 5., 1.]])
|
930 |
+
>>> b = np.array([2., 4., -1.])
|
931 |
+
>>> x, exitCode = qmr(A, b, atol=1e-5)
|
932 |
+
>>> print(exitCode) # 0 indicates successful convergence
|
933 |
+
0
|
934 |
+
>>> np.allclose(A.dot(x), b)
|
935 |
+
True
|
936 |
+
"""
|
937 |
+
A_ = A
|
938 |
+
A, M, x, b, postprocess = make_system(A, None, x0, b)
|
939 |
+
bnrm2 = np.linalg.norm(b)
|
940 |
+
|
941 |
+
atol, _ = _get_atol_rtol('qmr', bnrm2, tol, atol, rtol)
|
942 |
+
|
943 |
+
if bnrm2 == 0:
|
944 |
+
return postprocess(b), 0
|
945 |
+
|
946 |
+
if M1 is None and M2 is None:
|
947 |
+
if hasattr(A_, 'psolve'):
|
948 |
+
def left_psolve(b):
|
949 |
+
return A_.psolve(b, 'left')
|
950 |
+
|
951 |
+
def right_psolve(b):
|
952 |
+
return A_.psolve(b, 'right')
|
953 |
+
|
954 |
+
def left_rpsolve(b):
|
955 |
+
return A_.rpsolve(b, 'left')
|
956 |
+
|
957 |
+
def right_rpsolve(b):
|
958 |
+
return A_.rpsolve(b, 'right')
|
959 |
+
M1 = LinearOperator(A.shape,
|
960 |
+
matvec=left_psolve,
|
961 |
+
rmatvec=left_rpsolve)
|
962 |
+
M2 = LinearOperator(A.shape,
|
963 |
+
matvec=right_psolve,
|
964 |
+
rmatvec=right_rpsolve)
|
965 |
+
else:
|
966 |
+
def id(b):
|
967 |
+
return b
|
968 |
+
M1 = LinearOperator(A.shape, matvec=id, rmatvec=id)
|
969 |
+
M2 = LinearOperator(A.shape, matvec=id, rmatvec=id)
|
970 |
+
|
971 |
+
n = len(b)
|
972 |
+
if maxiter is None:
|
973 |
+
maxiter = n*10
|
974 |
+
|
975 |
+
dotprod = np.vdot if np.iscomplexobj(x) else np.dot
|
976 |
+
|
977 |
+
rhotol = np.finfo(x.dtype.char).eps
|
978 |
+
betatol = rhotol
|
979 |
+
gammatol = rhotol
|
980 |
+
deltatol = rhotol
|
981 |
+
epsilontol = rhotol
|
982 |
+
xitol = rhotol
|
983 |
+
|
984 |
+
r = b - A.matvec(x) if x.any() else b.copy()
|
985 |
+
|
986 |
+
vtilde = r.copy()
|
987 |
+
y = M1.matvec(vtilde)
|
988 |
+
rho = np.linalg.norm(y)
|
989 |
+
wtilde = r.copy()
|
990 |
+
z = M2.rmatvec(wtilde)
|
991 |
+
xi = np.linalg.norm(z)
|
992 |
+
gamma, eta, theta = 1, -1, 0
|
993 |
+
v = np.empty_like(vtilde)
|
994 |
+
w = np.empty_like(wtilde)
|
995 |
+
|
996 |
+
# Dummy values to initialize vars, silence linter warnings
|
997 |
+
epsilon, q, d, p, s = None, None, None, None, None
|
998 |
+
|
999 |
+
for iteration in range(maxiter):
|
1000 |
+
if np.linalg.norm(r) < atol: # Are we done?
|
1001 |
+
return postprocess(x), 0
|
1002 |
+
if np.abs(rho) < rhotol: # rho breakdown
|
1003 |
+
return postprocess(x), -10
|
1004 |
+
if np.abs(xi) < xitol: # xi breakdown
|
1005 |
+
return postprocess(x), -15
|
1006 |
+
|
1007 |
+
v[:] = vtilde[:]
|
1008 |
+
v *= (1 / rho)
|
1009 |
+
y *= (1 / rho)
|
1010 |
+
w[:] = wtilde[:]
|
1011 |
+
w *= (1 / xi)
|
1012 |
+
z *= (1 / xi)
|
1013 |
+
delta = dotprod(z, y)
|
1014 |
+
|
1015 |
+
if np.abs(delta) < deltatol: # delta breakdown
|
1016 |
+
return postprocess(x), -13
|
1017 |
+
|
1018 |
+
ytilde = M2.matvec(y)
|
1019 |
+
ztilde = M1.rmatvec(z)
|
1020 |
+
|
1021 |
+
if iteration > 0:
|
1022 |
+
ytilde -= (xi * delta / epsilon) * p
|
1023 |
+
p[:] = ytilde[:]
|
1024 |
+
ztilde -= (rho * (delta / epsilon).conj()) * q
|
1025 |
+
q[:] = ztilde[:]
|
1026 |
+
else: # First spin
|
1027 |
+
p = ytilde.copy()
|
1028 |
+
q = ztilde.copy()
|
1029 |
+
|
1030 |
+
ptilde = A.matvec(p)
|
1031 |
+
epsilon = dotprod(q, ptilde)
|
1032 |
+
if np.abs(epsilon) < epsilontol: # epsilon breakdown
|
1033 |
+
return postprocess(x), -14
|
1034 |
+
|
1035 |
+
beta = epsilon / delta
|
1036 |
+
if np.abs(beta) < betatol: # beta breakdown
|
1037 |
+
return postprocess(x), -11
|
1038 |
+
|
1039 |
+
vtilde[:] = ptilde[:]
|
1040 |
+
vtilde -= beta*v
|
1041 |
+
y = M1.matvec(vtilde)
|
1042 |
+
|
1043 |
+
rho_prev = rho
|
1044 |
+
rho = np.linalg.norm(y)
|
1045 |
+
wtilde[:] = w[:]
|
1046 |
+
wtilde *= - beta.conj()
|
1047 |
+
wtilde += A.rmatvec(q)
|
1048 |
+
z = M2.rmatvec(wtilde)
|
1049 |
+
xi = np.linalg.norm(z)
|
1050 |
+
gamma_prev = gamma
|
1051 |
+
theta_prev = theta
|
1052 |
+
theta = rho / (gamma_prev * np.abs(beta))
|
1053 |
+
gamma = 1 / np.sqrt(1 + theta**2)
|
1054 |
+
|
1055 |
+
if np.abs(gamma) < gammatol: # gamma breakdown
|
1056 |
+
return postprocess(x), -12
|
1057 |
+
|
1058 |
+
eta *= -(rho_prev / beta) * (gamma / gamma_prev)**2
|
1059 |
+
|
1060 |
+
if iteration > 0:
|
1061 |
+
d *= (theta_prev * gamma) ** 2
|
1062 |
+
d += eta*p
|
1063 |
+
s *= (theta_prev * gamma) ** 2
|
1064 |
+
s += eta*ptilde
|
1065 |
+
else:
|
1066 |
+
d = p.copy()
|
1067 |
+
d *= eta
|
1068 |
+
s = ptilde.copy()
|
1069 |
+
s *= eta
|
1070 |
+
|
1071 |
+
x += d
|
1072 |
+
r -= s
|
1073 |
+
|
1074 |
+
if callback:
|
1075 |
+
callback(x)
|
1076 |
+
|
1077 |
+
else: # for loop exhausted
|
1078 |
+
# Return incomplete progress
|
1079 |
+
return postprocess(x), maxiter
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/lgmres.py
ADDED
@@ -0,0 +1,242 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (C) 2009, Pauli Virtanen <[email protected]>
|
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 |
+
from scipy._lib.deprecation import _NoValue, _deprecate_positional_args
|
10 |
+
|
11 |
+
from ._gcrotmk import _fgmres
|
12 |
+
|
13 |
+
__all__ = ['lgmres']
|
14 |
+
|
15 |
+
|
16 |
+
@_deprecate_positional_args(version="1.14.0")
|
17 |
+
def lgmres(A, b, x0=None, *, tol=_NoValue, maxiter=1000, M=None, callback=None,
|
18 |
+
inner_m=30, outer_k=3, outer_v=None, store_outer_Av=True,
|
19 |
+
prepend_outer_v=False, atol=None, rtol=1e-5):
|
20 |
+
"""
|
21 |
+
Solve a matrix equation using the LGMRES algorithm.
|
22 |
+
|
23 |
+
The LGMRES algorithm [1]_ [2]_ is designed to avoid some problems
|
24 |
+
in the convergence in restarted GMRES, and often converges in fewer
|
25 |
+
iterations.
|
26 |
+
|
27 |
+
Parameters
|
28 |
+
----------
|
29 |
+
A : {sparse matrix, 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`` 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 ``rtol=1e-5``, the default for ``atol`` is ``rtol``.
|
42 |
+
|
43 |
+
.. warning::
|
44 |
+
|
45 |
+
The default value for ``atol`` will be changed to ``0.0`` in
|
46 |
+
SciPy 1.14.0.
|
47 |
+
maxiter : int, optional
|
48 |
+
Maximum number of iterations. Iteration will stop after maxiter
|
49 |
+
steps even if the specified tolerance has not been achieved.
|
50 |
+
M : {sparse matrix, ndarray, LinearOperator}, optional
|
51 |
+
Preconditioner for A. The preconditioner should approximate the
|
52 |
+
inverse of A. Effective preconditioning dramatically improves the
|
53 |
+
rate of convergence, which implies that fewer iterations are needed
|
54 |
+
to reach a given error tolerance.
|
55 |
+
callback : function, optional
|
56 |
+
User-supplied function to call after each iteration. It is called
|
57 |
+
as callback(xk), where xk is the current solution vector.
|
58 |
+
inner_m : int, optional
|
59 |
+
Number of inner GMRES iterations per each outer iteration.
|
60 |
+
outer_k : int, optional
|
61 |
+
Number of vectors to carry between inner GMRES iterations.
|
62 |
+
According to [1]_, good values are in the range of 1...3.
|
63 |
+
However, note that if you want to use the additional vectors to
|
64 |
+
accelerate solving multiple similar problems, larger values may
|
65 |
+
be beneficial.
|
66 |
+
outer_v : list of tuples, optional
|
67 |
+
List containing tuples ``(v, Av)`` of vectors and corresponding
|
68 |
+
matrix-vector products, used to augment the Krylov subspace, and
|
69 |
+
carried between inner GMRES iterations. The element ``Av`` can
|
70 |
+
be `None` if the matrix-vector product should be re-evaluated.
|
71 |
+
This parameter is modified in-place by `lgmres`, and can be used
|
72 |
+
to pass "guess" vectors in and out of the algorithm when solving
|
73 |
+
similar problems.
|
74 |
+
store_outer_Av : bool, optional
|
75 |
+
Whether LGMRES should store also A@v in addition to vectors `v`
|
76 |
+
in the `outer_v` list. Default is True.
|
77 |
+
prepend_outer_v : bool, optional
|
78 |
+
Whether to put outer_v augmentation vectors before Krylov iterates.
|
79 |
+
In standard LGMRES, prepend_outer_v=False.
|
80 |
+
tol : float, optional, deprecated
|
81 |
+
|
82 |
+
.. deprecated:: 1.12.0
|
83 |
+
`lgmres` keyword argument ``tol`` is deprecated in favor of ``rtol``
|
84 |
+
and will be removed in SciPy 1.14.0.
|
85 |
+
|
86 |
+
Returns
|
87 |
+
-------
|
88 |
+
x : ndarray
|
89 |
+
The converged solution.
|
90 |
+
info : int
|
91 |
+
Provides convergence information:
|
92 |
+
|
93 |
+
- 0 : successful exit
|
94 |
+
- >0 : convergence to tolerance not achieved, number of iterations
|
95 |
+
- <0 : illegal input or breakdown
|
96 |
+
|
97 |
+
Notes
|
98 |
+
-----
|
99 |
+
The LGMRES algorithm [1]_ [2]_ is designed to avoid the
|
100 |
+
slowing of convergence in restarted GMRES, due to alternating
|
101 |
+
residual vectors. Typically, it often outperforms GMRES(m) of
|
102 |
+
comparable memory requirements by some measure, or at least is not
|
103 |
+
much worse.
|
104 |
+
|
105 |
+
Another advantage in this algorithm is that you can supply it with
|
106 |
+
'guess' vectors in the `outer_v` argument that augment the Krylov
|
107 |
+
subspace. If the solution lies close to the span of these vectors,
|
108 |
+
the algorithm converges faster. This can be useful if several very
|
109 |
+
similar matrices need to be inverted one after another, such as in
|
110 |
+
Newton-Krylov iteration where the Jacobian matrix often changes
|
111 |
+
little in the nonlinear steps.
|
112 |
+
|
113 |
+
References
|
114 |
+
----------
|
115 |
+
.. [1] A.H. Baker and E.R. Jessup and T. Manteuffel, "A Technique for
|
116 |
+
Accelerating the Convergence of Restarted GMRES", SIAM J. Matrix
|
117 |
+
Anal. Appl. 26, 962 (2005).
|
118 |
+
.. [2] A.H. Baker, "On Improving the Performance of the Linear Solver
|
119 |
+
restarted GMRES", PhD thesis, University of Colorado (2003).
|
120 |
+
|
121 |
+
Examples
|
122 |
+
--------
|
123 |
+
>>> import numpy as np
|
124 |
+
>>> from scipy.sparse import csc_matrix
|
125 |
+
>>> from scipy.sparse.linalg import lgmres
|
126 |
+
>>> A = csc_matrix([[3, 2, 0], [1, -1, 0], [0, 5, 1]], dtype=float)
|
127 |
+
>>> b = np.array([2, 4, -1], dtype=float)
|
128 |
+
>>> x, exitCode = lgmres(A, b, atol=1e-5)
|
129 |
+
>>> print(exitCode) # 0 indicates successful convergence
|
130 |
+
0
|
131 |
+
>>> np.allclose(A.dot(x), b)
|
132 |
+
True
|
133 |
+
"""
|
134 |
+
A,M,x,b,postprocess = make_system(A,M,x0,b)
|
135 |
+
|
136 |
+
if not np.isfinite(b).all():
|
137 |
+
raise ValueError("RHS must contain only finite numbers")
|
138 |
+
|
139 |
+
matvec = A.matvec
|
140 |
+
psolve = M.matvec
|
141 |
+
|
142 |
+
if outer_v is None:
|
143 |
+
outer_v = []
|
144 |
+
|
145 |
+
axpy, dot, scal = None, None, None
|
146 |
+
nrm2 = get_blas_funcs('nrm2', [b])
|
147 |
+
|
148 |
+
b_norm = nrm2(b)
|
149 |
+
|
150 |
+
# we call this to get the right atol/rtol and raise warnings as necessary
|
151 |
+
atol, rtol = _get_atol_rtol('lgmres', b_norm, tol, atol, rtol)
|
152 |
+
|
153 |
+
if b_norm == 0:
|
154 |
+
x = b
|
155 |
+
return (postprocess(x), 0)
|
156 |
+
|
157 |
+
ptol_max_factor = 1.0
|
158 |
+
|
159 |
+
for k_outer in range(maxiter):
|
160 |
+
r_outer = matvec(x) - b
|
161 |
+
|
162 |
+
# -- callback
|
163 |
+
if callback is not None:
|
164 |
+
callback(x)
|
165 |
+
|
166 |
+
# -- determine input type routines
|
167 |
+
if axpy is None:
|
168 |
+
if np.iscomplexobj(r_outer) and not np.iscomplexobj(x):
|
169 |
+
x = x.astype(r_outer.dtype)
|
170 |
+
axpy, dot, scal, nrm2 = get_blas_funcs(['axpy', 'dot', 'scal', 'nrm2'],
|
171 |
+
(x, r_outer))
|
172 |
+
|
173 |
+
# -- check stopping condition
|
174 |
+
r_norm = nrm2(r_outer)
|
175 |
+
if r_norm <= max(atol, rtol * b_norm):
|
176 |
+
break
|
177 |
+
|
178 |
+
# -- inner LGMRES iteration
|
179 |
+
v0 = -psolve(r_outer)
|
180 |
+
inner_res_0 = nrm2(v0)
|
181 |
+
|
182 |
+
if inner_res_0 == 0:
|
183 |
+
rnorm = nrm2(r_outer)
|
184 |
+
raise RuntimeError("Preconditioner returned a zero vector; "
|
185 |
+
"|v| ~ %.1g, |M v| = 0" % rnorm)
|
186 |
+
|
187 |
+
v0 = scal(1.0/inner_res_0, v0)
|
188 |
+
|
189 |
+
ptol = min(ptol_max_factor, max(atol, rtol*b_norm)/r_norm)
|
190 |
+
|
191 |
+
try:
|
192 |
+
Q, R, B, vs, zs, y, pres = _fgmres(matvec,
|
193 |
+
v0,
|
194 |
+
inner_m,
|
195 |
+
lpsolve=psolve,
|
196 |
+
atol=ptol,
|
197 |
+
outer_v=outer_v,
|
198 |
+
prepend_outer_v=prepend_outer_v)
|
199 |
+
y *= inner_res_0
|
200 |
+
if not np.isfinite(y).all():
|
201 |
+
# Overflow etc. in computation. There's no way to
|
202 |
+
# recover from this, so we have to bail out.
|
203 |
+
raise LinAlgError()
|
204 |
+
except LinAlgError:
|
205 |
+
# Floating point over/underflow, non-finite result from
|
206 |
+
# matmul etc. -- report failure.
|
207 |
+
return postprocess(x), k_outer + 1
|
208 |
+
|
209 |
+
# Inner loop tolerance control
|
210 |
+
if pres > ptol:
|
211 |
+
ptol_max_factor = min(1.0, 1.5 * ptol_max_factor)
|
212 |
+
else:
|
213 |
+
ptol_max_factor = max(1e-16, 0.25 * ptol_max_factor)
|
214 |
+
|
215 |
+
# -- GMRES terminated: eval solution
|
216 |
+
dx = zs[0]*y[0]
|
217 |
+
for w, yc in zip(zs[1:], y[1:]):
|
218 |
+
dx = axpy(w, dx, dx.shape[0], yc) # dx += w*yc
|
219 |
+
|
220 |
+
# -- Store LGMRES augmentation vectors
|
221 |
+
nx = nrm2(dx)
|
222 |
+
if nx > 0:
|
223 |
+
if store_outer_Av:
|
224 |
+
q = Q.dot(R.dot(y))
|
225 |
+
ax = vs[0]*q[0]
|
226 |
+
for v, qc in zip(vs[1:], q[1:]):
|
227 |
+
ax = axpy(v, ax, ax.shape[0], qc)
|
228 |
+
outer_v.append((dx/nx, ax/nx))
|
229 |
+
else:
|
230 |
+
outer_v.append((dx/nx, None))
|
231 |
+
|
232 |
+
# -- Retain only a finite number of augmentation vectors
|
233 |
+
while len(outer_v) > outer_k:
|
234 |
+
del outer_v[0]
|
235 |
+
|
236 |
+
# -- Apply step
|
237 |
+
x += dx
|
238 |
+
else:
|
239 |
+
# didn't converge ...
|
240 |
+
return postprocess(x), maxiter
|
241 |
+
|
242 |
+
return postprocess(x), 0
|
venv/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 [email protected]
|
10 |
+
Institute for Computational and Mathematical Engineering
|
11 |
+
Stanford University
|
12 |
+
|
13 |
+
Michael Saunders [email protected]
|
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 matrix, 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_matrix
|
146 |
+
>>> from scipy.sparse.linalg import lsmr
|
147 |
+
>>> A = csc_matrix([[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('damp = %20.14e\n' % (damp))
|
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(' normx =%8.1e' % (normx))
|
483 |
+
print(str1, str2)
|
484 |
+
print(str3, str4)
|
485 |
+
|
486 |
+
return x, istop, itn, normr, normar, normA, condA, normx
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/lsqr.py
ADDED
@@ -0,0 +1,587 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
|
58 |
+
eps = np.finfo(np.float64).eps
|
59 |
+
|
60 |
+
|
61 |
+
def _sym_ortho(a, b):
|
62 |
+
"""
|
63 |
+
Stable implementation of Givens rotation.
|
64 |
+
|
65 |
+
Notes
|
66 |
+
-----
|
67 |
+
The routine 'SymOrtho' was added for numerical stability. This is
|
68 |
+
recommended by S.-C. Choi in [1]_. It removes the unpleasant potential of
|
69 |
+
``1/eps`` in some important places (see, for example text following
|
70 |
+
"Compute the next plane rotation Qk" in minres.py).
|
71 |
+
|
72 |
+
References
|
73 |
+
----------
|
74 |
+
.. [1] S.-C. Choi, "Iterative Methods for Singular Linear Equations
|
75 |
+
and Least-Squares Problems", Dissertation,
|
76 |
+
http://www.stanford.edu/group/SOL/dissertations/sou-cheng-choi-thesis.pdf
|
77 |
+
|
78 |
+
"""
|
79 |
+
if b == 0:
|
80 |
+
return np.sign(a), 0, abs(a)
|
81 |
+
elif a == 0:
|
82 |
+
return 0, np.sign(b), abs(b)
|
83 |
+
elif abs(b) > abs(a):
|
84 |
+
tau = a / b
|
85 |
+
s = np.sign(b) / sqrt(1 + tau * tau)
|
86 |
+
c = s * tau
|
87 |
+
r = b / s
|
88 |
+
else:
|
89 |
+
tau = b / a
|
90 |
+
c = np.sign(a) / sqrt(1+tau*tau)
|
91 |
+
s = c * tau
|
92 |
+
r = a / c
|
93 |
+
return c, s, r
|
94 |
+
|
95 |
+
|
96 |
+
def lsqr(A, b, damp=0.0, atol=1e-6, btol=1e-6, conlim=1e8,
|
97 |
+
iter_lim=None, show=False, calc_var=False, x0=None):
|
98 |
+
"""Find the least-squares solution to a large, sparse, linear system
|
99 |
+
of equations.
|
100 |
+
|
101 |
+
The function solves ``Ax = b`` or ``min ||Ax - b||^2`` or
|
102 |
+
``min ||Ax - b||^2 + d^2 ||x - x0||^2``.
|
103 |
+
|
104 |
+
The matrix A may be square or rectangular (over-determined or
|
105 |
+
under-determined), and may have any rank.
|
106 |
+
|
107 |
+
::
|
108 |
+
|
109 |
+
1. Unsymmetric equations -- solve Ax = b
|
110 |
+
|
111 |
+
2. Linear least squares -- solve Ax = b
|
112 |
+
in the least-squares sense
|
113 |
+
|
114 |
+
3. Damped least squares -- solve ( A )*x = ( b )
|
115 |
+
( damp*I ) ( damp*x0 )
|
116 |
+
in the least-squares sense
|
117 |
+
|
118 |
+
Parameters
|
119 |
+
----------
|
120 |
+
A : {sparse matrix, ndarray, LinearOperator}
|
121 |
+
Representation of an m-by-n matrix.
|
122 |
+
Alternatively, ``A`` can be a linear operator which can
|
123 |
+
produce ``Ax`` and ``A^T x`` using, e.g.,
|
124 |
+
``scipy.sparse.linalg.LinearOperator``.
|
125 |
+
b : array_like, shape (m,)
|
126 |
+
Right-hand side vector ``b``.
|
127 |
+
damp : float
|
128 |
+
Damping coefficient. Default is 0.
|
129 |
+
atol, btol : float, optional
|
130 |
+
Stopping tolerances. `lsqr` continues iterations until a
|
131 |
+
certain backward error estimate is smaller than some quantity
|
132 |
+
depending on atol and btol. Let ``r = b - Ax`` be the
|
133 |
+
residual vector for the current approximate solution ``x``.
|
134 |
+
If ``Ax = b`` seems to be consistent, `lsqr` terminates
|
135 |
+
when ``norm(r) <= atol * norm(A) * norm(x) + btol * norm(b)``.
|
136 |
+
Otherwise, `lsqr` terminates when ``norm(A^H r) <=
|
137 |
+
atol * norm(A) * norm(r)``. If both tolerances are 1.0e-6 (default),
|
138 |
+
the final ``norm(r)`` should be accurate to about 6
|
139 |
+
digits. (The final ``x`` will usually have fewer correct digits,
|
140 |
+
depending on ``cond(A)`` and the size of LAMBDA.) If `atol`
|
141 |
+
or `btol` is None, a default value of 1.0e-6 will be used.
|
142 |
+
Ideally, they should be estimates of the relative error in the
|
143 |
+
entries of ``A`` and ``b`` respectively. For example, if the entries
|
144 |
+
of ``A`` have 7 correct digits, set ``atol = 1e-7``. This prevents
|
145 |
+
the algorithm from doing unnecessary work beyond the
|
146 |
+
uncertainty of the input data.
|
147 |
+
conlim : float, optional
|
148 |
+
Another stopping tolerance. lsqr terminates if an estimate of
|
149 |
+
``cond(A)`` exceeds `conlim`. For compatible systems ``Ax =
|
150 |
+
b``, `conlim` could be as large as 1.0e+12 (say). For
|
151 |
+
least-squares problems, conlim should be less than 1.0e+8.
|
152 |
+
Maximum precision can be obtained by setting ``atol = btol =
|
153 |
+
conlim = zero``, but the number of iterations may then be
|
154 |
+
excessive. Default is 1e8.
|
155 |
+
iter_lim : int, optional
|
156 |
+
Explicit limitation on number of iterations (for safety).
|
157 |
+
show : bool, optional
|
158 |
+
Display an iteration log. Default is False.
|
159 |
+
calc_var : bool, optional
|
160 |
+
Whether to estimate diagonals of ``(A'A + damp^2*I)^{-1}``.
|
161 |
+
x0 : array_like, shape (n,), optional
|
162 |
+
Initial guess of x, if None zeros are used. Default is None.
|
163 |
+
|
164 |
+
.. versionadded:: 1.0.0
|
165 |
+
|
166 |
+
Returns
|
167 |
+
-------
|
168 |
+
x : ndarray of float
|
169 |
+
The final solution.
|
170 |
+
istop : int
|
171 |
+
Gives the reason for termination.
|
172 |
+
1 means x is an approximate solution to Ax = b.
|
173 |
+
2 means x approximately solves the least-squares problem.
|
174 |
+
itn : int
|
175 |
+
Iteration number upon termination.
|
176 |
+
r1norm : float
|
177 |
+
``norm(r)``, where ``r = b - Ax``.
|
178 |
+
r2norm : float
|
179 |
+
``sqrt( norm(r)^2 + damp^2 * norm(x - x0)^2 )``. Equal to `r1norm`
|
180 |
+
if ``damp == 0``.
|
181 |
+
anorm : float
|
182 |
+
Estimate of Frobenius norm of ``Abar = [[A]; [damp*I]]``.
|
183 |
+
acond : float
|
184 |
+
Estimate of ``cond(Abar)``.
|
185 |
+
arnorm : float
|
186 |
+
Estimate of ``norm(A'@r - damp^2*(x - x0))``.
|
187 |
+
xnorm : float
|
188 |
+
``norm(x)``
|
189 |
+
var : ndarray of float
|
190 |
+
If ``calc_var`` is True, estimates all diagonals of
|
191 |
+
``(A'A)^{-1}`` (if ``damp == 0``) or more generally ``(A'A +
|
192 |
+
damp^2*I)^{-1}``. This is well defined if A has full column
|
193 |
+
rank or ``damp > 0``. (Not sure what var means if ``rank(A)
|
194 |
+
< n`` and ``damp = 0.``)
|
195 |
+
|
196 |
+
Notes
|
197 |
+
-----
|
198 |
+
LSQR uses an iterative method to approximate the solution. The
|
199 |
+
number of iterations required to reach a certain accuracy depends
|
200 |
+
strongly on the scaling of the problem. Poor scaling of the rows
|
201 |
+
or columns of A should therefore be avoided where possible.
|
202 |
+
|
203 |
+
For example, in problem 1 the solution is unaltered by
|
204 |
+
row-scaling. If a row of A is very small or large compared to
|
205 |
+
the other rows of A, the corresponding row of ( A b ) should be
|
206 |
+
scaled up or down.
|
207 |
+
|
208 |
+
In problems 1 and 2, the solution x is easily recovered
|
209 |
+
following column-scaling. Unless better information is known,
|
210 |
+
the nonzero columns of A should be scaled so that they all have
|
211 |
+
the same Euclidean norm (e.g., 1.0).
|
212 |
+
|
213 |
+
In problem 3, there is no freedom to re-scale if damp is
|
214 |
+
nonzero. However, the value of damp should be assigned only
|
215 |
+
after attention has been paid to the scaling of A.
|
216 |
+
|
217 |
+
The parameter damp is intended to help regularize
|
218 |
+
ill-conditioned systems, by preventing the true solution from
|
219 |
+
being very large. Another aid to regularization is provided by
|
220 |
+
the parameter acond, which may be used to terminate iterations
|
221 |
+
before the computed solution becomes very large.
|
222 |
+
|
223 |
+
If some initial estimate ``x0`` is known and if ``damp == 0``,
|
224 |
+
one could proceed as follows:
|
225 |
+
|
226 |
+
1. Compute a residual vector ``r0 = b - A@x0``.
|
227 |
+
2. Use LSQR to solve the system ``A@dx = r0``.
|
228 |
+
3. Add the correction dx to obtain a final solution ``x = x0 + dx``.
|
229 |
+
|
230 |
+
This requires that ``x0`` be available before and after the call
|
231 |
+
to LSQR. To judge the benefits, suppose LSQR takes k1 iterations
|
232 |
+
to solve A@x = b and k2 iterations to solve A@dx = r0.
|
233 |
+
If x0 is "good", norm(r0) will be smaller than norm(b).
|
234 |
+
If the same stopping tolerances atol and btol are used for each
|
235 |
+
system, k1 and k2 will be similar, but the final solution x0 + dx
|
236 |
+
should be more accurate. The only way to reduce the total work
|
237 |
+
is to use a larger stopping tolerance for the second system.
|
238 |
+
If some value btol is suitable for A@x = b, the larger value
|
239 |
+
btol*norm(b)/norm(r0) should be suitable for A@dx = r0.
|
240 |
+
|
241 |
+
Preconditioning is another way to reduce the number of iterations.
|
242 |
+
If it is possible to solve a related system ``M@x = b``
|
243 |
+
efficiently, where M approximates A in some helpful way (e.g. M -
|
244 |
+
A has low rank or its elements are small relative to those of A),
|
245 |
+
LSQR may converge more rapidly on the system ``A@M(inverse)@z =
|
246 |
+
b``, after which x can be recovered by solving M@x = z.
|
247 |
+
|
248 |
+
If A is symmetric, LSQR should not be used!
|
249 |
+
|
250 |
+
Alternatives are the symmetric conjugate-gradient method (cg)
|
251 |
+
and/or SYMMLQ. SYMMLQ is an implementation of symmetric cg that
|
252 |
+
applies to any symmetric A and will converge more rapidly than
|
253 |
+
LSQR. If A is positive definite, there are other implementations
|
254 |
+
of symmetric cg that require slightly less work per iteration than
|
255 |
+
SYMMLQ (but will take the same number of iterations).
|
256 |
+
|
257 |
+
References
|
258 |
+
----------
|
259 |
+
.. [1] C. C. Paige and M. A. Saunders (1982a).
|
260 |
+
"LSQR: An algorithm for sparse linear equations and
|
261 |
+
sparse least squares", ACM TOMS 8(1), 43-71.
|
262 |
+
.. [2] C. C. Paige and M. A. Saunders (1982b).
|
263 |
+
"Algorithm 583. LSQR: Sparse linear equations and least
|
264 |
+
squares problems", ACM TOMS 8(2), 195-209.
|
265 |
+
.. [3] M. A. Saunders (1995). "Solution of sparse rectangular
|
266 |
+
systems using LSQR and CRAIG", BIT 35, 588-604.
|
267 |
+
|
268 |
+
Examples
|
269 |
+
--------
|
270 |
+
>>> import numpy as np
|
271 |
+
>>> from scipy.sparse import csc_matrix
|
272 |
+
>>> from scipy.sparse.linalg import lsqr
|
273 |
+
>>> A = csc_matrix([[1., 0.], [1., 1.], [0., 1.]], dtype=float)
|
274 |
+
|
275 |
+
The first example has the trivial solution ``[0, 0]``
|
276 |
+
|
277 |
+
>>> b = np.array([0., 0., 0.], dtype=float)
|
278 |
+
>>> x, istop, itn, normr = lsqr(A, b)[:4]
|
279 |
+
>>> istop
|
280 |
+
0
|
281 |
+
>>> x
|
282 |
+
array([ 0., 0.])
|
283 |
+
|
284 |
+
The stopping code `istop=0` returned indicates that a vector of zeros was
|
285 |
+
found as a solution. The returned solution `x` indeed contains
|
286 |
+
``[0., 0.]``. The next example has a non-trivial solution:
|
287 |
+
|
288 |
+
>>> b = np.array([1., 0., -1.], dtype=float)
|
289 |
+
>>> x, istop, itn, r1norm = lsqr(A, b)[:4]
|
290 |
+
>>> istop
|
291 |
+
1
|
292 |
+
>>> x
|
293 |
+
array([ 1., -1.])
|
294 |
+
>>> itn
|
295 |
+
1
|
296 |
+
>>> r1norm
|
297 |
+
4.440892098500627e-16
|
298 |
+
|
299 |
+
As indicated by `istop=1`, `lsqr` found a solution obeying the tolerance
|
300 |
+
limits. The given solution ``[1., -1.]`` obviously solves the equation. The
|
301 |
+
remaining return values include information about the number of iterations
|
302 |
+
(`itn=1`) and the remaining difference of left and right side of the solved
|
303 |
+
equation.
|
304 |
+
The final example demonstrates the behavior in the case where there is no
|
305 |
+
solution for the equation:
|
306 |
+
|
307 |
+
>>> b = np.array([1., 0.01, -1.], dtype=float)
|
308 |
+
>>> x, istop, itn, r1norm = lsqr(A, b)[:4]
|
309 |
+
>>> istop
|
310 |
+
2
|
311 |
+
>>> x
|
312 |
+
array([ 1.00333333, -0.99666667])
|
313 |
+
>>> A.dot(x)-b
|
314 |
+
array([ 0.00333333, -0.00333333, 0.00333333])
|
315 |
+
>>> r1norm
|
316 |
+
0.005773502691896255
|
317 |
+
|
318 |
+
`istop` indicates that the system is inconsistent and thus `x` is rather an
|
319 |
+
approximate solution to the corresponding least-squares problem. `r1norm`
|
320 |
+
contains the norm of the minimal residual that was found.
|
321 |
+
"""
|
322 |
+
A = aslinearoperator(A)
|
323 |
+
b = np.atleast_1d(b)
|
324 |
+
if b.ndim > 1:
|
325 |
+
b = b.squeeze()
|
326 |
+
|
327 |
+
m, n = A.shape
|
328 |
+
if iter_lim is None:
|
329 |
+
iter_lim = 2 * n
|
330 |
+
var = np.zeros(n)
|
331 |
+
|
332 |
+
msg = ('The exact solution is x = 0 ',
|
333 |
+
'Ax - b is small enough, given atol, btol ',
|
334 |
+
'The least-squares solution is good enough, given atol ',
|
335 |
+
'The estimate of cond(Abar) has exceeded conlim ',
|
336 |
+
'Ax - b is small enough for this machine ',
|
337 |
+
'The least-squares solution is good enough for this machine',
|
338 |
+
'Cond(Abar) seems to be too large for this machine ',
|
339 |
+
'The iteration limit has been reached ')
|
340 |
+
|
341 |
+
if show:
|
342 |
+
print(' ')
|
343 |
+
print('LSQR Least-squares solution of Ax = b')
|
344 |
+
str1 = f'The matrix A has {m} rows and {n} columns'
|
345 |
+
str2 = f'damp = {damp:20.14e} calc_var = {calc_var:8g}'
|
346 |
+
str3 = f'atol = {atol:8.2e} conlim = {conlim:8.2e}'
|
347 |
+
str4 = f'btol = {btol:8.2e} iter_lim = {iter_lim:8g}'
|
348 |
+
print(str1)
|
349 |
+
print(str2)
|
350 |
+
print(str3)
|
351 |
+
print(str4)
|
352 |
+
|
353 |
+
itn = 0
|
354 |
+
istop = 0
|
355 |
+
ctol = 0
|
356 |
+
if conlim > 0:
|
357 |
+
ctol = 1/conlim
|
358 |
+
anorm = 0
|
359 |
+
acond = 0
|
360 |
+
dampsq = damp**2
|
361 |
+
ddnorm = 0
|
362 |
+
res2 = 0
|
363 |
+
xnorm = 0
|
364 |
+
xxnorm = 0
|
365 |
+
z = 0
|
366 |
+
cs2 = -1
|
367 |
+
sn2 = 0
|
368 |
+
|
369 |
+
# Set up the first vectors u and v for the bidiagonalization.
|
370 |
+
# These satisfy beta*u = b - A@x, alfa*v = A'@u.
|
371 |
+
u = b
|
372 |
+
bnorm = np.linalg.norm(b)
|
373 |
+
|
374 |
+
if x0 is None:
|
375 |
+
x = np.zeros(n)
|
376 |
+
beta = bnorm.copy()
|
377 |
+
else:
|
378 |
+
x = np.asarray(x0)
|
379 |
+
u = u - A.matvec(x)
|
380 |
+
beta = np.linalg.norm(u)
|
381 |
+
|
382 |
+
if beta > 0:
|
383 |
+
u = (1/beta) * u
|
384 |
+
v = A.rmatvec(u)
|
385 |
+
alfa = np.linalg.norm(v)
|
386 |
+
else:
|
387 |
+
v = x.copy()
|
388 |
+
alfa = 0
|
389 |
+
|
390 |
+
if alfa > 0:
|
391 |
+
v = (1/alfa) * v
|
392 |
+
w = v.copy()
|
393 |
+
|
394 |
+
rhobar = alfa
|
395 |
+
phibar = beta
|
396 |
+
rnorm = beta
|
397 |
+
r1norm = rnorm
|
398 |
+
r2norm = rnorm
|
399 |
+
|
400 |
+
# Reverse the order here from the original matlab code because
|
401 |
+
# there was an error on return when arnorm==0
|
402 |
+
arnorm = alfa * beta
|
403 |
+
if arnorm == 0:
|
404 |
+
if show:
|
405 |
+
print(msg[0])
|
406 |
+
return x, istop, itn, r1norm, r2norm, anorm, acond, arnorm, xnorm, var
|
407 |
+
|
408 |
+
head1 = ' Itn x[0] r1norm r2norm '
|
409 |
+
head2 = ' Compatible LS Norm A Cond A'
|
410 |
+
|
411 |
+
if show:
|
412 |
+
print(' ')
|
413 |
+
print(head1, head2)
|
414 |
+
test1 = 1
|
415 |
+
test2 = alfa / beta
|
416 |
+
str1 = f'{itn:6g} {x[0]:12.5e}'
|
417 |
+
str2 = f' {r1norm:10.3e} {r2norm:10.3e}'
|
418 |
+
str3 = f' {test1:8.1e} {test2:8.1e}'
|
419 |
+
print(str1, str2, str3)
|
420 |
+
|
421 |
+
# Main iteration loop.
|
422 |
+
while itn < iter_lim:
|
423 |
+
itn = itn + 1
|
424 |
+
# Perform the next step of the bidiagonalization to obtain the
|
425 |
+
# next beta, u, alfa, v. These satisfy the relations
|
426 |
+
# beta*u = a@v - alfa*u,
|
427 |
+
# alfa*v = A'@u - beta*v.
|
428 |
+
u = A.matvec(v) - alfa * u
|
429 |
+
beta = np.linalg.norm(u)
|
430 |
+
|
431 |
+
if beta > 0:
|
432 |
+
u = (1/beta) * u
|
433 |
+
anorm = sqrt(anorm**2 + alfa**2 + beta**2 + dampsq)
|
434 |
+
v = A.rmatvec(u) - beta * v
|
435 |
+
alfa = np.linalg.norm(v)
|
436 |
+
if alfa > 0:
|
437 |
+
v = (1 / alfa) * v
|
438 |
+
|
439 |
+
# Use a plane rotation to eliminate the damping parameter.
|
440 |
+
# This alters the diagonal (rhobar) of the lower-bidiagonal matrix.
|
441 |
+
if damp > 0:
|
442 |
+
rhobar1 = sqrt(rhobar**2 + dampsq)
|
443 |
+
cs1 = rhobar / rhobar1
|
444 |
+
sn1 = damp / rhobar1
|
445 |
+
psi = sn1 * phibar
|
446 |
+
phibar = cs1 * phibar
|
447 |
+
else:
|
448 |
+
# cs1 = 1 and sn1 = 0
|
449 |
+
rhobar1 = rhobar
|
450 |
+
psi = 0.
|
451 |
+
|
452 |
+
# Use a plane rotation to eliminate the subdiagonal element (beta)
|
453 |
+
# of the lower-bidiagonal matrix, giving an upper-bidiagonal matrix.
|
454 |
+
cs, sn, rho = _sym_ortho(rhobar1, beta)
|
455 |
+
|
456 |
+
theta = sn * alfa
|
457 |
+
rhobar = -cs * alfa
|
458 |
+
phi = cs * phibar
|
459 |
+
phibar = sn * phibar
|
460 |
+
tau = sn * phi
|
461 |
+
|
462 |
+
# Update x and w.
|
463 |
+
t1 = phi / rho
|
464 |
+
t2 = -theta / rho
|
465 |
+
dk = (1 / rho) * w
|
466 |
+
|
467 |
+
x = x + t1 * w
|
468 |
+
w = v + t2 * w
|
469 |
+
ddnorm = ddnorm + np.linalg.norm(dk)**2
|
470 |
+
|
471 |
+
if calc_var:
|
472 |
+
var = var + dk**2
|
473 |
+
|
474 |
+
# Use a plane rotation on the right to eliminate the
|
475 |
+
# super-diagonal element (theta) of the upper-bidiagonal matrix.
|
476 |
+
# Then use the result to estimate norm(x).
|
477 |
+
delta = sn2 * rho
|
478 |
+
gambar = -cs2 * rho
|
479 |
+
rhs = phi - delta * z
|
480 |
+
zbar = rhs / gambar
|
481 |
+
xnorm = sqrt(xxnorm + zbar**2)
|
482 |
+
gamma = sqrt(gambar**2 + theta**2)
|
483 |
+
cs2 = gambar / gamma
|
484 |
+
sn2 = theta / gamma
|
485 |
+
z = rhs / gamma
|
486 |
+
xxnorm = xxnorm + z**2
|
487 |
+
|
488 |
+
# Test for convergence.
|
489 |
+
# First, estimate the condition of the matrix Abar,
|
490 |
+
# and the norms of rbar and Abar'rbar.
|
491 |
+
acond = anorm * sqrt(ddnorm)
|
492 |
+
res1 = phibar**2
|
493 |
+
res2 = res2 + psi**2
|
494 |
+
rnorm = sqrt(res1 + res2)
|
495 |
+
arnorm = alfa * abs(tau)
|
496 |
+
|
497 |
+
# Distinguish between
|
498 |
+
# r1norm = ||b - Ax|| and
|
499 |
+
# r2norm = rnorm in current code
|
500 |
+
# = sqrt(r1norm^2 + damp^2*||x - x0||^2).
|
501 |
+
# Estimate r1norm from
|
502 |
+
# r1norm = sqrt(r2norm^2 - damp^2*||x - x0||^2).
|
503 |
+
# Although there is cancellation, it might be accurate enough.
|
504 |
+
if damp > 0:
|
505 |
+
r1sq = rnorm**2 - dampsq * xxnorm
|
506 |
+
r1norm = sqrt(abs(r1sq))
|
507 |
+
if r1sq < 0:
|
508 |
+
r1norm = -r1norm
|
509 |
+
else:
|
510 |
+
r1norm = rnorm
|
511 |
+
r2norm = rnorm
|
512 |
+
|
513 |
+
# Now use these norms to estimate certain other quantities,
|
514 |
+
# some of which will be small near a solution.
|
515 |
+
test1 = rnorm / bnorm
|
516 |
+
test2 = arnorm / (anorm * rnorm + eps)
|
517 |
+
test3 = 1 / (acond + eps)
|
518 |
+
t1 = test1 / (1 + anorm * xnorm / bnorm)
|
519 |
+
rtol = btol + atol * anorm * xnorm / bnorm
|
520 |
+
|
521 |
+
# The following tests guard against extremely small values of
|
522 |
+
# atol, btol or ctol. (The user may have set any or all of
|
523 |
+
# the parameters atol, btol, conlim to 0.)
|
524 |
+
# The effect is equivalent to the normal tests using
|
525 |
+
# atol = eps, btol = eps, conlim = 1/eps.
|
526 |
+
if itn >= iter_lim:
|
527 |
+
istop = 7
|
528 |
+
if 1 + test3 <= 1:
|
529 |
+
istop = 6
|
530 |
+
if 1 + test2 <= 1:
|
531 |
+
istop = 5
|
532 |
+
if 1 + t1 <= 1:
|
533 |
+
istop = 4
|
534 |
+
|
535 |
+
# Allow for tolerances set by the user.
|
536 |
+
if test3 <= ctol:
|
537 |
+
istop = 3
|
538 |
+
if test2 <= atol:
|
539 |
+
istop = 2
|
540 |
+
if test1 <= rtol:
|
541 |
+
istop = 1
|
542 |
+
|
543 |
+
if show:
|
544 |
+
# See if it is time to print something.
|
545 |
+
prnt = False
|
546 |
+
if n <= 40:
|
547 |
+
prnt = True
|
548 |
+
if itn <= 10:
|
549 |
+
prnt = True
|
550 |
+
if itn >= iter_lim-10:
|
551 |
+
prnt = True
|
552 |
+
# if itn%10 == 0: prnt = True
|
553 |
+
if test3 <= 2*ctol:
|
554 |
+
prnt = True
|
555 |
+
if test2 <= 10*atol:
|
556 |
+
prnt = True
|
557 |
+
if test1 <= 10*rtol:
|
558 |
+
prnt = True
|
559 |
+
if istop != 0:
|
560 |
+
prnt = True
|
561 |
+
|
562 |
+
if prnt:
|
563 |
+
str1 = f'{itn:6g} {x[0]:12.5e}'
|
564 |
+
str2 = f' {r1norm:10.3e} {r2norm:10.3e}'
|
565 |
+
str3 = f' {test1:8.1e} {test2:8.1e}'
|
566 |
+
str4 = f' {anorm:8.1e} {acond:8.1e}'
|
567 |
+
print(str1, str2, str3, str4)
|
568 |
+
|
569 |
+
if istop != 0:
|
570 |
+
break
|
571 |
+
|
572 |
+
# End of iteration loop.
|
573 |
+
# Print the stopping condition.
|
574 |
+
if show:
|
575 |
+
print(' ')
|
576 |
+
print('LSQR finished')
|
577 |
+
print(msg[istop])
|
578 |
+
print(' ')
|
579 |
+
str1 = f'istop ={istop:8g} r1norm ={r1norm:8.1e}'
|
580 |
+
str2 = f'anorm ={anorm:8.1e} arnorm ={arnorm:8.1e}'
|
581 |
+
str3 = f'itn ={itn:8g} r2norm ={r2norm:8.1e}'
|
582 |
+
str4 = f'acond ={acond:8.1e} xnorm ={xnorm:8.1e}'
|
583 |
+
print(str1 + ' ' + str2)
|
584 |
+
print(str3 + ' ' + str4)
|
585 |
+
print(' ')
|
586 |
+
|
587 |
+
return x, istop, itn, r1norm, r2norm, anorm, acond, arnorm, xnorm, var
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/minres.py
ADDED
@@ -0,0 +1,387 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import warnings
|
2 |
+
from numpy import inner, zeros, inf, finfo
|
3 |
+
from numpy.linalg import norm
|
4 |
+
from math import sqrt
|
5 |
+
|
6 |
+
from .utils import make_system
|
7 |
+
from scipy._lib.deprecation import _NoValue, _deprecate_positional_args
|
8 |
+
|
9 |
+
__all__ = ['minres']
|
10 |
+
|
11 |
+
|
12 |
+
@_deprecate_positional_args(version="1.14.0")
|
13 |
+
def minres(A, b, x0=None, *, shift=0.0, tol=_NoValue, maxiter=None,
|
14 |
+
M=None, callback=None, show=False, check=False, rtol=1e-5):
|
15 |
+
"""
|
16 |
+
Use MINimum RESidual iteration to solve Ax=b
|
17 |
+
|
18 |
+
MINRES minimizes norm(Ax - b) for a real symmetric matrix A. Unlike
|
19 |
+
the Conjugate Gradient method, A can be indefinite or singular.
|
20 |
+
|
21 |
+
If shift != 0 then the method solves (A - shift*I)x = b
|
22 |
+
|
23 |
+
Parameters
|
24 |
+
----------
|
25 |
+
A : {sparse matrix, ndarray, LinearOperator}
|
26 |
+
The real symmetric N-by-N matrix of the linear system
|
27 |
+
Alternatively, ``A`` can be a linear operator which can
|
28 |
+
produce ``Ax`` using, e.g.,
|
29 |
+
``scipy.sparse.linalg.LinearOperator``.
|
30 |
+
b : ndarray
|
31 |
+
Right hand side of the linear system. Has shape (N,) or (N,1).
|
32 |
+
|
33 |
+
Returns
|
34 |
+
-------
|
35 |
+
x : ndarray
|
36 |
+
The converged solution.
|
37 |
+
info : integer
|
38 |
+
Provides convergence information:
|
39 |
+
0 : successful exit
|
40 |
+
>0 : convergence to tolerance not achieved, number of iterations
|
41 |
+
<0 : illegal input or breakdown
|
42 |
+
|
43 |
+
Other Parameters
|
44 |
+
----------------
|
45 |
+
x0 : ndarray
|
46 |
+
Starting guess for the solution.
|
47 |
+
shift : float
|
48 |
+
Value to apply to the system ``(A - shift * I)x = b``. Default is 0.
|
49 |
+
rtol : float
|
50 |
+
Tolerance to achieve. The algorithm terminates when the relative
|
51 |
+
residual is below ``rtol``.
|
52 |
+
maxiter : integer
|
53 |
+
Maximum number of iterations. Iteration will stop after maxiter
|
54 |
+
steps even if the specified tolerance has not been achieved.
|
55 |
+
M : {sparse matrix, ndarray, LinearOperator}
|
56 |
+
Preconditioner for A. The preconditioner should approximate the
|
57 |
+
inverse of A. Effective preconditioning dramatically improves the
|
58 |
+
rate of convergence, which implies that fewer iterations are needed
|
59 |
+
to reach a given error tolerance.
|
60 |
+
callback : function
|
61 |
+
User-supplied function to call after each iteration. It is called
|
62 |
+
as callback(xk), where xk is the current solution vector.
|
63 |
+
show : bool
|
64 |
+
If ``True``, print out a summary and metrics related to the solution
|
65 |
+
during iterations. Default is ``False``.
|
66 |
+
check : bool
|
67 |
+
If ``True``, run additional input validation to check that `A` and
|
68 |
+
`M` (if specified) are symmetric. Default is ``False``.
|
69 |
+
tol : float, optional, deprecated
|
70 |
+
|
71 |
+
.. deprecated:: 1.12.0
|
72 |
+
`minres` keyword argument ``tol`` is deprecated in favor of ``rtol``
|
73 |
+
and will be removed in SciPy 1.14.0.
|
74 |
+
|
75 |
+
Examples
|
76 |
+
--------
|
77 |
+
>>> import numpy as np
|
78 |
+
>>> from scipy.sparse import csc_matrix
|
79 |
+
>>> from scipy.sparse.linalg import minres
|
80 |
+
>>> A = csc_matrix([[3, 2, 0], [1, -1, 0], [0, 5, 1]], dtype=float)
|
81 |
+
>>> A = A + A.T
|
82 |
+
>>> b = np.array([2, 4, -1], dtype=float)
|
83 |
+
>>> x, exitCode = minres(A, b)
|
84 |
+
>>> print(exitCode) # 0 indicates successful convergence
|
85 |
+
0
|
86 |
+
>>> np.allclose(A.dot(x), b)
|
87 |
+
True
|
88 |
+
|
89 |
+
References
|
90 |
+
----------
|
91 |
+
Solution of sparse indefinite systems of linear equations,
|
92 |
+
C. C. Paige and M. A. Saunders (1975),
|
93 |
+
SIAM J. Numer. Anal. 12(4), pp. 617-629.
|
94 |
+
https://web.stanford.edu/group/SOL/software/minres/
|
95 |
+
|
96 |
+
This file is a translation of the following MATLAB implementation:
|
97 |
+
https://web.stanford.edu/group/SOL/software/minres/minres-matlab.zip
|
98 |
+
|
99 |
+
"""
|
100 |
+
A, M, x, b, postprocess = make_system(A, M, x0, b)
|
101 |
+
|
102 |
+
if tol is not _NoValue:
|
103 |
+
msg = ("'scipy.sparse.linalg.minres' keyword argument `tol` is "
|
104 |
+
"deprecated in favor of `rtol` and will be removed in SciPy "
|
105 |
+
"v1.14. Until then, if set, it will override `rtol`.")
|
106 |
+
warnings.warn(msg, category=DeprecationWarning, stacklevel=4)
|
107 |
+
rtol = float(tol) if tol is not None else rtol
|
108 |
+
|
109 |
+
matvec = A.matvec
|
110 |
+
psolve = M.matvec
|
111 |
+
|
112 |
+
first = 'Enter minres. '
|
113 |
+
last = 'Exit minres. '
|
114 |
+
|
115 |
+
n = A.shape[0]
|
116 |
+
|
117 |
+
if maxiter is None:
|
118 |
+
maxiter = 5 * n
|
119 |
+
|
120 |
+
msg = [' beta2 = 0. If M = I, b and x are eigenvectors ', # -1
|
121 |
+
' beta1 = 0. The exact solution is x0 ', # 0
|
122 |
+
' A solution to Ax = b was found, given rtol ', # 1
|
123 |
+
' A least-squares solution was found, given rtol ', # 2
|
124 |
+
' Reasonable accuracy achieved, given eps ', # 3
|
125 |
+
' x has converged to an eigenvector ', # 4
|
126 |
+
' acond has exceeded 0.1/eps ', # 5
|
127 |
+
' The iteration limit was reached ', # 6
|
128 |
+
' A does not define a symmetric matrix ', # 7
|
129 |
+
' M does not define a symmetric matrix ', # 8
|
130 |
+
' M does not define a pos-def preconditioner '] # 9
|
131 |
+
|
132 |
+
if show:
|
133 |
+
print(first + 'Solution of symmetric Ax = b')
|
134 |
+
print(first + f'n = {n:3g} shift = {shift:23.14e}')
|
135 |
+
print(first + f'itnlim = {maxiter:3g} rtol = {rtol:11.2e}')
|
136 |
+
print()
|
137 |
+
|
138 |
+
istop = 0
|
139 |
+
itn = 0
|
140 |
+
Anorm = 0
|
141 |
+
Acond = 0
|
142 |
+
rnorm = 0
|
143 |
+
ynorm = 0
|
144 |
+
|
145 |
+
xtype = x.dtype
|
146 |
+
|
147 |
+
eps = finfo(xtype).eps
|
148 |
+
|
149 |
+
# Set up y and v for the first Lanczos vector v1.
|
150 |
+
# y = beta1 P' v1, where P = C**(-1).
|
151 |
+
# v is really P' v1.
|
152 |
+
|
153 |
+
if x0 is None:
|
154 |
+
r1 = b.copy()
|
155 |
+
else:
|
156 |
+
r1 = b - A@x
|
157 |
+
y = psolve(r1)
|
158 |
+
|
159 |
+
beta1 = inner(r1, y)
|
160 |
+
|
161 |
+
if beta1 < 0:
|
162 |
+
raise ValueError('indefinite preconditioner')
|
163 |
+
elif beta1 == 0:
|
164 |
+
return (postprocess(x), 0)
|
165 |
+
|
166 |
+
bnorm = norm(b)
|
167 |
+
if bnorm == 0:
|
168 |
+
x = b
|
169 |
+
return (postprocess(x), 0)
|
170 |
+
|
171 |
+
beta1 = sqrt(beta1)
|
172 |
+
|
173 |
+
if check:
|
174 |
+
# are these too strict?
|
175 |
+
|
176 |
+
# see if A is symmetric
|
177 |
+
w = matvec(y)
|
178 |
+
r2 = matvec(w)
|
179 |
+
s = inner(w,w)
|
180 |
+
t = inner(y,r2)
|
181 |
+
z = abs(s - t)
|
182 |
+
epsa = (s + eps) * eps**(1.0/3.0)
|
183 |
+
if z > epsa:
|
184 |
+
raise ValueError('non-symmetric matrix')
|
185 |
+
|
186 |
+
# see if M is symmetric
|
187 |
+
r2 = psolve(y)
|
188 |
+
s = inner(y,y)
|
189 |
+
t = inner(r1,r2)
|
190 |
+
z = abs(s - t)
|
191 |
+
epsa = (s + eps) * eps**(1.0/3.0)
|
192 |
+
if z > epsa:
|
193 |
+
raise ValueError('non-symmetric preconditioner')
|
194 |
+
|
195 |
+
# Initialize other quantities
|
196 |
+
oldb = 0
|
197 |
+
beta = beta1
|
198 |
+
dbar = 0
|
199 |
+
epsln = 0
|
200 |
+
qrnorm = beta1
|
201 |
+
phibar = beta1
|
202 |
+
rhs1 = beta1
|
203 |
+
rhs2 = 0
|
204 |
+
tnorm2 = 0
|
205 |
+
gmax = 0
|
206 |
+
gmin = finfo(xtype).max
|
207 |
+
cs = -1
|
208 |
+
sn = 0
|
209 |
+
w = zeros(n, dtype=xtype)
|
210 |
+
w2 = zeros(n, dtype=xtype)
|
211 |
+
r2 = r1
|
212 |
+
|
213 |
+
if show:
|
214 |
+
print()
|
215 |
+
print()
|
216 |
+
print(' Itn x(1) Compatible LS norm(A) cond(A) gbar/|A|')
|
217 |
+
|
218 |
+
while itn < maxiter:
|
219 |
+
itn += 1
|
220 |
+
|
221 |
+
s = 1.0/beta
|
222 |
+
v = s*y
|
223 |
+
|
224 |
+
y = matvec(v)
|
225 |
+
y = y - shift * v
|
226 |
+
|
227 |
+
if itn >= 2:
|
228 |
+
y = y - (beta/oldb)*r1
|
229 |
+
|
230 |
+
alfa = inner(v,y)
|
231 |
+
y = y - (alfa/beta)*r2
|
232 |
+
r1 = r2
|
233 |
+
r2 = y
|
234 |
+
y = psolve(r2)
|
235 |
+
oldb = beta
|
236 |
+
beta = inner(r2,y)
|
237 |
+
if beta < 0:
|
238 |
+
raise ValueError('non-symmetric matrix')
|
239 |
+
beta = sqrt(beta)
|
240 |
+
tnorm2 += alfa**2 + oldb**2 + beta**2
|
241 |
+
|
242 |
+
if itn == 1:
|
243 |
+
if beta/beta1 <= 10*eps:
|
244 |
+
istop = -1 # Terminate later
|
245 |
+
|
246 |
+
# Apply previous rotation Qk-1 to get
|
247 |
+
# [deltak epslnk+1] = [cs sn][dbark 0 ]
|
248 |
+
# [gbar k dbar k+1] [sn -cs][alfak betak+1].
|
249 |
+
|
250 |
+
oldeps = epsln
|
251 |
+
delta = cs * dbar + sn * alfa # delta1 = 0 deltak
|
252 |
+
gbar = sn * dbar - cs * alfa # gbar 1 = alfa1 gbar k
|
253 |
+
epsln = sn * beta # epsln2 = 0 epslnk+1
|
254 |
+
dbar = - cs * beta # dbar 2 = beta2 dbar k+1
|
255 |
+
root = norm([gbar, dbar])
|
256 |
+
Arnorm = phibar * root
|
257 |
+
|
258 |
+
# Compute the next plane rotation Qk
|
259 |
+
|
260 |
+
gamma = norm([gbar, beta]) # gammak
|
261 |
+
gamma = max(gamma, eps)
|
262 |
+
cs = gbar / gamma # ck
|
263 |
+
sn = beta / gamma # sk
|
264 |
+
phi = cs * phibar # phik
|
265 |
+
phibar = sn * phibar # phibark+1
|
266 |
+
|
267 |
+
# Update x.
|
268 |
+
|
269 |
+
denom = 1.0/gamma
|
270 |
+
w1 = w2
|
271 |
+
w2 = w
|
272 |
+
w = (v - oldeps*w1 - delta*w2) * denom
|
273 |
+
x = x + phi*w
|
274 |
+
|
275 |
+
# Go round again.
|
276 |
+
|
277 |
+
gmax = max(gmax, gamma)
|
278 |
+
gmin = min(gmin, gamma)
|
279 |
+
z = rhs1 / gamma
|
280 |
+
rhs1 = rhs2 - delta*z
|
281 |
+
rhs2 = - epsln*z
|
282 |
+
|
283 |
+
# Estimate various norms and test for convergence.
|
284 |
+
|
285 |
+
Anorm = sqrt(tnorm2)
|
286 |
+
ynorm = norm(x)
|
287 |
+
epsa = Anorm * eps
|
288 |
+
epsx = Anorm * ynorm * eps
|
289 |
+
epsr = Anorm * ynorm * rtol
|
290 |
+
diag = gbar
|
291 |
+
|
292 |
+
if diag == 0:
|
293 |
+
diag = epsa
|
294 |
+
|
295 |
+
qrnorm = phibar
|
296 |
+
rnorm = qrnorm
|
297 |
+
if ynorm == 0 or Anorm == 0:
|
298 |
+
test1 = inf
|
299 |
+
else:
|
300 |
+
test1 = rnorm / (Anorm*ynorm) # ||r|| / (||A|| ||x||)
|
301 |
+
if Anorm == 0:
|
302 |
+
test2 = inf
|
303 |
+
else:
|
304 |
+
test2 = root / Anorm # ||Ar|| / (||A|| ||r||)
|
305 |
+
|
306 |
+
# Estimate cond(A).
|
307 |
+
# In this version we look at the diagonals of R in the
|
308 |
+
# factorization of the lower Hessenberg matrix, Q @ H = R,
|
309 |
+
# where H is the tridiagonal matrix from Lanczos with one
|
310 |
+
# extra row, beta(k+1) e_k^T.
|
311 |
+
|
312 |
+
Acond = gmax/gmin
|
313 |
+
|
314 |
+
# See if any of the stopping criteria are satisfied.
|
315 |
+
# In rare cases, istop is already -1 from above (Abar = const*I).
|
316 |
+
|
317 |
+
if istop == 0:
|
318 |
+
t1 = 1 + test1 # These tests work if rtol < eps
|
319 |
+
t2 = 1 + test2
|
320 |
+
if t2 <= 1:
|
321 |
+
istop = 2
|
322 |
+
if t1 <= 1:
|
323 |
+
istop = 1
|
324 |
+
|
325 |
+
if itn >= maxiter:
|
326 |
+
istop = 6
|
327 |
+
if Acond >= 0.1/eps:
|
328 |
+
istop = 4
|
329 |
+
if epsx >= beta1:
|
330 |
+
istop = 3
|
331 |
+
# if rnorm <= epsx : istop = 2
|
332 |
+
# if rnorm <= epsr : istop = 1
|
333 |
+
if test2 <= rtol:
|
334 |
+
istop = 2
|
335 |
+
if test1 <= rtol:
|
336 |
+
istop = 1
|
337 |
+
|
338 |
+
# See if it is time to print something.
|
339 |
+
|
340 |
+
prnt = False
|
341 |
+
if n <= 40:
|
342 |
+
prnt = True
|
343 |
+
if itn <= 10:
|
344 |
+
prnt = True
|
345 |
+
if itn >= maxiter-10:
|
346 |
+
prnt = True
|
347 |
+
if itn % 10 == 0:
|
348 |
+
prnt = True
|
349 |
+
if qrnorm <= 10*epsx:
|
350 |
+
prnt = True
|
351 |
+
if qrnorm <= 10*epsr:
|
352 |
+
prnt = True
|
353 |
+
if Acond <= 1e-2/eps:
|
354 |
+
prnt = True
|
355 |
+
if istop != 0:
|
356 |
+
prnt = True
|
357 |
+
|
358 |
+
if show and prnt:
|
359 |
+
str1 = f'{itn:6g} {x[0]:12.5e} {test1:10.3e}'
|
360 |
+
str2 = f' {test2:10.3e}'
|
361 |
+
str3 = f' {Anorm:8.1e} {Acond:8.1e} {gbar/Anorm:8.1e}'
|
362 |
+
|
363 |
+
print(str1 + str2 + str3)
|
364 |
+
|
365 |
+
if itn % 10 == 0:
|
366 |
+
print()
|
367 |
+
|
368 |
+
if callback is not None:
|
369 |
+
callback(x)
|
370 |
+
|
371 |
+
if istop != 0:
|
372 |
+
break # TODO check this
|
373 |
+
|
374 |
+
if show:
|
375 |
+
print()
|
376 |
+
print(last + f' istop = {istop:3g} itn ={itn:5g}')
|
377 |
+
print(last + f' Anorm = {Anorm:12.4e} Acond = {Acond:12.4e}')
|
378 |
+
print(last + f' rnorm = {rnorm:12.4e} ynorm = {ynorm:12.4e}')
|
379 |
+
print(last + f' Arnorm = {Arnorm:12.4e}')
|
380 |
+
print(last + msg[istop+1])
|
381 |
+
|
382 |
+
if istop == 6:
|
383 |
+
info = maxiter
|
384 |
+
else:
|
385 |
+
info = 0
|
386 |
+
|
387 |
+
return (postprocess(x),info)
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/__init__.py
ADDED
File without changes
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (201 Bytes). View file
|
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/__pycache__/test_gcrotmk.cpython-310.pyc
ADDED
Binary file (5.28 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/__pycache__/test_iterative.cpython-310.pyc
ADDED
Binary file (21.3 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/__pycache__/test_lgmres.cpython-310.pyc
ADDED
Binary file (6.67 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/__pycache__/test_lsmr.cpython-310.pyc
ADDED
Binary file (6.64 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/__pycache__/test_lsqr.cpython-310.pyc
ADDED
Binary file (3.04 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/__pycache__/test_minres.cpython-310.pyc
ADDED
Binary file (3.16 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/__pycache__/test_utils.cpython-310.pyc
ADDED
Binary file (599 Bytes). View file
|
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_gcrotmk.py
ADDED
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python
|
2 |
+
"""Tests for the linalg._isolve.gcrotmk module
|
3 |
+
"""
|
4 |
+
|
5 |
+
from numpy.testing import (assert_, assert_allclose, assert_equal,
|
6 |
+
suppress_warnings)
|
7 |
+
|
8 |
+
import numpy as np
|
9 |
+
from numpy import zeros, array, allclose
|
10 |
+
from scipy.linalg import norm
|
11 |
+
from scipy.sparse import csr_matrix, eye, rand
|
12 |
+
|
13 |
+
from scipy.sparse.linalg._interface import LinearOperator
|
14 |
+
from scipy.sparse.linalg import splu
|
15 |
+
from scipy.sparse.linalg._isolve import gcrotmk, gmres
|
16 |
+
|
17 |
+
|
18 |
+
Am = csr_matrix(array([[-2,1,0,0,0,9],
|
19 |
+
[1,-2,1,0,5,0],
|
20 |
+
[0,1,-2,1,0,0],
|
21 |
+
[0,0,1,-2,1,0],
|
22 |
+
[0,3,0,1,-2,1],
|
23 |
+
[1,0,0,0,1,-2]]))
|
24 |
+
b = array([1,2,3,4,5,6])
|
25 |
+
count = [0]
|
26 |
+
|
27 |
+
|
28 |
+
def matvec(v):
|
29 |
+
count[0] += 1
|
30 |
+
return Am@v
|
31 |
+
|
32 |
+
|
33 |
+
A = LinearOperator(matvec=matvec, shape=Am.shape, dtype=Am.dtype)
|
34 |
+
|
35 |
+
|
36 |
+
def do_solve(**kw):
|
37 |
+
count[0] = 0
|
38 |
+
with suppress_warnings() as sup:
|
39 |
+
sup.filter(DeprecationWarning, ".*called without specifying.*")
|
40 |
+
x0, flag = gcrotmk(A, b, x0=zeros(A.shape[0]), rtol=1e-14, **kw)
|
41 |
+
count_0 = count[0]
|
42 |
+
assert_(allclose(A@x0, b, rtol=1e-12, atol=1e-12), norm(A@x0-b))
|
43 |
+
return x0, count_0
|
44 |
+
|
45 |
+
|
46 |
+
class TestGCROTMK:
|
47 |
+
def test_preconditioner(self):
|
48 |
+
# Check that preconditioning works
|
49 |
+
pc = splu(Am.tocsc())
|
50 |
+
M = LinearOperator(matvec=pc.solve, shape=A.shape, dtype=A.dtype)
|
51 |
+
|
52 |
+
x0, count_0 = do_solve()
|
53 |
+
x1, count_1 = do_solve(M=M)
|
54 |
+
|
55 |
+
assert_equal(count_1, 3)
|
56 |
+
assert_(count_1 < count_0/2)
|
57 |
+
assert_(allclose(x1, x0, rtol=1e-14))
|
58 |
+
|
59 |
+
def test_arnoldi(self):
|
60 |
+
np.random.seed(1)
|
61 |
+
|
62 |
+
A = eye(2000) + rand(2000, 2000, density=5e-4)
|
63 |
+
b = np.random.rand(2000)
|
64 |
+
|
65 |
+
# The inner arnoldi should be equivalent to gmres
|
66 |
+
with suppress_warnings() as sup:
|
67 |
+
sup.filter(DeprecationWarning, ".*called without specifying.*")
|
68 |
+
x0, flag0 = gcrotmk(A, b, x0=zeros(A.shape[0]), m=15, k=0, maxiter=1)
|
69 |
+
x1, flag1 = gmres(A, b, x0=zeros(A.shape[0]), restart=15, maxiter=1)
|
70 |
+
|
71 |
+
assert_equal(flag0, 1)
|
72 |
+
assert_equal(flag1, 1)
|
73 |
+
assert np.linalg.norm(A.dot(x0) - b) > 1e-3
|
74 |
+
|
75 |
+
assert_allclose(x0, x1)
|
76 |
+
|
77 |
+
def test_cornercase(self):
|
78 |
+
np.random.seed(1234)
|
79 |
+
|
80 |
+
# Rounding error may prevent convergence with tol=0 --- ensure
|
81 |
+
# that the return values in this case are correct, and no
|
82 |
+
# exceptions are raised
|
83 |
+
|
84 |
+
for n in [3, 5, 10, 100]:
|
85 |
+
A = 2*eye(n)
|
86 |
+
|
87 |
+
with suppress_warnings() as sup:
|
88 |
+
sup.filter(DeprecationWarning, ".*called without specifying.*")
|
89 |
+
b = np.ones(n)
|
90 |
+
x, info = gcrotmk(A, b, maxiter=10)
|
91 |
+
assert_equal(info, 0)
|
92 |
+
assert_allclose(A.dot(x) - b, 0, atol=1e-14)
|
93 |
+
|
94 |
+
x, info = gcrotmk(A, b, rtol=0, maxiter=10)
|
95 |
+
if info == 0:
|
96 |
+
assert_allclose(A.dot(x) - b, 0, atol=1e-14)
|
97 |
+
|
98 |
+
b = np.random.rand(n)
|
99 |
+
x, info = gcrotmk(A, b, maxiter=10)
|
100 |
+
assert_equal(info, 0)
|
101 |
+
assert_allclose(A.dot(x) - b, 0, atol=1e-14)
|
102 |
+
|
103 |
+
x, info = gcrotmk(A, b, rtol=0, maxiter=10)
|
104 |
+
if info == 0:
|
105 |
+
assert_allclose(A.dot(x) - b, 0, atol=1e-14)
|
106 |
+
|
107 |
+
def test_nans(self):
|
108 |
+
A = eye(3, format='lil')
|
109 |
+
A[1,1] = np.nan
|
110 |
+
b = np.ones(3)
|
111 |
+
|
112 |
+
with suppress_warnings() as sup:
|
113 |
+
sup.filter(DeprecationWarning, ".*called without specifying.*")
|
114 |
+
x, info = gcrotmk(A, b, rtol=0, maxiter=10)
|
115 |
+
assert_equal(info, 1)
|
116 |
+
|
117 |
+
def test_truncate(self):
|
118 |
+
np.random.seed(1234)
|
119 |
+
A = np.random.rand(30, 30) + np.eye(30)
|
120 |
+
b = np.random.rand(30)
|
121 |
+
|
122 |
+
for truncate in ['oldest', 'smallest']:
|
123 |
+
with suppress_warnings() as sup:
|
124 |
+
sup.filter(DeprecationWarning, ".*called without specifying.*")
|
125 |
+
x, info = gcrotmk(A, b, m=10, k=10, truncate=truncate,
|
126 |
+
rtol=1e-4, maxiter=200)
|
127 |
+
assert_equal(info, 0)
|
128 |
+
assert_allclose(A.dot(x) - b, 0, atol=1e-3)
|
129 |
+
|
130 |
+
def test_CU(self):
|
131 |
+
for discard_C in (True, False):
|
132 |
+
# Check that C,U behave as expected
|
133 |
+
CU = []
|
134 |
+
x0, count_0 = do_solve(CU=CU, discard_C=discard_C)
|
135 |
+
assert_(len(CU) > 0)
|
136 |
+
assert_(len(CU) <= 6)
|
137 |
+
|
138 |
+
if discard_C:
|
139 |
+
for c, u in CU:
|
140 |
+
assert_(c is None)
|
141 |
+
|
142 |
+
# should converge immediately
|
143 |
+
x1, count_1 = do_solve(CU=CU, discard_C=discard_C)
|
144 |
+
if discard_C:
|
145 |
+
assert_equal(count_1, 2 + len(CU))
|
146 |
+
else:
|
147 |
+
assert_equal(count_1, 3)
|
148 |
+
assert_(count_1 <= count_0/2)
|
149 |
+
assert_allclose(x1, x0, atol=1e-14)
|
150 |
+
|
151 |
+
def test_denormals(self):
|
152 |
+
# Check that no warnings are emitted if the matrix contains
|
153 |
+
# numbers for which 1/x has no float representation, and that
|
154 |
+
# the solver behaves properly.
|
155 |
+
A = np.array([[1, 2], [3, 4]], dtype=float)
|
156 |
+
A *= 100 * np.nextafter(0, 1)
|
157 |
+
|
158 |
+
b = np.array([1, 1])
|
159 |
+
|
160 |
+
with suppress_warnings() as sup:
|
161 |
+
sup.filter(DeprecationWarning, ".*called without specifying.*")
|
162 |
+
xp, info = gcrotmk(A, b)
|
163 |
+
|
164 |
+
if info == 0:
|
165 |
+
assert_allclose(A.dot(xp), b)
|
venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_iterative.py
ADDED
@@ -0,0 +1,796 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
""" Test functions for the sparse.linalg._isolve module
|
2 |
+
"""
|
3 |
+
|
4 |
+
import itertools
|
5 |
+
import platform
|
6 |
+
import sys
|
7 |
+
import pytest
|
8 |
+
|
9 |
+
import numpy as np
|
10 |
+
from numpy.testing import assert_array_equal, assert_allclose
|
11 |
+
from numpy import zeros, arange, array, ones, eye, iscomplexobj
|
12 |
+
from numpy.linalg import norm
|
13 |
+
|
14 |
+
from scipy.sparse import spdiags, csr_matrix, kronsum
|
15 |
+
|
16 |
+
from scipy.sparse.linalg import LinearOperator, aslinearoperator
|
17 |
+
from scipy.sparse.linalg._isolve import (bicg, bicgstab, cg, cgs,
|
18 |
+
gcrotmk, gmres, lgmres,
|
19 |
+
minres, qmr, tfqmr)
|
20 |
+
|
21 |
+
# TODO check that method preserve shape and type
|
22 |
+
# TODO test both preconditioner methods
|
23 |
+
|
24 |
+
|
25 |
+
# list of all solvers under test
|
26 |
+
_SOLVERS = [bicg, bicgstab, cg, cgs, gcrotmk, gmres, lgmres,
|
27 |
+
minres, qmr, tfqmr]
|
28 |
+
|
29 |
+
pytestmark = [
|
30 |
+
# remove this once atol defaults to 0.0 for all methods
|
31 |
+
pytest.mark.filterwarnings("ignore:.*called without specifying.*"),
|
32 |
+
]
|
33 |
+
|
34 |
+
|
35 |
+
# create parametrized fixture for easy reuse in tests
|
36 |
+
@pytest.fixture(params=_SOLVERS, scope="session")
|
37 |
+
def solver(request):
|
38 |
+
"""
|
39 |
+
Fixture for all solvers in scipy.sparse.linalg._isolve
|
40 |
+
"""
|
41 |
+
return request.param
|
42 |
+
|
43 |
+
|
44 |
+
class Case:
|
45 |
+
def __init__(self, name, A, b=None, skip=None, nonconvergence=None):
|
46 |
+
self.name = name
|
47 |
+
self.A = A
|
48 |
+
if b is None:
|
49 |
+
self.b = arange(A.shape[0], dtype=float)
|
50 |
+
else:
|
51 |
+
self.b = b
|
52 |
+
if skip is None:
|
53 |
+
self.skip = []
|
54 |
+
else:
|
55 |
+
self.skip = skip
|
56 |
+
if nonconvergence is None:
|
57 |
+
self.nonconvergence = []
|
58 |
+
else:
|
59 |
+
self.nonconvergence = nonconvergence
|
60 |
+
|
61 |
+
|
62 |
+
class SingleTest:
|
63 |
+
def __init__(self, A, b, solver, casename, convergence=True):
|
64 |
+
self.A = A
|
65 |
+
self.b = b
|
66 |
+
self.solver = solver
|
67 |
+
self.name = casename + '-' + solver.__name__
|
68 |
+
self.convergence = convergence
|
69 |
+
|
70 |
+
def __repr__(self):
|
71 |
+
return f"<{self.name}>"
|
72 |
+
|
73 |
+
|
74 |
+
class IterativeParams:
|
75 |
+
def __init__(self):
|
76 |
+
sym_solvers = [minres, cg]
|
77 |
+
posdef_solvers = [cg]
|
78 |
+
real_solvers = [minres]
|
79 |
+
|
80 |
+
# list of Cases
|
81 |
+
self.cases = []
|
82 |
+
|
83 |
+
# Symmetric and Positive Definite
|
84 |
+
N = 40
|
85 |
+
data = ones((3, N))
|
86 |
+
data[0, :] = 2
|
87 |
+
data[1, :] = -1
|
88 |
+
data[2, :] = -1
|
89 |
+
Poisson1D = spdiags(data, [0, -1, 1], N, N, format='csr')
|
90 |
+
self.cases.append(Case("poisson1d", Poisson1D))
|
91 |
+
# note: minres fails for single precision
|
92 |
+
self.cases.append(Case("poisson1d-F", Poisson1D.astype('f'),
|
93 |
+
skip=[minres]))
|
94 |
+
|
95 |
+
# Symmetric and Negative Definite
|
96 |
+
self.cases.append(Case("neg-poisson1d", -Poisson1D,
|
97 |
+
skip=posdef_solvers))
|
98 |
+
# note: minres fails for single precision
|
99 |
+
self.cases.append(Case("neg-poisson1d-F", (-Poisson1D).astype('f'),
|
100 |
+
skip=posdef_solvers + [minres]))
|
101 |
+
|
102 |
+
# 2-dimensional Poisson equations
|
103 |
+
Poisson2D = kronsum(Poisson1D, Poisson1D)
|
104 |
+
# note: minres fails for 2-d poisson problem,
|
105 |
+
# it will be fixed in the future PR
|
106 |
+
self.cases.append(Case("poisson2d", Poisson2D, skip=[minres]))
|
107 |
+
# note: minres fails for single precision
|
108 |
+
self.cases.append(Case("poisson2d-F", Poisson2D.astype('f'),
|
109 |
+
skip=[minres]))
|
110 |
+
|
111 |
+
# Symmetric and Indefinite
|
112 |
+
data = array([[6, -5, 2, 7, -1, 10, 4, -3, -8, 9]], dtype='d')
|
113 |
+
RandDiag = spdiags(data, [0], 10, 10, format='csr')
|
114 |
+
self.cases.append(Case("rand-diag", RandDiag, skip=posdef_solvers))
|
115 |
+
self.cases.append(Case("rand-diag-F", RandDiag.astype('f'),
|
116 |
+
skip=posdef_solvers))
|
117 |
+
|
118 |
+
# Random real-valued
|
119 |
+
np.random.seed(1234)
|
120 |
+
data = np.random.rand(4, 4)
|
121 |
+
self.cases.append(Case("rand", data,
|
122 |
+
skip=posdef_solvers + sym_solvers))
|
123 |
+
self.cases.append(Case("rand-F", data.astype('f'),
|
124 |
+
skip=posdef_solvers + sym_solvers))
|
125 |
+
|
126 |
+
# Random symmetric real-valued
|
127 |
+
np.random.seed(1234)
|
128 |
+
data = np.random.rand(4, 4)
|
129 |
+
data = data + data.T
|
130 |
+
self.cases.append(Case("rand-sym", data, skip=posdef_solvers))
|
131 |
+
self.cases.append(Case("rand-sym-F", data.astype('f'),
|
132 |
+
skip=posdef_solvers))
|
133 |
+
|
134 |
+
# Random pos-def symmetric real
|
135 |
+
np.random.seed(1234)
|
136 |
+
data = np.random.rand(9, 9)
|
137 |
+
data = np.dot(data.conj(), data.T)
|
138 |
+
self.cases.append(Case("rand-sym-pd", data))
|
139 |
+
# note: minres fails for single precision
|
140 |
+
self.cases.append(Case("rand-sym-pd-F", data.astype('f'),
|
141 |
+
skip=[minres]))
|
142 |
+
|
143 |
+
# Random complex-valued
|
144 |
+
np.random.seed(1234)
|
145 |
+
data = np.random.rand(4, 4) + 1j * np.random.rand(4, 4)
|
146 |
+
skip_cmplx = posdef_solvers + sym_solvers + real_solvers
|
147 |
+
self.cases.append(Case("rand-cmplx", data, skip=skip_cmplx))
|
148 |
+
self.cases.append(Case("rand-cmplx-F", data.astype('F'),
|
149 |
+
skip=skip_cmplx))
|
150 |
+
|
151 |
+
# Random hermitian complex-valued
|
152 |
+
np.random.seed(1234)
|
153 |
+
data = np.random.rand(4, 4) + 1j * np.random.rand(4, 4)
|
154 |
+
data = data + data.T.conj()
|
155 |
+
self.cases.append(Case("rand-cmplx-herm", data,
|
156 |
+
skip=posdef_solvers + real_solvers))
|
157 |
+
self.cases.append(Case("rand-cmplx-herm-F", data.astype('F'),
|
158 |
+
skip=posdef_solvers + real_solvers))
|
159 |
+
|
160 |
+
# Random pos-def hermitian complex-valued
|
161 |
+
np.random.seed(1234)
|
162 |
+
data = np.random.rand(9, 9) + 1j * np.random.rand(9, 9)
|
163 |
+
data = np.dot(data.conj(), data.T)
|
164 |
+
self.cases.append(Case("rand-cmplx-sym-pd", data, skip=real_solvers))
|
165 |
+
self.cases.append(Case("rand-cmplx-sym-pd-F", data.astype('F'),
|
166 |
+
skip=real_solvers))
|
167 |
+
|
168 |
+
# Non-symmetric and Positive Definite
|
169 |
+
#
|
170 |
+
# cgs, qmr, bicg and tfqmr fail to converge on this one
|
171 |
+
# -- algorithmic limitation apparently
|
172 |
+
data = ones((2, 10))
|
173 |
+
data[0, :] = 2
|
174 |
+
data[1, :] = -1
|
175 |
+
A = spdiags(data, [0, -1], 10, 10, format='csr')
|
176 |
+
self.cases.append(Case("nonsymposdef", A,
|
177 |
+
skip=sym_solvers + [cgs, qmr, bicg, tfqmr]))
|
178 |
+
self.cases.append(Case("nonsymposdef-F", A.astype('F'),
|
179 |
+
skip=sym_solvers + [cgs, qmr, bicg, tfqmr]))
|
180 |
+
|
181 |
+
# Symmetric, non-pd, hitting cgs/bicg/bicgstab/qmr/tfqmr breakdown
|
182 |
+
A = np.array([[0, 0, 0, 0, 0, 1, -1, -0, -0, -0, -0],
|
183 |
+
[0, 0, 0, 0, 0, 2, -0, -1, -0, -0, -0],
|
184 |
+
[0, 0, 0, 0, 0, 2, -0, -0, -1, -0, -0],
|
185 |
+
[0, 0, 0, 0, 0, 2, -0, -0, -0, -1, -0],
|
186 |
+
[0, 0, 0, 0, 0, 1, -0, -0, -0, -0, -1],
|
187 |
+
[1, 2, 2, 2, 1, 0, -0, -0, -0, -0, -0],
|
188 |
+
[-1, 0, 0, 0, 0, 0, -1, -0, -0, -0, -0],
|
189 |
+
[0, -1, 0, 0, 0, 0, -0, -1, -0, -0, -0],
|
190 |
+
[0, 0, -1, 0, 0, 0, -0, -0, -1, -0, -0],
|
191 |
+
[0, 0, 0, -1, 0, 0, -0, -0, -0, -1, -0],
|
192 |
+
[0, 0, 0, 0, -1, 0, -0, -0, -0, -0, -1]], dtype=float)
|
193 |
+
b = np.array([0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], dtype=float)
|
194 |
+
assert (A == A.T).all()
|
195 |
+
self.cases.append(Case("sym-nonpd", A, b,
|
196 |
+
skip=posdef_solvers,
|
197 |
+
nonconvergence=[cgs, bicg, bicgstab, qmr, tfqmr]
|
198 |
+
)
|
199 |
+
)
|
200 |
+
|
201 |
+
def generate_tests(self):
|
202 |
+
# generate test cases with skips applied
|
203 |
+
tests = []
|
204 |
+
for case in self.cases:
|
205 |
+
for solver in _SOLVERS:
|
206 |
+
if (solver in case.skip):
|
207 |
+
continue
|
208 |
+
if solver in case.nonconvergence:
|
209 |
+
tests += [SingleTest(case.A, case.b, solver, case.name,
|
210 |
+
convergence=False)]
|
211 |
+
else:
|
212 |
+
tests += [SingleTest(case.A, case.b, solver, case.name)]
|
213 |
+
return tests
|
214 |
+
|
215 |
+
|
216 |
+
cases = IterativeParams().generate_tests()
|
217 |
+
|
218 |
+
|
219 |
+
@pytest.fixture(params=cases, ids=[x.name for x in cases], scope="module")
|
220 |
+
def case(request):
|
221 |
+
"""
|
222 |
+
Fixture for all cases in IterativeParams
|
223 |
+
"""
|
224 |
+
return request.param
|
225 |
+
|
226 |
+
|
227 |
+
def test_maxiter(case):
|
228 |
+
if not case.convergence:
|
229 |
+
pytest.skip("Solver - Breakdown case, see gh-8829")
|
230 |
+
A = case.A
|
231 |
+
rtol = 1e-12
|
232 |
+
|
233 |
+
b = case.b
|
234 |
+
x0 = 0 * b
|
235 |
+
|
236 |
+
residuals = []
|
237 |
+
|
238 |
+
def callback(x):
|
239 |
+
residuals.append(norm(b - case.A * x))
|
240 |
+
|
241 |
+
x, info = case.solver(A, b, x0=x0, rtol=rtol, maxiter=1, callback=callback)
|
242 |
+
|
243 |
+
assert len(residuals) == 1
|
244 |
+
assert info == 1
|
245 |
+
|
246 |
+
|
247 |
+
def test_convergence(case):
|
248 |
+
A = case.A
|
249 |
+
|
250 |
+
if A.dtype.char in "dD":
|
251 |
+
rtol = 1e-8
|
252 |
+
else:
|
253 |
+
rtol = 1e-2
|
254 |
+
|
255 |
+
b = case.b
|
256 |
+
x0 = 0 * b
|
257 |
+
|
258 |
+
x, info = case.solver(A, b, x0=x0, rtol=rtol)
|
259 |
+
|
260 |
+
assert_array_equal(x0, 0 * b) # ensure that x0 is not overwritten
|
261 |
+
if case.convergence:
|
262 |
+
assert info == 0
|
263 |
+
assert norm(A @ x - b) <= norm(b) * rtol
|
264 |
+
else:
|
265 |
+
assert info != 0
|
266 |
+
assert norm(A @ x - b) <= norm(b)
|
267 |
+
|
268 |
+
|
269 |
+
def test_precond_dummy(case):
|
270 |
+
if not case.convergence:
|
271 |
+
pytest.skip("Solver - Breakdown case, see gh-8829")
|
272 |
+
|
273 |
+
rtol = 1e-8
|
274 |
+
|
275 |
+
def identity(b, which=None):
|
276 |
+
"""trivial preconditioner"""
|
277 |
+
return b
|
278 |
+
|
279 |
+
A = case.A
|
280 |
+
|
281 |
+
M, N = A.shape
|
282 |
+
# Ensure the diagonal elements of A are non-zero before calculating
|
283 |
+
# 1.0/A.diagonal()
|
284 |
+
diagOfA = A.diagonal()
|
285 |
+
if np.count_nonzero(diagOfA) == len(diagOfA):
|
286 |
+
spdiags([1.0 / diagOfA], [0], M, N)
|
287 |
+
|
288 |
+
b = case.b
|
289 |
+
x0 = 0 * b
|
290 |
+
|
291 |
+
precond = LinearOperator(A.shape, identity, rmatvec=identity)
|
292 |
+
|
293 |
+
if case.solver is qmr:
|
294 |
+
x, info = case.solver(A, b, M1=precond, M2=precond, x0=x0, rtol=rtol)
|
295 |
+
else:
|
296 |
+
x, info = case.solver(A, b, M=precond, x0=x0, rtol=rtol)
|
297 |
+
assert info == 0
|
298 |
+
assert norm(A @ x - b) <= norm(b) * rtol
|
299 |
+
|
300 |
+
A = aslinearoperator(A)
|
301 |
+
A.psolve = identity
|
302 |
+
A.rpsolve = identity
|
303 |
+
|
304 |
+
x, info = case.solver(A, b, x0=x0, rtol=rtol)
|
305 |
+
assert info == 0
|
306 |
+
assert norm(A @ x - b) <= norm(b) * rtol
|
307 |
+
|
308 |
+
|
309 |
+
# Specific test for poisson1d and poisson2d cases
|
310 |
+
@pytest.mark.parametrize('case', [x for x in IterativeParams().cases
|
311 |
+
if x.name in ('poisson1d', 'poisson2d')],
|
312 |
+
ids=['poisson1d', 'poisson2d'])
|
313 |
+
def test_precond_inverse(case):
|
314 |
+
for solver in _SOLVERS:
|
315 |
+
if solver in case.skip or solver is qmr:
|
316 |
+
continue
|
317 |
+
|
318 |
+
rtol = 1e-8
|
319 |
+
|
320 |
+
def inverse(b, which=None):
|
321 |
+
"""inverse preconditioner"""
|
322 |
+
A = case.A
|
323 |
+
if not isinstance(A, np.ndarray):
|
324 |
+
A = A.toarray()
|
325 |
+
return np.linalg.solve(A, b)
|
326 |
+
|
327 |
+
def rinverse(b, which=None):
|
328 |
+
"""inverse preconditioner"""
|
329 |
+
A = case.A
|
330 |
+
if not isinstance(A, np.ndarray):
|
331 |
+
A = A.toarray()
|
332 |
+
return np.linalg.solve(A.T, b)
|
333 |
+
|
334 |
+
matvec_count = [0]
|
335 |
+
|
336 |
+
def matvec(b):
|
337 |
+
matvec_count[0] += 1
|
338 |
+
return case.A @ b
|
339 |
+
|
340 |
+
def rmatvec(b):
|
341 |
+
matvec_count[0] += 1
|
342 |
+
return case.A.T @ b
|
343 |
+
|
344 |
+
b = case.b
|
345 |
+
x0 = 0 * b
|
346 |
+
|
347 |
+
A = LinearOperator(case.A.shape, matvec, rmatvec=rmatvec)
|
348 |
+
precond = LinearOperator(case.A.shape, inverse, rmatvec=rinverse)
|
349 |
+
|
350 |
+
# Solve with preconditioner
|
351 |
+
matvec_count = [0]
|
352 |
+
x, info = solver(A, b, M=precond, x0=x0, rtol=rtol)
|
353 |
+
|
354 |
+
assert info == 0
|
355 |
+
assert norm(case.A @ x - b) <= norm(b) * rtol
|
356 |
+
|
357 |
+
# Solution should be nearly instant
|
358 |
+
assert matvec_count[0] <= 3
|
359 |
+
|
360 |
+
|
361 |
+
def test_atol(solver):
|
362 |
+
# TODO: minres / tfqmr. It didn't historically use absolute tolerances, so
|
363 |
+
# fixing it is less urgent.
|
364 |
+
if solver in (minres, tfqmr):
|
365 |
+
pytest.skip("TODO: Add atol to minres/tfqmr")
|
366 |
+
|
367 |
+
# Historically this is tested as below, all pass but for some reason
|
368 |
+
# gcrotmk is over-sensitive to difference between random.seed/rng.random
|
369 |
+
# Hence tol lower bound is changed from -10 to -9
|
370 |
+
# np.random.seed(1234)
|
371 |
+
# A = np.random.rand(10, 10)
|
372 |
+
# A = A @ A.T + 10 * np.eye(10)
|
373 |
+
# b = 1e3*np.random.rand(10)
|
374 |
+
|
375 |
+
rng = np.random.default_rng(168441431005389)
|
376 |
+
A = rng.uniform(size=[10, 10])
|
377 |
+
A = A @ A.T + 10*np.eye(10)
|
378 |
+
b = 1e3 * rng.uniform(size=10)
|
379 |
+
|
380 |
+
b_norm = np.linalg.norm(b)
|
381 |
+
|
382 |
+
tols = np.r_[0, np.logspace(-9, 2, 7), np.inf]
|
383 |
+
|
384 |
+
# Check effect of badly scaled preconditioners
|
385 |
+
M0 = rng.standard_normal(size=(10, 10))
|
386 |
+
M0 = M0 @ M0.T
|
387 |
+
Ms = [None, 1e-6 * M0, 1e6 * M0]
|
388 |
+
|
389 |
+
for M, rtol, atol in itertools.product(Ms, tols, tols):
|
390 |
+
if rtol == 0 and atol == 0:
|
391 |
+
continue
|
392 |
+
|
393 |
+
if solver is qmr:
|
394 |
+
if M is not None:
|
395 |
+
M = aslinearoperator(M)
|
396 |
+
M2 = aslinearoperator(np.eye(10))
|
397 |
+
else:
|
398 |
+
M2 = None
|
399 |
+
x, info = solver(A, b, M1=M, M2=M2, rtol=rtol, atol=atol)
|
400 |
+
else:
|
401 |
+
x, info = solver(A, b, M=M, rtol=rtol, atol=atol)
|
402 |
+
|
403 |
+
assert info == 0
|
404 |
+
residual = A @ x - b
|
405 |
+
err = np.linalg.norm(residual)
|
406 |
+
atol2 = rtol * b_norm
|
407 |
+
# Added 1.00025 fudge factor because of `err` exceeding `atol` just
|
408 |
+
# very slightly on s390x (see gh-17839)
|
409 |
+
assert err <= 1.00025 * max(atol, atol2)
|
410 |
+
|
411 |
+
|
412 |
+
def test_zero_rhs(solver):
|
413 |
+
rng = np.random.default_rng(1684414984100503)
|
414 |
+
A = rng.random(size=[10, 10])
|
415 |
+
A = A @ A.T + 10 * np.eye(10)
|
416 |
+
|
417 |
+
b = np.zeros(10)
|
418 |
+
tols = np.r_[np.logspace(-10, 2, 7)]
|
419 |
+
|
420 |
+
for tol in tols:
|
421 |
+
x, info = solver(A, b, rtol=tol)
|
422 |
+
assert info == 0
|
423 |
+
assert_allclose(x, 0., atol=1e-15)
|
424 |
+
|
425 |
+
x, info = solver(A, b, rtol=tol, x0=ones(10))
|
426 |
+
assert info == 0
|
427 |
+
assert_allclose(x, 0., atol=tol)
|
428 |
+
|
429 |
+
if solver is not minres:
|
430 |
+
x, info = solver(A, b, rtol=tol, atol=0, x0=ones(10))
|
431 |
+
if info == 0:
|
432 |
+
assert_allclose(x, 0)
|
433 |
+
|
434 |
+
x, info = solver(A, b, rtol=tol, atol=tol)
|
435 |
+
assert info == 0
|
436 |
+
assert_allclose(x, 0, atol=1e-300)
|
437 |
+
|
438 |
+
x, info = solver(A, b, rtol=tol, atol=0)
|
439 |
+
assert info == 0
|
440 |
+
assert_allclose(x, 0, atol=1e-300)
|
441 |
+
|
442 |
+
|
443 |
+
@pytest.mark.xfail(reason="see gh-18697")
|
444 |
+
def test_maxiter_worsening(solver):
|
445 |
+
if solver not in (gmres, lgmres, qmr):
|
446 |
+
# these were skipped from the very beginning, see gh-9201; gh-14160
|
447 |
+
pytest.skip("Solver breakdown case")
|
448 |
+
# Check error does not grow (boundlessly) with increasing maxiter.
|
449 |
+
# This can occur due to the solvers hitting close to breakdown,
|
450 |
+
# which they should detect and halt as necessary.
|
451 |
+
# cf. gh-9100
|
452 |
+
if (solver is gmres and platform.machine() == 'aarch64'
|
453 |
+
and sys.version_info[1] == 9):
|
454 |
+
pytest.xfail(reason="gh-13019")
|
455 |
+
if (solver is lgmres and
|
456 |
+
platform.machine() not in ['x86_64' 'x86', 'aarch64', 'arm64']):
|
457 |
+
# see gh-17839
|
458 |
+
pytest.xfail(reason="fails on at least ppc64le, ppc64 and riscv64")
|
459 |
+
|
460 |
+
# Singular matrix, rhs numerically not in range
|
461 |
+
A = np.array([[-0.1112795288033378, 0, 0, 0.16127952880333685],
|
462 |
+
[0, -0.13627952880333782 + 6.283185307179586j, 0, 0],
|
463 |
+
[0, 0, -0.13627952880333782 - 6.283185307179586j, 0],
|
464 |
+
[0.1112795288033368, 0j, 0j, -0.16127952880333785]])
|
465 |
+
v = np.ones(4)
|
466 |
+
best_error = np.inf
|
467 |
+
|
468 |
+
# Unable to match the Fortran code tolerance levels with this example
|
469 |
+
# Original tolerance values
|
470 |
+
|
471 |
+
# slack_tol = 7 if platform.machine() == 'aarch64' else 5
|
472 |
+
slack_tol = 9
|
473 |
+
|
474 |
+
for maxiter in range(1, 20):
|
475 |
+
x, info = solver(A, v, maxiter=maxiter, rtol=1e-8, atol=0)
|
476 |
+
|
477 |
+
if info == 0:
|
478 |
+
assert norm(A @ x - v) <= 1e-8 * norm(v)
|
479 |
+
|
480 |
+
error = np.linalg.norm(A @ x - v)
|
481 |
+
best_error = min(best_error, error)
|
482 |
+
|
483 |
+
# Check with slack
|
484 |
+
assert error <= slack_tol * best_error
|
485 |
+
|
486 |
+
|
487 |
+
def test_x0_working(solver):
|
488 |
+
# Easy problem
|
489 |
+
rng = np.random.default_rng(1685363802304750)
|
490 |
+
n = 10
|
491 |
+
A = rng.random(size=[n, n])
|
492 |
+
A = A @ A.T
|
493 |
+
b = rng.random(n)
|
494 |
+
x0 = rng.random(n)
|
495 |
+
|
496 |
+
if solver is minres:
|
497 |
+
kw = dict(rtol=1e-6)
|
498 |
+
else:
|
499 |
+
kw = dict(atol=0, rtol=1e-6)
|
500 |
+
|
501 |
+
x, info = solver(A, b, **kw)
|
502 |
+
assert info == 0
|
503 |
+
assert norm(A @ x - b) <= 1e-6 * norm(b)
|
504 |
+
|
505 |
+
x, info = solver(A, b, x0=x0, **kw)
|
506 |
+
assert info == 0
|
507 |
+
assert norm(A @ x - b) <= 2e-6*norm(b)
|
508 |
+
|
509 |
+
|
510 |
+
def test_x0_equals_Mb(case):
|
511 |
+
if case.solver is tfqmr:
|
512 |
+
pytest.skip("Solver does not support x0='Mb'")
|
513 |
+
A = case.A
|
514 |
+
b = case.b
|
515 |
+
x0 = 'Mb'
|
516 |
+
rtol = 1e-8
|
517 |
+
x, info = case.solver(A, b, x0=x0, rtol=rtol)
|
518 |
+
|
519 |
+
assert_array_equal(x0, 'Mb') # ensure that x0 is not overwritten
|
520 |
+
assert info == 0
|
521 |
+
assert norm(A @ x - b) <= rtol * norm(b)
|
522 |
+
|
523 |
+
|
524 |
+
@pytest.mark.parametrize('solver', _SOLVERS)
|
525 |
+
def test_x0_solves_problem_exactly(solver):
|
526 |
+
# See gh-19948
|
527 |
+
mat = np.eye(2)
|
528 |
+
rhs = np.array([-1., -1.])
|
529 |
+
|
530 |
+
sol, info = solver(mat, rhs, x0=rhs)
|
531 |
+
assert_allclose(sol, rhs)
|
532 |
+
assert info == 0
|
533 |
+
|
534 |
+
|
535 |
+
# Specific tfqmr test
|
536 |
+
@pytest.mark.parametrize('case', IterativeParams().cases)
|
537 |
+
def test_show(case, capsys):
|
538 |
+
def cb(x):
|
539 |
+
pass
|
540 |
+
|
541 |
+
x, info = tfqmr(case.A, case.b, callback=cb, show=True)
|
542 |
+
out, err = capsys.readouterr()
|
543 |
+
|
544 |
+
if case.name == "sym-nonpd":
|
545 |
+
# no logs for some reason
|
546 |
+
exp = ""
|
547 |
+
elif case.name in ("nonsymposdef", "nonsymposdef-F"):
|
548 |
+
# Asymmetric and Positive Definite
|
549 |
+
exp = "TFQMR: Linear solve not converged due to reach MAXIT iterations"
|
550 |
+
else: # all other cases
|
551 |
+
exp = "TFQMR: Linear solve converged due to reach TOL iterations"
|
552 |
+
|
553 |
+
assert out.startswith(exp)
|
554 |
+
assert err == ""
|
555 |
+
|
556 |
+
|
557 |
+
def test_positional_deprecation(solver):
|
558 |
+
# from test_x0_working
|
559 |
+
rng = np.random.default_rng(1685363802304750)
|
560 |
+
n = 10
|
561 |
+
A = rng.random(size=[n, n])
|
562 |
+
A = A @ A.T
|
563 |
+
b = rng.random(n)
|
564 |
+
x0 = rng.random(n)
|
565 |
+
with pytest.deprecated_call(
|
566 |
+
# due to the use of the _deprecate_positional_args decorator, it's not possible
|
567 |
+
# to separate the two warnings (1 for positional use, 1 for `tol` deprecation).
|
568 |
+
match="use keyword arguments.*|argument `tol` is deprecated.*"
|
569 |
+
):
|
570 |
+
solver(A, b, x0, 1e-5)
|
571 |
+
|
572 |
+
|
573 |
+
class TestQMR:
|
574 |
+
@pytest.mark.filterwarnings('ignore::scipy.sparse.SparseEfficiencyWarning')
|
575 |
+
def test_leftright_precond(self):
|
576 |
+
"""Check that QMR works with left and right preconditioners"""
|
577 |
+
|
578 |
+
from scipy.sparse.linalg._dsolve import splu
|
579 |
+
from scipy.sparse.linalg._interface import LinearOperator
|
580 |
+
|
581 |
+
n = 100
|
582 |
+
|
583 |
+
dat = ones(n)
|
584 |
+
A = spdiags([-2 * dat, 4 * dat, -dat], [-1, 0, 1], n, n)
|
585 |
+
b = arange(n, dtype='d')
|
586 |
+
|
587 |
+
L = spdiags([-dat / 2, dat], [-1, 0], n, n)
|
588 |
+
U = spdiags([4 * dat, -dat], [0, 1], n, n)
|
589 |
+
L_solver = splu(L)
|
590 |
+
U_solver = splu(U)
|
591 |
+
|
592 |
+
def L_solve(b):
|
593 |
+
return L_solver.solve(b)
|
594 |
+
|
595 |
+
def U_solve(b):
|
596 |
+
return U_solver.solve(b)
|
597 |
+
|
598 |
+
def LT_solve(b):
|
599 |
+
return L_solver.solve(b, 'T')
|
600 |
+
|
601 |
+
def UT_solve(b):
|
602 |
+
return U_solver.solve(b, 'T')
|
603 |
+
|
604 |
+
M1 = LinearOperator((n, n), matvec=L_solve, rmatvec=LT_solve)
|
605 |
+
M2 = LinearOperator((n, n), matvec=U_solve, rmatvec=UT_solve)
|
606 |
+
|
607 |
+
rtol = 1e-8
|
608 |
+
x, info = qmr(A, b, rtol=rtol, maxiter=15, M1=M1, M2=M2)
|
609 |
+
|
610 |
+
assert info == 0
|
611 |
+
assert norm(A @ x - b) <= rtol * norm(b)
|
612 |
+
|
613 |
+
|
614 |
+
class TestGMRES:
|
615 |
+
def test_basic(self):
|
616 |
+
A = np.vander(np.arange(10) + 1)[:, ::-1]
|
617 |
+
b = np.zeros(10)
|
618 |
+
b[0] = 1
|
619 |
+
|
620 |
+
x_gm, err = gmres(A, b, restart=5, maxiter=1)
|
621 |
+
|
622 |
+
assert_allclose(x_gm[0], 0.359, rtol=1e-2)
|
623 |
+
|
624 |
+
def test_callback(self):
|
625 |
+
|
626 |
+
def store_residual(r, rvec):
|
627 |
+
rvec[rvec.nonzero()[0].max() + 1] = r
|
628 |
+
|
629 |
+
# Define, A,b
|
630 |
+
A = csr_matrix(array([[-2, 1, 0, 0, 0, 0],
|
631 |
+
[1, -2, 1, 0, 0, 0],
|
632 |
+
[0, 1, -2, 1, 0, 0],
|
633 |
+
[0, 0, 1, -2, 1, 0],
|
634 |
+
[0, 0, 0, 1, -2, 1],
|
635 |
+
[0, 0, 0, 0, 1, -2]]))
|
636 |
+
b = ones((A.shape[0],))
|
637 |
+
maxiter = 1
|
638 |
+
rvec = zeros(maxiter + 1)
|
639 |
+
rvec[0] = 1.0
|
640 |
+
|
641 |
+
def callback(r):
|
642 |
+
return store_residual(r, rvec)
|
643 |
+
|
644 |
+
x, flag = gmres(A, b, x0=zeros(A.shape[0]), rtol=1e-16,
|
645 |
+
maxiter=maxiter, callback=callback)
|
646 |
+
|
647 |
+
# Expected output from SciPy 1.0.0
|
648 |
+
assert_allclose(rvec, array([1.0, 0.81649658092772603]), rtol=1e-10)
|
649 |
+
|
650 |
+
# Test preconditioned callback
|
651 |
+
M = 1e-3 * np.eye(A.shape[0])
|
652 |
+
rvec = zeros(maxiter + 1)
|
653 |
+
rvec[0] = 1.0
|
654 |
+
x, flag = gmres(A, b, M=M, rtol=1e-16, maxiter=maxiter,
|
655 |
+
callback=callback)
|
656 |
+
|
657 |
+
# Expected output from SciPy 1.0.0
|
658 |
+
# (callback has preconditioned residual!)
|
659 |
+
assert_allclose(rvec, array([1.0, 1e-3 * 0.81649658092772603]),
|
660 |
+
rtol=1e-10)
|
661 |
+
|
662 |
+
def test_abi(self):
|
663 |
+
# Check we don't segfault on gmres with complex argument
|
664 |
+
A = eye(2)
|
665 |
+
b = ones(2)
|
666 |
+
r_x, r_info = gmres(A, b)
|
667 |
+
r_x = r_x.astype(complex)
|
668 |
+
x, info = gmres(A.astype(complex), b.astype(complex))
|
669 |
+
|
670 |
+
assert iscomplexobj(x)
|
671 |
+
assert_allclose(r_x, x)
|
672 |
+
assert r_info == info
|
673 |
+
|
674 |
+
def test_atol_legacy(self):
|
675 |
+
|
676 |
+
A = eye(2)
|
677 |
+
b = ones(2)
|
678 |
+
x, info = gmres(A, b, rtol=1e-5)
|
679 |
+
assert np.linalg.norm(A @ x - b) <= 1e-5 * np.linalg.norm(b)
|
680 |
+
assert_allclose(x, b, atol=0, rtol=1e-8)
|
681 |
+
|
682 |
+
rndm = np.random.RandomState(12345)
|
683 |
+
A = rndm.rand(30, 30)
|
684 |
+
b = 1e-6 * ones(30)
|
685 |
+
x, info = gmres(A, b, rtol=1e-7, restart=20)
|
686 |
+
assert np.linalg.norm(A @ x - b) > 1e-7
|
687 |
+
|
688 |
+
A = eye(2)
|
689 |
+
b = 1e-10 * ones(2)
|
690 |
+
x, info = gmres(A, b, rtol=1e-8, atol=0)
|
691 |
+
assert np.linalg.norm(A @ x - b) <= 1e-8 * np.linalg.norm(b)
|
692 |
+
|
693 |
+
def test_defective_precond_breakdown(self):
|
694 |
+
# Breakdown due to defective preconditioner
|
695 |
+
M = np.eye(3)
|
696 |
+
M[2, 2] = 0
|
697 |
+
|
698 |
+
b = np.array([0, 1, 1])
|
699 |
+
x = np.array([1, 0, 0])
|
700 |
+
A = np.diag([2, 3, 4])
|
701 |
+
|
702 |
+
x, info = gmres(A, b, x0=x, M=M, rtol=1e-15, atol=0)
|
703 |
+
|
704 |
+
# Should not return nans, nor terminate with false success
|
705 |
+
assert not np.isnan(x).any()
|
706 |
+
if info == 0:
|
707 |
+
assert np.linalg.norm(A @ x - b) <= 1e-15 * np.linalg.norm(b)
|
708 |
+
|
709 |
+
# The solution should be OK outside null space of M
|
710 |
+
assert_allclose(M @ (A @ x), M @ b)
|
711 |
+
|
712 |
+
def test_defective_matrix_breakdown(self):
|
713 |
+
# Breakdown due to defective matrix
|
714 |
+
A = np.array([[0, 1, 0], [1, 0, 0], [0, 0, 0]])
|
715 |
+
b = np.array([1, 0, 1])
|
716 |
+
rtol = 1e-8
|
717 |
+
x, info = gmres(A, b, rtol=rtol, atol=0)
|
718 |
+
|
719 |
+
# Should not return nans, nor terminate with false success
|
720 |
+
assert not np.isnan(x).any()
|
721 |
+
if info == 0:
|
722 |
+
assert np.linalg.norm(A @ x - b) <= rtol * np.linalg.norm(b)
|
723 |
+
|
724 |
+
# The solution should be OK outside null space of A
|
725 |
+
assert_allclose(A @ (A @ x), A @ b)
|
726 |
+
|
727 |
+
def test_callback_type(self):
|
728 |
+
# The legacy callback type changes meaning of 'maxiter'
|
729 |
+
np.random.seed(1)
|
730 |
+
A = np.random.rand(20, 20)
|
731 |
+
b = np.random.rand(20)
|
732 |
+
|
733 |
+
cb_count = [0]
|
734 |
+
|
735 |
+
def pr_norm_cb(r):
|
736 |
+
cb_count[0] += 1
|
737 |
+
assert isinstance(r, float)
|
738 |
+
|
739 |
+
def x_cb(x):
|
740 |
+
cb_count[0] += 1
|
741 |
+
assert isinstance(x, np.ndarray)
|
742 |
+
|
743 |
+
# 2 iterations is not enough to solve the problem
|
744 |
+
cb_count = [0]
|
745 |
+
x, info = gmres(A, b, rtol=1e-6, atol=0, callback=pr_norm_cb,
|
746 |
+
maxiter=2, restart=50)
|
747 |
+
assert info == 2
|
748 |
+
assert cb_count[0] == 2
|
749 |
+
|
750 |
+
# With `callback_type` specified, no warning should be raised
|
751 |
+
cb_count = [0]
|
752 |
+
x, info = gmres(A, b, rtol=1e-6, atol=0, callback=pr_norm_cb,
|
753 |
+
maxiter=2, restart=50, callback_type='legacy')
|
754 |
+
assert info == 2
|
755 |
+
assert cb_count[0] == 2
|
756 |
+
|
757 |
+
# 2 restart cycles is enough to solve the problem
|
758 |
+
cb_count = [0]
|
759 |
+
x, info = gmres(A, b, rtol=1e-6, atol=0, callback=pr_norm_cb,
|
760 |
+
maxiter=2, restart=50, callback_type='pr_norm')
|
761 |
+
assert info == 0
|
762 |
+
assert cb_count[0] > 2
|
763 |
+
|
764 |
+
# 2 restart cycles is enough to solve the problem
|
765 |
+
cb_count = [0]
|
766 |
+
x, info = gmres(A, b, rtol=1e-6, atol=0, callback=x_cb, maxiter=2,
|
767 |
+
restart=50, callback_type='x')
|
768 |
+
assert info == 0
|
769 |
+
assert cb_count[0] == 1
|
770 |
+
|
771 |
+
def test_callback_x_monotonic(self):
|
772 |
+
# Check that callback_type='x' gives monotonic norm decrease
|
773 |
+
np.random.seed(1)
|
774 |
+
A = np.random.rand(20, 20) + np.eye(20)
|
775 |
+
b = np.random.rand(20)
|
776 |
+
|
777 |
+
prev_r = [np.inf]
|
778 |
+
count = [0]
|
779 |
+
|
780 |
+
def x_cb(x):
|
781 |
+
r = np.linalg.norm(A @ x - b)
|
782 |
+
assert r <= prev_r[0]
|
783 |
+
prev_r[0] = r
|
784 |
+
count[0] += 1
|
785 |
+
|
786 |
+
x, info = gmres(A, b, rtol=1e-6, atol=0, callback=x_cb, maxiter=20,
|
787 |
+
restart=10, callback_type='x')
|
788 |
+
assert info == 20
|
789 |
+
assert count[0] == 20
|
790 |
+
|
791 |
+
def test_restrt_dep(self):
|
792 |
+
with pytest.warns(
|
793 |
+
DeprecationWarning,
|
794 |
+
match="'gmres' keyword argument 'restrt'"
|
795 |
+
):
|
796 |
+
gmres(np.array([1]), np.array([1]), restrt=10)
|