Algorithm Search⌘K

Algorithmcore

Siddon's algorithm

Also called Siddon ray tracing.

Compute the exact length of a ray in each pixel or voxel it crosses, by merging the sorted parameters of its crossings with the grid lines or planes.

Time
O(a d n) worst
Space
O(n) 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
Robert L. Siddon, 1985

Siddon's algorithm computes, for one ray, the exact length of its path inside each pixel of a 2D grid or each voxel of a 3D grid. These lengths are the entries of one row of the system matrix AA in the discrete model y=Axy = A x of transmission tomography, where xx holds the pixel values and yiy_i approximates the line integral of the X-ray transform along ray ii. The method writes the ray as p(α)=p0+α(p1−p0)p(\alpha) = p_0 + \alpha(p_1 - p_0), lists the values of α\alpha where the ray meets each family of grid lines, merges these sorted lists, and reads off one pixel and one length between each two neighbors. It takes O(n)O(n) time per ray on an n×nn \times n grid. It is the standard ray-driven projector for the iterative methods SART, SIRT and ART. Joseph's projector and the distance-driven projector are cheaper or smoother approximations of the same matrix.

In plain words

Draw a straight line across a sheet of squared paper. The line passes through some squares, and it spends a different length in each one. Siddon's method finds these lengths with no guessing.

Walk along the line from its start. Each time the line crosses a vertical grid line or a horizontal grid line, write down how far along the line you are. The crossings with the vertical lines come in order, and so do the crossings with the horizontal lines. Merge the two ordered lists into one. Between two crossings that are next to each other, the line stays in one square. The distance between the two crossings is the length in that square, and the point halfway between them tells you which square it is.

The problem

The image is n×nn \times n on the square [−1,1]2[-1, 1]^2, with pixel size h=2/nh = 2/n. Pixel (i,j)(i, j), in row ii from the top and column jj from the left, is the closed square [−1+jh,−1+(j+1)h]×[1−(i+1)h,1−ih][-1 + jh, -1 + (j+1)h] \times [1 - (i+1)h, 1 - ih]. Its center 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. A ray is the segment from p0=(x0,y0)p_0 = (x_0, y_0) to p1=(x1,y1)p_1 = (x_1, y_1). The output is the list of pairs (pixel, length) for each pixel whose intersection with the segment has positive length, in the order in which the ray meets them. For a piecewise constant image f=∑i,jxijχijf = \sum_{i,j} x_{ij} \chi_{ij}, the sum of length times value is the exact line integral of ff along the segment.

In parallel-beam geometry, ray (k,b)(k, b) is the line xcos⁡θk+ysin⁡θk=sbx\cos\theta_k + y\sin\theta_k = s_b of the Radon transform, with ω=(cos⁡θ,sin⁡θ)\omega = (\cos\theta, \sin\theta) and ω⊥=(−sin⁡θ,cos⁡θ)\omega^\perp = (-\sin\theta, \cos\theta). The code takes p0=sbω−2ω⊥p_0 = s_b\omega - 2\omega^\perp and p1=sbω+2ω⊥p_1 = s_b\omega + 2\omega^\perp, a segment long enough to cross the whole square.

The algorithm

  1. SIDDON(n, p0, p1) ▷ grid lines x = -1 + k h and y = -1 + k h, h = 2/n
  2. 1dx ← x1 - x0, dy ← y1 - y0, D ← sqrt(dx² + dy²)
  3. 2[α_min, α_max] ← [0, 1] ∩ {α : p(α) ∈ [-1, 1]²} ▷ one interval per axis with dx or dy ≠ 0
  4. 3if α_min ≥ α_max then return the empty list
  5. 4Ax ← the α in (α_min, α_max) with x0 + α dx = -1 + k h for an integer k, increasing
  6. 5Ay ← the α in (α_min, α_max) with y0 + α dy = -1 + k h for an integer k, increasing
  7. 6S ← α_min, then MERGE(Ax, Ay), then α_max
  8. 7for each pair (α_prev, α_next) of neighbors in S with α_next > α_prev do
  9. 8(x_m, y_m) ← p((α_prev + α_next) / 2)
  10. 9j ← ⌊(x_m + 1)/h⌋, i ← ⌊(1 - y_m)/h⌋
  11. 10output (i, j, (α_next - α_prev) D)

Line L2 clips the segment to the square. For an axis with dx≠0dx \ne 0, the ray is inside the slab −1≤x≤1-1 \le x \le 1 for α\alpha between (−1−x0)/dx(-1 - x_0)/dx and (1−x0)/dx(1 - x_0)/dx. If dx=0dx = 0, the ray is inside the slab for all α\alpha or for none. Lines L4 and L5 do not scan all n+1n + 1 grid lines. They compute the first and last index kk of the lines that the clipped segment crosses, with a floor and a ceiling of n(x+1)/2n(x + 1)/2 at its two ends, and then step kk up for dx>0dx > 0 or down for dx<0dx < 0. So each list is already sorted, and line L6 is the merge step of merge sort. Line L7 skips a pair with equal values: a ray through a grid corner meets a vertical and a horizontal line at the same α\alpha. Line L9 finds the pixel from the midpoint, which is strictly inside one pixel. In 3D, line L5 has a third list for the zz planes, and the merge takes three lists.

