Algorithm Search⌘K

Algorithmresearch

SVD clutter filter

Also called spatiotemporal SVD clutter filter.

Separate blood from tissue echoes by removing the largest singular components of the space by slow time Casorati matrix of the data.

Time
O(M N^2 + N^3) worst
Space
O(M N + N^2) extra
Where
M = the number of pixels; N = the number of frames (the ensemble length)
Properties
deterministicnot exactnot linear in dataiterative
Origin
Charlie Demene, Thomas Deffieux, Mathieu Pernot, Mickael Tanter, 2015

The SVD clutter filter separates the echo of blood from the much stronger echo of tissue in ultrasound Doppler data. It stacks the NN complex frames of an acquisition into the Casorati matrix SS, with one row per pixel and one column per frame, and computes its singular value decomposition. Tissue moves slowly and together over large regions, so it fills the first few singular components, which hold almost all the energy. Blood moves fast and decorrelates in space, so it lies in the middle components, and noise in the last ones. The filter removes the first k1k_1 components, and optionally the components after k2k_2, and keeps Sf=∑j=k1+1k2σjujvjHS_f = \sum_{j = k_1 + 1}^{k_2} \sigma_j u_j v_j^H. The power of SfS_f at each pixel is the power Doppler image. Unlike a high-pass filter on each pixel, the SVD filter uses the spatial coherence of tissue, and it removes tissue that moves as fast as blood. It needs many frames per pixel, which plane wave compounding gives at thousands of frames per second. The cut-off ranks k1k_1 and k2k_2 are choices, not outputs of the method.

In plain words

Each pixel of an ultrasound movie has a signal over time. Tissue gives a strong signal that changes slowly, and the tissue in one region moves together, so many pixels show the same pattern in time. Blood gives a weak signal that changes fast and differs from pixel to pixel.

Put all the pixel signals in a table, one row per pixel and one column per frame. The singular value decomposition splits the table into layers, from the strongest pattern shared by many pixels to the weakest. The first few layers are tissue, because tissue is strong and moves together. The filter deletes them and keeps the rest, which is mostly blood and noise. The number of layers to delete is a setting that the user picks.

The problem

Input. A stack of NN complex IQ frames xt(i,j)x_t(i, j), t=0…N−1t = 0 \ldots N-1, of MM pixels each, and two cut-off ranks 0≤k1≤k2≤N0 \le k_1 \le k_2 \le N.

Model. The data are the sum of a tissue part, a blood part and noise. The tissue echo is often tens of decibels stronger than the blood echo, and in a single pixel its Doppler spectrum can overlap that of slow blood, for example when the tissue moves with breathing or with the hand of the operator. A filter that acts on each slow time signal alone must separate the two by frequency. The SVD filter also uses the fact that tissue motion is coherent over many pixels.

Output. The filtered frames, with the tissue removed, and the power Doppler image PD(p)=1N∑t∣Sf(p,t)∣2\mathrm{PD}(p) = \frac{1}{N} \sum_t |S_f(p, t)|^2.

The algorithm

  1. SVD-CLUTTER-FILTER(frames x_0 … x_{N-1}, k1, k2)
  2. 1S ← M × N Casorati matrix, row p = slow time signal of pixel p
  3. 2C ← S^H S ▷ N × N Gram matrix
  4. 3(σ_j^2, v_j) ← eigenpairs of C, σ_1 ≥ … ≥ σ_N ▷ right singular vectors of S
  5. 4check 0 ≤ k1 ≤ k2 ≤ N ▷ the cut-off ranks are chosen by the user
  6. 5P ← Σ_{j=k1+1}^{k2} v_j v_j^H ▷ projector onto the kept components
  7. 6S_f ← S P ▷ = Σ_{j=k1+1}^{k2} σ_j u_j v_j^H
  8. 7PD(p) ← (1/N) Σ_t |S_f[p, t]|^2 ▷ power Doppler image
  9. 8return frames of S_f, PD

The number of frames NN is much smaller than the number of pixels MM (for example 200 frames and 10410^4 pixels), so lines L2 and L3 solve a small N×NN \times N eigenproblem in place of the SVD of the large matrix. Line L6 never needs the left singular vectors uju_j. The Python code computes the eigenpairs of the complex Hermitian matrix CC with a real symmetric eigensolver applied to the real 2N×2N2N \times 2N matrix (Re⁡C−Im⁡CIm⁡CRe⁡C)\begin{pmatrix} \operatorname{Re} C & -\operatorname{Im} C \\ \operatorname{Im} C & \operatorname{Re} C \end{pmatrix}, whose eigenvalues are those of CC, each twice. The velocity image follows from SfS_f with the Kasai estimator.

Example

Tissue that moves as fast as blood. Take three pixels and N=4N = 4 frames. Two tissue pixels have the amplitude 10 and the phase turns by a quarter turn per pulse, e1=(1,i,−1,−i)e_1 = (1, i, -1, -i), a Doppler frequency of +PRF/4+\mathrm{PRF}/4. The blood pixel has the amplitude 1 and turns the other way, e3=(1,−i,−1,i)e_3 = (1, -i, -1, i), a Doppler frequency of −PRF/4-\mathrm{PRF}/4:

S=(1010i−10−10i1010i−10−10i1−i−1i).S = \begin{pmatrix} 10 & 10i & -10 & -10i \\ 10 & 10i & -10 & -10i \\ 1 & -i & -1 & i \end{pmatrix}.

