Algorithmresearch
Slice-GRAPPA
Also called simultaneous multi-slice GRAPPA.
Separates slices that were excited at the same time: one GRAPPA-type kernel per slice maps the collapsed k-space of all coils to the k-space of that slice, fitted on single-slice calibration data.
- Solves
- MRI reconstruction
- Time
- O(S (a n c^2 q^2 + c^3 q^3 + c^2 q n^2)) worst
- Space
- O(c^2 q^2 + a n c q + S c n^2) extra
- Where
- S = the number of slices; 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
- Model
- Real RAM
- Properties
- deterministicnot exactnot in placeoffline
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Kawin Setsompop, Borjan A. Gagoski, Jonathan R. Polimeni, Thomas Witzel, Van J. Wedeen, Lawrence L. Wald, 2012
Slice-GRAPPA reconstructs simultaneous multi-slice (SMS) MR data. The scan excites slices at once, so each coil records the sum of their k-spaces, the collapsed k-space. For each slice, a small kernel maps a patch of the collapsed k-space of all coils to the k-space sample of every coil of that slice. The kernel is fitted by least squares on single-slice calibration data, summed into a synthetic collapsed k-space. With blipped CAIPI, each slice is shifted by a fraction of the field of view, so the slices overlap less in the coil images and the separation is better conditioned. Setsompop and colleagues published the method in 2012. It extends GRAPPA from skipped lines to stacked slices.
In plain words
Several slices are imaged at once, and each coil hears all of them added together. Each coil sits closer to some slices and farther from others, so it hears them with different loudness, in a way that changes smoothly over the image. Slice-GRAPPA learns, from separate short scans of each slice, a recipe that pulls one slice out of the mix. Shifting one slice by half the picture before mixing helps, because then two places with different coil loudness overlap instead of two places with almost the same loudness.
The problem
The input is the collapsed k-space of each coil on an grid, the shifts in rows, and calibration k-space of each slice alone on a block of center rows. is the k-space of coil of slice after the CAIPI shift, that is, with row multiplied by . The output is for every slice and coil. The kernel size , the calibration size and the regularization are choices.
The algorithm
SLICE-GRAPPA(y, calib, Delta, kernel shape)- 1
y_cal <- sum over z of the shifted calibration k-space of slice z ▷ synthetic collapsed data - 2
for each slice z do - 3
collect patches u(kappa) of y_cal for kappa in the calibration rows, with the targets (shifted calibration of slice z at kappa) for every coil- 4
W_z <- least squares solution of U W = Y (small Tikhonov term) - 5
for each kappa do - 6
u <- patch of y around kappa (all coils, k_r x k_c) - 7
x~_{z,a}(kappa) <- sum_s u_s W_z[s][a] for every coil a - 8
x_{z,a} <- remove the shift Delta_z from x~_{z,a} - 9
return x
Line L1 builds collapsed calibration data with the same shifts as the scan, so the kernel learns to undo exactly that mixing. Lines L3 and L4 are the fit of GRAPPA, with all collapsed neighbors as sources and one slice as target. Line L7 is a convolution of the collapsed k-space with the kernel. Line L8 multiplies row by . The code handles SMS without in-plane undersampling; with in-plane acceleration, a GRAPPA step fills the missing lines after the separation.
Example
Two slices, a modified Shepp-Logan phantom in slice 0 and a disk of radius 0.7 with a darker inner disk in slice 1, four coils, no noise. The band maps have only the image frequencies 0 and 1 on each axis; the ring maps are smooth Gaussian profiles, with the ring turned by 20 degrees in slice 0 and by 65 degrees in slice 1. The table gives the relative k-space error of each slice after separation, with a kernel and the regularization times the mean diagonal (measurement with the code of this page).
| maps | CAIPI shift | calibration rows | error slice 0 | error slice 1 |
|---|---|---|---|---|
| band | 0 | 16 | ||
| band | 16 | |||
| ring | 0 | 12 | 0.094 | 0.045 |
| ring | 0 | 16 | 0.087 | 0.042 |
| ring | 12 | 0.051 | 0.025 | |
| ring | 16 | 0.047 | 0.023 | |
| ring | 24 | 0.046 | 0.022 |
For the band maps the separation is exact up to the regularization, as the theorem says. For the ring maps the half field of view shift halves the error, and more calibration rows help little.
Correctness
The CAIPI shift of an image by a whole number of rows keeps the coil maps band-limited with the same support, only with new phases. So, as for GRAPPA, every collapsed source and every target is a linear function of the object samples of all slices in a small window. If the target of one slice lies in the span of the collapsed sources, and the calibration data contain enough independent patterns, every exact solution of the fit gives the exact slice at every k-space position. The proof gives the details. This is a theorem about maps with a finite k-space support and integer shifts. For real coils the leakage between slices is a measurement.
Proof: Slice-GRAPPA separates the slices exactly when the coil maps have a finite k-space support that the kernel spansfull
The setting is that of the algorithm, in exact arithmetic and with (any exact solution of the normal equations of line L4). There are slices and coils. The k-space of coil of slice is on , with the unitary DFT. The shifts are integers. The CAIPI shift of line L1 multiplies row by , which is the k-space of the slice image moved by rows, . Write for the shifted k-space. The collapsed data are
The kernel of slice uses the offsets of a patch and predicts . Line L8 undoes the shift.
Model (H1). For each slice there are a finite set and numbers with , where is the k-space of the object of slice . This holds when the maps of every slice are trigonometric polynomials with image frequencies in .
Lemma 1. Under (H1), the shifted k-space also satisfies (H1) with the same : , where is the k-space of the shifted object and .
Proof. Multiply (H1) by . The first factor turns into , and the second goes into the coefficient. Both factors are periodic in with period because is an integer.
Let . The unknowns near are the numbers . By Lemma 1, each source is with , and the target is with if and 0 otherwise.
Theorem. Assume (H1) and integer shifts. Fix a slice , and suppose:
- (span) every row of lies in the row space of ;
- (rich calibration) the matrix whose rows are , for the calibration positions of line L3, has full column rank .
Then line L7 gives for every coil and every , and line L8 returns .
Proof. The calibration of lines L1 to L3 sums the shifted single-slice calibration data into a synthetic collapsed k-space, so its patches are , and the targets of slice are . The rest is the argument of the GRAPPA proof: by the span assumption an exact with exists, so the least squares fit has the value 0, every solution satisfies , and full column rank of gives . Applied to the collapsed data at any , the kernel then returns . Line L8 multiplies by , which undoes the shift.
Remarks.
- The kernel must cancel the other slices exactly. The span assumption therefore needs more sources than for in-plane GRAPPA: for the band maps of the tests (), a kernel, two slices and four coils, there are 36 sources for unknowns. The tests find the error below with the small regularization of the code, which is consistent with the assumption; the rank is not proved here.
- The theorem does not need a CAIPI shift. The shift changes the conditioning of the fit and the noise of the result: with the shift, the aliased copies of the slices fall on different coil profiles. The gain is a measurement.
- With a non-integer shift, the phase ramp is not periodic on the grid, and Lemma 1 fails.
- For real coils, (H1) is an approximation, and the slice leakage is a measurement.
Complexity
In the real RAM, with and sources: line L1 costs . For each slice, the fit of lines L3 and L4 costs to form the normal equations and to solve them, and lines L5 to L7 cost . The total is . Image domain application of the kernel with FFTs reduces the last term to per slice. The memory holds the normal equations, the calibration patches and the output, .
Properties
- Exact for band-limited maps. Under the span and calibration assumptions, the output is the k-space of each slice (theorem).
- CAIPI lowers the noise and the leakage. Shifting the slices against each other makes the coil profiles of overlapping pixels more different. For the ring maps of the example, the shift by halved the error (measurement). Setsompop et al. (2012) report lower g-factors with blipped CAIPI on in vivo data (measurement).
- No SNR loss from fewer samples. SMS does not skip k-space samples, so there is no loss; the cost is the g-factor of the separation.
- Slice leakage. The fit minimizes the error of the target slice on the calibration data. It does not force the contribution of the other slices to zero, so signal from one slice can leak into another (Cauley et al. 2014).
- Linear. For a fixed kernel, the output is linear in the data.
Variants and improvements
- Split slice-GRAPPA. Cauley et al. (2014) fit the kernel so that it also cancels the other slices on their own calibration data, which reduces the leakage at a small cost in noise.
- SENSE for SMS. With coil maps of each slice, the separation is a SENSE problem with the slices as the folded pixels (Larkman et al. 2001).
- CAIPIRINHA. Breuer et al. (2005) shifted the slices by alternating the phase of the excitation from line to line; blipped CAIPI does the same in echo planar imaging with gradient blips.
- In-plane acceleration. SMS is often combined with in-plane undersampling; the slices are separated first, then GRAPPA fills the missing lines.
- Iterative methods. SPIRiT and other consistency methods can include the slice dimension.
When to use it
Use slice-GRAPPA for simultaneous multi-slice echo planar imaging, as in functional MRI and diffusion MRI, where many slices must be acquired in a short time and the k-space of each slice is already sampled as fast as the hardware allows. Use a CAIPI shift whenever the sequence allows it. Collect a single-slice calibration scan with the same contrast and geometry. For quantitative studies of activation in neighboring slices, check the leakage, or use split slice-GRAPPA.
Pitfalls
- Calibration without the shift. If line L1 sums the calibration slices without the CAIPI shifts of the scan, the kernel learns a different mixing and fails.
- Forgetting to undo the shift. Without line L8, each slice is shifted by rows.
- Slices with the same coil profiles. If the slices are close together along the coil axis, the coils hear them alike, and the separation is ill-conditioned even with CAIPI.
- Calibration from a different scan. Motion or different contrast between the calibration scan and the SMS scan makes the kernel wrong.
- Leakage taken for activation. In fMRI, a signal from one slice that leaks into another can look like activation there.
- Non-integer shifts. A shift that is not a whole number of rows on the grid does not move the image periodically, and the model of the proof fails.
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.
# 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
slice_grappa.py 110 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/slice-grappa/. The authors are listed in prov/863VBG.jsonl.
"""Slice-GRAPPA for simultaneous multi-slice imaging (Setsompop et al. 2012).
Conventions: the k-space of coil k of one slice is an n x n array in DFT
order, rows kappa (phase encoding) first, with the unitary DFT F / n. A scan
excites S slices at once, so each coil records the sum of the k-space of the
slices. With blipped CAIPI, slice z is shifted by Delta_z rows in the image
(a phase ramp exp(-2 pi i kappa Delta_z / n) on the k-space rows), so the
slices overlap less in the collapsed image.
Slice-GRAPPA fits one kernel per slice. The kernel maps a patch of the
collapsed k-space of all coils to the k-space sample of every coil of that
slice. The fit uses single-slice calibration data of each slice, summed into
a synthetic collapsed calibration. The kernel size (kr x kc), the calibration
rows and the small regularization are choices.
"""
import cmath
import math
from typing import Sequence
from imgla import solve
Array = list[list[complex]]
def caipi_shift(ksp: Array, shift: float) -> Array:
"""Shift the image by `shift` rows: multiply row kappa by exp(-2 pi i kappa shift / n)."""
n = len(ksp)
out = []
for kappa, row in enumerate(ksp):
ph = cmath.exp(-2j * math.pi * kappa * shift / n)
out.append([v * ph for v in row])
return out
def collapse(slices: Sequence[Sequence[Array]], shifts: Sequence[float]) -> list[Array]:
"""The collapsed k-space of each coil: the sum over slices of the shifted slice k-space."""
c, n = len(slices[0]), len(slices[0][0])
out = [[[0j] * n for _ in range(n)] for _ in range(c)]
for sl, d in zip(slices, shifts):
for k in range(c):
sh = caipi_shift(sl[k], d)
for kappa in range(n):
row, src = out[k][kappa], sh[kappa]
for l in range(n):
row[l] += src[l]
return out
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 _offsets(kr: int, kc: int) -> list[tuple[int, int]]:
return [(dr, dc) for dr in range(-(kr // 2), kr - kr // 2) for dc in range(-(kc // 2), kc - kc // 2)]
def _patch(ksp: Sequence[Array], kappa: int, l: int, offs) -> list[complex]:
n = len(ksp[0])
return [ksp[k][(kappa + dr) % n][(l + dc) % n] for k in range(len(ksp)) for dr, dc in offs]
def slice_grappa(
y: Sequence[Array],
calib: Sequence[Sequence[Array]],
shifts: Sequence[float],
acs: int = 16,
kr: int = 3,
kc: int = 3,
lam: float = 1e-8,
) -> list[list[Array]]:
"""Separate the collapsed k-space y (one n x n array per coil) into the S slices.
calib[z] holds the single-slice calibration k-space of slice z (its center
rows are read). Returns out[z][k], the k-space of coil k of slice z.
"""
c, n = len(y), len(y[0])
offs = _offsets(kr, kc)
rows = calib_rows(n, acs)
y_cal = collapse(calib, shifts) # @line L1
lo = -min(o[0] for o in offs)
hi = max(o[0] for o in offs)
result = []
for z, d in enumerate(shifts): # @line L2
target = [caipi_shift(calib[z][k], d) for k in range(c)]
a_rows, b_rows = [], []
for t in range(lo, len(rows) - hi): # @line L3
kappa = rows[t]
for l in range(n):
a_rows.append(_patch(y_cal, kappa, l, offs))
b_rows.append([target[k][kappa][l] for k in range(c)])
m = len(a_rows[0])
gram = [[sum(ar[p].conjugate() * ar[q] for ar in a_rows) for q in range(m)] for p in range(m)]
reg = lam * sum(gram[p][p].real for p in range(m)) / m
for p in range(m):
gram[p][p] += reg
rhs = [[sum(ar[p].conjugate() * br[a] for ar, br in zip(a_rows, b_rows)) for a in range(c)] for p in range(m)]
wz = solve(gram, rhs) # @line L4
xz = [[[0j] * n for _ in range(n)] for _ in range(c)]
for kappa in range(n): # @line L5
for l in range(n):
u = _patch(y, kappa, l, offs) # @line L6
for a in range(c):
xz[a][kappa][l] = sum(us * wz[s][a] for s, us in enumerate(u)) # @line L7
result.append([caipi_shift(xz[k], -d) for k in range(c)]) # @line L8
return result # @line L9
test_slice_grappa.py 98 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/slice-grappa/. The authors are listed in prov/863VBG.jsonl.
import cmath
import functools
import math
import random
from imgkit import MODIFIED_SHEPP_LOGAN, dft2, disk_phantom, ellipse_phantom, idft2, pixel_centers
from slice_grappa import caipi_shift, collapse, slice_grappa
N = 32
P0 = [(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)]
P1 = [(0.5, 0.6, 8, 0.4, 20), (-0.7, 0.7, 24, 0.3, 8), (1.4, 0.4, 12, 0.7, 10), (2.5, 0.3, 26, 0.6, 24)]
def band_maps(n, params):
"""Coil maps with image frequencies 0 and 1 on each axis."""
out = []
for psi, a, col, b, row in params:
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, rot, 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(rot + 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)
@functools.lru_cache(maxsize=None)
def slices(kind):
ph0 = ellipse_phantom(N, MODIFIED_SHEPP_LOGAN)
d1, d2 = disk_phantom(N, 0.7), disk_phantom(N, 0.3)
ph1 = [[a - 0.5 * b for a, b in zip(r1, r2)] for r1, r2 in zip(d1, d2)]
if kind == "band":
m0, m1 = band_maps(N, P0), band_maps(N, P1)
else:
m0, m1 = ring_maps(N, 20), ring_maps(N, 65)
return ksp_of(m0, ph0), ksp_of(m1, ph1)
def separate(kind, shift):
k0, k1 = slices(kind)
shifts = [0, shift]
out = slice_grappa(collapse([k0, k1], shifts), [k0, k1], shifts, acs=16)
return rel(out[0], k0), rel(out[1], k1)
def test_caipi_shift_moves_the_image_by_whole_rows():
rng = random.Random(1)
img = [[complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(8)] for _ in range(8)]
for s in (1, 3, 4):
back = idft2(caipi_shift(dft2(img), s))
for i in range(8):
for j in range(8):
assert abs(back[i][j] - img[(i - s) % 8][j]) < 1e-12
def test_collapse_is_the_sum_of_the_shifted_slices():
k0, k1 = slices("band")
y = collapse([k0, k1], [0, N // 2])
for c in (0, 3):
for kap in (0, 1, 5):
sign = 1 if kap % 2 == 0 else -1
for l in (0, 7):
assert abs(y[c][kap][l] - (k0[c][kap][l] + sign * k1[c][kap][l])) < 1e-12
def test_band_maps_slices_separate():
e0, e1 = separate("band", N // 2)
assert e0 < 1e-3 and e1 < 1e-3
def test_ring_maps_caipi_shift_lowers_the_error():
plain = separate("ring", 0)
caipi = separate("ring", N // 2)
assert max(plain) < 0.2
assert caipi[0] < plain[0] and caipi[1] < plain[1]
History
Larkman and colleagues showed in 2001 that coil arrays can separate slices excited at the same time. Breuer and colleagues proposed CAIPIRINHA in 2005: shift the slices against each other to make the aliasing easier to undo. Setsompop, Gagoski, Polimeni, Witzel, Wedeen and Wald published blipped CAIPI and slice-GRAPPA in 2012, which made SMS echo planar imaging practical for diffusion imaging and fMRI. Cauley and colleagues reduced the leakage between slices with split slice-GRAPPA in 2014.
References
- Kawin Setsompop, Borjan A. Gagoski, Jonathan R. Polimeni, Thomas Witzel, Van J. Wedeen and Lawrence L. Wald, Blipped-controlled aliasing in parallel imaging for simultaneous multislice echo planar imaging with reduced g-factor penalty, Magnetic Resonance in Medicine 67(5), 2012, 1210 to 1224, the blipped CAIPI shift and the slice-GRAPPA kernel fitted on single-slice calibration data (general locator; section numbers not confirmed)
- David J. Larkman, Joseph V. Hajnal, Amy H. Herlihy, Glyn A. Coutts, Ian R. Young and Gosta Ehnholm, Use of multicoil arrays for separation of signal from multiple slices simultaneously excited, Journal of Magnetic Resonance Imaging 13(2), 2001, 313 to 317, the separation of simultaneously excited slices with coil sensitivities (general locator)
- 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 slices against each other by phase cycling of the excitation (general locator)
- Stephen F. Cauley, Jonathan R. Polimeni, Himanshu Bhat, Lawrence L. Wald and Kawin Setsompop, Interslice leakage artifact reduction technique for simultaneous multislice acquisitions, Magnetic Resonance in Medicine 72(1), 2014, 93 to 102, the leakage between slices in slice-GRAPPA and the split slice-GRAPPA fit that reduces it (general locator)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 863VBG Edit this page History Report an error Markdown