Algorithm Search⌘K

Algorithmcore

SENSE

Also called sensitivity encoding.

Unfolds an aliased image from uniformly undersampled multi-coil Cartesian data by solving a small least squares problem with the coil sensitivities at each pixel. Needs R <= c.

Time
O(c n^2 log n + c^2 n^2) worst
Space
O(c n^2) extra
Where
R = the reduction factor, R <= c; c = the number of coils; n = the side of the n x n image, a multiple of R
Properties
deterministicexactnot in placeoffline
Origin
Klaas P. Pruessmann, Markus Weiger, Markus B. Scheidegger, Peter Boesiger, 1999

SENSE (sensitivity encoding) reconstructs an MR image from a Cartesian scan that skips phase encoding lines, with an array of cc receive coils. If the scan keeps every RR-th line, the image of each coil is folded: RR pixels, at distance n/Rn/R apart, fall on the same place. Each coil sees the folded pixels with different weights, its coil sensitivity map. At each folded pixel the cc coil values give cc linear equations in RR unknowns, and SENSE solves this small least squares problem. Pruessmann, Weiger, Scheidegger and Boesiger published it in 1999. Without noise and with full column rank at every pixel, the result is exact (a theorem; the proof is on this page). The noise grows by the g-factor times R\sqrt{R}.

In plain words

Leave out every second line of the scan and the picture folds: the top half lands on the bottom half. One coil cannot tell which half a bright spot came from. But a coil near the top sees the top half brightly and the bottom half dimly, and a coil near the bottom sees the opposite. If we know how bright each coil sees each place, every folded pixel gives a small puzzle: two unknown values, one equation per coil. With two or more coils that see the two places differently, the puzzle has one answer. SENSE solves one such puzzle for every folded pixel.

The problem

The input is the k-space yky_k of each coil k=1,…,ck = 1, \ldots, c on the rows κ=0,R,2R,…\kappa = 0, R, 2R, \ldots of the phase encoding axis of an n×nn \times n grid, the maps sks_k, the reduction factor RR with R∣nR \mid n, and optionally the c×cc \times c noise covariance Ψ\Psi between the coils. The model is yk=MFu(skx)y_k = M F_u (s_k x) with the unitary 2D DFT Fu=F/nF_u = F/n and the row mask MM (see mri-signal-equation and k-space). The output is the image xx. This is the Cartesian case of the MRI reconstruction problem with uniform undersampling.

The algorithm

Let m=n/Rm = n/R. The folded pixel (i,j)(i, j) with 0≤i<m0 \le i < m holds the image pixels (i+pm,j)(i + pm, j) for p=0,…,R−1p = 0, \ldots, R - 1.

  1. SENSE(y, s, R, Psi) ▷ y_k known on the rows kappa = 0, R, 2R, ...
  2. 1m <- n / R
  3. 2a_k <- n F^{-1}_{m x n}(kept rows of y_k) for each coil k ▷ folded images
  4. 3L <- Cholesky factor of Psi (Psi = L L^H)
  5. 4for each folded pixel (i, j), 0 <= i < m do
  6. 5E[k][p] <- s_k(i + p m, j) ▷ c x R unfolding matrix
  7. 6E <- L^{-1} E; b <- L^{-1} (a_1(i,j), ..., a_c(i,j))
  8. 7solve (E^H E) v = E^H b ▷ R x R normal equations
  9. 8x(i + p m, j) <- v_p for p = 0, ..., R - 1
  10. 9return x

Line L2 is an inverse DFT of size m×nm \times n of the kept rows; by the folding lemma of the proof it gives ak(i,j)=∑psk(i+pm,j) x(i+pm,j)a_k(i, j) = \sum_p s_k(i + pm, j)\, x(i + pm, j). The rows that the scan skips are never read. Line L6 whitens the coils, so that line L7 solves the weighted least squares problem min⁡v(a−Ev)HΨ−1(a−Ev)\min_v (a - Ev)^H \Psi^{-1} (a - Ev). Without a covariance, L=IL = I. The code can also add λI\lambda I to the matrix of line L7, a Tikhonov step against noise; then the output is biased.

Example