Both frequencies have the same magnitude, so a filter that removes frequencies near zero, or one that is symmetric in frequency, cannot remove the tissue and keep the blood. The vectors e1e_1 and e3e_3 are orthogonal: ∑te3(t)e1(t)‾=1−1+1−1=0\sum_t e_3(t) \overline{e_1(t)} = 1 - 1 + 1 - 1 = 0. So

C=SHS=200 e1‾e1T+e3‾e3TC = S^H S = 200\, \overline{e_1} e_1^T + \overline{e_3} e_3^T

has the eigenvalues 200⋅4=800200 \cdot 4 = 800 and 44, and 0 twice. The singular values are σ1=202=28.28\sigma_1 = 20\sqrt{2} = 28.28 and σ2=2\sigma_2 = 2. With k1=1k_1 = 1 and k2=4k_2 = 4, P=I−v1v1HP = I - v_1 v_1^H with v1=e1‾/2v_1 = \overline{e_1}/2. A tissue row gives e1TP=e1T−(e1Te1‾/2)(e1T/2)=e1T−e1T=0e_1^T P = e_1^T - (e_1^T \overline{e_1}/2)(e_1^T/2) = e_1^T - e_1^T = 0, and the blood row gives e3Tv1=0e_3^T v_1 = 0, so it is unchanged. The power Doppler values change from (100,100,1)(100, 100, 1) to (0,0,1)(0, 0, 1). The code returns these values up to rounding.

A simulated vessel. The test simulates 8 by 6 pixels and 16 frames: tissue speckle with amplitude 10 and a slow common motion everywhere, a vessel of two rows with weak blood that decorrelates from pulse to pulse, and white noise. The first singular value holds 99.7 percent of the energy. The mean power Doppler inside the vessel divided by the mean outside is 0.10 without the filter, 130 with k1=1k_1 = 1, 35 with k1=2k_1 = 2 and 22 with k1=3k_1 = 3. In this simulation the tissue is close to rank one, and a cut that is too high removes blood.

Correctness

By the orthonormality of the right singular vectors, Svl=σlulS v_l = \sigma_l u_l, so line L6 gives Sf=∑j=k1+1k2σjujvjHS_f = \sum_{j = k_1+1}^{k_2} \sigma_j u_j v_j^H and ∥Sf∥F2=∑j=k1+1k2σj2\|S_f\|_F^2 = \sum_{j = k_1+1}^{k_2} \sigma_j^2. With k2=Nk_2 = N the removed part S−SfS - S_f is the truncated SVD of rank k1k_1, which by the Eckart-Young theorem is the matrix of rank at most k1k_1 closest to SS in the Frobenius norm. This is a theorem about energy: the filter removes the rank k1k_1 structure that explains the most energy. It is a heuristic that this structure is tissue.

The separation is exact in one case. Let S=T+BS = T + B where the tissue part TT has rank k1k_1, the columns of TT and BB are orthogonal (tissue and blood occupy orthogonal spatial patterns, for example disjoint pixels), and the rows of TT and BB are orthogonal (orthogonal slow time patterns, for example tones on disjoint DFT bins). Then the SVDs of TT and BB together form an SVD of SS, and if every singular value of TT exceeds every singular value of BB, the filter with k1k_1 returns Sf=BS_f = B exactly. If the parts overlap in both space and time, the singular vectors mix them and some blood is removed with the tissue.

The filter is equivariant under unitary changes of the pixels and of slow time: the data ΠSW\Pi S W give ΠSfW\Pi S_f W. A common shift of all Doppler frequencies is such a WW, so the filter does not select by frequency. The real embedding used by the code has the eigenvalues of CC with doubled multiplicity, and its projector has Re⁡P\operatorname{Re} P and Im⁡P\operatorname{Im} P as its left blocks, so line L5 is computed correctly whenever the cuts fall between distinct singular values. The proofs are in proofs/correctness.md.

Proof: The SVD clutter filter removes the best rank k1 approximation of the Casorati matrix, separates tissue exactly when tissue and blood are orthogonal in space and slow time, and is computed correctly through the real embedding of the Gram matrixfull

Notation. SS is the M×NM \times N complex Casorati matrix (pixels by slow time), with the thin SVD S=∑j=1NσjujvjHS = \sum_{j=1}^{N} \sigma_j u_j v_j^H, σ1≥⋯≥σN≥0\sigma_1 \ge \dots \ge \sigma_N \ge 0, orthonormal uj∈CMu_j \in \mathbb{C}^M and orthonormal vj∈CNv_j \in \mathbb{C}^N (if M<NM < N, some σj\sigma_j are zero and the uju_j for them are any completion; they do not appear in the results). For 0≤k1≤k2≤N0 \le k_1 \le k_2 \le N let P=∑j=k1+1k2vjvjHP = \sum_{j = k_1 + 1}^{k_2} v_j v_j^H (line L5) and Sf=SPS_f = S P (line L6). The norm is the Frobenius norm.

Lemma 1 (the filter is a band of singular components). Sf=∑j=k1+1k2σjujvjHS_f = \sum_{j = k_1 + 1}^{k_2} \sigma_j u_j v_j^H, and ∥Sf∥2=∑j=k1+1k2σj2\|S_f\|^2 = \sum_{j = k_1 + 1}^{k_2} \sigma_j^2.

