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
- Model
- Real RAM
- Properties
- deterministicnot exactnot in placeoffline
- Evidence
- Proof sketchCode in 1 languages
- 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 along the phase encoding axis, in DFT order with frequencies , and the number with . The data are for the acquired frequencies , where is the unitary DFT (, see mri-signal-equation). The fraction of acquired samples is , for example 5/8 or 3/4. The output is a real image . The model is with real and smooth. 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
is the unitary inverse DFT, computed with an FFT.
HOMODYNE(y, n, k0) ▷ y known for f = -n/2 .. k0- 1
H(f) <- 0 if f > k0; 1 if |f| <= k0 or f = -n/2; 2 otherwise - 2
T(f) <- 1 - |f|/(k0 + 1) if |f| <= k0; 0 otherwise - 3
z <- F_u^H (H y) ▷ the weighted image - 4
l <- F_u^H (T y) ▷ the low resolution image - 5
for each pixel j do - 6
if l_j = 0 then rho_j <- 0 - 7
else rho_j <- Re(conj(l_j) z_j / |l_j|) - 8
return rho
Line L1 is the homodyne filter. The two values of a pair always sum to 2: the band is measured on both sides and gets 1 on each side, an unpaired frequency gets 2 and its missing partner gets 0, and the Nyquist frequency 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 and 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, for . It also sums to 2 across the center and gives less ringing at the edges of the band.
Example
Take , , the real profile and the constant phase rad. The scan acquires , which is 6 of 8 samples, and misses . Line L1 gives in DFT order (frequencies ) and line L2 gives . The table shows each pixel with the phase taken out of and , rounded to 3 places.
| pixel | zero filled | output | |||
|---|---|---|---|---|---|
| 0 | 0 | 0.663 | 0.646 | 0 | |
| 1 | 0 | 0.541 | 1.500 | 0 | |
| 2 | 4 | 3.870 | 2.354 | 4 | |
| 3 | 4 | 3.707 | 2.707 | 4 | |
| 4 | 4 | 3.870 | 2.354 | 4 | |
| 5 | 0 | 0.541 | 1.500 | 0 | |
| 6 | 0 | 0.663 | 0.646 | 0 | |
| 7 | 0 | 0.707 | 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 . The weighted image 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 exactly.
Correctness
The key fact is the sum rule . Write ; then is odd. For a real profile , the DFT is Hermitian, , so is anti-Hermitian and its inverse DFT is purely imaginary. Hence with real. The window is real and even, so with real, and is smoothed by the Fejér kernel, which is nonnegative. Line L7 then returns , which is when . The proof gives the details. This is a theorem about the model with a constant ; 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 , and is the unitary DFT, . Frequencies are taken modulo and written in . The scan acquires the set with . The filter of line L1 is real, is for , and satisfies
The step filter and the ramp filter both satisfy (1): for the step filter gives and the ramp gives ; for the pair is ; and is its own negative modulo , with . The window of line L2 is for and otherwise.
Theorem. Let with a constant and a real vector , and let for . Let . Then is real, and the output of HOMODYNE is where and where . If , then .
Lemma 1. Let be a sequence on the frequencies with for all . Then is real. If instead for all , then is purely imaginary.
Proof. Write , so . Then
after the change of index , which is a bijection modulo . In the first case , so . In the second case , so .
Lemma 2. For and , the value is positive.
Proof. The product is a pointwise product in frequency, so is the periodic convolution with the kernel . For , the number of pairs with and is , so . The frequencies are distinct modulo because . Hence
the discrete Fejér kernel, with . All terms of are then nonnegative, and .
Proof of the theorem. Put . Because is real, . By linearity for .
First, lines L3 and L4 read only on : for , and for . So and as full sequences.
The window. is real and even, so satisfies . By Lemma 1, is real, and line L4 gives .
The filter. Write with . By (1), , so is real and odd. The sequence satisfies . By Lemma 1, is purely imaginary; write with real. Since , line L3 gives
Lines L5 to L7. If , then and line L6 returns . Otherwise and
whose real part, kept by line L7, is . This is the first claim.
If : where , Lemma 2 gives and the output is . Where , the output is or, if , the value of line L6. In both cases the output is .
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 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 is only an estimate of the phase of , and the output is an approximation. The theorem gives no error bound in that case.
Complexity
Each line costs two inverse DFTs of length and other operations: with an FFT when is a power of two, and with a direct DFT. An image needs one inverse DFT along the readout for each of the k-space lines and one homodyne step for each of the columns, in total in the real RAM. The memory holds and , numbers per line. The method is not iterative.
Properties
- Exact for a constant phase. For with the output is (theorem). With a signed real , the output is multiplied by the sign of its smoothed version.
- Approximate for a smooth phase. On a modified Shepp-Logan phantom with the phase rad on 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 .
- One pass. No iteration and no parameter other than 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 in line L4. A nonnegative kernel, such as the triangle here, keeps the sign of 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 , 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 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 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 , the result is , and the error 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 , 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.
# 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
- 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)
- 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
- 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)
- 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.
| 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 4ZY7XX Edit this page History Report an error Markdown