Algorithm Search⌘K

Algorithmresearch

Variational network

Also called variational network for MRI.

An unrolled gradient scheme for MRI whose regularizer filters and activation functions are learned from pairs of undersampled and full data.

Time
O(T (a + g)) worst
Space
O(c n) extra
Where
T = the number of stages; a = the cost of one call to A plus one call to its adjoint; c = the number of coils; g = the cost of one call to the learned regularizer of a stage (outside this page); n = the number of pixels
Properties
deterministicnot exactiterativelearned
Origin
Kerstin Hammernik, Teresa Klatzer, Erich Kobler, Michael P. Recht, Daniel K. Sodickson, Thomas Pock, Florian Knoll, 2018

The variational network (VN) reconstructs an image from undersampled MRI data with a fixed number TT of steps, each of which looks like one step of gradient descent on a regularized energy. In each step, a learned regularizer applies a set of filters to the image, passes the responses through learned activation functions and filters them back, and a learned weight scales the gradient of the data term. Hammernik et al. (2018) trained the filters, activations and weights of all steps together on pairs of undersampled and fully sampled knee scans. In compressed sensing MRI, the regularizer is chosen by hand, such as a wavelet ℓ1\ell_1 norm or total variation, and the iteration runs until it converges. In the VN, the regularizer is learned and the number of steps is fixed, as in other unrolled algorithms. With a fixed derivative activation, a step is a gradient step on a known energy. For a trained network there is no such energy, and the quality is measured.

In plain words

Compressed sensing MRI fills in missing k-space data by asking for an image that fits the data and looks "simple", for example one with few edges. The measure of "simple" is chosen by a person, and the solver needs many steps.

The variational network keeps the shape of that solver but runs only about ten steps. In each step, it measures local patterns in the image with a set of small filters. It then pushes the image away from the patterns it was trained to dislike, such as aliasing streaks, and pulls the image back toward the measured data. The filters, the push in each step and the pull strength are learned from scans where the full data are known. After training, a reconstruction is a fast fixed sequence of steps.

The problem

The input is the undersampled k-space data ff of one image with nn pixels, from cc coils, and the forward operator Au=(MF(sju))j=1cA u = (M F (s_j u))_{j=1}^c of SENSE, with the unitary 2D DFT FF, the sampling mask MM and the coil maps sjs_j. The other input is a trained network: a list of TT stages. Stage tt has a regularizer function rtr_t and a data weight μt≥0\mu_t \ge 0. In the VN, rtr_t has the form of the gradient of a fields of experts energy (Roth and Black 2009),

rt(u)=∑i=1Nk(Kit)Tϕit′(Kitu),r_t(u) = \sum_{i=1}^{N_k} (K_i^t)^T \phi_i^{t\prime}(K_i^t u),

where KitK_i^t is a filter that maps the complex image to a real image, (Ku)(p)=∑okoreRe⁡u(p+o)+koimIm⁡u(p+o)(K u)(p) = \sum_o k^{\text{re}}_o \operatorname{Re} u(p + o) + k^{\text{im}}_o \operatorname{Im} u(p + o), and ϕit′\phi_i^{t\prime} is a learned activation applied pixel by pixel. The output is the image uTu_T. The problem that the network tries to solve is the MRI reconstruction problem: find the image that produced ff. The network does not minimize a stated objective; it is trained so that uTu_T is close to the fully sampled image on the training data.

The algorithm

  1. VARIATIONALNETWORK(f, A, A*, stages (r_1, mu_1), ..., (r_T, mu_T))
  2. 1u <- A* f ▷ the zero filled, coil combined image
  3. 2for t = 1 to T do
  4. 3r <- r_t(u) ▷ learned: sum_i K_i^T phi_i'(K_i u)
  5. 4g <- A*(A u - f) ▷ gradient of (1/2)||A u - f||^2
  6. 5u <- u - r - mu_t g
  7. 6return u

This is Eq. 6 of Hammernik et al. A step size is not shown, because it is absorbed into the activations and into μt\mu_t. Compare it with one gradient step on E(u)=∑i∑pϕi((Kiu)(p))+λ2∥Au−f∥2E(u) = \sum_i \sum_p \phi_i((K_i u)(p)) + \frac{\lambda}{2}\|A u - f\|^2 with the step α\alpha:

u←u−α∑iKiTϕi′(Kiu)−αλA∗(Au−f).u \leftarrow u - \alpha \sum_i K_i^T \phi_i'(K_i u) - \alpha \lambda A^*(A u - f).

The two are the same if rtr_t uses the activations αϕi′\alpha \phi_i' and μt=αλ\mu_t = \alpha \lambda. With no regularizer, the scheme is the Landweber iteration. The VN unties the parameters: each stage has its own filters, activations and weight, so it is no longer a gradient method on one energy. The same idea, applied to image denoising, is the trainable reaction diffusion of Chen and Pock (2017).

