Algorithm Search⌘K

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
Properties
deterministicnot in placeiterativekeeps nonnegativitynot linear in datamonotone likelihooditerative
Origin
Lawrence A. Shepp, Yehuda Vardi, 1982

MLEM computes the maximum likelihood image of the emission tomography model. The counts are yi∼Poisson⁡(yˉi)y_i \sim \operatorname{Poisson}(\bar y_i) with yˉ=Ax+b\bar y = A x + b, where AA is a nonnegative m×Nm \times N system matrix, b≥0b \ge 0 a known background and x≥0x \ge 0 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: xj←(xj/sj)∑iaijyi/yˉix_j \leftarrow (x_j / s_j) \sum_i a_{ij} y_i / \bar y_i with sj=∑iaijs_j = \sum_i a_{ij}. It is the EM algorithm for this model. The update keeps the image nonnegative, never decreases the likelihood, and with b=0b = 0 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 y∈{0,1,2,…}my \in \{0, 1, 2, \ldots\}^m, a matrix AA with aij≥0a_{ij} \ge 0 and positive column sums sj=∑iaijs_j = \sum_i a_{ij}, and a background b≥0b \ge 0, maximize the Poisson log-likelihood

L(x)=∑i[yilog⁡yˉi−yˉi],yˉ=Ax+b,L(x) = \sum_i \big[y_i \log \bar y_i - \bar y_i\big], \qquad \bar y = A x + b,

over x≥0x \ge 0. The constant −∑ilog⁡yi!-\sum_i \log y_i! is left out. Maximizing LL is the same as minimizing the Kullback-Leibler divergence KL⁡(y,Ax+b)\operatorname{KL}(y, A x + b). LL is concave, and x^\hat x is a maximizer if and only if the KKT conditions hold: ∑iaijyi/yˉi≤sj\sum_i a_{ij} y_i / \bar y_i \le s_j for each jj, with equality where x^j>0\hat x_j > 0.

The algorithm

  1. MLEM(A, y, b, x0, K) ▷ x0 > 0 in every pixel; b ≥ 0 is known
  2. 1s_j ← Σ_i a_ij for each pixel j ▷ the sensitivity image, A^T 1
  3. 2x ← x0
  4. 3for k ← 1 to K do
  5. 4ȳ ← A x + b ▷ the forward projection
  6. 5r_i ← y_i / ȳ_i for each bin i ▷ r_i ← 0 if y_i = 0
  7. 6g ← A^T r ▷ the back projection of the ratios
  8. 7x_j ← x_j g_j / s_j for each pixel j
  9. 8return 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 ss 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 zij∼Poisson⁡(aijxj)z_{ij} \sim \operatorname{Poisson}(a_{ij} x_j) from pixel jj in bin ii. The E-step estimates them by E[zij∣y]=yiaijxj/yˉi\mathbb{E}[z_{ij} \mid y] = y_i a_{ij} x_j / \bar y_i, and the M-step sets xjx_j to ∑iE[zij∣y]/sj\sum_i \mathbb{E}[z_{ij} \mid y] / s_j. This is line L7.

Example

Take a 2×22 \times 2 image x=(x0,x1,x2,x3)x = (x_0, x_1, x_2, x_3) in row-major order, no background, and five rays with weights 0 or 1: the two rows, the two columns and the diagonal through x0x_0 and x3x_3. The counts are the exact projections of (1,2,3,4)(1, 2, 3, 4): y=(3,7,4,6,5)y = (3, 7, 4, 6, 5). The sensitivities are s=(3,2,2,3)s = (3, 2, 2, 3). Start from x=(1,1,1,1)x = (1, 1, 1, 1), so yˉ=(2,2,2,2,2)\bar y = (2, 2, 2, 2, 2). Line L5 gives r=(3/2,7/2,2,3,5/2)r = (3/2, 7/2, 2, 3, 5/2). Line L6 gives g0=3/2+2+5/2=6g_0 = 3/2 + 2 + 5/2 = 6, g1=3/2+3=9/2g_1 = 3/2 + 3 = 9/2, g2=7/2+2=11/2g_2 = 7/2 + 2 = 11/2 and g3=7/2+3+5/2=9g_3 = 7/2 + 3 + 5/2 = 9. Line L7 multiplies by xj/sjx_j / s_j:

