Algorithm Search⌘K

Algorithmadvanced

RAPT pitch tracker

Also called robust algorithm for pitch tracking.

Talkin's pitch tracker. Candidate periods from normalized cross-correlation peaks, then a dynamic program picks the best voiced or unvoiced path.

Time
O(F (K n + C^2)) worst
Space
O(K + n + F C) extra
Where
C = the most candidates per frame; F = the number of frames; K = the largest lag in samples; n = the correlation window in samples
Properties
deterministicnot exactnot in placeoffline
Origin
David Talkin, 1995

RAPT, the robust algorithm for pitch tracking, is a pitch tracker by David Talkin (1995) that finds several period candidates in each frame and then chooses one candidate, or the label unvoiced, per frame with a dynamic program. The candidates are the peaks of the normalized cross-correlation (NCCF) of the frame with later parts of the signal, and the dynamic program adds costs for weak peaks, for changes of pitch and for switches of voicing. It is close to pYIN, which also keeps candidates and decodes a track, but with probabilities from YIN and a hidden Markov model instead of hand-set costs, and to the cepstral detector, which decides each frame alone.

In plain words

Take a short piece of the sound and slide it along the sound that follows. Where the piece matches the sound one period later, the match score is close to 1. In speech, the score is also high at two and three periods, and noise gives small bumps everywhere. RAPT keeps every clear bump as a possible period, plus one "no pitch" choice. Then it looks at the whole utterance. It prefers strong bumps, short periods, small changes from one frame to the next, and few switches between voice and silence. A switch is cheaper where the loudness or the spectrum changes. The cheapest path through all the choices is the pitch track.

The problem

Given a signal at a sample rate fsf_s and a pitch range F0min⁡F_{0\min} to F0max⁡F_{0\max} (50 to 500 Hz by default), return for every frame (every 10 ms by default) either a fundamental frequency in Hz or the label unvoiced. The task and its error measures are on the pitch detection page. The lag range in samples is kmin⁡=⌊fs/F0max⁡⌋k_{\min} = \lfloor f_s / F_{0\max} \rfloor to K=⌈fs/F0min⁡⌉K = \lceil f_s / F_{0\min} \rceil.

The algorithm

For a frame that starts at sample mm, with a window of nn samples (7.5 ms by default), the NCCF at lag kk is

ϕ(k)=∑j=mm+n−1xj xj+kem em+k,ej=∑l=jj+n−1xl2.\phi(k) = \frac{\sum_{j=m}^{m+n-1} x_j\, x_{j+k}}{\sqrt{e_m\, e_{m+k}}}, \qquad e_j = \sum_{l=j}^{j+n-1} x_l^2 .

Unlike the plain autocorrelation, each lag is normalized by the energy of both windows, so ∣ϕ(k)∣≤1|\phi(k)| \le 1 and the value does not fall off at long lags. The voiced candidates of the frame are the local maxima of ϕ\phi with ϕ≥\phi \ge CAND_TR times the largest value, at most N_CANDS minus 1 of them, refined by a parabola through three points. Each candidate jj has a lag LjL_j and a value CjC_j. One more candidate means unvoiced.