To project an image, run SIDDON for each ray and sum length times pixel value. To back-project, run SIDDON for each ray again and add length times the ray value to each pixel. The two are exact transposes of each other, because they use the same weights.

Example

Take n=4n = 4, so h=1/2h = 1/2, and the ray from p0=(−1,−1/2)p_0 = (-1, -1/2) to p1=(1,1)p_1 = (1, 1). Then dx=2dx = 2, dy=3/2dy = 3/2 and D=5/2D = 5/2. The whole segment is in the square, so αmin⁡=0\alpha_{\min} = 0 and αmax⁡=1\alpha_{\max} = 1.

step values
xx lines −1/2,0,1/2-1/2, 0, 1/2 at α=(x+1)/2\alpha = (x + 1)/2 Ax=1/4,1/2,3/4A_x = 1/4, 1/2, 3/4
yy lines 0,1/20, 1/2 at α=(y+1/2)/(3/2)\alpha = (y + 1/2)/(3/2) Ay=1/3,2/3A_y = 1/3, 2/3
merged SS 0,1/4,1/3,1/2,2/3,3/4,10, 1/4, 1/3, 1/2, 2/3, 3/4, 1
differences 1/4,1/12,1/6,1/6,1/12,1/41/4, 1/12, 1/6, 1/6, 1/12, 1/4
lengths =D×= D \times difference 5/8,5/24,5/12,5/12,5/24,5/85/8, 5/24, 5/12, 5/12, 5/24, 5/8
pixels (i,j)(i, j) from the midpoints (2,0),(2,1),(1,1),(1,2),(0,2),(0,3)(2,0), (2,1), (1,1), (1,2), (0,2), (0,3)

The first midpoint is α=1/8\alpha = 1/8, the point (−0.75,−0.3125)(-0.75, -0.3125). It is in column ⌊0.25/0.5⌋=0\lfloor 0.25 / 0.5 \rfloor = 0 and row ⌊1.3125/0.5⌋=2\lfloor 1.3125/0.5 \rfloor = 2. The lengths add up to 5/2=D5/2 = D, because the whole segment is inside the square. All values are exact rationals, and the test file checks them with fractions.Fraction.

The code below also projects a disk of radius 1/21/2, sampled at the pixel centers of a 32×3232 \times 32 grid, along 88 angles and 2323 bins. At the bins with ∣s∣<0.35|s| < 0.35, the projection differs from the analytic value 21/4−s22\sqrt{1/4 - s^2} by at most 0.0610.061. That is less than one pixel width 2/n=0.06252/n = 0.0625, because the pixelated disk and the true disk differ by at most about one pixel along a chord. For the smooth image e−16∣x∣2e^{-16|x|^2}, sampled at the pixel centers, the largest error against the exact projection π/16 e−16s2\sqrt{\pi/16}\,e^{-16 s^2} is 0.01150.0115 for n=16n = 16, 0.00240.0024 for n=32n = 32 and 0.000590.00059 for n=64n = 64. These are measurements of this setup. The error falls by about 4 when nn doubles, as for a second order method.

Correctness

The pieces between neighbors in SS partition the clipped segment. Inside one piece no α\alpha of a grid line occurs, so x(α)x(\alpha) and y(α)y(\alpha) each stay between two neighboring grid lines, and the open piece lies inside one pixel: the pixel of its midpoint. The length of the piece is (αnext−αprev)D(\alpha_{\text{next}} - \alpha_{\text{prev}})D, because pp is affine with speed DD. A pixel cannot hold two pieces, because between them the ray crosses a grid line, and a pixel lies on one side of each grid line. So the output lists each pixel with positive intersection length once, with its exact length. The full proof, with the clipping of line L2 and the index ranges of lines L4 and L5, is in proofs/correctness.md.

Proof: Correctness of Siddon's algorithmfull

We use the conventions of the page. The image is n×nn \times n on Q=[−1,1]2Q = [-1, 1]^2 with h=2/nh = 2/n. Pixel (i,j)(i, j) is the closed square Pij=[−1+jh,−1+(j+1)h]×[1−(i+1)h,1−ih]P_{ij} = [-1 + jh, -1 + (j+1)h] \times [1 - (i+1)h, 1 - ih]. The ray is p(α)=p0+αdp(\alpha) = p_0 + \alpha d with d=p1−p0=(dx,dy)≠0d = p_1 - p_0 = (d_x, d_y) \ne 0, 0≤α≤10 \le \alpha \le 1, and D=∣d∣D = |d|. We work in exact arithmetic. A vertical grid line is a line x=−1+khx = -1 + kh and a horizontal grid line is a line y=−1+khy = -1 + kh, for an integer kk with 0≤k≤n0 \le k \le n.

