Algorithm Search⌘K

Algorithmadvanced

SPIRiT

Also called iterative self-consistent parallel imaging.

Finds the missing multi-coil k-space samples for any sampling pattern by asking that every sample agree with a calibrated kernel over its neighbors, solved by CGLS with the acquired samples kept.

Time
O(a n c^2 q^2 + c^4 q^3 + K c^2 q n^2) worst
Space
O(c^2 q^2 + a n c q + c n^2) extra
Where
K = the number of iterations; a = the number of calibration rows; c = the number of coils; n = the side of the n x n k-space; q = the number of kernel positions per coil
Properties
deterministicnot exactnot in placeoffline
Origin
Michael Lustig, John M. Pauly, 2010

SPIRiT (iterative self-consistent parallel imaging reconstruction) fills the missing k-space samples of a multi-coil MR scan for any sampling pattern. Like GRAPPA, it fits a kernel on a fully sampled calibration region. Unlike GRAPPA, the kernel predicts each sample of each coil from all its neighbors in all coils, acquired or not. SPIRiT then asks for a full k-space that agrees with the kernel everywhere and with the data on the acquired samples, and solves this least squares problem with CGLS. Lustig and Pauly published it in 2010. The consistency residual decreases at every step (a theorem), and the result is exact when the kernel is consistent with the true k-space and the missing samples are determined.

In plain words

In the middle of k-space every sample is known, so we can learn how each sample follows from its neighbors in all coils. That rule should hold everywhere. Where samples are missing, we look for the values that make the rule hold as well as possible, while the measured samples stay as they are. GRAPPA uses the rule once, with only measured neighbors. SPIRiT uses it everywhere at once and solves for all missing values together, so it does not care which samples are missing.

The problem

The input is the multi-coil k-space yy on the acquired samples of an n×nn \times n grid, the sampling mask, which can be any pattern, and a block of aa fully sampled calibration rows at the center. The kernel size kr×kck_r \times k_c and the regularization of the fit are choices. The output is the full k-space xx of every coil, with x=yx = y on the acquired samples, that minimizes ∥(G−I)x∥2\lVert (G - I) x \rVert^2, where GG is the calibrated kernel operator. The model is yk=MFu(skx)y_k = M F_u(s_k x), but the maps are not inputs.

The algorithm

PP selects the missing samples, and PTP^{\mathsf T} puts values on them. The unknowns zz are the missing values.

  1. SPIRIT(y, mask, ACS, kernel shape, iters)
  2. 1G <- fit of each sample from its k_r x k_c neighbors in all coils, without itself, on the ACS rows
  3. 2x0 <- y on the acquired samples, 0 elsewhere
  4. 3B z = (G - I) P^T z; B^H w = P (G^H - I) w
  5. 4r <- -(G - I) x0; z <- 0; s <- B^H r; p <- s
  6. 5for t = 1, ..., iters do
  7. 6q <- B p
  8. 7alpha <- ||s||^2 / ||q||^2
  9. 8z <- z + alpha p; r <- r - alpha q
  10. 9s_new <- B^H r; p <- s_new + (||s_new||^2 / ||s||^2) p; s <- s_new
  11. 10return x0 + P^T z

Line L1 solves one small regularized least squares problem per target coil: the sources are all patch entries of all coils except the target sample itself. Line L3 defines the operator on the missing samples; it applies the kernel as a sum of shifted copies of the coil arrays. Lines L4 to L9 are CGLS for min⁡z∥Bz−r∥2\min_z \lVert B z - r \rVert^2, which is ∥(G−I)(x0+PTz)∥2\lVert (G - I)(x_0 + P^{\mathsf T} z) \rVert^2. The acquired samples never change. Each iteration applies GG once and GHG^H once.

Example

Four coils, a modified Shepp-Logan phantom, no noise, a 3×33 \times 3 kernel. The table gives the relative error of the full k-space against the truth (measurement with the code of this page). The band maps have only the image frequencies 0 and 1 on each axis; the ring maps are smooth Gaussian profiles, see coil sensitivity map.