iteration x0x_0 x1x_1 x2x_2 x3x_3 L(x)L(x)
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 L(1,2,3,4)=16.2601L(1, 2, 3, 4) = 16.2601. After iteration 1 the weighted sum ∑jsjxj\sum_j s_j x_j equals the total count 25, and it stays there. The error max⁡j∣xj−xj†∣\max_j |x_j - x^\dagger_j| is 0.130.13 after 10 iterations, 1.7⋅10−31.7 \cdot 10^{-3} after 50 and 8.2⋅10−68.2 \cdot 10^{-6} 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 16×1616 \times 16 on [−1,1]2[-1, 1]^2, with pixel (i,j)(i, j) centered at xj=−1+(2j+1)/nx_j = -1 + (2j+1)/n and yi=1−(2i+1)/ny_i = 1 - (2i+1)/n. The object is a disk of radius 0.6 with value 1, scanned at 12 angles in [0,π)[0, \pi) with 23 bins and the pixel-driven matrix of the shared helper. With exact mean data (5 times the projections), the relative error ∥xk−x∥/∥x∥\|x_k - x\| / \|x\| is 0.630.63 after 1 iteration, 0.190.19 after 10, 0.130.13 after 50, 0.110.11 after 100 and 0.0660.066 after 300. With Poisson counts of mean 50 times the projections (seed 7, 5676 counts in total), the error of xk/50x_k / 50 is smallest, 0.2350.235, at k=10k = 10. Then it rises to 0.410.41 at k=50k = 50, 0.470.47 at k=100k = 100 and 0.560.56 at k=300k = 300, 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 xx with yˉi>0\bar y_i > 0 wherever yi>0y_i > 0. The weights aijxj/yˉia_{ij} x_j / \bar y_i and bi/yˉib_i / \bar y_i are nonnegative and sum to 1 over jj. Jensen's inequality for the concave logarithm then gives, for every x′≥0x' \ge 0,

L(x′)≥Q(x′;x)=const+∑j[xjgjlog⁡xj′−sjxj′],gj=∑iaijyiyˉi,L(x') \ge Q(x'; x) = \text{const} + \sum_j \Big[x_j g_j \log x'_j - s_j x'_j\Big], \qquad g_j = \sum_i a_{ij} \frac{y_i}{\bar y_i},

with equality at x′=xx' = x. The surrogate QQ splits into one concave function per pixel, and the maximizer of xjgjlog⁡t−sjtx_j g_j \log t - s_j t is t=xjgj/sjt = x_j g_j / s_j, the update of line L7. So L(xk+1)≥Q(xk+1;xk)≥Q(xk;xk)=L(xk)L(x^{k+1}) \ge Q(x^{k+1}; x^k) \ge Q(x^k; x^k) = L(x^k): the likelihood never decreases. It increases strictly unless xk+1=xkx^{k+1} = x^k. 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 b=0b = 0, ∑jsjxjk+1=∑iyi\sum_j s_j x^{k+1}_j = \sum_i y_i after every iteration.
  • Fixed points. A positive xx is a fixed point if and only if ∂L/∂xj=gj−sj=0\partial L / \partial x_j = g_j - s_j = 0 for all jj. 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 b=0b = 0 and a positive start, the iterates converge to a maximizer of LL. 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. AA is an m×Nm \times N matrix with aij≥0a_{ij} \ge 0, every column sum sj=∑iaijs_j = \sum_i a_{ij} is positive (a pixel with sj=0s_j = 0 is removed; the code sets it to 0), b≥0b \ge 0 is the known background and y≥0y \ge 0 holds the counts. For x≥0x \ge 0 put yˉ=Ax+b\bar y = A x + b and

L(x)=∑i[yilog⁡yˉi−yˉi],L(x) = \sum_i \big[y_i \log \bar y_i - \bar y_i\big],

the Poisson log-likelihood without the constant −∑ilog⁡yi!-\sum_i \log y_i!. A term with yi=0y_i = 0 is −yˉi-\bar y_i. We call x≥0x \ge 0 admissible if yˉi>0\bar y_i > 0 for each ii with yi>0y_i > 0; then L(x)L(x) is finite. Lines L4 to L7 map an admissible xx to

xj′=xjsj∑iaijyiyˉi,(1)x'_j = \frac{x_j}{s_j} \sum_i a_{ij} \frac{y_i}{\bar y_i}, \tag{1}

where the sum runs over the rays with yi>0y_i > 0 (line L5 sets the other ratios to 0). We work in exact arithmetic.

Lemma 1 (admissible and positive). If xx is admissible, then x′≥0x' \ge 0, and xj′=0x'_j = 0 if and only if xj=0x_j = 0 or no ray with aij>0a_{ij} > 0 has yi>0y_i > 0. If x>0x > 0 and every ray with yi>0y_i > 0 has a positive entry or bi>0b_i > 0, then x′x' is admissible.

