Algorithmcore
Simultaneous algebraic reconstruction technique
Also called SART.
Update the image by the normalized back projection of the residuals of one whole projection angle at a time, between ART and SIRT.
- Time
- O(K a d n) totalO(a d n) per_sweepO(d n) per_view
- Space
- O(a d + n^2) extra
- Where
- K = the number of sweeps; 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
- block iterativedeterministicin placeiterativeorder dependentiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Anders H. Andersen, Avinash C. Kak, 1984
SART reconstructs an image from the data of the discrete model of tomography. Here holds the pixel values, is a sparse nonnegative matrix, and its rows are grouped by projection angle into views . For one view , SART computes the residuals of all rays of the view, divides each by the sum of its row, back-projects them, divides each pixel by the sum of its column over the rays of that view, and adds the result. Then it moves to the next view. One pass through all views is a sweep, and it costs the same as one iteration of SIRT: one forward and one back projection of all rays. It sits between ART, which corrects after each ray, and SIRT, which corrects after all rays. In practice it reaches a given error in far fewer passes than SIRT, and its images are smoother than those of ART.
In plain words
A CT scan measures the object from many angles, and at each angle a row of detectors records many parallel rays. SART takes the angles one at a time. For the current angle, it computes what each ray would measure through the current image and compares it with the true measurement. It spreads the error of each ray back along the ray, divided by the length of the ray. Each pixel then takes the average correction of the rays of this angle that cross it, times a factor . Then SART goes to the next angle with the improved image.
Since the image changes after each angle and not only after all angles, the next angle already sees a better image. That is why SART needs fewer passes than SIRT. Since all rays of an angle act together, the correction is smoother than the ray by ray correction of ART.
The problem
Given a nonnegative matrix whose rows are split into views , and data , find with . Write and for the rows and data of view , for the row sums, and for the column sums inside view . Let over the rays of the view, and , with . The step for view is
With exact consistent data, the target is a solution of . With noisy data, the target is a good early iterate, as for every iterative method of this kind (see semi-convergence).
The algorithm
SART(A, y, V_1..V_a, λ, K, x0) ▷ 0 < λ < 2- 1
r_i ← Σ_j a_ij for every ray i - 2
x ← x0 - 3
for k ← 1 to K do ▷ one sweep - 4
for each view v in the chosen order do - 5
e_i ← (y_i - ⟨a_i, x⟩) / r_i for each ray i in V_v - 6
g ← A_v^T e; c_v ← A_v^T 1 ▷ back projection and column sums of the view - 7
x_j ← x_j + λ g_j / c_vj for each pixel j with c_vj > 0 - 8
(optional) x_j ← max(x_j, 0) - 9
return x
Line L5 is the forward projection of one view, and line L6 its back projection. A pixel that no ray of the view meets has and does not change in that step. The view order matters. A common choice visits the angles in an order that keeps successive angles far apart, so that their corrections are close to independent; the default of the code is the natural order. Line L8 keeps the image nonnegative.
Example
Take a image in row-major order with the true values , and three views with weights 0 or 1:
| view | ray | pixels | ||
|---|---|---|---|---|
| rows | row 0 | 3 | 2 | |
| rows | row 1 | 8 | 2 | |
| columns | column 0 | 4 | 2 | |
| columns | column 1 | 7 | 2 | |
| diagonal | ray 1 | 3 | 1 | |
| diagonal | ray 2 | 6 | 2 | |
| diagonal | ray 3 | 2 | 1 |
Each pixel lies on exactly one ray of each view, so for all views and pixels. Start from with and the order rows, diagonal, columns:
| step | residuals divided by | after the step |
|---|---|---|
| rows | ||
| diagonal | ||
| columns | ||
| rows |
For example, in the diagonal step the ray through and measures against , so it adds to both pixels. SART finds the exact image in the first step of the second sweep and then stays there. With the order rows, columns, diagonal it is exact after the first sweep. With and the natural order, the first sweep gives , and 60 sweeps reach the true image to . The tests check all these values with fractions.Fraction.
A larger case: a disk of radius 0.6 on a grid, 12 angles in , 23 bins, the pixel-driven matrix of the shared helper, and the natural order. These are measurements of this setup. With exact data and , the relative error is after one sweep, after 10 and after 40. On the same data, SIRT has the error after one iteration, after 10, after 100 and after 400, and one SIRT iteration costs the same as one sweep. With Gaussian noise of standard deviation 2 percent of the largest ray sum (seed 5), SART with has its smallest error at sweep 6, and the error grows to at sweep 40. With the smallest error is at sweep 31, and SIRT reaches at iteration 101. A smaller gives a slower but flatter curve, which makes the stopping index less critical.
Correctness
The proofs below need one assumption: all views have the same column sums, for every . The pixel-driven matrix of the helper satisfies it exactly, because each pixel splits its whole weight among the bins of each view (a test checks this). Strip-integral weights, where is the area of pixel inside strip divided by the strip width, satisfy it too when the strips of a view cover the image. Put , and . The step becomes
a Landweber step on the block , and by the Cauchy-Schwarz argument of SIRT applied to the rows of the view. These are theorems, proved in proofs/correctness.md:
- One step is SIRT. If there is a single view that holds all rays, one sweep is exactly one SIRT iteration (a test checks this).
- Consistent data. If has a solution and , the iterates converge, for any order, to the solution closest to in the norm . The convergence is linear per sweep. The key fact is that each step lowers by at least .
- Inconsistent data. For any data and , the iterates at the ends of the sweeps converge. Inside a sweep they follow a cycle of points. The limit depends on and on the order, and in general it is not the weighted least squares solution of SIRT.
In a test with nine random rays and four pixels (seed 3), the distance from the limit to the weighted least squares solution is , , , and for , , , and : about proportional to . This is a measurement. For ART, Censor, Eggermont and Gordon showed in 1983 that the limit tends to a weighted least squares solution as the relaxation goes to 0. We do not prove the block version here.
When the column sums differ from view to view, the steps act in different metrics, and the proof above does not apply. Jiang and Wang (2003) proved convergence for the form that takes all views in one step, from any start, to a weighted least squares solution, when . That form is SIRT.
Proof: Correctness and convergence of SARTfull
We use the notation of the page and work in exact arithmetic. is an matrix with , its rows are split into views , and for every ray (rays with are skipped by the code and can be removed). We do not cover the clipping of line L8.
What the lines compute. For the current view , line L5 forms , line L6 forms and the column sums , and line L7 adds to each pixel with . Line L5 computes all residuals of the view from the same , because changes only in line L7, after the loop over the rays. So one view step is
with and . A pixel with has , so it does not change.
Proposition 1 (one view of all rays). If and holds all rays, one sweep is one SIRT iteration .
Proof. With one view, , and , so (1) is the SIRT step.
The assumption. From now on, all views have the same column sums: for all and , and . For the pixel-driven matrix of the shared helper, each pixel adds the weights and to two bins of each view, so for all and (the code checks this). For strip-integral weights with strips of width that cover the image, as well.
Put , , the matrix of all blocks stacked, and . Multiplying (1) by gives
Also . Let and .
Lemma 1. for every view, so is symmetric with eigenvalues in .
Proof. For a ray , the Cauchy-Schwarz inequality with the weights gives . So . Summing over and using gives .
Lemma 2 (the decrease). For and every , .
Proof. . By Lemma 1, , so . Hence .
Let be the orthogonal projector onto , and , its orthogonal complement. Each is the identity on , and since is symmetric it also maps into . Let for the chosen order .
Lemma 3. For , the restriction of to has norm .
Proof. By Lemma 2 each has norm at most 1, so . Suppose and . Put and , so . The norms do not increase and the last equals the first, so for every . By Lemma 2, , and then . By induction, for every , so for all and . So for every in . The function is continuous on the unit sphere of the finite-dimensional space , which is compact, so its maximum is attained and .
Theorem 1 (consistent data). Let have a solution and . Then for every order and every start , the SART iterates converge to the solution closest to in the norm, and after sweeps.
Proof. The solutions of are the solutions of in the variable . Let be the orthogonal projection of onto this affine set. Then , because the set is and the projection makes the difference orthogonal to . Since , the step (2) gives . So after sweeps , and Lemma 3 gives . The point solves and is closest to in the norm , which is the norm of .
Theorem 2 (any data). Let . For any data, the iterates at the ends of the sweeps converge, and so do the iterates after the -th view of each sweep, for each . So the iterates approach a cycle of at most points.
Proof. Step (2) is , so one sweep is with a sum of terms . Each such term lies in , because and the maps keep . Write with . Since each is the identity on and keeps , the sweep gives and . By Lemma 3, the map is a contraction on with the factor , so converges to its unique fixed point , and . The iterate after the -th view of sweep is an affine, hence continuous, function of , so it converges too. Map back with .
The limit of Theorem 2 is a fixed point of the sweep map, which depends on and on the order. It is not the -weighted least squares solution in general: the test with nine rays and four pixels finds a distance of for and for . These two numbers are measurements, not part of the theorem.
Cost. Line L1 reads each nonzero entry of once. For view , line L5 reads the entries of once and line L6 reads them once more, and line L7 touches at most the pixels that the view meets. So a view step costs time and a sweep costs , which is for a ray-driven matrix with entries per ray. The code keeps the row sums, , the image, , and two dictionaries for the current view, .
Complexity
In the real-RAM model, with views of rays each and an image, a ray-driven matrix has nonzero entries per ray. Line L5 reads the entries of the view once and line L6 reads them once more, so one view costs time and one sweep costs , the same as one SIRT iteration. Line L7 touches only the pixels the view meets. Line L1 takes one pass over . The extra space is for the row sums and for the dictionaries of one view; the code computes the column sums of a view on the fly instead of storing them for all views, which would cost . With a matrix-free projector, count one projection and one back projection of one view per step.
The number of sweeps is the regularization parameter, as for SIRT. Its best value depends on the noise, on and on the order. It is found by a stopping rule, not by a formula.
Properties
- Block iterative. The image changes after each view, so later views see the corrections of earlier views. This is the source of the speed over SIRT.
- Order dependent. The iterates depend on the view order. With consistent data and common column sums, the limit does not.
- Smooth corrections. All rays of a view act together, and the division by averages their corrections at each pixel. The streaks that ART can leave when it corrects ray by ray are weaker.
- Not a fixed-point method for noisy data. With fixed and inconsistent data, the iterates cycle through points and do not converge to a single image.
- Parallel inside a view. The rays of one view are independent, so a view step is parallel over its rays and its pixels. The views are sequential.
Variants and improvements
- Ordered subsets. Group the views into subsets and apply the step to one subset at a time. One subset holding all views is SIRT; one view per subset is SART. The OSEM method does the same with the multiplicative update of the maximum likelihood method for emission tomography.
- Diminishing relaxation. Let decrease from sweep to sweep. The cycle of the inconsistent case then shrinks, and the iterates can approach a weighted least squares solution. The step rule has to make diverge.
- Bilinear or Joseph weights. Andersen and Kak computed the weights with bilinear interpolation along each ray. Any projector works: Siddon, Joseph or distance-driven.
- With a prior. Alternate SART sweeps with a total variation step, as ASD-POCS does, to reconstruct piecewise constant images from few views.
When to use it
Use SART when an algebraic method is needed (few views, a limited angle, noise, or a nonstandard geometry) and convergence per pass matters. It is the usual data step of iterative CT codes that work view by view. Use SIRT when the result must not depend on the order of the views, when all rays must be processed in parallel, or when a fixed-point analysis is needed. For complete data with many angles, filtered back-projection is much cheaper.
Pitfalls
- Expecting a single limit with noise. With fixed and inconsistent data, SART does not converge to one image. Stop early, or let decrease.
- Bad view orders. Consecutive views at nearby angles carry nearly the same information, so the second step adds little to the first. Interleave the angles. This is a heuristic; the code does not measure it.
- Zero sums. A ray outside the image has , and a pixel outside all rays of a view has . Skip them, or the division fails.
- An unmatched back projector. Line L6 must use the transpose of the matrix of line L5. Otherwise the step is not a Landweber step for any block, and does not hold.
- Too large . Each block step needs . Values near 2 converge slowly on the components with the largest singular value and amplify noise in early sweeps.
Implementations
The Python code takes the sparse rows of as (column, weight) pairs and the views as lists of row indices; views_by_angle gives the views of the shared helper imgkit.parallel_beam_matrix. It works with float or fractions.Fraction data. The tests check the worked example exactly, the relaxed example, that one view of all rays is one SIRT step, the limit for consistent data against the projection of onto the solution set, the convergence of the sweep ends for inconsistent data and the dependence of the limit on , the equal column sums of the helper matrix, a disk phantom against SIRT, and the nonnegativity option.
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
sart.py 67 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sart/. The authors are listed in prov/9QD7WM.jsonl.
"""SART, the simultaneous algebraic 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. The rays are grouped into views: views[v] is the
list of the row indices of view v. For one view v, the update is
x <- x + lam * C_v A_v^T R_v (y_v - A_v x),
with R_v = diag(1 / r_i) over the rays i of the view and C_v = diag(1 / c_vj),
c_vj the sum of column j over the rays of the view. A pixel with c_vj = 0 is
not changed by view v, and a ray with r_i = 0 is skipped. One sweep applies
the update once for each view, in the given order. The code works with float
or with fractions.Fraction data.
"""
def views_by_angle(nangles, nbins):
"""The views of imgkit.parallel_beam_matrix: angle a holds the rows a * nbins + b."""
return [list(range(a * nbins, (a + 1) * nbins)) for a in range(nangles)]
def view_sums(rows, views):
"""The row sums r_i, and for each view a dict j -> c_vj of its column sums."""
r = [sum(w for _, w in row) for row in rows]
cs = []
for view in views:
c = {}
for i in view:
for j, w in rows[i]:
c[j] = c.get(j, 0) + w
cs.append(c)
return r, cs
def sart(rows, ncols, y, views, lam=1.0, sweeps=10, x0=None, order=None, nonneg=False, callback=None):
"""Run SART and return x after the given number of sweeps.
rows: the sparse rows of A; y: the data; views: the row indices of each
view; lam: the relaxation, 0 < lam < 2; x0: the start (zero by default);
order: the order of the views in a sweep (0, 1, 2, ... by default);
nonneg: clip to x >= 0 after each view; callback(k, x) is called after
sweep k.
"""
r = [sum(w for _, w in row) for row in rows] # @line L1
x = list(x0) if x0 is not None else [0 * lam] * ncols # @line L2
seq = list(order) if order is not None else list(range(len(views)))
for k in range(sweeps): # @line L3
for v in seq: # @line L4
g, c = {}, {}
for i in views[v]:
if r[i] == 0:
continue
e = (y[i] - sum(w * x[j] for j, w in rows[i])) / r[i] # @line L5
for j, w in rows[i]:
g[j] = g.get(j, 0) + w * e # @line L6
c[j] = c.get(j, 0) + w
for j, gj in g.items():
if c[j] != 0:
x[j] = x[j] + lam * gj / c[j] # @line L7
if nonneg and x[j] < 0:
x[j] = 0 * x[j] # @line L8
if callback is not None:
callback(k + 1, list(x))
return x # @line L9
test_sart.py 167 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sart/. The authors are listed in prov/9QD7WM.jsonl.
import math
import random
from fractions import Fraction as F
import imgkit as ik
from sart import sart, view_sums, views_by_angle
# The 2 x 2 example of the page: a view of two rows, a view of two columns, and
# a diagonal view of three rays. The true image is (1, 2, 3, 5).
A = [[1, 1, 0, 0], [0, 0, 1, 1], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0], [1, 0, 0, 1], [0, 1, 0, 0]]
ROWS = [[(j, F(w)) for j, w in enumerate(r) if w] for r in A]
XT = [1, 2, 3, 5]
Y = [sum(F(a) * b for a, b in zip(r, XT)) for r in A]
VIEWS = [[0, 1], [2, 3], [4, 5, 6]]
def _sparse(dense):
return [[(j, w) for j, w in enumerate(r) if w != 0] for r in dense]
def _views_with_unit_column_sums(rng, sizes, n):
"""Random nonnegative views whose column sums are all 1, so C_v = I for every view."""
dense, views = [], []
for k in sizes:
block = [[rng.random() + 0.1 for _ in range(n)] for _ in range(k)]
for j in range(n):
s = sum(block[i][j] for i in range(k))
for i in range(k):
block[i][j] /= s
views.append(list(range(len(dense), len(dense) + k)))
dense.extend(block)
return dense, views
def _solve(m, b):
"""Gaussian elimination with partial pivoting for a small dense system."""
n = len(b)
a = [list(row) + [bi] for row, bi in zip(m, b)]
for c in range(n):
p = max(range(c, n), key=lambda i: abs(a[i][c]))
a[c], a[p] = a[p], a[c]
for i in range(c + 1, n):
f = a[i][c] / a[c][c]
for j in range(c, n + 1):
a[i][j] -= f * a[c][j]
x = [0.0] * n
for i in range(n - 1, -1, -1):
x[i] = (a[i][n] - sum(a[i][j] * x[j] for j in range(i + 1, n))) / a[i][i]
return x
def test_worked_example_exact() -> None:
seen = []
sart(ROWS, 4, Y, VIEWS, lam=F(1), sweeps=2, order=[0, 2, 1], callback=lambda k, x: seen.append(x))
assert seen[0] == [F(11, 8), F(19, 8), F(21, 8), F(37, 8)]
assert seen[1] == [F(1), F(2), F(3), F(5)]
# inside the first sweep: after the rows and after the diagonal view
assert sart(ROWS, 4, Y, VIEWS, lam=F(1), sweeps=1, order=[0]) == [F(3, 2), F(3, 2), F(4), F(4)]
assert sart(ROWS, 4, Y, VIEWS, lam=F(1), sweeps=1, order=[0, 2]) == [F(7, 4), F(2), F(3), F(17, 4)]
def test_relaxed_example_converges() -> None:
seen = []
sart(ROWS, 4, Y, VIEWS, lam=F(1, 2), sweeps=1, callback=lambda k, x: seen.append(x))
assert seen[0] == [F(49, 32), F(61, 32), F(85, 32), F(113, 32)]
x = sart(ROWS, 4, [float(v) for v in Y], VIEWS, lam=0.5, sweeps=60)
assert max(abs(a - b) for a, b in zip(x, XT)) < 1e-12
def test_one_view_with_all_rays_is_one_sirt_step() -> None:
rng = random.Random(1)
m, n, lam = 7, 5, 0.7
dense = [[rng.random() if rng.random() < 0.7 else 0.0 for _ in range(n)] for _ in range(m)]
for i in range(m):
dense[i][i % n] += 0.5
y = [rng.uniform(0, 2) for _ in range(m)]
x0 = [rng.uniform(0, 1) for _ in range(n)]
r = [sum(row) for row in dense]
c = [sum(dense[i][j] for i in range(m)) for j in range(n)]
e = [(yi - sum(a * b for a, b in zip(row, x0))) / ri for row, yi, ri in zip(dense, y, r)]
expect = [x0[j] + lam * sum(dense[i][j] * e[i] for i in range(m)) / c[j] for j in range(n)]
x = sart(_sparse(dense), n, y, [list(range(m))], lam=lam, sweeps=1, x0=x0)
assert max(abs(a - b) for a, b in zip(x, expect)) < 1e-14
def test_consistent_limit_is_the_nearest_solution() -> None:
rng = random.Random(2)
n = 6
dense, views = _views_with_unit_column_sums(rng, (2, 2), n)
m = len(dense)
xt = [rng.uniform(0, 2) for _ in range(n)]
y = [sum(a * b for a, b in zip(row, xt)) for row in dense]
x0 = [rng.uniform(-1, 1) for _ in range(n)]
# C_v = I, so the limit is the projection x0 + A^T (A A^T)^(-1) (y - A x0) of x0
# onto {x : A x = y}. The rows of each view add up to the ones vector, so the
# last row is a combination of the others and is left out of the formula.
keep = dense[: m - 1]
res = [yi - sum(a * b for a, b in zip(row, x0)) for row, yi in zip(keep, y)]
aat = [[sum(p * q for p, q in zip(a, b)) for b in keep] for a in keep]
u = _solve(aat, res)
expect = [x0[j] + sum(row[j] * ui for row, ui in zip(keep, u)) for j in range(n)]
for lam, order in ((1.0, None), (1.6, [1, 0]), (0.4, None)):
x = sart(_sparse(dense), n, y, views, lam=lam, sweeps=3000, x0=x0, order=order)
assert max(abs(a - b) for a, b in zip(x, expect)) < 1e-9
def test_inconsistent_data_sweeps_converge_to_a_lambda_dependent_limit() -> None:
rng = random.Random(3)
n = 4
dense, views = _views_with_unit_column_sums(rng, (3, 3, 3), n)
m = len(dense)
y = [rng.uniform(0, 3) for _ in range(m)]
rows = _sparse(dense)
r = [sum(row) for row in dense]
# the R-weighted least squares solution
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)]
xls = _solve(atra, atry)
gaps = []
for lam in (1.0, 0.25):
ends = []
sart(rows, n, y, views, lam=lam, sweeps=3000, callback=lambda k, x: ends.append(x))
assert max(abs(a - b) for a, b in zip(ends[-1], ends[-2])) < 1e-12
gaps.append(max(abs(a - b) for a, b in zip(ends[-1], xls)))
# measured: 0.172 for lam = 1 and 0.054 for lam = 1/4
assert gaps[0] > 0.1
assert gaps[1] < 0.5 * gaps[0]
def test_helper_matrix_has_equal_column_sums_in_every_view() -> None:
n, nbins, na = 16, 23, 12
rows = ik.parallel_beam_matrix(n, [k * math.pi / na for k in range(na)], nbins)
_, cs = view_sums(rows, views_by_angle(na, nbins))
ref = (2.0 / n) ** 2 / (2.0 * math.sqrt(2.0) / nbins)
for c in cs:
assert len(c) == n * n
assert all(abs(v - ref) < 1e-12 for v in c.values())
def test_phantom_sart_beats_sirt_per_pass() -> None:
n, nbins, na = 16, 23, 12
rows = ik.parallel_beam_matrix(n, [k * math.pi / na for k in range(na)], nbins)
xt = ik.flatten(ik.disk_phantom(n, 0.6))
y = ik.sp_matvec(rows, xt)
nt = math.sqrt(sum(t * t for t in xt))
errs = []
sart(rows, n * n, y, views_by_angle(na, nbins), lam=1.0, sweeps=10, callback=lambda k, x: errs.append(math.dist(x, xt) / nt))
# SIRT with the same matrix, 10 passes through the data
r = [sum(w for _, w in row) for row in rows]
c = ik.sp_rmatvec(rows, [1.0] * len(rows), n * n)
x = [0.0] * (n * n)
for _ in range(10):
e = [(yi - s) / ri if ri > 0 else 0.0 for yi, s, ri in zip(y, ik.sp_matvec(rows, x), r)]
x = [xj + g / cj for xj, g, cj in zip(x, ik.sp_rmatvec(rows, e, n * n), c)]
sirt_err = math.dist(x, xt) / nt
assert errs[0] < 0.4
assert errs[-1] < 0.12
assert errs[-1] < 0.5 * sirt_err
def test_nonnegativity_option() -> None:
y = [3.0, -1.0, 4.0, 6.0, -2.0, 0.5, 2.0]
x = sart(_sparse(A), 4, y, VIEWS, lam=1.0, sweeps=30, nonneg=True)
assert min(x) >= 0.0
History
Gordon, Bender and Herman published ART in 1970, and Gilbert published SIRT in 1972. ART converged fast but gave noisy images with streaks; SIRT gave smooth images but converged slowly. Andersen and Kak proposed SART in 1984 in Ultrasonic Imaging as a compromise: one correction per projection angle, with bilinear weights along the rays. Block-iterative methods for partitioned linear systems had been studied by Eggermont, Herman and Lent in 1981. Jiang and Wang proved the convergence of the form that uses all rays in one step in 2003. SART became a standard data step of iterative CT, often accelerated with ordered subsets and run on GPUs.
References
- A. H. Andersen and A. C. Kak, Simultaneous algebraic reconstruction technique (SART): a superior implementation of the ART algorithm, Ultrasonic Imaging 6(1), 1984, 81 to 94, the update per projection angle with the row and column normalization (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 form that uses all rays in one step, to a weighted least squares solution)
- P. P. B. Eggermont, G. T. Herman and A. Lent, Iterative algorithms for large partitioned linear systems, with applications to image reconstruction, Linear Algebra and its Applications 40, 1981, 37 to 67, block-iterative methods that correct the image once per block of equations (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)
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 9QD7WM Edit this page History Report an error Markdown