Algorithm Search⌘K

Algorithmresearch

ESPIRiT

Also called eigenvector-based SPIRiT.

Estimates coil sensitivity maps from calibration k-space: the null space of the calibration matrix defines a small matrix at each pixel, and its eigenvector with eigenvalue 1 is the map.

Time
O(a^2 c^2 K^2 + c^3 K^3 + n^2 c^2 K^2) worst
Space
O(a^2 c K + c^2 K^2 + c n^2) extra
Where
K = the number of kernel positions per coil; a = the side of the square ACS block; c = the number of coils; n = the side of the n x n image
Properties
deterministicnot exactnot in placeoffline
Origin
Martin Uecker, Peng Lai, Mark J. Murphy, Patrick Virtue, Michael Elad, John M. Pauly, Shreyas S. Vasanawala, Michael Lustig, 2014

ESPIRiT estimates the coil sensitivity maps of a multi-coil MR scan from a small fully sampled calibration region at the center of k-space. It puts all patches of the calibration k-space of all coils into a matrix and splits the patch space into a signal space and a null space with the singular value decomposition. The null space turns, pixel by pixel, into a small c×cc \times c matrix, and the coil map at that pixel is the eigenvector with eigenvalue 1. The maps then go into SENSE or CG-SENSE. Uecker and colleagues published the method in 2014. When the maps have a finite k-space support and the calibration is rich enough, the method returns the normalized maps exactly (a theorem).

In plain words

The calibration region tells us which combinations of neighboring k-space samples of all coils always give zero. Each such rule, moved to the image domain, says that at each pixel the coil values are perpendicular to a certain vector. Collect all these vectors at a pixel: the coil profile must be perpendicular to all of them. ESPIRiT builds a small matrix at each pixel that keeps exactly what is perpendicular to them, and reads off the coil profile as the direction that the matrix does not change. Where there is no signal, no direction survives, and the map is set to zero.

The problem

The input is the multi-coil k-space xbx_b, b=1,…,cb = 1, \ldots, c, on an n×nn \times n grid, of which only the central a×aa \times a block (the ACS block) is used. The kernel size kr×kck_r \times k_c, with K=krkcK = k_r k_c, the signal threshold tst_s and the eigenvalue threshold tet_e are choices; the code uses 3×33 \times 3, ts=10−3t_s = 10^{-3} and te=0.9t_e = 0.9 by default. The output is a map mb(p)m_b(p) for every coil and pixel, with ∑b∣mb(p)∣2=1\sum_b |m_b(p)|^2 = 1 and m0(p)m_0(p) real and positive where the map is kept, and the top eigenvalue at each pixel. The maps match the true maps sb(p)s_b(p) up to a scalar factor at each pixel, which goes into the image.

The algorithm

  1. ESPIRIT(x, ACS, k_r, k_c, t_s, t_e)
  2. 1A <- one row per k_r x k_c patch of the ACS block, entry (b, d) = x_b(kappa + d);
  3. V <- right singular vectors of A with sigma > t_s sigma_1
  4. 2N_v <- the number of kept vectors
  5. 3for each pixel p do
  6. 4a_l(p)[b] <- sum over d of conj(v_l(b, d)) exp(2 pi i d . p / n), for l = 1, ..., N_v
  7. 5G(p) <- (1/K) sum over l of a_l(p) a_l(p)^H
  8. 6(lambda_1, u) <- largest eigenvalue of G(p) and its unit eigenvector
  9. 7if lambda_1 >= t_e then m(p) <- u / (u_0 / |u_0|) else m(p) <- 0
  10. 8return m and lambda_1 at every pixel

Line L1 takes the singular vectors from the Hermitian eigenproblem of AHAA^H A, a matrix of size cKc K; the code uses the complex Jacobi eigenvalue algorithm. Line L4 is the inverse DFT of the kernel vˉl\bar v_l of each coil, taken at one pixel. Line L5 sums over the kept vectors; by Lemma 2 of the proof this is the identity minus the same sum over the discarded vectors, so the null space decides the result. Line L7 fixes the free phase of the eigenvector and masks pixels with a small top eigenvalue.

Example

Four coils, 3×33 \times 3 kernel, no noise. The band maps have only the image frequencies 0 and 1 on each axis; the ring maps are smooth Gaussian profiles, see coil sensitivity map. The map error is the Euclidean norm of the difference between the normalized true map and the estimate at a pixel (measurements with the code of this page).