The local costs of frame ii are (Talkin's equations 3.6 and 3.7)

di,j=1−Ci,j(1−LAG_WTKLi,j),di,unv=VO_BIAS+max⁡jCi,j.d_{i,j} = 1 - C_{i,j} \Bigl(1 - \frac{\text{LAG\_WT}}{K} L_{i,j}\Bigr), \qquad d_{i,\text{unv}} = \text{VO\_BIAS} + \max_j C_{i,j}.

The transition costs from candidate kk of frame i−1i - 1 to candidate jj of frame ii are, with ξ=∣ln⁡(Li,j/Li−1,k)∣\xi = |\ln(L_{i,j} / L_{i-1,k})| (equations 3.8 to 3.15),

from to cost
voiced voiced FREQ_WT ⋅min⁡(ξ, DOUBL_C+∣ξ−ln⁡2∣)\cdot \min(\xi,\ \text{DOUBL\_C} + \lvert \xi - \ln 2 \rvert)
unvoiced voiced VTRAN_C + VTR_S_C ⋅Si\cdot S_i + VTR_A_C /ri/ r_i
voiced unvoiced VTRAN_C + VTR_S_C ⋅Si\cdot S_i + VTR_A_C ⋅ri\cdot r_i
unvoiced unvoiced 0

Here rir_i is the ratio of the RMS of frame ii to the RMS of frame i−1i - 1, so an onset is cheap where the level rises and an offset is cheap where it falls. Si=0.2/(Ii−0.8)S_i = 0.2 / (I_i - 0.8), where Ii≥1I_i \ge 1 is the Itakura ratio of the LPC spectra of the two frames, so a voicing switch is cheap where the spectrum changes. The defaults (Talkin's table) are CAND_TR 0.3, LAG_WT 0.3, FREQ_WT 0.02, VTRAN_C 0.005, VTR_A_C 0.5, VTR_S_C 0.5, VO_BIAS 0, DOUBL_C 0.35 and N_CANDS 20.

  1. RAPT(x, fs)
  2. 1for each frame i: phi_i(k) <- the NCCF at lag k for k_min - 1 <= k <= K + 1
  3. 2cands_i <- the interpolated local maxima of phi_i with value >= CAND_TR * max, at most N_CANDS - 1, plus unvoiced
  4. 3d_i(j) <- 1 - C_j (1 - LAG_WT L_j / K) for voiced j; d_i(unvoiced) <- VO_BIAS + max_j C_j
  5. 4r_i <- RMS ratio to frame i - 1; S_i <- 0.2 / (Itakura ratio - 0.8)
  6. 5D_1(j) <- d_1(j) for every candidate j of frame 1
  7. 6for i <- 2 to F do
  8. 7D_i(j) <- d_i(j) + min over k of (D_{i-1}(k) + delta_i(k, j)); psi_i(j) <- the argmin
  9. 8j_F <- the argmin of D_F
  10. 9for i <- F down to 2 do j_{i-1} <- psi_i(j_i)
  11. 10return fs / L for each frame whose chosen candidate is voiced, else unvoiced

Lines L1 to L4 are the per-frame stage and lines L5 to L9 the dynamic program (equations 3.17 and 3.18). The code here computes the NCCF at the full rate. The paper does it in two passes, which is faster: a first pass on a copy of the signal downsampled to about 4F0max⁡4 F_{0\max} finds the rough peaks, and a second pass computes the NCCF at the full rate only near those peaks.

Example

The dynamic program. Take fs=8000f_s = 8000 Hz, so K=160K = 160 and LAG_WT/K=0.001875/K = 0.001875. Four frames have these voiced candidates (lag, value) and frame values rir_i and SiS_i:

frame candidates rir_i SiS_i
1 (40, 0.95), (80, 0.90)
2 (40, 0.45), (120, 0.40) 1 1
3 (40, 0.94), (80, 0.88) 1 1
4 (97, 0.30) 0.1 0.2

The local costs are

frame first second unvoiced
1 0.12125 0.235 0.95
2 0.58375 0.69 0.45
3 0.1305 0.252 0.94
4 0.75456 0.30

Alone, frame 2 would be unvoiced, since 0.45<0.583750.45 < 0.58375. But each switch between frames 1 to 3 costs 0.005+0.5+0.5=1.0050.005 + 0.5 + 0.5 = 1.005, so the path 40, unvoiced, 40 pays 2.01 for two switches. The best path is 40, 40, 40, unvoiced, with cost

0.12125+0.58375+0.1305+0.30+(0.005+0.5⋅0.2+0.5⋅0.1)=1.2905.0.12125 + 0.58375 + 0.1305 + 0.30 + (0.005 + 0.5 \cdot 0.2 + 0.5 \cdot 0.1) = 1.2905 .

The last switch is cheap, 0.155, because the level falls by a factor of 10 and the spectrum changes. The next best path, which starts at lag 80 in frame 1, costs 1.41125. The frequency of the first three frames is 8000/40=2008000 / 40 = 200 Hz. A search over all 3⋅3⋅3⋅2=543 \cdot 3 \cdot 3 \cdot 2 = 54 paths gives the same answer.

A track. A 160 Hz pulse train through a resonance at 500 Hz, 1200 samples long, followed by 800 samples of noise with standard deviation 0.02, gives 23 frames. On the periodic part the NCCF is 1.0 at lags 50, 100 and 150, and the lag cost picks 50, so the first 14 frames give 159.85 to 160.2 Hz. On the noise the largest NCCF peak is between 0.25 and 0.4, the unvoiced cost is lower, and the offset is cheap there (r=0.585r = 0.585 and S=0.166S = 0.166 at frame 14), so the last 9 frames are unvoiced.

Correctness

RAPT is an estimator, so no theorem says that its track is the true pitch. The provable parts are these. The NCCF lies in [−1,1][-1, 1] by the Cauchy-Schwarz inequality, and it equals 1 at every multiple of the period of a periodic signal with a nonzero frame. The Itakura ratio is at least 1, because the LPC inverse filter of a frame minimizes the quadratic form of its autocorrelation matrix, so Si≤1S_i \le 1. And the dynamic program returns a path of least total cost, by induction on the frames: the best path to candidate jj of frame ii extends a best path to some candidate of frame i−1i - 1, because the cost is a sum of terms that each depend on one frame or one pair of neighbors. The proofs are in proofs/correctness.md.

The costs themselves are heuristics. Talkin chose the defaults by hand on speech data.

Proof: Correctness of the RAPT pitch trackerfull

RAPT is an estimator with costs set by hand, so we do not prove that its track is the true pitch. We prove the facts that the method relies on: the range of the NCCF and its value at the period, the bound on the spectral term SS, and the optimality of the dynamic program.

Lemma 1 (the NCCF is bounded)

If emem+k>0e_m e_{m+k} > 0, then ∣ϕ(k)∣≤1|\phi(k)| \le 1.

Proof. With uj=xm+ju_j = x_{m+j} and vj=xm+k+jv_j = x_{m+k+j} for 0≤j<n0 \le j < n, the numerator is ∑jujvj\sum_j u_j v_j, and em=∑juj2e_m = \sum_j u_j^2, em+k=∑jvj2e_{m+k} = \sum_j v_j^2. By the Cauchy-Schwarz inequality, ∣∑jujvj∣≤∑juj2∑jvj2|\sum_j u_j v_j| \le \sqrt{\sum_j u_j^2} \sqrt{\sum_j v_j^2}. Divide by the right side. □\square

Lemma 2 (the NCCF is 1 at the period)

If xj+P=xjx_{j + P} = x_j for all jj in [m,m+n+K)[m, m + n + K) and em>0e_m > 0, then ϕ(qP)=1\phi(qP) = 1 for every integer q≥1q \ge 1 with qP≤KqP \le K.

Proof. By induction on qq, xj+qP=xjx_{j + qP} = x_j for m≤j<m+nm \le j < m + n. So v=uv = u in Lemma 1, the numerator is eme_m and em+qP=eme_{m+qP} = e_m, and ϕ(qP)=em/em2=1\phi(qP) = e_m / \sqrt{e_m^2} = 1. □\square

Equality in Cauchy-Schwarz holds only when vv is a positive multiple of uu. So in a periodic signal the value 1 marks the multiples of the period, and a peak of 1 at a lag that is not a multiple needs a signal that is periodic with that lag too. This is why each multiple of the period is a candidate and the lag cost LAG_WT is needed to prefer the shortest.

Lemma 3 (the Itakura ratio is at least 1)

Let RR be the (p+1)×(p+1)(p+1) \times (p+1) Toeplitz matrix of an autocorrelation sequence r0,…,rpr_0, \ldots, r_p with RR positive definite, let ar=(1,−a1,…,−ap)a_r = (1, -a_1, \ldots, -a_p) be the inverse filter from the Levinson-Durbin recursion on rr, and let bb be any vector with b0=1b_0 = 1. Then b⊤Rb≥ar⊤Rar>0b^\top R b \ge a_r^\top R a_r > 0, so I=b⊤Rb/ar⊤Rar≥1I = b^\top R b / a_r^\top R a_r \ge 1 and S=0.2/(I−0.8)∈(0,1]S = 0.2 / (I - 0.8) \in (0, 1].

Proof. Write b=(1,−c)b = (1, -c) with c∈Rpc \in \mathbb{R}^p. Then b⊤Rb=r0−2c⊤ρ+c⊤Tcb^\top R b = r_0 - 2 c^\top \rho + c^\top T c, with ρ=(r1,…,rp)\rho = (r_1, \ldots, r_p) and TT the leading p×pp \times p block of RR, which is positive definite. This quadratic in cc has its unique minimum where Tc=ρT c = \rho, the normal equations of linear prediction. The Levinson-Durbin recursion solves exactly these equations, so c=(a1,…,ap)c = (a_1, \ldots, a_p) attains the minimum. The minimum is positive because RR is positive definite and b≠0b \ne 0. Then I≥1I \ge 1 gives I−0.8≥0.2I - 0.8 \ge 0.2 and 0<S≤10 < S \le 1. □\square

The code computes rr from a windowed segment, which makes RR positive semidefinite, and positive definite unless the segment is degenerate; for a silent segment it returns I=1I = 1. In floating point the computed II can fall below 1 by rounding.

Lemma 4 (the local costs are bounded)

For a voiced candidate with 0<C≤10 < C \le 1 and 0<L≤K+10 < L \le K + 1, the local cost d=1−C(1−LAG_WT L/K)d = 1 - C(1 - \text{LAG\_WT}\, L / K) lies in [0,1+LAG_WT][0, 1 + \text{LAG\_WT}] when LAG_WT ≤1\le 1, and among candidates with equal CC it grows with LL.

Proof. The factor 1−LAG_WT L/K1 - \text{LAG\_WT}\, L / K lies in [1−LAG_WT(1+1/K),1)[1 - \text{LAG\_WT}(1 + 1/K), 1), so CC times it lies in an interval inside [−LAG_WT,1)[-\text{LAG\_WT}, 1), and dd in (0,1+LAG_WT](0, 1 + \text{LAG\_WT}]. For fixed C>0C > 0, dd is increasing in LL with slope C⋅LAG_WT/K>0C \cdot \text{LAG\_WT} / K > 0. □\square

So, for equal correlation, a shorter period always has the lower local cost, which is how RAPT breaks the tie of Lemma 2 between multiples of the period.

Theorem (the dynamic program is optimal)

Let frame ii have candidates 0,…,ci−10, \ldots, c_i - 1 with local costs di(j)d_i(j), and let δi(k,j)\delta_i(k, j) be the cost of moving from candidate kk of frame i−1i - 1 to candidate jj of frame ii. The cost of a path j1,…,jFj_1, \ldots, j_F is

cost(j1,…,jF)=d1(j1)+∑i=2F(di(ji)+δi(ji−1,ji)).\mathrm{cost}(j_1, \ldots, j_F) = d_1(j_1) + \sum_{i=2}^{F} \bigl( d_i(j_i) + \delta_i(j_{i-1}, j_i) \bigr).

The path returned by lines L5 to L9 has the least cost of all paths.

Proof. Let Vi(j)V_i(j) be the least cost of a path over frames 1,…,i1, \ldots, i that ends at candidate jj of frame ii. We show Di(j)=Vi(j)D_i(j) = V_i(j) by induction on ii. For i=1i = 1 a path is one candidate, so V1(j)=d1(j)=D1(j)V_1(j) = d_1(j) = D_1(j) by line L5. For i≥2i \ge 2, a path that ends at jj is a path over frames 1,…,i−11, \ldots, i - 1 that ends at some kk, followed by jj, and its cost is the cost of the prefix plus di(j)+δi(k,j)d_i(j) + \delta_i(k, j). For a fixed kk this is least when the prefix is a best path to kk, of cost Vi−1(k)=Di−1(k)V_{i-1}(k) = D_{i-1}(k) by the induction hypothesis. Minimizing over kk gives

Vi(j)=di(j)+min⁡k(Di−1(k)+δi(k,j)),V_i(j) = d_i(j) + \min_k \bigl( D_{i-1}(k) + \delta_i(k, j) \bigr),

which is line L7. So DF(j)=VF(j)D_F(j) = V_F(j), and line L8 picks jFj_F with the least VFV_F, which is the least cost of any path.

For the back pointers, ψi(j)\psi_i(j) attains the minimum above, so Vi(ji)=Vi−1(ji−1)+di(ji)+δi(ji−1,ji)V_i(j_i) = V_{i-1}(j_{i-1}) + d_i(j_i) + \delta_i(j_{i-1}, j_i) with ji−1=ψi(ji)j_{i-1} = \psi_i(j_i). Summing these equations for i=Fi = F down to 2 and adding V1(j1)=d1(j1)V_1(j_1) = d_1(j_1) shows that the path from line L9 has cost VF(jF)V_F(j_F). □\square

The proof needs no sign or bound on the costs, and no relation between the transition costs of different frames. So it holds for the costs of Talkin, which depend on the frame through rir_i and SiS_i, and for any other choice. Ties are broken toward the smallest candidate index, which does not change the cost.

The transition costs

Two facts about the voiced-to-voiced cost δ=FREQ_WTmin⁡(ξ,DOUBL_C+∣ξ−ln⁡2∣)\delta = \text{FREQ\_WT} \min(\xi, \text{DOUBL\_C} + |\xi - \ln 2|) with ξ=∣ln⁡(Lj/Lk)∣\xi = |\ln(L_j / L_k)| follow from the formula. It is symmetric in the two lags, since ξ\xi is. And for ξ\xi near ln⁡2\ln 2, a jump of one octave, the second term is the smaller one when ∣ξ−ln⁡2∣<ln⁡2−DOUBL_C|\xi - \ln 2| < \ln 2 - \text{DOUBL\_C} and ξ>DOUBL_C+∣ξ−ln⁡2∣\xi > \text{DOUBL\_C} + |\xi - \ln 2|, so an octave jump costs FREQ_WT⋅DOUBL_C=0.007\text{FREQ\_WT} \cdot \text{DOUBL\_C} = 0.007 with the defaults instead of FREQ_WTln⁡2≈0.0139\text{FREQ\_WT} \ln 2 \approx 0.0139.

Complexity

In the real RAM, line L1 costs O(Kn)O(K n) per frame, with running sums for the energies em+ke_{m+k}. Line L2 costs O(Klog⁡K)O(K \log K), line L4 O(np+p2)O(n p + p^2) for LPC order pp, and line L7 O(C2)O(C^2) for CC candidates per frame. The total is O(F(Kn+C2))O(F (K n + C^2)) time, with O(FC)O(F C) memory for the back pointers. At 8 kHz with defaults, Kn=160⋅60=9600K n = 160 \cdot 60 = 9600 products per frame. The two passes of the paper reduce this: the first pass works on a signal downsampled by a factor qq, which costs about 1/q21/q^2 as much, and the second pass computes only a few lags around each peak.

Properties

  • Candidates, not decisions. Each frame keeps up to 19 periods and an unvoiced choice, so a weak frame inside a vowel can still get the right period from its neighbors.
  • Voicing from costs. The voicing decision uses the correlation, the level change and the spectral change together, not a fixed threshold.
  • Short delay in practice. The best paths to the candidates of the current frame usually share their start, so the decision for an older frame is fixed after a short delay. Talkin reports that this delay is rarely over 100 ms, which is a measurement.
  • Octave jumps are allowed. The term DOUBL_C +∣ξ−ln⁡2∣+ |\xi - \ln 2| makes a jump of one octave cost 0.02⋅0.35=0.0070.02 \cdot 0.35 = 0.007 instead of 0.02ln⁡2=0.0140.02 \ln 2 = 0.014, so real octave jumps, such as into vocal fry, are not blocked.
  • Deterministic. The same input gives the same track.

Variants and improvements

  • Two passes. The paper's form, described above. It is the main speed difference from this code.
  • Other candidate sources. YIN dips or cepstral peaks can feed the same dynamic program.
  • Probabilistic costs. pYIN replaces the hand-set costs by probabilities and the dynamic program by the Viterbi algorithm on a hidden Markov model.
  • Later trackers by Talkin. REAPER, from Google, also uses an NCCF and dynamic programming, and adds glottal closure instants.

When to use it

Use RAPT for speech when a robust offline pitch track with voicing decisions is needed and no training data are available, for example for prosody analysis, speech synthesis corpora and voice research. It is a common reference tracker. For music with a wide pitch range, or when a voicing probability is needed, pYIN is a better fit. For noisy speech, learned trackers are now often better; their results depend on the data.

Pitfalls

  • The frame needs more signal than the window. The NCCF uses n+K+1n + K + 1 samples from the frame start; at 50 Hz and 16 kHz that is more than 320 lags.
  • Silent frames. If emem+k=0e_m e_{m+k} = 0, the NCCF is undefined. This code returns 0 there; a small constant in the denominator also works and lowers the values in very quiet frames.
  • Parameters for another sample rate. The defaults are in seconds and in hertz, so they carry over, but the lag weight uses KK, which depends on F0min⁡F_{0\min}. Changing the range changes the costs.
  • Sub-octave errors. Every multiple of the period also gives an NCCF peak close to 1. Only the lag weight, LAG_WT, prefers the shortest one. If LAG_WT is 0, the tracker can choose half the true frequency.
  • Hand-set costs. The costs are not probabilities, so the total cost has no meaning outside the comparison of paths.

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.

nlsdsp.pyI0RawGitHub
# 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
rapt_pitch_tracker.py 203 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/rapt-pitch-tracker/. The authors are listed in prov/D01A4J.jsonl.

"""RAPT, the robust algorithm for pitch tracking of Talkin (1995), in one pass.

Per frame: the normalized cross-correlation function (NCCF) over the lags of the
pitch range, its local maxima above CAND_TR times the largest value as voiced
candidates, and one unvoiced candidate. Over frames: a dynamic program with the
local costs and transition costs of Talkin, section 3.5, picks the path of least
total cost. The paper first finds peaks on a downsampled signal and then refines
them at the full rate; this code computes the NCCF at the full rate directly,
which gives the same kind of candidates at a higher cost.

Costs (Talkin's names):
  voiced local cost     1 - C (1 - LAG_WT L / L_max)
  unvoiced local cost   VO_BIAS + the largest candidate C of the frame
  voiced to voiced      FREQ_WT min(xi, DOUBL_C + |xi - ln 2|), xi = |ln(L_j / L_k)|
  unvoiced to voiced    VTRAN_C + VTR_S_C S + VTR_A_C / rr
  voiced to unvoiced    VTRAN_C + VTR_S_C S + VTR_A_C rr
  unvoiced to unvoiced  0
where rr is the RMS ratio of the frame to the previous frame and S = 0.2 / (I - 0.8)
with I the Itakura ratio of the LPC spectra of the two frames.
"""

import math
from typing import Callable, List, Optional, Sequence, Tuple

from nlsdsp import autocorr, hamming, levinson

PARAMS = {
    "f0_min": 50.0,
    "f0_max": 500.0,
    "frame_step": 0.01,
    "wind_dur": 0.0075,
    "cand_tr": 0.3,
    "lag_wt": 0.3,
    "freq_wt": 0.02,
    "vtran_c": 0.005,
    "vtr_a_c": 0.5,
    "vtr_s_c": 0.5,
    "vo_bias": 0.0,
    "doubl_c": 0.35,
    "n_cands": 20,
}

Candidate = Tuple[float, float]  # (lag in samples, correlation); lag 0 means unvoiced


def nccf(x: Sequence[float], m: int, n: int, k_lo: int, k_hi: int, eps: float = 0.0) -> List[float]:
    """phi(k) = sum_{j=m}^{m+n-1} x_j x_{j+k} / sqrt(e_m e_{m+k} + eps) for k = k_lo .. k_hi.

    Here e_j = sum_{l=j}^{j+n-1} x_l^2. The value is 0 when the denominator is 0.
    Needs m + k_hi + n <= len(x).
    """
    if m < 0 or k_lo < 0 or m + k_hi + n > len(x):
        raise ValueError("the signal is too short for this frame and lag range")
    e_m = sum(x[m + l] ** 2 for l in range(n))
    e_k = sum(x[m + k_lo + l] ** 2 for l in range(n))
    out = []
    for k in range(k_lo, k_hi + 1):
        if k > k_lo:  # slide the energy window by one sample
            e_k += x[m + k + n - 1] ** 2 - x[m + k - 1] ** 2
            e_k = max(e_k, 0.0)
        num = sum(x[m + j] * x[m + j + k] for j in range(n))
        den = math.sqrt(e_m * e_k + eps)
        out.append(num / den if den > 0 else 0.0)
    return out


def peaks(phi: Sequence[float], k_lo: int, k_min: int, k_max: int, cand_tr: float, n_max: int) -> List[Candidate]:
    """Voiced candidates: interpolated local maxima of phi in [k_min, k_max] with value >= cand_tr * the largest.

    phi[i] is the value at lag k_lo + i, and must cover k_min - 1 .. k_max + 1.
    At most n_max candidates are kept, the largest first; ties go to the shorter lag.
    """
    at = lambda k: phi[k - k_lo]
    top = max(at(k) for k in range(k_min, k_max + 1))
    if top <= 0:
        return []
    found = []
    for k in range(k_min, k_max + 1):
        if at(k) >= at(k - 1) and at(k) > at(k + 1) and at(k) >= cand_tr * top:
            a = at(k - 1) - 2 * at(k) + at(k + 1)
            off = (at(k - 1) - at(k + 1)) / (2 * a) if a < 0 else 0.0
            value = at(k) - 0.25 * (at(k - 1) - at(k + 1)) * off
            found.append((k + off, min(value, 1.0)))
    found.sort(key=lambda c: (-c[1], c[0]))
    return found[:n_max]


def itakura_ratio(seg_ref: Sequence[float], seg_other: Sequence[float], order: int) -> float:
    """I = a_o' R a_o / a_r' R a_r, with R the autocorrelation matrix of seg_ref and a_r, a_o the LPC inverse filters.

    The LPC of seg_ref minimizes the quadratic form, so I >= 1. A silent segment gives 1.
    """
    w = hamming(len(seg_ref))
    r = autocorr([v * u for v, u in zip(seg_ref, w)], order)
    r2 = autocorr([v * u for v, u in zip(seg_other, w)], order)
    if r[0] <= 1e-12 or r2[0] <= 1e-12:
        return 1.0
    a_ref = [1.0] + [-c for c in levinson(r, order)[0]]
    a_oth = [1.0] + [-c for c in levinson(r2, order)[0]]

    def form(a):
        return sum(a[j] * a[k] * r[abs(j - k)] for j in range(order + 1) for k in range(order + 1))

    base = form(a_ref)
    return form(a_oth) / base if base > 0 else 1.0


def rms(seg: Sequence[float]) -> float:
    return math.sqrt(sum(v * v for v in seg) / len(seg))


def transition_cost(
    prev: Candidate, cur: Candidate, rr: float, s: float, p: dict = PARAMS
) -> float:
    """The cost of moving from candidate prev of frame i - 1 to candidate cur of frame i."""
    pv, cv = prev[0] > 0, cur[0] > 0
    if pv and cv:
        xi = abs(math.log(cur[0] / prev[0]))
        return p["freq_wt"] * min(xi, p["doubl_c"] + abs(xi - math.log(2.0)))
    if not pv and not cv:
        return 0.0
    if cv:  # onset
        return p["vtran_c"] + p["vtr_s_c"] * s + p["vtr_a_c"] / rr
    return p["vtran_c"] + p["vtr_s_c"] * s + p["vtr_a_c"] * rr  # offset


def dp(local: Sequence[Sequence[float]], trans: Callable[[int, int, int], float]) -> Tuple[List[int], float]:
    """The path of least total cost: D_1 = d_1, D_i(j) = d_i(j) + min_k D_{i-1}(k) + trans(i, k, j).

    local[i][j] is the local cost of state j in frame i, trans(i, k, j) the cost of
    moving from state k of frame i - 1 to state j of frame i. Ties go to the
    smallest state. Returns the states, one per frame, and the total cost.
    """
    if not local:
        return [], 0.0
    cost = list(local[0])  # @line L5
    back: List[List[int]] = []
    for i in range(1, len(local)):  # @line L6
        new, ptr = [], []
        for j, d in enumerate(local[i]):
            best_k = min(range(len(cost)), key=lambda k: (cost[k] + trans(i, k, j), k))
            new.append(d + cost[best_k] + trans(i, best_k, j))  # @line L7
            ptr.append(best_k)
        cost = new
        back.append(ptr)
    last = min(range(len(cost)), key=lambda j: (cost[j], j))  # @line L8
    path = [last]
    for ptr in reversed(back):  # @line L9
        path.append(ptr[path[-1]])
    path.reverse()
    return path, cost[last]


def frame_states(
    x: Sequence[float], fs: float, p: dict = PARAMS, lpc_order: int = 8
) -> Tuple[List[List[Candidate]], List[List[float]], List[float], List[float]]:
    """Candidates (voiced ones, then (0, 0) for unvoiced), local costs, rr and S of every frame."""
    hop = round(p["frame_step"] * fs)
    n = round(p["wind_dur"] * fs)
    k_min = max(2, math.floor(fs / p["f0_max"]))
    k_max = math.ceil(fs / p["f0_min"])
    span = k_max + 1 + n
    beta = p["lag_wt"] / k_max
    cands, local, rrs, ss = [], [], [], []
    prev_seg = None
    m = 0
    while m + span <= len(x):
        phi = nccf(x, m, n, k_min - 1, k_max + 1)  # @line L1
        voiced = peaks(phi, k_min - 1, k_min, k_max, p["cand_tr"], p["n_cands"] - 1)  # @line L2
        c_max = max((c for _, c in voiced), default=0.0)
        costs = [1.0 - c * (1.0 - beta * lag) for lag, c in voiced]  # @line L3
        costs.append(p["vo_bias"] + c_max)
        seg = x[m : m + span]
        if prev_seg is None:
            rr, s = 1.0, 1.0
        else:
            rr = (rms(seg) + 1e-9) / (rms(prev_seg) + 1e-9)  # @line L4
            s = 0.2 / (itakura_ratio(seg, prev_seg, lpc_order) - 0.8)
        cands.append(voiced + [(0.0, 0.0)])
        local.append(costs)
        rrs.append(rr)
        ss.append(s)
        prev_seg = seg
        m += hop
    return cands, local, rrs, ss


def rapt(x: Sequence[float], fs: float, p: dict = PARAMS) -> List[Optional[float]]:
    """The RAPT track: fs / L for each voiced frame, None for each unvoiced frame. Frames start every frame_step seconds."""
    cands, local, rrs, ss = frame_states(x, fs, p)

    def trans(i, k, j):
        return transition_cost(cands[i - 1][k], cands[i][j], rrs[i], ss[i], p)

    path, _ = dp(local, trans)
    out = []
    for i, j in enumerate(path):
        lag = cands[i][j][0]
        out.append(fs / lag if lag > 0 else None)  # @line L10
    return out
test_rapt_pitch_tracker.py 126 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/rapt-pitch-tracker/. The authors are listed in prov/D01A4J.jsonl.

import itertools
import math
import random

from nlsdsp import all_pole, pulse_train, white_noise
from rapt_pitch_tracker import PARAMS, dp, itakura_ratio, nccf, peaks, rapt, transition_cost

FS = 8000
BETA = 0.3 / 160  # LAG_WT / L_max with F0min = 50 Hz at 8 kHz


def test_nccf_matches_the_definition_and_is_bounded():
    rng = random.Random(1)
    x = [rng.uniform(-1, 1) for _ in range(300)]
    m, n, lo, hi = 17, 40, 5, 120
    phi = nccf(x, m, n, lo, hi)
    for k in range(lo, hi + 1):
        num = sum(x[m + j] * x[m + j + k] for j in range(n))
        e0 = sum(x[m + j] ** 2 for j in range(n))
        ek = sum(x[m + k + j] ** 2 for j in range(n))
        assert abs(phi[k - lo] - num / math.sqrt(e0 * ek)) < 1e-12
        assert abs(phi[k - lo]) <= 1 + 1e-12


def test_nccf_is_one_at_the_period_of_a_periodic_signal():
    x = all_pole(pulse_train(200, FS, 400), [1.2, -0.5])  # period 40
    x = x[100:]  # past the start, the signal repeats every 40 samples to rounding
    phi = nccf(x, 0, 60, 15, 161)
    for k in (40, 80, 120, 160):
        assert abs(phi[k - 15] - 1) < 1e-9
    assert max(phi[k - 15] for k in range(15, 39)) < 0.99


def test_peaks_are_the_local_maxima_above_the_relative_threshold():
    rng = random.Random(2)
    for _ in range(200):
        phi = [rng.uniform(-0.5, 1.0) for _ in range(30)]  # lags 10 .. 39
        got = peaks(phi, 10, 11, 38, 0.3, 50)
        top = max(phi[1:29])
        want = [
            k for k in range(11, 39) if phi[k - 10] >= phi[k - 11] and phi[k - 10] > phi[k - 9] and phi[k - 10] >= 0.3 * top
        ]
        if top <= 0:
            want = []
        assert sorted(round(c[0]) for c in got) == sorted(want)
        for lag, value in got:
            assert abs(lag - round(lag)) <= 0.5  # the vertex stays within half a lag
            assert value >= phi[round(lag) - 10] - 1e-12


def brute_force(local, trans):
    best = math.inf
    for path in itertools.product(*[range(len(c)) for c in local]):
        cost = local[0][path[0]] + sum(local[i][path[i]] + trans(i, path[i - 1], path[i]) for i in range(1, len(local)))
        best = min(best, cost)
    return best


def test_dp_matches_brute_force():
    rng = random.Random(3)
    for _ in range(30):
        frames = rng.randint(1, 5)
        local = [[rng.random() for _ in range(rng.randint(1, 4))] for _ in range(frames)]
        table = {}

        def trans(i, k, j):
            if (i, k, j) not in table:
                table[(i, k, j)] = rng.random()
            return table[(i, k, j)]

        path, total = dp(local, trans)
        assert abs(total - brute_force(local, trans)) < 1e-12
        again = local[0][path[0]] + sum(local[i][path[i]] + trans(i, path[i - 1], path[i]) for i in range(1, frames))
        assert abs(again - total) < 1e-12


def test_transition_costs():
    p = PARAMS
    assert transition_cost((40.0, 0.9), (40.0, 0.8), 1.0, 1.0) == 0.0
    assert abs(transition_cost((40.0, 0.9), (80.0, 0.8), 1.0, 1.0) - p["freq_wt"] * p["doubl_c"]) < 1e-15
    up = transition_cost((40.0, 0.9), (53.0, 0.8), 1.0, 1.0)
    assert abs(up - transition_cost((53.0, 0.9), (40.0, 0.8), 1.0, 1.0)) < 1e-15
    assert abs(up - p["freq_wt"] * math.log(53 / 40)) < 1e-15
    assert transition_cost((0.0, 0.0), (0.0, 0.0), 0.3, 0.4) == 0.0
    onset = transition_cost((0.0, 0.0), (40.0, 0.9), 4.0, 0.2)
    offset = transition_cost((40.0, 0.9), (0.0, 0.0), 0.25, 0.2)
    assert abs(onset - (0.005 + 0.5 * 0.2 + 0.5 / 4.0)) < 1e-15
    assert abs(offset - (0.005 + 0.5 * 0.2 + 0.5 * 0.25)) < 1e-15


def test_itakura_ratio_is_at_least_one():
    rng = random.Random(4)
    for _ in range(20):
        a = [rng.gauss(0, 1) for _ in range(120)]
        b = all_pole([rng.gauss(0, 1) for _ in range(120)], [rng.uniform(-0.6, 0.6)])
        assert itakura_ratio(a, b, 6) >= 1 - 1e-9
        assert abs(itakura_ratio(a, a, 6) - 1) < 1e-9


def test_example_of_the_page():
    frames = [[(40.0, 0.95), (80.0, 0.90)], [(40.0, 0.45), (120.0, 0.40)], [(40.0, 0.94), (80.0, 0.88)], [(97.0, 0.30)]]
    rr, s = [1.0, 1.0, 1.0, 0.1], [1.0, 1.0, 1.0, 0.2]
    cands = [f + [(0.0, 0.0)] for f in frames]
    local = [[1 - c * (1 - BETA * lag) for lag, c in f] + [max(c for _, c in f)] for f in frames]
    assert [round(v, 5) for v in local[1]] == [0.58375, 0.69, 0.45]  # alone, frame 2 looks unvoiced

    def trans(i, k, j):
        return transition_cost(cands[i - 1][k], cands[i][j], rr[i], s[i])

    path, total = dp(local, trans)
    assert path == [0, 0, 0, 1]
    assert abs(total - 1.2905) < 1e-12


def test_track_of_a_voiced_segment_then_noise():
    rng = random.Random(5)
    v = all_pole(pulse_train(160, FS, 1200), [1.662983, -0.81])
    peak = max(abs(t) for t in v)
    x = [t / peak for t in v] + white_noise(rng, 800, 0.02)
    track = rapt(x, FS)
    assert len(track) == 23
    assert all(f is not None and abs(f - 160) < 0.5 for f in track[:14])
    assert all(f is None for f in track[14:])

History

Talkin's program get_f0, which implements RAPT, shipped with the ESPS speech tools of Entropic Research Laboratory. The 1995 book chapter is the reference description. The method combined ideas older than it: the normalized cross-correlation for periodicity, a coarse search on a downsampled signal, and dynamic programming over frame candidates, which earlier trackers had used for smoothing. RAPT became a standard baseline in speech research.

References

  1. David Talkin, A robust algorithm for pitch tracking (RAPT), chapter 14 of W. B. Kleijn and K. K. Paliwal (editors), Speech Coding and Synthesis, Elsevier, 1995, 495 to 518, Section 2.2.6 (the normalized cross-correlation, equations 2.6 and 2.7), Section 3.3 (the two passes), Section 3.5 (the dynamic program, equations 3.6 to 3.20) and the table of parameters on page 509
  2. Lawrence R. Rabiner and Ronald W. Schafer, Digital Processing of Speech Signals, Prentice-Hall, 1978, the sections on autocorrelation methods of pitch detection

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
  • at least three sources
  • a scene preset for the example