Algorithmadvanced
CG-SENSE
Also called iterative SENSE.
Solves the SENSE least squares problem for any k-space trajectory with the conjugate gradient method on the normal equations, with the coil encoding operator and its adjoint by FFT or nonuniform FFT.
- Solves
- MRI reconstruction
- Time
- O(K c (n^2 log n + S)) worst
- Space
- O(c (n^2 + S)) extra
- Where
- K = the number of iterations, at most n^2 in exact arithmetic; S = the number of samples per coil; c = the number of coils; n = the side of the n x n image
- Model
- Real RAM
- Properties
- deterministicexactnot in placeoffline
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Klaas P. Pruessmann, Markus Weiger, Peter Boernert, Peter Boesiger, 2001
CG-SENSE reconstructs an MR image from multi-coil data on any k-space trajectory: radial, spiral, or a Cartesian pattern with irregular gaps. It solves the same least squares problem as SENSE, but the problem no longer splits into small pixel groups, so it uses the conjugate gradient method on the normal equations. Each iteration applies the encoding operator and its adjoint once, by an FFT on a Cartesian grid or by a nonuniform FFT on a trajectory. Pruessmann, Weiger, Boernert and Boesiger published it in 2001. In exact arithmetic it reaches the least squares solution in at most steps, and the energy norm of the error does not increase (theorems).
In plain words
SENSE solves many tiny puzzles, one per folded pixel. With spokes or spirals instead of skipped lines, the folding is spread over the whole image, and there is one huge puzzle instead. CG-SENSE does not write that puzzle down. It only needs two moves: predict the coil data from a guess of the image, and spread a set of data back onto the image. With these two moves the conjugate gradient method walks to the best fitting image in a few dozen steps, each step better than the last in a fixed sense.
The problem
The input is the data , samples per coil at the k-space points of the trajectory, the coil sensitivity maps , and optionally positive sample weights . The encoding operator is , where is the unitary DFT followed by the sampling on a Cartesian grid, or the nonuniform DFT on a trajectory. The output is the minimizer of over images, the solution of
This is the MRI reconstruction problem with coil maps and a quadratic data term.
The algorithm
. and are given as functions.
CG-SENSE(y, E, E^H, D, iters, tol)- 1
b <- E^H (D y) - 2
x <- 0; r <- b; p <- r - 3
for t = 0, 1, ..., iters - 1 do - 4
if ||r|| <= tol ||b|| then stop - 5
q <- E^H (D (E p)) ▷ one E and one E^H - 6
alpha <- ||r||^2 / <p, q> - 7
x <- x + alpha p - 8
r_new <- r - alpha q - 9
p <- r_new + (||r_new||^2 / ||r||^2) p; r <- r_new - 10
return x
Line L1 is the back projection of the weighted data. Line L5 is the only expensive step: it multiplies by the maps, transforms, samples, weights, and goes back. The vector of line L8 is the residual of the normal equations. Line L9 makes the new direction conjugate to the old ones. With equal to a density compensation for a radial or spiral trajectory, the iteration converges in fewer steps on noiseless data; Pruessmann et al. (2001) apply it as a preconditioner.
Example
Take an modified Shepp-Logan phantom, the four ring coil maps of the coil sensitivity map page, and a radial trajectory of 8 spokes with 8 samples each, without noise. The data have values for 64 unknowns. The table gives the relative error (measurement with the code of this page, direct nonuniform DFT).
| weights | error after 5 steps | after 10 steps | steps to | steps to |
|---|---|---|---|---|
| 0.256 | 0.078 | 44 | 49 | |
| (radial density) | 0.116 | 0.055 | 31 | 34 |
Both runs reach the object, as part 4 of the theorem says for noiseless data, and both stop below steps. The density weights change the path, not the end point. On a image with 24 of 32 phase encoding lines kept (a full center of 7 lines and random outer lines), the error was after 5 steps, after 10, and after 20 (measurement).
Correctness
If has full column rank, is Hermitian positive definite and the least squares solution is unique. The conjugate gradient iterates satisfy the Galerkin condition: the residual is orthogonal to the Krylov subspace , with . So minimizes the energy norm over , the norm does not increase, and the residuals, which are mutually orthogonal, vanish after at most steps. For uniform Cartesian undersampling and , the least squares problem splits into the SENSE problems of the folded pixels, so is the SENSE output. The proof gives all steps. These are theorems in exact arithmetic; in floating point the residuals lose orthogonality and the finite termination is lost.
Proof: CG-SENSE reaches the weighted least squares solution in at most n^2 steps, and the energy norm of its error does not increasefull
The setting is that of the algorithm, in exact arithmetic. The image has pixels. The encoding operator maps an image to the samples of each of the coils, , where is the unitary DFT on a Cartesian grid or the nonuniform DFT on a trajectory. is a diagonal matrix with positive entries, and when no weights are given. Let
Line L1 computes , line L2 sets , , and each pass of the loop computes (line L5), (line L6), (line L7), (line L8), and with (line L9). The inner product is .
Theorem. Suppose has full column rank . Then:
- is Hermitian positive definite, and is the unique minimizer of .
- As long as , the iterate minimizes over the Krylov subspace . Hence does not increase with .
- Some has , and then .
- If (no noise), then for every positive .
- For a Cartesian scan that keeps the rows and , is the output of SENSE with .
Proof of 1. because is real and diagonal. For , , because by full column rank and is invertible. The objective has the gradient and the Hessian , which is positive definite, so its only stationary point is its unique minimizer.
Lemma. As long as : (a) for ; (b) the residuals are mutually orthogonal; (c) the directions are -conjugate, for ; (d) .
Proof. (a) holds for , and line L8 keeps it, since . Part (d) follows by induction from , and : each step adds at most one power of . For (b) and (c), use induction on . Suppose they hold up to . The choice of and (since is a multiple of , which is -conjugate to ) give . For , , because lies in the span of , which are -conjugate to . So (b) holds up to . For (c), by line L8, so for . For , and , while ; the sum is 0.
Proof of 2. By (d), . By (a) and (b), is orthogonal to , which span . So for every , , and the last term is 0. Hence is the minimizer over . The subspaces are nested, , so the minimum does not increase.
Proof of 3. Nonzero mutually orthogonal vectors in number at most , so by (b) some with is zero. Then by (a), so . Line L4 stops the loop there.
Proof of 4. With , , the least possible value, and the minimizer is unique by part 1.
Proof of 5. By the folding lemma on the SENSE page, the kept rows of coil are times the DFT of size , , of the folded image . That DFT is times a unitary map, so , where are the folded images from the data, the unfolding matrix and the pixel group of . The right side is a sum of independent SENSE objectives, one for each folded pixel, so the two problems have the same minimizers.
Remarks.
- In floating point the residuals lose their orthogonality, and CG does not stop exactly after steps. The bound with the condition number of is the standard rate in exact arithmetic.
- With noise, is the weighted least squares solution, not the object. Stopping early regularizes; the choice of the stopping index is then a heuristic unless the noise level is known.
- The weights change the solution when the data are noisy or inconsistent. For noiseless data they change only the speed (part 4).
Complexity
In the real RAM, one iteration costs one application of and one of , plus for the vector updates. On a Cartesian grid with an FFT, one application costs . On a trajectory with a nonuniform FFT of fixed kernel width and oversampling, it costs ; the direct nonuniform DFT of the code costs . The nonuniform FFT is not a reconstruction by itself: it only applies and fast, and CG-SENSE calls it twice per iteration. With iterations the total is . The bound holds in exact arithmetic. In practice the iteration stops when , and the number of steps depends on the condition number of , which grows with the g-factor. The memory holds a few images and one data vector, .
Properties
- Least squares solution. With full column rank, the iteration reaches in at most steps in exact arithmetic (theorem).
- Monotone error. does not increase (theorem). The test of this page checks it at each step on a radial problem. The Euclidean error does not increase either (Hestenes and Stiefel 1952), and the weighted residual does not increase, because its square differs from by a constant. The plain data residual is not monotone in general when is not a multiple of the identity. The tests do not check these.
- Same as SENSE for uniform Cartesian sampling. For , the limit is the SENSE output (theorem). The test of this page checks it on a image with and noise to .
- Matrix free. Only and are needed, so any trajectory, field map or other linear term can be added to .
- Same noise as SENSE at convergence. At the solution the noise covariance is the one of the least squares estimate; the g-factor describes it for uniform Cartesian sampling.
Variants and improvements
- CGLS and LSQR. CGLS runs the same iteration on without forming the normal equations, with better behavior in floating point. Its iterates are the same in exact arithmetic.
- Regularized CG-SENSE. Adding or to the objective gives a better conditioned system, the Tikhonov form. Early stopping regularizes as well.
- Preconditioning. Density compensation in , or a diagonal preconditioner in the image, reduces the number of steps.
- Nonlinear priors. Compressed sensing MRI adds a sparsity term and replaces CG by a proximal method, with the same .
- k-space alternatives. SPIRiT poses a consistency problem in k-space with a calibrated kernel instead of explicit maps, and also solves it with conjugate gradients.
When to use it
Use CG-SENSE for non-Cartesian trajectories and for Cartesian patterns that SENSE cannot unfold pixel by pixel, such as variable density or random line patterns, when good coil maps are known. On uniform Cartesian data, direct SENSE gives the same result faster. With noisy data and a high g-factor, stop early or add regularization. When the maps are not available, use ESPIRiT to estimate them, or a k-space method such as SPIRiT.
Pitfalls
- Adjoint that is not the adjoint. Line L5 needs the exact adjoint of . A gridding operator with a different kernel for the two directions breaks the theorem, and the iteration can stall or diverge. An adjoint test, small, finds the error.
- Weights in the wrong place. must appear in line L1 and inside line L5. Weighting only line L1 solves a different, non-Hermitian system.
- Running to convergence on noisy data. With a high g-factor, the late iterations fit the noise. The semi-convergence of the error is the reason; choose the stopping index or a regularization weight.
- Rank deficiency. Where all maps are zero, or where the trajectory leaves a gap that the coils cannot fill, does not have full column rank. CG then converges to the solution of least norm in the range, and the missing part stays zero.
- Floating point. The residual of line L8 is updated, not recomputed, and drifts from after many steps.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cg-sense/. The authors are listed in prov/CCN5EK.jsonl.
"""CG-SENSE: iterative SENSE for any k-space trajectory (Pruessmann, Weiger, Boernert and Boesiger 2001).
The model is y = E x + e with the encoding operator E x = (M F (s_k x))_k for
coils k = 1..c: multiply by the coil map, transform, keep the samples. The
method runs the conjugate gradient method (Hestenes and Stiefel 1952) on the
normal equations
E^H D E x = E^H D y,
where D is a positive diagonal weight on the samples (the density
compensation; D = 1 gives the plain least squares solution). E is given as
two functions, so the same code works for a Cartesian mask (with the FFT)
and for a non-Cartesian trajectory (here with a direct nonuniform DFT).
Images are flat row-major lists of n^2 complex numbers. Data are flat lists:
coil 0 first, then coil 1, and so on.
"""
import cmath
import math
from typing import Callable, Optional, Sequence
from imgkit import dft2, idft2
Vector = list[complex]
Operator = Callable[[Sequence[complex]], Vector]
def _dot(u: Sequence[complex], v: Sequence[complex]) -> complex:
return sum(a.conjugate() * b for a, b in zip(u, v))
def cartesian_ops(maps: Sequence[Sequence[Sequence[complex]]], mask: Sequence[Sequence[bool]]):
"""E and E^H for a Cartesian sampling mask (n x n booleans) with the unitary DFT F / n."""
n = len(mask)
where = [(i, j) for i in range(n) for j in range(n) if mask[i][j]]
def apply_e(x: Sequence[complex]) -> Vector:
out = []
for s in maps:
img = [[s[i][j] * x[i * n + j] for j in range(n)] for i in range(n)]
ksp = dft2(img)
out.extend(ksp[i][j] / n for i, j in where)
return out
def apply_eh(y: Sequence[complex]) -> Vector:
out = [0j] * (n * n)
per = len(where)
for k, s in enumerate(maps):
ksp = [[0j] * n for _ in range(n)]
for t, (i, j) in enumerate(where):
ksp[i][j] = y[k * per + t]
img = idft2(ksp)
for i in range(n):
for j in range(n):
out[i * n + j] += s[i][j].conjugate() * img[i][j] * n
return out
return apply_e, apply_eh
def nudft_ops(maps: Sequence[Sequence[Sequence[complex]]], points: Sequence[tuple[float, float]]):
"""E and E^H for k-space points (kx, ky) in cycles per field of view, by direct sums.
Pixel (i, j) sits at (j - n/2, i - n/2) in pixel units, and the sample at
(kx, ky) of coil k is (1/n) sum s_k x exp(-2 pi i (kx (j - n/2) + ky (i - n/2)) / n).
This is the nonuniform DFT; a fast code would use a nonuniform FFT instead.
"""
n = len(maps[0])
h = n / 2.0
phase = [
[cmath.exp(-2j * math.pi * (kx * (j - h) + ky * (i - h)) / n) / n for i in range(n) for j in range(n)]
for kx, ky in points
]
def apply_e(x: Sequence[complex]) -> Vector:
out = []
for s in maps:
sx = [s[i][j] * x[i * n + j] for i in range(n) for j in range(n)]
out.extend(sum(a * b for a, b in zip(row, sx)) for row in phase)
return out
def apply_eh(y: Sequence[complex]) -> Vector:
out = [0j] * (n * n)
m = len(points)
for k, s in enumerate(maps):
acc = [0j] * (n * n)
for t, row in enumerate(phase):
yt = y[k * m + t]
if yt != 0:
for q in range(n * n):
acc[q] += row[q].conjugate() * yt
for i in range(n):
for j in range(n):
out[i * n + j] += s[i][j].conjugate() * acc[i * n + j]
return out
return apply_e, apply_eh
def cg_sense(
y: Sequence[complex],
apply_e: Operator,
apply_eh: Operator,
size: int,
iters: int,
weights: Optional[Sequence[float]] = None,
tol: float = 0.0,
callback: Optional[Callable[[int, Vector], None]] = None,
) -> Vector:
"""Solve E^H D E x = E^H D y by CG from x = 0 with at most iters steps.
size is the number of pixels, weights the diagonal of D (None for D = 1).
The loop stops early when ||r|| <= tol ||b||. callback(t, x) sees each iterate.
"""
def weigh(v):
return list(v) if weights is None else [w * a for w, a in zip(weights, v)]
def normal(v):
return apply_eh(weigh(apply_e(v)))
b = apply_eh(weigh(y)) # @line L1
x = [0j] * size # @line L2
r = list(b)
p = list(r)
rr = _dot(r, r).real
bnorm = math.sqrt(_dot(b, b).real)
for t in range(iters): # @line L3
if rr == 0.0 or math.sqrt(rr) <= tol * bnorm: # @line L4
break
q = normal(p) # @line L5
alpha = rr / _dot(p, q).real # @line L6
x = [xi + alpha * pi for xi, pi in zip(x, p)] # @line L7
r = [ri - alpha * qi for ri, qi in zip(r, q)] # @line L8
rr_new = _dot(r, r).real
p = [ri + (rr_new / rr) * pi for ri, pi in zip(r, p)] # @line L9
rr = rr_new
if callback is not None:
callback(t + 1, x)
return x # @line L10
def radial_points(spokes: int, samples: int) -> list[tuple[float, float]]:
"""A radial trajectory: spokes through the center at angles pi s / spokes, samples at r = t - (samples - 1) / 2."""
pts = []
for s in range(spokes):
th = math.pi * s / spokes
for t in range(samples):
r = t - (samples - 1) / 2.0
pts.append((r * math.cos(th), r * math.sin(th)))
return pts
def radial_density(points: Sequence[tuple[float, float]]) -> list[float]:
"""A simple density compensation for a radial trajectory: the distance |k| to the center."""
return [math.hypot(kx, ky) for kx, ky in points]
imgkit.py 322 lines
# SPDX-License-Identifier: MIT
# Shared helper of the imaging and inverse problems pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small images and signals for the imaging and inverse problems pages.
Conventions:
- A signal is a list of numbers. An image is a list of rows, img[i][j], with
row i from the top and column j from the left.
- An n x n image covers the square [-1, 1]^2. The center of pixel (i, j) is
x_j = -1 + (2 j + 1) / n and y_i = 1 - (2 i + 1) / n, so y goes up.
- DFT: X_k = sum_j x_j exp(-2 pi i j k / n), unnormalized; the inverse has
the factor 1 / n. Index k stands for frequency k for k < n / 2 and k - n
otherwise. fftshift moves the zero frequency to position n // 2.
- Periodic convolution kernels are stored with their center at index 0
(wrapped around), so a delta kernel gives the identity and no shift.
"""
import cmath
import math
# ------------------------------------------------------------------ images
def new_image(n1, n2, value=0.0):
"""An n1 x n2 image (n1 rows, n2 columns) filled with value."""
return [[value] * n2 for _ in range(n1)]
def img_add(a, b):
"""The pixelwise sum a + b."""
return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
def img_scale(a, c):
"""The image c a."""
return [[c * x for x in row] for row in a]
def img_dot(a, b):
"""<a, b> = sum conj(a_ij) b_ij."""
return sum(x.conjugate() * y for ra, rb in zip(a, b) for x, y in zip(ra, rb))
def img_norm(a):
"""The Euclidean (Frobenius) norm of an image."""
return math.sqrt(sum(abs(x) ** 2 for row in a for x in row))
def flatten(img):
"""Row-major vector of an image."""
return [x for row in img for x in row]
def unflatten(v, n1, n2):
"""The n1 x n2 image of a row-major vector."""
return [list(v[i * n2:(i + 1) * n2]) for i in range(n1)]
# ------------------------------------------------------------------ DFT
def _is_pow2(n):
return n > 0 and n & (n - 1) == 0
def _fft_pow2(x):
"""Iterative radix-2 FFT, unnormalized forward transform."""
n = len(x)
a = [complex(v) for v in x]
j = 0
for i in range(1, n):
bit = n >> 1
while j & bit:
j ^= bit
bit >>= 1
j |= bit
if i < j:
a[i], a[j] = a[j], a[i]
size = 2
while size <= n:
half = size // 2
tw = [cmath.exp(-2j * math.pi * k / size) for k in range(half)]
for start in range(0, n, size):
for k in range(half):
u = a[start + k]
v = a[start + k + half] * tw[k]
a[start + k] = u + v
a[start + k + half] = u - v
size *= 2
return a
def dft(x):
"""X_k = sum_j x_j exp(-2 pi i j k / n). Radix-2 FFT when n is a power of 2."""
n = len(x)
if n == 0:
return []
if _is_pow2(n):
return _fft_pow2(x)
w = [cmath.exp(-2j * math.pi * t / n) for t in range(n)]
return [sum(x[j] * w[(j * k) % n] for j in range(n)) for k in range(n)]
def idft(xf):
"""x_j = (1/n) sum_k X_k exp(2 pi i j k / n)."""
n = len(xf)
if n == 0:
return []
y = dft([complex(v).conjugate() for v in xf])
return [v.conjugate() / n for v in y]
def _rows_then_cols(img, f):
rows = [f(row) for row in img]
cols = [f(list(col)) for col in zip(*rows)]
return [list(r) for r in zip(*cols)]
def dft2(img):
"""2D DFT: X_kl = sum_jq x_jq exp(-2 pi i (j k / n1 + q l / n2))."""
return _rows_then_cols(img, dft)
def idft2(img):
"""Inverse 2D DFT, with the factor 1 / (n1 n2)."""
return _rows_then_cols(img, idft)
def _shift1(x, s):
return list(x[s:]) + list(x[:s])
def fftshift(x):
"""Move the zero frequency to position n // 2 (1D, or both axes of an image)."""
if x and isinstance(x[0], (list, tuple)):
rows = [fftshift(r) for r in x]
return _shift1(rows, (len(rows) + 1) // 2)
return _shift1(x, (len(x) + 1) // 2)
def ifftshift(x):
"""The inverse of fftshift (1D, or both axes of an image)."""
if x and isinstance(x[0], (list, tuple)):
rows = [ifftshift(r) for r in x]
return _shift1(rows, len(rows) // 2)
return _shift1(x, len(x) // 2)
def circ_conv(x, h):
"""Periodic convolution y_i = sum_j h_j x_{(i - j) mod n}, kernel centered at index 0."""
n = len(x)
nz = [(j, hj) for j, hj in enumerate(h) if hj != 0]
return [sum(hj * x[(i - j) % n] for j, hj in nz) for i in range(n)]
def circ_conv2(img, h):
"""Periodic 2D convolution with the kernel h centered at index (0, 0)."""
n1, n2 = len(img), len(img[0])
nz = [(p, q, h[p][q]) for p in range(len(h)) for q in range(len(h[0])) if h[p][q] != 0]
out = new_image(n1, n2)
for i in range(n1):
for j in range(n2):
out[i][j] = sum(v * img[(i - p) % n1][(j - q) % n2] for p, q, v in nz)
return out
# ------------------------------------------------------------------ phantoms
def pixel_centers(n):
"""(xs, ys): xs[j] = -1 + (2 j + 1) / n and ys[i] = 1 - (2 i + 1) / n."""
xs = [-1.0 + (2 * j + 1) / n for j in range(n)]
ys = [1.0 - (2 * i + 1) / n for i in range(n)]
return xs, ys
# Rows: rho, A, B, x0, y0, phi (degrees). A is the semi-axis along the
# direction phi (counterclockwise from the x axis), B the other semi-axis.
# Geometry and densities of Shepp and Logan (1974), as reproduced in Kak and
# Slaney, Principles of Computerized Tomographic Imaging, Table 3.1. The value
# at the center (0, 0) is 2 - 0.98 = 1.02.
SHEPP_LOGAN = [
(2.0, 0.92, 0.69, 0.0, 0.0, 90.0),
(-0.98, 0.874, 0.6624, 0.0, -0.0184, 90.0),
(-0.02, 0.31, 0.11, 0.22, 0.0, 72.0),
(-0.02, 0.41, 0.16, -0.22, 0.0, 108.0),
(0.01, 0.25, 0.21, 0.0, 0.35, 90.0),
(0.01, 0.046, 0.046, 0.0, 0.1, 0.0),
(0.01, 0.046, 0.046, 0.0, -0.1, 0.0),
(0.01, 0.046, 0.023, -0.08, -0.605, 0.0),
(0.01, 0.023, 0.023, 0.0, -0.605, 0.0),
(0.01, 0.046, 0.023, 0.06, -0.605, 90.0),
]
# The same ellipses with the gray levels of Toft (1996), which give more
# contrast. The value at the center is 1 - 0.8 = 0.2.
MODIFIED_SHEPP_LOGAN = [
(rho, a, b, x0, y0, phi)
for rho, (_, a, b, x0, y0, phi) in zip(
(1.0, -0.8, -0.2, -0.2, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1), SHEPP_LOGAN
)
]
def ellipse_value(x, y, table):
"""The phantom value at the point (x, y): the sum of rho over the ellipses that hold it."""
total = 0.0
for rho, a, b, x0, y0, phi in table:
c, s = math.cos(math.radians(phi)), math.sin(math.radians(phi))
dx, dy = x - x0, y - y0
u = dx * c + dy * s
v = -dx * s + dy * c
if (u / a) ** 2 + (v / b) ** 2 <= 1.0:
total += rho
return total
def ellipse_phantom(n, table):
"""The n x n image of an ellipse table, sampled at the pixel centers."""
xs, ys = pixel_centers(n)
return [[ellipse_value(x, y, table) for x in xs] for y in ys]
def disk_phantom(n, radius):
"""1 at pixel centers with x^2 + y^2 <= radius^2, 0 elsewhere."""
xs, ys = pixel_centers(n)
r2 = radius * radius
return [[1.0 if x * x + y * y <= r2 else 0.0 for x in xs] for y in ys]
def spikes_1d(n, positions, amplitudes):
"""A signal of length n with the given amplitudes at the given positions."""
out = [0.0] * n
for p, a in zip(positions, amplitudes):
out[p] += a
return out
# ------------------------------------------------------------------ projector
def parallel_beam_matrix(n, angles, nbins):
"""Pixel-driven discrete Radon transform of an n x n image on [-1, 1]^2.
Each pixel center (x, y) projects to s = x cos(theta) + y sin(theta). Its
value times the pixel area over the bin width is split linearly between
the two nearest bin centers. The bins cover [-sqrt(2), sqrt(2)]. Row
a * nbins + b holds angle a and bin b; column i * n + j holds pixel (i, j).
Returns the sparse rows, each a list of (column, weight) pairs.
Pixel-driven projection has a ripple: with a bin width close to the pixel
size, a disk projection is off by up to about 10 percent in some bins. A
bin of about twice the pixel size (nbins = 23 for n = 32) keeps it near
1 percent.
"""
xs, ys = pixel_centers(n)
smax = math.sqrt(2.0)
width = 2.0 * smax / nbins
scale = (2.0 / n) ** 2 / width
rows = []
for theta in angles:
c, s = math.cos(theta), math.sin(theta)
acc = [dict() for _ in range(nbins)]
for i, y in enumerate(ys):
for j, x in enumerate(xs):
t = (x * c + y * s + smax) / width - 0.5
b0 = math.floor(t)
frac = t - b0
col = i * n + j
for b, w in ((b0, 1.0 - frac), (b0 + 1, frac)):
if 0 <= b < nbins and w > 0.0:
acc[b][col] = acc[b].get(col, 0.0) + w * scale
rows.extend(sorted(d.items()) for d in acc)
return rows
def sp_matvec(rows, x):
"""y = A x for sparse rows of (column, weight) pairs."""
return [sum(w * x[c] for c, w in row) for row in rows]
def sp_rmatvec(rows, y, ncols):
"""x = A^H y for sparse rows of (column, weight) pairs and ncols columns."""
out = [0.0] * ncols
for row, yi in zip(rows, y):
if yi == 0:
continue
for c, w in row:
out[c] += w.conjugate() * yi
return out
# ------------------------------------------------------------------ noise
def gauss_noise(rng, shape, sigma):
"""Independent N(0, sigma^2) values: a list for an int shape, an image for (n1, n2)."""
if isinstance(shape, int):
return [rng.gauss(0.0, sigma) for _ in range(shape)]
n1, n2 = shape
return [[rng.gauss(0.0, sigma) for _ in range(n2)] for _ in range(n1)]
def _poisson_small(rng, lam):
"""Knuth's product method, exact for a mean lam <= 30."""
limit = math.exp(-lam)
k, p = 0, rng.random()
while p > limit:
k += 1
p *= rng.random()
return k
def poisson_sample(rng, lam):
"""An exact Poisson(lam) sample: a sum of Knuth samples with means at most 30."""
if lam < 0:
raise ValueError("negative mean")
total = 0
while lam > 30.0:
total += _poisson_small(rng, 30.0)
lam -= 30.0
if lam > 0.0:
total += _poisson_small(rng, lam)
return total
imgla.py 259 lines
# SPDX-License-Identifier: MIT
# Shared helper of the imaging and inverse problems pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Dense linear algebra on lists of rows (float, complex or Fraction entries).
A matrix is a list of rows. A vector is a list of numbers. The inner product
is <u, v> = sum_i conj(u_i) v_i, linear in the second argument, so that the
adjoint A^H satisfies <A x, y> = <x, A^H y>.
"""
import math
def _flat(x):
"""Flatten a list of rows (an image) into one list; a vector is returned as is."""
if x and isinstance(x[0], (list, tuple)):
return [v for row in x for v in row]
return x
def zeros(m, n):
"""The m x n zero matrix."""
return [[0.0] * n for _ in range(m)]
def eye(n):
"""The n x n identity matrix."""
out = zeros(n, n)
for i in range(n):
out[i][i] = 1.0
return out
def transpose(a):
"""A^T."""
return [list(col) for col in zip(*a)]
def conj_transpose(a):
"""A^H, the conjugate transpose."""
return [[v.conjugate() for v in col] for col in zip(*a)]
def matmul(a, b):
"""The product A B."""
bt = list(zip(*b))
return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]
def matvec(a, x):
"""The product A x."""
return [sum(v * w for v, w in zip(row, x)) for row in a]
def rmatvec(a, y):
"""The product A^H y."""
n = len(a[0]) if a else 0
out = [0.0] * n
for row, yi in zip(a, y):
if yi == 0:
continue
for j, v in enumerate(row):
out[j] += v.conjugate() * yi
return out
def dot(u, v):
"""<u, v> = sum_i conj(u_i) v_i. Images (lists of rows) are flattened."""
return sum(a.conjugate() * b for a, b in zip(_flat(u), _flat(v)))
def norm2(x):
"""The Euclidean norm. Images (lists of rows) are flattened."""
return math.sqrt(sum(abs(v) ** 2 for v in _flat(x)))
def solve(a, b):
"""Solve A x = b by Gaussian elimination with partial pivoting.
b is a vector or a matrix (a list of rows). A must be square and
nonsingular; a zero pivot raises ValueError. Fractions stay exact.
"""
n = len(a)
vec = not (b and isinstance(b[0], (list, tuple)))
rhs = [[bi] for bi in b] if vec else [list(r) for r in b]
m = [list(row) + rhs[i] for i, row in enumerate(a)]
w = len(m[0])
for c in range(n):
p = max(range(c, n), key=lambda r: abs(m[r][c]))
if m[p][c] == 0:
raise ValueError("singular matrix")
m[c], m[p] = m[p], m[c]
piv = m[c][c]
for r in range(c + 1, n):
f = m[r][c] / piv
if f != 0:
mr, mc = m[r], m[c]
for j in range(c, w):
mr[j] -= f * mc[j]
x = [[0.0] * (w - n) for _ in range(n)]
for r in range(n - 1, -1, -1):
for j in range(w - n):
s = m[r][n + j] - sum(m[r][k] * x[k][j] for k in range(r + 1, n))
x[r][j] = s / m[r][r]
return [row[0] for row in x] if vec else x
def cholesky(a):
"""Lower triangular L with A = L L^H for a Hermitian positive definite A."""
n = len(a)
low = zeros(n, n)
for j in range(n):
d = a[j][j] - sum(abs(low[j][k]) ** 2 for k in range(j))
d = d.real if isinstance(d, complex) else d
if not d > 0:
raise ValueError("matrix is not positive definite")
ljj = math.sqrt(d)
low[j][j] = ljj
for i in range(j + 1, n):
s = a[i][j] - sum(low[i][k] * low[j][k].conjugate() for k in range(j))
low[i][j] = s / ljj
return low
def cho_solve(low, b):
"""Solve (L L^H) x = b, with L from cholesky."""
n = len(low)
z = [0.0] * n
for i in range(n):
z[i] = (b[i] - sum(low[i][k] * z[k] for k in range(i))) / low[i][i]
x = [0.0] * n
for i in range(n - 1, -1, -1):
s = z[i] - sum(low[k][i].conjugate() * x[k] for k in range(i + 1, n))
x[i] = s / low[i][i].conjugate()
return x
def _rot_params(app, aqq, apq):
"""c, s of the Jacobi rotation that zeroes the (p, q) entry of [[app, apq], [apq, aqq]]."""
theta = (aqq - app) / (2.0 * apq)
t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
c = 1.0 / math.sqrt(1.0 + t * t)
return c, c * t
def sym_eig(a, tol=1e-15, max_sweeps=100):
"""Eigenvalues (ascending) and eigenvectors (as columns) of a real symmetric matrix.
Cyclic Jacobi method. Returns (w, Q) with A = Q diag(w) Q^T.
"""
n = len(a)
m = [[float(v) for v in row] for row in a]
q = eye(n)
for _ in range(max_sweeps):
off = sum(m[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
scale = sum(m[i][i] ** 2 for i in range(n)) + off
if off <= (tol * tol) * scale or off == 0.0:
break
for p in range(n - 1):
for r in range(p + 1, n):
apq = m[p][r]
if apq == 0.0:
continue
c, s = _rot_params(m[p][p], m[r][r], apq)
for k in range(n):
mkp, mkr = m[k][p], m[k][r]
m[k][p] = c * mkp - s * mkr
m[k][r] = s * mkp + c * mkr
mp, mr = m[p], m[r]
for k in range(n):
mpk, mrk = mp[k], mr[k]
mp[k] = c * mpk - s * mrk
mr[k] = s * mpk + c * mrk
m[p][r] = m[r][p] = 0.0
for k in range(n):
qkp, qkr = q[k][p], q[k][r]
q[k][p] = c * qkp - s * qkr
q[k][r] = s * qkp + c * qkr
order = sorted(range(n), key=lambda i: m[i][i])
w = [m[i][i] for i in order]
qs = [[q[k][i] for i in order] for k in range(n)]
return w, qs
def _complete(cols, m):
"""Replace zero columns of an m-row column list by unit vectors orthogonal to the others."""
for idx, col in enumerate(cols):
if any(v != 0.0 for v in col):
continue
for e in range(m):
cand = [0.0] * m
cand[e] = 1.0
for _ in range(2):
for jdx, other in enumerate(cols):
if jdx == idx or not any(v != 0.0 for v in other):
continue
h = sum(a * b for a, b in zip(other, cand))
cand = [a - h * b for a, b in zip(cand, other)]
nrm = math.sqrt(sum(v * v for v in cand))
if nrm > 0.5:
cols[idx] = [v / nrm for v in cand]
break
return cols
def svd(a, tol=1e-15, max_sweeps=100):
"""Thin SVD of a real m x n matrix by one-sided Jacobi (Hestenes).
Returns (U, S, V) with p = min(m, n): U is m x p, S a list of p values in
descending order, V is n x p, U^T U = I, V^T V = I and A = U diag(S) V^T.
"""
m, n = len(a), len(a[0])
if m < n:
v, s, u = svd(transpose(a), tol, max_sweeps)
return u, s, v
cols = [[float(a[i][j]) for i in range(m)] for j in range(n)]
vcols = [[1.0 if i == j else 0.0 for i in range(n)] for j in range(n)]
for _ in range(max_sweeps):
rotated = False
for p in range(n - 1):
for r in range(p + 1, n):
cp, cr = cols[p], cols[r]
alpha = sum(x * x for x in cp)
beta = sum(x * x for x in cr)
gamma = sum(x * y for x, y in zip(cp, cr))
if gamma == 0.0 or abs(gamma) <= tol * math.sqrt(alpha * beta):
continue
rotated = True
c, s = _rot_params(alpha, beta, gamma)
cols[p] = [c * x - s * y for x, y in zip(cp, cr)]
cols[r] = [s * x + c * y for x, y in zip(cp, cr)]
vp, vr = vcols[p], vcols[r]
vcols[p] = [c * x - s * y for x, y in zip(vp, vr)]
vcols[r] = [s * x + c * y for x, y in zip(vp, vr)]
if not rotated:
break
sig = [math.sqrt(sum(x * x for x in col)) for col in cols]
# A column below 1e-150 times the largest one is zero to working precision;
# its squares underflow, so its direction carries no information.
floor = max(sig) * 1e-150 if sig else 0.0
sig = [t if t > floor and t > 1e-150 else 0.0 for t in sig]
order = sorted(range(n), key=lambda j: -sig[j])
s_out = [sig[j] for j in order]
ucols = [[x / sig[j] for x in cols[j]] if sig[j] > 0.0 else [0.0] * m for j in order]
ucols = _complete(ucols, m)
u = [[ucols[j][i] for j in range(n)] for i in range(m)]
v = [[vcols[j][i] for j in order] for i in range(n)]
return u, s_out, v
def adjoint_gap(apply_a, apply_ah, x, y):
"""|<A x, y> - <x, A^H y>| / (||A x|| ||y||) for given functions A and A^H.
x and y may be vectors or images (lists of rows). If the denominator is
zero, the absolute gap is returned.
"""
ax = apply_a(x)
gap = abs(dot(ax, y) - dot(x, apply_ah(y)))
den = norm2(ax) * norm2(y)
return gap / den if den > 0.0 else gap
test_cg_sense.py 162 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cg-sense/. The authors are listed in prov/CCN5EK.jsonl.
import cmath
import math
import random
from cg_sense import cartesian_ops, cg_sense, nudft_ops, radial_density, radial_points
from imgkit import MODIFIED_SHEPP_LOGAN, ellipse_phantom, pixel_centers
from imgla import adjoint_gap, solve
def ring_maps(n, c=4):
"""Smooth synthetic coil maps: Gaussian profiles of coils on a ring of radius 1.2, with a phase."""
xs, ys = pixel_centers(n)
maps = []
for k in range(c):
ang = math.radians(20.0 + 360.0 * k / c)
cx, cy = 1.2 * math.cos(ang), 1.2 * math.sin(ang)
maps.append([
[
math.exp(-((x - cx) ** 2 + (y - cy) ** 2) / 1.2) * cmath.exp(1j * (0.9 * k + 0.4 * x - 0.3 * y))
for x in xs
]
for y in ys
])
return maps
def phantom_vec(n):
xs, _ = pixel_centers(n)
img = ellipse_phantom(n, MODIFIED_SHEPP_LOGAN)
return [v * cmath.exp(0.3j * x) for row in img for v, x in zip(row, xs)]
def rel(a, b):
return math.sqrt(sum(abs(u - v) ** 2 for u, v in zip(a, b)) / sum(abs(v) ** 2 for v in b))
def dense_solution(apply_e, apply_eh, size, y, weights):
"""The solution of E^H D E x = E^H D y by Gaussian elimination."""
cols = []
for q in range(size):
e = [0j] * size
e[q] = 1.0
cols.append(apply_eh([w * v for w, v in zip(weights, apply_e(e))]))
a = [[cols[q][p] for q in range(size)] for p in range(size)]
return solve(a, apply_eh([w * v for w, v in zip(weights, y)])), a
def test_adjoint_cartesian_and_nudft():
rng = random.Random(1)
n = 8
maps = ring_maps(n)
mask = [[rng.random() < 0.5 for _ in range(n)] for _ in range(n)]
pts = radial_points(6, 8)
for e, eh in (cartesian_ops(maps, mask), nudft_ops(maps, pts)):
x = [complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(n * n)]
y = [complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(len(e(x)))]
assert adjoint_gap(e, eh, x, y) < 1e-10
def unfold_r2(y_img, maps, n):
"""Per-pixel SENSE for R = 2 (rows kappa even kept), written out for the comparison."""
from imgkit import idft2
m = n // 2
folded = []
for yk in y_img:
sub = [yk[kappa] for kappa in range(0, n, 2)]
folded.append([[v * n for v in row] for row in idft2(sub)])
out = [0j] * (n * n)
for i in range(m):
for j in range(n):
e = [[mp[i][j], mp[i + m][j]] for mp in maps]
gram = [[sum(e[k][p].conjugate() * e[k][q] for k in range(len(maps))) for q in range(2)] for p in range(2)]
rhs = [sum(e[k][p].conjugate() * folded[k][i][j] for k in range(len(maps))) for p in range(2)]
v = solve(gram, rhs)
out[i * n + j], out[(i + m) * n + j] = v[0], v[1]
return out
def test_uniform_cartesian_equals_sense_with_noise():
n = 32
maps = ring_maps(n)
mask = [[kappa % 2 == 0] * n for kappa in range(n)]
e, eh = cartesian_ops(maps, mask)
rng = random.Random(4)
y = [v + complex(rng.gauss(0, 0.002), rng.gauss(0, 0.002)) for v in e(phantom_vec(n))]
x = cg_sense(y, e, eh, n * n, 45, tol=1e-12)
# put the samples back on the grid for the direct SENSE unfolding
per = n * n // 2
y_img = []
for k in range(len(maps)):
arr = [[0j] * n for _ in range(n)]
t = 0
for kappa in range(n):
for l in range(n):
if mask[kappa][l]:
arr[kappa][l] = y[k * per + t]
t += 1
y_img.append(arr)
assert rel(x, unfold_r2(y_img, maps, n)) < 1e-8
def test_noiseless_variable_density_mask_converges_to_the_object():
n = 32
maps = ring_maps(n)
rng = random.Random(9)
keep = [abs(kappa if kappa < n // 2 else kappa - n) < 4 or rng.random() < 0.6 for kappa in range(n)]
mask = [[keep[kappa]] * n for kappa in range(n)]
e, eh = cartesian_ops(maps, mask)
x0 = phantom_vec(n)
errs = []
cg_sense(e(x0), e, eh, n * n, 30, callback=lambda t, x: errs.append(rel(x, x0)))
assert errs[-1] < 1e-6
assert errs[-1] < errs[4] < errs[0]
def test_radial_matches_dense_least_squares_with_and_without_density():
n = 8
maps = ring_maps(n)
pts = radial_points(8, 8)
e, eh = nudft_ops(maps, pts)
rng = random.Random(2)
y = [v + complex(rng.gauss(0, 0.01), rng.gauss(0, 0.01)) for v in e(phantom_vec(n))]
dens = radial_density(pts) * len(maps)
for w in (None, dens):
ref, _ = dense_solution(e, eh, n * n, y, w or [1.0] * len(y))
x = cg_sense(y, e, eh, n * n, 64, weights=w, tol=1e-13)
assert rel(x, ref) < 1e-8
def test_energy_norm_error_does_not_increase():
n = 8
maps = ring_maps(n)
pts = radial_points(8, 8)
e, eh = nudft_ops(maps, pts)
rng = random.Random(6)
y = [complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(len(pts) * len(maps))]
ones = [1.0] * len(y)
xs, a = dense_solution(e, eh, n * n, y, ones)
def energy(x):
d = [u - v for u, v in zip(x, xs)]
ad = [sum(a[p][q] * d[q] for q in range(n * n)) for p in range(n * n)]
return sum(u.conjugate() * v for u, v in zip(d, ad)).real
vals = [energy([0j] * (n * n))]
cg_sense(y, e, eh, n * n, 64, callback=lambda t, x: vals.append(energy(x)))
assert all(b <= a_ * (1 + 1e-9) + 1e-12 for a_, b in zip(vals, vals[1:]))
assert vals[-1] < 1e-12 * vals[0]
def test_noiseless_radial_reaches_the_object():
n = 8
maps = ring_maps(n)
pts = radial_points(8, 8)
e, eh = nudft_ops(maps, pts)
x0 = phantom_vec(n)
dens = radial_density(pts) * len(maps)
for w in (None, dens):
assert rel(cg_sense(e(x0), e, eh, n * n, 64, weights=w, tol=1e-13), x0) < 1e-6
History
Hestenes and Stiefel published the conjugate gradient method in 1952. Pruessmann, Weiger, Scheidegger and Boesiger published SENSE for Cartesian scans in 1999. In 2001 Pruessmann, Weiger, Boernert and Boesiger wrote the reconstruction for any trajectory as a large linear system, solved it with conjugate gradients, applied the encoding operator with gridding and FFTs, and used density compensation as a preconditioner. The method became the base of most later iterative MR reconstructions with coil arrays, including compressed sensing MRI.
References
- Klaas P. Pruessmann, Markus Weiger, Peter Boernert and Peter Boesiger, Advances in sensitivity encoding with arbitrary k-space trajectories, Magnetic Resonance in Medicine 46(4), 2001, 638 to 651, the encoding operator for any trajectory, the conjugate gradient iteration on the normal equations, and the density compensation as a preconditioner (general locator; section numbers not confirmed)
- Magnus R. Hestenes and Eduard Stiefel, Methods of conjugate gradients for solving linear systems, Journal of Research of the National Bureau of Standards 49(6), 1952, 409 to 436, the conjugate gradient method, its finite termination and the minimization of the error norm over the Krylov subspace (general locator)
- Klaas P. Pruessmann, Markus Weiger, Markus B. Scheidegger and Peter Boesiger, SENSE, sensitivity encoding for fast MRI, Magnetic Resonance in Medicine 42(5), 1999, 952 to 962, the least squares model of sensitivity encoding that CG-SENSE solves (general locator)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| 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 CCN5EK Edit this page History Report an error Markdown