Algorithm Search⌘K

Algorithmcore

Homodyne reconstruction

Also called homodyne detection for partial Fourier.

Reconstructs an MR image from partial k-space: double the unpaired high frequencies, remove a low resolution phase estimate and keep the real part. Exact for a real image with a constant phase.

Time
O(n^2 log n) worst
Space
O(n^2) extra
Where
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
Douglas C. Noll, Dwight G. Nishimura, Albert Macovski, 1991

Homodyne reconstruction rebuilds an MR image from a little more than half of k-space, the case of partial Fourier reconstruction. The scan acquires one side of the phase encoding axis fully and the other side only near the center. The method doubles the high frequencies that have no measured mirror partner, estimates the image phase from the small band that is measured on both sides, removes that phase, and keeps the real part. Noll, Nishimura and Macovski published it in 1991. For a real image times a constant phase factor, and with a nonnegative real part, the result is exact; this page proves it. For a smooth phase it is a good approximation, and for a phase that changes fast it fails.

In plain words

The picture we want is made of real numbers, but the scanner adds a slowly changing tilt to each value. For a picture of real numbers, each wave in its frequency description has a mirror wave that carries the same information. So half of the frequencies would be enough, if there were no tilt.

Homodyne uses this. The scanner measures all waves on one side, and only a few on the other side near the middle. Each unpaired wave is counted twice, to stand in for its missing mirror. The few paired waves near the middle give a blurry picture, and its tilt is a good guess of the true tilt. The method turns every pixel back by that guessed tilt, and then throws away the part that is not real. What it throws away is exactly the error that the doubling made.

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 the acquired frequencies f∈S={−n/2,…,k0}f \in S = \{-n/2, \ldots, k_0\}, where FuF_u is the unitary DFT (Fu=n−1/2FF_u = n^{-1/2} F, see mri-signal-equation). The fraction of acquired samples is (n/2+k0+1)/n(n/2 + k_0 + 1)/n, for example 5/8 or 3/4. The output is a real image ρ^\hat\rho. The model is x=eiφρx = e^{i\varphi}\rho with ρ\rho real and φ\varphi smooth. 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

FuHF_u^H is the unitary inverse DFT, computed with an FFT.

  1. HOMODYNE(y, n, k0) ▷ y known for f = -n/2 .. k0
  2. 1H(f) <- 0 if f > k0; 1 if |f| <= k0 or f = -n/2; 2 otherwise
  3. 2T(f) <- 1 - |f|/(k0 + 1) if |f| <= k0; 0 otherwise
  4. 3z <- F_u^H (H y) ▷ the weighted image
  5. 4l <- F_u^H (T y) ▷ the low resolution image
  6. 5for each pixel j do
  7. 6if l_j = 0 then rho_j <- 0
  8. 7else rho_j <- Re(conj(l_j) z_j / |l_j|)
  9. 8return rho

Line L1 is the homodyne filter. The two values of a pair f,−ff, -f always sum to 2: the band ∣f∣≤k0|f| \le k_0 is measured on both sides and gets 1 on each side, an unpaired frequency f<−k0f < -k_0 gets 2 and its missing partner gets 0, and the Nyquist frequency −n/2-n/2 is its own partner and gets 1. Line L2 is a triangular window on the symmetric band. Lines L3 and L4 read the data only where they are acquired, because HH and TT are zero elsewhere. Line L7 removes the phase of the low resolution image and keeps the real part.

A common variant replaces the step by a linear ramp on the band, H(f)=1−f/(k0+1)H(f) = 1 - f/(k_0+1) for ∣f∣≤k0|f| \le k_0. It also sums to 2 across the center and gives less ringing at the edges of the band.

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=0.5\varphi_0 = 0.5 rad. The scan acquires f=−4,…,1f = -4, \ldots, 1, which is 6 of 8 samples, and misses f=2,3f = 2, 3. Line L1 gives H=[1,1,0,0,1,2,2,1]H = [1, 1, 0, 0, 1, 2, 2, 1] in DFT order (frequencies 0,1,2,3,−4,−3,−2,−10, 1, 2, 3, -4, -3, -2, -1) and line L2 gives T=[1,12,0,0,0,0,0,12]T = [1, \frac{1}{2}, 0, 0, 0, 0, 0, \frac{1}{2}]. The table shows each pixel with the phase eiφ0e^{i\varphi_0} taken out of zz and ll, rounded to 3 places.

pixel jj ρj\rho_j zero filled ∣⋅∣\lvert\cdot\rvert e−iφ0zje^{-i\varphi_0} z_j e−iφ0lje^{-i\varphi_0} l_j output
0 0 0.663 −1.293i-1.293i 0.646 0
1 0 0.541 0.414i0.414i 1.500 0
2 4 3.870 4+0.707i4 + 0.707i 2.354 4
3 4 3.707 44 2.707 4
4 4 3.870 4−0.707i4 - 0.707i 2.354 4
5 0 0.541 −0.414i-0.414i 1.500 0
6 0 0.663 1.293i1.293i 0.646 0
7 0 0.707 00 0.293 0