In the paper, u0u_0 is the zero filled image, the coil maps are computed from the fully sampled k-space center, T=10T = 10, and each stage has Nk=48N_k = 48 filters of size 11×1111 \times 11 on the real and imaginary parts. Each activation is a weighted sum of 31 Gaussian radial basis functions on [−150,150][-150, 150]. The filters have zero mean and unit norm. The network has 131,050 parameters. They were trained on 200 images (20 slices from each of 10 patients) to minimize the mean squared error of smoothed magnitude images, with mini-batches of 10 for 1000 epochs. The training uses backpropagation through all ten stages.

Example

This example shows what the gradient step form of a stage does, without training. Take the modified Shepp-Logan phantom on 16×1616 \times 16 pixels, one coil and the 7 phase encoding rows 0, 1, 8, 9, 13, 14 and 15 of the unshifted k-space (rows 0, 1, 14 and 15 are the lowest frequencies). Use the four forward difference filters on the real and imaginary parts and the smooth absolute value ϕ(z)=z2+ε2\phi(z) = \sqrt{z^2 + \varepsilon^2} for all of them. Then EE is a smoothed total variation energy. Theorem 5 below allows the step α=1/(8/ε+λ)\alpha = 1/(8/\varepsilon + \lambda). The table gives the relative error of uTu_T and the energy E(uT)E(u_T) (measured with the code below).

stages ε\varepsilon λ\lambda step relative error E(uT)E(u_T)
0 (zero filling) 0.05 50 0.6165 96.62
10 0.05 50 α\alpha 0.5942 84.17
300 0.05 50 α\alpha 0.5086 83.02
10 0.05 200 α\alpha 0.5907
300 0.05 200 α\alpha 0.4476
10 0.1 50 α\alpha 0.5910
300 0.1 50 α\alpha 0.5447
10 0.05 50 5α5\alpha 0.7645 272
10 0.05 50 20α20\alpha diverges

With the safe step, the energy goes down at every stage (96.62 to 90.42 after the first one) as Theorem 5 says. But ten safe stages hardly improve on zero filling, because the safe step is small. Larger fixed steps make the energy go up, and twenty times the safe step diverges. A trained VN learns a separate step, filter set and activation for each stage, which lets ten stages do the work of hundreds. The quality of a trained network is not a property of this scheme. Hammernik et al. measured it on clinical knee data.

Correctness

For a trained network there is no correctness theorem: no energy that decreases, no convergence and no bound on the error. The network outputs whatever the ten stages compute, and its quality is a measurement on test data. What is proved, in full below, is this:

  • A stage is a gradient step. If the activations of stage tt are αϕi′\alpha \phi_i' for potentials ϕi\phi_i and μt=αλ\mu_t = \alpha\lambda, the stage is u−α∇E(u)u - \alpha \nabla E(u) for the fields of experts energy EE above (Theorem 2). Every activation is the derivative of its integral, so each trained stage is a gradient step on its own energy; but the energy changes from stage to stage.
  • Safe steps decrease the energy. For the forward difference filters, ∥∑iKiTKi∥≤8\|\sum_i K_i^T K_i\| \le 8. With ϕ(z)=z2+ε2\phi(z) = \sqrt{z^2 + \varepsilon^2} and ∥A∥≤1\|A\| \le 1, the gradient of EE is Lipschitz with the constant 8/ε+λ8/\varepsilon + \lambda, and for α≤1/(8/ε+λ)\alpha \le 1/(8/\varepsilon + \lambda) every stage lowers EE by at least ∥ut+1−ut∥2/(2α)\|u_{t+1} - u_t\|^2 / (2\alpha) (Theorem 5).
  • Landweber. With rt=0r_t = 0, the scheme is the Landweber iteration. With one coil, u0=A∗fu_0 = A^* f already fits the data, so the data term alone never changes the zero filled image.

Hammernik et al. report that the trained VN has a lower MSE and a higher SSIM than CG SENSE and a combined parallel imaging and compressed sensing reconstruction with total generalized variation (PI-CS TGV), on all tested knee sequences, for R=3R = 3 and R=4R = 4 with regular and variable density random sampling. These are measurements on their data. Larger benchmarks, such as fastMRI (Zbontar et al. 2018), are also measurements.

Proof: A variational network stage with derivative activations is a gradient step, and safe steps decrease a known energyfull

The setting is that of the algorithm. An image uu is a vector in CN\mathbb{C}^N with N=n1n2N = n_1 n_2. We use the real inner product ⟨u,v⟩R=Re⁡∑pu(p)‾v(p)\langle u, v \rangle_{\mathbb{R}} = \operatorname{Re} \sum_p \overline{u(p)} v(p), so CN\mathbb{C}^N is the real space R2N\mathbb{R}^{2N}, and gradients are taken in this space. The forward operator is Au=(MF(cju))jA u = (M F (c_j u))_{j} with the unitary 2D DFT FF, a 0/1 mask MM and coil maps cjc_j with ∑j∣cj(p)∣2≤1\sum_j |c_j(p)|^2 \le 1 at every pixel (one coil with c=1c = 1 if no maps are given). A stage is a pair (rt,μt)(r_t, \mu_t) of a function rtr_t and a number μt≥0\mu_t \ge 0, and the network computes