grid maps and object ACS tst_s result
16×1616 \times 16 band, Shepp-Logan 10 10−310^{-3} 16 of 36 vectors kept, gap above 10410^4; eigenvalue 1 and map error below 10−910^{-9} at every pixel
32×3232 \times 32 band, Shepp-Logan 12 10−310^{-3} 16 large singular values, then a gap of several orders of magnitude to the rest
16×1616 \times 16 ring, disk of radius 0.75 10 0.02 inside: eigenvalue at least 0.9989, map error at most 0.035, mean 0.010; outside: eigenvalue mean 0.929, least 0.626
32×3232 \times 32 ring, disk of radius 0.75 12 0.02 map error at most 0.053 inside
16×1616 \times 16 ring, disk of radius 0.75 10 10−310^{-3} 32 of 36 vectors kept, so too few null vectors remain

The band maps meet the model of the theorem, and the result is exact up to rounding. The ring maps do not: the singular values decay without a clear gap, and the threshold tst_s decides how many vectors count as signal. With te=0.99t_e = 0.99, many pixels outside the disk are masked, while all pixels inside are kept. A SENSE reconstruction at R=2R = 2 with the band ESPIRiT maps reproduces the coil images to 10−910^{-9} (measurement, the test of this page). The tests run on 16×1616 \times 16 grids to keep the run time short.

Correctness

A vector vv with Av=0A v = 0 for all patches of the whole k-space gives, in the image domain, av(p)Hf(p)=0a_v(p)^H f(p) = 0 at every pixel. The sum of av(p)av(p)Ha_v(p) a_v(p)^H over all singular vectors is KIK I, so G(p)G(p) is the identity minus a positive semidefinite part built from the null space, and its eigenvalues lie in [0,1][0, 1]. If the maps are trigonometric polynomials with a fixed finite set of frequencies and the calibration data contain enough independent object patterns, the null space of the calibration matrix is the null space of the whole k-space, and then G(p)s(p)=s(p)G(p) s(p) = s(p) at every pixel. If the eigenvalue 1 is simple, line L7 returns s(p)/∥s(p)∥s(p)/\lVert s(p)\rVert with the phase of coil 0 removed. The proof gives the details. These are theorems for maps with a finite k-space support; for real coils the quality of the maps is a measurement.

Proof: ESPIRiT returns the normalized coil maps when the coil maps have a finite k-space support and the calibration data are rich enoughfull

The setting is that of the algorithm, in exact arithmetic. There are cc coils on an n×nn \times n grid. The coil image is fb(p)=sb(p)ρ(p)f_b(p) = s_b(p) \rho(p), and its k-space is the unitary DFT

xb(κ)=1n∑pfb(p) e−2πiκ⋅p/n.x_b(\kappa) = \frac{1}{n} \sum_{p} f_b(p)\, e^{-2\pi i \kappa \cdot p / n}.

The patch offsets are O={0,…,kr−1}×{0,…,kc−1}O = \{0, \ldots, k_r - 1\} \times \{0, \ldots, k_c - 1\}, with K=krkcK = k_r k_c. A vector v∈CcKv \in \mathbb{C}^{cK} has the entries v(b,d)v(b, d) for a coil bb and an offset d∈Od \in O. The row of the calibration matrix AA for a patch at κ\kappa in the ACS block is (xb(κ+d))(b,d)(x_b(\kappa + d))_{(b,d)}. For a vector vv and a pixel pp, define av(p)∈Cca_v(p) \in \mathbb{C}^c by

av(p)[b]=∑d∈Ov(b,d)‾ e2πid⋅p/n,a_v(p)[b] = \sum_{d \in O} \overline{v(b, d)}\, e^{2\pi i d \cdot p / n},

as in line L4. Let V∥V_\parallel be the right singular vectors that line L1 keeps and V⊥V_\perp the other right singular vectors, so that [V∥ V⊥][V_\parallel\ V_\perp] is unitary. Line L5 builds G(p)=1K∑v∈V∥av(p)av(p)HG(p) = \frac{1}{K} \sum_{v \in V_\parallel} a_v(p) a_v(p)^H.

Lemma 1 (null vectors in the image domain). If ∑b,dxb(κ+d) v(b,d)=0\sum_{b, d} x_b(\kappa + d)\, v(b, d) = 0 for every κ∈Zn2\kappa \in \mathbb{Z}_n^2, then av(p)Hf(p)=0a_v(p)^H f(p) = 0 for every pixel pp, where f(p)=(fb(p))bf(p) = (f_b(p))_b.