The zero filled image, the inverse DFT with the missing samples set to 0, is blurred and has a relative error of 0.221 against xx. The weighted image zz has the exact profile in its real part and the whole error in its imaginary part. The low resolution image has the right phase at every pixel, so line L7 returns ρ\rho exactly.

Correctness

The key fact is the sum rule H(f)+H(−f)=2H(f) + H(-f) = 2. Write H=1+AH = 1 + A; then AA is odd. For a real profile ρ\rho, the DFT RR is Hermitian, R(−f)=R(f)‾R(-f) = \overline{R(f)}, so ARA R is anti-Hermitian and its inverse DFT is purely imaginary. Hence z=eiφ0(ρ+iq)z = e^{i\varphi_0}(\rho + i q) with qq real. The window TT is real and even, so l=eiφ0rl = e^{i\varphi_0} r with rr real, and rr is ρ\rho smoothed by the Fejér kernel, which is nonnegative. Line L7 then returns sign⁡(rj)ρj\operatorname{sign}(r_j)\rho_j, which is ρj\rho_j when ρ≥0\rho \ge 0. The proof gives the details. This is a theorem about the model x=eiφ0ρx = e^{i\varphi_0}\rho with a constant φ0\varphi_0; it says nothing about images whose phase varies.

Proof: Homodyne reconstruction is exact for a real image with a constant phasefull

The setting is that of the algorithm. The line has even length nn, and FuF_u is the unitary DFT, (Fuv)(f)=n−1/2∑j=0n−1vje−2πijf/n(F_u v)(f) = n^{-1/2} \sum_{j=0}^{n-1} v_j e^{-2\pi i j f / n}. Frequencies ff are taken modulo nn and written in −n/2,…,n/2−1-n/2, \ldots, n/2 - 1. The scan acquires the set S={−n/2,…,k0}S = \{-n/2, \ldots, k_0\} with 0≤k0<n/2−10 \le k_0 < n/2 - 1. The filter HH of line L1 is real, is 00 for f>k0f > k_0, and satisfies

H(f)+H(−f)=2for every f.(1)H(f) + H(-f) = 2 \quad \text{for every } f. \tag{1}

The step filter and the ramp filter both satisfy (1): for ∣f∣≤k0|f| \le k_0 the step filter gives 1+11 + 1 and the ramp gives (1−f/(k0+1))+(1+f/(k0+1))(1 - f/(k_0+1)) + (1 + f/(k_0+1)); for k0<f<n/2k_0 < f < n/2 the pair is 0+20 + 2; and f=−n/2f = -n/2 is its own negative modulo nn, with H(−n/2)=1H(-n/2) = 1. The window TT of line L2 is T(f)=1−∣f∣/(k0+1)T(f) = 1 - |f|/(k_0+1) for ∣f∣≤k0|f| \le k_0 and 00 otherwise.

Theorem. Let xj=eiφ0ρjx_j = e^{i\varphi_0} \rho_j with a constant φ0\varphi_0 and a real vector ρ\rho, and let yf=(Fux)(f)y_f = (F_u x)(f) for f∈Sf \in S. Let r=FuH(T⋅Fuρ)r = F_u^H (T \cdot F_u \rho). Then rr is real, and the output of HOMODYNE is ρ^j=sign⁡(rj) ρj\hat\rho_j = \operatorname{sign}(r_j)\, \rho_j where rj≠0r_j \ne 0 and ρ^j=0\hat\rho_j = 0 where rj=0r_j = 0. If ρ≥0\rho \ge 0, then ρ^=ρ\hat\rho = \rho.

Lemma 1. Let GG be a sequence on the frequencies with G(−f)=G(f)‾G(-f) = \overline{G(f)} for all ff. Then FuHGF_u^H G is real. If instead G(−f)=−G(f)‾G(-f) = -\overline{G(f)} for all ff, then FuHGF_u^H G is purely imaginary.

Proof. Write g=FuHGg = F_u^H G, so gj=n−1/2∑fG(f)e2πijf/ng_j = n^{-1/2} \sum_f G(f) e^{2\pi i j f/n}. Then

gj‾=n−1/2∑fG(f)‾ e−2πijf/n=n−1/2∑fG(−f)‾ e2πijf/n,\overline{g_j} = n^{-1/2} \sum_f \overline{G(f)}\, e^{-2\pi i j f/n} = n^{-1/2} \sum_f \overline{G(-f)}\, e^{2\pi i j f/n},

after the change of index f→−ff \to -f, which is a bijection modulo nn. In the first case G(−f)‾=G(f)\overline{G(-f)} = G(f), so gj‾=gj\overline{g_j} = g_j. In the second case G(−f)‾=−G(f)\overline{G(-f)} = -G(f), so gj‾=−gj\overline{g_j} = -g_j. □\square

Lemma 2. For ρ≥0\rho \ge 0 and ρj>0\rho_j > 0, the value rjr_j is positive.

