Algorithm Search⌘K

Algorithmadvanced

k-t BLAST

Also called k-t SENSE.

Undersample dynamic MRI in k-space and time on a lattice and unfold the aliases in x-f space with a prior from low resolution training data.

Time
O(c n f log(n f) + n f c^2 + n f c^3 / R) worst
Space
O(c n f) extra
Where
R = the acceleration factor; c = the number of coils; f = the number of frames; n = the number of pixels in one frame
Properties
deterministicnot in placenot iterativeoffline
Origin
Jeffrey Tsao, Peter Boesiger, Klaas P. Pruessmann, 2003

k-t BLAST (Broad-use Linear Acquisition Speed-up Technique) speeds up dynamic MRI by sampling only every RR-th phase encoding line in each frame, on a pattern that shifts from frame to frame. After a Fourier transform along space and along time, the missing lines show up as aliases in x-f space, the space of position and temporal frequency. Each measured x-f value is a sum of RR unknown values. k-t BLAST splits each sum with a Wiener-type estimate. The prior power of each value comes from a short training scan of low spatial resolution. With coil maps, the same estimate also uses the coil sensitivities, and the method is called k-t SENSE. Unlike low-rank plus sparse MRI and compressed sensing MRI, the reconstruction is linear and not iterative, but it needs the training data.

In plain words

In a heart scan, most pixels hardly change over time, and the pixels that do change are in a small region. Take the time course of each pixel and look at its frequencies. Static pixels have only the zero frequency. Moving pixels have a few low frequencies.

If you skip lines in k-space, each image gets copies of itself laid over it. k-t BLAST skips different lines in each frame, so the copies also move to other temporal frequencies. Most of the time, a copy lands where the true signal is near zero. A low resolution training scan tells the method where the signal is large and where it is small. For each overlap, it gives the measured value mostly to the place where the training scan expects signal.

The problem

The input is a dynamic series of ntn_t frames with nn pixels along the phase encoding direction (a 1D model; the read direction is fully sampled and separates). The sampled k-t data are dc(k,t)d_c(k, t) for coil cc, at the points of a lattice: frame tt keeps the lines k≡st(modR)k \equiv s t \pmod R. The acceleration RR divides nn and ntn_t, and the shift ss is prime to RR, so every line is sampled in nt/Rn_t / R frames. The other inputs are a prior power p(y,f)≥0p(y, f) \ge 0 for each x-f point, a noise variance ψ≥0\psi \ge 0 and, for k-t SENSE, the coil maps c(y)c(y). The unitary DFT along time of the series is ρ(y,f)\rho(y, f). The output is an estimate of the series.

Zero fill the data, apply the unitary inverse DFT along kk and the unitary DFT along tt. The result is the aliased x-f signal

ρalias,c(y,f)=1R∑j=0R−1c(yj) ρ(yj,fj),yj=y+jnR,fj=f+jsntR.\rho_{\text{alias}, c}(y, f) = \frac1R \sum_{j=0}^{R-1} c(y_j)\, \rho(y_j, f_j), \qquad y_j = y + \frac{jn}{R}, \quad f_j = f + \frac{j s n_t}{R}.

So the x-f grid splits into groups of RR points that fold onto one point, and each group is a small linear system v=AρGv = A \rho_G with the nc×Rn_c \times R matrix Acj=c(yj)/RA_{cj} = c(y_j)/R. The aliasing is the same as in SENSE, but in x-f space and not in image space.

The algorithm

  1. KTBLAST(d, lattice, p, psi, coils)
  2. 1b(k) <- mean of d(k, t) over the frames t that sample line k ▷ baseline
  3. 2d(k, t) <- d(k, t) - b(k) on the sampled points
  4. 3rho_alias <- DFT along t of the inverse DFT along k of the zero filled d
  5. 4for each alias group G = {(y_j, f_j)} folding onto (y_0, f_0) do
  6. 5A <- the n_c x R matrix c(y_j) / R; P <- diag(p(y_j, f_j))
  7. 6rho(G) <- P A^H (A P A^H + psi I)^(-1) rho_alias(y_0, f_0)
  8. 7x <- inverse DFT along t of rho
  9. 8return x + the image of b

Line L6 is the Wiener filter of one group. If the values ρG\rho_G have mean 0 and covariance PP and the noise has covariance ψI\psi I, it is the linear estimate with the least mean squared error. In the paper, PP is the squared magnitude of the training x-f signal, and ψ\psi is the noise variance. The training data are a few central k-space lines, fully sampled in every frame, so they give a low resolution series. The baseline (the time average) is removed from the data and from the training data before the unfolding and is added back at the end, because the time average is large and its prior would hide the dynamic part. With one coil, line L6 is a scalar formula:

ρ^(yj,fj)=R pj∑ipi+R2ψ ρalias(y0,f0).\hat\rho(y_j, f_j) = \frac{R\, p_j}{\sum_i p_i + R^2 \psi}\, \rho_{\text{alias}}(y_0, f_0).

Example

