Algorithm Search⌘K

Algorithmcore

Kasai autocorrelation estimator

Also called lag-one autocorrelation velocity estimator, pulse-pair estimator.

Estimate the mean Doppler velocity at a pixel from the phase of the lag one autocorrelation of its slow time IQ samples: v = c PRF arg R(1) / (4 pi f0).

Time
O(n^2 G N) worst
Space
O(1) extra
Where
G = the number of depth samples averaged per pixel; N = the ensemble length (pulses per pixel); n = the number of pixels along one side of the image
Properties
deterministicnot exactnot linear in dataiterative
Origin
C. Kasai, K. Namekawa, A. Koyano, R. Omoto, 1985

The Kasai autocorrelation estimator gives the mean axial velocity of blood at one pixel of a color flow image. Each pixel is sampled once per transmitted pulse, so it has a short slow time sequence of NN complex IQ samples, the ensemble. Motion of the scatterers turns the phase of these samples at a rate equal to the Doppler frequency. The estimator takes the lag one autocorrelation R(1)R(1) of the ensemble and reads the velocity from its phase: v=c⋅PRF4πf0arg⁡R(1)v = \frac{c \cdot \mathrm{PRF}}{4 \pi f_0} \arg R(1). It needs one complex multiply and add per sample, which made real-time color Doppler possible in 1985. The magnitude of R(1)R(1) against the power R(0)R(0) also gives the spectral width. In radar the same method is called the pulse-pair estimator. It is a spectral estimation method for one number, the center of the Doppler spectrum, and it assumes that tissue echoes were removed first, for example by an SVD clutter filter.

In plain words

An ultrasound scanner sends many pulses down the same line, one after another. At a fixed depth, the echo from moving blood comes back a little earlier or later each time. After demodulation, each echo is one complex number, an arrow with a length and an angle. If the blood moves toward the probe, the arrow turns by the same angle from one pulse to the next.

The estimator measures this turn. It multiplies each sample by the conjugate of the sample before it, which gives an arrow whose angle is the turn, and it adds these products up. The angle of the sum is the average turn per pulse. A fixed formula converts the angle into a velocity. Angles beyond half a turn cannot be told apart from smaller ones in the other direction, which limits the velocity that can be measured.

The problem

The input is, for one pixel, GG ensembles xg[0…N−1]x_g[0 \ldots N-1] of complex baseband (IQ) samples, one per depth sample gg near the pixel, taken at the pulse repetition frequency PRF, so the slow time step is T=1/PRFT = 1/\mathrm{PRF}. The parameters are the center frequency f0f_0 and the speed of sound cc, taken as 1540 m/s in soft tissue. That value is a convention close to measured averages, not a constant of nature.

Model. The IQ demodulation multiplies the RF signal by e−i2πf0te^{-i 2 \pi f_0 t}. A scatterer at depth z0z_0 that moves toward the probe with axial velocity vv has the round trip delay τk=2(z0−vkT)/c\tau_k = 2(z_0 - v k T)/c at pulse kk, so its IQ sample is a e−i2πf0τk=a eiφ0ei2πfDkTa\, e^{-i 2 \pi f_0 \tau_k} = a\, e^{i\varphi_0} e^{i 2 \pi f_D k T} with the Doppler frequency

fD=2vf0c.f_D = \frac{2 v f_0}{c}.

So v>0v > 0 means motion toward the probe. The pulse length is short against the motion between pulses, and the beam is along the flow; for an angle θ\theta between beam and flow the estimate is vcos⁡θv \cos\theta.

Output. An estimate of the mean axial velocity, of the power R(0)R(0) and of the spectral width.

The algorithm

  1. KASAI(x_1 … x_G, c, PRF, f0) ▷ G ensembles of N IQ samples
  2. 1R0 ← (1/(G N)) Σ_g Σ_{k=0}^{N-1} |x_g[k]|^2 ▷ power
  3. 2R1 ← (1/(G (N-1))) Σ_g Σ_{k=0}^{N-2} conj(x_g[k]) x_g[k+1] ▷ lag one autocorrelation
  4. 3v ← (c PRF / (4 π f0)) · arg R1 ▷ mean axial velocity
  5. 4σ_v ← (c PRF / (4 π f0)) · sqrt(2 (1 - |R1| / R0)) ▷ spectral width
  6. 5return v, R0, σ_v

Line L2 averages the products of each sample with the conjugate of the sample before it. For one moving scatterer each product is ∣a∣2ei2πfDT|a|^2 e^{i 2 \pi f_D T}, so its phase is the phase step per pulse. Line L3 turns the phase into a frequency with fD=arg⁡R1/(2πT)f_D = \arg R_1 / (2 \pi T) and then into a velocity with v=cfD/(2f0)v = c f_D / (2 f_0). The function arg returns a value in (−π,π](-\pi, \pi], so the velocities that can be told apart lie in (−va,va](-v_a, v_a] with the aliasing velocity