Proof. Svl=∑jσjuj(vjHvl)=σlulS v_l = \sum_j \sigma_j u_j (v_j^H v_l) = \sigma_l u_l by orthonormality, so SP=∑l=k1+1k2σlulvlHS P = \sum_{l = k_1+1}^{k_2} \sigma_l u_l v_l^H. The terms are orthogonal in the Frobenius inner product, since tr⁡((ujvjH)HulvlH)=(ujHul)(vlHvj)=δjl\operatorname{tr}((u_j v_j^H)^H u_l v_l^H) = (u_j^H u_l)(v_l^H v_j) = \delta_{jl}, which gives the norm. □\square

So with k2=Nk_2 = N the filter removes Sk1=∑j≤k1σjujvjHS_{k_1} = \sum_{j \le k_1} \sigma_j u_j v_j^H, and the removed energy is ∥S−Sf∥2=∑j≤k1σj2\|S - S_f\|^2 = \sum_{j \le k_1} \sigma_j^2.

Theorem 1 (the removed part is the best rank k1 fit). For every complex M×NM \times N matrix RR of rank at most k1k_1, ∥S−R∥2≥∑j>k1σj2=∥S−Sk1∥2\|S - R\|^2 \ge \sum_{j > k_1} \sigma_j^2 = \|S - S_{k_1}\|^2. This is the theorem of Eckart and Young (1936).

Proof. Weyl's inequality for singular values, σi+j−1(A+B)≤σi(A)+σj(B)\sigma_{i + j - 1}(A + B) \le \sigma_i(A) + \sigma_j(B), follows from the Courant-Fischer minimax characterization of σi\sigma_i. Apply it with A=S−RA = S - R, B=RB = R and j=k1+1j = k_1 + 1: since σk1+1(R)=0\sigma_{k_1 + 1}(R) = 0, σi+k1(S)≤σi(S−R)\sigma_{i + k_1}(S) \le \sigma_i(S - R) for every i≥1i \ge 1. Squaring and summing over ii gives ∥S−R∥2=∑iσi(S−R)2≥∑iσi+k1(S)2\|S - R\|^2 = \sum_i \sigma_i(S - R)^2 \ge \sum_{i} \sigma_{i + k_1}(S)^2. By Lemma 1 the bound is attained by R=Sk1R = S_{k_1}. □\square

So the filter models the tissue as the rank k1k_1 matrix closest to the data, and the blood and noise as the rest. This is a statement about energy. It does not say that the removed part is tissue; Theorem 2 gives a condition under which it is.

Theorem 2 (exact separation). Let S=T+BS = T + B where TT has rank k1k_1 and (a) THB=0T^H B = 0, that is the columns of TT and of BB are orthogonal in pixel space, and (b) TBH=0T B^H = 0, that is the rows of TT and of BB are orthogonal in slow time. If the smallest nonzero singular value of TT is larger than the largest singular value of BB, then the filter with k2=Nk_2 = N returns Sf=BS_f = B.

Proof. Let T=∑j=1k1τjajxjHT = \sum_{j=1}^{k_1} \tau_j a_j x_j^H and B=∑lβlblylHB = \sum_l \beta_l b_l y_l^H be SVDs. Condition (a) gives ajHbl=0a_j^H b_l = 0 for all j,lj, l (multiply THB=0T^H B = 0 by xjx_j on the left and yly_l on the right, after dividing by τjβl>0\tau_j \beta_l > 0). Condition (b) gives xjHyl=0x_j^H y_l = 0 in the same way. So the sets {aj}∪{bl}\{a_j\} \cup \{b_l\} and {xj}∪{yl}\{x_j\} \cup \{y_l\} are orthonormal, and S=∑jτjajxjH+∑lβlblylHS = \sum_j \tau_j a_j x_j^H + \sum_l \beta_l b_l y_l^H is an SVD of SS. Since every τj\tau_j exceeds every βl\beta_l, the first k1k_1 right singular vectors span the same space as the xjx_j (if some singular values are equal inside the tissue part or inside the blood part, the choice of basis inside that part does not change the span). So I−PI - P is the orthogonal projector onto the span of the xjx_j, and SP=S−T(I−P)−B(I−P)=S−T=BS P = S - T(I - P) - B(I - P) = S - T = B, because T(I−P)=TT(I - P) = T and Bxj=0B x_j = 0 by (b). □\square

Both conditions are needed. Disjoint supports in space give (a), and Doppler frequencies on disjoint sets of DFT bins of length NN give (b). If tissue and blood share pixels and slow time content, the singular vectors mix the two, and part of the blood is removed with the tissue. A Doppler frequency filter would need (b) and a frequency gap; the SVD filter needs (a) and (b) and an energy gap, but no frequency gap: Lemma 3 shows that it does not see frequencies as such.

Lemma 2 (the real embedding). For a Hermitian N×NN \times N matrix C=A+iBC = A + iB (AA real symmetric, BB real antisymmetric), let E(C)=(A−BBA)E(C) = \begin{pmatrix} A & -B \\ B & A \end{pmatrix}. Then EE is a real algebra homomorphism, E(C)E(C) is real symmetric, every eigenvalue λ\lambda of CC is an eigenvalue of E(C)E(C) with twice the multiplicity, and for an orthogonal projector PP onto an invariant subspace of CC, E(P)E(P) is the orthogonal projector onto the sum of the corresponding eigenspaces of E(C)E(C). In particular Re⁡P\operatorname{Re} P and Im⁡P\operatorname{Im} P are the left blocks of that real projector.

