Implement FIR filters in Python and C

Overview

Filters are often used in signal processing from the perspective of noise reduction. Implement the simplest FIR filter in Python and C. It is assumed that the filter is evaluated based on Python and the result is incorporated into a C language-based application.

Python code

The implementation of the FIR filter using scipy is shown below. The original signal x is a random number, and the filter coefficient is calculated by scipy.signal.firwin. Compare the signal y after applying the filter by scipy and the signal d after applying the filter by solid.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#

import numpy as np
import scipy.signal
from pylab import *
import csv
import matplotlib.pyplot as plt

#x can be anything
x = np.random.rand(512)
plt.plot(x)
plt.show()

fs = 512 #Sampling frequency
nyq = fs / 2.0  #Nyquist frequency

#Filter design
f1 = 1 / nyq      #Cutoff frequency 1
f2 = 30.0 / nyq      #Cutoff frequency 2
numtaps = 255       #Number of filter coefficients(Odd)

b = scipy.signal.firwin(numtaps, f1)                         #Low pass
#b = scipy.signal.firwin(numtaps, f2, pass_zero=False)        #High pass
#b = scipy.signal.firwin(numtaps, [f1, f2], pass_zero=False) #Bandpass

#Saving filter coefficients
with open('coeff.csv', 'w') as f:
    writer = csv.writer(f, lineterminator='\n') #Line feed code (\n) is specified
    writer.writerow(b)

#FIR filter by scipy
y = scipy.signal.lfilter(b, 1, x)     
               
#FIR filter by solid writing
d = np.zeros(fs)

for i in range(len(x)):
    d[i] = 0
    for j in range(len(b)):
        if(i-j)>=0:
            d[i] += b[j]*x[i-j]
    
plt.plot(y,color='r')
plt.plot(d,color='b')
plt.show()

Original signal

x.png

After applying the filter (red: y, blue: d)

low.png

C code

If the solid result on Python is correct, drop it into C language code. It's a little rough, but b stores an array of coeff.csv generated by Python code. Since it is saved in csv format, if you open it with a text editor etc., you can copy and paste it as it is.


    int sampleRate = 512

    x= //Although it is rough, describe x appropriately

    float* filteredData = (float*)malloc(sizeof(float)*512);
    
    float b[] = {} //Rough, but coeff written in Python.Insert the contents of csv in parentheses
    
    for(int i=0;i<sampleRate;i++){
        float d = 0;
        for(int j=0; j<(sizeof b)/(sizeof b[0]); j++){
            if((i-j)>=0){
                d += b[j]*x[i-j];
            }
        }
        filteredData[i]=d;
    }

    free(filteredData)

It's very simple, but it's just a memorandum, so forgive me, how do you implement an FIR filter? If it helps someone who says.

Recommended Posts

Implement FIR filters in Python and C
Write O_SYNC file in C and Python
Implement Enigma in python
Implement recommendations in Python
Implement XENO in python
Next Python in C
Implement sum in Python
C API in Python 3
Implement Traceroute in Python 3
Extend python in C ++ (Boost.NumPy)
Write Pandoc filters in Python
Implement naive bayes in Python 3.3
Implement ancient ciphers in python
Binary search in Python / C ++
Stack and Queue in Python
Implement Redis Mutex in Python
Implement extension field in Python
Implement fast RPC in Python
Implement method chain in Python
Implement Dijkstra's Algorithm in python
Implement Slack chatbot in Python
Unittest and CI in Python
Implement Depth-First Search (DFS) and Breadth-First Search (BFS) in python
Consider If Programming Was An Anime in Python and C
Object-oriented in C: Refactored "○ ✕ game" and ported it to Python
Implement stacking learning in Python [Kaggle]
MIDI packages in Python midi and pretty_midi
Difference between list () and [] in Python
Difference between == and is in python
View photos in Python and html
Sorting algorithm and implementation in Python
ABC166 in Python A ~ C problem
Manipulate files and folders in Python
About dtypes in Python and Cython
Implement the Singleton pattern in Python
Assignments and changes in Python objects
Check and move directories in Python
Ciphertext in Python: IND-CCA2 and RSA-OAEP
Hashing data in R and Python
Solve ABC036 A ~ C in Python
How to wrap C in Python
Function synthesis and application in Python
Export and output files in Python
Quickly implement REST API in Python
Reverse Hiragana and Katakana in Python2.7
Solve ABC037 A ~ C in Python
Reading and writing text in Python
[GUI in Python] PyQt5-Menu and Toolbar-
Write C unit tests in Python
Create and read messagepacks in Python
Overlapping regular expressions in Python and Java
I tried to implement PLSA in Python
Differences in authenticity between Python and JavaScript
Notes using cChardet and python3-chardet in Python 3.3.1.
Solve ABC175 A, B, C in Python
Modules and packages in Python are "namespaces"
Avoid nested loops in PHP and Python
Differences between Ruby and Python in scope
Implement __eq__ etc. generically in Python class
I tried to implement permutation in Python
Implement and understand union-find trees in Go