Algorithm Search⌘K

Algorithmadvanced

Distance-driven projector

Also called distance-driven projection.

A matched forward and back projector for CT that maps pixel borders and detector bin borders onto one axis and uses the lengths of their overlaps as weights.

Time
O(a n (n + d)) worst
Space
O(n + d) extra
Where
a = the number of projection angles; d = the number of detector bins; n = the side of the n x n image
Properties
deterministicnot in placenot iterativelineariterative
Origin
Bruno De Man, Samit Basu, 2002

The distance-driven projector computes the system matrix AA of the discrete model y=Axy = A x of transmission tomography, where xx holds the pixel values and yy the detector readings of a sinogram. For one view it takes each row of pixels (or each column, for a ray closer to horizontal), maps the borders of the pixels in that row and the borders of the detector bins onto one common axis, and uses the length of the overlap of each pixel and each bin as the weight. The back projector uses the same weights, so it is the exact transpose. One view costs O(n(n+d))O(n(n + d)) for an n×nn \times n image and dd bins. De Man and Basu designed it to remove the two known faults of the simpler projectors: the pixel-driven projector gives a high frequency ripple in the forward projection, and ray-driven projectors such as Siddon's algorithm and Joseph's projector give a similar artifact in the back projection when the bins are wide.

In plain words

Look at one row of pixels from the direction of the rays. Each pixel casts a shadow on the detector line. The shadows of the pixels in one row lie side by side, with no gap and no overlap. The detector is cut into bins, also side by side. Put the two cuttings on the same line, like two rulers next to each other. Where the shadow of a pixel and a bin overlap, the pixel sends that share of itself to that bin.

The bin value is then the average over the bin of what the rays see. Because both sets of cells cover the line with no gap, each pixel gives all of its mass to the bins, and a constant image gives a flat projection with no ripple. The back projection runs the same overlaps in the other direction.

The problem

The image is n×nn \times n on the square [−1,1]2[-1, 1]^2, with f[i][j]f[i][j] in row ii from the top and column jj from the left. The center of pixel (i,j)(i, j) is xj=−1+(2j+1)/nx_j = -1 + (2j+1)/n, yi=1−(2i+1)/ny_i = 1 - (2i+1)/n, so yy goes up, and h=2/nh = 2/n is the pixel size. A view has the angle θ\theta, with ω=(cos⁡θ,sin⁡θ)\omega = (\cos\theta, \sin\theta), and the detector coordinate of a point (x,y)(x, y) is s=xcos⁡θ+ysin⁡θs = x\cos\theta + y\sin\theta, as for the Radon transform. Bin bb covers [s0+bw,s0+(b+1)w][s_0 + b w, s_0 + (b+1) w] for b=0,…,d−1b = 0, \ldots, d - 1. The code uses the bins of the shared pixel-driven projector: dd bins of width w=22/dw = 2\sqrt{2}/d on [−2,2][-\sqrt{2}, \sqrt{2}].

The image model is this. Suppose ∣cos⁡θ∣≥∣sin⁡θ∣|\cos\theta| \ge |\sin\theta|. Then each row of pixels is collapsed onto its center line y=yiy = y_i, with the thickness hh. A ray crosses the row along a path of length Δ=h/∣cos⁡θ∣\Delta = h/|\cos\theta|, and it sees the value of the pixel where it meets the center line. The bin value is the average over the bin width of the sum of these row contributions. For ∣cos⁡θ∣<∣sin⁡θ∣|\cos\theta| < |\sin\theta|, swap the roles of rows and columns, with Δ=h/∣sin⁡θ∣\Delta = h/|\sin\theta|. The task is to compute all bin values of all views, and the transpose of this linear map.

The algorithm

  1. DD-VIEW(f, c, σ, s0, w, d) ▷ c = cos θ, σ = sin θ; out has d zeros
  2. 1h ← 2/n
  3. 2if |c| ≥ |σ| then Δ ← h/|c|, the lines are rows else Δ ← h/|σ|, the lines are columns
  4. 3for k ← 0 to n - 1 do ▷ row k, or column k
  5. 4B ← the n + 1 pixel borders of line k mapped to s = x c + y σ, in increasing order
  6. 5D ← the bin borders s0, s0 + w, ..., s0 + d w
  7. 6p ← 0, q ← 0 ▷ p: a pixel of line k, q: a bin
  8. 7while p < n and q < d do
  9. 8ℓ ← min(B[p+1], D[q+1]) - max(B[p], D[q])
  10. 9if ℓ > 0 then out[q] ← out[q] + (Δ ℓ / w) · f[pixel p of line k]
  11. 10if B[p+1] < D[q+1] then p ← p + 1 else q ← q + 1
  12. 11return out

