Algorithmcore
CGLS
Also called conjugate gradient least squares, CGNR.
The conjugate gradient method applied to the normal equations A* A x = A* y without forming A* A; stopped early, its iteration count regularizes an ill-posed problem.
- Time
- O(k (a + m + n)) totalO(k m n) denseO(a + m + n) per_iteration
- Space
- O(m + n) extra
- 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
- Model
- Real RAM
- Properties
- deterministicfinite terminationiterativenot linear in datamatrix free
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Magnus R. Hestenes, Eduard Stiefel, 1952
CGLS is the conjugate gradient method applied to the normal equations , written so that it never forms . Each step costs one product with and one with the adjoint , the same as one Landweber step. The iterate minimizes the residual over the Krylov subspace . For a well-posed least squares problem this is a fast solver. For an ill-posed problem with noisy data , , the first iterates capture the dominant singular components and later ones fit the noise, so the iteration count is a regularization parameter. Stopped by the discrepancy principle, CGLS reaches the optimal rate in about the square root of the number of Landweber steps.
In plain words
The method improves a guess step by step, like the plain gradient method, but it remembers its earlier search directions. Each new direction is chosen so that it does not undo the progress of the earlier ones. So each step fits as much of the data as is possible with the directions found so far. On a blurred or smoothed measurement, the first directions describe the coarse, reliable shape of the answer, and later directions add fine details that are mostly noise. Stop at the right moment and the answer is sharp but not noisy. Run too long and it fills with noise. The stopping point comes from the noise level: stop as soon as the misfit is as small as the noise.
The problem
Given (an matrix, or an operator given by the functions and ), data with , and , find an approximation of the minimum norm solution whose error goes to with . Without noise and with large enough, CGLS solves the least squares problem .
The algorithm
CGLS(A, y, K, δ, τ) ▷ τ > 1- 1
x ← 0; r ← y; s ← A* r; p ← s; γ ← ‖s‖² - 2
for k ← 0 to K - 1 do - 3
if ‖r‖ ≤ τ δ then return (x, k) - 4
if γ = 0 then return (x, k) ▷ A* r = 0: least squares solution - 5
q ← A p - 6
α ← γ / ‖q‖² - 7
x ← x + α p - 8
r ← r - α q - 9
s ← A* r - 10
β ← ‖s‖² / γ; γ ← ‖s‖² - 11
p ← s + β p - 12
return (x, K)
The vector is the residual , and is the residual of the normal equations, that is, minus the gradient of . Line L1 starts at . Line L3 is the discrepancy principle, which returns the first iterate whose residual is at the noise level. The code compares with , so the loop takes no square roots and runs in exact rational arithmetic on rational data. Line L4 returns when the gradient is zero, which in exact arithmetic happens after at most steps. Lines L5 to L8 take the exact line search step along , and lines L9 to L11 build the next direction from the new gradient, with the factor that makes the directions -conjugate.
Compared with the textbook CG on , CGLS keeps and computes in line L9, instead of updating by . In exact arithmetic the two are equal. In floating point the CGLS form is more accurate, because it never forms , whose condition number is the square of that of .
Example
A trace. Take , , and the noise , so . With , . The iterates were computed in exact rational arithmetic and are rounded here.
| 0 | 2.4495 | 1.18896 | |
| 1 | 2.1007 | 0.45791 | |
| 2 | 1.7896 | 0.24458 | |
| 3 | 1.5720 | 0.11691 | |
| 4 | 1.1217 | 0.07137 | |
| 5 | 1.5109 | 0.01289 | |
| 6 | 1.8473 | 0 |
The residual decreases at every step and is after six steps, where (finite termination). The error decreases until and then increases: this is semi-convergence. Line L3 returns , the first iterate with a residual below . Each step "finishes" one more component: the first component is from on, which is plus the noise .
An integral operator. For the diagonal model of with 200 components, (the source condition with ) and Gaussian noise with seed 3, CGLS with gave (a measurement):
| stop at | error at the stop | best error (at ) | |
|---|---|---|---|
| 2 | 0.0206 | 0.0126 (3) | |
| 3 | 0.0080 | 0.0048 (4) | |
| 5 | 0.0026 | 0.00175 (7) | |
| 10 | 0.00071 | 0.00053 (13) |
Landweber needs hundreds to tens of thousands of steps for the same errors (see its page). The errors fall with slope about in , as the theory gives for .
Correctness
The full proof is in proofs/correctness.md, in exact arithmetic.
- CG on the normal equations (theorem). By induction, and hold after every step, and the iterates are those of CG for . On the range of , where all vectors stay, is positive definite, so the CG theorems apply.
- Residual minimization (theorem). minimizes over , so the residual does not increase.
- Finite termination (theorem). Line L4 returns after at most steps with .
- Growing norm (theorem). increases strictly until the end.
- Filter factors (theorem). with , where are the Ritz values of on the Krylov space. The filter depends on the data through the , so is not a linear function of .
- Discrepancy stop (theorem). If and , line L3 passes at the latest at the breakdown step.
That CGLS with the discrepancy principle is order optimal, with error under the source condition for every , is a theorem of Nemirovskii (1986); see EHN Chapter 7. It is cited, not proved here.
Proof: Correctness of CGLSfull
Exact arithmetic, finite dimension. is a real matrix of rank , , and , which is the orthogonal complement of . The values are those of the pseudocode after passes of the loop: , and (line L1), then lines L5 to L11. is the Krylov space . (For an operator between Hilbert spaces the same statements hold before breakdown, with the same proofs; see Engl, Hanke and Neubauer, Chapter 7.)
Step 1 (CGLS is CG on the normal equations). Put and . Then and for every , and the sequence is the sequence of the conjugate gradient method for from .
Proof. Induction on . At this is line L1. Assume it for . Line L8 gives by line L7. Line L9 gives , which is the residual update of CG for . Line L6 gives , the CG step length, and lines L10 and L11 are the CG updates and . Finally .
Step 2 (restriction to ). maps into , and is positive definite on : for we have , since , so . Since , all of , , and lie in . In an orthonormal basis of , restricted to is a symmetric positive definite matrix of order . So the theorem and corollaries of the conjugate gradient method apply to it. As long as are nonzero:
- the residuals are pairwise orthogonal, and , of dimension ;
- for , and for ;
- minimizes over , where solves ;
- some with is zero.
In particular the division at line L6 is safe: if , then and , so .
Theorem 1 (residual minimization). If , then minimizes over , and .
Proof. For , . The two parts are orthogonal: for every . So , and minimizing the residual over is minimizing over , which does by Step 2. The spaces are nested, , so the minimum does not increase.
Theorem 2 (finite termination). Line L4 returns after at most passes of the loop (if no earlier return happens), and then is a least squares solution. If (for example ), it is the minimum norm least squares solution .
Proof. By Step 2, some with is zero, so and line L4 returns. Then : solves the normal equations, so it is a least squares solution. If , then . The least squares solutions are , and the only one orthogonal to is .
Theorem 3 (the norm of the iterate grows). Let . Then for every with .
Proof. First, for before breakdown. Indeed , so , and by repeating this, , since every is positive before breakdown. Now with every , so and
Theorem 4 (the discrepancy test passes). Let , and , and run CGLS on with . Then line L3 returns some with , and every earlier iterate has a residual above .
Proof. If line L3 never returns before the breakdown of Theorem 2, then at breakdown is a least squares solution, so is the projection of onto . Since , this is the projection of , of norm at most . Line L3 comes before line L4 in the loop, so it returns at that at the latest. It tests the iterates in order of , which gives the last claim.
Theorem 5 (filter factors). Let , let be the SVD, and let . Let be the Ritz values of on , that is, the eigenvalues of for an orthonormal basis of . Then
Proof. Since , for a polynomial of degree less than , and with , a polynomial of degree at most with . In the SVD basis, and , so the coefficient of in is . It remains to show .
The residuals are pairwise orthogonal. In the eigenbasis of this says for , with the weights at the eigenvalues . So are orthogonal polynomials for a discrete measure with positive weights. Since , the polynomials of degree less than are not zero on the support, so the support has at least points. Then has exactly simple real roots, all in , which is a standard property of orthogonal polynomials. Write with these roots , which is possible because .
For each put and . Then , which is orthogonal to . So satisfies the Galerkin condition of a Ritz pair with Ritz value : with , . The polynomials are linearly independent (each vanishes at all roots but its own), and is one-to-one on the polynomials of degree less than because . So are independent eigenvectors of the matrix , with eigenvalues . These are all its eigenvalues: .
Complexity
- Per iteration (real-ram). Line L5 is one product with , line L9 one product with , and lines L6 to L11 cost for norms and vector updates. That is , or for a dense matrix. Line L1 costs one more product with .
- Iterations. Without noise, at most steps in exact arithmetic. With the discrepancy principle under the source condition, the stopping index is (a theorem, EHN Chapter 7), against for Landweber.
- Space. Four vectors of length and of length , plus : . The code also keeps every iterate for the tests, which takes ; a production version does not.
Properties
- Nonlinear in the data. The step lengths and the Ritz values depend on . Eicke, Louis and Plato (1990) showed that is not continuous for a fixed , so a stopping index fixed in advance does not give a regularization method. The stopping index must depend on the data, as with the discrepancy principle.
- Monotone curves. decreases and increases, the same shape as the curves of truncated SVD and Tikhonov regularization.
- Adaptive filter. The Ritz values converge first to the largest squared singular values (a property of the Lanczos algorithm, which CGLS runs implicitly on ), so CGLS filters like a truncated SVD whose cut adapts to the components that are present in the data.
- Optimal among Krylov methods. No other method with iterates in the same Krylov space has a smaller residual.
Variants and improvements
- LSQR. The same iterates in exact arithmetic, computed by Golub-Kahan bidiagonalization. It is the more common choice in floating point and gives the bidiagonal matrix for free.
- Hybrid Krylov methods. Apply Tikhonov regularization to the small projected problem at each step, so the result no longer depends strongly on the exact stopping index.
- CGME (Craig's method). CG on with . It minimizes the error over the same Krylov space , and needs a different stopping rule (EHN Chapter 7).
- Preconditioning. A right preconditioner changes the norm that is penalized, for example to a smoothness norm. A left preconditioner changes the residual norm and the meaning of the discrepancy test.
- Reorthogonalization. Keeping the vectors orthogonal in floating point delays the effects of rounding, at extra cost per step.
When to use it
CGLS is the standard first choice for a large ill-posed linear problem with a fast forward and adjoint code and a known noise level. It needs far fewer products than Landweber for the same error. Prefer LSQR when you also want the bidiagonal matrix, for hybrid methods or for estimates of the singular values. Prefer Landweber or a projected gradient method when you need constraints such as , or a stopping index that changes smoothly with the data. Without a reliable noise level, CGLS is fragile, because the error can increase fast after the best step; a hybrid method is then safer.
Pitfalls
- Updating from the normal equations. Writing line L9 as is the same in exact arithmetic, but writing CG for an explicit squares the condition number. Keep and compute as in line L9.
- Testing the wrong residual. The discrepancy test of line L3 uses , not . A test on has no relation to .
- A fixed number of steps. Choosing in advance, without line L3, is not a regularization method (Eicke, Louis and Plato). Use a stopping rule that looks at the data.
- Running past the stop. Because the error can grow fast after the best (in the integral example with , the error at is , twenty times the best error at ), a few extra steps can ruin the result. Use between and , and check line L3 at every step.
- A wrong adjoint at line L9. If the code for is not the adjoint of the code for , the directions lose conjugacy and the method can stall or diverge. Run an adjoint test first.
- Expecting exact termination. In floating point the vectors lose orthogonality, and the method may need more than steps to converge. For regularization this matters little, because the stop comes early.
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
# Part of https://algorithm.tamnd.com/cgls/. The authors are listed in prov/83ANX4.jsonl.
"""CGLS: the conjugate gradient method on the normal equations A^T A x = A^T y.
The iterate x_k minimizes ||y - A x|| over x0 + K_k(A^T A, A^T r_0), but the
method never forms A^T A. It needs one product with A and one with A^T per
step. The step count k is the regularization parameter; with a noise level
delta the discrepancy principle stops at the first k with
||y - A x_k|| <= tau delta.
The loop takes no square roots: the stop test compares squared norms. So the
code runs in exact Fraction arithmetic if the operator and the data are
Fractions, and then it gives the exact Krylov solutions.
"""
from typing import Any, Callable, List, Optional, Sequence
from imgla import matvec, rmatvec
Vector = List[Any]
Operator = Callable[[Sequence[Any]], Vector]
def _sq(v: Sequence[Any]) -> Any:
return sum(t * t for t in v)
class CGLSResult:
"""x: the last iterate; k: the number of steps done; iterates: x_0, ..., x_k;
res2: ||y - A x_j||^2 for j = 0, ..., k; stopped: "discrepancy", "breakdown"
(A^T r = 0, so x_k is a least squares solution) or "maxit"."""
def __init__(self, x: Vector, k: int, iterates: List[Vector], res2: List[Any], stopped: str) -> None:
self.x, self.k, self.iterates, self.res2, self.stopped = x, k, iterates, res2, stopped
def cgls(apply_a: Operator, apply_at: Operator, y: Sequence[Any], kmax: int,
x0: Optional[Sequence[Any]] = None, delta: Optional[Any] = None, tau: Any = 1.01,
n: Optional[int] = None) -> CGLSResult:
"""Run at most kmax CGLS steps from x0 (default 0).
Precondition: apply_at is the adjoint of apply_a. If delta is given, stop
at the first k with ||y - A x_k|| <= tau delta. n is the number of
unknowns; it is needed only when x0 is None and apply_at cannot tell it.
Cost: per step one product with A, one with A^T and O(m + n) more; the
iterates list takes O(k n) space.
"""
if x0 is None:
size = n if n is not None else len(apply_at([0 * t for t in y]))
x = [0 * y[0]] * size
else:
x = list(x0)
r = [yi - v for yi, v in zip(y, apply_a(x))]
s = apply_at(r)
p = list(s)
gamma = _sq(s) # @line L1
rr = _sq(r)
iterates, res2 = [list(x)], [rr]
for k in range(kmax): # @line L2
if delta is not None and rr <= (tau * delta) ** 2: # @line L3
return CGLSResult(x, k, iterates, res2, "discrepancy")
if gamma == 0: # @line L4
return CGLSResult(x, k, iterates, res2, "breakdown")
q = apply_a(p) # @line L5
alpha = gamma / _sq(q) # @line L6
x = [xi + alpha * pi for xi, pi in zip(x, p)] # @line L7
r = [ri - alpha * qi for ri, qi in zip(r, q)] # @line L8
s = apply_at(r) # @line L9
gamma_new = _sq(s)
beta = gamma_new / gamma # @line L10
gamma = gamma_new
p = [si + beta * pi for si, pi in zip(s, p)] # @line L11
rr = _sq(r)
iterates.append(list(x))
res2.append(rr)
if delta is not None and rr <= (tau * delta) ** 2:
return CGLSResult(x, kmax, iterates, res2, "discrepancy")
return CGLSResult(x, kmax, iterates, res2, "maxit") # @line L12
def cgls_matrix(a: List[List[float]], y: Sequence[float], kmax: int,
x0: Optional[Sequence[float]] = None, delta: Optional[float] = None,
tau: float = 1.01) -> CGLSResult:
"""CGLS for a dense matrix A (a list of rows of floats). Cost: O(m n) per step."""
return cgls(lambda x: matvec(a, x), lambda r: rmatvec(a, r), y, kmax,
x0=x0, delta=delta, tau=tau, n=len(a[0]))
def ritz_filter_factor(sigma: float, ritz: Sequence[float]) -> float:
"""The CGLS filter factor 1 - prod_j (1 - sigma^2 / theta_j) for x0 = 0.
ritz holds the k Ritz values theta_j of A^T A on K_k(A^T A, A^T y).
"""
f = 1.0
for theta in ritz:
f *= 1.0 - sigma * sigma / theta
return 1.0 - f
imgla.py 259 lines
# 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
test_cgls.py 210 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cgls/. The authors are listed in prov/83ANX4.jsonl.
import math
import random
import unittest
from fractions import Fraction
from cgls import cgls, cgls_matrix, ritz_filter_factor
from imgla import adjoint_gap, matmul, matvec, norm2, solve, svd, sym_eig, transpose
def exact_ops(a):
"""A x and A^T y in exact arithmetic (no float start value)."""
at = transpose(a)
return (lambda x: [sum(v * w for v, w in zip(row, x)) for row in a],
lambda y: [sum(v * w for v, w in zip(row, y)) for row in at])
def int_matrix(rng, m, n):
return [[Fraction(rng.randint(-4, 4)) for _ in range(n)] for _ in range(m)]
def krylov_solution(a, y, k):
"""Brute force: minimize ||y - A x|| over x in K_k(A^T A, A^T y), exactly."""
ap, atp = exact_ops(a)
basis = [atp(y)]
for _ in range(k - 1):
basis.append(atp(ap(basis[-1])))
ak = [ap(b) for b in basis]
gram = [[sum(p * q for p, q in zip(u, w)) for w in ak] for u in ak]
rhs = [sum(p * q for p, q in zip(u, y)) for u in ak]
c = solve(gram, rhs)
n = len(a[0])
return [sum(c[j] * basis[j][i] for j in range(k)) for i in range(n)]
class TestCGLS(unittest.TestCase):
def test_iterates_minimize_over_krylov_space(self):
rng = random.Random(21)
a = int_matrix(rng, 7, 4)
y = [Fraction(rng.randint(-5, 5)) for _ in range(7)]
ap, atp = exact_ops(a)
res = cgls(ap, atp, y, 4)
for k in range(1, 5):
self.assertEqual(res.iterates[k], krylov_solution(a, y, k))
def test_page_example(self):
# A = diag(1, 1/2, ..., 1/32), x^dagger = ones, noise +-1/20, tau = 3/2.
d = [Fraction(1, 2 ** j) for j in range(6)]
e = [Fraction(1, 20) * s for s in (1, -1, 1, -1, 1, -1)]
y = [a + b for a, b in zip(d, e)]
def op(x):
return [a * b for a, b in zip(d, x)]
res = cgls(op, op, y, 6)
errs = [math.sqrt(sum((float(v) - 1.0) ** 2 for v in x)) for x in res.iterates]
self.assertEqual(min(range(7), key=lambda k: errs[k]), 4)
self.assertAlmostEqual(errs[4], 1.1217, places=4)
self.assertEqual(res.iterates[6], [b / a for a, b in zip(d, y)])
self.assertEqual(res.res2[6], 0)
delta2 = sum(t * t for t in e)
stop = cgls(op, op, y, 6, delta=math.sqrt(delta2), tau=1.5)
self.assertEqual((stop.k, stop.stopped), (3, "discrepancy"))
first = next(k for k, r2 in enumerate(res.res2) if r2 <= Fraction(9, 4) * delta2)
self.assertEqual(first, 3)
def test_finite_termination(self):
rng = random.Random(22)
a = int_matrix(rng, 6, 4)
y = [Fraction(rng.randint(-5, 5)) for _ in range(6)]
ap, atp = exact_ops(a)
res = cgls(ap, atp, y, 10)
self.assertEqual(res.stopped, "breakdown")
self.assertLessEqual(res.k, 4)
ata = matmul(transpose(a), a)
self.assertEqual(res.x, solve(ata, atp(y)))
def test_rank_deficient_gives_minimum_norm_solution(self):
rng = random.Random(23)
b = int_matrix(rng, 6, 2)
c = int_matrix(rng, 2, 5)
a = matmul(b, c)
y = [Fraction(rng.randint(-5, 5)) for _ in range(6)]
ap, atp = exact_ops(a)
res = cgls(ap, atp, y, 10)
self.assertEqual(res.stopped, "breakdown")
self.assertEqual(res.k, 2)
self.assertTrue(all(t == 0 for t in atp([p - q for p, q in zip(y, ap(res.x))])))
u, s, v = svd([[float(t) for t in row] for row in a])
ref = [0.0] * 5
for i in range(2):
coef = sum(u[r][i] * float(y[r]) for r in range(6)) / s[i]
ref = [rj + coef * v[j][i] for j, rj in enumerate(ref)]
for p, q in zip(res.x, ref):
self.assertAlmostEqual(float(p), q, places=9)
def test_monotone_quantities(self):
rng = random.Random(24)
a = int_matrix(rng, 8, 5)
y = [Fraction(rng.randint(-5, 5)) for _ in range(8)]
ap, atp = exact_ops(a)
res = cgls(ap, atp, y, 5)
xls = res.x if res.stopped == "breakdown" else solve(matmul(transpose(a), a), atp(y))
xn = [sum(t * t for t in x) for x in res.iterates]
en = [sum((p - q) ** 2 for p, q in zip(x, xls)) for x in res.iterates]
for j in range(len(res.iterates) - 1):
self.assertLessEqual(res.res2[j + 1], res.res2[j])
self.assertGreaterEqual(xn[j + 1], xn[j])
self.assertLessEqual(en[j + 1], en[j])
def test_ritz_filter_factors(self):
rng = random.Random(25)
a = [[rng.uniform(-1.0, 1.0) for _ in range(5)] for _ in range(9)]
y = [rng.gauss(0.0, 1.0) for _ in range(9)]
u, s, v = svd(a)
ata = matmul(transpose(a), a)
for k in (1, 2, 3):
x = cgls_matrix(a, y, k).x
# Orthonormal basis of K_k(A^T A, A^T y) by Gram-Schmidt, twice.
q, w = [], [sum(a[r][j] * y[r] for r in range(9)) for j in range(5)]
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])
t = [[sum(qi[r] * sum(ata[r][c] * qj[c] for c in range(5)) for r in range(5))
for qj in q] for qi in q]
ritz, _ = sym_eig(t)
ref = [0.0] * 5
for i, si in enumerate(s):
coef = ritz_filter_factor(si, ritz) * sum(u[r][i] * y[r] for r in range(9)) / si
ref = [rj + coef * v[j][i] for j, rj in enumerate(ref)]
for p, r in zip(x, ref):
self.assertAlmostEqual(p, r, places=8)
def test_discrepancy_stop(self):
rng = random.Random(26)
a = [[rng.uniform(-1.0, 1.0) for _ in range(6)] for _ in range(12)]
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 = cgls_matrix(a, y, 50, delta=delta, tau=tau)
self.assertEqual(res.stopped, "discrepancy")
self.assertLessEqual(res.res2[-1], (tau * delta) ** 2)
for r in res.res2[:-1]:
self.assertGreater(r, (tau * delta) ** 2)
def test_matrix_free_operator(self):
n = 40
h = 1.0 / n
rng = random.Random(27)
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)]
# Few steps: the two versions round differently, and late CG steps on an
# ill-conditioned operator amplify rounding differences.
free = cgls(op, opt, z, 4).x
dense = cgls_matrix(a, z, 4).x
gap = norm2([p - q for p, q in zip(free, dense)])
self.assertLess(gap, 1e-8 * norm2(dense))
def test_discrepancy_rule_on_integration_operator(self):
# Diagonal model of (A x)(s) = int_0^s x; x^dagger = 1 - t, so nu = 1/2.
n = 200
sig = [2.0 / ((2 * k - 1) * math.pi) for k in range(1, n + 1)]
xd = [math.sqrt(2.0) * t * t for t in sig]
y = [t * x for t, x in zip(sig, xd)]
def op(x):
return [t * v for t, v in zip(sig, x)]
rng = random.Random(3)
e = [rng.gauss(0.0, 1.0) for _ in range(n)]
ne = norm2(e)
errs, deltas = [], [1e-2, 1e-5]
for delta in deltas:
yd = [p + delta * q / ne for p, q in zip(y, e)]
res = cgls(op, op, yd, 60)
all_errs = [norm2([p - q for p, q in zip(x, xd)]) for x in res.iterates]
k = next(j for j, r in enumerate(res.res2) if r <= (1.5 * delta) ** 2)
self.assertLessEqual(all_errs[k], 2.0 * min(all_errs))
errs.append(all_errs[k])
slope = math.log(errs[0] / errs[1]) / math.log(deltas[0] / deltas[1])
self.assertLess(abs(slope - 0.5), 0.15)
if __name__ == "__main__":
unittest.main()
History
Hestenes and Stiefel introduced the conjugate gradient method in 1952, and their paper already gives a form for least squares problems that never forms . Its use for ill-posed problems grew in the 1970s and 1980s. Nemirovskii (1986) proved that it is an order optimal regularization method when it is stopped by the discrepancy principle, and Eicke, Louis and Plato (1990) showed that a stopping index fixed in advance does not give a regularization method. Hanke's 1995 monograph and Chapter 7 of Engl, Hanke and Neubauer (1996) give the full theory. Paige and Saunders (1982) gave LSQR, which computes the same iterates with better behavior in floating point.
References
- Magnus R. Hestenes and Eduard Stiefel, Methods of conjugate gradients for solving linear systems, Journal of Research of the National Bureau of Standards 49(6), 1952, 409 to 436, the conjugate gradient method and its variant for least squares problems
- A. S. Nemirovskii, The regularizing properties of the adjoint gradient method in ill-posed problems, USSR Computational Mathematics and Mathematical Physics 26(2), 1986, 7 to 16, order optimality of the conjugate gradient method with the discrepancy principle
- B. Eicke, A. K. Louis and R. Plato, The instability of some gradient methods for ill-posed problems, Numerische Mathematik 58(1), 1990, 129 to 134, the conjugate gradient iterates do not depend continuously on the data, so an a priori stopping index does not give a regularization method
- Heinz W. Engl, Martin Hanke and Andreas Neubauer, Regularization of Inverse Problems, Kluwer, 1996, Chapter 7 (the conjugate gradient method as a regularization method)
- Per Christian Hansen, Rank-Deficient and Discrete Ill-Posed Problems, SIAM, 1998, Sections 6.3 and 6.4 (regularizing CG iterations and their convergence properties)
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 83ANX4 Edit this page History Report an error Markdown