Algorithm Search⌘K

Algorithmcore

Simultaneous iterative reconstruction technique

Also called SIRT.

Update all pixels at once by the back projection of all ray residuals, scaled by the row and column sums of the system matrix. It is a weighted Landweber iteration.

Time
O(K a d n) totalO(a d n) per_iteration
Space
O(a d + n^2) extra
Where
K = the number of iterations; a = the number of projection angles; d = the number of detector bins; n = the side of the n x n image
Properties
deterministicnot in placeiterativelinear in dataorder independentiterative
Origin
Peter Gilbert, 1972

SIRT reconstructs an image from the data yy of the discrete model y=Ax+ey = A x + e of tomography, where x∈RNx \in \mathbb{R}^N holds the N=n2N = n^2 pixel values, y∈Rmy \in \mathbb{R}^m holds the mm ray sums, and AA is a sparse m×Nm \times N matrix with nonnegative entries aija_{ij}, the weight of pixel jj in ray ii. Each iteration computes the residuals of all rays, divides each by the sum of its row, back-projects them, divides each pixel by the sum of its column, and adds the result: x←x+λCATR(y−Ax)x \leftarrow x + \lambda C A^T R (y - A x) with R=diag⁡(1/ri)R = \operatorname{diag}(1/r_i) and C=diag⁡(1/cj)C = \operatorname{diag}(1/c_j). It is the Landweber iteration for the scaled system R1/2AC1/2R^{1/2} A C^{1/2}, which has norm exactly 1. So it converges for 0<λ<20 < \lambda < 2 to a weighted least squares solution, and with noisy data it needs a stopping rule. It differs from ART, which corrects the image after each single ray, and from SART, which corrects it after the rays of one view.

In plain words

Each ray gives one equation: the weighted sum of the pixel values along the ray must equal the measured value. SIRT starts from an image, often all zeros, and computes what each ray would measure. The difference to the measurement is the error of that ray. Divide each error by the total weight of its ray, so that a long ray does not count more than a short one, and spread it back over the pixels of the ray.

Now each pixel holds the sum of the corrections that its rays want. Divide this sum by the total weight of the pixel, so that the pixel takes the average correction. Add this average, times a factor λ\lambda, and repeat. Every pixel listens to all rays at once, so the image changes smoothly and the order of the rays does not matter.

The problem

Given a nonnegative m×Nm \times N matrix AA and data y∈Rmy \in \mathbb{R}^m, find xx that fits Ax≈yA x \approx y. Write ri=∑jaijr_i = \sum_j a_{ij} for the row sums and cj=∑iaijc_j = \sum_i a_{ij} for the column sums, and assume all are positive (a ray that misses the image, or a pixel that no ray meets, is removed first; the code gives it the weight 0). The weighted norm of a residual is ∥v∥R2=∑ivi2/ri\|v\|_R^2 = \sum_i v_i^2 / r_i. With exact consistent data, the target is a solution of Ax=yA x = y. With inconsistent data, SIRT solves the weighted least squares problem

min⁡x∥y−Ax∥R2,\min_x \|y - A x\|_R^2,

and among its solutions it picks the one closest to the start x0x_0 in the norm ∥v∥C−12=∑jcjvj2\|v\|_{C^{-1}}^2 = \sum_j c_j v_j^2. In tomography the data are noisy and the matrix is ill-conditioned, so this limit is not the goal: the useful result is an early iterate.

The algorithm

  1. SIRT(A, y, λ, K, x0) ▷ 0 < λ < 2; δ is the noise level if known
  2. 1r_i ← Σ_j a_ij, c_j ← Σ_i a_ij; R ← diag(1/r_i), C ← diag(1/c_j)
  3. 2x ← x0
  4. 3for k ← 1 to K do
  5. 4e ← y - A x; if δ is known and ‖e‖ ≤ τ δ then return x
  6. 5e_i ← e_i / r_i for each ray i
  7. 6g ← A^T e ▷ the back projection of the scaled residuals
  8. 7x_j ← x_j + λ g_j / c_j for each pixel j
  9. 8(optional) x_j ← max(x_j, 0)
  10. 9return x

Line L4 is one forward projection and line L6 one back projection, so the cost of an iteration is that of two passes over the nonzero entries of AA. Any projector gives the matrix: Siddon's algorithm, Joseph's projector or the distance-driven projector. The method needs ATA^T in line L6, not an approximate back projector. Line L4 also tests the discrepancy principle with a fixed τ>1\tau > 1. Line L8 keeps the image nonnegative. With it, the method is a projected iteration and the linear analysis below no longer applies, but it still converges (see Correctness).

Example

Take a 2×22 \times 2 image x=(x0,x1,x2,x3)x = (x_0, x_1, x_2, x_3) in row-major order, the true values (1,2,3,4)(1, 2, 3, 4), and five rays with weights 0 or 1: the two rows, the two columns, and the diagonal through x0x_0 and x3x_3.

ray pixels yiy_i rir_i
row 0 x0,x1x_0, x_1 3 2
row 1 x2,x3x_2, x_3 7 2
column 0 x0,x2x_0, x_2 4 2
column 1 x1,x3x_1, x_3 6 2
diagonal x0,x3x_0, x_3 5 2

