Algorithmcore
GRAPPA
Also called generalized autocalibrating partially parallel acquisitions.
Fills the skipped k-space lines of each coil with a small shift-invariant kernel over the acquired neighbors of all coils, fitted by least squares on a fully sampled center block. Needs no coil maps.
- Solves
- MRI reconstruction
- Time
- O(R a n c^2 k^2 + R c^3 k^3 + c^2 k n^2 + c n^2 log n) worst
- Space
- O(c^2 k^2 + a n c k + c n^2) extra
- Where
- R = the reduction factor; a = the number of ACS rows; c = the number of coils; k = the number of source positions per coil in the kernel; n = the side of the n x n k-space
- Model
- Real RAM
- Properties
- deterministicnot exactnot in placeoffline
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Mark A. Griswold, Peter M. Jakob, Robin M. Heidemann, Mathias Nittka, Vladimir Jellus, Jianmin Wang, Berthold Kiefer, Axel Haase, 2002
GRAPPA (generalized autocalibrating partially parallel acquisitions) reconstructs multi-coil MR data from a Cartesian scan that skips phase encoding lines. It works in k-space and needs no coil sensitivity maps. A small kernel predicts each missing sample of each coil as a linear combination of the acquired samples of all coils near it. The weights come from a least squares fit on a fully sampled block at the center of k-space, the autocalibration signal (ACS). Each coil image is then an inverse FFT, and the coil images are combined, for example by root sum of squares. Griswold and colleagues published it in 2002. It is exact when the k-space of the maps has a small support that the kernel spans (a theorem on this page); for real coils it is an approximation.
In plain words
Each coil sees the body through its own smooth window. In k-space, a smooth window makes each sample a blend of a few neighboring samples of the true object. So the samples of all coils near a missing point already know a lot about that point. GRAPPA learns the recipe, "take this much of coil 1 above, that much of coil 3 below", from the middle of k-space, where nothing is missing. Because the windows are the same everywhere, the same recipe works on every missing line.
The problem
The input is the k-space of coils on an grid, with the rows acquired and a block of consecutive ACS rows at the center also acquired. The other rows are missing. The kernel shape is a choice: the code uses source rows for in a block of values and the columns , where . The output is the full k-space of every coil. The model is , but the maps are not inputs.
The algorithm
GRAPPA(y, R, ACS, kernel shape)- 1
for delta = 1, ..., R - 1 do ▷ one kernel per row offset - 2
collect, over the ACS rows kappa whose sources lie in the ACS block and all columns l, the source vector u(kappa, l) = (y_b(kappa + o))_{b, o in O_delta} and the targets (y_a(kappa, l))_a- 3
W_delta <- least squares solution of U W = Y (small Tikhonov term) - 4
for each missing row kappa do - 5
delta <- kappa mod R - 6
for each column l do - 7
u <- (y_b(kappa + o))_{b, o in O_delta} ▷ acquired samples only - 8
y_a(kappa, l) <- sum_s u_s W_delta[s][a] for every coil a - 9
return y
Line L2 builds the calibration matrix: one row per target position, one column per source (coil and offset). Line L3 solves the normal equations with a small multiple of the trace on the diagonal, which keeps the system solvable when it is nearly singular. Line L7 reads only rows , which the scan acquired. Line L8 fills all coils at once. The acquired rows, the ACS rows among them, are kept. The kernel size, the number of ACS rows and the regularization are design choices and are tuned in practice (Griswold et al. 2002).
Example
The table shows the relative k-space error over all coils and samples, which by Parseval equals the relative error of the coil images, for a modified Shepp-Logan phantom and four coils, without noise (measurement with the code of this page, regularization ). 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. "Zero filled" is the error with the missing rows set to 0.
| maps | ACS rows | kernel () | GRAPPA error | zero filled | |
|---|---|---|---|---|---|
| band | 2 | 12 | 0.400 | ||
| band | 2 | 8 | 0.464 | ||
| band | 4 | 16 | 0.272 | 0.451 | |
| band | 4 | 16 | 1.00 | 0.451 | |
| ring | 2 | 12 | 0.013 | 0.395 | |
| ring | 2 | 8 | 0.023 | 0.466 | |
| ring | 4 | 16 | 0.137 | 0.437 | |
| ring | 4 | 16 | 0.115 | 0.437 |
For the band maps at the kernel spans the target, and the error is at the rounding level, as the theorem says. At the kernel does not span it, and the error is large. The large kernel on the band maps shows the danger of a fit with more unknowns than the calibration data support: the calibration matrix is nearly singular, and the weights that fit the ACS block fail elsewhere.
Correctness
Assume the coil k-space is the object k-space convolved with a kernel of finite support , which holds when the maps are trigonometric polynomials. Then each source and each target is a linear function of the object samples in a small window around the target. If the targets lie in the span of the sources, an exact kernel exists. If the calibration data contain enough independent object patterns, every solution of the fit is that exact kernel on the level of the object samples, so it is exact at every missing position. The proof gives the details. This is a theorem about maps with a finite k-space support; real maps are smooth but not band-limited, and the error for them is a measurement.
Proof: GRAPPA is exact when the coil maps have a finite k-space support that the kernel spans and the calibration data are rich enoughfull
The setting is that of the algorithm, in exact arithmetic and with (any exact solution of the normal equations of line L3). k-space is indexed by , with the phase encoding index first and wrap-around in both indices. The scan keeps the rows and the ACS rows, a block of consecutive rows where every sample is known. For the offset , the kernel has the source offsets for a fixed set of integers, and predicts
Model (H1). The coil k-space is a convolution of the object k-space with a kernel of finite support: there are a finite set and numbers with
where is the k-space of the object. This holds when each map is a trigonometric polynomial whose image frequencies lie in , because multiplication in the image is circular convolution in k-space. Real maps are smooth but not band-limited, so (H1) holds only approximately for them.
Let , the set of object samples, relative to , that the sources and the target depend on. Define the source matrix with a row for each source and a column for each , (zero when ), and the target matrix . By (H1), and .
Theorem. Assume (H1). Fix , and suppose:
- (span) every row of lies in the row space of ;
- (rich calibration) the matrix whose rows are the vectors , for the target positions used in the fit of line L2, has full column rank .
Then the weights of line L3 satisfy for every coil and every with . If this holds for every , GRAPPA returns the full k-space of every coil. Every sample it reads was acquired.
Proof. Reading. For a target row , the source rows are , which the scan keeps. In the fit, line L2 uses only target rows whose source rows lie inside the ACS block. So the method reads only acquired samples.
Existence. By the span assumption there is a matrix with for all and , that is, .
Calibration. The rows of the calibration matrix of line L2 are the source vectors for the fit positions , so the calibration matrix is , and the right side is . Then , so the least squares problem has the value 0, and every solution of the normal equations (with ) is a minimizer and satisfies . Hence . has full column rank, so : the fitted kernel is exact on the level of the object samples.
Prediction. For any with ,
Lines L4 to L8 apply this to every missing row, and the acquired rows are kept, so the output is the full k-space.
Remarks.
- The span assumption needs at least as many independent sources as the dimension of the span of the target rows. For the band maps of the tests (), , two source rows and three columns, has 16 elements and there are sources. The tests find the error below , which is consistent with the span assumption for those maps; the rank is not proved here.
- The calibration assumption fails, for example, when the ACS block is too narrow for the kernel, or when the object k-space vanishes on a pattern inside the ACS block. Then the fit has several exact solutions, and some of them are wrong outside the ACS block.
- With the weights solve a Tikhonov problem; as they tend to the solution of least norm of the normal equations, which is exact under the assumptions, so the theorem holds in the limit.
- For real coils, (H1) is an approximation, and GRAPPA is an approximate method. The size of the error is a measurement.
Complexity
In the real RAM, with sources per kernel: for each of the offsets, line L2 collects up to calibration rows, forming the normal equations costs , and solving them costs . Lines L4 to L8 compute outputs from sources for each of the fewer than missing samples, . The coil images need inverse FFTs, . The total is . The memory holds the normal equations, , the calibration rows, , and the k-space, . The method is not iterative.
Properties
- Exact for band-limited maps. Under the span and calibration assumptions, the output is the full k-space (theorem).
- No maps. The method needs no map estimate, so it does not fail where a map estimate is poor, for example at the edge of the object or when the field of view is tight.
- Linear. For fixed weights, the output is a linear function of the data, so its noise is described by a g-factor (Breuer et al. 2009).
- Coil images, not one image. The output is one image per coil; the final image needs a coil combination, which adds its own noise properties.
- Cartesian. The kernel assumes the same pattern of neighbors at every missing sample. Irregular patterns need one kernel per pattern, or SPIRiT.
Variants and improvements
- SPIRiT. SPIRiT uses a kernel over all neighbors, acquired or not, and asks that the whole k-space be consistent with it. It works for any sampling and reduces to a GRAPPA-like step for uniform patterns. GRAPPA computes the missing samples in one pass; SPIRiT solves for them iteratively.
- Slice-GRAPPA. Slice-GRAPPA uses one kernel per slice to separate simultaneously excited slices.
- Image domain GRAPPA. The kernel is a convolution, so it can be applied as a pixelwise multiplication of the coil images, which is faster for large kernels and gives the g-factor map.
- SENSE. SENSE uses explicit maps instead of a kernel. With good maps it gives the optimal noise for the model; ESPIRiT links the two views.
- Regularized fits. Larger Tikhonov terms in line L3 lower the noise of the kernel at the cost of residual aliasing; the weight is tuned.
When to use it
Use GRAPPA for Cartesian scans with uniform undersampling and a fully sampled center, when coil maps are not available or not reliable, for example with a tight field of view, motion between a map scan and the main scan, or a body region with fast changing maps. Keep well below the number of coils, and collect enough ACS rows for the kernel: the ACS block must hold many more independent rows than the kernel has weights. For non-Cartesian or random patterns use SPIRiT or CG-SENSE.
Pitfalls
- Too few ACS rows. If line L2 collects fewer independent patterns than the kernel has weights, the fit of line L3 is underdetermined, and the kernel can fit the ACS block and fail elsewhere (the row of the table).
- Kernel too small. If the sources of line L7 do not span the target, the error stays large however good the calibration is (the rows of the table).
- No regularization. With the normal equations of line L3 can be singular for clean synthetic data and badly conditioned for real data.
- Wrong row offset. Line L5 must pick the kernel by ; using one kernel for all offsets mixes up the neighbor patterns.
- Combining badly. A root sum of squares of the output coil images carries the noise bias and the coil shading of RSS.
- Motion in the ACS. If the ACS block comes from a separate scan, motion or contrast changes between the scans make the kernel wrong.
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
# Part of https://algorithm.tamnd.com/grappa/. The authors are listed in prov/KY1RH2.jsonl.
"""GRAPPA: generalized autocalibrating partially parallel acquisitions (Griswold et al. 2002).
Conventions: the k-space of coil k is an n x n array in DFT order, with the
phase encoding rows kappa as the first index and the readout columns l as the
second. The scan keeps the rows kappa = 0, R, 2R, ... and a block of
consecutive rows at the center (the ACS rows, autocalibration signal). Rows
and columns wrap around, as the DFT does.
For each offset delta = 1, ..., R - 1, a kernel predicts the sample of every
coil at (kappa, l) from the acquired samples of all coils at the rows
kappa - delta + R t (t in the block range) and the columns l - w, ..., l + w.
The weights are fitted by least squares on the ACS rows, where every row is
known. The kernel shape (the number of blocks nb and the half width w) and the
small regularization are choices.
"""
from typing import Sequence
from imgla import solve
Array = list[list[complex]]
def signed(kappa: int, n: int) -> int:
"""The signed frequency of DFT index kappa."""
return kappa if kappa < n // 2 else kappa - n
def acs_rows(n: int, acs: int) -> list[int]:
"""The DFT indices of the acs center rows: signed frequencies -acs/2 .. acs/2 - 1, in increasing order."""
return [(f + n) % n for f in range(-(acs // 2), acs - acs // 2)]
def grappa_mask(n: int, r: int, acs: int) -> list[bool]:
"""True for the acquired rows: kappa = 0 mod R, and the ACS rows."""
keep = [kappa % r == 0 for kappa in range(n)]
for kappa in acs_rows(n, acs):
keep[kappa] = True
return keep
def source_offsets(r: int, delta: int, nb: int, w: int) -> list[tuple[int, int]]:
"""Row and column offsets of the kernel sources, relative to the target at offset delta."""
blocks = range(-(nb // 2 - 1), nb // 2 + 1)
return [(-delta + r * t, d) for t in blocks for d in range(-w, w + 1)]
def calibrate(
ksp: Sequence[Array],
r: int,
acs: int,
nb: int = 2,
w: int = 1,
lam: float = 1e-8,
) -> dict[int, list[list[complex]]]:
"""Fit one weight matrix W_delta (sources x coils) for each delta = 1 .. R - 1 on the ACS rows."""
c, n = len(ksp), len(ksp[0])
rows = acs_rows(n, acs)
weights = {}
for delta in range(1, r): # @line L1
offs = source_offsets(r, delta, nb, w)
lo = min(o[0] for o in offs)
hi = max(o[0] for o in offs)
a_rows, b_rows = [], []
for t in range(max(0, -lo), min(len(rows), len(rows) - hi)): # @line L2
kappa = rows[t]
for l in range(n):
a_rows.append([ksp[k][(kappa + dr) % n][(l + dc) % n] for k in range(c) for dr, dc in offs])
b_rows.append([ksp[k][kappa][l] for k in range(c)])
m = len(a_rows[0])
gram = [[sum(row[p].conjugate() * row[q] for row 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)]
weights[delta] = solve(gram, rhs) # @line L3
return weights
def grappa(
ksp: Sequence[Array],
r: int,
acs: int,
nb: int = 2,
w: int = 1,
lam: float = 1e-8,
) -> list[Array]:
"""Fill the rows that were not acquired. ksp holds the acquired rows; the others are never read."""
c, n = len(ksp), len(ksp[0])
if n % r != 0:
raise ValueError("n must be a multiple of R")
keep = grappa_mask(n, r, acs)
weights = calibrate(ksp, r, acs, nb, w, lam)
out = [[list(ksp[k][kappa]) if keep[kappa] else [0j] * n for kappa in range(n)] for k in range(c)]
for kappa in range(n): # @line L4
if keep[kappa]:
continue
delta = kappa % r # @line L5
offs = source_offsets(r, delta, nb, w)
wd = weights[delta]
for l in range(n): # @line L6
u = [ksp[k][(kappa + dr) % n][(l + dc) % n] for k in range(c) for dr, dc in offs] # @line L7
for a in range(c):
out[a][kappa][l] = sum(us * wd[s][a] for s, us in enumerate(u)) # @line L8
return out # @line L9
imgkit.py 322 lines
# SPDX-License-Identifier: MIT
# Shared helper of the imaging and inverse problems pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small images and signals for the imaging and inverse problems pages.
Conventions:
- A signal is a list of numbers. An image is a list of rows, img[i][j], with
row i from the top and column j from the left.
- An n x n image covers the square [-1, 1]^2. The center of pixel (i, j) is
x_j = -1 + (2 j + 1) / n and y_i = 1 - (2 i + 1) / n, so y goes up.
- DFT: X_k = sum_j x_j exp(-2 pi i j k / n), unnormalized; the inverse has
the factor 1 / n. Index k stands for frequency k for k < n / 2 and k - n
otherwise. fftshift moves the zero frequency to position n // 2.
- Periodic convolution kernels are stored with their center at index 0
(wrapped around), so a delta kernel gives the identity and no shift.
"""
import cmath
import math
# ------------------------------------------------------------------ images
def new_image(n1, n2, value=0.0):
"""An n1 x n2 image (n1 rows, n2 columns) filled with value."""
return [[value] * n2 for _ in range(n1)]
def img_add(a, b):
"""The pixelwise sum a + b."""
return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
def img_scale(a, c):
"""The image c a."""
return [[c * x for x in row] for row in a]
def img_dot(a, b):
"""<a, b> = sum conj(a_ij) b_ij."""
return sum(x.conjugate() * y for ra, rb in zip(a, b) for x, y in zip(ra, rb))
def img_norm(a):
"""The Euclidean (Frobenius) norm of an image."""
return math.sqrt(sum(abs(x) ** 2 for row in a for x in row))
def flatten(img):
"""Row-major vector of an image."""
return [x for row in img for x in row]
def unflatten(v, n1, n2):
"""The n1 x n2 image of a row-major vector."""
return [list(v[i * n2:(i + 1) * n2]) for i in range(n1)]
# ------------------------------------------------------------------ DFT
def _is_pow2(n):
return n > 0 and n & (n - 1) == 0
def _fft_pow2(x):
"""Iterative radix-2 FFT, unnormalized forward transform."""
n = len(x)
a = [complex(v) for v in x]
j = 0
for i in range(1, n):
bit = n >> 1
while j & bit:
j ^= bit
bit >>= 1
j |= bit
if i < j:
a[i], a[j] = a[j], a[i]
size = 2
while size <= n:
half = size // 2
tw = [cmath.exp(-2j * math.pi * k / size) for k in range(half)]
for start in range(0, n, size):
for k in range(half):
u = a[start + k]
v = a[start + k + half] * tw[k]
a[start + k] = u + v
a[start + k + half] = u - v
size *= 2
return a
def dft(x):
"""X_k = sum_j x_j exp(-2 pi i j k / n). Radix-2 FFT when n is a power of 2."""
n = len(x)
if n == 0:
return []
if _is_pow2(n):
return _fft_pow2(x)
w = [cmath.exp(-2j * math.pi * t / n) for t in range(n)]
return [sum(x[j] * w[(j * k) % n] for j in range(n)) for k in range(n)]
def idft(xf):
"""x_j = (1/n) sum_k X_k exp(2 pi i j k / n)."""
n = len(xf)
if n == 0:
return []
y = dft([complex(v).conjugate() for v in xf])
return [v.conjugate() / n for v in y]
def _rows_then_cols(img, f):
rows = [f(row) for row in img]
cols = [f(list(col)) for col in zip(*rows)]
return [list(r) for r in zip(*cols)]
def dft2(img):
"""2D DFT: X_kl = sum_jq x_jq exp(-2 pi i (j k / n1 + q l / n2))."""
return _rows_then_cols(img, dft)
def idft2(img):
"""Inverse 2D DFT, with the factor 1 / (n1 n2)."""
return _rows_then_cols(img, idft)
def _shift1(x, s):
return list(x[s:]) + list(x[:s])
def fftshift(x):
"""Move the zero frequency to position n // 2 (1D, or both axes of an image)."""
if x and isinstance(x[0], (list, tuple)):
rows = [fftshift(r) for r in x]
return _shift1(rows, (len(rows) + 1) // 2)
return _shift1(x, (len(x) + 1) // 2)
def ifftshift(x):
"""The inverse of fftshift (1D, or both axes of an image)."""
if x and isinstance(x[0], (list, tuple)):
rows = [ifftshift(r) for r in x]
return _shift1(rows, len(rows) // 2)
return _shift1(x, len(x) // 2)
def circ_conv(x, h):
"""Periodic convolution y_i = sum_j h_j x_{(i - j) mod n}, kernel centered at index 0."""
n = len(x)
nz = [(j, hj) for j, hj in enumerate(h) if hj != 0]
return [sum(hj * x[(i - j) % n] for j, hj in nz) for i in range(n)]
def circ_conv2(img, h):
"""Periodic 2D convolution with the kernel h centered at index (0, 0)."""
n1, n2 = len(img), len(img[0])
nz = [(p, q, h[p][q]) for p in range(len(h)) for q in range(len(h[0])) if h[p][q] != 0]
out = new_image(n1, n2)
for i in range(n1):
for j in range(n2):
out[i][j] = sum(v * img[(i - p) % n1][(j - q) % n2] for p, q, v in nz)
return out
# ------------------------------------------------------------------ phantoms
def pixel_centers(n):
"""(xs, ys): xs[j] = -1 + (2 j + 1) / n and ys[i] = 1 - (2 i + 1) / n."""
xs = [-1.0 + (2 * j + 1) / n for j in range(n)]
ys = [1.0 - (2 * i + 1) / n for i in range(n)]
return xs, ys
# Rows: rho, A, B, x0, y0, phi (degrees). A is the semi-axis along the
# direction phi (counterclockwise from the x axis), B the other semi-axis.
# Geometry and densities of Shepp and Logan (1974), as reproduced in Kak and
# Slaney, Principles of Computerized Tomographic Imaging, Table 3.1. The value
# at the center (0, 0) is 2 - 0.98 = 1.02.
SHEPP_LOGAN = [
(2.0, 0.92, 0.69, 0.0, 0.0, 90.0),
(-0.98, 0.874, 0.6624, 0.0, -0.0184, 90.0),
(-0.02, 0.31, 0.11, 0.22, 0.0, 72.0),
(-0.02, 0.41, 0.16, -0.22, 0.0, 108.0),
(0.01, 0.25, 0.21, 0.0, 0.35, 90.0),
(0.01, 0.046, 0.046, 0.0, 0.1, 0.0),
(0.01, 0.046, 0.046, 0.0, -0.1, 0.0),
(0.01, 0.046, 0.023, -0.08, -0.605, 0.0),
(0.01, 0.023, 0.023, 0.0, -0.605, 0.0),
(0.01, 0.046, 0.023, 0.06, -0.605, 90.0),
]
# The same ellipses with the gray levels of Toft (1996), which give more
# contrast. The value at the center is 1 - 0.8 = 0.2.
MODIFIED_SHEPP_LOGAN = [
(rho, a, b, x0, y0, phi)
for rho, (_, a, b, x0, y0, phi) in zip(
(1.0, -0.8, -0.2, -0.2, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1), SHEPP_LOGAN
)
]
def ellipse_value(x, y, table):
"""The phantom value at the point (x, y): the sum of rho over the ellipses that hold it."""
total = 0.0
for rho, a, b, x0, y0, phi in table:
c, s = math.cos(math.radians(phi)), math.sin(math.radians(phi))
dx, dy = x - x0, y - y0
u = dx * c + dy * s
v = -dx * s + dy * c
if (u / a) ** 2 + (v / b) ** 2 <= 1.0:
total += rho
return total
def ellipse_phantom(n, table):
"""The n x n image of an ellipse table, sampled at the pixel centers."""
xs, ys = pixel_centers(n)
return [[ellipse_value(x, y, table) for x in xs] for y in ys]
def disk_phantom(n, radius):
"""1 at pixel centers with x^2 + y^2 <= radius^2, 0 elsewhere."""
xs, ys = pixel_centers(n)
r2 = radius * radius
return [[1.0 if x * x + y * y <= r2 else 0.0 for x in xs] for y in ys]
def spikes_1d(n, positions, amplitudes):
"""A signal of length n with the given amplitudes at the given positions."""
out = [0.0] * n
for p, a in zip(positions, amplitudes):
out[p] += a
return out
# ------------------------------------------------------------------ projector
def parallel_beam_matrix(n, angles, nbins):
"""Pixel-driven discrete Radon transform of an n x n image on [-1, 1]^2.
Each pixel center (x, y) projects to s = x cos(theta) + y sin(theta). Its
value times the pixel area over the bin width is split linearly between
the two nearest bin centers. The bins cover [-sqrt(2), sqrt(2)]. Row
a * nbins + b holds angle a and bin b; column i * n + j holds pixel (i, j).
Returns the sparse rows, each a list of (column, weight) pairs.
Pixel-driven projection has a ripple: with a bin width close to the pixel
size, a disk projection is off by up to about 10 percent in some bins. A
bin of about twice the pixel size (nbins = 23 for n = 32) keeps it near
1 percent.
"""
xs, ys = pixel_centers(n)
smax = math.sqrt(2.0)
width = 2.0 * smax / nbins
scale = (2.0 / n) ** 2 / width
rows = []
for theta in angles:
c, s = math.cos(theta), math.sin(theta)
acc = [dict() for _ in range(nbins)]
for i, y in enumerate(ys):
for j, x in enumerate(xs):
t = (x * c + y * s + smax) / width - 0.5
b0 = math.floor(t)
frac = t - b0
col = i * n + j
for b, w in ((b0, 1.0 - frac), (b0 + 1, frac)):
if 0 <= b < nbins and w > 0.0:
acc[b][col] = acc[b].get(col, 0.0) + w * scale
rows.extend(sorted(d.items()) for d in acc)
return rows
def sp_matvec(rows, x):
"""y = A x for sparse rows of (column, weight) pairs."""
return [sum(w * x[c] for c, w in row) for row in rows]
def sp_rmatvec(rows, y, ncols):
"""x = A^H y for sparse rows of (column, weight) pairs and ncols columns."""
out = [0.0] * ncols
for row, yi in zip(rows, y):
if yi == 0:
continue
for c, w in row:
out[c] += w.conjugate() * yi
return out
# ------------------------------------------------------------------ noise
def gauss_noise(rng, shape, sigma):
"""Independent N(0, sigma^2) values: a list for an int shape, an image for (n1, n2)."""
if isinstance(shape, int):
return [rng.gauss(0.0, sigma) for _ in range(shape)]
n1, n2 = shape
return [[rng.gauss(0.0, sigma) for _ in range(n2)] for _ in range(n1)]
def _poisson_small(rng, lam):
"""Knuth's product method, exact for a mean lam <= 30."""
limit = math.exp(-lam)
k, p = 0, rng.random()
while p > limit:
k += 1
p *= rng.random()
return k
def poisson_sample(rng, lam):
"""An exact Poisson(lam) sample: a sum of Knuth samples with means at most 30."""
if lam < 0:
raise ValueError("negative mean")
total = 0
while lam > 30.0:
total += _poisson_small(rng, 30.0)
lam -= 30.0
if lam > 0.0:
total += _poisson_small(rng, lam)
return total
imgla.py 259 lines
# SPDX-License-Identifier: MIT
# Shared helper of the imaging and inverse problems pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Dense linear algebra on lists of rows (float, complex or Fraction entries).
A matrix is a list of rows. A vector is a list of numbers. The inner product
is <u, v> = sum_i conj(u_i) v_i, linear in the second argument, so that the
adjoint A^H satisfies <A x, y> = <x, A^H y>.
"""
import math
def _flat(x):
"""Flatten a list of rows (an image) into one list; a vector is returned as is."""
if x and isinstance(x[0], (list, tuple)):
return [v for row in x for v in row]
return x
def zeros(m, n):
"""The m x n zero matrix."""
return [[0.0] * n for _ in range(m)]
def eye(n):
"""The n x n identity matrix."""
out = zeros(n, n)
for i in range(n):
out[i][i] = 1.0
return out
def transpose(a):
"""A^T."""
return [list(col) for col in zip(*a)]
def conj_transpose(a):
"""A^H, the conjugate transpose."""
return [[v.conjugate() for v in col] for col in zip(*a)]
def matmul(a, b):
"""The product A B."""
bt = list(zip(*b))
return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]
def matvec(a, x):
"""The product A x."""
return [sum(v * w for v, w in zip(row, x)) for row in a]
def rmatvec(a, y):
"""The product A^H y."""
n = len(a[0]) if a else 0
out = [0.0] * n
for row, yi in zip(a, y):
if yi == 0:
continue
for j, v in enumerate(row):
out[j] += v.conjugate() * yi
return out
def dot(u, v):
"""<u, v> = sum_i conj(u_i) v_i. Images (lists of rows) are flattened."""
return sum(a.conjugate() * b for a, b in zip(_flat(u), _flat(v)))
def norm2(x):
"""The Euclidean norm. Images (lists of rows) are flattened."""
return math.sqrt(sum(abs(v) ** 2 for v in _flat(x)))
def solve(a, b):
"""Solve A x = b by Gaussian elimination with partial pivoting.
b is a vector or a matrix (a list of rows). A must be square and
nonsingular; a zero pivot raises ValueError. Fractions stay exact.
"""
n = len(a)
vec = not (b and isinstance(b[0], (list, tuple)))
rhs = [[bi] for bi in b] if vec else [list(r) for r in b]
m = [list(row) + rhs[i] for i, row in enumerate(a)]
w = len(m[0])
for c in range(n):
p = max(range(c, n), key=lambda r: abs(m[r][c]))
if m[p][c] == 0:
raise ValueError("singular matrix")
m[c], m[p] = m[p], m[c]
piv = m[c][c]
for r in range(c + 1, n):
f = m[r][c] / piv
if f != 0:
mr, mc = m[r], m[c]
for j in range(c, w):
mr[j] -= f * mc[j]
x = [[0.0] * (w - n) for _ in range(n)]
for r in range(n - 1, -1, -1):
for j in range(w - n):
s = m[r][n + j] - sum(m[r][k] * x[k][j] for k in range(r + 1, n))
x[r][j] = s / m[r][r]
return [row[0] for row in x] if vec else x
def cholesky(a):
"""Lower triangular L with A = L L^H for a Hermitian positive definite A."""
n = len(a)
low = zeros(n, n)
for j in range(n):
d = a[j][j] - sum(abs(low[j][k]) ** 2 for k in range(j))
d = d.real if isinstance(d, complex) else d
if not d > 0:
raise ValueError("matrix is not positive definite")
ljj = math.sqrt(d)
low[j][j] = ljj
for i in range(j + 1, n):
s = a[i][j] - sum(low[i][k] * low[j][k].conjugate() for k in range(j))
low[i][j] = s / ljj
return low
def cho_solve(low, b):
"""Solve (L L^H) x = b, with L from cholesky."""
n = len(low)
z = [0.0] * n
for i in range(n):
z[i] = (b[i] - sum(low[i][k] * z[k] for k in range(i))) / low[i][i]
x = [0.0] * n
for i in range(n - 1, -1, -1):
s = z[i] - sum(low[k][i].conjugate() * x[k] for k in range(i + 1, n))
x[i] = s / low[i][i].conjugate()
return x
def _rot_params(app, aqq, apq):
"""c, s of the Jacobi rotation that zeroes the (p, q) entry of [[app, apq], [apq, aqq]]."""
theta = (aqq - app) / (2.0 * apq)
t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
c = 1.0 / math.sqrt(1.0 + t * t)
return c, c * t
def sym_eig(a, tol=1e-15, max_sweeps=100):
"""Eigenvalues (ascending) and eigenvectors (as columns) of a real symmetric matrix.
Cyclic Jacobi method. Returns (w, Q) with A = Q diag(w) Q^T.
"""
n = len(a)
m = [[float(v) for v in row] for row in a]
q = eye(n)
for _ in range(max_sweeps):
off = sum(m[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
scale = sum(m[i][i] ** 2 for i in range(n)) + off
if off <= (tol * tol) * scale or off == 0.0:
break
for p in range(n - 1):
for r in range(p + 1, n):
apq = m[p][r]
if apq == 0.0:
continue
c, s = _rot_params(m[p][p], m[r][r], apq)
for k in range(n):
mkp, mkr = m[k][p], m[k][r]
m[k][p] = c * mkp - s * mkr
m[k][r] = s * mkp + c * mkr
mp, mr = m[p], m[r]
for k in range(n):
mpk, mrk = mp[k], mr[k]
mp[k] = c * mpk - s * mrk
mr[k] = s * mpk + c * mrk
m[p][r] = m[r][p] = 0.0
for k in range(n):
qkp, qkr = q[k][p], q[k][r]
q[k][p] = c * qkp - s * qkr
q[k][r] = s * qkp + c * qkr
order = sorted(range(n), key=lambda i: m[i][i])
w = [m[i][i] for i in order]
qs = [[q[k][i] for i in order] for k in range(n)]
return w, qs
def _complete(cols, m):
"""Replace zero columns of an m-row column list by unit vectors orthogonal to the others."""
for idx, col in enumerate(cols):
if any(v != 0.0 for v in col):
continue
for e in range(m):
cand = [0.0] * m
cand[e] = 1.0
for _ in range(2):
for jdx, other in enumerate(cols):
if jdx == idx or not any(v != 0.0 for v in other):
continue
h = sum(a * b for a, b in zip(other, cand))
cand = [a - h * b for a, b in zip(cand, other)]
nrm = math.sqrt(sum(v * v for v in cand))
if nrm > 0.5:
cols[idx] = [v / nrm for v in cand]
break
return cols
def svd(a, tol=1e-15, max_sweeps=100):
"""Thin SVD of a real m x n matrix by one-sided Jacobi (Hestenes).
Returns (U, S, V) with p = min(m, n): U is m x p, S a list of p values in
descending order, V is n x p, U^T U = I, V^T V = I and A = U diag(S) V^T.
"""
m, n = len(a), len(a[0])
if m < n:
v, s, u = svd(transpose(a), tol, max_sweeps)
return u, s, v
cols = [[float(a[i][j]) for i in range(m)] for j in range(n)]
vcols = [[1.0 if i == j else 0.0 for i in range(n)] for j in range(n)]
for _ in range(max_sweeps):
rotated = False
for p in range(n - 1):
for r in range(p + 1, n):
cp, cr = cols[p], cols[r]
alpha = sum(x * x for x in cp)
beta = sum(x * x for x in cr)
gamma = sum(x * y for x, y in zip(cp, cr))
if gamma == 0.0 or abs(gamma) <= tol * math.sqrt(alpha * beta):
continue
rotated = True
c, s = _rot_params(alpha, beta, gamma)
cols[p] = [c * x - s * y for x, y in zip(cp, cr)]
cols[r] = [s * x + c * y for x, y in zip(cp, cr)]
vp, vr = vcols[p], vcols[r]
vcols[p] = [c * x - s * y for x, y in zip(vp, vr)]
vcols[r] = [s * x + c * y for x, y in zip(vp, vr)]
if not rotated:
break
sig = [math.sqrt(sum(x * x for x in col)) for col in cols]
# A column below 1e-150 times the largest one is zero to working precision;
# its squares underflow, so its direction carries no information.
floor = max(sig) * 1e-150 if sig else 0.0
sig = [t if t > floor and t > 1e-150 else 0.0 for t in sig]
order = sorted(range(n), key=lambda j: -sig[j])
s_out = [sig[j] for j in order]
ucols = [[x / sig[j] for x in cols[j]] if sig[j] > 0.0 else [0.0] * m for j in order]
ucols = _complete(ucols, m)
u = [[ucols[j][i] for j in range(n)] for i in range(m)]
v = [[vcols[j][i] for j in order] for i in range(n)]
return u, s_out, v
def adjoint_gap(apply_a, apply_ah, x, y):
"""|<A x, y> - <x, A^H y>| / (||A x|| ||y||) for given functions A and A^H.
x and y may be vectors or images (lists of rows). If the denominator is
zero, the absolute gap is returned.
"""
ax = apply_a(x)
gap = abs(dot(ax, y) - dot(x, apply_ah(y)))
den = norm2(ax) * norm2(y)
return gap / den if den > 0.0 else gap
test_grappa.py 90 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/grappa/. The authors are listed in prov/KY1RH2.jsonl.
import cmath
import functools
import math
import pytest
from grappa import grappa, grappa_mask, source_offsets
from imgkit import MODIFIED_SHEPP_LOGAN, dft2, ellipse_phantom, pixel_centers
N = 32
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 small kernel can be exact at R = 2."""
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
@functools.lru_cache(maxsize=None)
def kspace(kind):
maps = band_maps(N) if kind == "band" else ring_maps(N)
ph = ellipse_phantom(N, MODIFIED_SHEPP_LOGAN)
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, ph)])] 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 acquire(k, keep, fill=0j):
return [[list(row) if keep[kap] else [fill] * N for kap, row in enumerate(a)] for a in k]
def test_source_offsets():
assert source_offsets(2, 1, 2, 1) == [(-1, -1), (-1, 0), (-1, 1), (1, -1), (1, 0), (1, 1)]
assert [o[0] for o in source_offsets(4, 3, 2, 0)] == [-3, 1]
def test_mask():
keep = grappa_mask(16, 4, 4)
assert [kap for kap in range(16) if keep[kap]] == [0, 1, 4, 8, 12, 14, 15]
def test_exact_for_band_maps_and_missing_rows_not_read():
k = kspace("band")
keep = grappa_mask(N, 2, 12)
y = acquire(k, keep, fill=1e6 + 1e6j)
out = grappa(y, 2, 12)
assert rel(out, k) < 1e-6
for a in range(4):
for kap in range(N):
if keep[kap]:
assert out[a][kap] == k[a][kap]
def test_ring_maps_r2_and_r4_beat_zero_filling():
k = kspace("ring")
for r, acs, bound in ((2, 12, 0.1), (4, 16, 0.5)):
keep = grappa_mask(N, r, acs)
y = acquire(k, keep)
err = rel(grappa(y, r, acs), k)
assert err < bound * rel(y, k)
def test_r_must_divide_n():
k = kspace("band")
with pytest.raises(ValueError):
grappa(k, 3, 12)
History
Sodickson and Manning showed in 1997 with SMASH that combinations of coil signals can synthesize shifted k-space lines. Jakob, Griswold, Heidemann and colleagues then added autocalibration lines in AUTO-SMASH and VD-AUTO-SMASH. Griswold, Jakob, Heidemann, Nittka, Jellus, Wang, Kiefer and Haase published GRAPPA in 2002: a kernel over several neighboring lines for each coil, fitted on the ACS lines, and a coil combination at the end. Lustig and Pauly generalized it to any sampling with SPIRiT in 2010, and Setsompop and colleagues used the same idea for simultaneous multi-slice imaging with slice-GRAPPA in 2012.
References
- 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 kernel that predicts each coil from the acquired neighbors of all coils, the fit on the autocalibration lines, and the combination of the coil images (general locator; section numbers not confirmed)
- 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 synthesis of shifted k-space lines from linear combinations of coil signals (general locator)
- Felix A. Breuer, Stephan A. R. Kannengiesser, Martin Blaimer, Nicole Seiberlich, Peter M. Jakob and Mark A. Griswold, General formulation for quantitative g-factor calculation in GRAPPA reconstructions, Magnetic Resonance in Medicine 62(3), 2009, 739 to 746, the image domain form of the GRAPPA kernel and its g-factor (general locator)
- 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, GRAPPA as one step of a k-space consistency condition, and its generalization to any sampling (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.
| 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 KY1RH2 Edit this page History Report an error Markdown