Algorithm Search⌘K

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
Properties
deterministicheuristiciterativenot linear in data
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

min⁡xTV⁡(x)subject to∥Ax−y∥≤ε, x≥0.\min_x \operatorname{TV}(x) \quad\text{subject to}\quad \|A x - y\| \le \varepsilon,\ x \ge 0.

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 m×Nm \times N system matrix AA for an n×nn \times n image (N=n2N = n^2), data y∈Rmy \in \mathbb{R}^m with mm often much smaller than NN, and a tolerance ε≥0\varepsilon \ge 0, find an image x≥0x \ge 0 with ∥Ax−y∥≤ε\|A x - y\| \le \varepsilon and a small value of

TV⁡η(x)=∑i,j(xi+1,j−xi,j)2+(xi,j+1−xi,j)2+η2,\operatorname{TV}_\eta(x) = \sum_{i,j} \sqrt{(x_{i+1,j} - x_{i,j})^2 + (x_{i,j+1} - x_{i,j})^2 + \eta^2},

with forward differences that are 0 at the last row and the last column, and a small η>0\eta > 0 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

  1. ASD-POCS(A, y, ε, K; β, β_red, g, α, α_red, r_max)
  2. 1x ← 0; dtvg ← undefined
  3. 2for k ← 1 to K do
  4. 3x0 ← x; for each ray i: x ← x + β a_i (y_i - ⟨a_i, x⟩) / ‖a_i‖² ▷ one ART sweep
  5. 4x ← max(x, 0); x_res ← x ▷ positivity
  6. 5dd ← ‖A x - y‖; dp ← ‖x - x0‖; if k = 1 then dtvg ← α dp
  7. 6x1 ← x; repeat g times: v ← ∇TV(x); x ← x - dtvg v / ‖v‖ ▷ TV steps
  8. 7dg ← ‖x - x1‖; if dg > r_max dp and dd > ε then dtvg ← α_red dtvg
  9. 8β ← β_red β
  10. 9return x_res

Line L3 projects the image in turn onto the hyperplane of each ray, relaxed by β\beta. Line L4 projects onto the nonnegative orthant. Line L5 measures the data misfit dddd and the change dpdp made by the data steps, and the first change fixes the scale of the TV step length. Line L6 takes gg steps of length dtvgdtvg along the normalized negative TV gradient, so each step moves the image by exactly dtvgdtvg. Line L7 is the adaptive rule: if the TV steps moved the image more than rmax⁡r_{\max} 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 dddd was measured. The defaults of the code are β=1\beta = 1, βred=0.995\beta_{\text{red}} = 0.995, g=20g = 20, α=0.2\alpha = 0.2, αred=0.95\alpha_{\text{red}} = 0.95 and rmax⁡=0.95r_{\max} = 0.95.

Example

The worked case of the tests: a 16×1616 \times 16 phantom of three ellipses with the values 0, 0.5, 1 and 1.5 (its TV is 49.3), 6 angles in [0,π)[0, \pi) with 23 bins each, so 138 rays for 256 pixels, the pixel-driven matrix of the shared helper, exact data, and ε=10−3∥y∥=0.0077\varepsilon = 10^{-3}\|y\| = 0.0077. All numbers are measurements of this setup. The relative error ∥x−xtrue∥/∥xtrue∥\|x - x_{\text{true}}\| / \|x_{\text{true}}\| after kk iterations:

method k=50k = 50 k=200k = 200 k=400k = 400 k=1000k = 1000
ART with positivity (g=0g = 0) 0.087 0.068 0.068 0.067
ASD-POCS, defaults 0.185 0.071 0.045 0.039
ASD-POCS, g=10g = 10, α=0.05\alpha = 0.05 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 AA. 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 ε\varepsilon, because the ART relaxation β\beta has decayed to 0.9951000≈0.0070.995^{1000} \approx 0.007 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 (g=0g = 0) and with βred=1\beta_{\text{red}} = 1, the method is ART with positivity. On the 2×22 \times 2 image (1,2,3,5)(1, 2, 3, 5) with the rays of the two rows, the two columns and the two diagonals, the first ART step on row 0 sets x0=x1=3/2x_0 = x_1 = 3/2, the step on row 1 sets x2=x3=4x_2 = x_3 = 4, and 200 sweeps reach the true image to 10−910^{-9}.

Correctness

There is no convergence theorem for ASD-POCS. What can be said:

  • The data steps (theorem). Without lines L6 and L7, and with 0<β<20 < \beta < 2 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 g=0g = 0 checks this on a small system.
  • The TV steps (theorem). TV⁡η\operatorname{TV}_\eta is convex and differentiable for η>0\eta > 0, 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 ε\varepsilon. 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 ε\varepsilon 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 RN\mathbb{R}^N with the Euclidean norm.

Part 1: the data steps

