Algorithm Search⌘K

Algorithmadvanced

Ephraim-Malah estimator

Also called MMSE short-time spectral amplitude estimator, MMSE-STSA.

Speech enhancement by the minimum mean squared error estimate of each spectral amplitude under Gaussian models, with decision-directed SNR.

Time
O(F N log N) worst
Space
O(N) extra
Where
F = the number of frames; N = the frame and FFT length
Properties
deterministicnot exactnot in placeonline
Origin
Yariv Ephraim, David Malah, 1984

The Ephraim-Malah estimator removes stationary noise from speech. In each frame of the short-time Fourier transform it multiplies every bin by a gain that makes the amplitude of the bin the minimum mean squared error estimate of the clean amplitude, under Gaussian models of speech and noise, and it keeps the noisy phase. It belongs with the Wiener filter, which estimates the complex coefficient instead of the amplitude and gives the gain ξ/(1+ξ)\xi / (1 + \xi), and with spectral subtraction, which subtracts a noise power and is the simplest of the three. The statistical model VAD uses the same models to decide whether a frame is speech.

In plain words

Noisy speech is cut into short overlapping pieces, and each piece is split into frequencies. At each frequency we know how strong the noise usually is, and we guess how strong the speech is from the previous piece. If a frequency is much louder than the noise, it is probably speech, and the method keeps most of it. If it is about as loud as the noise, it is probably noise, and the method turns it down. The exact amount follows from probability: of all possible clean values, it picks the one with the smallest average squared error. The guess of the speech strength changes slowly from piece to piece, which avoids the short random tones, called musical noise, that simpler methods leave behind.

The problem

In one frame, a DFT bin is Y=X+DY = X + D, where the clean coefficient X=AeiαX = A e^{i\alpha} and the noise DD are independent complex Gaussians with mean 0 and variances λx\lambda_x and λd\lambda_d. Given YY, λd\lambda_d and the a priori SNR ξ=λx/λd\xi = \lambda_x / \lambda_d, find the estimate A^\hat A that minimizes E[(A−A^)2]E[(A - \hat A)^2]. The noise power λd\lambda_d comes from frames without speech, and ξ\xi must be estimated as well.

The algorithm

With the a posteriori SNR γ=∣Y∣2/λd\gamma = |Y|^2 / \lambda_d and v=ξγ/(1+ξ)v = \xi\gamma / (1 + \xi), the estimate is A^=G(ξ,γ) ∣Y∣\hat A = G(\xi, \gamma)\, |Y| with

G(ξ,γ)=π2vγe−v/2[(1+v)I0 ⁣(v2)+v I1 ⁣(v2)],G(\xi, \gamma) = \frac{\sqrt{\pi}}{2} \frac{\sqrt{v}}{\gamma} e^{-v/2} \left[(1 + v) I_0\!\left(\frac{v}{2}\right) + v\, I_1\!\left(\frac{v}{2}\right)\right],

where I0I_0 and I1I_1 are the modified Bessel functions of the first kind. The a priori SNR comes from the decision-directed rule, which mixes the clean estimate of the previous frame with the current frame.

  1. EPHRAIM-MALAH(y, frames of N samples, init frames, alpha, xi_min)
  2. 1Y(n) <- the DFT of frame n with the periodic Hann window, hop N / 2
  3. 2lambda_d[k] <- the mean of |Y_k|^2 over the first init frames
  4. 3for each frame n and bin k: gamma <- |Y_k(n)|^2 / lambda_d[k]
  5. 4xi <- max(alpha A_k^2 / lambda_d[k] + (1 - alpha) max(gamma - 1, 0), xi_min)
  6. 5G <- G(xi, gamma)
  7. 6X_k(n) <- G Y_k(n); A_k <- G |Y_k(n)|
  8. 7y_hat <- overlap-add of the inverse DFTs of X(n)

The Hann window shifted by N/2N/2 adds to 1, so with G=1G = 1 the output equals the input. The code computes e−xIν(x)e^{-x} I_\nu(x) directly, by the power series in log space for x<50x < 50 and by the asymptotic series above, so that no exponential overflows.

Example

Some values of the gain, against the Wiener gain ξ/(1+ξ)\xi / (1 + \xi):

ξ\xi γ=0.5\gamma = 0.5 γ=1\gamma = 1 γ=4\gamma = 4 γ=25\gamma = 25 Wiener
0.1 0.3864 0.2792 0.1569 0.1017 0.0909
1 0.9937 0.7743 0.5681 0.5101 0.5000
10 1.4522 1.1912 0.9745 0.9191 0.9091

For a fixed ξ\xi the gain falls toward the Wiener gain as γ\gamma grows. For a small γ\gamma it is larger, and it can exceed 1: a bin weaker than the model expects is raised.

On a signal of one second at fs=8000f_s = 8000 Hz, with 0.2 s of white noise of standard deviation 0.05 and then a 500 Hz tone of amplitude 0.1 in the same noise (random seed 3), frames of 256 samples, 10 noise frames, α=0.98\alpha = 0.98 and ξmin⁡=10−2.5\xi_{\min} = 10^{-2.5} give these measurements:

  • The SNR over samples 2400 to 7600 rises from 2.89 dB to 15.00 dB.
  • In the noise-only part, the power falls from 0.00243 to 0.0000489, by 17 dB.
  • The Wiener gain with the same decision-directed ξ\xi gives 18.89 dB and a residual noise power of 0.0000019 on this signal.

