Filtering#
The filtering module holds the functions for frequency manipulation:
The functions have similar calling signatures. For example, to filter a 1000 Hz signal between 10 and 20 Hz using a Butterworth filter:
>>> new_tsd = nap.apply_bandpass_filter(tsd, (10, 20), fs=1000, mode='butter')
Currently, the filtering module provides two methods for frequency manipulation: butter for a recursive Butterworth filter and sinc for a Windowed-sinc convolution. This notebook provides a comparison of the two methods.
Basics#
We start by generating a signal with multiple frequencies (2, 10 and 50 Hz).
fs = 1000 # sampling frequency
t = np.linspace(0, 2, fs * 2)
f2 = np.cos(t*2*np.pi*2)
f10 = np.cos(t*2*np.pi*10)
f50 = np.cos(t*2*np.pi*50)
sig = nap.Tsd(t=t,d=f2+f10+f50 + np.random.normal(0, 0.5, len(t)))
Text(0.5, 0, 'Time (s)')
We can compute the Fourier transform of sig to verify that all the frequencies are there.
psd = nap.compute_power_spectral_density(sig, fs)
(0.0, 100.0)
Let’s say we would like to see only the 10 Hz component.
We can use the function apply_bandpass_filter with mode butter for Butterworth.
sig_butter = nap.apply_bandpass_filter(sig, (8, 12), fs, mode='butter')
Let’s compare it to the sinc mode for Windowed-sinc.
sig_sinc = nap.apply_bandpass_filter(sig, (8, 12), fs, mode='sinc', transition_bandwidth=0.003)
(0.0, 1.0)
This gives similar results except at the edges.
Another use of filtering is to remove some frequencies. Here we can try to remove the 50 Hz component in the signal.
sig_butter = nap.apply_bandstop_filter(sig, cutoff=(45, 55), fs=fs, mode='butter')
sig_sinc = nap.apply_bandstop_filter(sig, cutoff=(45, 55), fs=fs, mode='sinc', transition_bandwidth=0.004)
(0.0, 1.0)
Let’s see what frequencies remain;
psd_butter = nap.compute_power_spectral_density(sig_butter, fs)
psd_sinc = nap.compute_power_spectral_density(sig_sinc, fs)
(0.0, 70.0)
Inspecting frequency responses of a filter#
We can inspect the frequency response of a filter by plotting its FFT.
To do this, we can use the get_filter_frequency_response function, which returns a pandas Series with the frequencies as the index and the amplitude as values.
Let’s extract the frequency response of a Butterworth filter and a sinc low-pass filter.
# compute the frequency response of the filters
psd_butter = nap.get_filter_frequency_response(
200, fs,"lowpass", "butter", order=8
)
psd_sinc = nap.get_filter_frequency_response(
200, fs,"lowpass", "sinc", transition_bandwidth=0.1
)
Transition band butterworth filter: (164Hz, 290Hz)
Transition band sinc filter: (146Hz, 268Hz)
The frequency band with response close to one will be preserved by the filtering (pass band), the band with response close to zero will be discarded (stop band), and the band in between will be partially attenuated (transition band).
Note
Here, we define the transition band as the range where the amplitude attenuation is between 99% and 1%.
The transition_bandwidth parameter of the sinc filter is approximately the width of the transition band normalized by the sampling frequency. In the example above, if you divide the transition band width of 122Hz by the sampling frequency of 1000Hz, you get 0.122, which is close to the 0.1 value set.
You can modulate the width of the transition band by setting the order parameter of the Butterworth filter
or the transition_bandwidth parameter of the sinc filter.
First, let’s get the frequency response for a Butterworth low pass filter with different order:
butter_freq = {
order: nap.get_filter_frequency_response(250, fs, "lowpass", "butter", order=order)
for order in [2, 4, 6]}
… and then the frequency response for the Windowed-sinc equivalent with different transition bandwidth.
sinc_freq = {
tb: nap.get_filter_frequency_response(250, fs,"lowpass", "sinc", transition_bandwidth=tb)
for tb in [0.002, 0.02, 0.2]}
Let’s plot the frequency response of both.
Warning
In some cases, the transition bandwidth that is too high generates a kernel that is too short. The amplitude of the original signal will then be lower than expected. In this case, the solution is to decrease the transition bandwidth when using the windowed-sinc mode. Note that this increases the length of the kernel significantly. Let see it with the band pass filter.
sinc_freq = {
tb:nap.get_filter_frequency_response((100, 200), fs, "bandpass", "sinc", transition_bandwidth=tb)
for tb in [0.004, 0.2]}
Performances#
Let’s compare the performance of each when varying the number of time points and the number of dimensions.
Text(0.5, 1.0, 'Low pass filtering benchmark')
Detecting Oscillatory Events#
The filtering module also provides a method detect_oscillatory_events to automatically detect intervals containing oscillatory events (such as ripples or spindles) in a signal.
To demonstrate, let’s create a synthetic signal where a fast oscillation (e.g., 40 Hz) occurs in a noisy signal:
# Parameters
fs = 1000 # Sampling frequency (Hz)
duration = 3 # seconds
t = np.linspace(0, duration, int(fs * duration))
# 40 Hz oscillation
osc = np.sin(2 * np.pi * 40 * t)
signal = np.zeros_like(t) + 0.2 * np.random.randn(len(t))
mask = (t > 1) & (t < 1.5)
signal[mask] += osc[mask]
# Create Tsd object
ts = nap.Tsd(t=t, d=signal)
Now, let’s use detect_oscillatory_events to find the oscillation intervals. The function will return the detected intervals as an IntervalSet along with metadata containing peak times.
# Define detection parameters
freq_band = (35, 45) # Bandpass filter for 40 Hz
thres_band = (1, 10) # Thresholds for normalized squared signal
min_dur = 0.03 # Minimum event duration (s)
max_dur = 1 # Maximum event duration (s)
min_inter = 0.02 # Minimum interval between events (s)
epoch = nap.IntervalSet(start=0, end=duration)
# Detect oscillatory events
osc_ep = nap.filtering.detect_oscillatory_events(
ts, epoch, freq_band, thres_band, (min_dur, max_dur), min_inter
)
print("Detected intervals:\n", osc_ep)
Detected intervals:
index start end power amplitude peak_time
0 1.02334 1.47849 -3.03 1.09 1.39
shape: (1, 2), time unit: sec.
Let’s visualize the detected intervals and peaks on the original signal: