Algorithm Search⌘K

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
Properties
deterministicnot exactnot in placeoffline
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 nn along the phase encoding axis, in DFT order with frequencies −n/2,…,n/2−1-n/2, \ldots, n/2 - 1, and the number k0k_0 with 0≤k0<n/2−10 \le k_0 < n/2 - 1. The data are yf=(Fux)(f)y_f = (F_u x)(f) for f∈S={−n/2,…,k0}f \in S = \{-n/2, \ldots, k_0\}, where Fu=n−1/2FF_u = n^{-1/2} F is the unitary DFT. The model is x=eiφρx = e^{i\varphi}\rho with ρ\rho real and φ\varphi smooth. The output is a complex image x^\hat x whose acquired samples equal yy and whose phase is the reference phase. For an n1×n2n_1 \times n_2 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 C1={ρp:ρ∈Rn}C_1 = \{\rho p : \rho \in \mathbb{R}^n\}, the images with the reference phase pp, and C2C_2, the images whose samples on SS equal yy.

  1. POCS-PF(y, n, k0, K) ▷ y known for f = -n/2 .. k0
  2. 1p <- unit phase of F_u^H (T y) ▷ T: triangle window on |f| <= k0
  3. 2x <- F_u^H (y on S, 0 elsewhere) ▷ the zero filled image
  4. 3repeat K times
  5. 4x_j <- Re(conj(p_j) x_j) p_j for each pixel j ▷ project onto C1
  6. 5X <- F_u x
  7. 6X(f) <- y(f) for each f in S ▷ project onto C2
  8. 7x <- F_u^H X
  9. 8return x

Line L1 makes the reference phase from the band ∣f∣≤k0|f| \le k_0, which is measured on both sides, with the window T(f)=1−∣f∣/(k0+1)T(f) = 1 - |f|/(k_0+1). Where the low resolution image is zero, pj=1p_j = 1. Line L2 starts from the zero filled image. Line L4 keeps, at each pixel, the component of xjx_j along pjp_j; this is the nearest image with the phase pp. Lines L5 to L7 replace the acquired samples by the data and keep the estimate of the missing samples; because FuF_u is unitary, this is the nearest image that agrees with the data. The magnitude image ∣x^∣|\hat x| or the real part Re⁡(p‾x^)\operatorname{Re}(\overline{p} \hat x) is the result.

Example

Take n=8n = 8, k0=1k_0 = 1, the real profile ρ=[0,0,4,4,4,0,0,0]\rho = [0, 0, 4, 4, 4, 0, 0, 0] and the constant phase 0.50.5 rad, so x=e0.5iρx = e^{0.5i}\rho. The scan acquires f=−4,…,1f = -4, \ldots, 1 and misses f=2,3f = 2, 3. The reference phase of line L1 is e0.5ie^{0.5i} at every pixel. The table gives the relative error ∥xt−x∥/∥x∥\|x_t - x\| / \|x\| after tt iterations, rounded.

iteration tt 0 1 2 3 5 10 20
relative error 0.22094 0.11047 0.05524 0.02762 0.00690 0.00022 2×10−72 \times 10^{-7}

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 ρ=[0,0,4,4,−2,0,0,0]\rho = [0, 0, 4, 4, -2, 0, 0, 0] and the same phase, the errors are 0.516, 0.258, 0.129 and so on, and POCS again converges to xx. Homodyne reconstruction returns the sign of the smoothed image times ρ\rho, so it can give the wrong sign in such a case.

Correctness

Line L4 is the orthogonal projection onto C1C_1, a real linear subspace of Cn\mathbb{C}^n seen as R2n\mathbb{R}^{2n}. Lines L5 to L7 are the orthogonal projection onto C2C_2, an affine subspace. The key invariant is that for every z∈C1∩C2z \in C_1 \cap C_2, the distance ∥xt−z∥\|x_t - z\| never grows. The proof shows three theorems.

  • If C1∩C2C_1 \cap C_2 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 C2C_2 whose distance to C1C_1 is the distance between the sets.
  • For a real image with a constant phase and pj=±eiφ0p_j = \pm e^{i\varphi_0}, 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 C1C_1 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 Cn\mathbb{C}^n, viewed as the real vector space R2n\mathbb{R}^{2n} with the inner product ⟨u,v⟩=Re⁡∑juj‾vj\langle u, v \rangle = \operatorname{Re} \sum_j \overline{u_j} v_j and the norm ∥u∥2=∑j∣uj∣2\|u\|^2 = \sum_j |u_j|^2. FuF_u is the unitary DFT, so ∥Fuu∥=∥u∥\|F_u u\| = \|u\|. The acquired set is S={−n/2,…,k0}S = \{-n/2, \ldots, k_0\} (frequencies modulo nn), the reference phase pp has ∣pj∣=1|p_j| = 1, and

