Algorithm Search⌘K

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
Properties
deterministicfinite terminationiterativenot linear in datamatrix free
Origin
Magnus R. Hestenes, Eduard Stiefel, 1952

CGLS is the conjugate gradient method applied to the normal equations A∗Ax=A∗yA^* A x = A^* y, written so that it never forms A∗AA^* A. Each step costs one product with AA and one with the adjoint A∗A^*, the same as one Landweber step. The iterate xkx_k minimizes the residual ∥y−Ax∥\|y - A x\| over the Krylov subspace Kk(A∗A,A∗y)\mathcal{K}_k(A^* A, A^* y). For a well-posed least squares problem this is a fast solver. For an ill-posed problem with noisy data yδy^\delta, ∥yδ−y∥≤δ\|y^\delta - y\| \le \delta, the first iterates capture the dominant singular components and later ones fit the noise, so the iteration count kk 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 A:X→YA: X \to Y (an m×nm \times n matrix, or an operator given by the functions x↦Axx \mapsto A x and r↦A∗rr \mapsto A^* r), data yδy^\delta with ∥yδ−Ax†∥≤δ\|y^\delta - A x^\dagger\| \le \delta, and δ\delta, find an approximation of the minimum norm solution x†=A†yx^\dagger = A^\dagger y whose error goes to 00 with δ\delta. Without noise and with kk large enough, CGLS solves the least squares problem min⁡x∥y−Ax∥\min_x \|y - A x\|.

The algorithm

  1. CGLS(A, y, K, δ, τ) ▷ τ > 1
  2. 1x ← 0; r ← y; s ← A* r; p ← s; γ ← ‖s‖²
  3. 2for k ← 0 to K - 1 do
  4. 3if ‖r‖ ≤ τ δ then return (x, k)
  5. 4if γ = 0 then return (x, k) ▷ A* r = 0: least squares solution
  6. 5q ← A p
  7. 6α ← γ / ‖q‖²
  8. 7x ← x + α p
  9. 8r ← r - α q
  10. 9s ← A* r
  11. 10β ← ‖s‖² / γ; γ ← ‖s‖²
  12. 11p ← s + β p
  13. 12return (x, K)

The vector rr is the residual y−Axy - A x, and s=A∗rs = A^* r is the residual of the normal equations, that is, minus the gradient of 12∥y−Ax∥2\frac12\|y - A x\|^2. Line L1 starts at x=0x = 0. Line L3 is the discrepancy principle, which returns the first iterate whose residual is at the noise level. The code compares ∥r∥2\|r\|^2 with (τδ)2(\tau\delta)^2, 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 rank⁡(A)\operatorname{rank}(A) steps. Lines L5 to L8 take the exact line search step along pp, and lines L9 to L11 build the next direction from the new gradient, with the factor β\beta that makes the directions A∗AA^* A-conjugate.

Compared with the textbook CG on A∗Ax=A∗yA^* A x = A^* y, CGLS keeps rr and computes s=A∗rs = A^* r in line L9, instead of updating ss by s−αA∗Aps - \alpha A^* A p. In exact arithmetic the two are equal. In floating point the CGLS form is more accurate, because it never forms A∗AA^* A, whose condition number is the square of that of AA.

Example

A trace. Take A=diag(1,12,14,18,116,132)A = \mathrm{diag}(1, \frac12, \frac14, \frac18, \frac1{16}, \frac1{32}), x†=(1,1,1,1,1,1)x^\dagger = (1, 1, 1, 1, 1, 1), and the noise e=120(1,−1,1,−1,1,−1)e = \frac1{20}(1, -1, 1, -1, 1, -1), so δ=∥e∥=0.12247\delta = \|e\| = 0.12247. With τ=1.5\tau = 1.5, τδ=0.18371\tau\delta = 0.18371. The iterates were computed in exact rational arithmetic and are rounded here.

