scientific-skills/neurokit2/references/signal_processing.md
NeuroKit2 provides comprehensive signal processing utilities applicable to any time series data. These functions support filtering, transformation, peak detection, decomposition, and analysis operations that work across all signal types.
Apply frequency-domain filtering to remove noise or isolate frequency bands.
filtered = nk.signal_filter(signal, sampling_rate=1000, lowcut=None, highcut=None,
method='butterworth', order=5)
Filter types (via lowcut/highcut combinations):
Lowpass (highcut only):
lowpass = nk.signal_filter(signal, sampling_rate=1000, highcut=50)
Highpass (lowcut only):
highpass = nk.signal_filter(signal, sampling_rate=1000, lowcut=0.5)
Bandpass (both lowcut and highcut):
bandpass = nk.signal_filter(signal, sampling_rate=1000, lowcut=0.5, highcut=50)
Bandstop/Notch (powerline removal):
notch = nk.signal_filter(signal, sampling_rate=1000, method='powerline', powerline=50)
Methods:
'butterworth' (default): Smooth frequency response, flat passband'bessel': Linear phase, minimal ringing'chebyshev1': Steeper rolloff, ripple in passband'chebyshev2': Steeper rolloff, ripple in stopband'elliptic': Steepest rolloff, ripple in both bands'powerline': Notch filter for 50/60 HzOrder parameter:
Remove invalid values (NaN, inf) and optionally interpolate.
clean_signal = nk.signal_sanitize(signal, interpolate=True)
Use cases:
Change sampling rate of signal (upsample or downsample).
resampled = nk.signal_resample(signal, sampling_rate=1000, desired_sampling_rate=500,
method='interpolation')
Methods:
'interpolation': Cubic spline interpolation'FFT': Frequency-domain resampling'poly': Polyphase filtering (best for downsampling)Use cases:
Interpolate missing or invalid data points.
filled = nk.signal_fillmissing(signal, method='linear')
Methods:
'linear': Linear interpolation'nearest': Nearest neighbor'pad': Forward/backward fill'cubic': Cubic spline'polynomial': Polynomial fittingRemove slow trends from signal.
detrended = nk.signal_detrend(signal, method='polynomial', order=1)
Methods:
'polynomial': Fit and subtract polynomial (order 1 = linear)'loess': Locally weighted regression'tarvainen2002': Smoothness priors detrendingUse cases:
Decompose signal into constituent components.
components = nk.signal_decompose(signal, sampling_rate=1000, method='emd')
Methods:
Empirical Mode Decomposition (EMD):
components = nk.signal_decompose(signal, sampling_rate=1000, method='emd')
Singular Spectrum Analysis (SSA):
components = nk.signal_decompose(signal, method='ssa')
Wavelet decomposition:
Returns:
Use cases:
Reconstruct signal from decomposed components.
reconstructed = nk.signal_recompose(components, indices=[1, 2, 3])
Use case:
Convert continuous signal to binary (0/1) based on threshold.
binary = nk.signal_binarize(signal, method='threshold', threshold=0.5)
Methods:
'threshold': Simple threshold'median': Median-based'mean': Mean-based'quantile': Percentile-basedUse case:
Add controlled noise or artifacts for testing.
distorted = nk.signal_distort(signal, sampling_rate=1000, noise_amplitude=0.1,
noise_frequency=50, artifacts_amplitude=0.5)
Parameters:
noise_amplitude: Gaussian noise levelnoise_frequency: Sinusoidal interference (e.g., powerline)artifacts_amplitude: Random spike artifactsartifacts_number: Number of artifacts to addUse cases:
Interpolate signal at new time points or fill gaps.
interpolated = nk.signal_interpolate(x_values, y_values, x_new=None, method='quadratic')
Methods:
'linear', 'quadratic', 'cubic': Polynomial interpolation'nearest': Nearest neighbor'monotone_cubic': Preserves monotonicityUse case:
Combine multiple signals with different sampling rates.
merged = nk.signal_merge(signal1, signal2, time1=None, time2=None, sampling_rate=None)
Use case:
Identify periods of constant signal (artifacts or sensor failure).
flatline_mask = nk.signal_flatline(signal, duration=5.0, sampling_rate=1000)
Returns:
Add various types of noise to signal.
noisy = nk.signal_noise(signal, sampling_rate=1000, noise_type='gaussian',
amplitude=0.1)
Noise types:
'gaussian': White noise'pink': 1/f noise (common in physiological signals)'brown': Brownian (random walk)'powerline': Sinusoidal interference (50/60 Hz)Generate surrogate signals preserving certain properties.
surrogate = nk.signal_surrogate(signal, method='IAAFT')
Methods:
'IAAFT': Iterated Amplitude Adjusted Fourier Transform
'random_shuffle': Random permutation (null hypothesis testing)Use case:
Detect local maxima (peaks) in signal.
peaks_dict = nk.signal_findpeaks(signal, height_min=None, height_max=None,
relative_height_min=None, relative_height_max=None)
Key parameters:
height_min/max: Absolute amplitude thresholdsrelative_height_min/max: Relative to signal range (0-1)threshold: Minimum prominencedistance: Minimum samples between peaksReturns:
'Peaks': Peak indices'Height': Peak amplitudes'Distance': Inter-peak intervalsUse cases:
Correct detected peaks for artifacts and anomalies.
corrected = nk.signal_fixpeaks(peaks, sampling_rate=1000, iterative=True,
method='Kubios', interval_min=None, interval_max=None)
Methods:
'Kubios': Kubios HRV software method (default)'Malik1996': Task Force Standards (1996)'Kamath1993': Kamath's approachCorrections:
Use case:
Compute instantaneous rate from event occurrences (peaks).
rate = nk.signal_rate(peaks, sampling_rate=1000, desired_length=None)
Method:
Use case:
Find dominant period/frequency in signal.
period = nk.signal_period(signal, sampling_rate=1000, method='autocorrelation',
show=False)
Methods:
'autocorrelation': Peak in autocorrelation function'powerspectraldensity': Peak in frequency spectrumReturns:
Use case:
Compute instantaneous phase of signal.
phase = nk.signal_phase(signal, method='hilbert')
Methods:
'hilbert': Hilbert transform (analytic signal)'wavelet': Wavelet-based phaseReturns:
Use cases:
Compute Power Spectral Density.
psd, freqs = nk.signal_psd(signal, sampling_rate=1000, method='welch',
max_frequency=None, show=False)
Methods:
'welch': Welch's periodogram (windowed FFT, default)'multitapers': Multitaper method (superior spectral estimation)'lomb': Lomb-Scargle (unevenly sampled data)'burg': Autoregressive (parametric)Returns:
psd: Power at each frequency (units²/Hz)freqs: Frequency bins (Hz)Use case:
Compute power in specific frequency bands.
power_dict = nk.signal_power(signal, sampling_rate=1000, frequency_bands={
'VLF': (0.003, 0.04),
'LF': (0.04, 0.15),
'HF': (0.15, 0.4)
}, method='welch')
Returns:
Use case:
Compute autocorrelation function.
autocorr = nk.signal_autocor(signal, lag=1000, show=False)
Interpretation:
Use cases:
Count zero crossings (sign changes).
n_crossings = nk.signal_zerocrossings(signal)
Interpretation:
Use case:
Detect abrupt changes in signal properties (mean, variance).
changepoints = nk.signal_changepoints(signal, penalty=10, method='pelt', show=False)
Methods:
'pelt': Pruned Exact Linear Time (fast, exact)'binseg': Binary segmentation (faster, approximate)Parameters:
penalty: Controls sensitivity (higher = fewer changepoints)Returns:
Use cases:
Assess synchronization between two signals.
sync = nk.signal_synchrony(signal1, signal2, method='correlation')
Methods:
'correlation': Pearson correlation'coherence': Frequency-domain coherence'mutual_information': Information-theoretic measure'phase': Phase locking valueUse cases:
Apply smoothing to reduce noise.
smoothed = nk.signal_smooth(signal, method='convolution', kernel='boxzen', size=10)
Methods:
'convolution': Apply kernel (boxcar, Gaussian, etc.)'median': Median filter (robust to outliers)'savgol': Savitzky-Golay filter (preserves peaks)'loess': Locally weighted regressionKernel types (for convolution):
'boxcar': Simple moving average'gaussian': Gaussian-weighted average'hann', 'hamming', 'blackman': Windowing functionsUse cases:
Time-frequency representation (spectrogram).
tf, time, freq = nk.signal_timefrequency(signal, sampling_rate=1000, method='stft',
max_frequency=50, show=False)
Methods:
'stft': Short-Time Fourier Transform'cwt': Continuous Wavelet TransformReturns:
tf: Time-frequency matrix (power at each time-frequency point)time: Time binsfreq: Frequency binsUse cases:
Generate various synthetic signals for testing.
signal = nk.signal_simulate(duration=10, sampling_rate=1000, frequency=[5, 10],
amplitude=[1.0, 0.5], noise=0.1)
Signal types:
Use cases:
Visualize signal and optional markers.
nk.signal_plot(signal, sampling_rate=1000, peaks=None, show=True)
Features:
Choosing filter parameters:
Handling edge effects:
Dealing with gaps:
signal_fillmissing() with interpolationCombining operations:
# Typical preprocessing pipeline
signal = nk.signal_sanitize(raw_signal) # Remove invalid values
signal = nk.signal_filter(signal, sampling_rate=1000, lowcut=0.5, highcut=40) # Bandpass
signal = nk.signal_detrend(signal, method='polynomial', order=1) # Remove linear trend
Performance considerations: