Algorithm Search⌘K

Algorithmadvanced

CG-SENSE

Also called iterative SENSE.

Solves the SENSE least squares problem for any k-space trajectory with the conjugate gradient method on the normal equations, with the coil encoding operator and its adjoint by FFT or nonuniform FFT.

Time
O(K c (n^2 log n + S)) worst
Space
O(c (n^2 + S)) extra
Where
K = the number of iterations, at most n^2 in exact arithmetic; S = the number of samples per coil; c = the number of coils; n = the side of the n x n image
Properties
deterministicexactnot in placeoffline
Origin
Klaas P. Pruessmann, Markus Weiger, Peter Boernert, Peter Boesiger, 2001

CG-SENSE reconstructs an MR image from multi-coil data on any k-space trajectory: radial, spiral, or a Cartesian pattern with irregular gaps. It solves the same least squares problem as SENSE, but the problem no longer splits into small pixel groups, so it uses the conjugate gradient method on the normal equations. Each iteration applies the encoding operator and its adjoint once, by an FFT on a Cartesian grid or by a nonuniform FFT on a trajectory. Pruessmann, Weiger, Boernert and Boesiger published it in 2001. In exact arithmetic it reaches the least squares solution in at most n2n^2 steps, and the energy norm of the error does not increase (theorems).

In plain words

SENSE solves many tiny puzzles, one per folded pixel. With spokes or spirals instead of skipped lines, the folding is spread over the whole image, and there is one huge puzzle instead. CG-SENSE does not write that puzzle down. It only needs two moves: predict the coil data from a guess of the image, and spread a set of data back onto the image. With these two moves the conjugate gradient method walks to the best fitting image in a few dozen steps, each step better than the last in a fixed sense.

The problem

The input is the data y=(y1,…,yc)y = (y_1, \ldots, y_c), SS samples per coil at the k-space points of the trajectory, the coil sensitivity maps sks_k, and optionally positive sample weights DD. The encoding operator is Ex=(MF(skx))kE x = (M F (s_k x))_k, where FF is the unitary DFT followed by the sampling MM on a Cartesian grid, or the nonuniform DFT on a trajectory. The output is the minimizer of ∥D1/2(Ex−y)∥2\lVert D^{1/2}(E x - y) \rVert^2 over n×nn \times n images, the solution of

EHDE x=EHDy.E^H D E\, x = E^H D y.

This is the MRI reconstruction problem with coil maps and a quadratic data term.

The algorithm

⟨u,w⟩=uHw\langle u, w \rangle = u^H w. EE and EHE^H are given as functions.

  1. CG-SENSE(y, E, E^H, D, iters, tol)
  2. 1b <- E^H (D y)
  3. 2x <- 0; r <- b; p <- r
  4. 3for t = 0, 1, ..., iters - 1 do
  5. 4if ||r|| <= tol ||b|| then stop
  6. 5q <- E^H (D (E p)) ▷ one E and one E^H
  7. 6alpha <- ||r||^2 / <p, q>
  8. 7x <- x + alpha p
  9. 8r_new <- r - alpha q
  10. 9p <- r_new + (||r_new||^2 / ||r||^2) p; r <- r_new
  11. 10return x

Line L1 is the back projection of the weighted data. Line L5 is the only expensive step: it multiplies by the maps, transforms, samples, weights, and goes back. The vector rr of line L8 is the residual b−EHDExb - E^H D E x of the normal equations. Line L9 makes the new direction conjugate to the old ones. With DD equal to a density compensation for a radial or spiral trajectory, the iteration converges in fewer steps on noiseless data; Pruessmann et al. (2001) apply it as a preconditioner.

Example

Take an 8×88 \times 8 modified Shepp-Logan phantom, the four ring coil maps of the coil sensitivity map page, and a radial trajectory of 8 spokes with 8 samples each, without noise. The data have 4⋅64=2564 \cdot 64 = 256 values for 64 unknowns. The table gives the relative error ∥xt−x∥/∥x∥\lVert x_t - x \rVert / \lVert x \rVert (measurement with the code of this page, direct nonuniform DFT).

weights DD error after 5 steps after 10 steps steps to 10−310^{-3} steps to 10−610^{-6}
D=ID = I 0.256 0.078 44 49
D=∣k∣D = \lvert k \rvert (radial density) 0.116 0.055 31 34

Both runs reach the object, as part 4 of the theorem says for noiseless data, and both stop below n2=64n^2 = 64 steps. The density weights change the path, not the end point. On a 32×3232 \times 32 image with 24 of 32 phase encoding lines kept (a full center of 7 lines and random outer lines), the error was 2.5×10−22.5 \times 10^{-2} after 5 steps, 1.5×10−31.5 \times 10^{-3} after 10, and 2.2×10−62.2 \times 10^{-6} after 20 (measurement).

Correctness

If EE has full column rank, EHDEE^H D E is Hermitian positive definite and the least squares solution x⋆x^\star is unique. The conjugate gradient iterates satisfy the Galerkin condition: the residual rtr_t is orthogonal to the Krylov subspace Kt=span⁡{b,Ab,…,At−1b}\mathcal{K}_t = \operatorname{span}\{b, Ab, \ldots, A^{t-1}b\}, with A=EHDEA = E^H D E. So xtx_t minimizes the energy norm ∥x−x⋆∥A\lVert x - x^\star \rVert_A over Kt\mathcal{K}_t, the norm does not increase, and the residuals, which are mutually orthogonal, vanish after at most n2n^2 steps. For uniform Cartesian undersampling and D=ID = I, the least squares problem splits into the SENSE problems of the folded pixels, so x⋆x^\star is the SENSE output. The proof gives all steps. These are theorems in exact arithmetic; in floating point the residuals lose orthogonality and the finite termination is lost.

