Algorithmadvanced
Density compensation
Also called Pipe-Menon density compensation.
Weights for non-Cartesian k-space samples, found by the Pipe-Menon fixed point iteration w <- w / (C w), so that the weighted samples convolved with the gridding kernel give a flat density.
- Solves
- MRI reconstruction
- Time
- O(m^2 + K m q) worst
- Space
- O(m q) extra
- Where
- K = the number of iterations; m = the number of k-space samples; q = the largest number of samples within the kernel radius of one sample
- Model
- Real RAM
- Properties
- deterministicnot exactnot in placeoffline
- Evidence
- Proof sketchCode in 1 languages
- Origin
- James G. Pipe, Padmanabhan Menon, 1999
Density compensation gives each sample of a non-Cartesian k-space trajectory a weight that corrects for how densely the trajectory samples k-space near it. A radial trajectory, for example, samples the center far more densely than the edge. Without weights, gridding and the adjoint nonuniform FFT give an image that is blurred by this extra weight at low frequencies. This page treats the iterative method of Pipe and Menon (1999). It needs only the sample positions and the gridding kernel , and it looks for weights with at every sample . It starts from and repeats . Analytic weights such as the radial ramp exist only for simple trajectories; this method works for any trajectory.
In plain words
A non-Cartesian scan takes its measurements at points that are close together in some places and far apart in others. When the computer adds up the measurements to make a picture, the crowded places count too much. Each measurement needs a weight: small where the points are crowded and large where they are sparse.
The method finds the weights by trial. It starts with equal weights. It then measures how much total weight sits near each point, using the same smoothing shape that the picture step uses. Where that total is too large, the weight of the point goes down; where it is too small, the weight goes up. After a few rounds the total weight near every point is nearly the same.
The problem
The input is a set of sample positions in , in units of the Cartesian grid spacing , and a gridding kernel with and for . A common kernel is the Kaiser-Bessel function , recommended for gridding by Jackson and colleagues (1991), with the width and the shape parameter . The output is a vector of weights such that the weighted sample distribution , convolved with , is close to 1 at every sample. In matrix form, with , the aim is .
The algorithm
PIPE-MENON(k_1..k_m, C, W, K)- 1
for each i: N(i) <- {(j, C_ij) : |k_i - k_j| < W/2 and C_ij > 0} - 2
w_i <- 1 for each i - 3
repeat K times - 4
d_i <- sum over (j, c) in N(i) of c w_j for each i ▷ d = C w - 5
w_i <- w_i / d_i for each i - 6
return w
Line L1 finds the neighbours of each sample. The code of this page does it by brute force in ; a cell grid or a k-d tree finds them faster. Line L4 is the convolution of the weighted samples with the kernel, evaluated at the samples. Line L5 divides each weight by that density. A sample that sees too much weight around it gets a smaller weight, and a sample that sees too little gets a larger one. The weights are used in gridding: the sample is multiplied by before it is spread onto the grid with .
Example
Take a radial trajectory with 16 spokes through the center at angles , each with 16 samples at the radii , so . The kernel is Kaiser-Bessel with and , whose integral over the plane is 2.1497. The residual after iterations was as follows.
| 0 | 1 | 2 | 5 | 10 | 20 | 50 | |
|---|---|---|---|---|---|---|---|
| residual | 19.4 | 0.151 | 0.0508 | 0.00396 |
With the weights are all 1, and the most crowded sample, near the center, sees a kernel sum of 20.4 where 1 is wanted. After 50 iterations the weights on one spoke, which are the same on every spoke by symmetry, compare with the ramp as follows. The ramp is the area of the ring around radius shared among the 32 half spokes, divided by the kernel integral.
| radius | 0.5 | 1.5 | 2.5 | 3.5 | 4.5 | 5.5 | 6.5 | 7.5 |
|---|---|---|---|---|---|---|---|---|
| weight | 0.039 | 0.140 | 0.230 | 0.321 | 0.404 | 0.520 | 0.565 | 0.823 |
| ramp | 0.046 | 0.137 | 0.228 | 0.320 | 0.411 | 0.502 | 0.594 | 0.685 |
In the inner part the weights follow the ramp within a few percent. At the outer edge they are larger, because the outermost samples have no neighbours beyond them, and they oscillate a little near the edge.
Correctness
The proof shows these facts for every input.
- Every iterate is positive and well defined, because ; after the first step every weight is at most .
- A positive vector is a fixed point of line L5 if and only if . So a positive limit, if one exists, is a solution.
- If the kernel is multiplied by , every iterate after the first is divided by .
- Samples at the same position keep equal weights.
The key invariant is . The page does not claim that the iteration converges. Pipe and Menon did not prove convergence, and the system need not have a positive solution (see Pitfalls). In the tests, the iterates matched the direct solution of when it was positive.
Proof: Invariants of the Pipe-Menon density compensation iterationfull
The setting is that of the algorithm. There are sample positions , and a kernel with and for . The matrix has the entries , so it is symmetric, nonnegative, and has the diagonal . The iteration is (line L2) and
Line L1 only stores the nonzero entries of each row of , so line L4 computes exactly.
This page does not claim that the iteration converges. Pipe and Menon give no convergence proof, and examples exist where the system has no positive solution. The statements below are what holds for every input.
Theorem 1 (the iterates are well defined and positive). For every and every , and . For , also .
Proof. By induction on . The start is positive. If , every term is nonnegative, and the diagonal term is . So , line L5 does not divide by zero, and . The same inequality gives .
Theorem 2 (fixed points). A vector with positive entries satisfies for all if and only if .
Proof. Since , the equation holds if and only if .
So if the iterates converge to a positive limit, line L5 is continuous there and the limit solves : the weighted samples, convolved with the kernel, give the value 1 at every sample. If has no positive solution, the iterates cannot converge to a positive vector.
Theorem 3 (scale of the kernel). Let , and let be the iterates for the kernel . Then for every .
Proof. For : . If , then , so .
The weights therefore carry the unit of the inverse kernel. A reconstruction that grids with the kernel must use weights from the same , or rescale them.
Theorem 4 (repeated samples). If , then for every .
Proof. The rows and of are equal, because . By induction, if , then , so . The start has equal entries.
Moreover, the columns and of are equal too, so depends on and only through . If has a positive solution, the two copies share the weight that one sample at that place would get in the system without the repeat, provided that system has a unique solution.
Remarks.
- Theorems 1 to 4 hold for every positive starting vector in place of , except that Theorem 4 needs equal starting values on the repeated samples.
- The fixed points solve , a diagonal scaling equation. This page gives no convergence theorem for the iteration. In the tests, the iterates matched the direct solution of when that solution was positive.
Complexity
The brute force search of line L1 costs distance computations. With a cell grid of cell size it costs on average for evenly spread samples. Each iteration of lines L4 and L5 costs , where is the largest neighbour count, so iterations cost . The neighbour lists take memory. A gridding implementation can also compute by spreading onto an oversampled grid and interpolating back, which costs per iteration for a grid of points.
Properties
- Positive weights. Every iterate is positive (theorem). This is not true of a direct solve of , which can give negative weights.
- Kernel dependent. The weights depend on the kernel and its width, and they carry its scale (theorem). Weights made for one kernel are not right for another.
- Fast first steps. On the radial example the residual fell by a factor of about 130 in the first iteration and below in 10 (measurement).
- No convergence guarantee. On random points in the plane with the Kaiser-Bessel kernel, the residual stopped falling near 0.038, because no positive solution exists (measurement).
- Any trajectory. It needs only positions, so it works for radial, spiral, PROPELLER and random trajectories.
Variants and improvements
- Analytic weights. For radial sampling the ramp ; for spirals the Jacobian of the trajectory, as in Hoge, Kwan and Pike (1997). These need no iteration, but they are wrong where the trajectory deviates from the model, for example at the center of a radial scan.
- Voronoi weights. The area of the Voronoi cell of each sample, a common geometric choice. Rasche and colleagues (1999) treat density compensation for convolution interpolation on arbitrary grids. The cells at the edge of the sampled region need a bound.
- Grid-based evaluation. Line L4 can be done with the gridding operator itself, by spreading the weights onto a grid with and reading the grid back at the samples. This is how the method is often run on large data.
- Weighted variant for PROPELLER. Pipe used a version that also multiplies the weights by a quality factor per blade in PROPELLER.
- Least squares in place of weights. An iterative solver such as the conjugate gradient method, as in CG-SENSE, solves the least squares problem directly; density weights then serve only as a preconditioner.
When to use it
Use density compensation for gridding or for the adjoint nonuniform FFT on any non-Cartesian trajectory, and as a preconditioner for iterative solvers. Compute the weights once per trajectory and kernel, then reuse them for every scan with that trajectory. Use the iterative method when no analytic formula fits the trajectory, or when the trajectory deviates from its design. For conjugate phase reconstruction the same weights serve as .
Pitfalls
- Kernel that differs from the gridding kernel. If line L4 uses a kernel that is not the one used in gridding, or with a different scale, the weights are wrong by the ratio of the two (Theorem 3 of the proof).
- Oscillating weights for a narrow kernel. With the points on a line and the triangle kernel of width 3, the weights after one pass of line L5 are , which look right. The limit, the solution of , is : the extra point at 2.5 gets a large weight and its neighbours small ones. A kernel width close to the gap between samples gives such patterns.
- Slow or no convergence. With the points and the triangle kernel of width 2, the exact solution has zero weights and the iterates approach it slowly, like . When has no positive solution, line L3 should stop after a fixed number of iterations.
- Neighbour search with a radius too small. If line L1 uses a radius below , some kernel terms are lost and is too small.
- Edge of k-space. Samples at the edge have neighbours only on one side, so their weights grow. Some implementations limit the weights at the edge.
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/density-compensation/. The authors are listed in prov/4CW95Q.jsonl.
"""Iterative sampling density compensation (Pipe and Menon 1999).
Input: m k-space sample positions (tuples of floats in grid units, any
dimension) and a radial kernel C(r) that is zero for r >= width / 2. The
method looks for weights w > 0 with sum_j C(|k_i - k_j|) w_j = 1 at every
sample i, so that the weighted samples, convolved with C, give a flat
density. It starts from w = 1 and repeats the update
w_i <- w_i / sum_j C(|k_i - k_j|) w_j.
Facts used by the tests (see proofs/correctness.md):
- every iterate is positive when C(0) > 0 and C >= 0;
- a positive w is a fixed point exactly when C w = 1;
- replacing C by c C (c > 0) divides every iterate after the first by c.
The paper gives no convergence proof, and none is claimed here.
Cost: O(m^2) to build the neighbour lists by brute force, then O(K m q)
for K iterations when each sample has at most q neighbours.
"""
import math
from typing import Callable, Sequence
Point = Sequence[float]
def bessel_i0(x: float) -> float:
"""The modified Bessel function I0 by its power series sum ((x/2)^(2k) / (k!)^2)."""
term, total, k = 1.0, 1.0, 0
q = (x / 2.0) ** 2
while term > 1e-17 * total:
k += 1
term *= q / (k * k)
total += term
return total
def kaiser_bessel(width: float, beta: float) -> Callable[[float], float]:
"""C(r) = I0(beta sqrt(1 - (2 r / width)^2)) / I0(beta) for r < width / 2, else 0."""
norm = bessel_i0(beta)
def c(r: float) -> float:
u = 2.0 * r / width
if u >= 1.0:
return 0.0
return bessel_i0(beta * math.sqrt(1.0 - u * u)) / norm
return c
def triangle(width: float) -> Callable[[float], float]:
"""C(r) = 1 - 2 r / width for r < width / 2, else 0."""
def c(r: float) -> float:
u = 2.0 * r / width
return 1.0 - u if u < 1.0 else 0.0
return c
def neighbours(points: Sequence[Point], kernel: Callable[[float], float], width: float) -> list[list[tuple[int, float]]]:
"""For each sample i, the pairs (j, C(|k_i - k_j|)) with |k_i - k_j| < width / 2."""
m = len(points)
half = width / 2.0
out: list[list[tuple[int, float]]] = [[] for _ in range(m)]
for i in range(m):
for j in range(m):
r = math.dist(points[i], points[j])
if r < half:
v = kernel(r)
if v != 0.0:
out[i].append((j, v))
return out
def pipe_menon(
points: Sequence[Point],
kernel: Callable[[float], float],
width: float,
iters: int = 50,
) -> list[float]:
"""Density compensation weights by the Pipe-Menon fixed-point iteration."""
if kernel(0.0) <= 0.0:
raise ValueError("the kernel must be positive at 0")
nb = neighbours(points, kernel, width) # @line L1
w = [1.0] * len(points) # @line L2
for _ in range(iters): # @line L3
d = [sum(c * w[j] for j, c in row) for row in nb] # @line L4
w = [wi / di for wi, di in zip(w, d)] # @line L5
return w # @line L6
def kernel_matrix(points: Sequence[Point], kernel: Callable[[float], float]) -> list[list[float]]:
"""The dense m x m matrix C_ij = C(|k_i - k_j|)."""
return [[kernel(math.dist(p, q)) for q in points] for p in points]
def residual(points: Sequence[Point], kernel: Callable[[float], float], w: Sequence[float]) -> float:
"""max_i |sum_j C_ij w_j - 1|."""
c = kernel_matrix(points, kernel)
return max(abs(sum(cij * wj for cij, wj in zip(row, w)) - 1.0) for row in c)
def radial_points(spokes: int, samples: int, kmax: float) -> list[tuple[float, float]]:
"""A radial trajectory: spokes through the center at angles pi s / spokes, samples per spoke.
Sample q of a spoke sits at radius kmax (2 q - samples + 1) / samples, so
no spoke has a sample at the exact center when samples is even.
"""
pts = []
for s in range(spokes):
a = math.pi * s / spokes
ca, sa = math.cos(a), math.sin(a)
for q in range(samples):
r = kmax * (2 * q - samples + 1) / samples
pts.append((r * ca, r * sa))
return pts
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_density_compensation.py 119 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/density-compensation/. The authors are listed in prov/4CW95Q.jsonl.
import math
import random
import pytest
from density_compensation import (
bessel_i0,
kaiser_bessel,
kernel_matrix,
neighbours,
pipe_menon,
radial_points,
residual,
triangle,
)
from imgla import matvec, solve
def test_bessel_i0_values():
# I0(0) = 1; I0(1) = 1.2660658777520082; I0(x) e^(-x) sqrt(2 pi x) -> 1 for large x.
assert bessel_i0(0.0) == 1.0
assert bessel_i0(1.0) == pytest.approx(1.2660658777520082, rel=1e-14)
assert bessel_i0(6.0) == pytest.approx(67.23440697647797, rel=1e-13)
def test_neighbour_lists_match_dense_matrix():
rng = random.Random(11)
pts = [(rng.uniform(0, 6), rng.uniform(0, 6)) for _ in range(30)]
kb = kaiser_bessel(3.0, 6.0)
nb = neighbours(pts, kb, 3.0)
dense = kernel_matrix(pts, kb)
for i in range(len(pts)):
row = [0.0] * len(pts)
for j, c in nb[i]:
row[j] = c
assert max(abs(a - b) for a, b in zip(row, dense[i])) < 1e-15
def test_weights_stay_positive():
rng = random.Random(12)
pts = [(rng.uniform(0, 10),) for _ in range(25)]
kb = kaiser_bessel(4.0, 8.0)
for k in (0, 1, 5, 40):
assert min(pipe_menon(pts, kb, 4.0, k)) > 0.0
def test_matches_direct_solve_when_positive_solution_exists():
# Jittered samples with a wide triangle kernel: C w = 1 has a positive solution.
rng = random.Random(13)
pts = [(i + rng.uniform(-0.15, 0.15),) for i in range(40)]
tri = triangle(3.0)
ref = solve(kernel_matrix(pts, tri), [1.0] * len(pts))
assert min(ref) > 0.0
w = pipe_menon(pts, tri, 3.0, 300)
assert max(abs(a - b) for a, b in zip(w, ref)) < 1e-6
assert residual(pts, tri, w) < 1e-6
def test_positive_solution_is_a_fixed_point():
rng = random.Random(14)
pts = [(i + rng.uniform(-0.15, 0.15),) for i in range(30)]
tri = triangle(3.0)
c = kernel_matrix(pts, tri)
ref = solve(c, [1.0] * len(pts))
d = matvec(c, ref)
nxt = [wi / di for wi, di in zip(ref, d)]
assert max(abs(a - b) for a, b in zip(nxt, ref)) < 1e-12
def test_kernel_scaling_divides_weights():
rng = random.Random(15)
pts = [(rng.uniform(0, 8), rng.uniform(0, 8)) for _ in range(40)]
kb = kaiser_bessel(3.0, 6.0)
def kb3(r):
return 3.0 * kb(r)
a = pipe_menon(pts, kb, 3.0, 10)
b = pipe_menon(pts, kb3, 3.0, 10)
assert max(abs(x - 3.0 * y) for x, y in zip(a, b)) < 1e-12
def test_duplicate_sample_splits_its_weight():
rng = random.Random(16)
pts = [(i + rng.uniform(-0.15, 0.15),) for i in range(20)]
tri = triangle(3.0)
w = pipe_menon(pts, tri, 3.0, 300)
dup = pts[:10] + [pts[10], pts[10]] + pts[11:]
wd = pipe_menon(dup, tri, 3.0, 300)
assert wd[10] == pytest.approx(wd[11], rel=1e-12)
assert wd[10] + wd[11] == pytest.approx(w[10], rel=1e-6)
assert max(abs(a - b) for a, b in zip(wd[:10], w[:10])) < 1e-6
def test_radial_weights_follow_the_ramp():
spokes, samples, kmax = 16, 16, 8.0
pts = radial_points(spokes, samples, kmax)
kb = kaiser_bessel(3.0, 6.0)
w = pipe_menon(pts, kb, 3.0, 50)
assert residual(pts, kb, w) < 1e-10
# Expected ramp: w(r) ~ 2 pi r delta / (2 spokes integral of C), delta the step along a spoke.
steps = 3000
h = 1.5 / steps
area = 2.0 * math.pi * h * sum((i + 0.5) * h * kb((i + 0.5) * h) for i in range(steps))
slope = 2.0 * math.pi * (2.0 * kmax / samples) / (2 * spokes * area)
for q in range(samples // 2 + 1, samples - 2):
r = math.hypot(*pts[q])
assert w[q] == pytest.approx(slope * r, rel=0.06)
# Every spoke gets the same weights by symmetry.
for s in range(1, spokes):
assert max(abs(w[s * samples + q] - w[q]) for q in range(samples)) < 1e-9
def test_rejects_kernel_zero_at_origin():
with pytest.raises(ValueError):
pipe_menon([(0.0,)], lambda r: 0.0, 1.0)
History
Jackson, Meyer, Nishimura and Macovski (1991) studied the choice of the gridding kernel and recommended the Kaiser-Bessel function. Hoge, Kwan and Pike (1997) compared density compensation functions for spirals. Pipe and Menon (1999) explained why the weights should make the weighted samples, convolved with the kernel, flat, and gave the fixed point iteration. In the same year Rasche and colleagues treated resampling between arbitrary grids by convolution. Later work replaced density weights in many uses by iterative least squares with the nonuniform FFT.
References
- James G. Pipe and Padmanabhan Menon, Sampling density compensation in MRI, rationale and an iterative numerical solution, Magnetic Resonance in Medicine 41(1), 1999, 179 to 186, the rationale for density weights in gridding and the iteration W <- W / (W convolved with C) (general locator; equation numbers not confirmed)
- John I. Jackson, Craig H. Meyer, Dwight G. Nishimura and Albert Macovski, Selection of a convolution function for Fourier inversion using gridding, IEEE Transactions on Medical Imaging 10(3), 1991, 473 to 478, gridding with a Kaiser-Bessel kernel and the role of the density weights (general locator)
- Volker Rasche, Roland Proksa, Ralph Sinkus, Peter Bornert and Holger Eggers, Resampling of data between arbitrary grids using convolution interpolation, IEEE Transactions on Medical Imaging 18(5), 1999, 385 to 392, resampling between arbitrary grids by convolution interpolation and its density compensation (general locator)
- Richard D. Hoge, Remi K. S. Kwan and G. Bruce Pike, Density compensation functions for spiral MRI, Magnetic Resonance in Medicine 38(1), 1997, 117 to 128, analytic density compensation for spiral trajectories (general locator)
- Matt A. Bernstein, Kevin F. King and Xiaohong Joe Zhou, Handbook of MRI Pulse Sequences, Elsevier Academic Press, 2004, Section 13.2, Gridding Reconstruction
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 4CW95Q Edit this page History Report an error Markdown