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.
-
-
""" Encapulates a scipy filter. Given type, freq and order,
-
create the coefficients and internal conditions, etc."""
-
import scipy.signal.filter_design as fd
-
import scipy.signal.signaltools as st
-
_filterTypeDict = {'elliptic':'ellip', 'Butterworth':'butter',
-
'Chebyshev I':'cheby1', 'Chebyshev II':'cheby2',
-
'Bessel':'bessel'}
-
DefaultFilterType = 'Butterworth'
-
DefaultFilterOrder = 2
-
DefaultFilterFreq = 0.1
-
-
class FilterObject(object):
-
def __init__(self, channelNumber, nTaps, freq,
-
bType='lowpass', fType="butter", output='ba'):
-
self.channelNumber = channelNumber
-
self.InitFilter(nTaps, freq, bType, fType, output)
-
def InitFilter(self, nTaps, freq, bType, fType, output):
-
print "taps = %d: freq = %f" % (nTaps, freq)
-
b, a = fd.iirfilter(nTaps, freq, btype=bType, ftype=fType, output=output)
-
self.b, self.a = b, a
-
self.ic = st.lfiltic(b, a, (0.0,))
-
def Filter(self, dataArray):
-
resTuple = st.lfilter(self.b, self.a, dataArray, zi=self.ic)
-
self.ic = resTuple[-1]
-
return resTuple[0]
-
-
if __name__ == "__main__":
-
x = (1.5, 1.4, 1.5, 1.6, 1.5, 1.4, 1.5, 1.6)
-
f = FilterObject(2, .05)
-
for a in range(20):
-
print f.Filter(x)
-
-
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).