08. LPC, the source-filter model and formants

In the source-filter model of a vowel, the vocal folds produce a periodic train of air pulses (the source), and the throat, mouth and lips act as a resonant filter whose peaks, the formants, decide which vowel we hear. Linear predictive coding (LPC) fits an all-pole filter to a short frame of speech, so it estimates the filter part of that model: its roots are the formants, and speech codecs such as SILK (inside Opus) transmit a quantised form of its coefficients (as line spectral frequencies).

Learning outcomes. After working through this notebook you can

  • write down the source-filter model and convert a formant (frequency, bandwidth) into a pole pair and back;

  • derive the normal equations of linear prediction and solve them with the Levinson-Durbin recursion;

  • estimate formants from the roots of \(A(z)\) and choose the model order;

  • explain why autocorrelation LPC (written out here, as the Rust crate’s lpc_analysis does it) and Burg LPC (AudioSamples.lpc) give slightly different coefficients but the same formants.

The bindings’ LPC function, AudioSamples.lpc(order=...), fits the coefficients by Burg’s method. The windowed autocorrelation method with the Levinson-Durbin recursion (the Rust crate’s lpc_analysis and levinson_durbin, behind its opus-codec feature) has no Python binding. So this notebook uses the library for the signal container, windowing, autocorrelation, spectra, the Burg fit and the explanation of the method, and writes the Levinson-Durbin step in NumPy, exactly as the Rust crate does it.

import matplotlib.pyplot as plt
import numpy as np
import scipy.linalg
import scipy.signal

import audio_samples as aus

rng = np.random.default_rng(seed=2026)
F64 = np.dtype("float64")
FS = 16_000  # sample rate in Hz used throughout

Concept

Source-filter model. A voiced frame is modelled as

\[X(z) = E(z)\,H(z), \qquad H(z) = \frac{G}{A(z)}, \qquad A(z) = 1 + \sum_{k=1}^{p} a_k z^{-k}\]

where \(E(z)\) is the excitation (here an impulse train with one pulse every \(1/f_0\) seconds, \(f_0\) the fundamental frequency in Hz), \(H(z)\) the vocal-tract filter, \(G\) a gain, \(p\) the model order and \(a_k\) the (dimensionless) predictor coefficients. We write \(A(z)\) with a plus sign, as the Rust crate does; many textbooks predict \(\hat{x}[n] = \sum_k \alpha_k x[n-k]\) instead, so \(\alpha_k = -a_k\).

Formants as poles. One formant at frequency \(F\) (Hz) with 3 dB bandwidth \(B\) (Hz) is a pair of complex-conjugate poles at radius \(r\) and angle \(\theta\):

\[r \approx e^{-\pi B / f_s}, \qquad \theta = \frac{2\pi F}{f_s}\]

where \(f_s\) is the sample rate in Hz and \(\theta\) is in radians per sample. The radius formula is the usual narrow-band approximation (good for \(B \ll f_s\)); the notebook uses it as the definition of \(r\). Each pole pair contributes a factor \(1 - 2r\cos\theta\,z^{-1} + r^2 z^{-2}\) to \(A(z)\). Inverting: a root \(z_i\) of \(A(z)\) with \(\operatorname{Im} z_i > 0\) gives

\[F_i = \frac{f_s \arg z_i}{2\pi}, \qquad B_i = -\frac{f_s \ln|z_i|}{\pi}\]

Linear prediction. The prediction error (residual) is \(e[n] = x[n] + \sum_{k=1}^{p} a_k x[n-k]\). Minimising its energy over a windowed frame gives the normal (Yule-Walker) equations

\[\sum_{k=1}^{p} a_k R[|i-k|] = -R[i], \qquad i = 1, \dots, p\]

with the biased autocorrelation \(R[m] = \sum_{n=0}^{N-1-m} x_w[n]\,x_w[n+m]\) of the windowed frame \(x_w[n] = w[n]x[n]\) (\(N\) samples, \(w\) a Hamming window, \(R\) in squared signal units). The matrix is Toeplitz, so the Levinson-Durbin recursion solves it in \(O(p^2)\) operations, one order at a time (\(E_0 = R[0]\), \(m = 1, \dots, p\)):