The column sums are c=(3,2,2,3)c = (3, 2, 2, 3), because x0x_0 and x3x_3 lie on three rays and the others on two. Start from x=0x = 0 with λ=1\lambda = 1. Line L5 gives e/r=(3/2,7/2,2,3,5/2)e / r = (3/2, 7/2, 2, 3, 5/2). Line L6 gives g0=3/2+2+5/2=6g_0 = 3/2 + 2 + 5/2 = 6, g1=3/2+3=9/2g_1 = 3/2 + 3 = 9/2, g2=7/2+2=11/2g_2 = 7/2 + 2 = 11/2 and g3=7/2+3+5/2=9g_3 = 7/2 + 3 + 5/2 = 9. Line L7 divides by cc:

iteration x0x_0 x1x_1 x2x_2 x3x_3 ∥y−Ax∥R2\|y - A x\|_R^2
0 0 0 0 0 135/2135/2
1 2 9/49/4 11/411/4 3 17/817/8
2 5/35/3 17/817/8 23/823/8 10/310/3 265/288265/288
3 13/913/9 33/1633/16 47/1647/16 32/932/9 4177/103684177/10368

The weighted residual falls at each step, as the theory says. The five rays determine the image, so the iterates converge to (1,2,3,4)(1, 2, 3, 4); after 400 steps the error is below 10−910^{-9} for λ=0.5\lambda = 0.5, 11 and 1.91.9. The scaled matrix B=R1/2AC1/2B = R^{1/2} A C^{1/2} has the singular values 11, 1/21/\sqrt{2}, 1/31/\sqrt{3} and 1/61/\sqrt{6}, so the error of the slowest component shrinks by the factor 1−1/6=5/61 - 1/6 = 5/6 per step for λ=1\lambda = 1. The test file checks all values of the table with fractions.Fraction.

A larger case: a disk of radius 0.6 on a 16×1616 \times 16 grid, 12 angles in [0,π)[0, \pi), 23 bins, and the pixel-driven matrix of the shared helper. With exact data, the relative error ∥xk−x∥/∥x∥\|x_k - x\|/\|x\| is 0.630.63 after 1 step, 0.240.24 after 10, 0.120.12 after 100 and 0.0940.094 after 400. With Gaussian noise of standard deviation 22 percent of the largest ray sum (seed 5), the error is smallest, 0.1810.181, at k=101k = 101, and it grows to 0.2070.207 at k=400k = 400: this is semi-convergence. The discrepancy principle with τ=1.01\tau = 1.01 stops at k=24k = 24 with the error 0.2040.204. These numbers are measurements of this setup, not properties of the method.

Correctness

Put B=R1/2AC1/2B = R^{1/2} A C^{1/2}, b=R1/2yb = R^{1/2} y and x=C1/2zx = C^{1/2} z. Then line L7 reads z←z+λBT(b−Bz)z \leftarrow z + \lambda B^T (b - B z), the Landweber iteration for BB with the step ω=λ\omega = \lambda. Two facts make the theory of Landweber apply:

  • ∥B∥2=1\|B\|_2 = 1. By the Cauchy-Schwarz inequality, (∑jaijcj−1/2zj)2≤ri∑jaijcj−1zj2\big(\sum_j a_{ij} c_j^{-1/2} z_j\big)^2 \le r_i \sum_j a_{ij} c_j^{-1} z_j^2, and summing over ii with the weights 1/ri1/r_i gives ∥Bz∥2≤∑jzj2=∥z∥2\|B z\|^2 \le \sum_j z_j^2 = \|z\|^2. The vector z=(cj)z = (\sqrt{c_j}) gives Bz=(ri)B z = (\sqrt{r_i}), and ∑iri=∑jcj\sum_i r_i = \sum_j c_j, so the bound is attained.
  • So 0<λ<2=2/∥B∥20 < \lambda < 2 = 2/\|B\|^2 is the Landweber condition. With B=∑kσkukvkTB = \sum_k \sigma_k u_k v_k^T, the iterate from z0=0z_0 = 0 is zk=∑k[1−(1−λσk2)k](ukTb/σk)vkz_k = \sum_k [1 - (1 - \lambda\sigma_k^2)^k] (u_k^T b / \sigma_k) v_k: the spectral filter factors of Landweber.

Each factor 1−λσ21 - \lambda\sigma^2 lies in (−1,1)(-1, 1) for 0<σ≤10 < \sigma \le 1, so zkz_k converges to B†bB^\dagger b plus the part of z0z_0 in the null space of BB. In the variable xx this is the weighted least squares solution of the problem section, closest to x0x_0 in the C−1C^{-1} norm. The weighted residual ∥y−Axk∥R=∥b−Bzk∥\|y - A x_k\|_R = \|b - B z_k\| does not increase, because b−Bzk+1=(I−λBBT)(b−Bzk)b - B z_{k+1} = (I - \lambda B B^T)(b - B z_k) and the eigenvalues of I−λBBTI - \lambda B B^T lie in (−1,1](-1, 1]. For λ>2\lambda > 2 the factor ∣1−λ∣>1|1 - \lambda| > 1 on the top singular value, and from x0=0x_0 = 0 the iteration diverges whenever ∑iyi≠0\sum_i y_i \ne 0, because the top singular vector is (ri)(\sqrt{r_i}) up to scaling. With line L8, the step is a projected gradient step for 12∥b−Bz∥2\frac{1}{2}\|b - B z\|^2 over z≥0z \ge 0, because CC is diagonal and positive, so x≥0x \ge 0 if and only if z≥0z \ge 0, and the projection onto the orthant is the clipping. A projected gradient step with a step size below 2/∥B∥22/\|B\|^2 converges to a minimizer on the orthant when one exists (projected gradient descent). The full proofs are in proofs/correctness.md.

