Algorithmresearch
Adaptive steepest descent POCS
Also called ASD-POCS.
Reconstruct sparse-view CT by alternating projections onto the data and positivity constraints with steepest descent steps on total variation.
- Time
- O(K (a d n + g n^2)) totalO(a d n + g n^2) 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; g = the number of TV steps per iteration; n = the side of the n x n image
- Model
- Real RAM
- Properties
- deterministicheuristiciterativenot linear in data
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Emil Y. Sidky, Xiaochuan Pan, 2008
ASD-POCS reconstructs a CT image from few projection angles by looking for an image with a small total variation that fits the data within a tolerance and has no negative values. It alternates two kinds of steps. A data step is one sweep of ART over all rays followed by clipping at zero, as in the method of projections onto convex sets (POCS). A TV step is a short run of normalized steepest descent steps on the total variation. The name means adaptive steepest descent POCS: the length of the TV steps adapts to the size of the change made by the data steps, so that the TV steps do not undo the data fit. The target is the constrained problem
ASD-POCS is a heuristic. It has no convergence proof, and its result depends on five tuning parameters. Its value is that it works well in practice on piecewise constant objects with few views, where SART, SIRT and filtered back-projection give streaks.
In plain words
With few projection angles, many images fit the data, and the plain algebraic methods pick one with streaks. Most real objects are made of regions of nearly constant value. Such images have a small total variation: the sum over all pixels of the local jump in value. So among the images that fit the data, pick one with small total variation.
ASD-POCS does this by turns. It pulls the image toward the data with one ART sweep and sets negative values to zero. Then it pushes the image toward smaller total variation with a few steepest descent steps. If the push is stronger than the pull, the image drifts away from the data. So after each round, ASD-POCS compares the two, and if the push was larger, it makes the next push smaller. The ART steps also get smaller over time, so that both settle down together.
The problem
Given a nonnegative system matrix for an image (), data with often much smaller than , and a tolerance , find an image with and a small value of
with forward differences that are 0 at the last row and the last column, and a small that makes the function differentiable. The constrained problem is convex. ASD-POCS does not solve it exactly; it looks for a point that is close to feasible and has a small TV value. See sparse-view CT reconstruction for the problem and other methods.
The algorithm
ASD-POCS(A, y, ε, K; β, β_red, g, α, α_red, r_max)- 1
x ← 0; dtvg ← undefined - 2
for k ← 1 to K do - 3
x0 ← x; for each ray i: x ← x + β a_i (y_i - ⟨a_i, x⟩) / ‖a_i‖² ▷ one ART sweep - 4
x ← max(x, 0); x_res ← x ▷ positivity - 5
dd ← ‖A x - y‖; dp ← ‖x - x0‖; if k = 1 then dtvg ← α dp - 6
x1 ← x; repeat g times: v ← ∇TV(x); x ← x - dtvg v / ‖v‖ ▷ TV steps - 7
dg ← ‖x - x1‖; if dg > r_max dp and dd > ε then dtvg ← α_red dtvg - 8
β ← β_red β - 9
return x_res
Line L3 projects the image in turn onto the hyperplane of each ray, relaxed by . Line L4 projects onto the nonnegative orthant. Line L5 measures the data misfit and the change made by the data steps, and the first change fixes the scale of the TV step length. Line L6 takes steps of length along the normalized negative TV gradient, so each step moves the image by exactly . Line L7 is the adaptive rule: if the TV steps moved the image more than times as far as the data steps did, and the data are not yet fit, shorten the TV steps. Line L8 shrinks the ART relaxation. The code returns the image after the data steps of the last iteration, whose misfit was measured. The defaults of the code are , , , , and .
Example
The worked case of the tests: a phantom of three ellipses with the values 0, 0.5, 1 and 1.5 (its TV is 49.3), 6 angles in with 23 bins each, so 138 rays for 256 pixels, the pixel-driven matrix of the shared helper, exact data, and . All numbers are measurements of this setup. The relative error after iterations:
| method | ||||
|---|---|---|---|---|
| ART with positivity () | 0.087 | 0.068 | 0.068 | 0.067 |
| ASD-POCS, defaults | 0.185 | 0.071 | 0.045 | 0.039 |
| ASD-POCS, , | 0.124 | 0.050 | 0.037 |
ART alone converges to an image that fits the data but keeps the error of the null space of . ASD-POCS starts slower, because the early TV steps pull away from the data, and then goes past ART. The TV of the result is 48.3 with the defaults after 1000 iterations, against 51.3 for ART. The final misfit is 0.015 with the defaults, above , because the ART relaxation has decayed to and the data steps are weak. The second parameter set reaches a smaller error sooner. Both facts show that the parameters matter.
A small exact case: without TV steps () and with , the method is ART with positivity. On the image with the rays of the two rows, the two columns and the two diagonals, the first ART step on row 0 sets , the step on row 1 sets , and 200 sweeps reach the true image to .
Correctness
There is no convergence theorem for ASD-POCS. What can be said:
- The data steps (theorem). Without lines L6 and L7, and with fixed, line L3 is the Kaczmarz method and line L4 a projection onto a convex set. For consistent data with a nonnegative solution, this cyclic projection scheme converges to a point of the intersection of the hyperplanes and the orthant (the theory of convex feasibility by successive projections). The test with checks this on a small system.
- The TV steps (theorem). is convex and differentiable for , and the code computes its exact gradient (a test compares it with finite differences). A short enough step along the negative gradient lowers TV. Line L6 uses a fixed length per step, not a line search, so a single step can raise TV.
- The combination (heuristic). The adaptive rule of line L7 keeps the TV steps from growing larger than the data steps while the misfit is above . Sidky and Pan argued that near a solution of the constrained problem, the TV gradient and the gradient of the data constraint point in opposite directions, and they used the cosine of their angle as a check. This is a necessary condition for optimality, not a proof that the iterates reach it.
So the output is an image that fits the data roughly and has a smaller TV than the ART image; neither the misfit bound nor TV optimality is guaranteed. Methods with a proof for the same constrained problem exist: the Chambolle-Pock algorithm solves it with known convergence, as Sidky, Jorgensen and Pan showed in 2012. The file proofs/correctness.md proves the two theorem parts above.
Proof: What can be proved about ASD-POCSpartial
ASD-POCS as a whole has no convergence proof, and we give none. We prove the two parts that the page states as theorems: the data steps alone converge on consistent data, and line L6 uses the exact gradient of a convex function, so short steps along it lower the total variation. We also prove two small facts about lines L6 and L7. We work in exact arithmetic in with the Euclidean norm.
Part 1: the data steps
Let for each ray with , and . The projection onto is , and the projection onto clips at 0. So with and a fixed (), line L3 applies for each ray in turn, and line L4 applies .
Lemma 1 (Fejer steps). Let and . Then
Proof. The vector is a multiple of , and is orthogonal to because both and lie in . Write and , so . Then . For the closed convex set , the projection satisfies , so .
Theorem 1. Let be nonempty (consistent data with a nonnegative solution), fixed and . Then the iterates of ASD-POCS converge to a point of .
Proof. List all sub-steps (one per ray, then the clipping) as one sequence . By Lemma 1, does not increase for each , so the sequence is bounded, and summing the decreases gives , so the step lengths tend to 0. Let be a cluster point of the sweep starts , along a subsequence . The sweep has a fixed finite number of sub-steps, each of length tending to 0, so all sub-iterates of sweep tend to too. The sub-step for ray moves by , and the clipping moves by . These tend to 0, and the distance functions are continuous, so for every and . The sets are closed, so . Now apply the monotonicity with : does not increase and has a subsequence tending to 0, so the whole sequence tends to . The code returns , a member of this sequence, so it converges to as well.
With the relaxation tends to 0 and is summable, so Theorem 1 does not apply. The example of the page shows the misfit leveling off above in that case.
Part 2: the TV steps
For , index , put if and 0 otherwise, if and 0 otherwise, and . Then .
Lemma 2 (convexity). For , is convex. For it is differentiable everywhere.
Proof. The map is affine, and is the Euclidean norm of its value. A norm composed with an affine map is convex, and a sum of convex functions is convex. For , the norm is evaluated away from the origin, where it is differentiable.
Lemma 3 (the gradient). For , tv_grad returns .
Proof. The term depends on , on when , and on when . By the chain rule, , and , where a difference that is fixed at 0 contributes nothing. The code adds exactly these terms for each , and the gradient of a sum is the sum of the gradients.
Proposition 4 (descent for short steps). If , then for all small enough .
Proof. The directional derivative of at along is .
Line L6 uses the fixed length , not a line search, so this proposition does not imply that each step of line L6 lowers TV.
Part 3: two facts about lines L6 and L7
Proposition 5. Each step of line L6 moves the image by exactly , and .
Proof. The step is , a vector of length . The total change is the sum of such vectors, and the triangle inequality bounds its length. (The code stops early if , which only shortens the sum.)
Proposition 6. The TV step length never increases, and it decreases by the factor in each iteration in which and .
Proof. Line L7 is the only line that changes after the first iteration, and it multiplies it by under exactly this condition.
These facts bound the TV steps; they do not show that the iterates converge or that the limit, if any, solves the constrained TV problem.
Complexity
In the real-RAM model, with angles of bins, an image and a ray-driven matrix with nonzero entries per ray:
- Line L3 reads each nonzero entry twice per ray, time.
- Lines L4, L5 and L7 take time, plus for the product in line L5.
- Line L6 computes TV gradients, each in time.
So one iteration costs time and extra space, and iterations cost . With few views, is small, and the TV steps can dominate. The number of iterations needed is not bounded by any theorem; published uses run hundreds to thousands of iterations.
Properties
- Heuristic. No convergence proof, and no guarantee that the result is feasible or TV-minimal.
- Five parameters. , , , and , plus . In the example, two parameter sets differ in error by a factor of 1.4 to 1.5 at a fixed iteration count (a measurement).
- Matrix free. It needs only the action of single rows of and the TV gradient, so it works with any projector, including cone-beam projectors that compute rows on the fly.
- Nonlinear in the data. The clipping and the normalized TV steps make the output a nonlinear function of , unlike SIRT.
- Strong prior. It favors piecewise constant images. Smooth gradients in the object turn into flat regions with steps, the staircase effect of TV.
Variants and improvements
- TV-POCS. The earlier method of Sidky, Kao and Pan (2006) used the same two kinds of steps with fixed step lengths.
- SART or SIRT data steps. Line L3 can be any data step: a SART sweep, a SIRT iteration, or ordered subsets. The method is often run on GPUs with SART.
- Other priors. Replace TV with total generalized variation to reduce the staircase effect, or with a weighted TV that penalizes some directions less.
- Primal-dual methods. The Chambolle-Pock algorithm and ADMM solve the same constrained TV problem, or its penalized form, with a convergence proof and fewer parameters.
- Learned methods. Unrolled networks such as learned primal-dual learn the steps from training data.
When to use it
Use ASD-POCS for sparse-view or limited-angle CT of objects that are close to piecewise constant, when a simple code built on an existing ART or SART loop is wanted. Use a primal-dual method when convergence to the solution of the convex problem matters, for example to compare priors or to study the number of views needed. Do not use it for objects with fine texture or smooth gradients, where TV erases detail, and do not use it when many views are available: there filtered back-projection or SIRT are cheaper and the prior adds little.
Pitfalls
- Treating it as a solver. The output is not the solution of the constrained TV problem. Check the misfit and the TV value; do not report them as optimal.
- The tolerance . With noisy data, must be close to the noise norm. A smaller value overfits noise, and a larger value over-smooths. With exact data, a tiny only means that the rule of line L7 keeps shrinking the TV steps.
- Decay of . With , the data steps vanish over time. After many iterations the misfit stops falling, as in the example.
- No stopping rule from theory. Nothing tells when the iterates are good enough. Record the misfit and the TV value over the iterations, and stop when both have leveled off.
- The smoothing . With the gradient is not defined at flat regions. Use a small , or a subgradient with care.
Implementations
The Python code takes the sparse rows of as (column, weight) pairs, for example from the shared helper imgkit.parallel_beam_matrix, and an image as a row-major vector. It has the TV function and its exact gradient, the residual norm, and the main loop with the six parameters. The tests check two TV values, the gradient against central differences, the reduction to ART with positivity for (with the first ART steps by hand), the sparse-view phantom of the example against ART, and positivity with noisy data.
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
# Part of https://algorithm.tamnd.com/asd-pocs/. The authors are listed in prov/4RF9RF.jsonl.
"""ASD-POCS: adaptive steepest descent on total variation, alternated with
projections onto the data and positivity constraints (Sidky and Pan, 2008).
The image is a row-major vector of an n x n image. The system matrix A is
given as sparse rows of (column, weight) pairs, as returned by
imgkit.parallel_beam_matrix. The aim is a small total variation under the
constraints ||A x - y|| <= eps and x >= 0. The method is a heuristic: it has
no convergence proof.
"""
import math
def tv(x, n, eta=1e-8):
"""The smoothed isotropic total variation sum sqrt(dx^2 + dy^2 + eta^2).
dx and dy are forward differences down the rows and along the columns,
with a zero difference at the last row and the last column.
"""
total = 0.0
for i in range(n):
for j in range(n):
p = x[i * n + j]
dx = x[(i + 1) * n + j] - p if i + 1 < n else 0.0
dy = x[i * n + j + 1] - p if j + 1 < n else 0.0
total += math.sqrt(dx * dx + dy * dy + eta * eta)
return total
def tv_grad(x, n, eta=1e-8):
"""The exact gradient of tv(x, n, eta)."""
g = [0.0] * (n * n)
for i in range(n):
for j in range(n):
k = i * n + j
p = x[k]
dx = x[k + n] - p if i + 1 < n else 0.0
dy = x[k + 1] - p if j + 1 < n else 0.0
s = math.sqrt(dx * dx + dy * dy + eta * eta)
if i + 1 < n:
g[k + n] += dx / s
g[k] -= dx / s
if j + 1 < n:
g[k + 1] += dy / s
g[k] -= dy / s
return g
def _norm(v):
return math.sqrt(sum(t * t for t in v))
def residual_norm(rows, y, x):
"""||A x - y||."""
return _norm([sum(w * x[j] for j, w in row) - yi for row, yi in zip(rows, y)])
def asd_pocs(rows, n, y, eps, iters=100, beta=1.0, beta_red=0.995, ng=20, alpha=0.2,
alpha_red=0.95, r_max=0.95, eta=1e-8, callback=None):
"""Run ASD-POCS and return the image after the data and positivity steps
of the last iteration.
eps: the allowed data misfit ||A x - y||; beta, beta_red: the ART
relaxation and its factor per iteration; ng: the number of TV steps per
iteration (ng = 0 gives plain ART with positivity); alpha: the first TV
step length as a fraction of the change made by the data steps; alpha_red
and r_max: the adaptive rule for the TV step length. callback(k, x, dd)
is called after the data steps of iteration k, with dd = ||A x - y||.
"""
norms = [sum(w * w for _, w in row) for row in rows]
x = [0.0] * (n * n) # @line L1
dtvg = None
xres = x
for k in range(iters): # @line L2
x0 = list(x)
for row, yi, ai in zip(rows, y, norms): # @line L3
if ai > 0:
t = beta * (yi - sum(w * x[j] for j, w in row)) / ai
for j, w in row:
x[j] += t * w
x = [t if t > 0 else 0.0 for t in x] # @line L4
xres = list(x)
dd = residual_norm(rows, y, x) # @line L5
dp = _norm([a - b for a, b in zip(x, x0)])
if dtvg is None:
dtvg = alpha * dp
if callback is not None:
callback(k + 1, xres, dd)
x1 = list(x)
for _ in range(ng): # @line L6
g = tv_grad(x, n, eta)
gn = _norm(g)
if gn == 0.0:
break
x = [a - dtvg * b / gn for a, b in zip(x, g)]
dg = _norm([a - b for a, b in zip(x, x1)]) # @line L7
if dg > r_max * dp and dd > eps:
dtvg *= alpha_red
beta *= beta_red # @line L8
return xres # @line L9
imgkit.py 322 lines
# 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
test_asd_pocs.py 80 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/asd-pocs/. The authors are listed in prov/4RF9RF.jsonl.
import math
import random
import imgkit as ik
from asd_pocs import asd_pocs, residual_norm, tv, tv_grad
# Three ellipses, values 0, 0.5, 1 and 1.5: a piecewise constant phantom.
TABLE = [
(1.0, 0.7, 0.5, 0.0, 0.0, 0.0),
(0.5, 0.25, 0.25, 0.25, 0.1, 0.0),
(-0.5, 0.15, 0.3, -0.3, -0.05, 0.0),
]
def test_tv_values() -> None:
n = 4
assert abs(tv([2.0] * (n * n), n, eta=0.5) - n * n * 0.5) < 1e-12
# left half 0, right half 1: one unit jump in each row
step = [0.0 if j < n // 2 else 1.0 for i in range(n) for j in range(n)]
assert abs(tv(step, n, eta=1e-12) - n) < 1e-9
def test_tv_gradient_matches_finite_differences() -> None:
rng = random.Random(1)
n, eta, h = 5, 0.1, 1e-6
x = [rng.uniform(0, 1) for _ in range(n * n)]
g = tv_grad(x, n, eta)
for k in range(n * n):
xp, xm = list(x), list(x)
xp[k] += h
xm[k] -= h
fd = (tv(xp, n, eta) - tv(xm, n, eta)) / (2 * h)
assert abs(fd - g[k]) < 1e-6
def test_without_tv_steps_it_is_art_with_positivity() -> None:
# a consistent 2 x 2 system: rows, columns and the two diagonals
rows = [
[(0, 1.0), (1, 1.0)], [(2, 1.0), (3, 1.0)], [(0, 1.0), (2, 1.0)],
[(1, 1.0), (3, 1.0)], [(0, 1.0), (3, 1.0)], [(1, 1.0), (2, 1.0)],
]
xt = [1.0, 2.0, 3.0, 5.0]
y = [sum(w * xt[j] for j, w in row) for row in rows]
x = asd_pocs(rows, 2, y, eps=0.0, iters=200, beta_red=1.0, ng=0)
assert max(abs(a - b) for a, b in zip(x, xt)) < 1e-9
# one sweep by hand: the first ray sets x0 = x1 = 3/2, the second x2 = x3 = 4, ...
seen = []
asd_pocs(rows[:2], 2, y[:2], eps=0.0, iters=1, ng=0, callback=lambda k, x, dd: seen.append(x))
assert seen[0] == [1.5, 1.5, 4.0, 4.0]
def test_sparse_view_phantom_beats_art() -> None:
n, nbins, na, iters = 16, 23, 6, 200
rows = ik.parallel_beam_matrix(n, [k * math.pi / na for k in range(na)], nbins)
xt = ik.flatten(ik.ellipse_phantom(n, TABLE))
y = ik.sp_matvec(rows, xt)
eps = 1e-3 * math.sqrt(sum(t * t for t in y))
nt = math.sqrt(sum(t * t for t in xt))
art = asd_pocs(rows, n, y, eps, iters=iters, ng=0)
tvr = asd_pocs(rows, n, y, eps, iters=iters, ng=10, alpha=0.05)
e_art = math.dist(art, xt) / nt
e_tv = math.dist(tvr, xt) / nt
# measured: 0.068 for ART and 0.050 for ASD-POCS
assert e_tv < 0.8 * e_art
assert tv(tvr, n) < tv(art, n)
assert min(tvr) >= 0.0
assert residual_norm(rows, y, tvr) < 0.05
def test_positivity_holds_with_noisy_data() -> None:
n, nbins, na = 8, 13, 4
rows = ik.parallel_beam_matrix(n, [k * math.pi / na for k in range(na)], nbins)
rng = random.Random(2)
xt = ik.flatten(ik.disk_phantom(n, 0.5))
y = [t + rng.gauss(0.0, 0.05) for t in ik.sp_matvec(rows, xt)]
x = asd_pocs(rows, n, y, eps=0.05 * math.sqrt(len(y)), iters=30)
assert min(x) >= 0.0
History
Rudin, Osher and Fatemi introduced total variation as an image prior for denoising in 1992. In 2006, Candes, Romberg and Tao showed that a piecewise constant image can be recovered exactly from few Fourier samples by TV minimization, which started compressed sensing and suggested that CT could use far fewer views. In the same year, Sidky, Kao and Pan proposed TV-POCS for few-view and limited-angle fan-beam and cone-beam CT. In 2008 Sidky and Pan published ASD-POCS, with adaptive step lengths, for circular cone-beam CT. It became a standard reference method for sparse-view CT. In 2012 Sidky, Jorgensen and Pan showed how to solve the same convex problems with the Chambolle-Pock algorithm, which has a convergence proof.
References
- Emil Y. Sidky and Xiaochuan Pan, Image reconstruction in circular cone-beam computed tomography by constrained, total-variation minimization, Physics in Medicine and Biology 53(17), 2008, the ASD-POCS algorithm, its adaptive step rules and its use in few-view cone-beam CT (general locator)
- E. Y. Sidky, C.-M. Kao and X. Pan, Accurate image reconstruction from few-views and limited-angle data in divergent-beam CT, Journal of X-Ray Science and Technology 14(2), 2006, 119 to 139, the earlier TV-POCS method with fixed steps (general locator)
- Emil Y. Sidky, Jakob H. Jorgensen and Xiaochuan Pan, Convex optimization problem prototyping for image reconstruction in computed tomography with the Chambolle-Pock algorithm, Physics in Medicine and Biology 57(10), 2012, solving the same constrained TV problem with a primal-dual method that has a convergence proof (general locator)
- Emmanuel J. Candes, Justin Romberg and Terence Tao, Robust uncertainty principles, exact signal reconstruction from highly incomplete frequency information, IEEE Transactions on Information Theory 52(2), 2006, exact recovery of piecewise constant images from few Fourier samples by TV minimization (general locator)
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 4RF9RF Edit this page History Report an error Markdown