We prove that SIDDON returns, for each pixel PijP_{ij} whose intersection with the segment has positive length, exactly one triple (i,j,ℓ)(i, j, \ell) with ℓ\ell that length, and no other triple. For a ray that lies on a grid line, the length goes to one of the two pixels that share that line, as the page says.

Lemma 1 (clipping, line L2). Let I={α∈[0,1]:p(α)∈Q}I = \{\alpha \in [0, 1] : p(\alpha) \in Q\}. If II has positive length, line L2 sets [αmin⁡,αmax⁡]=I[\alpha_{\min}, \alpha_{\max}] = I. If II is empty or one point, line L3 returns the empty list, which is correct.

Proof. p(α)∈Qp(\alpha) \in Q if and only if −1≤x0+αdx≤1-1 \le x_0 + \alpha d_x \le 1 and −1≤y0+αdy≤1-1 \le y_0 + \alpha d_y \le 1. For dx≠0d_x \ne 0, the first condition is α\alpha between (−1−x0)/dx(-1 - x_0)/d_x and (1−x0)/dx(1 - x_0)/d_x, a closed interval, and line L2 intersects [0,1][0, 1] with it. For dx=0d_x = 0 the condition does not depend on α\alpha: it holds for all α\alpha or for none. The same holds for yy. An intersection of closed intervals is a closed interval, so I=[αmin⁡,αmax⁡]I = [\alpha_{\min}, \alpha_{\max}] when it is not empty. A segment of zero length meets no pixel with positive length. □\square

The code tests −1≤c0<1-1 \le c_0 < 1 when dc=0d_c = 0, not c0≤1c_0 \le 1. A ray on the line x=1x = 1 touches only the border of QQ, and the rule of line L9 would give it to column nn, which does not exist. So the code drops it. This changes only rays on the border of QQ.

Lemma 2 (the crossing lists, lines L4 and L5). Suppose dx≠0d_x \ne 0. Line L4 returns, in increasing order, exactly the values α∈(αmin⁡,αmax⁡)\alpha \in (\alpha_{\min}, \alpha_{\max}) at which x(α)=x0+αdxx(\alpha) = x_0 + \alpha d_x is on a vertical grid line. The same holds for line L5 and the horizontal lines.

Proof. Put u(α)=n(x(α)+1)/2u(\alpha) = n(x(\alpha) + 1)/2. Then x(α)=−1+khx(\alpha) = -1 + kh if and only if u(α)=ku(\alpha) = k. The function uu is affine and strictly monotone, so it maps (αmin⁡,αmax⁡)(\alpha_{\min}, \alpha_{\max}) onto the open interval between u(αmin⁡)u(\alpha_{\min}) and u(αmax⁡)u(\alpha_{\max}). Call its ends u−<u+u_- < u_+. The integers in (u−,u+)(u_-, u_+) are k=⌊u−⌋+1,…,⌈u+⌉−1k = \lfloor u_- \rfloor + 1, \ldots, \lceil u_+ \rceil - 1, which is the range that the code builds. Each such kk gives exactly one α=(−1+kh−x0)/dx\alpha = (-1 + kh - x_0)/d_x in the open interval. Because x(α)∈[−1,1]x(\alpha) \in [-1, 1] on II, we have u∈[0,n]u \in [0, n], so each kk is a real grid line. If dx>0d_x > 0, then α\alpha increases with kk and the code lists kk upward. If dx<0d_x < 0, then α\alpha decreases with kk and the code lists kk downward. So the list is increasing in both cases. □\square

If dx=0d_x = 0, line L4 returns the empty list. That is correct too: then xx is constant, and either it is not on a grid line, or it is on one for every α\alpha, which is the case of a ray on a grid line that we treat at the end.

Lemma 3 (merge, line L6). SS is the increasing list of αmin⁡\alpha_{\min}, all values of Lemma 2 for both axes, and αmax⁡\alpha_{\max}. Equal values from the two lists stay as two equal neighbors.

Proof. AxA_x and AyA_y are increasing by Lemma 2. MERGE of two increasing lists is the increasing list of all their elements, with repetitions, by the standard invariant of the merge step of merge sort: the output so far is increasing and holds the smallest elements. All values are in (αmin⁡,αmax⁡)(\alpha_{\min}, \alpha_{\max}), so putting αmin⁡\alpha_{\min} in front and αmax⁡\alpha_{\max} at the end keeps the list increasing. □\square

Let β0<β1<⋯<βm\beta_0 < \beta_1 < \cdots < \beta_m be the distinct values of SS. These are the pairs that the loop of line L7 keeps, because it skips the pairs of equal neighbors. Put Jr=(βr−1,βr)J_r = (\beta_{r-1}, \beta_r) for r=1,…,mr = 1, \ldots, m.

Lemma 4 (one piece, one pixel). Assume the ray is not on a grid line. For each rr, the open piece p(Jr)p(J_r) lies in the interior of one pixel PijP_{ij}, and lines L8 and L9 compute this (i,j)(i, j).