The Wiener gain wins here because a pure tone in white noise needs only strong suppression. The Ephraim-Malah gain minimizes the error of the amplitude under the Gaussian model, not the SNR, and its advantage on speech is a smaller musical noise, which is a judgment of listeners.

Correctness

These are theorems, proved in proofs/correctness.md:

  • The gain gives the posterior mean. Under the Gaussian model, the posterior of AA given YY has density proportional to a e−a2(1/λx+1/λd)I0(2a∣Y∣/λd)a\, e^{-a^2 (1/\lambda_x + 1/\lambda_d)} I_0(2 a |Y| / \lambda_d), and E[A∣Y]=G(ξ,γ)∣Y∣E[A \mid Y] = G(\xi, \gamma) |Y|. The posterior mean minimizes the mean squared error over all functions of YY, so the estimate is optimal for the stated criterion.
  • The limit is the Wiener gain. For a fixed ξ\xi, G(ξ,γ)=ξ1+ξ+14γ+O(1/γ2)G(\xi, \gamma) = \frac{\xi}{1 + \xi} + \frac{1}{4\gamma} + O(1/\gamma^2) as γ→∞\gamma \to \infty.
  • Identity. With G=1G = 1 the output equals the input, except in the first and last half frames.

The tests check the first statement against a numerical integral of the posterior, the second for γ=104\gamma = 10^4 and 10610^6, and the third exactly. The use of the noisy phase is also justified by Ephraim and Malah: the MMSE estimate of the complex exponential of the phase has the noisy phase. In practice ξ\xi and λd\lambda_d are estimates and speech is not Gaussian, so on real speech the optimality is a heuristic.

Proof: Correctness of the Ephraim-Malah estimatorfull

We prove that the gain gives the posterior mean of the amplitude, that the posterior mean is the estimate of least mean squared error, that the gain tends to the Wiener gain, and that the analysis and synthesis of the code are exact when the gain is 1.

Setup

In one bin, Y=X+DY = X + D with X=AeiαX = A e^{i\alpha} and DD independent complex Gaussians of mean 0 and variances λx\lambda_x and λd\lambda_d. Write R=∣Y∣R = |Y|, ξ=λx/λd\xi = \lambda_x / \lambda_d, γ=R2/λd\gamma = R^2 / \lambda_d and v=ξγ/(1+ξ)v = \xi\gamma / (1 + \xi). The modified Bessel function is Iν(x)=∑k≥0(x/2)2k+ν/(k! (k+ν)!)I_\nu(x) = \sum_{k \ge 0} (x/2)^{2k + \nu} / (k!\, (k + \nu)!) for ν=0,1\nu = 0, 1, and I0(x)=12π∫02πexcos⁡t dtI_0(x) = \frac{1}{2\pi} \int_0^{2\pi} e^{x \cos t}\, dt.

Lemma 1 (the posterior of the amplitude)

The posterior density of AA given YY is proportional to a e−ca2I0(ba)a\, e^{-c a^2} I_0(b a) on a>0a > 0, with c=1/λx+1/λdc = 1/\lambda_x + 1/\lambda_d and b=2R/λdb = 2R / \lambda_d.

Proof. A complex Gaussian XX of variance λx\lambda_x has, in polar form, independent AA with the Rayleigh density 2aλxe−a2/λx\frac{2a}{\lambda_x} e^{-a^2/\lambda_x} and α\alpha uniform on [0,2π)[0, 2\pi). Given A=aA = a and α\alpha, YY has density 1πλde−∣Y−aeiα∣2/λd\frac{1}{\pi\lambda_d} e^{-|Y - a e^{i\alpha}|^2 / \lambda_d}, and ∣Y−aeiα∣2=R2+a2−2aRcos⁡(α−θ)|Y - a e^{i\alpha}|^2 = R^2 + a^2 - 2aR\cos(\alpha - \theta) with θ=arg⁡Y\theta = \arg Y. Integrating over α\alpha gives a factor e−(R2+a2)/λdI0(2aR/λd)e^{-(R^2 + a^2)/\lambda_d} I_0(2aR / \lambda_d), by the integral form of I0I_0. Multiply by the prior and drop the factors that do not depend on aa. □\square

Lemma 2 (two integrals)

For c>0c > 0 and b≥0b \ge 0, with z=b2/(4c)z = b^2 / (4c),

∫0∞a e−ca2I0(ba) da=ez2c,∫0∞a2e−ca2I0(ba) da=π4c3/2 1F1 ⁣(32;1;z),\int_0^\infty a\, e^{-c a^2} I_0(b a)\, da = \frac{e^{z}}{2c}, \qquad \int_0^\infty a^2 e^{-c a^2} I_0(b a)\, da = \frac{\sqrt{\pi}}{4 c^{3/2}}\, {}_1F_1\!\left(\tfrac32; 1; z\right),