Jiang and Wang (2003) proved the convergence of this simultaneous update for nonnegative AA from any start, under the name SART; see SART for the form that works one view at a time.

Proof: Correctness and convergence of SIRTfull

We use the notation of the page. AA is an m×Nm \times N matrix with aij≥0a_{ij} \ge 0, all row sums ri=∑jaijr_i = \sum_j a_{ij} and all column sums cj=∑iaijc_j = \sum_i a_{ij} are positive (a zero row or column gets the weight 0 in the code, which is the same as removing it), R=diag⁡(1/ri)R = \operatorname{diag}(1/r_i) and C=diag⁡(1/cj)C = \operatorname{diag}(1/c_j). Without line L8, lines L4 to L7 compute

xk+1=xk+λ CATR (y−Axk).(1)x_{k+1} = x_k + \lambda\, C A^T R\,(y - A x_k). \tag{1}

This is a direct reading of the lines: L4 forms y−Axky - A x_k, L5 multiplies by RR, L6 by ATA^T, and L7 by λC\lambda C and adds. We work in exact arithmetic.

The change of variables. Put

B=R1/2AC1/2,b=R1/2y,x=C1/2z.B = R^{1/2} A C^{1/2}, \qquad b = R^{1/2} y, \qquad x = C^{1/2} z.

Multiply (1) on the left by C−1/2C^{-1/2}:

zk+1=zk+λ C1/2ATR (y−AC1/2zk)=zk+λ BT(b−Bzk).(2)z_{k+1} = z_k + \lambda\, C^{1/2} A^T R\,(y - A C^{1/2} z_k) = z_k + \lambda\, B^T (b - B z_k). \tag{2}

So SIRT is the Landweber iteration for the system Bz=bB z = b with the step λ\lambda. Also ∥y−Ax∥R2=∑i(y−Ax)i2/ri=∥b−Bz∥2\|y - A x\|_R^2 = \sum_i (y - A x)_i^2 / r_i = \|b - B z\|^2 and ∥x−x′∥C−12=∑jcj(xj−xj′)2=∥z−z′∥2\|x - x'\|_{C^{-1}}^2 = \sum_j c_j (x_j - x'_j)^2 = \|z - z'\|^2.

Lemma 1 (the norm). ∥B∥2=1\|B\|_2 = 1.

Proof. Let z∈RNz \in \mathbb{R}^N. For each row ii, the Cauchy-Schwarz inequality with the weights aij≥0a_{ij} \ge 0 gives

(∑jaij cj−1/2zj)2≤(∑jaij)(∑jaij cj−1zj2)=ri∑jaij cj−1zj2.\Big(\sum_j a_{ij}\, c_j^{-1/2} z_j\Big)^2 \le \Big(\sum_j a_{ij}\Big)\Big(\sum_j a_{ij}\, c_j^{-1} z_j^2\Big) = r_i \sum_j a_{ij}\, c_j^{-1} z_j^2.

So (Bz)i2=ri−1(∑jaijcj−1/2zj)2≤∑jaijcj−1zj2(B z)_i^2 = r_i^{-1}\big(\sum_j a_{ij} c_j^{-1/2} z_j\big)^2 \le \sum_j a_{ij} c_j^{-1} z_j^2. Sum over ii and use ∑iaij=cj\sum_i a_{ij} = c_j:

∥Bz∥2≤∑jcj−1zj2∑iaij=∥z∥2.\|B z\|^2 \le \sum_j c_j^{-1} z_j^2 \sum_i a_{ij} = \|z\|^2.

So ∥B∥≤1\|B\| \le 1. For z=(cj)jz = (\sqrt{c_j})_j, (Bz)i=ri−1/2∑jaij=ri(B z)_i = r_i^{-1/2} \sum_j a_{ij} = \sqrt{r_i}, so ∥Bz∥2=∑iri=∑i,jaij=∑jcj=∥z∥2>0\|B z\|^2 = \sum_i r_i = \sum_{i,j} a_{ij} = \sum_j c_j = \|z\|^2 > 0. So ∥B∥=1\|B\| = 1. □\square

Theorem 1 (filter factors). Let B=∑q=1pσquqvqTB = \sum_{q=1}^{p} \sigma_q u_q v_q^T be a singular value decomposition with σq>0\sigma_q > 0, and let P0P_0 be the orthogonal projector onto the null space of BB. Then for every k≥0k \ge 0,

zk=P0z0+∑q=1p[(1−λσq2)k vqTz0+(1−(1−λσq2)k)uqTbσq]vq.z_k = P_0 z_0 + \sum_{q=1}^{p}\Big[(1 - \lambda\sigma_q^2)^k\, v_q^T z_0 + \big(1 - (1 - \lambda\sigma_q^2)^k\big)\frac{u_q^T b}{\sigma_q}\Big] v_q.

