嗯,使用滤波器,您始终可以在信号失真和去除不需要的频率之间进行折衷。过滤后总会有某种信号残留,具体取决于滤波器的衰减系数。如果指定为陷波滤波器,巴特沃斯滤波器可以具有几乎 100% 的衰减。这是使用巴特沃斯滤波器的效果:
这显示了 50 Hz 的原始信号,目标是如果过滤器足够好,过滤后我们应该看不到任何信号。然而,在应用带宽为 15 Hz 的二阶巴特沃斯滤波器后,我们确实看到仍然有一些信号,尤其是在信号的开头和结尾,这是由于滤波器失真造成的。
滤波器的频率响应在频域(幅度和相位)中看起来像这样。
所以虽然相位变化平滑,但巴特沃斯滤波器幅度的“陷波”效应也是平滑的。
另一方面,iirnotch 滤波器可以在感兴趣的频率上单击一次,但是为了限制失真,它不能达到 100% 衰减。
这是使用 Q = 30 的 iirnotch 滤波器进行滤波前后的信号
和滤波器频率响应:
改变 Q 将改变 50 Hz 处的衰减水平和失真。我认为总体而言,如果您的噪声接近或与感兴趣的信号重叠,则使用 iirnotch 是一个好主意,否则Butterwoth 可能是更好的选择。
这是数字的代码:
from scipy.signal import filtfilt, iirnotch, freqz, butter
from scipy.fftpack import fft, fftshift, fftfreq
import numpy as np
from matplotlib import pyplot
def do_fft(y, fs):
Y = fftshift(fft(y, 2 ** 12))
f = fftshift(fftfreq(2 ** 12, 1 / fs))
return f, Y
def make_signal(fs, f0, T=250e-3):
# T is total signal time
t = np.arange(0, T, 1 / fs)
y = np.sin(2 * np.pi * f0 * t)
return t, y
def make_plot():
fig, ax = pyplot.subplots(1, 2)
ax[0].plot(t, y)
ax[0].plot(t, y_filt)
ax[0].set_title('Time domain')
ax[0].set_xlabel('time [seconds]')
ax[1].plot(f, abs(Y))
ax[1].plot(f, abs(Y_filt))
ax[1].set_title('Frequency domain')
ax[1].set_xlabel('Freq [Hz]')
# filter response
fig, ax = pyplot.subplots(1, 2)
ax[0].plot(filt_freq, abs(h))
ax[0].set_title('Amplitude')
ax[0].set_xlim([0, 200])
ax[0].set_xlabel('Freq [Hz]')
ax[1].plot(filt_freq, np.unwrap(np.angle(h)) * 180 / np.pi)
ax[1].set_title('Phase')
ax[1].set_xlim([0, 200])
ax[1].set_xlabel('Freq [Hz]')
pyplot.show()
fs = 1000
f0 = 50
t, y = make_signal(fs=fs, f0=f0)
f, Y = do_fft(y, fs=1000)
# Filtering using iirnotch
w0 = f0/(fs/2)
Q = 30
b, a = iirnotch(w0, Q)
# filter response
w, h = freqz(b, a)
filt_freq = w*fs/(2*np.pi)
y_filt = filtfilt(b, a, y)
f, Y_filt = do_fft(y_filt, fs)
make_plot()
w0 = [(f0-15)/(fs/2), (f0+15)/(fs/2)]
b, a = butter(2, w0, btype='bandstop')
w, h = freqz(b, a)
filt_freq = w*fs/(2*np.pi)
y_filt = filtfilt(b, a, y)
f, Y_filt = do_fft(y_filt, fs)
make_plot()