\[k_m = -\frac{R[m] + \sum_{i=1}^{m-1} a_i^{(m-1)} R[m-i]}{E_{m-1}}, \qquad a_i^{(m)} = a_i^{(m-1)} + k_m a_{m-i}^{(m-1)}, \qquad a_m^{(m)} = k_m, \qquad E_m = (1 - k_m^2)E_{m-1}\]

where \(k_m\) is the (dimensionless) reflection coefficient, \(|k_m| < 1\) for a stable filter, and \(E_m\) the prediction-error energy of the order-\(m\) predictor.

Choosing \(p\). Each formant needs two poles and there is roughly one formant per kilohertz of bandwidth; two more poles absorb the spectral tilt of the source and lip radiation. Hence the rule of thumb \(p \approx f_s/1000 + 2\) (\(f_s\) in Hz), 18 at 16 kHz.

Pre-emphasis. Real glottal pulses fall off at about \(-12\) dB per octave, so high formants are weak and the fit spends poles on the tilt. The first-order high-pass \(y[n] = x[n] - \alpha x[n-1]\) with \(\alpha \approx 0.97\) flattens the spectrum before analysis.

With the library

We synthesise an /a/-like vowel at 16 kHz: formants (700, 80), (1220, 90) and (2600, 120) Hz as \((F, B)\), excited by an impulse train at \(f_0 = 120\) Hz (one pulse every \(\operatorname{round}(16000/120) = 133\) samples), and analyse a 512-sample (32 ms) frame taken after the filter has settled. These are the same numbers as the Rust guide chapter, so the results can be compared line by line.

formants = [(700.0, 80.0), (1220.0, 90.0), (2600.0, 120.0)]  # (F, B) in Hz

# A(z) as the product of one second-order section per formant.
a_true = np.array([1.0])
for f, b in formants:
    r, theta = np.exp(-np.pi * b / FS), 2 * np.pi * f / FS
    a_true = np.convolve(a_true, [1.0, -2 * r * np.cos(theta), r * r])
assert len(a_true) == 7  # three pole pairs: order 6

period = round(FS / 120)
assert period == 133
excitation = np.zeros(2400)
excitation[::period] = 1.0
vowel = scipy.signal.lfilter([1.0], a_true, excitation)  # 1/A(z)

# The Rust crate analyses f32 frames; we do the same so the numbers match the Rust chapter.
frame = aus.AudioSamples.new_mono(vowel[1600:2112].astype(np.float32), sample_rate=FS)
print(frame)
AudioSamples<f32>: 1 ch × 512 samples @ 16000 Hz (0.032 s)

The library’s rfft gives the magnitude spectrum of the Hamming-windowed frame (zero-padded to 4096 points for a smooth plot). It is a comb of harmonics at multiples of 120 Hz whose heights trace the vocal-tract response. The first check confirms that rfft returns \(|X[k]|\) with no scaling, as numpy.fft.rfft does.

N = len(frame)
windowed = frame.apply_window(np.hamming(N))  # Hamming: 0.54 - 0.46 cos(2 pi n/(N-1))
n_fft = 4096
mag = np.asarray(windowed.rfft(n_fft))[0]  # shape (1, n_fft/2 + 1) for mono
freqs = np.fft.rfftfreq(n_fft, 1 / FS)

reference = np.abs(np.fft.rfft(windowed.to_numpy().astype(np.float64), n_fft))
# f32 input, f64 FFT on both sides: agreement to ~1e-6 of the peak is rounding.
assert np.allclose(mag, reference, atol=1e-5 * reference.max())

fig, ax = plt.subplots(figsize=(8, 3))
ax.plot(freqs, 20 * np.log10(mag + 1e-12), lw=0.8)
for f, _ in formants:
    ax.axvline(f, color="C3", ls=":", lw=1)
ax.set(xlabel="Frequency (Hz)", ylabel="Magnitude (dB)", title="Windowed vowel frame (red: true formants)",
       xlim=(0, FS / 2))
plt.show()
../_images/01fc9629412ded21c1631de8a096fc737c2d40872abc838bf5a97cbf77788d39.png

LPC needs \(R[0], \dots, R[p]\) of the windowed frame. The library’s autocorrelation(max_lag) computes them, but with the unbiased normalisation \(R[m]/(N-m)\) (one value per lag, averaged over the number of products). Levinson-Durbin needs the biased sum \(R[m]\): only the biased estimate is guaranteed to give a positive-definite Toeplitz matrix, hence a stable \(1/A(z)\). So we multiply by \(N - m\).

