Algorithmresearch
pYIN
Also called probabilistic YIN.
YIN with a distribution over thresholds that gives many pitch candidates with probabilities, then Viterbi decoding of a pitch HMM.
- Solves
- Pitch detection
- Time
- O(F (W T + N T + M J)) worst
- Space
- O(T + F M) extra
- Where
- F = the number of frames; J = the largest pitch jump in bins; M = the number of pitch bins; N = the number of thresholds; T = the largest lag; W = the frame length
- Model
- Real RAM
- Properties
- deterministicnot exactnot in placeoffline
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Matthias Mauch, Simon Dixon, 2014
pYIN, or probabilistic YIN, is a pitch tracker by Matthias Mauch and Simon Dixon (2014) that keeps several period candidates per frame and then chooses one track over all frames. Its first stage is the YIN algorithm run with 100 thresholds at once, weighted by a prior, so that each candidate period gets a probability and the mass left over means unvoiced. Its second stage is a hidden Markov model with a voiced and an unvoiced state for each pitch bin, decoded by the Viterbi algorithm. Plain YIN commits to one period per frame with one threshold; the cepstral detector decides each frame alone from the cepstrum; RAPT also keeps candidates and uses a dynamic program, but with the normalized cross-correlation and hand-set costs instead of probabilities.
In plain words
YIN looks for the first shift at which a sound matches a copy of itself well enough, and "well enough" is a fixed limit. The right limit changes from sound to sound. pYIN tries a hundred limits at once. Each limit points to some shift, and more likely limits count more, so each frame gets a short list of possible pitches with weights. What is left of the weight says that the frame may be noise. Then pYIN looks at all frames together and picks the path through the lists that is most likely, where the pitch moves smoothly and the voice does not switch on and off at every frame.
The problem
Given a signal at a sample rate , cut into frames, and a pitch range to (55 to 880 Hz in the paper), return for each frame either a fundamental frequency in Hz or the label unvoiced. A frame of samples needs samples of signal, where is the largest lag. The problem and its error measures are on the pitch detection page. Unlike YIN, pYIN works on the whole sequence of frames, so it is an offline method.
The algorithm
Stage 1 works on one frame. With the YIN difference function and its cumulative mean normalized form , let be the YIN period for the threshold : the bottom of the first dip of below , or, if no value is below , the lag of the global minimum of . For thresholds with prior probabilities , the probability of a period is (equation 4 of the paper)
with . The prior is a Beta distribution with mean 0.1, 0.15 or 0.2, discretized as with the Beta distribution function ; for mean 0.1 this page uses and .
Stage 2 works on all frames. The pitch range is cut into bins of 10 cents ( from 55 Hz up to just under 880 Hz). Each bin has a voiced state and an unvoiced state . If is the candidate mass of frame whose frequency is nearest to bin , the observation weights are (equation 6)
The transition from to is the product of a pitch move and a voicing move: the pitch move is a triangle, for with bins, and the voicing stays with probability 0.99 and switches with probability 0.01 (equations 7 and 8).
PYIN(frames x_1 .. x_F, fs, P(s_1 .. s_N), p_a, M, J)- 1
for each frame t: d <- the YIN difference function of x_t for 0 <= tau <= T - 2
d' <- the cumulative mean normalized difference of d; mass <- empty - 3
for i <- 1 to N do - 4
(tau, below) <- Y(s_i): the bottom of the first dip of d' under s_i, or the argmin of d' with below = false - 5
mass[tau] <- mass[tau] + (1 if below else p_a) * P(s_i) - 6
each tau with mass[tau] > 0 gives a candidate fs / tau', with tau' from a parabola through d' around tau - 7
p*_m <- the candidate mass nearest to bin m; b_t(m, 1) <- 0.5 p*_m; b_t(m, 0) <- 0.5 (1 - sum_k p*_k) - 8
delta_1(q) <- log pi(q) + log b_1(q) for every state q = (m, v) - 9
for t <- 2 to F do - 10
delta_t(q) <- max over q' of delta_{t-1}(q') + log A(q', q); psi_t(q) <- the argmax - 11
delta_t(q) <- delta_t(q) + log b_t(q) - 12
q_F <- the argmax of delta_F - 13
for t <- F down to 2 do q_{t-1} <- psi_t(q_t) - 14
return, for each frame t, the frequency of the bin of q_t if q_t is voiced, else unvoiced
Lines L1 to L7 are stage 1, once per frame, and lines L8 to L13 are the Viterbi algorithm in log space. The maximum in line L10 runs only over the states that can reach . The code returns the center frequency of the chosen bin; the paper's Vamp plugin can also report the candidate frequency nearest to it.
The paper prints the Beta parameters as "α = 1 and β = 18, 11 1/3, 8". With the means would be 0.053, 0.081 and 0.111, not the stated 0.1, 0.15 and 0.2, and the density would be largest at 0, not near 0.07 as in its Figure 2. The stated means need , the value that later ports use, and this page uses it.
The paper starts the chain uniformly over the unvoiced states. If the first frame has candidate mass 1, then every unvoiced weight is 0, and every path has probability 0. The code therefore starts uniformly over all states by default and keeps the paper's start as an option.
Example
Stage 1. Take Hz and plus Gaussian noise with standard deviation 0.12 (seed 3), and the range 55 to 880 Hz, so . The period is samples. The noise makes the three dips of nearly equal:
| 35 | 36 | 37 | 72 | 73 | 74 | 108 | 109 | 110 | |
|---|---|---|---|---|---|---|---|---|---|
| 0.1003 | 0.0610 | 0.0740 | 0.0782 | 0.0570 | 0.0862 | 0.0891 | 0.0548 | 0.0691 |
For no value is below , so , the global minimum, with weight . For the first value below is , since is not. For the first dip is at 36. With the Beta(2, 18) prior, , and , so the candidates are
| period | frequency | probability |
|---|---|---|
| 36, interpolated | 220.68 Hz | 0.6829 |
| 73, interpolated | 109.71 Hz | 0.0718 |
| 109, interpolated | 73.26 Hz |
The voiced mass is 0.7572, so the unvoiced weight is . Plain YIN with would return 73.26 Hz here, and with it would return 220.68 Hz; pYIN keeps both and lets the next frames decide.
Stage 2. A tiny chain with bins, , a voicing stay probability of 0.9 and a uniform start of over the four states. The pitch move is to the same bin and to the other one. The weights of three frames are
| state | frame 1 | frame 2 | frame 3 |
|---|---|---|---|
| (0, voiced) | 0.45 | 0.20 | 0 |
| (1, voiced) | 0 | 0.15 | 0.40 |
| (0, unvoiced) and (1, unvoiced) | 0.05 | 0.15 | 0.10 |
The best path is (0, voiced), (0, voiced), (1, voiced), with probability . The path (0, voiced), (1, voiced), (1, voiced) gives , and every path that ends on (0, voiced) gives 0. A search over all paths gives the same best value.
A track. The same tone with noise 0.05, 1000 samples followed by 600 samples of silence, frames of every 200 samples and bins, gives 220.0 Hz (bin 240) for the four frames inside the tone and unvoiced for the last three.
Correctness
pYIN is an estimator, so no theorem says that its track is the true pitch. Two things can be proved: stage 1 computes equation 4, and stage 2 returns a state sequence of largest weight under the model. The proofs are in proofs/correctness.md.
For stage 1, line L4 returns the smallest lag in the range with and either or , which is the YIN rule, or the global minimum when there is none. Line L5 adds times to exactly one lag for each , so after the loop the mass of each lag is the sum in equation 4. The total mass is , with equality only when every threshold finds a dip. For every threshold on the grid, the YIN estimate is among the candidates, because it gets the positive mass ; this is property 3 of the paper.
For stage 2, the weight of a state sequence is . By induction on , is the log of the largest weight of a sequence of length that ends in : the best such sequence ends with a best sequence of length that ends in some , because the weight factors over . So ends a best sequence, and the back pointers rebuild one. This holds for any nonnegative weights, so it does not matter that is not a normalized distribution or that the rows of near the ends of the bin range sum to less than 1. Log space changes nothing, since the log is increasing, and it avoids underflow.
Proof: Correctness of pYINfull
pYIN is an estimator, so we do not prove that its track is the true pitch. We prove two things. Stage 1 (lines L1 to L7) computes the candidate probabilities of equation 4 of Mauch and Dixon, and these sum to at most 1. Stage 2 (lines L8 to L14) returns a state sequence of largest weight under the HMM.
Setup
Let for be the cumulative mean normalized difference of a frame, and let be the lag range. For a threshold , let . The YIN period is defined as follows. If is not empty, let be its smallest element, and let be the first with or ; set . If is empty, let be the smallest lag of the minimum of on the range, and set .
The prior is nonnegative and sums to 1. The candidate probability of a lag is
(When is not empty, , so agrees with the factor of the paper evaluated at .)
Lemma 1 (line L4 computes Y)
The function yin_period returns when is not empty and otherwise.
Proof. The first loop scans upward from and stops at the first with , which is . The inner loop then moves right while and , so it stops at the first with or . That is . Along the way only decreases, so , and the flag true is correct. If no has , the second loop keeps the first lag of strictly smaller value, which is the smallest lag of the minimum.
The test of the code compares this with a different description: the smallest with and ( or ). The two agree. The lag above has both properties. Any smaller lag with is at least and lies on the strictly decreasing run from to , so and .
Lemma 2 (lines L3 to L5 compute P)
After the loop, mass[] for every , where a missing key means 0.
Proof. By induction on , after iteration the value mass[] is . Before the loop every value is 0. Iteration adds to the key only, by Lemma 1. At this is .
Lemma 3 (the mass is a subprobability)
, with equality if and only if is not empty for every with . Hence the unvoiced weight of line L7 is nonnegative.
Proof. Exchange the sums: , since each has exactly one . Each and the sum to 1, so the total is at most 1. It equals 1 exactly when wherever , since . Line L7 puts each candidate mass in at most one bin, so . The code also clips at 0, which only guards against rounding.
Corollary (YIN is covered)
For every grid threshold with , the YIN period is a candidate with positive probability, since . So if YIN with some grid threshold is right on a frame, the right period is among the pYIN candidates of that frame.
Lemma 4 (the Viterbi recursion)
Let the states be , with start weights , transition weights and observation weights . The weight of a sequence is
Let be the largest weight of a sequence of length that ends in . Then for all and , with .
Proof. By induction on . For a sequence is one state, so , which is line L8 in logs. For , a sequence of length ending in is a sequence of length ending in some , followed by , and its weight is the weight of the prefix times . These factors are nonnegative, so for a fixed the largest weight comes from the best prefix, of weight . Hence
The logarithm is increasing on with , so the log of this is , which is lines L10 and L11. The maximum may skip with , which add ; the code loops only over the in the band , where , and over states with . If no term is finite, the code sets , which is right, since then .
Theorem (the decoded track is a best sequence)
If some sequence has positive weight, the path returned by lines L12 and L13 has weight , the largest weight of any sequence. If every sequence has weight 0, the code raises an error.
Proof. Line L12 picks with , which by Lemma 4 is the log of the best weight. If it is , every sequence has weight 0 and the code raises. Otherwise, for , the pointer is a that attains the maximum in the recursion for , so with , and because . Unrolling this down to gives . Line L14 maps each state to its bin frequency if it is voiced and to unvoiced otherwise, which is the output.
Remarks
The proof uses only that all weights are nonnegative. It does not need the to be probability distributions, which they are not here, or the rows of to sum to 1, which they do not near the ends of the bin range, where the part of the triangular window outside the range is dropped.
With the paper's start, on the unvoiced states and 0 on the voiced ones. If the first frame has , then on every unvoiced state, so and every sequence has weight 0. The theorem then gives the error, and the default start, uniform over all states, avoids it.
In floating point, the sums of logs in lines L8 to L11 can lose a few units in the last place per frame, which can change the argmax only between sequences whose weights agree to that precision. The product form underflows to 0 after a few hundred frames of small weights, which would make every sequence look equal; the log form does not.
Complexity
In the real RAM, line L1 costs per frame directly, or with the FFT as on the YIN page. Lines L3 to L5 cost , since each threshold scans at most lags. Line L10 looks at predecessors for each of the states, so a frame costs . The total time is . The memory is for one frame of stage 1, for , and for the back pointers, which dominate. With the paper's numbers, and , the Viterbi step costs about 98000 additions per frame.
Properties
- More candidates than YIN. For every threshold on the grid, the YIN estimate is a candidate, so pYIN covers at least the correct estimates of YIN with any of those thresholds.
- A voicing probability. The mass not given to any period, , is a probability of unvoiced; YIN has no such number.
- Offline. The Viterbi step needs all frames before it returns the first one. A version with a fixed delay can decode a sliding window, at the cost of exactness.
- Quantized output. The track moves in 10 cent steps. The candidate frequency itself has the precision of the parabolic interpolation.
- Measured accuracy. On more than 30 hours of synthesized singing made from the pitch tracks of the RWC music database, at 44.1 kHz with frames of 2048 samples and a hop of 256, the median recall was 0.977, 0.982 and 0.984 for the three priors, against medians below 0.951 for YIN with the three single thresholds. These are measurements on that data set.
Variants and improvements
- Other priors. The paper tests Beta priors with means 0.1, 0.15 and 0.2, and a prior with a single threshold, which is YIN followed by HMM smoothing.
- Note tracking. Mauch and others built a note transcription method on top of the pYIN pitch track, in the Tony tool for melody annotation.
- Posterior decoding. The forward-backward algorithm gives the probability of voicing in each frame, which some ports report next to the Viterbi track.
- Faster stage 2. The transition matrix is banded, so the maximum of line L10 can use a sliding window maximum; with the triangle weights a direct band sum is already .
- Other trackers. The RAPT dynamic program uses costs set by hand instead of probabilities, and a median filter on a YIN track is the cheapest smoothing.
When to use it
Use pYIN for offline pitch tracks of a single voice or instrument, such as intonation studies, singing analysis and melody annotation, when octave jumps and voicing errors matter more than speed. It needs no training data. For real-time use with a small delay, use YIN with a short smoothing filter. For polyphonic music it is the wrong tool, because the HMM allows one pitch per frame.
Pitfalls
- The printed Beta parameters. With the priors do not have the stated means. Use with , and 8.
- Starting on unvoiced states. As above, a first frame with voiced mass 1 makes every path impossible. Start on all states, or put a small floor under the unvoiced weight.
- Normalizing each transition row. If each row of the pitch move is scaled to sum to 1, the rows near the ends of the range get larger weights, and an unvoiced path can sit at the end bin and win. The paper normalizes the triangle once, so those rows sum to less than 1.
- Short voiced segments. A switch of voicing costs a factor of 0.01 each way. In the test of the code, four noisy frames with voiced weight about twice the unvoiced weight did not pay for the two switches, and the whole track came out unvoiced.
- Products of probabilities. A track of a few hundred frames multiplies hundreds of small weights, which underflows to 0 in double precision. Work with logs, as in lines L8 to L11.
- A frame that is too short. The frame must cover samples, with ; at 55 Hz and 44.1 kHz that is more than 800 samples of lag alone.
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/.
"""Log-space arithmetic and semirings for the natural-language-and-speech pages.
Every log is the natural log. A probability of 0 is NEG_INF (float("-inf")),
never a large negative number. A cost is -log p, so a probability of 0 is a
cost of POS_INF.
The semirings are (K, plus, times, zero, one) as on the weighted-automaton page:
PROB probabilities plus = + times = * zero = 0 one = 1
LOG log probabilities plus = log_add times = + zero = -inf one = 0
VITERBI log probabilities plus = max times = + zero = -inf one = 0
TROPICAL costs -log p plus = min times = + zero = +inf one = 0
LOG_COST costs -log p plus = -log_add(-a, -b), times = +, zero = +inf, one = 0
BOOLEAN truth values plus = or times = and zero = False one = True
COUNTING path counts plus = + times = * zero = 0 one = 1
This module holds no algorithm of any page: no forward, Viterbi, CKY, Eisner,
CTC or DTW recursion. The pages build their dynamic programs on top of it.
"""
import math
from dataclasses import dataclass
from typing import Any, Callable, Iterable, List, Sequence
NEG_INF = float("-inf")
POS_INF = float("inf")
def safe_log(p) -> float:
"""Return log p, and NEG_INF for p = 0. Raise ValueError for p < 0."""
if p < 0:
raise ValueError("log of a negative number")
if p == 0:
return NEG_INF
return math.log(p)
def log_add(a: float, b: float) -> float:
"""Return log(exp(a) + exp(b)) = max(a, b) + log(1 + exp(-|a - b|)).
log_add(NEG_INF, NEG_INF) is NEG_INF. No exp of a large number is taken.
"""
if a < b:
a, b = b, a
if b == NEG_INF or a == POS_INF:
return a
return a + math.log1p(math.exp(b - a))
def log_sum(xs: Iterable[float]) -> float:
"""Return log(sum of exp(x)) over xs. An empty input gives NEG_INF."""
xs = list(xs)
if not xs:
return NEG_INF
m = max(xs)
if m == NEG_INF or m == POS_INF:
return m
return m + math.log(math.fsum(math.exp(x - m) for x in xs))
def log_normalize(xs: Sequence[float]) -> List[float]:
"""Return the list x - log_sum(xs): log values whose exps sum to 1.
Raise ValueError if every value is NEG_INF (nothing to normalize).
"""
z = log_sum(xs)
if z == NEG_INF:
raise ValueError("every weight is zero")
return [x - z for x in xs]
def log_softmax(xs: Sequence[float]) -> List[float]:
"""Return log softmax(xs): the logits xs turned into log probabilities."""
return log_normalize(xs)
def softmax(xs: Sequence[float], temperature: float = 1.0) -> List[float]:
"""Return the probabilities exp(x / temperature) / sum, computed stably.
The temperature must be positive. Logits of NEG_INF get probability 0.
"""
if not temperature > 0:
raise ValueError("the temperature must be positive")
m = max(xs)
if m == NEG_INF:
raise ValueError("every logit is -inf")
es = [math.exp((x - m) / temperature) for x in xs]
s = math.fsum(es)
return [e / s for e in es]
def argmax(xs: Sequence[Any]) -> int:
"""Return the first index of a largest value. Raise ValueError if xs is empty."""
if len(xs) == 0:
raise ValueError("argmax of an empty sequence")
best = 0
for i in range(1, len(xs)):
if xs[i] > xs[best]:
best = i
return best
@dataclass(frozen=True)
class Semiring:
"""A semiring (K, plus, times, zero, one). idempotent is True when a plus a = a."""
name: str
plus: Callable[[Any, Any], Any]
times: Callable[[Any, Any], Any]
zero: Any
one: Any
idempotent: bool
def _add(a, b):
return a + b
def _mul(a, b):
return a * b
def _log_add_cost(a: float, b: float) -> float:
return -log_add(-a, -b)
PROB = Semiring("probability", _add, _mul, 0, 1, False)
LOG = Semiring("log", log_add, _add, NEG_INF, 0.0, False)
VITERBI = Semiring("viterbi", max, _add, NEG_INF, 0.0, True)
TROPICAL = Semiring("tropical", min, _add, POS_INF, 0.0, True)
LOG_COST = Semiring("log-cost", _log_add_cost, _add, POS_INF, 0.0, False)
BOOLEAN = Semiring("boolean", lambda a, b: a or b, lambda a, b: a and b, False, True, True)
COUNTING = Semiring("counting", _add, _mul, 0, 1, False)
def sr_sum(sr: Semiring, xs: Iterable[Any]) -> Any:
"""Return the semiring sum of xs, and sr.zero for an empty input."""
acc = sr.zero
for x in xs:
acc = sr.plus(acc, x)
return acc
def sr_prod(sr: Semiring, xs: Iterable[Any]) -> Any:
"""Return the semiring product of xs, and sr.one for an empty input."""
acc = sr.one
for x in xs:
acc = sr.times(acc, x)
return acc
pyin.py 240 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pyin/. The authors are listed in prov/FCGMHH.jsonl.
"""pYIN, the probabilistic YIN pitch tracker of Mauch and Dixon (2014).
Stage 1, per frame: the YIN difference function d and its cumulative mean
normalized form d', then a prior P(s_i) over N = 100 thresholds s_i = i / 100.
Each threshold picks the YIN period Y(s_i): the bottom of the first dip of d'
below s_i, or, if no value is below s_i, the global minimum of d'. The period
tau gets the probability sum_i a(s_i, tau) P(s_i) [Y(s_i) = tau], with a = 1 when
d'(tau) < s_i and a = p_a = 0.01 otherwise. The mass left over means unvoiced.
Stage 2, over frames: an HMM with M pitch bins of 10 cents from 55 Hz, each with
a voiced and an unvoiced state. The observation of voiced bin m is 0.5 p*_m (the
candidate mass in the bin) and of every unvoiced state 0.5 (1 - sum_k p*_k). The
pitch moves by at most J bins per frame with triangular weights, the voicing
stays with probability 0.99. Viterbi decoding in log space gives the track.
The paper prints the Beta parameters as alpha = 1 and beta = 18, 11 1/3, 8, but
its stated means 0.10, 0.15 and 0.20 need alpha = 2, which this code uses.
"""
import math
from fractions import Fraction
from math import comb
from typing import Dict, List, Optional, Sequence, Tuple
from nlslog import NEG_INF, safe_log
# ---------------------------------------------------------------- stage 1
def difference(x: Sequence[float], w: int, tau_max: int) -> List[float]:
"""d(tau) = sum_{j=0}^{w-1} (x[j] - x[j + tau])^2 for tau = 0 .. tau_max. Needs w + tau_max samples."""
if len(x) < w + tau_max:
raise ValueError("the frame needs w + tau_max samples")
return [sum((x[j] - x[j + tau]) ** 2 for j in range(w)) for tau in range(tau_max + 1)]
def cmndf(d: Sequence[float]) -> List[float]:
"""d'(0) = 1 and d'(tau) = tau d(tau) / sum_{j=1}^{tau} d(j), or 1 when the sum is 0."""
out = [1.0]
s = 0.0
for tau in range(1, len(d)):
s += d[tau]
out.append(tau * d[tau] / s if s > 0 else 1.0)
return out
def beta_cdf(x, a: int, b: int):
"""The regularized incomplete beta function I_x(a, b) for integer a, b >= 1, by the binomial sum.
It is exact on Fractions: I_x(a, b) = sum_{j=a}^{a+b-1} C(a+b-1, j) x^j (1 - x)^(a+b-1-j).
"""
n = a + b - 1
return sum(comb(n, j) * x ** j * (1 - x) ** (n - j) for j in range(a, n + 1))
def threshold_prior(n: int = 100, a: int = 2, b: int = 18) -> List[Fraction]:
"""P(s_i) = I_{s_i}(a, b) - I_{s_{i-1}}(a, b) for s_i = i / n, i = 1 .. n. Sums to exactly 1."""
cdf = [beta_cdf(Fraction(i, n), a, b) for i in range(n + 1)]
return [cdf[i] - cdf[i - 1] for i in range(1, n + 1)]
def yin_period(dp: Sequence[float], s: float, tau_min: int, tau_max: int) -> Tuple[int, bool]:
"""Y(s): the bottom of the first dip of d' below s in [tau_min, tau_max], and True; else the argmin and False."""
for tau in range(tau_min, tau_max + 1):
if dp[tau] < s:
while tau < tau_max and dp[tau + 1] < dp[tau]:
tau += 1
return tau, True
best = tau_min
for tau in range(tau_min + 1, tau_max + 1):
if dp[tau] < dp[best]:
best = tau
return best, False
def parabolic(v: Sequence[float], tau: int) -> float:
"""The vertex of the parabola through v[tau - 1], v[tau], v[tau + 1], or tau at an edge."""
if tau < 1 or tau + 1 >= len(v):
return float(tau)
a = v[tau - 1] - 2 * v[tau] + v[tau + 1]
if a == 0:
return float(tau)
return tau + (v[tau - 1] - v[tau + 1]) / (2 * a)
def candidates(
frame: Sequence[float],
fs: float,
w: int,
fmin: float,
fmax: float,
prior: Sequence[float],
p_a: float = 0.01,
) -> List[Tuple[float, float]]:
"""Stage 1 on one frame: a list of (frequency in Hz, probability), at most one pair per period."""
tau_min = max(2, math.floor(fs / fmax))
tau_max = math.ceil(fs / fmin)
d = difference(frame, w, tau_max + 1) # @line L1
dp = cmndf(d) # @line L2
n = len(prior)
mass: Dict[int, float] = {}
for i in range(1, n + 1): # @line L3
tau, below = yin_period(dp, i / n, tau_min, tau_max) # @line L4
mass[tau] = mass.get(tau, 0.0) + (1.0 if below else p_a) * float(prior[i - 1]) # @line L5
out = []
for tau in sorted(mass):
period = parabolic(dp, tau) # @line L6
out.append((fs / period, mass[tau]))
return out
# ---------------------------------------------------------------- stage 2
def bin_frequency(m: int, fref: float = 55.0) -> float:
"""The center frequency of bin m: 10 cents per bin from fref."""
return fref * 2.0 ** (m / 120.0)
def observations(cands: Sequence[Tuple[float, float]], m_bins: int, fref: float = 55.0) -> List[float]:
"""The 2M observation probabilities: voiced bins 0 .. M-1, then unvoiced bins M .. 2M-1."""
pstar = [0.0] * m_bins
for f, p in cands:
m = round(1200.0 * math.log2(f / fref) / 10.0)
if 0 <= m < m_bins:
pstar[m] += p # @line L7
unvoiced = 0.5 * max(0.0, 1.0 - sum(pstar))
return [0.5 * v for v in pstar] + [unvoiced] * m_bins
def pitch_transition(m_bins: int, jump: int) -> List[List[Tuple[int, float]]]:
"""For each bin i, the list of (j, P(j | i)) with P(j | i) = (jump + 1 - |j - i|) / (jump + 1)^2 for |j - i| <= jump.
The triangular window sums to 1, as in the paper. Near the ends of the bin
range the part of the window outside the range is dropped, so those rows sum
to less than 1; normalizing each row instead would favor the end bins.
"""
z = float((jump + 1) ** 2)
rows = []
for i in range(m_bins):
lo, hi = max(0, i - jump), min(m_bins - 1, i + jump)
rows.append([(j, (jump + 1 - abs(j - i)) / z) for j in range(lo, hi + 1)])
return rows
def transition_prob(i: int, j: int, m_bins: int, rows, p_stay: float) -> float:
"""P(state j | state i) for the 2M states: the pitch move times the voicing move."""
bi, vi = i % m_bins, i < m_bins
bj, vj = j % m_bins, j < m_bins
pitch = dict(rows[bi]).get(bj, 0.0)
return pitch * (p_stay if vi == vj else 1.0 - p_stay)
def initial(m_bins: int, start: str) -> List[float]:
"""Log start probabilities: "all" is uniform over the 2M states, "unvoiced" (the paper) over the M unvoiced ones."""
if start == "all":
return [-math.log(2 * m_bins)] * (2 * m_bins)
if start == "unvoiced":
return [NEG_INF] * m_bins + [-math.log(m_bins)] * m_bins
raise ValueError("start must be 'all' or 'unvoiced'")
def viterbi(
obs: Sequence[Sequence[float]], m_bins: int, jump: int = 25, p_stay: float = 0.99, start: str = "all"
) -> Tuple[List[int], float]:
"""The most probable state sequence of the pYIN HMM and its log probability.
The states are 0 .. M-1 (voiced) and M .. 2M-1 (unvoiced). Ties go to the
smallest state. With start = "unvoiced", as in the paper, a first frame whose
voiced mass is 1 gives every path probability 0, and ValueError is raised.
"""
s_count = 2 * m_bins
rows = pitch_transition(m_bins, jump)
into: List[List[Tuple[int, float]]] = [[] for _ in range(m_bins)] # into[j] = (i, log P(j | i))
for i, row in enumerate(rows):
for j, p in row:
into[j].append((i, math.log(p)))
log_stay, log_switch = safe_log(p_stay), safe_log(1.0 - p_stay)
init = initial(m_bins, start)
delta = [init[s] + safe_log(obs[0][s]) for s in range(s_count)] # @line L8
back: List[List[int]] = []
for t in range(1, len(obs)): # @line L9
new = [NEG_INF] * s_count
ptr = [0] * s_count
for j in range(s_count):
bj, vj = j % m_bins, j < m_bins
best, arg = NEG_INF, -1
for bi, lp in into[bj]:
for vi in (True, False):
i = bi if vi else bi + m_bins
if delta[i] == NEG_INF:
continue
cand = delta[i] + lp + (log_stay if vi == vj else log_switch) # @line L10
if cand > best or (cand == best and i < arg):
best, arg = cand, i
new[j] = best + safe_log(obs[t][j]) if arg >= 0 else NEG_INF # @line L11
ptr[j] = max(arg, 0)
delta = new
back.append(ptr)
last = max(range(s_count), key=lambda s: (delta[s], -s)) # @line L12
if delta[last] == NEG_INF:
raise ValueError("every state sequence has probability 0")
path = [last]
for ptr in reversed(back): # @line L13
path.append(ptr[path[-1]])
path.reverse()
return path, delta[last]
def pyin(
x: Sequence[float],
fs: float,
frame_len: int,
hop: int,
fmin: float = 55.0,
fmax: float = 880.0,
m_bins: int = 480,
jump: int = 25,
prior: Optional[Sequence[float]] = None,
start: str = "all",
) -> List[Optional[float]]:
"""The pYIN track: one frequency in Hz (the bin center) or None (unvoiced) per frame.
Each frame uses frame_len samples for the sum and needs frame_len + fs / fmin + 2 samples.
"""
if prior is None:
prior = threshold_prior()
need = frame_len + math.ceil(fs / fmin) + 2
obs = []
pos = 0
while pos + need <= len(x):
obs.append(observations(candidates(x[pos : pos + need], fs, frame_len, fmin, fmax, prior), m_bins))
pos += hop
if not obs:
return []
path, _ = viterbi(obs, m_bins, jump, 0.99, start)
return [bin_frequency(s) if s < m_bins else None for s in path] # @line L14
test_pyin.py 156 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pyin/. The authors are listed in prov/FCGMHH.jsonl.
import itertools
import math
import random
from fractions import Fraction
import pytest
from nlslog import NEG_INF, safe_log
from pyin import (
beta_cdf,
bin_frequency,
candidates,
cmndf,
difference,
initial,
observations,
pitch_transition,
pyin,
threshold_prior,
transition_prob,
viterbi,
yin_period,
)
FS = 8000
def tone(n, f=220.0, noise=0.0, seed=0):
rng = random.Random(seed)
return [
0.6 * math.sin(2 * math.pi * f * i / FS) + 0.3 * math.sin(4 * math.pi * f * i / FS + 0.5) + rng.gauss(0, noise)
for i in range(n)
]
def test_prior_sums_to_one_exactly_and_has_mean_near_one_tenth():
prior = threshold_prior()
assert len(prior) == 100
assert sum(prior) == 1
assert all(p > 0 for p in prior)
mean = sum(Fraction(i, 100) * p for i, p in enumerate(prior, 1))
assert abs(float(mean) - 0.105) < 1e-3 # right ends of the bins of a Beta(2, 18) with mean 0.1
assert max(range(100), key=lambda i: prior[i]) == 5 # s = 0.06, near the mode 1/18
def test_beta_cdf_matches_numerical_integration():
def pdf(x):
return 342 * x * (1 - x) ** 17 # Beta(2, 18): 1 / B(2, 18) = 19! / (1! 17!) = 18 * 19
for x in (0.05, 0.1, 0.3):
n = 1000
h = x / n
simpson = h / 3 * sum((1 if k in (0, n) else 4 if k % 2 else 2) * pdf(k * h) for k in range(n + 1))
assert abs(beta_cdf(x, 2, 18) - simpson) < 1e-9
def test_yin_period_is_the_smallest_local_minimum_below_the_threshold():
rng = random.Random(4)
for _ in range(300):
dp = [rng.random() for _ in range(15)]
s = rng.random()
lo, hi = 2, 13
got = yin_period(dp, s, lo, hi)
brute = [t for t in range(lo, hi + 1) if dp[t] < s and (t == hi or dp[t + 1] >= dp[t])]
if brute:
assert got == (brute[0], True)
else:
assert got == (min(range(lo, hi + 1), key=lambda t: (dp[t], t)), False)
def test_candidate_mass_is_the_sum_over_thresholds():
frame = tone(400, noise=0.12, seed=3)
prior = threshold_prior()
cands = candidates(frame, FS, 200, 55, 880, prior)
dp = cmndf(difference(frame, 200, 147))
total = 0.0
for i in range(1, 101):
_, below = yin_period(dp, i / 100, 9, 146)
total += (1.0 if below else 0.01) * float(prior[i - 1])
assert abs(sum(p for _, p in cands) - total) < 1e-12
assert 0 < total < 1
assert len(cands) >= 2 # noise splits the mass between periods
def test_clean_sine_gives_one_certain_candidate():
frame = [math.sin(2 * math.pi * 200 * i / FS) for i in range(400)]
cands = candidates(frame, FS, 200, 55, 880, threshold_prior())
assert len(cands) == 1
f, p = cands[0]
assert abs(f - 200) < 0.1
assert abs(p - 1) < 1e-12
def brute_force_best(obs, m, jump, p_stay, start):
rows = pitch_transition(m, jump)
init = initial(m, start)
best = NEG_INF
for seq in itertools.product(range(2 * m), repeat=len(obs)):
score = init[seq[0]] + safe_log(obs[0][seq[0]])
for t in range(1, len(obs)):
score += safe_log(transition_prob(seq[t - 1], seq[t], m, rows, p_stay)) + safe_log(obs[t][seq[t]])
best = max(best, score)
return best
def path_score(path, obs, m, jump, p_stay, start):
rows = pitch_transition(m, jump)
score = initial(m, start)[path[0]] + safe_log(obs[0][path[0]])
for t in range(1, len(obs)):
score += safe_log(transition_prob(path[t - 1], path[t], m, rows, p_stay)) + safe_log(obs[t][path[t]])
return score
def test_viterbi_matches_brute_force():
rng = random.Random(11)
for trial in range(6):
m, jump, frames = 3, 1, 4
obs = []
for _ in range(frames):
p = [rng.random() for _ in range(m)]
z = sum(p) * rng.uniform(1.0, 2.0)
p = [v / z for v in p] # candidate mass per bin, total below 1
obs.append([0.5 * v for v in p] + [0.5 * (1 - sum(p))] * m)
for start in ("all", "unvoiced"):
path, score = viterbi(obs, m, jump, 0.9, start)
best = brute_force_best(obs, m, jump, 0.9, start)
assert abs(score - best) < 1e-9
assert abs(path_score(path, obs, m, jump, 0.9, start) - best) < 1e-9
def test_log_space_survives_where_the_product_underflows():
m, frames = 2, 400
obs = [[1e-3, 1e-4, 1e-5, 1e-5] for _ in range(frames)]
assert math.prod(o[0] for o in obs) == 0.0
path, score = viterbi(obs, m, 1, 0.99)
assert path == [0] * frames
assert math.isfinite(score)
def test_paper_start_fails_when_the_first_frame_is_surely_voiced():
obs = [observations([(220.0, 1.0)], 3, 220.0), observations([(220.0, 0.5)], 3, 220.0)]
assert obs[0] == [0.5, 0.0, 0.0, 0.0, 0.0, 0.0]
with pytest.raises(ValueError):
viterbi(obs, 3, 1, 0.99, "unvoiced")
path, _ = viterbi(obs, 3, 1, 0.99, "all")
assert path[0] < 3
def test_track_of_a_tone_then_silence():
x = tone(1000, noise=0.05, seed=3) + [0.0] * 600
track = pyin(x, FS, 200, 200, m_bins=250)
assert track == [220.0] * 4 + [None] * 3
assert bin_frequency(240) == 220.0
History
Alain de Cheveigné and Hideki Kawahara published YIN in 2002. Matthias Mauch and Simon Dixon, at Queen Mary University of London, presented pYIN at ICASSP 2014, with a Vamp plugin implementation. The idea of the paper is that some threshold usually gives the right YIN estimate, but no single threshold is right for every frame, so a distribution over thresholds and a tracking HMM can recover the right one. Ports of pYIN later appeared in common audio libraries.
References
- Matthias Mauch and Simon Dixon, PYIN, a fundamental frequency estimator using probabilistic threshold distributions, Proceedings of the IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP), 2014, 659 to 663, Section 2.1 (equations 1 to 5, the threshold prior and the candidate probabilities), Section 2.2 (equations 6 to 8, the pitch and voicing HMM) and Section 3 (the evaluation on synthesized singing)
- Alain de Cheveigné and Hideki Kawahara, YIN, a fundamental frequency estimator for speech and music, Journal of the Acoustical Society of America 111(4), 2002, 1917 to 1930, Section II, steps 2 to 5 (the difference function, the cumulative mean normalization, the absolute threshold and the parabolic interpolation)
- Lawrence R. Rabiner, A tutorial on hidden Markov models and selected applications in speech recognition, Proceedings of the IEEE 77(2), 1989, 257 to 286, Section III, the solution to problem 2 (the Viterbi algorithm)
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 FCGMHH Edit this page History Report an error Markdown