u0=A∗f,ut+1=ut−rt(ut)−μtA∗(Aut−f),t=0,…,T−1.u_0 = A^* f, \qquad u_{t+1} = u_t - r_t(u_t) - \mu_t A^*(A u_t - f), \quad t = 0, \ldots, T-1.

A trained network is a list of such stages. Nothing below is about training. It is about what one stage computes and about a special choice of stages for which the answer is known.

1. The operators

Lemma 1. ∥A∥≤1\|A\| \le 1. The function apply_ah is the adjoint of apply_a. For a filter (kre,kim)(k^{\text{re}}, k^{\text{im}}), the real image (Ku)(p)=∑okoreRe⁡u(p+o)+koimIm⁡u(p+o)(K u)(p) = \sum_o k^{\text{re}}_o \operatorname{Re} u(p + o) + k^{\text{im}}_o \operatorname{Im} u(p + o) has the adjoint (KTz)(q)=∑o(kore+ikoim)z(q−o)(K^T z)(q) = \sum_o (k^{\text{re}}_o + i k^{\text{im}}_o) z(q - o), that is, ∑p(Ku)(p)z(p)=⟨u,KTz⟩R\sum_p (K u)(p) z(p) = \langle u, K^T z \rangle_{\mathbb{R}} for every real image zz.

Proof. ∥Au∥2=∑j∥MF(cju)∥2≤∑j∥cju∥2=∑p∑j∣cj(p)∣2∣u(p)∣2≤∥u∥2\|A u\|^2 = \sum_j \|M F (c_j u)\|^2 \le \sum_j \|c_j u\|^2 = \sum_p \sum_j |c_j(p)|^2 |u(p)|^2 \le \|u\|^2, because FF is unitary and MM is a projection. The adjoint of u↦MF(cju)u \mapsto M F (c_j u) is y↦cˉjF∗Myy \mapsto \bar c_j F^* M y, and the adjoint of a stack is the sum, which is what apply_ah computes. For the filter, ∑pz(p)∑okoreRe⁡u(p+o)=∑qRe⁡u(q)∑okorez(q−o)\sum_p z(p) \sum_o k^{\text{re}}_o \operatorname{Re} u(p+o) = \sum_q \operatorname{Re} u(q) \sum_o k^{\text{re}}_o z(q - o) with q=p+oq = p + o, and the same holds for the imaginary part. Since ⟨u,a+ib⟩R=∑qRe⁡u(q) a(q)+Im⁡u(q) b(q)\langle u, a + i b \rangle_{\mathbb{R}} = \sum_q \operatorname{Re} u(q)\, a(q) + \operatorname{Im} u(q)\, b(q) for real images aa and bb, the claim follows. □\square

2. A stage is a gradient step when the activations are derivatives

Take filters K1,…,KmK_1, \ldots, K_m, potentials ϕi:R→R\phi_i : \mathbb{R} \to \mathbb{R} with continuous derivatives ϕi′\phi_i', a weight λ≥0\lambda \ge 0, and the energy

E(u)=∑i=1m∑pϕi((Kiu)(p))+λ2∥Au−f∥2.E(u) = \sum_{i=1}^m \sum_p \phi_i\big((K_i u)(p)\big) + \frac{\lambda}{2} \|A u - f\|^2.

Theorem 2. ∇E(u)=∑iKiTϕi′(Kiu)+λA∗(Au−f)\nabla E(u) = \sum_i K_i^T \phi_i'(K_i u) + \lambda A^*(A u - f), with ϕi′\phi_i' applied pixel by pixel. So if rt(u)=α∑iKiTϕi′(Kiu)r_t(u) = \alpha \sum_i K_i^T \phi_i'(K_i u) and μt=αλ\mu_t = \alpha \lambda, then ut+1=ut−α∇E(ut)u_{t+1} = u_t - \alpha \nabla E(u_t).

Proof. For a direction hh, the derivative of ∑pϕi((Kiu)(p))\sum_p \phi_i((K_i u)(p)) is ∑pϕi′((Kiu)(p))(Kih)(p)=⟨h,KiTϕi′(Kiu)⟩R\sum_p \phi_i'((K_i u)(p)) (K_i h)(p) = \langle h, K_i^T \phi_i'(K_i u) \rangle_{\mathbb{R}} by Lemma 1, because KiK_i is real linear. The derivative of 12∥Au−f∥2\frac12 \|A u - f\|^2 is Re⁡⟨Ah,Au−f⟩=⟨h,A∗(Au−f)⟩R\operatorname{Re} \langle A h, A u - f \rangle = \langle h, A^*(A u - f) \rangle_{\mathbb{R}}. □\square

Every continuous activation ψ\psi of one real variable is the derivative of ϕ(z)=∫0zψ(s) ds\phi(z) = \int_0^z \psi(s)\, ds. So each stage of a trained network of this form is a gradient step on its own energy EtE_t. But EtE_t changes from stage to stage, and its step is not limited, so the results of Section 3 do not apply to a trained network. This is the reason a trained network has no energy that decreases and no convergence theorem.