Proof. By (2), zk+1=(I−λBTB)zk+λBTbz_{k+1} = (I - \lambda B^T B) z_k + \lambda B^T b. The vectors vqv_q and the null space of BB are invariant under I−λBTBI - \lambda B^T B, with the factor 1−λσq21 - \lambda\sigma_q^2 on vqv_q and the factor 1 on the null space, and BTb=∑qσq(uqTb)vqB^T b = \sum_q \sigma_q (u_q^T b) v_q has no part in the null space. So P0zk+1=P0zkP_0 z_{k+1} = P_0 z_k and, with γk=vqTzk\gamma_k = v_q^T z_k and ρ=1−λσq2\rho = 1 - \lambda\sigma_q^2, γk+1=ργk+λσq(uqTb)\gamma_{k+1} = \rho\gamma_k + \lambda\sigma_q (u_q^T b). The solution of this recursion is γk=ρkγ0+(1−ρk)(uqTb)/σq\gamma_k = \rho^k \gamma_0 + (1 - \rho^k)(u_q^T b)/\sigma_q, because (1−ρ)/σq=λσq(1 - \rho)/\sigma_q = \lambda\sigma_q. □\square

Theorem 2 (convergence). If 0<λ<20 < \lambda < 2, then xkx_k converges for every yy and every x0x_0. The limit x∗x^* minimizes ∥y−Ax∥R\|y - A x\|_R, and among all minimizers it is the unique one closest to x0x_0 in the C−1C^{-1} norm. In particular, if Ax=yA x = y has a solution, x∗x^* is a solution, and from x0=0x_0 = 0 with AA of full row rank,

x∗=CAT(ACAT)−1y.x^* = C A^T (A C A^T)^{-1} y.

Proof. By Lemma 1, 0<σq≤10 < \sigma_q \le 1, so −1<1−λσq2<1-1 < 1 - \lambda\sigma_q^2 < 1 and (1−λσq2)k→0(1 - \lambda\sigma_q^2)^k \to 0. By Theorem 1, zk→z∗=P0z0+B†bz_k \to z^* = P_0 z_0 + B^\dagger b. The set of minimizers of ∥b−Bz∥\|b - B z\| is B†b+null⁡(B)B^\dagger b + \operatorname{null}(B), and B†bB^\dagger b lies in the range of BTB^T, which is orthogonal to the null space. For a minimizer z=B†b+wz = B^\dagger b + w with w∈null⁡(B)w \in \operatorname{null}(B), Pythagoras gives ∥z−z0∥2=∥B†b−(I−P0)z0∥2+∥w−P0z0∥2\|z - z_0\|^2 = \|B^\dagger b - (I - P_0) z_0\|^2 + \|w - P_0 z_0\|^2, which is smallest exactly for w=P0z0w = P_0 z_0, that is for z=z∗z = z^*. Map back with x=C1/2zx = C^{1/2} z, which carries the two norms as shown above. If Ax=yA x = y is solvable, the minimum of the residual is 0. For full row rank, the minimizers of ∥z−0∥\|z - 0\| subject to Bz=bB z = b give z∗=BT(BBT)−1bz^* = B^T (B B^T)^{-1} b, and C1/2BT(BBT)−1b=CATR1/2(R1/2ACATR1/2)−1R1/2y=CAT(ACAT)−1yC^{1/2} B^T (B B^T)^{-1} b = C A^T R^{1/2} (R^{1/2} A C A^T R^{1/2})^{-1} R^{1/2} y = C A^T (A C A^T)^{-1} y. □\square

Theorem 3 (the weighted residual). For 0<λ≤20 < \lambda \le 2, ∥y−Axk+1∥R≤∥y−Axk∥R\|y - A x_{k+1}\|_R \le \|y - A x_k\|_R.

Proof. From (2), b−Bzk+1=(I−λBBT)(b−Bzk)b - B z_{k+1} = (I - \lambda B B^T)(b - B z_k). The matrix BBTB B^T is symmetric with eigenvalues in [0,1][0, 1] by Lemma 1, so I−λBBTI - \lambda B B^T is symmetric with eigenvalues in [1−λ,1]⊆[−1,1][1 - \lambda, 1] \subseteq [-1, 1], and its norm is at most 1. □\square

Theorem 4 (the bound on lambda is sharp). If λ>2\lambda > 2, x0=0x_0 = 0 and ∑iyi≠0\sum_i y_i \ne 0, then ∥xk∥→∞\|x_k\| \to \infty.

Proof. Let S=(∑iri)1/2=(∑jcj)1/2S = (\sum_i r_i)^{1/2} = (\sum_j c_j)^{1/2}, u1=(ri)i/Su_1 = (\sqrt{r_i})_i / S and v1=(cj)j/Sv_1 = (\sqrt{c_j})_j / S. Since Bij=aij/ricjB_{ij} = a_{ij}/\sqrt{r_i c_j}, we get (Bv1)i=∑jaij/(ri S)=ri/S(B v_1)_i = \sum_j a_{ij} / (\sqrt{r_i}\, S) = \sqrt{r_i}/S and (BTu1)j=∑iaij/(cj S)=cj/S(B^T u_1)_j = \sum_i a_{ij} / (\sqrt{c_j}\, S) = \sqrt{c_j}/S. So Bv1=u1B v_1 = u_1 and BTu1=v1B^T u_1 = v_1, a singular pair with σ=1\sigma = 1, and we may choose an SVD that contains it. By Theorem 1 with z0=0z_0 = 0, the coefficient of v1v_1 in zkz_k is (1−ρk) u1Tb(1 - \rho^k)\, u_1^T b with ρ=1−λ<−1\rho = 1 - \lambda < -1. Here u1Tb=∑iri yi/ri/S=∑iyi/S≠0u_1^T b = \sum_i \sqrt{r_i}\, y_i / \sqrt{r_i} / S = \sum_i y_i / S \ne 0, so the coefficient grows without bound, and so does ∥zk∥\|z_k\|. Since xj=zj/cjx_j = z_j / \sqrt{c_j}, ∥xk∥≥∥zk∥/max⁡jcj→∞\|x_k\| \ge \|z_k\| / \max_j \sqrt{c_j} \to \infty. □\square