For a row kk the borders are x=−1+jhx = -1 + jh at the height yky_k, so BB holds (−1+jh)cos⁡θ+yksin⁡θ(-1 + jh)\cos\theta + y_k\sin\theta for j=0,…,nj = 0, \ldots, n. These values are equally spaced, h∣cos⁡θ∣h|\cos\theta| apart. If cos⁡θ<0\cos\theta < 0 they decrease, and line L4 reverses them, which also reverses the order of the pixels. Lines L6 to L10 are the merge of two sorted lists, as in merge sort: at each step the cell that ends first moves on. Line L8 is the overlap of pixel pp and bin qq, and line L9 adds the share of the pixel. The factor Δ/w\Delta/w makes the weights of one pixel, times ww, sum to Δ⋅h∣cos⁡θ∣=h2\Delta \cdot h|\cos\theta| = h^2, the pixel area, when the detector covers its shadow.

The pairs (pixel, bin, weight) of line L9 are the nonzero entries of one view of the system matrix. The back projector runs the same loops and adds weight times the bin value to the pixel. It is the exact transpose.

Example

Take n=2n = 2, so h=1h = 1, the image f=[[1,2],[3,4]]f = [[1, 2], [3, 4]], cos⁡θ=4/5\cos\theta = 4/5, sin⁡θ=3/5\sin\theta = 3/5 and four bins of width w=1/2w = 1/2 on [−1,1][-1, 1]. Then ∣c∣≥∣σ∣|c| \ge |\sigma|, the lines are rows, and Δ=5/4\Delta = 5/4.

row yy borders BB pixel and its shadow overlaps with the bins weights Δℓ/w\Delta\ell/w
0 1/21/2 −1/2,3/10,11/10-1/2, 3/10, 11/10 (0,0)(0,0): [−1/2,3/10][-1/2, 3/10] bin 1: 1/21/2, bin 2: 3/103/10 5/45/4, 3/43/4
(0,1)(0,1): [3/10,11/10][3/10, 11/10] bin 2: 1/51/5, bin 3: 1/21/2 1/21/2, 5/45/4
1 −1/2-1/2 −11/10,−3/10,1/2-11/10, -3/10, 1/2 (1,0)(1,0): [−11/10,−3/10][-11/10, -3/10] bin 0: 1/21/2, bin 1: 1/51/5 5/45/4, 1/21/2
(1,1)(1,1): [−3/10,1/2][-3/10, 1/2] bin 1: 3/103/10, bin 2: 1/21/2 3/43/4, 5/45/4

The bin values are (5/4⋅3,  5/4+3/2+3,  3/4+1+5,  5/4⋅2)=(15/4,23/4,27/4,5/2)(5/4 \cdot 3, \; 5/4 + 3/2 + 3, \; 3/4 + 1 + 5, \; 5/4 \cdot 2) = (15/4, 23/4, 27/4, 5/2). The shadow of a pixel has the width h∣cos⁡θ∣=4/5h|\cos\theta| = 4/5. The detector ends at s=±1s = \pm 1, so it misses 1/101/10, that is 1/81/8, of the shadow of pixel (0,1)(0, 1) and 1/81/8 of the shadow of pixel (1,0)(1, 0). So ww times the sum of the bins is (1/2)(75/4)=75/8=10−2/8−3/8(1/2)(75/4) = 75/8 = 10 - 2/8 - 3/8, the image mass minus the missed parts. The test file checks every weight, every bin value and this sum with fractions.Fraction.

The code also measures the projector on a 32×3232 \times 32 grid with 2323 bins. For a constant image of value 1, every bin that lies fully inside the part of the detector where each ray crosses all rows gets exactly 2/max⁡(∣cos⁡θ∣,∣sin⁡θ∣)2/\max(|\cos\theta|, |\sin\theta|), within 4⋅10−154 \cdot 10^{-15}, at the angles 00, 0.30.3, 1.21.2 and 2.02.0. The pixel-driven projector of the shared helper differs from the same value by up to 0.110.11 percent on the same bins: that is its ripple. For a disk of radius 1/21/2 sampled at the pixel centers, over 8 angles and the bins with ∣s∣<0.35|s| < 0.35, the largest difference from the bin average of 21/4−s22\sqrt{1/4 - s^2} is 0.0340.034. For the image e−16∣x∣2e^{-16|x|^2} sampled at the pixel centers, the largest difference from the bin average of π/16 e−16s2\sqrt{\pi/16}\,e^{-16 s^2} is 0.0180.018 for n=16n = 16, 0.00190.0019 for n=32n = 32 and 0.000460.00046 for n=64n = 64. These are measurements of this setup with the bin width fixed at 0.1230.123.