grid maps sampling calibration rows iterations SPIRiT error zero filled
32×3232 \times 32 band every 2nd row 8 40 8.7×10−98.7 \times 10^{-9} 0.464
32×3232 \times 32 ring every 2nd row 8 40 0.080 0.466
32×3232 \times 32 band every 3rd row 10 40 0.358
16×1616 \times 16 band every 2nd row 8 20 4.8×10−94.8 \times 10^{-9}
16×1616 \times 16 ring calibration rows, then each other sample with probability 0.5 8 25 0.148 0.370

The first row is exact up to rounding, as part 3 of the theorem says. In the third row the consistency residual fell to 4×10−74 \times 10^{-7} while the error stayed at 0.358: the kernel is consistent with the truth, but other k-spaces fit as well, so the missing samples are not determined. The tests of this page run on 16×1616 \times 16 grids to keep the run time short.

Correctness

CGLS is the conjugate gradient method on the normal equations BHBz=BHr0B^H B z = B^H r_0. Its iterates minimize the residual over a growing Krylov subspace, so the consistency residual ∥(G−I)x∥\lVert (G - I) x \rVert does not increase, and the method reaches a minimizer after at most as many steps as there are missing samples. If the true k-space kk satisfies Gk=kG k = k, it is a minimizer with residual 0, and it is the only one when no nonzero k-space that is zero on the acquired samples satisfies Gv=vG v = v. A kernel with Gk=kG k = k exists, and the fit finds it, under the band-limited map model of the GRAPPA proof. The proof gives the details. These are theorems in exact arithmetic.

Proof: SPIRiT by CGLS decreases the consistency residual at every step and returns the true k-space when the kernel is consistent with it and the missing samples are determinedfull

The setting is that of the algorithm, in exact arithmetic. The unknown is the full multi-coil k-space x∈CNx \in \mathbb{C}^{N}, N=cn2N = c n^2. The kernel operator GG of line L1 is linear, (Gx)a(κ)=∑b∑dg[a][b][d] xb(κ+d)(Gx)_a(\kappa) = \sum_b \sum_{d} g[a][b][d]\, x_b(\kappa + d) with g[a][a][(0,0)]=0g[a][a][(0,0)] = 0. PP selects the missing samples, so PTzP^{\mathsf T} z puts a vector zz of missing values into a k-space that is zero on the acquired samples. x0x_0 is the data with zeros on the missing samples (line L2). Line L3 defines B=(G−I)PTB = (G - I) P^{\mathsf T}, with the adjoint BH=P(GH−I)B^H = P (G^H - I). Let r0=−(G−I)x0r_0 = -(G - I) x_0 (line L4). The method minimizes

ϕ(z)=∥(G−I)(x0+PTz)∥2=∥Bz−r0∥2\phi(z) = \lVert (G - I)(x_0 + P^{\mathsf T} z) \rVert^2 = \lVert B z - r_0 \rVert^2

by CGLS: z0=0z_0 = 0, s0=p0=BHr0s_0 = p_0 = B^H r_0, and for each step qt=Bptq_t = B p_t (line L6), αt=∥st∥2/∥qt∥2\alpha_t = \lVert s_t \rVert^2 / \lVert q_t \rVert^2 (line L7), zt+1=zt+αtptz_{t+1} = z_t + \alpha_t p_t and rt+1=rt−αtqtr_{t+1} = r_t - \alpha_t q_t (line L8), st+1=BHrt+1s_{t+1} = B^H r_{t+1} and pt+1=st+1+(∥st+1∥2/∥st∥2)ptp_{t+1} = s_{t+1} + (\lVert s_{t+1}\rVert^2/\lVert s_t \rVert^2) p_t (line L9). The output is x0+PTzx_0 + P^{\mathsf T} z (line L10).

