Algorithm Search⌘K

Algorithmcore

Truncated singular value decomposition

Also called TSVD, truncated SVD.

Regularize A x = y by keeping the k largest singular components of the pseudoinverse solution and dropping the rest. Choose k from the noise level, for example by the discrepancy principle.

Time
O(m n^2 + k (m + n)) worst
Space
O(m n) extra
Where
k = the truncation index; m = the number of rows of A; n = the number of columns of A with m >= n
Properties
deterministicdirectnot iterativelinear in data
Origin
Per Christian Hansen, 1987

The truncated singular value decomposition (TSVD) solves an ill-conditioned linear system Ax=yA x = y by keeping the kk largest singular components of the pseudoinverse solution and dropping the rest: xk=∑i=1kuiTyσivix_k = \sum_{i=1}^{k} \frac{u_i^T y}{\sigma_i} v_i. Dropping the components with small σi\sigma_i removes the ones that amplify noise most, at the cost of a bias, and the index kk is the regularization parameter. It costs one SVD, O(mn2)O(m n^2) for m≥nm \ge n, after which each xkx_k costs O(k(m+n))O(k(m + n)) and all residual norms together O(mn)O(m n). It is the simplest regularization method and the sharp-cutoff case of spectral filter factors; Tikhonov regularization is the smooth-cutoff case, and on discrete ill-posed problems the two give solutions of similar quality.

In plain words

The SVD splits a matrix into independent channels, each with a gain. Solving the system means dividing the data in each channel by its gain. The channels with tiny gains are the trouble: the true signal in them is tiny too, so what you measure there is mostly noise, and dividing by a tiny gain makes that noise huge. The truncated method simply ignores those channels. You keep the strong channels, where the signal is well above the noise, and set the rest of the answer to zero. The number of channels you keep is the one knob. A good rule is to keep adding channels until the solution explains the data about as well as the noise level allows, and then stop.

The problem

Given an m×nm \times n real matrix AA, data yδ∈Rmy^\delta \in \mathbb{R}^m with yδ=Axtrue+ey^\delta = A x^{\mathrm{true}} + e, and either a noise bound ∥e∥2≤δ\|e\|_2 \le \delta or a target rank, find an approximation of the minimum norm solution x†=A†yx^\dagger = A^\dagger y of the noise-free problem that is stable against ee. Typically AA is the discretization of a compact operator, such as a Fredholm integral equation of the first kind, and its singular values decay with no gap. The same algorithm also computes the minimum norm least squares solution of a rank-deficient system when kk equals the numerical rank.

The algorithm

Write the thin SVD as A=UΣVT=∑i=1pσiuiviTA = U \Sigma V^T = \sum_{i=1}^{p} \sigma_i u_i v_i^T with p=min⁡(m,n)p = \min(m, n) and σ1≥⋯≥σp≥0\sigma_1 \ge \cdots \ge \sigma_p \ge 0. Let rr be the number of positive σi\sigma_i.

  1. TSVD(A, y, k) ▷ 0 ≤ k ≤ r
  2. 1(U, Σ, V) ← SVD(A) ▷ σ_1 ≥ σ_2 ≥ … ≥ σ_p
  3. 2x ← 0 ∈ ℝ^n
  4. 3for i ← 1 to k do
  5. 4c ← (u_iᵀ y) / σ_i
  6. 5x ← x + c · v_i
  7. 6return x
  8. TSVD-PATH(U, Σ, y, δ, τ) ▷ residual norms ρ_k = ‖A x_k - y‖ for k = 0 … r
  9. 7β_i ← u_iᵀ y for i = 1 … r; ρ_r² ← ‖y - Σ_{i ≤ r} β_i u_i‖²
  10. 8for k ← r - 1 down to 0 do
  11. 9ρ_k² ← ρ_{k+1}² + β_{k+1}²
  12. 10return the smallest k with ρ_k ≤ τ δ, or "none"

TSVD computes the SVD once (L1) and then sums the first kk terms of the pseudoinverse expansion (L2 to L5). TSVD-PATH uses the same SVD to get the residual norm for every kk at once. The part y−∑i≤rβiuiy - \sum_{i \le r} \beta_i u_i of the data lies outside the range of AA; no xkx_k can fit it. Each extra component k+1k + 1 removes βk+12\beta_{k+1}^2 from the squared residual. Line L10 is the discrepancy principle: stop at the first kk whose residual is at the noise level, with a safety factor τ>1\tau > 1 (the code uses τ=1.1\tau = 1.1; the factor is a choice).

Example

A trace. Let A=diag⁡(1, 0.1, 0.001)A = \operatorname{diag}(1,\ 0.1,\ 0.001), so that U=V=IU = V = I, xtrue=(1,1,1)x^{\mathrm{true}} = (1, 1, 1) and e=(0, 0.01, 0.01)e = (0,\ 0.01,\ 0.01), with ∥e∥=δ=0.014142\|e\| = \delta = 0.014142. The data are y=(1, 0.11, 0.011)y = (1,\ 0.11,\ 0.011).

kk ck=βk/σkc_k = \beta_k/\sigma_k xkx_k ∥xk−xtrue∥\|x_k - x^{\mathrm{true}}\| ρk=∥Axk−y∥\rho_k = \|A x_k - y\|
0 (0,0,0)(0, 0, 0) 1.7321 1.00609
1 1 (1,0,0)(1, 0, 0) 1.4142 0.11055
2 1.1 (1,1.1,0)(1, 1.1, 0) 1.0050 0.011
3 11 (1,1.1,11)(1, 1.1, 11) 10.0005 0

Line L7 gives β=(1, 0.11, 0.011)\beta = (1,\ 0.11,\ 0.011) and ρ3=0\rho_3 = 0, since AA is square and nonsingular. Lines L8 and L9 add 0.01120.011^2, then 0.1120.11^2, then 121^2. With τδ=0.015556\tau\delta = 0.015556, line L10 returns k=2k = 2. The third component has σ3=0.001\sigma_3 = 0.001, and its datum 0.0110.011 is ten parts noise to one part signal; dividing by σ3\sigma_3 turns the noise 0.010.01 into an error of 1010.

A discretized integral equation. Take the rectangle-rule matrix of the integration operator (Ax)(s)=∫0sx(t) dt(A x)(s) = \int_0^s x(t)\,dt with n=24n = 24 (h=1/24h = 1/24 on and below the diagonal), with singular values from σ1=0.64999\sigma_1 = 0.64999 down to σ24=0.02088\sigma_{24} = 0.02088. Let xj=sin⁡(πtj)x_j = \sin(\pi t_j) at the midpoints tj=(j+12)/24t_j = (j + \tfrac12)/24, so ∥x∥=3.464\|x\| = 3.464, and add Gaussian noise (seed 15) scaled to ∥e∥=δ=10−2\|e\| = \delta = 10^{-2}.

kk 0 3 6 9 12 18 24
∥xk−x∥\|x_k - x\| 3.464 0.245 0.108 0.063 0.118 0.221 0.416
ρk\rho_k 1.964 0.0216 0.0103 0.0096 0.0089 0.0075 0

The error falls while kk adds signal and rises when kk adds mostly noise; the best kk is 99. The discrepancy principle with τ=1.1\tau = 1.1 stops at k=6k = 6 (ρ5=0.0115>0.011≥ρ6=0.0103\rho_5 = 0.0115 > 0.011 \ge \rho_6 = 0.0103), with an error within a factor 1.71.7 of the best. A Picard plot of this problem is on the page Picard condition.

Correctness