Proof. Insert the DFT:

∑b,dv(b,d) xb(κ+d)=1n∑pe−2πiκ⋅p/n∑bfb(p)∑dv(b,d) e−2πid⋅p/n=1n∑pe−2πiκ⋅p/n av(p)Hf(p).\sum_{b,d} v(b,d)\, x_b(\kappa + d) = \frac{1}{n} \sum_p e^{-2\pi i \kappa \cdot p/n} \sum_b f_b(p) \sum_d v(b,d)\, e^{-2\pi i d \cdot p/n} = \frac{1}{n} \sum_p e^{-2\pi i \kappa \cdot p/n}\, a_v(p)^H f(p).

This is the DFT of the function p↦av(p)Hf(p)p \mapsto a_v(p)^H f(p). It is 0 for every κ\kappa, and the DFT is invertible, so the function is 0. □\square

Lemma 2 (the operator is a part of the identity). For every pp, G(p)G(p) is Hermitian, 0⪯G(p)⪯I0 \preceq G(p) \preceq I, and

G(p)+1K∑v∈V⊥av(p)av(p)H=I.G(p) + \frac{1}{K} \sum_{v \in V_\perp} a_v(p) a_v(p)^H = I.

Proof. Let Φ(p)\Phi(p) be the c×cKc \times cK matrix with Φ(p)[a,(b,d)]=δab e2πid⋅p/n\Phi(p)[a, (b, d)] = \delta_{ab}\, e^{2\pi i d \cdot p/n}. Then av(p)=Φ(p)vˉa_v(p) = \Phi(p) \bar v, and Φ(p)Φ(p)H=KI\Phi(p) \Phi(p)^H = K I, because each row has KK entries of modulus 1 and different rows have disjoint supports. The conjugate of a unitary matrix is unitary, so ∑all vvˉ vˉH=I\sum_{\text{all } v} \bar v\, \bar v^H = I, and

∑all vav(p)av(p)H=Φ(p)(∑all vvˉ vˉH)Φ(p)H=KI.\sum_{\text{all } v} a_v(p) a_v(p)^H = \Phi(p) \Big( \sum_{\text{all } v} \bar v\, \bar v^H \Big) \Phi(p)^H = K I.

Divide by KK. Both sums are Hermitian and positive semidefinite, so 0⪯G(p)⪯I0 \preceq G(p) \preceq I. □\square

Model (H1). As in the GRAPPA proof, the maps are trigonometric polynomials with image frequencies in a finite set HH: sb(p)=∑e∈Hhb(e) e2πie⋅p/ns_b(p) = \sum_{e \in H} h_b(e)\, e^{2\pi i e \cdot p/n}. Then xb(κ)=∑e∈Hhb(e) X(κ−e)x_b(\kappa) = \sum_{e \in H} h_b(e)\, X(\kappa - e), with XX the k-space of ρ\rho. Let U={d−e:d∈O, e∈H}U = \{d - e : d \in O,\ e \in H\}, and let MM be the ∣U∣×cK|U| \times cK matrix M[u,(b,d)]=hb(d−u)M[u, (b, d)] = h_b(d - u), with hb=0h_b = 0 outside HH. Then

∑b,dxb(κ+d) v(b,d)=∑u∈UX(κ+u) (Mv)ufor every κ.(1)\sum_{b,d} x_b(\kappa + d)\, v(b,d) = \sum_{u \in U} X(\kappa + u)\, (M v)_u \quad \text{for every } \kappa. \qquad (1)

Theorem. Assume (H1), and:

  1. (rich calibration) the matrix PP whose rows are (X(κ+u))u∈U(X(\kappa + u))_{u \in U}, for the patch positions κ\kappa of the ACS block, has full column rank ∣U∣|U|;
  2. (threshold) line L1 keeps exactly the right singular vectors with a nonzero singular value.

Then for every pixel pp, G(p) s(p)=s(p)G(p)\, s(p) = s(p), and 1 is the largest eigenvalue of G(p)G(p). If moreover 3. (simple eigenvalue) the eigenvalue 1 of G(p)G(p) is simple and s0(p)≠0s_0(p) \ne 0,

then the map that lines L6 and L7 return at pp is s(p)/∥s(p)∥s(p)/\lVert s(p) \rVert times the phase s0(p)‾/∣s0(p)∣\overline{s_0(p)}/|s_0(p)|, for any te≤1t_e \le 1.