Take n=32n = 32 pixels and nt=16n_t = 16 frames. The body is 1 on the pixels 4 to 27. A bright region of height 1 between two edges at 12−2.5cos⁡(2πt/16)12 - 2.5 \cos(2\pi t/16) and 20+2.5cos⁡(2πt/16)20 + 2.5 \cos(2\pi t/16), with smooth edges, models a beating heart. Pixels 24 to 26 also rise linearly by 0.5 over the scan, like contrast uptake. Sample with R=4R = 4 and s=1s = 1, so each frame keeps 8 of 32 lines. The training series uses the 2w−12w - 1 central lines of each frame. The table gives the relative error of the whole series (measured with the code below, one coil, no noise).

reconstruction relative error
zero filled, scaled by RR, no baseline 1.728
the time average alone 0.160
flat prior p=1p = 1, with baseline 0.142
training with 3 lines, ψ=10−6\psi = 10^{-6} 0.055
training with 7 lines, ψ=10−6\psi = 10^{-6} 0.052
training with 11 lines, ψ=10−6\psi = 10^{-6} 0.048
training with 7 lines, ψ=0.01\psi = 0.01 0.071
the true power as the prior, ψ=10−9\psi = 10^{-9} 0.047

A flat prior splits each alias value evenly among the RR points, which leaves the aliases in place. Even 3 training lines cut the error by more than half. The true power does not give zero error: some groups hold two points with signal, such as the two moving edges, and one coil cannot separate them. The shift s=3s = 3 gives the same numbers on this series. Without the baseline, the flat prior gives 0.867 and the training prior gives the same errors as with it, because the data have no noise.

Correctness

The following results hold, and all are proved in full below.

  • Aliasing. For the lattice above, the zero filled x-f signal is exactly 1R∑jc(yj)ρ(yj,fj)\frac1R \sum_j c(y_j) \rho(y_j, f_j), and the groups partition the x-f grid. The proof writes the mask as a sum of RR complex exponentials, each of which shifts the signal in yy and in ff.
  • Wiener estimate. Line L6 minimizes the mean squared error among linear estimates, under the prior and noise model above. For ψ>0\psi > 0 and P>0P > 0 it also equals (AHA/ψ+P−1)−1AHv/ψ(A^H A/\psi + P^{-1})^{-1} A^H v/\psi, the minimizer of ∥v−Aρ∥2/ψ+∑j∣ρj∣2/pj\|v - A\rho\|^2/\psi + \sum_j |\rho_j|^2/p_j.
  • Exact cases. If the true group signal is zero where p=0p = 0, and the columns of AA where p>0p > 0 are independent, the estimate tends to the truth as ψ→0\psi \to 0. This covers one signal point per group with one coil, k-t SENSE with at least RR coils whose maps separate the group, and full sampling.
  • Baseline. The baseline from the sampled data is the true time average plus copies of the signal at the temporal frequencies that are nonzero multiples of nt/Rn_t/R. A static series is recovered exactly.

The model of a zero-mean prior with independent values is a heuristic. Real x-f signals are not Gaussian, and the training power is only an estimate of the true power. So the quality of the result for a real scan is measured, not proved.

Proof: The x-f aliasing of lattice sampling and the exactness of the k-t BLAST unfoldingfull

The setting is that of the algorithm. A series x(y,t)x(y, t) has nn pixels and ntn_t frames. Coil cc has the map c(y)c(y); with one coil, c=1c = 1. The unitary DFT along yy is K(k)=n−1/2∑yx(y)e−2πiky/nK(k) = n^{-1/2} \sum_y x(y) e^{-2\pi i k y / n}, and the unitary DFT along tt is ρ(y,f)=nt−1/2∑tx(y,t)e−2πift/nt\rho(y, f) = n_t^{-1/2} \sum_t x(y, t) e^{-2\pi i f t / n_t}. All indices are taken modulo nn or ntn_t. The acceleration RR divides nn and ntn_t, and the shift ss is prime to RR. Frame tt keeps the lines kk with k≡st(modR)k \equiv s t \pmod R.

1. Aliasing in x-f space

Theorem 1. Let ρc\rho_c be the x-f signal of c xc\, x. Zero fill the sampled k-t data of coil cc, apply the unitary inverse DFT along kk and the unitary DFT along tt. The result is

ρalias,c(y,f)=1R∑j=0R−1ρc(y+jnR, f+jsntR).\rho_{\text{alias}, c}(y, f) = \frac1R \sum_{j=0}^{R-1} \rho_c\Big(y + \frac{jn}{R},\ f + \frac{j s n_t}{R}\Big).