TSVD returns xk=Ak†yx_k = A_k^\dagger y, where Ak=∑i≤kσiuiviTA_k = \sum_{i \le k} \sigma_i u_i v_i^T is the truncated matrix: xkx_k is the minimum norm minimizer of ∥Akx−y∥\|A_k x - y\|. By the Eckart-Young theorem, AkA_k is the closest matrix of rank at most kk to AA in the 2-norm (error σk+1\sigma_{k+1}) and in the Frobenius norm (error (∑i>kσi2)1/2(\sum_{i > k} \sigma_i^2)^{1/2}); Mirsky extended this to every unitarily invariant norm. The residual and the solution norm are ∥Axk−y∥2=∥y⊥∥2+∑i>kβi2\|A x_k - y\|^2 = \|y_\perp\|^2 + \sum_{i > k} \beta_i^2 and ∥xk∥2=∑i≤k(βi/σi)2\|x_k\|^2 = \sum_{i \le k} (\beta_i/\sigma_i)^2, so L7 to L9 compute the residuals exactly, the residual does not increase with kk, and L10 finds the first crossing. For noisy data with ∥yδ−y∥≤δ\|y^\delta - y\| \le \delta and y=Ax†y = A x^\dagger,

∥xkδ−x†∥≤δσk+∥∑i>kuiTyσivi∥,\|x_k^\delta - x^\dagger\| \le \frac{\delta}{\sigma_k} + \Big\| \sum_{i > k} \frac{u_i^T y}{\sigma_i} v_i \Big\|,

and under the source condition x†=(ATA)νwx^\dagger = (A^T A)^\nu w with ∥w∥≤C\|w\| \le C, the choice of the largest kk with σk≥δ1/(2ν+1)\sigma_k \ge \delta^{1/(2\nu+1)} gives an error at most (1+C) δ2ν/(2ν+1)(1 + C)\, \delta^{2\nu/(2\nu+1)}, for every ν>0\nu > 0. The proofs are in proofs/correctness.md.

Proof: TSVD returns the minimum norm solution of the truncated problem, its residuals are exact, and it converges at the optimal ratefull

Setting. Let AA be a real m×nm \times n matrix with SVD A=∑i=1pσiuiviTA = \sum_{i=1}^{p} \sigma_i u_i v_i^T, p=min⁡(m,n)p = \min(m, n), where u1,…,upu_1, \ldots, u_p are orthonormal in Rm\mathbb{R}^m, v1,…,vpv_1, \ldots, v_p are orthonormal in Rn\mathbb{R}^n, and σ1≥⋯≥σr>0=σr+1=⋯=σp\sigma_1 \ge \cdots \ge \sigma_r > 0 = \sigma_{r+1} = \cdots = \sigma_p. For 0≤k≤r0 \le k \le r let Ak=∑i≤kσiuiviTA_k = \sum_{i \le k} \sigma_i u_i v_i^T, βi=uiTy\beta_i = u_i^T y and Pk=∑i≤kuiuiTP_k = \sum_{i \le k} u_i u_i^T. All statements are in exact arithmetic. In floating point they hold for the exact SVD of a nearby matrix A+EA + E with ∥E∥≤c u∥A∥\|E\| \le c\,u\|A\|, if the SVD is backward stable.

Step 1: the output of TSVD. Lines L2 to L5 return xk=∑i≤k(βi/σi)vix_k = \sum_{i \le k} (\beta_i/\sigma_i) v_i. The loop adds one term per pass, and k≤rk \le r makes each σi\sigma_i positive, so no division by zero occurs.

Step 2: xkx_k is the minimum norm minimizer of ∥Akx−y∥\|A_k x - y\|. Complete v1,…,vkv_1, \ldots, v_k to an orthonormal basis of Rn\mathbb{R}^n and write zi=viTxz_i = v_i^T x. Since Akx=∑i≤kσiziui∈R(Pk)A_k x = \sum_{i \le k} \sigma_i z_i u_i \in R(P_k),

∥Akx−y∥2=∥Akx−Pky∥2+∥y−Pky∥2=∑i≤k(σizi−βi)2+∥y−Pky∥2.\|A_k x - y\|^2 = \|A_k x - P_k y\|^2 + \|y - P_k y\|^2 = \sum_{i \le k} (\sigma_i z_i - \beta_i)^2 + \|y - P_k y\|^2.

The second term does not depend on xx, so the minimizers are exactly the xx with zi=βi/σiz_i = \beta_i/\sigma_i for i≤ki \le k, and the other coordinates of xx are free. The norm ∥x∥2=∑izi2\|x\|^2 = \sum_i z_i^2 is smallest when the free coordinates are zero, which gives xkx_k. So xk=Ak†yx_k = A_k^\dagger y. For k=rk = r, Ar=AA_r = A and xr=A†yx_r = A^\dagger y, the minimum norm least squares solution.

Step 3: the residual and the solution norm. Let y⊥=y−Pryy_\perp = y - P_r y, which is orthogonal to every uiu_i with i≤ri \le r. Then

Axk−y=∑i≤kβiui−y=−(∑k<i≤rβiui+y⊥),A x_k - y = \sum_{i \le k} \beta_i u_i - y = -\Big(\sum_{k < i \le r} \beta_i u_i + y_\perp\Big),

and by orthogonality

ρk2=∥Axk−y∥2=∥y⊥∥2+∑k<i≤rβi2,∥xk∥2=∑i≤kβi2σi2.\rho_k^2 = \|A x_k - y\|^2 = \|y_\perp\|^2 + \sum_{k < i \le r} \beta_i^2, \qquad \|x_k\|^2 = \sum_{i \le k} \frac{\beta_i^2}{\sigma_i^2}.

For k=rk = r the sum is empty, so ρr2=∥y−∑i≤rβiui∥2\rho_r^2 = \|y - \sum_{i \le r} \beta_i u_i\|^2, which is line L7. For k<rk < r, ρk2−ρk+12=βk+12\rho_k^2 - \rho_{k+1}^2 = \beta_{k+1}^2, which is line L9. Line L8 runs kk from r−1r - 1 down to 00, so every ρk2\rho_k^2 is computed from ρk+12\rho_{k+1}^2 after that value is known. Both formulas show that ρk\rho_k does not increase and ∥xk∥\|x_k\| does not decrease as kk grows. Line L10 scans k=0,1,…,rk = 0, 1, \ldots, r and returns the first kk with ρk≤τδ\rho_k \le \tau\delta; by the monotony, every larger kk also satisfies the test, and if ρr>τδ\rho_r > \tau\delta no kk does, so "none" is correct.

Step 4: the error for noisy data. Let y=Ax†y = A x^\dagger with x†=A†yx^\dagger = A^\dagger y, so βi/σi=viTx†\beta_i/\sigma_i = v_i^T x^\dagger for i≤ri \le r and x†=∑i≤r(viTx†)vix^\dagger = \sum_{i \le r} (v_i^T x^\dagger) v_i. Let ∥yδ−y∥≤δ\|y^\delta - y\| \le \delta and let xkδx_k^\delta be the TSVD solution for yδy^\delta. Then

xkδ−x†=∑i≤kuiT(yδ−y)σivi  −  ∑k<i≤r(viTx†) vi.x_k^\delta - x^\dagger = \sum_{i \le k} \frac{u_i^T (y^\delta - y)}{\sigma_i} v_i \;-\; \sum_{k < i \le r} (v_i^T x^\dagger)\, v_i.

The two sums are orthogonal. The first has norm squared ∑i≤k(uiT(yδ−y))2/σi2≤σk−2∑i≤k(uiT(yδ−y))2≤δ2/σk2\sum_{i \le k} (u_i^T(y^\delta - y))^2/\sigma_i^2 \le \sigma_k^{-2} \sum_{i \le k} (u_i^T(y^\delta - y))^2 \le \delta^2/\sigma_k^2, by Bessel's inequality. So

∥xkδ−x†∥≤δσk+∥∑i>kuiTyσivi∥,\|x_k^\delta - x^\dagger\| \le \frac{\delta}{\sigma_k} + \Big\| \sum_{i > k} \frac{u_i^T y}{\sigma_i} v_i \Big\|,

