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.
- Solves
- Pitch detection
- 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
- Model
- Real RAM
- Properties
- deterministicnot exactnot in placeoffline
- Evidence
- Proof sketchCode in 1 languages
- 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 and a pitch range to (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 to .
The algorithm
For a frame that starts at sample , with a window of samples (7.5 ms by default), the NCCF at lag is
Unlike the plain autocorrelation, each lag is normalized by the energy of both windows, so and the value does not fall off at long lags. The voiced candidates of the frame are the local maxima of with CAND_TR times the largest value, at most N_CANDS minus 1 of them, refined by a parabola through three points. Each candidate has a lag and a value . One more candidate means unvoiced.
The local costs of frame are (Talkin's equations 3.6 and 3.7)
The transition costs from candidate of frame to candidate of frame are, with (equations 3.8 to 3.15),
| from | to | cost |
|---|---|---|
| voiced | voiced | FREQ_WT |
| unvoiced | voiced | VTRAN_C + VTR_S_C + VTR_A_C |
| voiced | unvoiced | VTRAN_C + VTR_S_C + VTR_A_C |
| unvoiced | unvoiced | 0 |
Here is the ratio of the RMS of frame to the RMS of frame , so an onset is cheap where the level rises and an offset is cheap where it falls. , where 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.
RAPT(x, fs)- 1
for each frame i: phi_i(k) <- the NCCF at lag k for k_min - 1 <= k <= K + 1 - 2
cands_i <- the interpolated local maxima of phi_i with value >= CAND_TR * max, at most N_CANDS - 1, plus unvoiced - 3
d_i(j) <- 1 - C_j (1 - LAG_WT L_j / K) for voiced j; d_i(unvoiced) <- VO_BIAS + max_j C_j - 4
r_i <- RMS ratio to frame i - 1; S_i <- 0.2 / (Itakura ratio - 0.8) - 5
D_1(j) <- d_1(j) for every candidate j of frame 1 - 6
for i <- 2 to F do - 7
D_i(j) <- d_i(j) + min over k of (D_{i-1}(k) + delta_i(k, j)); psi_i(j) <- the argmin - 8
j_F <- the argmin of D_F - 9
for i <- F down to 2 do j_{i-1} <- psi_i(j_i) - 10
return 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 finds the rough peaks, and a second pass computes the NCCF at the full rate only near those peaks.
Example
The dynamic program. Take Hz, so and LAG_WT. Four frames have these voiced candidates (lag, value) and frame values and :
| frame | candidates | ||
|---|---|---|---|
| 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 . But each switch between frames 1 to 3 costs , so the path 40, unvoiced, 40 pays 2.01 for two switches. The best path is 40, 40, 40, unvoiced, with cost
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 Hz. A search over all 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 ( and 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 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 . And the dynamic program returns a path of least total cost, by induction on the frames: the best path to candidate of frame extends a best path to some candidate of frame , 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 , and the optimality of the dynamic program.
Lemma 1 (the NCCF is bounded)
If , then .
Proof. With and for , the numerator is , and , . By the Cauchy-Schwarz inequality, . Divide by the right side.
Lemma 2 (the NCCF is 1 at the period)
If for all in and , then for every integer with .
Proof. By induction on , for . So in Lemma 1, the numerator is and , and .
Equality in Cauchy-Schwarz holds only when is a positive multiple of . 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 be the Toeplitz matrix of an autocorrelation sequence with positive definite, let be the inverse filter from the Levinson-Durbin recursion on , and let be any vector with . Then , so and .
Proof. Write with . Then , with and the leading block of , which is positive definite. This quadratic in has its unique minimum where , the normal equations of linear prediction. The Levinson-Durbin recursion solves exactly these equations, so attains the minimum. The minimum is positive because is positive definite and . Then gives and .
The code computes from a windowed segment, which makes positive semidefinite, and positive definite unless the segment is degenerate; for a silent segment it returns . In floating point the computed can fall below 1 by rounding.
Lemma 4 (the local costs are bounded)
For a voiced candidate with and , the local cost lies in when LAG_WT , and among candidates with equal it grows with .
Proof. The factor lies in , so times it lies in an interval inside , and in . For fixed , is increasing in with slope .
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 have candidates with local costs , and let be the cost of moving from candidate of frame to candidate of frame . The cost of a path is
The path returned by lines L5 to L9 has the least cost of all paths.
Proof. Let be the least cost of a path over frames that ends at candidate of frame . We show by induction on . For a path is one candidate, so by line L5. For , a path that ends at is a path over frames that ends at some , followed by , and its cost is the cost of the prefix plus . For a fixed this is least when the prefix is a best path to , of cost by the induction hypothesis. Minimizing over gives
which is line L7. So , and line L8 picks with the least , which is the least cost of any path.
For the back pointers, attains the minimum above, so with . Summing these equations for down to 2 and adding shows that the path from line L9 has cost .
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 and , 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 with follow from the formula. It is symmetric in the two lags, since is. And for near , a jump of one octave, the second term is the smaller one when and , so an octave jump costs with the defaults instead of .
Complexity
In the real RAM, line L1 costs per frame, with running sums for the energies . Line L2 costs , line L4 for LPC order , and line L7 for candidates per frame. The total is time, with memory for the back pointers. At 8 kHz with defaults, products per frame. The two passes of the paper reduce this: the first pass works on a signal downsampled by a factor , which costs about 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 makes a jump of one octave cost instead of , 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 samples from the frame start; at 50 Hz and 16 kHz that is more than 320 lags.
- Silent frames. If , 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 , which depends on . 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.
# 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag D01A4J Edit this page History Report an error Markdown