The test file checks Theorem 2 with central differences of EE for the forward difference filters, the potential ϕ(z)=z2+ε2\phi(z) = \sqrt{z^2 + \varepsilon^2}, two coils and a random mask.

3. Safe steps decrease the energy

The forward difference filters are K1u=DxRe⁡uK_1 u = D_x \operatorname{Re} u, K2u=DyRe⁡uK_2 u = D_y \operatorname{Re} u, K3u=DxIm⁡uK_3 u = D_x \operatorname{Im} u and K4u=DyIm⁡uK_4 u = D_y \operatorname{Im} u, where (Dxa)(i,j)=a(i,j+1)−a(i,j)(D_x a)(i, j) = a(i, j+1) - a(i, j) and (Dya)(i,j)=a(i+1,j)−a(i,j)(D_y a)(i, j) = a(i+1, j) - a(i, j), with periodic indices.

Lemma 3. ∥∑i=14KiTKi∥≤8\|\sum_{i=1}^4 K_i^T K_i\| \le 8.

Proof. By Lemma 1, K1Tz=DxTzK_1^T z = D_x^T z and K3Tz=iDxTzK_3^T z = i D_x^T z, and the same for DyD_y. So ∑iKiTKiu=LRe⁡u+iLIm⁡u\sum_i K_i^T K_i u = L \operatorname{Re} u + i L \operatorname{Im} u with L=DxTDx+DyTDyL = D_x^T D_x + D_y^T D_y. Each difference operator has norm at most 2, because ∥Dxa∥≤∥a(⋅,⋅+1)∥+∥a∥=2∥a∥\|D_x a\| \le \|a(\cdot, \cdot + 1)\| + \|a\| = 2 \|a\|. So ∥L∥≤4+4=8\|L\| \le 4 + 4 = 8, and the real and imaginary parts do not mix. □\square

Lemma 4. Let ϕ(z)=z2+ε2\phi(z) = \sqrt{z^2 + \varepsilon^2} with ε>0\varepsilon > 0 for all four filters. Then ∇E\nabla E is Lipschitz with the constant LE=8/ε+λL_E = 8/\varepsilon + \lambda.

Proof. ϕ′′(z)=ε2(z2+ε2)−3/2∈(0,1/ε]\phi''(z) = \varepsilon^2 (z^2 + \varepsilon^2)^{-3/2} \in (0, 1/\varepsilon], so ϕ′\phi' is Lipschitz with the constant 1/ε1/\varepsilon. Write Ku=(K1u,…,K4u)\mathcal{K} u = (K_1 u, \ldots, K_4 u), so that ∥K∥2=∥KTK∥=∥∑iKiTKi∥≤8\|\mathcal{K}\|^2 = \|\mathcal{K}^T \mathcal{K}\| = \|\sum_i K_i^T K_i\| \le 8 by Lemma 3. Then the regularizer part of the gradient is KTϕ′(Ku)\mathcal{K}^T \phi'(\mathcal{K} u), and

∥KT(ϕ′(Ku)−ϕ′(Kv))∥≤∥K∥⋅1ε∥K(u−v)∥≤8ε∥u−v∥.\|\mathcal{K}^T (\phi'(\mathcal{K} u) - \phi'(\mathcal{K} v))\| \le \|\mathcal{K}\| \cdot \frac1\varepsilon \|\mathcal{K}(u - v)\| \le \frac{8}{\varepsilon} \|u - v\|.

The data part λA∗A\lambda A^* A has norm at most λ\lambda by Lemma 1. □\square

Theorem 5. With the stages of Theorem 2 for this energy and 0<α≤1/LE0 < \alpha \le 1/L_E,

E(ut+1)≤E(ut)−12α∥ut+1−ut∥2E(u_{t+1}) \le E(u_t) - \frac{1}{2\alpha} \|u_{t+1} - u_t\|^2

for every tt. So E(ut)E(u_t) does not increase, and the sum of ∥ut+1−ut∥2\|u_{t+1} - u_t\|^2 over all stages is at most 2α(E(u0)−inf⁡E)2\alpha (E(u_0) - \inf E).

Proof. For a function with an LEL_E-Lipschitz gradient, E(u+h)≤E(u)+⟨∇E(u),h⟩R+LE2∥h∥2E(u + h) \le E(u) + \langle \nabla E(u), h \rangle_{\mathbb{R}} + \frac{L_E}{2} \|h\|^2 (the descent lemma, from the integral form of the remainder). With g=∇E(ut)g = \nabla E(u_t) and h=−αgh = -\alpha g, this gives E(ut+1)≤E(ut)−α(1−αLE/2)∥g∥2≤E(ut)−α2∥g∥2E(u_{t+1}) \le E(u_t) - \alpha (1 - \alpha L_E / 2) \|g\|^2 \le E(u_t) - \frac{\alpha}{2} \|g\|^2, and α2∥g∥2=12α∥ut+1−ut∥2\frac{\alpha}{2} \|g\|^2 = \frac{1}{2\alpha} \|u_{t+1} - u_t\|^2. The energy is bounded below by 0, which gives the sum. □\square