where 1F1(p;q;z)=∑k(p)k(q)kzkk!{}_1F_1(p; q; z) = \sum_k \frac{(p)_k}{(q)_k} \frac{z^k}{k!} is Kummer's function.

Proof. All terms are nonnegative, so the series of I0I_0 may be integrated term by term. With ∫0∞a2k+1e−ca2da=k!2ck+1\int_0^\infty a^{2k+1} e^{-ca^2} da = \frac{k!}{2 c^{k+1}}, the first integral is ∑k(b/2)2k(k!)2k!2ck+1=12c∑kzkk!=ez2c\sum_k \frac{(b/2)^{2k}}{(k!)^2} \frac{k!}{2c^{k+1}} = \frac{1}{2c} \sum_k \frac{z^k}{k!} = \frac{e^z}{2c}. With ∫0∞a2k+2e−ca2da=Γ(k+3/2)2ck+3/2\int_0^\infty a^{2k+2} e^{-ca^2} da = \frac{\Gamma(k + 3/2)}{2 c^{k + 3/2}} and Γ(k+3/2)=Γ(3/2)(3/2)k=π2(3/2)k\Gamma(k + 3/2) = \Gamma(3/2) (3/2)_k = \frac{\sqrt\pi}{2} (3/2)_k, the second is π4c3/2∑k(3/2)kk! k!zk\frac{\sqrt\pi}{4 c^{3/2}} \sum_k \frac{(3/2)_k}{k!\, k!} z^k, and (1)k=k!(1)_k = k!. □\square

Theorem 1 (the gain is the posterior mean)

E[A∣Y]=G(ξ,γ) RE[A \mid Y] = G(\xi, \gamma)\, R, with G(ξ,γ)=π2vγe−v/2[(1+v)I0(v/2)+vI1(v/2)]G(\xi, \gamma) = \frac{\sqrt\pi}{2} \frac{\sqrt v}{\gamma} e^{-v/2} [(1 + v) I_0(v/2) + v I_1(v/2)].

Proof. By Lemmas 1 and 2, E[A∣Y]=π2c e−z 1F1(32;1;z)E[A \mid Y] = \frac{\sqrt\pi}{2\sqrt c}\, e^{-z}\, {}_1F_1(\tfrac32; 1; z). We use two standard identities of Kummer's function: Kummer's transformation 1F1(p;q;z)=ez1F1(q−p;q;−z){}_1F_1(p; q; z) = e^z {}_1F_1(q - p; q; -z), and 1F1(−12;1;−z)=e−z/2[(1+z)I0(z/2)+zI1(z/2)]{}_1F_1(-\tfrac12; 1; -z) = e^{-z/2} [(1 + z) I_0(z/2) + z I_1(z/2)]. Together they give E[A∣Y]=π2ce−z/2[(1+z)I0(z/2)+zI1(z/2)]E[A \mid Y] = \frac{\sqrt\pi}{2\sqrt c} e^{-z/2} [(1 + z) I_0(z/2) + z I_1(z/2)]. Now

z=b24c=R2/λd2(λx+λd)/(λxλd)=R2λdλxλx+λd=γξ1+ξ=v,z = \frac{b^2}{4c} = \frac{R^2 / \lambda_d^2}{(\lambda_x + \lambda_d) / (\lambda_x \lambda_d)} = \frac{R^2}{\lambda_d} \frac{\lambda_x}{\lambda_x + \lambda_d} = \gamma \frac{\xi}{1 + \xi} = v,

and 1c=λxλdλx+λd=λdvγ\frac{1}{\sqrt c} = \sqrt{\frac{\lambda_x \lambda_d}{\lambda_x + \lambda_d}} = \sqrt{\lambda_d \frac{v}{\gamma}}. Dividing by R=γλdR = \sqrt{\gamma \lambda_d} gives π2vγe−v/2[… ]=G\frac{\sqrt\pi}{2} \frac{\sqrt{v}}{\gamma} e^{-v/2}[\dots] = G. □\square

The second identity of Kummer's function is the one step not derived here. The tests check the final formula against a direct numerical integration of the posterior of Lemma 1, by Simpson's rule, at six pairs (ξ,γ)(\xi, \gamma), with agreement to 7 decimal places.

Theorem 2 (the posterior mean minimizes the mean squared error)

For every measurable function ff of YY with E[f(Y)2]<∞E[f(Y)^2] < \infty, E[(A−f(Y))2]≥E[(A−E[A∣Y])2]E[(A - f(Y))^2] \ge E[(A - E[A \mid Y])^2].

Proof. Let m(Y)=E[A∣Y]m(Y) = E[A \mid Y]. Then E[(A−f)2]=E[(A−m)2]+2E[(A−m)(m−f)]+E[(m−f)2]E[(A - f)^2] = E[(A - m)^2] + 2E[(A - m)(m - f)] + E[(m - f)^2]. The middle term is 0, because E[(A−m)(m−f)∣Y]=(m−f)E[A−m∣Y]=0E[(A - m)(m - f) \mid Y] = (m - f) E[A - m \mid Y] = 0. The last term is nonnegative. □\square

So A^=GR\hat A = G R is the estimate of least mean squared amplitude error for the model, and the code multiplies the complex bin by GG, which gives this amplitude and keeps the phase of YY.

