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)
- Model
- Real RAM
- Properties
- deterministicnot exactnot linear in dataiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 complex frames of an acquisition into the Casorati matrix , 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 components, and optionally the components after , and keeps . The power of 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 and 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 complex IQ frames , , of pixels each, and two cut-off ranks .
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 .
The algorithm
SVD-CLUTTER-FILTER(frames x_0 … x_{N-1}, k1, k2)- 1
S ← M × N Casorati matrix, row p = slow time signal of pixel p - 2
C ← S^H S ▷ N × N Gram matrix - 3
(σ_j^2, v_j) ← eigenpairs of C, σ_1 ≥ … ≥ σ_N ▷ right singular vectors of S - 4
check 0 ≤ k1 ≤ k2 ≤ N ▷ the cut-off ranks are chosen by the user - 5
P ← Σ_{j=k1+1}^{k2} v_j v_j^H ▷ projector onto the kept components - 6
S_f ← S P ▷ = Σ_{j=k1+1}^{k2} σ_j u_j v_j^H - 7
PD(p) ← (1/N) Σ_t |S_f[p, t]|^2 ▷ power Doppler image - 8
return frames of S_f, PD
The number of frames is much smaller than the number of pixels (for example 200 frames and pixels), so lines L2 and L3 solve a small eigenproblem in place of the SVD of the large matrix. Line L6 never needs the left singular vectors . The Python code computes the eigenpairs of the complex Hermitian matrix with a real symmetric eigensolver applied to the real matrix , whose eigenvalues are those of , each twice. The velocity image follows from with the Kasai estimator.
Example
Tissue that moves as fast as blood. Take three pixels and frames. Two tissue pixels have the amplitude 10 and the phase turns by a quarter turn per pulse, , a Doppler frequency of . The blood pixel has the amplitude 1 and turns the other way, , a Doppler frequency of :
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 and are orthogonal: . So
has the eigenvalues and , and 0 twice. The singular values are and . With and , with . A tissue row gives , and the blood row gives , so it is unchanged. The power Doppler values change from to . 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 , 35 with and 22 with . 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, , so line L6 gives and . With the removed part is the truncated SVD of rank , which by the Eckart-Young theorem is the matrix of rank at most closest to in the Frobenius norm. This is a theorem about energy: the filter removes the rank structure that explains the most energy. It is a heuristic that this structure is tissue.
The separation is exact in one case. Let where the tissue part has rank , the columns of and are orthogonal (tissue and blood occupy orthogonal spatial patterns, for example disjoint pixels), and the rows of and are orthogonal (orthogonal slow time patterns, for example tones on disjoint DFT bins). Then the SVDs of and together form an SVD of , and if every singular value of exceeds every singular value of , the filter with returns 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 give . A common shift of all Doppler frequencies is such a , so the filter does not select by frequency. The real embedding used by the code has the eigenvalues of with doubled multiplicity, and its projector has and 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. is the complex Casorati matrix (pixels by slow time), with the thin SVD , , orthonormal and orthonormal (if , some are zero and the for them are any completion; they do not appear in the results). For let (line L5) and (line L6). The norm is the Frobenius norm.
Lemma 1 (the filter is a band of singular components). , and .
Proof. by orthonormality, so . The terms are orthogonal in the Frobenius inner product, since , which gives the norm.
So with the filter removes , and the removed energy is .
Theorem 1 (the removed part is the best rank k1 fit). For every complex matrix of rank at most , . This is the theorem of Eckart and Young (1936).
Proof. Weyl's inequality for singular values, , follows from the Courant-Fischer minimax characterization of . Apply it with , and : since , for every . Squaring and summing over gives . By Lemma 1 the bound is attained by .
So the filter models the tissue as the rank 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 where has rank and (a) , that is the columns of and of are orthogonal in pixel space, and (b) , that is the rows of and of are orthogonal in slow time. If the smallest nonzero singular value of is larger than the largest singular value of , then the filter with returns .
Proof. Let and be SVDs. Condition (a) gives for all (multiply by on the left and on the right, after dividing by ). Condition (b) gives in the same way. So the sets and are orthonormal, and is an SVD of . Since every exceeds every , the first right singular vectors span the same space as the (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 is the orthogonal projector onto the span of the , and , because and by (b).
Both conditions are needed. Disjoint supports in space give (a), and Doppler frequencies on disjoint sets of DFT bins of length 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 matrix ( real symmetric, real antisymmetric), let . Then is a real algebra homomorphism, is real symmetric, every eigenvalue of is an eigenvalue of with twice the multiplicity, and for an orthogonal projector onto an invariant subspace of , is the orthogonal projector onto the sum of the corresponding eigenspaces of . In particular and are the left blocks of that real projector.
Proof. Identify with . A direct computation gives , and , . If with real , then and , with orthogonal to . An orthonormal eigenbasis of gives the orthonormal basis of (the real inner product of and is ), so the spectrum of is that of with doubled multiplicity. is real symmetric and idempotent because is Hermitian and idempotent, and it maps and to themselves or to 0 as maps .
The code applies Lemma 2 to (line L2), whose eigenvalues are with eigenvectors . If and , the real eigenvectors number to of in descending order span exactly the embedding of the span of , whatever real basis the eigensolver returns inside a pair. Their real projector is , and line L5 reads from its left blocks. If a cut falls inside a group of equal singular values, is not defined by the data; this is a property of the problem, not of the method of computation.
Lemma 3 (invariances). Let be an unitary matrix (for example a permutation of the pixels times a common phase) and an unitary matrix (for example the diagonal matrix , a shift of every Doppler frequency by ). Then the filter maps to .
Proof. is an SVD with the same singular values, and the right singular vectors are . So and .
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 operations in the real-RAM model with an eigensolver that is counted as to working precision, and space.
Proof. Line L2 forms inner products of length . Line L3 is an eigenproblem of size , which a fixed number of Jacobi sweeps or a tridiagonal QR method solves in . Line L5 forms entries, each a sum of at most products, . Line L6 is an by product, . Line L7 is . The matrices , , and need space.
Complexity
With pixels and frames, line L2 costs , line L3 costs with a dense eigensolver to working precision, line L5 costs and line L6 costs . The total is time, which is because in practice, and space. A filter that acts on each pixel alone with a fixed number of taps costs , so the SVD filter is more expensive by a factor of order . A partial eigensolver such as the Lanczos algorithm or a randomized SVD lowers the cost when and are small.
Properties
- Best rank removal (theorem). The removed part is the best rank approximation of the data in the Frobenius norm, and the kept energy is .
- 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 permutes the rows of ; 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 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 .
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 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 leaves tissue that the Kasai estimator then reads as slow flow.
- Ties in the singular values. If , 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 near the number of tissue components, there is no room for blood in the remaining subspace.
- Cost of a full SVD. Computing all singular vectors is not needed; form the Gram matrix or use a partial eigensolver.
- Gram matrix accuracy. Forming squares the condition number, so singular values below about lose their accuracy in double precision. This matters for the noise cut , not for the tissue cut. Use the SVD of 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 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.
# 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
- 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)
- 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)
- 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)
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag BBV2DJ Edit this page History Report an error Markdown