P

Pro Neurokit2 Workspace

Production-ready skill that handles comprehensive, biosignal, processing, toolkit. Includes structured workflows, validation checks, and reusable patterns for scientific.

SkillClipticsscientificv1.0.0MIT
0 views0 copies

Pro NeuroKit2 Workspace

Process and analyze physiological signals using NeuroKit2, a Python toolkit for neurophysiological signal processing. This skill covers ECG, EEG, EMG, EDA, and respiration signal analysis with automated preprocessing, feature extraction, and event-related analysis.

When to Use This Skill

Choose Pro NeuroKit2 Workspace when you need to:

  • Process ECG signals for heart rate variability (HRV) analysis
  • Analyze EDA (electrodermal activity) for stress or emotion research
  • Extract features from EMG signals for motor control studies
  • Perform event-related analysis across multiple physiological modalities

Consider alternatives when:

  • You need real-time physiological signal streaming (use BrainFlow or LSL)
  • You need advanced EEG source localization (use MNE-Python)
  • You need clinical-grade ECG interpretation (use specialized clinical tools)

Quick Start

pip install neurokit2 matplotlib pandas
import neurokit2 as nk import matplotlib.pyplot as plt # Simulate and analyze an ECG signal ecg = nk.ecg_simulate(duration=30, sampling_rate=500, heart_rate=75) signals, info = nk.ecg_process(ecg, sampling_rate=500) # Visualize processed ECG nk.ecg_plot(signals, info) plt.tight_layout() plt.savefig("ecg_analysis.png", dpi=150) # Extract HRV features hrv = nk.hrv(signals, sampling_rate=500) print(f"Mean HR: {hrv['HRV_MeanNN'].values[0]:.1f} ms") print(f"RMSSD: {hrv['HRV_RMSSD'].values[0]:.1f} ms") print(f"SDNN: {hrv['HRV_SDNN'].values[0]:.1f} ms")

Core Concepts

Supported Signal Types

SignalFunctionsKey Outputs
ECGecg_process(), ecg_peaks()R-peaks, HRV, cardiac cycles
EDAeda_process(), eda_phasic()SCR peaks, tonic/phasic components
EMGemg_process(), emg_amplitude()Activation onsets, amplitude envelope
RSPrsp_process(), rsp_rate()Breathing rate, inhalation/exhalation
EEGeeg_power(), eeg_badchannels()Band power, artifact detection
PPGppg_process(), ppg_peaks()Pulse rate, pulse wave features

Multi-Modal Physiological Analysis

import neurokit2 as nk import pandas as pd def multimodal_analysis(ecg_signal, eda_signal, rsp_signal, sampling_rate=500): """Process multiple physiological signals simultaneously.""" # Process each modality ecg_processed, ecg_info = nk.ecg_process( ecg_signal, sampling_rate=sampling_rate ) eda_processed, eda_info = nk.eda_process( eda_signal, sampling_rate=sampling_rate ) rsp_processed, rsp_info = nk.rsp_process( rsp_signal, sampling_rate=sampling_rate ) # Combine into single DataFrame combined = pd.concat([ ecg_processed, eda_processed, rsp_processed ], axis=1) # Extract features from each modality features = {} # HRV features hrv = nk.hrv(ecg_processed, sampling_rate=sampling_rate) features["mean_hr"] = hrv["HRV_MeanNN"].values[0] features["rmssd"] = hrv["HRV_RMSSD"].values[0] # EDA features scr_peaks = eda_info.get("SCR_Peaks", []) features["scr_count"] = len(scr_peaks) features["mean_scl"] = eda_processed["EDA_Tonic"].mean() # Respiration features features["mean_rsp_rate"] = rsp_processed["RSP_Rate"].mean() features["rsp_amplitude"] = rsp_processed["RSP_Amplitude"].mean() return combined, features # Simulate signals for demo ecg = nk.ecg_simulate(duration=60, sampling_rate=500) eda = nk.eda_simulate(duration=60, sampling_rate=500) rsp = nk.rsp_simulate(duration=60, sampling_rate=500) combined, features = multimodal_analysis(ecg, eda, rsp) for key, val in features.items(): print(f"{key}: {val:.2f}")
import neurokit2 as nk import numpy as np def event_related_physiology(ecg_signal, events, sampling_rate=500, epoch_start=-1, epoch_end=5): """Analyze physiological responses to events.""" signals, info = nk.ecg_process(ecg_signal, sampling_rate=sampling_rate) # Create epochs around events epochs = nk.epochs_create( signals, events=events, sampling_rate=sampling_rate, epochs_start=epoch_start, epochs_end=epoch_end ) # Analyze each epoch results = [] for epoch_id, epoch_data in epochs.items(): epoch_features = { "epoch": epoch_id, "mean_hr": epoch_data["ECG_Rate"].mean(), "max_hr": epoch_data["ECG_Rate"].max(), "hr_change": (epoch_data["ECG_Rate"].iloc[-1] - epoch_data["ECG_Rate"].iloc[0]) } results.append(epoch_features) return pd.DataFrame(results) # Simulate with events at 10s, 25s, 40s ecg = nk.ecg_simulate(duration=60, sampling_rate=500, heart_rate=70) events = [5000, 12500, 20000] # Event indices era = event_related_physiology(ecg, events) print(era)