The test file checks the inequality of Theorem 5 at every stage with α=1/LE\alpha = 1/L_E. The bound α≤1/LE\alpha \le 1/L_E is sufficient, not necessary. With five times this step, the example on the page shows the energy go up, and with twenty times it diverges.

4. Two further facts

Lemma 6 (no regularizer). If rt=0r_t = 0 for all tt, the network is the Landweber iteration ut+1=ut−μtA∗(Aut−f)u_{t+1} = u_t - \mu_t A^*(A u_t - f) from u0=A∗fu_0 = A^* f. With one coil, c=1c = 1 and f=Mff = M f (data only on the mask), u0u_0 fits the data exactly, so ut=u0u_t = u_0 for every tt.

Proof. The first claim is the definition. With one coil, AA∗=MFF∗M=MA A^* = M F F^* M = M, so Au0−f=Mf−f=0A u_0 - f = M f - f = 0, the correction is zero, and the iterates do not move. □\square

So with one coil, data consistency alone never improves on zero filling. All the change from u0u_0 comes from the regularizer.

Lemma 7 (call counts). A network of TT stages calls each rtr_t once, AA exactly TT times and A∗A^* exactly T+1T + 1 times.

Proof. Line L1 calls A∗A^* once, and each pass of the loop calls rtr_t, AA and A∗A^* once each. □\square

Complexity

The model is real-ram. Line L1 calls A∗A^* once. Each of the TT stages calls the regularizer rtr_t once, AA once and A∗A^* once. So the time is O(T(a+g))O(T(a + g)), where aa is the cost of one call to AA and one to A∗A^*, and gg is the cost of one regularizer. For cc coils with the FFT, a=O(c nlog⁡n)a = O(c\, n \log n). The cost of the regularizer depends on the network and is outside this page. For NkN_k filters of size s×ss \times s applied directly, and activations made of NwN_w basis functions, it is O(Nk(s2+Nw)n)O(N_k (s^2 + N_w) n). The extra space is O(c n)O(c\, n) for the residual in k-space. Training needs the gradient through all TT stages, which costs a constant times the forward pass and stores all TT intermediate images. Hammernik et al. report 193 ms per slice on one GPU (measurement).

Properties

  • Fixed cost. The number of stages is fixed, so the run time does not depend on the data or on a stopping rule.
  • Data consistency in every stage. Each stage uses the true operator AA with the coil maps, so the network knows the acquisition and does not learn it.
  • Interpretable stages. The filters and activations of each stage can be plotted, and with derivative activations a stage is a gradient step.
  • Deterministic. For given weights, the output is a fixed function of the data.
  • Not monotone. A trained network need not lower any energy from one stage to the next.

Variants and improvements

  • Trainable reaction diffusion. Chen and Pock (2017) used the same stage form for denoising, with learned filters and influence functions in each step. The VN adds the MRI forward operator and complex images.
  • Other unrolled schemes. Learned primal-dual unrolls a primal-dual method with small networks in place of the proximal steps. LISTA unrolls ISTA for sparse coding. Later networks for MRI replace the fields of experts regularizer by a general convolutional network and keep the data consistency step. These are described on the algorithm unrolling page.
  • Plug and play. Plug-and-play priors put a trained denoiser inside a fixed iteration that runs until it converges, and do not train the steps end to end.
  • Learned energies. Bilevel learning of regularizers learns the parameters of one energy that is then minimized to convergence. Then the theorems for gradient methods, such as those of FISTA, apply again.

When to use it

Use a VN when many scans of the same kind (protocol, anatomy and sampling pattern) are available with fully sampled references, and the reconstruction must be fast. It suits clinical protocols where the same sequence runs many times. When there are no training data, or the scan type differs from the training data, use a hand-made regularizer, such as compressed sensing MRI or low rank plus sparse MRI for dynamic data.

Pitfalls

  • Change of distribution. A network trained on one contrast, field strength, coil array or sampling pattern can fail on another, and the failure may look like a plausible image.
  • Hallucinated detail. The learned regularizer can add structures that are not in the data, or remove small lesions. Check results against the data residual and against a classical reconstruction.
  • Coil maps. Errors in the coil maps enter every stage through AA. In the paper, they come from the fully sampled k-space center.
  • No convergence. Running more stages than were trained does not converge to anything and usually makes the image worse.
  • Fixed step sizes. As the example shows, a gradient step that is too large makes the energy go up, and even larger steps diverge. Training learns steps that work for its data, without a guarantee.
  • Quality metrics. MSE and SSIM of magnitude images do not measure diagnostic value. A lower error on a test set does not show that the images are safe to read.

Implementations