va=c⋅PRF4f0.v_a = \frac{c \cdot \mathrm{PRF}}{4 f_0}.

Line L4 is the width estimate of Kasai et al.; it is zero when all products have the same phase and grows as the phases spread. The sum over gg averages several depth samples of the same pixel, which lowers the variance and costs depth resolution. R0R_0 is the power Doppler value of the pixel.

Example

Check value. With c=1540c = 1540 m/s, PRF =5= 5 kHz and f0=5f_0 = 5 MHz, the aliasing velocity is 1540⋅5000/(4⋅5⋅106)=0.3851540 \cdot 5000 / (4 \cdot 5 \cdot 10^6) = 0.385 m/s.

One scatterer. For v=0.2v = 0.2 m/s, fD=2⋅0.2⋅5⋅106/1540=1298.70f_D = 2 \cdot 0.2 \cdot 5 \cdot 10^6 / 1540 = 1298.70 Hz, and the phase step per pulse is 2πfD/PRF=1.632002 \pi f_D / \mathrm{PRF} = 1.63200 rad. With a little noise, rounded to two decimals, an ensemble of N=5N = 5 samples is

x=(0.97+0.05i, −0.08+0.97i, −1.09−0.14i, 0.29−0.94i, 1.07+0.27i)x = (0.97 + 0.05i,\ -0.08 + 0.97i,\ -1.09 - 0.14i,\ 0.29 - 0.94i,\ 1.07 + 0.27i).

kk x[k]‾ x[k+1]\overline{x[k]}\, x[k+1] phase (rad)
0 −0.0291+0.9449i-0.0291 + 0.9449i 1.6016
1 −0.0486+1.0685i-0.0486 + 1.0685i 1.6163
2 −0.1845+1.0652i-0.1845 + 1.0652i 1.7423
3 0.0565+1.0841i0.0565 + 1.0841i 1.5187

The mean of the four products is R1=−0.051425+1.040675iR_1 = -0.051425 + 1.040675i, with arg⁡R1=1.62017\arg R_1 = 1.62017 rad and ∣R1∣=1.04194|R_1| = 1.04194. The mean of ∣x[k]∣2|x[k]|^2 is R0=1.05678R_0 = 1.05678. Line L3 gives v=0.122549⋅1.62017=0.19855v = 0.122549 \cdot 1.62017 = 0.19855 m/s, close to 0.2. Line L4 gives σv=0.122549⋅2(1−1.04194/1.05678)=0.0205\sigma_v = 0.122549 \cdot \sqrt{2(1 - 1.04194/1.05678)} = 0.0205 m/s, a small width caused only by the noise.

Aliasing. For v=0.5v = 0.5 m/s the phase step is 4.079994.07999 rad, which arg returns as 4.07999−2π=−2.203194.07999 - 2\pi = -2.20319 rad. The estimate is −0.27-0.27 m/s, that is 0.5−2⋅0.3850.5 - 2 \cdot 0.385: fast flow toward the probe shows as flow away from it.

Correctness

The estimator is exact for one scatterer: every product in line L2 has the phase 2πfDT2 \pi f_D T, so if ∣fD∣<PRF/2|f_D| < \mathrm{PRF}/2 then arg⁡R1=2πfDT\arg R_1 = 2 \pi f_D T and line L3 returns vv. The general statement is about a stationary slow time process with power spectral density S(f)S(f) on one period [−PRF/2,PRF/2)[-\mathrm{PRF}/2, \mathrm{PRF}/2). By the Wiener-Khinchin relation, R(T)=∫S(f)ei2πfTdfR(T) = \int S(f) e^{i 2 \pi f T} df. If SS is symmetric about a frequency fˉ\bar f and its mass lies within 1/(4T)1/(4T) of fˉ\bar f on the circle, then

R(T)=ei2πfˉT∫S(fˉ+u)cos⁡(2πuT) duR(T) = e^{i 2 \pi \bar f T} \int S(\bar f + u) \cos(2 \pi u T)\, du

with a positive integral, so arg⁡R(T)=2πfˉT\arg R(T) = 2 \pi \bar f T exactly: the phase gives the center of the spectrum. Line L2 is an unbiased estimate of R(T)R(T), so for an ergodic process the estimate converges to fˉ\bar f as GNG N grows. For a spectrum that is not symmetric the phase of R(T)R(T) is not the mean frequency, but it is close to it when the spectrum is narrow: the first moment of SS equals the derivative of the phase of R(τ)R(\tau) at τ=0\tau = 0, and arg⁡R(T)/T\arg R(T)/T is the slope of a chord. The width formula of line L4 comes from ∣R(T)∣/R(0)≈1−2π2σf2T2|R(T)|/R(0) \approx 1 - 2 \pi^2 \sigma_f^2 T^2 for small σfT\sigma_f T; it is an approximation. The proofs are in proofs/correctness.md.