Proof. The product T⋅FuρT \cdot F_u \rho is a pointwise product in frequency, so rr is the periodic convolution rj=∑iκj−i ρir_j = \sum_i \kappa_{j-i}\, \rho_i with the kernel κm=n−1∑∣f∣≤k0T(f)e2πimf/n\kappa_m = n^{-1} \sum_{|f| \le k_0} T(f) e^{2\pi i m f/n}. For ∣f∣≤k0|f| \le k_0, the number of pairs (a,b)(a, b) with 0≤a,b≤k00 \le a, b \le k_0 and a−b=fa - b = f is k0+1−∣f∣k_0 + 1 - |f|, so T(f)=(k0+1)−1#{(a,b):a−b=f}T(f) = (k_0+1)^{-1} \#\{(a,b) : a - b = f\}. The frequencies −k0,…,k0-k_0, \ldots, k_0 are distinct modulo nn because 2k0+1<n2k_0 + 1 < n. Hence

κm=1n(k0+1)∑a=0k0∑b=0k0e2πim(a−b)/n=1n(k0+1)∣∑a=0k0e2πima/n∣2≥0,\kappa_m = \frac{1}{n (k_0+1)} \sum_{a=0}^{k_0} \sum_{b=0}^{k_0} e^{2\pi i m (a - b)/n} = \frac{1}{n (k_0+1)} \Bigl|\sum_{a=0}^{k_0} e^{2\pi i m a/n}\Bigr|^2 \ge 0,

the discrete Fejér kernel, with κ0=(k0+1)/n>0\kappa_0 = (k_0+1)/n > 0. All terms of rjr_j are then nonnegative, and rj≥κ0ρj>0r_j \ge \kappa_0 \rho_j > 0. □\square

Proof of the theorem. Put R=FuρR = F_u \rho. Because ρ\rho is real, R(−f)=R(f)‾R(-f) = \overline{R(f)}. By linearity yf=eiφ0R(f)y_f = e^{i\varphi_0} R(f) for f∈Sf \in S.

First, lines L3 and L4 read yy only on SS: H(f)=0H(f) = 0 for f>k0f > k_0, and T(f)=0T(f) = 0 for ∣f∣>k0|f| > k_0. So H⋅y=eiφ0H⋅RH \cdot y = e^{i\varphi_0} H \cdot R and T⋅y=eiφ0T⋅RT \cdot y = e^{i\varphi_0} T \cdot R as full sequences.

The window. TT is real and even, so G=T⋅RG = T \cdot R satisfies G(−f)=T(f)R(f)‾=G(f)‾G(-f) = T(f) \overline{R(f)} = \overline{G(f)}. By Lemma 1, r=FuHGr = F_u^H G is real, and line L4 gives l=eiφ0rl = e^{i\varphi_0} r.