the propagated noise plus the truncation error. For k=0k = 0 the first term is absent.

Step 5: the rate under a source condition. Assume x†=(ATA)νwx^\dagger = (A^T A)^\nu w with ν>0\nu > 0 and ∥w∥≤C\|w\| \le C. Then viTx†=σi2ν viTwv_i^T x^\dagger = \sigma_i^{2\nu}\, v_i^T w, and the truncation error is

∥∑k<i≤rσi2ν(viTw)vi∥≤σk+12ν∥w∥≤σk+12νC,\Big\| \sum_{k < i \le r} \sigma_i^{2\nu} (v_i^T w) v_i \Big\| \le \sigma_{k+1}^{2\nu} \|w\| \le \sigma_{k+1}^{2\nu} C,

with σr+1=0\sigma_{r+1} = 0. Let μ=δ1/(2ν+1)\mu = \delta^{1/(2\nu+1)} and let k≤rk \le r be the largest index with σk≥μ\sigma_k \ge \mu, or k=0k = 0 if σ1<μ\sigma_1 < \mu. Then σk+1<μ\sigma_{k+1} < \mu, so the truncation error is at most Cμ2ν=C δ2ν/(2ν+1)C\mu^{2\nu} = C\,\delta^{2\nu/(2\nu+1)}. The noise term is 00 if k=0k = 0 and at most δ/μ=δ2ν/(2ν+1)\delta/\mu = \delta^{2\nu/(2\nu+1)} otherwise. Hence

∥xkδ−x†∥≤(1+C) δ2ν/(2ν+1).\|x_k^\delta - x^\dagger\| \le (1 + C)\, \delta^{2\nu/(2\nu+1)}.

The bound σk+12ν\sigma_{k+1}^{2\nu} holds for every ν\nu, so there is no saturation: the qualification of TSVD is infinite. In δ\delta this is the order δ2ν/(2ν+1)\delta^{2\nu/(2\nu+1)} that no method can beat on this set (see the order optimality statement on the page regularization method).

Step 6: convergence for an operator. The same computation holds for a compact operator with singular system (σi;vi,ui)(\sigma_i; v_i, u_i) and yy in the domain of A†A^\dagger; the sums become series, which converge by the Picard condition. If k(δ)→∞k(\delta) \to \infty and δ/σk(δ)→0\delta/\sigma_{k(\delta)} \to 0 as δ→0\delta \to 0, both terms of Step 4 tend to zero: the first by assumption, the second because it is the tail of a convergent series. The bound does not depend on which yδy^\delta was chosen, so TSVD with such a rule is a regularization method.

Step 7: AkA_k is the best rank-kk approximation (Eckart-Young). First the 2-norm. ∥A−Ak∥2=∥∑i>kσiuiviT∥2=σk+1\|A - A_k\|_2 = \|\sum_{i > k} \sigma_i u_i v_i^T\|_2 = \sigma_{k+1}. Let BB have rank at most kk. Its null space has dimension at least n−kn - k, and the span of v1,…,vk+1v_1, \ldots, v_{k+1} has dimension k+1k + 1, so the two spaces share a unit vector z=∑i≤k+1civiz = \sum_{i \le k+1} c_i v_i with ∑ci2=1\sum c_i^2 = 1. Then

∥(A−B)z∥2=∥Az∥2=∑i≤k+1σi2ci2≥σk+12,\|(A - B) z\|^2 = \|A z\|^2 = \sum_{i \le k+1} \sigma_i^2 c_i^2 \ge \sigma_{k+1}^2,

so ∥A−B∥2≥σk+1\|A - B\|_2 \ge \sigma_{k+1}.

Next the Frobenius norm, through Weyl's inequality σi+j−1(C+D)≤σi(C)+σj(D)\sigma_{i+j-1}(C + D) \le \sigma_i(C) + \sigma_j(D). To prove it, let Ci−1C_{i-1} and Dj−1D_{j-1} be the truncations of CC and DD. Their sum has rank at most i+j−2i + j - 2, so by the 2-norm result

σi+j−1(C+D)≤∥C+D−Ci−1−Dj−1∥2≤∥C−Ci−1∥2+∥D−Dj−1∥2=σi(C)+σj(D).\sigma_{i+j-1}(C + D) \le \|C + D - C_{i-1} - D_{j-1}\|_2 \le \|C - C_{i-1}\|_2 + \|D - D_{j-1}\|_2 = \sigma_i(C) + \sigma_j(D).

Apply it with C=A−BC = A - B, D=BD = B and j=k+1j = k + 1. Since σk+1(B)=0\sigma_{k+1}(B) = 0, we get σi+k(A)≤σi(A−B)\sigma_{i+k}(A) \le \sigma_i(A - B) for every ii. Squaring and adding over ii gives

∥A−B∥F2=∑iσi(A−B)2≥∑i>kσi(A)2=∥A−Ak∥F2.\|A - B\|_F^2 = \sum_i \sigma_i(A - B)^2 \ge \sum_{i > k} \sigma_i(A)^2 = \|A - A_k\|_F^2.

So AkA_k is a closest matrix of rank at most kk in both norms. □\square

Complexity

  • The SVD (L1). O(mn2)O(m n^2) flops for m≥nm \ge n with the Golub-Kahan bidiagonalization and the QR iteration (see Golub-Kahan SVD algorithm). The reference code uses one-sided Jacobi, which costs O(mn2)O(m n^2) per sweep and needs a small number of sweeps in practice. If m<nm < n, apply the method to ATA^T; the cost is O(nm2)O(n m^2).
  • One solution (L2 to L6). kk inner products of length mm and kk vector updates of length nn: O(k(m+n))O(k(m + n)).
  • All residuals (L7 to L10). O(mr)O(m r) for the coefficients and the out-of-range part, then O(r)O(r) for the tail sums and the search. Every solution norm ∥xk∥\|x_k\| also costs O(r)O(r) in total. So the whole L-curve or discrepancy curve costs O(mn)O(m n) after the SVD.
  • Space. O(mn)O(m n) for UU and VV; the thin SVD stores mp+p+npm p + p + n p numbers.

For one value of kk and a large sparse AA, a full SVD is wasteful. A partial SVD by Lanczos bidiagonalization, or an iterative method such as LSQR, costs only products with AA and ATA^T.

Properties

  • Linear in the data. xk=VkΣk−1UkTyx_k = V_k \Sigma_k^{-1} U_k^T y for a fixed kk. With the discrepancy principle, kk depends on yy and the map is no longer linear.
  • Filter factors. fi=1f_i = 1 for i≤ki \le k and 00 otherwise. The noise amplification is ∥Ak†∥=1/σk\|A_k^\dagger\| = 1/\sigma_k.
  • Infinite qualification. Under the source condition the bias is at most σk+12ν∥w∥\sigma_{k+1}^{2\nu} \|w\| for every ν\nu, so TSVD does not saturate as Tikhonov does at ν=1\nu = 1 (see qualification of regularization).
  • Monotone curves. As kk grows, ∥Axk−y∥\|A x_k - y\| does not increase and ∥xk∥\|x_k\| does not decrease.
  • Resolution. The resolution matrix VkVkTV_k V_k^T is an orthogonal projection of trace kk.
  • Sign invariance. Each term (uiTy)vi(u_i^T y) v_i is unchanged if the SVD returns −ui-u_i and −vi-v_i, so the arbitrary signs of a computed SVD do not matter.

Variants and improvements

  • Truncated GSVD. With a regularization matrix LL (for example a difference operator), truncate the generalized SVD of the pair (A,L)(A, L) instead. This penalizes roughness rather than size.
  • Damped or smoothed truncation. Replace the sharp cutoff by a smooth one; Tikhonov is the standard choice, with fi=σi2/(σi2+α)f_i = \sigma_i^2/(\sigma_i^2 + \alpha).
  • Truncated rank-revealing QR. A rank-revealing factorization gives a cheaper approximation of the dominant subspace when there is a clear gap.
  • Partial and randomized SVD. For a large AA, compute only the first kk triples by Lanczos bidiagonalization or by a randomized range finder.
  • Other parameter rules. The L-curve and generalized cross-validation choose kk without δ\delta; they are heuristics (see Bakushinskii veto).