Proof. Every factor in (1) is nonnegative, and the sum is positive exactly when some ray with aij>0a_{ij} > 0 has yi>0y_i > 0. For the second claim, let yi>0y_i > 0. If bi>0b_i > 0 then yˉi′≥bi>0\bar y'_i \ge b_i > 0. Otherwise some aij>0a_{ij} > 0; for this jj the ray ii itself has aij>0a_{ij} > 0 and yi>0y_i > 0, so xj′>0x'_j > 0 by the first claim, and yˉi′≥aijxj′>0\bar y'_i \ge a_{ij} x'_j > 0. □\square

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 xx be admissible, let J={j:xj>0}J = \{j : x_j > 0\}, and for every x′≥0x' \ge 0 define

Q(x′;x)=∑iyi[log⁡yˉi+∑j∈Jaijxjyˉilog⁡xj′xj]−∑iyˉi′,Q(x'; x) = \sum_i y_i \Big[\log \bar y_i + \sum_{j \in J} \frac{a_{ij} x_j}{\bar y_i} \log \frac{x'_j}{x_j}\Big] - \sum_i \bar y'_i,

with the terms of rays with yi=0y_i = 0 left out of the first sum, and log⁡0=−∞\log 0 = -\infty. Then L(x′)≥Q(x′;x)L(x') \ge Q(x'; x) and L(x)=Q(x;x)L(x) = Q(x; x).

Proof. The second claim is clear, because log⁡(xj/xj)=0\log(x_j/x_j) = 0. For the first, fix a ray with yi>0y_i > 0, so yˉi>0\bar y_i > 0. The weights wij=aijxj/yˉiw_{ij} = a_{ij} x_j / \bar y_i for j∈Jj \in J and wi0=bi/yˉiw_{i0} = b_i / \bar y_i are nonnegative and sum to 1. Write

yˉi′≥∑j∈Jaijxj′+bi=∑j∈Jwij(yˉixj′xj)+wi0 yˉi,\bar y'_i \ge \sum_{j \in J} a_{ij} x'_j + b_i = \sum_{j \in J} w_{ij} \Big(\bar y_i \frac{x'_j}{x_j}\Big) + w_{i0}\, \bar y_i,

where the terms with wij=0w_{ij} = 0 are dropped. The logarithm is concave and increasing, so Jensen's inequality gives

log⁡yˉi′≥∑j∈Jwijlog⁡(yˉixj′xj)+wi0log⁡yˉi=log⁡yˉi+∑j∈Jwijlog⁡xj′xj.\log \bar y'_i \ge \sum_{j \in J} w_{ij} \log\Big(\bar y_i \frac{x'_j}{x_j}\Big) + w_{i0} \log \bar y_i = \log \bar y_i + \sum_{j \in J} w_{ij} \log \frac{x'_j}{x_j}.

Multiply by yi>0y_i > 0, sum over these rays and subtract ∑iyˉi′\sum_i \bar y'_i on both sides. □\square

Theorem 1 (monotone likelihood). Let xx be admissible and let x′x' be given by (1). Then L(x′)≥L(x)L(x') \ge L(x), with equality only if x′=xx' = x.

Proof. Put ej=xj∑iaijyi/yˉie_j = x_j \sum_i a_{ij} y_i / \bar y_i, so that xj′=ej/sjx'_j = e_j / s_j and ej=0e_j = 0 for j∉Jj \notin J. Since ∑iyˉi′=∑jsjxj′+∑ibi\sum_i \bar y'_i = \sum_j s_j x'_j + \sum_i b_i, the surrogate is