Proof. By (1), A=PMA = P M. Since PP has full column rank, Av=0A v = 0 if and only if Mv=0M v = 0. By assumption 2, the discarded vectors V⊥V_\perp span the null space of AA, so Mv=0M v = 0 for each v∈V⊥v \in V_\perp, and by (1) the hypothesis of Lemma 1 holds for each of them. The same computation as in Lemma 1, with sbs_b in place of fbf_b, gives more: by (H1),

av(p)Hs(p)=∑b,dv(b,d) e−2πid⋅p/n∑ehb(e) e2πie⋅p/n=∑u∈Ue−2πiu⋅p/n (Mv)u=0a_v(p)^H s(p) = \sum_{b,d} v(b,d)\, e^{-2\pi i d \cdot p/n} \sum_{e} h_b(e)\, e^{2\pi i e \cdot p/n} = \sum_{u \in U} e^{-2\pi i u \cdot p/n}\, (M v)_u = 0

at every pixel pp, also where ρ(p)=0\rho(p) = 0. By Lemma 2, G(p)s(p)=s(p)−1K∑v∈V⊥av(p) av(p)Hs(p)=s(p)G(p) s(p) = s(p) - \frac{1}{K} \sum_{v \in V_\perp} a_v(p)\, a_v(p)^H s(p) = s(p). Since G(p)⪯IG(p) \preceq I, no eigenvalue is larger than 1. If s(p)≠0s(p) \ne 0 and the eigenvalue 1 is simple, the top eigenvector of line L6 is u=eiθs(p)/∥s(p)∥u = e^{i\theta} s(p)/\lVert s(p) \rVert for some phase θ\theta. Its eigenvalue is 1≥te1 \ge t_e, so line L7 keeps it and divides by u0/∣u0∣=eiθs0(p)/∣s0(p)∣u_0/|u_0| = e^{i\theta} s_0(p)/|s_0(p)|, which removes θ\theta. □\square

Corollary (the maps explain the data). Under the assumptions 1 to 3 at every pixel, the maps m(p)m(p) of the algorithm satisfy fb(p)=mb(p) ρ′(p)f_b(p) = m_b(p)\, \rho'(p) for the image ρ′(p)=∥s(p)∥ s0(p)∣s0(p)∣ ρ(p)\rho'(p) = \lVert s(p) \rVert\, \tfrac{s_0(p)}{|s_0(p)|}\, \rho(p). So a SENSE reconstruction with these maps that is exact for the true maps returns ρ′\rho', and the coil images mbρ′m_b \rho' are the true coil images.

Proof. Multiply the result of the theorem by ρ′(p)\rho'(p). □\square

Remarks.

  • Assumption 1 is the rich calibration assumption of the GRAPPA proof. Under it, the rank of AA is the rank of MM, at most ∣U∣|U|. For the band maps of the tests (H={0,1}2H = \{0,1\}^2, a 3×33 \times 3 kernel, ∣U∣=16|U| = 16), the tests find 16 large singular values and a gap of more than 10410^4 to the rest (measurement).
  • Assumption 3 can fail. If the object is larger than the field of view, or if the coils give fewer independent profiles than needed, the eigenvalue 1 can have a multiplicity above 1, and ESPIRiT then uses several sets of maps (Uecker et al. 2014). The tests check the result for the band maps, not the assumption.
  • For maps that are not trigonometric polynomials, (H1) holds only approximately. Then the discarded vectors are only approximately null, G(p)G(p) has eigenvalues close to 1 where the object has signal, and the thresholds tst_s and tet_e are choices. The behavior for the ring maps of the tests is a measurement.
  • The theorem says nothing about the eigenvalues outside the object for real data: there the data do not constrain the maps, and line L7 uses tet_e to mask such pixels. For (H1) maps, the eigenvalue is 1 everywhere.

Complexity

In the real RAM: line L1 forms AHAA^H A from about a2a^2 patches in O(a2c2K2)O(a^2 c^2 K^2) and solves the eigenproblem of size cKc K in O(c3K3)O(c^3 K^3) per Jacobi sweep, with a number of sweeps that is small in practice (a heuristic). At each of the n2n^2 pixels, line L4 costs O(NvcK)O(N_v c K), line L5 costs O(Nvc2)O(N_v c^2) and line L6 costs O(c3)O(c^3) per sweep. With Nv≤cKN_v \le c K, the total is O(a2c2K2+c3K3+n2c2K2)O(a^2 c^2 K^2 + c^3 K^3 + n^2 c^2 K^2). Practical codes compute line L4 for all pixels with FFTs, O(Nvc n2log⁡n)O(N_v c\, n^2 \log n), and use power iteration for the top eigenvector. The memory holds the patches, the Gram matrix and the maps.