When to use it

Use TSVD on small and medium dense problems, where one SVD is affordable (up to a few thousand unknowns), and when you want to see the problem: the singular values, the Picard plot and the effect of each kk all come from the same SVD. It is the natural method when the singular values have a clear gap, because then the numerical rank is well defined. When the singular values decay without a gap, Tikhonov regularization gives similar errors with a smoother solution and a continuous parameter. For large or sparse problems use an iterative method such as LSQR or CGLS, which regularize by the number of steps.

Pitfalls

  • Forming ATAA^T A. Computing the SVD from the eigenvalues of ATAA^T A squares the condition number. Singular values below u σ1\sqrt{u}\,\sigma_1, with u=2−53u = 2^{-53}, are then lost. Use an SVD of AA itself.
  • Truncating below the rounding level. In the floating-point model, a backward stable SVD returns the exact SVD of A+EA + E with ∥E∥≤c u∥A∥\|E\| \le c\, u \|A\|, so each computed σi\sigma_i has an absolute error of about u σ1u\,\sigma_1. Components with σi\sigma_i near u σ1u\,\sigma_1 are rounding noise even for exact data; never choose kk beyond them.
  • Close singular values at the cut. If σk\sigma_k and σk+1\sigma_{k+1} are close, the individual vectors vkv_k and vk+1v_{k+1} are ill determined, and xkx_k changes a lot with small changes of AA. The space of the first kk vectors is stable only when the gap σk−σk+1\sigma_k - \sigma_{k+1} is large compared with the perturbation (see Davis-Kahan theorem).
  • Looking for a gap that is not there. For a discretized compact operator the singular values decay smoothly. The choice of kk must come from the noise level, not from a gap.
  • Gibbs-like ringing. The sharp cutoff makes the rows of the resolution matrix oscillate, with negative side lobes, so TSVD solutions can ring near jumps. A smooth filter rings less.
  • Out-of-range data. If m>nm > n, the part of yy outside the range of AA stays in every residual. The discrepancy principle then needs δ\delta to include it, or no kk satisfies L10.

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.

imgkit.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the imaging and inverse problems pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small images and signals for the imaging and inverse problems pages.

Conventions:
- A signal is a list of numbers. An image is a list of rows, img[i][j], with
  row i from the top and column j from the left.
- An n x n image covers the square [-1, 1]^2. The center of pixel (i, j) is
  x_j = -1 + (2 j + 1) / n and y_i = 1 - (2 i + 1) / n, so y goes up.
- DFT: X_k = sum_j x_j exp(-2 pi i j k / n), unnormalized; the inverse has
  the factor 1 / n. Index k stands for frequency k for k < n / 2 and k - n
  otherwise. fftshift moves the zero frequency to position n // 2.
- Periodic convolution kernels are stored with their center at index 0
  (wrapped around), so a delta kernel gives the identity and no shift.