Proof. Take α∈Jr\alpha \in J_r. By Lemmas 2 and 3, no value of JrJ_r puts x(α)x(\alpha) or y(α)y(\alpha) on a grid line. Also p(α)p(\alpha) is in QQ, by Lemma 1. Consider xx. If dx≠0d_x \ne 0, the continuous function x(α)x(\alpha) on the interval JrJ_r never meets a grid line, so it stays in one open interval (−1+jh,−1+(j+1)h)(-1 + jh, -1 + (j+1)h). If dx=0d_x = 0, then xx is constant and, by the assumption, not on a grid line, so it is in one such interval as well. The same holds for yy and an interval (1−(i+1)h,1−ih)(1 - (i+1)h, 1 - ih). So p(Jr)p(J_r) is in the interior of PijP_{ij}. The midpoint (xm,ym)(x_m, y_m) of line L8 is in p(Jr)p(J_r). From −1+jh<xm<−1+(j+1)h-1 + jh < x_m < -1 + (j+1)h we get j<(xm+1)/h<j+1j < (x_m + 1)/h < j + 1, so ⌊(xm+1)/h⌋=j\lfloor (x_m + 1)/h \rfloor = j. From 1−(i+1)h<ym<1−ih1 - (i+1)h < y_m < 1 - ih we get i<(1−ym)/h<i+1i < (1 - y_m)/h < i + 1, so ⌊(1−ym)/h⌋=i\lfloor (1 - y_m)/h \rfloor = i. The clamp to [0,n−1][0, n-1] does not change these values. □\square

Lemma 5 (length, line L10). The length of p(Jr)p(J_r) is (βr−βr−1)D(\beta_r - \beta_{r-1})D.

Proof. ∣p(α)−p(α′)∣=∣α−α′∣ ∣d∣=∣α−α′∣D|p(\alpha) - p(\alpha')| = |\alpha - \alpha'|\,|d| = |\alpha - \alpha'| D. □\square

Theorem. Assume the ray is not on a grid line. Then SIDDON returns each pixel PijP_{ij} whose intersection with the segment has positive length exactly once, with the length of that intersection, and no other pixel.

Proof. The segment inside QQ is p(I)p(I) by Lemma 1, and II is the union of the pieces JrJ_r and the finite set {β0,…,βm}\{\beta_0, \ldots, \beta_m\}. A finite set of points has length 0. So the length of p(I)∩Pijp(I) \cap P_{ij} is the sum of the lengths of the pieces p(Jr)p(J_r) that lie in PijP_{ij}. By Lemma 4, every piece lies in exactly one pixel and in the interior of it.

It remains to show that no two pieces lie in the same pixel. Take r<r′r < r' with both pieces in PijP_{ij}. Then βr\beta_r is in (αmin⁡,αmax⁡)(\alpha_{\min}, \alpha_{\max}) and is a value of AxA_x or AyA_y, so p(βr)p(\beta_r) is on a grid line, say x=−1+khx = -1 + kh, and dx≠0d_x \ne 0. On JrJ_r the value of xx is on one side of this line, and on Jr′J_{r'} it is on the other side, because x(α)x(\alpha) is strictly monotone. Both sides cannot meet the interior of PijP_{ij}, because the interior of a pixel lies on one side of each grid line. This is a contradiction.

So each pixel with positive length gets exactly one triple, with its full length by Lemma 5. A pixel with zero length gets no piece, so it gets no triple. □\square

A ray on a grid line. Suppose dx=0d_x = 0 and x0=−1+khx_0 = -1 + kh with 0≤k<n0 \le k < n. Then the segment touches columns k−1k - 1 and kk (or only column kk when k=0k = 0), and the closed intersection with a pixel of each column has positive length. Lemmas 1 to 3 and 5 hold as before. In the proof of Lemma 4, yy still stays in one open row interval, and the midpoint gives (xm+1)/h=k(x_m + 1)/h = k, so line L9 returns column kk. So the code returns the pixels of column kk with their full lengths, and none of column k−1k - 1. This is the convention of the page: the length goes to the pixel on the right of a vertical line, and below a horizontal line by the same argument with ⌊(1−ym)/h⌋\lfloor (1 - y_m)/h \rfloor. The sum of all lengths is still the length of p(I)p(I), so a projection of an image that is constant across the line is still exact.

Exactness with rationals. All the operations of lines L2 to L9 are additions, subtractions, products, quotients, floors and ceilings of the input coordinates and the integers kk and nn. So with rational input, every α\alpha is rational and computed exactly, and all comparisons in Lemma 2, Lemma 3 and line L7 are exact. The only square root is DD. If DD is rational, as for the directions (3,4)(3, 4) or (5,12)(5, 12), every output length is exact. This is the setting of the test that compares the output with a brute-force clip of the segment against each pixel.