Proof. Identify z=p+iq∈CNz = p + iq \in \mathbb{C}^N with z^=(p,q)∈R2N\hat z = (p, q) \in \mathbb{R}^{2N}. A direct computation gives Cz^=E(C)z^\widehat{C z} = E(C) \hat z, and E(C1C2)=E(C1)E(C2)E(C_1 C_2) = E(C_1) E(C_2), E(CH)=E(C)TE(C^H) = E(C)^T. If Cz=λzC z = \lambda z with real λ\lambda, then E(C)z^=λz^E(C) \hat z = \lambda \hat z and E(C)iz^=λiz^E(C) \widehat{iz} = \lambda \widehat{iz}, with iz^=(−q,p)\widehat{iz} = (-q, p) orthogonal to z^\hat z. An orthonormal eigenbasis z1,…,zNz_1, \dots, z_N of CC gives the orthonormal basis z^j,izj^\hat z_j, \widehat{i z_j} of R2N\mathbb{R}^{2N} (the real inner product of z^\hat z and w^\hat w is Re⁡(zHw)\operatorname{Re}(z^H w)), so the spectrum of E(C)E(C) is that of CC with doubled multiplicity. E(P)E(P) is real symmetric and idempotent because PP is Hermitian and idempotent, and it maps z^j\hat z_j and izj^\widehat{i z_j} to themselves or to 0 as PP maps zjz_j. □\square

The code applies Lemma 2 to C=SHSC = S^H S (line L2), whose eigenvalues are σj2\sigma_j^2 with eigenvectors vjv_j. If σk1>σk1+1\sigma_{k_1} > \sigma_{k_1 + 1} and σk2>σk2+1\sigma_{k_2} > \sigma_{k_2 + 1}, the real eigenvectors number 2k1+12 k_1 + 1 to 2k22 k_2 of E(C)E(C) in descending order span exactly the embedding of the span of vk1+1,…,vk2v_{k_1 + 1}, \dots, v_{k_2}, whatever real basis the eigensolver returns inside a pair. Their real projector is E(P)E(P), and line L5 reads PP from its left blocks. If a cut falls inside a group of equal singular values, PP is not defined by the data; this is a property of the problem, not of the method of computation.

Lemma 3 (invariances). Let Π\Pi be an M×MM \times M unitary matrix (for example a permutation of the pixels times a common phase) and WW an N×NN \times N unitary matrix (for example the diagonal matrix diag⁡(eiωt)\operatorname{diag}(e^{i \omega t}), a shift of every Doppler frequency by ω\omega). Then the filter maps ΠSW\Pi S W to ΠSfW\Pi S_f W.

Proof. ΠSW=∑jσj(Πuj)(WHvj)H\Pi S W = \sum_j \sigma_j (\Pi u_j)(W^H v_j)^H is an SVD with the same singular values, and the right singular vectors are WHvjW^H v_j. So P′=WHPWP' = W^H P W and ΠSWP′=ΠSPW=ΠSfW\Pi S W P' = \Pi S P W = \Pi S_f W. □\square

So the result depends neither on the order of the pixels nor on a common shift of the Doppler frequencies. A tissue echo that moves fast is removed as long as it is strong and coherent in space, and blood that is slow is kept as long as it is weak and incoherent in space.

Theorem 3 (cost). Lines L1 to L8 cost O(MN2+N3)O(M N^2 + N^3) operations in the real-RAM model with an eigensolver that is counted as O(N3)O(N^3) to working precision, and O(MN+N2)O(M N + N^2) space.

Proof. Line L2 forms N2N^2 inner products of length MM. Line L3 is an eigenproblem of size 2N2N, which a fixed number of Jacobi sweeps or a tridiagonal QR method solves in O(N3)O(N^3). Line L5 forms N2N^2 entries, each a sum of at most 2N2N products, O(N3)O(N^3). Line L6 is an M×NM \times N by N×NN \times N product, O(MN2)O(M N^2). Line L7 is O(MN)O(M N). The matrices SS, SfS_f, CC and PP need O(MN+N2)O(M N + N^2) space. □\square

Complexity

With MM pixels and NN frames, line L2 costs O(MN2)O(M N^2), line L3 costs O(N3)O(N^3) with a dense eigensolver to working precision, line L5 costs O(N3)O(N^3) and line L6 costs O(MN2)O(M N^2). The total is O(MN2+N3)O(M N^2 + N^3) time, which is O(MN2)O(M N^2) because N≤MN \le M in practice, and O(MN+N2)O(M N + N^2) space. A filter that acts on each pixel alone with a fixed number of taps costs O(MN)O(M N), so the SVD filter is more expensive by a factor of order NN. A partial eigensolver such as the Lanczos algorithm or a randomized SVD lowers the cost when k1k_1 and N−k2N - k_2 are small.

Properties

  • Best rank k1k_1 removal (theorem). The removed part is the best rank k1k_1 approximation of the data in the Frobenius norm, and the kept energy is ∑j=k1+1k2σj2\sum_{j = k_1+1}^{k_2} \sigma_j^2.
  • Exact separation (theorem) when tissue and blood are orthogonal in space and in slow time and the tissue singular values are the largest.
  • Not tied to frequency. A common frequency shift of the data shifts the output in the same way. Fast tissue motion is removed if it is coherent in space.
  • Independent of the pixel order. A permutation of the rows of SS permutes the rows of SfS_f; the filter does not use the positions of the pixels, only the correlations between their signals.
  • Data adaptive and nonlinear. The projector depends on the data, so the filter is not a linear time-invariant filter, and its frequency response changes from one acquisition to the next.
  • Needs many coherent frames. With N=8N = 8 to 16 frames, as in conventional color flow imaging, the tissue and blood subspaces are hard to tell apart; with hundreds of frames from ultrafast imaging the gain over frequency filters is large (Demene et al. 2015, a measurement on in vivo data).