Theorem 3 (the limit is the Wiener gain)

For fixed ξ>0\xi > 0, G(ξ,γ)=ξ1+ξ+14γ+O(γ−2)G(\xi, \gamma) = \frac{\xi}{1 + \xi} + \frac{1}{4\gamma} + O(\gamma^{-2}) as γ→∞\gamma \to \infty.

Proof. As γ→∞\gamma \to \infty, v→∞v \to \infty. The standard asymptotic expansion e−xIν(x)=12πx(1−4ν2−18x+O(x−2))e^{-x} I_\nu(x) = \frac{1}{\sqrt{2\pi x}} \left(1 - \frac{4\nu^2 - 1}{8x} + O(x^{-2})\right) at x=v/2x = v/2 gives e−v/2I0(v/2)=1πv(1+14v+O(v−2))e^{-v/2} I_0(v/2) = \frac{1}{\sqrt{\pi v}} (1 + \frac{1}{4v} + O(v^{-2})) and e−v/2I1(v/2)=1πv(1−34v+O(v−2))e^{-v/2} I_1(v/2) = \frac{1}{\sqrt{\pi v}} (1 - \frac{3}{4v} + O(v^{-2})). Then

G=12γ[(1+v)(1+14v)+v(1−34v)+O(v−1)]=12γ[2v+12+O(v−1)]=vγ+14γ+O ⁣(1vγ).G = \frac{1}{2\gamma} \left[(1 + v)\left(1 + \frac{1}{4v}\right) + v\left(1 - \frac{3}{4v}\right) + O(v^{-1})\right] = \frac{1}{2\gamma}\left[2v + \frac12 + O(v^{-1})\right] = \frac{v}{\gamma} + \frac{1}{4\gamma} + O\!\left(\frac{1}{v\gamma}\right).

Since v/γ=ξ/(1+ξ)v / \gamma = \xi / (1 + \xi) and vv is proportional to γ\gamma, the claim follows. □\square

Theorem 4 (identity of the analysis and synthesis)

With the periodic Hann window w[i]=12−12cos⁡(2πi/N)w[i] = \frac12 - \frac12 \cos(2\pi i / N), the hop N/2N/2 and the gain 1 in every bin, the output equals the input at every sample covered by two frames.

Proof. For 0≤i<N/20 \le i < N/2, w[i]+w[i+N/2]=1−12(cos⁡(2πi/N)+cos⁡(2πi/N+π))=1w[i] + w[i + N/2] = 1 - \frac12(\cos(2\pi i/N) + \cos(2\pi i/N + \pi)) = 1. With gain 1, the inverse DFT of frame tt is w[i] y[tN/2+i]w[i]\, y[tN/2 + i], and the overlap-add at a sample covered by frames tt and t+1t + 1 gives (w[i+N/2]+w[i]) y=y(w[i + N/2] + w[i])\, y = y. □\square

Remarks

The function bessel_ie of the code returns e−xIν(x)e^{-x} I_\nu(x) from the power series in log space for x<50x < 50, and from five terms of the asymptotic series for x≥50x \ge 50; the tests compare both against the integral 1π∫0πex(cos⁡t−1)cos⁡(νt) dt\frac{1}{\pi}\int_0^\pi e^{x(\cos t - 1)} \cos(\nu t)\, dt, with relative error below 10−910^{-9}. The decision-directed ξ\xi is an estimate that depends on the data, so on real signals the optimality of Theorem 2 holds only for the model with ξ\xi given.

Complexity

Each frame costs one FFT, one inverse FFT and one gain per bin. The gain needs two Bessel values, a constant number of operations for each vv up to a fixed bound, so the time is O(FNlog⁡N)O(F N \log N) for FF frames. The state is the noise power and the previous clean amplitudes, O(N)O(N), and the method runs online with a delay of one frame. Real systems take the gain from a table indexed by ξ\xi and γ\gamma.

Properties

  • Soft decision. Every bin is scaled, never set to 0, so the speech is not cut abruptly.
  • Low musical noise. The decision-directed ξ\xi changes slowly in noise, so the gain does not jump from frame to frame. Cappé traced most of the reduction of musical noise to this smoothing.
  • Noisy phase. Only the amplitudes change. At low SNR the phase error limits the quality.
  • Needs a noise estimate. Like all methods of this family it fails when the noise changes faster than the estimate of λd\lambda_d.

Variants and improvements

  • Log-spectral amplitude (log-MMSE). Minimize E[(log⁡A−log⁡A^)2]E[(\log A - \log \hat A)^2] instead. The gain is ξ1+ξexp⁡(12∫v∞e−tt dt)\frac{\xi}{1 + \xi} \exp\left(\frac12 \int_v^\infty \frac{e^{-t}}{t}\, dt\right). It suppresses more noise with little more distortion, and Ephraim and Malah published it in 1985.
  • Speech presence uncertainty. Multiply the gain by the probability that speech is present in the bin, computed from the same likelihood ratio as the statistical model VAD.
  • Other priors. Laplacian, Gamma or super-Gaussian models of the speech coefficients fit speech better and give other gain functions.
  • Better noise tracking. Minimum statistics and MMSE noise trackers update λd\lambda_d during speech.
  • Neural enhancement. Networks that predict the gain or the clean spectrum now give better quality when training data exist.