Projection and back projection. Let AA be the matrix with Ar,in+j=ℓA_{r, in + j} = \ell for each output triple (i,j,ℓ)(i, j, \ell) of ray rr. The projector computes (Ax)r=∑ℓ xij(Ax)_r = \sum \ell\, x_{ij} over the triples of ray rr, and the back projector adds ℓ yr\ell\, y_r to pixel (i,j)(i, j) for the same triples, which is (ATy)in+j(A^T y)_{in+j}. So ⟨Ax,y⟩=∑r∑(i,j,ℓ)ℓ xij yr=⟨x,ATy⟩\langle Ax, y\rangle = \sum_r \sum_{(i,j,\ell)} \ell\, x_{ij}\, y_r = \langle x, A^T y\rangle for all xx and yy. By the theorem, for a piecewise constant image f=∑xijχPijf = \sum x_{ij}\chi_{P_{ij}}, (Ax)r(Ax)_r is the exact integral of ff along the segment of ray rr.

Complexity

In the real-RAM model:

  • Lines L1 to L3 take O(1)O(1).
  • The clipped segment crosses at most n+1n + 1 vertical and n+1n + 1 horizontal grid lines. Lines L4 and L5 compute their α\alpha values in O(n)O(n) time, with no search.
  • The merge of line L6 takes O(n)O(n), and the loop of lines L7 to L10 runs at most 2n+12n + 1 times with O(1)O(1) work each.

So one ray takes O(n)O(n) time and O(n)O(n) extra space, and a sinogram of aa angles and dd bins takes O(adn)O(a d n). The output of one ray has at most 2n−12n - 1 pixels, so the bound is tight up to a constant. In 3D, an n×n×nn \times n \times n grid gives O(n)O(n) per ray in the same way, with three lists. Siddon's paper presents this as the gain over a method that tests every voxel against the ray, which costs O(n3)O(n^3) per ray in 3D.

Properties

  • Exact. The weights are the true intersection lengths of a line and the pixel squares. The forward projection of a piecewise constant image is its exact line integral. With rational endpoints and a rational length DD (a direction such as (3,4)(3, 4)), the code returns exact rationals.
  • Matched pair. The back projector uses the same weights, so it is the exact adjoint ATA^T of the forward projector. Iterative methods that assume ATA^T, such as SIRT and the Landweber iteration, need this.
  • Ray-driven. The work is organized by rays. Each ray reads (forward) or writes (back projection) a thin set of pixels. On parallel hardware, the back projection has write conflicts, because two rays may update the same pixel.
  • Aliasing of thin rays. A ray has zero width, while a detector bin has a finite width. When the bins are wider than the pixels, some pixels are crossed by no ray of a view, and the back projection of a smooth sinogram shows a moire pattern. The distance-driven projector integrates over the bin width and avoids this.

Variants and improvements

  • Incremental form (Jacobs et al. 1998). Keep the next crossing αx\alpha_x and αy\alpha_y and the current index (i,j)(i, j). At each step take the smaller of the two, add its distance to the output, and step jj or ii by ±1\pm 1. There is no merge list and no floor at each pixel. The same idea is the Amanatides-Woo traversal of computer graphics and the digital differential analyzer of line drawing.
  • 3D cone beam. Each ray runs from the source to the center of a detector cell. The algorithm is the same with three plane families.
  • Several rays per bin. Trace a few rays across the width of each detector bin and average them. This reduces the aliasing of thin rays at a proportional cost.
  • Integer coordinates. With the grid lines at integers and rational endpoints, all α\alpha values are rational and the comparisons in the merge are exact. The test file uses this to check the code against a brute-force clip of the segment with each pixel.

When to use it

Use Siddon's algorithm when the system matrix must hold the exact intersection lengths: for an exact model of a piecewise constant image, for a matched projector and back projector in ART, SART and SIRT, for dose calculations in radiotherapy, and for digitally reconstructed radiographs. Use Joseph's projector when a smoother model of the image is better and a fixed cost per row is easier to vectorize. Use the distance-driven projector when the detector bins are wide and the back projection must be free of moire patterns. Filtered back-projection needs no system matrix at all.

Pitfalls

  • Rounding at the grid lines. In floating point, a crossing may land a tiny distance on the wrong side of a grid line. The floor in line L9 then picks a neighbor pixel for a piece of length near zero. This is harmless for the weights, but code that assumes each pixel appears once must merge such entries. Line L9 must also clamp ii and jj to [0,n−1][0, n - 1].
  • Equal crossings. A ray through a grid corner gives the same α\alpha in both lists. Without the test αnext>αprev\alpha_{\text{next}} > \alpha_{\text{prev}} of line L7, the code outputs a piece of length zero, and with rounding it may put it in a wrong pixel.
  • A ray on a grid line. If dx=0dx = 0 and x0x_0 is a grid line, the ray runs along the border of two pixel columns. The intersection length is the full length for both. The code gives it to the column on the right, by the floor in line L9. Another convention is half to each. Pick one and keep it.
  • Sorting instead of merging. Line L6 needs only a merge, because lines L4 and L5 give sorted lists. A general sort costs O(nlog⁡n)O(n \log n) per ray.
  • Wrong row direction. Row ii counts from the top while yy goes up. Line L9 uses 1−ym1 - y_m, not ym+1y_m + 1. A wrong sign flips the image upside down.