Proof: CG-SENSE reaches the weighted least squares solution in at most n^2 steps, and the energy norm of its error does not increasefull

The setting is that of the algorithm, in exact arithmetic. The image has N=n2N = n^2 pixels. The encoding operator E:CN→CcSE : \mathbb{C}^N \to \mathbb{C}^{cS} maps an image to the SS samples of each of the cc coils, Ex=(MF(skx))kE x = (M F (s_k x))_k, where FF is the unitary DFT on a Cartesian grid or the nonuniform DFT on a trajectory. DD is a diagonal matrix with positive entries, and D=ID = I when no weights are given. Let

A=EHDE,b=EHDy.A = E^H D E, \qquad b = E^H D y.

Line L1 computes bb, line L2 sets x0=0x_0 = 0, r0=p0=br_0 = p_0 = b, and each pass of the loop computes qt=Aptq_t = A p_t (line L5), αt=∥rt∥2/⟨pt,qt⟩\alpha_t = \lVert r_t \rVert^2 / \langle p_t, q_t \rangle (line L6), xt+1=xt+αtptx_{t+1} = x_t + \alpha_t p_t (line L7), rt+1=rt−αtqtr_{t+1} = r_t - \alpha_t q_t (line L8), and pt+1=rt+1+βtptp_{t+1} = r_{t+1} + \beta_t p_t with βt=∥rt+1∥2/∥rt∥2\beta_t = \lVert r_{t+1} \rVert^2 / \lVert r_t \rVert^2 (line L9). The inner product is ⟨u,w⟩=uHw\langle u, w \rangle = u^H w.

Theorem. Suppose EE has full column rank NN. Then:

  1. AA is Hermitian positive definite, and x⋆=A−1bx^\star = A^{-1} b is the unique minimizer of ∥D1/2(Ex−y)∥2\lVert D^{1/2}(E x - y) \rVert^2.
  2. As long as rt≠0r_t \ne 0, the iterate xtx_t minimizes ∥x−x⋆∥A2=(x−x⋆)HA(x−x⋆)\lVert x - x^\star \rVert_A^2 = (x - x^\star)^H A (x - x^\star) over the Krylov subspace Kt=span⁡{b,Ab,…,At−1b}\mathcal{K}_t = \operatorname{span}\{b, Ab, \ldots, A^{t-1} b\}. Hence ∥xt−x⋆∥A\lVert x_t - x^\star \rVert_A does not increase with tt.
  3. Some t≤Nt \le N has rt=0r_t = 0, and then xt=x⋆x_t = x^\star.
  4. If y=Extruey = E x_{\text{true}} (no noise), then x⋆=xtruex^\star = x_{\text{true}} for every positive DD.
  5. For a Cartesian scan that keeps the rows κ≡0(modR)\kappa \equiv 0 \pmod R and D=ID = I, x⋆x^\star is the output of SENSE with Ψ=I\Psi = I.

Proof of 1. AH=EHDHE=AA^H = E^H D^H E = A because DD is real and diagonal. For w≠0w \ne 0, wHAw=∥D1/2Ew∥2>0w^H A w = \lVert D^{1/2} E w \rVert^2 > 0, because Ew≠0E w \ne 0 by full column rank and D1/2D^{1/2} is invertible. The objective ϕ(x)=∥D1/2(Ex−y)∥2\phi(x) = \lVert D^{1/2}(Ex - y) \rVert^2 has the gradient 2(Ax−b)2(Ax - b) and the Hessian 2A2A, which is positive definite, so its only stationary point x⋆x^\star is its unique minimizer. □\square

Lemma. As long as r0,…,rt≠0r_0, \ldots, r_{t} \ne 0: (a) rj=b−Axjr_j = b - A x_j for j≤tj \le t; (b) the residuals r0,…,rtr_0, \ldots, r_t are mutually orthogonal; (c) the directions p0,…,ptp_0, \ldots, p_t are AA-conjugate, ⟨pi,Apj⟩=0\langle p_i, A p_j \rangle = 0 for i≠ji \ne j; (d) span⁡{r0,…,rt−1}=span⁡{p0,…,pt−1}=Kt\operatorname{span}\{r_0, \ldots, r_{t-1}\} = \operatorname{span}\{p_0, \ldots, p_{t-1}\} = \mathcal{K}_t.