The filter. Write H=1+AH = 1 + A with A(f)=H(f)−1A(f) = H(f) - 1. By (1), A(−f)=1−H(f)=−A(f)A(-f) = 1 - H(f) = -A(f), so AA is real and odd. The sequence G′=A⋅RG' = A \cdot R satisfies G′(−f)=−A(f) R(f)‾=−G′(f)‾G'(-f) = -A(f)\, \overline{R(f)} = -\overline{G'(f)}. By Lemma 1, q′=FuHG′q' = F_u^H G' is purely imaginary; write q′=iqq' = i q with qq real. Since FuHR=ρF_u^H R = \rho, line L3 gives

z=eiφ0(FuHR+FuH(A⋅R))=eiφ0(ρ+iq).z = e^{i\varphi_0} \bigl(F_u^H R + F_u^H (A \cdot R)\bigr) = e^{i\varphi_0} (\rho + i q).

Lines L5 to L7. If lj=0l_j = 0, then rj=0r_j = 0 and line L6 returns 00. Otherwise ∣lj∣=∣rj∣|l_j| = |r_j| and

lj‾ zj∣lj∣=rj e−iφ0 eiφ0(ρj+iqj)∣rj∣=sign⁡(rj) (ρj+iqj),\frac{\overline{l_j}\, z_j}{|l_j|} = \frac{r_j\, e^{-i\varphi_0}\, e^{i\varphi_0} (\rho_j + i q_j)}{|r_j|} = \operatorname{sign}(r_j)\,(\rho_j + i q_j),

whose real part, kept by line L7, is sign⁡(rj) ρj\operatorname{sign}(r_j)\, \rho_j. This is the first claim.

If ρ≥0\rho \ge 0: where ρj>0\rho_j > 0, Lemma 2 gives rj>0r_j > 0 and the output is ρj\rho_j. Where ρj=0\rho_j = 0, the output is sign⁡(rj)⋅0=0\operatorname{sign}(r_j) \cdot 0 = 0 or, if rj=0r_j = 0, the value 00 of line L6. In both cases the output is ρj\rho_j. ■\blacksquare

Remarks.

  • The two-dimensional method of the page applies an inverse DFT along the fully sampled readout axis first. That step is exact and acts on each column separately, so the theorem holds column by column when the phase is constant over the image.
  • The imaginary part qq is the error that a filter with (1) puts into the image. Taking the real part after the phase removal discards it. A filter without (1) leaves a real error term that the real part cannot remove.
  • For a phase that is not constant, the phase of ll is only an estimate of the phase of xx, and the output is an approximation. The theorem gives no error bound in that case.

Complexity

Each line costs two inverse DFTs of length nn and O(n)O(n) other operations: O(nlog⁡n)O(n \log n) with an FFT when nn is a power of two, and O(n2)O(n^2) with a direct DFT. An n×nn \times n image needs one inverse DFT along the readout for each of the nn k-space lines and one homodyne step for each of the nn columns, O(n2log⁡n)O(n^2 \log n) in total in the real RAM. The memory holds zz and ll, O(n)O(n) numbers per line. The method is not iterative.

Properties

  • Exact for a constant phase. For x=eiφ0ρx = e^{i\varphi_0}\rho with ρ≥0\rho \ge 0 the output is ρ\rho (theorem). With a signed real ρ\rho, the output is ρ\rho multiplied by the sign of its smoothed version.
  • Approximate for a 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 error was 0.094 with the step filter and 0.085 with the ramp, against 0.333 for the zero filled magnitude (measurement with the code of this page).
  • Real output. The method returns a real image. It discards the phase, so it does not suit phase-sensitive uses such as flow or susceptibility imaging.
  • Linear in the data for a fixed phase. With the phase estimate fixed, lines L3 and L7 are linear in yy.
  • One pass. No iteration and no parameter other than k0k_0 and the shape of the filter.

Variants and improvements

  • Ramp filter. A linear ramp across the band in line L1 in place of the step. It keeps the sum rule and reduces the ringing that the step causes.
  • Other phase windows. Any real, even window on the band gives a real rr in line L4. A nonnegative kernel, such as the triangle here, keeps the sign of rr right for a nonnegative image. A Hann window is another choice.
  • Iterative homodyne and POCS. POCS partial Fourier reconstruction iterates between the phase constraint and the data. It costs more and handles a varying phase better.
  • Zero filling. The inverse DFT with the missing samples set to zero. It needs no phase model and gives a blurred image (the zero filled column of the table).
  • Earlier phase-corrected half Fourier methods. Margosian, Schmitt and Purdy (1986) used a low resolution phase estimate before the conjugate synthesis.

When to use it

Use homodyne reconstruction for partial Fourier magnitude images in k-space when the phase is smooth, for example in spin echo images, in echo planar images with a shortened echo time, and in fast spin echo with fewer phase encoding lines. The phase estimate is only as sharp as the band ∣f∣≤k0|f| \le k_0, so collect enough lines past the center for the phase of the object. When the phase has sharp features, or when the image phase is needed, use full sampling or a constrained method such as POCS. When the image is not real up to a phase, partial Fourier gives no gain.

Pitfalls

  • Filter that does not sum to 2. If line L1 gives the unpaired frequencies weight 1 instead of 2, the image keeps only half of their energy and is blurred. If line L1 gives the Nyquist frequency −n/2-n/2 weight 2, that frequency is counted twice, because it is its own mirror.
  • Window that is not even. If line L2 uses all acquired samples, or any window that is not symmetric about 0, then rr is not real and the phase estimate of line L4 is wrong even for a constant phase.
  • Magnitude in place of the real part. If line L7 takes ∣zj∣|z_j|, the result is ρj2+qj2\sqrt{\rho_j^2 + q_j^2}, and the error qq stays in the image.
  • Fast phase changes. Flow, susceptibility edges and motion change the phase faster than the band can show. The phase error then turns into signal loss and wrong signs.
  • Signed images. For an inversion recovery image with negative real values, the output takes the sign of the smoothed image, so small negative regions next to large positive ones change sign.
  • Too narrow a band. With a very small k0k_0, the phase estimate is poor, and the error grows.

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.

homodyne_reconstruction.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/homodyne-reconstruction/. The authors are listed in prov/4ZY7XX.jsonl.

"""Homodyne reconstruction of partial Fourier MRI data (Noll, Nishimura and Macovski 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 entries of y at
the frequencies k0 + 1, ..., n/2 - 1 are not read.

For an image x = exp(i phi0) rho with a constant phase phi0 and rho >= 0, the
output is rho exactly (see proofs/correctness.md). For a smooth phase the
output is an approximation.

Cost: two inverse DFTs of length n and O(n) other work per line, so
O(n log n) with the radix-2 FFT of imgkit when n is a power of two.
"""

import math
from typing import 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 homodyne_weights(n: int, k0: int, kind: str = "step") -> list[float]:
    """The homodyne filter H in DFT order. H(f) + H(-f) = 2 for every frequency f.

    kind "step": 2 on the high frequencies of the acquired side, 1 on the
    symmetric band |f| <= k0 and at f = -n/2, 0 on the missing side.
    kind "ramp": the same, with a linear ramp 1 - f / (k0 + 1) on |f| <= k0.
    """
    h = [0.0] * n
    for k in range(n):
        f = signed_freq(k, n)
        if f > k0:
            h[k] = 0.0
        elif abs(f) <= k0:
            h[k] = 1.0 if kind == "step" else 1.0 - f / (k0 + 1)
        elif f == -(n // 2):
            h[k] = 1.0
        else:
            h[k] = 2.0
    return h


def triangle_window(n: int, k0: int) -> list[float]:
    """T(f) = 1 - |f| / (k0 + 1) on |f| <= k0, 0 elsewhere, in DFT order."""
    t = [0.0] * n
    for k in range(n):
        f = signed_freq(k, n)
        if abs(f) <= k0:
            t[k] = 1.0 - abs(f) / (k0 + 1)
    return t


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 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 homodyne_1d(y: Sequence[complex], k0: int, kind: str = "step") -> list[float]:
    """The real image rho from partial k-space y (DFT order, frequencies -n/2 .. k0 acquired)."""
    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")
    h = homodyne_weights(n, k0, kind)  # @line L1
    t = triangle_window(n, k0)  # @line L2
    z = unitary_idft([h[k] * y[k] for k in range(n)])  # @line L3
    low = unitary_idft([t[k] * y[k] for k in range(n)])  # @line L4
    rho = [0.0] * n
    for j in range(n):  # @line L5
        if low[j] == 0:  # @line L6
            rho[j] = 0.0
        else:
            rho[j] = (low[j].conjugate() * z[j]).real / abs(low[j])  # @line L7
    return rho  # @line L8


def homodyne_2d(kspace: Sequence[Sequence[complex]], k0: int, kind: str = "step") -> list[list[float]]:
    """Homodyne 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, both in DFT order. All columns are acquired.
    The inverse DFT along the columns (the readout) gives one 1D problem per
    image column, and each one is solved by homodyne_1d.
    """
    n1, n2 = len(kspace), len(kspace[0])
    hybrid = [unitary_idft(row) for row in kspace]  # rows: ky; columns: x
    out = [[0.0] * n2 for _ in range(n1)]
    for j in range(n2):
        col = homodyne_1d([hybrid[a][j] for a in range(n1)], k0, kind)
        for i in range(n1):
            out[i][j] = col[i]
    return out


def unitary_dft2(img: Sequence[Sequence[complex]]) -> list[list[complex]]:
    """The unitary 2D DFT of an image (DFT order on both axes)."""
    rows = [unitary_dft(r) for r in img]
    cols = [unitary_dft(list(c)) for c in zip(*rows)]
    return [list(r) for r in zip(*cols)]


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 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 0.0 for v, a in zip(y, m)])
imgkit.py 322 lines
# SPDX-License-Identifier: MIT
# Shared helper of the imaging and inverse problems pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small images and signals for the imaging and inverse problems pages.