Proof. The mask is m(k,t)=1R∑j=0R−1e2πij(k−st)/Rm(k, t) = \frac1R \sum_{j=0}^{R-1} e^{2\pi i j (k - s t)/R}, because the sum over jj is RR when k−st≡0(modR)k - st \equiv 0 \pmod R and 0 otherwise. Write e2πijk/R=e2πik(jn/R)/ne^{2\pi i j k / R} = e^{2\pi i k (jn/R) / n}. Multiplying a k-space line by e2πika/ne^{2\pi i k a / n} shifts its unitary inverse DFT: the result is x(y+a)x(y + a). Write e−2πijst/R=e−2πi(jsnt/R)t/nte^{-2\pi i j s t / R} = e^{-2\pi i (j s n_t / R) t / n_t}. Multiplying a time series by e−2πibt/nte^{-2\pi i b t / n_t} shifts its unitary DFT: the result is ρ(f+b)\rho(f + b). The three transforms are linear, so the term jj of the mask gives 1Rρc(y+jn/R,f+jsnt/R)\frac1R \rho_c(y + jn/R, f + j s n_t / R). □\square

Lemma 2. The groups G(y0,f0)={(y0+jn/R, f0+jsnt/R):j=0,…,R−1}G(y_0, f_0) = \{(y_0 + jn/R,\ f_0 + j s n_t / R) : j = 0, \ldots, R-1\} for 0≤y0<n/R0 \le y_0 < n/R and 0≤f0<nt0 \le f_0 < n_t partition the x-f grid into nnt/Rn n_t / R sets of RR points, and ρalias,c(y0,f0)\rho_{\text{alias}, c}(y_0, f_0) depends only on the values of ρ\rho in G(y0,f0)G(y_0, f_0).

Proof. A point (y,f)(y, f) lies in the group with j=⌊y/(n/R)⌋j = \lfloor y / (n/R) \rfloor, y0=y−jn/Ry_0 = y - jn/R and f0=f−jsnt/Rf_0 = f - j s n_t / R, and in no other, because jj and y0y_0 are fixed by yy. The groups have RR distinct points, because their yy values differ. The second claim is Theorem 1. □\square

So, for each group, the data are v=AρGv = A \rho_G, where vc=ρalias,c(y0,f0)v_c = \rho_{\text{alias}, c}(y_0, f_0) and AA is the nc×Rn_c \times R matrix Acj=c(y0+jn/R)/RA_{c j} = c(y_0 + jn/R) / R. With one coil, A=1R(1,…,1)A = \frac1R (1, \ldots, 1).

2. The unfolding is a Wiener estimate

Let P=diag⁡(p1,…,pR)P = \operatorname{diag}(p_1, \ldots, p_R) with pj≥0p_j \ge 0 and ψ≥0\psi \ge 0. The code computes

ρ^G=PAH(APAH+ψI)−1v,\hat\rho_G = P A^H (A P A^H + \psi I)^{-1} v,

and returns 0 when P=0P = 0.

Lemma 3. If ρG\rho_G is a random vector with mean 0 and covariance PP, and v=AρG+ev = A \rho_G + e with noise ee of mean 0 and covariance ψI\psi I, uncorrelated with ρG\rho_G, and APAH+ψIA P A^H + \psi I is invertible, then ρ^G=Wv\hat\rho_G = W v with W=PAH(APAH+ψI)−1W = P A^H (A P A^H + \psi I)^{-1} minimizes the mean squared error E∥Wv−ρG∥2\mathbb{E} \|W v - \rho_G\|^2 over all matrices WW.

Proof. The error is E∥Wv−ρG∥2=tr⁡(WCWH)−2Re⁡tr⁡(WAP)+tr⁡P\mathbb{E}\|W v - \rho_G\|^2 = \operatorname{tr}(W C W^H) - 2 \operatorname{Re} \operatorname{tr}(W A P) + \operatorname{tr} P with C=APAH+ψIC = A P A^H + \psi I, because E[vvH]=C\mathbb{E}[v v^H] = C and E[vρGH]=AP\mathbb{E}[v \rho_G^H] = A P. Write W=W0+ΔW = W_0 + \Delta with W0=PAHC−1W_0 = P A^H C^{-1}. Since W0C=PAHW_0 C = P A^H, the terms linear in Δ\Delta cancel, and the error is the error of W0W_0 plus tr⁡(ΔCΔH)≥0\operatorname{tr}(\Delta C \Delta^H) \ge 0. □\square

Lemma 4 (the second form). If ψ>0\psi > 0 and all pj>0p_j > 0, then PAH(APAH+ψI)−1=(AHA/ψ+P−1)−1AH/ψP A^H (A P A^H + \psi I)^{-1} = (A^H A / \psi + P^{-1})^{-1} A^H / \psi. So ρ^G\hat\rho_G also minimizes ∥v−Aρ∥2/ψ+∑j∣ρj∣2/pj\|v - A \rho\|^2 / \psi + \sum_j |\rho_j|^2 / p_j.

Proof. Multiply both sides on the left by AHA/ψ+P−1A^H A/\psi + P^{-1} and on the right by APAH+ψIA P A^H + \psi I. The left side gives (AHAP/ψ+I)AH=AH(APAH+ψI)/ψ(A^H A P/\psi + I) A^H = A^H (A P A^H + \psi I)/\psi, which is the right side. The quadratic ∥v−Aρ∥2/ψ+ρHP−1ρ\|v - A\rho\|^2/\psi + \rho^H P^{-1} \rho has the gradient zero exactly at this point. □\square