Theorem.

  1. The residual rt=r0−Bztr_t = r_0 - B z_t satisfies ∥rt+1∥≤∥rt∥\lVert r_{t+1} \rVert \le \lVert r_t \rVert for every step, and ztz_t minimizes ϕ\phi over the Krylov subspace Kt=span⁡{b,Ab,…,At−1b}\mathcal{K}_t = \operatorname{span}\{b, Ab, \ldots, A^{t-1} b\} with A=BHBA = B^H B and b=BHr0b = B^H r_0.
  2. After at most MM steps, where MM is the number of missing samples, ztz_t minimizes ϕ\phi over CM\mathbb{C}^M.
  3. Let kk be the true full k-space, equal to the data on the acquired samples. If Gk=kG k = k, then z†=Pkz^\dagger = P k is a minimizer with ϕ(z†)=0\phi(z^\dagger) = 0. If moreover BB has full column rank, that is, no nonzero k-space that vanishes on the acquired samples satisfies Gv=vG v = v, then z†z^\dagger is the only minimizer, and the method returns kk after at most MM steps.

Proof of 1 and 2. The recurrences are those of the conjugate gradient method for Az=bA z = b, with the residual st=b−Azt=BHrts_t = b - A z_t = B^H r_t and ⟨pt,Apt⟩=∥Bpt∥2=∥qt∥2\langle p_t, A p_t \rangle = \lVert B p_t \rVert^2 = \lVert q_t \rVert^2; the identity st=BHrts_t = B^H r_t holds by induction, since BHrt+1=BHrt−αtAptB^H r_{t+1} = B^H r_t - \alpha_t A p_t. The vector bb lies in the range of BHB^H, which is the range of AA, and so does every Krylov vector. On that range, AA is positive definite. The lemma in the CG-SENSE proof, restricted to the range of AA, shows that the residuals sts_t are mutually orthogonal and that ztz_t minimizes (z−z⋆)HA(z−z⋆)=∥B(z−z⋆)∥2(z - z^\star)^H A (z - z^\star) = \lVert B(z - z^\star) \rVert^2 over Kt\mathcal{K}_t, where z⋆z^\star is the least squares solution in the range of AA. For any zz,

ϕ(z)=∥B(z−z⋆)∥2+∥Bz⋆−r0∥2,\phi(z) = \lVert B(z - z^\star) \rVert^2 + \lVert B z^\star - r_0 \rVert^2,

because Bz⋆−r0B z^\star - r_0 is orthogonal to the range of BB (the normal equations). So ztz_t also minimizes ϕ\phi over Kt\mathcal{K}_t, and since Kt⊆Kt+1\mathcal{K}_t \subseteq \mathcal{K}_{t+1}, ϕ(zt+1)≤ϕ(zt)\phi(z_{t+1}) \le \phi(z_t), which is ∥rt+1∥≤∥rt∥\lVert r_{t+1} \rVert \le \lVert r_t \rVert. The nonzero orthogonal residuals sts_t are at most MM in number, so some sts_t with t≤Mt \le M is 0. Then ztz_t solves the normal equations and minimizes ϕ\phi over CM\mathbb{C}^M. □\square

Proof of 3. Since k=x0+PTPkk = x_0 + P^{\mathsf T} P k, we get ϕ(Pk)=∥(G−I)k∥2=0\phi(P k) = \lVert (G - I) k \rVert^2 = 0, the least value of ϕ\phi. If BB has full column rank, ϕ\phi is strictly convex and has one minimizer. By part 2 the method finds it, and line L10 returns x0+PTPk=kx_0 + P^{\mathsf T} P k = k. □\square

Lemma (a consistent kernel exists). Assume the coil k-space satisfies the model (H1) of the GRAPPA proof: xb(κ)=∑e∈Hhb(e)X(κ−e)x_b(\kappa) = \sum_{e \in H} h_b(e) X(\kappa - e) for a finite HH. If for every coil aa the target xa(κ)x_a(\kappa) lies in the span of the other patch entries as functions of the object samples, and the calibration patches contain enough independent object patterns (full column rank of the matrix of object samples), then every exact solution of the fit of line L1 satisfies Gk=kG k = k on the whole k-space.