Proof: The phase of the lag one autocorrelation gives the Doppler velocity of one scatterer exactly and the center of a narrow symmetric spectrum exactly, and the width formula is a second order approximationfull

We prove the facts behind lines L1 to L5 of the main page. The slow time step is T=1/PRFT = 1/\mathrm{PRF}, the IQ samples are complex numbers, and arg⁡\arg returns a value in (−π,π](-\pi, \pi]. Let κ=c⋅PRF/(4πf0)\kappa = c \cdot \mathrm{PRF}/(4 \pi f_0), so line L3 is v=κarg⁡R1v = \kappa \arg R_1, and fD=2vf0/cf_D = 2 v f_0 / c is the Doppler frequency.

Lemma 1 (the phase of one scatterer). Under the model of the main page, a scatterer that moves toward the probe with constant axial velocity vv has the IQ samples x[k]=a ei(φ0+2πfDkT)x[k] = a\, e^{i(\varphi_0 + 2 \pi f_D k T)} for a complex aa and a real φ0\varphi_0.

Proof. The delay of pulse kk is τk=2(z0−vkT)/c\tau_k = 2(z_0 - v k T)/c. The demodulated sample is the echo amplitude times e−i2πf0τk=e−i4πf0z0/c ei4πf0vkT/ce^{-i 2 \pi f_0 \tau_k} = e^{-i 4 \pi f_0 z_0 / c}\, e^{i 4 \pi f_0 v k T / c}, and 4πf0v/c=2πfD4 \pi f_0 v / c = 2 \pi f_D. The envelope of the pulse is assumed constant over the small shift vkTv k T, so the amplitude aa does not depend on kk. □\square

Theorem 1 (exact for one scatterer). If ∣v∣<va=c⋅PRF/(4f0)|v| < v_a = c \cdot \mathrm{PRF}/(4 f_0) and a≠0a \ne 0, then for any G≥1G \ge 1 and N≥2N \ge 2 lines L1 to L4 return vv, R0=∣a∣2R_0 = |a|^2 and σv=0\sigma_v = 0, when every gate holds the same scatterer velocity (with any amplitudes and phases per gate).

Proof. For gate gg, xg[k]‾ xg[k+1]=∣ag∣2ei2πfDT\overline{x_g[k]}\, x_g[k+1] = |a_g|^2 e^{i 2 \pi f_D T} for every kk. So R1=Aˉ ei2πfDTR_1 = \bar A\, e^{i 2 \pi f_D T} and R0=AˉR_0 = \bar A, where Aˉ>0\bar A > 0 is the mean of ∣ag∣2|a_g|^2. The condition ∣v∣<va|v| < v_a is ∣2πfDT∣=4πf0∣v∣/(c⋅PRF)<π|2 \pi f_D T| = 4 \pi f_0 |v| / (c \cdot \mathrm{PRF}) < \pi, so arg⁡R1=2πfDT\arg R_1 = 2 \pi f_D T and κarg⁡R1=c PRF4πf0⋅4πf0vc PRF=v\kappa \arg R_1 = \frac{c\, \mathrm{PRF}}{4 \pi f_0} \cdot \frac{4 \pi f_0 v}{c\, \mathrm{PRF}} = v. Also ∣R1∣=R0|R_1| = R_0, so line L4 gives 0. □\square

If ∣v∣≥va|v| \ge v_a, the same computation gives arg⁡R1=2πfDT−2πm\arg R_1 = 2 \pi f_D T - 2 \pi m for the integer mm that puts it in (−π,π](-\pi, \pi], so the estimate is v−2mvav - 2 m v_a. This is the aliasing of the main page.

Lemma 2 (invariances). Let R1R_1 be computed from data xgx_g. (a) For data c xgc\, x_g with a complex c≠0c \ne 0, the value is ∣c∣2R1|c|^2 R_1. (b) For the conjugate data xg‾\overline{x_g}, it is R1‾\overline{R_1}. (c) For the reversed data xg[N−1−k]x_g[N-1-k], it is R1‾\overline{R_1}.

Proof. (a) cx‾ cy=∣c∣2xˉy\overline{c x}\, c y = |c|^2 \bar x y. (b) xyˉ=xˉy‾x \bar y = \overline{\bar x y}. (c) Reversal turns the pair (x[k],x[k+1])(x[k], x[k+1]) into (x[k+1],x[k])(x[k+1], x[k]), and x[k+1]‾ x[k]=x[k]‾ x[k+1]‾\overline{x[k+1]}\, x[k] = \overline{\overline{x[k]}\, x[k+1]}. □\square

So the velocity does not depend on the gain, and conjugation or time reversal changes the sign of vv (when arg⁡R1≠π\arg R_1 \ne \pi).