When to use it

Use it to reduce stationary or slowly changing noise in speech, for telephony, hearing aids and the front end of recognizers, when no training data are available and the delay must be small. For noise that changes fast, such as other talkers, it does little; use a trained model or several microphones.

Pitfalls

  • Overflow of the Bessel functions. I0(v/2)I_0(v/2) grows like ev/2e^{v/2} and overflows for vv above about 1400. Compute e−xIν(x)e^{-x} I_\nu(x) directly, as the code does.
  • No floor on the a priori SNR. Without ξmin⁡\xi_{\min}, the gain in noise goes to 0 and the residual noise sounds unnatural. A floor of about −25-25 dB is common.
  • A smoothing factor too small. With α\alpha well below 0.98, ξ\xi follows the noise and the musical noise returns.
  • Speech in the noise estimate. If the first frames contain speech, λd\lambda_d is too large and the speech is suppressed.
  • Gains above 1. For γ<1\gamma < 1 the gain can exceed 1; some systems clip it to 1.

Implementations

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

ephraim_malah_estimator.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ephraim-malah-estimator/. The authors are listed in prov/EV1Q5W.jsonl.

"""The Ephraim-Malah MMSE short-time spectral amplitude estimator.

Each DFT bin is Y = X + D, with X and D independent complex Gaussians of
variances lambda_x and lambda_d. The a priori SNR is xi = lambda_x / lambda_d and
the a posteriori SNR is gamma = |Y|^2 / lambda_d. The estimate of the clean
amplitude A = |X| that minimizes E[(A - A_hat)^2] is A_hat = G(xi, gamma) |Y| with

    v = xi gamma / (1 + xi)
    G = (sqrt(pi) / 2) (sqrt(v) / gamma) exp(-v / 2) [(1 + v) I0(v / 2) + v I1(v / 2)],

where I0 and I1 are modified Bessel functions of the first kind. The phase of Y
is kept. The a priori SNR comes from the decision-directed rule.
"""

import math
from typing import Callable, List, Sequence

from nlsdsp import fft


def bessel_ie(nu: int, x: float) -> float:
    """exp(-x) I_nu(x) for nu in {0, 1} and x >= 0: the power series below 50, the asymptotic series above."""
    if x < 0:
        raise ValueError("x must be nonnegative")
    if x == 0.0:
        return 1.0 if nu == 0 else 0.0
    if x < 50.0:
        # I_nu(x) = sum_k (x / 2)^(2k + nu) / (k! (k + nu)!), summed with the factor exp(-x) in log space
        lx = math.log(x / 2.0)
        total = 0.0
        k = 0
        while True:
            t = math.exp((2 * k + nu) * lx - math.lgamma(k + 1) - math.lgamma(k + nu + 1) - x)
            total += t
            if k > x and t < 1e-17 * total:
                return total
            k += 1
    mu = 4.0 * nu * nu
    s, term = 1.0, 1.0
    for j in range(1, 6):
        term *= -(mu - (2 * j - 1) ** 2) / (j * 8.0 * x)
        s += term
    return s / math.sqrt(2.0 * math.pi * x)


def mmse_stsa_gain(xi: float, gamma: float) -> float:
    """The Ephraim-Malah gain G(xi, gamma) for xi > 0 and gamma > 0."""
    if xi <= 0 or gamma <= 0:
        raise ValueError("xi and gamma must be positive")
    v = xi * gamma / (1.0 + xi)
    # exp(-v / 2) I_nu(v / 2) = bessel_ie(nu, v / 2), so no exponential overflows
    return 0.5 * math.sqrt(math.pi * v) / gamma * ((1.0 + v) * bessel_ie(0, v / 2.0) + v * bessel_ie(1, v / 2.0))


def periodic_hann(n: int) -> List[float]:
    """w[i] = 0.5 - 0.5 cos(2 pi i / n); its shifts by n / 2 add to 1."""
    return [0.5 - 0.5 * math.cos(2.0 * math.pi * i / n) for i in range(n)]


def ifft(spec: Sequence[complex]) -> List[complex]:
    """The inverse DFT by the forward FFT of the conjugate."""
    n = len(spec)
    return [v.conjugate() / n for v in fft([s.conjugate() for s in spec])]


def enhance(
    y: Sequence[float],
    n: int = 256,
    init_frames: int = 10,
    alpha: float = 0.98,
    xi_min: float = 10 ** (-2.5),
    gain: Callable[[float, float], float] = mmse_stsa_gain,
) -> List[float]:
    """Enhance y frame by frame. The first init_frames frames must be noise. n must be a power of 2.

    gain(xi, gamma) is the spectral gain; the default is the Ephraim-Malah gain.
    """
    hop = n // 2
    w = periodic_hann(n)
    starts = list(range(0, len(y) - n + 1, hop))
    spectra = [fft([y[s + i] * w[i] for i in range(n)]) for s in starts]  # @line L1
    if len(spectra) < init_frames or init_frames < 1:
        raise ValueError("need at least init_frames frames")
    noise = [max(sum(abs(sp[k]) ** 2 for sp in spectra[:init_frames]) / init_frames, 1e-20) for k in range(n)]  # @line L2
    prev_amp2 = [0.0] * n
    out = [0.0] * len(y)
    for s, spec in zip(starts, spectra):
        clean = []
        for k in range(n):
            gamma = max(abs(spec[k]) ** 2 / noise[k], 1e-12)  # @line L3
            xi = max(alpha * prev_amp2[k] / noise[k] + (1.0 - alpha) * max(gamma - 1.0, 0.0), xi_min)  # @line L4
            g = gain(xi, gamma)  # @line L5
            clean.append(g * spec[k])  # @line L6
            prev_amp2[k] = (g * abs(spec[k])) ** 2
        frame = ifft(clean)  # @line L7
        for i in range(n):
            out[s + i] += frame[i].real
    return out