Properties

  • Eigenvalues in [0,1][0, 1]. For any data and any threshold, 0⪯G(p)⪯I0 \preceq G(p) \preceq I (theorem).
  • Exact for band-limited maps. Under the model and the rich calibration assumption, the true map is an eigenvector with eigenvalue 1 at every pixel (theorem). With a simple eigenvalue, the method returns it normalized (theorem).
  • Maps up to a pixelwise factor. The maps have unit norm across coils at each pixel. The missing factor ∥s(p)∥\lVert s(p) \rVert and the phase go into the image, so the coil images are unchanged (theorem, corollary of the proof).
  • Built-in mask. Outside the object, the top eigenvalue drops below 1, and the threshold tet_e masks those pixels (measurement for the ring maps). This mask also suppresses the noise outside the object in a SENSE reconstruction.
  • Same calibration as GRAPPA and SPIRiT. ESPIRiT needs only the ACS block that GRAPPA and SPIRiT use, no extra reference scan.

Variants and improvements

  • Several sets of maps. If the eigenvalue 1 is not simple, for example when the object is larger than the field of view, Uecker et al. (2014) keep two or more eigenvectors as separate sets of maps, and the SENSE model uses one image per set.
  • Soft weighting. Instead of the hard mask of line L7, the maps can be weighted by a function of the eigenvalue.
  • Fast versions. Practical codes compute G(p)G(p) with FFTs of the zero-padded kernels, on a coarse grid with interpolation, and find the top eigenvector by power iteration.
  • Walsh maps. Walsh, Gmitro and Marcellin (2000) take the top eigenvector of the local correlation matrix of the coil images. This needs fully sampled low resolution images and gives no theorem of exactness.
  • SENSE with ESPIRiT maps. The maps feed SENSE, CG-SENSE, or a reconstruction with a sparsity prior.

When to use it

Use ESPIRiT to get coil maps from the same calibration data that k-space methods use, when a separate reference scan is not available or not reliable. The maps then allow image domain reconstructions with priors that need an image, not coil images. Use several sets of maps when the field of view is tight. If a body coil reference scan is available and the coil setup does not move, ratio maps are simpler. For a quick combination of fully sampled data, the root sum of squares needs no maps at all.

Pitfalls

  • Wrong signal threshold. If tst_s is too small, line L1 keeps vectors that carry only noise or model error, and the null space is too small to fix the maps (the last row of the example). If tst_s is too large, true signal vectors count as null, and the eigenvalue drops inside the object.
  • Missing conjugate. Line L4 needs vˉ\bar v, as the proof shows. Without it the matrix G(p)G(p) belongs to the mirrored kernel, and the maps are wrong.
  • Phase of the eigenvector. An eigenvector has a free phase at each pixel. Without the fix of line L7 the maps have random phase jumps, which do no harm in SENSE in exact arithmetic but break smoothness and any phase-based method.
  • Too small a calibration block. With few patches, AA has fewer rows than columns, and the null space contains vectors that are not null for the whole k-space.
  • Masking the object. A high tet_e can mask pixels with weak signal inside the object, which then come out as zero in SENSE.

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.

espirit.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/espirit/. The authors are listed in prov/CN1ST0.jsonl.

"""ESPIRiT: coil maps as eigenvectors of a calibration operator (Uecker et al. 2014).

Conventions: the k-space of coil k is an n x n array in DFT order (rows
first), of the coil image f_k with the unitary DFT F / n. The ACS block is
the center acs x acs part of k-space (signed frequencies -acs/2 .. acs/2 - 1
on both axes), where every sample is known.

Step 1. Put every kr x kc patch of the ACS block of all coils as a row of the
calibration matrix A. The entry (b, d) of a row is x_b(kappa + d). Keep the
right singular vectors v_l of A with sigma_l > t_s sigma_1 (the signal space).

Step 2. For each pixel p, build the c x c matrix

    G(p) = (1 / K) sum_l a_l(p) a_l(p)^H,   a_l(p)[a] = sum_d conj(v_l(a, d)) exp(2 pi i d . p / n),

with K = kr kc. A null vector v of A (A v = 0) gives sum_b conj(a(p)[b]) f_b(p) = 0
in the image domain, so the coil vector s(p) is orthogonal to every null
a(p), and G(p) s(p) = s(p) when the signal space is exact. The coil maps are the eigenvectors of G(p) with eigenvalue
1. The code takes the top eigenvector, makes its coil 0 entry real and
positive, and sets the map to 0 where the top eigenvalue is below t_e.

The kernel size, the ACS size and the thresholds t_s and t_e are choices.
"""