Let Hi={x:⟨ai,x⟩=yi}H_i = \{x : \langle a_i, x\rangle = y_i\} for each ray ii with ai≠0a_i \ne 0, and Q={x:x≥0}Q = \{x : x \ge 0\}. The projection onto HiH_i is Pix=x+yi−⟨ai,x⟩∥ai∥2aiP_i x = x + \frac{y_i - \langle a_i, x\rangle}{\|a_i\|^2} a_i, and the projection onto QQ clips at 0. So with g=0g = 0 and a fixed β\beta (βred=1\beta_{\text{red}} = 1), line L3 applies x←x+β(Pix−x)x \leftarrow x + \beta(P_i x - x) for each ray in turn, and line L4 applies PQP_Q.

Lemma 1 (Fejer steps). Let p∈S=Q∩⋂iHip \in S = Q \cap \bigcap_i H_i and 0<β<20 < \beta < 2. Then

∥x+β(Pix−x)−p∥2=∥x−p∥2−β(2−β)∥Pix−x∥2,∥PQx−p∥2≤∥x−p∥2−∥PQx−x∥2.\|x + \beta(P_i x - x) - p\|^2 = \|x - p\|^2 - \beta(2 - \beta)\|P_i x - x\|^2, \qquad \|P_Q x - p\|^2 \le \|x - p\|^2 - \|P_Q x - x\|^2.

Proof. The vector Pix−xP_i x - x is a multiple of aia_i, and x−Pixx - P_i x is orthogonal to Pix−pP_i x - p because both PixP_i x and pp lie in HiH_i. Write u=x−pu = x - p and s=Pix−xs = P_i x - x, so ⟨u,s⟩=⟨Pix−p,s⟩−∥s∥2=−∥s∥2\langle u, s\rangle = \langle P_i x - p, s\rangle - \|s\|^2 = -\|s\|^2. Then ∥u+βs∥2=∥u∥2+2β⟨u,s⟩+β2∥s∥2=∥u∥2−(2β−β2)∥s∥2\|u + \beta s\|^2 = \|u\|^2 + 2\beta\langle u, s\rangle + \beta^2\|s\|^2 = \|u\|^2 - (2\beta - \beta^2)\|s\|^2. For the closed convex set QQ, the projection satisfies ⟨x−PQx,p−PQx⟩≤0\langle x - P_Q x, p - P_Q x\rangle \le 0, so ∥x−p∥2=∥x−PQx∥2+∥PQx−p∥2+2⟨x−PQx,PQx−p⟩≥∥x−PQx∥2+∥PQx−p∥2\|x - p\|^2 = \|x - P_Q x\|^2 + \|P_Q x - p\|^2 + 2\langle x - P_Q x, P_Q x - p\rangle \ge \|x - P_Q x\|^2 + \|P_Q x - p\|^2. □\square

Theorem 1. Let SS be nonempty (consistent data with a nonnegative solution), 0<β<20 < \beta < 2 fixed and g=0g = 0. Then the iterates of ASD-POCS converge to a point of SS.

Proof. List all sub-steps (one per ray, then the clipping) as one sequence u0,u1,u2,…u_0, u_1, u_2, \dots. By Lemma 1, ∥ut−p∥\|u_t - p\| does not increase for each p∈Sp \in S, so the sequence is bounded, and summing the decreases gives ∑t∥ut+1−ut∥2<∞\sum_t \|u_{t+1} - u_t\|^2 < \infty, so the step lengths tend to 0. Let x∗x^* be a cluster point of the sweep starts xkx_k, along a subsequence klk_l. The sweep has a fixed finite number of sub-steps, each of length tending to 0, so all sub-iterates of sweep klk_l tend to x∗x^* too. The sub-step for ray ii moves uu by β dist(u,Hi)\beta\,\mathrm{dist}(u, H_i), and the clipping moves uu by dist(u,Q)\mathrm{dist}(u, Q). These tend to 0, and the distance functions are continuous, so dist(x∗,Hi)=0\mathrm{dist}(x^*, H_i) = 0 for every ii and dist(x∗,Q)=0\mathrm{dist}(x^*, Q) = 0. The sets are closed, so x∗∈Sx^* \in S. Now apply the monotonicity with p=x∗p = x^*: ∥ut−x∗∥\|u_t - x^*\| does not increase and has a subsequence tending to 0, so the whole sequence tends to x∗x^*. The code returns xresx_{\text{res}}, a member of this sequence, so it converges to x∗x^* as well. □\square

With βred<1\beta_{\text{red}} < 1 the relaxation βk=β βredk\beta_k = \beta\,\beta_{\text{red}}^k tends to 0 and is summable, so Theorem 1 does not apply. The example of the page shows the misfit leveling off above ε\varepsilon in that case.

Part 2: the TV steps