nlsdsp.py 191 lines
# SPDX-License-Identifier: MIT
# Shared helper of the natural-language-and-speech pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small signal processing tools for the natural-language-and-speech pages.

A signal is a list of floats x[0], ..., x[L - 1], usually in [-1, 1]. A frame is
a list of floats. A spectrum is a list of floats or complex numbers.

The defaults of the area are fs = 16000 Hz, frames of 400 samples (25 ms), a hop
of 160 samples (10 ms), the symmetric Hamming window and an FFT length of 512.

The LPC sign convention is A(z) = 1 - sum_{k=1}^{p} a_k z^-k, so the prediction
of x[n] is sum_{k=1}^{p} a_k x[n - k].

This module holds no algorithm of any page of the area: no mel scale, no mel
filter bank, no feature extractor, no pre-emphasis and no zero-crossing rate.
The pages build those on top of it.
"""

import cmath
import math
from typing import List, Sequence, Tuple


def frames(x: Sequence[float], frame_len: int, hop: int) -> List[List[float]]:
    """Cut x into frames of frame_len samples, one every hop samples, with no padding.

    A signal of L >= frame_len samples gives 1 + (L - frame_len) // hop frames.
    A signal shorter than one frame gives no frame. The last samples that do not
    fill a frame are dropped.
    """
    if frame_len <= 0 or hop <= 0:
        raise ValueError("frame_len and hop must be positive")
    n = len(x)
    if n < frame_len:
        return []
    count = 1 + (n - frame_len) // hop
    return [list(x[i * hop : i * hop + frame_len]) for i in range(count)]


def hamming(n: int) -> List[float]:
    """The symmetric Hamming window w[i] = 0.54 - 0.46 cos(2 pi i / (n - 1)), i = 0 to n - 1."""
    if n <= 0:
        raise ValueError("the window length must be positive")
    if n == 1:
        return [1.0]
    return [0.54 - 0.46 * math.cos(2.0 * math.pi * i / (n - 1)) for i in range(n)]


def hann(n: int) -> List[float]:
    """The symmetric Hann window w[i] = 0.5 - 0.5 cos(2 pi i / (n - 1)), i = 0 to n - 1."""
    if n <= 0:
        raise ValueError("the window length must be positive")
    if n == 1:
        return [1.0]
    return [0.5 - 0.5 * math.cos(2.0 * math.pi * i / (n - 1)) for i in range(n)]


def fft(x: Sequence[complex]) -> List[complex]:
    """The DFT X[k] = sum_n x[n] exp(-2 pi i k n / N) by the iterative radix 2 FFT.

    The length N must be a power of 2. The cost is O(N log N) operations.
    """
    n = len(x)
    if n == 0 or n & (n - 1):
        raise ValueError("the FFT length must be a power of 2")
    a = [complex(v) for v in x]
    # bit reversal permutation
    j = 0
    for i in range(1, n):
        bit = n >> 1
        while j & bit:
            j ^= bit
            bit >>= 1
        j |= bit
        if i < j:
            a[i], a[j] = a[j], a[i]
    size = 2
    while size <= n:
        half = size // 2
        w_step = cmath.exp(-2j * math.pi / size)
        for start in range(0, n, size):
            w = 1.0 + 0.0j
            for k in range(start, start + half):
                u = a[k]
                v = a[k + half] * w
                a[k] = u + v
                a[k + half] = u - v
                w *= w_step
        size *= 2
    return a


def power_spectrum(frame: Sequence[float], nfft: int) -> List[float]:
    """|X[k]|^2 for k = 0 to nfft / 2, where X is the DFT of the frame zero padded to nfft."""
    if len(frame) > nfft:
        raise ValueError("the frame is longer than the FFT length")
    spec = fft(list(frame) + [0.0] * (nfft - len(frame)))
    return [abs(spec[k]) ** 2 for k in range(nfft // 2 + 1)]


def dct2(x: Sequence[float], k: int) -> List[float]:
    """The first k coefficients of the orthonormal DCT-II of x.

    c[j] = s_j sum_{n=0}^{N-1} x[n] cos(pi j (2 n + 1) / (2 N)), with s_0 = sqrt(1 / N)
    and s_j = sqrt(2 / N) for j >= 1. The full transform (k = N) is an orthogonal matrix.
    """
    n = len(x)
    if n == 0:
        raise ValueError("empty input")
    if k < 0 or k > n:
        raise ValueError("k must be between 0 and len(x)")
    out = []
    for j in range(k):
        s = math.sqrt((1.0 if j == 0 else 2.0) / n)
        out.append(s * sum(x[i] * math.cos(math.pi * j * (2 * i + 1) / (2 * n)) for i in range(n)))
    return out


def autocorr(x: Sequence[float], max_lag: int) -> List[float]:
    """r[k] = sum_{n=0}^{L-1-k} x[n] x[n + k] for k = 0 to max_lag (no normalization)."""
    n = len(x)
    return [sum(x[i] * x[i + k] for i in range(n - k)) if k < n else 0.0 for k in range(max_lag + 1)]


def levinson(r: Sequence[float], p: int) -> Tuple[List[float], float]:
    """Solve the normal equations of linear prediction of order p by the Levinson-Durbin recursion.

    Returns (a, e): a = [a_1, ..., a_p] with A(z) = 1 - sum a_k z^-k, and e the
    prediction error of order p. Needs r[0] > 0 and len(r) > p. If the error
    reaches 0 before order p (a perfectly predictable signal), the remaining
    coefficients are 0.
    """
    if len(r) <= p:
        raise ValueError("need r[0] to r[p]")
    if r[0] <= 0:
        raise ValueError("r[0] must be positive")
    a = [0.0] * (p + 1)  # a[0] is unused
    e = float(r[0])
    for i in range(1, p + 1):
        if e <= 0.0:
            break
        acc = r[i] - sum(a[j] * r[i - j] for j in range(1, i))
        k = acc / e
        new = a[:]
        new[i] = k
        for j in range(1, i):
            new[j] = a[j] - k * a[i - j]
        a = new
        e *= 1.0 - k * k
    return a[1:], e


def sine(f: float, fs: float, n: int, amp: float = 1.0, phase: float = 0.0) -> List[float]:
    """x[i] = amp sin(2 pi f i / fs + phase) for i = 0 to n - 1."""
    return [amp * math.sin(2.0 * math.pi * f * i / fs + phase) for i in range(n)]


def pulse_train(f0: float, fs: float, n: int) -> List[float]:
    """Unit pulses at the samples round(j fs / f0), j = 0, 1, 2, ..., and 0 elsewhere, n samples."""
    if f0 <= 0:
        raise ValueError("f0 must be positive")
    x = [0.0] * n
    period = fs / f0
    j = 0
    while True:
        pos = int(math.floor(j * period + 0.5))
        if pos >= n:
            break
        x[pos] = 1.0
        j += 1
    return x


def white_noise(rng, n: int, sigma: float) -> List[float]:
    """n samples of Gaussian noise with mean 0 and standard deviation sigma, from rng (a random.Random)."""
    return [rng.gauss(0.0, sigma) for _ in range(n)]


def all_pole(x: Sequence[float], a: Sequence[float]) -> List[float]:
    """Filter x through 1 / A(z): y[n] = x[n] + sum_{k=1}^{p} a_k y[n - k], with zero initial state."""
    p = len(a)
    y: List[float] = []
    for i, v in enumerate(x):
        acc = float(v)
        for k in range(1, p + 1):
            if i - k < 0:
                break
            acc += a[k - 1] * y[i - k]
        y.append(acc)
    return y
test_ephraim_malah_estimator.py 108 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ephraim-malah-estimator/. The authors are listed in prov/EV1Q5W.jsonl.

import math
import random
import unittest

from ephraim_malah_estimator import bessel_ie, enhance, mmse_stsa_gain
from nlsdsp import sine, white_noise

FS = 8000


def bessel_ie_integral(nu, x, m=2000):
    """exp(-x) I_nu(x) = (1 / pi) int_0^pi exp(x (cos t - 1)) cos(nu t) dt, by Simpson's rule."""
    h = math.pi / m
    f = [math.exp(x * (math.cos(i * h) - 1.0)) * math.cos(nu * i * h) for i in range(m + 1)]
    return h / 3.0 * (f[0] + f[-1] + 4.0 * sum(f[1:-1:2]) + 2.0 * sum(f[2:-1:2])) / math.pi


