|
|
# -*- coding: utf-8 -*-
|
|
|
"""
|
|
|
Created on Tue Nov 13 15:53:23 2012
|
|
|
|
|
|
@author: pedroluizcoelhorodrigues
|
|
|
"""
|
|
|
import numpy as np
|
|
|
from bin16 import *
|
|
|
|
|
|
class Filter_Coefficients():
|
|
|
"""List of coefficients of a IIR filter of order 2"""
|
|
|
def __init__(self,a0=0,a1=0,a2=0,b0=0,b1=0,b2=0):
|
|
|
self.b0 = b0
|
|
|
self.b1 = b1
|
|
|
self.b2 = b2
|
|
|
self.a0 = a0
|
|
|
self.a1 = a1
|
|
|
self.a2 = a2
|
|
|
|
|
|
class Filter(object):
|
|
|
"""Basic Filter of Order 2"""
|
|
|
|
|
|
def __init__(self,Coefficients,x1=0,x2=0,y1=0,y2=0):
|
|
|
self.Coefficients = Coefficients
|
|
|
self.x1 = x1
|
|
|
self.x2 = x2
|
|
|
self.y1 = y1
|
|
|
self.y2 = y2
|
|
|
|
|
|
def print_coefficients(self):
|
|
|
print 'a0 = ', self.Coefficients.a0
|
|
|
print 'a1 = ', self.Coefficients.a1
|
|
|
print 'a2 = ', self.Coefficients.a2
|
|
|
print 'b0 = ', self.Coefficients.b0
|
|
|
print 'b1 = ', self.Coefficients.b1
|
|
|
print 'b2 = ', self.Coefficients.b2, "\n"
|
|
|
|
|
|
def convolve(self,input):
|
|
|
|
|
|
B = np.array([self.Coefficients.b0,self.Coefficients.b1,self.Coefficients.b2])
|
|
|
A = np.array([self.Coefficients.a1,self.Coefficients.a2])
|
|
|
|
|
|
y = np.zeros(len(input))
|
|
|
y[0] = round(1.0/(self.Coefficients.a0) * (np.dot(B,np.array([input[0],self.x1,self.x2])) - np.dot(A,np.array([self.y1,self.y2]))))
|
|
|
y[0] = trunc16(y[0])
|
|
|
y[1] = round(1.0/(self.Coefficients.a0) * (np.dot(B,np.array([input[1],input[0],self.x1])) - np.dot(A,np.array([y[0],self.y1]))))
|
|
|
y[1] = trunc16(y[1])
|
|
|
|
|
|
for j in range(2,len(input)):
|
|
|
y[j] = trunc16(round(1.0/(self.Coefficients.a0) * (np.dot(B,np.array([input[j],input[j-1],input[j-2]])) - np.dot(A,np.array([y[j-1],y[j-2]])))))
|
|
|
|
|
|
self.x1 = input[j]
|
|
|
self.x2 = input[j-1]
|
|
|
self.y1 = y[j]
|
|
|
self.y2 = y[j-1]
|
|
|
|
|
|
return y
|
|
|
|
|
|
def reset(self):
|
|
|
self.x1 = 0
|
|
|
self.x2 = 0
|
|
|
self.y1 = 0
|
|
|
self.y2 = 0
|
|
|
|
|
|
def impulsive_response(self, N):
|
|
|
delta = np.zeros(N)
|
|
|
delta[0] = 1
|
|
|
return self.convolve(delta)
|
|
|
|
|
|
class FilterGlobal(object):
|
|
|
"""Global filter with other basic filters (of order 2) in cascade"""
|
|
|
def __init__(self,Filters):
|
|
|
self.Filter = Filters
|
|
|
|
|
|
def convolve(self,x):
|
|
|
y = np.zeros(len(x))
|
|
|
y = self.Filter[0].convolve(x)
|
|
|
if len(self.Filter) > 1:
|
|
|
for j in range(1,len(self.Filter)):
|
|
|
y = self.Filter[j].convolve(y)
|
|
|
return y
|
|
|
|
|
|
def impulsive_response(self, N):
|
|
|
delta = np.zeros(N)
|
|
|
delta[0] = 1
|
|
|
return self.convolve(delta)
|
|
|
|
|
|
def reset(self):
|
|
|
for j in range(len(self.Filter)):
|
|
|
self.Filter[j].reset()
|
|
|
|