Proof. This is the argument of the GRAPPA proof with the sources {(b,d):d in the patch}∖{(a,(0,0))}\{(b, d) : d \text{ in the patch}\} \setminus \{(a, (0,0))\} for target coil aa: an exact kernel exists, the fit has the value 0, every solution agrees with an exact kernel on the object samples, and so it predicts every xa(κ)x_a(\kappa) exactly. □\square

Remarks.

  • The condition on BB in part 3 can fail even with a consistent kernel. For the band maps of the tests on a 32×3232 \times 32 grid with uniform sampling at R=3R = 3, the residual fell to 4×10−74 \times 10^{-7} while the error stayed at 0.36, so BB was singular or nearly so; random sampling of the same maps on a 16×1616 \times 16 grid left the error at 0.14 (measurements). Uniform sampling with R=2R = 2 gave the exact answer.
  • With the small Tikhonov term of the code, the kernel is close to an exact one, and the result has a small error.
  • Part 1 is a monotonicity theorem for the consistency residual only. The error against the true k-space is not proved monotone, and the tests do not check it.
  • CGLS and LSQR give the same iterates in exact arithmetic. With noisy data the objective treats the acquired samples as exact; Lustig and Pauly (2010) also give a form with a data weight.

Complexity

In the real RAM, with q=krkcq = k_r k_c: line L1 forms one Gram matrix of size cqc q from about ana n patches, O(anc2q2)O(a n c^2 q^2), and solves cc systems of size cq−1c q - 1, O(c4q3)O(c^4 q^3). One application of GG or GHG^H costs O(c2qn2)O(c^2 q n^2), so each iteration costs O(c2qn2)O(c^2 q n^2), and KK iterations cost O(Kc2qn2)O(K c^2 q n^2). Applying the kernel in the image domain, as a pixelwise c×cc \times c matrix after FFTs, costs O(c2n2+cn2log⁡n)O(c^2 n^2 + c n^2 \log n) per application instead. The memory holds the Gram matrix, the patches and a few k-space arrays, O(c2q2+ancq+cn2)O(c^2 q^2 + a n c q + c n^2). The number of iterations depends on the conditioning of BB; the bound of at most one step per missing sample holds only in exact arithmetic.

Properties

  • Monotone consistency residual. ∥(G−I)xt∥\lVert (G - I) x_t \rVert does not increase (theorem). The test of this page checks it at every step. The error against the truth is not proved monotone.
  • Exact under consistency and uniqueness. If Gk=kG k = k and the missing samples are determined, the method returns kk (theorem). The test checks it for band maps at R=2R = 2 with junk in the missing samples, which are never read.
  • Any sampling. The kernel uses all neighbors, so the same kernel works for uniform, random, variable density and, with gridding, non-Cartesian patterns.
  • Coil images out. Like GRAPPA, the method returns one k-space per coil, and a coil combination follows.
  • Linear. For a fixed kernel and a fixed number of iterations, the output is linear in the data.

Variants and improvements

  • Data weighting. Lustig and Pauly (2010) also give a form where the data term ∥Mx−y∥2\lVert M x - y \rVert^2 is weighted against the consistency term, for noisy data.
  • L1-SPIRiT. Adding a sparsity term, as in compressed sensing MRI, regularizes the solution; Murphy et al. (2012) made it fast enough for clinical use.
  • Non-Cartesian SPIRiT. With a gridding operator in the data term, the consistency is imposed on a Cartesian grid while the data are on a trajectory.
  • ESPIRiT. ESPIRiT shows that the consistency condition Gx=xG x = x is the same as a set of coil maps, which turns SPIRiT into a SENSE-type problem with maps from the calibration data.
  • Low-rank methods. Structured low-rank methods such as LORAKS impose the null space of the calibration matrix directly, without a fitted kernel.
  • Image space methods. CG-SENSE solves the same kind of least squares problem with explicit maps.

When to use it