Variants and improvements

  • Choice of the cut-off ranks. Fixed ranks, a threshold on the decay of the singular values, the mean Doppler frequency of each right singular vector, and the similarity of the spatial singular vectors (Baranger et al. 2018) are all used. Each is a heuristic.
  • Block-wise filtering. Splitting the image into overlapping blocks and filtering each one alone adapts the cut-off to local tissue motion and reduces the cost of each SVD.
  • Higher order SVD of a pixels by slow time by ensemble tensor, used when several acquisitions are combined.
  • Low rank plus sparse models. Robust PCA writes the data as a low rank part plus a sparse part and solves a convex problem, as in low-rank plus sparse MRI. It replaces the hard cut of rank by a penalty, at the cost of an iterative solver.
  • Eigenvector regression filters. In conventional color flow imaging, the eigenvectors of the slow time correlation matrix estimated over a region define a projection filter for each pixel; this is the same idea with a smaller NN.

When to use it

Use the SVD clutter filter for ultrafast Doppler and functional ultrasound, where plane wave imaging gives hundreds of frames per second per pixel and the blood signal is weak, as in small vessels or in the brain. Use it when the tissue moves, since a high-pass filter then either leaves tissue or removes slow blood. For conventional color flow imaging with short ensembles, a frequency filter of the kind reviewed by Bjaerum, Torp and Kristoffersen (2002) is cheaper. Use a robust PCA model when a sparse foreground (for example a contrast agent bubble) must be kept apart from the low rank background.

Pitfalls

  • Cut-off too high. Strong blood that is coherent over many pixels, as in a large vessel, appears in the first components and is removed with the tissue. In the test simulation the vessel contrast falls from 130 to 22 when k1k_1 goes from 1 to 3.
  • Cut-off too low. Tissue that moves in several independent ways (breathing and the pulse, for example) needs more than one component, and a small k1k_1 leaves tissue that the Kasai estimator then reads as slow flow.
  • Ties in the singular values. If σk1=σk1+1\sigma_{k_1} = \sigma_{k_1+1}, the filter is not defined by the data, and a small change of the data changes the output a lot. Choose cuts at gaps in the singular value curve.
  • Too few frames. With NN near the number of tissue components, there is no room for blood in the remaining subspace.
  • Cost of a full SVD. Computing all M×NM \times N singular vectors is not needed; form the N×NN \times N Gram matrix or use a partial eigensolver.
  • Gram matrix accuracy. Forming SHSS^H S squares the condition number, so singular values below about 10−8σ110^{-8} \sigma_1 lose their accuracy in double precision. This matters for the noise cut k2k_2, not for the tissue cut. Use the SVD of SS when the small singular values matter.

Implementations

The Python code builds the Casorati matrix, forms the Gram matrix and finds its eigenpairs with the real symmetric Jacobi eigensolver of the shared imgla helper through the real embedding. The tests compare the result with the SVD of the real embedding of SS from imgla, check exact separation for orthogonal tissue and blood, the removed energy and the best rank fit, the noise cut, the invariances under a pixel permutation, a global phase and a frequency shift, and the vessel contrast on simulated data.

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.

imgla.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/.
"""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
svd_clutter_filter.py 159 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/svd-clutter-filter/. The authors are listed in prov/BBV2DJ.jsonl.
"""The spatiotemporal SVD clutter filter of ultrafast Doppler ultrasound.

The input is a stack of N complex IQ frames frames[t][i][j] (slow time t,
depth i, lateral position j). The Casorati matrix S has one row per pixel and
one column per frame. With the singular values sigma_1 >= sigma_2 >= ... and
the right singular vectors v_j of S, the filter keeps the components k1 + 1 to
k2 (1-based):

    S_f = S P,  P = sum_{j = k1 + 1}^{k2} v_j v_j^H,

which equals sum_{j = k1 + 1}^{k2} sigma_j u_j v_j^H. The first k1 components
are the tissue (clutter) and the components after k2 are noise. The cut-off
ranks k1 and k2 are choices of the user, not outputs of the method.

