By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
431,991 Members | 1,737 Online
Bytes IT Community
Submit an Article
Got Smarts?
Share your bits of IT knowledge by writing an article on Bytes.

Encapsulating a SyPy filter

bartonc
Expert 5K+
P: 6,596
By encapsulating just a few fuctions from two library modules, we get a clear picture of what a digital filter looks like. Also, by splitting __init__ into two section, the filter's creation parameters and internal condition can be reset on the fly.

Expand|Select|Wrap|Line Numbers
  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.  
Here's another good example.

_filterTypeDict is an example of "name mangling". This is a way to keep module scope variables semi-private.
When you import myModule
module scope classes, functions and variables are referenced by
myModule.myClass(), myModule.myFunction(), myModule.myVariable, respectively.
When you import the object of a module with
from myModule import *
all the names in that module are put into the scope of the importing module except _semiprivate variables. They are semi-private because you can still do
a = myModule._semiprivate (the name has been imported into the current scope with the name of the module prepended onto it).
Nov 23 '06 #1
Share this Article
Share on Google+