The test file checks Lemma 4 for a random 3×23 \times 2 matrix AA.

3. When the unfolding is exact

Theorem 5. Let QQ be the set of indices jj with pj>0p_j > 0. Suppose that the true ρG\rho_G is zero outside QQ and that the columns of AA with indices in QQ are linearly independent. Then ρ^G→ρG\hat\rho_G \to \rho_G as ψ→0+\psi \to 0^+, and ρ^G=ρG\hat\rho_G = \rho_G for ψ=0\psi = 0 if APAHA P A^H is invertible.

Proof. Only the columns in QQ enter, so write AQA_Q, PQP_Q and B=AQPQ1/2B = A_Q P_Q^{1/2}, which has full column rank. With v=AQρQv = A_Q \rho_Q,

ρ^Q=PQ1/2BH(BBH+ψI)−1B PQ−1/2ρQ=PQ1/2(BHB+ψI)−1BHB PQ−1/2ρQ,\hat\rho_Q = P_Q^{1/2} B^H (B B^H + \psi I)^{-1} B\, P_Q^{-1/2} \rho_Q = P_Q^{1/2} (B^H B + \psi I)^{-1} B^H B\, P_Q^{-1/2} \rho_Q,

using BH(BBH+ψI)−1=(BHB+ψI)−1BHB^H (B B^H + \psi I)^{-1} = (B^H B + \psi I)^{-1} B^H. As ψ→0\psi \to 0, (BHB+ψI)−1BHB→I(B^H B + \psi I)^{-1} B^H B \to I because BHBB^H B is invertible, and so ρ^Q→ρQ\hat\rho_Q \to \rho_Q. Outside QQ, ρ^\hat\rho is 0 because pj=0p_j = 0. □\square

Three cases follow, and the test file checks each.

  • One coil, one signal point per group. With one coil, every column of AA is 1/R1/R, so QQ may hold only one index. If each group holds at most one nonzero point of the dynamic signal and the power is positive exactly there, the unfolding is exact.
  • k-t SENSE with nc≥Rn_c \ge R coils. If the coil matrix AA of every group has full column rank, QQ may be the whole group, and the unfolding is exact for every series and every positive PP in the limit ψ→0\psi \to 0. This is SENSE unfolding in x-f space.
  • Full sampling. With R=1R = 1, every group has one point and A=(c)A = (c), so the result is exact.

When two points of one group carry signal and AA cannot separate them, Theorem 5 does not apply. The estimate then splits the alias value in proportion to the prior, and its error is measured.

4. The baseline

The code takes the mean of the sampled values of each line kk as the baseline k-space, then subtracts it from the samples and adds its image back at the end.

Lemma 6. The baseline image is xˉ(y)+nt−1/2∑j=1R−1ρ(y+jn/R, jsnt/R)\bar x(y) + n_t^{-1/2} \sum_{j=1}^{R-1} \rho(y + jn/R,\ j s n_t / R), where xˉ\bar x is the true time average. If the series is static, the baseline is exact and the output equals the series for every PP and ψ\psi.

Proof. Line kk is sampled at the nt/Rn_t / R frames with k≡stk \equiv st. With the mask expansion of Theorem 1, the mean over these frames is Rnt∑tm(k,t)K(k,t)=1nt∑je2πijk/R∑te−2πijst/RK(k,t)\frac{R}{n_t} \sum_t m(k, t) K(k, t) = \frac{1}{n_t} \sum_j e^{2\pi i jk/R} \sum_t e^{-2\pi i j s t / R} K(k, t). The term j=0j = 0 is the time average of K(k,⋅)K(k, \cdot). The term jj is nt−1/2e2πijk/Rn_t^{-1/2} e^{2\pi i jk/R} times the unitary temporal DFT of K(k,⋅)K(k, \cdot) at f=jsnt/Rf = j s n_t / R, and the inverse DFT along kk turns the factor e2πijk/Re^{2\pi i jk/R} into the shift y+jn/Ry + jn/R. For a static series, ρ(⋅,f)=0\rho(\cdot, f) = 0 for f≠0f \ne 0, so the baseline is xˉ=x\bar x = x, the data minus the baseline are zero, the unfolding gives ρ^=0\hat\rho = 0, and the output is xx. □\square

Since ss is prime to RR, the frequencies jsnt/Rj s n_t / R for j=1,…,R−1j = 1, \ldots, R-1 are the nonzero multiples of nt/Rn_t / R. So the baseline holds, besides the true average, copies of the signal at these temporal frequencies, moved in yy by multiples of n/Rn/R. After the subtraction, the sum over the sampled frames of each line is zero, so the aliased value at f=0f = 0 is zero for every yy, and the unfolding sets every group G(y0,0)G(y_0, 0) to zero. The result is exact when the dynamic signal at the multiples of nt/Rn_t / R is zero, as in the tests. Otherwise this is part of the measured error, and it is small when the signal at those frequencies is weak.

