Algorithmcore
Maximum likelihood expectation maximization reconstruction
Also called MLEM, Shepp-Vardi algorithm.
Maximize the Poisson likelihood of emission data by multiplying the image by the back-projected ratio of measured to predicted counts, keeping it nonnegative.
- Time
- O(K a d n) totalO(a d n) per_iteration
- Space
- O(a d + n^2) extra
- Where
- K = the number of iterations; a = the number of projection angles; d = the number of detector bins; n = the side of the n x n image
- Model
- Real RAM
- Properties
- deterministicnot in placeiterativekeeps nonnegativitynot linear in datamonotone likelihooditerative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Lawrence A. Shepp, Yehuda Vardi, 1982
MLEM computes the maximum likelihood image of the emission tomography model. The counts are with , where is a nonnegative system matrix, a known background and the activity image. Each iteration projects the current image, divides the measured counts by the predicted counts, back-projects the ratios, and multiplies the image by the result, pixel by pixel: with . It is the EM algorithm for this model. The update keeps the image nonnegative, never decreases the likelihood, and with converges to a maximizer. With noisy data the maximizer is noisy, so in practice the iteration is stopped early. The same update for a convolution is Richardson-Lucy deconvolution.
In plain words
A scanner counts photons from a tracer in the body. Each detector bin sees the photons from the pixels along its line. MLEM starts with a flat image that has no negative values. It computes how many counts the image would give in each bin. Then it compares these numbers with the measured counts, bin by bin, as a ratio.
A ratio above 1 says that the image is too dark along that line. A ratio below 1 says that it is too bright. Each pixel collects the ratios of all bins that see it and takes their weighted average. Then it multiplies its value by this average. A pixel never becomes negative, because it only gets multiplied by a positive number. Each step makes the measured counts more probable for the image. Too many steps make the image fit the random noise of the counts.
The problem
Given the counts , a matrix with and positive column sums , and a background , maximize the Poisson log-likelihood
over . The constant is left out. Maximizing is the same as minimizing the Kullback-Leibler divergence . is concave, and is a maximizer if and only if the KKT conditions hold: for each , with equality where .
The algorithm
MLEM(A, y, b, x0, K) ▷ x0 > 0 in every pixel; b ≥ 0 is known- 1
s_j ← Σ_i a_ij for each pixel j ▷ the sensitivity image, A^T 1 - 2
x ← x0 - 3
for k ← 1 to K do - 4
ȳ ← A x + b ▷ the forward projection - 5
r_i ← y_i / ȳ_i for each bin i ▷ r_i ← 0 if y_i = 0 - 6
g ← A^T r ▷ the back projection of the ratios - 7
x_j ← x_j g_j / s_j for each pixel j - 8
return x
Line L1 runs once. Each iteration does one forward projection (line L4) and one back projection (line L6). Line L6 must use the transpose of the matrix of line L4, and must be the column sums of the same matrix, or the theory below does not hold. A common start is the constant image whose projections have the measured total count; the code uses it by default. In the EM view, the complete data are the unobserved counts from pixel in bin . The E-step estimates them by , and the M-step sets to . This is line L7.
Example
Take a image in row-major order, no background, and five rays with weights 0 or 1: the two rows, the two columns and the diagonal through and . The counts are the exact projections of : . The sensitivities are . Start from , so . Line L5 gives . Line L6 gives , , and . Line L7 multiplies by :
| iteration | |||||
|---|---|---|---|---|---|
| 0 | 1 | 1 | 1 | 1 | 7.3287 |
| 1 | 2 | 9/4 | 11/4 | 3 | 15.8143 |
| 2 | 1646/969 = 1.6987 | 495/238 = 2.0798 | 2475/874 = 2.8318 | 541/161 = 3.3602 | 16.0627 |
| 3 | 1.5091 | 1.9726 | 2.8508 | 3.6086 | 16.1712 |
The likelihood rises at each step toward its maximum . After iteration 1 the weighted sum equals the total count 25, and it stays there. The error is after 10 iterations, after 50 and after 100. The iterates are rational, but their denominators grow fast: iteration 3 already has 16 digits in each denominator.
A larger case. The image is on , with pixel centered at and . The object is a disk of radius 0.6 with value 1, scanned at 12 angles in with 23 bins and the pixel-driven matrix of the shared helper. With exact mean data (5 times the projections), the relative error is after 1 iteration, after 10, after 50, after 100 and after 300. With Poisson counts of mean 50 times the projections (seed 7, 5676 counts in total), the error of is smallest, , at . Then it rises to at , at and at , while the likelihood still rises. This is semi-convergence. These numbers are measurements of this setup, not properties of the method.
Correctness
Fix a positive with wherever . The weights and are nonnegative and sum to 1 over . Jensen's inequality for the concave logarithm then gives, for every ,
with equality at . The surrogate splits into one concave function per pixel, and the maximizer of is , the update of line L7. So : the likelihood never decreases. It increases strictly unless . This is a minorize-maximize argument, and it is the EM monotonicity for this model.
Three more facts follow from the update.
- Positivity. A positive pixel stays positive if some bin that sees it has counts. A zero pixel stays zero.
- The total count. With , after every iteration.
- Fixed points. A positive is a fixed point if and only if for all . A maximizer is a fixed point. A fixed point with zero pixels need not be a maximizer, which is why the start must be positive.
With and a positive start, the iterates converge to a maximizer of . Vardi, Shepp and Kaufman (1985) proved this for PET, and Csiszar and Tusnady (1984) proved it for alternating minimization of the KL divergence, of which MLEM is a case. The proofs of monotonicity, positivity, the count and the fixed points are in proofs/correctness.md; the convergence is cited there.
Proof: Monotone likelihood and fixed points of MLEMfull
We use the notation of the page. is an matrix with , every column sum is positive (a pixel with is removed; the code sets it to 0), is the known background and holds the counts. For put and
the Poisson log-likelihood without the constant . A term with is . We call admissible if for each with ; then is finite. Lines L4 to L7 map an admissible to
where the sum runs over the rays with (line L5 sets the other ratios to 0). We work in exact arithmetic.
Lemma 1 (admissible and positive). If is admissible, then , and if and only if or no ray with has . If and every ray with has a positive entry or , then is admissible.
Proof. Every factor in (1) is nonnegative, and the sum is positive exactly when some ray with has . For the second claim, let . If then . Otherwise some ; for this the ray itself has and , so by the first claim, and .
So from a positive start the iteration is well defined at every step, and a pixel can only reach 0 if no ray that sees it has counts.
Lemma 2 (the surrogate). Let be admissible, let , and for every define
with the terms of rays with left out of the first sum, and . Then and .
Proof. The second claim is clear, because . For the first, fix a ray with , so . The weights for and are nonnegative and sum to 1. Write
where the terms with are dropped. The logarithm is concave and increasing, so Jensen's inequality gives
Multiply by , sum over these rays and subtract on both sides.
Theorem 1 (monotone likelihood). Let be admissible and let be given by (1). Then , with equality only if .
Proof. Put , so that and for . Since , the surrogate is
with independent of . It is a sum of functions of one variable each. For the function is strictly concave on and has its unique maximum at . For the function has its unique maximum on at . So of (1) is the unique maximizer of over , and by Lemma 2
If , the middle inequality is strict, because the maximizer is unique.
Theorem 2 (the total count). If , then for every admissible .
Proof. By (1), , the sum over the rays with , because when .
So with the expected total count equals the measured total count after the first iteration.
Theorem 3 (fixed points). An admissible is a fixed point of (1) if and only if for every with . A maximizer of over is a fixed point. A fixed point is a maximizer if and only if also for every with .
Proof. The gradient is . For , (1) gives if and only if , that is . For , (1) gives always. The function is concave on the admissible set, because each is the logarithm of an affine function and is affine. For a concave differentiable function on the orthant, is a maximizer if and only if the KKT conditions hold: for all , with equality where . Both claims follow.
A fixed point with a zero pixel need not be a maximizer: a start with keeps for ever. This is why the start must be positive.
Convergence (cited, not proved here). For and a positive start, the iterates converge to a maximizer of over . Vardi, Shepp and Kaufman (1985) gave the argument for emission tomography, and Csiszar and Tusnady (1984) proved it for the alternating minimization of the Kullback-Leibler divergence, of which MLEM with is a special case. Theorem 1 alone does not give convergence of the iterates: it gives a nondecreasing sequence that is bounded above, since for every .
Complexity
In the real-RAM model, with angles of bins each ( bins) and an image ( pixels):
- Line L1 takes one pass over the nonzero entries of . A ray-driven projector has entries per bin, so .
- Lines L4 and L6 take each. Lines L5 and L7 take and .
So one iteration costs time and extra space, and iterations cost . The number of iterations is the regularization parameter. No bound on the right follows from the model: without a known noise level, every stopping rule for MLEM is a heuristic. The error of the slow components falls slowly, and in the small example above the error shrinks by a factor of about 3 every 10 iterations.
Properties
- Nonnegative. The update multiplies by nonnegative numbers, so no projection onto is necessary.
- Monotone likelihood. never decreases. This is a theorem (see Correctness). The error against the true image is not monotone with noise.
- A scaled gradient step. Line L7 equals . So MLEM is gradient ascent with the step for pixel . The step is small where the pixel is small, which keeps the pixel positive.
- Count preserving. With the predicted total count equals the measured one after each iteration.
- Not linear in the data. The iterate depends on in a nonlinear way, unlike SIRT without the positivity step. So its noise cannot be written in closed form.
- Slow at fine detail. In practice the coarse structure of the image appears in a few iterations and fine detail needs many. This is an observation, and it is why OSEM is used.
Variants and improvements
- OSEM. Apply the update with one subset of the bins at a time. One pass over the subsets costs about as much as one MLEM iteration and does about as much work as several. See OSEM.
- Penalized likelihood. Add a penalty to . The one-step-late algorithm of Green (1990) puts the gradient of at the old image into the denominator of line L7. Separable paraboloidal surrogates minimize a separable quadratic majorizer and keep the monotone property with a penalty.
- Transmission data. Lange and Carson (1984) gave an EM algorithm for the transmission model too. Its M-step has no closed form.
- Richardson-Lucy. For a convolution matrix with , the update is Richardson-Lucy deconvolution.
- List mode and time of flight. The same update works on a list of single events instead of binned counts. Time of flight adds a position along each line to the model, which only changes .
- Post-filtering. Run many iterations and smooth the result. It is a common practice, but its choice of the filter is a heuristic.
When to use it
Use MLEM for emission data with low counts, where the Poisson model matters and filtered back-projection gives streaks. It needs only a forward and a back projector, it handles any geometry and any known background, and it keeps the image nonnegative. Use it as the reference method when you test a faster variant: OSEM, for example, should give a similar image in fewer passes. For a reproducible result, fix the number of iterations or add a penalty, because the image depends on where you stop. For high counts, a weighted least squares method is also good.
Pitfalls
- A zero start. A pixel that starts at 0 stays at 0. Start with a positive image.
- Division by zero. A bin with and makes line L5 fail. This happens if the bin sees no pixel and . Remove such bins, or give them a small background.
- Precorrected data. If the data have random coincidences subtracted, some counts can be negative and the model is wrong. Put the estimate in and keep the raw counts.
- A mismatched back projector. If line L6 does not use , or is not for the same , the likelihood can decrease and the limit is not the maximum likelihood image.
- Too many iterations. With noise, the image becomes noisy as grows, while the likelihood still increases. The rise of is not a sign of a better image.
- Expecting a unique answer. If does not have full column rank, the maximizer is not unique, and the limit depends on the start.
Implementations
The Python code takes the system matrix as sparse rows of (column, weight) pairs, as built by the shared helper imgkit.parallel_beam_matrix or by any projector page, and works with float or fractions.Fraction data. The tests check the worked example exactly, the total count, the convergence on a consistent system, the monotone likelihood and the positivity on random problems with background, the KKT conditions at the limit, the adjoint test of the projector pair, and the disk phantom with exact and with noisy counts.
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
mlem_reconstruction.py 85 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mlem-reconstruction/. The authors are listed in prov/83T1AZ.jsonl.
"""MLEM, the maximum likelihood expectation maximization reconstruction of
Shepp and Vardi for emission tomography.
The model is y_i ~ Poisson((A x)_i + b_i), independent, with a nonnegative
system matrix A, a known background b >= 0 and an image x >= 0. A is given as
sparse rows: row i is a list of (column, weight) pairs, as returned by
imgkit.parallel_beam_matrix. One iteration is
x_j <- (x_j / s_j) sum_i a_ij y_i / (A x + b)_i, s_j = sum_i a_ij.
A pixel with s_j = 0 is set to 0. The update works with float or with
fractions.Fraction data; the log-likelihood is a float.
"""
import math
def forward(rows, x):
"""A x for sparse rows."""
return [sum(w * x[j] for j, w in row) for row in rows]
def back(rows, v, ncols):
"""A^T v for sparse rows with ncols columns."""
out = [0 * v[0] if v else 0] * ncols
for row, vi in zip(rows, v):
if vi != 0:
for j, w in row:
out[j] += w * vi
return out
def sensitivity(rows, ncols):
"""s_j = sum_i a_ij, the back projection of a vector of ones."""
s = [0] * ncols
for row in rows:
for j, w in row:
s[j] += w
return s
def log_likelihood(rows, y, x, b=None):
"""L(x) = sum_i [y_i log ybar_i - ybar_i] with ybar = A x + b.
The constant -sum_i log(y_i!) is left out. A ray with ybar_i = 0 and
y_i > 0 gives -inf.
"""
ybar = forward(rows, x)
total = 0.0
for i, (yi, li) in enumerate(zip(y, ybar)):
if b is not None:
li += b[i]
if yi != 0:
if li <= 0:
return -math.inf
total += float(yi) * math.log(float(li))
total -= float(li)
return total
def mlem(rows, ncols, y, b=None, iters=50, x0=None, callback=None):
"""Run MLEM and return the image after iters iterations.
rows: the sparse rows of A; y: the counts; b: the background (zero by
default); x0: a positive start (by default the constant image whose
projections have the total count of y); callback(k, x) is called after
each iteration.
"""
s = sensitivity(rows, ncols) # @line L1
if x0 is None:
c = sum(y) / sum(s)
x0 = [c if sj != 0 else 0 * c for sj in s]
x = list(x0) # @line L2
for k in range(iters): # @line L3
ybar = forward(rows, x) # @line L4
if b is not None:
ybar = [li + bi for li, bi in zip(ybar, b)]
ratio = [yi / li if yi != 0 else 0 * li for yi, li in zip(y, ybar)] # @line L5
g = back(rows, ratio, ncols) # @line L6
x = [xj * gj / sj if sj != 0 else 0 * xj for xj, gj, sj in zip(x, g, s)] # @line L7
if callback is not None:
callback(k + 1, x)
return x # @line L8
test_mlem_reconstruction.py 114 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mlem-reconstruction/. The authors are listed in prov/83T1AZ.jsonl.
import math
import random
from fractions import Fraction as F
import imgkit as ik
from mlem_reconstruction import back, forward, log_likelihood, mlem, sensitivity
# The 2 x 2 example of the page: two rows, two columns and one diagonal.
A = [[1, 1, 0, 0], [0, 0, 1, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 0, 1]]
ROWS = [[(j, F(w)) for j, w in enumerate(r) if w] for r in A]
Y = [F(v) for v in (3, 7, 4, 6, 5)]
def _random_problem(rng, m, n, density=0.6):
rows = []
for _ in range(m):
row = [(j, rng.uniform(0.1, 1.0)) for j in range(n) if rng.random() < density]
if not row:
row = [(rng.randrange(n), 0.5)]
rows.append(row)
x = [rng.uniform(0.0, 3.0) for _ in range(n)]
b = [rng.uniform(0.0, 0.5) for _ in range(m)]
lam = [li + bi for li, bi in zip(forward(rows, x), b)]
y = [ik.poisson_sample(rng, 4.0 * v) for v in lam]
return [[(j, 4.0 * w) for j, w in row] for row in rows], y, b
def test_worked_example_exact() -> None:
seen = []
mlem(ROWS, 4, Y, iters=2, x0=[F(1)] * 4, callback=lambda k, x: seen.append(x))
assert seen[0] == [F(2), F(9, 4), F(11, 4), F(3)]
assert seen[1] == [F(1646, 969), F(495, 238), F(2475, 874), F(541, 161)]
def test_total_count_is_kept_without_background() -> None:
s = sensitivity(ROWS, 4)
seen = []
mlem(ROWS, 4, Y, iters=3, x0=[F(1)] * 4, callback=lambda k, x: seen.append(x))
for x in seen:
assert sum(sj * xj for sj, xj in zip(s, x)) == sum(Y)
def test_consistent_data_give_the_true_image() -> None:
x = mlem(ROWS, 4, [float(v) for v in Y], iters=500, x0=[1.0] * 4)
assert max(abs(a - b) for a, b in zip(x, (1, 2, 3, 4))) < 1e-12
def test_likelihood_does_not_decrease_and_x_stays_positive() -> None:
rng = random.Random(11)
for _ in range(5):
rows, y, b = _random_problem(rng, 12, 6)
lls = []
def cb(k, x):
assert all(v > 0 for v in x)
lls.append(log_likelihood(rows, y, x, b))
x0 = [1.0] * 6
lls.append(log_likelihood(rows, y, x0, b))
mlem(rows, 6, y, b=b, iters=60, x0=x0, callback=cb)
for a, c in zip(lls, lls[1:]):
assert c >= a - 1e-9 * abs(a)
def test_limit_satisfies_the_kkt_conditions() -> None:
rng = random.Random(4)
rows, y, b = _random_problem(rng, 10, 3, density=0.9)
x = mlem(rows, 3, y, b=b, iters=3000, x0=[1.0] * 3)
s = sensitivity(rows, 3)
ybar = [li + bi for li, bi in zip(forward(rows, x), b)]
grad = [gj - sj for gj, sj in zip(back(rows, [yi / li for yi, li in zip(y, ybar)], 3), s)]
for xj, gj, sj in zip(x, grad, s):
assert gj <= 1e-6 * sj
assert abs(xj * gj) <= 1e-6 * sj * (1.0 + xj)
def test_projector_adjoint() -> None:
rng = random.Random(2)
n = 8
rows = ik.parallel_beam_matrix(n, [math.pi * a / 6 for a in range(6)], 11)
x = [rng.gauss(0.0, 1.0) for _ in range(n * n)]
v = [rng.gauss(0.0, 1.0) for _ in range(len(rows))]
ax, atv = forward(rows, x), back(rows, v, n * n)
lhs = sum(p * q for p, q in zip(ax, v))
rhs = sum(p * q for p, q in zip(x, atv))
norm = math.sqrt(sum(p * p for p in ax) * sum(q * q for q in v))
assert abs(lhs - rhs) <= 1e-10 * norm
def test_disk_phantom_exact_and_noisy() -> None:
n = 16
rows = ik.parallel_beam_matrix(n, [math.pi * a / 12 for a in range(12)], 23)
truth = ik.flatten(ik.disk_phantom(n, 0.6))
tn = math.sqrt(sum(v * v for v in truth))
lam = [5.0 * v for v in forward(rows, truth)]
def errors(y, scale, iters):
out = []
cb = lambda k, x: out.append(math.sqrt(sum((a / scale - t) ** 2 for a, t in zip(x, truth))) / tn)
mlem(rows, n * n, y, iters=iters, callback=cb)
return out
e = errors(lam, 5.0, 300)
assert e[9] < 0.2 and e[99] < 0.12 and e[299] < 0.07
rng = random.Random(7)
y = [ik.poisson_sample(rng, 10.0 * v) for v in lam]
assert sum(y) == 5676
e = errors(y, 50.0, 300)
best = min(range(300), key=lambda k: e[k])
assert best + 1 == 10 and abs(e[best] - 0.2348) < 1e-3
assert e[299] > 2.0 * e[best]
History
Richardson (1972) and Lucy (1974) used the same multiplicative update to deblur images in optics and astronomy. Dempster, Laird and Rubin named and analyzed the general EM algorithm in 1977. Shepp and Vardi (1982) introduced the Poisson model of positron emission tomography and derived MLEM as its EM algorithm. Lange and Carson (1984) gave EM algorithms for emission and for transmission tomography. Vardi, Shepp and Kaufman (1985) proved the convergence for emission data, and Csiszar and Tusnady (1984) proved the convergence of alternating minimization of the KL divergence in general. The slow convergence led to OSEM in 1994, which made the method practical in the clinic.
References
- L. A. Shepp and Y. Vardi, Maximum likelihood reconstruction for emission tomography, IEEE Transactions on Medical Imaging 1(2), 1982, pp. 113 to 122 (the EM algorithm for the Poisson model of PET)
- K. Lange and R. Carson, EM reconstruction algorithms for emission and transmission tomography, Journal of Computer Assisted Tomography 8(2), 1984, the EM update for emission data and its monotone likelihood (general locator)
- Y. Vardi, L. A. Shepp and L. Kaufman, A statistical model for positron emission tomography, Journal of the American Statistical Association 80(389), 1985, pp. 8 to 20 (the convergence of the EM iterates to a maximum likelihood estimate)
- I. Csiszar and G. Tusnady, Information geometry and alternating minimization procedures, Statistics and Decisions, Supplement Issue 1, 1984, pp. 205 to 237 (the convergence of alternating minimization of the Kullback-Leibler divergence)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 83T1AZ Edit this page History Report an error Markdown