Correctness

The proof has three parts, and the full form is in proofs/correctness.md. First, the sweep of lines L6 to L10 visits every pair of a pixel and a bin whose intervals overlap with positive length, once each. Both lists are sorted and each is a partition of an interval. The loop keeps the invariant that all pairs (p′,q′)(p', q') with p′<pp' < p or q′<qq' < q that overlap have been visited, because a cell is dropped only when it ends before the other current cell, and then it cannot meet any later cell of the other list. Second, the weight of a pair is Δℓ/w\Delta\ell/w, which is the integral over the bin, divided by ww, of the row contribution Δf\Delta f for the rays that meet the center line inside the pixel. So the code computes the model of "The problem" exactly. Third, the back projector uses the same list of weights, so it is the transpose.

Two exact facts follow. If the detector covers the shadow of the whole image, w∑qout[q]=h2∑i,jf[i][j]w\sum_q \text{out}[q] = h^2 \sum_{i,j} f[i][j], the integral of the pixel-square image. At θ=0\theta = 0, the rays are vertical and the collapse of a row onto its center line changes nothing, so each bin gets the exact average over its width of the line integrals of the pixel-square image.

The method is still an approximation of the X-ray transform of the pixel-square image at other angles, because it collapses each row to its center line. A ray that crosses a pixel near its corner sees the full Δ\Delta of that pixel, while its true path through the square is shorter.

Proof: Correctness of the distance-driven projectorfull

We use the conventions of the page. The image is n×nn \times n on [−1,1]2[-1, 1]^2 with h=2/nh = 2/n, the view has c=cos⁡θc = \cos\theta and σ=sin⁡θ\sigma = \sin\theta, and bin qq is Jq=[s0+qw,s0+(q+1)w]J_q = [s_0 + qw, s_0 + (q+1)w] for 0≤q<d0 \le q < d. We treat the case ∣c∣≥∣σ∣|c| \ge |\sigma|, where the lines are rows and Δ=h/∣c∣\Delta = h/|c|. The column case is the same with xx and yy exchanged. We work in exact arithmetic.

The model. For row kk, let gk(s)g_k(s) be the value of the pixel of row kk whose part of the center line y=yky = y_k the ray {xc+yσ=s}\{x c + y\sigma = s\} meets, and 00 if it meets none. The model value of bin qq is

Pq=1w∫JqΔ∑k=0n−1gk(s) ds.P_q = \frac{1}{w}\int_{J_q} \Delta \sum_{k=0}^{n-1} g_k(s)\,ds.

We prove that DD-VIEW returns out[q]=Pq\text{out}[q] = P_q for all qq, that the back projector is the transpose, and the two exact facts of the page.

Lemma 1 (the borders, line L4). On the center line of row kk, pixel (k,j)(k, j) is the segment −1+jh≤x≤−1+(j+1)h-1 + jh \le x \le -1 + (j+1)h. The ray with parameter ss meets it if and only if ss lies between (−1+jh)c+ykσ(-1 + jh)c + y_k\sigma and (−1+(j+1)h)c+ykσ(-1 + (j+1)h)c + y_k\sigma.

Proof. On the line y=yky = y_k, the map x↦xc+ykσx \mapsto x c + y_k\sigma is affine with slope c≠0c \ne 0 (since ∣c∣≥∣σ∣|c| \ge |\sigma| and c2+σ2=1c^2 + \sigma^2 = 1, ∣c∣≥1/2|c| \ge 1/\sqrt{2}). So it maps the segment of the pixel onto the interval between the images of its ends, one to one. □\square

So the shadows of the nn pixels of row kk are the nn intervals between neighbors of the list BB, each of length h∣c∣h|c|, and they tile the interval [B[0],B[n]][B[0], B[n]]. If c<0c < 0, the list decreases in jj; line L4 reverses it, and pixel pp of the sorted list is column n−1−pn - 1 - p. Lines L4 and L5 give two increasing lists. Call the cells Up=[B[p],B[p+1]]U_p = [B[p], B[p+1]] and Vq=[D[q],D[q+1]]=JqV_q = [D[q], D[q+1]] = J_q.

