{ "cells": [ { "cell_type": "markdown", "id": "c000", "metadata": {}, "source": [ "# 09. Pitch: autocorrelation and YIN\n", "\n", "The previous notebook recovered the vocal-tract filter; this one recovers the source. The\n", "fundamental frequency $f_0$ of voiced speech carries intonation, stress, speaker identity and, in\n", "tone languages, meaning. Pitch estimators look for the *period* of the waveform rather than for a\n", "spectral peak, which is why they still work when the fundamental itself is missing (as it is on a\n", "telephone line, which cuts everything below about 300 Hz).\n", "\n", "**Learning outcomes.** After working through this notebook you can\n", "\n", "* estimate $f_0$ with autocorrelation and explain why its answers lie on the grid $f_s/\\tau$;\n", "* compute YIN's difference function and cumulative-mean-normalised difference (CMND) in NumPy and\n", " reproduce `detect_pitch_yin` to rounding error;\n", "* recognise octave errors and the missing fundamental, and control them with the YIN threshold;\n", "* track pitch over time with `track_pitch` and choose a frame length from $f_{min}$." ] }, { "cell_type": "code", "execution_count": null, "id": "c001", "metadata": {}, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "import numpy as np\n", "\n", "import audio_samples as aus\n", "\n", "rng = np.random.default_rng(seed=2026)\n", "F64 = np.dtype(\"float64\") # generators default to float32\n", "FS = 16_000 # sample rate in Hz used throughout" ] }, { "cell_type": "markdown", "id": "c002", "metadata": {}, "source": [ "## Concept\n", "\n", "A signal is periodic with period $T_0$ seconds if $x(t) = x(t + T_0)$; its fundamental frequency\n", "is $f_0 = 1/T_0$ Hz. In samples the period is the lag $\\tau_0 = f_s/f_0$, where $f_s$ is the\n", "sample rate in Hz; in general $\\tau_0$ is not an integer.\n", "\n", "**Autocorrelation.** The (unnormalised) autocorrelation of an $N$-sample frame $x$ at lag $\\tau$\n", "(samples) is\n", "\n", "$$r(\\tau) = \\sum_{i=0}^{N-1-\\tau} x[i]\\,x[i+\\tau]$$\n", "\n", "It peaks at multiples of the period. The estimator searches\n", "$\\tau_{min} = \\lfloor f_s/f_{max} \\rfloor \\le \\tau \\le \\tau_{max} = \\lfloor f_s/f_{min} \\rfloor$\n", "($f_{min}$, $f_{max}$ the search range in Hz) and reports $\\hat{f}_0 = f_s/\\hat{\\tau}$. Because\n", "$\\hat{\\tau}$ is an integer, the answers lie on the grid $f_s/\\tau$, whose spacing near $f_0$ is\n", "\n", "$$\\Delta f = \\frac{f_s}{\\tau} - \\frac{f_s}{\\tau + 1} = \\frac{f_s}{\\tau(\\tau+1)} \\approx \\frac{f_0^2}{f_s}$$\n", "\n", "so the worst-case error is $\\Delta f/2$. For a 110 Hz voice at 16 kHz that is small\n", "($\\Delta f \\approx 0.76$ Hz, so the error is at most 0.38 Hz), but at 440 Hz the step is\n", "$\\Delta f \\approx 12$ Hz (errors up to about 6 Hz) and at 880 Hz it is about 47 Hz (errors up to\n", "about 23 Hz).\n", "\n", "**YIN** (de Cheveigné and Kawahara, 2002) replaces the product by a squared difference, normalises\n", "it and interpolates:\n", "\n", "$$d(\\tau) = \\sum_{j=0}^{N-1-\\tau} \\left(x[j] - x[j+\\tau]\\right)^2$$\n", "\n", "$$d'(0) = 1, \\qquad d'(\\tau) = \\frac{d(\\tau)}{\\frac{1}{\\tau}\\sum_{i=1}^{\\tau} d(i)}$$\n", "\n", "where $d(\\tau)$ (squared signal units) is the difference function over all $N - \\tau$\n", "overlapping pairs of samples and $d'(\\tau)$ (dimensionless) the CMND. $d'$ starts at 1, stays near 1 for lags shorter\n", "than the period and dips towards 0 at the period. The estimate is the first lag with\n", "$d'(\\tau) < \\theta$ ($\\theta$ the threshold, typically 0.1 to 0.2), moved forward to the bottom of\n", "that dip, and refined by a parabola through $d'(\\tau_0-1), d'(\\tau_0), d'(\\tau_0+1)$. With\n", "$a = d'(\\tau_0+1) + d'(\\tau_0-1) - 2d'(\\tau_0)$ and $b = (d'(\\tau_0+1) - d'(\\tau_0-1))/2$ the vertex\n", "lies at $\\tau_0 - b/a$:\n", "\n", "$$\\hat{\\tau} = \\tau_0 + \\frac{1}{2}\\,\\frac{d'(\\tau_0-1) - d'(\\tau_0+1)}{d'(\\tau_0-1) - 2d'(\\tau_0) + d'(\\tau_0+1)}, \\qquad \\hat{f}_0 = \\frac{f_s}{\\hat{\\tau}}$$\n", "\n", "so the period estimate is fractional and not restricted to the integer grid. The shift is\n", "skipped (left at 0) when $\\tau_0$ is at either end of the search range or when $|b| \\ge |a|$ (the\n", "vertex would lie more than one lag away). If no lag dips below $\\theta$ the frame is declared\n", "unvoiced.\n", "\n", "Two details differ from the paper. De Cheveigné and Kawahara's step 5 takes the period from a\n", "parabola fitted to the raw difference function $d(\\tau)$, because the abscissa of the\n", "interpolated $d'$ minimum is slightly biased; this library takes it from $d'$. And when no lag\n", "dips below $\\theta$, the paper falls back to the global minimum of $d'$, where this library\n", "returns \"unvoiced\". The paper's step 6, a \"best local estimate\" search around each frame, is not\n", "implemented. Finally, the paper sums $d(\\tau)$ over a fixed window of $W$ samples from the start\n", "of the frame;\n", "this library sums over all $N - \\tau$ overlapping pairs, so it measures the pitch of the whole\n", "frame rather than of its early part.\n", "\n", "**Octave errors.** A signal with period $\\tau_0$ also repeats at $2\\tau_0, 3\\tau_0, \\dots$; and if\n", "its odd harmonics are weak it *nearly* repeats at $\\tau_0/2$. Picking $2\\tau_0$ halves the\n", "estimate; picking $\\tau_0/2$ doubles it. YIN's \"first dip below $\\theta$\" rule guards against the\n", "first kind; the second is controlled by $\\theta$.\n", "\n", "**Frame length.** The difference function needs lags up to $\\tau_{max}$ plus a window, so both\n", "detectors in this library require $N > 2\\tau_{max} + 1$, i.e. at least $N_{min} = 2(\\tau_{max}+1)$\n", "samples, a little more than two periods of $f_{min}$." ] }, { "cell_type": "code", "execution_count": null, "id": "grid-steps", "metadata": {}, "outputs": [], "source": [ "# The grid steps and worst-case errors quoted above (tau: the nearest integer lag).\n", "for f0, step, step_tol, worst, worst_tol in [(110.0, 0.76, 0.005, 0.38, 0.005),\n", " (440.0, 12.0, 0.05, 6.0, 0.05),\n", " (880.0, 47.0, 0.5, 23.0, 0.5)]:\n", " tau = round(FS / f0)\n", " delta_f = FS / (tau * (tau + 1))\n", " print(f\"{f0:5.0f} Hz: tau = {tau}, grid step {delta_f:6.3f} Hz, worst-case error {delta_f / 2:6.3f} Hz\")\n", " assert abs(delta_f - step) < step_tol and abs(delta_f / 2 - worst) < worst_tol" ] }, { "cell_type": "markdown", "id": "c003", "metadata": {}, "source": [ "## With the library\n", "\n", "`detect_pitch_autocorr(min_frequency, max_frequency)` and\n", "`detect_pitch_yin(threshold, min_frequency, max_frequency)` analyse the **whole signal as one\n", "frame** and return `None` when no pitch is found. A 50 ms, 440 Hz tone:" ] }, { "cell_type": "code", "execution_count": null, "id": "c004", "metadata": {}, "outputs": [], "source": [ "x = aus.sine_wave(440.0, 0.05, sample_rate=FS, amplitude=0.8, dtype=F64)\n", "ac = x.detect_pitch_autocorr(80.0, 1000.0)\n", "yin = x.detect_pitch_yin(0.1, 80.0, 1000.0)\n", "print(f\"autocorrelation {ac:.2f} Hz, YIN {yin:.4f} Hz\")\n", "\n", "# The true period is 16000/440 = 36.36 samples. Autocorrelation must pick an integer\n", "# lag (36), so it reports 444.44 Hz: within half of the grid step f_s/36 - f_s/37.\n", "assert ac == FS / 36\n", "assert abs(ac - 440.0) <= 0.5 * (FS / 36 - FS / 37)\n", "# YIN interpolates the period and is within 0.1 Hz (440.0986 Hz).\n", "assert abs(yin - 440.0986) < 5e-5\n", "assert abs(yin - 440.0) < 0.1" ] }, { "cell_type": "markdown", "id": "c005", "metadata": {}, "source": [ "Repeating this for 110, 220, 440 and 880 Hz: the autocorrelation errors are $+0.34$, $-0.82$,\n", "$+4.44$ and $+8.89$ Hz, always within half a grid step; YIN's are $+0.0006$, $+0.0124$, $+0.0986$\n", "and $+1.2354$ Hz (the same numbers as the Rust guide's lab)." ] }, { "cell_type": "code", "execution_count": null, "id": "c006", "metadata": {}, "outputs": [], "source": [ "rows = []\n", "for f0 in (110.0, 220.0, 440.0, 880.0):\n", " tone = aus.sine_wave(f0, 0.05, sample_rate=FS, amplitude=0.8, dtype=F64)\n", " e_ac = tone.detect_pitch_autocorr(80.0, 1000.0) - f0\n", " e_yin = tone.detect_pitch_yin(0.1, 80.0, 1000.0) - f0\n", " tau = round(FS / f0)\n", " half_step = 0.5 * FS / (tau * (tau + 1))\n", " assert abs(e_ac) <= half_step + 1e-9\n", " rows.append((f0, e_ac, e_yin))\n", " print(f\"{f0:5.0f} Hz: autocorrelation {e_ac:+6.2f} Hz (half step {half_step:5.2f}), YIN {e_yin:+.4f} Hz\")\n", "\n", "assert np.allclose([r[1] for r in rows], [0.34, -0.82, 4.44, 8.89], atol=0.005)\n", "assert np.allclose([r[2] for r in rows], [0.0006, 0.0124, 0.0986, 1.2354], atol=5e-5) # rounding of the quoted values" ] }, { "cell_type": "markdown", "id": "c007", "metadata": {}, "source": [ "## How it works\n", "\n", "Both estimators are short enough to write out. We implement them exactly as the formulas above and\n", "compare with the library on the same 440 Hz frame." ] }, { "cell_type": "code", "execution_count": null, "id": "c008", "metadata": {}, "outputs": [], "source": [ "xs = x.to_numpy()\n", "n = len(xs)\n", "min_tau, max_tau = int(FS / 1000.0), int(FS / 80.0) # 16, 200\n", "\n", "# Autocorrelation: argmax of r(tau) over the lag range.\n", "r = np.array([xs[: n - tau] @ xs[tau:] for tau in range(max_tau + 1)])\n", "best = min_tau + int(np.argmax(r[min_tau : max_tau + 1]))\n", "assert best == 36 and FS / best == x.detect_pitch_autocorr(80.0, 1000.0)\n", "\n", "# YIN step 1: difference function over all n - tau overlapping pairs.\n", "d = np.array([np.sum((xs[: n - tau] - xs[tau:]) ** 2) for tau in range(max_tau + 1)])\n", "# Step 2: cumulative-mean-normalised difference d'.\n", "cmnd = np.ones(max_tau + 1)\n", "cmnd[1:] = d[1:] * np.arange(1, max_tau + 1) / np.cumsum(d[1:])\n", "# Step 3: first lag below theta, then down to the bottom of the dip.\n", "theta = 0.1\n", "tau = min_tau + int(np.argmax(cmnd[min_tau : max_tau + 1] < theta))\n", "assert tau == 34 # d'(34) = 0.0756 is already below 0.1 ...\n", "assert abs(cmnd[34] - 0.0756) < 1e-4 and abs(cmnd[36] - 0.0019) < 1e-4\n", "while tau < max_tau and cmnd[tau + 1] < cmnd[tau]:\n", " tau += 1\n", "assert tau == 36 # ... but the minimum of the dip is at 36\n", "# Step 4: parabolic interpolation (skipped at the ends of the range or when |b| >= |a|).\n", "a = cmnd[tau + 1] + cmnd[tau - 1] - 2 * cmnd[tau]\n", "b = (cmnd[tau + 1] - cmnd[tau - 1]) / 2\n", "shift = -b / a if min_tau < tau < max_tau and abs(b) < abs(a) else 0.0\n", "assert abs(shift - 0.3555) < 1e-4 # the true period is 36.3636 samples\n", "tau_hat = tau + shift\n", "f_hat = FS / tau_hat\n", "print(f\"d'(34..38) = {np.round(cmnd[34:39], 4)}; period {tau_hat:.4f} samples, f0 {f_hat:.4f} Hz\")\n", "# Same operations on the same f64 samples: agreement to rounding error.\n", "assert abs(f_hat - x.detect_pitch_yin(theta, 80.0, 1000.0)) < 1e-9\n", "\n", "fig, axs = plt.subplots(1, 2, figsize=(8, 3))\n", "lags = np.arange(max_tau + 1)\n", "axs[0].plot(lags[: max_tau + 1], r / r[0])\n", "axs[0].axvline(best, color=\"C3\", ls=\":\")\n", "axs[0].set(xlabel=\"Lag (samples)\", ylabel=\"r(τ)/r(0)\", title=\"Autocorrelation\")\n", "axs[1].plot(lags, cmnd)\n", "axs[1].axhline(theta, color=\"C2\", ls=\"--\", label=\"θ = 0.1\")\n", "axs[1].axvline(tau_hat, color=\"C3\", ls=\":\", label=\"τ̂\")\n", "axs[1].set(xlabel=\"Lag (samples)\", ylabel=\"d'(τ)\", title=\"YIN CMND\", xlim=(0, 120))\n", "axs[1].legend()\n", "plt.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "c009", "metadata": {}, "source": [ "**An independent reference: `librosa.yin`.** librosa implements the same CMND and parabolic\n", "interpolation, but frame by frame, with its own window ($W$ = half the frame length, here 512 of\n", "1024 samples) and with a fallback to the global minimum when no dip goes below the threshold. On\n", "0.5 s tones (median over frames) both implementations stay within 0.4 % of the truth, and they\n", "do not agree with each other to better than that because the windows differ." ] }, { "cell_type": "code", "execution_count": null, "id": "c010", "metadata": {}, "outputs": [], "source": [ "import librosa\n", "\n", "for f0 in (110.0, 220.0, 440.0, 880.0):\n", " tone = aus.sine_wave(f0, 0.5, sample_rate=FS, amplitude=0.8, dtype=F64)\n", " est_lib = np.median(librosa.yin(tone.to_numpy(), fmin=80, fmax=1000, sr=FS, frame_length=1024,\n", " center=False, trough_threshold=0.1))\n", " est_aus = tone.detect_pitch_yin(0.1, 80.0, 1000.0)\n", " print(f\"{f0:5.0f} Hz: audio_samples {est_aus - f0:+.3f} Hz, librosa {est_lib - f0:+.3f} Hz\")\n", " assert abs(est_aus - f0) / f0 < 0.004 and abs(est_lib - f0) / f0 < 0.004" ] }, { "cell_type": "markdown", "id": "c011", "metadata": {}, "source": [ "**Octave errors and the missing fundamental.** First, harmonics 2 to 6 of 200 Hz with equal\n", "amplitudes and nothing at 200 Hz itself. Then a signal whose odd harmonics (1, 3, 5) are 20 dB\n", "weaker than its even ones: its true period is still 80 samples (5 ms), but it is almost periodic at\n", "40 samples." ] }, { "cell_type": "code", "execution_count": null, "id": "c012", "metadata": {}, "outputs": [], "source": [ "N_C = 1600 # 0.1 s: 20 periods of 200 Hz, so FFT bins land on harmonics\n", "i = np.arange(N_C)\n", "\n", "\n", "def complex_tone(harmonics):\n", " y = sum(amp * np.cos(2 * np.pi * h * 200.0 * i / FS) for h, amp in harmonics)\n", " return aus.AudioSamples.new_mono(y, sample_rate=FS)\n", "\n", "\n", "# 1. Missing fundamental: no energy at 200 Hz, yet both detectors find it.\n", "missing = complex_tone([(2, 1.0), (3, 1.0), (4, 1.0), (5, 1.0), (6, 1.0)])\n", "spec = np.asarray(missing.rfft(N_C))[0] # bin k is at k * 10 Hz\n", "assert spec[20] < 1e-9 * spec[40] # bin 20 = 200 Hz is empty\n", "assert abs(missing.detect_pitch_yin(0.1, 80.0, 500.0) - 200.0) < 0.1\n", "assert missing.detect_pitch_autocorr(80.0, 500.0) == 200.0\n", "\n", "# 2. Weak odd harmonics: an octave error, controlled by the YIN threshold.\n", "weak = complex_tone([(1, 0.1), (2, 1.0), (3, 0.1), (4, 1.0), (5, 0.1), (6, 1.0)])\n", "yin_at = lambda theta: weak.detect_pitch_yin(theta, 80.0, 500.0)\n", "assert abs(yin_at(0.1) - 400.0) < 1.0 # octave error: half the period\n", "assert abs(yin_at(0.01) - 200.0) < 0.1 # strict threshold: the true period\n", "# Autocorrelation is biased towards short lags (fewer terms in the sum at long lags)\n", "# and doubles the pitch too.\n", "assert weak.detect_pitch_autocorr(80.0, 500.0) == 400.0\n", "# librosa.yin makes the same octave error on this signal at theta = 0.1.\n", "est = np.median(librosa.yin(weak.to_numpy(), fmin=80, fmax=500, sr=FS, frame_length=1024, center=False))\n", "assert abs(est - 400.0) < 1.0\n", "print(f\"YIN(0.1) {yin_at(0.1):.2f} Hz, YIN(0.01) {yin_at(0.01):.2f} Hz, librosa {est:.2f} Hz\")" ] }, { "cell_type": "markdown", "id": "c013", "metadata": {}, "source": [ "At the half period (lag 40) the CMND has a deep dip of its own (exercise 3 asks you to compute\n", "how deep): any threshold above that depth accepts the half period. A strict threshold corrects this signal but rejects more real,\n", "slightly aperiodic speech frames: that is the trade-off the threshold controls.\n", "\n", "**Tracking a glide.** `track_pitch(window_size, hop_size, method, threshold, min_frequency,\n", "max_frequency)` cuts the signal into frames of `window_size` samples every `hop_size` samples (no\n", "window function, no padding) and runs the detector on each. Each `PitchFrame`'s `time` is the\n", "frame **start**; for a linear glide the appropriate reference is the frequency at the frame centre.\n", "`PitchContour.frames()` and `mean_pitch()` are methods, not properties." ] }, { "cell_type": "code", "execution_count": null, "id": "c014", "metadata": {}, "outputs": [], "source": [ "# 0.5 s linear glide from 100 to 200 Hz: f(t) = 100 + 200 t.\n", "glide = aus.chirp(100.0, 200.0, 0.5, sample_rate=FS, amplitude=0.8, dtype=F64)\n", "YIN = aus.PitchDetectionMethod.yin\n", "\n", "# 512 samples (32 ms) is more than the 402 needed to search down to 80 Hz.\n", "track = glide.track_pitch(512, 128, YIN, 0.1, 80.0, 400.0)\n", "full = [f for f in track.frames() if f.time + 512 / FS <= 0.5]\n", "truth = np.array([100 + 200 * (f.time + 256 / FS) for f in full])\n", "est = np.array([f.frequency for f in full]) # every full frame is voiced\n", "worst = np.max(np.abs(est - truth))\n", "print(f\"worst error {worst:.2f} Hz over {len(full)} full frames ({len(track)} frames in total)\")\n", "assert worst < 1.0 and abs(worst - 0.12) < 0.005\n", "\n", "# 256 samples (16 ms) cannot hold two periods of 80 Hz: every frame is unvoiced.\n", "short = glide.track_pitch(256, 64, YIN, 0.1, 80.0, 400.0)\n", "assert all(f.frequency is None for f in short.frames()) and short.mean_pitch() is None\n", "\n", "fig, ax = plt.subplots(figsize=(8, 3))\n", "ax.plot([f.time + 256 / FS for f in full], est, \"o\", ms=3, label=\"track_pitch (YIN), frame centre\")\n", "ax.plot([f.time + 256 / FS for f in full], truth, lw=1, label=\"true f(t)\")\n", "ax.set(xlabel=\"Time (s)\", ylabel=\"f0 (Hz)\", title=\"Tracking a 100-200 Hz glide\")\n", "ax.legend()\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "c015", "metadata": {}, "source": [ "## Ask the library to explain\n", "\n", "`aus.explain.yin` and `aus.explain.autocorrelation_pitch` evaluate the formulas at your settings:\n", "lag range, minimum frame length, the integer-lag pitch steps, and warnings for frames that are too\n", "short or ranges prone to octave errors." ] }, { "cell_type": "code", "execution_count": null, "id": "c016", "metadata": {}, "outputs": [], "source": [ "doc = aus.explain.yin(0.1, 80.0, 400.0, 16_000.0, frame_length=256)\n", "assert doc.quantity(\"Longest lag\") == 200\n", "assert doc.quantity(\"Minimum frame length\") == 402\n", "assert doc.has_warning(\"problem\") # 256 < 402\n", "assert not aus.explain.yin(0.1, 80.0, 400.0, 16_000.0, frame_length=512).has_warning(\"problem\")\n", "doc" ] }, { "cell_type": "code", "execution_count": null, "id": "c017", "metadata": {}, "outputs": [], "source": [ "doc = aus.explain.autocorrelation_pitch(80.0, 1000.0, 16_000.0)\n", "assert doc.quantity(\"Shortest lag\") == 16\n", "step = doc.quantity(\"Pitch step at f_max\")\n", "assert abs(step - (1000.0 - 16_000.0 / 17)) < 1e-9 # 58.8 Hz\n", "assert doc.has_warning_containing(\"octave errors\")\n", "doc" ] }, { "cell_type": "markdown", "id": "c018", "metadata": {}, "source": [ "## Exercises\n", "\n", "**Exercise 1 (grid step).** Near 1 kHz at $f_s = 16$ kHz, how far apart are neighbouring\n", "autocorrelation estimates? Compare with $f_0^2/f_s$. Store the step in Hz in `answer`." ] }, { "cell_type": "code", "execution_count": null, "id": "c019", "metadata": {}, "outputs": [], "source": [ "answer = None # TODO" ] }, { "cell_type": "code", "execution_count": null, "id": "c020", "metadata": { "tags": [ "solution" ] }, "outputs": [], "source": [ "# Solution\n", "answer = 16_000 / 16 - 16_000 / 17\n", "assert abs(answer - 58.82) < 0.01\n", "assert 1000.0**2 / 16_000 == 62.5 # tau(tau+1) ~ tau^2 is coarse for short lags\n", "assert abs(aus.explain.autocorrelation_pitch(80.0, 1000.0, 16_000.0).quantity(\"Pitch step at f_max\") - answer) < 1e-9\n", "print(f\"{answer:.2f} Hz versus f0^2/f_s = 62.5 Hz\")" ] }, { "cell_type": "markdown", "id": "c021", "metadata": {}, "source": [ "**Exercise 2 (low voices).** A bass singer goes down to 60 Hz. What is the minimum YIN frame\n", "length at 16 kHz? Predict what `track_pitch` returns on a 70 Hz tone with 512-sample frames and\n", "$f_{min} = 60$ Hz, then check. Store the minimum frame length 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", "answer = 2 * (16_000 // 60 + 1) # tau_max = 266\n", "assert answer == 534 # 33.4 ms\n", "doc = aus.explain.yin(0.1, 60.0, 400.0, 16_000.0, frame_length=512)\n", "assert doc.quantity(\"Minimum frame length\") == answer\n", "assert doc.has_warning_containing(\"shorter than the 534 samples\")\n", "\n", "low = aus.sine_wave(70.0, 0.3, sample_rate=FS, amplitude=0.8, dtype=F64)\n", "# 512 samples hold more than two 70 Hz periods (457 samples), but not the whole *search* range:\n", "assert all(f.frequency is None for f in low.track_pitch(512, 128, YIN, 0.1, 60.0, 400.0).frames())\n", "assert abs(low.track_pitch(1024, 256, YIN, 0.1, 60.0, 400.0).mean_pitch() - 70.0) < 0.5" ] }, { "cell_type": "markdown", "id": "c024", "metadata": {}, "source": [ "**Exercise 3 (choosing the threshold).** For the weak-odd-harmonics signal above, compute $d'(40)$\n", "yourself (lag range of the 80-500 Hz search, $\\tau_{max} = 200$) and predict the YIN estimate with\n", "$\\theta = 0.021$ and $\\theta = 0.019$. Store $d'(40)$ 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", "w = weak.to_numpy()\n", "max_tau = 200\n", "# d summed over all N - tau overlapping pairs, as in the Concept section.\n", "d = np.array([np.sum((w[: len(w) - t] - w[t:]) ** 2) for t in range(max_tau + 1)])\n", "cm = lambda t: d[t] * t / d[1 : t + 1].sum()\n", "answer = cm(40)\n", "assert abs(answer - 0.0196) < 5e-5\n", "assert all(cm(t) > answer for t in range(32, 40)) # 40 is the bottom of the dip\n", "assert abs(weak.detect_pitch_yin(0.021, 80.0, 500.0) - 400.0) < 1.0 # accepts the half period\n", "assert abs(weak.detect_pitch_yin(0.019, 80.0, 500.0) - 200.0) < 0.1 # continues to the true period\n", "print(f\"d'(40) = {answer:.4f}\")" ] }, { "cell_type": "markdown", "id": "c027", "metadata": {}, "source": [ "## Common pitfalls\n", "\n", "- **Frame length is set by $f_{min}$**, not by the pitch you expect: frames of at most\n", " $2\\lfloor f_s/f_{min} \\rfloor + 1$ samples always return `None`.\n", "- **`detect_pitch_yin` is clip-global**: one number for the whole signal, silence included. Use\n", " `track_pitch` for anything longer than a steady frame.\n", "- **`PitchFrame.time` is the frame start**, not its centre; shift by half a frame to compare\n", " with a tracker that reports centred frames.\n", "- **No fallback.** This library's YIN declares a frame with no dip below $\\theta$ unvoiced,\n", " instead of falling back to the global minimum of $d'$ (as the `librosa.yin` reference above\n", " does), and it sums the difference function over all $N - \\tau$ overlapping pairs rather than\n", " a fixed window.\n", "- **The autocorrelation estimate is quantised** to $f_s/\\tau$; use YIN when you need better than\n", " $f_0^2/f_s$.\n", "- **Octave errors are a property of the signal**, not of the implementation: narrow $[f_{min}, f_{max}]$ when you\n", " know the speaker, and lower $\\theta$ when harmonics alternate in strength.\n", "- **Generators default to `float32`.** Pass `dtype=np.dtype(\"float64\")` when you want to compare\n", " with a float64 re-derivation to rounding error.\n", "\n", "## See also\n", "\n", "- Rust guide chapter: [Pitch: autocorrelation and YIN](https://docs.rs/audio_samples/latest/audio_samples/guide/c09_pitch/index.html) (available from the next release; until then build the docs locally with `cargo doc --features educational,full_no_plotting --open`).\n", "- Python API: `AudioSamples.detect_pitch_yin`, `AudioSamples.detect_pitch_autocorr`,\n", " `AudioSamples.track_pitch`, `PitchContour`, `PitchFrame`, `aus.explain.yin`,\n", " `aus.explain.autocorrelation_pitch` ([API reference](../api/audio_samples.rst)).\n", "- Previous: [08. LPC and formants](08_lpc_formants.ipynb). Next:\n", " [10. Cepstrum, mel and MFCC](10_cepstrum_mel_mfcc.ipynb), which finds the pitch a third way." ] }, { "cell_type": "markdown", "id": "references", "metadata": {}, "source": [ "## References\n", "\n", "* de Cheveigné, A. and Kawahara, H. (2002). YIN, a fundamental frequency estimator for speech and music. *Journal of the Acoustical Society of America*, 111(4), 1917-1930.\n", "* Rabiner, L. R. and Schafer, R. W. (1978). *Digital Processing of Speech Signals*. Prentice-Hall. Chapter 4 (short-time autocorrelation and pitch period estimation)." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 5 }