The right singular vectors are the eigenvectors of the N x N Gram matrix
C = S^H S. This module finds them with the real symmetric eigensolver of
imgla, applied to the real 2N x 2N matrix [[Re C, -Im C], [Im C, Re C]].
"""

import cmath
import math
import random

from imgla import sym_eig


def casorati(frames):
    """The Casorati matrix: row p = i * nx + j holds the slow time samples of pixel (i, j)."""
    nt, nz, nx = len(frames), len(frames[0]), len(frames[0][0])
    return [[frames[t][i][j] for t in range(nt)] for i in range(nz) for j in range(nx)]


def frames_of(s, nz, nx):
    """The inverse of casorati: the list of frames of a pixels by slow time matrix."""
    nt = len(s[0])
    return [[[s[i * nx + j][t] for j in range(nx)] for i in range(nz)] for t in range(nt)]


def gram(s):
    """C = S^H S, the N x N Hermitian Gram matrix of the slow time columns."""
    n = len(s[0])
    c = [[0j] * n for _ in range(n)]
    for row in s:
        conj = [v.conjugate() for v in row]
        for a in range(n):
            ca, cr = conj[a], c[a]
            for b in range(n):
                cr[b] += ca * row[b]
    return c


def _embedded_eig(c):
    """Eigenpairs of the real embedding of a Hermitian C, eigenvalues in descending order.

    Each eigenvalue of C appears twice. The eigenvectors are the columns of the
    returned 2N x 2N real matrix.
    """
    n = len(c)
    emb = [[c[i][j].real for j in range(n)] + [-c[i][j].imag for j in range(n)] for i in range(n)]
    emb += [[c[i][j].imag for j in range(n)] + [c[i][j].real for j in range(n)] for i in range(n)]
    w, q = sym_eig(emb)
    order = list(range(2 * n - 1, -1, -1))
    return [w[k] for k in order], [[row[k] for k in order] for row in q]


def _projector(q, n, lo, hi):
    """The complex N x N projector onto the right singular vectors lo + 1 .. hi (1-based).

    The real columns 2 lo .. 2 hi - 1 of q span the embedding of that complex
    subspace. Their real projector is [[Re P, -Im P], [Im P, Re P]], so P is read
    from its left blocks.
    """
    cols = range(2 * lo, 2 * hi)
    p = [[0j] * n for _ in range(n)]
    for a in range(n):
        qa, qia = q[a], q[n + a]
        for b in range(n):
            qb = q[b]
            re = sum(qa[m] * qb[m] for m in cols)
            im = sum(qia[m] * qb[m] for m in cols)
            p[a][b] = complex(re, im)
    return p


def singular_values(s):
    """The singular values of S in descending order (the square roots of the eigenvalues of S^H S)."""
    w, _ = _embedded_eig(gram(s))
    return [math.sqrt(max(0.0, w[2 * j])) for j in range(len(s[0]))]


def svd_filter_matrix(s, tissue_cut, noise_cut=None):
    """Filter a Casorati matrix. Returns (S_f, sigma) with S_f = S P as in the module text."""
    n = len(s[0])
    hi = n if noise_cut is None else noise_cut
    if not 0 <= tissue_cut <= hi <= n:
        raise ValueError("need 0 <= tissue_cut <= noise_cut <= number of frames")
    c = gram(s)  # @line L2
    w, q = _embedded_eig(c)  # @line L3
    sigma = [math.sqrt(max(0.0, w[2 * j])) for j in range(n)]
    p = _projector(q, n, tissue_cut, hi)  # @line L5
    sf = [[sum(row[a] * p[a][b] for a in range(n)) for b in range(n)] for row in s]  # @line L6
    return sf, sigma


def svd_clutter_filter(frames, tissue_cut, noise_cut=None):
    """Filter a stack of IQ frames. Returns (filtered frames, power Doppler image, sigma).

    tissue_cut = k1 components are removed as tissue; components after
    noise_cut = k2 are removed as noise (None keeps all of them).
    """
    nt, nz, nx = len(frames), len(frames[0]), len(frames[0][0])
    s = casorati(frames)  # @line L1
    if not 0 <= tissue_cut <= (nt if noise_cut is None else noise_cut) <= nt:  # @line L4
        raise ValueError("need 0 <= tissue_cut <= noise_cut <= number of frames")
    sf, sigma = svd_filter_matrix(s, tissue_cut, noise_cut)
    pd = [[sum(abs(v) ** 2 for v in sf[i * nx + j]) / nt for j in range(nx)] for i in range(nz)]  # @line L7
    return frames_of(sf, nz, nx), pd, sigma  # @line L8


def simulate(nz, nx, nt, vessel_rows, seed, tissue_amp=10.0, blood_amp=1.0, noise=0.05, prf=1.0):
    """A small synthetic ultrafast Doppler acquisition.

    Tissue: a speckle field of strong amplitude in every pixel (scaled by 0.3
    inside the vessel, for the vessel wall and side lobes), moved by a slow
    common axial motion (breathing), so its phase changes smoothly in slow time
    with a small depth dependence. Blood: weak speckle in
    the rows of vessel_rows, with Doppler frequencies that follow a parabolic
    profile across the vessel and decorrelate from pulse to pulse (a random phase
    step with standard deviation 0.5 rad per pulse). Noise: white,
    complex Gaussian. Returns (frames, vessel_mask).
    """
    rng = random.Random(seed)

    def cgauss(sig):
        return complex(rng.gauss(0.0, sig / math.sqrt(2.0)), rng.gauss(0.0, sig / math.sqrt(2.0)))

    tissue = [[cgauss(tissue_amp) for _ in range(nx)] for _ in range(nz)]
    blood = [[cgauss(blood_amp) for _ in range(nx)] for _ in range(nz)]
    lo, hi = vessel_rows
    mid, half = 0.5 * (lo + hi - 1), 0.5 * (hi - lo) + 0.5
    mask = [[lo <= i < hi for _ in range(nx)] for i in range(nz)]
    frames = []
    for t in range(nt):
        motion = 0.6 * math.sin(2.0 * math.pi * t / (2.0 * nt))
        frame = []
        for i in range(nz):
            row = []
            for j in range(nx):
                val = tissue[i][j] * cmath.exp(1j * motion * (1.0 + 0.1 * i / nz))
                if mask[i][j]:
                    fd = 0.3 * prf * (1.0 - ((i - mid) / half) ** 2)
                    blood[i][j] *= cmath.exp(1j * rng.gauss(0.0, 0.5))
                    val = 0.3 * val + blood[i][j] * cmath.exp(2j * math.pi * fd * t / prf)
                row.append(val + cgauss(noise))
            frame.append(row)
        frames.append(frame)
    return frames, mask
test_svd_clutter_filter.py 161 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/svd-clutter-filter/. The authors are listed in prov/BBV2DJ.jsonl.

import cmath
import math
import random

from imgla import svd
from svd_clutter_filter import (casorati, frames_of, simulate, singular_values, svd_clutter_filter,
                                svd_filter_matrix)


def _cgauss(rng, sig=1.0):
    return complex(rng.gauss(0.0, sig), rng.gauss(0.0, sig))


def _rand(rng, m, n):
    return [[_cgauss(rng) for _ in range(n)] for _ in range(m)]


def _fro2(a):
    return sum(abs(v) ** 2 for row in a for v in row)


def _diff2(a, b):
    return sum(abs(x - y) ** 2 for ra, rb in zip(a, b) for x, y in zip(ra, rb))


def test_matches_the_reference_svd_of_the_real_embedding() -> None:
    # Reference: imgla.svd of [[Re S, -Im S], [Im S, Re S]], whose singular values
    # are those of S, each twice; removing its top 2k terms removes the top k of S.
    rng = random.Random(6201)
    m, n, k = 20, 7, 2
    s = _rand(rng, m, n)
    emb = [[v.real for v in r] + [-v.imag for v in r] for r in s] + [[v.imag for v in r] + [v.real for v in r] for r in s]
    u, sv, v = svd(emb)
    sigma = singular_values(s)
    for j in range(n):
        assert abs(sigma[j] - sv[2 * j]) < 1e-9 * sv[0]
        assert abs(sigma[j] - sv[2 * j + 1]) < 1e-9 * sv[0]
    ref = [[emb[i][j] - sum(sv[q] * u[i][q] * v[j][q] for q in range(2 * k)) for j in range(2 * n)] for i in range(2 * m)]
    sf, _ = svd_filter_matrix(s, k)
    for i in range(m):
        for j in range(n):
            assert abs(sf[i][j] - complex(ref[i][j], ref[m + i][j])) < 1e-9 * sv[0]


def test_exact_separation_when_tissue_and_blood_are_orthogonal() -> None:
    # Tissue in rows 0, 1, 4, 5 with slow time tones on DFT bins 0 and 1; blood in
    # rows 2, 3 with tones on bins 3 to 7. The two parts are orthogonal in space and
    # in slow time, and the tissue singular values are the largest ones.
    nz, nx, nt = 6, 4, 8
    rng = random.Random(6202)
    tissue_rows, vessel = (0, 1, 4, 5), (2, 3)
    a = [[_cgauss(rng, 5.0) if i in tissue_rows else 0j for j in range(nx)] for i in range(nz)]
    b = [[_cgauss(rng, 4.0) if i in tissue_rows else 0j for j in range(nx)] for i in range(nz)]
    blood_bin = [[3 + (i * nx + j) % 5 for j in range(nx)] for i in range(nz)]
    blood_amp = [[_cgauss(rng, 0.3) if i in vessel else 0j for j in range(nx)] for i in range(nz)]
    frames, blood = [], []
    for t in range(nt):
        e0, e1 = 1.0, cmath.exp(2j * math.pi * t / nt)
        bl = [[blood_amp[i][j] * cmath.exp(2j * math.pi * blood_bin[i][j] * t / nt) for j in range(nx)]
              for i in range(nz)]
        blood.append(bl)
        frames.append([[a[i][j] * e0 + b[i][j] * e1 + bl[i][j] for j in range(nx)] for i in range(nz)])
    out, _, sigma = svd_clutter_filter(frames, 2)
    assert sigma[1] > 5 * sigma[2]
    for t in range(nt):
        for i in range(nz):
            for j in range(nx):
                assert abs(out[t][i][j] - blood[t][i][j]) < 1e-9


def test_removed_energy_is_the_tail_and_no_rank_k_matrix_does_better() -> None:
    rng = random.Random(6203)
    m, n = 18, 6
    s = _rand(rng, m, n)
    sigma = singular_values(s)
    for k in range(n + 1):
        sf, _ = svd_filter_matrix(s, k)
        assert abs(_fro2(sf) - sum(x * x for x in sigma[k:])) < 1e-9 * _fro2(s)
        assert abs(_diff2(s, sf) - sum(x * x for x in sigma[:k])) < 1e-9 * _fro2(s)
    # S - S_f is the best rank-k approximation: random rank-one competitors fit worse.
    sf, _ = svd_filter_matrix(s, 1)
    best = _fro2(sf)
    for _ in range(30):
        x = [_cgauss(rng) for _ in range(m)]
        y = [_cgauss(rng) for _ in range(n)]
        # the best scalar for the direction x y^H, so each competitor is fitted
        num = sum(x[i].conjugate() * s[i][j] * y[j] for i in range(m) for j in range(n))
        den = sum(abs(v) ** 2 for v in x) * sum(abs(v) ** 2 for v in y)
        g = num / den
        resid = sum(abs(s[i][j] - g * x[i] * y[j].conjugate()) ** 2 for i in range(m) for j in range(n))
        assert resid >= best - 1e-9


def test_noise_cut_keeps_the_middle_band() -> None:
    rng = random.Random(6204)
    s = _rand(rng, 15, 6)
    sigma = singular_values(s)
    sf, _ = svd_filter_matrix(s, 1, 4)
    assert abs(_fro2(sf) - sum(x * x for x in sigma[1:4])) < 1e-9 * _fro2(s)
    full, _ = svd_filter_matrix(s, 0)
    assert _diff2(full, s) < 1e-18 * _fro2(s)


def test_pixel_order_and_global_phase_do_not_matter() -> None:
    rng = random.Random(6205)
    s = _rand(rng, 12, 5)
    sf, _ = svd_filter_matrix(s, 2)
    perm = list(range(12))
    rng.shuffle(perm)
    g = 0.7 * cmath.exp(0.9j)
    sp, _ = svd_filter_matrix([[g * v for v in s[p]] for p in perm], 2)
    for r, p in enumerate(perm):
        for t in range(5):
            assert abs(sp[r][t] - g * sf[p][t]) < 1e-9


def test_a_frequency_shift_of_all_echoes_gives_the_shifted_output() -> None:
    # Multiplying slow time sample t by exp(i w t) is a unitary change of the
    # columns, so the filter output is shifted in the same way. The SVD filter
    # separates by energy and spatial coherence, not by Doppler frequency.
    rng = random.Random(6206)
    s = _rand(rng, 14, 6)
    w = 1.3
    shifted = [[v * cmath.exp(1j * w * t) for t, v in enumerate(row)] for row in s]
    sf, _ = svd_filter_matrix(s, 2)
    ss, _ = svd_filter_matrix(shifted, 2)
    for row_f, row_s in zip(sf, ss):
        for t in range(6):
            assert abs(row_s[t] - row_f[t] * cmath.exp(1j * w * t)) < 1e-9


def test_casorati_round_trip() -> None:
    rng = random.Random(6207)
    frames = [[[_cgauss(rng) for _ in range(3)] for _ in range(4)] for _ in range(5)]
    s = casorati(frames)
    assert len(s) == 12 and len(s[0]) == 5
    assert s[1 * 3 + 2][4] == frames[4][1][2]
    assert frames_of(s, 4, 3) == frames


def test_power_doppler_contrast_on_a_simulated_vessel() -> None:
    nz, nx, nt = 8, 6, 16
    frames, mask = simulate(nz, nx, nt, (3, 5), seed=6208)

    def contrast(pd):
        inside = [pd[i][j] for i in range(nz) for j in range(nx) if mask[i][j]]
        outside = [pd[i][j] for i in range(nz) for j in range(nx) if not mask[i][j]]
        return (sum(inside) / len(inside)) / (sum(outside) / len(outside))

    _, raw, sigma = svd_clutter_filter(frames, 0)
    _, pd1, _ = svd_clutter_filter(frames, 1)
    _, pd3, _ = svd_clutter_filter(frames, 3)
    # The tissue is strong and close to rank one: sigma_1 holds almost all the energy.
    assert sigma[0] ** 2 > 0.95 * sum(x * x for x in sigma)
    assert contrast(raw) < 0.5
    assert contrast(pd1) > 50.0
    # A cut-off rank that is too high also removes blood.
    assert contrast(pd3) < contrast(pd1)

History

Clutter filters for color flow imaging act on each slow time signal, for example with FIR, IIR or polynomial regression filters (Bjaerum, Torp and Kristoffersen 2002). Ledoux, Brands and Hoeks (1997) used the singular value decomposition to reduce clutter in simulated Doppler signals. With ultrafast plane wave imaging, long ensembles at every pixel became available, and Demene et al. (2015) applied the SVD to the Casorati matrix of all pixels and frames, which raised the sensitivity of Doppler and functional ultrasound. Baranger et al. (2018) proposed an adaptive choice of the cut-off ranks from the spatial singular vectors.

References

  1. Charlie Demene, Thomas Deffieux, Mathieu Pernot, Bruno-Felix Osmanski, Valerie Biran, Jean-Luc Gennisson, Lim-Anna Sieu, Antoine Bergel, Stephanie Franqui, Jean-Michel Correas, Ivan Cohen, Olivier Baud and Mickael Tanter, Spatiotemporal clutter filtering of ultrafast ultrasound data highly increases Doppler and fUltrasound sensitivity, IEEE Transactions on Medical Imaging 34(11), 2015, 2271 to 2285, the Casorati matrix of the ultrafast data, its singular value decomposition, and the removal of the tissue singular components (general locator)
  2. L. A. F. Ledoux, P. J. Brands and A. P. G. Hoeks, Reduction of the clutter component in Doppler ultrasound signals based on singular value decomposition: a simulation study, Ultrasonic Imaging 19(1), 1997, 1 to 18, the first use of the singular value decomposition for Doppler clutter reduction (general locator)
  3. Jerome Baranger, Bastien Arnal, Fabienne Perren, Olivier Baud, Mickael Tanter and Charlie Demene, Adaptive spatiotemporal SVD clutter filtering for ultrafast Doppler imaging using similarity of spatial singular vectors, IEEE Transactions on Medical Imaging 37(7), 2018, 1574 to 1586, the choice of the cut-off ranks from the similarity of the spatial singular vectors (general locator)
  4. S. Bjaerum, H. Torp and K. Kristoffersen, Clutter filter design for ultrasound color flow imaging, IEEE Transactions on Ultrasonics, Ferroelectrics and Frequency Control 49(2), 2002, 204 to 216, the conventional clutter filters that act on each slow time signal separately (general locator)
  5. Carl Eckart and Gale Young, The approximation of one matrix by another of lower rank, Psychometrika 1(3), 1936, 211 to 218, the best approximation of lower rank by truncating the singular value form

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