"""

import cmath
import math

# ------------------------------------------------------------------ images


def new_image(n1, n2, value=0.0):
    """An n1 x n2 image (n1 rows, n2 columns) filled with value."""
    return [[value] * n2 for _ in range(n1)]


def img_add(a, b):
    """The pixelwise sum a + b."""
    return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]


def img_scale(a, c):
    """The image c a."""
    return [[c * x for x in row] for row in a]


def img_dot(a, b):
    """<a, b> = sum conj(a_ij) b_ij."""
    return sum(x.conjugate() * y for ra, rb in zip(a, b) for x, y in zip(ra, rb))


def img_norm(a):
    """The Euclidean (Frobenius) norm of an image."""
    return math.sqrt(sum(abs(x) ** 2 for row in a for x in row))


def flatten(img):
    """Row-major vector of an image."""
    return [x for row in img for x in row]


def unflatten(v, n1, n2):
    """The n1 x n2 image of a row-major vector."""
    return [list(v[i * n2:(i + 1) * n2]) for i in range(n1)]


# ------------------------------------------------------------------ DFT


def _is_pow2(n):
    return n > 0 and n & (n - 1) == 0


def _fft_pow2(x):
    """Iterative radix-2 FFT, unnormalized forward transform."""
    n = len(x)
    a = [complex(v) for v in x]
    j = 0
    for i in range(1, n):
        bit = n >> 1
        while j & bit:
            j ^= bit
            bit >>= 1
        j |= bit
        if i < j:
            a[i], a[j] = a[j], a[i]
    size = 2
    while size <= n:
        half = size // 2
        tw = [cmath.exp(-2j * math.pi * k / size) for k in range(half)]
        for start in range(0, n, size):
            for k in range(half):
                u = a[start + k]
                v = a[start + k + half] * tw[k]
                a[start + k] = u + v
                a[start + k + half] = u - v
        size *= 2
    return a


def dft(x):
    """X_k = sum_j x_j exp(-2 pi i j k / n). Radix-2 FFT when n is a power of 2."""
    n = len(x)
    if n == 0:
        return []
    if _is_pow2(n):
        return _fft_pow2(x)
    w = [cmath.exp(-2j * math.pi * t / n) for t in range(n)]
    return [sum(x[j] * w[(j * k) % n] for j in range(n)) for k in range(n)]


def idft(xf):
    """x_j = (1/n) sum_k X_k exp(2 pi i j k / n)."""
    n = len(xf)
    if n == 0:
        return []
    y = dft([complex(v).conjugate() for v in xf])
    return [v.conjugate() / n for v in y]


def _rows_then_cols(img, f):
    rows = [f(row) for row in img]
    cols = [f(list(col)) for col in zip(*rows)]
    return [list(r) for r in zip(*cols)]


def dft2(img):
    """2D DFT: X_kl = sum_jq x_jq exp(-2 pi i (j k / n1 + q l / n2))."""
    return _rows_then_cols(img, dft)


def idft2(img):
    """Inverse 2D DFT, with the factor 1 / (n1 n2)."""
    return _rows_then_cols(img, idft)


def _shift1(x, s):
    return list(x[s:]) + list(x[:s])


def fftshift(x):
    """Move the zero frequency to position n // 2 (1D, or both axes of an image)."""
    if x and isinstance(x[0], (list, tuple)):
        rows = [fftshift(r) for r in x]
        return _shift1(rows, (len(rows) + 1) // 2)
    return _shift1(x, (len(x) + 1) // 2)


def ifftshift(x):
    """The inverse of fftshift (1D, or both axes of an image)."""
    if x and isinstance(x[0], (list, tuple)):
        rows = [ifftshift(r) for r in x]
        return _shift1(rows, len(rows) // 2)
    return _shift1(x, len(x) // 2)


def circ_conv(x, h):
    """Periodic convolution y_i = sum_j h_j x_{(i - j) mod n}, kernel centered at index 0."""
    n = len(x)
    nz = [(j, hj) for j, hj in enumerate(h) if hj != 0]
    return [sum(hj * x[(i - j) % n] for j, hj in nz) for i in range(n)]


def circ_conv2(img, h):
    """Periodic 2D convolution with the kernel h centered at index (0, 0)."""
    n1, n2 = len(img), len(img[0])
    nz = [(p, q, h[p][q]) for p in range(len(h)) for q in range(len(h[0])) if h[p][q] != 0]
    out = new_image(n1, n2)
    for i in range(n1):
        for j in range(n2):
            out[i][j] = sum(v * img[(i - p) % n1][(j - q) % n2] for p, q, v in nz)
    return out


# ------------------------------------------------------------------ phantoms


def pixel_centers(n):
    """(xs, ys): xs[j] = -1 + (2 j + 1) / n and ys[i] = 1 - (2 i + 1) / n."""
    xs = [-1.0 + (2 * j + 1) / n for j in range(n)]
    ys = [1.0 - (2 * i + 1) / n for i in range(n)]
    return xs, ys


# Rows: rho, A, B, x0, y0, phi (degrees). A is the semi-axis along the
# direction phi (counterclockwise from the x axis), B the other semi-axis.
# Geometry and densities of Shepp and Logan (1974), as reproduced in Kak and
# Slaney, Principles of Computerized Tomographic Imaging, Table 3.1. The value
# at the center (0, 0) is 2 - 0.98 = 1.02.
SHEPP_LOGAN = [
    (2.0, 0.92, 0.69, 0.0, 0.0, 90.0),
    (-0.98, 0.874, 0.6624, 0.0, -0.0184, 90.0),
    (-0.02, 0.31, 0.11, 0.22, 0.0, 72.0),
    (-0.02, 0.41, 0.16, -0.22, 0.0, 108.0),
    (0.01, 0.25, 0.21, 0.0, 0.35, 90.0),
    (0.01, 0.046, 0.046, 0.0, 0.1, 0.0),
    (0.01, 0.046, 0.046, 0.0, -0.1, 0.0),
    (0.01, 0.046, 0.023, -0.08, -0.605, 0.0),
    (0.01, 0.023, 0.023, 0.0, -0.605, 0.0),
    (0.01, 0.046, 0.023, 0.06, -0.605, 90.0),
]

# The same ellipses with the gray levels of Toft (1996), which give more
# contrast. The value at the center is 1 - 0.8 = 0.2.
MODIFIED_SHEPP_LOGAN = [
    (rho, a, b, x0, y0, phi)
    for rho, (_, a, b, x0, y0, phi) in zip(
        (1.0, -0.8, -0.2, -0.2, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1), SHEPP_LOGAN
    )
]


def ellipse_value(x, y, table):
    """The phantom value at the point (x, y): the sum of rho over the ellipses that hold it."""
    total = 0.0
    for rho, a, b, x0, y0, phi in table:
        c, s = math.cos(math.radians(phi)), math.sin(math.radians(phi))
        dx, dy = x - x0, y - y0
        u = dx * c + dy * s
        v = -dx * s + dy * c
        if (u / a) ** 2 + (v / b) ** 2 <= 1.0:
            total += rho
    return total


def ellipse_phantom(n, table):
    """The n x n image of an ellipse table, sampled at the pixel centers."""
    xs, ys = pixel_centers(n)
    return [[ellipse_value(x, y, table) for x in xs] for y in ys]


def disk_phantom(n, radius):
    """1 at pixel centers with x^2 + y^2 <= radius^2, 0 elsewhere."""
    xs, ys = pixel_centers(n)
    r2 = radius * radius
    return [[1.0 if x * x + y * y <= r2 else 0.0 for x in xs] for y in ys]


def spikes_1d(n, positions, amplitudes):
    """A signal of length n with the given amplitudes at the given positions."""
    out = [0.0] * n
    for p, a in zip(positions, amplitudes):
        out[p] += a
    return out


# ------------------------------------------------------------------ projector


def parallel_beam_matrix(n, angles, nbins):
    """Pixel-driven discrete Radon transform of an n x n image on [-1, 1]^2.

    Each pixel center (x, y) projects to s = x cos(theta) + y sin(theta). Its
    value times the pixel area over the bin width is split linearly between
    the two nearest bin centers. The bins cover [-sqrt(2), sqrt(2)]. Row
    a * nbins + b holds angle a and bin b; column i * n + j holds pixel (i, j).
    Returns the sparse rows, each a list of (column, weight) pairs.
    Pixel-driven projection has a ripple: with a bin width close to the pixel
    size, a disk projection is off by up to about 10 percent in some bins. A
    bin of about twice the pixel size (nbins = 23 for n = 32) keeps it near
    1 percent.
    """
    xs, ys = pixel_centers(n)
    smax = math.sqrt(2.0)
    width = 2.0 * smax / nbins
    scale = (2.0 / n) ** 2 / width
    rows = []
    for theta in angles:
        c, s = math.cos(theta), math.sin(theta)
        acc = [dict() for _ in range(nbins)]
        for i, y in enumerate(ys):
            for j, x in enumerate(xs):
                t = (x * c + y * s + smax) / width - 0.5
                b0 = math.floor(t)
                frac = t - b0
                col = i * n + j
                for b, w in ((b0, 1.0 - frac), (b0 + 1, frac)):
                    if 0 <= b < nbins and w > 0.0:
                        acc[b][col] = acc[b].get(col, 0.0) + w * scale
        rows.extend(sorted(d.items()) for d in acc)
    return rows


def sp_matvec(rows, x):
    """y = A x for sparse rows of (column, weight) pairs."""
    return [sum(w * x[c] for c, w in row) for row in rows]


def sp_rmatvec(rows, y, ncols):
    """x = A^H y for sparse rows of (column, weight) pairs and ncols columns."""
    out = [0.0] * ncols
    for row, yi in zip(rows, y):
        if yi == 0:
            continue
        for c, w in row:
            out[c] += w.conjugate() * yi
    return out


# ------------------------------------------------------------------ noise


def gauss_noise(rng, shape, sigma):
    """Independent N(0, sigma^2) values: a list for an int shape, an image for (n1, n2)."""
    if isinstance(shape, int):
        return [rng.gauss(0.0, sigma) for _ in range(shape)]
    n1, n2 = shape
    return [[rng.gauss(0.0, sigma) for _ in range(n2)] for _ in range(n1)]


def _poisson_small(rng, lam):
    """Knuth's product method, exact for a mean lam <= 30."""
    limit = math.exp(-lam)
    k, p = 0, rng.random()
    while p > limit:
        k += 1
        p *= rng.random()
    return k


def poisson_sample(rng, lam):
    """An exact Poisson(lam) sample: a sum of Knuth samples with means at most 30."""
    if lam < 0:
        raise ValueError("negative mean")
    total = 0
    while lam > 30.0:
        total += _poisson_small(rng, 30.0)
        lam -= 30.0
    if lam > 0.0:
        total += _poisson_small(rng, lam)
    return total
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
truncated_svd.py 69 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/truncated-svd/. The authors are listed in prov/7EBBWK.jsonl.
"""Truncated singular value decomposition (TSVD) for a real linear system A x = y.

The regularized solution is x_k = sum_{i=1}^{k} (<u_i, y> / sigma_i) v_i, with
the singular triples of A in descending order of sigma_i.
"""

import math

from imgla import svd


def tsvd(a, y, k):
    """The TSVD solution x_k of A x = y. Computes one SVD of A."""
    u, s, v = svd(a)  # @line L1
    return tsvd_from_svd(u, s, v, y, k)


def tsvd_from_svd(u, s, v, y, k):
    """x_k from a thin SVD (U, S, V) of A, S descending. Costs O(k (m + n))."""
    if not 0 <= k <= len(s):
        raise ValueError("k must be between 0 and min(m, n)")
    if k > 0 and not s[k - 1] > 0.0:
        raise ValueError("k is larger than the rank")
    m, n = len(u), len(v)
    x = [0.0] * n  # @line L2
    for i in range(k):  # @line L3
        c = sum(u[r][i] * y[r] for r in range(m)) / s[i]  # @line L4
        for j in range(n):  # @line L5
            x[j] += c * v[j][i]
    return x  # @line L6


def tsvd_path(u, s, y):
    """Residual norms and solution norms of x_k for k = 0, 1, ..., r.

    With beta_i = <u_i, y>: ||A x_k - y||^2 = ||y_perp||^2 + sum_{i>k} beta_i^2,
    where y_perp is the part of y outside the range of A, and
    ||x_k||^2 = sum_{i<=k} (beta_i / sigma_i)^2. r is the number of positive
    singular values. Costs O(m r) for the coefficients, then O(1) per k.
    """
    m = len(u)
    r = sum(1 for si in s if si > 0.0)
    beta = [sum(u[q][i] * y[q] for q in range(m)) for i in range(r)]  # @line L7
    perp = [y[q] - sum(beta[i] * u[q][i] for i in range(r)) for q in range(m)]
    tail = [0.0] * (r + 1)
    tail[r] = sum(v * v for v in perp)
    for i in range(r - 1, -1, -1):  # @line L8
        tail[i] = tail[i + 1] + beta[i] * beta[i]  # @line L9
    sol2 = 0.0
    norms = [0.0]
    for i in range(r):
        sol2 += (beta[i] / s[i]) ** 2
        norms.append(math.sqrt(sol2))
    return [math.sqrt(t) for t in tail], norms


def discrepancy_index(residuals, delta, tau=1.1):
    """The smallest k with ||A x_k - y|| <= tau delta, or None if no k qualifies."""
    for k, rk in enumerate(residuals):  # @line L10
        if rk <= tau * delta:
            return k
    return None


def filter_factors(k, p):
    """The TSVD filter factors f_i = 1 for i <= k and 0 for k < i <= p."""
    return [1.0 if i < k else 0.0 for i in range(p)]
test_truncated_svd.py 385 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/truncated-svd/. The authors are listed in prov/7EBBWK.jsonl.
# This file also tests the shared helpers imgla.py and imgkit.py.

import cmath
import math
import random
from fractions import Fraction

import imgkit as ik
import imgla as la
from truncated_svd import discrepancy_index, filter_factors, tsvd, tsvd_from_svd, tsvd_path


def rand_matrix(rng, m, n):
    return [[rng.gauss(0.0, 1.0) for _ in range(n)] for _ in range(m)]


def max_abs_diff(a, b):
    return max(abs(x - y) for ra, rb in zip(a, b) for x, y in zip(ra, rb))


def integration_matrix(n):
    """Rectangle rule for (A x)(s) = int_0^s x(t) dt on [0, 1]: h on and below the diagonal."""
    h = 1.0 / n
    return [[h if j <= i else 0.0 for j in range(n)] for i in range(n)]


# ------------------------------------------------------------------ imgla


def test_svd_reconstructs() -> None:
    rng = random.Random(1)
    for m, n in ((6, 4), (4, 6), (5, 5)):
        a = rand_matrix(rng, m, n)
        u, s, v = la.svd(a)
        p = min(m, n)
        assert len(s) == p and all(s[i] >= s[i + 1] for i in range(p - 1))
        us = [[u[i][j] * s[j] for j in range(p)] for i in range(m)]
        assert max_abs_diff(la.matmul(us, la.transpose(v)), a) < 1e-10
        assert max_abs_diff(la.matmul(la.transpose(u), u), la.eye(p)) < 1e-10
        assert max_abs_diff(la.matmul(la.transpose(v), v), la.eye(p)) < 1e-10


def test_svd_rank_deficient() -> None:
    a = [[1.0, 2.0, 3.0], [2.0, 4.0, 6.0], [1.0, 0.0, 1.0], [0.0, 0.0, 0.0]]
    u, s, v = la.svd(a)
    assert s[2] < 1e-12
    assert max_abs_diff(la.matmul(la.transpose(u), u), la.eye(3)) < 1e-10
    z = la.zeros(3, 2)
    u0, s0, v0 = la.svd(z)
    assert s0 == [0.0, 0.0]
    assert max_abs_diff(la.matmul(la.transpose(u0), u0), la.eye(2)) < 1e-12


def test_sym_eig_reconstructs() -> None:
    rng = random.Random(2)
    b = rand_matrix(rng, 5, 5)
    a = [[b[i][j] + b[j][i] for j in range(5)] for i in range(5)]
    w, q = la.sym_eig(a)
    assert all(w[i] <= w[i + 1] for i in range(4))
    qw = [[q[i][j] * w[j] for j in range(5)] for i in range(5)]
    assert max_abs_diff(la.matmul(qw, la.transpose(q)), a) < 1e-10
    assert max_abs_diff(la.matmul(la.transpose(q), q), la.eye(5)) < 1e-10


def test_adjoint_gap_matrix() -> None:
    rng = random.Random(3)
    a = [[complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(4)] for _ in range(6)]
    x = [complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(4)]
    y = [complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(6)]
    gap = la.adjoint_gap(lambda t: la.matvec(a, t), lambda t: la.rmatvec(a, t), x, y)
    assert gap < 1e-12
    ah = la.conj_transpose(a)
    assert max(abs(p - q) for p, q in zip(la.matvec(ah, y), la.rmatvec(a, y))) < 1e-12
    wrong = la.adjoint_gap(lambda t: la.matvec(a, t), lambda t: la.matvec(la.transpose(a), t), x, y)
    assert wrong > 1e-3


def test_solve_and_cholesky() -> None:
    a = [[Fraction(2), Fraction(1), Fraction(0)], [Fraction(4), Fraction(3), Fraction(1)], [Fraction(0), Fraction(1), Fraction(5)]]
    x = la.solve(a, [Fraction(3), Fraction(8), Fraction(6)])
    assert x == [Fraction(1), Fraction(1), Fraction(1)]
    rng = random.Random(4)
    b = rand_matrix(rng, 5, 5)
    spd = la.matmul(la.transpose(b), b)
    for i in range(5):
        spd[i][i] += 1.0
    rhs = [rng.gauss(0, 1) for _ in range(5)]
    low = la.cholesky(spd)
    assert max_abs_diff(la.matmul(low, la.transpose(low)), spd) < 1e-10
    x1 = la.cho_solve(low, rhs)
    x2 = la.solve(spd, rhs)
    assert max(abs(p - q) for p, q in zip(x1, x2)) < 1e-10
    xm = la.solve(spd, [[1.0, 0.0], [0.0, 1.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0]])
    assert len(xm) == 5 and len(xm[0]) == 2
    assert abs(la.dot([1j, 2.0], [1j, 1.0]) - 3.0) < 1e-15
    assert abs(la.norm2([[3.0, 0.0], [0.0, 4.0]]) - 5.0) < 1e-15


# ------------------------------------------------------------------ imgkit


def test_dft_check_value_and_inverse() -> None:
    xf = ik.dft([1, 2, 3, 4])
    for got, want in zip(xf, (10, -2 + 2j, -2, -2 - 2j)):
        assert abs(got - want) < 1e-12
    rng = random.Random(5)
    for n in (8, 12, 16):
        x = [complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(n)]
        back = ik.idft(ik.dft(x))
        assert max(abs(p - q) for p, q in zip(back, x)) < 1e-12
        xf = ik.dft(x)
        assert abs(sum(abs(v) ** 2 for v in xf) - n * sum(abs(v) ** 2 for v in x)) < 1e-9
        direct = [sum(x[j] * cmath.exp(-2j * math.pi * j * k / n) for j in range(n)) for k in range(n)]
        assert max(abs(p - q) for p, q in zip(xf, direct)) < 1e-10


def test_dft2_and_shift() -> None:
    rng = random.Random(6)
    img = [[rng.gauss(0, 1) for _ in range(6)] for _ in range(4)]
    back = ik.idft2(ik.dft2(img))
    assert max_abs_diff(back, img) < 1e-12
    xf = ik.dft2(img)
    assert abs(xf[0][0] - sum(map(sum, img))) < 1e-12
    assert ik.fftshift([0, 1, 2, 3]) == [2, 3, 0, 1]
    assert ik.fftshift([0, 1, 2, 3, 4]) == [3, 4, 0, 1, 2]
    for n in (4, 5):
        assert ik.ifftshift(ik.fftshift(list(range(n)))) == list(range(n))
    sh = ik.fftshift([[0, 1], [2, 3]])
    assert sh == [[3, 2], [1, 0]]
    assert ik.ifftshift(sh) == [[0, 1], [2, 3]]


def test_circ_conv() -> None:
    rng = random.Random(7)
    n = 12
    x = [rng.gauss(0, 1) for _ in range(n)]
    h = [rng.gauss(0, 1) for _ in range(n)]
    y = ik.circ_conv(x, h)
    yf = ik.idft([a * b for a, b in zip(ik.dft(x), ik.dft(h))])
    assert max(abs(p - q) for p, q in zip(y, yf)) < 1e-12
    delta = ik.spikes_1d(n, [0], [1.0])
    assert ik.circ_conv(x, delta) == x
    img = [[rng.gauss(0, 1) for _ in range(4)] for _ in range(4)]
    k2 = [[rng.gauss(0, 1) for _ in range(4)] for _ in range(4)]
    c2 = ik.circ_conv2(img, k2)
    f2 = ik.idft2([[a * b for a, b in zip(ra, rb)] for ra, rb in zip(ik.dft2(img), ik.dft2(k2))])
    assert max_abs_diff(c2, f2) < 1e-12
    d2 = ik.new_image(4, 4)
    d2[0][0] = 1.0
    assert ik.circ_conv2(img, d2) == img


def test_image_ops() -> None:
    a = [[1.0, 2.0], [3.0, 4.0]]
    b = ik.img_scale(a, 2.0)
    assert ik.img_add(a, b) == [[3.0, 6.0], [9.0, 12.0]]
    assert ik.img_dot(a, a) == 30.0
    assert abs(ik.img_norm(a) - math.sqrt(30.0)) < 1e-15
    assert ik.unflatten(ik.flatten(a), 2, 2) == a
    xs, ys = ik.pixel_centers(4)
    assert xs == [-0.75, -0.25, 0.25, 0.75] and ys == [0.75, 0.25, -0.25, -0.75]


def test_shepp_logan_centers() -> None:
    assert len(ik.SHEPP_LOGAN) == 10 and len(ik.MODIFIED_SHEPP_LOGAN) == 10
    assert abs(ik.ellipse_value(0.0, 0.0, ik.SHEPP_LOGAN) - 1.02) < 1e-12
    assert abs(ik.ellipse_value(0.0, 0.0, ik.MODIFIED_SHEPP_LOGAN) - 0.2) < 1e-12
    img = ik.ellipse_phantom(33, ik.MODIFIED_SHEPP_LOGAN)
    assert abs(img[16][16] - 0.2) < 1e-12
    assert img[0][0] == 0.0
    # The large dark ellipse on the right of the image (x = 0.22) lies inside the brain.
    assert abs(ik.ellipse_value(0.22, 0.0, ik.SHEPP_LOGAN) - 1.0) < 1e-12


def test_parallel_beam_matrix() -> None:
    # A bin about twice the pixel size keeps the ripple of pixel-driven projection small.
    n, nbins = 32, 23
    angles = [math.pi * a / 8 for a in range(8)]
    rows = ik.parallel_beam_matrix(n, angles, nbins)
    assert len(rows) == len(angles) * nbins
    rng = random.Random(8)
    x = [rng.gauss(0, 1) for _ in range(n * n)]
    y = [rng.gauss(0, 1) for _ in range(len(rows))]
    gap = la.adjoint_gap(lambda t: ik.sp_matvec(rows, t), lambda t: ik.sp_rmatvec(rows, t, n * n), x, y)
    assert gap < 1e-12
    disk = ik.flatten(ik.disk_phantom(n, 1.0))
    proj = ik.sp_matvec(rows, disk)
    width = 2.0 * math.sqrt(2.0) / nbins
    for a in range(len(angles)):
        for b in range(nbins // 2 - 3, nbins // 2 + 4):
            s = -math.sqrt(2.0) + (b + 0.5) * width
            exact = 2.0 * math.sqrt(1.0 - s * s)
            assert abs(proj[a * nbins + b] - exact) <= 0.05 * exact


def test_noise() -> None:
    rng = random.Random(9)
    draws = [ik.poisson_sample(rng, 4.0) for _ in range(2000)]
    assert abs(sum(draws) / 2000 - 4.0) < 0.2
    big = [ik.poisson_sample(rng, 75.0) for _ in range(400)]
    assert abs(sum(big) / 400 - 75.0) < 2.0
    assert ik.poisson_sample(rng, 0.0) == 0
    g = ik.gauss_noise(rng, (3, 4), 0.5)
    assert len(g) == 3 and len(g[0]) == 4
    v = ik.gauss_noise(random.Random(10), 4000, 2.0)
    var = sum(t * t for t in v) / len(v)
    assert abs(var - 4.0) < 0.3


# ------------------------------------------------------------------ TSVD


def test_integration_operator_singular_values() -> None:
    # The lower triangular matrix of ones has singular values 1 / (2 sin((2k - 1) pi / (4n + 2))).
    n = 24
    _, s, _ = la.svd(integration_matrix(n))
    for k in range(1, n + 1):
        assert abs(s[k - 1] - 1.0 / (2 * n * math.sin((2 * k - 1) * math.pi / (4 * n + 2)))) < 1e-12
    # They approach the continuous values 2 / ((2k - 1) pi); sigma_1 tends to 2 / pi = 0.63662.
    for k in range(1, 4):
        assert abs(s[k - 1] - 2.0 / ((2 * k - 1) * math.pi)) < 0.15 * 2.0 / ((2 * k - 1) * math.pi)
    assert abs(2.0 / math.pi - 0.63662) < 5e-6


def test_tsvd_matches_eigen_route() -> None:
    # Reference: the eigen decomposition of A^T A (a different algorithm) gives
    # x_k = sum_{i<=k} (<v_i, A^T y> / lambda_i) v_i over the k largest eigenvalues.
    rng = random.Random(11)
    m, n = 9, 6
    a = rand_matrix(rng, m, n)
    y = [rng.gauss(0, 1) for _ in range(m)]
    w, q = la.sym_eig(la.matmul(la.transpose(a), a))
    aty = la.rmatvec(a, y)
    for k in range(n + 1):
        x = tsvd(a, y, k)
        ref = [0.0] * n
        for idx in range(n - 1, n - 1 - k, -1):
            vi = [q[j][idx] for j in range(n)]
            c = sum(p * t for p, t in zip(vi, aty)) / w[idx]
            ref = [r + c * t for r, t in zip(ref, vi)]
        assert max(abs(p - t) for p, t in zip(x, ref)) < 1e-9


def test_full_rank_is_least_squares() -> None:
    rng = random.Random(12)
    a = rand_matrix(rng, 8, 5)
    y = [rng.gauss(0, 1) for _ in range(8)]
    x = tsvd(a, y, 5)
    ref = la.solve(la.matmul(la.transpose(a), a), la.rmatvec(a, y))
    assert max(abs(p - t) for p, t in zip(x, ref)) < 1e-10


def test_minimum_norm_on_rank_deficient() -> None:
    # Two equal columns: rank 1. The minimum norm solution splits the weight equally.
    a = [[1.0, 1.0], [1.0, 1.0], [0.0, 0.0]]
    u, s, v = la.svd(a)
    x = tsvd_from_svd(u, s, v, [2.0, 2.0, 5.0], 1)
    assert abs(x[0] - 1.0) < 1e-12 and abs(x[1] - 1.0) < 1e-12
    try:
        tsvd_from_svd(u, s, v, [2.0, 2.0, 5.0], 2)
    except ValueError:
        pass
    else:
        raise AssertionError("k above the rank must be rejected")


def test_path_norms_and_filters() -> None:
    rng = random.Random(13)
    m, n = 10, 7
    a = rand_matrix(rng, m, n)
    y = [rng.gauss(0, 1) for _ in range(m)]
    u, s, v = la.svd(a)
    res, nrm = tsvd_path(u, s, y)
    for k in range(n + 1):
        x = tsvd_from_svd(u, s, v, y, k)
        r = [p - t for p, t in zip(la.matvec(a, x), y)]
        assert abs(la.norm2(r) - res[k]) < 1e-10
        assert abs(la.norm2(x) - nrm[k]) < 1e-10
        assert all(res[k] >= res[k + 1] - 1e-15 for k in range(n))
    assert filter_factors(2, 4) == [1.0, 1.0, 0.0, 0.0]


def test_eckart_young() -> None:
    rng = random.Random(14)
    m, n, k = 6, 5, 2
    a = rand_matrix(rng, m, n)
    u, s, v = la.svd(a)
    ak = [[sum(u[i][t] * s[t] * v[j][t] for t in range(k)) for j in range(n)] for i in range(m)]
    diff = [[a[i][j] - ak[i][j] for j in range(n)] for i in range(m)]
    _, sd, _ = la.svd(diff)
    assert abs(sd[0] - s[k]) < 1e-10
    best_f = la.norm2(diff)
    assert abs(best_f - math.sqrt(sum(t * t for t in s[k:]))) < 1e-10
    for _ in range(100):
        left = rand_matrix(rng, m, k)
        right = rand_matrix(rng, k, n)
        cand = la.matmul(left, right)
        d = [[a[i][j] - cand[i][j] for j in range(n)] for i in range(m)]
        assert la.norm2(d) >= best_f - 1e-12
        _, sc, _ = la.svd(d)
        assert sc[0] >= s[k] - 1e-12


def test_noise_amplification_and_discrepancy() -> None:
    n = 24
    a = integration_matrix(n)
    u, s, v = la.svd(a)
    t = [(j + 0.5) / n for j in range(n)]
    x_true = [math.sin(math.pi * tj) for tj in t]
    y_exact = la.matvec(a, x_true)
    rng = random.Random(15)
    e = [rng.gauss(0, 1) for _ in range(n)]
    delta = 1e-2
    scale = delta / la.norm2(e)
    y = [p + scale * q for p, q in zip(y_exact, e)]
    errs = [la.norm2([p - q for p, q in zip(tsvd_from_svd(u, s, v, y, k), x_true)]) for k in range(n + 1)]
    best = min(range(n + 1), key=lambda k: errs[k])
    assert 0 < best < n
    assert errs[n] > 2.0 * errs[best]
    res, _ = tsvd_path(u, s, y)
    k_dp = discrepancy_index(res, delta, tau=1.1)
    assert k_dp is not None
    assert res[k_dp] <= 1.1 * delta and (k_dp == 0 or res[k_dp - 1] > 1.1 * delta)
    assert errs[k_dp] <= 3.0 * errs[best]


def worst_case_error(sigma, delta, nu, rho):
    """TSVD error for the worst pair of a source element and a noise vector of a diagonal problem.

    k is the largest index with sigma_k >= delta^(1/(2 nu + 1)). The exact solution is
    rho sigma_{k+1}^(2 nu) e_{k+1} (it satisfies the source condition with ||w|| = rho)
    and the noise is delta e_k. Returns (error, k).
    """
    p = len(sigma)
    u = la.eye(p)
    level = delta ** (1.0 / (2 * nu + 1))
    k = max(i + 1 for i in range(p) if sigma[i] >= level)
    x_true = [0.0] * p
    x_true[k] = rho * sigma[k] ** (2 * nu)
    y = [sigma[i] * x_true[i] for i in range(p)]
    y[k - 1] += delta
    x = tsvd_from_svd(u, sigma, u, y, k)
    return la.norm2([p_ - q for p_, q in zip(x, x_true)]), k


def test_convergence_rate() -> None:
    sigma = [1.0 / i for i in range(1, 161)]
    deltas = [1e-1, 1e-2, 1e-3, 1e-4]
    rho = 1.0
    for nu in (0.5, 1.0):
        rate = 2 * nu / (2 * nu + 1)
        errs = []
        for d in deltas:
            err, _ = worst_case_error(sigma, d, nu, rho)
            assert err <= (1 + rho) * d ** rate + 1e-15
            errs.append(err)
        xs = [math.log(d) for d in deltas]
        ys = [math.log(e) for e in errs]
        mx, my = sum(xs) / len(xs), sum(ys) / len(ys)
        slope = sum((p - mx) * (q - my) for p, q in zip(xs, ys)) / sum((p - mx) ** 2 for p in xs)
        assert abs(slope - rate) < 0.15


def test_rate_bound_random_noise() -> None:
    # Error <= delta / sigma_k + rho sigma_{k+1}^(2 nu) for any noise with ||e|| <= delta.
    rng = random.Random(16)
    p, nu, rho = 60, 0.5, 1.0
    sigma = [1.0 / i for i in range(1, p + 1)]
    u = la.eye(p)
    w = [rng.gauss(0, 1) for _ in range(p)]
    wn = la.norm2(w)
    w = [rho * t / wn for t in w]
    x_true = [sigma[i] ** (2 * nu) * w[i] for i in range(p)]
    for d in (1e-2, 1e-3, 1e-4):
        e = [rng.gauss(0, 1) for _ in range(p)]
        en = la.norm2(e)
        y = [sigma[i] * x_true[i] + d * e[i] / en for i in range(p)]
        k = max(i + 1 for i in range(p) if sigma[i] >= d ** (1.0 / (2 * nu + 1)))
        x = tsvd_from_svd(u, sigma, u, y, k)
        err = la.norm2([a - b for a, b in zip(x, x_true)])
        bound = d / sigma[k - 1] + (rho * sigma[k] ** (2 * nu) if k < p else 0.0)
        assert err <= bound + 1e-14
        assert bound <= (1 + rho) * d ** (2 * nu / (2 * nu + 1)) + 1e-15

History

Erhard Schmidt proved in 1907 that the truncated singular expansion gives the best approximation of an integral operator by one of finite rank. Eckart and Young proved the matrix version in 1936, and Mirsky extended it to all unitarily invariant norms in 1960. After Golub and Kahan made the SVD computable in 1965, Hanson (1971) and others solved discretized first-kind integral equations from their leading singular components. Hansen (1987) analyzed TSVD as a regularization method, gave its perturbation bounds and showed that under the discrete Picard condition it gives solutions close to those of Tikhonov regularization.

References

  1. Per Christian Hansen, The truncated SVD as a method for regularization, BIT 27(4), 1987, 534 to 553, the TSVD solution, its perturbation bounds, and its relation to Tikhonov regularization
  2. Carl Eckart and Gale Young, The approximation of one matrix by another of lower rank, Psychometrika 1(3), 1936, 211 to 218, the best approximation of lower rank by truncating the canonical (singular value) form
  3. L. Mirsky, Symmetric gauge functions and unitarily invariant norms, Quarterly Journal of Mathematics 11(1), 1960, 50 to 59, the extension of the best low-rank approximation to every unitarily invariant norm
  4. Richard J. Hanson, A numerical method for solving Fredholm integral equations of the first kind using singular values, SIAM Journal on Numerical Analysis 8(3), 1971, 616 to 622, the solution of a discretized first-kind equation from its leading singular components
  5. Per Christian Hansen, Rank-Deficient and Discrete Ill-Posed Problems, Numerical Aspects of Linear Inversion, SIAM, 1998, Chapter 3 (numerical rank and truncated SVD) and Chapter 7 (the discrepancy principle)
  6. Heinz W. Engl, Martin Hanke and Andreas Neubauer, Regularization of Inverse Problems, Kluwer, 1996, Chapters 3 and 4 (truncated singular value expansion as a regularization method, its infinite qualification)

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.worst
  • a full proof of space.extra
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