Theorem 2 (the center of a symmetric spectrum). Let the slow time samples be a wide-sense stationary process with autocorrelation R(m)=E[x[k]‾ x[k+m]]R(m) = E[\overline{x[k]}\, x[k+m]] and a spectral measure SS on the circle [−PRF/2,PRF/2)[-\mathrm{PRF}/2, \mathrm{PRF}/2), so that R(m)=∫S(f) ei2πfmT dfR(m) = \int S(f)\, e^{i 2 \pi f m T}\, df (the Herglotz representation, which is the Wiener-Khinchin relation for sampled processes). Suppose that SS is symmetric about fˉ\bar f, that is S(fˉ+u)=S(fˉ−u)S(\bar f + u) = S(\bar f - u) with frequencies taken modulo PRF, that SS puts all its mass on ∣u∣<PRF/4|u| < \mathrm{PRF}/4, and that S≠0S \ne 0. Then arg⁡R(1)=2πfˉT\arg R(1) = 2 \pi \bar f T modulo 2π2\pi, and κarg⁡R(1)\kappa \arg R(1) is the velocity of fˉ\bar f when ∣fˉ∣<PRF/2|\bar f| < \mathrm{PRF}/2.

Proof. Substitute f=fˉ+uf = \bar f + u, with uu in a period centered at 0:

R(1)=ei2πfˉT∫S(fˉ+u) ei2πuT du=ei2πfˉT∫S(fˉ+u)cos⁡(2πuT) du,R(1) = e^{i 2 \pi \bar f T} \int S(\bar f + u)\, e^{i 2 \pi u T}\, du = e^{i 2 \pi \bar f T} \int S(\bar f + u) \cos(2 \pi u T)\, du,

because the sine part is odd in uu and the measure is even in uu. On the support, ∣2πuT∣<π/2|2 \pi u T| < \pi/2, so the cosine is positive and the integral is a positive number. So the phase of R(1)R(1) is 2πfˉT2 \pi \bar f T. □\square

The test checks Theorem 2 on a discrete spectrum with lines at fˉ\bar f, fˉ±200\bar f \pm 200, fˉ±450\bar f \pm 450 and fˉ±900\bar f \pm 900 Hz at PRF 5 kHz, to 1e-12.

Lemma 3 (the estimate of R(1) is unbiased). For a wide-sense stationary process, E[R1]=R(1)E[R_1] = R(1) and E[R0]=R(0)E[R_0] = R(0), where R0R_0 and R1R_1 are lines L1 and L2 over independent or dependent gates of the same process.

Proof. Each term xg[k]‾ xg[k+1]\overline{x_g[k]}\, x_g[k+1] has the mean R(1)R(1), and line L2 divides the sum of the G(N−1)G(N - 1) terms by their number. The same holds for line L1. □\square

If the process is ergodic in the second moment (for example a Gaussian process with a continuous spectrum, or independent gates), R1→R(1)R_1 \to R(1) in probability as GN→∞G N \to \infty, and since arg is continuous away from 0, the estimate converges to κarg⁡R(1)\kappa \arg R(1). With Theorem 2, it converges to the velocity of the center fˉ\bar f. For finite NN the estimate has a variance and, because arg is nonlinear, a small bias; the main page labels these as statistical properties, not as exact facts.

Lemma 4 (the phase slope at zero is the mean frequency). If SS has a finite first moment and R(0)>0R(0) > 0, the continuous lag function R(τ)=∫S(f)ei2πfτdfR(\tau) = \int S(f) e^{i 2 \pi f \tau} df satisfies

ddτarg⁡R(τ)∣τ=0=2π∫f S(f) df∫S(f) df.\frac{d}{d\tau} \arg R(\tau) \Big|_{\tau = 0} = 2 \pi \frac{\int f\, S(f)\, df}{\int S(f)\, df}.

Proof. R(0)=∫S>0R(0) = \int S > 0 is real and R′(0)=i2π∫fS(f) dfR'(0) = i 2 \pi \int f S(f)\, df. The derivative of arg⁡R\arg R is Im⁡(R′/R)\operatorname{Im}(R'/R), which at 0 is 2π∫fS/∫S2 \pi \int f S / \int S. □\square

So arg⁡R(T)/T\arg R(T)/T is the slope of a chord of the phase curve, and it equals the slope at 0, the mean frequency, when the phase is linear in τ\tau. Theorem 2 is such a case. For a skewed spectrum the two differ by a term of order T2T^2 times the third central moment, so the estimate is close to the mean frequency only for narrow spectra.

Lemma 5 (the width formula is second order). Let SS have mean frequency fˉ\bar f and variance σf2\sigma_f^2, with finite fourth moment. Then

