python - 沿 N 维数组的任意轴应用初始条件的 SciPy lfilter

标签 python numpy scipy filtering

根据 SciPy 文档 lfilter :

zi : 类似数组,可选 滤波器延迟的初始条件。它是一个长度为 max(len(a),len(b))-1 的向量(或 N 维输入的向量数组)。如果 zi 为 None 或未给出,则假定初始休息。请参阅 lfiltic 了解更多信息。

以下代码调用 lfilter,并使用 lfilter_zi 传递 zi使得 zi 最后一维的长度为 max(len(a),len(b))-1。但是,它会引发错误,具体取决于应用程序的轴:

import numpy as np
import scipy.signal as sig

def apply_filter(B, A, signal, axis=-1):
   # apply filter, setting proper initial state (doesn't assume rest)
   filtered, zf = sig.lfilter(B, A, signal, 
             zi=sig.lfilter_zi(B, A) * np.take(signal, 0, axis=axis)[..., np.newaxis], axis=axis)
   return filtered

B, A = sig.butter(1, 0.5)
x = np.random.randn(12, 50)
apply_filter(B, A, x, axis=1)    # works without error
apply_filter(B, A, x, axis=0)    # raises ValueError

ValueError:初始条件的数量必须为 max([len(a),len(b)]) - 1

如何避免错误,并沿任何轴应用过滤器而不假设初始静止?

最佳答案

zi 中的初始条件必须与为 lfilter 指定的轴位于同一轴。更改此:

np.take(signal, 0, axis=axis)[..., np.newaxis]

np.take(signal, [0], axis=axis)
<小时/>

np.take(signal, 0, axis=axis)np.take(signal, [0], axis=axis) 之间的区别在于后者保留维数。例如

In [105]: signal
Out[105]: 
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])

In [106]: signal.shape
Out[106]: (3, 5)

如果我们获取来自轴 1 的第一个索引,我们将得到一个形状为 (3,) 的一维数组:

In [107]: a = np.take(signal, 0, axis=1)

In [108]: a.shape
Out[108]: (3,)

In [109]: a
Out[109]: array([ 0,  5, 10])

如果我们在 indices 参数中使用列表 [0],我们会得到一个形状为 (3, 1) 的数组:

In [110]: b = np.take(signal, [0], axis=1)

In [111]: b.shape
Out[111]: (3, 1)

In [112]: b
Out[112]: 
array([[ 0],
       [ 5],
       [10]])

关于python - 沿 N 维数组的任意轴应用初始条件的 SciPy lfilter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28683232/

相关文章:

python - python中的函数

python - numpy.random.normal() 函数的最大和最小间隔是多少?

Python:scipy/numpy 两个一维向量之间的所有对计算

python - 使用 Python 将带有附件的 XML 发送到 SOAP ws

python - 为什么代码在收到响应后不执行

python - 通过基于 Python 的守护程序在 NFS 共享上执行文件 I/O 时的特殊注意事项?

python - 用整数运算准确反射(reflect)大数和的大小

python - 在 zipapp 存档中嵌入 numpy

python - Griddata 创建坏形状 scipy

python - 如何为曲线下的区域添加阴影