Take one image column with n=4n = 4, R=2R = 2, c=2c = 2, the maps s1=(1,0.9,0.5,0.3)s_1 = (1, 0.9, 0.5, 0.3) and s2=(0.5,0.6,1,0.9)s_2 = (0.5, 0.6, 1, 0.9) along the column, the object x=(2,3,1,0)x = (2, 3, 1, 0) and Ψ=I\Psi = I. Then m=2m = 2. Folded pixel 0 holds pixels 0 and 2, and folded pixel 1 holds pixels 1 and 3.

folded pixel EE (rows are coils) aa vv g-factor of the two pixels
0 (10.50.51)\begin{pmatrix} 1 & 0.5 \\ 0.5 & 1 \end{pmatrix} (2.5,2)(2.5, 2) (2,1)(2, 1) 1.6667, 1.6667
1 (0.90.30.60.9)\begin{pmatrix} 0.9 & 0.3 \\ 0.6 & 0.9 \end{pmatrix} (2.7,1.8)(2.7, 1.8) (3,0)(3, 0) 1.6288, 1.6288

For folded pixel 0, a1=1⋅2+0.5⋅1=2.5a_1 = 1 \cdot 2 + 0.5 \cdot 1 = 2.5 and a2=0.5⋅2+1⋅1=2a_2 = 0.5 \cdot 2 + 1 \cdot 1 = 2, and the 2×22 \times 2 system gives v=(2,1)v = (2, 1), so line L8 writes x0=2x_0 = 2 and x2=1x_2 = 1. For folded pixel 1, det⁡E=0.63\det E = 0.63 and v=(3,0)v = (3, 0). The output is (2,3,1,0)(2, 3, 1, 0), the object. The g-factor of folded pixel 0 is [(EHE)−1]00[EHE]00=2.2222⋅1.25=1.6667\sqrt{[(E^HE)^{-1}]_{00} [E^HE]_{00}} = \sqrt{2.2222 \cdot 1.25} = 1.6667. With c=Rc = R the two pixels of a group have the same g-factor.

Correctness

At each folded pixel the data are a=Eva = Ev plus noise. If EE has full column rank, the normal equations of line L7 have one solution, and without noise that solution is vv, the true pixel values. Full column rank of a c×Rc \times R matrix needs R≤cR \le c. The noise covariance of the output at pixel i+pmi + pm is R[(EHΨ−1E)−1]ppR[(E^H\Psi^{-1}E)^{-1}]_{pp}, and the g-factor is at least 1 by the Cauchy-Schwarz inequality. The proof gives the folding lemma and both statements. These are theorems about the discrete model with known maps; they say nothing about errors in the maps.

Proof: SENSE recovers the image exactly when every unfolding matrix has full column rank, and its g-factor is at least 1full

The setting is that of the algorithm. The image xx and the coil maps s1,…,scs_1, \ldots, s_c are n×nn \times n arrays, indexed (i,j)(i, j) with ii the phase encoding axis. The k-space of coil kk is Fu(skx)F_u(s_k x), where Fu=F/nF_u = F/n is the unitary 2D DFT, (Fuf)(κ,l)=n−1∑i,jf(i,j) e−2πi(κi+lj)/n(F_u f)(\kappa, l) = n^{-1} \sum_{i, j} f(i, j)\, e^{-2\pi i (\kappa i + l j)/n}. The reduction factor RR divides nn, m=n/Rm = n/R, and the scan keeps the rows κ=Rκ′\kappa = R \kappa' for κ′=0,…,m−1\kappa' = 0, \ldots, m - 1. Line L2 forms, for each coil, nn times the inverse DFT of size m×nm \times n of the kept rows:

ak(i,j)=nmn∑κ′=0m−1∑l=0n−1yk(Rκ′,l) e2πi(κ′i/m+lj/n),0≤i<m.a_k(i, j) = \frac{n}{m n} \sum_{\kappa'=0}^{m-1} \sum_{l=0}^{n-1} y_k(R\kappa', l)\, e^{2\pi i (\kappa' i/m + l j/n)}, \qquad 0 \le i < m.

For a folded pixel (i,j)(i, j) the unfolding matrix EE is the c×Rc \times R matrix with E[k][p]=sk(i+pm,j)E[k][p] = s_k(i + p m, j), and vp=x(i+pm,j)v_p = x(i + pm, j).

Theorem. Let Ψ\Psi be Hermitian positive definite (the identity when no covariance is given) and λ=0\lambda = 0. If EE has full column rank RR at every folded pixel, which needs R≤cR \le c, and the data have no noise, then SENSE returns xx. If the k-space samples carry noise that is independent between samples, with zero mean and covariance Ψ\Psi between the coils at each sample, the output at pixel i+pmi + pm has the noise variance R [(EHΨ−1E)−1]ppR\,[(E^H \Psi^{-1} E)^{-1}]_{pp}, and the g-factor gp=[(EHΨ−1E)−1]pp [EHΨ−1E]ppg_p = \sqrt{[(E^H \Psi^{-1} E)^{-1}]_{pp}\, [E^H \Psi^{-1} E]_{pp}} is at least 1.

Lemma 1 (folding). Without noise, ak(i,j)=∑p=0R−1sk(i+pm,j) x(i+pm,j)=(Ev)ka_k(i, j) = \sum_{p=0}^{R-1} s_k(i + pm, j)\, x(i + pm, j) = (E v)_k.

Proof. Write f=skxf = s_k x. For a kept row, yk(Rκ′,l)=n−1∑i′′,j′f(i′′,j′) e−2πi(κ′i′′/m+lj′/n)y_k(R\kappa', l) = n^{-1} \sum_{i'', j'} f(i'', j')\, e^{-2\pi i (\kappa' i''/m + l j'/n)}, because Rκ′i′′/n=κ′i′′/mR \kappa' i''/n = \kappa' i''/m. Write i′′=i′+pmi'' = i' + p m with 0≤i′<m0 \le i' < m; then e−2πiκ′i′′/m=e−2πiκ′i′/me^{-2\pi i \kappa' i''/m} = e^{-2\pi i \kappa' i'/m}, so the kept rows are n−1n^{-1} times the DFT of size m×nm \times n of the folded array ϕ(i′,j′)=∑pf(i′+pm,j′)\phi(i', j') = \sum_p f(i' + pm, j'). The inverse DFT of size m×nm \times n gives back n−1ϕn^{-1} \phi, and the factor nn in line L2 gives ϕ\phi. □\square

Lemma 2. With Ψ=LLH\Psi = L L^H (Cholesky), lines L6 and L7 solve the weighted least squares problem min⁡v(a−Ev)HΨ−1(a−Ev)\min_v (a - Ev)^H \Psi^{-1} (a - Ev). If EE has full column rank, the solution is unique and is v⋆=(EHΨ−1E)−1EHΨ−1av^\star = (E^H \Psi^{-1} E)^{-1} E^H \Psi^{-1} a.

Proof. Line L6 replaces EE and aa by L−1EL^{-1}E and L−1aL^{-1}a, and ∥L−1(a−Ev)∥2=(a−Ev)HΨ−1(a−Ev)\lVert L^{-1}(a - Ev) \rVert^2 = (a - Ev)^H \Psi^{-1}(a - Ev). The normal equations of this least squares problem are EHΨ−1E v=EHΨ−1aE^H \Psi^{-1} E\, v = E^H \Psi^{-1} a, which line L7 forms and solves. If EE has full column rank and Ψ−1\Psi^{-1} is positive definite, then wHEHΨ−1Ew=∥L−1Ew∥2>0w^H E^H \Psi^{-1} E w = \lVert L^{-1} E w \rVert^2 > 0 for w≠0w \ne 0, so the matrix is positive definite and the solution is unique. □\square

Proof of the theorem. Exactness. By Lemma 1, a=Eva = E v at each folded pixel, so a−Ev=0a - E v = 0 and vv minimizes the objective of Lemma 2 with the value 0. The minimizer is unique, so line L7 returns vv, and line L8 writes x(i+pm,j)x(i + pm, j) for p=0,…,R−1p = 0, \ldots, R - 1. The folded pixels (i,j)(i, j) with 0≤i<m0 \le i < m and the offsets pp cover every pixel exactly once, so the output is xx. A c×Rc \times R matrix has rank at most min⁡(c,R)\min(c, R), so full column rank needs R≤cR \le c.

Noise. The map from the kept samples to ak(i,j)a_k(i, j) is (1/m)(1/m) times a sum over the mnm n kept samples with weights of modulus 1. For independent samples with covariance Ψ\Psi between the coils, the folded noise vector at a pixel has the covariance mn⋅m−2 Ψ=RΨm n \cdot m^{-2}\, \Psi = R \Psi. The output is v⋆=Hav^\star = H a with H=(EHΨ−1E)−1EHΨ−1H = (E^H \Psi^{-1} E)^{-1} E^H \Psi^{-1}, so its noise covariance is H(RΨ)HH=R (EHΨ−1E)−1H (R\Psi) H^H = R\,(E^H \Psi^{-1} E)^{-1}, and the variance at pixel i+pmi + pm is the diagonal entry pp.

g-factor. Let M=EHΨ−1EM = E^H \Psi^{-1} E, positive definite, and epe_p the unit vector. By the Cauchy-Schwarz inequality,

1=(epHep)2=∣(M1/2ep)H(M−1/2ep)∣2≤(epHMep)(epHM−1ep)=[M]pp [M−1]pp,1 = (e_p^H e_p)^2 = \bigl|(M^{1/2} e_p)^H (M^{-1/2} e_p)\bigr|^2 \le (e_p^H M e_p)(e_p^H M^{-1} e_p) = [M]_{pp}\,[M^{-1}]_{pp},

so gp≥1g_p \ge 1. Equality holds if and only if M1/2epM^{1/2} e_p and M−1/2epM^{-1/2} e_p are parallel, that is, MepM e_p is a multiple of epe_p: column pp of EE is orthogonal to the other columns in the inner product ⟨u,w⟩=uHΨ−1w\langle u, w \rangle = u^H \Psi^{-1} w. □\square

Remarks.

  • With full sampling (R=1R = 1) the same model gives the variance 1/[M]pp1/[M]_{pp}, the variance of the optimal coil combination at that pixel. The ratio of the two signal to noise ratios is therefore R gp\sqrt{R}\, g_p, which is the formula of Pruessmann et al. (1999).
  • With λ>0\lambda > 0, line L7 solves (M+λI)v=EHΨ−1a(M + \lambda I) v = E^H \Psi^{-1} a, a Tikhonov problem. Its output is biased, and the theorem does not apply.
  • The theorem is about the discrete model yk=MFu(skx)y_k = M F_u(s_k x) with known maps. Errors in the maps, a field of view smaller than the object, and motion are outside it.

Complexity

In the real RAM, line L2 costs cc inverse FFTs of size m×nm \times n, O(cn2log⁡n)O(c n^2 \log n) for nn a power of two (with a direct DFT it would be O(cn3)O(c n^3) by rows and columns). Line L3 costs O(c3)O(c^3) once. The loop runs over n2/Rn^2/R folded pixels. Each one whitens R+1R + 1 vectors in O(c2)O(c^2) each, forms the normal equations in O(cR2)O(c R^2) and solves them in O(R3)O(R^3). With R≤cR \le c the loop costs O(c2n2)O(c^2 n^2), and the total is O(cn2log⁡n+c2n2)O(c n^2 \log n + c^2 n^2). The memory holds the cc folded images, O(cn2)O(c n^2). The method is not iterative.

Properties

  • Exact without noise. If every unfolding matrix has full column rank, the output is the object (theorem).
  • Linear. For fixed maps and Ψ\Psi, the output is a linear function of the data.
  • Noise. The signal to noise ratio falls by gRg\sqrt{R} against full sampling, with g≥1g \ge 1 at every pixel (theorem; Pruessmann et al. 1999). The test of this page checks the predicted variance on pure noise with a correlated Ψ\Psi within 8 percent.
  • Coil geometry sets the g-factor. For the four ring coils of the tests (32×3232 \times 32, Gaussian coils centered at distance 1.2 at the angles 20, 110, 200 and 290 degrees), the g-factor had the mean 1.342 and the maximum 2.918 at R=2R = 2, and the mean 67.3 and the maximum 393 at R=4R = 4, although the noiseless R=4R = 4 result was still exact to 1.2×10−111.2 \times 10^{-11} (measurement with the code of this page).
  • Local. Each folded pixel is a separate problem, so the work runs in parallel.

Variants and improvements

  • CG-SENSE. For non-Cartesian or irregular sampling the problem does not split into small pixel groups. CG-SENSE solves the same least squares problem with the conjugate gradient method. For uniform Cartesian sampling both give the same answer.
  • Regularized SENSE. Adding λI\lambda I, or a prior image, in line L7 lowers the noise where the g-factor is high, at the cost of bias.
  • CAIPIRINHA. Shifting the sampling pattern between the two phase encoding axes in 3D, or between slices in simultaneous multi-slice imaging, moves the aliased copies apart and lowers the g-factor (Breuer et al. 2005; see slice-GRAPPA).
  • Maps from the data. ESPIRiT estimates the maps from a calibration region, so that SENSE becomes autocalibrating.
  • k-space methods. GRAPPA and SPIRiT fill the missing k-space samples without explicit maps. SMASH (Sodickson and Manning 1997) was the first such method.

When to use it

Use SENSE for Cartesian scans with uniform undersampling when good coil maps are known, for example from a low resolution prescan or from ESPIRiT. It is fast and gives an exact answer for exact maps. Choose RR well below the number of coils that see each pixel group differently: the g-factor grows quickly as RR approaches that number. When the object is larger than the reduced field of view in a way the maps do not model, or the maps are poor, use GRAPPA, which needs no maps.

Pitfalls

  • R larger than c. With R>cR > c, the matrix of line L7 is singular, and the problem has no unique solution. The code refuses this case without regularization.
  • Wrong maps. Errors in sks_k in line L5 go straight into the output as residual aliasing. Maps from a prescan can be wrong after motion.
  • Object outside the maps. If the maps are zero, or wrong, where the object has signal, for example when the field of view of the maps is too small, line L7 places that signal in the wrong pixel.
  • High g-factor. Where the coils see the folded pixels in almost the same way, EE in line L7 is ill-conditioned, and the noise is amplified even though the noiseless result is exact.
  • Forgetting the noise covariance. Correlated coil noise with Ψ=I\Psi = I in line L3 still gives an exact noiseless result, but not the least noise.
  • Scale of the folded image. Line L2 needs the factor nn; without it the output is too small by that factor.

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.

imgkit.pyI0RawGitHub
# 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
sense.py 154 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sense/. The authors are listed in prov/7VT2V0.jsonl.

"""SENSE reconstruction for Cartesian undersampling (Pruessmann, Weiger, Scheidegger and Boesiger 1999).

Conventions: an image is a list of n rows, img[i][j]. The k-space of coil k
is y_k = F_u (s_k x) with the unitary 2D DFT F_u = F / n, in DFT order. The
scan keeps the rows kappa = 0, R, 2R, ... of the phase encoding axis (the first
index) and skips the others, with n a multiple of R. The other k-space rows of
the input are never read.

Folding: with m = n / R, the inverse DFT of size m x n of the kept rows gives
a_k(i, j) = sum_p s_k(i + p m, j) x(i + p m, j) / n, so n times it is the
folded image, the sum of the R pixels that fall on the same place. At each
folded pixel, SENSE solves the c x R weighted least squares problem
min (a - E v)^H Psi^(-1) (a - E v) with E[k][p] = s_k(i + p m, j).

Noise: if the k-space noise of the coils has the covariance Psi at each
sample, the folded noise has the covariance R Psi, and the noise covariance
of the unfolded pixels is R (E^H Psi^(-1) E)^(-1).
"""

import math
from typing import Optional, Sequence

from imgkit import dft2, idft2
from imgla import cholesky, solve

Image = list[list[complex]]


def unitary_dft2(img: Sequence[Sequence[complex]]) -> Image:
    """F_u x = F x / n for an n x n image."""
    n = len(img)
    return [[v / n for v in row] for row in dft2(img)]


def unitary_idft2(ksp: Sequence[Sequence[complex]]) -> Image:
    """F_u^H y = n idft2(y) for an n x n array."""
    n = len(ksp)
    return [[v * n for v in row] for row in idft2(ksp)]


def sense_mask(n: int, r: int) -> list[bool]:
    """True for the kept phase encoding rows kappa = 0, R, 2R, ..."""
    return [kappa % r == 0 for kappa in range(n)]


def encode(x: Image, maps: Sequence[Image], r: int) -> list[Image]:
    """The forward model: y_k = M F_u (s_k x), with the skipped rows set to 0."""
    keep = sense_mask(len(x), r)
    out = []
    for s in maps:
        ksp = unitary_dft2([[sv * xv for sv, xv in zip(srow, xrow)] for srow, xrow in zip(s, x)])
        out.append([row if keep[kappa] else [0j] * len(row) for kappa, row in enumerate(ksp)])
    return out


def encode_adjoint(y: Sequence[Image], maps: Sequence[Image], r: int) -> Image:
    """The adjoint: x = sum_k conj(s_k) F_u^H (M y_k)."""
    n = len(maps[0])
    keep = sense_mask(n, r)
    out = [[0j] * n for _ in range(n)]
    for s, yk in zip(maps, y):
        img = unitary_idft2([list(row) if keep[kappa] else [0j] * n for kappa, row in enumerate(yk)])
        for i in range(n):
            for j in range(n):
                out[i][j] += s[i][j].conjugate() * img[i][j]
    return out


def folded_images(y: Sequence[Image], r: int) -> list[Image]:
    """n times the inverse DFT of size (n/R) x n of the kept rows of each coil."""
    n = len(y[0])
    out = []
    for yk in y:
        sub = [list(yk[kappa]) for kappa in range(0, n, r)]
        out.append([[v * n for v in row] for row in idft2(sub)])
    return out


def _whitener(psi: Optional[Sequence[Sequence[complex]]], c: int):
    """A function v -> L^(-1) v with Psi = L L^H, or the identity when psi is None."""
    if psi is None:
        return lambda v: list(v)
    low = cholesky(psi)

    def apply(v):
        z = [0j] * c
        for i in range(c):
            z[i] = (v[i] - sum(low[i][k] * z[k] for k in range(i))) / low[i][i]
        return z

    return apply


def sense(
    y: Sequence[Image],
    maps: Sequence[Image],
    r: int,
    psi: Optional[Sequence[Sequence[complex]]] = None,
    lam: float = 0.0,
) -> Image:
    """Unfold the image from the kept rows of y (one n x n array per coil).

    psi is the c x c coil noise covariance (None for the identity). lam >= 0
    adds lam ||v||^2 to each small problem (Tikhonov); lam = 0 is plain SENSE
    and needs R <= c and a full column rank E at every folded pixel.
    """
    c = len(maps)
    n = len(maps[0])
    if n % r != 0:
        raise ValueError("n must be a multiple of R")
    if r > c and lam == 0.0:
        raise ValueError("SENSE needs R <= c")
    m = n // r  # @line L1
    a = folded_images(y, r)  # @line L2
    white = _whitener(psi, c)  # @line L3
    x = [[0j] * n for _ in range(n)]
    for i in range(m):  # @line L4
        for j in range(n):
            e = [[maps[k][i + p * m][j] for p in range(r)] for k in range(c)]  # @line L5
            cols = [white([e[k][p] for k in range(c)]) for p in range(r)]  # @line L6
            b = white([a[k][i][j] for k in range(c)])
            gram = [[sum(cols[p][k].conjugate() * cols[q][k] for k in range(c)) for q in range(r)] for p in range(r)]  # @line L7
            for p in range(r):
                gram[p][p] += lam
            rhs = [sum(cols[p][k].conjugate() * b[k] for k in range(c)) for p in range(r)]
            v = solve(gram, rhs)
            for p in range(r):  # @line L8
                x[i + p * m][j] = v[p]
    return x  # @line L9


def g_factor(
    maps: Sequence[Image],
    r: int,
    psi: Optional[Sequence[Sequence[complex]]] = None,
) -> list[list[float]]:
    """The g-factor map: g = sqrt([(E^H Psi^-1 E)^-1]_pp [E^H Psi^-1 E]_pp) at pixel i + p m."""
    c = len(maps)
    n = len(maps[0])
    m = n // r
    white = _whitener(psi, c)
    g = [[0.0] * n for _ in range(n)]
    eye_r = [[1.0 if p == q else 0.0 for q in range(r)] for p in range(r)]
    for i in range(m):
        for j in range(n):
            cols = [white([maps[k][i + p * m][j] for k in range(c)]) for p in range(r)]
            gram = [[sum(cols[p][k].conjugate() * cols[q][k] for k in range(c)) for q in range(r)] for p in range(r)]
            inv = solve(gram, eye_r)
            for p in range(r):
                g[i + p * m][j] = math.sqrt(max(0.0, (inv[p][p] * gram[p][p]).real))
    return g
test_sense.py 190 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sense/. The authors are listed in prov/7VT2V0.jsonl.

import cmath
import math
import random

import pytest

from imgkit import MODIFIED_SHEPP_LOGAN, ellipse_phantom, pixel_centers
from imgla import adjoint_gap, cholesky, matvec, solve
from sense import encode, encode_adjoint, g_factor, sense, unitary_idft2


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)
        phase0 = 0.9 * k
        maps.append([
            [
                math.exp(-((x - cx) ** 2 + (y - cy) ** 2) / 1.2)
                * cmath.exp(1j * (phase0 + 0.4 * x - 0.3 * y))
                for x in xs
            ]
            for y in ys
        ])
    return maps


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


def rel_err(a, b):
    num = sum(abs(u - v) ** 2 for ra, rb in zip(a, b) for u, v in zip(ra, rb))
    den = sum(abs(v) ** 2 for rb in b for v in rb)
    return math.sqrt(num / den)


@pytest.mark.parametrize("r", [2, 4])
def test_exact_without_noise(r):
    n = 32
    maps, x = ring_maps(n), phantom(n)
    y = encode(x, maps, r)
    assert rel_err(sense(y, maps, r), x) < 1e-9


def test_skipped_rows_are_not_read():
    n, r = 16, 2
    maps, x = ring_maps(n), phantom(n)
    y = encode(x, maps, r)
    rng = random.Random(3)
    for yk in y:
        for kappa in range(1, n, 2):
            yk[kappa] = [complex(rng.gauss(0, 9), rng.gauss(0, 9)) for _ in range(n)]
    assert rel_err(sense(y, maps, r), x) < 1e-9


def test_correlated_noise_covariance_keeps_exactness():
    n, r = 16, 2
    maps, x = ring_maps(n), phantom(n)
    psi = [[1.0, 0.3, 0.1j, 0.0], [0.3, 1.5, 0.2, 0.0], [-0.1j, 0.2, 0.8, 0.1], [0.0, 0.0, 0.1, 1.2]]
    y = encode(x, maps, r)
    assert rel_err(sense(y, maps, r, psi=psi), x) < 1e-9


def test_encoding_adjoint():
    n, r = 16, 2
    maps = ring_maps(n)
    rng = random.Random(5)
    x = [[complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(n)] for _ in range(n)]
    y = [[[complex(rng.gauss(0, 1), rng.gauss(0, 1)) if kappa % r == 0 else 0j for _ in range(n)]
          for kappa in range(n)] for _ in maps]
    def flat(arrs):
        return [v for a in arrs for row in a for v in row]

    def unflat(v):
        return [[[v[(k * n + i) * n + j] for j in range(n)] for i in range(n)] for k in range(len(maps))]

    gap = adjoint_gap(
        lambda v: flat(encode(v, maps, r)),
        lambda w: encode_adjoint(unflat(w), maps, r),
        x,
        flat(y),
    )
    assert gap < 1e-10


def test_matches_dense_least_squares_with_noise():
    n, r = 8, 2
    maps = ring_maps(n)
    rng = random.Random(7)
    x = phantom(n)
    y = encode(x, maps, r)
    for yk in y:
        for kappa in range(0, n, r):
            yk[kappa] = [v + complex(rng.gauss(0, 0.05), rng.gauss(0, 0.05)) for v in yk[kappa]]
    # dense normal equations of the full model
    cols = []
    for idx in range(n * n):
        e = [[0j] * n for _ in range(n)]
        e[idx // n][idx % n] = 1.0
        cols.append([v for yk in encode(e, maps, r) for row in yk for v in row])
    data = [v for yk in y for row in yk for v in row]
    gram = [[sum(a.conjugate() * b for a, b in zip(cp, cq)) for cq in cols] for cp in cols]
    rhs = [sum(a.conjugate() * b for a, b in zip(cp, data)) for cp in cols]
    xs = solve(gram, rhs)
    out = sense(y, maps, r)
    assert max(abs(out[i][j] - xs[i * n + j]) for i in range(n) for j in range(n)) < 1e-9


def test_g_factor_is_at_least_one_and_one_without_acceleration():
    n = 16
    maps = ring_maps(n)
    g1 = g_factor(maps, 1)
    assert all(abs(v - 1.0) < 1e-12 for row in g1 for v in row)
    for r in (2, 4):
        g = g_factor(maps, r)
        assert min(v for row in g for v in row) >= 1.0 - 1e-12
    assert max(v for row in g_factor(maps, 4) for v in row) > max(v for row in g_factor(maps, 2) for v in row)


def test_g_factor_two_coil_hand_example():
    a = 0.5
    maps = [[[1.0, 1.0], [a, a]], [[a, a], [1.0, 1.0]]]
    g = g_factor(maps, 2)
    assert abs(g[0][0] - (1 + a * a) / (1 - a * a)) < 1e-12


def test_noise_variance_matches_theory():
    # Linear method: reconstruct pure k-space noise. Coil noise covariance psi at each sample.
    n, r, trials = 8, 2, 300
    maps = ring_maps(n)
    psi = [[1.0, 0.2, 0.0, 0.1], [0.2, 1.0, 0.2, 0.0], [0.0, 0.2, 1.0, 0.2], [0.1, 0.0, 0.2, 1.0]]
    low = cholesky(psi)
    rng = random.Random(11)
    s = 1.0 / math.sqrt(2.0)
    acc = {1: [[0.0] * n for _ in range(n)], r: [[0.0] * n for _ in range(n)]}
    for _ in range(trials):
        w = [[[complex(rng.gauss(0, s), rng.gauss(0, s)) for _ in range(n)] for _ in range(n)] for _ in maps]
        e = [[[0j] * n for _ in range(n)] for _ in maps]
        for kappa in range(n):
            for l in range(n):
                v = matvec(low, [wk[kappa][l] for wk in w])
                for k in range(len(maps)):
                    e[k][kappa][l] = v[k]
        for rr in (1, r):
            out = sense(e, maps, rr, psi=psi)
            for i in range(n):
                for j in range(n):
                    acc[rr][i][j] += abs(out[i][j]) ** 2 / trials
    # theory: variance R [(E^H Psi^-1 E)^-1]_pp, and var_R / var_1 = R g^2
    g = g_factor(maps, r, psi)
    ratio_emp = sum(acc[r][i][j] for i in range(n) for j in range(n)) / sum(
        acc[1][i][j] * r * g[i][j] ** 2 for i in range(n) for j in range(n))
    assert abs(ratio_emp - 1.0) < 0.08
    # full sampling: the variance is 1 / (s^H Psi^-1 s)
    pred = 0.0
    for i in range(n):
        for j in range(n):
            sv = [mp[i][j] for mp in maps]
            pred += 1.0 / sum(a.conjugate() * b for a, b in zip(sv, solve(psi, sv))).real
    emp = sum(acc[1][i][j] for i in range(n) for j in range(n))
    assert abs(emp / pred - 1.0) < 0.08


def test_r_larger_than_c_is_refused():
    maps = ring_maps(8, c=2)
    y = [[[0j] * 8 for _ in range(8)] for _ in maps]
    with pytest.raises(ValueError):
        sense(y, maps, 4)


def test_full_sampling_is_coil_combination():
    n = 8
    maps, x = ring_maps(n), phantom(n)
    y = encode(x, maps, 1)
    imgs = [unitary_idft2(yk) for yk in y]
    out = sense(y, maps, 1)
    for i in range(n):
        for j in range(n):
            sv = [mp[i][j] for mp in maps]
            est = sum(a.conjugate() * im[i][j] for a, im in zip(sv, imgs)) / sum(abs(a) ** 2 for a in sv)
            assert abs(out[i][j] - est) < 1e-12

History

Sodickson and Manning showed in 1997 with SMASH that coil arrays can replace phase encoding steps. Pruessmann, Weiger, Scheidegger and Boesiger published SENSE in 1999, with the unfolding in the image domain, the use of the coil noise matrix and the g-factor. In 2001 Pruessmann, Weiger, Boernert and Boesiger extended it to any trajectory with the conjugate gradient method, the method now called CG-SENSE. Griswold and colleagues published GRAPPA, a k-space method without explicit maps, in 2002.

References

  1. 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 unfolding of Cartesian data with known sensitivities, the weighted least squares solution with the noise matrix, and the g-factor (general locator; section numbers not confirmed)
  2. Daniel K. Sodickson and Warren J. Manning, Simultaneous acquisition of spatial harmonics (SMASH), fast imaging with radiofrequency coil arrays, Magnetic Resonance in Medicine 38(4), 1997, 591 to 603, the earlier k-space method that combines coil signals to synthesize the missing spatial harmonics (general locator)
  3. 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 iterative form for any trajectory (general locator)
  4. Felix A. Breuer, Martin Blaimer, Robin M. Heidemann, Matthias F. Mueller, Mark A. Griswold and Peter M. Jakob, Controlled aliasing in parallel imaging results in higher acceleration (CAIPIRINHA) for multi-slice imaging, Magnetic Resonance in Medicine 53(3), 2005, 684 to 691, the shift of the aliased copies that lowers the g-factor (general locator)

Where this leads

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