pythonnumpyfilterjupyter-notebookbutterworth

How to implement a butterworth filter


I am trying to implement a butterworthfilter with python in jupyter Notebook. I wrote this code by a tutorial.

The data are from a CSV-File, it calls Samples.csv

The data in Samples.csv are like

998,4778415
1009,209592
1006,619094
1001,785406
993,9426543
990,1408991
992,736118
995,8127334
1002,381664
1006,094429
1000,634799
999,3287747
1002,318812
999,3287747
1004,427698
1008,516733
1007,964781
1002,680906
1000,14449
994,257009

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

This is the code in Jupyter:

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 doesnt 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. It looks very similar. Its like the same graph

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