Algorithmadvanced
Separable paraboloidal surrogates
Also called SPS.
Minimize penalized likelihood for transmission or emission tomography by minimizing at each step a separable quadratic surrogate that majorizes the cost.
- 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 nonnegativitymonotone objectiveparallel over pixelsiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Hakan Erdogan, Jeffrey A. Fessler, 1999
Separable paraboloidal surrogates (SPS) is a monotone method for penalized likelihood reconstruction. For the emission tomography model it minimizes over , where is the negative Poisson log-likelihood of bin and is a convex penalty. Each iteration does two things. First, it replaces each by a parabola that touches it at the current line sum and lies above it for all nonnegative line sums. Second, it splits the sum of parabolas and the penalty into a sum of one-pixel quadratics with De Pierro's convexity trick. The minimizer of the result is a clipped Newton step for each pixel, all in parallel. The cost never increases, the image stays nonnegative, and any works. This is the difference from the one-step-late algorithm, which can fail for a large . Erdogan and Fessler introduced the method for transmission tomography in 1999.
In plain words
The cost of an image measures how badly it explains the counts, plus a charge for roughness. It is hard to minimize directly, because each count depends on many pixels at once.
SPS builds, at each step, a simpler cost that is never below the true one and is equal to it at the current image. The simpler cost is a sum of terms with one pixel each, and each term is a parabola, so its lowest point has a formula. If the lowest point is negative, the pixel is set to 0. Moving to the lowest point of the simpler cost cannot raise the true cost, because the simpler cost is above the true cost everywhere and equal at the start.
The method is safe for any strength of the smoothing. The price is speed: each step is cautious, so it can need more steps than MLEM.
The problem
Given counts , a matrix with and row sums , a background for every bin with , a weight , and the quadratic neighbor penalty
minimize over . This is the negative of the penalized log-likelihood of the one-step-late page, up to a constant. is a convex function, so its minimizers are the points that satisfy the KKT conditions for . The background must be positive where there are counts: if and , then , and no finite parabola lies above on .
The surrogate has two parts. For the data, at the current line sum , take the parabola
This optimal curvature makes , and it is the smallest curvature for which on . Then De Pierro's split writes , a convex combination, so the convexity of gives a sum of one-pixel terms that lies above . The same trick on the penalty gives one-pixel terms of curvature for pixel .
The algorithm
SPS(A, y, b, β, w, x0, K) ▷ x0 ≥ 0; b_i > 0 where y_i > 0- 1
a_i ← Σ_j a_ij for each ray i - 2
p_j ← 2 Σ_k w_jk for each pixel j ▷ the penalty curvature - 3
x ← x0 - 4
for k ← 1 to K do - 5
l ← A x ▷ the line sums - 6
h'_i ← 1 - y_i / (l_i + b_i) ▷ the slopes of the data terms - 7
c_i ← the optimal curvature of h_i at l_i - 8
d ← A^T (a ⊙ c) ▷ d_j = Σ_i a_ij a_i c_i - 9
g ← A^T h' ▷ the gradient of the data part - 10
x_j ← max(0, x_j - (g_j + β ∂R/∂x_j(x)) / (d_j + β p_j)) for each pixel j - 11
return x
One iteration has one forward projection (L5) and two back projections (L8 and L9). The curvatures cost each. Line L10 updates all pixels at once, from the same old image, so it is parallel over the pixels. If a pixel has , only rays with see it and it has no penalty neighbor; then the cost is linear in and increasing, and the code sets .
Example
Take the image of the MLEM page, with 5 rays: the two rows, the two columns and one diagonal (pixels 1 and 4), and , so . The counts are and the background is . These data are consistent: at , so is the minimizer for . Start from .
Every line sum is . The slopes are , and the optimal curvatures are . For pixel 1, which lies on rays 1, 3 and 5, and , so . The first iterate is .
| iteration | 1 | 2 | 3 | 10 | 50 | 100 | 300 |
|---|---|---|---|---|---|---|---|
| for SPS | |||||||
| max error of SPS | 2.46 | 2.19 | 1.94 | 0.87 | 0.024 | 2.1e-3 | 2.4e-7 |
| max error of MLEM | 1.35 | 0.75 | 0.58 | 0.18 | 5.5e-3 | 8.5e-5 | 5.1e-12 |
starts at and decreases at each step to the minimum . On this problem, a measurement, SPS needs about twice as many iterations as MLEM for the same error. With and the 4 edges of the grid, SPS converges to , a smoother image, again with a decreasing cost.
A larger measurement uses a disk phantom of radius 0.6, 12 angles, 23 bins, a count scale of 50, a background of 1 per bin and Poisson noise with seed 7 (5958 counts). The image covers , and pixel has its center at , . The table gives the relative error after iterations. decreased at every step for every .
| OSL after 300 | |||||
|---|---|---|---|---|---|
| 1 | 0.579 | 0.250 | 0.214 | 0.253 | 0.271 |
| 5 | 0.583 | 0.261 | 0.226 | 0.227 | 0.227 |
| 20 | 0.595 | 0.294 | 0.272 | 0.272 | fails: a denominator |
| 100 | 0.649 | 0.392 | 0.366 | 0.364 | fails: a denominator |
With , MLEM reaches after 10 iterations, and SPS needs between 50 and 100 iterations for the same value.
Correctness
Three facts give a monotone method. They are theorems, proved in proofs/correctness.md.
- The parabola lies above the data term. For and the optimal curvature, for all . The proof uses that decreases, so has a convex derivative; with zeros of at and and a zero slope at , this forces on .
- The split keeps it above. The weights form a convex combination, so Jensen's inequality for the convex gives the separable surrogate with on and at the current image. The split can evaluate at negative arguments; that is fine, because only the convexity of is used there, and is needed only at .
- Line L10 minimizes . is a sum of one-pixel quadratics with slope and curvature at the current image, and L10 is the clipped Newton step for each.
So . The fixed points with positive curvatures are exactly the points that satisfy the KKT conditions, which are the minimizers since is convex. The convergence of the iterates themselves is not proved on this page; it needs conditions such as a strictly convex cost.
Proof: The SPS surrogate lies above the cost, so SPS does not increase itfull
We use the notation of the page. is an matrix with and row sums . The data are , the background is with wherever , and . The cost is
with . Each is convex and finite on . Fix the current image and write . All statements are in exact arithmetic.
Lemma 1 (the one-dimensional parabola). Let with and , let , and let
Then , and satisfies for all , with equality at . For , is linear and gives .
Proof. because is convex: . Let on . Then and , and . Since is decreasing, is increasing, so is convex.
If , then , so is convex with , and .
If , the choice of gives . Since , Rolle's theorem gives a with . The convex function is 0 at and at , so on and on and on . So rises from on , falls to on , and rises again after . Each piece starts or ends at the value 0 from above, so on .
The curvature is the smallest one with this property for : a parabola with the same value and slope at and a smaller curvature is below at .
Lemma 2 (the separable surrogate). For let
with the parabola of Lemma 1 for at . Then and for every .
Proof. The weights are nonnegative and sum to 1 over , and . The parabola is convex on all of , so Jensen's inequality gives . Since , Lemma 1 gives . Note that the arguments can be negative; this is no problem, because only the convexity of is used there, and is defined everywhere.
For the penalty, , and by the convexity of the square. Multiplying by gives the penalty terms of . At every inequality is an equality: all arguments of equal , , and .
Theorem 1 (the update minimizes the surrogate). is a sum of one-pixel quadratics with
If , the minimizer of over is , which is line L10.
Proof. The derivative of the -th data term with respect to at is , and its second derivative is . Each edge adds to , which is at , and to . Summing gives the formulas, and the gradient of at is , which matches. A one-variable quadratic with positive curvature has its minimizer over at the clipped Newton point. If , then every ray through has (so and ) and has no penalty edge with ; is linear with slope , and the code takes if the slope is positive.
Theorem 2 (monotone decrease). Let be the SPS update of . Then and .
Proof. by the clipping. By Lemma 2 and Theorem 1, .
Theorem 3 (fixed points). If every , then is a fixed point of the update if and only if it satisfies the KKT conditions where and where . Since is convex, these are exactly the minimizers of over .
Proof. With , holds if and only if (when ) or (when ). For a convex function on the nonnegative orthant, the KKT conditions are necessary and sufficient for a minimum.
Convergence (cited, not proved here). Theorem 2 makes a nonincreasing sequence that is bounded below when is bounded below on , so it converges. That the iterates themselves converge to a minimizer needs more: a lower bound on the curvatures and a strictly convex cost are typical conditions. The papers of Erdogan and Fessler discuss this; this page does not prove it. The tests check the KKT conditions at the limit for a small problem.
Complexity
In the real-RAM model, with angles of bins and an image, a forward or back projection costs . One iteration costs one forward and two back projections plus for the curvatures and the penalty, so time and extra space. iterations cost . The number of iterations for a given accuracy has no general bound.
Properties
- Monotone for any . The cost does not increase. This is a theorem.
- Nonnegative. The clipping keeps , and a pixel can reach exactly 0 in one step. MLEM keeps a positive pixel positive unless every ray through it has no counts.
- Parallel over the pixels. All pixels update from the same old image, so the update is a vector operation, like MLEM.
- Correct fixed points. A fixed point satisfies the KKT conditions, so it is a minimizer.
- Slow when the curvatures are large. The surrogate is a safe upper bound, and its curvature adds up the curvatures of all the rays through the pixel. So the steps are short. In the measurements above, SPS needed more iterations than MLEM.
- Any convex penalty with a quadratic surrogate. The quadratic penalty is the simplest case. Edge-keeping penalties such as the Huber function have parabolas above them too, and fit in the same way.
Variants and improvements
- Transmission data. The original setting of Erdogan and Fessler. For transmission scans, the mean count is by the Beer-Lambert law, and is not convex for every data value. Erdogan and Fessler showed that the optimal curvature formula, with the same form, still gives a parabola above on for this model.
- Precomputed curvatures. A fixed curvature, computed once from the data, avoids line L7 and the back projection of line L8 at each iteration. It is not always above , so the method is no longer monotone in general.
- Ordered subsets. Using one subset of the rays per sub-iteration, with the gradient scaled by the number of subsets, gives OS-SPS. Like OSEM, it is fast early but has no monotone guarantee and does not converge in general. The number of subsets is a tuned design choice.
- Coordinate descent. The paraboloidal surrogate can be minimized one pixel at a time, with the line sums updated after each pixel, as in coordinate descent. This uses less cautious steps but is harder to run in parallel.
- De Pierro's modified EM. De Pierro (1995) used the same separable trick on the penalty with an EM-type data surrogate. SPS uses parabolas for both parts.
When to use it
Use SPS when you need a penalized likelihood image and a guarantee that the cost decreases, for any penalty weight. It is a good reference method to check faster methods against, for example OSL with a small or an ordered subsets method. When speed matters more than a guarantee, use an ordered subsets form for the first iterations and then a monotone method.
Pitfalls
- No background. With and the data term is infinite at a zero line sum, and no parabola lies above it. Add a small positive background, or use a method for the case without background.
- The curvature at a zero line sum. For the formula has a ; the right value is the limit . Rounding errors near can give a slightly negative value; clip it at 0.
- A small background gives a huge curvature. Then is large for rays with a small line sum, and those pixels move very slowly.
- Clipping before the sum. Clip each pixel after the full step. Clipping inside the sums changes the surrogate and breaks the proof.
- Testing the wrong property. Test that does not increase. Do not test that the error to the true image decreases: with noisy data it does not, as the row of the table shows.
Implementations
The Python code takes the system matrix as sparse rows of (column, weight) pairs and the penalty as a list of weighted edges. It raises an error when a bin has counts and no background. The tests check that the optimal curvature gives a parabola above on and that it is the smallest such curvature, that the separable surrogate is above the cost and equal at the current image, that one step minimizes the surrogate, the first iterate of the example and its limit, that the cost does not increase on a phantom for and , the KKT conditions at the limit with pixels at 0, the gradient against finite differences, and the adjoint test of the projector pair. It uses the shared imgkit helper for the phantom and the projector.
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
separable_paraboloidal_surrogates.py 146 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/separable-paraboloidal-surrogates/. The authors are listed in prov/DG54BX.jsonl.
"""Separable paraboloidal surrogates (SPS) for penalized likelihood emission
reconstruction.
The model is y_i ~ Poisson((A x)_i + b_i) with a known background b_i > 0.
SPS minimizes the cost
Phi(x) = sum_i h_i([A x]_i) + beta R(x), h_i(l) = (l + b_i) - y_i log(l + b_i),
over x >= 0, with the quadratic neighbor penalty R(x) = (1/2) sum over the
edges {j, k} of w_jk (x_j - x_k)^2. Each iteration replaces each h_i by a
parabola that lies above it on [0, inf) and touches it at the current line
sum (the optimal curvature of Erdogan and Fessler), splits the parabolas and
the penalty into one-pixel terms with De Pierro's convexity trick, and
minimizes the result over x >= 0. Phi does not increase.
A is given as sparse rows of (column, weight) pairs with weights >= 0.
"""
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.0] * ncols
for row, vi in zip(rows, v):
if vi != 0:
for j, w in row:
out[j] += w * vi
return out
def grid_edges(n, weight=1.0):
"""The edges (j, k, w) of the 4-neighbor graph of an n x n image, each once."""
edges = []
for i in range(n):
for j in range(n):
p = i * n + j
if j + 1 < n:
edges.append((p, p + 1, weight))
if i + 1 < n:
edges.append((p, p + n, weight))
return edges
def penalty(x, edges):
"""R(x) = (1/2) sum w_jk (x_j - x_k)^2 over the edges."""
return sum(w * (x[j] - x[k]) ** 2 for j, k, w in edges) / 2
def penalty_grad(x, edges):
"""dR/dx_j = sum over the neighbors k of w_jk (x_j - x_k)."""
g = [0.0] * len(x)
for j, k, w in edges:
d = w * (x[j] - x[k])
g[j] += d
g[k] -= d
return g
def h(yi, bi, l):
"""The negative log-likelihood of one bin, up to a constant: (l + b) - y log(l + b)."""
m = l + bi
return m - (yi * math.log(m) if yi != 0 else 0.0)
def h_prime(yi, bi, l):
"""h'(l) = 1 - y / (l + b)."""
return 1.0 - yi / (l + bi)
def optimal_curvature(yi, bi, l):
"""The smallest c >= 0 such that the parabola
q(t) = h(l) + h'(l) (t - l) + (c / 2) (t - l)^2 lies above h on [0, inf).
For l > 0 it is 2 [h(0) - h(l) + h'(l) l] / l^2, the curvature for which
q(0) = h(0). For l = 0 it is h''(0) = y / b^2.
"""
if yi == 0:
return 0.0
if l <= 0.0:
return yi / (bi * bi)
c = 2.0 * (h(yi, bi, 0.0) - h(yi, bi, l) + h_prime(yi, bi, l) * l) / (l * l)
return max(c, 0.0)
def objective(rows, y, x, beta, edges, b):
"""Phi(x) = sum_i h_i([A x]_i) + beta R(x)."""
lines = forward(rows, x)
return sum(h(yi, bi, li) for yi, bi, li in zip(y, b, lines)) + beta * penalty(x, edges)
def gradient(rows, y, x, beta, edges, b):
"""The gradient of Phi: A^T h'(A x) + beta grad R(x)."""
lines = forward(rows, x)
g = back(rows, [h_prime(yi, bi, li) for yi, bi, li in zip(y, b, lines)], len(x))
u = penalty_grad(x, edges)
return [gj + beta * uj for gj, uj in zip(g, u)]
def sps(rows, ncols, y, b, beta=0.0, edges=(), iters=50, x0=None, callback=None):
"""Run SPS with optimal curvatures and return the image after iters iterations.
b is the background, with b_i > 0 wherever y_i > 0. beta >= 0 is the
penalty weight and edges a list of (j, k, w) with w >= 0. x0 >= 0 is the
start (by default the constant image whose projections have the total
count of y - b). callback(k, x) is called after each iteration.
"""
for yi, bi in zip(y, b):
if yi != 0 and bi <= 0:
raise ValueError("a bin with counts needs a positive background")
asum = [sum(w for _, w in row) for row in rows] # @line L1
p = [0.0] * ncols # @line L2
for j, k, w in edges:
p[j] += 2.0 * w
p[k] += 2.0 * w
if x0 is None:
s = back(rows, [1.0] * len(rows), ncols)
c = max(sum(y) - sum(b), 0.0) / sum(s)
x0 = [c] * ncols
x = [float(v) for v in x0] # @line L3
for k in range(iters): # @line L4
lines = forward(rows, x) # @line L5
dh = [h_prime(yi, bi, li) for yi, bi, li in zip(y, b, lines)] # @line L6
curv = [optimal_curvature(yi, bi, li) for yi, bi, li in zip(y, b, lines)] # @line L7
d = back(rows, [ai * ci for ai, ci in zip(asum, curv)], ncols) # @line L8
g = back(rows, dh, ncols) # @line L9
u = penalty_grad(x, edges)
newx = []
for j in range(ncols): # @line L10
den = d[j] + beta * p[j]
if den <= 0.0:
# only rays with y_i = 0 see pixel j: Phi is linear in x_j with slope g_j >= 0
newx.append(0.0 if g[j] > 0 else x[j])
else:
newx.append(max(0.0, x[j] - (g[j] + beta * u[j]) / den))
x = newx
if callback is not None:
callback(k + 1, x)
return x # @line L11
test_separable_paraboloidal_surrogates.py 167 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/separable-paraboloidal-surrogates/. The authors are listed in prov/DG54BX.jsonl.
import math
import random
import imgkit as ik
from separable_paraboloidal_surrogates import (
back,
forward,
gradient,
grid_edges,
h,
h_prime,
objective,
optimal_curvature,
penalty,
sps,
)
# The example of the page: a 2 x 2 image, 5 rays, background 0.5 in each bin.
A5 = [[1, 1, 0, 0], [0, 0, 1, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 0, 1]]
ROWS5 = [[(j, float(w)) for j, w in enumerate(r) if w] for r in A5]
Y5 = [3.0, 7.0, 4.0, 6.0, 5.0]
B5 = [0.5] * 5
def _random_problem(rng, n, zeros=0):
rows = []
for _ in range(3 * n * n):
row = [(j, rng.uniform(0.1, 1.0)) for j in range(n * n) if rng.random() < 0.4]
rows.append(row or [(rng.randrange(n * n), 0.5)])
xt = [rng.uniform(0.5, 2.0) for _ in range(n * n)]
for j in rng.sample(range(n * n), zeros):
xt[j] = 0.0
b = [rng.uniform(0.2, 1.0) for _ in rows]
lam = forward(rows, xt)
y = [ik.poisson_sample(rng, 3.0 * (li + bi)) / 3.0 for li, bi in zip(lam, b)]
return rows, y, b
def _parabola(yi, bi, l, c, t):
return h(yi, bi, l) + h_prime(yi, bi, l) * (t - l) + c / 2 * (t - l) ** 2
def test_optimal_curvature_majorizes_and_is_tight() -> None:
rng = random.Random(3)
grid = [0.02 * k for k in range(1500)]
for _ in range(40):
yi, bi, l = rng.uniform(0.5, 20.0), rng.uniform(0.05, 3.0), rng.choice([0.0, rng.uniform(0.01, 25.0)])
c = optimal_curvature(yi, bi, l)
for t in grid:
assert _parabola(yi, bi, l, c, t) >= h(yi, bi, t) - 1e-9 * (1 + abs(h(yi, bi, t)))
if l > 0:
# tight: q(0) = h(0), so a smaller curvature fails at t = 0
assert abs(_parabola(yi, bi, l, c, 0.0) - h(yi, bi, 0.0)) < 1e-9 * (1 + abs(h(yi, bi, 0.0)))
assert _parabola(yi, bi, l, 0.99 * c, 0.0) < h(yi, bi, 0.0)
else:
assert c == yi / bi ** 2
assert optimal_curvature(0.0, 1.0, 5.0) == 0.0
def test_separable_surrogate_lies_above_the_cost() -> None:
rng = random.Random(4)
rows, y, b = _random_problem(rng, 3)
edges = [(j, k, rng.uniform(0.5, 2.0)) for j, k, _ in grid_edges(3)]
beta = 0.7
x = [rng.uniform(0.1, 3.0) for _ in range(9)]
lines = forward(rows, x)
curv = [optimal_curvature(yi, bi, li) for yi, bi, li in zip(y, b, lines)]
asum = [sum(w for _, w in row) for row in rows]
def surrogate(z):
# De Pierro split: [A z]_i = sum_j (a_ij / a_i) (a_i (z_j - x_j) + l_i)
total = 0.0
for row, yi, bi, li, ci, ai in zip(rows, y, b, lines, curv, asum):
total += sum(w / ai * _parabola(yi, bi, li, ci, ai * (z[j] - x[j]) + li) for j, w in row)
for j, k, w in edges:
m = x[j] + x[k]
total += beta * w / 2 * ((2 * z[j] - m) ** 2 + (2 * z[k] - m) ** 2) / 2
return total
assert abs(surrogate(x) - objective(rows, y, x, beta, edges, b)) < 1e-9
for _ in range(200):
z = [rng.uniform(0.0, 4.0) for _ in range(9)]
assert surrogate(z) >= objective(rows, y, z, beta, edges, b) - 1e-9
# one SPS step is the minimizer of the surrogate over z >= 0
x1 = sps(rows, 9, y, b, beta, edges, iters=1, x0=x)
s1 = surrogate(x1)
for _ in range(200):
z = [max(0.0, v + rng.gauss(0.0, 0.05)) for v in x1]
assert surrogate(z) >= s1 - 1e-9
def test_worked_example() -> None:
x1 = sps(ROWS5, 4, Y5, B5, iters=1, x0=[1.0] * 4)
for got, want in zip(x1, [1.1853137810, 1.2196311478, 1.2695473178, 1.2882658815]):
assert abs(got - want) < 1e-9
# these data are consistent: A x + b = y at x = (0.75, 1.75, 2.75, 3.75)
x = sps(ROWS5, 4, Y5, B5, iters=600, x0=[1.0] * 4)
assert max(abs(p - q) for p, q in zip(x, [0.75, 1.75, 2.75, 3.75])) < 1e-9
def test_cost_does_not_increase_on_a_phantom() -> None:
n = 12
rows = ik.parallel_beam_matrix(n, [math.pi * a / 10 for a in range(10)], 17)
xt = ik.flatten(ik.disk_phantom(n, 0.6))
rows = [[(j, 50.0 * w) for j, w in row] for row in rows]
b = [1.0] * len(rows)
rng = random.Random(7)
y = [ik.poisson_sample(rng, li + 1.0) for li in forward(rows, xt)]
edges = grid_edges(n)
for beta in (0.0, 20.0):
costs = []
sps(rows, n * n, y, b, beta, edges, iters=60,
callback=lambda k, x: costs.append((objective(rows, y, x, beta, edges, b), min(x))))
assert all(m >= 0.0 for _, m in costs)
assert all(q <= p + 1e-9 * abs(p) for (p, _), (q, _) in zip(costs, costs[1:]))
def test_limit_satisfies_the_kkt_conditions() -> None:
rng = random.Random(5)
rows, y, b = _random_problem(rng, 3, zeros=4)
edges = grid_edges(3)
beta = 0.3
x = sps(rows, 9, y, b, beta, edges, iters=3000)
g = gradient(rows, y, x, beta, edges, b)
assert any(v == 0.0 for v in x)
for xj, gj in zip(x, g):
if xj > 0:
assert abs(gj) < 1e-7
else:
assert gj > -1e-7
def test_gradient_by_finite_differences() -> None:
rng = random.Random(1)
rows, y, b = _random_problem(rng, 3)
edges = [(j, k, rng.uniform(0.5, 2.0)) for j, k, _ in grid_edges(3)]
x = [rng.uniform(0.2, 3.0) for _ in range(9)]
g = gradient(rows, y, x, 0.8, edges, b)
eps = 1e-6
for j in range(9):
xp, xm = list(x), list(x)
xp[j] += eps
xm[j] -= eps
fd = (objective(rows, y, xp, 0.8, edges, b) - objective(rows, y, xm, 0.8, edges, b)) / (2 * eps)
assert abs(fd - g[j]) < 1e-5 * (1 + abs(g[j]))
assert penalty([1.0, 3.0], [(0, 1, 2.0)]) == 4.0
def test_counts_without_background_are_rejected() -> None:
try:
sps(ROWS5, 4, Y5, [0.0] * 5, iters=1)
except ValueError:
return
raise AssertionError("expected ValueError")
def test_projector_adjoint() -> None:
rng = random.Random(2)
rows = ik.parallel_beam_matrix(8, [math.pi * a / 6 for a in range(6)], 11)
x = [rng.gauss(0.0, 1.0) for _ in range(64)]
v = [rng.gauss(0.0, 1.0) for _ in range(len(rows))]
ax, atv = forward(rows, x), back(rows, v, 64)
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))
History
De Pierro (1995) found that the convexity of the penalty lets one split it into one-pixel terms, which gave a monotone EM method for penalized likelihood in emission tomography. Erdogan and Fessler (1999) used quadratic surrogates for the transmission log-likelihood, found the optimal curvature, combined it with De Pierro's split and got the SPS method; they also gave ordered subsets forms. Fessler and Erdogan (1998) applied paraboloidal surrogates to emission data with a background.
References
- H. Erdogan and J. A. Fessler, Monotonic algorithms for transmission tomography, IEEE Transactions on Medical Imaging 18(9), 1999, pp. 801 to 814 (paraboloidal surrogates for the transmission log-likelihood, the optimal curvature, and the separable SPS update)
- H. Erdogan and J. A. Fessler, Ordered subsets algorithms for transmission tomography, Physics in Medicine and Biology 44(11), 1999, pp. 2835 to 2851 (ordered subsets with precomputed curvatures)
- J. A. Fessler and H. Erdogan, A paraboloidal surrogates algorithm for convergent penalized-likelihood emission image reconstruction, IEEE Nuclear Science Symposium Conference Record, vol. 2, 1998, pp. 1132 to 1135 (paraboloidal surrogates for emission data with a background)
- A. R. De Pierro, A modified expectation maximization algorithm for penalized likelihood estimation in emission tomography, IEEE Transactions on Medical Imaging 14(1), 1995, pp. 132 to 137 (the convexity split that makes a surrogate separable)
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 DG54BX Edit this page History Report an error Markdown