∣R(T)∣R(0)=1−2π2σf2T2+O(T3),\frac{|R(T)|}{R(0)} = 1 - 2 \pi^2 \sigma_f^2 T^2 + O(T^3),

so 2T2(1−∣R(T)∣R(0))=4π2σf2+O(T)\frac{2}{T^2}\left(1 - \frac{|R(T)|}{R(0)}\right) = 4 \pi^2 \sigma_f^2 + O(T), and line L4 is κ2(1−∣R1∣/R0)≈c σf/(2f0)\kappa \sqrt{2(1 - |R_1|/R_0)} \approx c\, \sigma_f/(2 f_0), the velocity spread.

Proof. Write R(T)/R(0)=ei2πfˉT E[ei2πUT]R(T)/R(0) = e^{i 2 \pi \bar f T} \, E[e^{i 2 \pi U T}] with U=f−fˉU = f - \bar f distributed by S/∫SS / \int S, so E[U]=0E[U] = 0 and E[U2]=σf2E[U^2] = \sigma_f^2. A Taylor expansion gives E[ei2πUT]=1−2π2σf2T2+i O(T3)+O(T4)E[e^{i 2 \pi U T}] = 1 - 2 \pi^2 \sigma_f^2 T^2 + i\, O(T^3) + O(T^4), whose modulus is 1−2π2σf2T2+O(T3)1 - 2 \pi^2 \sigma_f^2 T^2 + O(T^3). Finally κ⋅2πσfT⋅PRF⋅T=c4πf02πσf=c σf2f0\kappa \cdot 2 \pi \sigma_f T \cdot \mathrm{PRF} \cdot T = \frac{c}{4 \pi f_0} 2 \pi \sigma_f = \frac{c\, \sigma_f}{2 f_0}. □\square

Lemma 5 is an approximation for small σfT\sigma_f T; for wide spectra line L4 underestimates the spread, and noise adds to it. The main page calls it an estimate, not an exact value.

Theorem 3 (cost). One pixel with GG gates of NN samples costs O(GN)O(G N) operations and O(1)O(1) extra space; an n×nn \times n image costs O(n2GN)O(n^2 G N).

Proof. Lines L1 and L2 each visit every sample or every adjacent pair once. Lines L3 to L5 are a fixed number of operations. Only R0R_0 and R1R_1 are stored. □\square

Complexity

In the real-RAM model, lines L1 and L2 cost O(GN)O(G N) complex operations, and lines L3 and L4 cost O(1)O(1), with one arctangent and one square root. An image of n×nn \times n pixels costs O(n2GN)O(n^2 G N). The extra space is O(1)O(1) per pixel. A sliding sum along depth makes the cost of the depth averaging independent of GG. This is the reason for the method: a periodogram on a grid of FF frequencies costs O(NF)O(N F) per pixel, and a fit of a spectral model costs more.

Properties

  • Exact for one tone inside the Nyquist range, and exact for the center of any symmetric spectrum that is narrow enough (see Correctness).
  • Invariant to a complex gain. Multiplying all samples by aeiφa e^{i \varphi} scales R1R_1 by ∣a∣2|a|^2, so vv does not change. The estimate does not depend on the strength of the echo.
  • Antisymmetric. Conjugating the data or reversing the slow time order changes the sign of vv.
  • Aliasing. The estimate lies in (−va,va](-v_a, v_a]; a true velocity outside that range wraps by multiples of 2va2 v_a.
  • Variance. The variance falls with the number of products G(N−1)G(N-1) and with the signal to noise ratio; for one tone in white noise at high SNR the estimate is close to the periodogram peak, the maximum likelihood estimate, but it is not efficient at low SNR or for wide spectra (Miller and Rochwarger 1972).
  • Bias from clutter. Any slow or stationary component in the ensemble pulls the phase of R1R_1 toward zero. The clutter filter must come first.

Variants and improvements

  • Depth averaging. The sum over gg in lines L1 and L2 is the usual form in scanners; it trades depth resolution for variance.
  • Two-dimensional autocorrelator (Loupas, Powers and Gill 1995). It also estimates the mean RF frequency from the correlation along depth and uses it in place of f0f_0, which removes the bias from the frequency dependent attenuation of tissue.
  • Higher lags. arg⁡R(m)\arg R(m) divided by mm gives a finer estimate when there is no aliasing at lag mm; combinations of lags extend the measurable range.
  • Staggered PRF and dual-PRF methods unwrap the aliased velocity with two pulse intervals, as in weather radar.
  • Power Doppler. The value R0R_0 after the clutter filter alone is the power Doppler image, which shows where blood is but not how fast it moves.
  • Spectral Doppler. A short-time Fourier transform of a long ensemble at one gate shows the full velocity distribution; it is the method for quantitative peak velocities.

When to use it