Lemma 2 (the sweep, lines L6 to L10). The loop visits every pair (p,q)(p, q) with ∣Up∩Vq∣>0|U_p \cap V_q| > 0 exactly once, and line L8 sets ℓ=∣Up∩Vq∣\ell = |U_p \cap V_q| for it.

Proof. For two closed intervals, min⁡\min of the right ends minus max⁡\max of the left ends is the length of the intersection when it is positive, and it is ≤0\le 0 when they overlap in at most one point. So line L8 is correct, and line L9 adds a term only for pairs with positive overlap.

Each step increases pp or qq by one, so no pair is visited twice, and the loop ends after at most n+dn + d steps. Invariant: when the loop is at (p,q)(p, q), every pair (p′,q′)(p', q') with positive overlap and with p′<pp' < p or q′<qq' < q was visited. It holds at (0,0)(0, 0). Suppose the loop moves from (p,q)(p, q) to (p+1,q)(p + 1, q), because B[p+1]<D[q+1]B[p+1] < D[q+1]. The pairs that the move gives up are (p,q′)(p, q') with q′>qq' > q. For those, Vq′V_{q'} starts at D[q′]≥D[q+1]>B[p+1]D[q'] \ge D[q+1] > B[p+1], so UpU_p ends before Vq′V_{q'} begins and the overlap is zero. The move to (p,q+1)(p, q+1) with D[q+1]≤B[p+1]D[q+1] \le B[p+1] is the same with the roles exchanged: Up′U_{p'} with p′>pp' > p starts at B[p′]≥B[p+1]≥D[q+1]B[p'] \ge B[p+1] \ge D[q+1], so it meets VqV_q in at most one point. When the loop stops, p=np = n or q=dq = d. If p=np = n, every pair with a positive overlap has p′<np' < n and was visited. If q=dq = d, the same holds for the bins. □\square

Theorem (the forward projector). DD-VIEW returns out[q]=Pq\text{out}[q] = P_q.

Proof. By Lemma 1, gk(s)=f[k][j(p)]g_k(s) = f[k][j(p)] for ss in the interior of UpU_p, where j(p)j(p) is the column of sorted pixel pp, and gk(s)=0g_k(s) = 0 outside [B[0],B[n]][B[0], B[n]]. The ends of the intervals are a finite set and do not change the integral. So

1w∫JqΔgk(s) ds=∑pΔ ∣Up∩Vq∣w f[k][j(p)].\frac{1}{w}\int_{J_q}\Delta g_k(s)\,ds = \sum_{p} \frac{\Delta\,|U_p \cap V_q|}{w}\, f[k][j(p)].

By Lemma 2, line L9 adds exactly the terms of this sum with positive overlap, for each row kk that line L3 visits. Summing over kk gives PqP_q. □\square

Theorem (the transpose). Let WW be the list of triples (q,pixel,Δℓ/w)(q, \text{pixel}, \Delta\ell/w) that line L9 uses for all views. The forward projector is yq=∑(q,π,ω)∈Wωfπy_q = \sum_{(q, \pi, \omega) \in W} \omega f_\pi, and the back projector of the code is zπ=∑(q,π,ω)∈Wω gqz_\pi = \sum_{(q, \pi, \omega) \in W} \omega\, g_q. Then ⟨y,g⟩=∑Wωfπgq=⟨f,z⟩\langle y, g\rangle = \sum_W \omega f_\pi g_q = \langle f, z\rangle for all ff and gg, so the back projector is ATA^T. A pixel and a bin may appear in two triples only if they come from two views, which are different rows of AA, so the sum over WW is the sum over the nonzero entries of AA. □\square

Corollary 1 (mass). If s0≤min⁡kB[0]s_0 \le \min_k B[0] and s0+dw≥max⁡kB[n]s_0 + dw \ge \max_k B[n] for a view, then w∑qout[q]=h2∑i,jf[i][j]w \sum_q \text{out}[q] = h^2 \sum_{i,j} f[i][j].

Proof. Under the hypothesis, the bins tile an interval that contains each UpU_p. So ∑q∣Up∩Vq∣=∣Up∣=h∣c∣\sum_q |U_p \cap V_q| = |U_p| = h|c|. Then w∑qout[q]=∑k,pΔ h∣c∣ f[k][j(p)]=∑k,ph2f[k][j(p)]w\sum_q \text{out}[q] = \sum_{k,p} \Delta\, h|c|\, f[k][j(p)] = \sum_{k,p} h^2 f[k][j(p)]. □\square