Proof. (a) holds for j=0j = 0, and line L8 keeps it, since b−Axj+1=rj−αjApjb - A x_{j+1} = r_j - \alpha_j A p_j. Part (d) follows by induction from p0=r0=bp_0 = r_0 = b, rj+1=rj−αjApjr_{j+1} = r_j - \alpha_j A p_j and pj+1=rj+1+βjpjp_{j+1} = r_{j+1} + \beta_j p_j: each step adds at most one power of AA. For (b) and (c), use induction on tt. Suppose they hold up to tt. The choice of αt\alpha_t and ⟨pt,Apt⟩=⟨rt,Apt⟩\langle p_t, A p_t \rangle = \langle r_t, A p_t \rangle (since pt−rtp_t - r_t is a multiple of pt−1p_{t-1}, which is AA-conjugate to ptp_t) give ⟨rt,rt+1⟩=∥rt∥2−αt⟨rt,Apt⟩=0\langle r_t, r_{t+1} \rangle = \lVert r_t \rVert^2 - \alpha_t \langle r_t, A p_t \rangle = 0. For j<tj < t, ⟨rj,rt+1⟩=⟨rj,rt⟩−αt⟨rj,Apt⟩=0\langle r_j, r_{t+1} \rangle = \langle r_j, r_t \rangle - \alpha_t \langle r_j, A p_t \rangle = 0, because rjr_j lies in the span of p0,…,pjp_0, \ldots, p_j, which are AA-conjugate to ptp_t. So (b) holds up to t+1t + 1. For (c), Apj∈span⁡{rj,rj+1}A p_j \in \operatorname{span}\{r_j, r_{j+1}\} by line L8, so ⟨pt+1,Apj⟩=⟨rt+1,Apj⟩+βt⟨pt,Apj⟩=0\langle p_{t+1}, A p_j \rangle = \langle r_{t+1}, A p_j \rangle + \beta_t \langle p_t, A p_j \rangle = 0 for j<tj < t. For j=tj = t, Apt=(rt−rt+1)/αtA p_t = (r_t - r_{t+1})/\alpha_t and ⟨rt+1,Apt⟩=−∥rt+1∥2/αt\langle r_{t+1}, A p_t \rangle = -\lVert r_{t+1} \rVert^2/\alpha_t, while βt⟨pt,Apt⟩=βt∥rt∥2/αt=∥rt+1∥2/αt\beta_t \langle p_t, A p_t \rangle = \beta_t \lVert r_t \rVert^2/\alpha_t = \lVert r_{t+1} \rVert^2/\alpha_t; the sum is 0. □\square

Proof of 2. By (d), xt∈Ktx_t \in \mathcal{K}_t. By (a) and (b), A(x⋆−xt)=rtA(x^\star - x_t) = r_t is orthogonal to r0,…,rt−1r_0, \ldots, r_{t-1}, which span Kt\mathcal{K}_t. So for every z∈Ktz \in \mathcal{K}_t, ∥z−x⋆∥A2=∥xt−x⋆∥A2+∥z−xt∥A2+2Re⁡⟨z−xt,A(xt−x⋆)⟩\lVert z - x^\star \rVert_A^2 = \lVert x_t - x^\star \rVert_A^2 + \lVert z - x_t \rVert_A^2 + 2 \operatorname{Re} \langle z - x_t, A(x_t - x^\star) \rangle, and the last term is 0. Hence xtx_t is the minimizer over Kt\mathcal{K}_t. The subspaces are nested, Kt⊆Kt+1\mathcal{K}_t \subseteq \mathcal{K}_{t+1}, so the minimum does not increase. □\square

Proof of 3. Nonzero mutually orthogonal vectors in CN\mathbb{C}^N number at most NN, so by (b) some rtr_t with t≤Nt \le N is zero. Then Axt=bA x_t = b by (a), so xt=x⋆x_t = x^\star. Line L4 stops the loop there. □\square

Proof of 4. With y=Extruey = E x_{\text{true}}, ϕ(xtrue)=0\phi(x_{\text{true}}) = 0, the least possible value, and the minimizer is unique by part 1. □\square

Proof of 5. By the folding lemma on the SENSE page, the kept rows of coil kk are n−1n^{-1} times the DFT of size m×nm \times n, m=n/Rm = n/R, of the folded image ∑p(skx)(i+pm,j)\sum_p (s_k x)(i + pm, j). That DFT is mn\sqrt{mn} times a unitary map, so ∑k∥yk−Ekx∥2=(m/n)∑k∑(i,j)∣ak(i,j)−(Eijvij)k∣2\sum_k \lVert y_k - E_k x \rVert^2 = (m/n) \sum_k \sum_{(i,j)} |a_k(i, j) - (E_{ij} v_{ij})_k|^2, where aka_k are the folded images from the data, EijE_{ij} the unfolding matrix and vijv_{ij} the pixel group of xx. The right side is a sum of independent SENSE objectives, one for each folded pixel, so the two problems have the same minimizers. □\square

Remarks.

  • In floating point the residuals lose their orthogonality, and CG does not stop exactly after NN steps. The bound ∥xt−x⋆∥A≤2(κ−1κ+1)t∥x⋆∥A\lVert x_t - x^\star \rVert_A \le 2 \bigl(\frac{\sqrt{\kappa} - 1}{\sqrt{\kappa} + 1}\bigr)^t \lVert x^\star \rVert_A with the condition number κ\kappa of AA is the standard rate in exact arithmetic.
  • With noise, x⋆x^\star is the weighted least squares solution, not the object. Stopping early regularizes; the choice of the stopping index is then a heuristic unless the noise level is known.
  • The weights DD change the solution when the data are noisy or inconsistent. For noiseless data they change only the speed (part 4).

Complexity

In the real RAM, one iteration costs one application of EE and one of EHE^H, plus O(n2)O(n^2) for the vector updates. On a Cartesian grid with an FFT, one application costs O(cn2log⁡n)O(c n^2 \log n). On a trajectory with a nonuniform FFT of fixed kernel width and oversampling, it costs O(c(n2log⁡n+S))O(c(n^2 \log n + S)); the direct nonuniform DFT of the code costs O(cSn2)O(c S n^2). The nonuniform FFT is not a reconstruction by itself: it only applies EE and EHE^H fast, and CG-SENSE calls it twice per iteration. With KK iterations the total is O(Kc(n2log⁡n+S))O(K c (n^2 \log n + S)). The bound K≤n2K \le n^2 holds in exact arithmetic. In practice the iteration stops when ∥r∥≤tol∥b∥\lVert r \rVert \le \mathrm{tol} \lVert b \rVert, and the number of steps depends on the condition number of EHDEE^H D E, which grows with the g-factor. The memory holds a few images and one data vector, O(c(n2+S))O(c(n^2 + S)).

