Algorithm Search⌘K

Algorithmadvanced

Conjugate phase reconstruction

Also called off-resonance correction by conjugate phase.

Reconstructs each pixel by weighting every k-space sample with its density weight and the conjugate of its predicted phase, field map term included: the adjoint of the signal model.

Time
O(m N) worst
Space
O(1) extra
Where
N = the number of pixels; m = the number of k-space samples
Properties
deterministicnot exactnot in placeoffline
Origin
Akira Maeda, Koichi Sano, Tetsuo Yokoyama, 1988

Conjugate phase reconstruction makes an MR image from samples anywhere in k-space, and it can correct the blur and shift that an uneven magnetic field causes. For each pixel it multiplies every sample by its density weight and by the conjugate of the phase that the signal equation predicts for that pixel at that sample, and adds the products. With a field map, the predicted phase includes the extra precession ω(r) t\omega(r)\, t of the pixel at the time of the sample. In matrix form the result is AHWsA^H W s, the adjoint of the signal model applied to the weighted data. Maeda, Sano and Yokoyama described the weighted correlation in 1988, and Noll and colleagues added the field map in 1991. The method is exact on a full Cartesian grid with a constant field; this page proves it. For a field that varies it is an approximation, and a least squares solution of the full model, as in CG-SENSE, gives the exact answer for data without noise when the model matrix has full column rank.

In plain words

Each measurement of the scanner mixes the signal of every pixel. Each pixel enters the mix with a known turn, which depends on where the pixel is and, if the magnet is not perfectly even, on how fast that pixel spins. To get back one pixel, the method turns every measurement back by the turn that this pixel would have given it, and adds them up. The signal of that pixel then adds up in step, while the signals of the other pixels point in many directions and mostly cancel.

Measurements that sit close together in the frequency plane get less weight, so that crowded places do not count too much.

The problem

The input is a set of mm samples sjs_j at k-space positions kjk_j (cycles per unit length) and times tjt_j after excitation, the density weights wjw_j (for example from density compensation), the pixel positions rir_i, and a field map ωi\omega_i in rad/s at each pixel. The signal model for one coil, without relaxation during the readout, is

sj=∑ixi e−iωitj e−2πi kj⋅ri,s=Ax,s_j = \sum_i x_i\, e^{-i \omega_i t_j}\, e^{-2\pi i\, k_j \cdot r_i}, \qquad s = A x,

the discrete signal equation with an off-resonance term. The sign is that of the forward DFT. The output is an image x^\hat x that approximates xx.

The algorithm

  1. CONJUGATE-PHASE(s, k, t, w, r, omega)
  2. 1for each pixel i do
  3. 2acc <- 0
  4. 3for each sample j do
  5. 4acc <- acc + w_j s_j exp(+i 2 pi k_j . r_i) exp(+i omega_i t_j)
  6. 5xhat_i <- acc
  7. 6return xhat

Line L4 removes, for pixel ii, the phase of both encodings: the spatial phase 2πkj⋅ri2\pi k_j \cdot r_i and the off-resonance phase ωitj\omega_i t_j. With ω=0\omega = 0 the method is the adjoint nonuniform DFT with density weights, which gridding approximates. The double loop is the direct method; gridding with a nonuniform FFT and a split of the field into a few frequency bins or time segments makes it fast.

Example

Take a 16×1616 \times 16 image that is 1 inside the disk ∣r∣<0.84⋅8|r| < 0.84 \cdot 8 pixels and 0 outside. The field is a Gaussian bump with a peak of 40 Hz at the pixel (2.67,−2)(2.67, -2) and a width of 4 pixels. The scan is a full Cartesian grid read in echo planar order, line by line with alternating direction, with an echo spacing of 0.5 ms and a dwell time of 4 microseconds. The last sample comes 7.56 ms after the first, so the largest off-resonance phase is 1.89 rad. The weights are wj=1/256w_j = 1/256. The relative errors were as follows (measurement with the code of this page).

reconstruction complex error magnitude error
without the field map (ω=0\omega = 0 in line L4) 0.54 0.0645
conjugate phase with the field map 0.0373 0.0345

The uncorrected image has the wrong phase in the region of the bump and is shifted along the phase encoding axis, where the time between samples is long. The conjugate phase image is close to the true disk. The rest of the error comes from the change of the field across the point spread function.