p = 18
r_unbiased = np.asarray(windowed.autocorrelation(p), dtype=np.float64)
R = r_unbiased * (N - np.arange(p + 1))

xw = windowed.to_numpy().astype(np.float64)
R_direct = np.array([xw[: N - m] @ xw[m:] for m in range(p + 1)])
# Both sums run over the same f32 samples; 1e-9 relative is far above f64 rounding.
assert np.allclose(R, R_direct, rtol=1e-9)
assert np.isclose(r_unbiased[1], R_direct[1] / (N - 1))
print("R[0..3] =", np.round(R[:4], 2))
R[0..3] = [33357.88 31275.19 25390.32 16686.7 ]

How it works

Levinson-Durbin, written out. We follow the Rust crate’s lpc_analysis exactly: Hamming window, biased autocorrelation, and a tiny diagonal loading \(R[0] \leftarrow (1 + 10^{-5})R[0]\) for numerical safety. Then we check the answer against a general Toeplitz solver (scipy.linalg.solve_toeplitz, which is not Levinson-Durbin specific) and against the defining property: all \(p\) normal equations hold.

def levinson_durbin(R, p):
    # Solve sum_k a_k R[|i-k|] = -R[i] for A(z) = 1 + sum a_k z^-k. Returns (a, E_p, k).
    a = np.zeros(p + 1)
    a[0] = 1.0
    err = R[0]
    ks = np.zeros(p)
    for m in range(1, p + 1):
        k = -(R[m] + a[1:m] @ R[m - 1 : 0 : -1]) / err
        a[1:m] = a[1:m] + k * a[m - 1 : 0 : -1]  # right-hand side is evaluated first: uses a^(m-1)
        a[m] = k
        err *= 1.0 - k * k
        ks[m - 1] = k
    return a, err, ks


def lpc(x, p, loading=1e-5):
    # Autocorrelation-method LPC as in the Rust crate: Hamming window, biased R, diagonal loading.
    x = np.asarray(x, dtype=np.float32)
    n = len(x)
    xw = (np.hamming(n) * x).astype(np.float32).astype(np.float64)
    R = np.array([xw[: n - m] @ xw[m:] for m in range(p + 1)])
    R[0] *= 1.0 + loading
    return (*levinson_durbin(R, p), R)


a, E_p, ks, R_loaded = lpc(frame.to_numpy(), p)
print("a_1..a_3 =", np.round(a[1:4], 5), " E_p =", round(E_p, 3))

# 1. A general Toeplitz solver agrees; 1e-9 of the largest coefficient is ample for an
#    order-18 f64 solve (condition number here is about 1e5).
a_scipy = scipy.linalg.solve_toeplitz(R_loaded[:p], -R_loaded[1 : p + 1])
assert np.allclose(a[1:], a_scipy, atol=1e-9 * np.abs(a).max())
# 2. Every normal equation holds to rounding error.
T = scipy.linalg.toeplitz(R_loaded[:p])
assert np.allclose(T @ a[1:], -R_loaded[1 : p + 1], atol=1e-9 * R_loaded[0])
# 3. All reflection coefficients have |k| < 1, so 1/A(z) is stable.
assert np.all(np.abs(ks) < 1)
a_1..a_3 = [-2.50554  1.98543  0.04531]  E_p = 44.83

Prediction gain. Inverse filtering with \(A(z)\) (an FIR filter) leaves the residual \(e[n]\): mostly the pulses of the source, which a predictor built from the previous 18 samples cannot predict. The prediction gain \(10\log_{10}(\sum x^2/\sum e^2)\) is 13.8 dB, the same value as the Rust chapter’s lpc_residual.

x = frame.to_numpy().astype(np.float64)
residual = scipy.signal.lfilter(a, [1.0], x)  # e[n] = x[n] + sum a_k x[n-k], zero initial state
gain_db = 10 * np.log10(np.sum(x**2) / np.sum(residual**2))
print(f"prediction gain {gain_db:.2f} dB")
assert abs(gain_db - 13.8) < 0.05  # the Rust chapter's value, to the printed precision

