Algorithm Search⌘K

Algorithmadvanced

Perceptual linear prediction

Also called PLP, PLP analysis.

Hermansky's features: a Bark-scale critical band spectrum with equal loudness and cube-root compression, modeled by an all-pole fit.

Time
O(N log N + M N + M p + p^2) worst
Space
O(M N) extra
Where
M = the number of critical band samples; N = the FFT length; p = the model order
Properties
deterministicexactnot in placeonline
Origin
Hynek Hermansky, 1990

Perceptual linear prediction, or PLP, is the feature extractor of Hermansky (1990): it warps the power spectrum of a frame to the Bark scale, smooths it with a critical band curve, weights it by an equal loudness curve and takes its cube root, and then fits an all-pole model to the result. Plain linear predictive coding fits the all-pole model to the spectrum as it is, with the same resolution at all frequencies; PLP fits it to a spectrum that has first been reshaped to match hearing, so a low model order such as 5 is enough. MFCC shape the spectrum with a mel filter bank and a log and then use a cosine transform, where PLP uses the cube root and the all-pole fit. RASTA filtering is often added to PLP to remove slow channel effects.

In plain words

PLP first changes the spectrum of a short frame of speech the way the ear would. It spreads the frequencies on a scale where equal steps sound like equal steps, and it sums the energy in bands about as wide as the ear's own filters. It then lowers the very low and very high frequencies, which the ear hears less, and compresses loud and soft parts with a cube root, as loudness grows with the cube root of power. On this reshaped spectrum it fits a smooth curve with only a few peaks, using the same method that linear prediction uses on the raw spectrum. The curve's few numbers, usually turned into cepstral coefficients, are the features. Because the reshaping hides details that differ between speakers, a curve with just two peaks describes the vowel well.

The problem

Given a frame of speech at a sample rate of fsf_s Hz and a model order pp, compute the cepstrum c0,…,cKc_0, \ldots, c_K of an all-pole model of the auditory spectrum of the frame. Hermansky's analysis has these steps. The frame is windowed (Hamming) and its power spectrum P(ω)P(\omega) is computed by the FFT. The frequency ff in Hz goes to the Bark value

Ω(f)=6ln⁡(f600+(f600)2+1)=6asinh⁡(f/600).\Omega(f) = 6 \ln\Bigl(\frac{f}{600} + \sqrt{\Bigl(\frac{f}{600}\Bigr)^2 + 1}\Bigr) = 6 \operatorname{asinh}(f / 600).

The critical band curve, with zz in Bark, is