kk xkx_k ∥xk−x†∥\|x_k - x^\dagger\| ∥yδ−Axk∥\|y^\delta - A x_k\|
0 (0,0,0,0,0,0)(0, 0, 0, 0, 0, 0) 2.4495 1.18896
1 (1.0908,0.2337,0.0779,0.0097,0.0073,−0.0006)(1.0908, 0.2337, 0.0779, 0.0097, 0.0073, -0.0006) 2.1007 0.45791
2 (1.0491,0.9871,0.3926,0.0511,0.0387,−0.0032)(1.0491, 0.9871, 0.3926, 0.0511, 0.0387, -0.0032) 1.7896 0.24458
3 (1.05,0.8993,1.2304,0.1897,0.1493,−0.0126)(1.05, 0.8993, 1.2304, 0.1897, 0.1493, -0.0126) 1.5720 0.11691
4 (1.05,0.9,1.1979,0.8499,0.8081,−0.0711)(1.05, 0.9, 1.1979, 0.8499, 0.8081, -0.0711) 1.1217 0.07137
5 (1.05,0.9,1.2,0.5994,1.8114,−0.1880)(1.05, 0.9, 1.2, 0.5994, 1.8114, -0.1880) 1.5109 0.01289
6 (1.05,0.9,1.2,0.6,1.8,−0.6)(1.05, 0.9, 1.2, 0.6, 1.8, -0.6) 1.8473 0

The residual decreases at every step and is 00 after six steps, where x6=A−1yδx_6 = A^{-1} y^\delta (finite termination). The error decreases until k=4k = 4 and then increases: this is semi-convergence. Line L3 returns k=3k = 3, the first iterate with a residual below 0.183710.18371. Each step "finishes" one more component: the first component is 1.051.05 from k=3k = 3 on, which is x1†x^\dagger_1 plus the noise 0.05/σ10.05/\sigma_1.

An integral operator. For the diagonal model of (Ax)(s)=∫0sx(t) dt(A x)(s) = \int_0^s x(t)\,dt with 200 components, x†=1−tx^\dagger = 1 - t (the source condition with ν=12\nu = \frac12) and Gaussian noise with seed 3, CGLS with τ=1.5\tau = 1.5 gave (a measurement):

δ\delta stop at kk error at the stop best error (at kk)
10−210^{-2} 2 0.0206 0.0126 (3)
10−310^{-3} 3 0.0080 0.0048 (4)
10−410^{-4} 5 0.0026 0.00175 (7)
10−510^{-5} 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 0.50.5 in log⁡δ\log\delta, as the theory gives for ν=12\nu = \frac12.

Correctness

The full proof is in proofs/correctness.md, in exact arithmetic.

  • CG on the normal equations (theorem). By induction, r=y−Axr = y - A x and s=A∗rs = A^* r hold after every step, and the iterates are those of CG for A∗Az=A∗yA^* A z = A^* y. On the range of A∗A^*, where all vectors stay, A∗AA^* A is positive definite, so the CG theorems apply.
  • Residual minimization (theorem). xkx_k minimizes ∥y−Ax∥\|y - A x\| over Kk(A∗A,A∗y)\mathcal{K}_k(A^* A, A^* y), so the residual does not increase.
  • Finite termination (theorem). Line L4 returns after at most rank⁡(A)\operatorname{rank}(A) steps with x=A†yx = A^\dagger y.
  • Growing norm (theorem). ∥xk∥\|x_k\| increases strictly until the end.
  • Filter factors (theorem). xk=∑ifi(k)(uiTy/σi)vix_k = \sum_i f_i^{(k)} (u_i^T y/\sigma_i) v_i with fi(k)=1−∏j=1k(1−σi2/θj)f_i^{(k)} = 1 - \prod_{j=1}^k (1 - \sigma_i^2/\theta_j), where θj\theta_j are the Ritz values of A∗AA^* A on the Krylov space. The filter depends on the data through the θj\theta_j, so xkx_k is not a linear function of yy.
  • Discrepancy stop (theorem). If y∈range⁡(A)y \in \operatorname{range}(A) and τ>1\tau > 1, line L3 passes at the latest at the breakdown step.

That CGLS with the discrepancy principle is order optimal, with error O(δ2ν/(2ν+1))O(\delta^{2\nu/(2\nu+1)}) under the source condition x†=(A∗A)νwx^\dagger = (A^* A)^\nu w for every ν>0\nu > 0, is a theorem of Nemirovskii (1986); see EHN Chapter 7. It is cited, not proved here.

Proof: Correctness of CGLSfull