fig, ax = plt.subplots(figsize=(8, 3))
t_ms = 1000 * np.arange(N) / FS
ax.plot(t_ms, x, lw=0.8, label="frame $x[n]$")
ax.plot(t_ms, residual, lw=0.8, label="residual $e[n]$")
ax.set(xlabel="Time (ms)", ylabel="Amplitude", title="Inverse filtering leaves the excitation pulses")
ax.legend(loc="upper right")
plt.show()
prediction gain 13.78 dB
../_images/d99997cbddf5c9e28bd3c618547cb2f2617d7a4ac2f7f8f83273735ea2aaefa6.png

From roots to formants. \(z^p A(z)\) is the polynomial \(z^p + a_1 z^{p-1} + \dots + a_p\), so np.roots(a) returns the \(p\) poles of \(1/A(z)\). Each root in the upper half plane converts to \((F_i, B_i)\) with the formulas above. LPC also places broad poles (bandwidths of a kilohertz or more) that shape the overall slope, so we keep only resonances narrower than 400 Hz.

def resonances(a, max_bandwidth=400.0):
    # (F, B) in Hz of the upper-half-plane roots of A(z) narrower than max_bandwidth, sorted by F.
    z = np.roots(a)
    z = z[z.imag > 0]
    F = np.angle(z) * FS / (2 * np.pi)
    B = -np.log(np.abs(z)) * FS / np.pi
    keep = B < max_bandwidth
    order = np.argsort(F[keep])
    return F[keep][order], B[keep][order]


assert np.all(np.abs(np.roots(a)) < 1)  # all poles inside the unit circle
F_est, B_est = resonances(a)
print("narrow resonances (F, B) in Hz:", [(round(float(f), 1), round(float(b), 1)) for f, b in zip(F_est, B_est)])
assert len(F_est) == 3
errors = np.round(F_est - [f for f, _ in formants])
# A periodic source samples the envelope only at multiples of 120 Hz, which biases
# autocorrelation LPC by a few hertz; these are the Rust chapter's numbers.
assert list(errors) == [11.0, -9.0, -3.0]
narrow resonances (F, B) in Hz: [(711.3, 65.9), (1210.8, 76.6), (2597.1, 138.6)]

The three formants are recovered to within 11 Hz (errors \(+11\), \(-9\) and \(-3\) Hz), with bandwidths of the right order. The small bias comes from the harmonic excitation: the frame’s spectrum samples the envelope only at multiples of \(f_0\).

An independent estimate: AudioSamples.lpc. The library’s lpc uses Burg’s method on the raw (unwindowed) frame, not the windowed autocorrelation method. Its coefficients therefore differ from the NumPy ones, but both are estimates of the same all-pole filter, so we compare the formants and the shape of the envelope \(|1/A(e^{j\omega})|\). librosa.lpc implements the same Burg recursion and serves as a cross-check.

import librosa

# lpc returns one row of order + 1 coefficients [1, a_1, ..., a_p] per channel.
a_burg = aus.AudioSamples.new_mono(x, sample_rate=FS).lpc(order=p)[0]
assert a_burg.dtype == F64 and a_burg[0] == 1.0  # f64 in, f64 out
# The same recursion as librosa.lpc in the same precision: equal to f64 rounding.
assert np.allclose(a_burg, librosa.lpc(x, order=p), rtol=0, atol=1e-12)
print("max |a_autocorrelation - a_burg| =", round(float(np.max(np.abs(a - a_burg))), 3))
assert np.max(np.abs(a - a_burg)) > 0.1  # different coefficients ...

F_burg, B_burg = resonances(a_burg)
print("Burg resonances:", [(round(float(f), 1), round(float(b), 1)) for f, b in zip(F_burg, B_burg)])
true_F = np.array([f for f, _ in formants])
# ... but the same three formants, each within 20 Hz (3 % of F1) of the truth.
assert len(F_burg) == 3 and np.all(np.abs(F_burg - true_F) < 20)
assert np.all(np.abs(F_est - true_F) < 20)
max |a_autocorrelation - a_burg| = 12.512
Burg resonances: [(710.5, 55.2), (1201.3, 63.0), (2609.1, 109.6)]