Configuration

ParameterDescriptionDefault
sampling_rateSignal sampling frequency (Hz)Required
methodPeak detection algorithm"neurokit"
clean_methodSignal cleaning approach"default"
hrv_methodsHRV domains to compute["time", "frequency"]
epoch_startPre-event window (seconds)-0.5
epoch_endPost-event window (seconds)1.0

Best Practices

  1. Always specify the correct sampling rate โ€” Every NeuroKit2 function requires the sampling rate parameter. Using the wrong rate produces incorrect peak detection, heart rate calculations, and frequency analysis. Verify your recording device's actual sampling rate rather than assuming the nominal rate.

  2. Inspect signals visually before automated processing โ€” Plot raw signals with nk.signal_plot(signal) to check for movement artifacts, lead disconnections, or saturation before running automated processing. Automated algorithms produce plausible-looking but incorrect results on corrupted data.

  3. Use appropriate epoch windows for your paradigm โ€” ECG responses to events develop over 2-5 seconds; EDA responses peak at 1-4 seconds post-stimulus. Set epoch windows based on the expected physiological response time for your signal type, not arbitrary values.

  4. Report HRV analysis parameters โ€” When publishing HRV results, specify the recording duration, peak detection method, artifact correction approach, and which HRV metrics you computed. The Task Force of ESC/NASPE recommends minimum 5-minute recordings for frequency-domain HRV analysis.

  5. Handle missing data and artifacts explicitly โ€” Mark artifact segments as NaN rather than interpolating blindly. NeuroKit2's ecg_clean() handles common artifacts, but severe motion artifacts require manual inspection. Report the percentage of data rejected due to artifacts.

Common Issues

R-peak detection fails on noisy ECG โ€” Low signal-to-noise ratio causes missed or false peaks. Try different detection methods: nk.ecg_peaks(ecg, method="pantompkins1985") or method="hamilton2002". Pre-filter with nk.ecg_clean(ecg, method="biosppy") which uses a more aggressive bandpass filter for noisy recordings.

EDA decomposition produces flat tonic component โ€” This happens when the EDA signal range is too small or the signal is already mean-centered. Check that your EDA signal is in microSiemens (typical range 1-20 ยตS). If the signal was recorded in different units, scale it appropriately before processing.

Sampling rate mismatch causes incorrect HRV values โ€” If you specify 1000 Hz but the data was recorded at 500 Hz, all timing-based HRV metrics (RMSSD, SDNN) will be exactly doubled. Verify sampling rate by checking the time vector or counting samples per second in your raw data file.

Community

Reviews

Write a review

No reviews yet. Be the first to review this template!

Similar Templates