{ "cells": [ { "cell_type": "markdown", "id": "c000", "metadata": {}, "source": [ "# 08. LPC, the source-filter model and formants\n", "\n", "In the source-filter model of a vowel, the vocal folds produce a periodic train of air pulses (the\n", "*source*), and the throat, mouth and lips act as a resonant filter whose peaks, the *formants*,\n", "decide which vowel we hear. Linear predictive coding (LPC) fits an all-pole filter to a short\n", "frame of speech, so it estimates the filter part of that model: its roots are the formants, and\n", "speech codecs such as SILK (inside Opus) transmit a quantised form of its coefficients (as line\n", "spectral frequencies).\n", "\n", "**Learning outcomes.** After working through this notebook you can\n", "\n", "* write down the source-filter model and convert a formant (frequency, bandwidth) into a pole\n", " pair and back;\n", "* derive the normal equations of linear prediction and solve them with the Levinson-Durbin\n", " recursion;\n", "* estimate formants from the roots of $A(z)$ and choose the model order;\n", "* explain why autocorrelation LPC (written out here, as the Rust crate's `lpc_analysis` does it)\n", " and Burg LPC (`AudioSamples.lpc`) give slightly different coefficients but the same formants.\n", "\n", "The bindings' LPC function, `AudioSamples.lpc(order=...)`, fits the coefficients by **Burg's\n", "method**. The windowed autocorrelation method with the Levinson-Durbin recursion (the Rust crate's\n", "`lpc_analysis` and `levinson_durbin`, behind its `opus-codec` feature) has no Python binding. So\n", "this notebook uses the library for the signal container, windowing, autocorrelation, spectra, the\n", "Burg fit and the explanation of the method, and writes the Levinson-Durbin step in NumPy, exactly\n", "as the Rust crate does it." ] }, { "cell_type": "code", "execution_count": null, "id": "c001", "metadata": {}, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "import numpy as np\n", "import scipy.linalg\n", "import scipy.signal\n", "\n", "import audio_samples as aus\n", "\n", "rng = np.random.default_rng(seed=2026)\n", "F64 = np.dtype(\"float64\")\n", "FS = 16_000 # sample rate in Hz used throughout" ] }, { "cell_type": "markdown", "id": "c002", "metadata": {}, "source": [ "## Concept\n", "\n", "**Source-filter model.** A voiced frame is modelled as\n", "\n", "$$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}$$\n", "\n", "where $E(z)$ is the excitation (here an impulse train with one pulse every $1/f_0$ seconds,\n", "$f_0$ the fundamental frequency in Hz), $H(z)$ the vocal-tract filter, $G$ a gain, $p$ the model\n", "order and $a_k$ the (dimensionless) predictor coefficients. We write $A(z)$ with a **plus** sign,\n", "as the Rust crate does; many textbooks predict\n", "$\\hat{x}[n] = \\sum_k \\alpha_k x[n-k]$ instead, so $\\alpha_k = -a_k$.\n", "\n", "**Formants as poles.** One formant at frequency $F$ (Hz) with 3 dB bandwidth $B$ (Hz) is a pair\n", "of complex-conjugate poles at radius $r$ and angle $\\theta$:\n", "\n", "$$r \\approx e^{-\\pi B / f_s}, \\qquad \\theta = \\frac{2\\pi F}{f_s}$$\n", "\n", "where $f_s$ is the sample rate in Hz and $\\theta$ is in radians per sample. The radius formula is\n", "the usual narrow-band approximation (good for $B \\ll f_s$); the notebook uses it as the definition\n", "of $r$. Each pole pair\n", "contributes a factor $1 - 2r\\cos\\theta\\,z^{-1} + r^2 z^{-2}$ to $A(z)$. Inverting: a root $z_i$\n", "of $A(z)$ with $\\operatorname{Im} z_i > 0$ gives\n", "\n", "$$F_i = \\frac{f_s \\arg z_i}{2\\pi}, \\qquad B_i = -\\frac{f_s \\ln|z_i|}{\\pi}$$\n", "\n", "**Linear prediction.** The prediction error (residual) is\n", "$e[n] = x[n] + \\sum_{k=1}^{p} a_k x[n-k]$. Minimising its energy over a windowed frame gives the\n", "*normal* (Yule-Walker) equations\n", "\n", "$$\\sum_{k=1}^{p} a_k R[|i-k|] = -R[i], \\qquad i = 1, \\dots, p$$\n", "\n", "with the biased autocorrelation $R[m] = \\sum_{n=0}^{N-1-m} x_w[n]\\,x_w[n+m]$ of the windowed\n", "frame $x_w[n] = w[n]x[n]$ ($N$ samples, $w$ a Hamming window, $R$ in squared signal units). The\n", "matrix is Toeplitz, so the **Levinson-Durbin** recursion solves it in $O(p^2)$ operations, one\n", "order at a time ($E_0 = R[0]$, $m = 1, \\dots, p$):\n", "\n", "$$k_m = -\\frac{R[m] + \\sum_{i=1}^{m-1} a_i^{(m-1)} R[m-i]}{E_{m-1}}, \\qquad\n", "a_i^{(m)} = a_i^{(m-1)} + k_m a_{m-i}^{(m-1)}, \\qquad a_m^{(m)} = k_m, \\qquad\n", "E_m = (1 - k_m^2)E_{m-1}$$\n", "\n", "where $k_m$ is the (dimensionless) reflection coefficient, $|k_m| < 1$ for a stable filter, and\n", "$E_m$ the prediction-error energy of the order-$m$ predictor.\n", "\n", "**Choosing $p$.** Each formant needs two poles and there is roughly one formant per kilohertz of\n", "bandwidth; two more poles absorb the spectral tilt of the source and lip radiation. Hence the rule\n", "of thumb $p \\approx f_s/1000 + 2$ ($f_s$ in Hz), 18 at 16 kHz.\n", "\n", "**Pre-emphasis.** Real glottal pulses fall off at about $-12$ dB per octave, so high formants are\n", "weak and the fit spends poles on the tilt. The first-order high-pass $y[n] = x[n] - \\alpha x[n-1]$\n", "with $\\alpha \\approx 0.97$ flattens the spectrum before analysis." ] }, { "cell_type": "markdown", "id": "c003", "metadata": {}, "source": [ "## With the library\n", "\n", "We synthesise an /a/-like vowel at 16 kHz: formants (700, 80), (1220, 90) and (2600, 120) Hz as\n", "$(F, B)$, excited by an impulse train at $f_0 = 120$ Hz (one pulse every\n", "$\\operatorname{round}(16000/120) = 133$ samples), and analyse a 512-sample (32 ms) frame taken\n", "after the filter has settled. These are the same numbers as the Rust guide chapter, so the results\n", "can be compared line by line." ] }, { "cell_type": "code", "execution_count": null, "id": "c004", "metadata": {}, "outputs": [], "source": [ "formants = [(700.0, 80.0), (1220.0, 90.0), (2600.0, 120.0)] # (F, B) in Hz\n", "\n", "# A(z) as the product of one second-order section per formant.\n", "a_true = np.array([1.0])\n", "for f, b in formants:\n", " r, theta = np.exp(-np.pi * b / FS), 2 * np.pi * f / FS\n", " a_true = np.convolve(a_true, [1.0, -2 * r * np.cos(theta), r * r])\n", "assert len(a_true) == 7 # three pole pairs: order 6\n", "\n", "period = round(FS / 120)\n", "assert period == 133\n", "excitation = np.zeros(2400)\n", "excitation[::period] = 1.0\n", "vowel = scipy.signal.lfilter([1.0], a_true, excitation) # 1/A(z)\n", "\n", "# The Rust crate analyses f32 frames; we do the same so the numbers match the Rust chapter.\n", "frame = aus.AudioSamples.new_mono(vowel[1600:2112].astype(np.float32), sample_rate=FS)\n", "print(frame)" ] }, { "cell_type": "markdown", "id": "c005", "metadata": {}, "source": [ "The library's `rfft` gives the magnitude spectrum of the Hamming-windowed frame (zero-padded to\n", "4096 points for a smooth plot). It is a comb of harmonics at multiples of 120 Hz whose heights\n", "trace the vocal-tract response. The first check confirms that `rfft` returns $|X[k]|$ with no\n", "scaling, as `numpy.fft.rfft` does." ] }, { "cell_type": "code", "execution_count": null, "id": "c006", "metadata": {}, "outputs": [], "source": [ "N = len(frame)\n", "windowed = frame.apply_window(np.hamming(N)) # Hamming: 0.54 - 0.46 cos(2 pi n/(N-1))\n", "n_fft = 4096\n", "mag = np.asarray(windowed.rfft(n_fft))[0] # shape (1, n_fft/2 + 1) for mono\n", "freqs = np.fft.rfftfreq(n_fft, 1 / FS)\n", "\n", "reference = np.abs(np.fft.rfft(windowed.to_numpy().astype(np.float64), n_fft))\n", "# f32 input, f64 FFT on both sides: agreement to ~1e-6 of the peak is rounding.\n", "assert np.allclose(mag, reference, atol=1e-5 * reference.max())\n", "\n", "fig, ax = plt.subplots(figsize=(8, 3))\n", "ax.plot(freqs, 20 * np.log10(mag + 1e-12), lw=0.8)\n", "for f, _ in formants:\n", " ax.axvline(f, color=\"C3\", ls=\":\", lw=1)\n", "ax.set(xlabel=\"Frequency (Hz)\", ylabel=\"Magnitude (dB)\", title=\"Windowed vowel frame (red: true formants)\",\n", " xlim=(0, FS / 2))\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "c007", "metadata": {}, "source": [ "LPC needs $R[0], \\dots, R[p]$ of the windowed frame. The library's `autocorrelation(max_lag)`\n", "computes them, but with the **unbiased** normalisation $R[m]/(N-m)$ (one value per lag, averaged\n", "over the number of products). Levinson-Durbin needs the *biased* sum $R[m]$: only the biased\n", "estimate is guaranteed to give a positive-definite Toeplitz matrix, hence a stable $1/A(z)$. So we\n", "multiply by $N - m$." ] }, { "cell_type": "code", "execution_count": null, "id": "c008", "metadata": {}, "outputs": [], "source": [ "p = 18\n", "r_unbiased = np.asarray(windowed.autocorrelation(p), dtype=np.float64)\n", "R = r_unbiased * (N - np.arange(p + 1))\n", "\n", "xw = windowed.to_numpy().astype(np.float64)\n", "R_direct = np.array([xw[: N - m] @ xw[m:] for m in range(p + 1)])\n", "# Both sums run over the same f32 samples; 1e-9 relative is far above f64 rounding.\n", "assert np.allclose(R, R_direct, rtol=1e-9)\n", "assert np.isclose(r_unbiased[1], R_direct[1] / (N - 1))\n", "print(\"R[0..3] =\", np.round(R[:4], 2))" ] }, { "cell_type": "markdown", "id": "c009", "metadata": {}, "source": [ "## How it works\n", "\n", "**Levinson-Durbin, written out.** We follow the Rust crate's `lpc_analysis` exactly: Hamming\n", "window, biased autocorrelation, and a tiny diagonal loading $R[0] \\leftarrow (1 + 10^{-5})R[0]$\n", "for numerical safety. Then we check the answer against a general Toeplitz solver\n", "(`scipy.linalg.solve_toeplitz`, which is not Levinson-Durbin specific) and against the defining\n", "property: all $p$ normal equations hold." ] }, { "cell_type": "code", "execution_count": null, "id": "c010", "metadata": {}, "outputs": [], "source": [ "def levinson_durbin(R, p):\n", " # Solve sum_k a_k R[|i-k|] = -R[i] for A(z) = 1 + sum a_k z^-k. Returns (a, E_p, k).\n", " a = np.zeros(p + 1)\n", " a[0] = 1.0\n", " err = R[0]\n", " ks = np.zeros(p)\n", " for m in range(1, p + 1):\n", " k = -(R[m] + a[1:m] @ R[m - 1 : 0 : -1]) / err\n", " a[1:m] = a[1:m] + k * a[m - 1 : 0 : -1] # right-hand side is evaluated first: uses a^(m-1)\n", " a[m] = k\n", " err *= 1.0 - k * k\n", " ks[m - 1] = k\n", " return a, err, ks\n", "\n", "\n", "def lpc(x, p, loading=1e-5):\n", " # Autocorrelation-method LPC as in the Rust crate: Hamming window, biased R, diagonal loading.\n", " x = np.asarray(x, dtype=np.float32)\n", " n = len(x)\n", " xw = (np.hamming(n) * x).astype(np.float32).astype(np.float64)\n", " R = np.array([xw[: n - m] @ xw[m:] for m in range(p + 1)])\n", " R[0] *= 1.0 + loading\n", " return (*levinson_durbin(R, p), R)\n", "\n", "\n", "a, E_p, ks, R_loaded = lpc(frame.to_numpy(), p)\n", "print(\"a_1..a_3 =\", np.round(a[1:4], 5), \" E_p =\", round(E_p, 3))\n", "\n", "# 1. A general Toeplitz solver agrees; 1e-9 of the largest coefficient is ample for an\n", "# order-18 f64 solve (condition number here is about 1e5).\n", "a_scipy = scipy.linalg.solve_toeplitz(R_loaded[:p], -R_loaded[1 : p + 1])\n", "assert np.allclose(a[1:], a_scipy, atol=1e-9 * np.abs(a).max())\n", "# 2. Every normal equation holds to rounding error.\n", "T = scipy.linalg.toeplitz(R_loaded[:p])\n", "assert np.allclose(T @ a[1:], -R_loaded[1 : p + 1], atol=1e-9 * R_loaded[0])\n", "# 3. All reflection coefficients have |k| < 1, so 1/A(z) is stable.\n", "assert np.all(np.abs(ks) < 1)" ] }, { "cell_type": "markdown", "id": "c011", "metadata": {}, "source": [ "**Prediction gain.** Inverse filtering with $A(z)$ (an FIR filter) leaves the residual $e[n]$:\n", "mostly the pulses of the source, which a predictor built from the previous 18 samples\n", "cannot predict. The prediction gain $10\\log_{10}(\\sum x^2/\\sum e^2)$ is 13.8 dB, the same value as\n", "the Rust chapter's `lpc_residual`." ] }, { "cell_type": "code", "execution_count": null, "id": "c012", "metadata": {}, "outputs": [], "source": [ "x = frame.to_numpy().astype(np.float64)\n", "residual = scipy.signal.lfilter(a, [1.0], x) # e[n] = x[n] + sum a_k x[n-k], zero initial state\n", "gain_db = 10 * np.log10(np.sum(x**2) / np.sum(residual**2))\n", "print(f\"prediction gain {gain_db:.2f} dB\")\n", "assert abs(gain_db - 13.8) < 0.05 # the Rust chapter's value, to the printed precision\n", "\n", "fig, ax = plt.subplots(figsize=(8, 3))\n", "t_ms = 1000 * np.arange(N) / FS\n", "ax.plot(t_ms, x, lw=0.8, label=\"frame $x[n]$\")\n", "ax.plot(t_ms, residual, lw=0.8, label=\"residual $e[n]$\")\n", "ax.set(xlabel=\"Time (ms)\", ylabel=\"Amplitude\", title=\"Inverse filtering leaves the excitation pulses\")\n", "ax.legend(loc=\"upper right\")\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "c013", "metadata": {}, "source": [ "**From roots to formants.** $z^p A(z)$ is the polynomial $z^p + a_1 z^{p-1} + \\dots + a_p$, so\n", "`np.roots(a)` returns the $p$ poles of $1/A(z)$. Each root in the upper half plane converts to\n", "$(F_i, B_i)$ with the formulas above. LPC also places broad poles (bandwidths of a kilohertz or\n", "more) that shape the overall slope, so we keep only resonances narrower than 400 Hz." ] }, { "cell_type": "code", "execution_count": null, "id": "c014", "metadata": {}, "outputs": [], "source": [ "def resonances(a, max_bandwidth=400.0):\n", " # (F, B) in Hz of the upper-half-plane roots of A(z) narrower than max_bandwidth, sorted by F.\n", " z = np.roots(a)\n", " z = z[z.imag > 0]\n", " F = np.angle(z) * FS / (2 * np.pi)\n", " B = -np.log(np.abs(z)) * FS / np.pi\n", " keep = B < max_bandwidth\n", " order = np.argsort(F[keep])\n", " return F[keep][order], B[keep][order]\n", "\n", "\n", "assert np.all(np.abs(np.roots(a)) < 1) # all poles inside the unit circle\n", "F_est, B_est = resonances(a)\n", "print(\"narrow resonances (F, B) in Hz:\", [(round(float(f), 1), round(float(b), 1)) for f, b in zip(F_est, B_est)])\n", "assert len(F_est) == 3\n", "errors = np.round(F_est - [f for f, _ in formants])\n", "# A periodic source samples the envelope only at multiples of 120 Hz, which biases\n", "# autocorrelation LPC by a few hertz; these are the Rust chapter's numbers.\n", "assert list(errors) == [11.0, -9.0, -3.0]" ] }, { "cell_type": "markdown", "id": "c015", "metadata": {}, "source": [ "The three formants are recovered to within 11 Hz (errors $+11$, $-9$ and $-3$ Hz), with\n", "bandwidths of the right order. The small bias comes from the harmonic excitation: the frame's\n", "spectrum samples the envelope only at multiples of $f_0$.\n", "\n", "**An independent estimate: `AudioSamples.lpc`.** The library's `lpc` uses **Burg's method** on\n", "the raw (unwindowed) frame, not the windowed autocorrelation method. Its coefficients therefore\n", "differ from the NumPy ones, but both are estimates of the same all-pole filter, so we compare the\n", "formants and the shape of the envelope $|1/A(e^{j\\omega})|$. `librosa.lpc` implements the same\n", "Burg recursion and serves as a cross-check." ] }, { "cell_type": "code", "execution_count": null, "id": "c016", "metadata": {}, "outputs": [], "source": [ "import librosa\n", "\n", "# lpc returns one row of order + 1 coefficients [1, a_1, ..., a_p] per channel.\n", "a_burg = aus.AudioSamples.new_mono(x, sample_rate=FS).lpc(order=p)[0]\n", "assert a_burg.dtype == F64 and a_burg[0] == 1.0 # f64 in, f64 out\n", "# The same recursion as librosa.lpc in the same precision: equal to f64 rounding.\n", "assert np.allclose(a_burg, librosa.lpc(x, order=p), rtol=0, atol=1e-12)\n", "print(\"max |a_autocorrelation - a_burg| =\", round(float(np.max(np.abs(a - a_burg))), 3))\n", "assert np.max(np.abs(a - a_burg)) > 0.1 # different coefficients ...\n", "\n", "F_burg, B_burg = resonances(a_burg)\n", "print(\"Burg resonances:\", [(round(float(f), 1), round(float(b), 1)) for f, b in zip(F_burg, B_burg)])\n", "true_F = np.array([f for f, _ in formants])\n", "# ... but the same three formants, each within 20 Hz (3 % of F1) of the truth.\n", "assert len(F_burg) == 3 and np.all(np.abs(F_burg - true_F) < 20)\n", "assert np.all(np.abs(F_est - true_F) < 20)" ] }, { "cell_type": "markdown", "id": "c017", "metadata": {}, "source": [ "To compare envelope *shapes* we remove each curve's mean level (the gain $G$ is a separate\n", "question) and measure the RMS deviation from the true $|1/A_{\\text{true}}|$ in dB. Below 3 kHz both\n", "methods follow the true envelope to within 1 dB RMS. Above 4 kHz they diverge: the Hamming\n", "window's sidelobes leak energy that fills in the deep high-frequency valley (the grey\n", "FFT in the plot flattens above 4 kHz), and the windowed autocorrelation LPC\n", "models that floor, spanning only 60 dB. Burg works on the unwindowed frame, which here is noiseless\n", "and exactly all-pole, and spans 95 dB against the true envelope's 92 dB." ] }, { "cell_type": "code", "execution_count": null, "id": "c018", "metadata": {}, "outputs": [], "source": [ "w_grid, H_true = scipy.signal.freqz([1.0], a_true, worN=1024, fs=FS)\n", "_, H_ours = scipy.signal.freqz([1.0], a, worN=1024, fs=FS)\n", "_, H_burg = scipy.signal.freqz([1.0], a_burg, worN=1024, fs=FS)\n", "db = lambda h: 20 * np.log10(np.abs(h))\n", "\n", "\n", "def shape_rms(h, lo, hi):\n", " band = (w_grid >= lo) & (w_grid < hi)\n", " d = db(h)[band] - db(H_true)[band]\n", " return float(np.sqrt(np.mean((d - d.mean()) ** 2)))\n", "\n", "\n", "low_ours, low_burg = shape_rms(H_ours, 0, 3000), shape_rms(H_burg, 0, 3000)\n", "high_ours, high_burg = shape_rms(H_ours, 4000, 8000), shape_rms(H_burg, 4000, 8000)\n", "print(f\"0-3 kHz shape error: ours {low_ours:.2f} dB, Burg {low_burg:.2f} dB\")\n", "print(f\"4-8 kHz shape error: ours {high_ours:.2f} dB, Burg {high_burg:.2f} dB\")\n", "assert low_ours < 1.0 and low_burg < 1.0\n", "assert high_ours > 5.0 and high_burg < 0.1\n", "\n", "span = lambda h: db(h).max() - db(h).min()\n", "print(f\"dynamic range: true {span(H_true):.0f} dB, ours {span(H_ours):.0f} dB, Burg {span(H_burg):.0f} dB\")\n", "assert round(span(H_true)) == 92 and round(span(H_ours)) == 60 and round(span(H_burg)) == 95\n", "\n", "# Plot: FFT of the frame and the envelopes, each shifted to the same level at 0-3 kHz.\n", "fig, ax = plt.subplots(figsize=(8, 3))\n", "ref = db(H_true)[w_grid < 3000].mean()\n", "ax.plot(freqs, 20 * np.log10(mag + 1e-12) - (20 * np.log10(mag[freqs < 3000] + 1e-12).mean() - ref) - 10,\n", " lw=0.6, color=\"0.6\", label=\"|FFT| of frame (shifted)\")\n", "for h, lab in [(H_true, \"true 1/A\"), (H_ours, \"autocorrelation LPC\"), (H_burg, \"Burg (AudioSamples.lpc)\")]:\n", " ax.plot(w_grid, db(h) - (db(h)[w_grid < 3000].mean() - ref), lw=1.2, label=lab)\n", "ax.set(xlabel=\"Frequency (Hz)\", ylabel=\"Level (dB, aligned)\", title=\"LPC envelopes, order 18\", xlim=(0, FS / 2))\n", "ax.legend(fontsize=8, loc=\"lower left\")\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "c019", "metadata": {}, "source": [ "## Ask the library to explain\n", "\n", "`aus.explain.lpc(order, sample_rate)` prints the method in this notebook's sign convention, the\n", "rule-of-thumb order and how many resonances the order can represent, with warnings when the order\n", "is far from the rule of thumb." ] }, { "cell_type": "code", "execution_count": null, "id": "c020", "metadata": {}, "outputs": [], "source": [ "doc = aus.explain.lpc(18, 16_000.0)\n", "assert doc.quantity(\"Rule-of-thumb order\") == 18\n", "assert doc.quantity(\"Resonances representable\") == 9\n", "assert doc.has_warning_containing(\"silently lowers the order\")\n", "# An order-4 model is far below the rule of thumb: a caution-level warning.\n", "assert aus.explain.lpc(4, 16_000.0).has_warning(\"caution\")\n", "doc" ] }, { "cell_type": "markdown", "id": "c021", "metadata": {}, "source": [ "The informational warning refers to the Rust `lpc_analysis`, which lowers the order to half the\n", "frame length for very short frames; our NumPy `lpc` above has no such guard, and `AudioSamples.lpc`\n", "raises a `ValueError` when the order is not below the frame length.\n", "\n", "## Exercises\n", "\n", "**Exercise 1 (pole radius).** Predict the pole radius of the 700 Hz formant ($B = 80$ Hz) at\n", "$f_s = 16$ kHz. What radius gives the same bandwidth at $f_s = 8$ kHz? Store the pair\n", "`(r16, r8)` in `answer`." ] }, { "cell_type": "code", "execution_count": null, "id": "c022", "metadata": {}, "outputs": [], "source": [ "answer = None # TODO" ] }, { "cell_type": "code", "execution_count": null, "id": "c023", "metadata": { "tags": [ "solution" ] }, "outputs": [], "source": [ "# Solution\n", "r16 = np.exp(-np.pi * 80 / 16_000)\n", "r8 = np.exp(-np.pi * 80 / 8_000)\n", "answer = (r16, r8)\n", "# Halving f_s doubles B/f_s, so the pole moves away from the unit circle.\n", "assert abs(r16 - 0.98441) < 5e-6 and abs(r8 - 0.96907) < 5e-6\n", "print(f\"r(16 kHz) = {r16:.5f}, r(8 kHz) = {r8:.5f}\")" ] }, { "cell_type": "markdown", "id": "c024", "metadata": {}, "source": [ "**Exercise 2 (how many poles?).** For the frame above, try orders 4, 6, 8, 10 and 12. Predict the\n", "smallest order that recovers all three formants (within 150 Hz, with $B < 400$ Hz), then check.\n", "Why is the answer larger than $2 \\times 3$? Store the smallest order in `answer`." ] }, { "cell_type": "code", "execution_count": null, "id": "c025", "metadata": {}, "outputs": [], "source": [ "answer = None # TODO" ] }, { "cell_type": "code", "execution_count": null, "id": "c026", "metadata": { "tags": [ "solution" ] }, "outputs": [], "source": [ "# Solution\n", "def n_found(order):\n", " F, _ = resonances(lpc(frame.to_numpy(), order)[0])\n", " return sum(bool(np.any(np.abs(F - f) < 150)) for f, _ in formants)\n", "\n", "counts = [n_found(order) for order in (4, 6, 8, 10, 12)]\n", "print(\"formants found for orders 4, 6, 8, 10, 12:\", counts)\n", "assert counts == [0, 0, 2, 3, 3]\n", "answer = 10\n", "# Six poles suffice for a noise-excited, unwindowed frame; the Hamming window, the short frame\n", "# and the harmonic excitation leave energy that LPC absorbs with extra broad poles: the \"+2\"\n", "# margin of the rule of thumb." ] }, { "cell_type": "markdown", "id": "c027", "metadata": {}, "source": [ "**Exercise 3 (pre-emphasis).** Pass the impulse train through two real poles at $z = 0.95$ (a\n", "glottal-like tilt) before the vocal tract. At order 18, is the 2600 Hz formant still found (with\n", "$B < 400$ Hz) without pre-emphasis? With $y[n] = x[n] - 0.97x[n-1]$? Store the rounded\n", "`(frequency, bandwidth)` of the pole nearest 2600 Hz without pre-emphasis in `answer`." ] }, { "cell_type": "code", "execution_count": null, "id": "c028", "metadata": {}, "outputs": [], "source": [ "answer = None # TODO" ] }, { "cell_type": "code", "execution_count": null, "id": "c029", "metadata": { "tags": [ "solution" ] }, "outputs": [], "source": [ "# Solution\n", "glottal = scipy.signal.lfilter([1.0], np.convolve([1, -0.95], [1, -0.95]), excitation)\n", "y = scipy.signal.lfilter([1.0], a_true, glottal)\n", "raw = y[1600:2112]\n", "pre = y[1600:2112] - 0.97 * y[1599:2111]\n", "\n", "\n", "def nearest(x, f):\n", " F, B = resonances(lpc(x, 18)[0], max_bandwidth=np.inf)\n", " i = np.argmin(np.abs(F - f))\n", " return F[i], B[i]\n", "\n", "f3, b3 = nearest(raw, 2600.0)\n", "answer = (round(f3), round(b3))\n", "assert answer == (2701, 729) and b3 > 400 # F3 is too broad without pre-emphasis\n", "estimates = []\n", "for f, _ in formants:\n", " fe, be = nearest(pre, f)\n", " assert abs(fe - f) < 30 and be < 400\n", " estimates.append(round(fe))\n", "assert estimates == [709, 1219, 2577] # all three back after pre-emphasis\n", "print(\"without pre-emphasis:\", answer, \" with:\", estimates)" ] }, { "cell_type": "markdown", "id": "c030", "metadata": {}, "source": [ "**Exercise 4 (rule of thumb).** What order does $f_s/1000 + 2$ suggest at 8 kHz and at 44.1 kHz?\n", "Use the explainer and store the pair in `answer`." ] }, { "cell_type": "code", "execution_count": null, "id": "c031", "metadata": {}, "outputs": [], "source": [ "answer = None # TODO" ] }, { "cell_type": "code", "execution_count": null, "id": "c032", "metadata": { "tags": [ "solution" ] }, "outputs": [], "source": [ "# Solution\n", "rule = lambda fs: aus.explain.lpc(10, fs).quantity(\"Rule-of-thumb order\")\n", "answer = (rule(8_000.0), rule(44_100.0))\n", "assert answer[0] == 10 and abs(answer[1] - 46.1) < 1e-9\n", "# 10 at 8 kHz (telephone speech; SILK narrowband also uses 10); 46.1 at 44.1 kHz, which is\n", "# why speech is usually downsampled before LPC.\n", "print(answer)" ] }, { "cell_type": "markdown", "id": "c033", "metadata": {}, "source": [ "## Common pitfalls\n", "\n", "- **Sign convention.** $A(z) = 1 + \\sum a_k z^{-k}$ (this notebook and the Rust crate); the\n", " \"predictor\" form uses $-a_k$.\n", "- **Biased versus unbiased autocorrelation.** `AudioSamples.autocorrelation` divides by $N - m$;\n", " multiply back before Levinson-Durbin, or the Toeplitz matrix may not be positive definite.\n", "- **Autocorrelation versus Burg.** Burg's method on the raw frame (the reference above) and the\n", " autocorrelation method with a Hamming window give slightly different coefficients and a\n", " shallower envelope. Compare formants or envelopes, not coefficients.\n", "- **Not every pole is a formant.** Filter roots by bandwidth (and frequency) before calling them\n", " formants, and expect estimates biased towards harmonics for high-pitched voices.\n", "- **Pre-emphasis changes the gain and the residual**, so undo it (with $1/(1 - \\alpha z^{-1})$) if\n", " you resynthesise.\n", "\n", "## See also\n", "\n", "- Rust guide chapter: [LPC, the source-filter model and formants](https://docs.rs/audio_samples/latest/audio_samples/guide/c08_lpc_formants/index.html) (available from the next release; until then build the docs locally with `cargo doc --features educational,full_no_plotting --open`)\n", " (uses the crate's `lpc_analysis`, `levinson_durbin` and `lpc_residual`).\n", "- Python API: `AudioSamples.lpc`, `AudioSamples.apply_window`, `AudioSamples.autocorrelation`,\n", " `AudioSamples.rfft`, `aus.explain.lpc` ([API reference](../api/audio_samples.rst)).\n", "- Previous: [07. Resampling](07_resampling.ipynb). Next: [09. Pitch](09_pitch.ipynb), which\n", " estimates the *source* half of the model." ] }, { "cell_type": "markdown", "id": "references", "metadata": {}, "source": [ "## References\n", "\n", "* Makhoul, J. (1975). Linear prediction: a tutorial review. *Proceedings of the IEEE*, 63(4), 561-580.\n", "* Rabiner, L. R. and Schafer, R. W. (1978). *Digital Processing of Speech Signals*. Prentice-Hall. Chapter 8 (linear predictive coding of speech).\n", "* 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.)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 5 }