Corollary 2 (a constant image). Let f≡1f \equiv 1 and let bin JqJ_q lie inside every interval [B[0],B[n]][B[0], B[n]], k=0,…,n−1k = 0, \ldots, n - 1. Then out[q]=nΔ=2/∣c∣\text{out}[q] = n\Delta = 2/|c|.

Proof. For each row, the UpU_p tile an interval that contains JqJ_q, so ∑p∣Up∩Jq∣=w\sum_p |U_p \cap J_q| = w, and the row adds Δ\Delta. □\square

The intervals [B[0],B[n]][B[0], B[n]] of the rows are [−∣c∣+ykσ,∣c∣+ykσ][-|c| + y_k\sigma, |c| + y_k\sigma], and ∣yk∣<1|y_k| < 1. So the condition of Corollary 2 holds for every bin with ∣scenter∣+w/2≤∣c∣−∣σ∣|s_{\text{center}}| + w/2 \le |c| - |\sigma|, which is the condition that the test uses.

Corollary 3 (axis-aligned rays). At θ=0\theta = 0, out[q]\text{out}[q] is the average over JqJ_q of the exact line integral of the pixel-square image ∑f[i][j]χij\sum f[i][j]\chi_{ij}.

Proof. At θ=0\theta = 0 the ray is the vertical line x=sx = s. For ss inside column jj, it crosses every row in a segment of length h=Δh = \Delta inside pixel (k,j)(k, j), so the line integral is ∑kΔf[k][j]=Δ∑kgk(s)\sum_k \Delta f[k][j] = \Delta\sum_k g_k(s). Integrate over JqJ_q and divide by ww. □\square

Remark (the approximation). For other angles the model differs from the line integral of the pixel-square image. The ray crosses row kk along a segment of length Δ\Delta, which may pass through two pixels of the row, while the model gives the whole length Δ\Delta to the pixel at the center line. For one row, the difference is at most Δ\Delta times the jump of ff between the two neighbors, and it occurs only for the rays whose segment in the row crosses a pixel border. For an image with a bounded gradient the jump is O(h)O(h), so the difference per row is O(h2)O(h^2) and the sum over the nn rows is O(h)O(h). This is a property of the model, not of the code.

Cost. By Lemma 2 the sweep of one line takes at most n+dn + d steps of O(1)O(1) work, and lines L4 and L5 take O(n+d)O(n + d). With nn lines per view and aa views, the time is O(an(n+d))O(a n (n + d)) in the real-RAM model, and the extra space is that of the two lists, O(n+d)O(n + d).

Complexity

In the real-RAM model:

  • Lines L4 and L5 build two sorted lists of n+1n + 1 and d+1d + 1 numbers in O(n+d)O(n + d) time.
  • The loop of lines L7 to L10 moves pp or qq at each step, so it runs at most n+dn + d times with O(1)O(1) work each.
  • Line L3 repeats this for nn lines.

So one view costs O(n(n+d))O(n(n + d)) time and O(n+d)O(n + d) extra space, and a sinogram of aa views costs O(an(n+d))O(a n (n + d)). In practice dd is about nn, which gives O(an2)O(a n^2), the same order as the pixel-driven and the ray-driven projectors, which cost O(an2)O(a n^2) and O(adn)O(a d n). The number of nonzero weights per view is at most n(n+d)n(n + d), because each step of the sweep gives at most one. A real code computes the bin borders once per view, not once per line. In 3D, De Man and Basu map the voxel borders and the detector cell borders onto a common plane and take the overlaps in the two directions separately, as the product of two 1D overlaps.

Properties

  • Matched pair. The back projector is the exact transpose of the forward projector. The test checks ∣⟨Ax,y⟩−⟨x,ATy⟩∣≤10−10∥Ax∥∥y∥|\langle A x, y\rangle - \langle x, A^T y\rangle| \le 10^{-10}\|A x\|\|y\|.
  • No ripple. A constant image gives a flat projection inside the image, because the shadows of the pixels in a row tile the detector line with no gap and no overlap. The pixel-driven projector splits each pixel between the two nearest bin centers, so its projection of a constant image ripples.
  • No moire pattern in the back projection. Each bin spreads its value over all pixels whose shadows it overlaps, in proportion to the overlap. A ray-driven back projector with thin rays misses pixels when the bins are wider than the pixels.
  • Mass conservation. Each pixel sends exactly its area, times its value, to the detector.
  • Direction dependent model. The lines switch from rows to columns at ∣cos⁡θ∣=∣sin⁡θ∣|\cos\theta| = |\sin\theta|. At θ=π/4\theta = \pi/4 both models apply, and they give slightly different weights.
  • Positive weights. All weights are nonnegative, which the convergence results of SART and SIRT need for their row and column sums.

