swharden / SWHarden.com

The personal website of Scott W Harden
https://swharden.com
MIT License
4 stars 0 forks source link

new favorite bandpass method in python #8

Closed swharden closed 1 year ago

swharden commented 1 year ago

Update old related pages to use this method

signal = # data to be smoothed
sample_rate = # points per second
poles = 6 # larger is sharper frequency cutoff

freq_low = 1 # Hz
freq_high = 30 # Hz
freq_edges= [freq_low , freq_high ]

import scipy.signal
sos = scipy.signal.butter(poles, freq_edges, 'bandpass', fs=sample_rate, output='sos')
smooth = scipy.signal.sosfilt(sos, signal)
def bandpass(ys, sample_rate, low, high):
    sos = scipy.signal.butter(6, [low, high], 'bandpass',
                              fs=sample_rate, output='sos')
    return scipy.signal.sosfilt(sos, ys)

def lowpass(ys, sample_rate, cutoff):
    sos = scipy.signal.butter(6, cutoff, 'lowpass',
                              fs=sample_rate, output='sos')
    return scipy.signal.sosfilt(sos, ys)

def highpass(ys, sample_rate, cutoff):
    sos = scipy.signal.butter(6, cutoff, 'highpass',
                              fs=sample_rate, output='sos')
    return scipy.signal.sosfilt(sos, ys)

https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.sosfilt.html

swharden commented 1 year ago

Currently https://swharden.com/blog/2020-09-23-signal-filtering-in-python/ recommends scipy.signal.filtfilt but the docs https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.filtfilt.html say the following:

The function sosfiltfilt (and filter design using output='sos') should be preferred over filtfilt for most filtering tasks, as second-order sections have fewer numerical problems.

swharden commented 1 year ago

b8a42228cec60155539b4d8c8154c080f7d24f8c