To compare envelope shapes we remove each curve’s mean level (the gain \(G\) is a separate question) and measure the RMS deviation from the true \(|1/A_{\text{true}}|\) in dB. Below 3 kHz both methods follow the true envelope to within 1 dB RMS. Above 4 kHz they diverge: the Hamming window’s sidelobes leak energy that fills in the deep high-frequency valley (the grey FFT in the plot flattens above 4 kHz), and the windowed autocorrelation LPC models that floor, spanning only 60 dB. Burg works on the unwindowed frame, which here is noiseless and exactly all-pole, and spans 95 dB against the true envelope’s 92 dB.

w_grid, H_true = scipy.signal.freqz([1.0], a_true, worN=1024, fs=FS)
_, H_ours = scipy.signal.freqz([1.0], a, worN=1024, fs=FS)
_, H_burg = scipy.signal.freqz([1.0], a_burg, worN=1024, fs=FS)
db = lambda h: 20 * np.log10(np.abs(h))


def shape_rms(h, lo, hi):
    band = (w_grid >= lo) & (w_grid < hi)
    d = db(h)[band] - db(H_true)[band]
    return float(np.sqrt(np.mean((d - d.mean()) ** 2)))


low_ours, low_burg = shape_rms(H_ours, 0, 3000), shape_rms(H_burg, 0, 3000)
high_ours, high_burg = shape_rms(H_ours, 4000, 8000), shape_rms(H_burg, 4000, 8000)
print(f"0-3 kHz shape error: ours {low_ours:.2f} dB, Burg {low_burg:.2f} dB")
print(f"4-8 kHz shape error: ours {high_ours:.2f} dB, Burg {high_burg:.2f} dB")
assert low_ours < 1.0 and low_burg < 1.0
assert high_ours > 5.0 and high_burg < 0.1

span = lambda h: db(h).max() - db(h).min()
print(f"dynamic range: true {span(H_true):.0f} dB, ours {span(H_ours):.0f} dB, Burg {span(H_burg):.0f} dB")
assert round(span(H_true)) == 92 and round(span(H_ours)) == 60 and round(span(H_burg)) == 95

# Plot: FFT of the frame and the envelopes, each shifted to the same level at 0-3 kHz.
fig, ax = plt.subplots(figsize=(8, 3))
ref = db(H_true)[w_grid < 3000].mean()
ax.plot(freqs, 20 * np.log10(mag + 1e-12) - (20 * np.log10(mag[freqs < 3000] + 1e-12).mean() - ref) - 10,
        lw=0.6, color="0.6", label="|FFT| of frame (shifted)")
for h, lab in [(H_true, "true 1/A"), (H_ours, "autocorrelation LPC"), (H_burg, "Burg (AudioSamples.lpc)")]:
    ax.plot(w_grid, db(h) - (db(h)[w_grid < 3000].mean() - ref), lw=1.2, label=lab)
ax.set(xlabel="Frequency (Hz)", ylabel="Level (dB, aligned)", title="LPC envelopes, order 18", xlim=(0, FS / 2))
ax.legend(fontsize=8, loc="lower left")
plt.show()
0-3 kHz shape error: ours 0.63 dB, Burg 0.83 dB
4-8 kHz shape error: ours 5.45 dB, Burg 0.02 dB
dynamic range: true 92 dB, ours 60 dB, Burg 95 dB
../_images/340c9c2271ade713ee72073bbb0cf37b473e53517822091ace2ecc76f30137c7.png

Ask the library to explain

aus.explain.lpc(order, sample_rate) prints the method in this notebook’s sign convention, the rule-of-thumb order and how many resonances the order can represent, with warnings when the order is far from the rule of thumb.

doc = aus.explain.lpc(18, 16_000.0)
assert doc.quantity("Rule-of-thumb order") == 18
assert doc.quantity("Resonances representable") == 9
assert doc.has_warning_containing("silently lowers the order")
# An order-4 model is far below the rule of thumb: a caution-level warning.
assert aus.explain.lpc(4, 16_000.0).has_warning("caution")
doc

Linear predictive coding (LPC)

An order-18 predictor models each sample as a weighted sum of the previous 18, which corresponds to an all-pole filter with up to 9 resonances (formants). At 16000 Hz the usual rule of thumb suggests about 18 coefficients.

Formulas

Prediction error (residual) and inverse filter; note the plus sign: the crate stores a_k with this convention:

$$ e[n] = x[n] + \sum_{k=1}^{p} a_k , x[n-k], \quad A(z) = 1 + \sum_{k=1}^{p} a_k z^{-k} $$

Autocorrelation of the Hamming-windowed frame (biased estimate); R[0] is multiplied by 1 + 1e-5 for numerical stability:

$$ R[m] = \sum_{n=0}^{N-1-m} w[n]x[n] , w[n+m]x[n+m] $$

Levinson-Durbin: reflection coefficient at step m (E_0 = R[0]):

$$ k_m = -\frac{R[m] + \sum_{i=1}^{m-1} a_i^{(m-1)} R[m-i]}{E_{m-1}} $$

Levinson-Durbin: coefficient and prediction-error updates:

$$ a_i^{(m)} = a_i^{(m-1)} + k_m , a_{m-i}^{(m-1)}, \quad a_m^{(m)} = k_m, \quad E_m = (1 - k_m^2) E_{m-1} $$

All-pole model of the vocal tract:

$$ H(z) = \frac{G}{A(z)} $$

Symbols

| Symbol | Meaning | Value | |—|—|—| | $p$ | predictor order | 18 | | $a_k$ | predictor coefficients | | | $k_m$ | reflection (PARCOR) coefficients, |k_m| < 1 for a stable model | | | $E_m$ | prediction-error energy after m steps | |

Derived quantities

| Quantity | Value | Formula | |—|—|—| | Rule-of-thumb order | $p_{rule}$ = 18 | $f_s / 1000 + 2$ | | Resonances representable | $\lfloor p/2 \rfloor$ = 9 | $\lfloor p/2 \rfloor$ | | Minimum frame length | $2p$ = 36 samples | $2p$ | | SILK reference order | $p_{SILK}$ = 16 | $\mathrm{SILK_LPC_ORDER}$ |

Trade-offs

  • The rule of thumb allows one pole pair per kHz of bandwidth (one formant per kHz) plus two poles for the glottal and radiation spectral tilt.

  • Too low an order merges formants; too high an order starts modelling individual harmonics of the voice instead of the envelope.

Warnings

  • Info: lpc_analysis (Rust only; not in the Python bindings) silently lowers the order to half the frame length for very short frames. Hint: Use frames of at least 36 samples.

See also

  • Analysis: audio_samples::lpc_analysis (feature opus-codec)

  • Recursion: audio_samples::levinson_durbin (feature opus-codec)

The informational warning refers to the Rust lpc_analysis, which lowers the order to half the frame length for very short frames; our NumPy lpc above has no such guard, and AudioSamples.lpc raises a ValueError when the order is not below the frame length.

Exercises

Exercise 1 (pole radius). Predict the pole radius of the 700 Hz formant (\(B = 80\) Hz) at \(f_s = 16\) kHz. What radius gives the same bandwidth at \(f_s = 8\) kHz? Store the pair (r16, r8) in answer.

answer = None  # TODO
# Solution
r16 = np.exp(-np.pi * 80 / 16_000)
r8 = np.exp(-np.pi * 80 / 8_000)
answer = (r16, r8)
# Halving f_s doubles B/f_s, so the pole moves away from the unit circle.
assert abs(r16 - 0.98441) < 5e-6 and abs(r8 - 0.96907) < 5e-6
print(f"r(16 kHz) = {r16:.5f}, r(8 kHz) = {r8:.5f}")
r(16 kHz) = 0.98441, r(8 kHz) = 0.96907

Exercise 2 (how many poles?). For the frame above, try orders 4, 6, 8, 10 and 12. Predict the smallest order that recovers all three formants (within 150 Hz, with \(B < 400\) Hz), then check. Why is the answer larger than \(2 \times 3\)? Store the smallest order in answer.

answer = None  # TODO
# Solution
def n_found(order):
    F, _ = resonances(lpc(frame.to_numpy(), order)[0])
    return sum(bool(np.any(np.abs(F - f) < 150)) for f, _ in formants)

counts = [n_found(order) for order in (4, 6, 8, 10, 12)]
print("formants found for orders 4, 6, 8, 10, 12:", counts)
assert counts == [0, 0, 2, 3, 3]
answer = 10
# Six poles suffice for a noise-excited, unwindowed frame; the Hamming window, the short frame
# and the harmonic excitation leave energy that LPC absorbs with extra broad poles: the "+2"
# margin of the rule of thumb.
formants found for orders 4, 6, 8, 10, 12: [0, 0, 2, 3, 3]