Variants and improvements

  • Three dimensions (De Man and Basu 2004). Map the voxel borders and the detector cell borders onto a plane through the center of the volume, and take the area of overlap as the product of the overlaps in the two directions. The cost per view stays proportional to the number of voxels plus the number of detector cells per line.
  • Fan beam and cone beam. The rays of a view meet in a source point. The borders are mapped by a central projection from the source onto the common axis, not by the parallel map of line L4. The overlaps and the sweep are the same.
  • Branchless distance-driven projection. For GPUs, later work replaces the sweep with a difference of integrals of the image: precompute the cumulative sums of each line, then each bin value is a difference of two interpolated cumulative sums. This removes the branch of line L10.
  • Separable footprints. Long, Fessler and Balter in 2010 model the footprint of a voxel on the detector as a trapezoid instead of a rectangle. This is more accurate at oblique angles, at a higher cost.

When to use it

Use the distance-driven projector as the forward and back projector of an iterative method, such as SART, SIRT, MLEM or penalized least squares, when the detector bins are about as wide as the pixels or wider, and when the back projection must be free of high frequency artifacts. Use Siddon's algorithm when the weights must be the exact path lengths, and Joseph's projector for a smooth image model with a fixed cost per ray. Filtered back-projection needs only a back projector, and the pixel-driven back projector with linear interpolation is the usual choice there.

Pitfalls

  • Decreasing borders. For cos⁡θ<0\cos\theta < 0 (rows) or for the column case, the mapped borders come out in decreasing order. The merge needs increasing lists, so line L4 must reverse them and also reverse the pixel index.
  • Wrong normalization of the back projector. Some codes divide the back projected overlaps by the pixel width instead of the bin width, so that a constant sinogram gives a flat image. That pair is not an exact transpose. Use the same weights in both directions when an iterative method assumes ATA^T.
  • Detector too short. If the bins do not cover the shadow of the image, mass leaks out at the ends, as in the example. This is correct for the model, but a test of mass conservation must use a detector that covers the image.
  • Equal borders. If a pixel border and a bin border coincide, line L8 gives ℓ=0\ell = 0 for one pair. Line L9 must skip it, or the matrix gets explicit zero entries.
  • Forgetting the factor Δ\Delta. Without 1/∣cos⁡θ∣1/|\cos\theta| the projection of a constant image depends on the angle.

Implementations

The Python code computes the weights of one view with float or fractions.Fraction input, the forward projector, the back projector and the sparse matrix, with the bins of the shared pixel-driven projector imgkit.parallel_beam_matrix. The tests check the worked example exactly, the exact mass conservation for random integer images at five rational angles, the flat projection of a constant image against the ripple of the pixel-driven projector, the adjoint, the matrix against the projector, and the projection of a disk against the analytic Radon transform averaged over each bin.

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.

distance_driven_projector.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/distance-driven-projector/. The authors are listed in prov/MVREDC.jsonl.
"""The distance-driven projector and its exact transpose, for 2D parallel beams.

Conventions:
- The image is n x n on the square [-1, 1]^2, stored as img[i][j] with row i
  from the top and column j from the left. 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.
- A view has the angle theta, and the detector coordinate of a point (x, y)
  is s = x cos(theta) + y sin(theta). Bin b covers [s0 + b w, s0 + (b + 1) w].
- The value of a bin is the average over its width of the projection of the
  image model: inside each row (or column) the image is constant on each
  pixel, and the row has the thickness h / |cos(theta)| along the ray.
- The code works with float or with fractions.Fraction values of cos(theta),
  sin(theta), s0 and w. With Fraction input the weights are exact.
"""

import math
from fractions import Fraction


def _overlaps(pb, bb):
    """Sweep two increasing lists of cell borders; yield (cell of pb, cell of bb, overlap length)."""
    p, q = 0, 0
    while p < len(pb) - 1 and q < len(bb) - 1:  # @line L7
        length = min(pb[p + 1], bb[q + 1]) - max(pb[p], bb[q])  # @line L8
        if length > 0:
            yield p, q, length  # @line L9
        if pb[p + 1] < bb[q + 1]:  # @line L10
            p += 1
        else:
            q += 1


