Skip to content

Instantly share code, notes, and snippets.

@lukicdarkoo
Last active July 29, 2016 12:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukicdarkoo/050c415843cae0611833 to your computer and use it in GitHub Desktop.
Save lukicdarkoo/050c415843cae0611833 to your computer and use it in GitHub Desktop.
Basic implementation of FIR filter with given coefficients
'''
Basic implementation of FIR filter with given coefficients
Y[n] = sum(f(i)*g(n-i))
'''
__author__ = 'Darko Lukic'
__email__ = 'lukicdarkoo@gmail.com'
import numpy as np
import matplotlib.pyplot as plt
SAMPLE_RATE = 8192
N = 128 # Windowing
# Generated with: http://t-filter.engineerjs.com/
filter = [
38187311164.760864,
222104632565.16745,
-278907616677.3709,
-494639530286.5757,
617425373598.061,
255943274597.81885,
-64755010449.17185,
-695553688939.9774,
-271477106814.2853,
1101809427479.7473,
292604714803.50635,
-553556367022.7665,
-1329404651336.4807,
637666123638.598,
1530947087313.8647,
491084885187.5182,
-2426202180883.679,
-2392282493314.974,
6638011630752.459,
-2392282493314.974,
-2426202180883.679,
491084885187.5182,
1530947087313.8647,
637666123638.598,
-1329404651336.4807,
-553556367022.7665,
292604714803.50635,
1101809427479.7473,
-271477106814.2853,
-695553688939.9774,
-64755010449.17185,
255943274597.81885,
617425373598.061,
-494639530286.5757,
-278907616677.3709,
222104632565.16745,
38187311164.760864
]
# Convolution is used to apply filter
def convolution(input_signal, filter):
output_signal = list()
for n in xrange(0, len(input_signal) - len(filter)):
output_signal.append(0)
'''
After few experiments this method gives the best result. I mean on:
int(np.floor(len(input_signal)/len(filter)))
'''
for i in xrange(0, int(np.floor(len(input_signal)/len(filter))) * len(filter)):
output_signal[n] += filter[i%len(filter)] * input_signal[n-i]
return output_signal
# Make two sine signals frequencies of 128Hz and 256Hz
x_values = np.arange(0, N, 1)
x = np.sin((2*np.pi*x_values / 32.0)) # 32 - 256Hz
x += np.sin((2*np.pi*x_values / 64.0)) # 64 - 128Hz
Y = convolution(x, filter)
#Y = np.convolve(x, filter, 'valid')
# Plotting
_, plots = plt.subplots(3)
## Plot in time domain
plots[0].plot(x)
plots[1].plot(Y)
## Plot filtered signal in frequent domain
S = np.fft.fft(Y);
powers_all = np.abs(np.divide(S, N/2))
powers = powers_all[0:N/2]
frequencies = np.divide(np.multiply(SAMPLE_RATE, np.arange(0, N/2)), N)
plots[2].plot(frequencies, powers)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment