scipy.signal.

sosfiltfilt#

scipy.signal.sosfiltfilt(sos, x, axis=-1, padtype='odd', padlen=None)[原始碼]#

使用級聯二階區段的前向-後向數位濾波器。

請參閱 filtfilt 以取得關於此方法的更完整資訊。

參數:
sosarray_like

二階濾波器係數陣列,必須具有形狀 (n_sections, 6)。每一列對應一個二階區段,前三列提供分子係數,後三列提供分母係數。

xarray_like

要被濾波的資料陣列。

axisint, 選用

要套用濾波器的 x 軸。預設值為 -1。

padtypestr 或 None, 選用

必須是 ‘odd’、‘even’、‘constant’ 或 None。這決定了用於填充訊號的擴展類型,濾波器將應用於該訊號。如果 padtype 為 None,則不使用填充。預設值為 ‘odd’。

padlenint 或 None, 選用

在套用濾波器之前,在 axis 的兩端擴展 x 的元素數量。此值必須小於 x.shape[axis] - 1padlen=0 表示不填充。預設值為

3 * (2 * len(sos) + 1 - min((sos[:, 2] == 0).sum(),
                            (sos[:, 5] == 0).sum()))

結尾的額外減法試圖補償原點的極點和零點(例如,對於奇數階濾波器),以產生與使用 scipy.signal 函數建置的二階區段濾波器的 filtfilt 等效的 padlen 估計值。

回傳值:
yndarray

已濾波的輸出,形狀與 x 相同。

註解

在版本 0.18.0 中新增。

範例

>>> import numpy as np
>>> from scipy.signal import sosfiltfilt, butter
>>> import matplotlib.pyplot as plt
>>> rng = np.random.default_rng()

建立一個有趣的訊號來濾波。

>>> n = 201
>>> t = np.linspace(0, 1, n)
>>> x = 1 + (t < 0.5) - 0.25*t**2 + 0.05*rng.standard_normal(n)

建立一個低通 Butterworth 濾波器,並使用它來濾波 x

>>> sos = butter(4, 0.125, output='sos')
>>> y = sosfiltfilt(sos, x)

為了比較,使用 sosfilt 應用一個 8 階濾波器。濾波器使用 x 的前四個值的平均值初始化。

>>> from scipy.signal import sosfilt, sosfilt_zi
>>> sos8 = butter(8, 0.125, output='sos')
>>> zi = x[:4].mean() * sosfilt_zi(sos8)
>>> y2, zo = sosfilt(sos8, x, zi=zi)

繪製結果。請注意 y 的相位與輸入匹配,而 y2 具有顯著的相位延遲。

>>> plt.plot(t, x, alpha=0.5, label='x(t)')
>>> plt.plot(t, y, label='y(t)')
>>> plt.plot(t, y2, label='y2(t)')
>>> plt.legend(framealpha=1, shadow=True)
>>> plt.grid(alpha=0.25)
>>> plt.xlabel('t')
>>> plt.show()
../../_images/scipy-signal-sosfiltfilt-1.png