import cmath
import math
from typing import Sequence

Array = list[list[complex]]
Matrix = list[list[complex]]


def herm_eig(a: Sequence[Sequence[complex]], tol: float = 1e-14, max_sweeps: int = 60) -> tuple[list[float], Matrix]:
    """Eigenvalues (descending) and eigenvectors (as columns) of a complex Hermitian matrix.

    Cyclic Jacobi method with complex rotations. Returns (w, Q) with A = Q diag(w) Q^H.
    """
    n = len(a)
    m = [[complex(v) for v in row] for row in a]
    q = [[1.0 + 0j if i == j else 0j for j in range(n)] for i in range(n)]
    for _ in range(max_sweeps):
        off = sum(abs(m[i][j]) ** 2 for i in range(n) for j in range(n) if i != j)
        scale = sum(abs(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):
                apr = m[p][r]
                b = abs(apr)
                if b == 0.0:
                    continue
                ph = apr / b  # exp(i phi)
                alpha, beta = m[p][p].real, m[r][r].real
                theta = (beta - alpha) / (2.0 * b)
                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)
                s = c * t
                sp = s * ph.conjugate()  # s exp(-i phi)
                cp = c * ph.conjugate()  # c exp(-i phi)
                # columns: J = diag(1, exp(-i phi)) [[c, s], [-s, c]]
                for k in range(n):
                    mkp, mkr = m[k][p], m[k][r]
                    m[k][p] = c * mkp - sp * mkr
                    m[k][r] = s * mkp + cp * mkr
                # rows: the conjugate coefficients
                rp, rr = m[p], m[r]
                for k in range(n):
                    mpk, mrk = rp[k], rr[k]
                    rp[k] = c * mpk - sp.conjugate() * mrk
                    rr[k] = s * mpk + cp.conjugate() * mrk
                m[p][r] = m[r][p] = 0j
                for k in range(n):
                    qkp, qkr = q[k][p], q[k][r]
                    q[k][p] = c * qkp - sp * qkr
                    q[k][r] = s * qkp + cp * qkr
    order = sorted(range(n), key=lambda i: -m[i][i].real)
    return [m[i][i].real for i in order], [[q[k][i] for i in order] for k in range(n)]


def kernel_offsets(kr: int, kc: int) -> list[tuple[int, int]]:
    """The patch offsets (dr, dc), from (0, 0) to (kr - 1, kc - 1)."""
    return [(dr, dc) for dr in range(kr) for dc in range(kc)]