C1={ρ⋅p:ρ∈Rn},C2={x∈Cn:(Fux)(f)=yf for all f∈S}.C_1 = \{\rho \cdot p : \rho \in \mathbb{R}^n\}, \qquad C_2 = \{x \in \mathbb{C}^n : (F_u x)(f) = y_f \text{ for all } f \in S\}.

The iterates are x0=FuH(y on S,0 elsewhere)x_0 = F_u^H(y \text{ on } S, 0 \text{ elsewhere}) (line L2) and xt+1=P2P1xtx_{t+1} = P_2 P_1 x_t (lines L4 to L7).

Lemma 1 (the two steps are projections). Line L4 maps xx to the point of C1C_1 nearest to xx, and lines L5 to L7 map xx to the point of C2C_2 nearest to xx. C1C_1 is a real linear subspace, and C2C_2 is a nonempty affine subspace.

Proof. C1C_1 is closed under real linear combinations. For ρ∈Rn\rho \in \mathbb{R}^n, ∥x−ρp∥2=∑j∣xj−ρjpj∣2=∑j∣pj‾xj−ρj∣2\|x - \rho p\|^2 = \sum_j |x_j - \rho_j p_j|^2 = \sum_j |\overline{p_j} x_j - \rho_j|^2 because ∣pj∣=1|p_j| = 1. Each term is smallest for ρj=Re⁡(pj‾xj)\rho_j = \operatorname{Re}(\overline{p_j} x_j), which is line L4. C2C_2 is the solution set of linear equations and contains x0x_0. For v∈C2v \in C_2, ∥x−v∥=∥Fux−Fuv∥\|x - v\| = \|F_u x - F_u v\|, and FuvF_u v is free on the frequencies outside SS and fixed to yy on SS. The distance is smallest when FuvF_u v equals FuxF_u x outside SS, which is lines L5 to L7. □\square

For a closed subspace UU write PUP_U for the orthogonal projection. If C=a+UC = a + U is an affine subspace, the nearest point map is PC(x)=a+PU(x−a)P_C(x) = a + P_U(x - a).

Lemma 2. Let UU and VV be subspaces of a finite dimensional real inner product space, W=U∩VW = U \cap V and T=PVPUT = P_V P_U. Then Tw=wT w = w for w∈Ww \in W, TT maps W⊥W^\perp into W⊥W^\perp, and there is c<1c < 1 with ∥Te∥≤c∥e∥\|T e\| \le c \|e\| for all e∈W⊥e \in W^\perp. Hence Ttu→PWuT^t u \to P_W u for every uu, with ∥Ttu−PWu∥≤ct∥u−PWu∥\|T^t u - P_W u\| \le c^t \|u - P_W u\|.

Proof. For w∈Ww \in W, PUw=wP_U w = w and PVw=wP_V w = w. For e∈W⊥e \in W^\perp and w∈Ww \in W, using that projections are self-adjoint, ⟨Te,w⟩=⟨PUe,PVw⟩=⟨PUe,w⟩=⟨e,PUw⟩=⟨e,w⟩=0\langle T e, w \rangle = \langle P_U e, P_V w \rangle = \langle P_U e, w \rangle = \langle e, P_U w \rangle = \langle e, w \rangle = 0, so Te∈W⊥T e \in W^\perp. Projections do not increase norms, so ∥Te∥≤∥e∥\|T e\| \le \|e\|. If ∥Te∥=∥e∥\|T e\| = \|e\| for some e≠0e \ne 0, then ∥PUe∥=∥e∥\|P_U e\| = \|e\|, so e∈Ue \in U by Pythagoras, and then ∥PVe∥=∥e∥\|P_V e\| = \|e\|, so e∈Ve \in V. Then e∈W∩W⊥={0}e \in W \cap W^\perp = \{0\}, a contradiction. So ∥Te∥<∥e∥\|T e\| < \|e\| on the unit sphere of W⊥W^\perp, which is compact, and the maximum cc of the continuous function ∥Te∥\|T e\| there is below 1. Write u=PWu+eu = P_W u + e with e∈W⊥e \in W^\perp; then Ttu=PWu+TteT^t u = P_W u + T^t e and ∥Tte∥≤ct∥e∥\|T^t e\| \le c^t \|e\|. □\square