Use SPIRiT when the sampling is not uniform, for example random or variable density patterns for compressed sensing, or when the coil maps are hard to estimate, and when a fully sampled calibration region is available. It is a natural base for combination with sparsity. For uniform Cartesian undersampling, GRAPPA is faster and gives a similar result. When good maps are available or can be computed with ESPIRiT, a SENSE-type reconstruction has fewer unknowns.

Pitfalls

  • Including the target in the kernel. If line L1 lets a sample predict itself, the fit returns the identity, and G−I=0G - I = 0: every k-space is consistent.
  • Too few calibration rows. As for GRAPPA, an underdetermined fit in line L1 gives a kernel that fits the calibration region and fails elsewhere.
  • Non-unique solution. If BB has a null space, the consistency residual goes to zero while the error stays large (the third row of the example). More samples or a prior, such as sparsity, fix it.
  • Overwriting the data. The unknowns are only the missing samples (line L3). Letting CGLS change the acquired samples loses the data constraint.
  • Wrong adjoint. Line L3 needs the exact adjoint of GG, with the shift −d-d and the conjugated weights. A wrong adjoint breaks the monotone residual.
  • Running long on noisy data. With noise, the late iterations fit noise into the missing samples; stop early or add a data weight or a prior.

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
spirit.py 176 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/spirit/. The authors are listed in prov/VXHK1N.jsonl.

"""SPIRiT: iterative self-consistent parallel imaging reconstruction (Lustig and Pauly 2010).

Conventions: the k-space of coil k is an n x n array in DFT order, rows first,
and rows and columns wrap around as in the DFT. mask[kappa][l] is True where
the sample was acquired; the sampling pattern may be any pattern. A block of
fully sampled center rows (the calibration region) gives the kernel.

The kernel G predicts each sample of coil a from the samples of all coils in
a kr x kc patch around it, without the sample itself:

    (G x)_a(kappa) = sum_b sum_d g[a][b][d] x_b(kappa + d),   g[a][a][0] = 0.

SPIRiT asks for a k-space x that is consistent with the kernel, x = G x, and
with the data, x = y on the acquired samples. With the data kept exactly,
the unknowns z are the missing samples, and the method minimizes
||(G - I)(x0 + P^T z)||^2 by CGLS (conjugate gradients on the normal
equations), where x0 is the zero-filled data and P^T puts z on the missing
samples. The kernel size, the calibration region and the small
regularization of the fit are choices.

Inside, each coil is a flat row-major list of n * n samples, and a shift by
d is a fixed permutation of the indices.
"""

import math
from typing import Callable, Optional, Sequence

from imgla import solve

Array = list[list[complex]]
Kernel = list[list[dict[tuple[int, int], complex]]]
Flat = list[list[complex]]