Implementations

The Python code traces rays in 2D with float or fractions.Fraction coordinates. It builds parallel-beam rays with the same bins as the pixel-driven projector of the shared helper, and it gives the forward projector, the back projector and the sparse matrix. The tests check the worked example exactly, compare 40 rational rays with a brute-force clip against each pixel, check the adjoint, and compare the projections of a disk and of a Gaussian with the analytic Radon transform.

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

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

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

import cmath
import math

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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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

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


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


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


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


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


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


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

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


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


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


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


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


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


def poisson_sample(rng, lam):
    """An exact Poisson(lam) sample: a sum of Knuth samples with means at most 30."""
    if lam < 0:
        raise ValueError("negative mean")
    total = 0
    while lam > 30.0:
        total += _poisson_small(rng, 30.0)
        lam -= 30.0
    if lam > 0.0:
        total += _poisson_small(rng, lam)
    return total
siddon_algorithm.py 127 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/siddon-algorithm/. The authors are listed in prov/3SDE4K.jsonl.
"""Siddon's algorithm: exact intersection lengths of a ray with a pixel grid.

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. Column j covers
  x in [-1 + 2 j / n, -1 + 2 (j + 1) / n] and row i covers
  y in [1 - 2 (i + 1) / n, 1 - 2 i / n], so y goes up.
- A ray is the segment p(alpha) = p0 + alpha (p1 - p0), 0 <= alpha <= 1.
- The code works with float or with fractions.Fraction coordinates. With
  Fraction input every alpha is exact, and the lengths are exact when the
  length of p1 - p0 is rational (for example a 3-4-5 direction).
"""

import math
from fractions import Fraction


def seg_length(dx, dy):
    """The length of (dx, dy): exact for Fraction input with a rational length."""
    if isinstance(dx, Fraction) or isinstance(dy, Fraction):
        q = Fraction(dx) ** 2 + Fraction(dy) ** 2
        rn, rd = math.isqrt(q.numerator), math.isqrt(q.denominator)
        if rn * rn == q.numerator and rd * rd == q.denominator:
            return Fraction(rn, rd)
        return math.sqrt(q)
    return math.hypot(dx, dy)


def _plane_alphas(n, c0, dc, a_lo, a_hi):
    """The alphas in (a_lo, a_hi) where c0 + alpha dc meets a plane -1 + 2 k / n, in increasing order."""
    if dc == 0:
        return []
    u_lo = n * (c0 + a_lo * dc + 1) / 2  # the plane index at a_lo, as a real number
    u_hi = n * (c0 + a_hi * dc + 1) / 2
    k_first, k_last = math.floor(min(u_lo, u_hi)) + 1, math.ceil(max(u_lo, u_hi)) - 1
    ks = range(k_first, k_last + 1) if dc > 0 else range(k_last, k_first - 1, -1)
    if isinstance(dc, Fraction) or isinstance(c0, Fraction):
        return [(Fraction(2 * k, n) - 1 - c0) / dc for k in ks]
    return [(-1.0 + 2.0 * k / n - c0) / dc for k in ks]


def _merge(xs, ys):
    """Merge two increasing lists into one increasing list."""
    out, p, q = [], 0, 0
    while p < len(xs) and q < len(ys):
        if xs[p] <= ys[q]:
            out.append(xs[p])
            p += 1
        else:
            out.append(ys[q])
            q += 1
    return out + xs[p:] + ys[q:]


def siddon_ray(n, p0, p1):
    """The list of (i, j, length) of the pixels that the segment p0 -> p1 crosses, in ray order.

    A ray that lies on a grid line gives its length to the pixels on the
    right of it (for a vertical line) or below it (for a horizontal line).
    """
    (x0, y0), (x1, y1) = p0, p1
    dx, dy = x1 - x0, y1 - y0  # @line L1
    dist = seg_length(dx, dy)
    a_min, a_max = 0, 1  # @line L2
    for c0, dc in ((x0, dx), (y0, dy)):
        if dc == 0:
            if not -1 <= c0 < 1:
                return []
            continue
        a_a, a_b = (-1 - c0) / dc, (1 - c0) / dc
        a_min, a_max = max(a_min, min(a_a, a_b)), min(a_max, max(a_a, a_b))
    if a_min >= a_max:  # @line L3
        return []
    ax = _plane_alphas(n, x0, dx, a_min, a_max)  # @line L4
    ay = _plane_alphas(n, y0, dy, a_min, a_max)  # @line L5
    alphas = [a_min] + _merge(ax, ay) + [a_max]  # @line L6
    out = []
    for a_prev, a_next in zip(alphas, alphas[1:]):  # @line L7
        if a_next <= a_prev:
            continue  # a ray through a grid corner meets two planes at one alpha
        a_mid = (a_prev + a_next) / 2  # @line L8
        xm, ym = x0 + a_mid * dx, y0 + a_mid * dy
        j = min(n - 1, max(0, math.floor(n * (xm + 1) / 2)))  # @line L9
        i = min(n - 1, max(0, math.floor(n * (1 - ym) / 2)))
        out.append((i, j, (a_next - a_prev) * dist))  # @line L10
    return out