Complexity

Let nn be the number of pixels along the phase encoding direction, ntn_t the number of frames and ncn_c the number of coils. The FFTs along kk and tt cost O(ncnntlog⁡(nnt))O(n_c n n_t \log(n n_t)) (lines L3 and L7). There are nnt/Rn n_t / R groups, and each needs the nc×ncn_c \times n_c matrix APAH+ψIA P A^H + \psi I in O(nc2R)O(n_c^2 R) and one solve in O(nc3)O(n_c^3) (lines L5 and L6). The total is O(ncnntlog⁡(nnt)+nntnc2+nntnc3/R)O(n_c n n_t \log(n n_t) + n n_t n_c^2 + n n_t n_c^3 / R) in the real RAM, with O(ncnnt)O(n_c n n_t) space for the data. For one coil this is O(nntlog⁡(nnt))O(n n_t \log(n n_t)), the cost of the FFTs. The method makes one pass and needs no iterations. The training scan costs extra scan time: a few central lines in every frame.

Properties

  • Linear and direct. The output is a linear function of the data for a fixed prior. There is no iteration and no tuning of a step size.
  • Needs training data. The prior comes from a separate low resolution scan, or from the central lines acquired together with the lattice.
  • Local in x-f. Each group is solved alone, so the work is easy to split.
  • Temporal blurring. Where the training prior is wrong or too smooth, the estimate pulls the dynamic signal toward zero. This shows up as a loss of temporal detail in small moving structures.

Variants and improvements

  • k-t SENSE. With coil maps, AA has one row per coil, and line L6 is SENSE unfolding with a prior. With at least RR coils that separate each group, it is exact in the noiseless limit. k-t SENSE is the name of this coil version, from the same paper.
  • UNFOLD. Madore, Glover and Pelc (1999) used the same shifted sampling to move aliases to other temporal frequencies and removed them with a fixed temporal filter, with no training data. k-t BLAST replaces the fixed filter by the data adaptive prior.
  • k-t PCA. Pedersen et al. (2009) restricted the temporal signal of each pixel to a few principal components of the training data. This is close to the partial separability model, which also uses a low rank temporal basis.
  • Sparse and low rank priors. Compressed sensing MRI and L+S replace the training prior by sparsity or low rank, and need random sampling instead of a lattice.

When to use it

Use k-t BLAST or k-t SENSE for dynamic scans where most of the field of view is static or slowly changing, such as cardiac cine, and when a short training scan is acceptable. It is fast and direct, so it suits real-time display. For scans with large motion across the field of view, or when no training data can be acquired, use a method with a sparse or low rank prior instead.

Pitfalls

  • The lattice conditions. The shift ss must be prime to RR, and RR must divide nn and ntn_t. Otherwise some lines are never sampled, and the groups do not partition the x-f grid.
  • Points that share a group. With one coil, two points in one group with signal cannot be separated. In the example, this keeps the error at 0.047 even with the true power. Choose the shift so that the aliases of the dynamic region land on static regions.
  • The noise term. ψ\psi trades noise against temporal detail. In the example, ψ=0.01\psi = 0.01 raises the error from 0.052 to 0.071. With real noise, ψ=0\psi = 0 amplifies it.
  • Wrong training data. If the patient moves between the training scan and the main scan, the prior puts the signal in the wrong place.
  • Signal at multiples of nt/Rn_t/R. The baseline from the sampled data mixes in the signal at these temporal frequencies, and the groups at f=0f = 0 are set to zero after the subtraction.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

imgkit.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the imaging and inverse problems pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small images and signals for the imaging and inverse problems pages.

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

import cmath
import math

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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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

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


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


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


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


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


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


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

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


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


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


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


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


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


def poisson_sample(rng, lam):
    """An exact Poisson(lam) sample: a sum of Knuth samples with means at most 30."""
    if lam < 0:
        raise ValueError("negative mean")
    total = 0
    while lam > 30.0:
        total += _poisson_small(rng, 30.0)
        lam -= 30.0
    if lam > 0.0:
        total += _poisson_small(rng, lam)
    return total
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
k_t_blast.py 171 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/k-t-blast/. The authors are listed in prov/MVRMMT.jsonl.

"""k-t BLAST and k-t SENSE (Tsao, Boesiger and Pruessmann 2003) for a series of 1D frames.

A series is a list of nt frames x[t][y], each a list of n complex pixels.
Frame t of coil c has the k-space F_u(c x_t), with the unitary DFT F_u
(F_u^H F_u = I) in DFT order. Data are stored on the full grid as
data[t][c][k], with zeros where the mask is 0. With no coil maps there is
one coil with c = 1.

Sampling: frame t keeps the lines k with k = shift * t (mod R). This is a
sheared lattice in k-t space. It needs n and nt divisible by R and shift
prime to R, so every line is sampled in nt / R frames.

x-f space: rho(y, f) is the unitary DFT along time of x(y, t). For the
lattice above, the zero filled data give, after the unitary inverse DFT
along k and the unitary DFT along t,

    rho_alias_c(y, f) = (1/R) sum_{j=0}^{R-1} c(y_j) rho(y_j, f_j),
    y_j = y + j n / R,  f_j = f + j shift nt / R (mod nt).

So the x-f grid splits into alias groups of R points, and each group is
one small linear system rho_alias = A rho_G with an nc x R matrix A.

Reconstruction of one group, with the prior power P = diag(|rho_train|^2)
from training data and the noise variance psi:

    rho_G = P A^H (A P A^H + psi I)^(-1) rho_alias.

This is the Wiener estimate for a zero-mean prior with covariance P and
white noise of variance psi. The time average (the baseline) is removed
before the unfolding and added back after it.
"""