So for nonnegative data that are not all zero, SIRT from x0=0x_0 = 0 diverges for every λ>2\lambda > 2. For λ=2\lambda = 2 the same coefficient oscillates between 00 and 2u1Tb2 u_1^T b and does not converge.

Theorem 5 (the nonnegative variant). With line L8, and 0<λ<20 < \lambda < 2, the iterates converge to a minimizer of ∥y−Ax∥R\|y - A x\|_R over x≥0x \ge 0.

Proof. Since C1/2C^{1/2} is diagonal with positive entries, x≥0x \ge 0 if and only if z≥0z \ge 0, and clipping xx at 0 is the same as clipping zz at 0, which is the Euclidean projection onto the orthant. So in the variable zz, lines L4 to L8 are

zk+1=Π≥0(zk−λ∇f(zk)),f(z)=12∥b−Bz∥2,z_{k+1} = \Pi_{\ge 0}\big(z_k - \lambda \nabla f(z_k)\big), \qquad f(z) = \tfrac{1}{2}\|b - B z\|^2,

the projected gradient method for the convex function ff over a closed convex set. The gradient ∇f(z)=BT(Bz−b)\nabla f(z) = B^T(B z - b) is Lipschitz with the constant L=∥B∥2=1L = \|B\|^2 = 1 (Lemma 1). The function ff is a convex quadratic and bounded below, so it attains its minimum on the orthant (a convex quadratic bounded below on a polyhedron attains its infimum, by the Frank-Wolfe theorem). For a step in (0,2/L)(0, 2/L), the projected gradient method on a convex function with an LL-Lipschitz gradient converges to a minimizer whenever one exists (the iteration is an averaged operator, and the Krasnoselskii-Mann theorem applies). Map back with x=C1/2zx = C^{1/2} z. □\square

Corollary (the discrepancy stop). Let 0<λ<20 < \lambda < 2, let x∗x^* be the limit of Theorem 2 or Theorem 5, and let ∥y−Ax∗∥<τδ\|y - A x^*\| < \tau\delta. Then the test of line L4 succeeds after a finite number of steps.

Proof. The map x↦∥y−Ax∥x \mapsto \|y - A x\| is continuous and xk→x∗x_k \to x^*, so ∥y−Axk∥→∥y−Ax∗∥<τδ\|y - A x_k\| \to \|y - A x^*\| < \tau\delta, and some finite kk passes the test. □\square

The hypothesis is needed. Line L4 tests the plain norm of the residual, while SIRT minimizes the RR-weighted norm, so ∥y−Ax∗∥\|y - A x^*\| can exceed ∥e∥\|e\| even when y=Ax†+ey = A x^\dagger + e. If all row sums are equal, the two norms differ by a constant factor and the limit minimizes the plain residual too, so ∥y−Ax∗∥≤∥e∥≤δ<τδ\|y - A x^*\| \le \|e\| \le \delta < \tau\delta for every τ>1\tau > 1 (with clipping, this needs x†≥0x^\dagger \ge 0). The convergence rate of the stopping index under a source condition is a result on the Landweber iteration for BB; see the page.

Cost. Line L1 reads each nonzero entry of AA once. In each iteration, line L4 reads each nonzero entry once, line L6 reads each nonzero entry of a row with ei≠0e_i \ne 0 once, and lines L5, L7 and L8 take O(m)O(m) and O(N)O(N) time. So one iteration costs O(nnz⁡(A)+m+N)O(\operatorname{nnz}(A) + m + N) time and O(m+N)O(m + N) extra space. For a ray-driven projector of an n×nn \times n image with aa angles of dd bins, nnz⁡(A)=O(adn)\operatorname{nnz}(A) = O(a d n), m=adm = a d and N=n2N = n^2, so one iteration costs O(adn+n2)O(a d n + n^2), which is O(adn)O(a d n) when ad≥na d \ge n, as in any scan that can determine the image. □\square

Complexity

In the real-RAM model, with aa angles of dd bins each, so m=adm = a d rays, and an n×nn \times n image:

  • Line L1 takes one pass over the nonzero entries of AA. A ray-driven projector has O(n)O(n) entries per ray, so nnz⁡(A)=O(adn)\operatorname{nnz}(A) = O(a d n).
  • Lines L4 and L6 are one forward and one back projection, O(adn)O(a d n) each. Lines L5 and L7 take O(ad)O(a d) and O(n2)O(n^2).

So one iteration costs O(adn+n2)O(a d n + n^2) time, which is O(adn)O(a d n) since ad≥n2≥na d \ge n^2 \ge n in any scan that can determine the image. It needs O(ad+n2)O(a d + n^2) extra space, and KK iterations cost O(Kadn)O(K a d n). With a matrix-free projector, count one application of AA and one of ATA^T per iteration. The number of iterations is the regularization parameter. With noise level δ\delta, the discrepancy principle and the source condition of Landweber for BB in the EHN form z†=(BTB)νwz^\dagger = (B^T B)^\nu w, the stopping index is O(δ−2/(2ν+1))O(\delta^{-2/(2\nu+1)}) (EHN chapter 6). A measured iteration count, such as the k=24k = 24 above, is not a bound.