Correctness

Line L4 adds Aji‾ wjsj\overline{A_{ji}}\, w_j s_j, so the output is x^=AHWs\hat x = A^H W s, and with data s=Axs = A x the output is PxP x with P=AHWAP = A^H W A. The proof shows:

  • The method is exact for every image if and only if P=IP = I.
  • On a full Cartesian n×nn \times n grid with wj=1/n2w_j = 1/n^2 and no field, P=IP = I: the method is the inverse DFT.
  • A constant field cancels in PP, so the method is exact for a constant field with any sample times.
  • The field enters PP only through the differences ωi−ωi′\omega_i - \omega_{i'}.

The key invariant is that the output equals PxP x, the true image seen through the point spread function. For a field that varies, PP is not the identity. The quality then depends on how much the field changes across the width of the point spread function; this is a heuristic, and the example gives a measurement.

Proof: When conjugate phase reconstruction is exactfull

The setting is that of the algorithm. The image has NN pixels at positions r1,…,rNr_1, \ldots, r_N, with the values xix_i and the off-resonance frequencies ωi\omega_i (rad/s). The scan has mm samples at the k-space positions kjk_j and the times tjt_j, with the density weights wj>0w_j > 0. The signal model is s=Axs = A x with

Aji=e−iωitj e−2πi kj⋅ri.A_{ji} = e^{-i \omega_i t_j}\, e^{-2\pi i\, k_j \cdot r_i}.

Write W=diag⁡(w1,…,wm)W = \operatorname{diag}(w_1, \ldots, w_m).

Lemma 1 (the algorithm computes the adjoint). The output of CONJUGATE-PHASE is x^=AHWs\hat x = A^H W s.

Proof. Line L4 adds wjsje+2πi kj⋅rie+iωitj=Aji‾ wjsjw_j s_j e^{+2\pi i\, k_j \cdot r_i} e^{+i \omega_i t_j} = \overline{A_{ji}}\, w_j s_j for each sample jj, and lines L1 to L5 do this for each pixel ii. So x^i=∑jAji‾ wjsj=(AHWs)i\hat x_i = \sum_j \overline{A_{ji}}\, w_j s_j = (A^H W s)_i. □\square

Theorem 1 (exactness). Let P=AHWAP = A^H W A. For data s=Axs = A x without noise, x^=Px\hat x = P x. Hence the method returns xx for every image xx if and only if P=IP = I. The entries of PP are

Pii′=∑j=1mwj e2πi kj⋅(ri−ri′) ei(ωi−ωi′)tj.(1)P_{i i'} = \sum_{j=1}^{m} w_j\, e^{2\pi i\, k_j \cdot (r_i - r_{i'})}\, e^{i (\omega_i - \omega_{i'}) t_j}. \tag{1}

Proof. By Lemma 1, x^=AHWAx=Px\hat x = A^H W A x = P x. If P=IP = I, then x^=x\hat x = x. If x^=x\hat x = x for every xx, take xx to be each unit vector in turn; the columns of PP are then the columns of II. Equation (1) is the product ∑jAji‾ wjAji′\sum_j \overline{A_{ji}}\, w_j A_{j i'} written out. □\square

Column i′i' of PP is the point spread function: the image that the method returns for a single point at ri′r_{i'}.

Theorem 2 (full Cartesian grid, no field). Let the image be an n×nn \times n grid with ri∈{−n/2,…,n/2−1}2r_i \in \{-n/2, \ldots, n/2 - 1\}^2 in pixel units, let the samples be the n2n^2 points kj=(u,v)/nk_j = (u, v)/n with u,v∈{−n/2,…,n/2−1}u, v \in \{-n/2, \ldots, n/2 - 1\}, each once, in any order and at any times, let wj=1/n2w_j = 1/n^2 and let ωi=0\omega_i = 0. Then P=IP = I.

Proof. With ω=0\omega = 0, equation (1) gives Pii′=n−2∑u∑ve2πi(ua+vb)/nP_{i i'} = n^{-2} \sum_{u} \sum_{v} e^{2\pi i (u a + v b)/n}, where (a,b)=ri−ri′(a, b) = r_i - r_{i'} has integer entries with ∣a∣,∣b∣<n|a|, |b| < n. The double sum is the product of ∑ue2πiua/n\sum_u e^{2\pi i u a/n} and ∑ve2πivb/n\sum_v e^{2\pi i v b/n}. Each factor is a sum of nn consecutive powers of the root of unity e2πia/ne^{2\pi i a/n}. It equals nn if a=0a = 0, and otherwise e2πia/n≠1e^{2\pi i a/n} \ne 1 because 0<∣a∣<n0 < |a| < n, so the geometric sum is e−πia (e2πia−1)/(e2πia/n−1)=0e^{-\pi i a}\,(e^{2\pi i a} - 1)/(e^{2\pi i a/n} - 1) = 0. So Pii′=1P_{i i'} = 1 if ri=ri′r_i = r_{i'} and 00 otherwise. □\square

Theorem 3 (a constant field). If ωi=ω0\omega_i = \omega_0 for all ii, then PP does not depend on ω0\omega_0 or on the times tjt_j. In particular, under the sampling of Theorem 2 with any constant field and any sample times, P=IP = I.

Proof. In equation (1), ωi−ωi′=0\omega_i - \omega_{i'} = 0, so the last factor is 1 for every jj, and (1) reduces to the case ω=0\omega = 0. Theorem 2 then gives P=IP = I. ■\blacksquare

Remarks.

  • Equation (1) shows that the field enters PP only through the differences ωi−ωi′\omega_i - \omega_{i'}. When the field is nearly constant over the region where the point spread function without field is large, the entries of PP near the diagonal are close to those without field. This is why the method works well for smooth fields. It is a heuristic argument, not a bound; the page gives measured errors.
  • For a field that varies, P≠IP \ne I in general, and the exact answer is the solution of Ax=sA x = s in the least squares sense, for example by the conjugate gradient method. The tests compare both.
  • A constant field still matters for the uncorrected image: with the weights of Theorem 2 but the correction left out, the output is A0HWAxA_0^H W A x with A0A_0 the matrix for ω=0\omega = 0. Each sample then carries the extra phase e−iω0tje^{-i \omega_0 t_j}, which shifts and blurs the image along the direction in which tjt_j grows.

Complexity

The direct method computes mm complex exponentials per pixel, O(mN)O(m N) operations for NN pixels in the real RAM, and needs O(1)O(1) memory beyond the input and the output. For N=n2N = n^2 pixels and m=n2m = n^2 samples this is O(n4)O(n^4). Gridding with a nonuniform FFT costs O(m+Nlog⁡N)O(m + N \log N) without a field. With the field split into LL frequency bins or time segments, the cost is O(L(m+Nlog⁡N))O(L (m + N \log N)), and the error depends on LL.

Properties

  • Linear. The output is linear in the data.
  • Adjoint of the model. x^=AHWs\hat x = A^H W s (theorem). With W=IW = I it is the adjoint used inside iterative solvers.
  • Exact cases. Full Cartesian sampling with w=1/n2w = 1/n^2 and a constant field (theorem).
  • Approximate for a varying field. On the example the complex error fell from 0.54 to 0.037 (measurement). The error grows with the field gradient and the readout time.
  • No iteration. One pass, with no parameter other than the weights and the field map.

Variants and improvements

  • Without a field map. With ω=0\omega = 0 it is the weighted adjoint nonuniform DFT, the basis of gridding for radial and spiral data.
  • Fast approximations. The phase eiωitje^{i \omega_i t_j} is approximated by a sum of a few terms that separate in ii and jj, by time segmentation or by frequency segmentation. Each term needs one gridding step.
  • Least squares. Solve min⁡x∥Ax−s∥2\min_x \|A x - s\|^2, often with a penalty, by the conjugate gradient method. Sutton, Noll and Fessler (2003) used a time segmented model with the nonuniform FFT. This removes the approximation of P≈IP \approx I at the cost of several applications of AA and AHA^H.
  • Field map estimation. The map ω\omega comes from the phase difference of two images at different echo times, divided by the echo time difference, often after phase unwrapping.

When to use it

Use conjugate phase reconstruction for spiral and echo planar images with a known field map when a fast, non-iterative correction is enough, and as the first step or the adjoint inside iterative methods. When the field changes fast, for example near air-tissue boundaries, or when the error must be small, use least squares with the full model. The field map must be accurate; an error of δω\delta\omega leaves a phase error of δω tj\delta\omega\, t_j.

Pitfalls

  • Wrong sign of the phase. If line L4 uses e−iωitje^{-i \omega_i t_j}, the correction doubles the off-resonance phase instead of removing it. The same holds for the spatial term, where a sign flip mirrors the image. Scanners and books use both sign conventions.
  • Times from the wrong origin. The times tjt_j in line L4 must be measured from the same origin as in the field map, usually the echo time or the start of the readout. A shift adds a constant phase per pixel.
  • No density weights. If line L4 uses wj=1w_j = 1 for a radial or spiral trajectory, the center of k-space counts too much and the image is blurred.
  • Large field gradients. Where the field changes fast, the point spread function is not narrow, and the method leaves blur and signal loss.
  • Cost of the direct sum. The double loop of lines L1 and L3 is O(mN)O(m N); for a 256×256256 \times 256 image with as many samples it needs about 4×1094 \times 10^9 exponentials.

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.

conjugate_phase_reconstruction.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/conjugate-phase-reconstruction/. The authors are listed in prov/ES8X47.jsonl.

"""Conjugate phase reconstruction with off-resonance correction.

Signal model (single coil, no relaxation during the readout): sample j at
k-space position k_j (cycles per unit length) and time t_j (seconds) is
    s_j = sum_i x_i exp(-i omega_i t_j) exp(-i 2 pi k_j . r_i),
where pixel i sits at r_i and has off-resonance frequency omega_i (rad/s).
Write this as s = A x.

Conjugate phase reconstruction undoes both phase terms at each pixel and
weights each sample by its density compensation weight w_j:
    xhat_i = sum_j w_j s_j exp(+i 2 pi k_j . r_i) exp(+i omega_i t_j),
that is xhat = A^H W s. It is exact when A^H W A = I, for example on a
full Cartesian grid with w_j = 1 / m and a constant omega. Otherwise it is
an approximation: it ignores the change of omega inside the support of the
point spread function.

Cost: O(m n) complex exponentials for m samples and n pixels.
"""

import cmath
import math
from typing import Sequence

Vec = Sequence[float]


def forward(x: Sequence[complex], pos: Sequence[Vec], omega: Sequence[float], ks: Sequence[Vec], ts: Sequence[float]) -> list[complex]:
    """s = A x, the signal of image x with field map omega at samples (ks, ts)."""
    out = []
    for k, t in zip(ks, ts):
        acc = 0j
        for xi, r, om in zip(x, pos, omega):
            ph = -om * t - 2.0 * math.pi * sum(a * b for a, b in zip(k, r))
            acc += xi * cmath.exp(1j * ph)
        out.append(acc)
    return out


def conjugate_phase(
    s: Sequence[complex],
    ks: Sequence[Vec],
    ts: Sequence[float],
    w: Sequence[float],
    pos: Sequence[Vec],
    omega: Sequence[float],
) -> list[complex]:
    """xhat = A^H W s: the conjugate phase image at the pixel positions pos."""
    xhat = []
    for r, om in zip(pos, omega):  # @line L1
        acc = 0j  # @line L2
        for sj, k, t, wj in zip(s, ks, ts, w):  # @line L3
            ph = 2.0 * math.pi * sum(a * b for a, b in zip(k, r)) + om * t
            acc += wj * sj * cmath.exp(1j * ph)  # @line L4
        xhat.append(acc)  # @line L5
    return xhat  # @line L6


def pixel_grid(n: int) -> list[tuple[float, float]]:
    """Pixel positions (column, row) - n/2 in pixel units, row-major, for an n x n image."""
    return [(c - n // 2, a - n // 2) for a in range(n) for c in range(n)]


def epi_cartesian(n: int, fov: float, esp: float = 5e-4, dwell: float = 4e-6, t0: float = 0.0):
    """A full n x n Cartesian k-space grid in EPI order and its sample times.

    k = (u, v) / fov with u, v in -n/2 .. n/2 - 1; with pixel_grid positions,
    fov = n gives the DFT grid. Line v is read at
    t0 + (v + n/2) esp, and sample u of a line adds (u + n/2) dwell. The
    readout direction alternates line by line, as in EPI. Returns (ks, ts).
    """
    ks, ts = [], []
    for li, v in enumerate(range(-n // 2, n // 2)):
        us = list(range(-n // 2, n // 2))
        if li % 2:
            us.reverse()
        for q, u in enumerate(us):
            ks.append((u / fov, v / fov))
            ts.append(t0 + li * esp + q * dwell)
    return ks, ts
imgla.py 259 lines
# SPDX-License-Identifier: MIT
# Shared helper of the imaging and inverse problems pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Dense linear algebra on lists of rows (float, complex or Fraction entries).

A matrix is a list of rows. A vector is a list of numbers. The inner product
is <u, v> = sum_i conj(u_i) v_i, linear in the second argument, so that the
adjoint A^H satisfies <A x, y> = <x, A^H y>.
"""

import math


def _flat(x):
    """Flatten a list of rows (an image) into one list; a vector is returned as is."""
    if x and isinstance(x[0], (list, tuple)):
        return [v for row in x for v in row]
    return x


def zeros(m, n):
    """The m x n zero matrix."""
    return [[0.0] * n for _ in range(m)]


def eye(n):
    """The n x n identity matrix."""
    out = zeros(n, n)
    for i in range(n):
        out[i][i] = 1.0
    return out


def transpose(a):
    """A^T."""
    return [list(col) for col in zip(*a)]


def conj_transpose(a):
    """A^H, the conjugate transpose."""
    return [[v.conjugate() for v in col] for col in zip(*a)]


def matmul(a, b):
    """The product A B."""
    bt = list(zip(*b))
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def matvec(a, x):
    """The product A x."""
    return [sum(v * w for v, w in zip(row, x)) for row in a]


def rmatvec(a, y):
    """The product A^H y."""
    n = len(a[0]) if a else 0
    out = [0.0] * n
    for row, yi in zip(a, y):
        if yi == 0:
            continue
        for j, v in enumerate(row):
            out[j] += v.conjugate() * yi
    return out


def dot(u, v):
    """<u, v> = sum_i conj(u_i) v_i. Images (lists of rows) are flattened."""
    return sum(a.conjugate() * b for a, b in zip(_flat(u), _flat(v)))


def norm2(x):
    """The Euclidean norm. Images (lists of rows) are flattened."""
    return math.sqrt(sum(abs(v) ** 2 for v in _flat(x)))


def solve(a, b):
    """Solve A x = b by Gaussian elimination with partial pivoting.

    b is a vector or a matrix (a list of rows). A must be square and
    nonsingular; a zero pivot raises ValueError. Fractions stay exact.
    """
    n = len(a)
    vec = not (b and isinstance(b[0], (list, tuple)))
    rhs = [[bi] for bi in b] if vec else [list(r) for r in b]
    m = [list(row) + rhs[i] for i, row in enumerate(a)]
    w = len(m[0])
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(m[r][c]))
        if m[p][c] == 0:
            raise ValueError("singular matrix")
        m[c], m[p] = m[p], m[c]
        piv = m[c][c]
        for r in range(c + 1, n):
            f = m[r][c] / piv
            if f != 0:
                mr, mc = m[r], m[c]
                for j in range(c, w):
                    mr[j] -= f * mc[j]
    x = [[0.0] * (w - n) for _ in range(n)]
    for r in range(n - 1, -1, -1):
        for j in range(w - n):
            s = m[r][n + j] - sum(m[r][k] * x[k][j] for k in range(r + 1, n))
            x[r][j] = s / m[r][r]
    return [row[0] for row in x] if vec else x


def cholesky(a):
    """Lower triangular L with A = L L^H for a Hermitian positive definite A."""
    n = len(a)
    low = zeros(n, n)
    for j in range(n):
        d = a[j][j] - sum(abs(low[j][k]) ** 2 for k in range(j))
        d = d.real if isinstance(d, complex) else d
        if not d > 0:
            raise ValueError("matrix is not positive definite")
        ljj = math.sqrt(d)
        low[j][j] = ljj
        for i in range(j + 1, n):
            s = a[i][j] - sum(low[i][k] * low[j][k].conjugate() for k in range(j))
            low[i][j] = s / ljj
    return low


def cho_solve(low, b):
    """Solve (L L^H) x = b, with L from cholesky."""
    n = len(low)
    z = [0.0] * n
    for i in range(n):
        z[i] = (b[i] - sum(low[i][k] * z[k] for k in range(i))) / low[i][i]
    x = [0.0] * n
    for i in range(n - 1, -1, -1):
        s = z[i] - sum(low[k][i].conjugate() * x[k] for k in range(i + 1, n))
        x[i] = s / low[i][i].conjugate()
    return x


def _rot_params(app, aqq, apq):
    """c, s of the Jacobi rotation that zeroes the (p, q) entry of [[app, apq], [apq, aqq]]."""
    theta = (aqq - app) / (2.0 * apq)
    t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
    c = 1.0 / math.sqrt(1.0 + t * t)
    return c, c * t


def sym_eig(a, tol=1e-15, max_sweeps=100):
    """Eigenvalues (ascending) and eigenvectors (as columns) of a real symmetric matrix.

    Cyclic Jacobi method. Returns (w, Q) with A = Q diag(w) Q^T.
    """
    n = len(a)
    m = [[float(v) for v in row] for row in a]
    q = eye(n)
    for _ in range(max_sweeps):
        off = sum(m[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
        scale = sum(m[i][i] ** 2 for i in range(n)) + off
        if off <= (tol * tol) * scale or off == 0.0:
            break
        for p in range(n - 1):
            for r in range(p + 1, n):
                apq = m[p][r]
                if apq == 0.0:
                    continue
                c, s = _rot_params(m[p][p], m[r][r], apq)
                for k in range(n):
                    mkp, mkr = m[k][p], m[k][r]
                    m[k][p] = c * mkp - s * mkr
                    m[k][r] = s * mkp + c * mkr
                mp, mr = m[p], m[r]
                for k in range(n):
                    mpk, mrk = mp[k], mr[k]
                    mp[k] = c * mpk - s * mrk
                    mr[k] = s * mpk + c * mrk
                m[p][r] = m[r][p] = 0.0
                for k in range(n):
                    qkp, qkr = q[k][p], q[k][r]
                    q[k][p] = c * qkp - s * qkr
                    q[k][r] = s * qkp + c * qkr
    order = sorted(range(n), key=lambda i: m[i][i])
    w = [m[i][i] for i in order]
    qs = [[q[k][i] for i in order] for k in range(n)]
    return w, qs


def _complete(cols, m):
    """Replace zero columns of an m-row column list by unit vectors orthogonal to the others."""
    for idx, col in enumerate(cols):
        if any(v != 0.0 for v in col):
            continue
        for e in range(m):
            cand = [0.0] * m
            cand[e] = 1.0
            for _ in range(2):
                for jdx, other in enumerate(cols):
                    if jdx == idx or not any(v != 0.0 for v in other):
                        continue
                    h = sum(a * b for a, b in zip(other, cand))
                    cand = [a - h * b for a, b in zip(cand, other)]
            nrm = math.sqrt(sum(v * v for v in cand))
            if nrm > 0.5:
                cols[idx] = [v / nrm for v in cand]
                break
    return cols


def svd(a, tol=1e-15, max_sweeps=100):
    """Thin SVD of a real m x n matrix by one-sided Jacobi (Hestenes).

    Returns (U, S, V) with p = min(m, n): U is m x p, S a list of p values in
    descending order, V is n x p, U^T U = I, V^T V = I and A = U diag(S) V^T.
    """
    m, n = len(a), len(a[0])
    if m < n:
        v, s, u = svd(transpose(a), tol, max_sweeps)
        return u, s, v
    cols = [[float(a[i][j]) for i in range(m)] for j in range(n)]
    vcols = [[1.0 if i == j else 0.0 for i in range(n)] for j in range(n)]
    for _ in range(max_sweeps):
        rotated = False
        for p in range(n - 1):
            for r in range(p + 1, n):
                cp, cr = cols[p], cols[r]
                alpha = sum(x * x for x in cp)
                beta = sum(x * x for x in cr)
                gamma = sum(x * y for x, y in zip(cp, cr))
                if gamma == 0.0 or abs(gamma) <= tol * math.sqrt(alpha * beta):
                    continue
                rotated = True
                c, s = _rot_params(alpha, beta, gamma)
                cols[p] = [c * x - s * y for x, y in zip(cp, cr)]
                cols[r] = [s * x + c * y for x, y in zip(cp, cr)]
                vp, vr = vcols[p], vcols[r]
                vcols[p] = [c * x - s * y for x, y in zip(vp, vr)]
                vcols[r] = [s * x + c * y for x, y in zip(vp, vr)]
        if not rotated:
            break
    sig = [math.sqrt(sum(x * x for x in col)) for col in cols]
    # A column below 1e-150 times the largest one is zero to working precision;
    # its squares underflow, so its direction carries no information.
    floor = max(sig) * 1e-150 if sig else 0.0
    sig = [t if t > floor and t > 1e-150 else 0.0 for t in sig]
    order = sorted(range(n), key=lambda j: -sig[j])
    s_out = [sig[j] for j in order]
    ucols = [[x / sig[j] for x in cols[j]] if sig[j] > 0.0 else [0.0] * m for j in order]
    ucols = _complete(ucols, m)
    u = [[ucols[j][i] for j in range(n)] for i in range(m)]
    v = [[vcols[j][i] for j in order] for i in range(n)]
    return u, s_out, v


def adjoint_gap(apply_a, apply_ah, x, y):
    """|<A x, y> - <x, A^H y>| / (||A x|| ||y||) for given functions A and A^H.

    x and y may be vectors or images (lists of rows). If the denominator is
    zero, the absolute gap is returned.
    """
    ax = apply_a(x)
    gap = abs(dot(ax, y) - dot(x, apply_ah(y)))
    den = norm2(ax) * norm2(y)
    return gap / den if den > 0.0 else gap
test_conjugate_phase_reconstruction.py 118 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/conjugate-phase-reconstruction/. The authors are listed in prov/ES8X47.jsonl.

import cmath
import math
import random

from conjugate_phase_reconstruction import conjugate_phase, epi_cartesian, forward, pixel_grid
from imgla import adjoint_gap, solve


def rel_err(a, b):
    return math.sqrt(sum(abs(u - v) ** 2 for u, v in zip(a, b))) / math.sqrt(sum(abs(v) ** 2 for v in b))


def disk(n):
    return [1.0 if (c / (n / 2)) ** 2 + (a / (n / 2)) ** 2 < 0.7 else 0.0 for c, a in pixel_grid(n)]


def smooth_field(n, hz):
    return [2 * math.pi * hz * math.exp(-((c - n / 6) ** 2 + (a + n / 8) ** 2) / (2 * (n / 4) ** 2)) for c, a in pixel_grid(n)]


def test_adjoint_of_forward_model():
    rng = random.Random(21)
    n = 6
    pos = pixel_grid(n)
    omega = [rng.uniform(-200, 200) for _ in pos]
    ks = [(rng.uniform(-0.5, 0.5), rng.uniform(-0.5, 0.5)) for _ in range(40)]
    ts = [rng.uniform(0, 0.01) for _ in ks]
    x = [complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in pos]
    y = [complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in ks]

    def a(v):
        return forward(v, pos, omega, ks, ts)

    def ah(v):
        return conjugate_phase(v, ks, ts, [1.0] * len(ks), pos, omega)

    assert adjoint_gap(a, ah, x, y) < 1e-12


def test_full_cartesian_without_field_is_inverse_dft():
    rng = random.Random(22)
    n = 8
    pos = pixel_grid(n)
    x = [complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in pos]
    ks, ts = epi_cartesian(n, float(n))
    zero = [0.0] * len(pos)
    s = forward(x, pos, zero, ks, ts)
    out = conjugate_phase(s, ks, ts, [1.0 / len(ks)] * len(ks), pos, zero)
    assert rel_err(out, x) < 1e-12


def test_constant_field_is_exact():
    rng = random.Random(23)
    n = 8
    pos = pixel_grid(n)
    x = [complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in pos]
    ks, ts = epi_cartesian(n, float(n), esp=6e-4)
    omega = [2 * math.pi * 75.0] * len(pos)
    s = forward(x, pos, omega, ks, ts)
    out = conjugate_phase(s, ks, ts, [1.0 / len(ks)] * len(ks), pos, omega)
    assert rel_err(out, x) < 1e-12
    # Without the correction the same data give a different image.
    plain = conjugate_phase(s, ks, ts, [1.0 / len(ks)] * len(ks), pos, [0.0] * len(pos))
    assert rel_err(plain, x) > 0.5


def test_smooth_field_map_epi():
    n = 16
    pos = pixel_grid(n)
    x = disk(n)
    omega = smooth_field(n, 40.0)
    ks, ts = epi_cartesian(n, float(n))
    s = forward(x, pos, omega, ks, ts)
    w = [1.0 / len(ks)] * len(ks)
    cp = conjugate_phase(s, ks, ts, w, pos, omega)
    plain = conjugate_phase(s, ks, ts, w, pos, [0.0] * len(pos))
    assert rel_err(cp, x) < 0.06
    assert rel_err(cp, x) < 0.1 * rel_err(plain, x)
    mag_cp = rel_err([abs(v) for v in cp], x)
    mag_plain = rel_err([abs(v) for v in plain], x)
    assert mag_cp < mag_plain


def test_exact_solve_beats_conjugate_phase():
    n = 8
    pos = pixel_grid(n)
    x = disk(n)
    omega = smooth_field(n, 60.0)
    ks, ts = epi_cartesian(n, float(n), esp=8e-4)
    s = forward(x, pos, omega, ks, ts)
    # The square system A x = s, built column by column from unit images.
    m = len(ks)
    cols = []
    for i in range(len(pos)):
        e = [0.0] * len(pos)
        e[i] = 1.0
        cols.append(forward(e, pos, omega, ks, ts))
    a = [[cols[i][j] for i in range(len(pos))] for j in range(m)]
    exact = solve(a, s)
    assert rel_err(exact, x) < 1e-9
    cp = conjugate_phase(s, ks, ts, [1.0 / m] * m, pos, omega)
    e_cp = rel_err(cp, x)
    assert 1e-4 < e_cp < 0.1


def test_phase_of_sample_matches_model():
    # One pixel at r with field omega: s_j = exp(-i (omega t_j + 2 pi k_j . r)).
    pos = [(1.5, -2.0)]
    omega = [300.0]
    ks = [(0.1, 0.2), (-0.3, 0.05)]
    ts = [0.001, 0.004]
    s = forward([1.0], pos, omega, ks, ts)
    for sj, k, t in zip(s, ks, ts):
        want = cmath.exp(-1j * (300.0 * t + 2 * math.pi * (k[0] * 1.5 - k[1] * 2.0)))
        assert abs(sj - want) < 1e-14

History

Maeda, Sano and Yokoyama (1988) reconstructed MR data from time-varying gradients by correlating the data with the expected signal of each pixel. Noll, Meyer, Pauly, Nishimura and Macovski (1991) used the field map in the same correlation to correct off-resonance for spiral and other time-varying gradients. Sutton, Noll and Fessler (2003) replaced the correction by an iterative least squares solution with a fast approximation of the model. Fessler (2010) reviews model-based reconstruction for MRI, which uses the same system matrix.

References

  1. Akira Maeda, Koichi Sano and Tetsuo Yokoyama, Reconstruction by weighted correlation for MRI with time-varying gradients, IEEE Transactions on Medical Imaging 7(1), 1988, 26 to 31, the reconstruction of each pixel by correlation of the data with its expected signal (general locator)
  2. Douglas C. Noll, Craig H. Meyer, John M. Pauly, Dwight G. Nishimura and Albert Macovski, A homogeneity correction method for magnetic resonance imaging with time-varying gradients, IEEE Transactions on Medical Imaging 10(4), 1991, 629 to 637, the conjugate phase correction of off-resonance with a field map for time-varying gradients (general locator)
  3. Bradley P. Sutton, Douglas C. Noll and Jeffrey A. Fessler, Fast, iterative image reconstruction for MRI in the presence of field inhomogeneities, IEEE Transactions on Medical Imaging 22(2), 2003, 178 to 188, the least squares alternative with a field map and its fast approximation (general locator)
  4. Jeffrey A. Fessler, Model-based image reconstruction for MRI, IEEE Signal Processing Magazine 27(4), 2010, 81 to 89, the system model of MRI and model-based reconstruction (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