Properties

  • Least squares solution. With full column rank, the iteration reaches x⋆x^\star in at most n2n^2 steps in exact arithmetic (theorem).
  • Monotone error. ∥xt−x⋆∥A\lVert x_t - x^\star \rVert_A does not increase (theorem). The test of this page checks it at each step on a radial problem. The Euclidean error ∥xt−x⋆∥\lVert x_t - x^\star \rVert does not increase either (Hestenes and Stiefel 1952), and the weighted residual ∥D1/2(Ext−y)∥\lVert D^{1/2}(E x_t - y) \rVert does not increase, because its square differs from ∥xt−x⋆∥A2\lVert x_t - x^\star \rVert_A^2 by a constant. The plain data residual ∥Ext−y∥\lVert E x_t - y \rVert is not monotone in general when DD is not a multiple of the identity. The tests do not check these.
  • Same as SENSE for uniform Cartesian sampling. For D=ID = I, the limit is the SENSE output (theorem). The test of this page checks it on a 32×3232 \times 32 image with R=2R = 2 and noise to 10−810^{-8}.
  • Matrix free. Only EE and EHE^H are needed, so any trajectory, field map or other linear term can be added to EE.
  • Same noise as SENSE at convergence. At the solution the noise covariance is the one of the least squares estimate; the g-factor describes it for uniform Cartesian sampling.

Variants and improvements

  • CGLS and LSQR. CGLS runs the same iteration on D1/2ED^{1/2} E without forming the normal equations, with better behavior in floating point. Its iterates are the same in exact arithmetic.
  • Regularized CG-SENSE. Adding λ∥x∥2\lambda \lVert x \rVert^2 or λ∥Lx∥2\lambda \lVert L x \rVert^2 to the objective gives a better conditioned system, the Tikhonov form. Early stopping regularizes as well.
  • Preconditioning. Density compensation in DD, or a diagonal preconditioner in the image, reduces the number of steps.
  • Nonlinear priors. Compressed sensing MRI adds a sparsity term and replaces CG by a proximal method, with the same EE.
  • k-space alternatives. SPIRiT poses a consistency problem in k-space with a calibrated kernel instead of explicit maps, and also solves it with conjugate gradients.

When to use it

Use CG-SENSE for non-Cartesian trajectories and for Cartesian patterns that SENSE cannot unfold pixel by pixel, such as variable density or random line patterns, when good coil maps are known. On uniform Cartesian data, direct SENSE gives the same result faster. With noisy data and a high g-factor, stop early or add regularization. When the maps are not available, use ESPIRiT to estimate them, or a k-space method such as SPIRiT.

Pitfalls

  • Adjoint that is not the adjoint. Line L5 needs the exact adjoint of EE. A gridding operator with a different kernel for the two directions breaks the theorem, and the iteration can stall or diverge. An adjoint test, ∣⟨Ex,y⟩−⟨x,EHy⟩∣|\langle E x, y \rangle - \langle x, E^H y \rangle| small, finds the error.
  • Weights in the wrong place. DD must appear in line L1 and inside line L5. Weighting only line L1 solves a different, non-Hermitian system.
  • Running to convergence on noisy data. With a high g-factor, the late iterations fit the noise. The semi-convergence of the error is the reason; choose the stopping index or a regularization weight.
  • Rank deficiency. Where all maps are zero, or where the trajectory leaves a gap that the coils cannot fill, EE does not have full column rank. CG then converges to the solution of least norm in the range, and the missing part stays zero.
  • Floating point. The residual of line L8 is updated, not recomputed, and drifts from b−Axb - Ax after many steps.

Implementations

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.

cg_sense.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cg-sense/. The authors are listed in prov/CCN5EK.jsonl.

"""CG-SENSE: iterative SENSE for any k-space trajectory (Pruessmann, Weiger, Boernert and Boesiger 2001).

The model is y = E x + e with the encoding operator E x = (M F (s_k x))_k for
coils k = 1..c: multiply by the coil map, transform, keep the samples. The
method runs the conjugate gradient method (Hestenes and Stiefel 1952) on the
normal equations

    E^H D E x = E^H D y,

where D is a positive diagonal weight on the samples (the density
compensation; D = 1 gives the plain least squares solution). E is given as
two functions, so the same code works for a Cartesian mask (with the FFT)
and for a non-Cartesian trajectory (here with a direct nonuniform DFT).

Images are flat row-major lists of n^2 complex numbers. Data are flat lists:
coil 0 first, then coil 1, and so on.
"""

import cmath
import math
from typing import Callable, Optional, Sequence

from imgkit import dft2, idft2

Vector = list[complex]
Operator = Callable[[Sequence[complex]], Vector]


def _dot(u: Sequence[complex], v: Sequence[complex]) -> complex:
    return sum(a.conjugate() * b for a, b in zip(u, v))


def cartesian_ops(maps: Sequence[Sequence[Sequence[complex]]], mask: Sequence[Sequence[bool]]):
    """E and E^H for a Cartesian sampling mask (n x n booleans) with the unitary DFT F / n."""
    n = len(mask)
    where = [(i, j) for i in range(n) for j in range(n) if mask[i][j]]

    def apply_e(x: Sequence[complex]) -> Vector:
        out = []
        for s in maps:
            img = [[s[i][j] * x[i * n + j] for j in range(n)] for i in range(n)]
            ksp = dft2(img)
            out.extend(ksp[i][j] / n for i, j in where)
        return out

    def apply_eh(y: Sequence[complex]) -> Vector:
        out = [0j] * (n * n)
        per = len(where)
        for k, s in enumerate(maps):
            ksp = [[0j] * n for _ in range(n)]
            for t, (i, j) in enumerate(where):
                ksp[i][j] = y[k * per + t]
            img = idft2(ksp)
            for i in range(n):
                for j in range(n):
                    out[i * n + j] += s[i][j].conjugate() * img[i][j] * n
        return out

    return apply_e, apply_eh