Use the Kasai estimator for color flow and tissue Doppler imaging, where each pixel has only 8 to 16 pulses and the whole image must be computed at frame rate. Use spectral Doppler at one gate when the distribution of velocities or the peak velocity matters. Use the SVD clutter filter or another clutter filter before it, and use a longer ensemble or depth averaging when the variance is too high.

Pitfalls

  • No clutter filter. Applied to raw data, line L2 is dominated by the tissue echo, which is often tens of decibels stronger than the blood echo, and the estimate is close to zero. Filter first. With tissue 10 times stronger in amplitude than blood at 0.25 m/s, the test gets an estimate below 0.05 m/s.
  • Aliasing. Flow faster than vav_a shows with the opposite sign. Raise the PRF, lower f0f_0, or unwrap the phase in space with care, since a jump of 2va2 v_a inside a vessel looks like a real change of direction.
  • Wrong sign convention. If the demodulation uses e+i2πf0te^{+i 2 \pi f_0 t}, the sign of vv flips. Check the convention of the IQ data before reading line L3.
  • Mean phase in place of the phase of the mean. Averaging the phases of the products instead of the products themselves wraps at ±π\pm \pi and gives weak samples the same weight as strong ones. Line L2 averages the complex products, then takes one phase.
  • Normalization of R1. Dividing by G(N−1)G(N-1) in line L2 and by GNGN in line L1 matters for the width of line L4: with other factors the ratio ∣R1∣/R0|R_1|/R_0 is off for short ensembles.
  • Angle. The method measures only the axial component vcos⁡θv \cos\theta. Flow across the beam shows as zero velocity.

Implementations

The Python code takes the ensembles of one pixel as lists of complex numbers. It uses no helper. The tests check the check value 0.385 m/s, exactness for one tone, the wrap of 0.50.5 m/s to −0.27-0.27 m/s, the invariances, the exact phase for a symmetric discrete spectrum, the estimate on a random process with a symmetric spectrum, and compare noisy estimates with the periodogram peak as a reference.

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.

kasai_autocorrelation_estimator.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kasai-autocorrelation-estimator/. The authors are listed in prov/CC9PV7.jsonl.
"""The Kasai autocorrelation (pulse-pair) estimator of the mean Doppler velocity.

The input is the slow time ensemble of complex IQ samples x_g[0 .. N-1] of one
pixel, for G range gates g that are averaged together (G = 1 is the plain
estimator). The pulse repetition frequency is prf, the centre frequency f0 and
the speed of sound c. With the lag-one autocorrelation R1 and the power R0,

    v = c prf arg(R1) / (4 pi f0),
    sigma_v^2 = 2 (c prf / (4 pi f0))^2 (1 - |R1| / R0).

Sign convention: the IQ demodulation multiplies by exp(-i 2 pi f0 t), so an
echo from a scatterer that moves toward the probe has a phase that grows from
pulse to pulse, and v > 0 means motion toward the probe.
"""

import cmath
import math


def aliasing_velocity(c, prf, f0):
    """The largest velocity without aliasing, c prf / (4 f0)."""
    return c * prf / (4.0 * f0)


def doppler_iq(n, v, c, prf, f0, amp=1.0, phase0=0.0):
    """Slow time IQ samples of one scatterer with axial velocity v (toward the probe).

    The round trip delay of pulse k is tau_k = 2 (z0 - v k / prf) / c, so the IQ
    phase -2 pi f0 tau_k grows by 4 pi f0 v / (c prf) per pulse.
    """
    dphi = 4.0 * math.pi * f0 * v / (c * prf)
    return [amp * cmath.exp(1j * (phase0 + dphi * k)) for k in range(n)]


def lag_correlations(gates):
    """R0 = mean |x|^2 and R1 = mean conj(x[k]) x[k+1] over all gates and pulses."""
    g_count, n = len(gates), len(gates[0])
    r0 = sum(abs(v) ** 2 for x in gates for v in x) / (g_count * n)  # @line L1
    r1 = sum(x[k].conjugate() * x[k + 1] for x in gates for k in range(n - 1)) / (g_count * (n - 1))  # @line L2
    return r0, r1


def kasai(gates, c, prf, f0):
    """Return (v, power, sigma_v) for the IQ ensembles of the G gates of one pixel.

    v is the mean axial velocity, power is R0 (the power Doppler value) and
    sigma_v is the spectral width estimate of Kasai et al., in velocity units.
    """
    if len(gates[0]) < 2:
        raise ValueError("the ensemble needs at least two pulses")
    r0, r1 = lag_correlations(gates)
    if r0 == 0:
        return 0.0, 0.0, 0.0
    scale = c * prf / (4.0 * math.pi * f0)
    v = scale * cmath.phase(r1)  # @line L3
    ratio = min(1.0, abs(r1) / r0)
    sigma_v = scale * math.sqrt(2.0 * (1.0 - ratio))  # @line L4
    return v, r0, sigma_v  # @line L5


