def test_subpixel(fig=None): np.random.seed(2019) ims = np.random.rand(40, )**2 + 1e1 smooth_ims = smoothImage(ims) mpos = peak_local_max(smooth_ims, min_distance=3).flatten() subpos, subval = subpixelmax(smooth_ims, mpos) np.testing.assert_array_almost_equal( subpos, np.array([34.48945739, 19.7971219, 14.04429215, 7.17665281]), decimal=8) np.testing.assert_array_almost_equal( subval, np.array([10.75670888, 10.46787185, 10.59470934, 10.70051573]), decimal=8) if fig: plt.figure(fig) plt.clf() plt.plot(np.arange(ims.size), ims, '.:r', label='data points') plt.plot(mpos, ims[mpos], 'om', label='integer maxima') plt.plot(subpos, subval, '.g', markersize=15, label='subpixel maxima') plt.legend(numpoints=1) plt.close('all')
def estimate_dominant_frequency(signal, sample_rate=1, remove_dc=True, fig=None): """ Estimate dominant frequency in a signal Args: signal (array): Input data sample_rate (float): Sample rate of the data remove_dc (bool): If True, then do not estimate the DC component fig (int or None): Optionally plot the estimated frequency Returns: Estimated dominant frequency """ w = np.fft.fft(signal) freqs = np.fft.fftfreq(len(signal), d=1. / sample_rate) if remove_dc: w[0] = 0 w[freqs < 0] = 0 dominant_idx = np.argmax(np.abs(w)) dominant_frequency = freqs[dominant_idx] if 0 < dominant_idx < freqs.size / 2 - 1: dominant_idx_subpixel, _ = subpixelmax(np.abs(w), [dominant_idx]) dominant_frequency = np.interp(dominant_idx_subpixel, np.arange(freqs.size), freqs)[0] if fig: plt.figure(fig) plt.clf() plt.plot(freqs, np.abs(w), '.b') plt.xlabel('Frequency') plt.ylabel('Abs of fft') plot_vertical_line(dominant_frequency, label='Dominant frequency') return dominant_frequency