def view_weights(n, c, sn, s0, w, nbins):
    """The (b, i, j, weight) entries of one view with c = cos(theta), sn = sin(theta)."""
    exact = any(isinstance(v, Fraction) for v in (c, sn, s0, w))
    h = Fraction(2, n) if exact else 2.0 / n  # @line L1
    bins = [s0 + b * w for b in range(nbins + 1)]  # @line L5
    out = []
    rows = abs(c) >= abs(sn)  # @line L2
    step = h / abs(c) if rows else h / abs(sn)
    for k in range(n):  # @line L3
        if rows:  # row k: pixel borders x = -1 + j h at the height y_k
            y = 1 - (2 * k + 1) * h / 2
            borders = [(-1 + j * h) * c + y * sn for j in range(n + 1)]
        else:  # column k: pixel borders y = 1 - i h at the abscissa x_k
            x = -1 + (2 * k + 1) * h / 2
            borders = [x * c + (1 - i * h) * sn for i in range(n + 1)]
        flip = borders[0] > borders[-1]  # @line L4
        if flip:
            borders.reverse()
        for p, b, length in _overlaps(borders, bins):  # @line L6
            m = n - 1 - p if flip else p
            i, j = (k, m) if rows else (m, k)
            out.append((b, i, j, step * length / w))
    return out


def detector(nbins):
    """(s0, w) of the bins of imgkit: nbins bins of width 2 sqrt(2) / nbins on [-sqrt(2), sqrt(2)]."""
    return -math.sqrt(2.0), 2.0 * math.sqrt(2.0) / nbins


def dd_project_view(img, c, sn, s0, w, nbins):
    """The bin values of one view."""
    out = [0 * w] * nbins
    for b, i, j, wt in view_weights(len(img), c, sn, s0, w, nbins):
        out[b] += wt * img[i][j]
    return out  # @line L11


def dd_project(img, angles, nbins):
    """The sinogram as a flat list: entry k * nbins + b holds angle k and bin b."""
    s0, w = detector(nbins)
    out = []
    for theta in angles:
        out.extend(dd_project_view(img, math.cos(theta), math.sin(theta), s0, w, nbins))
    return out


def dd_back_project(n, angles, nbins, values):
    """The exact transpose of dd_project: each weight carries its bin value back to its pixel."""
    s0, w = detector(nbins)
    out = [[0.0] * n for _ in range(n)]
    for k, theta in enumerate(angles):
        for b, i, j, wt in view_weights(n, math.cos(theta), math.sin(theta), s0, w, nbins):
            out[i][j] += wt * values[k * nbins + b]
    return out


def dd_matrix(n, angles, nbins):
    """The system matrix as sparse rows of (column, weight) pairs, column i * n + j."""
    s0, w = detector(nbins)
    rows = []
    for theta in angles:
        acc = [dict() for _ in range(nbins)]
        for b, i, j, wt in view_weights(n, math.cos(theta), math.sin(theta), s0, w, nbins):
            acc[b][i * n + j] = acc[b].get(i * n + j, 0.0) + wt
        rows.extend(sorted(d.items()) for d in acc)
    return rows