import math

from imgkit import dft, idft
from imgla import solve


# ------------------------------------------------------------------ transforms


def _fu(x):
    s = 1.0 / math.sqrt(len(x))
    return [v * s for v in dft(x)]


def _fuh(k):
    s = math.sqrt(len(k))
    return [v * s for v in idft(k)]


def time_ft(rows):
    """Unitary DFT along time of rows[t][y]; returns rho[f][y]."""
    nt, n = len(rows), len(rows[0])
    cols = [_fu([rows[t][y] for t in range(nt)]) for y in range(n)]
    return [[cols[y][f] for y in range(n)] for f in range(nt)]


def time_ift(rho):
    """Inverse of time_ft."""
    nt, n = len(rho), len(rho[0])
    cols = [_fuh([rho[f][y] for f in range(nt)]) for y in range(n)]
    return [[cols[y][t] for y in range(n)] for t in range(nt)]


# ------------------------------------------------------------------ sampling


def lattice_mask(n, nt, r, shift=1):
    """mask[t][k] = 1 if k = shift * t (mod r)."""
    if n % r or nt % r or math.gcd(shift, r) != 1:
        raise ValueError("need n and nt divisible by r and shift prime to r")
    return [[1 if (k - shift * t) % r == 0 else 0 for k in range(n)] for t in range(nt)]


def acquire(series, mask, coils=None):
    """data[t][c][k] = mask[t][k] F_u(c x_t)(k)."""
    out = []
    for t, frame in enumerate(series):
        per_coil = []
        for cmap in coils or [None]:
            img = frame if cmap is None else [a * b for a, b in zip(cmap, frame)]
            per_coil.append([v if m else 0j for v, m in zip(_fu(img), mask[t])])
        out.append(per_coil)
    return out


def xf_alias(data):
    """rho_alias[c][f][y]: inverse DFT along k, then DFT along t, per coil."""
    nc = len(data[0])
    return [time_ft([_fuh(per_coil[c]) for per_coil in data]) for c in range(nc)]


