去趋势或过滤锯齿信号(Python)
我试图通过使用filfilt滤波器消除信号的趋势(锯齿),但效果不好。这是 当我使用巴特沃斯过滤器时去趋势或过滤锯齿信号(Python),python,numpy,filter,scipy,trend,Python,Numpy,Filter,Scipy,Trend,我试图通过使用filfilt滤波器消除信号的趋势(锯齿),但效果不好。这是 当我使用巴特沃斯过滤器时 b3, a3 = sg.butter(1, 0.045) y3 = sg.filtfilt(b3, a3, core_3.temp) b7, a7 = sg.butter(1, 0.030) y7 = sg.filtfilt(b7, a7, core_7.temp) 结果是 正如你所看到的,对于3太赫兹信号,有一种锯切的趋势。在21:45信号有一个扰动(我想研究那个扰动)。在
b3, a3 = sg.butter(1, 0.045)
y3 = sg.filtfilt(b3, a3, core_3.temp)
b7, a7 = sg.butter(1, 0.030)
y7 = sg.filtfilt(b7, a7, core_7.temp)
结果是
正如你所看到的,对于3太赫兹信号,有一种锯切的趋势。在21:45信号有一个扰动(我想研究那个扰动)。在7太赫兹时可以清楚地观察到这种扰动。在3太赫兹时,观察到锯齿的中断。所以,我需要去趋势或过滤这个信号。我试着使用了一个
filter
过滤器,但我不知道使用scipy.detrend
过滤或简单的去趋势处理对这个信号都没有好处。第一个问题是这种趋势有点周期性。第二个问题是周期性不是平稳的。我相信线性方法不能解决这个问题
我建议你做以下几点:
import numpy as np
import scipy.signal as sps
import matplotlib.pyplot as plt
np.random.seed(123)
# create an example signal
x = []
ofs = 3.4
slope = 0.002
for t in np.linspace(0, 100, 1000):
ofs += slope
x.append(np.sin(t*2) * 0.1 + ofs)
if x[-1] > 4:
ofs =3.2
slope = np.random.rand() * 0.003 + 0.002
x = np.asarray(x)
plt.plot(x, label='original')
# detect and remove jumps
jmps = np.where(np.diff(x) < -0.5)[0] # find large, rapid drops in amplitdue
for j in jmps:
x[j+1:] += x[j] - x[j+1]
plt.plot(x, label='unrolled')
# detrend with a low-pass
order = 200
x -= sps.filtfilt([1] * order, [order], x) # this is a very simple moving average filter
plt.plot(x, label='detrended')
plt.legend(loc='best')
plt.show()
将numpy导入为np
将scipy.signal作为sps导入
将matplotlib.pyplot作为plt导入
np.随机种子(123)
#创建一个示例信号
x=[]
ofs=3.4
斜率=0.002
对于np.linspace中的t(0,100,1000):
ofs+=斜率
x、 附加(np.sin(t*2)*0.1+ofs)
如果x[-1]>4:
ofs=3.2
斜率=np.random.rand()*0.003+0.002
x=np.asarray(x)
plt.绘图(x,标签='原始')
#检测并删除跳转
jmps=np.where(np.diff(x)<-0.5)[0]#在振幅中找到大而快速的下降
对于jmps中的j:
x[j+1::]+=x[j]-x[j+1]
plt.plot(x,label='unrolled')
#用低通滤波器衰减
订单=200
x-=sps.filtfilt([1]*order,[order],x)#这是一个非常简单的移动平均滤波器
plt.plot(x,label='detrended')
plt.图例(loc='best')
plt.show()
谢谢,只是一个问题,当你在代码中写
+=
或-=
时意味着什么?我知道了,正好是:x=x+1(x+=1)。不过有一点不同:x+=
修改现有变量x
,但x=
为变量指定一个新对象。在这里,这并不重要,但在某些情况下这很重要。
import numpy as np
import scipy.signal as sps
import matplotlib.pyplot as plt
np.random.seed(123)
# create an example signal
x = []
ofs = 3.4
slope = 0.002
for t in np.linspace(0, 100, 1000):
ofs += slope
x.append(np.sin(t*2) * 0.1 + ofs)
if x[-1] > 4:
ofs =3.2
slope = np.random.rand() * 0.003 + 0.002
x = np.asarray(x)
plt.plot(x, label='original')
# detect and remove jumps
jmps = np.where(np.diff(x) < -0.5)[0] # find large, rapid drops in amplitdue
for j in jmps:
x[j+1:] += x[j] - x[j+1]
plt.plot(x, label='unrolled')
# detrend with a low-pass
order = 200
x -= sps.filtfilt([1] * order, [order], x) # this is a very simple moving average filter
plt.plot(x, label='detrended')
plt.legend(loc='best')
plt.show()