def kasai_image(ensembles, c, prf, f0, gate_avg=1):
    """Velocity image from ensembles[i][j] = the IQ list of pixel (i, j).

    Each pixel averages R0 and R1 over gate_avg depth samples centred on it
    (rows i - h .. i + h, clipped at the edges, with h = gate_avg // 2).
    """
    rows, cols = len(ensembles), len(ensembles[0])
    h = gate_avg // 2
    out = [[0.0] * cols for _ in range(rows)]
    for i in range(rows):
        lo, hi = max(0, i - h), min(rows, i + h + 1)
        for j in range(cols):
            out[i][j] = kasai([ensembles[r][j] for r in range(lo, hi)], c, prf, f0)[0]
    return out


def periodogram_peak_velocity(x, c, prf, f0, grid=4096):
    """Reference estimate: the velocity at the peak of |sum_k x[k] exp(-i w k)|^2 on a fine grid.

    For one tone in white noise this is the maximum likelihood estimate of the
    frequency. It costs O(N grid), far more than the Kasai estimator.
    """
    best, best_w = -1.0, 0.0
    for q in range(grid):
        w = -math.pi + 2.0 * math.pi * q / grid
        s = sum(v * cmath.exp(-1j * w * k) for k, v in enumerate(x))
        p = abs(s) ** 2
        if p > best:
            best, best_w = p, w
    return c * prf * best_w / (4.0 * math.pi * f0)
test_kasai_autocorrelation_estimator.py 131 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kasai-autocorrelation-estimator/. The authors are listed in prov/CC9PV7.jsonl.

import cmath
import math
import random

from kasai_autocorrelation_estimator import (aliasing_velocity, doppler_iq, kasai, kasai_image, lag_correlations,
                                             periodogram_peak_velocity)

C, PRF, F0 = 1540.0, 5000.0, 5.0e6
VA = aliasing_velocity(C, PRF, F0)


def _noise(rng, n, sigma):
    s = sigma / math.sqrt(2.0)
    return [complex(rng.gauss(0, s), rng.gauss(0, s)) for _ in range(n)]


def test_aliasing_velocity_check_value() -> None:
    assert abs(VA - 0.385) < 1e-12


def test_single_tone_is_exact_inside_the_nyquist_range() -> None:
    for v in (-0.38, -0.2, -0.01, 0.0, 0.05, 0.2, 0.3849):
        x = doppler_iq(8, v, C, PRF, F0, amp=2.5, phase0=1.1)
        est, power, width = kasai([x], C, PRF, F0)
        assert abs(est - v) < 1e-12
        assert abs(power - 6.25) < 1e-12
        assert width < 1e-6


def test_aliasing_wraps_by_twice_the_nyquist_velocity() -> None:
    est = kasai([doppler_iq(8, 0.5, C, PRF, F0)], C, PRF, F0)[0]
    assert abs(est - (0.5 - 2 * VA)) < 1e-12
    assert abs(est + 0.27) < 1e-12


def test_gain_conjugation_and_reversal() -> None:
    rng = random.Random(5101)
    x = [a + b for a, b in zip(doppler_iq(10, 0.12, C, PRF, F0), _noise(rng, 10, 0.3))]
    v = kasai([x], C, PRF, F0)[0]
    g = 0.3 * cmath.exp(2.0j)
    assert abs(kasai([[g * a for a in x]], C, PRF, F0)[0] - v) < 1e-12
    assert abs(kasai([[a.conjugate() for a in x]], C, PRF, F0)[0] + v) < 1e-12
    assert abs(kasai([x[::-1]], C, PRF, F0)[0] + v) < 1e-12


def test_symmetric_spectrum_gives_its_centre_exactly() -> None:
    # R(T) = sum_k S_k exp(i 2 pi f_k T) for a spectrum symmetric about fbar with
    # half-width below prf / 4: the phase of R(T) is exactly 2 pi fbar T.
    t = 1.0 / PRF
    for fbar in (-1700.0, 300.0, 1100.0):
        r = 0j
        for u, s in ((0.0, 1.0), (200.0, 0.6), (450.0, 0.25), (900.0, 0.05)):
            for sign in ((1,) if u == 0.0 else (1, -1)):
                r += s * cmath.exp(2j * math.pi * (fbar + sign * u) * t)
        assert abs(cmath.phase(r) - 2 * math.pi * fbar * t) < 1e-12