def posterior_mean_gain(xi, gamma, m=3000):
    """E[A | Y] / |Y| by Simpson's rule on the posterior density of the amplitude, with lambda_d = 1."""
    lx, r = xi, math.sqrt(gamma)
    c = 1.0 / lx + 1.0
    top = r + 12.0 / math.sqrt(c) + 5.0
    h = top / m
    num = den = 0.0
    for i in range(1, m + 1):
        a = i * h
        z = 2.0 * a * r
        # p(a | Y) is proportional to a exp(-c a^2) I0(2 a r) = a exp(-c a^2 + z) bessel_ie(0, z)
        w = a * math.exp(-c * a * a + z) * bessel_ie(0, z)
        wt = 1.0 if i == m else (4.0 if i % 2 else 2.0)
        num += wt * w * a
        den += wt * w
    return num / den / r


def tone_in_noise(seed):
    rng = random.Random(seed)
    clean = [0.0] * 1600 + sine(500, FS, 6400, 0.1)
    noisy = [c + v for c, v in zip(clean, white_noise(rng, 8000, 0.05))]
    return clean, noisy


def snr_db(ref, sig, lo, hi):
    s = sum(ref[i] ** 2 for i in range(lo, hi))
    e = sum((ref[i] - sig[i]) ** 2 for i in range(lo, hi))
    return 10.0 * math.log10(s / e)