Conventions:
- A signal is a list of numbers. An image is a list of rows, img[i][j], with
  row i from the top and column j from the left.
- An n x n image covers the square [-1, 1]^2. The center of pixel (i, j) is
  x_j = -1 + (2 j + 1) / n and y_i = 1 - (2 i + 1) / n, so y goes up.
- DFT: X_k = sum_j x_j exp(-2 pi i j k / n), unnormalized; the inverse has
  the factor 1 / n. Index k stands for frequency k for k < n / 2 and k - n
  otherwise. fftshift moves the zero frequency to position n // 2.
- Periodic convolution kernels are stored with their center at index 0
  (wrapped around), so a delta kernel gives the identity and no shift.
"""

import cmath
import math

# ------------------------------------------------------------------ images


def new_image(n1, n2, value=0.0):
    """An n1 x n2 image (n1 rows, n2 columns) filled with value."""
    return [[value] * n2 for _ in range(n1)]


def img_add(a, b):
    """The pixelwise sum a + b."""
    return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]


def img_scale(a, c):
    """The image c a."""
    return [[c * x for x in row] for row in a]


def img_dot(a, b):
    """<a, b> = sum conj(a_ij) b_ij."""
    return sum(x.conjugate() * y for ra, rb in zip(a, b) for x, y in zip(ra, rb))


def img_norm(a):
    """The Euclidean (Frobenius) norm of an image."""
    return math.sqrt(sum(abs(x) ** 2 for row in a for x in row))


def flatten(img):
    """Row-major vector of an image."""
    return [x for row in img for x in row]


def unflatten(v, n1, n2):
    """The n1 x n2 image of a row-major vector."""
    return [list(v[i * n2:(i + 1) * n2]) for i in range(n1)]


# ------------------------------------------------------------------ DFT


def _is_pow2(n):
    return n > 0 and n & (n - 1) == 0


def _fft_pow2(x):
    """Iterative radix-2 FFT, unnormalized forward transform."""
    n = len(x)
    a = [complex(v) for v in x]
    j = 0
    for i in range(1, n):
        bit = n >> 1
        while j & bit:
            j ^= bit
            bit >>= 1
        j |= bit
        if i < j:
            a[i], a[j] = a[j], a[i]
    size = 2
    while size <= n:
        half = size // 2
        tw = [cmath.exp(-2j * math.pi * k / size) for k in range(half)]
        for start in range(0, n, size):
            for k in range(half):
                u = a[start + k]
                v = a[start + k + half] * tw[k]
                a[start + k] = u + v
                a[start + k + half] = u - v
        size *= 2
    return a


def dft(x):
    """X_k = sum_j x_j exp(-2 pi i j k / n). Radix-2 FFT when n is a power of 2."""
    n = len(x)
    if n == 0:
        return []
    if _is_pow2(n):
        return _fft_pow2(x)
    w = [cmath.exp(-2j * math.pi * t / n) for t in range(n)]
    return [sum(x[j] * w[(j * k) % n] for j in range(n)) for k in range(n)]


def idft(xf):
    """x_j = (1/n) sum_k X_k exp(2 pi i j k / n)."""
    n = len(xf)
    if n == 0:
        return []
    y = dft([complex(v).conjugate() for v in xf])
    return [v.conjugate() / n for v in y]


def _rows_then_cols(img, f):
    rows = [f(row) for row in img]
    cols = [f(list(col)) for col in zip(*rows)]
    return [list(r) for r in zip(*cols)]


def dft2(img):
    """2D DFT: X_kl = sum_jq x_jq exp(-2 pi i (j k / n1 + q l / n2))."""
    return _rows_then_cols(img, dft)


def idft2(img):
    """Inverse 2D DFT, with the factor 1 / (n1 n2)."""
    return _rows_then_cols(img, idft)


def _shift1(x, s):
    return list(x[s:]) + list(x[:s])


def fftshift(x):
    """Move the zero frequency to position n // 2 (1D, or both axes of an image)."""
    if x and isinstance(x[0], (list, tuple)):
        rows = [fftshift(r) for r in x]
        return _shift1(rows, (len(rows) + 1) // 2)
    return _shift1(x, (len(x) + 1) // 2)


def ifftshift(x):
    """The inverse of fftshift (1D, or both axes of an image)."""
    if x and isinstance(x[0], (list, tuple)):
        rows = [ifftshift(r) for r in x]
        return _shift1(rows, len(rows) // 2)
    return _shift1(x, len(x) // 2)


def circ_conv(x, h):
    """Periodic convolution y_i = sum_j h_j x_{(i - j) mod n}, kernel centered at index 0."""
    n = len(x)
    nz = [(j, hj) for j, hj in enumerate(h) if hj != 0]
    return [sum(hj * x[(i - j) % n] for j, hj in nz) for i in range(n)]


def circ_conv2(img, h):
    """Periodic 2D convolution with the kernel h centered at index (0, 0)."""
    n1, n2 = len(img), len(img[0])
    nz = [(p, q, h[p][q]) for p in range(len(h)) for q in range(len(h[0])) if h[p][q] != 0]
    out = new_image(n1, n2)
    for i in range(n1):
        for j in range(n2):
            out[i][j] = sum(v * img[(i - p) % n1][(j - q) % n2] for p, q, v in nz)
    return out


# ------------------------------------------------------------------ phantoms


def pixel_centers(n):
    """(xs, ys): xs[j] = -1 + (2 j + 1) / n and ys[i] = 1 - (2 i + 1) / n."""
    xs = [-1.0 + (2 * j + 1) / n for j in range(n)]
    ys = [1.0 - (2 * i + 1) / n for i in range(n)]
    return xs, ys


# Rows: rho, A, B, x0, y0, phi (degrees). A is the semi-axis along the
# direction phi (counterclockwise from the x axis), B the other semi-axis.
# Geometry and densities of Shepp and Logan (1974), as reproduced in Kak and
# Slaney, Principles of Computerized Tomographic Imaging, Table 3.1. The value
# at the center (0, 0) is 2 - 0.98 = 1.02.
SHEPP_LOGAN = [
    (2.0, 0.92, 0.69, 0.0, 0.0, 90.0),
    (-0.98, 0.874, 0.6624, 0.0, -0.0184, 90.0),
    (-0.02, 0.31, 0.11, 0.22, 0.0, 72.0),
    (-0.02, 0.41, 0.16, -0.22, 0.0, 108.0),
    (0.01, 0.25, 0.21, 0.0, 0.35, 90.0),
    (0.01, 0.046, 0.046, 0.0, 0.1, 0.0),
    (0.01, 0.046, 0.046, 0.0, -0.1, 0.0),
    (0.01, 0.046, 0.023, -0.08, -0.605, 0.0),
    (0.01, 0.023, 0.023, 0.0, -0.605, 0.0),
    (0.01, 0.046, 0.023, 0.06, -0.605, 90.0),
]

# The same ellipses with the gray levels of Toft (1996), which give more
# contrast. The value at the center is 1 - 0.8 = 0.2.
MODIFIED_SHEPP_LOGAN = [
    (rho, a, b, x0, y0, phi)
    for rho, (_, a, b, x0, y0, phi) in zip(
        (1.0, -0.8, -0.2, -0.2, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1), SHEPP_LOGAN
    )
]


def ellipse_value(x, y, table):
    """The phantom value at the point (x, y): the sum of rho over the ellipses that hold it."""
    total = 0.0
    for rho, a, b, x0, y0, phi in table:
        c, s = math.cos(math.radians(phi)), math.sin(math.radians(phi))
        dx, dy = x - x0, y - y0
        u = dx * c + dy * s
        v = -dx * s + dy * c
        if (u / a) ** 2 + (v / b) ** 2 <= 1.0:
            total += rho
    return total


def ellipse_phantom(n, table):
    """The n x n image of an ellipse table, sampled at the pixel centers."""
    xs, ys = pixel_centers(n)
    return [[ellipse_value(x, y, table) for x in xs] for y in ys]


def disk_phantom(n, radius):
    """1 at pixel centers with x^2 + y^2 <= radius^2, 0 elsewhere."""
    xs, ys = pixel_centers(n)
    r2 = radius * radius
    return [[1.0 if x * x + y * y <= r2 else 0.0 for x in xs] for y in ys]


def spikes_1d(n, positions, amplitudes):
    """A signal of length n with the given amplitudes at the given positions."""
    out = [0.0] * n
    for p, a in zip(positions, amplitudes):
        out[p] += a
    return out


# ------------------------------------------------------------------ projector


def parallel_beam_matrix(n, angles, nbins):
    """Pixel-driven discrete Radon transform of an n x n image on [-1, 1]^2.

    Each pixel center (x, y) projects to s = x cos(theta) + y sin(theta). Its
    value times the pixel area over the bin width is split linearly between
    the two nearest bin centers. The bins cover [-sqrt(2), sqrt(2)]. Row
    a * nbins + b holds angle a and bin b; column i * n + j holds pixel (i, j).
    Returns the sparse rows, each a list of (column, weight) pairs.
    Pixel-driven projection has a ripple: with a bin width close to the pixel
    size, a disk projection is off by up to about 10 percent in some bins. A
    bin of about twice the pixel size (nbins = 23 for n = 32) keeps it near
    1 percent.
    """
    xs, ys = pixel_centers(n)
    smax = math.sqrt(2.0)
    width = 2.0 * smax / nbins
    scale = (2.0 / n) ** 2 / width
    rows = []
    for theta in angles:
        c, s = math.cos(theta), math.sin(theta)
        acc = [dict() for _ in range(nbins)]
        for i, y in enumerate(ys):
            for j, x in enumerate(xs):
                t = (x * c + y * s + smax) / width - 0.5
                b0 = math.floor(t)
                frac = t - b0
                col = i * n + j
                for b, w in ((b0, 1.0 - frac), (b0 + 1, frac)):
                    if 0 <= b < nbins and w > 0.0:
                        acc[b][col] = acc[b].get(col, 0.0) + w * scale
        rows.extend(sorted(d.items()) for d in acc)
    return rows


def sp_matvec(rows, x):
    """y = A x for sparse rows of (column, weight) pairs."""
    return [sum(w * x[c] for c, w in row) for row in rows]


def sp_rmatvec(rows, y, ncols):
    """x = A^H y for sparse rows of (column, weight) pairs and ncols columns."""
    out = [0.0] * ncols
    for row, yi in zip(rows, y):
        if yi == 0:
            continue
        for c, w in row:
            out[c] += w.conjugate() * yi
    return out


# ------------------------------------------------------------------ noise


def gauss_noise(rng, shape, sigma):
    """Independent N(0, sigma^2) values: a list for an int shape, an image for (n1, n2)."""
    if isinstance(shape, int):
        return [rng.gauss(0.0, sigma) for _ in range(shape)]
    n1, n2 = shape
    return [[rng.gauss(0.0, sigma) for _ in range(n2)] for _ in range(n1)]


def _poisson_small(rng, lam):
    """Knuth's product method, exact for a mean lam <= 30."""
    limit = math.exp(-lam)
    k, p = 0, rng.random()
    while p > limit:
        k += 1
        p *= rng.random()
    return k


def poisson_sample(rng, lam):
    """An exact Poisson(lam) sample: a sum of Knuth samples with means at most 30."""
    if lam < 0:
        raise ValueError("negative mean")
    total = 0
    while lam > 30.0:
        total += _poisson_small(rng, 30.0)
        lam -= 30.0
    if lam > 0.0:
        total += _poisson_small(rng, lam)
    return total
test_homodyne_reconstruction.py 131 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/homodyne-reconstruction/. The authors are listed in prov/4ZY7XX.jsonl.

import cmath
import math
import random

import pytest

from homodyne_reconstruction import (
    homodyne_1d,
    homodyne_2d,
    homodyne_weights,
    partial_mask,
    signed_freq,
    triangle_window,
    unitary_dft,
    unitary_dft2,
    zero_filled_1d,
)
from imgkit import ellipse_phantom, MODIFIED_SHEPP_LOGAN, pixel_centers


def direct_homodyne(y, k0, kind="step"):
    """The same method with explicit O(n^2) sums instead of the FFT."""
    n = len(y)
    h = homodyne_weights(n, k0, kind)
    t = triangle_window(n, k0)
    s = 1.0 / math.sqrt(n)
    out = []
    for j in range(n):
        z = sum(h[k] * y[k] * cmath.exp(2j * math.pi * j * k / n) for k in range(n)) * s
        low = sum(t[k] * y[k] * cmath.exp(2j * math.pi * j * k / n) for k in range(n)) * s
        out.append(0.0 if low == 0 else (low.conjugate() * z).real / abs(low))
    return out


def masked(y, k0):
    """Keep the acquired samples; put garbage in the missing ones to show they are never read."""
    m = partial_mask(len(y), k0)
    return [v if a else complex(1e6, -1e6) for v, a in zip(y, m)]


def test_filter_sums_to_two():
    for n, k0 in ((8, 1), (16, 3), (32, 0), (32, 14)):
        for kind in ("step", "ramp"):
            h = homodyne_weights(n, k0, kind)
            for k in range(n):
                f = signed_freq(k, n)
                g = (-f) % n
                assert h[k] + h[g] == pytest.approx(2.0, abs=1e-15)


def test_constant_phase_nonnegative_is_exact():
    rng = random.Random(1)
    for n, k0 in ((8, 1), (16, 2), (32, 5), (64, 9)):
        for kind in ("step", "ramp"):
            rho = [rng.uniform(0.0, 2.0) for _ in range(n)]
            phase = cmath.exp(1j * rng.uniform(-math.pi, math.pi))
            y = unitary_dft([phase * r for r in rho])
            out = homodyne_1d(masked(y, k0), k0, kind)
            assert max(abs(a - b) for a, b in zip(out, rho)) < 1e-10


def test_signed_real_image_gives_sign_of_lowres():
    rng = random.Random(2)
    n, k0 = 32, 4
    rho = [rng.uniform(-1.0, 1.0) for _ in range(n)]
    phase = cmath.exp(0.7j)
    y = unitary_dft([phase * r for r in rho])
    out = homodyne_1d(masked(y, k0), k0)
    t = triangle_window(n, k0)
    # Low-resolution real image r = F_u^H T F_u rho by direct sums.
    yr = unitary_dft(rho)
    r = [sum(t[k] * yr[k] * cmath.exp(2j * math.pi * j * k / n) for k in range(n)).real / math.sqrt(n) for j in range(n)]
    for j in range(n):
        if abs(r[j]) > 1e-9:
            assert out[j] == pytest.approx(math.copysign(1.0, r[j]) * rho[j], abs=1e-10)


def test_matches_direct_sums_on_random_data():
    rng = random.Random(3)
    for n, k0 in ((16, 3), (12, 2)):
        y = [complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(n)]
        y = masked(y, k0)
        for kind in ("step", "ramp"):
            a = homodyne_1d(y, k0, kind)
            b = direct_homodyne(y, k0, kind)
            assert max(abs(u - v) for u, v in zip(a, b)) < 1e-9


def test_full_band_limits():
    with pytest.raises(ValueError):
        homodyne_1d([0j] * 8, 3)
    with pytest.raises(ValueError):
        homodyne_1d([0j] * 7, 1)


def phantom_with_phase(n):
    rho = ellipse_phantom(n, MODIFIED_SHEPP_LOGAN)
    xs, ys = pixel_centers(n)
    return rho, [[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)]


def test_2d_smooth_phase_beats_zero_filling():
    n, k0 = 16, 3
    rho, x = phantom_with_phase(n)
    ks = unitary_dft2(x)
    keep = partial_mask(n, k0)
    ks = [ks[a] if keep[a] else [complex(9.0, 9.0)] * n for a in range(n)]
    out = homodyne_2d(ks, k0)
    err_h = math.sqrt(sum((out[i][j] - rho[i][j]) ** 2 for i in range(n) for j in range(n)))
    # Zero filling, column by column, then the magnitude.
    zf = [[0.0] * n for _ in range(n)]
    for j in range(n):
        col = [sum(ks[a][b] * cmath.exp(2j * math.pi * j * b / n) for b in range(n)) / math.sqrt(n) 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)))
    norm = math.sqrt(sum(v * v for row in rho for v in row))
    assert err_h < err_z
    assert err_h / norm < 0.35


def test_2d_constant_phase_exact():
    n, k0 = 16, 2
    rho = ellipse_phantom(n, MODIFIED_SHEPP_LOGAN)
    ks = unitary_dft2([[cmath.exp(-1.1j) * v for v in row] for row in rho])
    out = homodyne_2d(ks, k0, "ramp")
    assert max(abs(out[i][j] - rho[i][j]) for i in range(n) for j in range(n)) < 1e-10

History

Feinberg and colleagues showed in 1986 that conjugate symmetry can halve the scan time. In the same year Margosian, Schmitt and Purdy described a half Fourier method that corrects the phase with a low resolution estimate. Noll, Nishimura and Macovski published the homodyne method in 1991, with a filter that sums to 2 across the center and a phase estimate from the symmetric band. The name refers to homodyne detection in radio, where a signal is demodulated with a reference of the same frequency and phase. POCS, published by Haacke, Lindskog and Lin in the same year, is its iterative relative.

References

  1. Douglas C. Noll, Dwight G. Nishimura and Albert Macovski, Homodyne detection in magnetic resonance imaging, IEEE Transactions on Medical Imaging 10(2), 1991, 154 to 163, the homodyne weighting of the asymmetric data, the phase estimate from the symmetric low frequency band, and the real part after phase removal (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
  3. Paul Margosian, F. Schmitt and D. E. Purdy, Faster MR imaging: imaging with half the data, Health Care Instrumentation 1, 1986, pages 195 to 197, the earlier half Fourier method with a low resolution phase correction (general locator)
  4. David A. Feinberg, John D. Hale, John C. Watts, Leon Kaufman and Alexander Mark, Halving MR imaging time by conjugation, demonstration at 3.5 kG, Radiology 161(2), 1986, 527 to 531, the use of conjugate symmetry to halve the number of phase encoding steps (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.

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
  • a scene preset for the example