def test_stft(): """Test STFT calculation""" assert_raises(ValueError, stft, 0) assert_raises(ValueError, stft, [], window='foo') assert_raises(ValueError, stft, [[]]) result = stft([]) assert np.allclose(result, np.zeros_like(result)) n_fft = 256 step = 128 for n_samples, n_estimates in ((256, 1), (383, 1), (384, 2), (511, 2), (512, 3)): result = stft(np.ones(n_samples), n_fft=n_fft, step=step, window=None) assert result.shape[1] == n_estimates expected = np.zeros(n_fft // 2 + 1) expected[0] = 1 for res in result.T: assert np.allclose(expected, np.abs(res)) assert np.allclose(expected, np.abs(res)) for n_pts, last_freq in zip((256, 255), (500., 498.)): freqs = fft_freqs(n_pts, 1000) assert freqs[0] == 0 assert np.allclose(freqs[-1], last_freq, atol=1e-1)
def _calculate_spectrogram(self): if self._x is not None: x = self._x nan_mean = np.nanmean(x) idx = np.isnan(x) x[idx] = nan_mean data = stft(x, self._n_fft, self._step, self._fs, self._window) data = np.abs(data) data = 20 * np.log10(data) if self._color_scale == 'log' else data if self._normalize: for i in range(data.shape[0]): data[i, :] -= np.mean(data[i, :]) data[i, :] /= np.std(data[i, :]) return data else: return None
def _do_spec(self, min_time, max_time): if min_time < 0: min_time = 0 if max_time - min_time > 30: step = 0.1 else: step = self.step step = (max_time - min_time) / 1000 min_samp = int(min_time * self._sr) max_samp = int(max_time * self._sr) self.xscale = step step_samp = int(step * self._sr) #if step_samp < 28: # step_samp = 28 # step = step_samp / self._sr if self._n_fft < 32: self._n_fft = 32 #self._n_fft = 512 data = stft(self._signal[min_samp:max_samp], self._n_fft, step_samp, self._sr, self._window) data = np.abs(data) data = 20 * np.log10(data) if self._color_scale == 'log' else data return data