imgkit.py 322 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/.
"""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
test_distance_driven_projector.py 96 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/distance-driven-projector/. The authors are listed in prov/MVREDC.jsonl.

import math
import random
from fractions import Fraction as F

import imgkit as ik
from distance_driven_projector import (
    dd_back_project,
    dd_matrix,
    dd_project,
    dd_project_view,
    detector,
    view_weights,
)


def test_worked_example() -> None:
    # n = 2, cos = 4/5, sin = 3/5, four bins of width 1/2 on [-1, 1]
    w = view_weights(2, F(4, 5), F(3, 5), F(-1), F(1, 2), 4)
    assert sorted(w) == sorted([
        (1, 0, 0, F(5, 4)), (2, 0, 0, F(3, 4)), (2, 0, 1, F(1, 2)), (3, 0, 1, F(5, 4)),
        (0, 1, 0, F(5, 4)), (1, 1, 0, F(1, 2)), (1, 1, 1, F(3, 4)), (2, 1, 1, F(5, 4)),
    ])
    p = dd_project_view([[1, 2], [3, 4]], F(4, 5), F(3, 5), F(-1), F(1, 2), 4)
    assert p == [F(15, 4), F(23, 4), F(27, 4), F(5, 2)]
    # the detector misses 1/8 of pixel (0, 1) and 1/8 of pixel (1, 0)
    assert F(1, 2) * sum(p) == 10 - F(2, 8) - F(3, 8)


def test_mass_is_conserved_exactly() -> None:
    rng = random.Random(1)
    n = 6
    img = [[F(rng.randint(0, 9)) for _ in range(n)] for _ in range(n)]
    mass = sum(sum(row) for row in img) * F(2, n) ** 2
    s0, w, nbins = F(-3, 2), F(1, 4), 12
    for c, sn in ((F(4, 5), F(3, 5)), (F(-3, 5), F(4, 5)), (F(12, 13), F(-5, 13)), (F(5, 13), F(12, 13)), (F(1), F(0))):
        p = dd_project_view(img, c, sn, s0, w, nbins)
        assert w * sum(p) == mass


def test_constant_image_has_no_ripple() -> None:
    n, nbins = 32, 23
    angles = [0.0, 0.3, 1.2, 2.0]
    one = [[1.0] * n for _ in range(n)]
    p = dd_project(one, angles, nbins)
    q = ik.sp_matvec(ik.parallel_beam_matrix(n, angles, nbins), ik.flatten(one))
    s0, w = detector(nbins)
    ripple = 0.0
    for k, theta in enumerate(angles):
        c, sn = abs(math.cos(theta)), abs(math.sin(theta))
        for b in range(nbins):
            s = s0 + (b + 0.5) * w
            if abs(s) + w / 2 < max(c, sn) - min(c, sn):
                assert abs(p[k * nbins + b] - 2.0 / max(c, sn)) < 1e-12
                ripple = max(ripple, abs(q[k * nbins + b] - 2.0 / max(c, sn)))
    # the pixel-driven projector of imgkit has a ripple on the same bins
    assert ripple > 1e-3


def test_adjoint() -> None:
    rng = random.Random(2)
    n, nbins = 16, 23
    angles = [k * math.pi / 7 for k in range(7)]
    x = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(n)]
    y = [rng.uniform(-1, 1) for _ in range(len(angles) * nbins)]
    ax = dd_project(x, angles, nbins)
    aty = dd_back_project(n, angles, nbins, y)
    lhs = sum(a * b for a, b in zip(ax, y))
    rhs = ik.img_dot(x, aty)
    assert abs(lhs - rhs) <= 1e-10 * math.sqrt(sum(a * a for a in ax)) * math.sqrt(sum(b * b for b in y))


def test_matrix_matches_projector() -> None:
    rng = random.Random(3)
    n, nbins = 16, 23
    angles = [0.0, 0.5, 1.0, 2.0, 3.0]
    x = [[rng.random() for _ in range(n)] for _ in range(n)]
    a = ik.sp_matvec(dd_matrix(n, angles, nbins), ik.flatten(x))
    b = dd_project(x, angles, nbins)
    assert max(abs(p - q) for p, q in zip(a, b)) < 1e-12


def test_disk_projection() -> None:
    n, nbins = 32, 23
    angles = [k * math.pi / 8 for k in range(8)]
    p = dd_project(ik.disk_phantom(n, 0.5), angles, nbins)
    s0, w = detector(nbins)
    for k in range(len(angles)):
        for b in range(nbins):
            if abs(s0 + (b + 0.5) * w) < 0.35:
                # the average of the analytic projection 2 sqrt(1/4 - s^2) over the bin
                m = 64
                avg = sum(2.0 * math.sqrt(max(0.0, 0.25 - (s0 + (b + (r + 0.5) / m) * w) ** 2)) for r in range(m)) / m
                assert abs(p[k * nbins + b] - avg) < 2.0 / n

History

Bruno De Man and Samit Basu presented the distance-driven method in 2002 at the IEEE Nuclear Science Symposium and Medical Imaging Conference. They argued that the pixel-driven projector is a poor forward projector and the ray-driven projector a poor back projector, and that the distance-driven method is good in both directions at a similar cost. Their 2004 paper in Physics in Medicine and Biology gave the 3D form for cone-beam and helical CT. Later work moved the method to GPUs, and Long, Fessler and Balter in 2010 refined its rectangular footprint into the separable footprint projector.

References

  1. Bruno De Man and Samit Basu, Distance-driven projection and backprojection, 2002 IEEE Nuclear Science Symposium Conference Record, vol. 3, 2002, pp. 1477 to 1480 (the 2D method, the comparison with pixel-driven and ray-driven projectors)
  2. Bruno De Man and Samit Basu, Distance-driven projection and backprojection in three dimensions, Physics in Medicine and Biology 49(11), 2004, pp. 2463 to 2475 (the 3D form with the overlaps computed separately in the two detector directions; general locator)
  3. A. C. Kak and M. Slaney, Principles of Computerized Tomographic Imaging, SIAM Classics in Applied Mathematics 33, 2001, Chapter 7, algebraic reconstruction algorithms (the system matrix of the discrete model y = A x)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

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