Properties

  • Order independent. All rays act at once, so the result does not depend on the order of the rays, and the iteration is fully parallel over rays and over pixels. ART and SART depend on the order.
  • Weighted Landweber. SIRT is Landweber on BB; the theory of the Landweber iteration (filter factors, infinite qualification, order optimal rates with the discrepancy principle) carries over, in the weighted norms.
  • Slow. Each iteration damps the component of singular value σ\sigma by 1−λσ21 - \lambda\sigma^2. The small singular values of a tomography matrix need many iterations. ART and SART reach the same image quality in fewer passes through the data, at the price of sequential work.
  • Smooth iterates and semi-convergence. The early iterates hold only the components with large σ\sigma, which are smooth images. With noise the error first falls and then rises. Stopping early is the regularization.
  • Linear in the data. Without line L8, xkx_k is a fixed linear function of yy and x0x_0, so its noise can be analyzed exactly. With line L8 it is not linear.

Variants and improvements

  • Cimmino's method (1938) projects onto all hyperplanes ⟨ai,x⟩=yi\langle a_i, x\rangle = y_i and averages: x←x+λ∑iwiyi−⟨ai,x⟩∥ai∥2aix \leftarrow x + \lambda \sum_i w_i \frac{y_i - \langle a_i, x\rangle}{\|a_i\|^2} a_i. It is the same scheme with ∥ai∥2\|a_i\|^2 in place of rir_i and no column scaling.
  • Plain Landweber uses R=C=IR = C = I and needs λ<2/∥A∥2\lambda < 2/\|A\|^2, which requires an estimate of the norm, for example by power iteration. The scaling of SIRT gives the bound ∥B∥=1\|B\| = 1 for free.
  • SART applies the same update with the rays of one view at a time. One pass through all views is then a sequence of aa small SIRT steps, and it converges much faster in practice. The ordered subsets form takes a group of views at a time.
  • Krylov methods. CGLS applied to BB minimizes the same weighted residual over a Krylov subspace. It usually needs far fewer iterations than SIRT for the same residual, but its iterates depend on the data in a nonlinear way.
  • Box constraints. Line L8 can clip to any box [0,u][0, u]; the projected iteration still converges, by the same argument.

When to use it

Use SIRT for tomography when the data are noisy or the angles are few, when a smooth and stable result matters more than speed, and when the forward and back projections run in parallel, for example on a GPU. Its iterates are linear in the data and do not depend on the ray order, which makes it easy to analyze. Use SART or ART when fast convergence per pass matters more than parallel work. For complete data with many angles, filtered back-projection is far cheaper. For few angles of a piecewise constant object, add a total variation step, as in ASD-POCS.

Pitfalls

  • Zero rows or columns. A ray that misses the image has ri=0r_i = 0, and a pixel outside all rays has cj=0c_j = 0. Division by zero follows unless they are removed or given the weight 0.
  • An unmatched back projector. If line L6 uses a back projector that is not ATA^T, the iteration is not Landweber for any matrix, ∥B∥≤1\|B\| \le 1 no longer follows, and the method can diverge or converge to a wrong point.
  • No stopping rule. With noisy data the iterates converge to the weighted least squares solution, which is dominated by noise. Run to convergence only with exact data. Stop by the discrepancy principle if the noise level is known; other rules are heuristics.
  • λ≥2\lambda \ge 2. The bound is sharp, because ∥B∥=1\|B\| = 1 exactly. λ=2\lambda = 2 gives a component that does not decay, and λ>2\lambda > 2 diverges.
  • Confusing the norms. The limit minimizes the RR-weighted residual, not the plain residual, and it is closest to x0x_0 in the C−1C^{-1} norm. A test against a plain least squares solution fails.
  • Expecting monotone error. Only the weighted residual is monotone. The error against the true image is not monotone with noise.

Implementations

The Python code takes the system matrix as sparse rows of (column, weight) pairs, as built by the shared helper imgkit.parallel_beam_matrix or by any projector page, and works with float or fractions.Fraction data. The tests check the worked example exactly, the convergence to the solution of a consistent system, ∥B∥=1\|B\| = 1, the limit against the weighted normal equations and against the minimum C−1C^{-1} norm solution, the filter factors against an SVD of BB, the monotone weighted residual, the divergence for λ>2\lambda > 2, and a disk phantom with the discrepancy stop.

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
sirt.py 71 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sirt/. The authors are listed in prov/KFR7FZ.jsonl.
"""SIRT, the simultaneous iterative reconstruction technique.

The system matrix A is given as sparse rows: row i is a list of (column,
weight) pairs with nonnegative weights, as returned by
imgkit.parallel_beam_matrix. One iteration is

    x <- x + lam * C A^T R (y - A x),

with R = diag(1 / r_i), r_i the sum of row i, and C = diag(1 / c_j), c_j the
sum of column j. A zero row or column gets the weight 0. The code works with
float or with fractions.Fraction data.
"""

import math


def row_col_sums(rows, ncols):
    """The row sums r_i and the column sums c_j of a sparse matrix."""
    r = [sum(w for _, w in row) for row in rows]
    c = [0] * ncols
    for row in rows:
        for j, w in row:
            c[j] += w
    return r, c


def _inv(v):
    return [1 / t if t != 0 else 0 * t for t in v]