def test_random_process_with_symmetric_spectrum() -> None:
    # Many gates, each a sum of tones at fbar +- u with random phases: the
    # pooled estimate approaches the centre velocity.
    rng = random.Random(5102)
    v_true = 0.15
    fbar = 2 * v_true * F0 / C
    gates = []
    for _ in range(200):
        x = [0j] * 12
        for u, a in ((0.0, 1.0), (150.0, 0.7), (300.0, 0.4)):
            for sign in ((1,) if u == 0.0 else (1, -1)):
                ph = rng.uniform(0, 2 * math.pi)
                f = fbar + sign * u
                x = [xk + a * cmath.exp(1j * (ph + 2 * math.pi * f * k / PRF)) for k, xk in enumerate(x)]
        gates.append(x)
    est, _, width = kasai(gates, C, PRF, F0)
    assert abs(est - v_true) < 0.01
    assert width > 0.0


def test_noisy_tone_matches_the_periodogram_reference() -> None:
    rng = random.Random(5103)
    err_k, err_p = 0.0, 0.0
    trials = 20
    for _ in range(trials):
        v = rng.uniform(-0.3, 0.3)
        x = [a + b for a, b in zip(doppler_iq(16, v, C, PRF, F0, phase0=rng.uniform(0, 6.3)),
                                   _noise(rng, 16, 0.3))]
        vk = kasai([x], C, PRF, F0)[0]
        vp = periodogram_peak_velocity(x, C, PRF, F0, grid=512)
        err_k += (vk - v) ** 2
        err_p += (vp - v) ** 2
        assert abs(vk - vp) < 0.02
    assert math.sqrt(err_k / trials) < 0.01
    assert math.sqrt(err_p / trials) < 0.01


def test_gate_averaging_lowers_the_error() -> None:
    rng = random.Random(5104)
    v = 0.1
    single, pooled = 0.0, 0.0
    for _ in range(30):
        gates = [[a + b for a, b in zip(doppler_iq(8, v, C, PRF, F0, phase0=rng.uniform(0, 6.3)),
                                        _noise(rng, 8, 1.0))] for _ in range(5)]
        single += (kasai(gates[:1], C, PRF, F0)[0] - v) ** 2
        pooled += (kasai(gates, C, PRF, F0)[0] - v) ** 2
    assert pooled < single


def test_lag_correlations_by_hand() -> None:
    r0, r1 = lag_correlations([[1, 1j, -1, -1j]])
    assert abs(r0 - 1) < 1e-15
    assert abs(r1 - 1j) < 1e-15


def test_unfiltered_clutter_biases_toward_zero() -> None:
    blood = doppler_iq(8, 0.25, C, PRF, F0)
    tissue = [10.0 + 0j] * 8
    v = kasai([[a + b for a, b in zip(blood, tissue)]], C, PRF, F0)[0]
    assert abs(v) < 0.05


def test_velocity_image() -> None:
    rows, cols = 6, 4
    ens = [[doppler_iq(8, 0.2 if 1 <= i <= 3 and j >= 2 else 0.0, C, PRF, F0, phase0=0.3 * i + j) for j in range(cols)]
           for i in range(rows)]
    img = kasai_image(ens, C, PRF, F0, gate_avg=1)
    for i in range(rows):
        for j in range(cols):
            want = 0.2 if 1 <= i <= 3 and j >= 2 else 0.0
            assert abs(img[i][j] - want) < 1e-12

History

The phase of the autocorrelation at one lag was used in weather radar to estimate the mean Doppler frequency, where it is known as the pulse-pair method; Miller and Rochwarger (1972) gave its statistical analysis as a covariance approach to spectral moment estimation. Kasai, Namekawa, Koyano and Omoto (1985) used it for ultrasound and built a real-time two-dimensional blood flow imager with it, which led to color flow imaging in clinical scanners. Loupas, Powers and Gill (1995) extended it to a two-dimensional autocorrelator over slow time and depth.

References

  1. C. Kasai, K. Namekawa, A. Koyano and R. Omoto, Real-time two-dimensional blood flow imaging using an autocorrelation technique, IEEE Transactions on Sonics and Ultrasonics 32(3), 1985, 458 to 464, the mean Doppler frequency from the phase of the autocorrelation at lag one pulse, and the variance from its magnitude (general locator)
  2. K. Miller and M. Rochwarger, A covariance approach to spectral moment estimation, IEEE Transactions on Information Theory 18(5), 1972, 588 to 596, the pulse-pair estimate of the mean frequency and the spectral width from the covariance at one lag, and its statistics (general locator)
  3. T. Loupas, J. T. Powers and R. W. Gill, An axial velocity estimator for ultrasound blood flow imaging, based on a full evaluation of the Doppler equation by means of a two-dimensional autocorrelation approach, IEEE Transactions on Ultrasonics, Ferroelectrics and Frequency Control 42(4), 1995, 672 to 688, the two-dimensional autocorrelator that also estimates the mean RF frequency over depth (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 clutter filters that must run before the velocity estimator (general locator)
  5. Thomas L. Szabo, Diagnostic Ultrasound Imaging: Inside Out, second edition, Academic Press, 2014, the chapter on Doppler modes (color flow imaging and the autocorrelation estimator)

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