def parallel_rays(angles, nbins):
    """One ray per angle and bin, on the line x cos(theta) + y sin(theta) = s_b.

    The bins cover [-sqrt(2), sqrt(2)] with centers s_b = -sqrt(2) + (b + 1/2) w,
    w = 2 sqrt(2) / nbins, as in the pixel-driven projector of imgkit. Each ray
    runs from s omega - 2 omega_perp to s omega + 2 omega_perp, so it crosses the
    whole square. Ray k * nbins + b holds angle k and bin b.
    """
    smax = math.sqrt(2.0)
    width = 2.0 * smax / nbins
    rays = []
    for theta in angles:
        c, s = math.cos(theta), math.sin(theta)
        for b in range(nbins):
            sb = -smax + (b + 0.5) * width
            rays.append(((sb * c + 2.0 * s, sb * s - 2.0 * c), (sb * c - 2.0 * s, sb * s + 2.0 * c)))
    return rays


def siddon_project(img, rays):
    """The ray sums: for each ray, the sum over its pixels of length times value."""
    n = len(img)
    return [sum(w * img[i][j] for i, j, w in siddon_ray(n, p0, p1)) for p0, p1 in rays]


def siddon_back_project(n, rays, values):
    """The adjoint of siddon_project: each ray adds length times its value to its pixels."""
    out = [[0.0] * n for _ in range(n)]
    for (p0, p1), v in zip(rays, values):
        for i, j, w in siddon_ray(n, p0, p1):
            out[i][j] += w * v
    return out


def siddon_matrix(n, rays):
    """The system matrix as sparse rows of (column, weight) pairs, column i * n + j."""
    return [sorted((i * n + j, w) for i, j, w in siddon_ray(n, p0, p1)) for p0, p1 in rays]
test_siddon_algorithm.py 152 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/siddon-algorithm/. The authors are listed in prov/3SDE4K.jsonl.

import math
import random
from fractions import Fraction as F

import imgkit as ik
from siddon_algorithm import (
    parallel_rays,
    siddon_back_project,
    siddon_matrix,
    siddon_project,
    siddon_ray,
)


def clip_length(p0, p1, box):
    """Brute force: the length of the segment p0 -> p1 inside an axis-aligned box (Liang-Barsky)."""
    (x0, y0), (x1, y1) = p0, p1
    dx, dy = x1 - x0, y1 - y0
    lo, hi = F(0), F(1)
    for c0, dc, cmin, cmax in ((x0, dx, box[0], box[1]), (y0, dy, box[2], box[3])):
        if dc == 0:
            if not cmin <= c0 <= cmax:
                return F(0)
            continue
        a, b = (cmin - c0) / dc, (cmax - c0) / dc
        lo, hi = max(lo, min(a, b)), min(hi, max(a, b))
    if hi <= lo:
        return F(0)
    q = dx * dx + dy * dy
    return (hi - lo) * F(math.isqrt(q.numerator), math.isqrt(q.denominator))


def pixel_box(n, i, j):
    return (F(2 * j, n) - 1, F(2 * j + 2, n) - 1, 1 - F(2 * i + 2, n), 1 - F(2 * i, n))


def test_worked_example() -> None:
    out = siddon_ray(4, (F(-1), F(-1, 2)), (F(1), F(1)))
    assert out == [
        (2, 0, F(5, 8)),
        (2, 1, F(5, 24)),
        (1, 1, F(5, 12)),
        (1, 2, F(5, 12)),
        (0, 2, F(5, 24)),
        (0, 3, F(5, 8)),
    ]


def test_exact_against_brute_force() -> None:
    rng = random.Random(1)
    n = 8
    dirs = [(3, 4), (4, -3), (-5, 12), (12, 5), (8, -15), (1, 0), (0, 1), (-1, 0)]
    for trial in range(40):
        u, v = dirs[trial % len(dirs)]
        x0, y0 = F(rng.randint(-24, 24), 16), F(rng.randint(-24, 24), 16)
        t = F(rng.randint(1, 8), 4)
        p0, p1 = (x0, y0), (x0 + t * u, y0 + t * v)
        got = {}
        for i, j, w in siddon_ray(n, p0, p1):
            assert (i, j) not in got
            got[(i, j)] = w
        want = {}
        for i in range(n):
            for j in range(n):
                w = clip_length(p0, p1, pixel_box(n, i, j))
                if w > 0:
                    want[(i, j)] = w
        if u == 0 or v == 0:
            # a ray on a grid line touches two pixels; Siddon gives it to one of them
            assert sum(got.values()) == clip_length(p0, p1, (F(-1), F(1), F(-1), F(1)))
            assert all(want.get(key) == w for key, w in got.items())
        else:
            assert got == want


