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
- Model
- Real RAM
- Properties
- deterministicnot in placenot iterativelineariterative
- Evidence
- Proof sketchCode in 1 languages
- 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 in the discrete model of transmission tomography, where holds the pixel values and approximates the line integral of the X-ray transform along ray . The method writes the ray as , lists the values of 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 time per ray on an 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 on the square , with pixel size . Pixel , in row from the top and column from the left, is the closed square . Its center is , , so goes up. A ray is the segment from to . 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 , the sum of length times value is the exact line integral of along the segment.
In parallel-beam geometry, ray is the line of the Radon transform, with and . The code takes and , a segment long enough to cross the whole square.
The algorithm
SIDDON(n, p0, p1) ▷ grid lines x = -1 + k h and y = -1 + k h, h = 2/n- 1
dx ← x1 - x0, dy ← y1 - y0, D ← sqrt(dx² + dy²) - 2
[α_min, α_max] ← [0, 1] ∩ {α : p(α) ∈ [-1, 1]²} ▷ one interval per axis with dx or dy ≠ 0 - 3
if α_min ≥ α_max then return the empty list - 4
Ax ← the α in (α_min, α_max) with x0 + α dx = -1 + k h for an integer k, increasing - 5
Ay ← the α in (α_min, α_max) with y0 + α dy = -1 + k h for an integer k, increasing - 6
S ← α_min, then MERGE(Ax, Ay), then α_max - 7
for each pair (α_prev, α_next) of neighbors in S with α_next > α_prev do - 8
(x_m, y_m) ← p((α_prev + α_next) / 2) - 9
j ← ⌊(x_m + 1)/h⌋, i ← ⌊(1 - y_m)/h⌋ - 10
output (i, j, (α_next - α_prev) D)
Line L2 clips the segment to the square. For an axis with , the ray is inside the slab for between and . If , the ray is inside the slab for all or for none. Lines L4 and L5 do not scan all grid lines. They compute the first and last index of the lines that the clipped segment crosses, with a floor and a ceiling of at its two ends, and then step up for or down for . 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 . Line L9 finds the pixel from the midpoint, which is strictly inside one pixel. In 3D, line L5 has a third list for the 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 , so , and the ray from to . Then , and . The whole segment is in the square, so and .
| step | values |
|---|---|
| lines at | |
| lines at | |
| merged | |
| differences | |
| lengths difference | |
| pixels from the midpoints |
The first midpoint is , the point . It is in column and row . The lengths add up to , 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 , sampled at the pixel centers of a grid, along angles and bins. At the bins with , the projection differs from the analytic value by at most . That is less than one pixel width , because the pixelated disk and the true disk differ by at most about one pixel along a chord. For the smooth image , sampled at the pixel centers, the largest error against the exact projection is for , for and for . These are measurements of this setup. The error falls by about 4 when doubles, as for a second order method.
Correctness
The pieces between neighbors in partition the clipped segment. Inside one piece no of a grid line occurs, so and 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 , because is affine with speed . 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 on with . Pixel is the closed square . The ray is with , , and . We work in exact arithmetic. A vertical grid line is a line and a horizontal grid line is a line , for an integer with .
We prove that SIDDON returns, for each pixel whose intersection with the segment has positive length, exactly one triple with 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 . If has positive length, line L2 sets . If is empty or one point, line L3 returns the empty list, which is correct.
Proof. if and only if and . For , the first condition is between and , a closed interval, and line L2 intersects with it. For the condition does not depend on : it holds for all or for none. The same holds for . An intersection of closed intervals is a closed interval, so when it is not empty. A segment of zero length meets no pixel with positive length.
The code tests when , not . A ray on the line touches only the border of , and the rule of line L9 would give it to column , which does not exist. So the code drops it. This changes only rays on the border of .
Lemma 2 (the crossing lists, lines L4 and L5). Suppose . Line L4 returns, in increasing order, exactly the values at which is on a vertical grid line. The same holds for line L5 and the horizontal lines.
Proof. Put . Then if and only if . The function is affine and strictly monotone, so it maps onto the open interval between and . Call its ends . The integers in are , which is the range that the code builds. Each such gives exactly one in the open interval. Because on , we have , so each is a real grid line. If , then increases with and the code lists upward. If , then decreases with and the code lists downward. So the list is increasing in both cases.
If , line L4 returns the empty list. That is correct too: then is constant, and either it is not on a grid line, or it is on one for every , which is the case of a ray on a grid line that we treat at the end.
Lemma 3 (merge, line L6). is the increasing list of , all values of Lemma 2 for both axes, and . Equal values from the two lists stay as two equal neighbors.
Proof. and 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 , so putting in front and at the end keeps the list increasing.
Let be the distinct values of . These are the pairs that the loop of line L7 keeps, because it skips the pairs of equal neighbors. Put for .
Lemma 4 (one piece, one pixel). Assume the ray is not on a grid line. For each , the open piece lies in the interior of one pixel , and lines L8 and L9 compute this .
Proof. Take . By Lemmas 2 and 3, no value of puts or on a grid line. Also is in , by Lemma 1. Consider . If , the continuous function on the interval never meets a grid line, so it stays in one open interval . If , then is constant and, by the assumption, not on a grid line, so it is in one such interval as well. The same holds for and an interval . So is in the interior of . The midpoint of line L8 is in . From we get , so . From we get , so . The clamp to does not change these values.
Lemma 5 (length, line L10). The length of is .
Proof. .
Theorem. Assume the ray is not on a grid line. Then SIDDON returns each pixel whose intersection with the segment has positive length exactly once, with the length of that intersection, and no other pixel.
Proof. The segment inside is by Lemma 1, and is the union of the pieces and the finite set . A finite set of points has length 0. So the length of is the sum of the lengths of the pieces that lie in . 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 with both pieces in . Then is in and is a value of or , so is on a grid line, say , and . On the value of is on one side of this line, and on it is on the other side, because is strictly monotone. Both sides cannot meet the interior of , 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.
A ray on a grid line. Suppose and with . Then the segment touches columns and (or only column when ), 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, still stays in one open row interval, and the midpoint gives , so line L9 returns column . So the code returns the pixels of column with their full lengths, and none of column . 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 . The sum of all lengths is still the length of , 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 and . So with rational input, every is rational and computed exactly, and all comparisons in Lemma 2, Lemma 3 and line L7 are exact. The only square root is . If is rational, as for the directions or , 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 be the matrix with for each output triple of ray . The projector computes over the triples of ray , and the back projector adds to pixel for the same triples, which is . So for all and . By the theorem, for a piecewise constant image , is the exact integral of along the segment of ray .
Complexity
In the real-RAM model:
- Lines L1 to L3 take .
- The clipped segment crosses at most vertical and horizontal grid lines. Lines L4 and L5 compute their values in time, with no search.
- The merge of line L6 takes , and the loop of lines L7 to L10 runs at most times with work each.
So one ray takes time and extra space, and a sinogram of angles and bins takes . The output of one ray has at most pixels, so the bound is tight up to a constant. In 3D, an grid gives 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 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 (a direction such as ), the code returns exact rationals.
- Matched pair. The back projector uses the same weights, so it is the exact adjoint of the forward projector. Iterative methods that assume , 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 and and the current index . At each step take the smaller of the two, add its distance to the output, and step or by . 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 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 and to .
- Equal crossings. A ray through a grid corner gives the same in both lists. Without the test 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 and 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 per ray.
- Wrong row direction. Row counts from the top while goes up. Line L9 uses , not . 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.
# 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
- 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)
- 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)
- 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)
- 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.
| 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 3SDE4K Edit this page History Report an error Markdown