Search code examples
pythonnumpymachine-learningfilterbutterworth

How to implement a butterworth filter


I am trying to implement a butterworthfilter with python

The data are from a CSV-File, which is called Samples.csv and looks like this

998,4778415
1009,209592
1006,619094
1001,785406
993,9426543
990,1408991
992,736118
995,8127334
...

The column calls Euclidian Norm. The range of the data are from 0 to 1679.286158 and there are 1838 rows.

This is the code I use:

from scipy.signal import filtfilt
from scipy import stats

import csv
import pandas as pd
import numpy as np

import matplotlib.pyplot as plt
import scipy
def plot():
    data=pd.read_csv('Samples.csv',sep=";", decimal=",")
    sensor_data=data[['Euclidian Norm']]
    sensor_data=np.array(sensor_data)
    
    time=np.linspace(0,1679.286158,1838)
    plt.plot(time,sensor_data)
    plt.show()
    
    filtered_signal=bandPassFilter(sensor_data)
    plt.plot(time,sensor_data)
    plt.show()
    
    
def bandPassFilter(signal):
    fs = 4000.0
    lowcut=20.0
    highcut=50.0

    nyq=0.5*fs
    low=lowcut/nyq
    high=highcut/nyq

    order =2

    b,a=scipy.signal.butter(order,[low,high],'bandpass',analog=False)

    y=scipy.signal.filtfilt(b,a,signal,axis=0)

    return(y)

plot()

My problem is that nothing changes in my data. It doesn't filtered my data. The graph of the filtered data is the same like the source data. Does anyone know what could be wrong?

The first graph is the source data and the second graph is the filtered graph, which looks like the same graph to me.

The first graph is the source data and the second graph is the filtered graph


Solution

  • I can't comment yet.

    You're never using filtered_signal and plot with the same arguments twice.

    Here`s one of my implementations with added interpolation, very similar to yours:

    def butterFit(data, freq, order=2):
        ar = scipy.signal.butter(order, freq)       # Gets params for filttilt
        return spfilter.filtfilt(ar[0], ar[1], data)
    
    
    def plotFilteredSplines(timeframe, data, amount_points):
        # Generate evenly spread indices for the data points.
        indices = np.arange(0, len(data), amount_points)
    
        cutoff_freq = 2 / (2/10 * len(timeframe))
        # Reshape the data with butter :)
        data = butterFit(data, cutoff_freq)
    
        # Plot Fitlered data
        plt.plot(timeframe, data, '-.')
        interpol_x = np.linspace(timeframe[0], timeframe[-1], 100)
    
        # Get the cubic spline approx function
        interpolation = sp.interpolate.interp1d(timeframe, data, kind='cubic')
    
        # Plot the interpolation over the extended time frame.
        plt.plot(interpol_x, interpolation(interpol_x), '-r')
    

    enter image description here