The network is a given input: the code takes the stages (rt,μt)(r_t, \mu_t) as functions and numbers, and the operators AA and A∗A^* as functions, and runs lines L1 to L6 around them. It does not train a network, and no weights are downloaded. The tests build the stages by hand from the forward difference filters and the activation αϕ′\alpha \phi' of ϕ(z)=z2+ε2\phi(z) = \sqrt{z^2 + \varepsilon^2}, or as simple fixed maps. The tests check the adjoint of AA with and without coils, the adjoint of a random complex-to-real filter, the bound 8 for the forward difference filters, that one stage equals the gradient step on the known energy (with central differences), the energy decrease of Theorem 5 at every stage, the call counts (TT regularizer calls, TT calls to AA, T+1T + 1 calls to A∗A^*), and the Landweber case.

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
variational_network_mri.py 150 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/variational-network-mri/. The authors are listed in prov/THXH29.jsonl.

"""The variational network (Hammernik et al. 2018) as an unrolled gradient scheme.

The network is given. This module does not train it. A stage t is a pair
(reg_t, lam_t): reg_t is a function that maps an image u to the image
sum_i K_i^T phi'_i(K_i u), and lam_t >= 0 weights the data term. The
forward pass is

    u_0 = A^* f,   u_{t+1} = u_t - reg_t(u_t) - lam_t A^*(A u_t - f).

An image is an n1 x n2 complex image, stored row-major as one list. The
operator A maps u to the coil k-space M F_u (c_j u) on the full grid, with
the unitary 2D DFT F_u, a 0/1 mask M and coil maps c_j (one coil, c = 1, if
no maps are given).

Fields of experts terms: a filter is a pair of real kernels (k_re, k_im),
each a dict {(di, dj): weight} on periodic offsets, and

    (K u)(p) = sum_o k_re[o] Re u(p + o) + k_im[o] Im u(p + o),

a real image, as in Hammernik et al. Its adjoint for the real inner product
Re <u, v> maps a real image z to sum_o (k_re[o] + i k_im[o]) z(p - o).
With a potential phi and its derivative dphi, foe_regularizer builds reg_t
and foe_energy evaluates sum_i sum_p phi_i((K_i u)(p)).
"""

import math

from imgkit import dft2, idft2, unflatten


# ------------------------------------------------------------------ the data term


def _fu2(img, n1, n2):
    s = 1.0 / math.sqrt(n1 * n2)
    return [v * s for row in dft2(unflatten(img, n1, n2)) for v in row]


def _fu2h(k, n1, n2):
    s = math.sqrt(n1 * n2)
    return [v * s for row in idft2(unflatten(k, n1, n2)) for v in row]


def make_operator(mask, n1, n2, coils=None):
    """The pair (A, A^*) for one frame, as functions."""
    maps = coils or [None]

    def apply_a(u):
        out = []
        for cmap in maps:
            img = u if cmap is None else [c * v for c, v in zip(cmap, u)]
            out.append([v if m else 0j for v, m in zip(_fu2(img, n1, n2), mask)])
        return out

    def apply_ah(data):
        acc = [0j] * (n1 * n2)
        for cmap, k in zip(maps, data):
            img = _fu2h([v if m else 0j for v, m in zip(k, mask)], n1, n2)
            if cmap is None:
                acc = [a + v for a, v in zip(acc, img)]
            else:
                acc = [a + c.conjugate() * v for a, c, v in zip(acc, cmap, img)]
        return acc

    return apply_a, apply_ah


# ------------------------------------------------------------------ fields of experts


def filter_apply(kernel, u, n1, n2):
    """(K u)(p) = sum_o k_re[o] Re u(p + o) + k_im[o] Im u(p + o), periodic."""
    k_re, k_im = kernel
    out = [0.0] * (n1 * n2)
    for i in range(n1):
        for j in range(n2):
            s = 0.0
            for (di, dj), w in k_re.items():
                s += w * u[((i + di) % n1) * n2 + (j + dj) % n2].real
            for (di, dj), w in k_im.items():
                s += w * u[((i + di) % n1) * n2 + (j + dj) % n2].imag
            out[i * n2 + j] = s
    return out


def filter_adjoint(kernel, z, n1, n2):
    """K^T z for the real inner product: sum_o (k_re[o] + i k_im[o]) z(p - o)."""
    k_re, k_im = kernel
    out = [0j] * (n1 * n2)
    for i in range(n1):
        for j in range(n2):
            v = z[i * n2 + j]
            if v == 0:
                continue
            for (di, dj), w in k_re.items():
                q = ((i + di) % n1) * n2 + (j + dj) % n2
                out[q] += w * v
            for (di, dj), w in k_im.items():
                q = ((i + di) % n1) * n2 + (j + dj) % n2
                out[q] += 1j * w * v
    return out


def forward_differences():
    """Four filters: forward differences along rows and columns of Re u and of Im u."""
    dx = {(0, 0): -1.0, (0, 1): 1.0}
    dy = {(0, 0): -1.0, (1, 0): 1.0}
    return [(dx, {}), (dy, {}), ({}, dx), ({}, dy)]