Exact arithmetic, finite dimension. AA is a real m×nm \times n matrix of rank r≥1r \ge 1, M=ATAM = A^T A, and N=range⁡(AT)N = \operatorname{range}(A^T), which is the orthogonal complement of null⁡(A)\operatorname{null}(A). The values xk,rk,sk,pk,γk,αk,βkx_k, r_k, s_k, p_k, \gamma_k, \alpha_k, \beta_k are those of the pseudocode after kk passes of the loop: r0=y−Ax0r_0 = y - A x_0, s0=p0=ATr0s_0 = p_0 = A^T r_0 and γ0=∥s0∥2\gamma_0 = \|s_0\|^2 (line L1), then lines L5 to L11. Kk=span⁡{s0,Ms0,…,Mk−1s0}\mathcal{K}_k = \operatorname{span}\{s_0, M s_0, \ldots, M^{k-1} s_0\} is the Krylov space Kk(ATA,ATr0)\mathcal{K}_k(A^T A, A^T r_0). (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 zk=xk−x0z_k = x_k - x_0 and b=s0=ATr0b = s_0 = A^T r_0. Then rk=y−Axkr_k = y - A x_k and sk=ATrk=b−Mzks_k = A^T r_k = b - M z_k for every kk, and the sequence (zk,sk,pk)(z_k, s_k, p_k) is the sequence of the conjugate gradient method for Mz=bM z = b from z0=0z_0 = 0.

Proof. Induction on kk. At k=0k = 0 this is line L1. Assume it for kk. Line L8 gives rk+1=rk−αkApk=y−Axk−αkApk=y−Axk+1r_{k+1} = r_k - \alpha_k A p_k = y - A x_k - \alpha_k A p_k = y - A x_{k+1} by line L7. Line L9 gives sk+1=ATrk+1=sk−αkMpks_{k+1} = A^T r_{k+1} = s_k - \alpha_k M p_k, which is the residual update of CG for Mz=bM z = b. Line L6 gives αk=γk/∥Apk∥2=∥sk∥2/(pkTMpk)\alpha_k = \gamma_k/\|A p_k\|^2 = \|s_k\|^2/(p_k^T M p_k), the CG step length, and lines L10 and L11 are the CG updates βk=∥sk+1∥2/∥sk∥2\beta_k = \|s_{k+1}\|^2/\|s_k\|^2 and pk+1=sk+1+βkpkp_{k+1} = s_{k+1} + \beta_k p_k. Finally b−Mzk+1=ATr0−ATA(xk+1−x0)=AT(y−Axk+1)=sk+1b - M z_{k+1} = A^T r_0 - A^T A (x_{k+1} - x_0) = A^T (y - A x_{k+1}) = s_{k+1}. □\square

Step 2 (restriction to NN). MM maps NN into NN, and MM is positive definite on NN: for 0≠z∈N0 \ne z \in N we have Az≠0A z \ne 0, since N∩null⁡(A)={0}N \cap \operatorname{null}(A) = \{0\}, so zTMz=∥Az∥2>0z^T M z = \|A z\|^2 > 0. Since b=ATr0∈Nb = A^T r_0 \in N, all of sks_k, pkp_k, zkz_k and Kk\mathcal{K}_k lie in NN. In an orthonormal basis of NN, MM restricted to NN is a symmetric positive definite matrix of order rr. So the theorem and corollaries of the conjugate gradient method apply to it. As long as s0,…,sk−1s_0, \ldots, s_{k-1} are nonzero:

  • the residuals s0,…,sks_0, \ldots, s_k are pairwise orthogonal, and span⁡{s0,…,sk−1}=span⁡{p0,…,pk−1}=Kk\operatorname{span}\{s_0, \ldots, s_{k-1}\} = \operatorname{span}\{p_0, \ldots, p_{k-1}\} = \mathcal{K}_k, of dimension kk;
  • pjTMpi=0p_j^T M p_i = 0 for i≠ji \ne j, and pj≠0p_j \ne 0 for j<kj < k;
  • zkz_k minimizes ∥z−z∗∥M=∥A(z−z∗)∥\|z - z^*\|_M = \|A(z - z^*)\| over z∈Kkz \in \mathcal{K}_k, where z∗∈Nz^* \in N solves Mz∗=bM z^* = b;
  • some sks_k with k≤rk \le r is zero.

In particular the division at line L6 is safe: if γk≠0\gamma_k \ne 0, then pk≠0p_k \ne 0 and pk∈Np_k \in N, so ∥Apk∥>0\|A p_k\| > 0.

Theorem 1 (residual minimization). If s0,…,sk−1≠0s_0, \ldots, s_{k-1} \ne 0, then xkx_k minimizes ∥y−Ax∥\|y - A x\| over x∈x0+Kkx \in x_0 + \mathcal{K}_k, and ∥y−Axk+1∥≤∥y−Axk∥\|y - A x_{k+1}\| \le \|y - A x_k\|.

Proof. For x=x0+zx = x_0 + z, y−Ax=(r0−Az∗)+A(z∗−z)y - A x = (r_0 - A z^*) + A(z^* - z). The two parts are orthogonal: ⟨r0−Az∗,Aw⟩=⟨ATr0−Mz∗,w⟩=⟨b−Mz∗,w⟩=0\langle r_0 - A z^*, A w\rangle = \langle A^T r_0 - M z^*, w\rangle = \langle b - M z^*, w\rangle = 0 for every ww. So ∥y−Ax∥2=∥r0−Az∗∥2+∥A(z−z∗)∥2\|y - A x\|^2 = \|r_0 - A z^*\|^2 + \|A(z - z^*)\|^2, and minimizing the residual over x0+Kkx_0 + \mathcal{K}_k is minimizing ∥z−z∗∥M\|z - z^*\|_M over Kk\mathcal{K}_k, which zkz_k does by Step 2. The spaces are nested, Kk⊆Kk+1\mathcal{K}_k \subseteq \mathcal{K}_{k+1}, so the minimum does not increase. □\square

Theorem 2 (finite termination). Line L4 returns after at most rr passes of the loop (if no earlier return happens), and then xkx_k is a least squares solution. If x0∈Nx_0 \in N (for example x0=0x_0 = 0), it is the minimum norm least squares solution A†yA^\dagger y.

Proof. By Step 2, some sks_k with k≤rk \le r is zero, so γk=0\gamma_k = 0 and line L4 returns. Then AT(y−Axk)=sk=0A^T(y - A x_k) = s_k = 0: xkx_k solves the normal equations, so it is a least squares solution. If x0∈Nx_0 \in N, then xk=x0+zk∈N=null⁡(A)⊥x_k = x_0 + z_k \in N = \operatorname{null}(A)^\perp. The least squares solutions are A†y+null⁡(A)A^\dagger y + \operatorname{null}(A), and the only one orthogonal to null⁡(A)\operatorname{null}(A) is A†yA^\dagger y. □\square

Theorem 3 (the norm of the iterate grows). Let x0=0x_0 = 0. Then ∥xk+1∥>∥xk∥\|x_{k+1}\| > \|x_k\| for every kk with sk≠0s_k \ne 0.

Proof. First, ⟨pi,pj⟩>0\langle p_i, p_j\rangle > 0 for j<ij < i before breakdown. Indeed si⊥Ki∋pjs_i \perp \mathcal{K}_i \ni p_j, so ⟨pi,pj⟩=⟨si+βi−1pi−1,pj⟩=βi−1⟨pi−1,pj⟩\langle p_i, p_j\rangle = \langle s_i + \beta_{i-1} p_{i-1}, p_j\rangle = \beta_{i-1}\langle p_{i-1}, p_j\rangle, and by repeating this, ⟨pi,pj⟩=βi−1⋯βj∥pj∥2>0\langle p_i, p_j\rangle = \beta_{i-1} \cdots \beta_j \|p_j\|^2 > 0, since every β\beta is positive before breakdown. Now xk=∑j<kαjpjx_k = \sum_{j<k} \alpha_j p_j with every αj>0\alpha_j > 0, so ⟨xk,pk⟩≥0\langle x_k, p_k\rangle \ge 0 and

∥xk+1∥2=∥xk∥2+2αk⟨xk,pk⟩+αk2∥pk∥2>∥xk∥2.□\|x_{k+1}\|^2 = \|x_k\|^2 + 2\alpha_k\langle x_k, p_k\rangle + \alpha_k^2\|p_k\|^2 > \|x_k\|^2. \qquad \square

Theorem 4 (the discrepancy test passes). Let y=Ax†y = A x^\dagger, ∥yδ−y∥≤δ\|y^\delta - y\| \le \delta and τ>1\tau > 1, and run CGLS on yδy^\delta with K≥rK \ge r. Then line L3 returns some xkx_k with ∥yδ−Axk∥≤τδ\|y^\delta - A x_k\| \le \tau\delta, and every earlier iterate has a residual above τδ\tau\delta.

Proof. If line L3 never returns before the breakdown of Theorem 2, then at breakdown xkx_k is a least squares solution, so yδ−Axky^\delta - A x_k is the projection of yδy^\delta onto range⁡(A)⊥\operatorname{range}(A)^\perp. Since y∈range⁡(A)y \in \operatorname{range}(A), this is the projection of yδ−yy^\delta - y, of norm at most δ<τδ\delta < \tau\delta. Line L3 comes before line L4 in the loop, so it returns at that kk at the latest. It tests the iterates in order of kk, which gives the last claim. □\square

Theorem 5 (filter factors). Let x0=0x_0 = 0, let A=∑iσiuiviTA = \sum_i \sigma_i u_i v_i^T be the SVD, and let s0,…,sk−1≠0s_0, \ldots, s_{k-1} \ne 0. Let θ1,…,θk\theta_1, \ldots, \theta_k be the Ritz values of MM on Kk\mathcal{K}_k, that is, the eigenvalues of QTMQQ^T M Q for an orthonormal basis QQ of Kk\mathcal{K}_k. Then

xk=∑i=1rfi(k)uiTyσivi,fi(k)=1−∏j=1k(1−σi2θj).x_k = \sum_{i=1}^{r} f_i^{(k)} \frac{u_i^T y}{\sigma_i} v_i, \qquad f_i^{(k)} = 1 - \prod_{j=1}^{k}\Big(1 - \frac{\sigma_i^2}{\theta_j}\Big).

Proof. Since xk∈Kkx_k \in \mathcal{K}_k, xk=q(M)bx_k = q(M) b for a polynomial qq of degree less than kk, and sk=b−Mxk=R(M)bs_k = b - M x_k = R(M) b with R(λ)=1−λq(λ)R(\lambda) = 1 - \lambda q(\lambda), a polynomial of degree at most kk with R(0)=1R(0) = 1. In the SVD basis, b=ATy=∑iσi(uiTy)vib = A^T y = \sum_i \sigma_i (u_i^T y) v_i and Mvi=σi2viM v_i = \sigma_i^2 v_i, so the coefficient of viv_i in xkx_k is q(σi2)σi(uiTy)=(1−R(σi2))(uiTy)/σiq(\sigma_i^2)\sigma_i (u_i^T y) = (1 - R(\sigma_i^2)) (u_i^T y)/\sigma_i. It remains to show R(λ)=∏j(1−λ/θj)R(\lambda) = \prod_j (1 - \lambda/\theta_j).

The residuals sj=Rj(M)bs_j = R_j(M) b are pairwise orthogonal. In the eigenbasis of MM this says ∑iRj(λi)Rl(λi)wi=0\sum_i R_j(\lambda_i) R_l(\lambda_i) w_i = 0 for j≠lj \ne l, with the weights wi=∣viTb∣2≥0w_i = |v_i^T b|^2 \ge 0 at the eigenvalues λi=σi2\lambda_i = \sigma_i^2. So R0,…,RkR_0, \ldots, R_k are orthogonal polynomials for a discrete measure with positive weights. Since dim⁡Kk=k\dim \mathcal{K}_k = k, the polynomials of degree less than kk are not zero on the support, so the support has at least kk points. Then R=RkR = R_k has exactly kk simple real roots, all in (0,∥A∥2](0, \|A\|^2], which is a standard property of orthogonal polynomials. Write R(λ)=∏j(1−λ/μj)R(\lambda) = \prod_j (1 - \lambda/\mu_j) with these roots μj\mu_j, which is possible because R(0)=1R(0) = 1.

For each jj put gj(λ)=∏l≠j(1−λ/μl)g_j(\lambda) = \prod_{l \ne j}(1 - \lambda/\mu_l) and wj=gj(M)b∈Kkw_j = g_j(M) b \in \mathcal{K}_k. Then (M−μjI)wj=−μjR(M)b=−μjsk(M - \mu_j I) w_j = -\mu_j R(M) b = -\mu_j s_k, which is orthogonal to Kk\mathcal{K}_k. So wjw_j satisfies the Galerkin condition of a Ritz pair with Ritz value μj\mu_j: with wj=Qcjw_j = Q c_j, (QTMQ−μjI)cj=0(Q^T M Q - \mu_j I) c_j = 0. The kk polynomials gjg_j are linearly independent (each vanishes at all roots but its own), and p↦p(M)bp \mapsto p(M) b is one-to-one on the polynomials of degree less than kk because dim⁡Kk=k\dim \mathcal{K}_k = k. So c1,…,ckc_1, \ldots, c_k are kk independent eigenvectors of the k×kk \times k matrix QTMQQ^T M Q, with eigenvalues μ1,…,μk\mu_1, \ldots, \mu_k. These are all its eigenvalues: {μj}={θj}\{\mu_j\} = \{\theta_j\}. ■\blacksquare

Complexity

  • Per iteration (real-ram). Line L5 is one product with AA, line L9 one product with A∗A^*, and lines L6 to L11 cost O(m+n)O(m + n) for norms and vector updates. That is O(a+m+n)O(a + m + n), or O(mn)O(m n) for a dense matrix. Line L1 costs one more product with A∗A^*.
  • Iterations. Without noise, at most r=rank⁡(A)r = \operatorname{rank}(A) steps in exact arithmetic. With the discrepancy principle under the source condition, the stopping index is O(δ−1/(2ν+1))O(\delta^{-1/(2\nu+1)}) (a theorem, EHN Chapter 7), against O(δ−2/(2ν+1))O(\delta^{-2/(2\nu+1)}) for Landweber.
  • Space. Four vectors x,px, p of length nn and r,qr, q of length mm, plus ss: O(m+n)O(m + n). The code also keeps every iterate for the tests, which takes O(kn)O(k n); a production version does not.

Properties

  • Nonlinear in the data. The step lengths and the Ritz values depend on yy. Eicke, Louis and Plato (1990) showed that y↦xky \mapsto x_k is not continuous for a fixed kk, 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. ∥y−Axk∥\|y - A x_k\| decreases and ∥xk∥\|x_k\| 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 A∗AA^* A), 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 AA∗z=yA A^* z = y with x=A∗zx = A^* z. It minimizes the error ∥x−x†∥\|x - x^\dagger\| over the same Krylov space Kk(A∗A,A∗y)\mathcal{K}_k(A^* A, A^* y), and needs a different stopping rule (EHN Chapter 7).
  • Preconditioning. A right preconditioner x=L−1ξx = L^{-1}\xi 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 sks_k orthogonal in floating point delays the effects of rounding, at O(kn)O(k n) 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 x≥0x \ge 0, 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 ss from the normal equations. Writing line L9 as s←s−αA∗qs \leftarrow s - \alpha A^* q is the same in exact arithmetic, but writing CG for an explicit A∗AA^* A squares the condition number. Keep rr and compute s=A∗rs = A^* r as in line L9.
  • Testing the wrong residual. The discrepancy test of line L3 uses ∥y−Ax∥\|y - A x\|, not ∥s∥=∥A∗(y−Ax)∥\|s\| = \|A^* (y - A x)\|. A test on ∥s∥\|s\| has no relation to δ\delta.
  • A fixed number of steps. Choosing KK 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 kk (in the integral example with δ=10−2\delta = 10^{-2}, the error at k=6k = 6 is 0.26270.2627, twenty times the best error 0.01260.0126 at k=3k = 3), a few extra steps can ruin the result. Use τ\tau between 1.011.01 and 22, and check line L3 at every step.
  • A wrong adjoint at line L9. If the code for A∗A^* is not the adjoint of the code for AA, the directions lose conjugacy and the method can stall or diverge. Run an adjoint test first.
  • Expecting exact termination. In floating point the vectors sks_k lose orthogonality, and the method may need more than rank⁡(A)\operatorname{rank}(A) 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.

cgls.pyI0RawGitHub
# 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 ATAA^T A. 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

  1. 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
  2. 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
  3. 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
  4. Heinz W. Engl, Martin Hanke and Andreas Neubauer, Regularization of Inverse Problems, Kluwer, 1996, Chapter 7 (the conjugate gradient method as a regularization method)
  5. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.dense
  • a full proof of time.per_iteration
  • a full proof of time.total
  • a full proof of space.extra
  • a full proof of iterations.exact_termination
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example