封装SyPy筛选器

通过封装来自两个库模块的几个函数,我们可以清楚地了解数字滤波器是什么样子的。此外,通过将__init__拆分成两个部分,可以动态重置过滤器的创建参数和内部条件。

选择 | 换行 | 行号
  1.  
  2. """ Encapulates a scipy filter. Given type, freq and order,
  3.     create the coefficients and internal conditions, etc."""
  4. import scipy.signal.filter_design as fd
  5. import scipy.signal.signaltools as st
  6. _filterTypeDict = {'elliptic':'ellip', 'Butterworth':'butter',
  7.                     'Chebyshev I':'cheby1', 'Chebyshev II':'cheby2',
  8.                     'Bessel':'bessel'}
  9. DefaultFilterType = 'Butterworth'
  10. DefaultFilterOrder = 2
  11. DefaultFilterFreq = 0.1
  12.  
  13. class FilterObject(object):
  14.     def __init__(self, channelNumber, nTaps, freq,
  15.                  bType='lowpass', fType="butter", output='ba'):
  16.         self.channelNumber = channelNumber
  17.         self.InitFilter(nTaps, freq, bType, fType, output)
  18.     def InitFilter(self, nTaps, freq, bType, fType, output):
  19.         print "taps = %d: freq = %f" % (nTaps, freq)
  20.         b, a = fd.iirfilter(nTaps, freq, btype=bType, ftype=fType, output=output)
  21.         self.b, self.a = b, a
  22.         self.ic = st.lfiltic(b, a, (0.0,))
  23.     def Filter(self, dataArray):
  24.         resTuple = st.lfilter(self.b, self.a, dataArray, zi=self.ic)
  25.         self.ic = resTuple[-1]
  26.         return resTuple[0]
  27.  
  28. if __name__ == "__main__":
  29.     x = (1.5, 1.4, 1.5, 1.6, 1.5, 1.4, 1.5, 1.6)
  30.     f = FilterObject(2, .05)
  31.     for a in range(20):
  32.         print f.Filter(x)
  33.  
  34.  

这是另一个很好的例子。
_filterTypeDict就是"名称损坏"的一个例子。这是一种使模块作用域变量保持半私有的方法。
当您导入myModule时
模块作用域类、函数和变量由引用
MyModule.myClass()、myModule.myFunction()、myModule.myVariable。
使用导入模块的对象时
从myModule导入*
除了_SemiPrivate变量之外,该模块中的所有名称都被放入导入模块的作用域中。它们是半私密的,因为您仍然可以
A=myModel._SemiPrivate(名称已导入到当前作用域中,并在其前面添加了模块的名称)。

标签: python

添加新评论