def foe_regularizer(kernels, dphis, n1, n2):
    """The function u -> sum_i K_i^T dphi_i(K_i u)."""

    def reg(u):
        acc = [0j] * (n1 * n2)
        for kernel, dphi in zip(kernels, dphis):
            z = [dphi(v) for v in filter_apply(kernel, u, n1, n2)]
            acc = [a + b for a, b in zip(acc, filter_adjoint(kernel, z, n1, n2))]
        return acc

    return reg


def foe_energy(u, kernels, phis, n1, n2):
    """sum_i sum_p phi_i((K_i u)(p))."""
    return sum(sum(phi(v) for v in filter_apply(kernel, u, n1, n2)) for kernel, phi in zip(kernels, phis))


# ------------------------------------------------------------------ the network


def variational_network(f, stages, apply_a, apply_ah, history=None):
    """Run the given stages [(reg_t, lam_t), ...] on the data f.

    If history is a list, u_0, ..., u_T are appended to it.
    """
    u = apply_ah(f)  # @line L1
    if history is not None:
        history.append(u)
    for reg, lam in stages:  # @line L2
        r = reg(u)  # @line L3
        resid = [[a - b for a, b in zip(ac, fc)] for ac, fc in zip(apply_a(u), f)]  # @line L4
        g = apply_ah(resid)
        u = [x - rr - lam * gg for x, rr, gg in zip(u, r, g)]  # @line L5
        if history is not None:
            history.append(u)
    return u  # @line L6
test_variational_network_mri.py 173 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/variational-network-mri/. The authors are listed in prov/THXH29.jsonl.

import math
import random

from variational_network_mri import (
    filter_adjoint,
    filter_apply,
    foe_energy,
    foe_regularizer,
    forward_differences,
    make_operator,
    variational_network,
)

N1, N2 = 6, 5


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


def rand_image(rng):
    return [rand_c(rng) for _ in range(N1 * N2)]


def rand_mask(rng):
    return [1 if rng.random() < 0.5 else 0 for _ in range(N1 * N2)]


def two_coils(rng):
    c1, c2 = [], []
    for _ in range(N1 * N2):
        a, b = rand_c(rng), rand_c(rng)
        s = math.sqrt(abs(a) ** 2 + abs(b) ** 2)
        c1.append(a / s)
        c2.append(b / s)
    return [c1, c2]


def re_inner(u, v):
    return sum((a.conjugate() * b).real for a, b in zip(u, v))


def charbonnier(eps):
    return (lambda z: math.sqrt(z * z + eps * eps)), (lambda z: z / math.sqrt(z * z + eps * eps))


def energy(u, f, apply_a, lam, eps):
    phi, _ = charbonnier(eps)
    kern = forward_differences()
    fit = sum(abs(a - b) ** 2 for ac, fc in zip(apply_a(u), f) for a, b in zip(ac, fc))
    return foe_energy(u, kern, [phi] * 4, N1, N2) + 0.5 * lam * fit


def gradient_stage(alpha, lam, eps):
    """One stage that is alpha times the gradient of energy(., lam, eps)."""
    _, dphi = charbonnier(eps)
    reg = foe_regularizer(forward_differences(), [lambda z: alpha * dphi(z)] * 4, N1, N2)
    return reg, alpha * lam


def test_operator_adjoint():
    rng = random.Random(1)
    mask = rand_mask(rng)
    for coils in (None, two_coils(rng)):
        apply_a, apply_ah = make_operator(mask, N1, N2, coils)
        u = rand_image(rng)
        y = [rand_image(rng) for _ in range(1 if coils is None else 2)]
        lhs = sum(sum(a.conjugate() * b for a, b in zip(ac, yc)) for ac, yc in zip(apply_a(u), y))
        rhs = sum(a.conjugate() * b for a, b in zip(u, apply_ah(y)))
        assert abs(lhs - rhs) < 1e-10 * abs(lhs)


def test_filter_adjoint():
    rng = random.Random(2)
    kernel = (
        {(di, dj): rng.gauss(0, 1) for di in (-1, 0, 1) for dj in (-1, 0, 1)},
        {(di, dj): rng.gauss(0, 1) for di in (-1, 0, 1) for dj in (0, 2)},
    )
    u = rand_image(rng)
    z = [rng.gauss(0, 1) for _ in range(N1 * N2)]
    lhs = sum(a * b for a, b in zip(filter_apply(kernel, u, N1, N2), z))
    rhs = re_inner(u, filter_adjoint(kernel, z, N1, N2))
    assert abs(lhs - rhs) < 1e-10 * abs(lhs)


def test_forward_difference_filter_norm():
    # sum_i K_i^T K_i is minus the periodic Laplacian on Re u and on Im u; its norm is at most 8.
    rng = random.Random(3)
    kern = forward_differences()
    u = rand_image(rng)
    for _ in range(30):
        v = [0j] * (N1 * N2)
        for k in kern:
            w = filter_adjoint(k, filter_apply(k, u, N1, N2), N1, N2)
            v = [a + b for a, b in zip(v, w)]
        nv = math.sqrt(re_inner(v, v))
        u = [a / nv for a in v]
    assert 0 < nv <= 8 + 1e-9