def sirt(rows, ncols, y, lam=1.0, iters=100, x0=None, nonneg=False, delta=None, tau=1.01, callback=None):
    """Run SIRT and return (x, k), with k the number of updates done.

    rows: the sparse rows of A; y: the data; lam: the relaxation, 0 < lam < 2;
    x0: the start (zero by default); nonneg: clip to x >= 0 after each step
    (this is then a projected iteration, outside the linear theory);
    delta: the noise level, to stop by the discrepancy principle at the first
    k with ||y - A x_k|| <= tau delta; callback(k, x) is called after each step.
    """
    r, c = row_col_sums(rows, ncols)
    rinv, cinv = _inv(r), _inv(c)  # @line L1
    x = list(x0) if x0 is not None else [0 * lam] * ncols  # @line L2
    for k in range(iters):  # @line L3
        e = [yi - sum(w * x[j] for j, w in row) for row, yi in zip(rows, y)]  # @line L4
        if delta is not None and math.sqrt(sum(t * t for t in e)) <= tau * delta:
            return x, k
        e = [ei * ri for ei, ri in zip(e, rinv)]  # @line L5
        g = [0 * lam] * ncols
        for row, ei in zip(rows, e):  # @line L6
            if ei != 0:
                for j, w in row:
                    g[j] += w * ei
        x = [xj + lam * cj * gj for xj, cj, gj in zip(x, cinv, g)]  # @line L7
        if nonneg:
            x = [xj if xj > 0 else 0 * xj for xj in x]  # @line L8
        if callback is not None:
            callback(k + 1, x)
    return x, iters  # @line L9


def weighted_residual(rows, y, x):
    """||y - A x||_R^2 = sum_i (y_i - (A x)_i)^2 / r_i over the rows with r_i > 0."""
    total = 0
    for row, yi in zip(rows, y):
        ri = sum(w for _, w in row)
        if ri != 0:
            e = yi - sum(w * x[j] for j, w in row)
            total += e * e / ri
    return total
test_sirt.py 141 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sirt/. The authors are listed in prov/KFR7FZ.jsonl.

import math
import random
from fractions import Fraction as F

import imgkit as ik
import imgla as la
from sirt import row_col_sums, sirt, weighted_residual

# The 2 x 2 example of the page: two row sums, two column sums, one diagonal.
A = [[1, 1, 0, 0], [0, 0, 1, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 0, 1]]
ROWS = [[(j, F(w)) for j, w in enumerate(r) if w] for r in A]
Y = [F(v) for v in (3, 7, 4, 6, 5)]


def _sparse(dense):
    return [[(j, w) for j, w in enumerate(r) if w != 0] for r in dense]


def _scaled(dense):
    """B = R^(1/2) A C^(1/2) as a dense float matrix, and the vectors r and c."""
    r, c = row_col_sums(_sparse(dense), len(dense[0]))
    b = [[float(a) / math.sqrt(r[i] * c[j]) for j, a in enumerate(row)] for i, row in enumerate(dense)]
    return b, r, c


def test_worked_example_exact() -> None:
    seen = []
    sirt(ROWS, 4, Y, lam=F(1), iters=3, callback=lambda k, x: seen.append(x))
    assert seen[0] == [F(2), F(9, 4), F(11, 4), F(3)]
    assert seen[1] == [F(5, 3), F(17, 8), F(23, 8), F(10, 3)]
    assert seen[2] == [F(13, 9), F(33, 16), F(47, 16), F(32, 9)]
    assert [weighted_residual(ROWS, Y, x) for x in seen] == [F(17, 8), F(265, 288), F(4177, 10368)]


def test_consistent_system_converges_to_the_solution() -> None:
    for lam in (0.5, 1.0, 1.9):
        x, _ = sirt(ROWS, 4, [float(v) for v in Y], lam=lam, iters=400)
        assert max(abs(a - b) for a, b in zip(x, (1, 2, 3, 4))) < 1e-9


def test_scaled_matrix_has_norm_one() -> None:
    rng = random.Random(3)
    for dense in (A, [[rng.random() for _ in range(5)] for _ in range(8)]):
        _, s, _ = la.svd(_scaled(dense)[0])
        assert abs(s[0] - 1.0) < 1e-12


def test_limit_is_the_weighted_least_squares_solution() -> None:
    rng = random.Random(4)
    m, n = 8, 5
    dense = [[rng.choice((0.0, rng.random())) + 0.05 for _ in range(n)] for _ in range(m)]
    y = [rng.uniform(0, 3) for _ in range(m)]
    rows = _sparse(dense)
    r, _ = row_col_sums(rows, n)
    # normal equations A^T R A x = A^T R y
    atra = [[sum(dense[i][p] * dense[i][q] / r[i] for i in range(m)) for q in range(n)] for p in range(n)]
    atry = [sum(dense[i][p] * y[i] / r[i] for i in range(m)) for p in range(n)]
    xs = la.solve(atra, atry)
    x, _ = sirt(rows, n, y, lam=1.5, iters=3000)
    assert max(abs(a - b) for a, b in zip(x, xs)) < 1e-8


def test_underdetermined_limit_has_minimal_weighted_norm() -> None:
    rng = random.Random(5)
    m, n = 3, 6
    dense = [[rng.random() for _ in range(n)] for _ in range(m)]
    y = [rng.uniform(1, 2) for _ in range(m)]
    rows = _sparse(dense)
    _, c = row_col_sums(rows, n)
    # x = C A^T (A C A^T)^(-1) y with C = diag(1 / c_j)
    aca = [[sum(dense[p][j] * dense[q][j] / c[j] for j in range(n)) for q in range(m)] for p in range(m)]
    u = la.solve(aca, y)
    xs = [sum(dense[i][j] * u[i] for i in range(m)) / c[j] for j in range(n)]
    x, _ = sirt(rows, n, y, lam=1.0, iters=3000)
    assert max(abs(a - b) for a, b in zip(x, xs)) < 1e-9