def alias_groups(n, nt, r, shift=1):
    """The groups of R x-f points that fold onto one point (y0, f0), y0 < n / R."""
    return [
        [((y0 + j * n // r) % n, (f0 + j * shift * nt // r) % nt) for j in range(r)]
        for y0 in range(n // r)
        for f0 in range(nt)
    ]


# ------------------------------------------------------------------ prior


def training_power(train, remove_mean=True):
    """|rho_train(y, f)|^2 of a training series, by default after its time average is removed."""
    nt, n = len(train), len(train[0])
    mean = [sum(train[t][y] for t in range(nt)) / nt if remove_mean else 0j for y in range(n)]
    rho = time_ft([[train[t][y] - mean[y] for y in range(n)] for t in range(nt)])
    return [[abs(v) ** 2 for v in row] for row in rho]


def unfold_group(a, power, psi, v):
    """P A^H (A P A^H + psi I)^(-1) v for the nc x R matrix a and P = diag(power)."""
    nc, r = len(a), len(power)
    if all(p == 0 for p in power):
        return [0j] * r
    g = [
        [sum(a[i][q] * power[q] * a[j][q].conjugate() for q in range(r)) + (psi if i == j else 0) for j in range(nc)]
        for i in range(nc)
    ]
    w = solve(g, list(v))
    return [power[q] * sum(a[i][q].conjugate() * w[i] for i in range(nc)) for q in range(r)]


# ------------------------------------------------------------------ the method


def k_t_blast(data, mask, r, shift, power, psi, coils=None, baseline=True):
    """Reconstruct the series x[t][y] from lattice data.

    power[f][y] is the prior power in x-f space, usually training_power of a
    low resolution training series. psi >= 0 is the noise variance. With
    baseline=True the time average of the sampled data is removed first and
    added back at the end; the power should then come from a training
    series with its mean removed.
    """
    nt, nc, n = len(data), len(data[0]), len(data[0][0])
    base_k = []  # @line L1
    for c in range(nc):
        acc, cnt = [0j] * n, [0] * n
        for t in range(nt):
            for k in range(n):
                if mask[t][k] and baseline:
                    acc[k] += data[t][c][k]
                    cnt[k] += 1
        base_k.append([a / m if m else 0j for a, m in zip(acc, cnt)])
    diff = [[[(v - b) if m else 0j for v, b, m in zip(data[t][c], base_k[c], mask[t])] for c in range(nc)] for t in range(nt)]  # @line L2
    alias = xf_alias(diff)  # @line L3
    rho = [[0j] * n for _ in range(nt)]
    for group in alias_groups(n, nt, r, shift):  # @line L4
        a = [[(1.0 if coils is None else coils[c][y]) / r for (y, _) in group] for c in range(nc)]  # @line L5
        y0, f0 = group[0]
        est = unfold_group(a, [power[f][y] for (y, f) in group], psi, [alias[c][f0][y0] for c in range(nc)])  # @line L6
        for (y, f), val in zip(group, est):
            rho[f][y] = val
    series = time_ift(rho)  # @line L7
    base_imgs = [_fuh(base_k[c]) for c in range(nc)]
    if coils is None:
        base = base_imgs[0]
    else:
        den = [sum(abs(coils[c][y]) ** 2 for c in range(nc)) for y in range(n)]
        base = [
            sum(coils[c][y].conjugate() * base_imgs[c][y] for c in range(nc)) / den[y] if den[y] > 0 else 0j
            for y in range(n)
        ]
    return [[v + b for v, b in zip(frame, base)] for frame in series]  # @line L8
test_k_t_blast.py 159 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/k-t-blast/. The authors are listed in prov/MVRMMT.jsonl.

import cmath
import math
import random

from imgla import solve
from k_t_blast import (
    acquire,
    alias_groups,
    k_t_blast,
    lattice_mask,
    time_ft,
    time_ift,
    training_power,
    unfold_group,
    xf_alias,
)


def rand_c(rng):
    return complex(rng.gauss(0, 1), rng.gauss(0, 1))


def rand_series(rng, nt, n):
    return [[rand_c(rng) for _ in range(n)] for _ in range(nt)]


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


def unitary_dft(x):
    n = len(x)
    return [sum(x[j] * cmath.exp(-2j * math.pi * j * k / n) for j in range(n)) / math.sqrt(n) for k in range(n)]


def test_lattice_mask():
    m = lattice_mask(8, 4, 4, 1)
    assert [k for k in range(8) if m[2][k]] == [2, 6]
    assert all(sum(m[t][k] for t in range(4)) == 1 for k in range(8))
    for bad in ((8, 4, 4, 2), (6, 4, 4, 1)):
        try:
            lattice_mask(*bad)
            assert False
        except ValueError:
            pass


def test_alias_formula_by_brute_force():
    rng = random.Random(1)
    n, nt, r, shift = 8, 6, 2, 1
    x = rand_series(rng, nt, n)
    coils = [[rand_c(rng) for _ in range(n)] for _ in range(2)]
    mask = lattice_mask(n, nt, r, shift)
    for maps in (None, coils):
        alias = xf_alias(acquire(x, mask, maps))
        for c, cmap in enumerate(maps or [[1.0] * n]):
            weighted = [[cmap[y] * x[t][y] for y in range(n)] for t in range(nt)]
            # rho(y, f) by a direct sum, not by the code under test.
            rho = [[unitary_dft([weighted[t][y] for t in range(nt)])[f] for y in range(n)] for f in range(nt)]
            for y in range(n):
                for f in range(nt):
                    want = sum(rho[(f + j * shift * nt // r) % nt][(y + j * n // r) % n] for j in range(r)) / r
                    assert abs(alias[c][f][y] - want) < 1e-12


def test_groups_partition_the_grid():
    for n, nt, r, shift in ((8, 4, 2, 1), (12, 6, 3, 2), (16, 8, 4, 3)):
        seen = [p for g in alias_groups(n, nt, r, shift) for p in g]
        assert len(seen) == n * nt and len(set(seen)) == n * nt


def test_time_transform_round_trip():
    rng = random.Random(2)
    x = rand_series(rng, 6, 5)
    assert rel_err(time_ift(time_ft(x)), x) < 1e-14


def test_unfold_group_woodbury_form():
    rng = random.Random(3)
    nc, r, psi = 3, 2, 0.3
    a = [[rand_c(rng) for _ in range(r)] for _ in range(nc)]
    power = [0.7, 2.5]
    v = [rand_c(rng) for _ in range(nc)]
    got = unfold_group(a, power, psi, v)
    # (A^H A / psi + P^(-1))^(-1) A^H v / psi
    lhs = [[sum(a[i][p].conjugate() * a[i][q] for i in range(nc)) / psi + (1 / power[p] if p == q else 0) for q in range(r)] for p in range(r)]
    rhs = [sum(a[i][p].conjugate() * v[i] for i in range(nc)) / psi for p in range(r)]
    want = solve(lhs, rhs)
    assert max(abs(g - w) for g, w in zip(got, want)) < 1e-12
    assert unfold_group(a, [0.0, 0.0], 0.0, v) == [0j, 0j]


def test_one_signal_point_per_group_is_exact():
    n, nt, r, shift = 8, 8, 2, 1
    points = {(1, 1): 0.8, (6, 3): -0.5j, (3, 6): 0.4 + 0.2j}
    groups = alias_groups(n, nt, r, shift)
    owner = {p: i for i, g in enumerate(groups) for p in g}
    assert len({owner[p] for p in points}) == len(points)
    rho = [[0j] * n for _ in range(nt)]
    for (y, f), val in points.items():
        rho[f][y] = val
    dyn = time_ift(rho)
    x = [[dyn[t][y] + (1.0 if 2 <= y < 6 else 0.0) for y in range(n)] for t in range(nt)]
    mask = lattice_mask(n, nt, r, shift)
    out = k_t_blast(acquire(x, mask), mask, r, shift, training_power(x), 1e-12)
    assert rel_err(out, x) < 1e-9


def test_k_t_sense_with_r_coils_is_exact():
    rng = random.Random(4)
    n, nt, r = 8, 4, 2
    x = rand_series(rng, nt, n)
    coils = [[rand_c(rng) for _ in range(n)] for _ in range(r)]
    mask = lattice_mask(n, nt, r, 1)
    flat = [[1.0] * n for _ in range(nt)]
    out = k_t_blast(acquire(x, mask, coils), mask, r, 1, flat, 1e-13, coils, False)
    assert rel_err(out, x) < 1e-6


def test_full_sampling_and_static_series():
    rng = random.Random(5)
    n, nt = 6, 4
    x = rand_series(rng, nt, n)
    mask = lattice_mask(n, nt, 1, 1)
    out = k_t_blast(acquire(x, mask), mask, 1, 1, [[1.0] * n for _ in range(nt)], 1e-13, None, False)
    assert rel_err(out, x) < 1e-10
    static = [x[0]] * 4
    mask = lattice_mask(n, nt, 2, 1)
    zero = [[0.0] * n for _ in range(nt)]
    out = k_t_blast(acquire(static, mask), mask, 2, 1, zero, 0.1)
    assert rel_err(out, static) < 1e-12


def test_training_beats_a_flat_prior():
    n, nt, r = 32, 16, 4
    x = []
    for t in range(nt):
        a = 12 - 2.5 * math.cos(2 * math.pi * t / nt)
        b = 20 + 2.5 * math.cos(2 * math.pi * t / nt)
        frame = [0j] * n
        for y in range(4, 28):
            frame[y] = 1.0 + 1.0 / (1 + math.exp(-(y - a) / 0.6)) - 1.0 / (1 + math.exp(-(y - b) / 0.6))
        for y in range(24, 27):
            frame[y] += 0.5 * t / nt
        x.append(frame)
    mask = lattice_mask(n, nt, r, 1)
    data = acquire(x, mask)
    train = []
    for frame in x:
        k = unitary_dft(frame)
        k = [v if min(i, n - i) < 4 else 0j for i, v in enumerate(k)]
        train.append([sum(k[i] * cmath.exp(2j * math.pi * i * y / n) for i in range(n)) / math.sqrt(n) for y in range(n)])
    with_training = rel_err(k_t_blast(data, mask, r, 1, training_power(train), 1e-6), x)
    flat = rel_err(k_t_blast(data, mask, r, 1, [[1.0] * n for _ in range(nt)], 1e-9), x)
    assert with_training < 0.06 and flat > 0.13

History

Madore, Glover and Pelc introduced UNFOLD in 1999, which shifts the sampling from frame to frame so that aliases move along the temporal frequency axis. In the same year Pruessmann and coauthors published SENSE. In 2003 Tsao, Boesiger and Pruessmann joined the two ideas: lattice sampling in k-t space, aliases in x-f space, and an unfolding with a prior from training data, for one coil (k-t BLAST) and for several coils (k-t SENSE). Later work, such as k-t PCA in 2009, constrained the temporal signal further, and the compressed sensing and low rank methods of the following years removed the need for training data.

References

  1. Jeffrey Tsao, Peter Boesiger and Klaas P. Pruessmann, k-t BLAST and k-t SENSE, dynamic MRI with high frame rate exploiting spatiotemporal correlations, Magnetic Resonance in Medicine 50(5), 2003, 1031 to 1042, the lattice sampling in k-t space, the point spread function in x-f space, the reconstruction formula with the training estimate and the noise term, baseline subtraction, and the coil version (general locator)
  2. Bruno Madore, Gary H. Glover and Norbert J. Pelc, Unaliasing by Fourier-encoding the overlaps using the temporal dimension (UNFOLD), applied to cardiac imaging and fMRI, Magnetic Resonance in Medicine 42(5), 1999, 813 to 828, the shifted sampling in k-t space that moves aliases to other temporal frequencies (general locator)
  3. Henrik Pedersen, Sebastian Kozerke, Steffen Ringgaard, Kay Nehrke and Won Yong Kim, k-t PCA, temporally constrained k-t BLAST reconstruction using principal component analysis, Magnetic Resonance in Medicine 62(3), 2009, 706 to 716, the use of a temporal basis from the training data in the k-t BLAST 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