Theorem 1 (consistent case). If C1∩C2≠∅C_1 \cap C_2 \ne \emptyset, then xtx_t converges to the point of C1∩C2C_1 \cap C_2 nearest to x0x_0, and the error falls at least geometrically: ∥xt−x∗∥≤ct∥x0−x∗∥\|x_t - x_\ast\| \le c^t \|x_0 - x_\ast\| with c<1c < 1 from Lemma 2. Moreover ∥xt+1−z∥≤∥xt−z∥\|x_{t+1} - z\| \le \|x_t - z\| for every z∈C1∩C2z \in C_1 \cap C_2 and every tt.

Proof. Take z∈C1∩C2z \in C_1 \cap C_2. Then C1=z+UC_1 = z + U with U=C1U = C_1 (a subspace that contains zz), and C2=z+VC_2 = z + V with V={v:(Fuv)(f)=0 for f∈S}V = \{v : (F_u v)(f) = 0 \text{ for } f \in S\}. By Lemma 1 and the formula for PCP_C, xt+1−z=PVPU(xt−z)=T(xt−z)x_{t+1} - z = P_V P_U (x_t - z) = T (x_t - z). Lemma 2 gives xt−z→PW(x0−z)x_t - z \to P_W(x_0 - z) with W=U∩VW = U \cap V, at the stated rate. The limit x∗=z+PW(x0−z)x_\ast = z + P_W(x_0 - z) lies in z+W=C1∩C2z + W = C_1 \cap C_2, and it is the point of z+Wz + W nearest to x0x_0. The monotone distance follows from ∥Te∥≤∥e∥\|T e\| \le \|e\| with e=xt−ze = x_t - z. □\square

Theorem 2 (inconsistent case). If C1∩C2=∅C_1 \cap C_2 = \emptyset, for example with noisy data, then xtx_t still converges, to a point b∈C2b \in C_2 such that P1b∈C1P_1 b \in C_1 and ∥b−P1b∥\|b - P_1 b\| is the distance between C1C_1 and C2C_2.