def test_total_length_is_the_chord() -> None:
    for u, v in ((3, 4), (5, -12), (7, 24)):
        p0, p1 = (F(-3, 2), F(-1, 3)), (F(-3, 2) + 3 * u, F(-1, 3) + 3 * v)
        total = sum(w for _, _, w in siddon_ray(16, p0, p1))
        assert total == clip_length(p0, p1, (F(-1), F(1), F(-1), F(1)))


def test_axis_parallel_ray() -> None:
    n = 8
    x = F(-1) + F(2 * 3 + 1, n)  # the center of column 3
    out = siddon_ray(n, (x, F(-2)), (x, F(2)))
    assert out == [(i, 3, F(2, n)) for i in range(n - 1, -1, -1)]
    assert siddon_ray(n, (F(1), F(-2)), (F(1), F(2))) == []
    assert siddon_ray(n, (F(-3), F(3)), (F(3), F(5))) == []


def test_adjoint() -> None:
    rng = random.Random(2)
    n, nbins = 16, 23
    rays = parallel_rays([k * math.pi / 6 for k in range(6)], nbins)
    x = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(n)]
    y = [rng.uniform(-1, 1) for _ in rays]
    ax = siddon_project(x, rays)
    aty = siddon_back_project(n, rays, 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:
    n, nbins = 16, 23
    rays = parallel_rays([0.0, 0.4, 1.3], nbins)
    rng = random.Random(3)
    x = [[rng.random() for _ in range(n)] for _ in range(n)]
    rows = siddon_matrix(n, rays)
    a = ik.sp_matvec(rows, ik.flatten(x))
    b = siddon_project(x, rays)
    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)]
    img = ik.disk_phantom(n, 0.5)
    p = siddon_project(img, parallel_rays(angles, nbins))
    q = ik.sp_matvec(ik.parallel_beam_matrix(n, angles, nbins), ik.flatten(img))
    width = 2.0 * math.sqrt(2.0) / nbins
    for k in range(len(angles)):
        for b in range(nbins):
            s = -math.sqrt(2.0) + (b + 0.5) * width
            exact = 2.0 * math.sqrt(0.25 - s * s) if abs(s) < 0.5 else 0.0
            # the pixelated disk differs from the true disk by at most one pixel (2 / n = 0.0625) along a chord
            if abs(s) < 0.35:
                assert abs(p[k * nbins + b] - exact) < 2.0 / n
                assert abs(p[k * nbins + b] - q[k * nbins + b]) < 0.1


def test_gaussian_second_order() -> None:
    errs = []
    angles = [0.3, 1.1]
    nbins = 23
    width = 2.0 * math.sqrt(2.0) / nbins
    for n in (16, 32):
        xs, ys = ik.pixel_centers(n)
        g = [[math.exp(-16.0 * (x * x + y * y)) for x in xs] for y in ys]
        p = siddon_project(g, parallel_rays(angles, nbins))
        e = 0.0
        for k in range(len(angles)):
            for b in range(nbins):
                s = -math.sqrt(2.0) + (b + 0.5) * width
                e = max(e, abs(p[k * nbins + b] - math.sqrt(math.pi / 16.0) * math.exp(-16.0 * s * s)))
        errs.append(e)
    assert errs[1] < 0.003
    assert errs[0] / errs[1] > 3.0

History

Robert Siddon published the method in Medical Physics in 1985 for three-dimensional CT arrays. Before, the exact path through a voxel array was found by testing the ray against each voxel or each plane in turn. Siddon's key step was to treat the voxels as the intersections of three families of equally spaced parallel planes, so that the crossings come from three arithmetic sequences. Jacobs, Sundermann, De Sutter, Christiaens and Lemahieu removed the merge and the index computation in 1998 with an incremental update, which is now often called the Siddon-Jacobs algorithm. The same traversal appeared in computer graphics in 1987 as the voxel traversal of Amanatides and Woo.

References

  1. Robert L. Siddon, Fast calculation of the exact radiological path for a three-dimensional CT array, Medical Physics 12(2), 1985, pp. 252 to 255 (the parametric form of the ray, the alpha sets of the x, y and z planes, their merge and the voxel index from the midpoint)
  2. F. Jacobs, E. Sundermann, B. De Sutter, M. Christiaens and I. Lemahieu, A fast algorithm to calculate the exact radiological path through a pixel or voxel space, Journal of Computing and Information Technology 6(1), 1998, pages 89 to 94, the incremental form that updates the next crossing and the voxel index without a merge (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 weights of the system matrix as intersection lengths of rays and pixels)
  4. Gabor T. Herman, Fundamentals of Computerized Tomography, Image Reconstruction from Projections, second edition, Springer, 2009, the discussion of the fast calculation of ray sums for a digitized picture (general locator; chapter not confirmed)

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