E4 cut a sound into frames, windowed each frame, took its DFT and lined the results up into a spectrogram. This exercise finds the peaks in the spectrum of each frame and connects the peaks of neighbouring frames into lines. Each line is a sinusoid whose frequency and amplitude change over time, and this representation is called the sinusoidal model.
The exercise has four parts: getting the frequency estimate of a sinusoid to within 0.05 Hz, tracking two chirps 40 Hz apart, tracking a sinusoid 500 times weaker than another, and choosing the analysis parameters for a complex signal.
Finding peaks in a spectrum
E3 read a frequency from a spectrum by taking the bin with the largest magnitude. 440 Hz came out as 430.66 Hz, because the bins are 21.5 Hz apart and a frequency between two bins can be off by up to half a bin. E4 showed that after windowing every peak has the shape of the window’s main lobe, which is several bins wide, so the values on either side of the highest bin also carry information about where the peak is, and they can be used to place the peak between bins.
First find the peaks. A bin whose value is higher than both of its neighbours and above a threshold t counts as a peak. The threshold is a dB value such as −40 dB; local maxima below it are treated as noise and dropped. peakDetection(mX, t) returns the numbers of these bins.
Then fit a parabola through three points at each peak. Let the highest bin be bin k with value β, and let its left and right neighbours have values α and γ, all in dB. The vertex of the parabola through these three points is at a distance of
$$ \hat p = \frac{1}{2}\,\frac{\alpha - \gamma}{\alpha - 2\beta + \gamma} $$from bin k, in bins. The peak is at k + p̂, which converts to a frequency of (k + p̂) × fs / N. If the left neighbour is higher than the right one, p̂ is negative and the vertex lies to the left; if both are equal, p̂ is 0 and the vertex is exactly on bin k. This is called parabolic interpolation, and peakInterp(mX, pX, ploc) does it, returning the position, magnitude and phase of each peak’s vertex. The top of the main lobe plotted in dB is close to a parabola, so the estimate is quite accurate.
On the left is the spectrum of one frame of a 490 Hz sinusoid with a Blackman window, showing only the region around the peak. The blue dots are the DFT bins, the three orange dots are the highest bin and its two neighbours, the dashed green line is the parabola through them, the solid green line is its vertex, and the dashed orange line is the true frequency. On the right is the error for each window length M, with the dashed orange line at 0.05 Hz.
The exercise asks for window lengths of the form M = 100k + 1, trying k = 1, 2, 3 and so on, with N the smallest power of 2 larger than M, and for the first M whose error is below 0.05 Hz. Drag k and the error in the right-hand figure does not fall steadily. At M = 601, N = 1024 and the error is 0.07 Hz; at M = 1001, N is still 1024 and the error has risen to 0.23 Hz; at M = 1101, N becomes 2048 and the error falls to 0.037 Hz. The reason is that the quality of the parabola fit depends on how many points there are across the main lobe. A larger M makes the main lobe narrower, and if N stays the same there are fewer points on it, so the three points are relatively further from the vertex and the fit is worse; when N doubles, the points become dense again.
The three test cases of the exercise: sine-490.wav gives 489.963 Hz at M = 1101 and N = 2048, an error of 0.037 Hz; sine-1000.wav also needs M = 1101 and gives 1000.020 Hz; sine-200.wav needs M = 1201 and gives 200.038 Hz. The frequencies differ by a factor of ten but the required M is about the same, because the error depends on where the peak falls between two bins, not much on the frequency itself.
0.05 Hz near 490 Hz is 0.18 cents. E3 mentioned that the ear can tell about 5 cents, so a 489.963 Hz sinusoid played next to the original 490 Hz sounds the same.
Implementation
dftAnal(x1, w, N) is what E4’s stftAnal does for each frame: window one frame, zero-pad to N, take the DFT, and return the magnitude spectrum in dB and the phase spectrum. The frame is centred at 0.5 s:
import math
import numpy as np
from scipy.signal import get_window
from smstools.models import dftModel as DFT
from smstools.models import utilFunctions as UF
def min_freq_est_err(input_file, f):
window = 'blackman'
t = -40
fs, x = UF.wavread(input_file)
centre = int(0.5 * fs)
k = 1
while True:
M = 100 * k + 1
N = int(2 ** math.ceil(math.log2(M)))
w = get_window(window, M)
hM1 = (M + 1) // 2
hM2 = M // 2
mX, pX = DFT.dftAnal(x[centre - hM1:centre + hM2], w, N)
ploc = UF.peakDetection(mX, t)
iploc, ipmag, ipphase = UF.peakInterp(mX, pX, ploc)
f_est = fs * iploc[0] / N
if abs(f_est - f) < 0.05:
return f_est, M, N
k += 1
The file holds a single sinusoid, so there is only one peak above −40 dB and iploc[0] is taken directly.
Connecting peaks into tracks
The peaks of one frame form a list, with a frequency, magnitude and phase for each. The next frame has its own list. The sinusoidal model matches the two lists: two peaks whose frequencies line up count as the same line, called a track. Once a sound has been analysed, each track is a sinusoid whose frequency and amplitude change over time, and generating these sinusoids and adding them up synthesises the sound again.
The analysis is done by sms-tools’ sineModelAnal(x, fs, w, N, H, t, maxnSines, minSineDur, freqDevOffset, freqDevSlope). The first six parameters are the same as for the STFT, plus the threshold t. The remaining four are tracking parameters:
maxnSines, the maximum number of tracks kept per frame, taken in order of decreasing magnitude;minSineDur, in seconds: tracks shorter than this are removed, and 0 removes nothing;freqDevOffsetandfreqDevSlope: for a peak to join a track from the previous frame, the frequency difference has to be below freqDevOffset + freqDevSlope × frequency. Higher frequencies are allowed a larger deviation, because their tracks wobble more anyway.
It returns three 2-D arrays, frequency, magnitude and phase, with one row per frame and one column per track, and 0 where there is no track.
Two chirps close together
A chirp is a sinusoid whose frequency changes continuously over time. chirp-150-190-linear.wav holds two of them, one rising from 150 Hz to 1400 Hz and the other from 190 Hz to 1440 Hz, both over 2 seconds and always 40 Hz apart. The exercise fixes the Blackman window, t = −80 and H = 128, and only M is to be chosen, so that the mean error of both tracks is below 2 Hz.
The upper figure is the tracking result: the two dashed lines are the true frequencies, the blue dots are the two tracks returned by sineModelAnal, and the first and last 20 frames are not counted in the error. The lower figure is the spectrum of one frame; drag the slider to change the frame. The grey dots are the peaks above −80 dB, the blue dots the two chosen ones, the blue bar is the main-lobe width for this M, and the orange bar is 40 Hz. The chirp in the animation is generated from the file’s parameters rather than taken from the file itself, so the error values differ from the file results given below, but the trend is the same.
At M = 1023, the main lobe of the Blackman window is 6 × 44100 / 1023 = 259 Hz wide, far wider than 40 Hz, the two peaks merge into one, and the other track can only attach to a side lobe; the mean errors are 13.7 and 528.5 Hz. At M = 3071 the main lobe is 86 Hz wide, the two maxima are already separate, and the errors fall to 1.2 and 13.4 Hz; at M = 4095 the main lobe is 65 Hz, the errors are 0.72 and 1.30 Hz, and the target is met. The two main lobes do not have to be fully apart; the two maxima have to be, and that takes a spacing of roughly more than half the main-lobe width.
M cannot keep growing either. At M = 8191 a frame is 186 ms long; the frequency rises by 625 Hz per second, so within one frame it rises by 116 Hz, the peak is smeared flat, and the errors are back up at 16 and 25 Hz. The trade-off between frame length and time resolution from E4 appears here as separating 40 Hz on one side and keeping up with the moving frequency on the other, and M = 4095 is enough for both.
One strong, one weak
sines-440-602-hRange.wav holds two sinusoids, 440 Hz with amplitude 1 and 602 Hz with amplitude 0.002, 500 times weaker, 54 dB down. The exercise fixes M = 2047, N = 4096, H = 128, maxnSines = 2, minSineDur = 0.02 and freqDevOffset = 10; only the window and the threshold t are to be chosen.
The figure is the spectrum of one frame at 1.5 s, 0 to 1000 Hz. The dashed orange lines are 440 Hz and the threshold, the dashed green line is 602 Hz, the grey dots are the peaks above the threshold, and the blue dots are the two strongest of them, which is what remains with maxnSines = 2.
With a Hann window and a threshold of −80 dB, the peak at 602 Hz is at −58 dB, but the side lobes on either side of 440 Hz reach −38 dB and are still at −49 dB near 602 Hz, all higher than the 602 Hz peak, so the two strongest peaks are 440 Hz and a side lobe at 388 Hz to its left, and the weak one is covered. In E4’s table the side lobe of the Hann window is −31.5 dB, which relative to the −6.5 dB peak is −38 dB, falling off further from the peak. With a Blackman-Harris window the side lobes are at −92 dB, the 602 Hz peak in the spectrum is at −60 dB with no other peak near it, and the two strongest are 440 and 602.
The threshold has to be below −60 dB for the 602 Hz peak to count as a peak; −60 just misses it, while −70 and −80 both work. It cannot be too low either: dragged below −110, the floating-point noise is picked up as peaks too.
A problem in the current smstools
By the analysis above, a Blackman-Harris window with t = −80 should be the answer. But with the 2025 version of smstools, sineModelAnal returns a second track that is all zeros, and the mean errors are 0.005 and 602 Hz. The cause is in the tracking step. The file starts with a short fade-in, and in the first few frames the spectrum holds a dozen spurious peaks besides 440 Hz. They are all made into new tracks and occupy positions 1 to 12. When the 602 Hz track appears, it lands in position 5. sineModelAnal keeps all tracks internally and only truncates to the first maxnSines when writing the output, so the output only ever holds positions 0 and 1, the 602 Hz track stays in position 5, and it never shows up.
The original sms-tools cut the track list down to maxnSines after tracking each frame, before passing it to the next frame, so the spurious peaks from the fade-in were quickly pushed out and 602 Hz could attach to position 1. A small loop of one’s own restores that behaviour:
from smstools.models import sineModel as SM
def sine_model_anal(x, fs, w, N, H, t, maxnSines, minSineDur, freqDevOffset, freqDevSlope):
hM1 = (w.size + 1) // 2
hM2 = w.size // 2
x = np.concatenate([np.zeros(hM2), x, np.zeros(hM2)])
w = w / np.sum(w)
pin = hM1
pend = x.size - hM1
tfreq = np.array([])
rows = []
while pin < pend:
mX, pX = DFT.dftAnal(x[pin - hM1:pin + hM2], w, N)
ploc = UF.peakDetection(mX, t)
iploc, ipmag, ipphase = UF.peakInterp(mX, pX, ploc)
tfreq, tmag, tphase = SM.sineTracking(fs * iploc / N, ipmag, ipphase, tfreq, freqDevOffset, freqDevSlope)
tfreq = tfreq[:maxnSines]
row = np.zeros(maxnSines)
row[:tfreq.size] = tfreq
rows.append(row)
pin += H
return SM.cleaningSineTracks(np.array(rows), round(fs * minSineDur / H))
This function returns only the frequencies, which is all freq_tracker_error needs. With it, the Blackman-Harris window at t = −80 gives mean errors of 0.005 and 0.019 Hz; the Blackman window gives 0.011 and 1.58 Hz, just within the target; the Hann window gives 0.02 and 212 Hz and the Hamming window 0.03 and 64 Hz, neither of which works. In part two of the exercise, both versions give the same result at M = 4095, but at M = 5001 they differ: the original behaviour gives 0.94 and 1.85 Hz, while the current version has an error of 170 Hz on the second track.
A complex signal
multiSines.wav is 6 seconds long, in four sections separated by silence. Each section has six to nine sinusoids, some at fixed frequencies and some chirps that cross each other, with a few weak ones more than 20 dB below the strong ones, and each section starts abruptly. The exercise asks for all the parameters of sineModelAnal, such that the resynthesised sound cannot be told apart from the original. The synthesis parameters Ns = 512 and H = 128 are fixed.
The figure is the spectrogram from 0 to 2000 Hz, with the analysed tracks in orange. Four parameter sets can be switched between, and the button plays the original. The resynthesis has to be listened to in the notebook, where the last code cell runs both the analysis and the synthesis.
My choice is a Blackman-Harris window, M = 2047, N = 4096, t = −90, minSineDur = 0.02, maxnSines = 30, freqDevOffset = 10 and freqDevSlope = 0.001.
- The window and the threshold go together. The strong sinusoids are around −18 dB and the weak ones around −40 dB, so the threshold has to be below −45 dB. The Hamming window’s side lobes are at −43 dB, which relative to a −18 dB peak is −61 dB, so a threshold of −60 picks up side lobes as peaks, and the first parameter set shows a crowd of extra tracks. The Blackman-Harris side lobes are below −110 dB, so the threshold can go down to −90, all the weak sinusoids are found, and not a single side lobe gets in;
- M has to separate the two closest frequencies. In one section two sinusoids are only 43 Hz apart; at M = 2047 the Blackman-Harris main lobe is 172 Hz wide and the two maxima are just about separate, while the third parameter set lowers M to 1023, the main lobe is 345 Hz, and the two merge into one. M cannot be longer either, because each section starts abruptly and a longer frame blurs the attack;
- minSineDur = 0.02 removes tracks shorter than 20 ms. The fourth parameter set sets it to 0, and fragments a few frames long appear at the start and end of each section, which are spurious peaks at the attacks and at the edges of the silences;
- freqDevOffset = 10 requires the frequency of neighbouring frames to differ by less than 10 Hz to join one track. The chirps rise by a few hundred Hz per second, less than 1 Hz within one 2.9 ms frame, so they connect; where two chirps cross, the 10 Hz limit keeps each on its own path instead of swapping at the crossing.
Summary
- A peak is a bin that is higher than both neighbours and above the threshold. A parabola through the highest bin and its two neighbours puts the peak between bins;
- The parabola fit depends on how many points there are across the main lobe; with N fixed, a larger M means fewer points, so the error does not fall steadily with M;
- The sinusoidal model connects peaks of neighbouring frames whose frequencies line up into tracks, and each track is a sinusoid changing over time;
- Separating two close frequencies needs a long window; following a fast-changing frequency needs a short one;
- A weak frequency next to a strong one needs a window with low side lobes, and a threshold below the weak peak;
- The current
sineModelAnaldoes not cut the track list to maxnSines before the next frame, so a weak track may never appear; a loop of one’s own works around it.
Exercise source: E5-Sinusoidal-model.ipynb
The multiSines.wav played in this post comes from the sounds directory of sms-tools-materials, by Xavier Serra, CC BY 4.0.