def test_filter_factors() -> None:
    rng = random.Random(6)
    m, n, k, lam = 7, 4, 9, 0.8
    dense = [[rng.random() for _ in range(n)] for _ in range(m)]
    y = [rng.uniform(-1, 1) for _ in range(m)]
    b, r, c = _scaled(dense)
    u, s, v = la.svd(b)
    bv = [yi / math.sqrt(ri) for yi, ri in zip(y, r)]
    z = [0.0] * n
    for q in range(n):
        f = 1.0 - (1.0 - lam * s[q] ** 2) ** k
        coef = f * sum(u[i][q] * bv[i] for i in range(m)) / s[q]
        for j in range(n):
            z[j] += coef * v[j][q]
    expect = [zj / math.sqrt(cj) for zj, cj in zip(z, c)]
    x, _ = sirt(_sparse(dense), n, y, lam=lam, iters=k)
    assert max(abs(a - e) for a, e in zip(x, expect)) < 1e-12


def test_weighted_residual_does_not_increase() -> None:
    rng = random.Random(7)
    m, n = 9, 6
    dense = [[rng.random() if rng.random() < 0.7 else 0.0 for _ in range(n)] for _ in range(m)]
    y = [rng.uniform(0, 2) for _ in range(m)]
    rows = _sparse(dense)
    for lam in (0.3, 1.0, 1.95):
        res = [weighted_residual(rows, y, [0.0] * n)]
        sirt(rows, n, y, lam=lam, iters=60, callback=lambda k, x: res.append(weighted_residual(rows, y, x)))
        assert all(b <= a * (1 + 1e-12) + 1e-15 for a, b in zip(res, res[1:]))


def test_relaxation_above_two_diverges() -> None:
    y = [3.0, 7.0, 4.0, 6.0, 5.1]
    x, _ = sirt(ROWS, 4, y, lam=2.2, iters=80)
    assert max(abs(t) for t in x) > 1e3


def test_phantom_reconstruction_and_discrepancy_stop() -> None:
    n, nbins = 16, 23
    angles = [k * math.pi / 12 for k in range(12)]
    rows = ik.parallel_beam_matrix(n, angles, nbins)
    xt = ik.flatten(ik.disk_phantom(n, 0.6))
    yt = ik.sp_matvec(rows, xt)
    nt = math.sqrt(sum(t * t for t in xt))
    errs = []
    sirt(rows, n * n, yt, 1.0, 100, callback=lambda k, x: errs.append(math.dist(x, xt) / nt))
    assert errs[-1] < 0.5 * errs[0]
    rng = random.Random(8)
    sigma = 0.02 * max(yt)
    yd = [t + rng.gauss(0.0, sigma) for t in yt]
    delta = math.sqrt(len(yd)) * sigma
    x, k = sirt(rows, n * n, yd, 1.0, 400, delta=delta)
    e = [a - sum(w * x[j] for j, w in row) for row, a in zip(rows, yd)]
    assert 0 < k < 400
    assert math.sqrt(sum(t * t for t in e)) <= 1.01 * delta


def test_nonnegativity_option() -> None:
    y = [3.0, -1.0, 4.0, 6.0, 0.5]
    x, _ = sirt(ROWS, 4, y, lam=1.0, iters=50, nonneg=True)
    assert min(x) >= 0.0

History

Peter Gilbert proposed SIRT in 1972 in the Journal of Theoretical Biology, two years after Gordon, Bender and Herman published ART in the same journal. ART corrects the image after each ray and gave noisy, streaky images; Gilbert corrected every pixel from all ray sums at once, which gave smoother results. The averaging of projections onto all hyperplanes is older: Cimmino published it for linear systems in 1938. Van der Sluis and van der Vorst analyzed SIRT in 1990 as a scaled Landweber iteration for a weighted least squares problem. Andersen and Kak introduced SART in 1984, and Jiang and Wang proved the convergence of the simultaneous update in 2003.

References

  1. P. Gilbert, Iterative methods for the three-dimensional reconstruction of an object from projections, Journal of Theoretical Biology 36(1), 1972, 105 to 117, the simultaneous correction of all pixels from all ray sums (general locator)
  2. Ming Jiang and Ge Wang, Convergence of the simultaneous algebraic reconstruction technique (SART), IEEE Transactions on Image Processing 12(8), 2003, pp. 957 to 961 (convergence of the simultaneous form x + lambda V A^T W (y - A x) for nonnegative A to a weighted least squares solution from any start)
  3. A. van der Sluis and H. A. van der Vorst, SIRT- and CG-type methods for the iterative solution of sparse linear least-squares problems, Linear Algebra and its Applications 130, 1990, 257 to 302, SIRT as a scaled Landweber iteration and its weighted least squares limit (general locator)
  4. A. C. Kak and M. Slaney, Principles of Computerized Tomographic Imaging, SIAM Classics in Applied Mathematics 33, 2001, Chapter 7, algebraic reconstruction algorithms (ART, SIRT and SART)
  5. Heinz W. Engl, Martin Hanke and Andreas Neubauer, Regularization of Inverse Problems, Kluwer, 1996, Chapter 6 (Landweber iteration, its stopping by the discrepancy principle and its rates)

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.per_iteration
  • a full proof of time.total
  • 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