For x∈Rn×nx \in \mathbb{R}^{n \times n}, index k=in+jk = i n + j, put δkx=xk+n−xk\delta^x_k = x_{k+n} - x_k if i+1<ni + 1 < n and 0 otherwise, δky=xk+1−xk\delta^y_k = x_{k+1} - x_k if j+1<nj + 1 < n and 0 otherwise, and sk=(δkx)2+(δky)2+η2s_k = \sqrt{(\delta^x_k)^2 + (\delta^y_k)^2 + \eta^2}. Then TV⁡η(x)=∑ksk\operatorname{TV}_\eta(x) = \sum_k s_k.

Lemma 2 (convexity). For η≥0\eta \ge 0, TV⁡η\operatorname{TV}_\eta is convex. For η>0\eta > 0 it is differentiable everywhere.

Proof. The map x↦(δkx,δky,η)x \mapsto (\delta^x_k, \delta^y_k, \eta) is affine, and sks_k 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 η>0\eta > 0, the norm is evaluated away from the origin, where it is differentiable. □\square

Lemma 3 (the gradient). For η>0\eta > 0, tv_grad returns ∇TV⁡η(x)\nabla \operatorname{TV}_\eta(x).

Proof. The term sks_k depends on xkx_k, on xk+nx_{k+n} when i+1<ni + 1 < n, and on xk+1x_{k+1} when j+1<nj + 1 < n. By the chain rule, ∂sk/∂xk+n=δkx/sk\partial s_k / \partial x_{k+n} = \delta^x_k / s_k, ∂sk/∂xk+1=δky/sk\partial s_k / \partial x_{k+1} = \delta^y_k / s_k and ∂sk/∂xk=−(δkx+δky)/sk\partial s_k / \partial x_k = -(\delta^x_k + \delta^y_k)/s_k, where a difference that is fixed at 0 contributes nothing. The code adds exactly these terms for each kk, and the gradient of a sum is the sum of the gradients. □\square

Proposition 4 (descent for short steps). If v=∇TV⁡η(x)≠0v = \nabla \operatorname{TV}_\eta(x) \ne 0, then TV⁡η(x−tv/∥v∥)<TV⁡η(x)\operatorname{TV}_\eta(x - t v/\|v\|) < \operatorname{TV}_\eta(x) for all small enough t>0t > 0.

Proof. The directional derivative of TV⁡η\operatorname{TV}_\eta at xx along −v/∥v∥-v/\|v\| is −⟨v,v⟩/∥v∥=−∥v∥<0-\langle v, v\rangle / \|v\| = -\|v\| < 0. □\square

Line L6 uses the fixed length dtvgdtvg, 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 dtvgdtvg, and dg≤g⋅dtvgdg \le g \cdot dtvg.

Proof. The step is −dtvg⋅v/∥v∥-dtvg \cdot v/\|v\|, a vector of length dtvgdtvg. The total change x−x1x - x_1 is the sum of gg such vectors, and the triangle inequality bounds its length. (The code stops early if v=0v = 0, which only shortens the sum.) □\square

Proposition 6. The TV step length dtvgdtvg never increases, and it decreases by the factor αred\alpha_{\text{red}} in each iteration in which dg>rmax⁡ dpdg > r_{\max}\, dp and dd>εdd > \varepsilon.

Proof. Line L7 is the only line that changes dtvgdtvg after the first iteration, and it multiplies it by αred<1\alpha_{\text{red}} < 1 under exactly this condition. □\square

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 aa angles of dd bins, an n×nn \times n image and a ray-driven matrix with O(n)O(n) nonzero entries per ray:

  • Line L3 reads each nonzero entry twice per ray, O(adn)O(a d n) time.
  • Lines L4, L5 and L7 take O(n2)O(n^2) time, plus O(adn)O(a d n) for the product AxA x in line L5.
  • Line L6 computes gg TV gradients, each in O(n2)O(n^2) time.

So one iteration costs O(adn+gn2)O(a d n + g n^2) time and O(ad+n2)O(a d + n^2) extra space, and KK iterations cost O(K(adn+gn2))O(K (a d n + g n^2)). With few views, ada d 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. βred\beta_{\text{red}}, gg, α\alpha, αred\alpha_{\text{red}} and rmax⁡r_{\max}, plus ε\varepsilon. 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 AA 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 yy, 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 ε\varepsilon. With noisy data, ε\varepsilon must be close to the noise norm. A smaller value overfits noise, and a larger value over-smooths. With exact data, a tiny ε\varepsilon only means that the rule of line L7 keeps shrinking the TV steps.
  • Decay of β\beta. With βred<1\beta_{\text{red}} < 1, 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 dddd and the TV value over the iterations, and stop when both have leveled off.
  • The smoothing η\eta. With η=0\eta = 0 the gradient is not defined at flat regions. Use a small η>0\eta > 0, or a subgradient with care.

Implementations

The Python code takes the sparse rows of AA 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 g=0g = 0 (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.

asd_pocs.pyI0RawGitHub
# 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

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

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of correctness
  • a full proof of time.per_iteration
  • a full proof of time.total
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example