Exercise 3 (pre-emphasis). Pass the impulse train through two real poles at \(z = 0.95\) (a glottal-like tilt) before the vocal tract. At order 18, is the 2600 Hz formant still found (with \(B < 400\) Hz) without pre-emphasis? With \(y[n] = x[n] - 0.97x[n-1]\)? Store the rounded (frequency, bandwidth) of the pole nearest 2600 Hz without pre-emphasis in answer.

answer = None  # TODO
# Solution
glottal = scipy.signal.lfilter([1.0], np.convolve([1, -0.95], [1, -0.95]), excitation)
y = scipy.signal.lfilter([1.0], a_true, glottal)
raw = y[1600:2112]
pre = y[1600:2112] - 0.97 * y[1599:2111]


def nearest(x, f):
    F, B = resonances(lpc(x, 18)[0], max_bandwidth=np.inf)
    i = np.argmin(np.abs(F - f))
    return F[i], B[i]

f3, b3 = nearest(raw, 2600.0)
answer = (round(f3), round(b3))
assert answer == (2701, 729) and b3 > 400  # F3 is too broad without pre-emphasis
estimates = []
for f, _ in formants:
    fe, be = nearest(pre, f)
    assert abs(fe - f) < 30 and be < 400
    estimates.append(round(fe))
assert estimates == [709, 1219, 2577]  # all three back after pre-emphasis
print("without pre-emphasis:", answer, " with:", estimates)
without pre-emphasis: (2701, 729)  with: [709, 1219, 2577]

Exercise 4 (rule of thumb). What order does \(f_s/1000 + 2\) suggest at 8 kHz and at 44.1 kHz? Use the explainer and store the pair in answer.

answer = None  # TODO
# Solution
rule = lambda fs: aus.explain.lpc(10, fs).quantity("Rule-of-thumb order")
answer = (rule(8_000.0), rule(44_100.0))
assert answer[0] == 10 and abs(answer[1] - 46.1) < 1e-9
# 10 at 8 kHz (telephone speech; SILK narrowband also uses 10); 46.1 at 44.1 kHz, which is
# why speech is usually downsampled before LPC.
print(answer)
(10.0, 46.1)

Common pitfalls

  • Sign convention. \(A(z) = 1 + \sum a_k z^{-k}\) (this notebook and the Rust crate); the “predictor” form uses \(-a_k\).

  • Biased versus unbiased autocorrelation. AudioSamples.autocorrelation divides by \(N - m\); multiply back before Levinson-Durbin, or the Toeplitz matrix may not be positive definite.

  • Autocorrelation versus Burg. Burg’s method on the raw frame (the reference above) and the autocorrelation method with a Hamming window give slightly different coefficients and a shallower envelope. Compare formants or envelopes, not coefficients.

  • Not every pole is a formant. Filter roots by bandwidth (and frequency) before calling them formants, and expect estimates biased towards harmonics for high-pitched voices.

  • Pre-emphasis changes the gain and the residual, so undo it (with \(1/(1 - \alpha z^{-1})\)) if you resynthesise.

See also

  • Rust guide chapter: LPC, the source-filter model and formants (available from the next release; until then build the docs locally with cargo doc --features educational,full_no_plotting --open) (uses the crate’s lpc_analysis, levinson_durbin and lpc_residual).

  • Python API: AudioSamples.lpc, AudioSamples.apply_window, AudioSamples.autocorrelation, AudioSamples.rfft, aus.explain.lpc (API reference).

  • Previous: 07. Resampling. Next: 09. Pitch, which estimates the source half of the model.

References

  • Makhoul, J. (1975). Linear prediction: a tutorial review. Proceedings of the IEEE, 63(4), 561-580.

  • Rabiner, L. R. and Schafer, R. W. (1978). Digital Processing of Speech Signals. Prentice-Hall. Chapter 8 (linear predictive coding of speech).

  • Valin, J.-M., Vos, K. and Terriberry, T. (2012). Definition of the Opus Audio Codec. RFC 6716, IETF. (SILK’s LPC order and its line-spectral-frequency coding.)