Q(x′;x)=C(x)+∑j∈Jejlog⁡xj′−∑jsjxj′,Q(x'; x) = C(x) + \sum_{j \in J} e_j \log x'_j - \sum_j s_j x'_j,

with C(x)C(x) independent of x′x'. It is a sum of functions of one variable each. For ej>0e_j > 0 the function t↦ejlog⁡t−sjtt \mapsto e_j \log t - s_j t is strictly concave on t>0t > 0 and has its unique maximum at t=ej/sjt = e_j / s_j. For ej=0e_j = 0 the function t↦−sjtt \mapsto -s_j t has its unique maximum on t≥0t \ge 0 at t=0=ej/sjt = 0 = e_j / s_j. So x′x' of (1) is the unique maximizer of Q(⋅ ;x)Q(\cdot\,; x) over x′≥0x' \ge 0, and by Lemma 2

L(x′)≥Q(x′;x)≥Q(x;x)=L(x).L(x') \ge Q(x'; x) \ge Q(x; x) = L(x).

If x′≠xx' \ne x, the middle inequality is strict, because the maximizer is unique. □\square

Theorem 2 (the total count). If b=0b = 0, then ∑jsjxj′=∑iyi\sum_j s_j x'_j = \sum_i y_i for every admissible xx.

Proof. By (1), ∑jsjxj′=∑iyiyˉi∑jaijxj=∑iyi\sum_j s_j x'_j = \sum_i \frac{y_i}{\bar y_i} \sum_j a_{ij} x_j = \sum_i y_i, the sum over the rays with yi>0y_i > 0, because yˉi=∑jaijxj\bar y_i = \sum_j a_{ij} x_j when b=0b = 0. □\square

So with b=0b = 0 the expected total count ∑iyˉi\sum_i \bar y_i equals the measured total count after the first iteration.

Theorem 3 (fixed points). An admissible xx is a fixed point of (1) if and only if ∂L/∂xj=0\partial L / \partial x_j = 0 for every jj with xj>0x_j > 0. A maximizer of LL over x≥0x \ge 0 is a fixed point. A fixed point xx is a maximizer if and only if also ∂L/∂xj≤0\partial L / \partial x_j \le 0 for every jj with xj=0x_j = 0.

Proof. The gradient is ∂L/∂xj=∑iaijyi/yˉi−sj\partial L / \partial x_j = \sum_i a_{ij} y_i / \bar y_i - s_j. For xj>0x_j > 0, (1) gives xj′=xjx'_j = x_j if and only if ∑iaijyi/yˉi=sj\sum_i a_{ij} y_i / \bar y_i = s_j, that is ∂L/∂xj=0\partial L / \partial x_j = 0. For xj=0x_j = 0, (1) gives xj′=0x'_j = 0 always. The function LL is concave on the admissible set, because each log⁡yˉi\log \bar y_i is the logarithm of an affine function and −yˉi-\bar y_i is affine. For a concave differentiable function on the orthant, xx is a maximizer if and only if the KKT conditions hold: ∂L/∂xj≤0\partial L / \partial x_j \le 0 for all jj, with equality where xj>0x_j > 0. Both claims follow. □\square

A fixed point with a zero pixel need not be a maximizer: a start with xj=0x_j = 0 keeps xj=0x_j = 0 for ever. This is why the start must be positive.

Convergence (cited, not proved here). For b=0b = 0 and a positive start, the iterates converge to a maximizer of LL over x≥0x \ge 0. 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 b=0b = 0 is a special case. Theorem 1 alone does not give convergence of the iterates: it gives a nondecreasing sequence L(xk)L(x^k) that is bounded above, since yilog⁡t−t≤yilog⁡yi−yiy_i \log t - t \le y_i \log y_i - y_i for every t>0t > 0.

Complexity

In the real-RAM model, with aa angles of dd bins each (m=adm = a d bins) and an n×nn \times n image (N=n2N = n^2 pixels):

  • Line L1 takes one pass over the nonzero entries of AA. A ray-driven projector has O(n)O(n) entries per bin, so nnz⁡(A)=O(adn)\operatorname{nnz}(A) = O(a d n).
  • Lines L4 and L6 take O(adn)O(a d n) each. Lines L5 and L7 take O(ad)O(a d) and O(n2)O(n^2).

So one iteration costs O(adn)O(a d n) time and O(ad+n2)O(a d + n^2) extra space, and KK iterations cost O(Kadn)O(K a d n). The number of iterations is the regularization parameter. No bound on the right KK 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 x≥0x \ge 0 is necessary.
  • Monotone likelihood. L(xk)L(x^k) 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 xj+(xj/sj) ∂L/∂xjx_j + (x_j / s_j)\, \partial L / \partial x_j. So MLEM is gradient ascent with the step xj/sjx_j / s_j for pixel jj. The step is small where the pixel is small, which keeps the pixel positive.
  • Count preserving. With b=0b = 0 the predicted total count equals the measured one after each iteration.
  • Not linear in the data. The iterate depends on yy 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 −βR(x)-\beta R(x) to LL. The one-step-late algorithm of Green (1990) puts the gradient of RR 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 AA with ∑iaij=1\sum_i a_{ij} = 1, 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 AA.
  • 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 yi>0y_i > 0 and yˉi=0\bar y_i = 0 makes line L5 fail. This happens if the bin sees no pixel and bi=0b_i = 0. 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 bb and keep the raw counts.
  • A mismatched back projector. If line L6 does not use ATA^T, or ss is not AT1A^T \mathbf{1} for the same AA, the likelihood can decrease and the limit is not the maximum likelihood image.
  • Too many iterations. With noise, the image becomes noisy as kk grows, while the likelihood still increases. The rise of LL is not a sign of a better image.
  • Expecting a unique answer. If AA 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.

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
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

  1. 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)
  2. 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)
  3. 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)
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.per_iteration
  • a full proof of time.total
  • 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