def kernel_offsets(kr: int, kc: int) -> list[tuple[int, int]]:
    """The patch offsets (dr, dc), centered on (0, 0)."""
    return [(dr, dc) for dr in range(-(kr // 2), kr - kr // 2) for dc in range(-(kc // 2), kc - kc // 2)]


def calib_rows(n: int, acs: int) -> list[int]:
    """DFT indices of the acs center rows, signed frequencies -acs/2 .. acs/2 - 1, in order."""
    return [(f + n) % n for f in range(-(acs // 2), acs - acs // 2)]


def calibrate(ksp: Sequence[Array], acs: int, kr: int = 3, kc: int = 3, lam: float = 1e-8) -> Kernel:
    """Fit g[a][b][d] by regularized least squares on the patches inside the calibration rows."""
    c, n = len(ksp), len(ksp[0])
    offs = kernel_offsets(kr, kc)
    rows = calib_rows(n, acs)
    lo, hi = -min(o[0] for o in offs), max(o[0] for o in offs)
    cols = [(b, d) for b in range(c) for d in offs]
    patches = []
    for t in range(lo, len(rows) - hi):
        kappa = rows[t]
        for l in range(n):
            patches.append([ksp[b][(kappa + d[0]) % n][(l + d[1]) % n] for b, d in cols])
    m = len(cols)
    gram = [[sum(p[i].conjugate() * p[j] for p in patches) for j in range(m)] for i in range(m)]
    reg = lam * sum(gram[i][i].real for i in range(m)) / m
    g: Kernel = []
    for a in range(c):
        target = cols.index((a, (0, 0)))
        keep = [i for i in range(m) if i != target]
        sub = [[gram[i][j] + (reg if i == j else 0.0) for j in keep] for i in keep]
        rhs = [gram[i][target] for i in keep]
        w = solve(sub, rhs)
        row = [dict() for _ in range(c)]
        for i, wi in zip(keep, w):
            b, d = cols[i]
            row[b][d] = wi
        g.append(row)
    return g


def _perm(n: int, dr: int, dc: int) -> list[int]:
    """Indices with out[kappa * n + l] = x[((kappa + dr) % n) * n + (l + dc) % n]."""
    return [((kappa + dr) % n) * n + (l + dc) % n for kappa in range(n) for l in range(n)]


def _g_flat(x: Flat, g: Kernel, n: int, adjoint: bool = False) -> Flat:
    """G x (or G^H x) on flat coils."""
    c = len(x)
    offs = sorted({d for row in g for gab in row for d in gab})
    out = [[0j] * (n * n) for _ in range(c)]
    for d in offs:
        # G: shift by d. G^H: shift by -d, (G^H y)_a(kappa) = sum_b sum_d conj(g[b][a][d]) y_b(kappa - d).
        perm = _perm(n, -d[0], -d[1]) if adjoint else _perm(n, d[0], d[1])
        for b in range(c):
            src = None
            for a in range(c):
                w = g[b][a].get(d) if adjoint else g[a][b].get(d)
                if w is None:
                    continue
                if adjoint:
                    w = w.conjugate()
                if src is None:
                    xb = x[b]
                    src = [xb[i] for i in perm]
                out[a] = [u + w * v for u, v in zip(out[a], src)]
    return out


def _flatten(x: Sequence[Array]) -> Flat:
    return [[v for row in a for v in row] for a in x]


def _unflatten(x: Flat, n: int) -> list[Array]:
    return [[a[i * n:(i + 1) * n] for i in range(n)] for a in x]


def apply_g(x: Sequence[Array], g: Kernel) -> list[Array]:
    """(G x)_a(kappa) = sum_b sum_d g[a][b][d] x_b(kappa + d)."""
    n = len(x[0])
    return _unflatten(_g_flat(_flatten(x), g, n), n)


def apply_g_adjoint(y: Sequence[Array], g: Kernel) -> list[Array]:
    """(G^H y)_b(kappa) = sum_a sum_d conj(g[a][b][d]) y_a(kappa - d)."""
    n = len(y[0])
    return _unflatten(_g_flat(_flatten(y), g, n, adjoint=True), n)


def _norm2(x: Flat) -> float:
    return sum(abs(v) ** 2 for a in x for v in a)


def spirit(
    y: Sequence[Array],
    mask: Sequence[Sequence[bool]],
    acs: int,
    iters: int,
    kr: int = 3,
    kc: int = 3,
    lam: float = 1e-8,
    g: Optional[Kernel] = None,
    callback: Optional[Callable[[int, float], None]] = None,
) -> list[Array]:
    """Return the full k-space of every coil. y holds the acquired samples; the others are never read.

    callback(t, ||r||) sees the residual norm ||(G - I) x|| after each iteration.
    """
    n = len(y[0])
    if g is None:
        g = calibrate(y, acs, kr, kc, lam)  # @line L1
    mflat = [mk for mrow in mask for mk in mrow]
    x0 = [[v if mk else 0j for v, mk in zip(a, mflat)] for a in _flatten(y)]  # @line L2

    def op(z: Flat) -> Flat:  # B z = (G - I) P^T z, with z stored as full arrays that are 0 on the acquired samples  # @line L3
        return [[u - v for u, v in zip(ga, za)] for ga, za in zip(_g_flat(z, g, n), z)]

    def op_h(w: Flat) -> Flat:  # B^H w = P (G^H - I) w
        return [[0j if mk else u - v for u, v, mk in zip(ga, wa, mflat)] for ga, wa in zip(_g_flat(w, g, n, True), w)]

    r = [[v - u for u, v in zip(ga, xa)] for ga, xa in zip(_g_flat(x0, g, n), x0)]  # @line L4
    z = [[0j] * (n * n) for _ in x0]
    s = op_h(r)
    p = s
    gamma = _norm2(s)
    for t in range(iters):  # @line L5
        if gamma == 0.0:
            break
        q = op(p)  # @line L6
        alpha = gamma / _norm2(q)  # @line L7
        z = [[u + alpha * v for u, v in zip(za, pa)] for za, pa in zip(z, p)]  # @line L8
        r = [[u - alpha * v for u, v in zip(ra, qa)] for ra, qa in zip(r, q)]
        s = op_h(r)  # @line L9
        gamma_new = _norm2(s)
        beta = gamma_new / gamma
        p = [[u + beta * v for u, v in zip(sa, pa)] for sa, pa in zip(s, p)]
        gamma = gamma_new
        if callback is not None:
            callback(t + 1, math.sqrt(_norm2(r)))
    return _unflatten([[u + v for u, v in zip(xa, za)] for xa, za in zip(x0, z)], n)  # @line L10
test_spirit.py 122 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/spirit/. The authors are listed in prov/VXHK1N.jsonl.

import cmath
import functools
import math
import random

from imgkit import MODIFIED_SHEPP_LOGAN, dft2, ellipse_phantom, pixel_centers
from imgla import adjoint_gap
from spirit import apply_g, apply_g_adjoint, calib_rows, calibrate, spirit

N = 16
ACS = 8
BAND = [(0.0, 0.8, 4, 0.3, 16), (1.0, 0.8, 28, 0.2, 12), (2.0, 0.3, 16, 0.8, 4), (-1.5, 0.25, 20, 0.8, 28)]


def band_maps(n):
    """Coil maps with image frequencies 0 and 1 on each axis: a 3 x 3 kernel can be exact."""
    out = []
    for psi, a, col, b, row in BAND:
        u, v = 2 * math.pi * col / n, 2 * math.pi * row / n
        out.append([[cmath.exp(1j * psi) * (1 + a * cmath.exp(1j * (2 * math.pi * j / n - u)))
                     * (1 + b * cmath.exp(1j * (2 * math.pi * i / n - v))) for j in range(n)] for i in range(n)])
    return out


def ring_maps(n, c=4):
    """Smooth Gaussian coil profiles around the object, with a phase ramp."""
    xs, ys = pixel_centers(n)
    maps = []
    for k in range(c):
        ang = math.radians(20 + 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 ksp_of(maps, img):
    n = len(img)
    return [[[v / n for v in row] for row in dft2([[s * p for s, p in zip(sr, pr)] for sr, pr in zip(mp, img)])] for mp in maps]


def rel(a, b):
    num = sum(abs(x - y) ** 2 for aa, bb in zip(a, b) for ra, rb in zip(aa, bb) for x, y in zip(ra, rb))
    den = sum(abs(y) ** 2 for bb in b for rb in bb for y in rb)
    return math.sqrt(num / den)


def keep(k, mask, fill=0j):
    return [[[v if m else fill for v, m in zip(row, mrow)] for row, mrow in zip(a, mask)] for a in k]


@functools.lru_cache(maxsize=None)
def band_case():
    k = ksp_of(band_maps(N), ellipse_phantom(N, MODIFIED_SHEPP_LOGAN))
    cal = set(calib_rows(N, ACS))
    mask = [[(kap % 2 == 0) or (kap in cal)] * N for kap in range(N)]
    return k, mask


@functools.lru_cache(maxsize=None)
def ring_random_case():
    k = ksp_of(ring_maps(N), ellipse_phantom(N, MODIFIED_SHEPP_LOGAN))
    cal = set(calib_rows(N, ACS))
    rng = random.Random(5)
    mask = [[(kap in cal) or rng.random() < 0.5 for _ in range(N)] for kap in range(N)]
    y = keep(k, mask)
    hist = []
    out = spirit(y, mask, ACS, 25, callback=lambda t, r: hist.append(r))
    return k, mask, y, out, hist


def test_exact_recovery_uniform_r2_and_missing_samples_not_read():
    k, mask = band_case()
    y = keep(k, mask, fill=1e6 + 1e6j)  # junk on the missing samples
    out = spirit(y, mask, ACS, 25)
    assert rel(out, k) < 1e-6
    for a in range(4):
        for kap in range(N):
            for l in range(N):
                if mask[kap][l]:
                    assert out[a][kap][l] == k[a][kap][l]


def test_kernel_leaves_out_the_target_and_truth_is_consistent():
    k, mask = band_case()
    g = calibrate(keep(k, mask), ACS)
    for a in range(4):
        assert (0, 0) not in g[a][a]
        assert (0, 0) in g[a][(a + 1) % 4]
    assert rel(apply_g(k, g), k) < 1e-6


def test_adjoint_of_g():
    k, mask = band_case()
    g = calibrate(keep(k, mask), ACS)
    rng = random.Random(3)

    def rnd():
        return [[[complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(N)] for _ in range(N)] for _ in range(4)]

    def flat(f):
        return lambda v: [w for a in f([[v[(c * N + i) * N:(c * N + i + 1) * N] for i in range(N)] for c in range(4)])
                          for row in a for w in row]

    x = [w for a in rnd() for row in a for w in row]
    y = [w for a in rnd() for row in a for w in row]
    assert adjoint_gap(flat(lambda u: apply_g(u, g)), flat(lambda u: apply_g_adjoint(u, g)), x, y) < 1e-12


def test_random_sampling_ring_maps_beats_zero_filling():
    k, mask, y, out, _ = ring_random_case()
    assert rel(out, k) < 0.5 * rel(y, k)


def test_cgls_residual_does_not_increase():
    _, _, _, _, hist = ring_random_case()
    assert len(hist) == 25
    assert all(b <= a * (1 + 1e-12) for a, b in zip(hist, hist[1:]))
    assert hist[-1] < 0.2 * hist[0]

History

Griswold and colleagues published GRAPPA in 2002, with a kernel over the acquired neighbors only. Lustig and Pauly published SPIRiT in 2010: a kernel over all neighbors, a consistency equation on the whole k-space, and an iterative solution that works for any sampling, with sparsity priors as an option. Murphy and colleagues made L1-SPIRiT fast in 2012, and Uecker and colleagues explained the consistency condition through coil maps with ESPIRiT in 2014.

References

  1. Michael Lustig and John M. Pauly, SPIRiT, iterative self-consistent parallel imaging reconstruction from arbitrary k-space, Magnetic Resonance in Medicine 64(2), 2010, 457 to 471, the calibration consistency equation x = G x, the data consistency constraint, and the conjugate gradient solution (general locator; section and equation numbers not confirmed)
  2. Mark A. Griswold, Peter M. Jakob, Robin M. Heidemann, Mathias Nittka, Vladimir Jellus, Jianmin Wang, Berthold Kiefer and Axel Haase, Generalized autocalibrating partially parallel acquisitions (GRAPPA), Magnetic Resonance in Medicine 47(6), 2002, 1202 to 1210, the k-space kernel fitted on autocalibration data that SPIRiT generalizes (general locator)
  3. 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 on the normal equations of a least squares problem, the form now called CGLS (general locator)
  4. Mark Murphy, Marcus Alley, James Demmel, Kurt Keutzer, Shreyas Vasanawala and Michael Lustig, Fast l1-SPIRiT compressed sensing parallel imaging MRI, scalable parallel implementation and clinically feasible runtime, IEEE Transactions on Medical Imaging 31(6), 2012, 1250 to 1262, the combination of SPIRiT with a sparsity term and a fast parallel implementation (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