Algorithmadvanced
LSQR
Also called Paige-Saunders LSQR.
Paige and Saunders' Krylov method for least squares, built on Golub-Kahan bidiagonalization; equal to CGLS in exact arithmetic, more stable in floating point, and a standard iterative regularizer.
- Time
- O(k (a + m + n)) totalO(a + m + n) per_iterationO(k (a + k (m + n))) reorthogonalized
- Space
- O(m + n) extraO(k (m + n)) reorthogonalized
- Counts
- iterations r exact_termination
- Where
- a = the cost of one product with A plus one product with A*; k = the number of iterations; m = the number of data values; n = the number of unknowns; r = the rank of A
- Properties
- deterministiciterativenot linear in datamatrix free
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Christopher C. Paige, Michael A. Saunders, 1982
LSQR, by Paige and Saunders (1982), solves with one product with and one with per step. It runs the Golub-Kahan bidiagonalization of started from , which builds orthonormal bases of the Krylov spaces, and it solves the projected least squares problem with one plane rotation per step. In exact arithmetic its iterates are those of CGLS: minimizes over . In floating point it is more reliable on ill-conditioned problems. On an ill-posed problem with noisy data , , the iteration count is the regularization parameter, and the rotations give the residual norm for free, so the discrepancy principle costs nothing extra. The bidiagonal matrix it builds is also the starting point of hybrid Krylov methods.
In plain words
LSQR builds, one step at a time, a small set of directions that describe the answer and a matching set that describe the data. Both sets are made of perpendicular directions, so that no direction repeats what another already says. In these directions the large problem looks like a tiny one with a simple two-diagonal shape, and the tiny problem is easy to solve exactly. Each step adds one direction to each set and updates the answer. The method also knows, at every step and without extra work, how well the answer fits the data. On noisy, blurred data, it is stopped as soon as that misfit drops to the noise level, because later steps mostly add noise.
The problem
Given (an matrix, or the two functions and ) and data , find the least squares solution of minimum norm, . For ill-posed problems the data are noisy, , and the goal is an approximation of whose error goes to with ; then the iteration is stopped early.
The algorithm
LSQR(A, y, K, δ, τ) ▷ τ > 1; real data- 1
β u ← y; α v ← A* u; w ← v; x ← 0; φ̄ ← β; ρ̄ ← α - 2
for k ← 1 to K do - 3
β u ← A v - α u ▷ β = norm, u a unit vector - 4
α v ← A* u - β v - 5
ρ ← √(ρ̄² + β²); c ← ρ̄ / ρ; s ← β / ρ - 6
θ ← s α; ρ̄ ← -c α; φ ← c φ̄; φ̄ ← s φ̄ - 7
x ← x + (φ / ρ) w; w ← v - (θ / ρ) w - 8
if |φ̄| ≤ τ δ or α = 0 or β = 0 then return (x, k) - 9
return (x, K)
A line "" means: and . Lines L1, L3 and L4 are the Golub-Kahan bidiagonalization: after steps, , where and have orthonormal columns and is lower bidiagonal of size , with on the diagonal and below it. LSQR looks for with minimizing . Lines L5 and L6 apply one plane rotation that removes the new subdiagonal entry , which updates a QR factorization of and of the right side. Line L7 updates by a short recurrence, so no basis vectors are kept. After the rotations, is exactly the residual norm , which line L8 compares with . Line L8 also returns when the bidiagonalization breaks down ( or ), which in exact arithmetic means that . The code has an option that orthogonalizes each new and against all earlier ones, which costs per step.
Example
A trace. Take the example of the CGLS page: , , and , so and, with , . Row shows the values after step (row after line L1).
| 0 | 0.90542 | 1.18896 | 1.18896 | 1.18896 | 2.4495 |
| 1 | 0.43930 | 0.37786 | 0.45791 | 0.45791 | 2.1007 |
| 2 | 0.27115 | 0.25614 | 0.24458 | 0.24458 | 1.7896 |
| 3 | 0.09064 | 0.12475 | 0.11691 | 0.11691 | 1.5720 |
| 4 | 0.09778 | 0.06136 | 0.07137 | 0.07137 | 1.1217 |
| 5 | 0.03193 | 0.01423 | 0.01289 | 0.01289 | 1.5109 |
| 6 | 0 (rounding level) | 0 | 0 | 1.8473 |
The residual estimate equals the true residual, and the residuals and errors agree with those of CGLS to all digits shown. Line L8 returns . At the bidiagonalization has exhausted and is zero up to rounding.
Loss of orthogonality. For the rectangle-rule matrix of and smooth data, the largest entry of was after 5 steps and after 8 steps without reorthogonalization; with full reorthogonalization it stayed at (a measurement). After 20 steps the residual was without and with reorthogonalization: the loss of orthogonality delays convergence, but the computed residual estimate still matched the true residual of the computed .
Correctness
The proof is in proofs/correctness.md, in exact arithmetic.
- Bidiagonalization (theorem). By induction, the vectors are orthonormal, the vectors are orthonormal, , and spans .
- Rotations (theorem). After rotations, with upper bidiagonal and nonsingular.
- Minimization (theorem). For , . So minimizes the residual over the Krylov space, which makes it the CGLS iterate, and its residual norm is . The recurrence of line L7 computes without storing .
- Breakdown (theorem). If or , then , and this happens after at most steps.
- Discrepancy stop (theorem). If has norm at most and , line L8 returns the first with .
The regularization properties are those of CGLS: with the discrepancy principle, LSQR is order optimal under the source condition for every (Nemirovskii 1986; EHN Chapter 7), a theorem cited and not proved here.
Proof: Correctness of LSQRfull
Exact arithmetic. is a real matrix and (for the code returns at once). The quantities are those of the pseudocode: line L1 sets , , , , , , where each is the norm that makes unit vectors. Step computes
"Before breakdown at step " means and are all positive. , , and is the lower bidiagonal matrix with diagonal and subdiagonal .
Lemma 1 (Golub-Kahan bidiagonalization). Before breakdown at step : the columns of are orthonormal, the columns of are orthonormal (where is defined, that is, ), and
Also .
Proof. The two relations are lines L3 and L4 read column by column: and (with ). Orthonormality by induction on ; the base is that and are unit vectors. Assume and are orthonormal. For ,
so , and . Then for ,
so , and . For the spans: , and by L3 and L4, is a combination of , and , so by induction. The are orthonormal, hence independent, so spans the -dimensional space .
Lemma 2 (the rotations). Before breakdown at step , every for , and there is an orthogonal matrix of order with
where is upper bidiagonal with diagonal and superdiagonal , and . Moreover the last row of , restricted to the new column , has the entries (row ) and (row ).
Proof. Induction on . Let be the identity except in rows and columns , where it is ; it is orthogonal because . Put (with extended by a on the diagonal). By the induction hypothesis (or directly for ), before acts, rows and of the matrix are and : row is the new row of , which the earlier rotations do not touch. maps the column pair to , and the right side to . Applied to the next column of , which has in row and in row , it gives . Positivity: . If , then , , and when . So for all .
Theorem 1 (LSQR minimizes the residual over the Krylov space). Before breakdown at step , with , is the unique minimizer of over , so it equals the CGLS iterate, and .
Proof. Every is for a unique (Lemma 1). Then , and since has orthonormal columns and is orthogonal,
is nonsingular by Lemma 2, so the unique minimizer is , with residual norm . It remains to show that line L7 computes . Put , with columns . Reading column by column gives and . With this is and , the update of line L7. The vector extends by one entry, because does not change rows . So , which is the sum that line L7 builds. By the correctness proof of CGLS (Theorem 1 there), the CGLS iterate is the same minimizer.
Theorem 2 (breakdown gives the minimum norm solution). If the loop stops with or (and all earlier values positive), then .
Proof. If , then and , so by Theorem 1 the residual is and . If , Lemma 1 gives , so , because solves the small least squares problem and so satisfies its normal equations. In both cases is a least squares solution. It lies in , and the only least squares solution orthogonal to is . The process must break down: the are orthonormal in , which has dimension , so or for some .
Theorem 3 (the discrepancy test). Let with and . Then line L8 stops the loop at the first with , and such a exists.
Proof. By Theorem 1 the test of line L8 compares the true residual with . At breakdown, by Theorem 2, and is the projection of onto , which is the projection of , of norm at most . So the test passes at the breakdown step at the latest. Since the test is made after every step in order, the first passing is returned.
Complexity
- Per iteration (floating-point model). One product with (line L3), one with (line L4), two norms, and about further operations for the vector updates. That is , or for a dense matrix.
- Iterations. In exact arithmetic, at most steps. With the discrepancy principle under the source condition, the stopping index is (a theorem, as for CGLS). In floating point more steps can be needed, because the bases lose orthogonality.
- Space. : . Full reorthogonalization stores and , space, and costs more time in step .
The condition number matters for accuracy, not for the count above. CGLS forms the gradient as LSQR does, but its recurrences for the scalars amplify rounding errors more when is ill-conditioned (Paige and Saunders 1982, an observed behavior with analysis in their paper).
Properties
- Same iterates as CGLS in exact arithmetic, with the same residual and solution norm curves: decreases and increases.
- Free residual norm. , and , also at no cost (Paige and Saunders).
- Free projected problem. The bidiagonal and the bases are available, so the small problem can be solved again with Tikhonov regularization (hybrid methods), and the singular values of approximate the largest singular values of .
- Nonlinear in the data, as CGLS, so the stopping index must depend on the data.
- Damped form. LSQR also solves with one more rotation per step, which is Tikhonov regularization with a fixed parameter.
Variants and improvements
- Damped LSQR. As in the paper, solve the Tikhonov problem by applying LSQR to the stacked matrix without forming it.
- Hybrid LSQR. Choose a Tikhonov parameter for the projected problem at each step, by the discrepancy principle or by a cross-validation rule; see hybrid Krylov regularization.
- Reorthogonalization. Full, partial or selective reorthogonalization keeps the bases orthogonal and makes the computed iterates follow the exact ones, at extra cost in time and memory.
- LSMR. Fong and Saunders (2011) apply MINRES to the normal equations in the same bidiagonal framework, so that decreases monotonically. Compare MINRES.
- Preconditioning. As for CGLS, a right preconditioner changes the penalized norm, for example to a smoothness seminorm.
When to use it
LSQR is the standard Krylov solver for large sparse or matrix-free least squares problems, well-posed or ill-posed. Use it instead of CGLS when the matrix is ill-conditioned and you care about the late iterates, when you want the residual norm without an extra product, or when you need the bidiagonal matrix for a hybrid method or for estimates of the singular values. CGLS is a little cheaper per step and simpler to write; for an early stop on a regularization problem the two usually give the same result (a heuristic). For small dense problems, truncated SVD gives more insight at a cost of .
Pitfalls
- Running without a stopping rule. Line L2 run to the end converges to the least squares solution of the noisy data, which is dominated by noise. Keep the test of line L8, with .
- Testing a breakdown with in floating point. In the example, is not exactly but at rounding level, and the normalization of line L3 then produces a vector of rounding noise. Line L8 should compare and with a tolerance such as times in production code.
- Trusting orthogonality. Without reorthogonalization, loses orthogonality after a few steps once a singular value has converged (in the example, from step 8). The iterates then lag behind the exact ones, and the singular values of contain spurious copies. Use reorthogonalization at lines L3 and L4 when you need the bases, as in hybrid methods.
- Damped LSQR as a parameter search. Running damped LSQR once per value of repeats the whole bidiagonalization each time. The bidiagonalization does not depend on ; a hybrid method reuses it.
- A wrong adjoint at line L4. The recurrences assume that the code for is the adjoint of the code for . Check it by an adjoint test.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the imaging and inverse problems pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Dense linear algebra on lists of rows (float, complex or Fraction entries).
A matrix is a list of rows. A vector is a list of numbers. The inner product
is <u, v> = sum_i conj(u_i) v_i, linear in the second argument, so that the
adjoint A^H satisfies <A x, y> = <x, A^H y>.
"""
import math
def _flat(x):
"""Flatten a list of rows (an image) into one list; a vector is returned as is."""
if x and isinstance(x[0], (list, tuple)):
return [v for row in x for v in row]
return x
def zeros(m, n):
"""The m x n zero matrix."""
return [[0.0] * n for _ in range(m)]
def eye(n):
"""The n x n identity matrix."""
out = zeros(n, n)
for i in range(n):
out[i][i] = 1.0
return out
def transpose(a):
"""A^T."""
return [list(col) for col in zip(*a)]
def conj_transpose(a):
"""A^H, the conjugate transpose."""
return [[v.conjugate() for v in col] for col in zip(*a)]
def matmul(a, b):
"""The product A B."""
bt = list(zip(*b))
return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]
def matvec(a, x):
"""The product A x."""
return [sum(v * w for v, w in zip(row, x)) for row in a]
def rmatvec(a, y):
"""The product A^H y."""
n = len(a[0]) if a else 0
out = [0.0] * n
for row, yi in zip(a, y):
if yi == 0:
continue
for j, v in enumerate(row):
out[j] += v.conjugate() * yi
return out
def dot(u, v):
"""<u, v> = sum_i conj(u_i) v_i. Images (lists of rows) are flattened."""
return sum(a.conjugate() * b for a, b in zip(_flat(u), _flat(v)))
def norm2(x):
"""The Euclidean norm. Images (lists of rows) are flattened."""
return math.sqrt(sum(abs(v) ** 2 for v in _flat(x)))
def solve(a, b):
"""Solve A x = b by Gaussian elimination with partial pivoting.
b is a vector or a matrix (a list of rows). A must be square and
nonsingular; a zero pivot raises ValueError. Fractions stay exact.
"""
n = len(a)
vec = not (b and isinstance(b[0], (list, tuple)))
rhs = [[bi] for bi in b] if vec else [list(r) for r in b]
m = [list(row) + rhs[i] for i, row in enumerate(a)]
w = len(m[0])
for c in range(n):
p = max(range(c, n), key=lambda r: abs(m[r][c]))
if m[p][c] == 0:
raise ValueError("singular matrix")
m[c], m[p] = m[p], m[c]
piv = m[c][c]
for r in range(c + 1, n):
f = m[r][c] / piv
if f != 0:
mr, mc = m[r], m[c]
for j in range(c, w):
mr[j] -= f * mc[j]
x = [[0.0] * (w - n) for _ in range(n)]
for r in range(n - 1, -1, -1):
for j in range(w - n):
s = m[r][n + j] - sum(m[r][k] * x[k][j] for k in range(r + 1, n))
x[r][j] = s / m[r][r]
return [row[0] for row in x] if vec else x
def cholesky(a):
"""Lower triangular L with A = L L^H for a Hermitian positive definite A."""
n = len(a)
low = zeros(n, n)
for j in range(n):
d = a[j][j] - sum(abs(low[j][k]) ** 2 for k in range(j))
d = d.real if isinstance(d, complex) else d
if not d > 0:
raise ValueError("matrix is not positive definite")
ljj = math.sqrt(d)
low[j][j] = ljj
for i in range(j + 1, n):
s = a[i][j] - sum(low[i][k] * low[j][k].conjugate() for k in range(j))
low[i][j] = s / ljj
return low
def cho_solve(low, b):
"""Solve (L L^H) x = b, with L from cholesky."""
n = len(low)
z = [0.0] * n
for i in range(n):
z[i] = (b[i] - sum(low[i][k] * z[k] for k in range(i))) / low[i][i]
x = [0.0] * n
for i in range(n - 1, -1, -1):
s = z[i] - sum(low[k][i].conjugate() * x[k] for k in range(i + 1, n))
x[i] = s / low[i][i].conjugate()
return x
def _rot_params(app, aqq, apq):
"""c, s of the Jacobi rotation that zeroes the (p, q) entry of [[app, apq], [apq, aqq]]."""
theta = (aqq - app) / (2.0 * apq)
t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
c = 1.0 / math.sqrt(1.0 + t * t)
return c, c * t
def sym_eig(a, tol=1e-15, max_sweeps=100):
"""Eigenvalues (ascending) and eigenvectors (as columns) of a real symmetric matrix.
Cyclic Jacobi method. Returns (w, Q) with A = Q diag(w) Q^T.
"""
n = len(a)
m = [[float(v) for v in row] for row in a]
q = eye(n)
for _ in range(max_sweeps):
off = sum(m[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
scale = sum(m[i][i] ** 2 for i in range(n)) + off
if off <= (tol * tol) * scale or off == 0.0:
break
for p in range(n - 1):
for r in range(p + 1, n):
apq = m[p][r]
if apq == 0.0:
continue
c, s = _rot_params(m[p][p], m[r][r], apq)
for k in range(n):
mkp, mkr = m[k][p], m[k][r]
m[k][p] = c * mkp - s * mkr
m[k][r] = s * mkp + c * mkr
mp, mr = m[p], m[r]
for k in range(n):
mpk, mrk = mp[k], mr[k]
mp[k] = c * mpk - s * mrk
mr[k] = s * mpk + c * mrk
m[p][r] = m[r][p] = 0.0
for k in range(n):
qkp, qkr = q[k][p], q[k][r]
q[k][p] = c * qkp - s * qkr
q[k][r] = s * qkp + c * qkr
order = sorted(range(n), key=lambda i: m[i][i])
w = [m[i][i] for i in order]
qs = [[q[k][i] for i in order] for k in range(n)]
return w, qs
def _complete(cols, m):
"""Replace zero columns of an m-row column list by unit vectors orthogonal to the others."""
for idx, col in enumerate(cols):
if any(v != 0.0 for v in col):
continue
for e in range(m):
cand = [0.0] * m
cand[e] = 1.0
for _ in range(2):
for jdx, other in enumerate(cols):
if jdx == idx or not any(v != 0.0 for v in other):
continue
h = sum(a * b for a, b in zip(other, cand))
cand = [a - h * b for a, b in zip(cand, other)]
nrm = math.sqrt(sum(v * v for v in cand))
if nrm > 0.5:
cols[idx] = [v / nrm for v in cand]
break
return cols
def svd(a, tol=1e-15, max_sweeps=100):
"""Thin SVD of a real m x n matrix by one-sided Jacobi (Hestenes).
Returns (U, S, V) with p = min(m, n): U is m x p, S a list of p values in
descending order, V is n x p, U^T U = I, V^T V = I and A = U diag(S) V^T.
"""
m, n = len(a), len(a[0])
if m < n:
v, s, u = svd(transpose(a), tol, max_sweeps)
return u, s, v
cols = [[float(a[i][j]) for i in range(m)] for j in range(n)]
vcols = [[1.0 if i == j else 0.0 for i in range(n)] for j in range(n)]
for _ in range(max_sweeps):
rotated = False
for p in range(n - 1):
for r in range(p + 1, n):
cp, cr = cols[p], cols[r]
alpha = sum(x * x for x in cp)
beta = sum(x * x for x in cr)
gamma = sum(x * y for x, y in zip(cp, cr))
if gamma == 0.0 or abs(gamma) <= tol * math.sqrt(alpha * beta):
continue
rotated = True
c, s = _rot_params(alpha, beta, gamma)
cols[p] = [c * x - s * y for x, y in zip(cp, cr)]
cols[r] = [s * x + c * y for x, y in zip(cp, cr)]
vp, vr = vcols[p], vcols[r]
vcols[p] = [c * x - s * y for x, y in zip(vp, vr)]
vcols[r] = [s * x + c * y for x, y in zip(vp, vr)]
if not rotated:
break
sig = [math.sqrt(sum(x * x for x in col)) for col in cols]
# A column below 1e-150 times the largest one is zero to working precision;
# its squares underflow, so its direction carries no information.
floor = max(sig) * 1e-150 if sig else 0.0
sig = [t if t > floor and t > 1e-150 else 0.0 for t in sig]
order = sorted(range(n), key=lambda j: -sig[j])
s_out = [sig[j] for j in order]
ucols = [[x / sig[j] for x in cols[j]] if sig[j] > 0.0 else [0.0] * m for j in order]
ucols = _complete(ucols, m)
u = [[ucols[j][i] for j in range(n)] for i in range(m)]
v = [[vcols[j][i] for j in order] for i in range(n)]
return u, s_out, v
def adjoint_gap(apply_a, apply_ah, x, y):
"""|<A x, y> - <x, A^H y>| / (||A x|| ||y||) for given functions A and A^H.
x and y may be vectors or images (lists of rows). If the denominator is
zero, the absolute gap is returned.
"""
ax = apply_a(x)
gap = abs(dot(ax, y) - dot(x, apply_ah(y)))
den = norm2(ax) * norm2(y)
return gap / den if den > 0.0 else gap
lsqr.py 115 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lsqr/. The authors are listed in prov/BNV7VJ.jsonl.
"""LSQR of Paige and Saunders for min ||y - A x|| with noisy data y.
Golub-Kahan bidiagonalization builds orthonormal bases U_{k+1} and V_k with
A V_k = U_{k+1} B_k, where B_k is lower bidiagonal of size (k+1) x k. LSQR
solves the small problem min ||beta_1 e_1 - B_k z|| by Givens rotations,
one per step, and updates x_k = V_k z_k with a short recurrence. In exact
arithmetic x_k is the CGLS iterate. The rotations also give the residual
norm ||y - A x_k|| = |phibar_k| at no extra cost, so the discrepancy
principle needs no extra product with A.
reorth=True keeps the U and V vectors and orthogonalizes each new vector
against all old ones (two passes). This costs O(k (m + n)) per step but
removes the loss of orthogonality that rounding causes.
"""
import math
from typing import Callable, List, Optional, Sequence
from imgla import matvec, rmatvec
Vector = List[float]
Operator = Callable[[Sequence[float]], Vector]
def _norm(v: Sequence[float]) -> float:
return math.sqrt(sum(t * t for t in v))
def _reorth(w: Vector, basis: List[Vector]) -> Vector:
for _ in range(2):
for b in basis:
h = sum(p * q for p, q in zip(b, w))
w = [p - h * q for p, q in zip(w, b)]
return w
class LSQRResult:
"""x: the last iterate; k: steps done; iterates: x_0, ..., x_k; resnorms:
|phibar_j| = ||y - A x_j|| (in exact arithmetic) for j = 0, ..., k; alphas and
betas: the bidiagonal entries alpha_1, ... and beta_1, ...; us, vs: the
Lanczos vectors (kept only with keep=True or reorth=True); stopped:
"discrepancy", "breakdown" or "maxit"."""
def __init__(self, **kw: object) -> None:
self.__dict__.update(kw)
def lsqr(apply_a: Operator, apply_at: Operator, y: Sequence[float], kmax: int,
delta: Optional[float] = None, tau: float = 1.01, reorth: bool = False,
keep: bool = False) -> LSQRResult:
"""Run at most kmax LSQR steps from x_0 = 0.
Precondition: apply_at is the adjoint of apply_a. If delta is given, stop
at the first k with |phibar_k| <= tau delta. Cost: per step one product
with A, one with A^T and O(m + n) more, plus O(k (m + n)) with reorth.
"""
beta = _norm(y)
u = [t / beta for t in y] if beta > 0 else [0.0] * len(y)
v = apply_at(u)
alpha = _norm(v)
v = [t / alpha for t in v] if alpha > 0 else v
w = list(v)
x = [0.0] * len(v)
phibar, rhobar = beta, alpha # @line L1
store = reorth or keep
us, vs = ([u], [v]) if store else ([], [])
alphas, betas = [alpha], [beta]
iterates, resnorms = [list(x)], [abs(phibar)]
stopped, k = "maxit", 0
if delta is not None and abs(phibar) <= tau * delta:
stopped = "discrepancy"
elif alpha == 0 or beta == 0:
stopped = "breakdown"
while stopped == "maxit" and k < kmax: # @line L2
k += 1
u = [p - alpha * q for p, q in zip(apply_a(v), u)]
if reorth:
u = _reorth(u, us)
beta = _norm(u)
u = [t / beta for t in u] if beta > 0 else [0.0] * len(u) # @line L3
v = [p - beta * q for p, q in zip(apply_at(u), v)]
if reorth:
v = _reorth(v, vs)
alpha = _norm(v)
v = [t / alpha for t in v] if alpha > 0 else [0.0] * len(v) # @line L4
rho = math.hypot(rhobar, beta)
c, s = rhobar / rho, beta / rho # @line L5
theta = s * alpha
rhobar = -c * alpha
phi = c * phibar
phibar = s * phibar # @line L6
x = [xi + (phi / rho) * wi for xi, wi in zip(x, w)]
w = [vi - (theta / rho) * wi for vi, wi in zip(v, w)] # @line L7
if store:
us.append(u)
vs.append(v)
alphas.append(alpha)
betas.append(beta)
iterates.append(list(x))
resnorms.append(abs(phibar))
if delta is not None and abs(phibar) <= tau * delta: # @line L8
stopped = "discrepancy"
elif alpha == 0 or beta == 0:
stopped = "breakdown"
return LSQRResult(x=x, k=k, iterates=iterates, resnorms=resnorms, alphas=alphas, # @line L9
betas=betas, us=us, vs=vs, stopped=stopped)
def lsqr_matrix(a: List[List[float]], y: Sequence[float], kmax: int, delta: Optional[float] = None,
tau: float = 1.01, reorth: bool = False, keep: bool = False) -> LSQRResult:
"""LSQR for a dense matrix A (a list of rows). Cost: O(m n) per step."""
return lsqr(lambda x: matvec(a, x), lambda r: rmatvec(a, r), y, kmax,
delta=delta, tau=tau, reorth=reorth, keep=keep)
test_lsqr.py 146 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lsqr/. The authors are listed in prov/BNV7VJ.jsonl.
import math
import random
import unittest
from imgla import adjoint_gap, matmul, matvec, norm2, rmatvec, solve, transpose
from lsqr import lsqr, lsqr_matrix
def rand_matrix(rng, m, n):
return [[rng.uniform(-1.0, 1.0) for _ in range(n)] for _ in range(m)]
def krylov_solution(a, y, k):
"""Brute force: minimize ||y - A x|| over K_k(A^T A, A^T y) with an orthonormal basis."""
ata = matmul(transpose(a), a)
q, w = [], rmatvec(a, y)
for _ in range(k):
for _ in range(2):
for b in q:
h = sum(p * t for p, t in zip(b, w))
w = [p - h * t for p, t in zip(w, b)]
nw = norm2(w)
q.append([p / nw for p in w])
w = matvec(ata, q[-1])
aq = [matvec(a, b) for b in q]
gram = [[sum(p * t for p, t in zip(u, v)) for v in aq] for u in aq]
c = solve(gram, [sum(p * t for p, t in zip(u, y)) for u in aq])
return [sum(c[j] * q[j][i] for j in range(k)) for i in range(len(a[0]))]
def max_orth_loss(vs):
return max(abs(sum(p * q for p, q in zip(vs[i], vs[j])) - (1.0 if i == j else 0.0))
for i in range(len(vs)) for j in range(len(vs)))
class TestLSQR(unittest.TestCase):
def test_bidiagonalization(self):
rng = random.Random(31)
a = rand_matrix(rng, 9, 6)
y = [rng.gauss(0.0, 1.0) for _ in range(9)]
k = 4
res = lsqr_matrix(a, y, k, keep=True)
self.assertLess(max_orth_loss(res.us), 1e-12)
self.assertLess(max_orth_loss(res.vs[:k]), 1e-12)
# A v_i = alpha_i u_i + beta_{i+1} u_{i+1}, the columns of A V_k = U_{k+1} B_k.
for i in range(k):
lhs = matvec(a, res.vs[i])
rhs = [res.alphas[i] * p + res.betas[i + 1] * q for p, q in zip(res.us[i], res.us[i + 1])]
for p, q in zip(lhs, rhs):
self.assertAlmostEqual(p, q, places=12)
self.assertAlmostEqual(res.betas[0], norm2(y), places=12)
def test_iterates_match_krylov_least_squares(self):
rng = random.Random(32)
a = rand_matrix(rng, 10, 6)
y = [rng.gauss(0.0, 1.0) for _ in range(10)]
res = lsqr_matrix(a, y, 6)
for k in range(1, 7):
ref = krylov_solution(a, y, k)
gap = norm2([p - q for p, q in zip(res.iterates[k], ref)])
self.assertLess(gap, 1e-8 * norm2(ref))
def test_residual_norm_estimate(self):
rng = random.Random(33)
a = rand_matrix(rng, 10, 6)
y = [rng.gauss(0.0, 1.0) for _ in range(10)]
res = lsqr_matrix(a, y, 6)
for x, est in zip(res.iterates, res.resnorms):
true = norm2([p - q for p, q in zip(y, matvec(a, x))])
self.assertAlmostEqual(est, true, places=10)
for r0, r1 in zip(res.resnorms, res.resnorms[1:]):
self.assertLessEqual(r1, r0 + 1e-14)
def test_full_rank_least_squares(self):
rng = random.Random(34)
a = rand_matrix(rng, 8, 5)
y = [rng.gauss(0.0, 1.0) for _ in range(8)]
x = lsqr_matrix(a, y, 5).x
ref = solve(matmul(transpose(a), a), rmatvec(a, y))
for p, q in zip(x, ref):
self.assertAlmostEqual(p, q, places=9)
def test_small_cases(self):
res = lsqr_matrix([[2.0]], [6.0], 5)
self.assertEqual(res.x, [3.0])
self.assertEqual(res.stopped, "breakdown")
self.assertEqual(res.k, 1)
res = lsqr_matrix([[1.0, 2.0], [3.0, 4.0]], [0.0, 0.0], 5)
self.assertEqual((res.x, res.k, res.stopped), ([0.0, 0.0], 0, "breakdown"))
def test_discrepancy_stop(self):
rng = random.Random(35)
a = rand_matrix(rng, 12, 6)
xt = [rng.gauss(0.0, 1.0) for _ in range(6)]
e = [rng.gauss(0.0, 1.0) for _ in range(12)]
delta, tau = 0.3, 1.1
ne = norm2(e)
y = [p + delta * q / ne for p, q in zip(matvec(a, xt), e)]
res = lsqr_matrix(a, y, 50, delta=delta, tau=tau)
self.assertEqual(res.stopped, "discrepancy")
self.assertLessEqual(res.resnorms[-1], tau * delta)
for r in res.resnorms[:-1]:
self.assertGreater(r, tau * delta)
def test_loss_of_orthogonality_and_reorthogonalization(self):
n = 60
h = 1.0 / n
a = [[h if j <= i else 0.0 for j in range(n)] for i in range(n)]
y = [(i + 0.5) * h * (1.0 - (i + 0.5) * h / 2.0) for i in range(n)]
plain = lsqr_matrix(a, y, 20, keep=True)
full = lsqr_matrix(a, y, 20, reorth=True)
self.assertGreater(max_orth_loss(plain.vs), 0.1)
self.assertLess(max_orth_loss(full.vs), 1e-12)
def test_matrix_free_operator(self):
n = 40
h = 1.0 / n
rng = random.Random(36)
def op(x):
out, acc = [], 0.0
for t in x:
acc += h * t
out.append(acc)
return out
def opt(y):
out, acc = [0.0] * n, 0.0
for i in range(n - 1, -1, -1):
acc += h * y[i]
out[i] = acc
return out
x = [rng.gauss(0.0, 1.0) for _ in range(n)]
z = [rng.gauss(0.0, 1.0) for _ in range(n)]
self.assertLess(adjoint_gap(op, opt, x, z), 1e-12)
a = [[h if j <= i else 0.0 for j in range(n)] for i in range(n)]
free = lsqr(op, opt, z, 4).x
dense = lsqr_matrix(a, z, 4).x
self.assertLess(norm2([p - q for p, q in zip(free, dense)]), 1e-8 * norm2(dense))
if __name__ == "__main__":
unittest.main()
History
Golub and Kahan described the bidiagonalization of a matrix in 1965, as the first step of a stable SVD algorithm, both by orthogonal transformations and by a Lanczos-type recurrence. Paige (1974) studied the recurrence for large sparse problems. Paige and Saunders published LSQR in 1982 in ACM Transactions on Mathematical Software, with the QR update by rotations, the residual estimates and a careful comparison with CGLS. Its use as an iterative regularization method, and as the core of hybrid methods, goes back to O'Leary and Simmons (1981) and Björck (1988), and is described in Hansen's books of 1998 and 2010.
References
- Christopher C. Paige and Michael A. Saunders, LSQR, an algorithm for sparse linear equations and sparse least squares, ACM Transactions on Mathematical Software 8(1), 1982, 43 to 71, the bidiagonalization, the QR update by plane rotations, the residual estimates and the stopping rules
- Gene Golub and William Kahan, Calculating the singular values and pseudo-inverse of a matrix, SIAM Journal on Numerical Analysis 2(2), 1965, 205 to 224, the bidiagonalization of a matrix by orthogonal transformations and by the Lanczos-type recurrence
- Per Christian Hansen, Rank-Deficient and Discrete Ill-Posed Problems, SIAM, 1998, Sections 6.3 to 6.5 (regularizing CG and LSQR iterations, and LSQR in finite precision)
- Per Christian Hansen, Discrete Inverse Problems, Insight and Algorithms, SIAM, 2010, Chapter 6 (iterative regularization with Krylov methods)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag BNV7VJ Edit this page History Report an error Markdown