Algorithmadvanced
POCS partial Fourier reconstruction
Also called Haacke POCS reconstruction.
Rebuilds an MR image from partial k-space by alternate projections onto the images with a low resolution phase and onto the images that agree with the measured samples.
- Time
- O(K n^2 log n) worst
- Space
- O(n^2) extra
- Where
- K = the number of iterations; n = the side of an n x n image (the number of samples along the partial axis), with n a power of two and an FFT
- Model
- Real RAM
- Properties
- deterministicnot exactnot in placeoffline
- Evidence
- Proof sketchCode in 1 languages
- Origin
- E. Mark Haacke, E. D. Lindskog, W. Lin, 1991
POCS partial Fourier reconstruction rebuilds an MR image from a little more than half of k-space, the case of partial Fourier reconstruction. It alternates two steps. The first step gives every pixel the phase of a low resolution image made from the band that is measured on both sides of the center. The second step puts the measured samples back into the k-space of the current image. Each step is the projection onto a convex set, so the name is projections onto convex sets (POCS). Haacke, Lindskog and Lin published the method in 1991. The iterates converge for any phase estimate, and for a real image with a constant phase the error halves at each iteration. Both facts are proved on this page.
In plain words
The picture we want is made of real numbers, but the scanner adds a slowly changing tilt to each value. The scan measures only a little more than half of the frequency description of the picture. A blurry picture made from the frequencies near the middle shows the tilt well.
The method then repeats two steps. First, it makes every pixel point in the direction of that tilt, and it keeps only the part of the value that points that way. Second, it puts back the frequencies that the scanner measured, because the first step changed them. Each step moves the picture to the nearest picture that obeys one rule. Repeating the two steps brings the picture closer to one that obeys both rules.
The problem
The input is one line of k-space data of even length along the phase encoding axis, in DFT order with frequencies , and the number with . The data are for , where is the unitary DFT. The model is with real and smooth. The output is a complex image whose acquired samples equal and whose phase is the reference phase. For an image with partial phase encoding, an inverse DFT along the fully sampled readout axis first gives one such line per image column.
The algorithm
The two sets are , the images with the reference phase , and , the images whose samples on equal .
POCS-PF(y, n, k0, K) ▷ y known for f = -n/2 .. k0- 1
p <- unit phase of F_u^H (T y) ▷ T: triangle window on |f| <= k0 - 2
x <- F_u^H (y on S, 0 elsewhere) ▷ the zero filled image - 3
repeat K times - 4
x_j <- Re(conj(p_j) x_j) p_j for each pixel j ▷ project onto C1 - 5
X <- F_u x - 6
X(f) <- y(f) for each f in S ▷ project onto C2 - 7
x <- F_u^H X - 8
return x
Line L1 makes the reference phase from the band , which is measured on both sides, with the window . Where the low resolution image is zero, . Line L2 starts from the zero filled image. Line L4 keeps, at each pixel, the component of along ; this is the nearest image with the phase . Lines L5 to L7 replace the acquired samples by the data and keep the estimate of the missing samples; because is unitary, this is the nearest image that agrees with the data. The magnitude image or the real part is the result.
Example
Take , , the real profile and the constant phase rad, so . The scan acquires and misses . The reference phase of line L1 is at every pixel. The table gives the relative error after iterations, rounded.
| iteration | 0 | 1 | 2 | 3 | 5 | 10 | 20 |
|---|---|---|---|---|---|---|---|
| relative error | 0.22094 | 0.11047 | 0.05524 | 0.02762 | 0.00690 | 0.00022 |
Iteration 0 is the zero filled image of line L2. The error halves at each step, as the theorem below says. With the signed profile and the same phase, the errors are 0.516, 0.258, 0.129 and so on, and POCS again converges to . Homodyne reconstruction returns the sign of the smoothed image times , so it can give the wrong sign in such a case.
Correctness
Line L4 is the orthogonal projection onto , a real linear subspace of seen as . Lines L5 to L7 are the orthogonal projection onto , an affine subspace. The key invariant is that for every , the distance never grows. The proof shows three theorems.
- If is not empty, the iterates converge to the point of the intersection nearest to the zero filled image, at a geometric rate.
- If the intersection is empty, for example with noise, the iterates still converge, to a point of whose distance to is the distance between the sets.
- For a real image with a constant phase and , the intersection is the true image, and the error halves exactly at each iteration.
These are theorems about the sets. When the phase of the image varies, the set is built from an estimated phase, so the limit is the nearest image of the model, not the true image.
Proof: Convergence of POCS partial Fourier reconstructionfull
The setting is that of the algorithm. Images are vectors in , viewed as the real vector space with the inner product and the norm . is the unitary DFT, so . The acquired set is (frequencies modulo ), the reference phase has , and
The iterates are (line L2) and (lines L4 to L7).
Lemma 1 (the two steps are projections). Line L4 maps to the point of nearest to , and lines L5 to L7 map to the point of nearest to . is a real linear subspace, and is a nonempty affine subspace.
Proof. is closed under real linear combinations. For , because . Each term is smallest for , which is line L4. is the solution set of linear equations and contains . For , , and is free on the frequencies outside and fixed to on . The distance is smallest when equals outside , which is lines L5 to L7.
For a closed subspace write for the orthogonal projection. If is an affine subspace, the nearest point map is .
Lemma 2. Let and be subspaces of a finite dimensional real inner product space, and . Then for , maps into , and there is with for all . Hence for every , with .
Proof. For , and . For and , using that projections are self-adjoint, , so . Projections do not increase norms, so . If for some , then , so by Pythagoras, and then , so . Then , a contradiction. So on the unit sphere of , which is compact, and the maximum of the continuous function there is below 1. Write with ; then and .
Theorem 1 (consistent case). If , then converges to the point of nearest to , and the error falls at least geometrically: with from Lemma 2. Moreover for every and every .
Proof. Take . Then with (a subspace that contains ), and with . By Lemma 1 and the formula for , . Lemma 2 gives with , at the stated rate. The limit lies in , and it is the point of nearest to . The monotone distance follows from with .
Theorem 2 (inconsistent case). If , for example with noisy data, then still converges, to a point such that and is the distance between and .
Proof. Write and with . The sum is a subspace of a finite dimensional space, so with , and . Put ; then , so . For any , and , because . With and ,
By Lemma 2, , so . Then . For any and , because . So is the distance between the sets.
Theorem 3 (constant phase). Let with real, on , and for all . Then , and for every .
Proof. The set is , because a sign on does not change the real multiples. It contains , and contains . Let and with real. Then is Hermitian, , and for . Every frequency has or : if then . So and .
For the rate, let be the missing set; then and . The error lies in , so is zero on and lives on . Line L4 fixes and is real linear, so . The DFT of at is , which lives on . Lines L5 to L7 set the spectrum on back to that of , so they remove that part, and . By Parseval, .
Remarks.
- The reference phase of line L1 is for the triangle-windowed image . For with real , with real (the argument of the homodyne proof), so wherever , and Theorem 3 applies when no is zero.
- The variant that replaces by (keep the magnitude, impose the phase) does not map onto a convex set. The theorems above do not cover it.
- For a phase that varies, the theorems still hold for the sets and , but is built from an estimated phase. The limit is then the nearest point of the model, not the true image.
Complexity
Each iteration costs one DFT and one inverse DFT of length and other operations. With an FFT and a power of two this is per line, and for iterations on an image, in the real RAM. The method stores the hybrid data and the image, numbers. Line L1 costs one more inverse DFT per line.
Properties
- Convergence. The iterates converge for any unit phase (theorem). The rate is geometric, with a constant that depends on the angle between the two sets.
- Exact rate for a constant phase. The error halves at each iteration (theorem). Ten iterations reduce it by a factor of about 1000.
- Signed images. For a constant phase, the limit is the true image even when has both signs (theorem). The sign of is relative to .
- Smooth phase. On a modified Shepp-Logan phantom with the phase rad on and 12 of 16 phase encoding lines, the relative magnitude error was 0.156 after 1 iteration, 0.046 after 5 and 0.0455 after 30, against 0.333 for the zero filled magnitude (measurement with the code of this page). Homodyne gave 0.094 on the same data.
- Data consistency. The output agrees with the measured samples exactly, because line L6 is the last step that changes them.
Variants and improvements
- Magnitude with the reference phase. Many descriptions replace by in line L4. That map is not a projection onto a convex set, and the convergence theorems do not cover it. It gives a nonnegative magnitude by construction.
- Smooth transition. Some implementations blend the estimated and the measured samples near the edge to reduce ringing.
- Two-dimensional partial Fourier. The same iteration works when both axes are partial; the data step then uses a 2D DFT.
- Combination with other constraints. The phase constraint can join the coil sensitivity constraint of SENSE or a sparsity term as in compressed sensing MRI.
- Relatives in phase retrieval. The error reduction algorithm and the Gerchberg-Saxton algorithm also alternate between an image constraint and a Fourier constraint, but their Fourier set is not convex.
When to use it
Use POCS for partial Fourier data when the phase varies inside the image and homodyne is not accurate enough, when the image has both signs, or when the output must agree with the data. It costs several times more than homodyne reconstruction, but 5 to 10 iterations are often enough. As with any partial Fourier method, the phase must be smooth enough for the central band to show it.
Pitfalls
- Phase from the wrong samples. If line L1 uses all acquired samples, not a symmetric band, the reference phase is wrong even for a constant phase, and the limit is not the true image.
- Data step that changes the missing samples. If line L6 also sets the missing samples to zero, every iteration returns the zero filled image.
- No unitary scale. If line L5 and line L7 use DFTs with scales that do not cancel, line L7 does not invert line L5, and the data step is not a projection.
- Too many iterations on noisy data. With noise the sets do not meet. The iterates converge, but late iterations change little and can make the noise at the edge of the band more visible.
- Phase zeros. Where the low resolution image is zero, line L1 has no phase; the code uses 1 there.
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
pocs_partial_fourier.py 128 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pocs-partial-fourier/. The authors are listed in prov/KZJ4DM.jsonl.
"""POCS partial Fourier reconstruction (after Haacke, Lindskog and Lin 1991).
k-space convention: a list y of length n (n even) in DFT order, so index k
holds the signed frequency k for k < n/2 and k - n for k >= n/2. The data are
unitary DFT samples, y = F_u x with F_u = n^(-1/2) F. The scan acquires the
signed frequencies -n/2, ..., k0 with 0 <= k0 < n/2 - 1; the other entries of
y are not read.
The method alternates two projections in C^n, seen as R^(2n) with the real
inner product Re <u, v>:
- P1, onto C1 = {rho p : rho real}, the images with the reference phase p:
x_j <- Re(conj(p_j) x_j) p_j, with |p_j| = 1.
- P2, onto C2 = {x : (F_u x)_k = y_k for every acquired k}: replace the
acquired k-space samples of x by the data. F_u is unitary, so this is the
orthogonal projection.
Both sets are closed and convex (C1 is a real subspace, C2 an affine
subspace), so the iterates converge (see proofs/correctness.md).
The reference phase comes from the central band |k| <= k0, which is acquired
on both sides, weighted by a triangle window.
Cost: two DFTs of length n per iteration, O(K n log n) for K iterations
when n is a power of two.
"""
import math
from typing import Optional, Sequence
from imgkit import dft, idft
def signed_freq(k: int, n: int) -> int:
"""The signed frequency of DFT index k: k for k < n/2, k - n otherwise."""
return k if k < n // 2 else k - n
def partial_mask(n: int, k0: int) -> list[bool]:
"""True at the acquired DFT indices: the signed frequencies -n/2 .. k0."""
return [signed_freq(k, n) <= k0 for k in range(n)]
def unitary_dft(x: Sequence[complex]) -> list[complex]:
"""F_u x = n^(-1/2) times the DFT."""
s = 1.0 / math.sqrt(len(x))
return [v * s for v in dft(list(x))]
def unitary_idft(y: Sequence[complex]) -> list[complex]:
"""F_u^H y = sqrt(n) times the inverse DFT."""
s = math.sqrt(len(y))
return [v * s for v in idft(list(y))]
def reference_phase(y: Sequence[complex], k0: int) -> list[complex]:
"""Unit phase p of the low-resolution image of the band |f| <= k0 (triangle window); 1 where it is zero."""
n = len(y)
w = [0.0] * n
for k in range(n):
f = signed_freq(k, n)
if abs(f) <= k0:
w[k] = 1.0 - abs(f) / (k0 + 1)
low = unitary_idft([w[k] * y[k] for k in range(n)])
return [v / abs(v) if v != 0 else 1.0 + 0j for v in low]
def project_phase(x: Sequence[complex], p: Sequence[complex]) -> list[complex]:
"""P1: the nearest image of the form rho p with rho real."""
return [(pj.conjugate() * xj).real * pj for xj, pj in zip(x, p)]
def project_data(x: Sequence[complex], y: Sequence[complex], mask: Sequence[bool]) -> list[complex]:
"""P2: the nearest image whose acquired k-space samples equal the data."""
big = unitary_dft(x)
return unitary_idft([yk if a else bk for yk, bk, a in zip(y, big, mask)])
def pocs_1d(
y: Sequence[complex],
k0: int,
iters: int = 100,
phase: Optional[Sequence[complex]] = None,
history: Optional[list] = None,
) -> list[complex]:
"""POCS reconstruction of one line; returns the complex image estimate.
phase: an optional unit reference phase; by default reference_phase(y, k0).
history: if a list is given, each iterate is appended to it.
"""
n = len(y)
if n % 2 or not 0 <= k0 < n // 2 - 1:
raise ValueError("need an even n and 0 <= k0 < n/2 - 1")
mask = partial_mask(n, k0)
p = list(phase) if phase is not None else reference_phase(y, k0) # @line L1
x = unitary_idft([yk if a else 0j for yk, a in zip(y, mask)]) # @line L2
for _ in range(iters): # @line L3
x = project_phase(x, p) # @line L4
big = unitary_dft(x) # @line L5
big = [yk if a else bk for yk, bk, a in zip(y, big, mask)] # @line L6
x = unitary_idft(big) # @line L7
if history is not None:
history.append(x)
return x # @line L8
def pocs_2d(kspace: Sequence[Sequence[complex]], k0: int, iters: int = 100) -> list[list[complex]]:
"""POCS on an image whose k-space rows (axis 0, phase encoding) are partial.
kspace[a][b] is the unitary 2D DFT sample at row frequency index a and
column frequency index b. All columns are acquired, so an inverse DFT
along the columns splits the problem into one line per image column.
"""
n1, n2 = len(kspace), len(kspace[0])
hybrid = [unitary_idft(row) for row in kspace]
out = [[0j] * n2 for _ in range(n1)]
for j in range(n2):
col = pocs_1d([hybrid[a][j] for a in range(n1)], k0, iters)
for i in range(n1):
out[i][j] = col[i]
return out
def zero_filled_1d(y: Sequence[complex], k0: int) -> list[complex]:
"""The zero-filled image: F_u^H of y with the missing samples set to 0."""
m = partial_mask(len(y), k0)
return unitary_idft([v if a else 0j for v, a in zip(y, m)])
test_pocs_partial_fourier.py 179 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pocs-partial-fourier/. The authors are listed in prov/KZJ4DM.jsonl.
import cmath
import math
import random
import pytest
from imgkit import ellipse_phantom, MODIFIED_SHEPP_LOGAN, pixel_centers
from pocs_partial_fourier import (
partial_mask,
pocs_1d,
pocs_2d,
project_data,
project_phase,
reference_phase,
unitary_dft,
unitary_idft,
zero_filled_1d,
)
def dist(a, b):
return math.sqrt(sum(abs(u - v) ** 2 for u, v in zip(a, b)))
def gauss_solve(a, b):
"""Gaussian elimination with partial pivoting for a small dense real system."""
n = len(a)
m = [list(row) + [bi] for row, bi in zip(a, b)]
for c in range(n):
p = max(range(c, n), key=lambda r: abs(m[r][c]))
m[c], m[p] = m[p], m[c]
for r in range(c + 1, n):
f = m[r][c] / m[c][c]
for j in range(c, n + 1):
m[r][j] -= f * m[c][j]
x = [0.0] * n
for r in range(n - 1, -1, -1):
x[r] = (m[r][n] - sum(m[r][k] * x[k] for k in range(r + 1, n))) / m[r][r]
return x
def brute_least_squares(y, k0, p):
"""The real rho that fits F_u(rho p) to the acquired data best, from the normal equations."""
n = len(y)
mask = partial_mask(n, k0)
rows, rhs = [], []
for k in range(n):
if not mask[k]:
continue
coef = [cmath.exp(-2j * math.pi * j * k / n) / math.sqrt(n) * p[j] for j in range(n)]
rows.append([c.real for c in coef])
rhs.append(y[k].real)
rows.append([c.imag for c in coef])
rhs.append(y[k].imag)
ata = [[sum(r[i] * r[j] for r in rows) for j in range(n)] for i in range(n)]
atb = [sum(r[i] * b for r, b in zip(rows, rhs)) for i in range(n)]
rho = gauss_solve(ata, atb)
return [r * pj for r, pj in zip(rho, p)]
def masked(y, k0):
m = partial_mask(len(y), k0)
return [v if a else complex(-7.0, 3.0) for v, a in zip(y, m)]
def test_projections_are_idempotent():
rng = random.Random(5)
n, k0 = 16, 3
y = [complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(n)]
x = [complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(n)]
p = [cmath.exp(1j * rng.uniform(-3, 3)) for _ in range(n)]
mask = partial_mask(n, k0)
a = project_phase(x, p)
assert dist(project_phase(a, p), a) < 1e-12
b = project_data(x, y, mask)
assert dist(project_data(b, y, mask), b) < 1e-12
# Orthogonality of the residual in the real inner product.
for _ in range(5):
r = rng.gauss(0, 1)
u = [r * pj for pj in p]
assert abs(sum((ui.conjugate() * (xi - ai)).real for ui, xi, ai in zip(u, x, a))) < 1e-12
def test_constant_phase_signed_real_is_recovered():
rng = random.Random(6)
for n, k0 in ((16, 3), (32, 5)):
rho = [rng.uniform(-1.0, 1.0) for _ in range(n)]
ph = cmath.exp(0.9j)
x_true = [ph * r for r in rho]
y = masked(unitary_dft(x_true), k0)
out = pocs_1d(y, k0, iters=300)
assert dist(out, x_true) / dist(x_true, [0] * n) < 1e-6
def test_constant_phase_error_halves_each_iteration():
rng = random.Random(10)
n, k0 = 32, 6
rho = [rng.uniform(-1.0, 1.0) for _ in range(n)]
ph = cmath.exp(-0.4j)
x_true = [ph * r for r in rho]
y = unitary_dft(x_true)
hist = []
pocs_1d(y, k0, iters=8, phase=[ph] * n, history=hist)
d = [dist(zero_filled_1d(y, k0), x_true)] + [dist(h, x_true) for h in hist]
for a, b in zip(d, d[1:]):
assert b == pytest.approx(a / 2, rel=1e-9)
def test_matches_brute_force_least_squares_with_given_phase():
rng = random.Random(7)
n, k0 = 16, 2
xs = [-1 + (2 * j + 1) / n for j in range(n)]
p = [cmath.exp(1j * (0.3 + 1.2 * x - 0.4 * x * x)) for x in xs]
rho = [rng.uniform(0.0, 2.0) for _ in range(n)]
y = masked(unitary_dft([r * pj for r, pj in zip(rho, p)]), k0)
ref = brute_least_squares(y, k0, p)
out = pocs_1d(y, k0, iters=400, phase=p)
assert dist(out, ref) < 1e-6
assert dist(ref, [r * pj for r, pj in zip(rho, p)]) < 1e-8
def test_distance_to_solution_never_grows():
rng = random.Random(8)
n, k0 = 32, 4
xs = [-1 + (2 * j + 1) / n for j in range(n)]
p = [cmath.exp(1j * (1.0 - 0.8 * x)) for x in xs]
z = [rng.uniform(0.0, 1.0) * pj for pj in p]
y = unitary_dft(z)
hist = []
pocs_1d(y, k0, iters=60, phase=p, history=hist)
x0 = zero_filled_1d(y, k0)
d = [dist(x0, z)] + [dist(h, z) for h in hist]
for a, b in zip(d, d[1:]):
assert b <= a + 1e-12
assert d[-1] < 0.2 * d[0]
def test_inconsistent_data_still_settles():
rng = random.Random(9)
n, k0 = 16, 3
y = [complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(n)]
hist = []
pocs_1d(y, k0, iters=400, history=hist)
assert dist(hist[-1], hist[-2]) < 1e-8
def test_reference_phase_is_exact_for_constant_phase():
n, k0 = 16, 3
ph = cmath.exp(-2.0j)
rho = [0.0, 0.5, 1.0, 1.0, 2.0, 2.0, 1.0, 0.0, 0.0, 0.3, 0.3, 0.3, 0.0, 0.0, 1.0, 0.2]
p = reference_phase(unitary_dft([ph * r for r in rho]), k0)
assert max(abs(v - ph) for v in p) < 1e-12
def test_2d_smooth_phase_beats_zero_filling():
n, k0 = 16, 3
rho = ellipse_phantom(n, MODIFIED_SHEPP_LOGAN)
xs, ys = pixel_centers(n)
x = [[rho[i][j] * cmath.exp(1j * (0.4 + 0.5 * xs[j] - 0.6 * ys[i] + 0.2 * xs[j] * ys[i])) for j in range(n)] for i in range(n)]
rows = [unitary_dft(r) for r in x]
ks = [list(r) for r in zip(*[unitary_dft(list(c)) for c in zip(*rows)])]
out = pocs_2d(ks, k0, iters=30)
err_p = math.sqrt(sum((abs(out[i][j]) - rho[i][j]) ** 2 for i in range(n) for j in range(n)))
zf = [[0.0] * n for _ in range(n)]
for j in range(n):
col = [unitary_idft(ks[a])[j] for a in range(n)]
img = zero_filled_1d(col, k0)
for i in range(n):
zf[i][j] = abs(img[i])
err_z = math.sqrt(sum((zf[i][j] - rho[i][j]) ** 2 for i in range(n) for j in range(n)))
assert err_p < 0.8 * err_z
def test_bad_arguments():
with pytest.raises(ValueError):
pocs_1d([0j] * 8, 3)
History
Margosian, Schmitt and Purdy (1986) and Feinberg and colleagues (1986) showed that half of k-space with a phase correction gives a full image. Noll, Nishimura and Macovski (1991) gave the one-step homodyne method. In the same year Haacke, Lindskog and Lin published the iterative method in the Journal of Magnetic Resonance, with the phase constraint in the image domain and the data constraint in k-space. The idea of alternate projections onto convex sets goes back to von Neumann for two subspaces.
References
- E. M. Haacke, E. D. Lindskog and W. Lin, A fast, iterative, partial-Fourier technique capable of local phase recovery, Journal of Magnetic Resonance 92(1), 1991, 126 to 145, the iteration between the phase constraint in the image and the measured data in k-space (general locator; section numbers not confirmed)
- Matt A. Bernstein, Kevin F. King and Xiaohong Joe Zhou, Handbook of MRI Pulse Sequences, Elsevier Academic Press, 2004, Section 13.4, Partial Fourier Reconstruction
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 KZJ4DM Edit this page History Report an error Markdown