def calibration_matrix(ksp: Sequence[Array], acs: int, kr: int, kc: int) -> Matrix:
    """One row per kr x kc patch inside the ACS block; column (b, d) holds x_b(kappa + d)."""
    c, n = len(ksp), len(ksp[0])
    idx = [(f + n) % n for f in range(-(acs // 2), acs - acs // 2)]
    offs = kernel_offsets(kr, kc)
    rows = []
    for u in range(acs - kr + 1):
        for v in range(acs - kc + 1):
            rows.append([ksp[b][idx[u + dr]][idx[v + dc]] for b in range(c) for dr, dc in offs])
    return rows


def signal_space(ksp: Sequence[Array], acs: int, kr: int = 3, kc: int = 3, t_s: float = 1e-3) -> tuple[list[float], Matrix]:
    """Singular values of the calibration matrix and the kept right singular vectors (as columns)."""
    a = calibration_matrix(ksp, acs, kr, kc)
    m = len(a[0])
    gram = [[sum(row[i].conjugate() * row[j] for row in a) for j in range(m)] for i in range(m)]
    w, q = herm_eig(gram)
    sig = [math.sqrt(max(x, 0.0)) for x in w]
    keep = [l for l in range(m) if sig[l] > t_s * sig[0]]
    return sig, [[q[i][l] for l in keep] for i in range(m)]


def espirit(
    ksp: Sequence[Array],
    acs: int,
    kr: int = 3,
    kc: int = 3,
    t_s: float = 1e-3,
    t_e: float = 0.9,
) -> tuple[list[Array], list[list[float]]]:
    """Return (maps, eig): maps[k] is the n x n map of coil k, eig the top eigenvalue of G(p) at each pixel."""
    c, n = len(ksp), len(ksp[0])
    offs = kernel_offsets(kr, kc)
    kk = kr * kc
    _, v = signal_space(ksp, acs, kr, kc, t_s)  # @line L1
    nv = len(v[0])  # @line L2
    maps = [[[0j] * n for _ in range(n)] for _ in range(c)]
    eig = [[0.0] * n for _ in range(n)]
    for i in range(n):  # @line L3
        for j in range(n):
            ph = [cmath.exp(2j * math.pi * (dr * i + dc * j) / n) for dr, dc in offs]
            avec = [[sum(v[b * kk + t][l].conjugate() * ph[t] for t in range(kk)) for b in range(c)] for l in range(nv)]  # @line L4
            g = [[sum(al[a] * al[b].conjugate() for al in avec) / kk for b in range(c)] for a in range(c)]  # @line L5
            w, q = herm_eig(g)  # @line L6
            u = [q[a][0] for a in range(c)]
            eig[i][j] = w[0]
            if w[0] < t_e:  # @line L7
                continue
            ref = u[0] / abs(u[0]) if abs(u[0]) > 0 else 1.0
            for a in range(c):
                maps[a][i][j] = u[a] / ref
    return maps, eig  # @line L8
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
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_espirit.py 122 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/espirit/. The authors are listed in prov/CN1ST0.jsonl.

import cmath
import functools
import math
import random

from espirit import espirit, herm_eig, signal_space
from imgkit import MODIFIED_SHEPP_LOGAN, dft2, disk_phantom, ellipse_phantom, idft2, pixel_centers
from imgla import solve

N = 16
BAND = [(0.0, 0.8, 4, 0.3, 16), (1.0, 0.8, 28, 0.2, 12), (2.0, 0.3, 16, 0.8, 4), (-1.5, 0.25, 20, 0.8, 28)]


def band_maps(n):
    """Coil maps with image frequencies 0 and 1 on each axis: the patch space of a 3 x 3 kernel is exact."""
    out = []
    for psi, a, col, b, row in BAND:
        u, v = 2 * math.pi * col / n, 2 * math.pi * row / n
        out.append([[cmath.exp(1j * psi) * (1 + a * cmath.exp(1j * (2 * math.pi * j / n - u)))
                     * (1 + b * cmath.exp(1j * (2 * math.pi * i / n - v))) for j in range(n)] for i in range(n)])
    return out


def ring_maps(n, c=4):
    """Smooth Gaussian coil profiles around the object, with a phase ramp."""
    xs, ys = pixel_centers(n)
    maps = []
    for k in range(c):
        ang = math.radians(20 + 360.0 * k / c)
        cx, cy = 1.2 * math.cos(ang), 1.2 * math.sin(ang)
        maps.append([[math.exp(-((x - cx) ** 2 + (y - cy) ** 2) / 1.2) * cmath.exp(1j * (0.9 * k + 0.4 * x - 0.3 * y))
                      for x in xs] for y in ys])
    return maps


def coil_images(maps, img):
    return [[[s * p for s, p in zip(sr, pr)] for sr, pr in zip(mp, img)] for mp in maps]


def ksp_of(coils):
    n = len(coils[0])
    return [[[v / n for v in row] for row in dft2(f)] for f in coils]


def normalized(s):
    """s / ||s|| with the coil 0 entry made real and positive."""
    nr = math.sqrt(sum(abs(x) ** 2 for x in s))
    ref = s[0] / abs(s[0])
    return [x / nr / ref for x in s]


@functools.lru_cache(maxsize=None)
def band_case():
    maps = band_maps(N)
    coils = coil_images(maps, ellipse_phantom(N, MODIFIED_SHEPP_LOGAN))
    k = ksp_of(coils)
    est, eig = espirit(k, 10)
    return maps, coils, k, est, eig


def test_herm_eig():
    rng = random.Random(1)
    a = [[complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(6)] for _ in range(6)]
    h = [[a[i][j] + a[j][i].conjugate() for j in range(6)] for i in range(6)]
    w, q = herm_eig(h)
    assert all(x >= y for x, y in zip(w, w[1:]))
    for i in range(6):
        for l in range(6):
            assert abs(sum(h[i][k] * q[k][l] for k in range(6)) - w[l] * q[i][l]) < 1e-12
            assert abs(sum(q[k][i].conjugate() * q[k][l] for k in range(6)) - (1 if i == l else 0)) < 1e-12


def test_signal_space_has_rank_16_for_band_maps():
    _, _, k, _, _ = band_case()
    sig, v = signal_space(k, 10)
    assert len(sig) == 36 and len(v[0]) == 16
    assert sig[15] > 1e4 * sig[16]


def test_band_maps_are_recovered_with_eigenvalue_one():
    maps, _, _, est, eig = band_case()
    for i in range(N):
        for j in range(N):
            assert abs(eig[i][j] - 1.0) < 1e-9
            truth = normalized([m[i][j] for m in maps])
            assert max(abs(a - b[i][j]) for a, b in zip(truth, est)) < 1e-9


def test_sense_with_espirit_maps_is_consistent_with_the_data():
    _, coils, k, est, _ = band_case()
    h = N // 2
    # R = 2: keep the even rows; the inverse DFT of size (n/2) x n gives the folded coil images / n.
    folded = [[[N * v for v in row] for row in idft2([k[c][2 * r] for r in range(h)])] for c in range(4)]
    for i in range(h):
        for j in range(N):
            e = [[est[c][i][j], est[c][i + h][j]] for c in range(4)]
            a = [folded[c][i][j] for c in range(4)]
            gram = [[sum(e[c][p].conjugate() * e[c][q] for c in range(4)) for q in range(2)] for p in range(2)]
            rhs = [sum(e[c][p].conjugate() * a[c] for c in range(4)) for p in range(2)]
            m = solve(gram, rhs)
            for c in range(4):
                assert abs(est[c][i][j] * m[0] - coils[c][i][j]) < 1e-9
                assert abs(est[c][i + h][j] * m[1] - coils[c][i + h][j]) < 1e-9


def test_ring_maps_disk_object():
    maps = ring_maps(N)
    img = disk_phantom(N, 0.75)
    k = ksp_of(coil_images(maps, img))
    est, eig = espirit(k, 10, t_s=0.02, t_e=0.99)
    inside = [(i, j) for i in range(N) for j in range(N) if img[i][j] != 0]
    outside = [(i, j) for i in range(N) for j in range(N) if img[i][j] == 0]
    assert min(eig[i][j] for i, j in inside) > 0.99
    assert sum(eig[i][j] for i, j in outside) / len(outside) < 0.97
    for i, j in inside:
        truth = normalized([m[i][j] for m in maps])
        assert math.sqrt(sum(abs(a - b[i][j]) ** 2 for a, b in zip(truth, est))) < 0.1
    masked = [(i, j) for i, j in outside if all(b[i][j] == 0 for b in est)]
    assert masked

History

Walsh, Gmitro and Marcellin estimated maps from local eigenvectors of coil correlation matrices in 2000. Lustig and Pauly introduced the SPIRiT consistency condition in 2010. Uecker, Lai, Murphy, Virtue, Elad, Pauly, Vasanawala and Lustig showed in 2014 that this condition defines the coil maps as eigenvectors with eigenvalue 1 of a pixelwise operator, which links the k-space methods of the GRAPPA family with the image space methods of the SENSE family.

References

  1. Martin Uecker, Peng Lai, Mark J. Murphy, Patrick Virtue, Michael Elad, John M. Pauly, Shreyas S. Vasanawala and Michael Lustig, ESPIRiT, an eigenvalue approach to autocalibrating parallel MRI, where SENSE meets GRAPPA, Magnetic Resonance in Medicine 71(3), 2014, 990 to 1001, the calibration matrix and its null space, the pointwise eigenvalue problem with eigenvalue 1, the thresholds, and the multiple sets of maps (general locator; section and equation numbers not confirmed)
  2. Michael Lustig and John M. Pauly, SPIRiT, iterative self-consistent parallel imaging reconstruction from arbitrary k-space, Magnetic Resonance in Medicine 64(2), 2010, 457 to 471, the calibration consistency condition that ESPIRiT turns into an eigenvalue problem (general locator)
  3. David O. Walsh, Arthur F. Gmitro and Michael W. Marcellin, Adaptive reconstruction of phased array MR imagery, Magnetic Resonance in Medicine 43(5), 2000, 682 to 690, the earlier map estimate from the dominant eigenvector of the local signal correlation matrix (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