I am trying to filter a 2D array of dimension 19 channels x 10,000 samples using 'scipy.sosfilt' but am receiving an error regarding my initial filter shape. I read the solutions posted here and here but am looking for something more general than just the 2-channel solution as well as something that doesn't involve looping over each channel.
Here is what I have tried:
import numpy as np
import scipy
from scipy import signal
# data
# 19 channels x 10,000 samples
data = np.random.rand(19, 10000)
# sampling rate (Hz)
sampling_rate = 500
# filters
nyq = sampling_rate / 2
# create bandpass filter
band_low = 0.01
band_lowcut = band_low / nyq
band_high = 50.0
band_highcut = band_high / nyq
band_sos = scipy.signal.butter(N = 3, Wn = [band_lowcut, band_highcut], btype = 'bandpass', fs = sampling_rate, output = 'sos')
band_z = scipy.signal.sosfilt_zi(band_sos)
# apply bandpass filter across the columns i.e. each of 19 channels bandpassed individually
bandpassed_data, band_z = scipy.signal.sosfilt(sos = band_sos, x = data, zi = band_z, axis = 1)
I receive the following error:
ValueError: Invalid zi shape. With axis=1, an input with shape (19, 10000), and an sos array with 3 sections, zi must have shape (3, 19, 2), got (3, 2).
- How should I go about either reshaping my initial filter or my data to avoid this error?
- The naive approach would be to loop through each of 19 channels, and filter each channel separately. But I am hoping I can instead filter the entire 19x10000 array without any loops.
Thanks!
CodePudding user response:
The reshaping to (3, 19, 2) can be done like this, assuming you want the same for all 19 channels:
band_z = np.repeat(np.expand_dims(band_z, axis=1), 19, axis=1)
I tried it in the latest scipy version and this worked.
Cheers