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
- Model
- Real RAM
- Properties
- deterministicnot in placeiterativelinear in dataorder independentiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Peter Gilbert, 1972
SIRT reconstructs an image from the data of the discrete model of tomography, where holds the pixel values, holds the ray sums, and is a sparse matrix with nonnegative entries , the weight of pixel in ray . 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: with and . It is the Landweber iteration for the scaled system , which has norm exactly 1. So it converges for 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 , 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 matrix and data , find that fits . Write for the row sums and 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 . With exact consistent data, the target is a solution of . With inconsistent data, SIRT solves the weighted least squares problem
and among its solutions it picks the one closest to the start in the norm . 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
SIRT(A, y, λ, K, x0) ▷ 0 < λ < 2; δ is the noise level if known- 1
r_i ← Σ_j a_ij, c_j ← Σ_i a_ij; R ← diag(1/r_i), C ← diag(1/c_j) - 2
x ← x0 - 3
for k ← 1 to K do - 4
e ← y - A x; if δ is known and ‖e‖ ≤ τ δ then return x - 5
e_i ← e_i / r_i for each ray i - 6
g ← A^T e ▷ the back projection of the scaled residuals - 7
x_j ← x_j + λ g_j / c_j for each pixel j - 8
(optional) x_j ← max(x_j, 0) - 9
return 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 . Any projector gives the matrix: Siddon's algorithm, Joseph's projector or the distance-driven projector. The method needs in line L6, not an approximate back projector. Line L4 also tests the discrepancy principle with a fixed . 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 image in row-major order, the true values , and five rays with weights 0 or 1: the two rows, the two columns, and the diagonal through and .
| ray | pixels | ||
|---|---|---|---|
| row 0 | 3 | 2 | |
| row 1 | 7 | 2 | |
| column 0 | 4 | 2 | |
| column 1 | 6 | 2 | |
| diagonal | 5 | 2 |
The column sums are , because and lie on three rays and the others on two. Start from with . Line L5 gives . Line L6 gives , , and . Line L7 divides by :
| iteration | |||||
|---|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 | |
| 1 | 2 | 3 | |||
| 2 | |||||
| 3 |
The weighted residual falls at each step, as the theory says. The five rays determine the image, so the iterates converge to ; after 400 steps the error is below for , and . The scaled matrix has the singular values , , and , so the error of the slowest component shrinks by the factor per step for . The test file checks all values of the table with fractions.Fraction.
A larger case: a disk of radius 0.6 on a grid, 12 angles in , 23 bins, and the pixel-driven matrix of the shared helper. With exact data, the relative error is after 1 step, after 10, after 100 and after 400. With Gaussian noise of standard deviation percent of the largest ray sum (seed 5), the error is smallest, , at , and it grows to at : this is semi-convergence. The discrepancy principle with stops at with the error . These numbers are measurements of this setup, not properties of the method.
Correctness
Put , and . Then line L7 reads , the Landweber iteration for with the step . Two facts make the theory of Landweber apply:
- . By the Cauchy-Schwarz inequality, , and summing over with the weights gives . The vector gives , and , so the bound is attained.
- So is the Landweber condition. With , the iterate from is : the spectral filter factors of Landweber.
Each factor lies in for , so converges to plus the part of in the null space of . In the variable this is the weighted least squares solution of the problem section, closest to in the norm. The weighted residual does not increase, because and the eigenvalues of lie in . For the factor on the top singular value, and from the iteration diverges whenever , because the top singular vector is up to scaling. With line L8, the step is a projected gradient step for over , because is diagonal and positive, so if and only if , and the projection onto the orthant is the clipping. A projected gradient step with a step size below 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 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. is an matrix with , all row sums and all column sums are positive (a zero row or column gets the weight 0 in the code, which is the same as removing it), and . Without line L8, lines L4 to L7 compute
This is a direct reading of the lines: L4 forms , L5 multiplies by , L6 by , and L7 by and adds. We work in exact arithmetic.
The change of variables. Put
Multiply (1) on the left by :
So SIRT is the Landweber iteration for the system with the step . Also and .
Lemma 1 (the norm). .
Proof. Let . For each row , the Cauchy-Schwarz inequality with the weights gives
So . Sum over and use :
So . For , , so . So .
Theorem 1 (filter factors). Let be a singular value decomposition with , and let be the orthogonal projector onto the null space of . Then for every ,
Proof. By (2), . The vectors and the null space of are invariant under , with the factor on and the factor 1 on the null space, and has no part in the null space. So and, with and , . The solution of this recursion is , because .
Theorem 2 (convergence). If , then converges for every and every . The limit minimizes , and among all minimizers it is the unique one closest to in the norm. In particular, if has a solution, is a solution, and from with of full row rank,
Proof. By Lemma 1, , so and . By Theorem 1, . The set of minimizers of is , and lies in the range of , which is orthogonal to the null space. For a minimizer with , Pythagoras gives , which is smallest exactly for , that is for . Map back with , which carries the two norms as shown above. If is solvable, the minimum of the residual is 0. For full row rank, the minimizers of subject to give , and .
Theorem 3 (the weighted residual). For , .
Proof. From (2), . The matrix is symmetric with eigenvalues in by Lemma 1, so is symmetric with eigenvalues in , and its norm is at most 1.
Theorem 4 (the bound on lambda is sharp). If , and , then .
Proof. Let , and . Since , we get and . So and , a singular pair with , and we may choose an SVD that contains it. By Theorem 1 with , the coefficient of in is with . Here , so the coefficient grows without bound, and so does . Since , .
So for nonnegative data that are not all zero, SIRT from diverges for every . For the same coefficient oscillates between and and does not converge.
Theorem 5 (the nonnegative variant). With line L8, and , the iterates converge to a minimizer of over .
Proof. Since is diagonal with positive entries, if and only if , and clipping at 0 is the same as clipping at 0, which is the Euclidean projection onto the orthant. So in the variable , lines L4 to L8 are
the projected gradient method for the convex function over a closed convex set. The gradient is Lipschitz with the constant (Lemma 1). The function 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 , the projected gradient method on a convex function with an -Lipschitz gradient converges to a minimizer whenever one exists (the iteration is an averaged operator, and the Krasnoselskii-Mann theorem applies). Map back with .
Corollary (the discrepancy stop). Let , let be the limit of Theorem 2 or Theorem 5, and let . Then the test of line L4 succeeds after a finite number of steps.
Proof. The map is continuous and , so , and some finite passes the test.
The hypothesis is needed. Line L4 tests the plain norm of the residual, while SIRT minimizes the -weighted norm, so can exceed even when . If all row sums are equal, the two norms differ by a constant factor and the limit minimizes the plain residual too, so for every (with clipping, this needs ). The convergence rate of the stopping index under a source condition is a result on the Landweber iteration for ; see the page.
Cost. Line L1 reads each nonzero entry of once. In each iteration, line L4 reads each nonzero entry once, line L6 reads each nonzero entry of a row with once, and lines L5, L7 and L8 take and time. So one iteration costs time and extra space. For a ray-driven projector of an image with angles of bins, , and , so one iteration costs , which is when , as in any scan that can determine the image.
Complexity
In the real-RAM model, with angles of bins each, so rays, and an image:
- Line L1 takes one pass over the nonzero entries of . A ray-driven projector has entries per ray, so .
- Lines L4 and L6 are one forward and one back projection, each. Lines L5 and L7 take and .
So one iteration costs time, which is since in any scan that can determine the image. It needs extra space, and iterations cost . With a matrix-free projector, count one application of and one of per iteration. The number of iterations is the regularization parameter. With noise level , the discrepancy principle and the source condition of Landweber for in the EHN form , the stopping index is (EHN chapter 6). A measured iteration count, such as the 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 ; 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 by . 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 , 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, is a fixed linear function of and , 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 and averages: . It is the same scheme with in place of and no column scaling.
- Plain Landweber uses and needs , which requires an estimate of the norm, for example by power iteration. The scaling of SIRT gives the bound 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 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 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 ; 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 , and a pixel outside all rays has . 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 , the iteration is not Landweber for any matrix, 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.
- . The bound is sharp, because exactly. gives a component that does not decay, and diverges.
- Confusing the norms. The limit minimizes the -weighted residual, not the plain residual, and it is closest to in the 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, , the limit against the weighted normal equations and against the minimum norm solution, the filter factors against an SVD of , the monotone weighted residual, the divergence for , 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.
# 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
- 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)
- 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)
- 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)
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag KFR7FZ Edit this page History Report an error Markdown