def nudft_ops(maps: Sequence[Sequence[Sequence[complex]]], points: Sequence[tuple[float, float]]):
    """E and E^H for k-space points (kx, ky) in cycles per field of view, by direct sums.

    Pixel (i, j) sits at (j - n/2, i - n/2) in pixel units, and the sample at
    (kx, ky) of coil k is (1/n) sum s_k x exp(-2 pi i (kx (j - n/2) + ky (i - n/2)) / n).
    This is the nonuniform DFT; a fast code would use a nonuniform FFT instead.
    """
    n = len(maps[0])
    h = n / 2.0
    phase = [
        [cmath.exp(-2j * math.pi * (kx * (j - h) + ky * (i - h)) / n) / n for i in range(n) for j in range(n)]
        for kx, ky in points
    ]

    def apply_e(x: Sequence[complex]) -> Vector:
        out = []
        for s in maps:
            sx = [s[i][j] * x[i * n + j] for i in range(n) for j in range(n)]
            out.extend(sum(a * b for a, b in zip(row, sx)) for row in phase)
        return out

    def apply_eh(y: Sequence[complex]) -> Vector:
        out = [0j] * (n * n)
        m = len(points)
        for k, s in enumerate(maps):
            acc = [0j] * (n * n)
            for t, row in enumerate(phase):
                yt = y[k * m + t]
                if yt != 0:
                    for q in range(n * n):
                        acc[q] += row[q].conjugate() * yt
            for i in range(n):
                for j in range(n):
                    out[i * n + j] += s[i][j].conjugate() * acc[i * n + j]
        return out

    return apply_e, apply_eh


def cg_sense(
    y: Sequence[complex],
    apply_e: Operator,
    apply_eh: Operator,
    size: int,
    iters: int,
    weights: Optional[Sequence[float]] = None,
    tol: float = 0.0,
    callback: Optional[Callable[[int, Vector], None]] = None,
) -> Vector:
    """Solve E^H D E x = E^H D y by CG from x = 0 with at most iters steps.

    size is the number of pixels, weights the diagonal of D (None for D = 1).
    The loop stops early when ||r|| <= tol ||b||. callback(t, x) sees each iterate.
    """
    def weigh(v):
        return list(v) if weights is None else [w * a for w, a in zip(weights, v)]

    def normal(v):
        return apply_eh(weigh(apply_e(v)))

    b = apply_eh(weigh(y))  # @line L1
    x = [0j] * size  # @line L2
    r = list(b)
    p = list(r)
    rr = _dot(r, r).real
    bnorm = math.sqrt(_dot(b, b).real)
    for t in range(iters):  # @line L3
        if rr == 0.0 or math.sqrt(rr) <= tol * bnorm:  # @line L4
            break
        q = normal(p)  # @line L5
        alpha = rr / _dot(p, q).real  # @line L6
        x = [xi + alpha * pi for xi, pi in zip(x, p)]  # @line L7
        r = [ri - alpha * qi for ri, qi in zip(r, q)]  # @line L8
        rr_new = _dot(r, r).real
        p = [ri + (rr_new / rr) * pi for ri, pi in zip(r, p)]  # @line L9
        rr = rr_new
        if callback is not None:
            callback(t + 1, x)
    return x  # @line L10


def radial_points(spokes: int, samples: int) -> list[tuple[float, float]]:
    """A radial trajectory: spokes through the center at angles pi s / spokes, samples at r = t - (samples - 1) / 2."""
    pts = []
    for s in range(spokes):
        th = math.pi * s / spokes
        for t in range(samples):
            r = t - (samples - 1) / 2.0
            pts.append((r * math.cos(th), r * math.sin(th)))
    return pts


def radial_density(points: Sequence[tuple[float, float]]) -> list[float]:
    """A simple density compensation for a radial trajectory: the distance |k| to the center."""
    return [math.hypot(kx, ky) for kx, ky in points]
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
imgla.py 259 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/.
"""Dense linear algebra on lists of rows (float, complex or Fraction entries).

A matrix is a list of rows. A vector is a list of numbers. The inner product
is <u, v> = sum_i conj(u_i) v_i, linear in the second argument, so that the
adjoint A^H satisfies <A x, y> = <x, A^H y>.
"""

import math


def _flat(x):
    """Flatten a list of rows (an image) into one list; a vector is returned as is."""
    if x and isinstance(x[0], (list, tuple)):
        return [v for row in x for v in row]
    return x


def zeros(m, n):
    """The m x n zero matrix."""
    return [[0.0] * n for _ in range(m)]


def eye(n):
    """The n x n identity matrix."""
    out = zeros(n, n)
    for i in range(n):
        out[i][i] = 1.0
    return out


def transpose(a):
    """A^T."""
    return [list(col) for col in zip(*a)]


def conj_transpose(a):
    """A^H, the conjugate transpose."""
    return [[v.conjugate() for v in col] for col in zip(*a)]


def matmul(a, b):
    """The product A B."""
    bt = list(zip(*b))
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def matvec(a, x):
    """The product A x."""
    return [sum(v * w for v, w in zip(row, x)) for row in a]