def test_stage_is_a_gradient_step_on_a_known_energy():
    rng = random.Random(4)
    mask = rand_mask(rng)
    coils = two_coils(rng)
    apply_a, apply_ah = make_operator(mask, N1, N2, coils)
    f = apply_a(rand_image(rng))
    u0 = rand_image(rng)
    alpha, lam, eps = 0.01, 3.0, 0.5
    reg, lam_t = gradient_stage(alpha, lam, eps)
    hist = []

    def ah_start(data):
        return u0 if data is f else apply_ah(data)

    variational_network(f, [(reg, lam_t)], apply_a, ah_start, hist)
    grad = [(a - b) / alpha for a, b in zip(hist[0], hist[1])]
    for _ in range(3):
        h = rand_image(rng)
        s = 1e-5
        plus = energy([a + s * b for a, b in zip(u0, h)], f, apply_a, lam, eps)
        minus = energy([a - s * b for a, b in zip(u0, h)], f, apply_a, lam, eps)
        assert abs((plus - minus) / (2 * s) - re_inner(grad, h)) < 1e-5 * (1 + abs(re_inner(grad, h)))


def test_energy_decreases_for_safe_steps():
    rng = random.Random(5)
    mask = rand_mask(rng)
    apply_a, apply_ah = make_operator(mask, N1, N2)
    f = apply_a(rand_image(rng))
    lam, eps = 4.0, 0.2
    alpha = 1.0 / (8.0 / eps + lam)
    hist = []
    variational_network(f, [gradient_stage(alpha, lam, eps)] * 8, apply_a, apply_ah, hist)
    for u, v in zip(hist, hist[1:]):
        step = sum(abs(a - b) ** 2 for a, b in zip(u, v))
        assert energy(v, f, apply_a, lam, eps) <= energy(u, f, apply_a, lam, eps) - step / (2 * alpha) + 1e-9


def test_call_counts():
    rng = random.Random(6)
    apply_a, apply_ah = make_operator(rand_mask(rng), N1, N2)
    calls = {"a": 0, "ah": 0, "net": 0}

    def a(u):
        calls["a"] += 1
        return apply_a(u)

    def ah(d):
        calls["ah"] += 1
        return apply_ah(d)

    def net(u):
        calls["net"] += 1
        return [0.1 * v for v in u]

    f = apply_a(rand_image(rng))
    u = variational_network(f, [(net, 0.5)] * 7, a, ah)
    assert calls == {"a": 7, "ah": 8, "net": 7}
    assert len(u) == N1 * N2


def test_no_regularizer_is_landweber():
    rng = random.Random(7)
    apply_a, apply_ah = make_operator(rand_mask(rng), N1, N2)
    f = apply_a(rand_image(rng))
    zero = lambda u: [0j] * len(u)
    u = variational_network(f, [(zero, 0.7)] * 3, apply_a, apply_ah)
    # u_0 = A^* f is consistent with the data, so Landweber steps keep it.
    u0 = apply_ah(f)
    assert max(abs(a - b) for a, b in zip(u, u0)) < 1e-12

History

Roth and Black introduced the fields of experts prior in 2005, with a journal version in 2009: an image energy that is a sum of potentials of the responses of learned filters. Chen and Pock (2015 on arXiv, 2017 in print) unrolled a few gradient steps on such energies, learned the filters and the influence functions of each step separately, and obtained fast and accurate denoising. Hammernik, Klatzer, Kobler, Recht, Sodickson, Pock and Knoll put the MRI forward operator into these steps and trained the result on clinical knee data, first shown at ISMRM 2016 and published in 2018. The fastMRI data set of Zbontar et al. (2018) then gave a common benchmark, and many later unrolled networks for MRI follow the same pattern of learned regularizer steps and data consistency steps.

References

  1. Kerstin Hammernik, Teresa Klatzer, Erich Kobler, Michael P. Recht, Daniel K. Sodickson, Thomas Pock and Florian Knoll, Learning a variational network for reconstruction of accelerated MRI data, Magnetic Resonance in Medicine 79(6), 2018, 3055 to 3071 (arXiv 1704.00447), in the arXiv version 1704.00447v1, Eq. 4 to 6 for the energy and the stage update, the Methods section for the filters, the activation functions, the coil maps and the training, and Table 1 for the measured MSE and SSIM against CG SENSE and PI-CS TGV
  2. Yunjin Chen and Thomas Pock, Trainable nonlinear reaction diffusion, a flexible framework for fast and effective image restoration, IEEE Transactions on Pattern Analysis and Machine Intelligence 39(6), 2017, pages 1256 to 1272 (the gradient steps with learned filters and influence functions per step that the variational network builds on)
  3. Stefan Roth and Michael J. Black, Fields of experts, International Journal of Computer Vision 82(2), 2009, pages 205 to 229 (the fields of experts prior, a sum of potentials of filter responses)
  4. Jure Zbontar and coauthors, fastMRI, an open dataset and benchmarks for accelerated MRI, arXiv 1811.08839, 2018, the knee data set and the baseline measurements (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