Proof. Write C1=UC_1 = U and C2=a+VC_2 = a + V with a=x0a = x_0. The sum U+VU + V is a subspace of a finite dimensional space, so a=u−v+ga = u - v + g with u∈Uu \in U, v∈Vv \in V and g⊥U+Vg \perp U + V. Put a′=u∈C1a' = u \in C_1; then a+v=a′+ga + v = a' + g, so C2=a′+g+VC_2 = a' + g + V. For any xx, P1x=a′+PU(x−a′)P_1 x = a' + P_U(x - a') and P2x=a′+g+PV(x−a′−g)=a′+g+PV(x−a′)P_2 x = a' + g + P_V(x - a' - g) = a' + g + P_V(x - a'), because PVg=0P_V g = 0. With et=xt−a′−ge_t = x_t - a' - g and PUg=0P_U g = 0,

et+1=PVPU(xt−a′)=PVPU(et+g)=Tet.e_{t+1} = P_V P_U (x_t - a') = P_V P_U (e_t + g) = T e_t.

By Lemma 2, et→PWe0e_t \to P_W e_0, so xt→b=a′+g+PWe0∈C2x_t \to b = a' + g + P_W e_0 \in C_2. Then P1b=a′+PU(g+PWe0)=a′+PWe0=b−g∈C1P_1 b = a' + P_U(g + P_W e_0) = a' + P_W e_0 = b - g \in C_1. For any c1=a′+u1∈C1c_1 = a' + u_1 \in C_1 and c2=a′+g+v2∈C2c_2 = a' + g + v_2 \in C_2, ∥c2−c1∥2=∥g∥2+∥v2−u1∥2≥∥g∥2\|c_2 - c_1\|^2 = \|g\|^2 + \|v_2 - u_1\|^2 \ge \|g\|^2 because g⊥U+Vg \perp U + V. So ∥b−P1b∥=∥g∥\|b - P_1 b\| = \|g\| is the distance between the sets. □\square

Theorem 3 (constant phase). Let x=eiφ0ρx = e^{i\varphi_0}\rho with ρ\rho real, y=Fuxy = F_u x on SS, and pj∈{eiφ0,−eiφ0}p_j \in \{e^{i\varphi_0}, -e^{i\varphi_0}\} for all jj. Then C1∩C2={x}C_1 \cap C_2 = \{x\}, and ∥xt−x∥=2−t∥x0−x∥\|x_t - x\| = 2^{-t} \|x_0 - x\| for every tt.

Proof. The set C1C_1 is eiφ0Rne^{i\varphi_0}\mathbb{R}^n, because a sign on pjp_j does not change the real multiples. It contains xx, and C2C_2 contains xx. Let x′∈C1∩C2x' \in C_1 \cap C_2 and d=x−x′=eiφ0δd = x - x' = e^{i\varphi_0}\delta with δ\delta real. Then D=FuδD = F_u \delta is Hermitian, D(−f)=D(f)‾D(-f) = \overline{D(f)}, and D(f)=0D(f) = 0 for f∈Sf \in S. Every frequency ff has f∈Sf \in S or −f∈S-f \in S: if f>k0≥0f > k_0 \ge 0 then −n/2<−f<0-n/2 < -f < 0. So D=0D = 0 and x′=xx' = x.

For the rate, let M={k0+1,…,n/2−1}M = \{k_0 + 1, \ldots, n/2 - 1\} be the missing set; then −M⊂S-M \subset S and M∩(−M)=∅M \cap (-M) = \emptyset. The error et=xt−xe_t = x_t - x lies in VV, so Et=FuetE_t = F_u e_t is zero on SS and lives on MM. Line L4 fixes xx and is real linear, so P1xt−x=P1et=eiφ0Re⁡(e−iφ0et)=12(et+e2iφ0et‾)P_1 x_t - x = P_1 e_t = e^{i\varphi_0} \operatorname{Re}(e^{-i\varphi_0} e_t) = \frac{1}{2}\bigl(e_t + e^{2i\varphi_0}\overline{e_t}\bigr). The DFT of et‾\overline{e_t} at ff is Et(−f)‾\overline{E_t(-f)}, which lives on −M⊂S-M \subset S. Lines L5 to L7 set the spectrum on SS back to that of xx, so they remove that part, and Et+1=12EtE_{t+1} = \frac{1}{2} E_t. By Parseval, ∥et+1∥=12∥et∥\|e_{t+1}\| = \frac{1}{2}\|e_t\|. ■\blacksquare

Remarks.

  • The reference phase of line L1 is pj=lj/∣lj∣p_j = l_j/|l_j| for the triangle-windowed image ll. For x=eiφ0ρx = e^{i\varphi_0}\rho with real ρ\rho, l=eiφ0rl = e^{i\varphi_0} r with rr real (the argument of the homodyne proof), so pj=±eiφ0p_j = \pm e^{i\varphi_0} wherever lj≠0l_j \ne 0, and Theorem 3 applies when no ljl_j is zero.
  • The variant that replaces xjx_j by ∣xj∣pj|x_j| p_j (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 C1C_1 and C2C_2, but C1C_1 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 nn and O(n)O(n) other operations. With an FFT and nn a power of two this is O(nlog⁡n)O(n \log n) per line, and O(Kn2log⁡n)O(K n^2 \log n) for KK iterations on an n×nn \times n image, in the real RAM. The method stores the hybrid data and the image, O(n2)O(n^2) numbers. Line L1 costs one more inverse DFT per line.

Properties

  • Convergence. The iterates converge for any unit phase pp (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 ρ\rho has both signs (theorem). The sign of ρ\rho is relative to pp.
  • Smooth phase. On a 16×1616 \times 16 modified Shepp-Logan phantom with the phase 0.4+0.5x−0.6y+0.2xy0.4 + 0.5x - 0.6y + 0.2xy rad on [−1,1]2[-1, 1]^2 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 xjx_j by ∣xj∣pj|x_j| p_j 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 f=k0f = k_0 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.

imgkit.pyI0RawGitHub
# 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

  1. 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)
  2. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example