class TestBessel(unittest.TestCase):
    def test_against_integral(self):
        for x in (0.0, 0.1, 1.0, 10.0, 49.9, 50.0, 120.0, 1000.0):
            for nu in (0, 1):
                ref = bessel_ie_integral(nu, x)
                self.assertLess(abs(bessel_ie(nu, x) - ref), 1e-9 * max(ref, 1e-3))

    def test_negative(self):
        with self.assertRaises(ValueError):
            bessel_ie(0, -1.0)


class TestGain(unittest.TestCase):
    def test_gain_is_the_posterior_mean(self):
        for xi, gamma in [(1.0, 1.0), (1.0, 4.0), (0.1, 2.0), (10.0, 10.0), (3.16, 0.5), (0.01, 30.0)]:
            self.assertAlmostEqual(mmse_stsa_gain(xi, gamma), posterior_mean_gain(xi, gamma), places=7)

    def test_page_table(self):
        self.assertAlmostEqual(mmse_stsa_gain(1.0, 1.0), 0.7743, places=4)
        self.assertAlmostEqual(mmse_stsa_gain(1.0, 4.0), 0.5681, places=4)
        self.assertAlmostEqual(mmse_stsa_gain(0.1, 1.0), 0.2792, places=4)
        self.assertAlmostEqual(mmse_stsa_gain(10.0, 0.5), 1.4522, places=4)

    def test_limit_is_wiener(self):
        # G -> xi / (1 + xi) + 1 / (4 gamma) + O(1 / gamma^2) as gamma grows with xi fixed.
        for xi in (0.5, 1.0, 4.0):
            for gamma in (1e4, 1e6):
                self.assertAlmostEqual(mmse_stsa_gain(xi, gamma), xi / (1 + xi) + 0.25 / gamma, delta=2.0 / gamma**2 * (1 + 1 / xi) ** 2)

    def test_monotone_in_xi(self):
        for gamma in (0.5, 2.0, 20.0):
            vals = [mmse_stsa_gain(xi, gamma) for xi in (0.01, 0.1, 1.0, 10.0, 100.0)]
            self.assertEqual(vals, sorted(vals))

    def test_bad_input(self):
        with self.assertRaises(ValueError):
            mmse_stsa_gain(0.0, 1.0)


class TestEnhance(unittest.TestCase):
    def test_unit_gain_gives_identity(self):
        _, noisy = tone_in_noise(3)
        out = enhance(noisy, gain=lambda xi, gamma: 1.0)
        self.assertLess(max(abs(a - b) for a, b in zip(noisy[128:7800], out[128:7800])), 1e-12)

    def test_page_example(self):
        clean, noisy = tone_in_noise(3)
        out = enhance(noisy)
        self.assertAlmostEqual(snr_db(clean, noisy, 2400, 7600), 2.89, places=2)
        self.assertAlmostEqual(snr_db(clean, out, 2400, 7600), 15.00, places=2)
        p_in = sum(v * v for v in noisy[200:1400]) / 1200
        p_out = sum(v * v for v in out[200:1400]) / 1200
        self.assertGreater(10 * math.log10(p_in / p_out), 16.0)


if __name__ == "__main__":
    unittest.main()

History

Yariv Ephraim and David Malah, at the Technion in Israel, published the estimator in 1984 in the IEEE Transactions on Acoustics, Speech, and Signal Processing. The same paper introduced the decision-directed estimate of the a priori SNR, which became standard in speech enhancement. Their 1985 paper gave the log-spectral version. Olivier Cappé analyzed in 1994 why the method leaves little musical noise. The Gaussian model and the decision-directed rule were later used for voice activity detection by Sohn, Kim and Sung, and they remain the baseline that neural enhancement methods are compared with.

References

  1. Y. Ephraim and D. Malah, Speech enhancement using a minimum-mean square error short-time spectral amplitude estimator, IEEE Transactions on Acoustics, Speech, and Signal Processing 32(6), 1984, 1109 to 1121, the derivation of the amplitude estimator under the Gaussian model, its gain function, and the decision-directed estimate of the a priori SNR
  2. Y. Ephraim and D. Malah, Speech enhancement using a minimum mean-square error log-spectral amplitude estimator, IEEE Transactions on Acoustics, Speech, and Signal Processing 33(2), 1985, 443 to 445, the whole paper (the estimator of the log amplitude)
  3. O. Cappé, Elimination of the musical noise phenomenon with the Ephraim and Malah noise suppressor, IEEE Transactions on Speech and Audio Processing 2(2), 1994, 345 to 349, the whole paper (why the decision-directed estimate reduces musical noise)
  4. Philipos C. Loizou, Speech Enhancement, Theory and Practice, second edition, CRC Press, 2013, Chapter 7, Sections 7.3.1 (p. 211), 7.3.3.2 (p. 218) and 7.7 (log-MMSE, p. 227), and Appendix B (p. 661)

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