ψ(z)={0z<−1.3102.5(z+0.5)−1.3≤z<−0.51−0.5≤z≤0.510−(z−0.5)0.5<z≤2.50z>2.5,\psi(z) = \begin{cases} 0 & z < -1.3 \\ 10^{2.5 (z + 0.5)} & -1.3 \le z < -0.5 \\ 1 & -0.5 \le z \le 0.5 \\ 10^{-(z - 0.5)} & 0.5 < z \le 2.5 \\ 0 & z > 2.5, \end{cases}

the equal loudness curve, with ω=2πf\omega = 2\pi f in rad/s, is

E(ω)=(ω2+56.8⋅106) ω4(ω2+6.3⋅106)2 (ω2+0.38⋅109),E(\omega) = \frac{(\omega^2 + 56.8 \cdot 10^6)\, \omega^4}{(\omega^2 + 6.3 \cdot 10^6)^2\, (\omega^2 + 0.38 \cdot 10^9)},

and the intensity-to-loudness law is Φ=Ξ0.33\Phi = \Xi^{0.33}. The all-pole model is g/∣A(ejω)∣2g / |A(e^{j\omega})|^2 with A(z)=1−∑k=1pakz−kA(z) = 1 - \sum_{k=1}^{p} a_k z^{-k}.

The algorithm

The band centers Ω0,…,ΩM−1\Omega_0, \ldots, \Omega_{M-1} are M=⌈Ω(fs/2)⌉+1M = \lceil \Omega(f_s/2) \rceil + 1 points evenly spaced from 0 to Ω(fs/2)\Omega(f_s/2), a little under 1 Bark apart. Bin kk of the FFT is at fk=kfs/Nf_k = k f_s / N.

  1. PLP(frame, f_s, p, K)
  2. 1P[k] ← |FFT_N(Hamming · frame)[k]|² for k ← 0 to N/2
  3. 2W[i][k] ← ψ(Ω_i - Ω(f_k)) for i ← 0 to M - 1 and k ← 0 to N/2
  4. 3θ[i] ← Σ_k W[i][k] P[k] ▷ critical band integration
  5. 4ξ[i] ← E(2π · Ω⁻¹(Ω_i)) · θ[i] ▷ equal loudness
  6. 5φ[i] ← ξ[i]^0.33 ▷ cube root law
  7. 6φ[0] ← φ[1]; φ[M - 1] ← φ[M - 2]
  8. 7r[τ] ← (φ[0] + 2 Σ_{i=1}^{M-2} φ[i] cos(π τ i / (M - 1)) + φ[M - 1] cos(π τ)) / (2(M - 1)) for τ ← 0 to p
  9. 8(a_1 … a_p, g) ← LEVINSON-DURBIN(r, p)
  10. 9c_0 ← ln g; c_m ← a_m + Σ_{k=1}^{m-1} (k/m) c_k a_{m-k} for m ← 1 to K ▷ a_j = 0 for j > p

Line L2 sums over the FFT bins with the weight ψ(Ωi−Ω(fk))\psi(\Omega_i - \Omega(f_k)); a bin contributes to band ii when it lies between 2.5 Bark below and 1.3 Bark above the center, the same reach as the integration of the paper, which resamples the warped spectrum instead. Line L6 copies the end values, because the two end bands have no data beyond the band edges; the paper does the same. Line L7 is the inverse DFT of the even extension of ϕ\phi over 2(M−1)2(M-1) points, so rr is the autocorrelation of a signal whose power spectrum on the Bark axis is ϕ\phi. Line L8 is the Levinson-Durbin recursion, as in linear predictive coding, and gg is its final prediction error. Line L9 turns the model into its cepstrum, the usual output. The model lives on the Bark axis: ω=π\omega = \pi in A(ejω)A(e^{j\omega}) means fs/2f_s / 2, and ω=πΩ/Ω(fs/2)\omega = \pi \Omega / \Omega(f_s/2) in general.

Example

Take fs=8000f_s = 8000 Hz, so Ω(4000)=15.58\Omega(4000) = 15.58 Bark, M=17M = 17 bands 0.973 Bark apart, centered at 0, 98, 198, 304, 417, 542, 681, 838, 1017, 1222, 1460, 1737, 2059, 2436, 2877, 3394 and 4000 Hz. The equal loudness weight is −32.8-32.8 dB at 100 Hz, −12.0-12.0 dB at 500 Hz, −7.7-7.7 dB at 1 kHz, −4.3-4.3 dB at 2 kHz and −1.8-1.8 dB at 4 kHz, relative to its limit at high frequencies.

A pulse train of 100 Hz through one resonance at 1000 Hz with a bandwidth of 80 Hz gives, for a frame of 200 samples (25 ms), the auditory spectrum ϕ\phi = 0.194, 0.194, 0.468, 0.750, 1.066, 1.473, 2.073, 4.153, 6.955, 5.356, 3.201, 1.973, 1.583, 1.388, 1.280, 1.240, 1.240, with its peak in the band at 1017 Hz. A 5th order model gives a=(−0.2828,−0.5812,−0.2315,−0.0571,−0.0879)a = (-0.2828, -0.5812, -0.2315, -0.0571, -0.0879), g=1.4723g = 1.4723, and the cepstrum c0c_0 to c5c_5 = 0.3869, −0.2828-0.2828, −0.5413-0.5413, −0.0747-0.0747, 0.1325, −0.0384-0.0384. The peak of the model spectrum, mapped back from the Bark axis, is at 1104 Hz. For resonances at 500, 1500 and 2000 Hz the peaks are at 531, 1577 and 2059 Hz, all within 0.6 Bark of the resonance.

Correctness

PLP computes a defined feature, so correctness means that lines L7 to L9 do what they claim for the auditory spectrum built in lines L1 to L6. The full proofs are below.

  • Line L7 gives a valid autocorrelation. If every ϕ[i]>0\phi[i] > 0, the Toeplitz matrix of r[0],…,r[p]r[0], \ldots, r[p] is positive definite (theorem), so the Levinson-Durbin recursion runs without division by zero, every reflection coefficient has ∣k∣<1|k| < 1, and AA has all its zeros inside the unit circle.
  • Line L9 is the cepstrum of the model. With AA minimum phase, the numbers of line L9 are the Fourier coefficients of ln⁡(g/∣A(ejω)∣2)\ln(g / |A(e^{j\omega})|^2): ln⁡(g/∣A∣2)=∑m=−∞∞c∣m∣e−jωm\ln(g/|A|^2) = \sum_{m=-\infty}^{\infty} c_{|m|} e^{-j\omega m} (theorem).
  • Loudness moves only c0c_0. A gain ss on the frame multiplies θ\theta and ξ\xi by s2s^2, ϕ\phi and rr by s0.66s^{0.66}, leaves aa unchanged and multiplies gg by s0.66s^{0.66}, so only c0c_0 changes, by 0.66ln⁡∣s∣0.66 \ln |s| (theorem).
  • The model peak follows a formant. A 5th order model has room for two resonances, and on vowel-like inputs its peaks sit near the formants on the Bark axis, as in the example (measurement). Hermansky's experiments that favour order 5 for speaker-independent features are measurements too.
Proof: The all-pole fit and the cepstrum of PLP are well defined and correctfull

We work in the real RAM. Lines L1 to L6 compute the auditory spectrum ϕ[0],…,ϕ[M−1]\phi[0], \ldots, \phi[M-1] by direct formulas, so there is nothing to prove about them beyond the definitions on the page. We prove that lines L7 to L9 are well defined and compute the cepstrum of an all-pole model of ϕ\phi, and that a gain on the frame changes only c0c_0. Let n=2(M−1)n = 2(M - 1) and assume M≥2M \ge 2, 1≤p<n1 \le p < n and ϕ[i]>0\phi[i] > 0 for every ii.

Let ϕ~\tilde\phi be the even extension of ϕ\phi to nn points: ϕ~[i]=ϕ[i]\tilde\phi[i] = \phi[i] for 0≤i≤M−10 \le i \le M - 1 and ϕ~[i]=ϕ[n−i]\tilde\phi[i] = \phi[n - i] for M≤i≤n−1M \le i \le n - 1. Let ωi=2πi/n\omega_i = 2\pi i / n.

Lemma 1 (line L7 is an inverse DFT). For 0≤τ≤p0 \le \tau \le p, r[τ]=1n∑i=0n−1ϕ~[i] ejωiτr[\tau] = \frac{1}{n} \sum_{i=0}^{n-1} \tilde\phi[i]\, e^{j \omega_i \tau}, and this number is real.

Proof. Pair the term ii with the term n−in - i for 1≤i≤M−21 \le i \le M - 2. They have the same ϕ~\tilde\phi and conjugate exponentials, so together they give 2ϕ[i]cos⁡(πτi/(M−1))2 \phi[i] \cos(\pi \tau i / (M - 1)). The term i=0i = 0 gives ϕ[0]\phi[0], and the term i=M−1i = M - 1 gives ϕ[M−1]ejπτ=ϕ[M−1]cos⁡(πτ)\phi[M - 1] e^{j\pi\tau} = \phi[M-1] \cos(\pi \tau). Dividing by nn gives line L7. □\square

Lemma 2 (positive definite). The (p+1)×(p+1)(p+1) \times (p+1) Toeplitz matrix RR with Rs,t=r[∣s−t∣]R_{s,t} = r[|s - t|] is positive definite.

Proof. Since r[−τ]=r[τ]r[-\tau] = r[\tau] by Lemma 1 (the sum is real and even in τ\tau), Rs,t=1n∑iϕ~[i]ejωi(s−t)R_{s,t} = \frac{1}{n} \sum_i \tilde\phi[i] e^{j\omega_i (s - t)}. For a real vector v≠0v \ne 0,

vTRv=1n∑i=0n−1ϕ~[i] ∣∑s=0pvsejωis∣2≥0.v^{\mathsf T} R v = \frac{1}{n} \sum_{i=0}^{n-1} \tilde\phi[i]\, \Bigl|\sum_{s=0}^{p} v_s e^{j\omega_i s}\Bigr|^2 \ge 0.

Equality would need the polynomial V(z)=∑svszsV(z) = \sum_s v_s z^s, of degree at most pp and not zero, to vanish at the nn distinct points ejωie^{j\omega_i}, because every ϕ~[i]>0\tilde\phi[i] > 0. A nonzero polynomial of degree at most p<np < n has fewer than nn roots, so the sum is positive. □\square

Lemma 3 (line L8). On a positive definite Toeplitz matrix, the Levinson-Durbin recursion never divides by zero, every reflection coefficient satisfies ∣ki∣<1|k_i| < 1, every prediction error eie_i is positive, and the result a1,…,apa_1, \ldots, a_p solves the normal equations ∑k=1pakr[∣i−k∣]=r[i]\sum_{k=1}^{p} a_k r[|i - k|] = r[i] for 1≤i≤p1 \le i \le p, with g=ep=r[0]−∑kakr[k]>0g = e_p = r[0] - \sum_k a_k r[k] > 0. The polynomial A(z)=1−∑kakz−kA(z) = 1 - \sum_k a_k z^{-k} then has all its zeros strictly inside the unit circle.

Proof. These are the standard facts about the recursion, proved on the Levinson-Durbin recursion page: the error after step ii is ei=det⁡Ri+1/det⁡Rie_i = \det R_{i+1} / \det R_i, a ratio of leading principal minors, so it is positive, and ei=ei−1(1−ki2)e_i = e_{i-1}(1 - k_i^2) forces ∣ki∣<1|k_i| < 1. A polynomial built by the recursion from reflection coefficients of modulus below 1 has its zeros inside the unit circle, which is the stability result of the lattice form (the Schur-Cohn test read backwards). □\square

Lemma 4 (line L9 is the cepstrum). Let AA have all its zeros inside the unit circle and g>0g > 0. Define c0=ln⁡gc_0 = \ln g and cmc_m for m≥1m \ge 1 by line L9. Then for every real ω\omega,

ln⁡g∣A(ejω)∣2=∑m=−∞∞c∣m∣ e−jωm.\ln \frac{g}{|A(e^{j\omega})|^2} = \sum_{m=-\infty}^{\infty} c_{|m|}\, e^{-j\omega m}.

Proof. Write A(z)=∏i=1p(1−ziz−1)A(z) = \prod_{i=1}^{p} (1 - z_i z^{-1}) with ∣zi∣<1|z_i| < 1. For ∣z∣≥1|z| \ge 1 each factor has the convergent series ln⁡(1−ziz−1)=−∑m≥1zimz−m/m\ln(1 - z_i z^{-1}) = -\sum_{m \ge 1} z_i^m z^{-m} / m, so L(z)=−ln⁡A(z)=∑m≥1c^mz−mL(z) = -\ln A(z) = \sum_{m \ge 1} \hat c_m z^{-m} converges for ∣z∣≥1|z| \ge 1, with real c^m\hat c_m because the aka_k are real. Differentiate A(z)eL(z)=1A(z) e^{L(z)} = 1, or equivalently L′(z)A(z)=−A′(z)L'(z) A(z) = -A'(z), and multiply by −z-z:

(∑m≥1mc^mz−m)(1−∑k=1pakz−k)=∑k=1pkakz−k.\Bigl(\sum_{m \ge 1} m \hat c_m z^{-m}\Bigr)\Bigl(1 - \sum_{k=1}^{p} a_k z^{-k}\Bigr) = \sum_{k=1}^{p} k a_k z^{-k}.

The coefficient of z−mz^{-m} gives mc^m−∑k=1m−1kc^kam−k=mamm \hat c_m - \sum_{k=1}^{m-1} k \hat c_k a_{m-k} = m a_m, with aj=0a_j = 0 for j>pj > p. Dividing by mm gives the recursion of line L9, so c^m=cm\hat c_m = c_m for m≥1m \ge 1 by induction on mm. Finally ln⁡(g/∣A∣2)=ln⁡g−ln⁡A(ejω)−ln⁡A(ejω)‾=ln⁡g+∑m≥1cm(e−jωm+ejωm)\ln(g / |A|^2) = \ln g - \ln A(e^{j\omega}) - \overline{\ln A(e^{j\omega})} = \ln g + \sum_{m \ge 1} c_m (e^{-j\omega m} + e^{j\omega m}). □\square

Lemma 5 (a gain moves only c0c_0). If the frame is multiplied by s≠0s \ne 0 and every ϕ[i]>0\phi[i] > 0, then aa is unchanged, gg is multiplied by ∣s∣0.66|s|^{0.66}, c0c_0 grows by 0.66ln⁡∣s∣0.66 \ln |s|, and cmc_m for m≥1m \ge 1 is unchanged.

Proof. PP scales by s2s^2 in line L1. Lines L3 and L4 are linear, so θ\theta and ξ\xi scale by s2s^2, and line L5 gives ϕ\phi scaled by (s2)0.33=∣s∣0.66(s^2)^{0.33} = |s|^{0.66}. Line L6 copies values, and line L7 is linear, so rr scales by the same factor λ=∣s∣0.66\lambda = |s|^{0.66}. The normal equations of Lemma 3 are unchanged when rr is scaled, so aa is the same, and g=r[0]−∑akr[k]g = r[0] - \sum a_k r[k] scales by λ\lambda. In line L9, c0=ln⁡gc_0 = \ln g grows by ln⁡λ\ln \lambda, and the cmc_m for m≥1m \ge 1 depend only on aa. □\square

Theorem. If the auditory spectrum is positive and p<2(M−1)p < 2(M - 1), PLP returns the first K+1K + 1 cepstral coefficients of a stable all-pole model g/∣A∣2g / |A|^2 whose predictor solves the normal equations of the autocorrelation rr of ϕ\phi, and a gain on the frame changes only c0c_0.

Proof. Lemmas 1 to 5. □\square

The tests check Lemma 1 against a complex inverse DFT, Lemma 3 against a direct solve of the normal equations, Lemma 4 against the inverse DFT of the log model spectrum on 1024 points, and Lemma 5 with a gain of 4.

Complexity

In the real RAM, line L1 costs O(Nlog⁡N)O(N \log N), line L2 O(MN)O(M N) but only once per sample rate, line L3 O(MN)O(M N) with the dense weights or O(N)O(N) with only the nonzero ones, lines L4 to L6 O(M)O(M), line L7 O(Mp)O(M p), line L8 O(p2)O(p^2) and line L9 O(Kp)O(K p). With MM about 17 to 21 and p=5p = 5 to 12, the FFT dominates. The weight table takes O(MN)O(M N) memory.

Properties

  • Low order. The reshaped spectrum is smooth enough that a 5th order model describes the first two formants, against 10 to 14 for plain LPC at 8 to 10 kHz.
  • Gain separated. The predictor aa does not depend on the loudness, and all of it goes to gg and c0c_0.
  • Less speaker dependent. By smoothing over critical bands, PLP hides details such as the exact higher formants, which vary between speakers more than between vowels (measurement in the paper).
  • Not robust to the channel by itself. A fixed filter still changes the spectrum; RASTA filtering or cepstral mean normalization is needed for that.

Variants and improvements

  • RASTA-PLP. Filter the log critical band trajectories over time with the RASTA filter between lines L3 and L4, then exponentiate; this removes slow channel effects and is the common form in noisy and telephone speech.
  • PLP on mel filters. HTK computes PLP from its mel filter bank, with the equal loudness curve and the cube root applied to the filter outputs, and allows higher orders such as 12 for recognition.
  • Order and number of cepstra. Order 5 for speaker independence, orders 8 to 14 when more detail is wanted; usually 13 cepstra with delta features.
  • Other loudness laws. Some front ends use a log or a smaller power in place of the cube root; the all-pole fit then models a more compressed spectrum.

When to use it

Use PLP in place of or beside MFCC for GMM-HMM speech recognition, especially in the RASTA-PLP form for telephone or noisy speech, and when features should depend little on the speaker. Systems that combine several front ends often include it. For neural network recognizers trained on large data the log mel energies of a mel filter bank are simpler and usual. Do not use a 5th order PLP model when speaker identity matters: the point of the low order is to hide it.

Pitfalls

  • Forgetting the Bark axis. The model spectrum is a function of the warped frequency. Its peaks must be mapped back through Ω−1\Omega^{-1} before they are compared with formants in Hz.
  • Zero bands. A band with ϕ=0\phi = 0, from digital silence, makes the Toeplitz matrix singular. Add a tiny dither or a floor before line L5.
  • The cube root of negative values. Numerical noise can make a filtered (RASTA) band slightly negative; clamp before the power.
  • Mixing implementations. The paper's resampling, the HTK mel version and the rastamat code give different numbers; the end band handling and the equal loudness form differ too.
  • The sign of aa. With A(z)=1+∑akz−kA(z) = 1 + \sum a_k z^{-k}, as in some code, the recursion of line L9 changes sign. This page uses A(z)=1−∑akz−kA(z) = 1 - \sum a_k z^{-k}.

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
perceptual_linear_prediction.py 122 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/perceptual-linear-prediction/. The authors are listed in prov/H7TRFV.jsonl.

"""Perceptual linear prediction (PLP) of one frame, after Hermansky (1990).

Steps: the power spectrum of the windowed frame; critical band integration with
the masking curve psi on the Bark scale Omega(f) = 6 asinh(f / 600); the equal
loudness weight E(omega) of the paper (the form for a band up to about 5 kHz);
the cube root law Phi = Xi^0.33; an all-pole model of order p fitted to Phi
through its autocorrelation (the inverse DFT of Phi) and the Levinson-Durbin
recursion; and the cepstrum of the all-pole model.

The integration sums over the FFT bins with the weight psi(Omega_i - Omega(f_k)),
in place of the paper's resampling of the warped spectrum. The band centers are
M = ceil(Omega(fs / 2)) + 1 points equally spaced from 0 to Omega(fs / 2), a little
under 1 Bark apart. The LPC sign convention is A(z) = 1 - sum a_k z^-k.
"""

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

from nlsdsp import hamming, levinson, power_spectrum


def hz_to_bark(f: float) -> float:
    """Omega(f) = 6 ln(f / 600 + sqrt((f / 600)^2 + 1)) = 6 asinh(f / 600), f in Hz."""
    return 6.0 * math.asinh(f / 600.0)


def bark_to_hz(b: float) -> float:
    return 600.0 * math.sinh(b / 6.0)


def masking_curve(z: float) -> float:
    """The critical band curve psi of Hermansky (1990), z in Bark (target minus masker)."""
    if z < -1.3 or z > 2.5:
        return 0.0
    if z < -0.5:
        return 10.0 ** (2.5 * (z + 0.5))
    if z <= 0.5:
        return 1.0
    return 10.0 ** (-1.0 * (z - 0.5))


def equal_loudness(f: float) -> float:
    """E(omega) = (omega^2 + 56.8e6) omega^4 / ((omega^2 + 6.3e6)^2 (omega^2 + 0.38e9)), omega = 2 pi f."""
    w2 = (2.0 * math.pi * f) ** 2
    return (w2 + 56.8e6) * w2 * w2 / ((w2 + 6.3e6) ** 2 * (w2 + 0.38e9))


def band_centers(fs: float) -> List[float]:
    top = hz_to_bark(fs / 2.0)
    m = int(math.ceil(top)) + 1
    return [i * top / (m - 1) for i in range(m)]


def critical_band_weights(nfft: int, fs: float) -> Tuple[List[float], List[List[float]]]:
    """The band centers in Bark and the weights W[i][k] = psi(Omega_i - Omega(f_k))."""
    centers = band_centers(fs)
    barks = [hz_to_bark(k * fs / nfft) for k in range(nfft // 2 + 1)]
    return centers, [[masking_curve(c - b) for b in barks] for c in centers]


def autocorrelation_of_spectrum(phi: Sequence[float], max_lag: int) -> List[float]:
    """The inverse DFT of the even extension of phi_0 .. phi_{M-1} (a spectrum on 0 to pi):
    r[k] = phi_0 + 2 sum_{i=1}^{M-2} phi_i cos(pi k i / (M - 1)) + phi_{M-1} cos(pi k), over 2 (M - 1)."""
    m = len(phi)
    n = 2 * (m - 1)
    out = []
    for k in range(max_lag + 1):
        s = phi[0] + phi[-1] * math.cos(math.pi * k)
        s += 2.0 * sum(phi[i] * math.cos(math.pi * k * i / (m - 1)) for i in range(1, m - 1))
        out.append(s / n)
    return out


def lpc_to_cepstrum(a: Sequence[float], gain: float, n: int) -> List[float]:
    """The cepstrum c_0 .. c_{n-1} of the model spectrum gain / |A(e^{jw})|^2.

    c_0 = ln gain, and for m >= 1, c_m = a_m + sum_{k=1}^{m-1} (k / m) c_k a_{m-k},
    with a_m = 0 for m > p. This is the Fourier series of the log model spectrum."""
    p = len(a)
    c = [math.log(gain)] + [0.0] * (n - 1)
    for m in range(1, n):
        acc = a[m - 1] if m <= p else 0.0
        for k in range(max(1, m - p), m):
            acc += (k / m) * c[k] * a[m - k - 1]
        c[m] = acc
    return c


def plp_frame(
    frame: Sequence[float],
    fs: float = 8000.0,
    order: int = 5,
    num_ceps: Optional[int] = None,
    nfft: Optional[int] = None,
    weights=None,
) -> Tuple[List[float], List[float], float, List[float]]:
    """PLP of one frame. Returns (cepstrum, a, gain, phi): the cepstrum c_0 .. c_{num_ceps-1}
    of the all-pole model, the predictor a_1 .. a_p, the model gain and the auditory spectrum phi."""
    if nfft is None:
        nfft = 1 << max(1, (len(frame) - 1).bit_length())
    if num_ceps is None:
        num_ceps = order + 1
    win = hamming(len(frame))
    p = power_spectrum([s * w for s, w in zip(frame, win)], nfft)  # @line L1
    centers, w = weights if weights is not None else critical_band_weights(nfft, fs)  # @line L2
    theta = [sum(wi * pk for wi, pk in zip(row, p)) for row in w]  # @line L3
    xi = [equal_loudness(bark_to_hz(c)) * t for c, t in zip(centers, theta)]  # @line L4
    phi = [v ** 0.33 for v in xi]  # @line L5
    phi[0], phi[-1] = phi[1], phi[-2]  # @line L6
    r = autocorrelation_of_spectrum(phi, order)  # @line L7
    a, gain = levinson(r, order)  # @line L8
    return lpc_to_cepstrum(a, gain, num_ceps), a, gain, phi  # @line L9


def model_spectrum(a: Sequence[float], gain: float, omega: float) -> float:
    """gain / |A(e^{j omega})|^2 with A(z) = 1 - sum a_k z^-k."""
    re = 1.0 - sum(ak * math.cos(omega * (k + 1)) for k, ak in enumerate(a))
    im = sum(ak * math.sin(omega * (k + 1)) for k, ak in enumerate(a))
    return gain / (re * re + im * im)
test_perceptual_linear_prediction.py 136 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/perceptual-linear-prediction/. The authors are listed in prov/H7TRFV.jsonl.

import cmath
import math
import random

from nlsdsp import all_pole, levinson, pulse_train, white_noise
from perceptual_linear_prediction import (
    autocorrelation_of_spectrum,
    band_centers,
    bark_to_hz,
    critical_band_weights,
    equal_loudness,
    hz_to_bark,
    lpc_to_cepstrum,
    masking_curve,
    model_spectrum,
    plp_frame,
)


def test_bark_scale():
    assert round(hz_to_bark(5000.0), 1) == 16.9
    assert abs(hz_to_bark(600.0) - 6.0 * math.log(1.0 + math.sqrt(2.0))) < 1e-12
    for f in (0.0, 100.0, 1000.0, 3999.0):
        assert abs(bark_to_hz(hz_to_bark(f)) - f) < 1e-9


def test_masking_curve():
    assert masking_curve(0.0) == 1.0
    assert masking_curve(-0.5) == 1.0 and masking_curve(0.5) == 1.0
    assert abs(masking_curve(-1.3) - 0.01) < 1e-12
    assert abs(masking_curve(1.5) - 0.1) < 1e-12
    assert abs(masking_curve(2.5) - 0.01) < 1e-12
    assert masking_curve(-1.31) == 0.0 and masking_curve(2.51) == 0.0


def test_equal_loudness_rises_to_one():
    vals = [equal_loudness(f) for f in (50.0, 100.0, 500.0, 1000.0, 2000.0, 4000.0, 8000.0)]
    assert all(a < b for a, b in zip(vals, vals[1:]))
    assert all(0.0 < v < 1.0 for v in vals)
    assert equal_loudness(0.0) == 0.0
    assert abs(equal_loudness(1e7) - 1.0) < 1e-3


def test_band_centers_and_weights():
    c = band_centers(8000.0)
    assert len(c) == 17 and c[0] == 0.0 and abs(c[-1] - hz_to_bark(4000.0)) < 1e-12
    assert all(0.9 < b - a < 1.0 for a, b in zip(c, c[1:]))
    centers, w = critical_band_weights(256, 8000.0)
    assert len(w) == 17 and all(len(row) == 129 for row in w)
    # each band reaches 2.5 Bark below its center and 1.3 Bark above
    for ci, row in zip(centers, w):
        for k, v in enumerate(row):
            z = hz_to_bark(k * 8000.0 / 256)
            if v > 0:
                assert ci - 2.5 <= z <= ci + 1.3


def test_autocorrelation_of_spectrum_is_an_inverse_dft():
    rng = random.Random(3)
    phi = [rng.uniform(0.1, 2.0) for _ in range(9)]
    full = phi + phi[-2:0:-1]  # the even extension, 16 points
    n = len(full)
    ref = [(sum(full[i] * cmath.exp(2j * math.pi * k * i / n) for i in range(n)) / n).real for k in range(6)]
    got = autocorrelation_of_spectrum(phi, 5)
    assert all(abs(g - r) < 1e-12 for g, r in zip(got, ref))
    # a flat spectrum is white: r = [phi, 0, 0, ...]
    flat = autocorrelation_of_spectrum([2.0] * 9, 4)
    assert abs(flat[0] - 2.0) < 1e-12 and all(abs(v) < 1e-12 for v in flat[1:])


def _solve(m, b):
    # Gauss elimination with partial pivoting, for the Toeplitz check
    n = len(b)
    a = [row[:] + [b[i]] for i, row in enumerate(m)]
    for col in range(n):
        piv = max(range(col, n), key=lambda r: abs(a[r][col]))
        a[col], a[piv] = a[piv], a[col]
        for r in range(n):
            if r != col:
                f = a[r][col] / a[col][col]
                a[r] = [x - f * y for x, y in zip(a[r], a[col])]
    return [a[i][n] / a[i][i] for i in range(n)]


def test_levinson_on_an_auditory_spectrum_matches_a_direct_solve():
    rng = random.Random(8)
    x = white_noise(rng, 200, 0.3)
    _, a, gain, phi = plp_frame(x, 8000.0, order=5)
    r = autocorrelation_of_spectrum(phi, 5)
    toeplitz = [[r[abs(i - j)] for j in range(5)] for i in range(5)]
    direct = _solve(toeplitz, r[1:6])
    assert all(abs(u - v) < 1e-9 for u, v in zip(a, direct))
    assert abs(gain - (r[0] - sum(ak * rk for ak, rk in zip(a, r[1:6])))) < 1e-9


def test_lpc_to_cepstrum_matches_the_log_spectrum():
    a, gain, n = [1.2, -0.7, 0.2], 0.5, 1024
    c = lpc_to_cepstrum(a, gain, 12)
    log_s = [math.log(model_spectrum(a, gain, 2 * math.pi * i / n)) for i in range(n)]
    for m in range(12):
        # c is the inverse DFT of the log model spectrum: ln S(w) = sum over all m of c_|m| e^{-j w m}
        ref = sum(log_s[i] * math.cos(2 * math.pi * m * i / n) for i in range(n)) / n
        assert abs(c[m] - ref) < 1e-9


def test_end_samples_copy_their_neighbors():
    rng = random.Random(1)
    _, _, _, phi = plp_frame(white_noise(rng, 200, 0.2), 8000.0)
    assert phi[0] == phi[1] and phi[-1] == phi[-2]


def test_gain_changes_only_c0():
    rng = random.Random(5)
    x = white_noise(rng, 200, 0.2)
    c1, a1, _, _ = plp_frame(x, 8000.0)
    c2, a2, _, _ = plp_frame([4.0 * v for v in x], 8000.0)
    # power scales by 16, the cube root law by 16^0.33, the gain by the same
    assert abs(c2[0] - c1[0] - 0.33 * math.log(16.0)) < 1e-9
    assert all(abs(u - v) < 1e-9 for u, v in zip(c1[1:], c2[1:]))
    assert all(abs(u - v) < 1e-9 for u, v in zip(a1, a2))


def test_model_peak_near_a_formant():
    fs = 8000.0
    top = hz_to_bark(fs / 2.0)
    for formant in (500.0, 1000.0, 1500.0, 2000.0):
        r = math.exp(-math.pi * 80.0 / fs)
        th = 2.0 * math.pi * formant / fs
        x = all_pole(pulse_train(100.0, fs, 600), [2.0 * r * math.cos(th), -r * r])
        _, a, gain, _ = plp_frame(x[200:400], fs, order=5)
        best = max(range(401), key=lambda i: model_spectrum(a, gain, math.pi * i / 400))
        # the model lives on the Bark axis: omega = pi means fs / 2
        assert abs(best / 400.0 * top - hz_to_bark(formant)) < 1.0

History

Linear prediction came to speech in the late 1960s and early 1970s with the work of Itakura and Saito and of Atal and Hanauer, and its all-pole fit follows the spectrum with the same accuracy at all frequencies, unlike the ear. Hynek Hermansky published PLP in the Journal of the Acoustical Society of America in 1990. The paper joined three approximations from psychoacoustics with an all-pole model and, from its experiments, recommended a 5th order model for features that should not depend on the speaker. In 1994 Hermansky and Morgan added RASTA filtering, and RASTA-PLP became a standard front end of the 1990s, used next to MFCC in many recognizers.

References

  1. Hynek Hermansky, Perceptual linear predictive (PLP) analysis of speech, Journal of the Acoustical Society of America 87(4), 1990, 1738 to 1752, the steps of the analysis (the Bark warping, the critical band curve, the equal loudness curve, the cube root law and the all-pole model fitted through the inverse DFT) and the experiments that recommend a 5th order model
  2. The HTK Book, version 3.4, Chapter Speech Input/Output, section Perceptual Linear Prediction (PLP computed on a mel filter bank)
  3. Xuedong Huang, Alex Acero and Hsiao-Wuen Hon, Spoken Language Processing, Prentice Hall, 2001, Chapter 6 (Speech Signal Representations), sections Linear Predictive Coding and Perceptually Motivated Representations
  4. S. B. Davis and P. Mermelstein, Comparison of parametric representations for monosyllabic word recognition in continuously spoken sentences, IEEE Transactions on Acoustics, Speech, and Signal Processing 28(4), 1980, 357 to 366, Section II.C, Eq. (3): the cepstrum computed directly from the linear prediction coefficients

Where this leads

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
  • a scene preset for the example