Algorithmresearch
LORAKS
Also called low-rank modeling of local k-space neighborhoods.
Reconstruct undersampled MRI by asking that matrices built from local k-space neighborhoods have low rank, which follows from limited support or smooth phase.
- Solves
- MRI reconstruction
- Time
- O(K (n w^2 + w^3)) worst
- Space
- O(n w) extra
- Where
- K = the number of iterations; n = the number of k-space grid points; r = the target rank; w = the number of offsets in one neighborhood
- Model
- Real RAM
- Properties
- not convexdeterministicnot in placeiterativemonotoneoffline
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Justin P. Haldar, 2014
LORAKS (low-rank modeling of local k-space neighborhoods) reconstructs an MR image from undersampled k-space by a low rank fit in k-space itself. It builds a matrix whose rows are small neighborhoods of k-space samples. When the image is zero outside a region, or when its phase is smooth, this matrix has low rank, or nearly so. LORAKS fills the missing samples so that the matrix is close to rank and the measured samples agree with the data. It uses no sparsifying transform, which sets it apart from compressed sensing MRI. It also differs from low-rank plus sparse MRI and the partial separability model: those methods ask for low rank in a space-time matrix of a dynamic series, while LORAKS asks for low rank in a structured matrix of one k-space.
In plain words
Look at a small window of k-space, a few neighboring samples. Slide the window over all of k-space and write each window as one row of a big table. If the image is empty outside some region, the rows are not independent: some fixed mix of the samples in a window gives zero in every window. So the table has fewer independent rows than columns. The same is true, with a different table, when the image phase changes slowly.
Now some samples are missing. LORAKS guesses them, builds the table, and replaces it by the nearest table with only independent rows. Then it reads the samples back out of that table, puts the measured samples back, and starts again. Each pass makes the table closer to low rank.
The problem
The input is a grid of k-space samples with a 0/1 mask of the measured points, a neighborhood of integer offsets, a target rank , a weight or the choice of exact data, and an iteration count . The grid is in centered order: point holds the signed frequency . The data come from the model of the MRI reconstruction problem, with the unitary DFT () and one coil.
The operator maps a grid to the matrix with one row for each center whose whole neighborhood lies in the grid, and one column for each offset : . This is the C matrix of Haldar. In 1D it is a Hankel-like matrix with one window per row; in 2D the neighborhood is the set of offsets in a disk. The adjoint adds each entry back onto its grid point, and is the diagonal of the counts , the number of rows that hold .
The output is a full grid that minimizes, as far as the method can,
or, with exact data, the tail sum alone over the grids with on the mask. The penalty is the squared distance from to the set of matrices of rank at most (equation (5) of the USC-SIPI report). The image is .
The algorithm
The method is majorize-minimize. At the current , the distance to rank is at most for the best rank matrix of the current iterate. The new minimizes this upper bound plus the data term. Because is diagonal, the minimizer is one division per grid point.
LORAKS(d, M, offsets, r, lambda, K) ▷ lambda = none keeps the data exactly- 1
k <- M d ▷ zero filled start - 2
repeat K times - 3
C <- P(k) ▷ one row per neighborhood - 4
L <- best rank r approximation of C (truncated SVD) - 5
z <- P^H(L) ▷ add the entries back onto the grid - 6
for each grid point q do - 7
if lambda = none: k(q) <- d(q) if M(q) = 1, else z(q) / D(q) - 8
else: k(q) <- (M(q) d(q) + lambda z(q)) / (M(q) + lambda D(q)) - 9
return k
Line L4 is the truncated SVD of . The code works with the Gram matrix , because is small and the number of rows is large. A point with and lies in no neighborhood and has no sample; the code sets it to 0.
Example
Take a 1D line of pixels with three nonzero pixels: , and . Its k-space has 32 samples at the frequencies . With the neighborhood of radius 4 ( offsets), is a matrix. Its singular values are
| 3.58 | 1.408 | 0.6427 | below |
The squares of the last six are at the rounding level , so the rank is 3, the number of nonzero pixels, as the rank bound below says.
Now keep 16 of the 32 samples (): the frequencies . Zero filling has a relative error of 0.688. LORAKS with and exact data gives these values (measured with the code below):
| iterations | relative error of | |
|---|---|---|
| 1 | 2.672 | 0.517 |
| 2 | 1.411 | 0.340 |
| 5 | 0.0798 | 0.128 |
| 10 | 0.00395 | 0.0421 |
| 20 | 0.00598 | |
| 50 | ||
| 100 | 0 (rounding) | |
| 150 | 0 (rounding) |
falls at every step, as the proof says. Here the iterates also reach the true k-space, but that is a measurement on this example, not a theorem. With the error stops at 0.21, and with it is 0.0029 after 150 iterations. With only 11 samples (another random mask), the error stays between 0.6 and 0.9 for the radii 3, 4 and 5, close to the zero filled error of 0.80.
Correctness
Two results hold, and both are proved in full below.
- Rank bound. If the image has nonzero pixels, then . More exactly, , where is the matrix of the neighborhood exponentials on the support. Every filter on the neighborhood whose image-domain function vanishes on the support is in the null space. This is the annihilating filter of Prony's method in a new form.
- Monotone objective. With , at every pass. With exact data, the tail sum does not increase. The proof uses the Eckart-Young theorem: the best rank matrix gives a surrogate that touches at and lies above it elsewhere, and line L8 minimizes the surrogate exactly.
The rank penalty is not convex. So the theorems give a non-increasing sequence , not a global minimizer and not recovery of the true k-space. For a real image whose support has positive area, the rank deficiency is only approximate (Haldar and Setsompop 2020), which is why the method penalizes the tail and does not force an exact rank.
Proof: The LORAKS rank bound and the monotone decrease of its objectivefull
The setting is that of the algorithm. The grid is , and a grid point holds the signed frequency . The neighborhood is a list of integer offsets . The centers are the grid points with on the grid for every . The operator maps a grid to the matrix . Its adjoint adds the entry to grid point . So , where is the number of pairs with . The mask marks the sampled points.
1. The rank bound
Theorem 1. Let be an image on an grid of pixels, and let be the set of pixels where , with . Let in centered order:
Then , where is the matrix . Every vector with satisfies .
Proof. Write for an integer vector . Then , and . So
This is the product with , an matrix. The rank of a product is at most the rank of each factor, so . If , then .
The vector is a filter on the neighborhood. Its image-domain function is , so the condition says that vanishes on the support . Then pixel by pixel, and in k-space the filter annihilates every neighborhood. This is the annihilating filter reading of the bound.
Remark. The bound is exact for the discrete model. For a continuous image with a support of positive area, a trigonometric polynomial with frequencies in the neighborhood cannot vanish on the whole support, so the rank deficiency is only approximate. This is why the method penalizes the tail of the singular values instead of imposing an exact rank.
2. The best rank r approximation
Lemma 2 (Eckart-Young). For a complex matrix with singular values and an integer ,
and attains the minimum, where the columns of are the top right singular vectors.
This is the Eckart-Young theorem in the Frobenius norm; see singular-value-decomposition. The code forms from the eigenvectors of the real symmetric matrix , where . The map is a ring homomorphism from complex to real matrices, and . If , then has the two orthogonal eigenvectors and with the eigenvalue . So each eigenvalue of appears twice, and the sum of over the top eigenvectors of is , when . The test file checks the result against the real SVD of .
3. Monotone decrease
The objective is
Theorem 3. Let be the iterate at the start of a pass of line L2, the matrix of line L4, and the result of line L8. Then .
Proof. Define the surrogate . By Lemma 2, for every of rank at most , and , because is the best rank approximation of .
Now minimize over . Expand , using . So is a sum of independent terms, one per grid point:
Each term is a convex quadratic in with the leading coefficient . Where this coefficient is positive, its minimizer is , which is line L8. Where it is zero, and , so the term does not depend on , and line L8 sets , which is a minimizer. So minimizes , and
Theorem 4 (exact data). With = none, line L7 keeps where , and does not increase.
Proof. The same argument applies to the surrogate over the set of grids with on the samples. On a free point with the minimizer of is , which is line L7. A free point with does not enter the surrogate.
Since and does not increase, the values converge. The theorems do not say that the limit is the true k-space, or that it is a global minimizer: the rank penalty is not convex. Recovery from a given sampling pattern is a measured property.
4. Fixed points
If everywhere and , then , , and line L8 gives . Line L7 gives at once. So the true k-space is a fixed point in both modes.
Complexity
Let be the number of grid points, the size of the neighborhood and the number of rows of . One pass costs:
- to build (line L3) and to scatter back (line L5).
- to form the Gram matrix and the product (line L4).
- for the eigendecomposition of the Gram matrix with a dense solver. The code uses the cyclic Jacobi method on a real matrix, with work per sweep and a number of sweeps that is small in practice but not bounded here.
- for the update (lines L6 to L8).
So passes take in the real RAM, and the space is for . No bound on in terms of the accuracy is known for this non-convex method; the number of passes is a measured quantity. Real implementations use larger neighborhoods (in 2D, a disk of radius 3 has 29 offsets), several coils and FFT-based products with and .
Properties
- Calibrationless. LORAKS needs no fully sampled k-space center and no coil maps. The structure comes from the image support and phase.
- No sparsifying transform. The prior is a rank condition on k-space, not a sparse representation of the image.
- Monotone but non-convex. The objective does not increase, but the limit depends on the start and on .
- Local in k-space. The neighborhood is small, so the method can fill gaps that are a few samples wide, but not a large missing block far from any measured sample.
Variants and improvements
- G and S matrices. Haldar also builds matrices from each neighborhood together with its mirror neighborhood at the negative frequencies. If the image is with a real and a smooth phase , then , so the conjugate mirrored k-space is the k-space convolved with a short kernel. This gives linear relations between a neighborhood and its mirror, and so low rank. The S matrix uses the real and imaginary parts of these pairs. Smooth phase is the same prior that homodyne reconstruction and partial Fourier reconstruction use, and LORAKS can use it with partial Fourier sampling.
- P-LORAKS. With several coils, the neighborhoods of all coils go into one row. Coil sensitivities add more linear relations, as in SPIRiT and ESPIRiT, but no calibration region is needed (Haldar and Zhuo 2016).
- Other structured low rank methods. Methods such as SAKE and ALOHA use the same idea with block Hankel matrices and other priors; Jacob, Mani and Ye (2020) survey them. The common root is the annihilating filter and linear prediction (see linear prediction).
- Convex relaxations. One can replace the tail penalty by the nuclear norm of and solve a convex problem with singular value thresholding, as in matrix completion. The tail penalty fits the rank better but gives up convexity.
When to use it
Use LORAKS when the data lack a fully sampled calibration region, when the sampling is unusual (partial Fourier, random, or with gaps), or when the image support is small compared to the field of view. Use it with a sparsity prior when the image is also compressible. For standard Cartesian scans with a good calibration region, GRAPPA or SENSE is faster and simpler.
Pitfalls
- The rank is a choice. In the example, fails and converges slowly. For real data the singular values decay without a clear gap, and and are tuned.
- The neighborhood size. A larger neighborhood has more annihilating filters but fewer rows and a higher cost. The rank bound is useful only when is well below .
- Too few samples. Recovery is measured, not proved. In the example, 11 of 32 samples fail for every neighborhood tried.
- Edges of the grid. Points near the edge lie in few rows, so is small there and the update is weak. A point in no row and with no sample stays at 0.
- Complex SVD. A real SVD of the real and imaginary parts as separate columns is not the complex SVD. The code embeds the complex Gram matrix as a real symmetric matrix of twice the size, where each eigenvalue appears twice.
- Slow convergence with a penalty. With the data term pulls each sample only part of the way. On the example above with , the relative error is still 0.42 after 150 passes, while exact data give .
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the imaging and inverse problems pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small images and signals for the imaging and inverse problems pages.
Conventions:
- A signal is a list of numbers. An image is a list of rows, img[i][j], with
row i from the top and column j from the left.
- An n x n image covers the square [-1, 1]^2. The center of pixel (i, j) is
x_j = -1 + (2 j + 1) / n and y_i = 1 - (2 i + 1) / n, so y goes up.
- DFT: X_k = sum_j x_j exp(-2 pi i j k / n), unnormalized; the inverse has
the factor 1 / n. Index k stands for frequency k for k < n / 2 and k - n
otherwise. fftshift moves the zero frequency to position n // 2.
- Periodic convolution kernels are stored with their center at index 0
(wrapped around), so a delta kernel gives the identity and no shift.
"""
import cmath
import math
# ------------------------------------------------------------------ images
def new_image(n1, n2, value=0.0):
"""An n1 x n2 image (n1 rows, n2 columns) filled with value."""
return [[value] * n2 for _ in range(n1)]
def img_add(a, b):
"""The pixelwise sum a + b."""
return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
def img_scale(a, c):
"""The image c a."""
return [[c * x for x in row] for row in a]
def img_dot(a, b):
"""<a, b> = sum conj(a_ij) b_ij."""
return sum(x.conjugate() * y for ra, rb in zip(a, b) for x, y in zip(ra, rb))
def img_norm(a):
"""The Euclidean (Frobenius) norm of an image."""
return math.sqrt(sum(abs(x) ** 2 for row in a for x in row))
def flatten(img):
"""Row-major vector of an image."""
return [x for row in img for x in row]
def unflatten(v, n1, n2):
"""The n1 x n2 image of a row-major vector."""
return [list(v[i * n2:(i + 1) * n2]) for i in range(n1)]
# ------------------------------------------------------------------ DFT
def _is_pow2(n):
return n > 0 and n & (n - 1) == 0
def _fft_pow2(x):
"""Iterative radix-2 FFT, unnormalized forward transform."""
n = len(x)
a = [complex(v) for v in x]
j = 0
for i in range(1, n):
bit = n >> 1
while j & bit:
j ^= bit
bit >>= 1
j |= bit
if i < j:
a[i], a[j] = a[j], a[i]
size = 2
while size <= n:
half = size // 2
tw = [cmath.exp(-2j * math.pi * k / size) for k in range(half)]
for start in range(0, n, size):
for k in range(half):
u = a[start + k]
v = a[start + k + half] * tw[k]
a[start + k] = u + v
a[start + k + half] = u - v
size *= 2
return a
def dft(x):
"""X_k = sum_j x_j exp(-2 pi i j k / n). Radix-2 FFT when n is a power of 2."""
n = len(x)
if n == 0:
return []
if _is_pow2(n):
return _fft_pow2(x)
w = [cmath.exp(-2j * math.pi * t / n) for t in range(n)]
return [sum(x[j] * w[(j * k) % n] for j in range(n)) for k in range(n)]
def idft(xf):
"""x_j = (1/n) sum_k X_k exp(2 pi i j k / n)."""
n = len(xf)
if n == 0:
return []
y = dft([complex(v).conjugate() for v in xf])
return [v.conjugate() / n for v in y]
def _rows_then_cols(img, f):
rows = [f(row) for row in img]
cols = [f(list(col)) for col in zip(*rows)]
return [list(r) for r in zip(*cols)]
def dft2(img):
"""2D DFT: X_kl = sum_jq x_jq exp(-2 pi i (j k / n1 + q l / n2))."""
return _rows_then_cols(img, dft)
def idft2(img):
"""Inverse 2D DFT, with the factor 1 / (n1 n2)."""
return _rows_then_cols(img, idft)
def _shift1(x, s):
return list(x[s:]) + list(x[:s])
def fftshift(x):
"""Move the zero frequency to position n // 2 (1D, or both axes of an image)."""
if x and isinstance(x[0], (list, tuple)):
rows = [fftshift(r) for r in x]
return _shift1(rows, (len(rows) + 1) // 2)
return _shift1(x, (len(x) + 1) // 2)
def ifftshift(x):
"""The inverse of fftshift (1D, or both axes of an image)."""
if x and isinstance(x[0], (list, tuple)):
rows = [ifftshift(r) for r in x]
return _shift1(rows, len(rows) // 2)
return _shift1(x, len(x) // 2)
def circ_conv(x, h):
"""Periodic convolution y_i = sum_j h_j x_{(i - j) mod n}, kernel centered at index 0."""
n = len(x)
nz = [(j, hj) for j, hj in enumerate(h) if hj != 0]
return [sum(hj * x[(i - j) % n] for j, hj in nz) for i in range(n)]
def circ_conv2(img, h):
"""Periodic 2D convolution with the kernel h centered at index (0, 0)."""
n1, n2 = len(img), len(img[0])
nz = [(p, q, h[p][q]) for p in range(len(h)) for q in range(len(h[0])) if h[p][q] != 0]
out = new_image(n1, n2)
for i in range(n1):
for j in range(n2):
out[i][j] = sum(v * img[(i - p) % n1][(j - q) % n2] for p, q, v in nz)
return out
# ------------------------------------------------------------------ phantoms
def pixel_centers(n):
"""(xs, ys): xs[j] = -1 + (2 j + 1) / n and ys[i] = 1 - (2 i + 1) / n."""
xs = [-1.0 + (2 * j + 1) / n for j in range(n)]
ys = [1.0 - (2 * i + 1) / n for i in range(n)]
return xs, ys
# Rows: rho, A, B, x0, y0, phi (degrees). A is the semi-axis along the
# direction phi (counterclockwise from the x axis), B the other semi-axis.
# Geometry and densities of Shepp and Logan (1974), as reproduced in Kak and
# Slaney, Principles of Computerized Tomographic Imaging, Table 3.1. The value
# at the center (0, 0) is 2 - 0.98 = 1.02.
SHEPP_LOGAN = [
(2.0, 0.92, 0.69, 0.0, 0.0, 90.0),
(-0.98, 0.874, 0.6624, 0.0, -0.0184, 90.0),
(-0.02, 0.31, 0.11, 0.22, 0.0, 72.0),
(-0.02, 0.41, 0.16, -0.22, 0.0, 108.0),
(0.01, 0.25, 0.21, 0.0, 0.35, 90.0),
(0.01, 0.046, 0.046, 0.0, 0.1, 0.0),
(0.01, 0.046, 0.046, 0.0, -0.1, 0.0),
(0.01, 0.046, 0.023, -0.08, -0.605, 0.0),
(0.01, 0.023, 0.023, 0.0, -0.605, 0.0),
(0.01, 0.046, 0.023, 0.06, -0.605, 90.0),
]
# The same ellipses with the gray levels of Toft (1996), which give more
# contrast. The value at the center is 1 - 0.8 = 0.2.
MODIFIED_SHEPP_LOGAN = [
(rho, a, b, x0, y0, phi)
for rho, (_, a, b, x0, y0, phi) in zip(
(1.0, -0.8, -0.2, -0.2, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1), SHEPP_LOGAN
)
]
def ellipse_value(x, y, table):
"""The phantom value at the point (x, y): the sum of rho over the ellipses that hold it."""
total = 0.0
for rho, a, b, x0, y0, phi in table:
c, s = math.cos(math.radians(phi)), math.sin(math.radians(phi))
dx, dy = x - x0, y - y0
u = dx * c + dy * s
v = -dx * s + dy * c
if (u / a) ** 2 + (v / b) ** 2 <= 1.0:
total += rho
return total
def ellipse_phantom(n, table):
"""The n x n image of an ellipse table, sampled at the pixel centers."""
xs, ys = pixel_centers(n)
return [[ellipse_value(x, y, table) for x in xs] for y in ys]
def disk_phantom(n, radius):
"""1 at pixel centers with x^2 + y^2 <= radius^2, 0 elsewhere."""
xs, ys = pixel_centers(n)
r2 = radius * radius
return [[1.0 if x * x + y * y <= r2 else 0.0 for x in xs] for y in ys]
def spikes_1d(n, positions, amplitudes):
"""A signal of length n with the given amplitudes at the given positions."""
out = [0.0] * n
for p, a in zip(positions, amplitudes):
out[p] += a
return out
# ------------------------------------------------------------------ projector
def parallel_beam_matrix(n, angles, nbins):
"""Pixel-driven discrete Radon transform of an n x n image on [-1, 1]^2.
Each pixel center (x, y) projects to s = x cos(theta) + y sin(theta). Its
value times the pixel area over the bin width is split linearly between
the two nearest bin centers. The bins cover [-sqrt(2), sqrt(2)]. Row
a * nbins + b holds angle a and bin b; column i * n + j holds pixel (i, j).
Returns the sparse rows, each a list of (column, weight) pairs.
Pixel-driven projection has a ripple: with a bin width close to the pixel
size, a disk projection is off by up to about 10 percent in some bins. A
bin of about twice the pixel size (nbins = 23 for n = 32) keeps it near
1 percent.
"""
xs, ys = pixel_centers(n)
smax = math.sqrt(2.0)
width = 2.0 * smax / nbins
scale = (2.0 / n) ** 2 / width
rows = []
for theta in angles:
c, s = math.cos(theta), math.sin(theta)
acc = [dict() for _ in range(nbins)]
for i, y in enumerate(ys):
for j, x in enumerate(xs):
t = (x * c + y * s + smax) / width - 0.5
b0 = math.floor(t)
frac = t - b0
col = i * n + j
for b, w in ((b0, 1.0 - frac), (b0 + 1, frac)):
if 0 <= b < nbins and w > 0.0:
acc[b][col] = acc[b].get(col, 0.0) + w * scale
rows.extend(sorted(d.items()) for d in acc)
return rows
def sp_matvec(rows, x):
"""y = A x for sparse rows of (column, weight) pairs."""
return [sum(w * x[c] for c, w in row) for row in rows]
def sp_rmatvec(rows, y, ncols):
"""x = A^H y for sparse rows of (column, weight) pairs and ncols columns."""
out = [0.0] * ncols
for row, yi in zip(rows, y):
if yi == 0:
continue
for c, w in row:
out[c] += w.conjugate() * yi
return out
# ------------------------------------------------------------------ noise
def gauss_noise(rng, shape, sigma):
"""Independent N(0, sigma^2) values: a list for an int shape, an image for (n1, n2)."""
if isinstance(shape, int):
return [rng.gauss(0.0, sigma) for _ in range(shape)]
n1, n2 = shape
return [[rng.gauss(0.0, sigma) for _ in range(n2)] for _ in range(n1)]
def _poisson_small(rng, lam):
"""Knuth's product method, exact for a mean lam <= 30."""
limit = math.exp(-lam)
k, p = 0, rng.random()
while p > limit:
k += 1
p *= rng.random()
return k
def poisson_sample(rng, lam):
"""An exact Poisson(lam) sample: a sum of Knuth samples with means at most 30."""
if lam < 0:
raise ValueError("negative mean")
total = 0
while lam > 30.0:
total += _poisson_small(rng, 30.0)
lam -= 30.0
if lam > 0.0:
total += _poisson_small(rng, lam)
return total
imgla.py 259 lines
# SPDX-License-Identifier: MIT
# Shared helper of the imaging and inverse problems pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Dense linear algebra on lists of rows (float, complex or Fraction entries).
A matrix is a list of rows. A vector is a list of numbers. The inner product
is <u, v> = sum_i conj(u_i) v_i, linear in the second argument, so that the
adjoint A^H satisfies <A x, y> = <x, A^H y>.
"""
import math
def _flat(x):
"""Flatten a list of rows (an image) into one list; a vector is returned as is."""
if x and isinstance(x[0], (list, tuple)):
return [v for row in x for v in row]
return x
def zeros(m, n):
"""The m x n zero matrix."""
return [[0.0] * n for _ in range(m)]
def eye(n):
"""The n x n identity matrix."""
out = zeros(n, n)
for i in range(n):
out[i][i] = 1.0
return out
def transpose(a):
"""A^T."""
return [list(col) for col in zip(*a)]
def conj_transpose(a):
"""A^H, the conjugate transpose."""
return [[v.conjugate() for v in col] for col in zip(*a)]
def matmul(a, b):
"""The product A B."""
bt = list(zip(*b))
return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]
def matvec(a, x):
"""The product A x."""
return [sum(v * w for v, w in zip(row, x)) for row in a]
def rmatvec(a, y):
"""The product A^H y."""
n = len(a[0]) if a else 0
out = [0.0] * n
for row, yi in zip(a, y):
if yi == 0:
continue
for j, v in enumerate(row):
out[j] += v.conjugate() * yi
return out
def dot(u, v):
"""<u, v> = sum_i conj(u_i) v_i. Images (lists of rows) are flattened."""
return sum(a.conjugate() * b for a, b in zip(_flat(u), _flat(v)))
def norm2(x):
"""The Euclidean norm. Images (lists of rows) are flattened."""
return math.sqrt(sum(abs(v) ** 2 for v in _flat(x)))
def solve(a, b):
"""Solve A x = b by Gaussian elimination with partial pivoting.
b is a vector or a matrix (a list of rows). A must be square and
nonsingular; a zero pivot raises ValueError. Fractions stay exact.
"""
n = len(a)
vec = not (b and isinstance(b[0], (list, tuple)))
rhs = [[bi] for bi in b] if vec else [list(r) for r in b]
m = [list(row) + rhs[i] for i, row in enumerate(a)]
w = len(m[0])
for c in range(n):
p = max(range(c, n), key=lambda r: abs(m[r][c]))
if m[p][c] == 0:
raise ValueError("singular matrix")
m[c], m[p] = m[p], m[c]
piv = m[c][c]
for r in range(c + 1, n):
f = m[r][c] / piv
if f != 0:
mr, mc = m[r], m[c]
for j in range(c, w):
mr[j] -= f * mc[j]
x = [[0.0] * (w - n) for _ in range(n)]
for r in range(n - 1, -1, -1):
for j in range(w - n):
s = m[r][n + j] - sum(m[r][k] * x[k][j] for k in range(r + 1, n))
x[r][j] = s / m[r][r]
return [row[0] for row in x] if vec else x
def cholesky(a):
"""Lower triangular L with A = L L^H for a Hermitian positive definite A."""
n = len(a)
low = zeros(n, n)
for j in range(n):
d = a[j][j] - sum(abs(low[j][k]) ** 2 for k in range(j))
d = d.real if isinstance(d, complex) else d
if not d > 0:
raise ValueError("matrix is not positive definite")
ljj = math.sqrt(d)
low[j][j] = ljj
for i in range(j + 1, n):
s = a[i][j] - sum(low[i][k] * low[j][k].conjugate() for k in range(j))
low[i][j] = s / ljj
return low
def cho_solve(low, b):
"""Solve (L L^H) x = b, with L from cholesky."""
n = len(low)
z = [0.0] * n
for i in range(n):
z[i] = (b[i] - sum(low[i][k] * z[k] for k in range(i))) / low[i][i]
x = [0.0] * n
for i in range(n - 1, -1, -1):
s = z[i] - sum(low[k][i].conjugate() * x[k] for k in range(i + 1, n))
x[i] = s / low[i][i].conjugate()
return x
def _rot_params(app, aqq, apq):
"""c, s of the Jacobi rotation that zeroes the (p, q) entry of [[app, apq], [apq, aqq]]."""
theta = (aqq - app) / (2.0 * apq)
t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
c = 1.0 / math.sqrt(1.0 + t * t)
return c, c * t
def sym_eig(a, tol=1e-15, max_sweeps=100):
"""Eigenvalues (ascending) and eigenvectors (as columns) of a real symmetric matrix.
Cyclic Jacobi method. Returns (w, Q) with A = Q diag(w) Q^T.
"""
n = len(a)
m = [[float(v) for v in row] for row in a]
q = eye(n)
for _ in range(max_sweeps):
off = sum(m[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
scale = sum(m[i][i] ** 2 for i in range(n)) + off
if off <= (tol * tol) * scale or off == 0.0:
break
for p in range(n - 1):
for r in range(p + 1, n):
apq = m[p][r]
if apq == 0.0:
continue
c, s = _rot_params(m[p][p], m[r][r], apq)
for k in range(n):
mkp, mkr = m[k][p], m[k][r]
m[k][p] = c * mkp - s * mkr
m[k][r] = s * mkp + c * mkr
mp, mr = m[p], m[r]
for k in range(n):
mpk, mrk = mp[k], mr[k]
mp[k] = c * mpk - s * mrk
mr[k] = s * mpk + c * mrk
m[p][r] = m[r][p] = 0.0
for k in range(n):
qkp, qkr = q[k][p], q[k][r]
q[k][p] = c * qkp - s * qkr
q[k][r] = s * qkp + c * qkr
order = sorted(range(n), key=lambda i: m[i][i])
w = [m[i][i] for i in order]
qs = [[q[k][i] for i in order] for k in range(n)]
return w, qs
def _complete(cols, m):
"""Replace zero columns of an m-row column list by unit vectors orthogonal to the others."""
for idx, col in enumerate(cols):
if any(v != 0.0 for v in col):
continue
for e in range(m):
cand = [0.0] * m
cand[e] = 1.0
for _ in range(2):
for jdx, other in enumerate(cols):
if jdx == idx or not any(v != 0.0 for v in other):
continue
h = sum(a * b for a, b in zip(other, cand))
cand = [a - h * b for a, b in zip(cand, other)]
nrm = math.sqrt(sum(v * v for v in cand))
if nrm > 0.5:
cols[idx] = [v / nrm for v in cand]
break
return cols
def svd(a, tol=1e-15, max_sweeps=100):
"""Thin SVD of a real m x n matrix by one-sided Jacobi (Hestenes).
Returns (U, S, V) with p = min(m, n): U is m x p, S a list of p values in
descending order, V is n x p, U^T U = I, V^T V = I and A = U diag(S) V^T.
"""
m, n = len(a), len(a[0])
if m < n:
v, s, u = svd(transpose(a), tol, max_sweeps)
return u, s, v
cols = [[float(a[i][j]) for i in range(m)] for j in range(n)]
vcols = [[1.0 if i == j else 0.0 for i in range(n)] for j in range(n)]
for _ in range(max_sweeps):
rotated = False
for p in range(n - 1):
for r in range(p + 1, n):
cp, cr = cols[p], cols[r]
alpha = sum(x * x for x in cp)
beta = sum(x * x for x in cr)
gamma = sum(x * y for x, y in zip(cp, cr))
if gamma == 0.0 or abs(gamma) <= tol * math.sqrt(alpha * beta):
continue
rotated = True
c, s = _rot_params(alpha, beta, gamma)
cols[p] = [c * x - s * y for x, y in zip(cp, cr)]
cols[r] = [s * x + c * y for x, y in zip(cp, cr)]
vp, vr = vcols[p], vcols[r]
vcols[p] = [c * x - s * y for x, y in zip(vp, vr)]
vcols[r] = [s * x + c * y for x, y in zip(vp, vr)]
if not rotated:
break
sig = [math.sqrt(sum(x * x for x in col)) for col in cols]
# A column below 1e-150 times the largest one is zero to working precision;
# its squares underflow, so its direction carries no information.
floor = max(sig) * 1e-150 if sig else 0.0
sig = [t if t > floor and t > 1e-150 else 0.0 for t in sig]
order = sorted(range(n), key=lambda j: -sig[j])
s_out = [sig[j] for j in order]
ucols = [[x / sig[j] for x in cols[j]] if sig[j] > 0.0 else [0.0] * m for j in order]
ucols = _complete(ucols, m)
u = [[ucols[j][i] for j in range(n)] for i in range(m)]
v = [[vcols[j][i] for j in order] for i in range(n)]
return u, s_out, v
def adjoint_gap(apply_a, apply_ah, x, y):
"""|<A x, y> - <x, A^H y>| / (||A x|| ||y||) for given functions A and A^H.
x and y may be vectors or images (lists of rows). If the denominator is
zero, the absolute gap is returned.
"""
ax = apply_a(x)
gap = abs(dot(ax, y) - dot(x, apply_ah(y)))
den = norm2(ax) * norm2(y)
return gap / den if den > 0.0 else gap
loraks.py 197 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/loraks/. The authors are listed in prov/HJ4N14.jsonl.
"""LORAKS: low-rank modeling of local k-space neighborhoods (Haldar 2014).
k-space convention: a grid kspace[a][b] of n1 rows and n2 columns of complex
samples, in centered order (row a holds the signed frequency a - n1 // 2, and
the same for the columns). A 1D line is a grid with n1 = 1. A neighborhood
is a list of integer offsets (da, db). The C matrix P(k) has one row for each
center (a, b) whose whole neighborhood lies inside the grid, and one column
for each offset: P(k)[row, j] = k[a + da_j][b + db_j]. P^H scatters a matrix
back onto the grid and adds the entries that fall on the same point, so
P^H P is the diagonal of the counts D (how many rows hold each point).
The method fits k-space so that P(k) is close to rank r and the samples
agree with the data. It minimizes, by majorize-minimize,
J(k) = ||M k - d||^2 + lambda * sum_{j > r} sigma_j(P(k))^2,
with the 0/1 sampling mask M. With lambda = None the data are kept exactly
and J(k) is the tail sum alone.
Complex SVD: imgla.svd is for real matrices, so the best rank r
approximation C P_r uses the real symmetric embedding of the Gram matrix
C^H C and imgla.sym_eig (see low_rank_projector). This small piece of code
lives here and not in a helper.
Cost per iteration, for N rows and w offsets: O(N w^2) for the Gram matrix,
O(w^3) per Jacobi sweep of the 2w x 2w embedding, O(N w^2) for C P_r and
O(N w) for the scatter and the update.
"""
import math
from imgla import sym_eig
def line_offsets(radius):
"""The 1D neighborhood (0, -radius), ..., (0, radius)."""
return [(0, d) for d in range(-radius, radius + 1)]
def disk_offsets(radius):
"""The 2D LORAKS neighborhood: all integer offsets with da^2 + db^2 <= radius^2."""
top = int(math.floor(radius))
return [
(da, db)
for da in range(-top, top + 1)
for db in range(-top, top + 1)
if da * da + db * db <= radius * radius
]
def centers(n1, n2, offsets):
"""The centers (a, b) whose whole neighborhood lies inside the n1 x n2 grid."""
amin = min(da for da, _ in offsets)
amax = max(da for da, _ in offsets)
bmin = min(db for _, db in offsets)
bmax = max(db for _, db in offsets)
return [(a, b) for a in range(-amin, n1 - amax) for b in range(-bmin, n2 - bmax)]
def c_matrix(kspace, offsets):
"""P(k): one row per center, one column per offset."""
n1, n2 = len(kspace), len(kspace[0])
return [[kspace[a + da][b + db] for da, db in offsets] for a, b in centers(n1, n2, offsets)]
def c_adjoint(mat, n1, n2, offsets):
"""P^H(L): add each entry of L back onto its grid point."""
out = [[0j] * n2 for _ in range(n1)]
for (a, b), row in zip(centers(n1, n2, offsets), mat):
for (da, db), v in zip(offsets, row):
out[a + da][b + db] += v
return out
def coverage(n1, n2, offsets):
"""D = P^H P as a grid: the number of rows of P(k) that hold each point."""
out = [[0] * n2 for _ in range(n1)]
for a, b in centers(n1, n2, offsets):
for da, db in offsets:
out[a + da][b + db] += 1
return out
def gram(c):
"""G = C^H C."""
w = len(c[0])
g = [[0j] * w for _ in range(w)]
for row in c:
for i in range(w):
ci = row[i].conjugate()
if ci == 0:
continue
gi = g[i]
for j in range(w):
gi[j] += ci * row[j]
return g
def low_rank_projector(c, r):
"""The orthogonal projector P_r onto the top r right singular vectors of C.
Returns (P_r, s2) with s2 the squared singular values of C in descending
order. The Hermitian Gram matrix G = C^H C is embedded as the real
symmetric matrix [[Re G, -Im G], [Im G, Re G]]; each eigenvalue of G
appears twice there, and the sum of q q^T over the top 2 r eigenvectors
is the embedding of P_r.
"""
g = gram(c)
w = len(g)
emb = [[0.0] * (2 * w) for _ in range(2 * w)]
for i in range(w):
for j in range(w):
re, im = g[i][j].real, g[i][j].imag
emb[i][j] = re
emb[i + w][j + w] = re
emb[i][j + w] = -im
emb[i + w][j] = im
vals, vecs = sym_eig(emb)
top = list(range(2 * w - 1, 2 * w - 1 - 2 * r, -1))
proj = [[0j] * w for _ in range(w)]
for i in range(w):
for j in range(w):
re = sum(vecs[i][t] * vecs[j][t] for t in top)
im = sum(vecs[i + w][t] * vecs[j][t] for t in top)
proj[i][j] = complex(re, im)
desc = sorted((max(v, 0.0) for v in vals), reverse=True)
s2 = [desc[2 * t] for t in range(w)]
return proj, s2
def rank_r_approx(c, r):
"""(L, tail): L = C P_r is the best rank r approximation of C in the
Frobenius norm, and tail = ||C - L||_F^2 = sum_{j > r} sigma_j^2."""
proj, s2 = low_rank_projector(c, r)
w = len(proj)
low = [[sum(row[k] * proj[k][j] for k in range(w)) for j in range(w)] for row in c]
total = sum(abs(v) ** 2 for row in c for v in row)
tail = max(total - sum(s2[:r]), 0.0)
return low, tail
def objective(kspace, data, mask, offsets, r, lam=None):
"""J(k) = ||M k - d||^2 + lambda * tail, or the tail alone for lambda = None."""
_, tail = rank_r_approx(c_matrix(kspace, offsets), r)
if lam is None:
return tail
fit = sum(
abs(kv - dv) ** 2
for krow, drow, mrow in zip(kspace, data, mask)
for kv, dv, mv in zip(krow, drow, mrow)
if mv
)
return fit + lam * tail
def loraks(data, mask, offsets, r, lam=None, iters=100, history=None):
"""Recover a k-space grid from the samples data[a][b] where mask[a][b] is 1.
lam = None keeps the samples exactly. Otherwise lam > 0 weighs the rank
penalty against the data term. If history is a list, J of each iterate
k_0, ..., k_{iters - 1} is appended to it.
"""
n1, n2 = len(data), len(data[0])
cnt = coverage(n1, n2, offsets)
k = [[complex(data[a][b]) if mask[a][b] else 0j for b in range(n2)] for a in range(n1)] # @line L1
for _ in range(iters): # @line L2
c = c_matrix(k, offsets) # @line L3
low, tail = rank_r_approx(c, r) # @line L4
if history is not None:
if lam is None:
history.append(tail)
else:
fit = sum(
abs(k[a][b] - data[a][b]) ** 2
for a in range(n1)
for b in range(n2)
if mask[a][b]
)
history.append(fit + lam * tail)
z = c_adjoint(low, n1, n2, offsets) # @line L5
for a in range(n1): # @line L6
for b in range(n2):
if lam is None: # @line L7
if mask[a][b]:
k[a][b] = complex(data[a][b])
elif cnt[a][b] > 0:
k[a][b] = z[a][b] / cnt[a][b]
else:
k[a][b] = 0j
else: # @line L8
num = (data[a][b] if mask[a][b] else 0.0) + lam * z[a][b]
den = (1.0 if mask[a][b] else 0.0) + lam * cnt[a][b]
k[a][b] = num / den if den > 0 else 0j
return k # @line L9
test_loraks.py 159 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/loraks/. The authors are listed in prov/HJ4N14.jsonl.
import cmath
import math
import random
from imgla import adjoint_gap, svd
from loraks import (
c_adjoint,
c_matrix,
coverage,
disk_offsets,
line_offsets,
loraks,
low_rank_projector,
objective,
rank_r_approx,
)
def kspace_line(x):
"""Centered unitary DFT of a 1D signal: frequencies -n/2, ..., n/2 - 1."""
n = len(x)
return [
sum(x[j] * cmath.exp(-2j * math.pi * f * j / n) for j in range(n)) / math.sqrt(n)
for f in range(-n // 2, n // 2)
]
def kspace_grid(img):
"""Centered unitary 2D DFT of a small square image."""
n = len(img)
return [
[
sum(
img[p][q] * cmath.exp(-2j * math.pi * (a * p + b * q) / n)
for p in range(n)
for q in range(n)
if img[p][q] != 0
)
/ n
for b in range(-n // 2, n // 2)
]
for a in range(-n // 2, n // 2)
]
def three_spikes(n=32):
x = [0j] * n
x[5] = 1.0
x[6] = 0.7 - 0.3j
x[20] = -0.5 + 0.2j
return x
def random_mask(n, seed, p=0.4):
rng = random.Random(seed)
return [[1 if abs(f) <= 2 or rng.random() < p else 0 for f in range(-n // 2, n // 2)]]
def rel_err(u, v):
num = sum(abs(a - b) ** 2 for ra, rb in zip(u, v) for a, b in zip(ra, rb))
den = sum(abs(b) ** 2 for rb in v for b in rb)
return math.sqrt(num / den)
def embed(c):
"""The real matrix [[Re C, -Im C], [Im C, Re C]]."""
top = [[v.real for v in row] + [-v.imag for v in row] for row in c]
bot = [[v.imag for v in row] + [v.real for v in row] for row in c]
return top + bot
def test_rank_equals_support_size_1d():
k = [kspace_line(three_spikes())]
c = c_matrix(k, line_offsets(4))
assert len(c) == 24 and len(c[0]) == 9
_, s2 = low_rank_projector(c, 3)
assert s2[2] > 1e-2 * s2[0]
assert all(v <= 1e-12 * s2[0] for v in s2[3:])
def test_rank_at_most_support_size_2d():
img = [[0j] * 8 for _ in range(8)]
img[1][2] = 1.0
img[4][4] = 0.5j
img[6][1] = -0.8
c = c_matrix(kspace_grid(img), disk_offsets(2))
assert len(c) == 16 and len(c[0]) == 13
_, s2 = low_rank_projector(c, 3)
assert s2[2] > 1e-2 * s2[0]
assert all(v <= 1e-12 * s2[0] for v in s2[3:])
def test_adjoint_and_coverage():
rng = random.Random(3)
off = disk_offsets(1.5)
n1, n2 = 6, 7
x = [[complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(n2)] for _ in range(n1)]
rows = len(c_matrix(x, off))
y = [[complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in off] for _ in range(rows)]
gap = adjoint_gap(lambda v: c_matrix(v, off), lambda v: c_adjoint(v, n1, n2, off), x, y)
assert gap < 1e-12
ones = [[1.0] * n2 for _ in range(n1)]
back = c_adjoint(c_matrix(ones, off), n1, n2, off)
cnt = coverage(n1, n2, off)
assert all(back[a][b] == cnt[a][b] for a in range(n1) for b in range(n2))
def test_rank_r_approx_matches_real_svd():
rng = random.Random(5)
c = [[complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(5)] for _ in range(8)]
for r in (1, 2, 3):
low, tail = rank_r_approx(c, r)
u, s, v = svd(embed(c))
# Each singular value of C appears twice in the embedding.
trunc = [
[sum(u[i][t] * s[t] * v[j][t] for t in range(2 * r)) for j in range(len(v))]
for i in range(len(u))
]
e = embed(low)
assert max(abs(e[i][j] - trunc[i][j]) for i in range(len(e)) for j in range(len(e[0]))) < 1e-10
assert abs(tail - sum(t * t for t in s[2 * r:]) / 2) < 1e-10
resid = sum(abs(a - b) ** 2 for ra, rb in zip(c, low) for a, b in zip(ra, rb))
assert abs(resid - tail) < 1e-10
def test_exact_kspace_is_a_fixed_point():
k = [kspace_line(three_spikes())]
mask = [[1] * 32]
out = loraks(k, mask, line_offsets(3), 3, None, 2)
assert rel_err(out, k) < 1e-12
out = loraks(k, mask, line_offsets(3), 3, 0.5, 2)
assert rel_err(out, k) < 1e-6
def test_hard_constraint_monotone_and_recovers():
k = [kspace_line(three_spikes())]
mask = random_mask(32, 1)
assert sum(mask[0]) == 16
hist = []
out = loraks(k, mask, line_offsets(4), 3, None, 100, hist)
for a, b in zip(hist, hist[1:]):
assert b <= a + 1e-12 * hist[0]
assert all(out[0][j] == k[0][j] for j in range(32) if mask[0][j])
assert rel_err(out, k) < 1e-6
def test_penalized_objective_does_not_increase():
k = [kspace_line(three_spikes())]
mask = random_mask(32, 2)
for lam in (0.3, 3.0):
hist = []
out = loraks(k, mask, line_offsets(3), 3, lam, 30, hist)
for a, b in zip(hist, hist[1:]):
assert b <= a + 1e-12 * hist[0]
final = objective(out, k, mask, line_offsets(3), 3, lam)
assert final <= hist[-1] + 1e-12 * hist[0]
History
Justin Haldar introduced LORAKS in 2014 in IEEE Transactions on Medical Imaging, with a technical report and code for reproducible research. The idea joins two older lines. One is the annihilating filter and linear prediction of signals with few components, which goes back to Prony. The other is the use of support and smooth phase constraints in MRI, as in partial Fourier methods. In 2016 Haldar and Zhuo extended the method to multichannel data as P-LORAKS. Haldar and Setsompop (2020) and Jacob, Mani and Ye (2020) later placed LORAKS among the structured low rank methods for MRI.
References
- Justin P. Haldar, Low-rank modeling of local k-space neighborhoods (LORAKS) for constrained MRI, IEEE Transactions on Medical Imaging 33(3), 2014, 668 to 681, the C, G and S matrices, the rank arguments from limited support and smooth phase, and the penalized reconstruction (general locator)
- Justin P. Haldar, Low-rank modeling of local k-space neighborhoods (LORAKS): implementation and examples for reproducible research, USC-SIPI Technical Report 414, University of Southern California, April 2014, equation (4) for the penalized objective, equation (5) for the tail sum of squared singular values, and the majorize-minimize algorithm
- Justin P. Haldar and Jingwei Zhuo, P-LORAKS, low-rank modeling of local k-space neighborhoods with parallel imaging data, Magnetic Resonance in Medicine 75(4), 2016, 1499 to 1514, the extension to multichannel data and calibrationless parallel imaging (general locator)
- Justin P. Haldar and Kawin Setsompop, Linear predictability in magnetic resonance imaging reconstruction, IEEE Signal Processing Magazine 37(1), 2020, 69 to 82 (arXiv:1903.03141), the linear predictability of k-space from limited support, smooth phase and multichannel data, and the note that exact annihilation needs a support of measure zero (general locator)
- Mathews Jacob, Merry P. Mani and Jong Chul Ye, Structured low-rank algorithms, IEEE Signal Processing Magazine 37(1), 2020, 54 to 68, the survey of structured low rank methods for MRI and their relation to annihilating filters (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 HJ4N14 Edit this page History Report an error Markdown