def rmatvec(a, y):
    """The product A^H y."""
    n = len(a[0]) if a else 0
    out = [0.0] * n
    for row, yi in zip(a, y):
        if yi == 0:
            continue
        for j, v in enumerate(row):
            out[j] += v.conjugate() * yi
    return out


def dot(u, v):
    """<u, v> = sum_i conj(u_i) v_i. Images (lists of rows) are flattened."""
    return sum(a.conjugate() * b for a, b in zip(_flat(u), _flat(v)))


def norm2(x):
    """The Euclidean norm. Images (lists of rows) are flattened."""
    return math.sqrt(sum(abs(v) ** 2 for v in _flat(x)))


def solve(a, b):
    """Solve A x = b by Gaussian elimination with partial pivoting.

    b is a vector or a matrix (a list of rows). A must be square and
    nonsingular; a zero pivot raises ValueError. Fractions stay exact.
    """
    n = len(a)
    vec = not (b and isinstance(b[0], (list, tuple)))
    rhs = [[bi] for bi in b] if vec else [list(r) for r in b]
    m = [list(row) + rhs[i] for i, row in enumerate(a)]
    w = len(m[0])
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(m[r][c]))
        if m[p][c] == 0:
            raise ValueError("singular matrix")
        m[c], m[p] = m[p], m[c]
        piv = m[c][c]
        for r in range(c + 1, n):
            f = m[r][c] / piv
            if f != 0:
                mr, mc = m[r], m[c]
                for j in range(c, w):
                    mr[j] -= f * mc[j]
    x = [[0.0] * (w - n) for _ in range(n)]
    for r in range(n - 1, -1, -1):
        for j in range(w - n):
            s = m[r][n + j] - sum(m[r][k] * x[k][j] for k in range(r + 1, n))
            x[r][j] = s / m[r][r]
    return [row[0] for row in x] if vec else x


def cholesky(a):
    """Lower triangular L with A = L L^H for a Hermitian positive definite A."""
    n = len(a)
    low = zeros(n, n)
    for j in range(n):
        d = a[j][j] - sum(abs(low[j][k]) ** 2 for k in range(j))
        d = d.real if isinstance(d, complex) else d
        if not d > 0:
            raise ValueError("matrix is not positive definite")
        ljj = math.sqrt(d)
        low[j][j] = ljj
        for i in range(j + 1, n):
            s = a[i][j] - sum(low[i][k] * low[j][k].conjugate() for k in range(j))
            low[i][j] = s / ljj
    return low


def cho_solve(low, b):
    """Solve (L L^H) x = b, with L from cholesky."""
    n = len(low)
    z = [0.0] * n
    for i in range(n):
        z[i] = (b[i] - sum(low[i][k] * z[k] for k in range(i))) / low[i][i]
    x = [0.0] * n
    for i in range(n - 1, -1, -1):
        s = z[i] - sum(low[k][i].conjugate() * x[k] for k in range(i + 1, n))
        x[i] = s / low[i][i].conjugate()
    return x


def _rot_params(app, aqq, apq):
    """c, s of the Jacobi rotation that zeroes the (p, q) entry of [[app, apq], [apq, aqq]]."""
    theta = (aqq - app) / (2.0 * apq)
    t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
    c = 1.0 / math.sqrt(1.0 + t * t)
    return c, c * t


