Algorithmcore
Ordered subsets expectation maximization
Also called OSEM.
Speed up MLEM by applying its multiplicative update with one subset of projections at a time, cycling through the subsets.
- Time
- O(K (a d n + T n^2)) totalO(a d n + T n^2) per_iteration
- Space
- O(a d + T n^2) extra
- Where
- K = the number of passes over all subsets; T = the number of subsets; 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
- not convergent on noisy datadeterministicnot in placeiterativekeeps nonnegativitynot monotone likelihoodorder dependentiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- H. Malcolm Hudson, Richard S. Larkin, 1994
OSEM is a faster form of MLEM for the emission tomography model . It splits the detector bins into subsets, usually groups of whole views, and applies the MLEM update with the bins of one subset at a time: , with the sensitivity of the subset. One pass over all subsets costs about as much as one MLEM iteration. In the early passes it raises the likelihood about as much as MLEM iterations; this is a measurement, not a theorem. The price is that OSEM does not maximize the likelihood. With noisy data its iterates do not converge to the maximum likelihood image and can cycle. Like MLEM, it keeps the image nonnegative and is stopped early in practice. It is the standard reconstruction of clinical PET and SPECT.
In plain words
MLEM looks at all the data before it changes the image once. That is slow, because each change needs a full pass over the data. OSEM cuts the data into a few groups, for example every fourth view of the scanner. It does the MLEM step with the first group only, and changes the image at once. Then it does the step with the next group, starting from the new image, and so on.
Each group alone gives a fair picture of the object, so each small step goes in about the right direction. So one pass over all groups does about as much work as several MLEM steps, for the same cost. But no group sees all the data. Near the end, each group pulls the image to its own best answer, and the image moves in a circle among them instead of settling.
The problem
The same as for MLEM: given counts , a matrix with and a background , find a nonnegative image with a high Poisson log-likelihood
OSEM also needs a partition of the bins into subsets . In practice the goal is not the maximizer of , which is noisy, but a good image after a few passes. The subsets are balanced if every pixel has the same sensitivity in every subset, .
The algorithm
OSEM(A, y, b, x0, S_1..S_T, K) ▷ x0 > 0; the subsets partition the bins- 1
s^t_j ← Σ_{i ∈ S_t} a_ij for each subset t and pixel j - 2
x ← x0 - 3
for k ← 1 to K do - 4
for t ← 1 to T do ▷ one sub-iteration per subset - 5
ȳ_i ← (A x)_i + b_i for i ∈ S_t - 6
r_i ← y_i / ȳ_i for i ∈ S_t ▷ r_i ← 0 if y_i = 0 - 7
g_j ← Σ_{i ∈ S_t} a_ij r_i for each pixel j - 8
x_j ← x_j g_j / s^t_j for each pixel j with s^t_j > 0 - 9
return x
Lines L5 and L7 are a forward and a back projection of the views in only, so a sub-iteration costs about of an MLEM iteration. A pixel that no bin of sees is not changed by line L8. With , OSEM is MLEM.
The usual subsets are interleaved views: with angles, subset holds the angles . Then each subset covers the whole range of angles, and for a parallel-beam scan the subsets are close to balanced. The number of subsets is a tuned design choice: more subsets give a faster start, but each subset then holds fewer views and more noise. The order of the subsets also matters, and orders that make successive subsets far apart in angle are common. These choices are heuristics.
Example
Rows, then columns. Take a image in row-major order, the counts of the two rows and of the two columns , no background, and the subsets and . Each pixel lies on one row and one column, so and the subsets are balanced. From :
| step | ||||
|---|---|---|---|---|
| start | 1 | 1 | 1 | 1 |
| rows: scale row 0 by and row 1 by | 3/2 | 3/2 | 7/2 | 7/2 |
| columns: scale column 0 by and column 1 by | 6/5 | 9/5 | 14/5 | 21/5 |
The result fits all four counts after one pass, and later passes do not change it. Here OSEM is iterative proportional fitting of a table to its row and column sums. Four counts do not determine four pixels: MLEM from the same start reaches a different solution, , and the image that made the data could have been . All three fit the data.
A cycle. Take one pixel seen by two bins with , the counts and one bin per subset. The first sub-iteration sets and the second sets , from every positive start. So the sub-iterates are , and every pass ends at 3. The maximum likelihood estimate is 2. The subsets are balanced; the data are inconsistent, as noisy data always are.
A limit cycle. Take the image with the rows, the columns and the diagonal through and , and the inconsistent counts . The maximum likelihood image is with . OSEM with the three subsets rows, columns and diagonal converges to a cycle. After the rows the image is , and after the columns and after the diagonal it is , with . Neither point is the maximizer.
The speedup, measured. 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. The counts are Poisson with mean 50 times the projections (seed 7, 5676 counts). The table compares one OSEM pass with interleaved view subsets and iterations of MLEM, from the same flat start. The error is .
| after one OSEM pass | after MLEM iterations | error after one OSEM pass | |
|---|---|---|---|
| 1 | 14794.1 | 14794.1 | 0.637 |
| 2 | 15440.5 | 15439.9 | 0.464 |
| 3 | 15813.7 | 15810.2 | 0.365 |
| 4 | 16015.5 | 16006.8 | 0.297 |
| 6 | 16191.1 | 16170.7 | 0.250 |
| 12 | 16133.2 | 16266.5 | 0.462 |
Up to 6 subsets, one pass does a little more than MLEM iterations. With 12 subsets of one view each, it does much less: one view alone is a poor picture of the object. With , five passes reach , about as much as 30 MLEM iterations, and the error has risen to : the best MLEM error in this setup is , after 10 iterations, so five passes are already too many. These numbers are measurements of this setup, not properties of the method.
Correctness
Each sub-iteration is one MLEM iteration for the data of its subset. So by the MLEM theorem it keeps the image nonnegative and does not decrease the subset likelihood . It can decrease the full likelihood , so OSEM is not a monotone method for , and the tests do not check a monotone . If the data are consistent, that is for some , every such is a fixed point of every sub-iteration. Hudson and Larkin (1994) proved that with exact data and balanced subsets, OSEM converges to such a solution. With inconsistent data there is no such point, and the examples above show a cycle and a limit cycle away from the maximizer. The proofs are in proofs/correctness.md.
Proof: What OSEM guarantees and what it does notfull
We use the notation of the page. is an matrix with , is the known background, holds the counts, and the bins are split into disjoint subsets whose union is all bins. For a subset put and
so the full log-likelihood is . Sub-iteration (lines L5 to L8) maps to
where the sum runs over the bins of with . We assume that for every bin with , as on the MLEM page. We work in exact arithmetic.
Theorem 1 (one sub-iteration). For every subset , , with equality only if , and .
Proof. Let be the rows of in , and remove the pixels with : they do not enter , because their column in is zero, and (1) does not change them. On the other pixels, (1) is exactly one MLEM iteration for the matrix , the counts , , and the background , . Theorem 1 of the MLEM proof (the Jensen surrogate) gives with equality only if . Every factor in (1) is nonnegative.
So OSEM is a cycle of maps, and map climbs its own likelihood . It does not climb : a step that raises can lower for by more.
Theorem 2 (the subset count). If , then after sub-iteration , .
Proof. Sum (1) times over the pixels with and swap the sums: , because for . The pixels with add nothing.
Theorem 3 (consistent data). If satisfies , then is a fixed point of every sub-iteration, so OSEM started at stays at .
Proof. For every with , . So for , (1) gives . A bin with has , so for all in that bin. Hence , and .
Theorem 4 (no convergence in general). There are data for which the OSEM iterates do not converge, and for which the end points of the passes converge to a point that is not a maximizer of .
Proof. Take one pixel, two bins with , , counts , and the subsets , . Both subsets have , so they are balanced. Sub-iteration 1 gives , and sub-iteration 2 gives , from every positive start. So the sub-iterates are and do not converge. The end point of each pass is 3. The maximizer of is , because .
The example has inconsistent data: no has and . Real counts are always inconsistent with the model in this sense, because of the noise. So in practice OSEM does not converge to the maximum likelihood image. Its passes approach a limit cycle near it. The page shows a second example on a image.
What is known about convergence (cited, not proved here). Hudson and Larkin (1994) proved that if the data are exact, so that a nonnegative solution of exists, and the subsets are balanced, that is does not depend on , then OSEM converges to such a solution. Methods that converge with noisy data change the update: they make the step size go to 0, as in RAMLA, or they keep a running sum of all subset gradients, as in COSEM. They are not the plain OSEM of this page.
Complexity
In the real-RAM model, with angles of bins, an image and subsets that split the views:
- Line L1 takes one pass over the nonzero entries of , , and stores sensitivity images, space.
- In one pass, lines L5 and L7 touch every nonzero entry of twice, in total. Line L8 runs times over the image, .
So a pass costs time, which is when and , and passes cost . The extra space is . As with MLEM, the number of passes is the regularization parameter, and every stopping rule without a known noise level is a heuristic.
Properties
- Nonnegative. As in MLEM, each sub-iteration multiplies by nonnegative numbers.
- Not monotone. The full likelihood can decrease from one sub-iteration to the next. Each sub-iteration raises only its own subset likelihood.
- Not convergent with noisy data. The passes approach a limit cycle, not the maximizer. With exact data and balanced subsets, OSEM converges to a solution (Hudson and Larkin).
- Fast at the start. In the early passes, one pass with subsets does about the work of MLEM iterations, for up to a limit that depends on the data. This is a measurement, as in the table above.
- Order dependent. The result depends on the subsets and on their order, like ART and SART. OSEM is to MLEM what SART is to SIRT, and what stochastic gradient descent with a fixed step is to gradient descent.
Variants and improvements
- Relaxed and convergent forms. RAMLA (Browne and De Pierro, 1996) updates with one block of bins at a time and a relaxation parameter that goes to 0, and it converges to the maximizer. COSEM keeps a running sum of the subset terms and also converges. Both trade some of the early speed for convergence.
- Fewer subsets later. Start with many subsets and reduce in later passes. Then the method ends closer to MLEM. The schedule is a heuristic.
- Penalized forms. The one-step-late update of OSL and the SPS update can both use ordered subsets. The penalized forms with ordered subsets have the same convergence problem as OSEM unless the step size goes to 0.
- Block iterative EM. Byrne gave rescaled block forms (RBI-EM) that converge with consistent data without the balance condition.
When to use it
Use OSEM when you need an MLEM-like image from emission data in a few passes, as in clinical PET and SPECT. Choose the subsets as interleaved views, keep enough views in each subset that it covers the full range of angles, and fix the number of subsets and passes for a protocol, because the image depends on both. Use MLEM or a convergent method when you need the maximum likelihood image itself, for example to study the method, and use a penalized method when you want the result not to depend on where you stop.
Pitfalls
- Too many subsets. A subset of one or two views gives a poor picture of the object, and the method becomes noisy and unstable. In the table above, 12 subsets of one view each did worse than 6.
- Unbalanced subsets. If the sensitivity of a pixel differs much between subsets, the image changes in a different way in each sub-iteration, and the cycle is larger.
- Reading convergence into it. After a few passes the image changes little, but this is not convergence to the maximum likelihood image. With more passes, the noise grows as in MLEM.
- Testing a monotone likelihood. The full likelihood is not monotone. Only the likelihood of the subset that was just used is.
- Comparing by iterations. Compare OSEM and MLEM by the number of projections, or by the total time, not by the number of passes or sub-iterations.
Implementations
The Python code takes the system matrix as sparse rows of (column, weight) pairs and a list of subsets of row indices, and it works with float or fractions.Fraction data. A helper builds interleaved view subsets for the row order of imgkit.parallel_beam_matrix. The tests check the rows-then-columns example exactly, that one subset gives MLEM, the cycle of the one-pixel example, the limit cycle of the example and its gap to the maximizer, the monotone subset likelihood of each sub-iteration on random problems, the convergence to a solution with exact data and balanced subsets, the adjoint test of the projector pair, and the measured speedup on the disk phantom.
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
osem.py 90 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/osem/. The authors are listed in prov/H40E6J.jsonl.
"""OSEM, ordered subsets expectation maximization (Hudson and Larkin, 1994).
The model is y_i ~ Poisson((A x)_i + b_i). A is given as sparse rows: row i is
a list of (column, weight) pairs, as returned by imgkit.parallel_beam_matrix.
The bins are split into subsets S_1, ..., S_T, and one sub-iteration is the
MLEM update with the bins of one subset only:
x_j <- (x_j / s_j^t) sum_{i in S_t} a_ij y_i / (A x + b)_i,
s_j^t = sum_{i in S_t} a_ij.
A pixel with s_j^t = 0 is not changed by subset t. With one subset that holds
all bins, OSEM is MLEM. The code works with float or fractions.Fraction data.
"""
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 log_likelihood(rows, y, x, b=None):
"""L(x) = sum_i [y_i log ybar_i - ybar_i] with ybar = A x + b (float)."""
total = 0.0
for i, (row, yi) in enumerate(zip(rows, y)):
li = sum(w * x[j] for j, w in row) + (b[i] if b is not None else 0)
if yi != 0:
if li <= 0:
return -math.inf
total += float(yi) * math.log(float(li))
total -= float(li)
return total
def view_subsets(nangles, nbins, nsubsets):
"""Interleaved subsets of whole views: subset t holds the angles a with a mod T = t.
Row a * nbins + q holds angle a and bin q, as in imgkit.parallel_beam_matrix.
"""
return [[a * nbins + q for a in range(t, nangles, nsubsets) for q in range(nbins)] for t in range(nsubsets)]
def osem(rows, ncols, y, subsets, b=None, iters=10, x0=None, callback=None, sub_callback=None):
"""Run OSEM and return the image after iters full passes over the subsets.
subsets: a list of lists of row indices, which together hold every row
once; x0: a positive start (by default the constant image whose projections
have the total count of y); callback(k, x) is called after each full pass,
sub_callback(k, t, x) after each sub-iteration.
"""
sens = []
for sub in subsets: # @line L1
s = [0] * ncols
for i in sub:
for j, w in rows[i]:
s[j] += w
sens.append(s)
if x0 is None:
total = [sum(col) for col in zip(*sens)]
c = sum(y) / sum(total)
x0 = [c if t != 0 else 0 * c for t in total]
x = list(x0) # @line L2
for k in range(iters): # @line L3
for t, sub in enumerate(subsets): # @line L4
sub_rows = [rows[i] for i in sub]
ybar = forward(sub_rows, x) # @line L5
if b is not None:
ybar = [li + b[i] for li, i in zip(ybar, sub)]
ratio = [y[i] / li if y[i] != 0 else 0 * li for li, i in zip(ybar, sub)] # @line L6
g = back(sub_rows, ratio, ncols) # @line L7
s = sens[t]
x = [xj * gj / sj if sj != 0 else xj for xj, gj, sj in zip(x, g, s)] # @line L8
if sub_callback is not None:
sub_callback(k + 1, t + 1, x)
if callback is not None:
callback(k + 1, x)
return x # @line L9
test_osem.py 125 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/osem/. The authors are listed in prov/H40E6J.jsonl.
import math
import random
from fractions import Fraction as F
import imgkit as ik
from osem import back, forward, log_likelihood, osem, view_subsets
# The 2 x 2 example of the page: the two rows and the two columns.
A4 = [[1, 1, 0, 0], [0, 0, 1, 1], [1, 0, 1, 0], [0, 1, 0, 1]]
ROWS4 = [[(j, F(w)) for j, w in enumerate(r) if w] for r in A4]
Y4 = [F(v) for v in (3, 7, 4, 6)]
# The inconsistent example: rows, columns and one diagonal.
A5 = [[1, 1, 0, 0], [0, 0, 1, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 0, 1]]
ROWS5 = [[(j, 1.0) for j, w in enumerate(r) if w] for r in A5]
Y5 = [3.0, 8.0, 4.0, 6.0, 5.0]
def test_rows_then_columns_exact() -> None:
seen = []
osem(ROWS4, 4, Y4, [[0, 1], [2, 3]], iters=3, x0=[F(1)] * 4, sub_callback=lambda k, t, x: seen.append(x))
assert seen[0] == [F(3, 2), F(3, 2), F(7, 2), F(7, 2)]
assert seen[1] == [F(6, 5), F(9, 5), F(14, 5), F(21, 5)]
assert all(x == seen[1] for x in seen[2:])
assert forward(ROWS4, seen[1]) == Y4
def test_one_subset_is_mlem() -> None:
x = osem(ROWS4, 4, Y4, [[0, 1, 2, 3]], iters=1, x0=[F(1)] * 4)
assert x == [F(7, 4), F(9, 4), F(11, 4), F(13, 4)]
def test_cycle_on_inconsistent_data() -> None:
rows = [[(0, F(1))], [(0, F(1))]]
seen = []
x = osem(rows, 1, [F(1), F(3)], [[0], [1]], iters=4, x0=[F(1)], sub_callback=lambda k, t, v: seen.append(v[0]))
assert seen == [1, 3, 1, 3, 1, 3, 1, 3]
ml = osem(rows, 1, [F(1), F(3)], [[0, 1]], iters=1, x0=[F(1)])
assert ml == [F(2)] and x == [F(3)]
def test_limit_cycle_misses_the_maximum() -> None:
ml = osem(ROWS5, 4, Y5, [[0, 1, 2, 3, 4]], iters=3000, x0=[1.0] * 4)
assert max(abs(a - b) for a, b in zip(ml, (43 / 55, 229 / 110, 188 / 55, 232 / 55))) < 1e-9
seen = []
osem(ROWS5, 4, Y5, [[0, 1], [2, 3], [4]], iters=2000, x0=[1.0] * 4, sub_callback=lambda k, t, v: seen.append(v))
after_rows, end = seen[-3], seen[-1]
assert max(abs(a - 22 * b / 20) for a, b in zip(after_rows, end)) < 1e-9
assert max(abs(22 * a - b) for a, b in zip(end, (19, 41, 69, 91))) < 1e-9
assert log_likelihood(ROWS5, Y5, end) < log_likelihood(ROWS5, Y5, ml) - 0.02
def test_each_sub_iteration_raises_its_subset_likelihood() -> None:
rng = random.Random(5)
for _ in range(4):
m, n = 12, 6
rows = [[(j, rng.uniform(0.1, 1.0)) for j in range(n) if rng.random() < 0.6] or [(0, 0.5)] for _ in range(m)]
b = [rng.uniform(0.0, 0.5) for _ in range(m)]
y = [ik.poisson_sample(rng, 3.0 * (li + bi)) for li, bi in zip(forward(rows, [rng.uniform(0, 3) for _ in range(n)]), b)]
subsets = [[0, 3, 6, 9], [1, 4, 7, 10], [2, 5, 8, 11]]
prev = {"x": [1.0] * n}
def sub_ll(t, x):
sub = subsets[t - 1]
return log_likelihood([rows[i] for i in sub], [y[i] for i in sub], x, [b[i] for i in sub])
def check(k, t, x):
assert sub_ll(t, x) >= sub_ll(t, prev["x"]) - 1e-9
assert all(v >= 0 for v in x)
prev["x"] = x
osem(rows, n, y, subsets, b=b, iters=10, x0=[1.0] * n, sub_callback=check)
def test_balanced_subsets_with_exact_data_reach_a_solution() -> None:
rng = random.Random(8)
n = 6
subsets_rows = []
for _ in range(3):
block = [[rng.uniform(0.0, 1.0) for _ in range(n)] for _ in range(3)]
col = [sum(r[j] for r in block) for j in range(n)]
subsets_rows.extend([(j, r[j] / col[j]) for j in range(n)] for r in block)
xt = [rng.uniform(0.5, 2.0) for _ in range(n)]
y = forward(subsets_rows, xt)
x = osem(subsets_rows, n, y, [[0, 1, 2], [3, 4, 5], [6, 7, 8]], iters=3000, x0=[1.0] * n)
assert max(abs(a - c) for a, c in zip(forward(subsets_rows, x), y)) < 1e-6
def test_view_subsets_partition_the_rows() -> None:
subs = view_subsets(12, 5, 4)
assert sorted(i for s in subs for i in s) == list(range(60))
assert subs[1][:5] == [5, 6, 7, 8, 9] and subs[1][5] == 25
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)
gap = abs(sum(p * q for p, q in zip(ax, v)) - sum(p * q for p, q in zip(x, atv)))
assert gap <= 1e-10 * math.sqrt(sum(p * p for p in ax) * sum(q * q for q in v))
def test_disk_phantom_speedup_measurement() -> None:
n, na, nb = 16, 12, 23
rows = ik.parallel_beam_matrix(n, [math.pi * a / na for a in range(na)], nb)
truth = ik.flatten(ik.disk_phantom(n, 0.6))
rng = random.Random(7)
y = [ik.poisson_sample(rng, 50.0 * v) for v in forward(rows, truth)]
assert sum(y) == 5676
mlem_ll = []
osem(rows, n * n, y, [list(range(len(rows)))], iters=12, callback=lambda k, x: mlem_ll.append(log_likelihood(rows, y, x)))
one_pass = {}
for t in (2, 4, 6, 12):
x = osem(rows, n * n, y, view_subsets(na, nb, t), iters=1)
one_pass[t] = log_likelihood(rows, y, x)
for t in (2, 4, 6):
assert one_pass[t] >= mlem_ll[t - 1]
assert abs(one_pass[6] - 16191.1) < 0.1
assert one_pass[12] < mlem_ll[11] - 100
History
Hudson and Larkin published OSEM in 1994 in IEEE Transactions on Medical Imaging. They applied the MLEM update of Shepp and Vardi (1982) to ordered subsets of the projections, proved convergence for exact data with balanced subsets, and reported a speedup by about the number of subsets in the early iterations. The idea is the same as in the algebraic methods, where ART updates after each ray and SART after each view, instead of after all data as SIRT does. OSEM made iterative reconstruction fast enough for clinical use, and it became the standard method for PET and SPECT. Browne and De Pierro (1996) introduced the convergent row-action form RAMLA.
References
- H. M. Hudson and R. S. Larkin, Accelerated image reconstruction using ordered subsets of projection data, IEEE Transactions on Medical Imaging 13(4), 1994, pp. 601 to 609 (the OSEM update, subset balance, convergence with exact data, and the speedup)
- 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 MLEM update that OSEM applies to each subset)
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 H40E6J Edit this page History Report an error Markdown