<jupyter_start><jupyter_text>STFT (Short Time Fourier Transform) testcf) https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.stft.html<jupyter_code>%matplotlib inline
import matplotlib.pyplot as plt
from scipy.fftpack import fft
from scipy.signal import stft
import numpy as np
fs = 10e3  # sampling frequency (default = 10kHz)
N = 1e5
amp = 2 * 2 ** 0.5
noise_power = 0.01 * fs / 2
time = np.arange(N) / float(fs)
mod = 500 * np.cos(2 * np.pi * 0.25 * time)
carrier = amp * np.sin(2 * np.pi * 3e3 * time + mod)  # modulates around 3kHz
noise = np.random.normal(scale=np.sqrt(noise_power),
                         size=time.shape)
noise *= np.exp(-time / 5)  # exponentially decaying noise
x = carrier + noise
plt.plot(mod);<jupyter_output><empty_output><jupyter_text>`carrier` contians frequencies around 3kHz. The plot below doesn't look so obvious as `carrier` is perturbated by adding `mod`.<jupyter_code>fig, ax = plt.subplots()

ax.plot(np.linspace(0, fs / 2, int(N//2)),
                    np.abs(fft(carrier)[0:int(N//2)]))
ax.set_xlabel('Frequency [Hz]');<jupyter_output><empty_output><jupyter_text>Exponentially decaying noise is also added to `carrier`.<jupyter_code>plt.plot(noise);<jupyter_output><empty_output><jupyter_text>Apply STFTnumber of samples = 100000  `nperseg` = 1000  `noverlap` = `nperseg` // 2 = 500  `nfft` = `nperseg`One can see from below that the main frequency evolved around 3kHz. In addition, the plot contains white noise evenly distributed in the frequency domain up until around 2 second. This is because white noise theoretically carries all frequencies.<jupyter_code>f, t, Zxx = stft(x, fs, nperseg=1000)

fig, ax = plt.subplots()
ax.pcolormesh(t, f, np.abs(Zxx), vmin=0, vmax=amp)
ax.set_title('STFT Magnitude')
ax.set_ylabel('Frequency [Hz]')
ax.set_xlabel('Time [sec]');
print(f.shape)
print(t.shape)
print(Zxx.shape)<jupyter_output>(501,)
(201,)
(501, 201)
StarcoderdataJupyterStructuredCleanDedup