def sym_eig(a, tol=1e-15, max_sweeps=100):
    """Eigenvalues (ascending) and eigenvectors (as columns) of a real symmetric matrix.

    Cyclic Jacobi method. Returns (w, Q) with A = Q diag(w) Q^T.
    """
    n = len(a)
    m = [[float(v) for v in row] for row in a]
    q = eye(n)
    for _ in range(max_sweeps):
        off = sum(m[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
        scale = sum(m[i][i] ** 2 for i in range(n)) + off
        if off <= (tol * tol) * scale or off == 0.0:
            break
        for p in range(n - 1):
            for r in range(p + 1, n):
                apq = m[p][r]
                if apq == 0.0:
                    continue
                c, s = _rot_params(m[p][p], m[r][r], apq)
                for k in range(n):
                    mkp, mkr = m[k][p], m[k][r]
                    m[k][p] = c * mkp - s * mkr
                    m[k][r] = s * mkp + c * mkr
                mp, mr = m[p], m[r]
                for k in range(n):
                    mpk, mrk = mp[k], mr[k]
                    mp[k] = c * mpk - s * mrk
                    mr[k] = s * mpk + c * mrk
                m[p][r] = m[r][p] = 0.0
                for k in range(n):
                    qkp, qkr = q[k][p], q[k][r]
                    q[k][p] = c * qkp - s * qkr
                    q[k][r] = s * qkp + c * qkr
    order = sorted(range(n), key=lambda i: m[i][i])
    w = [m[i][i] for i in order]
    qs = [[q[k][i] for i in order] for k in range(n)]
    return w, qs


def _complete(cols, m):
    """Replace zero columns of an m-row column list by unit vectors orthogonal to the others."""
    for idx, col in enumerate(cols):
        if any(v != 0.0 for v in col):
            continue
        for e in range(m):
            cand = [0.0] * m
            cand[e] = 1.0
            for _ in range(2):
                for jdx, other in enumerate(cols):
                    if jdx == idx or not any(v != 0.0 for v in other):
                        continue
                    h = sum(a * b for a, b in zip(other, cand))
                    cand = [a - h * b for a, b in zip(cand, other)]
            nrm = math.sqrt(sum(v * v for v in cand))
            if nrm > 0.5:
                cols[idx] = [v / nrm for v in cand]
                break
    return cols


def svd(a, tol=1e-15, max_sweeps=100):
    """Thin SVD of a real m x n matrix by one-sided Jacobi (Hestenes).

    Returns (U, S, V) with p = min(m, n): U is m x p, S a list of p values in
    descending order, V is n x p, U^T U = I, V^T V = I and A = U diag(S) V^T.
    """
    m, n = len(a), len(a[0])
    if m < n:
        v, s, u = svd(transpose(a), tol, max_sweeps)
        return u, s, v
    cols = [[float(a[i][j]) for i in range(m)] for j in range(n)]
    vcols = [[1.0 if i == j else 0.0 for i in range(n)] for j in range(n)]
    for _ in range(max_sweeps):
        rotated = False
        for p in range(n - 1):
            for r in range(p + 1, n):
                cp, cr = cols[p], cols[r]
                alpha = sum(x * x for x in cp)
                beta = sum(x * x for x in cr)
                gamma = sum(x * y for x, y in zip(cp, cr))
                if gamma == 0.0 or abs(gamma) <= tol * math.sqrt(alpha * beta):
                    continue
                rotated = True
                c, s = _rot_params(alpha, beta, gamma)
                cols[p] = [c * x - s * y for x, y in zip(cp, cr)]
                cols[r] = [s * x + c * y for x, y in zip(cp, cr)]
                vp, vr = vcols[p], vcols[r]
                vcols[p] = [c * x - s * y for x, y in zip(vp, vr)]
                vcols[r] = [s * x + c * y for x, y in zip(vp, vr)]
        if not rotated:
            break
    sig = [math.sqrt(sum(x * x for x in col)) for col in cols]
    # A column below 1e-150 times the largest one is zero to working precision;
    # its squares underflow, so its direction carries no information.
    floor = max(sig) * 1e-150 if sig else 0.0
    sig = [t if t > floor and t > 1e-150 else 0.0 for t in sig]
    order = sorted(range(n), key=lambda j: -sig[j])
    s_out = [sig[j] for j in order]
    ucols = [[x / sig[j] for x in cols[j]] if sig[j] > 0.0 else [0.0] * m for j in order]
    ucols = _complete(ucols, m)
    u = [[ucols[j][i] for j in range(n)] for i in range(m)]
    v = [[vcols[j][i] for j in order] for i in range(n)]
    return u, s_out, v


def adjoint_gap(apply_a, apply_ah, x, y):
    """|<A x, y> - <x, A^H y>| / (||A x|| ||y||) for given functions A and A^H.

    x and y may be vectors or images (lists of rows). If the denominator is
    zero, the absolute gap is returned.
    """
    ax = apply_a(x)
    gap = abs(dot(ax, y) - dot(x, apply_ah(y)))
    den = norm2(ax) * norm2(y)
    return gap / den if den > 0.0 else gap
test_cg_sense.py 162 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cg-sense/. The authors are listed in prov/CCN5EK.jsonl.

import cmath
import math
import random

from cg_sense import cartesian_ops, cg_sense, nudft_ops, radial_density, radial_points
from imgkit import MODIFIED_SHEPP_LOGAN, ellipse_phantom, pixel_centers
from imgla import adjoint_gap, solve


def ring_maps(n, c=4):
    """Smooth synthetic coil maps: Gaussian profiles of coils on a ring of radius 1.2, with a phase."""
    xs, ys = pixel_centers(n)
    maps = []
    for k in range(c):
        ang = math.radians(20.0 + 360.0 * k / c)
        cx, cy = 1.2 * math.cos(ang), 1.2 * math.sin(ang)
        maps.append([
            [
                math.exp(-((x - cx) ** 2 + (y - cy) ** 2) / 1.2) * cmath.exp(1j * (0.9 * k + 0.4 * x - 0.3 * y))
                for x in xs
            ]
            for y in ys
        ])
    return maps


def phantom_vec(n):
    xs, _ = pixel_centers(n)
    img = ellipse_phantom(n, MODIFIED_SHEPP_LOGAN)
    return [v * cmath.exp(0.3j * x) for row in img for v, x in zip(row, xs)]


def rel(a, b):
    return math.sqrt(sum(abs(u - v) ** 2 for u, v in zip(a, b)) / sum(abs(v) ** 2 for v in b))


def dense_solution(apply_e, apply_eh, size, y, weights):
    """The solution of E^H D E x = E^H D y by Gaussian elimination."""
    cols = []
    for q in range(size):
        e = [0j] * size
        e[q] = 1.0
        cols.append(apply_eh([w * v for w, v in zip(weights, apply_e(e))]))
    a = [[cols[q][p] for q in range(size)] for p in range(size)]
    return solve(a, apply_eh([w * v for w, v in zip(weights, y)])), a


def test_adjoint_cartesian_and_nudft():
    rng = random.Random(1)
    n = 8
    maps = ring_maps(n)
    mask = [[rng.random() < 0.5 for _ in range(n)] for _ in range(n)]
    pts = radial_points(6, 8)
    for e, eh in (cartesian_ops(maps, mask), nudft_ops(maps, pts)):
        x = [complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(n * n)]
        y = [complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(len(e(x)))]
        assert adjoint_gap(e, eh, x, y) < 1e-10


def unfold_r2(y_img, maps, n):
    """Per-pixel SENSE for R = 2 (rows kappa even kept), written out for the comparison."""
    from imgkit import idft2
    m = n // 2
    folded = []
    for yk in y_img:
        sub = [yk[kappa] for kappa in range(0, n, 2)]
        folded.append([[v * n for v in row] for row in idft2(sub)])
    out = [0j] * (n * n)
    for i in range(m):
        for j in range(n):
            e = [[mp[i][j], mp[i + m][j]] for mp in maps]
            gram = [[sum(e[k][p].conjugate() * e[k][q] for k in range(len(maps))) for q in range(2)] for p in range(2)]
            rhs = [sum(e[k][p].conjugate() * folded[k][i][j] for k in range(len(maps))) for p in range(2)]
            v = solve(gram, rhs)
            out[i * n + j], out[(i + m) * n + j] = v[0], v[1]
    return out


def test_uniform_cartesian_equals_sense_with_noise():
    n = 32
    maps = ring_maps(n)
    mask = [[kappa % 2 == 0] * n for kappa in range(n)]
    e, eh = cartesian_ops(maps, mask)
    rng = random.Random(4)
    y = [v + complex(rng.gauss(0, 0.002), rng.gauss(0, 0.002)) for v in e(phantom_vec(n))]
    x = cg_sense(y, e, eh, n * n, 45, tol=1e-12)
    # put the samples back on the grid for the direct SENSE unfolding
    per = n * n // 2
    y_img = []
    for k in range(len(maps)):
        arr = [[0j] * n for _ in range(n)]
        t = 0
        for kappa in range(n):
            for l in range(n):
                if mask[kappa][l]:
                    arr[kappa][l] = y[k * per + t]
                    t += 1
        y_img.append(arr)
    assert rel(x, unfold_r2(y_img, maps, n)) < 1e-8


def test_noiseless_variable_density_mask_converges_to_the_object():
    n = 32
    maps = ring_maps(n)
    rng = random.Random(9)
    keep = [abs(kappa if kappa < n // 2 else kappa - n) < 4 or rng.random() < 0.6 for kappa in range(n)]
    mask = [[keep[kappa]] * n for kappa in range(n)]
    e, eh = cartesian_ops(maps, mask)
    x0 = phantom_vec(n)
    errs = []
    cg_sense(e(x0), e, eh, n * n, 30, callback=lambda t, x: errs.append(rel(x, x0)))
    assert errs[-1] < 1e-6
    assert errs[-1] < errs[4] < errs[0]


def test_radial_matches_dense_least_squares_with_and_without_density():
    n = 8
    maps = ring_maps(n)
    pts = radial_points(8, 8)
    e, eh = nudft_ops(maps, pts)
    rng = random.Random(2)
    y = [v + complex(rng.gauss(0, 0.01), rng.gauss(0, 0.01)) for v in e(phantom_vec(n))]
    dens = radial_density(pts) * len(maps)
    for w in (None, dens):
        ref, _ = dense_solution(e, eh, n * n, y, w or [1.0] * len(y))
        x = cg_sense(y, e, eh, n * n, 64, weights=w, tol=1e-13)
        assert rel(x, ref) < 1e-8


def test_energy_norm_error_does_not_increase():
    n = 8
    maps = ring_maps(n)
    pts = radial_points(8, 8)
    e, eh = nudft_ops(maps, pts)
    rng = random.Random(6)
    y = [complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(len(pts) * len(maps))]
    ones = [1.0] * len(y)
    xs, a = dense_solution(e, eh, n * n, y, ones)

    def energy(x):
        d = [u - v for u, v in zip(x, xs)]
        ad = [sum(a[p][q] * d[q] for q in range(n * n)) for p in range(n * n)]
        return sum(u.conjugate() * v for u, v in zip(d, ad)).real

    vals = [energy([0j] * (n * n))]
    cg_sense(y, e, eh, n * n, 64, callback=lambda t, x: vals.append(energy(x)))
    assert all(b <= a_ * (1 + 1e-9) + 1e-12 for a_, b in zip(vals, vals[1:]))
    assert vals[-1] < 1e-12 * vals[0]


def test_noiseless_radial_reaches_the_object():
    n = 8
    maps = ring_maps(n)
    pts = radial_points(8, 8)
    e, eh = nudft_ops(maps, pts)
    x0 = phantom_vec(n)
    dens = radial_density(pts) * len(maps)
    for w in (None, dens):
        assert rel(cg_sense(e(x0), e, eh, n * n, 64, weights=w, tol=1e-13), x0) < 1e-6

History

Hestenes and Stiefel published the conjugate gradient method in 1952. Pruessmann, Weiger, Scheidegger and Boesiger published SENSE for Cartesian scans in 1999. In 2001 Pruessmann, Weiger, Boernert and Boesiger wrote the reconstruction for any trajectory as a large linear system, solved it with conjugate gradients, applied the encoding operator with gridding and FFTs, and used density compensation as a preconditioner. The method became the base of most later iterative MR reconstructions with coil arrays, including compressed sensing MRI.

References

  1. Klaas P. Pruessmann, Markus Weiger, Peter Boernert and Peter Boesiger, Advances in sensitivity encoding with arbitrary k-space trajectories, Magnetic Resonance in Medicine 46(4), 2001, 638 to 651, the encoding operator for any trajectory, the conjugate gradient iteration on the normal equations, and the density compensation as a preconditioner (general locator; section numbers not confirmed)
  2. Magnus R. Hestenes and Eduard Stiefel, Methods of conjugate gradients for solving linear systems, Journal of Research of the National Bureau of Standards 49(6), 1952, 409 to 436, the conjugate gradient method, its finite termination and the minimization of the error norm over the Krylov subspace (general locator)
  3. Klaas P. Pruessmann, Markus Weiger, Markus B. Scheidegger and Peter Boesiger, SENSE, sensitivity encoding for fast MRI, Magnetic Resonance in Medicine 42(5), 1999, 952 to 962, the least squares model of sensitivity encoding that CG-SENSE solves (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 time.worst
  • 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